repo_name
stringlengths 6
130
| hexsha
list | file_path
list | code
list | apis
list |
---|---|---|---|---|
rajk97/Adversial-Attacks-on-densely-fused-point-clouds-for-6D-Pose-Estimation | [
"e296e70c3a1286b7491995215369d9f39cfcba17"
]
| [
"tools/sampling.py"
]
| [
"import numpy as np\nfrom numba import jit\nfrom projection import cross, norm\n\n@jit(nopython = True)\ndef _init_seed():\n np.random.seed(1234)\n\n_init_seed()\n\n@jit(nopython = True)\ndef binary_search(a, b):\n lo = 0\n hi = len(a) - 1\n\n while lo < hi:\n m = (lo + hi - 1) // 2\n\n if a[m] < b:\n lo = m + 1\n else:\n hi = m\n\n if a[hi] == b:\n return min(hi + 1, len(a) - 1)\n else:\n return hi\n\n@jit(nopython = True)\ndef sample_points(triangles, num_points):\n prefix_areas = []\n\n for i in range(len(triangles)):\n area = np.linalg.norm(cross(triangles[i][2] - triangles[i][0], triangles[i][1] - triangles[i][0])) / 2.0\n\n if i == 0:\n prefix_areas.append(area)\n else:\n prefix_areas.append(prefix_areas[i - 1] + area)\n\n prefix_areas = np.array(prefix_areas)\n total_area = prefix_areas[-1]\n points = np.empty((num_points, 3))\n\n for i in range(num_points):\n rand = np.random.uniform(0.0, total_area)\n idx = binary_search(prefix_areas, rand)\n\n a = triangles[idx][0]\n b = triangles[idx][1]\n c = triangles[idx][2]\n\n r1 = np.random.random()\n r2 = np.random.random()\n\n if r1 + r2 >= 1.0:\n r1 = 1.0 - r1\n r2 = 1.0 - r2\n\n point = a + r1 * (c - a) + r2 * (b - a)\n points[i] = point\n\n return points\n\n@jit(nopython = True)\ndef farthest_point(sampled_points, initial_points, num_points):\n curr_points = np.empty((num_points, 3))\n dists = np.full(len(sampled_points), np.inf)\n\n if initial_points is None:\n dists = np.minimum(dists, norm(sampled_points - sampled_points[0].reshape((1, -1))))\n curr_points[0] = sampled_points[0]\n start_idx = 1\n else:\n for i in range(len(initial_points)):\n dists = np.minimum(dists, norm(sampled_points - initial_points[i].reshape((1, -1))))\n\n start_idx = 0\n\n for i in range(start_idx, num_points):\n curr_points[i] = sampled_points[np.argmax(dists)]\n dists = np.minimum(dists, norm(sampled_points - curr_points[i].reshape((1, -1))))\n\n return curr_points\n\n@jit(nopython = True)\ndef farthest_point_idx(sampled_points, initial_points, num_points):\n curr_points = np.empty(num_points, dtype = np.int64)\n dists = np.full(len(sampled_points), np.inf)\n\n if initial_points is None:\n dists = np.minimum(dists, norm(sampled_points - sampled_points[0].reshape((1, -1))))\n curr_points[0] = 0\n start_idx = 1\n else:\n for i in range(len(initial_points)):\n dists = np.minimum(dists, norm(sampled_points - initial_points[i].reshape((1, -1))))\n\n start_idx = 0\n\n for i in range(start_idx, num_points):\n curr_points[i] = np.argmax(dists)\n dists = np.minimum(dists, norm(sampled_points - sampled_points[curr_points[i]].reshape((1, -1))))\n\n return curr_points\n\n@jit(nopython = True)\ndef farthest_point_sampling(triangles, initial_points, num_points, kappa):\n sampled_points = sample_points(triangles, kappa * num_points)\n return farthest_point(sampled_points, initial_points, num_points)\n\n@jit(nopython = True)\ndef gaussian_rbf(norm, shape):\n return np.exp(-((shape * norm) ** 2))\n\n@jit(nopython = True)\ndef radial_basis(sampled_points, initial_points, num_points, shape):\n probs = []\n total_prob = 0.0\n curr_points = np.empty((num_points, 3))\n\n for i in range(len(sampled_points)):\n prob = -np.inf\n\n for j in range(len(initial_points)):\n prob = max(prob, gaussian_rbf(np.linalg.norm(sampled_points[i] - initial_points[j]), shape))\n\n probs.append(prob)\n total_prob += prob\n\n for i in range(num_points):\n rand = np.random.uniform(0.0, total_prob)\n sum_prob = 0.0\n\n for j in range(len(sampled_points)):\n sum_prob += probs[j]\n\n if rand < sum_prob or j == len(sampled_points) - 1:\n curr_points[i] = sampled_points[j]\n total_prob -= probs[j]\n probs[j] = 0.0\n break\n\n return curr_points\n\n@jit(nopython = True)\ndef radial_basis_sampling(triangles, initial_points, num_points, kappa, num_farthest, shape):\n if num_farthest is None:\n sampled_points = sample_points(triangles, kappa * num_points)\n radial_basis_points = radial_basis(sampled_points, initial_points, kappa // 2 * num_points, shape)\n return farthest_point(radial_basis_points, None, num_points)\n else:\n sampled_points = sample_points(triangles, kappa * num_points)\n radial_basis_points = radial_basis(sampled_points, initial_points, num_points - num_farthest, shape)\n initial_points = np.concatenate((initial_points, radial_basis_points))\n return np.concatenate((farthest_point(sampled_points, initial_points, num_farthest), radial_basis_points))\n\n@jit(nopython = True)\ndef sample_on_line_segments(x, x_perturb, sigma):\n small_perturb = 0.003\n norms = norm(x_perturb - x)\n prefix = []\n\n for i in range(len(norms)):\n if i == 0:\n prefix.append(norms[i])\n else:\n prefix.append(prefix[i - 1] + norms[i])\n\n total_prob = prefix[-1]\n count = np.zeros(len(norms))\n\n for i in range(sigma):\n rand = np.random.uniform(0.0, total_prob)\n idx = binary_search(prefix, rand)\n count[idx] += 1.0\n\n x_sample = np.empty((sigma, 3))\n idx = 0\n\n for i in range(len(norms)):\n for j in range(count[i]):\n x_sample[idx] = x[i] + (x_perturb[i] - x[i]) * j / count[i] + small_perturb * np.random.randn(3)\n idx += 1\n\n return x_sample\n"
]
| [
[
"numpy.random.random",
"numpy.random.seed",
"numpy.linalg.norm",
"numpy.concatenate",
"numpy.argmax",
"numpy.random.randn",
"numpy.random.uniform",
"numpy.array",
"numpy.exp",
"numpy.empty"
]
]
|
TurnphyGithub/PhotonicComposite | [
"ec6abdd8b5eb2181236a466b40a03074a7c9aca4"
]
| [
"MultilayerSimulationFunc.py"
]
| [
"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n@author: Turnphy\r\n\"\"\"\r\n\r\nfrom tkinter import filedialog\r\nfrom tkinter import *\r\nfrom PIL import ImageTk\r\nimport numpy as np\r\nfrom matplotlib import pyplot as plt\r\nfrom tkinter import *\r\nfrom TransferMatrixEngine import (coh_tmm, position_resolved, find_in_structure_with_inf)\r\nfrom numpy import pi, linspace, inf, array\r\nfrom scipy.interpolate import interp1d\r\nimport matplotlib.pyplot as plt\r\nimport PIL\r\n\r\n# Define the buttons\r\ndef saveStruc():\r\n global index1,thickness1,index2,thickness2,repeats\r\n index1,thickness1=float(n1.get() or 1),float(d1.get() or 0)\r\n index2,thickness2,repeats=float(n2.get() or 1),float(d2.get() or 0), int(period1.get() or 0) \r\n global index12,thickness12,index22,thickness22,repeats2\r\n index12,thickness12=float(n12.get() or 1),float(d12.get() or 0)\r\n index22,thickness22,repeats2=float(n22.get() or 1),float(d22.get() or 0), int(period12.get() or 0)\r\n global index11,thickness11,index21,thickness21,repeats1\r\n index11,thickness11=float(n11.get() or 1),float(d11.get() or 0)\r\n index21,thickness21,repeats1=float(n21.get() or 1),float(d21.get() or 0), int(period11.get() or 0)\r\n\r\n print(\"Saved successfully!\" )\r\n return\r\n\r\ndef AngularRef(wavelength0, thetal1, thetal2):\r\n \"\"\"\r\n This code use TMM\r\n \"\"\"\r\n global index1,thickness1,index2,thickness2,repeats\r\n global index12,thickness12,index22,thickness22,repeats2\r\n global index11,thickness11,index21,thickness21,repeats1\r\n d_list = [inf, 300]+[thickness1, thickness2]*repeats+[thickness11,\\\r\nthickness21]*repeats1+[thickness12, thickness22]*repeats2+[inf]\r\n \r\n n_list = [2.2, 1]+[index1+0.01j, index2+0.001j]*repeats+ [index11, \\\r\nindex21]*repeats1+[index12, index22]*repeats2+ [3.46] \r\n \r\n \r\n # list of theta to plot in deg\r\n thetas=linspace(thetal1, thetal2, num=1000)\r\n # list of wavenumbers to plot in nm^-1\r\n # ks = linspace(0.0001, .01, num=400)\r\n # initialize lists of y-values to plot\r\n Rangle = []\r\n for theta in thetas:\r\n\t\t# For normal incidence, s and p polarizations are identical.\r\n\t\t# I arbitrarily decided to use 's'. \r\n Rangle.append(coh_tmm('s', n_list, d_list, theta*pi/180, wavelength0)['R'])\r\n # R45.append(unpolarized_RT(n_list, d_list, 45*degree, 1/k)['R'])\r\n # kcm = ks * 1e7 #ks in cm^-1 rather than nm^-1\r\n plt.figure()\r\n plt.plot(thetas, Rangle, 'blue')\r\n plt.xlabel('Incident Angle (degree)')\r\n plt.ylabel('Reflectance')\r\n # plt.title('Reflection of unpolarized light at 0$^\\circ$ incidence (blue), '\r\n # '45$^\\circ$ (purple)')\r\n plt.show()\r\n \r\ndef Spectral(angle0, wavelength1, wavelength2):\r\n \"\"\"\r\n This code use TMM\r\n \"\"\"\r\n global index1,thickness1,index2,thickness2,repeats\r\n global index12,thickness12,index22,thickness22,repeats2\r\n global index11,thickness11,index21,thickness21,repeats1\r\n d_list = [inf, 300]+[thickness1, thickness2]*repeats+[thickness11,\\\r\nthickness21]*repeats1+[thickness12, thickness22]*repeats2+[inf]\r\n \r\n n_list = [2.2, 1]+[index1+0.01j, index2+0.001j]*repeats+ [index11, \\\r\nindex21]*repeats1+[index12, index22]*repeats2+ [3.46] \r\n \r\n \r\n # list of theta to plot in deg\r\n wavelengths=linspace(wavelength1, wavelength2, num=1000)\r\n # thetas=linspace(thetal1, thetal2, num=1000)\r\n # list of wavenumbers to plot in nm^-1\r\n # ks = linspace(0.0001, .01, num=400)\r\n # initialize lists of y-values to plot\r\n Rw = []\r\n for wavelength in wavelengths:\r\n\t\t# For normal incidence, s and p polarizations are identical.\r\n\t\t# I arbitrarily decided to use 's'.\r\n Rw.append(coh_tmm('s', n_list, d_list, angle0, wavelength)['R'])\r\n # R45.append(unpolarized_RT(n_list, d_list, 45*degree, 1/k)['R'])\r\n # kcm = ks * 1e7 #ks in cm^-1 rather than nm^-1\r\n plt.figure()\r\n plt.plot(wavelengths, Rw, 'red')\r\n plt.xlabel('Wavelength (nm)')\r\n plt.ylabel('Reflectance')\r\n # plt.title('Reflection of unpolarized light at 0$^\\circ$ incidence (blue), '\r\n # '45$^\\circ$ (purple)')\r\n plt.show()\r\n \r\ndef CalRef():\r\n saveStruc()\r\n global clicked, wavelength0, thetal1, thetal2\r\n if clicked.get()=='Angle (deg)':\r\n print('Calculating the angular reflectance...')\r\n thetal1, thetal2=float(lim1.get()),float(lim2.get())\r\n wavelength0=float(lim0.get())\r\n AngularRef(wavelength0, thetal1, thetal2)\r\n else:\r\n wavelength1, wavelength2=float(lim1.get()),float(lim2.get())\r\n angle0=float(lim0.get())\r\n Spectral(angle0, wavelength1, wavelength2)\r\n print('Calculating the spectral reflectance...')\r\n return\r\n\r\n# Calculate the electric field\r\ndef E_y(angle0, wavelength0, depth=600):\r\n saveStruc()\r\n \"\"\"\r\n Here is an example where we plot absorption and Poynting vector\r\n as a function of depth.\r\n \"\"\"\r\n print('Calculating the field profile...')\r\n global index1,thickness1,index2,thickness2,repeats\r\n global index12,thickness12,index22,thickness22,repeats2\r\n global index11,thickness11,index21,thickness21,repeats1\r\n d_list = [inf, 300]+[thickness1, thickness2]*repeats+[thickness11,\\\r\nthickness21]*repeats1+[thickness12, thickness22]*repeats2+[inf]\r\n \r\n n_list = [2.2, 1]+[index1+0.01j, index2+0.001j]*repeats+ [index11, \\\r\nindex21]*repeats1+[index12, index22]*repeats2+ [3.46] \r\n # d_list = [inf, 300, 310,1330, inf] #in nm\r\n # n_list = [2.2, 1, 2.08+0.01j, 1.41+0.001j, 3.46]\r\n depth=sum(d_list[1:-2])+depth\r\n th_0 = pi*angle0/180\r\n lam_vac =wavelength0\r\n pol = 's'\r\n coh_tmm_data = coh_tmm(pol, n_list, d_list, th_0, lam_vac)\r\n\r\n ds = linspace(-50, depth, num=1000) #position in structure\r\n poyn = []\r\n Ey = []\r\n for d in ds:\r\n layer, d_in_layer = find_in_structure_with_inf(d_list, d)\r\n data = position_resolved(layer, d_in_layer, coh_tmm_data)\r\n poyn.append(data['poyn'])\r\n Ey.append(data['Ey'])\r\n # convert data to numpy arrays for easy scaling in the plot\r\n poyn = array(poyn)\r\n Ey = array(Ey)\r\n plt.figure(figsize=(4, 2.5), dpi=200, facecolor='w', edgecolor='k')\r\n plt.plot(ds, abs(Ey)**2, 'purple')\r\n zintface=d_list[1]\r\n plt.plot([zintface,zintface],[0, max(abs(Ey)**2)], 'k--')\r\n plt.xlabel('depth (nm)',fontsize=14)\r\n plt.ylabel('E-squared (a.u.)',fontsize=14)\r\n plt.xticks(fontsize= 12) \r\n plt.yticks(fontsize= 12)\r\n plt.tight_layout()\r\n # plt.title('E-squared')\r\n plt.show()\r\n \r\ndef ShowField():\r\n global theta2f,lambda2f, z2f\r\n theta2f,lambda2f, z2f=float(angle2f.get()),float(wavelength2f.get()), float(depth2f.get())\r\n E_y(theta2f,lambda2f, z2f) \r\n return\r\n\r\ndef LabelDestroy(l0,l1,l2,l3, l1x, l2x, l3x):\r\n l0.destroy()\r\n l1.destroy()\r\n l2.destroy()\r\n l3.destroy() \r\n l1x.destroy()\r\n l2x.destroy()\r\n l3x.destroy()\r\n\r\ndef CalChoice(modes):\r\n global lim0, lim1, lim2\r\n global l0,l1,l2,l3, l1x, l2x, l3x\r\n if modes=='Angle (deg)':\r\n LabelDestroy(l0,l1,l2,l3, l1x, l2x, l3x) \r\n \r\n l0=Label(frame01, text=\"Setting the working wavelength and angle limits \")\r\n l0.grid(row=1, column=0, columnspan=2) \r\n l1=Label(frame01, text=\"wavelength \")\r\n l1.grid(row=2, column=0) \r\n lim0=Entry(frame01, width = 10, borderwidth=5) \r\n lim0.grid(row=2, column=1, columnspan=1, padx=5, pady=5) \r\n l1x=Label(frame01, text=\" nm\")\r\n l1x.grid(row=2, column=2)\r\n \r\n l2=Label(frame01, text=\"theta1 \")\r\n l2.grid(row=3, column=0)\r\n lim1=Entry(frame01, width = 10, borderwidth=5)\r\n lim1.grid(row=3, column=1, columnspan=1, padx=5, pady=5)\r\n l2x=Label(frame01, text=\" deg\")\r\n l2x.grid(row=3, column=2) \r\n \r\n l3=Label(frame01, text=\"theta2 \")\r\n l3.grid(row=4, column=0)\r\n lim2=Entry(frame01, width = 10, borderwidth=5)\r\n lim2.grid(row=4, column=1, columnspan=1, padx=5, pady=5)\r\n l3x=Label(frame01, text=\" deg\")\r\n l3x.grid(row=4, column=2) \r\n \r\n lim0.insert(0, 1550)\r\n lim1.insert(0, 30)\r\n lim2.insert(0, 70)\r\n \r\n if modes==\"Wavelength (nm)\":\r\n \r\n LabelDestroy(l0,l1,l2,l3, l1x, l2x, l3x) \r\n l0=Label(frame01, text=\"Setting the working angle and wavelength limits:\")\r\n l0.grid(row=1, column=0, columnspan=2)\r\n l1=Label(frame01, text=\"angle \")\r\n l1.grid(row=2, column=0)\r\n lim0=Entry(frame01, width = 10, borderwidth=5)\r\n lim0.grid(row=2, column=1, columnspan=1, padx=5, pady=5)\r\n l1x=Label(frame01, text=\" deg\")\r\n l1x.grid(row=2, column=2)\r\n \r\n l2=Label(frame01, text=\"wavelength1 \")\r\n l2.grid(row=3, column=0)\r\n lim1=Entry(frame01, width = 10, borderwidth=5)\r\n lim1.grid(row=3, column=1, columnspan=1, padx=5, pady=5)\r\n l2x=Label(frame01, text=\" nm\")\r\n l2x.grid(row=3, column=2) \r\n \r\n l3=Label(frame01, text=\"wavelength2 \")\r\n l3.grid(row=4, column=0)\r\n lim2=Entry(frame01, width = 10, borderwidth=5)\r\n lim2.grid(row=4, column=1, columnspan=1, padx=5, pady=5)\r\n l3x=Label(frame01, text=\" nm\")\r\n l3x.grid(row=4, column=2) \r\n \r\n lim0.insert(0, 0) \r\n lim1.insert(0, 1250)\r\n lim2.insert(0, 1750) \r\n \r\n \r\n\r\ndef CleTable():\r\n global n1, n2, d1, d2, period1 \r\n global n11, n21, d11, d21, period11\r\n global n12, n22, d12, d22, period12\r\n n1.delete(0,END)\r\n n2.delete(0,END)\r\n d1.delete(0,END)\r\n d2.delete(0,END)\r\n period1.delete(0,END)\r\n n11.delete(0,END)\r\n n21.delete(0,END)\r\n d11.delete(0,END)\r\n d21.delete(0,END)\r\n period11.delete(0,END)\r\n n12.delete(0,END)\r\n n22.delete(0,END)\r\n d12.delete(0,END)\r\n d22.delete(0,END)\r\n period12.delete(0,END) \r\n return\r\n\r\n\r\ndef setND(DefaultValues):\r\n global n1, n2, d1, d2, period1 \r\n global n11, n21, d11, d21, period11\r\n global n12, n22, d12, d22, period12\r\n #***************************************\r\n global index1,thickness1,index2,thickness2,repeats\r\n index1,thickness1,index2,thickness2,repeats=DefaultValues[0]\r\n global index11,thickness11,index21,thickness21,repeats1\r\n index11,thickness11,index21,thickness21,repeats1=DefaultValues[1]\r\n global index12,thickness12,index22,thickness22,repeats2\r\n index12,thickness12,index22,thickness22,repeats2=DefaultValues[2]\r\n n1.insert(0,index1)\r\n d1.insert(0,thickness1)\r\n n2.insert(0,index2)\r\n d2.insert(0,thickness2)\r\n period1.insert(0,repeats)\r\n n11.insert(0,index11)\r\n d11.insert(0,thickness11)\r\n n21.insert(0,index21)\r\n d21.insert(0,thickness21)\r\n period11.insert(0,repeats1)\r\n n12.insert(0,index12)\r\n d12.insert(0,thickness12)\r\n n22.insert(0,index22)\r\n d22.insert(0,thickness22)\r\n period12.insert(0,repeats2)\r\n\r\n\r\n# def SetClear():\r\n# CleTable()\r\n# DefaultValues=[[1, 0, 1, 0, 1],[1, 0, 1, 0, 0],[1, 0, 1, 0, 0]]\r\n# setND(DefaultValues) \r\n \r\ndef SetWaveguide():\r\n # Examples 1\r\n CleTable()\r\n DefaultValues=[[2.08, 310, 1.41, 1330, 1],[1, 0, 1, 0, 0],[1, 0, 1, 0, 0]]\r\n setND(DefaultValues) \r\n \r\ndef SetBraggStack():\r\n global lim1, lim2, angle2f, wavelength2f, theta2f, lambda2f\r\n # Examples 2\r\n CleTable()\r\n DefaultValues=[[1.8, 90.278, 1.2, 135.416, 15],[1, 0, 1, 0, 0],[1, 0, 1, 0, 0]]\r\n setND(DefaultValues)\r\n lim1.delete(0, END)\r\n lim2.delete(0, END)\r\n angle2f.delete(0, END)\r\n wavelength2f.delete(0, END)\r\n lim1.insert(0, 400)\r\n lim2.insert(0, 950)\r\n angle2f.insert(0, 0)\r\n wavelength2f.insert(0, 650)\r\n lambda2f=650\r\n theta2f=0\r\n\r\ndef SetMicrocavity():\r\n # Examples 3\r\n global lim1, lim2, angle2f, wavelength2f, theta2f, lambda2f\r\n CleTable()\r\n DefaultValues=[[1.8, 90.278, 1.2, 135.416, 7],[1.8, 90.278, 1.8, 90.278, 1],[ 1.2, 135.416, 1.8, 90.278, 7]]\r\n setND(DefaultValues)\r\n lim1.delete(0, END)\r\n lim2.delete(0, END)\r\n angle2f.delete(0, END)\r\n wavelength2f.delete(0, END)\r\n lim1.insert(0, 400)\r\n lim2.insert(0, 950)\r\n angle2f.insert(0, 0)\r\n wavelength2f.insert(0, 650)\r\n lambda2f=650\r\n theta2f=0\r\ndef MS_create():\r\n global MS_, n1, n2, d1, d2, period1 \r\n MS_= Toplevel()\r\n MS_.title('Multilayer Simulations')\r\n \r\n global frame00, frame01, frame02, frameHD\r\n# Layout\r\n # frameHD=LabelFrame(MS_)\r\n # frameHD.grid(row=0, column=0, columnspan=2, padx=100,pady=10)\r\n \r\n frame00=LabelFrame(MS_,text=\"Define the structure here\", font='Arial 12 bold',padx=130, pady=50)\r\n frame00.grid(row=1, column=0, columnspan=2, padx=100,pady=10)\r\n frame01=LabelFrame(MS_,text=\"Calculate the reflectance\",font='Arial 12 bold', padx=10, pady=20)\r\n frame01.grid(row=2, column=0, padx=5,pady=5)\r\n frame02=LabelFrame(MS_,text=\"Show field profile\", font='Arial 12 bold', padx=10, pady=20)\r\n frame02.grid(row=2, column=1, padx=5,pady=5)\r\n # Frame for the structures Frame00 blanks\r\n Position=[0,0]\r\n i,j= Position \r\n DefineStructureLabel=Label(frame00, text=\"From Top to Bottom, Units (RIU, nm, #)\", \\\r\n anchor=CENTER, font='Arial 10 italic')\r\n DefineStructureLabel.grid(row=0, column=0, columnspan=10, padx=10, pady=5)\r\n\r\n# frame00 \r\n Label(frame00, text=\"n1 \").grid(row=1, column=0)\r\n n1=Entry(frame00, width = 10, borderwidth=5)\r\n n1.grid(row=1, column=1, columnspan=1, padx=5, pady=5)\r\n Label(frame00, text=\"d1 \").grid(row=1, column=2)\r\n d1=Entry(frame00, width = 10, borderwidth=5)\r\n d1.grid(row=1, column=3, columnspan=1, padx=5, pady=5)\r\n Label(frame00, text=\"n2 \").grid(row=1, column=4)\r\n n2=Entry(frame00, width = 10, borderwidth=5)\r\n n2.grid(row=1, column=5, columnspan=1, padx=5, pady=5)\r\n Label(frame00, text=\"d2 \").grid(row=1, column=6)\r\n d2=Entry(frame00, width = 10, borderwidth=5)\r\n d2.grid(row=1, column=7, columnspan=1, padx=5, pady=5)\r\n Label(frame00, text=\"repeats \").grid(row=1, column=8)\r\n period1=Entry(frame00, width = 10, borderwidth=5)\r\n period1.grid(row=1, column=9, columnspan=1, padx=5, pady=5)\r\n \r\n \r\n global n11, n21, d11, d21, period11\r\n iloc=1\r\n Label(frame00, text=\"n1 \").grid(row=1+iloc, column=0)\r\n n11=Entry(frame00, width = 10, borderwidth=5)\r\n n11.grid(row=1+iloc, column=1, columnspan=1, padx=5, pady=5)\r\n Label(frame00, text=\"d1 \").grid(row=1+iloc, column=2)\r\n d11=Entry(frame00, width = 10, borderwidth=5)\r\n d11.grid(row=1+iloc, column=3, columnspan=1, padx=5, pady=5)\r\n Label(frame00, text=\"n2 \").grid(row=1+iloc, column=4)\r\n n21=Entry(frame00, width = 10, borderwidth=5)\r\n n21.grid(row=1+iloc, column=5, columnspan=1, padx=5, pady=5)\r\n Label(frame00, text=\"d2 \").grid(row=1+iloc, column=6)\r\n d21=Entry(frame00, width = 10, borderwidth=5)\r\n d21.grid(row=1+iloc, column=7, columnspan=1, padx=5, pady=5)\r\n Label(frame00, text=\"repeats \").grid(row=1+iloc, column=8)\r\n period11=Entry(frame00, width = 10, borderwidth=5)\r\n period11.grid(row=1+iloc, column=9, columnspan=1, padx=5, pady=5)\r\n \r\n global n12, n22, d12, d22, period12\r\n iloc=2\r\n Label(frame00, text=\"n1 \").grid(row=1+iloc, column=0)\r\n n12=Entry(frame00, width = 10, borderwidth=5)\r\n n12.grid(row=1+iloc, column=1, columnspan=1, padx=5, pady=5)\r\n Label(frame00, text=\"d1 \").grid(row=1+iloc, column=2)\r\n d12=Entry(frame00, width = 10, borderwidth=5)\r\n d12.grid(row=1+iloc, column=3, columnspan=1, padx=5, pady=5)\r\n Label(frame00, text=\"n2 \").grid(row=1+iloc, column=4)\r\n n22=Entry(frame00, width = 10, borderwidth=5)\r\n n22.grid(row=1+iloc, column=5, columnspan=1, padx=5, pady=5)\r\n Label(frame00, text=\"d2 \").grid(row=1+iloc, column=6)\r\n d22=Entry(frame00, width = 10, borderwidth=5)\r\n d22.grid(row=1+iloc, column=7, columnspan=1, padx=5, pady=5)\r\n Label(frame00, text=\"repeats \").grid(row=1+iloc, column=8)\r\n period12=Entry(frame00, width = 10, borderwidth=5)\r\n period12.grid(row=1+iloc, column=9, columnspan=1, padx=5, pady=5)\r\n \r\n # Default photonic structure\r\n \r\n DefaultValues=[[2.08, 310, 1.41, 1330, 1],[1, 0, 1, 0, 0],[1, 0, 1, 0, 0]]\r\n setND(DefaultValues) \r\n \r\n # Set the buttons in Frame00 \r\n CleTableButton =Button(frame00, text= \"Clear\", command=CleTable)\r\n CleTableButton.grid(row=10, column=9, columnspan=2)\r\n \r\n Label(frame00, text='Examples:').grid(row=10, column=1, columnspan=1)\r\n \r\n SetBraggStackButton =Button(frame00, text= \"Bragg Stack\", command=SetBraggStack)\r\n SetBraggStackButton.grid(row=10, column=2, columnspan=2)\r\n \r\n SetWaveguideButton =Button(frame00, text= \"Waveguide\", command=SetWaveguide)\r\n SetWaveguideButton.grid(row=10, column=4, columnspan=2)\r\n \r\n SetDefaultButton =Button(frame00, text= \"Microcavity\", command=SetMicrocavity)\r\n SetDefaultButton.grid(row=10, column=6, columnspan=2)\r\n \r\n# frame01 \r\n # Options in Frame01\r\n Label(frame01, text=\"Select mode\", font='Arial 10 bold').grid(row=0, column=0)\r\n options=['Angle (deg)', 'Wavelength (nm)']\r\n global clicked\r\n clicked=StringVar()\r\n clicked.set(options[1]) # default option\r\n \r\n ## defaults\r\n global lim1, lim2,lim0, l0, l1, l2, l3, l1x, l2x, l3x\r\n l0=Label(frame01, text=\"Setting the working angle and wavelength limits:\")\r\n l0.grid(row=1, column=0, columnspan=2)\r\n l1=Label(frame01, text=\"angle \")\r\n l1.grid(row=2, column=0)\r\n lim0=Entry(frame01, width = 10, borderwidth=5)\r\n lim0.grid(row=2, column=1, columnspan=1, padx=5, pady=5)\r\n l1x=Label(frame01, text=\" deg\")\r\n l1x.grid(row=2, column=2)\r\n \r\n l2=Label(frame01, text=\"wavelength1 \")\r\n l2.grid(row=3, column=0)\r\n lim1=Entry(frame01, width = 10, borderwidth=5)\r\n lim1.grid(row=3, column=1, columnspan=1, padx=5, pady=5)\r\n l2x=Label(frame01, text=\" nm\")\r\n l2x.grid(row=3, column=2) \r\n \r\n l3=Label(frame01, text=\"wavelength2 \")\r\n l3.grid(row=4, column=0)\r\n lim2=Entry(frame01, width = 10, borderwidth=5)\r\n lim2.grid(row=4, column=1, columnspan=1, padx=5, pady=5)\r\n l3x=Label(frame01, text=\" nm\")\r\n l3x.grid(row=4, column=2) \r\n \r\n lim0.insert(0, 0) \r\n lim1.insert(0, 1250)\r\n lim2.insert(0, 1750) \r\n \r\n \r\n # Dropdown \r\n drop = OptionMenu(frame01, clicked, *options, command=CalChoice)\r\n drop.grid(row=0, column=1)\r\n \r\n # Set the buttons in Frame01\r\n CalRefButton =Button(frame01, text= \"Calculate\", command=CalRef)\r\n CalRefButton.grid(row=10, column=0,columnspan=2)\r\n \r\n \r\n # Frame for the structures Frame02 blanks\r\n global angle2f, depth2f, wavelength2f, theta2f, lambda2f, z2f\r\n Label(frame02, text=\"Setting the working conditions:\\\r\n \", font='Arial 10 bold').grid(row=1, column=0, columnspan=2)\r\n Label(frame02, text=\"angle \").grid(row=2, column=0)\r\n angle2f=Entry(frame02, width = 10, borderwidth=5)\r\n angle2f.grid(row=2, column=1, columnspan=1, padx=5, pady=5)\r\n Label(frame02, text=\" deg\").grid(row=2, column=2)\r\n Label(frame02, text=\"wavelength \").grid(row=3, column=0)\r\n wavelength2f=Entry(frame02, width = 10, borderwidth=5)\r\n wavelength2f.grid(row=3, column=1, columnspan=1, padx=5, pady=5)\r\n Label(frame02, text=\" nm\").grid(row=3, column=2)\r\n Label(frame02, text=\"+ Depth \").grid(row=4, column=0)\r\n depth2f=Entry(frame02, width = 10, borderwidth=5)\r\n depth2f.grid(row=4, column=1, columnspan=1, padx=5, pady=5)\r\n Label(frame02, text=\" nm\").grid(row=4, column=2)\r\n angle2f.insert(0, 50.42) \r\n wavelength2f.insert(0, 1550)\r\n depth2f.insert(0, 1000) \r\n theta2f,lambda2f, z2f=50.42,1550,1000\r\n \r\n \r\n # Set the buttons in Frame02\r\n \r\n ShowFieldButton=Button(frame02, text= \"Show Field Profile\",command=ShowField)\r\n ShowFieldButton.grid(row=10, column=0,columnspan=2)\r\n \r\n # canvas = Canvas(MS_)\r\n # canvas.grid(row=20, column=0)\r\n # img=tkinter.PhotoImage(file=\"Images/Header.jpg\")\r\n # canvas.create_image(100,100,image=img)\r\n # The headerImage\r\n# Header_img= ImageTk.PhotoImage(PIL.Image.open(\"Images/Header.jpg\"))\r\n# global B1\r\n# B1=Button(frame01, text=\"Multilayer Simulation\", padx=40, pady=10, image=Header_img,\\\r\n# compound = LEFT, command=MS_create, font='Arial 10 bold')\r\n# B1.grid(row=20, column=0, columnspan=2, padx=50,pady=10)\r\n return"
]
| [
[
"matplotlib.pyplot.yticks",
"matplotlib.pyplot.tight_layout",
"numpy.linspace",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.xlabel",
"numpy.array",
"matplotlib.pyplot.show",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.ylabel"
]
]
|
michaelhilborn/AmbulanceDeployement | [
"7bc1e920ba6ba45cd29e8fc3d9f62c8cb7bdf18d"
]
| [
"Data_Preprocessing/unit_test.py"
]
| [
"# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nThis is a temporary script file.\n\"\"\"\n\nimport numpy as np\nimport json\nimport math\nimport collections\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\n\n# This is the grid object, which is used throughout all data preprocessing.\n# It represents the city of Austin through a series of grids.\n# It thus makes a tractable way to compute distance between grids, ect. \nclass Grid():\n def __init__(self, grid_json):\n self.grid = grid_json\n self.min_lat = self.grid[\"latitude_min\"]\n self.min_lon = self.grid[\"longitude_min\"]\n self.max_lat = self.grid[\"latitude_max\"]\n self.max_lon = self.grid[\"longitude_max\"]\n self.latitude_delta = self.grid[\"latitude_step\"]\n self.longitude_delta = self.grid[\"longitude_step\"]\n self.nrows = math.ceil((self.max_lat - self.min_lat) / self.latitude_delta)\n self.ncols = math.ceil((self.max_lon - self.min_lon) / self.longitude_delta)\n self.times = self.grid[\"time_matrix\"]\n self.census_tract_region_map = self.grid[\"census_tract_region_mapping\"]\n self.region_to_tract = collections.defaultdict(list)\n for census_tract in self.census_tract_region_map:\n for region in self.census_tract_region_map[census_tract]:\n self.region_to_tract[region].append(census_tract)\n def map_point_to_region(self, latitude, longitude):\n return math.floor((latitude-self.min_lat)/self.latitude_delta) * self.ncols + math.floor((longitude-self.min_lon)/self.longitude_delta)\n def get_representative(self, region_num):\n row_num = region_num//self.ncols\n col_num = region_num - row_num*self.ncols\n lat = self.min_lat + row_num * self.latitude_delta + 0.5*self.latitude_delta\n lon = self.min_lon + col_num * self.longitude_delta + 0.5*self.longitude_delta\n return [lon, lat]\n def get_time(self, region1, region2):\n try:\n return self.times[region1][region2]\n except IndexError:\n return -1\n def region_to_census_tract(self, region):\n try:\n return self.region_to_tract[region]\n except KeyError:\n return \"0_0\"\n\n#the adjacent neighborhoods should be the same as the number of grid neighborhoods\ndef unit_test_adjacent_file_size(g, a_n): \n if len(g_lil.times) != a_n.shape[0]:\n raise AssertionError(\"adjacent_neighborhood file is the wrong size\")\n print(\"unit_test_adjacent_file_size passed\")\n\n#input: c,c2 two coverage matrices \ndef unit_test_compare_coverage_percentage(c, c2): \n c_coverage = np.sum(c) / (c.shape[0] * c.shape[1])\n c2_coverage = np.sum(c2) / (c2.shape[0] * c2.shape[1])\n print(\"c coverage = \" + str(c_coverage)) \n print(\"c2 coverage = \" + str(c2_coverage)) \n return\n\n#input: g1, g2 two travel matrices. \ndef unit_test_compare_travel_times(g, g2): \n g_times = np.array(g.times)\n g_times = g_times.flatten()\n g2_times = np.array(g2.times)\n g2_times = g2_times.flatten()\n sns.kdeplot(data = g_times , label=\"g1\")\n sns.kdeplot(g2_times, label=\"g2\")\n plt.show()\n return\n\ndef unit_test_testcall_coverage(calls, coverage, test_name): \n nsamples = 1000\n for i in range(1,nsamples):\n nbhd = calls[i,1]\n nbhd_coverage = np.sum(coverage_3200_r[:,int(nbhd)]) \n print(nbhd_coverage)\n return\n\n##############\n#LOAD ALL DATA\n##############\n# Using old distance matrix to get an idea of how close we are (?)\nwith open(\"../Input_Data/grid_info_3200_v2.json\", \"r\") as f:\n grid_json = json.load(f)\ng_big = Grid(grid_json)\n\n# Using old distance matrix to get an idea of how close we are (?)\nwith open(\"../Input_Data/grid_info_smaller.json\", \"r\") as f:\n grid_json = json.load(f)\ng_lil = Grid(grid_json)\n\nadjacent_210 = (np.genfromtxt(\"../Output_Data/austin_data/adjacent_nbhd.csv\", delimiter=\",\", dtype = str))\nadjacent_3200 = (np.genfromtxt(\"../Output_Data/austin_data_3200/adjacent_nbhd.csv\", delimiter=\",\", dtype = str))\n\ncoverage_210 = (np.genfromtxt(\"../Output_Data/austin_data/coverage.csv\", delimiter=\",\"))\ncoverage_210 = coverage_210[1:,1:] #take off header row and column.\ncoverage_3200_r = (np.genfromtxt(\"../Output_Data/austin_data_3200/coverage_regression.csv\", delimiter=\",\"))\ncoverage_3200_r = coverage_3200_r[1:,1:] #take off header row and column.\n\ncalls = (np.genfromtxt(\"../Output_Data/austin_data_3200/austin_test_calls_v3.csv\", delimiter=\",\"))\n\n##############\n#UNIT TEST\n##############\n\n# unit_test_adjacent_file_size(g_lil, adjacent_210)\n#unit_test_compare_travel_times(g_lil,g_big) #takes a long time to flatten\n#unit_test_compare_coverage_percentage(coverage_210,coverage_3200_r)\n#unit_test_compare_coverage_percentage(coverage_210,coverage_3200_r)\nunit_test_testcall_coverage(calls,coverage_3200_r,\"3200 test call coverage\")\nprint(\"hello world\")"
]
| [
[
"numpy.array",
"numpy.sum",
"matplotlib.pyplot.show",
"numpy.genfromtxt"
]
]
|
Vious/LPG_BBox_Segmentation | [
"bcb4c9e948df16763308087a4986cdb7f1a5896b"
]
| [
"utils/losses.py"
]
| [
"import torch\nimport torch.nn as nn\nfrom PIL import Image\nimport numpy as np\n\n\ndef resize_labels(labels, size):\n \"\"\"\n Downsample labels for 0.5x and 0.75x logits by nearest interpolation.\n Other nearest methods result in misaligned labels.\n -> F.interpolate(labels, shape, mode='nearest')\n -> cv2.resize(labels, shape, interpolation=cv2.INTER_NEAREST)\n \"\"\"\n new_labels = []\n for label in labels:\n label = label.float().numpy()\n label = Image.fromarray(label).resize(size, resample=Image.NEAREST)\n new_labels.append(np.asarray(label))\n new_labels = torch.LongTensor(new_labels)\n return new_labels\n\ndef build_metrics(model, batch, device):\n CEL = nn.CrossEntropyLoss(ignore_index=255).to(device)\n\n image_ids, images, labels = batch\n labels = resize_labels(labels, size=(41, 41)).to(device)\n logits = model(images.to(device))\n\n loss_seg = CEL(logits, labels)\n\n # preds = torch.argmax(logits, dim=1)\n # accuracy = float(torch.eq(preds, labels).sum().cpu()) / (len(image_ids) * logits.shape[2] * logits.shape[3])\n\n return loss_seg #, accuracy\n \n"
]
| [
[
"numpy.asarray",
"torch.LongTensor",
"torch.nn.CrossEntropyLoss"
]
]
|
HolyCrap96/mmocr-1 | [
"c6c4acd39b1c56fec1b87530b2d241fe8af4ceed"
]
| [
"mmocr/models/textdet/dense_heads/pan_head.py"
]
| [
"# Copyright (c) OpenMMLab. All rights reserved.\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom mmcv.runner import BaseModule\n\nfrom mmocr.models.builder import HEADS, build_loss\nfrom mmocr.utils import check_argument\nfrom . import HeadMixin\n\n\[email protected]_module()\nclass PANHead(HeadMixin, BaseModule):\n \"\"\"The class for PANet head.\n\n Args:\n in_channels (list[int]): A list of 4 numbers of input channels.\n out_channels (int): Number of output channels.\n text_repr_type (str): Use polygon or quad to represent. Available\n options are \"poly\" or \"quad\".\n downsample_ratio (float): Downsample ratio.\n loss (dict): Configuration dictionary for loss type. Supported loss\n types are \"PANLoss\" and \"PSELoss\".\n train_cfg, test_cfg (dict): Depreciated.\n init_cfg (dict or list[dict], optional): Initialization configs.\n \"\"\"\n\n def __init__(\n self,\n in_channels,\n out_channels,\n text_repr_type='poly', # 'poly' or 'quad'\n downsample_ratio=0.25,\n loss=dict(type='PANLoss'),\n train_cfg=None,\n test_cfg=None,\n init_cfg=dict(\n type='Normal', mean=0, std=0.01, override=dict(name='out_conv'))):\n super().__init__(init_cfg=init_cfg)\n\n assert check_argument.is_type_list(in_channels, int)\n assert isinstance(out_channels, int)\n assert text_repr_type in ['poly', 'quad']\n assert 0 <= downsample_ratio <= 1\n\n self.loss_module = build_loss(loss)\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.text_repr_type = text_repr_type\n self.train_cfg = train_cfg\n self.test_cfg = test_cfg\n self.downsample_ratio = downsample_ratio\n if loss['type'] == 'PANLoss':\n self.decoding_type = 'pan'\n elif loss['type'] == 'PSELoss':\n self.decoding_type = 'pse'\n else:\n type = loss['type']\n raise NotImplementedError(f'unsupported loss type {type}.')\n\n self.out_conv = nn.Conv2d(\n in_channels=np.sum(np.array(in_channels)),\n out_channels=out_channels,\n kernel_size=1)\n\n def forward(self, inputs):\n r\"\"\"\n Args:\n inputs (list[Tensor] | Tensor): Each tensor has the shape of\n :math:`(N, C_i, W, H)`, where :math:`\\sum_iC_i=C_{in}` and\n :math:`C_{in}` is ``input_channels``.\n\n Returns:\n Tensor: A tensor of shape :math:`(N, C_{out}, W, H)` where\n :math:`C_{out}` is ``output_channels``.\n \"\"\"\n if isinstance(inputs, tuple):\n outputs = torch.cat(inputs, dim=1)\n else:\n outputs = inputs\n outputs = self.out_conv(outputs)\n return outputs\n"
]
| [
[
"numpy.array",
"torch.cat"
]
]
|
ffmpbgrnn/google-research | [
"eb924d158768e0ca91fd382f02818d1440fb5e75"
]
| [
"l2tl/train_l2tl.py"
]
| [
"# coding=utf-8\n# Copyright 2020 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Trains an L2TL model jointly on the source and target datasets.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport re\n\nfrom absl import app\nfrom absl import flags\nimport model\nimport model_utils\nimport tensorflow as tf\nimport tensorflow_datasets as tfds\nimport tensorflow_probability as tfp\nimport numpy as np\n\nFLAGS = flags.FLAGS\n\nflags.DEFINE_string(\n 'model_dir',\n None,\n help=('The directory where the model and training/evaluation summaries are'\n ' stored.'))\nflags.DEFINE_integer(\n 'log_step_count_steps', 64, 'The number of steps at '\n 'which the global step information is logged.')\nflags.DEFINE_string(\n 'warm_start_ckpt_path', None, 'The path to the checkpoint '\n 'that will be used before training.')\nflags.DEFINE_integer('train_steps', 120000, 'Number of total training steps.')\nflags.DEFINE_integer('num_choices', 100,\n 'Number of actions for the scaling variable.')\nflags.DEFINE_float('base_learning_rate_scale', 0.001,\n 'The value of the learning rate')\nflags.DEFINE_float('dst_weight_decay', 0.0005,\n 'Weight decay for the target dataset.')\nflags.DEFINE_integer('save_checkpoints_steps', 100,\n 'Number of steps for each checkpoint saving.')\nflags.DEFINE_float('rl_learning_rate', 0.001, 'Learning rate for RL updates.')\nflags.DEFINE_float('learning_rate', 0.001, 'Learning rate for l2tl.')\nflags.DEFINE_integer('target_num_classes', 10,\n 'The number of classes in the target dataset.')\nflags.DEFINE_integer('train_batch_size', 128, 'The batch size during training.')\nflags.DEFINE_integer(\n 'source_train_batch_multiplier', 5,\n 'The multiplier will be used to increase the batch size '\n 'to sample more examples.')\nflags.DEFINE_float('loss_weight_scale', 1000.0, 'Scaling of the loss weight.')\nflags.DEFINE_integer('first_pretrain_steps', 0,\n 'Number of steps for pretraining.')\nflags.DEFINE_integer('target_val_batch_multiplier', 4,\n 'Multiplier for the target evaluation batch size.')\nflags.DEFINE_integer('target_train_batch_multiplier', 1,\n 'Multiplier for the target evaluation train batch size.')\nflags.DEFINE_integer('uniform_weight', 0,\n 'Use of uniform weight in the ablation studies.')\n\n\ndef get_global_step(name):\n \"\"\"Returns the global step variable.\"\"\"\n global_step = tf.get_variable(\n name,\n shape=[],\n dtype=tf.int64,\n initializer=tf.initializers.zeros(),\n trainable=False,\n collections=[tf.GraphKeys.GLOBAL_VARIABLES])\n return global_step\n\n\ndef get_src_train_op(loss): # pylint: disable=unused-argument\n \"\"\"Returns the source training op.\"\"\"\n global_step = tf.train.get_global_step()\n src_learning_rate = FLAGS.learning_rate\n src_learning_rate = tf.train.piecewise_constant(\n global_step, [800,],\n [FLAGS.learning_rate, FLAGS.learning_rate * 0.1])\n optimizer = tf.train.MomentumOptimizer(\n learning_rate=src_learning_rate,\n momentum=0.9,\n use_nesterov=True\n )\n with tf.variable_scope('src'):\n return optimizer.minimize(loss, global_step), src_learning_rate\n\n\ndef meta_train_op(acc, rl_entropy, log_prob, rl_scope, params): # pylint: disable=unused-argument\n \"\"\"Returns the target training op.\n\n Update the control variables using policy gradient.\n Args:\n acc: reward on validation set. In our case, the reward is the top-1 acc;\n rl_entropy: entropy of action logits;\n log_prob: log prob of the action;\n rl_scope: variable scope;\n params: other params;\n\n Returns:\n target_train_op: train op;\n rl_learning_rate: lr;\n out_metric: metric dict;\n \"\"\"\n target_global_step = get_global_step('train_rl_global_step')\n rl_reward = acc\n rl_step_baseline = rl_reward\n rl_baseline_momentum = 0.9\n rl_entropy_regularization = 0.001\n\n def update_rl_baseline():\n return model_utils.update_exponential_moving_average(\n rl_step_baseline, momentum=rl_baseline_momentum)\n\n rl_baseline = update_rl_baseline()\n\n rl_advantage = rl_reward - rl_baseline\n rl_empirical_loss = -tf.stop_gradient(rl_advantage) * log_prob\n\n rl_entropy_loss = -rl_entropy_regularization * rl_entropy\n\n enable_rl_optimizer = tf.cast(\n tf.greater_equal(target_global_step, FLAGS.first_pretrain_steps),\n tf.float32)\n rl_learning_rate = FLAGS.rl_learning_rate * enable_rl_optimizer\n rl_learning_rate = tf.train.piecewise_constant(\n target_global_step, [800,],\n [rl_learning_rate, rl_learning_rate * 0.1])\n\n optimizer = tf.train.AdamOptimizer(rl_learning_rate)\n target_train_op = optimizer.minimize(\n rl_empirical_loss,\n target_global_step,\n var_list=tf.trainable_variables(rl_scope.name))\n\n out_metric = {\n 'rl_empirical_loss': rl_empirical_loss,\n 'rl_entropy_loss': rl_entropy_loss,\n 'rl_reward': rl_reward,\n 'rl_step_baseline': rl_step_baseline,\n 'rl_baseline': rl_baseline,\n 'rl_advantage': rl_advantage,\n 'log_prob': log_prob,\n }\n return target_train_op, rl_learning_rate, out_metric\n\n\ndef get_logits(feature, mode, dataset_name, reuse=None):\n \"\"\"Returns the network logits.\"\"\"\n avg_pool = model.conv_model(feature, mode,\n target_dataset=FLAGS.target_dataset,\n src_hw=FLAGS.src_hw,\n target_hw=FLAGS.target_hw,\n dataset_name=dataset_name,\n reuse=reuse)\n return avg_pool\n\n\ndef do_cls(avg_pool, num_classes, name='dense'):\n \"\"\"Applies classification.\"\"\"\n with tf.variable_scope('target_CLS', reuse=tf.AUTO_REUSE):\n logits = tf.layers.dense(\n inputs=avg_pool,\n units=num_classes,\n kernel_initializer=tf.random_normal_initializer(stddev=.05),\n name=name)\n return logits\n\n\ndef get_model_logits(src_features, finetune_features, mode, num_classes,\n target_num_classes):\n \"\"\"Gets the logits from different models.\"\"\"\n src_avg_pool = get_logits(\n src_features, mode, FLAGS.source_dataset, reuse=None)\n dst_avg_pool = get_logits(\n finetune_features, mode, FLAGS.target_dataset, reuse=True)\n\n src_logits = do_cls(src_avg_pool, num_classes, name='final_dense_dst')\n dst_logits = do_cls(\n dst_avg_pool, target_num_classes, name='final_target_dense')\n return src_logits, dst_logits\n\n\ndef get_final_loss(src_logits, src_one_hot_labels, dst_logits,\n finetune_one_hot_labels, global_step, loss_weights,\n inst_weights):\n \"\"\"Gets the final loss for l2tl.\"\"\"\n if FLAGS.uniform_weight:\n inst_weights = 1.0\n\n def get_loss(logits, inst_weights, one_hot_labels):\n \"\"\"Returns the loss function.\"\"\"\n loss = tf.losses.softmax_cross_entropy(\n logits=logits, weights=inst_weights, onehot_labels=one_hot_labels)\n return loss\n\n src_loss = get_loss(src_logits, inst_weights, src_one_hot_labels)\n dst_loss = get_loss(dst_logits, 1., finetune_one_hot_labels)\n l2_loss = []\n for v in tf.trainable_variables():\n if 'batch_normalization' not in v.name and 'rl_controller' not in v.name:\n l2_loss.append(tf.nn.l2_loss(v))\n l2_loss = FLAGS.dst_weight_decay * tf.add_n(l2_loss)\n\n enable_pretrain = tf.cast(\n tf.greater_equal(global_step, FLAGS.first_pretrain_steps), tf.float32)\n\n loss = src_loss * tf.stop_gradient(loss_weights) * enable_pretrain\n loss += dst_loss + l2_loss\n\n return tf.identity(loss), src_loss, dst_loss\n\n\ndef train_model_fn(features, labels, mode, params): # pylint: disable=unused-argument\n \"\"\"Defines the model function.\"\"\"\n target_num_classes = FLAGS.target_num_classes\n global_step = tf.train.get_global_step()\n\n src_features, src_labels = features['src'], tf.cast(labels['src'], tf.int64)\n finetune_features = features['finetune']\n target_features = features['target']\n\n num_classes = FLAGS.src_num_classes\n\n finetune_one_hot_labels = tf.one_hot(\n tf.cast(labels['finetune'], tf.int64), target_num_classes)\n target_one_hot_labels = tf.one_hot(\n tf.cast(labels['target'], tf.int64), target_num_classes)\n\n with tf.variable_scope('rl_controller') as rl_scope:\n # It creates a `rl_scope` which will be used for ops.\n pass\n rl_entropy, label_weights, log_prob = rl_label_weights(rl_scope)\n loss_entropy, loss_weights, loss_log_prob = get_loss_weights(rl_scope)\n\n def gather_init_weights():\n inst_weights = tf.stop_gradient(tf.gather(label_weights, src_labels))\n return inst_weights\n\n inst_weights = gather_init_weights()\n bs = FLAGS.train_batch_size\n hw = FLAGS.src_hw\n inst_weights, indices = tf.nn.top_k(\n inst_weights,\n k=bs,\n sorted=True,\n )\n src_features = tf.reshape(src_features, [\n bs * FLAGS.source_train_batch_multiplier,\n hw,\n hw,\n 1,\n ])\n src_features = tf.gather(src_features, indices, axis=0)\n src_features = tf.stop_gradient(src_features)\n\n src_labels = tf.gather(src_labels, indices)\n\n inst_weights = bs * inst_weights / tf.reduce_sum(inst_weights)\n\n src_one_hot_labels = tf.one_hot(tf.cast(src_labels, tf.int64), num_classes)\n\n src_logits, dst_logits = get_model_logits(src_features, finetune_features,\n mode, num_classes,\n target_num_classes)\n\n loss, _, _ = get_final_loss(src_logits, src_one_hot_labels, dst_logits,\n finetune_one_hot_labels, global_step,\n loss_weights, inst_weights)\n\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n\n with tf.control_dependencies(update_ops):\n src_train_op, _ = get_src_train_op(loss)\n with tf.control_dependencies([src_train_op]):\n target_avg_pool = get_logits(\n target_features, mode, FLAGS.target_dataset, reuse=True)\n target_logits = do_cls(\n target_avg_pool, target_num_classes, name='final_target_dense')\n is_prediction_correct = tf.equal(\n tf.argmax(tf.identity(target_logits), axis=1),\n tf.argmax(target_one_hot_labels, axis=1))\n acc = tf.reduce_mean(tf.cast(is_prediction_correct, tf.float32))\n\n entropy = loss_entropy + rl_entropy\n log_prob = loss_log_prob + log_prob\n train_op, _, _ = meta_train_op(acc, entropy, log_prob, rl_scope, params)\n\n return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op)\n\n\ndef rl_label_weights(name=None):\n \"\"\"Returns the weight for importance.\"\"\"\n with tf.variable_scope(name, 'rl_op_selection'):\n num_classes = FLAGS.src_num_classes\n num_choices = FLAGS.num_choices\n\n logits = tf.get_variable(\n name='logits_rl_w',\n initializer=tf.initializers.zeros(),\n shape=[num_classes, num_choices],\n dtype=tf.float32)\n dist = tfp.distributions.Categorical(logits=logits)\n dist_entropy = tf.reduce_sum(dist.entropy())\n\n sample = dist.sample()\n sample_masks = 1. * tf.cast(sample, tf.float32) / num_choices\n sample_log_prob = tf.reduce_mean(dist.log_prob(sample))\n\n return (dist_entropy, sample_masks, sample_log_prob)\n\n\ndef get_loss_weights(name=None):\n \"\"\"Returns the weight for loss.\"\"\"\n with tf.variable_scope(name, 'rl_op_selection'):\n\n logits = tf.get_variable(\n name='loss_logits_rl_w',\n initializer=tf.initializers.zeros(),\n shape=[\n FLAGS.num_choices,\n ],\n dtype=tf.float32)\n dist = tfp.distributions.Categorical(logits=logits)\n dist_entropy = tf.reduce_sum(dist.entropy())\n\n sample = dist.sample()\n sample_masks = 1. * tf.cast(sample, tf.float32) / FLAGS.loss_weight_scale\n sample_log_prob = tf.reduce_mean(dist.log_prob(sample))\n\n return (dist_entropy, sample_masks, sample_log_prob)\n\n\ndef main(unused_argv):\n tf.set_random_seed(FLAGS.random_seed)\n\n run_config_args = {\n 'model_dir': FLAGS.model_dir,\n 'save_checkpoints_steps': FLAGS.save_checkpoints_steps,\n 'log_step_count_steps': FLAGS.log_step_count_steps,\n 'keep_checkpoint_max': 100,\n }\n config = tf.contrib.tpu.RunConfig(**run_config_args)\n\n if FLAGS.warm_start_ckpt_path:\n var_names = []\n checkpoint_path = FLAGS.warm_start_ckpt_path\n reader = tf.train.NewCheckpointReader(checkpoint_path)\n for key in reader.get_variable_to_shape_map():\n keep_str = 'Momentum|global_step|finetune_global_step'\n if not re.findall('({})'.format(keep_str,), key):\n var_names.append(key)\n\n tf.logging.info('Warm-starting tensors: %s', sorted(var_names))\n\n vars_to_warm_start = var_names\n warm_start_settings = tf.estimator.WarmStartSettings(\n ckpt_to_initialize_from=checkpoint_path,\n vars_to_warm_start=vars_to_warm_start)\n else:\n warm_start_settings = None\n\n l2tl_classifier = tf.estimator.Estimator(\n train_model_fn, config=config, warm_start_from=warm_start_settings)\n\n def make_input_dataset():\n \"\"\"Return input dataset.\"\"\"\n\n def _merge_datasets(train_batch, finetune_batch, target_batch):\n \"\"\"Merge different splits.\"\"\"\n train_features, train_labels = train_batch['image'], train_batch['label']\n finetune_features, finetune_labels = finetune_batch[\n 'image'], finetune_batch['label']\n target_features, target_labels = target_batch['image'], target_batch[\n 'label']\n features = {\n 'src': train_features,\n 'finetune': finetune_features,\n 'target': target_features\n }\n labels = {\n 'src': train_labels,\n 'finetune': finetune_labels,\n 'target': target_labels\n }\n return (features, labels)\n\n source_train_batch_size = int(\n round(FLAGS.train_batch_size * FLAGS.source_train_batch_multiplier))\n\n train_data = tfds.load(name=FLAGS.source_dataset, split='train')\n train_data = train_data.shuffle(512).repeat().batch(source_train_batch_size)\n\n target_train_batch_size = int(\n round(FLAGS.train_batch_size * FLAGS.target_train_batch_multiplier))\n finetune_data = tfds.load(name=FLAGS.target_dataset, split='train')\n finetune_data = finetune_data.shuffle(512).repeat().batch(\n target_train_batch_size)\n\n target_val_batch_size = int(\n round(FLAGS.train_batch_size * FLAGS.target_val_batch_multiplier))\n\n target_data = tfds.load(name=FLAGS.target_dataset, split='validation')\n target_data = target_data.shuffle(512).repeat().batch(target_val_batch_size)\n\n dataset = tf.data.Dataset.zip((train_data, finetune_data, target_data))\n dataset = dataset.map(_merge_datasets)\n dataset = dataset.prefetch(buffer_size=tf.contrib.data.AUTOTUNE)\n return dataset\n\n max_train_steps = FLAGS.train_steps\n l2tl_classifier.train(make_input_dataset, max_steps=max_train_steps)\n\n\nif __name__ == '__main__':\n tf.logging.set_verbosity(tf.logging.INFO)\n app.run(main)\n"
]
| [
[
"tensorflow.initializers.zeros",
"tensorflow.control_dependencies",
"tensorflow.reduce_sum",
"tensorflow.cast",
"tensorflow.nn.l2_loss",
"tensorflow.train.AdamOptimizer",
"tensorflow.add_n",
"tensorflow.get_collection",
"tensorflow.train.get_global_step",
"tensorflow.stop_gradient",
"tensorflow.losses.softmax_cross_entropy",
"tensorflow.train.piecewise_constant",
"tensorflow.nn.top_k",
"tensorflow.gather",
"tensorflow.train.MomentumOptimizer",
"tensorflow.logging.set_verbosity",
"tensorflow.data.Dataset.zip",
"tensorflow.trainable_variables",
"tensorflow.argmax",
"tensorflow.random_normal_initializer",
"tensorflow.estimator.WarmStartSettings",
"tensorflow.estimator.Estimator",
"tensorflow.identity",
"tensorflow.train.NewCheckpointReader",
"tensorflow.set_random_seed",
"tensorflow.reshape",
"tensorflow.contrib.tpu.RunConfig",
"tensorflow.estimator.EstimatorSpec",
"tensorflow.variable_scope",
"tensorflow.greater_equal"
]
]
|
Narsil/chempy | [
"ac7217f45a8cfe3b11ca771f78f0a04c07708818"
]
| [
"chempy/tests/test_reactionsystem.py"
]
| [
"# -*- coding: utf-8 -*-\nfrom __future__ import (absolute_import, division, print_function)\n\nfrom itertools import chain\n\nimport pytest\n\nfrom ..util.testing import requires\nfrom ..util.parsing import parsing_library\nfrom ..units import default_units, units_library\nfrom ..chemistry import Substance, Reaction\nfrom ..reactionsystem import ReactionSystem\n\n\n@requires(parsing_library, 'numpy')\ndef test_ReactionSystem():\n import numpy as np\n kw = dict(substance_factory=Substance.from_formula)\n r1 = Reaction.from_string('H2O -> H+ + OH-', 'H2O H+ OH-', name='r1')\n rs = ReactionSystem([r1], 'H2O H+ OH-', **kw)\n r2 = Reaction.from_string('H2O -> 2 H+ + OH-', 'H2O H+ OH-', name='r2')\n with pytest.raises(ValueError):\n ReactionSystem([r2], 'H2O H+ OH-', **kw)\n with pytest.raises(ValueError):\n ReactionSystem([r1, r1], 'H2O H+ OH-', **kw)\n assert rs.as_substance_index('H2O') == 0\n assert rs.as_substance_index(0) == 0\n varied, varied_keys = rs.per_substance_varied({'H2O': 55.4, 'H+': 1e-7, 'OH-': 1e-7},\n {'H+': [1e-8, 1e-9, 1e-10, 1e-11], 'OH-': [1e-3, 1e-2]})\n assert varied_keys == ('H+', 'OH-')\n assert len(varied.shape) == 3\n assert varied.shape[:-1] == (4, 2)\n assert varied.shape[-1] == 3\n assert np.all(varied[..., 0] == 55.4)\n assert np.all(varied[:, 1, 2] == 1e-2)\n\n assert rs['r1'] is r1\n rs.rxns.append(r2)\n assert rs['r2'] is r2\n with pytest.raises(KeyError):\n rs['r3']\n rs.rxns.append(Reaction({}, {}, 0, name='r2', checks=()))\n with pytest.raises(ValueError):\n rs['r2']\n\n\n@requires(parsing_library)\ndef test_ReactionSystem__check_balance():\n rs1 = ReactionSystem.from_string('\\n'.join(['2 NH3 -> N2 + 3 H2', 'N2H4 -> N2 + 2 H2']))\n assert rs1.check_balance(strict=True)\n rs2 = ReactionSystem.from_string('\\n'.join(['2 A -> B', 'B -> 2A']),\n substance_factory=Substance)\n assert not rs2.check_balance(strict=True)\n assert rs2.composition_balance_vectors() == ([], [])\n\n\ndef test_ReactionSystem__per_reaction_effect_on_substance():\n rs = ReactionSystem([Reaction({'H2': 2, 'O2': 1}, {'H2O': 2})])\n assert rs.per_reaction_effect_on_substance('H2') == {0: -2}\n assert rs.per_reaction_effect_on_substance('O2') == {0: -1}\n assert rs.per_reaction_effect_on_substance('H2O') == {0: 2}\n\n\ndef test_ReactionSystem__rates():\n rs = ReactionSystem([Reaction({'H2O'}, {'H+', 'OH-'}, 11)])\n assert rs.rates({'H2O': 3, 'H+': 5, 'OH-': 7}) == {'H2O': -11*3, 'H+': 11*3, 'OH-': 11*3}\n\n\ndef test_ReactionSystem__rates__cstr():\n k = 11\n rs = ReactionSystem([Reaction({'H2O2': 2}, {'O2': 1, 'H2O': 2}, k)])\n c0 = {'H2O2': 3, 'O2': 5, 'H2O': 53}\n fr = 7\n fc = {'H2O2': 13, 'O2': 17, 'H2O': 23}\n r = k*c0['H2O2']**2\n ref = {\n 'H2O2': -2*r + fr*fc['H2O2'] - fr*c0['H2O2'],\n 'O2': r + fr*fc['O2'] - fr*c0['O2'],\n 'H2O': 2*r + fr*fc['H2O'] - fr*c0['H2O']\n }\n variables = dict(chain(c0.items(), [('fc_'+key, val) for key, val in fc.items()], [('fr', fr)]))\n for fck in (['fc_'+key for key in rs.substances], 'fc_'):\n assert rs.rates(variables, cstr_fr_fc=('fr', fck)) == ref\n\n\ndef test_ReactionSystem__html_tables():\n r1 = Reaction({'A': 2}, {'A'}, name='R1')\n r2 = Reaction({'A'}, {'A': 2}, name='R2')\n rs = ReactionSystem([r1, r2])\n ut, unc = rs.unimolecular_html_table()\n assert unc == [r1]\n assert ut == u'<table><tr><td>A</td><td ><a title=\"A → 2 A\">R2</a></td></tr></table>'\n\n bt, bnc = rs.bimolecular_html_table()\n assert bnc == [r2]\n assert bt == u'<table><th></th><th>A</th>\\n<tr><td>A</td><td ><a title=\"2 A → A\">R1</a></td></tr></table>'\n\n\n@requires(parsing_library, 'numpy')\ndef test_ReactionSystem__substance_factory():\n r1 = Reaction.from_string('H2O -> H+ + OH-', 'H2O H+ OH-')\n rs = ReactionSystem([r1], 'H2O H+ OH-',\n substance_factory=Substance.from_formula)\n assert rs.net_stoichs(['H2O']) == [-1]\n assert rs.net_stoichs(['H+']) == [1]\n assert rs.net_stoichs(['OH-']) == [1]\n assert rs.substances['H2O'].composition[8] == 1\n assert rs.substances['OH-'].composition[0] == -1\n assert rs.substances['H+'].charge == 1\n\n\n@requires(units_library)\ndef test_ReactionSystem__as_per_substance_array_dict():\n mol = default_units.mol\n m = default_units.metre\n M = default_units.molar\n rs = ReactionSystem([], [Substance('H2O')])\n c = rs.as_per_substance_array({'H2O': 1*M}, unit=M)\n assert c.dimensionality == M.dimensionality\n assert abs(c[0]/(1000*mol/m**3) - 1) < 1e-16\n\n c = rs.as_per_substance_array({'H2O': 1})\n with pytest.raises(KeyError):\n c = rs.as_per_substance_array({'H': 1})\n\n assert rs.as_per_substance_dict([42]) == {'H2O': 42}\n\n\n@requires(parsing_library)\ndef test_ReactionSystem__add():\n rs1 = ReactionSystem.from_string('\\n'.join(['2 H2O2 -> O2 + 2 H2O', 'H2 + O2 -> H2O2']))\n rs2 = ReactionSystem.from_string('\\n'.join(['2 NH3 -> N2 + 3 H2']))\n rs3 = rs1 + rs2\n assert rs1 == rs1\n assert rs1 != rs2\n assert rs3 != rs1\n assert len(rs1.rxns) == 2 and len(rs2.rxns) == 1 and len(rs3.rxns) == 3\n for k in 'H2O2 O2 H2O H2 NH3 N2'.split():\n assert k in rs3.substances\n rs1 += rs2\n assert len(rs1.rxns) == 3 and len(rs2.rxns) == 1\n assert rs1 == rs3\n\n rs4 = ReactionSystem.from_string(\"H2O -> H+ + OH-; 1e-4\")\n rs4 += [Reaction({'H+', 'OH-'}, {'H2O'}, 1e10)]\n res = rs4.rates({'H2O': 1, 'H+': 1e-7, 'OH-': 1e-7})\n for k in 'H2O H+ OH-'.split():\n assert abs(res[k]) < 1e-16\n\n rs5 = ReactionSystem.from_string(\"H3O+ -> H+ + H2O\")\n rs6 = rs4 + rs5\n rs7 = rs6 + (Reaction.from_string(\"H+ + H2O -> H3O+\"),)\n assert len(rs7.rxns) == 4\n\n\n@requires(parsing_library)\ndef test_ReactionSystem__from_string():\n rs = ReactionSystem.from_string('-> H + OH; Radiolytic(2.1e-7)', checks=())\n assert rs.rxns[0].reac == {}\n assert rs.rxns[0].prod == {'H': 1, 'OH': 1}\n assert rs.rxns[0].param.args == [2.1e-7]\n ref = 2.1e-7 * 0.15 * 998\n assert rs.rates({'doserate': .15, 'density': 998}) == {'H': ref, 'OH': ref}\n\n r2, = ReactionSystem.from_string(\"H2O + H2O + H+ -> H3O+ + H2O\").rxns\n assert r2.reac == {'H2O': 2, 'H+': 1}\n assert r2.prod == {'H2O': 1, 'H3O+': 1}\n\n\n@requires(parsing_library)\ndef test_ReactionSystem__from_string__string_rate_const():\n rsys = ReactionSystem.from_string(\"H+ + OH- -> H2O; 'kf'\")\n r2, = rsys.rxns\n assert r2.reac == {'OH-': 1, 'H+': 1}\n assert r2.prod == {'H2O': 1}\n r2str = r2.string(rsys.substances, with_param=True)\n assert r2str.endswith('; kf')\n\n\n@requires('numpy')\ndef test_ReactionSystem__upper_conc_bounds():\n rs = ReactionSystem.from_string('\\n'.join(['2 NH3 -> N2 + 3 H2', 'N2H4 -> N2 + 2 H2']))\n c0 = {'NH3': 5, 'N2': 7, 'H2': 11, 'N2H4': 2}\n _N = 5 + 14 + 4\n _H = 15 + 22 + 8\n ref = {\n 'NH3': min(_N, _H/3),\n 'N2': _N/2,\n 'H2': _H/2,\n 'N2H4': min(_N/2, _H/4),\n }\n res = rs.as_per_substance_dict(rs.upper_conc_bounds(c0))\n assert res == ref\n\n\n@requires('numpy')\ndef test_ReactionSystem__upper_conc_bounds__a_substance_no_composition():\n rs = ReactionSystem.from_string(\"\"\"\n H2O -> e-(aq) + H2O+\n H2O+ + e-(aq) -> H2O\n \"\"\")\n c0 = {'H2O': 55.0, 'e-(aq)': 2e-3, 'H2O+': 3e-3}\n _O = 55 + 3e-3\n _H = 2*55 + 2*3e-3\n ref = {\n 'H2O': min(_O, _H/2),\n 'e-(aq)': float('inf'),\n 'H2O+': min(_O, _H/2),\n }\n res = rs.as_per_substance_dict(rs.upper_conc_bounds(c0))\n assert res == ref\n\n\ndef test_ReactionSystem__identify_equilibria():\n rsys = ReactionSystem.from_string(\"\"\"\n 2 H2 + O2 -> 2 H2O ; 1e-3\n H2O -> H+ + OH- ; 1e-4/55.35\n H+ + OH- -> H2O ; 1e10\n 2 H2O -> 2 H2 + O2\n \"\"\")\n assert rsys.identify_equilibria() == [(0, 3), (1, 2)]\n"
]
| [
[
"numpy.all"
]
]
|
LeiWang1999/tf-lenet | [
"9b47f8b4c5aad40d1bdaeed917f86d920124b6ce"
]
| [
"lenet/network.py"
]
| [
"import tensorflow as tf\nimport numpy as np\nfrom .layers import *\nfrom .support import visualize_images\nfrom .global_definitions import *\n\ndef apply_gradient_descent(var_list, obj):\n \"\"\"\n Sets up the gradient descent optimizer\n\n Args:\n var_list: List of variables to optimizer over. \n obj: Node of the objective to minimize\n Notes:\n learning_rate: What learning rate to run with. (Default = ``0.01``) Set with ``LR``\n \"\"\"\n back_prop = tf.train.GradientDescentOptimizer(\n learning_rate = LR,\n name = 'gradient_descent' ).minimize(loss = obj, \\\n var_list = var_list ) \n return back_prop\n\ndef apply_adam (var_list, obj, learning_rate = 1e-4):\n \"\"\"\n Sets up the ADAM optimizer\n\n Args:\n var_list: List of variables to optimizer over.\n obj: Node of the objective to minimize \n \n Notes:\n learning_rate: What learning rate to run with. (Default = ``0.01``) Set with ``LR``\n \"\"\" \n back_prop = tf.train.AdamOptimizer(\n learning_rate = LR,\n name = 'adam' ).minimize(loss = obj, \\\n var_list = var_list) \n return back_prop \n\ndef apply_rmsprop( var_list, obj ):\n \"\"\"\n Sets up the RMS Prop optimizer\n\n Args:\n var_list: List of variables to optimizer over.\n obj: Node of the objective to minimize \n\n Notes:\n * learning_rate: What learning rate to run with. (Default = ``0.001``). Set ``LR``\n * momentum: What is the weight for momentum to run with. (Default = ``0.7``). Set ``MOMENTUM``\n * decay: What rate should learning rate decay. (Default = ``0.95``). Set ``DECAY`` \n \"\"\" \n back_prop = tf.train.RMSPropOptimizer(\n learning_rate = LR,\n decay = DECAY,\n momentum = MOMENTUM,\n name = 'rmsprop' ).minimize(loss = obj, \\\n var_list = var_list) \n return back_prop\n\ndef apply_weight_decay (var_list, name = 'weight_decay'):\n \"\"\"\n This method applies L2 Regularization to all weights and adds it to the ``objectives`` \n collection. \n \n Args:\n name: For the tensorflow scope.\n var_list: List of variables to apply.\n \n Notes:\n What is the co-efficient of the L2 weight? Set ``WEIGHT_DECAY_COEFF``.( Default = 0.0001 )\n \"\"\" \n for param in var_list:\n norm = WEIGHT_DECAY_COEFF * tf.nn.l2_loss(param)\n tf.summary.scalar('l2_' + param.name, norm) \n tf.add_to_collection('objectives', norm)\n\ndef apply_l1 ( var_list, name = 'l1'):\n \"\"\"\n This method applies L1 Regularization to all weights and adds it to the ``objectives`` \n collection. \n \n Args:\n var_list: List of variables to apply l1\n name: For the tensorflow scope.\n \n Notes:\n What is the co-efficient of the L1 weight? Set ``L1_COEFF``.( Default = 0.0001 )\n \"\"\" \n for param in var_list:\n norm = L1_COEFF * tf.reduce_sum(tf.abs(param, name = 'abs'), name = 'l1')\n tf.summary.scalar('l1_' + param.name, norm) \n tf.add_to_collection( 'objectives', norm)\n\ndef process_params(params):\n \"\"\"\n This method adds the params to two collections.\n The first element is added to ``regularizer_worthy_params``.\n The first and second elements are is added to ``trainable_parmas``.\n\n Args:\n params: List of two.\n \"\"\"\n tf.add_to_collection( 'trainable_params', params[0])\n tf.add_to_collection( 'trainable_params', params[1]) \n tf.add_to_collection('regularizer_worthy_params', params[0]) \n\ndef apply_regularizer ( var_list):\n \"\"\"\n This method applyies Regularization to all weights and adds it to the ``objectives`` \n collection. \n \n Args:\n var_list: List of variables to apply l1\n \n Notes:\n What is the co-efficient of the L1 weight? Set ``L1_COEFF``.( Default = 0.0001 )\n \"\"\" \n with tf.variable_scope( 'weight-decay') as scope:\n if WEIGHT_DECAY_COEFF > 0:\n apply_weight_decay(name = 'weight_decay', var_list = var_list )\n\n with tf.variable_scope( 'l1-regularization') as scope:\n if L1_COEFF > 0:\n apply_l1(name = 'weight_decay', var_list = var_list)\n\n\nclass lenet5(object):\n \"\"\"\n Definition of the lenet class of networks.\n\n Notes:\n * Produces the lenet model and returns the weights. A typical lenet has \n two convolutional layers with filters sizes ``5X5`` and ``3X3``. These\n are followed by two fully-connected layers and a softmax layer. This \n network model, reproduces this network to be trained on MNIST images\n of size ``28X28``. \n * Most of the important parameters are stored in :mod:`global_definitions` \n in the file ``global_definitions.py``.\n\n Args:\n images: Placeholder for images\n\n Attributes: \n images: This is the placeholder for images. This needs to be fed in from :class:`lenet.dataset.mnist``.\n dropout_prob: This is also a placeholder for dropout probability. This needs to be fed in. \n logits: Output node of the softmax layer, before softmax. This is an output from a \n :meth:`lenet.layers.dot_product_layer`.\n inference: Output node of the softmax layer that produces inference.\n predictions: Its a predictions node which is :meth:`tf.nn.argmax` of ``inference``. \n back_prop: Backprop is an optimizer. This is a node that will be used by a :class:`lenet.trainer.trainer` later.\n obj: Is a cumulative objective tensor. This produces the total summer objective in a node.\n cost: Cost of the back prop error alone. \n labels: Placeholder for labels, needs to be fed in. This is added fed in from the dataset class.\n accuracy: Tensor for accuracy. This is a node that measures the accuracy for the mini batch.\n\n \"\"\"\n def __init__ ( self,\n images ):\n \"\"\"\n Class constructor. Creates the model and allthe connections. \n \"\"\"\n self.images = images\n # Unflatten Layer\n images_square = unflatten_layer ( self.images )\n visualize_images(images_square)\n\n # Conv Layer 1\n conv1_out, params = conv_2d_layer ( input = images_square,\n neurons = C1,\n filter_size = F1,\n name = 'conv_1',\n visualize = True )\n process_params(params)\n pool1_out = max_pool_2d_layer ( input = conv1_out, name = 'pool_1')\n lrn1_out = local_response_normalization_layer (pool1_out, name = 'lrn_1' )\n\n # Conv Layer 2\n conv2_out, params = conv_2d_layer ( input = lrn1_out,\n neurons = C2,\n filter_size = F2,\n name = 'conv_2' )\n process_params(params)\n \n pool2_out = max_pool_2d_layer ( input = conv2_out, name = 'pool_2')\n lrn2_out = local_response_normalization_layer (pool2_out, name = 'lrn_2' )\n\n flattened = flatten_layer(lrn2_out)\n\n # Placeholder probability for dropouts.\n self.dropout_prob = tf.placeholder(tf.float32,\n name = 'dropout_probability')\n\n # Dropout Layer 1 \n flattened_dropout = dropout_layer ( input = flattened,\n prob = self.dropout_prob,\n name = 'dropout_1') \n\n # Dot Product Layer 1\n fc1_out, params = dot_product_layer ( input = flattened_dropout,\n neurons = D1,\n name = 'dot_1')\n process_params(params)\n\n # Dropout Layer 2 \n fc1_out_dropout = dropout_layer ( input = fc1_out,\n prob = self.dropout_prob,\n name = 'dropout_2')\n # Dot Product Layer 2\n fc2_out, params = dot_product_layer ( input = fc1_out_dropout, \n neurons = D2,\n name = 'dot_2')\n process_params(params)\n\n # Dropout Layer 3 \n fc2_out_dropout = dropout_layer ( input = fc2_out,\n prob = self.dropout_prob,\n name = 'dropout_3')\n\n # Logits layer\n self.logits, params = dot_product_layer ( input = fc2_out_dropout,\n neurons = C,\n activation = 'identity',\n name = 'logits_layer')\n process_params(params)\n\n # Softmax layer\n self.inference, self.predictions = softmax_layer ( input = self.logits,\n name = 'softmax_layer' ) \n \n def cook(self, labels):\n \"\"\"\n Prepares the network for training\n\n Args:\n labels: placeholder for labels\n\n Notes:\n * Each optimizer has a lot parameters that, if you want to change, modify in the code\n directly. Most do not take in inputs and runs. Some parameters such as learning rates \n play a significant role in learning and are good choices to experiment with.\n * what optimizer to run with. (Default = ``sgd``), other options include\n 'rmsprop' and 'adam'. Set ``OPTIMIZER``\n \"\"\" \n with tf.variable_scope('objective') as scope:\n self.labels = labels\n with tf.variable_scope('cross-entropy') as scope:\n loss = tf.reduce_mean(\n tf.nn.softmax_cross_entropy_with_logits ( \n labels = self.labels,\n logits = self.logits)\n )\n self.cost = loss\n tf.add_to_collection('objectives', loss ) \n tf.summary.scalar('cost', loss) \n\n apply_regularizer (var_list = tf.get_collection( 'regularizer_worthy_params') )\n self.obj = tf.add_n(tf.get_collection('objectives'), name='objective')\n tf.summary.scalar('obj', self.obj) \n\n\n with tf.variable_scope('train') as scope:\n # Change (supply as arguments) parameters here directly in the code.\n if OPTIMIZER == 'sgd': \n self.back_prop = apply_gradient_descent(var_list = tf.get_collection( \\\n 'trainable_params'),\n obj = self.obj )\n elif OPTIMIZER == 'rmsprop':\n self.back_prop = apply_rmsprop(var_list = tf.get_collection( \\\n 'trainable_params') ,\n obj = self.obj)\n elif OPTIMIZER == 'adam':\n self.back_prop = apply_adam (var_list = tf.get_collection( \\\n 'trainable_params') ,\n obj = self.obj )\n else:\n raise Error('Invalid entry to optimizer')\n \n\n with tf.variable_scope('test') as scope: \n correct_predictions = tf.equal(self.predictions, tf.argmax(self.labels, 1), \\\n name = 'correct_predictions')\n self.accuracy = tf.reduce_mean(tf.cast(correct_predictions, tf.float32) , name ='accuracy') \n tf.summary.scalar('accuracy', self.accuracy) \n \n with tf.variable_scope(\"confusion\"):\n confusion = tf.confusion_matrix(tf.argmax(self.labels,1), self.predictions,\n num_classes=C,\n name='confusion')\n confusion_image = tf.reshape( tf.cast( confusion, tf.float32),[1, C, C, 1])\n tf.summary.image('confusion',confusion_image) "
]
| [
[
"tensorflow.nn.softmax_cross_entropy_with_logits",
"tensorflow.summary.scalar",
"tensorflow.train.RMSPropOptimizer",
"tensorflow.get_collection",
"tensorflow.summary.image",
"tensorflow.cast",
"tensorflow.placeholder",
"tensorflow.nn.l2_loss",
"tensorflow.train.GradientDescentOptimizer",
"tensorflow.train.AdamOptimizer",
"tensorflow.variable_scope",
"tensorflow.argmax",
"tensorflow.add_to_collection",
"tensorflow.abs"
]
]
|
deicon/tastyworks-pnl | [
"de949852865eb6b163245e06ecfcfc1a6511ca47"
]
| [
"tw-pnl.py"
]
| [
"#!/usr/bin/python3\n#\n# Copyright (C) 2020-2021 Florian La Roche <[email protected]>\n# https://github.com/laroche/tastyworks-pnl\n#\n# Generate data for a German tax income statement from Tastyworks trade history.\n#\n#\n# Download your trade history as csv file from\n# https://trade.tastyworks.com/index.html#/transactionHistoryPage\n# (Choose 'Activity' and then 'History' and then setup the filter for a\n# custom period of time and download it as csv file.)\n# Newest entries in the csv file should be on the top and it should contain the complete\n# history over all years. The csv file has the following first line:\n# Date/Time,Transaction Code,Transaction Subcode,Symbol,Buy/Sell,Open/Close,\\\n# Quantity,Expiration Date,Strike,Call/Put,Price,Fees,Amount,Description,Account Reference\n#\n#\n# Install on Debian/Ubuntu-based systems:\n#\n# sudo apt-get install python3-pandas\n#\n#\n# pylint: disable=C0103,C0111,C0114,C0116,C0326,C0330\n#\n\nimport enum\nimport sys\nimport os\nimport getopt\nfrom collections import deque\nimport math\nimport datetime as pydatetime\nimport pandas\n\n# Damit werden auch Verluste beim Schreiben von Optionen berechnet. Dies ist\n# nicht nach aktuellem Steuergesetz der Fall.\nbmf_force = False\n\ntax_output = None\n#tax_output = '2020'\n\nconvert_currency = True\n\n# For an unknown symbol (underlying), assume it is a individual/normal stock.\n# Otherwise you need to adjust the hardcoded list in this script.\nassume_stock = False\n\neurusd = None\n\n# Setup 'eurusd' as dict() to contain the EURUSD exchange rate on a given date\n# based on official data from bundesbank.de.\n# If the file 'eurusd.csv' does not exist, download the data from\n# the bundesbank directly.\ndef read_eurusd():\n global eurusd\n url = 'eurusd.csv'\n if not os.path.exists(url):\n url = 'https://www.bundesbank.de/statistic-rmi/StatisticDownload?tsId=BBEX3.D.USD.EUR.BB.AC.000&its_csvFormat=en&its_fileFormat=csv&mode=its&its_from=2010'\n eurusd = pandas.read_csv(url, skiprows=5, skipfooter=2, names=['date', 'eurusd', 'nix'],\n usecols=['date', 'eurusd'], na_values=['.'], engine='python')\n eurusd = dict(eurusd.values.tolist())\n\ndef isnan(x):\n return str(x) == 'nan'\n\ndef get_eurusd(date, debug=False):\n while True:\n try:\n x = eurusd[date]\n except KeyError:\n print('ERROR: No EURUSD conversion data available for %s,'\n ' please download newer data into the file eurusd.csv.' % date)\n sys.exit(1)\n if not isnan(x):\n return x\n if debug:\n print('EURUSD conversion not found for', date)\n date = str(pydatetime.date(*map(int, date.split('-'))) - pydatetime.timedelta(days=1))\n\ndef eur2usd(x, date, conv=None):\n if convert_currency:\n if conv is None:\n return x * get_eurusd(date)\n return x * conv\n return x\n\ndef usd2eur(x, date, conv=None):\n if convert_currency:\n if conv is None:\n return x / get_eurusd(date)\n return x / conv\n return x\n\ndef check_tcode(tcode, tsubcode, description):\n if tcode not in ('Money Movement', 'Trade', 'Receive Deliver'):\n raise\n if tcode == 'Money Movement':\n if tsubcode not in ('Transfer', 'Deposit', 'Credit Interest', 'Balance Adjustment',\n 'Fee', 'Withdrawal', 'Dividend', 'Debit Interest', 'Mark to Market'):\n raise\n if tsubcode == 'Balance Adjustment' and description != 'Regulatory fee adjustment':\n raise\n elif tcode == 'Trade':\n if tsubcode not in ('Sell to Open', 'Buy to Close', 'Buy to Open', 'Sell to Close', 'Buy', 'Sell'):\n raise\n elif tcode == 'Receive Deliver':\n if tsubcode not in ('Sell to Open', 'Buy to Close', 'Buy to Open', 'Sell to Close',\n 'Expiration', 'Assignment', 'Exercise', 'Forward Split', 'Reverse Split',\n 'Special Dividend', 'Cash Settled Exercise'): # XXX, 'Cash Settled Assignment'):\n raise\n if tsubcode == 'Assignment' and description != 'Removal of option due to assignment':\n raise\n if tsubcode == 'Exercise' and description != 'Removal of option due to exercise':\n raise\n\ndef check_param(buysell, openclose, callput):\n if str(buysell) not in ('nan', 'Buy', 'Sell'):\n raise\n if str(openclose) not in ('nan', 'Open', 'Close'):\n raise\n if str(callput) not in ('nan', 'C', 'P'):\n raise\n\ndef check_trade(tsubcode, check_amount, amount, asset_type):\n #print('FEHLER:', check_amount, amount)\n if tsubcode in ('Buy', 'Sell', 'Cash Settled Exercise', 'Special Dividend'):\n pass\n elif tsubcode not in ('Expiration', 'Assignment', 'Exercise'):\n if asset_type == AssetType.Crypto:\n if not math.isclose(check_amount, amount, abs_tol=0.01):\n raise\n else:\n if not math.isclose(check_amount, amount, abs_tol=0.001):\n raise\n else:\n if not isnan(amount) and amount != .0:\n raise\n if not isnan(check_amount) and check_amount != .0:\n raise\n\nclass AssetType(enum.IntEnum):\n LongOption = 1\n ShortOption = 2\n IndStock = 3\n AktienFond = 4\n MischFond = 5\n ImmobilienFond = 6\n OtherStock = 7\n Crypto = 8\n Future = 9\n Transfer = 10\n Dividend = 11\n Interest = 12\n WithholdingTax = 13\n OrderPayments = 14\n Fee = 15\n\ndef transaction_type(asset_type):\n t = ['', 'Long-Option', 'Stillhalter-Option', 'Aktie', 'Aktienfond', 'Mischfond', 'Immobilienfond',\n 'Sonstiges', 'Krypto', 'Future', 'Ein/Auszahlung', 'Dividende', 'Zinsen',\n 'Quellensteuer', 'Ordergebühr', 'Brokergebühr']\n if int(asset_type) >= 1 and int(asset_type) <= 15:\n return t[asset_type]\n return ''\n\n# https://en.wikipedia.org/wiki/List_of_S%26P_500_companies\nSP500 = ('A', 'AAL', 'AAP', 'AAPL', 'ABBV', 'ABC', 'ABMD', 'ABT', 'ACN', 'ADBE',\n 'ADI', 'ADM', 'ADP', 'ADSK', 'AEE', 'AEP', 'AES', 'AFL', 'AIG', 'AIZ',\n 'AJG', 'AKAM', 'ALB', 'ALGN', 'ALK', 'ALL', 'ALLE', 'AMAT', 'AMCR', 'AMD',\n 'AME', 'AMGN', 'AMP', 'AMT', 'AMZN', 'ANET', 'ANSS', 'ANTM', 'AON', 'AOS',\n 'APA', 'APD', 'APH', 'APTV', 'ARE', 'ATO', 'ATVI', 'AVB', 'AVGO', 'AVY',\n 'AWK', 'AXP', 'AZO', 'BA', 'BAC', 'BAX', 'BBWI', 'BBY', 'BDX', 'BEN',\n 'BF.B', 'BIIB', 'BIO', 'BK', 'BKNG', 'BKR', 'BLK', 'BLL', 'BMY', 'BR',\n 'BRK.B', 'BRO', 'BSX', 'BWA', 'BXP', 'C', 'CAG', 'CAH', 'CARR', 'CAT',\n 'CB', 'CBOE', 'CBRE', 'CCI', 'CCL', 'CDAY', 'CDNS', 'CDW', 'CE', 'CERN',\n 'CF', 'CFG', 'CHD', 'CHRW', 'CHTR', 'CI', 'CINF', 'CL', 'CLX', 'CMA',\n 'CMCSA', 'CME', 'CMG', 'CMI', 'CMS', 'CNC', 'CNP', 'COF', 'COO', 'COP',\n 'COST', 'CPB', 'CPRT', 'CRL', 'CRM', 'CSCO', 'CSX', 'CTAS', 'CTLT', 'CTRA',\n 'CTSH', 'CTVA', 'CTXS', 'CVS', 'CVX', 'CZR', 'D', 'DAL', 'DD', 'DE', 'DFS',\n 'DG', 'DGX', 'DHI', 'DHR', 'DIS', 'DISCA', 'DISCK', 'DISH', 'DLR', 'DLTR',\n 'DOV', 'DOW', 'DPZ', 'DRE', 'DRI', 'DTE', 'DUK', 'DVA', 'DVN', 'DXC',\n 'DXCM', 'EA', 'EBAY', 'ECL', 'ED', 'EFX', 'EIX', 'EL', 'EMN', 'EMR',\n 'ENPH', 'EOG', 'EPAM', 'EQIX', 'EQR', 'ES', 'ESS', 'ETN', 'ETR', 'ETSY',\n 'EVRG', 'EW', 'EXC', 'EXPD', 'EXPE', 'EXR', 'F', 'FANG', 'FAST', 'FB',\n 'FBHS', 'FCX', 'FDS', 'FDX', 'FE', 'FFIV', 'FIS', 'FISV', 'FITB', 'FLT',\n 'FMC', 'FOX', 'FOXA', 'FRC', 'FRT', 'FTNT', 'FTV', 'GD', 'GE', 'GILD',\n 'GIS', 'GL', 'GLW', 'GM', 'GNRC', 'GOOG', 'GOOGL', 'GPC', 'GPN', 'GPS',\n 'GRMN', 'GS', 'GWW', 'HAL', 'HAS', 'HBAN', 'HCA', 'HD', 'HES', 'HIG',\n 'HII', 'HLT', 'HOLX', 'HON', 'HPE', 'HPQ', 'HRL', 'HSIC', 'HST', 'HSY',\n 'HUM', 'HWM', 'IBM', 'ICE', 'IDXX', 'IEX', 'IFF', 'ILMN', 'INCY', 'INFO',\n 'INTC', 'INTU', 'IP', 'IPG', 'IPGP', 'IQV', 'IR', 'IRM', 'ISRG', 'IT',\n 'ITW', 'IVZ', 'J', 'JBHT', 'JCI', 'JKHY', 'JNJ', 'JNPR', 'JPM', 'K', 'KEY',\n 'KEYS', 'KHC', 'KIM', 'KLAC', 'KMB', 'KMI', 'KMX', 'KO', 'KR', 'L', 'LDOS',\n 'LEN', 'LH', 'LHX', 'LIN', 'LKQ', 'LLY', 'LMT', 'LNC', 'LNT', 'LOW',\n 'LRCX', 'LUMN', 'LUV', 'LVS', 'LW', 'LYB', 'LYV', 'MA', 'MAA', 'MAR',\n 'MAS', 'MCD', 'MCHP', 'MCK', 'MCO', 'MDLZ', 'MDT', 'MET', 'MGM', 'MHK',\n 'MKC', 'MKTX', 'MLM', 'MMC', 'MMM', 'MNST', 'MO', 'MOS', 'MPC', 'MPWR',\n 'MRK', 'MRNA', 'MRO', 'MS', 'MSCI', 'MSFT', 'MSI', 'MTB', 'MTCH', 'MTD',\n 'MU', 'NCLH', 'NDAQ', 'NEE', 'NEM', 'NFLX', 'NI', 'NKE', 'NLOK', 'NLSN',\n 'NOC', 'NOW', 'NRG', 'NSC', 'NTAP', 'NTRS', 'NUE', 'NVDA', 'NVR', 'NWL',\n 'NWS', 'NWSA', 'NXPI', 'O', 'ODFL', 'OGN', 'OKE', 'OMC', 'ORCL', 'ORLY',\n 'OTIS', 'OXY', 'PAYC', 'PAYX', 'PBCT', 'PCAR', 'PEAK', 'PEG', 'PENN',\n 'PEP', 'PFE', 'PFG', 'PG', 'PGR', 'PH', 'PHM', 'PKG', 'PKI', 'PLD', 'PM',\n 'PNC', 'PNR', 'PNW', 'POOL', 'PPG', 'PPL', 'PRU', 'PSA', 'PSX', 'PTC',\n 'PVH', 'PWR', 'PXD', 'PYPL', 'QCOM', 'QRVO', 'RCL', 'RE', 'REG', 'REGN',\n 'RF', 'RHI', 'RJF', 'RL', 'RMD', 'ROK', 'ROL', 'ROP', 'ROST', 'RSG', 'RTX',\n 'SBAC', 'SBNY', 'SBUX', 'SCHW', 'SEDG', 'SEE', 'SHW', 'SIVB', 'SJM', 'SLB',\n 'SNA', 'SNPS', 'SO', 'SPG', 'SPGI', 'SRE', 'STE', 'STT', 'STX', 'STZ',\n 'SWK', 'SWKS', 'SYF', 'SYK', 'SYY', 'T', 'TAP', 'TDG', 'TDY', 'TECH',\n 'TEL', 'TER', 'TFC', 'TFX', 'TGT', 'TJX', 'TMO', 'TMUS', 'TPR', 'TRMB',\n 'TROW', 'TRV', 'TSCO', 'TSLA', 'TSN', 'TT', 'TTWO', 'TWTR', 'TXN', 'TXT',\n 'TYL', 'UA', 'UAA', 'UAL', 'UDR', 'UHS', 'ULTA', 'UNH', 'UNP', 'UPS',\n 'URI', 'USB', 'V', 'VFC', 'VIAC', 'VLO', 'VMC', 'VNO', 'VRSK', 'VRSN',\n 'VRTX', 'VTR', 'VTRS', 'VZ', 'WAB', 'WAT', 'WBA', 'WDC', 'WEC', 'WELL',\n 'WFC', 'WHR', 'WLTW', 'WM', 'WMB', 'WMT', 'WRB', 'WRK', 'WST', 'WY',\n 'WYNN', 'XEL', 'XLNX', 'XOM', 'XRAY', 'XYL', 'YUM', 'ZBH', 'ZBRA', 'ZION',\n 'ZTS')\n\n# https://en.wikipedia.org/wiki/NASDAQ-100\nNASDAQ100 = ('ATVI', 'ADBE', 'AMD', 'ABNB', 'ALGN', 'GOOGL', 'GOOG', 'AMZN', 'AEP',\n 'AMGN', 'ADI', 'ANSS', 'AAPL', 'AMAT', 'ASML', 'TEAM', 'ADSK', 'ADP',\n 'BIDU', 'BIIB', 'BKNG', 'AVGO', 'CDNS', 'CHTR', 'CTAS', 'CSCO', 'CTSH',\n 'CMCSA', 'CPRT', 'COST', 'CRWD', 'CSX', 'DDOG', 'DXCM', 'DOCU', 'DLTR',\n 'EBAY', 'EA', 'EXC', 'FAST', 'FISV', 'FTNT', 'GILD', 'HON', 'IDXX', 'ILMN',\n 'INTC', 'INTU', 'ISRG', 'JD', 'KDP', 'KLAC', 'KHC', 'LRCX', 'LCID', 'LULU',\n 'MAR', 'MRVL', 'MTCH', 'MELI', 'FB', 'MCHP', 'MU', 'MSFT', 'MRNA', 'MDLZ',\n 'MNST', 'NTES', 'NFLX', 'NVDA', 'NXPI', 'ORLY', 'OKTA', 'PCAR', 'PANW',\n 'PAYX', 'PYPL', 'PTON', 'PEP', 'PDD', 'QCOM', 'REGN', 'ROST', 'SGEN',\n 'SIRI', 'SWKS', 'SPLK', 'SBUX', 'SNPS', 'TMUS', 'TSLA', 'TXN', 'VRSN',\n 'VRSK', 'VRTX', 'WBA', 'WDAY', 'XEL', 'XLNX', 'ZM', 'ZS')\n\ndef read_sp500():\n table = pandas.read_html('https://en.wikipedia.org/wiki/List_of_S%26P_500_companies')\n df = table[0]\n df.drop('SEC filings', axis=1, inplace=True)\n return df\n\ndef print_sp500():\n import pprint\n df = read_sp500()\n #df['Symbol'] = df['Symbol'].str.replace('.', '/')\n symbols = df['Symbol'].values.tolist()\n symbols.sort()\n p = pprint.pformat(symbols, width=79, compact=True, indent=4)\n print(p)\n\ndef read_nasdaq100():\n table = pandas.read_html('https://en.wikipedia.org/wiki/NASDAQ-100')\n df = table[3]\n return df\n\ndef print_nasdaq100():\n import pprint\n df = read_nasdaq100()\n #df['Ticker'] = df['Ticker'].str.replace('.', '/')\n symbols = df['Ticker'].values.tolist()\n p = pprint.pformat(symbols, width=79, compact=True, indent=4)\n print(p)\n\n\n# Is the symbol a individual stock or anything else\n# like an ETF or fond?\ndef is_stock(symbol, tsubcode):\n # Crypto assets like BTC/USD or ETH/USD:\n if symbol[-4:] == '/USD':\n return AssetType.Crypto\n #if symbol in ('SPY','IWM','QQQ'):\n # return AssetType.AktienFond\n # Well known ETFs:\n if symbol in ('DIA','DXJ','EEM','EFA','EFA','EWW','EWZ','FEZ','FXB','FXE','FXI',\n 'GDX','GDXJ','IWM','IYR','KRE','OIH','QQQ','TQQQ',\n 'RSX','SMH','SPY','NOBL','UNG','XBI','XHB','XLB',\n 'XLE','XLF','XLI','XLK','XLP','XLU','XLV','XME','XOP','XRT','XLRE'):\n return AssetType.OtherStock # AktienFond\n # Just an example, unfortunately EQQQ cannot be traded with Tastyworks:\n if symbol in ('EQQQ',):\n return AssetType.AktienFond\n if symbol in ('TLT','HYG','IEF','GLD','SLV','VXX','UNG','USO'):\n return AssetType.OtherStock\n # Well known individual stock names:\n if symbol in SP500 or symbol in NASDAQ100:\n return AssetType.IndStock\n if symbol.startswith('/'):\n if tsubcode not in ('Buy', 'Sell'):\n raise\n return AssetType.Future\n # The conservative way is to through an exception if we are not sure.\n if not assume_stock:\n print('No idea if this is a stock:', symbol)\n print('Use the option --assume-individual-stock to assume ' +\n 'individual stock for all unknown symbols.')\n raise\n # Just assume this is a normal stock if not in the above list\n return AssetType.IndStock\n\ndef sign(x):\n if x >= 0:\n return 1\n return -1\n\n# return date of one year earlier:\ndef prev_year(date):\n if date is None:\n return None\n return str(int(date[:4]) - 1) + date[4:]\n\n# 'fifos' is a dictionary with 'asset' names. It contains a FIFO\n# 'deque()' with a list of 'price' (as float), 'price_usd' (as float),\n# 'quantity' (as integer), 'date' of purchase and 'tax_free'.\ndef fifo_add(fifos, quantity, price, price_usd, asset, is_option, date=None,\n tax_free=False, debug=False, debugfifo=False, debugcurr=False):\n prevyear = prev_year(date)\n (pnl, pnl_notax, term_losses) = (.0, .0, .0)\n if quantity == 0:\n return (pnl, pnl_notax, term_losses)\n if debug:\n print_fifos(fifos)\n print('fifo_add', quantity, price, asset)\n # Find the right FIFO queue for our asset:\n if fifos.get(asset) is None:\n fifos[asset] = deque()\n fifo = fifos[asset]\n # If the queue is empty, just add it to the queue:\n while len(fifo) > 0:\n # If we add assets into the same trading direction,\n # just add the asset into the queue. (Buy more if we are\n # already long, or sell more if we are already short.)\n if sign(fifo[0][2]) == sign(quantity):\n break\n # Here we start removing entries from the FIFO.\n # Check if the FIFO queue has enough entries for\n # us to finish:\n if abs(fifo[0][2]) >= abs(quantity):\n if is_option and quantity > 0:\n pnl -= quantity * price\n if bmf_force and price > fifo[0][0]:\n term_losses += quantity * (price - fifo[0][0])\n #print('PLANA', term_losses)\n if term_losses < .0:\n raise\n else:\n p = quantity * (price - fifo[0][0])\n if date is None or \\\n (fifo[0][3] > prevyear and quantity < 0 and \\\n not fifo[0][4] and not tax_free):\n pnl -= p\n else:\n pnl_notax -= p\n if date is not None and debugcurr:\n print(fifo[0][3], '%.2f' % (-p / 10000.0),\n 'over one year ago or paying back loan or tax free')\n if is_option and quantity < 0 and p > .0:\n #print('Termingeschäft-Verlust von %.2f:' % p)\n term_losses += p\n if debugfifo:\n print('DEBUG FIFO: %s: del %7d * %8.4f (new: %8.4f) = %8.2f pnl %8.2f notax' \\\n % (asset, quantity, fifo[0][0], price, pnl, pnl_notax))\n fifo[0][2] += quantity\n if fifo[0][2] == 0:\n fifo.popleft()\n if len(fifo) == 0:\n del fifos[asset]\n return (pnl, pnl_notax, term_losses)\n # Remove the oldest FIFO entry and continue\n # the loop for further entries (or add the\n # remaining entries into the FIFO).\n if is_option and quantity > 0:\n pnl += fifo[0][2] * price\n if bmf_force and price > fifo[0][0]:\n term_losses -= fifo[0][2] * (price - fifo[0][0])\n #print('PLANB', term_losses)\n if term_losses < .0:\n raise\n else:\n p = fifo[0][2] * (price - fifo[0][0])\n if date is None or \\\n (fifo[0][3] > prevyear and quantity < 0 and \\\n not fifo[0][4] and not tax_free):\n pnl += p\n else:\n pnl_notax += p\n if date is not None and debugcurr:\n print(fifo[0][3], '%.2f' % (p / 10000.0),\n 'over one year ago or paying back loan or tax free')\n if is_option and quantity < 0 and p < .0:\n #print('Termingeschäft-Verlust von %.2f:' % -p)\n term_losses -= p\n if debugfifo:\n print('DEBUG FIFO: %s: del %7d * %8.4f (new: %8.4f) = %8.2f pnl, %8.2f notax' \\\n % (asset, -fifo[0][2], fifo[0][0], price, pnl, pnl_notax))\n quantity += fifo[0][2]\n fifo.popleft()\n # Just add this to the FIFO queue:\n fifo.append([price, price_usd, quantity, date, tax_free])\n # selling an option is taxed directly as income\n if is_option and quantity < 0:\n pnl -= quantity * price\n if debugfifo:\n print('DEBUG FIFO: %s: add %7d * %8.2f = %8.2f pnl %8.2f notax' \\\n % (asset, quantity, price, pnl, pnl_notax))\n return (pnl, pnl_notax, term_losses)\n\n# Check if the first entry in the FIFO\n# is 'long' the underlying or 'short'.\ndef fifos_islong(fifos, asset):\n return fifos[asset][0][2] > 0\n\ndef fifos_sum_usd(fifos):\n sum_usd = .0\n for fifo in fifos:\n if fifo != 'account-usd':\n for (price, price_usd, quantity, date, tax_free) in fifos[fifo]:\n sum_usd += price_usd * quantity\n return sum_usd\n\n# stock (and option) split\ndef fifos_split(fifos, asset, ratio):\n for fifo in fifos:\n # adjust stock for split:\n if fifo == asset:\n for f in fifos[fifo]:\n f[0] = f[0] / ratio\n f[1] = f[1] / ratio\n f[2] = f[2] * ratio\n # XXX: implement option strike adjustment\n # fifo == asset + ' ' + 'P/C' + Strike + ' '\n\ndef print_fifos(fifos):\n print('open positions:')\n for fifo in fifos:\n print(fifo, fifos[fifo])\n\n# account-usd should always be the same as total together with\n# EURUSD conversion data. So just a sanity check:\ndef check_total(fifos, total):\n for (price, price_usd, quantity, date, tax_free) in fifos['account-usd']:\n total -= quantity / 10000\n if abs(total) > 0.004:\n print(total)\n raise\n\ndef show_plt(df):\n import matplotlib.pyplot as plt\n for i in ('account_total', 'net_total', 'pnl', 'usd_gains', 'term_loss'):\n df[i] = pandas.to_numeric(df[i]) # df[i].astype(float)\n #df.plot(x='datetime', y=['account_total', 'pnl', 'term_loss'])\n df2 = df.copy()\n df2['datetime2'] = pandas.to_datetime(df2['datetime'])\n monthly_totals = df2.resample(rule='M', on='datetime2').sum() # .mean() rule='Q' quarterly\n monthly_totals.plot(kind='bar', y=['pnl',])\n #monthly_list = pandas.date_range(start='2018-04-01', end='2021-07-31', freq='M')\n #print(monthly_list)\n df.plot(y=['net_total'])\n df.plot(y=['account_total'])\n df.plot(kind='bar', y=['pnl', 'usd_gains', 'term_loss'])\n df.plot(kind='bar', y=['usd_gains'])\n df.plot(kind='bar', y=['term_loss'])\n plt.show()\n\ndef print_yearly_summary(cur_year, curr_sym, dividends, withholding_tax,\n withdrawal, interest_recv, interest_paid, fee_adjustments, pnl_stocks_gains,\n pnl_stocks_losses, future, pnl, account_usd, account_usd_notax, total_fees,\n term_losses, total, fifos, verbose):\n print()\n print('Total sums paid and received in the year %s:' % cur_year)\n if dividends != .0 or withholding_tax != .0 or verbose:\n print('dividends received: ', f'{dividends:10.2f}' + curr_sym)\n print('withholding tax paid: ', f'{withholding_tax:10.2f}' + curr_sym)\n if withdrawal != .0:\n print('dividends paid: ', f'{withdrawal:10.2f}' + curr_sym)\n print('interest received: ', f'{interest_recv:10.2f}' + curr_sym)\n if interest_paid != .0:\n print('interest paid: ', f'{interest_paid:10.2f}' + curr_sym)\n print('fee adjustments: ', f'{fee_adjustments:10.2f}' + curr_sym)\n if pnl_stocks_gains != .0 or pnl_stocks_losses != .0 or verbose:\n print('pnl stocks gains: ', f'{pnl_stocks_gains:10.2f}' + curr_sym)\n print('pnl stocks losses: ', f'{pnl_stocks_losses:10.2f}' + curr_sym)\n if future != .0 or verbose:\n print('pnl futures: ', f'{future:10.2f}' + curr_sym)\n print('pnl other: ', f'{pnl:10.2f}' + curr_sym)\n print('pnl total: ', '%10.2f' % (dividends + \\\n withdrawal + interest_recv + interest_paid + fee_adjustments + \\\n pnl_stocks_gains + pnl_stocks_losses + future + pnl) + curr_sym)\n print('USD currency gains: ', f'{account_usd:10.2f}' + curr_sym)\n print('USD curr. gains (no tax):', f'{account_usd_notax:10.2f}' + curr_sym)\n print('losses future contracts: ', f'{-term_losses:10.2f}' + curr_sym)\n print()\n print('New end sums and open positions:')\n print('total fees paid: ', f'{total_fees:10.2f}' + curr_sym)\n print('account cash balance: ', f'{total:10.2f}' + '$')\n print_fifos(fifos)\n print()\n\ndef get_summary(new_wk, year):\n stock_gains = .0\n stock_losses = .0\n fonds_gains = .0\n fonds_losses = .0\n dividend_gains = .0\n dividend_losses = .0\n withholdingtax = .0\n interest_gains = .0\n interest_losses = .0\n fee_adjustments = .0\n futures_gains = .0\n futures_losses = .0\n other_gains = .0\n other_losses = .0\n option_gains = .0\n option_losses = .0\n soption_gains = .0\n soption_losses = .0\n crypto_gains = .0\n crypto_losses = .0\n usd = .0\n usd_notax = .0\n for i in new_wk:\n type = i[1]\n usd += float(i[9])\n usd_notax += float(i[10])\n pnl = .0\n if i[2] != '':\n pnl = float(i[2])\n tax_free = i[8]\n # steuerfreie Zahlungen:\n if type in ('Brokergebühr', 'Ordergebühr', 'Zinsen', 'Dividende', 'Quellensteuer'):\n if tax_free == False:\n raise\n # keine steuerfreien Zahlungen:\n if type in ('Ein/Auszahlung', 'Aktie', 'Aktienfond', 'Mischfond',\n 'Immobilienfond', 'Sonstiges', 'Long-Option', 'Future'):\n if tax_free == True:\n raise\n if type in ('Ein/Auszahlung', 'Brokergebühr'):\n pass\n elif type == 'Ordergebühr':\n fee_adjustments += pnl\n elif type == 'Aktie':\n if pnl < .0:\n stock_losses += pnl\n else:\n stock_gains += pnl\n elif type in ('Aktienfond', 'Mischfond', 'Immobilienfond'):\n if pnl < .0:\n fonds_losses += pnl\n else:\n fonds_gains += pnl\n elif type == 'Zinsen':\n if pnl < .0:\n interest_losses += pnl\n else:\n interest_gains += pnl\n elif type == 'Sonstiges':\n if pnl < .0:\n other_losses += pnl\n else:\n other_gains += pnl\n elif type == 'Long-Option':\n if pnl < .0:\n option_losses += pnl\n else:\n option_gains += pnl\n elif type == 'Stillhalter-Option':\n if pnl < .0:\n soption_losses += pnl\n else:\n soption_gains += pnl\n # Kontrolle: Praemien sind alle steuerfrei, Glattstellungen nicht:\n if tax_free == False:\n if pnl > .0:\n raise\n else:\n if pnl < .0:\n raise\n elif type == 'Krypto':\n if pnl < .0:\n crypto_losses += pnl\n else:\n crypto_gains += pnl\n elif type == 'Dividende':\n if pnl < .0:\n dividend_losses += pnl\n else:\n dividend_gains += pnl\n elif type == 'Quellensteuer':\n withholdingtax += pnl\n elif type == 'Future':\n if pnl < .0:\n future_losses += pnl\n else:\n future_gains += pnl\n else:\n print(i)\n raise\n\n # header:\n new_wk.insert(0, ['Tastyworks %s' % year, '', '', '', '', '', '', '', '', '', ''])\n new_wk.insert(1, ['', '', '', '', '', '', '', '', '', '', ''])\n new_wk.insert(1, ['', '', '', '', '', '', '', '', '', '', ''])\n new_wk.insert(1, ['', '', '', '', '', '', '', '', '', '', ''])\n\n # summary at the end:\n new_wk.append(['', '', '', '', '', '', '', '', '', '', ''])\n new_wk.append(['', '', '', '', '', '', '', '', '', '', ''])\n new_wk.append(['', '', '', '', '', '', '', '', '', '', ''])\n new_wk.append(['', '', '', '', '', '', '', '', '', '', ''])\n if fonds_gains != .0 or fonds_losses != .0:\n new_wk.append(['Investmentfonds:', '', '', '', f'{fonds_gains + fonds_losses:.2f}', 'Euro', '', '', '', '', ''])\n if stock_gains != .0 or stock_losses != .0:\n new_wk.append(['Aktien Gewinne:', '', '', '', f'{stock_gains:.2f}', 'Euro', '', '', '', '', ''])\n new_wk.append(['Aktien Verluste:', '', '', '', f'{stock_losses:.2f}', 'Euro', '', '', '', '', ''])\n new_wk.append(['Aktien Gesamt:', '', '', '', f'{stock_gains + stock_losses:.2f}', 'Euro', '', '', '', '', ''])\n if dividend_gains != .0 or dividend_losses != .0:\n new_wk.append(['Dividenden:', '', '', '', f'{dividend_gains:.2f}', 'Euro', '', '', '', '', ''])\n if dividend_losses != .0:\n new_wk.append(['bezahlte Dividenden:', '', '', '', f'{dividend_losses:.2f}', 'Euro', '', '', '', '', ''])\n new_wk.append(['Dividenden Gesamt:', '', '', '', f'{dividend_gains + dividend_losses:.2f}', 'Euro', '', '', '', '', ''])\n if withholdingtax != .0:\n new_wk.append(['Quellensteuer:', '', '', '', f'{withholdingtax:.2f}', 'Euro', '', '', '', '', ''])\n if other_gains != .0 or other_losses != .0:\n new_wk.append(['Sonstige Gewinne:', '', '', '', f'{other_gains:.2f}', 'Euro', '', '', '', '', ''])\n new_wk.append(['Sonstige Verluste:', '', '', '', f'{other_losses:.2f}', 'Euro', '', '', '', '', ''])\n new_wk.append(['Sonstige Gesamt:', '', '', '', f'{other_gains + other_losses:.2f}', 'Euro', '', '', '', '', ''])\n if soption_gains != .0 or soption_losses != .0:\n new_wk.append(['Stillhalter Gewinne:', '', '', '', f'{soption_gains:.2f}', 'Euro', '', '', '', '', ''])\n new_wk.append(['Stillhalter Verluste:', '', '', '', f'{soption_losses:.2f}', 'Euro', '', '', '', '', ''])\n new_wk.append(['Stillhalter Gesamt:', '', '', '', f'{soption_gains + soption_losses:.2f}', 'Euro', '', '', '', '', ''])\n if option_gains != .0 or option_losses != .0:\n new_wk.append(['Long-Optionen Gewinne:', '', '', '', f'{option_gains:.2f}', 'Euro', '', '', '', '', ''])\n new_wk.append(['Long-Optionen Verluste:', '', '', '', f'{option_losses:.2f}', 'Euro', '', '', '', '', ''])\n new_wk.append(['Long-Optionen Gesamt:', '', '', '', f'{option_gains + option_losses:.2f}', 'Euro', '', '', '', '', ''])\n if crypto_gains != .0 or crypto_losses != .0:\n new_wk.append(['Krypto Gewinne:', '', '', '', f'{crypto_gains:.2f}', 'Euro', '', '', '', '', ''])\n new_wk.append(['Krypto Verluste:', '', '', '', f'{crypto_losses:.2f}', 'Euro', '', '', '', '', ''])\n new_wk.append(['Krypto Gesamt:', '', '', '', f'{crypto_gains + crypto_losses:.2f}', 'Euro', '', '', '', '', ''])\n if futures_gains != .0 or futures_losses != .0:\n new_wk.append(['Future Gewinne:', '', '', '', f'{futures_gains:.2f}', 'Euro', '', '', '', '', ''])\n new_wk.append(['Future Verluste:', '', '', '', f'{futures_losses:.2f}', 'Euro', '', '', '', '', ''])\n new_wk.append(['Future Gesamt:', '', '', '', f'{futures_gains + futures_losses:.2f}', 'Euro', '', '', '', '', ''])\n if interest_gains != .0 or interest_losses != .0:\n new_wk.append(['Zinseinnahmen:', '', '', '', f'{interest_gains:.2f}', 'Euro', '', '', '', '', ''])\n new_wk.append(['Zinsausgaben:', '', '', '', f'{interest_losses:.2f}', 'Euro', '', '', '', '', ''])\n new_wk.append(['Zinsen Gesamt:', '', '', '', f'{interest_gains + interest_losses:.2f}', 'Euro', '', '', '', '', ''])\n if fee_adjustments != .0:\n new_wk.append(['Ordergebühren:', '', '', '', f'{fee_adjustments:.2f}', 'Euro', '', '', '', '', ''])\n new_wk.append(['', '', '', '', '', '', '', '', '', '', ''])\n total_other = dividend_gains + dividend_losses + other_gains + other_losses + soption_gains + soption_losses \\\n + option_gains + option_losses + futures_gains + futures_losses + interest_gains + interest_losses + fee_adjustments\n total = total_other + fonds_gains + fonds_losses + stock_gains + stock_losses + crypto_losses + crypto_gains\n new_wk.append(['Alle Sonstige Gesamt:', '', '', '', f'{total_other:.2f}', 'Euro', '', '', '', '', ''])\n new_wk.append(['Gesamt:', '', '', '', f'{total:.2f}', 'Euro', '', '', '', '', ''])\n new_wk.append(['', '', '', '', '', '', '', '', '', '', ''])\n new_wk.append(['Währungsgewinne USD:', '', '', '', f'{usd:.2f}', 'Euro', '', '', '', '', ''])\n new_wk.append(['Währungsgewinne USD (steuerfrei):', '', '', '', f'{usd_notax:.2f}', 'Euro', '', '', '', '', ''])\n\ndef check(wk, output_csv, output_excel, opt_long, verbose, show, debugfifo):\n #print(wk)\n splits = {} # save data for stock/option splits\n curr_sym = '€'\n if not convert_currency:\n curr_sym = '$'\n fifos = {}\n total = .0 # account total\n (pnl_stocks_gains, pnl_stocks_losses, future, pnl) = (.0, .0, .0, .0)\n (account_usd, account_usd_notax) = (.0, .0)\n (dividends, withholding_tax, interest_recv, interest_paid) = (.0, .0, .0, .0)\n (withdrawal, fee_adjustments, total_fees, term_losses) = (.0, .0, .0, .0)\n cur_year = None\n prev_datetime = None\n check_account_ref = None\n new_wk = []\n for i in reversed(wk.index):\n # Date/Time,Transaction Code,Transaction Subcode,Symbol,Buy/Sell,Open/Close,\\\n # Quantity,Expiration Date,Strike,Call/Put,Price,Fees,Amount,Description,\\\n # Account Reference\n (datetime, tcode, tsubcode, symbol, buysell, openclose, quantity, expire, strike,\n callput, price, fees, amount, description, account_ref) = wk.iloc[i]\n if str(datetime)[16:] != ':00': # minimum output is minutes, seconds are 00 here\n raise\n datetime = str(datetime)[:16]\n if prev_datetime is not None and prev_datetime > datetime:\n raise\n prev_datetime = datetime\n date = datetime[:10] # year-month-day but no time\n if cur_year != datetime[:4]:\n if cur_year is not None:\n print_yearly_summary(cur_year, curr_sym, dividends, withholding_tax,\n withdrawal, interest_recv, interest_paid, fee_adjustments,\n pnl_stocks_gains, pnl_stocks_losses, future, pnl, account_usd, account_usd_notax,\n total_fees, term_losses, total, fifos, verbose)\n (pnl_stocks_gains, pnl_stocks_losses, future, pnl) = (.0, .0, .0, .0)\n (account_usd, account_usd_notax) = (.0, .0)\n (dividends, withholding_tax, interest_recv, interest_paid) = (.0, .0, .0, .0)\n (withdrawal, fee_adjustments, total_fees, term_losses) = (.0, .0, .0, .0)\n cur_year = datetime[:4]\n check_tcode(tcode, tsubcode, description)\n check_param(buysell, openclose, callput)\n if check_account_ref is None:\n check_account_ref = account_ref\n if account_ref != check_account_ref: # check if this does not change over time\n raise\n (amount, fees) = (float(amount), float(fees))\n # option/stock splits are tax neutral, so zero out amount/fees for it:\n if tcode == 'Receive Deliver' and (tsubcode == 'Forward Split' or tsubcode == 'Reverse Split'):\n (amount, fees) = (.0, .0)\n conv_usd = get_eurusd(date)\n total_fees += usd2eur(fees, date, conv_usd)\n total += amount - fees\n eur_amount = usd2eur(amount - fees, date)\n # look at currency conversion gains:\n tax_free = False\n if tsubcode in ('Deposit', 'Credit Interest', 'Debit Interest', 'Dividend',\n 'Fee', 'Balance Adjustment', 'Special Dividend'):\n tax_free = True\n if tsubcode == 'Withdrawal' and not isnan(symbol):\n tax_free = True\n # Stillhalterpraemien gelten als Zufluss und nicht als Anschaffung\n # und sind daher steuer-neutral:\n # XXX We use \"Sell-to-Open\" to find all \"Stillhaltergeschäfte\". This works\n # ok for me, but what happens if we have one long option and sell two? Will\n # Tastyworks split this into two transactions or keep this? With keeping this\n # as one transaction, we should split the currency gains transaction as well.\n # Could we detect this bad case within transactions?\n if tcode != 'Money Movement' and \\\n not isnan(expire) and str(buysell) == 'Sell' and str(openclose) == 'Open':\n tax_free = True\n # USD as a big integer number:\n (usd_gains, usd_gains_notax, _) = fifo_add(fifos, int((amount - fees) * 10000),\n 1 / conv_usd, 1, 'account-usd', False, date, tax_free, debugfifo=debugfifo)\n (usd_gains, usd_gains_notax) = (usd_gains / 10000.0, usd_gains_notax / 10000.0)\n account_usd += usd_gains\n account_usd_notax += usd_gains_notax\n\n asset = ''\n newdescription = ''\n\n if isnan(quantity):\n quantity = 1\n else:\n if tcode == 'Receive Deliver' and (tsubcode == 'Forward Split' or tsubcode == 'Reverse Split'):\n pass # splits might have further data, not quantity\n elif int(quantity) != quantity:\n # Hardcode AssetType.Crypto here again:\n if symbol[-4:] != '/USD':\n raise\n else:\n quantity = int(quantity)\n\n if isnan(price):\n price = .0\n if price < .0:\n raise\n\n header = '%s %s' % (datetime, f'{eur_amount:10.2f}' + curr_sym)\n if verbose:\n header += ' %s' % f'{usd_gains:10.2f}' + '€'\n header += ' %s' % f'{amount - fees:10.2f}' + '$'\n #if verbose:\n # header += ' %s' % f'{conv_usd:8.4f}'\n if tcode != 'Receive Deliver' or (tsubcode != 'Forward Split' and tsubcode != 'Reverse Split'):\n header += ' %5d' % quantity\n\n if tcode == 'Money Movement':\n local_pnl = '%.4f' % eur_amount\n term_loss = .0\n if tsubcode != 'Transfer' and fees != .0:\n raise\n if tsubcode == 'Transfer':\n local_pnl = ''\n asset = 'transfer'\n newdescription = description\n print(header, 'transferred:', description)\n asset_type = AssetType.Transfer\n elif tsubcode in ('Deposit', 'Credit Interest', 'Debit Interest'):\n if isnan(symbol):\n asset = 'interest'\n asset_type = AssetType.Interest\n if amount > .0:\n interest_recv += eur_amount\n else:\n interest_paid += eur_amount\n if description != 'INTEREST ON CREDIT BALANCE':\n newdescription = description\n print(header, 'interest:', description)\n else:\n print(header, 'interest')\n else:\n if amount > .0:\n asset = 'dividends for %s' % symbol\n asset_type = AssetType.Dividend\n dividends += eur_amount\n print(header, 'dividends: %s,' % symbol, description)\n else:\n asset = 'withholding tax for %s' % symbol\n asset_type = AssetType.WithholdingTax\n withholding_tax += eur_amount\n print(header, 'withholding tax: %s,' % symbol, description)\n newdescription = description\n elif tsubcode == 'Balance Adjustment':\n asset = 'balance adjustment'\n asset_type = AssetType.OrderPayments\n if opt_long:\n print(header, 'balance adjustment')\n fee_adjustments += eur_amount\n total_fees += eur_amount\n elif tsubcode == 'Fee':\n if description == 'INTL WIRE FEE':\n local_pnl = ''\n asset = 'fee'\n asset_type = AssetType.Fee\n newdescription = description\n print(header, 'fee:', description)\n total_fees += eur_amount\n else:\n # XXX In my case: stock borrow fee:\n asset = 'stock borrow fees for %s' % symbol\n asset_type = AssetType.Interest\n newdescription = description\n print(header, 'stock borrow fees: %s,' % symbol, description)\n fee_adjustments += eur_amount\n total_fees += eur_amount\n if amount >= .0:\n raise\n elif tsubcode == 'Withdrawal':\n if not isnan(symbol):\n # XXX In my case: dividends paid for short stock:\n asset = 'dividends paid for %s' % symbol\n asset_type = AssetType.Dividend\n newdescription = description\n print(header, 'dividends paid: %s,' % symbol, description)\n withdrawal += eur_amount\n if amount >= .0:\n raise\n else:\n if description[:5] == 'FROM ':\n asset = 'interest'\n asset_type = AssetType.Interest\n if amount > .0:\n interest_recv += eur_amount\n else:\n interest_paid += eur_amount\n if description != 'INTEREST ON CREDIT BALANCE':\n newdescription = description\n print(header, 'interest:', description)\n else:\n print(header, 'interest')\n else:\n # account deposit/withdrawal\n local_pnl = ''\n asset = 'transfer'\n asset_type = AssetType.Transfer\n newdescription = description\n print(header, 'transferred:', description)\n elif tsubcode == 'Dividend':\n if amount > .0:\n asset = 'dividends for %s' % symbol\n asset_type = AssetType.Dividend\n dividends += eur_amount\n print(header, 'dividends: %s,' % symbol, description)\n else:\n asset = 'withholding tax for %s' % symbol\n asset_type = AssetType.WithholdingTax\n withholding_tax += eur_amount\n print(header, 'withholding tax: %s,' % symbol, description)\n newdescription = description\n elif tsubcode == 'Mark to Market':\n asset = 'mark-to-market for %s' % symbol\n asset_type = AssetType.Future\n future += eur_amount\n print(header, description)\n newdescription = description\n elif tcode == 'Receive Deliver' and (tsubcode == 'Forward Split' or tsubcode == 'Reverse Split'):\n # XXX: We might check that the two relevant entries have the same data for 'amount'.\n x = symbol + '-' + date\n # quantity for splits seems to be more like strike price and how it changes.\n # We use it to calculate the split ration / reverse ratio.\n if (tsubcode == 'Forward Split' and str(buysell) == 'Sell') or \\\n (tsubcode == 'Reverse Split' and str(buysell) == 'Buy'):\n splits[x] = quantity\n else:\n oldquantity = splits[x]\n ratio = quantity / oldquantity\n if int(ratio) == ratio:\n ratio = int(ratio)\n #print(symbol, quantity, oldquantity, ratio)\n fifos_split(fifos, symbol, ratio)\n else:\n asset = symbol\n if not isnan(expire):\n expire = pydatetime.datetime.strptime(expire, '%m/%d/%Y').strftime('%y-%m-%d')\n # XXX hack for future multiples\n # check https://tastyworks.freshdesk.com/support/solutions/articles/43000435192\n # SP500/Nasdaq/Russel2000 and corn:\n if asset[:3] in ('/ES', '/ZW', '/ZS', '/ZC'):\n price *= 50.0\n elif asset[:3] in ('/NQ',):\n price *= 20.0\n elif asset[:4] in ('/RTY',):\n price *= 50.0\n # silver and gold:\n elif asset[:3] in ('/GC',):\n price *= 100.0\n elif asset[:4] in ('/MGC',):\n price *= 10.0\n elif asset[:3] in ('/SI',):\n price *= 5000.0\n elif asset[:4] in ('/SIL',):\n price *= 1000.0\n # oil and gas:\n elif asset[:3] in ('/CL',):\n price *= 1000.0\n elif asset[:3] in ('/QM',):\n price *= 500.0\n elif asset[:3] in ('/NG',):\n price *= 10000.0\n # bitcoin:\n elif asset[:4] in ('/BTC',):\n price *= 5.0\n elif asset[:4] in ('/MBT',):\n price *= .1\n # interest rates:\n elif asset[:3] in ('/ZT',):\n price *= 2000.0\n elif asset[:3] in ('/ZF', '/ZN', '/ZB', '/UB'):\n price *= 1000.0\n else:\n price *= 100.0\n if int(strike) == strike: # convert to integer for full numbers\n strike = int(strike)\n asset = '%s %s%s %s' % (symbol, callput, strike, expire)\n asset_type = AssetType.LongOption\n if not isnan(expire) and ((str(buysell) == 'Sell' and str(openclose) == 'Open') or \\\n (str(buysell) == 'Buy' and str(openclose) == 'Close') or\n (tsubcode in ('Expiration', 'Exercise', 'Assignment') and not fifos_islong(fifos, asset))):\n asset_type = AssetType.ShortOption\n else:\n asset_type = is_stock(symbol, tsubcode)\n # 'buysell' is not set correctly for 'Expiration'/'Exercise'/'Assignment' entries,\n # so we look into existing positions to check if we are long or short (we cannot\n # be both, so this test should be safe):\n if str(buysell) == 'Sell' or \\\n (tsubcode in ('Expiration', 'Exercise', 'Assignment') and fifos_islong(fifos, asset)):\n quantity = - quantity\n if tsubcode in ('Exercise', 'Assignment') and quantity < 0:\n print('Assignment/Exercise for a long option, please move pnl on next line to stock:')\n if tsubcode == 'Cash Settled Assignment':\n quantity = 1.0\n check_trade(tsubcode, - (quantity * price), amount, asset_type)\n price_usd = abs((amount - fees) / quantity)\n price = usd2eur(price_usd, date, conv_usd)\n (local_pnl, _, term_loss) = fifo_add(fifos, quantity, price, price_usd, asset,\n (asset_type == AssetType.LongOption) or (asset_type == AssetType.ShortOption),\n debugfifo=debugfifo)\n if term_loss < .0:\n raise\n term_losses += term_loss\n header = '%s %s' % (datetime, f'{local_pnl:10.2f}' + curr_sym)\n if verbose:\n header += ' %s' % f'{usd_gains:10.2f}' + '€'\n header += ' %s' % f'{amount-fees:10.2f}' + '$'\n #if verbose:\n # header += ' %s' % f'{conv_usd:8.4f}'\n print(header, '%5d' % quantity, asset)\n if asset_type == AssetType.IndStock:\n if local_pnl > .0:\n pnl_stocks_gains += local_pnl\n else:\n pnl_stocks_losses += local_pnl\n elif asset_type == AssetType.Future:\n if tsubcode not in ('Buy', 'Sell'):\n raise\n # XXX For futures we just add all payments as-is for taxes. We should add them\n # up until final closing instead. This should be changed. ???\n local_pnl = eur_amount\n future += local_pnl\n else:\n if cur_year >= '2018':\n if asset_type == AssetType.AktienFond:\n local_pnl *= 0.70\n elif asset_type == AssetType.MischFond:\n local_pnl *= 0.85\n elif asset_type == AssetType.ImmobilienFond:\n local_pnl *= 0.20\n pnl += local_pnl\n description = ''\n local_pnl = '%.4f' % local_pnl\n\n #check_total(fifos, total)\n\n net_total = total + fifos_sum_usd(fifos)\n\n if tax_output:\n if datetime[:4] == tax_output:\n if local_pnl != '':\n local_pnl = '%.2f' % float(local_pnl)\n new_wk.append([datetime[:10], transaction_type(asset_type),\n local_pnl, '%.2f' % eur_amount, '%.2f' % (amount - fees), '%.4f' % conv_usd,\n quantity, asset,\n tax_free, '%.2f' % usd_gains, '%.2f' % usd_gains_notax])\n else:\n new_wk.append([datetime, transaction_type(asset_type),\n local_pnl, '%.4f' % term_loss,\n '%.4f' % eur_amount, '%.4f' % amount, '%.4f' % fees, '%.4f' % conv_usd,\n quantity, asset, symbol, newdescription, '%.2f' % total, '%.2f' % net_total,\n tax_free, '%.4f' % usd_gains, '%.4f' % usd_gains_notax])\n\n wk.drop('Account Reference', axis=1, inplace=True)\n\n print_yearly_summary(cur_year, curr_sym, dividends, withholding_tax,\n withdrawal, interest_recv, interest_paid, fee_adjustments, pnl_stocks_gains,\n pnl_stocks_losses, future, pnl, account_usd, account_usd_notax, total_fees,\n term_losses, total, fifos, verbose)\n\n #print(wk)\n if tax_output:\n new_wk = sorted(new_wk, key=lambda x: x[1])\n get_summary(new_wk, tax_output)\n new_wk = pandas.DataFrame(new_wk, columns=('date', 'type', 'pnl',\n 'eur_amount', 'usd_amount', 'eurusd', 'quantity', 'asset',\n 'tax_free', 'usd_gains', 'usd_gains_notax'))\n else:\n new_wk = pandas.DataFrame(new_wk, columns=('datetime', 'type', 'pnl', 'term_loss',\n 'eur_amount', 'usd_amount', 'fees', 'eurusd', 'quantity', 'asset', 'symbol',\n 'description', 'account_total', 'net_total',\n 'tax_free', 'usd_gains', 'usd_gains_notax'))\n if output_csv is not None:\n with open(output_csv, 'w') as f:\n new_wk.to_csv(f, index=False)\n if output_excel is not None:\n with pandas.ExcelWriter(output_excel) as f:\n new_wk.to_excel(f, index=False, sheet_name='Tastyworks Report') #, engine='xlsxwriter')\n #print(new_wk)\n\n if show:\n show_plt(new_wk)\n\ndef check_csv(csv_file):\n with open(csv_file) as f:\n content = f.readlines()\n if len(content) < 1 or content[0] != 'Date/Time,Transaction Code,' + \\\n 'Transaction Subcode,Symbol,Buy/Sell,Open/Close,Quantity,' + \\\n 'Expiration Date,Strike,Call/Put,Price,Fees,Amount,Description,' + \\\n 'Account Reference\\n':\n print('ERROR: Wrong first line in csv file.')\n sys.exit(1)\n\ndef usage():\n print('tw-pnl.py [--assume-individual-stock][--long][--usd]' + \\\n '[--output-csv=test.csv][--output-excel=test.xlsx][--help]' + \\\n '[--verbose] *.csv')\n\ndef main(argv):\n #print_sp500()\n #print_nasdaq100()\n #sys.exit(0)\n opt_long = False\n verbose = False\n debugfifo = False\n output_csv = None\n output_excel = None\n show = False\n try:\n opts, args = getopt.getopt(argv, 'bhluv', ['assume-individual-stock',\n 'bmf-force', 'help', 'long', 'output-csv=',\n 'output-excel=', 'show', 'tax-output=', 'usd', 'verbose', 'debug-fifo'])\n except getopt.GetoptError:\n usage()\n sys.exit(2)\n for opt, arg in opts:\n if opt == '--assume-individual-stock':\n global assume_stock\n assume_stock = True\n elif opt in ('-b', '--bmf-force'):\n global bmf_force\n bmf_force = True\n elif opt in ('-h', '--help'):\n usage()\n sys.exit()\n elif opt in ('-l', '--long'):\n opt_long = True\n elif opt == '--output-csv':\n output_csv = arg\n elif opt == '--output-excel':\n output_excel = arg\n elif opt in ('-u', '--usd'):\n global convert_currency\n convert_currency = False\n elif opt in ('-v', '--verbose'):\n verbose = True\n elif opt == '--show':\n show = True\n elif opt == '--tax-output':\n global tax_output\n tax_output = arg\n elif opt == '--debug-fifo':\n debugfifo = True\n if len(args) == 0:\n usage()\n sys.exit()\n read_eurusd()\n args.reverse()\n for csv_file in args:\n check_csv(csv_file)\n wk = pandas.read_csv(csv_file, parse_dates=['Date/Time']) # 'Expiration Date'])\n check(wk, output_csv, output_excel, opt_long, verbose, show, debugfifo)\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n\n"
]
| [
[
"pandas.read_csv",
"pandas.to_datetime",
"pandas.read_html",
"pandas.DataFrame",
"pandas.ExcelWriter",
"matplotlib.pyplot.show",
"pandas.to_numeric"
]
]
|
MontpellierRessourcesImagerie/napari | [
"8d5ffd29f3c9d460600e65e58c64c7294fb2164e"
]
| [
"napari/_qt/qt_viewer.py"
]
| [
"from __future__ import annotations\n\nimport logging\nimport warnings\nfrom typing import TYPE_CHECKING, List, Optional, Sequence, Tuple\n\nimport numpy as np\nfrom qtpy.QtCore import QCoreApplication, QObject, Qt\nfrom qtpy.QtGui import QCursor, QGuiApplication\nfrom qtpy.QtWidgets import QFileDialog, QSplitter, QVBoxLayout, QWidget\n\nfrom ..components._interaction_box_mouse_bindings import (\n InteractionBoxMouseBindings,\n)\nfrom ..components.camera import Camera\nfrom ..components.layerlist import LayerList\nfrom ..layers.base.base import Layer\nfrom ..plugins import _npe2\nfrom ..utils import config, perf\nfrom ..utils._proxies import ReadOnlyWrapper\nfrom ..utils.action_manager import action_manager\nfrom ..utils.colormaps.standardize_color import transform_color\nfrom ..utils.history import (\n get_open_history,\n get_save_history,\n update_open_history,\n update_save_history,\n)\nfrom ..utils.interactions import (\n mouse_double_click_callbacks,\n mouse_move_callbacks,\n mouse_press_callbacks,\n mouse_release_callbacks,\n mouse_wheel_callbacks,\n)\nfrom ..utils.io import imsave\nfrom ..utils.key_bindings import KeymapHandler\nfrom ..utils.misc import in_ipython\nfrom ..utils.theme import get_theme\nfrom ..utils.translations import trans\nfrom .containers import QtLayerList\nfrom .dialogs.screenshot_dialog import ScreenshotDialog\nfrom .perf.qt_performance import QtPerformance\nfrom .utils import QImg2array, circle_pixmap, crosshair_pixmap, square_pixmap\nfrom .widgets.qt_dims import QtDims\nfrom .widgets.qt_viewer_buttons import QtLayerButtons, QtViewerButtons\nfrom .widgets.qt_viewer_dock_widget import QtViewerDockWidget\nfrom .widgets.qt_welcome import QtWidgetOverlay\n\nfrom .._vispy import ( # isort:skip\n VispyAxesOverlay,\n VispyCamera,\n VispyCanvas,\n VispyScaleBarOverlay,\n VispyInteractionBox,\n VispyTextOverlay,\n create_vispy_visual,\n)\n\n\nif TYPE_CHECKING:\n from ..components import ViewerModel\n from npe2.manifest.contributions import WriterContribution\n\nfrom ..settings import get_settings\nfrom ..utils.io import imsave_extensions\n\n\ndef _npe2_decode_selected_filter(\n ext_str: str, selected_filter: str, writers: Sequence[WriterContribution]\n) -> Optional[WriterContribution]:\n \"\"\"Determine the writer that should be invoked to save data.\n\n When npe2 can be imported, resolves a selected file extension\n string into a specific writer. Otherwise, returns None.\n \"\"\"\n # When npe2 is not present, `writers` is expected to be an empty list,\n # `[]`. This function will return None.\n\n for entry, writer in zip(\n ext_str.split(\";;\"),\n writers,\n ):\n if entry.startswith(selected_filter):\n return writer\n return None\n\n\ndef _extension_string_for_layers(\n layers: Sequence[Layer],\n) -> Tuple[str, List[WriterContribution]]:\n \"\"\"Return an extension string and the list of corresponding writers.\n\n The extension string is a \";;\" delimeted string of entries. Each entry\n has a brief description of the file type and a list of extensions.\n\n The writers, when provided, are the npe2.manifest.io.WriterContribution\n objects. There is one writer per entry in the extension string. If npe2\n is not importable, the list of writers will be empty.\n \"\"\"\n # try to use npe2\n ext_str, writers = _npe2.file_extensions_string_for_layers(layers)\n if ext_str:\n return ext_str, writers\n\n # fallback to old behavior\n\n if len(layers) == 1:\n selected_layer = layers[0]\n # single selected layer.\n if selected_layer._type_string == 'image':\n\n ext = imsave_extensions()\n\n ext_list = [f\"*{val}\" for val in ext]\n ext_str = ';;'.join(ext_list)\n\n ext_str = trans._(\n \"All Files (*);; Image file types:;;{ext_str}\",\n ext_str=ext_str,\n )\n\n elif selected_layer._type_string == 'points':\n\n ext_str = trans._(\"All Files (*);; *.csv;;\")\n\n else:\n # layer other than image or points\n ext_str = trans._(\"All Files (*);;\")\n\n else:\n # multiple layers.\n ext_str = trans._(\"All Files (*);;\")\n return ext_str, []\n\n\nclass QtViewer(QSplitter):\n \"\"\"Qt view for the napari Viewer model.\n\n Parameters\n ----------\n viewer : napari.components.ViewerModel\n Napari viewer containing the rendered scene, layers, and controls.\n show_welcome_screen : bool, optional\n Flag to show a welcome message when no layers are present in the\n canvas. Default is `False`.\n\n Attributes\n ----------\n canvas : vispy.scene.SceneCanvas\n Canvas for rendering the current view.\n console : QtConsole\n IPython console terminal integrated into the napari GUI.\n controls : QtLayerControlsContainer\n Qt view for GUI controls.\n dims : napari.qt_dims.QtDims\n Dimension sliders; Qt View for Dims model.\n dockConsole : QtViewerDockWidget\n QWidget wrapped in a QDockWidget with forwarded viewer events.\n aboutKeybindings : QtAboutKeybindings\n Key bindings for the 'About' Qt dialog.\n dockLayerControls : QtViewerDockWidget\n QWidget wrapped in a QDockWidget with forwarded viewer events.\n dockLayerList : QtViewerDockWidget\n QWidget wrapped in a QDockWidget with forwarded viewer events.\n layerButtons : QtLayerButtons\n Button controls for napari layers.\n layers : QtLayerList\n Qt view for LayerList controls.\n layer_to_visual : dict\n Dictionary mapping napari layers with their corresponding vispy_layers.\n view : vispy scene widget\n View displayed by vispy canvas. Adds a vispy ViewBox as a child widget.\n viewer : napari.components.ViewerModel\n Napari viewer containing the rendered scene, layers, and controls.\n viewerButtons : QtViewerButtons\n Button controls for the napari viewer.\n \"\"\"\n\n def __init__(self, viewer: ViewerModel, show_welcome_screen: bool = False):\n # Avoid circular import.\n from .layer_controls import QtLayerControlsContainer\n\n super().__init__()\n self.setAttribute(Qt.WA_DeleteOnClose)\n\n self._show_welcome_screen = show_welcome_screen\n\n QCoreApplication.setAttribute(\n Qt.AA_UseStyleSheetPropagationInWidgetStyles, True\n )\n\n self.viewer = viewer\n self.dims = QtDims(self.viewer.dims)\n self.controls = QtLayerControlsContainer(self.viewer)\n self.layers = QtLayerList(self.viewer.layers)\n self.layerButtons = QtLayerButtons(self.viewer)\n self.viewerButtons = QtViewerButtons(self.viewer)\n self._key_map_handler = KeymapHandler()\n self._key_map_handler.keymap_providers = [self.viewer]\n self._console = None\n\n layerList = QWidget()\n layerList.setObjectName('layerList')\n layerListLayout = QVBoxLayout()\n layerListLayout.addWidget(self.layerButtons)\n layerListLayout.addWidget(self.layers)\n layerListLayout.addWidget(self.viewerButtons)\n layerListLayout.setContentsMargins(8, 4, 8, 6)\n layerList.setLayout(layerListLayout)\n\n self.dockLayerList = QtViewerDockWidget(\n self,\n layerList,\n name=trans._('layer list'),\n area='left',\n allowed_areas=['left', 'right'],\n object_name='layer list',\n )\n self.dockLayerControls = QtViewerDockWidget(\n self,\n self.controls,\n name=trans._('layer controls'),\n area='left',\n allowed_areas=['left', 'right'],\n object_name='layer controls',\n )\n self.dockConsole = QtViewerDockWidget(\n self,\n QWidget(),\n name=trans._('console'),\n area='bottom',\n allowed_areas=['top', 'bottom'],\n object_name='console',\n )\n self.dockConsole.setVisible(False)\n # because the console is loaded lazily in the @getter, this line just\n # gets (or creates) the console when the dock console is made visible.\n self.dockConsole.visibilityChanged.connect(self._ensure_connect)\n self.dockLayerControls.visibilityChanged.connect(self._constrain_width)\n self.dockLayerList.setMaximumWidth(258)\n self.dockLayerList.setMinimumWidth(258)\n\n # Only created if using perfmon.\n self.dockPerformance = self._create_performance_dock_widget()\n\n # This dictionary holds the corresponding vispy visual for each layer\n self.layer_to_visual = {}\n\n self._create_canvas()\n\n # Stacked widget to provide a welcome page\n self._canvas_overlay = QtWidgetOverlay(self, self.canvas.native)\n self._canvas_overlay.set_welcome_visible(show_welcome_screen)\n self._canvas_overlay.sig_dropped.connect(self.dropEvent)\n\n main_widget = QWidget()\n main_layout = QVBoxLayout()\n main_layout.setContentsMargins(10, 22, 10, 2)\n main_layout.addWidget(self._canvas_overlay)\n main_layout.addWidget(self.dims)\n main_layout.setSpacing(10)\n main_widget.setLayout(main_layout)\n\n self.setOrientation(Qt.Vertical)\n self.addWidget(main_widget)\n\n self._cursors = {\n 'cross': Qt.CrossCursor,\n 'forbidden': Qt.ForbiddenCursor,\n 'pointing': Qt.PointingHandCursor,\n 'standard': QCursor(),\n }\n\n self._on_active_change()\n self.viewer.layers.events.inserted.connect(self._update_welcome_screen)\n self.viewer.layers.events.removed.connect(self._update_welcome_screen)\n self.viewer.layers.selection.events.active.connect(\n self._on_active_change\n )\n self.viewer.camera.events.interactive.connect(self._on_interactive)\n self.viewer.cursor.events.style.connect(self._on_cursor)\n self.viewer.cursor.events.size.connect(self._on_cursor)\n self.viewer.layers.events.reordered.connect(self._reorder_layers)\n self.viewer.layers.events.inserted.connect(self._on_add_layer_change)\n self.viewer.layers.events.removed.connect(self._remove_layer)\n\n self.setAcceptDrops(True)\n\n for layer in self.viewer.layers:\n self._add_layer(layer)\n\n self.view = self.canvas.central_widget.add_view(border_width=0)\n self.camera = VispyCamera(\n self.view, self.viewer.camera, self.viewer.dims\n )\n self.canvas.events.draw.connect(self.camera.on_draw)\n\n # Add axes, scale bar\n self._add_visuals()\n\n # Create the experimental QtPool for octree and/or monitor.\n self._qt_poll = _create_qt_poll(self, self.viewer.camera)\n\n # Create the experimental RemoteManager for the monitor.\n self._remote_manager = _create_remote_manager(\n self.viewer.layers, self._qt_poll\n )\n\n # moved from the old layerlist... still feels misplaced.\n # can you help me move this elsewhere?\n if config.async_loading:\n from .experimental.qt_chunk_receiver import QtChunkReceiver\n\n # The QtChunkReceiver object allows the ChunkLoader to pass newly\n # loaded chunks to the layers that requested them.\n self.chunk_receiver = QtChunkReceiver(self.layers)\n else:\n self.chunk_receiver = None\n\n # bind shortcuts stored in settings last.\n self._bind_shortcuts()\n\n def _ensure_connect(self):\n # lazy load console\n id(self.console)\n\n def _bind_shortcuts(self):\n \"\"\"Bind shortcuts stored in SETTINGS to actions.\"\"\"\n for action, shortcuts in get_settings().shortcuts.shortcuts.items():\n action_manager.unbind_shortcut(action)\n for shortcut in shortcuts:\n action_manager.bind_shortcut(action, shortcut)\n\n def _create_canvas(self) -> None:\n \"\"\"Create the canvas and hook up events.\"\"\"\n self.canvas = VispyCanvas(\n keys=None,\n vsync=True,\n parent=self,\n size=self.viewer._canvas_size[::-1],\n )\n self.canvas.events.draw.connect(self.dims.enable_play)\n\n self.canvas.events.mouse_double_click.connect(\n self.on_mouse_double_click\n )\n self.canvas.events.mouse_move.connect(self.on_mouse_move)\n self.canvas.events.mouse_press.connect(self.on_mouse_press)\n self.canvas.events.mouse_release.connect(self.on_mouse_release)\n self.canvas.events.key_press.connect(\n self._key_map_handler.on_key_press\n )\n self.canvas.events.key_release.connect(\n self._key_map_handler.on_key_release\n )\n self.canvas.events.mouse_wheel.connect(self.on_mouse_wheel)\n self.canvas.events.draw.connect(self.on_draw)\n self.canvas.events.resize.connect(self.on_resize)\n self.canvas.bgcolor = transform_color(\n get_theme(self.viewer.theme, False).canvas.as_hex()\n )[0]\n theme = self.viewer.events.theme\n\n on_theme_change = self.canvas._on_theme_change\n theme.connect(on_theme_change)\n\n self.canvas.destroyed.connect(self._diconnect_theme)\n\n def _diconnect_theme(self):\n self.viewer.events.theme.disconnect(self.canvas._on_theme_change)\n\n def _add_visuals(self) -> None:\n \"\"\"Add visuals for axes, scale bar, and welcome text.\"\"\"\n\n self.axes = VispyAxesOverlay(\n self.viewer,\n parent=self.view.scene,\n order=1e6,\n )\n self.scale_bar = VispyScaleBarOverlay(\n self.viewer,\n parent=self.view,\n order=1e6 + 1,\n )\n self.canvas.events.resize.connect(self.scale_bar._on_position_change)\n self.text_overlay = VispyTextOverlay(\n self.viewer,\n parent=self.view,\n order=1e6 + 2,\n )\n self.canvas.events.resize.connect(\n self.text_overlay._on_position_change\n )\n self.interaction_box_visual = VispyInteractionBox(\n self.viewer, parent=self.view.scene, order=1e6 + 3\n )\n self.interaction_box_mousebindings = InteractionBoxMouseBindings(\n self.viewer, self.interaction_box_visual\n )\n\n def _create_performance_dock_widget(self):\n \"\"\"Create the dock widget that shows performance metrics.\"\"\"\n if perf.USE_PERFMON:\n return QtViewerDockWidget(\n self,\n QtPerformance(),\n name=trans._('performance'),\n area='bottom',\n )\n return None\n\n @property\n def console(self):\n \"\"\"QtConsole: iPython console terminal integrated into the napari GUI.\"\"\"\n if self._console is None:\n try:\n from napari_console import QtConsole\n\n import napari\n\n with warnings.catch_warnings():\n warnings.filterwarnings(\"ignore\")\n self.console = QtConsole(self.viewer)\n self.console.push(\n {'napari': napari, 'action_manager': action_manager}\n )\n except ImportError:\n warnings.warn(\n trans._(\n 'napari-console not found. It can be installed with'\n ' \"pip install napari_console\"'\n )\n )\n self._console = None\n return self._console\n\n @console.setter\n def console(self, console):\n self._console = console\n if console is not None:\n self.dockConsole.setWidget(console)\n console.setParent(self.dockConsole)\n\n def _constrain_width(self, event):\n \"\"\"Allow the layer controls to be wider, only if floated.\n\n Parameters\n ----------\n event : napari.utils.event.Event\n The napari event that triggered this method.\n \"\"\"\n if self.dockLayerControls.isFloating():\n self.controls.setMaximumWidth(700)\n else:\n self.controls.setMaximumWidth(220)\n\n def _on_active_change(self):\n \"\"\"When active layer changes change keymap handler.\"\"\"\n self._key_map_handler.keymap_providers = (\n [self.viewer]\n if self.viewer.layers.selection.active is None\n else [self.viewer.layers.selection.active, self.viewer]\n )\n\n def _on_add_layer_change(self, event):\n \"\"\"When a layer is added, set its parent and order.\n\n Parameters\n ----------\n event : napari.utils.event.Event\n The napari event that triggered this method.\n \"\"\"\n layer = event.value\n self._add_layer(layer)\n\n def _add_layer(self, layer):\n \"\"\"When a layer is added, set its parent and order.\n\n Parameters\n ----------\n layer : napari.layers.Layer\n Layer to be added.\n \"\"\"\n vispy_layer = create_vispy_visual(layer)\n\n # QtPoll is experimental.\n if self._qt_poll is not None:\n # QtPoll will call VipyBaseImage._on_poll() when the camera\n # moves or the timer goes off.\n self._qt_poll.events.poll.connect(vispy_layer._on_poll)\n\n # In the other direction, some visuals need to tell QtPoll to\n # start polling. When they receive new data they need to be\n # polled to load it, even if the camera is not moving.\n if vispy_layer.events is not None:\n vispy_layer.events.loaded.connect(self._qt_poll.wake_up)\n\n vispy_layer.node.parent = self.view.scene\n vispy_layer.order = len(self.viewer.layers) - 1\n self.layer_to_visual[layer] = vispy_layer\n\n def _remove_layer(self, event):\n \"\"\"When a layer is removed, remove its parent.\n\n Parameters\n ----------\n event : napari.utils.event.Event\n The napari event that triggered this method.\n \"\"\"\n layer = event.value\n vispy_layer = self.layer_to_visual[layer]\n vispy_layer.close()\n del vispy_layer\n del self.layer_to_visual[layer]\n self._reorder_layers()\n\n def _reorder_layers(self):\n \"\"\"When the list is reordered, propagate changes to draw order.\"\"\"\n for i, layer in enumerate(self.viewer.layers):\n vispy_layer = self.layer_to_visual[layer]\n vispy_layer.order = i\n self.canvas._draw_order.clear()\n self.canvas.update()\n\n def _save_layers_dialog(self, selected=False):\n \"\"\"Save layers (all or selected) to disk, using ``LayerList.save()``.\n\n Parameters\n ----------\n selected : bool\n If True, only layers that are selected in the viewer will be saved.\n By default, all layers are saved.\n \"\"\"\n msg = ''\n if not len(self.viewer.layers):\n msg = trans._(\"There are no layers in the viewer to save\")\n elif selected and not len(self.viewer.layers.selection):\n msg = trans._(\n 'Please select one or more layers to save,'\n '\\nor use \"Save all layers...\"'\n )\n if msg:\n raise OSError(trans._(\"Nothing to save\"))\n\n # prepare list of extensions for drop down menu.\n ext_str, writers = _extension_string_for_layers(\n list(self.viewer.layers.selection)\n if selected\n else self.viewer.layers\n )\n\n msg = trans._(\"selected\") if selected else trans._(\"all\")\n dlg = QFileDialog()\n hist = get_save_history()\n dlg.setHistory(hist)\n\n filename, selected_filter = dlg.getSaveFileName(\n parent=self,\n caption=trans._('Save {msg} layers', msg=msg),\n directory=hist[0], # home dir by default,\n filter=ext_str,\n options=(\n QFileDialog.DontUseNativeDialog\n if in_ipython()\n else QFileDialog.Options()\n ),\n )\n logging.debug(\n f'QFileDialog - filename: {filename or None} '\n f'selected_filter: {selected_filter or None}'\n )\n\n if filename:\n writer = _npe2_decode_selected_filter(\n ext_str, selected_filter, writers\n )\n with warnings.catch_warnings(record=True) as wa:\n saved = self.viewer.layers.save(\n filename, selected=selected, _writer=writer\n )\n logging.debug(f'Saved {saved}')\n error_messages = \"\\n\".join(str(x.message.args[0]) for x in wa)\n\n if not saved:\n raise OSError(\n trans._(\n \"File {filename} save failed.\\n{error_messages}\",\n deferred=True,\n filename=filename,\n error_messages=error_messages,\n )\n )\n else:\n update_save_history(saved[0])\n\n def _update_welcome_screen(self):\n \"\"\"Update welcome screen display based on layer count.\"\"\"\n if self._show_welcome_screen:\n self._canvas_overlay.set_welcome_visible(not self.viewer.layers)\n\n def _screenshot(self, flash=True):\n \"\"\"Capture a screenshot of the Vispy canvas.\n\n Parameters\n ----------\n flash : bool\n Flag to indicate whether flash animation should be shown after\n the screenshot was captured.\n \"\"\"\n # CAN REMOVE THIS AFTER DEPRECATION IS DONE, see self.screenshot.\n img = self.canvas.native.grabFramebuffer()\n if flash:\n from .utils import add_flash_animation\n\n # Here we are actually applying the effect to the `_canvas_overlay`\n # and not # the `native` widget because it does not work on the\n # `native` widget. It's probably because the widget is in a stack\n # with the `QtWelcomeWidget`.\n add_flash_animation(self._canvas_overlay)\n return img\n\n def screenshot(self, path=None, flash=True):\n \"\"\"Take currently displayed screen and convert to an image array.\n\n Parameters\n ----------\n path : str\n Filename for saving screenshot image.\n flash : bool\n Flag to indicate whether flash animation should be shown after\n the screenshot was captured.\n\n Returns\n -------\n image : array\n Numpy array of type ubyte and shape (h, w, 4). Index [0, 0] is the\n upper-left corner of the rendered region.\n \"\"\"\n import warnings\n\n warnings.warn(\n trans._(\n \"'window.qt_viewer.screenshot' is deprecated and will be removed in v0.4.14. Please use 'window.screenshot(canvas_only=True)' instead\"\n ),\n FutureWarning,\n stacklevel=2,\n )\n\n img = QImg2array(self._screenshot(flash))\n if path is not None:\n imsave(path, img) # scikit-image imsave method\n return img\n\n def clipboard(self, flash=True):\n \"\"\"Take a screenshot of the currently displayed screen and copy the\n image to the clipboard.\n\n Parameters\n ----------\n flash : bool\n Flag to indicate whether flash animation should be shown after\n the screenshot was captured.\n \"\"\"\n import warnings\n\n warnings.warn(\n trans._(\n \"'window.qt_viewer.screenshot' is deprecated and will be removed in v0.4.14. Please use 'window.screenshot(canvas_only=True)' instead\"\n ),\n FutureWarning,\n stacklevel=2,\n )\n cb = QGuiApplication.clipboard()\n cb.setImage(self._screenshot(flash))\n\n def _screenshot_dialog(self):\n \"\"\"Save screenshot of current display, default .png\"\"\"\n hist = get_save_history()\n dial = ScreenshotDialog(self.screenshot, self, hist[0], hist)\n if dial.exec_():\n update_save_history(dial.selectedFiles()[0])\n\n def _open_files_dialog(self):\n \"\"\"Add files from the menubar.\"\"\"\n dlg = QFileDialog()\n hist = get_open_history()\n dlg.setHistory(hist)\n\n filenames, _ = dlg.getOpenFileNames(\n parent=self,\n caption=trans._('Select file(s)...'),\n directory=hist[0],\n options=(\n QFileDialog.DontUseNativeDialog\n if in_ipython()\n else QFileDialog.Options()\n ),\n )\n\n if (filenames != []) and (filenames is not None):\n self.viewer.open(filenames)\n update_open_history(filenames[0])\n\n def _open_files_dialog_as_stack_dialog(self):\n \"\"\"Add files as a stack, from the menubar.\"\"\"\n dlg = QFileDialog()\n hist = get_open_history()\n dlg.setHistory(hist)\n\n filenames, _ = dlg.getOpenFileNames(\n parent=self,\n caption=trans._('Select files...'),\n directory=hist[0], # home dir by default\n options=(\n QFileDialog.DontUseNativeDialog\n if in_ipython()\n else QFileDialog.Options()\n ),\n )\n\n if (filenames != []) and (filenames is not None):\n self.viewer.open(filenames, stack=True)\n update_open_history(filenames[0])\n\n def _open_folder_dialog(self):\n \"\"\"Add a folder of files from the menubar.\"\"\"\n dlg = QFileDialog()\n hist = get_open_history()\n dlg.setHistory(hist)\n\n folder = dlg.getExistingDirectory(\n parent=self,\n caption=trans._('Select folder...'),\n directory=hist[0], # home dir by default\n options=(\n QFileDialog.DontUseNativeDialog\n if in_ipython()\n else QFileDialog.Options()\n ),\n )\n\n if folder not in {'', None}:\n self.viewer.open([folder])\n update_open_history(folder)\n\n def _toggle_chunk_outlines(self):\n \"\"\"Toggle whether we are drawing outlines around the chunks.\"\"\"\n from ..layers.image.experimental.octree_image import _OctreeImageBase\n\n for layer in self.viewer.layers:\n if isinstance(layer, _OctreeImageBase):\n layer.display.show_grid = not layer.display.show_grid\n\n def _on_interactive(self):\n \"\"\"Link interactive attributes of view and viewer.\"\"\"\n self.view.interactive = self.viewer.camera.interactive\n\n def _on_cursor(self):\n \"\"\"Set the appearance of the mouse cursor.\"\"\"\n cursor = self.viewer.cursor.style\n # Scale size by zoom if needed\n if self.viewer.cursor.scaled:\n size = self.viewer.cursor.size * self.viewer.camera.zoom\n else:\n size = self.viewer.cursor.size\n\n if cursor == 'square':\n # make sure the square fits within the current canvas\n if size < 8 or size > (\n min(*self.viewer.window._qt_viewer.canvas.size) - 4\n ):\n q_cursor = self._cursors['cross']\n else:\n q_cursor = QCursor(square_pixmap(size))\n elif cursor == 'circle':\n q_cursor = QCursor(circle_pixmap(size))\n elif cursor == 'crosshair':\n q_cursor = QCursor(crosshair_pixmap())\n else:\n q_cursor = self._cursors[cursor]\n\n self.canvas.native.setCursor(q_cursor)\n\n def toggle_console_visibility(self, event=None):\n \"\"\"Toggle console visible and not visible.\n\n Imports the console the first time it is requested.\n \"\"\"\n # force instantiation of console if not already instantiated\n _ = self.console\n\n viz = not self.dockConsole.isVisible()\n # modulate visibility at the dock widget level as console is dockable\n self.dockConsole.setVisible(viz)\n if self.dockConsole.isFloating():\n self.dockConsole.setFloating(True)\n\n if viz:\n self.dockConsole.raise_()\n\n self.viewerButtons.consoleButton.setProperty(\n 'expanded', self.dockConsole.isVisible()\n )\n self.viewerButtons.consoleButton.style().unpolish(\n self.viewerButtons.consoleButton\n )\n self.viewerButtons.consoleButton.style().polish(\n self.viewerButtons.consoleButton\n )\n\n def _map_canvas2world(self, position):\n \"\"\"Map position from canvas pixels into world coordinates.\n\n Parameters\n ----------\n position : 2-tuple\n Position in canvas (x, y).\n\n Returns\n -------\n coords : tuple\n Position in world coordinates, matches the total dimensionality\n of the viewer.\n \"\"\"\n nd = self.viewer.dims.ndisplay\n transform = self.view.scene.transform\n mapped_position = transform.imap(list(position))[:nd]\n position_world_slice = mapped_position[::-1]\n\n position_world = list(self.viewer.dims.point)\n for i, d in enumerate(self.viewer.dims.displayed):\n position_world[d] = position_world_slice[i]\n\n return tuple(position_world)\n\n @property\n def _canvas_corners_in_world(self):\n \"\"\"Location of the corners of canvas in world coordinates.\n\n Returns\n -------\n corners : 2-tuple\n Coordinates of top left and bottom right canvas pixel in the world.\n \"\"\"\n # Find corners of canvas in world coordinates\n top_left = self._map_canvas2world([0, 0])\n bottom_right = self._map_canvas2world(self.canvas.size)\n return np.array([top_left, bottom_right])\n\n def on_resize(self, event):\n \"\"\"Called whenever canvas is resized.\n\n event : vispy.util.event.Event\n The vispy event that triggered this method.\n \"\"\"\n self.viewer._canvas_size = tuple(self.canvas.size[::-1])\n\n def _process_mouse_event(self, mouse_callbacks, event):\n \"\"\"Add properties to the mouse event before passing the event to the\n napari events system. Called whenever the mouse moves or is clicked.\n As such, care should be taken to reduce the overhead in this function.\n In future work, we should consider limiting the frequency at which\n it is called.\n\n This method adds following:\n position: the position of the click in world coordinates.\n view_direction: a unit vector giving the direction of the camera in\n world coordinates.\n dims_displayed: a list of the dimensions currently being displayed\n in the viewer. This comes from viewer.dims.displayed.\n dims_point: the indices for the data in view in world coordinates.\n This comes from viewer.dims.point\n\n Parameters\n ----------\n mouse_callbacks : function\n Mouse callbacks function.\n event : vispy.event.Event\n The vispy event that triggered this method.\n \"\"\"\n if event.pos is None:\n return\n\n # Add the view ray to the event\n event.view_direction = self.viewer.camera.calculate_nd_view_direction(\n self.viewer.dims.ndim, self.viewer.dims.displayed\n )\n\n # Update the cursor position\n self.viewer.cursor._view_direction = event.view_direction\n self.viewer.cursor.position = self._map_canvas2world(list(event.pos))\n\n # Add the cursor position to the event\n event.position = self.viewer.cursor.position\n\n # Add the displayed dimensions to the event\n event.dims_displayed = list(self.viewer.dims.displayed)\n\n # Add the current dims indices\n event.dims_point = list(self.viewer.dims.point)\n\n # Put a read only wrapper on the event\n event = ReadOnlyWrapper(event)\n mouse_callbacks(self.viewer, event)\n\n layer = self.viewer.layers.selection.active\n if layer is not None:\n mouse_callbacks(layer, event)\n\n def on_mouse_wheel(self, event):\n \"\"\"Called whenever mouse wheel activated in canvas.\n\n Parameters\n ----------\n event : vispy.event.Event\n The vispy event that triggered this method.\n \"\"\"\n self._process_mouse_event(mouse_wheel_callbacks, event)\n\n def on_mouse_double_click(self, event):\n \"\"\"Called whenever a mouse double-click happen on the canvas\n\n Parameters\n ----------\n event : vispy.event.Event\n The vispy event that triggered this method. The `event.type` will always be `mouse_double_click`\n\n Notes\n -----\n\n Note that this triggers in addition to the usual mouse press and mouse release.\n Therefore a double click from the user will likely triggers the following event in sequence:\n\n - mouse_press\n - mouse_release\n - mouse_double_click\n - mouse_release\n \"\"\"\n self._process_mouse_event(mouse_double_click_callbacks, event)\n\n def on_mouse_press(self, event):\n \"\"\"Called whenever mouse pressed in canvas.\n\n Parameters\n ----------\n event : vispy.event.Event\n The vispy event that triggered this method.\n \"\"\"\n self._process_mouse_event(mouse_press_callbacks, event)\n\n def on_mouse_move(self, event):\n \"\"\"Called whenever mouse moves over canvas.\n\n Parameters\n ----------\n event : vispy.event.Event\n The vispy event that triggered this method.\n \"\"\"\n self._process_mouse_event(mouse_move_callbacks, event)\n\n def on_mouse_release(self, event):\n \"\"\"Called whenever mouse released in canvas.\n\n Parameters\n ----------\n event : vispy.event.Event\n The vispy event that triggered this method.\n \"\"\"\n self._process_mouse_event(mouse_release_callbacks, event)\n\n def on_draw(self, event):\n \"\"\"Called whenever the canvas is drawn.\n\n This is triggered from vispy whenever new data is sent to the canvas or\n the camera is moved and is connected in the `QtViewer`.\n \"\"\"\n for layer in self.viewer.layers:\n if layer.ndim <= self.viewer.dims.ndim:\n nd = len(layer._displayed_axes)\n if nd > self.viewer.dims.ndisplay:\n displayed_axes = layer._displayed_axes\n else:\n displayed_axes = self.viewer.dims.displayed[-nd:]\n layer._update_draw(\n scale_factor=1 / self.viewer.camera.zoom,\n corner_pixels_displayed=self._canvas_corners_in_world[\n :, displayed_axes\n ],\n shape_threshold=self.canvas.size,\n )\n\n def set_welcome_visible(self, visible):\n \"\"\"Show welcome screen widget.\"\"\"\n self._show_welcome_screen = visible\n self._canvas_overlay.set_welcome_visible(visible)\n\n def keyPressEvent(self, event):\n \"\"\"Called whenever a key is pressed.\n\n Parameters\n ----------\n event : qtpy.QtCore.QEvent\n Event from the Qt context.\n \"\"\"\n self.canvas._backend._keyEvent(self.canvas.events.key_press, event)\n event.accept()\n\n def keyReleaseEvent(self, event):\n \"\"\"Called whenever a key is released.\n\n Parameters\n ----------\n event : qtpy.QtCore.QEvent\n Event from the Qt context.\n \"\"\"\n self.canvas._backend._keyEvent(self.canvas.events.key_release, event)\n event.accept()\n\n def dragEnterEvent(self, event):\n \"\"\"Ignore event if not dragging & dropping a file or URL to open.\n\n Using event.ignore() here allows the event to pass through the\n parent widget to its child widget, otherwise the parent widget\n would catch the event and not pass it on to the child widget.\n\n Parameters\n ----------\n event : qtpy.QtCore.QEvent\n Event from the Qt context.\n \"\"\"\n if event.mimeData().hasUrls():\n event.accept()\n else:\n event.ignore()\n\n def dropEvent(self, event):\n \"\"\"Add local files and web URLS with drag and drop.\n\n Parameters\n ----------\n event : qtpy.QtCore.QEvent\n Event from the Qt context.\n \"\"\"\n shift_down = QGuiApplication.keyboardModifiers() & Qt.ShiftModifier\n filenames = []\n for url in event.mimeData().urls():\n if url.isLocalFile():\n filenames.append(url.toLocalFile())\n else:\n filenames.append(url.toString())\n\n self.viewer.open(filenames, stack=bool(shift_down))\n\n def closeEvent(self, event):\n \"\"\"Cleanup and close.\n\n Parameters\n ----------\n event : qtpy.QtCore.QEvent\n Event from the Qt context.\n \"\"\"\n self.layers.close()\n\n # if the viewer.QtDims object is playing an axis, we need to terminate\n # the AnimationThread before close, otherwise it will cauyse a segFault\n # or Abort trap. (calling stop() when no animation is occurring is also\n # not a problem)\n self.dims.stop()\n self.canvas.native.deleteLater()\n if self._console is not None:\n self.console.close()\n self.dockConsole.deleteLater()\n event.accept()\n\n\nif TYPE_CHECKING:\n from ..components.experimental.remote import RemoteManager\n from .experimental.qt_poll import QtPoll\n\n\ndef _create_qt_poll(parent: QObject, camera: Camera) -> Optional[QtPoll]:\n \"\"\"Create and return a QtPoll instance, if needed.\n\n Create a QtPoll instance for octree or monitor.\n\n Octree needs QtPoll so VispyTiledImageLayer can finish in-progress\n loads even if the camera is not moving. Once loading is finish it will\n tell QtPoll it no longer needs to be polled.\n\n Monitor needs QtPoll to poll for incoming messages. This might be\n temporary until we can process incoming messages with a dedicated\n thread.\n\n Parameters\n ----------\n parent : QObject\n Parent Qt object.\n camera : Camera\n Camera that the QtPoll object will listen to.\n\n Returns\n -------\n Optional[QtPoll]\n The new QtPoll instance, if we need one.\n \"\"\"\n if not config.async_octree and not config.monitor:\n return None\n\n from .experimental.qt_poll import QtPoll\n\n qt_poll = QtPoll(parent)\n camera.events.connect(qt_poll.on_camera)\n return qt_poll\n\n\ndef _create_remote_manager(\n layers: LayerList, qt_poll\n) -> Optional[RemoteManager]:\n \"\"\"Create and return a RemoteManager instance, if we need one.\n\n Parameters\n ----------\n layers : LayersList\n The viewer's layers.\n qt_poll : QtPoll\n The viewer's QtPoll instance.\n \"\"\"\n if not config.monitor:\n return None # Not using the monitor at all\n\n from ..components.experimental.monitor import monitor\n from ..components.experimental.remote import RemoteManager\n\n # Start the monitor so we can access its events. The monitor has no\n # dependencies to napari except to utils.Event.\n started = monitor.start()\n\n if not started:\n return None # Probably not >= Python 3.9, so no manager is needed.\n\n # Create the remote manager and have monitor call its process_command()\n # method to execute commands from clients.\n manager = RemoteManager(layers)\n\n # RemoteManager will process incoming command from the monitor.\n monitor.run_command_event.connect(manager.process_command)\n\n # QtPoll should pool the RemoteManager and the Monitor.\n qt_poll.events.poll.connect(manager.on_poll)\n qt_poll.events.poll.connect(monitor.on_poll)\n\n return manager\n"
]
| [
[
"numpy.array"
]
]
|
Ignoramus-Sage/RBM-DBN_DNN | [
"175d722c4c9898a1a61e86ea164d80c17f4b7943"
]
| [
"principal_DNN_MNIST.py"
]
| [
"from principal_DBN_alpha import *\r\nimport tensorflow as tf\r\nimport numpy as np\r\n\r\ndef scale_and_read_img(data_set):\r\n snip = None\r\n data_std = (data_set - np.min(data_set))/(np.max(data_set) - np.min(data_set))\r\n for datum in data_std:\r\n temp = datum.flatten(order='F')\r\n if snip is not None:\r\n snip = np.vstack((snip, temp))\r\n else :\r\n snip = temp\r\n return snip\r\n\r\ndef transform_labels(labels):\r\n output = np.zeros((labels.shape[0], 10))\r\n for idx, label in enumerate(labels):\r\n output[idx, label] = 1\r\n return output\r\n\r\nclass MNIST_DNN(DNN):\r\n \r\n def __init__(self, n_layers):\r\n super().__init__(n_layers)\r\n \r\n def calcul_softmax(self, rbm_struct, data_in):\r\n _, h_p = rbm_struct.entree_sortie_RBM(data_in, act='softmax')\r\n return h_p\r\n \r\n def entree_sortie_reseau(self, data_in):\r\n outputs = [data_in]\r\n for rbm in self.RBM_list[:-1]:\r\n _ , data_in = rbm.entree_sortie_RBM(data_in)\r\n outputs.append(data_in)\r\n outputs.append(self.calcul_softmax(self.RBM_list[-1], data_in))\r\n return outputs\r\n \r\n def retropropagation(self, data, labels, batch_size=50, n_epoch=10000, lr_rate=0.01, verbose=True):\r\n assert n_epoch > 0\r\n batch_size = batch_size if batch_size <= data.shape[1] else data.shape[1]\r\n for i in range(n_epoch):\r\n batch_idx = np.random.choice(np.arange(data.shape[0]), batch_size)\r\n batch = data[batch_idx]\r\n batch_labels = labels[batch_idx]\r\n outputs = self.entree_sortie_reseau(batch)\r\n rbm = self.RBM_list[-1]\r\n c = (outputs[-1]-batch_labels)\r\n rbm.weights -= lr_rate/batch_size * outputs[-2].T @ c \r\n rbm.bias_b -= lr_rate * np.mean(c, axis = 0) \r\n for idx, rbm in reversed(list(enumerate(self.RBM_list[:-1]))):\r\n c = [email protected]_list[idx+1].weights.T*outputs[idx+1]*(1-outputs[idx+1])\r\n rbm.weights -= lr_rate/batch_size * outputs[idx].T @ c \r\n rbm.bias_b -= lr_rate * np.mean(c, axis=0) \r\n if verbose==True and i%1000==0:\r\n print(\"Iteration %d out of %d. CELoss value is %.4f\" %(i, n_epoch,\r\n -np.sum(batch_labels*np.log(outputs[-1]))/batch_size))\r\n return self\r\n \r\n def test_dnn(self, data, labels):\r\n for rbm in self.RBM_list[:-1]:\r\n _ , data = rbm.entree_sortie_RBM(data)\r\n preds = np.argmax(self.calcul_softmax(self.RBM_list[-1], data), axis=1)\r\n good_labels = 0\r\n for idx, pred in enumerate(preds):\r\n if pred==labels[idx]:\r\n good_labels+=1\r\n print(\"The percentage of false labeled data is \", 100*(labels.shape[0]-good_labels)/labels.shape[0])\r\n return 100*(labels.shape[0]-good_labels)/labels.shape[0]\r\n \r\n \r\nif __name__ == \"__main__\" :\r\n \r\n print('Loading data...')\r\n (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data(path=\"mnist.npz\")\r\n print('Transforming and standarising data...')\r\n data = scale_and_read_img(x_train) # This may take a while to execute\r\n test_data = scale_and_read_img(x_test)\r\n labels = transform_labels(y_train)\r\n \r\n layers = [data[0, :].shape[0], 700, 600, 500, 400, 300, 200, 100, 50, 10]\r\n test_dnn = MNIST_DNN(layers)\r\n print('begin unsupervised training')\r\n test_dnn = test_dnn.pretrain_DNN(data, batch_size=150, n_epoch=20000)\r\n print('Unsupervised training is done')\r\n \r\n print('begin supervised training')\r\n test_dnn = test_dnn.retropropagation(data, labels, lr_rate=0.1, batch_size=150, n_epoch=60000)\r\n print('Supervised training is done')\r\n test_dnn.test(test_data, y_test)\r\n \r\n test_dnn1 = MNIST_DNN(layers)\r\n print('begin unsupervised training')\r\n test_dnn1 = test_dnn1.retropropagation(data, labels, lr_rate=0.1, batch_size=150, n_epoch=60000)\r\n print('Unsupervised training is done')\r\n \r\n test_dnn1.test(test_data, y_test)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n"
]
| [
[
"numpy.log",
"numpy.min",
"numpy.arange",
"tensorflow.keras.datasets.mnist.load_data",
"numpy.max",
"numpy.mean",
"numpy.zeros",
"numpy.vstack"
]
]
|
justiniann/ConvX | [
"78e74a2cd8b8f43088d7fd52e75db5e2468177b9"
]
| [
"source/convx/analysis.py"
]
| [
"from keras.applications import ResNet50\nfrom keras.layers import *\nfrom keras.models import Model\nfrom keras.models import Sequential\nfrom keras.models import model_from_json\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.utils import to_categorical\nfrom sklearn.metrics import accuracy_score, fbeta_score, confusion_matrix\n\nfrom convx.convx_utils import *\n\nif __name__ == '__main__':\n # This is our base model. We will use the weights and structure already known to be successful in other domains and\n # adjust it to fit our current problem\n base_model = ResNet50(include_top=False, weights='imagenet', input_shape=(512, 512, 3))\n\n target_image_size = (512, 512)\n batch_size = 32\n transfer_learning_epochs = 100\n fine_tuning_epochs = 20\n fine_tuning_layers_to_train = 10\n\n # The following are directories used for reading/saving data\n RES_PATH = \"..{0}..{0}resources{0}\".format(os.path.sep)\n IMG_PATH = \"..{0}..{0}images{0}\".format(os.path.sep)\n BOTTLENECK_PATH = \"..{0}..{0}bottleneck{0}\".format(os.path.sep)\n SAVE_PATH = \"..{0}..{0}saved_models{0}\".format(os.path.sep)\n TRAIN_PATH = os.path.join(IMG_PATH, \"train\")\n VAL_PATH = os.path.join(IMG_PATH, \"validation\")\n TEST_PATH = os.path.join(IMG_PATH, \"test\")\n\n model_name = \"convx_model\" # The directory all data will be saved in will be named whatever this value is.\n models_save_directory = os.path.join(SAVE_PATH, model_name)\n build_dir_path(models_save_directory) # build the directory structure we need for saving results\n\n def count_files(root_dir):\n return sum([len(files) for r, d, files in os.walk(root_dir)])\n\n def get_iterations_per_epoch(total_images, batch_size):\n return np.ceil(total_images / batch_size)\n\n healthy_train_images = count_files(os.path.join(TRAIN_PATH, \"healthy\"))\n unhealthy_train_images = count_files(os.path.join(TRAIN_PATH, \"unhealthy\"))\n healthy_validation_images = count_files(os.path.join(VAL_PATH, \"healthy\"))\n unhealthy_validation_images = count_files(os.path.join(VAL_PATH, \"unhealthy\"))\n\n num_training_steps = get_iterations_per_epoch((healthy_train_images + unhealthy_train_images), batch_size)\n num_validation_steps = get_iterations_per_epoch((healthy_validation_images + unhealthy_validation_images), batch_size)\n\n data_generator = ImageDataGenerator(\n rescale=1. / 255,\n horizontal_flip=True,\n vertical_flip=True,\n rotation_range=90,\n width_shift_range=20,\n height_shift_range=20\n )\n\n bottleneck_file_path = os.path.join(BOTTLENECK_PATH, model_name)\n train_bottleneck_file = os.path.join(bottleneck_file_path, \"train.npy\")\n validation_bottleneck_file = os.path.join(bottleneck_file_path, \"validation.npy\")\n\n # BOTTLENECK EXTRACTION -------------------------------------------------------------------------------------------\n if not os.path.exists(bottleneck_file_path):\n train_generator = data_generator.flow_from_directory(\n TRAIN_PATH,\n target_size=target_image_size,\n batch_size=batch_size,\n class_mode=None,\n shuffle=False\n )\n\n bottleneck_features_train = base_model.predict_generator(train_generator, num_training_steps)\n build_dir_path(bottleneck_file_path)\n np.save(open(train_bottleneck_file, 'wb'), bottleneck_features_train)\n\n validation_path_generator = data_generator.flow_from_directory(\n VAL_PATH,\n target_size=target_image_size,\n batch_size=batch_size,\n class_mode='binary',\n shuffle=False\n )\n\n bottleneck_features_validation = base_model.predict_generator(validation_path_generator, num_validation_steps)\n np.save(open(validation_bottleneck_file, 'wb'), bottleneck_features_validation)\n\n # TRANSFER LEARNING -----------------------------------------------------------------------------------------------\n def build_fully_connected_top_layer(connecting_shape, dropout=True):\n top_layers = Sequential()\n # top_layers.add(Flatten(input_shape=connecting_shape))\n top_layers.add(GlobalAveragePooling2D(input_shape=connecting_shape))\n top_layers.add(Dense(256, activation='relu'))\n if dropout:\n top_layers.add(Dropout(0.1))\n top_layers.add(Dense(2, activation='softmax'))\n return top_layers\n\n # load training data\n train_data = np.load(open(train_bottleneck_file, 'rb'))\n train_labels = to_categorical(np.array(([0] * healthy_train_images) + ([1] * unhealthy_train_images)),\n num_classes=2)\n\n # load validation data\n validation_data = np.load(open(validation_bottleneck_file, 'rb'))\n validation_labels = to_categorical(np.array([0] * healthy_validation_images + [1] * unhealthy_validation_images),\n num_classes=2)\n\n top_layer = build_fully_connected_top_layer(train_data.shape[1:])\n\n def compile_model(model):\n model.compile(loss='hinge',\n optimizer='sgd',\n metrics=['accuracy'])\n\n compile_model(top_layer)\n\n top_layer.fit(train_data, train_labels,\n epochs=transfer_learning_epochs,\n batch_size=batch_size,\n validation_data=(validation_data, validation_labels),\n verbose=1)\n\n top_layers_weights_path = os.path.join(models_save_directory, \"transfer_learning_weights.h5\")\n top_layer.save_weights(top_layers_weights_path)\n\n # FINE TUNING -----------------------------------------------------------------------------------------------------\n top_layer = build_fully_connected_top_layer(base_model.output_shape[1:])\n top_layer.load_weights(top_layers_weights_path)\n\n convx_model = Model(inputs=base_model.input, outputs=top_layer(base_model.output))\n\n for layer in convx_model.layers[:len(convx_model.layers) - fine_tuning_layers_to_train]:\n layer.trainable = False\n\n compile_model(convx_model)\n\n train_generator = data_generator.flow_from_directory(\n TRAIN_PATH,\n target_size=target_image_size,\n batch_size=batch_size,\n class_mode='categorical')\n\n validation_generator = data_generator.flow_from_directory(\n VAL_PATH,\n target_size=target_image_size,\n batch_size=batch_size,\n class_mode='categorical')\n\n convx_model.fit_generator(\n train_generator,\n steps_per_epoch=num_training_steps,\n epochs=fine_tuning_epochs,\n validation_data=validation_generator,\n validation_steps=num_validation_steps,\n verbose=1\n )\n\n with open(os.path.join(models_save_directory, \"best_model.json\".format(model_name)), \"w\") as json_file:\n json_file.write(convx_model.to_json())\n\n # MODEL EVALUATION ------------------------------------------------------------------------------------------------\n with open(os.path.join(models_save_directory, \"best_model.json\"), 'r') as model_file:\n convx_model = model_from_json(model_file.read())\n compile_model(convx_model)\n\n healthy_test_images = count_files(os.path.join(TEST_PATH, \"healthy\"))\n unhealthy_test_images = count_files(os.path.join(TEST_PATH, \"unhealthy\"))\n test_iteration_count = get_iterations_per_epoch((healthy_test_images + unhealthy_test_images), batch_size)\n\n # load test data\n test_labels = np.array(([0] * healthy_test_images) + ([1] * unhealthy_test_images))\n formatted_test_labels = to_categorical(test_labels, num_classes=2)\n\n test_generator = data_generator.flow_from_directory(\n TEST_PATH,\n target_size=target_image_size,\n batch_size=batch_size,\n class_mode='binary',\n shuffle=False,\n )\n\n raw_predictions = convx_model.predict_generator(test_generator, test_iteration_count, verbose=1)\n predicted_labels = np.argmax(raw_predictions, axis=1)\n\n accuracy = accuracy_score(test_labels, predicted_labels)\n print(\"Accuracy: {}\".format(accuracy))\n\n f3_score = fbeta_score(test_labels, predicted_labels, 3)\n print(\"F3 Score: {}\".format(f3_score))\n\n conf_matrix = confusion_matrix(test_labels, predicted_labels)\n print(\"Confusion Matrix: \\n{}\".format(conf_matrix))\n"
]
| [
[
"sklearn.metrics.fbeta_score",
"sklearn.metrics.confusion_matrix",
"sklearn.metrics.accuracy_score"
]
]
|
Willqie/pytorch | [
"5bc28c897e5d00c0a839de9692b9b54de5294aff"
]
| [
"torch/utils/cpp_extension.py"
]
| [
"import copy\nimport glob\nimport importlib\nimport os\nimport re\nimport shlex\nimport setuptools\nimport subprocess\nimport sys\nimport sysconfig\nimport warnings\nimport collections\n\nimport torch\nimport torch._appdirs\nfrom .file_baton import FileBaton\nfrom ._cpp_extension_versioner import ExtensionVersioner\nfrom .hipify import hipify_python\nfrom .hipify.hipify_python import get_hip_file_path, GeneratedFileCleaner\nfrom typing import List, Optional, Union\n\nfrom setuptools.command.build_ext import build_ext\nfrom pkg_resources import packaging, parse_version # type: ignore[attr-defined]\n\nIS_WINDOWS = sys.platform == 'win32'\nLIB_EXT = '.pyd' if IS_WINDOWS else '.so'\nEXEC_EXT = '.exe' if IS_WINDOWS else ''\nCLIB_PREFIX = '' if IS_WINDOWS else 'lib'\nCLIB_EXT = '.dll' if IS_WINDOWS else '.so'\nSHARED_FLAG = '/DLL' if IS_WINDOWS else '-shared'\n\n_HERE = os.path.abspath(__file__)\n_TORCH_PATH = os.path.dirname(os.path.dirname(_HERE))\nTORCH_LIB_PATH = os.path.join(_TORCH_PATH, 'lib')\n\n\nBUILD_SPLIT_CUDA = os.getenv('BUILD_SPLIT_CUDA') or (os.path.exists(os.path.join(\n TORCH_LIB_PATH, f'{CLIB_PREFIX}torch_cuda_cu{CLIB_EXT}')) and os.path.exists(os.path.join(TORCH_LIB_PATH, f'{CLIB_PREFIX}torch_cuda_cpp{CLIB_EXT}')))\n\n# Taken directly from python stdlib < 3.9\n# See https://github.com/pytorch/pytorch/issues/48617\ndef _nt_quote_args(args: Optional[List[str]]) -> List[str]:\n \"\"\"Quote command-line arguments for DOS/Windows conventions.\n\n Just wraps every argument which contains blanks in double quotes, and\n returns a new argument list.\n \"\"\"\n # Cover None-type\n if not args:\n return []\n return [f'\"{arg}\"' if ' ' in arg else arg for arg in args]\n\ndef _find_cuda_home() -> Optional[str]:\n r'''Finds the CUDA install path.'''\n # Guess #1\n cuda_home = os.environ.get('CUDA_HOME') or os.environ.get('CUDA_PATH')\n if cuda_home is None:\n # Guess #2\n try:\n which = 'where' if IS_WINDOWS else 'which'\n with open(os.devnull, 'w') as devnull:\n nvcc = subprocess.check_output([which, 'nvcc'],\n stderr=devnull).decode().rstrip('\\r\\n')\n cuda_home = os.path.dirname(os.path.dirname(nvcc))\n except Exception:\n # Guess #3\n if IS_WINDOWS:\n cuda_homes = glob.glob(\n 'C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v*.*')\n if len(cuda_homes) == 0:\n cuda_home = ''\n else:\n cuda_home = cuda_homes[0]\n else:\n cuda_home = '/usr/local/cuda'\n if not os.path.exists(cuda_home):\n cuda_home = None\n if cuda_home and not torch.cuda.is_available():\n print(f\"No CUDA runtime is found, using CUDA_HOME='{cuda_home}'\")\n return cuda_home\n\ndef _find_rocm_home() -> Optional[str]:\n r'''Finds the ROCm install path.'''\n # Guess #1\n rocm_home = os.environ.get('ROCM_HOME') or os.environ.get('ROCM_PATH')\n if rocm_home is None:\n # Guess #2\n try:\n pipe_hipcc = subprocess.Popen(\n [\"which hipcc | xargs readlink -f\"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\n hipcc, _ = pipe_hipcc.communicate()\n # this will be either <ROCM_HOME>/hip/bin/hipcc or <ROCM_HOME>/bin/hipcc\n rocm_home = os.path.dirname(os.path.dirname(hipcc.decode().rstrip('\\r\\n')))\n if os.path.basename(rocm_home) == 'hip':\n rocm_home = os.path.dirname(rocm_home)\n except Exception:\n # Guess #3\n rocm_home = '/opt/rocm'\n if not os.path.exists(rocm_home):\n rocm_home = None\n if rocm_home and torch.version.hip is None:\n print(f\"No ROCm runtime is found, using ROCM_HOME='{rocm_home}'\")\n return rocm_home\n\n\ndef _join_rocm_home(*paths) -> str:\n r'''\n Joins paths with ROCM_HOME, or raises an error if it ROCM_HOME is not set.\n\n This is basically a lazy way of raising an error for missing $ROCM_HOME\n only once we need to get any ROCm-specific path.\n '''\n if ROCM_HOME is None:\n raise EnvironmentError('ROCM_HOME environment variable is not set. '\n 'Please set it to your ROCm install root.')\n elif IS_WINDOWS:\n raise EnvironmentError('Building PyTorch extensions using '\n 'ROCm and Windows is not supported.')\n return os.path.join(ROCM_HOME, *paths)\n\n\nMINIMUM_GCC_VERSION = (5, 0, 0)\nMINIMUM_MSVC_VERSION = (19, 0, 24215)\nABI_INCOMPATIBILITY_WARNING = '''\n\n !! WARNING !!\n\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\nYour compiler ({}) may be ABI-incompatible with PyTorch!\nPlease use a compiler that is ABI-compatible with GCC 5.0 and above.\nSee https://gcc.gnu.org/onlinedocs/libstdc++/manual/abi.html.\n\nSee https://gist.github.com/goldsborough/d466f43e8ffc948ff92de7486c5216d6\nfor instructions on how to install GCC 5 or higher.\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n !! WARNING !!\n'''\nWRONG_COMPILER_WARNING = '''\n\n !! WARNING !!\n\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\nYour compiler ({user_compiler}) is not compatible with the compiler Pytorch was\nbuilt with for this platform, which is {pytorch_compiler} on {platform}. Please\nuse {pytorch_compiler} to to compile your extension. Alternatively, you may\ncompile PyTorch from source using {user_compiler}, and then you can also use\n{user_compiler} to compile your extension.\n\nSee https://github.com/pytorch/pytorch/blob/master/CONTRIBUTING.md for help\nwith compiling PyTorch from source.\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n !! WARNING !!\n'''\nCUDA_MISMATCH_MESSAGE = '''\nThe detected CUDA version ({0}) mismatches the version that was used to compile\nPyTorch ({1}). Please make sure to use the same CUDA versions.\n'''\nCUDA_MISMATCH_WARN = \"The detected CUDA version ({0}) has a minor version mismatch with the version that was used to compile PyTorch ({1}). Most likely this shouldn't be a problem.\"\nCUDA_NOT_FOUND_MESSAGE = '''\nCUDA was not found on the system, please set the CUDA_HOME or the CUDA_PATH\nenvironment variable or add NVCC to your system PATH. The extension compilation will fail.\n'''\nROCM_HOME = _find_rocm_home()\nMIOPEN_HOME = _join_rocm_home('miopen') if ROCM_HOME else None\nIS_HIP_EXTENSION = True if ((ROCM_HOME is not None) and (torch.version.hip is not None)) else False\nROCM_VERSION = None\nif torch.version.hip is not None:\n ROCM_VERSION = tuple(int(v) for v in torch.version.hip.split('.')[:2])\n\nCUDA_HOME = _find_cuda_home()\nCUDNN_HOME = os.environ.get('CUDNN_HOME') or os.environ.get('CUDNN_PATH')\n# PyTorch releases have the version pattern major.minor.patch, whereas when\n# PyTorch is built from source, we append the git commit hash, which gives\n# it the below pattern.\nBUILT_FROM_SOURCE_VERSION_PATTERN = re.compile(r'\\d+\\.\\d+\\.\\d+\\w+\\+\\w+')\n\nCOMMON_MSVC_FLAGS = ['/MD', '/wd4819', '/wd4251', '/wd4244', '/wd4267', '/wd4275', '/wd4018', '/wd4190', '/EHsc']\n\nMSVC_IGNORE_CUDAFE_WARNINGS = [\n 'base_class_has_different_dll_interface',\n 'field_without_dll_interface',\n 'dll_interface_conflict_none_assumed',\n 'dll_interface_conflict_dllexport_assumed'\n]\n\nCOMMON_NVCC_FLAGS = [\n '-D__CUDA_NO_HALF_OPERATORS__',\n '-D__CUDA_NO_HALF_CONVERSIONS__',\n '-D__CUDA_NO_BFLOAT16_CONVERSIONS__',\n '-D__CUDA_NO_HALF2_OPERATORS__',\n '--expt-relaxed-constexpr'\n]\n\nCOMMON_HIP_FLAGS = [\n '-fPIC',\n '-D__HIP_PLATFORM_HCC__=1',\n]\n\nCOMMON_HIPCC_FLAGS = [\n '-DCUDA_HAS_FP16=1',\n '-D__HIP_NO_HALF_OPERATORS__=1',\n '-D__HIP_NO_HALF_CONVERSIONS__=1',\n]\n\nJIT_EXTENSION_VERSIONER = ExtensionVersioner()\n\nPLAT_TO_VCVARS = {\n 'win32' : 'x86',\n 'win-amd64' : 'x86_amd64',\n}\n\n\ndef _is_binary_build() -> bool:\n return not BUILT_FROM_SOURCE_VERSION_PATTERN.match(torch.version.__version__)\n\n\ndef _accepted_compilers_for_platform() -> List[str]:\n # gnu-c++ and gnu-cc are the conda gcc compilers\n return ['clang++', 'clang'] if sys.platform.startswith('darwin') else ['g++', 'gcc', 'gnu-c++', 'gnu-cc']\n\n\ndef get_default_build_root() -> str:\n r'''\n Returns the path to the root folder under which extensions will built.\n\n For each extension module built, there will be one folder underneath the\n folder returned by this function. For example, if ``p`` is the path\n returned by this function and ``ext`` the name of an extension, the build\n folder for the extension will be ``p/ext``.\n\n This directory is **user-specific** so that multiple users on the same\n machine won't meet permission issues.\n '''\n return os.path.realpath(torch._appdirs.user_cache_dir(appname='torch_extensions'))\n\n\ndef check_compiler_ok_for_platform(compiler: str) -> bool:\n r'''\n Verifies that the compiler is the expected one for the current platform.\n\n Args:\n compiler (str): The compiler executable to check.\n\n Returns:\n True if the compiler is gcc/g++ on Linux or clang/clang++ on macOS,\n and always True for Windows.\n '''\n if IS_WINDOWS:\n return True\n which = subprocess.check_output(['which', compiler], stderr=subprocess.STDOUT)\n # Use os.path.realpath to resolve any symlinks, in particular from 'c++' to e.g. 'g++'.\n compiler_path = os.path.realpath(which.decode().strip())\n # Check the compiler name\n if any(name in compiler_path for name in _accepted_compilers_for_platform()):\n return True\n # If ccache is used the compiler path is /usr/bin/ccache. Check by -v flag.\n version_string = subprocess.check_output([compiler, '-v'], stderr=subprocess.STDOUT).decode()\n if sys.platform.startswith('linux'):\n # Check for 'gcc' or 'g++'\n pattern = re.compile(\"^COLLECT_GCC=(.*)$\", re.MULTILINE)\n results = re.findall(pattern, version_string)\n if len(results) != 1:\n return False\n compiler_path = os.path.realpath(results[0].strip())\n return any(name in compiler_path for name in _accepted_compilers_for_platform())\n if sys.platform.startswith('darwin'):\n # Check for 'clang' or 'clang++'\n return version_string.startswith(\"Apple clang\")\n return False\n\n\ndef check_compiler_abi_compatibility(compiler) -> bool:\n r'''\n Verifies that the given compiler is ABI-compatible with PyTorch.\n\n Args:\n compiler (str): The compiler executable name to check (e.g. ``g++``).\n Must be executable in a shell process.\n\n Returns:\n False if the compiler is (likely) ABI-incompatible with PyTorch,\n else True.\n '''\n if not _is_binary_build():\n return True\n if os.environ.get('TORCH_DONT_CHECK_COMPILER_ABI') in ['ON', '1', 'YES', 'TRUE', 'Y']:\n return True\n\n # First check if the compiler is one of the expected ones for the particular platform.\n if not check_compiler_ok_for_platform(compiler):\n warnings.warn(WRONG_COMPILER_WARNING.format(\n user_compiler=compiler,\n pytorch_compiler=_accepted_compilers_for_platform()[0],\n platform=sys.platform))\n return False\n\n if sys.platform.startswith('darwin'):\n # There is no particular minimum version we need for clang, so we're good here.\n return True\n try:\n if sys.platform.startswith('linux'):\n minimum_required_version = MINIMUM_GCC_VERSION\n versionstr = subprocess.check_output([compiler, '-dumpfullversion', '-dumpversion'])\n version = versionstr.decode().strip().split('.')\n else:\n minimum_required_version = MINIMUM_MSVC_VERSION\n compiler_info = subprocess.check_output(compiler, stderr=subprocess.STDOUT)\n match = re.search(r'(\\d+)\\.(\\d+)\\.(\\d+)', compiler_info.decode().strip())\n version = (0, 0, 0) if match is None else match.groups()\n except Exception:\n _, error, _ = sys.exc_info()\n warnings.warn(f'Error checking compiler version for {compiler}: {error}')\n return False\n\n if tuple(map(int, version)) >= minimum_required_version:\n return True\n\n compiler = f'{compiler} {\".\".join(version)}'\n warnings.warn(ABI_INCOMPATIBILITY_WARNING.format(compiler))\n\n return False\n\n\n# See below for why we inherit BuildExtension from object.\n# https://stackoverflow.com/questions/1713038/super-fails-with-error-typeerror-argument-1-must-be-type-not-classobj-when\n\n\nclass BuildExtension(build_ext, object):\n r'''\n A custom :mod:`setuptools` build extension .\n\n This :class:`setuptools.build_ext` subclass takes care of passing the\n minimum required compiler flags (e.g. ``-std=c++14``) as well as mixed\n C++/CUDA compilation (and support for CUDA files in general).\n\n When using :class:`BuildExtension`, it is allowed to supply a dictionary\n for ``extra_compile_args`` (rather than the usual list) that maps from\n languages (``cxx`` or ``nvcc``) to a list of additional compiler flags to\n supply to the compiler. This makes it possible to supply different flags to\n the C++ and CUDA compiler during mixed compilation.\n\n ``use_ninja`` (bool): If ``use_ninja`` is ``True`` (default), then we\n attempt to build using the Ninja backend. Ninja greatly speeds up\n compilation compared to the standard ``setuptools.build_ext``.\n Fallbacks to the standard distutils backend if Ninja is not available.\n\n .. note::\n By default, the Ninja backend uses #CPUS + 2 workers to build the\n extension. This may use up too many resources on some systems. One\n can control the number of workers by setting the `MAX_JOBS` environment\n variable to a non-negative number.\n '''\n\n @classmethod\n def with_options(cls, **options):\n r'''\n Returns a subclass with alternative constructor that extends any original keyword\n arguments to the original constructor with the given options.\n '''\n class cls_with_options(cls): # type: ignore[misc, valid-type]\n def __init__(self, *args, **kwargs):\n kwargs.update(options)\n super().__init__(*args, **kwargs)\n\n return cls_with_options\n\n def __init__(self, *args, **kwargs) -> None:\n super(BuildExtension, self).__init__(*args, **kwargs)\n self.no_python_abi_suffix = kwargs.get(\"no_python_abi_suffix\", False)\n\n self.use_ninja = kwargs.get('use_ninja', True)\n if self.use_ninja:\n # Test if we can use ninja. Fallback otherwise.\n msg = ('Attempted to use ninja as the BuildExtension backend but '\n '{}. Falling back to using the slow distutils backend.')\n if not is_ninja_available():\n warnings.warn(msg.format('we could not find ninja.'))\n self.use_ninja = False\n\n def finalize_options(self) -> None:\n super().finalize_options()\n if self.use_ninja:\n self.force = True\n\n def build_extensions(self) -> None:\n self._check_abi()\n\n cuda_ext = False\n extension_iter = iter(self.extensions)\n extension = next(extension_iter, None)\n while not cuda_ext and extension:\n for source in extension.sources:\n _, ext = os.path.splitext(source)\n if ext == '.cu':\n cuda_ext = True\n break\n extension = next(extension_iter, None)\n\n if cuda_ext and not IS_HIP_EXTENSION:\n self._check_cuda_version()\n\n for extension in self.extensions:\n # Ensure at least an empty list of flags for 'cxx' and 'nvcc' when\n # extra_compile_args is a dict. Otherwise, default torch flags do\n # not get passed. Necessary when only one of 'cxx' and 'nvcc' is\n # passed to extra_compile_args in CUDAExtension, i.e.\n # CUDAExtension(..., extra_compile_args={'cxx': [...]})\n # or\n # CUDAExtension(..., extra_compile_args={'nvcc': [...]})\n if isinstance(extension.extra_compile_args, dict):\n for ext in ['cxx', 'nvcc']:\n if ext not in extension.extra_compile_args:\n extension.extra_compile_args[ext] = []\n\n self._add_compile_flag(extension, '-DTORCH_API_INCLUDE_EXTENSION_H')\n # See note [Pybind11 ABI constants]\n for name in [\"COMPILER_TYPE\", \"STDLIB\", \"BUILD_ABI\"]:\n val = getattr(torch._C, f\"_PYBIND11_{name}\")\n if val is not None and not IS_WINDOWS:\n self._add_compile_flag(extension, f'-DPYBIND11_{name}=\"{val}\"')\n self._define_torch_extension_name(extension)\n self._add_gnu_cpp_abi_flag(extension)\n\n # Register .cu, .cuh and .hip as valid source extensions.\n self.compiler.src_extensions += ['.cu', '.cuh', '.hip']\n # Save the original _compile method for later.\n if self.compiler.compiler_type == 'msvc':\n self.compiler._cpp_extensions += ['.cu', '.cuh']\n original_compile = self.compiler.compile\n original_spawn = self.compiler.spawn\n else:\n original_compile = self.compiler._compile\n\n def append_std14_if_no_std_present(cflags) -> None:\n # NVCC does not allow multiple -std to be passed, so we avoid\n # overriding the option if the user explicitly passed it.\n cpp_format_prefix = '/{}:' if self.compiler.compiler_type == 'msvc' else '-{}='\n cpp_flag_prefix = cpp_format_prefix.format('std')\n cpp_flag = cpp_flag_prefix + 'c++14'\n if not any(flag.startswith(cpp_flag_prefix) for flag in cflags):\n cflags.append(cpp_flag)\n\n def unix_cuda_flags(cflags):\n cflags = (COMMON_NVCC_FLAGS +\n ['--compiler-options', \"'-fPIC'\"] +\n cflags + _get_cuda_arch_flags(cflags))\n\n # NVCC does not allow multiple -ccbin/--compiler-bindir to be passed, so we avoid\n # overriding the option if the user explicitly passed it.\n _ccbin = os.getenv(\"CC\")\n if (\n _ccbin is not None\n and not any([flag.startswith('-ccbin') or flag.startswith('--compiler-bindir') for flag in cflags])\n ):\n cflags.extend(['-ccbin', _ccbin])\n\n return cflags\n\n def convert_to_absolute_paths_inplace(paths):\n # Helper function. See Note [Absolute include_dirs]\n if paths is not None:\n for i in range(len(paths)):\n if not os.path.isabs(paths[i]):\n paths[i] = os.path.abspath(paths[i])\n\n def unix_wrap_single_compile(obj, src, ext, cc_args, extra_postargs, pp_opts) -> None:\n # Copy before we make any modifications.\n cflags = copy.deepcopy(extra_postargs)\n try:\n original_compiler = self.compiler.compiler_so\n if _is_cuda_file(src):\n nvcc = [_join_rocm_home('bin', 'hipcc') if IS_HIP_EXTENSION else _join_cuda_home('bin', 'nvcc')]\n self.compiler.set_executable('compiler_so', nvcc)\n if isinstance(cflags, dict):\n cflags = cflags['nvcc']\n if IS_HIP_EXTENSION:\n cflags = COMMON_HIPCC_FLAGS + cflags + _get_rocm_arch_flags(cflags)\n else:\n cflags = unix_cuda_flags(cflags)\n elif isinstance(cflags, dict):\n cflags = cflags['cxx']\n if IS_HIP_EXTENSION:\n cflags = COMMON_HIP_FLAGS + cflags\n append_std14_if_no_std_present(cflags)\n\n original_compile(obj, src, ext, cc_args, cflags, pp_opts)\n finally:\n # Put the original compiler back in place.\n self.compiler.set_executable('compiler_so', original_compiler)\n\n def unix_wrap_ninja_compile(sources,\n output_dir=None,\n macros=None,\n include_dirs=None,\n debug=0,\n extra_preargs=None,\n extra_postargs=None,\n depends=None):\n r\"\"\"Compiles sources by outputting a ninja file and running it.\"\"\"\n # NB: I copied some lines from self.compiler (which is an instance\n # of distutils.UnixCCompiler). See the following link.\n # https://github.com/python/cpython/blob/f03a8f8d5001963ad5b5b28dbd95497e9cc15596/Lib/distutils/ccompiler.py#L564-L567\n # This can be fragile, but a lot of other repos also do this\n # (see https://github.com/search?q=_setup_compile&type=Code)\n # so it is probably OK; we'll also get CI signal if/when\n # we update our python version (which is when distutils can be\n # upgraded)\n\n # Use absolute path for output_dir so that the object file paths\n # (`objects`) get generated with absolute paths.\n output_dir = os.path.abspath(output_dir)\n\n # See Note [Absolute include_dirs]\n convert_to_absolute_paths_inplace(self.compiler.include_dirs)\n\n _, objects, extra_postargs, pp_opts, _ = \\\n self.compiler._setup_compile(output_dir, macros,\n include_dirs, sources,\n depends, extra_postargs)\n common_cflags = self.compiler._get_cc_args(pp_opts, debug, extra_preargs)\n extra_cc_cflags = self.compiler.compiler_so[1:]\n with_cuda = any(map(_is_cuda_file, sources))\n\n # extra_postargs can be either:\n # - a dict mapping cxx/nvcc to extra flags\n # - a list of extra flags.\n if isinstance(extra_postargs, dict):\n post_cflags = extra_postargs['cxx']\n else:\n post_cflags = list(extra_postargs)\n if IS_HIP_EXTENSION:\n post_cflags = COMMON_HIP_FLAGS + post_cflags\n append_std14_if_no_std_present(post_cflags)\n\n cuda_post_cflags = None\n cuda_cflags = None\n if with_cuda:\n cuda_cflags = common_cflags\n if isinstance(extra_postargs, dict):\n cuda_post_cflags = extra_postargs['nvcc']\n else:\n cuda_post_cflags = list(extra_postargs)\n if IS_HIP_EXTENSION:\n cuda_post_cflags = cuda_post_cflags + _get_rocm_arch_flags(cuda_post_cflags)\n cuda_post_cflags = COMMON_HIP_FLAGS + COMMON_HIPCC_FLAGS + cuda_post_cflags\n else:\n cuda_post_cflags = unix_cuda_flags(cuda_post_cflags)\n append_std14_if_no_std_present(cuda_post_cflags)\n cuda_cflags = [shlex.quote(f) for f in cuda_cflags]\n cuda_post_cflags = [shlex.quote(f) for f in cuda_post_cflags]\n\n _write_ninja_file_and_compile_objects(\n sources=sources,\n objects=objects,\n cflags=[shlex.quote(f) for f in extra_cc_cflags + common_cflags],\n post_cflags=[shlex.quote(f) for f in post_cflags],\n cuda_cflags=cuda_cflags,\n cuda_post_cflags=cuda_post_cflags,\n build_directory=output_dir,\n verbose=True,\n with_cuda=with_cuda)\n\n # Return *all* object filenames, not just the ones we just built.\n return objects\n\n def win_cuda_flags(cflags):\n return (COMMON_NVCC_FLAGS +\n cflags + _get_cuda_arch_flags(cflags))\n\n def win_wrap_single_compile(sources,\n output_dir=None,\n macros=None,\n include_dirs=None,\n debug=0,\n extra_preargs=None,\n extra_postargs=None,\n depends=None):\n\n self.cflags = copy.deepcopy(extra_postargs)\n extra_postargs = None\n\n def spawn(cmd):\n # Using regex to match src, obj and include files\n src_regex = re.compile('/T(p|c)(.*)')\n src_list = [\n m.group(2) for m in (src_regex.match(elem) for elem in cmd)\n if m\n ]\n\n obj_regex = re.compile('/Fo(.*)')\n obj_list = [\n m.group(1) for m in (obj_regex.match(elem) for elem in cmd)\n if m\n ]\n\n include_regex = re.compile(r'((\\-|\\/)I.*)')\n include_list = [\n m.group(1)\n for m in (include_regex.match(elem) for elem in cmd) if m\n ]\n\n if len(src_list) >= 1 and len(obj_list) >= 1:\n src = src_list[0]\n obj = obj_list[0]\n if _is_cuda_file(src):\n nvcc = _join_cuda_home('bin', 'nvcc')\n if isinstance(self.cflags, dict):\n cflags = self.cflags['nvcc']\n elif isinstance(self.cflags, list):\n cflags = self.cflags\n else:\n cflags = []\n\n cflags = win_cuda_flags(cflags) + ['--use-local-env']\n for flag in COMMON_MSVC_FLAGS:\n cflags = ['-Xcompiler', flag] + cflags\n for ignore_warning in MSVC_IGNORE_CUDAFE_WARNINGS:\n cflags = ['-Xcudafe', '--diag_suppress=' + ignore_warning] + cflags\n cmd = [nvcc, '-c', src, '-o', obj] + include_list + cflags\n elif isinstance(self.cflags, dict):\n cflags = COMMON_MSVC_FLAGS + self.cflags['cxx']\n cmd += cflags\n elif isinstance(self.cflags, list):\n cflags = COMMON_MSVC_FLAGS + self.cflags\n cmd += cflags\n\n return original_spawn(cmd)\n\n try:\n self.compiler.spawn = spawn\n return original_compile(sources, output_dir, macros,\n include_dirs, debug, extra_preargs,\n extra_postargs, depends)\n finally:\n self.compiler.spawn = original_spawn\n\n def win_wrap_ninja_compile(sources,\n output_dir=None,\n macros=None,\n include_dirs=None,\n debug=0,\n extra_preargs=None,\n extra_postargs=None,\n depends=None):\n\n if not self.compiler.initialized:\n self.compiler.initialize()\n output_dir = os.path.abspath(output_dir)\n\n # Note [Absolute include_dirs]\n # Convert relative path in self.compiler.include_dirs to absolute path if any,\n # For ninja build, the build location is not local, the build happens\n # in a in script created build folder, relative path lost their correctness.\n # To be consistent with jit extension, we allow user to enter relative include_dirs\n # in setuptools.setup, and we convert the relative path to absolute path here\n convert_to_absolute_paths_inplace(self.compiler.include_dirs)\n\n _, objects, extra_postargs, pp_opts, _ = \\\n self.compiler._setup_compile(output_dir, macros,\n include_dirs, sources,\n depends, extra_postargs)\n common_cflags = extra_preargs or []\n cflags = []\n if debug:\n cflags.extend(self.compiler.compile_options_debug)\n else:\n cflags.extend(self.compiler.compile_options)\n common_cflags.extend(COMMON_MSVC_FLAGS)\n cflags = cflags + common_cflags + pp_opts\n with_cuda = any(map(_is_cuda_file, sources))\n\n # extra_postargs can be either:\n # - a dict mapping cxx/nvcc to extra flags\n # - a list of extra flags.\n if isinstance(extra_postargs, dict):\n post_cflags = extra_postargs['cxx']\n else:\n post_cflags = list(extra_postargs)\n append_std14_if_no_std_present(post_cflags)\n\n cuda_post_cflags = None\n cuda_cflags = None\n if with_cuda:\n cuda_cflags = ['--use-local-env']\n for common_cflag in common_cflags:\n cuda_cflags.append('-Xcompiler')\n cuda_cflags.append(common_cflag)\n for ignore_warning in MSVC_IGNORE_CUDAFE_WARNINGS:\n cuda_cflags.append('-Xcudafe')\n cuda_cflags.append('--diag_suppress=' + ignore_warning)\n cuda_cflags.extend(pp_opts)\n if isinstance(extra_postargs, dict):\n cuda_post_cflags = extra_postargs['nvcc']\n else:\n cuda_post_cflags = list(extra_postargs)\n cuda_post_cflags = win_cuda_flags(cuda_post_cflags)\n\n cflags = _nt_quote_args(cflags)\n post_cflags = _nt_quote_args(post_cflags)\n if with_cuda:\n cuda_cflags = _nt_quote_args(cuda_cflags)\n cuda_post_cflags = _nt_quote_args(cuda_post_cflags)\n\n _write_ninja_file_and_compile_objects(\n sources=sources,\n objects=objects,\n cflags=cflags,\n post_cflags=post_cflags,\n cuda_cflags=cuda_cflags,\n cuda_post_cflags=cuda_post_cflags,\n build_directory=output_dir,\n verbose=True,\n with_cuda=with_cuda)\n\n # Return *all* object filenames, not just the ones we just built.\n return objects\n\n # Monkey-patch the _compile or compile method.\n # https://github.com/python/cpython/blob/dc0284ee8f7a270b6005467f26d8e5773d76e959/Lib/distutils/ccompiler.py#L511\n if self.compiler.compiler_type == 'msvc':\n if self.use_ninja:\n self.compiler.compile = win_wrap_ninja_compile\n else:\n self.compiler.compile = win_wrap_single_compile\n else:\n if self.use_ninja:\n self.compiler.compile = unix_wrap_ninja_compile\n else:\n self.compiler._compile = unix_wrap_single_compile\n\n build_ext.build_extensions(self)\n\n def get_ext_filename(self, ext_name):\n # Get the original shared library name. For Python 3, this name will be\n # suffixed with \"<SOABI>.so\", where <SOABI> will be something like\n # cpython-37m-x86_64-linux-gnu.\n ext_filename = super(BuildExtension, self).get_ext_filename(ext_name)\n # If `no_python_abi_suffix` is `True`, we omit the Python 3 ABI\n # component. This makes building shared libraries with setuptools that\n # aren't Python modules nicer.\n if self.no_python_abi_suffix:\n # The parts will be e.g. [\"my_extension\", \"cpython-37m-x86_64-linux-gnu\", \"so\"].\n ext_filename_parts = ext_filename.split('.')\n # Omit the second to last element.\n without_abi = ext_filename_parts[:-2] + ext_filename_parts[-1:]\n ext_filename = '.'.join(without_abi)\n return ext_filename\n\n def _check_abi(self):\n # On some platforms, like Windows, compiler_cxx is not available.\n if hasattr(self.compiler, 'compiler_cxx'):\n compiler = self.compiler.compiler_cxx[0]\n elif IS_WINDOWS:\n compiler = os.environ.get('CXX', 'cl')\n else:\n compiler = os.environ.get('CXX', 'c++')\n check_compiler_abi_compatibility(compiler)\n # Warn user if VC env is activated but `DISTUILS_USE_SDK` is not set.\n if IS_WINDOWS and 'VSCMD_ARG_TGT_ARCH' in os.environ and 'DISTUTILS_USE_SDK' not in os.environ:\n msg = ('It seems that the VC environment is activated but DISTUTILS_USE_SDK is not set.'\n 'This may lead to multiple activations of the VC env.'\n 'Please set `DISTUTILS_USE_SDK=1` and try again.')\n raise UserWarning(msg)\n\n def _check_cuda_version(self):\n if CUDA_HOME:\n nvcc = os.path.join(CUDA_HOME, 'bin', 'nvcc')\n cuda_version_str = subprocess.check_output([nvcc, '--version']).strip().decode()\n cuda_version = re.search(r'release (\\d+[.]\\d+)', cuda_version_str)\n if cuda_version is not None:\n cuda_str_version = cuda_version.group(1)\n cuda_ver = parse_version(cuda_str_version)\n torch_cuda_version = parse_version(torch.version.cuda) # type: ignore[arg-type]\n if cuda_ver.major != torch_cuda_version.major: # type: ignore[attr-defined]\n raise RuntimeError(CUDA_MISMATCH_MESSAGE.format(\n cuda_str_version, torch.version.cuda))\n elif cuda_ver.minor != torch_cuda_version.minor: # type: ignore[attr-defined]\n warnings.warn(CUDA_MISMATCH_WARN.format(\n cuda_str_version, torch.version.cuda))\n else:\n raise RuntimeError(CUDA_NOT_FOUND_MESSAGE)\n\n def _add_compile_flag(self, extension, flag):\n extension.extra_compile_args = copy.deepcopy(extension.extra_compile_args)\n if isinstance(extension.extra_compile_args, dict):\n for args in extension.extra_compile_args.values():\n args.append(flag)\n else:\n extension.extra_compile_args.append(flag)\n\n def _define_torch_extension_name(self, extension):\n # pybind11 doesn't support dots in the names\n # so in order to support extensions in the packages\n # like torch._C, we take the last part of the string\n # as the library name\n names = extension.name.split('.')\n name = names[-1]\n define = f'-DTORCH_EXTENSION_NAME={name}'\n self._add_compile_flag(extension, define)\n\n def _add_gnu_cpp_abi_flag(self, extension):\n # use the same CXX ABI as what PyTorch was compiled with\n self._add_compile_flag(extension, '-D_GLIBCXX_USE_CXX11_ABI=' + str(int(torch._C._GLIBCXX_USE_CXX11_ABI)))\n\n\ndef CppExtension(name, sources, *args, **kwargs):\n r'''\n Creates a :class:`setuptools.Extension` for C++.\n\n Convenience method that creates a :class:`setuptools.Extension` with the\n bare minimum (but often sufficient) arguments to build a C++ extension.\n\n All arguments are forwarded to the :class:`setuptools.Extension`\n constructor.\n\n Example:\n >>> from setuptools import setup\n >>> from torch.utils.cpp_extension import BuildExtension, CppExtension\n >>> setup(\n name='extension',\n ext_modules=[\n CppExtension(\n name='extension',\n sources=['extension.cpp'],\n extra_compile_args=['-g']),\n ],\n cmdclass={\n 'build_ext': BuildExtension\n })\n '''\n include_dirs = kwargs.get('include_dirs', [])\n include_dirs += include_paths()\n kwargs['include_dirs'] = include_dirs\n\n library_dirs = kwargs.get('library_dirs', [])\n library_dirs += library_paths()\n kwargs['library_dirs'] = library_dirs\n\n libraries = kwargs.get('libraries', [])\n libraries.append('c10')\n libraries.append('torch')\n libraries.append('torch_cpu')\n libraries.append('torch_python')\n kwargs['libraries'] = libraries\n\n kwargs['language'] = 'c++'\n return setuptools.Extension(name, sources, *args, **kwargs)\n\n\ndef CUDAExtension(name, sources, *args, **kwargs):\n r'''\n Creates a :class:`setuptools.Extension` for CUDA/C++.\n\n Convenience method that creates a :class:`setuptools.Extension` with the\n bare minimum (but often sufficient) arguments to build a CUDA/C++\n extension. This includes the CUDA include path, library path and runtime\n library.\n\n All arguments are forwarded to the :class:`setuptools.Extension`\n constructor.\n\n Example:\n >>> from setuptools import setup\n >>> from torch.utils.cpp_extension import BuildExtension, CUDAExtension\n >>> setup(\n name='cuda_extension',\n ext_modules=[\n CUDAExtension(\n name='cuda_extension',\n sources=['extension.cpp', 'extension_kernel.cu'],\n extra_compile_args={'cxx': ['-g'],\n 'nvcc': ['-O2']})\n ],\n cmdclass={\n 'build_ext': BuildExtension\n })\n\n Compute capabilities:\n\n By default the extension will be compiled to run on all archs of the cards visible during the\n building process of the extension, plus PTX. If down the road a new card is installed the\n extension may need to be recompiled. If a visible card has a compute capability (CC) that's\n newer than the newest version for which your nvcc can build fully-compiled binaries, Pytorch\n will make nvcc fall back to building kernels with the newest version of PTX your nvcc does\n support (see below for details on PTX).\n\n You can override the default behavior using `TORCH_CUDA_ARCH_LIST` to explicitly specify which\n CCs you want the extension to support:\n\n TORCH_CUDA_ARCH_LIST=\"6.1 8.6\" python build_my_extension.py\n TORCH_CUDA_ARCH_LIST=\"5.2 6.0 6.1 7.0 7.5 8.0 8.6+PTX\" python build_my_extension.py\n\n The +PTX option causes extension kernel binaries to include PTX instructions for the specified\n CC. PTX is an intermediate representation that allows kernels to runtime-compile for any CC >=\n the specified CC (for example, 8.6+PTX generates PTX that can runtime-compile for any GPU with\n CC >= 8.6). This improves your binary's forward compatibility. However, relying on older PTX to\n provide forward compat by runtime-compiling for newer CCs can modestly reduce performance on\n those newer CCs. If you know exact CC(s) of the GPUs you want to target, you're always better\n off specifying them individually. For example, if you want your extension to run on 8.0 and 8.6,\n \"8.0+PTX\" would work functionally because it includes PTX that can runtime-compile for 8.6, but\n \"8.0 8.6\" would be better.\n\n Note that while it's possible to include all supported archs, the more archs get included the\n slower the building process will be, as it will build a separate kernel image for each arch.\n\n '''\n library_dirs = kwargs.get('library_dirs', [])\n library_dirs += library_paths(cuda=True)\n kwargs['library_dirs'] = library_dirs\n\n libraries = kwargs.get('libraries', [])\n libraries.append('c10')\n libraries.append('torch')\n libraries.append('torch_cpu')\n libraries.append('torch_python')\n if IS_HIP_EXTENSION:\n assert ROCM_VERSION is not None\n libraries.append('amdhip64' if ROCM_VERSION >= (3, 5) else 'hip_hcc')\n libraries.append('c10_hip')\n libraries.append('torch_hip')\n else:\n libraries.append('cudart')\n libraries.append('c10_cuda')\n if BUILD_SPLIT_CUDA:\n libraries.append('torch_cuda_cu')\n libraries.append('torch_cuda_cpp')\n else:\n libraries.append('torch_cuda')\n kwargs['libraries'] = libraries\n\n include_dirs = kwargs.get('include_dirs', [])\n\n if IS_HIP_EXTENSION:\n build_dir = os.getcwd()\n hipify_result = hipify_python.hipify(\n project_directory=build_dir,\n output_directory=build_dir,\n includes=[os.path.join(os.path.relpath(include_dir, build_dir), '*') for include_dir in include_dirs] if include_dirs else ['*'],\n extra_files=[os.path.abspath(s) for s in sources],\n show_detailed=True,\n is_pytorch_extension=True,\n )\n\n hipified_sources = set()\n for source in sources:\n s_abs = os.path.abspath(source)\n hipified_sources.add(hipify_result[s_abs][\"hipified_path\"] if s_abs in hipify_result else s_abs)\n\n sources = list(hipified_sources)\n\n include_dirs += include_paths(cuda=True)\n kwargs['include_dirs'] = include_dirs\n\n kwargs['language'] = 'c++'\n\n return setuptools.Extension(name, sources, *args, **kwargs)\n\n\ndef include_paths(cuda: bool = False) -> List[str]:\n '''\n Get the include paths required to build a C++ or CUDA extension.\n\n Args:\n cuda: If `True`, includes CUDA-specific include paths.\n\n Returns:\n A list of include path strings.\n '''\n lib_include = os.path.join(_TORCH_PATH, 'include')\n paths = [\n lib_include,\n # Remove this once torch/torch.h is officially no longer supported for C++ extensions.\n os.path.join(lib_include, 'torch', 'csrc', 'api', 'include'),\n # Some internal (old) Torch headers don't properly prefix their includes,\n # so we need to pass -Itorch/lib/include/TH as well.\n os.path.join(lib_include, 'TH'),\n os.path.join(lib_include, 'THC')\n ]\n if cuda and IS_HIP_EXTENSION:\n paths.append(os.path.join(lib_include, 'THH'))\n paths.append(_join_rocm_home('include'))\n if MIOPEN_HOME is not None:\n paths.append(os.path.join(MIOPEN_HOME, 'include'))\n elif cuda:\n cuda_home_include = _join_cuda_home('include')\n # if we have the Debian/Ubuntu packages for cuda, we get /usr as cuda home.\n # but gcc doesn't like having /usr/include passed explicitly\n if cuda_home_include != '/usr/include':\n paths.append(cuda_home_include)\n if CUDNN_HOME is not None:\n paths.append(os.path.join(CUDNN_HOME, 'include'))\n return paths\n\n\ndef library_paths(cuda: bool = False) -> List[str]:\n r'''\n Get the library paths required to build a C++ or CUDA extension.\n\n Args:\n cuda: If `True`, includes CUDA-specific library paths.\n\n Returns:\n A list of library path strings.\n '''\n # We need to link against libtorch.so\n paths = [TORCH_LIB_PATH]\n\n if cuda and IS_HIP_EXTENSION:\n lib_dir = 'lib'\n paths.append(_join_rocm_home(lib_dir))\n elif cuda:\n if IS_WINDOWS:\n lib_dir = 'lib/x64'\n else:\n lib_dir = 'lib64'\n if (not os.path.exists(_join_cuda_home(lib_dir)) and\n os.path.exists(_join_cuda_home('lib'))):\n # 64-bit CUDA may be installed in 'lib' (see e.g. gh-16955)\n # Note that it's also possible both don't exist (see\n # _find_cuda_home) - in that case we stay with 'lib64'.\n lib_dir = 'lib'\n\n paths.append(_join_cuda_home(lib_dir))\n if CUDNN_HOME is not None:\n paths.append(os.path.join(CUDNN_HOME, lib_dir))\n return paths\n\n\ndef load(name,\n sources: Union[str, List[str]],\n extra_cflags=None,\n extra_cuda_cflags=None,\n extra_ldflags=None,\n extra_include_paths=None,\n build_directory=None,\n verbose=False,\n with_cuda: Optional[bool] = None,\n is_python_module=True,\n is_standalone=False,\n keep_intermediates=True):\n r'''\n Loads a PyTorch C++ extension just-in-time (JIT).\n\n To load an extension, a Ninja build file is emitted, which is used to\n compile the given sources into a dynamic library. This library is\n subsequently loaded into the current Python process as a module and\n returned from this function, ready for use.\n\n By default, the directory to which the build file is emitted and the\n resulting library compiled to is ``<tmp>/torch_extensions/<name>``, where\n ``<tmp>`` is the temporary folder on the current platform and ``<name>``\n the name of the extension. This location can be overridden in two ways.\n First, if the ``TORCH_EXTENSIONS_DIR`` environment variable is set, it\n replaces ``<tmp>/torch_extensions`` and all extensions will be compiled\n into subfolders of this directory. Second, if the ``build_directory``\n argument to this function is supplied, it overrides the entire path, i.e.\n the library will be compiled into that folder directly.\n\n To compile the sources, the default system compiler (``c++``) is used,\n which can be overridden by setting the ``CXX`` environment variable. To pass\n additional arguments to the compilation process, ``extra_cflags`` or\n ``extra_ldflags`` can be provided. For example, to compile your extension\n with optimizations, pass ``extra_cflags=['-O3']``. You can also use\n ``extra_cflags`` to pass further include directories.\n\n CUDA support with mixed compilation is provided. Simply pass CUDA source\n files (``.cu`` or ``.cuh``) along with other sources. Such files will be\n detected and compiled with nvcc rather than the C++ compiler. This includes\n passing the CUDA lib64 directory as a library directory, and linking\n ``cudart``. You can pass additional flags to nvcc via\n ``extra_cuda_cflags``, just like with ``extra_cflags`` for C++. Various\n heuristics for finding the CUDA install directory are used, which usually\n work fine. If not, setting the ``CUDA_HOME`` environment variable is the\n safest option.\n\n Args:\n name: The name of the extension to build. This MUST be the same as the\n name of the pybind11 module!\n sources: A list of relative or absolute paths to C++ source files.\n extra_cflags: optional list of compiler flags to forward to the build.\n extra_cuda_cflags: optional list of compiler flags to forward to nvcc\n when building CUDA sources.\n extra_ldflags: optional list of linker flags to forward to the build.\n extra_include_paths: optional list of include directories to forward\n to the build.\n build_directory: optional path to use as build workspace.\n verbose: If ``True``, turns on verbose logging of load steps.\n with_cuda: Determines whether CUDA headers and libraries are added to\n the build. If set to ``None`` (default), this value is\n automatically determined based on the existence of ``.cu`` or\n ``.cuh`` in ``sources``. Set it to `True`` to force CUDA headers\n and libraries to be included.\n is_python_module: If ``True`` (default), imports the produced shared\n library as a Python module. If ``False``, behavior depends on\n ``is_standalone``.\n is_standalone: If ``False`` (default) loads the constructed extension\n into the process as a plain dynamic library. If ``True``, build a\n standalone executable.\n\n Returns:\n If ``is_python_module`` is ``True``:\n Returns the loaded PyTorch extension as a Python module.\n\n If ``is_python_module`` is ``False`` and ``is_standalone`` is ``False``:\n Returns nothing. (The shared library is loaded into the process as\n a side effect.)\n\n If ``is_standalone`` is ``True``.\n Return the path to the executable. (On Windows, TORCH_LIB_PATH is\n added to the PATH environment variable as a side effect.)\n\n Example:\n >>> from torch.utils.cpp_extension import load\n >>> module = load(\n name='extension',\n sources=['extension.cpp', 'extension_kernel.cu'],\n extra_cflags=['-O2'],\n verbose=True)\n '''\n return _jit_compile(\n name,\n [sources] if isinstance(sources, str) else sources,\n extra_cflags,\n extra_cuda_cflags,\n extra_ldflags,\n extra_include_paths,\n build_directory or _get_build_directory(name, verbose),\n verbose,\n with_cuda,\n is_python_module,\n is_standalone,\n keep_intermediates=keep_intermediates)\n\n\ndef load_inline(name,\n cpp_sources,\n cuda_sources=None,\n functions=None,\n extra_cflags=None,\n extra_cuda_cflags=None,\n extra_ldflags=None,\n extra_include_paths=None,\n build_directory=None,\n verbose=False,\n with_cuda=None,\n is_python_module=True,\n with_pytorch_error_handling=True,\n keep_intermediates=True):\n r'''\n Loads a PyTorch C++ extension just-in-time (JIT) from string sources.\n\n This function behaves exactly like :func:`load`, but takes its sources as\n strings rather than filenames. These strings are stored to files in the\n build directory, after which the behavior of :func:`load_inline` is\n identical to :func:`load`.\n\n See `the\n tests <https://github.com/pytorch/pytorch/blob/master/test/test_cpp_extensions_jit.py>`_\n for good examples of using this function.\n\n Sources may omit two required parts of a typical non-inline C++ extension:\n the necessary header includes, as well as the (pybind11) binding code. More\n precisely, strings passed to ``cpp_sources`` are first concatenated into a\n single ``.cpp`` file. This file is then prepended with ``#include\n <torch/extension.h>``.\n\n Furthermore, if the ``functions`` argument is supplied, bindings will be\n automatically generated for each function specified. ``functions`` can\n either be a list of function names, or a dictionary mapping from function\n names to docstrings. If a list is given, the name of each function is used\n as its docstring.\n\n The sources in ``cuda_sources`` are concatenated into a separate ``.cu``\n file and prepended with ``torch/types.h``, ``cuda.h`` and\n ``cuda_runtime.h`` includes. The ``.cpp`` and ``.cu`` files are compiled\n separately, but ultimately linked into a single library. Note that no\n bindings are generated for functions in ``cuda_sources`` per se. To bind\n to a CUDA kernel, you must create a C++ function that calls it, and either\n declare or define this C++ function in one of the ``cpp_sources`` (and\n include its name in ``functions``).\n\n See :func:`load` for a description of arguments omitted below.\n\n Args:\n cpp_sources: A string, or list of strings, containing C++ source code.\n cuda_sources: A string, or list of strings, containing CUDA source code.\n functions: A list of function names for which to generate function\n bindings. If a dictionary is given, it should map function names to\n docstrings (which are otherwise just the function names).\n with_cuda: Determines whether CUDA headers and libraries are added to\n the build. If set to ``None`` (default), this value is\n automatically determined based on whether ``cuda_sources`` is\n provided. Set it to ``True`` to force CUDA headers\n and libraries to be included.\n with_pytorch_error_handling: Determines whether pytorch error and\n warning macros are handled by pytorch instead of pybind. To do\n this, each function ``foo`` is called via an intermediary ``_safe_foo``\n function. This redirection might cause issues in obscure cases\n of cpp. This flag should be set to ``False`` when this redirect\n causes issues.\n\n Example:\n >>> from torch.utils.cpp_extension import load_inline\n >>> source = \\'\\'\\'\n at::Tensor sin_add(at::Tensor x, at::Tensor y) {\n return x.sin() + y.sin();\n }\n \\'\\'\\'\n >>> module = load_inline(name='inline_extension',\n cpp_sources=[source],\n functions=['sin_add'])\n\n .. note::\n By default, the Ninja backend uses #CPUS + 2 workers to build the\n extension. This may use up too many resources on some systems. One\n can control the number of workers by setting the `MAX_JOBS` environment\n variable to a non-negative number.\n '''\n build_directory = build_directory or _get_build_directory(name, verbose)\n\n if isinstance(cpp_sources, str):\n cpp_sources = [cpp_sources]\n cuda_sources = cuda_sources or []\n if isinstance(cuda_sources, str):\n cuda_sources = [cuda_sources]\n\n cpp_sources.insert(0, '#include <torch/extension.h>')\n\n # If `functions` is supplied, we create the pybind11 bindings for the user.\n # Here, `functions` is (or becomes, after some processing) a map from\n # function names to function docstrings.\n if functions is not None:\n module_def = []\n module_def.append('PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {')\n if isinstance(functions, str):\n functions = [functions]\n if isinstance(functions, list):\n # Make the function docstring the same as the function name.\n functions = dict((f, f) for f in functions)\n elif not isinstance(functions, dict):\n raise ValueError(f\"Expected 'functions' to be a list or dict, but was {type(functions)}\")\n for function_name, docstring in functions.items():\n if with_pytorch_error_handling:\n module_def.append(\n 'm.def(\"{0}\", torch::wrap_pybind_function({0}), \"{1}\");'\n .format(function_name, docstring))\n else:\n module_def.append('m.def(\"{0}\", {0}, \"{1}\");'.format(function_name, docstring))\n module_def.append('}')\n cpp_sources += module_def\n\n cpp_source_path = os.path.join(build_directory, 'main.cpp')\n with open(cpp_source_path, 'w') as cpp_source_file:\n cpp_source_file.write('\\n'.join(cpp_sources))\n\n sources = [cpp_source_path]\n\n if cuda_sources:\n cuda_sources.insert(0, '#include <torch/types.h>')\n cuda_sources.insert(1, '#include <cuda.h>')\n cuda_sources.insert(2, '#include <cuda_runtime.h>')\n\n cuda_source_path = os.path.join(build_directory, 'cuda.cu')\n with open(cuda_source_path, 'w') as cuda_source_file:\n cuda_source_file.write('\\n'.join(cuda_sources))\n\n sources.append(cuda_source_path)\n\n return _jit_compile(\n name,\n sources,\n extra_cflags,\n extra_cuda_cflags,\n extra_ldflags,\n extra_include_paths,\n build_directory,\n verbose,\n with_cuda,\n is_python_module,\n is_standalone=False,\n keep_intermediates=keep_intermediates)\n\n\ndef _jit_compile(name,\n sources,\n extra_cflags,\n extra_cuda_cflags,\n extra_ldflags,\n extra_include_paths,\n build_directory: str,\n verbose: bool,\n with_cuda: Optional[bool],\n is_python_module,\n is_standalone,\n keep_intermediates=True) -> None:\n if is_python_module and is_standalone:\n raise ValueError(\"`is_python_module` and `is_standalone` are mutually exclusive.\")\n\n if with_cuda is None:\n with_cuda = any(map(_is_cuda_file, sources))\n with_cudnn = any(['cudnn' in f for f in extra_ldflags or []])\n old_version = JIT_EXTENSION_VERSIONER.get_version(name)\n version = JIT_EXTENSION_VERSIONER.bump_version_if_changed(\n name,\n sources,\n build_arguments=[extra_cflags, extra_cuda_cflags, extra_ldflags, extra_include_paths],\n build_directory=build_directory,\n with_cuda=with_cuda,\n is_python_module=is_python_module,\n is_standalone=is_standalone,\n )\n if version > 0:\n if version != old_version and verbose:\n print(f'The input conditions for extension module {name} have changed. ' +\n f'Bumping to version {version} and re-building as {name}_v{version}...')\n name = f'{name}_v{version}'\n\n if version != old_version:\n baton = FileBaton(os.path.join(build_directory, 'lock'))\n if baton.try_acquire():\n try:\n with GeneratedFileCleaner(keep_intermediates=keep_intermediates) as clean_ctx:\n if IS_HIP_EXTENSION and (with_cuda or with_cudnn):\n hipify_python.hipify(\n project_directory=build_directory,\n output_directory=build_directory,\n includes=os.path.join(build_directory, '*'),\n extra_files=[os.path.abspath(s) for s in sources],\n show_detailed=verbose,\n is_pytorch_extension=True,\n clean_ctx=clean_ctx\n )\n _write_ninja_file_and_build_library(\n name=name,\n sources=sources,\n extra_cflags=extra_cflags or [],\n extra_cuda_cflags=extra_cuda_cflags or [],\n extra_ldflags=extra_ldflags or [],\n extra_include_paths=extra_include_paths or [],\n build_directory=build_directory,\n verbose=verbose,\n with_cuda=with_cuda,\n is_standalone=is_standalone)\n finally:\n baton.release()\n else:\n baton.wait()\n elif verbose:\n print('No modifications detected for re-loaded extension '\n f'module {name}, skipping build step...')\n\n if verbose:\n print(f'Loading extension module {name}...')\n\n if is_standalone:\n return _get_exec_path(name, build_directory)\n\n return _import_module_from_library(name, build_directory, is_python_module)\n\n\ndef _write_ninja_file_and_compile_objects(\n sources: List[str],\n objects,\n cflags,\n post_cflags,\n cuda_cflags,\n cuda_post_cflags,\n build_directory: str,\n verbose: bool,\n with_cuda: Optional[bool]) -> None:\n verify_ninja_availability()\n if IS_WINDOWS:\n compiler = os.environ.get('CXX', 'cl')\n else:\n compiler = os.environ.get('CXX', 'c++')\n check_compiler_abi_compatibility(compiler)\n if with_cuda is None:\n with_cuda = any(map(_is_cuda_file, sources))\n build_file_path = os.path.join(build_directory, 'build.ninja')\n if verbose:\n print(f'Emitting ninja build file {build_file_path}...')\n _write_ninja_file(\n path=build_file_path,\n cflags=cflags,\n post_cflags=post_cflags,\n cuda_cflags=cuda_cflags,\n cuda_post_cflags=cuda_post_cflags,\n sources=sources,\n objects=objects,\n ldflags=None,\n library_target=None,\n with_cuda=with_cuda)\n if verbose:\n print('Compiling objects...')\n _run_ninja_build(\n build_directory,\n verbose,\n # It would be better if we could tell users the name of the extension\n # that failed to build but there isn't a good way to get it here.\n error_prefix='Error compiling objects for extension')\n\n\ndef _write_ninja_file_and_build_library(\n name,\n sources: List[str],\n extra_cflags,\n extra_cuda_cflags,\n extra_ldflags,\n extra_include_paths,\n build_directory: str,\n verbose: bool,\n with_cuda: Optional[bool],\n is_standalone: bool = False) -> None:\n verify_ninja_availability()\n if IS_WINDOWS:\n compiler = os.environ.get('CXX', 'cl')\n else:\n compiler = os.environ.get('CXX', 'c++')\n check_compiler_abi_compatibility(compiler)\n if with_cuda is None:\n with_cuda = any(map(_is_cuda_file, sources))\n extra_ldflags = _prepare_ldflags(\n extra_ldflags or [],\n with_cuda,\n verbose,\n is_standalone)\n build_file_path = os.path.join(build_directory, 'build.ninja')\n if verbose:\n print(f'Emitting ninja build file {build_file_path}...')\n # NOTE: Emitting a new ninja build file does not cause re-compilation if\n # the sources did not change, so it's ok to re-emit (and it's fast).\n _write_ninja_file_to_build_library(\n path=build_file_path,\n name=name,\n sources=sources,\n extra_cflags=extra_cflags or [],\n extra_cuda_cflags=extra_cuda_cflags or [],\n extra_ldflags=extra_ldflags or [],\n extra_include_paths=extra_include_paths or [],\n with_cuda=with_cuda,\n is_standalone=is_standalone)\n\n if verbose:\n print(f'Building extension module {name}...')\n _run_ninja_build(\n build_directory,\n verbose,\n error_prefix=f\"Error building extension '{name}'\")\n\n\ndef is_ninja_available():\n r'''\n Returns ``True`` if the `ninja <https://ninja-build.org/>`_ build system is\n available on the system, ``False`` otherwise.\n '''\n try:\n subprocess.check_output('ninja --version'.split())\n except Exception:\n return False\n else:\n return True\n\n\ndef verify_ninja_availability():\n r'''\n Raises ``RuntimeError`` if `ninja <https://ninja-build.org/>`_ build system is not\n available on the system, does nothing otherwise.\n '''\n if not is_ninja_available():\n raise RuntimeError(\"Ninja is required to load C++ extensions\")\n\n\ndef _prepare_ldflags(extra_ldflags, with_cuda, verbose, is_standalone):\n if IS_WINDOWS:\n python_path = os.path.dirname(sys.executable)\n python_lib_path = os.path.join(python_path, 'libs')\n\n extra_ldflags.append('c10.lib')\n if with_cuda:\n extra_ldflags.append('c10_cuda.lib')\n extra_ldflags.append('torch_cpu.lib')\n if BUILD_SPLIT_CUDA and with_cuda:\n extra_ldflags.append('torch_cuda_cu.lib')\n # /INCLUDE is used to ensure torch_cuda_cu is linked against in a project that relies on it.\n extra_ldflags.append('-INCLUDE:?searchsorted_cuda@native@at@@YA?AVTensor@2@AEBV32@0_N1@Z')\n extra_ldflags.append('torch_cuda_cpp.lib')\n # /INCLUDE is used to ensure torch_cuda_cpp is linked against in a project that relies on it.\n # Related issue: https://github.com/pytorch/pytorch/issues/31611\n extra_ldflags.append('-INCLUDE:?warp_size@cuda@at@@YAHXZ')\n elif with_cuda:\n extra_ldflags.append('torch_cuda.lib')\n # /INCLUDE is used to ensure torch_cuda is linked against in a project that relies on it.\n # Related issue: https://github.com/pytorch/pytorch/issues/31611\n extra_ldflags.append('-INCLUDE:?warp_size@cuda@at@@YAHXZ')\n extra_ldflags.append('torch.lib')\n extra_ldflags.append(f'/LIBPATH:{TORCH_LIB_PATH}')\n if not is_standalone:\n extra_ldflags.append('torch_python.lib')\n extra_ldflags.append(f'/LIBPATH:{python_lib_path}')\n\n else:\n extra_ldflags.append(f'-L{TORCH_LIB_PATH}')\n extra_ldflags.append('-lc10')\n if with_cuda:\n extra_ldflags.append('-lc10_hip' if IS_HIP_EXTENSION else '-lc10_cuda')\n extra_ldflags.append('-ltorch_cpu')\n if BUILD_SPLIT_CUDA and with_cuda:\n extra_ldflags.append('-ltorch_hip' if IS_HIP_EXTENSION else '-ltorch_cuda_cu -ltorch_cuda_cpp')\n elif with_cuda:\n extra_ldflags.append('-ltorch_hip' if IS_HIP_EXTENSION else '-ltorch_cuda')\n extra_ldflags.append('-ltorch')\n if not is_standalone:\n extra_ldflags.append('-ltorch_python')\n\n if is_standalone and \"TBB\" in torch.__config__.parallel_info():\n extra_ldflags.append('-ltbb')\n\n if is_standalone:\n extra_ldflags.append(f\"-Wl,-rpath,{TORCH_LIB_PATH}\")\n\n if with_cuda:\n if verbose:\n print('Detected CUDA files, patching ldflags')\n if IS_WINDOWS:\n extra_ldflags.append(f'/LIBPATH:{_join_cuda_home(\"lib/x64\")}')\n extra_ldflags.append('cudart.lib')\n if CUDNN_HOME is not None:\n extra_ldflags.append(os.path.join(CUDNN_HOME, 'lib/x64'))\n elif not IS_HIP_EXTENSION:\n extra_ldflags.append(f'-L{_join_cuda_home(\"lib64\")}')\n extra_ldflags.append('-lcudart')\n if CUDNN_HOME is not None:\n extra_ldflags.append(f'-L{os.path.join(CUDNN_HOME, \"lib64\")}')\n elif IS_HIP_EXTENSION:\n assert ROCM_VERSION is not None\n extra_ldflags.append(f'-L{_join_rocm_home(\"lib\")}')\n extra_ldflags.append('-lamdhip64' if ROCM_VERSION >= (3, 5) else '-lhip_hcc')\n return extra_ldflags\n\n\ndef _get_cuda_arch_flags(cflags: Optional[List[str]] = None) -> List[str]:\n r'''\n Determine CUDA arch flags to use.\n\n For an arch, say \"6.1\", the added compile flag will be\n ``-gencode=arch=compute_61,code=sm_61``.\n For an added \"+PTX\", an additional\n ``-gencode=arch=compute_xx,code=compute_xx`` is added.\n\n See select_compute_arch.cmake for corresponding named and supported arches\n when building with CMake.\n '''\n # If cflags is given, there may already be user-provided arch flags in it\n # (from `extra_compile_args`)\n if cflags is not None:\n for flag in cflags:\n if 'arch' in flag:\n return []\n\n # Note: keep combined names (\"arch1+arch2\") above single names, otherwise\n # string replacement may not do the right thing\n named_arches = collections.OrderedDict([\n ('Kepler+Tesla', '3.7'),\n ('Kepler', '3.5+PTX'),\n ('Maxwell+Tegra', '5.3'),\n ('Maxwell', '5.0;5.2+PTX'),\n ('Pascal', '6.0;6.1+PTX'),\n ('Volta', '7.0+PTX'),\n ('Turing', '7.5+PTX'),\n ('Ampere', '8.0;8.6+PTX'),\n ])\n\n supported_arches = ['3.5', '3.7', '5.0', '5.2', '5.3', '6.0', '6.1', '6.2',\n '7.0', '7.2', '7.5', '8.0', '8.6']\n valid_arch_strings = supported_arches + [s + \"+PTX\" for s in supported_arches]\n\n # The default is sm_30 for CUDA 9.x and 10.x\n # First check for an env var (same as used by the main setup.py)\n # Can be one or more architectures, e.g. \"6.1\" or \"3.5;5.2;6.0;6.1;7.0+PTX\"\n # See cmake/Modules_CUDA_fix/upstream/FindCUDA/select_compute_arch.cmake\n _arch_list = os.environ.get('TORCH_CUDA_ARCH_LIST', None)\n\n # If not given, determine what's best for the GPU / CUDA version that can be found\n if not _arch_list:\n arch_list = []\n # the assumption is that the extension should run on any of the currently visible cards,\n # which could be of different types - therefore all archs for visible cards should be included\n for i in range(torch.cuda.device_count()):\n capability = torch.cuda.get_device_capability(i)\n supported_sm = [int(arch.split('_')[1])\n for arch in torch.cuda.get_arch_list() if 'sm_' in arch]\n max_supported_sm = max((sm // 10, sm % 10) for sm in supported_sm)\n # Capability of the device may be higher than what's supported by the user's\n # NVCC, causing compilation error. User's NVCC is expected to match the one\n # used to build pytorch, so we use the maximum supported capability of pytorch\n # to clamp the capability.\n capability = min(max_supported_sm, capability)\n arch = f'{capability[0]}.{capability[1]}'\n if arch not in arch_list:\n arch_list.append(arch)\n arch_list = sorted(arch_list)\n arch_list[-1] += '+PTX'\n else:\n # Deal with lists that are ' ' separated (only deal with ';' after)\n _arch_list = _arch_list.replace(' ', ';')\n # Expand named arches\n for named_arch, archval in named_arches.items():\n _arch_list = _arch_list.replace(named_arch, archval)\n\n arch_list = _arch_list.split(';')\n\n flags = []\n for arch in arch_list:\n if arch not in valid_arch_strings:\n raise ValueError(f\"Unknown CUDA arch ({arch}) or GPU not supported\")\n else:\n num = arch[0] + arch[2]\n flags.append(f'-gencode=arch=compute_{num},code=sm_{num}')\n if arch.endswith('+PTX'):\n flags.append(f'-gencode=arch=compute_{num},code=compute_{num}')\n\n return sorted(list(set(flags)))\n\n\ndef _get_rocm_arch_flags(cflags: Optional[List[str]] = None) -> List[str]:\n # If cflags is given, there may already be user-provided arch flags in it\n # (from `extra_compile_args`)\n if cflags is not None:\n for flag in cflags:\n if 'amdgpu-target' in flag:\n return ['-fno-gpu-rdc']\n # Use same defaults from file cmake/public/LoadHIP.cmake.\n # Must keep in sync if defaults change.\n # Allow env var to override, just like during initial cmake build.\n archs = os.environ.get('PYTORCH_ROCM_ARCH', 'gfx803;gfx900;gfx906;gfx908')\n flags = ['--amdgpu-target=%s' % arch for arch in archs.split(';')]\n flags += ['-fno-gpu-rdc']\n return flags\n\ndef _get_build_directory(name: str, verbose: bool) -> str:\n root_extensions_directory = os.environ.get('TORCH_EXTENSIONS_DIR')\n if root_extensions_directory is None:\n root_extensions_directory = get_default_build_root()\n cu_str = ('cpu' if torch.version.cuda is None else\n f'cu{torch.version.cuda.replace(\".\", \"\")}') # type: ignore[attr-defined]\n python_version = f'py{sys.version_info.major}{sys.version_info.minor}'\n build_folder = f'{python_version}_{cu_str}'\n\n root_extensions_directory = os.path.join(\n root_extensions_directory, build_folder)\n\n if verbose:\n print(f'Using {root_extensions_directory} as PyTorch extensions root...')\n\n build_directory = os.path.join(root_extensions_directory, name)\n if not os.path.exists(build_directory):\n if verbose:\n print(f'Creating extension directory {build_directory}...')\n # This is like mkdir -p, i.e. will also create parent directories.\n os.makedirs(build_directory, exist_ok=True)\n\n return build_directory\n\n\ndef _get_num_workers(verbose: bool) -> Optional[int]:\n max_jobs = os.environ.get('MAX_JOBS')\n if max_jobs is not None and max_jobs.isdigit():\n if verbose:\n print(f'Using envvar MAX_JOBS ({max_jobs}) as the number of workers...')\n return int(max_jobs)\n if verbose:\n print('Allowing ninja to set a default number of workers... '\n '(overridable by setting the environment variable MAX_JOBS=N)')\n return None\n\n\ndef _run_ninja_build(build_directory: str, verbose: bool, error_prefix: str) -> None:\n command = ['ninja', '-v']\n num_workers = _get_num_workers(verbose)\n if num_workers is not None:\n command.extend(['-j', str(num_workers)])\n env = os.environ.copy()\n # Try to activate the vc env for the users\n if IS_WINDOWS and 'VSCMD_ARG_TGT_ARCH' not in env:\n from setuptools import distutils\n\n plat_name = distutils.util.get_platform()\n plat_spec = PLAT_TO_VCVARS[plat_name]\n\n vc_env = distutils._msvccompiler._get_vc_env(plat_spec)\n vc_env = {k.upper(): v for k, v in vc_env.items()}\n for k, v in env.items():\n uk = k.upper()\n if uk not in vc_env:\n vc_env[uk] = v\n env = vc_env\n try:\n sys.stdout.flush()\n sys.stderr.flush()\n # Warning: don't pass stdout=None to subprocess.run to get output.\n # subprocess.run assumes that sys.__stdout__ has not been modified and\n # attempts to write to it by default. However, when we call _run_ninja_build\n # from ahead-of-time cpp extensions, the following happens:\n # 1) If the stdout encoding is not utf-8, setuptools detachs __stdout__.\n # https://github.com/pypa/setuptools/blob/7e97def47723303fafabe48b22168bbc11bb4821/setuptools/dist.py#L1110\n # (it probably shouldn't do this)\n # 2) subprocess.run (on POSIX, with no stdout override) relies on\n # __stdout__ not being detached:\n # https://github.com/python/cpython/blob/c352e6c7446c894b13643f538db312092b351789/Lib/subprocess.py#L1214\n # To work around this, we pass in the fileno directly and hope that\n # it is valid.\n stdout_fileno = 1\n subprocess.run(\n command,\n stdout=stdout_fileno if verbose else subprocess.PIPE,\n stderr=subprocess.STDOUT,\n cwd=build_directory,\n check=True,\n env=env)\n except subprocess.CalledProcessError as e:\n # Python 2 and 3 compatible way of getting the error object.\n _, error, _ = sys.exc_info()\n # error.output contains the stdout and stderr of the build attempt.\n message = error_prefix\n # `error` is a CalledProcessError (which has an `ouput`) attribute, but\n # mypy thinks it's Optional[BaseException] and doesn't narrow\n if hasattr(error, 'output') and error.output: # type: ignore[union-attr]\n message += f\": {error.output.decode()}\" # type: ignore[union-attr]\n raise RuntimeError(message) from e\n\n\ndef _get_exec_path(module_name, path):\n if IS_WINDOWS and TORCH_LIB_PATH not in os.getenv('PATH', '').split(';'):\n torch_lib_in_path = any(\n os.path.exists(p) and os.path.samefile(p, TORCH_LIB_PATH)\n for p in os.getenv('PATH', '').split(';')\n )\n if not torch_lib_in_path:\n os.environ['PATH'] = f\"{TORCH_LIB_PATH};{os.getenv('PATH', '')}\"\n return os.path.join(path, f'{module_name}{EXEC_EXT}')\n\n\ndef _import_module_from_library(module_name, path, is_python_module):\n filepath = os.path.join(path, f\"{module_name}{LIB_EXT}\")\n if is_python_module:\n # https://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path\n spec = importlib.util.spec_from_file_location(module_name, filepath)\n module = importlib.util.module_from_spec(spec)\n assert isinstance(spec.loader, importlib.abc.Loader)\n spec.loader.exec_module(module)\n return module\n else:\n torch.ops.load_library(filepath)\n\n\ndef _write_ninja_file_to_build_library(path,\n name,\n sources,\n extra_cflags,\n extra_cuda_cflags,\n extra_ldflags,\n extra_include_paths,\n with_cuda,\n is_standalone) -> None:\n extra_cflags = [flag.strip() for flag in extra_cflags]\n extra_cuda_cflags = [flag.strip() for flag in extra_cuda_cflags]\n extra_ldflags = [flag.strip() for flag in extra_ldflags]\n extra_include_paths = [flag.strip() for flag in extra_include_paths]\n\n # Turn into absolute paths so we can emit them into the ninja build\n # file wherever it is.\n user_includes = [os.path.abspath(file) for file in extra_include_paths]\n\n # include_paths() gives us the location of torch/extension.h\n system_includes = include_paths(with_cuda)\n # sysconfig.get_path('include') gives us the location of Python.h\n # Explicitly specify 'posix_prefix' scheme on non-Windows platforms to workaround error on some MacOS\n # installations where default `get_path` points to non-existing `/Library/Python/M.m/include` folder\n python_include_path = sysconfig.get_path('include', scheme='nt' if IS_WINDOWS else 'posix_prefix')\n if python_include_path is not None:\n system_includes.append(python_include_path)\n\n # Windows does not understand `-isystem`.\n if IS_WINDOWS:\n user_includes += system_includes\n system_includes.clear()\n\n common_cflags = []\n if not is_standalone:\n common_cflags.append(f'-DTORCH_EXTENSION_NAME={name}')\n common_cflags.append('-DTORCH_API_INCLUDE_EXTENSION_H')\n\n # Note [Pybind11 ABI constants]\n #\n # Pybind11 before 2.4 used to build an ABI strings using the following pattern:\n # f\"__pybind11_internals_v{PYBIND11_INTERNALS_VERSION}{PYBIND11_INTERNALS_KIND}{PYBIND11_BUILD_TYPE}__\"\n # Since 2.4 compier type, stdlib and build abi parameters are also encoded like this:\n # f\"__pybind11_internals_v{PYBIND11_INTERNALS_VERSION}{PYBIND11_INTERNALS_KIND}{PYBIND11_COMPILER_TYPE}{PYBIND11_STDLIB}{PYBIND11_BUILD_ABI}{PYBIND11_BUILD_TYPE}__\"\n #\n # This was done in order to further narrow down the chances of compiler ABI incompatibility\n # that can cause a hard to debug segfaults.\n # For PyTorch extensions we want to relax those restrictions and pass compiler, stdlib and abi properties\n # captured during PyTorch native library compilation in torch/csrc/Module.cpp\n\n for pname in [\"COMPILER_TYPE\", \"STDLIB\", \"BUILD_ABI\"]:\n pval = getattr(torch._C, f\"_PYBIND11_{pname}\")\n if pval is not None and not IS_WINDOWS:\n common_cflags.append(f'-DPYBIND11_{pname}=\\\\\"{pval}\\\\\"')\n\n common_cflags += [f'-I{include}' for include in user_includes]\n common_cflags += [f'-isystem {include}' for include in system_includes]\n\n common_cflags += ['-D_GLIBCXX_USE_CXX11_ABI=' + str(int(torch._C._GLIBCXX_USE_CXX11_ABI))]\n\n if IS_WINDOWS:\n cflags = common_cflags + COMMON_MSVC_FLAGS + extra_cflags\n cflags = _nt_quote_args(cflags)\n else:\n cflags = common_cflags + ['-fPIC', '-std=c++14'] + extra_cflags\n\n if with_cuda and IS_HIP_EXTENSION:\n cuda_flags = ['-DWITH_HIP'] + cflags + COMMON_HIP_FLAGS + COMMON_HIPCC_FLAGS\n cuda_flags += extra_cuda_cflags\n cuda_flags += _get_rocm_arch_flags(cuda_flags)\n sources = [s if not _is_cuda_file(s) else\n os.path.abspath(os.path.join(\n path, get_hip_file_path(os.path.relpath(s, path), is_pytorch_extension=True)))\n for s in sources]\n elif with_cuda:\n cuda_flags = common_cflags + COMMON_NVCC_FLAGS + _get_cuda_arch_flags()\n if IS_WINDOWS:\n for flag in COMMON_MSVC_FLAGS:\n cuda_flags = ['-Xcompiler', flag] + cuda_flags\n for ignore_warning in MSVC_IGNORE_CUDAFE_WARNINGS:\n cuda_flags = ['-Xcudafe', '--diag_suppress=' + ignore_warning] + cuda_flags\n cuda_flags = _nt_quote_args(cuda_flags)\n cuda_flags += _nt_quote_args(extra_cuda_cflags)\n else:\n cuda_flags += ['--compiler-options', \"'-fPIC'\"]\n cuda_flags += extra_cuda_cflags\n if not any(flag.startswith('-std=') for flag in cuda_flags):\n cuda_flags.append('-std=c++14')\n if os.getenv(\"CC\") is not None:\n cuda_flags = ['-ccbin', os.getenv(\"CC\")] + cuda_flags\n else:\n cuda_flags = None\n\n def object_file_path(source_file: str) -> str:\n # '/path/to/file.cpp' -> 'file'\n file_name = os.path.splitext(os.path.basename(source_file))[0]\n if _is_cuda_file(source_file) and with_cuda:\n # Use a different object filename in case a C++ and CUDA file have\n # the same filename but different extension (.cpp vs. .cu).\n target = f'{file_name}.cuda.o'\n else:\n target = f'{file_name}.o'\n return target\n\n objects = [object_file_path(src) for src in sources]\n ldflags = ([] if is_standalone else [SHARED_FLAG]) + extra_ldflags\n\n # The darwin linker needs explicit consent to ignore unresolved symbols.\n if sys.platform.startswith('darwin'):\n ldflags.append('-undefined dynamic_lookup')\n elif IS_WINDOWS:\n ldflags = _nt_quote_args(ldflags)\n\n ext = EXEC_EXT if is_standalone else LIB_EXT\n library_target = f'{name}{ext}'\n\n _write_ninja_file(\n path=path,\n cflags=cflags,\n post_cflags=None,\n cuda_cflags=cuda_flags,\n cuda_post_cflags=None,\n sources=sources,\n objects=objects,\n ldflags=ldflags,\n library_target=library_target,\n with_cuda=with_cuda)\n\n\ndef _write_ninja_file(path,\n cflags,\n post_cflags,\n cuda_cflags,\n cuda_post_cflags,\n sources,\n objects,\n ldflags,\n library_target,\n with_cuda) -> None:\n r\"\"\"Write a ninja file that does the desired compiling and linking.\n\n `path`: Where to write this file\n `cflags`: list of flags to pass to $cxx. Can be None.\n `post_cflags`: list of flags to append to the $cxx invocation. Can be None.\n `cuda_cflags`: list of flags to pass to $nvcc. Can be None.\n `cuda_postflags`: list of flags to append to the $nvcc invocation. Can be None.\n `sources`: list of paths to source files\n `objects`: list of desired paths to objects, one per source.\n `ldflags`: list of flags to pass to linker. Can be None.\n `library_target`: Name of the output library. Can be None; in that case,\n we do no linking.\n `with_cuda`: If we should be compiling with CUDA.\n \"\"\"\n def sanitize_flags(flags):\n if flags is None:\n return []\n else:\n return [flag.strip() for flag in flags]\n\n cflags = sanitize_flags(cflags)\n post_cflags = sanitize_flags(post_cflags)\n cuda_cflags = sanitize_flags(cuda_cflags)\n cuda_post_cflags = sanitize_flags(cuda_post_cflags)\n ldflags = sanitize_flags(ldflags)\n\n # Sanity checks...\n assert len(sources) == len(objects)\n assert len(sources) > 0\n\n if IS_WINDOWS:\n compiler = os.environ.get('CXX', 'cl')\n else:\n compiler = os.environ.get('CXX', 'c++')\n\n # Version 1.3 is required for the `deps` directive.\n config = ['ninja_required_version = 1.3']\n config.append(f'cxx = {compiler}')\n if with_cuda:\n if IS_HIP_EXTENSION:\n nvcc = _join_rocm_home('bin', 'hipcc')\n else:\n nvcc = _join_cuda_home('bin', 'nvcc')\n config.append(f'nvcc = {nvcc}')\n\n flags = [f'cflags = {\" \".join(cflags)}']\n flags.append(f'post_cflags = {\" \".join(post_cflags)}')\n if with_cuda:\n flags.append(f'cuda_cflags = {\" \".join(cuda_cflags)}')\n flags.append(f'cuda_post_cflags = {\" \".join(cuda_post_cflags)}')\n flags.append(f'ldflags = {\" \".join(ldflags)}')\n\n # Turn into absolute paths so we can emit them into the ninja build\n # file wherever it is.\n sources = [os.path.abspath(file) for file in sources]\n\n # See https://ninja-build.org/build.ninja.html for reference.\n compile_rule = ['rule compile']\n if IS_WINDOWS:\n compile_rule.append(\n ' command = cl /showIncludes $cflags -c $in /Fo$out $post_cflags')\n compile_rule.append(' deps = msvc')\n else:\n compile_rule.append(\n ' command = $cxx -MMD -MF $out.d $cflags -c $in -o $out $post_cflags')\n compile_rule.append(' depfile = $out.d')\n compile_rule.append(' deps = gcc')\n\n if with_cuda:\n cuda_compile_rule = ['rule cuda_compile']\n nvcc_gendeps = ''\n # --generate-dependencies-with-compile was added in CUDA 10.2.\n # Compilation will work on earlier CUDA versions but header file\n # dependencies are not correctly computed.\n required_cuda_version = packaging.version.parse('10.2')\n has_cuda_version = torch.version.cuda is not None\n if has_cuda_version and packaging.version.parse(torch.version.cuda) >= required_cuda_version:\n cuda_compile_rule.append(' depfile = $out.d')\n cuda_compile_rule.append(' deps = gcc')\n # Note: non-system deps with nvcc are only supported\n # on Linux so use --generate-dependencies-with-compile\n # to make this work on Windows too.\n if IS_WINDOWS:\n nvcc_gendeps = '--generate-dependencies-with-compile --dependency-output $out.d'\n cuda_compile_rule.append(\n f' command = $nvcc {nvcc_gendeps} $cuda_cflags -c $in -o $out $cuda_post_cflags')\n\n # Emit one build rule per source to enable incremental build.\n build = []\n for source_file, object_file in zip(sources, objects):\n is_cuda_source = _is_cuda_file(source_file) and with_cuda\n rule = 'cuda_compile' if is_cuda_source else 'compile'\n if IS_WINDOWS:\n source_file = source_file.replace(':', '$:')\n object_file = object_file.replace(':', '$:')\n source_file = source_file.replace(\" \", \"$ \")\n object_file = object_file.replace(\" \", \"$ \")\n build.append(f'build {object_file}: {rule} {source_file}')\n\n if library_target is not None:\n link_rule = ['rule link']\n if IS_WINDOWS:\n cl_paths = subprocess.check_output(['where',\n 'cl']).decode().split('\\r\\n')\n if len(cl_paths) >= 1:\n cl_path = os.path.dirname(cl_paths[0]).replace(':', '$:')\n else:\n raise RuntimeError(\"MSVC is required to load C++ extensions\")\n link_rule.append(f' command = \"{cl_path}/link.exe\" $in /nologo $ldflags /out:$out')\n else:\n link_rule.append(' command = $cxx $in $ldflags -o $out')\n\n link = [f'build {library_target}: link {\" \".join(objects)}']\n\n default = [f'default {library_target}']\n else:\n link_rule, link, default = [], [], []\n\n # 'Blocks' should be separated by newlines, for visual benefit.\n blocks = [config, flags, compile_rule]\n if with_cuda:\n blocks.append(cuda_compile_rule)\n blocks += [link_rule, build, link, default]\n with open(path, 'w') as build_file:\n for block in blocks:\n lines = '\\n'.join(block)\n build_file.write(f'{lines}\\n\\n')\n\n\ndef _join_cuda_home(*paths) -> str:\n r'''\n Joins paths with CUDA_HOME, or raises an error if it CUDA_HOME is not set.\n\n This is basically a lazy way of raising an error for missing $CUDA_HOME\n only once we need to get any CUDA-specific path.\n '''\n if CUDA_HOME is None:\n raise EnvironmentError('CUDA_HOME environment variable is not set. '\n 'Please set it to your CUDA install root.')\n return os.path.join(CUDA_HOME, *paths)\n\n\ndef _is_cuda_file(path: str) -> bool:\n valid_ext = ['.cu', '.cuh']\n if IS_HIP_EXTENSION:\n valid_ext.append('.hip')\n return os.path.splitext(path)[1] in valid_ext\n"
]
| [
[
"torch.version.hip.split",
"torch.__config__.parallel_info",
"torch.ops.load_library",
"torch._appdirs.user_cache_dir",
"torch.cuda.get_device_capability",
"torch.version.cuda.replace",
"torch.cuda.is_available",
"torch.cuda.device_count",
"torch.cuda.get_arch_list"
]
]
|
seequent/lfview-resources-files | [
"7ac0d44724471646bb90cf0a030b279fbc9c5c7e"
]
| [
"tests/test_array.py"
]
| [
"from __future__ import unicode_literals\n\nimport numpy as np\nimport pytest\n\nimport properties\nimport properties.extras\nfrom lfview.resources import files\n\n\ndef test_empty_init():\n arr = files.Array()\n with pytest.raises(properties.ValidationError):\n arr.validate()\n\n\ndef test_object_without_array():\n arr = files.Array()\n arr.content_length = 64\n arr.dtype = 'Int8Array'\n arr.shape = [64]\n assert arr.validate()\n\n\[email protected](\n 'input_arr', [\n [1, 2, 3],\n (1, 2, 3),\n np.array([1, 2, 3]),\n ]\n)\ndef test_array_init(input_arr):\n arr = files.Array(input_arr)\n assert arr.validate()\n assert isinstance(arr.array, np.ndarray)\n assert np.array_equal(arr.array, np.array([1, 2, 3]))\n assert arr.dtype.startswith('Int')\n assert arr.shape == [3]\n assert arr.content_type == 'application/octet-stream'\n assert arr.content_length == np.dtype(arr.array.dtype).itemsize * 3\n assert arr.is_1d()\n\n\[email protected](\n 'input_arr', [\n ['a', 'b', 'c'],\n ('a', 'b', 'c'),\n np.array(['a', 'b', 'c']),\n ]\n)\ndef test_array_assignment(input_arr):\n arr = files.Array()\n with pytest.raises(ValueError):\n arr.array = input_arr\n\n\[email protected](\n 'input_arr', [\n [[1., 2], [3, 4]],\n ((1., 2), (3, 4)),\n np.array([[1., 2], [3, 4]]),\n ]\n)\ndef test_hasarray_assignment(input_arr):\n class HasArray(properties.extras.HasUID):\n arr = properties.extras.Pointer('array', files.Array)\n\n has_array = HasArray()\n has_array.arr = input_arr\n assert has_array.validate()\n assert isinstance(has_array.arr.array, np.ndarray)\n assert np.allclose(has_array.arr.array, np.array([[1., 2], [3, 4]]))\n assert has_array.arr.dtype.startswith('Float')\n assert has_array.arr.shape == [2, 2]\n assert has_array.arr.content_type == 'application/octet-stream'\n dtype = np.dtype(has_array.arr.array.dtype)\n assert has_array.arr.content_length == dtype.itemsize * 4\n assert not has_array.arr.is_1d()\n\n\ndef test_array_serialize():\n arr = files.Array([[1]])\n arr.validate()\n serial_arr = arr.serialize()\n assert serial_arr == {\n '__class__': 'Array',\n 'content_length': np.dtype(arr.array.dtype).itemsize,\n 'content_type': 'application/octet-stream',\n 'dtype': 'Int32Array',\n 'shape': [1, 1],\n }\n\n\ndef test_unsupported_array():\n with pytest.raises(ValueError):\n files.Array('bad array')\n int64array = np.array([100000000000])\n with pytest.raises(ValueError):\n files.Array(int64array)\n\n\ndef test_bad_input():\n with pytest.raises(properties.ValidationError):\n files.Array(dtype='bad')\n arr = files.Array(dtype='Int32Array', shape=[1])\n with pytest.raises(properties.ValidationError):\n arr.content_length = 100\n\n\[email protected](\n ('input', 'is_1d'),\n [(None, False), ([1, 2, 3], True), ([[1, 2], [3, 4]], False)]\n)\ndef test_is_1d(input, is_1d):\n assert files.Array(input).is_1d() == is_1d\n\n\ndef test_types():\n assert files.Array.BASE_TYPE == 'files'\n assert files.Array.SUB_TYPE == 'array'\n\n\nif __name__ == '__main__':\n pytest.main()\n"
]
| [
[
"numpy.array",
"numpy.dtype"
]
]
|
MatthewK3023/FoodCalorieDetector | [
"b0bfa4e0f10bd70bbb9b2bee085a15706c566fe5"
]
| [
"caffe_transfer/demo_tensorrt.py"
]
| [
"import logging\nimport math\nimport os\nimport pickle\nimport time\n\nimport cv2\nimport numpy as np\nimport tensorrt as trt\nimport torch\nimport _init_paths\nfrom torchvision import transforms\nfrom opts_pose import opts\nfrom centernet_tensorrt_engine import CenterNetTensorRTEngine\n\nlogger = logging.getLogger(__name__)\nTRT_LOGGER = trt.Logger() # required by TensorRT \n\n\ndef build_engine(onnx_file_path, engine_file_path, precision, max_batch_size, cache_file=None):\n \"\"\"Builds a new TensorRT engine and saves it, if no engine presents\"\"\"\n\n if os.path.exists(engine_file_path):\n logger.info('{} TensorRT engine already exists. Skip building engine...'.format(precision))\n return\n\n logger.info('Building {} TensorRT engine from onnx file...'.format(precision))\n with trt.Builder(TRT_LOGGER) as b, b.create_network() as n, trt.OnnxParser(n, TRT_LOGGER) as p:\n b.max_workspace_size = 1 << 30 # 1GB\n b.max_batch_size = max_batch_size\n if precision == 'fp16':\n b.fp16_mode = True\n elif precision == 'int8':\n from ..calibrator import Calibrator\n b.int8_mode = True\n b.int8_calibrator = Calibrator(cache_file=cache_file)\n elif precision == 'fp32':\n pass\n else:\n logger.error('Engine precision not supported: {}'.format(precision))\n raise NotImplementedError\n # Parse model file\n with open(onnx_file_path, 'rb') as model:\n p.parse(model.read())\n if p.num_errors:\n logger.error('Parsing onnx file found {} errors.'.format(p.num_errors))\n engine = b.build_cuda_engine(n)\n print(engine_file_path)\n with open(engine_file_path, \"wb\") as f:\n f.write(engine.serialize())\n\n\ndef add_coco_bbox(image, bbox, conf=1):\n txt = '{}{:.1f}'.format('person', conf)\n font = cv2.FONT_HERSHEY_SIMPLEX\n cv2.rectangle(image, (bbox[0], bbox[1]), (bbox[2], bbox[3]), (0, 255, 255), 2)\n cv2.putText(image, txt, (bbox[0], bbox[1] - 2),\n font, 0.5, (0, 255, 0), thickness=1, lineType=cv2.LINE_AA)\n\ndef add_coco_hp(image, points, keypoints_prob):\n for j in range(5):\n if keypoints_prob[j] > 0.5:\n cv2.circle(image, (points[j, 0], points[j, 1]), 2, (255, 255, 0), -1)\n return image\n\n\nif __name__ == '__main__':\n # 0. build trnsorrt engine/转成tensorrt模型\n # onnx_path = '../output/onnx_model/mobilev2_large.onnx'\n trt_path = '../output/onnx_model/mobilev2.trt'\n # build_engine(onnx_path, trt_path, 'fp32', 1)\n # print('build trnsorrt engine done')\n config = opts().init()\n\n # 1. load trnsorrt engine\n body_engine = CenterNetTensorRTEngine(weight_file=trt_path, config=config)\n print('load trnsorrt engine done')\n\n # 2. video for the tracking\n cap = cv2.VideoCapture('../readme/唐人街网剧.mp4')\n\n # 3. write the result image into video\n if config.output_video:\n fourcc = cv2.VideoWriter_fourcc(*'mp4v') # 如果是mp4视频,编码需要为mp4v\n im_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))\n im_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\n write_cap = cv2.VideoWriter(config.output_video, fourcc, 50, (im_width, im_height))\n\n k = 1; start_time = time.time()\n while cap.grab():\n k += 1\n ret, image = cap.retrieve() # Capture frame-by-frame\n rgb_img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n\n detections = body_engine.run(rgb_img)[1]\n\n print('fps is:{:.3f}'.format(k/(time.time() - start_time)))\n\n for i, bbox in enumerate(detections):\n if bbox[4] > 0.4:\n body_bbox = np.array(bbox[:4], dtype=np.int32)\n body_prob = bbox[4]\n add_coco_bbox(image, body_bbox, body_prob)\n body_pose = np.array(bbox[5:15], dtype=np.int32)\n keypoints = np.array(body_pose, dtype=np.int32).reshape(5, 2)\n keypoints_prob = bbox[15:]\n image = add_coco_hp(image, keypoints, keypoints_prob)\n # debug show\n # cv2.imshow('image result', image)\n # if cv2.waitKey(1) & 0xFF == ord('q'):\n # break\n\n # write into video\n if config.output_video:\n write_cap.write(image)\n"
]
| [
[
"numpy.array"
]
]
|
kos-kaggle/pytorch_advanced | [
"a241067ddbcb37ef42bb243ea55efddf8cc36860"
]
| [
"2_objectdetection/utils/ssd_model.py"
]
| [
"\"\"\"\n第2章SSDで実装した内容をまとめたファイル\n\"\"\"\n\n# パッケージのimport\nimport torch.nn as nn\nimport torch.nn.init as init\nimport torch.nn.functional as F\nfrom torch.autograd import Function\nimport torch.utils.data as data\nimport torch\nimport cv2\nimport numpy as np\nimport os.path as osp\nfrom itertools import product as product\nfrom math import sqrt as sqrt\n\n# XMLをファイルやテキストから読み込んだり、加工したり、保存したりするためのライブラリ\nimport xml.etree.ElementTree as ET\n\n# フォルダ「utils」のdata_augumentation.pyからimport。入力画像の前処理をするクラス\nfrom utils.data_augumentation import Compose, ConvertFromInts, ToAbsoluteCoords, PhotometricDistort, Expand, RandomSampleCrop, RandomMirror, ToPercentCoords, Resize, SubtractMeans\n\n# フォルダ「utils」にある関数matchを記述したmatch.pyからimport\nfrom utils.match import match\n\n\n# 学習、検証の画像データとアノテーションデータへのファイルパスリストを作成する\n\ndef make_datapath_list(rootpath):\n \"\"\"\n データへのパスを格納したリストを作成する。\n\n Parameters\n ----------\n rootpath : str\n データフォルダへのパス\n\n Returns\n -------\n ret : train_img_list, train_anno_list, val_img_list, val_anno_list\n データへのパスを格納したリスト\n \"\"\"\n\n # 画像ファイルとアノテーションファイルへのパスのテンプレートを作成\n imgpath_template = osp.join(rootpath, 'JPEGImages', '%s.jpg')\n annopath_template = osp.join(rootpath, 'Annotations', '%s.xml')\n\n # 訓練と検証、それぞれのファイルのID(ファイル名)を取得する\n train_id_names = osp.join(rootpath + 'ImageSets/Main/train.txt')\n val_id_names = osp.join(rootpath + 'ImageSets/Main/val.txt')\n\n # 訓練データの画像ファイルとアノテーションファイルへのパスリストを作成\n train_img_list = list()\n train_anno_list = list()\n\n for line in open(train_id_names):\n file_id = line.strip() # 空白スペースと改行を除去\n img_path = (imgpath_template % file_id) # 画像のパス\n anno_path = (annopath_template % file_id) # アノテーションのパス\n train_img_list.append(img_path) # リストに追加\n train_anno_list.append(anno_path) # リストに追加\n\n # 検証データの画像ファイルとアノテーションファイルへのパスリストを作成\n val_img_list = list()\n val_anno_list = list()\n\n for line in open(val_id_names):\n file_id = line.strip() # 空白スペースと改行を除去\n img_path = (imgpath_template % file_id) # 画像のパス\n anno_path = (annopath_template % file_id) # アノテーションのパス\n val_img_list.append(img_path) # リストに追加\n val_anno_list.append(anno_path) # リストに追加\n\n return train_img_list, train_anno_list, val_img_list, val_anno_list\n\n\n# 「XML形式のアノテーション」を、リスト形式に変換するクラス\n\n\nclass Anno_xml2list(object):\n \"\"\"\n 1枚の画像に対する「XML形式のアノテーションデータ」を、画像サイズで規格化してからリスト形式に変換する。\n\n Attributes\n ----------\n classes : リスト\n VOCのクラス名を格納したリスト\n \"\"\"\n\n def __init__(self, classes):\n\n self.classes = classes\n\n def __call__(self, xml_path, width, height):\n \"\"\"\n 1枚の画像に対する「XML形式のアノテーションデータ」を、画像サイズで規格化してからリスト形式に変換する。\n\n Parameters\n ----------\n xml_path : str\n xmlファイルへのパス。\n width : int\n 対象画像の幅。\n height : int\n 対象画像の高さ。\n\n Returns\n -------\n ret : [[xmin, ymin, xmax, ymax, label_ind], ... ]\n 物体のアノテーションデータを格納したリスト。画像内に存在する物体数分のだけ要素を持つ。\n \"\"\"\n\n # 画像内の全ての物体のアノテーションをこのリストに格納します\n ret = []\n\n # xmlファイルを読み込む\n xml = ET.parse(xml_path).getroot()\n\n # 画像内にある物体(object)の数だけループする\n for obj in xml.iter('object'):\n\n # アノテーションで検知がdifficultに設定されているものは除外\n difficult = int(obj.find('difficult').text)\n if difficult == 1:\n continue\n\n # 1つの物体に対するアノテーションを格納するリスト\n bndbox = []\n\n name = obj.find('name').text.lower().strip() # 物体名\n bbox = obj.find('bndbox') # バウンディングボックスの情報\n\n # アノテーションの xmin, ymin, xmax, ymaxを取得し、0~1に規格化\n pts = ['xmin', 'ymin', 'xmax', 'ymax']\n\n for pt in (pts):\n # VOCは原点が(1,1)なので1を引き算して(0, 0)に\n cur_pixel = int(bbox.find(pt).text) - 1\n\n # 幅、高さで規格化\n if pt == 'xmin' or pt == 'xmax': # x方向のときは幅で割算\n cur_pixel /= width\n else: # y方向のときは高さで割算\n cur_pixel /= height\n\n bndbox.append(cur_pixel)\n\n # アノテーションのクラス名のindexを取得して追加\n label_idx = self.classes.index(name)\n bndbox.append(label_idx)\n\n # resに[xmin, ymin, xmax, ymax, label_ind]を足す\n ret += [bndbox]\n\n return np.array(ret) # [[xmin, ymin, xmax, ymax, label_ind], ... ]\n\n\n# 入力画像の前処理をするクラス\n\n\nclass DataTransform():\n \"\"\"\n 画像とアノテーションの前処理クラス。訓練と推論で異なる動作をする。\n 画像のサイズを300x300にする。\n 学習時はデータオーギュメンテーションする。\n\n\n Attributes\n ----------\n input_size : int\n リサイズ先の画像の大きさ。\n color_mean : (B, G, R)\n 各色チャネルの平均値。\n \"\"\"\n\n def __init__(self, input_size, color_mean):\n self.data_transform = {\n 'train': Compose([\n ConvertFromInts(), # intをfloat32に変換\n ToAbsoluteCoords(), # アノテーションデータの規格化を戻す\n PhotometricDistort(), # 画像の色調などをランダムに変化\n Expand(color_mean), # 画像のキャンバスを広げる\n RandomSampleCrop(), # 画像内の部分をランダムに抜き出す\n RandomMirror(), # 画像を反転させる\n ToPercentCoords(), # アノテーションデータを0-1に規格化\n Resize(input_size), # 画像サイズをinput_size×input_sizeに変形\n SubtractMeans(color_mean) # BGRの色の平均値を引き算\n ]),\n 'val': Compose([\n ConvertFromInts(), # intをfloatに変換\n Resize(input_size), # 画像サイズをinput_size×input_sizeに変形\n SubtractMeans(color_mean) # BGRの色の平均値を引き算\n ])\n }\n\n def __call__(self, img, phase, boxes, labels):\n \"\"\"\n Parameters\n ----------\n phase : 'train' or 'val'\n 前処理のモードを指定。\n \"\"\"\n return self.data_transform[phase](img, boxes, labels)\n\n\nclass VOCDataset(data.Dataset):\n \"\"\"\n VOC2012のDatasetを作成するクラス。PyTorchのDatasetクラスを継承。\n\n Attributes\n ----------\n img_list : リスト\n 画像のパスを格納したリスト\n anno_list : リスト\n アノテーションへのパスを格納したリスト\n phase : 'train' or 'test'\n 学習か訓練かを設定する。\n transform : object\n 前処理クラスのインスタンス\n transform_anno : object\n xmlのアノテーションをリストに変換するインスタンス\n \"\"\"\n\n def __init__(self, img_list, anno_list, phase, transform, transform_anno):\n self.img_list = img_list\n self.anno_list = anno_list\n self.phase = phase # train もしくは valを指定\n self.transform = transform # 画像の変形\n self.transform_anno = transform_anno # アノテーションデータをxmlからリストへ\n\n def __len__(self):\n '''画像の枚数を返す'''\n return len(self.img_list)\n\n def __getitem__(self, index):\n '''\n 前処理をした画像のテンソル形式のデータとアノテーションを取得\n '''\n im, gt, h, w = self.pull_item(index)\n return im, gt\n\n def pull_item(self, index):\n '''前処理をした画像のテンソル形式のデータ、アノテーション、画像の高さ、幅を取得する'''\n\n # 1. 画像読み込み\n image_file_path = self.img_list[index]\n img = cv2.imread(image_file_path) # [高さ][幅][色BGR]\n height, width, channels = img.shape # 画像のサイズを取得\n\n # 2. xml形式のアノテーション情報をリストに\n anno_file_path = self.anno_list[index]\n anno_list = self.transform_anno(anno_file_path, width, height)\n\n # 3. 前処理を実施\n img, boxes, labels = self.transform(\n img, self.phase, anno_list[:, :4], anno_list[:, 4])\n\n # 色チャネルの順番がBGRになっているので、RGBに順番変更\n # さらに(高さ、幅、色チャネル)の順を(色チャネル、高さ、幅)に変換\n img = torch.from_numpy(img[:, :, (2, 1, 0)]).permute(2, 0, 1)\n\n # BBoxとラベルをセットにしたnp.arrayを作成、変数名「gt」はground truth(答え)の略称\n gt = np.hstack((boxes, np.expand_dims(labels, axis=1)))\n\n return img, gt, height, width\n\n\ndef od_collate_fn(batch):\n \"\"\"\n Datasetから取り出すアノテーションデータのサイズが画像ごとに異なります。\n 画像内の物体数が2個であれば(2, 5)というサイズですが、3個であれば(3, 5)など変化します。\n この変化に対応したDataLoaderを作成するために、\n カスタイマイズした、collate_fnを作成します。\n collate_fnは、PyTorchでリストからmini-batchを作成する関数です。\n ミニバッチ分の画像が並んでいるリスト変数batchに、\n ミニバッチ番号を指定する次元を先頭に1つ追加して、リストの形を変形します。\n \"\"\"\n\n targets = []\n imgs = []\n for sample in batch:\n imgs.append(sample[0]) # sample[0] は画像imgです\n targets.append(torch.FloatTensor(sample[1])) # sample[1] はアノテーションgtです\n\n # imgsはミニバッチサイズのリストになっています\n # リストの要素はtorch.Size([3, 300, 300])です。\n # このリストをtorch.Size([batch_num, 3, 300, 300])のテンソルに変換します\n imgs = torch.stack(imgs, dim=0)\n\n # targetsはアノテーションデータの正解であるgtのリストです。\n # リストのサイズはミニバッチサイズです。\n # リストtargetsの要素は [n, 5] となっています。\n # nは画像ごとに異なり、画像内にある物体の数となります。\n # 5は [xmin, ymin, xmax, ymax, class_index] です\n\n return imgs, targets\n\n\n# 35層にわたる、vggモジュールを作成\ndef make_vgg():\n layers = []\n in_channels = 3 # 色チャネル数\n\n # vggモジュールで使用する畳み込み層やマックスプーリングのチャネル数\n cfg = [64, 64, 'M', 128, 128, 'M', 256, 256,\n 256, 'MC', 512, 512, 512, 'M', 512, 512, 512]\n\n for v in cfg:\n if v == 'M':\n layers += [nn.MaxPool2d(kernel_size=2, stride=2)]\n elif v == 'MC':\n # ceilは出力サイズを、計算結果(float)に対して、切り上げで整数にするモード\n # デフォルトでは出力サイズを計算結果(float)に対して、切り下げで整数にするfloorモード\n layers += [nn.MaxPool2d(kernel_size=2, stride=2, ceil_mode=True)]\n else:\n conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1)\n layers += [conv2d, nn.ReLU(inplace=True)]\n in_channels = v\n\n pool5 = nn.MaxPool2d(kernel_size=3, stride=1, padding=1)\n conv6 = nn.Conv2d(512, 1024, kernel_size=3, padding=6, dilation=6)\n conv7 = nn.Conv2d(1024, 1024, kernel_size=1)\n layers += [pool5, conv6,\n nn.ReLU(inplace=True), conv7, nn.ReLU(inplace=True)]\n return nn.ModuleList(layers)\n\n\n# 8層にわたる、extrasモジュールを作成\ndef make_extras():\n layers = []\n in_channels = 1024 # vggモジュールから出力された、extraに入力される画像チャネル数\n\n # extraモジュールの畳み込み層のチャネル数を設定するコンフィギュレーション\n cfg = [256, 512, 128, 256, 128, 256, 128, 256]\n\n layers += [nn.Conv2d(in_channels, cfg[0], kernel_size=(1))]\n layers += [nn.Conv2d(cfg[0], cfg[1], kernel_size=(3), stride=2, padding=1)]\n layers += [nn.Conv2d(cfg[1], cfg[2], kernel_size=(1))]\n layers += [nn.Conv2d(cfg[2], cfg[3], kernel_size=(3), stride=2, padding=1)]\n layers += [nn.Conv2d(cfg[3], cfg[4], kernel_size=(1))]\n layers += [nn.Conv2d(cfg[4], cfg[5], kernel_size=(3))]\n layers += [nn.Conv2d(cfg[5], cfg[6], kernel_size=(1))]\n layers += [nn.Conv2d(cfg[6], cfg[7], kernel_size=(3))]\n\n return nn.ModuleList(layers)\n\n\n# デフォルトボックスのオフセットを出力するloc_layers、\n# デフォルトボックスに対する各クラスの確率を出力するconf_layersを作成\n\n\ndef make_loc_conf(num_classes=21, bbox_aspect_num=[4, 6, 6, 6, 4, 4]):\n\n loc_layers = []\n conf_layers = []\n\n # VGGの22層目、conv4_3(source1)に対する畳み込み層\n loc_layers += [nn.Conv2d(512, bbox_aspect_num[0]\n * 4, kernel_size=3, padding=1)]\n conf_layers += [nn.Conv2d(512, bbox_aspect_num[0]\n * num_classes, kernel_size=3, padding=1)]\n\n # VGGの最終層(source2)に対する畳み込み層\n loc_layers += [nn.Conv2d(1024, bbox_aspect_num[1]\n * 4, kernel_size=3, padding=1)]\n conf_layers += [nn.Conv2d(1024, bbox_aspect_num[1]\n * num_classes, kernel_size=3, padding=1)]\n\n # extraの(source3)に対する畳み込み層\n loc_layers += [nn.Conv2d(512, bbox_aspect_num[2]\n * 4, kernel_size=3, padding=1)]\n conf_layers += [nn.Conv2d(512, bbox_aspect_num[2]\n * num_classes, kernel_size=3, padding=1)]\n\n # extraの(source4)に対する畳み込み層\n loc_layers += [nn.Conv2d(256, bbox_aspect_num[3]\n * 4, kernel_size=3, padding=1)]\n conf_layers += [nn.Conv2d(256, bbox_aspect_num[3]\n * num_classes, kernel_size=3, padding=1)]\n\n # extraの(source5)に対する畳み込み層\n loc_layers += [nn.Conv2d(256, bbox_aspect_num[4]\n * 4, kernel_size=3, padding=1)]\n conf_layers += [nn.Conv2d(256, bbox_aspect_num[4]\n * num_classes, kernel_size=3, padding=1)]\n\n # extraの(source6)に対する畳み込み層\n loc_layers += [nn.Conv2d(256, bbox_aspect_num[5]\n * 4, kernel_size=3, padding=1)]\n conf_layers += [nn.Conv2d(256, bbox_aspect_num[5]\n * num_classes, kernel_size=3, padding=1)]\n\n return nn.ModuleList(loc_layers), nn.ModuleList(conf_layers)\n\n\n# convC4_3からの出力をscale=20のL2Normで正規化する層\nclass L2Norm(nn.Module):\n def __init__(self, input_channels=512, scale=20):\n super(L2Norm, self).__init__() # 親クラスのコンストラクタ実行\n self.weight = nn.Parameter(torch.Tensor(input_channels))\n self.scale = scale # 係数weightの初期値として設定する値\n self.reset_parameters() # パラメータの初期化\n self.eps = 1e-10\n\n def reset_parameters(self):\n '''結合パラメータを大きさscaleの値にする初期化を実行'''\n init.constant_(self.weight, self.scale) # weightの値がすべてscale(=20)になる\n\n def forward(self, x):\n '''38×38の特徴量に対して、512チャネルにわたって2乗和のルートを求めた\n 38×38個の値を使用し、各特徴量を正規化してから係数をかけ算する層'''\n\n # 各チャネルにおける38×38個の特徴量のチャネル方向の2乗和を計算し、\n # さらにルートを求め、割り算して正規化する\n # normのテンソルサイズはtorch.Size([batch_num, 1, 38, 38])になります\n norm = x.pow(2).sum(dim=1, keepdim=True).sqrt()+self.eps\n x = torch.div(x, norm)\n\n # 係数をかける。係数はチャネルごとに1つで、512個の係数を持つ\n # self.weightのテンソルサイズはtorch.Size([512])なので\n # torch.Size([batch_num, 512, 38, 38])まで変形します\n weights = self.weight.unsqueeze(\n 0).unsqueeze(2).unsqueeze(3).expand_as(x)\n out = weights * x\n\n return out\n\n\n# デフォルトボックスを出力するクラス\nclass DBox(object):\n def __init__(self, cfg):\n super(DBox, self).__init__()\n\n # 初期設定\n self.image_size = cfg['input_size'] # 画像サイズの300\n # [38, 19, …] 各sourceの特徴量マップのサイズ\n self.feature_maps = cfg['feature_maps']\n self.num_priors = len(cfg[\"feature_maps\"]) # sourceの個数=6\n self.steps = cfg['steps'] # [8, 16, …] DBoxのピクセルサイズ\n\n self.min_sizes = cfg['min_sizes']\n # [30, 60, …] 小さい正方形のDBoxのピクセルサイズ(正確には面積)\n\n self.max_sizes = cfg['max_sizes']\n # [60, 111, …] 大きい正方形のDBoxのピクセルサイズ(正確には面積)\n\n self.aspect_ratios = cfg['aspect_ratios'] # 長方形のDBoxのアスペクト比\n\n def make_dbox_list(self):\n '''DBoxを作成する'''\n mean = []\n # 'feature_maps': [38, 19, 10, 5, 3, 1]\n for k, f in enumerate(self.feature_maps):\n for i, j in product(range(f), repeat=2): # fまでの数で2ペアの組み合わせを作る f_P_2 個\n # 特徴量の画像サイズ\n # 300 / 'steps': [8, 16, 32, 64, 100, 300],\n f_k = self.image_size / self.steps[k]\n\n # DBoxの中心座標 x,y ただし、0~1で規格化している\n cx = (j + 0.5) / f_k\n cy = (i + 0.5) / f_k\n\n # アスペクト比1の小さいDBox [cx,cy, width, height]\n # 'min_sizes': [30, 60, 111, 162, 213, 264]\n s_k = self.min_sizes[k]/self.image_size\n mean += [cx, cy, s_k, s_k]\n\n # アスペクト比1の大きいDBox [cx,cy, width, height]\n # 'max_sizes': [60, 111, 162, 213, 264, 315],\n s_k_prime = sqrt(s_k * (self.max_sizes[k]/self.image_size))\n mean += [cx, cy, s_k_prime, s_k_prime]\n\n # その他のアスペクト比のdefBox [cx,cy, width, height]\n for ar in self.aspect_ratios[k]:\n mean += [cx, cy, s_k*sqrt(ar), s_k/sqrt(ar)]\n mean += [cx, cy, s_k/sqrt(ar), s_k*sqrt(ar)]\n\n # DBoxをテンソルに変換 torch.Size([8732, 4])\n output = torch.Tensor(mean).view(-1, 4)\n\n # DBoxの大きさが1を超えている場合は1にする\n output.clamp_(max=1, min=0)\n\n return output\n\n\n# オフセット情報を使い、DBoxをBBoxに変換する関数\ndef decode(loc, dbox_list):\n \"\"\"\n オフセット情報を使い、DBoxをBBoxに変換する。\n\n Parameters\n ----------\n loc: [8732,4]\n SSDモデルで推論するオフセット情報。\n dbox_list: [8732,4]\n DBoxの情報\n\n Returns\n -------\n boxes : [xmin, ymin, xmax, ymax]\n BBoxの情報\n \"\"\"\n\n # DBoxは[cx, cy, width, height]で格納されている\n # locも[Δcx, Δcy, Δwidth, Δheight]で格納されている\n\n # オフセット情報からBBoxを求める\n boxes = torch.cat((\n dbox_list[:, :2] + loc[:, :2] * 0.1 * dbox_list[:, 2:],\n dbox_list[:, 2:] * torch.exp(loc[:, 2:] * 0.2)), dim=1)\n # boxesのサイズはtorch.Size([8732, 4])となります\n\n # BBoxの座標情報を[cx, cy, width, height]から[xmin, ymin, xmax, ymax] に\n boxes[:, :2] -= boxes[:, 2:] / 2 # 座標(xmin,ymin)へ変換\n boxes[:, 2:] += boxes[:, :2] # 座標(xmax,ymax)へ変換\n\n return boxes\n\n# Non-Maximum Suppressionを行う関数\n\n\ndef nm_suppression(boxes, scores, overlap=0.45, top_k=200):\n \"\"\"\n Non-Maximum Suppressionを行う関数。\n boxesのうち被り過ぎ(overlap以上)のBBoxを削除する。\n\n Parameters\n ----------\n boxes : [確信度閾値(0.01)を超えたBBox数,4]\n BBox情報。\n scores :[確信度閾値(0.01)を超えたBBox数]\n confの情報\n\n Returns\n -------\n keep : リスト\n confの降順にnmsを通過したindexが格納\n count:int\n nmsを通過したBBoxの数\n \"\"\"\n\n # returnのひな形を作成\n count = 0\n keep = scores.new(scores.size(0)).zero_().long()\n # keep:torch.Size([確信度閾値を超えたBBox数])、要素は全部0\n\n # 各BBoxの面積areaを計算\n x1 = boxes[:, 0]\n y1 = boxes[:, 1]\n x2 = boxes[:, 2]\n y2 = boxes[:, 3]\n area = torch.mul(x2 - x1, y2 - y1)\n\n # boxesをコピーする。後で、BBoxの被り度合いIOUの計算に使用する際のひな形として用意\n tmp_x1 = boxes.new()\n tmp_y1 = boxes.new()\n tmp_x2 = boxes.new()\n tmp_y2 = boxes.new()\n tmp_w = boxes.new()\n tmp_h = boxes.new()\n\n # socreを昇順に並び変える\n v, idx = scores.sort(0)\n\n # 上位top_k個(200個)のBBoxのindexを取り出す(200個存在しない場合もある)\n idx = idx[-top_k:]\n\n # idxの要素数が0でない限りループする\n while idx.numel() > 0:\n i = idx[-1] # 現在のconf最大のindexをiに\n\n # keepの現在の最後にconf最大のindexを格納する\n # このindexのBBoxと被りが大きいBBoxをこれから消去する\n keep[count] = i\n count += 1\n\n # 最後のBBoxになった場合は、ループを抜ける\n if idx.size(0) == 1:\n break\n\n # 現在のconf最大のindexをkeepに格納したので、idxをひとつ減らす\n idx = idx[:-1]\n\n # -------------------\n # これからkeepに格納したBBoxと被りの大きいBBoxを抽出して除去する\n # -------------------\n # ひとつ減らしたidxまでのBBoxを、outに指定した変数として作成する\n torch.index_select(x1, 0, idx, out=tmp_x1)\n torch.index_select(y1, 0, idx, out=tmp_y1)\n torch.index_select(x2, 0, idx, out=tmp_x2)\n torch.index_select(y2, 0, idx, out=tmp_y2)\n\n # すべてのBBoxに対して、現在のBBox=indexがiと被っている値までに設定(clamp)\n tmp_x1 = torch.clamp(tmp_x1, min=x1[i])\n tmp_y1 = torch.clamp(tmp_y1, min=y1[i])\n tmp_x2 = torch.clamp(tmp_x2, max=x2[i])\n tmp_y2 = torch.clamp(tmp_y2, max=y2[i])\n\n # wとhのテンソルサイズをindexを1つ減らしたものにする\n tmp_w.resize_as_(tmp_x2)\n tmp_h.resize_as_(tmp_y2)\n\n # clampした状態でのBBoxの幅と高さを求める\n tmp_w = tmp_x2 - tmp_x1\n tmp_h = tmp_y2 - tmp_y1\n\n # 幅や高さが負になっているものは0にする\n tmp_w = torch.clamp(tmp_w, min=0.0)\n tmp_h = torch.clamp(tmp_h, min=0.0)\n\n # clampされた状態での面積を求める\n inter = tmp_w*tmp_h\n\n # IoU = intersect部分 / (area(a) + area(b) - intersect部分)の計算\n rem_areas = torch.index_select(area, 0, idx) # 各BBoxの元の面積\n union = (rem_areas - inter) + area[i] # 2つのエリアのANDの面積\n IoU = inter/union\n\n # IoUがoverlapより小さいidxのみを残す\n idx = idx[IoU.le(overlap)] # leはLess than or Equal toの処理をする演算です\n # IoUがoverlapより大きいidxは、最初に選んでkeepに格納したidxと同じ物体に対してBBoxを囲んでいるため消去\n\n # whileのループが抜けたら終了\n\n return keep, count\n\n\n# SSDの推論時にconfとlocの出力から、被りを除去したBBoxを出力する\n\n\nclass Detect(Function):\n\n def __init__(self, conf_thresh=0.01, top_k=200, nms_thresh=0.45):\n self.softmax = nn.Softmax(dim=-1) # confをソフトマックス関数で正規化するために用意\n self.conf_thresh = conf_thresh # confがconf_thresh=0.01より高いDBoxのみを扱う\n self.top_k = top_k # nm_supressionでconfの高いtop_k個を計算に使用する, top_k = 200\n self.nms_thresh = nms_thresh # nm_supressionでIOUがnms_thresh=0.45より大きいと、同一物体へのBBoxとみなす\n\n def forward(self, loc_data, conf_data, dbox_list):\n \"\"\"\n 順伝搬の計算を実行する。\n\n Parameters\n ----------\n loc_data: [batch_num,8732,4]\n オフセット情報。\n conf_data: [batch_num, 8732,num_classes]\n 検出の確信度。\n dbox_list: [8732,4]\n DBoxの情報\n\n Returns\n -------\n output : torch.Size([batch_num, 21, 200, 5])\n (batch_num、クラス、confのtop200、BBoxの情報)\n \"\"\"\n\n # 各サイズを取得\n num_batch = loc_data.size(0) # ミニバッチのサイズ\n num_dbox = loc_data.size(1) # DBoxの数 = 8732\n num_classes = conf_data.size(2) # クラス数 = 21\n\n # confはソフトマックスを適用して正規化する\n conf_data = self.softmax(conf_data)\n\n # 出力の型を作成する。テンソルサイズは[minibatch数, 21, 200, 5]\n output = torch.zeros(num_batch, num_classes, self.top_k, 5)\n\n # cof_dataを[batch_num,8732,num_classes]から[batch_num, num_classes,8732]に順番変更\n conf_preds = conf_data.transpose(2, 1)\n\n # ミニバッチごとのループ\n for i in range(num_batch):\n\n # 1. locとDBoxから修正したBBox [xmin, ymin, xmax, ymax] を求める\n decoded_boxes = decode(loc_data[i], dbox_list)\n\n # confのコピーを作成\n conf_scores = conf_preds[i].clone()\n\n # 画像クラスごとのループ(背景クラスのindexである0は計算せず、index=1から)\n for cl in range(1, num_classes):\n\n # 2.confの閾値を超えたBBoxを取り出す\n # confの閾値を超えているかのマスクを作成し、\n # 閾値を超えたconfのインデックスをc_maskとして取得\n c_mask = conf_scores[cl].gt(self.conf_thresh)\n # gtはGreater thanのこと。gtにより閾値を超えたものが1に、以下が0になる\n # conf_scores:torch.Size([21, 8732])\n # c_mask:torch.Size([8732])\n\n # scoresはtorch.Size([閾値を超えたBBox数])\n scores = conf_scores[cl][c_mask]\n\n # 閾値を超えたconfがない場合、つまりscores=[]のときは、何もしない\n if scores.nelement() == 0: # nelementで要素数の合計を求める\n continue\n\n # c_maskを、decoded_boxesに適用できるようにサイズを変更します\n l_mask = c_mask.unsqueeze(1).expand_as(decoded_boxes)\n # l_mask:torch.Size([8732, 4])\n\n # l_maskをdecoded_boxesに適応します\n boxes = decoded_boxes[l_mask].view(-1, 4)\n # decoded_boxes[l_mask]で1次元になってしまうので、\n # viewで(閾値を超えたBBox数, 4)サイズに変形しなおす\n\n # 3. Non-Maximum Suppressionを実施し、被っているBBoxを取り除く\n ids, count = nm_suppression(\n boxes, scores, self.nms_thresh, self.top_k)\n # ids:confの降順にNon-Maximum Suppressionを通過したindexが格納\n # count:Non-Maximum Suppressionを通過したBBoxの数\n\n # outputにNon-Maximum Suppressionを抜けた結果を格納\n output[i, cl, :count] = torch.cat((scores[ids[:count]].unsqueeze(1),\n boxes[ids[:count]]), 1)\n\n return output # torch.Size([1, 21, 200, 5])\n\n# SSDクラスを作成する\n\n\nclass SSD(nn.Module):\n\n def __init__(self, phase, cfg):\n super(SSD, self).__init__()\n\n self.phase = phase # train or inferenceを指定\n self.num_classes = cfg[\"num_classes\"] # クラス数=21\n\n # SSDのネットワークを作る\n self.vgg = make_vgg()\n self.extras = make_extras()\n self.L2Norm = L2Norm()\n self.loc, self.conf = make_loc_conf(\n cfg[\"num_classes\"], cfg[\"bbox_aspect_num\"])\n\n # DBox作成\n dbox = DBox(cfg)\n self.dbox_list = dbox.make_dbox_list()\n\n # 推論時はクラス「Detect」を用意します\n if phase == 'inference':\n self.detect = Detect()\n\n def forward(self, x):\n sources = list() # locとconfへの入力source1~6を格納\n loc = list() # locの出力を格納\n conf = list() # confの出力を格納\n\n # vggのconv4_3まで計算する\n for k in range(23):\n x = self.vgg[k](x)\n\n # conv4_3の出力をL2Normに入力し、source1を作成、sourcesに追加\n source1 = self.L2Norm(x)\n sources.append(source1)\n\n # vggを最後まで計算し、source2を作成、sourcesに追加\n for k in range(23, len(self.vgg)):\n x = self.vgg[k](x)\n\n sources.append(x)\n\n # extrasのconvとReLUを計算\n # source3~6を、sourcesに追加\n for k, v in enumerate(self.extras):\n x = F.relu(v(x), inplace=True)\n if k % 2 == 1: # conv→ReLU→cov→ReLUをしたらsourceに入れる\n sources.append(x)\n\n # source1~6に、それぞれ対応する畳み込みを1回ずつ適用する\n # zipでforループの複数のリストの要素を取得\n # source1~6まであるので、6回ループが回る\n for (x, l, c) in zip(sources, self.loc, self.conf):\n # Permuteは要素の順番を入れ替え\n loc.append(l(x).permute(0, 2, 3, 1).contiguous())\n conf.append(c(x).permute(0, 2, 3, 1).contiguous())\n # l(x)とc(x)で畳み込みを実行\n # l(x)とc(x)の出力サイズは[batch_num, 4*アスペクト比の種類数, featuremapの高さ, featuremap幅]\n # sourceによって、アスペクト比の種類数が異なり、面倒なので順番入れ替えて整える\n # permuteで要素の順番を入れ替え、\n # [minibatch数, featuremap数, featuremap数,4*アスペクト比の種類数]へ\n # (注釈)\n # torch.contiguous()はメモリ上で要素を連続的に配置し直す命令です。\n # あとでview関数を使用します。\n # このviewを行うためには、対象の変数がメモリ上で連続配置されている必要があります。\n\n # さらにlocとconfの形を変形\n # locのサイズは、torch.Size([batch_num, 34928])\n # confのサイズはtorch.Size([batch_num, 183372])になる\n loc = torch.cat([o.view(o.size(0), -1) for o in loc], 1)\n conf = torch.cat([o.view(o.size(0), -1) for o in conf], 1)\n\n # さらにlocとconfの形を整える\n # locのサイズは、torch.Size([batch_num, 8732, 4])\n # confのサイズは、torch.Size([batch_num, 8732, 21])\n loc = loc.view(loc.size(0), -1, 4)\n conf = conf.view(conf.size(0), -1, self.num_classes)\n\n # 最後に出力する\n output = (loc, conf, self.dbox_list)\n\n if self.phase == \"inference\": # 推論時\n # クラス「Detect」のforwardを実行\n # 返り値のサイズは torch.Size([batch_num, 21, 200, 5])\n return self.detect(output[0], output[1], output[2])\n\n else: # 学習時\n return output\n # 返り値は(loc, conf, dbox_list)のタプル\n\n\nclass MultiBoxLoss(nn.Module):\n \"\"\"SSDの損失関数のクラスです。\"\"\"\n\n def __init__(self, jaccard_thresh=0.5, neg_pos=3, device='cpu'):\n super(MultiBoxLoss, self).__init__()\n self.jaccard_thresh = jaccard_thresh # 0.5 関数matchのjaccard係数の閾値\n self.negpos_ratio = neg_pos # 3:1 Hard Negative Miningの負と正の比率\n self.device = device # CPUとGPUのいずれで計算するのか\n\n def forward(self, predictions, targets):\n \"\"\"\n 損失関数の計算。\n\n Parameters\n ----------\n predictions : SSD netの訓練時の出力(tuple)\n (loc=torch.Size([num_batch, 8732, 4]), conf=torch.Size([num_batch, 8732, 21]), dbox_list=torch.Size [8732,4])。\n\n targets : [num_batch, num_objs, 5]\n 5は正解のアノテーション情報[xmin, ymin, xmax, ymax, label_ind]を示す\n\n Returns\n -------\n loss_l : テンソル\n locの損失の値\n loss_c : テンソル\n confの損失の値\n\n \"\"\"\n\n # SSDモデルの出力がタプルになっているので、個々にばらす\n loc_data, conf_data, dbox_list = predictions\n\n # 要素数を把握\n num_batch = loc_data.size(0) # ミニバッチのサイズ\n num_dbox = loc_data.size(1) # DBoxの数 = 8732\n num_classes = conf_data.size(2) # クラス数 = 21\n\n # 損失の計算に使用するものを格納する変数を作成\n # conf_t_label:各DBoxに一番近い正解のBBoxのラベルを格納させる\n # loc_t:各DBoxに一番近い正解のBBoxの位置情報を格納させる\n conf_t_label = torch.LongTensor(num_batch, num_dbox).to(self.device)\n loc_t = torch.Tensor(num_batch, num_dbox, 4).to(self.device)\n\n # loc_tとconf_t_labelに、\n # DBoxと正解アノテーションtargetsをmatchさせた結果を上書きする\n for idx in range(num_batch): # ミニバッチでループ\n\n # 現在のミニバッチの正解アノテーションのBBoxとラベルを取得\n truths = targets[idx][:, :-1].to(self.device) # BBox\n # ラベル [物体1のラベル, 物体2のラベル, …]\n labels = targets[idx][:, -1].to(self.device)\n\n # デフォルトボックスを新たな変数で用意\n dbox = dbox_list.to(self.device)\n\n # 関数matchを実行し、loc_tとconf_t_labelの内容を更新する\n # (詳細)\n # loc_t:各DBoxに一番近い正解のBBoxの位置情報が上書きされる\n # conf_t_label:各DBoxに一番近いBBoxのラベルが上書きされる\n # ただし、一番近いBBoxとのjaccard overlapが0.5より小さい場合は\n # 正解BBoxのラベルconf_t_labelは背景クラスの0とする\n variance = [0.1, 0.2]\n # このvarianceはDBoxからBBoxに補正計算する際に使用する式の係数です\n match(self.jaccard_thresh, truths, dbox,\n variance, labels, loc_t, conf_t_label, idx)\n\n # ----------\n # 位置の損失:loss_lを計算\n # Smooth L1関数で損失を計算する。ただし、物体を発見したDBoxのオフセットのみを計算する\n # ----------\n # 物体を検出したBBoxを取り出すマスクを作成\n pos_mask = conf_t_label > 0 # torch.Size([num_batch, 8732])\n\n # pos_maskをloc_dataのサイズに変形\n pos_idx = pos_mask.unsqueeze(pos_mask.dim()).expand_as(loc_data)\n\n # Positive DBoxのloc_dataと、教師データloc_tを取得\n loc_p = loc_data[pos_idx].view(-1, 4)\n loc_t = loc_t[pos_idx].view(-1, 4)\n\n # 物体を発見したPositive DBoxのオフセット情報loc_tの損失(誤差)を計算\n loss_l = F.smooth_l1_loss(loc_p, loc_t, reduction='sum')\n\n # ----------\n # クラス予測の損失:loss_cを計算\n # 交差エントロピー誤差関数で損失を計算する。ただし、背景クラスが正解であるDBoxが圧倒的に多いので、\n # Hard Negative Miningを実施し、物体発見DBoxと背景クラスDBoxの比が1:3になるようにする。\n # そこで背景クラスDBoxと予想したもののうち、損失が小さいものは、クラス予測の損失から除く\n # ----------\n batch_conf = conf_data.view(-1, num_classes)\n\n # クラス予測の損失を関数を計算(reduction='none'にして、和をとらず、次元をつぶさない)\n loss_c = F.cross_entropy(\n batch_conf, conf_t_label.view(-1), reduction='none')\n\n # -----------------\n # これからNegative DBoxのうち、Hard Negative Miningで抽出するものを求めるマスクを作成します\n # -----------------\n\n # 物体発見したPositive DBoxの損失を0にする\n # (注意)物体はlabelが1以上になっている。ラベル0は背景。\n num_pos = pos_mask.long().sum(1, keepdim=True) # ミニバッチごとの物体クラス予測の数\n loss_c = loss_c.view(num_batch, -1) # torch.Size([num_batch, 8732])\n loss_c[pos_mask] = 0 # 物体を発見したDBoxは損失0とする\n\n # Hard Negative Miningを実施する\n # 各DBoxの損失の大きさloss_cの順位であるidx_rankを求める\n _, loss_idx = loss_c.sort(1, descending=True)\n _, idx_rank = loss_idx.sort(1)\n\n # (注釈)\n # 実装コードがかなり特殊で直感的ではないです。\n # 上記2行は、要は各DBoxに対して、損失の大きさが何番目なのかの情報を\n # 変数idx_rankとして高速に取得したいというコードです。\n #\n # DBOXの損失値の大きい方から降順に並べ、DBoxの降順のindexをloss_idxに格納。\n # 損失の大きさloss_cの順位であるidx_rankを求める。\n # ここで、\n # 降順になった配列indexであるloss_idxを、0から8732まで昇順に並べ直すためには、\n # 何番目のloss_idxのインデックスをとってきたら良いのかを示すのが、idx_rankである。\n # 例えば、\n # idx_rankの要素0番目 = idx_rank[0]を求めるには、loss_idxの値が0の要素、\n # つまりloss_idx[?}=0 の、?は何番かを求めることになる。ここで、? = idx_rank[0]である。\n # いま、loss_idx[?]=0の0は、元のloss_cの要素の0番目という意味である。\n # つまり?は、元のloss_cの要素0番目は、降順に並び替えられたloss_idxの何番目ですか\n # を求めていることになり、 結果、\n # ? = idx_rank[0] はloss_cの要素0番目が、降順の何番目かを示すことになる。\n\n # 背景のDBoxの数num_negを決める。HardNegative Miningにより、\n # 物体発見のDBoxの数num_posの3倍(self.negpos_ratio倍)とする。\n # ただし、万が一、DBoxの数を超える場合は、DBoxの数を上限とする\n num_neg = torch.clamp(num_pos*self.negpos_ratio, max=num_dbox)\n\n # idx_rankは各DBoxの損失の大きさが上から何番目なのかが入っている\n # 背景のDBoxの数num_negよりも、順位が低い(すなわち損失が大きい)DBoxを取るマスク作成\n # torch.Size([num_batch, 8732])\n neg_mask = idx_rank < (num_neg).expand_as(idx_rank)\n\n # -----------------\n # (終了)これからNegative DBoxのうち、Hard Negative Miningで抽出するものを求めるマスクを作成します\n # -----------------\n\n # マスクの形を整形し、conf_dataに合わせる\n # pos_idx_maskはPositive DBoxのconfを取り出すマスクです\n # neg_idx_maskはHard Negative Miningで抽出したNegative DBoxのconfを取り出すマスクです\n # pos_mask:torch.Size([num_batch, 8732])→pos_idx_mask:torch.Size([num_batch, 8732, 21])\n pos_idx_mask = pos_mask.unsqueeze(2).expand_as(conf_data)\n neg_idx_mask = neg_mask.unsqueeze(2).expand_as(conf_data)\n\n # conf_dataからposとnegだけを取り出してconf_hnmにする。形はtorch.Size([num_pos+num_neg, 21])\n conf_hnm = conf_data[(pos_idx_mask+neg_idx_mask).gt(0)\n ].view(-1, num_classes)\n # (注釈)gtは greater than (>)の略称。これでmaskが1のindexを取り出す。\n # pos_idx_mask+neg_idx_maskは足し算だが、indexへのmaskをまとめているだけである。\n # つまり、posであろうがnegであろうが、マスクが1のものを足し算で一つのリストにし、それをgtで取得\n\n # 同様に教師データであるconf_t_labelからposとnegだけを取り出してconf_t_label_hnmに\n # 形はtorch.Size([pos+neg])になる\n conf_t_label_hnm = conf_t_label[(pos_mask+neg_mask).gt(0)]\n\n # confidenceの損失関数を計算(要素の合計=sumを求める)\n loss_c = F.cross_entropy(conf_hnm, conf_t_label_hnm, reduction='sum')\n\n # 物体を発見したBBoxの数N(全ミニバッチの合計)で損失を割り算\n N = num_pos.sum()\n loss_l /= N\n loss_c /= N\n\n return loss_l, loss_c\n"
]
| [
[
"torch.nn.Softmax",
"numpy.expand_dims",
"torch.zeros",
"torch.FloatTensor",
"torch.nn.functional.smooth_l1_loss",
"torch.from_numpy",
"torch.mul",
"torch.index_select",
"torch.div",
"torch.LongTensor",
"torch.nn.init.constant_",
"torch.nn.ModuleList",
"torch.nn.Conv2d",
"torch.nn.ReLU",
"torch.exp",
"torch.stack",
"numpy.array",
"torch.Tensor",
"torch.nn.functional.cross_entropy",
"torch.nn.MaxPool2d",
"torch.clamp"
]
]
|
abstractpaper/prop | [
"f2ca127119ffbfb3f7d2855eff7e7473e0bb3a80"
]
| [
"tests/buffers/priority_rep_buffer_test.py"
]
| [
"import pytest\nimport numpy as np\nimport torch\nimport random\nfrom collections import namedtuple\nfrom prop.buffers.priority_replay_buffer import PrioritizedReplayBuffer\n\nTransition = namedtuple('Transition',\n ('state', 'action', 'next_state', 'reward', 'mask'))\n\[email protected]\ndef buffer():\n buffer = PrioritizedReplayBuffer(capacity=1000)\n return buffer\n\ndef test_push(buffer):\n assert buffer.tree.n_entries == 0\n for _ in range(10):\n buffer.push(0.5, Transition(np.zeros(9), [1], None, 1, np.zeros(3)))\n assert buffer.tree.n_entries == 10\n\ndef test_sample(buffer):\n # add 1000 samples with error (priority) increasing for each n\n for n in range(1000):\n sample = Transition(np.zeros(9), [n], None, n, np.zeros(3))\n buffer.push(n/1000, sample)\n\n def normalize(a):\n max_n = max(a)\n return [v/max_n for v in a]\n\n results = []\n for _ in range(100):\n batch, _, _ = buffer.sample(32)\n\n # reward=n\n td = sorted([b.reward for b in batch])\n # normalize\n td_normalized = np.array(normalize(td))\n\n # sample from an exponential curve\n exp_curve = sorted(np.random.exponential(size=32))\n # normalize\n exp_curve_normalized = np.array(normalize(exp_curve))\n\n # calculate MSE for both lists\n mse = ((td_normalized - exp_curve_normalized)**2).mean(axis=0)\n results.append(mse)\n\n # assert that the two curves don't deviate much; meaning that our buffer\n # is sampling transitions with higher priorities more often.\n assert max(results) < 0.5\n \ndef test_update(buffer):\n for n in range(10):\n buffer.push(n/10, Transition(np.zeros(9), [n], None, n, np.zeros(3)))\n buffer.update(1000, 0.9)\n # assert new priority = (error + epsilon) ^ alpha\n assert buffer.tree.tree[1000] == (np.abs(0.9) + buffer.e) ** buffer.alpha"
]
| [
[
"numpy.random.exponential",
"numpy.zeros",
"numpy.abs"
]
]
|
amueller/scikit-learn_bench | [
"4752e4590c11cdd6c13a4af5aaf9f88e8a86ecbb"
]
| [
"sklearn/distances.py"
]
| [
"# Copyright (C) 2017-2019 Intel Corporation\n#\n# SPDX-License-Identifier: MIT\n\nimport argparse\nfrom bench import parse_args, time_mean_min, print_header, print_row\nimport numpy as np\nfrom sklearn.metrics.pairwise import pairwise_distances\n\nparser = argparse.ArgumentParser(description='scikit-learn pairwise distances '\n 'benchmark')\nparser.add_argument('--metrics', nargs='*', default=['cosine', 'correlation'],\n help='Metrics to test for pairwise_distances')\nparams = parse_args(parser, size=(1000, 150000), dtypes=('f8', 'f4'))\n\n# Generate random data\nX = np.random.rand(*params.shape).astype(params.dtype)\n\ncolumns = ('batch', 'arch', 'prefix', 'function', 'threads', 'dtype', 'size',\n 'time')\nprint_header(columns, params)\n\nfor metric in params.metrics:\n time, _ = time_mean_min(pairwise_distances, X, metric=metric,\n n_jobs=params.n_jobs,\n outer_loops=params.outer_loops,\n inner_loops=params.inner_loops)\n print_row(columns, params, function=metric.capitalize(), time=time)\n"
]
| [
[
"numpy.random.rand"
]
]
|
mevol/metric_ml | [
"f09ef35eeec8fe64fce83bb238f1ba75362856ce"
]
| [
"metrix_ml/decisiontree_ada_randomsearch_scaled.py"
]
| [
"###############################################################################\n#\n# imports and set up environment\n#\n###############################################################################\n'''Defining the environment for this class'''\nimport argparse\nimport pandas as pd\nimport os\nimport numpy as np\nimport joblib\nimport logging\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.model_selection import RandomizedSearchCV\nfrom sklearn.preprocessing import StandardScaler\nfrom datetime import datetime\nfrom scipy.stats import randint\nfrom scipy.stats import uniform\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom tbx import get_confidence_interval, feature_importances_best_estimator\nfrom tbx import feature_importances_error_bars, confusion_matrix_and_stats\nfrom tbx import training_cv_stats, testing_predict_stats, plot_hist_pred_proba\nfrom tbx import plot_precision_recall_vs_threshold, plot_roc_curve, evaluate_threshold\nfrom tbx import calibrate_classifier, plot_radar_chart, print_to_consol\n\ndef make_output_folder(outdir):\n '''A small function for making an output directory\n Args:\n outdir (str): user provided directory where the output directory will be created\n output_dir (str): the newly created output directory named\n \"decisiontree_ada_randomsearch_scaled\"\n Yields:\n directory\n '''\n output_dir = os.path.join(outdir, 'decisiontree_ada_randomsearch_scaled')\n os.makedirs(output_dir, exist_ok=True)\n return output_dir\n\nclass TreeAdaBoostRandSearch():\n ''' A class to conduct a randomised search and training for best parameters for a\n decision tree classifier with AdaBoost; the following steps are executed:\n * loading input data in CSV format\n * creating output directory to write results files to\n * set up a log file to keep note of stats and processes\n * prepare the input data by splitting into a calibration (5%), testing (20%) and\n training (80%) sets and applying StandardScaler\n * conduct randomised search to find best parameters for the best predictor\n * save model to disk\n * get 95% confidence interval for uncalibrated classifier\n * get feature importances\n * get statistics for training using 3-fold cross-validation and testing\n * get more detailed statistics and plots for prediction performances on the testing\n set; this includes a confusion matrix, histogram of prediction probabilities,\n precision-recall curve and ROC curve\n * explore sensitivity/specificity trade-off when using different probability\n thresholds\n * calibrate the predictor and write the calibrated version to disk\n * get 95% confidence interval for calibrated classifier\n\n Args:\n\n data (str): file path to the input CSV file\n directory (str): target output directory where an output folder will be created\n and all results will be written to\n numf (int): maximum number of features to use in training; default = 10\n numc (int): number of search cycles for randomised search; default = 500\n cv (int): number of cross-validation cycles to use during training; default = 3\n bootiter (int): number of bootstrap cylces to use for getting confidence\n intervals; default = 1000\n\n Yields:\n trained predictor: \"best_predictor_<date>.pkl\"\n trained and calibrated predictor: \"best_predictor_calibrated_<date>.pkl\"\n logfile: \"decisiontree_ada_randomsearch.log\"\n plots: \"bootstrap_hist_uncalibrated_<date>.png\"\n \"feature_importances_best_bar_plot_<date>.png\"\n \"feature_importances_all_error_bars_<date>.png\"\n \"confusion_matrix_for_test_set_<date>.png\"\n \"hist_pred_proba_<date>.png\"\n \"Precision_Recall_<date>.png\"\n \"ROC_curve_<date>.png\"\n \"bootstrap_hist_calibrated_<date>.png\"\n \"radar_plot_prediction_metrics<date>.png\"\n '''\n def __init__(self, data, directory, numf, numc, cv, bootiter):\n self.numf = numf\n self.numc = numc\n self.cv = cv\n self.bootiter = bootiter\n self.data = pd.read_csv(data)\n self.directory = make_output_folder(directory)\n\n logging.basicConfig(level=logging.INFO, filename=os.path.join(self.directory,\n 'decisiontree_ada_randomsearch.log'), filemode='w')\n logging.info(f'Loaded input data \\n'\n f'Created output directories at {self.directory} \\n')\n\n self.start = datetime.now()\n\n self.prepare_data()\n self.randomised_search()\n self.get_training_testing_prediction_stats()\n self.detailed_analysis()\n\n###############################################################################\n#\n# prepare input data\n#\n###############################################################################\n\n def prepare_data(self):\n print_to_consol('Preparing input data and split in train/test/calibration set')\n\n for name in self.data.columns:\n if 'success' in name or \"ground_truth\" in name:\n y = self.data[name]\n X = self.data.drop([name, 'Unnamed: 0'], axis=1).select_dtypes(\n exclude=['object'])\n\n # create a 5% calibration set if needed\n X_temp, X_cal, y_temp, self.y_cal = train_test_split(X, y, test_size=0.05,\n random_state=42)\n\n # use the remaining data for 80/20 train-test split\n X_train, X_test, self.y_train, self.y_test = train_test_split(X_temp,\n y_temp,\n test_size=0.2,\n random_state=100)\n\n scaler = StandardScaler()\n scaler.fit(X_train)\n X_train_scaled = scaler.transform(X_train)\n X_test_scaled = scaler.transform(X_test)\n X_cal_scaled = scaler.transform(X_cal)\n \n self.X_train_scaled = pd.DataFrame(data=X_train_scaled,\n index=X_train.index,\n columns=X_train.columns)\n self.X_test_scaled = pd.DataFrame(data=X_test_scaled,\n index=X_test.index,\n columns=X_test.columns)\n \n self.X_cal_scaled = pd.DataFrame(data=X_cal_scaled,\n index=X_cal.index,\n columns=X_cal.columns)\n\n logging.info(f'Created test, train and validation set \\n'\n f'Scaling the train set and applying to test set and calibration set \\n')\n\n###############################################################################\n#\n# randomized search\n#\n###############################################################################\n\n def randomised_search(self):\n print_to_consol('Running randomized search to find best classifier')\n\n #create the decision forest\n clf1 = DecisionTreeClassifier(random_state=20,\n class_weight='balanced',\n max_features = self.numf)\n\n ada = AdaBoostClassifier(base_estimator=clf1,\n algorithm =\"SAMME.R\",\n random_state=55)\n\n logging.info(f'Initialised classifier using balanced class weights \\n')\n\n #set up randomized search\n param_dict = {\n 'base_estimator__criterion': ['gini', 'entropy'],\n 'n_estimators': randint(100, 10000),#number of base estimators to use\n 'learning_rate': uniform(0.0001, 1.0),\n 'base_estimator__min_samples_split': randint(2, 20),\n 'base_estimator__max_depth': randint(1, 10),\n 'base_estimator__min_samples_leaf': randint(1, 20),\n 'base_estimator__max_leaf_nodes': randint(10, 20)}\n\n logging.info(f'Following parameters will be explored in randomized search \\n'\n f'{param_dict} \\n')\n\n #building and running the randomized search\n rand_search = RandomizedSearchCV(ada, param_dict, random_state=5,\n cv=self.cv, n_iter=self.numc,\n scoring='accuracy', n_jobs=-1)\n\n rand_search_fitted = rand_search.fit(self.X_train_scaled,\n self.y_train)\n \n best_parameters = rand_search_fitted.best_params_\n best_scores = rand_search_fitted.best_score_\n\n logging.info(f'Running randomised search for best patameters of classifier \\n'\n f'Best parameters found: {best_parameters} \\n'\n f'Best accuracy scores found: {best_scores} \\n')\n \n self.model = rand_search_fitted.best_estimator_\n\n datestring = datetime.strftime(datetime.now(), '%Y%m%d_%H%M')\n joblib.dump(self.model, os.path.join(self.directory,\n 'best_predictor_'+datestring+'.pkl'))\n\n logging.info(f'Writing best classifier to disk in {self.directory} \\n')\n\n print_to_consol('Getting 95% confidence interval for uncalibrated classifier')\n\n alpha, upper, lower = get_confidence_interval(self.X_train_scaled, self.y_train,\n self.X_test_scaled, self.y_test,\n self.model, self.directory,\n self.bootiter, 'uncalibrated')\n\n logging.info(f'{alpha}% confidence interval {upper}% and {lower}% \\n'\n f'for uncalibrated classifier. \\n')\n\n print_to_consol('Getting feature importances for best classifier')\n\n best_clf_feat_import = self.model.feature_importances_\n best_clf_feat_import_sorted = sorted(zip(best_clf_feat_import,\n self.X_train_scaled.columns),\n reverse=True)\n\n logging.info(f'Feature importances for best classifier {best_clf_feat_import_sorted} \\n')\n\n all_clf_feat_import_mean = np.mean(\n [tree.feature_importances_ for tree in self.model.estimators_], axis=0)\n all_clf_feat_import_mean_sorted = sorted(zip(all_clf_feat_import_mean,\n self.X_train_scaled.columns),\n reverse=True)\n\n print_to_consol('Plotting feature importances for best classifier')\n\n feature_importances_best_estimator(best_clf_feat_import_sorted, self.directory)\n logging.info(f'Plotting feature importances for best classifier in decreasing order \\n')\n feature_importances_error_bars(self.model, self.X_train_scaled.columns, self.directory)\n logging.info(f'Plotting feature importances for best classifier with errorbars \\n')\n\n###############################################################################\n#\n# get training and testing stats\n#\n###############################################################################\n\n def get_training_testing_prediction_stats(self):\n print_to_consol('Getting basic stats for training set and cross-validation')\n\n training_stats, y_train_pred, y_train_pred_proba = training_cv_stats(\n self.model, self.X_train_scaled,\n self.y_train, self.cv)\n\n logging.info(f'Basic stats achieved for training set and 3-fold CV \\n'\n f'Accuracy for each individual fold of 3 CV folds: {training_stats[\"acc_cv\"]} \\n'\n f'Accuracy across all 3 CV-folds: {training_stats[\"acc\"]} \\n'\n f'ROC_AUC across all 3 CV-folds: {training_stats[\"roc_auc\"]} \\n'\n f'Recall across all 3 CV-folds: {training_stats[\"recall\"]} \\n'\n f'Precision across all 3 CV-folds: {training_stats[\"precision\"]} \\n'\n f'F1 score across all 3 CV-folds: {training_stats[\"f1-score\"]} \\n'\n f'Storing cross-validated y_train classes in y_train_pred \\n'\n f'Storing cross-validated y_train probabilities in y_train_pred_proba \\n')\n\n print_to_consol('Getting class predictions and probabilities for test set')\n\n test_stats, self.y_pred, self.y_pred_proba = testing_predict_stats(\n self.model, self.X_test_scaled, self.y_test)\n\n logging.info(f'Predicting on the test set. \\n'\n f'Storing classes in y_pred and probabilities in y_pred_proba \\n')\n\n print_to_consol(\n 'Calculate prediction stats for y_pred and y_pred_proba of test set')\n\n logging.info(f'Basic stats on the test set. \\n'\n f'Prediction accuracy on the test set: {test_stats[\"predict_acc\"]} \\n'\n f'Class distributio in the test set: {test_stats[\"class_distribution\"]} \\n'\n f'Matthews Correlation Coefficient: {test_stats[\"mcc\"]} \\n'\n f'Average number of class 1 samples: {test_stats[\"class_one\"]} \\n'\n f'Average number of class 0 samples: {test_stats[\"class_zero\"]} \\n'\n f'Null accuracy: {test_stats[\"null_acc\"]} \\n')\n\n print_to_consol(\n 'Plotting histogram for class 1 prediction probabilities for test set')\n\n #store the predicted probabilities for class 1 of test set\n self.y_pred_proba_ones = self.y_pred_proba[:, 1]\n\n plot_hist_pred_proba(self.y_pred_proba_ones, self.directory)\n\n logging.info(\n f'Plotting prediction probabilities for class 1 in test set in histogram. \\n')\n\n###############################################################################\n#\n# get more detailed stats and plots\n#\n###############################################################################\n\n def detailed_analysis(self):\n print_to_consol('Making a confusion matrix for test set classification outcomes')\n\n matrix_stats = confusion_matrix_and_stats(self.y_test, self.y_pred,\n 'before_cal', self.directory)\n\n logging.info(f'Detailed analysis of confusion matrix for test set. \\n'\n f'True positives: {matrix_stats[\"TP\"]} \\n'\n f'True negatives: {matrix_stats[\"TN\"]} \\n'\n f'False positives: {matrix_stats[\"FP\"]} \\n'\n f'False negatives: {matrix_stats[\"FN\"]} \\n'\n f'Classification accuracy: {matrix_stats[\"acc\"]} \\n'\n f'Classification error: {matrix_stats[\"err\"]} \\n'\n f'Sensitivity: {matrix_stats[\"sensitivity\"]} \\n'\n f'Specificity: {matrix_stats[\"specificity\"]} \\n'\n f'False positive rate: {matrix_stats[\"FP-rate\"]} \\n'\n f'False negative rate: {matrix_stats[\"FN-rate\"]} \\n'\n f'Precision: {matrix_stats[\"precision\"]} \\n'\n f'F1-score: {matrix_stats[\"F1-score\"]} \\n')\n\n print_to_consol(\n 'Plotting precision recall curve for test set class 1 probabilities')\n\n logging.info(\n f'Plotting precision recall curve for class 1 in test set probabilities. \\n')\n \n plot_precision_recall_vs_threshold(self.y_test, self.y_pred_proba_ones,\n self.directory)\n\n print_to_consol(\n 'Plotting ROC curve ad calculating AUC for test set class 1 probabilities')\n\n logging.info(\n f'Plotting ROC curve for class 1 in test set probabilities. \\n')\n\n self.fpr, self.tpr, self.thresholds = plot_roc_curve(self.y_test,\n self.y_pred_proba_ones, self.directory)\n\n AUC = round(roc_auc_score(self.y_test, self.y_pred_proba_ones) * 100, 2)\n\n logging.info(\n f'Calculating AUC for ROC curve for class 1 in test set probabilities: {AUC} \\n')\n\n print_to_consol('Make a radar plot for performance metrics')\n\n radar_dict = {'Classification accuracy' : matrix_stats[\"acc\"],\n 'Classification error' : matrix_stats[\"err\"],\n 'Sensitivity' : matrix_stats[\"sensitivity\"],\n 'Specificity' : matrix_stats[\"specificity\"],\n 'False positive rate' : matrix_stats[\"FP-rate\"],\n 'False negative rate' : matrix_stats[\"FN-rate\"],\n 'Precision' : matrix_stats[\"precision\"],\n 'F1-score' : matrix_stats[\"F1-score\"],\n 'ROC AUC' : AUC}\n\n plot_radar_chart(radar_dict, self.directory)\n\n print_to_consol(\n 'Exploring probability thresholds, sensitivity, specificity for class 1')\n\n threshold_dict = evaluate_threshold(self.tpr, self.fpr, self.thresholds)\n\n logging.info(\n f'Exploring different probability thresholds and sensitivity-specificity trade-offs. \\n'\n f'Threshold 0.2: {threshold_dict[\"0.2\"]} \\n'\n f'Threshold 0.3: {threshold_dict[\"0.3\"]} \\n'\n f'Threshold 0.4: {threshold_dict[\"0.4\"]} \\n'\n f'Threshold 0.5: {threshold_dict[\"0.5\"]} \\n'\n f'Threshold 0.6: {threshold_dict[\"0.6\"]} \\n'\n f'Threshold 0.7: {threshold_dict[\"0.7\"]} \\n'\n f'Threshold 0.8: {threshold_dict[\"0.8\"]} \\n'\n f'Threshold 0.9: {threshold_dict[\"0.9\"]} \\n')\n\n print_to_consol(\n 'Calibrating classifier and writing to disk; getting new accuracy')\n\n self.calibrated_clf, clf_acc = calibrate_classifier(self.model, self.X_cal_scaled,\n self.y_cal)\n\n date = datetime.strftime(datetime.now(), '%Y%m%d_%H%M')\n joblib.dump(self.calibrated_clf, os.path.join(self.directory,\n 'best_calibrated_predictor_'+date+'.pkl'))\n\n logging.info(\n f'Calibrated the best classifier with X_cal and y_cal and new accuracy {clf_acc}\\n'\n f'Writing file to disk disk in {self.directory} \\n')\n\n print_to_consol('Getting 95% confidence interval for calibrated classifier')\n\n alpha, upper, lower = get_confidence_interval(self.X_train_scaled, self.y_train,\n self.X_test_scaled, self.y_test,\n self.calibrated_clf, self.directory,\n self.bootiter, 'calibrated')\n\n logging.info(f'{alpha}% confidence interval {upper}% and {lower}% \\n'\n f'for calibrated classifier. \\n')\n\n print_to_consol('Running prediction for calibrated classifier')\n\n print_to_consol(\n 'Getting class predictions and probabilities for test set with calibrated classifier')\n\n test_stats_cal, self.y_pred_cal, self.y_pred_proba_cal = testing_predict_stats(\n self.calibrated_clf,\n self.X_test_scaled, self.y_test)\n\n logging.info(\n f'Predicting on the test set with calibrated classifier. \\n'\n f'Storing classes for calibrated classifier in y_pred and probabilities in y_pred_proba. \\n')\n\n print_to_consol(\n 'Calculate prediction stats for y_pred and y_pred_proba of test set with calibrated classifier')\n\n logging.info(f'Basic stats on the test set woth calibrated classifier. \\n'\n f'Prediction accuracy on the test set: {test_stats_cal[\"predict_acc\"]} \\n'\n f'Class distributio in the test set: {test_stats_cal[\"class_distribution\"]} \\n'\n f'Matthews Correlation Coefficient: {test_stats_cal[\"mcc\"]} \\n'\n f'Average number of class 1 samples: {test_stats_cal[\"class_one\"]} \\n'\n f'Average number of class 0 samples: {test_stats_cal[\"class_zero\"]} \\n'\n f'Null accuracy: {test_stats_cal[\"null_acc\"]} \\n')\n\n print_to_consol(\n 'Plotting histogram for class 1 prediction probabilities for test set')\n\n #store the predicted probabilities for class 1 of test set\n self.y_pred_proba_cal_ones = self.y_pred_proba_cal[:, 1]\n\n plot_hist_pred_proba(self.y_pred_proba_cal_ones, self.directory)\n\n logging.info(\n f'Plotting prediction probabilities for class 1 in test set in histogram for calibrated classifier. \\n')\n\n print_to_consol(\n 'Making a confusion matrix for test set classification outcomes with calibrated classifier')\n\n matrix_stats_cal = confusion_matrix_and_stats(self.y_test, self.y_pred_cal,\n 'after_cal', self.directory)\n\n logging.info(f'Detailed analysis of confusion matrix for test set with calibrated classifier. \\n'\n f'True positives: {matrix_stats_cal[\"TP\"]} \\n'\n f'True negatives: {matrix_stats_cal[\"TN\"]} \\n'\n f'False positives: {matrix_stats_cal[\"FP\"]} \\n'\n f'False negatives: {matrix_stats_cal[\"FN\"]} \\n'\n f'Classification accuracy: {matrix_stats_cal[\"acc\"]} \\n'\n f'Classification error: {matrix_stats_cal[\"err\"]} \\n'\n f'Sensitivity: {matrix_stats_cal[\"sensitivity\"]} \\n'\n f'Specificity: {matrix_stats_cal[\"specificity\"]} \\n'\n f'False positive rate: {matrix_stats_cal[\"FP-rate\"]} \\n'\n f'False negative rate: {matrix_stats_cal[\"FN-rate\"]} \\n'\n f'Precision: {matrix_stats_cal[\"precision\"]} \\n'\n f'F1-score: {matrix_stats_cal[\"F1-score\"]} \\n')\n\n print_to_consol(\n 'Plotting precision recall curve for test set class 1 probabilities with calibrated classifier')\n\n logging.info(\n f'Plotting precision recall curve for class 1 in test set probabilities with calibrated classifier. \\n')\n \n plot_precision_recall_vs_threshold(self.y_test, self.y_pred_proba_cal_ones,\n self.directory)\n\n print_to_consol(\n 'Plotting ROC curve ad calculating AUC for test set class 1 probabilities with calibrated classifier')\n\n logging.info(\n f'Plotting ROC curve for class 1 in test set probabilities with calibrated classifier. \\n')\n\n self.fpr_cal, self.tpr_cal, self.thresholds_cal = plot_roc_curve(self.y_test,\n self.y_pred_proba_cal_ones, self.directory)\n\n AUC_cal = round(roc_auc_score(self.y_test, self.y_pred_proba_cal_ones) * 100, 2)\n\n logging.info(\n f'Calculating AUC for ROC curve for class 1 in test set probabilities with calibrated classifier: {AUC_cal} \\n')\n\n print_to_consol('Make a radar plot for performance metrics with calibrated classifier')\n\n radar_dict_cal = {'Classification accuracy' : matrix_stats_cal[\"acc\"],\n 'Classification error' : matrix_stats_cal[\"err\"],\n 'Sensitivity' : matrix_stats_cal[\"sensitivity\"],\n 'Specificity' : matrix_stats_cal[\"specificity\"],\n 'False positive rate' : matrix_stats_cal[\"FP-rate\"],\n 'False negative rate' : matrix_stats_cal[\"FN-rate\"],\n 'Precision' : matrix_stats_cal[\"precision\"],\n 'F1-score' : matrix_stats_cal[\"F1-score\"],\n 'ROC AUC' : AUC_cal}\n\n plot_radar_chart(radar_dict_cal, self.directory)\n\n print_to_consol(\n 'Exploring probability thresholds, sensitivity, specificity for class 1 with calibrated classifier')\n\n threshold_dict_cal = evaluate_threshold(self.tpr_cal, self.fpr_cal, self.thresholds_cal)\n\n logging.info(\n f'Exploring different probability thresholds and sensitivity-specificity trade-offs \\n'\n f'for calibrated classifier. \\n'\n f'Threshold 0.2: {threshold_dict_cal[\"0.2\"]} \\n'\n f'Threshold 0.3: {threshold_dict_cal[\"0.3\"]} \\n'\n f'Threshold 0.4: {threshold_dict_cal[\"0.4\"]} \\n'\n f'Threshold 0.5: {threshold_dict_cal[\"0.5\"]} \\n'\n f'Threshold 0.6: {threshold_dict_cal[\"0.6\"]} \\n'\n f'Threshold 0.7: {threshold_dict_cal[\"0.7\"]} \\n'\n f'Threshold 0.8: {threshold_dict_cal[\"0.8\"]} \\n'\n f'Threshold 0.9: {threshold_dict_cal[\"0.9\"]} \\n')\n\n end = datetime.now()\n duration = end - self.start\n\n logging.info(f'Training lasted for {duration} minutes \\n')\n\n logging.info(f'Training completed \\n')\n\n print_to_consol('Training completed')\n\n\ndef run(input_csv, output_dir, features, cycles, boot_iter, cv):\n\n TreeAdaBoostRandSearch(input_csv, output_dir, features, cycles, boot_iter, cv)\n\n\n\ndef main():\n '''defining the command line input to make it runable'''\n parser = argparse.ArgumentParser(description='AdaBoost and DecisionTree randomized search')\n\n parser.add_argument(\n '--input', \n type=str, \n dest='input',\n default='',\n help='The input CSV file')\n\n parser.add_argument(\n '--outdir',\n type=str,\n dest='outdir',\n default='',\n help='Specify output directory')\n\n parser.add_argument(\n '--num_features',\n type=int,\n dest='num_features',\n default=10,\n help='Number of features to look for')\n\n parser.add_argument(\n '--num_cycles',\n type=int,\n dest='num_cycles',\n default=500,\n help='Number of randomized search cycles')\n\n parser.add_argument(\n '--cv',\n type=int,\n dest='cv',\n default=3,\n help='Number of cross-validation repeats to use during training')\n\n parser.add_argument(\n '--boot_iter',\n type=int,\n dest='boot_iter',\n default=1000,\n help='Number of bootstrap cycles')\n\n args = parser.parse_args()\n\n if args.input == '':\n parser.print_help()\n exit(0)\n\n run(args.input,\n args.outdir,\n args.num_features,\n args.num_cycles,\n args.cv,\n args.boot_iter)\n\n\nif __name__ == \"__main__\":\n main()\n"
]
| [
[
"sklearn.metrics.roc_auc_score",
"pandas.read_csv",
"sklearn.model_selection.RandomizedSearchCV",
"sklearn.model_selection.train_test_split",
"pandas.DataFrame",
"sklearn.tree.DecisionTreeClassifier",
"sklearn.ensemble.AdaBoostClassifier",
"numpy.mean",
"scipy.stats.uniform",
"scipy.stats.randint",
"sklearn.preprocessing.StandardScaler"
]
]
|
tguillemLSST/eotest | [
"c6f150984fa5dff85b9805028645bf46fc846f11"
]
| [
"python/lsst/eotest/simulation/generate_Fe55_images.py"
]
| [
"\"\"\"\n@brief Generate Fe55 images and associated darks and bias images\naccording to section 5.4 of the E/O document (Dec 19, 2012 version).\n\n@author J. Chiang <[email protected]>\n\"\"\"\nimport os\nimport numpy as np\nfrom sim_inputs import *\nfrom sim_tools import *\n\n\ndef generate_Fe55_images(exptimes, nxrays, outdir, sensorid, gain=gain,\n bias_level=bias_level, sys_noise=sys_noise,\n dark_current=dark_current):\n nexp = len(exptimes)\n for i, exptime, nxray in zip(list(range(nexp)), exptimes, nxrays):\n #\n # Bias images\n #\n outfile = \"Fe55_bias_%s_%02i.fits\" % (sensorid, i)\n bias_file = os.path.join(outdir, outfile)\n bias_segs = []\n for hdu in range(nhdu):\n seg = SegmentExposure(exptime=0, gain=gain)\n seg.add_bias(level=bias_level, sigma=sys_noise) # electronics\n seg.add_bias(level=0, sigma=read_noise) # read noise\n bias_segs.append(seg)\n bias_output = fitsFile(bias_segs)\n bias_output[0].header['GAIN'] = gain\n bias_output[0].header['BIASLVL'] = bias_level\n bias_output[0].header['SYSNOISE'] = sys_noise\n bias_output[0].header['RDNOISE'] = read_noise\n bias_output.writeto(bias_file, overwrite=True)\n #\n # Dark images\n #\n outfile = \"Fe55_dark_%s_%02i.fits\" % (sensorid, i)\n dark_file = os.path.join(outdir, outfile)\n dark_segs = []\n for hdu in range(nhdu):\n seg = SegmentExposure(exptime=exptime, gain=gain)\n seg.add_bias(level=bias_level, sigma=sys_noise) # electronics\n seg.add_bias(level=0, sigma=read_noise) # read noise\n seg.add_dark_current(level=dark_current) # dark current\n dark_segs.append(seg)\n dark_output = fitsFile(dark_segs)\n dark_output[0].header['GAIN'] = gain\n dark_output[0].header['BIASLVL'] = bias_level\n dark_output[0].header['SYSNOISE'] = sys_noise\n dark_output[0].header['RDNOISE'] = read_noise\n dark_output[0].header['DARKCURR'] = dark_current\n dark_output.writeto(dark_file, overwrite=True)\n #\n # Fe55 exposures\n #\n outfile = \"Fe55_exp_%s_%02i.fits\" % (sensorid, i)\n Fe55_file = os.path.join(outdir, outfile)\n fe55_segs = []\n for hdu in range(nhdu):\n seg = SegmentExposure(exptime=exptime, gain=gain)\n seg.add_bias(level=bias_level, sigma=sys_noise) # electronics\n seg.add_bias(level=0, sigma=read_noise) # read noise\n seg.add_dark_current(level=dark_current) # dark current\n seg.add_Fe55_hits(nxrays=nxray)\n fe55_segs.append(seg)\n fe55_output = fitsFile(fe55_segs)\n fe55_output[0].header['GAIN'] = gain\n fe55_output[0].header['BIASLVL'] = bias_level\n fe55_output[0].header['SYSNOISE'] = sys_noise\n fe55_output[0].header['RDNOISE'] = read_noise\n fe55_output[0].header['DARKCURR'] = dark_current\n fe55_output[0].header['FE55HITS'] = nxray\n fe55_output.writeto(Fe55_file, overwrite=True)\n\n\nif __name__ == '__main__':\n nexp = 10\n\n exptimes = np.linspace(1, 5, nexp)\n nxrays = [int(x*1000) for x in exptimes]\n\n generate_Fe55_images(exptimes, nxrays, '.', 'xxx-xx')\n"
]
| [
[
"numpy.linspace"
]
]
|
RobertLuo1/AmazonShoesReviewsClassifier | [
"752f17f9c253a08513b143be9e90fa1e3f9335fb"
]
| [
"textdataset.py"
]
| [
"#-*- coding: utf-8 -*-\n#@author: Zhuoyan Luo,Ruiming Chen\n\nimport torch\nfrom torch.utils.data import DataLoader,Dataset\nfrom config import ws,max_len,train_batch_size,test_batch_size\nimport os\nfrom nltk import word_tokenize\nimport numpy as np\n\nclass textDataset(Dataset):\n def __init__(self,mode):\n super(textDataset,self).__init__()\n data_base_file = r'../data/dataset'\n if mode =='train':\n review_path = os.path.join(data_base_file,'train')\n else:\n review_path = os.path.join(data_base_file,'test')\n temp_data_path = [os.path.join(review_path, 'pos'), os.path.join(review_path, 'neg')]\n self.total_file_path = [] # 所有评论文件的路径\n for path in temp_data_path:\n file_name_list = os.listdir(path)\n file_path_list = [os.path.join(path, i) for i in file_name_list if i.endswith('.txt')]\n self.total_file_path.extend(file_path_list)\n\n def __getitem__(self, idx):\n cur_path = self.total_file_path[idx]\n label_temp = cur_path.split('\\\\')[-2]\n label = 1 if label_temp == 'pos' else 0\n with open(cur_path,'r',encoding='utf-8') as f:\n text = f.read()\n review = word_tokenize(text)\n input_length = len(review)\n if input_length >= max_len:\n input_length = max_len\n return review,label,input_length\n\n def __len__(self):\n return len(self.total_file_path)\n\n\ndef collate_fn(batch):\n \"\"\"\n\n :param batch: [text,label],[text,label]\n :return:\n \"\"\"\n batch = sorted(batch,key=lambda x:x[2],reverse=True)\n review,label,input_length = zip(*batch)\n review = [ws.transform(i,max_len=max_len) for i in review]\n review = torch.LongTensor(review)\n label = torch.LongTensor(label)\n input_length = torch.tensor(input_length,dtype=torch.int64)\n return review,label,input_length\n\n\n\ntrain_textdataset = textDataset(mode='train')\ntrainLoader = DataLoader(train_textdataset,train_batch_size,shuffle=True,collate_fn=collate_fn)\ntest_textdataset = textDataset(mode='test')\ntestLoader = DataLoader(test_textdataset,test_batch_size,collate_fn=collate_fn,shuffle=True)\n\n\ndef getdataLoader(mode):\n \"\"\"\n 这个函数用于到时候训练的时候获取dataloader的\n :param mode: 训练还是测试\n :return: DataLoader\n \"\"\"\n if mode == \"train\":\n return trainLoader\n else:\n return testLoader\n\n\n\n# for idx,(content,label) in enumerate(testLoader):\n# print(label)\n# content_list = []\n# for content,label in train_textdataset:\n# content_list.append(len(content))\n# print(np.mean(content_list))\n#33.20325092200519\n\n\n\n\n"
]
| [
[
"torch.LongTensor",
"torch.utils.data.DataLoader",
"torch.tensor"
]
]
|
zhaofeng-shu33/pyBHC | [
"55f80e6d13cbfc12555bd165a49ae80ea6f08393"
]
| [
"pyBHC/bhc.py"
]
| [
"from __future__ import print_function, division\nimport itertools as it\nimport numpy as np\nimport sys\n\nfrom numpy import logaddexp\nimport math\n\n\nclass bhc(object):\n \"\"\"\n An instance of Bayesian hierarchical clustering CRP mixture model.\n Attributes\n ----------\n assignments : list(list(int))\n A list of lists, where each list records the clustering at\n each step by giving the index of the leftmost member of the\n cluster a leaf is traced to.\n root_node : Node\n The root node of the clustering tree.\n lml : float\n An estimate of the log marginal likelihood of the model\n under a DPMM.\n Notes\n -----\n The cost of BHC scales as O(n^2) and so becomes inpractically\n large for datasets of more than a few hundred points.\n \"\"\"\n\n def __init__(self, data, data_model, crp_alpha=1.0,\n verbose=False):\n \"\"\"\n Init a bhc instance and perform the clustering.\n\n Parameters\n ----------\n data : numpy.ndarray (n, d)\n Array of data where each row is a data point and each\n column is a dimension.\n data_model : CollapsibleDistribution\n Provides the approprite ``log_marginal_likelihood``\n function for the data.\n crp_alpha : float (0, Inf)\n CRP concentration parameter.\n verbose : bool, optional\n Determibes whetrher info gets dumped to stdout.\n \"\"\"\n self.data = data\n self.data_model = data_model\n self.crp_alpha = crp_alpha\n\n self.verbose = verbose\n\n # initialize the tree\n nodes = dict((i, Node(np.array([x]), data_model, crp_alpha,\n indexes=i))\n for i, x in enumerate(data))\n n_nodes = len(nodes)\n start_n_nodes = len(nodes)\n assignment = [i for i in range(n_nodes)]\n self.assignments = [list(assignment)]\n rks = []\n self.lmls = []\n while n_nodes > 1:\n if self.verbose:\n sys.stdout.write(\"\\r{0:d} of {1:d} \".format(n_nodes,\n start_n_nodes))\n sys.stdout.flush()\n\n max_rk = float('-Inf')\n merged_node = None\n\n # for each pair of clusters (nodes), compute the merger\n # score.\n for left_idx, right_idx in it.combinations(nodes.keys(),\n 2):\n tmp_node = Node.as_merge(nodes[left_idx],\n nodes[right_idx])\n\n if tmp_node.log_rk > max_rk:\n max_rk = tmp_node.log_rk\n merged_node = tmp_node\n merged_right = right_idx\n merged_left = left_idx\n\n rks.append(math.exp(max_rk))\n\n # Merge the highest-scoring pair\n del nodes[merged_right]\n nodes[merged_left] = merged_node\n\n for i, k in enumerate(assignment):\n if k == merged_right:\n assignment[i] = merged_left\n self.assignments.append(list(assignment))\n\n n_nodes -= 1\n self.lmls.append(denom)\n self.root_node = nodes[0]\n self.assignments = np.array(self.assignments)\n\n # The denominator of log_rk is at the final merge is an\n # estimate of the marginal likelihood of the data under DPMM\n self.lml = self.root_node.log_ml\n\n def left_run(self):\n node = self.root_node\n while node.left_child is not None:\n print(node.indexes, np.mean(node.data, axis=0), node.data.shape)\n node = node.left_child\n print(node.indexes, np.mean(node.data, axis=0), node.data.shape)\n\n def right_run(self):\n node = self.root_node\n while node.right_child is not None:\n print(node.indexes, np.mean(node.data, axis=0), node.data.shape)\n node = node.right_child\n print(node.indexes, np.mean(node.data, axis=0), node.data.shape)\n\n def find_path(self, index):\n \"\"\" find_path(index)\n\n Finds the sequence of left and right merges needed to\n run from the root node to a particular leaf.\n\n Parameters\n ----------\n index : int\n The index of the leaf for which we want the path\n from the root node.\n \"\"\"\n merge_path = []\n last_leftmost_index = self.assignments[-1][index]\n last_right_incluster = (self.assignments[-1]\n == last_leftmost_index)\n\n for it in range(len(self.assignments)-2, -1, -1):\n new_leftmost_index = self.assignments[it][index]\n\n if new_leftmost_index != last_leftmost_index:\n # True if leaf is on the right hand side of a merge\n merge_path.append(\"right\")\n last_leftmost_index = new_leftmost_index\n last_right_incluster = (self.assignments[it]\n == new_leftmost_index)\n\n else: # Not in a right hand side of a merge\n\n new_right_incluster = (self.assignments[it]\n == last_leftmost_index)\n\n if (new_right_incluster != last_right_incluster).any():\n # True if leaf is on the left hand side of a merge\n merge_path.append(\"left\")\n last_right_incluster = new_right_incluster\n\n return merge_path\n\n def sample(self, size=1):\n\n output = np.zeros((size, self.root_node.data.shape[1]))\n\n for it in range(size):\n\n sampled = False\n node = self.root_node\n\n while not sampled:\n\n if node.log_rk is None: # Node is a leaf\n output[it, :] = self.data_model.conditional_sample(\n node.data)\n sampled = True\n\n elif np.random.rand() < math.exp(node.log_rk):\n # sample from node\n output[it, :] = self.data_model.conditional_sample(\n node.data)\n sampled = True\n\n else: # drop to next level\n child_ratio = (node.left_child.nk\n / (node.left_child.nk+node.right_child.nk))\n if np.random.rand() >= child_ratio:\n node = node.right_child\n else:\n node = node.left_child\n\n return output\n\n\nclass Node(object):\n \"\"\" A node in the hierarchical clustering.\n Attributes\n ----------\n nk : int\n Number of data points assigned to the node\n data : numpy.ndarrary (n, d)\n The data assigned to the Node. Each row is a datum.\n data_model : idsteach.CollapsibleDistribution\n The data model used to calcuate marginal likelihoods\n crp_alpha : float\n Chinese restaurant process concentration parameter\n log_dk : float\n Used in the calculation of the prior probability. Defined in\n Fig 3 of Heller & Ghahramani (2005).\n log_pi : float\n Prior probability that all associated leaves belong to one\n cluster.\n log_ml : float\n The log marginal likelihood for the tree of the node and\n its children. This is given by eqn 2 of Heller &\n Ghahrimani (2005). Note that this definition is\n recursive. Do not define if the node is\n a leaf.\n logp : float\n The log marginal likelihood for the particular cluster\n represented by the node. Given by eqn 1 of Heller &\n Ghahramani (2005).\n log_rk : float\n The log-probability of the merge that created the node. For\n nodes that are leaves (i.e. not created by a merge) this is\n None.\n left_child : Node\n The left child of a merge. For nodes that are leaves (i.e.\n the original data points and not made by a merge) this is\n None.\n right_child : Node\n The right child of a merge. For nodes that are leaves\n (i.e. the original data points and not made by a merge)\n this is None.\n index : int\n The indexes of the leaves associated with the node in some\n indexing scheme.\n \"\"\"\n\n def __init__(self, data, data_model, crp_alpha=1.0, log_dk=None,\n log_pi=0.0, log_ml=None, logp=None, log_rk=None,\n left_child=None, right_child=None, indexes=None):\n \"\"\"\n Parameters\n ----------\n data : numpy.ndarray\n Array of data_model-appropriate data\n data_model : idsteach.CollapsibleDistribution\n The data model used to calcuate marginal likelihoods\n crp_alpha : float (0, Inf)\n CRP concentration parameter\n log_dk : float\n Cached probability variable. Do not define if the node is\n a leaf.\n log_pi : float\n Cached probability variable. Do not define if the node is\n a leaf.\n log_ml : float\n The log marginal likelihood for the tree of the node and\n its children. This is given by eqn 2 of Heller &\n Ghahrimani (2005). Note that this definition is\n recursive. Do not define if the node is\n a leaf.\n logp : float\n The log marginal likelihood for the particular cluster\n represented by the node. Given by eqn 1 of Heller &\n Ghahramani (2005).\n log_rk : float\n The probability of the merged hypothesis for the node.\n Given by eqn 3 of Heller & Ghahrimani (2005). Do not\n define if the node is a leaf.\n left_child : Node, optional\n The left child of a merge. For nodes that are leaves (i.e.\n the original data points and not made by a merge) this is\n None.\n right_child : Node, optional\n The right child of a merge. For nodes that are leaves\n (i.e. the original data points and not made by a merge)\n this is None.\n index : int, optional\n The index of the node in some indexing scheme.\n \"\"\"\n self.data_model = data_model\n self.data = data\n self.nk = data.shape[0]\n self.crp_alpha = crp_alpha\n self.log_pi = log_pi\n self.log_rk = log_rk\n\n self.left_child = left_child\n self.right_child = right_child\n\n if isinstance(indexes, int):\n self.indexes = [indexes]\n else:\n self.indexes = indexes\n\n if log_dk is None:\n self.log_dk = math.log(crp_alpha)\n else:\n self.log_dk = log_dk\n\n if logp is None: # i.e. for a leaf\n self.logp = self.data_model.\\\n log_marginal_likelihood(self.data)\n else:\n self.logp = logp\n\n if log_ml is None: # i.e. for a leaf\n self.log_ml = self.logp\n else:\n self.log_ml = log_ml\n\n @classmethod\n def as_merge(cls, node_left, node_right):\n \"\"\" Create a node from two other nodes\n Parameters\n ----------\n node_left : Node\n the Node on the left\n node_right : Node\n The Node on the right\n \"\"\"\n crp_alpha = node_left.crp_alpha\n data_model = node_left.data_model\n data = np.vstack((node_left.data, node_right.data))\n indexes = node_left.indexes + node_right.indexes\n indexes.sort()\n\n nk = data.shape[0]\n log_dk = logaddexp(math.log(crp_alpha) + math.lgamma(nk),\n node_left.log_dk + node_right.log_dk)\n log_pi = -math.log1p(math.exp(node_left.log_dk\n + node_right.log_dk\n - math.log(crp_alpha)\n - math.lgamma(nk)))\n\n # Calculate log_rk - the log probability of the merge\n\n logp = data_model.log_marginal_likelihood(data)\n numer = log_pi + logp\n\n neg_pi = math.log(-math.expm1(log_pi))\n log_ml = logaddexp(numer, neg_pi+node_left.log_ml + node_right.log_ml)\n\n log_rk = numer-log_ml\n\n if log_pi == 0:\n raise RuntimeError('Precision error')\n\n return cls(data, data_model, crp_alpha, log_dk, log_pi,\n log_ml, logp, log_rk, node_left, node_right,\n indexes)\n"
]
| [
[
"numpy.vstack",
"numpy.mean",
"numpy.random.rand",
"numpy.array",
"numpy.zeros",
"numpy.logaddexp"
]
]
|
aurora32s/pytorch-example | [
"83d494306829aec025796eb6adba4cef5b1641eb"
]
| [
"mnist/main.py"
]
| [
"from __future__ import print_function\nimport argparse\nimport json #변경222\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torchvision import datasets, transforms\nfrom torch.optim.lr_scheduler import StepLR\n\n\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.conv1 = nn.Conv2d(1, 32, 3, 1)\n self.conv2 = nn.Conv2d(32, 64, 3, 1)\n self.dropout1 = nn.Dropout2d(0.25)\n self.dropout2 = nn.Dropout2d(0.5)\n self.fc1 = nn.Linear(9216, 128)\n self.fc2 = nn.Linear(128, 10)\n\n def forward(self, x):\n x = self.conv1(x)\n x = F.relu(x)\n x = self.conv2(x)\n x = F.max_pool2d(x, 2)\n x = self.dropout1(x)\n x = torch.flatten(x, 1)\n x = self.fc1(x)\n x = F.relu(x)\n x = self.dropout2(x)\n x = self.fc2(x)\n output = F.log_softmax(x, dim=1)\n return output\n\n\ndef train(args, model, device, train_loader, optimizer, epoch):\n model.train()\n for batch_idx, (data, target) in enumerate(train_loader):\n data, target = data.to(device), target.to(device)\n optimizer.zero_grad()\n output = model(data)\n loss = F.nll_loss(output, target)\n loss.backward()\n optimizer.step()\n if batch_idx % args.log_interval == 0:\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n epoch, batch_idx * len(data), len(train_loader.dataset),\n 100. * batch_idx / len(train_loader), loss.item()))\n if args.dry_run:\n break\n\n\ndef test(args, model, device, test_loader):\n model.eval()\n test_loss = 0\n correct = 0\n with torch.no_grad():\n for data, target in test_loader:\n data, target = data.to(device), target.to(device)\n output = model(data)\n test_loss += F.nll_loss(output, target, reduction='sum').item() # sum up batch loss\n pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability\n correct += pred.eq(target.view_as(pred)).sum().item()\n\n test_loss /= len(test_loader.dataset)\n\n print('\\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\\n'.format(\n test_loss, correct, len(test_loader.dataset),\n 100. * correct / len(test_loader.dataset)))\n\n\ndef main():\n # Training settings\n parser = argparse.ArgumentParser(description='PyTorch MNIST Example')\n parser.add_argument('--batch-size', type=int, default=64, metavar='N',\n help='input batch size for training (default: 64)')\n parser.add_argument('--test-batch-size', type=int, default=1000, metavar='N',\n help='input batch size for testing (default: 1000)')\n parser.add_argument('--epochs', type=int, default=14, metavar='N',\n help='number of epochs to train (default: 10)')\n parser.add_argument('--lr', type=float, default=1.0, metavar='LR',\n help='learning rate (default: 1.0)')\n parser.add_argument('--gamma', type=float, default=0.7, metavar='M',\n help='Learning rate step gamma (default: 0.7)')\n parser.add_argument('--no-cuda', action='store_true', default=False,\n help='disables CUDA training')\n parser.add_argument('--dry-run', action='store_true', default=False,\n help='quickly check a single pass')\n parser.add_argument('--seed', type=int, default=1, metavar='S',\n help='random seed (default: 1)')\n parser.add_argument('--log-interval', type=int, default=10, metavar='N',\n help='how many batches to wait before logging training status')\n parser.add_argument('--save-model', action='store_true', default=False,\n help='For Saving the current Model')\n args = parser.parse_args()\n use_cuda = not args.no_cuda and torch.cuda.is_available()\n\n torch.manual_seed(args.seed)\n\n device = torch.device(\"cuda\" if use_cuda else \"cpu\")\n\n kwargs = {'batch_size': args.batch_size}\n if use_cuda:\n kwargs.update({'num_workers': 1,\n 'pin_memory': True,\n 'shuffle': True},\n )\n\n transform=transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))\n ])\n dataset1 = datasets.MNIST('../data', train=True, download=True,\n transform=transform)\n dataset2 = datasets.MNIST('../data', train=False,\n transform=transform)\n train_loader = torch.utils.data.DataLoader(dataset1,**kwargs)\n test_loader = torch.utils.data.DataLoader(dataset2, **kwargs)\n\n model = Net().to(device)\n optimizer = optim.Adadelta(model.parameters(), lr=args.lr)\n\n scheduler = StepLR(optimizer, step_size=1, gamma=args.gamma)\n for epoch in range(1, args.epochs + 1):\n train(args, model, device, train_loader, optimizer, epoch)\n test(args, model, device, test_loader)\n scheduler.step()\n\n if args.save_model:\n torch.save(model.state_dict(), \"mnist_cnn.pt\")\n\n\nif __name__ == '__main__':\n main()\n'hello world!'\n"
]
| [
[
"torch.nn.Dropout2d",
"torch.nn.functional.log_softmax",
"torch.nn.functional.nll_loss",
"torch.manual_seed",
"torch.nn.Conv2d",
"torch.utils.data.DataLoader",
"torch.nn.Linear",
"torch.nn.functional.relu",
"torch.no_grad",
"torch.cuda.is_available",
"torch.flatten",
"torch.device",
"torch.nn.functional.max_pool2d",
"torch.optim.lr_scheduler.StepLR"
]
]
|
kmagdy20/qiskit-terra | [
"fcec842f1de9fd12120e30a1bf73bf7c52b1bf81"
]
| [
"test/python/visualization/test_circuit_latex.py"
]
| [
"# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2017.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n# pylint: disable=arguments-differ\n\n\"\"\"Tests for visualization of circuit with Latex drawer.\"\"\"\n\nimport os\nimport unittest\nimport math\nimport numpy as np\n\nfrom qiskit.visualization import circuit_drawer\nfrom qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, transpile\nfrom qiskit.test.mock import FakeTenerife\nfrom qiskit.circuit.library import XGate, MCXGate, RZZGate, SwapGate, DCXGate\nfrom qiskit.extensions import HamiltonianGate\nfrom qiskit.circuit import Parameter\nfrom qiskit.circuit import Qubit, Clbit\nfrom qiskit.circuit.library import IQP\nfrom qiskit.quantum_info.random import random_unitary\nfrom .visualization import QiskitVisualizationTestCase\n\npi = np.pi\n\n\nclass TestLatexSourceGenerator(QiskitVisualizationTestCase):\n \"\"\"Qiskit latex source generator tests.\"\"\"\n\n def _get_resource_path(self, filename):\n reference_dir = os.path.dirname(os.path.abspath(__file__))\n return os.path.join(reference_dir, filename)\n\n def test_empty_circuit(self):\n \"\"\"Test draw an empty circuit\"\"\"\n filename = self._get_resource_path(\"test_latex_empty.tex\")\n circuit = QuantumCircuit(1)\n circuit_drawer(circuit, filename=filename, output=\"latex_source\")\n\n self.assertEqualToReference(filename)\n\n def test_tiny_circuit(self):\n \"\"\"Test draw tiny circuit.\"\"\"\n filename = self._get_resource_path(\"test_latex_tiny.tex\")\n circuit = QuantumCircuit(1)\n circuit.h(0)\n\n circuit_drawer(circuit, filename=filename, output=\"latex_source\")\n\n self.assertEqualToReference(filename)\n\n def test_multi_underscore_reg_names(self):\n \"\"\"Test multi-underscores in register names display properly\"\"\"\n filename1 = self._get_resource_path(\"test_latex_multi_underscore_true.tex\")\n filename2 = self._get_resource_path(\"test_latex_multi_underscore_false.tex\")\n q_reg1 = QuantumRegister(1, \"q1_re__g__g\")\n q_reg3 = QuantumRegister(3, \"q3_re_g__g\")\n c_reg1 = ClassicalRegister(1, \"c1_re_g__g\")\n c_reg3 = ClassicalRegister(3, \"c3_re_g__g\")\n circuit = QuantumCircuit(q_reg1, q_reg3, c_reg1, c_reg3)\n circuit_drawer(circuit, cregbundle=True, filename=filename1, output=\"latex_source\")\n circuit_drawer(circuit, cregbundle=False, filename=filename2, output=\"latex_source\")\n self.assertEqualToReference(filename1)\n self.assertEqualToReference(filename2)\n\n def test_normal_circuit(self):\n \"\"\"Test draw normal size circuit.\"\"\"\n filename = self._get_resource_path(\"test_latex_normal.tex\")\n circuit = QuantumCircuit(5)\n for qubit in range(5):\n circuit.h(qubit)\n\n circuit_drawer(circuit, filename=filename, output=\"latex_source\")\n\n self.assertEqualToReference(filename)\n\n def test_4597(self):\n \"\"\"Test cregbundle and conditional gates.\n See: https://github.com/Qiskit/qiskit-terra/pull/4597\"\"\"\n filename = self._get_resource_path(\"test_latex_4597.tex\")\n qr = QuantumRegister(3, \"q\")\n cr = ClassicalRegister(3, \"c\")\n circuit = QuantumCircuit(qr, cr)\n circuit.x(qr[2]).c_if(cr, 2)\n circuit.draw(output=\"latex_source\", cregbundle=True)\n\n circuit_drawer(circuit, filename=filename, output=\"latex_source\")\n\n self.assertEqualToReference(filename)\n\n def test_deep_circuit(self):\n \"\"\"Test draw deep circuit.\"\"\"\n filename = self._get_resource_path(\"test_latex_deep.tex\")\n circuit = QuantumCircuit(1)\n for _ in range(100):\n circuit.h(0)\n\n circuit_drawer(circuit, filename=filename, output=\"latex_source\")\n\n self.assertEqualToReference(filename)\n\n def test_huge_circuit(self):\n \"\"\"Test draw huge circuit.\"\"\"\n filename = self._get_resource_path(\"test_latex_huge.tex\")\n circuit = QuantumCircuit(40)\n for qubit in range(39):\n circuit.h(qubit)\n circuit.cx(qubit, 39)\n\n circuit_drawer(circuit, filename=filename, output=\"latex_source\")\n\n self.assertEqualToReference(filename)\n\n def test_teleport(self):\n \"\"\"Test draw teleport circuit.\"\"\"\n filename = self._get_resource_path(\"test_latex_teleport.tex\")\n qr = QuantumRegister(3, \"q\")\n cr = ClassicalRegister(3, \"c\")\n circuit = QuantumCircuit(qr, cr)\n # Prepare an initial state\n circuit.u(0.3, 0.2, 0.1, [qr[0]])\n # Prepare a Bell pair\n circuit.h(qr[1])\n circuit.cx(qr[1], qr[2])\n # Barrier following state preparation\n circuit.barrier(qr)\n # Measure in the Bell basis\n circuit.cx(qr[0], qr[1])\n circuit.h(qr[0])\n circuit.measure(qr[0], cr[0])\n circuit.measure(qr[1], cr[1])\n # Apply a correction\n circuit.z(qr[2]).c_if(cr, 1)\n circuit.x(qr[2]).c_if(cr, 2)\n circuit.measure(qr[2], cr[2])\n\n circuit_drawer(circuit, filename=filename, output=\"latex_source\")\n\n self.assertEqualToReference(filename)\n\n def test_global_phase(self):\n \"\"\"Test circuit with global phase\"\"\"\n filename = self._get_resource_path(\"test_latex_global_phase.tex\")\n circuit = QuantumCircuit(3, global_phase=1.57079632679)\n circuit.h(range(3))\n\n circuit_drawer(circuit, filename=filename, output=\"latex_source\")\n\n self.assertEqualToReference(filename)\n\n def test_no_ops(self):\n \"\"\"Test circuit with no ops.\n See https://github.com/Qiskit/qiskit-terra/issues/5393\"\"\"\n filename = self._get_resource_path(\"test_latex_no_ops.tex\")\n circuit = QuantumCircuit(2, 3)\n circuit_drawer(circuit, filename=filename, output=\"latex_source\")\n\n self.assertEqualToReference(filename)\n\n def test_long_name(self):\n \"\"\"Test to see that long register names can be seen completely\n As reported in #2605\n \"\"\"\n filename = self._get_resource_path(\"test_latex_long_name.tex\")\n\n # add a register with a very long name\n qr = QuantumRegister(4, \"veryLongQuantumRegisterName\")\n # add another to make sure adjustments are made based on longest\n qrr = QuantumRegister(1, \"q0\")\n circuit = QuantumCircuit(qr, qrr)\n\n # check gates are shifted over accordingly\n circuit.h(qr)\n circuit.h(qr)\n circuit.h(qr)\n\n circuit_drawer(circuit, filename=filename, output=\"latex_source\")\n\n self.assertEqualToReference(filename)\n\n def test_conditional(self):\n \"\"\"Test that circuits with conditionals draw correctly\"\"\"\n filename = self._get_resource_path(\"test_latex_conditional.tex\")\n qr = QuantumRegister(2, \"q\")\n cr = ClassicalRegister(2, \"c\")\n circuit = QuantumCircuit(qr, cr)\n\n # check gates are shifted over accordingly\n circuit.h(qr)\n circuit.measure(qr, cr)\n circuit.h(qr[0]).c_if(cr, 2)\n\n circuit_drawer(circuit, filename=filename, output=\"latex_source\")\n\n self.assertEqualToReference(filename)\n\n def test_plot_partial_barrier(self):\n \"\"\"Test plotting of partial barriers.\"\"\"\n\n filename = self._get_resource_path(\"test_latex_plot_partial_barriers.tex\")\n # generate a circuit with barrier and other barrier like instructions in\n q = QuantumRegister(2, \"q\")\n c = ClassicalRegister(2, \"c\")\n circuit = QuantumCircuit(q, c)\n\n # check for barriers\n circuit.h(q[0])\n circuit.barrier(0)\n circuit.h(q[0])\n\n circuit_drawer(circuit, filename=filename, output=\"latex_source\")\n\n self.assertEqualToReference(filename)\n\n def test_plot_barriers(self):\n \"\"\"Test to see that plotting barriers works.\n If it is set to False, no blank columns are introduced\"\"\"\n\n filename1 = self._get_resource_path(\"test_latex_plot_barriers_true.tex\")\n filename2 = self._get_resource_path(\"test_latex_plot_barriers_false.tex\")\n # generate a circuit with barriers and other barrier like instructions in\n q = QuantumRegister(2, \"q\")\n c = ClassicalRegister(2, \"c\")\n circuit = QuantumCircuit(q, c)\n\n # check for barriers\n circuit.h(q[0])\n circuit.barrier()\n\n # check for other barrier like commands\n circuit.h(q[1])\n\n # this import appears to be unused, but is actually needed to get snapshot instruction\n import qiskit.extensions.simulator # pylint: disable=unused-import\n\n circuit.snapshot(\"1\")\n\n # check the barriers plot properly when plot_barriers= True\n circuit_drawer(circuit, filename=filename1, output=\"latex_source\", plot_barriers=True)\n\n self.assertEqualToReference(filename1)\n circuit_drawer(circuit, filename=filename2, output=\"latex_source\", plot_barriers=False)\n\n self.assertEqualToReference(filename2)\n\n def test_no_barriers_false(self):\n \"\"\"Generate the same circuit as test_plot_barriers but without the barrier commands\n as this is what the circuit should look like when displayed with plot barriers false\"\"\"\n filename = self._get_resource_path(\"test_latex_no_barriers_false.tex\")\n q1 = QuantumRegister(2, \"q\")\n c1 = ClassicalRegister(2, \"c\")\n circuit = QuantumCircuit(q1, c1)\n circuit.h(q1[0])\n circuit.h(q1[1])\n\n circuit_drawer(circuit, filename=filename, output=\"latex_source\")\n\n self.assertEqualToReference(filename)\n\n def test_big_gates(self):\n \"\"\"Test large gates with params\"\"\"\n filename = self._get_resource_path(\"test_latex_big_gates.tex\")\n qr = QuantumRegister(6, \"q\")\n circuit = QuantumCircuit(qr)\n circuit.append(IQP([[6, 5, 3], [5, 4, 5], [3, 5, 1]]), [0, 1, 2])\n\n desired_vector = [\n 1 / math.sqrt(16) * complex(0, 1),\n 1 / math.sqrt(8) * complex(1, 0),\n 1 / math.sqrt(16) * complex(1, 1),\n 0,\n 0,\n 1 / math.sqrt(8) * complex(1, 2),\n 1 / math.sqrt(16) * complex(1, 0),\n 0,\n ]\n\n circuit.initialize(desired_vector, [qr[3], qr[4], qr[5]])\n circuit.unitary([[1, 0], [0, 1]], [qr[0]])\n matrix = np.zeros((4, 4))\n theta = Parameter(\"theta\")\n circuit.append(HamiltonianGate(matrix, theta), [qr[1], qr[2]])\n circuit = circuit.bind_parameters({theta: 1})\n circuit.isometry(np.eye(4, 4), list(range(3, 5)), [])\n\n circuit_drawer(circuit, filename=filename, output=\"latex_source\")\n\n self.assertEqualToReference(filename)\n\n def test_cnot(self):\n \"\"\"Test different cnot gates (ccnot, mcx, etc)\"\"\"\n filename = self._get_resource_path(\"test_latex_cnot.tex\")\n qr = QuantumRegister(5, \"q\")\n circuit = QuantumCircuit(qr)\n circuit.x(0)\n circuit.cx(0, 1)\n circuit.ccx(0, 1, 2)\n circuit.append(XGate().control(3, ctrl_state=\"010\"), [qr[2], qr[3], qr[0], qr[1]])\n circuit.append(MCXGate(num_ctrl_qubits=3, ctrl_state=\"101\"), [qr[0], qr[1], qr[2], qr[4]])\n\n circuit_drawer(circuit, filename=filename, output=\"latex_source\")\n\n self.assertEqualToReference(filename)\n\n def test_pauli_clifford(self):\n \"\"\"Test Pauli(green) and Clifford(blue) gates\"\"\"\n filename = self._get_resource_path(\"test_latex_pauli_clifford.tex\")\n qr = QuantumRegister(5, \"q\")\n circuit = QuantumCircuit(qr)\n circuit.x(0)\n circuit.y(0)\n circuit.z(0)\n circuit.id(0)\n circuit.h(1)\n circuit.cx(1, 2)\n circuit.cy(1, 2)\n circuit.cz(1, 2)\n circuit.swap(3, 4)\n circuit.s(3)\n circuit.sdg(3)\n circuit.iswap(3, 4)\n circuit.dcx(3, 4)\n\n circuit_drawer(circuit, filename=filename, output=\"latex_source\")\n\n self.assertEqualToReference(filename)\n\n def test_u_gates(self):\n \"\"\"Test U 1, 2, & 3 gates\"\"\"\n filename = self._get_resource_path(\"test_latex_u_gates.tex\")\n from qiskit.circuit.library import U1Gate, U2Gate, U3Gate, CU1Gate, CU3Gate\n\n qr = QuantumRegister(4, \"q\")\n circuit = QuantumCircuit(qr)\n circuit.append(U1Gate(3 * pi / 2), [0])\n circuit.append(U2Gate(3 * pi / 2, 2 * pi / 3), [1])\n circuit.append(U3Gate(3 * pi / 2, 4.5, pi / 4), [2])\n circuit.append(CU1Gate(pi / 4), [0, 1])\n circuit.append(U2Gate(pi / 2, 3 * pi / 2).control(1), [2, 3])\n circuit.append(CU3Gate(3 * pi / 2, -3 * pi / 4, -pi / 2), [0, 1])\n\n circuit_drawer(circuit, filename=filename, output=\"latex_source\")\n\n self.assertEqualToReference(filename)\n\n def test_creg_initial(self):\n \"\"\"Test cregbundle and initial state options\"\"\"\n filename1 = self._get_resource_path(\"test_latex_creg_initial_true.tex\")\n filename2 = self._get_resource_path(\"test_latex_creg_initial_false.tex\")\n qr = QuantumRegister(2, \"q\")\n cr = ClassicalRegister(2, \"c\")\n circuit = QuantumCircuit(qr, cr)\n circuit.x(0)\n circuit.h(0)\n circuit.x(1)\n\n circuit_drawer(\n circuit, filename=filename1, output=\"latex_source\", cregbundle=True, initial_state=True\n )\n\n self.assertEqualToReference(filename1)\n circuit_drawer(\n circuit,\n filename=filename2,\n output=\"latex_source\",\n cregbundle=False,\n initial_state=False,\n )\n\n self.assertEqualToReference(filename2)\n\n def test_r_gates(self):\n \"\"\"Test all R gates\"\"\"\n filename = self._get_resource_path(\"test_latex_r_gates.tex\")\n qr = QuantumRegister(4, \"q\")\n circuit = QuantumCircuit(qr)\n circuit.r(3 * pi / 4, 3 * pi / 8, 0)\n circuit.rx(pi / 2, 1)\n circuit.ry(-pi / 2, 2)\n circuit.rz(3 * pi / 4, 3)\n circuit.rxx(pi / 2, 0, 1)\n circuit.ryy(3 * pi / 4, 2, 3)\n circuit.rzx(-pi / 2, 0, 1)\n circuit.rzz(pi / 2, 2, 3)\n\n circuit_drawer(circuit, filename=filename, output=\"latex_source\")\n\n self.assertEqualToReference(filename)\n\n def test_cswap_rzz(self):\n \"\"\"Test controlled swap and rzz gates\"\"\"\n filename = self._get_resource_path(\"test_latex_cswap_rzz.tex\")\n qr = QuantumRegister(5, \"q\")\n circuit = QuantumCircuit(qr)\n circuit.x(0)\n circuit.x(1)\n circuit.cswap(0, 1, 2)\n circuit.append(RZZGate(3 * pi / 4).control(3, ctrl_state=\"010\"), [2, 1, 4, 3, 0])\n\n circuit_drawer(circuit, filename=filename, output=\"latex_source\")\n\n self.assertEqualToReference(filename)\n\n def test_ghz_to_gate(self):\n \"\"\"Test controlled GHZ to_gate circuit\"\"\"\n filename = self._get_resource_path(\"test_latex_ghz_to_gate.tex\")\n qr = QuantumRegister(5, \"q\")\n circuit = QuantumCircuit(qr)\n ghz_circuit = QuantumCircuit(3, name=\"Ctrl-GHZ Circuit\")\n ghz_circuit.h(0)\n ghz_circuit.cx(0, 1)\n ghz_circuit.cx(1, 2)\n ghz = ghz_circuit.to_gate()\n ccghz = ghz.control(2, ctrl_state=\"10\")\n circuit.append(ccghz, [4, 0, 1, 3, 2])\n\n circuit_drawer(circuit, filename=filename, output=\"latex_source\")\n\n self.assertEqualToReference(filename)\n\n def test_scale(self):\n \"\"\"Tests scale\n See: https://github.com/Qiskit/qiskit-terra/issues/4179\"\"\"\n filename1 = self._get_resource_path(\"test_latex_scale_default.tex\")\n filename2 = self._get_resource_path(\"test_latex_scale_half.tex\")\n filename3 = self._get_resource_path(\"test_latex_scale_double.tex\")\n circuit = QuantumCircuit(5)\n circuit.unitary(random_unitary(2**5), circuit.qubits)\n\n circuit_drawer(circuit, filename=filename1, output=\"latex_source\")\n\n self.assertEqualToReference(filename1)\n circuit_drawer(circuit, filename=filename2, output=\"latex_source\", scale=0.5)\n\n self.assertEqualToReference(filename2)\n circuit_drawer(circuit, filename=filename3, output=\"latex_source\", scale=2.0)\n\n self.assertEqualToReference(filename3)\n\n def test_pi_param_expr(self):\n \"\"\"Text pi in circuit with parameter expression.\"\"\"\n filename = self._get_resource_path(\"test_latex_pi_param_expr.tex\")\n x, y = Parameter(\"x\"), Parameter(\"y\")\n circuit = QuantumCircuit(1)\n circuit.rx((pi - x) * (pi - y), 0)\n\n circuit_drawer(circuit, filename=filename, output=\"latex_source\")\n\n self.assertEqualToReference(filename)\n\n def test_partial_layout(self):\n \"\"\"Tests partial_layout\n See: https://github.com/Qiskit/qiskit-terra/issues/4757\"\"\"\n filename = self._get_resource_path(\"test_latex_partial_layout.tex\")\n circuit = QuantumCircuit(3)\n circuit.h(1)\n transpiled = transpile(\n circuit,\n backend=FakeTenerife(),\n optimization_level=0,\n initial_layout=[1, 2, 0],\n seed_transpiler=0,\n )\n\n circuit_drawer(transpiled, filename=filename, output=\"latex_source\")\n\n self.assertEqualToReference(filename)\n\n def test_init_reset(self):\n \"\"\"Test reset and initialize with 1 and 2 qubits\"\"\"\n filename = self._get_resource_path(\"test_latex_init_reset.tex\")\n circuit = QuantumCircuit(2)\n circuit.initialize([0, 1], 0)\n circuit.reset(1)\n circuit.initialize([0, 1, 0, 0], [0, 1])\n\n circuit_drawer(circuit, filename=filename, output=\"latex_source\")\n\n self.assertEqualToReference(filename)\n\n def test_iqx_colors(self):\n \"\"\"Tests with iqx color scheme\"\"\"\n filename = self._get_resource_path(\"test_latex_iqx.tex\")\n circuit = QuantumCircuit(7)\n circuit.h(0)\n circuit.x(0)\n circuit.cx(0, 1)\n circuit.ccx(0, 1, 2)\n circuit.swap(0, 1)\n circuit.cswap(0, 1, 2)\n circuit.append(SwapGate().control(2), [0, 1, 2, 3])\n circuit.dcx(0, 1)\n circuit.append(DCXGate().control(1), [0, 1, 2])\n circuit.append(DCXGate().control(2), [0, 1, 2, 3])\n circuit.z(4)\n circuit.s(4)\n circuit.sdg(4)\n circuit.t(4)\n circuit.tdg(4)\n circuit.p(pi / 2, 4)\n circuit.p(pi / 2, 4)\n circuit.cz(5, 6)\n circuit.cp(pi / 2, 5, 6)\n circuit.y(5)\n circuit.rx(pi / 3, 5)\n circuit.rzx(pi / 2, 5, 6)\n circuit.u(pi / 2, pi / 2, pi / 2, 5)\n circuit.barrier(5, 6)\n circuit.reset(5)\n\n circuit_drawer(circuit, filename=filename, output=\"latex_source\")\n\n self.assertEqualToReference(filename)\n\n def test_reverse_bits(self):\n \"\"\"Tests reverse_bits parameter\"\"\"\n filename = self._get_resource_path(\"test_latex_reverse_bits.tex\")\n circuit = QuantumCircuit(3)\n circuit.h(0)\n circuit.cx(0, 1)\n circuit.ccx(2, 1, 0)\n\n circuit_drawer(circuit, filename=filename, output=\"latex_source\", reverse_bits=True)\n\n self.assertEqualToReference(filename)\n\n def test_meas_condition(self):\n \"\"\"Tests measure with a condition\"\"\"\n\n filename = self._get_resource_path(\"test_latex_meas_condition.tex\")\n qr = QuantumRegister(2, \"qr\")\n cr = ClassicalRegister(2, \"cr\")\n circuit = QuantumCircuit(qr, cr)\n circuit.h(qr[0])\n circuit.measure(qr[0], cr[0])\n circuit.h(qr[1]).c_if(cr, 1)\n circuit_drawer(circuit, filename=filename, output=\"latex_source\")\n\n self.assertEqualToReference(filename)\n\n def test_inst_with_cbits(self):\n \"\"\"Test custom instructions with classical bits\"\"\"\n\n filename = self._get_resource_path(\"test_latex_inst_with_cbits.tex\")\n qinst = QuantumRegister(2, \"q\")\n cinst = ClassicalRegister(2, \"c\")\n inst = QuantumCircuit(qinst, cinst, name=\"instruction\").to_instruction()\n\n qr = QuantumRegister(4, \"qr\")\n cr = ClassicalRegister(4, \"cr\")\n circuit = QuantumCircuit(qr, cr)\n circuit.append(inst, [qr[1], qr[2]], [cr[2], cr[1]])\n circuit_drawer(circuit, filename=filename, output=\"latex_source\")\n\n self.assertEqualToReference(filename)\n\n def test_cif_single_bit(self):\n \"\"\"Tests conditioning gates on single classical bit\"\"\"\n\n filename = self._get_resource_path(\"test_latex_cif_single_bit.tex\")\n qr = QuantumRegister(2, \"qr\")\n cr = ClassicalRegister(2, \"cr\")\n circuit = QuantumCircuit(qr, cr)\n circuit.h(qr[0]).c_if(cr[1], 0)\n circuit.x(qr[1]).c_if(cr[0], 1)\n circuit_drawer(circuit, cregbundle=False, filename=filename, output=\"latex_source\")\n\n self.assertEqualToReference(filename)\n\n def test_cif_single_bit_cregbundle(self):\n \"\"\"Tests conditioning gates on single classical bit with cregbundle\"\"\"\n\n filename = self._get_resource_path(\"test_latex_cif_single_bit_bundle.tex\")\n qr = QuantumRegister(2, \"qr\")\n cr = ClassicalRegister(2, \"cr\")\n circuit = QuantumCircuit(qr, cr)\n circuit.h(qr[0]).c_if(cr[1], 0)\n circuit.x(qr[1]).c_if(cr[0], 1)\n circuit_drawer(circuit, cregbundle=True, filename=filename, output=\"latex_source\")\n\n self.assertEqualToReference(filename)\n\n def test_registerless_one_bit(self):\n \"\"\"Text circuit with one-bit registers and registerless bits.\"\"\"\n filename = self._get_resource_path(\"test_latex_registerless_one_bit.tex\")\n qrx = QuantumRegister(2, \"qrx\")\n qry = QuantumRegister(1, \"qry\")\n crx = ClassicalRegister(2, \"crx\")\n circuit = QuantumCircuit(qrx, [Qubit(), Qubit()], qry, [Clbit(), Clbit()], crx)\n circuit_drawer(circuit, filename=filename, output=\"latex_source\")\n\n self.assertEqualToReference(filename)\n\n def test_measures_with_conditions(self):\n \"\"\"Test that a measure containing a condition displays\"\"\"\n filename1 = self._get_resource_path(\"test_latex_meas_cond_false.tex\")\n filename2 = self._get_resource_path(\"test_latex_meas_cond_true.tex\")\n qr = QuantumRegister(2, \"qr\")\n cr1 = ClassicalRegister(2, \"cr1\")\n cr2 = ClassicalRegister(2, \"cr2\")\n circuit = QuantumCircuit(qr, cr1, cr2)\n circuit.h(0)\n circuit.h(1)\n circuit.measure(0, cr1[1])\n circuit.measure(1, cr2[0]).c_if(cr1, 1)\n circuit.h(0).c_if(cr2, 3)\n circuit_drawer(circuit, cregbundle=False, filename=filename1, output=\"latex_source\")\n circuit_drawer(circuit, cregbundle=True, filename=filename2, output=\"latex_source\")\n self.assertEqualToReference(filename1)\n self.assertEqualToReference(filename2)\n\n def test_measures_with_conditions_with_bits(self):\n \"\"\"Condition and measure on single bits cregbundle true\"\"\"\n filename1 = self._get_resource_path(\"test_latex_meas_cond_bits_false.tex\")\n filename2 = self._get_resource_path(\"test_latex_meas_cond_bits_true.tex\")\n bits = [Qubit(), Qubit(), Clbit(), Clbit()]\n cr = ClassicalRegister(2, \"cr\")\n crx = ClassicalRegister(3, \"cs\")\n circuit = QuantumCircuit(bits, cr, [Clbit()], crx)\n circuit.x(0).c_if(crx[1], 0)\n circuit.measure(0, bits[3])\n circuit_drawer(circuit, cregbundle=False, filename=filename1, output=\"latex_source\")\n circuit_drawer(circuit, cregbundle=True, filename=filename2, output=\"latex_source\")\n self.assertEqualToReference(filename1)\n self.assertEqualToReference(filename2)\n\n\nif __name__ == \"__main__\":\n unittest.main(verbosity=2)\n"
]
| [
[
"numpy.eye",
"numpy.zeros"
]
]
|
Escapist-007/CVIP_Projects | [
"457dbdde3dca78229c2ae4eeb852681c42563ba9"
]
| [
"Project_01/Template_Matching/task1.py"
]
| [
"\"\"\"\n UB_ID : 50291708\n Name : Md Moniruzzaman Monir\n\nEdge Detection : (Due date: March 8th, 11: 59 P.M.)\n\nThe goal of this task is to experiment with two commonly used edge detection operator, i.e., Prewitt operator and Sobel operator,\nand familiarize you with 'tricks', e.g., padding, commonly used by computer vision 'researchers'.\n\nPlease complete all the functions that are labelled with '# TODO'. Hints or steps are provided to make your lives easier.\nWhem implementing the functions, comment the lines 'raise NotImplementedError' instead of deleting them.\n\nAs we have written lots of utility functions for you, you only need to write about 40 lines of code.\n\nThe functions defined in utils.py are building blocks you could use when implementing the functions labelled with 'TODO'.\n\nI strongly suggest you to read the function \"zero_pad\" that is defined in utils.py. It is quite important!\n\nDo NOT modify the code provided.\nDo NOT use any API provided by opencv (cv2) and numpy (np) in your code.\nDo NOT import any library (function, module, etc.).\n\nHow to run the script : python task1.py --img_path=\"data/proj1-task1.jpg\" --kernel=\"prewitt\" or python task1.py --img_path=\"data/proj1-task1.jpg\" --kernel=\"sobel\"\n\n\"\"\"\n\nimport argparse\nimport copy\nimport os\n\nimport cv2\nimport numpy as np\n\nimport utils\n\n# Prewitt operator\nprewitt_x = [[1, 0, -1]] * 3 \nprewitt_y = [[1] * 3, [0] * 3, [-1] * 3]\n\n# Sobel operator\nsobel_x = [[1, 0, -1], [2, 0, -2], [1, 0, -1]]\nsobel_y = [[-1, -2, -1], [0, 0, 0], [1, 2, 1]]\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description=\"cse 473/573 project 1.\")\n parser.add_argument(\n \"--img_path\", type=str, default=\"\",\n help=\"path to the image used for edge detection\")\n parser.add_argument(\n \"--kernel\", type=str, default=\"sobel\",\n choices=[\"prewitt\", \"sobel\", \"Prewitt\", \"Sobel\"],\n help=\"type of edge detector used for edge detection\")\n parser.add_argument(\n \"--result_saving_directory\", dest=\"rs_directory\", type=str, default=\"./results/\",\n help=\"directory to which results are saved (do not change this arg)\")\n args = parser.parse_args()\n return args\n\n\ndef read_image(img_path, show=False):\n \"\"\"Reads an image into memory as a grayscale array\"\"\"\n \n img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)\n \n if not img.dtype == np.uint8:\n pass\n\n if show:\n show_image(img)\n\n img = [list(row) for row in img] # converting to nested list\n return img\n\n\ndef show_image(img, delay=1000):\n \"\"\"Shows an image\"\"\"\n\n cv2.namedWindow('image', cv2.WINDOW_AUTOSIZE)\n cv2.imshow('image', img)\n cv2.waitKey(delay)\n cv2.destroyAllWindows()\n\n\ndef write_image(img, img_saving_path):\n \"\"\"Writes an image to a given path\"\"\"\n\n if isinstance(img, list):\n img = np.asarray(img, dtype=np.uint8)\n elif isinstance(img, np.ndarray):\n if not img.dtype == np.uint8:\n assert np.max(img) <= 1, \"Maximum pixel value {:.3f} is greater than 1\".format(np.max(img))\n img = (255 * img).astype(np.uint8)\n else:\n raise TypeError(\"img is neither a list nor a ndarray.\")\n\n cv2.imwrite(img_saving_path, img)\n\n \n \ndef convolve2d(img, kernel):\n \"\"\"Convolves a given image and a given kernel.\n \n Steps:\n (1) flips either the img or the kernel.\n\n (2) pads the img or the flipped img. This step handles pixels along the border of the img,\n and makes sure that the output img is of the same size as the input image.\n\n (3) applies the flipped kernel to the image or the kernel to the flipped image,using nested for loop.\n\n Args:\n img : nested list (int), image.\n kernel: nested list (int), kernel.\n\n Returns:\n img_conv: nested list (int), image.\n \"\"\"\n # TODO: DONE\n \n padding_layer = len(kernel)//2\n \n kernel = utils.flip2d(kernel) # flip the kernel\n img = utils.zero_pad(img,padding_layer,padding_layer) # padding the image\n \n row_count = len(img) \n col_count = len(img[0])\n \n # output image having same size as the input image\n img_conv = [] \n \n zeros = [0]*(col_count-2*padding_layer)\n\n for i in range(row_count-2*padding_layer):\n img_conv.insert(0, [0 for value in enumerate(zeros)])\n \n kernel_h = len(kernel)\n kernel_w = len(kernel[0])\n\n for i in range(row_count - kernel_h + 1):\n for j in range(col_count - kernel_w + 1):\n # multiplying the cropped portion with kernel\n mult_result = utils.elementwise_mul( utils.crop(img,i,i+kernel_h,j,j+kernel_w), kernel) \n sum = 0\n for p in range(len(mult_result)):\n for q in range(len(mult_result[p])):\n sum += mult_result[p][q]\n img_conv[i][j] = sum\n \n #raise NotImplementedError\n return img_conv\n\n\ndef normalize(img):\n \"\"\"Normalizes a given image.\n\n Hints:\n Normalize a given image using the following equation:\n \n normalized_img = frac{img - min(img)}{max(img) - min(img)},\n\n so that the maximum pixel value is 1 and the minimum pixel value is 0.\n\n Args:\n img: numpy.ndarray, np.uint8 --> image.\n\n Returns:\n normalized_img: numpy.ndarray, np.float32 --> normalized image.\n \"\"\"\n # TODO: DONE\n\n img = np.asarray(img,dtype=np.float32)\n\n max_value = max([max(row) for row in img])\n min_value = min([min(row) for row in img])\n \n diff = (max_value - min_value)\n \n for r in range(len(img)):\n for c in range(len(img[r])):\n img[r][c] = (img[r][c]-min_value) / diff\n \n # raise NotImplementedError\n return img\n\n\ndef detect_edges(img, kernel, norm=True):\n \"\"\"Detects edges using a given kernel.\n\n Args:\n img : nested list (int), image.\n kernel: nested list (int), kernel used to detect edges.\n norm (bool): whether to normalize the image or not.\n\n Returns:\n img_edge: nested list (int), image containing detected edges.\n \"\"\"\n # TODO: DONE\n \n # edge detection\n img_edge = convolve2d (img, kernel)\n \n # normalization\n if norm==True:\n img_edge = normalize(img_edge)\n \n #raise NotImplementedError\n return img_edge\n\n\ndef edge_magnitude(edge_x, edge_y):\n \"\"\"Calculate magnitude of edges by combining edges along two orthogonal directions.\n\n Hints:\n Combine edges along two orthogonal directions using the following equation:\n\n edge_mag = sqrt(edge_x ** 2 + edge_y **).\n\n Make sure that you normalize the edge_mag, so that the maximum pixel value is 1. ***\n\n Args:\n edge_x: nested list (int), image containing detected edges along one direction.\n edge_y: nested list (int), image containing detected edges along another direction.\n\n Returns:\n edge_mag: nested list (int), image containing magnitude of detected edges.\n \"\"\"\n \n # TODO: DONE\n edge_mag = copy.deepcopy(edge_x)\n \n for r in range(len(edge_mag)):\n for c in range(len(edge_mag[r])):\n x = edge_x[r][c] ** 2\n y = edge_y[r][c] ** 2\n edge_mag[r][c] = np.sqrt(x+y)\n\n edge_mag = normalize(edge_mag)\n #raise NotImplementedError\n return normalize(edge_mag)\n\n\ndef main():\n \n args = parse_args()\n\n img = read_image(args.img_path)\n\n if args.kernel in [\"prewitt\", \"Prewitt\"]:\n kernel_x = prewitt_x\n kernel_y = prewitt_y\n elif args.kernel in [\"sobel\", \"Sobel\"]:\n kernel_x = sobel_x\n kernel_y = sobel_y\n else:\n raise ValueError(\"Kernel type not recognized.\")\n\n if not os.path.exists(args.rs_directory):\n os.makedirs(args.rs_directory)\n\n img_edge_x = detect_edges(img, kernel_x, False)\n img_edge_x = np.asarray(img_edge_x)\n\n write_image(normalize(img_edge_x), os.path.join(args.rs_directory, \"{}_edge_x.jpg\".format(args.kernel.lower())))\n\n img_edge_y = detect_edges(img, kernel_y, False)\n img_edge_y = np.asarray(img_edge_y)\n\n write_image(normalize(img_edge_y), os.path.join(args.rs_directory, \"{}_edge_y.jpg\".format(args.kernel.lower())))\n\n img_edges = edge_magnitude(img_edge_x, img_edge_y)\n write_image(img_edges, os.path.join(args.rs_directory, \"{}_edge_mag.jpg\".format(args.kernel.lower())))\n\n\nif __name__ == \"__main__\":\n main()\n"
]
| [
[
"numpy.asarray",
"numpy.max",
"numpy.sqrt"
]
]
|
Cerenaut/rsm | [
"33bf8a3a620b46b5180280f2ca5f0b28c168b806"
]
| [
"rsm/datasets/text_embedding_dataset.py"
]
| [
"# Copyright (C) 2019 Project AGI\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"TextEmbeddingDataset class.\"\"\"\n\nimport logging\nimport os.path\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom pagi.datasets.dataset import Dataset\n\nfrom pagi.utils.embedding import SparseEmbedding, DenseEmbedding, SemanticEmbedding\n\n\nclass TextEmbeddingDataset(Dataset): # pylint: disable=W0223\n \"\"\"TextEmbeddingDataset based on tf.data.\"\"\"\n\n def __init__(self, directory):\n super(TextEmbeddingDataset, self).__init__(\n name='text-embedding',\n directory=directory,\n dataset_shape=[-1, 1, 1, 1],\n train_size=0,\n test_size=0,\n num_train_classes=0,\n num_test_classes=0,\n num_classes=0)\n\n self._use_sparse_embedding = True\n self._embedding = None\n self._embedding_shape = None\n\n self._max_length = 0\n self._subsets = {}\n\n def get_embedding(self):\n return self._embedding\n\n def get_subset(self, key):\n \"\"\"Get a subset of the data.\"\"\"\n if key in self._subsets:\n subset = self._subsets[key]\n return subset\n\n subset = {\n 'size': 0,\n 'corpus': None,\n 'offsets': np.zeros(self._batch_size, dtype=np.int32),\n 'lengths': np.zeros(self._batch_size, dtype=np.int32),\n 'mask': np.zeros(self._batch_size, dtype=np.float32) # Default zeros = clear all\n }\n self._subsets[key] = subset\n return subset\n\n def get_train(self, preprocess=False, options=None): # pylint: disable=W0221\n \"\"\"Returns tf.data.Dataset object \"\"\"\n return self._dataset(preprocess, options, self._embedding, 'train')\n\n def get_test(self, preprocess=False, options=None): # pylint: disable=W0221\n \"\"\"Returns tf.data.Dataset object \"\"\"\n return self._dataset(preprocess, options, self._embedding, 'test', random_offsets=False)\n\n def get_words(self, embedding, text_file, eos):\n \"\"\"Get a list of words from the corpus.\"\"\"\n del eos\n\n sentences = embedding.read_corpus_files([text_file])\n\n corpus = []\n for sentence in sentences:\n for word in sentence:\n corpus.append(word)\n\n return corpus\n\n def is_test_state(self, subset):\n \"\"\"Check if subset contains test state.\"\"\"\n # A note about timing.\n # The current input x or label l is predicted withut using current x\n # Perplexity is measured every step\n # We are OK (for now) training every step\n # algo does:\n # classification_loss = self._build_classification_loss(self._label_values, next_prediction)\n # algo predicts the CURRENT label, which means the *last* element of the sequence\n # if the NEXT value z=0.\n subset = self.get_subset(subset)\n sequence_lengths = subset['lengths']\n\n max_length = self._max_length\n if max_length == 0:\n return False # All test states, so meaningless\n\n # Since theyre all synchronized, we only need to check one\n z = sequence_lengths[0]\n if z == 0:\n return True\n return False\n\n def _create_embedding(self, train_text_file, test_text_file, embedding_file, embedding_shape,\n embedding_sparsity, eos):\n if self._embedding_type == 'sparse':\n return self._create_sparse_embedding(train_text_file, test_text_file, embedding_file, embedding_shape,\n embedding_sparsity, eos)\n if self._embedding_type == 'dense':\n return self._create_dense_embedding(train_text_file, test_text_file, embedding_file, embedding_shape,\n embedding_sparsity, eos)\n return self._create_semantic_embedding(train_text_file, test_text_file, embedding_file, embedding_shape,\n embedding_sparsity, eos)\n\n def _create_sparse_embedding(self, train_text_file, test_text_file, embedding_file, embedding_shape,\n embedding_sparsity, eos):\n \"\"\"Create a sparse embedding.\"\"\"\n embedding = SparseEmbedding()\n if not os.path.isfile(embedding_file):\n logging.info('Creating sparse embedding...')\n embedding.create([train_text_file, test_text_file], embedding_file, embedding_shape, embedding_sparsity, eos)\n\n logging.info('Reading embedding...')\n embedding.read(embedding_file)\n\n # embedding.check()\n\n return embedding, embedding_shape\n\n def _create_dense_embedding(self, train_text_file, test_text_file, embedding_file, embedding_shape,\n embedding_sparsity, eos):\n \"\"\"Create a dense embedding.\"\"\"\n embedding = DenseEmbedding()\n corpus_files = [train_text_file, test_text_file]\n if not os.path.isfile(embedding_file):\n logging.info('Creating dense embedding...')\n embedding_shape = embedding.create(corpus_files, embedding_file, embedding_shape, embedding_sparsity, eos)\n else:\n embedding_shape = embedding.create_shape(corpus_files, eos)\n\n logging.info('Reading embedding...')\n embedding.read(embedding_file)\n\n return embedding, embedding_shape\n\n def _create_semantic_embedding(self, train_text_file, test_text_file, embedding_file, embedding_shape,\n embedding_sparsity, eos):\n \"\"\"Create a semantic embedding.\"\"\"\n embedding = SemanticEmbedding()\n if not os.path.isfile(embedding_file):\n logging.info('Creating semantic embedding...')\n embedding.create([train_text_file, test_text_file], embedding_file, embedding_shape, embedding_sparsity, eos)\n\n logging.info('Reading embedding...')\n embedding.read(embedding_file)\n return embedding, embedding_shape\n\n def setup(self, batch_size, train_text_file, test_text_file, embedding_type, embedding_file, embedding_shape,\n embedding_sparsity, max_sequence_length, eos='<end>'):\n \"\"\"Setup the text embedding dataset.\"\"\"\n\n embedding_size = np.prod(embedding_shape[:])\n logging.info('Batch size: %s', str(batch_size))\n logging.info('Training corpus file: %s', train_text_file)\n logging.info('Testing corpus file: %s', test_text_file)\n logging.info('Embedding type: %s', embedding_type)\n logging.info('Embedding file: %s', embedding_file)\n logging.info('Embedding size: %s', str(embedding_size))\n logging.info('Max seq. len.: %s', str(max_sequence_length))\n\n self._eos = eos\n self._embedding_type = embedding_type\n self._batch_size = int(batch_size)\n self._max_length = int(max_sequence_length)\n\n self._embedding, self._embedding_shape = self._create_embedding(train_text_file, test_text_file, embedding_file,\n embedding_shape, embedding_sparsity, eos)\n\n emb_keys = self._embedding.get_num_keys()\n emb_vals = self._embedding.get_num_values()\n\n logging.info('Embedding has %s keys and %s values.', str(emb_keys), str(emb_vals))\n\n corpus_train = self.get_words(self._embedding, train_text_file, self._eos)\n corpus_test = self.get_words(self._embedding, test_text_file, self._eos)\n\n ok_train = self._embedding.has_keys(corpus_train)\n ok_test = self._embedding.has_keys(corpus_test)\n\n if ok_train and ok_test:\n logging.info('All tokens found in embedding.')\n else:\n logging.error('Some tokens missing from embedding.')\n\n # Override base dataset properties:\n self._dataset_shape = [-1, self._embedding_shape[0], self._embedding_shape[1], 1]\n self._num_classes = emb_keys\n\n train_size = len(corpus_train)\n test_size = len(corpus_test)\n\n train_subset = self.get_subset('train')\n test_subset = self.get_subset('test')\n\n train_subset['size'] = train_size\n test_subset['size'] = test_size\n\n train_subset['corpus'] = corpus_train\n test_subset['corpus'] = corpus_test\n\n def get_embedding_shape(self):\n return self._embedding_shape\n\n def _dataset(self, preprocess, options, embedding, subset_key, random_offsets=True): # pylint: disable=W0613, W0221\n \"\"\"Generate a dataset from the provided sentences & embedding.\"\"\"\n\n max_length = self._max_length\n subset = self.get_subset(subset_key)\n\n words = subset['corpus']\n sequence_offsets = subset['offsets']\n sequence_lengths = subset['lengths']\n reset_masks = subset['mask']\n num_words = subset['size']\n\n logging.info('Dataset subset %s has %d tokens.', subset_key, num_words)\n\n # Default max seq len is the corpus size; but can be made shorter\n max_seq_length = num_words\n if max_length > 0:\n max_seq_length = max_length # Truncate sequences to this length\n\n # Initialise the sequence list with N (=batch_size) sequences\n embedding_shape = [self._embedding_shape[0], self._embedding_shape[1], 1]\n\n def get_random_index(num_words, max_length):\n # Say we have max_length = 5 and num_words = 100\n # Valid indices are 0..99\n # 100-5 = 95\n # i z1 z2\n # 95 0 1\n # 96 1 2\n # 97 2 3\n # 98 3 4\n # 99 4 5 >= 5 --> 0\n i = np.random.randint(num_words - max_length) # don't pick truncated seq\n return i\n\n # init the batch of indices into the corpus\n for b in range(self._batch_size):\n if random_offsets:\n i = get_random_index(num_words, max_length)\n sequence_offsets[b] = i\n\n def sequence_generator():\n \"\"\"Batch sequence generator.\"\"\"\n\n # Loop indefinitely\n while True:\n for b in range(self._batch_size):\n\n i = sequence_offsets[b]\n z = sequence_lengths[b]\n\n key = words[i] # CURRENT input\n\n z = z + 1 # Increase length\n i = i +1 # NEXT index.\n mask = 1.0 # keep\n\n # Wrap @ fixed length smaller than the dataset\n # Or if we've watche a sequence of defined length\n if z >= max_seq_length:\n z = 0\n if random_offsets:\n i = get_random_index(num_words, max_length)\n else:\n i = 0\n mask = 0.0 # clear\n\n # Wrap @ end of corpus\n if i >= num_words:\n #z = 0 don't truncate the sequence counter\n i = 0 # Wrap to start\n mask = 0.0 # clear\n\n logging.debug('Dataset subset: %s batch %d mask: %f offset: %s len: %d of %d',\n subset_key, b, mask, i, z, num_words)\n\n sequence_offsets[b] = i\n sequence_lengths[b] = z\n reset_masks[b] = mask # need to produce a mask for NEXT sample.\n\n values = self._embedding.get_values(key)\n values_3d = np.reshape(values, embedding_shape)\n label = self._embedding.get_index(key)\n\n yield (values_3d, label)\n\n # Calculate size of embedding\n output_shapes = (tf.TensorShape(embedding_shape), tf.TensorShape([]))\n\n return tf.data.Dataset.from_generator(sequence_generator, output_types=(tf.float32, tf.int32),\n output_shapes=output_shapes)\n"
]
| [
[
"tensorflow.TensorShape",
"numpy.reshape",
"numpy.prod",
"tensorflow.data.Dataset.from_generator",
"numpy.zeros",
"numpy.random.randint"
]
]
|
Ali-Parandeh/Transfer_Learning_Image_Classifier | [
"b887a14053d30dd14ed340d88cd02b1ccde190fc"
]
| [
"train.py"
]
| [
"# PROGRAMMER: Alireza Parandeh\n# DATE CREATED: 22.06.2019\n# REVISED DATE:\n# PURPOSE: Create functions to train a new network on a dataset and save the model as a checkpoint.\n# Also, Prints out training loss, validation loss, and validation accuracy as the network trains\n\nimport torch\nfrom torch import nn\nfrom torchvision import datasets, transforms, models\nfrom classifier import Classifier, Arguments\nfrom args import get_training_input_args\n\n\n# Defining transforms for the training, validation, and testing sets\ndef data_loader(data_dir):\n # I'm just going to put my hands in the training flower basket and shuffle, cut and skew my flowers\n train_dir = data_dir + '/train'\n valid_dir = data_dir + '/valid'\n test_dir = data_dir + '/test'\n train_transforms = transforms.Compose([transforms.RandomRotation(30),\n transforms.RandomResizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406],\n [0.229, 0.224, 0.225])])\n\n test_valid_transforms = transforms.Compose([transforms.Resize(255),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406],\n [0.229, 0.224, 0.225])])\n\n # Loading the datasets with ImageFolder\n data = {}\n data[\"train_data\"] = datasets.ImageFolder(train_dir, transform=train_transforms)\n data[\"test_data\"] = datasets.ImageFolder(test_dir, transform=test_valid_transforms)\n data[\"valid_data\"] = datasets.ImageFolder(valid_dir, transform=test_valid_transforms)\n\n # Using the image datasets and the trainforms, define the dataloaders\n data_iterator = {}\n data_iterator[\"train_loader\"] = torch.utils.data.DataLoader(data[\"train_data\"],\n batch_size=64, shuffle=True)\n data_iterator[\"test_loader\"] = torch.utils.data.DataLoader(data[\"test_data\"],\n batch_size=64, shuffle=True)\n data_iterator[\"valid_loader\"] = torch.utils.data.DataLoader(data[\"valid_data\"],\n batch_size=64, shuffle=True)\n return data, data_iterator\n\n\n# Trains the Network\ndef train(model, device, train_iterator, valid_iterator, criterion, optimizer, epochs):\n ''' Trains a neural network.\n\n Arguments\n ---------\n model: Un-trained Model\n train_iterator: a data generator that can provide a batch of data for training the model\n valid_iterator: a data generator that can provide a batch of data for validating the model\n criterion: Torch Function, Is used to calculate the error loss\n device: string that specifies what hardware the validation should be run on\n optimizer: Torch Module, Optimises the model weights per epoch\n \n Outputs\n ---------\n model: Trained Model\n training_losses: A list of average training losses in percentage of the batch per epoch\n validation_losses: A list of average validation losses of the batch per epoch\n validation_accuracies: A list of average accuracies in percentage of the batch per epoch\n\n '''\n for e in range(epochs):\n training_loss = 0\n validation_loss = 0\n validation_accuracy = 0\n model.train()\n # Perform a training pass for all images\n for images, labels in train_iterator:\n optimizer.zero_grad()\n images, labels = images.to(device), labels.to(device)\n train_logits = model(images)\n loss = criterion(train_logits, labels)\n loss.backward()\n optimizer.step()\n training_loss += loss.item()\n\n # Perform a validation pass for all images\n else:\n\n with torch.no_grad():\n validation_loss, validation_accuracy = validation(model, valid_iterator, criterion, device)\n\n print(f\"Device = {device}\", \"Epoch {}/{}.. \".format(e+1, epochs),\n \"Training Loss: {:.3f}.. \".format(\n training_loss/len(train_iterator)),\n \"Validation Loss: {:.3f}.. \".format(\n validation_loss/len(valid_iterator)),\n \"Validation Accuracy: {:.3f}\".format(validation_accuracy/len(valid_iterator)))\n\n model.train()\n\n return model\n\n\ndef validation(model, data_iterator, criterion, device):\n ''' Validates the predictions of the network.\n\n Arguments\n ---------\n - model: dictionary, neural network model\n - data_iterator: a data iterator that can provide a batch of data for validation\n - criterion: Torch function, Is used to calculate the error loss\n - device: string that specifies what hardware the validation should be run on\n \n Outputs\n ---------\n - test_loss: Average loss per batch\n - accuracy: Average accuracy in percentage per batch\n\n '''\n model.eval()\n validation_loss = 0\n validation_accuracy = 0\n for images, labels in data_iterator:\n images, labels = images.to(device), labels.to(device)\n valid_logits = model.forward(images)\n validation_loss += criterion(valid_logits, labels)\n ps = torch.exp(valid_logits)\n top_p, top_class = ps.topk(1, dim=1)\n equality = top_class == labels.view(*top_class.shape)\n validation_accuracy += torch.mean(equality.type(torch.FloatTensor))\n\n return validation_loss, validation_accuracy\n\n\n# Save the checkpoint\ndef save_model(model, data, checkpoint_dir, optimizer):\n ''' Saves the model checkpoint into a tph file\n '''\n model.class_to_idx = data.class_to_idx\n\n checkpoint = {\"class_to_idx\": data.class_to_idx,\n \"model\": model,\n \"state_dict\": model.state_dict(),\n \"optimiser_state_dict\": optimizer.state_dict()}\n\n torch.save(checkpoint, checkpoint_dir)\n\n print(\"Model Saved!\")\n\n\ndef main():\n # Get user inputs for constructing and training a model.\n ti = get_training_input_args()\n data, data_iterator = data_loader(ti.dir)\n\n if ti.arch == \"vgg16\":\n model = models.vgg16(pretrained=True)\n input_features = model.classifier[0].in_features\n checkpoint_dir = ti.save_dir + \"vgg16_checkpoint.pth\"\n else:\n model = models.densenet121(pretrained=True)\n input_features = model.classifier.in_features\n checkpoint_dir = ti.save_dir + \"densenet121_checkpoint.pth\"\n\n # Freeze all parameters. When the classifier later on is replaced with our own, only our classifier parameters will be updated during training.\n for param in model.parameters():\n param.requires_grad = False\n\n # Replacing the pre-trained model classifier with my own. The previous classifier parameters were frozen. Mine aren't so now if I train the network, only parameters of my classifier will be updated not the features layer.\n model.classifier = Classifier(input_features, 102, ti.hidden_units, drop_p=ti.dropout)\n hyperparams = Arguments(model, ti.gpu, ti.learning_rate, ti.epochs)\n model = model.to(hyperparams.device)\n\n model = train(\n model,\n hyperparams.device,\n data_iterator[\"train_loader\"],\n data_iterator[\"train_loader\"],\n hyperparams.criterion,\n hyperparams.optimizer,\n hyperparams.epochs)\n\n save_model(model, data[\"train_data\"], checkpoint_dir, hyperparams.optimizer)\n\n\nif __name__ == \"__main__\":\n main()\n"
]
| [
[
"torch.exp",
"torch.no_grad",
"torch.utils.data.DataLoader",
"torch.save"
]
]
|
kyleclo/allennlp | [
"0205c26f3db7ef44d7ee70fa9ebdf5a7f6b43baf",
"0205c26f3db7ef44d7ee70fa9ebdf5a7f6b43baf"
]
| [
"allennlp/training/checkpointer.py",
"allennlp/models/encoder_decoders/copynet_seq2seq.py"
]
| [
"from typing import Union, Dict, Any, List, Tuple\n\nimport logging\nimport os\nimport re\nimport shutil\nimport time\n\nimport torch\n\nfrom allennlp.nn import util as nn_util\n\nlogger = logging.getLogger(__name__)\n\nclass Checkpointer:\n \"\"\"\n This class implements the functionality for checkpointing your model and trainer state\n during training. It is agnostic as to what those states look like (they are typed as\n Dict[str, Any]), but they will be fed to ``torch.save`` so they should be serializable\n in that sense. They will also be restored as Dict[str, Any], which means the calling\n code is responsible for knowing what to do with them.\n \"\"\"\n def __init__(self,\n serialization_dir: str = None,\n keep_serialized_model_every_num_seconds: int = None,\n num_serialized_models_to_keep: int = 20) -> None:\n self._serialization_dir = serialization_dir\n self._keep_serialized_model_every_num_seconds = keep_serialized_model_every_num_seconds\n self._num_serialized_models_to_keep = num_serialized_models_to_keep\n\n self._last_permanent_saved_checkpoint_time = time.time()\n self._serialized_paths: List[Tuple[float, str, str]] = []\n\n def save_checkpoint(self,\n epoch: Union[int, str],\n model_state: Dict[str, Any],\n training_states: Dict[str, Any],\n is_best_so_far: bool) -> None:\n if self._serialization_dir is not None:\n model_path = os.path.join(self._serialization_dir, \"model_state_epoch_{}.th\".format(epoch))\n torch.save(model_state, model_path)\n training_path = os.path.join(self._serialization_dir,\n \"training_state_epoch_{}.th\".format(epoch))\n torch.save({**training_states, \"epoch\": epoch}, training_path)\n\n if is_best_so_far:\n logger.info(\"Best validation performance so far. \"\n \"Copying weights to '%s/best.th'.\", self._serialization_dir)\n shutil.copyfile(model_path, os.path.join(self._serialization_dir, \"best.th\"))\n\n if self._num_serialized_models_to_keep and self._num_serialized_models_to_keep >= 0:\n self._serialized_paths.append((time.time(), model_path, training_path))\n if len(self._serialized_paths) > self._num_serialized_models_to_keep:\n paths_to_remove = self._serialized_paths.pop(0)\n # Check to see if we should keep this checkpoint, if it has been longer\n # then self._keep_serialized_model_every_num_seconds since the last\n # kept checkpoint.\n remove_path = True\n if self._keep_serialized_model_every_num_seconds is not None:\n save_time = paths_to_remove[0]\n time_since_checkpoint_kept = save_time - self._last_permanent_saved_checkpoint_time\n if time_since_checkpoint_kept > self._keep_serialized_model_every_num_seconds:\n # We want to keep this checkpoint.\n remove_path = False\n self._last_permanent_saved_checkpoint_time = save_time\n if remove_path:\n for fname in paths_to_remove[1:]:\n os.remove(fname)\n\n def find_latest_checkpoint(self) -> Tuple[str, str]:\n \"\"\"\n Return the location of the latest model and training state files.\n If there isn't a valid checkpoint then return None.\n \"\"\"\n have_checkpoint = (self._serialization_dir is not None and\n any(\"model_state_epoch_\" in x for x in os.listdir(self._serialization_dir)))\n\n if not have_checkpoint:\n return None\n\n serialization_files = os.listdir(self._serialization_dir)\n model_checkpoints = [x for x in serialization_files if \"model_state_epoch\" in x]\n # Get the last checkpoint file. Epochs are specified as either an\n # int (for end of epoch files) or with epoch and timestamp for\n # within epoch checkpoints, e.g. 5.2018-02-02-15-33-42\n found_epochs = [\n re.search(r\"model_state_epoch_([0-9\\.\\-]+)\\.th\", x).group(1)\n for x in model_checkpoints\n ]\n int_epochs: Any = []\n for epoch in found_epochs:\n pieces = epoch.split('.')\n if len(pieces) == 1:\n # Just a single epoch without timestamp\n int_epochs.append([int(pieces[0]), '0'])\n else:\n # has a timestamp\n int_epochs.append([int(pieces[0]), pieces[1]])\n last_epoch = sorted(int_epochs, reverse=True)[0]\n if last_epoch[1] == '0':\n epoch_to_load = str(last_epoch[0])\n else:\n epoch_to_load = '{0}.{1}'.format(last_epoch[0], last_epoch[1])\n\n model_path = os.path.join(self._serialization_dir,\n \"model_state_epoch_{}.th\".format(epoch_to_load))\n training_state_path = os.path.join(self._serialization_dir,\n \"training_state_epoch_{}.th\".format(epoch_to_load))\n\n return (model_path, training_state_path)\n\n def restore_checkpoint(self) -> Tuple[Dict[str, Any], Dict[str, Any]]:\n \"\"\"\n Restores a model from a serialization_dir to the last saved checkpoint.\n This includes a training state (typically consisting of an epoch count and optimizer state),\n which is serialized separately from model parameters. This function should only be used to\n continue training - if you wish to load a model for inference/load parts of a model into a new\n computation graph, you should use the native Pytorch functions:\n `` model.load_state_dict(torch.load(\"/path/to/model/weights.th\"))``\n\n If ``self._serialization_dir`` does not exist or does not contain any checkpointed weights,\n this function will do nothing and return empty dicts.\n\n Returns\n -------\n states: Tuple[Dict[str, Any], Dict[str, Any]]\n The model state and the training state.\n \"\"\"\n latest_checkpoint = self.find_latest_checkpoint()\n\n if latest_checkpoint is None:\n # No checkpoint to restore, start at 0\n return {}, {}\n\n model_path, training_state_path = latest_checkpoint\n\n # Load the parameters onto CPU, then transfer to GPU.\n # This avoids potential OOM on GPU for large models that\n # load parameters onto GPU then make a new GPU copy into the parameter\n # buffer. The GPU transfer happens implicitly in load_state_dict.\n model_state = torch.load(model_path, map_location=nn_util.device_mapping(-1))\n training_state = torch.load(training_state_path, map_location=nn_util.device_mapping(-1))\n return model_state, training_state\n\n def best_model_state(self) -> Dict[str, Any]:\n if self._serialization_dir:\n logger.info(\"loading best weights\")\n best_model_state_path = os.path.join(self._serialization_dir, 'best.th')\n return torch.load(best_model_state_path)\n else:\n logger.info(\"cannot load best weights without `serialization_dir`, \"\n \"so you're just getting the last weights\")\n return {}\n",
"import logging\nfrom typing import Dict, Tuple, List, Any, Union\n\nimport numpy\nfrom overrides import overrides\nimport torch\nfrom torch.nn.modules.linear import Linear\nfrom torch.nn.modules.rnn import LSTMCell\n\nfrom allennlp.common.util import START_SYMBOL, END_SYMBOL\nfrom allennlp.data.vocabulary import Vocabulary\nfrom allennlp.models.model import Model\nfrom allennlp.modules import Attention, TextFieldEmbedder, Seq2SeqEncoder\nfrom allennlp.modules.token_embedders import Embedding\nfrom allennlp.nn import util\nfrom allennlp.training.metrics import Metric, BLEU\nfrom allennlp.nn.beam_search import BeamSearch\n\n\nlogger = logging.getLogger(__name__) # pylint: disable=invalid-name\n\n\[email protected](\"copynet_seq2seq\")\nclass CopyNetSeq2Seq(Model):\n \"\"\"\n This is an implementation of `CopyNet <https://arxiv.org/pdf/1603.06393>`_.\n CopyNet is a sequence-to-sequence encoder-decoder model with a copying mechanism\n that can copy tokens from the source sentence into the target sentence instead of\n generating all target tokens only from the target vocabulary.\n\n It is very similar to a typical seq2seq model used in neural machine translation\n tasks, for example, except that in addition to providing a \"generation\" score at each timestep\n for the tokens in the target vocabulary, it also provides a \"copy\" score for each\n token that appears in the source sentence. In other words, you can think of CopyNet\n as a seq2seq model with a dynamic target vocabulary that changes based on the tokens\n in the source sentence, allowing it to predict tokens that are out-of-vocabulary (OOV)\n with respect to the actual target vocab.\n\n Parameters\n ----------\n vocab : ``Vocabulary``, required\n Vocabulary containing source and target vocabularies.\n source_embedder : ``TextFieldEmbedder``, required\n Embedder for source side sequences\n encoder : ``Seq2SeqEncoder``, required\n The encoder of the \"encoder/decoder\" model\n attention : ``Attention``, required\n This is used to get a dynamic summary of encoder outputs at each timestep\n when producing the \"generation\" scores for the target vocab.\n beam_size : ``int``, required\n Beam width to use for beam search prediction.\n max_decoding_steps : ``int``, required\n Maximum sequence length of target predictions.\n target_embedding_dim : ``int``, optional (default = 30)\n The size of the embeddings for the target vocabulary.\n copy_token : ``str``, optional (default = '@COPY@')\n The token used to indicate that a target token was copied from the source.\n If this token is not already in your target vocabulary, it will be added.\n source_namespace : ``str``, optional (default = 'source_tokens')\n The namespace for the source vocabulary.\n target_namespace : ``str``, optional (default = 'target_tokens')\n The namespace for the target vocabulary.\n tensor_based_metric : ``Metric``, optional (default = BLEU)\n A metric to track on validation data that takes raw tensors when its called.\n This metric must accept two arguments when called: a batched tensor\n of predicted token indices, and a batched tensor of gold token indices.\n token_based_metric : ``Metric``, optional (default = None)\n A metric to track on validation data that takes lists of lists of tokens\n as input. This metric must accept two arguments when called, both\n of type `List[List[str]]`. The first is a predicted sequence for each item\n in the batch and the second is a gold sequence for each item in the batch.\n \"\"\"\n\n def __init__(self,\n vocab: Vocabulary,\n source_embedder: TextFieldEmbedder,\n encoder: Seq2SeqEncoder,\n attention: Attention,\n beam_size: int,\n max_decoding_steps: int,\n target_embedding_dim: int = 30,\n copy_token: str = \"@COPY@\",\n source_namespace: str = \"source_tokens\",\n target_namespace: str = \"target_tokens\",\n tensor_based_metric: Metric = None,\n token_based_metric: Metric = None) -> None:\n super().__init__(vocab)\n self._source_namespace = source_namespace\n self._target_namespace = target_namespace\n self._src_start_index = self.vocab.get_token_index(START_SYMBOL, self._source_namespace)\n self._src_end_index = self.vocab.get_token_index(END_SYMBOL, self._source_namespace)\n self._start_index = self.vocab.get_token_index(START_SYMBOL, self._target_namespace)\n self._end_index = self.vocab.get_token_index(END_SYMBOL, self._target_namespace)\n self._oov_index = self.vocab.get_token_index(self.vocab._oov_token, self._target_namespace) # pylint: disable=protected-access\n self._pad_index = self.vocab.get_token_index(self.vocab._padding_token, self._target_namespace) # pylint: disable=protected-access\n self._copy_index = self.vocab.add_token_to_namespace(copy_token, self._target_namespace)\n\n self._tensor_based_metric = tensor_based_metric or \\\n BLEU(exclude_indices={self._pad_index, self._end_index, self._start_index})\n self._token_based_metric = token_based_metric\n\n self._target_vocab_size = self.vocab.get_vocab_size(self._target_namespace)\n\n # Encoding modules.\n self._source_embedder = source_embedder\n self._encoder = encoder\n\n # Decoder output dim needs to be the same as the encoder output dim since we initialize the\n # hidden state of the decoder with the final hidden state of the encoder.\n # We arbitrarily set the decoder's input dimension to be the same as the output dimension.\n self.encoder_output_dim = self._encoder.get_output_dim()\n self.decoder_output_dim = self.encoder_output_dim\n self.decoder_input_dim = self.decoder_output_dim\n\n target_vocab_size = self.vocab.get_vocab_size(self._target_namespace)\n\n # The decoder input will be a function of the embedding of the previous predicted token,\n # an attended encoder hidden state called the \"attentive read\", and another\n # weighted sum of the encoder hidden state called the \"selective read\".\n # While the weights for the attentive read are calculated by an `Attention` module,\n # the weights for the selective read are simply the predicted probabilities\n # corresponding to each token in the source sentence that matches the target\n # token from the previous timestep.\n self._target_embedder = Embedding(target_vocab_size, target_embedding_dim)\n self._attention = attention\n self._input_projection_layer = Linear(\n target_embedding_dim + self.encoder_output_dim * 2,\n self.decoder_input_dim)\n\n # We then run the projected decoder input through an LSTM cell to produce\n # the next hidden state.\n self._decoder_cell = LSTMCell(self.decoder_input_dim, self.decoder_output_dim)\n\n # We create a \"generation\" score for each token in the target vocab\n # with a linear projection of the decoder hidden state.\n self._output_generation_layer = Linear(self.decoder_output_dim, target_vocab_size)\n\n # We create a \"copying\" score for each source token by applying a non-linearity\n # (tanh) to a linear projection of the encoded hidden state for that token,\n # and then taking the dot product of the result with the decoder hidden state.\n self._output_copying_layer = Linear(self.encoder_output_dim, self.decoder_output_dim)\n\n # At prediction time, we'll use a beam search to find the best target sequence.\n self._beam_search = BeamSearch(self._end_index, max_steps=max_decoding_steps, beam_size=beam_size)\n\n @overrides\n def forward(self, # type: ignore\n source_tokens: Dict[str, torch.LongTensor],\n source_token_ids: torch.Tensor,\n source_to_target: torch.Tensor,\n metadata: List[Dict[str, Any]],\n target_tokens: Dict[str, torch.LongTensor] = None,\n target_token_ids: torch.Tensor = None) -> Dict[str, torch.Tensor]:\n # pylint: disable=arguments-differ\n \"\"\"\n Make foward pass with decoder logic for producing the entire target sequence.\n\n Parameters\n ----------\n source_tokens : ``Dict[str, torch.LongTensor]``, required\n The output of `TextField.as_array()` applied on the source `TextField`. This will be\n passed through a `TextFieldEmbedder` and then through an encoder.\n source_token_ids : ``torch.Tensor``, required\n Tensor containing IDs that indicate which source tokens match each other.\n Has shape: `(batch_size, trimmed_source_length)`.\n source_to_target : ``torch.Tensor``, required\n Tensor containing vocab index of each source token with respect to the\n target vocab namespace. Shape: `(batch_size, trimmed_source_length)`.\n metadata : ``List[Dict[str, Any]]``, required\n Metadata field that contains the original source tokens with key 'source_tokens'\n and any other meta fields. When 'target_tokens' is also passed, the metadata\n should also contain the original target tokens with key 'target_tokens'.\n target_tokens : ``Dict[str, torch.LongTensor]``, optional (default = None)\n Output of `Textfield.as_array()` applied on target `TextField`. We assume that the\n target tokens are also represented as a `TextField` which must contain a \"tokens\"\n key that uses single ids.\n target_token_ids : ``torch.Tensor``, optional (default = None)\n A tensor of shape `(batch_size, target_sequence_length)` which indicates which\n tokens in the target sequence match tokens in the source sequence.\n\n Returns\n -------\n Dict[str, torch.Tensor]\n \"\"\"\n state = self._encode(source_tokens)\n state[\"source_token_ids\"] = source_token_ids\n state[\"source_to_target\"] = source_to_target\n\n if target_tokens:\n state = self._init_decoder_state(state)\n output_dict = self._forward_loss(target_tokens, target_token_ids, state)\n else:\n output_dict = {}\n\n output_dict[\"metadata\"] = metadata\n\n if not self.training:\n state = self._init_decoder_state(state)\n predictions = self._forward_beam_search(state)\n output_dict.update(predictions)\n if target_tokens:\n if self._tensor_based_metric is not None:\n # shape: (batch_size, beam_size, max_sequence_length)\n top_k_predictions = output_dict[\"predictions\"]\n # shape: (batch_size, max_predicted_sequence_length)\n best_predictions = top_k_predictions[:, 0, :]\n # shape: (batch_size, target_sequence_length)\n gold_tokens = self._gather_extended_gold_tokens(target_tokens[\"tokens\"],\n source_token_ids,\n target_token_ids)\n self._tensor_based_metric(best_predictions, gold_tokens) # type: ignore\n if self._token_based_metric is not None:\n predicted_tokens = self._get_predicted_tokens(output_dict[\"predictions\"],\n metadata,\n n_best=1)\n self._token_based_metric(predicted_tokens, # type: ignore\n [x[\"target_tokens\"] for x in metadata])\n\n return output_dict\n\n def _gather_extended_gold_tokens(self,\n target_tokens: torch.Tensor,\n source_token_ids: torch.Tensor,\n target_token_ids: torch.Tensor) -> torch.LongTensor:\n \"\"\"\n Modify the gold target tokens relative to the extended vocabulary.\n\n For gold targets that are OOV but were copied from the source, the OOV index\n will be changed to the index of the first occurence in the source sentence,\n offset by the size of the target vocabulary.\n\n Parameters\n ----------\n target_tokens : ``torch.Tensor``\n Shape: `(batch_size, target_sequence_length)`.\n source_token_ids : ``torch.Tensor``\n Shape: `(batch_size, trimmed_source_length)`.\n target_token_ids : ``torch.Tensor``\n Shape: `(batch_size, target_sequence_length)`.\n\n Returns\n -------\n torch.Tensor\n Modified `target_tokens` with OOV indices replaced by offset index\n of first match in source sentence.\n \"\"\"\n batch_size, target_sequence_length = target_tokens.size()\n trimmed_source_length = source_token_ids.size(1)\n # Only change indices for tokens that were OOV in target vocab but copied from source.\n # shape: (batch_size, target_sequence_length)\n oov = (target_tokens == self._oov_index)\n # shape: (batch_size, target_sequence_length, trimmed_source_length)\n expanded_source_token_ids = source_token_ids\\\n .unsqueeze(1)\\\n .expand(batch_size, target_sequence_length, trimmed_source_length)\n # shape: (batch_size, target_sequence_length, trimmed_source_length)\n expanded_target_token_ids = target_token_ids\\\n .unsqueeze(-1)\\\n .expand(batch_size, target_sequence_length, trimmed_source_length)\n # shape: (batch_size, target_sequence_length, trimmed_source_length)\n matches = (expanded_source_token_ids == expanded_target_token_ids)\n # shape: (batch_size, target_sequence_length)\n copied = (matches.sum(-1) > 0)\n # shape: (batch_size, target_sequence_length)\n mask = (oov & copied).long()\n # shape: (batch_size, target_sequence_length)\n first_match = ((matches.cumsum(-1) == 1) * matches).argmax(-1)\n # shape: (batch_size, target_sequence_length)\n new_target_tokens = target_tokens * (1 - mask) + (first_match.long() + self._target_vocab_size) * mask\n return new_target_tokens\n\n def _init_decoder_state(self, state: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:\n \"\"\"\n Initialize the encoded state to be passed to the first decoding time step.\n \"\"\"\n batch_size, _ = state[\"source_mask\"].size()\n\n # Initialize the decoder hidden state with the final output of the encoder,\n # and the decoder context with zeros.\n # shape: (batch_size, encoder_output_dim)\n final_encoder_output = util.get_final_encoder_states(\n state[\"encoder_outputs\"],\n state[\"source_mask\"],\n self._encoder.is_bidirectional())\n # shape: (batch_size, decoder_output_dim)\n state[\"decoder_hidden\"] = final_encoder_output\n # shape: (batch_size, decoder_output_dim)\n state[\"decoder_context\"] = state[\"encoder_outputs\"].new_zeros(batch_size, self.decoder_output_dim)\n\n return state\n\n def _encode(self, source_tokens: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:\n \"\"\"\n Encode source input sentences.\n \"\"\"\n # shape: (batch_size, max_input_sequence_length, encoder_input_dim)\n embedded_input = self._source_embedder(source_tokens)\n # shape: (batch_size, max_input_sequence_length)\n source_mask = util.get_text_field_mask(source_tokens)\n # shape: (batch_size, max_input_sequence_length, encoder_output_dim)\n encoder_outputs = self._encoder(embedded_input, source_mask)\n return {\"source_mask\": source_mask, \"encoder_outputs\": encoder_outputs}\n\n def _decoder_step(self,\n last_predictions: torch.Tensor,\n selective_weights: torch.Tensor,\n state: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:\n # shape: (group_size, max_input_sequence_length, encoder_output_dim)\n encoder_outputs_mask = state[\"source_mask\"].float()\n # shape: (group_size, target_embedding_dim)\n embedded_input = self._target_embedder(last_predictions)\n # shape: (group_size, max_input_sequence_length)\n attentive_weights = self._attention(\n state[\"decoder_hidden\"], state[\"encoder_outputs\"], encoder_outputs_mask)\n # shape: (group_size, encoder_output_dim)\n attentive_read = util.weighted_sum(state[\"encoder_outputs\"], attentive_weights)\n # shape: (group_size, encoder_output_dim)\n selective_read = util.weighted_sum(state[\"encoder_outputs\"][:, 1:-1], selective_weights)\n # shape: (group_size, target_embedding_dim + encoder_output_dim * 2)\n decoder_input = torch.cat((embedded_input, attentive_read, selective_read), -1)\n # shape: (group_size, decoder_input_dim)\n projected_decoder_input = self._input_projection_layer(decoder_input)\n\n state[\"decoder_hidden\"], state[\"decoder_context\"] = self._decoder_cell(\n projected_decoder_input,\n (state[\"decoder_hidden\"], state[\"decoder_context\"]))\n return state\n\n def _get_generation_scores(self, state: Dict[str, torch.Tensor]) -> torch.Tensor:\n return self._output_generation_layer(state[\"decoder_hidden\"])\n\n def _get_copy_scores(self, state: Dict[str, torch.Tensor]) -> torch.Tensor:\n # shape: (batch_size, max_input_sequence_length - 2, encoder_output_dim)\n trimmed_encoder_outputs = state[\"encoder_outputs\"][:, 1:-1]\n # shape: (batch_size, max_input_sequence_length - 2, decoder_output_dim)\n copy_projection = self._output_copying_layer(trimmed_encoder_outputs)\n # shape: (batch_size, max_input_sequence_length - 2, decoder_output_dim)\n copy_projection = torch.tanh(copy_projection)\n # shape: (batch_size, max_input_sequence_length - 2)\n copy_scores = copy_projection.bmm(state[\"decoder_hidden\"].unsqueeze(-1)).squeeze(-1)\n return copy_scores\n\n def _get_ll_contrib(self,\n generation_scores: torch.Tensor,\n generation_scores_mask: torch.Tensor,\n copy_scores: torch.Tensor,\n target_tokens: torch.Tensor,\n target_to_source: torch.Tensor,\n copy_mask: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:\n \"\"\"\n Get the log-likelihood contribution from a single timestep.\n\n Parameters\n ----------\n generation_scores : ``torch.Tensor``\n Shape: `(batch_size, target_vocab_size)`\n generation_scores_mask : ``torch.Tensor``\n Shape: `(batch_size, target_vocab_size)`. This is just a tensor of 1's.\n copy_scores : ``torch.Tensor``\n Shape: `(batch_size, trimmed_source_length)`\n target_tokens : ``torch.Tensor``\n Shape: `(batch_size,)`\n target_to_source : ``torch.Tensor``\n Shape: `(batch_size, trimmed_source_length)`\n copy_mask : ``torch.Tensor``\n Shape: `(batch_size, trimmed_source_length)`\n\n Returns\n -------\n Tuple[torch.Tensor, torch.Tensor]\n Shape: `(batch_size,), (batch_size, max_input_sequence_length)`\n \"\"\"\n _, target_size = generation_scores.size()\n\n # The point of this mask is to just mask out all source token scores\n # that just represent padding. We apply the mask to the concatenation\n # of the generation scores and the copy scores to normalize the scores\n # correctly during the softmax.\n # shape: (batch_size, target_vocab_size + trimmed_source_length)\n mask = torch.cat((generation_scores_mask, copy_mask), dim=-1)\n # shape: (batch_size, target_vocab_size + trimmed_source_length)\n all_scores = torch.cat((generation_scores, copy_scores), dim=-1)\n # Normalize generation and copy scores.\n # shape: (batch_size, target_vocab_size + trimmed_source_length)\n log_probs = util.masked_log_softmax(all_scores, mask)\n # Calculate the log probability (`copy_log_probs`) for each token in the source sentence\n # that matches the current target token. We use the sum of these copy probabilities\n # for matching tokens in the source sentence to get the total probability\n # for the target token. We also need to normalize the individual copy probabilities\n # to create `selective_weights`, which are used in the next timestep to create\n # a selective read state.\n # shape: (batch_size, trimmed_source_length)\n copy_log_probs = log_probs[:, target_size:] + (target_to_source.float() + 1e-45).log()\n # Since `log_probs[:, target_size]` gives us the raw copy log probabilities,\n # we use a non-log softmax to get the normalized non-log copy probabilities.\n selective_weights = util.masked_softmax(log_probs[:, target_size:], target_to_source)\n # This mask ensures that item in the batch has a non-zero generation probabilities\n # for this timestep only when the gold target token is not OOV or there are no\n # matching tokens in the source sentence.\n # shape: (batch_size, 1)\n gen_mask = ((target_tokens != self._oov_index) | (target_to_source.sum(-1) == 0)).float()\n log_gen_mask = (gen_mask + 1e-45).log().unsqueeze(-1)\n # Now we get the generation score for the gold target token.\n # shape: (batch_size, 1)\n generation_log_probs = log_probs.gather(1, target_tokens.unsqueeze(1)) + log_gen_mask\n # ... and add the copy score to get the step log likelihood.\n # shape: (batch_size, 1 + trimmed_source_length)\n combined_gen_and_copy = torch.cat((generation_log_probs, copy_log_probs), dim=-1)\n # shape: (batch_size,)\n step_log_likelihood = util.logsumexp(combined_gen_and_copy)\n\n return step_log_likelihood, selective_weights\n\n def _forward_loss(self,\n target_tokens: Dict[str, torch.LongTensor],\n target_token_ids: torch.Tensor,\n state: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:\n \"\"\"\n Calculate the loss against gold targets.\n \"\"\"\n batch_size, target_sequence_length = target_tokens[\"tokens\"].size()\n\n # shape: (batch_size, max_input_sequence_length)\n source_mask = state[\"source_mask\"]\n\n # The last input from the target is either padding or the end symbol.\n # Either way, we don't have to process it.\n num_decoding_steps = target_sequence_length - 1\n # We use this to fill in the copy index when the previous input was copied.\n # shape: (batch_size,)\n copy_input_choices = source_mask.new_full((batch_size,), fill_value=self._copy_index)\n # shape: (batch_size, trimmed_source_length)\n copy_mask = source_mask[:, 1:-1].float()\n # We need to keep track of the probabilities assigned to tokens in the source\n # sentence that were copied during the previous timestep, since we use\n # those probabilities as weights when calculating the \"selective read\".\n # shape: (batch_size, trimmed_source_length)\n selective_weights = state[\"decoder_hidden\"].new_zeros(copy_mask.size())\n\n # Indicates which tokens in the source sentence match the current target token.\n # shape: (batch_size, trimmed_source_length)\n target_to_source = state[\"source_token_ids\"].new_zeros(copy_mask.size())\n\n # This is just a tensor of ones which we use repeatedly in `self._get_ll_contrib`,\n # so we create it once here to avoid doing it over-and-over.\n generation_scores_mask = state[\"decoder_hidden\"].new_full((batch_size, self._target_vocab_size),\n fill_value=1.0)\n\n step_log_likelihoods = []\n for timestep in range(num_decoding_steps):\n # shape: (batch_size,)\n input_choices = target_tokens[\"tokens\"][:, timestep]\n # If the previous target token was copied, we use the special copy token.\n # But the end target token will always be THE end token, so we know\n # it was not copied.\n if timestep < num_decoding_steps - 1:\n # Get mask tensor indicating which instances were copied.\n # shape: (batch_size,)\n copied = ((input_choices == self._oov_index) &\n (target_to_source.sum(-1) > 0)).long()\n # shape: (batch_size,)\n input_choices = input_choices * (1 - copied) + copy_input_choices * copied\n # shape: (batch_size, trimmed_source_length)\n target_to_source = state[\"source_token_ids\"] == target_token_ids[:, timestep+1].unsqueeze(-1)\n # Update the decoder state by taking a step through the RNN.\n state = self._decoder_step(input_choices, selective_weights, state)\n # Get generation scores for each token in the target vocab.\n # shape: (batch_size, target_vocab_size)\n generation_scores = self._get_generation_scores(state)\n # Get copy scores for each token in the source sentence, excluding the start\n # and end tokens.\n # shape: (batch_size, trimmed_source_length)\n copy_scores = self._get_copy_scores(state)\n # shape: (batch_size,)\n step_target_tokens = target_tokens[\"tokens\"][:, timestep + 1]\n step_log_likelihood, selective_weights = self._get_ll_contrib(\n generation_scores,\n generation_scores_mask,\n copy_scores,\n step_target_tokens,\n target_to_source,\n copy_mask)\n step_log_likelihoods.append(step_log_likelihood.unsqueeze(1))\n\n # Gather step log-likelihoods.\n # shape: (batch_size, num_decoding_steps = target_sequence_length - 1)\n log_likelihoods = torch.cat(step_log_likelihoods, 1)\n # Get target mask to exclude likelihood contributions from timesteps after\n # the END token.\n # shape: (batch_size, target_sequence_length)\n target_mask = util.get_text_field_mask(target_tokens)\n # The first timestep is just the START token, which is not included in the likelihoods.\n # shape: (batch_size, num_decoding_steps)\n target_mask = target_mask[:, 1:].float()\n # Sum of step log-likelihoods.\n # shape: (batch_size,)\n log_likelihood = (log_likelihoods * target_mask).sum(dim=-1)\n # The loss is the negative log-likelihood, averaged over the batch.\n loss = - log_likelihood.sum() / batch_size\n\n return {\"loss\": loss}\n\n def _forward_beam_search(self, state: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:\n batch_size, source_length = state[\"source_mask\"].size()\n trimmed_source_length = source_length - 2\n # Initialize the copy scores to zero.\n state[\"copy_log_probs\"] = \\\n (state[\"decoder_hidden\"].new_zeros((batch_size, trimmed_source_length)) + 1e-45).log()\n # shape: (batch_size,)\n start_predictions = state[\"source_mask\"].new_full((batch_size,), fill_value=self._start_index)\n # shape (all_top_k_predictions): (batch_size, beam_size, num_decoding_steps)\n # shape (log_probabilities): (batch_size, beam_size)\n all_top_k_predictions, log_probabilities = self._beam_search.search(\n start_predictions, state, self.take_search_step)\n return {\n \"predicted_log_probs\": log_probabilities,\n \"predictions\": all_top_k_predictions,\n }\n\n def _get_input_and_selective_weights(self,\n last_predictions: torch.LongTensor,\n state: Dict[str, torch.Tensor]) -> Tuple[torch.LongTensor, torch.Tensor]:\n \"\"\"\n Get input choices for the decoder and the selective copy weights.\n\n The decoder input choices are simply the `last_predictions`, except for\n target OOV predictions that were copied from source tokens, in which case\n the prediction will be changed to the COPY symbol in the target namespace.\n\n The selective weights are just the probabilities assigned to source\n tokens that were copied, normalized to sum to 1. If no source tokens were copied,\n there will be all zeros.\n\n Parameters\n ----------\n last_predictions : ``torch.LongTensor``\n Shape: `(group_size,)`\n state : ``Dict[str, torch.Tensor]``\n\n Returns\n -------\n Tuple[torch.LongTensor, torch.Tensor]\n `input_choices` (shape `(group_size,)`) and `selective_weights`\n (shape `(group_size, trimmed_source_length)`).\n \"\"\"\n group_size, trimmed_source_length = state[\"source_to_target\"].size()\n\n # This is a mask indicating which last predictions were copied from the\n # the source AND not in the target vocabulary (OOV).\n # (group_size,)\n only_copied_mask = (last_predictions >= self._target_vocab_size).long()\n\n # If the last prediction was in the target vocab or OOV but not copied,\n # we use that as input, otherwise we use the COPY token.\n # shape: (group_size,)\n copy_input_choices = only_copied_mask.new_full((group_size,), fill_value=self._copy_index)\n input_choices = last_predictions * (1 - only_copied_mask) + copy_input_choices * only_copied_mask\n\n # In order to get the `selective_weights`, we need to find out which predictions\n # were copied or copied AND generated, which is the case when a prediction appears\n # in both the source sentence and the target vocab. But whenever a prediction\n # is in the target vocab (even if it also appeared in the source sentence),\n # its index will be the corresponding target vocab index, not its index in\n # the source sentence offset by the target vocab size. So we first\n # use `state[\"source_to_target\"]` to get an indicator of every source token\n # that matches the predicted target token.\n # shape: (group_size, trimmed_source_length)\n expanded_last_predictions = last_predictions.unsqueeze(-1).expand(group_size, trimmed_source_length)\n # shape: (group_size, trimmed_source_length)\n source_copied_and_generated = (state[\"source_to_target\"] == expanded_last_predictions).long()\n\n # In order to get indicators for copied source tokens that are OOV with respect\n # to the target vocab, we'll make use of `state[\"source_token_ids\"]`.\n # First we adjust predictions relative to the start of the source tokens.\n # This makes sense because predictions for copied tokens are given by the index of the copied\n # token in the source sentence, offset by the size of the target vocabulary.\n # shape: (group_size,)\n adjusted_predictions = last_predictions - self._target_vocab_size\n # The adjusted indices for items that were not copied will be negative numbers,\n # and therefore invalid. So we zero them out.\n adjusted_predictions = adjusted_predictions * only_copied_mask\n # shape: (group_size, trimmed_source_length)\n source_token_ids = state[\"source_token_ids\"]\n # shape: (group_size, trimmed_source_length)\n adjusted_prediction_ids = source_token_ids.gather(-1, adjusted_predictions.unsqueeze(-1))\n # This mask will contain indicators for source tokens that were copied\n # during the last timestep.\n # shape: (group_size, trimmed_source_length)\n source_only_copied = (source_token_ids == adjusted_prediction_ids).long()\n # Since we zero'd-out indices for predictions that were not copied,\n # we need to zero out all entries of this mask corresponding to those predictions.\n source_only_copied = source_only_copied * only_copied_mask.unsqueeze(-1)\n\n # shape: (group_size, trimmed_source_length)\n mask = source_only_copied | source_copied_and_generated\n # shape: (group_size, trimmed_source_length)\n selective_weights = util.masked_softmax(state[\"copy_log_probs\"], mask)\n\n return input_choices, selective_weights\n\n def _gather_final_log_probs(self,\n generation_log_probs: torch.Tensor,\n copy_log_probs: torch.Tensor,\n state: Dict[str, torch.Tensor]) -> torch.Tensor:\n \"\"\"\n Combine copy probabilities with generation probabilities for matching tokens.\n\n Parameters\n ----------\n generation_log_probs : ``torch.Tensor``\n Shape: `(group_size, target_vocab_size)`\n copy_log_probs : ``torch.Tensor``\n Shape: `(group_size, trimmed_source_length)`\n state : ``Dict[str, torch.Tensor]``\n\n Returns\n -------\n torch.Tensor\n Shape: `(group_size, target_vocab_size + trimmed_source_length)`.\n \"\"\"\n _, trimmed_source_length = state[\"source_to_target\"].size()\n source_token_ids = state[\"source_token_ids\"]\n\n # shape: [(batch_size, *)]\n modified_log_probs_list: List[torch.Tensor] = [generation_log_probs]\n for i in range(trimmed_source_length):\n # shape: (group_size,)\n copy_log_probs_slice = copy_log_probs[:, i]\n # `source_to_target` is a matrix of shape (group_size, trimmed_source_length)\n # where element (i, j) is the vocab index of the target token that matches the jth\n # source token in the ith group, if there is one, or the index of the OOV symbol otherwise.\n # We'll use this to add copy scores to corresponding generation scores.\n # shape: (group_size,)\n source_to_target_slice = state[\"source_to_target\"][:, i]\n # The OOV index in the source_to_target_slice indicates that the source\n # token is not in the target vocab, so we don't want to add that copy score\n # to the OOV token.\n copy_log_probs_to_add_mask = (source_to_target_slice != self._oov_index).float()\n copy_log_probs_to_add = copy_log_probs_slice + (copy_log_probs_to_add_mask + 1e-45).log()\n # shape: (batch_size, 1)\n copy_log_probs_to_add = copy_log_probs_to_add.unsqueeze(-1)\n # shape: (batch_size, 1)\n selected_generation_log_probs = generation_log_probs.gather(1, source_to_target_slice.unsqueeze(-1))\n combined_scores = util.logsumexp(\n torch.cat((selected_generation_log_probs, copy_log_probs_to_add), dim=1))\n generation_log_probs.scatter_(-1, source_to_target_slice.unsqueeze(-1), combined_scores.unsqueeze(-1))\n # We have to combine copy scores for duplicate source tokens so that\n # we can find the overall most likely source token. So, if this is the first\n # occurence of this particular source token, we add the log_probs from all other\n # occurences, otherwise we zero it out since it was already accounted for.\n if i < (trimmed_source_length - 1):\n # Sum copy scores from future occurences of source token.\n # shape: (group_size, trimmed_source_length - i)\n source_future_occurences = (source_token_ids[:, (i+1):] == source_token_ids[:, i].unsqueeze(-1)).float() # pylint: disable=line-too-long\n # shape: (group_size, trimmed_source_length - i)\n future_copy_log_probs = copy_log_probs[:, (i+1):] + (source_future_occurences + 1e-45).log()\n # shape: (group_size, 1 + trimmed_source_length - i)\n combined = torch.cat((copy_log_probs_slice.unsqueeze(-1), future_copy_log_probs), dim=-1)\n # shape: (group_size,)\n copy_log_probs_slice = util.logsumexp(combined)\n if i > 0:\n # Remove copy log_probs that we have already accounted for.\n # shape: (group_size, i)\n source_previous_occurences = source_token_ids[:, 0:i] == source_token_ids[:, i].unsqueeze(-1)\n # shape: (group_size,)\n duplicate_mask = (source_previous_occurences.sum(dim=-1) == 0).float()\n copy_log_probs_slice = copy_log_probs_slice + (duplicate_mask + 1e-45).log()\n\n # Finally, we zero-out copy scores that we added to the generation scores\n # above so that we don't double-count them.\n # shape: (group_size,)\n left_over_copy_log_probs = copy_log_probs_slice + (1.0 - copy_log_probs_to_add_mask + 1e-45).log()\n modified_log_probs_list.append(left_over_copy_log_probs.unsqueeze(-1))\n\n # shape: (group_size, target_vocab_size + trimmed_source_length)\n modified_log_probs = torch.cat(modified_log_probs_list, dim=-1)\n\n return modified_log_probs\n\n def take_search_step(self,\n last_predictions: torch.Tensor,\n state: Dict[str, torch.Tensor]) -> Tuple[torch.Tensor, Dict[str, torch.Tensor]]:\n \"\"\"\n Take step during beam search.\n\n This function is what gets passed to the `BeamSearch.search` method. It takes\n predictions from the last timestep and the current state and outputs\n the log probabilities assigned to tokens for the next timestep, as well as the updated\n state.\n\n Since we are predicting tokens out of the extended vocab (target vocab + all unique\n tokens from the source sentence), this is a little more complicated that just\n making a forward pass through the model. The output log probs will have\n shape `(group_size, target_vocab_size + trimmed_source_length)` so that each\n token in the target vocab and source sentence are assigned a probability.\n\n Note that copy scores are assigned to each source token based on their position, not unique value.\n So if a token appears more than once in the source sentence, it will have more than one score.\n Further, if a source token is also part of the target vocab, its final score\n will be the sum of the generation and copy scores. Therefore, in order to\n get the score for all tokens in the extended vocab at this step,\n we have to combine copy scores for re-occuring source tokens and potentially\n add them to the generation scores for the matching token in the target vocab, if\n there is one.\n\n So we can break down the final log probs output as the concatenation of two\n matrices, A: `(group_size, target_vocab_size)`, and B: `(group_size, trimmed_source_length)`.\n Matrix A contains the sum of the generation score and copy scores (possibly 0)\n for each target token. Matrix B contains left-over copy scores for source tokens\n that do NOT appear in the target vocab, with zeros everywhere else. But since\n a source token may appear more than once in the source sentence, we also have to\n sum the scores for each appearance of each unique source token. So matrix B\n actually only has non-zero values at the first occurence of each source token\n that is not in the target vocab.\n\n Parameters\n ----------\n last_predictions : ``torch.Tensor``\n Shape: `(group_size,)`\n\n state : ``Dict[str, torch.Tensor]``\n Contains all state tensors necessary to produce generation and copy scores\n for next step.\n\n Notes\n -----\n `group_size` != `batch_size`. In fact, `group_size` = `batch_size * beam_size`.\n \"\"\"\n _, trimmed_source_length = state[\"source_to_target\"].size()\n\n # Get input to the decoder RNN and the selective weights. `input_choices`\n # is the result of replacing target OOV tokens in `last_predictions` with the\n # copy symbol. `selective_weights` consist of the normalized copy probabilities\n # assigned to the source tokens that were copied. If no tokens were copied,\n # there will be all zeros.\n # shape: (group_size,), (group_size, trimmed_source_length)\n input_choices, selective_weights = self._get_input_and_selective_weights(last_predictions, state)\n # Update the decoder state by taking a step through the RNN.\n state = self._decoder_step(input_choices, selective_weights, state)\n # Get the un-normalized generation scores for each token in the target vocab.\n # shape: (group_size, target_vocab_size)\n generation_scores = self._get_generation_scores(state)\n # Get the un-normalized copy scores for each token in the source sentence,\n # excluding the start and end tokens.\n # shape: (group_size, trimmed_source_length)\n copy_scores = self._get_copy_scores(state)\n # Concat un-normalized generation and copy scores.\n # shape: (batch_size, target_vocab_size + trimmed_source_length)\n all_scores = torch.cat((generation_scores, copy_scores), dim=-1)\n # shape: (group_size, trimmed_source_length)\n copy_mask = state[\"source_mask\"][:, 1:-1].float()\n # shape: (batch_size, target_vocab_size + trimmed_source_length)\n mask = torch.cat((generation_scores.new_full(generation_scores.size(), 1.0), copy_mask), dim=-1)\n # Normalize generation and copy scores.\n # shape: (batch_size, target_vocab_size + trimmed_source_length)\n log_probs = util.masked_log_softmax(all_scores, mask)\n # shape: (group_size, target_vocab_size), (group_size, trimmed_source_length)\n generation_log_probs, copy_log_probs = log_probs.split(\n [self._target_vocab_size, trimmed_source_length], dim=-1)\n # Update copy_probs needed for getting the `selective_weights` at the next timestep.\n state[\"copy_log_probs\"] = copy_log_probs\n # We now have normalized generation and copy scores, but to produce the final\n # score for each token in the extended vocab, we have to go through and add\n # the copy scores to the generation scores of matching target tokens, and sum\n # the copy scores of duplicate source tokens.\n # shape: (group_size, target_vocab_size + trimmed_source_length)\n final_log_probs = self._gather_final_log_probs(generation_log_probs, copy_log_probs, state)\n\n return final_log_probs, state\n\n def _get_predicted_tokens(self,\n predicted_indices: Union[torch.Tensor, numpy.ndarray],\n batch_metadata: List[Any],\n n_best: int = None) -> List[Union[List[List[str]], List[str]]]:\n \"\"\"\n Convert predicted indices into tokens.\n\n If `n_best = 1`, the result type will be `List[List[str]]`. Otherwise the result\n type will be `List[List[List[str]]]`.\n \"\"\"\n if not isinstance(predicted_indices, numpy.ndarray):\n predicted_indices = predicted_indices.detach().cpu().numpy()\n predicted_tokens: List[Union[List[List[str]], List[str]]] = []\n for top_k_predictions, metadata in zip(predicted_indices, batch_metadata):\n batch_predicted_tokens: List[List[str]] = []\n for indices in top_k_predictions[:n_best]:\n tokens: List[str] = []\n indices = list(indices)\n if self._end_index in indices:\n indices = indices[:indices.index(self._end_index)]\n for index in indices:\n if index >= self._target_vocab_size:\n adjusted_index = index - self._target_vocab_size\n token = metadata[\"source_tokens\"][adjusted_index]\n else:\n token = self.vocab.get_token_from_index(index, self._target_namespace)\n tokens.append(token)\n batch_predicted_tokens.append(tokens)\n if n_best == 1:\n predicted_tokens.append(batch_predicted_tokens[0])\n else:\n predicted_tokens.append(batch_predicted_tokens)\n return predicted_tokens\n\n @overrides\n def decode(self, output_dict: Dict[str, torch.Tensor]) -> Dict[str, Any]:\n \"\"\"\n Finalize predictions.\n\n After a beam search, the predicted indices correspond to tokens in the target vocabulary\n OR tokens in source sentence. Here we gather the actual tokens corresponding to\n the indices.\n \"\"\"\n predicted_tokens = self._get_predicted_tokens(output_dict[\"predictions\"],\n output_dict[\"metadata\"])\n output_dict[\"predicted_tokens\"] = predicted_tokens\n return output_dict\n\n @overrides\n def get_metrics(self, reset: bool = False) -> Dict[str, float]:\n all_metrics: Dict[str, float] = {}\n if not self.training:\n if self._tensor_based_metric is not None:\n all_metrics.update(self._tensor_based_metric.get_metric(reset=reset)) # type: ignore\n if self._token_based_metric is not None:\n all_metrics.update(self._token_based_metric.get_metric(reset=reset)) # type: ignore\n return all_metrics\n"
]
| [
[
"torch.load",
"torch.save"
],
[
"torch.tanh",
"torch.nn.modules.linear.Linear",
"torch.cat",
"torch.nn.modules.rnn.LSTMCell"
]
]
|
IgorDavidyuk/conflicting_tasks_learning | [
"ecaed415d710723e5fe9880984cae3f163735860"
]
| [
"dataset/classification_dataset.py"
]
| [
"import os\n# import cv2\nfrom PIL import Image\nimport numpy as np\nimport torch\nfrom torch.utils.data import Dataset\nfrom torchvision import transforms\nfrom create_google_fonts_dataset import parse_gf_metadata, save_rendered_glyphs\n\n\nclass CharClassificationDataset(Dataset):\n\n def __init__(self, gf_dataframe, root_dir, charset=None, img_size=64, transform=None):\n '''\n Args:\n gf_dataframe (pd.DataFrame): Info from parsed google fonts metadata files.\n root_dir (string): Directory with all the images grooped in folders by font name.\n charset (string): A string contains all the unique chars used for each typeface\n transform (callable, optional): Optional transform to be applied\n on a sample.\n '''\n self.gf_dataframe = gf_dataframe\n self.root_dir = root_dir\n self.img_size = img_size\n\n if charset is not None:\n self.charset = str(charset)\n else:\n # construct letter set\n capital_alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n char_set = capital_alphabet\n for char in 'OQMWIN': # removing problematic symbols\n char_set = char_set.replace(char, '')\n self.charset = char_set\n \n # render dataset if it is absent and check validity if it was rendered before\n self.render_fonts()\n self.font_names = list(map(self.split_path, self.gf_dataframe.path.values))\n\n if transform is not None:\n self.transform = transform\n else:\n self.transform = transforms.Compose([\n transforms.Resize((img_size, img_size)),\n transforms.ToTensor(),\n # we use 1 channel images\n transforms.Normalize(mean=[np.mean([0.485, 0.456, 0.406])],\n std=[np.mean([0.229, 0.224, 0.225])]) \n ]) \n\n @staticmethod\n def split_path(path):\n return path.split('/')[-1].split('.')[0]\n \n \n def render_fonts(self):\n '''\n Check existans of pre-rendered dataset in root_dir\n '''\n for i, row in self.gf_dataframe.iterrows():\n font_name = row.path.split('/')[-1].split('.')[0]\n for char in self.charset:\n pic_address = os.path.join(self.root_dir, font_name, f'{char}.jpg')\n try:\n size_b = os.path.getsize(pic_address)\n if size_b > 100:\n continue\n else: raise Exception()\n except:\n print(f'valid image {pic_address} is absent')\n print(f'\\ncreating dataset in {self.root_dir} directory\\n')\n save_rendered_glyphs(self.gf_dataframe, self.charset, self.root_dir, \\\n pic_size=self.img_size )\n return\n \n\n def __len__(self):\n return len(self.gf_dataframe) * len(self.charset)\n\n def __getitem__(self, idx):\n if torch.is_tensor(idx):\n idx = idx.tolist()\n # font_name = self.gf_dataframe.path[idx//len(self.charset)].split('/')[-1].split('.')[0]\n font_name = self.font_names[idx//len(self.charset)]\n letter_id = idx%len(self.charset)\n letter = self.charset[letter_id]\n img_name = os.path.join(self.root_dir, font_name, f'{letter}.jpg')\n image = Image.open(img_name)\n\n if self.transform is not None:\n image = self.transform(image)\n\n return image, letter_id"
]
| [
[
"numpy.mean",
"torch.is_tensor"
]
]
|
healenrens/A-fast-demo-to-help-you-build-and-training-your-network | [
"62494656d3555ecb0c424d539630c74ef4db791f"
]
| [
"test.py"
]
| [
"import torch\r\nimport torch.nn as nn\r\nclass tester():\r\n def __init__(self,model,testdata,criterion,batchsize):\r\n self.modle=model\r\n self.set=testdata\r\n self.device=torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\r\n self.cri=criterion\r\n self.batchsize=batchsize\r\n self.avetestloss=0\r\n self.avetestacc=0\r\n def test(self):\r\n testlosss=0\r\n correct=0\r\n total=0\r\n for j, dataa in enumerate(self.set):\r\n self.modle.eval()#将模型设置为测试,在含有dropout层等可变层时应该添加\r\n inputst, labelst = dataa\r\n inputst, labelst = inputst.to(self.device), labelst.to(self.device)\r\n outputst = self.modle(inputst)\r\n testlosss = testlosss + self.cri(outputst, labelst).item()\r\n _, predictedd = torch.max(outputst.data, 1)\r\n outlistt = predictedd.tolist()\r\n labelslistt = labelst.tolist()\r\n for q in range(0, self.batchsize):\r\n aq = outlistt[q]\r\n bq = labelslistt[q]\r\n if aq == bq:\r\n correct = correct + 1\r\n total = total + 1\r\n #if total==2:\r\n # break\r\n self.avetestloss=testlosss/total\r\n self.avetestacc = correct / (total * self.batchsize)\r\n return self.avetestloss,self.avetestacc"
]
| [
[
"torch.max",
"torch.cuda.is_available"
]
]
|
marcelsan/Deep-HdrReconstruction | [
"7cb0d93938baa6fbe029116451a661c18dfba49e"
]
| [
"loss.py"
]
| [
"import sys\nsys.path.append(\"..\")\n\nimport torch\nimport torch.nn as nn\n\nfrom lib.io import print_\nfrom network.vgg import VGG16FeatureExtractor\n\ndef gram_matrix(feat):\n \"\"\"\n Calculate gram matrix used in style loss\n https://github.com/pytorch/examples/blob/master/fast_neural_style/neural_style/utils.py\n \"\"\"\n (b, ch, h, w) = feat.size()\n feat = feat.view(b, ch, h * w)\n feat_t = feat.transpose(1, 2)\n gram = torch.bmm(feat, feat_t) / (ch * h * w)\n\n return gram\n\ndef normalize_batch(batch):\n \"\"\" Normalize batch using imagenet mean and std \"\"\"\n mean = batch.new_tensor([0.485, 0.456, 0.406]).view(-1, 1, 1)\n std = batch.new_tensor([0.229, 0.224, 0.225]).view(-1, 1, 1)\n return (batch - mean) / std\n\nclass PerceptualLossBase(nn.Module):\n def __init__(self, extractor, device):\n super().__init__()\n self.l1 = nn.L1Loss()\n self.extractor = extractor\n self.device = device\n\n def _total_variation_loss(self, image, mask):\n \"\"\"Total variation loss, used for smoothing the hole region\"\"\"\n\n # Create dilated hole region using a 3x3 kernel of all 1s.\n _, ch, _, _ = mask.shape\n dilation_conv = nn.Conv2d(ch, ch, 3, padding=1, bias=False).to(self.device)\n torch.nn.init.constant_(dilation_conv.weight, 1.0)\n with torch.no_grad():\n output_mask = dilation_conv(1-mask)\n\n # Cast values to be [0., 1.], and compute dilated hole region of y_comp.\n dilated_holes = (output_mask != 0).float()\n P = dilated_holes*image\n\n # Calculate total variation loss.\n a = torch.mean(torch.abs(P[:, :, :, 1:]-P[:, :, :, :-1]))\n b = torch.mean(torch.abs(P[:, :, 1:, :]-P[:, :, :-1, :]))\n\n return a+b\n\n def forward(self, input, mask, output, gt):\n raise NotImplementedError()\n\nclass HDRLoss(PerceptualLossBase):\n def __init__(self, extractor, device):\n PerceptualLossBase.__init__(self, extractor, device)\n self.LAMBDA_DICT = { 'hole': 6.0, 'prc': 1.0, 'style' : 120 }\n\n def forward(self, input, mask, output, gt):\n loss_dict = {}\n mask_hole = 1-mask\n output = torch.clamp(output, min=0, max=10)\n\n # Compute predicted image with non-hole pixels set to ground truth.\n log_gt = torch.log(gt+1)\n loss_dict['hole'] = self.l1(mask_hole*output, mask_hole*log_gt)\n\n # Other loss terms.\n with torch.no_grad():\n y = torch.exp(output)-1\n \n # Range compress images.\n y_clamp = torch.clamp(y, min=0, max=50)\n gt_clamp = torch.clamp(gt, min=0, max=50)\n \n k = gt_clamp.view(gt_clamp.shape[0],-1).max(1)[0].view((gt_clamp.shape[0],1,1,1))\n y_ = y_clamp / k\n gt_ = gt_clamp / k\n\n out_mu = self._mu_law(y_, 500)\n gt_mu = self._mu_law(gt_, 500)\n\n # Compose images.\n out_comp = mask*gt_mu + mask_hole*out_mu\n\n # Extract features maps.\n if output.shape[1] == 3:\n feat_output = self.extractor(normalize_batch(out_comp))\n feat_gt = self.extractor(normalize_batch(gt_mu))\n elif output.shape[1] == 1:\n feat_output = self.extractor(torch.cat([normalize_batch(out_comp)]*3, 1))\n feat_gt = self.extractor(torch.cat([normalize_batch(gt_mu)]*3, 1))\n else:\n raise ValueError('Data format error.')\n\n # Calculate VGG loss.\n loss_dict['prc'] = 0.0\n for i in range(3):\n loss_dict['prc'] += self.l1(feat_output[i], feat_gt[i])\n\n # Calculate style loss.\n loss_dict['style'] = 0.0\n for i in range(3):\n loss_dict['style'] += self.l1(gram_matrix(feat_output[i]),\n gram_matrix(feat_gt[i]))\n\n # Calculate total variation loss.\n if 'tv' in self.LAMBDA_DICT:\n loss_dict['tv'] = self._total_variation_loss(out_comp, mask)\n\n return loss_dict\n\n def _mu_law(self, H, mu=5000):\n x = torch.max(H, torch.tensor(0.0).to(self.device)).to(self.device)\n res = torch.log(1. + mu*x)/torch.log(torch.tensor(1.+mu))\n return res\n\nclass InpaintingLoss(PerceptualLossBase):\n def __init__(self, extractor, device):\n PerceptualLossBase.__init__(self, extractor, device)\n self.LAMBDA_DICT = {'valid': 1.0, 'hole': 6.0, 'tv': 0.1, 'prc': 0.05, 'style': 120.0}\n\n def forward(self, input, mask, output, gt):\n loss_dict = {}\n output_comp = mask * input + (1 - mask) * output\n\n loss_dict['hole'] = self.l1((1 - mask) * output, (1 - mask) * gt)\n loss_dict['valid'] = self.l1(mask*output, mask*gt)\n\n if output.shape[1] == 3:\n feat_output_comp = self.extractor(output_comp)\n feat_output = self.extractor(output)\n feat_gt = self.extractor(gt)\n elif output.shape[1] == 1:\n feat_output_comp = self.extractor(torch.cat([output_comp]*3, 1))\n feat_output = self.extractor(torch.cat([output]*3, 1))\n feat_gt = self.extractor(torch.cat([gt]*3, 1))\n else:\n raise ValueError('Data format error.')\n\n loss_dict['prc'] = 0.0\n for i in range(3):\n loss_dict['prc'] += self.l1(feat_output[i], feat_gt[i])\n loss_dict['prc'] += self.l1(feat_output_comp[i], feat_gt[i])\n\n loss_dict['style'] = 0.0\n for i in range(3):\n loss_dict['style'] += self.l1(gram_matrix(feat_output[i]),\n gram_matrix(feat_gt[i]))\n loss_dict['style'] += self.l1(gram_matrix(feat_output_comp[i]),\n gram_matrix(feat_gt[i]))\n\n if 'tv' in self.LAMBDA_DICT:\n loss_dict['tv'] = self._total_variation_loss(output_comp, mask)\n\n return loss_dict\n\ndef load(mode, device = torch.device(\"cuda\")):\n criterion = None\n if mode == \"hdr\":\n print_('\\tExperiment running HDR loss.\\n', bold=True)\n return HDRLoss(VGG16FeatureExtractor(), device).to(device)\n elif mode == \"inpainting\":\n print_('\\tExperiment running inpainting loss.\\n', bold=True)\n return InpaintingLoss(VGG16FeatureExtractor(), device).to(device)\n else:\n raise ValueError('unknown mode {}'.format(mode))"
]
| [
[
"torch.abs",
"torch.cat",
"torch.nn.init.constant_",
"torch.nn.Conv2d",
"torch.tensor",
"torch.exp",
"torch.log",
"torch.bmm",
"torch.no_grad",
"torch.device",
"torch.clamp",
"torch.nn.L1Loss"
]
]
|
shumwaymark/sentinelcam | [
"a6381915b6b315b354856e6895a1ceacb798d755"
]
| [
"camwatcher/camdata.py"
]
| [
"\"\"\"camdata: access to camera event data from sentinelcam outpost nodes\n\nCopyright (c) 2021 by Mark K Shumway, [email protected]\nLicense: MIT, see the sentinelcam LICENSE for more details.\n\"\"\"\n\nimport os\nimport pandas as pd\nfrom datetime import datetime\n\nclass CamData:\n \"\"\" Data and access methods to camwatcher CSV data.\n\n Always operates within the context of a specific date. Any\n call to `set_event()` should refernce an event within the \n current date index. Use `set_date()` as necessary to change\n context to another date. \n\n Parameters\n ----------\n dir : str \n High-level folder name for camwatcher CSV date folders\n date : str, optional\n Target date in \"YYYY-MM-DD\" format. This defaults to \n current date if not specified.\n \n Methods\n -------\n set_date(date)\n Set index to specified (YYYY-MM-DD) date\n get_date() -> str\n Return current index date as YYYY-MM-DD\n get_index_name(date) -> str\n For given date, returns filesystem pathname to camwatcher index\n get_index() -> pandas.DataFrame\n Returns reference to the current camwatacher index data\n get_last_event() -> str\n Returns most recent event id \n set_event(event)\n Set index to specifed event id\n get_event_node() -> str\n Returns node name associated with current event\n get_event_view() -> str\n Returns view name associated with current event\n get_event_types() -> pandas.DataFrame\n Returns the event types available for this event\n get_event_pathname(event, type) -> str\n Retruns filesystem pathname to event detail file\n get_event_data(type) -> pandas.DataFrame\n Returns reference to tracking detail for current event and type\n \"\"\"\n\n IDXFILE = \"camwatcher.csv\"\n IDXCOLS = [\"node\",\"viewname\",\"timestamp\",\"event\",\"fps\",\"type\"]\n IDXTYPES = [\"trk\"]\n\n def set_date(self, date):\n \"\"\" Initialize CamData objet to the given date \n\n Loads the camwatcher index data for the given date. Clears any existing\n references to event and camera data. This is a clean reset to an entirely\n new date. \n\n Parameter\n ---------\n date : str\n Target date in \"YYYY-MM-DD\" format\n \"\"\"\n\n self._ymd = date\n self._indexfile = self.get_index_name(date)\n self._lastEvent = None\n self._event_id = None\n self._event_node = None\n self._event_view = None\n self._event_start = None\n self._event_subset = None\n self._event_types = None\n self._event_data = None\n if self._indexfile:\n # read camwatcher index into pandas DataFrame\n self._index = pd.read_csv(\n self._indexfile, \n names=CamData.IDXCOLS, \n parse_dates=[\"timestamp\"]\n ).sort_values(\n by=\"timestamp\", ascending=False)\n # retrive the event_id for the most recent event in the index\n self._lastEvent = self._index.iloc[0].event\n else:\n # if no index file, provide an empty DataFrame \n self._index = pd.DataFrame(columns=CamData.IDXCOLS)\n\n def get_date(self):\n \"\"\" Return current index date\n \n Returns\n -------\n str\n Currently selected index date in YYYY-MM-DD format.\n \"\"\"\n\n return self._ymd\n\n def get_index_name(self, date):\n \"\"\" Return filename reference to camwatcher index\n\n Based on the supplied date parameter, return the pathname to \n the camwatcher index if it exsits. Otherwise return None. This \n function can be used to quickly determine whether any data is \n available for the specified date. \n\n Parameters\n ----------\n date : str\n Target date in \"YYYY-MM-DD\" format\n \n Returns\n -------\n str\n Pathname to camwatcher index for supplied date, or None \n \"\"\"\n\n indexname = os.path.join(self._index_path, date, CamData.IDXFILE)\n if not os.path.exists(indexname):\n indexname = None\n return indexname\n\n def get_index(self):\n \"\"\" Return reference to the current camwatcher index as a pandas DataFrame \n \n Returns\n -------\n pandas.DataFrame\n Reference to camwatcher index as a pandas.DataFrame\n \"\"\"\n\n return self._index\n\n def get_last_event(self):\n \"\"\" Return most recent Event ID \n \n Returns\n -------\n str\n Most recent event id within the index\n \"\"\"\n\n return self._lastEvent\n\n def set_event(self, event):\n \"\"\" Set camwatcher index to the specified Event ID\n\n Sets index to the specified event. Establishes references to event detail \n files. Loads camera detail data for default event type. A prerequisite\n to establishing valid references to event and camera data. \n\n Parameters\n ----------\n event : str\n Event ID\n \"\"\"\n\n self._event_id = event\n self._event_subset = self._index[(self._index['event'] == event)]\n self._event_node = self._event_subset.iloc[0].node\n self._event_view = self._event_subset.iloc[0].viewname\n self._event_start = self._event_subset[\"timestamp\"].min()\n self._event_types = self._event_subset[\"type\"]\n\n def get_event_node(self):\n \"\"\" Return node name from event\n \n Must have first invoked `set_event()` to load camera detail for the event.\n \n Returns\n -------\n str\n Node name associated with the current event\n \"\"\"\n\n return self._event_node\n\n def get_event_view(self):\n \"\"\" Return view name from the event\n \n Must have first invoked `set_event()` to load camera detail for the event.\n \n Returns\n -------\n str\n View name associated with the current event\n \"\"\"\n\n return self._event_view\n\n def get_event_start(self):\n \"\"\" Return view name from the event\n \n Must have first invoked `set_event()` to load camera detail for the event.\n \n Returns\n -------\n datetime\n Starting timestamp for current event\n \"\"\"\n\n return self._event_start\n\n def get_event_types(self):\n \"\"\" Return the event types for the selected event. \n \n Must have first invoked `set_event()` to load camera detail for the event.\n \n Returns\n -------\n pandas.DataFrame\n The available event types for the current event.\n \"\"\"\n \n return self._event_types\n \n def get_event_pathname(self, event, type='trk'):\n \"\"\" Return pathname to the camera event detail file\n \n Parameters\n ----------\n event : str\n Event ID\n type : str, optional\n Event type\n \n Returns\n -------\n str\n Pathname to camwatcher detail for specified event and type\n \"\"\"\n\n return os.path.join(self._index_path, self._ymd, event + \"_\" + type + \".csv\")\n\n def get_event_data(self, type='trk'):\n \"\"\" Return reference to selected event tracking data as a pandas DataFrame \n \n Must have first invoked `set_event()` to load camera detail for the event.\n \n Parameters\n ----------\n type : str, optional\n Event type \n \n Returns\n -------\n pandas.DataFrame\n Reference to event detail data as a pandas.DataFrame\n \"\"\"\n\n self._event_data = pd.read_csv(\n self.get_event_pathname(self._event_id, type),\n parse_dates=['timestamp']\n )\n self._event_data[\"elapsed\"] = self._event_data[\"timestamp\"] - self._event_start\n return self._event_data\n\n def _list_date_folders(self):\n # returns a list of the available date folders\n return self._list_files(self._index_path, prefix=None)\n\n def _list_event_images(self, imagebase):\n # return the set of image files for the current event\n imagefolder = os.path.join(imagebase, self._ymd)\n return self._list_files(imagefolder, prefix=self._event_id)\n\n def _list_files(self, basePath, prefix):\n # loop over filenames in the directory\n for filename in os.listdir(basePath):\n # skip any files without a matching filename prefix\n if prefix is not None and not filename.startswith(prefix):\n continue\n # construct the path to the image and yield it\n imagePath = os.path.join(basePath, filename)\n yield imagePath\n\n def get_date_list(self):\n return sorted([d[-10:] for d in list(self._list_date_folders())], reverse=True)\n\n def get_event_images(self, imagebase):\n return sorted(list(self._list_event_images(imagebase)))\n\n def __init__(self, dir, date = datetime.utcnow().isoformat()[:10]):\n self._index_path = dir\n self.set_date(date)\n\n# ----------------------------------------------------------------------------------------\n# See below for usaage \n# ----------------------------------------------------------------------------------------\n\ncfg = {'csvdir': '/mnt/usb1/imagedata/camwatcher'} \n\nif __name__ == '__main__' :\n\n cdata = CamData(cfg[\"csvdir\"]) # allocate and initialize index for current date\n cindx = cdata.get_index() # get reference to index DataFrame\n \n # most recent 5 events\n for row in cindx[:5].itertuples():\n print(row.node + \" \" + row.viewname + \" \" + str(row.timestamp) + \" \" + row.event)\n\n event_id = cdata.get_last_event() # grab the most recent event id\n if event_id:\n cdata.set_event(event_id) # load event data \n evt_data = cdata.get_event_data() # cam tracking dataset from event \n \n print(f\"Event ID [{event_id}] started at {str(cdata.get_event_start())}\")\n for row in evt_data[:10].itertuples():\n print(str(row.timestamp) + \" \" + \n str(row.elapsed) + \" \" + \n str(row.objid) + \" \" + \n str(row.centroid_x) + \" \" + \n str(row.centroid_y))\n"
]
| [
[
"pandas.read_csv",
"pandas.DataFrame"
]
]
|
simonverret/deep_continuation | [
"986bfba7f6806dc4869a023ff1fc1d0d18324b25"
]
| [
"deep_continuation/function_generator.py"
]
| [
"import time\nimport warnings\n\nimport numpy as np\nfrom scipy import integrate\nfrom scipy.special import gamma\nimport matplotlib.pyplot as plt\n\nfrom deep_continuation import utils\nfrom deep_continuation import monotonous_functions as monofunc\n\n\nSMALL = 1e-10\nINF = 1e10\n\ndefault_parameters = {\n 'seed': int(time.time()),\n # peaks\n \"variant\": \"B\",\n \"anormal\": False,\n \"wmax\": 20.0,\n \"nmbrs\": [[0, 4],[0, 6]],\n \"cntrs\": [[0.00, 0.00], [4.00, 16.0]],\n \"wdths\": [[0.40, 4.00], [0.40, 4.00]],\n \"wghts\": [[0.00, 1.00], [0.00, 1.00]],\n \"arngs\": [[2.00, 10.00], [0.70, 10.00]],\n \"brngs\": [[2.00, 10.00], [0.70, 10.00]],\n \"even\": True,\n # lorentz\n 'num_peaks': 10000,\n 'width': 0.05,\n # rescale\n 'rescale': 4.0,\n 'spurious': False,\n}\n\ndefault_parameters_help = {\n 'seed': \"Random seed used to generate the data\",\n 'variant': \"Gaussian (G), Beta (B) or Lorentz (L)\",\n 'anormal': \"(bool) When true, individual peaks are not normalized as in\",\n 'wmax': \"Maximum frequencies of the discrete samples\",\n 'nmbrs': \"(list of list) List of ranges for number of peaks (for each peak group)\",\n 'cntrs': \"(list of list) List of ranges for positions of peaks\",\n 'wdths': \"(list of list) List of ranges for widths of peaks\",\n 'wghts': \"(list of list) List of ranges for weights (heights) of peaks\",\n 'arngs': \"(list of list) List of ranges of the a parameters of Beta peaks\",\n 'brngs': \"(list of list) List of ranges of the b parameters of Beta peaks\",\n 'even': \"(bool) Make a copy of each peaks at negative positions\",\n 'num_peaks': \"Number of Lorentz peaks used in the Lorentz comb\",\n 'width': \"Width of Lorentz peaks of the Lorentz comb\",\n 'rescale': \"Value for fixing the variance of all spectra\",\n 'spurious': \"(bool) Compute Matsubara responses BEFORE rescaling, introducing spurious correlation\",\n}\n\n\ndef simple_plot(pi, wn, sigma, w):\n fig, ax = plt.subplots(1, 3, figsize=[10, 5])\n \n ax[0].set_ylabel(r\"$\\Pi(i\\omega_n)$\")\n ax[0].set_xlabel(r\"$\\omega_n$\")\n ax[0].plot(wn.T, pi.T, '.')\n\n ax[1].set_xlabel(r\"$n$\")\n ax[1].plot( pi.T, '.')\n \n ax[2].set_ylabel(r\"$\\sigma(\\omega)$\")\n ax[2].set_xlabel(r\"$\\omega$\")\n ax[2].plot(w.T, sigma.T, ms=2, lw=1)\n \n # fig.tight_layout()\n plt.show()\n\n\ndef main():\n args = utils.parse_file_and_command(default_parameters, {})\n generator = SigmaPiGenerator.factory(**vars(args))\n\n np.random.seed(args.seed)\n sigma_func, pi_func = generator.generate()\n \n wmax_list = [args.wmax]\n M = 512\n beta_list = [200,400,600]\n N = 128\n\n wn = np.array([np.arange(0, N)*2*np.pi/beta for beta in beta_list])\n Pi = np.array([pi_func(np.arange(0, N)*2*np.pi/beta) for beta in beta_list])\n \n w = np.array([np.linspace(-wmax, wmax, 2*M+1) for wmax in wmax_list])\n sigma = np.array([(wmax/20)*sigma_func(np.linspace(-wmax, wmax, 2*M+1)) for wmax in wmax_list])\n \n simple_plot(Pi, wn, sigma, w)\n\n\ndef sum_on_args(f, x, *args):\n \"\"\"Broadcast a 1D function to all arguments and return the sum.\n\n computes: `f(x, a0[0], a1[0], ...) + f(x, a0[1], a1[1], ...) + ...`\n\n Args:\n f (function): Function to broadcast.\n x (array): Array on which to evaluate\n *args (arrays): Regular arguments of the function as arrays\n\n Returns:\n array: Sum of functions at each `x`\n \"\"\" \n if isinstance(x, np.ndarray):\n x = x[np.newaxis, :]\n args = [a for a in args] # copy args to allow reassign\n for i in range(len(args)):\n if isinstance(args[i], np.ndarray):\n while len(args[i].shape) < len(x.shape):\n args[i] = args[i][:, np.newaxis]\n return f(x, *args).sum(axis=0)\n\n\ndef integrate_with_tails(integrand, grid=4096, tail=1024, grid_end=10, tail_power=7):\n \"\"\"Broadcastable integration on dense grid with long tails\n\n Integrate using `scipy.integrate.simps` using a three piece grid: one linearly\n spaced grid centered at zero, and two logarithmically spaced grid at each ends.\n\n Args:\n integrand (function): Function to be integrated\n grid (int, optional): Number of points in central grid. Defaults to 4096.\n tail (int, optional): Number of points in each tail. Defaults to 1024.\n grid_end (int, optional): Span of central grid (`-grid_end` to `grid_end`). Defaults to 10.\n tail_power (int, optional): Tail . Defaults to 7.\n\n Returns:\n ndarray: Result from an integration on `axis=-1`\n \"\"\"\n grid_sampling = np.linspace(-grid_end, grid_end, grid)\n tail_sampling = np.logspace(\n np.log10(grid_end), tail_power, tail)[1:]\n full_sampling = np.concatenate([\n -np.flip(tail_sampling),\n grid_sampling,\n tail_sampling\n ])\n return integrate.simps(integrand(full_sampling), full_sampling, axis=-1)\n\n\ndef pi_integral(wn, spectral_function, **kwargs):\n \"\"\"Broadcastable integral for the Current-current response function.\n\n Integrate the spectral function :math:`\\sigma(\\omega)`\n .. math::\n \\\\Pi(i\\\\omega_n) = \\\\int_{-\\infty}^{\\\\infty}\n \\\\frac{\\\\omega^2}{\\\\omega^2+\\\\omega_n^2}\\sigma()_{i}\n using :func:`~integrate_with_tails`\n\n Args:\n wn (array): Matsubara frequencies at which to compute the response\n spectral_function (function): Callable spectral function\n\n Keyword Args:\n see :func:`~deep_continuation.function_generator.integrate_with_tails` \n \n Returns:\n array: Result from an integration on `axis=-1`\n \"\"\"\n if isinstance(wn, np.ndarray):\n wn = wn[:, np.newaxis]\n\n integrand = lambda x: (1/np.pi) * x**2 / (x**2+wn**2) * spectral_function(x)\n return integrate_with_tails(integrand, **kwargs)\n\n\ndef normalization(f, **kwargs):\n \"\"\"Integrate function using :func:`~integrate_with_tails`\n\n Args:\n f (function): Function to be integrated.\n\n Returns:\n float: Normalization value\n \"\"\" \n def integrand(x): return f(x)\n return integrate_with_tails(integrand, **kwargs)\n\n\ndef first_moment(f, **kwargs):\n \"\"\"Computes the first central moment (average) using :func:`~integrate_with_tails`\n\n Args:\n f (function): Input function for which the moment is computed\n \n Returns:\n float: First central moment (average)\n \"\"\"\n def integrand(x): return x*f(x)\n return integrate_with_tails(integrand, **kwargs)\n\n\ndef second_moment(f, **kwargs):\n \"\"\"Computes the sencond central moment (variance) using :func:`~integrate_with_tails`\n\n Args:\n f (function): Input function for which the moment is computed\n\n Returns:\n float: Second central moment (variance)\n \"\"\"\n def integrand(x): return ((x - first_moment(f))**2)*f(x)\n return integrate_with_tails(integrand, **kwargs)\n\n\ndef gaussian(x, c, w, h):\n \"\"\"Gaussian distributions.\n\n Args:\n x (array): Values at which the gaussian is evaluated\n c (float): Center of the distribution (average)\n w (float): Width of the distribution (variance)\n h (float): Height/weight of the distribtuion (area under the curve)\n\n Returns:\n array: Values of the gaussian at values in `x`\n \"\"\"\n return (h/(np.sqrt(2*np.pi)*w))*np.exp(-((x-c)/w)**2/2)\n\n\ndef lorentzian(x, c, w, h):\n \"\"\"Lorentz distributions.\n\n Args:\n x (array): Values at which the lorentzian is evaluated\n c (float): Center of the distribution\n w (float): Width of the distribution (at half height)\n h (float): Height/weight of the distribtuion (area under the curve)\n\n Returns:\n array: Values of the lorentzian at values in `x`\n \"\"\"\n return (h/np.pi)*w/((x-c)**2+w**2)\n\n\ndef even_lorentzian(x, c, w, h):\n \"\"\"Even pair of identical Lorentz distributions.\n \n Args:\n x (array): Values at which the lorentzian is evaluated\n c (float): Center of the distribution (+ or -)\n w (float): Width of the distribution (variance)\n h (float): Height/weight of the distribtuion (area under the curve)\n\n Returns:\n array: Values of the lorentzian pair at values in `x`\n \"\"\"\n return (1/np.pi)*4*c*w*h/(((x-c)**2+w**2)*((x+c)**2+w**2))\n\n\ndef analytic_pi(x, c, w, h):\n \"\"\"Analytic response function for an even pair of Lorentz distributions.\n\n Correspond to\n .. math::\n \\\\Pi(x) = \\\\int_{-\\infty}^{\\\\infty}\n \\\\frac{\\\\omega^2}{\\\\omega^2+x^2}\\sigma()_{i}\n where :math:`\\\\sigma(\\\\omega)` is :func:`~even_lorentzian`.\n\n Args:\n x (array): matsubara at which the response function is evaluated\n c (float): Center of the distribution (+ or -)\n w (float): Width of the distribution (variance)\n h (float): Height/weight of the distribtuion (area under the curve)\n\n Returns:\n array: Values of the integral at imaginary `x`\n \"\"\"\n return 2*h*c/(c**2+(x+w)**2)\n\n\ndef beta_dist(x, a, b):\n \"\"\"Beta distribution.\n\n Args:\n x (array): Values at which to evaluate the distribution\n a (float): First Beta function parameter\n b (float): Second Beta function parameter\n\n Returns:\n array: Values of the function at the values of `x`\n \"\"\" \n\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n return (gamma(a+b)/(SMALL+gamma(a)*gamma(b)))\\\n * np.nan_to_num((x**(a-1))*((1-x)**(b-1))\\\n * (x > 0) * (x < 1), copy=False)\n\n\ndef centered_beta(x, a, b):\n \"\"\"Beta distribution centered at x=0.\n\n Args:\n x (array): Values at which to evaluate the distribution\n a (float): First Beta function parameter\n b (float): Second Beta function parameter\n\n Returns:\n array: Values of the function at the values of `x`\n \"\"\"\n c = a/(a+b)\n return beta_dist(x+c, a, b)\n\n\ndef standardized_beta(x, a, b):\n \"\"\"Beta distribution centered at x=0 with variance 1.\n\n Args:\n x (array): Values at which to evaluate the distribution\n a (float): First Beta function parameter\n b (float): Second Beta function parameter\n\n Returns:\n array: Values of the function at the values of `x`\n \"\"\"\n w = np.sqrt(a*b/((a+b+1)*(a+b)**2))\n return centered_beta(x*w, a, b)*w\n\n\ndef free_beta(x, c, w, h, a, b):\n \"\"\"Beta distribution with user-defined center, width and height.\n\n Args:\n x (array): Values at which to evaluate the distribution\n c (float): Center of the distribution (average)\n w (float): Width of the distribution (variance)\n h (float): Height/weight of the distribtuion (area under the curve)\n a (float): First Beta function parameter\n b (float): Second Beta function parameter\n\n Returns:\n array: Values of the function at the values of `x`\n \"\"\"\n return h*standardized_beta((x-c)/w, a, b)/w\n\n\nclass SigmaGenerator():\n \"\"\"Base class for conductivity functions generators, with static factory method.\"\"\"\n \n def generate(self):\n \"\"\"Each call outputs a new random function as specified in subclasses.\"\"\"\n raise NotImplementedError(\"To be overridden in subclasses\")\n\n def factory(variant, **kwargs):\n \"\"\"Static factory method: Creates the subclass specified by `variant`.\n \n The available generators include:\n - Gaussian mixture generator (G)\n - Beta mixture generator (B)\n - Lorentzian mixture generator (L)\n\n Args:\n variant (string): Specifies which subclass to instanciate\n nmbrs (list of tuples, optional): List of groups of peaks\n where tuples indicate a range for the number of peaks\n in each group. Defaults to [[0,4],[0,6]] (two groups\n of peaks, one up to 4 peaks the other up to 6).\n cntrs (list of tuples, optional): List of groups of peaks\n where tuples indicate a range for the centers of the\n peaks in each group. Defaults to [[0.00, 0.00], \n [4.00, 16.0]] (two groups of peaks, the firsts\n centered at 0 the other centered between 4 and 16).\n wdths (list of tuples, optional): List of groups of peaks\n where tuples indicate a range for the widths of the\n peaks in each group. Defaults to [[0.04, 0.40],\n [0.04, 0.40]].\n wgths (list of tuples, optional): List of groups of peaks\n where tuples indicate a range for the heights/widths\n of the peaks in each group. Defaults to \n [[0.00, 1.00], [0.00, 1.00]].\n arngs (list of tuples, optional): List of groups of peaks\n where tuples indicate a range for the `a` parameters\n for Beta peaks. Defaults to \n [[2.00, 5.00], [0.50, 5.00]].\n brngs (list of tuples, optional): List of groups of peaks\n where tuples indicate a range for the `b` parameters\n for Beta peaks. Defaults to \n [[2.00, 5.00], [0.50, 5.00]].\n norm (int, optional): Total weight. Defaults to 1.\n anormal (bool, optional): All peaks are equally weighted.\n Defaults to False.\n\n Raises:\n ValueError: if `variant` is not recognized\n\n Returns:\n SigmaGenerator: One subclass of SigmaGenerator\n \"\"\" \n if variant in [\"G\", \"Gaussian\", \"gaussian\"]:\n return GaussianMix(**kwargs)\n elif variant in [\"B\", \"Beta\", \"beta\"]:\n return BetaMix(**kwargs)\n elif variant in [\"L\", \"Lorentzian\", \"lorentzian\"]:\n return LorentzMix(**kwargs)\n else:\n raise ValueError(f\"SigmaGenerator variant {variant} not recognized\")\n factory = staticmethod(factory)\n \n \nclass GaussianMix(SigmaGenerator):\n \"\"\"Gaussian mixture generator, doc at :func:`~SigmaGenerator.factory`\"\"\"\n \n def __init__(self, \n nmbrs=[[0,4],[0,6]],\n cntrs=[[0.00, 0.00], [4.00, 16.0]],\n wdths=[[0.04, 0.40], [0.04, 0.40]],\n wgths=[[0.00, 1.00], [0.00, 1.00]],\n norm=1, anormal=False,\n **kwargs\n ):\n self.nmbrs = nmbrs\n self.cntrs = cntrs\n self.wdths = wdths\n self.wgths = wgths\n self.norm = norm\n self.anormal = anormal\n\n def _random_num_per_group(self):\n num_per_group = [np.random.randint(n[0], n[1]+1) for n in self.nmbrs]\n if all(num_per_group) == 0:\n lucky_group = np.random.randint(0,len(num_per_group)-1)\n num_per_group[lucky_group] = 1\n return num_per_group\n\n def _random_cwh(self, num_per_groups):\n cl, wl, hl = [], [], []\n for i, n in enumerate(num_per_groups):\n cl.append(np.random.uniform(self.cntrs[i][0], self.cntrs[i][1], n))\n wl.append(np.random.uniform(self.wdths[i][0], self.wdths[i][1], n))\n hl.append(np.random.uniform(self.wgths[i][0], self.wgths[i][1], n))\n c = np.hstack(cl)\n w = np.hstack(wl)\n h = np.hstack(hl)\n\n if self.anormal:\n h *= w # In some papers the gaussians are not normalized\n if self.norm:\n h *= np.pi*self.norm/(h.sum()+SMALL)\n\n return c, w, h\n\n def generate(self):\n c, w, h = self._random_cwh(self._random_num_per_group())\n sigma = lambda x: sum_on_args(gaussian, x, c, w, h)\n return sigma\n\n\nclass LorentzMix(GaussianMix):\n \"\"\"Lorentzian mixture generator, doc at :func:`~SigmaGenerator.factory`\"\"\"\n \n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n\n def generate(self):\n c, w, h = self._random_cwh(self._random_num_per_group())\n sigma = lambda x: sum_on_args(lorentzian, x, c, w, h)\n return sigma\n\n\nclass BetaMix(GaussianMix):\n \"\"\"Beta mixture generator, doc at :func:`~SigmaGenerator.factory`\"\"\"\n\n def __init__(self, \n arngs=[[2.00, 5.00], [0.50, 5.00]],\n brngs=[[2.00, 5.00], [0.50, 5.00]],\n **kwargs\n ):\n super().__init__(**kwargs)\n self.arngs = arngs\n self.brngs = brngs\n\n def _random_ab(self, num_per_groups):\n al, bl = [], []\n for i, n in enumerate(num_per_groups):\n al.append(np.random.uniform(self.arngs[i][0], self.arngs[i][1], n))\n bl.append(np.random.uniform(self.brngs[i][0], self.brngs[i][1], n))\n a = np.hstack(al)\n b = np.hstack(bl)\n return a, b\n\n def generate(self):\n num_per_groups = self._random_num_per_group()\n c, w, h = self._random_cwh(num_per_groups)\n a, b = self._random_ab(num_per_groups)\n sigma = lambda x: sum_on_args(free_beta, x, c, w, h, a, b)\n return sigma\n\n\nclass SigmaPiGenerator():\n def generate(self):\n \"\"\"outputs two functions\"\"\"\n raise NotImplementedError\n\n def factory(variant, rescale=False, spurious=False, **kwargs):\n if variant in [\"LC\", \"Lorentz_comb\", \"lorentz_comb\"]:\n return LorentzComb(**kwargs)\n\n sigma_generator = SigmaGenerator.factory(variant, **kwargs)\n if rescale:\n if spurious:\n return Fix2ndMomSpuriousGenerator(sigma_generator, factor=rescale, **kwargs)\n else:\n return Fix2ndMomentGenerator(sigma_generator, factor=rescale, **kwargs)\n\n return IntegralGenerator(sigma_generator, **kwargs)\n factory = staticmethod(factory)\n\n\nclass IntegralGenerator(SigmaPiGenerator):\n def __init__(self, sigma_generator, wmax=20, **kwargs):\n self.sigma_generator = sigma_generator\n self.wmax = wmax\n\n def generate_sigma_even(self):\n sigma_base = self.sigma_generator.generate()\n sigma_even = lambda x: 0.5*(sigma_base(x)+sigma_base(-x))\n return sigma_even\n \n def generate_integrator_pi(self, sigma_even, grid_end):\n return lambda x: pi_integral(x, sigma_even, grid_end=self.wmax)\n\n def generate(self):\n sigma_even = self.generate_sigma_even()\n pi = self.generate_integrator_pi(sigma_even, grid_end=self.wmax)\n return sigma_even, pi\n\n\ndef rescaling(sigma_even, wmax, factor):\n sec_moment = (INF**2)*pi_integral(INF, sigma_even, grid_end=wmax)\n new_wmax = np.sqrt(sec_moment) * factor\n s = (new_wmax/wmax)\n resc_sigma = lambda x: s*sigma_even(s*x)\n return resc_sigma, new_wmax\n\n\nclass Fix2ndMomentGenerator(IntegralGenerator):\n def __init__(self, sigma_generator, factor=4.0, **kwargs):\n super().__init__(sigma_generator, **kwargs)\n self.factor = factor\n self.tmp_wmax = self.wmax\n \n def generate(self):\n sigma_even = self.generate_sigma_even()\n resc_sigma, self.tmp_wmax = rescaling(sigma_even, self.wmax, self.factor)\n pi = self.generate_integrator_pi(resc_sigma, grid_end=self.tmp_wmax) \n return resc_sigma, pi\n\n\nclass Fix2ndMomSpuriousGenerator(Fix2ndMomentGenerator):\n \"\"\"Uses the original Pi with the rescaled sigma\n\n The Pi obtained before rescaling is compatible with the rescaled sigma but\n causes a spurious correlation between temperature and sigma structure \n \"\"\"\n def __init__(self, sigma_generator, **kwargs):\n super().__init__(sigma_generator, **kwargs)\n \n def generate(self):\n sigma_even = self.generate_sigma_even()\n pi = self.generate_integrator_pi(sigma_even, grid_end=self.wmax) \n resc_sigma, self.tmp_wmax = rescaling(sigma_even, self.wmax, self.factor)\n return resc_sigma, pi\n\n\nclass LorentzComb(SigmaPiGenerator):\n def __init__(self, norm=1, num_peaks=1000, width=0.05, wmax=20, **kwargs):\n self.norm = norm\n self.num_peaks = num_peaks\n self.width = width\n self.wmax = wmax\n\n def generate(self):\n k = np.linspace(0, 1, self.num_peaks)\n # c = monofunc.piecewise_gap(k, n=8, soft=0.05, xlims=[0,1], ylims=[0,0.8*self.wmax])\n c = monofunc.random_climb(k, xlims=[0, 1], ylims=[0, 0.8*self.wmax])\n w = np.ones(self.num_peaks)*self.width\n h = abs(c) + 0.05\n h *= self.norm/(2*h*c/(c**2+w**2)).sum()\n sigma = lambda x: sum_on_args(even_lorentzian, x, c, w, h)\n pi = lambda x: sum_on_args(analytic_pi, x, c, w, h)\n return sigma, pi\n\n\nif __name__ == \"__main__\":\n main()\n"
]
| [
[
"numpy.hstack",
"scipy.special.gamma",
"numpy.sqrt",
"numpy.random.seed",
"numpy.linspace",
"numpy.arange",
"matplotlib.pyplot.subplots",
"numpy.nan_to_num",
"numpy.ones",
"numpy.log10",
"numpy.exp",
"numpy.random.uniform",
"matplotlib.pyplot.show",
"numpy.flip",
"numpy.random.randint"
]
]
|
rohitgajawada/Where-are-they-looking-PyTorch | [
"d4627a1659b5f6ddc7b829b3a60f5e360f1791d5"
]
| [
"modeltester.py"
]
| [
"import torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.autograd import Variable\nimport getdata as ld\nimport utils\nimport os\nimport opts\nfrom PIL import Image\nimport models.gazenet as gazenet\nimport torchvision\nfrom torchvision import transforms\nimport matplotlib.pyplot as plt\nimport matplotlib\n\nparser = opts.optionargparser()\nopt = parser.parse_args()\n\nopt.testbatchsize = 16\n\ncheckpoint = torch.load('./savedmodels/gazenet_gazefollow_softmaxnesterovsgd_70epoch.pth.tar')\nprint(\"Loading pretrained model: \")\nstart_epoch = checkpoint['epoch']\nbest_err = checkpoint['best_err']\n\nmodel = gazenet.Net(opt).cuda()\nmodel.load_state_dict(checkpoint['state_dict'])\n\ndataloader = ld.GazeFollow(opt)\n\nimages, xis, eye_coords, pred_coords, eyes, names, eyes2, gaze_final = next(iter(dataloader.val_loader))\n\nimages, xis, eye_coords, pred_coords, gaze_final = images.cuda(), xis.cuda(), eye_coords.cuda(), pred_coords.cuda(), gaze_final.cuda()\n\noutputs = model.predict(images, xis, eye_coords)\n\nuntr = transforms.Compose([\n transforms.Normalize([0, 0, 0], [1/(0.229), 1/(0.224), 1/(0.225)])])\nuntr2 = transforms.Compose([\n transforms.Normalize([-0.485, -0.456, -0.406], [1, 1, 1])])\n\nto_pil = torchvision.transforms.ToPILImage()\n\nfor i in range(16):\n\n name = names[i]\n img = untr(images[i].data.contiguous().cpu())\n img = untr2(img)\n\n print(torch.max(outputs[i]))\n\n heat_in = torch.clamp(outputs[i].data.cpu(), 0, 1)\n\n heatmap = to_pil(heat_in)\n plt.imshow(heatmap)\n plt.savefig('./model_outputs/' + str(i) + '_heat.jpg')\n plt.clf()\n\n\n pred = outputs[i].data.view(1, 227 * 227)\n ind = pred.max(1)[1]\n\n y = ((float(ind[0]/ 227.0)) / 227.0)\n x = ((float(ind[0] % 227.0)) / 227.0)\n\n print(x, y)\n\n im = to_pil(img)\n eye_np = eyes[i].cpu().numpy()\n\n print(eye_np)\n print(x * 227, y * 227)\n\n plt.plot([x* 227, eye_np[0]* 227],[y* 227, eye_np[1]* 227])\n plt.imshow(im)\n plt.savefig('./model_outputs/' + str(i) + '.jpg')\n plt.clf()\n\n# exit()\n"
]
| [
[
"matplotlib.pyplot.imshow",
"torch.max",
"torch.load",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.clf"
]
]
|
pkulwj1994/AdversarialConsistentScoreMatching | [
"f439f242f004ce06382ed72f2aa7daf9c262abfa"
]
| [
"runners/abc_runner.py"
]
| [
"import abc\nimport os\n\nimport numpy as np\nfrom torch.nn import DataParallel\n\nfrom datasets import data_transform, get_dataloader\nfrom losses import get_optimizer\nfrom models.GAN_D import *\nfrom models.UNet import *\nfrom models.ema import EMAHelper\nfrom models.ncsnv2 import NCSNv2, NCSNv2Deeper, NCSNv2Deepest\n\n\ndef get_model(m_config, d_config, args):\n\n if m_config.unet:\n kwargs = {'n_channels': 3, 'dropout': m_config.dropout,\n 'deeper': not (d_config.dataset == 'CIFAR10' or d_config.dataset == 'CELEBA'),\n 'ngf': m_config.ngf}\n return UNet(**kwargs).to(args.device)\n\n if d_config.dataset == \"FFHQ\":\n model = NCSNv2Deepest\n elif d_config.dataset == 'LSUN':\n model = NCSNv2Deeper\n else:\n model = NCSNv2\n\n sigmoid = args.target == 'dae'\n model_args = [m_config, d_config, sigmoid, args.no_dilation, args.std]\n return model(*model_args).to(args.device)\n\n\nclass Runner(abc.ABC):\n def __init__(self, args, config):\n self.args = args\n self.config = config\n args.log_sample_path = os.path.join(args.log_path, 'samples')\n os.makedirs(args.log_sample_path, exist_ok=True)\n\n @abc.abstractmethod\n def run(self):\n pass\n\n def get_model(self, dataparallel=True):\n score = get_model(self.config.model, self.config.data, self.args)\n if dataparallel:\n score = DataParallel(score)\n return score\n\n def get_sigmas(self, npy=False, training=False):\n sigmas = get_sigma(self.config.model, self.config.sampling, training)\n return sigmas if npy else torch.tensor(sigmas).float().to(self.args.device)\n\n def get_dataloader(self, **kwargs):\n return get_dataloader(self.config.data, self.config.sampling.data_init, self.args.data_folder, **kwargs)\n\n def get_optimizer(self, params, adv=False):\n return get_optimizer(self.config.optim, params, adv_opt=adv)\n\n # noinspection PyShadowingBuiltins\n def load_score(self, eval=False):\n score = self.get_model()\n score = self._load_states(score)\n\n if eval:\n score.eval()\n\n return score\n\n def _load_states(self, score):\n if self.config.sampling.ckpt_id is None:\n path = os.path.join(self.args.log_path, 'checkpoint.pth')\n else:\n path = os.path.join(self.args.log_path, f'checkpoint_{self.config.sampling.ckpt_id}.pth')\n states = torch.load(path, map_location=self.args.device)\n\n # score.load_state_dict(states[0], strict=True)\n\n if self.config.model.ema:\n ema_helper = EMAHelper(mu=self.config.model.ema_rate)\n ema_helper.register(score)\n ema_helper.load_state_dict(states[-1])\n ema_helper.ema(score)\n else:\n score.load_state_dict(states[0])\n\n del states\n\n return score\n\n def get_initsamples(self, dataloader, sigma_begin=None, inpainting=False, data_iter=None, bs=None):\n if inpainting:\n data_iter = iter(dataloader)\n refer_images, _ = next(data_iter)\n refer_images = refer_images.to(self.args.device)\n width = int(np.sqrt(self.config.sampling.batch_size))\n init_samples = torch.rand(width, width, self.config.data.channels,\n self.config.data.image_size,\n self.config.data.image_size,\n device=self.args.device)\n init_samples = data_transform(self.config.data, init_samples)\n return init_samples, refer_images\n\n elif self.config.sampling.data_init:\n _return_iter = data_iter is not None\n if data_iter is None:\n data_iter = iter(dataloader)\n\n try:\n samples, _ = next(data_iter)\n except StopIteration:\n data_iter = iter(dataloader)\n samples, _ = next(data_iter)\n\n if bs is not None:\n samples = samples[:bs]\n\n samples = samples.to(self.args.device)\n samples = data_transform(self.config.data, samples)\n init_samples = samples\n if not self.config.sampling.noise_first:\n init_samples += sigma_begin * torch.randn_like(samples)\n\n if _return_iter:\n return init_samples, data_iter\n return init_samples\n\n else:\n bs = self.config.sampling.batch_size if bs is None else bs # fid else config.fast_fid.batch_size\n init_samples = torch.rand(bs, self.config.data.channels,\n self.config.data.image_size, self.config.data.image_size,\n device=self.args.device)\n init_samples = data_transform(self.config.data, init_samples)\n return init_samples\n\ndef get_sigma(m_config, s_config, training):\n \"\"\"\n\n Args:\n m_config: model config\n s_config: sampling config\n training: are the sigmas used for training (true) or sampling (false)\n\n Returns:\n\n \"\"\"\n sigma_dist = m_config.sigma_dist if training else s_config.sigma_dist\n\n num_classes = m_config.num_classes\n if s_config.consistent and not training:\n num_classes = (num_classes - 1) * s_config.nsigma + 1\n\n if sigma_dist == 'geometric':\n return np.geomspace(m_config.sigma_begin, m_config.sigma_end, num_classes)\n\n elif sigma_dist == 'linear':\n return np.linspace(m_config.sigma_begin, m_config.sigma_end, num_classes)\n\n else:\n raise NotImplementedError('sigma distribution not supported')\n"
]
| [
[
"numpy.geomspace",
"torch.nn.DataParallel",
"numpy.sqrt",
"numpy.linspace"
]
]
|
emirkmo/imagematch | [
"99c48a37aad455c7451e907f9ea8689b19e21a35"
]
| [
"imagematch/VTKHelperFunctions.py"
]
| [
"'''A module to help translate back and forth from python layer to VTK'''\n\nimport vtk\nfrom vtk.util import numpy_support\nimport numpy as np\n\n\ndef NumToVTKArray(arr, name=None):\n __typeDict = {np.uint8:vtk.vtkUnsignedCharArray,\n np.byte:vtk.vtkUnsignedCharArray,\n np.bool:vtk.vtkUnsignedCharArray,\n np.int8:vtk.vtkUnsignedCharArray,\n np.int16:vtk.vtkShortArray,\n np.uint16:vtk.vtkUnsignedShortArray,\n np.int32:vtk.vtkIntArray, np.int64:vtk.vtkLongArray,\n np.float32:vtk.vtkFloatArray,\n np.float64:vtk.vtkDoubleArray, \n np.complex64:vtk.vtkFloatArray, \n np.complex128:vtk.vtkDoubleArray }\n nt = arr.dtype\n for td in __typeDict.keys():\n if td == nt: utd=td;break\n vtkarray = __typeDict[utd]()\n dims = arr.shape\n vtkarray.SetVoidArray(arr.ravel(),np.multiply.reduce(dims),1)\n if len(dims) > 1: vtkarray.SetNumberOfComponents(dims[0])\n else: vtkarray.SetNumberOfComponents(1)\n vtkarray.SetNumberOfValues(np.multiply.reduce(dims))\n if name: vtkarray.SetName(name)\n return vtkarray\n\ndef VTKArrayToVTKImage(v,nc=-1,wid=-1,hei=-1):\n ii = vtk.vtkImageData()\n\n shape2 = [v.GetNumberOfComponents(), v.GetNumberOfTuples()]\n ii.SetDimensions(shape2[1], shape2[0], 1)\n ii.AllocateScalars(v.GetDataType(), 1)\n\n ii.GetPointData().SetScalars(v)\n if wid>0 and hei>0:\n ii.SetExtent(0,wid-1,0,hei-1,0,0)\n return ii\n\ndef NumToVTKImage(numarray,name=None):\n dims = numarray.shape\n if len(dims) ==1:\n return NumToVTKArray(numarray, name)\n ii = vtk.vtkImageData()\n ii.SetDimensions(numarray.shape[0], numarray.shape[1], 1)\n ii.SetSpacing(1,1,1)\n ii.SetOrigin(0,0,0)\n ii.SetExtent(0, numarray.shape[0]-1, 0, numarray.shape[1]-1, 0, 0)\n vtktype = numpy_support.get_vtk_array_type(numarray.dtype)\n ii.AllocateScalars(vtktype, 1)\n pd = ii.GetPointData()\n arr = numpy_support.numpy_to_vtk(np.ndarray.flatten(numarray, 'F'))\n pd.SetScalars(arr)\n return ii\n\ndef VTKImageToNum(i):\n __typeDict = { vtk.VTK_ID_TYPE: np.int64, \n vtk.VTK_CHAR:np.int8, \n vtk.VTK_UNSIGNED_CHAR:np.uint8,\n vtk.VTK_SHORT:np.int16, \n vtk.VTK_UNSIGNED_SHORT:np.uint16, \n vtk.VTK_INT:np.int32, \n vtk.VTK_FLOAT:np.float32, \n vtk.VTK_DOUBLE:np.float64, \n vtk.VTK_LONG:np.int64}\n ie = vtk.vtkImageExport()\n d = list(i.GetDimensions())\n d.reverse()\n if d[0] == 1: d = d[1:]\n if d[0] == 1: d = d[1:]\n #d.reverse()\n it = i.GetScalarType()\n scalars = i.GetPointData().GetScalars()\n if scalars: it = scalars.GetDataType()\n else: it = vtk.VTK_FLOAT\n nat = __typeDict[it]\n x = np.zeros(d,nat)\n ie.SetExportVoidPointer(x)\n ie.ImageLowerLeftOn()\n ie.SetInputData(i)\n ie.Export()\n return np.squeeze(x).T\n\n\ndef VTKImageShift(x,u,v,numret=False,interp=True,wrap=False,mirror=False,\n constant=None,cubic=False):\n if type(x) == type(np.arange(2)): i = NumToVTKImage(x)\n else: i = x\n if 0 and int(u) == u and int(v) == v:\n s = vtk.vtkImageTranslateExtent()\n s.SetInput(i)\n s.SetTranslation(u,v,0)\n o = s.GetOutput()\n s.Update()\n else:\n s = vtk.vtkImageReslice()\n s.AutoCropOutputOn()\n if wrap: s.WrapOn()\n else: s.WrapOff()\n if mirror or constant != None: s.MirrorOn()\n else: s.MirrorOff()\n if interp:\n s.InterpolateOn()\n if cubic:\n s.SetInterpolationModeToCubic()\n else:\n s.SetInterpolationModeToLinear()\n else: s.InterpolateOff()\n s.OptimizationOn()\n s.SetOutputOrigin(u,v,0)\n s.SetInputData(i)\n o=s.GetOutput()\n s.Update()\n if numret: return VTKImageToNum(o)\n else: return o\n\n\ndef VTKImageArith(x1,x2,op,numret=False,rep=0.0):\n if type(x1) == np.ndarray and type(x2) == np.ndarray:\n if x1.dtype == np.float64 or x2.dtype == np.float64:\n x1,x2 = x1.astype(np.float64), x2.astype(np.float64)\n elif x1.dtype == np.float32 or x2.dtype == np.float32:\n x1,x2 = x1.astype(np.float32), x2.astype(np.float32)\n if type(x1) == np.ndarray: i1 = NumToVTKImage(x1)\n else: i1 = x1\n if type(x2) == np.ndarray: i2 = NumToVTKImage(x2)\n else: i2 = x2\n m = vtk.vtkImageMathematics()\n numops = [ \"multiply\",\"divide\",\"add\",\"subtract\"]\n if op == \"divide\":\n m.SetConstantC(rep); m.DivideByZeroToCOn()\n if type(x1) == np.ndarray and type(x2) == np.ndarray:\n m.SetInput1Data(i1)\n m.SetInput2Data(i2)\n vtkops = [ m.SetOperationToMultiply, m.SetOperationToDivide, m.SetOperationToAdd, m.SetOperationToSubtract]\n elif type(x1) == np.ndarray:\n m.SetInput1Data(i1)\n if i2 == 0:\n const = 0.0\n else:\n const = [i2,1.0/i2,i2,-i2][numops.index(op)]\n m.SetConstantK(const)\n m.SetConstantC(const)\n vtkops = [ m.SetOperationToMultiplyByK, m.SetOperationToMultiplyByK, m.SetOperationToAddConstant, m.SetOperationToAddConstant]\n if type(x1) != np.ndarray and type(x2) != np.ndarray:\n return eval(op)(x1,x2)\n else:\n vtkops[numops.index(op)]()\n o = m.GetOutput()\n m.Update()\n if numret: return VTKImageToNum(o)\n else: return o\n\ndef VTKAdd(x1,x2): return VTKImageArith(x1,x2,\"add\",numret=True)\ndef VTKSubtract(x1,x2): return VTKImageArith(x1,x2,\"subtract\",numret=True)\ndef VTKMultiply(x1,x2): return VTKImageArith(x1,x2,\"multiply\",numret=True)\ndef VTKDivide(x1,x2,rep=0): return VTKImageArith(x1,x2,\"divide\",numret=True,\n rep=rep)\n\n\ndef VTKImageLogic(x1,x2=None,op=\"or\",numret=False):\n if type(x1) == np.ndarray: i1 = NumToVTKImage(x1)\n else: i1 = x1\n if type(x2) == np.ndarray: i2 = NumToVTKImage(x2)\n elif x2: i2 = x2\n m = vtk.vtkImageLogic()\n numops = [ \"and\",\"or\",\"xor\",\"nand\",\"nor\",\"not\"]\n vtkops = [ m.SetOperationToAnd, m.SetOperationToOr, m.SetOperationToXor, m.SetOperationToNand, m.SetOperationToNor, m.SetOperationToNot]\n m.SetOutputTrueValue(1.0)\n vtkops[numops.index(op)]()\n m.SetInput1Data(i1)\n if x2 is not None: m.SetInput2Data(i2)\n o = m.GetOutput()\n m.Update()\n if numret: return VTKImageToNum(o)\n else: return o\n\ndef VTKOr(x1,x2): return VTKImageLogic(x1,x2=x2,op=\"or\",numret=1)\ndef VTKAnd(x1,x2): return VTKImageLogic(x1,x2=x2,op=\"and\",numret=1)\ndef VTKNot(x1): return VTKImageLogic(x1,x2=None,op=\"not\",numret=1)\n\ndef VTKGrowN(x,n=2,m=None,numret=False,origsize=None,interp=False,wrap=False,\n constant=None,mirror=False,xshift=0,yshift=0):\n if type(x) == np.ndarray: i = NumToVTKImage(x)\n else: i = x\n d = i.GetDimensions()\n if not m: m = n\n if d[0] == 1: n = 1\n if d[1] == 1: m = 1\n im = vtk.vtkImageMagnify()\n im.SetMagnificationFactors(n,m,1)\n if interp: im.InterpolateOn()\n else: im.InterpolateOff()\n im.SetInputData(i)\n o = im.GetOutput()\n im.Update()\n o.SetSpacing(1,1,1)\n #o.Update()\n o = VTKImageShift(o,xshift,yshift,interp=True,wrap=wrap,constant=constant,\n mirror=mirror)\n if origsize is not None:\n if len(origsize) == 1: origsize=(1,)+origsize\n p = vtk.vtkImageMirrorPad()\n p.SetOutputWholeExtent(0,origsize[1]-1,0,origsize[0]-1,0,0)\n p.SetInputData(o)\n f = p.GetOutput()\n p.Update()\n o = f\n if numret: return VTKImageToNum(o)\n else: return o\n\n\ndef VTKImageTransform(x,dx,dy,numret=False,reverse=False,origsize=None,\n cubic=False,interp=True,scalex=1,scaley=1,constant=0,wrap=False,\n mirror=False):\n\n maxdx = max([int(max(abs(dx.ravel()))+1),(dx.shape[1]-x.shape[1])])\n maxdy = max([int(max(abs(dy.ravel()))+1),(dx.shape[0]-x.shape[0])])\n dx = dx.astype(np.float32)\n dy = dy.astype(np.float32)\n if scalex > 1:\n xx = np.arange(x.shape[1])\n dx = (xx[np.newaxis,::]+dx).astype(np.float32)\n dy = VTKGrowN(dy,scalex,1,numret=True)\n dx = VTKGrowN(dx,scalex,1,numret=True)\n dx = (dx-np.arange(scalex*x.shape[1])[np.newaxis,::]).\\\n astype(np.float32)\n if scaley > 1:\n yy = np.arange(x.shape[0])\n dy = (yy[::,np.newaxis]+dy).astype(np.float32)\n dy = VTKGrowN(dy,1,scaley,numret=True)\n dx = VTKGrowN(dx,1,scaley,numret=True)\n dy = (dy-np.arange(scaley*x.shape[0])[::,np.newaxis]).\\\n astype(np.float32)\n if type(x) == np.ndarray: i = NumToVTKImage(x)\n else: i = x\n if type(dx) == np.ndarray: tx = NumToVTKImage(dx)\n else: tx = dx\n if type(dy) == np.ndarray: ty = NumToVTKImage(dy)\n else: ty = dy\n dm = ty.GetDimensions()\n dz = np.zeros(dy.shape,dy.dtype)\n tz = NumToVTKImage(dz)\n a = vtk.vtkImageAppendComponents()\n a.AddInputData(tx)\n a.AddInputData(ty)\n a.AddInputData(tz)\n a.Update()\n t = a.GetOutput()\n r = vtk.vtkGridTransform()\n r.SetDisplacementGridData(t)\n r.Update()\n s = vtk.vtkImageReslice()\n s.WrapOff()\n s.MirrorOn()\n if interp:\n s.InterpolateOn()\n if cubic: s.SetInterpolationModeToCubic()\n else: s.SetInterpolationModeToLinear()\n s.SetOutputDimensionality(2)\n if reverse:\n r.SetInterpolationModeToLinear()\n r.SetInverseTolerance(0.001)\n r.SetInverseIterations(1000)\n r.DebugOff()\n ir = r.GetInverse()\n ir.SetInterpolationModeToLinear()\n ir.SetInverseTolerance(0.001)\n ir.SetInverseIterations(1000)\n ir.GlobalWarningDisplayOff()\n s.SetResliceTransform(ir)\n s.AutoCropOutputOff()\n if origsize: s.SetOutputExtent(0,origsize[1]-1,0,origsize[0]-1,0,0)\n else: s.SetOutputExtent(0,scalex*dm[0]-1,0,scaley*dm[1]-1,0,0)\n else:\n r.SetInterpolationModeToCubic()\n r.SetInverseTolerance(0.001)\n r.SetInverseIterations(1000)\n r.GlobalWarningDisplayOff()\n s.SetOutputExtent(0,scalex*dm[0]-1,0,scaley*dm[1]-1,0,0)\n s.AutoCropOutputOff()\n s.SetResliceTransform(r)\n if mirror: ip = vtk.vtkImageMirrorPad()\n elif wrap: ip = vtk.vtkImageWrapPad()\n else: ip = vtk.vtkImageConstantPad(); ip.SetConstant(constant)\n ip.SetOutputWholeExtent(0-maxdx,dm[0]-1+maxdx,0-maxdy,dm[1]-1+maxdy,0,0)\n ip.SetInputData(i)\n ip.Update()\n s.SetInputData(ip.GetOutput())\n o=s.GetOutput()\n s.Update()\n if numret: ri = VTKImageToNum(o)\n else: ri = o\n return ri\n\ndef VTKConvolve(im,numret=0,k=5,clip=1,x=1,y=1,wrap=0,mirror=1,constant=None,\n kernel=None):\n if type(im) == np.ndarray: i = NumToVTKImage(im)\n else: i = im\n d = i.GetDimensions()\n e = i.GetExtent()\n dtest = np.sort(d)\n if sum(dtest[:2]) == 2: onedim=1\n else: onedim = 0\n if (d[0] == 1): oned = 1\n elif (d[1] == 1): oned = 2\n else: oned = 0\n if x and not y: oned = 2\n if y and not x: oned = 1\n if onedim: oned = 1\n if constant is not None:\n ip = vtk.vtkImageConstantPad()\n if d[0] > 1: x0,x1=-k,d[0]+k-1\n else: x0,x1=0,0\n if d[1] > 1: y0,y1=-k,d[1]+k-1\n else: y0,y1=0,0\n ip.SetOutputWholeExtent(x0,x1,y0,y1,0,0)\n ip.SetConstant(constant)\n ip.SetInputData(i)\n i = ip.GetOutput()\n ip.Update()\n elif mirror:\n ip = vtk.vtkImageMirrorPad()\n if d[0] > 1: x0,x1=-k,d[0]+k-1\n else: x0,x1=0,0\n if d[1] > 1: y0,y1=-k,d[1]+k-1\n else: y0,y1=0,0\n ip.SetOutputWholeExtent(x0,x1,y0,y1,0,0)\n ip.SetInputData(i)\n i = ip.GetOutput()\n ip.Update()\n elif wrap:\n ip = vtk.vtkImageWrapPad()\n if d[0] > 1: x0,x1=-k,d[0]+k-1\n else: x0,x1=0,0\n if d[1] > 1: y0,y1=-k,d[1]+k-1\n else: y0,y1=0,0\n ip.SetOutputWholeExtent(x0,x1,y0,y1,0,0)\n ip.SetInputData(i)\n i = ip.GetOutput()\n ip.Update()\n c = vtk.vtkImageConvolve()\n if kernel is None:\n if k == 3: k1 = np.asarray([0.25,0.5,0.25])\n elif k == 5: k1 = np.asarray([0.0625,0.25,0.375,0.25,0.0625])\n if onedim: ke = np.ones((k,k),np.float64) * k1\n elif not oned: ke = k1[::,np.newaxis]*k1[np.newaxis,::]\n elif oned == 1: ke = np.zeros((k,k),np.float64); ke[::,2] = k1\n elif oned == 2: ke = np.zeros((k,k),np.float64); ke[2] = k1\n ke = np.ravel(ke)\n ke = ke / np.sum(ke)\n if onedim: ke = len(k1)*ke\n else:\n k = kernel.shape[0]\n ke = np.ravel(kernel)\n if k == 3: c.SetKernel3x3(ke)\n if k == 5: c.SetKernel5x5(ke)\n if k == 7: c.SetKernel7x7(ke)\n c.SetInputData(i)\n o = c.GetOutput()\n c.Update()\n if clip:\n ic = vtk.vtkImageClip()\n notx = -(not x) * 0\n noty = -(not y) * 0\n ic.SetOutputWholeExtent(notx,d[0]-1+notx,noty,d[1]-1+noty,0,0)\n ic.SetInputData(o)\n ic.ClipDataOn()\n o = ic.GetOutput()\n ic.Update()\n if numret: return VTKImageToNum(o)\n else: return o\n\ndef VTKGauss(x,sigma=5,numret=1,radius=3,sigmax=None,sigmay=None):\n if type(x) == np.ndarray: i = NumToVTKImage(x)\n else: i = x\n if sigmax is None: sigmax=sigma\n if sigmay is None: sigmay=sigma\n d = vtk.vtkImageGaussianSmooth()\n d.SetStandardDeviations(sigmax,sigmay,0)\n d.SetRadiusFactors(radius,radius,1)\n d.SetInputData(i)\n o = d.GetOutput()\n d.Update()\n if numret: return VTKImageToNum(o)\n else: return o\n\ndef VTKDilate(x,k=5,l=None,numret=0):\n if type(x) == np.ndarray: i = NumToVTKImage(x)\n else: i = x\n if l is None: l = k\n d = vtk.vtkImageContinuousDilate3D()\n d.SetKernelSize(k,l,1)\n d.SetInputData(i)\n o = d.GetOutput()\n d.Update()\n if numret: return VTKImageToNum(o)\n else: return o\n\ndef VTKAbs(x1):\n if type(x1) == np.ndarray: i1 = NumToVTKImage(x1)\n else: i1 = x1\n m = vtk.vtkImageMathematics()\n m.SetOperationToAbsoluteValue()\n m.AddInputData(i1)\n o = m.GetOutput()\n m.Update()\n return VTKImageToNum(o)\n\n\ndef VTKSqrt(x0,rep=0.0):\n bad = np.less(x0,0)\n x1 = VTKAbs(x0)\n if type(x1) == np.ndarray: i1 = NumToVTKImage(x1)\n else: i1 = x1\n m = vtk.vtkImageMathematics()\n m.SetOperationToSquareRoot()\n m.AddInputData(i1)\n o = m.GetOutput()\n m.Update()\n b = VTKImageToNum(o)\n return np.where(bad,rep,b)\n\ndef VTKInvert(x1,rep=0.0):\n if type(x1) == np.ndarray: i1 = NumToVTKImage(x1)\n else: i1 = x1\n m = vtk.vtkImageMathematics()\n m.SetOperationToInvert()\n m.AddInputData(i1)\n m.SetConstantC(rep)\n m.DivideByZeroToCOn()\n o = m.GetOutput()\n m.Update()\n return VTKImageToNum(o)\n\n\ndef VTKIslandRemoval(x,isval,repval,area,numret=0):\n if type(x) == np.ndarray: i = NumToVTKImage(x)\n else: i = x\n d = vtk.vtkImageIslandRemoval2D()\n d.SetIslandValue(isval)\n d.SetReplaceValue(repval)\n d.SetAreaThreshold(area)\n d.SquareNeighborhoodOn()\n d.SetInputData(i)\n o = d.GetOutput()\n d.Update()\n if numret: return VTKImageToNum(o)\n else: return o\n\n\ndef VTKGreaterEqual(x1,th):\n if type(x1) == np.ndarray: i1 = NumToVTKImage(x1)\n else: i1 = x1\n m = vtk.vtkImageThreshold()\n m.ThresholdByUpper(th)\n m.SetInputData(i1)\n m.ReplaceInOn()\n m.ReplaceOutOn()\n m.SetInValue(1.0)\n m.SetOutValue(0.0)\n m.SetOutputScalarTypeToFloat()\n o = m.GetOutput()\n m.Update()\n return VTKImageToNum(o)\n\ndef VTKLessEqual(x1,th):\n if type(x1) == np.ndarray: i1 = NumToVTKImage(x1)\n else: i1 = x1\n m = vtk.vtkImageThreshold()\n m.ThresholdByLower(th)\n m.SetInputData(i1)\n m.ReplaceInOn()\n m.ReplaceOutOn()\n m.SetInValue(1.0)\n m.SetOutValue(0.0)\n m.SetOutputScalarTypeToFloat()\n o = m.GetOutput()\n m.Update()\n return VTKImageToNum(o)\n\ndef VTKBetween(x1,th1,th2):\n if type(x1) == np.ndarray: i1 = NumToVTKImage(x1)\n else: i1 = x1\n m = vtk.vtkImageThreshold()\n m.ThresholdBetween(th1,th2)\n m.SetInputData(i1)\n m.ReplaceInOn()\n m.ReplaceOutOn()\n m.SetInValue(1.0)\n m.SetOutValue(0.0)\n m.SetOutputScalarTypeToFloat()\n o = m.GetOutput()\n m.Update()\n return VTKImageToNum(o)\n\n"
]
| [
[
"numpy.multiply.reduce",
"numpy.sum",
"numpy.asarray",
"numpy.less",
"numpy.squeeze",
"numpy.arange",
"numpy.ndarray.flatten",
"numpy.sort",
"numpy.ones",
"numpy.ravel",
"numpy.zeros",
"numpy.where"
]
]
|
algoix/blog | [
"91adfe1f526f0ebd41febe469f114871555e3c02",
"91adfe1f526f0ebd41febe469f114871555e3c02"
]
| [
"resource 1/join.py",
"resource 1/plotdata.py"
]
| [
"import pandas as pd\n\n\ndef test_run():\n # Define test range\n start_date = '2015-01-01'\n end_date = '2015-01-31'\n dates = pd.date_range(start_date, end_date)\n\n # Create an empty dataframe\n df1 = pd.DataFrame(index=dates)\n\n # Read SPY data into temporary dataframe\n dfSPY = pd.read_csv(\"../data/SPY.csv\", index_col=\"Date\",\n parse_dates=True, usecols=['Date', 'Adj Close'],\n na_values=['nan'])\n # Rename 'Adj Close' column to 'SPY' to prevent clash\n dfSPY = dfSPY.rename(columns={'Adj Close': 'SPY'})\n # Join the two dataframes using DataFrame.join(), with how='inner'\n df1 = df1.join(dfSPY, how='inner')\n\n # Read in more stocks\n symbols = ['AAPL', 'IBM']\n for symbol in symbols:\n df_temp = pd.read_csv(\"../data/{}.csv\".format(symbol), index_col=\"Date\",\n parse_dates=True, usecols=['Date', 'Adj Close'],\n na_values=['nan'])\n # rename to prevent clash\n df_temp = df_temp.rename(columns={'Adj Close': symbol})\n df1 = df1.join(df_temp) # use default how='left'\n\n # Reverse order of rows\n df1 = df1.iloc[::-1]\n print(df1)\n\n\nif __name__ == \"__main__\":\n test_run()\n",
"import pandas as pd\nimport matplotlib.pyplot as plt\n\n\ndef test_run():\n df = pd.read_csv(\"../data/AAPL.csv\")\n print(df['Adj Close'])\n df['Adj Close'].plot()\n plt.show()\n\n\nif __name__ == \"__main__\":\n test_run()\n"
]
| [
[
"pandas.read_csv",
"pandas.DataFrame",
"pandas.date_range"
],
[
"pandas.read_csv",
"matplotlib.pyplot.show"
]
]
|
szussman/strikeouts | [
"afe6be07a49e8e2c0450e505af0ebbef8bede710"
]
| [
"strikeouts.py"
]
| [
"import numpy as np\nimport pandas as pd\nfrom bokeh.plotting import figure, output_file, show\nimport bokeh.models.tickers as tickers\nfrom bokeh.models import NumeralTickFormatter\n\noutput_file(\"so.html\")\n\nfilename = \"/Users/stuartzussman/Desktop/baseballdatabank-master/core/Teams.csv\"\nstarting_df = pd.read_csv(filename)\n\n# look at only years after 1910\ndf = starting_df[(starting_df.yearID>1910)]\n\n# for years before HBP were recorded and the field is thus empty\ndf['HBP']=df['HBP'].fillna(0) \n\n# approximation of PA, ignoring catcher interference\ndf['PA'] = df['AB'] + df['BB'] + df['HBP']\n\n# create series that include year and the respective statistic\nso = df.groupby('yearID')['SO'].sum()\nbb = df.groupby('yearID')['BB'].sum()\npa = df.groupby('yearID')['PA'].sum()\n\nbbs, sm, yrs = bb.values, so.values, so.index\n\nso_pct = []\nbb_pct=[]\n\nfor yr in yrs:\n so_sum = df[df[\"yearID\"]==yr][\"SO\"].sum()\n pa_sum = df[df[\"yearID\"]==yr][\"PA\"].sum()\n bb_sum = df[df[\"yearID\"]==yr][\"BB\"].sum()\n so_pct.append(so_sum/pa_sum)\n bb_pct.append(bb_sum/pa_sum)\n \n# plot the data\np = figure(plot_width=1200, plot_height=600,title=\"Outcomes per Plate Appearance by Year\", x_axis_label='Year', y_axis_label='% of PA')\np.title.align = 'center'\np.line(x=yrs,y=so_pct,line_width=2, line_color='red')\np.line(x=yrs,y=bb_pct,line_width=2, line_color='green')\n\np.yaxis[0].formatter = NumeralTickFormatter(format=\"0%\")\np.circle(x=yrs,y=so_pct, legend=\"K/PA\", line_width=2, fill_color='red',line_color=\"red\", size=6)\np.circle(x=yrs,y=bb_pct, legend=\"BB/PA\", line_width=2, fill_color='green',line_color=\"green\", size=6)\np.xgrid.ticker = tickers.FixedTicker(ticks=np.arange(1910, 2030, 10))\np.xaxis.ticker = tickers.FixedTicker(ticks=np.arange(1910, 2030, 10))\n\np.xaxis.major_label_text_font_size = \"16pt\"\np.legend.location = \"bottom_center\"\nshow(p)\n"
]
| [
[
"numpy.arange",
"pandas.read_csv"
]
]
|
metang/MLProj1 | [
"3964a1e75bb31b5ce9d043dcdc626e3285821cd8"
]
| [
"src/run_pretraining_ort.py"
]
| [
"# coding=utf-8\n# Copyright (c) 2019 NVIDIA CORPORATION. All rights reserved.\n# Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. 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.\n\n\"\"\"BERT finetuning runner.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n# ==================\nimport csv\nimport os\nimport sys\nimport time\nimport argparse\nimport random\nimport h5py\nfrom tqdm import tqdm, trange\nimport os\nimport numpy as np\nimport torch\nimport torch.distributed as dist\nfrom torch.utils.tensorboard import SummaryWriter\nfrom torch.utils.data import DataLoader, RandomSampler, SequentialSampler, Dataset\nimport math\nimport multiprocessing\nimport modeling\nimport shutil\n\nfrom utils import format_step\nfrom datetime import datetime\n\nfrom watchdog.observers import Observer\nfrom watchdog.events import FileSystemEventHandler\nDIRECTORY_TO_WATCH = \"/usr/share\"\n\nfrom multiprocessing import Value\nfrom ctypes import c_bool\n\nclass PreemptHandler(FileSystemEventHandler):\n def __init__(self):\n super(PreemptHandler, self).__init__()\n self.is_preempted = Value(c_bool, False)\n\n def on_any_event(self, event):\n if not event.is_directory and event.src_path.endswith(\"/to-be-preempted\"):\n print(datetime.utcnow(),\"Detected Preempt Signal, should stop and return.\")\n self.is_preempted.value = True\n\nclass PreemptDetector:\n def __init__(self):\n self.observer = Observer()\n self.event_handler = PreemptHandler()\n\n def run(self):\n self.observer.schedule(self.event_handler, DIRECTORY_TO_WATCH, recursive=False)\n self.observer.start()\n\n def is_preempted(self):\n return self.event_handler.is_preempted.value\n\n def stop(self):\n self.observer.stop()\n\n# replace routine from utils.py as we dont use torch.distributed\ndef is_main_process(args):\n if hasattr(args, 'world_rank'):\n return args.world_rank == 0\n if dist.is_available() and dist.is_initialized():\n return dist.get_rank() == 0\n return True\n\nimport dllogger\nfrom concurrent.futures import ProcessPoolExecutor\n\ntorch._C._jit_set_profiling_mode(False)\ntorch._C._jit_set_profiling_executor(False)\n\nskipped_steps = 0\n\nimport onnx\n\n#Workaround because python functions are not picklable\nclass WorkerInitObj(object):\n def __init__(self, seed):\n self.seed = seed\n def __call__(self, id):\n np.random.seed(seed=self.seed + id)\n random.seed(self.seed + id)\n\ndef create_pretraining_dataset(input_file, max_pred_length, shared_list, args, worker_init):\n train_data = pretraining_dataset(input_file=input_file, max_pred_length=max_pred_length)\n train_sampler = RandomSampler(train_data)\n # --- ort training edit: we need to skip last batch when hard coding inputs as an optimization\n train_dataloader = DataLoader(train_data, sampler=train_sampler,\n batch_size=args.train_batch_size * args.n_gpu, \n num_workers=4, worker_init_fn=worker_init,\n pin_memory=True, drop_last=True)\n # ---\n return train_dataloader, input_file\n\nclass pretraining_dataset(Dataset):\n\n def __init__(self, input_file, max_pred_length):\n self.input_file = input_file\n self.max_pred_length = max_pred_length\n f = h5py.File(input_file, \"r\")\n keys = ['input_ids', 'input_mask', 'segment_ids', 'masked_lm_positions', 'masked_lm_ids',\n 'next_sentence_labels']\n self.inputs = [np.asarray(f[key][:]) for key in keys]\n f.close()\n\n def __len__(self):\n 'Denotes the total number of samples'\n return len(self.inputs[0])\n\n def __getitem__(self, index):\n\n [input_ids, input_mask, segment_ids, masked_lm_positions, masked_lm_ids, next_sentence_labels] = [\n torch.from_numpy(input[index].astype(np.int64)) if indice < 5 else torch.from_numpy(\n np.asarray(input[index].astype(np.int64))) for indice, input in enumerate(self.inputs)]\n\n masked_lm_labels = torch.ones(input_ids.shape, dtype=torch.long) * -1\n index = self.max_pred_length\n # store number of masked tokens in index\n padded_mask_indices = (masked_lm_positions == 0).nonzero()\n if len(padded_mask_indices) != 0:\n index = padded_mask_indices[0].item()\n masked_lm_labels[masked_lm_positions[:index]] = masked_lm_ids[:index]\n\n return [input_ids, segment_ids, input_mask,\n masked_lm_labels, next_sentence_labels]\nclass BertPretrainingCriterion(torch.nn.Module):\n def __init__(self, vocab_size, batch_size, seq_length):\n super(BertPretrainingCriterion, self).__init__()\n self.loss_fn = torch.nn.CrossEntropyLoss(ignore_index=-1)\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.vocab_size = vocab_size\n def forward(self, prediction_scores, seq_relationship_score, masked_lm_labels, next_sentence_labels):\n print(\"BertPretrainingCriterion: batch_size: \",self.batch_size, \", self.seq_length:\", self.seq_length )\n masked_lm_loss = self.loss_fn(prediction_scores.view([self.batch_size * self.seq_length, self.vocab_size]), masked_lm_labels.view(self.batch_size * self.seq_length))\n next_sentence_loss = self.loss_fn(seq_relationship_score, next_sentence_labels.view(self.batch_size))\n total_loss = masked_lm_loss + next_sentence_loss\n return total_loss\n\n# we manually add the loss function into the bert model\n# currently ort front end support for this assumes a single tensor input for labels\nclass bert_model_with_loss(torch.nn.Module):\n def __init__(self, model, loss_fn):\n super(bert_model_with_loss, self).__init__()\n self.model_ = model\n self.loss_fn_ = loss_fn\n\n def forward(self, input_ids, segment_ids, input_mask, masked_lm_labels, next_sentence_labels):\n preds_score, seq_relation_score = self.model_(input_ids, segment_ids, input_mask)\n return self.loss_fn_(preds_score, seq_relation_score, masked_lm_labels, next_sentence_labels)\n\ndef parse_arguments():\n\n parser = argparse.ArgumentParser()\n\n ## Required parameters\n parser.add_argument(\"--input_dir\",\n default=None,\n type=str,\n required=True,\n help=\"The input data dir. Should contain .hdf5 files for the task.\")\n\n parser.add_argument(\"--config_file\",\n default=None,\n type=str,\n required=True,\n help=\"The BERT model config\")\n\n parser.add_argument(\"--bert_model\", default=\"bert-large-uncased\", type=str,\n help=\"Bert pre-trained model selected in the list: bert-base-uncased, \"\n \"bert-large-uncased, bert-base-cased, bert-base-multilingual, bert-base-chinese.\")\n\n parser.add_argument(\"--output_dir\",\n default=None,\n type=str,\n required=True,\n help=\"The output directory where the model checkpoints will be written.\")\n\n ## Other parameters\n parser.add_argument(\"--init_checkpoint\",\n default=None,\n type=str,\n help=\"The initial checkpoint to start training from.\")\n\n parser.add_argument(\"--max_seq_length\",\n default=512,\n type=int,\n help=\"The maximum total input sequence length after WordPiece tokenization. \\n\"\n \"Sequences longer than this will be truncated, and sequences shorter \\n\"\n \"than this will be padded.\")\n parser.add_argument(\"--max_predictions_per_seq\",\n default=80,\n type=int,\n help=\"The maximum total of masked tokens in input sequence\")\n parser.add_argument(\"--train_batch_size\",\n default=32,\n type=int,\n help=\"Per GPU batch size for training.\")\n parser.add_argument(\"--learning_rate\",\n default=5e-5,\n type=float,\n help=\"The initial learning rate for Adam.\")\n parser.add_argument(\"--num_train_epochs\",\n default=3.0,\n type=float,\n help=\"Total number of training epochs to perform.\")\n parser.add_argument(\"--max_steps\",\n default=1000,\n type=float,\n help=\"Total number of training steps to perform.\")\n parser.add_argument(\"--warmup_proportion\",\n default=0.01,\n type=float,\n help=\"Proportion of training to perform linear learning rate warmup for. \"\n \"E.g., 0.1 = 10%% of training.\")\n parser.add_argument(\"--local_rank\",\n type=int,\n default=-1,\n help=\"local_rank for distributed training on gpus\")\n parser.add_argument('--seed',\n type=int,\n default=42,\n help=\"random seed for initialization\")\n parser.add_argument('--fp16',\n default=False,\n action='store_true',\n help=\"Whether to use 16-bit float precision instead of 32-bit\")\n parser.add_argument('--loss_scale',\n type=float, default=0.0,\n help='Loss scaling, positive power of 2 values can improve fp16 convergence.')\n parser.add_argument('--log_freq',\n type=float, default=1.0,\n help='frequency of logging loss.')\n parser.add_argument('--checkpoint_activations',\n default=False,\n action='store_true',\n help=\"Whether to use gradient checkpointing\")\n parser.add_argument(\"--resume_from_checkpoint\",\n default=True,\n action='store_true',\n help=\"Whether to resume training from checkpoint.\")\n parser.add_argument('--resume_step',\n type=int,\n default=-1,\n help=\"Step to resume training from.\")\n parser.add_argument('--num_steps_per_checkpoint',\n type=int,\n default=100,\n help=\"Number of update steps until a model checkpoint is saved to disk.\")\n parser.add_argument('--skip_checkpoint',\n default=False,\n action='store_true',\n help=\"Whether to save checkpoints\")\n parser.add_argument('--phase2',\n default=False,\n action='store_true',\n help=\"Whether to train with seq len 512\")\n parser.add_argument('--allreduce_post_accumulation',\n default=False,\n action='store_true',\n help=\"Whether to do allreduces during gradient accumulation steps.\")\n parser.add_argument('--allreduce_post_accumulation_fp16',\n default=False,\n action='store_true',\n help=\"Whether to do fp16 allreduce post accumulation.\")\n parser.add_argument('--phase1_end_step',\n type=int,\n default=7038,\n help=\"Number of training steps in Phase1 - seq len 128\")\n parser.add_argument(\"--do_train\",\n default=False,\n action='store_true',\n help=\"Whether to run training.\")\n parser.add_argument('--json-summary', type=str, default=\"dllogger.json\",\n help='If provided, the json summary will be written to'\n 'the specified file.')\n parser.add_argument(\"--use_env\",\n action='store_true',\n help=\"Whether to read local rank from ENVVAR\")\n parser.add_argument('--disable_progress_bar',\n default=False,\n action='store_true',\n help='Disable tqdm progress bar')\n parser.add_argument('--use_ib',\n default=False,\n action='store_true',\n help=\"Whether to use infiniband on Azure ML submission.\")\n parser.add_argument('--partition_optimizer',\n default=False,\n action='store_true',\n help=\"Whether ORT will partition optimizer.\")\n parser.add_argument(\"--gpu_memory_limit_gb\",\n type=int,\n default=32,\n help=\"GPU memory limit in GBs\")\n parser.add_argument('--schedule',\n default='warmup_poly',\n type=str)\n parser.add_argument('--tensorboard_dir',\n default='./outputs',\n type=str)\n args = parser.parse_args()\n \n return args\n\ndef setup_training(args):\n\n assert (torch.cuda.is_available())\n\n global ort_supplement\n import ort_supplement.ort_supplement as ort_supplement\n device = ort_supplement.setup_onnxruntime_with_mpi(args)\n \n if is_main_process(args):\n dllogger.init(backends=[dllogger.JSONStreamBackend(verbosity=dllogger.Verbosity.VERBOSE,\n filename=args.json_summary),\n dllogger.StdOutBackend(verbosity=dllogger.Verbosity.VERBOSE, step_format=format_step)])\n else:\n dllogger.init(backends=[])\n\n print(\"device: {} n_gpu: {}, distributed training: {}, 16-bits training: {}, world size: {}\".format(\n device, args.n_gpu, bool(args.local_rank != -1), args.fp16, args.world_size))\n\n global_batch_size = 65536\n if args.phase2:\n global_batch_size = 32768\n\n args.gradient_accumulation_steps = int(round(global_batch_size / args.world_size / args.train_batch_size))\n print(\"real global batch size is \", args.train_batch_size * args.world_size * args.gradient_accumulation_steps,\n \", gradient_accumulation_steps: \", args.gradient_accumulation_steps)\n\n if args.gradient_accumulation_steps < 1:\n raise ValueError(\"Invalid gradient_accumulation_steps parameter: {}, should be >= 1\".format(\n args.gradient_accumulation_steps))\n\n if not args.do_train:\n raise ValueError(\" `do_train` must be True.\")\n\n if not args.resume_from_checkpoint and os.path.exists(args.output_dir) and (\n os.listdir(args.output_dir) and any([i.startswith('ckpt') for i in os.listdir(args.output_dir)])):\n raise ValueError(\"Output directory ({}) already exists and is not empty.\".format(args.output_dir))\n\n if (not args.resume_from_checkpoint or not os.path.exists(args.output_dir)) and is_main_process(args):\n os.makedirs(args.output_dir, exist_ok=True)\n\n return device, args\n\ndef prepare_model(args, device):\n\n # Prepare model\n config = modeling.BertConfig.from_json_file(args.config_file)\n\n # Padding for divisibility by 8\n if config.vocab_size % 8 != 0:\n config.vocab_size += 8 - (config.vocab_size % 8)\n\n model = modeling.BertForPreTraining(config)\n criterion = BertPretrainingCriterion(config.vocab_size, args.train_batch_size, args.max_seq_length)\n\n model.enable_apex(False)\n model = bert_model_with_loss(model, criterion)\n model = ort_supplement.create_ort_trainer(args, device, model)\n\n checkpoint = None\n if not args.resume_from_checkpoint or os.path.exists(args.output_dir) == False or len(os.listdir(args.output_dir)) == 0:\n global_step = 0\n else:\n if args.resume_step == -1 and not args.init_checkpoint:\n model_names = [f for f in os.listdir(args.output_dir) if f.endswith(\".pt\")]\n args.resume_step = max([int(x.split('.pt')[0].split('_')[1].strip()) for x in model_names])\n\n global_step = args.resume_step if not args.init_checkpoint else 0\n print(\"resume global_step: \", global_step)\n\n if not args.init_checkpoint:\n checkpoint = torch.load(os.path.join(args.output_dir, \"ckpt_{}.pt\".format(global_step)), map_location=\"cpu\")\n else:\n checkpoint = torch.load(args.init_checkpoint, map_location=\"cpu\")\n print(\"after load checkpoint: \", global_step)\n model.load_state_dict(checkpoint['model'], strict=False)\n\n print(\"after load checkpoint 2: \", global_step)\n if args.phase2 and not args.init_checkpoint:\n global_step -= args.phase1_end_step\n if is_main_process(args):\n print(\"resume step from \", args.resume_step)\n\n return model, checkpoint, global_step\n \ndef main():\n\n args = parse_arguments()\n\n if args.use_env and 'LOCAL_RANK' in os.environ:\n args.local_rank = int(os.environ['LOCAL_RANK'])\n \n random.seed(args.seed + args.local_rank)\n np.random.seed(args.seed + args.local_rank)\n torch.manual_seed(args.seed + args.local_rank)\n torch.cuda.manual_seed(args.seed + args.local_rank)\n worker_init = WorkerInitObj(args.seed + args.local_rank)\n\n device, args = setup_training(args)\n dllogger.log(step=\"PARAMETER\", data={\"Config\": [str(args)]})\n\n # Prepare optimizer\n model, checkpoint, global_step = prepare_model(args, device)\n\n if is_main_process(args):\n dllogger.log(step=\"PARAMETER\", data={\"SEED\": args.seed})\n writer = SummaryWriter(log_dir=args.tensorboard_dir)\n\n raw_train_start = time.time()\n if args.do_train:\n if is_main_process(args):\n dllogger.log(step=\"PARAMETER\", data={\"train_start\": True})\n dllogger.log(step=\"PARAMETER\", data={\"batch_size_per_gpu\": args.train_batch_size})\n dllogger.log(step=\"PARAMETER\", data={\"learning_rate\": args.learning_rate})\n\n model.train()\n most_recent_ckpts_paths = []\n average_loss = 0.0 # averaged loss every args.log_freq steps\n epoch = 0\n training_steps = 0\n\n pool = ProcessPoolExecutor(1)\n\n detector = PreemptDetector()\n detector.run()\n\n # Note: We loop infinitely over epochs, termination is handled via iteration count\n while True:\n thread = None\n if not args.resume_from_checkpoint or os.path.exists(args.output_dir) == False or len(os.listdir(args.output_dir)) == 0 or epoch > 0 or (args.phase2 and global_step < 1) or args.init_checkpoint:\n files = [os.path.join(args.input_dir, f) for f in os.listdir(args.input_dir) if\n os.path.isfile(os.path.join(args.input_dir, f)) and 'training' in f]\n files.sort()\n num_files = len(files)\n random.shuffle(files)\n #f_start_id = 0\n rank_0_file_id = 0\n else:\n #f_start_id = checkpoint['files'][0]\n files = checkpoint['files'][1:]\n rank_0_file_id = checkpoint['rank_0_file_id']\n args.resume_from_checkpoint = False\n num_files = len(files)\n\n print(\"rank_0_file_id is \", rank_0_file_id)\n\n shared_file_list = {}\n\n if torch.distributed.is_initialized():\n world_size = torch.distributed.get_world_size()\n world_rank = torch.distributed.get_rank()\n print(\"torch.distributed.is_initialized world_size: \", world_size)\n elif hasattr(args, 'world_size'):\n world_size = args.world_size\n world_rank = args.world_rank\n else:\n world_size = 1\n world_rank = 0\n\n if world_size > num_files:\n remainder = world_size % num_files\n #data_file = files[(f_start_id*world_size + world_rank + remainder*f_start_id)%num_files]\n data_file = files[(rank_0_file_id + world_rank)%num_files]\n elif world_size > 1:\n #data_file = files[(f_start_id*world_size + world_rank)%num_files]\n data_file = files[(rank_0_file_id + world_rank)%num_files]\n else:\n #data_file = files[f_start_id % num_files]\n data_file = files[rank_0_file_id % num_files]\n # ---\n\n previous_file = data_file\n\n train_data = pretraining_dataset(data_file, args.max_predictions_per_seq)\n train_sampler = RandomSampler(train_data)\n # we need to skip last batch when we hard code inputs as an optimization\n train_dataloader = DataLoader(train_data, sampler=train_sampler,\n batch_size=args.train_batch_size * args.n_gpu,\n num_workers=4, worker_init_fn=worker_init,\n pin_memory=True, drop_last=True)\n\n\n #if len(files) == 1:\n # f_start_id = -1\n rank0_f_id = rank_0_file_id \n while rank0_f_id < len(files):\n next_rank_0_f_id = rank0_f_id + world_size\n\n need_load_next = next_rank_0_f_id < len(files)\n if need_load_next:\n if world_size > num_files:\n data_file = files[(next_rank_0_f_id + world_rank)%num_files]\n elif world_size > 1:\n data_file = files[(next_rank_0_f_id + world_rank)%num_files]\n print(\"current worker use file id \", (next_rank_0_f_id + world_rank)%num_files)\n else:\n data_file = files[next_rank_0_f_id % num_files]\n\n previous_file = data_file\n\n dataset_future = pool.submit(create_pretraining_dataset, data_file, args.max_predictions_per_seq, shared_file_list, args, worker_init)\n\n train_iter = tqdm(train_dataloader, desc=\"Iteration\", disable=args.disable_progress_bar) if is_main_process(args) else train_dataloader\n prev_step_time = time.time()\n for step, batch in enumerate(train_iter):\n\n training_steps += 1\n batch = [t.to(device) for t in batch]\n input_ids, segment_ids, input_mask, masked_lm_labels, next_sentence_labels = batch\n divisor = args.gradient_accumulation_steps\n\n loss, global_step = ort_supplement.run_ort_training_step(args, global_step, training_steps, model, batch)\n average_loss += loss.item()\n\n if global_step >= args.max_steps:\n train_time_raw = time.time() - raw_train_start\n last_num_steps = int(training_steps / args.gradient_accumulation_steps) % args.log_freq\n last_num_steps = args.log_freq if last_num_steps == 0 else last_num_steps\n average_loss = torch.tensor(average_loss, dtype=torch.float32).cuda()\n average_loss = average_loss / (last_num_steps * divisor)\n if (torch.distributed.is_initialized()):\n average_loss /= torch.distributed.get_world_size()\n torch.distributed.all_reduce(average_loss)\n final_loss = average_loss.item()\n if is_main_process(args):\n dllogger.log(step=(epoch, global_step, ), data={\"final_loss\": final_loss})\n elif training_steps % (args.log_freq * args.gradient_accumulation_steps) == 0:\n throughput = (args.train_batch_size * args.gradient_accumulation_steps) / (time.time() - prev_step_time)\n print('throughput = ', throughput ,'seq/sec')\n prev_step_time = time.time()\n sys.stdout.flush()\n\n if is_main_process(args):\n data = {\"average_loss\": average_loss / (args.log_freq * divisor),\n \"step_loss\": loss.item() * args.gradient_accumulation_steps / divisor}\n dllogger.log(step=(epoch, global_step,), data=data)\n writer.add_scalar('train/summary/scalar/total_loss', average_loss / (args.log_freq * divisor),\n global_step + args.phase1_end_step if args.resume_step >= 0 and args.phase2 else global_step)\n writer.add_scalar('train/summary/scalar/world_size', world_size,\n global_step + args.phase1_end_step if args.resume_step >= 0 and args.phase2 else global_step)\n writer.add_scalar('train/summary/scalar/throughput', throughput,\n global_step + args.phase1_end_step if args.resume_step >= 0 and args.phase2 else global_step)\n writer.flush()\n\n average_loss = 0\n\n if is_main_process(args):\n print(datetime.utcnow(), \"training loop is_preempted: \", detector.is_preempted())\n if global_step >= args.max_steps or training_steps % (\n args.num_steps_per_checkpoint*args.gradient_accumulation_steps) == 0 or detector.is_preempted():\n if detector.is_preempted() and is_main_process(args):\n print(datetime.utcnow(), \"is_preempted: \", detector.is_preempted(), \" global_step: \", global_step)\n\n if is_main_process(args) and not args.skip_checkpoint:\n # Save a trained model\n dllogger.log(step=\"PARAMETER\", data={\"checkpoint_step\": global_step})\n model_to_save = model.module if hasattr(model,\n 'module') else model # Only save the model it-self\n if args.resume_step < 0 or not args.phase2:\n # output_save_file = os.path.join(args.output_dir, \"ckpt_{}.pt\".format(global_step))\n file_name = \"ckpt_{}.pt\".format(global_step)\n else:\n # output_save_file = os.path.join(args.output_dir, \"ckpt_{}.pt\".format(global_step + args.phase1_end_step))\n file_name = \"ckpt_{}.pt\".format(global_step + args.phase1_end_step)\n if args.do_train:\n output_save_file_tmp = os.path.join('/tmp/', file_name)\n output_save_file_blob = os.path.join(args.output_dir, file_name)\n\n if detector.is_preempted():\n to_save = rank0_f_id\n else:\n if need_load_next:\n to_save = next_rank_0_f_id\n else:\n to_save = 0\n\n state = {'model': model_to_save.state_dict(),\n 'files': [-1] + files,\n 'rank_0_file_id': to_save}\n # torch.save(state, output_save_file)\n\n start_time = time.time()\n torch.save(state, output_save_file_tmp)\n elapsed_time = time.time() - start_time\n print(\"save checkpoint time on local /tmp \", elapsed_time, \", rank0_f_id:\", to_save)\n start_time = time.time()\n shutil.copyfile(output_save_file_tmp, output_save_file_blob)\n elapsed_time = time.time() - start_time\n print(\"save checkpoint time (copy to blob) \", elapsed_time)\n print(\"output_save_file_blob: \", output_save_file_blob)\n most_recent_ckpts_paths.append(output_save_file_blob)\n\n\n # most_recent_ckpts_paths.append(output_save_file)\n if len(most_recent_ckpts_paths) > 3:\n ckpt_to_be_removed = most_recent_ckpts_paths.pop(0)\n os.remove(ckpt_to_be_removed)\n\n if global_step >= args.max_steps or detector.is_preempted():\n if is_main_process(args):\n if detector.is_preempted():\n print(datetime.utcnow(), \"is_preempted: \", detector.is_preempted(), \" save onnx model\")\n print('-----------------------save onnx model-----------------------')\n if not args.phase2:\n # model_to_save.save_as_onnx('{}/phase1_bert.onnx'.format(args.output_dir))\n start_time = time.time()\n model_to_save.save_as_onnx('/tmp/phase1_bert.onnx')\n elapsed_time = time.time() - start_time\n print(\"save onnx model on local /tmp\", elapsed_time, \" global_step \", global_step)\n start_time = time.time()\n shutil.copyfile('/tmp/phase1_bert.onnx', '{}/phase1_bert.onnx'.format(args.output_dir))\n elapsed_time = time.time() - start_time\n print(\"save onnx model time (copy to blob) \", elapsed_time, \" global_step \", global_step)\n else:\n # model_to_save.save_as_onnx('{}/final_bert.onnx'.format(args.output_dir))\n start_time = time.time()\n model_to_save.save_as_onnx('/tmp/final_bert.onnx')\n elapsed_time = time.time() - start_time\n print(\"save onnx model on local /tmp\", elapsed_time, \" global_step \", global_step)\n start_time = time.time()\n shutil.copyfile('/tmp/final_bert.onnx', '{}/final_bert.onnx'.format(args.output_dir))\n elapsed_time = time.time() - start_time\n print(\"save onnx model time (copy to blob) \", elapsed_time, \" global_step \", global_step)\n del train_dataloader\n # thread.join()\n if detector.is_preempted():\n print(\"exit training main function after preemption\")\n return args, 0, time.time() - raw_train_start\n return args, final_loss, train_time_raw\n\n del train_dataloader\n # thread.join()\n # Make sure pool has finished and switch train_dataloader\n # NOTE: Will block until complete\n if need_load_next:\n train_dataloader, data_file = dataset_future.result(timeout=None)\n rank0_f_id = next_rank_0_f_id\n epoch += 1\n detector.stop()\n writer.close()\n\n\nif __name__ == \"__main__\":\n print(\"======================in run_pretraining_ort.py==================\")\n now = time.time()\n args, final_loss, train_time_raw = main()\n gpu_count = args.n_gpu\n args.max_steps += args.phase1_end_step if (args.phase2 and args.resume_step > 0) else 0\n if args.resume_step == -1:\n args.resume_step = 0\n if torch.distributed.is_initialized():\n gpu_count = torch.distributed.get_world_size()\n if is_main_process(args):\n e2e_time = time.time() - now\n training_perf = args.train_batch_size * args.gradient_accumulation_steps * gpu_count\\\n * (args.max_steps - args.resume_step + skipped_steps) / train_time_raw\n dllogger.log(step=tuple(), data={\"e2e_train_time\": e2e_time, \"training_sequences_per_second\": training_perf,\n \"final_loss\": final_loss, \"raw_train_time\": train_time_raw })\n print(\"exit training program\")\n dllogger.flush()\n\n"
]
| [
[
"torch.load",
"numpy.asarray",
"torch._C._jit_set_profiling_mode",
"torch.utils.data.DataLoader",
"torch.utils.tensorboard.SummaryWriter",
"torch.cuda.is_available",
"torch.distributed.get_rank",
"torch.save",
"torch.nn.CrossEntropyLoss",
"torch.ones",
"torch.tensor",
"torch.distributed.is_initialized",
"torch.distributed.is_available",
"torch.distributed.get_world_size",
"torch._C._jit_set_profiling_executor",
"numpy.random.seed",
"torch.cuda.manual_seed",
"torch.manual_seed",
"torch.utils.data.RandomSampler",
"torch.distributed.all_reduce"
]
]
|
ostrokach/protein-adjacency-net | [
"fd3ad0b9034eb61b0187752c1f38f7eed1a8f1dc"
]
| [
"src/pagnn/training/dcn/main.py"
]
| [
"import itertools\nimport json\nimport logging\nimport os\nimport random\nimport runpy\nimport time\nfrom typing import Any, Dict, Optional, Union\n\nimport numpy as np\nimport sqlalchemy as sa\nimport torch\nimport torch.nn as nn\nimport torch.onnx\nimport torch.optim as optim\n\nimport pagnn.models\nfrom pagnn import init_gpu, settings\nfrom pagnn.utils import eval_net, kill_tree\n\nfrom .args import Args\nfrom .stats import Stats\nfrom .utils import get_data_pipe, get_internal_validation_datasets, get_training_datasets\n\nlogger = logging.getLogger(__name__)\n\n\nclass DatasetFinishedError(Exception):\n pass\n\n\nclass RuntimeExceededError(Exception):\n pass\n\n\ndef train(\n args: Args,\n stats: Stats,\n datapipe,\n internal_validation_datasets,\n engine: Optional[sa.engine.Engine] = None,\n checkpoint: Optional[Dict[str, Any]] = None,\n current_performance: Optional[Dict[str, Union[str, float]]] = None,\n):\n \"\"\"Train GAN network.\"\"\"\n if checkpoint is None:\n checkpoint = {}\n\n # Set up network\n Net = getattr(pagnn.models.dcn, args.network_name)\n net = Net().to(settings.device)\n\n ds_weight = torch.tensor(\n [1.0] + [1.0 / args.num_negative_examples] * args.num_negative_examples\n )\n if args.predict_pc_identity:\n loss = nn.L1Loss(reduction=\"none\").to(settings.device)\n else:\n loss = nn.BCELoss(reduction=\"none\").to(settings.device)\n\n optimizer = optim.Adam(net.parameters(), lr=args.learning_rate, betas=(args.beta1, args.beta2))\n\n if args.array_id:\n net.load_state_dict(stats.load_model_state())\n write_graph = False\n elif args.model_path is not None:\n net.load_state_dict(torch.load(args.model_path))\n write_graph = False\n else:\n write_graph = True\n\n while True:\n current_time = time.perf_counter()\n\n if (current_time - stats.start_time) > args.runtime:\n raise RuntimeExceededError(\n f\"Runtime exceeded! ({(current_time - stats.start_time)} > {args.runtime})\"\n )\n calculate_basic_statistics = (\n stats.validation_time_basic == 0\n or (current_time - stats.validation_time_basic) > args.time_between_checkpoints\n )\n calculate_extended_statistics = calculate_basic_statistics and (\n stats.validation_time_extended == 0\n or (current_time - stats.validation_time_extended)\n > args.time_between_extended_checkpoints\n )\n\n # === Train discriminator ===\n net.zero_grad()\n\n ds_list = list(itertools.islice(datapipe, args.batch_size))\n if not ds_list:\n raise DatasetFinishedError()\n\n pred_list = []\n target_list = []\n error_list = []\n for ds in ds_list:\n dv = net.dataset_to_datavar(ds)\n pred = net(dv.seqs, [dv.adjs])\n pred = pred.sigmoid().mean(2).squeeze()\n error = (loss(pred, ds.targets) * ds_weight).sum()\n error.backward()\n pred_list.append(pred.detach())\n target_list.append(ds.targets.detach())\n error_list.append(error.detach())\n preds = torch.cat(pred_list)\n targets = torch.cat(target_list)\n errors = torch.stack(error_list)\n optimizer.step()\n\n # === Calculate Statistics ===\n if write_graph:\n # Commented out because causes errors:\n # > ** ValueError: Auto nesting doesn't know how to process an input object of type int.\n # > Accepted types: Tensors, or lists/tuples of them.\n # > ** RuntimeError: sparse tensors not supported.\n # dv = net.dataset_to_datavar(ds_list[0])\n # torch.onnx.export(\n # net, (dv.seqs, [dv.adjs]), args.root_path.joinpath(\"model.onnx\").as_posix()\n # )\n write_graph = False\n\n if calculate_basic_statistics:\n logger.debug(\"Calculating basic statistics...\")\n\n stats.preds.append(preds.numpy())\n stats.targets.append(targets.numpy())\n stats.losses.append(errors.numpy())\n\n with torch.no_grad(), eval_net(net):\n stats.calculate_statistics_basic()\n\n if calculate_extended_statistics:\n logger.debug(\"Calculating extended statistics...\")\n\n with torch.no_grad(), eval_net(net):\n stats.calculate_statistics_extended(net, internal_validation_datasets)\n\n stats.dump_model_state(net)\n\n if calculate_basic_statistics or calculate_extended_statistics:\n stats.write_row()\n if current_performance is not None:\n current_performance.update(stats.scores)\n\n stats.update()\n\n\ndef main(args: Optional[Args] = None):\n # === Arguments ===\n if args is None:\n args = Args.from_cli()\n\n logging_level = {0: logging.ERROR, 1: logging.INFO, 2: logging.DEBUG}[args.verbosity]\n logging.basicConfig(format=\"%(message)s\", level=logging_level)\n\n logger.info(\"Started training network with args: %s\", args.to_dict())\n\n if args.custom_module:\n runpy.run_path(args.custom_module.as_posix(), globals())\n\n if args.gpu == -1:\n settings.device = torch.device(\"cpu\")\n logger.info(\"Running on the CPU.\")\n else:\n init_gpu(args.gpu)\n\n # === Stats ===\n db_path = args.root_path.joinpath(\"stats.db\")\n engine = sa.create_engine(f\"sqlite:///{db_path}\")\n stats = Stats(engine, args)\n\n # === Random Seed ===\n random.seed(stats.step)\n np.random.seed(stats.step)\n torch.manual_seed(stats.step)\n torch.cuda.manual_seed(stats.step)\n\n # === Internal Validation Dataset ===\n logger.debug(\"Initializing validation dataset...\")\n internal_validation_datasets = get_internal_validation_datasets(args)\n\n # === Training Dataset ===\n logger.debug(\"Initializing training dataset...\")\n if True:\n datapipe = get_data_pipe(args)\n else:\n datapipe = get_training_datasets(args)\n\n # === Train ===\n logger.debug(\"Training the network...\")\n start_time = time.perf_counter()\n pid = os.getpid()\n result: Dict[str, Union[str, float]] = {}\n\n try:\n train(args, stats, datapipe, internal_validation_datasets, current_performance=result)\n except (KeyboardInterrupt, RuntimeExceededError, DatasetFinishedError) as e:\n kill_tree(pid)\n logger.error(\"Training terminated with error '%s': '%s'\", type(e), e)\n except Exception as e:\n kill_tree(pid)\n logger.error(\"Training terminated with error '%s': '%s'\", type(e), e)\n raise\n finally:\n result[\"time_elapsed\"] = time.perf_counter() - start_time\n print(json.dumps(result, sort_keys=True, indent=4))\n"
]
| [
[
"torch.cuda.manual_seed",
"torch.cat",
"numpy.random.seed",
"torch.manual_seed",
"torch.load",
"torch.tensor",
"torch.nn.BCELoss",
"torch.no_grad",
"torch.stack",
"torch.device",
"torch.nn.L1Loss"
]
]
|
cedricrupb/ctxmutants | [
"88f5bdc0e320c2e9c74012e8c6fc56f63b6d548d"
]
| [
"ctxmutants/mutation/utils.py"
]
| [
"import random\nimport numpy as np\n\n\nclass MutationSampler:\n\n def __init__(self, mutation_op):\n self.mutation_op = mutation_op\n\n def __call__(self, tokens, location, types = None):\n mutation_dist = self.mutation_op(tokens, location, types)\n \n operators = list(mutation_dist.keys())\n probs = [mutation_dist[operator] for operator in operators]\n\n cum_probs = np.cumsum(probs)\n selection = np.searchsorted(cum_probs, np.random.rand())\n\n return operators[selection]\n\n\n\n "
]
| [
[
"numpy.random.rand",
"numpy.cumsum"
]
]
|
futurityab/haystack | [
"af8ce74dde221a58f01d25aa9c54fbb646549418"
]
| [
"haystack/retriever/dense.py"
]
| [
"import logging\nfrom typing import List, Union, Tuple, Optional\nimport torch\nimport numpy as np\nfrom pathlib import Path\nfrom tqdm import tqdm\n\nfrom haystack.document_store.base import BaseDocumentStore\nfrom haystack import Document\nfrom haystack.retriever.base import BaseRetriever\n\nfrom farm.infer import Inferencer\nfrom farm.modeling.tokenization import Tokenizer\nfrom farm.modeling.language_model import LanguageModel\nfrom farm.modeling.biadaptive_model import BiAdaptiveModel\nfrom farm.modeling.prediction_head import TextSimilarityHead\nfrom farm.data_handler.processor import TextSimilarityProcessor\nfrom farm.data_handler.data_silo import DataSilo\nfrom farm.data_handler.dataloader import NamedDataLoader\nfrom farm.modeling.optimization import initialize_optimizer\nfrom farm.train import Trainer\nfrom torch.utils.data.sampler import SequentialSampler\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass DensePassageRetriever(BaseRetriever):\n \"\"\"\n Retriever that uses a bi-encoder (one transformer for query, one transformer for passage).\n See the original paper for more details:\n Karpukhin, Vladimir, et al. (2020): \"Dense Passage Retrieval for Open-Domain Question Answering.\"\n (https://arxiv.org/abs/2004.04906).\n \"\"\"\n\n def __init__(self,\n document_store: BaseDocumentStore,\n query_embedding_model: Union[Path, str] = \"facebook/dpr-question_encoder-single-nq-base\",\n passage_embedding_model: Union[Path, str] = \"facebook/dpr-ctx_encoder-single-nq-base\",\n max_seq_len_query: int = 64,\n max_seq_len_passage: int = 256,\n use_gpu: bool = True,\n batch_size: int = 16,\n embed_title: bool = True,\n use_fast_tokenizers: bool = True,\n similarity_function: str = \"dot_product\"\n ):\n \"\"\"\n Init the Retriever incl. the two encoder models from a local or remote model checkpoint.\n The checkpoint format matches huggingface transformers' model format\n\n **Example:**\n\n ```python\n | # remote model from FAIR\n | DensePassageRetriever(document_store=your_doc_store,\n | query_embedding_model=\"facebook/dpr-question_encoder-single-nq-base\",\n | passage_embedding_model=\"facebook/dpr-ctx_encoder-single-nq-base\")\n | # or from local path\n | DensePassageRetriever(document_store=your_doc_store,\n | query_embedding_model=\"model_directory/question-encoder\",\n | passage_embedding_model=\"model_directory/context-encoder\")\n ```\n\n :param document_store: An instance of DocumentStore from which to retrieve documents.\n :param query_embedding_model: Local path or remote name of question encoder checkpoint. The format equals the\n one used by hugging-face transformers' modelhub models\n Currently available remote names: ``\"facebook/dpr-question_encoder-single-nq-base\"``\n :param passage_embedding_model: Local path or remote name of passage encoder checkpoint. The format equals the\n one used by hugging-face transformers' modelhub models\n Currently available remote names: ``\"facebook/dpr-ctx_encoder-single-nq-base\"``\n :param max_seq_len_query: Longest length of each query sequence. Maximum number of tokens for the query text. Longer ones will be cut down.\"\n :param max_seq_len_passage: Longest length of each passage/context sequence. Maximum number of tokens for the passage text. Longer ones will be cut down.\"\n :param use_gpu: Whether to use gpu or not\n :param batch_size: Number of questions or passages to encode at once\n :param embed_title: Whether to concatenate title and passage to a text pair that is then used to create the embedding.\n This is the approach used in the original paper and is likely to improve performance if your\n titles contain meaningful information for retrieval (topic, entities etc.) .\n The title is expected to be present in doc.meta[\"name\"] and can be supplied in the documents\n before writing them to the DocumentStore like this:\n {\"text\": \"my text\", \"meta\": {\"name\": \"my title\"}}.\n \"\"\"\n\n self.document_store = document_store\n self.batch_size = batch_size\n self.max_seq_len_passage = max_seq_len_passage\n self.max_seq_len_query = max_seq_len_query\n\n if use_gpu and torch.cuda.is_available():\n self.device = torch.device(\"cuda\")\n else:\n self.device = torch.device(\"cpu\")\n\n self.embed_title = embed_title\n\n # Init & Load Encoders\n self.query_tokenizer = Tokenizer.load(pretrained_model_name_or_path=query_embedding_model,\n do_lower_case=True, use_fast=use_fast_tokenizers)\n self.query_encoder = LanguageModel.load(pretrained_model_name_or_path=query_embedding_model,\n language_model_class=\"DPRQuestionEncoder\")\n\n self.passage_tokenizer = Tokenizer.load(pretrained_model_name_or_path=passage_embedding_model,\n do_lower_case=True, use_fast=use_fast_tokenizers)\n self.passage_encoder = LanguageModel.load(pretrained_model_name_or_path=passage_embedding_model,\n language_model_class=\"DPRContextEncoder\")\n\n self.processor = TextSimilarityProcessor(tokenizer=self.query_tokenizer,\n passage_tokenizer=self.passage_tokenizer,\n max_seq_len_passage=self.max_seq_len_passage,\n max_seq_len_query=self.max_seq_len_query,\n label_list=[\"hard_negative\", \"positive\"],\n metric=\"text_similarity_metric\",\n embed_title=self.embed_title,\n num_hard_negatives=0,\n num_negatives=0)\n\n prediction_head = TextSimilarityHead(similarity_function=similarity_function)\n self.model = BiAdaptiveModel(\n language_model1=self.query_encoder,\n language_model2=self.passage_encoder,\n prediction_heads=[prediction_head],\n embeds_dropout_prob=0.1,\n lm1_output_types=[\"per_sequence\"],\n lm2_output_types=[\"per_sequence\"],\n device=self.device,\n )\n self.model.connect_heads_with_processor(self.processor.tasks, require_labels=False)\n\n def retrieve(self, query: str, filters: dict = None, top_k: int = 10, index: str = None) -> List[Document]:\n \"\"\"\n Scan through documents in DocumentStore and return a small number documents\n that are most relevant to the query.\n\n :param query: The query\n :param filters: A dictionary where the keys specify a metadata field and the value is a list of accepted values for that field\n :param top_k: How many documents to return per query.\n :param index: The name of the index in the DocumentStore from which to retrieve documents\n \"\"\"\n if index is None:\n index = self.document_store.index\n query_emb = self.embed_queries(texts=[query])\n documents = self.document_store.query_by_embedding(query_emb=query_emb[0], top_k=top_k, filters=filters, index=index)\n return documents\n\n def _get_predictions(self, dicts, tokenizer):\n \"\"\"\n Feed a preprocessed dataset to the model and get the actual predictions (forward pass + formatting).\n\n :param dicts: list of dictionaries\n examples:[{'query': \"where is florida?\"}, {'query': \"who wrote lord of the rings?\"}, ...]\n [{'passages': [{\n \"title\": 'Big Little Lies (TV series)',\n \"text\": 'series garnered several accolades. It received..',\n \"label\": 'positive',\n \"external_id\": '18768923'},\n {\"title\": 'Framlingham Castle',\n \"text\": 'Castle on the Hill \"Castle on the Hill\" is a song by English..',\n \"label\": 'positive',\n \"external_id\": '19930582'}, ...]\n :return: dictionary of embeddings for \"passages\" and \"query\"\n \"\"\"\n\n\n dataset, tensor_names, baskets = self.processor.dataset_from_dicts(\n dicts, indices=[i for i in range(len(dicts))], return_baskets=True\n )\n\n data_loader = NamedDataLoader(\n dataset=dataset, sampler=SequentialSampler(dataset), batch_size=self.batch_size, tensor_names=tensor_names\n )\n all_embeddings = {\"query\": [], \"passages\": []}\n self.model.eval()\n for i, batch in enumerate(tqdm(data_loader, desc=f\"Inferencing Samples\", unit=\" Batches\", disable=False)):\n batch = {key: batch[key].to(self.device) for key in batch}\n\n # get logits\n with torch.no_grad():\n query_embeddings, passage_embeddings = self.model.forward(**batch)[0]\n if query_embeddings is not None:\n all_embeddings[\"query\"].append(query_embeddings.cpu().numpy())\n if passage_embeddings is not None:\n all_embeddings[\"passages\"].append(passage_embeddings.cpu().numpy())\n\n if all_embeddings[\"passages\"]:\n all_embeddings[\"passages\"] = np.concatenate(all_embeddings[\"passages\"])\n if all_embeddings[\"query\"]:\n all_embeddings[\"query\"] = np.concatenate(all_embeddings[\"query\"])\n return all_embeddings\n\n def embed_queries(self, texts: List[str]) -> List[np.array]:\n \"\"\"\n Create embeddings for a list of queries using the query encoder\n\n :param texts: Queries to embed\n :return: Embeddings, one per input queries\n \"\"\"\n queries = [{'query': q} for q in texts]\n result = self._get_predictions(queries, self.query_tokenizer)[\"query\"]\n return result\n\n def embed_passages(self, docs: List[Document]) -> List[np.array]:\n \"\"\"\n Create embeddings for a list of passages using the passage encoder\n\n :param docs: List of Document objects used to represent documents / passages in a standardized way within Haystack.\n :return: Embeddings of documents / passages shape (batch_size, embedding_dim)\n \"\"\"\n passages = [{'passages': [{\n \"title\": d.meta[\"name\"] if d.meta and \"name\" in d.meta else \"\",\n \"text\": d.text,\n \"label\": d.meta[\"label\"] if d.meta and \"label\" in d.meta else \"positive\",\n \"external_id\": d.id}]\n } for d in docs]\n embeddings = self._get_predictions(passages, self.passage_tokenizer)[\"passages\"]\n\n return embeddings\n\n def train(self,\n data_dir: str,\n train_filename: str,\n dev_filename: str = None,\n test_filename: str = None,\n batch_size: int = 2,\n embed_title: bool = True,\n num_hard_negatives: int = 1,\n num_negatives: int = 0,\n n_epochs: int = 3,\n evaluate_every: int = 1000,\n n_gpu: int = 1,\n learning_rate: float = 1e-5,\n epsilon: float = 1e-08,\n weight_decay: float = 0.0,\n num_warmup_steps: int = 100,\n grad_acc_steps: int = 1,\n optimizer_name: str = \"TransformersAdamW\",\n optimizer_correct_bias: bool = True,\n save_dir: str = \"../saved_models/dpr-tutorial\",\n query_encoder_save_dir: str = \"lm1\",\n passage_encoder_save_dir: str = \"lm2\"\n ):\n \"\"\"\n train a DensePassageRetrieval model\n :param data_dir: Directory where training file, dev file and test file are present\n :param train_filename: training filename\n :param dev_filename: development set filename, file to be used by model in eval step of training\n :param test_filename: test set filename, file to be used by model in test step after training\n :param batch_size: total number of samples in 1 batch of data\n :param embed_title: whether to concatenate passage title with each passage. The default setting in official DPR embeds passage title with the corresponding passage\n :param num_hard_negatives: number of hard negative passages(passages which are very similar(high score by BM25) to query but do not contain the answer\n :param num_negatives: number of negative passages(any random passage from dataset which do not contain answer to query)\n :param n_epochs: number of epochs to train the model on\n :param evaluate_every: number of training steps after evaluation is run\n :param n_gpu: number of gpus to train on\n :param learning_rate: learning rate of optimizer\n :param epsilon: epsilon parameter of optimizer\n :param weight_decay: weight decay parameter of optimizer\n :param grad_acc_steps: number of steps to accumulate gradient over before back-propagation is done\n :param optimizer_name: what optimizer to use (default: TransformersAdamW)\n :param num_warmup_steps: number of warmup steps\n :param optimizer_correct_bias: Whether to correct bias in optimizer\n :param save_dir: directory where models are saved\n :param query_encoder_save_dir: directory inside save_dir where query_encoder model files are saved\n :param passage_encoder_save_dir: directory inside save_dir where passage_encoder model files are saved\n \"\"\"\n\n self.embed_title = embed_title\n self.processor = TextSimilarityProcessor(tokenizer=self.query_tokenizer,\n passage_tokenizer=self.passage_tokenizer,\n max_seq_len_passage=self.max_seq_len_passage,\n max_seq_len_query=self.max_seq_len_query,\n label_list=[\"hard_negative\", \"positive\"],\n metric=\"text_similarity_metric\",\n data_dir=data_dir,\n train_filename=train_filename,\n dev_filename=dev_filename,\n test_filename=test_filename,\n embed_title=self.embed_title,\n num_hard_negatives=num_hard_negatives,\n num_negatives=num_negatives)\n\n self.model.connect_heads_with_processor(self.processor.tasks, require_labels=True)\n\n data_silo = DataSilo(processor=self.processor, batch_size=batch_size, distributed=False)\n\n # 5. Create an optimizer\n self.model, optimizer, lr_schedule = initialize_optimizer(\n model=self.model,\n learning_rate=learning_rate,\n optimizer_opts={\"name\": optimizer_name, \"correct_bias\": optimizer_correct_bias,\n \"weight_decay\": weight_decay, \"eps\": epsilon},\n schedule_opts={\"name\": \"LinearWarmup\", \"num_warmup_steps\": num_warmup_steps},\n n_batches=len(data_silo.loaders[\"train\"]),\n n_epochs=n_epochs,\n grad_acc_steps=grad_acc_steps,\n device=self.device\n )\n\n # 6. Feed everything to the Trainer, which keeps care of growing our model and evaluates it from time to time\n trainer = Trainer(\n model=self.model,\n optimizer=optimizer,\n data_silo=data_silo,\n epochs=n_epochs,\n n_gpu=n_gpu,\n lr_schedule=lr_schedule,\n evaluate_every=evaluate_every,\n device=self.device,\n )\n\n # 7. Let it grow! Watch the tracked metrics live on the public mlflow server: https://public-mlflow.deepset.ai\n trainer.train()\n\n self.model.save(Path(save_dir), lm1_name=query_encoder_save_dir, lm2_name=passage_encoder_save_dir)\n self.processor.save(Path(save_dir))\n\n def save(self, save_dir: Union[Path, str]):\n \"\"\"\n Save DensePassageRetriever to the specified directory.\n\n :param save_dir: Directory to save to.\n :return: None\n \"\"\"\n save_dir = Path(save_dir)\n self.model.save(save_dir, lm1_name=\"query_encoder\", lm2_name=\"passage_encoder\")\n save_dir = str(save_dir)\n self.query_tokenizer.save_pretrained(save_dir + \"/query_encoder\")\n self.passage_tokenizer.save_pretrained(save_dir + \"/passage_encoder\")\n\n @classmethod\n def load(cls,\n load_dir: Union[Path, str],\n document_store: BaseDocumentStore,\n max_seq_len_query: int = 64,\n max_seq_len_passage: int = 256,\n use_gpu: bool = True,\n batch_size: int = 16,\n embed_title: bool = True,\n use_fast_tokenizers: bool = True,\n similarity_function: str = \"dot_product\",\n ):\n \"\"\"\n Load DensePassageRetriever from the specified directory.\n \"\"\"\n\n load_dir = Path(load_dir)\n dpr = cls(\n document_store=document_store,\n query_embedding_model=Path(load_dir) / \"query_encoder\",\n passage_embedding_model=Path(load_dir) / \"passage_encoder\",\n max_seq_len_query=max_seq_len_query,\n max_seq_len_passage=max_seq_len_passage,\n use_gpu=use_gpu,\n batch_size=batch_size,\n embed_title=embed_title,\n use_fast_tokenizers=use_fast_tokenizers,\n similarity_function=similarity_function\n )\n\n return dpr\n\n\nclass EmbeddingRetriever(BaseRetriever):\n def __init__(\n self,\n document_store: BaseDocumentStore,\n embedding_model: str,\n use_gpu: bool = True,\n model_format: str = \"farm\",\n pooling_strategy: str = \"reduce_mean\",\n emb_extraction_layer: int = -1,\n ):\n \"\"\"\n :param document_store: An instance of DocumentStore from which to retrieve documents.\n :param embedding_model: Local path or name of model in Hugging Face's model hub such as ``'deepset/sentence_bert'``\n :param use_gpu: Whether to use gpu or not\n :param model_format: Name of framework that was used for saving the model. Options:\n\n - ``'farm'``\n - ``'transformers'``\n - ``'sentence_transformers'``\n :param pooling_strategy: Strategy for combining the embeddings from the model (for farm / transformers models only).\n Options:\n\n - ``'cls_token'`` (sentence vector)\n - ``'reduce_mean'`` (sentence vector)\n - ``'reduce_max'`` (sentence vector)\n - ``'per_token'`` (individual token vectors)\n :param emb_extraction_layer: Number of layer from which the embeddings shall be extracted (for farm / transformers models only).\n Default: -1 (very last layer).\n \"\"\"\n self.document_store = document_store\n self.model_format = model_format\n self.embedding_model = embedding_model\n self.pooling_strategy = pooling_strategy\n self.emb_extraction_layer = emb_extraction_layer\n\n logger.info(f\"Init retriever using embeddings of model {embedding_model}\")\n if model_format == \"farm\" or model_format == \"transformers\":\n self.embedding_model = Inferencer.load(\n embedding_model, task_type=\"embeddings\", extraction_strategy=self.pooling_strategy,\n extraction_layer=self.emb_extraction_layer, gpu=use_gpu, batch_size=4, max_seq_len=512, num_processes=0\n )\n\n elif model_format == \"sentence_transformers\":\n try:\n from sentence_transformers import SentenceTransformer\n except ImportError:\n raise ImportError(\"Can't find package `sentence-transformers` \\n\"\n \"You can install it via `pip install sentence-transformers` \\n\"\n \"For details see https://github.com/UKPLab/sentence-transformers \")\n # pretrained embedding models coming from: https://github.com/UKPLab/sentence-transformers#pretrained-models\n # e.g. 'roberta-base-nli-stsb-mean-tokens'\n if use_gpu:\n device = \"cuda\"\n else:\n device = \"cpu\"\n self.embedding_model = SentenceTransformer(embedding_model, device=device)\n else:\n raise NotImplementedError\n\n def retrieve(self, query: str, filters: dict = None, top_k: int = 10, index: str = None) -> List[Document]:\n \"\"\"\n Scan through documents in DocumentStore and return a small number documents\n that are most relevant to the query.\n\n :param query: The query\n :param filters: A dictionary where the keys specify a metadata field and the value is a list of accepted values for that field\n :param top_k: How many documents to return per query.\n :param index: The name of the index in the DocumentStore from which to retrieve documents\n \"\"\"\n if index is None:\n index = self.document_store.index\n query_emb = self.embed(texts=[query])\n documents = self.document_store.query_by_embedding(query_emb=query_emb[0], filters=filters,\n top_k=top_k, index=index)\n return documents\n\n def embed(self, texts: Union[List[str], str]) -> List[np.array]:\n \"\"\"\n Create embeddings for each text in a list of texts using the retrievers model (`self.embedding_model`)\n\n :param texts: Texts to embed\n :return: List of embeddings (one per input text). Each embedding is a list of floats.\n \"\"\"\n\n # for backward compatibility: cast pure str input\n if type(texts) == str:\n texts = [texts] # type: ignore\n assert type(texts) == list, \"Expecting a list of texts, i.e. create_embeddings(texts=['text1',...])\"\n\n if self.model_format == \"farm\" or self.model_format == \"transformers\":\n # TODO: FARM's `sample_to_features_text` need to fix following warning -\n # tokenization_utils.py:460: FutureWarning: `is_pretokenized` is deprecated and will be removed in a future version, use `is_split_into_words` instead.\n emb = self.embedding_model.inference_from_dicts(dicts=[{\"text\": t} for t in texts]) # type: ignore\n emb = [(r[\"vec\"]) for r in emb]\n elif self.model_format == \"sentence_transformers\":\n # text is single string, sentence-transformers needs a list of strings\n # get back list of numpy embedding vectors\n emb = self.embedding_model.encode(texts) # type: ignore\n emb = [r for r in emb]\n return emb\n\n def embed_queries(self, texts: List[str]) -> List[np.array]:\n \"\"\"\n Create embeddings for a list of queries. For this Retriever type: The same as calling .embed()\n\n :param texts: Queries to embed\n :return: Embeddings, one per input queries\n \"\"\"\n return self.embed(texts)\n\n def embed_passages(self, docs: List[Document]) -> List[np.array]:\n \"\"\"\n Create embeddings for a list of passages. For this Retriever type: The same as calling .embed()\n\n :param docs: List of documents to embed\n :return: Embeddings, one per input passage\n \"\"\"\n texts = [d.text for d in docs]\n\n return self.embed(texts)\n"
]
| [
[
"numpy.concatenate",
"torch.no_grad",
"torch.cuda.is_available",
"torch.device",
"torch.utils.data.sampler.SequentialSampler"
]
]
|
maltanar/dataset_loading | [
"75ba02f16735c78dfbd3e3962b484b9b57189dcd"
]
| [
"tests/time_read.py"
]
| [
"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport timeit\nfrom time import sleep # noqa\nfrom dataset_loading import cifar # noqa\nimport io\nfrom contextlib import redirect_stdout\nimport argparse\n\n\ndef test_time(args):\n setup = \"\"\"\ndef transform(x):\n return x-np.mean(x)\n\ntrain_queue, test_queue, val_queue = cifar.get_cifar_queues(\n '', maxsize=1000, transform=transform, _rand_data=True)\nsleep(1)\n \"\"\"\n cmd = \"train_queue.get_batch(100, block=True)\"\"\"\n f = io.StringIO()\n with redirect_stdout(f):\n a = timeit.repeat(cmd, setup, number=10, globals=globals())\n\n if args.print:\n print(a)\n else:\n print(np.median(a))\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--no-print', dest='print', action='store_false',\n default=True)\n args = parser.parse_args()\n test_time(args)\n"
]
| [
[
"numpy.median"
]
]
|
rpatil524/data | [
"9e76c7f22a75ad4e52522444a080ed3f5c6da7dd"
]
| [
"scripts/us_cdc/environmental_health_toxicology/parse_air_quality.py"
]
| [
"# Copyright 2021 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'''\nAuthor: Padma Gundapaneni @padma-g\nDate: 7/28/21\nDescription: This script cleans up a csv file on census tract or county level\nair quality (ozone or 2.5 PM) data downloaded from the CDC.\nURL: https://data.cdc.gov/browse?category=Environmental+Health+%26+Toxicology\n@input_file filepath to the original csv that needs to be cleaned\n@output_file filepath to the csv to which the cleaned data is written\npython3 parse_air_quality.py input_file output_file\n'''\n\nimport sys\nimport pandas as pd\n\n# Mapping of column names in file to StatVar names.\nSTATVARS = {\n \"DS_PM_pred\": \"Mean_Concentration_AirPollutant_PM2.5\",\n \"DS_O3_pred\": \"Mean_Concentration_AirPollutant_Ozone\",\n \"PM25_max_pred\": \"Max_Concentration_AirPollutant_PM2.5\",\n \"PM25_med_pred\": \"Median_Concentration_AirPollutant_PM2.5\",\n \"PM25_mean_pred\": \"Mean_Concentration_AirPollutant_PM2.5\",\n \"PM25_pop_pred\": \"PopulationWeighted_Concentration_AirPollutant_PM2.5\",\n \"O3_max_pred\": \"Max_Concentration_AirPollutant_Ozone\",\n \"O3_med_pred\": \"Median_Concentration_AirPollutant_Ozone\",\n \"O3_mean_pred\": \"Mean_Concentration_AirPollutant_Ozone\",\n \"O3_pop_pred\": \"PopulationWeighted_Concentration_AirPollutant_Ozone\"\n}\n\n# Mapping of month abbreviations to month numbers.\nMONTH_MAP = {\n \"JAN\": 1,\n \"FEB\": 2,\n \"MAR\": 3,\n \"APR\": 4,\n \"MAY\": 5,\n \"JUN\": 6,\n \"JUL\": 7,\n \"AUG\": 8,\n \"SEP\": 9,\n \"OCT\": 10,\n \"NOV\": 11,\n \"DEC\": 12\n}\n\n\ndef main():\n \"\"\"Main function to generate the cleaned csv file.\"\"\"\n file_path = sys.argv[1]\n output_file = sys.argv[2]\n clean_air_quality_data(file_path, output_file)\n\n\ndef clean_air_quality_data(file_path, output_file):\n \"\"\"\n Args:\n file_path: path to a comma-separated CDC air quality data file\n output_file: path for the cleaned csv to be stored\n Returns:\n a cleaned csv file\n \"\"\"\n print(\"Cleaning file...\")\n data = pd.read_csv(file_path)\n if \"Ozone\" in file_path and \"County\" in file_path:\n data[\"Month\"] = data[\"Month\"].map(MONTH_MAP)\n data[\"date\"] = pd.to_datetime(data[[\"Year\", \"Month\", \"Day\"]],\n yearfirst=True)\n else:\n data[\"date\"] = pd.to_datetime(data[\"date\"], yearfirst=True)\n if \"PM2.5\" in file_path:\n census_tract = \"DS_PM\"\n elif \"Ozone\" in file_path:\n census_tract = \"DS_O3\"\n if \"Census\" in file_path:\n data = pd.melt(data,\n id_vars=[\n 'year', 'date', 'statefips', 'countyfips', 'ctfips',\n 'latitude', 'longitude', census_tract + '_stdd'\n ],\n value_vars=[str(census_tract + '_pred')],\n var_name='StatisticalVariable',\n value_name='Value')\n data.rename(columns={census_tract + '_stdd': 'Error'}, inplace=True)\n data[\"dcid\"] = \"geoId/\" + data[\"ctfips\"].astype(str)\n data['StatisticalVariable'] = data['StatisticalVariable'].map(STATVARS)\n elif \"County\" in file_path and \"PM\" in file_path:\n data[\"countyfips\"] = \"1200\" + data[\"countyfips\"].astype(str)\n data[\"dcid\"] = \"geoId/\" + data[\"countyfips\"].astype(str)\n elif \"County\" in file_path and \"Ozone\" in file_path:\n data[\"countyfips\"] = \"1200\" + data[\"countyfips\"].astype(str)\n data[\"dcid\"] = \"geoId/\" + data[\"countyfips\"].astype(str)\n data.to_csv(output_file, float_format='%.6f', index=False)\n print(\"Finished cleaning file!\")\n\n\nif __name__ == \"__main__\":\n main()\n"
]
| [
[
"pandas.read_csv",
"pandas.to_datetime"
]
]
|
txyzwh/MarioPCG | [
"26b8804b30371bf699dbbc1f0897653dec784006"
]
| [
"pytorch/generator_ws.py"
]
| [
"# This generator program expands a low-dimentional latent vector into a 2D array of tiles.\n# Each line of input should be an array of z vectors (which are themselves arrays of floats -1 to 1)\n# Each line of output is an array of 32 levels (which are arrays-of-arrays of integer tile ids)\n\nimport torch\nimport torchvision.utils as vutils\nfrom torch.autograd import Variable\n\nimport sys\nimport json\nimport numpy\nimport models.dcgan as dcgan\n#import matplotlib.pyplot as plt\nimport math\n\nimport random\nfrom collections import OrderedDict\n\ndef combine_images(generated_images):\n num = generated_images.shape[0]\n width = int(math.sqrt(num))\n height = int(math.ceil(float(num)/width))\n shape = generated_images.shape[1:]\n image = numpy.zeros((height*shape[0], width*shape[1],shape[2]), dtype=generated_images.dtype)\n for index, img in enumerate(generated_images):\n i = int(index/width)\n j = index % width\n image[i*shape[0]:(i+1)*shape[0], j*shape[1]:(j+1)*shape[1]] = img\n return image\n\nif __name__ == '__main__':\n # Since the Java program is not launched from the pytorch directory,\n # it cannot find this file when it is specified as being in the current\n # working directory. This is why the network has to be a command line\n # parameter. However, this model should load by default if no parameter\n # is provided.\n if len(sys.argv) ==1:\n \tmodelToLoad = \"netG_epoch_5000.pth\"\n else:\n \tmodelToLoad = sys.argv[1]\n if len(sys.argv) >=3:\n \tnz = int(sys.argv[2])\n else:\n \tnz = 32\n\n #Jacob: I added this to maintain backwards compatibility\n if len(sys.argv) >=4:\n # User can set this to 10 to recreate behavior of original Mario GAN in GECCO 2018\n \tz_dims = int(sys.argv[3])\n elif len(sys.argv) ==1: # If equal to 1, then the old netG_epoch_5000.pth model was loaded above\n \tz_dims = 10 # Number of tiles in original MarioGAN\n else:\n \tz_dims = 13 # This is the new default\n\n batchSize = 1\n #nz = 10 #Dimensionality of latent vector\n\n imageSize = 32\n ngf = 64\n ngpu = 1\n n_extra_layers = 0\n #z_dims = 10 #number different titles: set by command line above\n\n # This is a new DCGAN model that has the proper state dict labels/keys for the latest version of PyTorch (no periods '.')\n generator = dcgan.DCGAN_G(imageSize, nz, z_dims, ngf, ngpu, n_extra_layers)\n #print(generator.state_dict()) \n # This is a state dictionary with deprecated key labels/names\n deprecatedModel = torch.load(modelToLoad, map_location=lambda storage, loc: storage)\n #print(deprecatedModel)\n # Make new model with weights/parameters from deprecatedModel but labels/keys from generator.state_dict()\n fixedModel = OrderedDict()\n for (goodKey,ignore) in generator.state_dict().items():\n # Take the good key and replace the : with . in order to get the deprecated key so the associated value can be retrieved\n badKey = goodKey.replace(\":\",\".\")\n #print(goodKey)\n #print(badKey)\n # Some parameter settings of the generator.state_dict() are not actually part of the saved models\n if badKey in deprecatedModel:\n goodValue = deprecatedModel[badKey]\n fixedModel[goodKey] = goodValue\n\n# print(\"**** fixedModel: \", fixedModel )\n\n if not fixedModel:\n #print(\"LOAD REGULAR\")\n #print(deprecatedModel)\n # If the fixedModel was empty, then the model was trained with the new labels, and the regular load process is fine\n generator.load_state_dict(deprecatedModel)\n else:\n # Load the parameters with the fixed labels \n generator.load_state_dict(fixedModel)\n\n testing = False\n\n if testing: \n line = []\n for i in range (batchSize):\n line.append( [ random.uniform(-1.0, 1.0) ]*nz )\n\n #This is the format that we expect from sys.stdin\n print(line)\n line = json.dumps(line)\n lv = numpy.array(json.loads(line))\n latent_vector = torch.FloatTensor( lv ).view(batchSize, nz, 1, 1) #torch.from_numpy(lv)# torch.FloatTensor( torch.from_numpy(lv) )\n #latent_vector = numpy.array(json.loads(line))\n levels = generator(Variable(latent_vector, volatile=True))\n im = levels.data.cpu().numpy()\n im = im[:,:,:14,:28] #Cut of rest to fit the 14x28 tile dimensions\n im = numpy.argmax( im, axis = 1)\n #print(json.dumps(levels.data.tolist()))\n print(\"Saving to file \")\n im = ( plt.get_cmap('rainbow')( im/float(z_dims) ) )\n\n plt.imsave('fake_sample.png', combine_images(im) )\n\n exit()\n\n print(\"READY\") # Java loops until it sees this special signal\n sys.stdout.flush() # Make sure Java can sense this output before Python blocks waiting for input\n #for line in sys.stdin.readlines(): # Jacob: I changed this to make this work on Windows ... did this break on Mac?\n\n #for line in sys.stdin:\n while 1:\n line = sys.stdin.readline()\n if len(line)==2 and int(line)==0:\n break\n lv = numpy.array(json.loads(line))\n latent_vector = torch.FloatTensor( lv ).view(batchSize, nz, 1, 1)\n\n with torch.no_grad():\n levels = generator(Variable(latent_vector))\n\n #levels.data = levels.data[:,:,:14,:28] #Cut of rest to fit the 14x28 tile dimensions\n\n level = levels.data.cpu().numpy()\n level = level[:,:,:14,:28] #Cut of rest to fit the 14x28 tile dimensions\n level = numpy.argmax( level, axis = 1)\n \n\n #levels.data[levels.data > 0.] = 1 #SOLID BLOCK\n #levels.data[levels.data < 0.] = 2 #EMPTY TILE\n\n # Jacob: Only output first level, since we are only really evaluating one at a time\n print(json.dumps(level[0].tolist()))\n sys.stdout.flush() # Make Java sense output before blocking on next input\n\n\n"
]
| [
[
"torch.load",
"numpy.argmax",
"torch.no_grad",
"torch.FloatTensor",
"numpy.zeros",
"torch.autograd.Variable"
]
]
|
junohpark221/BSc_individual_project | [
"44f49d3cbb93298880f046551056185b72324d17"
]
| [
"codes/Version 8.3 - supp_node_num is multiple of 2/main.py"
]
| [
"import networkx as nx\nimport pandas as pd\n\nfrom pymnet import *\nimport random\nimport matplotlib\nimport cascade as cas\nimport statistics\nimport math\nimport time\nimport csv\nmatplotlib.use('TkAgg')\n\nnodes = 500\nlayers = 3\nsupp_node_num = 2\nintra_thres = 0.0392\ninter_thres = 0.7\n\nattack_size = 50\nattack_point = (0.5, 0.5)\n\nattack_type = \"spatial_number\" # choose one of the \"normal\", \"spatial_number\", \"spatial_range\"\nsupport_type = \"random_nodes\" # choose one of the \"random_nodes\", \"random_layers\"\nedge_type = \"undirected\" # choose one of the \"undirected\", \"directed\"\n\ncoords = {}\n\nrgg_supp_nodes = {}\nrand_supp_nodes = {}\n\nintra_rgg_edges = []\nintra_rand_edges = []\ninter_rgg_edges = []\ninter_rand_edges = []\n\nintra_edges_num = []\ninter_edges_num = [] # [for_edge, back_edge, for_supp_edge, back_supp_edge]\n\n\ndef cal_dist(cur_node, target_node):\n x1, y1 = coords[cur_node]\n if target_node == -1:\n x2, y2 = attack_point\n else:\n x2, y2 = coords[target_node]\n d = math.sqrt((x1-x2)**2 + (y1-y2)**2)\n\n return d\n\n\ndef make_interlayer_edges(net, cur_layer, layer_names, intra_type, inter_type):\n if (intra_type == 'RGG') and (inter_type == 'RGG'):\n for_supp_edges = 0\n back_supp_edges = 0\n\n for cur_node in range((cur_layer * nodes), (cur_layer + 1) * nodes):\n for supp_node in rgg_supp_nodes[cur_node]:\n if supp_node != -1:\n net[supp_node, cur_node, layer_names[supp_node // nodes], layer_names[cur_layer]] = 1\n inter_rgg_edges.append((supp_node, cur_node, layer_names[supp_node // nodes], layer_names[cur_layer]))\n\n if ((supp_node // nodes) > cur_layer) or ((cur_layer == len(layer_names) - 1) and ((supp_node // nodes) == 0)):\n back_supp_edges += 1\n else:\n for_supp_edges += 1\n\n inter_edges_num.append([for_supp_edges, back_supp_edges])\n\n elif (intra_type == 'RGG') and (inter_type == 'Random'):\n for_supp_edges = 0\n back_supp_edges = 0\n\n for cur_node in range((cur_layer * nodes), (cur_layer + 1) * nodes):\n for supp_node in rand_supp_nodes[cur_node]:\n if supp_node != -1:\n if ((supp_node // nodes) > cur_layer) or ((cur_layer == len(layer_names) - 1) and ((supp_node // nodes) == 0)):\n if back_supp_edges < inter_edges_num[cur_layer][1]:\n net[supp_node, cur_node, layer_names[supp_node // nodes], layer_names[cur_layer]] = 1\n inter_rand_edges.append((supp_node, cur_node, layer_names[supp_node // nodes], layer_names[cur_layer]))\n back_supp_edges += 1\n else:\n if for_supp_edges < inter_edges_num[cur_layer][0]:\n net[supp_node, cur_node, layer_names[supp_node // nodes], layer_names[cur_layer]] = 1\n inter_rand_edges.append((supp_node, cur_node, layer_names[supp_node // nodes], layer_names[cur_layer]))\n for_supp_edges += 1\n\n elif (intra_type == 'Random') and (inter_type == 'RGG'):\n for node_from, node_to, layer_from, layer_to in inter_rgg_edges:\n net[node_from, node_to, layer_from, layer_to] = 1\n\n elif (intra_type == 'Random') and (inter_type == 'Random'):\n for node_from, node_to, layer_from, layer_to in inter_rand_edges:\n net[node_from, node_to, layer_from, layer_to] = 1\n\n return net\n\n\ndef make_intralayer_edges(net, cur_layer, cur_layer_name, intra_type, inter_type):\n if (intra_type == 'RGG') and (inter_type == 'RGG'):\n edges = 0\n for cur_node in range(cur_layer * nodes, (cur_layer + 1) * nodes):\n for target_node in range(cur_layer * nodes, (cur_layer + 1) * nodes):\n if cur_node != target_node:\n d = cal_dist(cur_node, target_node)\n if d <= intra_thres:\n net[cur_node, target_node, cur_layer_name, cur_layer_name] = 1\n intra_rgg_edges.append((cur_node, target_node, cur_layer_name))\n edges += 1\n intra_edges_num.append(edges)\n\n elif (intra_type == 'RGG') and (inter_type == 'Random'):\n for cur_node, target_node, cur_layer_name in intra_rgg_edges:\n net[cur_node, target_node, cur_layer_name, cur_layer_name] = 1\n\n elif (intra_type == 'Random') and (inter_type == 'RGG'):\n cur_nodes = list(range((cur_layer * nodes), ((cur_layer + 1) * nodes)))\n target_nodes = list(range((cur_layer * nodes), ((cur_layer + 1) * nodes)))\n\n edges = 0\n while edges < (intra_edges_num[cur_layer] / 2):\n cur_node = random.choice(cur_nodes)\n target_node = random.choice(target_nodes)\n if net[cur_node, target_node, cur_layer_name, cur_layer_name] == 0:\n net[cur_node, target_node, cur_layer_name, cur_layer_name] = 1\n intra_rand_edges.append((cur_node, target_node, cur_layer_name))\n edges += 1\n\n elif (intra_type == 'Random') and (inter_type == 'Random'):\n for cur_node, target_node, cur_layer_name in intra_rand_edges:\n net[cur_node, target_node, cur_layer_name, cur_layer_name] = 1\n\n return net\n\n\ndef make_edges(net, layer_names, intra_type, inter_type):\n for cur_layer in range(layers):\n net = make_intralayer_edges(net, cur_layer, layer_names[cur_layer], intra_type, inter_type)\n net = make_interlayer_edges(net, cur_layer, layer_names, intra_type, inter_type)\n\n return net\n\n\ndef find_supp_pair(cur_layer, target_nodes):\n supp_pairs = []\n for cur_node in range(cur_layer * nodes, (cur_layer + 1) * nodes):\n cur_node_pair = []\n\n for target_node in target_nodes:\n cur_dist = cal_dist(cur_node, target_node)\n if cur_dist <= inter_thres:\n cur_node_pair.append(target_node)\n\n supp_pairs.append([cur_node, cur_node_pair])\n\n return supp_pairs\n\n\ndef find_supporting_nodes(layer_names, intra_type, inter_type):\n if (intra_type == 'RGG') and (inter_type == 'RGG'):\n for cur_layer in range(len(layer_names)):\n target_nodes = []\n if cur_layer == len(layer_names) - 1:\n target_nodes = list(range(nodes))\n elif cur_layer == 0:\n target_nodes = list(range(((cur_layer + 1) * nodes), ((cur_layer + 2) * nodes)))\n else:\n if support_type == \"random_nodes\":\n target_nodes = list(range(((cur_layer + 1) * nodes), ((cur_layer + 2) * nodes)))\n elif support_type == \"random_layers\":\n choice = random.choice([(cur_layer - 1), (cur_layer + 1)])\n target_nodes = list(range((choice * nodes), ((choice + 1) * nodes)))\n\n supp_pairs = find_supp_pair(cur_layer, target_nodes)\n\n s_supp_pairs = sorted(supp_pairs, key=lambda l: len(l[1]))\n\n for i in range(nodes):\n if len(s_supp_pairs[0][1]) != 0:\n target = random.choice(s_supp_pairs[0][1])\n if cur_layer == 0:\n rgg_supp_nodes[s_supp_pairs[0][0]] = [target]\n rgg_supp_nodes[target] = [s_supp_pairs[0][0]]\n elif cur_layer == len(layer_names) - 1:\n rgg_supp_nodes[s_supp_pairs[0][0]].append(target)\n rgg_supp_nodes[target].append(s_supp_pairs[0][0])\n else:\n rgg_supp_nodes[s_supp_pairs[0][0]].append(target)\n rgg_supp_nodes[target] = [s_supp_pairs[0][0]]\n\n index = 0\n for j in range(len(s_supp_pairs)):\n if target in s_supp_pairs[index][1]:\n s_supp_pairs[index][1].remove(target)\n index += 1\n else:\n rgg_supp_nodes[s_supp_pairs[0][0]] = -1\n\n del s_supp_pairs[0]\n s_supp_pairs = sorted(s_supp_pairs, key=lambda l: len(l[1]))\n\n del supp_pairs\n del s_supp_pairs\n\n elif (intra_type == 'RGG') and (inter_type == 'Random'):\n for cur_layer in range(len(layer_names)):\n target_nodes = []\n if cur_layer == len(layer_names) - 1:\n target_nodes = list(range(nodes))\n elif cur_layer == 0:\n target_nodes = list(range(((cur_layer + 1) * nodes), ((cur_layer + 2) * nodes)))\n else:\n if support_type == \"random_nodes\":\n target_nodes = list(range(((cur_layer + 1) * nodes), ((cur_layer + 2) * nodes)))\n elif support_type == \"random_layers\":\n if inter_edges_num[cur_layer][1] == 0:\n choice = cur_layer - 1\n else:\n choice = cur_layer + 1\n target_nodes = list(range((choice * nodes), ((choice + 1) * nodes)))\n\n random.shuffle(target_nodes)\n cur_layer_nodes = list(range((cur_layer * nodes), ((cur_layer + 1) * nodes)))\n\n index = 0\n for cur_node in cur_layer_nodes:\n if cur_layer == 0:\n rand_supp_nodes[cur_node] = [target_nodes[index]]\n rand_supp_nodes[target_nodes[index]] = [cur_node]\n elif cur_layer == len(layer_names) - 1:\n rand_supp_nodes[cur_node].append(target_nodes[index])\n rand_supp_nodes[target_nodes[index]].append(cur_node)\n else:\n rand_supp_nodes[cur_node].append(target_nodes[index])\n rand_supp_nodes[target_nodes[index]] = [cur_node]\n index += 1\n\n\ndef make_nodes(net, layer_names, intra_type, inter_type):\n for i in range(layers):\n for j in range(nodes):\n if (intra_type == 'RGG') and (inter_type == 'RGG'):\n coords[(i * nodes) + j] = (random.random(), random.random())\n net.add_node((i * nodes) + j, layer_names[i])\n\n return net\n\n\ndef make_network_layer(net, layer_names):\n for i in range(layers):\n layer_name = chr(97 + i)\n net.add_layer(layer_name, aspect=0)\n layer_names.append(layer_name)\n\n return net, layer_names\n\n\ndef build_network(rep, intra_type, inter_type):\n layer_names = []\n net = MultilayerNetwork(aspects=1, fullyInterconnected=False, directed=False)\n\n net, layer_names = make_network_layer(net, layer_names)\n net = make_nodes(net, layer_names, intra_type, inter_type)\n find_supporting_nodes(layer_names, intra_type, inter_type)\n net = make_edges(net, layer_names, intra_type, inter_type)\n\n return net\n\n\ndef analyse_initial_network(net, init_data):\n layer_names = net.get_layers() # return dictionary\n layer_names = sorted(list(layer_names))\n\n stats = { \"clustering\":[], # Average clustering coefficient\n \"mean degree\":[], # Mean degree\n \"the most far node\":[], # The most far node from the attack centre\n \"components\":[], # Components of the graph in each layers\n \"largest component\":[], # The largest component of the graphs\n \"size of largest component\":[], # The size of the largest component\n }\n\n # init_intra_edge, init_inter_edge, init_supp_edge, init_far_node, init_clust, init_mean_deg, init_large_comp\n cur_layer = 0\n for layer in layer_names:\n edges = []\n for edge in net.edges:\n if edge[2] == edge[3] == layer:\n edges.append(edge[:2])\n\n G = nx.Graph()\n G.add_edges_from(edges)\n\n components = list(nx.connected_components(G))\n\n far_dist = 0\n for cur_node in range(cur_layer * nodes, (cur_layer + 1) * nodes):\n d = cal_dist(cur_node, -1)\n if d > far_dist:\n far_dist = d\n\n stats[\"clustering\"].append(nx.average_clustering(G))\n stats[\"mean degree\"].append(len(edges) * 2 / nodes)\n stats[\"the most far node\"].append(far_dist)\n stats[\"components\"].append(components)\n stats[\"largest component\"].append(max(components, key=len))\n stats[\"size of largest component\"].append(len(max(components, key=len)))\n\n cur_layer +=1\n\n supp_edge = []\n for inter_edges in inter_edges_num:\n supp_edge.append(inter_edges[0] + inter_edges[1])\n\n init_data.append(statistics.mean(intra_edges_num))\n init_data.append(sum(supp_edge) / layers)\n init_data.append(statistics.mean(stats[\"the most far node\"]))\n init_data.append(statistics.mean(stats[\"clustering\"]))\n init_data.append(statistics.mean(stats[\"mean degree\"]))\n init_data.append(statistics.mean(stats[\"size of largest component\"]))\n\n del G\n\n return init_data\n\n\ndef draw_network(net, type):\n fig = draw(net, nodeCoords=coords, nodeLabelRule={}, nodeSizeRule={'rule':'scaled', 'scalecoeff': 0.01}, defaultEdgeWidth=0.5, show=False)\n fig.savefig(\"%s Network.pdf\" % type)\n\n\ndef make_data_frame(init_data, cas_data, rep, graph_type):\n \"\"\"\n if graph_type == 'RGG_RGG':\n f = open('rgg_rgg_cas_raw_50.csv', 'a', newline='')\n wr = csv.writer(f)\n elif graph_type == 'RGG_Random':\n f = open('rgg_rand_cas_raw_50.csv', 'a', newline='')\n wr = csv.writer(f)\n elif graph_type == 'Random_RGG':\n f = open('rand_rgg_cas_raw_50.csv', 'a', newline='')\n wr = csv.writer(f)\n else:\n f = open('rand_rand_cas_raw_50.csv', 'a', newline='')\n wr = csv.writer(f)\n\n \"\"\"\n f = open('find intra thres for rand.csv', 'a', newline='')\n wr = csv.writer(f)\n\n # init_intra_edge, init_supp_edge, init_far_node, init_clust, init_mean_deg, init_large_comp\n # fin_intra_edge, fin_supp_edge, alive_nodes, tot_isol_node, tot_unsupp_node, cas_steps, fin_far_node, fin_clust, fin_mean_deg, fin_larg_comp, deg_assort, dist_deg_cent, dist_bet_cent, step.....\n data = [rep, intra_thres, init_data[0], init_data[1], cas_data[0], cas_data[1], cas_data[2], cas_data[3], cas_data[4], cas_data[5], init_data[2], cas_data[6], init_data[3], cas_data[7], init_data[4], cas_data[8], init_data[5], cas_data[9], cas_data[10], cas_data[11], cas_data[12]]\n for index in range(len(cas_data[13])):\n data.append(cas_data[13][index])\n data.append(cas_data[14][index])\n\n wr.writerow(data)\n f.close()\n\n\nif __name__ == \"__main__\":\n\n \"\"\"\n Types of attacks/cascades:\n 1. normal attack: select nodes that will be initially attacked randomly.\n 2. spatial_number attack: select the nearest (attack_number) nodes from the attack_point, and they will be initially attacked.\n 3. spatial_range attack: nodes in the circle (centre: attack_point, radius: attack_radius) will be attacked initially.\n\n For \"normal\" attack, cas.attack_network(network, coords, supporting_nodes, attack_type, attack_size=20)\n For \"spatial_number\" attack, cas.attack_network(network, coords, supporting_nodes, attack_type, attack_size=20, attack_layer='a', attack_point=(0.5, 0.5))\n For \"spatial_range\" attack, cas.attack_network(network, coords, supporting_nodes, attack_type, attack_layer='a', attack_point=(0.5, 0.5), attack_radius=0.1)\n\n attack_size = 20 # number of nodes that will be initially killed\n attack_layer = 'a' # the target layer of the attack.\n 'a', 'b', 'c'... means the specific layer. 0 means that suppose every nodes are in the same layer.\n attack_point = (0.5, 0.5) # attack point for spatial_number and spatial_range attacks\n attack_radius = 0.1 # the radius of attack in spatial_range attacks\n \"\"\"\n\n start = time.time()\n print(\"Start\")\n\n # data = {}\n # cur_data = []\n\n # Current number of repeat: 0\n rep = 1\n\n for i in range(1500):\n # init_intra_edge, init_inter_edge, init_supp_edge, init_far_node, init_clust, init_mean_deg, init_large_comp,\n init_data = []\n # fin_intra_edge, fin_inter_edge, fin_supp_edge, alive_nodes, tot_isol_node, tot_unsupp_node, cas_steps, fin_far_node, fin_clust, fin_mean_deg, fin_larg_comp, deg_assort, dist_deg_cent, dist_bet_cent, step.....\n cas_data = []\n\n rgg_rgg_net = build_network(rep, intra_type='RGG', inter_type='RGG')\n init_data = analyse_initial_network(rgg_rgg_net, init_data)\n # draw_network(rgg_rgg_net, type=\"intra_RGG, inter_RGG\")\n # att_rgg_rgg_net, cas_data = cas.attack_network(rgg_rgg_net, coords, rgg_supp_nodes, supp_node_num, cas_data, attack_type, graph_type=\"RGG_RGG\", attack_size=20)\n att_rgg_rgg_net, cas_data = cas.attack_network(rgg_rgg_net, coords, rgg_supp_nodes, supp_node_num, cas_data, attack_type, graph_type=\"RGG_RGG\", attack_size=attack_size, attack_point=attack_point)\n # att_rgg_rgg_net, cas_data = cas.attack_network(rgg_rgg_net, coords, rgg_supp_nodes, supp_node_num, cas_data, attack_type, graph_type=\"RGG_RGG\", attack_point=(0.5, 0.5), attack_radius=0.1)\n make_data_frame(init_data, cas_data, rep, graph_type='RGG_RGG')\n\n del rgg_rgg_net\n del att_rgg_rgg_net\n\n \"\"\"\n cur_data.append(init_data[1])\n\n if rep % 50 == 0:\n data[inter_thres] = cur_data.copy()\n\n inter_thres += 0.05\n del cur_data[:]\n \"\"\"\n \n del init_data[:]\n del cas_data[:]\n\n rgg_rand_net = build_network(rep, intra_type='RGG', inter_type='Random')\n init_data = analyse_initial_network(rgg_rand_net, init_data)\n # draw_network(rgg_rand_net, type=\"intra_RGG, inter_Random\")\n # att_rgg_rand_net, cas_data = cas.attack_network(rgg_rand_net, coords, rand_supp_nodes, supp_node_num, cas_data, attack_type, graph_type=\"RGG_Rand\", attack_size=20)\n att_rgg_rand_net, cas_data = cas.attack_network(rgg_rand_net, coords, rand_supp_nodes, supp_node_num, cas_data, attack_type, graph_type=\"RGG_Rand\", attack_size=attack_size, attack_point=attack_point)\n # att_rgg_rand_net, cas_data = cas.attack_network(rgg_rand_net, coords, rand_supp_nodes, supp_node_num, cas_data, attack_type, graph_type=\"RGG_Rand\", attack_point=(0.5, 0.5), attack_radius=0.1)\n make_data_frame(init_data, cas_data, rep, graph_type='RGG_Random')\n\n del rgg_rand_net\n del att_rgg_rand_net\n\n del init_data[:]\n del cas_data[:]\n\n rand_rgg_net = build_network(rep, intra_type='Random', inter_type='RGG')\n init_data = analyse_initial_network(rand_rgg_net, init_data)\n # draw_network(rand_rgg_net, type=\"intra_Random, inter_RGG\")\n # att_rand_rgg_net, cas_data = cas.attack_network(rand_rgg_net, coords, rgg_supp_nodes, supp_node_num, cas_data, attack_type, graph_type=\"Rand_RGG\", attack_size=20)\n att_rand_rgg_net, cas_data = cas.attack_network(rand_rgg_net, coords, rgg_supp_nodes, supp_node_num, cas_data, attack_type, graph_type=\"Rand_RGG\", attack_size=attack_size, attack_point=attack_point)\n # att_rand_rgg_net, cas_data = cas.attack_network(rand_rgg_net, coords, rgg_supp_nodes, supp_node_num, cas_data, attack_type, graph_type=\"Rand_RGG\", attack_point=(0.5, 0.5), attack_radius=0.1)\n make_data_frame(init_data, cas_data, rep, graph_type='Random_RGG')\n\n del rand_rgg_net\n del att_rand_rgg_net\n\n del init_data[:]\n del cas_data[:]\n\n rand_rand_net = build_network(rep, intra_type='Random', inter_type='Random')\n init_data = analyse_initial_network(rand_rand_net, init_data)\n # draw_network(rand_rand_net, type=\"intra_Random, inter_Random\")\n # att_rand_rand_net, cas_data = cas.attack_network(rand_rand_net, coords, rand_supp_nodes, supp_node_num, cas_data, attack_type, graph_type=\"Rand_Rand\", attack_size=20)\n att_rand_rand_net, cas_data = cas.attack_network(rand_rand_net, coords, rand_supp_nodes, supp_node_num, cas_data, attack_type, graph_type=\"Rand_Rand\", attack_size=attack_size, attack_point=attack_point)\n # att_rand_rand_net, cas_data = cas.attack_network(rand_rand_net, coords, rand_supp_nodes, supp_node_num, cas_data, attack_type, graph_type=\"Rand_Rand\", attack_point=(0.5, 0.5), attack_radius=0.1)\n make_data_frame(init_data, cas_data, rep, graph_type='Random_Random')\n\n del rand_rand_net\n del att_rand_rand_net\n\n print(\"Repeat %d is done\" % rep)\n\n if rep % 30 == 0:\n intra_thres += 0.0002\n\n del intra_rgg_edges[:]\n del intra_rand_edges[:]\n del inter_rgg_edges[:]\n del inter_rand_edges[:]\n del intra_edges_num[:]\n del inter_edges_num[:]\n\n rep += 1\n\n print(\"time: \", time.time() - start)\n\n # draw_network(att_rgg_rgg_net, type=\"Attacked intra_RGG, inter_RGG\")\n # draw_network(att_rgg_rand_net, type=\"Attacked intra_RGG, inter_Rand\")\n # draw_network(att_rand_rgg_net, type=\"Attacked intra_Rand, inter_RGG\")\n # draw_network(att_rand_rand_net, type=\"Attacked intra_Rand, inter_Rand\")\n\n # df = pd.DataFrame(data)\n # df.to_csv('find inter thres.csv')\n\n print(\"time: \", time.time() - start)\n print(\"End\")\n"
]
| [
[
"matplotlib.use"
]
]
|
luis-armando-perez-rey/diffusion_vae_github | [
"1d44723a6363c304f575c584142492950591e6f5"
]
| [
"modules/utils/callbacks/latent_space_callback.py"
]
| [
"import keras\nimport time\nimport numpy as np\nimport imageio\nimport glob\nimport os\n\nclass LatentSpaceCallback(keras.callbacks.Callback):\n def __init__(self, train_data, vae,save_folder, experiment_name, periodicity, batch_size):\n self.train_data = train_data\n self.vae = vae\n self.save_folder = save_folder\n self.experiment_name = experiment_name\n self.batch_size = batch_size\n self.periodicity = periodicity\n self.time_stamp = time.strftime(\"%Y-%m-%d-%H-%M_\")\n self.filename = os.path.join(save_folder, experiment_name + '_' + self.time_stamp)\n\n def on_train_begin(self, logs={}):\n '''Initialize the learning rate to the maximum value at the start of training.'''\n #matrix_utils.plot_angles_from_matrices(self.train_data, 1, 1)\n #plt.savefig(self.filename + '_angle_epoch_-1' + '.png')\n self.vae.save_plot_latent_space(self.train_data, self.batch_size, self.filename + '_epoch_-1' + '.png')\n\n def on_epoch_end(self, epoch, logs={}):\n '''Check for end of current cycle, apply restarts when necessary.'''\n if epoch % self.periodicity == 0:\n self.vae.save_plot_latent_space(self.train_data, self.batch_size, self.filename + '_epoch_' + str(epoch) + '.png')\n\n\n def on_train_end(self, logs={}):\n # RP3 plot\n path_list = np.array(list(glob.glob(self.filename + '*')))\n print(path_list)\n epochs = np.array([int(x.split('_epoch_')[-1].split('.')[0]) for x in path_list])\n ordered_indexes = np.argsort(epochs)\n images = np.array([imageio.imread(x) for x in path_list[ordered_indexes]])\n imageio.mimsave(self.filename+ '.gif', images, fps=1000)\n\n\n\n"
]
| [
[
"numpy.argsort"
]
]
|
zhonghua-wang/NPTP | [
"bbf2367395c0a0b0aad63cb39d6f9403a215a52f"
]
| [
"python_code/ml/RF_2.py"
]
| [
"import multiprocessing as mp\nimport os\nimport warnings\nfrom random import shuffle\nfrom rdkit.Chem import MACCSkeys\nimport numpy as np\nimport pandas as pd\nfrom rdkit.Chem import MolFromSmiles,AllChem\nfrom rdkit.Chem.AllChem import GetMorganFingerprintAsBitVect\nfrom rdkit import DataStructs\n#from sklearn.cluster import AgglomerativeClustering\n#from sklearn.neighbors import DistanceMetric\nfrom sklearn.ensemble import RandomForestClassifier\n#from xgboost.sklearn import XGBClassifier\n#from sklearn.svm import SVC\n#from sklearn.naive_bayes import BernoulliNB\n#from sklearn.neighbors import KNeighborsClassifier\n#from sklearn.ensemble import AdaBoostClassifier\nimport joblib\nfrom sklearn.metrics import accuracy_score, recall_score, precision_score, f1_score, roc_auc_score, cohen_kappa_score\nfrom sklearn.metrics import confusion_matrix, silhouette_score, average_precision_score\nimport datetime\nimport argparse\nimport pandas as pd\nimport itertools\nimport numpy as np\nimport pickle\nwarnings.filterwarnings(\"ignore\")\nbasePath=os.getcwd()\ndictionary0 = {\n 'n_estimators':[10,50,100,300,700,1000],\n 'criterion':['gini','entropy'],\n 'max_features':['sqrt','log2']\n}\nhyperParams0 = pd.DataFrame(list(itertools.product(*dictionary0.values())), columns=dictionary0.keys())\nhyperParams0.index=np.arange(len(hyperParams0.index.values))\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-cl_file\", help=\"cl per target\", type=str, default=basePath+'/test_data/cl/')\nparser.add_argument(\"-pertarget_file\", help=\"smi per target\", type=str, default=basePath+'/test_data/pertargetdata/')\nparser.add_argument(\"-datasetNames\", help=\"Dataset Name\",type=str, default=\"ecfp6fcfp6MACCS\")\nparser.add_argument(\"-saveBasePath\", help=\"saveBasePath\", type=str, default=basePath+'/res_test_data/')\nparser.add_argument(\"-ofolds\", help=\"Outer Folds\", nargs='+', type=int, default=[0, 1, 2])\nparser.add_argument(\"-ifolds\", help=\"Inner Folds\", nargs='+', type=int, default=[0, 1, 2])\nparser.add_argument(\"-pStart\", help=\"Parameter Start Index\", type=int, default=0)\nparser.add_argument(\"-pEnd\", help=\"Parameter End Index\", type=int, default=24)\nargs = parser.parse_args()\ncl_file = args.cl_file\npertarget_file = args.pertarget_file\ndatasetNames = args.datasetNames\nsaveBasePath = args.saveBasePath\ncompOuterFolds = args.ofolds\ncompInnerFolds = args.ifolds\nparamStart = args.pStart\nparamEnd = args.pEnd\ncompParams = list(range(paramStart, paramEnd))\nprint()\n\ndef bestSettingsSimple(perfFiles, nrParams):\n aucFold=[]\n for foldInd in range(0, len(perfFiles)):\n innerFold=-1\n aucParam=[]\n for paramNr in range(0, nrParams):\n #try:\n saveFile=open(perfFiles[foldInd][paramNr], \"rb\")\n aucRun=pickle.load(saveFile)\n saveFile.close()\n #except:\n # pass\n if(len(aucRun)>0):\n aucParam.append(aucRun[-1])\n \n aucParam=np.array(aucParam)\n \n if(len(aucParam)>0):\n aucFold.append(aucParam)\n aucFold=np.array(aucFold)\n aucMean=np.nanmean(aucFold, axis=0)\n paramInd=np.nanmean(aucMean, axis=1).argmax()\n \n return (paramInd, aucMean, aucFold)\n\ndef ClusterCV(csv_file):\n tar_id = csv_file.split('.')[0]\n file_name = pertarget_file + csv_file\n clusterSampleFilename = os.path.join(cl_file, 'cl' + tar_id + \".info\")\n chembl_data = file_reader(file_name)\n target_name = chembl_data.iloc[0,0]\n labels = chembl_data.active_label\n features = batchECFP(chembl_data.canonical_smiles)\n clusterTab = pd.read_csv(clusterSampleFilename, header=None, index_col=False, sep=\",\")\n df = clusterTab.values\n folds = df[:, 0]\n return folds, features, labels, target_name\n\n\ndef batchECFP(smiles, radius=3, nBits=2048):\n smiles = np.array(smiles)\n n = len(smiles)\n fingerprints_0 = np.zeros((n, nBits), dtype=int)\n fingerprints_1 = np.zeros((n, nBits), dtype=int)\n MACCSArray = []\n for i in range(n):\n mol = MolFromSmiles(smiles[i])\n fp = GetMorganFingerprintAsBitVect(mol, radius, nBits=nBits)\n fp_1 = GetMorganFingerprintAsBitVect(mol, radius, nBits=nBits, useFeatures=True)\n MACCSArray.append(MACCSkeys.GenMACCSKeys(mol))\n fingerprints_0[i] = np.array(list(fp.ToBitString()))\n fingerprints_1[i] = np.array(list(fp_1.ToBitString()))\n fingerprints_2 = np.array(MACCSArray)\n fingerprints = np.hstack((fingerprints_0,fingerprints_1,fingerprints_2))\n fingerprints_3=np.hstack((fingerprints_0,fingerprints_1))\n fingerprints_4=np.hstack((fingerprints_0,fingerprints_2))\n fingerprints_5=np.hstack((fingerprints_1,fingerprints_2))\n if datasetNames==\"ecfp6fcfp6MACCS\":\n fingerprints_out=fingerprints\n elif datasetNames==\"ecfp6\":\n fingerprints_out=fingerprints_0\n elif datasetNames==\"fcfp6\":\n fingerprints_out=fingerprints_1\n elif datasetNames==\"MACCS\":\n fingerprints_out=fingerprints_2\n elif datasetNames==\"ecfp6fcfp6\":\n fingerprints_out=fingerprints_3\n elif datasetNames==\"ecfp6MACCS\":\n fingerprints_out=fingerprints_4\n elif datasetNames==\"fcfp6MACCS\":\n fingerprints_out=fingerprints_5\n \n return fingerprints_out\n\n\ndef get_file_list(file_folder):\n # method one: file_list = os.listdir(file_folder)\n for root, dirs, file_list in os.walk(file_folder):\n return file_list\n\n\ndef file_reader(file_path):\n data = pd.read_csv(file_path)\n return data\n\ndef data_split_modeling(target_file):\n # validation data construction\n target_id = target_file.split('.')[0]\n\n cluster_res = ClusterCV(csv_file=target_file)\n folds = cluster_res[0]\n features = cluster_res[1]\n active_label = cluster_res[2]\n target_name = cluster_res[3]\n save_path =saveBasePath+\"/ML/\"+datasetNames+\"/RF/\" + target_name + '/'\n if not os.path.exists(save_path):\n os.makedirs(save_path)\n dbgPath=save_path+\"dbg/\"\n if not os.path.exists(dbgPath):\n os.makedirs(dbgPath)\n # modeling\n\n for outerFold in compOuterFolds:\n savePrefix0=\"o\"+'{0:04d}'.format(outerFold+1)\n savePrefix=save_path+savePrefix0\n dbgOutput=open(dbgPath+savePrefix0+\".dbg\", \"w\")\n perfFiles=[]\n for innerFold in compInnerFolds:\n if innerFold == outerFold:\n continue\n perfFiles.append([])\n for paramNr in range(0, hyperParams0.shape[0]):\n perfFiles[-1].append(save_path+\"o\"+'{0:04d}'.format(outerFold+1)+\"_i\"+'{0:04d}'.format(innerFold+1)+\"_p\"+'{0:04d}'.format(hyperParams0.index.values[paramNr])+\".test.auc.pckl\")\n paramNr, perfTable, perfTableOrig=bestSettingsSimple(perfFiles, hyperParams0.shape[0])\n print(hyperParams0.iloc[paramNr], file=dbgOutput)\n print(perfTable, file=dbgOutput)\n dbgOutput.close()\n \n roc_auc = []\n n_estimators1 = hyperParams0.iloc[paramNr].n_estimators\n criterion1 = hyperParams0.iloc[paramNr].criterion\n max_features1 = hyperParams0.iloc[paramNr].max_features\n rf = RandomForestClassifier(n_estimators=n_estimators1,criterion=criterion1,max_features=max_features1)\n print('rf')\n\n # Get training and testing set\n test_index = np.where(folds == outerFold)[0]\n train_index = np.where(folds != outerFold)[0]\n #print(train_index)\n # Get train and test samples\n X_test = features[test_index, :]\n X_train = features[train_index, :]\n y_test = active_label.iloc[test_index]\n y_train = active_label.iloc[train_index]\n # Modeling and Evaluate\n rf.fit(X_train, y_train)\n y_pred = rf.predict(X_test)\n # compute roc-auc\n y_pred_proba = rf.predict_proba(X_test)\n roc_auc.append(roc_auc_score(y_test, y_pred_proba[:, 1]))\n a = np.array(roc_auc)\n \n reportTestAUC = []\n reportTestAUC.append(a)\n saveFilename = savePrefix + \".test.auc.pckl\"\n saveFile = open(saveFilename, \"wb\")\n pickle.dump(reportTestAUC, saveFile)\n saveFile.close()\n\nstartime = datetime.datetime.now()\nprint(\"Start time\", startime)\nfolder_path = pertarget_file\nfiles_list = get_file_list(folder_path)\np = mp.Pool(processes=1)\nfor tar_file in files_list:\n result = p.apply_async(data_split_modeling, args=(tar_file,)) # distribute one task to one pool\np.close() # finished load task\np.join() # start\nprint(\"Sub-process(es) done.\")\nendtime = datetime.datetime.now()\nprint(\"End time\", endtime)\ncostime = endtime - startime\nprint(\"Cost time\", costime)\n#data_split_modeling(files_list[0])\n"
]
| [
[
"numpy.hstack",
"sklearn.metrics.roc_auc_score",
"pandas.read_csv",
"sklearn.ensemble.RandomForestClassifier",
"numpy.nanmean",
"numpy.array",
"numpy.zeros",
"numpy.where"
]
]
|
david0811/atms597_proj3 | [
"3f89c4e4d745b19879dee9bf71fa01ce23e5a909"
]
| [
".ipynb_checkpoints/seasonal_anomalies-checkpoint.py"
]
| [
"import xarray as xr\nimport pandas as pd\nfrom siphon.catalog import TDSCatalog\nimport metpy\nfrom metpy.units import units\n\n# Create list of extreme precipitation days from PrecipData.py\ntimes = ['1997-06-13T00:00:00.000000000', '1997-07-06T00:00:00.000000000',\n '1997-07-25T00:00:00.000000000', '1997-07-26T00:00:00.000000000',\n '1997-08-01T00:00:00.000000000', '1997-08-22T00:00:00.000000000',\n '1997-08-23T00:00:00.000000000', '1997-08-24T00:00:00.000000000',\n '1997-08-25T00:00:00.000000000', '1998-06-15T00:00:00.000000000',\n '1998-07-07T00:00:00.000000000', '1998-07-28T00:00:00.000000000',\n '1998-07-29T00:00:00.000000000', '1998-08-24T00:00:00.000000000',\n '1999-06-11T00:00:00.000000000', '1999-06-22T00:00:00.000000000',\n '1999-07-07T00:00:00.000000000', '1999-07-15T00:00:00.000000000',\n '1999-07-19T00:00:00.000000000', '1999-08-09T00:00:00.000000000',\n '2000-07-13T00:00:00.000000000', '2000-08-24T00:00:00.000000000',\n '2002-06-25T00:00:00.000000000', '2002-06-26T00:00:00.000000000',\n '2002-08-03T00:00:00.000000000', '2002-08-24T00:00:00.000000000',\n '2003-07-27T00:00:00.000000000', '2003-07-28T00:00:00.000000000',\n '2003-08-23T00:00:00.000000000', '2003-08-24T00:00:00.000000000',\n '2004-06-15T00:00:00.000000000', '2004-07-16T00:00:00.000000000',\n '2004-07-30T00:00:00.000000000', '2004-08-02T00:00:00.000000000',\n '2004-08-05T00:00:00.000000000', '2004-08-11T00:00:00.000000000',\n '2005-06-28T00:00:00.000000000', '2005-06-29T00:00:00.000000000',\n '2005-07-19T00:00:00.000000000', '2005-08-01T00:00:00.000000000',\n '2006-06-22T00:00:00.000000000', '2006-06-23T00:00:00.000000000',\n '2006-07-03T00:00:00.000000000', '2006-07-04T00:00:00.000000000',\n '2006-07-05T00:00:00.000000000', '2006-07-29T00:00:00.000000000',\n '2006-07-31T00:00:00.000000000', '2006-08-05T00:00:00.000000000',\n '2006-08-06T00:00:00.000000000', '2006-08-07T00:00:00.000000000',\n '2006-08-08T00:00:00.000000000', '2006-08-09T00:00:00.000000000',\n '2007-06-22T00:00:00.000000000', '2007-07-01T00:00:00.000000000',\n '2007-07-02T00:00:00.000000000', '2007-07-08T00:00:00.000000000',\n '2007-07-26T00:00:00.000000000', '2007-08-08T00:00:00.000000000',\n '2007-08-26T00:00:00.000000000', '2007-08-27T00:00:00.000000000',\n '2007-08-28T00:00:00.000000000', '2008-08-05T00:00:00.000000000',\n '2009-07-21T00:00:00.000000000', '2009-07-22T00:00:00.000000000',\n '2009-08-19T00:00:00.000000000', '2010-07-02T00:00:00.000000000',\n '2010-07-24T00:00:00.000000000', '2011-07-06T00:00:00.000000000',\n '2011-08-28T00:00:00.000000000', '2012-08-30T00:00:00.000000000',\n '2013-06-16T00:00:00.000000000', '2013-07-19T00:00:00.000000000',\n '2013-08-01T00:00:00.000000000', '2013-08-23T00:00:00.000000000',\n '2014-07-22T00:00:00.000000000', '2014-07-23T00:00:00.000000000',\n '2014-07-29T00:00:00.000000000', '2014-07-30T00:00:00.000000000',\n '2014-08-21T00:00:00.000000000', '2014-08-23T00:00:00.000000000',\n '2014-08-25T00:00:00.000000000', '2015-07-25T00:00:00.000000000',\n '2015-07-27T00:00:00.000000000', '2015-08-04T00:00:00.000000000',\n '2015-08-05T00:00:00.000000000', '2016-07-03T00:00:00.000000000',\n '2016-07-09T00:00:00.000000000', '2016-07-10T00:00:00.000000000',\n '2016-07-11T00:00:00.000000000', '2016-08-01T00:00:00.000000000',\n '2016-08-02T00:00:00.000000000', '2016-08-06T00:00:00.000000000',\n '2017-06-03T00:00:00.000000000', '2017-07-20T00:00:00.000000000',\n '2017-07-28T00:00:00.000000000', '2017-08-20T00:00:00.000000000',\n '2018-07-09T00:00:00.000000000', '2018-08-16T00:00:00.000000000',\n '2018-08-21T00:00:00.000000000', '2019-07-20T00:00:00.000000000',\n '2019-07-28T00:00:00.000000000', '2019-07-29T00:00:00.000000000',\n '2019-07-31T00:00:00.000000000', '2019-08-08T00:00:00.000000000',\n '2019-08-09T00:00:00.000000000', '2019-08-30T00:00:00.000000000']\n\n# Format times as pandas datatime, making easier for xarray subsetting\ntime_formatted = pd.to_datetime(times)\n\ndef remote_data_grab(var, var_type, level=None, time_scale=None, time=time_formatted):\n \"\"\"\n Grabs data from NCEP Reanalysis data given different variables and levels\n\n Input\n -------\n var = string of variable name (ex. temp)\n\n var_type = string with variable type (ex. precipitation)\n\n level (optional) = integer with pressure level (ex. 1000) in hPa\n\n time_scale (optional) = string detailing the time interval (can set to 'long_term'\n mean)\n time (optional) = list of times for precipitation data\n\n Output\n --------\n ds = xarray dataset with seasonal average for JJA (June, July, August)\n\n \"\"\"\n\n var_name = {'temp':'air',\n 'height':'hgt',\n 'q':'shum',\n 'u_wind':'uwnd',\n 'v_wind':'vwnd',\n 'skin_temp':'skt.sfc.gauss',\n 'sfc_u_wind':'uwnd.sig995',\n 'sfc_v_wind':'vwnd.sig995'}\n\n # Setup data link\n link = 'https://www.esrl.noaa.gov/psd/thredds/dodsC/Aggregations/ncep.reanalysis/'+var_type+'/'+var_name[var]+'.nc'\n\n if time_scale == 'long_term':\n\n # Create a new dictionary with variables for monthly data\n var_name = {'temp':'air',\n 'height':'hgt',\n 'q':'shum',\n 'u_wind':'uwnd',\n 'v_wind':'vwnd',\n 'skin_temp':'skt',\n 'sfc_u_wind':'uwnd.sig995',\n 'sfc_v_wind':'vwnd.sig995',\n 'wind_spd' : 'wspd'}\n\n # Create link to data\n link = 'https://www.esrl.noaa.gov/psd/thredds/dodsC/Datasets/ncep.reanalysis.derived/'+var_type+'/'+var_name[var]+'.mon.ltm.nc'\n\n # Add time subset\n ds = xr.open_dataset('https://www.esrl.noaa.gov/psd/thredds/dodsC/Datasets/ncep.reanalysis.derived/pressure/air.mon.ltm.nc')\n time = (ds['time.season'] == 'JJA')\n\n # Deal with pressure levels\n if var_type == 'pressure':\n ds = xr.open_dataset(link).sel(time=time, level=level).metpy.parse_cf()\n\n # Calculate total column water vapor\n elif var_type == 'total_column':\n\n # Add new link\n try:\n link = 'https://www.esrl.noaa.gov/psd/thredds/dodsC/Aggregations/ncep.reanalysis/pressure/'+var_name[var]+'.nc'\n\n # Open the dataset\n ds = xr.open_dataset(link).sel(time=time).metpy.parse_cf()\n\n except:\n link = 'https://www.esrl.noaa.gov/psd/thredds/dodsC/Datasets/ncep.reanalysis.derived/pressure/'+var_name[var]+'.mon.ltm.nc'\n\n # Open the dataset and subset for given months, along with only the pressure levels from the other dataset\n ds = xr.open_dataset(link).sel(time=time).metpy.parse_cf()\n\n # Integrate total column water vapor\n ds = ds.sum('level')\n\n else:\n\n # Find average of skin temperature\n ds = xr.open_dataset(link).sel(time=time).metpy.parse_cf()\n\n # Set level to surface\n level = 'surface'\n\n # Make sure temperature is in degrees Celsius\n if var == 'temp':\n ds[var_name[var]].metpy.convert_units('degC')\n\n if var == 'q':\n ds[var_name[var]].metpy.convert_units('g/kg')\n\n try:\n\n # Give special name to total column specific humidity\n if var_type == 'total_column':\n ds = ds.rename({var_name[var]:'total_column_q'})\n\n else:\n\n # Rename the variable to contain the level\n ds = ds.rename({var_name[var]:var+'_'+str(level)})\n\n except:\n\n # Rename varaibles that have extra characters\n if var == 'skin_temp':\n var_name[var] = 'skt'\n\n elif var == 'sfc_u_wind':\n var_name[var] = 'uwnd'\n\n elif var == 'sfc_v_wind':\n var_name[var] = 'vwnd'\n\n # Rename variable\n ds = ds.rename({var_name[var]:var+'_'+str(level)})\n\n # Calcualte the seasonal average\n return ds.groupby('time.season').mean('time').squeeze()\n\ndef merge_datasets(var_type, time_scale=None):\n \"\"\"\n Finds seasonal average then merges into a single dataset\n\n Input\n -------\n var_type = string detailing variable type ('pressure', 'surface_gauss', 'surface',\n or total_column)\n\n time_scale = flag to calculate long term mean instead of daily values (default daily values)\n\n Output\n -------\n ds = merged dataset with all variables\n\n \"\"\"\n\n # Create a list for the datasets\n datasets = []\n\n # Pressure variables\n atmos_vars = {250:['u_wind', 'v_wind', 'wind_spd'],\n 500:['u_wind', 'v_wind', 'height'],\n 850:['temp', 'q', 'u_wind', 'v_wind']}\n\n # Gaussian surface variables\n surface_gaussian = ['skin_temp']\n\n # Surface variables\n surface = ['sfc_u_wind', 'sfc_v_wind']\n\n if var_type == 'pressure':\n levels = [250, 500, 850]\n\n for lev in levels:\n for var in atmos_vars[lev]:\n datasets.append(remote_data_grab(var, var_type, lev, time_scale))\n print('Done with ', var, ' ', lev)\n\n elif var_type == 'surface_gauss':\n for var in surface_gaussian:\n datasets.append(remote_data_grab(var, var_type, None, time_scale))\n print('Done with ', var)\n\n elif var_type == 'surface':\n for var in surface:\n datasets.append(remote_data_grab(var, var_type, None, time_scale))\n print('Done with ', var)\n\n elif var_type == 'total_column':\n datasets.append(remote_data_grab('q', var_type, None, time_scale))\n print('Done with Total Column Water Vapor')\n\n else:\n print('Error!')\n\n return xr.merge(datasets, compat='override')\n\ndef anomaly(var_type):\n \"\"\"\n Calculates the averages, anomaly, and saves them to a netcdf file\n\n Input\n ------\n var_type = string with variable type ('pressure', 'surface_gauss', 'surface',\n or 'total_column')\n\n Output\n -------\n Saved netcdf file for seasonal average (JJA) for long term mean, extreme precipitation\n days, and anomalies (extreme precipitation - long term mean)\n\n \"\"\"\n\n # Dataset with extreme precipitation days\n extreme_precip_ds = merge_datasets(var_type)\n\n # Dataset with long-term seasonal average\n long_term_average = merge_datasets(var_type, 'long_term').drop('valid_yr_count')\n\n # Calculate the anomaly\n anomaly = extreme_precip_ds - long_term_average\n\n # Save the datasets to netcdf so they can be plotted later\n extreme_precip_ds.drop('crs').to_netcdf(var_type + '_extreme_precip_mean.nc')\n long_term_average.drop('crs').to_netcdf(var_type + '_long_term_mean.nc')\n anomaly.drop('crs').to_netcdf(var_type + '_anomaly.nc')\n\n return print('Done with all ', var_type, 'variables')\n\n# Run the anomaly calculations\n\n# Find anomalies for all the pressure level data (ex. 850 winds)\nanomaly('pressure')\n\n# Find anomalies for all surface data (ex. skin temperature)\nanomaly('surface')\n\n# Find anomalies for all surface gaussian data (ex. sig995 winds)\nanomaly('surface_gauss')\n\n# Find anomalies for integrated water vapor\nanomaly('total_column')\n"
]
| [
[
"pandas.to_datetime"
]
]
|
spcl/GMS | [
"bd8f384ca2f02c52909f4ab77cbb86edba89c7b6"
]
| [
"scripts/plotmaker_old.py"
]
| [
"#!/bin/python3\n\n##################################################################################################################\n##\n## usage info is at the bottom, scroll down to main part for how-to\n##\n##################################################################################################################\n\nimport os, re\nimport numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot\n\ndef defaultOptions():\n return {\n \"pueschel\":False, \n \"pooling\":\"mean\", \n \"saveas\":None,\n \"noPP\":\"id\"\n }\n\ndef shortenGraphName(arg):\n name = basename(arg)\n pattern = 'd-abc'\n return name[:len(pattern)]\n\ndef basename(arg):\n \"\"\"Try to extract a basename from the provided argument.\"\"\"\n if not isinstance(arg, str):\n arg = str(arg)\n try:\n name = os.path.basename(arg)\n except:\n name = arg\n\n fileExtensions = ['el', 'txt', 'dat', 'csv', 'exe', 'out']\n for ext in fileExtensions:\n name = re.sub(r'\\.'+'{}$'.format(ext), '', name)\n name = re.sub(r'\\.', '_', name)\n return name\n\ndef SetPueschelStyle(axes):\n \"\"\"Set a graph style like prof. pueschel.\n \n Style includes a grey backgroud, a horizontal grid with\n white lines.\"\"\"\n if isinstance(axes, pyplot.Figure):\n axes = axes.gca()\n if not isinstance(axes, pyplot.Axes):\n raise ValueError(\"axes must be pyplot.Figure or pyplot.Axes\")\n\n axes.set_facecolor('xkcd:light grey')\n for spine in ['top', 'right', 'bottom', 'left']:\n axes.spines[spine].set_visible(False)\n axes.grid(which='major', axis='y', color='w',\n linestyle='-', linewidth=2)\n axes.tick_params(axis='y', length=0)\n\n\ndef PlotRuntime(data, figure=None, graph=None, options=\"default\"):\n \"\"\"\"Plots the runtime of a single algorithm.\n \n Assumes data is pandas DataFrame.\"\"\"\n # check columns\n for col in [\"threads\", \"trial_time\"]:\n if not col in data.columns:\n raise ValueError(\"columns require label '{}'\".format(col))\n\n if figure==None:\n figure = pyplot.figure()\n ax = figure.gca()\n\n if options == \"default\":\n options = defaultOptions()\n\n if options[\"pooling\"]=='mean':\n algTime = data.groupby(['threads']).mean()\n elif options[\"pooling\"]=='median':\n algTime = data.groupby(['threads']).median()\n else:\n raise ValueError(\"Unknown pooling strategy\")\n \n if \"algorithm\" in options:\n algorithm = options[\"algorithm\"]\n elif \"algorithm\" in data.columns:\n algorithm = data[\"algorithm\"].iloc[0]\n else:\n algorithm= None\n\n if algorithm==None:\n ax.plot(algTime.index, algTime['trial_time'])\n else:\n ax.plot(algTime.index, algTime['trial_time'], label=algorithm)\n ax.legend(loc='upper right')\n ax.set_xlabel('# threads')\n ax.set_ylabel('Runtime [s]')\n if graph==None:\n title_add=''\n else:\n title_add=' [{}]'.format(graph)\n ax.set_title('Strong Scaling' + title_add)\n\n if options[\"pueschel\"]:\n SetPueschelStyle(ax)\n return figure\n\ndef PlotSpeedup(data, figure=None, graph=None, options=\"default\"):\n \"\"\"Plot the speedup of a single algorithm.\n \n Assumes data is pandas DataFrame with columns\n 'algorithm' (used as label), 'time' and 'threads'.\"\"\"\n # check columns\n for col in [\"threads\", \"trial_time\"]:\n if not col in data.columns:\n raise ValueError(\"columns require label '{}'\".format(col))\n\n if figure==None:\n figure = pyplot.figure()\n ax = figure.gca()\n\n if options == \"default\":\n options = defaultOptions()\n\n if options[\"pooling\"]=='mean':\n algTime = data.groupby(['threads']).mean()\n elif options[\"pooling\"]=='median':\n algTime = data.groupby(['threads']).median()\n else:\n raise ValueError(\"Unknown pooling strategy\")\n\n baseline = algTime.iloc[0]['trial_time']\n algTime['speedup'] = baseline/algTime['trial_time']\n\n if \"algorithm\" in options:\n algorithm = options[\"algorithm\"]\n elif \"algorithm\" in data.columns:\n algorithm = data[\"algorithm\"].iloc[0]\n else:\n algorithm= None\n\n if algorithm==None:\n ax.plot(algTime.index, algTime['speedup'])\n else:\n ax.plot(algTime.index, algTime['speedup'], label=algorithm)\n ax.legend(loc='upper left')\n ax.set_xlabel('# threads')\n ax.set_ylabel('Speedup [1]')\n if graph == None:\n title_add=''\n else:\n title_add=' [{}]'.format(graph)\n ax.set_title('Speedup'+title_add)\n\n if options[\"pueschel\"]:\n SetPueschelStyle(ax)\n return figure\n\ndef PlotPreprocessing(data, graph=None, options=\"default\"):\n \"\"\"Plot the impact of the preprocessing.\n \n Arguments:\n data: pandas DataFrame. Has columns 'pp_method', 'pp_time' and 'trial_time'\n graph: name of graph (relevant for title)\n options: dictionary with plotting options.\n\n Returns figure, ax1, ax2, ax2y2 where ax1 and ax2 are the axes of th respective subplots. ax2y2 is the secondary axis of\n the second plot.\n \"\"\"\n # check dict\n for col in [\"pp_method\", \"pp_time\", \"trial_time\"]:\n if not col in data.columns:\n raise ValueError(\"columns require label :'{}'\".format(col))\n if options == \"default\":\n options = defaultOptions()\n\n if \"threads\" in data.columns:\n maxthread = data[\"threads\"].max()\n data = data[ data[\"threads\"] == maxthread ]\n\n figure = pyplot.figure()\n ax1, ax2 = figure.subplots(1,2)\n # do preprocessing time\n if options[\"pooling\"] == 'mean':\n ppTimes = data[['pp_method', 'pp_time', 'trial_time']].groupby(['pp_method']).mean()\n elif options[\"pooling\"] == 'median':\n ppTimes = data[['pp_method', 'pp_time', 'trial_time']].groupby(['pp_method']).median()\n else:\n raise ValueError(\"Unknown pooling method\")\n \n ax1.bar(ppTimes.index, ppTimes['pp_time'])\n ax1.set_xticklabels(ppTimes.index, rotation=60)\n ax1.set_ylabel(\"time [s]\")\n ax1.set_title('Preprocessing time')\n \n # do runtime comp\n if options[\"pooling\"] == 'mean':\n nopptime = data[ data['pp_method'] == options['noPP']]['trial_time'].mean()\n elif options[\"pooling\"] == 'median':\n nopptime = data[ data['pp_method'] == options['noPP']]['trial_time'].median()\n else:\n raise ValueError(\"Unknown pooling method\")\n\n ax2.axhline(y=nopptime, color='c')\n ax2.bar(ppTimes.index, ppTimes['trial_time'])\n ax2.set_xticklabels(ppTimes.index, rotation=0)\n ax2.set_ylabel(\"time [s]\")\n\n def percentage(y):\n return 100*y/nopptime\n \n def invpercentage(y):\n return y*nopptime/100\n\n ax2y2 = ax2.secondary_yaxis('right', functions=(percentage, invpercentage) )\n ax2y2.set_ylabel('percentage [%]')\n\n if \"algorithm\" in options:\n algorithm = options[\"algorithm\"]\n elif \"algorithm\" in data.columns:\n algorithm = data[\"algorithm\"].iloc[0]\n else:\n algorithm= None\n\n if algorithm==None:\n ax2.set_title('Runtime')\n else:\n ax2.set_title('Runtime: {}'.format(algorithm))\n \n if graph==None:\n figure.suptitle('Impact of preprocessing')\n else:\n figure.suptitle('Impact of preprocessing [{}]'.format(graph))\n\n figure.SubplotParams(wspace=0.2)\n return figure, ax1, ax2, ax2y2\n\ndef createPlots(data, options, graph=None, runTimeFig=None, speedupFig=None):\n \n if options == \"default\":\n options = defaultOptions()\n\n if \"algorithm\" in options:\n algorithm = options[\"algorithm\"]\n elif \"algorithm\" in data.columns:\n algorithm = data[\"algorithm\"].iloc[0]\n else:\n algorithm= None\n\n # configure what to do\n makeRuntime = True\n for col in [\"threads\", \"trial_time\"]:\n if not col in data.columns:\n makeRuntime = False\n \n makeSpeedup = True\n for col in [\"threads\", \"trial_time\"]:\n if not col in data.columns:\n makeSpeedup = False\n \n makePP = True\n for col in [\"pp_method\", \"pp_time\", \"trial_time\"]:\n if not col in data.columns:\n makePP = False\n\n if not options[\"saveas\"] == None:\n if graph==None:\n suffix=\"_{}.{}\".format(algorithm, options[\"saveas\"])\n else:\n suffix=\"_{}_{}.{}\".format(algorithm, graph, options[\"saveas\"])\n else:\n suffix=\"\" \n\n if makeRuntime:\n runFig = PlotRuntime(data, runTimeFig, graph, options)\n if not options[\"saveas\"] == None:\n runFig.savefig(\"runtime\"+suffix)\n else:\n runFig = None\n \n if makeSpeedup:\n speedFig = PlotSpeedup(data, speedupFig, graph, options)\n if not options[\"saveas\"] == None:\n speedFig.savefig(\"speedup\"+suffix)\n else:\n speedFig = None\n\n if makePP:\n ppFig = PlotPreprocessing(data, graph, options)\n if not options[\"saveas\"] == None:\n ppFig.savefig(\"pp\"+suffix)\n else:\n ppFig = None\n\n return runFig, speedFig, ppFig\n\ndef get_kc_columns(pp=True):\n columns = dict()\n columns = dict()\n columns[\"algorithm\"] = 0\n columns[\"graphs\"] = 4\n columns[\"trial_time\"] = 5\n columns[\"threads\"] = 3\n if pp:\n columns[\"pp_method\"] = 9\n columns[\"pp_time\"] = 6\n \n\n return columns\n\n\n\n###############################################################################################################\n## \n## main part: function for plotting\n##\n## customize here\n##\n###############################################################################################################\n\ndef plotSingleAlgorithm():\n \"\"\"This function can plot Runtime, Speedup and preprocessing info for a single Algorithm.\"\"\"\n # read in data from relevant file\n filepath = \"/home/yschaffner/Dokumente/ETH/sa_graphs/cscs_output/20200109_data.csv\"\n rawdata = pd.read_csv(filepath, sep=\" \", header=None)\n\n # set the columns of the respective values for the current algorithm\n # set only what you need/want to plot\n # to plot runtime/speedup you need: \"trial_time\", \"threads\"\n # to plot preprocessing info you need: \"pp_method\", \"pp_time\"\n columns = dict()\n ## need to include in dict:\n columns[\"algorithm\"] = 0 #Column with executable name (always column 0)\n columns[\"graphs\"] = 2 #Column where the input graph is specified\n\n ## optional to include in dict:\n columns[\"trial_time\"] = 5 #Column with the trial time\n columns[\"threads\"] = 4 #Column with the number of used threads\n\n columns[\"pp_method\"] = 7 #Column with the applied preprocessing method\n columns[\"pp_time\"] = 6 #Column with the time measurement for the preprocessing\n\n \n\n # set columns explicitly (as above) or get from predefined function (as below)\n columns = get_kc_columns(True)\n\n \n ##################################################################################################\n ## do some basic preprocessing:\n # shorten file names, change name patterns of algorithm, graphs, ...\n # select relevant rows,...\n data = rawdata.rename(columns={ v:k for k,v in columns.items()})\n data.loc[:,\"algorithm\"] = data[\"algorithm\"].apply(basename)\n\n \n\n ###################################################################################################\n ## define which algorithm you wish to plot (name the executble)\n selectedAlgorithm = \"clique_count_danisch_nodeParallel\"\n\n algData = data[ data[\"algorithm\"] == selectedAlgorithm].copy()\n # => apply some cosmetic changes. Perform as suits you best\n algData.loc[:,\"algorithm\"] = algData[\"algorithm\"].apply(lambda arg : re.sub(\"clique_count_danisch\", \"cc\", arg))\n algData.loc[:,\"graphs\"] = algData[\"graphs\"].apply(shortenGraphName) \n algData.loc[:,\"pp_method\"] = algData[\"pp_method\"].apply(lambda arg: re.sub(\"degeneracy\", \"deg\", arg))\n\n ## define options for plotting\n options = defaultOptions()\n options[\"pueschel\"] = True #True: use pueschel graph style, False: use default style\n options[\"saveas\"] = \"png\" #set to None to not save to disk\n\n # convert data types\n if \"trial_time\" in columns:\n algData.loc[:,\"trial_time\"] = algData[\"trial_time\"].astype(float)\n if \"pp_time\" in columns:\n algData.loc[:,\"pp_time\"] = algData[\"pp_time\"].astype(float)\n if \"threads\" in columns:\n algData.loc[:,\"threads\"] = algData[\"threads\"].astype(int)\n graphGroups = algData.groupby([\"graphs\"])\n for key, group in graphGroups:\n createPlots(group, graph=key, options=options)\n\nif __name__ == \"__main__\":\n ## to plot information of a single algorithm\n plotSingleAlgorithm()\n\n\n\n\n\n"
]
| [
[
"pandas.read_csv",
"matplotlib.pyplot.figure"
]
]
|
ianhi/animatplot | [
"632d988687fca7e7415e9fa49fe7eebc3f0991c6"
]
| [
"animatplot/blocks/base.py"
]
| [
"import matplotlib.pyplot as plt\n\n\nclass Block:\n \"\"\"A base class for blocks\n\n Parameters\n ----------\n ax : matplotlib.axes.Axes, optional\n The matplotlib axes to attach the animation to.\n Defaults to matplotlib.pyplot.gca()\n t_axis : int, optional\n The axis of the data that represents time.\n\n Attributes\n ----------\n ax : matplotlib.axes.Axes\n The matplotlib axes that the block is attached to.\n \"\"\"\n def __init__(self, ax=None, t_axis=None):\n self.ax = ax if ax is not None else plt.gca()\n self.t_axis = t_axis\n self._is_list = False\n\n def _init(self):\n \"\"\"initialize the animation.\n\n To be (optionally) implemented by subclasses\n \"\"\"\n pass\n\n def _update(self, i):\n \"\"\"updates the block to display the corresponding frame i.\n\n To be implemented by subclasses\n \"\"\"\n raise NotImplementedError()\n\n def __len__(self):\n \"\"\"Returns the length of the 'time' axis\"\"\"\n raise NotImplementedError()\n\n def _make_slice(self, i, dim):\n \"\"\"A helper function to slice arrays or lists\"\"\"\n if self._is_list:\n return i\n Slice = [slice(None)]*dim\n Slice[self.t_axis] = i\n return tuple(Slice)\n"
]
| [
[
"matplotlib.pyplot.gca"
]
]
|
jennahamlin/nf-core-mashwrapper | [
"621e68fa1f1b37bd1dfd2795f4b56d6e7bff0a92"
]
| [
"bin/run_species_id.py"
]
| [
"#!/usr/bin/env python3.7\n\nimport argparse, sys, os\nimport logging\nimport shutil\nimport subprocess\nimport pandas as pd\nfrom io import StringIO\nfrom datetime import datetime\nfrom tabulate import tabulate\n\n#############################\n## Argument Error Messages ##\n#############################\n\n## create class of formatted error messages\n## input variable is argparse.ArgumentParser, which initializes the parser\nclass ParserWithErrors(argparse.ArgumentParser):\n def error(self, message):\n print('\\n{0}\\n\\n'.format(message))\n self.print_help()\n sys.exit(2)\n\n def is_valid_mash(self, parser, arg):\n base, ext = os.path.splitext(arg)\n if ext not in ('.msh') or ext in ('') :\n parser.error('This is not a file ending with .msh.\\\n Did you generate the mash sketch and specified that file to be uploaded?')\n else:\n return arg\n\n def is_valid_fastq(self, parser, arg):\n base, ext = os.path.splitext(arg)\n if ext not in ('.gz', '.fastq', '.fastq.gz'):\n parser.error('This is not a file ending with either .fastq or \\\n.fastq.gz. This flag requires the input of a fastq file.')\n else:\n return arg\n\n def is_valid_distance(self, parser, arg):\n isFloat = True\n try:\n float(arg)\n except ValueError:\n isFloat = False\n if (isFloat == False) or (float(arg) < 0) :\n parser.error('%s is not a positive number (e.g., a float, aka a \\\n number with a decimal point)' % arg)\n else:\n return arg\n\n def is_valid_int(self, parser, arg):\n isInt = True\n try:\n int(arg)\n except ValueError:\n isInt = False\n if isInt == False:\n parser.error(\"You input %s. This is NOT an integer.\" % arg)\n elif arg.isnumeric() == False:\n parser.error(\"You input %s. This is NOT a positive number.\" % arg)\n else:\n return arg\n\n#########################\n## ArgParser Arguments ##\n#########################\n\ndef argparser():\n \"\"\"\n Returns an argument parser for this script\n \"\"\"\n description = \"\"\" A script to parse the output from Mash into a table \\\n listing the top five matches from the user specified pre-built Mash Database.\n \"\"\"\n\n ## use class to parse the arguments with formatted error message\n parser = ParserWithErrors(description = description)\n\n ## Define required and optional groups\n parser._action_groups.pop()\n required = parser.add_argument_group('Required Arguments')\n optional = parser.add_argument_group('Optional Arguments')\n\n required.add_argument(\"--database\", \"-b\", required=True,\n help=\"Pre-built Mash Sketch\",\n type=lambda x: parser.is_valid_mash(parser, x))\n required.add_argument(\"--read1\", \"-r1\", required=True,\n help=\"Input Read 1 (forward) file\",\n type=lambda x: parser.is_valid_fastq(parser, x))\n required.add_argument(\"--read2\", \"-r2\", required=True,\n help=\"Input Read 2 (reverse) file\",\n type=lambda x: parser.is_valid_fastq(parser, x))\n optional.add_argument(\"--max_dist\", \"-d\", default=0.05,\n help=\"User specified mash distance (default: 0.05)\",\n type=lambda x: parser.is_valid_distance(parser, x))\n optional.add_argument(\"--kmer_min\", \"-m\", default=2,\n help=\"Minimum copies of kmer count (default: 2)\",\n type=lambda x: parser.is_valid_int(parser, x))\n optional.add_argument(\"--num_threads\", \"-p\", default=2,\n help=\"Number of computing threads to use (default: 2)\",\n type=lambda x: parser.is_valid_int(parser, x))\n return parser\n\n###############\n## FUNCTIONS ##\n###############\ndef fastq_name(inRead1):\n \"\"\"\n Gets stripped read name for appending to output files\n\n Parameters\n ----------\n inRead1 : xx\n xxx\n\n Returns\n -------\n xxx\n xxx\n \"\"\"\n if inRead1.endswith(\"_1.fastq\"):\n name = inRead1.split(\"_1.fastq\")[0]\n return(name)\n elif inRead1.endswith(\"_R1_001.fastq\"):\n name = inRead1.split(\"_R1_001.fastq\")[0]\n return(name)\n else:\n logging.critical(\"Please check your file endings, assumes either \\\n_1.fastq(.gz) or _R1_001.fastq(.gz)\")\n sys.exit(1)\n\ndef make_output_log(log):\n \"\"\"\n Makes the output directory and the log file\n\n Parameters\n ----------\n log : str\n Name of the log file\n\n Returns\n -------\n None\n Exits the program if unable to make output directory\n \"\"\"\n logging.basicConfig(filename=log, filemode=\"a\", level=logging.DEBUG,\n format=\"%(asctime)s - %(message)s\", datefmt=\"%m/%d/%Y %I:%M:%S %p\")\n logging.info(\"New log file created in output directory - %s... \" % log)\n logging.info(\"Starting the tool...\")\n\n\ndef get_input(inRead1, inRead2, inMash, inMaxDis, inKmer, inThreads):\n \"\"\"\n Prints the command line input to the log file\n\n Parameters\n ----------\n inRead1 : str\n XXX\n inRead2 : str\n XXX\n inMash : str\n XXX\n inMaxDis : str\n XXX\n inKmer : str\n XXX\n inThreads : str\n XXX\n\n Returns\n -------\n None\n XXX\n \"\"\"\n\n logging.info(\"The input parameters... \\n \\n \\\n * Read1: %s \\n \\\n * Read2: %s \\n \\\n * Mash Databse: %s \\n \\\n * Maximum Distance: %s \\n \\\n * Minimum Kmer Count: %s \\n \\\n * Number of Threads: %s \\n \" %\n (inRead1, inRead2, inMash, inMaxDis, inKmer, inThreads))\n\ndef check_files(inRead1, inRead2, inMash):\n \"\"\"\n Checks if all the input files exists; exits if file not found or if file is\n a directory\n\n Parameters\n ----------\n inRead1 : XX\n XXX\n inRead2 : XX\n XXX\n inMash : XX\n XXX\n Returns\n -------\n None\n Exits the program if file doesn't exist\n \"\"\"\n\n if inMash and not os.path.isfile(inMash):\n logging.critical(\"The database - %s - doesn't exist. Exiting.\" % inMash)\n sys.exit(1)\n if inRead1 and not os.path.isfile(inRead1):\n logging.critical(\"Read file 1: %s doesn't exist. Exiting.\" % inRead1)\n sys.exit(1)\n if inRead2 and not os.path.isfile(inRead2):\n logging.critical(\"Read file 2: %s doesn't exist. Exiting.\" % inRead2)\n sys.exit(1)\n if inRead1 == inRead2:\n logging.critical(\"Read1 - %s\" % inRead1)\n logging.critical(\"Read2 - %s\" % inRead2)\n logging.critical(\"Looks like you entered the same read file twice. \\\n Exiting.\")\n sys.exit(1)\n##TO DO: - do i want to check if the beginning of the file name is a match between the two files?\n\ndef check_program(program_name):\n \"\"\"\n Checks if the supplied program_name exists\n\n Parameters\n ----------\n program_name : str\n Name of the program to check if it exists\n\n Returns\n -------\n None\n Exits the program if a dependency doesn't exist\n \"\"\"\n ##assumes that program name is lower case\n logging.info(\"Checking for program %s...\" % program_name)\n path = shutil.which(program_name)\n ver = sys.version_info[0:3]\n ver = ''.join(str(ver))\n ver = ver.replace(\",\", \".\")\n ver = ver.replace('(','').replace(')','')\n\n if path != None:\n if program_name == 'python' and sys.version_info >= (3,7):\n logging.info(\"Great, the program %s is loaded ...\" % program_name)\n logging.info(\"The version of python is: %s...\" % ver)\n elif program_name != 'python':\n logging.info(\"Great, the program %s is loaded...\" % program_name)\n else:\n logging.info(\"You do not have an appropriate version of python. \\\n Requires Python version >= 3.7. Exiting.\")\n sys.exit(1)\n else:\n logging.critical(\"Program %s not found! Cannot continue; dependency\\\n not fulfilled. Exiting.\" % program_name)\n sys.exit(1)\n\ndef cat_files(inRead1, inRead2):\n \"\"\"\n XXXX\n\n Parameters\n ----------\n inRead1 : XX\n XXX\n inRead2 : XX\n XXX\n\n Returns\n -------\n None\n XXX\n \"\"\"\n if inRead1 and inRead2 != None and inRead1.endswith('.gz'):\n logging.critical(\"The files are still gzipped. Exiting\")\n sys.exit(1)\n else:\n logging.info(\"The files have been gunzipped ...\")\n with open(inRead1) as readFile:\n read1 = readFile.read()\n with open(inRead2) as readFile:\n read2 = readFile.read()\n read1 += read2\n with open('myCatFile', 'w') as readFile:\n readFile.write(read1)\n readFile.close()\n\ndef minKmer(calculatedKmer, inKmer):\n \"\"\"\n Determine the value of the kmers (-m flag); if less than 2, set as 2\n\n Parameters\n ----------\n calculatedKmer : int\n Value that is calculated based on genomeCoverage/3\n inKmer : int, optional, default is 2\n Input kmer value specified by user; to be used instead of calucated\n\n Returns\n ----------\n int\n integer value used for min_kmer (-m flag) with paired-end reads\n \"\"\"\n if int(inKmer) == 2:\n logging.info(\"Should kmer value be different than default (2)...\")\n logging.info(\"Min. kmer = genome coverage divided by 3...\" )\n #return calculatedKmer\n if (calculatedKmer < 2 or int(inKmer) < 2):\n logging.info(\"The calucated kmer is less than 2, so will use 2...\")\n calculatedKmer = 2\n return calculatedKmer\n elif (int(inKmer) > 2):\n logging.info(\"User specified a value for minimum kmer: %s ...\" % inKmer)\n return int(inKmer)\n\ndef run_cmd(command):\n \"\"\"\n XXXX\n\n Parameters\n ----------\n XX : XX\n XXX\n\n Returns\n -------\n XXX : XXX\n XXX\n \"\"\"\n\n try:\n result = subprocess.run(command, capture_output=True,\\\n check=True, text=True)\n logging.info(\"This is the command... \\n %s \" % command)\n except subprocess.CalledProcessError:\n logging.critical(\"CRITICAL ERROR. The following command had an improper\\\n error: \\n %s .\" % command)\n sys.exit(1)\n return result\n\ndef cal_kmer():\n \"\"\"\n XXXX\n\n Parameters\n ----------\n XX : XX\n XXX\n\n Returns\n -------\n mFlag : tuple, position 0\n XXX\n \"\"\"\n\n f = open('myCatFile', 'r')\n fastqCmd1 = ['mash', 'dist', inMash, '-r', 'myCatFile', '-p', inThreads, '-S', '42']\n\n outputFastq1 = run_cmd(fastqCmd1)\n\n ## get genome size and coverage; will provide as ouput for user\n gSize = outputFastq1.stderr.splitlines()[0]\n gSize = gSize[23:]\n logging.info(\"Estimated Genome Size: %s \" % gSize)\n gCoverage = outputFastq1.stderr.splitlines()[1]\n gCoverage = gCoverage[23:]\n logging.info(\"Estimated Genome coverage: %s \"% gCoverage)\n\n minKmers = int(float(gCoverage))/3\n minKmers = int(float(minKmers))\n\n ## this is used the calucate the minimum kmer copies to use (-m flag)\n mFlag = minKmer(minKmers, inKmer) # returned as an integer\n return mFlag, gSize, gCoverage\n\n\ndef get_results(mFlag, inThreads):\n fastqCmd2 = ['mash', 'dist', '-r', '-m', str(mFlag), inMash, 'myCatFile', '-p', inThreads, '-S', '123456']\n outputFastq2 = run_cmd(fastqCmd2)\n #os.remove('myCatFile')\n return outputFastq2\n\ndef isTie(df):\n \"\"\"\n Determine if the kmers count value is a tie with the second top isolate; if\n so then indicate a tie was found in the results\n\n Parameters\n ----------\n df : pandas data frame\n\n Returns\n ----------\n str\n string of best genus either genus or a sentence\n str\n string of best species either species or a blank string\n\n \"\"\"\n dfSort = df.sort_values('KmersCount', ascending=False)\n logging.info(\"Checking if matching kmers count is tied for top 2 results...\")\n\n ## assumes based on position the first and second value are always\n ## column 11; row 1 and 2\n if dfSort.iloc[0:1, 10:11].equals(dfSort.iloc[1:2, 10:11]):\n bestGenus = \"This was a tie, see the top 5 results below\"\n bestSpecies = \" \"\n logging.info(\"The top two isolates have the same number of matching\\\nkmers, indicating a tie... \")\n return bestGenus, bestSpecies\n else:\n best = dfSort.head(1)\n bestGenus = best['Genus']\n bestGenus = bestGenus.str.cat(sep='\\n')\n bestSpecies = best['Species']\n bestSpecies = bestSpecies.str.cat(sep='\\n')\n logging.info(\"There was not a tie of kmers for the top two species...\")\n return bestGenus, bestSpecies\n\ndef noResult(inFile, inMaxDis, bestG, bestS):\n \"\"\"\n Determine if top hit mash distances are >= user specified mash distance\n\n Parameters\n ----------\n inFile : pandas core frame data frame\n Parsed results from running mash\n inDist : int\n User specified maximum mash distance as a cut-off\n\n Returns\n ----------\n Message to log file and replacement of best species with message\n \"\"\"\n inMaxDis = float(inMaxDis)\n logging.info(\"Confirming that best match is less than user specfied distance...\")\n\n if (inFile['Mash Dist'].values[0] < inMaxDis):\n logging.info(\"Okay, a best species match was found with mash distance \\\nless than %s...\" % inMaxDis)\n else:\n bestG = \"No matches found with mash distances < %s...\" % inMaxDis\n bestS = \" \"\n logging.info(\"No matches found with mash distances < %s...\" % inMaxDis)\n return bestG, bestS\n\ndef parseResults(cmd, inMaxDis):\n \"\"\"\n run initial command and parse the results from mash\n\n Parameters\n ----------\n cmd : list\n Initial command to run for either fasta or fastq\n inMaxDis : XXX\n XXX\n\n Returns\n ----------\n bestGenus\n The most likely genus of the isolate tested\n bestSpecies\n The most likely species of the isolate tested\n dfTop\n The top five results from sorting Mash output\n \"\"\"\n\n ## convert with StringIO and added headers (for development)\n df = pd.read_csv(StringIO(cmd.stdout), sep='\\t',\n names=['Ref ID', 'Query ID', 'Mash Dist', 'P-value', 'Kmer'],\n index_col=False)\n\n dfGenus = df['Ref ID'].str.split('_', 1, expand=True)\n tmpDF = pd.DataFrame(columns=['Genus', 'Species', 'GeneBank Identifier', '% Seq Sim'])\n tmpDF['Genus'] = dfGenus[0]\n\n dfSpecies = dfGenus.iloc[:, -1].str.split('_', 1, expand=True)\n tmpDF['Species'] = dfSpecies[0]\n\n dfGB = dfSpecies.iloc[:, -1].str.split('GCA', expand=True)\n dfGB = 'GCA' + dfGB.iloc[:,-1]\n tmpDF['GeneBank Identifier'] = dfGB\n\n df = df.join(tmpDF)\n\n ## split the kmers for sorting because xx/xxxx\n df[['KmersCount','sketchSize']] = df.Kmer.str.split(\"/\", expand=True,)\n df['KmersCount'] = df.KmersCount.astype(int)\n\n ## add column that is (1 - Mash Distance) * 100, which is % sequence similarity\n df['% Seq Sim'] = (1 - df['Mash Dist'])*100\n\n ## now sort and get top species; test for a tie in kmerscount value\n dfSorted = df.sort_values('KmersCount', ascending=False)\n dfSortOut = isTie(dfSorted)\n bestGenusSort = dfSortOut[0]\n bestSpeciesSort = dfSortOut[1]\n\n ## use column (axis = 1), to create minimal dataframe\n dfSortedDropped = dfSorted.drop(['Ref ID', 'Query ID', 'KmersCount',\n 'sketchSize' ], axis=1)\n\n ## noResult function - confirm mash distance is < than user specified\n ## even if mash distance !< user specified, return the top five hits\n noMash = noResult(dfSortedDropped, inMaxDis, bestGenusSort, bestSpeciesSort)\n bestGenus = noMash[0]\n bestSpecies = noMash[1]\n\n # change order\n dfSortedDropped = dfSortedDropped[['Genus', 'Species', 'GeneBank Identifier',\n 'Mash Dist', '% Seq Sim', 'P-value', 'Kmer']]\n dfTop = dfSortedDropped[:5]\n\n##TO DO - scienfitic notation for P-value\n\n dfTop.reset_index(drop=True, inplace=True) #make index start at 0\n return bestGenus, bestSpecies, dfTop\n\ndef makeTable(dateTime, name, inRead1, inRead2, inMaxDist, results, mFlag):\n \"\"\"\n Parse results into text output and include relavant variables\n\n Parameters\n ----------\n dataTime : str\n get current date and time for when analysis is run\n maxDist : float, optional\n optional input to specify the value of maximum mash distance\n results : tuple\n output from running and parsing mash commands\n\n Returns\n ----------\n txt file\n text file with each isolates results appended that were run through\n\n \"\"\"\n\n with open(f\"{name}_results_{dateString}.txt\" ,'a+') as f:\n f.writelines(\"\\n\" + \"Legionella Species ID Tool using Mash\" + \"\\n\")\n f.writelines(\"Date and Time = \" + dtString + \"\\n\") #+str(variable)\n f.write(\"Input query file 1: \" + inRead1 + \"\\n\")\n f.write(\"Input query file 2: \" + inRead2 + \"\\n\")\n f.write(\"Genome size estimate for fastq files: \" + mFlag[1] + \" \" +\"(bp)\" +\"\\n\") #make into variable\n f.write(\"Genome coverage estimate for fastq files: \" + mFlag[2] + \"\\n\") #make into variables\n f.write(\"Maximum mash distance (-d): \" + str(inMaxDis) + \"\\n\")\n f.write(\"Minimum kmer copy number (-m) to be included in the sketch: \" + str(mFlag[0]) + \"\\n\" + \"\\n\")\n f.write(\"Best species match: \" + results[0] + \" \" + results[1] + \"\\n\" + \"\\n\")\n f.write(\"Top 5 hits:\" + \"\\n\")\n f.writelines(u'\\u2500' * 100 + \"\\n\")\n f.writelines(tabulate(results[2], headers='keys', tablefmt='pqsl', numalign=\"center\", stralign=\"center\")+ \"\\n\")\n\nif __name__ == '__main__':\n\n ## parser is created from the function argparser\n ## parse the arguments\n parser = argparser()\n args = parser.parse_args()\n\ninMash = args.database\ninMaxDis = args.max_dist\ninKmer = args.kmer_min\ninThreads = args.num_threads\ninRead1 = args.read1\ninRead2 = args.read2\n\nnow = datetime.now()\ndtString = now.strftime(\"%B %d, %Y %H:%M:%S\")\ndateString = now.strftime(\"%Y-%m-%d\")\n\n#unique name for log file based on read name\nname = fastq_name(inRead1)\nlog = name + \"_run\" + \".log\"\n\nreq_programs=['mash', 'python']\n\nmake_output_log(log)\nget_input(inRead1, inRead2, inMash, inMaxDis, inKmer, inThreads)\n\nlogging.info(\"Checking if all the required input files exist...\")\ncheck_files(inRead1, inRead2, inMash)\nlogging.info(\"Input files are present...\")\n\nlogging.info(\"Checking if all the prerequisite programs are installed...\")\nfor program in req_programs:\n check_program(program)\nlogging.info(\"All prerequisite programs are accessible...\")\n\nlogging.info(\"Begin concatenation of the fastq files...\")\ncat_files(inRead1, inRead2)\nlogging.info(\"Great, I was able to concatenate the files...\")\n\nlogging.info(\"Calculating estimated genome size and coverage...\")\nmFlag = cal_kmer()\nlogging.info(\"Minimum copies of each kmer required to pass noise filter \\\nidentified ...\")\n\nlogging.info(\"Running Mash Dist command with -m flag...\")\noutputFastq2 = get_results(mFlag[0], inThreads)\nlogging.info(\"Completed running mash dist command...\")\n\nlogging.info(\"Beginning to parse the output results from mash dist...\")\nresults = parseResults(outputFastq2, inMaxDis)\nlogging.info(\"Okay, completed parsing of the results...\")\n\nlogging.info(\"Generating table of results as a text file...\")\nmakeTable(dtString, name, inRead1, inRead2, inMaxDis, results, mFlag)\nlogging.info(\"Completed analysis for the sample: %s...\" % name )\n"
]
| [
[
"pandas.DataFrame"
]
]
|
darrida/Detect-and-Move-Blury-Images--using-Open-CV- | [
"7c3c702ce362cc77e2f9594a7c00baa40be24288"
]
| [
"working_sample/2017.12.31/findedges.py"
]
| [
"from PIL import Image\nfrom PIL import ImageFilter\n#from IPython.display import Image as JubImage\nimport numpy\n\n# NOTE: last try before it somehow worked was pip3 install opencv-python\n#\n# Sorts pictures in current directory into two subdirs, blurred and ok\n# Found original here: https://photo.stackexchange.com/questions/20432/is-there-photo-analysis-software-which-will-pre-sort-images-by-identifying-poten\n# Modified for my own purposes.\n#\n\n# stock python libs\nimport os, shutil, re, sys\n# additional libs\n#import cv2\nfrom pathlib import Path\n\n# DEFAULTS\nFOCUS_THRESHOLD = 20\nDIRECTORY = Path.cwd()\nEXT = '.JPG'\n\nHELP_MESSAGE = f\"\"\"\nThis tool assists with blur dectection on images. The follow parameters are available:\n\nFOCUS_THRESHOLD => --focus <int> [0-100]\n DIRECTORY => --dir <path> [i.e., ./dir1/dir2/dir3 or C:/dir1/dir2/dir3]\n EXT => --ext <ext> [.jpg, jpeg, etc]\n \nDefaults for each are the following => FOCUS_THRESHOLD: {FOCUS_THRESHOLD} | DIRECTORY: {DIRECTORY} | EXT: {EXT}\n\"\"\"\narguments = len(sys.argv)\nposition = 1\nwhile position < arguments:\n if sys.argv[position] == '--focus':\n FOCUS_THRESHOLD = sys.argv[position + 1]\n if isinstance(int(FOCUS_THRESHOLD), int):\n FOCUS_THRESHOLD = int(FOCUS_THRESHOLD)\n else:\n print('ERROR: --focus parameter did not meet int requirements. See \"--help\" for options.')\n exit()\n elif sys.argv[position] == '--ext':\n EXT = sys.argv[position + 1]\n elif sys.argv[position] == '--dir':\n DIRECTORY = Path(sys.argv[position + 1])\n elif sys.argv[position] == '--help':\n print(HELP_MESSAGE)\n exit()\n elif sys.argv[position] == '--h':\n print(HELP_MESSAGE)\n exit()\n position = position + 1\n #elif sys.argv[position] and sys.argv[position] != re.match('^--', sys.argv[position]):\n # print('\\nERROR: INVALID ARGUMENT. See the --help information below.\\n' + HELP_MESSAGE)\n # exit()\n position = position + 1\n\nprint(f\"PARAMETERS => FOCUS_THRESHOLD: {FOCUS_THRESHOLD} | DIRECTORY: '{DIRECTORY}' | EXT: {EXT}. For options, use '--help'\")\n\nBLURRED_DIR = 'blurred'\nOK_DIR = 'ok'\n\nblur_count = 0\n\nprint(str(Path.cwd()) + '\\\\' + str(DIRECTORY))\nfiles = [f for f in os.listdir(DIRECTORY) if f.endswith(EXT)]\n\ntry:\n os.makedirs(BLURRED_DIR)\n os.makedirs(OK_DIR)\nexcept:\n pass\n\nnext = 'y'\nfor infile in files:\n if next == 'n':\n exit()\n else:\n print(f'Processing file {infile}... {DIRECTORY}\\{infile}')\n print(str(Path.cwd()) + '\\\\' + str(DIRECTORY) + '\\\\' + infile)\n image = Image.open(infile)\n print(infile)\n h1 = image.histogram()\n zero = 0\n not_zero = 0\n for i in h1:\n if i < 150:\n zero = zero + i\n else:\n not_zero = not_zero + i\n print(f'Original: {zero} zeros vs {not_zero} not_zeros, median: {numpy.median(h1)}')\n #arr1 = numpy.array(image)\n #print(image.getdata())\n imageWithEdges = image.filter(ImageFilter.FIND_EDGES)\n h2 = imageWithEdges.histogram()\n #print(h2)\n zero = 0\n not_zero = 0\n for i in h2:\n if i < 150:\n zero = zero + i\n else:\n not_zero = not_zero + i\n print(f'Filtered: {zero} zeros vs {not_zero} not_zeros, median: {numpy.median(h2)}')\n #image_file = image_file.convert('1')\n \n\n bw = imageWithEdges.convert('L')\n bw.show()\n\n black = 0\n white = 0\n\n for pixel in bw.getdata():\n #print(pixel)\n if pixel == (0): # if your image is RGB (if RGBA, (0, 0, 0, 255) or so\n black += 1\n elif pixel == (255):\n white += 1\n print(f'Black: {str(black)} | White: {str(white)} | B/W Ratio: {str(white/black)}')\n #imageWithEdges.show()\n #arr2 = numpy.array(imageWithEdges)\n #diff = arr1 - arr2\n #new_image = Image.fromarray(diff)\n #new_image.show()\n #print(arr1)\n #print(arr2)\n next = input('y for next, n for stop: ')"
]
| [
[
"numpy.median"
]
]
|
nettourist/ex_pandas | [
"61998b448ef21d19389dc43943faf4b6ac2ab929"
]
| [
"main.py"
]
| [
"# -*- coding: utf-8 -*-\n# -*- vk.com/nettourist -*-\nimport pandas as pd\n\ndefault = pd.read_excel (r'data/default.xlsx')\nkeys = pd.read_excel (r'data/keys.xlsx')\n\nwhile True:\n search = input('[1] Default\\n[2] Keys\\nPress: ')\n if search in ['1']:\n print (default)\n\n if search in ['2']:\n print (keys)\n"
]
| [
[
"pandas.read_excel"
]
]
|
Fanta007/Graph-U-Nets | [
"96fcd45fd1f486d2e9e45cde169b7cadaca86247"
]
| [
"network.py"
]
| [
"from __future__ import print_function\nimport os\nimport ops\nimport sys\nimport torch\nfrom torch.autograd import Variable\nimport torch.nn as nn\nimport torch.nn.functional as F\nsys.path.append('%s/pytorch_structure2vec-master/s2v_lib' % os.path.dirname(\n os.path.realpath(__file__)))\nfrom s2v_lib import S2VLIB # noqa\nfrom pytorch_util import weights_init, gnn_spmm # noqa\n\n\nclass GUNet(nn.Module):\n def __init__(self, output_dim, num_node_feats, num_edge_feats,\n latent_dim=[32, 32, 32, 1], k=30, conv1d_channels=[16, 32],\n conv1d_kws=[0, 5]):\n print('Initializing GUNet')\n super(GUNet, self).__init__()\n self.latent_dim = latent_dim\n self.output_dim = output_dim\n self.num_node_feats = num_node_feats\n self.num_edge_feats = num_edge_feats\n self.k = k\n self.total_latent_dim = sum(latent_dim)\n conv1d_kws[0] = self.total_latent_dim\n\n self.conv_params = nn.ModuleList()\n self.conv_params.append(nn.Linear(num_node_feats, latent_dim[0]))\n for i in range(1, len(latent_dim)):\n self.conv_params.append(nn.Linear(latent_dim[i-1], latent_dim[i]))\n\n self.conv1d_params1 = nn.Conv1d(\n 1, conv1d_channels[0], conv1d_kws[0], conv1d_kws[0])\n self.maxpool1d = nn.MaxPool1d(2, 2)\n self.conv1d_params2 = nn.Conv1d(\n conv1d_channels[0], conv1d_channels[1], conv1d_kws[1], 1)\n\n dense_dim = int((k - 2) / 2 + 1)\n self.dense_dim = (dense_dim - conv1d_kws[1] + 1) * conv1d_channels[1]\n\n if num_edge_feats > 0:\n self.w_e2l = nn.Linear(num_edge_feats, latent_dim)\n if output_dim > 0:\n self.out_params = nn.Linear(self.dense_dim, output_dim)\n # ks = [4000, 3000, 2000, 1000]\n ks = [0.9, 0.7, 0.6, 0.5]\n# self.gUnet = ops.GraphUnet(ks, num_node_feats, 97).cuda()\n self.gUnet = ops.GraphUnet(ks, num_node_feats, 97)\n \n weights_init(self)\n\n def forward(self, graph_list, node_feat, edge_feat):\n graph_sizes = [graph_list[i].num_nodes for i in range(len(graph_list))]\n node_degs = [torch.Tensor(graph_list[i].degs) + 1\n for i in range(len(graph_list))]\n node_degs = torch.cat(node_degs).unsqueeze(1)\n\n n2n_sp, e2n_sp, subg_sp = S2VLIB.PrepareMeanField(graph_list)\n\n if isinstance(node_feat, torch.cuda.FloatTensor):\n n2n_sp = n2n_sp.cuda()\n e2n_sp = e2n_sp.cuda()\n subg_sp = subg_sp.cuda()\n node_degs = node_degs.cuda()\n node_feat = Variable(node_feat)\n if edge_feat is not None:\n edge_feat = Variable(edge_feat)\n n2n_sp = Variable(n2n_sp)\n e2n_sp = Variable(e2n_sp)\n subg_sp = Variable(subg_sp)\n node_degs = Variable(node_degs)\n\n h = self.sortpooling_embedding(\n node_feat, edge_feat, n2n_sp, e2n_sp, subg_sp, graph_sizes,\n node_degs)\n return h\n\n def sortpooling_embedding(self, node_feat, edge_feat, n2n_sp, e2n_sp,\n subg_sp, graph_sizes, node_degs):\n ''' if exists edge feature, concatenate to node feature vector '''\n if edge_feat is not None:\n input_edge_linear = self.w_e2l(edge_feat)\n e2npool_input = gnn_spmm(e2n_sp, input_edge_linear)\n node_feat = torch.cat([node_feat, e2npool_input], 1)\n\n ''' graph convolution layers '''\n A = ops.normalize_adj(n2n_sp)\n\n ver = 2\n\n if ver == 2:\n cur_message_layer = self.gUnet(A, node_feat)\n else:\n lv = 0\n cur_message_layer = node_feat\n cat_message_layers = []\n while lv < len(self.latent_dim):\n n2npool = gnn_spmm(n2n_sp, cur_message_layer) + cur_message_layer # noqa\n node_linear = self.conv_params[lv](n2npool) # Y = Y * W\n normalized_linear = node_linear.div(node_degs) # Y = D^-1 * Y\n cur_message_layer = F.tanh(normalized_linear)\n cat_message_layers.append(cur_message_layer)\n lv += 1\n\n cur_message_layer = torch.cat(cat_message_layers, 1)\n\n ''' sortpooling layer '''\n sort_channel = cur_message_layer[:, -1]\n batch_sortpooling_graphs = torch.zeros(\n len(graph_sizes), self.k, self.total_latent_dim)\n if isinstance(node_feat.data, torch.cuda.FloatTensor):\n batch_sortpooling_graphs = batch_sortpooling_graphs.cuda()\n\n batch_sortpooling_graphs = Variable(batch_sortpooling_graphs)\n accum_count = 0\n for i in range(subg_sp.size()[0]):\n to_sort = sort_channel[accum_count: accum_count + graph_sizes[i]]\n k = self.k if self.k <= graph_sizes[i] else graph_sizes[i]\n _, topk_indices = to_sort.topk(k)\n topk_indices += accum_count\n sortpooling_graph = cur_message_layer.index_select(0, topk_indices)\n if k < self.k:\n to_pad = torch.zeros(self.k-k, self.total_latent_dim)\n if isinstance(node_feat.data, torch.cuda.FloatTensor):\n to_pad = to_pad.cuda()\n\n to_pad = Variable(to_pad)\n sortpooling_graph = torch.cat((sortpooling_graph, to_pad), 0)\n batch_sortpooling_graphs[i] = sortpooling_graph\n accum_count += graph_sizes[i]\n\n ''' traditional 1d convlution and dense layers '''\n to_conv1d = batch_sortpooling_graphs.view(\n (-1, 1, self.k * self.total_latent_dim))\n conv1d_res = self.conv1d_params1(to_conv1d)\n conv1d_res = F.relu(conv1d_res)\n conv1d_res = self.maxpool1d(conv1d_res)\n conv1d_res = self.conv1d_params2(conv1d_res)\n conv1d_res = F.relu(conv1d_res)\n\n to_dense = conv1d_res.view(len(graph_sizes), -1)\n\n if self.output_dim > 0:\n out_linear = self.out_params(to_dense)\n reluact_fp = F.relu(out_linear)\n else:\n reluact_fp = to_dense\n\n return F.relu(reluact_fp)\n"
]
| [
[
"torch.Tensor",
"torch.cat",
"torch.zeros",
"torch.nn.ModuleList",
"torch.nn.MaxPool1d",
"torch.nn.Linear",
"torch.nn.functional.relu",
"torch.nn.Conv1d",
"torch.nn.functional.tanh",
"torch.autograd.Variable"
]
]
|
chriscohoat/3DDFA_V2 | [
"35815c91acc2cb7ba0450ba4a318eb4e7e3b3928"
]
| [
"utils/serialization.py"
]
| [
"# coding: utf-8\n\n__author__ = 'cleardusk'\n\nimport numpy as np\n\nfrom utils.pose import calc_pose\n\nfrom .tddfa_util import _to_ctype\nfrom .functions import get_suffix\nimport matplotlib.pyplot as plt\nfrom itertools import product, combinations\n\nheader_temp = \"\"\"ply\nformat ascii 1.0\nelement vertex {}\nproperty float x\nproperty float y\nproperty float z\nelement face {}\nproperty list uchar int vertex_indices\nend_header\n\"\"\"\n\n\ndef ser_to_ply_single(ver_lst, tri, height, wfp, reverse=True):\n suffix = get_suffix(wfp)\n\n for i, ver in enumerate(ver_lst):\n wfp_new = wfp.replace(suffix, f'_{i + 1}{suffix}')\n\n n_vertex = ver.shape[1]\n n_face = tri.shape[0]\n header = header_temp.format(n_vertex, n_face)\n\n with open(wfp_new, 'w') as f:\n f.write(header + '\\n')\n for i in range(n_vertex):\n x, y, z = ver[:, i]\n if reverse:\n f.write(f'{x:.2f} {height-y:.2f} {z:.2f}\\n')\n else:\n f.write(f'{x:.2f} {y:.2f} {z:.2f}\\n')\n for i in range(n_face):\n idx1, idx2, idx3 = tri[i] # m x 3\n if reverse:\n f.write(f'3 {idx3} {idx2} {idx1}\\n')\n else:\n f.write(f'3 {idx1} {idx2} {idx3}\\n')\n\n print(f'Dump tp {wfp_new}')\n\n\ndef ser_to_ply_multiple(ver_lst, tri, height, wfp, reverse=True):\n n_ply = len(ver_lst) # count ply\n\n if n_ply <= 0:\n return\n\n n_vertex = ver_lst[0].shape[1]\n n_face = tri.shape[0]\n header = header_temp.format(n_vertex * n_ply, n_face * n_ply)\n\n with open(wfp, 'w') as f:\n f.write(header + '\\n')\n\n for i in range(n_ply):\n ver = ver_lst[i]\n for j in range(n_vertex):\n x, y, z = ver[:, j]\n if reverse:\n f.write(f'{x:.2f} {height - y:.2f} {z:.2f}\\n')\n else:\n f.write(f'{x:.2f} {y:.2f} {z:.2f}\\n')\n\n for i in range(n_ply):\n offset = i * n_vertex\n for j in range(n_face):\n idx1, idx2, idx3 = tri[j] # m x 3\n if reverse:\n f.write(\n f'3 {idx3 + offset} {idx2 + offset} {idx1 + offset}\\n')\n else:\n f.write(\n f'3 {idx1 + offset} {idx2 + offset} {idx3 + offset}\\n')\n\n print(f'Dump tp {wfp}')\n\n\ndef get_colors(img, ver):\n h, w, _ = img.shape\n ver[0, :] = np.minimum(np.maximum(ver[0, :], 0), w - 1) # x\n ver[1, :] = np.minimum(np.maximum(ver[1, :], 0), h - 1) # y\n ind = np.round(ver).astype(np.int32)\n colors = img[ind[1, :], ind[0, :], :] / 255. # n x 3\n\n return colors.copy()\n\n\ndef ser_to_obj_single(img, ver_lst, tri, height, wfp):\n suffix = get_suffix(wfp)\n\n n_face = tri.shape[0]\n for i, ver in enumerate(ver_lst):\n colors = get_colors(img, ver)\n\n n_vertex = ver.shape[1]\n\n wfp_new = wfp.replace(suffix, f'_{i + 1}{suffix}')\n\n with open(wfp_new, 'w') as f:\n for i in range(n_vertex):\n x, y, z = ver[:, i]\n f.write(\n f'v {x:.2f} {height - y:.2f} {z:.2f} {colors[i, 2]:.2f} {colors[i, 1]:.2f} {colors[i, 0]:.2f}\\n')\n for i in range(n_face):\n idx1, idx2, idx3 = tri[i] # m x 3\n f.write(f'f {idx3 + 1} {idx2 + 1} {idx1 + 1}\\n')\n\n print(f'Dump tp {wfp_new}')\n\n\ndef ser_to_obj_multiple(img, ver_lst, tri, height, wfp):\n n_obj = len(ver_lst) # count obj\n\n if n_obj <= 0:\n return\n\n n_vertex = ver_lst[0].shape[1]\n n_face = tri.shape[0]\n\n with open(wfp, 'w') as f:\n for i in range(n_obj):\n ver = ver_lst[i]\n colors = get_colors(img, ver)\n\n for j in range(n_vertex):\n x, y, z = ver[:, j]\n f.write(\n f'v {x:.2f} {height - y:.2f} {z:.2f} {colors[j, 2]:.2f} {colors[j, 1]:.2f} {colors[j, 0]:.2f}\\n')\n\n for i in range(n_obj):\n offset = i * n_vertex\n for j in range(n_face):\n idx1, idx2, idx3 = tri[j] # m x 3\n f.write(\n f'f {idx3 + 1 + offset} {idx2 + 1 + offset} {idx1 + 1 + offset}\\n')\n\n print(f'Dump tp {wfp}')\n\n\ndef create_sphere(cx, cy, cz, r, resolution=360, phi_resolution=360, theta_resolution=360):\n '''\n create sphere with center (cx, cy, cz) and radius r\n '''\n phi = np.linspace(0, 2*np.pi, 2*(phi_resolution if phi_resolution else resolution))\n theta = np.linspace(0, np.pi, theta_resolution if theta_resolution else resolution)\n\n theta, phi = np.meshgrid(theta, phi)\n\n r_xy = r*np.sin(theta)\n x = cx + np.cos(phi) * r_xy\n y = cy + np.sin(phi) * r_xy\n z = cz + r * np.cos(theta)\n\n return x, y, z\n\n\ndef rotate_point_in_3d(point, origin, pitch, yaw, roll):\n '''\n Given a point, rotates the point around an origin in 3D\n '''\n x, y, z = point\n pitch = np.deg2rad(pitch)\n yaw = np.deg2rad(yaw)\n roll = np.deg2rad(roll)\n\n Rx = np.array([[1, 0, 0],\n [0, np.cos(pitch), -np.sin(pitch)],\n [0, np.sin(pitch), np.cos(pitch)]])\n Ry = np.array([[np.cos(yaw), 0, np.sin(yaw)],\n [0, 1, 0],\n [-np.sin(yaw), 0, np.cos(yaw)]])\n Rz = np.array([[np.cos(roll), -np.sin(roll), 0],\n [np.sin(roll), np.cos(roll), 0],\n [0, 0, 1]])\n R = Rz @ Ry @ Rx\n o = np.atleast_2d(origin)\n p = np.atleast_2d(point)\n return np.squeeze((R @ (p.T-o.T) + o.T).T)\n\n\ndef create_circle(cx, cy, cz, rotate_around_point, pitch, yaw, roll, r, resolution=360, view='front'):\n '''\n create circle with center (cx, cy, cz) and radius r\n '''\n theta = np.linspace(0, 2*np.pi, resolution)\n if not view or view == 'front':\n x = cx + r * np.cos(theta)\n y = cy + r * np.sin(theta)\n z = cz\n elif view == 'side':\n x = cx\n y = cy + r * np.cos(theta)\n z = cz + r * np.sin(theta)\n return rotate_point_in_3d((x, y, z), rotate_around_point, pitch, yaw, roll)\n\n\ndef rotate_line(p, origin=(0, 0), degrees=0):\n angle = np.deg2rad(degrees)\n R = np.array([[np.cos(angle), -np.sin(angle)],\n [np.sin(angle), np.cos(angle)]])\n o = np.atleast_2d(origin)\n p = np.atleast_2d(p)\n return np.squeeze((R @ (p.T-o.T) + o.T).T)\n\n\ndef plot_simple_line(ax, start_point, end_point, color=\"black\"):\n '''\n Plot a simple line between two points\n '''\n ax.plot(\n (\n start_point[0],\n end_point[0]\n ),\n (\n start_point[1],\n end_point[1]\n ),\n (\n start_point[2],\n end_point[2]\n ),\n color=color\n )\n\ndef get_line_center_point(line):\n '''\n Get the center point of a line.\n line = [start_point, end_point]\n Returns a point in X, Y, Z space.\n '''\n return (\n (line[0][0] + line[1][0]) / 2,\n (line[0][1] + line[1][1]) / 2,\n (line[0][2] + line[1][2]) / 2,\n )\n\ndef ser_to_simple_obj_multiple(img, param_lst, ver_lst, tri, height, wfp):\n n_obj = len(ver_lst) # count obj\n\n if n_obj <= 0:\n return\n\n n_vertex = ver_lst[0].shape[1]\n n_face = tri.shape[0]\n\n fig = plt.figure(figsize=(10, 10))\n ax = plt.axes(projection=\"3d\")\n ax.set_xlabel('X Label')\n ax.set_ylabel('Y Label')\n ax.set_zlabel('Z Label')\n ax.set_proj_type('ortho')\n\n ax.set_xlim(300, 800)\n ax.set_ylim(100, 600)\n ax.set_zlim(-200, 300)\n\n with open(wfp, 'w') as f:\n\n zipped_pose = zip(param_lst, ver_lst)\n\n for i in range(n_obj):\n param, ver = list(zipped_pose)[i]\n P, pose = calc_pose(param)\n face_pitch = pose[1]\n face_yaw = pose[0]\n face_roll = pose[2]\n \n ver = ver_lst[i]\n \n nums = [0, 17, 22, 27, 31, 36, 42, 48, 60, 68]\n corresponding_groupings = [\n \"jaw\",\n \"right eyebrow\",\n \"left eyebrow\",\n \"nose vertical\",\n \"nose bottom\",\n \"right eye\",\n \"left eye\",\n \"lips boundary\",\n \"inner lips\"\n ]\n line_groupings = []\n\n def get_points_for_grouping(index, as_points=False):\n '''\n This function returns the points for a given grouping.\n Normally, it returns the points as an array of arrays.\n If as_points is set to True, it returns the points as a list of points.\n\n Example return result:\n\n nose points:\n [546.5509 546.80835 547.1167 547.1211 ] (x)\n [361.8166 382.8972 404.28387 422.21112] (y)\n [155.2895 169.74472 184.611 187.74591] (z)\n\n If as_points is True:\n\n nose points:\n (546.5509, 361.8166, 155.2895)\n (546.80835, 382.8972, 169.74472)\n (547.1167, 404.28387, 184.611)\n (547.1211, 422.21112, 187.74591)\n '''\n l, r = nums[index], nums[index + 1]\n x = ver_lst[i][0, l:r]\n y = ver_lst[i][1, l:r]\n z = ver_lst[i][2, l:r]\n if as_points:\n vertices = zip(x, y, z)\n return list(vertices)\n return (\n x, y, z\n )\n\n for ind in range(len(nums) - 1):\n f.write('# {}\\n'.format(corresponding_groupings[ind]))\n l, r = nums[ind], nums[ind + 1]\n sphere_x = ver_lst[i][0, l:r]\n sphere_y = ver_lst[i][1, l:r]\n sphere_z = ver_lst[i][2, l:r]\n vertices = zip(sphere_x, sphere_y, sphere_z)\n for (sphere_x, sphere_y, sphere_z) in vertices:\n f.write(\n f'v {sphere_x:.2f} {height - sphere_y:.2f} {sphere_z:.2f}\\n')\n if ind == 1:\n print(\n f'v {sphere_x:.2f} {sphere_y:.2f} {sphere_z:.2f}\\n')\n f.write('\\n')\n line_groupings.append((sphere_x, sphere_y, sphere_z))\n ax.plot(sphere_x, sphere_y, sphere_z,\n label=corresponding_groupings[ind])\n\n # Connecting lines\n plt.plot(ver_lst[i][0, l:r], ver_lst[i]\n [1, l:r], ver_lst[i][2, l:r], color='red')\n # Individual points\n plt.plot(ver_lst[i][0, l:r], ver_lst[i][1, l:r],\n ver_lst[i][2, l:r], marker='o', linestyle='None')\n\n for ind in range(len(nums) - 1):\n l, r = nums[ind], nums[ind + 1]\n print()\n print('ind: {}'.format(ind))\n print(l, '-', r)\n f.write('# {}\\n'.format(corresponding_groupings[ind]))\n f.write('l {}\\n'.format(\n \" \".join([\"{}\".format(l + item + 1) for item in range(r - l)])))\n\n # draw cube\n #r = [-1, 1]\n # for s, e in combinations(np.array(list(product(r, r, r))), 2):\n # if np.sum(np.abs(s-e)) == r[1]-r[0]:\n # ax.plot3D(*zip(s, e), color=\"b\")\n\n # draw sphere\n\n # get the points that correspond to the nose in the Z direction\n\n nose_points = list(get_points_for_grouping(\n 3)[2]) + list(get_points_for_grouping(4)[2])\n\n # find the largest point in the Z direction\n\n max_nose_z = max(nose_points)\n\n f.write('# {}\\n'.format(corresponding_groupings[ind]))\n right_eyebrow_points = get_points_for_grouping(1)\n left_eyebrow_points = get_points_for_grouping(2)\n eyebrow_centroid = (\n sum(right_eyebrow_points[0] + left_eyebrow_points[0]) /\n (len(right_eyebrow_points[0]) + len(left_eyebrow_points[0])),\n sum(right_eyebrow_points[1] + left_eyebrow_points[1]) /\n (len(right_eyebrow_points[1]) + len(left_eyebrow_points[1])),\n sum(right_eyebrow_points[2] + left_eyebrow_points[2]) /\n (len(right_eyebrow_points[2]) + len(left_eyebrow_points[2])),\n )\n\n outer_lips_points = get_points_for_grouping(8)\n lips_centroid = (\n sum(outer_lips_points[0]) / (len(outer_lips_points[0])),\n sum(outer_lips_points[1]) / (len(outer_lips_points[1])),\n sum(outer_lips_points[2]) / (len(outer_lips_points[2])),\n )\n\n jaw_points = get_points_for_grouping(0)\n\n ax.plot(\n (jaw_points[0][0], jaw_points[0][-1]),\n (jaw_points[1][0], jaw_points[1][-1]),\n (jaw_points[2][0], jaw_points[2][-1]),\n color=\"black\"\n )\n\n # Find the center of a line between the two points\n\n jaw_point1 = (jaw_points[0][0], jaw_points[1][0], jaw_points[2][0])\n jaw_point2 = (jaw_points[0][-1],\n jaw_points[1][-1], jaw_points[2][-1])\n\n jaw_back_line_center_point = (\n (jaw_point1[0] + jaw_point2[0]) / 2,\n (jaw_point1[1] + jaw_point2[1]) / 2,\n (jaw_point1[2] + jaw_point2[2]) / 2,\n )\n\n ax.scatter(\n jaw_back_line_center_point[0], jaw_back_line_center_point[1], jaw_back_line_center_point[2], color=\"red\")\n\n sphere_radius = abs(lips_centroid[1] - eyebrow_centroid[1])\n sphere_x, sphere_y, sphere_z = create_sphere(\n jaw_back_line_center_point[0],\n jaw_back_line_center_point[1],\n max_nose_z - sphere_radius,\n sphere_radius,\n resolution=10\n )\n\n # The following code finds all of the sphere points that are within the jaw\n\n # get the points that correspond to the jaw in the X direction\n jaw_points_x = list(jaw_points[0])\n max_jaw_x = max(jaw_points_x)\n min_jaw_x = min(jaw_points_x)\n # get the points that correspond to the jaw in the Y direction\n jaw_points_y = list(get_points_for_grouping(0)[1])\n min_jaw_Y = min(jaw_points_y)\n\n # unzip sphere points\n\n sphere_points = list(\n zip(sphere_x.flatten(), sphere_y.flatten(), sphere_z.flatten()))\n\n # remove the points where X is greater than max_jaw_x and less than min_jaw_x\n\n sphere_points_inside_jaw = [point for point in sphere_points if point[0]\n <= max_jaw_x and point[0] >= min_jaw_x and point[1] <= min_jaw_Y]\n\n # Zip sphere points to X, Y, and Z\n\n sphere_x_inside_jaw, sphere_y_inside_jaw, sphere_z_inside_jaw = zip(\n *sphere_points_inside_jaw)\n\n # ax.plot_wireframe(sphere_x, sphere_y, sphere_z, color=\"red\") # plot_surface is a function also\n # ax.scatter(np.array(sphere_x_inside_jaw), np.array(sphere_y_inside_jaw), np.array(sphere_z_inside_jaw), color=\"black\")\n\n # 2d only:\n # ax.scatter(sphere_x, sphere_y, color=\"red\") # plot_surface is a function also\n # ax.scatter(np.array(sphere_x_inside_jaw), np.array(sphere_y_inside_jaw), color=\"orange\") # plot_surface is a function also\n\n rectangle_half_height = 2 * (sphere_radius) / 3 # 2/3 of the sphere diameter\n\n left_cutoff_line_horizontal = [\n (jaw_point1[0], jaw_point1[1], jaw_point1[2] - rectangle_half_height),\n (jaw_point1[0], jaw_point1[1], jaw_point1[2] + rectangle_half_height),\n ]\n left_cutoff_line_vertical = [\n (jaw_point1[0], jaw_point1[1] - rectangle_half_height, jaw_point1[2]),\n (jaw_point1[0], jaw_point1[1] + rectangle_half_height, jaw_point1[2]),\n ]\n\n left_cutoff_line_line_center_point = get_line_center_point(left_cutoff_line_horizontal)\n\n right_cutoff_line_horizontal = [\n (jaw_point2[0], jaw_point2[1], jaw_point2[2] - rectangle_half_height),\n (jaw_point2[0], jaw_point2[1], jaw_point2[2] + rectangle_half_height),\n ]\n right_cutoff_line_vertical = [\n (jaw_point2[0], jaw_point2[1] - rectangle_half_height, jaw_point2[2]),\n (jaw_point2[0], jaw_point2[1] + rectangle_half_height, jaw_point2[2]),\n ]\n\n right_cutoff_line_line_center_point = get_line_center_point(right_cutoff_line_horizontal)\n\n # plot_simple_line(ax, left_cutoff_line_horizontal[0], left_cutoff_line_horizontal[1], color=\"black\")\n # plot_simple_line(ax, left_cutoff_line_vertical[0], left_cutoff_line_vertical[1], color=\"black\")\n # plot_simple_line(ax, right_cutoff_line_horizontal[0], right_cutoff_line_horizontal[1], color=\"black\")\n # plot_simple_line(ax, right_cutoff_line_vertical[0], right_cutoff_line_vertical[1], color=\"black\")\n\n # Rotate left_cutoff_line around a point in 3D\n\n print(face_yaw, '..', face_pitch, '...', face_roll)\n yaw = -face_yaw\n pitch = face_pitch\n roll = face_roll\n\n rotated_left_cutoff_line_horizontal_start = rotate_point_in_3d(left_cutoff_line_horizontal[0], left_cutoff_line_line_center_point, pitch, yaw, roll)\n rotated_left_cutoff_line_horizontal_end = rotate_point_in_3d(left_cutoff_line_horizontal[1], left_cutoff_line_line_center_point, pitch, yaw, roll)\n rotated_left_cutoff_line_vertical_start = rotate_point_in_3d(left_cutoff_line_vertical[0], left_cutoff_line_line_center_point, pitch, yaw, roll)\n rotated_left_cutoff_line_vertical_end = rotate_point_in_3d(left_cutoff_line_vertical[1], left_cutoff_line_line_center_point, pitch, yaw, roll)\n\n rotated_right_cutoff_line_horizontal_start = rotate_point_in_3d(right_cutoff_line_horizontal[0], right_cutoff_line_line_center_point, pitch, yaw, roll)\n rotated_right_cutoff_line_horizontal_end = rotate_point_in_3d(right_cutoff_line_horizontal[1], right_cutoff_line_line_center_point, pitch, yaw, roll)\n rotated_right_cutoff_line_vertical_start = rotate_point_in_3d(right_cutoff_line_vertical[0], right_cutoff_line_line_center_point, pitch, yaw, roll)\n rotated_right_cutoff_line_vertical_end = rotate_point_in_3d(right_cutoff_line_vertical[1], right_cutoff_line_line_center_point, pitch, yaw, roll)\n\n plot_simple_line(ax, rotated_left_cutoff_line_horizontal_start, rotated_left_cutoff_line_horizontal_end, color=\"blue\")\n plot_simple_line(ax, rotated_left_cutoff_line_vertical_start, rotated_left_cutoff_line_vertical_end, color=\"blue\")\n plot_simple_line(ax, rotated_right_cutoff_line_horizontal_start, rotated_right_cutoff_line_horizontal_end, color=\"blue\")\n plot_simple_line(ax, rotated_right_cutoff_line_vertical_start, rotated_right_cutoff_line_vertical_end, color=\"blue\")\n\n front_circle_x, front_circle_y, front_circle_z = create_circle(\n jaw_back_line_center_point[0],\n jaw_back_line_center_point[1],\n jaw_back_line_center_point[2],\n jaw_back_line_center_point,\n pitch, yaw, roll,\n sphere_radius,\n resolution=360,\n view='front',\n )\n ax.scatter(front_circle_x, front_circle_y, front_circle_z, color=\"blue\")\n\n right_circle_x, right_circle_y, right_circle_z = create_circle(\n right_cutoff_line_line_center_point[0],\n right_cutoff_line_line_center_point[1],\n right_cutoff_line_line_center_point[2],\n right_cutoff_line_line_center_point,\n pitch, yaw, roll,\n rectangle_half_height,\n resolution=360,\n view='side',\n )\n ax.scatter(right_circle_x, right_circle_y, right_circle_z, color=\"blue\")\n \n left_circle_x, left_circle_y, left_circle_z = create_circle(\n left_cutoff_line_line_center_point[0],\n left_cutoff_line_line_center_point[1],\n left_cutoff_line_line_center_point[2],\n left_cutoff_line_line_center_point,\n pitch, yaw, roll,\n rectangle_half_height,\n resolution=360,\n view='side',\n )\n ax.scatter(left_circle_x, left_circle_y, left_circle_z, color=\"blue\")\n\n # Get all zipped_left_circle_points that have Z greater than left_cutoff_line_line_center_point\n\n # zipped_left_circle_points = zip(left_circle_x, left_circle_y, left_circle_z)\n # zipped_left_circle_points = [x for x in zipped_left_circle_points if x[0] > left_cutoff_line_line_center_point[0] and x[2] > left_cutoff_line_line_center_point[2]]\n # zipped_left_circle_points_x, zipped_left_circle_points_y, zipped_left_circle_points_z = zip(*zipped_left_circle_points)\n # ax.scatter(zipped_left_circle_points_x, zipped_left_circle_points_y, zipped_left_circle_points_z, color=\"yellow\")\n\n \n ax.view_init(90, 90)\n # ax.view_init(90, 180)\n\n plt.show()\n\n\nser_to_ply = ser_to_ply_multiple # ser_to_ply_single\nser_to_obj = ser_to_obj_multiple # ser_to_obj_multiple\n"
]
| [
[
"numpy.maximum",
"numpy.linspace",
"numpy.squeeze",
"numpy.cos",
"numpy.sin",
"matplotlib.pyplot.axes",
"numpy.atleast_2d",
"numpy.deg2rad",
"numpy.round",
"matplotlib.pyplot.plot",
"numpy.meshgrid",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
]
|
dhomeier/lightkurve | [
"ea53c81f3d7617441a02288ed84c016e8ef80ceb"
]
| [
"lightkurve/search.py"
]
| [
"\"\"\"Defines tools to retrieve Kepler data from the archive at MAST.\"\"\"\nfrom __future__ import division\nimport os\nimport glob\nimport logging\nimport re\nimport warnings\nfrom requests import HTTPError\n\nimport numpy as np\nfrom astropy.table import join, Table, Row\nfrom astropy.coordinates import SkyCoord\nfrom astropy.io import ascii\nfrom astropy import units as u\nfrom astropy.utils import deprecated\n\nfrom .targetpixelfile import TargetPixelFile\nfrom .collections import TargetPixelFileCollection, LightCurveCollection\nfrom .utils import suppress_stdout, LightkurveWarning, LightkurveDeprecationWarning\nfrom .io import read\nfrom . import PACKAGEDIR\n\nlog = logging.getLogger(__name__)\n\n__all__ = ['search_targetpixelfile', 'search_lightcurve',\n 'search_lightcurvefile', 'search_tesscut',\n 'SearchResult']\n\n\nclass SearchError(Exception):\n pass\n\n\nclass SearchResult(object):\n \"\"\"Container for the results returned by `search_targetpixelfile`,\n `search_lightcurve`, or `search_tesscut`.\n\n The purpose of this class is to provide a convenient way to inspect and\n download products that have been identified using one of the data search\n functions.\n\n Parameters\n ----------\n table : `astropy.table.Table` object\n Astropy table returned by a join of the astroquery `Observations.query_criteria()`\n and `Observations.get_product_list()` methods.\n \"\"\"\n def __init__(self, table=None):\n if table is None:\n self.table = Table()\n else:\n self.table = table\n if len(table) > 0:\n self._add_columns()\n\n def _add_columns(self):\n \"\"\"Adds user-friendly index (``#``) column.\n\n These columns are not part of the MAST Portal API, but they make the\n display of search results much nicer in Lightkurve.\n \"\"\"\n self.table['#'] = None\n for idx in range(len(self.table)):\n self.table['#'][idx] = idx\n\n def __repr__(self, html=False):\n out = 'SearchResult containing {} data products.'.format(len(self.table))\n if len(self.table) == 0:\n return out\n columns = ['#', 'observation', 'author', 'target_name', 't_exptime', 'productFilename', 'distance']\n self.table['t_exptime'].unit = \"sec\"\n self.table['t_exptime'].format = \".0f\"\n self.table['distance'].unit = \"arcsec\"\n return out + '\\n\\n' + '\\n'.join(self.table[columns].pformat(max_width=300, html=html))\n\n def _repr_html_(self):\n return self.__repr__(html=True)\n\n def __getitem__(self, key):\n \"\"\"Implements indexing and slicing, e.g. SearchResult[2:5].\"\"\"\n # this check is necessary due to an astropy bug\n # for more information, see issue #445\n if key == -1:\n key = len(self.table) - 1\n selection = self.table[key]\n # Indexing a Table with an integer will return a Row\n if isinstance(selection, Row):\n selection = Table(selection)\n return SearchResult(table=selection)\n\n def __len__(self):\n \"\"\"Returns the number of products in the SearchResult table.\"\"\"\n return len(self.table)\n\n @property\n def unique_targets(self):\n \"\"\"Returns a table of targets and their RA & dec values produced by search\"\"\"\n mask = ['target_name', 's_ra', 's_dec']\n return Table.from_pandas(self.table[mask].to_pandas().drop_duplicates('target_name').reset_index(drop=True))\n\n @property\n def obsid(self):\n \"\"\"Returns an array of MAST observation IDs\"\"\"\n return np.asarray(np.unique(self.table['obsid']), dtype='int64')\n\n @property\n def target_name(self):\n \"\"\"Returns an array of target names\"\"\"\n return self.table['target_name'].data.data\n\n @property\n def ra(self):\n \"\"\"Returns an array of RA values for targets in search\"\"\"\n return self.table['s_ra'].data.data\n\n @property\n def dec(self):\n \"\"\"Returns an array of dec values for targets in search\"\"\"\n return self.table['s_dec'].data.data\n\n def _download_one(self, table, quality_bitmask, download_dir, cutout_size, **kwargs):\n \"\"\"Private method used by `download()` and `download_all()` to download\n exactly one file from the MAST archive.\n\n Always returns a `TargetPixelFile` or `LightCurve` object.\n \"\"\"\n # Make sure astroquery uses the same level of verbosity\n logging.getLogger('astropy').setLevel(log.getEffectiveLevel())\n\n if download_dir is None:\n download_dir = self._default_download_dir()\n\n # if the SearchResult row is a TESScut entry, then download cutout\n if 'FFI Cutout' in table[0]['description']:\n try:\n log.debug(\"Started downloading TESSCut for '{}' sector {}.\"\n \"\".format(table[0]['target_name'], table[0]['sequence_number']))\n path = self._fetch_tesscut_path(table[0]['target_name'],\n table[0]['sequence_number'],\n download_dir,\n cutout_size)\n except Exception as exc:\n msg = str(exc)\n if \"504\" in msg:\n # TESSCut will occasionally return a \"504 Gateway Timeout\n # error\" when it is overloaded.\n raise HTTPError('The TESS FFI cutout service at MAST appears '\n 'to be temporarily unavailable. It returned '\n 'the following error: {}'.format(exc))\n else:\n raise SearchError('Unable to download FFI cutout. Desired target '\n 'coordinates may be too near the edge of the FFI.'\n 'Error: {}'.format(exc))\n\n return read(path,\n quality_bitmask=quality_bitmask,\n targetid=table[0]['targetid'])\n\n else:\n if cutout_size is not None:\n warnings.warn('`cutout_size` can only be specified for TESS '\n 'Full Frame Image cutouts.', LightkurveWarning)\n from astroquery.mast import Observations\n log.debug(\"Started downloading {}.\".format(table[:1]['dataURL'][0]))\n path = Observations.download_products(table[:1], mrp_only=False,\n download_dir=download_dir)['Local Path'][0]\n log.debug(\"Finished downloading.\")\n return read(path, quality_bitmask=quality_bitmask, **kwargs)\n\n @suppress_stdout\n def download(self, quality_bitmask='default', download_dir=None, cutout_size=None, **kwargs):\n \"\"\"Returns a single `LightCurve` or `TargetPixelFile` object.\n\n If multiple files are present in `SearchResult.table`, only the first\n will be downloaded.\n\n Parameters\n ----------\n quality_bitmask : str or int, optional\n Bitmask (integer) which identifies the quality flag bitmask that should\n be used to mask out bad cadences. If a string is passed, it has the\n following meaning:\n\n * \"none\": no cadences will be ignored\n * \"default\": cadences with severe quality issues will be ignored\n * \"hard\": more conservative choice of flags to ignore\n This is known to remove good data.\n * \"hardest\": removes all data that has been flagged\n This mask is not recommended.\n\n See the :class:`KeplerQualityFlags <lightkurve.utils.KeplerQualityFlags>` or :class:`TessQualityFlags <lightkurve.utils.TessQualityFlags>` class for details on the bitmasks.\n download_dir : str, optional\n Location where the data files will be stored.\n Defaults to \"~/.lightkurve-cache\" if `None` is passed.\n cutout_size : int, float or tuple, optional\n Side length of cutout in pixels. Tuples should have dimensions (y, x).\n Default size is (5, 5)\n flux_column : str, optional\n The column in the FITS file to be read as `flux`. Defaults to 'pdcsap_flux'.\n Typically 'pdcsap_flux' or 'sap_flux'.\n kwargs : dict, optional\n Extra keyword arguments passed on to the file format reader function.\n\n Returns\n -------\n data : `TargetPixelFile` or `LightCurve` object\n The first entry in the products table.\n\n Raises\n ------\n HTTPError\n If the TESSCut service times out (i.e. returns HTTP status 504).\n SearchError\n If any other error occurs.\n \"\"\"\n if len(self.table) == 0:\n warnings.warn(\"Cannot download from an empty search result.\",\n LightkurveWarning)\n return None\n if len(self.table) != 1:\n warnings.warn('Warning: {} files available to download. '\n 'Only the first file has been downloaded. '\n 'Please use `download_all()` or specify additional '\n 'criteria (e.g. quarter, campaign, or sector) '\n 'to limit your search.'.format(len(self.table)),\n LightkurveWarning)\n\n return self._download_one(table=self.table[:1],\n quality_bitmask=quality_bitmask,\n download_dir=download_dir,\n cutout_size=cutout_size,\n **kwargs)\n\n @suppress_stdout\n def download_all(self, quality_bitmask='default', download_dir=None, cutout_size=None, **kwargs):\n \"\"\"Returns a `~lightkurve.collections.TargetPixelFileCollection` or\n `~lightkurve.collections.LightCurveCollection`.\n\n Parameters\n ----------\n quality_bitmask : str or int, optional\n Bitmask (integer) which identifies the quality flag bitmask that should\n be used to mask out bad cadences. If a string is passed, it has the\n following meaning:\n\n * \"none\": no cadences will be ignored\n * \"default\": cadences with severe quality issues will be ignored\n * \"hard\": more conservative choice of flags to ignore\n This is known to remove good data.\n * \"hardest\": removes all data that has been flagged\n This mask is not recommended.\n\n See the :class:`KeplerQualityFlags <lightkurve.utils.KeplerQualityFlags>` or :class:`TessQualityFlags <lightkurve.utils.TessQualityFlags>` class for details on the bitmasks.\n download_dir : str, optional\n Location where the data files will be stored.\n Defaults to \"~/.lightkurve-cache\" if `None` is passed.\n cutout_size : int, float or tuple, optional\n Side length of cutout in pixels. Tuples should have dimensions (y, x).\n Default size is (5, 5)\n flux_column : str, optional\n The column in the FITS file to be read as `flux`. Defaults to 'pdcsap_flux'.\n Typically 'pdcsap_flux' or 'sap_flux'.\n kwargs : dict, optional\n Extra keyword arguments passed on to the file format reader function.\n\n Returns\n -------\n collection : `~lightkurve.collections.Collection` object\n Returns a `~lightkurve.collections.LightCurveCollection` or\n `~lightkurve.collections.TargetPixelFileCollection`,\n containing all entries in the products table\n\n Raises\n ------\n HTTPError\n If the TESSCut service times out (i.e. returns HTTP status 504).\n SearchError\n If any other error occurs.\n \"\"\"\n if len(self.table) == 0:\n warnings.warn(\"Cannot download from an empty search result.\",\n LightkurveWarning)\n return None\n log.debug(\"{} files will be downloaded.\".format(len(self.table)))\n\n products = []\n for idx in range(len(self.table)):\n products.append(self._download_one(table=self.table[idx:idx+1],\n quality_bitmask=quality_bitmask,\n download_dir=download_dir,\n cutout_size=cutout_size,\n **kwargs))\n if isinstance(products[0], TargetPixelFile):\n return TargetPixelFileCollection(products)\n else:\n return LightCurveCollection(products)\n\n def _default_download_dir(self):\n \"\"\"Returns the default path to the directory where files will be downloaded.\n\n By default, this method will return \"~/.lightkurve-cache\" and create\n this directory if it does not exist. If the directory cannot be\n access or created, then it returns the local directory (\".\").\n\n Returns\n -------\n download_dir : str\n Path to location of `mastDownload` folder where data downloaded from MAST are stored\n \"\"\"\n download_dir = os.path.join(os.path.expanduser('~'), '.lightkurve-cache')\n if os.path.isdir(download_dir):\n return download_dir\n else:\n # if it doesn't exist, make a new cache directory\n try:\n os.mkdir(download_dir)\n # downloads locally if OS error occurs\n except OSError:\n log.warning('Warning: unable to create {}. '\n 'Downloading MAST files to the current '\n 'working directory instead.'.format(download_dir))\n download_dir = '.'\n\n return download_dir\n\n def _fetch_tesscut_path(self, target, sector, download_dir, cutout_size):\n \"\"\"Downloads TESS FFI cutout and returns path to local file.\n\n Parameters\n ----------\n download_dir : str\n Path to location of `.lightkurve-cache` directory where downloaded\n cutouts are stored\n cutout_size : int, float or tuple\n Side length of cutout in pixels. Tuples should have dimensions (y, x).\n Default size is (5, 5)\n\n Returns\n -------\n path : str\n Path to locally downloaded cutout file\n \"\"\"\n from astroquery.mast import TesscutClass\n coords = _resolve_object(target)\n\n # Set cutout_size defaults\n if cutout_size is None:\n cutout_size = 5\n\n # Check existence of `~/.lightkurve-cache/tesscut`\n tesscut_dir = os.path.join(download_dir, 'tesscut')\n if not os.path.isdir(tesscut_dir):\n # if it doesn't exist, make a new cache directory\n try:\n os.mkdir(tesscut_dir)\n # downloads into default cache if OSError occurs\n except OSError:\n tesscut_dir = download_dir\n\n # Resolve SkyCoord of given target\n coords = _resolve_object(target)\n\n # build path string name and check if it exists\n # this is necessary to ensure cutouts are not downloaded multiple times\n sec = TesscutClass().get_sectors(coords)\n sector_name = sec[sec['sector'] == sector]['sectorName'][0]\n if isinstance(cutout_size, int):\n size_str = str(int(cutout_size)) + 'x' + str(int(cutout_size))\n elif isinstance(cutout_size, tuple) or isinstance(cutout_size, list):\n size_str = str(int(cutout_size[1])) + 'x' + str(int(cutout_size[0]))\n\n # search cache for file with matching ra, dec, and cutout size\n # ra and dec are searched within 0.001 degrees of input target\n ra_string = str(coords.ra.value)\n dec_string = str(coords.dec.value)\n matchstring = r\"{}_{}*_{}*_{}_astrocut.fits\".format(sector_name,\n ra_string[:ra_string.find('.')+4],\n dec_string[:dec_string.find('.')+4],\n size_str)\n cached_files = glob.glob(os.path.join(tesscut_dir, matchstring))\n\n # if any files exist, return the path to them instead of downloading\n if len(cached_files) > 0:\n path = cached_files[0]\n log.debug(\"Cached file found.\")\n # otherwise the file will be downloaded\n else:\n cutout_path = TesscutClass().download_cutouts(coords, size=cutout_size,\n sector=sector, path=tesscut_dir)\n path = os.path.join(download_dir, cutout_path[0][0])\n log.debug(\"Finished downloading.\")\n return path\n\n\ndef search_targetpixelfile(target, radius=None, cadence=None,\n mission=('Kepler', 'K2', 'TESS'),\n author=('Kepler', 'K2', 'SPOC'),\n quarter=None, month=None, campaign=None, sector=None,\n limit=None):\n \"\"\"Searches the `public data archive at MAST <https://archive.stsci.edu>`_\n for target pixel files.\n\n This function fetches a data table that lists the Target Pixel Files (TPFs)\n that fall within a region of sky centered around the position of `target`\n and within a cone of a given `radius`. If no value is provided for `radius`,\n only a single target will be returned.\n\n Parameters\n ----------\n target : str, int, or `astropy.coordinates.SkyCoord` object\n Target around which to search. Valid inputs include:\n\n * The name of the object as a string, e.g. \"Kepler-10\".\n * The KIC or EPIC identifier as an integer, e.g. 11904151.\n * A coordinate string in decimal format, e.g. \"285.67942179 +50.24130576\".\n * A coordinate string in sexagesimal format, e.g. \"19:02:43.1 +50:14:28.7\".\n * An `astropy.coordinates.SkyCoord` object.\n radius : float or `astropy.units.Quantity` object\n Conesearch radius. If a float is given it will be assumed to be in\n units of arcseconds. If `None` then we default to 0.0001 arcsec.\n cadence : 'long', 'short', 'fast', or float\n 'long' selects 10-min and 30-min cadence products;\n 'short' selects 1-min and 2-min products;\n 'fast' selects 20-sec products.\n Alternatively, you can pass the exact exposure time in seconds as\n an int or a float, e.g. ``cadence=600`` selects 10-minute cadence.\n By default, all cadence modes are returned.\n mission : str, tuple of str\n 'Kepler', 'K2', or 'TESS'. By default, all will be returned.\n author : str, tuple of str, or \"any\"\n Author of the data product (`provenance_name` in the MAST API).\n Defaults to the official products: ('Kepler', 'K2', 'SPOC').\n Use \"any\" to retrieve all light curves regardless of the author.\n quarter, campaign, sector : int, list of ints\n Kepler Quarter, K2 Campaign, or TESS Sector number.\n By default all quarters/campaigns/sectors will be returned.\n month : 1, 2, 3, 4 or list of int\n For Kepler's prime mission, there are three short-cadence\n TargetPixelFiles for each quarter, each covering one month.\n Hence, if cadence='short' you can specify month=1, 2, 3, or 4.\n By default all months will be returned.\n limit : int\n Maximum number of products to return.\n\n Returns\n -------\n result : :class:`SearchResult` object\n Object detailing the data products found.\n\n Examples\n --------\n This example demonstrates how to use the `search_targetpixelfile()` function\n to query and download data. Before instantiating a\n `~lightkurve.targetpixelfile.KeplerTargetPixelFile` object or\n downloading any science products, we can identify potential desired targets\n with `search_targetpixelfile()`::\n\n >>> search_result = search_targetpixelfile('Kepler-10') # doctest: +SKIP\n >>> print(search_result) # doctest: +SKIP\n\n The above code will query mast for Target Pixel Files (TPFs) available for\n the known planet system Kepler-10, and display a table containing the\n available science products. Because Kepler-10 was observed during 15 Quarters,\n the table will have 15 entries. To obtain a\n `~lightkurve.collections.TargetPixelFileCollection` object containing all\n 15 observations, use::\n\n >>> search_result.download_all() # doctest: +SKIP\n\n or we can download a single product by limiting our search::\n\n >>> tpf = search_targetpixelfile('Kepler-10', quarter=2).download() # doctest: +SKIP\n\n The above line of code will only download Quarter 2 and create a single\n `~lightkurve.targetpixelfile.KeplerTargetPixelFile` object called `tpf`.\n\n We can also pass a radius into `search_targetpixelfile` to perform a cone search::\n\n >>> search_targetpixelfile('Kepler-10', radius=100).targets # doctest: +SKIP\n\n This will display a table containing all targets within 100 arcseconds of Kepler-10.\n We can download a `~lightkurve.collections.TargetPixelFileCollection` object\n containing all available products for these targets in Quarter 4 with::\n\n >>> search_targetpixelfile('Kepler-10', radius=100, quarter=4).download_all() # doctest: +SKIP\n \"\"\"\n try:\n return _search_products(target, radius=radius, filetype=\"Target Pixel\",\n cadence=cadence, mission=mission,\n provenance_name=author,\n quarter=quarter, month=month,\n campaign=campaign, sector=sector,\n limit=limit)\n except SearchError as exc:\n log.error(exc)\n return SearchResult(None)\n\n\n@deprecated(\"2.0\", alternative=\"search_lightcurve()\", warning_type=LightkurveDeprecationWarning)\ndef search_lightcurvefile(*args, **kwargs):\n return search_lightcurve(*args, **kwargs)\n\n\ndef search_lightcurve(target, radius=None, cadence=None,\n mission=('Kepler', 'K2', 'TESS'),\n author=('Kepler', 'K2', 'SPOC'),\n quarter=None, month=None, campaign=None, sector=None,\n limit=None):\n \"\"\"Searches the `public data archive at MAST <https://archive.stsci.edu>`_ for a Kepler or TESS\n :class:`LightCurve <lightkurve.lightcurve.LightCurve>`.\n\n This function fetches a data table that lists the Light Curve Files\n that fall within a region of sky centered around the position of `target`\n and within a cone of a given `radius`. If no value is provided for `radius`,\n only a single target will be returned.\n\n Parameters\n ----------\n target : str, int, or `astropy.coordinates.SkyCoord` object\n Target around which to search. Valid inputs include:\n\n * The name of the object as a string, e.g. \"Kepler-10\".\n * The KIC or EPIC identifier as an integer, e.g. 11904151.\n * A coordinate string in decimal format, e.g. \"285.67942179 +50.24130576\".\n * A coordinate string in sexagesimal format, e.g. \"19:02:43.1 +50:14:28.7\".\n * An `astropy.coordinates.SkyCoord` object.\n radius : float or `astropy.units.Quantity` object\n Conesearch radius. If a float is given it will be assumed to be in\n units of arcseconds. If `None` then we default to 0.0001 arcsec.\n cadence : 'long', 'short', 'fast', or float\n 'long' selects 10-min and 30-min cadence products;\n 'short' selects 1-min and 2-min products;\n 'fast' selects 20-sec products.\n Alternatively, you can pass the exact exposure time in seconds as\n an int or a float, e.g. ``cadence=600`` selects 10-minute cadence.\n By default, all cadence modes are returned.\n mission : str, tuple of str\n 'Kepler', 'K2', or 'TESS'. By default, all will be returned.\n author : str, tuple of str, or \"any\"\n Author of the data product (`provenance_name` in the MAST API).\n Defaults to the official products: ('Kepler', 'K2', 'SPOC').\n Community-provided products that are supported include ('K2SFF', 'EVEREST').\n Use \"any\" to retrieve all light curves regardless of the author.\n quarter, campaign, sector : int, list of ints\n Kepler Quarter, K2 Campaign, or TESS Sector number.\n By default all quarters/campaigns/sectors will be returned.\n month : 1, 2, 3, 4 or list of int\n For Kepler's prime mission, there are three short-cadence\n TargetPixelFiles for each quarter, each covering one month.\n Hence, if cadence='short' you can specify month=1, 2, 3, or 4.\n By default all months will be returned.\n limit : int\n Maximum number of products to return.\n\n Returns\n -------\n result : :class:`SearchResult` object\n Object detailing the data products found.\n\n Examples\n --------\n This example demonstrates how to use the `search_lightcurve()` function to\n query and download data. Before instantiating a `KeplerLightCurve` object or\n downloading any science products, we can identify potential desired targets with\n `search_lightcurve`::\n\n >>> from lightkurve import search_lightcurvefile # doctest: +SKIP\n >>> search_result = search_lightcurvefile(\"Kepler-10\") # doctest: +SKIP\n >>> print(search_result) # doctest: +SKIP\n\n The above code will query mast for lightcurve files available for the known\n planet system Kepler-10, and display a table containing the available\n data products. Because Kepler-10 was observed in 15 quarters, the search\n result will list 15 different files. If we want to download a\n `~lightkurve.collections.LightCurveFileCollection` object containing all\n 15 observations, use::\n\n >>> search_result.download_all() # doctest: +SKIP\n\n or we can specify the downloaded products by limiting our search::\n\n >>> lcf = search_lightcurvefile('Kepler-10', quarter=2).download() # doctest: +SKIP\n\n The above line of code will only search and download Quarter 2 data and\n create a `LightCurveFile` object called lcf.\n\n We can also pass a radius into `search_lightcurvefile` to perform a cone search::\n\n >>> search_lightcurvefile('Kepler-10', radius=100, quarter=4) # doctest: +SKIP\n\n This will display a table containing all targets within 100 arcseconds of\n Kepler-10 and in Quarter 4. We can then download a\n `~lightkurve.collections.LightCurveFileCollection` containing all these\n products using::\n\n >>> search_lightcurvefile('kepler-10', radius=100, quarter=4).download_all() # doctest: +SKIP\n \"\"\"\n try:\n return _search_products(target, radius=radius, filetype=\"Lightcurve\",\n cadence=cadence, mission=mission,\n provenance_name=author,\n quarter=quarter, month=month,\n campaign=campaign, sector=sector, limit=limit)\n except SearchError as exc:\n log.error(exc)\n return SearchResult(None)\n\n\ndef search_tesscut(target, sector=None):\n \"\"\"Searches MAST for TESS Full Frame Image cutouts containing a desired target or region.\n\n This feature uses the `TESScut service <https://mast.stsci.edu/tesscut/>`_\n provided by the TESS data archive at MAST. If you use this service in\n your work, please `cite TESScut <https://ascl.net/code/v/2239>`_ in your\n publications.\n\n Parameters\n ----------\n target : str, int, or `astropy.coordinates.SkyCoord` object\n Target around which to search. Valid inputs include:\n\n * The name of the object as a string, e.g. \"Kepler-10\".\n * The KIC or EPIC identifier as an integer, e.g. 11904151.\n * A coordinate string in decimal format, e.g. \"285.67942179 +50.24130576\".\n * A coordinate string in sexagesimal format, e.g. \"19:02:43.1 +50:14:28.7\".\n * An `astropy.coordinates.SkyCoord` object.\n sector : int or list\n TESS Sector number. Default (None) will return all available sectors. A\n list of desired sectors can also be provided.\n\n Returns\n -------\n result : :class:`SearchResult` object\n Object detailing the data products found.\n \"\"\"\n try:\n return _search_products(target, filetype=\"ffi\", mission='TESS', sector=sector)\n except SearchError as exc:\n log.error(exc)\n return SearchResult(None)\n\n\ndef _search_products(target, radius=None, filetype=\"Lightcurve\", cadence=None,\n mission=('Kepler', 'K2', 'TESS'),\n provenance_name=('Kepler', 'K2', 'SPOC'),\n t_exptime=(0, 9999), quarter=None, month=None,\n campaign=None, sector=None, limit=None,\n **extra_query_criteria):\n \"\"\"Helper function which returns a SearchResult object containing MAST\n products that match several criteria.\n\n Parameters\n ----------\n target : str, int, or `astropy.coordinates.SkyCoord` object\n See docstrings above.\n radius : float or `astropy.units.Quantity` object\n Conesearch radius. If a float is given it will be assumed to be in\n units of arcseconds. If `None` then we default to 0.0001 arcsec.\n filetype : {'Target pixel', 'Lightcurve', 'FFI'}\n Type of files queried at MAST.\n cadence : 'long', 'short', 'fast', or float\n 'long' selects 10-min and 30-min cadence products;\n 'short' selects 1-min and 2-min products;\n 'fast' selects 20-sec products.\n Alternatively, you can pass the exact exposure time in seconds as\n an int or a float, e.g. ``cadence=600`` selects 10-minute cadence.\n By default, all cadence modes are returned.\n mission : str, list of str\n 'Kepler', 'K2', or 'TESS'. By default, all will be returned.\n provenance_name : str, list of str\n Provenance of the data product. Defaults to official products, i.e.\n ('Kepler', 'K2', 'SPOC'). Community-provided products such as 'K2SFF'\n are supported as well.\n quarter, campaign, sector : int, list of ints\n Kepler Quarter, K2 Campaign, or TESS Sector number.\n By default all quarters/campaigns/sectors will be returned.\n month : 1, 2, 3, 4 or list of int\n For Kepler's prime mission, there are three short-cadence\n TargetPixelFiles for each quarter, each covering one month.\n Hence, if cadence='short' you can specify month=1, 2, 3, or 4.\n By default all months will be returned.\n limit : int\n Maximum number of products to return\n\n Returns\n -------\n SearchResult : :class:`SearchResult` object.\n \"\"\"\n if isinstance(target, int):\n if (0 < target) and (target < 13161030):\n log.warning(\"Warning: {} may refer to a different Kepler or TESS target. \"\n \"Please add the prefix 'KIC' or 'TIC' to disambiguate.\"\n \"\".format(target))\n elif (0 < 200000000) and (target < 251813739):\n log.warning(\"Warning: {} may refer to a different K2 or TESS target. \"\n \"Please add the prefix 'EPIC' or 'TIC' to disambiguate.\"\n \"\".format(target))\n\n # Ensure mission is a list\n mission = np.atleast_1d(mission).tolist()\n\n # Avoid filtering on `provenance_name` if `author` equals \"any\" or \"all\"\n if provenance_name in (\"any\", \"all\") or provenance_name is None:\n provenance_name = None\n else:\n provenance_name = np.atleast_1d(provenance_name).tolist()\n\n # Speed up by restricting the MAST query if we don't want FFI image data\n extra_query_criteria = {}\n if filetype in ['Lightcurve', 'Target Pixel']:\n # At MAST, non-FFI Kepler pipeline products are known as \"cube\" products,\n # and non-FFI TESS pipeline products are listed as \"timeseries\".\n extra_query_criteria['dataproduct_type'] = ['cube', 'timeseries']\n # Make sure `search_tesscut` always performs a cone search (i.e. always\n # passed a radius value), because strict target name search does not apply.\n if filetype.lower() == 'ffi' and radius is None:\n radius = .0001 * u.arcsec\n observations = _query_mast(target, radius=radius,\n project=mission,\n provenance_name=provenance_name,\n t_exptime=t_exptime,\n sequence_number=campaign or sector,\n **extra_query_criteria)\n log.debug(\"MAST found {} observations. \"\n \"Now querying MAST for the corresponding data products.\"\n \"\".format(len(observations)))\n if len(observations) == 0:\n raise SearchError('No data found for target \"{}\".'.format(target))\n\n # Light curves and target pixel files\n if filetype.lower() != 'ffi':\n from astroquery.mast import Observations\n products = Observations.get_product_list(observations)\n result = join(observations, products, keys=\"obs_id\", join_type='right',\n uniq_col_name='{col_name}{table_name}', table_names=['', '_products'])\n result.sort(['distance', 'obs_id'])\n\n # Add the user-friendly 'author' column (synonym for 'provenance_name')\n result['author'] = result['provenance_name']\n # Add the user-friendly 'observation' column\n result['observation'] = None\n obs_prefix = {'Kepler': 'Quarter', 'K2': 'Campaign', 'TESS': 'Sector'}\n for idx in range(len(result)):\n obs_project = result['project'][idx]\n obs_seqno = result['sequence_number'][idx]\n # Kepler sequence_number values were not populated at the time of\n # writing this code, so we parse them from the description field.\n if obs_project == 'Kepler' and result['sequence_number'].mask[idx]:\n try:\n obs_seqno = re.findall(r\".*Q(\\d+)\", result['description'][idx])[0]\n except IndexError:\n obs_seqno = \"\"\n result['observation'][idx] = \"{} {} {}\".format(obs_project,\n obs_prefix.get(obs_project, \"\"),\n obs_seqno)\n\n masked_result = _filter_products(result, filetype=filetype,\n campaign=campaign, quarter=quarter,\n cadence=cadence, project=mission,\n provenance_name=provenance_name,\n month=month, sector=sector, limit=limit)\n log.debug(\"MAST found {} matching data products.\".format(len(masked_result)))\n masked_result['distance'].info.format = '.1f' # display <0.1 arcsec\n return SearchResult(masked_result)\n\n # Full Frame Images\n else:\n cutouts = []\n for idx in np.where(['TESS FFI' in t for t in observations['target_name']])[0]:\n # if target passed in is a SkyCoord object, convert to RA, dec pair\n if isinstance(target, SkyCoord):\n target = '{}, {}'.format(target.ra.deg, target.dec.deg)\n # pull sector numbers\n s = observations['sequence_number'][idx]\n # if the desired sector is available, add a row\n if s in np.atleast_1d(sector) or sector is None:\n cutouts.append({'description': f'TESS FFI Cutout (sector {s})',\n 'observation': f'TESS Sector {s}',\n 'target_name': str(target),\n 'targetid': str(target),\n 't_exptime': observations['t_exptime'][idx],\n 'productFilename': 'TESSCut',\n 'provenance_name': 'MAST',\n 'author': 'MAST',\n 'distance': 0.0,\n 'sequence_number': s,\n 'project': 'TESS',\n 'obs_collection': 'TESS'}\n )\n if len(cutouts) > 0:\n log.debug(\"Found {} matching cutouts.\".format(len(cutouts)))\n masked_result = Table(cutouts)\n masked_result.sort(['distance', 'sequence_number'])\n else:\n masked_result = None\n return SearchResult(masked_result)\n\n\ndef _query_mast(target, radius=None,\n project=('Kepler', 'K2', 'TESS'),\n provenance_name=(\"Kepler\", \"K2\", \"SPOC\"),\n t_exptime=(0, 9999),\n sequence_number=None,\n **extra_query_criteria):\n \"\"\"Helper function which wraps `astroquery.mast.Observations.query_criteria()`\n to return a table of all Kepler/K2/TESS observations of a given target.\n\n By default only the official data products are returned, but this can be\n adjusted by adding alternative data product names into `provenance_name`.\n\n Parameters\n ----------\n target : str, int, or `astropy.coordinates.SkyCoord` object\n See docstrings above.\n radius : float or `astropy.units.Quantity` object\n Conesearch radius. If a float is given it will be assumed to be in\n units of arcseconds. If `None` then we default to 0.0001 arcsec.\n project : str, list of str\n Mission name. Typically 'Kepler', 'K2', or 'TESS'.\n This parameter is case-insensitive.\n provenance_name : str, list of str\n Provenance of the observation. Common options include 'Kepler', 'K2',\n 'SPOC', 'K2SFF', 'EVEREST', 'KEPSEISMIC'.\n This parameter is case-insensitive.\n t_exptime : (float, float) tuple\n Exposure time range in seconds. Common values include `(59, 61)`\n for Kepler short cadence and `(1799, 1801)` for Kepler long cadence.\n sequence_number : int, list of int\n Quarter, Campaign, or Sector number.\n **extra_query_criteria : kwargs\n Extra criteria to be passed to `astroquery.mast.Observations.query_criteria`.\n\n Returns\n -------\n obs : astropy.Table\n Table detailing the available observations on MAST.\n \"\"\"\n # Local astroquery import because the package is not used elsewhere\n from astroquery.mast import Observations\n from astroquery.exceptions import ResolverError, NoResultsWarning\n\n # If passed a SkyCoord, convert it to an \"ra, dec\" string for MAST\n if isinstance(target, SkyCoord):\n target = '{}, {}'.format(target.ra.deg, target.dec.deg)\n\n # We pass the following `query_criteria` to MAST regardless of whether\n # we search by position or target name:\n query_criteria = {\n 'project': project,\n **extra_query_criteria\n }\n if provenance_name is not None:\n query_criteria['provenance_name'] = provenance_name\n if sequence_number is not None:\n query_criteria['sequence_number'] = sequence_number\n if t_exptime is not None:\n query_criteria['t_exptime'] = t_exptime\n\n # If an exact KIC ID is passed, we will search by the exact `target_name`\n # under which MAST will know the object to prevent source confusion.\n # For discussion, see e.g. GitHub issues #148, #718.\n exact_target_name = None\n target_lower = str(target).lower()\n # Was a Kepler target ID passed?\n kplr_match = re.match(\"^(kplr|kic) ?(\\d+)$\", target_lower)\n if kplr_match:\n exact_target_name = f\"kplr{kplr_match.group(2).zfill(9)}\"\n # Was a K2 target ID passed?\n ktwo_match = re.match(\"^(ktwo|epic) ?(\\d+)$\", target_lower)\n if ktwo_match:\n exact_target_name = f\"ktwo{ktwo_match.group(2).zfill(9)}\"\n # Was a TESS target ID passed?\n tess_match = re.match(\"^(tess|tic) ?(\\d+)$\", target_lower)\n if tess_match:\n exact_target_name = f\"{tess_match.group(2).zfill(9)}\"\n\n if exact_target_name and radius is None:\n log.debug(\"Started querying MAST for observations with the exact \"\n f\"target_name='{exact_target_name}'.\")\n with warnings.catch_warnings():\n warnings.filterwarnings(\"ignore\", category=NoResultsWarning)\n obs = Observations.query_criteria(target_name=exact_target_name,\n **query_criteria)\n if len(obs) > 0:\n # astroquery does not report distance when querying by `target_name`;\n # we add it here so that the table returned always has this column.\n obs['distance'] = 0.\n return obs\n else:\n log.debug(f\"No observations found. Now performing a cone search instead.\")\n\n # If the above did not return a result, then do a cone search using the MAST name resolver\n # `radius` defaults to 0.0001 and unit arcsecond\n if radius is None:\n radius = .0001 * u.arcsec\n elif not isinstance(radius, u.quantity.Quantity):\n radius = radius * u.arcsec\n query_criteria['radius'] = str(radius.to(u.deg))\n\n try:\n log.debug(\"Started querying MAST for observations within \"\n f\"{radius.to(u.arcsec)} arcsec of objectname='{target}'.\")\n with warnings.catch_warnings():\n warnings.filterwarnings(\"ignore\", category=NoResultsWarning)\n obs = Observations.query_criteria(objectname=target,\n **query_criteria)\n obs.sort('distance')\n return obs\n except ResolverError as exc:\n # MAST failed to resolve the object name to sky coordinates\n raise SearchError(exc) from exc\n\n\ndef _filter_products(products, campaign=None, quarter=None, month=None,\n sector=None, cadence=None, limit=None,\n project=('Kepler', 'K2', 'TESS'),\n provenance_name=('Kepler', 'K2', 'SPOC'),\n filetype='Target Pixel'):\n \"\"\"Helper function which filters a SearchResult's products table by one or\n more criteria.\n\n Parameters\n ----------\n products : `astropy.table.Table` object\n Astropy table containing data products returned by MAST\n campaign : int or list\n Desired campaign of observation for data products\n quarter : int or list\n Desired quarter of observation for data products\n month : int or list\n Desired month of observation for data products\n cadence : 'long', 'short', 'fast', or float\n 'long' selects 10-min and 30-min cadence products;\n 'short' selects 1-min and 2-min products;\n 'fast' selects 20-sec products.\n Alternatively, you can pass the exact exposure time in seconds as\n an int or a float, e.g. ``cadence=600`` selects 10-minute cadence.\n By default, all cadence modes are returned.\n filetype : str\n Type of files queried at MAST (`Target Pixel` or `Lightcurve`).\n\n Returns\n -------\n products : `astropy.table.Table` object\n Masked astropy table containing desired data products\n \"\"\"\n if provenance_name is None: # apply all filters\n provenance_lower = ('kepler', 'k2', 'spoc')\n else:\n provenance_lower = [p.lower() for p in np.atleast_1d(provenance_name)]\n\n mask = np.ones(len(products), dtype=bool)\n\n # Kepler data needs a special filter for quarter, month, and file type\n mask &= ~np.array([prov.lower() == 'kepler' for prov in products['provenance_name']])\n if 'kepler' in provenance_lower and campaign is None and sector is None:\n mask |= _mask_kepler_products(products, quarter=quarter, month=month,\n filetype=filetype)\n\n # K2 data needs a special filter for file type\n mask &= ~np.array([prov.lower() == 'k2' for prov in products['provenance_name']])\n if 'k2' in provenance_lower and quarter is None and sector is None:\n mask |= _mask_k2_products(products, campaign=campaign, filetype=filetype)\n\n # TESS SPOC data needs a special filter for file type\n mask &= ~np.array([prov.lower() == 'spoc' for prov in products['provenance_name']])\n if 'spoc' in provenance_lower and quarter is None and campaign is None:\n mask |= _mask_spoc_products(products, sector=sector, filetype=filetype)\n\n # Allow only fits files\n mask &= np.array([uri.lower().endswith('fits') or\n uri.lower().endswith('fits.gz')\n for uri in products['productFilename']])\n\n # Filter by cadence\n mask &= _mask_by_cadence(products, cadence)\n\n products = products[mask]\n\n products.sort(['distance', 'productFilename'])\n if limit is not None:\n return products[0:limit]\n return products\n\n\ndef _mask_kepler_products(products, quarter=None, month=None,\n filetype='Target Pixel'):\n \"\"\"Returns a mask flagging the Kepler products that match the criteria.\"\"\"\n mask = np.array([proj.lower() == 'kepler' for proj in products['provenance_name']])\n if mask.sum() == 0:\n return mask\n\n # Filter on product type\n mask &= np.array([filetype in desc for desc in products['description']])\n\n # Identify quarter by the description.\n # This is necessary because the `sequence_number` field was not populated\n # for Kepler prime data at the time of writing this function.\n if quarter is not None:\n quarter_mask = np.zeros(len(products), dtype=bool)\n for q in np.atleast_1d(quarter):\n quarter_mask |= np.array([desc.lower().replace('-', '').endswith('q{}'.format(q))\n for desc in products['description']])\n mask &= quarter_mask\n\n # For Kepler short cadence data the month can be specified\n if month is not None:\n month = np.atleast_1d(month)\n # Get the short cadence date lookup table.\n table = ascii.read(os.path.join(PACKAGEDIR, 'data', 'short_cadence_month_lookup.csv'))\n # The following line is needed for systems where the default integer type\n # is int32 (e.g. Windows/Appveyor), the column will then be interpreted\n # as string which makes the test fail.\n table['StartTime'] = table['StartTime'].astype(str)\n # Grab the dates of each of the short cadence files.\n # Make sure every entry has the correct month\n is_shortcadence = mask & np.asarray(['Short' in desc for desc in products['description']])\n for idx in np.where(is_shortcadence)[0]:\n quarter = int(products['description'][idx].split(' - ')[-1][1:].replace('-', ''))\n date = products['dataURI'][idx].split('/')[-1].split('-')[1].split('_')[0]\n permitted_dates = []\n for m in month:\n try:\n permitted_dates.append(table['StartTime'][\n np.where((table['Month'] == m) & (table['Quarter'] == quarter))[0][0]\n ])\n except IndexError:\n pass\n if not (date in permitted_dates):\n mask[idx] = False\n\n return mask\n\n\ndef _mask_k2_products(products, campaign=None, filetype='Target Pixel'):\n \"\"\"Returns a mask flagging the K2 products that match the criteria.\"\"\"\n mask = np.array([prov.lower() == 'k2' for prov in products['provenance_name']])\n if mask.sum() == 0:\n return mask\n\n # Filter on product type\n mask &= np.array([filetype in desc for desc in products['description']])\n\n return mask\n\n\ndef _mask_spoc_products(products, sector=None, filetype='Target Pixel'):\n \"\"\"Returns a mask flagging the TESS products that match the criteria.\"\"\"\n mask = np.array([p.lower() == 'spoc' for p in products['provenance_name']])\n if mask.sum() == 0:\n return mask\n\n # Filter on product type\n if filetype.lower() == 'lightcurve':\n description_string = 'Light curves'\n elif filetype.lower() == 'target pixel':\n description_string = 'Target pixel files'\n elif filetype.lower() == 'ffi':\n description_string = 'TESScut'\n mask &= np.array([description_string in desc for desc in products['description']])\n\n return mask\n\n\ndef _mask_by_cadence(products, cadence):\n \"\"\"Helper function to filter by exposure time.\"\"\"\n mask = np.ones(len(products), dtype=bool)\n if isinstance(cadence, (int, float)):\n mask &= products['t_exptime'] == cadence\n elif cadence in ['fast']:\n mask &= products['t_exptime'] < 60\n elif cadence in ['short']:\n mask &= (products['t_exptime'] >= 60) & (products['t_exptime'] < 300)\n elif cadence in ['long', 'ffi']:\n mask &= products['t_exptime'] >= 300\n return mask\n\n\ndef _resolve_object(target):\n \"\"\"Ask MAST to resolve an object string to a set of coordinates.\"\"\"\n from astroquery.mast import MastClass\n # Note: `_resolve_object` was renamed `resolve_object` in astroquery 0.3.10 (2019)\n return MastClass().resolve_object(target)\n"
]
| [
[
"numpy.unique",
"numpy.asarray",
"numpy.atleast_1d",
"numpy.array",
"numpy.where"
]
]
|
IC-hub/ProteinLM | [
"fda4f381b4b974721b187cece968dd7bc96a81f4"
]
| [
"tape/tape/utils/utils.py"
]
| [
"import typing\nimport random\nfrom pathlib import Path\nimport logging\nfrom time import strftime, gmtime\nfrom datetime import datetime\nimport os\nimport argparse\nimport contextlib\nfrom collections import defaultdict\n\nimport numpy as np\nimport torch\nfrom torch.utils.data import Dataset\nimport torch.distributed as dist\n\nlogger = logging.getLogger(__name__)\nFloatOrTensor = typing.Union[float, torch.Tensor]\n\n\ndef int_or_str(arg: str) -> typing.Union[int, str]:\n try:\n return int(arg)\n except ValueError:\n return arg\n\n\ndef check_is_file(file_path: str) -> str:\n if file_path is None or os.path.isfile(file_path):\n return file_path\n else:\n raise argparse.ArgumentTypeError(f\"File path: {file_path} is not a valid file\")\n\n\ndef check_is_dir(dir_path: str) -> str:\n if dir_path is None or os.path.isdir(dir_path):\n return dir_path\n else:\n raise argparse.ArgumentTypeError(f\"Directory path: {dir_path} is not a valid directory\")\n\n\ndef path_to_datetime(path: Path) -> datetime:\n name = path.name\n datetime_string = name.split('_')[0]\n try:\n year, month, day, hour, minute, second = datetime_string.split('-')\n except ValueError:\n try:\n # Deprecated datetime strings\n year, month, day, time_str = datetime_string.split('-')\n hour, minute, second = time_str.split(':')\n except ValueError:\n return datetime(1, 1, 1)\n\n pathdatetime = datetime(\n int(year), int(month), int(day), int(hour), int(minute), int(second))\n return pathdatetime\n\n\ndef get_expname(exp_name: typing.Optional[str],\n task: typing.Optional[str] = None,\n model_type: typing.Optional[str] = None,\n save_name: typing.Optional[str] = 'time') -> str:\n if exp_name is None:\n # add time_or_name param, to specify ckpt folder's name manually, instead of timestamp+randint\n # reason to do so: to make eval script easy, load from the specified folder\n if save_name == 'time':\n time_stamp = strftime(\"%y-%m-%d-%H-%M-%S\", gmtime())\n exp_name = f\"{task}_{model_type}_{time_stamp}_{random.randint(0, int(1e6)):0>6d}\"\n else:\n exp_name = f\"{task}_{model_type}_{save_name}\"\n return exp_name\n\n\ndef set_random_seeds(seed: int, n_gpu: int) -> None:\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n if n_gpu > 0:\n torch.cuda.manual_seed_all(seed) # type: ignore\n\n\ndef get_effective_num_gpus(local_rank: int, n_gpu: int) -> int:\n if local_rank == -1:\n num_gpus = n_gpu\n else:\n num_gpus = dist.get_world_size()\n return num_gpus\n\n\ndef get_effective_batch_size(batch_size: int,\n local_rank: int,\n n_gpu: int,\n gradient_accumulation_steps: int = 1) -> int:\n eff_batch_size = float(batch_size)\n eff_batch_size /= gradient_accumulation_steps\n eff_batch_size /= get_effective_num_gpus(local_rank, n_gpu)\n return int(eff_batch_size)\n\n\ndef get_num_train_optimization_steps(dataset: Dataset,\n batch_size: int,\n num_train_epochs: int) -> int:\n return int(len(dataset) / batch_size * num_train_epochs)\n\n\nclass MetricsAccumulator:\n\n def __init__(self, smoothing: float = 0.95):\n self._loss_tmp = 0.\n self._smoothloss: typing.Optional[float] = None\n self._totalloss = 0.\n self._metricstmp: typing.Dict[str, float] = defaultdict(lambda: 0.0)\n self._smoothmetrics: typing.Dict[str, float] = {}\n self._totalmetrics: typing.Dict[str, float] = defaultdict(lambda: 0.0)\n\n self._nacc_steps = 0\n self._nupdates = 0\n self._smoothing = smoothing\n\n def update(self,\n loss: FloatOrTensor,\n metrics: typing.Dict[str, FloatOrTensor],\n step: bool = True) -> None:\n if isinstance(loss, torch.Tensor):\n loss = loss.item()\n\n self._loss_tmp += loss\n for name, value in metrics.items():\n if isinstance(value, torch.Tensor):\n value = value.item()\n self._metricstmp[name] += value\n self._nacc_steps += 1\n\n if step:\n self.step()\n\n def step(self) -> typing.Dict[str, float]:\n loss_tmp = self._loss_tmp / self._nacc_steps\n metricstmp = {name: value / self._nacc_steps\n for name, value in self._metricstmp.items()}\n\n if self._smoothloss is None:\n self._smoothloss = loss_tmp\n else:\n self._smoothloss *= self._smoothing\n self._smoothloss += (1 - self._smoothing) * loss_tmp\n self._totalloss += loss_tmp\n\n for name, value in metricstmp.items():\n if name in self._smoothmetrics:\n currvalue = self._smoothmetrics[name]\n newvalue = currvalue * self._smoothing + value * (1 - self._smoothing)\n else:\n newvalue = value\n\n self._smoothmetrics[name] = newvalue\n self._totalmetrics[name] += value\n\n self._nupdates += 1\n\n self._nacc_steps = 0\n self._loss_tmp = 0\n self._metricstmp = defaultdict(lambda: 0.0)\n\n metricstmp['loss'] = loss_tmp\n return metricstmp\n\n def loss(self) -> float:\n if self._smoothloss is None:\n raise RuntimeError(\"Trying to get the loss without any updates\")\n return self._smoothloss\n\n def metrics(self) -> typing.Dict[str, float]:\n if self._nupdates == 0:\n raise RuntimeError(\"Trying to get metrics without any updates\")\n return dict(self._smoothmetrics)\n\n def final_loss(self) -> float:\n return self._totalloss / self._nupdates\n\n def final_metrics(self) -> typing.Dict[str, float]:\n return {name: value / self._nupdates\n for name, value in self._totalmetrics.items()}\n\n\nclass wrap_cuda_oom_error(contextlib.ContextDecorator):\n \"\"\"A context manager that wraps the Cuda OOM message so that you get some more helpful\n context as to what you can/should change. Can also be used as a decorator.\n\n Examples:\n 1) As a context manager:\n\n with wrap_cuda_oom_error(local_rank, batch_size, n_gpu, gradient_accumulation):\n loss = model.forward(batch)\n loss.backward()\n optimizer.step()\n optimizer.zero_grad\n\n 2) As a decorator:\n\n @wrap_cuda_oom_error(local_rank, batch_size, n_gpu, gradient_accumulation)\n def run_train_epoch(args):\n ...\n <code to run training epoch>\n ...\n \"\"\"\n\n def __init__(self,\n local_rank: int,\n batch_size: int,\n n_gpu: int = 1,\n gradient_accumulation_steps: typing.Optional[int] = None):\n self._local_rank = local_rank\n self._batch_size = batch_size\n self._n_gpu = n_gpu\n self._gradient_accumulation_steps = gradient_accumulation_steps\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n exc_args = exc_value.args if exc_value is not None else None\n if exc_args and 'CUDA out of memory' in exc_args[0]:\n eff_ngpu = get_effective_num_gpus(self._local_rank, self._n_gpu)\n if self._gradient_accumulation_steps is not None:\n eff_batch_size = get_effective_batch_size(\n self._batch_size, self._local_rank, self._n_gpu,\n self._gradient_accumulation_steps)\n message = (f\"CUDA out of memory. Reduce batch size or increase \"\n f\"gradient_accumulation_steps to divide each batch over more \"\n f\"forward passes.\\n\\n\"\n f\"\\tHyperparameters:\\n\"\n f\"\\t\\tbatch_size per backward-pass: {self._batch_size}\\n\"\n f\"\\t\\tgradient_accumulation_steps: \"\n f\"{self._gradient_accumulation_steps}\\n\"\n f\"\\t\\tn_gpu: {eff_ngpu}\\n\"\n f\"\\t\\tbatch_size per (gpu * forward-pass): \"\n f\"{eff_batch_size}\")\n else:\n eff_batch_size = get_effective_batch_size(\n self._batch_size, self._local_rank, self._n_gpu)\n message = (f\"CUDA out of memory. Reduce batch size to fit each \"\n f\"iteration in memory.\\n\\n\"\n f\"\\tHyperparameters:\\n\"\n f\"\\t\\tbatch_size per forward-pass: {self._batch_size}\\n\"\n f\"\\t\\tn_gpu: {eff_ngpu}\\n\"\n f\"\\t\\tbatch_size per (gpu * forward-pass): \"\n f\"{eff_batch_size}\")\n raise RuntimeError(message)\n return False\n\n\ndef write_lmdb(filename: str, iterable: typing.Iterable, map_size: int = 2 ** 20):\n \"\"\"Utility for writing a dataset to an LMDB file.\n\n Args:\n filename (str): Output filename to write to\n iterable (Iterable): An iterable dataset to write to. Entries must be pickleable.\n map_size (int, optional): Maximum allowable size of database in bytes. Required by LMDB.\n You will likely have to increase this. Default: 1MB.\n \"\"\"\n import lmdb\n import pickle as pkl\n env = lmdb.open(filename, map_size=map_size)\n\n with env.begin(write=True) as txn:\n for i, entry in enumerate(iterable):\n txn.put(str(i).encode(), pkl.dumps(entry))\n txn.put(b'num_examples', pkl.dumps(i + 1))\n env.close()\n\n\nclass IncrementalNPZ(object):\n # Modified npz that allows incremental saving, from https://stackoverflow.com/questions/22712292/how-to-use-numpy-savez-in-a-loop-for-save-more-than-one-array # noqa: E501\n def __init__(self, file):\n import tempfile\n import zipfile\n import os\n\n if isinstance(file, str):\n if not file.endswith('.npz'):\n file = file + '.npz'\n\n compression = zipfile.ZIP_STORED\n\n zipfile = self.zipfile_factory(file, mode=\"w\", compression=compression)\n\n # Stage arrays in a temporary file on disk, before writing to zip.\n fd, tmpfile = tempfile.mkstemp(suffix='-numpy.npy')\n os.close(fd)\n\n self.tmpfile = tmpfile\n self.zip = zipfile\n self._i = 0\n\n def zipfile_factory(self, *args, **kwargs):\n import zipfile\n import sys\n if sys.version_info >= (2, 5):\n kwargs['allowZip64'] = True\n return zipfile.ZipFile(*args, **kwargs)\n\n def savez(self, *args, **kwds):\n import os\n import numpy.lib.format as fmt\n\n namedict = kwds\n for val in args:\n key = 'arr_%d' % self._i\n if key in namedict.keys():\n raise ValueError(\"Cannot use un-named variables and keyword %s\" % key)\n namedict[key] = val\n self._i += 1\n\n try:\n for key, val in namedict.items():\n fname = key + '.npy'\n fid = open(self.tmpfile, 'wb')\n with open(self.tmpfile, 'wb') as fid:\n fmt.write_array(fid, np.asanyarray(val), allow_pickle=True)\n self.zip.write(self.tmpfile, arcname=fname)\n finally:\n os.remove(self.tmpfile)\n\n def close(self):\n self.zip.close()\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n self.close()\n"
]
| [
[
"numpy.random.seed",
"torch.manual_seed",
"numpy.asanyarray",
"torch.cuda.manual_seed_all",
"torch.distributed.get_world_size"
]
]
|
pappuks/rpi-soundmeter | [
"8d1aa585cc08669bc496cdb64ce7fed0c9403971"
]
| [
"spl_meter_lcd.py"
]
| [
"#!/usr/bin/env python\nimport os, errno\nimport pyaudio\nimport spl_lib as spl\nfrom scipy.signal import lfilter\nimport numpy\nimport lcd1602 as lcd1602\nimport led_bcm as led\n\n## For web browser handling\n#from selenium import webdriver\n\n\n''' The following is similar to a basic CD quality\n When CHUNK size is 4096 it routinely throws an IOError.\n When it is set to 8192 it doesn't.\n IOError happens due to the small CHUNK size\n\n What is CHUNK? Let's say CHUNK = 4096\n math.pow(2, 12) => RATE / CHUNK = 100ms = 0.1 sec\n'''\nCHUNKS = [4096, 9600] # Use what you need\nCHUNK = CHUNKS[1]\nFORMAT = pyaudio.paInt16 # 16 bit\nCHANNEL = 1 # 1 means mono. If stereo, put 2\n\n'''\nDifferent mics have different rates.\nFor example, Logitech HD 720p has rate 48000Hz\n'''\nRATES = [44300, 48000]\nRATE = RATES[1]\n\nNUMERATOR, DENOMINATOR = spl.A_weighting(RATE)\n\nSND_SAMPLES = list()\nLED_THRESHOLD = 70 # 70 dB threshold\n\ndef get_path(base, tail, head=''):\n return os.path.join(base, tail) if head == '' else get_path(head, get_path(base, tail)[1:])\n\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\nHTML_PATH = get_path(BASE_DIR, 'html/main.html', 'file:///')\nSINGLE_DECIBEL_FILE_PATH = get_path(BASE_DIR, 'decibel_data/single_decibel.txt')\nMAX_DECIBEL_FILE_PATH = get_path(BASE_DIR, 'decibel_data/max_decibel.txt')\n\n'''\nListen to mic\n'''\npa = pyaudio.PyAudio()\n\nstream = pa.open(format = FORMAT,\n channels = CHANNEL,\n rate = RATE,\n input = True,\n frames_per_buffer = CHUNK)\n\n\ndef is_meaningful(old, new):\n return abs(old - new) > 3\n\ndef update_text(path, content):\n try:\n f = open(path, 'w')\n except IOError as e:\n print(e)\n else:\n f.write(content)\n f.close()\n\ndef click(id):\n driver.find_element_by_id(id).click()\n\ndef open_html(path):\n driver.get(path)\n\ndef update_max_if_new_is_larger_than_max(new, max):\n print(\"update_max_if_new_is_larger_than_max called\")\n if new > max:\n print(\"max observed\")\n #update_text(MAX_DECIBEL_FILE_PATH, 'MAX: {:.2f} dBA'.format(new))\n #click('update_max_decibel')\n return new\n else:\n return max\n\ndef addSoundSample(new):\n if (len(SND_SAMPLES) > 300):\n SND_SAMPLES.pop(0)\n SND_SAMPLES.append(new)\n return max(SND_SAMPLES)\n\n\ndef listen(old=0, error_count=0, min_decibel=100, max_decibel=0, prev_led_max=0):\n global lcd\n lcd = lcd1602.LCD()\n print(\"Listening\")\n lcd.clear()\n lcd.message(\"Listening\")\n while True:\n try:\n ## read() returns string. You need to decode it into an array later.\n block = stream.read(CHUNK)\n except IOError as e:\n error_count += 1\n print(\" (%d) Error recording: %s\" % (error_count, e))\n lcd.clear()\n lcd.message(\"Error recording\")\n else:\n ## Int16 is a numpy data type which is Integer (-32768 to 32767)\n ## If you put Int8 or Int32, the result numbers will be ridiculous\n decoded_block = numpy.fromstring(block, 'Int16')\n ## This is where you apply A-weighted filter\n y = lfilter(NUMERATOR, DENOMINATOR, decoded_block)\n new_decibel = 20*numpy.log10(spl.rms_flat(y))\n if is_meaningful(old, new_decibel):\n old = new_decibel\n print('A-weighted: {:+.2f} dB'.format(new_decibel))\n \n #update_text(SINGLE_DECIBEL_FILE_PATH, '{:.2f} dBA'.format(new_decibel))\n #max_decibel = update_max_if_new_is_larger_than_max(new_decibel, max_decibel)\n max_decibel = addSoundSample(new_decibel)\n lcd.clear()\n lcd.message('Max New:\\n{:+.2f}'.format(max_decibel) + ' {:+.2f} dB'.format(new_decibel))\n if (max_decibel > LED_THRESHOLD):\n led.led_on()\n else:\n led.led_off()\n sleep(1) # sleep for 1 second before reading next sample\n #click('update_decibel')\n\n\n stream.stop_stream()\n stream.close()\n pa.terminate()\n\ndef destroy():\n lcd.destroy()\n led.destroy_led()\n\nif __name__ == '__main__':\n #driver = webdriver.Firefox()\n #open_html(HTML_PATH)\n try:\n led.setup_led()\n listen()\n except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed.\n destroy()\n #driver.close()\n"
]
| [
[
"scipy.signal.lfilter",
"numpy.fromstring"
]
]
|
liuhongbing1220/fundanNLP_task | [
"20c7b3b5d21d4b030dc936b2f0bc54fc17f9a619"
]
| [
"segment_classifier/charCNN_classifier/charCNN_model.py"
]
| [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jun 29 13:07:37 2019\n\n@author: liuhongbing\n\"\"\" \n \n# coding=utf-8\nimport tensorflow as tf\nfrom read_data import Dataset\nfrom math import sqrt\n\n\nclass CharCNN(object):\n \"\"\"\n A CNN for text classification.\n Uses an embedding layer, followed by a convolutional, max-pooling and softmax layer.\n \"\"\"\n def __init__(self, l0, num_classes, alphabet_size, convLayers,fcLayers,l2_reg_lambda=0.0):\n \n # Placeholders for input, output and dropout\n self.input_x = tf.placeholder(tf.int32, [None, l0], name=\"input_x\")\n self.input_y = tf.placeholder(tf.float32, [None, num_classes], name=\"input_y\")\n self.dropout_keep_prob = tf.placeholder(tf.float32, name=\"dropout_keep_prob\")\n\n # Keeping track of l2 regularization loss (optional)\n l2_loss = tf.constant(0.0)\n\n # Embedding layer\n with tf.device('/cpu:0'), tf.name_scope(\"embedding\"):\n \n train_data = Dataset()\n self.W, _ = train_data.onehot_dic_build()\n self.x_image = tf.nn.embedding_lookup(self.W, self.input_x)\n self.x_flat = tf.expand_dims(self.x_image, -1)\n \n print('X-flat-origin:', self.x_flat)\n for i, cl in enumerate(convLayers):\n with tf.name_scope(\"conv_layer-%s\" % (i+1)):\n print(\"开始第\" + str(i + 1) + \"卷积层的处理\")\n \n filter_width = self.x_flat.get_shape()[2].value\n filter_shape = [cl[1], filter_width, 1, cl[0]]\n\n stdv = 1 / sqrt(cl[0] * cl[1])\n w_conv = tf.Variable(tf.random_uniform(filter_shape, minval=-stdv, maxval=stdv),\n dtype='float32', name='w')\n # w_conv = tf.Variable(tf.truncated_normal(filter_shape, stddev=0.05), name=\"W\")\n b_conv = tf.Variable(tf.random_uniform(shape=[cl[0]], minval=-stdv, maxval=stdv), name='b')\n # b_conv = tf.Variable(tf.constant(0.1, shape=[cl[0]]), name=\"b\")\n conv = tf.nn.conv2d(\n self.x_flat,\n w_conv,\n strides=[1, 1, 1, 1],\n padding=\"VALID\",\n name=\"conv\"\n )\n h_conv = tf.nn.bias_add(conv, b_conv)\n\n\n if not cl[-1] is None:\n ksize_shape = [1, cl[2], 1, 1]\n h_pool = tf.nn.max_pool(\n h_conv,\n ksize=ksize_shape,\n strides=ksize_shape,\n padding='VALID',\n name='pool')\n else:\n h_pool = h_conv\n \n self.x_flat = tf.transpose(h_pool, [0, 1, 3, 2], name='transpose')\n# print(\"filter_width:\", filter_width)\n# print(\"h_conv:\", h_conv)\n# print(\"h_pool:\", h_pool)\n# print(\"x_flat\", self.x_flat)\n\n with tf.name_scope('reshape'):\n fc_dim = self.x_flat.get_shape()[1].value * self.x_flat.get_shape()[2].value\n self.x_flat = tf.reshape(self.x_flat, [-1, fc_dim])\n\n\n print(\"x_flat:\", self.x_flat)\n weights = [fc_dim] + fcLayers\n \n for i, fl in enumerate(fcLayers):\n \n with tf.name_scope('fc_layer-%s' % (i+1)):\n print(\"开始第\" + str(i + 1) + \"全连接层的处理\")\n stdv = 1 / sqrt(weights[i])\n \n w_fc = tf.Variable(tf.random_uniform([weights[i], fl], minval=-stdv, maxval=stdv), \n dtype='float32', name='w')\n \n b_fc = tf.Variable(tf.random_uniform(shape=[fl], minval=-stdv, maxval=stdv), dtype='float32', name='b')\n # 不同的初始化方式\n # w_fc = tf.Variable(tf.truncated_normal([weights[i], fl], stddev=0.05), name=\"W\")\n # b_fc = tf.Variable(tf.constant(0.1, shape=[fl]), name=\"b\")\n self.x_flat = tf.nn.relu(tf.matmul(self.x_flat, w_fc) + b_fc)\n\n with tf.name_scope('drop_out'):\n self.x_flat = tf.nn.dropout(self.x_flat, self.dropout_keep_prob)\n\n with tf.name_scope('output_layer'):\n print(\"开始输出层的处理\")\n # w_out = tf.Variable(tf.truncated_normal([fc_layers[-1], num_classes], stddev=0.1), name=\"W\")\n # b_out = tf.Variable(tf.constant(0.1, shape=[num_classes]), name=\"b\")\n stdv = 1 / sqrt(weights[-1])\n w_out = tf.Variable(tf.random_uniform([fcLayers[-1], num_classes], minval=-stdv, maxval=stdv), \n dtype='float32', name='W')\n b_out = tf.Variable(tf.random_uniform(shape=[num_classes], minval=-stdv, maxval=stdv), name='b')\n self.y_pred = tf.nn.xw_plus_b(self.x_flat, w_out, b_out, name=\"y_pred\")\n self.predictions = tf.argmax(self.y_pred, 1, name=\"predictions\")\n\n # CalculateMean cross-entropy loss\n with tf.name_scope(\"loss\"):\n losses = tf.nn.softmax_cross_entropy_with_logits(logits=self.y_pred, labels=self.input_y)\n self.loss = tf.reduce_mean(losses) + l2_reg_lambda * l2_loss\n\n # Accuracy\n with tf.name_scope(\"accuracy\"):\n correct_predictions = tf.equal(self.predictions, tf.argmax(self.input_y, 1))\n self.accuracy = tf.reduce_mean(tf.cast(correct_predictions, \"float\"), name=\"accuracy\")\n\n\n\n\n\n"
]
| [
[
"tensorflow.device",
"tensorflow.nn.softmax_cross_entropy_with_logits",
"tensorflow.nn.max_pool",
"tensorflow.cast",
"tensorflow.nn.conv2d",
"tensorflow.name_scope",
"tensorflow.argmax",
"tensorflow.nn.dropout",
"tensorflow.nn.xw_plus_b",
"tensorflow.matmul",
"tensorflow.placeholder",
"tensorflow.nn.embedding_lookup",
"tensorflow.nn.bias_add",
"tensorflow.constant",
"tensorflow.transpose",
"tensorflow.reduce_mean",
"tensorflow.reshape",
"tensorflow.expand_dims",
"tensorflow.random_uniform"
]
]
|
Daniel1586/Initiative_machine_learning | [
"dfbadd50c14ccccf1cd28acc314e4ae8cd511f60"
]
| [
"04_classification_naive_bayes/tutorials_naive_bayes.py"
]
| [
"#!/usr/bin/python\n# -*- coding:utf-8 -*-\n\n\"\"\"\n@file: tutorials_naive_bayes.py\n\"\"\"\nimport numpy as np\nimport pandas as pd\n\n\n# 读取样本数据,最后1列为类别\ndef load_data(file):\n dataset = pd.read_csv(file)\n\n return dataset\n\n\n# 数据集划分训练集和测试集(当前设置测试集仅1个数据)\n# 返回数据类型为n维数组格式\ndef split_dataset(dataset, test_size=1):\n cols = dataset.columns.tolist()\n data_idx = dataset.index.tolist()\n test_idx = data_idx[-test_size:]\n train_idx = [i for i in data_idx if i not in test_idx]\n\n # 计算训练集, 转化为n维数组格式\n trainset = dataset.iloc[train_idx]\n train_datas = trainset.values[:, 0:len(cols)-1]\n train_label = trainset.values[:, -1:]\n\n # 计算测试集, 转化为n维数组格式\n testset = dataset.iloc[test_idx]\n test_datas = testset.values[:, 0:len(cols)-1]\n test_label = testset.values[:, -1:]\n\n return train_datas, train_label, test_datas, test_label\n\n\n# 分类算法--朴素贝叶斯\nclass NaiveBayes:\n\n def __init__(self):\n self.classes = None\n self.x = None\n self.y = None\n self.paras = [] # 存储数据集中每个特征中每个特征值出现概率\n\n # 计算不同类别不同特征不同特征值的条件概率\n def fit(self, x, y):\n self.x = x\n self.y = y\n self.classes = np.unique(y)\n\n # 遍历所有类别\n for i in range(len(self.classes)):\n c = self.classes[i]\n c_idx = np.where(y == c)\n c_set = x[c_idx[0]]\n self.paras.append([])\n\n # 遍历相同类别不同特征\n for j in range(c_set.shape[1]):\n c_para = {}\n c_attr = np.unique(c_set[:, j])\n\n # 遍历相同特征不同特征值\n for attr_value in c_attr:\n attr_value_num = c_set[c_set[:, j] == attr_value].shape[0]\n attr_value_pro = attr_value_num/c_set.shape[0]\n c_para[attr_value] = attr_value_pro\n self.paras[i].append(c_para)\n\n # 计算类别先验概率\n def calc_prior_prob(self, c):\n c_idx = np.where(self.y == c)\n c_set = self.x[c_idx[0]]\n prior = c_set.shape[0]/self.x.shape[0]\n\n return prior\n\n # 单个样本数据分类\n def classify(self, sample):\n posteriors = []\n\n # 遍历所有类别,计算后验概率\n for i in range(len(self.classes)):\n c = self.classes[i]\n prior = self.calc_prior_prob(c)\n posterior = prior\n\n # 遍历所有特征的特征值\n for j, params in enumerate(self.paras[i]):\n sample_attr = sample[j] # 预测样本第j个特征的值\n prob = params.get(sample_attr)\n posterior *= prob\n\n posteriors.append(posterior)\n\n # 后验概率排序,找出最大后验概率\n idx_of_max = np.argmax(posteriors)\n max_value = posteriors[idx_of_max]\n max_class = self.classes[idx_of_max]\n print(\"The max posterior prob: \", max_value)\n print(\"Classes by Naive Bayes: \", max_class)\n\n return max_class\n\n # 对数据集进行类别预测\n def predict(self, x):\n y_predict = []\n for sample in x:\n y = self.classify(sample)\n y_predict.append(y)\n\n return np.array(y_predict)\n\n\nif __name__ == \"__main__\":\n filename = \"dataset.csv\"\n data_set = load_data(filename)\n x_train, y_train, x_test, y_test = split_dataset(data_set, test_size=1)\n\n clf = NaiveBayes()\n clf.fit(x_train, y_train)\n y_pred = clf.predict(x_test)\n"
]
| [
[
"pandas.read_csv",
"numpy.unique",
"numpy.argmax",
"numpy.array",
"numpy.where"
]
]
|
MICLab-Unicamp/BTRSeg | [
"03078ac591fe95cf6cf3efaeb00ebf3e509181dc"
]
| [
"src/train.py"
]
| [
"'''\nExperiment Description\nBTRSeg architecutre: expansion of the 2D UNet from E2DHipseg to 3D, testing various parameter configurations.\n'''\nEXPERIMENT_NAME = \"BTRSeg\"\n\n# Standard Library\nimport os\nimport logging\nimport argparse\n\n# External Libraries\nimport numpy as np\nimport torch\nfrom torch.optim import Adam, SGD\n\n# Pytorch Lightning\nimport pytorch_lightning as pl\nfrom pytorch_lightning import Trainer\nfrom pytorch_lightning.loggers import MLFlowLogger\nfrom pytorch_lightning.callbacks import ModelCheckpoint\n\n# DLPT\nfrom DLPT.models.unet import UNet\nfrom DLPT.metrics.brats import BraTSMetrics\nfrom DLPT.loss.dice import DICELoss, BalancedMultiChannelDICELoss\nfrom DLPT.optimizers.radam import RAdam\nfrom DLPT.transforms.to_tensor import ToTensor\nfrom DLPT.transforms.patches import ReturnPatch, CenterCrop\nfrom DLPT.transforms.intensity import RandomIntensity\nfrom DLPT.transforms import Compose\nfrom DLPT.datasets.brats import BRATS\nfrom DLPT.utils.git import get_git_hash\nfrom DLPT.utils.reproducible import deterministic_run\n\n\nBRATS.PATHS[\"2020\"][\"default\"] = \"data/MICCAI_BraTS2020_TrainingData\"\n\n\nclass BRATS3DSegmentation(pl.LightningModule):\n def __init__(self, hparams, loss, metric):\n super(BRATS3DSegmentation, self).__init__()\n self.loss_calculator = loss\n self.metric_calculator = metric\n self.hparams = hparams\n self.model = UNet(n_channels=hparams.nin, n_classes=hparams.nout,\n apply_sigmoid=self.hparams.final_labels, apply_softmax=not(self.hparams.final_labels),\n residual=True, small=False, bias=False, bn=self.hparams.norm,\n dim='3d', use_attention=self.hparams.use_attention, channel_factor=self.hparams.channel_factor)\n\n def forward(self, x):\n return self.model(x)\n\n def training_step(self, batch, batch_idx):\n '''\n Training\n '''\n x, y, _, _, _ = batch\n y_hat = self.forward(x)\n loss = self.loss_calculator(y_hat, y) # DICE Loss per channel mean\n\n tensorboard_logs = {'loss': loss}\n\n return {'loss': loss, 'log': tensorboard_logs}\n\n def validation_step(self, batch, batch_idx):\n '''\n Validation step.\n '''\n x, y, _, _, _ = batch\n y_hat = self.forward(x)\n loss = self.loss_calculator(y_hat, y) # DICE Loss per channel mean\n metrics = self.metric_calculator(y_hat, y)\n metrics[\"loss\"] = loss\n\n return metrics\n\n def test_step(self, batch, batch_idx):\n '''\n Test. Should be exactly equal to validation step\n '''\n x, y, _, _, _ = batch\n y_hat = self.forward(x)\n loss = self.loss_calculator(y_hat, y) # DICE Loss per channel mean\n metrics = self.metric_calculator(y_hat, y)\n metrics[\"loss\"] = loss\n\n return metrics\n\n # -----------------------------------------------------------------------------------------------------------------#\n\n def training_epoch_end(self, outputs):\n '''\n Training\n '''\n name = \"train_\"\n\n avg_loss = torch.stack([x['loss'] for x in outputs]).mean()\n\n return {'log': {name + 'loss': avg_loss}}\n\n def validation_epoch_end(self, outputs):\n '''\n Validation\n '''\n name = 'val_'\n\n # Initialize metric dict\n metrics = {}\n for k in outputs[0].keys():\n metrics[name + k] = []\n\n # Fill metric dict\n for x in outputs:\n for k, v in x.items():\n metrics[name + k].append(v)\n\n # Get mean for every metric\n for k, v in metrics.items():\n if k == name + 'loss':\n metrics[k] = torch.stack(v).mean()\n else:\n metrics[k] = np.array(v).mean()\n\n avg_loss = metrics[name + \"loss\"]\n tqdm_dict = {name + \"loss\": avg_loss}\n\n print(tqdm_dict)\n if self.hparams.balanced_dice:\n loss_calculator.increment_weights()\n\n return {name + 'loss': avg_loss, 'log': metrics, 'progress_bar': tqdm_dict,\n name + \"WT_dice\": metrics[name + \"WT_dice\"],\n name + \"TC_dice\": metrics[name + \"TC_dice\"],\n name + \"ET_dice\": metrics[name + \"ET_dice\"]\n }\n\n def test_epoch_end(self, outputs):\n '''\n Test\n '''\n name = 'test_'\n\n # Initialize metric dict\n metrics = {}\n for k in outputs[0].keys():\n metrics[name + k] = []\n\n # Fill metric dict\n for x in outputs:\n for k, v in x.items():\n metrics[name + k].append(v)\n\n # Get mean for every metric\n for k, v in metrics.items():\n if k == name + 'loss':\n metrics[k] = torch.stack(v).mean()\n else:\n metrics[k] = np.array(v).mean()\n\n avg_loss = metrics[name + \"loss\"]\n tqdm_dict = {name + \"loss\": avg_loss}\n\n return {name + 'loss': avg_loss, 'log': metrics, 'progress_bar': tqdm_dict,\n name + \"WT_dice\": metrics[name + \"WT_dice\"],\n name + \"TC_dice\": metrics[name + \"TC_dice\"],\n name + \"ET_dice\": metrics[name + \"ET_dice\"]\n }\n\n # -----------------------------------------------------------------------------------------------------------------#\n\n def configure_optimizers(self):\n if self.hparams.opt == \"Adam\":\n opt = Adam(self.model.parameters(), lr=self.hparams.lr, weight_decay=self.hparams.wd)\n elif self.hparams.opt == \"RAdam\":\n opt = RAdam(self.model.parameters(), lr=self.hparams.lr, weight_decay=self.hparams.wd)\n elif self.hparams.opt == \"SGD\":\n opt = SGD(self.model.parameters(), lr=self.hparams.lr, weight_decay=self.hparams.wd)\n\n return [opt], [torch.optim.lr_scheduler.ExponentialLR(opt, gamma=0.985)]\n\n def train_dataloader(self):\n dataset = BRATS(year=self.hparams.dataset_year, release=\"default\", group=\"all\", mode=\"train\",\n transform=transforms, convert_to_eval_format=(self.hparams.nout == 3))\n return dataset.get_dataloader(batch_size=self.hparams.bs, shuffle=True if self.hparams.forced_overfit == 0 else False,\n num_workers=0 if self.hparams.cpu else 4)\n\n def val_dataloader(self):\n dataset = BRATS(year=self.hparams.dataset_year, release=\"default\", group=\"all\", mode=\"validation\",\n transform=test_transforms, convert_to_eval_format=(self.hparams.nout == 3))\n return dataset.get_dataloader(batch_size=self.hparams.test_bs, shuffle=False, num_workers=0 if self.hparams.cpu else 4)\n\n def test_dataloader(self):\n dataset = BRATS(year=self.hparams.dataset_year, release=\"default\", group=\"all\", mode=\"test\",\n transform=test_transforms, convert_to_eval_format=(self.hparams.nout == 3))\n return dataset.get_dataloader(batch_size=self.hparams.test_bs, shuffle=False, num_workers=0 if self.hparams.cpu else 4)\n\n\ntest_transforms = Compose([CenterCrop(128, 128, 128, segmentation=True, assert_big_enough=True),\n ToTensor(volumetric=True, classify=False)])\nmodel_folder = \"models\"\nlog_folder = \"mlruns\"\n\nif __name__ == \"__main__\":\n # Logging initialization\n debug = False\n FORMAT = '%(asctime)s %(levelname)s: %(message)s'\n logging.basicConfig(level=logging.DEBUG if debug else logging.INFO, format=FORMAT)\n logging.info(\"Logging initialized with debug={}\".format(debug))\n\n loss_calculator = DICELoss(volumetric=True, per_channel=True)\n metric_calculator = BraTSMetrics(dice_only=True)\n\n transforms = Compose([ReturnPatch(patch_size=(128, 128, 128), segmentation=True, fullrandom=True,\n reset_seed=False), RandomIntensity(reset_seed=False),\n ToTensor(volumetric=True, classify=False)])\n test_transforms = Compose([CenterCrop(128, 128, 128, segmentation=True, assert_big_enough=True),\n ToTensor(volumetric=True, classify=False)])\n\n parser = argparse.ArgumentParser()\n parser.add_argument(dest=\"desc\", type=str)\n\n # Variables to experimented with\n parser.add_argument(\"-bs\", type=int, required=True, help=\"Batch size.\")\n parser.add_argument(\"-norm\", type=str, required=True, help=\"batch, norm or none.\")\n parser.add_argument(\"-opt\", type=str, required=True, help=\"Adam or RAdam.\")\n parser.add_argument(\"-precision\", type=int, required=True, help=\"16 (mixed) or 32 (full)\")\n parser.add_argument(\"-balanced_dice\", action='store_true', help=\"Enables the custom balanced dice.\")\n\n # Fixed arguments\n parser.add_argument(\"-loss\", type=str, default=loss_calculator.__class__.__name__)\n parser.add_argument(\"-metric\", type=str, default=metric_calculator.__class__.__name__)\n parser.add_argument(\"-type\", type=str, default=\"segmentation\")\n parser.add_argument(\"-debug\", action=\"store_true\")\n parser.add_argument(\"-cpu\", action=\"store_true\")\n parser.add_argument(\"-final_labels\", type=bool, default=True)\n parser.add_argument(\"-lr\", type=float, default=0.0005)\n parser.add_argument(\"-wd\", type=float, default=1e-5)\n parser.add_argument(\"-test_bs\", type=int, default=1)\n parser.add_argument(\"-max_epochs\", type=int, default=300)\n parser.add_argument(\"-channel_factor\", type=int, default=4)\n parser.add_argument(\"-nin\", type=int, default=4) # flair, t1, t1ce, t2\n parser.add_argument(\"-nout\", type=int, default=3) # WT, TC, ET\n parser.add_argument(\"-transforms\", type=str, default=str(transforms))\n parser.add_argument(\"-test_transforms\", type=str, default=str(test_transforms))\n parser.add_argument(\"-use_attention\", action='store_true')\n parser.add_argument(\"-rseed\", type=int, default=4321)\n parser.add_argument(\"-forced_overfit\", type=float, default=0)\n parser.add_argument(\"-dataset\", type=str, default=\"BRATS\")\n parser.add_argument(\"-dataset_year\", type=str, default=\"2020\")\n parser.add_argument(\"-splits\", type=str, default=\"(0.7, 0.1, 0.2)\")\n parser.add_argument(\"-kfold\", type=str, default=\"None\")\n parser.add_argument(\"-fold\", type=str, default=\"None\")\n\n hyperparameters = parser.parse_args()\n\n if hyperparameters.balanced_dice:\n print(\"Setting up BalancedMultiChannelDICELoss\")\n loss_calculator = BalancedMultiChannelDICELoss(hyperparameters.max_epochs, True)\n hyperparameters.loss = loss_calculator.__class__.__name__\n\n print(\"Experiment Hyperparameters:\\n\")\n print(vars(hyperparameters))\n\n # # Initialize Trainer\n # Instantiate model\n model = BRATS3DSegmentation(hyperparameters, loss=loss_calculator, metric=metric_calculator)\n\n # Folder management\n experiment_name = EXPERIMENT_NAME\n os.makedirs(model_folder, exist_ok=True)\n ckpt_path = os.path.join(model_folder, \"-{epoch}-{val_loss:.4f}-{val_WT_dice:.4f}-{val_TC_dice:.4f}-{val_ET_dice:.4f}\")\n\n # Callback initialization\n checkpoint_callback = ModelCheckpoint(prefix=experiment_name + '_' + hyperparameters.desc, filepath=ckpt_path, monitor=\"val_loss\",\n mode=\"min\")\n logger = MLFlowLogger(experiment_name=experiment_name, tracking_uri=\"file:\" + log_folder,\n tags={\"desc\": hyperparameters.desc, \"commit\": get_git_hash()})\n\n # PL Trainer initialization\n trainer = Trainer(gpus=0 if hyperparameters.cpu else 1, precision=hyperparameters.precision, checkpoint_callback=checkpoint_callback,\n early_stop_callback=False, logger=logger, max_epochs=hyperparameters.max_epochs, deterministic=True,\n fast_dev_run=hyperparameters.debug, progress_bar_refresh_rate=1, overfit_pct=hyperparameters.forced_overfit)\n\n # # Training Loop\n seed = hyperparameters.rseed\n print(f\"Applying random seed {seed}\")\n deterministic_run(seed)\n trainer.fit(model)\n"
]
| [
[
"torch.stack",
"numpy.array",
"torch.optim.lr_scheduler.ExponentialLR"
]
]
|
unknownuser13570/FODGE | [
"3d5c1c5fb3c5ff23b134afa633dcf0e1649d108c"
]
| [
"GEA/gae_pytorch/gae/utils.py"
]
| [
"import pickle as pkl\n\nimport networkx as nx\nimport numpy as np\nimport scipy.sparse as sp\nimport torch\nfrom sklearn.metrics import roc_auc_score, average_precision_score\n\n\ndef load_data(dataset):\n # load the data: x, tx, allx, graph\n names = ['x', 'tx', 'allx', 'graph']\n objects = []\n for i in range(len(names)):\n '''\n fix Pickle incompatibility of numpy arrays between Python 2 and 3\n https://stackoverflow.com/questions/11305790/pickle-incompatibility-of-numpy-arrays-between-python-2-and-3\n '''\n with open(\"data/ind.{}.{}\".format(dataset, names[i]), 'rb') as rf:\n u = pkl._Unpickler(rf)\n u.encoding = 'latin1'\n cur_data = u.load()\n objects.append(cur_data)\n # objects.append(\n # pkl.load(open(\"data/ind.{}.{}\".format(dataset, names[i]), 'rb')))\n x, tx, allx, graph = tuple(objects)\n print(\"len graph\", len(graph))\n test_idx_reorder = parse_index_file(\n \"data/ind.{}.test.index\".format(dataset))\n test_idx_range = np.sort(test_idx_reorder)\n\n if dataset == 'citeseer':\n # Fix citeseer dataset (there are some isolated nodes in the graph)\n # Find isolated nodes, add them as zero-vecs into the right position\n test_idx_range_full = range(\n min(test_idx_reorder), max(test_idx_reorder) + 1)\n tx_extended = sp.lil_matrix((len(test_idx_range_full), x.shape[1]))\n tx_extended[test_idx_range - min(test_idx_range), :] = tx\n tx = tx_extended\n\n features = sp.vstack((allx, tx)).tolil()\n features[test_idx_reorder, :] = features[test_idx_range, :]\n features = torch.FloatTensor(np.array(features.todense()))\n adj = nx.adjacency_matrix(nx.from_dict_of_lists(graph))\n print(\"adj\", adj.shape, type(adj))\n print(\"features\", features.shape, type(features))\n return adj, features\n\n\ndef parse_index_file(filename):\n index = []\n for line in open(filename):\n index.append(int(line.strip()))\n return index\n\n\ndef sparse_to_tuple(sparse_mx):\n if not sp.isspmatrix_coo(sparse_mx):\n sparse_mx = sparse_mx.tocoo()\n coords = np.vstack((sparse_mx.row, sparse_mx.col)).transpose()\n values = sparse_mx.data\n shape = sparse_mx.shape\n return coords, values, shape\n \n\ndef create_false_edges(adj):\n # Remove diagonal elements\n adj = adj - sp.dia_matrix((adj.diagonal()[np.newaxis, :], [0]), shape=adj.shape)\n adj.eliminate_zeros()\n # Check that diag is zero:\n assert np.diag(adj.todense()).sum() == 0\n \n adj_triu = sp.triu(adj)\n adj_tuple = sparse_to_tuple(adj_triu)\n edges = adj_tuple[0]\n train_edges = edges\n edges_all = sparse_to_tuple(adj)[0]\n all_edge_idx = list(range(edges.shape[0]))\n\n def ismember(a, b, tol=5):\n rows_close = np.all(np.round(a - b[:, None], tol) == 0, axis=-1)\n return np.any(rows_close)\n \n train_edges_false = []\n while len(train_edges_false) < len(train_edges):\n idx_i = np.random.randint(0, adj.shape[0])\n idx_j = np.random.randint(0, adj.shape[0])\n if idx_i == idx_j:\n continue\n if ismember([idx_i, idx_j], edges_all):\n continue\n if train_edges_false:\n if ismember([idx_j, idx_i], np.array(train_edges_false)):\n continue\n if ismember([idx_i, idx_j], np.array(train_edges_false)):\n continue\n train_edges_false.append([idx_i, idx_j])\n \n data = np.ones(train_edges.shape[0])\n\n # Re-build adj matrix\n adj_train = sp.csr_matrix((data, (train_edges[:, 0], train_edges[:, 1])), shape=adj.shape)\n adj_train = adj_train + adj_train.T\n\n # NOTE: these edge lists only contain single direction of edge!\n return adj_train, train_edges, train_edges_false\n\n\ndef mask_test_edges(adj):\n # Function to build test set with 10% positive links\n # NOTE: Splits are randomized and results might slightly deviate from reported numbers in the paper.\n # TODO: Clean up.\n\n # Remove diagonal elements\n adj = adj - sp.dia_matrix((adj.diagonal()[np.newaxis, :], [0]), shape=adj.shape)\n adj.eliminate_zeros()\n # Check that diag is zero:\n assert np.diag(adj.todense()).sum() == 0\n\n adj_triu = sp.triu(adj)\n adj_tuple = sparse_to_tuple(adj_triu)\n edges = adj_tuple[0]\n edges_all = sparse_to_tuple(adj)[0]\n num_test = int(np.floor(edges.shape[0] / 10.))\n num_val = int(np.floor(edges.shape[0] / 20.))\n print(\"num val\", num_val)\n print(\"num test\", num_test)\n \n train_edges = edges\n\n all_edge_idx = list(range(edges.shape[0]))\n np.random.shuffle(all_edge_idx)\n val_edge_idx = all_edge_idx[:num_val]\n test_edge_idx = all_edge_idx[num_val:(num_val + num_test)]\n test_edges = edges[test_edge_idx]\n val_edges = edges[val_edge_idx]\n print(\"test_edge_idx\", test_edge_idx)\n print(\"val_edge_idx\", val_edge_idx)\n train_edges = np.delete(edges, np.hstack([test_edge_idx, val_edge_idx]), axis=0)\n\n def ismember(a, b, tol=5):\n rows_close = np.all(np.round(a - b[:, None], tol) == 0, axis=-1)\n return np.any(rows_close)\n\n test_edges_false = []\n while len(test_edges_false) < len(test_edges):\n idx_i = np.random.randint(0, adj.shape[0])\n idx_j = np.random.randint(0, adj.shape[0])\n if idx_i == idx_j:\n continue\n if ismember([idx_i, idx_j], edges_all):\n continue\n if test_edges_false:\n if ismember([idx_j, idx_i], np.array(test_edges_false)):\n continue\n if ismember([idx_i, idx_j], np.array(test_edges_false)):\n continue\n test_edges_false.append([idx_i, idx_j])\n\n val_edges_false = []\n while len(val_edges_false) < len(val_edges):\n idx_i = np.random.randint(0, adj.shape[0])\n idx_j = np.random.randint(0, adj.shape[0])\n if idx_i == idx_j:\n continue\n if ismember([idx_i, idx_j], train_edges):\n continue\n if ismember([idx_j, idx_i], train_edges):\n continue\n if ismember([idx_i, idx_j], val_edges):\n continue\n if ismember([idx_j, idx_i], val_edges):\n continue\n if val_edges_false:\n if ismember([idx_j, idx_i], np.array(val_edges_false)):\n continue\n if ismember([idx_i, idx_j], np.array(val_edges_false)):\n continue\n val_edges_false.append([idx_i, idx_j])\n\n assert ~ismember(test_edges_false, edges_all)\n assert ~ismember(val_edges_false, edges_all)\n assert ~ismember(val_edges, train_edges)\n assert ~ismember(test_edges, train_edges)\n assert ~ismember(val_edges, test_edges)\n\n data = np.ones(train_edges.shape[0])\n\n # Re-build adj matrix\n adj_train = sp.csr_matrix((data, (train_edges[:, 0], train_edges[:, 1])), shape=adj.shape)\n adj_train = adj_train + adj_train.T\n\n # NOTE: these edge lists only contain single direction of edge!\n return adj_train, train_edges, val_edges, val_edges_false, test_edges, test_edges_false\n\n\ndef preprocess_graph(adj):\n adj = sp.coo_matrix(adj)\n adj_ = adj + sp.eye(adj.shape[0])\n rowsum = np.array(adj_.sum(1))\n degree_mat_inv_sqrt = sp.diags(np.power(rowsum, -0.5).flatten())\n adj_normalized = adj_.dot(degree_mat_inv_sqrt).transpose().dot(degree_mat_inv_sqrt).tocoo()\n # return sparse_to_tuple(adj_normalized)\n return sparse_mx_to_torch_sparse_tensor(adj_normalized)\n\n\ndef sparse_mx_to_torch_sparse_tensor(sparse_mx):\n \"\"\"Convert a scipy sparse matrix to a torch sparse tensor.\"\"\"\n sparse_mx = sparse_mx.tocoo().astype(np.float32)\n indices = torch.from_numpy(\n np.vstack((sparse_mx.row, sparse_mx.col)).astype(np.int64))\n values = torch.from_numpy(sparse_mx.data)\n shape = torch.Size(sparse_mx.shape)\n return torch.sparse.FloatTensor(indices, values, shape)\n\n\ndef get_roc_score(emb, adj_orig, edges_pos, edges_neg):\n def sigmoid(x):\n return 1 / (1 + np.exp(-x))\n\n # Predict on test set of edges\n adj_rec = np.dot(emb, emb.T)\n preds = []\n pos = []\n for e in edges_pos:\n preds.append(sigmoid(adj_rec[e[0], e[1]]))\n pos.append(adj_orig[e[0], e[1]])\n\n preds_neg = []\n neg = []\n for e in edges_neg:\n preds_neg.append(sigmoid(adj_rec[e[0], e[1]]))\n neg.append(adj_orig[e[0], e[1]])\n\n preds_all = np.hstack([preds, preds_neg])\n labels_all = np.hstack([np.ones(len(preds)), np.zeros(len(preds_neg))])\n roc_score = roc_auc_score(labels_all, preds_all)\n ap_score = average_precision_score(labels_all, preds_all)\n\n return roc_score, ap_score"
]
| [
[
"numpy.dot",
"sklearn.metrics.roc_auc_score",
"numpy.round",
"numpy.any",
"scipy.sparse.vstack",
"numpy.exp",
"numpy.random.randint",
"numpy.hstack",
"scipy.sparse.coo_matrix",
"torch.Size",
"scipy.sparse.isspmatrix_coo",
"torch.from_numpy",
"numpy.power",
"scipy.sparse.csr_matrix",
"scipy.sparse.triu",
"numpy.floor",
"numpy.array",
"scipy.sparse.eye",
"numpy.random.shuffle",
"numpy.sort",
"numpy.ones",
"sklearn.metrics.average_precision_score",
"torch.sparse.FloatTensor",
"numpy.vstack"
]
]
|
esp32wrangler/Self-Driving-Car | [
"d989a9aa8d309cc0de7939f94d5aaef1300eb442"
]
| [
"trainer/raw2img.py"
]
| [
"import numpy as np\nimport cv2\nimport matplotlib.image as mpimg\n\nfile1=open('image_raw_sample', 'r')\nimg_count=0\nwhile True:\n line = file1.readline();\n if not line:\n break\n if line[:7]==\"data: [\":\n lines = line.strip()[7:-1].split(',')\n print(len(lines))\n arr=np.array(lines, np.uint8)\n img = cv2.cvtColor(np.reshape(arr, (-1,800)), cv2.COLOR_BayerGB2RGB)\n mpimg.imsave('img_{:04}.png'.format(img_count), img)\n img_count+=1\n\nfile1.close()\n "
]
| [
[
"numpy.reshape",
"numpy.array"
]
]
|
tarrade/proj_DL_models_and_pipelines_with_GCP | [
"8c400b6bdc006f99f1412166824d68b64264abf2"
]
| [
"src/model_mnists_skripts/keras_cnn_eager.py"
]
| [
"# MNIST example from eager execution guide \n# https://www.tensorflow.org/guide/eager#train_a_model\nimport tensorflow as tf\nimport numpy as np\n\ntf.enable_eager_execution()\n\nBATCH = 32\n# Fetch and format the mnist data\n# (mnist_images, mnist_labels), _ = tf.keras.datasets.mnist.load_data()\ntry:\n raise Exception\n from tensorflow.keras.datasets import mnist\n (x_train, y_train), (X_test, y_test) = mnist.load_data()\nexcept Exception:\n print(\"download manually to ./data/ from {}\".format(\n \"https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz\"\n ))\n with np.load(\"./data/mnist.npz\") as f:\n mnist_images, mnist_labels = f['x_train'], f['y_train']\n test_images, test_labels = f['x_test'], f['y_test']\n\ndataset = tf.data.Dataset.from_tensor_slices(\n (tf.cast(mnist_images[..., tf.newaxis]/255, tf.float32),\n tf.cast(mnist_labels, tf.int64)))\ndataset = dataset.shuffle(1000).batch(BATCH)\n\n# Build the model\n# ToDo: replace by lower api model\nmnist_model = tf.keras.Sequential([\n tf.keras.layers.Conv2D(16,[3,3], activation='relu'),\n tf.keras.layers.Conv2D(16,[3,3], activation='relu'),\n tf.keras.layers.GlobalAveragePooling2D(),\n tf.keras.layers.Dense(10)\n])\n\n\nfor images,labels in dataset.take(1):\n print(\"Logits: \", mnist_model(images[0:1]).numpy())\n \noptimizer = tf.train.AdamOptimizer()\n\nloss_history = []\n\ni = 1\nN_train = len(mnist_images)\nn_batches = N_train / BATCH\nstep = int(n_batches/ 60)\nprint(\"Epoch {}: \".format(i), end='')\nfor (batch, (images, labels)) in enumerate(dataset.take(-1)):\n if batch % step == 0:\n print('#', end='')\n with tf.GradientTape() as tape: # Provide Foward-Path for Gradient calc\n logits = mnist_model(images, training=True)\n loss_value = tf.losses.sparse_softmax_cross_entropy(labels, logits)\n\n loss_history.append(loss_value.numpy())\n grads = tape.gradient(loss_value, mnist_model.variables) # tape instance is closed after being called once\n optimizer.apply_gradients(zip(grads, mnist_model.variables),\n global_step=tf.train.get_or_create_global_step())\n\nimport matplotlib.pyplot as plt\n\nplt.plot(loss_history)\nplt.xlabel('Batch #')\nplt.ylabel('Loss [entropy]')\nplt.show()"
]
| [
[
"tensorflow.enable_eager_execution",
"tensorflow.keras.layers.GlobalAveragePooling2D",
"tensorflow.losses.sparse_softmax_cross_entropy",
"tensorflow.keras.layers.Dense",
"tensorflow.cast",
"tensorflow.keras.layers.Conv2D",
"numpy.load",
"tensorflow.keras.datasets.mnist.load_data",
"tensorflow.train.get_or_create_global_step",
"matplotlib.pyplot.plot",
"tensorflow.GradientTape",
"tensorflow.train.AdamOptimizer",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel"
]
]
|
patricebechard/SDGym | [
"827272b877661d65cc91dc055799c53682834c41"
]
| [
"sdgym/synthesizers/sdv.py"
]
| [
"import pandas as pd\nfrom sdv import tabular\n\nfrom sdgym.synthesizers.base import BaseSynthesizer\nfrom sdgym.synthesizers.utils import select_device\n\n\nclass SDVTabular(BaseSynthesizer):\n\n _MODEL = None\n _MODEL_KWARGS = None\n\n def fit(self, data, categorical_columns, ordinal_columns):\n data = pd.DataFrame(data).astype('float64')\n field_types = {\n str(column): (\n {\n 'type': 'categorical'\n }\n if column in categorical_columns else\n {\n 'type': 'numerical',\n 'subtype': 'integer'\n }\n if column in ordinal_columns else\n {\n 'type': 'numerical',\n 'subtype': 'float'\n }\n )\n for column in data.columns\n }\n data.columns = data.columns.astype(str)\n self._model = self._MODEL(field_types=field_types, **self._MODEL_KWARGS.copy())\n self._model.fit(data)\n\n def sample(self, num_rows):\n return self._model.sample(num_rows).values.astype('float32')\n\n\nclass GaussianCopulaCategorical(SDVTabular):\n _MODEL = tabular.GaussianCopula\n _MODEL_KWARGS = {\n 'categorical_transformer': 'categorical'\n }\n\n\nclass GaussianCopulaCategoricalFuzzy(SDVTabular):\n _MODEL = tabular.GaussianCopula\n _MODEL_KWARGS = {\n 'categorical_transformer': 'categorical_fuzzy'\n }\n\n\nclass GaussianCopulaOneHot(SDVTabular):\n _MODEL = tabular.GaussianCopula\n _MODEL_KWARGS = {\n 'categorical_transformer': 'one_hot_encoding'\n }\n\n\nclass CTGAN(SDVTabular):\n _MODEL = tabular.CTGAN\n _MODEL_KWARGS = {}\n\n def fit(self, data, categorical_columns, ordinal_columns):\n self._MODEL_KWARGS = {'cuda': select_device()}\n super().fit(data, categorical_columns, ordinal_columns)\n\n\nclass CopulaGAN(CTGAN):\n _MODEL = tabular.CopulaGAN\n _MODEL_KWARGS = {}\n"
]
| [
[
"pandas.DataFrame"
]
]
|
rayguan97/M3DETR | [
"cb76890a28c1555f2c0138030e0a432df6ee731b"
]
| [
"pcdet/models/backbones_3d/pfe/voxel_set_abstraction.py"
]
| [
"import math\nimport numpy as np\nimport torch\nimport torch.nn as nn\n\nfrom ....ops.pointnet2.pointnet2_stack import pointnet2_modules as pointnet2_stack_modules\nfrom ....ops.pointnet2.pointnet2_stack import pointnet2_utils as pointnet2_stack_utils\nfrom ....utils import common_utils\nfrom ...backbones_2d.transformer import TransformerEncoderLayer3D, TransformerEncoder\nfrom ...roi_heads.target_assigner.proposal_target_layer import ProposalTargetLayer\nfrom ...model_utils.model_nms_utils import class_agnostic_nms\ndef bilinear_interpolate_torch(im, x, y):\n \"\"\"\n Args:\n im: (H, W, C) [y, x]\n x: (N)\n y: (N)\n Returns:\n \"\"\"\n x0 = torch.floor(x).long()\n x1 = x0 + 1\n\n y0 = torch.floor(y).long()\n y1 = y0 + 1\n\n x0 = torch.clamp(x0, 0, im.shape[1] - 1)\n x1 = torch.clamp(x1, 0, im.shape[1] - 1)\n y0 = torch.clamp(y0, 0, im.shape[0] - 1)\n y1 = torch.clamp(y1, 0, im.shape[0] - 1)\n\n Ia = im[y0, x0]\n Ib = im[y1, x0]\n Ic = im[y0, x1]\n Id = im[y1, x1]\n\n wa = (x1.type_as(x) - x) * (y1.type_as(y) - y)\n wb = (x1.type_as(x) - x) * (y - y0.type_as(y))\n wc = (x - x0.type_as(x)) * (y1.type_as(y) - y)\n wd = (x - x0.type_as(x)) * (y - y0.type_as(y))\n ans = torch.t((torch.t(Ia) * wa)) + torch.t(torch.t(Ib) * wb) + torch.t(torch.t(Ic) * wc) + torch.t(torch.t(Id) * wd)\n return ans\n\n\ndef sample_points_with_roi(rois, points, sample_radius_with_roi, num_max_points_of_part=200000):\n \"\"\"\n Args:\n rois: (M, 7 + C)\n points: (N, 3)\n sample_radius_with_roi:\n num_max_points_of_part:\n Returns:\n sampled_points: (N_out, 3)\n \"\"\"\n if points.shape[0] < num_max_points_of_part:\n distance = (points[:, None, :] - rois[None, :, 0:3]).norm(dim=-1)\n min_dis, min_dis_roi_idx = distance.min(dim=-1)\n roi_max_dim = (rois[min_dis_roi_idx, 3:6] / 2).norm(dim=-1)\n point_mask = min_dis < roi_max_dim + sample_radius_with_roi\n else:\n start_idx = 0\n point_mask_list = []\n while start_idx < points.shape[0]:\n distance = (points[start_idx:start_idx + num_max_points_of_part, None, :] - rois[None, :, 0:3]).norm(dim=-1)\n min_dis, min_dis_roi_idx = distance.min(dim=-1)\n roi_max_dim = (rois[min_dis_roi_idx, 3:6] / 2).norm(dim=-1)\n cur_point_mask = min_dis < roi_max_dim + sample_radius_with_roi\n point_mask_list.append(cur_point_mask)\n start_idx += num_max_points_of_part\n point_mask = torch.cat(point_mask_list, dim=0)\n\n sampled_points = points[:1] if point_mask.sum() == 0 else points[point_mask, :]\n\n return sampled_points, point_mask\n\n\ndef sector_fps(points, num_sampled_points, num_sectors):\n \"\"\"\n Args:\n points: (N, 3)\n num_sampled_points: int\n num_sectors: int\n Returns:\n sampled_points: (N_out, 3)\n \"\"\"\n sector_size = np.pi * 2 / num_sectors\n point_angles = torch.atan2(points[:, 1], points[:, 0]) + np.pi\n sector_idx = (point_angles / sector_size).floor().clamp(min=0, max=num_sectors)\n xyz_points_list = []\n xyz_batch_cnt = []\n num_sampled_points_list = []\n for k in range(num_sectors):\n mask = (sector_idx == k)\n cur_num_points = mask.sum().item()\n if cur_num_points > 0:\n xyz_points_list.append(points[mask])\n xyz_batch_cnt.append(cur_num_points)\n ratio = cur_num_points / points.shape[0]\n num_sampled_points_list.append(\n min(cur_num_points, math.ceil(ratio * num_sampled_points))\n )\n\n if len(xyz_batch_cnt) == 0:\n xyz_points_list.append(points)\n xyz_batch_cnt.append(len(points))\n num_sampled_points_list.append(num_sampled_points)\n print(f'Warning: empty sector points detected in SectorFPS: points.shape={points.shape}')\n\n xyz = torch.cat(xyz_points_list, dim=0)\n xyz_batch_cnt = torch.tensor(xyz_batch_cnt, device=points.device).int()\n sampled_points_batch_cnt = torch.tensor(num_sampled_points_list, device=points.device).int()\n\n sampled_pt_idxs = pointnet2_stack_utils.stack_farthest_point_sample(\n xyz.contiguous(), xyz_batch_cnt, sampled_points_batch_cnt\n ).long()\n\n sampled_points = xyz[sampled_pt_idxs]\n\n return sampled_points\n\n\nclass VoxelSetAbstractionTransFusionv5(nn.Module):\n def __init__(self, model_cfg, voxel_size, point_cloud_range, num_bev_features=None,\n num_rawpoint_features=None, **kwargs):\n super().__init__()\n self.model_cfg = model_cfg\n self.voxel_size = voxel_size\n self.point_cloud_range = point_cloud_range\n\n SA_cfg = self.model_cfg.SA_LAYER\n\n self.SA_layers = nn.ModuleList()\n self.linears_in = nn.ModuleList()\n self.linears_out = nn.ModuleList()\n self.fusion_channel = sum([x[-1] for x in SA_cfg[self.model_cfg.FEATURES_SOURCE[-2]].MLPS])\n # self.fusion_channel = 16\n self.SA_layer_names = []\n self.downsample_times_map = {}\n c_in = 0\n\n if 'bev' in self.model_cfg.FEATURES_SOURCE:\n c_bev = num_bev_features\n c_in += c_bev\n if c_bev == self.fusion_channel:\n self.linears_in.append(nn.Identity())\n self.linears_out.append(nn.Identity())\n else:\n self.linears_in.append(nn.Sequential(\n nn.Linear(c_bev, self.fusion_channel, bias=False),\n nn.BatchNorm1d(self.fusion_channel)))\n self.linears_out.append(nn.Sequential(\n nn.Linear(self.fusion_channel, c_bev, bias=False),\n nn.BatchNorm1d(c_bev)))\n\n if 'raw_points' in self.model_cfg.FEATURES_SOURCE:\n mlps = SA_cfg['raw_points'].MLPS\n for k in range(len(mlps)):\n mlps[k] = [num_rawpoint_features - 3] + mlps[k]\n\n self.SA_rawpoints = pointnet2_stack_modules.StackSAModuleMSG(\n radii=SA_cfg['raw_points'].POOL_RADIUS,\n nsamples=SA_cfg['raw_points'].NSAMPLE,\n mlps=mlps,\n use_xyz=True,\n pool_method='max_pool'\n )\n cur = sum([x[-1] for x in mlps])\n if cur == self.fusion_channel:\n self.linears_in.append(nn.Identity())\n self.linears_out.append(nn.Identity())\n else:\n self.linears_in.append(nn.Sequential(\n nn.Linear(cur, self.fusion_channel, bias=False),\n nn.BatchNorm1d(self.fusion_channel)))\n self.linears_out.append(nn.Sequential(\n nn.Linear(self.fusion_channel, cur, bias=False),\n nn.BatchNorm1d(cur)))\n c_in += cur\n\n\n for src_name in self.model_cfg.FEATURES_SOURCE:\n if src_name in ['bev', 'raw_points']:\n continue\n self.downsample_times_map[src_name] = SA_cfg[src_name].DOWNSAMPLE_FACTOR\n mlps = SA_cfg[src_name].MLPS\n for k in range(len(mlps)):\n mlps[k] = [mlps[k][0]] + mlps[k]\n cur_layer = pointnet2_stack_modules.StackSAModuleMSG(\n radii=SA_cfg[src_name].POOL_RADIUS,\n nsamples=SA_cfg[src_name].NSAMPLE,\n mlps=mlps,\n use_xyz=True,\n pool_method='max_pool',\n )\n self.SA_layers.append(cur_layer)\n cur = sum([x[-1] for x in mlps])\n if cur == self.fusion_channel:\n self.linears_in.append(nn.Identity())\n self.linears_out.append(nn.Identity())\n else:\n self.linears_in.append(nn.Sequential(\n nn.Linear(cur, self.fusion_channel, bias=False),\n nn.BatchNorm1d(self.fusion_channel)))\n self.linears_out.append(nn.Sequential(\n nn.Linear(self.fusion_channel, cur, bias=False),\n nn.BatchNorm1d(cur)))\n self.SA_layer_names.append(src_name)\n \n c_in += cur\n\n self.vsa_point_feature_fusion = nn.Sequential(\n nn.Linear(c_in, self.model_cfg.NUM_OUTPUT_FEATURES, bias=False),\n nn.BatchNorm1d(self.model_cfg.NUM_OUTPUT_FEATURES),\n nn.ReLU(),\n )\n self.num_point_features = self.model_cfg.NUM_OUTPUT_FEATURES\n self.num_point_features_before_fusion = c_in\n if self.model_cfg.NORM:\n self.transnorm = nn.LayerNorm(c_in)\n else:\n self.transnorm = None\n if self.model_cfg.NORM2:\n self.transnorm2 = nn.LayerNorm(self.fusion_channel)\n else:\n self.transnorm2 = None\n # multi_location\n self.trans_layer = TransformerEncoder(TransformerEncoderLayer3D(c_in, self.model_cfg.FUSION_HEAD), self.model_cfg.NUM_LAYERS, self.transnorm)\n # have multi-modality + multi-scale\n self.trans_fusion_layer = TransformerEncoder(TransformerEncoderLayer3D(self.fusion_channel, self.model_cfg.FUSION2_HEAD), self.model_cfg.NUM_LAYERS2, self.transnorm2)\n self.reduce_radius = self.model_cfg.REDUCE_RADIUS**2\n self.topks = self.model_cfg.NMS_CONFIG.TOPK\n self.max_keypoints = self.model_cfg.NMS_CONFIG.MAX_POINTS\n\n self.res1_actn_1 = nn.Sequential(\n nn.LayerNorm(c_in),\n nn.ReLU())\n\n self.res1_actn_2 = nn.Sequential(\n nn.LayerNorm(c_in),\n nn.ReLU())\n\n def interpolate_from_bev_features(self, keypoints, bev_features, batch_size, bev_stride):\n x_idxs = (keypoints[:, :, 0] - self.point_cloud_range[0]) / self.voxel_size[0]\n y_idxs = (keypoints[:, :, 1] - self.point_cloud_range[1]) / self.voxel_size[1]\n x_idxs = x_idxs / bev_stride\n y_idxs = y_idxs / bev_stride\n\n point_bev_features_list = []\n for k in range(batch_size):\n cur_x_idxs = x_idxs[k]\n cur_y_idxs = y_idxs[k]\n cur_bev_features = bev_features[k].permute(1, 2, 0) # (H, W, C)\n point_bev_features = bilinear_interpolate_torch(cur_bev_features, cur_x_idxs, cur_y_idxs)\n point_bev_features_list.append(point_bev_features.unsqueeze(dim=0))\n\n point_bev_features = torch.cat(point_bev_features_list, dim=0) # (B, N, C0)\n return point_bev_features\n\n def get_sampled_points(self, batch_dict):\n batch_size = batch_dict['batch_size']\n if self.model_cfg.POINT_SOURCE == 'raw_points':\n src_points = batch_dict['points'][:, 1:4]\n batch_indices = batch_dict['points'][:, 0].long()\n elif self.model_cfg.POINT_SOURCE == 'voxel_centers':\n src_points = common_utils.get_voxel_centers(\n batch_dict['voxel_coords'][:, 1:4],\n downsample_times=1,\n voxel_size=self.voxel_size,\n point_cloud_range=self.point_cloud_range\n )\n batch_indices = batch_dict['voxel_coords'][:, 0].long()\n else:\n raise NotImplementedError\n keypoints_list = []\n for bs_idx in range(batch_size):\n bs_mask = (batch_indices == bs_idx)\n sampled_points = src_points[bs_mask].unsqueeze(dim=0) # (1, N, 3)\n if self.model_cfg.SAMPLE_METHOD == 'FPS':\n cur_pt_idxs = pointnet2_stack_utils.furthest_point_sample(\n sampled_points[:, :, 0:3].contiguous(), self.model_cfg.NUM_KEYPOINTS\n ).long()\n\n if sampled_points.shape[1] < self.model_cfg.NUM_KEYPOINTS:\n empty_num = self.model_cfg.NUM_KEYPOINTS - sampled_points.shape[1]\n cur_pt_idxs[0, -empty_num:] = cur_pt_idxs[0, :empty_num]\n\n keypoints = sampled_points[0][cur_pt_idxs[0]].unsqueeze(dim=0)\n\n elif self.model_cfg.SAMPLE_METHOD == 'FastFPS':\n raise NotImplementedError\n else:\n raise NotImplementedError\n\n keypoints_list.append(keypoints)\n\n keypoints = torch.cat(keypoints_list, dim=0) # (B, M, 3)\n return keypoints\n\n def get_sampled_points_post(self, batch_dict, keypoints):\n batch_size = batch_dict['batch_size']\n src_points = keypoints\n\n keypoints_list = []\n\n for bs_idx in range(batch_size):\n sampled_points = src_points[bs_idx].unsqueeze(dim=0) # (1, N, 3)\n\n if sampled_points.shape[1] < self.max_keypoints:\n\n cur_count = sampled_points.shape[1]\n cur_pt_idxs = torch.arange(0, self.max_keypoints)\n\n empty_num = self.max_keypoints - cur_count\n while empty_num >= cur_count:\n cur_pt_idxs[cur_count:cur_count * 2] = cur_pt_idxs[:cur_count]\n empty_num -= cur_count\n cur_count *= 2\n if cur_count < self.max_keypoints:\n assert empty_num == self.max_keypoints - cur_count\n cur_pt_idxs[-empty_num:] = cur_pt_idxs[:empty_num]\n\n keypoint = sampled_points[0][cur_pt_idxs].unsqueeze(dim=0)\n else:\n cur_pt_idxs = pointnet2_stack_utils.furthest_point_sample(\n sampled_points[:, :, 0:3].contiguous(), self.max_keypoints\n ).long()\n\n if sampled_points.shape[1] < self.max_keypoints:\n empty_num = self.max_keypoints - sampled_points.shape[1]\n cur_pt_idxs[0, -empty_num:] = cur_pt_idxs[0, :empty_num]\n\n keypoint = sampled_points[0][cur_pt_idxs[0]].unsqueeze(dim=0)\n\n\n keypoints_list.append(keypoint)\n\n keypoint = torch.cat(keypoints_list, dim=0) # (B, M, 3)\n return keypoint\n\n def reduce_points(self, batch_dict):\n\n batch_indices = batch_dict['points'][:, 0].long()\n\n masks = []\n for bs_idx, roi in enumerate(batch_dict['batch_cls_preds']):\n bs_mask = (batch_indices == bs_idx)\n pts = batch_dict['points'][bs_mask].unsqueeze(dim=1)[:, :, 1: 4] # (N, 1, 3)\n s, _ = torch.max(batch_dict['batch_cls_preds'][bs_idx], dim=1)\n top, idx = torch.topk(s, self.topks)\n c = batch_dict['batch_box_preds'][bs_idx][idx][:, :3].unsqueeze(dim=0)\n dist = (pts - c)**2 \n\n dist, _ = dist.sum(dim=-1).min(dim=1)\n mask = (dist <= self.reduce_radius)\n masks.extend(mask)\n\n batch_dict['points'] = batch_dict['points'][masks]\n return batch_dict\n\n def reduce_points_post(self, keypoints, batch_dict):\n\n keypoints_list = []\n for bs_idx, roi in enumerate(batch_dict['batch_cls_preds']):\n pts = keypoints[bs_idx].unsqueeze(dim=1)\n s, _ = torch.max(batch_dict['batch_cls_preds'][bs_idx], dim=1)\n top, idx = torch.topk(s, self.topks)\n c = batch_dict['batch_box_preds'][bs_idx][idx][:, :3].unsqueeze(dim=0)\n dist = (pts - c)**2 \n\n dist, _ = dist.sum(dim=-1).min(dim=1)\n mask = (dist <= self.reduce_radius)\n keypoints_list.append(keypoints[bs_idx][mask])\n\n return keypoints_list\n\n def forward(self, batch_dict):\n \"\"\"\n Args:\n batch_dict:\n batch_size:\n keypoints: (B, num_keypoints, 3)\n multi_scale_3d_features: {\n 'x_conv4': ...\n }\n points: optional (N, 1 + 3 + C) [bs_idx, x, y, z, ...]\n spatial_features: optional\n spatial_features_stride: optional\n\n Returns:\n point_features: (N, C)\n point_coords: (N, 4)\n\n \"\"\"\n if self.model_cfg.POINT_SOURCE == 'raw_points' and self.reduce_radius > 0:\n # batch_dict = self.reduce_points(batch_dict)\n keypoints = self.get_sampled_points(batch_dict)\n keypoint_lst = self.reduce_points_post(keypoints, batch_dict)\n keypoints = self.get_sampled_points_post(batch_dict, keypoint_lst)\n else:\n keypoints = self.get_sampled_points(batch_dict)\n\n point_features_list = []\n if 'bev' in self.model_cfg.FEATURES_SOURCE:\n point_bev_features = self.interpolate_from_bev_features(\n keypoints, batch_dict['spatial_features'], batch_dict['batch_size'],\n bev_stride=batch_dict['spatial_features_stride']\n )\n point_features_list.append(point_bev_features)\n\n batch_size, num_keypoints, _ = keypoints.shape\n new_xyz = keypoints.view(-1, 3)\n new_xyz_batch_cnt = new_xyz.new_zeros(batch_size).int().fill_(num_keypoints)\n\n if 'raw_points' in self.model_cfg.FEATURES_SOURCE:\n raw_points = batch_dict['points']\n xyz = raw_points[:, 1:4]\n xyz_batch_cnt = xyz.new_zeros(batch_size).int()\n for bs_idx in range(batch_size):\n xyz_batch_cnt[bs_idx] = (raw_points[:, 0] == bs_idx).sum()\n point_features = raw_points[:, 4:].contiguous() if raw_points.shape[1] > 4 else None\n\n pooled_points, pooled_features = self.SA_rawpoints(\n xyz=xyz.contiguous(),\n xyz_batch_cnt=xyz_batch_cnt,\n new_xyz=new_xyz,\n new_xyz_batch_cnt=new_xyz_batch_cnt,\n features=point_features,\n )\n point_features_list.append(pooled_features.view(batch_size, num_keypoints, -1))\n\n for k, src_name in enumerate(self.SA_layer_names):\n cur_coords = batch_dict['multi_scale_3d_features'][src_name].indices\n xyz = common_utils.get_voxel_centers(\n cur_coords[:, 1:4],\n downsample_times=self.downsample_times_map[src_name],\n voxel_size=self.voxel_size,\n point_cloud_range=self.point_cloud_range\n )\n xyz_batch_cnt = xyz.new_zeros(batch_size).int()\n for bs_idx in range(batch_size):\n xyz_batch_cnt[bs_idx] = (cur_coords[:, 0] == bs_idx).sum()\n\n pooled_points, pooled_features = self.SA_layers[k](\n xyz=xyz.contiguous(),\n xyz_batch_cnt=xyz_batch_cnt,\n new_xyz=new_xyz,\n new_xyz_batch_cnt=new_xyz_batch_cnt,\n features=batch_dict['multi_scale_3d_features'][src_name].features.contiguous(),\n )\n \n point_features_list.append(pooled_features.view(batch_size, num_keypoints, -1))\n \n point_features_list_new = []\n\n\n for i, x in enumerate(point_features_list):\n feat = self.linears_in[i](x.view(batch_size * num_keypoints, -1))\n point_features_list_new.append(feat.view(1, batch_size * num_keypoints, -1))\n fusion_feat = torch.cat(point_features_list_new, dim=0)\n # have multi-modality + multi-scale\n\n trans1_feat_list = self.trans_fusion_layer(fusion_feat).view(len(fusion_feat), batch_size, num_keypoints, -1)\n trans1_feat_projected_list = []\n for i, x in enumerate(trans1_feat_list):\n feat = self.linears_out[i](x.view(batch_size * num_keypoints, -1))\n trans1_feat_projected_list.append(feat.view(batch_size, num_keypoints, -1))\n\n # multi_location\n point_features_main1 = torch.cat(point_features_list, dim=2)\n point_features_res1 = self.res1_actn_1(torch.cat(trans1_feat_projected_list, dim=2))\n\n point_features_main2 = point_features_res1 + point_features_main1\n\n point_features_res2 = self.res1_actn_2(self.trans_layer(point_features_main2.permute(1, 0, 2)).permute(1, 0, 2))\n point_features = point_features_main2 + point_features_res2 \n\n\n batch_idx = torch.arange(batch_size, device=keypoints.device).view(-1, 1).repeat(1, keypoints.shape[1]).view(-1)\n point_coords = torch.cat((batch_idx.view(-1, 1).float(), keypoints.view(-1, 3)), dim=1)\n\n batch_dict['point_features_before_fusion'] = point_features.reshape(-1, point_features.shape[-1])\n point_features = self.vsa_point_feature_fusion(point_features.reshape(-1, point_features.shape[-1]))\n\n batch_dict['point_features'] = point_features # (BxN, C)\n batch_dict['point_coords'] = point_coords # (BxN, 4)\n return batch_dict\n\nclass VoxelSetAbstraction(nn.Module):\n def __init__(self, model_cfg, voxel_size, point_cloud_range, num_bev_features=None,\n num_rawpoint_features=None, **kwargs):\n super().__init__()\n self.model_cfg = model_cfg\n self.voxel_size = voxel_size\n self.point_cloud_range = point_cloud_range\n\n SA_cfg = self.model_cfg.SA_LAYER\n\n self.SA_layers = nn.ModuleList()\n self.SA_layer_names = []\n self.downsample_times_map = {}\n c_in = 0\n for src_name in self.model_cfg.FEATURES_SOURCE:\n if src_name in ['bev', 'raw_points']:\n continue\n self.downsample_times_map[src_name] = SA_cfg[src_name].DOWNSAMPLE_FACTOR\n\n if SA_cfg[src_name].get('INPUT_CHANNELS', None) is None:\n input_channels = SA_cfg[src_name].MLPS[0][0] \\\n if isinstance(SA_cfg[src_name].MLPS[0], list) else SA_cfg[src_name].MLPS[0]\n else:\n input_channels = SA_cfg[src_name]['INPUT_CHANNELS']\n\n cur_layer, cur_num_c_out = pointnet2_stack_modules.build_local_aggregation_module(\n input_channels=input_channels, config=SA_cfg[src_name]\n )\n self.SA_layers.append(cur_layer)\n self.SA_layer_names.append(src_name)\n\n c_in += cur_num_c_out\n\n if 'bev' in self.model_cfg.FEATURES_SOURCE:\n c_bev = num_bev_features\n c_in += c_bev\n\n if 'raw_points' in self.model_cfg.FEATURES_SOURCE:\n self.SA_rawpoints, cur_num_c_out = pointnet2_stack_modules.build_local_aggregation_module(\n input_channels=num_rawpoint_features - 3, config=SA_cfg['raw_points']\n )\n\n c_in += cur_num_c_out\n\n self.vsa_point_feature_fusion = nn.Sequential(\n nn.Linear(c_in, self.model_cfg.NUM_OUTPUT_FEATURES, bias=False),\n nn.BatchNorm1d(self.model_cfg.NUM_OUTPUT_FEATURES),\n nn.ReLU(),\n )\n self.num_point_features = self.model_cfg.NUM_OUTPUT_FEATURES\n self.num_point_features_before_fusion = c_in\n\n def interpolate_from_bev_features(self, keypoints, bev_features, batch_size, bev_stride):\n \"\"\"\n Args:\n keypoints: (N1 + N2 + ..., 4)\n bev_features: (B, C, H, W)\n batch_size:\n bev_stride:\n Returns:\n point_bev_features: (N1 + N2 + ..., C)\n \"\"\"\n x_idxs = (keypoints[:, 1] - self.point_cloud_range[0]) / self.voxel_size[0]\n y_idxs = (keypoints[:, 2] - self.point_cloud_range[1]) / self.voxel_size[1]\n\n x_idxs = x_idxs / bev_stride\n y_idxs = y_idxs / bev_stride\n\n point_bev_features_list = []\n for k in range(batch_size):\n bs_mask = (keypoints[:, 0] == k)\n\n cur_x_idxs = x_idxs[bs_mask]\n cur_y_idxs = y_idxs[bs_mask]\n cur_bev_features = bev_features[k].permute(1, 2, 0) # (H, W, C)\n point_bev_features = bilinear_interpolate_torch(cur_bev_features, cur_x_idxs, cur_y_idxs)\n point_bev_features_list.append(point_bev_features)\n\n point_bev_features = torch.cat(point_bev_features_list, dim=0) # (N1 + N2 + ..., C)\n return point_bev_features\n\n def sectorized_proposal_centric_sampling(self, roi_boxes, points):\n \"\"\"\n Args:\n roi_boxes: (M, 7 + C)\n points: (N, 3)\n Returns:\n sampled_points: (N_out, 3)\n \"\"\"\n\n sampled_points, _ = sample_points_with_roi(\n rois=roi_boxes, points=points,\n sample_radius_with_roi=self.model_cfg.SPC_SAMPLING.SAMPLE_RADIUS_WITH_ROI,\n num_max_points_of_part=self.model_cfg.SPC_SAMPLING.get('NUM_POINTS_OF_EACH_SAMPLE_PART', 200000)\n )\n sampled_points = sector_fps(\n points=sampled_points, num_sampled_points=self.model_cfg.NUM_KEYPOINTS,\n num_sectors=self.model_cfg.SPC_SAMPLING.NUM_SECTORS\n )\n return sampled_points\n\n def get_sampled_points(self, batch_dict):\n \"\"\"\n Args:\n batch_dict:\n Returns:\n keypoints: (N1 + N2 + ..., 4), where 4 indicates [bs_idx, x, y, z]\n \"\"\"\n batch_size = batch_dict['batch_size']\n if self.model_cfg.POINT_SOURCE == 'raw_points':\n src_points = batch_dict['points'][:, 1:4]\n batch_indices = batch_dict['points'][:, 0].long()\n elif self.model_cfg.POINT_SOURCE == 'voxel_centers':\n src_points = common_utils.get_voxel_centers(\n batch_dict['voxel_coords'][:, 1:4],\n downsample_times=1,\n voxel_size=self.voxel_size,\n point_cloud_range=self.point_cloud_range\n )\n batch_indices = batch_dict['voxel_coords'][:, 0].long()\n else:\n raise NotImplementedError\n keypoints_list = []\n for bs_idx in range(batch_size):\n bs_mask = (batch_indices == bs_idx)\n sampled_points = src_points[bs_mask].unsqueeze(dim=0) # (1, N, 3)\n if self.model_cfg.SAMPLE_METHOD == 'FPS':\n cur_pt_idxs = pointnet2_stack_utils.farthest_point_sample(\n sampled_points[:, :, 0:3].contiguous(), self.model_cfg.NUM_KEYPOINTS\n ).long()\n\n if sampled_points.shape[1] < self.model_cfg.NUM_KEYPOINTS:\n times = int(self.model_cfg.NUM_KEYPOINTS / sampled_points.shape[1]) + 1\n non_empty = cur_pt_idxs[0, :sampled_points.shape[1]]\n cur_pt_idxs[0] = non_empty.repeat(times)[:self.model_cfg.NUM_KEYPOINTS]\n\n keypoints = sampled_points[0][cur_pt_idxs[0]].unsqueeze(dim=0)\n\n elif self.model_cfg.SAMPLE_METHOD == 'SPC':\n cur_keypoints = self.sectorized_proposal_centric_sampling(\n roi_boxes=batch_dict['rois'][bs_idx], points=sampled_points[0]\n )\n bs_idxs = cur_keypoints.new_ones(cur_keypoints.shape[0]) * bs_idx\n keypoints = torch.cat((bs_idxs[:, None], cur_keypoints), dim=1)\n else:\n raise NotImplementedError\n\n keypoints_list.append(keypoints)\n\n keypoints = torch.cat(keypoints_list, dim=0) # (B, M, 3) or (N1 + N2 + ..., 4)\n if len(keypoints.shape) == 3:\n batch_idx = torch.arange(batch_size, device=keypoints.device).view(-1, 1).repeat(1, keypoints.shape[1]).view(-1, 1)\n keypoints = torch.cat((batch_idx.float(), keypoints.view(-1, 3)), dim=1)\n\n return keypoints\n\n @staticmethod\n def aggregate_keypoint_features_from_one_source(\n batch_size, aggregate_func, xyz, xyz_features, xyz_bs_idxs, new_xyz, new_xyz_batch_cnt,\n filter_neighbors_with_roi=False, radius_of_neighbor=None, num_max_points_of_part=200000, rois=None\n ):\n \"\"\"\n Args:\n aggregate_func:\n xyz: (N, 3)\n xyz_features: (N, C)\n xyz_bs_idxs: (N)\n new_xyz: (M, 3)\n new_xyz_batch_cnt: (batch_size), [N1, N2, ...]\n filter_neighbors_with_roi: True/False\n radius_of_neighbor: float\n num_max_points_of_part: int\n rois: (batch_size, num_rois, 7 + C)\n Returns:\n \"\"\"\n xyz_batch_cnt = xyz.new_zeros(batch_size).int()\n if filter_neighbors_with_roi:\n point_features = torch.cat((xyz, xyz_features), dim=-1) if xyz_features is not None else xyz\n point_features_list = []\n for bs_idx in range(batch_size):\n bs_mask = (xyz_bs_idxs == bs_idx)\n _, valid_mask = sample_points_with_roi(\n rois=rois[bs_idx], points=xyz[bs_mask],\n sample_radius_with_roi=radius_of_neighbor, num_max_points_of_part=num_max_points_of_part,\n )\n point_features_list.append(point_features[bs_mask][valid_mask])\n xyz_batch_cnt[bs_idx] = valid_mask.sum()\n\n valid_point_features = torch.cat(point_features_list, dim=0)\n xyz = valid_point_features[:, 0:3]\n xyz_features = valid_point_features[:, 3:] if xyz_features is not None else None\n else:\n for bs_idx in range(batch_size):\n xyz_batch_cnt[bs_idx] = (xyz_bs_idxs == bs_idx).sum()\n\n pooled_points, pooled_features = aggregate_func(\n xyz=xyz.contiguous(),\n xyz_batch_cnt=xyz_batch_cnt,\n new_xyz=new_xyz,\n new_xyz_batch_cnt=new_xyz_batch_cnt,\n features=xyz_features.contiguous(),\n )\n return pooled_features\n\n def forward(self, batch_dict):\n \"\"\"\n Args:\n batch_dict:\n batch_size:\n keypoints: (B, num_keypoints, 3)\n multi_scale_3d_features: {\n 'x_conv4': ...\n }\n points: optional (N, 1 + 3 + C) [bs_idx, x, y, z, ...]\n spatial_features: optional\n spatial_features_stride: optional\n Returns:\n point_features: (N, C)\n point_coords: (N, 4)\n \"\"\"\n keypoints = self.get_sampled_points(batch_dict)\n\n point_features_list = []\n if 'bev' in self.model_cfg.FEATURES_SOURCE:\n point_bev_features = self.interpolate_from_bev_features(\n keypoints, batch_dict['spatial_features'], batch_dict['batch_size'],\n bev_stride=batch_dict['spatial_features_stride']\n )\n point_features_list.append(point_bev_features)\n\n batch_size = batch_dict['batch_size']\n\n new_xyz = keypoints[:, 1:4].contiguous()\n new_xyz_batch_cnt = new_xyz.new_zeros(batch_size).int()\n for k in range(batch_size):\n new_xyz_batch_cnt[k] = (keypoints[:, 0] == k).sum()\n\n if 'raw_points' in self.model_cfg.FEATURES_SOURCE:\n raw_points = batch_dict['points']\n\n pooled_features = self.aggregate_keypoint_features_from_one_source(\n batch_size=batch_size, aggregate_func=self.SA_rawpoints,\n xyz=raw_points[:, 1:4],\n xyz_features=raw_points[:, 4:].contiguous() if raw_points.shape[1] > 4 else None,\n xyz_bs_idxs=raw_points[:, 0],\n new_xyz=new_xyz, new_xyz_batch_cnt=new_xyz_batch_cnt,\n filter_neighbors_with_roi=self.model_cfg.SA_LAYER['raw_points'].get('FILTER_NEIGHBOR_WITH_ROI', False),\n radius_of_neighbor=self.model_cfg.SA_LAYER['raw_points'].get('RADIUS_OF_NEIGHBOR_WITH_ROI', None),\n rois=batch_dict.get('rois', None)\n )\n point_features_list.append(pooled_features)\n\n for k, src_name in enumerate(self.SA_layer_names):\n cur_coords = batch_dict['multi_scale_3d_features'][src_name].indices\n cur_features = batch_dict['multi_scale_3d_features'][src_name].features.contiguous()\n\n xyz = common_utils.get_voxel_centers(\n cur_coords[:, 1:4], downsample_times=self.downsample_times_map[src_name],\n voxel_size=self.voxel_size, point_cloud_range=self.point_cloud_range\n )\n\n pooled_features = self.aggregate_keypoint_features_from_one_source(\n batch_size=batch_size, aggregate_func=self.SA_layers[k],\n xyz=xyz.contiguous(), xyz_features=cur_features, xyz_bs_idxs=cur_coords[:, 0],\n new_xyz=new_xyz, new_xyz_batch_cnt=new_xyz_batch_cnt,\n filter_neighbors_with_roi=self.model_cfg.SA_LAYER[src_name].get('FILTER_NEIGHBOR_WITH_ROI', False),\n radius_of_neighbor=self.model_cfg.SA_LAYER[src_name].get('RADIUS_OF_NEIGHBOR_WITH_ROI', None),\n rois=batch_dict.get('rois', None)\n )\n\n point_features_list.append(pooled_features)\n\n point_features = torch.cat(point_features_list, dim=-1)\n\n batch_dict['point_features_before_fusion'] = point_features.view(-1, point_features.shape[-1])\n point_features = self.vsa_point_feature_fusion(point_features.view(-1, point_features.shape[-1]))\n\n batch_dict['point_features'] = point_features # (BxN, C)\n batch_dict['point_coords'] = keypoints # (BxN, 4)\n return batch_dict\n"
]
| [
[
"torch.nn.BatchNorm1d",
"torch.floor",
"torch.max",
"torch.cat",
"torch.nn.ModuleList",
"torch.nn.ReLU",
"torch.tensor",
"torch.nn.LayerNorm",
"torch.nn.Linear",
"torch.nn.Identity",
"torch.arange",
"torch.topk",
"torch.clamp",
"torch.t",
"torch.atan2"
]
]
|
maartenb/zipline-reloaded | [
"7cd7ef496dde7b5efe5423ae6c98181a67a99c15"
]
| [
"tests/test_algorithm.py"
]
| [
"#\n# Copyright 2018 Quantopian, Inc.\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 pytest\nimport warnings\nimport datetime\nfrom datetime import timedelta\nfrom functools import partial\nfrom textwrap import dedent\nfrom copy import deepcopy\n\nimport logbook\nimport toolz\nfrom logbook import TestHandler, WARNING\nfrom parameterized import parameterized\nfrom testfixtures import TempDirectory\n\nimport numpy as np\nimport pandas as pd\nimport pytz\nfrom zipline.utils.calendar_utils import get_calendar, register_calendar\n\nimport zipline.api\nfrom zipline.api import FixedSlippage\nfrom zipline.assets import Equity, Future, Asset\nfrom zipline.assets.continuous_futures import ContinuousFuture\nfrom zipline.assets.synthetic import (\n make_jagged_equity_info,\n make_simple_equity_info,\n)\nfrom zipline.errors import (\n AccountControlViolation,\n CannotOrderDelistedAsset,\n IncompatibleSlippageModel,\n RegisterTradingControlPostInit,\n ScheduleFunctionInvalidCalendar,\n SetCancelPolicyPostInit,\n SymbolNotFound,\n TradingControlViolation,\n UnsupportedCancelPolicy,\n UnsupportedDatetimeFormat,\n ZeroCapitalError,\n)\n\nfrom zipline.finance.commission import PerShare, PerTrade\nfrom zipline.finance.execution import LimitOrder\nfrom zipline.finance.order import ORDER_STATUS\nfrom zipline.finance.trading import SimulationParameters\nfrom zipline.finance.asset_restrictions import (\n Restriction,\n HistoricalRestrictions,\n StaticRestrictions,\n RESTRICTION_STATES,\n)\nfrom zipline.finance.controls import AssetDateBounds\nfrom zipline.testing import (\n FakeDataPortal,\n create_daily_df_for_asset,\n create_data_portal_from_trade_history,\n create_minute_df_for_asset,\n make_test_handler,\n make_trade_data_for_asset_info,\n parameter_space,\n str_to_seconds,\n to_utc,\n)\nfrom zipline.testing import RecordBatchBlotter\nimport zipline.testing.fixtures as zf\nfrom zipline.test_algorithms import (\n access_account_in_init,\n access_portfolio_in_init,\n api_algo,\n api_get_environment_algo,\n api_symbol_algo,\n handle_data_api,\n handle_data_noop,\n initialize_api,\n initialize_noop,\n noop_algo,\n record_float_magic,\n record_variables,\n call_with_kwargs,\n call_without_kwargs,\n call_with_bad_kwargs_current,\n call_with_bad_kwargs_history,\n bad_type_history_assets,\n bad_type_history_fields,\n bad_type_history_bar_count,\n bad_type_history_frequency,\n bad_type_history_assets_kwarg_list,\n bad_type_current_assets,\n bad_type_current_fields,\n bad_type_can_trade_assets,\n bad_type_is_stale_assets,\n bad_type_history_assets_kwarg,\n bad_type_history_fields_kwarg,\n bad_type_history_bar_count_kwarg,\n bad_type_history_frequency_kwarg,\n bad_type_current_assets_kwarg,\n bad_type_current_fields_kwarg,\n call_with_bad_kwargs_get_open_orders,\n call_with_good_kwargs_get_open_orders,\n call_with_no_kwargs_get_open_orders,\n empty_positions,\n no_handle_data,\n)\nfrom zipline.testing.predicates import assert_equal\nfrom zipline.utils.api_support import ZiplineAPI\nfrom zipline.utils.context_tricks import CallbackManager, nop_context\nfrom zipline.utils.events import (\n date_rules,\n time_rules,\n Always,\n ComposedRule,\n Never,\n OncePerDay,\n)\nfrom zipline.utils import factory\nfrom zipline.utils.pandas_utils import PerformanceWarning\n\n# Because test cases appear to reuse some resources.\n\n\n_multiprocess_can_split_ = False\n\n\nclass TestRecord(zf.WithMakeAlgo, zf.ZiplineTestCase):\n ASSET_FINDER_EQUITY_SIDS = (133,)\n SIM_PARAMS_DATA_FREQUENCY = \"daily\"\n DATA_PORTAL_USE_MINUTE_DATA = False\n\n def test_record_incr(self):\n def initialize(self):\n self.incr = 0\n\n def handle_data(self, data):\n self.incr += 1\n self.record(incr=self.incr)\n name = \"name\"\n self.record(name, self.incr)\n zipline.api.record(name, self.incr, \"name2\", 2, name3=self.incr)\n\n output = self.run_algorithm(\n initialize=initialize,\n handle_data=handle_data,\n )\n\n np.testing.assert_array_equal(output[\"incr\"].values, range(1, len(output) + 1))\n np.testing.assert_array_equal(output[\"name\"].values, range(1, len(output) + 1))\n np.testing.assert_array_equal(output[\"name2\"].values, [2] * len(output))\n np.testing.assert_array_equal(output[\"name3\"].values, range(1, len(output) + 1))\n\n\nclass TestMiscellaneousAPI(zf.WithMakeAlgo, zf.ZiplineTestCase):\n\n START_DATE = pd.Timestamp(\"2006-01-03\", tz=\"UTC\")\n END_DATE = pd.Timestamp(\"2006-01-04\", tz=\"UTC\")\n SIM_PARAMS_DATA_FREQUENCY = \"minute\"\n sids = 1, 2\n\n # FIXME: Pass a benchmark source instead of this.\n BENCHMARK_SID = None\n\n @classmethod\n def make_equity_info(cls):\n return pd.concat(\n (\n make_simple_equity_info(cls.sids, \"2002-02-1\", \"2007-01-01\"),\n pd.DataFrame.from_dict(\n {\n 3: {\n \"symbol\": \"PLAY\",\n \"start_date\": \"2002-01-01\",\n \"end_date\": \"2004-01-01\",\n \"exchange\": \"TEST\",\n },\n 4: {\n \"symbol\": \"PLAY\",\n \"start_date\": \"2005-01-01\",\n \"end_date\": \"2006-01-01\",\n \"exchange\": \"TEST\",\n },\n },\n orient=\"index\",\n ),\n )\n )\n\n @classmethod\n def make_futures_info(cls):\n return pd.DataFrame.from_dict(\n {\n 5: {\n \"symbol\": \"CLG06\",\n \"root_symbol\": \"CL\",\n \"start_date\": pd.Timestamp(\"2005-12-01\", tz=\"UTC\"),\n \"notice_date\": pd.Timestamp(\"2005-12-20\", tz=\"UTC\"),\n \"expiration_date\": pd.Timestamp(\"2006-01-20\", tz=\"UTC\"),\n \"exchange\": \"TEST\",\n },\n 6: {\n \"root_symbol\": \"CL\",\n \"symbol\": \"CLK06\",\n \"start_date\": pd.Timestamp(\"2005-12-01\", tz=\"UTC\"),\n \"notice_date\": pd.Timestamp(\"2006-03-20\", tz=\"UTC\"),\n \"expiration_date\": pd.Timestamp(\"2006-04-20\", tz=\"UTC\"),\n \"exchange\": \"TEST\",\n },\n 7: {\n \"symbol\": \"CLQ06\",\n \"root_symbol\": \"CL\",\n \"start_date\": pd.Timestamp(\"2005-12-01\", tz=\"UTC\"),\n \"notice_date\": pd.Timestamp(\"2006-06-20\", tz=\"UTC\"),\n \"expiration_date\": pd.Timestamp(\"2006-07-20\", tz=\"UTC\"),\n \"exchange\": \"TEST\",\n },\n 8: {\n \"symbol\": \"CLX06\",\n \"root_symbol\": \"CL\",\n \"start_date\": pd.Timestamp(\"2006-02-01\", tz=\"UTC\"),\n \"notice_date\": pd.Timestamp(\"2006-09-20\", tz=\"UTC\"),\n \"expiration_date\": pd.Timestamp(\"2006-10-20\", tz=\"UTC\"),\n \"exchange\": \"TEST\",\n },\n },\n orient=\"index\",\n )\n\n def test_cancel_policy_outside_init(self):\n code = \"\"\"\nfrom zipline.api import cancel_policy, set_cancel_policy\n\ndef initialize(algo):\n pass\n\ndef handle_data(algo, data):\n set_cancel_policy(cancel_policy.NeverCancel())\n\"\"\"\n algo = self.make_algo(script=code)\n with pytest.raises(SetCancelPolicyPostInit):\n algo.run()\n\n def test_cancel_policy_invalid_param(self):\n code = \"\"\"\nfrom zipline.api import set_cancel_policy\n\ndef initialize(algo):\n set_cancel_policy(\"foo\")\n\ndef handle_data(algo, data):\n pass\n\"\"\"\n algo = self.make_algo(script=code)\n with pytest.raises(UnsupportedCancelPolicy):\n algo.run()\n\n def test_zipline_api_resolves_dynamically(self):\n # Make a dummy algo.\n algo = self.make_algo(\n initialize=lambda context: None,\n handle_data=lambda context, data: None,\n )\n\n # Verify that api methods get resolved dynamically by patching them out\n # and then calling them\n for method in algo.all_api_methods():\n name = method.__name__\n sentinel = object()\n\n def fake_method(*args, **kwargs):\n return sentinel\n\n setattr(algo, name, fake_method)\n with ZiplineAPI(algo):\n assert sentinel is getattr(zipline.api, name)()\n\n def test_sid_datetime(self):\n algo_text = \"\"\"\nfrom zipline.api import sid, get_datetime\n\ndef initialize(context):\n pass\n\ndef handle_data(context, data):\n aapl_dt = data.current(sid(1), \"last_traded\")\n assert_equal(aapl_dt, get_datetime())\n\"\"\"\n self.run_algorithm(\n script=algo_text,\n namespace={\"assert_equal\": self.assertEqual},\n )\n\n def test_datetime_bad_params(self):\n algo_text = \"\"\"\nfrom zipline.api import get_datetime\nfrom pytz import timezone\n\ndef initialize(context):\n pass\n\ndef handle_data(context, data):\n get_datetime(timezone)\n\"\"\"\n algo = self.make_algo(script=algo_text)\n with pytest.raises(TypeError):\n algo.run()\n\n @parameterized.expand(\n [\n (-1000, \"invalid_base\"),\n (0, \"invalid_base\"),\n ]\n )\n def test_invalid_capital_base(self, cap_base, name):\n \"\"\"\n Test that the appropriate error is being raised and orders aren't\n filled for algos with capital base <= 0\n \"\"\"\n algo_text = \"\"\"\ndef initialize(context):\n pass\n\ndef handle_data(context, data):\n order(sid(24), 1000)\n \"\"\"\n sim_params = SimulationParameters(\n start_session=pd.Timestamp(\"2006-01-03\", tz=\"UTC\"),\n end_session=pd.Timestamp(\"2006-01-06\", tz=\"UTC\"),\n capital_base=cap_base,\n data_frequency=\"minute\",\n trading_calendar=self.trading_calendar,\n )\n expected_msg = \"initial capital base must be greater than zero\"\n with pytest.raises(ZeroCapitalError, match=expected_msg):\n # make_algo will trace to TradingAlgorithm,\n # where the exception will be raised\n self.make_algo(script=algo_text, sim_params=sim_params)\n # Make sure the correct error was raised\n\n def test_get_environment(self):\n expected_env = {\n \"arena\": \"backtest\",\n \"data_frequency\": \"minute\",\n \"start\": pd.Timestamp(\"2006-01-03 14:31:00+0000\", tz=\"utc\"),\n \"end\": pd.Timestamp(\"2006-01-04 21:00:00+0000\", tz=\"utc\"),\n \"capital_base\": 100000.0,\n \"platform\": \"zipline\",\n }\n\n def initialize(algo):\n assert \"zipline\" == algo.get_environment()\n assert expected_env == algo.get_environment(\"*\")\n\n def handle_data(algo, data):\n pass\n\n self.run_algorithm(initialize=initialize, handle_data=handle_data)\n\n def test_get_open_orders(self):\n def initialize(algo):\n algo.minute = 0\n\n def handle_data(algo, data):\n if algo.minute == 0:\n\n # Should be filled by the next minute\n algo.order(algo.sid(1), 1)\n\n # Won't be filled because the price is too low.\n algo.order(algo.sid(2), 1, style=LimitOrder(0.01, asset=algo.sid(2)))\n algo.order(algo.sid(2), 1, style=LimitOrder(0.01, asset=algo.sid(2)))\n algo.order(algo.sid(2), 1, style=LimitOrder(0.01, asset=algo.sid(2)))\n\n all_orders = algo.get_open_orders()\n assert list(all_orders.keys()) == [1, 2]\n\n assert all_orders[1] == algo.get_open_orders(1)\n assert len(all_orders[1]) == 1\n\n assert all_orders[2] == algo.get_open_orders(2)\n assert len(all_orders[2]) == 3\n\n if algo.minute == 1:\n # First order should have filled.\n # Second order should still be open.\n all_orders = algo.get_open_orders()\n assert list(all_orders.keys()) == [2]\n\n assert [] == algo.get_open_orders(1)\n\n orders_2 = algo.get_open_orders(2)\n assert all_orders[2] == orders_2\n assert len(all_orders[2]) == 3\n\n for order_ in orders_2:\n algo.cancel_order(order_)\n\n all_orders = algo.get_open_orders()\n assert all_orders == {}\n\n algo.minute += 1\n\n self.run_algorithm(initialize=initialize, handle_data=handle_data)\n\n def test_schedule_function_custom_cal(self):\n # run a simulation on the CMES cal, and schedule a function\n # using the NYSE cal\n algotext = \"\"\"\nfrom zipline.api import (\n schedule_function, get_datetime, time_rules, date_rules, calendars,\n)\n\ndef initialize(context):\n schedule_function(\n func=log_nyse_open,\n date_rule=date_rules.every_day(),\n time_rule=time_rules.market_open(),\n calendar=calendars.US_EQUITIES,\n )\n\n schedule_function(\n func=log_nyse_close,\n date_rule=date_rules.every_day(),\n time_rule=time_rules.market_close(),\n calendar=calendars.US_EQUITIES,\n )\n\n context.nyse_opens = []\n context.nyse_closes = []\n\ndef log_nyse_open(context, data):\n context.nyse_opens.append(get_datetime())\n\ndef log_nyse_close(context, data):\n context.nyse_closes.append(get_datetime())\n \"\"\"\n\n algo = self.make_algo(\n script=algotext,\n sim_params=self.make_simparams(\n trading_calendar=get_calendar(\"CMES\"),\n ),\n )\n algo.run()\n\n nyse = get_calendar(\"NYSE\")\n\n for minute in algo.nyse_opens:\n # each minute should be a nyse session open\n session_label = nyse.minute_to_session_label(minute)\n session_open = nyse.session_open(session_label)\n assert session_open == minute\n\n for minute in algo.nyse_closes:\n # each minute should be a minute before a nyse session close\n session_label = nyse.minute_to_session_label(minute)\n session_close = nyse.session_close(session_label)\n assert session_close - timedelta(minutes=1) == minute\n\n # Test that passing an invalid calendar parameter raises an error.\n erroring_algotext = dedent(\n \"\"\"\n from zipline.api import schedule_function\n from zipline.utils.calendar_utils import get_calendar\n\n def initialize(context):\n schedule_function(func=my_func, calendar=get_calendar('XNYS'))\n\n def my_func(context, data):\n pass\n \"\"\"\n )\n\n algo = self.make_algo(\n script=erroring_algotext,\n sim_params=self.make_simparams(\n trading_calendar=get_calendar(\"CMES\"),\n ),\n )\n\n with pytest.raises(ScheduleFunctionInvalidCalendar):\n algo.run()\n\n def test_schedule_function(self):\n us_eastern = pytz.timezone(\"US/Eastern\")\n\n def incrementer(algo, data):\n algo.func_called += 1\n curdt = algo.get_datetime().tz_convert(pytz.utc)\n assert curdt == us_eastern.localize(\n datetime.datetime.combine(curdt.date(), datetime.time(9, 31))\n )\n\n def initialize(algo):\n algo.func_called = 0\n algo.days = 1\n algo.date = None\n algo.schedule_function(\n func=incrementer,\n date_rule=date_rules.every_day(),\n time_rule=time_rules.market_open(),\n )\n\n def handle_data(algo, data):\n if not algo.date:\n algo.date = algo.get_datetime().date()\n\n if algo.date < algo.get_datetime().date():\n algo.days += 1\n algo.date = algo.get_datetime().date()\n\n algo = self.make_algo(\n initialize=initialize,\n handle_data=handle_data,\n )\n algo.run()\n\n assert algo.func_called == algo.days\n\n def test_event_context(self):\n expected_data = []\n collected_data_pre = []\n collected_data_post = []\n function_stack = []\n\n def pre(data):\n function_stack.append(pre)\n collected_data_pre.append(data)\n\n def post(data):\n function_stack.append(post)\n collected_data_post.append(data)\n\n def initialize(context):\n context.add_event(Always(), f)\n context.add_event(Always(), g)\n\n def handle_data(context, data):\n function_stack.append(handle_data)\n expected_data.append(data)\n\n def f(context, data):\n function_stack.append(f)\n\n def g(context, data):\n function_stack.append(g)\n\n algo = self.make_algo(\n initialize=initialize,\n handle_data=handle_data,\n create_event_context=CallbackManager(pre, post),\n )\n algo.run()\n\n assert len(expected_data) == 780\n assert collected_data_pre == expected_data\n assert collected_data_post == expected_data\n\n assert (\n len(function_stack) == 3900\n ), \"Incorrect number of functions called: %s != 3900\" % len(function_stack)\n expected_functions = [pre, handle_data, f, g, post] * 97530\n for n, (f, g) in enumerate(zip(function_stack, expected_functions)):\n assert (\n f == g\n ), \"function at position %d was incorrect, expected %s but got %s\" % (\n n,\n g.__name__,\n f.__name__,\n )\n\n @parameterized.expand(\n [\n (\"daily\",),\n (\"minute\"),\n ]\n )\n def test_schedule_function_rule_creation(self, mode):\n def nop(*args, **kwargs):\n return None\n\n self.sim_params.data_frequency = mode\n algo = self.make_algo(\n initialize=nop,\n handle_data=nop,\n sim_params=self.sim_params,\n )\n\n # Schedule something for NOT Always.\n # Compose two rules to ensure calendar is set properly.\n algo.schedule_function(nop, time_rule=Never() & Always())\n\n event_rule = algo.event_manager._events[1].rule\n assert isinstance(event_rule, OncePerDay)\n assert event_rule.cal == algo.trading_calendar\n\n inner_rule = event_rule.rule\n assert isinstance(inner_rule, ComposedRule)\n assert inner_rule.cal == algo.trading_calendar\n\n first = inner_rule.first\n second = inner_rule.second\n composer = inner_rule.composer\n\n assert isinstance(first, Always)\n assert first.cal == algo.trading_calendar\n assert second.cal == algo.trading_calendar\n\n if mode == \"daily\":\n assert isinstance(second, Always)\n else:\n assert isinstance(second, ComposedRule)\n assert isinstance(second.first, Never)\n assert second.first.cal == algo.trading_calendar\n\n assert isinstance(second.second, Always)\n assert second.second.cal == algo.trading_calendar\n\n assert composer is ComposedRule.lazy_and\n\n def test_asset_lookup(self):\n algo = self.make_algo()\n\n # this date doesn't matter\n start_session = pd.Timestamp(\"2000-01-01\", tz=\"UTC\")\n\n # Test before either PLAY existed\n algo.sim_params = algo.sim_params.create_new(\n start_session, pd.Timestamp(\"2001-12-01\", tz=\"UTC\")\n )\n\n with pytest.raises(SymbolNotFound):\n algo.symbol(\"PLAY\")\n with pytest.raises(SymbolNotFound):\n algo.symbols(\"PLAY\")\n\n # Test when first PLAY exists\n algo.sim_params = algo.sim_params.create_new(\n start_session, pd.Timestamp(\"2002-12-01\", tz=\"UTC\")\n )\n list_result = algo.symbols(\"PLAY\")\n assert 3 == list_result[0]\n\n # Test after first PLAY ends\n algo.sim_params = algo.sim_params.create_new(\n start_session, pd.Timestamp(\"2004-12-01\", tz=\"UTC\")\n )\n assert 3 == algo.symbol(\"PLAY\")\n\n # Test after second PLAY begins\n algo.sim_params = algo.sim_params.create_new(\n start_session, pd.Timestamp(\"2005-12-01\", tz=\"UTC\")\n )\n assert 4 == algo.symbol(\"PLAY\")\n\n # Test after second PLAY ends\n algo.sim_params = algo.sim_params.create_new(\n start_session, pd.Timestamp(\"2006-12-01\", tz=\"UTC\")\n )\n assert 4 == algo.symbol(\"PLAY\")\n list_result = algo.symbols(\"PLAY\")\n assert 4 == list_result[0]\n\n # Test lookup SID\n assert isinstance(algo.sid(3), Equity)\n assert isinstance(algo.sid(4), Equity)\n\n # Supplying a non-string argument to symbol()\n # should result in a TypeError.\n with pytest.raises(TypeError):\n algo.symbol(1)\n\n with pytest.raises(TypeError):\n algo.symbol((1,))\n\n with pytest.raises(TypeError):\n algo.symbol({1})\n\n with pytest.raises(TypeError):\n algo.symbol([1])\n\n with pytest.raises(TypeError):\n algo.symbol({\"foo\": \"bar\"})\n\n def test_future_symbol(self):\n \"\"\"Tests the future_symbol API function.\"\"\"\n algo = self.make_algo()\n algo.datetime = pd.Timestamp(\"2006-12-01\", tz=\"UTC\")\n\n # Check that we get the correct fields for the CLG06 symbol\n cl = algo.future_symbol(\"CLG06\")\n assert cl.sid == 5\n assert cl.symbol == \"CLG06\"\n assert cl.root_symbol == \"CL\"\n assert cl.start_date == pd.Timestamp(\"2005-12-01\", tz=\"UTC\")\n assert cl.notice_date == pd.Timestamp(\"2005-12-20\", tz=\"UTC\")\n assert cl.expiration_date == pd.Timestamp(\"2006-01-20\", tz=\"UTC\")\n\n with pytest.raises(SymbolNotFound):\n algo.future_symbol(\"\")\n\n with pytest.raises(SymbolNotFound):\n algo.future_symbol(\"PLAY\")\n\n with pytest.raises(SymbolNotFound):\n algo.future_symbol(\"FOOBAR\")\n\n # Supplying a non-string argument to future_symbol()\n # should result in a TypeError.\n with pytest.raises(TypeError):\n algo.future_symbol(1)\n\n with pytest.raises(TypeError):\n algo.future_symbol((1,))\n\n with pytest.raises(TypeError):\n algo.future_symbol({1})\n\n with pytest.raises(TypeError):\n algo.future_symbol([1])\n\n with pytest.raises(TypeError):\n algo.future_symbol({\"foo\": \"bar\"})\n\n\nclass TestSetSymbolLookupDate(zf.WithMakeAlgo, zf.ZiplineTestCase):\n # January 2006\n # Su Mo Tu We Th Fr Sa\n # 1 2 3 4 5 6 7\n # 8 9 10 11 12 13 14\n # 15 16 17 18 19 20 21\n # 22 23 24 25 26 27 28\n # 29 30 31\n START_DATE = pd.Timestamp(\"2006-01-03\", tz=\"UTC\")\n END_DATE = pd.Timestamp(\"2006-01-06\", tz=\"UTC\")\n SIM_PARAMS_START_DATE = pd.Timestamp(\"2006-01-04\", tz=\"UTC\")\n SIM_PARAMS_DATA_FREQUENCY = \"daily\"\n DATA_PORTAL_USE_MINUTE_DATA = False\n BENCHMARK_SID = 3\n\n @classmethod\n def make_equity_info(cls):\n dates = pd.date_range(cls.START_DATE, cls.END_DATE)\n assert len(dates) == 4, \"Expected four dates.\"\n\n # Two assets with the same ticker, ending on days[1] and days[3], plus\n # a benchmark that spans the whole period.\n cls.sids = [1, 2, 3]\n cls.asset_starts = [dates[0], dates[2]]\n cls.asset_ends = [dates[1], dates[3]]\n return pd.DataFrame.from_records(\n [\n {\n \"symbol\": \"DUP\",\n \"start_date\": cls.asset_starts[0],\n \"end_date\": cls.asset_ends[0],\n \"exchange\": \"TEST\",\n \"asset_name\": \"FIRST\",\n },\n {\n \"symbol\": \"DUP\",\n \"start_date\": cls.asset_starts[1],\n \"end_date\": cls.asset_ends[1],\n \"exchange\": \"TEST\",\n \"asset_name\": \"SECOND\",\n },\n {\n \"symbol\": \"BENCH\",\n \"start_date\": cls.START_DATE,\n \"end_date\": cls.END_DATE,\n \"exchange\": \"TEST\",\n \"asset_name\": \"BENCHMARK\",\n },\n ],\n index=cls.sids,\n )\n\n def test_set_symbol_lookup_date(self):\n \"\"\"\n Test the set_symbol_lookup_date API method.\n \"\"\"\n set_symbol_lookup_date = zipline.api.set_symbol_lookup_date\n\n def initialize(context):\n set_symbol_lookup_date(self.asset_ends[0])\n assert zipline.api.symbol(\"DUP\").sid == self.sids[0]\n\n set_symbol_lookup_date(self.asset_ends[1])\n assert zipline.api.symbol(\"DUP\").sid == self.sids[1]\n\n with pytest.raises(UnsupportedDatetimeFormat):\n set_symbol_lookup_date(\"foobar\")\n\n self.run_algorithm(initialize=initialize)\n\n\nclass TestPositions(zf.WithMakeAlgo, zf.ZiplineTestCase):\n START_DATE = pd.Timestamp(\"2006-01-03\", tz=\"utc\")\n END_DATE = pd.Timestamp(\"2006-01-06\", tz=\"utc\")\n SIM_PARAMS_CAPITAL_BASE = 1000\n\n ASSET_FINDER_EQUITY_SIDS = (1, 133)\n\n SIM_PARAMS_DATA_FREQUENCY = \"daily\"\n\n @classmethod\n def make_equity_daily_bar_data(cls, country_code, sids):\n frame = pd.DataFrame(\n {\n \"open\": [90, 95, 100, 105],\n \"high\": [90, 95, 100, 105],\n \"low\": [90, 95, 100, 105],\n \"close\": [90, 95, 100, 105],\n \"volume\": 100,\n },\n index=cls.equity_daily_bar_days,\n )\n return ((sid, frame) for sid in sids)\n\n @classmethod\n def make_futures_info(cls):\n return pd.DataFrame.from_dict(\n {\n 1000: {\n \"symbol\": \"CLF06\",\n \"root_symbol\": \"CL\",\n \"start_date\": cls.START_DATE,\n \"end_date\": cls.END_DATE,\n \"auto_close_date\": cls.END_DATE + cls.trading_calendar.day,\n \"exchange\": \"CMES\",\n \"multiplier\": 100,\n },\n },\n orient=\"index\",\n )\n\n @classmethod\n def make_future_minute_bar_data(cls):\n trading_calendar = cls.trading_calendars[Future]\n\n sids = cls.asset_finder.futures_sids\n minutes = trading_calendar.minutes_for_sessions_in_range(\n cls.future_minute_bar_days[0],\n cls.future_minute_bar_days[-1],\n )\n frame = pd.DataFrame(\n {\n \"open\": 2.0,\n \"high\": 2.0,\n \"low\": 2.0,\n \"close\": 2.0,\n \"volume\": 100,\n },\n index=minutes,\n )\n return ((sid, frame) for sid in sids)\n\n def test_portfolio_exited_position(self):\n # This test ensures ensures that 'phantom' positions do not appear in\n # context.portfolio.positions in the case that a position has been\n # entered and fully exited.\n\n def initialize(context, sids):\n context.ordered = False\n context.exited = False\n context.sids = sids\n\n def handle_data(context, data):\n if not context.ordered:\n for s in context.sids:\n context.order(context.sid(s), 1)\n context.ordered = True\n\n if not context.exited:\n amounts = [pos.amount for pos in context.portfolio.positions.values()]\n\n if len(amounts) > 0 and all([(amount == 1) for amount in amounts]):\n for stock in context.portfolio.positions:\n context.order(context.sid(stock), -1)\n context.exited = True\n\n # Should be 0 when all positions are exited.\n context.record(num_positions=len(context.portfolio.positions))\n\n result = self.run_algorithm(\n initialize=initialize,\n handle_data=handle_data,\n sids=self.ASSET_FINDER_EQUITY_SIDS,\n )\n\n expected_position_count = [\n 0, # Before entering the first position\n 2, # After entering, exiting on this date\n 0, # After exiting\n 0,\n ]\n for i, expected in enumerate(expected_position_count):\n assert result.iloc[i][\"num_positions\"] == expected\n\n def test_noop_orders(self):\n asset = self.asset_finder.retrieve_asset(1)\n\n # Algorithm that tries to buy with extremely low stops/limits and tries\n # to sell with extremely high versions of same. Should not end up with\n # any positions for reasonable data.\n def handle_data(algo, data):\n\n ########\n # Buys #\n ########\n\n # Buy with low limit, shouldn't trigger.\n algo.order(asset, 100, limit_price=1)\n\n # But with high stop, shouldn't trigger\n algo.order(asset, 100, stop_price=10000000)\n\n # Buy with high limit (should trigger) but also high stop (should\n # prevent trigger).\n algo.order(asset, 100, limit_price=10000000, stop_price=10000000)\n\n # Buy with low stop (should trigger), but also low limit (should\n # prevent trigger).\n algo.order(asset, 100, limit_price=1, stop_price=1)\n\n #########\n # Sells #\n #########\n\n # Sell with high limit, shouldn't trigger.\n algo.order(asset, -100, limit_price=1000000)\n\n # Sell with low stop, shouldn't trigger.\n algo.order(asset, -100, stop_price=1)\n\n # Sell with low limit (should trigger), but also high stop (should\n # prevent trigger).\n algo.order(asset, -100, limit_price=1000000, stop_price=1000000)\n\n # Sell with low limit (should trigger), but also low stop (should\n # prevent trigger).\n algo.order(asset, -100, limit_price=1, stop_price=1)\n\n ###################\n # Rounding Checks #\n ###################\n algo.order(asset, 100, limit_price=0.00000001)\n algo.order(asset, -100, stop_price=0.00000001)\n\n daily_stats = self.run_algorithm(handle_data=handle_data)\n\n # Verify that positions are empty for all dates.\n empty_positions = daily_stats.positions.map(lambda x: len(x) == 0)\n assert empty_positions.all()\n\n def test_position_weights(self):\n sids = (1, 133, 1000)\n equity_1, equity_133, future_1000 = self.asset_finder.retrieve_all(sids)\n\n def initialize(algo, sids_and_amounts, *args, **kwargs):\n algo.ordered = False\n algo.sids_and_amounts = sids_and_amounts\n algo.set_commission(\n us_equities=PerTrade(0),\n us_futures=PerTrade(0),\n )\n algo.set_slippage(\n us_equities=FixedSlippage(0),\n us_futures=FixedSlippage(0),\n )\n\n def handle_data(algo, data):\n if not algo.ordered:\n for s, amount in algo.sids_and_amounts:\n algo.order(algo.sid(s), amount)\n algo.ordered = True\n\n algo.record(\n position_weights=algo.portfolio.current_portfolio_weights,\n )\n\n daily_stats = self.run_algorithm(\n sids_and_amounts=zip(sids, [2, -1, 1]),\n initialize=initialize,\n handle_data=handle_data,\n )\n\n expected_position_weights = [\n # No positions held on the first day.\n pd.Series({}, dtype=float),\n # Each equity's position value is its price times the number of\n # shares held. In this example, we hold a long position in 2 shares\n # of equity_1 so its weight is (95.0 * 2) = 190.0 divided by the\n # total portfolio value. The total portfolio value is the sum of\n # cash ($905.00) plus the value of all equity positions.\n #\n # For a futures contract, its weight is the unit price times number\n # of shares held times the multiplier. For future_1000, this is\n # (2.0 * 1 * 100) = 200.0 divided by total portfolio value.\n pd.Series(\n {\n equity_1: 190.0 / (190.0 - 95.0 + 905.0),\n equity_133: -95.0 / (190.0 - 95.0 + 905.0),\n future_1000: 200.0 / (190.0 - 95.0 + 905.0),\n }\n ),\n pd.Series(\n {\n equity_1: 200.0 / (200.0 - 100.0 + 905.0),\n equity_133: -100.0 / (200.0 - 100.0 + 905.0),\n future_1000: 200.0 / (200.0 - 100.0 + 905.0),\n }\n ),\n pd.Series(\n {\n equity_1: 210.0 / (210.0 - 105.0 + 905.0),\n equity_133: -105.0 / (210.0 - 105.0 + 905.0),\n future_1000: 200.0 / (210.0 - 105.0 + 905.0),\n }\n ),\n ]\n\n for i, expected in enumerate(expected_position_weights):\n assert_equal(daily_stats.iloc[i][\"position_weights\"], expected)\n\n\nclass TestBeforeTradingStart(zf.WithMakeAlgo, zf.ZiplineTestCase):\n START_DATE = pd.Timestamp(\"2016-01-06\", tz=\"utc\")\n END_DATE = pd.Timestamp(\"2016-01-07\", tz=\"utc\")\n SIM_PARAMS_CAPITAL_BASE = 10000\n SIM_PARAMS_DATA_FREQUENCY = \"minute\"\n EQUITY_DAILY_BAR_LOOKBACK_DAYS = EQUITY_MINUTE_BAR_LOOKBACK_DAYS = 1\n\n DATA_PORTAL_FIRST_TRADING_DAY = pd.Timestamp(\"2016-01-05\", tz=\"UTC\")\n EQUITY_MINUTE_BAR_START_DATE = pd.Timestamp(\"2016-01-05\", tz=\"UTC\")\n FUTURE_MINUTE_BAR_START_DATE = pd.Timestamp(\"2016-01-05\", tz=\"UTC\")\n\n data_start = ASSET_FINDER_EQUITY_START_DATE = pd.Timestamp(\n \"2016-01-05\",\n tz=\"utc\",\n )\n\n SPLIT_ASSET_SID = 3\n ASSET_FINDER_EQUITY_SIDS = 1, 2, SPLIT_ASSET_SID\n\n @classmethod\n def make_equity_minute_bar_data(cls):\n asset_minutes = cls.trading_calendar.minutes_in_range(\n cls.data_start,\n cls.END_DATE,\n )\n minutes_count = len(asset_minutes)\n minutes_arr = np.arange(minutes_count) + 1\n split_data = pd.DataFrame(\n {\n \"open\": minutes_arr + 1,\n \"high\": minutes_arr + 2,\n \"low\": minutes_arr - 1,\n \"close\": minutes_arr,\n \"volume\": 100 * minutes_arr,\n },\n index=asset_minutes,\n )\n split_data.iloc[780:] = split_data.iloc[780:] / 2.0\n for sid in (1, 8554):\n yield sid, create_minute_df_for_asset(\n cls.trading_calendar,\n cls.data_start,\n cls.END_DATE,\n )\n\n yield 2, create_minute_df_for_asset(\n cls.trading_calendar,\n cls.data_start,\n cls.END_DATE,\n 50,\n )\n yield cls.SPLIT_ASSET_SID, split_data\n\n @classmethod\n def make_splits_data(cls):\n return pd.DataFrame.from_records(\n [\n {\n \"effective_date\": str_to_seconds(\"2016-01-07\"),\n \"ratio\": 0.5,\n \"sid\": cls.SPLIT_ASSET_SID,\n }\n ]\n )\n\n @classmethod\n def make_equity_daily_bar_data(cls, country_code, sids):\n for sid in sids:\n yield sid, create_daily_df_for_asset(\n cls.trading_calendar,\n cls.data_start,\n cls.END_DATE,\n )\n\n def test_data_in_bts_minute(self):\n algo_code = dedent(\n \"\"\"\n from zipline.api import record, sid\n def initialize(context):\n context.history_values = []\n\n def before_trading_start(context, data):\n record(the_price1=data.current(sid(1), \"price\"))\n record(the_high1=data.current(sid(1), \"high\"))\n record(the_price2=data.current(sid(2), \"price\"))\n record(the_high2=data.current(sid(2), \"high\"))\n\n context.history_values.append(data.history(\n [sid(1), sid(2)],\n [\"price\", \"high\"],\n 60,\n \"1m\"\n ))\n\n def handle_data(context, data):\n pass\n \"\"\"\n )\n\n algo = self.make_algo(script=algo_code)\n results = algo.run()\n\n # fetching data at midnight gets us the previous market minute's data\n assert 390 == results.iloc[0].the_price1\n assert 392 == results.iloc[0].the_high1\n\n # make sure that price is ffilled, but not other fields\n assert 350 == results.iloc[0].the_price2\n assert np.isnan(results.iloc[0].the_high2)\n\n # 10-minute history\n\n # asset1 day1 price should be 331-390\n np.testing.assert_array_equal(\n range(331, 391), algo.history_values[0].loc[pd.IndexSlice[:, 1], \"price\"]\n )\n\n # asset1 day1 high should be 333-392\n np.testing.assert_array_equal(\n range(333, 393), algo.history_values[0].loc[pd.IndexSlice[:, 1], \"high\"]\n )\n\n # asset2 day1 price should be 19 300s, then 40 350s\n np.testing.assert_array_equal(\n [300] * 19,\n algo.history_values[0].loc[pd.IndexSlice[:, 2], \"price\"].iloc[:19],\n )\n\n np.testing.assert_array_equal(\n [350] * 40,\n algo.history_values[0].loc[pd.IndexSlice[:, 2], \"price\"].iloc[20:],\n )\n\n # asset2 day1 high should be all NaNs except for the 19th item\n # = 2016-01-05 20:20:00+00:00\n np.testing.assert_array_equal(\n np.full(19, np.nan),\n algo.history_values[0].loc[pd.IndexSlice[:, 2], \"high\"].iloc[:19],\n )\n\n assert 352 == algo.history_values[0].loc[pd.IndexSlice[:, 2], \"high\"].iloc[19]\n\n np.testing.assert_array_equal(\n np.full(40, np.nan),\n algo.history_values[0].loc[pd.IndexSlice[:, 2], \"high\"].iloc[20:],\n )\n\n def test_data_in_bts_daily(self):\n algo_code = dedent(\n \"\"\"\n from zipline.api import record, sid\n def initialize(context):\n context.history_values = []\n\n def before_trading_start(context, data):\n record(the_price1=data.current(sid(1), \"price\"))\n record(the_high1=data.current(sid(1), \"high\"))\n record(the_price2=data.current(sid(2), \"price\"))\n record(the_high2=data.current(sid(2), \"high\"))\n\n context.history_values.append(data.history(\n [sid(1), sid(2)],\n [\"price\", \"high\"],\n 1,\n \"1d\",\n ))\n\n def handle_data(context, data):\n pass\n \"\"\"\n )\n\n algo = self.make_algo(script=algo_code)\n results = algo.run()\n\n assert 392 == results.the_high1[0]\n assert 390 == results.the_price1[0]\n\n # nan because asset2 only trades every 50 minutes\n assert np.isnan(results.the_high2[0])\n\n assert 350, results.the_price2[0]\n\n assert 392 == algo.history_values[0][\"high\"][0]\n assert 390 == algo.history_values[0][\"price\"][0]\n\n assert 352 == algo.history_values[0][\"high\"][1]\n assert 350 == algo.history_values[0][\"price\"][1]\n\n def test_portfolio_bts(self):\n algo_code = dedent(\n \"\"\"\n from zipline.api import order, sid, record\n\n def initialize(context):\n context.ordered = False\n context.hd_portfolio = context.portfolio\n\n def before_trading_start(context, data):\n bts_portfolio = context.portfolio\n\n # Assert that the portfolio in BTS is the same as the last\n # portfolio in handle_data\n assert (context.hd_portfolio == bts_portfolio)\n record(pos_value=bts_portfolio.positions_value)\n\n def handle_data(context, data):\n if not context.ordered:\n order(sid(1), 1)\n context.ordered = True\n context.hd_portfolio = context.portfolio\n \"\"\"\n )\n\n algo = self.make_algo(script=algo_code)\n results = algo.run()\n\n # Asset starts with price 1 on 1/05 and increases by 1 every minute.\n # Simulation starts on 1/06, where the price in bts is 390, and\n # positions_value is 0. On 1/07, price is 780, and after buying one\n # share on the first bar of 1/06, positions_value is 780\n assert results.pos_value.iloc[0] == 0\n assert results.pos_value.iloc[1] == 780\n\n def test_account_bts(self):\n algo_code = dedent(\n \"\"\"\n from zipline.api import order, sid, record, set_slippage, slippage\n\n def initialize(context):\n context.ordered = False\n context.hd_account = context.account\n set_slippage(slippage.VolumeShareSlippage())\n\n def before_trading_start(context, data):\n bts_account = context.account\n\n # Assert that the account in BTS is the same as the last account\n # in handle_data\n assert (context.hd_account == bts_account)\n record(port_value=context.account.equity_with_loan)\n\n def handle_data(context, data):\n if not context.ordered:\n order(sid(1), 1)\n context.ordered = True\n context.hd_account = context.account\n \"\"\"\n )\n\n algo = self.make_algo(script=algo_code)\n results = algo.run()\n\n # Starting portfolio value is 10000. Order for the asset fills on the\n # second bar of 1/06, where the price is 391, and costs the default\n # commission of 0. On 1/07, the price is 780, and the increase in\n # portfolio value is 780-392-0\n assert results.port_value.iloc[0] == 10000\n self.assertAlmostEqual(\n results.port_value.iloc[1], 10000 + 780 - 392 - 0, places=2\n )\n\n def test_portfolio_bts_with_overnight_split(self):\n algo_code = dedent(\n \"\"\"\n from zipline.api import order, sid, record\n\n def initialize(context):\n context.ordered = False\n context.hd_portfolio = context.portfolio\n\n def before_trading_start(context, data):\n bts_portfolio = context.portfolio\n # Assert that the portfolio in BTS is the same as the last\n # portfolio in handle_data, except for the positions\n for k in bts_portfolio.__dict__:\n if k != 'positions':\n assert (context.hd_portfolio.__dict__[k]\n == bts_portfolio.__dict__[k])\n record(pos_value=bts_portfolio.positions_value)\n record(pos_amount=bts_portfolio.positions[sid(3)].amount)\n record(\n last_sale_price=bts_portfolio.positions[sid(3)].last_sale_price\n )\n\n def handle_data(context, data):\n if not context.ordered:\n order(sid(3), 1)\n context.ordered = True\n context.hd_portfolio = context.portfolio\n \"\"\"\n )\n\n results = self.run_algorithm(script=algo_code)\n\n # On 1/07, positions value should by 780, same as without split\n assert results.pos_value.iloc[0] == 0\n assert results.pos_value.iloc[1] == 780\n\n # On 1/07, after applying the split, 1 share becomes 2\n assert results.pos_amount.iloc[0] == 0\n assert results.pos_amount.iloc[1] == 2\n\n # On 1/07, after applying the split, last sale price is halved\n assert results.last_sale_price.iloc[0] == 0\n assert results.last_sale_price.iloc[1] == 390\n\n def test_account_bts_with_overnight_split(self):\n algo_code = dedent(\n \"\"\"\n from zipline.api import order, sid, record, set_slippage, slippage\n\n def initialize(context):\n context.ordered = False\n context.hd_account = context.account\n set_slippage(slippage.VolumeShareSlippage())\n\n\n def before_trading_start(context, data):\n bts_account = context.account\n # Assert that the account in BTS is the same as the last account\n # in handle_data\n assert (context.hd_account == bts_account)\n record(port_value=bts_account.equity_with_loan)\n\n def handle_data(context, data):\n if not context.ordered:\n order(sid(1), 1)\n context.ordered = True\n context.hd_account = context.account\n \"\"\"\n )\n\n results = self.run_algorithm(script=algo_code)\n\n # On 1/07, portfolio value is the same as without split\n assert results.port_value.iloc[0] == 10000\n self.assertAlmostEqual(\n results.port_value.iloc[1], 10000 + 780 - 392 - 0, places=2\n )\n\n\nclass TestAlgoScript(zf.WithMakeAlgo, zf.ZiplineTestCase):\n START_DATE = pd.Timestamp(\"2006-01-03\", tz=\"utc\")\n END_DATE = pd.Timestamp(\"2006-12-31\", tz=\"utc\")\n SIM_PARAMS_DATA_FREQUENCY = \"daily\"\n DATA_PORTAL_USE_MINUTE_DATA = False\n EQUITY_DAILY_BAR_LOOKBACK_DAYS = 5 # max history window length\n\n STRING_TYPE_NAMES = [str.__name__]\n STRING_TYPE_NAMES_STRING = \", \".join(STRING_TYPE_NAMES)\n ASSET_TYPE_NAME = Asset.__name__\n CONTINUOUS_FUTURE_NAME = ContinuousFuture.__name__\n ASSET_OR_STRING_TYPE_NAMES = \", \".join([ASSET_TYPE_NAME] + STRING_TYPE_NAMES)\n ASSET_OR_STRING_OR_CF_TYPE_NAMES = \", \".join(\n [ASSET_TYPE_NAME, CONTINUOUS_FUTURE_NAME] + STRING_TYPE_NAMES\n )\n ARG_TYPE_TEST_CASES = (\n (\n \"history__assets\",\n (bad_type_history_assets, ASSET_OR_STRING_OR_CF_TYPE_NAMES, True),\n ),\n (\"history__fields\", (bad_type_history_fields, STRING_TYPE_NAMES_STRING, True)),\n (\"history__bar_count\", (bad_type_history_bar_count, \"int\", False)),\n (\n \"history__frequency\",\n (bad_type_history_frequency, STRING_TYPE_NAMES_STRING, False),\n ),\n (\n \"current__assets\",\n (bad_type_current_assets, ASSET_OR_STRING_OR_CF_TYPE_NAMES, True),\n ),\n (\"current__fields\", (bad_type_current_fields, STRING_TYPE_NAMES_STRING, True)),\n (\"is_stale__assets\", (bad_type_is_stale_assets, \"Asset\", True)),\n (\"can_trade__assets\", (bad_type_can_trade_assets, \"Asset\", True)),\n (\n \"history_kwarg__assets\",\n (bad_type_history_assets_kwarg, ASSET_OR_STRING_OR_CF_TYPE_NAMES, True),\n ),\n (\n \"history_kwarg_bad_list__assets\",\n (\n bad_type_history_assets_kwarg_list,\n ASSET_OR_STRING_OR_CF_TYPE_NAMES,\n True,\n ),\n ),\n (\n \"history_kwarg__fields\",\n (bad_type_history_fields_kwarg, STRING_TYPE_NAMES_STRING, True),\n ),\n (\"history_kwarg__bar_count\", (bad_type_history_bar_count_kwarg, \"int\", False)),\n (\n \"history_kwarg__frequency\",\n (bad_type_history_frequency_kwarg, STRING_TYPE_NAMES_STRING, False),\n ),\n (\n \"current_kwarg__assets\",\n (bad_type_current_assets_kwarg, ASSET_OR_STRING_OR_CF_TYPE_NAMES, True),\n ),\n (\n \"current_kwarg__fields\",\n (bad_type_current_fields_kwarg, STRING_TYPE_NAMES_STRING, True),\n ),\n )\n\n sids = 0, 1, 3, 133\n\n # FIXME: Pass a benchmark explicitly here.\n BENCHMARK_SID = None\n\n @classmethod\n def make_equity_info(cls):\n register_calendar(\"TEST\", get_calendar(\"NYSE\"), force=True)\n\n data = make_simple_equity_info(\n cls.sids,\n cls.START_DATE,\n cls.END_DATE,\n )\n data.loc[3, \"symbol\"] = \"TEST\"\n return data\n\n @classmethod\n def make_equity_daily_bar_data(cls, country_code, sids):\n cal = cls.trading_calendars[Equity]\n sessions = cal.sessions_in_range(cls.START_DATE, cls.END_DATE)\n frame = pd.DataFrame(\n {\n \"close\": 10.0,\n \"high\": 10.5,\n \"low\": 9.5,\n \"open\": 10.0,\n \"volume\": 100,\n },\n index=sessions,\n )\n\n for sid in sids:\n yield sid, frame\n\n def test_noop(self):\n self.run_algorithm(\n initialize=initialize_noop,\n handle_data=handle_data_noop,\n )\n\n def test_noop_string(self):\n self.run_algorithm(script=noop_algo)\n\n def test_no_handle_data(self):\n self.run_algorithm(script=no_handle_data)\n\n def test_api_calls(self):\n self.run_algorithm(\n initialize=initialize_api,\n handle_data=handle_data_api,\n )\n\n def test_api_calls_string(self):\n self.run_algorithm(script=api_algo)\n\n def test_api_get_environment(self):\n platform = \"zipline\"\n algo = self.make_algo(\n script=api_get_environment_algo,\n platform=platform,\n )\n algo.run()\n assert algo.environment == platform\n\n def test_api_symbol(self):\n self.run_algorithm(script=api_symbol_algo)\n\n def test_fixed_slippage(self):\n # verify order -> transaction -> portfolio position.\n # --------------\n test_algo = self.make_algo(\n script=\"\"\"\nfrom zipline.api import (slippage,\n commission,\n set_slippage,\n set_commission,\n order,\n record,\n sid)\n\ndef initialize(context):\n model = slippage.FixedSlippage(spread=0.10)\n set_slippage(model)\n set_commission(commission.PerTrade(100.00))\n context.count = 1\n context.incr = 0\n\ndef handle_data(context, data):\n if context.incr < context.count:\n order(sid(0), -1000)\n record(price=data.current(sid(0), \"price\"))\n\n context.incr += 1\"\"\",\n )\n results = test_algo.run()\n\n # flatten the list of txns\n all_txns = [\n val for sublist in results[\"transactions\"].tolist() for val in sublist\n ]\n\n assert len(all_txns) == 1\n txn = all_txns[0]\n\n expected_spread = 0.05\n expected_price = test_algo.recorded_vars[\"price\"] - expected_spread\n\n assert expected_price == txn[\"price\"]\n\n # make sure that the $100 commission was applied to our cash\n # the txn was for -1000 shares at 9.95, means -9.95k. our capital_used\n # for that day was therefore 9.95k, but after the $100 commission,\n # it should be 9.85k.\n assert 9850 == results.capital_used[1]\n assert 100 == results[\"orders\"].iloc[1][0][\"commission\"]\n\n @parameterized.expand(\n [\n (\n \"no_minimum_commission\",\n 0,\n ),\n (\n \"default_minimum_commission\",\n 0,\n ),\n (\n \"alternate_minimum_commission\",\n 2,\n ),\n ]\n )\n def test_volshare_slippage(self, name, minimum_commission):\n tempdir = TempDirectory()\n try:\n if name == \"default_minimum_commission\":\n commission_line = \"set_commission(commission.PerShare(0.02))\"\n else:\n commission_line = (\n \"set_commission(commission.PerShare(0.02, \"\n \"min_trade_cost={0}))\".format(minimum_commission)\n )\n\n # verify order -> transaction -> portfolio position.\n # --------------\n # XXX: This is the last remaining consumer of\n # create_daily_trade_source.\n trades = factory.create_daily_trade_source(\n [0], self.sim_params, self.asset_finder, self.trading_calendar\n )\n data_portal = create_data_portal_from_trade_history(\n self.asset_finder,\n self.trading_calendar,\n tempdir,\n self.sim_params,\n {0: trades},\n )\n test_algo = self.make_algo(\n data_portal=data_portal,\n script=\"\"\"\nfrom zipline.api import *\n\ndef initialize(context):\n model = slippage.VolumeShareSlippage(\n volume_limit=.3,\n price_impact=0.05\n )\n set_slippage(model)\n {0}\n\n context.count = 2\n context.incr = 0\n\ndef handle_data(context, data):\n if context.incr < context.count:\n # order small lots to be sure the\n # order will fill in a single transaction\n order(sid(0), 5000)\n record(price=data.current(sid(0), \"price\"))\n record(volume=data.current(sid(0), \"volume\"))\n record(incr=context.incr)\n context.incr += 1\n \"\"\".format(\n commission_line\n ),\n )\n results = test_algo.run()\n\n all_txns = [\n val for sublist in results[\"transactions\"].tolist() for val in sublist\n ]\n\n assert len(all_txns) == 67\n # all_orders are all the incremental versions of the\n # orders as each new fill comes in.\n all_orders = list(toolz.concat(results[\"orders\"]))\n\n if minimum_commission == 0:\n # for each incremental version of each order, the commission\n # should be its filled amount * 0.02\n for order_ in all_orders:\n assert (\n round(abs(order_[\"filled\"] * 0.02 - order_[\"commission\"]), 7)\n == 0\n )\n else:\n # the commission should be at least the min_trade_cost\n for order_ in all_orders:\n if order_[\"filled\"] > 0:\n assert (\n round(\n abs(\n max(order_[\"filled\"] * 0.02, minimum_commission)\n - order_[\"commission\"]\n ),\n 7,\n )\n == 0\n )\n else:\n assert 0 == order_[\"commission\"]\n finally:\n tempdir.cleanup()\n\n def test_incorrectly_set_futures_slippage_model(self):\n code = dedent(\n \"\"\"\n from zipline.api import set_slippage, slippage\n\n class MySlippage(slippage.FutureSlippageModel):\n def process_order(self, data, order):\n return data.current(order.asset, 'price'), order.amount\n\n def initialize(context):\n set_slippage(MySlippage())\n \"\"\"\n )\n test_algo = self.make_algo(script=code)\n with pytest.raises(IncompatibleSlippageModel):\n # Passing a futures slippage model as the first argument, which is\n # for setting equity models, should fail.\n test_algo.run()\n\n def test_algo_record_vars(self):\n test_algo = self.make_algo(script=record_variables)\n results = test_algo.run()\n\n for i in range(1, 252):\n assert results.iloc[i - 1][\"incr\"] == i\n\n def test_algo_record_nan(self):\n test_algo = self.make_algo(script=record_float_magic % \"nan\")\n results = test_algo.run()\n for i in range(1, 252):\n assert np.isnan(results.iloc[i - 1][\"data\"])\n\n def test_batch_market_order_matches_multiple_manual_orders(self):\n share_counts = pd.Series([50, 100])\n\n multi_blotter = RecordBatchBlotter()\n multi_test_algo = self.make_algo(\n script=dedent(\n \"\"\"\\\n from collections import OrderedDict\n from zipline.api import sid, order\n\n\n def initialize(context):\n context.assets = [sid(0), sid(3)]\n context.placed = False\n\n def handle_data(context, data):\n if not context.placed:\n it = zip(context.assets, {share_counts})\n for asset, shares in it:\n order(asset, shares)\n\n context.placed = True\n\n \"\"\"\n ).format(share_counts=list(share_counts)),\n blotter=multi_blotter,\n )\n multi_stats = multi_test_algo.run()\n assert not multi_blotter.order_batch_called\n\n batch_blotter = RecordBatchBlotter()\n batch_test_algo = self.make_algo(\n script=dedent(\n \"\"\"\\\n import pandas as pd\n\n from zipline.api import sid, batch_market_order\n\n\n def initialize(context):\n context.assets = [sid(0), sid(3)]\n context.placed = False\n\n def handle_data(context, data):\n if not context.placed:\n orders = batch_market_order(pd.Series(\n index=context.assets, data={share_counts}\n ))\n assert len(orders) == 2, \\\n \"len(orders) was %s but expected 2\" % len(orders)\n for o in orders:\n assert o is not None, \"An order is None\"\n\n context.placed = True\n\n \"\"\"\n ).format(share_counts=list(share_counts)),\n blotter=batch_blotter,\n )\n batch_stats = batch_test_algo.run()\n assert batch_blotter.order_batch_called\n\n for stats in (multi_stats, batch_stats):\n stats.orders = stats.orders.apply(\n lambda orders: [toolz.dissoc(o, \"id\") for o in orders]\n )\n stats.transactions = stats.transactions.apply(\n lambda txns: [toolz.dissoc(txn, \"order_id\") for txn in txns]\n )\n assert_equal(multi_stats.sort_index(axis=1), batch_stats.sort_index(axis=1))\n\n def test_batch_market_order_filters_null_orders(self):\n share_counts = [50, 0]\n\n batch_blotter = RecordBatchBlotter()\n batch_test_algo = self.make_algo(\n script=dedent(\n \"\"\"\\\n import pandas as pd\n\n from zipline.api import sid, batch_market_order\n\n def initialize(context):\n context.assets = [sid(0), sid(3)]\n context.placed = False\n\n def handle_data(context, data):\n if not context.placed:\n orders = batch_market_order(pd.Series(\n index=context.assets, data={share_counts}\n ))\n assert len(orders) == 1, \\\n \"len(orders) was %s but expected 1\" % len(orders)\n for o in orders:\n assert o is not None, \"An order is None\"\n\n context.placed = True\n\n \"\"\"\n ).format(share_counts=share_counts),\n blotter=batch_blotter,\n )\n batch_test_algo.run()\n assert batch_blotter.order_batch_called\n\n def test_order_dead_asset(self):\n # after asset 0 is dead\n params = SimulationParameters(\n start_session=pd.Timestamp(\"2007-01-03\", tz=\"UTC\"),\n end_session=pd.Timestamp(\"2007-01-05\", tz=\"UTC\"),\n trading_calendar=self.trading_calendar,\n )\n\n # order method shouldn't blow up\n self.run_algorithm(\n script=\"\"\"\nfrom zipline.api import order, sid\n\ndef initialize(context):\n pass\n\ndef handle_data(context, data):\n order(sid(0), 10)\n \"\"\",\n )\n\n # order_value and order_percent should blow up\n for order_str in [\"order_value\", \"order_percent\"]:\n test_algo = self.make_algo(\n script=\"\"\"\nfrom zipline.api import order_percent, order_value, sid\n\ndef initialize(context):\n pass\n\ndef handle_data(context, data):\n {0}(sid(0), 10)\n \"\"\".format(\n order_str\n ),\n sim_params=params,\n )\n\n with pytest.raises(CannotOrderDelistedAsset):\n test_algo.run()\n\n def test_portfolio_in_init(self):\n \"\"\"\n Test that accessing portfolio in init doesn't break.\n \"\"\"\n self.run_algorithm(script=access_portfolio_in_init)\n\n def test_account_in_init(self):\n \"\"\"\n Test that accessing account in init doesn't break.\n \"\"\"\n self.run_algorithm(script=access_account_in_init)\n\n def test_without_kwargs(self):\n \"\"\"\n Test that api methods on the data object can be called with positional\n arguments.\n \"\"\"\n params = SimulationParameters(\n start_session=pd.Timestamp(\"2006-01-10\", tz=\"UTC\"),\n end_session=pd.Timestamp(\"2006-01-11\", tz=\"UTC\"),\n trading_calendar=self.trading_calendar,\n )\n self.run_algorithm(sim_params=params, script=call_without_kwargs)\n\n def test_good_kwargs(self):\n \"\"\"\n Test that api methods on the data object can be called with keyword\n arguments.\n \"\"\"\n params = SimulationParameters(\n start_session=pd.Timestamp(\"2006-01-10\", tz=\"UTC\"),\n end_session=pd.Timestamp(\"2006-01-11\", tz=\"UTC\"),\n trading_calendar=self.trading_calendar,\n )\n self.run_algorithm(script=call_with_kwargs, sim_params=params)\n\n @parameterized.expand(\n [\n (\"history\", call_with_bad_kwargs_history),\n (\"current\", call_with_bad_kwargs_current),\n ]\n )\n def test_bad_kwargs(self, name, algo_text):\n \"\"\"\n Test that api methods on the data object called with bad kwargs return\n a meaningful TypeError that we create, rather than an unhelpful cython\n error\n \"\"\"\n algo = self.make_algo(script=algo_text)\n with pytest.raises(TypeError) as cm:\n algo.run()\n\n assert (\n \"%s() got an unexpected keyword argument 'blahblah'\" % name\n == cm.value.args[0]\n )\n\n @parameterized.expand(ARG_TYPE_TEST_CASES)\n def test_arg_types(self, name, inputs):\n\n keyword = name.split(\"__\")[1]\n\n algo = self.make_algo(script=inputs[0])\n with pytest.raises(TypeError) as cm:\n algo.run()\n\n expected = \"Expected %s argument to be of type %s%s\" % (\n keyword,\n \"or iterable of type \" if inputs[2] else \"\",\n inputs[1],\n )\n\n assert expected == cm.value.args[0]\n\n def test_empty_asset_list_to_history(self):\n params = SimulationParameters(\n start_session=pd.Timestamp(\"2006-01-10\", tz=\"UTC\"),\n end_session=pd.Timestamp(\"2006-01-11\", tz=\"UTC\"),\n trading_calendar=self.trading_calendar,\n )\n\n self.run_algorithm(\n script=dedent(\n \"\"\"\n def initialize(context):\n pass\n\n def handle_data(context, data):\n data.history([], \"price\", 5, '1d')\n \"\"\"\n ),\n sim_params=params,\n )\n\n @parameterized.expand(\n [\n (\"bad_kwargs\", call_with_bad_kwargs_get_open_orders),\n (\"good_kwargs\", call_with_good_kwargs_get_open_orders),\n (\"no_kwargs\", call_with_no_kwargs_get_open_orders),\n ]\n )\n def test_get_open_orders_kwargs(self, name, script):\n algo = self.make_algo(script=script)\n if name == \"bad_kwargs\":\n with pytest.raises(TypeError) as cm:\n algo.run()\n assert (\n \"Keyword argument `sid` is no longer \"\n \"supported for get_open_orders. Use `asset` \"\n \"instead.\" == cm.value.args[0]\n )\n else:\n algo.run()\n\n def test_empty_positions(self):\n \"\"\"\n Test that when we try context.portfolio.positions[stock] on a stock\n for which we have no positions, we return a Position with values 0\n (but more importantly, we don't crash) and don't save this Position\n to the user-facing dictionary PositionTracker._positions_store\n \"\"\"\n results = self.run_algorithm(script=empty_positions)\n num_positions = results.num_positions\n amounts = results.amounts\n assert all(num_positions == 0)\n assert all(amounts == 0)\n\n def test_schedule_function_time_rule_positionally_misplaced(self):\n \"\"\"\n Test that when a user specifies a time rule for the date_rule argument,\n but no rule in the time_rule argument\n (e.g. schedule_function(func, <time_rule>)), we assume that means\n assign a time rule but no date rule\n \"\"\"\n\n sim_params = factory.create_simulation_parameters(\n start=pd.Timestamp(\"2006-01-12\", tz=\"UTC\"),\n end=pd.Timestamp(\"2006-01-13\", tz=\"UTC\"),\n data_frequency=\"minute\",\n )\n\n algocode = dedent(\n \"\"\"\n from zipline.api import time_rules, schedule_function\n\n def do_at_open(context, data):\n context.done_at_open.append(context.get_datetime())\n\n def do_at_close(context, data):\n context.done_at_close.append(context.get_datetime())\n\n def initialize(context):\n context.done_at_open = []\n context.done_at_close = []\n schedule_function(do_at_open, time_rules.market_open())\n schedule_function(do_at_close, time_rules.market_close())\n\n def handle_data(algo, data):\n pass\n \"\"\"\n )\n\n with warnings.catch_warnings(record=True) as w:\n warnings.simplefilter(\"ignore\", PerformanceWarning)\n warnings.simplefilter(\n \"ignore\", RuntimeWarning\n ) # TODO: CHECK WHY DO I HAVE TO DO THAT (empyrical)\n\n algo = self.make_algo(script=algocode, sim_params=sim_params)\n algo.run()\n\n assert len(w) == 2\n\n for i, warning in enumerate(w):\n assert isinstance(warning.message, UserWarning)\n assert (\n warning.message.args[0]\n == \"Got a time rule for the second positional argument \"\n \"date_rule. You should use keyword argument \"\n \"time_rule= when calling schedule_function without \"\n \"specifying a date_rule\"\n )\n\n # The warnings come from line 13 and 14 in the algocode\n assert warning.lineno == 13 + i\n\n assert algo.done_at_open == [\n pd.Timestamp(\"2006-01-12 14:31:00\", tz=\"UTC\"),\n pd.Timestamp(\"2006-01-13 14:31:00\", tz=\"UTC\"),\n ]\n\n assert algo.done_at_close == [\n pd.Timestamp(\"2006-01-12 20:59:00\", tz=\"UTC\"),\n pd.Timestamp(\"2006-01-13 20:59:00\", tz=\"UTC\"),\n ]\n\n\nclass TestCapitalChanges(zf.WithMakeAlgo, zf.ZiplineTestCase):\n\n START_DATE = pd.Timestamp(\"2006-01-03\", tz=\"UTC\")\n END_DATE = pd.Timestamp(\"2006-01-09\", tz=\"UTC\")\n\n # XXX: This suite only has daily data for sid 0 and only has minutely data\n # for sid 1.\n sids = ASSET_FINDER_EQUITY_SIDS = (0, 1)\n DAILY_SID = 0\n MINUTELY_SID = 1\n\n # FIXME: Pass a benchmark source explicitly here.\n BENCHMARK_SID = None\n\n @classmethod\n def make_equity_minute_bar_data(cls):\n minutes = cls.trading_calendar.minutes_in_range(\n cls.START_DATE,\n cls.END_DATE,\n )\n closes = np.arange(100, 100 + len(minutes), 1)\n opens = closes\n highs = closes + 5\n lows = closes - 5\n\n frame = pd.DataFrame(\n index=minutes,\n data={\n \"open\": opens,\n \"high\": highs,\n \"low\": lows,\n \"close\": closes,\n \"volume\": 10000,\n },\n )\n\n yield cls.MINUTELY_SID, frame\n\n @classmethod\n def make_equity_daily_bar_data(cls, country_code, sids):\n days = cls.trading_calendar.sessions_in_range(\n cls.START_DATE,\n cls.END_DATE,\n )\n\n closes = np.arange(10.0, 10.0 + len(days), 1.0)\n opens = closes\n highs = closes + 0.5\n lows = closes - 0.5\n\n frame = pd.DataFrame(\n index=days,\n data={\n \"open\": opens,\n \"high\": highs,\n \"low\": lows,\n \"close\": closes,\n \"volume\": 10000,\n },\n )\n\n yield cls.DAILY_SID, frame\n\n @parameterized.expand([(\"target\", 151000.0), (\"delta\", 50000.0)])\n def test_capital_changes_daily_mode(self, change_type, value):\n capital_changes = {\n pd.Timestamp(\"2006-01-06\", tz=\"UTC\"): {\"type\": change_type, \"value\": value}\n }\n\n algocode = \"\"\"\nfrom zipline.api import set_slippage, set_commission, slippage, commission, \\\n schedule_function, time_rules, order, sid\n\ndef initialize(context):\n set_slippage(slippage.FixedSlippage(spread=0))\n set_commission(commission.PerShare(0, 0))\n schedule_function(order_stuff, time_rule=time_rules.market_open())\n\ndef order_stuff(context, data):\n order(sid(0), 1000)\n\"\"\"\n algo = self.make_algo(\n script=algocode,\n capital_changes=capital_changes,\n sim_params=SimulationParameters(\n start_session=self.START_DATE,\n end_session=self.END_DATE,\n trading_calendar=self.nyse_calendar,\n ),\n )\n\n # We call get_generator rather than `run()` here because we care about\n # the raw capital change packets.\n gen = algo.get_generator()\n results = list(gen)\n\n cumulative_perf = [\n r[\"cumulative_perf\"] for r in results if \"cumulative_perf\" in r\n ]\n daily_perf = [r[\"daily_perf\"] for r in results if \"daily_perf\" in r]\n capital_change_packets = [\n r[\"capital_change\"] for r in results if \"capital_change\" in r\n ]\n\n assert len(capital_change_packets) == 1\n assert capital_change_packets[0] == {\n \"date\": pd.Timestamp(\"2006-01-06\", tz=\"UTC\"),\n \"type\": \"cash\",\n \"target\": 151000.0 if change_type == \"target\" else None,\n \"delta\": 50000.0,\n }\n\n # 1/03: price = 10, place orders\n # 1/04: orders execute at price = 11, place orders\n # 1/05: orders execute at price = 12, place orders\n # 1/06: +50000 capital change,\n # orders execute at price = 13, place orders\n # 1/09: orders execute at price = 14, place orders\n\n expected_daily = {}\n\n expected_capital_changes = np.array([0.0, 0.0, 0.0, 50000.0, 0.0])\n\n # Day 1, no transaction. Day 2, we transact, but the price of our stock\n # does not change. Day 3, we start getting returns\n expected_daily[\"returns\"] = np.array(\n [\n 0.0,\n 0.0,\n # 1000 shares * gain of 1\n (100000.0 + 1000.0) / 100000.0 - 1.0,\n # 2000 shares * gain of 1, capital change of +50000\n (151000.0 + 2000.0) / 151000.0 - 1.0,\n # 3000 shares * gain of 1\n (153000.0 + 3000.0) / 153000.0 - 1.0,\n ]\n )\n\n expected_daily[\"pnl\"] = np.array(\n [\n 0.0,\n 0.0,\n 1000.00, # 1000 shares * gain of 1\n 2000.00, # 2000 shares * gain of 1\n 3000.00, # 3000 shares * gain of 1\n ]\n )\n\n expected_daily[\"capital_used\"] = np.array(\n [\n 0.0,\n -11000.0, # 1000 shares at price = 11\n -12000.0, # 1000 shares at price = 12\n -13000.0, # 1000 shares at price = 13\n -14000.0, # 1000 shares at price = 14\n ]\n )\n\n expected_daily[\"ending_cash\"] = (\n np.array([100000.0] * 5)\n + np.cumsum(expected_capital_changes)\n + np.cumsum(expected_daily[\"capital_used\"])\n )\n\n expected_daily[\"starting_cash\"] = (\n expected_daily[\"ending_cash\"] - expected_daily[\"capital_used\"]\n )\n\n expected_daily[\"starting_value\"] = np.array(\n [\n 0.0,\n 0.0,\n 11000.0, # 1000 shares at price = 11\n 24000.0, # 2000 shares at price = 12\n 39000.0, # 3000 shares at price = 13\n ]\n )\n\n expected_daily[\"ending_value\"] = (\n expected_daily[\"starting_value\"]\n + expected_daily[\"pnl\"]\n - expected_daily[\"capital_used\"]\n )\n\n expected_daily[\"portfolio_value\"] = (\n expected_daily[\"ending_value\"] + expected_daily[\"ending_cash\"]\n )\n\n stats = [\n \"returns\",\n \"pnl\",\n \"capital_used\",\n \"starting_cash\",\n \"ending_cash\",\n \"starting_value\",\n \"ending_value\",\n \"portfolio_value\",\n ]\n\n expected_cumulative = {\n \"returns\": np.cumprod(expected_daily[\"returns\"] + 1) - 1,\n \"pnl\": np.cumsum(expected_daily[\"pnl\"]),\n \"capital_used\": np.cumsum(expected_daily[\"capital_used\"]),\n \"starting_cash\": np.repeat(expected_daily[\"starting_cash\"][0:1], 5),\n \"ending_cash\": expected_daily[\"ending_cash\"],\n \"starting_value\": np.repeat(expected_daily[\"starting_value\"][0:1], 5),\n \"ending_value\": expected_daily[\"ending_value\"],\n \"portfolio_value\": expected_daily[\"portfolio_value\"],\n }\n\n for stat in stats:\n np.testing.assert_array_almost_equal(\n np.array([perf[stat] for perf in daily_perf]),\n expected_daily[stat],\n err_msg=\"daily \" + stat,\n )\n np.testing.assert_array_almost_equal(\n np.array([perf[stat] for perf in cumulative_perf]),\n expected_cumulative[stat],\n err_msg=\"cumulative \" + stat,\n )\n\n assert algo.capital_change_deltas == {\n pd.Timestamp(\"2006-01-06\", tz=\"UTC\"): 50000.0\n }\n\n @parameterized.expand(\n [\n (\"interday_target\", [(\"2006-01-04\", 2388.0)]),\n (\"interday_delta\", [(\"2006-01-04\", 1000.0)]),\n (\n \"intraday_target\",\n [(\"2006-01-04 17:00\", 2184.0), (\"2006-01-04 18:00\", 2804.0)],\n ),\n (\n \"intraday_delta\",\n [(\"2006-01-04 17:00\", 500.0), (\"2006-01-04 18:00\", 500.0)],\n ),\n ]\n )\n def test_capital_changes_minute_mode_daily_emission(self, change, values):\n change_loc, change_type = change.split(\"_\")\n\n sim_params = SimulationParameters(\n start_session=pd.Timestamp(\"2006-01-03\", tz=\"UTC\"),\n end_session=pd.Timestamp(\"2006-01-05\", tz=\"UTC\"),\n data_frequency=\"minute\",\n capital_base=1000.0,\n trading_calendar=self.nyse_calendar,\n )\n\n capital_changes = {\n pd.Timestamp(datestr, tz=\"UTC\"): {\"type\": change_type, \"value\": value}\n for datestr, value in values\n }\n\n algocode = \"\"\"\nfrom zipline.api import set_slippage, set_commission, slippage, commission, \\\n schedule_function, time_rules, order, sid\n\ndef initialize(context):\n set_slippage(slippage.FixedSlippage(spread=0))\n set_commission(commission.PerShare(0, 0))\n schedule_function(order_stuff, time_rule=time_rules.market_open())\n\ndef order_stuff(context, data):\n order(sid(1), 1)\n\"\"\"\n\n algo = self.make_algo(\n script=algocode, sim_params=sim_params, capital_changes=capital_changes\n )\n\n gen = algo.get_generator()\n results = list(gen)\n\n cumulative_perf = [\n r[\"cumulative_perf\"] for r in results if \"cumulative_perf\" in r\n ]\n daily_perf = [r[\"daily_perf\"] for r in results if \"daily_perf\" in r]\n capital_change_packets = [\n r[\"capital_change\"] for r in results if \"capital_change\" in r\n ]\n\n assert len(capital_change_packets) == len(capital_changes)\n expected = [\n {\n \"date\": pd.Timestamp(val[0], tz=\"UTC\"),\n \"type\": \"cash\",\n \"target\": val[1] if change_type == \"target\" else None,\n \"delta\": 1000.0 if len(values) == 1 else 500.0,\n }\n for val in values\n ]\n assert capital_change_packets == expected\n\n # 1/03: place orders at price = 100, execute at 101\n # 1/04: place orders at price = 490, execute at 491,\n # +500 capital change at 17:00 and 18:00 (intraday)\n # or +1000 at 00:00 (interday),\n # 1/05: place orders at price = 880, execute at 881\n\n expected_daily = {}\n\n expected_capital_changes = np.array([0.0, 1000.0, 0.0])\n\n if change_loc == \"intraday\":\n # Fills at 491, +500 capital change comes at 638 (17:00) and\n # 698 (18:00), ends day at 879\n day2_return = (1388.0 + 149.0 + 147.0) / 1388.0 * (\n 2184.0 + 60.0 + 60.0\n ) / 2184.0 * (2804.0 + 181.0 + 181.0) / 2804.0 - 1.0\n else:\n # Fills at 491, ends day at 879, capital change +1000\n day2_return = (2388.0 + 390.0 + 388.0) / 2388.0 - 1\n\n expected_daily[\"returns\"] = np.array(\n [\n # Fills at 101, ends day at 489\n (1000.0 + 489 - 101) / 1000.0 - 1.0,\n day2_return,\n # Fills at 881, ends day at 1269\n (3166.0 + 390.0 + 390.0 + 388.0) / 3166.0 - 1.0,\n ]\n )\n\n expected_daily[\"pnl\"] = np.array(\n [\n 388.0,\n 390.0 + 388.0,\n 390.0 + 390.0 + 388.0,\n ]\n )\n\n expected_daily[\"capital_used\"] = np.array([-101.0, -491.0, -881.0])\n\n expected_daily[\"ending_cash\"] = (\n np.array([1000.0] * 3)\n + np.cumsum(expected_capital_changes)\n + np.cumsum(expected_daily[\"capital_used\"])\n )\n\n expected_daily[\"starting_cash\"] = (\n expected_daily[\"ending_cash\"] - expected_daily[\"capital_used\"]\n )\n\n if change_loc == \"intraday\":\n # Capital changes come after day start\n expected_daily[\"starting_cash\"] -= expected_capital_changes\n\n expected_daily[\"starting_value\"] = np.array([0.0, 489.0, 879.0 * 2])\n\n expected_daily[\"ending_value\"] = (\n expected_daily[\"starting_value\"]\n + expected_daily[\"pnl\"]\n - expected_daily[\"capital_used\"]\n )\n\n expected_daily[\"portfolio_value\"] = (\n expected_daily[\"ending_value\"] + expected_daily[\"ending_cash\"]\n )\n\n stats = [\n \"returns\",\n \"pnl\",\n \"capital_used\",\n \"starting_cash\",\n \"ending_cash\",\n \"starting_value\",\n \"ending_value\",\n \"portfolio_value\",\n ]\n\n expected_cumulative = {\n \"returns\": np.cumprod(expected_daily[\"returns\"] + 1) - 1,\n \"pnl\": np.cumsum(expected_daily[\"pnl\"]),\n \"capital_used\": np.cumsum(expected_daily[\"capital_used\"]),\n \"starting_cash\": np.repeat(expected_daily[\"starting_cash\"][0:1], 3),\n \"ending_cash\": expected_daily[\"ending_cash\"],\n \"starting_value\": np.repeat(expected_daily[\"starting_value\"][0:1], 3),\n \"ending_value\": expected_daily[\"ending_value\"],\n \"portfolio_value\": expected_daily[\"portfolio_value\"],\n }\n\n for stat in stats:\n np.testing.assert_array_almost_equal(\n np.array([perf[stat] for perf in daily_perf]), expected_daily[stat]\n )\n np.testing.assert_array_almost_equal(\n np.array([perf[stat] for perf in cumulative_perf]),\n expected_cumulative[stat],\n )\n\n if change_loc == \"interday\":\n assert algo.capital_change_deltas == {\n pd.Timestamp(\"2006-01-04\", tz=\"UTC\"): 1000.0\n }\n else:\n assert algo.capital_change_deltas == {\n pd.Timestamp(\"2006-01-04 17:00\", tz=\"UTC\"): 500.0,\n pd.Timestamp(\"2006-01-04 18:00\", tz=\"UTC\"): 500.0,\n }\n\n @parameterized.expand(\n [\n (\"interday_target\", [(\"2006-01-04\", 2388.0)]),\n (\"interday_delta\", [(\"2006-01-04\", 1000.0)]),\n (\n \"intraday_target\",\n [(\"2006-01-04 17:00\", 2184.0), (\"2006-01-04 18:00\", 2804.0)],\n ),\n (\n \"intraday_delta\",\n [(\"2006-01-04 17:00\", 500.0), (\"2006-01-04 18:00\", 500.0)],\n ),\n ]\n )\n def test_capital_changes_minute_mode_minute_emission(self, change, values):\n change_loc, change_type = change.split(\"_\")\n\n sim_params = SimulationParameters(\n start_session=pd.Timestamp(\"2006-01-03\", tz=\"UTC\"),\n end_session=pd.Timestamp(\"2006-01-05\", tz=\"UTC\"),\n data_frequency=\"minute\",\n emission_rate=\"minute\",\n capital_base=1000.0,\n trading_calendar=self.nyse_calendar,\n )\n\n capital_changes = {\n pd.Timestamp(val[0], tz=\"UTC\"): {\"type\": change_type, \"value\": val[1]}\n for val in values\n }\n\n algocode = \"\"\"\nfrom zipline.api import set_slippage, set_commission, slippage, commission, \\\n schedule_function, time_rules, order, sid\n\ndef initialize(context):\n set_slippage(slippage.FixedSlippage(spread=0))\n set_commission(commission.PerShare(0, 0))\n schedule_function(order_stuff, time_rule=time_rules.market_open())\n\ndef order_stuff(context, data):\n order(sid(1), 1)\n\"\"\"\n\n algo = self.make_algo(\n script=algocode, sim_params=sim_params, capital_changes=capital_changes\n )\n\n gen = algo.get_generator()\n results = list(gen)\n\n cumulative_perf = [\n r[\"cumulative_perf\"] for r in results if \"cumulative_perf\" in r\n ]\n minute_perf = [r[\"minute_perf\"] for r in results if \"minute_perf\" in r]\n daily_perf = [r[\"daily_perf\"] for r in results if \"daily_perf\" in r]\n capital_change_packets = [\n r[\"capital_change\"] for r in results if \"capital_change\" in r\n ]\n\n assert len(capital_change_packets) == len(capital_changes)\n expected = [\n {\n \"date\": pd.Timestamp(val[0], tz=\"UTC\"),\n \"type\": \"cash\",\n \"target\": val[1] if change_type == \"target\" else None,\n \"delta\": 1000.0 if len(values) == 1 else 500.0,\n }\n for val in values\n ]\n assert capital_change_packets == expected\n\n # 1/03: place orders at price = 100, execute at 101\n # 1/04: place orders at price = 490, execute at 491,\n # +500 capital change at 17:00 and 18:00 (intraday)\n # or +1000 at 00:00 (interday),\n # 1/05: place orders at price = 880, execute at 881\n\n # Minute perfs are cumulative for the day\n expected_minute = {}\n\n capital_changes_after_start = np.array([0.0] * 1170)\n if change_loc == \"intraday\":\n capital_changes_after_start[539:599] = 500.0\n capital_changes_after_start[599:780] = 1000.0\n\n expected_minute[\"pnl\"] = np.array([0.0] * 1170)\n expected_minute[\"pnl\"][:2] = 0.0\n expected_minute[\"pnl\"][2:392] = 1.0\n expected_minute[\"pnl\"][392:782] = 2.0\n expected_minute[\"pnl\"][782:] = 3.0\n for start, end in ((0, 390), (390, 780), (780, 1170)):\n expected_minute[\"pnl\"][start:end] = np.cumsum(\n expected_minute[\"pnl\"][start:end]\n )\n\n expected_minute[\"capital_used\"] = np.concatenate(\n (\n [0.0] * 1,\n [-101.0] * 389,\n [0.0] * 1,\n [-491.0] * 389,\n [0.0] * 1,\n [-881.0] * 389,\n )\n )\n\n # +1000 capital changes comes before the day start if interday\n day2adj = 0.0 if change_loc == \"intraday\" else 1000.0\n\n expected_minute[\"starting_cash\"] = np.concatenate(\n (\n [1000.0] * 390,\n # 101 spent on 1/03\n [1000.0 - 101.0 + day2adj] * 390,\n # 101 spent on 1/03, 491 on 1/04, +1000 capital change on 1/04\n [1000.0 - 101.0 - 491.0 + 1000] * 390,\n )\n )\n\n expected_minute[\"ending_cash\"] = (\n expected_minute[\"starting_cash\"]\n + expected_minute[\"capital_used\"]\n + capital_changes_after_start\n )\n\n expected_minute[\"starting_value\"] = np.concatenate(\n ([0.0] * 390, [489.0] * 390, [879.0 * 2] * 390)\n )\n\n expected_minute[\"ending_value\"] = (\n expected_minute[\"starting_value\"]\n + expected_minute[\"pnl\"]\n - expected_minute[\"capital_used\"]\n )\n\n expected_minute[\"portfolio_value\"] = (\n expected_minute[\"ending_value\"] + expected_minute[\"ending_cash\"]\n )\n\n expected_minute[\"returns\"] = expected_minute[\"pnl\"] / (\n expected_minute[\"starting_value\"] + expected_minute[\"starting_cash\"]\n )\n\n # If the change is interday, we can just calculate the returns from\n # the pnl, starting_value and starting_cash. If the change is intraday,\n # the returns after the change have to be calculated from two\n # subperiods\n if change_loc == \"intraday\":\n # The last packet (at 1/04 16:59) before the first capital change\n prev_subperiod_return = expected_minute[\"returns\"][538]\n\n # From 1/04 17:00 to 17:59\n cur_subperiod_pnl = (\n expected_minute[\"pnl\"][539:599] - expected_minute[\"pnl\"][538]\n )\n cur_subperiod_starting_value = np.array(\n [expected_minute[\"ending_value\"][538]] * 60\n )\n cur_subperiod_starting_cash = np.array(\n [expected_minute[\"ending_cash\"][538] + 500] * 60\n )\n\n cur_subperiod_returns = cur_subperiod_pnl / (\n cur_subperiod_starting_value + cur_subperiod_starting_cash\n )\n expected_minute[\"returns\"][539:599] = (cur_subperiod_returns + 1.0) * (\n prev_subperiod_return + 1.0\n ) - 1.0\n\n # The last packet (at 1/04 17:59) before the second capital change\n prev_subperiod_return = expected_minute[\"returns\"][598]\n\n # From 1/04 18:00 to 21:00\n cur_subperiod_pnl = (\n expected_minute[\"pnl\"][599:780] - expected_minute[\"pnl\"][598]\n )\n cur_subperiod_starting_value = np.array(\n [expected_minute[\"ending_value\"][598]] * 181\n )\n cur_subperiod_starting_cash = np.array(\n [expected_minute[\"ending_cash\"][598] + 500] * 181\n )\n\n cur_subperiod_returns = cur_subperiod_pnl / (\n cur_subperiod_starting_value + cur_subperiod_starting_cash\n )\n expected_minute[\"returns\"][599:780] = (cur_subperiod_returns + 1.0) * (\n prev_subperiod_return + 1.0\n ) - 1.0\n\n # The last minute packet of each day\n expected_daily = {\n k: np.array([v[389], v[779], v[1169]]) for k, v in expected_minute.items()\n }\n\n stats = [\n \"pnl\",\n \"capital_used\",\n \"starting_cash\",\n \"ending_cash\",\n \"starting_value\",\n \"ending_value\",\n \"portfolio_value\",\n \"returns\",\n ]\n\n expected_cumulative = deepcopy(expected_minute)\n\n # \"Add\" daily return from 1/03 to minute returns on 1/04 and 1/05\n # \"Add\" daily return from 1/04 to minute returns on 1/05\n expected_cumulative[\"returns\"][390:] = (\n expected_cumulative[\"returns\"][390:] + 1\n ) * (expected_daily[\"returns\"][0] + 1) - 1\n expected_cumulative[\"returns\"][780:] = (\n expected_cumulative[\"returns\"][780:] + 1\n ) * (expected_daily[\"returns\"][1] + 1) - 1\n\n # Add daily pnl/capital_used from 1/03 to 1/04 and 1/05\n # Add daily pnl/capital_used from 1/04 to 1/05\n expected_cumulative[\"pnl\"][390:] += expected_daily[\"pnl\"][0]\n expected_cumulative[\"pnl\"][780:] += expected_daily[\"pnl\"][1]\n expected_cumulative[\"capital_used\"][390:] += expected_daily[\"capital_used\"][0]\n expected_cumulative[\"capital_used\"][780:] += expected_daily[\"capital_used\"][1]\n\n # starting_cash, starting_value are same as those of the first daily\n # packet\n expected_cumulative[\"starting_cash\"] = np.repeat(\n expected_daily[\"starting_cash\"][0:1], 1170\n )\n expected_cumulative[\"starting_value\"] = np.repeat(\n expected_daily[\"starting_value\"][0:1], 1170\n )\n\n # extra cumulative packet per day from the daily packet\n for stat in stats:\n for i in (390, 781, 1172):\n expected_cumulative[stat] = np.insert(\n expected_cumulative[stat], i, expected_cumulative[stat][i - 1]\n )\n\n for stat in stats:\n np.testing.assert_array_almost_equal(\n np.array([perf[stat] for perf in minute_perf]), expected_minute[stat]\n )\n np.testing.assert_array_almost_equal(\n np.array([perf[stat] for perf in daily_perf]), expected_daily[stat]\n )\n np.testing.assert_array_almost_equal(\n np.array([perf[stat] for perf in cumulative_perf]),\n expected_cumulative[stat],\n )\n\n if change_loc == \"interday\":\n assert algo.capital_change_deltas == {\n pd.Timestamp(\"2006-01-04\", tz=\"UTC\"): 1000.0\n }\n else:\n assert algo.capital_change_deltas == {\n pd.Timestamp(\"2006-01-04 17:00\", tz=\"UTC\"): 500.0,\n pd.Timestamp(\"2006-01-04 18:00\", tz=\"UTC\"): 500.0,\n }\n\n\nclass TestGetDatetime(zf.WithMakeAlgo, zf.ZiplineTestCase):\n SIM_PARAMS_DATA_FREQUENCY = \"minute\"\n START_DATE = to_utc(\"2014-01-02 9:31\")\n END_DATE = to_utc(\"2014-01-03 9:31\")\n\n ASSET_FINDER_EQUITY_SIDS = 0, 1\n\n # FIXME: Pass a benchmark source explicitly here.\n BENCHMARK_SID = None\n\n @parameterized.expand(\n [\n (\n \"default\",\n None,\n ),\n (\n \"utc\",\n \"UTC\",\n ),\n (\n \"us_east\",\n \"US/Eastern\",\n ),\n ]\n )\n def test_get_datetime(self, name, tz):\n algo = dedent(\n \"\"\"\n import pandas as pd\n from zipline.api import get_datetime\n\n def initialize(context):\n context.tz = {tz} or 'UTC'\n context.first_bar = True\n\n def handle_data(context, data):\n dt = get_datetime({tz})\n if dt.tz.zone != context.tz:\n raise ValueError(\"Mismatched Zone\")\n\n if context.first_bar:\n if dt.tz_convert(\"US/Eastern\").hour != 9:\n raise ValueError(\"Mismatched Hour\")\n elif dt.tz_convert(\"US/Eastern\").minute != 31:\n raise ValueError(\"Mismatched Minute\")\n\n context.first_bar = False\n \"\"\".format(\n tz=repr(tz)\n )\n )\n\n algo = self.make_algo(script=algo)\n algo.run()\n assert not algo.first_bar\n\n\nclass TestTradingControls(zf.WithMakeAlgo, zf.ZiplineTestCase):\n START_DATE = pd.Timestamp(\"2006-01-03\", tz=\"utc\")\n END_DATE = pd.Timestamp(\"2006-01-06\", tz=\"utc\")\n\n sid = 133\n sids = ASSET_FINDER_EQUITY_SIDS = 133, 134\n\n SIM_PARAMS_DATA_FREQUENCY = \"daily\"\n DATA_PORTAL_USE_MINUTE_DATA = True\n\n @classmethod\n def init_class_fixtures(cls):\n super(TestTradingControls, cls).init_class_fixtures()\n cls.asset = cls.asset_finder.retrieve_asset(cls.sid)\n cls.another_asset = cls.asset_finder.retrieve_asset(134)\n\n def _check_algo(self, algo, expected_order_count, expected_exc):\n\n with pytest.raises(expected_exc) if expected_exc else nop_context:\n algo.run()\n assert algo.order_count == expected_order_count\n\n def check_algo_succeeds(self, algo, order_count=4):\n # Default for order_count assumes one order per handle_data call.\n self._check_algo(algo, order_count, None)\n\n def check_algo_fails(self, algo, order_count):\n self._check_algo(algo, order_count, TradingControlViolation)\n\n def test_set_max_position_size(self):\n def initialize(self, asset, max_shares, max_notional):\n self.set_slippage(FixedSlippage())\n self.order_count = 0\n self.set_max_position_size(\n asset=asset, max_shares=max_shares, max_notional=max_notional\n )\n\n # Buy one share four times. Should be fine.\n def handle_data(algo, data):\n algo.order(algo.sid(self.sid), 1)\n algo.order_count += 1\n\n algo = self.make_algo(\n asset=self.asset,\n max_shares=10,\n max_notional=500.0,\n initialize=initialize,\n handle_data=handle_data,\n )\n self.check_algo_succeeds(algo)\n\n # Buy three shares four times. Should bail on the fourth before it's\n # placed.\n def handle_data(algo, data):\n algo.order(algo.sid(self.sid), 3)\n algo.order_count += 1\n\n algo = self.make_algo(\n asset=self.asset,\n max_shares=10,\n max_notional=500.0,\n initialize=initialize,\n handle_data=handle_data,\n )\n self.check_algo_fails(algo, 3)\n\n # Buy three shares four times. Should bail due to max_notional on the\n # third attempt.\n def handle_data(algo, data):\n algo.order(algo.sid(self.sid), 3)\n algo.order_count += 1\n\n algo = self.make_algo(\n asset=self.asset,\n max_shares=10,\n max_notional=67.0,\n initialize=initialize,\n handle_data=handle_data,\n )\n self.check_algo_fails(algo, 2)\n\n # Set the trading control to a different sid, then BUY ALL THE THINGS!.\n # Should continue normally.\n def handle_data(algo, data):\n algo.order(algo.sid(self.sid), 10000)\n algo.order_count += 1\n\n algo = self.make_algo(\n asset=self.another_asset,\n max_shares=10,\n max_notional=67.0,\n initialize=initialize,\n handle_data=handle_data,\n )\n self.check_algo_succeeds(algo)\n\n # Set the trading control sid to None, then BUY ALL THE THINGS!. Should\n # fail because setting sid to None makes the control apply to all sids.\n def handle_data(algo, data):\n algo.order(algo.sid(self.sid), 10000)\n algo.order_count += 1\n\n algo = self.make_algo(\n max_shares=10,\n max_notional=61.0,\n asset=None,\n initialize=initialize,\n handle_data=handle_data,\n )\n\n self.check_algo_fails(algo, 0)\n\n def test_set_asset_restrictions(self):\n def initialize(algo, sid, restrictions, on_error):\n algo.order_count = 0\n algo.set_asset_restrictions(restrictions, on_error)\n\n def handle_data(algo, data):\n algo.could_trade = data.can_trade(algo.sid(self.sid))\n algo.order(algo.sid(self.sid), 100)\n algo.order_count += 1\n\n # Set HistoricalRestrictions for one sid for the entire simulation,\n # and fail.\n rlm = HistoricalRestrictions(\n [\n Restriction(\n self.sid, self.sim_params.start_session, RESTRICTION_STATES.FROZEN\n )\n ]\n )\n algo = self.make_algo(\n sid=self.sid,\n restrictions=rlm,\n on_error=\"fail\",\n initialize=initialize,\n handle_data=handle_data,\n )\n self.check_algo_fails(algo, 0)\n assert not algo.could_trade\n\n # Set StaticRestrictions for one sid and fail.\n rlm = StaticRestrictions([self.sid])\n algo = self.make_algo(\n sid=self.sid,\n restrictions=rlm,\n on_error=\"fail\",\n initialize=initialize,\n handle_data=handle_data,\n )\n\n self.check_algo_fails(algo, 0)\n assert not algo.could_trade\n\n # just log an error on the violation if we choose not to fail.\n algo = self.make_algo(\n sid=self.sid,\n restrictions=rlm,\n on_error=\"log\",\n initialize=initialize,\n handle_data=handle_data,\n )\n with make_test_handler(self) as log_catcher:\n self.check_algo_succeeds(algo)\n logs = [r.message for r in log_catcher.records]\n assert (\n \"Order for 100 shares of Equity(133 [A]) at \"\n \"2006-01-03 21:00:00+00:00 violates trading constraint \"\n \"RestrictedListOrder({})\" in logs\n )\n assert not algo.could_trade\n\n # set the restricted list to exclude the sid, and succeed\n rlm = HistoricalRestrictions(\n [\n Restriction(\n sid, self.sim_params.start_session, RESTRICTION_STATES.FROZEN\n )\n for sid in [134, 135, 136]\n ]\n )\n algo = self.make_algo(\n sid=self.sid,\n restrictions=rlm,\n on_error=\"fail\",\n initialize=initialize,\n handle_data=handle_data,\n )\n self.check_algo_succeeds(algo)\n assert algo.could_trade\n\n @parameterized.expand(\n [(\"order_first_restricted_sid\", 0), (\"order_second_restricted_sid\", 1)]\n )\n def test_set_multiple_asset_restrictions(self, name, to_order_idx):\n def initialize(algo, restrictions1, restrictions2, on_error):\n algo.order_count = 0\n algo.set_asset_restrictions(restrictions1, on_error)\n algo.set_asset_restrictions(restrictions2, on_error)\n\n def handle_data(algo, data):\n algo.could_trade1 = data.can_trade(algo.sid(self.sids[0]))\n algo.could_trade2 = data.can_trade(algo.sid(self.sids[1]))\n algo.order(algo.sid(self.sids[to_order_idx]), 100)\n algo.order_count += 1\n\n rl1 = StaticRestrictions([self.sids[0]])\n rl2 = StaticRestrictions([self.sids[1]])\n algo = self.make_algo(\n restrictions1=rl1,\n restrictions2=rl2,\n initialize=initialize,\n handle_data=handle_data,\n on_error=\"fail\",\n )\n self.check_algo_fails(algo, 0)\n assert not algo.could_trade1\n assert not algo.could_trade2\n\n def test_set_do_not_order_list(self):\n def initialize(self, restricted_list):\n self.order_count = 0\n # self.set_do_not_order_list(restricted_list, on_error=\"fail\")\n self.set_asset_restrictions(\n StaticRestrictions(restricted_list), on_error=\"fail\"\n )\n\n def handle_data(algo, data):\n algo.could_trade = data.can_trade(algo.sid(self.sid))\n algo.order(algo.sid(self.sid), 100)\n algo.order_count += 1\n\n rlm = [self.sid]\n algo = self.make_algo(\n restricted_list=rlm,\n initialize=initialize,\n handle_data=handle_data,\n )\n\n self.check_algo_fails(algo, 0)\n assert not algo.could_trade\n\n def test_set_max_order_size(self):\n def initialize(algo, asset, max_shares, max_notional):\n algo.order_count = 0\n algo.set_max_order_size(\n asset=asset, max_shares=max_shares, max_notional=max_notional\n )\n\n # Buy one share.\n def handle_data(algo, data):\n algo.order(algo.sid(self.sid), 1)\n algo.order_count += 1\n\n algo = self.make_algo(\n initialize=initialize,\n handle_data=handle_data,\n asset=self.asset,\n max_shares=10,\n max_notional=500.0,\n )\n self.check_algo_succeeds(algo)\n\n # Buy 1, then 2, then 3, then 4 shares. Bail on the last attempt\n # because we exceed shares.\n def handle_data(algo, data):\n algo.order(algo.sid(self.sid), algo.order_count + 1)\n algo.order_count += 1\n\n algo = self.make_algo(\n initialize=initialize,\n handle_data=handle_data,\n asset=self.asset,\n max_shares=3,\n max_notional=500.0,\n )\n self.check_algo_fails(algo, 3)\n\n # Buy 1, then 2, then 3, then 4 shares. Bail on the last attempt\n # because we exceed notional.\n def handle_data(algo, data):\n algo.order(algo.sid(self.sid), algo.order_count + 1)\n algo.order_count += 1\n\n algo = self.make_algo(\n initialize=initialize,\n handle_data=handle_data,\n asset=self.asset,\n max_shares=10,\n max_notional=40.0,\n )\n self.check_algo_fails(algo, 3)\n\n # Set the trading control to a different sid, then BUY ALL THE THINGS!.\n # Should continue normally.\n def handle_data(algo, data):\n algo.order(algo.sid(self.sid), 10000)\n algo.order_count += 1\n\n algo = self.make_algo(\n initialize=initialize,\n handle_data=handle_data,\n asset=self.another_asset,\n max_shares=1,\n max_notional=1.0,\n )\n self.check_algo_succeeds(algo)\n\n # Set the trading control sid to None, then BUY ALL THE THINGS!.\n # Should fail because not specifying a sid makes the trading control\n # apply to all sids.\n def handle_data(algo, data):\n algo.order(algo.sid(self.sid), 10000)\n algo.order_count += 1\n\n algo = self.make_algo(\n initialize=initialize,\n handle_data=handle_data,\n asset=None,\n max_shares=1,\n max_notional=1.0,\n )\n self.check_algo_fails(algo, 0)\n\n def test_set_max_order_count(self):\n def initialize(algo, count):\n algo.order_count = 0\n algo.set_max_order_count(count)\n\n def handle_data(algo, data):\n for i in range(5):\n algo.order(self.asset, 1)\n algo.order_count += 1\n\n algo = self.make_algo(\n count=3,\n initialize=initialize,\n handle_data=handle_data,\n )\n with pytest.raises(TradingControlViolation):\n algo.run()\n\n assert algo.order_count == 3\n\n def test_set_max_order_count_minutely(self):\n sim_params = self.make_simparams(data_frequency=\"minute\")\n\n def initialize(algo, max_orders_per_day):\n algo.minute_count = 0\n algo.order_count = 0\n algo.set_max_order_count(max_orders_per_day)\n\n # Order 5 times twice in a single day, and set a max order count of\n # 9. The last order of the second batch should fail.\n def handle_data(algo, data):\n if algo.minute_count == 0 or algo.minute_count == 100:\n for i in range(5):\n algo.order(self.asset, 1)\n algo.order_count += 1\n\n algo.minute_count += 1\n\n algo = self.make_algo(\n initialize=initialize,\n handle_data=handle_data,\n max_orders_per_day=9,\n sim_params=sim_params,\n )\n\n with pytest.raises(TradingControlViolation):\n algo.run()\n\n assert algo.order_count == 9\n\n # Set a limit of 5 orders per day, and order 5 times in the first\n # minute of each day. This should succeed because the counter gets\n # reset each day.\n def handle_data(algo, data):\n if (algo.minute_count % 390) == 0:\n for i in range(5):\n algo.order(self.asset, 1)\n algo.order_count += 1\n\n algo.minute_count += 1\n\n algo = self.make_algo(\n initialize=initialize,\n handle_data=handle_data,\n max_orders_per_day=5,\n sim_params=sim_params,\n )\n algo.run()\n\n # 5 orders per day times 4 days.\n assert algo.order_count == 20\n\n def test_long_only(self):\n def initialize(algo):\n algo.order_count = 0\n algo.set_long_only()\n\n # Sell immediately -> fail immediately.\n def handle_data(algo, data):\n algo.order(algo.sid(self.sid), -1)\n algo.order_count += 1\n\n algo = self.make_algo(initialize=initialize, handle_data=handle_data)\n self.check_algo_fails(algo, 0)\n\n # Buy on even days, sell on odd days. Never takes a short position, so\n # should succeed.\n def handle_data(algo, data):\n if (algo.order_count % 2) == 0:\n algo.order(algo.sid(self.sid), 1)\n else:\n algo.order(algo.sid(self.sid), -1)\n algo.order_count += 1\n\n algo = self.make_algo(initialize=initialize, handle_data=handle_data)\n self.check_algo_succeeds(algo)\n\n # Buy on first three days, then sell off holdings. Should succeed.\n def handle_data(algo, data):\n amounts = [1, 1, 1, -3]\n algo.order(algo.sid(self.sid), amounts[algo.order_count])\n algo.order_count += 1\n\n algo = self.make_algo(initialize=initialize, handle_data=handle_data)\n self.check_algo_succeeds(algo)\n\n # Buy on first three days, then sell off holdings plus an extra share.\n # Should fail on the last sale.\n def handle_data(algo, data):\n amounts = [1, 1, 1, -4]\n algo.order(algo.sid(self.sid), amounts[algo.order_count])\n algo.order_count += 1\n\n algo = self.make_algo(initialize=initialize, handle_data=handle_data)\n self.check_algo_fails(algo, 3)\n\n def test_register_post_init(self):\n def initialize(algo):\n algo.initialized = True\n\n def handle_data(algo, data):\n with pytest.raises(RegisterTradingControlPostInit):\n algo.set_max_position_size(self.sid, 1, 1)\n with pytest.raises(RegisterTradingControlPostInit):\n algo.set_max_order_size(self.sid, 1, 1)\n with pytest.raises(RegisterTradingControlPostInit):\n algo.set_max_order_count(1)\n with pytest.raises(RegisterTradingControlPostInit):\n algo.set_long_only()\n\n self.run_algorithm(initialize=initialize, handle_data=handle_data)\n\n\nclass TestAssetDateBounds(zf.WithMakeAlgo, zf.ZiplineTestCase):\n\n START_DATE = pd.Timestamp(\"2014-01-02\", tz=\"UTC\")\n END_DATE = pd.Timestamp(\"2014-01-03\", tz=\"UTC\")\n SIM_PARAMS_START_DATE = END_DATE # Only run for one day.\n\n SIM_PARAMS_DATA_FREQUENCY = \"daily\"\n DATA_PORTAL_USE_MINUTE_DATA = False\n\n BENCHMARK_SID = 3\n\n @classmethod\n def make_equity_info(cls):\n T = partial(pd.Timestamp, tz=\"UTC\")\n return pd.DataFrame.from_records(\n [\n {\n \"sid\": 1,\n \"symbol\": \"OLD\",\n \"start_date\": T(\"1990\"),\n \"end_date\": T(\"1991\"),\n \"exchange\": \"TEST\",\n },\n {\n \"sid\": 2,\n \"symbol\": \"NEW\",\n \"start_date\": T(\"2017\"),\n \"end_date\": T(\"2018\"),\n \"exchange\": \"TEST\",\n },\n {\n \"sid\": 3,\n \"symbol\": \"GOOD\",\n \"start_date\": cls.START_DATE,\n \"end_date\": cls.END_DATE,\n \"exchange\": \"TEST\",\n },\n ]\n )\n\n def test_asset_date_bounds(self):\n def initialize(algo):\n algo.ran = False\n algo.register_trading_control(AssetDateBounds(on_error=\"fail\"))\n\n def handle_data(algo, data):\n # This should work because sid 3 is valid during the algo lifetime.\n algo.order(algo.sid(3), 1)\n\n # Sid already expired.\n with pytest.raises(TradingControlViolation):\n algo.order(algo.sid(1), 1)\n\n # Sid doesn't exist yet.\n with pytest.raises(TradingControlViolation):\n algo.order(algo.sid(2), 1)\n\n algo.ran = True\n\n algo = self.make_algo(initialize=initialize, handle_data=handle_data)\n algo.run()\n assert algo.ran\n\n\nclass TestAccountControls(zf.WithMakeAlgo, zf.ZiplineTestCase):\n START_DATE = pd.Timestamp(\"2006-01-03\", tz=\"utc\")\n END_DATE = pd.Timestamp(\"2006-01-06\", tz=\"utc\")\n\n (sidint,) = ASSET_FINDER_EQUITY_SIDS = (133,)\n BENCHMARK_SID = None\n SIM_PARAMS_DATA_FREQUENCY = \"daily\"\n DATA_PORTAL_USE_MINUTE_DATA = False\n\n @classmethod\n def make_equity_daily_bar_data(cls, country_code, sids):\n frame = pd.DataFrame(\n data={\n \"close\": [10.0, 10.0, 11.0, 11.0],\n \"open\": [10.0, 10.0, 11.0, 11.0],\n \"low\": [9.5, 9.5, 10.45, 10.45],\n \"high\": [10.5, 10.5, 11.55, 11.55],\n \"volume\": [100, 100, 100, 300],\n },\n index=cls.equity_daily_bar_days,\n )\n yield cls.sidint, frame\n\n def _check_algo(self, algo, expected_exc):\n with pytest.raises(expected_exc) if expected_exc else nop_context:\n algo.run()\n\n def check_algo_succeeds(self, algo):\n # Default for order_count assumes one order per handle_data call.\n self._check_algo(algo, None)\n\n def check_algo_fails(self, algo):\n self._check_algo(algo, AccountControlViolation)\n\n def test_set_max_leverage(self):\n def initialize(algo, max_leverage):\n algo.set_max_leverage(max_leverage=max_leverage)\n\n def handle_data(algo, data):\n algo.order(algo.sid(self.sidint), 1)\n algo.record(latest_time=algo.get_datetime())\n\n # Set max leverage to 0 so buying one share fails.\n algo = self.make_algo(\n initialize=initialize,\n handle_data=handle_data,\n max_leverage=0,\n )\n self.check_algo_fails(algo)\n assert algo.recorded_vars[\"latest_time\"] == pd.Timestamp(\n \"2006-01-04 21:00:00\", tz=\"UTC\"\n )\n\n # Set max leverage to 1 so buying one share passes\n def handle_data(algo, data):\n algo.order(algo.sid(self.sidint), 1)\n\n algo = self.make_algo(\n initialize=initialize,\n handle_data=handle_data,\n max_leverage=1,\n )\n self.check_algo_succeeds(algo)\n\n def test_set_min_leverage(self):\n def initialize(algo, min_leverage, grace_period):\n algo.set_min_leverage(min_leverage=min_leverage, grace_period=grace_period)\n\n def handle_data(algo, data):\n algo.order_target_percent(algo.sid(self.sidint), 0.5)\n algo.record(latest_time=algo.get_datetime())\n\n # Helper for not having to pass init/handle_data at each callsite.\n def make_algo(min_leverage, grace_period):\n return self.make_algo(\n initialize=initialize,\n handle_data=handle_data,\n min_leverage=min_leverage,\n grace_period=grace_period,\n )\n\n # Set min leverage to 1.\n # The algorithm will succeed because it doesn't run for more\n # than 10 days.\n offset = pd.Timedelta(\"10 days\")\n algo = make_algo(min_leverage=1, grace_period=offset)\n self.check_algo_succeeds(algo)\n\n # The algorithm will fail because it doesn't reach a min leverage of 1\n # after 1 day.\n offset = pd.Timedelta(\"1 days\")\n algo = make_algo(min_leverage=1, grace_period=offset)\n self.check_algo_fails(algo)\n assert algo.recorded_vars[\"latest_time\"] == pd.Timestamp(\n \"2006-01-04 21:00:00\", tz=\"UTC\"\n )\n\n # Increase the offset to 2 days, and the algorithm fails a day later\n offset = pd.Timedelta(\"2 days\")\n algo = make_algo(min_leverage=1, grace_period=offset)\n self.check_algo_fails(algo)\n assert algo.recorded_vars[\"latest_time\"] == pd.Timestamp(\n \"2006-01-05 21:00:00\", tz=\"UTC\"\n )\n\n # Set the min_leverage to .0001 and the algorithm succeeds.\n algo = make_algo(min_leverage=0.0001, grace_period=offset)\n self.check_algo_succeeds(algo)\n\n\nclass TestFuturesAlgo(zf.WithMakeAlgo, zf.ZiplineTestCase):\n START_DATE = pd.Timestamp(\"2016-01-06\", tz=\"utc\")\n END_DATE = pd.Timestamp(\"2016-01-07\", tz=\"utc\")\n FUTURE_MINUTE_BAR_START_DATE = pd.Timestamp(\"2016-01-05\", tz=\"UTC\")\n\n SIM_PARAMS_DATA_FREQUENCY = \"minute\"\n\n TRADING_CALENDAR_STRS = (\"us_futures\",)\n TRADING_CALENDAR_PRIMARY_CAL = \"us_futures\"\n BENCHMARK_SID = None\n\n @classmethod\n def make_futures_info(cls):\n return pd.DataFrame.from_dict(\n {\n 1: {\n \"symbol\": \"CLG16\",\n \"root_symbol\": \"CL\",\n \"start_date\": pd.Timestamp(\"2015-12-01\", tz=\"UTC\"),\n \"notice_date\": pd.Timestamp(\"2016-01-20\", tz=\"UTC\"),\n \"expiration_date\": pd.Timestamp(\"2016-02-19\", tz=\"UTC\"),\n \"auto_close_date\": pd.Timestamp(\"2016-01-18\", tz=\"UTC\"),\n \"exchange\": \"TEST\",\n },\n },\n orient=\"index\",\n )\n\n def test_futures_history(self):\n algo_code = dedent(\n \"\"\"\n from datetime import time\n from zipline.api import (\n date_rules,\n get_datetime,\n schedule_function,\n sid,\n time_rules,\n )\n\n def initialize(context):\n context.history_values = []\n\n schedule_function(\n make_history_call,\n date_rules.every_day(),\n time_rules.market_open(),\n )\n\n schedule_function(\n check_market_close_time,\n date_rules.every_day(),\n time_rules.market_close(),\n )\n\n def make_history_call(context, data):\n # Ensure that the market open is 6:31am US/Eastern.\n open_time = get_datetime().tz_convert('US/Eastern').time()\n assert open_time == time(6, 31)\n context.history_values.append(\n data.history(sid(1), 'close', 5, '1m'),\n )\n\n def check_market_close_time(context, data):\n # Ensure that this function is called at 4:59pm US/Eastern.\n # By default, `market_close()` uses an offset of 1 minute.\n close_time = get_datetime().tz_convert('US/Eastern').time()\n assert close_time == time(16, 59)\n \"\"\"\n )\n\n algo = self.make_algo(\n script=algo_code,\n trading_calendar=get_calendar(\"us_futures\"),\n )\n algo.run()\n\n # Assert that we were able to retrieve history data for minutes outside\n # of the 6:31am US/Eastern to 5:00pm US/Eastern futures open times.\n np.testing.assert_array_equal(\n algo.history_values[0].index,\n pd.date_range(\n \"2016-01-06 6:27\",\n \"2016-01-06 6:31\",\n freq=\"min\",\n tz=\"US/Eastern\",\n ),\n )\n np.testing.assert_array_equal(\n algo.history_values[1].index,\n pd.date_range(\n \"2016-01-07 6:27\",\n \"2016-01-07 6:31\",\n freq=\"min\",\n tz=\"US/Eastern\",\n ),\n )\n\n # Expected prices here are given by the range values created by the\n # default `make_future_minute_bar_data` method.\n np.testing.assert_array_equal(\n algo.history_values[0].values,\n list(map(float, range(2196, 2201))),\n )\n np.testing.assert_array_equal(\n algo.history_values[1].values,\n list(map(float, range(3636, 3641))),\n )\n\n @staticmethod\n def algo_with_slippage(slippage_model):\n return dedent(\n \"\"\"\n from zipline.api import (\n commission,\n order,\n set_commission,\n set_slippage,\n sid,\n slippage,\n get_datetime,\n )\n\n def initialize(context):\n commission_model = commission.PerFutureTrade(0)\n set_commission(us_futures=commission_model)\n slippage_model = slippage.{model}\n set_slippage(us_futures=slippage_model)\n context.ordered = False\n\n def handle_data(context, data):\n if not context.ordered:\n order(sid(1), 10)\n context.ordered = True\n context.order_price = data.current(sid(1), 'price')\n \"\"\"\n ).format(model=slippage_model)\n\n def test_fixed_future_slippage(self):\n algo_code = self.algo_with_slippage(\"FixedSlippage(spread=0.10)\")\n algo = self.make_algo(\n script=algo_code,\n trading_calendar=get_calendar(\"us_futures\"),\n )\n results = algo.run()\n\n # Flatten the list of transactions.\n all_txns = [\n val for sublist in results[\"transactions\"].tolist() for val in sublist\n ]\n\n assert len(all_txns) == 1\n txn = all_txns[0]\n\n # Add 1 to the expected price because the order does not fill until the\n # bar after the price is recorded.\n expected_spread = 0.05\n expected_price = (algo.order_price + 1) + expected_spread\n\n assert txn[\"price\"] == expected_price\n assert results[\"orders\"][0][0][\"commission\"] == 0.0\n\n def test_volume_contract_slippage(self):\n algo_code = self.algo_with_slippage(\n \"VolumeShareSlippage(volume_limit=0.05, price_impact=0.1)\",\n )\n algo = self.make_algo(\n script=algo_code,\n trading_calendar=get_calendar(\"us_futures\"),\n )\n results = algo.run()\n\n # There should be no commissions.\n assert results[\"orders\"][0][0][\"commission\"] == 0.0\n\n # Flatten the list of transactions.\n all_txns = [\n val for sublist in results[\"transactions\"].tolist() for val in sublist\n ]\n\n # With a volume limit of 0.05, and a total volume of 100 contracts\n # traded per minute, we should require 2 transactions to order 10\n # contracts.\n assert len(all_txns) == 2\n\n for i, txn in enumerate(all_txns):\n # Add 1 to the order price because the order does not fill until\n # the bar after the price is recorded.\n order_price = algo.order_price + i + 1\n expected_impact = order_price * 0.1 * (0.05**2)\n expected_price = order_price + expected_impact\n assert txn[\"price\"] == expected_price\n\n\nclass TestAnalyzeAPIMethod(zf.WithMakeAlgo, zf.ZiplineTestCase):\n START_DATE = pd.Timestamp(\"2016-01-05\", tz=\"utc\")\n END_DATE = pd.Timestamp(\"2016-01-05\", tz=\"utc\")\n SIM_PARAMS_DATA_FREQUENCY = \"daily\"\n DATA_PORTAL_USE_MINUTE_DATA = False\n\n def test_analyze_called(self):\n self.perf_ref = None\n\n def initialize(context):\n pass\n\n def handle_data(context, data):\n pass\n\n def analyze(context, perf):\n self.perf_ref = perf\n\n algo = self.make_algo(\n initialize=initialize,\n handle_data=handle_data,\n analyze=analyze,\n )\n results = algo.run()\n assert results is self.perf_ref\n\n\nclass TestOrderCancelation(zf.WithMakeAlgo, zf.ZiplineTestCase):\n START_DATE = pd.Timestamp(\"2016-01-05\", tz=\"utc\")\n END_DATE = pd.Timestamp(\"2016-01-07\", tz=\"utc\")\n\n ASSET_FINDER_EQUITY_SIDS = (1,)\n ASSET_FINDER_EQUITY_SYMBOLS = (\"ASSET1\",)\n BENCHMARK_SID = None\n\n code = dedent(\n \"\"\"\n from zipline.api import (\n sid, order, set_slippage, slippage, VolumeShareSlippage,\n set_cancel_policy, cancel_policy, EODCancel\n )\n\n\n def initialize(context):\n set_slippage(\n slippage.VolumeShareSlippage(\n volume_limit=1,\n price_impact=0\n )\n )\n\n {0}\n context.ordered = False\n\n\n def handle_data(context, data):\n if not context.ordered:\n order(sid(1), {1})\n context.ordered = True\n \"\"\",\n )\n\n @classmethod\n def make_equity_minute_bar_data(cls):\n asset_minutes = cls.trading_calendar.minutes_for_sessions_in_range(\n cls.START_DATE,\n cls.END_DATE,\n )\n\n minutes_count = len(asset_minutes)\n minutes_arr = np.arange(1, 1 + minutes_count)\n\n # normal test data, but volume is pinned at 1 share per minute\n yield 1, pd.DataFrame(\n {\n \"open\": minutes_arr + 1,\n \"high\": minutes_arr + 2,\n \"low\": minutes_arr - 1,\n \"close\": minutes_arr,\n \"volume\": np.full(minutes_count, 1.0),\n },\n index=asset_minutes,\n )\n\n @classmethod\n def make_equity_daily_bar_data(cls, country_code, sids):\n yield 1, pd.DataFrame(\n {\n \"open\": np.full(3, 1, dtype=np.float64),\n \"high\": np.full(3, 1, dtype=np.float64),\n \"low\": np.full(3, 1, dtype=np.float64),\n \"close\": np.full(3, 1, dtype=np.float64),\n \"volume\": np.full(3, 1, dtype=np.float64),\n },\n index=cls.equity_daily_bar_days,\n )\n\n def prep_algo(\n self,\n cancelation_string,\n data_frequency=\"minute\",\n amount=1000,\n minute_emission=False,\n ):\n code = self.code.format(cancelation_string, amount)\n return self.make_algo(\n script=code,\n sim_params=self.make_simparams(\n data_frequency=data_frequency,\n emission_rate=\"minute\" if minute_emission else \"daily\",\n ),\n )\n\n @parameter_space(\n direction=[1, -1],\n minute_emission=[True, False],\n )\n def test_eod_order_cancel_minute(self, direction, minute_emission):\n \"\"\"\n Test that EOD order cancel works in minute mode for both shorts and\n longs, and both daily emission and minute emission\n \"\"\"\n # order 1000 shares of asset1. the volume is only 1 share per bar,\n # so the order should be cancelled at the end of the day.\n algo = self.prep_algo(\n \"set_cancel_policy(cancel_policy.EODCancel())\",\n amount=np.copysign(1000, direction),\n minute_emission=minute_emission,\n )\n\n log_catcher = TestHandler()\n with log_catcher:\n results = algo.run()\n\n for daily_positions in results.positions:\n assert 1 == len(daily_positions)\n assert np.copysign(389, direction) == daily_positions[0][\"amount\"]\n assert 1 == results.positions[0][0][\"sid\"]\n\n # should be an order on day1, but no more orders afterwards\n np.testing.assert_array_equal([1, 0, 0], list(map(len, results.orders)))\n\n # should be 389 txns on day 1, but no more afterwards\n np.testing.assert_array_equal(\n [389, 0, 0], list(map(len, results.transactions))\n )\n\n the_order = results.orders[0][0]\n\n assert ORDER_STATUS.CANCELLED == the_order[\"status\"]\n assert np.copysign(389, direction) == the_order[\"filled\"]\n\n warnings = [\n record for record in log_catcher.records if record.level == WARNING\n ]\n\n assert 1 == len(warnings)\n\n if direction == 1:\n assert (\n \"Your order for 1000 shares of ASSET1 has been partially \"\n \"filled. 389 shares were successfully purchased. \"\n \"611 shares were not filled by the end of day and \"\n \"were canceled.\" == str(warnings[0].message)\n )\n elif direction == -1:\n assert (\n \"Your order for -1000 shares of ASSET1 has been partially \"\n \"filled. 389 shares were successfully sold. \"\n \"611 shares were not filled by the end of day and \"\n \"were canceled.\" == str(warnings[0].message)\n )\n\n def test_default_cancelation_policy(self):\n algo = self.prep_algo(\"\")\n\n log_catcher = TestHandler()\n with log_catcher:\n results = algo.run()\n\n # order stays open throughout simulation\n np.testing.assert_array_equal([1, 1, 1], list(map(len, results.orders)))\n\n # one txn per minute. 389 the first day (since no order until the\n # end of the first minute). 390 on the second day. 221 on the\n # the last day, sum = 1000.\n np.testing.assert_array_equal(\n [389, 390, 221], list(map(len, results.transactions))\n )\n\n assert not log_catcher.has_warnings\n\n def test_eod_order_cancel_daily(self):\n # in daily mode, EODCancel does nothing.\n algo = self.prep_algo(\"set_cancel_policy(cancel_policy.EODCancel())\", \"daily\")\n\n log_catcher = TestHandler()\n with log_catcher:\n results = algo.run()\n\n # order stays open throughout simulation\n np.testing.assert_array_equal([1, 1, 1], list(map(len, results.orders)))\n\n # one txn per day\n np.testing.assert_array_equal(\n [0, 1, 1], list(map(len, results.transactions))\n )\n\n assert not log_catcher.has_warnings\n\n\nclass TestDailyEquityAutoClose(zf.WithMakeAlgo, zf.ZiplineTestCase):\n \"\"\"\n Tests if delisted equities are properly removed from a portfolio holding\n positions in said equities.\n \"\"\"\n\n # January 2015\n # Su Mo Tu We Th Fr Sa\n # 1 2 3\n # 4 5 6 7 8 9 10\n # 11 12 13 14 15 16 17\n # 18 19 20 21 22 23 24\n # 25 26 27 28 29 30 31\n START_DATE = pd.Timestamp(\"2015-01-05\", tz=\"UTC\")\n END_DATE = pd.Timestamp(\"2015-01-13\", tz=\"UTC\")\n\n SIM_PARAMS_DATA_FREQUENCY = \"daily\"\n DATA_PORTAL_USE_MINUTE_DATA = False\n BENCHMARK_SID = None\n\n @classmethod\n def init_class_fixtures(cls):\n super(TestDailyEquityAutoClose, cls).init_class_fixtures()\n cls.assets = cls.asset_finder.retrieve_all(cls.asset_finder.equities_sids)\n\n @classmethod\n def make_equity_info(cls):\n cls.test_days = cls.trading_calendar.sessions_in_range(\n cls.START_DATE,\n cls.END_DATE,\n )\n assert len(cls.test_days) == 7, \"Number of days in test changed!\"\n cls.first_asset_expiration = cls.test_days[2]\n\n # Assets start on start date and delist every two days:\n #\n # start_date end_date auto_close_date\n # 0 2015-01-05 2015-01-07 2015-01-09\n # 1 2015-01-05 2015-01-09 2015-01-13\n # 2 2015-01-05 2015-01-13 2015-01-15\n cls.asset_info = make_jagged_equity_info(\n num_assets=3,\n start_date=cls.test_days[0],\n first_end=cls.first_asset_expiration,\n frequency=cls.trading_calendar.day,\n periods_between_ends=2,\n auto_close_delta=2 * cls.trading_calendar.day,\n )\n return cls.asset_info\n\n @classmethod\n def make_equity_daily_bar_data(cls, country_code, sids):\n cls.daily_data = make_trade_data_for_asset_info(\n dates=cls.test_days,\n asset_info=cls.asset_info,\n price_start=10,\n price_step_by_sid=10,\n price_step_by_date=1,\n volume_start=100,\n volume_step_by_sid=100,\n volume_step_by_date=10,\n )\n return cls.daily_data.items()\n\n def daily_prices_on_tick(self, row):\n return [trades.iloc[row].close for trades in self.daily_data.values()]\n\n def final_daily_price(self, asset):\n return self.daily_data[asset.sid].loc[asset.end_date].close\n\n def default_initialize(self):\n \"\"\"\n Initialize function shared between test algos.\n \"\"\"\n\n def initialize(context):\n context.ordered = False\n context.set_commission(PerShare(0, 0))\n context.set_slippage(FixedSlippage(spread=0))\n context.num_positions = []\n context.cash = []\n\n return initialize\n\n def default_handle_data(self, assets, order_size):\n \"\"\"\n Handle data function shared between test algos.\n \"\"\"\n\n def handle_data(context, data):\n if not context.ordered:\n for asset in assets:\n context.order(asset, order_size)\n context.ordered = True\n\n context.cash.append(context.portfolio.cash)\n context.num_positions.append(len(context.portfolio.positions))\n\n return handle_data\n\n @parameter_space(\n order_size=[10, -10],\n capital_base=[1, 100000],\n __fail_fast=True,\n )\n def test_daily_delisted_equities(self, order_size, capital_base):\n \"\"\"\n Make sure that after an equity gets delisted, our portfolio holds the\n correct number of equities and correct amount of cash.\n \"\"\"\n assets = self.assets\n final_prices = {asset.sid: self.final_daily_price(asset) for asset in assets}\n\n # Prices at which we expect our orders to be filled.\n initial_fill_prices = self.daily_prices_on_tick(1)\n cost_basis = sum(initial_fill_prices) * order_size\n\n # Last known prices of assets that will be auto-closed.\n fp0 = final_prices[0]\n fp1 = final_prices[1]\n\n algo = self.make_algo(\n initialize=self.default_initialize(),\n handle_data=self.default_handle_data(assets, order_size),\n sim_params=self.make_simparams(\n capital_base=capital_base,\n data_frequency=\"daily\",\n ),\n )\n output = algo.run()\n\n initial_cash = capital_base\n after_fills = initial_cash - cost_basis\n after_first_auto_close = after_fills + fp0 * (order_size)\n after_second_auto_close = after_first_auto_close + fp1 * (order_size)\n\n # Day 1: Order 10 shares of each equity; there are 3 equities.\n # Day 2: Order goes through at the day 2 price of each equity.\n # Day 3: End date of Equity 0.\n # Day 4: Nothing happens.\n # Day 5: End date of Equity 1. Auto close of equity 0.\n # Add cash == (fp0 * size).\n # Day 6: Nothing happens.\n # Day 7: End date of Equity 2 and auto-close date of Equity 1.\n # Add cash equal to (fp1 * size).\n expected_cash = [\n initial_cash,\n after_fills,\n after_fills,\n after_fills,\n after_first_auto_close,\n after_first_auto_close,\n after_second_auto_close,\n ]\n expected_num_positions = [0, 3, 3, 3, 2, 2, 1]\n\n # Check expected cash.\n assert expected_cash == list(output[\"ending_cash\"])\n\n # The cash recorded by the algo should be behind by a day from the\n # computed ending cash.\n expected_cash.insert(3, after_fills)\n assert algo.cash == expected_cash[:-1]\n\n # Check expected long/short counts.\n # We have longs if order_size > 0.\n # We have shorts if order_size < 0.\n if order_size > 0:\n assert expected_num_positions == list(output[\"longs_count\"])\n assert [0] * len(self.test_days) == list(output[\"shorts_count\"])\n else:\n assert expected_num_positions == list(output[\"shorts_count\"])\n assert [0] * len(self.test_days) == list(output[\"longs_count\"])\n\n # The number of positions recorded by the algo should be behind by a\n # day from the computed long/short counts.\n expected_num_positions.insert(3, 3)\n assert algo.num_positions == expected_num_positions[:-1]\n\n # Check expected transactions.\n # We should have a transaction of order_size shares per sid.\n transactions = output[\"transactions\"]\n initial_fills = transactions.iloc[1]\n assert len(initial_fills) == len(assets)\n\n last_minute_of_session = self.trading_calendar.session_close(self.test_days[1])\n\n for asset, txn in zip(assets, initial_fills):\n assert (\n dict(\n txn,\n **{\n \"amount\": order_size,\n \"commission\": None,\n \"dt\": last_minute_of_session,\n \"price\": initial_fill_prices[asset],\n \"sid\": asset,\n },\n )\n == txn\n )\n # This will be a UUID.\n assert isinstance(txn[\"order_id\"], str)\n\n def transactions_for_date(date):\n return transactions.iloc[self.test_days.get_loc(date)]\n\n # We should have exactly one auto-close transaction on the close date\n # of asset 0.\n (first_auto_close_transaction,) = transactions_for_date(\n assets[0].auto_close_date\n )\n assert first_auto_close_transaction == {\n \"amount\": -order_size,\n \"commission\": None,\n \"dt\": self.trading_calendar.session_close(\n assets[0].auto_close_date,\n ),\n \"price\": fp0,\n \"sid\": assets[0],\n \"order_id\": None, # Auto-close txns emit Nones for order_id.\n }\n\n (second_auto_close_transaction,) = transactions_for_date(\n assets[1].auto_close_date\n )\n assert second_auto_close_transaction == {\n \"amount\": -order_size,\n \"commission\": None,\n \"dt\": self.trading_calendar.session_close(\n assets[1].auto_close_date,\n ),\n \"price\": fp1,\n \"sid\": assets[1],\n \"order_id\": None, # Auto-close txns emit Nones for order_id.\n }\n\n def test_cancel_open_orders(self):\n \"\"\"\n Test that any open orders for an equity that gets delisted are\n canceled. Unless an equity is auto closed, any open orders for that\n equity will persist indefinitely.\n \"\"\"\n assets = self.assets\n first_asset_end_date = assets[0].end_date\n first_asset_auto_close_date = assets[0].auto_close_date\n\n def initialize(context):\n pass\n\n def handle_data(context, data):\n # The only order we place in this test should never be filled.\n assert context.portfolio.cash == context.portfolio.starting_cash\n\n today_session = self.trading_calendar.minute_to_session_label(\n context.get_datetime()\n )\n day_after_auto_close = self.trading_calendar.next_session_label(\n first_asset_auto_close_date,\n )\n\n if today_session == first_asset_end_date:\n # Equity 0 will no longer exist tomorrow, so this order will\n # never be filled.\n assert len(context.get_open_orders()) == 0\n context.order(context.sid(0), 10)\n assert len(context.get_open_orders()) == 1\n elif today_session == first_asset_auto_close_date:\n # We do not cancel open orders until the end of the auto close\n # date, so our open order should still exist at this point.\n assert len(context.get_open_orders()) == 1\n elif today_session == day_after_auto_close:\n assert len(context.get_open_orders()) == 0\n\n algo = self.make_algo(\n initialize=initialize,\n handle_data=handle_data,\n sim_params=self.make_simparams(\n data_frequency=\"daily\",\n ),\n )\n results = algo.run()\n\n orders = results[\"orders\"]\n\n def orders_for_date(date):\n return orders.iloc[self.test_days.get_loc(date)]\n\n original_open_orders = orders_for_date(first_asset_end_date)\n assert len(original_open_orders) == 1\n\n last_close_for_asset = algo.trading_calendar.session_close(first_asset_end_date)\n\n assert (\n dict(\n original_open_orders[0],\n **{\n \"amount\": 10,\n \"commission\": 0.0,\n \"created\": last_close_for_asset,\n \"dt\": last_close_for_asset,\n \"sid\": assets[0],\n \"status\": ORDER_STATUS.OPEN,\n \"filled\": 0,\n },\n )\n == original_open_orders[0]\n )\n\n orders_after_auto_close = orders_for_date(first_asset_auto_close_date)\n assert len(orders_after_auto_close) == 1\n assert (\n dict(\n orders_after_auto_close[0],\n **{\n \"amount\": 10,\n \"commission\": 0.0,\n \"created\": last_close_for_asset,\n \"dt\": algo.trading_calendar.session_close(\n first_asset_auto_close_date,\n ),\n \"sid\": assets[0],\n \"status\": ORDER_STATUS.CANCELLED,\n \"filled\": 0,\n },\n )\n == orders_after_auto_close[0]\n )\n\n\n# NOTE: This suite is almost the same as TestDailyEquityAutoClose, except it\n# uses minutely data instead of daily data, and the auto_close_date for\n# equities is one day after their end_date instead of two.\nclass TestMinutelyEquityAutoClose(zf.WithMakeAlgo, zf.ZiplineTestCase):\n # January 2015\n # Su Mo Tu We Th Fr Sa\n # 1 2 3\n # 4 5 6 7 8 9 10\n # 11 12 13 14 15 16 17\n # 18 19 20 21 22 23 24\n # 25 26 27 28 29 30 31\n START_DATE = pd.Timestamp(\"2015-01-05\", tz=\"UTC\")\n END_DATE = pd.Timestamp(\"2015-01-13\", tz=\"UTC\")\n\n BENCHMARK_SID = None\n\n @classmethod\n def init_class_fixtures(cls):\n super(TestMinutelyEquityAutoClose, cls).init_class_fixtures()\n cls.assets = cls.asset_finder.retrieve_all(cls.asset_finder.equities_sids)\n\n @classmethod\n def make_equity_info(cls):\n cls.test_days = cls.trading_calendar.sessions_in_range(\n cls.START_DATE,\n cls.END_DATE,\n )\n cls.test_minutes = cls.trading_calendar.minutes_for_sessions_in_range(\n cls.START_DATE,\n cls.END_DATE,\n )\n cls.first_asset_expiration = cls.test_days[2]\n\n # Assets start on start date and delist every two days:\n #\n # start_date end_date auto_close_date\n # 0 2015-01-05 2015-01-07 2015-01-09\n # 1 2015-01-05 2015-01-09 2015-01-13\n # 2 2015-01-05 2015-01-13 2015-01-15\n cls.asset_info = make_jagged_equity_info(\n num_assets=3,\n start_date=cls.test_days[0],\n first_end=cls.first_asset_expiration,\n frequency=cls.trading_calendar.day,\n periods_between_ends=2,\n auto_close_delta=1 * cls.trading_calendar.day,\n )\n return cls.asset_info\n\n # XXX: This test suite uses inconsistent data for minutely and daily bars.\n @classmethod\n def make_equity_minute_bar_data(cls):\n cls.minute_data = make_trade_data_for_asset_info(\n dates=cls.test_minutes,\n asset_info=cls.asset_info,\n price_start=10,\n price_step_by_sid=10,\n price_step_by_date=1,\n volume_start=100,\n volume_step_by_sid=100,\n volume_step_by_date=10,\n )\n return cls.minute_data.items()\n\n def minute_prices_on_tick(self, row):\n return [trades.iloc[row].close for trades in self.minute_data.values()]\n\n def final_minute_price(self, asset):\n return (\n self.minute_data[asset.sid]\n .loc[self.trading_calendar.session_close(asset.end_date)]\n .close\n )\n\n def default_initialize(self):\n \"\"\"\n Initialize function shared between test algos.\n \"\"\"\n\n def initialize(context):\n context.ordered = False\n context.set_commission(PerShare(0, 0))\n context.set_slippage(FixedSlippage(spread=0))\n context.num_positions = []\n context.cash = []\n\n return initialize\n\n def default_handle_data(self, assets, order_size):\n \"\"\"\n Handle data function shared between test algos.\n \"\"\"\n\n def handle_data(context, data):\n if not context.ordered:\n for asset in assets:\n context.order(asset, order_size)\n context.ordered = True\n\n context.cash.append(context.portfolio.cash)\n context.num_positions.append(len(context.portfolio.positions))\n\n return handle_data\n\n def test_minutely_delisted_equities(self):\n assets = self.assets\n final_prices = {asset.sid: self.final_minute_price(asset) for asset in assets}\n backtest_minutes = self.minute_data[0].index.tolist()\n\n order_size = 10\n\n capital_base = 100000\n algo = self.make_algo(\n initialize=self.default_initialize(),\n handle_data=self.default_handle_data(assets, order_size),\n sim_params=self.make_simparams(\n capital_base=capital_base,\n data_frequency=\"minute\",\n ),\n )\n\n output = algo.run()\n initial_fill_prices = self.minute_prices_on_tick(1)\n cost_basis = sum(initial_fill_prices) * order_size\n\n # Last known prices of assets that will be auto-closed.\n fp0 = final_prices[0]\n fp1 = final_prices[1]\n\n initial_cash = capital_base\n after_fills = initial_cash - cost_basis\n after_first_auto_close = after_fills + fp0 * (order_size)\n after_second_auto_close = after_first_auto_close + fp1 * (order_size)\n\n expected_cash = [initial_cash]\n expected_position_counts = [0]\n\n # We have the rest of the first sim day, plus the second, third and\n # fourth days' worth of minutes with cash spent.\n expected_cash.extend([after_fills] * (389 + 390 + 390 + 390))\n expected_position_counts.extend([3] * (389 + 390 + 390 + 390))\n\n # We then have two days with the cash refunded from asset 0.\n expected_cash.extend([after_first_auto_close] * (390 + 390))\n expected_position_counts.extend([2] * (390 + 390))\n\n # We then have one day with cash refunded from asset 1.\n expected_cash.extend([after_second_auto_close] * 390)\n expected_position_counts.extend([1] * 390)\n\n # Check list lengths first to avoid expensive comparison\n assert len(algo.cash) == len(expected_cash)\n # TODO find more efficient way to compare these lists\n assert algo.cash == expected_cash\n assert list(output[\"ending_cash\"]) == [\n after_fills,\n after_fills,\n after_fills,\n after_first_auto_close,\n after_first_auto_close,\n after_second_auto_close,\n after_second_auto_close,\n ]\n\n assert algo.num_positions == expected_position_counts\n assert list(output[\"longs_count\"]) == [3, 3, 3, 2, 2, 1, 1]\n\n # Check expected transactions.\n # We should have a transaction of order_size shares per sid.\n transactions = output[\"transactions\"]\n\n # Note that the transactions appear on the first day rather than the\n # second in minute mode, because the fills happen on the second tick of\n # the backtest, which is still on the first day in minute mode.\n initial_fills = transactions.iloc[0]\n assert len(initial_fills) == len(assets)\n for asset, txn in zip(assets, initial_fills):\n assert (\n dict(\n txn,\n **{\n \"amount\": order_size,\n \"commission\": None,\n \"dt\": backtest_minutes[1],\n \"price\": initial_fill_prices[asset],\n \"sid\": asset,\n },\n )\n == txn\n )\n # This will be a UUID.\n assert isinstance(txn[\"order_id\"], str)\n\n def transactions_for_date(date):\n return transactions.iloc[self.test_days.get_loc(date)]\n\n # We should have exactly one auto-close transaction on the close date\n # of asset 0.\n (first_auto_close_transaction,) = transactions_for_date(\n assets[0].auto_close_date\n )\n assert first_auto_close_transaction == {\n \"amount\": -order_size,\n \"commission\": None,\n \"dt\": algo.trading_calendar.session_close(\n assets[0].auto_close_date,\n ),\n \"price\": fp0,\n \"sid\": assets[0],\n \"order_id\": None, # Auto-close txns emit Nones for order_id.\n }\n\n (second_auto_close_transaction,) = transactions_for_date(\n assets[1].auto_close_date\n )\n assert second_auto_close_transaction == {\n \"amount\": -order_size,\n \"commission\": None,\n \"dt\": algo.trading_calendar.session_close(\n assets[1].auto_close_date,\n ),\n \"price\": fp1,\n \"sid\": assets[1],\n \"order_id\": None, # Auto-close txns emit Nones for order_id.\n }\n\n\nclass TestOrderAfterDelist(zf.WithMakeAlgo, zf.ZiplineTestCase):\n start = pd.Timestamp(\"2016-01-05\", tz=\"utc\")\n day_1 = pd.Timestamp(\"2016-01-06\", tz=\"utc\")\n day_4 = pd.Timestamp(\"2016-01-11\", tz=\"utc\")\n end = pd.Timestamp(\"2016-01-15\", tz=\"utc\")\n\n # FIXME: Pass a benchmark source here.\n BENCHMARK_SID = None\n\n @classmethod\n def make_equity_info(cls):\n return pd.DataFrame.from_dict(\n {\n # Asset whose auto close date is after its end date.\n 1: {\n \"start_date\": cls.start,\n \"end_date\": cls.day_1,\n \"auto_close_date\": cls.day_4,\n \"symbol\": \"ASSET1\",\n \"exchange\": \"TEST\",\n },\n # Asset whose auto close date is before its end date.\n 2: {\n \"start_date\": cls.start,\n \"end_date\": cls.day_4,\n \"auto_close_date\": cls.day_1,\n \"symbol\": \"ASSET2\",\n \"exchange\": \"TEST\",\n },\n },\n orient=\"index\",\n )\n\n # XXX: This suite doesn't use the data in its DataPortal; it uses a\n # FakeDataPortal with different mock data.\n def init_instance_fixtures(self):\n super(TestOrderAfterDelist, self).init_instance_fixtures()\n self.data_portal = FakeDataPortal(self.asset_finder)\n\n @parameterized.expand(\n [\n (\"auto_close_after_end_date\", 1),\n (\"auto_close_before_end_date\", 2),\n ]\n )\n def test_order_in_quiet_period(self, name, sid):\n asset = self.asset_finder.retrieve_asset(sid)\n\n algo_code = dedent(\n \"\"\"\n from zipline.api import (\n sid,\n order,\n order_value,\n order_percent,\n order_target,\n order_target_percent,\n order_target_value\n )\n\n def initialize(context):\n pass\n\n def handle_data(context, data):\n order(sid({sid}), 1)\n order_value(sid({sid}), 100)\n order_percent(sid({sid}), 0.5)\n order_target(sid({sid}), 50)\n order_target_percent(sid({sid}), 0.5)\n order_target_value(sid({sid}), 50)\n \"\"\"\n ).format(sid=sid)\n\n # run algo from 1/6 to 1/7\n algo = self.make_algo(\n script=algo_code,\n sim_params=SimulationParameters(\n start_session=pd.Timestamp(\"2016-01-06\", tz=\"UTC\"),\n end_session=pd.Timestamp(\"2016-01-07\", tz=\"UTC\"),\n trading_calendar=self.trading_calendar,\n data_frequency=\"minute\",\n ),\n )\n with make_test_handler(self) as log_catcher:\n algo.run()\n\n warnings = [r for r in log_catcher.records if r.level == logbook.WARNING]\n\n # one warning per order on the second day\n assert 6 * 390 == len(warnings)\n\n for w in warnings:\n expected_message = (\n \"Cannot place order for ASSET{sid}, as it has de-listed. \"\n \"Any existing positions for this asset will be liquidated \"\n \"on {date}.\".format(sid=sid, date=asset.auto_close_date)\n )\n assert expected_message == w.message\n\n\nclass AlgoInputValidationTestCase(zf.WithMakeAlgo, zf.ZiplineTestCase):\n def test_reject_passing_both_api_methods_and_script(self):\n script = dedent(\n \"\"\"\n def initialize(context):\n pass\n\n def handle_data(context, data):\n pass\n\n def before_trading_start(context, data):\n pass\n\n def analyze(context, results):\n pass\n \"\"\"\n )\n for method in (\"initialize\", \"handle_data\", \"before_trading_start\", \"analyze\"):\n\n with pytest.raises(ValueError):\n self.make_algo(script=script, **{method: lambda *args, **kwargs: None})\n"
]
| [
[
"pandas.Series",
"pandas.date_range",
"numpy.isnan",
"numpy.arange",
"numpy.repeat",
"numpy.cumsum",
"pandas.DataFrame",
"pandas.Timedelta",
"numpy.testing.assert_array_equal",
"numpy.concatenate",
"numpy.full",
"numpy.cumprod",
"numpy.insert",
"numpy.copysign",
"pandas.DataFrame.from_dict",
"pandas.DataFrame.from_records",
"numpy.array",
"pandas.Timestamp"
]
]
|
Ricardozzf/pytorch-0.4-yolov3 | [
"96a226a541158b640ad87781ca09c75baffe1956"
]
| [
"yolo_layer.py"
]
| [
"import math\nimport numpy as np\nimport sys\nimport time\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom utils import bbox_iou, multi_bbox_ious, convert2cpu\n\nclass YoloLayer(nn.Module):\n def __init__(self, anchor_mask=[], num_classes=0, anchors=[1.0], num_anchors=1, use_cuda=None):\n super(YoloLayer, self).__init__()\n use_cuda = torch.cuda.is_available() and (True if use_cuda is None else use_cuda)\n self.device = torch.device(\"cuda\" if use_cuda else \"cpu\")\n\n self.anchor_mask = anchor_mask\n self.num_classes = num_classes\n self.anchors = anchors\n self.num_anchors = num_anchors\n self.anchor_step = len(anchors)//num_anchors\n self.rescore = 0\n self.ignore_thresh = 0.5\n self.truth_thresh = 1.\n self.nth_layer = 0\n self.seen = 0\n self.net_width = 0\n self.net_height = 0\n\n def get_mask_boxes(self, output):\n masked_anchors = []\n for m in self.anchor_mask:\n masked_anchors += self.anchors[m*self.anchor_step:(m+1)*self.anchor_step]\n\n masked_anchors = torch.FloatTensor(masked_anchors).to(self.device)\n num_anchors = torch.IntTensor([len(self.anchor_mask)]).to(self.device)\n return {'x':output, 'a':masked_anchors, 'n':num_anchors}\n\n def build_targets(self, pred_boxes, target, anchors, nA, nH, nW):\n nB = target.size(0)\n anchor_step = anchors.size(1) # anchors[nA][anchor_step]\n noobj_mask = torch.ones (nB, nA, nH, nW)\n obj_mask = torch.zeros(nB, nA, nH, nW)\n tcoord = torch.zeros( 4, nB, nA, nH, nW)\n tconf = torch.zeros(nB, nA, nH, nW)\n tcls = torch.zeros(nB, nA, nH, nW)\n\n nAnchors = nA*nH*nW\n nPixels = nH*nW\n nGT = 0\n nRecall = 0\n nRecall75 = 0\n\n # it works faster on CPU than on GPU.\n anchors = anchors.to(\"cpu\")\n\n for b in range(nB):\n cur_pred_boxes = pred_boxes[b*nAnchors:(b+1)*nAnchors].t()\n cur_ious = torch.zeros(nAnchors)\n tbox = target[b].view(-1,5).to(\"cpu\")\n\n for t in range(50):\n if tbox[t][1] == 0:\n break\n gx, gy = tbox[t][1] * nW, tbox[t][2] * nH\n gw, gh = tbox[t][3] * self.net_width, tbox[t][4] * self.net_height\n cur_gt_boxes = torch.FloatTensor([gx, gy, gw, gh]).repeat(nAnchors,1).t()\n cur_ious = torch.max(cur_ious, multi_bbox_ious(cur_pred_boxes, cur_gt_boxes, x1y1x2y2=False))\n ignore_ix = cur_ious>self.ignore_thresh\n noobj_mask[b][ignore_ix.view(nA,nH,nW)] = 0\n\n for t in range(50):\n if tbox[t][1] == 0:\n break\n nGT += 1\n gx, gy = tbox[t][1] * nW, tbox[t][2] * nH\n gw, gh = tbox[t][3] * self.net_width, tbox[t][4] * self.net_height\n gw, gh = gw.float(), gh.float()\n gi, gj = int(gx), int(gy)\n\n tmp_gt_boxes = torch.FloatTensor([0, 0, gw, gh]).repeat(nA,1).t()\n anchor_boxes = torch.cat((torch.zeros(nA, anchor_step), anchors),1).t()\n _, best_n = torch.max(multi_bbox_ious(anchor_boxes, tmp_gt_boxes, x1y1x2y2=False), 0)\n\n gt_box = torch.FloatTensor([gx, gy, gw, gh])\n pred_box = pred_boxes[b*nAnchors+best_n*nPixels+gj*nW+gi]\n iou = bbox_iou(gt_box, pred_box, x1y1x2y2=False)\n\n obj_mask [b][best_n][gj][gi] = 1\n noobj_mask[b][best_n][gj][gi] = 0\n tcoord [0][b][best_n][gj][gi] = gx - gi\n tcoord [1][b][best_n][gj][gi] = gy - gj\n tcoord [2][b][best_n][gj][gi] = math.log(gw/anchors[best_n][0])\n tcoord [3][b][best_n][gj][gi] = math.log(gh/anchors[best_n][1])\n tcls [b][best_n][gj][gi] = tbox[t][0]\n tconf [b][best_n][gj][gi] = iou if self.rescore else 1.\n\n if iou > 0.5:\n nRecall += 1\n if iou > 0.75:\n nRecall75 += 1\n\n return nGT, nRecall, nRecall75, obj_mask, noobj_mask, tcoord, tconf, tcls\n\n def forward(self, output, target):\n #output : BxAs*(4+1+num_classes)*H*W\n mask_tuple = self.get_mask_boxes(output)\n t0 = time.time()\n nB = output.data.size(0) # batch size\n nA = mask_tuple['n'].item() # num_anchors\n nC = self.num_classes\n nH = output.data.size(2)\n nW = output.data.size(3)\n anchor_step = mask_tuple['a'].size(0)//nA\n anchors = mask_tuple['a'].view(nA, anchor_step).to(self.device)\n cls_anchor_dim = nB*nA*nH*nW\n\n output = output.view(nB, nA, (5+nC), nH, nW)\n cls_grid = torch.linspace(5,5+nC-1,nC).long().to(self.device)\n ix = torch.LongTensor(range(0,5)).to(self.device)\n pred_boxes = torch.FloatTensor(4, cls_anchor_dim).to(self.device)\n\n coord = output.index_select(2, ix[0:4]).view(nB*nA, -1, nH*nW).transpose(0,1).contiguous().view(-1,cls_anchor_dim) # x, y, w, h\n coord[0:2] = coord[0:2].sigmoid()\n conf = output.index_select(2, ix[4]).view(cls_anchor_dim).sigmoid()\n\n cls = output.index_select(2, cls_grid)\n cls = cls.view(nB*nA, nC, nH*nW).transpose(1,2).contiguous().view(cls_anchor_dim, nC)\n\n t1 = time.time()\n grid_x = torch.linspace(0, nW-1, nW).repeat(nB*nA, nH, 1).view(cls_anchor_dim).to(self.device)\n grid_y = torch.linspace(0, nH-1, nH).repeat(nW,1).t().repeat(nB*nA, 1, 1).view(cls_anchor_dim).to(self.device)\n anchor_w = anchors.index_select(1, ix[0]).repeat(1, nB*nH*nW).view(cls_anchor_dim)\n anchor_h = anchors.index_select(1, ix[1]).repeat(1, nB*nH*nW).view(cls_anchor_dim)\n\n pred_boxes[0] = coord[0] + grid_x\n pred_boxes[1] = coord[1] + grid_y\n pred_boxes[2] = coord[2].exp() * anchor_w\n pred_boxes[3] = coord[3].exp() * anchor_h\n # for build_targets. it works faster on CPU than on GPU\n pred_boxes = convert2cpu(pred_boxes.transpose(0,1).contiguous().view(-1,4)).detach()\n\n t2 = time.time()\n nGT, nRecall, nRecall75, obj_mask, noobj_mask, tcoord, tconf, tcls = \\\n self.build_targets(pred_boxes, target.detach(), anchors.detach(), nA, nH, nW)\n\n cls_mask = (obj_mask == 1)\n tcls = tcls[cls_mask].long().view(-1).to(self.device)\n cls_mask = cls_mask.view(-1, 1).repeat(1,nC).to(self.device)\n cls = cls[cls_mask].view(-1, nC)\n\n nProposals = int((conf > 0.25).sum())\n \n tcoord = tcoord.view(4, cls_anchor_dim).to(self.device)\n tconf = tconf.view(cls_anchor_dim).to(self.device) \n\n conf_mask = (obj_mask + noobj_mask).view(cls_anchor_dim).to(self.device)\n obj_mask = obj_mask.view(cls_anchor_dim).to(self.device)\n\n t3 = time.time()\n loss_coord = nn.MSELoss(reduction='sum')(coord*obj_mask, tcoord*obj_mask)/nB\n loss_conf = nn.MSELoss(reduction='sum')(conf*conf_mask, tconf*conf_mask)/nB\n loss_cls = nn.CrossEntropyLoss(reduction='sum')(cls, tcls)/nB if cls.size(0) > 0 else 0 \n loss = loss_coord + loss_conf + loss_cls\n\n t4 = time.time()\n if False:\n print('-'*30)\n print(' activation : %f' % (t1 - t0))\n print(' create pred_boxes : %f' % (t2 - t1))\n print(' build targets : %f' % (t3 - t2))\n print(' create loss : %f' % (t4 - t3))\n print(' total : %f' % (t4 - t0))\n print('%d: Layer(%03d) nGT %3d, nRC %3d, nRC75 %3d, nPP %3d, loss: box %6.3f, conf %6.3f, class %6.3f, total %7.3f' \n % (self.seen, self.nth_layer, nGT, nRecall, nRecall75, nProposals, loss_coord, loss_conf, loss_cls, loss))\n if math.isnan(loss.item()):\n print(conf, tconf)\n sys.exit(0)\n return loss\n"
]
| [
[
"torch.nn.CrossEntropyLoss",
"torch.linspace",
"torch.ones",
"torch.zeros",
"torch.FloatTensor",
"torch.cuda.is_available",
"torch.device",
"torch.nn.MSELoss"
]
]
|
bing-jian/probreg | [
"eee9839e4f9d7286128371f8d58444fe7fae589c"
]
| [
"probreg/se3_op.py"
]
| [
"from __future__ import print_function\nfrom __future__ import division\nimport numpy as np\nimport transformations as trans\nfrom . import _se3_op\n\n\ndef skew(x):\n \"\"\"\n skew-symmetric matrix, that represent\n cross products as matrix multiplications.\n\n Args:\n x (numpy.ndarray): 3D vector.\n Returns:\n 3x3 skew-symmetric matrix.\n \"\"\"\n return np.array([[0.0, -x[2], x[1]],\n [x[2], 0.0, -x[0]],\n [-x[1], x[0], 0.0]])\n\n\ndef twist_trans(tw):\n \"\"\"\n Linear approximation of transformation matrix\n using twist representation.\n\n Args:\n tw (numpy.ndarray): Twist vector.\n \"\"\"\n return np.identity(3) + skew(tw[:3]), tw[3:]\n\n\ndef twist_mul(tw, rot, t):\n tr, tt = twist_trans(tw)\n return np.dot(tr, rot), np.dot(t, tr.T) + tt\n\n\ndef diff_from_tw(x, w=None):\n if w is None:\n return _se3_op.diff_from_twist(x.T).T.reshape((-1, 3, 6))\n else:\n return _se3_op.diff_from_twist(x.T, w).T.reshape((-1, 3, 6))\n\n\ndef diff_from_tw2(x):\n return _se3_op.diff_from_twist2(x.reshape((-1, 18)).T)\n\n\ndef diff_rot_from_quaternion(q):\n \"\"\"Differencial rotation matrix from quaternion.\n\n dR(q)/dq = [dR(q)/dq0, dR(q)/dq1, dR(q)/dq2, dR(q)/dq3]\n\n Args:\n q (numpy.ndarray): Quaternion.\n \"\"\"\n rot = trans.quaternion_matrix(q)[:3, :3]\n q2 = np.square(q)\n z = np.sum(q2)\n z2 = z * z\n d_rot = np.zeros((4, 3, 3))\n d_rot[0, 0, 0] = 4 * q[0] * (q2[2] + q2[3]) / z2\n d_rot[1, 0, 0] = 4 * q[1] * (q2[2] + q2[3]) / z2\n d_rot[2, 0, 0] = -4 * q[2] * (q2[1] + q2[0]) / z2\n d_rot[3, 0, 0] = -4 * q[3] * (q2[1] + q2[0]) / z2\n\n d_rot[0, 1, 1] = 4 * q[0] * (q2[1] + q2[3]) / z2\n d_rot[1, 1, 1] = -4 * q[1] * (q2[2] + q2[0]) / z2\n d_rot[2, 1, 1] = 4 * q[2] * (q2[1] + q2[3]) / z2\n d_rot[3, 1, 1] = -4 * q[3] * (q2[2] + q2[0]) / z2\n\n d_rot[0, 2, 2] = 4 * q[0] * (q2[1] + q2[2]) / z2\n d_rot[1, 2, 2] = -4 * q[1] * (q2[3] + q2[0]) / z2\n d_rot[2, 2, 2] = -4 * q[2] * (q2[1] + q2[2]) / z2\n d_rot[3, 2, 2] = 4 * q[3] * (q2[3] + q2[0]) / z2\n\n d_rot[0, 0, 1] = -2 * q[3] / z - 2 * q[0] * rot[0, 1] / z2\n d_rot[1, 0, 1] = 2 * q[2] / z - 2 * q[1] * rot[0, 1] / z2\n d_rot[2, 0, 1] = 2 * q[1] / z - 2 * q[2] * rot[0, 1] / z2\n d_rot[3, 0, 1] = -2 * q[0] / z - 2 * q[3] * rot[0, 1] / z2\n\n d_rot[0, 0, 2] = 2 * q[2] / z - 2 * q[0] * rot[0, 2] / z2\n d_rot[1, 0, 2] = 2 * q[3] / z - 2 * q[1] * rot[0, 2] / z2\n d_rot[2, 0, 2] = 2 * q[0] / z - 2 * q[2] * rot[0, 2] / z2\n d_rot[3, 0, 2] = 2 * q[1] / z - 2 * q[3] * rot[0, 2] / z2\n\n d_rot[0, 1, 0] = 2 * q[3] / z - 2 * q[0] * rot[1, 0] / z2\n d_rot[1, 1, 0] = 2 * q[2] / z - 2 * q[1] * rot[1, 0] / z2\n d_rot[2, 1, 0] = 2 * q[1] / z - 2 * q[2] * rot[1, 0] / z2\n d_rot[3, 1, 0] = 2 * q[0] / z - 2 * q[3] * rot[1, 0] / z2\n\n d_rot[0, 1, 2] = -2 * q[1] / z - 2 * q[0] * rot[1, 2] / z2\n d_rot[1, 1, 2] = -2 * q[0] / z - 2 * q[1] * rot[1, 2] / z2\n d_rot[2, 1, 2] = 2 * q[3] / z - 2 * q[2] * rot[1, 2] / z2\n d_rot[3, 1, 2] = 2 * q[2] / z - 2 * q[3] * rot[1, 2] / z2\n\n d_rot[0, 2, 0] = -2 * q[2] / z - 2 * q[0] * rot[2, 0] / z2\n d_rot[1, 2, 0] = 2 * q[3] / z - 2 * q[1] * rot[2, 0] / z2\n d_rot[2, 2, 0] = -2 * q[0] / z - 2 * q[2] * rot[2, 0] / z2\n d_rot[3, 2, 0] = 2 * q[1] / z - 2 * q[3] * rot[2, 0] / z2\n\n d_rot[0, 2, 1] = 2 * q[1] / z - 2 * q[0] * rot[2, 1] / z2\n d_rot[1, 2, 1] = 2 * q[0] / z - 2 * q[1] * rot[2, 1] / z2\n d_rot[2, 2, 1] = 2 * q[3] / z - 2 * q[2] * rot[2, 1] / z2\n d_rot[3, 2, 1] = 2 * q[2] / z - 2 * q[3] * rot[2, 1] / z2\n\n return d_rot\n"
]
| [
[
"numpy.square",
"numpy.dot",
"numpy.identity",
"numpy.array",
"numpy.zeros",
"numpy.sum"
]
]
|
actuy/tensor2tensor | [
"607463b0c594896e1841d64b2110e1aafc99d646"
]
| [
"tensor2tensor/models/research/glow.py"
]
| [
"# coding=utf-8\n# Copyright 2019 The Tensor2Tensor Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Glow generative model.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nfrom tensor2tensor.layers import common_hparams\nfrom tensor2tensor.layers import common_layers\nfrom tensor2tensor.models.research import glow_init_hook\nfrom tensor2tensor.models.research import glow_ops\nfrom tensor2tensor.utils import registry\nfrom tensor2tensor.utils import t2t_model\nimport tensorflow as tf\n\narg_scope = tf.contrib.framework.arg_scope\nadd_arg_scope = tf.contrib.framework.add_arg_scope\n\nGLOW_DECODE_HPARAMS = (\"identity_output=True,log_results=False,\"\n \"decode_in_memory=True,display_decoded_images=True\")\n\n\[email protected]_hparams\ndef glow_hparams():\n \"\"\"Glow Hparams.\"\"\"\n hparams = common_hparams.basic_params1()\n hparams.clip_grad_norm = None\n hparams.weight_decay = 0.0\n hparams.learning_rate_constant = 3e-4\n hparams.batch_size = 32\n # can be prev_level, prev_step or normal.\n # see: glow_ops.merge_level_and_latent_dist\n hparams.add_hparam(\"level_scale\", \"prev_level\")\n hparams.add_hparam(\"n_levels\", 3)\n hparams.add_hparam(\"n_bits_x\", 8)\n hparams.add_hparam(\"depth\", 32)\n # Activation - Relu or Gatu\n hparams.add_hparam(\"activation\", \"relu\")\n # Coupling layer, additive or affine.\n hparams.add_hparam(\"coupling\", \"affine\")\n hparams.add_hparam(\"coupling_width\", 512)\n hparams.add_hparam(\"coupling_dropout\", 0.0)\n hparams.add_hparam(\"top_prior\", \"single_conv\")\n # init_batch_size denotes the number of examples used for data-dependent\n # initialization. A higher init_batch_size is required for training\n # stability especially when hparams.batch_size is low.\n hparams.add_hparam(\"init_batch_size\", 256)\n hparams.add_hparam(\"temperature\", 1.0)\n\n return hparams\n\n\[email protected]_model\nclass Glow(t2t_model.T2TModel):\n \"\"\"Glow generative model.\n\n Reference: https://arxiv.org/abs/1807.03039\"\"\"\n\n def init_preprocess(self, features):\n \"\"\"Preprocessing as per the input modality.\"\"\"\n return features\n\n def preprocess(self, x):\n \"\"\"Normalize x.\n\n Args:\n x: 4-D Tensor.\n\n Returns:\n x: Scaled such that x lies in-between -0.5 and 0.5\n \"\"\"\n n_bits_x = self.hparams.n_bits_x\n n_bins = 2**n_bits_x\n x = tf.cast(x, dtype=tf.float32)\n if n_bits_x < 8:\n x = tf.floor(x / 2 ** (8 - n_bits_x))\n x = x / n_bins - 0.5\n return x\n\n @property\n def temperature(self):\n if self.is_predicting:\n return self.hparams.temperature\n return 1.0\n\n @property\n def is_training(self):\n return self.hparams.mode == tf.estimator.ModeKeys.TRAIN\n\n def infer(self, features, *args, **kwargs): # pylint: disable=arguments-differ\n del args, kwargs\n x = features[\"inputs\"]\n batch_size = common_layers.shape_list(x)[0]\n features[\"targets\"] = tf.zeros(shape=(batch_size, 1, 1, 1))\n _, _ = self(features) # pylint: disable=not-callable\n\n ops = [glow_ops.get_variable_ddi, glow_ops.actnorm, glow_ops.get_dropout]\n var_scope = tf.variable_scope(\"glow/body\", reuse=True)\n # If eps=None, images are sampled from the prior.\n with arg_scope(ops, init=False), var_scope:\n predictions, _, _, _ = glow_ops.encoder_decoder(\n \"codec\", self.z_sample, self.hparams, eps=None, reverse=True,\n temperature=self.temperature)\n\n return glow_ops.postprocess(predictions, self.hparams.n_bits_x)\n\n def create_init_batch(self, features):\n \"\"\"Returns a batch of size \"hparams.init_batch_size\" for initialization.\n\n Args:\n features: input features.\n Returns:\n init_features: initialization features.\n \"\"\"\n train_dataset = self.hparams.problem.dataset(\n tf.estimator.ModeKeys.TRAIN, hparams=self.hparams)\n train_dataset = train_dataset.batch(self.hparams.init_batch_size)\n train_dataset = self.init_preprocess(train_dataset)\n return train_dataset.make_one_shot_iterator().get_next()\n\n @staticmethod\n def train_hooks(hook_context):\n del hook_context\n return [glow_init_hook.GlowInitHook()]\n\n def top_prior(self):\n \"\"\"Objective based on the prior over latent z.\n\n Returns:\n dist: instance of tf.distributions.Normal, prior distribution.\n \"\"\"\n return glow_ops.top_prior(\n \"top_prior\", self.z_top_shape, learn_prior=self.hparams.top_prior,\n temperature=self.temperature)\n\n def body(self, features):\n exp_coupling = [\"affine\", \"additive\"]\n if self.hparams.coupling not in exp_coupling:\n raise ValueError(\"Expected hparams.coupling to be in %s, got %s\" %\n (exp_coupling, self.hparams.coupling))\n if self.is_training:\n init_features = self.create_init_batch(features)\n init_op = self.objective_tower(init_features, init=True)\n init_op = tf.Print(\n init_op, [init_op], message=\"Triggering data-dependent init.\",\n first_n=20)\n tf.add_to_collection(\"glow_init_op\", init_op)\n train_op = self.objective_tower(features, init=False)\n return tf.zeros_like(features[\"targets\"]), {\"training\": train_op}\n\n def objective_tower(self, features, init=True):\n \"\"\"Objective in terms of bits-per-pixel.\n\n Args:\n features: dict of tensors with \"features\" and \"targets\" keys.\n init: Whether or not to run data-dependent init.\n Returns:\n objective: float, bits-per-pixel.\n \"\"\"\n x = features[\"inputs\"]\n\n # Scale x such that the pixels lie in-between -0.5 and.0.5\n x = self.preprocess(x)\n x, objective = glow_ops.uniform_binning_correction(x)\n\n # The arg_scope call ensures that the actnorm parameters are set such that\n # the per-channel output activations have zero mean and unit variance\n # ONLY during the first step. After that the parameters are learned\n # through optimisation.\n ops = [glow_ops.get_variable_ddi, glow_ops.actnorm, glow_ops.get_dropout]\n with arg_scope(ops, init=init):\n encoder = glow_ops.encoder_decoder\n\n\n self.z, encoder_objective, self.eps, _, _ = encoder(\n \"codec\", x, self.hparams, eps=None, reverse=False)\n objective += encoder_objective\n\n self.z_top_shape = common_layers.shape_list(self.z)\n prior_dist = self.top_prior()\n prior_objective = tf.reduce_sum(\n prior_dist.log_prob(self.z), axis=[1, 2, 3])\n self.z_sample = prior_dist.sample()\n objective += prior_objective\n\n # bits per pixel\n _, h, w, c = common_layers.shape_list(x)\n objective = -objective / (np.log(2) * h * w * c)\n return objective\n"
]
| [
[
"numpy.log",
"tensorflow.Print",
"tensorflow.zeros",
"tensorflow.cast",
"tensorflow.floor",
"tensorflow.zeros_like",
"tensorflow.variable_scope",
"tensorflow.add_to_collection"
]
]
|
rafiberlin/clp-sose21-pm-vision | [
"55c786182ed4568cdeda4bb3676fa02b9580d68d"
]
| [
"avatar_sgg/captioning/catr/inference.py"
]
| [
"import torch\nimport torch.nn.functional\n\nfrom transformers import BertTokenizer\nfrom PIL import Image\nfrom avatar_sgg.captioning.catr.hubconf import v3\nfrom avatar_sgg.captioning.catr.datasets import coco\nfrom avatar_sgg.captioning.catr.configuration import Config\nfrom avatar_sgg.config.util import get_config\nimport numpy as np\nimport os\n\n\n\nclass CATRInference():\n def __init__(self):\n self.config = Config()\n # set local file to True if you have connection issues...\n self.tokenizer = BertTokenizer.from_pretrained('bert-base-uncased', local_files_only=False)\n self.max_length = self.config.max_position_embeddings\n self.start_token = self.tokenizer.convert_tokens_to_ids(self.tokenizer._cls_token)\n self.end_token = self.tokenizer.convert_tokens_to_ids(self.tokenizer._sep_token)\n self.model = v3(pretrained=True)#torch.hub.load('saahiluppal/catr', 'v3', pretrained=True)\n self.model.eval()\n catr_config = get_config()[\"captioning\"][\"catr\"]\n self.cuda_device = catr_config[\"cuda_device\"]\n self.beam_size = catr_config[\"beam_size\"]\n\n if type(self.cuda_device) is str and self.cuda_device.startswith(\"cuda\"):\n print(\"Use CATR Model with GPU\", self.cuda_device)\n self.model.cuda(self.cuda_device)\n else:\n print(\"Use CATR Model with CPU\")\n\n def create_caption_and_mask(self):\n\n\n\n self.caption_template = torch.zeros((1, self.max_length), dtype=torch.long)\n self.mask_template = torch.ones((1, self.max_length), dtype=torch.bool)\n\n self.caption_template[:, 0] = self.start_token\n self.mask_template[:, 0] = False\n\n return self.caption_template, self.mask_template\n @torch.no_grad()\n def infer_beam(self, image_path):\n \"\"\"\n Beam Search still broken. Does not deliver better bleu score than greedy search\n :param image_path:\n :return:\n \"\"\"\n image = Image.open(image_path)\n image = coco.val_transform(image)\n image = image.unsqueeze(0)\n beam_size = self.beam_size\n caption, cap_mask = self.create_caption_and_mask()\n\n if self.cuda_device.startswith(\"cuda\"):\n image = image.cuda(self.cuda_device)\n caption = caption.cuda(self.cuda_device)\n cap_mask = cap_mask.cuda(self.cuda_device)\n src, mask, pos = self.model.init_sample(image)\n\n predictions = self.model.infer(src, mask, pos, caption, cap_mask) #self.model(image, caption, cap_mask)\n predictions = torch.nn.functional.log_softmax(predictions[:, 0, :], dim=-1)#predictions[:, 0, :]#torch.nn.functional.log_softmax(predictions[:, 0, :])\n previous_log_prob, candidate_indices = torch.topk(predictions, beam_size)\n preds = {i: np.zeros(self.max_length, dtype=int) for i in range(beam_size)}\n for i in range(beam_size):\n preds[i][0] = candidate_indices[0][i]\n # Copy entries a number of time equal to the beam size (the number of alternative paths)\n # 1 means the dimensions stay untouched\n #image = image.repeat(beam_size, 1, 1, 1)\n caption = caption.repeat(beam_size, 1)\n cap_mask = cap_mask.repeat(beam_size, 1)\n src = src.repeat(beam_size,1 ,1 ,1)\n mask = mask.repeat(beam_size,1 ,1)\n pos[0] = pos[0].repeat(beam_size,1, 1,1)\n candidates = []\n caption[:, 1] = candidate_indices\n cap_mask[:, 1] = False\n for step in range(1, self.max_length - 1):\n predictions = self.model.infer(src, mask, pos, caption, cap_mask) #self.model(image, caption, cap_mask)\n predictions = torch.nn.functional.log_softmax(predictions[:, step, :], dim=-1)#predictions[:, step, :]\n candidates_log_prob, candidate_indices = torch.topk(predictions, beam_size)\n candidates_log_prob = torch.reshape(candidates_log_prob + previous_log_prob, (-1,))\n candidate_indices = torch.reshape(candidate_indices, (-1,))\n current_top_candidates, current_top_candidates_idx = torch.topk(candidates_log_prob, k=beam_size)\n\n # Do the mapping best candidate and \"source\" of the best candidates\n k_idx = torch.index_select(candidate_indices, dim=0, index=current_top_candidates_idx)\n prev_idx = torch.floor(current_top_candidates_idx / beam_size).to(torch.int32)\n\n previous_log_prob = torch.unsqueeze(current_top_candidates, dim=1)\n np_prev_idx = prev_idx.cpu().numpy()\n # Overwrite the previous predictions due to the new best candidates\n temp = caption.clone()\n for i in range(prev_idx.shape[0]):\n temp[i][:step + 1] = caption[np_prev_idx[i]][:step + 1]\n caption = temp\n preds = {i: preds[np_prev_idx[i]].copy() for i in range(prev_idx.shape[0])}\n caption[:, step + 1] = k_idx\n cap_mask[:, step + 1] = False\n stop_idx = []\n for i in range(k_idx.shape[0]):\n preds[i][step] = k_idx[i]\n if k_idx[i] == self.end_token:\n stop_idx.append(i)\n\n # remove all finished captions and adjust all tensors accordingly...\n if len(stop_idx):\n for i in reversed(sorted(stop_idx)):\n candidate = preds.pop(i)\n loss = current_top_candidates[i]\n length = np.where(candidate == self.end_token)[0]\n normalized_loss = loss / float(length)\n candidates.append((candidate, normalized_loss))\n beam_size = beam_size - len(stop_idx)\n if beam_size > 0:\n left_idx = torch.LongTensor([i for i in range(k_idx.shape[0]) if i not in stop_idx])\n\n if self.cuda_device.startswith(\"cuda\"):\n left_idx = left_idx.cuda(self.cuda_device)\n # current_top_candidates = torch.IntTensor(\n # [current_top_candidates[i] for i in range(current_top_candidates.shape[0]) if\n # i not in stop_idx])\n caption = torch.index_select(caption, dim=0, index=left_idx)\n cap_mask = torch.index_select(cap_mask, dim=0, index=left_idx)\n #image = torch.index_select(image, dim=0, index=left_idx)\n previous_log_prob = torch.index_select(previous_log_prob, dim=0, index=left_idx)\n src = torch.index_select(src, dim=0, index=left_idx)\n mask = torch.index_select(mask, dim=0, index=left_idx)\n pos[0] = torch.index_select(pos[0], dim=0, index=left_idx)\n # now that the finished sentences have been removed, we need to update the predictions dict accordingly\n for i, key in enumerate(sorted(preds.keys())):\n preds[i] = preds.pop(key)\n else:\n break # No sequences unfinished\n\n\n\n if len(candidates) > 0:\n result, _ = max(candidates, key=lambda c: c[1])\n else:\n result = preds[0]\n\n output = self.tokenizer.decode(result, skip_special_tokens=True)\n return output\n\n\n @torch.no_grad()\n def infer(self, image_path):\n image = Image.open(image_path)\n image = coco.val_transform(image)\n image = image.unsqueeze(0)\n\n caption, cap_mask = self.create_caption_and_mask()\n if self.cuda_device.startswith(\"cuda\"):\n image = image.cuda(self.cuda_device)\n caption = caption.cuda(self.cuda_device)\n cap_mask = cap_mask.cuda(self.cuda_device)\n\n src, mask, pos = self.model.init_sample(image)\n #model.eval()\n for i in range(self.max_length - 1):\n predictions = self.model.infer(src, mask, pos, caption, cap_mask)\n predictions = predictions[:, i, :]\n predicted_id = torch.argmax(predictions, axis=-1)\n if predicted_id[0] == self.end_token:\n #return caption\n break\n caption[:, i+1] = predicted_id[0]\n cap_mask[:, i+1] = False\n output = self.tokenizer.decode(caption[0].tolist(), skip_special_tokens=True)\n return output\n\n\nif __name__ == \"__main__\":\n ade20k = get_config()[\"ade20k\"][\"root_dir\"]\n image_path = os.path.join(ade20k, \"images/training/u/utility_room/ADE_train_00019432.jpg\")\n catr = CATRInference()\n output = catr.infer(image_path)\n #result = catr.tokenizer.decode(output[0].tolist(), skip_special_tokens=True)\n #result = tokenizer.decode(output[0], skip_special_tokens=True)\n print(output)\n"
]
| [
[
"torch.ones",
"torch.floor",
"torch.nn.functional.log_softmax",
"torch.zeros",
"torch.reshape",
"torch.unsqueeze",
"torch.no_grad",
"torch.index_select",
"torch.topk",
"numpy.zeros",
"numpy.where",
"torch.argmax"
]
]
|
silentz/Free-Form-Image-Inpainting-With-Gated-Convolution | [
"75e1c5ea1950c9385651e353cb0562b9f1dbba6a"
]
| [
"train/lightning.py"
]
| [
"import torch\nimport torch.nn.functional as F\nfrom torch.utils.data import Dataset\nfrom torch.utils.data import DataLoader\n\nimport wandb\nfrom wandb.sdk.data_types import Image\nimport pytorch_lightning as pl\nfrom typing import Any, Dict, List\n\nfrom src.collate import collate_fn, Batch\nfrom src.models import Generator, Discriminator\nfrom src.loss import recon_loss\n\n\nclass DataModule(pl.LightningDataModule):\n\n def __init__(self, train_dataset: Dataset,\n train_batch_size: int,\n train_num_workers: int,\n val_dataset: Dataset,\n val_batch_size: int,\n val_num_workers: int):\n super().__init__()\n self.train_dataset = train_dataset\n self.val_dataset = val_dataset\n\n self.train_dataloader_kwargs = {\n 'batch_size': train_batch_size,\n 'num_workers': train_num_workers,\n 'collate_fn': collate_fn,\n }\n self.val_dataloader_kwargs = {\n 'batch_size': val_batch_size,\n 'num_workers': val_num_workers,\n 'collate_fn': collate_fn,\n }\n\n def train_dataloader(self) -> DataLoader:\n return DataLoader(self.train_dataset, **self.train_dataloader_kwargs)\n\n def val_dataloader(self) -> DataLoader:\n return DataLoader(self.val_dataset, **self.val_dataloader_kwargs)\n\n\nclass Module(pl.LightningModule):\n\n def __init__(self, gen_optimizer_lr: float,\n dis_optimizer_lr: float):\n super().__init__()\n self.gen_optimizer_lr = gen_optimizer_lr\n self.dis_optimizer_lr = dis_optimizer_lr\n\n self.generator = Generator()\n self.discriminator = Discriminator()\n self.automatic_optimization = False\n\n def configure_optimizers(self) -> List[torch.optim.Optimizer]:\n gen_optim = torch.optim.Adam(self.generator.parameters(), lr=self.gen_optimizer_lr)\n dis_optim = torch.optim.Adam(self.discriminator.parameters(), lr=self.dis_optimizer_lr)\n return [dis_optim, gen_optim]\n\n def training_step(self, batch: Batch, batch_idx: int) -> Dict[str, Any]:\n dis_optim, gen_optim = self.optimizers()\n images = batch.images\n masks = batch.masks.unsqueeze(dim=1)\n\n X_coarse, X_recon = self.generator(images, masks)\n X_complete = X_recon * masks + images * (1 - masks)\n\n # discriminator step\n X_disc_input = torch.cat([images, X_complete.detach()], dim=0)\n X_disc_masks = torch.cat([masks, masks], dim=0)\n X_disc_out = self.discriminator(X_disc_input, X_disc_masks)\n X_real, X_fake = torch.chunk(X_disc_out, chunks=2, dim=0)\n\n dis_real_loss = torch.mean(F.relu(1 - X_real))\n dis_fake_loss = torch.mean(F.relu(1 + X_fake))\n dis_loss = dis_real_loss + dis_fake_loss\n\n dis_optim.zero_grad()\n self.manual_backward(dis_loss, retain_graph=True)\n dis_optim.step()\n\n # generator step\n X_fake = self.discriminator(X_complete, masks)\n gen_gan_loss = -1 * torch.mean(X_fake)\n gen_rec_loss = recon_loss(images, X_coarse, X_recon, masks)\n gen_loss = gen_gan_loss + gen_rec_loss\n\n gen_optim.zero_grad()\n self.manual_backward(gen_loss)\n gen_optim.step()\n\n self.log('gen_gan_loss', gen_loss.item())\n self.log('gen_rec_loss', gen_rec_loss.item())\n self.log('gen_all_loss', gen_loss.item())\n self.log('disc_real_loss', dis_real_loss.item())\n self.log('disc_fake_loss', dis_fake_loss.item())\n self.log('disc_all_loss', dis_loss.item())\n\n def validation_step(self, batch: Batch, batch_idx: int) -> Dict[str, Any]:\n images = batch.images\n masks = batch.masks.unsqueeze(dim=1)\n\n X_coarse, X_recon = self.generator(images, masks)\n X_complete = X_recon * masks + images * (1 - masks)\n\n return {\n 'origin': images.detach().cpu().to(torch.float32),\n 'mask': masks.detach().cpu().to(torch.float32),\n 'coarse': X_coarse.detach().cpu().to(torch.float32),\n 'complete': X_complete.detach().cpu().to(torch.float32),\n }\n\n def validation_epoch_end(self, outputs: List[Dict[str, Any]]):\n n_batches = len(outputs)\n columns = ['origin', 'mask', 'coarse', 'complete']\n table = wandb.Table(columns=columns)\n\n for idx in range(n_batches):\n origins = outputs[idx]['origin']\n masks = outputs[idx]['mask']\n coarses = outputs[idx]['coarse']\n completes = outputs[idx]['complete']\n\n iterator = zip(origins, masks, coarses, completes)\n\n for origin, mask, coarse, complete in iterator:\n table.add_data(\n wandb.Image(origin),\n wandb.Image(mask),\n wandb.Image(coarse),\n wandb.Image(complete),\n )\n\n current_epoch = self.current_epoch\n metrics = {f'samples_{current_epoch:02d}': table}\n self.logger.log_metrics(metrics)\n"
]
| [
[
"torch.mean",
"torch.cat",
"torch.utils.data.DataLoader",
"torch.nn.functional.relu",
"torch.chunk"
]
]
|
VSAnimator/stgan | [
"afadc2356002092eed16d737a2ed0cb02dc94821"
]
| [
"models/networks_branched.py"
]
| [
"import torch\nimport torch.nn as nn\nfrom torch.nn import init\nimport functools\nfrom torch.optim import lr_scheduler\n\n\n###############################################################################\n# Helper Functions\n###############################################################################\ndef get_norm_layer(norm_type='instance'):\n \"\"\"Return a normalization layer\n\n Parameters:\n norm_type (str) -- the name of the normalization layer: batch | instance | none\n\n For BatchNorm, we use learnable affine parameters and track running statistics (mean/stddev).\n For InstanceNorm, we do not use learnable affine parameters. We do not track running statistics.\n \"\"\"\n if norm_type == 'batch':\n norm_layer = functools.partial(nn.BatchNorm2d, affine=True, track_running_stats=True)\n elif norm_type == 'instance':\n norm_layer = functools.partial(nn.InstanceNorm2d, affine=False, track_running_stats=False)\n elif norm_type == 'none':\n norm_layer = None\n else:\n raise NotImplementedError('normalization layer [%s] is not found' % norm_type)\n return norm_layer\n\n\ndef get_scheduler(optimizer, opt):\n \"\"\"Return a learning rate scheduler\n\n Parameters:\n optimizer -- the optimizer of the network\n opt (option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions. \n opt.lr_policy is the name of learning rate policy: linear | step | plateau | cosine\n\n For 'linear', we keep the same learning rate for the first <opt.niter> epochs\n and linearly decay the rate to zero over the next <opt.niter_decay> epochs.\n For other schedulers (step, plateau, and cosine), we use the default PyTorch schedulers.\n See https://pytorch.org/docs/stable/optim.html for more details.\n \"\"\"\n if opt.lr_policy == 'linear':\n def lambda_rule(epoch):\n lr_l = 1.0 - max(0, epoch + opt.epoch_count - opt.niter) / float(opt.niter_decay + 1)\n return lr_l\n scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda_rule)\n elif opt.lr_policy == 'step':\n scheduler = lr_scheduler.StepLR(optimizer, step_size=opt.lr_decay_iters, gamma=0.1)\n elif opt.lr_policy == 'plateau':\n scheduler = lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.2, threshold=0.01, patience=5)\n elif opt.lr_policy == 'cosine':\n scheduler = lr_scheduler.CosineAnnealingLR(optimizer, T_max=opt.niter, eta_min=0)\n else:\n return NotImplementedError('learning rate policy [%s] is not implemented', opt.lr_policy)\n return scheduler\n\n\ndef init_weights(net, init_type='normal', init_gain=0.02):\n \"\"\"Initialize network weights.\n\n Parameters:\n net (network) -- network to be initialized\n init_type (str) -- the name of an initialization method: normal | xavier | kaiming | orthogonal\n init_gain (float) -- scaling factor for normal, xavier and orthogonal.\n\n We use 'normal' in the original pix2pix and CycleGAN paper. But xavier and kaiming might\n work better for some applications. Feel free to try yourself.\n \"\"\"\n def init_func(m): # define the initialization function\n classname = m.__class__.__name__\n if hasattr(m, 'weight') and (classname.find('Conv') != -1 or classname.find('Linear') != -1):\n if init_type == 'normal':\n init.normal_(m.weight.data, 0.0, init_gain)\n elif init_type == 'xavier':\n init.xavier_normal_(m.weight.data, gain=init_gain)\n elif init_type == 'kaiming':\n init.kaiming_normal_(m.weight.data, a=0, mode='fan_in')\n elif init_type == 'orthogonal':\n init.orthogonal_(m.weight.data, gain=init_gain)\n else:\n raise NotImplementedError('initialization method [%s] is not implemented' % init_type)\n if hasattr(m, 'bias') and m.bias is not None:\n init.constant_(m.bias.data, 0.0)\n elif classname.find('BatchNorm2d') != -1: # BatchNorm Layer's weight is not a matrix; only normal distribution applies.\n init.normal_(m.weight.data, 1.0, init_gain)\n init.constant_(m.bias.data, 0.0)\n\n print('initialize network with %s' % init_type)\n net.apply(init_func) # apply the initialization function <init_func>\n\n\ndef init_net(net, init_type='normal', init_gain=0.02, gpu_ids=[]):\n \"\"\"Initialize a network: 1. register CPU/GPU device (with multi-GPU support); 2. initialize the network weights\n Parameters:\n net (network) -- the network to be initialized\n init_type (str) -- the name of an initialization method: normal | xavier | kaiming | orthogonal\n gain (float) -- scaling factor for normal, xavier and orthogonal.\n gpu_ids (int list) -- which GPUs the network runs on: e.g., 0,1,2\n\n Return an initialized network.\n \"\"\"\n if len(gpu_ids) > 0:\n assert(torch.cuda.is_available())\n net.to(gpu_ids[0])\n net = torch.nn.DataParallel(net, gpu_ids) # multi-GPUs\n init_weights(net, init_type, init_gain=init_gain)\n return net\n\n\ndef define_G(input_nc, output_nc, ngf, netG, norm='batch', use_dropout=False, init_type='normal', init_gain=0.02, gpu_ids=[]):\n \"\"\"Create a generator\n\n Parameters:\n input_nc (int) -- the number of channels in input images\n output_nc (int) -- the number of channels in output images\n ngf (int) -- the number of filters in the last conv layer\n netG (str) -- the architecture's name: resnet_9blocks | resnet_6blocks | unet_256 | unet_128\n norm (str) -- the name of normalization layers used in the network: batch | instance | none\n use_dropout (bool) -- if use dropout layers.\n init_type (str) -- the name of our initialization method.\n init_gain (float) -- scaling factor for normal, xavier and orthogonal.\n gpu_ids (int list) -- which GPUs the network runs on: e.g., 0,1,2\n\n Returns a generator\n\n Our current implementation provides two types of generators:\n U-Net: [unet_128] (for 128x128 input images) and [unet_256] (for 256x256 input images)\n The original U-Net paper: https://arxiv.org/abs/1505.04597\n\n Resnet-based generator: [resnet_6blocks] (with 6 Resnet blocks) and [resnet_9blocks] (with 9 Resnet blocks)\n Resnet-based generator consists of several Resnet blocks between a few downsampling/upsampling operations.\n We adapt Torch code from Justin Johnson's neural style transfer project (https://github.com/jcjohnson/fast-neural-style).\n\n\n The generator has been initialized by <init_net>. It uses RELU for non-linearity.\n \"\"\"\n net = None\n norm_layer = get_norm_layer(norm_type=norm)\n\n if netG == 'resnet_9blocks':\n net = ResnetGenerator(input_nc, output_nc, ngf, norm_layer=norm_layer, use_dropout=use_dropout, n_blocks=9)\n elif netG == 'resnet_6blocks':\n net = ResnetGenerator(input_nc, output_nc, ngf, norm_layer=norm_layer, use_dropout=use_dropout, n_blocks=6)\n elif netG == 'unet_128':\n net = UnetGenerator(input_nc, output_nc, 7, ngf, norm_layer=norm_layer, use_dropout=use_dropout)\n elif netG == 'unet_256':\n net = UnetBranchedGenerator(input_nc, output_nc, 8, ngf, norm_layer=norm_layer, use_dropout=use_dropout)\n elif netG == 'unet_256_independent':\n net = UnetIndependentBranchedGenerator(input_nc, output_nc, 8, ngf, norm_layer=norm_layer, use_dropout=use_dropout)\n elif netG == 'independent_resnet_9blocks':\n net = IndependentResnetGenerator(input_nc, output_nc, ngf, norm_layer=norm_layer, use_dropout=use_dropout, n_blocks=9)\n else:\n raise NotImplementedError('Generator model name [%s] is not recognized' % netG)\n return init_net(net, init_type, init_gain, gpu_ids)\n\n\ndef define_D(input_nc, ndf, netD, n_layers_D=3, norm='batch', init_type='normal', init_gain=0.02, gpu_ids=[]):\n \"\"\"Create a discriminator\n\n Parameters:\n input_nc (int) -- the number of channels in input images\n ndf (int) -- the number of filters in the first conv layer\n netD (str) -- the architecture's name: basic | n_layers | pixel\n n_layers_D (int) -- the number of conv layers in the discriminator; effective when netD=='n_layers'\n norm (str) -- the type of normalization layers used in the network.\n init_type (str) -- the name of the initialization method.\n init_gain (float) -- scaling factor for normal, xavier and orthogonal.\n gpu_ids (int list) -- which GPUs the network runs on: e.g., 0,1,2\n\n Returns a discriminator\n\n Our current implementation provides three types of discriminators:\n [basic]: 'PatchGAN' classifier described in the original pix2pix paper.\n It can classify whether 70×70 overlapping patches are real or fake.\n Such a patch-level discriminator architecture has fewer parameters\n than a full-image discriminator and can work on arbitrarily-sized images\n in a fully convolutional fashion.\n\n [n_layers]: With this mode, you cna specify the number of conv layers in the discriminator\n with the parameter <n_layers_D> (default=3 as used in [basic] (PatchGAN).)\n\n [pixel]: 1x1 PixelGAN discriminator can classify whether a pixel is real or not.\n It encourages greater color diversity but has no effect on spatial statistics.\n\n The discriminator has been initialized by <init_net>. It uses Leakly RELU for non-linearity.\n \"\"\"\n net = None\n norm_layer = get_norm_layer(norm_type=norm)\n\n if netD == 'basic': # default PatchGAN classifier\n net = NLayerDiscriminator(input_nc, ndf, n_layers=3, norm_layer=norm_layer)\n elif netD == 'n_layers': # more options\n net = NLayerDiscriminator(input_nc, ndf, n_layers_D, norm_layer=norm_layer)\n elif netD == 'pixel': # classify if each pixel is real or fake\n net = PixelDiscriminator(input_nc, ndf, norm_layer=norm_layer)\n else:\n raise NotImplementedError('Discriminator model name [%s] is not recognized' % net)\n return init_net(net, init_type, init_gain, gpu_ids)\n\n\n##############################################################################\n# Classes\n##############################################################################\nclass GANLoss(nn.Module):\n \"\"\"Define different GAN objectives.\n\n The GANLoss class abstracts away the need to create the target label tensor\n that has the same size as the input.\n \"\"\"\n\n def __init__(self, gan_mode, target_real_label=1.0, target_fake_label=0.0):\n \"\"\" Initialize the GANLoss class.\n\n Parameters:\n gan_mode (str) - - the type of GAN objective. It currently supports vanilla, lsgan, and wgangp.\n target_real_label (bool) - - label for a real image\n target_fake_label (bool) - - label of a fake image\n\n Note: Do not use sigmoid as the last layer of Discriminator.\n LSGAN needs no sigmoid. vanilla GANs will handle it with BCEWithLogitsLoss.\n \"\"\"\n super(GANLoss, self).__init__()\n self.register_buffer('real_label', torch.tensor(target_real_label))\n self.register_buffer('fake_label', torch.tensor(target_fake_label))\n self.gan_mode = gan_mode\n if gan_mode == 'lsgan':\n self.loss = nn.MSELoss()\n elif gan_mode == 'vanilla':\n self.loss = nn.BCEWithLogitsLoss()\n elif gan_mode in ['wgangp']:\n self.loss = None\n else:\n raise NotImplementedError('gan mode %s not implemented' % gan_mode)\n\n def get_target_tensor(self, prediction, target_is_real):\n \"\"\"Create label tensors with the same size as the input.\n\n Parameters:\n prediction (tensor) - - tpyically the prediction from a discriminator\n target_is_real (bool) - - if the ground truth label is for real images or fake images\n\n Returns:\n A label tensor filled with ground truth label, and with the size of the input\n \"\"\"\n\n if target_is_real:\n target_tensor = self.real_label\n else:\n target_tensor = self.fake_label\n return target_tensor.expand_as(prediction)\n\n def __call__(self, prediction, target_is_real):\n \"\"\"Calculate loss given Discriminator's output and grount truth labels.\n\n Parameters:\n prediction (tensor) - - tpyically the prediction output from a discriminator\n target_is_real (bool) - - if the ground truth label is for real images or fake images\n\n Returns:\n the calculated loss.\n \"\"\"\n if self.gan_mode in ['lsgan', 'vanilla']:\n target_tensor = self.get_target_tensor(prediction, target_is_real)\n loss = self.loss(prediction, target_tensor)\n elif self.gan_mode == 'wgangp':\n if target_is_real:\n loss = -prediction.mean()\n else:\n loss = prediction.mean()\n return loss\n\n\ndef cal_gradient_penalty(netD, real_data, fake_data, device, type='mixed', constant=1.0, lambda_gp=10.0):\n \"\"\"Calculate the gradient penalty loss, used in WGAN-GP paper https://arxiv.org/abs/1704.00028\n\n Arguments:\n netD (network) -- discriminator network\n real_data (tensor array) -- real images\n fake_data (tensor array) -- generated images from the generator\n device (str) -- GPU / CPU: from torch.device('cuda:{}'.format(self.gpu_ids[0])) if self.gpu_ids else torch.device('cpu')\n type (str) -- if we mix real and fake data or not [real | fake | mixed].\n constant (float) -- the constant used in formula ( | |gradient||_2 - constant)^2\n lambda_gp (float) -- weight for this loss\n\n Returns the gradient penalty loss\n \"\"\"\n if lambda_gp > 0.0:\n if type == 'real': # either use real images, fake images, or a linear interpolation of two.\n interpolatesv = real_data\n elif type == 'fake':\n interpolatesv = fake_data\n elif type == 'mixed':\n alpha = torch.rand(real_data.shape[0], 1)\n alpha = alpha.expand(real_data.shape[0], real_data.nelement() // real_data.shape[0]).contiguous().view(*real_data.shape)\n alpha = alpha.to(device)\n interpolatesv = alpha * real_data + ((1 - alpha) * fake_data)\n else:\n raise NotImplementedError('{} not implemented'.format(type))\n interpolatesv.requires_grad_(True)\n disc_interpolates = netD(interpolatesv)\n gradients = torch.autograd.grad(outputs=disc_interpolates, inputs=interpolatesv,\n grad_outputs=torch.ones(disc_interpolates.size()).to(device),\n create_graph=True, retain_graph=True, only_inputs=True)\n gradients = gradients[0].view(real_data.size(0), -1) # flat the data\n gradient_penalty = (((gradients + 1e-16).norm(2, dim=1) - constant) ** 2).mean() * lambda_gp # added eps\n return gradient_penalty, gradients\n else:\n return 0.0, None\n\nclass IndependentResnetGenerator(nn.Module):\n \"\"\"Resnet-based generator that consists of Resnet blocks between a few downsampling/upsampling operations.\n\n We adapt Torch code and idea from Justin Johnson's neural style transfer project(https://github.com/jcjohnson/fast-neural-style)\n \"\"\"\n\n def __init__(self, input_nc, output_nc, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False, n_blocks=6, padding_type='reflect'):\n \"\"\"Construct a Resnet-based generator\n\n Parameters:\n input_nc (int) -- the number of channels in input images\n output_nc (int) -- the number of channels in output images\n ngf (int) -- the number of filters in the last conv layer\n norm_layer -- normalization layer\n use_dropout (bool) -- if use dropout layers\n n_blocks (int) -- the number of ResNet blocks\n padding_type (str) -- the name of padding layer in conv layers: reflect | replicate | zero\n \"\"\"\n assert(n_blocks >= 0)\n super(IndependentResnetGenerator, self).__init__()\n if type(norm_layer) == functools.partial:\n use_bias = norm_layer.func == nn.InstanceNorm2d\n else:\n use_bias = norm_layer == nn.InstanceNorm2d\n\n model_initial = [nn.ReflectionPad2d(3),\n nn.Conv2d(input_nc, ngf, kernel_size=7, padding=0, bias=use_bias),\n norm_layer(ngf),\n nn.ReLU(True)]\n\n n_downsampling = 2\n model_intermediate = []\n for i in range(n_downsampling): # add downsampling layers\n mult = 2 ** i\n model_intermediate += [nn.Conv2d(2 * ngf * mult, 2 * ngf * mult * 2, kernel_size=3, stride=2, padding=1, bias=use_bias),\n norm_layer(2 * ngf * mult * 2),\n nn.ReLU(True)]\n\n mult = 2 ** n_downsampling\n for i in range(n_blocks): # add ResNet blocks\n model_intermediate += [ResnetBlock(2 * ngf * mult, padding_type=padding_type, norm_layer=norm_layer, use_dropout=use_dropout, use_bias=use_bias)]\n\n model_final = []\n for i in range(n_downsampling): # add upsampling layers\n mult = 2 ** (n_downsampling - i)\n model_final += [nn.ConvTranspose2d(6 * ngf * mult, int(6 * ngf * mult / 2),\n kernel_size=3, stride=2,\n padding=1, output_padding=1,\n bias=use_bias),\n norm_layer(int(6 * ngf * mult / 2)),\n nn.ReLU(True)]\n model_final += [nn.ReflectionPad2d(3)]\n model_final += [nn.Conv2d(6 * ngf, output_nc, kernel_size=7, padding=0)]\n model_final += [nn.Tanh()]\n\n self.model_initial_0 = nn.Sequential(*model_initial)\n self.model_initial_1 = nn.Sequential(*model_initial)\n self.model_initial_2 = nn.Sequential(*model_initial)\n self.model_intermediate_01 = nn.Sequential(*model_intermediate)\n self.model_intermediate_02 = nn.Sequential(*model_intermediate)\n self.model_intermediate_12 = nn.Sequential(*model_intermediate)\n self.model_final = nn.Sequential(*model_final)\n\n def forward(self, input):\n \"\"\"Standard forward\"\"\"\n input_0 = input[0]\n input_1 = input[1]\n input_2 = input[2] \n output_0 = self.model_initial_0(input_0)\n output_1 = self.model_initial_1(input_1)\n output_2 = self.model_initial_2(input_2)\n intermediate_input_01 = torch.cat((output_0, output_1), 1)\n intermediate_input_02 = torch.cat((output_0, output_2), 1)\n intermediate_input_12 = torch.cat((output_1, output_2), 1)\n output_intermediate_0 = self.model_intermediate_01(intermediate_input_01)\n output_intermediate_1 = self.model_intermediate_02(intermediate_input_02)\n output_intermediate_2 = self.model_intermediate_12(intermediate_input_12)\n return self.model_final(torch.cat((output_intermediate_0, output_intermediate_1, output_intermediate_2), 1))\t\n\n\nclass ResnetGenerator(nn.Module):\n \"\"\"Resnet-based generator that consists of Resnet blocks between a few downsampling/upsampling operations.\n\n We adapt Torch code and idea from Justin Johnson's neural style transfer project(https://github.com/jcjohnson/fast-neural-style)\n \"\"\"\n\n def __init__(self, input_nc, output_nc, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False, n_blocks=6, padding_type='reflect'):\n \"\"\"Construct a Resnet-based generator\n\n Parameters:\n input_nc (int) -- the number of channels in input images\n output_nc (int) -- the number of channels in output images\n ngf (int) -- the number of filters in the last conv layer\n norm_layer -- normalization layer\n use_dropout (bool) -- if use dropout layers\n n_blocks (int) -- the number of ResNet blocks\n padding_type (str) -- the name of padding layer in conv layers: reflect | replicate | zero\n \"\"\"\n assert(n_blocks >= 0)\n super(ResnetGenerator, self).__init__()\n if type(norm_layer) == functools.partial:\n use_bias = norm_layer.func == nn.InstanceNorm2d\n else:\n use_bias = norm_layer == nn.InstanceNorm2d\n\n model_initial = [nn.ReflectionPad2d(3),\n nn.Conv2d(input_nc, ngf, kernel_size=7, padding=0, bias=use_bias),\n norm_layer(ngf),\n nn.ReLU(True)]\n\n n_downsampling = 3\n model_intermediate = []\n for i in range(n_downsampling): # add downsampling layers\n mult = 2 ** i\n model_intermediate += [nn.Conv2d(2 * ngf * mult, 2 * ngf * mult * 2, kernel_size=3, stride=2, padding=1, bias=use_bias),\n norm_layer(2 * ngf * mult * 2),\n nn.ReLU(True)]\n\n mult = 2 ** n_downsampling\n for i in range(n_blocks): # add ResNet blocks\n model_intermediate += [ResnetBlock(2 * ngf * mult, padding_type=padding_type, norm_layer=norm_layer, use_dropout=use_dropout, use_bias=use_bias)]\n\n model_final = []\n for i in range(n_downsampling): # add upsampling layers\n mult = 2 ** (n_downsampling - i)\n model_final += [nn.ConvTranspose2d(6 * ngf * mult, int(6 * ngf * mult / 2),\n kernel_size=3, stride=2,\n padding=1, output_padding=1,\n bias=use_bias),\n norm_layer(int(6 * ngf * mult / 2)),\n nn.ReLU(True)]\n model_final += [nn.ReflectionPad2d(3)]\n model_final += [nn.Conv2d(6 * ngf, output_nc, kernel_size=7, padding=0)]\n model_final += [nn.Tanh()]\n\n self.model_initial = nn.Sequential(*model_initial)\n self.model_intermediate = nn.Sequential(*model_intermediate)\n self.model_final = nn.Sequential(*model_final)\n\n def forward(self, input):\n \"\"\"Standard forward\"\"\"\n input_0 = input[0]\n input_1 = input[1]\n input_2 = input[2] \n output_0 = self.model_initial(input_0)\n output_1 = self.model_initial(input_1)\n output_2 = self.model_initial(input_2)\n intermediate_input_01 = torch.cat((output_0, output_1), 1)\n intermediate_input_02 = torch.cat((output_0, output_2), 1)\n intermediate_input_12 = torch.cat((output_1, output_2), 1)\n output_intermediate_0 = self.model_intermediate(intermediate_input_01)\n output_intermediate_1 = self.model_intermediate(intermediate_input_02)\n output_intermediate_2 = self.model_intermediate(intermediate_input_12)\n return self.model_final(torch.cat((output_intermediate_0, output_intermediate_1, output_intermediate_2), 1))\t\n\n\nclass ResnetBlock(nn.Module):\n \"\"\"Define a Resnet block\"\"\"\n\n def __init__(self, dim, padding_type, norm_layer, use_dropout, use_bias):\n \"\"\"Initialize the Resnet block\n\n A resnet block is a conv block with skip connections\n We construct a conv block with build_conv_block function,\n and implement skip connections in <forward> function.\n Original Resnet paper: https://arxiv.org/pdf/1512.03385.pdf\n \"\"\"\n super(ResnetBlock, self).__init__()\n self.conv_block = self.build_conv_block(dim, padding_type, norm_layer, use_dropout, use_bias)\n\n def build_conv_block(self, dim, padding_type, norm_layer, use_dropout, use_bias):\n \"\"\"Construct a convolutional block.\n\n Parameters:\n dim (int) -- the number of channels in the conv layer.\n padding_type (str) -- the name of padding layer: reflect | replicate | zero\n norm_layer -- normalization layer\n use_dropout (bool) -- if use dropout layers.\n use_bias (bool) -- if the conv layer uses bias or not\n\n Returns a conv block (with a conv layer, a normalization layer, and a non-linearity layer (ReLU))\n \"\"\"\n conv_block = []\n p = 0\n if padding_type == 'reflect':\n conv_block += [nn.ReflectionPad2d(1)]\n elif padding_type == 'replicate':\n conv_block += [nn.ReplicationPad2d(1)]\n elif padding_type == 'zero':\n p = 1\n else:\n raise NotImplementedError('padding [%s] is not implemented' % padding_type)\n\n conv_block += [nn.Conv2d(dim, dim, kernel_size=3, padding=p, bias=use_bias), norm_layer(dim), nn.ReLU(True)]\n if use_dropout:\n conv_block += [nn.Dropout(0.5)]\n\n p = 0\n if padding_type == 'reflect':\n conv_block += [nn.ReflectionPad2d(1)]\n elif padding_type == 'replicate':\n conv_block += [nn.ReplicationPad2d(1)]\n elif padding_type == 'zero':\n p = 1\n else:\n raise NotImplementedError('padding [%s] is not implemented' % padding_type)\n conv_block += [nn.Conv2d(dim, dim, kernel_size=3, padding=p, bias=use_bias), norm_layer(dim)]\n\n return nn.Sequential(*conv_block)\n\n def forward(self, x):\n \"\"\"Forward function (with skip connections)\"\"\"\n out = x + self.conv_block(x) # add skip connections\n return out\n\nclass UnetGenerator(nn.Module):\n \"\"\"Create a Unet-based generator\"\"\"\n\n def __init__(self, input_nc, output_nc, num_downs, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False):\n \"\"\"Construct a Unet generator\n Parameters:\n input_nc (int) -- the number of channels in input images\n output_nc (int) -- the number of channels in output images\n num_downs (int) -- the number of downsamplings in UNet. For example, # if |num_downs| == 7,\n image of size 128x128 will become of size 1x1 # at the bottleneck\n ngf (int) -- the number of filters in the last conv layer\n norm_layer -- normalization layer\n\n We construct the U-Net from the innermost layer to the outermost layer.\n It is a recursive process.\n \"\"\"\n super(UnetGenerator, self).__init__()\n\n '''\n # construct unet structure\n unet_block = UnetSkipConnectionBlock(ngf * 8, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer, innermost=True) # add the innermost layer\n for i in range(num_downs - 5): # add intermediate layers with ngf * 8 filters\n unet_block = UnetSkipConnectionBlock(ngf * 8, ngf * 8, input_nc=None, submodule=unet_block, norm_layer=norm_layer, use_dropout=use_dropout)\n # gradually reduce the number of filters from ngf * 8 to ngf\n unet_block = UnetSkipConnectionBlock(ngf * 4, ngf * 8, input_nc=None, submodule=unet_block, norm_layer=norm_layer)\n unet_block = UnetSkipConnectionBlock(ngf * 2, ngf * 4, input_nc=None, submodule=unet_block, norm_layer=norm_layer)\n unet_block = UnetSkipConnectionBlock(ngf, ngf * 2, input_nc=None, submodule=unet_block, norm_layer=norm_layer)\n self.model = UnetSkipConnectionBlock(output_nc, ngf, input_nc=input_nc, submodule=unet_block, outermost=True, norm_layer=norm_layer) # add the outermost layer\n '''\n\n self.down8 = UnetSkipConnectionBlockDown(ngf * 8, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer, innermost=True) # add the innermost layer\n self.down7 = UnetSkipConnectionBlockDown(ngf * 8, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer) # add the innermost layer\n self.down6 = UnetSkipConnectionBlockDown(ngf * 8, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer) # add the innermost layer\n self.down5 = UnetSkipConnectionBlockDown(ngf * 8, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer) # add the innermost layer\n self.down4 = UnetSkipConnectionBlockDown(ngf * 4, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer)\n self.down3 = UnetSkipConnectionBlockDown(ngf * 2, ngf * 4, input_nc=None, submodule=None, norm_layer=norm_layer)\n self.down2 = UnetSkipConnectionBlockDown(ngf, ngf * 2, input_nc=None, submodule=None, norm_layer=norm_layer)\n self.down1 = UnetSkipConnectionBlockDown(output_nc, ngf, input_nc=input_nc, submodule=None, outermost=True, norm_layer=norm_layer) # add the outermost layer\n \n self.up8 = UnetSkipConnectionBlockUp(ngf * 8, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer, innermost=True) # add the innermost layer\n self.up7 = UnetSkipConnectionBlockUp(ngf * 8, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer) # add the innermost layer\n self.up6 = UnetSkipConnectionBlockUp(ngf * 8, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer) # add the innermost layer\n self.up5 = UnetSkipConnectionBlockUp(ngf * 8, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer) # add the innermost layer\n self.up4 = UnetSkipConnectionBlockUp(ngf * 4, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer)\n self.up3 = UnetSkipConnectionBlockUp(ngf * 2, ngf * 4, input_nc=None, submodule=None, norm_layer=norm_layer)\n self.up2 = UnetSkipConnectionBlockUp(ngf, ngf * 2, input_nc=None, submodule=None, norm_layer=norm_layer)\n self.up1 = UnetSkipConnectionBlockUp(output_nc, ngf, input_nc=input_nc, submodule=None, outermost=True, norm_layer=norm_layer) # add the outermost layer\n \n\n def forward(self, x):\n \"\"\"Standard forward\"\"\"\n x1 = self.down1(x)\n x2 = self.down2(x1)\n x3 = self.down3(x2)\n x4 = self.down4(x3)\n x5 = self.down5(x4)\n x6 = self.down6(x5)\n x7 = self.down7(x6)\n x8 = self.down8(x7)\n x = self.up8(x8, x7)\n x = self.up7(x, x6)\n x = self.up6(x, x5)\n x = self.up5(x, x4)\n x = self.up4(x, x3)\n x = self.up3(x, x2)\n x = self.up2(x, x1)\n x = self.up1(x, x)\n return x\n\nclass UnetSkipConnectionBlockDown(nn.Module):\n \"\"\"Defines the Unet submodule with skip connection.\n X -------------------identity----------------------\n |-- downsampling -- |submodule| -- upsampling --|\n \"\"\"\n\n def __init__(self, outer_nc, inner_nc, input_nc=None,\n submodule=None, outermost=False, innermost=False, norm_layer=nn.BatchNorm2d, use_dropout=False):\n \"\"\"Construct a Unet submodule with skip connections.\n\n Parameters:\n outer_nc (int) -- the number of filters in the outer conv layer\n inner_nc (int) -- the number of filters in the inner conv layer\n input_nc (int) -- the number of channels in input images/features\n submodule (UnetSkipConnectionBlock) -- previously defined submodules\n outermost (bool) -- if this module is the outermost module\n innermost (bool) -- if this module is the innermost module\n norm_layer -- normalization layer\n user_dropout (bool) -- if use dropout layers.\n \"\"\"\n super(UnetSkipConnectionBlockDown, self).__init__()\n self.outermost = outermost\n if type(norm_layer) == functools.partial:\n use_bias = norm_layer.func == nn.InstanceNorm2d\n else:\n use_bias = norm_layer == nn.InstanceNorm2d\n if input_nc is None:\n input_nc = outer_nc\n downconv = nn.Conv2d(input_nc, inner_nc, kernel_size=4,\n stride=2, padding=1, bias=use_bias)\n downrelu = nn.LeakyReLU(0.2, True)\n downnorm = norm_layer(inner_nc)\n uprelu = nn.ReLU(True)\n upnorm = norm_layer(outer_nc)\n\n if outermost:\n upconv = nn.ConvTranspose2d(inner_nc * 2, outer_nc,\n kernel_size=4, stride=2,\n padding=1)\n down = [downconv]\n up = [uprelu, upconv, nn.Tanh()]\n model = down\n elif innermost:\n upconv = nn.ConvTranspose2d(inner_nc, outer_nc,\n kernel_size=4, stride=2,\n padding=1, bias=use_bias)\n down = [downrelu, downconv]\n up = [uprelu, upconv, upnorm]\n model = down\n else:\n upconv = nn.ConvTranspose2d(inner_nc * 2, outer_nc,\n kernel_size=4, stride=2,\n padding=1, bias=use_bias)\n down = [downrelu, downconv, downnorm]\n up = [uprelu, upconv, upnorm]\n\n if use_dropout:\n model = down\n else:\n model = down\n\n self.model = nn.Sequential(*model)\n\n def forward(self, x):\n return self.model(x)\n\nclass UnetSkipConnectionBlockUp(nn.Module):\n \"\"\"Defines the Unet submodule with skip connection.\n X -------------------identity----------------------\n |-- downsampling -- |submodule| -- upsampling --|\n \"\"\"\n\n def __init__(self, outer_nc, inner_nc, input_nc=None,\n submodule=None, outermost=False, innermost=False, norm_layer=nn.BatchNorm2d, use_dropout=False):\n \"\"\"Construct a Unet submodule with skip connections.\n\n Parameters:\n outer_nc (int) -- the number of filters in the outer conv layer\n inner_nc (int) -- the number of filters in the inner conv layer\n input_nc (int) -- the number of channels in input images/features\n submodule (UnetSkipConnectionBlock) -- previously defined submodules\n outermost (bool) -- if this module is the outermost module\n innermost (bool) -- if this module is the innermost module\n norm_layer -- normalization layer\n user_dropout (bool) -- if use dropout layers.\n \"\"\"\n super(UnetSkipConnectionBlockUp, self).__init__()\n self.outermost = outermost\n if type(norm_layer) == functools.partial:\n use_bias = norm_layer.func == nn.InstanceNorm2d\n else:\n use_bias = norm_layer == nn.InstanceNorm2d\n if input_nc is None:\n input_nc = outer_nc\n downconv = nn.Conv2d(input_nc, inner_nc, kernel_size=4,\n stride=2, padding=1, bias=use_bias)\n downrelu = nn.LeakyReLU(0.2, True)\n downnorm = norm_layer(inner_nc)\n uprelu = nn.ReLU(True)\n upnorm = norm_layer(outer_nc)\n\n if outermost:\n upconv = nn.ConvTranspose2d(inner_nc * 2, outer_nc,\n kernel_size=4, stride=2,\n padding=1)\n down = [downconv]\n up = [uprelu, upconv, nn.Tanh()]\n model = up\n elif innermost:\n upconv = nn.ConvTranspose2d(inner_nc, outer_nc,\n kernel_size=4, stride=2,\n padding=1, bias=use_bias)\n down = [downrelu, downconv]\n up = [uprelu, upconv, upnorm]\n model = up\n else:\n upconv = nn.ConvTranspose2d(inner_nc * 2, outer_nc,\n kernel_size=4, stride=2,\n padding=1, bias=use_bias)\n down = [downrelu, downconv, downnorm]\n up = [uprelu, upconv, upnorm]\n\n if use_dropout:\n model = up + [nn.Dropout(0.5)]\n else:\n model = up\n\n self.model = nn.Sequential(*model)\n\n def forward(self, x1, x2):\n if self.outermost:\n return self.model(x1)\n else: # add skip connections\n return torch.cat([x2, self.model(x1)], 1)\n\nclass UnetIndependentBranchedGenerator(nn.Module):\n \"\"\"Create a Unet-based generator\"\"\"\n\n def __init__(self, input_nc, output_nc, num_downs, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False):\n \"\"\"Construct a Unet generator\n Parameters:\n input_nc (int) -- the number of channels in input images\n output_nc (int) -- the number of channels in output images\n num_downs (int) -- the number of downsamplings in UNet. For example, # if |num_downs| == 7,\n image of size 128x128 will become of size 1x1 # at the bottleneck\n ngf (int) -- the number of filters in the last conv layer\n norm_layer -- normalization layer\n\n We construct the U-Net from the innermost layer to the outermost layer.\n It is a recursive process.\n \"\"\"\n super(UnetIndependentBranchedGenerator, self).__init__()\n\n '''\n # construct unet structure\n unet_block = UnetSkipConnectionBlock(ngf * 8, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer, innermost=True) # add the innermost layer\n for i in range(num_downs - 5): # add intermediate layers with ngf * 8 filters\n unet_block = UnetSkipConnectionBlock(ngf * 8, ngf * 8, input_nc=None, submodule=unet_block, norm_layer=norm_layer, use_dropout=use_dropout)\n # gradually reduce the number of filters from ngf * 8 to ngf\n unet_block = UnetSkipConnectionBlock(ngf * 4, ngf * 8, input_nc=None, submodule=unet_block, norm_layer=norm_layer)\n unet_block = UnetSkipConnectionBlock(ngf * 2, ngf * 4, input_nc=None, submodule=unet_block, norm_layer=norm_layer)\n unet_block = UnetSkipConnectionBlock(ngf, ngf * 2, input_nc=None, submodule=unet_block, norm_layer=norm_layer)\n self.model = UnetSkipConnectionBlock(output_nc, ngf, input_nc=input_nc, submodule=unet_block, outermost=True, norm_layer=norm_layer) # add the outermost layer\n '''\n\n self.down8 = UnetIndependentBranchedSkipConnectionBlockDown(ngf * 8, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer, innermost=True) # add the innermost layer\n self.down7 = UnetIndependentBranchedSkipConnectionBlockDown(ngf * 8, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer) # add the innermost layer\n self.down6 = UnetIndependentBranchedSkipConnectionBlockDown(ngf * 8, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer) # add the innermost layer\n self.down5 = UnetIndependentBranchedSkipConnectionBlockDown(ngf * 8, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer) # add the innermost layer\n self.down4 = UnetIndependentBranchedSkipConnectionBlockDown(ngf * 4, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer)\n self.down3 = UnetIndependentBranchedSkipConnectionBlockDown(ngf * 2, ngf * 4, input_nc=None, submodule=None, norm_layer=norm_layer)\n self.down2 = UnetIndependentBranchedSkipConnectionBlockDown(ngf, ngf * 2, input_nc=None, submodule=None, norm_layer=norm_layer)\n self.down1 = UnetIndependentBranchedSkipConnectionBlockDown(output_nc, ngf, input_nc=input_nc, submodule=None, outermost=True, norm_layer=norm_layer) # add the outermost layer\n \n self.up8 = UnetBranchedSkipConnectionBlockUp(ngf * 8, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer, innermost=True) # add the innermost layer\n self.up7 = UnetBranchedSkipConnectionBlockUp(ngf * 8, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer) # add the innermost layer\n self.up6 = UnetBranchedSkipConnectionBlockUp(ngf * 8, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer) # add the innermost layer\n self.up5 = UnetBranchedSkipConnectionBlockUp(ngf * 8, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer) # add the innermost layer\n self.up4 = UnetBranchedSkipConnectionBlockUp(ngf * 4, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer)\n self.up3 = UnetBranchedSkipConnectionBlockUp(ngf * 2, ngf * 4, input_nc=None, submodule=None, norm_layer=norm_layer)\n self.up2 = UnetBranchedSkipConnectionBlockUp(ngf, ngf * 2, input_nc=None, submodule=None, norm_layer=norm_layer)\n self.up1 = UnetBranchedSkipConnectionBlockUp(output_nc, ngf, input_nc=input_nc, submodule=None, outermost=True, norm_layer=norm_layer) # add the outermost layer\n \n\n def forward(self, x):\n \"\"\"Standard forward\"\"\"\n x1 = self.down1(x)\n x2 = self.down2(x1)\n x3 = self.down3(x2)\n x4 = self.down4(x3)\n x5 = self.down5(x4)\n x6 = self.down6(x5)\n x7 = self.down7(x6)\n x8 = self.down8(x7)\n x = self.up8(x8, x7)\n x = self.up7(x, x6)\n x = self.up6(x, x5)\n x = self.up5(x, x4)\n x = self.up4(x, x3)\n x = self.up3(x, x2)\n x = self.up2(x, x1)\n x = self.up1(x, x)\n return x\n\nclass UnetIndependentBranchedSkipConnectionBlockDown(nn.Module):\n \"\"\"Defines the Unet submodule with skip connection.\n X -------------------identity----------------------\n |-- downsampling -- |submodule| -- upsampling --|\n \"\"\"\n\n def __init__(self, outer_nc, inner_nc, input_nc=None,\n submodule=None, outermost=False, innermost=False, norm_layer=nn.BatchNorm2d, use_dropout=False):\n \"\"\"Construct a Unet submodule with skip connections.\n\n Parameters:\n outer_nc (int) -- the number of filters in the outer conv layer\n inner_nc (int) -- the number of filters in the inner conv layer\n input_nc (int) -- the number of channels in input images/features\n submodule (UnetSkipConnectionBlock) -- previously defined submodules\n outermost (bool) -- if this module is the outermost module\n innermost (bool) -- if this module is the innermost module\n norm_layer -- normalization layer\n user_dropout (bool) -- if use dropout layers.\n \"\"\"\n super(UnetIndependentBranchedSkipConnectionBlockDown, self).__init__()\n self.outermost = outermost\n self.innermost = innermost\n if type(norm_layer) == functools.partial:\n use_bias = norm_layer.func == nn.InstanceNorm2d\n else:\n use_bias = norm_layer == nn.InstanceNorm2d\n if input_nc is None:\n input_nc = outer_nc\n downconv = nn.Conv2d(input_nc, inner_nc, kernel_size=4,\n stride=2, padding=1, bias=use_bias)\n downrelu = nn.LeakyReLU(0.2, True)\n downnorm = norm_layer(inner_nc)\n uprelu = nn.ReLU(True)\n upnorm = norm_layer(outer_nc)\n\n if outermost:\n upconv = nn.ConvTranspose2d(inner_nc * 2, outer_nc,\n kernel_size=4, stride=2,\n padding=1)\n down = [downconv]\n up = [uprelu, upconv, nn.Tanh()]\n model = down\n elif innermost:\n upconv = nn.ConvTranspose2d(inner_nc, outer_nc,\n kernel_size=4, stride=2,\n padding=1, bias=use_bias)\n down = [downrelu, downconv]\n up = [uprelu, upconv, upnorm]\n model = down\n else:\n upconv = nn.ConvTranspose2d(inner_nc * 2, outer_nc,\n kernel_size=4, stride=2,\n padding=1, bias=use_bias)\n down = [downrelu, downconv, downnorm]\n up = [uprelu, upconv, upnorm]\n\n if use_dropout:\n model = down\n else:\n model = down\n\n self.model_0 = nn.Sequential(*model)\n self.model_1 = nn.Sequential(*model)\n self.model_2 = nn.Sequential(*model)\n\n def forward(self, x):\n if self.innermost:\n return torch.cat([self.model_0(x[0]), self.model_1(x[1]), self.model_2(x[2])], 1)\n return [self.model_0(x[0]), self.model_1(x[1]), self.model_2(x[2])]\n\nclass UnetBranchedGenerator(nn.Module):\n \"\"\"Create a Unet-based generator\"\"\"\n\n def __init__(self, input_nc, output_nc, num_downs, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False):\n \"\"\"Construct a Unet generator\n Parameters:\n input_nc (int) -- the number of channels in input images\n output_nc (int) -- the number of channels in output images\n num_downs (int) -- the number of downsamplings in UNet. For example, # if |num_downs| == 7,\n image of size 128x128 will become of size 1x1 # at the bottleneck\n ngf (int) -- the number of filters in the last conv layer\n norm_layer -- normalization layer\n\n We construct the U-Net from the innermost layer to the outermost layer.\n It is a recursive process.\n \"\"\"\n super(UnetBranchedGenerator, self).__init__()\n\n '''\n # construct unet structure\n unet_block = UnetSkipConnectionBlock(ngf * 8, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer, innermost=True) # add the innermost layer\n for i in range(num_downs - 5): # add intermediate layers with ngf * 8 filters\n unet_block = UnetSkipConnectionBlock(ngf * 8, ngf * 8, input_nc=None, submodule=unet_block, norm_layer=norm_layer, use_dropout=use_dropout)\n # gradually reduce the number of filters from ngf * 8 to ngf\n unet_block = UnetSkipConnectionBlock(ngf * 4, ngf * 8, input_nc=None, submodule=unet_block, norm_layer=norm_layer)\n unet_block = UnetSkipConnectionBlock(ngf * 2, ngf * 4, input_nc=None, submodule=unet_block, norm_layer=norm_layer)\n unet_block = UnetSkipConnectionBlock(ngf, ngf * 2, input_nc=None, submodule=unet_block, norm_layer=norm_layer)\n self.model = UnetSkipConnectionBlock(output_nc, ngf, input_nc=input_nc, submodule=unet_block, outermost=True, norm_layer=norm_layer) # add the outermost layer\n '''\n\n self.down8 = UnetBranchedSkipConnectionBlockDown(ngf * 8, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer, innermost=True) # add the innermost layer\n self.down7 = UnetBranchedSkipConnectionBlockDown(ngf * 8, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer) # add the innermost layer\n self.down6 = UnetBranchedSkipConnectionBlockDown(ngf * 8, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer) # add the innermost layer\n self.down5 = UnetBranchedSkipConnectionBlockDown(ngf * 8, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer) # add the innermost layer\n self.down4 = UnetBranchedSkipConnectionBlockDown(ngf * 4, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer)\n self.down3 = UnetBranchedSkipConnectionBlockDown(ngf * 2, ngf * 4, input_nc=None, submodule=None, norm_layer=norm_layer)\n self.down2 = UnetBranchedSkipConnectionBlockDown(ngf, ngf * 2, input_nc=None, submodule=None, norm_layer=norm_layer)\n self.down1 = UnetBranchedSkipConnectionBlockDown(output_nc, ngf, input_nc=input_nc, submodule=None, outermost=True, norm_layer=norm_layer) # add the outermost layer\n \n self.up8 = UnetBranchedSkipConnectionBlockUp(ngf * 8, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer, innermost=True) # add the innermost layer\n self.up7 = UnetBranchedSkipConnectionBlockUp(ngf * 8, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer) # add the innermost layer\n self.up6 = UnetBranchedSkipConnectionBlockUp(ngf * 8, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer) # add the innermost layer\n self.up5 = UnetBranchedSkipConnectionBlockUp(ngf * 8, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer) # add the innermost layer\n self.up4 = UnetBranchedSkipConnectionBlockUp(ngf * 4, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer)\n self.up3 = UnetBranchedSkipConnectionBlockUp(ngf * 2, ngf * 4, input_nc=None, submodule=None, norm_layer=norm_layer)\n self.up2 = UnetBranchedSkipConnectionBlockUp(ngf, ngf * 2, input_nc=None, submodule=None, norm_layer=norm_layer)\n self.up1 = UnetBranchedSkipConnectionBlockUp(output_nc, ngf, input_nc=input_nc, submodule=None, outermost=True, norm_layer=norm_layer) # add the outermost layer\n \n\n def forward(self, x):\n \"\"\"Standard forward\"\"\"\n x1 = self.down1(x)\n x2 = self.down2(x1)\n x3 = self.down3(x2)\n x4 = self.down4(x3)\n x5 = self.down5(x4)\n x6 = self.down6(x5)\n x7 = self.down7(x6)\n x8 = self.down8(x7)\n x = self.up8(x8, x7)\n x = self.up7(x, x6)\n x = self.up6(x, x5)\n x = self.up5(x, x4)\n x = self.up4(x, x3)\n x = self.up3(x, x2)\n x = self.up2(x, x1)\n x = self.up1(x, x)\n return x\n\nclass UnetBranchedSkipConnectionBlockDown(nn.Module):\n \"\"\"Defines the Unet submodule with skip connection.\n X -------------------identity----------------------\n |-- downsampling -- |submodule| -- upsampling --|\n \"\"\"\n\n def __init__(self, outer_nc, inner_nc, input_nc=None,\n submodule=None, outermost=False, innermost=False, norm_layer=nn.BatchNorm2d, use_dropout=False):\n \"\"\"Construct a Unet submodule with skip connections.\n\n Parameters:\n outer_nc (int) -- the number of filters in the outer conv layer\n inner_nc (int) -- the number of filters in the inner conv layer\n input_nc (int) -- the number of channels in input images/features\n submodule (UnetSkipConnectionBlock) -- previously defined submodules\n outermost (bool) -- if this module is the outermost module\n innermost (bool) -- if this module is the innermost module\n norm_layer -- normalization layer\n user_dropout (bool) -- if use dropout layers.\n \"\"\"\n super(UnetBranchedSkipConnectionBlockDown, self).__init__()\n self.outermost = outermost\n self.innermost = innermost\n if type(norm_layer) == functools.partial:\n use_bias = norm_layer.func == nn.InstanceNorm2d\n else:\n use_bias = norm_layer == nn.InstanceNorm2d\n if input_nc is None:\n input_nc = outer_nc\n downconv = nn.Conv2d(input_nc, inner_nc, kernel_size=4,\n stride=2, padding=1, bias=use_bias)\n downrelu = nn.LeakyReLU(0.2, True)\n downnorm = norm_layer(inner_nc)\n uprelu = nn.ReLU(True)\n upnorm = norm_layer(outer_nc)\n\n if outermost:\n upconv = nn.ConvTranspose2d(inner_nc * 2, outer_nc,\n kernel_size=4, stride=2,\n padding=1)\n down = [downconv]\n up = [uprelu, upconv, nn.Tanh()]\n model = down\n elif innermost:\n upconv = nn.ConvTranspose2d(inner_nc, outer_nc,\n kernel_size=4, stride=2,\n padding=1, bias=use_bias)\n down = [downrelu, downconv]\n up = [uprelu, upconv, upnorm]\n model = down\n else:\n upconv = nn.ConvTranspose2d(inner_nc * 2, outer_nc,\n kernel_size=4, stride=2,\n padding=1, bias=use_bias)\n down = [downrelu, downconv, downnorm]\n up = [uprelu, upconv, upnorm]\n\n if use_dropout:\n model = down\n else:\n model = down\n\n self.model = nn.Sequential(*model)\n\n def forward(self, x):\n if self.innermost:\n return torch.cat([self.model(x[0]), self.model(x[1]), self.model(x[2])], 1)\n return [self.model(x[0]), self.model(x[1]), self.model(x[2])]\n\nclass UnetBranchedSkipConnectionBlockUp(nn.Module):\n \"\"\"Defines the Unet submodule with skip connection.\n X -------------------identity----------------------\n |-- downsampling -- |submodule| -- upsampling --|\n \"\"\"\n\n def __init__(self, outer_nc, inner_nc, input_nc=None,\n submodule=None, outermost=False, innermost=False, norm_layer=nn.BatchNorm2d, use_dropout=False):\n \"\"\"Construct a Unet submodule with skip connections.\n\n Parameters:\n outer_nc (int) -- the number of filters in the outer conv layer\n inner_nc (int) -- the number of filters in the inner conv layer\n input_nc (int) -- the number of channels in input images/features\n submodule (UnetSkipConnectionBlock) -- previously defined submodules\n outermost (bool) -- if this module is the outermost module\n innermost (bool) -- if this module is the innermost module\n norm_layer -- normalization layer\n user_dropout (bool) -- if use dropout layers.\n \"\"\"\n super(UnetBranchedSkipConnectionBlockUp, self).__init__()\n self.outermost = outermost\n if type(norm_layer) == functools.partial:\n use_bias = norm_layer.func == nn.InstanceNorm2d\n else:\n use_bias = norm_layer == nn.InstanceNorm2d\n if input_nc is None:\n input_nc = outer_nc\n downconv = nn.Conv2d(input_nc, inner_nc, kernel_size=4,\n stride=2, padding=1, bias=use_bias)\n downrelu = nn.LeakyReLU(0.2, True)\n downnorm = norm_layer(inner_nc)\n uprelu = nn.ReLU(True)\n upnorm = norm_layer(outer_nc)\n\n if outermost:\n upconv = nn.ConvTranspose2d(2*inner_nc * 2, outer_nc,\n kernel_size=4, stride=2,\n padding=1)\n down = [downconv]\n up = [uprelu, upconv, nn.Tanh()]\n model = up\n elif innermost:\n upconv = nn.ConvTranspose2d(3*inner_nc, outer_nc,\n kernel_size=4, stride=2,\n padding=1, bias=use_bias)\n down = [downrelu, downconv]\n up = [uprelu, upconv, upnorm]\n model = up\n else:\n upconv = nn.ConvTranspose2d(2*inner_nc * 2, outer_nc,\n kernel_size=4, stride=2,\n padding=1, bias=use_bias)\n down = [downrelu, downconv, downnorm]\n up = [uprelu, upconv, upnorm]\n\n if use_dropout:\n model = up + [nn.Dropout(0.5)]\n else:\n model = up\n\n self.model = nn.Sequential(*model)\n\n def forward(self, x1, x2):\n if self.outermost:\n return self.model(x1)\n else: # add skip connections\n return torch.cat([x2[0], x2[1], x2[2], self.model(x1)], 1)\n\nclass UnetSkipConnectionBlock(nn.Module):\n \"\"\"Defines the Unet submodule with skip connection.\n X -------------------identity----------------------\n |-- downsampling -- |submodule| -- upsampling --|\n \"\"\"\n\n def __init__(self, outer_nc, inner_nc, input_nc=None,\n submodule=None, outermost=False, innermost=False, norm_layer=nn.BatchNorm2d, use_dropout=False):\n \"\"\"Construct a Unet submodule with skip connections.\n\n Parameters:\n outer_nc (int) -- the number of filters in the outer conv layer\n inner_nc (int) -- the number of filters in the inner conv layer\n input_nc (int) -- the number of channels in input images/features\n submodule (UnetSkipConnectionBlock) -- previously defined submodules\n outermost (bool) -- if this module is the outermost module\n innermost (bool) -- if this module is the innermost module\n norm_layer -- normalization layer\n user_dropout (bool) -- if use dropout layers.\n \"\"\"\n super(UnetSkipConnectionBlock, self).__init__()\n self.outermost = outermost\n if type(norm_layer) == functools.partial:\n use_bias = norm_layer.func == nn.InstanceNorm2d\n else:\n use_bias = norm_layer == nn.InstanceNorm2d\n if input_nc is None:\n input_nc = outer_nc\n downconv = nn.Conv2d(input_nc, inner_nc, kernel_size=4,\n stride=2, padding=1, bias=use_bias)\n downrelu = nn.LeakyReLU(0.2, True)\n downnorm = norm_layer(inner_nc)\n uprelu = nn.ReLU(True)\n upnorm = norm_layer(outer_nc)\n\n if outermost:\n upconv = nn.ConvTranspose2d(inner_nc * 2, outer_nc,\n kernel_size=4, stride=2,\n padding=1)\n down = [downconv]\n up = [uprelu, upconv, nn.Tanh()]\n model = down + [submodule] + up\n elif innermost:\n upconv = nn.ConvTranspose2d(inner_nc, outer_nc,\n kernel_size=4, stride=2,\n padding=1, bias=use_bias)\n down = [downrelu, downconv]\n up = [uprelu, upconv, upnorm]\n model = down + up\n else:\n upconv = nn.ConvTranspose2d(inner_nc * 2, outer_nc,\n kernel_size=4, stride=2,\n padding=1, bias=use_bias)\n down = [downrelu, downconv, downnorm]\n up = [uprelu, upconv, upnorm]\n\n if use_dropout:\n model = down + [submodule] + up + [nn.Dropout(0.5)]\n else:\n model = down + [submodule] + up\n\n self.model = nn.Sequential(*model)\n\n def forward(self, x):\n if self.outermost:\n return self.model(x)\n else: # add skip connections\n return torch.cat([x, self.model(x)], 1)\n\n\nclass NLayerDiscriminator(nn.Module):\n \"\"\"Defines a PatchGAN discriminator\"\"\"\n\n def __init__(self, input_nc, ndf=64, n_layers=3, norm_layer=nn.BatchNorm2d):\n \"\"\"Construct a PatchGAN discriminator\n\n Parameters:\n input_nc (int) -- the number of channels in input images\n ndf (int) -- the number of filters in the last conv layer\n n_layers (int) -- the number of conv layers in the discriminator\n norm_layer -- normalization layer\n \"\"\"\n super(NLayerDiscriminator, self).__init__()\n if type(norm_layer) == functools.partial: # no need to use bias as BatchNorm2d has affine parameters\n use_bias = norm_layer.func != nn.BatchNorm2d\n else:\n use_bias = norm_layer != nn.BatchNorm2d\n\n kw = 4\n padw = 1\n sequence = [nn.Conv2d(input_nc, ndf, kernel_size=kw, stride=2, padding=padw), nn.LeakyReLU(0.2, True)]\n nf_mult = 1\n nf_mult_prev = 1\n for n in range(1, n_layers): # gradually increase the number of filters\n nf_mult_prev = nf_mult\n nf_mult = min(2 ** n, 8)\n sequence += [\n nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=kw, stride=2, padding=padw, bias=use_bias),\n norm_layer(ndf * nf_mult),\n nn.LeakyReLU(0.2, True)\n ]\n\n nf_mult_prev = nf_mult\n nf_mult = min(2 ** n_layers, 8)\n sequence += [\n nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=kw, stride=1, padding=padw, bias=use_bias),\n norm_layer(ndf * nf_mult),\n nn.LeakyReLU(0.2, True)\n ]\n\n sequence += [nn.Conv2d(ndf * nf_mult, 1, kernel_size=kw, stride=1, padding=padw)] # output 1 channel prediction map\n self.model = nn.Sequential(*sequence)\n\n def forward(self, input):\n \"\"\"Standard forward.\"\"\"\n return self.model(input)\n\n\nclass PixelDiscriminator(nn.Module):\n \"\"\"Defines a 1x1 PatchGAN discriminator (pixelGAN)\"\"\"\n\n def __init__(self, input_nc, ndf=64, norm_layer=nn.BatchNorm2d):\n \"\"\"Construct a 1x1 PatchGAN discriminator\n\n Parameters:\n input_nc (int) -- the number of channels in input images\n ndf (int) -- the number of filters in the last conv layer\n norm_layer -- normalization layer\n \"\"\"\n super(PixelDiscriminator, self).__init__()\n if type(norm_layer) == functools.partial: # no need to use bias as BatchNorm2d has affine parameters\n use_bias = norm_layer.func != nn.InstanceNorm2d\n else:\n use_bias = norm_layer != nn.InstanceNorm2d\n\n self.net = [\n nn.Conv2d(input_nc, ndf, kernel_size=1, stride=1, padding=0),\n nn.LeakyReLU(0.2, True),\n nn.Conv2d(ndf, ndf * 2, kernel_size=1, stride=1, padding=0, bias=use_bias),\n norm_layer(ndf * 2),\n nn.LeakyReLU(0.2, True),\n nn.Conv2d(ndf * 2, 1, kernel_size=1, stride=1, padding=0, bias=use_bias)]\n\n self.net = nn.Sequential(*self.net)\n\n def forward(self, input):\n \"\"\"Standard forward.\"\"\"\n return self.net(input)\n"
]
| [
[
"torch.optim.lr_scheduler.LambdaLR",
"torch.optim.lr_scheduler.CosineAnnealingLR",
"torch.cat",
"torch.nn.BCEWithLogitsLoss",
"torch.cuda.is_available",
"torch.nn.ReplicationPad2d",
"torch.nn.Dropout",
"torch.optim.lr_scheduler.ReduceLROnPlateau",
"torch.tensor",
"torch.rand",
"torch.optim.lr_scheduler.StepLR",
"torch.nn.Sequential",
"torch.nn.ConvTranspose2d",
"torch.nn.init.constant_",
"torch.nn.Conv2d",
"torch.nn.init.xavier_normal_",
"torch.nn.DataParallel",
"torch.nn.init.normal_",
"torch.nn.LeakyReLU",
"torch.nn.ReflectionPad2d",
"torch.nn.Tanh",
"torch.nn.init.orthogonal_",
"torch.nn.ReLU",
"torch.nn.MSELoss",
"torch.nn.init.kaiming_normal_"
]
]
|
horinoA/startSpotify | [
"524de651f72d0e89be01d3792c070cc70a3a36d7"
]
| [
"startSpotify.py"
]
| [
"# CSVファイルを保存するpandasをpdという名前でインポートします\nimport pandas as pd\n# Spotify用のAPIを取り込みます\nimport spotipy\nfrom spotipy.oauth2 import SpotifyClientCredentials\n# token用のファイルspotifyAPI.pyを別で用意し、apiよいう名前でインポートします\n# これでtokenをとりあえずベタガキしないですみます\nimport spotifyAPI as api\n\n# apiからtokenはよびだします\nclient_id = api.client_id\nclient_secret = api.client_secret\n# ここからはSpotifyAPIの設定です\nclient_credentials_manager = spotipy.oauth2.SpotifyClientCredentials(\n client_id, client_secret)\nspotify = spotipy.Spotify(\n client_credentials_manager=client_credentials_manager)\n\n# name変数に検索したいミュージシャン名をいれます\nname = \"Stevie Wonder\"\nresults = spotify.search(q='artist:' + name, type='artist')\nitems = results['artists']['items']\nserch_uri = ''\nif len(items) > 0:\n artist = items[0]\n serch_uri = artist['uri']\n# print(artist['name'], artist['uri'], artist['images'][0]\n# ['url'])\n\nif serch_uri != '':\n path = \"../albums.csv\"\n results = spotify.artist_albums(serch_uri, album_type='album')\n albums = results['items']\n\n while results['next']:\n results = spotify.next(results)\n albums.extend(results['items'])\n\n for album in albums:\n print(album['name'], album['release_date'],\n album['total_tracks'], album['uri'])\n\n # pandasのDataFrameでJsonを変換します\n df = pd.DataFrame(albums)\n # path変数にフルパス入るとフォルダも指定できます。encodingで文字コードを指定して保存できます\n df.to_csv(path, encoding='shift_jis')\n"
]
| [
[
"pandas.DataFrame"
]
]
|
NVIDIA-AI-IOT/centernet_kinect | [
"92438e9f1469d1d8deffb33569068d2b635f99b6"
]
| [
"model/utils.py"
]
| [
"'''\nCopyright (c) 2020, NVIDIA CORPORATION. All rights reserved.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n'''\nimport os\nimport sys\nimport torch\nimport torchvision\nimport torch.nn.functional as F\n\n# Adding Project Path\nDIR_PATH = os.path.dirname(os.path.abspath(__file__))\nPROJ_PATH = os.path.join(DIR_PATH, os.path.pardir)\nsys.path.append(PROJ_PATH)\n\n# Importing Project Libraries\nimport pipeline.constants as const\n\ndef Criterion(pred: torch.tensor, ground_truth: torch.tensor, loss_type=const.LOSS,\\\n alpha=const.ALPHA, beta=const.BETA, num_classes=const.NUM_CLASSES,\\\n lambda_h=const.LAMBDA_HEATMAP, lambda_s=const.LAMBDA_SIZE, lambda_o=const.LAMBDA_OFFSET):\n \"\"\"\n Logistic Regression Loss from Centernet Paper\n\n :param pred: torch.tensor, model prediction (N, Num_classes+4, 160, 160)\n :param ground_truth: torch.tensor, ground truth (N, Num_classes+4, 160, 160)\n :param alpha: int, constant defined in the paper\n :param beta: int, constant defined in the paper\n \"\"\"\n loss_switcher = {\n \"MSE\" : mse_loss,\n \"Logistic\": logisitc_reg_loss,\n }\n mas_loss = loss_switcher[loss_type]\n mask_loss = mas_loss(pred[:,0:num_classes], ground_truth[:,0:num_classes])\n # BBox Sizes\n size_loss_y = regression_loss(pred[:,-4], ground_truth[:,-4], ground_truth[:,0:num_classes])\n size_loss_x = regression_loss(pred[:,-3], ground_truth[:,-3], ground_truth[:,0:num_classes])\n # Offset Losses\n offset_loss_y = regression_loss(pred[:,-2], ground_truth[:,-2], ground_truth[:,0:num_classes])\n offset_loss_x = regression_loss(pred[:,-1], ground_truth[:,-1], ground_truth[:,0:num_classes])\n\n loss = lambda_h*mask_loss + lambda_s*(size_loss_x+size_loss_y) + lambda_o*(offset_loss_x+offset_loss_y)\n\n return loss\n\nclass Summary(object):\n \"\"\"\n Tracking summary of a variable\n \"\"\"\n def __init__(self):\n self.value = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n \n def update(self, value):\n self.value = value\n self.sum += value\n self.count += 1\n self.avg = self.sum / self.count\n\n############################\n### Internal Functions ###\n############################\n\ndef logisitc_reg_loss(pred: torch.tensor, ground_truth_heatmap: torch.tensor,\\\n alpha=const.ALPHA, beta=const.BETA, thresh=const.THRESHOLD, window_size=11):\n \"\"\"\n Logistic Regression Loss from Centernet Paper\n\n :param pred: torch.tensor, model prediction (N, Num_classes, 160, 160)\n :param ground_truth_heatmap: torch.tensor, ground truth (N, Num_classes, 160, 160)\n :param alpha: int, constant defined in the paper\n :param beta: int, constant defined in the paper\n :return: logistic regression loss (regressing heatmaps)\n \"\"\"\n p = pred\n # p = torch.max_pool2d(pred, kernel_size=window_size, stride=1, padding=window_size//2)\n # p = ((pred == p) * (p > thresh)).float()\n p[p.lt(1e-3)] = 1e-3\n p[p.gt(.99)] = .99\n\n gt = ground_truth_heatmap\n\n # pos_inds = gt.eq(1).float()\n # neg_inds = gt.lt(1).float()\n\n pos_inds = gt.gt(thresh).float() + gt.eq(thresh).float()\n neg_inds = gt.lt(thresh).float()\n\n # weights = gt[pos_inds.bool()].sum()\n weights = 1\n\n pos_loss = torch.log(p) * torch.pow(1-p, alpha) * pos_inds * weights\n neg_loss = torch.log(1-p) * torch.pow(p, alpha) * torch.pow(1-gt, beta) * neg_inds\n\n num_pos = pos_inds.float().sum()\n pos_loss = pos_loss.float().sum()\n neg_loss = neg_loss.float().sum()\n\n if torch.isnan(-1*(pos_loss + neg_loss)/num_pos if num_pos!=0 else -1*neg_loss):\n import pdb; pdb.set_trace()\n\n\n return -1*(pos_loss + neg_loss)/num_pos if num_pos!=0 else -1*neg_loss\n\ndef mse_loss(pred: torch.tensor, ground_truth_heatmap: torch.tensor):\n \"\"\"\n Logistic Regression Loss from Centernet Paper\n\n :param pred: torch.tensor, model prediction (N, Num_classes, 160, 160)\n :param ground_truth_heatmap: torch.tensor, ground truth (N, Num_classes, 160, 160)\n :param alpha: int, constant defined in the paper\n :param beta: int, constant defined in the paper\n :return: logistic regression loss (regressing heatmaps)\n \"\"\"\n\n loss = torch.nn.MSELoss()\n\n p = pred\n gt = ground_truth_heatmap\n\n return loss(p, gt)\n\ndef regression_loss(pred: torch.tensor, ground_truth: torch.tensor, ground_truth_heatmap: torch.tensor):\n \"\"\"\n Regression Loss from Centernet Paper\n\n :param pred: torch.tensor, model prediction (N, 1, 160, 160)\n :param ground_truth: torch.tensor, ground truth (N, 1, 160, 160)\n :param ground_truth_heatmap: torch.tensor, ground truth (N, Num_classes, 160, 160)\n :return: regression loss (regression size and offsets)\n \"\"\"\n\n num = ground_truth_heatmap.float().sum()*2\n \n mask, _ = ground_truth_heatmap.max(1)\n mask = mask.eq(1).float()\n\n pred = pred[mask==1]\n ground_truth = ground_truth[mask==1]\n \n reg_loss = F.l1_loss(\n pred, ground_truth, size_average=False\n )\n\n # reg_loss = reg_loss / (num + 1e-4)\n return reg_loss"
]
| [
[
"torch.nn.MSELoss",
"torch.nn.functional.l1_loss",
"torch.isnan",
"torch.log",
"torch.pow"
]
]
|
thomascbrs/quadruped-reactive-walking | [
"38553b3fd14dab3dd989a3488d4077df73cb2d26"
]
| [
"scripts/MPC_Wrapper.py"
]
| [
"# coding: utf8\n\nimport numpy as np\nimport libquadruped_reactive_walking as MPC\nfrom multiprocessing import Process, Value, Array\nfrom utils_mpc import quaternionToRPY\n# import crocoddyl_class.MPC_crocoddyl as MPC_crocoddyl\n\n\nclass Dummy:\n \"\"\"Dummy class to store variables\"\"\"\n\n def __init__(self):\n\n self.xref = None # Desired trajectory\n self.fsteps = None # Desired location of footsteps\n\n pass\n\n\nclass MPC_Wrapper:\n \"\"\"Wrapper to run both types of MPC (OQSP or Crocoddyl) with the possibility to run OSQP in\n a parallel process\n\n Args:\n mpc_type (bool): True to have PA's MPC, False to have Thomas's MPC\n dt (float): Time step of the MPC\n n_steps (int): Number of time steps in one gait cycle\n k_mpc (int): Number of inv dyn time step for one iteration of the MPC\n T_gait (float): Duration of one period of gait\n q_init (array): the default position of the robot\n multiprocessing (bool): Enable/Disable running the MPC with another process\n \"\"\"\n\n def __init__(self, mpc_type, dt, n_steps, k_mpc, T_gait, N_gait, q_init, multiprocessing=False):\n\n self.f_applied = np.zeros((12,))\n self.not_first_iter = False\n\n # Number of TSID steps for 1 step of the MPC\n self.k_mpc = k_mpc\n\n self.dt = dt\n self.n_steps = n_steps\n self.T_gait = T_gait\n self.N_gait = N_gait\n self.gait_memory = np.zeros(4)\n\n self.mpc_type = mpc_type\n self.multiprocessing = multiprocessing\n if multiprocessing: # Setup variables in the shared memory\n self.newData = Value('b', False)\n self.newResult = Value('b', False)\n self.dataIn = Array('d', [0.0] * (1 + (np.int(self.n_steps)+1) * 12 + 12*self.N_gait))\n self.dataOut = Array('d', [0] * 24 * (np.int(self.n_steps)))\n self.fsteps_future = np.zeros((self.N_gait, 12))\n self.running = Value('b', True)\n else:\n # Create the new version of the MPC solver object\n if mpc_type:\n self.mpc = MPC.MPC(dt, n_steps, T_gait, self.N_gait)\n else:\n self.mpc = MPC_crocoddyl.MPC_crocoddyl(\n dt=dt, T_mpc=T_gait, mu=0.9, inner=False, linearModel=True, n_period=int((dt * n_steps)/T_gait))\n\n # Setup initial result for the first iteration of the main control loop\n x_init = np.zeros(12)\n x_init[0:3] = q_init[0:3, 0]\n x_init[3:6] = quaternionToRPY(q_init[3:7, 0]).ravel()\n self.last_available_result = np.zeros((24, (np.int(self.n_steps))))\n self.last_available_result[:, 0] = np.hstack((x_init, np.array([0.0, 0.0, 8.0] * 4)))\n\n def solve(self, k, xref, fsteps, gait):\n \"\"\"Call either the asynchronous MPC or the synchronous MPC depending on the value of multiprocessing during\n the creation of the wrapper\n\n Args:\n k (int): Number of inv dynamics iterations since the start of the simulation\n xref (12xN): Desired state vector for the whole prediction horizon\n fsteps (12xN array): the [x, y, z]^T desired position of each foot for each time step of the horizon\n gait (4xN array): Contact state of feet (gait matrix)\n \"\"\"\n\n if self.multiprocessing: # Run in parallel process\n self.run_MPC_asynchronous(k, xref, fsteps)\n else: # Run in the same process than main loop\n self.run_MPC_synchronous(k, xref, fsteps)\n\n if k > 2:\n self.last_available_result[12:(12+self.n_steps), :] = np.roll(self.last_available_result[12:(12+self.n_steps), :], -1, axis=1)\n\n pt = 0\n while (np.any(gait[pt, :])):\n pt += 1\n if k > 2 and not np.array_equal(gait[0, :], gait[pt-1, :]):\n mass = 2.5 # TODO: grab from URDF?\n nb_ctc = np.sum(gait[pt-1, :])\n F = 9.81 * mass / nb_ctc\n self.last_available_result[12:, self.n_steps-1] = np.zeros(12)\n for i in range(4):\n if (gait[pt-1, i] == 1):\n self.last_available_result[12+3*i+2, self.n_steps-1] = F\n\n return 0\n\n def get_latest_result(self):\n \"\"\"Return the desired contact forces that have been computed by the last iteration of the MPC\n If a new result is available, return the new result. Otherwise return the old result again.\n \"\"\"\n\n if (self.not_first_iter):\n if self.multiprocessing:\n if self.newResult.value:\n self.newResult.value = False\n # Retrieve desired contact forces with through the memory shared with the asynchronous\n self.last_available_result = self.convert_dataOut()\n return self.last_available_result\n else:\n return self.last_available_result\n else:\n # Directly retrieve desired contact force of the synchronous MPC object\n return self.f_applied\n else:\n # Default forces for the first iteration\n self.not_first_iter = True\n return self.last_available_result\n\n def run_MPC_synchronous(self, k, xref, fsteps):\n \"\"\"Run the MPC (synchronous version) to get the desired contact forces for the feet currently in stance phase\n\n Args:\n k (int): Number of inv dynamics iterations since the start of the simulation\n xref (12xN): Desired state vector for the whole prediction horizon\n fsteps (12xN array): the [x, y, z]^T desired position of each foot for each time step of the horizon\n \"\"\"\n\n # Run the MPC to get the reference forces and the next predicted state\n # Result is stored in mpc.f_applied, mpc.q_next, mpc.v_next\n\n if self.mpc_type:\n # OSQP MPC\n self.mpc.run(np.int(k), xref.copy(), fsteps.copy())\n else:\n # Crocoddyl MPC (TODO: Adapt)\n self.mpc.solve(k, fstep_planner)\n\n # Output of the MPC\n self.f_applied = self.mpc.get_latest_result()\n\n def run_MPC_asynchronous(self, k, xref, fsteps):\n \"\"\"Run the MPC (asynchronous version) to get the desired contact forces for the feet currently in stance phase\n\n Args:\n k (int): Number of inv dynamics iterations since the start of the simulation\n fstep_planner (object): FootstepPlanner object of the control loop\n \"\"\"\n\n # If this is the first iteration, creation of the parallel process\n if (k == 0):\n p = Process(target=self.create_MPC_asynchronous, args=(\n self.newData, self.newResult, self.dataIn, self.dataOut, self.running))\n p.start()\n\n # Stacking data to send them to the parallel process\n self.compress_dataIn(k, xref, fsteps)\n self.newData.value = True\n\n return 0\n\n def create_MPC_asynchronous(self, newData, newResult, dataIn, dataOut, running):\n \"\"\"Parallel process with an infinite loop that run the asynchronous MPC\n\n Args:\n newData (Value): shared variable that is true if new data is available, false otherwise\n newResult (Value): shared variable that is true if a new result is available, false otherwise\n dataIn (Array): shared array that contains the data the asynchronous MPC will use as inputs\n dataOut (Array): shared array that contains the result of the asynchronous MPC\n running (Value): shared variable to stop the infinite loop when set to False\n \"\"\"\n\n # print(\"Entering infinite loop\")\n while running.value:\n # Checking if new data is available to trigger the asynchronous MPC\n if newData.value:\n\n # Set the shared variable to false to avoid re-trigering the asynchronous MPC\n newData.value = False\n # print(\"New data detected\")\n\n # Retrieve data thanks to the decompression function and reshape it\n kf, xref_1dim, fsteps_1dim = self.decompress_dataIn(dataIn)\n\n # Reshaping 1-dimensional data\n k = int(kf[0])\n xref = np.reshape(xref_1dim, (12, self.n_steps+1))\n fsteps = np.reshape(fsteps_1dim, (self.N_gait, 12))\n\n # Create the MPC object of the parallel process during the first iteration\n if k == 0:\n # loop_mpc = MPC.MPC(self.dt, self.n_steps, self.T_gait)\n if self.mpc_type:\n loop_mpc = MPC.MPC(self.dt, self.n_steps, self.T_gait)\n else:\n loop_mpc = MPC_crocoddyl.MPC_crocoddyl(self.dt, self.T_gait, 1, True)\n dummy_fstep_planner = Dummy()\n\n # Run the asynchronous MPC with the data that as been retrieved\n if self.mpc_type:\n fsteps[np.isnan(fsteps)] = 0.0\n loop_mpc.run(np.int(k), xref, fsteps)\n else:\n dummy_fstep_planner.xref = xref\n dummy_fstep_planner.fsteps = fsteps\n loop_mpc.solve(k, dummy_fstep_planner)\n\n # Store the result (predicted state + desired forces) in the shared memory\n # print(len(self.dataOut))\n # print((loop_mpc.get_latest_result()).shape)\n\n self.dataOut[:] = loop_mpc.get_latest_result().ravel(order='F')\n\n # Set shared variable to true to signal that a new result is available\n newResult.value = True\n\n return 0\n\n def compress_dataIn(self, k, xref, fsteps):\n \"\"\"Compress data in a single C-type array that belongs to the shared memory to send data from the main control\n loop to the asynchronous MPC\n\n Args:\n k (int): Number of inv dynamics iterations since the start of the simulation\n fstep_planner (object): FootstepPlanner object of the control loop\n \"\"\"\n\n # Replace NaN values by 0.0 to be stored in C-type arrays\n fsteps[np.isnan(fsteps)] = 0.0\n\n # Compress data in the shared input array\n self.dataIn[:] = np.concatenate([[(k/self.k_mpc)], xref.ravel(),\n fsteps.ravel()], axis=0)\n\n return 0.0\n\n def decompress_dataIn(self, dataIn):\n \"\"\"Decompress data from a single C-type array that belongs to the shared memory to retrieve data from the main control\n loop in the asynchronous MPC\n\n Args:\n dataIn (Array): shared array that contains the data the asynchronous MPC will use as inputs\n \"\"\"\n\n # Sizes of the different variables that are stored in the C-type array\n sizes = [0, 1, (np.int(self.n_steps)+1) * 12, 12*self.N_gait]\n csizes = np.cumsum(sizes)\n\n # Return decompressed variables in a list\n return [dataIn[csizes[i]:csizes[i+1]] for i in range(len(sizes)-1)]\n\n def convert_dataOut(self):\n \"\"\"Return the result of the asynchronous MPC (desired contact forces) that is stored in the shared memory\n \"\"\"\n\n return np.array(self.dataOut[:]).reshape((24, -1), order='F')\n\n def roll_asynchronous(self, fsteps):\n \"\"\"Move one step further in the gait cycle. Since the output of the asynchronous MPC is retrieved by\n TSID during the next call to the MPC, it should not work with the current state of the gait but with the\n gait on step into the future. That way, when TSID retrieves the result, it is consistent with the current\n state of the gait.\n\n Decrease by 1 the number of remaining step for the current phase of the gait and increase\n by 1 the number of remaining step for the last phase of the gait (periodic motion).\n Simplification: instead of creating a new phase if required (see roll function of FootstepPlanner) we always\n increase the last one by 1 step. That way we don't need to call other functions to predict the position of\n footstep when a new phase is created.\n\n Args:\n fsteps (13xN_gait array): the remaining number of steps of each phase of the gait (first column)\n and the [x, y, z]^T desired position of each foot for each phase of the gait (12 other columns)\n \"\"\"\n\n self.fsteps_future = fsteps.copy()\n\n # Index of the first empty line\n index = next((idx for idx, val in np.ndenumerate(self.fsteps_future[:, 0]) if val == 0.0), 0.0)[0]\n\n # Create a new phase if needed or increase the last one by 1 step\n self.fsteps_future[index-1, 0] += 1.0\n\n # Decrease the current phase by 1 step and delete it if it has ended\n if self.fsteps_future[0, 0] > 1.0:\n self.fsteps_future[0, 0] -= 1.0\n else:\n self.fsteps_future = np.roll(self.fsteps_future, -1, axis=0)\n self.fsteps_future[-1, :] = np.zeros((13, ))\n\n return 0\n\n def stop_parallel_loop(self):\n \"\"\"Stop the infinite loop in the parallel process to properly close the simulation\n \"\"\"\n\n self.running.value = False\n\n return 0\n"
]
| [
[
"numpy.sum",
"numpy.array_equal",
"numpy.reshape",
"numpy.isnan",
"numpy.cumsum",
"numpy.int",
"numpy.any",
"numpy.ndenumerate",
"numpy.array",
"numpy.zeros",
"numpy.roll"
]
]
|
KangSK-KAIST/SCALE-Sim | [
"349dd7b7053ea5bac482183597d2c403ad061560"
]
| [
"version2/memory/double_buffered_scratchpad_mem.py"
]
| [
"import time\nimport numpy as np\nfrom tqdm import tqdm\n\nfrom scalesim.memory.read_buffer import read_buffer as rdbuf\nfrom scalesim.memory.read_port import read_port as rdport\nfrom scalesim.memory.write_buffer import write_buffer as wrbuf\nfrom scalesim.memory.write_port import write_port as wrport\n\n\nclass double_buffered_scratchpad:\n def __init__(self):\n self.ifmap_buf = rdbuf()\n self.filter_buf = rdbuf()\n self.ofmap_buf =wrbuf()\n\n self.ifmap_port = rdport()\n self.filter_port = rdport()\n self.ofmap_port = wrport()\n\n self.verbose = True\n\n self.ifmap_trace_matrix = np.zeros((1,1), dtype=np.int)\n self.filter_trace_matrix = np.zeros((1,1), dtype=np.int)\n self.ofmap_trace_matrix = np.zeros((1,1), dtype=np.int)\n\n # Metrics to gather for generating run reports\n self.total_cycles = 0\n self.compute_cycles = 0\n self.stall_cycles = 0\n\n self.avg_ifmap_dram_bw = 0\n self.avg_filter_dram_bw = 0\n self.avg_ofmap_dram_bw = 0\n\n self.ifmap_sram_start_cycle = 0\n self.ifmap_sram_stop_cycle = 0\n self.filter_sram_start_cycle = 0\n self.filter_sram_stop_cycle = 0\n self.ofmap_sram_start_cycle = 0\n self.ofmap_sram_stop_cycle = 0\n\n self.ifmap_dram_start_cycle = 0\n self.ifmap_dram_stop_cycle = 0\n self.ifmap_dram_reads = 0\n self.filter_dram_start_cycle = 0\n self.filter_dram_stop_cycle = 0\n self.filter_dram_reads = 0\n self.ofmap_dram_start_cycle = 0\n self.ofmap_dram_stop_cycle = 0\n self.ofmap_dram_writes = 0\n\n self.traces_valid = False\n self.params_valid_flag = True\n\n #\n def set_params(self,\n verbose=True,\n word_size=1,\n ifmap_buf_size_bytes=2, filter_buf_size_bytes=2, ofmap_buf_size_bytes=2,\n rd_buf_active_frac=0.5, wr_buf_active_frac=0.5,\n ifmap_backing_buf_bw=1, filter_backing_buf_bw=1, ofmap_backing_buf_bw=1):\n\n self.ifmap_buf.set_params(backing_buf_obj=self.ifmap_port,\n total_size_bytes=ifmap_buf_size_bytes,\n word_size=word_size,\n active_buf_frac=rd_buf_active_frac,\n backing_buf_bw=ifmap_backing_buf_bw)\n\n self.filter_buf.set_params(backing_buf_obj=self.filter_port,\n total_size_bytes=filter_buf_size_bytes,\n word_size=word_size,\n active_buf_frac=rd_buf_active_frac,\n backing_buf_bw=filter_backing_buf_bw)\n\n self.ofmap_buf.set_params(backing_buf_obj=self.ofmap_port,\n total_size_bytes=ofmap_buf_size_bytes,\n word_size=word_size,\n active_buf_frac=wr_buf_active_frac,\n backing_buf_bw=ofmap_backing_buf_bw)\n\n self.verbose = verbose\n\n self.params_valid_flag = True\n\n #\n def set_read_buf_prefetch_matrices(self,\n ifmap_prefetch_mat=np.zeros((1,1)),\n filter_prefetch_mat=np.zeros((1,1))\n ):\n\n self.ifmap_buf.set_fetch_matrix(ifmap_prefetch_mat)\n self.filter_buf.set_fetch_matrix(filter_prefetch_mat)\n\n #\n def reset_buffer_states(self):\n\n self.ifmap_buf.reset()\n self.filter_buf.reset()\n self.ofmap_buf.reset()\n\n # The following are just shell methods for users to control each mem individually\n def service_ifmap_reads(self,\n incoming_requests_arr_np, # 2D array with the requests\n incoming_cycles_arr):\n out_cycles_arr_np = self.ifmap_buf.service_reads(incoming_requests_arr_np, incoming_cycles_arr)\n\n return out_cycles_arr_np\n\n #\n def service_filter_reads(self,\n incoming_requests_arr_np, # 2D array with the requests\n incoming_cycles_arr):\n out_cycles_arr_np = self.filter_buf.service_reads(incoming_requests_arr_np, incoming_cycles_arr)\n\n return out_cycles_arr_np\n\n #\n def service_ofmap_writes(self,\n incoming_requests_arr_np, # 2D array with the requests\n incoming_cycles_arr):\n\n out_cycles_arr_np = self.ofmap_buf.service_writes(incoming_requests_arr_np, incoming_cycles_arr)\n\n return out_cycles_arr_np\n\n #\n def service_memory_requests(self, ifmap_demand_mat, filter_demand_mat, ofmap_demand_mat):\n assert self.params_valid_flag, 'Memories not initialized yet'\n\n ofmap_lines = ofmap_demand_mat.shape[0]\n\n self.total_cycles = 0\n self.stall_cycles = 0\n\n ifmap_hit_latency = self.ifmap_buf.get_hit_latency()\n filter_hit_latency = self.ifmap_buf.get_hit_latency()\n\n ifmap_serviced_cycles = []\n filter_serviced_cycles = []\n ofmap_serviced_cycles = []\n\n pbar_disable = not self.verbose\n for i in tqdm(range(ofmap_lines), disable=pbar_disable):\n\n cycle_arr = np.zeros((1,1)) + i + self.stall_cycles\n ifmap_demand_line = ifmap_demand_mat[i, :].reshape((1,ifmap_demand_mat.shape[1]))\n ifmap_cycle_out = self.ifmap_buf.service_reads(incoming_requests_arr_np=ifmap_demand_line,\n incoming_cycles_arr=cycle_arr)\n ifmap_serviced_cycles += [ifmap_cycle_out[0]]\n ifmap_stalls = ifmap_cycle_out[0] - cycle_arr[0] - ifmap_hit_latency\n\n filter_demand_line = filter_demand_mat[i, :].reshape((1, filter_demand_mat.shape[1]))\n filter_cycle_out = self.filter_buf.service_reads(incoming_requests_arr_np=filter_demand_line,\n incoming_cycles_arr=cycle_arr)\n filter_serviced_cycles += [filter_cycle_out[0]]\n filter_stalls = filter_cycle_out[0] - cycle_arr[0] - filter_hit_latency\n\n ofmap_demand_line = ofmap_demand_mat[i, :].reshape((1, ofmap_demand_mat.shape[1]))\n ofmap_cycle_out = self.ofmap_buf.service_writes(incoming_requests_arr_np=ofmap_demand_line,\n incoming_cycles_arr_np=cycle_arr)\n ofmap_serviced_cycles += [ofmap_cycle_out[0]]\n ofmap_stalls = ofmap_cycle_out[0] - cycle_arr[0] - 1\n\n self.stall_cycles += int(max(ifmap_stalls[0], filter_stalls[0], ofmap_stalls[0]))\n\n #if i > 1021:\n # print('Trap')\n\n self.ofmap_buf.empty_all_buffers(ofmap_serviced_cycles[-1])\n\n # Prepare the traces\n ifmap_services_cycles_np = np.asarray(ifmap_serviced_cycles).reshape((len(ifmap_serviced_cycles), 1))\n self.ifmap_trace_matrix = np.concatenate((ifmap_services_cycles_np, ifmap_demand_mat), axis=1)\n\n filter_services_cycles_np = np.asarray(filter_serviced_cycles).reshape((len(filter_serviced_cycles), 1))\n self.filter_trace_matrix = np.concatenate((filter_services_cycles_np, filter_demand_mat), axis=1)\n\n ofmap_services_cycles_np = np.asarray(ofmap_serviced_cycles).reshape((len(ofmap_serviced_cycles), 1))\n self.ofmap_trace_matrix = np.concatenate((ofmap_services_cycles_np, ofmap_demand_mat), axis=1)\n self.total_cycles = int(ofmap_serviced_cycles[-1][0])\n\n # END of serving demands from memory\n self.traces_valid = True\n\n # This is the trace computation logic of this memory system\n # Anand: This is too complex, perform the serve cycle by cycle for the requests\n def service_memory_requests_old(self, ifmap_demand_mat, filter_demand_mat, ofmap_demand_mat):\n # TODO: assert sanity check\n assert self.params_valid_flag, 'Memories not initialized yet'\n\n # Logic:\n # Stalls can occur in both read and write portions and interfere with each other\n # We mitigate interference by picking a window in which there are no write stall,\n # ie, there is sufficient free space in the write buffer\n\n ofmap_lines_remaining = ofmap_demand_mat.shape[0] # The three demand mats have the same shape though\n start_line_idx = 0\n end_line_idx = 0\n\n first = True\n cycle_offset = 0\n self.total_cycles = 0\n self.stall_cycles = 0\n\n # Status bar\n pbar_disable = not self.verbose #or True\n pbar = tqdm(total=ofmap_lines_remaining, disable=pbar_disable)\n\n avg_read_time_series = []\n\n while ofmap_lines_remaining > 0:\n loop_start_time = time.time()\n ofmap_free_space = self.ofmap_buf.get_free_space()\n\n # Find the number of lines till the ofmap_free_space is filled up\n count = 0\n while not count > ofmap_free_space:\n this_line = ofmap_demand_mat[end_line_idx]\n for elem in this_line:\n if not elem == -1:\n count += 1\n\n if not count > ofmap_free_space:\n end_line_idx += 1\n # Limit check\n if not end_line_idx < ofmap_demand_mat.shape[0]:\n end_line_idx = ofmap_demand_mat.shape[0] - 1\n count = ofmap_free_space + 1\n else: # Send request with minimal data ie one line of the requests\n end_line_idx += 1\n # END of line counting\n\n num_lines = end_line_idx - start_line_idx + 1\n this_req_cycles_arr = [int(x + cycle_offset) for x in range(num_lines)]\n this_req_cycles_arr_np = np.asarray(this_req_cycles_arr).reshape((num_lines,1))\n\n this_req_ifmap_demands = ifmap_demand_mat[start_line_idx:(end_line_idx + 1), :]\n this_req_filter_demands = filter_demand_mat[start_line_idx:(end_line_idx + 1), :]\n this_req_ofmap_demands = ofmap_demand_mat[start_line_idx:(end_line_idx + 1), :]\n\n no_stall_cycles = num_lines # Since the cycles are consecutive at this point\n\n time_start = time.time()\n ifmap_cycles_out = self.ifmap_buf.service_reads(incoming_requests_arr_np=this_req_ifmap_demands,\n incoming_cycles_arr=this_req_cycles_arr_np)\n time_end = time.time()\n delta = time_end - time_start\n avg_read_time_series.append(delta)\n\n # Take care of the incurred stalls when launching demands for filter_reads\n # Note: Stalls incurred on reading line i in ifmap reflect the request cycles for line i+1 in filter\n ifmap_hit_latency = self.ifmap_buf.get_hit_latency()\n ifmap_stalls = ifmap_cycles_out - this_req_cycles_arr_np - ifmap_hit_latency # Vec - vec - scalar\n ifmap_stalls = np.concatenate((np.zeros((1,1)), ifmap_stalls[0:-1]), axis=0) # Shift by one row\n this_req_cycles_arr_np = this_req_cycles_arr_np + ifmap_stalls\n\n time_start = time.time()\n filter_cycles_out = self.filter_buf.service_reads(incoming_requests_arr_np=this_req_filter_demands,\n incoming_cycles_arr=this_req_cycles_arr_np)\n time_end = time.time()\n delta = time_end - time_start\n avg_read_time_series.append(delta)\n\n # Take care of stalls again --> The entire array stops when there is a stall\n filter_hit_latency = self.filter_buf.get_hit_latency()\n filter_stalls = filter_cycles_out - this_req_cycles_arr_np - filter_hit_latency # Vec - vec - scalar\n filter_stalls = np.concatenate((np.zeros((1, 1)), filter_stalls[0:-1]), axis=0) # Shift by one row\n this_req_cycles_arr_np = this_req_cycles_arr_np + filter_stalls\n\n ofmap_cycles_out = self.ofmap_buf.service_writes(incoming_requests_arr_np=this_req_ofmap_demands,\n incoming_cycles_arr_np=this_req_cycles_arr_np)\n\n # Make the trace matrices\n this_req_ifmap_trace_matrix = np.concatenate((ifmap_cycles_out, this_req_ifmap_demands), axis=1)\n this_req_filter_trace_matrix = np.concatenate((filter_cycles_out, this_req_filter_demands), axis=1)\n this_req_ofmap_trace_matrix = np.concatenate((ofmap_cycles_out, this_req_ofmap_demands), axis=1)\n\n actual_cycles = ofmap_cycles_out[-1][0] - this_req_cycles_arr_np[0][0] + 1\n num_stalls = actual_cycles - no_stall_cycles\n\n self.stall_cycles += num_stalls\n self.total_cycles = ofmap_cycles_out[-1][0] + 1 # OFMAP is served the last\n\n if first:\n first = False\n self.ifmap_trace_matrix = this_req_ifmap_trace_matrix\n self.filter_trace_matrix = this_req_filter_trace_matrix\n self.ofmap_trace_matrix = this_req_ofmap_trace_matrix\n else:\n self.ifmap_trace_matrix = np.concatenate((self.ifmap_trace_matrix, this_req_ifmap_trace_matrix), axis=0)\n self.filter_trace_matrix = np.concatenate((self.filter_trace_matrix, this_req_filter_trace_matrix), axis=0)\n self.ofmap_trace_matrix = np.concatenate((self.ofmap_trace_matrix, this_req_ofmap_trace_matrix), axis=0)\n\n # Update the local variable for another iteration of the while loop\n cycle_offset = ofmap_cycles_out[-1][0] + 1\n start_line_idx = end_line_idx + 1\n\n pbar.update(num_lines)\n ofmap_lines_remaining = max(ofmap_demand_mat.shape[0] - (end_line_idx + 1), 0) # Cutoff at 0\n #print(\"DEBUG: \" + str(end_line_idx))\n\n if end_line_idx > ofmap_demand_mat.shape[0]:\n print('Trap')\n\n #if int(ofmap_lines_remaining % 1000) == 0:\n # print(\"DEBUG: \" + str(ofmap_lines_remaining))\n\n loop_end_time = time.time()\n loop_time = loop_end_time - loop_start_time\n #print('DEBUG: Time taken in one iteration: ' + str(loop_time))\n\n # At this stage there might still be some data in the active buffer of the OFMAP scratchpad\n # The following drains it and generates the OFMAP\n drain_start_cycle = self.ofmap_trace_matrix[-1][0] + 1\n self.ofmap_buf.empty_all_buffers(drain_start_cycle)\n\n #avg_read_time = sum(avg_read_time_series) / len(avg_read_time_series)\n #print('DEBUG: Avg time to service reads= ' + str(avg_read_time))\n\n pbar.close()\n # END of serving demands from memory\n self.traces_valid = True\n\n #\n def get_total_compute_cycles(self):\n assert self.traces_valid, 'Traces not generated yet'\n return self.total_cycles\n\n #\n def get_stall_cycles(self):\n assert self.traces_valid, 'Traces not generated yet'\n return self.stall_cycles\n\n #\n def get_ifmap_sram_start_stop_cycles(self):\n assert self.traces_valid, 'Traces not generated yet'\n\n done = False\n for ridx in range(self.ifmap_trace_matrix.shape[0]):\n if done:\n break\n row = self.ifmap_trace_matrix[ridx,1:]\n for addr in row:\n if not addr == -1:\n self.ifmap_sram_start_cycle = self.ifmap_trace_matrix[ridx][0]\n done = True\n break\n\n done = False\n for ridx in range(self.ifmap_trace_matrix.shape[0]):\n if done:\n break\n ridx = -1 * (ridx + 1)\n row = self.ifmap_trace_matrix[ridx,1:]\n for addr in row:\n if not addr == -1:\n self.ifmap_sram_stop_cycle = self.ifmap_trace_matrix[ridx][0]\n done = True\n break\n\n return self.ifmap_sram_start_cycle, self.ifmap_sram_stop_cycle\n\n #\n def get_filter_sram_start_stop_cycles(self):\n assert self.traces_valid, 'Traces not generated yet'\n\n done = False\n for ridx in range(self.filter_trace_matrix.shape[0]):\n if done:\n break\n row = self.filter_trace_matrix[ridx, 1:]\n for addr in row:\n if not addr == -1:\n self.filter_sram_start_cycle = self.filter_trace_matrix[ridx][0]\n done = True\n break\n\n done = False\n for ridx in range(self.filter_trace_matrix.shape[0]):\n if done:\n break\n ridx = -1 * (ridx + 1)\n row = self.filter_trace_matrix[ridx, 1:]\n for addr in row:\n if not addr == -1:\n self.filter_sram_stop_cycle = self.filter_trace_matrix[ridx][0]\n done = True\n break\n\n return self.filter_sram_start_cycle, self.filter_sram_stop_cycle\n\n #\n def get_ofmap_sram_start_stop_cycles(self):\n assert self.traces_valid, 'Traces not generated yet'\n\n done = False\n for ridx in range(self.ofmap_trace_matrix.shape[0]):\n if done:\n break\n row = self.ofmap_trace_matrix[ridx, 1:]\n for addr in row:\n if not addr == -1:\n self.ofmap_sram_start_cycle = self.ofmap_trace_matrix[ridx][0]\n done = True\n break\n\n done = False\n for ridx in range(self.ofmap_trace_matrix.shape[0]):\n if done:\n break\n ridx = -1 * (ridx + 1)\n row = self.ofmap_trace_matrix[ridx, 1:]\n for addr in row:\n if not addr == -1:\n self.ofmap_sram_stop_cycle = self.ofmap_trace_matrix[ridx][0]\n done = True\n break\n\n return self.ofmap_sram_start_cycle, self.ofmap_sram_stop_cycle\n\n #\n def get_ifmap_dram_details(self):\n assert self.traces_valid, 'Traces not generated yet'\n\n self.ifmap_dram_reads = self.ifmap_buf.get_num_accesses()\n self.ifmap_dram_start_cycle, self.ifmap_dram_stop_cycle \\\n = self.ifmap_buf.get_external_access_start_stop_cycles()\n\n return self.ifmap_dram_start_cycle, self.ifmap_dram_stop_cycle, self.ifmap_dram_reads\n\n #\n def get_filter_dram_details(self):\n assert self.traces_valid, 'Traces not generated yet'\n\n self.filter_dram_reads = self.filter_buf.get_num_accesses()\n self.filter_dram_start_cycle, self.filter_dram_stop_cycle \\\n = self.filter_buf.get_external_access_start_stop_cycles()\n\n return self.filter_dram_start_cycle, self.filter_dram_stop_cycle, self.filter_dram_reads\n\n #\n def get_ofmap_dram_details(self):\n assert self.traces_valid, 'Traces not generated yet'\n\n self.ofmap_dram_writes = self.ofmap_buf.get_num_accesses()\n self.ofmap_dram_start_cycle, self.ofmap_dram_stop_cycle \\\n = self.ofmap_buf.get_external_access_start_stop_cycles()\n\n return self.ofmap_dram_start_cycle, self.ofmap_dram_stop_cycle, self.ofmap_dram_writes\n\n #\n def get_ifmap_sram_trace_matrix(self):\n assert self.traces_valid, 'Traces not generated yet'\n return self.ifmap_trace_matrix\n\n #\n def get_filter_sram_trace_matrix(self):\n assert self.traces_valid, 'Traces not generated yet'\n return self.filter_trace_matrix\n\n #\n def get_ofmap_sram_trace_matrix(self):\n assert self.traces_valid, 'Traces not generated yet'\n return self.ofmap_trace_matrix\n\n #\n def get_sram_trace_matrices(self):\n assert self.traces_valid, 'Traces not generated yet'\n return self.ifmap_trace_matrix, self.filter_trace_matrix, self.ofmap_trace_matrix\n\n #\n def get_ifmap_dram_trace_matrix(self):\n return self.ifmap_buf.get_trace_matrix()\n\n #\n def get_filter_dram_trace_matrix(self):\n return self.filter_buf.get_trace_matrix()\n\n #\n def get_ofmap_dram_trace_matrix(self):\n return self.ofmap_buf.get_trace_matrix()\n\n #\n def get_dram_trace_matrices(self):\n dram_ifmap_trace = self.ifmap_buf.get_trace_matrix()\n dram_filter_trace = self.filter_buf.get_trace_matrix()\n dram_ofmap_trace = self.ofmap_buf.get_trace_matrix()\n\n return dram_ifmap_trace, dram_filter_trace, dram_ofmap_trace\n\n #\n def print_ifmap_sram_trace(self, filename):\n assert self.traces_valid, 'Traces not generated yet'\n np.savetxt(filename, self.ifmap_trace_matrix, fmt='%i', delimiter=\",\")\n\n #\n def print_filter_sram_trace(self, filename):\n assert self.traces_valid, 'Traces not generated yet'\n np.savetxt(filename, self.filter_trace_matrix, fmt='%i', delimiter=\",\")\n\n #\n def print_ofmap_sram_trace(self, filename):\n assert self.traces_valid, 'Traces not generated yet'\n np.savetxt(filename, self.ofmap_trace_matrix, fmt='%i', delimiter=\",\")\n\n #\n def print_ifmap_dram_trace(self, filename):\n self.ifmap_buf.print_trace(filename)\n\n #\n def print_filter_dram_trace(self, filename):\n self.filter_buf.print_trace(filename)\n\n #\n def print_ofmap_dram_trace(self, filename):\n self.ofmap_buf.print_trace(filename)\n\n\n\n\n\n"
]
| [
[
"numpy.concatenate",
"numpy.zeros",
"numpy.asarray",
"numpy.savetxt"
]
]
|
bluesea0/nlp-tutorial | [
"9f17b18d3df9e79ea116d2c4c6ce0820a2dbe126"
]
| [
"5-1.Transformer/Transformer-Torch.py"
]
| [
"'''\n code by Tae Hwan Jung(Jeff Jung) @graykode, Derek Miller @dmmiller612\n Reference : https://github.com/jadore801120/attention-is-all-you-need-pytorch\n https://github.com/JayParks/transformer\n'''\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.autograd import Variable\nimport matplotlib.pyplot as plt\n\ndtype = torch.FloatTensor\n# S: Symbol that shows starting of decoding input\n# E: Symbol that shows starting of decoding output\n# P: Symbol that will fill in blank sequence if current batch data size is short than time steps\nsentences = ['ich mochte ein bier P', 'S i want a beer', 'i want a beer E']\n\n# Transformer Parameters\n# Padding Should be Zero\nsrc_vocab = {'P' : 0, 'ich' : 1, 'mochte' : 2, 'ein' : 3, 'bier' : 4}\nsrc_vocab_size = len(src_vocab)\n\ntgt_vocab = {'P' : 0, 'i' : 1, 'want' : 2, 'a' : 3, 'beer' : 4, 'S' : 5, 'E' : 6}\nnumber_dict = {i: w for i, w in enumerate(tgt_vocab)}\ntgt_vocab_size = len(tgt_vocab)\n\nsrc_len = 5\ntgt_len = 5\n\nd_model = 512 # Embedding Size\nd_ff = 2048 # FeedForward dimension\nd_k = d_v = 64 # dimension of K(=Q), V\nn_layers = 6 # number of Encoder of Decoder Layer\nn_heads = 8 # number of heads in Multi-Head Attention\n\ndef make_batch(sentences):\n input_batch = [[src_vocab[n] for n in sentences[0].split()]]\n output_batch = [[tgt_vocab[n] for n in sentences[1].split()]]\n target_batch = [[tgt_vocab[n] for n in sentences[2].split()]]\n return Variable(torch.LongTensor(input_batch)), Variable(torch.LongTensor(output_batch)), Variable(torch.LongTensor(target_batch))\n\ndef get_sinusoid_encoding_table(n_position, d_model):\n def cal_angle(position, hid_idx):\n return position / np.power(10000, 2 * (hid_idx // 2) / d_model)\n def get_posi_angle_vec(position):\n return [cal_angle(position, hid_j) for hid_j in range(d_model)]\n\n sinusoid_table = np.array([get_posi_angle_vec(pos_i) for pos_i in range(n_position)])\n sinusoid_table[:, 0::2] = np.sin(sinusoid_table[:, 0::2]) # dim 2i\n sinusoid_table[:, 1::2] = np.cos(sinusoid_table[:, 1::2]) # dim 2i+1\n return torch.FloatTensor(sinusoid_table)\n\ndef get_attn_pad_mask(seq_q, seq_k):\n batch_size, len_q = seq_q.size()\n batch_size, len_k = seq_k.size()\n # eq(zero) is PAD token\n pad_attn_mask = seq_k.data.eq(0).unsqueeze(1) # batch_size x 1 x len_k(=len_q), one is masking\n return pad_attn_mask.expand(batch_size, len_q, len_k) # batch_size x len_q x len_k\n\ndef get_attn_subsequent_mask(seq):\n attn_shape = [seq.size(0), seq.size(1), seq.size(1)]\n subsequent_mask = np.triu(np.ones(attn_shape), k=1)\n subsequent_mask = torch.from_numpy(subsequent_mask).byte()\n return subsequent_mask\n\nclass ScaledDotProductAttention(nn.Module):\n def __init__(self):\n super(ScaledDotProductAttention, self).__init__()\n\n def forward(self, Q, K, V, attn_mask):\n scores = torch.matmul(Q, K.transpose(-1, -2)) / np.sqrt(d_k) # scores : [batch_size x n_heads x len_q(=len_k) x len_k(=len_q)]\n scores.masked_fill_(attn_mask, -1e9) # Fills elements of self tensor with value where mask is one.\n attn = nn.Softmax(dim=-1)(scores)\n context = torch.matmul(attn, V)\n return context, attn\n\nclass MultiHeadAttention(nn.Module):\n def __init__(self):\n super(MultiHeadAttention, self).__init__()\n self.W_Q = nn.Linear(d_model, d_k * n_heads)\n self.W_K = nn.Linear(d_model, d_k * n_heads)\n self.W_V = nn.Linear(d_model, d_v * n_heads)\n def forward(self, Q, K, V, attn_mask):\n # q: [batch_size x len_q x d_model], k: [batch_size x len_k x d_model], v: [batch_size x len_k x d_model]\n residual, batch_size = Q, Q.size(0)\n # (B, S, D) -proj-> (B, S, D) -split-> (B, S, H, W) -trans-> (B, H, S, W)\n q_s = self.W_Q(Q).view(batch_size, -1, n_heads, d_k).transpose(1,2) # q_s: [batch_size x n_heads x len_q x d_k]\n k_s = self.W_K(K).view(batch_size, -1, n_heads, d_k).transpose(1,2) # k_s: [batch_size x n_heads x len_k x d_k]\n v_s = self.W_V(V).view(batch_size, -1, n_heads, d_v).transpose(1,2) # v_s: [batch_size x n_heads x len_k x d_v]\n\n attn_mask = attn_mask.unsqueeze(1).repeat(1, n_heads, 1, 1) # attn_mask : [batch_size x n_heads x len_q x len_k]\n\n # context: [batch_size x n_heads x len_q x d_v], attn: [batch_size x n_heads x len_q(=len_k) x len_k(=len_q)]\n context, attn = ScaledDotProductAttention()(q_s, k_s, v_s, attn_mask)\n context = context.transpose(1, 2).contiguous().view(batch_size, -1, n_heads * d_v) # context: [batch_size x len_q x n_heads * d_v]\n output = nn.Linear(n_heads * d_v, d_model)(context)\n return nn.LayerNorm(d_model)(output + residual), attn # output: [batch_size x len_q x d_model]\n\nclass PoswiseFeedForwardNet(nn.Module):\n def __init__(self):\n super(PoswiseFeedForwardNet, self).__init__()\n self.conv1 = nn.Conv1d(in_channels=d_model, out_channels=d_ff, kernel_size=1)\n self.conv2 = nn.Conv1d(in_channels=d_ff, out_channels=d_model, kernel_size=1)\n\n def forward(self, inputs):\n residual = inputs # inputs : [batch_size, len_q, d_model]\n output = nn.ReLU()(self.conv1(inputs.transpose(1, 2)))\n output = self.conv2(output).transpose(1, 2)\n return nn.LayerNorm(d_model)(output + residual)\n\nclass EncoderLayer(nn.Module):\n def __init__(self):\n super(EncoderLayer, self).__init__()\n self.enc_self_attn = MultiHeadAttention()\n self.pos_ffn = PoswiseFeedForwardNet()\n\n def forward(self, enc_inputs, enc_self_attn_mask):\n enc_outputs, attn = self.enc_self_attn(enc_inputs, enc_inputs, enc_inputs, enc_self_attn_mask) # enc_inputs to same Q,K,V\n enc_outputs = self.pos_ffn(enc_outputs) # enc_outputs: [batch_size x len_q x d_model]\n return enc_outputs, attn\n\nclass DecoderLayer(nn.Module):\n def __init__(self):\n super(DecoderLayer, self).__init__()\n self.dec_self_attn = MultiHeadAttention()\n self.dec_enc_attn = MultiHeadAttention()\n self.pos_ffn = PoswiseFeedForwardNet()\n\n def forward(self, dec_inputs, enc_outputs, dec_self_attn_mask, dec_enc_attn_mask):\n dec_outputs, dec_self_attn = self.dec_self_attn(dec_inputs, dec_inputs, dec_inputs, dec_self_attn_mask)\n dec_outputs, dec_enc_attn = self.dec_enc_attn(dec_outputs, enc_outputs, enc_outputs, dec_enc_attn_mask)\n dec_outputs = self.pos_ffn(dec_outputs)\n return dec_outputs, dec_self_attn, dec_enc_attn\n\nclass Encoder(nn.Module):\n def __init__(self):\n super(Encoder, self).__init__()\n self.src_emb = nn.Embedding(src_vocab_size, d_model)\n self.pos_emb = nn.Embedding.from_pretrained(get_sinusoid_encoding_table(src_len+1, d_model),freeze=True)\n self.layers = nn.ModuleList([EncoderLayer() for _ in range(n_layers)])\n\n def forward(self, enc_inputs): # enc_inputs : [batch_size x source_len]\n enc_outputs = self.src_emb(enc_inputs) + self.pos_emb(torch.LongTensor([[1,2,3,4,0]]))\n enc_self_attn_mask = get_attn_pad_mask(enc_inputs, enc_inputs)\n enc_self_attns = []\n for layer in self.layers:\n enc_outputs, enc_self_attn = layer(enc_outputs, enc_self_attn_mask)\n enc_self_attns.append(enc_self_attn)\n return enc_outputs, enc_self_attns\n\nclass Decoder(nn.Module):\n def __init__(self):\n super(Decoder, self).__init__()\n self.tgt_emb = nn.Embedding(tgt_vocab_size, d_model)\n self.pos_emb = nn.Embedding.from_pretrained(get_sinusoid_encoding_table(tgt_len+1, d_model),freeze=True)\n self.layers = nn.ModuleList([DecoderLayer() for _ in range(n_layers)])\n\n def forward(self, dec_inputs, enc_inputs, enc_outputs): # dec_inputs : [batch_size x target_len]\n dec_outputs = self.tgt_emb(dec_inputs) + self.pos_emb(torch.LongTensor([[5,1,2,3,4]]))\n dec_self_attn_pad_mask = get_attn_pad_mask(dec_inputs, dec_inputs)\n dec_self_attn_subsequent_mask = get_attn_subsequent_mask(dec_inputs)\n dec_self_attn_mask = torch.gt((dec_self_attn_pad_mask + dec_self_attn_subsequent_mask), 0)\n\n dec_enc_attn_mask = get_attn_pad_mask(dec_inputs, enc_inputs)\n\n dec_self_attns, dec_enc_attns = [], []\n for layer in self.layers:\n dec_outputs, dec_self_attn, dec_enc_attn = layer(dec_outputs, enc_outputs, dec_self_attn_mask, dec_enc_attn_mask)\n dec_self_attns.append(dec_self_attn)\n dec_enc_attns.append(dec_enc_attn)\n return dec_outputs, dec_self_attns, dec_enc_attns\n\nclass Transformer(nn.Module):\n def __init__(self):\n super(Transformer, self).__init__()\n self.encoder = Encoder()\n self.decoder = Decoder()\n self.projection = nn.Linear(d_model, tgt_vocab_size, bias=False)\n def forward(self, enc_inputs, dec_inputs):\n enc_outputs, enc_self_attns = self.encoder(enc_inputs)\n dec_outputs, dec_self_attns, dec_enc_attns = self.decoder(dec_inputs, enc_inputs, enc_outputs)\n dec_logits = self.projection(dec_outputs) # dec_logits : [batch_size x src_vocab_size x tgt_vocab_size]\n return dec_logits.view(-1, dec_logits.size(-1)), enc_self_attns, dec_self_attns, dec_enc_attns\n\nmodel = Transformer()\n\ncriterion = nn.CrossEntropyLoss()\noptimizer = optim.Adam(model.parameters(), lr=0.001)\n\ndef showgraph(attn):\n attn = attn[-1].squeeze(0)[0]\n attn = attn.squeeze(0).data.numpy()\n fig = plt.figure(figsize=(n_heads, n_heads)) # [n_heads, n_heads]\n ax = fig.add_subplot(1, 1, 1)\n ax.matshow(attn, cmap='viridis')\n ax.set_xticklabels(['']+sentences[0].split(), fontdict={'fontsize': 14}, rotation=90)\n ax.set_yticklabels(['']+sentences[2].split(), fontdict={'fontsize': 14})\n plt.show()\n\nfor epoch in range(20):\n optimizer.zero_grad()\n enc_inputs, dec_inputs, target_batch = make_batch(sentences)\n outputs, enc_self_attns, dec_self_attns, dec_enc_attns = model(enc_inputs, dec_inputs)\n loss = criterion(outputs, target_batch.contiguous().view(-1))\n print('Epoch:', '%04d' % (epoch + 1), 'cost =', '{:.6f}'.format(loss))\n loss.backward()\n optimizer.step()\n\n# Test\npredict, _, _, _ = model(enc_inputs, dec_inputs)\npredict = predict.data.max(1, keepdim=True)[1]\nprint(sentences[0], '->', [number_dict[n.item()] for n in predict.squeeze()])\n\nprint('first head of last state enc_self_attns')\nshowgraph(enc_self_attns)\n\nprint('first head of last state dec_self_attns')\nshowgraph(dec_self_attns)\n\nprint('first head of last state dec_enc_attns')\nshowgraph(dec_enc_attns)"
]
| [
[
"torch.nn.Softmax",
"numpy.sqrt",
"torch.nn.Embedding",
"torch.FloatTensor",
"torch.nn.CrossEntropyLoss",
"torch.from_numpy",
"numpy.sin",
"matplotlib.pyplot.figure",
"torch.LongTensor",
"numpy.power",
"torch.nn.Linear",
"torch.nn.Conv1d",
"matplotlib.pyplot.show",
"numpy.cos",
"numpy.ones",
"torch.nn.LayerNorm",
"torch.matmul",
"torch.nn.ReLU",
"torch.gt"
]
]
|
karlberggren/QuantumCircuitsClass | [
"ea0c7599c53a481ee854a0f8496cd91444311d16"
]
| [
"web_app/bokeh_measurement_and_diffusion/utils/wavefunction.py"
]
| [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Dec 16 17:34:28 2020\n\n@author: pmbpanther\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import quad, nquad\nfrom numpy.testing import assert_almost_equal\nfrom inspect import signature\n\nπ = np.pi\noo = np.inf\n\nclass Wavefunction(object):\n \"\"\"\n Class for 6.S079 Quantum Circuits, designed to work with and perform simple manipulations\n of wavefunctions, e.g. add, subtract, divide, multiply.\n \"\"\"\n \n def __init__(self, wfunc, ndim = None):\n \"\"\"\n Initializes an instance of the Wavefunction class, given a function object.\n wfunc must return a complex NumPy value.\n\n FIXME, slight concern what if someone calls Wavefunction(lambda *x: foobar(*x))\n \"\"\"\n self.ψ = wfunc\n self.ndim = ndim\n if not ndim:\n self.ndim = len(signature(wfunc).parameters)\n \n def __call__(self, *args):\n \"\"\"\n This code permits the wavefunction class to be callable\n\n >>> ψ = Wavefunction(lambda x: np.exp(-x**2))\n >>> print(ψ(0))\n 1.0\n >>> print(ψ.ψ(0))\n 1.0\n \"\"\"\n return self.ψ(*args)\n \n @classmethod\n def init_gaussian(cls, *args) -> \"Wavefunction object based on Gaussian\":\n \"\"\"\n Factory method that initializes a properly normalized Gaussian wavefunction.\n *args is a list of tuples. Each tuple contains (Xo, σ) for one of the\n dimensions along which the gaussian is to be defined\n\n >>> wf1 = Wavefunction.init_gaussian((0,1))\n >>> print(wf1(0))\n (0.6316187777460647+0j)\n\n\n >>> wf1 = Wavefunction.init_gaussian((0,1), (1,2))\n >>> print(wf1(0,1))\n (0.28209479177387814+0j)\n \"\"\"\n def result(*xs):\n return_val = 1\n for x, arg in zip(xs,args):\n Xo, σ = arg\n return_val *= np.exp(-(x - Xo)**2/(4*σ**2))/(2*π*σ**2)**0.25\n return return_val + 0j\n return cls(result, len(args))\n \n @classmethod\n def init_plane_wave(cls, *args) -> \"Wavefunction object based on plane wave\":\n \"\"\"\n Factory method that initializes a plane wave\n \"\"\"\n def result(*x):\n return_val = 1\n for i, arg in enumerate(args):\n Xo, λ = arg\n return_val *= np.exp(1j*(x[i]-Xo)*2*π/λ)\n return return_val\n return cls(result, len(args))\n\n\n @classmethod\n def init_interp(cls, vec):\n raise NotImplementedError\n \n def __add__(self, wf2):\n \"\"\"\n Note, the result is in general not normalized.\n\n >>> wf1 = Wavefunction.init_gaussian((0,1))\n >>> wf2 = Wavefunction.init_gaussian((1,2))\n >>> wf3 = wf1 + wf2\n >>> wf3(0)\n (1.0511812443492508+0j)\n >>> wf1(0) + wf2(0)\n (1.0511812443492508+0j)\n \"\"\"\n return self.__class__(lambda *x: self(*x) + wf2(*x))\n\n def __sub__(self, wf2):\n return self.__class__(lambda *x: self(*x) - wf2(*x))\n\n def __mul__(self, arg2):\n \"\"\"\n Multiply wavefunction by a complex value coefficient\n \"\"\"\n # FIXME, I think the first case should never happen\n if isinstance(arg2, self.__class__):\n return self.__class__(lambda *x: self(*x) * arg2(*x))\n else:\n return self.__class__(lambda *x: arg2 * self(*x))\n \n def __rmul__(self, arg2):\n \"\"\"\n Multiply wavefunction by another wavefunction or a complex value\n \"\"\" \n return self.__class__(lambda *x: arg2 * self(*x))\n\n \n def __truediv__(self, arg2):\n \"\"\"\n Divide wavefunction by another wavefunction or a complex value\n \"\"\"\n if not isinstance(arg2, self.__class__):\n return self.__class__(lambda *x: self(*x) / arg2)\n else:\n return self.__class__(lambda *x: self(*x) / arg2(*x))\n\n def __abs__(self):\n \"\"\" Calculate absolute value of wavefunction\n >>> abs(Wavefunction.init_gaussian((0,1)))\n 0.9999999999999997\n\n If for some reason the user wishes to normalize over a finite\n region (E.g. because the function is not integrable, or \n periodic boundary conditions are in effect over a finite range,\n the limits can be provided as a tuple.\n \"\"\"\n func = lambda *x: np.real(self(*x))**2 - np.imag(self(*x))**2\n limits = [(-oo, oo) for _ in range(self.ndim)]\n\n return nquad(func, limits)[0]\n\n\n def normalize(self): # FIXME\n \"\"\" \n Function returns a normalized wavefunction given an input of a non-normalized\n wavefunction. It is needed whenever wavefunctions are added.\n\n >>> wf = Wavefunction.init_gaussian((0,1)) + Wavefunction.init_gaussian((0,1))\n >>> abs(wf.normalize())\n 0.9999999999999999\n \"\"\"\n return self.__class__(self.ψ, self.ndim)/np.sqrt(abs(self))\n\n\n def vectorize(self, *args):\n \"\"\"\n Assigns the internal variable vec to be equal to the Wavefunction's ψ, broadcasted over an array,\n startingat x_min and ending at x_max, with N total points.\n\n Each dimension is spec'd in an (xmin, xmax, N) tuple\n \"\"\"\n # make arrays\n array_list = []\n for x_min, x_max, N in args:\n array_list.append(np.linspace(x_min, x_max, N))\n X = np.meshgrid(*array_list)\n self.mat = self(*X)\n self.ranges = args\n self.vec = self.mat.copy().flatten()\n return self.vec\n\n def visualize1D(self, **kwargs):\n \"\"\"\n plot_wavefunction:: plot a one-dimensional wavefunction.\n\n This is intended to be a utility function, so that, for example, one can quickly plot\n something as part of another routine. It can also be used to simply plot a static\n wavefunction.\n\n Not implemented: use it to update artists for an animation or another graphic setting\n that is already constructed. \n\n self: wavefunction to be plotted, can be a func or a vector\n range: tuple with min-max to be plotted\n N: number of plotpoints\n method: cartesian, polar, pdf, or 3d\n \"\"\"\n x_min, x_max = kwargs[\"x_range\"]\n xs = np.linspace(x_min, x_max, kwargs[\"N\"])\n x_label = kwargs[\"x_label\"]\n method = kwargs[\"method\"]\n\n # be flexible about accepting self either as a function or a vector\n try:\n ψs = self(xs)\n except:\n raise NotImplementedError\n\n if method == \"cartesian\": \n plt.plot(xs, np.abs(ψs), label=\"|ψ|\")\n plt.plot(xs, np.real(ψs), label=\"real part\")\n plt.plot(xs, np.imag(ψs), label=\"imaginary part\")\n plt.legend(loc='upper right')\n plt.xlabel(x_label)\n plt.ylabel(\"Amplitude\")\n plt.title(\"Wavefunction\")\n return plt.gcf()\n\n if method == \"polar\":\n # or equivalently, one can look at magnitude and phase\n fig, (ax1, ax2) = plt.subplots(2)\n fig.suptitle('Polar plot')\n ax1.plot(xs, np.abs(ψs), label=\"magnitude\")\n ax1.set(ylabel=\"|ψ|\")\n ax2.plot(xs, np.angle(ψs), label=\"phase\")\n ax2.set(xlabel=x_label, ylabel=\"∠ψ\")\n return plt.gcf()\n \n if method == \"pdf\":\n plt.plot(xs, np.abs(ψs)**2, color=\"black\")\n plt.xlabel(x_label)\n plt.ylabel(\"|ψ|²\")\n plt.title(\"Prob. dens. func.\")\n return plt.gcf()\n \n if method == \"3d\":\n #Adjusts the aspect ratio and enlarges the figure (text does not enlarge)\n fig = plt.figure(figsize=plt.figaspect(0.5)*1.5)\n ax = fig.gca(projection='3d')\n\n # Prepare arrays x, y, z\n y = np.imag(ψs)\n z = np.real(ψs)\n ax.plot(xs, y, z, label='parametric curve', color=\"red\")\n\n # Plot a curves using the x and y axes.\n ax.plot(xs, y, zs=-1, zdir='z', label='imag part')\n\n # Plot a curves using the x and z axes.\n ax.plot(xs, z, zs=1, zdir='y', label='real part')\n\n # Plot pdf using the x and z axes\n z = np.abs(ψs)\n ax.plot(xs, z, zs=1, zdir='y', label='|Ψ|', color='black')\n\n x = [x_min, x_max]\n y = [0,0]\n z = [0,0]\n ax.plot(x, y, z, label='axis')\n\n ax.legend()\n plt.rcParams['legend.fontsize'] = 10\n return plt.gcf()\n\nclass Ket(Wavefunction):\n def __init__(self, wf, ndim = None):\n if isinstance(wf, Bra):\n new_func = lambda *x: np.conj(wfunc(*x))\n Wavefunction.__init__(new_func, wf.ndim)\n else:\n Wavefunction.__init__(self, wf, ndim)\n\n def __mul__(self, arg2):\n if arg2.__class__ == Bra:\n raise NotImplementedError(\"This code cannot multiply Kets times Bras. You probably did this in error\")\n else:\n return Wavefunction.__mul__(self, arg2)\n \n def __rmatmul__(self, op1):\n \"\"\"\n multiply operator by a ket, returning a ket, e.g.\n O @ ket1 = ket2\n \"\"\"\n return op1(self)\n\nclass Bra(Wavefunction):\n def __init__(self, wf, ndim = None):\n if isinstance(wf, Ket):\n new_func = lambda *x: np.conj(wfunc(*x))\n Wavefunction.__init__(new_func, wf.ndim)\n else:\n Wavefunction.__init__(self,wf,ndim)\n\n\n def __mul__(self, arg2):\n if arg2.__class__ == Ket:\n raise NotImplementedError(\"\"\"str(\n '*' does not multiply Bra's times Ket's. If you want to do this, use '@'.\n A Bra is effectively a row vector, and a Ket is effectively a column vector,\n so their product is effectively a dot product (i.e. a matrix operation).\n \"\"\")\n else:\n return Wavefunction.__mul__(self, arg2)\n\n def __matmul__(self, ket):\n if not isinstance(ket, Ket):\n return NotImplemented\n func_to_split = lambda *x:self(*x) * ket(*x)\n real_func = lambda *x: np.real(func_to_split(*x))\n imag_func = lambda *x: np.imag(func_to_split(*x))\n\n limits = [(-oo, oo) for _ in range(self.ndim)]\n real_int = nquad(real_func, limits)[0]\n imag_int = nquad(imag_func, limits)[0]\n \n return real_int + 1j*imag_int\n\n \nif __name__ == '__main__':\n from numpy.testing import assert_approx_equal\n # test init gaussian\n for cls_type in [Wavefunction, Ket, Bra]:\n wf2 = cls_type.init_plane_wave((0, 1))\n wf1 = cls_type.init_gaussian((0, 1))\n assert wf1(0) == 1/(2*π)**0.25+0j, \"Error creating gaussian\"\n # test init plane wave\n assert wf2(0) == 1+0j, \"Error creating plane wave\"\n # test multiply by int\n assert (wf1*3)(0) == 3/(2*π)**0.25+0j, \"Error multiplying wavefunc by an int\"\n assert (3*wf1)(0) == 3/(2*π)**0.25+0j, \"Error multiplying wavefunc by an int\"\n # test mult by float\n assert (wf1*3.5)(0) == 3.5/(2*π)**0.25+0j, \"Error multiplying by a float\"\n # test mult by wf\n assert (wf1*wf2)(0) == 1/(2*π)**0.25+0j, \"Error multiplying two wfs\"\n # test div by int\n assert (wf1/2)(0) == .5/(2*π)**0.25+0j, \"Error dividing by int\" \n # test div by float\n assert (wf1/0.5)(0) == 2/(2*π)**0.25+0j, \"Error dividing by float\"\n # test div by wf\n assert (wf1/wf2)(0) == 1/(2*π)**0.25+0j, \"Error dividing wf by wf\"\n # test add two wfs\n assert (wf1+wf2)(0) == 1+1/(2*π)**0.25+0j, \"Error adding wf and wf\"\n # test sub two wfs\n assert (wf1-wf2)(0) == 1/(2*π)**0.25-1+0j, \"Error subtracting wf from wf\"\n # test vectorization of wfs\n wf1.vectorize((-10, 10, 21))\n assert wf1.mat[10] == 1/(2*π)**0.25+0j, \"Error vectorizing wf\"\n\n #tests init 2d gaussian\n wf3 = cls_type.init_gaussian((0,1),(0,2)) \n assert wf3(0,0) == 1/(2*π)**0.25/(2*π*4)**.25, \"Error creating gaussian\"\n # test multiply by int \n assert_approx_equal(np.real((wf3*3)(0,0)), 3/(2*π)**0.25/(2*π*4)**.25,\n err_msg = \"Error multiplying wavefunc by an int\")\n # test mult by float\n assert_approx_equal(np.real((wf3*3.5)(0,0)), 3.5/(2*π)**0.25/(2*π*4)**.25,\n err_msg = \"Error multiplying by a float\")\n #tests init 2d plane wave\n wf4 = cls_type.init_plane_wave((0,1),(0,2))\n assert wf4(0,0) == 1+0j, \"Error creating plane wave\"\n # test 2d vectorization\n wf3.vectorize((-10, 10, 21),(-10, 10, 21))\n assert wf3.mat[10][10] == 1/(2*π)**0.25/(2*π*4)**.25, \"Error vectorizing 2d wf\"\n #make test cases for vectorization in vectorize method.n\n assert wf3.vec[220] == 1/(2*π)**0.25/(2*π*4)**.25, \"Error vectorizing 2d wf\"\n wf3.vectorize((-10, 10, 41),(-10, 10, 21))\n assert wf3.mat[10][20] == 1/(2*π)**0.25/(2*π*4)**.25, \"Error vectorizing 2d wf\"\n \"\"\"\n # test div by int\n assert (wf3/2)(0,0) == .5/(2*π)**0.25/(2*π*4)**.25, \"Error dividing by int\" \n # test div by float\n assert (wf3/0.5)(0,0) == 2/(2*π)**0.25/(2*π*4)**.25, \"Error dividing by float\"\n \"\"\"\n\n wf1 = cls_type.init_gaussian((0, 1))*1j\n plot_params = {\"x_range\": (-4, 4), \"N\": 40,\n \"method\": \"pdf\", \"x_label\": \"Q\"}\n plt.close()\n plot_result = wf1.visualize1D(**plot_params)\n plot_result.savefig(\"wavefunction_plot_test_file_new.png\")\n from matplotlib.testing.compare import compare_images\n try:\n assert not compare_images(\"wavefunction_plot_test_file.png\", \"wavefunction_plot_test_file_new.png\", .001),\"Error plotting wf\"\n except AssertionError:\n print(\"AssertionError: Error plotting wf\")\n finally:\n import os\n os.remove(\"wavefunction_plot_test_file_new.png\")\n\n for cls1,cls2 in ((Bra, Ket), (Ket, Bra)): \n wf2 = cls1.init_plane_wave((0, 1))\n wf1 = cls2.init_gaussian((0, 1))\n try :\n wf1 * wf2\n except NotImplementedError:\n pass\n else:\n raise AssertionError(f\"{cls2} * {cls1} worked, shouldn't have\")\n\n \n \"\"\"\n test 3 D figure plot\n\n # plot_params[\"method\"] = \"cartesian\"\n # plot_params[\"method\"] = \"polar\"\n plot_params[\"method\"] = \"3d\"\n plt.close()\n wf1.plot_wf(**plot_params)\n plt.show()\n \"\"\"\n\n # testing 1d expectation values\n wf2 = Ket.init_gaussian((0, 2))\n wf1 = Bra.init_gaussian((0, 2))\n assert_almost_equal(wf1 @ wf2, 1, err_msg = \"1d Expectation value not working\")\n \n # testing 2d expectation values\n print(\"Starting 2D test routine\")\n wf2 = Ket.init_gaussian((0, 1), (0,2))\n wf1 = Bra.init_gaussian((0, 1), (0,2))\n assert_almost_equal(wf1 @ wf2, 1, err_msg = \"2d Expectation value not working\")\n\n import doctest\n doctest.testmod()\n \n print(\"Ended Wavefunction run\")\n\n \n"
]
| [
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.figaspect",
"numpy.imag",
"numpy.abs",
"numpy.linspace",
"matplotlib.pyplot.title",
"matplotlib.testing.compare.compare_images",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.gcf",
"numpy.testing.assert_almost_equal",
"numpy.real",
"scipy.integrate.nquad",
"matplotlib.pyplot.close",
"numpy.exp",
"matplotlib.pyplot.xlabel",
"numpy.angle",
"numpy.meshgrid",
"matplotlib.pyplot.ylabel"
]
]
|
omartrinidad/pattern-recognition-bit | [
"ba3eb4e541fff2b1aedbaa4420d7a8cea8100dc7"
]
| [
"03/lloyd-algorithm.py"
]
| [
"import numpy as np\n\nk = 3\nX = np.genfromtxt(\"data-clustering-1.csv\", dtype=float, delimiter=',')\nX = X.T\nmax_iter = 100\n\nn_examples = X.shape[0]\nn_features = X.shape[1]\nn_classes = k\n\n# Initialization\nt = 0\nu = np.random.rand(k, n_features)\nconverged = False\n\nindices = np.arange(n_examples)\n\n# Loop\nwhile(not(converged)):\n u_old = u\n distance_to_centroids = np.vstack([np.linalg.norm(X-u[i], axis=1) for i in range(k)])\n closest_cluster = np.argmin(distance_to_centroids, axis=0)\n C = np.array([indices[np.where(closest_cluster == i)] for i in range(k)])\n u = np.vstack([np.mean(X[C[i], :], axis=0)] for i in range(k))\n t = t + 1\n if(t==max_iter): converged = True\n if(np.array_equal(u_old,u)): converged = True\n"
]
| [
[
"numpy.array_equal",
"numpy.arange",
"numpy.linalg.norm",
"numpy.genfromtxt",
"numpy.argmin",
"numpy.random.rand",
"numpy.mean",
"numpy.where"
]
]
|
wenleix/torcharrow-1 | [
"9c398a361156973e29be868520ea9278db00ea52"
]
| [
"torcharrow/test/test_numerical_column.py"
]
| [
"# Copyright (c) Facebook, Inc. and its affiliates.\nimport statistics\nimport unittest\nfrom math import ceil, floor, log\n\nimport numpy as np\nimport numpy.testing\nimport torcharrow as ta\nimport torcharrow.dtypes as dt\nfrom torcharrow.icolumn import IColumn\nfrom torcharrow.inumerical_column import INumericalColumn\nfrom torcharrow.scope import Scope\n\n\nclass TestNumericalColumn(unittest.TestCase):\n def base_test_empty(self):\n empty_i64_column = ta.Column(dtype=dt.int64, device=self.device)\n\n # testing internals...\n self.assertTrue(isinstance(empty_i64_column, INumericalColumn))\n self.assertEqual(empty_i64_column.dtype, dt.int64)\n self.assertEqual(len(empty_i64_column), 0)\n self.assertEqual(empty_i64_column.null_count, 0)\n self.assertEqual(len(empty_i64_column), 0)\n\n return empty_i64_column\n\n def base_test_full(self):\n col = ta.Column([i for i in range(4)], dtype=dt.int64, device=self.device)\n\n # self.assertEqual(col._offset, 0)\n self.assertEqual(len(col), 4)\n self.assertEqual(col.null_count, 0)\n self.assertEqual(list(col), list(range(4)))\n m = col[0 : len(col)]\n self.assertEqual(list(m), list(range(4)))\n return col\n\n def base_test_is_immutable(self):\n col = ta.Column([i for i in range(4)], dtype=dt.int64, device=self.device)\n with self.assertRaises(AttributeError):\n # AssertionError: can't append a finalized list\n col._append(None)\n\n def base_test_full_nullable(self):\n col = ta.Column(dtype=dt.Int64(nullable=True), device=self.device)\n\n col = col.append([None, None, None])\n self.assertEqual(col[-1], None)\n\n col = col.append([3])\n self.assertEqual(col[-1], 3)\n\n self.assertEqual(col.length, 4)\n self.assertEqual(col.null_count, 3)\n\n self.assertEqual(col[0], None)\n self.assertEqual(col[3], 3)\n\n self.assertEqual(list(col), [None, None, None, 3])\n\n def base_test_indexing(self):\n col = ta.Column(\n [None] * 3 + [3, 4, 5], dtype=dt.Int64(nullable=True), device=self.device\n )\n\n # index\n self.assertEqual(col[0], None)\n self.assertEqual(col[-1], 5)\n\n # slice\n\n # continuous slice\n c = col[3 : len(col)]\n self.assertEqual(len(col), 6)\n self.assertEqual(len(c), 3)\n\n # non continuous slice\n d = col[::2]\n self.assertEqual(len(col), 6)\n self.assertEqual(len(d), 3)\n\n # slice has Python not Panda semantics\n e = col[: len(col) - 1]\n self.assertEqual(len(e), len(col) - 1)\n\n # indexing via lists\n f = col[[0, 1, 2]]\n self.assertEqual(list(f), list(col[:3]))\n\n # head/tail are special slices\n self.assertEqual(list(col.head(2)), [None, None])\n self.assertEqual(list(col.tail(2)), [4, 5])\n\n def base_test_boolean_column(self):\n\n col = ta.Column(dt.boolean, device=self.device)\n self.assertIsInstance(col, INumericalColumn)\n\n col = col.append([True, False, False])\n self.assertEqual(list(col), [True, False, False])\n\n # numerics can be converted to booleans...\n col = col.append([1])\n self.assertEqual(list(col), [True, False, False, True])\n\n def base_test_infer(self):\n # not enough info\n with self.assertRaises(ValueError):\n ta.Column([], device=self.device)\n\n # int\n c = ta.Column([1], device=self.device)\n self.assertEqual(c.dtype, dt.int64)\n self.assertEqual(list(c), [1])\n c = ta.Column([np.int64(2)], device=self.device)\n self.assertEqual(c.dtype, dt.int64)\n self.assertEqual(list(c), [2])\n c = ta.Column([np.int32(3)], device=self.device)\n self.assertEqual(c.dtype, dt.int32)\n self.assertEqual(list(c), [3])\n c = ta.Column([np.int16(4)], device=self.device)\n self.assertEqual(c.dtype, dt.int16)\n self.assertEqual(list(c), [4])\n c = ta.Column([np.int8(5)], device=self.device)\n self.assertEqual(c.dtype, dt.int8)\n self.assertEqual(list(c), [5])\n\n # bool\n c = ta.Column([True, None], device=self.device)\n self.assertEqual(c.dtype, dt.Boolean(nullable=True))\n self.assertEqual(list(c), [True, None])\n\n # note implicit promotion of bool to int\n c = ta.Column([True, 1], device=self.device)\n self.assertEqual(c.dtype, dt.int64)\n self.assertEqual(list(c), [1, 1])\n\n # float\n c = ta.Column([1.0, 2.0], device=self.device)\n self.assertEqual(c.dtype, dt.float32)\n self.assertEqual(list(c), [1.0, 2.0])\n c = ta.Column([1, 2.0], device=self.device)\n self.assertEqual(c.dtype, dt.float32)\n self.assertEqual(list(c), [1.0, 2.0])\n c = ta.Column([np.float64(1.0), 2.0], device=self.device)\n self.assertEqual(c.dtype, dt.float64)\n self.assertEqual(list(c), [1.0, 2.0])\n c = ta.Column([np.float64(1.0), np.float32(2.0)], device=self.device)\n self.assertEqual(c.dtype, dt.float64)\n self.assertEqual(list(c), [1.0, 2.0])\n\n def base_test_map_where_filter(self):\n col = ta.Column(\n [None] * 3 + [3, 4, 5], dtype=dt.Int64(nullable=True), device=self.device\n )\n\n # Values that are not found in the dict are converted to None\n self.assertEqual(list(col.map({3: 33})), [None, None, None, 33, None, None])\n\n # maps None\n self.assertEqual(\n list(col.map({None: 1, 3: 33})),\n [1, 1, 1, 33, None, None],\n )\n\n # propagates None\n self.assertEqual(\n list(col.map({None: 1, 3: 33}, na_action=\"ignore\")),\n [None, None, None, 33, None, None],\n )\n\n # maps as function\n self.assertEqual(\n list(\n col.map(\n lambda x: 1 if x is None else 33 if x == 3 else x,\n )\n ),\n [1, 1, 1, 33, 4, 5],\n )\n\n left = ta.Column([0] * 6, device=self.device)\n right = ta.Column([99] * 6, device=self.device)\n self.assertEqual(\n list(ta.if_else(col > 3, left, right)),\n [None, None, None, 99, 0, 0],\n )\n\n # filter\n self.assertEqual(list(col.filter([True, False] * 3)), [None, None, 4])\n\n @staticmethod\n def _accumulate(col, val):\n if len(col) == 0:\n col._append(val)\n else:\n col._append(col[-1] + val)\n return col\n\n @staticmethod\n def _finalize(col):\n return col._finalize()\n\n def base_test_reduce(self):\n c = ta.Column([1, 2, 3], device=self.device)\n d = c.reduce(\n fun=TestNumericalColumn._accumulate,\n initializer=Scope._EmptyColumn(dt.int64, device=self.device),\n finalizer=TestNumericalColumn._finalize,\n )\n self.assertEqual(list(d), [1, 3, 6])\n\n def base_test_sort_stuff(self):\n col = ta.Column([2, 1, 3], device=self.device)\n\n self.assertEqual(list(col.sort()), [1, 2, 3])\n self.assertEqual(list(col.sort(ascending=False)), [3, 2, 1])\n self.assertEqual(\n list(ta.Column([None, 1, 5, 2], device=self.device).sort()), [1, 2, 5, None]\n )\n self.assertEqual(\n list(\n ta.Column([None, 1, 5, 2], device=self.device).sort(na_position=\"first\")\n ),\n [None, 1, 2, 5],\n )\n self.assertEqual(\n list(\n ta.Column([None, 1, 5, 2], device=self.device).sort(na_position=\"last\")\n ),\n [1, 2, 5, None],\n )\n\n self.assertEqual(\n list(\n ta.Column([None, 1, 5, 2], device=self.device).sort(na_position=\"last\")\n ),\n [1, 2, 5, None],\n )\n\n # self.assertEqual(\n # list(ta.Column([None, 1, 5, 2]).nlargest(n=2, keep=\"first\")), [5, 2] # TODO zhongxu\n # )\n \"\"\"\n self.assertEqual(\n list(\n ta.Column([None, 1, 5, 2], device=self.device).nsmallest(\n n=2, keep=\"last\"\n )\n ),\n [1, 2],\n )\n \"\"\"\n\n def base_test_operators(self):\n # without None\n c = ta.Column([0, 1, 3], device=self.device)\n d = ta.Column([5, 5, 6], device=self.device)\n e = ta.Column([1.0, 1, 7], device=self.device)\n\n # ==, !=\n\n self.assertEqual(list(c == c), [True] * 3)\n self.assertEqual(list(c == d), [False] * 3)\n self.assertEqual(list(c != c), [False] * 3)\n self.assertEqual(list(c != d), [True] * 3)\n\n self.assertEqual(list(c == 1), [False, True, False])\n self.assertEqual(list(1 == c), [False, True, False])\n self.assertTrue(\n ((c == 1) == ta.Column([False, True, False], device=self.device)).all()\n )\n self.assertTrue(\n ((1 == c) == ta.Column([False, True, False], device=self.device)).all()\n )\n\n # validate comparing non-equal length columns fails\n with self.assertRaises(TypeError):\n assert c == c.append([None])\n\n # <, <=, >=, >\n\n self.assertEqual(list(c <= 2), [True, True, False])\n self.assertEqual(list(c <= e), [True, True, True])\n self.assertEqual(list(c < 1), [True, False, False])\n self.assertEqual(list(c < d), [True, True, True])\n self.assertEqual(list(c >= 1), [False, True, True])\n self.assertEqual(list(c >= d), [False, False, False])\n self.assertEqual(list(c > 2), [False, False, True])\n self.assertEqual(list(c > d), [False, False, False])\n\n # +,-,*,/,//,**,%\n\n self.assertEqual(list(-c), [0, -1, -3])\n self.assertEqual(list(+-c), [0, -1, -3])\n\n self.assertEqual(list(c + 1), [1, 2, 4])\n self.assertEqual(list(e + 1), [2.0, 2.0, 8.0])\n\n # self.assertEqual(list(c.add(1)), [1, 2, 4])\n\n self.assertEqual(list(1 + c), [1, 2, 4])\n # self.assertEqual(list(c.radd(1)), [1, 2, 4])\n\n self.assertEqual(list(c + d), [5, 6, 9])\n # self.assertEqual(list(c.add(d)), [5, 6, 9])\n\n self.assertEqual(list(c + 1), [1, 2, 4])\n self.assertEqual(list(1 + c), [1, 2, 4])\n self.assertEqual(list(c + d), [5, 6, 9])\n\n self.assertEqual(list(c - 1), [-1, 0, 2])\n self.assertEqual(list(1 - c), [1, 0, -2])\n self.assertEqual(list(d - c), [5, 4, 3])\n\n self.assertEqual(list(c * 2), [0, 2, 6])\n self.assertEqual(list(2 * c), [0, 2, 6])\n self.assertEqual(list(c * d), [0, 5, 18])\n\n self.assertEqual(list(c * 2), [0, 2, 6])\n self.assertEqual(list(2 * c), [0, 2, 6])\n self.assertEqual(list(c * d), [0, 5, 18])\n\n self.assertEqual(list(c / 2), [0.0, 0.5, 1.5])\n self.assertEqual(list(c / 0), [None, None, None])\n\n self.assertEqual(\n [round(i, 2) if i is not None else None for i in list(2 / c)],\n [round(i, 2) if i is not None else None for i in [None, 2.0, 0.66666667]],\n )\n\n self.assertEqual(list(c / d), [0.0, 0.2, 0.5])\n\n self.assertEqual(list(d // 2), [2, 2, 3])\n self.assertEqual(list(2 // d), [0, 0, 0])\n self.assertEqual(list(c // d), [0, 0, 0])\n self.assertEqual(list(e // d), [0.0, 0.0, 1.0])\n\n self.assertEqual(list(d // e), [5.0, 5.0, 0.0])\n\n self.assertEqual(list(c ** 2), [0, 1, 9])\n self.assertEqual(list(2 ** c), [1, 2, 8])\n self.assertEqual(list(c ** d), [0, 1, 729])\n\n self.assertEqual(list(d % 2), [1, 1, 0])\n self.assertEqual(list(2 % d), [2, 2, 2])\n self.assertEqual(list(c % d), [0, 1, 3])\n\n # TODO: Decide ...null handling.., bring back or ignore\n\n # c = ta.Column([0, 1, 3, None])\n # self.assertEqual(list(c.add(1)), [1, 2, 4, None])\n\n # self.assertEqual(list(c.add(1, fill_value=17)), [1, 2, 4, 18])\n # self.assertEqual(list(c.radd(1, fill_value=-1)), [1, 2, 4, 0])\n # f = ta.Column([None, 1, 3, None])\n # self.assertEqual(list(c.radd(f, fill_value=100)), [100, 2, 6, 200])\n\n # &, |, ^, ~\n g = ta.Column([True, False, True, False], device=self.device)\n h = ta.Column([False, False, True, True], device=self.device)\n self.assertEqual(list(g & h), [False, False, True, False])\n self.assertEqual(list(g | h), [True, False, True, True])\n self.assertEqual(list(g ^ h), [True, False, False, True])\n self.assertEqual(list(True & g), [True, False, True, False])\n self.assertEqual(list(True | g), [True, True, True, True])\n self.assertEqual(list(True ^ g), [False, True, False, True])\n self.assertEqual(list(~g), [False, True, False, True])\n\n i = ta.Column([1, 2, 0], device=self.device)\n j = ta.Column([3, 2, 3], device=self.device)\n self.assertEqual(list(i & j), [1, 2, 0])\n self.assertEqual(list(i | j), [3, 2, 3])\n self.assertEqual(list(i ^ j), [2, 0, 3])\n self.assertEqual(list(2 & i), [0, 2, 0])\n self.assertEqual(list(2 | i), [3, 2, 2])\n self.assertEqual(list(2 ^ i), [3, 0, 2])\n self.assertEqual(list(~i), [-2, -3, -1])\n\n # TODO Test type promotion rules\n\n def base_test_na_handling(self):\n c = ta.Column([None, 2, 17.0], device=self.device)\n\n self.assertEqual(list(c.fill_null(99.0)), [99.0, 2, 17.0])\n self.assertEqual(list(c.drop_null()), [2.0, 17.0])\n\n c = c.append([2])\n self.assertEqual(set(c.drop_duplicates()), {None, 2, 17.0})\n\n def base_test_agg_handling(self):\n import functools\n import operator\n\n c = [1, 4, 2, 7, 9, 1]\n D = ta.Column(c, device=self.device)\n C = ta.Column(c + [None], device=self.device)\n\n self.assertEqual(C.dtype, dt.Int64(nullable=True))\n self.assertEqual(C.min(), min(c))\n self.assertEqual(C.max(), max(c))\n self.assertEqual(C.sum(), sum(c))\n self.assertEqual(C.mode(), statistics.mode(c))\n\n self.assertEqual(D.std(), (statistics.stdev((float(i) for i in c))))\n\n self.assertEqual(C.std(), (statistics.stdev((float(i) for i in c))))\n self.assertEqual(C.mean(), statistics.mean(c))\n self.assertEqual(C.median(), statistics.median(c))\n\n self.assertEqual(\n list(C._cummin()), [min(c[:i]) for i in range(1, len(c) + 1)] + [None]\n )\n self.assertEqual(\n list(C._cummax()), [max(c[:i]) for i in range(1, len(c) + 1)] + [None]\n )\n self.assertEqual(\n list(C.cumsum()), [sum(c[:i]) for i in range(1, len(c) + 1)] + [None]\n )\n self.assertEqual(\n list(C._cumprod()),\n [functools.reduce(operator.mul, c[:i], 1) for i in range(1, len(c) + 1)]\n + [None],\n )\n self.assertEqual((C % 2 == 0)[:-1].all(), all(i % 2 == 0 for i in c))\n self.assertEqual((C % 2 == 0)[:-1].any(), any(i % 2 == 0 for i in c))\n\n def base_test_in_nunique(self):\n c = [1, 4, 2, 7]\n C = ta.Column(c + [None])\n self.assertEqual(list(C.isin([1, 2, 3])), [True, False, True, False, False])\n C = C.append(c)\n d = set(c)\n d.add(None)\n # self.assertEqual(C.nunique(), len(set(C) - {None}))\n # self.assertEqual(C.nunique(drop_null=False), len(set(C)))\n\n self.assertEqual(C.is_unique, False)\n self.assertEqual(ta.Column([1, 2, 3], device=self.device).is_unique, True)\n\n self.assertEqual(\n ta.Column([1, 2, 3], device=self.device).is_monotonic_increasing, True\n )\n self.assertEqual(ta.Column(dtype=dt.int64).is_monotonic_decreasing, True)\n\n def base_test_math_ops(self):\n c = [1.0, 4.2, 2, 7, -9, -2.5]\n C = ta.Column(c + [None], device=self.device)\n self.assertEqual(C.dtype, dt.Float32(nullable=True))\n\n numpy.testing.assert_almost_equal(list(C.abs())[:-1], [abs(i) for i in c], 6)\n self.assertEqual(list(C.abs())[-1], None)\n\n self.assertEqual(list(C.ceil())[:-1], [ceil(i) for i in c])\n self.assertEqual(list(C.ceil())[-1], None)\n\n self.assertEqual(list(C.floor())[:-1], [floor(i) for i in c])\n self.assertEqual(list(C.floor())[-1], None)\n\n self.assertEqual(list(C.round()), [round(i) for i in c] + [None])\n\n numpy.testing.assert_almost_equal(\n list(C.round(2))[:-1], [round(i, 2) for i in c], 6\n )\n self.assertEqual(list(C.round(2))[-1], None)\n # self.assertEqual(list(C.hash_values()), [hash(i) for i in c] + [None])\n\n c1 = ta.Column(\n [1, 0, 4, None], device=self.device, dtype=dt.Int32(nullable=True)\n )\n c2 = ta.Column(\n [1, 0, 4, None], device=self.device, dtype=dt.Float32(nullable=True)\n )\n for col in [c1, c2]:\n numpy.testing.assert_almost_equal(\n list(col.log())[:-1], [0.0, -float(\"inf\"), log(4)]\n )\n self.assertEqual(col.log().dtype, dt.Float32(nullable=True))\n self.assertEqual(list(col.log())[-1], None)\n\n c3 = ta.Column(\n [1.0, 0.0, 4.0, None], device=self.device, dtype=dt.Float64(nullable=True)\n )\n numpy.testing.assert_almost_equal(\n list(c3.log())[:-1], [0.0, -float(\"inf\"), log(4)]\n )\n self.assertEqual(c3.log().dtype, dt.Float64(nullable=True))\n self.assertEqual(list(c2.log())[-1], None)\n\n def base_test_describe(self):\n # requires 'implicitly' torcharrow.dataframe import DataFrame\n c = ta.Column([1, 2, 3], device=self.device)\n self.assertEqual(\n list(c.describe()),\n [\n (\"count\", 3.0),\n (\"mean\", 2.0),\n (\"std\", 1.0),\n (\"min\", 1.0),\n (\"25%\", 1.5),\n (\"50%\", 2.0),\n (\"75%\", 2.5),\n (\"max\", 3.0),\n ],\n )\n\n def base_test_cast(self):\n data = [1, 2, 3]\n col_int64 = ta.Column(data, device=\"cpu\")\n col2_int32 = col_int64.cast(dt.int32)\n self.assertEqual(list(col2_int32), data)\n self.assertEqual(col2_int32.dtype, dt.int32)\n\n data2 = [1, 2, None]\n col3 = ta.Column(data2, device=\"cpu\", dtype=dt.Int32(nullable=True))\n col3_float64 = col3.cast(dt.Float64(nullable=True))\n self.assertEqual(col3_float64.dtype, dt.Float64(nullable=True))\n self.assertEqual(list(col3_float64), data2)\n\n def base_test_column_from_numpy_array(self):\n seq_float = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]\n seq_int = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n seq_bool = [True, False, True, False, False, False, True, True, False]\n\n array_float32 = np.array(seq_float, dtype=np.float32)\n column_float32 = ta.Column(array_float32, device=self.device)\n self.assertEqual(list(column_float32), seq_float)\n\n array_float64 = np.array(seq_float, dtype=np.float64)\n column_float64 = ta.Column(array_float64, device=self.device)\n self.assertEqual(list(column_float64), seq_float)\n\n array_int32 = np.array(seq_int, dtype=np.int32)\n column_int32 = ta.Column(array_int32, device=self.device)\n self.assertEqual(list(column_int32), seq_int)\n\n array_int64 = np.array(seq_int, dtype=np.int64)\n column_int64 = ta.Column(array_int64, device=self.device)\n self.assertEqual(list(column_int64), seq_int)\n\n array_bool = np.array(seq_bool, dtype=np.bool)\n column_bool = ta.Column(array_bool, device=self.device)\n self.assertEquals(list(column_bool), seq_bool)\n\n def base_test_append_automatic_conversions(self):\n # ints ARE converted to floats\n seq_float = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]\n column_float = ta.Column(seq_float, device=self.device)\n column_float = column_float.append([11, 12])\n self.assertEqual(list(column_float), seq_float + [11.0, 12.0])\n\n # floats ARE NOT converted to ints\n seq_int = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n column_int = ta.Column(seq_int, device=self.device)\n with self.assertRaises(TypeError):\n # TypeError: append(): incompatible function arguments.\n column_int.append([11.0, 12.0])\n\n # ints ARE converted to bools\n seq_bool = [True, False, True, False, False, True, True]\n column_bool = ta.Column(seq_bool, device=self.device)\n column_bool = column_bool.append([1, 1, 0, 0])\n self.assertEqual(list(column_bool), seq_bool + [True, True, False, False])\n\n # floats ARE NOT converted to bools\n column_bool = ta.Column(seq_bool, device=self.device)\n with self.assertRaises(TypeError):\n # TypeError: append(): incompatible function arguments.\n column_bool = column_bool.append([1.0, 1.0, 0.0, 0.0])\n\n # experimental\n def base_test_batch_collate(self):\n c = ta.Column([1, 2, 3, 4, 5, 6, 7], device=self.device)\n # test iter\n it = c.batch(2)\n res = []\n for i in it:\n res.append(list(i))\n self.assertEqual(res, [[1, 2], [3, 4], [5, 6], [7]])\n # test collate\n it = c.batch(2)\n self.assertEqual(list(IColumn.unbatch(it)), [1, 2, 3, 4, 5, 6, 7])\n\n\nif __name__ == \"__main__\":\n\n unittest.main()\n"
]
| [
[
"numpy.int32",
"numpy.int8",
"numpy.int16",
"numpy.int64",
"numpy.float64",
"numpy.float32",
"numpy.array"
]
]
|
anonomity/MinMaxCheckers | [
"faadb081399387e38b061cd555c71eb9c02cd3d0"
]
| [
"src/board.py"
]
| [
"import numpy as np\nfrom pawn import pawn\nimport copy\nimport random\n\nclass board():\n\n\n def __init__(self):\n pos = 0\n col = pos % 8\n row = pos // 8\n reso = col % 2\n count = 1\n board = np.zeros([8, 8], dtype=int)\n posBoard = np.zeros([8, 8], dtype=int)\n self.board = board\n self.posBoard = posBoard\n pawns = []\n self.pawns = pawns\n finish = False\n while finish == False:\n if row < 3:\n col = pos % 8\n row = pos // 8\n reso = col % 2\n if (row == 0) | (row == 2):\n if col == 8 - 1:\n self.posBoard[row][col] = pos\n pos += 1\n elif reso == 0:\n self.board[row][col] = count\n\n pawns.insert(count,pawn(0, pos, self.board, count, self.posBoard))\n self.posBoard[row][col] = pos\n\n pos += 1\n count += 1\n else:\n self.posBoard[row][col] = pos\n pos += 1\n elif row == 1:\n if reso == 1:\n self.board[row][col] = count\n\n pawns.insert(count,pawn(0, pos, self.board, count, self.posBoard))\n self.posBoard[row][col] = pos\n pos += 1\n count += 1\n else:\n self.posBoard[row][col] = pos\n pos += 1\n elif (row == 3) | (row == 4):\n self.posBoard[row][col] = pos\n pos += 1\n col = pos % 8\n row = pos // 8\n elif row > 4 & row < 8:\n col = pos % 8\n row = pos // 8\n reso = col % 2\n if (row == 5) | (row == 7):\n if (col == 8 - 1) & (row == 5):\n self.board[row][col] = count\n pawns.insert(count, pawn(1, pos, self.board,count, self.posBoard))\n self.posBoard[row][col] = pos\n pos += 1\n count += 1\n elif (col == 8 - 1) & (row == 7):\n self.board[row][col] = count\n pawns.insert(count, pawn(1, pos, self.board,count, self.posBoard))\n self.posBoard[row][col] = pos\n pos += 1\n count += 1\n finish = True\n elif reso == 1:\n self.board[row][col] = count\n\n pawns.insert(count,pawn(1, pos, self.board,count, self.posBoard))\n self.posBoard[row][col] = pos\n pos += 1\n count += 1\n else:\n self.posBoard[row][col] = pos\n pos += 1\n elif (row == 6):\n if col == 8 - 1:\n self.posBoard[row][col] = pos\n pos += 1\n elif reso == 0:\n self.board[row][col] = count\n\n pawns.insert(count, pawn(1, pos, self.board,count, self.posBoard))\n self.posBoard[row][col] = pos\n pos += 1\n count += 1\n else:\n self.posBoard[row][col] = pos\n pos += 1\n\n\n\n def returnPawns(self):\n return self.pawns\n\n #TODO: king funct good but then can't move\n def HumanView(self):\n pos = 0\n humanView = copy.deepcopy(self.board)\n for i in range(64):\n col = pos % 8\n row = pos // 8\n pawnNum =self.board[row][col]\n if self.pawns[pawnNum-1].checkForKing():\n humanView[row][col] = 99\n pos+=1\n elif (humanView[row][col] < 13) & (humanView[row][col] != 0) :\n\n humanView[row][col]=69\n pos+=1\n else:\n pos+=1\n print(humanView)\n print(\" \")\n # print(self.posBoard)\n\n\n\n\n def updateBoard(self,board):\n self.board = board\n\n\n\n def jump(self,piece, direction, amount):\n piece = self.pawns[piece-1]\n piece.jump(direction,amount)\n #self.piece.checkForKing()\n\n def printPawns(self):\n for i in range(self.pawns.__len__()):\n print(i)\n\n def mov(self,number,dir):\n piece = self.pawns[number-1]\n piece.mov(dir)\n #piece.checkForKing()\n self.HumanView()\n\n\n def checkKing(self,pawn):\n if self.pawns[pawn-1].checkForKing():\n return True\n else:\n return False\n\n\n def AiMove(self):\n found = False\n while found ==False:\n rpawn = random.randint(1,12)\n destination = random.randint(0,1)\n pos = self.pawns[rpawn-1].getPos()\n col = pos % 8\n row = pos // 8\n if destination ==0:\n if ((row+1) > 7) | ((col - 1) < 0):\n pass\n elif self.pawns[rpawn-1].checkEmpty(row+1,col-1):\n self.board[row][col] = 0\n self.board[row+1][col-1] = rpawn\n self.pawns[rpawn-1].update(row+1,col-1)\n found = True\n self.HumanView()\n #check if human is there so it can eat\n elif self.pawns[rpawn-1].checkHuman(row+1,col-1):\n if ((row+2) > 7) | ((col - 2) < 0):\n pass\n #check if space is empty\n elif self.pawns[rpawn-1].checkEmpty(row+2,col-2):\n self.pawns[rpawn - 1].update(row+2,col-2)\n self.board[row][col] = 0\n self.board[row + 1][col - 1] = 0\n self.board[row + 2][col - 2] = rpawn\n else:\n pass\n else:\n pass\n elif destination ==1:\n if ((row+1) > 7) | ((col + 1) > 7):\n pass\n elif self.pawns[rpawn-1].checkEmpty(row+1,col+1):\n self.board[row][col] = 0\n self.board[row + 1][col + 1] = rpawn\n self.pawns[rpawn-1].update(row + 1, col + 1)\n found = True\n self.HumanView()\n elif self.pawns[rpawn-1].checkHuman(row+1,col+1):\n if ((row+2) > 7) | ((col + 2) > 7):\n pass\n elif self.pawns[rpawn - 1].checkEmpty(row + 2, col + 2):\n self.pawns[rpawn - 1].update(row + 2, col + 2)\n self.board[row][col] = 0\n self.board[row + 1][col + 1] = 0\n self.board[row + 2][col + 2] = rpawn\n else:\n pass\n else:\n pass\n #self.pawns[rpawn-1].checkForKing()\n\n\n def boardState(self, human):\n count = self.countPawns()\n # if human = 1:\n # count[0]\n pieceCount = 0\n kingCount = 0\n positionCount = 0\n return pieceCount + kingCount+ positionCount\n\n def countPawns(self):\n pos = 0\n col = pos % 8\n row = pos // 8\n aiCount = 0\n humanCount = 0\n for i in range(64):\n col = pos % 8\n row = pos // 8\n if (self.board[row][col] < 13) & (self.board[row][col] > 0):\n aiCount+=1\n pos+=1\n elif self.board[row][col] > 12:\n humanCount+=1\n pos += 1\n else:\n pos+=1\n return humanCount,aiCount\n\n def printScores(self):\n score = self.countPawns()\n print(\"Player1 count:\" + str(score[0]) + \" \"+ \"Player2 count: \" + str(score[1]))\n\n def gameOver(self):\n gameover = False\n score = self.countPawns()\n if (score[0] ==0) | (score[1] ==0):\n return True\n else:\n return True\n\n"
]
| [
[
"numpy.zeros"
]
]
|
devran1/gradslam | [
"1e3d8610101a07551a1dc5a4d40170becc8be2d3"
]
| [
"gradslam/datasets/tumutils.py"
]
| [
"#!/usr/bin/python\n# Software License Agreement (BSD License)\n#\n# Copyright (c) 2013, Juergen Sturm, TUM\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n#\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following\n# disclaimer in the documentation and/or other materials provided\n# with the distribution.\n# * Neither the name of TUM nor the names of its\n# contributors may be used to endorse or promote products derived\n# from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"\nSlightly modified version of the \"associate.py\" and \"evaluate_rpe.py\" helper provided by TUM at: \nhttps://svncvpr.in.tum.de/cvpr-ros-pkg/trunk/rgbd_benchmark/rgbd_benchmark_tools/src/rgbd_benchmark_tools/associate.py\nhttps://svncvpr.in.tum.de/cvpr-ros-pkg/trunk/rgbd_benchmark/rgbd_benchmark_tools/src/rgbd_benchmark_tools/evaluate_rpe.py\n\nThe Kinect provides the color and depth images in an un-synchronized way. This means that the set of time stamps from\nthe color images do not intersect with those of the depth images. Therefore, we need some way of associating color\nimages to depth images.\n\nThis script contains helpers for reading the time stamps from e.g. the \"rgb.txt\" file and the \"depth.txt\" file, \nand joining them by finding the best matches.\n\"\"\"\nfrom typing import Optional\n\nimport numpy as np\nimport warnings\n\n__all__ = [\"read_trajectory\", \"read_file_list\", \"associate\"]\n\n\n_EPS = np.finfo(float).eps * 4.0\n\n\ndef transform44(l: tuple):\n r\"\"\"Generate a 4x4 homogeneous transformation matrix from a 3D point and unit quaternion.\n\n Args:\n l (tuple): tuple consisting of (stamp,tx,ty,tz,qx,qy,qz,qw) where (tx,ty,tz) is the\n 3D position and (qx,qy,qz,qw) is the unit quaternion.\n\n Returns:\n np.ndarray: 4x4 homogeneous transformation matrix\n\n Shape:\n - Output: `(4, 4)`\n \"\"\"\n t = l[1:4]\n q = np.array(l[4:8], dtype=np.float64, copy=True)\n nq = np.dot(q, q)\n if nq < _EPS:\n return np.array(\n (\n (1.0, 0.0, 0.0, t[0]),(0.0, 1.0, 0.0, t[1]),(0.0, 0.0, 1.0, t[2]),(\n 0.0, 0.0, 0.0, 1.0\n )\n ),\n dtype=np.float64,\n )\n q *= np.sqrt(2.0 / nq)\n q = np.outer(q, q)\n return np.array(\n (\n (1.0 - q[1, 1] - q[2, 2], q[0, 1] - q[2, 3], q[0, 2] + q[1, 3], t[0]),\n (q[0, 1] + q[2, 3], 1.0 - q[0, 0] - q[2, 2], q[1, 2] - q[0, 3], t[1]),\n (q[0, 2] - q[1, 3], q[1, 2] + q[0, 3], 1.0 - q[0, 0] - q[1, 1], t[2]),\n (0.0, 0.0, 0.0, 1.0),\n ),\n dtype=np.float64,\n )\n\n\ndef read_trajectory(filename: str, matrix: bool = True):\n r\"\"\"Read a trajectory from a text file.\n\n Args:\n filename: Path of file to be read\n matrix (np.ndarray or tuple): If True, will convert poses to 4x4 homogeneous transformation\n matrices (of type np.ndarray). Else, will return poses as tuples consisting of\n (stamp,tx,ty,tz,qx,qy,qz,qw), where (tx,ty,tz) is the 3D position and (qx,qy,qz,qw)\n is the unit quaternion.\n\n Returns:\n dict: dictionary of {stamp: pose} where stamp is of type str and pose is a 4x4 np.ndarray if matrix is True,\n or a tuple of position and unit quaternion (tx,ty,tz,qx,qy,qz,qw) if matrix is False.\n\n \"\"\"\n file = open(filename)\n data = file.read()\n lines = data.replace(\",\", \" \").replace(\"\\t\", \" \").split(\"\\n\")\n list = []\n for line in lines:\n line_list = []\n if len(line) > 0 and line[0] != \"#\":\n for n, v in enumerate(line.split(\" \")):\n v = v.strip()\n if v != \"\":\n v = float(v) if n > 0 else v\n line_list.append(v)\n list.append(line_list)\n list_ok = []\n for i, l in enumerate(list):\n if l[4:8] == [0, 0, 0, 0]:\n continue\n isnan = False\n for v in l[1:]:\n if np.isnan(v):\n isnan = True\n break\n if isnan:\n sys.stderr.write(\n \"Warning: line %d of file '%s' has NaNs, skipping line\\n\"\n % (i, filename)\n )\n continue\n list_ok.append(l)\n if matrix:\n traj = dict([(l[0], transform44(l[0:])) for l in list_ok])\n else:\n traj = dict([(l[0], l[1:8]) for l in list_ok])\n return traj\n\n\ndef read_file_list(\n filename: str, start: Optional[int] = None, end: Optional[int] = None\n):\n r\"\"\"Reads a sequence from a text file and returns a {stamp: [d1, d2, d3, ...]} dictionary. The file should\n be a .txt file where each line contains \"stamp d1 d2 d3 ...\", where \"stamp\" and \"d1 d2 d3 ...\" denote\n the time stamp and data respectively.\n\n Args:\n filename (str): Path to text file, where text file has the format: \"stamp d1 d2 d3 ...\"\n start (int or None): Index of frame to start stamp/data extraction from.\n If None, will start from the first frame. Default: None\n end (int or None): Index of frame to end stamp/data extraction at.\n If None, will end at the final frame. Default: None\n\n Returns:\n dict: dictionary of {stamp: [d1, d2, d3]} keys and values, where stamp is of type str\n\n \"\"\"\n file = open(filename)\n data = file.read()\n lines = data.replace(\",\", \" \").replace(\"\\t\", \" \").split(\"\\n\")\n list = [\n [v.strip() for v in line.split(\" \") if v.strip() != \"\"]\n for num, line in enumerate(lines)\n if len(line) > 0 and line[0] != \"#\"\n ]\n start = start if start is not None else 0\n end = end if end is not None else len(lines)\n if end > len(lines):\n msg = '\"end\" was larger than number of frames in \"{0}\": {1} > {2}'\n warnings.warn(msg.format(filename, end, len(lines)))\n list = list[start:end]\n list = [(l[0], l[1:]) for l in list if len(l) > 1]\n return dict(list)\n\n\ndef associate(\n first_dict: dict, second_dict: dict, offset: float, max_difference: float\n):\n r\"\"\"Associate two dictionaries of {stamp1: data1} and {stamp2: data2} by returning\n (stamp1, stamp2). As the time stamps never match exactly, we aim to find the\n closest stamp match between input dictionaries.\n\n Args:\n first_dict (dict): First dictionary of {stamp1: data1} where stamp1 is of type str\n second_dict (dict): Second dictionary of {stamp2: data2} where stamp2 is of type str\n offset (float): Time offset between both dictionaries (e.g., to model the delay between the sensors)\n max_difference (float): Search radius for candidate generation\n\n Returns:\n matches (list of tuple of str): List of matched tuples (stamp1, stamp2)\n\n \"\"\"\n first_keys = list(first_dict.keys())\n second_keys = list(second_dict.keys())\n potential_matches = [\n (abs(float(a) - (float(b) + offset)), a, b)\n for a in first_keys\n for b in second_keys\n if abs(float(a) - (float(b) + offset)) < max_difference\n ]\n potential_matches.sort()\n matches = []\n for diff, a, b in potential_matches:\n if a in first_keys and b in second_keys:\n first_keys.remove(a)\n second_keys.remove(b)\n matches.append((a, b))\n\n matches.sort()\n return matches\n"
]
| [
[
"numpy.dot",
"numpy.sqrt",
"numpy.isnan",
"numpy.finfo",
"numpy.outer",
"numpy.array"
]
]
|
tjjlemaire/MorphoSONIC | [
"e1e302afe2e00642480dae8a5e869f0a16baa599"
]
| [
"tests/test_mpi.py"
]
| [
"# -*- coding: utf-8 -*-\n# @Author: Theo Lemaire\n# @Email: [email protected]\n# @Date: 2021-06-16 11:36:32\n# @Last Modified by: Theo Lemaire\n# @Last Modified time: 2021-07-27 17:46:58\n\nimport logging\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom argparse import ArgumentParser\n\nfrom PySONIC.core import Batch, getPulseTrainProtocol\nfrom PySONIC.utils import logger\nfrom MorphoSONIC.models import SennFiber\nfrom MorphoSONIC.sources import GaussianAcousticSource\nfrom MorphoSONIC.plt import SectionCompTimeSeries\n\n''' Small script showcasing multiprocessing possibilities for Python+NEURON simulations. '''\n\nlogger.setLevel(logging.INFO)\n\n# Fiber model\na = 32e-9 # m\nfs = 1.\nfiberD = 20e-6 # m\nnnodes = 21\nfiber = SennFiber(fiberD, nnodes=nnodes, a=a, fs=fs)\n\n# Acoustic source\nFdrive = 500e3 # Hz\namps = np.linspace(50e3, 400e3, 8) # Pa\nsource = GaussianAcousticSource(0, fiber.length / 10., Fdrive)\n\n# Pulsing protocol\ntpulse = 100e-6 # s\nPRF = 10 # Hz\nnpulses = 10\npp = getPulseTrainProtocol(tpulse, PRF, npulses)\n\nif __name__ == '__main__':\n # Parse command line arguments\n parser = ArgumentParser()\n parser.add_argument(\n '--mpi', default=False, action='store_true', help='Use multiprocessing')\n args = parser.parse_args()\n mpi = args.mpi\n\n # Initialize and run simulation batch\n batch = Batch(lambda x: fiber.simulate(source.updatedX(x), pp), [[x] for x in amps])\n output = batch.run(loglevel=logger.getEffectiveLevel(), mpi=mpi)\n\n # Plot results\n for data, meta in output:\n SectionCompTimeSeries([(data, meta)], 'Vm', fiber.nodeIDs).render()\n\n plt.show()\n"
]
| [
[
"matplotlib.pyplot.show",
"numpy.linspace"
]
]
|
Nikeshbajaj/MachineLearningFromScratch | [
"f025d3547bb7a605d62ed238536e6ae526ad55da"
]
| [
"DeepLearning from scratch/example2.py"
]
| [
"'''\nExample 2: Deep Neural Network from scrach\n\n@Author _ Nikesh Bajaj\nPhD Student at Queen Mary University of London &\nUniversity of Genova\nConact _ http://nikeshbajaj.in \nn[dot][email protected]\nbajaj[dot][email protected]\n'''\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom DeepNet import deepNet\nimport DataSet as ds\n\nplt.close('all')\n\ndtype = ['MOONS','GAUSSIANS','LINEAR','SINUSOIDAL','SPIRAL']\n\nX, y,_ = ds.create_dataset(200, dtype[3],0.0,varargin = 'PRESET');\n\nXts, yts,_ = ds.create_dataset(200, dtype[3],0.4,varargin = 'PRESET');\n\nprint(X.shape, y.shape)\n\n\nNN = deepNet(X,y,Xts=Xts, yts=yts, Net = [8,8,5],NetAf =['tanh'], alpha=0.01,miniBatchSize = 0.3, printCostAt =100,AdamOpt=True,lambd=0,keepProb =[1.0])\n\nplt.ion()\nfor i in range(15):\n\tNN.fit(itr=10)\n\tNN.PlotLCurve()\n\tNN.PlotBoundries(Layers=True)\n\n\nNN.PlotLCurve()\nNN.PlotBoundries(Layers=True)\nprint(NN)\nyi,yp = NN.predict(X)\nyti,ytp = NN.predict(Xts)\nprint('Accuracy::: Training :',100*np.sum(yi==y)/yi.shape[1], ' Testing :',100*np.sum(yti==yts)/yti.shape[1])"
]
| [
[
"matplotlib.pyplot.ion",
"numpy.sum",
"matplotlib.pyplot.close"
]
]
|
jim22k/dask-grblas | [
"f0090b61b220db06fa6b54b3448297c0e9ce8ca9"
]
| [
"dask_grblas/utils.py"
]
| [
"import numpy as np\n\n\ndef np_dtype(dtype):\n return np.dtype(dtype.numba_type.name)\n\n\ndef get_meta(val):\n return getattr(val, \"_meta\", val)\n\n\ndef get_grblas_type(val):\n return _grblas_types[type(val)]\n\n\ndef get_inner_type(val):\n return _inner_types[type(val)]\n\n\ndef get_return_type(val):\n return _return_types[type(val)]\n\n\ndef wrap_inner(val):\n return _inner_types[type(val)](val)\n\n\n# These will be finished constructed in __init__\n_grblas_types = {}\n_inner_types = {}\n_return_types = {}\n"
]
| [
[
"numpy.dtype"
]
]
|
stephaniemweber/pyblp | [
"3f8e0abb4f9473dd8d80468afed7b49c729dd6a2"
]
| [
"pyblp/moments.py"
]
| [
"\"\"\"Micro moments.\"\"\"\n\nimport abc\nimport collections\nimport functools\nfrom typing import Any, Callable, Dict, Hashable, List, Optional, Sequence, TYPE_CHECKING\n\nimport numpy as np\n\nfrom . import options\nfrom .utilities.basics import Array, StringRepresentation, format_number, format_table, output\n\n\n# only import objects that create import cycles when checking types\nif TYPE_CHECKING:\n from .economies.economy import Economy # noqa\n from .markets.market import Market # noqa\n\n\nclass Moment(StringRepresentation):\n \"\"\"Information about a single micro moment.\"\"\"\n\n value: float\n observations: int\n market_ids: Optional[Array]\n market_weights: Optional[Array]\n requires_inside: bool\n requires_eliminated: Sequence[Any]\n requires_inside_eliminated: bool\n\n def __init__(\n self, value: float, observations: int, market_ids: Optional[Sequence] = None,\n market_weights: Optional[Array] = None, requires_inside: bool = False,\n requires_eliminated: Sequence[Any] = (), requires_inside_eliminated: bool = False) -> None:\n \"\"\"Validate information about the moment to the greatest extent possible without an economy instance.\"\"\"\n self.value = value\n self.observations = observations\n if not isinstance(self.value, (int, float)):\n raise TypeError(\"value must be a float.\")\n if not isinstance(self.observations, int) or observations < 1:\n raise ValueError(\"observations must be a positive int.\")\n\n # validate market IDs\n if market_ids is None:\n self.market_ids = None\n else:\n self.market_ids = np.asarray(market_ids, np.object)\n\n # check for duplicates\n unique, counts = np.unique(self.market_ids, return_counts=True)\n duplicates = unique[counts > 1]\n if duplicates.size > 0:\n raise ValueError(f\"The following market IDs are duplicated in market_ids: {duplicates}.\")\n\n # validate market weights\n if market_weights is None:\n self.market_weights = None\n elif self.market_ids is None:\n raise ValueError(\"market_ids must be specified when using market_weights.\")\n else:\n self.market_weights = np.asarray(market_weights, options.dtype)\n\n # validate the shape\n if self.market_ids is not None and self.market_weights.shape != self.market_ids.shape:\n raise ValueError(\"market_weights must be the same shape as market_ids.\")\n\n # validate that they sum to 1\n if np.abs(1 - self.market_weights.sum()) > options.weights_tol:\n output(\"\")\n output(\"Warning: Market weights sum to a value that differs from 1 by more than options.weights_tol.\")\n output(\"\")\n\n # validate requirements\n assert not requires_inside_eliminated or requires_inside\n self.requires_inside = requires_inside\n self.requires_eliminated = requires_eliminated\n self.requires_inside_eliminated = requires_inside_eliminated\n\n def __str__(self) -> str:\n \"\"\"Format information about the micro moment as a string.\"\"\"\n return f\"{self._format_moment()} = {format_number(self.value)} in {self._format_markets(text=True)}\"\n\n def _format_markets(self, text: bool = False) -> str:\n \"\"\"Format information about the markets associated with the micro moment as a string.\"\"\"\n if self.market_ids is None:\n return \"All Markets\" if text else \"All\"\n\n joined = \", \".join(str(t) for t in self.market_ids)\n suffix = \"Market\" if len(self.market_ids) == 1 else \"Markets\"\n return f\"{suffix} {joined}\" if text else joined\n\n @abc.abstractmethod\n def _format_moment(self) -> str:\n \"\"\"Construct a string expression for the micro moment.\"\"\"\n\n def _validate(self, economy: 'Economy') -> None:\n \"\"\"Check that all market IDs associated with this moment are in the economy.\"\"\"\n if self.market_ids is not None:\n extra_ids = set(self.market_ids) - set(economy.unique_market_ids)\n if extra_ids:\n raise ValueError(f\"market_ids contains the following extra IDs: {sorted(extra_ids)}.\")\n\n @abc.abstractmethod\n def _compute_agent_values(\n self, market: 'Market', delta: Array, probabilities: Array, conditionals: Optional[Array],\n inside_probabilities: Optional[Array], eliminated_probabilities: Dict[int, Array],\n inside_eliminated_sum: Optional[Array]) -> Array:\n \"\"\"Compute agent-specific micro moment values, which will be aggregated up into means or covariances.\"\"\"\n\n @abc.abstractmethod\n def _compute_agent_values_tangent(\n self, market: 'Market', p: int, delta: Array, probabilities: Array, probabilities_tangent: Array,\n inside_probabilities: Optional[Array], inside_tangent: Optional[Array],\n eliminated_tangents: Dict[int, Array], inside_eliminated_sum: Optional[Array],\n inside_eliminated_sum_tangent: Optional[Array]) -> Array:\n \"\"\"Compute the tangent of agent-specific micro moments with respect to a parameter.\"\"\"\n\n\nclass DemographicExpectationMoment(Moment):\n r\"\"\"Configuration for micro moments that match expectations of demographics for agents who choose certain products.\n\n For example, micro data can sometimes be used to compute the mean :math:`\\mathscr{V}_m` of a demographic such as\n income, :math:`y_{it}`, for agents who choose products in some set :math:`J`. Its simulated analogue :math:`v_{mt}`\n can be defined by\n\n .. math:: v_{mt} = \\frac{E[y_{it} \\sum_{j \\in J} s_{ijt}]}{\\sum_{j \\in J} s_{jt}}.\n\n These are averaged across a set of markets :math:`T_m` and compared with :math:`\\mathscr{V}_m`, which gives\n :math:`\\bar{g}_{M,m}` in :eq:`averaged_micro_moments`.\n\n Parameters\n ----------\n product_ids : `sequence of object`\n IDs of the products :math:`j \\in J`, which may include ``None`` to denote the outside option :math:`j = 0`. If\n there is no ``None`, at least one of these IDs should show up in the ``product_ids`` field of ``product_data``\n in :class:`Problem` or :class:`Simulation` for each market over which this micro moment will be averaged.\n demographics_index : `int`\n Column index of the demographic :math:`y_{it}` (which can be any demographic, not just income) in the matrix of\n agent demographics, :math:`d`. This should be between zero and :math:`D - 1`, inclusive.\n value : `float`\n Value :math:`\\mathscr{V}_m` of the statistic estimated from micro data.\n observations : `int`\n Number of micro data observations :math:`N_m` used to estimate :math:`\\mathscr{V}_m`, which is used to properly\n scale micro moment covariances in :eq:`scaled_micro_moment_covariances`.\n market_ids : `array-like, optional`\n Distinct market IDs over which the micro moments will be averaged to get :math:`\\bar{g}_{M,m}`. These are also\n the only markets in which the moments will be computed. By default, the moments are computed for and averaged\n across all markets.\n market_weights : `array-like, optional`\n Weights for averaging micro moments over specified ``market_ids``. By default, these are :math:`1 / T_m`.\n\n Examples\n --------\n - :doc:`Tutorial </tutorial>`\n\n \"\"\"\n\n product_ids: Sequence[Any]\n demographics_index: int\n\n def __init__(\n self, product_ids: Optional[Any], demographics_index: int, value: float, observations: int,\n market_ids: Optional[Sequence] = None, market_weights: Optional[Array] = None) -> None:\n \"\"\"Validate information about the moment to the greatest extent possible without an economy instance.\"\"\"\n if not isinstance(product_ids, collections.abc.Sequence) or len(product_ids) == 0:\n raise ValueError(\"product_ids must be a sequence with at least one ID.\")\n if len(set(product_ids)) != len(product_ids):\n raise ValueError(\"product_ids should not have duplicates.\")\n if not isinstance(demographics_index, int) or demographics_index < 0:\n raise ValueError(\"demographics_index must be a positive int.\")\n super().__init__(value, observations, market_ids, market_weights)\n self.product_ids = product_ids\n self.demographics_index = demographics_index\n\n def _format_moment(self) -> str:\n \"\"\"Construct a string expression for the moment.\"\"\"\n products = \", \".join(\"Outside\" if i is None else f\"'{i}'\" for i in self.product_ids)\n return f\"E[Demographic Column {self.demographics_index} | {products}]\"\n\n def _validate(self, economy: 'Economy') -> None:\n \"\"\"Check that matrix indices are valid in the economy.\"\"\"\n super()._validate(economy)\n economy._validate_product_ids(self.product_ids, self.market_ids)\n if self.demographics_index >= economy.D:\n raise ValueError(f\"demographics_index must be between 0 and D = {economy.D}, inclusive.\")\n\n def _compute_agent_values(\n self, market: 'Market', delta: Array, probabilities: Array, conditionals: Optional[Array],\n inside_probabilities: Optional[Array], eliminated_probabilities: Dict[int, Array],\n inside_eliminated_sum: Optional[Array]) -> Array:\n \"\"\"Compute agent-specific micro moment values, which will be aggregated up into means or covariances.\"\"\"\n shares_sum = 0\n probabilities_sum = np.zeros((market.I, 1), options.dtype)\n for product_id in self.product_ids:\n if product_id is None:\n shares_sum += 1 - market.products.shares.sum()\n probabilities_sum += 1 - probabilities.sum(axis=0, keepdims=True).T\n elif product_id in market.products.product_ids:\n j = market.get_product(product_id)\n shares_sum += market.products.shares[j]\n probabilities_sum += probabilities[[j]].T\n\n d = market.agents.demographics[:, [self.demographics_index]]\n return d * probabilities_sum / shares_sum\n\n def _compute_agent_values_tangent(\n self, market: 'Market', p: int, delta: Array, probabilities: Array, probabilities_tangent: Array,\n inside_probabilities: Optional[Array], inside_tangent: Optional[Array],\n eliminated_tangents: Dict[int, Array], inside_eliminated_sum: Optional[Array],\n inside_eliminated_sum_tangent: Optional[Array]) -> Array:\n \"\"\"Compute the tangent of agent-specific micro moments with respect to a parameter.\"\"\"\n shares_sum = 0\n probabilities_tangent_sum = np.zeros((market.I, 1), options.dtype)\n for product_id in self.product_ids:\n if product_id is None:\n shares_sum += 1 - market.products.shares.sum()\n probabilities_tangent_sum += -probabilities_tangent.sum(axis=0, keepdims=True).T\n elif product_id in market.products.product_ids:\n j = market.get_product(product_id)\n shares_sum += market.products.shares[j]\n probabilities_tangent_sum += probabilities_tangent[[j]].T\n\n d = market.agents.demographics[:, [self.demographics_index]]\n return d * probabilities_tangent_sum / shares_sum\n\n\nclass CharacteristicExpectationMoment(Moment):\n r\"\"\"Configuration for micro moments that match expectations of characteristics of products chosen by certain agents.\n\n For example, micro data can sometimes be used to compute the mean :math:`\\mathscr{V}_m` of a product characteristic\n :math:`x_{jt}` of an agent's choice :math:`j` for agents in some set :math:`I`. Its simulated analogue\n :math:`v_{mt}` can be defined by\n\n .. math:: v_{mt} = E[z_{it} | i \\in I]\n\n where conditional on choosing an inside good, the expected value of :math:`x_{jt}` for agent :math:`i` is\n\n .. math:: z_{it} = \\sum_{j \\in J_t} x_{jt}s_{ij(-0)t}\n\n where :math:`s_{ij(-0)t} = s_{ijt} / (1 - s_{i0t})` is the probability of :math:`i` choosing :math:`j` when the\n outside option is removed from the choice set.\n\n These are averaged across a set of markets :math:`T_m` and compared with :math:`\\mathscr{V}_m`, which gives\n :math:`\\bar{g}_{M,m}` in :eq:`averaged_micro_moments`.\n\n Parameters\n ----------\n agent_ids : `sequence of object`\n IDs of the agents :math:`i \\in I`. At least one of these IDs should show up in the ``agent_ids`` field of\n ``agent_data`` in :class:`Problem` or :class:`Simulation` for each market over which this micro moment will be\n averaged.\n X2_index : `int`\n Column index of :math:`x_{jt}` in the matrix of demand-side nonlinear product characteristics, :math:`X_2`. This\n should be between zero and :math:`K_2 - 1`, inclusive.\n value : `float`\n Value :math:`\\mathscr{V}_m` of the statistic estimated from micro data.\n observations : `int`\n Number of micro data observations :math:`N_m` used to estimate :math:`\\mathscr{V}_m`, which is used to properly\n scale micro moment covariances in :eq:`scaled_micro_moment_covariances`.\n market_ids : `array-like, optional`\n Distinct market IDs over which the micro moments will be averaged to get :math:`\\bar{g}_{M,m}`. These are also\n the only markets in which the moments will be computed. By default, the moments are computed for and averaged\n across all markets.\n market_weights : `array-like, optional`\n Weights for averaging micro moments over specified ``market_ids``. By default, these are :math:`1 / T_m`.\n\n Examples\n --------\n - :doc:`Tutorial </tutorial>`\n\n \"\"\"\n\n agent_ids: Sequence[Any]\n X2_index: int\n\n def __init__(\n self, agent_ids: Optional[Any], X2_index: int, value: float, observations: int,\n market_ids: Optional[Sequence] = None, market_weights: Optional[Array] = None) -> None:\n \"\"\"Validate information about the moment to the greatest extent possible without an economy instance.\"\"\"\n if not isinstance(agent_ids, collections.abc.Sequence) or len(agent_ids) == 0:\n raise ValueError(\"agent_ids must be a sequence with at least one ID.\")\n if len(set(agent_ids)) != len(agent_ids):\n raise ValueError(\"agent_ids should not have duplicates.\")\n if not isinstance(X2_index, int) or X2_index < 0:\n raise ValueError(\"X2_index must be a positive int.\")\n super().__init__(value, observations, market_ids, market_weights, requires_inside=True)\n self.agent_ids = agent_ids\n self.X2_index = X2_index\n\n def _format_moment(self) -> str:\n \"\"\"Construct a string expression for the moment.\"\"\"\n agents = \", \".join(f\"'{i}'\" for i in self.agent_ids)\n return f\"E[X2 Column {self.X2_index} | {agents}]\"\n\n def _validate(self, economy: 'Economy') -> None:\n \"\"\"Check that matrix indices are valid in the economy.\"\"\"\n super()._validate(economy)\n economy._validate_agent_ids(self.agent_ids, self.market_ids)\n if self.X2_index >= economy.K2:\n raise ValueError(f\"X2_index must be between 0 and K2 = {economy.K2}, inclusive.\")\n\n def _compute_agent_values(\n self, market: 'Market', delta: Array, probabilities: Array, conditionals: Optional[Array],\n inside_probabilities: Optional[Array], eliminated_probabilities: Dict[int, Array],\n inside_eliminated_sum: Optional[Array]) -> Array:\n \"\"\"Compute agent-specific micro moment values, which will be aggregated up into means or covariances.\"\"\"\n assert inside_probabilities is not None\n I = market.get_agents_index(self.agent_ids)\n x = market.products.X2[:, [self.X2_index]]\n return np.where(I[None], inside_probabilities, 0).T @ x / market.agents.weights[I].sum()\n\n def _compute_agent_values_tangent(\n self, market: 'Market', p: int, delta: Array, probabilities: Array, probabilities_tangent: Array,\n inside_probabilities: Optional[Array], inside_tangent: Optional[Array],\n eliminated_tangents: Dict[int, Array], inside_eliminated_sum: Optional[Array],\n inside_eliminated_sum_tangent: Optional[Array]) -> Array:\n \"\"\"Compute the tangent of agent-specific micro moments with respect to a parameter.\"\"\"\n assert inside_tangent is not None\n I = market.get_agents_index(self.agent_ids)\n x = market.products.X2[:, [self.X2_index]]\n return np.where(I[None], inside_tangent, 0).T @ x / market.agents.weights[I].sum()\n\n\nclass DemographicCovarianceMoment(Moment):\n r\"\"\"Configuration for micro moments that match covariances between product characteristics and demographics.\n\n For example, micro data can sometimes be used to compute the sample covariance :math:`\\mathscr{V}_m` between a\n product characteristic :math:`x_{jt}` of an agent's choice :math:`j`, and a demographic such as income,\n :math:`y_{it}`, amongst those agents who purchase an inside good. Its simulated analogue :math:`v_{mt}` can be\n defined by\n\n .. math:: v_{mt} = \\text{Cov}(y_{it}, z_{it})\n\n where conditional on choosing an inside good, the expected value of :math:`x_{jt}` for agent :math:`i` is\n\n .. math:: z_{it} = \\sum_{j \\in J_t} x_{jt}s_{ij(-0)t}\n\n where :math:`s_{ij(-0)t} = s_{ijt} / (1 - s_{i0t})` is the probability of :math:`i` choosing :math:`j` when the\n outside option is removed from the choice set.\n\n These are averaged across a set of markets :math:`T_m` and compared with :math:`\\mathscr{V}_m`, which gives\n :math:`\\bar{g}_{M,m}` in :eq:`averaged_micro_moments`.\n\n Parameters\n ----------\n X2_index : `int`\n Column index of :math:`x_{jt}` in the matrix of demand-side nonlinear product characteristics, :math:`X_2`. This\n should be between zero and :math:`K_2 - 1`, inclusive.\n demographics_index : `int`\n Column index of the demographic :math:`y_{it}` (which can be any demographic, not just income) in the matrix of\n agent demographics, :math:`d`. This should be between zero and :math:`D - 1`, inclusive.\n value : `float`\n Value :math:`\\mathscr{V}_m` of the statistic estimated from micro data.\n observations : `int`\n Number of micro data observations :math:`N_m` used to estimate :math:`\\mathscr{V}_m`, which is used to properly\n scale micro moment covariances in :eq:`scaled_micro_moment_covariances`.\n market_ids : `array-like, optional`\n Distinct market IDs over which the micro moments will be averaged to get :math:`\\bar{g}_{M,m}`. These are also\n the only markets in which the moments will be computed. By default, the moments are computed for and averaged\n across all markets.\n market_weights : `array-like, optional`\n Weights for averaging micro moments over specified ``market_ids``. By default, these are :math:`1 / T_m`.\n\n Examples\n --------\n - :doc:`Tutorial </tutorial>`\n\n \"\"\"\n\n X2_index: int\n demographics_index: int\n\n def __init__(\n self, X2_index: int, demographics_index: int, value: float, observations: int,\n market_ids: Optional[Sequence] = None, market_weights: Optional[Array] = None) -> None:\n \"\"\"Validate information about the moment to the greatest extent possible without an economy instance.\"\"\"\n if not isinstance(X2_index, int) or X2_index < 0:\n raise ValueError(\"X2_index must be a positive int.\")\n if not isinstance(demographics_index, int) or demographics_index < 0:\n raise ValueError(\"demographics_index must be a positive int.\")\n super().__init__(value, observations, market_ids, market_weights, requires_inside=True)\n self.X2_index = X2_index\n self.demographics_index = demographics_index\n\n def _format_moment(self) -> str:\n \"\"\"Construct a string expression for the moment.\"\"\"\n return f\"Cov(X2 Column {self.X2_index}, Demographic Column {self.demographics_index})\"\n\n def _validate(self, economy: 'Economy') -> None:\n \"\"\"Check that matrix indices are valid in the economy.\"\"\"\n super()._validate(economy)\n if self.X2_index >= economy.K2:\n raise ValueError(f\"X2_index must be between 0 and K2 = {economy.K2}, inclusive.\")\n if self.demographics_index >= economy.D:\n raise ValueError(f\"demographics_index must be between 0 and D = {economy.D}, inclusive.\")\n\n def _compute_agent_values(\n self, market: 'Market', delta: Array, probabilities: Array, conditionals: Optional[Array],\n inside_probabilities: Optional[Array], eliminated_probabilities: Dict[int, Array],\n inside_eliminated_sum: Optional[Array]) -> Array:\n \"\"\"Compute agent-specific micro moment values, which will be aggregated up into means or covariances.\"\"\"\n assert inside_probabilities is not None\n x = market.products.X2[:, [self.X2_index]]\n d = market.agents.demographics[:, [self.demographics_index]]\n z = inside_probabilities.T @ x\n demeaned_z = z - market.agents.weights.T @ z\n demeaned_d = d - market.agents.weights.T @ d\n return demeaned_z * demeaned_d\n\n def _compute_agent_values_tangent(\n self, market: 'Market', p: int, delta: Array, probabilities: Array, probabilities_tangent: Array,\n inside_probabilities: Optional[Array], inside_tangent: Optional[Array],\n eliminated_tangents: Dict[int, Array], inside_eliminated_sum: Optional[Array],\n inside_eliminated_sum_tangent: Optional[Array]) -> Array:\n \"\"\"Compute the tangent of agent-specific micro moments with respect to a parameter.\"\"\"\n assert inside_tangent is not None\n x = market.products.X2[:, [self.X2_index]]\n d = market.agents.demographics[:, [self.demographics_index]]\n z_tangent = inside_tangent.T @ x\n demeaned_z_tangent = z_tangent - market.agents.weights.T @ z_tangent\n demeaned_d = d - market.agents.weights.T @ d\n return demeaned_z_tangent * demeaned_d\n\n\nclass DiversionProbabilityMoment(Moment):\n r\"\"\"Configuration for micro moments that match second choice probabilities of certain products for agents whose\n first choices are certain other products.\n\n For example, micro data can sometimes be used to compute the share :math:`\\mathscr{V}_m` of agents who would choose\n product :math:`k` if :math:`j` were removed from the choice set, out of those agents whose first choice is\n :math:`j`. Its simulated analogue :math:`v_{mt}` can be defined by\n\n .. math:: v_{mt} = \\frac{E[s_{ik(-j)t} s_{ijt}]}{s_{jt}}\n\n where :math:`s_{ik(-j)t} = s_{ijt} / (1 - s_{ijt})` is the probability of :math:`i` choosing :math:`k` when\n :math:`j` is removed from the choice set. Rearranging terms gives the equivalent definition\n\n .. math:: g_{M,mt} = \\mathscr{V}_m - \\frac{s_{k(-j)t} - s_{kt}}{s_{jt}},\n\n which is more reminiscent of the long-run diversion ratios :math:`\\bar{\\mathscr{D}}_{jk}` computed by\n :meth:`ProblemResults.compute_long_run_diversion_ratios`.\n\n These are averaged across a set of markets :math:`T_m` and compared with :math:`\\mathscr{V}_m`, which gives\n :math:`\\bar{g}_{M,m}` in :eq:`averaged_micro_moments`.\n\n Parameters\n ----------\n product_id1 : `object`\n ID of the first choice product :math:`j` or ``None`` to denote the outside option :math:`j = 0`. There must be\n exactly one of this ID in the ``product_ids`` field of ``product_data`` in :class:`Problem` or\n :class:`Simulation` for each market over which this micro moment will be averaged.\n product_id2 : `object`\n ID of the second choice product :math:`k` or ``None`` to denote the outside option :math:`j = 0`. If not\n ``None``, there must be exactly one of this ID for each market over which this micro moment will be averaged.\n value : `float`\n Value :math:`\\mathscr{V}_m` of the statistic estimated from micro data.\n observations : `int`\n Number of micro data observations :math:`N_m` used to estimate :math:`\\mathscr{V}_m`, which is used to properly\n scale micro moment covariances in :eq:`scaled_micro_moment_covariances`.\n market_ids : `array-like, optional`\n Distinct market IDs over which the micro moments will be averaged to get :math:`\\bar{g}_{M,m}`. These are also\n the only markets in which the moments will be computed. By default, the moments are computed for and averaged\n across all markets.\n market_weights : `array-like, optional`\n Weights for averaging micro moments over specified ``market_ids``. By default, these are :math:`1 / T_m`.\n\n Examples\n --------\n - :doc:`Tutorial </tutorial>`\n\n \"\"\"\n\n product_id1: Optional[Any]\n product_id2: Optional[Any]\n\n def __init__(\n self, product_id1: Any, product_id2: Optional[Any], value: float, observations: int,\n market_ids: Optional[Sequence] = None, market_weights: Optional[Array] = None) -> None:\n \"\"\"Validate information about the moment to the greatest extent possible without an economy instance.\"\"\"\n if product_id1 is None and product_id2 is None:\n raise ValueError(\"At least one of product_id1 or product_id2 must be not None.\")\n super().__init__(\n value, observations, market_ids, market_weights, requires_inside=product_id1 is None,\n requires_eliminated=[] if product_id1 is None else [product_id1]\n )\n self.product_id1 = product_id1\n self.product_id2 = product_id2\n\n def _format_moment(self) -> str:\n \"\"\"Construct a string expression for the moment.\"\"\"\n product1 = \"Outside\" if self.product_id1 is None else f\"'{self.product_id1}'\"\n product2 = \"Outside\" if self.product_id2 is None else f\"'{self.product_id2}'\"\n return f\"P({product1} First, {product2} Second)\"\n\n def _validate(self, economy: 'Economy') -> None:\n \"\"\"Check that matrix indices are valid in the economy.\"\"\"\n super()._validate(economy)\n economy._validate_product_ids([self.product_id1], self.market_ids)\n economy._validate_product_ids([self.product_id2], self.market_ids)\n\n def _compute_agent_values(\n self, market: 'Market', delta: Array, probabilities: Array, conditionals: Optional[Array],\n inside_probabilities: Optional[Array], eliminated_probabilities: Dict[int, Array],\n inside_eliminated_sum: Optional[Array]) -> Array:\n \"\"\"Compute agent-specific micro moment values, which will be aggregated up into means or covariances.\"\"\"\n\n # match the second choice probability of a certain inside good for agents who choose the outside good\n if self.product_id1 is None:\n assert inside_probabilities is not None\n k = market.get_product(self.product_id2)\n outside_share = 1 - market.products.shares.sum()\n numerator = inside_probabilities[[k]].T - market.products.shares[k]\n return numerator / outside_share\n\n # match the second choice probability of the outside good for agents who choose a certain inside good\n if self.product_id2 is None:\n j = market.get_product(self.product_id1)\n eliminated_outside_probabilities = 1 - eliminated_probabilities[j].sum(axis=0, keepdims=True)\n outside_share = 1 - market.products.shares.sum()\n numerator = eliminated_outside_probabilities.T - outside_share\n return numerator / market.products.shares[j]\n\n # match the second choice probability of a certain inside good for agents who choose a certain inside good\n j = market.get_product(self.product_id1)\n k = market.get_product(self.product_id2)\n numerator = eliminated_probabilities[j][[k]].T - market.products.shares[k]\n return numerator / market.products.shares[j]\n\n def _compute_agent_values_tangent(\n self, market: 'Market', p: int, delta: Array, probabilities: Array, probabilities_tangent: Array,\n inside_probabilities: Optional[Array], inside_tangent: Optional[Array],\n eliminated_tangents: Dict[int, Array], inside_eliminated_sum: Optional[Array],\n inside_eliminated_sum_tangent: Optional[Array]) -> Array:\n \"\"\"Compute the tangent of agent-specific micro moments with respect to a parameter.\"\"\"\n\n # handle the second choice probability of a certain inside good for agents who choose the outside good\n if self.product_id1 is None:\n assert inside_tangent is not None\n k = market.get_product(self.product_id2)\n outside_share = 1 - market.products.shares.sum()\n return inside_tangent[[k]].T / outside_share\n\n # handle the second choice probability of the outside good for agents who choose a certain inside good\n if self.product_id2 is None:\n j = market.get_product(self.product_id1)\n eliminated_outside_tangent = -eliminated_tangents[j].sum(axis=0, keepdims=True)\n return eliminated_outside_tangent.T / market.products.shares[j]\n\n # handle the second choice probability of a certain inside good for agents who choose a certain inside good\n j = market.get_product(self.product_id1)\n k = market.get_product(self.product_id2)\n return eliminated_tangents[j][[k]].T / market.products.shares[j]\n\n\nclass DiversionCovarianceMoment(Moment):\n r\"\"\"Configuration for micro moments that match covariances between product characteristics of first and second\n choices.\n\n For example, survey data can sometimes be used to compute the sample covariance :math:`\\mathscr{V}_m` between a\n product characteristic :math:`x_{jt}^{(1)}` of an agent's first choice :math:`j` and either the same or a different\n product characteristic :math:`x_{kt}^{(2)}` of the agent's second choice :math:`k` if :math:`j` were removed from\n the choice set, amongst those agents whose first and second choices are both inside goods. Its simulated analogue\n :math:`v_{mt}` can be defined by\n\n .. math:: v_{mt} = \\text{Cov}(z_{it}^{(1)}, z_{it}^{(2)})\n\n where conditional on purchasing inside goods, the expected values of :math:`x_{jt}^{(1)}` and\n :math:`x_{kt}^{(2)}` for agent :math:`i` are\n\n .. math::\n\n z_{it}^{(1)} = \\sum_{j \\in J_t} x_{jt}^{(1)} s_{ij(-0)t}, \\quad\n z_{it}^{(2)} = \\sum_{j, k \\in J_t} x_{kt}^{(2)} s_{ik(-0,j)t} s_{ij(-0)t}\n\n where :math:`s_{ij(-0)t}` is the probability of choosing :math:`j` when the outside option is removed from the\n choice set and :math:`s_{ik(-0,j)t}` is the probability of choosing :math:`k` when both the outside option and\n :math:`j` are removed from the choice set.\n\n These are averaged across a set of markets :math:`T_m` and compared with :math:`\\mathscr{V}_m`, which gives\n :math:`\\bar{g}_{M,m}` in :eq:`averaged_micro_moments`.\n\n Parameters\n ----------\n X2_index1 : `int`\n Column index of :math:`x_{jt}^{(1)}` in the matrix of demand-side nonlinear product characteristics,\n :math:`X_2`. This should be between zero and :math:`K_2 - 1`, inclusive.\n X2_index2 : `int`\n Column index of :math:`x_{kt}^{(2)}` in the matrix of demand-side nonlinear product characteristics,\n :math:`X_2`. This should be between zero and :math:`K_2 - 1`, inclusive.\n value : `float`\n Value :math:`\\mathscr{V}_m` of the statistic estimated from micro data.\n observations : `int`\n Number of micro data observations :math:`N_m` used to estimate :math:`\\mathscr{V}_m`, which is used to properly\n scale micro moment covariances in :eq:`scaled_micro_moment_covariances`.\n market_ids : `array-like, optional`\n Distinct market IDs over which the micro moments will be averaged to get :math:`\\bar{g}_{M,m}`. These are also\n the only markets in which the moments will be computed. By default, the moments are computed for and averaged\n across all markets.\n market_weights : `array-like, optional`\n Weights for averaging micro moments over specified ``market_ids``. By default, these are :math:`1 / T_m`.\n\n Examples\n --------\n - :doc:`Tutorial </tutorial>`\n\n \"\"\"\n\n X2_index1: int\n X2_index2: int\n\n def __init__(\n self, X2_index1: int, X2_index2: int, value: float, observations: int,\n market_ids: Optional[Sequence] = None, market_weights: Optional[Array] = None) -> None:\n \"\"\"Validate information about the moment to the greatest extent possible without an economy instance.\"\"\"\n if not isinstance(X2_index1, int) or X2_index1 < 0:\n raise ValueError(\"X2_index1 must be a positive int.\")\n if not isinstance(X2_index2, int) or X2_index2 < 0:\n raise ValueError(\"X2_index2 must be a positive int.\")\n super().__init__(\n value, observations, market_ids, market_weights, requires_inside=True, requires_inside_eliminated=True\n )\n self.X2_index1 = X2_index1\n self.X2_index2 = X2_index2\n\n def _format_moment(self) -> str:\n \"\"\"Construct a string expression for the moment.\"\"\"\n return f\"Cov(X2 Column {self.X2_index1} First, X2 Column {self.X2_index2} Second)\"\n\n def _validate(self, economy: 'Economy') -> None:\n \"\"\"Check that matrix indices are valid in the economy.\"\"\"\n super()._validate(economy)\n if self.X2_index1 >= economy.K2:\n raise ValueError(f\"X2_index1 must be between 0 and K2 = {economy.K2}, inclusive.\")\n if self.X2_index2 >= economy.K2:\n raise ValueError(f\"X2_index2 must be between 0 and K2 = {economy.K2}, inclusive.\")\n\n def _compute_agent_values(\n self, market: 'Market', delta: Array, probabilities: Array, conditionals: Optional[Array],\n inside_probabilities: Optional[Array], eliminated_probabilities: Dict[int, Array],\n inside_eliminated_sum: Optional[Array]) -> Array:\n \"\"\"Compute agent-specific micro moment values, which will be aggregated up into means or covariances.\"\"\"\n assert inside_probabilities is not None and inside_eliminated_sum is not None\n x1 = market.products.X2[:, [self.X2_index1]]\n x2 = market.products.X2[:, [self.X2_index2]]\n z1 = inside_probabilities.T @ x1\n z2 = inside_eliminated_sum.T @ x2\n demeaned_z1 = z1 - market.agents.weights.T @ z1\n demeaned_z2 = z2 - market.agents.weights.T @ z2\n return demeaned_z1 * demeaned_z2\n\n def _compute_agent_values_tangent(\n self, market: 'Market', p: int, delta: Array, probabilities: Array, probabilities_tangent: Array,\n inside_probabilities: Optional[Array], inside_tangent: Optional[Array],\n eliminated_tangents: Dict[int, Array], inside_eliminated_sum: Optional[Array],\n inside_eliminated_sum_tangent: Optional[Array]) -> Array:\n \"\"\"Compute the tangent of agent-specific micro moments with respect to a parameter.\"\"\"\n assert inside_probabilities is not None and inside_tangent is not None\n assert inside_eliminated_sum is not None and inside_eliminated_sum_tangent is not None\n x1 = market.products.X2[:, [self.X2_index1]]\n x2 = market.products.X2[:, [self.X2_index2]]\n z1 = inside_probabilities.T @ x1\n z1_tangent = inside_tangent.T @ x1\n z2 = inside_eliminated_sum.T @ x2\n z2_tangent = inside_eliminated_sum_tangent.T @ x2\n demeaned_z1 = z1 - market.agents.weights.T @ z1\n demeaned_z1_tangent = z1_tangent - market.agents.weights.T @ z1_tangent\n demeaned_z2 = z2 - market.agents.weights.T @ z2\n demeaned_z2_tangent = z2_tangent - market.agents.weights.T @ z2_tangent\n return demeaned_z1_tangent * demeaned_z2 + demeaned_z1 * demeaned_z2_tangent\n\n\nclass CustomMoment(Moment):\n r\"\"\"Configuration for custom micro moments.\n\n This configuration requires a value :math:`\\mathscr{V}_m` computed, for example, from survey data. It also requires\n a function that computes the simulated counterpart of this value,\n\n .. math:: v_{mt} = \\sum_{i \\in I_t} w_{it} v_{imt},\n\n a simulated integral over agent-specific micro values :math:`v_{imt}` computed according to a custom function. These\n are averaged across a set of markets :math:`T_m` and compared with :math:`\\mathscr{V}_m`, which gives\n :math:`\\bar{g}_{M,m}` in :eq:`averaged_micro_moments`.\n\n Parameters\n ----------\n value : `float`\n Value :math:`\\mathscr{V}_m` of the statistic estimated from micro data.\n observations : `int`\n Number of micro data observations :math:`N_m` used to estimate :math:`\\mathscr{V}_m`, which is used to properly\n scale micro moment covariances in :eq:`scaled_micro_moment_covariances`.\n compute_custom : `callable`\n Function that computes :math:`v_{imt}` in a single market :math:`t`, which is of the following form::\n\n compute_custom(t, sigma, pi, rho, products, agents, delta, mu, probabilities) -> custom\n\n where\n\n - ``t`` is the ID of the market in which the :math:`v_{imt}` should be computed;\n\n - ``sigma`` is the Cholesky root of the covariance matrix for unobserved taste heterogeneity,\n :math:`\\Sigma`, which will be empty if there are no such parameters;\n\n - ``pi`` are parameters that measure how agent tastes vary with demographics, :math:`\\Pi`, which will be\n empty if there are no such parameters;\n\n - ``rho`` is a :math:`J_t \\times 1` vector with parameters that measure within nesting group correlations\n for each product, :math:`\\rho_{h(j)}`, which will be empty if there is no nesting structure;\n\n - ``products`` is a :class:`Products` instance containing product data for the current market;\n\n - ``agents`` is an :class:`Agents` instance containing agent data for the current market;\n\n - ``delta`` is a :math:`J_t \\times 1` vector of mean utilities :math:`\\delta_{jt}`;\n\n - ``mu`` is a :math:`J_t \\times I_t` matrix of agent-specific utilities :math:`\\mu_{ijt}`;\n\n - ``probabilities`` is a :math:`J_t \\times I_t` matrix of choice probabilities :math:`s_{ijt}`; and\n\n - ``custom`` is an :math:`I_t \\times 1`` vector of agent-specific micro values :math:`v_{imt}`.\n\n compute_custom_derivatives : `callable, optional`\n Function that computes :math:`\\frac{\\partial v_{imt}}{\\partial \\theta_p}` in a single market :math:`t`, which is\n of the following form::\n\n compute_custom_derivatives(t, sigma, pi, rho, products, agents, delta, mu, probabilities, p, derivatives) ->\n custom_derivatives\n\n where the first few arguments are the same as above,\n\n - ``p`` is the index :math:`p \\in \\{0, \\dots, P - 1\\}` of :math:`\\theta_p` (for the ordering of the\n :math:`P` parameters in :math:`\\theta`, see :attr:`ProblemResults.theta`),\n\n - ``derivatives`` is a :math:`J_t \\times I_t` matrix of derivatives\n :math:`\\frac{\\partial s_{ijt}}{\\partial \\theta_p}`, and\n\n - ``custom_derivatives`` is an :math:`I_t \\times 1` vector of agent-specific micro value derivatives\n :math:`\\frac{\\partial v_{imt}}{\\partial \\theta_p}`.\n\n If this function is left unspecified, you must set ``finite_differences=True`` in :meth:`Problem.solve` when\n using custom moments. This may slow down optimization and slightly reduce the numerical accuracy of standard\n errors.\n\n If you specify this function, to check that you have implemented derivatives correctly, you can pass\n ``optimization=Optimization('return')`` to :meth:`Problem.solve` when evaluating the gradient with\n ``finite_differences=True`` and ``finite_differences=False``. If the numerical gradient is close to the analytic\n one, this suggests that you have implemented derivatives correctly.\n\n market_ids : `array-like, optional`\n Distinct market IDs over which the micro moments will be averaged to get :math:`\\bar{g}_{M,m}`. These are also\n the only markets in which the moments will be computed. By default, the moments are computed for and averaged\n across all markets.\n market_weights : `array-like, optional`\n Weights for averaging micro moments over specified ``market_ids``. By default, these are :math:`1 / T_m`.\n name : `str, optional`\n Name of the custom moment, which will be used when displaying information about micro moments. By default, this\n is ``\"Custom\"``.\n\n Examples\n --------\n - :doc:`Tutorial </tutorial>`\n\n \"\"\"\n\n name: str\n compute_custom: functools.partial\n compute_custom_derivatives: Optional[functools.partial]\n\n def __init__(\n self, value: float, observations: int, compute_custom: Callable,\n compute_custom_derivatives: Optional[Callable] = None, market_ids: Optional[Sequence] = None,\n market_weights: Optional[Array] = None, name: str = \"Custom\") -> None:\n \"\"\"Validate information about the moment to the greatest extent possible without an economy instance.\"\"\"\n if not callable(compute_custom):\n raise ValueError(\"compute_custom must be callable.\")\n if compute_custom_derivatives is not None and not callable(compute_custom_derivatives):\n raise ValueError(\"compute_custom_derivatives must be None or callable.\")\n super().__init__(value, observations, market_ids, market_weights)\n self.name = name\n self.compute_custom = functools.partial(compute_custom)\n if compute_custom_derivatives is None:\n self.compute_custom_derivatives = None\n else:\n self.compute_custom_derivatives = functools.partial(compute_custom_derivatives)\n\n def _format_moment(self) -> str:\n \"\"\"The expression for the moment is just the specified name.\"\"\"\n return self.name\n\n def _compute_agent_values(\n self, market: 'Market', delta: Array, probabilities: Array, conditionals: Optional[Array],\n inside_probabilities: Optional[Array], eliminated_probabilities: Dict[int, Array],\n inside_eliminated_sum: Optional[Array]) -> Array:\n \"\"\"Compute agent-specific micro moment values, which will be aggregated up into means or covariances.\"\"\"\n values = self.compute_custom(\n market.t, market.sigma, market.pi, market.rho, market.products, market.agents, delta, market.mu,\n probabilities\n )\n values = np.asarray(values, options.dtype)\n if values.size != market.I:\n raise ValueError(\"compute_custom must return a vector with as many elements as agents.\")\n return values.reshape((market.I, 1))\n\n def _compute_agent_values_tangent(\n self, market: 'Market', p: int, delta: Array, probabilities: Array, probabilities_tangent: Array,\n inside_probabilities: Optional[Array], inside_tangent: Optional[Array],\n eliminated_tangents: Dict[int, Array], inside_eliminated_sum: Optional[Array],\n inside_eliminated_sum_tangent: Optional[Array]) -> Array:\n \"\"\"Compute the tangent of agent-specific micro moments with respect to a parameter.\"\"\"\n assert self.compute_custom_derivatives is not None\n derivatives = self.compute_custom_derivatives(\n market.t, market.sigma, market.pi, market.rho, market.products, market.agents, delta, market.mu,\n probabilities, p, probabilities_tangent\n )\n derivatives = np.asarray(derivatives, options.dtype)\n if derivatives.size != market.I:\n raise ValueError(\"compute_custom_derivatives must return a vector with as many elements as agents.\")\n return derivatives.reshape((market.I, 1))\n\n\nclass Moments(object):\n \"\"\"Information about a sequence of micro moments.\"\"\"\n\n micro_moments: Sequence[Moment]\n MM: int\n\n def __init__(self, micro_moments: Sequence[Moment]) -> None:\n \"\"\"Store information about a sequence of micro moment instances.\"\"\"\n self.micro_moments = micro_moments\n self.MM = len(micro_moments)\n\n def format(self, title: str, values: Optional[Array] = None) -> str:\n \"\"\"Format micro moments (and optionally their values) as a string.\"\"\"\n\n # construct the leftmost part of the table that always shows up\n header = [\"Index\", \"Type\", \"Markets\", \"N\", \"Value\"]\n data: List[List[str]] = []\n for m, moment in enumerate(self.micro_moments):\n data.append([\n str(m),\n moment._format_moment(),\n moment._format_markets(),\n str(moment.observations),\n format_number(moment.value),\n ])\n\n # add moment values\n if values is not None:\n header.append(\"Moment\")\n for m, value in enumerate(values):\n data[m].append(format_number(value))\n\n return format_table(header, *data, title=title)\n\n\nclass EconomyMoments(Moments):\n \"\"\"Information about a sequence of micro moments in an economy.\"\"\"\n\n market_values: Dict[Hashable, Array]\n market_indices: Dict[Hashable, Array]\n market_weights: Dict[Hashable, Array]\n\n def __init__(self, economy: 'Economy', micro_moments: Sequence[Moment]) -> None:\n \"\"\"Validate and store information about a sequence of micro moment instances in the context of an economy.\"\"\"\n\n # validate the moments\n if not isinstance(micro_moments, collections.abc.Sequence):\n raise TypeError(\"micro_moments must be a sequence of micro moment instances.\")\n for moment in micro_moments:\n if not isinstance(moment, Moment):\n raise TypeError(\"micro_moments must consist only of micro moment instances.\")\n try:\n moment._validate(economy)\n except Exception as exception:\n raise ValueError(f\"The micro moment '{moment}' is invalid.\") from exception\n\n # store basic moment information\n super().__init__(micro_moments)\n\n # identify moment information that is relevant in each market\n self.market_values: Dict[Hashable, Array] = {}\n self.market_indices: Dict[Hashable, Array] = {}\n self.market_weights: Dict[Hashable, Array] = {}\n for t in economy.unique_market_ids:\n values = []\n indices = []\n weights = []\n for m, moment in enumerate(self.micro_moments):\n market_ids_m = economy.unique_market_ids if moment.market_ids is None else moment.market_ids\n if t in market_ids_m:\n values.append(moment.value)\n indices.append(m)\n if moment.market_weights is None:\n weights.append(1 / market_ids_m.size)\n else:\n weights.append(moment.market_weights[np.argmax(market_ids_m == t)])\n\n self.market_values[t] = np.array(values, options.dtype).flatten()\n self.market_indices[t] = np.array(indices, np.int)\n self.market_weights[t] = np.array(weights, options.dtype).flatten()\n\n\nclass MarketMoments(Moments):\n \"\"\"Information about a sequence of micro moments in a market.\"\"\"\n\n def __init__(self, economy_moments: EconomyMoments, t: Hashable) -> None:\n \"\"\"Select only those micro moment instances that will be computed for this market.\"\"\"\n super().__init__([m for m in economy_moments.micro_moments if m.market_ids is None or t in m.market_ids])\n"
]
| [
[
"numpy.unique",
"numpy.asarray",
"numpy.argmax",
"numpy.array",
"numpy.zeros",
"numpy.where"
]
]
|
efocht/tensorflow | [
"1e264cfc048d247c7f99d6eb663bdb219c97d36b"
]
| [
"tensorflow/api_template_v1.__init__.py"
]
| [
"# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Bring in all of the public TensorFlow interface into this module.\"\"\"\n\nfrom __future__ import absolute_import as _absolute_import\nfrom __future__ import division as _division\nfrom __future__ import print_function as _print_function\n\nimport distutils as _distutils\nimport inspect as _inspect\nimport os as _os\nimport site as _site\nimport sys as _sys\n\n# pylint: disable=g-bad-import-order\nfrom tensorflow.python import pywrap_tensorflow # pylint: disable=unused-import\nfrom tensorflow.python.tools import module_util as _module_util\n\n# API IMPORTS PLACEHOLDER\n\n# Make sure directory containing top level submodules is in\n# the __path__ so that \"from tensorflow.foo import bar\" works.\n# We're using bitwise, but there's nothing special about that.\n_API_MODULE = bitwise # pylint: disable=undefined-variable\n_current_module = _sys.modules[__name__]\n_tf_api_dir = _os.path.dirname(_os.path.dirname(_API_MODULE.__file__))\nif not hasattr(_current_module, '__path__'):\n __path__ = [_tf_api_dir]\nelif _tf_api_dir not in __path__:\n __path__.append(_tf_api_dir)\n\n# Hook external TensorFlow modules.\ntry:\n from tensorflow_estimator.python.estimator.api._v1 import estimator\n _current_module.__path__ = (\n [_module_util.get_parent_dir(estimator)] + _current_module.__path__)\nexcept ImportError:\n pass\n\ntry:\n from tensorflow.python.keras.api._v1 import keras\n _current_module.__path__ = (\n [_module_util.get_parent_dir(keras)] + _current_module.__path__)\nexcept ImportError:\n pass\n\n\nfrom tensorflow.python.util.lazy_loader import LazyLoader # pylint: disable=g-import-not-at-top\n_CONTRIB_WARNING = \"\"\"\nThe TensorFlow contrib module will not be included in TensorFlow 2.0.\nFor more information, please see:\n * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n * https://github.com/tensorflow/addons\n * https://github.com/tensorflow/io (for I/O related ops)\nIf you depend on functionality not listed there, please file an issue.\n\"\"\"\ncontrib = LazyLoader('contrib', globals(), 'tensorflow.contrib',\n _CONTRIB_WARNING)\ndel LazyLoader\n# The templated code that replaces the placeholder above sometimes\n# sets the __all__ variable. If it does, we have to be sure to add\n# \"contrib\".\nif '__all__' in vars():\n vars()['__all__'].append('contrib')\n\nfrom tensorflow.python.platform import flags # pylint: disable=g-import-not-at-top\n# The 'app' module will be imported as part of the placeholder section above.\napp.flags = flags # pylint: disable=undefined-variable\n\n# Load all plugin libraries from site-packages/tensorflow-plugins if we are\n# running under pip.\n# TODO(gunan): Enable setting an environment variable to define arbitrary plugin\n# directories.\n# TODO(gunan): Find a better location for this code snippet.\nfrom tensorflow.python.framework import load_library as _ll\nfrom tensorflow.python.lib.io import file_io as _fi\n\n# Get sitepackages directories for the python installation.\n_site_packages_dirs = []\n_site_packages_dirs += [_site.USER_SITE]\n_site_packages_dirs += [_p for _p in _sys.path if 'site-packages' in _p]\nif 'getsitepackages' in dir(_site):\n _site_packages_dirs += _site.getsitepackages()\n\nif 'sysconfig' in dir(_distutils):\n _site_packages_dirs += [_distutils.sysconfig.get_python_lib()]\n\n_site_packages_dirs = list(set(_site_packages_dirs))\n\n# Find the location of this exact file.\n_current_file_location = _inspect.getfile(_inspect.currentframe())\n\ndef _running_from_pip_package():\n return any(\n _current_file_location.startswith(dir_) for dir_ in _site_packages_dirs)\n\nif _running_from_pip_package():\n for s in _site_packages_dirs:\n # TODO(gunan): Add sanity checks to loaded modules here.\n plugin_dir = _os.path.join(s, 'tensorflow-plugins')\n if _fi.file_exists(plugin_dir):\n _ll.load_library(plugin_dir)\n\n# These symbols appear because we import the python package which\n# in turn imports from tensorflow.core and tensorflow.python. They\n# must come from this module. So python adds these symbols for the\n# resolution to succeed.\n# pylint: disable=undefined-variable\ntry:\n del python\n if '__all__' in vars():\n vars()['__all__'].remove('python')\n del core\n if '__all__' in vars():\n vars()['__all__'].remove('core')\nexcept NameError:\n # Don't fail if these modules are not available.\n # For e.g. this file will be originally placed under tensorflow/_api/v1 which\n # does not have 'python', 'core' directories. Then, it will be copied\n # to tensorflow/ which does have these two directories.\n pass\n# Similarly for compiler. Do it separately to make sure we do this even if the\n# others don't exist.\ntry:\n del compiler\n if '__all__' in vars():\n vars()['__all__'].remove('compiler')\nexcept NameError:\n pass\n# pylint: enable=undefined-variable\n\nif 'VEORUN_BIN' not in _os.environ:\n veorun = _os.path.dirname(_current_file_location) + \"/aux-bin/veorun_tf\"\n _os.environ['VEORUN_BIN'] = veorun\n"
]
| [
[
"tensorflow.python.framework.load_library.load_library",
"tensorflow.python.tools.module_util.get_parent_dir",
"tensorflow.python.lib.io.file_io.file_exists"
]
]
|
ZurichNLP/nematus-multisource | [
"6929149aa297625a92d52215bc0d6ed9bea48d50"
]
| [
"nematus/theano_util.py"
]
| [
"'''\nTheano utility functions\n'''\n\nimport sys\nimport json\nimport cPickle as pkl\nimport numpy\nfrom collections import OrderedDict\nimport logging\n\nimport theano\nimport theano.tensor as tensor\nfrom theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams\n\nfloatX = theano.config.floatX\nnumpy_floatX = numpy.typeDict[floatX]\n\n# float16 warning\nif floatX == 'float16':\n bad = True\n try:\n [major_v, minor_v, sub_v] = map(int, theano.version.short_version.split('.'))\n # When a version of Theano that supports float16 without bugs is released, add a check here\n except:\n pass\n if bad:\n print >> sys.stderr, \"Warning: float16 may not be fully supported by the current version of Theano\"\n\n# push parameters to Theano shared variables\ndef zip_to_theano(params, tparams):\n for kk, vv in params.iteritems():\n tparams[kk].set_value(vv)\n\n\n# pull parameters from Theano shared variables\ndef unzip_from_theano(zipped, excluding_prefix=None):\n new_params = OrderedDict()\n for kk, vv in zipped.iteritems():\n if excluding_prefix and (kk.startswith(excluding_prefix)):\n continue\n new_params[kk] = vv.get_value()\n return new_params\n\n\n# get the list of parameters: Note that tparams must be OrderedDict\ndef itemlist(tparams):\n return [vv for kk, vv in tparams.iteritems()]\n\n# make prefix-appended name\ndef pp(pp, name):\n return '%s_%s' % (pp, name)\n\n# initialize Theano shared variables according to the initial parameters\ndef init_theano_params(params):\n tparams = OrderedDict()\n\n for kk, pp in params.iteritems():\n #print('tparams[\"'+str(kk)+'\"] = theano.shared(params[\"'+str(kk)+'\"], name=\"'+str(kk)+'\")')\n tparams[kk] = theano.shared(params[kk], name=kk)\n\n return tparams\n\n\n# load parameters\ndef load_params(path, params, with_prefix=''):\n try:\n pp = numpy.load(path)\n except IOError:\n pp = numpy.load(path + '.npz')\n new_params = OrderedDict()\n for kk, vv in params.iteritems():\n if kk not in pp:\n logging.warn('%s is not in the archive' % kk)\n continue\n if kk == \"zipped_params\":\n continue\n new_params[with_prefix+kk] = pp[kk].astype(floatX, copy=False)\n\n params.update(new_params)\n return params\n\n# load parameters of the optimizer\ndef load_optimizer_params(path, optimizer_name):\n params = {}\n try:\n pp = numpy.load(path)\n except IOError:\n pp = numpy.load(path + '.npz')\n for kk in pp:\n if kk.startswith(optimizer_name):\n params[kk] = pp[kk].astype(floatX, copy=False)\n return params\n\n# save model parameters, optimizer parameters and progress\ndef save(model_params, optimizer_params, training_progress, base_filename, file_float_type='float32'):\n if file_float_type != floatX:\n new_model_params, new_optimizer_params = {}, {}\n for kk, vv in model_params.iteritems():\n new_model_params[kk] = vv.astype(file_float_type)\n for kk, vv in optimizer_params.iteritems():\n new_optimizer_params[kk] = vv.astype(file_float_type)\n model_params, optimizer_params = new_model_params, new_optimizer_params\n\n numpy.savez(base_filename, **model_params)\n numpy.savez(base_filename + '.gradinfo', **optimizer_params)\n training_progress.save_to_json(base_filename + '.progress.json')\n\ndef tanh(x):\n return tensor.tanh(x)\n\n\ndef linear(x):\n return x\n\n\ndef concatenate(tensor_list, axis=0):\n \"\"\"\n Alternative implementation of `theano.tensor.concatenate`.\n This function does exactly the same thing, but contrary to Theano's own\n implementation, the gradient is implemented on the GPU.\n Backpropagating through `theano.tensor.concatenate` yields slowdowns\n because the inverse operation (splitting) needs to be done on the CPU.\n This implementation does not have that problem.\n :usage:\n >>> x, y = theano.tensor.matrices('x', 'y')\n >>> c = concatenate([x, y], axis=1)\n :parameters:\n - tensor_list : list\n list of Theano tensor expressions that should be concatenated.\n - axis : int\n the tensors will be joined along this axis.\n :returns:\n - out : tensor\n the concatenated tensor expression.\n \"\"\"\n concat_size = sum(tt.shape[axis] for tt in tensor_list)\n\n output_shape = ()\n for k in range(axis):\n output_shape += (tensor_list[0].shape[k],)\n output_shape += (concat_size,)\n for k in range(axis + 1, tensor_list[0].ndim):\n output_shape += (tensor_list[0].shape[k],)\n\n out = tensor.zeros(output_shape)\n offset = 0\n for tt in tensor_list:\n indices = ()\n for k in range(axis):\n indices += (slice(None),)\n indices += (slice(offset, offset + tt.shape[axis]),)\n for k in range(axis + 1, tensor_list[0].ndim):\n indices += (slice(None),)\n\n out = tensor.set_subtensor(out[indices], tt)\n offset += tt.shape[axis]\n\n return out\n\n# return name of word embedding for factor i\n# special handling of factor 0 for backward compatibility\ndef embedding_name(i):\n if i == 0:\n return 'Wemb'\n else:\n return 'Wemb'+str(i)\n\n# Zero out all parameters\ndef zero_all(params):\n for kk, vv in params.iteritems():\n vv[:] = numpy.zeros_like(vv)\n\n"
]
| [
[
"numpy.load",
"numpy.savez",
"numpy.zeros_like"
]
]
|
potating-potato/napari | [
"2ab705daf6a47561f409fb623093fe93d5b11c35"
]
| [
"napari/components/_tests/test_viewer_model.py"
]
| [
"import time\n\nimport numpy as np\nimport pytest\n\nfrom napari._tests.utils import (\n good_layer_data,\n layer_test_data,\n restore_settings_on_exit,\n)\nfrom napari.components import ViewerModel\nfrom napari.errors import MultipleReaderError, ReaderPluginError\nfrom napari.errors.reader_errors import (\n MissingAssociatedReaderError,\n NoAvailableReaderError,\n)\nfrom napari.layers import Image\nfrom napari.settings import get_settings\nfrom napari.utils.colormaps import AVAILABLE_COLORMAPS, Colormap\nfrom napari.utils.events.event import WarningEmitter\n\n\ndef test_viewer_model():\n \"\"\"Test instantiating viewer model.\"\"\"\n viewer = ViewerModel()\n assert viewer.title == 'napari'\n assert len(viewer.layers) == 0\n assert viewer.dims.ndim == 2\n\n # Create viewer model with custom title\n viewer = ViewerModel(title='testing')\n assert viewer.title == 'testing'\n\n\ndef test_add_image():\n \"\"\"Test adding image.\"\"\"\n viewer = ViewerModel()\n np.random.seed(0)\n data = np.random.random((10, 15))\n viewer.add_image(data)\n assert len(viewer.layers) == 1\n assert np.all(viewer.layers[0].data == data)\n assert viewer.dims.ndim == 2\n\n\ndef test_add_image_multichannel_share_memory():\n viewer = ViewerModel()\n image = np.random.random((10, 5, 64, 64))\n layers = viewer.add_image(image, channel_axis=1)\n for layer in layers:\n assert np.may_share_memory(image, layer.data)\n\n\ndef test_add_image_colormap_variants():\n \"\"\"Test adding image with all valid colormap argument types.\"\"\"\n viewer = ViewerModel()\n np.random.seed(0)\n data = np.random.random((10, 15))\n # as string\n assert viewer.add_image(data, colormap='green')\n\n # as string that is valid, but not a default colormap\n assert viewer.add_image(data, colormap='fire')\n\n # as tuple\n cmap_tuple = (\"my_colormap\", Colormap(['g', 'm', 'y']))\n assert viewer.add_image(data, colormap=cmap_tuple)\n\n # as dict\n cmap_dict = {\"your_colormap\": Colormap(['g', 'r', 'y'])}\n assert viewer.add_image(data, colormap=cmap_dict)\n\n # as Colormap instance\n blue_cmap = AVAILABLE_COLORMAPS['blue']\n assert viewer.add_image(data, colormap=blue_cmap)\n\n # string values must be known colormap types\n with pytest.raises(KeyError) as err:\n viewer.add_image(data, colormap='nonsense')\n\n assert 'Colormap \"nonsense\" not found' in str(err.value)\n\n # lists are only valid with channel_axis\n with pytest.raises(TypeError) as err:\n viewer.add_image(data, colormap=['green', 'red'])\n\n assert \"did you mean to specify a 'channel_axis'\" in str(err.value)\n\n\ndef test_add_volume():\n \"\"\"Test adding volume.\"\"\"\n viewer = ViewerModel(ndisplay=3)\n np.random.seed(0)\n data = np.random.random((10, 15, 20))\n viewer.add_image(data)\n assert len(viewer.layers) == 1\n assert np.all(viewer.layers[0].data == data)\n assert viewer.dims.ndim == 3\n\n\ndef test_add_multiscale():\n \"\"\"Test adding image multiscale.\"\"\"\n viewer = ViewerModel()\n shapes = [(40, 20), (20, 10), (10, 5)]\n np.random.seed(0)\n data = [np.random.random(s) for s in shapes]\n viewer.add_image(data, multiscale=True)\n assert len(viewer.layers) == 1\n assert np.all(viewer.layers[0].data == data)\n assert viewer.dims.ndim == 2\n\n\ndef test_add_labels():\n \"\"\"Test adding labels image.\"\"\"\n viewer = ViewerModel()\n np.random.seed(0)\n data = np.random.randint(20, size=(10, 15))\n viewer.add_labels(data)\n assert len(viewer.layers) == 1\n assert np.all(viewer.layers[0].data == data)\n assert viewer.dims.ndim == 2\n\n\ndef test_add_points():\n \"\"\"Test adding points.\"\"\"\n viewer = ViewerModel()\n np.random.seed(0)\n data = 20 * np.random.random((10, 2))\n viewer.add_points(data)\n assert len(viewer.layers) == 1\n assert np.all(viewer.layers[0].data == data)\n assert viewer.dims.ndim == 2\n\n\ndef test_single_point_dims():\n \"\"\"Test dims of a Points layer with a single 3D point.\"\"\"\n viewer = ViewerModel()\n shape = (1, 3)\n data = np.zeros(shape)\n viewer.add_points(data)\n assert all(r == (0.0, 1.0, 1.0) for r in viewer.dims.range)\n\n\ndef test_add_empty_points_to_empty_viewer():\n viewer = ViewerModel()\n layer = viewer.add_points(name='empty points')\n assert layer.ndim == 2\n layer.add([1000.0, 27.0])\n assert layer.data.shape == (1, 2)\n\n\ndef test_add_empty_points_on_top_of_image():\n viewer = ViewerModel()\n image = np.random.random((8, 64, 64))\n # add_image always returns the corresponding layer\n _ = viewer.add_image(image)\n layer = viewer.add_points(ndim=3)\n assert layer.ndim == 3\n layer.add([5.0, 32.0, 61.0])\n assert layer.data.shape == (1, 3)\n\n\ndef test_add_empty_shapes_layer():\n viewer = ViewerModel()\n image = np.random.random((8, 64, 64))\n # add_image always returns the corresponding layer\n _ = viewer.add_image(image)\n layer = viewer.add_shapes(ndim=3)\n assert layer.ndim == 3\n\n\ndef test_add_vectors():\n \"\"\"Test adding vectors.\"\"\"\n viewer = ViewerModel()\n np.random.seed(0)\n data = 20 * np.random.random((10, 2, 2))\n viewer.add_vectors(data)\n assert len(viewer.layers) == 1\n assert np.all(viewer.layers[0].data == data)\n assert viewer.dims.ndim == 2\n\n\ndef test_add_shapes():\n \"\"\"Test adding shapes.\"\"\"\n viewer = ViewerModel()\n np.random.seed(0)\n data = 20 * np.random.random((10, 4, 2))\n viewer.add_shapes(data)\n assert len(viewer.layers) == 1\n assert np.all(viewer.layers[0].data == data)\n assert viewer.dims.ndim == 2\n\n\ndef test_add_surface():\n \"\"\"Test adding 3D surface.\"\"\"\n viewer = ViewerModel()\n np.random.seed(0)\n vertices = np.random.random((10, 3))\n faces = np.random.randint(10, size=(6, 3))\n values = np.random.random(10)\n data = (vertices, faces, values)\n viewer.add_surface(data)\n assert len(viewer.layers) == 1\n assert np.all(\n [np.all(vd == d) for vd, d in zip(viewer.layers[0].data, data)]\n )\n assert viewer.dims.ndim == 3\n\n\ndef test_mix_dims():\n \"\"\"Test adding images of mixed dimensionality.\"\"\"\n viewer = ViewerModel()\n np.random.seed(0)\n data = np.random.random((10, 15))\n viewer.add_image(data)\n assert len(viewer.layers) == 1\n assert np.all(viewer.layers[0].data == data)\n assert viewer.dims.ndim == 2\n\n data = np.random.random((6, 10, 15))\n viewer.add_image(data)\n assert len(viewer.layers) == 2\n assert np.all(viewer.layers[1].data == data)\n assert viewer.dims.ndim == 3\n\n\ndef test_new_labels_empty():\n \"\"\"Test adding new labels layer to empty viewer.\"\"\"\n viewer = ViewerModel()\n viewer._new_labels()\n assert len(viewer.layers) == 1\n assert np.max(viewer.layers[0].data) == 0\n assert viewer.dims.ndim == 2\n # Default shape when no data is present is 512x512\n np.testing.assert_equal(viewer.layers[0].data.shape, (512, 512))\n\n\ndef test_new_labels_image():\n \"\"\"Test adding new labels layer with image present.\"\"\"\n viewer = ViewerModel()\n np.random.seed(0)\n data = np.random.random((10, 15))\n viewer.add_image(data)\n viewer._new_labels()\n assert len(viewer.layers) == 2\n assert np.max(viewer.layers[1].data) == 0\n assert viewer.dims.ndim == 2\n np.testing.assert_equal(viewer.layers[1].data.shape, (10, 15))\n np.testing.assert_equal(viewer.layers[1].scale, (1, 1))\n np.testing.assert_equal(viewer.layers[1].translate, (0, 0))\n\n\ndef test_new_labels_scaled_image():\n \"\"\"Test adding new labels layer with scaled image present.\"\"\"\n viewer = ViewerModel()\n np.random.seed(0)\n data = np.random.random((10, 15))\n viewer.add_image(data, scale=(3, 3))\n viewer._new_labels()\n assert len(viewer.layers) == 2\n assert np.max(viewer.layers[1].data) == 0\n assert viewer.dims.ndim == 2\n np.testing.assert_equal(viewer.layers[1].data.shape, (10, 15))\n np.testing.assert_equal(viewer.layers[1].scale, (3, 3))\n np.testing.assert_equal(viewer.layers[1].translate, (0, 0))\n\n\ndef test_new_labels_scaled_translated_image():\n \"\"\"Test adding new labels layer with transformed image present.\"\"\"\n viewer = ViewerModel()\n np.random.seed(0)\n data = np.random.random((10, 15))\n viewer.add_image(data, scale=(3, 3), translate=(20, -5))\n viewer._new_labels()\n assert len(viewer.layers) == 2\n assert np.max(viewer.layers[1].data) == 0\n assert viewer.dims.ndim == 2\n np.testing.assert_almost_equal(viewer.layers[1].data.shape, (10, 15))\n np.testing.assert_almost_equal(viewer.layers[1].scale, (3, 3))\n np.testing.assert_almost_equal(viewer.layers[1].translate, (20, -5))\n\n\ndef test_new_points():\n \"\"\"Test adding new points layer.\"\"\"\n # Add labels to empty viewer\n viewer = ViewerModel()\n viewer.add_points()\n assert len(viewer.layers) == 1\n assert len(viewer.layers[0].data) == 0\n assert viewer.dims.ndim == 2\n\n # Add points with image already present\n viewer = ViewerModel()\n np.random.seed(0)\n data = np.random.random((10, 15))\n viewer.add_image(data)\n viewer.add_points()\n assert len(viewer.layers) == 2\n assert len(viewer.layers[1].data) == 0\n assert viewer.dims.ndim == 2\n\n\ndef test_view_centering_with_points_add():\n \"\"\"Test if the viewer is only centered when the first\n points were added\n Regression test for issue #3803\n \"\"\"\n image = np.zeros((5, 10, 10))\n\n viewer = ViewerModel()\n viewer.add_image(image)\n assert tuple(viewer.dims.point) == (2, 5, 5)\n\n viewer.dims.set_point(0, 0)\n # viewer point shouldn't change after this\n assert tuple(viewer.dims.point) == (0, 5, 5)\n\n pts_layer = viewer.add_points(ndim=3)\n assert tuple(viewer.dims.point) == (0, 5, 5)\n\n pts_layer.add([(0, 8, 8)])\n assert tuple(viewer.dims.point) == (0, 5, 5)\n\n\ndef test_new_shapes():\n \"\"\"Test adding new shapes layer.\"\"\"\n # Add labels to empty viewer\n viewer = ViewerModel()\n viewer.add_shapes()\n assert len(viewer.layers) == 1\n assert len(viewer.layers[0].data) == 0\n assert viewer.dims.ndim == 2\n\n # Add points with image already present\n viewer = ViewerModel()\n np.random.seed(0)\n data = np.random.random((10, 15))\n viewer.add_image(data)\n viewer.add_shapes()\n assert len(viewer.layers) == 2\n assert len(viewer.layers[1].data) == 0\n assert viewer.dims.ndim == 2\n\n\ndef test_swappable_dims():\n \"\"\"Test swapping dims after adding layers.\"\"\"\n viewer = ViewerModel()\n np.random.seed(0)\n image_data = np.random.random((7, 12, 10, 15))\n image_name = viewer.add_image(image_data).name\n assert np.all(\n viewer.layers[image_name]._data_view == image_data[3, 6, :, :]\n )\n\n points_data = np.random.randint(6, size=(10, 4))\n viewer.add_points(points_data)\n\n vectors_data = np.random.randint(6, size=(10, 2, 4))\n viewer.add_vectors(vectors_data)\n\n labels_data = np.random.randint(20, size=(7, 12, 10, 15))\n labels_name = viewer.add_labels(labels_data).name\n # midpoints indices into the data below depend on the data range.\n # This depends on the values in vectors_data and thus the random seed.\n assert np.all(\n viewer.layers[labels_name]._slice.image.raw == labels_data[3, 6, :, :]\n )\n\n # Swap dims\n viewer.dims.order = [0, 2, 1, 3]\n assert viewer.dims.order == (0, 2, 1, 3)\n assert np.all(\n viewer.layers[image_name]._data_view == image_data[3, :, 5, :]\n )\n assert np.all(\n viewer.layers[labels_name]._slice.image.raw == labels_data[3, :, 5, :]\n )\n\n\ndef test_grid():\n \"Test grid_view\"\n viewer = ViewerModel()\n\n np.random.seed(0)\n # Add image\n for i in range(6):\n data = np.random.random((15, 15))\n viewer.add_image(data)\n assert not viewer.grid.enabled\n assert viewer.grid.actual_shape(6) == (1, 1)\n assert viewer.grid.stride == 1\n translations = [layer._translate_grid for layer in viewer.layers]\n expected_translations = np.zeros((6, 2))\n np.testing.assert_allclose(translations, expected_translations)\n\n # enter grid view\n viewer.grid.enabled = True\n assert viewer.grid.enabled\n assert viewer.grid.actual_shape(6) == (2, 3)\n assert viewer.grid.stride == 1\n translations = [layer._translate_grid for layer in viewer.layers]\n expected_translations = [\n [0, 0],\n [0, 15],\n [0, 30],\n [15, 0],\n [15, 15],\n [15, 30],\n ]\n np.testing.assert_allclose(translations, expected_translations[::-1])\n\n # return to stack view\n viewer.grid.enabled = False\n assert not viewer.grid.enabled\n assert viewer.grid.actual_shape(6) == (1, 1)\n assert viewer.grid.stride == 1\n translations = [layer._translate_grid for layer in viewer.layers]\n expected_translations = np.zeros((6, 2))\n np.testing.assert_allclose(translations, expected_translations)\n\n # reenter grid view with new stride\n viewer.grid.stride = -2\n viewer.grid.enabled = True\n assert viewer.grid.enabled\n assert viewer.grid.actual_shape(6) == (2, 2)\n assert viewer.grid.stride == -2\n translations = [layer._translate_grid for layer in viewer.layers]\n expected_translations = [\n [0, 0],\n [0, 0],\n [0, 15],\n [0, 15],\n [15, 0],\n [15, 0],\n ]\n np.testing.assert_allclose(translations, expected_translations)\n\n\ndef test_add_remove_layer_dims_change():\n \"\"\"Test dims change appropriately when adding and removing layers.\"\"\"\n np.random.seed(0)\n viewer = ViewerModel()\n\n # Check ndim starts at 2\n assert viewer.dims.ndim == 2\n\n # Check ndim increase to 3 when 3D data added\n data = np.random.random((10, 15, 20))\n layer = viewer.add_image(data)\n assert len(viewer.layers) == 1\n assert np.all(viewer.layers[0].data == data)\n assert viewer.dims.ndim == 3\n\n # Remove layer and check ndim returns to 2\n viewer.layers.remove(layer)\n assert len(viewer.layers) == 0\n assert viewer.dims.ndim == 2\n\n\[email protected]('data', good_layer_data)\ndef test_add_layer_from_data(data):\n # make sure adding valid layer data calls the proper corresponding add_*\n # method for all layer types\n viewer = ViewerModel()\n viewer._add_layer_from_data(*data)\n\n # make sure a layer of the correct type got added\n assert len(viewer.layers) == 1\n expected_layer_type = data[2] if len(data) > 2 else 'image'\n assert viewer.layers[0]._type_string == expected_layer_type\n\n\ndef test_add_layer_from_data_raises():\n # make sure that adding invalid data or kwargs raises the right errors\n viewer = ViewerModel()\n # unrecognized layer type raises Value Error\n with pytest.raises(ValueError):\n # 'layer' is not a valid type\n # (even though there is an add_layer method)\n viewer._add_layer_from_data(\n np.random.random((10, 10)), layer_type='layer'\n )\n\n # even with the correct meta kwargs, the underlying add_* method may raise\n with pytest.raises(ValueError):\n # improper dims for rgb data\n viewer._add_layer_from_data(\n np.random.random((10, 10, 6)), {'rgb': True}\n )\n\n # using a kwarg in the meta dict that is invalid for the corresponding\n # add_* method raises a TypeError\n with pytest.raises(TypeError):\n viewer._add_layer_from_data(\n np.random.random((10, 2, 2)) * 20,\n {'rgb': True}, # vectors do not have an 'rgb' kwarg\n layer_type='vectors',\n )\n\n\ndef test_naming():\n \"\"\"Test unique naming in LayerList.\"\"\"\n viewer = ViewerModel()\n viewer.add_image(np.random.random((10, 10)), name='img')\n viewer.add_image(np.random.random((10, 10)), name='img')\n\n assert [lay.name for lay in viewer.layers] == ['img', 'img [1]']\n\n viewer.layers[1].name = 'chg'\n assert [lay.name for lay in viewer.layers] == ['img', 'chg']\n\n viewer.layers[0].name = 'chg'\n assert [lay.name for lay in viewer.layers] == ['chg [1]', 'chg']\n\n\ndef test_selection():\n \"\"\"Test only last added is selected.\"\"\"\n viewer = ViewerModel()\n viewer.add_image(np.random.random((10, 10)))\n assert viewer.layers[0] in viewer.layers.selection\n\n viewer.add_image(np.random.random((10, 10)))\n assert viewer.layers.selection == {viewer.layers[-1]}\n\n viewer.add_image(np.random.random((10, 10)))\n assert viewer.layers.selection == {viewer.layers[-1]}\n\n viewer.layers.selection.update(viewer.layers)\n viewer.add_image(np.random.random((10, 10)))\n assert viewer.layers.selection == {viewer.layers[-1]}\n\n\ndef test_add_delete_layers():\n \"\"\"Test adding and deleting layers with different dims.\"\"\"\n viewer = ViewerModel()\n np.random.seed(0)\n viewer.add_image(np.random.random((5, 5, 10, 15)))\n assert len(viewer.layers) == 1\n assert viewer.dims.ndim == 4\n viewer.add_image(np.random.random((5, 6, 5, 10, 15)))\n assert len(viewer.layers) == 2\n assert viewer.dims.ndim == 5\n viewer.layers.remove_selected()\n assert len(viewer.layers) == 1\n assert viewer.dims.ndim == 4\n\n\ndef test_active_layer():\n \"\"\"Test active layer is correct as layer selections change.\"\"\"\n viewer = ViewerModel()\n np.random.seed(0)\n # Check no active layer present\n assert viewer.layers.selection.active is None\n\n # Check added layer is active\n viewer.add_image(np.random.random((5, 5, 10, 15)))\n assert len(viewer.layers) == 1\n assert viewer.layers.selection.active == viewer.layers[0]\n\n # Check newly added layer is active\n viewer.add_image(np.random.random((5, 6, 5, 10, 15)))\n assert len(viewer.layers) == 2\n assert viewer.layers.selection.active == viewer.layers[1]\n\n # Check no active layer after unselecting all\n viewer.layers.selection.clear()\n assert viewer.layers.selection.active is None\n\n # Check selected layer is active\n viewer.layers.selection.add(viewer.layers[0])\n assert viewer.layers.selection.active == viewer.layers[0]\n\n # Check no layer is active if both layers are selected\n viewer.layers.selection.add(viewer.layers[1])\n assert viewer.layers.selection.active is None\n\n\ndef test_active_layer_status_update():\n \"\"\"Test status updates from active layer on cursor move.\"\"\"\n viewer = ViewerModel()\n np.random.seed(0)\n viewer.add_image(np.random.random((5, 5, 10, 15)))\n viewer.add_image(np.random.random((5, 6, 5, 10, 15)))\n assert len(viewer.layers) == 2\n assert viewer.layers.selection.active == viewer.layers[1]\n\n # wait 1 s to avoid the cursor event throttling\n time.sleep(1)\n viewer.cursor.position = [1, 1, 1, 1, 1]\n assert viewer.status == viewer.layers.selection.active.get_status(\n viewer.cursor.position, world=True\n )\n\n\ndef test_active_layer_cursor_size():\n \"\"\"Test cursor size update on active layer.\"\"\"\n viewer = ViewerModel()\n np.random.seed(0)\n viewer.add_image(np.random.random((10, 10)))\n # Base layer has a default cursor size of 1\n assert viewer.cursor.size == 1\n\n viewer.add_labels(np.random.randint(0, 10, size=(10, 10)))\n assert len(viewer.layers) == 2\n assert viewer.layers.selection.active == viewer.layers[1]\n\n viewer.layers[1].mode = 'paint'\n # Labels layer has a default cursor size of 10\n # due to paintbrush\n assert viewer.cursor.size == 10\n\n\ndef test_cursor_ndim_matches_layer():\n \"\"\"Test cursor position ndim matches viewer ndim after update.\"\"\"\n viewer = ViewerModel()\n np.random.seed(0)\n im = viewer.add_image(np.random.random((10, 10)))\n assert viewer.dims.ndim == 2\n assert len(viewer.cursor.position) == 2\n\n im.data = np.random.random((10, 10, 10))\n assert viewer.dims.ndim == 3\n assert len(viewer.cursor.position) == 3\n\n im.data = np.random.random((10, 10))\n assert viewer.dims.ndim == 2\n assert len(viewer.cursor.position) == 2\n\n\ndef test_sliced_world_extent():\n \"\"\"Test world extent after adding layers and slicing.\"\"\"\n np.random.seed(0)\n viewer = ViewerModel()\n\n # Empty data is taken to be 512 x 512\n np.testing.assert_allclose(viewer._sliced_extent_world[0], (-0.5, -0.5))\n np.testing.assert_allclose(viewer._sliced_extent_world[1], (511.5, 511.5))\n\n # Add one layer\n viewer.add_image(\n np.random.random((6, 10, 15)), scale=(3, 1, 1), translate=(10, 20, 5)\n )\n np.testing.assert_allclose(viewer.layers.extent.world[0], (8.5, 19.5, 4.5))\n np.testing.assert_allclose(\n viewer.layers.extent.world[1], (26.5, 29.5, 19.5)\n )\n np.testing.assert_allclose(viewer._sliced_extent_world[0], (19.5, 4.5))\n np.testing.assert_allclose(viewer._sliced_extent_world[1], (29.5, 19.5))\n\n # Change displayed dims order\n viewer.dims.order = (1, 2, 0)\n np.testing.assert_allclose(viewer._sliced_extent_world[0], (4.5, 8.5))\n np.testing.assert_allclose(viewer._sliced_extent_world[1], (19.5, 26.5))\n\n\ndef test_camera():\n \"\"\"Test camera.\"\"\"\n viewer = ViewerModel()\n np.random.seed(0)\n data = np.random.random((10, 15, 20))\n viewer.add_image(data)\n assert len(viewer.layers) == 1\n assert np.all(viewer.layers[0].data == data)\n assert viewer.dims.ndim == 3\n\n assert viewer.dims.ndisplay == 2\n assert viewer.camera.center == (0, 7, 9.5)\n assert viewer.camera.angles == (0, 0, 90)\n\n viewer.dims.ndisplay = 3\n assert viewer.dims.ndisplay == 3\n assert viewer.camera.center == (4.5, 7, 9.5)\n assert viewer.camera.angles == (0, 0, 90)\n\n viewer.dims.ndisplay = 2\n assert viewer.dims.ndisplay == 2\n assert viewer.camera.center == (0, 7, 9.5)\n assert viewer.camera.angles == (0, 0, 90)\n\n\ndef test_update_scale():\n viewer = ViewerModel()\n np.random.seed(0)\n shape = (10, 15, 20)\n data = np.random.random(shape)\n viewer.add_image(data)\n assert viewer.dims.range == tuple((0.0, x, 1.0) for x in shape)\n scale = (3.0, 2.0, 1.0)\n viewer.layers[0].scale = scale\n assert viewer.dims.range == tuple(\n (0.0, x * s, s) for x, s in zip(shape, scale)\n )\n\n\[email protected]('Layer, data, ndim', layer_test_data)\ndef test_add_remove_layer_no_callbacks(Layer, data, ndim):\n \"\"\"Test all callbacks for layer emmitters removed.\"\"\"\n viewer = ViewerModel()\n\n layer = Layer(data)\n # Check layer has been correctly created\n assert layer.ndim == ndim\n\n # Check that no internal callbacks have been registered\n len(layer.events.callbacks) == 0\n for em in layer.events.emitters.values():\n assert len(em.callbacks) == 0\n\n viewer.layers.append(layer)\n # Check layer added correctly\n assert len(viewer.layers) == 1\n\n # check that adding a layer created new callbacks\n assert any(len(em.callbacks) > 0 for em in layer.events.emitters.values())\n\n viewer.layers.remove(layer)\n # Check layer added correctly\n assert len(viewer.layers) == 0\n\n # Check that all callbacks have been removed\n assert len(layer.events.callbacks) == 0\n for em in layer.events.emitters.values():\n assert len(em.callbacks) == 0\n\n\[email protected]('Layer, data, ndim', layer_test_data)\ndef test_add_remove_layer_external_callbacks(Layer, data, ndim):\n \"\"\"Test external callbacks for layer emmitters preserved.\"\"\"\n viewer = ViewerModel()\n\n layer = Layer(data)\n # Check layer has been correctly created\n assert layer.ndim == ndim\n\n # Connect a custom callback\n def my_custom_callback():\n return\n\n layer.events.connect(my_custom_callback)\n\n # Check that no internal callbacks have been registered\n len(layer.events.callbacks) == 1\n for em in layer.events.emitters.values():\n if not isinstance(em, WarningEmitter):\n assert len(em.callbacks) == 1\n\n viewer.layers.append(layer)\n # Check layer added correctly\n assert len(viewer.layers) == 1\n\n # check that adding a layer created new callbacks\n assert any(len(em.callbacks) > 0 for em in layer.events.emitters.values())\n\n viewer.layers.remove(layer)\n # Check layer added correctly\n assert len(viewer.layers) == 0\n\n # Check that all internal callbacks have been removed\n assert len(layer.events.callbacks) == 1\n for em in layer.events.emitters.values():\n if not isinstance(em, WarningEmitter):\n assert len(em.callbacks) == 1\n\n\[email protected](\n 'field', ['camera', 'cursor', 'dims', 'grid', 'layers', 'scale_bar']\n)\ndef test_not_mutable_fields(field):\n \"\"\"Test appropriate fields are not mutable.\"\"\"\n viewer = ViewerModel()\n\n # Check attribute lives on the viewer\n assert hasattr(viewer, field)\n # Check attribute does not have an event emitter\n assert not hasattr(viewer.events, field)\n\n # Check attribute is not settable\n with pytest.raises(TypeError) as err:\n setattr(viewer, field, 'test')\n\n assert 'has allow_mutation set to False and cannot be assigned' in str(\n err.value\n )\n\n\[email protected]('Layer, data, ndim', layer_test_data)\ndef test_status_tooltip(Layer, data, ndim):\n viewer = ViewerModel()\n viewer.tooltip.visible = True\n layer = Layer(data)\n viewer.layers.append(layer)\n viewer.cursor.position = (1,) * ndim\n viewer._on_cursor_position_change()\n\n\ndef test_viewer_object_event_sources():\n viewer = ViewerModel()\n assert viewer.cursor.events.source is viewer.cursor\n assert viewer.camera.events.source is viewer.camera\n\n\ndef test_open_or_get_error_multiple_readers(mock_npe2_pm, tmp_reader):\n \"\"\"Assert error is returned when multiple plugins are available to read.\"\"\"\n viewer = ViewerModel()\n\n tmp_reader(mock_npe2_pm, 'p1')\n tmp_reader(mock_npe2_pm, 'p2')\n\n with pytest.raises(\n MultipleReaderError, match='Multiple plugins found capable'\n ):\n viewer._open_or_raise_error(['my_file.fake'])\n\n\ndef test_open_or_get_error_no_plugin(mock_npe2_pm):\n \"\"\"Assert error is raised when no plugin is available.\"\"\"\n viewer = ViewerModel()\n\n with pytest.raises(\n NoAvailableReaderError, match='No plugin found capable of reading'\n ):\n viewer._open_or_raise_error(['my_file.fake'])\n\n\ndef test_open_or_get_error_builtins(mock_npe2_pm, tmp_path):\n \"\"\"Test builtins is available to read npy files.\"\"\"\n viewer = ViewerModel()\n\n f_pth = tmp_path / 'my-file.npy'\n data = np.random.random((10, 10))\n np.save(f_pth, data)\n\n added = viewer._open_or_raise_error([str(f_pth)])\n assert len(added) == 1\n layer = added[0]\n assert isinstance(layer, Image)\n np.testing.assert_allclose(layer.data, data)\n assert layer.source.reader_plugin == 'builtins'\n\n\ndef test_open_or_get_error_prefered_plugin(mock_npe2_pm, tmp_reader, tmp_path):\n \"\"\"Test plugin preference is respected.\"\"\"\n viewer = ViewerModel()\n pth = tmp_path / 'my-file.npy'\n np.save(pth, np.random.random((10, 10)))\n\n with restore_settings_on_exit():\n get_settings().plugins.extension2reader = {'*.npy': 'builtins'}\n\n tmp_reader(mock_npe2_pm, 'fake-reader', filename_patterns=['*.npy'])\n tmp_reader(\n mock_npe2_pm, 'other-fake-reader', filename_patterns=['*.npy']\n )\n\n added = viewer._open_or_raise_error([str(pth)])\n assert len(added) == 1\n assert added[0].source.reader_plugin == 'builtins'\n\n\ndef test_open_or_get_error_cant_find_plugin(mock_npe2_pm, tmp_reader):\n \"\"\"Test correct error message is returned when prefered plugin is missing.\"\"\"\n viewer = ViewerModel()\n\n with restore_settings_on_exit():\n get_settings().plugins.extension2reader = {'*.fake': 'fake-reader'}\n\n tmp_reader(mock_npe2_pm, 'other-fake-reader')\n\n with pytest.raises(\n MissingAssociatedReaderError, match=\"Can't find fake-reader plugin\"\n ):\n viewer._open_or_raise_error(['my_file.fake'])\n\n\ndef test_open_or_get_error_preferred_fails(tmp_path):\n viewer = ViewerModel()\n pth = tmp_path / 'my-file.npy'\n\n with restore_settings_on_exit():\n get_settings().plugins.extension2reader = {'.npy': 'napari'}\n\n with pytest.raises(\n ReaderPluginError, match='Tried opening with napari, but failed.'\n ):\n viewer._open_or_raise_error([str(pth)])\n"
]
| [
[
"numpy.testing.assert_equal",
"numpy.random.random",
"numpy.random.seed",
"numpy.may_share_memory",
"numpy.save",
"numpy.all",
"numpy.testing.assert_almost_equal",
"numpy.max",
"numpy.testing.assert_allclose",
"numpy.zeros",
"numpy.random.randint"
]
]
|
hpc0/simple-neural-network | [
"222b75d8dce3603941ea3d43b67643fa3d99d945"
]
| [
"snn/__init__.py"
]
| [
"#!/usr/bin/env python\r\n# coding: utf-8\r\nimport numpy as np\r\n\r\n# tasks\r\nREGRESSION = 0\r\nCLASSIFICATION = 1\r\n\r\n\r\n# activation functions\r\ndef sigmoid(x):\r\n return 1 / (1 + np.exp(-x))\r\n\r\n\r\ndef identity(x):\r\n return x\r\n\r\n\r\nclass Layer:\r\n def train(self, prev_z, task, target=np.array([]), loss=None, next_w=np.array([]), next_dL_da=np.array([]), lr=0.2):\r\n if next_dL_da.size == 0: # last layer\r\n # dL_dz = (self.z - target) / loss # for 'distance based' (pythagoras) loss\r\n dL_dz = self.z - target\r\n if task == REGRESSION:\r\n dz_da = 1\r\n else: # task == CLASSIFICATION\r\n dz_da = self.z * (1 - self.z)\r\n else:\r\n dL_dz = next_dL_da @ next_w\r\n dz_da = self.z * (1 - self.z)\r\n\r\n # dz_da = self.z * (1 - self.z)\r\n self.dL_da = dL_dz * dz_da\r\n self.dL_dw = (np.tile(prev_z, (len(self.dL_da), 1)).T * self.dL_da).T\r\n self.dL_db = self.dL_da\r\n\r\n self.delta_w = self.dL_dw * (-lr)\r\n self.delta_b = self.dL_db * (-lr)\r\n\r\n def apply_training(self):\r\n self.w += self.delta_w\r\n self.b += self.delta_b\r\n\r\n def eval(self, input_list, act_f):\r\n a = self.w @ input_list + self.b\r\n self.z = act_f(a)\r\n\r\n def __init__(self, n_neurons, n_input) -> None:\r\n super().__init__()\r\n self.w = np.random.rand(n_neurons, n_input) * 2 - 1\r\n self.b = np.random.rand(n_neurons) * 2 - 1\r\n\r\n\r\nclass SNN:\r\n def train(self, input_list, target, lr=0.2):\r\n self.eval(input_list)\r\n # self.loss = np.sqrt(np.sum((self.layers[-1].z - target) ** 2))\r\n self.loss = np.sum((self.layers[-1].z - target) ** 2)\r\n\r\n # train each layer\r\n # train(self, prev_a, target?, loss?, next_w?, next_dL_dz?)\r\n for i in range(len(self.layers) - 1, -1, -1):\r\n if i == 0:\r\n prev_z = input_list\r\n else:\r\n prev_z = self.layers[i - 1].z\r\n\r\n if i == len(self.layers) - 1:\r\n self.layers[i].train(prev_z, self.task, target, self.loss, lr=lr)\r\n else:\r\n self.layers[i].train(prev_z, self.task, next_w=self.layers[i + 1].w,\r\n next_dL_da=self.layers[i + 1].dL_da, lr=lr)\r\n\r\n def apply_training(self):\r\n for layer in self.layers:\r\n layer.apply_training()\r\n\r\n def eval(self, input_list):\r\n for i, layer in enumerate(self.layers):\r\n if self.task == REGRESSION and i == len(self.layers) - 1: # last layer in regression task\r\n act_f = identity # sigmoid function\r\n else:\r\n act_f = sigmoid # identity function\r\n\r\n if i == 0:\r\n layer.eval(input_list, act_f)\r\n else:\r\n layer.eval(self.layers[i - 1].z, act_f)\r\n return self.layers[-1].z\r\n\r\n def __init__(self, topology, n_input, task=REGRESSION) -> None:\r\n super().__init__()\r\n self.task = task\r\n self.layers = []\r\n self.dL_da = []\r\n self.dL_dw = []\r\n self.dL_db = []\r\n self.delta_w = []\r\n self.delta_b = []\r\n\r\n for i, n in enumerate(topology):\r\n if i == 0:\r\n self.layers.append(Layer(n, n_input))\r\n else:\r\n self.layers.append(Layer(n, topology[i - 1]))\r\n"
]
| [
[
"numpy.exp",
"numpy.random.rand",
"numpy.array",
"numpy.sum"
]
]
|
jvdgoltz/launcher_trajectory | [
"a65a321ef6148a698fbe844e31a82fa719a3b83e"
]
| [
"main.py"
]
| [
"#this programm simulates the flight of multistage rocket from lift-off to orbit insertion\r\n#input parameters are:\r\n\t#the empty mass of the rocket\r\n\t#the fuel mass of the rocket\r\n\t#the engine expansion ratio, exit area, chamber pressure, propellant molecular mass\r\n\t#the mass flow of the rocket engine\r\n\t#the drag coefficient of the rocket\r\n\t#the drag surface of the rocket\r\n#it is suggested that the input variables are taken out from a file that will be loaded in the beginning\r\n\r\n#the effects of wind and turbulences are neglected, as well as the rounded character of the earth and celestial effects\r\n\r\n#the result of the simulation are the graphs:\r\n\t#y-position vs x-position\r\n\t#y-position vs time\r\n\t#velocity vs time\r\n\t#acceleration vs time\r\n\t#dynamic pressure vs time\r\n #Mach number vs time\r\n\t\r\n#import all necessary funtions\r\nfrom math import sqrt, atan2, sin, cos, pi\r\nimport xlrd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport modules.aerodynamics as aero\r\nimport modules.thrust as th\r\nimport modules.controls as ctl\r\nimport modules.fdm as fdm\r\nimport modules.guidance as guid\r\nfrom modules.isatmos import press\r\n\r\nclass vehicle:\r\n def __init__(self,fm,epsilon,Tc,Mw,kappa,At,pc,pratio,\r\n cd,S,nengines):\r\n self.fm = fm\r\n self.epsilon = epsilon\r\n self.Tc = Tc\r\n self.Mw = Mw\r\n self.kappa = kappa\r\n self.At = At\r\n self.pc = pc\r\n self.pratio = pratio\r\n self.cd = cd\r\n self.S = S\r\n self.nengines = nengines\r\n\r\n#read out data source\r\n\r\n#filename=raw_input(\"Please enter the data source file name.\")\r\nfilename=\"launcher_data/Saturn5.xls\"\r\ntable = xlrd.open_workbook(filename)\r\nsheet = table.sheet_by_name('Sheet')\r\n\r\n#define rocket technical data lists\r\noem = []\r\nfm = []\r\nTc = []\r\npc = []\r\nepsilon = []\r\nMw = []\r\nkappa = []\r\nAe = []\r\nnengines = []\r\ncd = []\r\nS = []\r\nt_ctl = []\r\nsepdur = []\r\n\r\ndt = sheet.cell_value(3,1)\r\nmaxt = sheet.cell_value(4,1)\r\nnstages = int(sheet.cell_value(1,1))\r\npayld = sheet.cell_value(2,1)\r\ntargetalt = sheet.cell_value(5,1)\r\ntargetvel = sheet.cell_value(6,1)\r\nfor i in range(nstages):\r\n oem.append(sheet.cell_value(8,1+i))\r\n fm.append(sheet.cell_value(9,1+i))\r\n Tc.append(sheet.cell_value(10,1+i))\r\n pc.append(sheet.cell_value(11,1+i))\r\n epsilon.append(sheet.cell_value(12,1+i))\r\n Mw.append(sheet.cell_value(13,1+i))\r\n kappa.append(sheet.cell_value(14,1+i))\r\n Ae.append(sheet.cell_value(15,1+i))\r\n nengines.append(sheet.cell_value(16,1+i))\r\n cd.append(sheet.cell_value(17,1+i))\r\n S.append(sheet.cell_value(18,1+i))\r\n t_ctl.append(sheet.cell_value(19,1+i))\r\n sepdur.append(sheet.cell_value(20,1+i))\r\n\r\nAt = np.divide(Ae,epsilon)\r\npratio = nstages * [0]\r\nfor p in range(nstages):\r\n pratio[p] = th.pratio(epsilon[p],kappa[p])\r\n\r\nttab=[0]\r\nmtab=[sum(oem)+sum(fm)+payld]\r\nTtab=[0]\r\nDtab=[0]\r\nvtab=[0]\r\natab=[0]\r\nxtab=[0]\r\nytab=[0]\r\nthtab = [0]\r\nqtab=[0]\r\nMtab=[0]\r\nm = sum(oem)+sum(fm)+payld\r\nI = 1.\r\ncg = 0.\r\nt = 0\r\nx = 0.\r\ny = 0.\r\ntheta = 90.*np.pi/180\r\nvx = 0.\r\nvy = 0.\r\nth_dot = 0.\r\nax = 0.\r\nay = 0.\r\nth_ddot = 0.\r\ng0 = 9.81\r\nT = 0.\r\nM = 0.\r\nD = 0.\r\nq = 0.\r\nstate = np.array([x,y,theta,vx,vy,th_dot,ax,ay,th_ddot,m,I,cg,T,M,D,q,fm[0]])\r\nstartstage = []\r\nreference = targetalt\r\nfor i in range(nstages):\r\n print(\"Simulating stage:\",i+1)\r\n if i>0:\r\n fm[i-1]=0\r\n oem[i-1]=0\r\n state[9] = sum(oem)+sum(fm)+payld\r\n state[16] = fm[i]\r\n stage = vehicle(fm[i],epsilon[i],Tc[i],Mw[i],kappa[i],At[i],pc[i],pratio[i],cd[i],S[i],nengines[i])\r\n startstage.append(t)\r\n sep = False\r\n while y>=0 and t<2000 and not sep:\r\n t = t + dt\r\n ttab.append(t)\r\n\r\n throttle, T_angle, sep = ctl.control(state,reference)\r\n \r\n #A,B = fdm.linearize(stage,state,throttle,T_angle,dt)\r\n state = fdm.fdm(stage,state,throttle,T_angle,dt)\r\n y = state[1]\r\n fm[i] = state[16]\r\n \r\n mtab.append(state[9])\r\n xtab.append(state[0])\r\n ytab.append(y)\r\n Ttab.append(state[12])\r\n vtab.append(np.sqrt(state[3]**2+state[4]**2))\r\n qtab.append(state[15])\r\n thtab.append(state[2])\r\n atab.append(np.sqrt(state[6]**2+state[7]**2))\r\n Mtab.append(state[13])\r\n Dtab.append(state[14])\r\n\r\nttab = np.array(ttab)/60\r\nplt.subplot(331)\r\nplt.plot(ttab, np.array(ytab)/1000)\r\nplt.title(\"flight profile: altitude [km] vs time [min]\")\r\n\r\nplt.subplot(332)\r\nplt.plot(np.array(xtab)/1000, np.array(ytab)/1000, 'b')\r\nplt.title(\"flight profile: altitude [km] vs ground range [km]\")\r\n\r\nplt.subplot(338)\r\nplt.plot(ttab, np.array(Ttab)/1000000)\r\nplt.title(\"Thrust [MN] vs time [min]\")\r\n\r\nplt.subplot(334)\r\nplt.plot(ttab, np.array(vtab)/1000)\r\nplt.title(\"velocity [km/s] vs time [min]\")\r\n\r\nplt.subplot(336)\r\nplt.plot(ttab, np.array(qtab)/1000)\r\nplt.title(\"dynamic pressure [kPa] vs time [min]\")\r\n\r\nplt.subplot(335)\r\nplt.plot(ttab, np.array(thtab)*180/np.pi,'b')\r\nplt.title(\"pitch angle [deg] vs time [min]\")\r\n\r\nplt.subplot(337)\r\nplt.plot(ttab, np.array(atab)/g0+1)\r\nplt.title(\"acceleration [g0] vs time [min]\")\r\n\r\nplt.subplot(333)\r\nplt.plot(ttab, np.array(Mtab)) \r\nplt.title(\"Mach number [-] vs time [min]\")\r\n\r\nplt.subplot(339)\r\nplt.plot(ttab, np.array(Dtab)/1000) \r\nplt.title(\"Drag [kN] vs time [min]\")\r\n\r\nprint('Orbit Insertion Velocity: ', round(targetvel), 'm/s')\r\nprint('Horizontal Velocity: ', round(state[3]), 'm/s')\r\nprint('Vertical Veloctity: ', round(state[4]), 'm/s')\r\nprint('Orbit Height: ', round(state[1]/1000), 'km')\r\n\r\nplt.show()\r\n# Required Total Energy as function of orbit altitude\r\nmu = 398600.4418\r\nRe = 6371.0\r\nVmax = targetvel/1000\r\nhmax = targetalt/1000\r\nrid = np.linspace(Re,Re+hmax)\r\nVid = np.linspace(0,Vmax)\r\n[X, Y] = np.meshgrid(rid,Vid)\r\n\r\nEtot = Y**2/2-mu/X\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\nfrom matplotlib import cm\r\nfrom matplotlib.ticker import LinearLocator, FormatStrFormatter\r\n\r\nfig = plt.figure()\r\nax = fig.gca(projection='3d')\r\n\r\nsurf = ax.plot_surface(X, Y,Etot, rstride=1, cstride=1, cmap=cm.coolwarm,\r\n linewidth=0, antialiased=False)\r\nr = Re+np.array(ytab)/1000\r\nV = np.array(vtab)/1000\r\nEtot = V**2/2-mu/r\r\nax.plot(r,V,zs=Etot, zdir='z', label='zs=0, zdir=z')\r\nEtot = Vid**2/2-mu/rid\r\nax.plot(rid,Vid,zs=Etot)\r\n\r\n\r\nplt.show()\r\nprint(\"done\")"
]
| [
[
"numpy.sqrt",
"matplotlib.pyplot.title",
"numpy.linspace",
"numpy.meshgrid",
"matplotlib.pyplot.subplot",
"numpy.array",
"matplotlib.pyplot.show",
"numpy.divide",
"matplotlib.pyplot.figure"
]
]
|
kpedro88/koza4ok | [
"32eaad4c7f352c53c4455e89123585607d4f4f74"
]
| [
"examples/bdt_sklearn_to_tmva_AdaBoost.py"
]
| [
"from sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import AdaBoostClassifier\n\nfrom skTMVA import convert_bdt_sklearn_tmva\n\nimport cPickle\n\nimport numpy as np\nfrom numpy.random import RandomState\n\nRNG = RandomState(21)\n\n# Construct an example dataset for binary classification\nn_vars = 2\nn_events = 10000\nsignal = RNG.multivariate_normal(\n np.ones(n_vars), np.diag(np.ones(n_vars)), n_events)\nbackground = RNG.multivariate_normal(\n np.ones(n_vars) * -1, np.diag(np.ones(n_vars)), n_events)\nX = np.concatenate([signal, background])\ny = np.ones(X.shape[0])\nw = RNG.randint(1, 10, n_events * 2)\ny[signal.shape[0]:] *= -1\npermute = RNG.permutation(y.shape[0])\nX = X[permute]\ny = y[permute]\n\n# Use all dataset for training\nX_train, y_train, w_train = X, y, w\n\n# Declare BDT - we are going to use AdaBoost Decision Tree\ndt = DecisionTreeClassifier(max_depth=3,\n min_samples_leaf=int(0.05*len(X_train)))\nbdt = AdaBoostClassifier(dt,\n algorithm='SAMME',\n n_estimators=800,\n learning_rate=0.5)\n\n# Train BDT\nbdt.fit(X_train, y_train)\n\n# Save BDT to pickle file\nwith open('bdt_sklearn_to_tmva_example.pkl', 'wb') as fid:\n cPickle.dump(bdt, fid)\n\n\n# Save BDT to TMVA xml file \n# Note:\n# - declare input variable names and their type \n# - variable order is important for TMVA\nconvert_bdt_sklearn_tmva(bdt, [('var1', 'F'), ('var2', 'F')], 'bdt_sklearn_to_tmva_example.xml')\n\n"
]
| [
[
"numpy.concatenate",
"numpy.random.RandomState",
"sklearn.ensemble.AdaBoostClassifier",
"numpy.ones"
]
]
|
wadimiusz/hseling-repo-diachrony-webvectors | [
"5488d74141df360a6a721637ae7c7577136172d7"
]
| [
"hseling_lib_diachrony_webvectors/hseling_lib_diachrony_webvectors/utils/utils.py"
]
| [
"import os\nimport sys\nimport gensim\nimport numpy as np\nimport logging\nimport functools\n\n\ndef informative_output(words_and_scores, w2v1: gensim.models.KeyedVectors, w2v2: gensim.models.KeyedVectors,\n top_n_neighbors: int, model_name: str):\n print(model_name.center(40, '='))\n\n for word, score in words_and_scores:\n top_n_1 = [word for word, score in w2v1.most_similar(word, topn=top_n_neighbors)]\n top_n_2 = [word for word, score in w2v2.most_similar(word, topn=top_n_neighbors)]\n print(\"word {word} has score {score}\".format(word=word, score=score))\n print(\"word {word} has the following neighbors in model1:\".format(word=word))\n print(*top_n_1, sep=',')\n print('_' * 40)\n print(\"word {word} has the following neighbors in model2:\".format(word=word))\n print(*top_n_2, sep=',')\n print(\"\")\n\n\ndef simple_output(words_and_scores, model_name):\n print(model_name.center(40, '='))\n print(*[word for word, score in words_and_scores], sep='\\n')\n print('')\n\n\ndef log(message: str, end: str = '\\n'):\n \"\"\"Used for logging. use 2> /dev/null to swich off log messages\"\"\"\n sys.stderr.write(message+end)\n sys.stderr.flush()\n\n\ndef format_time(time: float):\n hours = int(time // 3600)\n minutes = int(time % 3600) // 60\n seconds = time % 60\n return \"{h}h {m}m {s:.2f}s\".format(h=hours,m=minutes,s=seconds)\n\n\ndef load_model(embeddings_file):\n \"\"\"\n This function, written by github.com/akutuzov, unifies various standards of word embedding files.\n It automatically determines the format by the file extension and loads it from the disk correspondingly.\n :param embeddings_file: path to the file\n :return: the loaded model\n \"\"\"\n logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)\n\n if not os.path.isfile(embeddings_file):\n raise FileNotFoundError(\"No file called {file}\".format(file=embeddings_file))\n # Determine the model format by the file extension\n if embeddings_file.endswith('.bin.gz') or embeddings_file.endswith('.bin'): # Binary word2vec file\n emb_model = gensim.models.KeyedVectors.load_word2vec_format(\n embeddings_file, binary=True, unicode_errors='replace')\n elif embeddings_file.endswith('.txt.gz') or embeddings_file.endswith('.txt') \\\n or embeddings_file.endswith('.vec.gz') or embeddings_file.endswith('.vec'): # Text word2vec file\n emb_model = gensim.models.KeyedVectors.load_word2vec_format(\n embeddings_file, binary=False, unicode_errors='replace')\n else: # Native Gensim format?\n emb_model = gensim.models.KeyedVectors.load(embeddings_file)\n emb_model.init_sims(replace=True)\n\n return emb_model\n\n\ndef intersection_align_gensim(m1: gensim.models.KeyedVectors, m2: gensim.models.KeyedVectors,\n pos_tag: (str, None) = None, words: (list, None) = None):\n \"\"\"\n This procedure, taken from https://gist.github.com/quadrismegistus/09a93e219a6ffc4f216fb85235535faf and slightly\n modified, corrects two models in a way that only the shared words of the vocabulary are kept in the model,\n and both vocabularies are sorted by frequencies.\n Original comment is as follows:\n\n Intersect two gensim word2vec models, m1 and m2.\n Only the shared vocabulary between them is kept.\n If 'words' is set (as list or set), then the vocabulary is intersected with this list as well.\n Indices are re-organized from 0..N in order of descending frequency (=sum of counts from both m1 and m2).\n These indices correspond to the new vectors and vectors_norm objects in both gensim models:\n -- so that Row 0 of m1.vectors will be for the same word as Row 0 of m2.vectors\n -- you can find the index of any word on the .index2word list: model.index2word.index(word) => 2\n The .vocab dictionary is also updated for each model, preserving the count but updating the index.\n\n :param m1: the first model\n :param m2: the second model\n :param pos_tag: if given, we remove words with other pos tags\n :param words: a container\n :return m1, m2: both models after their vocabs are modified\n \"\"\"\n\n # Get the vocab for each model\n if pos_tag is None:\n vocab_m1 = set(m1.vocab.keys())\n vocab_m2 = set(m2.vocab.keys())\n else:\n vocab_m1 = set(word for word in m1.vocab.keys() if word.endswith(\"_\" + pos_tag))\n vocab_m2 = set(word for word in m2.vocab.keys() if word.endswith(\"_\" + pos_tag))\n\n # Find the common vocabulary\n common_vocab = vocab_m1 & vocab_m2\n if words:\n common_vocab &= set(words)\n\n # If no alignment necessary because vocab is identical...\n if not vocab_m1-common_vocab and not vocab_m2-common_vocab:\n return m1, m2\n\n # Otherwise sort lexicographically\n common_vocab = list(common_vocab)\n common_vocab.sort()\n\n # Then for each model...\n for m in (m1, m2):\n # Replace old vectors_norm array with new one (with common vocab)\n indices = [m.vocab[w].index for w in common_vocab]\n old_arr = m.vectors_norm\n new_arr = np.array([old_arr[index] for index in indices])\n m.vectors_norm = m.vectors = new_arr\n\n # Replace old vocab dictionary with new one (with common vocab)\n # and old index2word with new one\n m.index2word = common_vocab\n old_vocab = m.vocab\n new_vocab = dict()\n for new_index, word in enumerate(common_vocab):\n old_vocab_obj = old_vocab[word]\n new_vocab[word] = gensim.models.word2vec.Vocab(index=new_index, count=old_vocab_obj.count)\n m.vocab = new_vocab\n\n return m1, m2\n"
]
| [
[
"numpy.array"
]
]
|
pjvazquez/yolact_edge | [
"b5d246732ffc414d79d6986aa65a4ca0d81cfe1c"
]
| [
"yolact.py"
]
| [
"import torch, torchvision\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torchvision.models.resnet import Bottleneck, conv1x1, conv3x3\nimport numpy as np\nfrom functools import partial\nfrom itertools import product, chain\nfrom math import sqrt\nfrom typing import List, Tuple, Optional\nfrom torch import Tensor\n\nfrom data.config import cfg, mask_type\nfrom layers import Detect\nfrom layers.interpolate import InterpolateModule\nfrom layers.warp_utils import deform_op\nfrom backbone import construct_backbone\n\nimport torch.backends.cudnn as cudnn\nfrom utils import timer\nfrom utils.functions import MovingAverage\n\nimport logging\nimport os\n\nimport copy\n\ntry:\n from torch2trt import torch2trt\n from torch2trt.torch2trt import TRTModule\n use_torch2trt = True\nexcept:\n use_torch2trt = False\n\n# This is required for Pytorch 1.0.1 on Windows to initialize Cuda on some driver versions.\n# See the bug report here: https://github.com/pytorch/pytorch/issues/17108\ntorch.cuda.current_device()\n\n# As of March 10, 2019, Pytorch DataParallel still doesn't support JIT Script Modules\nuse_jit = False if use_torch2trt else torch.cuda.device_count() <= 1\n\nScriptModuleWrapper = torch.jit.ScriptModule if use_jit else nn.Module\nscript_method_wrapper = torch.jit.script_method if use_jit else lambda fn, _rcn=None: fn\n\n\nclass Concat(nn.Module):\n def __init__(self, nets, extra_params):\n super().__init__()\n\n self.nets = nn.ModuleList(nets)\n self.extra_params = extra_params\n \n def forward(self, x):\n # Concat each along the channel dimension\n return torch.cat([net(x) for net in self.nets], dim=1, **self.extra_params)\n\n\ndef make_net(in_channels, conf, include_last_relu=True):\n \"\"\"\n A helper function to take a config setting and turn it into a network.\n Used by protonet and extrahead. Returns (network, out_channels)\n \"\"\"\n def make_layer(layer_cfg):\n nonlocal in_channels\n \n # Possible patterns:\n # ( 256, 3, {}) -> conv\n # ( 256,-2, {}) -> deconv\n # (None,-2, {}) -> bilinear interpolate\n # ('cat',[],{}) -> concat the subnetworks in the list\n #\n # You know it would have probably been simpler just to adopt a 'c' 'd' 'u' naming scheme.\n # Whatever, it's too late now.\n if isinstance(layer_cfg[0], str):\n layer_name = layer_cfg[0]\n\n if layer_name == 'cat':\n nets = [make_net(in_channels, x) for x in layer_cfg[1]]\n layer = Concat([net[0] for net in nets], layer_cfg[2])\n num_channels = sum([net[1] for net in nets])\n else:\n num_channels = layer_cfg[0]\n kernel_size = layer_cfg[1]\n\n if kernel_size > 0:\n layer = nn.Conv2d(in_channels, num_channels, kernel_size, **layer_cfg[2])\n else:\n if num_channels is None:\n layer = InterpolateModule(scale_factor=-kernel_size, mode='bilinear', align_corners=False, **layer_cfg[2])\n else:\n layer = nn.ConvTranspose2d(in_channels, num_channels, -kernel_size, **layer_cfg[2])\n \n in_channels = num_channels if num_channels is not None else in_channels\n\n # Don't return a ReLU layer if we're doing an upsample. This probably doesn't affect anything\n # output-wise, but there's no need to go through a ReLU here.\n # Commented out for backwards compatibility with previous models\n # if num_channels is None:\n # return [layer]\n # else:\n return [layer, nn.ReLU(inplace=True)]\n\n # Use sum to concat together all the component layer lists\n net = sum([make_layer(x) for x in conf], [])\n if not include_last_relu:\n net = net[:-1]\n\n return nn.Sequential(*(net)), in_channels\n\n\nclass PredictionModule(nn.Module):\n \"\"\"\n The (c) prediction module adapted from DSSD:\n https://arxiv.org/pdf/1701.06659.pdf\n\n Note that this is slightly different to the module in the paper\n because the Bottleneck block actually has a 3x3 convolution in\n the middle instead of a 1x1 convolution. Though, I really can't\n be arsed to implement it myself, and, who knows, this might be\n better.\n\n Args:\n - in_channels: The input feature size.\n - out_channels: The output feature size (must be a multiple of 4).\n - aspect_ratios: A list of lists of priorbox aspect ratios (one list per scale).\n - scales: A list of priorbox scales relative to this layer's convsize.\n For instance: If this layer has convouts of size 30x30 for\n an image of size 600x600, the 'default' (scale\n of 1) for this layer would produce bounding\n boxes with an area of 20x20px. If the scale is\n .5 on the other hand, this layer would consider\n bounding boxes with area 10x10px, etc.\n - parent: If parent is a PredictionModule, this module will use all the layers\n from parent instead of from this module.\n \"\"\"\n \n def __init__(self, in_channels, out_channels=1024, aspect_ratios=[[1]], scales=[1], parent=None, index=0):\n super().__init__()\n\n self.params = [in_channels, out_channels, aspect_ratios, scales, parent, index]\n\n self.num_classes = cfg.num_classes\n self.mask_dim = cfg.mask_dim\n self.num_priors = sum(len(x) for x in aspect_ratios)\n self.parent = [parent] # Don't include this in the state dict\n self.index = index\n\n if cfg.mask_proto_prototypes_as_features:\n in_channels += self.mask_dim\n \n if parent is None:\n if cfg.extra_head_net is None:\n out_channels = in_channels\n else:\n self.upfeature, out_channels = make_net(in_channels, cfg.extra_head_net)\n\n if cfg.use_prediction_module:\n self.block = Bottleneck(out_channels, out_channels // 4)\n self.conv = nn.Conv2d(out_channels, out_channels, kernel_size=1, bias=True)\n self.bn = nn.BatchNorm2d(out_channels)\n\n self.bbox_layer = nn.Conv2d(out_channels, self.num_priors * 4, **cfg.head_layer_params)\n self.conf_layer = nn.Conv2d(out_channels, self.num_priors * self.num_classes, **cfg.head_layer_params)\n self.mask_layer = nn.Conv2d(out_channels, self.num_priors * self.mask_dim, **cfg.head_layer_params)\n\n if cfg.use_instance_coeff:\n self.inst_layer = nn.Conv2d(out_channels, self.num_priors * cfg.num_instance_coeffs, **cfg.head_layer_params)\n \n # What is this ugly lambda doing in the middle of all this clean prediction module code?\n def make_extra(num_layers):\n if num_layers == 0:\n return lambda x: x\n else:\n # Looks more complicated than it is. This just creates an array of num_layers alternating conv-relu\n return nn.Sequential(*sum([[\n nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1),\n nn.ReLU(inplace=True)\n ] for _ in range(num_layers)], []))\n\n self.bbox_extra, self.conf_extra, self.mask_extra = [make_extra(x) for x in cfg.extra_layers]\n \n if cfg.mask_type == mask_type.lincomb and cfg.mask_proto_coeff_gate:\n self.gate_layer = nn.Conv2d(out_channels, self.num_priors * self.mask_dim, kernel_size=3, padding=1)\n\n self.aspect_ratios = aspect_ratios\n self.scales = scales\n\n self.priors = None\n self.last_conv_size = None\n\n def forward(self, x):\n \"\"\"\n Args:\n - x: The convOut from a layer in the backbone network\n Size: [batch_size, in_channels, conv_h, conv_w])\n\n Returns a tuple (bbox_coords, class_confs, mask_output, prior_boxes) with sizes\n - bbox_coords: [batch_size, conv_h*conv_w*num_priors, 4]\n - class_confs: [batch_size, conv_h*conv_w*num_priors, num_classes]\n - mask_output: [batch_size, conv_h*conv_w*num_priors, mask_dim]\n - prior_boxes: [conv_h*conv_w*num_priors, 4]\n \"\"\"\n # In case we want to use another module's layers\n src = self if self.parent[0] is None else self.parent[0]\n \n conv_h = x.size(2)\n conv_w = x.size(3)\n \n if cfg.extra_head_net is not None:\n x = src.upfeature(x)\n \n if cfg.use_prediction_module:\n # The two branches of PM design (c)\n a = src.block(x)\n \n b = src.conv(x)\n b = src.bn(b)\n b = F.relu(b)\n \n # TODO: Possibly switch this out for a product\n x = a + b\n\n bbox_x = src.bbox_extra(x)\n conf_x = src.conf_extra(x)\n mask_x = src.mask_extra(x)\n\n bbox = src.bbox_layer(bbox_x).permute(0, 2, 3, 1).contiguous().view(x.size(0), -1, 4)\n conf = src.conf_layer(conf_x).permute(0, 2, 3, 1).contiguous().view(x.size(0), -1, self.num_classes)\n\n if cfg.eval_mask_branch:\n mask = src.mask_layer(mask_x).permute(0, 2, 3, 1).contiguous().view(x.size(0), -1, self.mask_dim)\n else:\n mask = torch.zeros(x.size(0), bbox.size(1), self.mask_dim, device=bbox.device)\n\n if cfg.use_instance_coeff:\n inst = src.inst_layer(x).permute(0, 2, 3, 1).contiguous().view(x.size(0), -1, cfg.num_instance_coeffs)\n\n # See box_utils.decode for an explanation of this\n if cfg.use_yolo_regressors:\n bbox[:, :, :2] = torch.sigmoid(bbox[:, :, :2]) - 0.5\n bbox[:, :, 0] /= conv_w\n bbox[:, :, 1] /= conv_h\n\n if cfg.eval_mask_branch:\n if cfg.mask_type == mask_type.direct:\n mask = torch.sigmoid(mask)\n elif cfg.mask_type == mask_type.lincomb:\n mask = cfg.mask_proto_coeff_activation(mask)\n\n if cfg.mask_proto_coeff_gate:\n gate = src.gate_layer(x).permute(0, 2, 3, 1).contiguous().view(x.size(0), -1, self.mask_dim)\n mask = mask * torch.sigmoid(gate)\n \n priors = self.make_priors(conv_h, conv_w)\n\n preds = { 'loc': bbox, 'conf': conf, 'mask': mask, 'priors': priors }\n\n if cfg.use_instance_coeff:\n preds['inst'] = inst\n \n return preds\n \n def make_priors(self, conv_h, conv_w):\n \"\"\" Note that priors are [x,y,width,height] where (x,y) is the center of the box. \"\"\"\n \n with timer.env('makepriors'):\n if self.last_conv_size != (conv_w, conv_h):\n prior_data = []\n\n # Iteration order is important (it has to sync up with the convout)\n for j, i in product(range(conv_h), range(conv_w)):\n # +0.5 because priors are in center-size notation\n x = (i + 0.5) / conv_w\n y = (j + 0.5) / conv_h\n \n for scale, ars in zip(self.scales, self.aspect_ratios):\n for ar in ars:\n if not cfg.backbone.preapply_sqrt:\n ar = sqrt(ar)\n\n if cfg.backbone.use_pixel_scales:\n if type(cfg.max_size) == tuple:\n width, height = cfg.max_size\n w = scale * ar / width\n h = scale / ar / height\n else:\n w = scale * ar / cfg.max_size\n h = scale / ar / cfg.max_size\n else:\n w = scale * ar / conv_w\n h = scale / ar / conv_h\n \n # This is for backward compatability with a bug where I made everything square by accident\n if cfg.backbone.use_square_anchors:\n h = w\n\n prior_data += [x, y, w, h]\n \n self.priors = torch.Tensor(prior_data).view(-1, 4)\n self.last_conv_size = (conv_w, conv_h)\n \n return self.priors\n\n\nclass PredictionModuleTRT(PredictionModule):\n \n def __init__(self, in_channels, out_channels=1024, aspect_ratios=[[1]], scales=[1], parent=None, index=0):\n super().__init__(in_channels, out_channels, aspect_ratios, scales, parent, index)\n\n if cfg.mask_proto_coeff_activation == torch.tanh:\n self.activation_func = nn.Tanh()\n else:\n raise NotImplementedError\n\n def forward(self, x):\n \"\"\"\n Args:\n - x: The convOut from a layer in the backbone network\n Size: [batch_size, in_channels, conv_h, conv_w])\n\n Returns a tuple (bbox_coords, class_confs, mask_output, prior_boxes) with sizes\n - bbox_coords: [batch_size, conv_h*conv_w*num_priors, 4]\n - class_confs: [batch_size, conv_h*conv_w*num_priors, num_classes]\n - mask_output: [batch_size, conv_h*conv_w*num_priors, mask_dim]\n - prior_boxes: [conv_h*conv_w*num_priors, 4]\n \"\"\"\n \n conv_h = x.size(2)\n conv_w = x.size(3)\n \n if cfg.extra_head_net is not None:\n x = self.upfeature(x)\n \n if cfg.use_prediction_module:\n # The two branches of PM design (c)\n a = self.block(x)\n \n b = self.conv(x)\n b = self.bn(b)\n b = F.relu(b)\n \n # TODO: Possibly switch this out for a product\n x = a + b\n\n bbox_x = self.bbox_extra(x)\n conf_x = self.conf_extra(x)\n mask_x = self.mask_extra(x)\n\n bbox = self.bbox_layer(bbox_x).permute(0, 2, 3, 1).contiguous().view(x.size(0), -1, 4)\n conf = self.conf_layer(conf_x).permute(0, 2, 3, 1).contiguous().view(x.size(0), -1, self.num_classes)\n\n if cfg.eval_mask_branch:\n mask = self.mask_layer(mask_x).permute(0, 2, 3, 1).contiguous().view(x.size(0), -1, self.mask_dim)\n else:\n mask = torch.zeros(x.size(0), bbox.size(1), self.mask_dim, device=bbox.device)\n\n if cfg.use_instance_coeff:\n inst = self.inst_layer(x).permute(0, 2, 3, 1).contiguous().view(x.size(0), -1, cfg.num_instance_coeffs)\n raise NotImplementedError\n\n # See box_utils.decode for an explanation of this\n if cfg.use_yolo_regressors:\n bbox[:, :, :2] = torch.sigmoid(bbox[:, :, :2]) - 0.5\n bbox[:, :, 0] /= conv_w\n bbox[:, :, 1] /= conv_h\n\n if cfg.eval_mask_branch:\n if cfg.mask_type == mask_type.direct:\n mask = torch.sigmoid(mask)\n elif cfg.mask_type == mask_type.lincomb:\n mask = self.activation_func(mask)\n\n if cfg.mask_proto_coeff_gate:\n gate = self.gate_layer(x).permute(0, 2, 3, 1).contiguous().view(x.size(0), -1, self.mask_dim)\n mask = mask * torch.sigmoid(gate)\n\n return bbox, conf, mask\n\n\ndef conv_bn_lrelu(in_features, out_features, kernel_size=3, stride=1, padding=1, dilation=1, batch_norm=True):\n if batch_norm:\n return nn.Sequential(\n nn.Conv2d(in_features, out_features, kernel_size=kernel_size, stride=stride,\n padding=padding, dilation=dilation, bias=False),\n nn.BatchNorm2d(out_features),\n nn.LeakyReLU(0.1, inplace=True)\n )\n else:\n return nn.Sequential(\n nn.Conv2d(in_features, out_features, kernel_size=kernel_size, stride=stride,\n padding=padding, dilation=dilation, bias=True),\n nn.LeakyReLU(0.1, inplace=True)\n )\n\n\ndef deconv_no_relu(in_features, out_features):\n return nn.Sequential(\n nn.Upsample(scale_factor=2),\n nn.Conv2d(in_features, out_features, kernel_size=3, stride=1, padding=1, bias=False)\n )\n\n\ndef conv(batchNorm, in_planes, out_planes, kernel_size=3, stride=1):\n if batchNorm:\n return nn.Sequential(\n nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding=(kernel_size-1)//2, bias=False),\n nn.BatchNorm2d(out_planes),\n nn.LeakyReLU(0.1,inplace=True)\n )\n else:\n return nn.Sequential(\n nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding=(kernel_size-1)//2, bias=True),\n nn.LeakyReLU(0.1,inplace=True)\n )\n\n\ndef deconv(in_features, out_features):\n return nn.Sequential(\n deconv_no_relu(in_features, out_features),\n nn.LeakyReLU(0.1, inplace=True)\n )\n\n\ndef predict_flow(in_features):\n return nn.Conv2d(in_features, 2, kernel_size=3, stride=1, padding=1, bias=False)\n\n\ndef conv_bn_relu(in_features, out_features, kernel_size=3, stride=1, dilation=1):\n return nn.Sequential(\n nn.Conv2d(in_features, out_features, kernel_size=kernel_size, stride=stride, padding=dilation, dilation=dilation),\n nn.BatchNorm2d(out_features),\n nn.ReLU(inplace=True)\n )\n\n\ndef conv_relu(in_features, out_features, kernel_size=3, stride=1, dilation=1, groups=1):\n return nn.Sequential(\n nn.Conv2d(in_features, out_features, kernel_size=kernel_size, stride=stride, padding=dilation,\n dilation=dilation, groups=groups),\n nn.ReLU(inplace=True)\n )\n\n\ndef conv_only(in_features, out_features, kernel_size=3, stride=1, dilation=1, groups=1):\n return nn.Conv2d(in_features, out_features, kernel_size=kernel_size, stride=stride, padding=dilation,\n dilation=dilation, groups=groups)\n\n\ndef conv_lrelu(in_features, out_features, kernel_size=3, stride=1, dilation=1, groups=1):\n return nn.Sequential(\n nn.Conv2d(in_features, out_features, kernel_size=kernel_size, stride=stride, padding=dilation,\n dilation=dilation, groups=groups),\n nn.LeakyReLU(0.1, inplace=True)\n )\n\n\ndef conv_bn(in_features, out_features, kernel_size=3, stride=1, dilation=1):\n return nn.Sequential(\n nn.Conv2d(in_features, out_features, kernel_size=kernel_size, stride=stride, padding=dilation,\n dilation=dilation),\n nn.BatchNorm2d(out_features)\n )\n\n\ndef shuffle_cat(a, b):\n assert a.size() == b.size()\n n, c, h, w = a.size()\n a = a.permute(0, 2, 3, 1).contiguous().view(-1, c)\n b = b.permute(0, 2, 3, 1).contiguous().view(-1, c)\n x = torch.cat((a, b), dim=0).transpose(1, 0).contiguous()\n x = x.view(c * 2, n, h, w).permute(1, 0, 2, 3)\n return x\n\n\nclass Cat(nn.Module):\n def forward(self, a, b):\n x = torch.cat((a, b), dim=1)\n return x\n\n\nclass ShuffleCat(nn.Module):\n def forward(self, a, b):\n assert a.size() == b.size()\n n, c, h, w = a.size()\n a = a.permute(0, 2, 3, 1).contiguous().view(-1, c)\n b = b.permute(0, 2, 3, 1).contiguous().view(-1, c)\n x = torch.cat((a, b), dim=0).transpose(1, 0).contiguous()\n x = x.view(c * 2, n, h, w).permute(1, 0, 2, 3)\n return x\n\n\nclass ShuffleCatChunk(nn.Module):\n def forward(self, a, b):\n assert a.size() == b.size()\n n, c, h, w = a.size()\n a = torch.chunk(a, chunks=c, dim=1)\n b = torch.chunk(b, chunks=c, dim=1)\n x = [None] * (c * 2)\n x[::2] = a\n x[1::2] = b\n x = torch.cat(x, dim=1)\n return x\n\n\nclass ShuffleCatAlt(nn.Module):\n def forward(self, a, b):\n assert a.size() == b.size()\n n, c, h, w = a.size()\n x = torch.zeros(n, c*2, h, w, dtype=a.dtype, device=a.device)\n x[:, ::2] = a\n x[:, 1::2] = b\n return x\n\n\nclass FlowNetUnwrap(nn.Module):\n def forward(self, preds):\n outs: List[Tuple[torch.Tensor, torch.Tensor, torch.Tensor]] = []\n\n flow1, scale1, bias1, flow2, scale2, bias2, flow3, scale3, bias3 = preds\n\n outs.append((flow1, scale1, bias1))\n outs.append((flow2, scale2, bias2))\n outs.append((flow3, scale3, bias3))\n return outs\n\n\nclass FlowNetMiniTRTWrapper(nn.Module):\n def __init__(self, flow_net):\n super().__init__()\n self.flow_net = flow_net\n if cfg.flow.use_shuffle_cat:\n self.cat = ShuffleCat()\n else:\n self.cat = Cat()\n self.unwrap = FlowNetUnwrap()\n\n def forward(self, a, b):\n concat = self.cat(a, b)\n dummy_tensor = torch.tensor(0, dtype=a.dtype)\n preds = [dummy_tensor, dummy_tensor, dummy_tensor]\n preds_ = self.flow_net(concat)\n preds.extend(preds_)\n outs = self.unwrap(preds)\n return outs\n\n\nclass PredictionModuleTRTWrapper(nn.Module):\n def __init__(self, pred_layer):\n super().__init__()\n self.pred_layer = PredictionModuleTRT(*pred_layer.params[:-2], None, pred_layer.params[-1])\n\n pred_layer_w = pred_layer.parent[0] if pred_layer.parent[0] is not None else pred_layer\n self.pred_layer.load_state_dict(pred_layer_w.state_dict())\n\n def to_tensorrt(self, int8_mode=False, calibration_dataset=None, batch_size=1):\n if int8_mode:\n trt_fn = partial(torch2trt, int8_mode=True, int8_calib_dataset=calibration_dataset, strict_type_constraints=True, max_batch_size=batch_size)\n else:\n trt_fn = partial(torch2trt, fp16_mode=True, strict_type_constraints=True, max_batch_size=batch_size)\n\n input_sizes = [\n (1, 256, 69, 69),\n (1, 256, 35, 35),\n (1, 256, 18, 18),\n (1, 256, 9, 9),\n (1, 256, 5, 5),\n ]\n\n x = torch.ones(input_sizes[self.pred_layer.index]).cuda()\n self.pred_layer_torch = self.pred_layer\n self.pred_layer = trt_fn(self.pred_layer, [x])\n\n def forward(self, x):\n conv_h = x.size(2)\n conv_w = x.size(3)\n \n bbox, conf, mask = self.pred_layer(x)\n priors = self.pred_layer_torch.make_priors(conv_h, conv_w)\n \n preds = { 'loc': bbox, 'conf': conf, 'mask': mask, 'priors': priors }\n \n return preds\n\n\nclass NoReLUBottleneck(nn.Module):\n expansion = 4\n\n def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,\n base_width=64, dilation=1, norm_layer=None):\n super(NoReLUBottleneck, self).__init__()\n if norm_layer is None:\n norm_layer = nn.BatchNorm2d\n width = int(planes * (base_width / 64.)) * groups\n # Both self.conv2 and self.downsample layers downsample the input when stride != 1\n self.conv1 = conv1x1(inplanes, width)\n self.bn1 = norm_layer(width)\n self.conv2 = conv3x3(width, width, stride, groups, dilation)\n self.bn2 = norm_layer(width)\n self.conv3 = conv1x1(width, planes * self.expansion)\n self.bn3 = norm_layer(planes * self.expansion)\n self.relu = nn.ReLU(inplace=True)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n identity = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n out = self.relu(out)\n\n out = self.conv3(out)\n out = self.bn3(out)\n\n if self.downsample is not None:\n identity = self.downsample(x)\n\n out += identity\n\n return out\n\n\nclass FlowNetMiniPredLayer(nn.Module):\n def __init__(self, in_features):\n super().__init__()\n\n self.conv = nn.Conv2d(in_features, 2, kernel_size=3, padding=1, bias=False)\n self.scale = nn.Conv2d(in_features, cfg.fpn.num_features, kernel_size=1, padding=0, bias=True)\n self.bias = nn.Conv2d(in_features, cfg.fpn.num_features, kernel_size=1, padding=0, bias=True)\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d):\n nn.init.kaiming_normal_(m.weight.data, mode='fan_in')\n if m.bias is not None:\n m.bias.data.zero_()\n\n nn.init.constant_(self.scale.bias, 1)\n\n def forward(self, x):\n offset = self.conv(x)\n scale = self.scale(x)\n bias = self.bias(x)\n return offset, scale, bias\n\n\nclass FlowNetMiniPreConvs(ScriptModuleWrapper):\n def __init__(self, reduce_channels):\n super().__init__()\n\n last_in_channels = cfg.fpn.num_features\n convs = []\n for reduce_channel in reduce_channels:\n convs.append(conv_lrelu(last_in_channels, reduce_channel))\n \n self.convs = nn.Sequential(*convs)\n\n @script_method_wrapper\n def forward(self, x):\n return self.convs(x)\n\n\ndef build_flow_convs(encode_layers, in_features, out_features, stride=1, groups=1):\n conv = []\n conv.append(conv_lrelu(in_features, cfg.flow.encode_channels * encode_layers[0], groups=groups, stride=stride))\n for encode_idx, encode_layer in enumerate(encode_layers[:-1]):\n conv.append(conv_lrelu(cfg.flow.encode_channels * encode_layers[encode_idx], cfg.flow.encode_channels * encode_layers[encode_idx + 1], groups=groups))\n conv.append(conv_lrelu(cfg.flow.encode_channels * encode_layers[-1], out_features))\n return nn.Sequential(*conv)\n\n\nclass FlowNetMini(ScriptModuleWrapper):\n __constants__ = ['interpolation_mode', 'use_shuffle_cat', 'skip_flow']\n def __init__(self, in_features):\n super().__init__()\n self.interpolation_mode = cfg.fpn.interpolation_mode\n self.use_shuffle_cat = cfg.flow.use_shuffle_cat\n\n self.conv1 = build_flow_convs(cfg.flow.encode_layers[0], in_features, cfg.flow.encode_channels, groups=cfg.flow.num_groups)\n self.conv2 = build_flow_convs(cfg.flow.encode_layers[1], cfg.flow.encode_channels, cfg.flow.encode_channels * 2, stride=2)\n self.conv3 = build_flow_convs(cfg.flow.encode_layers[2], cfg.flow.encode_channels * 2, cfg.flow.encode_channels * 4, stride=2)\n\n self.pred3 = FlowNetMiniPredLayer(cfg.flow.encode_channels * 4)\n self.pred2 = FlowNetMiniPredLayer(cfg.flow.encode_channels * 4 + 2)\n self.pred1 = FlowNetMiniPredLayer(cfg.flow.encode_channels * 2 + 2)\n\n self.upfeat3 = nn.Conv2d(cfg.flow.encode_channels * 4, cfg.flow.encode_channels * 2,\n kernel_size=3, stride=1, padding=1, bias=False)\n self.upflow3 = nn.Conv2d(2, 2, kernel_size=3, stride=1, padding=1, bias=False)\n\n self.upfeat2 = nn.Conv2d(cfg.flow.encode_channels * 4 + 2, cfg.flow.encode_channels,\n kernel_size=3, stride=1, padding=1, bias=False)\n self.upflow2 = nn.Conv2d(2, 2, kernel_size=3, stride=1, padding=1, bias=False)\n\n self.skip_flow = not self.training and cfg.flow.flow_layer != 'top' and '3' not in cfg.flow.warp_layers\n\n for m in chain(*[x.modules() for x in (self.conv1, self.conv2, self.conv3)]):\n if isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d):\n nn.init.kaiming_normal_(m.weight.data, 0.1, mode='fan_in')\n if m.bias is not None:\n m.bias.data.zero_()\n\n @script_method_wrapper\n def forward(self, target_feat, source_feat):\n preds: List[Tuple[torch.Tensor, torch.Tensor, torch.Tensor]] = []\n\n if self.use_shuffle_cat:\n concat0 = shuffle_cat(target_feat, source_feat)\n else:\n concat0 = torch.cat((target_feat, source_feat), dim=1)\n\n out_conv1 = self.conv1(concat0)\n out_conv2 = self.conv2(out_conv1)\n out_conv3 = self.conv3(out_conv2)\n\n _, _, h2, w2 = out_conv2.size()\n\n flow3, scale3, bias3 = self.pred3(out_conv3)\n out_upfeat3 = F.interpolate(out_conv3, size=(h2, w2), mode=self.interpolation_mode, align_corners=False)\n out_upfeat3 = self.upfeat3(out_upfeat3)\n out_upflow3 = F.interpolate(flow3, size=(h2, w2), mode=self.interpolation_mode, align_corners=False)\n out_upflow3 = self.upflow3(out_upflow3)\n\n concat2 = torch.cat((out_conv2, out_upfeat3, out_upflow3), dim=1)\n flow2, scale2, bias2 = self.pred2(concat2)\n\n dummy_tensor = torch.tensor(0, dtype=out_conv2.dtype)\n\n if not self.skip_flow:\n _, _, h1, w1 = out_conv1.size()\n out_upfeat2 = F.interpolate(concat2, size=(h1, w1), mode=self.interpolation_mode, align_corners=False)\n out_upfeat2 = self.upfeat2(out_upfeat2)\n out_upflow2 = F.interpolate(flow2, size=(h1, w1), mode=self.interpolation_mode, align_corners=False)\n out_upflow2 = self.upflow2(out_upflow2)\n\n concat1 = torch.cat((out_conv1, out_upfeat2, out_upflow2), dim=1)\n flow1, scale1, bias1 = self.pred1(concat1)\n\n preds.append((flow1, scale1, bias1))\n else:\n preds.append((dummy_tensor, dummy_tensor, dummy_tensor))\n preds.append((flow2, scale2, bias2))\n preds.append((flow3, scale3, bias3))\n\n return preds\n\n\nclass FlowNetMiniTRT(ScriptModuleWrapper):\n __constants__ = ['interpolation_mode']\n def __init__(self, in_features):\n super().__init__()\n self.interpolation_mode = cfg.fpn.interpolation_mode\n self.in_features = in_features\n\n self.conv1 = build_flow_convs(cfg.flow.encode_layers[0], in_features, cfg.flow.encode_channels, groups=cfg.flow.num_groups)\n self.conv2 = build_flow_convs(cfg.flow.encode_layers[1], cfg.flow.encode_channels, cfg.flow.encode_channels * 2, stride=2)\n self.conv3 = build_flow_convs(cfg.flow.encode_layers[2], cfg.flow.encode_channels * 2, cfg.flow.encode_channels * 4, stride=2)\n\n self.pred3 = FlowNetMiniPredLayer(cfg.flow.encode_channels * 4)\n self.pred2 = FlowNetMiniPredLayer(cfg.flow.encode_channels * 4 + 2)\n self.pred1 = FlowNetMiniPredLayer(cfg.flow.encode_channels * 2 + 2)\n\n self.upfeat3 = nn.Conv2d(cfg.flow.encode_channels * 4, cfg.flow.encode_channels * 2,\n kernel_size=3, stride=1, padding=1, bias=False)\n self.upflow3 = nn.Conv2d(2, 2, kernel_size=3, stride=1, padding=1, bias=False)\n\n self.upfeat2 = nn.Conv2d(cfg.flow.encode_channels * 4 + 2, cfg.flow.encode_channels,\n kernel_size=3, stride=1, padding=1, bias=False)\n self.upflow2 = nn.Conv2d(2, 2, kernel_size=3, stride=1, padding=1, bias=False)\n\n for m in chain(*[x.modules() for x in (self.conv1, self.conv2, self.conv3)]):\n if isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d):\n nn.init.kaiming_normal_(m.weight.data, 0.1, mode='fan_in')\n if m.bias is not None:\n m.bias.data.zero_()\n\n @script_method_wrapper\n # def forward(self, target_feat, source_feat):\n def forward(self, concat0):\n # preds: List[Tuple[torch.Tensor, torch.Tensor, torch.Tensor]] = []\n preds = []\n\n # concat0 = shuffle_cat(target_feat, source_feat)\n\n out_conv1 = self.conv1(concat0)\n out_conv2 = self.conv2(out_conv1)\n out_conv3 = self.conv3(out_conv2)\n\n _, _, h2, w2 = out_conv2.size()\n\n flow3, scale3, bias3 = self.pred3(out_conv3)\n out_upfeat3 = F.interpolate(out_conv3, size=(h2, w2), mode=self.interpolation_mode, align_corners=False)\n out_upfeat3 = self.upfeat3(out_upfeat3)\n out_upflow3 = F.interpolate(flow3, size=(h2, w2), mode=self.interpolation_mode, align_corners=False)\n out_upflow3 = self.upflow3(out_upflow3)\n\n concat2 = torch.cat((out_conv2, out_upfeat3, out_upflow3), dim=1)\n flow2, scale2, bias2 = self.pred2(concat2)\n\n # out_upfeat2 = F.interpolate(concat2, size=(h1, w1), mode=self.interpolation_mode, align_corners=False)\n # out_upfeat2 = self.upfeat2(out_upfeat2)\n # out_upflow2 = F.interpolate(flow2, size=(h1, w1), mode=self.interpolation_mode, align_corners=False)\n # out_upflow2 = self.upflow2(out_upflow2)\n\n # concat1 = torch.cat((out_conv1, out_upfeat2, out_upflow2), dim=1)\n # flow1, scale1, bias1 = self.pred1(concat1)\n\n preds.extend((flow2, scale2, bias2))\n preds.extend((flow3, scale3, bias3))\n\n return preds\n\n\nclass SPA(ScriptModuleWrapper):\n __constants__ = ['interpolation_mode', 'use_normalized_spa']\n\n def __init__(self, num_layers):\n super().__init__()\n self.interpolation_mode = cfg.fpn.interpolation_mode\n self.use_normalized_spa = cfg.flow.use_normalized_spa\n\n self.refine_convs = nn.ModuleList([\n conv_lrelu(cfg.fpn.num_features * 2, cfg.fpn.num_features)\n for _ in range(num_layers - 1)\n ])\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d):\n nn.init.kaiming_normal_(m.weight.data, 0.1, mode='fan_in')\n if m.bias is not None:\n m.bias.data.zero_()\n\n @script_method_wrapper\n def forward(self, c3, f2, f3):\n fpn_outs = [f2, f3]\n out = []\n\n j = 0\n\n for refine in self.refine_convs:\n x = fpn_outs[j]\n _, _, h, w = x.size()\n c3 = F.interpolate(c3, size=(h, w), mode=self.interpolation_mode, align_corners=False)\n x_normalize = F.normalize(x, dim=1)\n c3_normalize = F.normalize(c3, dim=1)\n if self.use_normalized_spa:\n x = x + refine(torch.cat((x_normalize, c3_normalize), dim=1))\n else:\n x = x + refine(torch.cat((x, c3), dim=1))\n out.append(x)\n j += 1\n return out\n\n\nclass FPN_phase_1(ScriptModuleWrapper):\n __constants__ = ['interpolation_mode']\n\n def __init__(self, in_channels):\n super().__init__()\n\n self.src_channels = in_channels\n\n self.lat_layers = nn.ModuleList([\n nn.Conv2d(x, cfg.fpn.num_features, kernel_size=1)\n for x in reversed(in_channels)\n ])\n\n self.interpolation_mode = cfg.fpn.interpolation_mode\n\n @script_method_wrapper\n def forward(self, x1=None, x2=None, x3=None, x4=None, x5=None, x6=None, x7=None):\n # type: (Optional[Tensor], Optional[Tensor], Optional[Tensor], Optional[Tensor], Optional[Tensor], Optional[Tensor], Optional[Tensor]) -> List[Tensor]\n \"\"\"\n Args:\n - convouts (list): A list of convouts for the corresponding layers in in_channels.\n Returns:\n - A list of FPN convouts in the same order as x with extra downsample layers if requested.\n \"\"\"\n\n convouts_ = [x1, x2, x3, x4, x5, x6, x7]\n # convouts = [x for x in convouts if x is not None]\n convouts = []\n j = 0\n while j < len(convouts_):\n t = convouts_[j]\n if t is not None:\n convouts.append(t)\n j += 1\n\n out = []\n lat_feats = []\n x = torch.zeros(1, device=convouts[0].device)\n for i in range(len(convouts)):\n out.append(x)\n lat_feats.append(x)\n\n # For backward compatability, the conv layers are stored in reverse but the input and output is\n # given in the correct order. Thus, use j=-i-1 for the input and output and i for the conv layers.\n j = len(convouts)\n for lat_layer in self.lat_layers:\n j -= 1\n\n if j < len(convouts) - 1:\n _, _, h, w = convouts[j].size()\n x = F.interpolate(x, size=(h, w), mode=self.interpolation_mode, align_corners=False)\n lat_j = lat_layer(convouts[j])\n lat_feats[j] = lat_j\n x = x + lat_j\n out[j] = x\n \n for i in range(len(convouts)):\n out.append(lat_feats[i])\n return out\n\n\nclass FPN_phase_2(ScriptModuleWrapper):\n __constants__ = ['num_downsample', 'use_conv_downsample']\n\n def __init__(self, in_channels):\n super().__init__()\n\n self.src_channels = in_channels\n\n # This is here for backwards compatability\n padding = 1 if cfg.fpn.pad else 0\n self.pred_layers = nn.ModuleList([\n nn.Conv2d(cfg.fpn.num_features, cfg.fpn.num_features, kernel_size=3, padding=padding)\n for _ in in_channels\n ])\n\n if cfg.fpn.use_conv_downsample:\n self.downsample_layers = nn.ModuleList([\n nn.Conv2d(cfg.fpn.num_features, cfg.fpn.num_features, kernel_size=3, padding=1, stride=2)\n for _ in range(cfg.fpn.num_downsample)\n ])\n\n self.num_downsample = cfg.fpn.num_downsample\n self.use_conv_downsample = cfg.fpn.use_conv_downsample\n\n @script_method_wrapper\n def forward(self, x1=None, x2=None, x3=None, x4=None, x5=None, x6=None, x7=None):\n # type: (Optional[Tensor], Optional[Tensor], Optional[Tensor], Optional[Tensor], Optional[Tensor], Optional[Tensor], Optional[Tensor]) -> List[Tensor]\n \"\"\"\n Args:\n - convouts (list): A list of convouts for the corresponding layers in in_channels.\n Returns:\n - A list of FPN convouts in the same order as x with extra downsample layers if requested.\n \"\"\"\n\n # out = [x1, x2, x3, x4, x5, x6, x7]\n # out = [x for x in out if x is not None]\n\n out_ = [x1, x2, x3, x4, x5, x6, x7]\n out = []\n j = 0\n while j < len(out_):\n t = out_[j]\n if t is not None:\n out.append(t)\n j += 1\n\n len_convouts = len(out)\n\n j = len_convouts\n for pred_layer in self.pred_layers:\n j -= 1\n out[j] = F.relu(pred_layer(out[j]))\n\n # In the original paper, this takes care of P6\n if self.use_conv_downsample:\n for downsample_layer in self.downsample_layers:\n out.append(downsample_layer(out[-1]))\n else:\n for idx in range(self.num_downsample):\n # Note: this is an untested alternative to out.append(out[-1][:, :, ::2, ::2]). Thanks TorchScript.\n out.append(nn.functional.max_pool2d(out[-1], 1, stride=2))\n\n return out\n\n\nclass FPN(ScriptModuleWrapper):\n \"\"\"\n Implements a general version of the FPN introduced in\n https://arxiv.org/pdf/1612.03144.pdf\n\n Parameters (in cfg.fpn):\n - num_features (int): The number of output features in the fpn layers.\n - interpolation_mode (str): The mode to pass to F.interpolate.\n - num_downsample (int): The number of downsampled layers to add onto the selected layers.\n These extra layers are downsampled from the last selected layer.\n\n Args:\n - in_channels (list): For each conv layer you supply in the forward pass,\n how many features will it have?\n \"\"\"\n __constants__ = ['interpolation_mode', 'num_downsample', 'use_conv_downsample']\n\n def __init__(self, in_channels):\n super().__init__()\n\n self.lat_layers = nn.ModuleList([\n nn.Conv2d(x, cfg.fpn.num_features, kernel_size=1)\n for x in reversed(in_channels)\n ])\n\n # This is here for backwards compatability\n padding = 1 if cfg.fpn.pad else 0\n self.pred_layers = nn.ModuleList([\n nn.Conv2d(cfg.fpn.num_features, cfg.fpn.num_features, kernel_size=3, padding=padding)\n for _ in in_channels\n ])\n\n if cfg.fpn.use_conv_downsample:\n self.downsample_layers = nn.ModuleList([\n nn.Conv2d(cfg.fpn.num_features, cfg.fpn.num_features, kernel_size=3, padding=1, stride=2)\n for _ in range(cfg.fpn.num_downsample)\n ])\n \n self.interpolation_mode = cfg.fpn.interpolation_mode\n self.num_downsample = cfg.fpn.num_downsample\n self.use_conv_downsample = cfg.fpn.use_conv_downsample\n\n @script_method_wrapper\n def forward(self, convouts:List[torch.Tensor]):\n \"\"\"\n Args:\n - convouts (list): A list of convouts for the corresponding layers in in_channels.\n Returns:\n - A list of FPN convouts in the same order as x with extra downsample layers if requested.\n \"\"\"\n\n out = []\n x = torch.zeros(1, device=convouts[0].device)\n for i in range(len(convouts)):\n out.append(x)\n\n # For backward compatability, the conv layers are stored in reverse but the input and output is\n # given in the correct order. Thus, use j=-i-1 for the input and output and i for the conv layers.\n j = len(convouts)\n for lat_layer in self.lat_layers:\n j -= 1\n\n if j < len(convouts) - 1:\n _, _, h, w = convouts[j].size()\n x = F.interpolate(x, size=(h, w), mode=self.interpolation_mode, align_corners=False)\n x = x + lat_layer(convouts[j])\n out[j] = x\n\n # This janky second loop is here because TorchScript.\n j = len(convouts)\n for pred_layer in self.pred_layers:\n j -= 1\n out[j] = F.relu(pred_layer(out[j]))\n\n # In the original paper, this takes care of P6\n if self.use_conv_downsample:\n for downsample_layer in self.downsample_layers:\n out.append(downsample_layer(out[-1]))\n else:\n for idx in range(self.num_downsample):\n # Note: this is an untested alternative to out.append(out[-1][:, :, ::2, ::2]). Thanks TorchScript.\n out.append(nn.functional.max_pool2d(out[-1], 1, stride=2))\n\n return out\n\n\nclass Yolact(nn.Module):\n \"\"\"\n\n\n ██╗ ██╗ ██████╗ ██╗ █████╗ ██████╗████████╗\n ╚██╗ ██╔╝██╔═══██╗██║ ██╔══██╗██╔════╝╚══██╔══╝\n ╚████╔╝ ██║ ██║██║ ███████║██║ ██║ \n ╚██╔╝ ██║ ██║██║ ██╔══██║██║ ██║ \n ██║ ╚██████╔╝███████╗██║ ██║╚██████╗ ██║ \n ╚═╝ ╚═════╝ ╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚═╝ \n\n\n You can set the arguments by chainging them in the backbone config object in config.py.\n\n Parameters (in cfg.backbone):\n - selected_layers: The indices of the conv layers to use for prediction.\n - pred_scales: A list with len(selected_layers) containing tuples of scales (see PredictionModule)\n - pred_aspect_ratios: A list of lists of aspect ratios with len(selected_layers) (see PredictionModule)\n \"\"\"\n\n def __init__(self, training=True):\n super().__init__()\n\n self.backbone = construct_backbone(cfg.backbone)\n\n self.training = training\n\n if cfg.freeze_bn:\n self.freeze_bn()\n\n # Compute mask_dim here and add it back to the config. Make sure Yolact's constructor is called early!\n if cfg.mask_type == mask_type.direct:\n cfg.mask_dim = cfg.mask_size**2\n elif cfg.mask_type == mask_type.lincomb:\n if cfg.mask_proto_use_grid:\n self.grid = torch.Tensor(np.load(cfg.mask_proto_grid_file))\n self.num_grids = self.grid.size(0)\n else:\n self.num_grids = 0\n\n self.proto_src = cfg.mask_proto_src\n \n if self.proto_src is None: in_channels = 3\n elif cfg.fpn is not None: in_channels = cfg.fpn.num_features\n else: in_channels = self.backbone.channels[self.proto_src]\n in_channels += self.num_grids\n\n # The include_last_relu=false here is because we might want to change it to another function\n self.proto_net, cfg.mask_dim = make_net(in_channels, cfg.mask_proto_net, include_last_relu=False)\n\n if cfg.mask_proto_bias:\n cfg.mask_dim += 1\n\n\n self.selected_layers = cfg.backbone.selected_layers\n src_channels = self.backbone.channels\n\n if cfg.fpn is not None:\n # Some hacky rewiring to accomodate the FPN\n if cfg.flow is not None:\n self.fpn_phase_1 = FPN_phase_1([src_channels[i] for i in self.selected_layers])\n self.fpn_phase_2 = FPN_phase_2([src_channels[i] for i in self.selected_layers])\n if cfg.flow.use_spa:\n self.spa = SPA(len(self.selected_layers))\n if cfg.flow.warp_mode == 'flow':\n if cfg.flow.model == 'mini':\n lateral_channels = cfg.fpn.num_features\n if len(cfg.flow.reduce_channels) > 0:\n lateral_channels = cfg.flow.reduce_channels[-1]\n self.flow_net_pre_convs = FlowNetMiniPreConvs(cfg.flow.reduce_channels)\n # Only use TRT version of FlowNetMini during evaluation and when TensorRT conversion is enforced.\n if not training and (cfg.torch2trt_flow_net or cfg.torch2trt_flow_net_int8):\n self.flow_net = FlowNetMiniTRT(lateral_channels * 2)\n else:\n self.flow_net = FlowNetMini(lateral_channels * 2)\n else:\n raise NotImplementedError\n self.selected_layers = list(range(len(self.selected_layers) + cfg.fpn.num_downsample))\n else:\n self.fpn = FPN([src_channels[i] for i in self.selected_layers])\n self.selected_layers = list(range(len(self.selected_layers) + cfg.fpn.num_downsample))\n src_channels = [cfg.fpn.num_features] * len(self.selected_layers)\n\n self.prediction_layers = nn.ModuleList()\n\n for idx, layer_idx in enumerate(self.selected_layers):\n # If we're sharing prediction module weights, have every module's parent be the first one\n parent = None\n if cfg.share_prediction_module and idx > 0:\n parent = self.prediction_layers[0]\n\n pred = PredictionModule(src_channels[layer_idx], src_channels[layer_idx],\n aspect_ratios = cfg.backbone.pred_aspect_ratios[idx],\n scales = cfg.backbone.pred_scales[idx],\n parent = parent,\n index = idx)\n self.prediction_layers.append(pred)\n\n # Extra parameters for the extra losses\n if cfg.use_class_existence_loss:\n # This comes from the smallest layer selected\n # Also note that cfg.num_classes includes background\n self.class_existence_fc = nn.Linear(src_channels[-1], cfg.num_classes - 1)\n \n if cfg.use_semantic_segmentation_loss:\n self.semantic_seg_conv = nn.Conv2d(src_channels[0], cfg.num_classes-1, kernel_size=1)\n\n # For use in evaluation\n self.detect = Detect(cfg.num_classes, bkg_label=0, top_k=200, conf_thresh=0.05, nms_thresh=0.5)\n\n def save_weights(self, path):\n \"\"\" Saves the model's weights using compression because the file sizes were getting too big. \"\"\"\n torch.save(self.state_dict(), path)\n \n def load_weights(self, path, args=None):\n \"\"\" Loads weights from a compressed save file. \"\"\"\n state_dict = torch.load(path, map_location='cpu')\n\n # Get all possible weights\n cur_state_dict = self.state_dict()\n\n if args is not None and args.drop_weights is not None:\n drop_weight_keys = args.drop_weights.split(',')\n \n transfered_from_yolact = False\n\n for key in list(state_dict.keys()):\n # For backward compatability, remove these (the new variable is called layers)\n if key.startswith('backbone.layer') and not key.startswith('backbone.layers'):\n del state_dict[key]\n \n # Also for backward compatibility with v1.0 weights, do this check\n if key.startswith('fpn.downsample_layers.'):\n if cfg.fpn is not None and int(key.split('.')[2]) >= cfg.fpn.num_downsample:\n del state_dict[key]\n\n if args is not None and args.drop_weights is not None:\n for drop_key in drop_weight_keys:\n if key.startswith(drop_key):\n del state_dict[key]\n\n if key.startswith('fpn.lat_layers'):\n transfered_from_yolact = True\n state_dict[key.replace('fpn.', 'fpn_phase_1.')] = state_dict[key]\n del state_dict[key]\n elif key.startswith('fpn.') and key in state_dict:\n transfered_from_yolact = True\n state_dict[key.replace('fpn.', 'fpn_phase_2.')] = state_dict[key]\n del state_dict[key]\n\n keys_not_exist = []\n keys_not_used = []\n keys_mismatch = []\n\n for key in list(cur_state_dict.keys()):\n if args is not None and args.drop_weights is not None:\n for drop_key in drop_weight_keys:\n if key.startswith(drop_key):\n state_dict[key] = cur_state_dict[key]\n\n # for compatibility with models without existing modules\n if key not in state_dict:\n keys_not_exist.append(key)\n state_dict[key] = cur_state_dict[key]\n else:\n # check key size mismatches\n if state_dict[key].size() != cur_state_dict[key].size():\n keys_mismatch.append(key)\n state_dict[key] = cur_state_dict[key]\n\n\n # for compatibility with models with simpler architectures, remove unused weights.\n for key in list(state_dict.keys()):\n if key not in cur_state_dict:\n keys_not_used.append(key)\n del state_dict[key]\n\n logger = logging.getLogger(\"yolact.model.load\")\n if len(keys_not_used) > 0:\n logger.warning(\"Some parameters in the checkpoint are not used: {}\".format(\", \".join(keys_not_used)))\n if len(keys_not_exist) > 0:\n logger.warning(\"Some parameters required by the model do not exist in the checkpoint, \"\n \"and are initialized as they should be: {}\".format(\", \".join(keys_not_exist)))\n if len(keys_mismatch) > 0:\n logger.warning(\"Some parameters in the checkpoint have a different shape in the current model, \"\n \"and are initialized as they should be: {}\".format(\", \".join(keys_mismatch)))\n\n if args is not None and (args.coco_transfer or args.yolact_transfer):\n logger.warning(\"`--coco_transfer` or `--yolact_transfer` is no longer needed. The code will automatically detect and convert YOLACT-trained weights now.\")\n\n self.load_state_dict(state_dict)\n\n if not self.training:\n self.create_partial_backbone()\n if cfg.torch2trt_flow_net or cfg.torch2trt_flow_net_int8:\n self.create_embed_flow_net()\n\n def init_weights(self, backbone_path):\n \"\"\" Initialize weights for training. \"\"\"\n # Initialize the backbone with the pretrained weights.\n self.backbone.init_backbone(backbone_path)\n\n conv_constants = getattr(nn.Conv2d(1, 1, 1), '__constants__')\n \n # Quick lambda to test if one list contains the other\n def all_in(x, y):\n for _x in x:\n if _x not in y:\n return False\n return True\n\n # Initialize the rest of the conv layers with xavier\n for name, module in self.named_modules():\n # See issue #127 for why we need such a complicated condition if the module is a WeakScriptModuleProxy\n # Broke in 1.3 (see issue #175), WeakScriptModuleProxy was turned into just ScriptModule.\n # Broke in 1.4 (see issue #292), where RecursiveScriptModule is the new star of the show.\n # Note that this might break with future pytorch updates, so let me know if it does\n is_script_conv = False\n if 'Script' in type(module).__name__:\n # 1.4 workaround: now there's an original_name member so just use that\n if hasattr(module, 'original_name'):\n is_script_conv = 'Conv' in module.original_name\n # 1.3 workaround: check if this has the same constants as a conv module\n else:\n is_script_conv = (\n all_in(module.__dict__['_constants_set'], conv_constants)\n and all_in(conv_constants, module.__dict__['_constants_set']))\n \n is_conv_layer = isinstance(module, nn.Conv2d) or is_script_conv\n \n if is_conv_layer and module not in self.backbone.backbone_modules:\n nn.init.xavier_uniform_(module.weight.data)\n \n if module.bias is not None:\n if cfg.use_focal_loss and 'conf_layer' in name:\n if not cfg.use_sigmoid_focal_loss:\n # Initialize the last layer as in the focal loss paper.\n # Because we use softmax and not sigmoid, I had to derive an alternate expression\n # on a notecard. Define pi to be the probability of outputting a foreground detection.\n # Then let z = sum(exp(x)) - exp(x_0). Finally let c be the number of foreground classes.\n # Chugging through the math, this gives us\n # x_0 = log(z * (1 - pi) / pi) where 0 is the background class\n # x_i = log(z / c) for all i > 0\n # For simplicity (and because we have a degree of freedom here), set z = 1. Then we have\n # x_0 = log((1 - pi) / pi) note: don't split up the log for numerical stability\n # x_i = -log(c) for all i > 0\n module.bias.data[0] = np.log((1 - cfg.focal_loss_init_pi) / cfg.focal_loss_init_pi)\n module.bias.data[1:] = -np.log(module.bias.size(0) - 1)\n else:\n module.bias.data[0] = -np.log(cfg.focal_loss_init_pi / (1 - cfg.focal_loss_init_pi))\n module.bias.data[1:] = -np.log((1 - cfg.focal_loss_init_pi) / cfg.focal_loss_init_pi)\n else:\n module.bias.data.zero_()\n\n def train(self, mode=True):\n super().train(mode)\n\n if cfg.freeze_bn:\n self.freeze_bn()\n\n if not mode:\n return\n \n if cfg.flow is not None and cfg.flow.fine_tune_layers is not None:\n self.fine_tune_layers()\n\n def freeze_bn(self):\n \"\"\" Adapted from https://discuss.pytorch.org/t/how-to-train-with-frozen-batchnorm/12106/8 \"\"\"\n for module in self.modules():\n if isinstance(module, nn.BatchNorm2d):\n module.eval()\n\n module.weight.requires_grad = False\n module.bias.requires_grad = False\n\n def fine_tune_layers(self):\n fine_tune_layers = cfg.flow.fine_tune_layers\n freeze_or_ft = fine_tune_layers[0] == '-'\n if freeze_or_ft:\n fine_tune_layers = fine_tune_layers[1:]\n fine_tune_layer_names = fine_tune_layers.split(',')\n logger = logging.getLogger(\"yolact.train\")\n freeze_layers = []\n fine_tune_layers = []\n for name, module in self.named_children():\n name_in_list = name in fine_tune_layer_names\n if name_in_list == freeze_or_ft:\n freeze_layers.append(name)\n module.eval()\n for param in module.parameters():\n param.requires_grad = False\n else:\n fine_tune_layers.append(name)\n logger.info(\"Fine tuning weights of modules: {}\".format(\", \".join(fine_tune_layers)))\n logger.info(\"Freezing weights of modules: {}\".format(\", \".join(freeze_layers)))\n\n def extra_loss(self, net_outs, gt_net_outs):\n losses = {}\n\n # feature matching loss\n if cfg.flow.feature_matching_loss is not None:\n def t(fea, layer_idx):\n fpn_net = self.fpn_phase_2\n pred_layer = fpn_net.pred_layers[layer_idx + 1]\n bias = pred_layer.bias.detach() if pred_layer.bias is not None else None\n fea = F.relu(F.conv2d(fea, weight=pred_layer.weight.detach(), bias=bias, stride=pred_layer.stride,\n padding=pred_layer.padding))\n return fea\n\n assert cfg.flow.fm_loss_loc in (\"L\", \"P\", \"L+P\")\n loss_W = 0\n # reverse the direction of outs_phase_1 to make resolution order match flow prediction\n\n pairs = []\n\n gt_outs_fpn = gt_net_outs[\"outs_phase_1\"][1:]\n preds_outs_fpn = [net_outs[\"outs_phase_1\"][1:]]\n if net_outs.get(\"direct_transform\", None):\n preds_outs_fpn.append(net_outs[\"direct_transform\"])\n for pred_outs_fpn in preds_outs_fpn:\n for layer_idx in range(2):\n FPN_GTs = gt_outs_fpn[layer_idx]\n FPN_preds = pred_outs_fpn[layer_idx]\n if cfg.flow.fm_loss_loc != \"P\":\n pairs.append((FPN_GTs, FPN_preds, ))\n if cfg.flow.fm_loss_loc != \"L\":\n pairs.append((t(FPN_GTs, layer_idx), t(FPN_preds, layer_idx), ))\n\n for FPN_GTs, FPN_preds in pairs:\n n_, c_ = FPN_preds.size()[:2]\n if cfg.flow.feature_matching_loss == 'SmoothL1':\n level_loss = F.smooth_l1_loss(FPN_preds, FPN_GTs, reduction=\"sum\")\n level_loss = level_loss / n_ / c_\n elif cfg.flow.feature_matching_loss == 'cosine':\n level_loss = F.cosine_similarity(FPN_preds, FPN_GTs)\n level_loss = (1 - level_loss).mean()\n else:\n raise NotImplementedError\n loss_W += level_loss\n\n loss_W /= len(pairs)\n losses['W'] = loss_W * cfg.flow.fm_loss_alpha\n return losses\n\n def forward_flow(self, extras):\n imgs_1, imgs_2 = extras\n\n if cfg.flow.model == 'mini':\n feas_1 = self.backbone(imgs_1, partial=True)\n feas_2 = self.backbone(imgs_2, partial=True)\n\n fea_1 = feas_1[-1].detach()\n fea_2 = feas_2[-1].detach()\n\n src_lat_layer = self.fpn_phase_1.lat_layers[-1]\n src_lat_1 = src_lat_layer(fea_1).detach()\n src_lat_2 = src_lat_layer(fea_2).detach()\n\n src_lat_1 = self.flow_net_pre_convs(src_lat_1)\n src_lat_2 = self.flow_net_pre_convs(src_lat_2)\n\n preds_flow = self.flow_net(src_lat_1, src_lat_2)\n preds_flow = [pred[0] for pred in preds_flow]\n\n else:\n raise NotImplementedError\n\n return preds_flow\n\n def create_embed_flow_net(self):\n if hasattr(self, \"flow_net\"):\n self.flow_net = FlowNetMiniTRTWrapper(self.flow_net)\n\n def create_partial_backbone(self):\n if cfg.flow.warp_mode == 'none':\n return\n\n logger = logging.getLogger(\"yolact.model.load\")\n logger.debug(\"Creating partial backbone...\")\n\n backbone = construct_backbone(cfg.backbone)\n backbone.load_state_dict(self.backbone.state_dict())\n backbone.layers = backbone.layers[:2]\n\n self.partial_backbone = backbone\n logger.debug(\"Partial backbone created...\")\n \n def _get_trt_cache_path(self, module_name, int8_mode=False, batch_size=1):\n return \"{}.{}{}{}.trt\".format(self.model_path, module_name, \".int8_{}\".format(cfg.torch2trt_max_calibration_images) if int8_mode else \"\", \"_bs_{}\".format(batch_size))\n\n def has_trt_cached_module(self, module_name, int8_mode=False, batch_size=1):\n module_path = self._get_trt_cache_path(module_name, int8_mode, batch_size)\n return os.path.isfile(module_path)\n\n def load_trt_cached_module(self, module_name, int8_mode=False, batch_size=1):\n module_path = self._get_trt_cache_path(module_name, int8_mode, batch_size)\n if not os.path.isfile(module_path):\n return None\n module = TRTModule()\n module.load_state_dict(torch.load(module_path))\n return module\n\n def save_trt_cached_module(self, module, module_name, int8_mode=False, batch_size=1):\n module_path = self._get_trt_cache_path(module_name, int8_mode, batch_size)\n torch.save(module.state_dict(), module_path)\n\n def trt_load_if(self, module_name, trt_fn, trt_fn_params, int8_mode=False, parent=None, batch_size=1):\n if parent is None: parent=self\n if not hasattr(parent, module_name): return\n module = getattr(parent, module_name)\n trt_cache = self.load_trt_cached_module(module_name, int8_mode, batch_size=batch_size)\n if trt_cache is None:\n module = trt_fn(module, trt_fn_params)\n self.save_trt_cached_module(module, module_name, int8_mode, batch_size=batch_size)\n else:\n module = trt_cache\n\n setattr(parent, module_name, module)\n\n def to_tensorrt_backbone(self, int8_mode=False, calibration_dataset=None, batch_size=1):\n \"\"\"Converts the Backbone to a TRTModule.\n \"\"\"\n if int8_mode:\n trt_fn = partial(torch2trt, int8_mode=True, int8_calib_dataset=calibration_dataset, strict_type_constraints=True, max_batch_size=batch_size)\n else:\n trt_fn = partial(torch2trt, fp16_mode=True, strict_type_constraints=True, max_batch_size=batch_size)\n\n x = torch.ones((1, 3, cfg.max_size, cfg.max_size)).cuda()\n # self.backbone = trt_fn(self.backbone, [x])\n # self.partial_backbone = trt_fn(self.partial_backbone, [x])\n self.trt_load_if(\"backbone\", trt_fn, [x], int8_mode, batch_size=batch_size)\n self.trt_load_if(\"partial_backbone\", trt_fn, [x], int8_mode, batch_size=batch_size)\n\n def to_tensorrt_protonet(self, int8_mode=False, calibration_dataset=None, batch_size=1):\n \"\"\"Converts ProtoNet to a TRTModule.\n \"\"\"\n if int8_mode:\n trt_fn = partial(torch2trt, int8_mode=True, int8_calib_dataset=calibration_dataset, strict_type_constraints=True, max_batch_size=batch_size)\n else:\n trt_fn = partial(torch2trt, fp16_mode=True, strict_type_constraints=True, max_batch_size=batch_size)\n\n x = torch.ones((1, 256, 69, 69)).cuda()\n # self.proto_net = trt_fn(self.proto_net, [x])\n self.trt_load_if(\"proto_net\", trt_fn, [x], int8_mode, batch_size=batch_size)\n\n def to_tensorrt_fpn(self, int8_mode=False, calibration_dataset=None, batch_size=1):\n \"\"\"Converts FPN to a TRTModule.\n \"\"\"\n if int8_mode:\n trt_fn = partial(torch2trt, int8_mode=True, int8_calib_dataset=calibration_dataset, strict_type_constraints=True, max_batch_size=batch_size)\n else:\n trt_fn = partial(torch2trt, fp16_mode=True, strict_type_constraints=True, max_batch_size=batch_size)\n\n self.lat_layer = self.fpn_phase_1.lat_layers[-1]\n\n if cfg.backbone.name == \"ResNet50\" or cfg.backbone.name == \"ResNet101\":\n x = [\n torch.randn(1, 512, 69, 69).cuda(),\n torch.randn(1, 1024, 35, 35).cuda(),\n torch.randn(1, 2048, 18, 18).cuda(),\n ]\n elif cfg.backbone.name == \"MobileNetV2\":\n x = [\n torch.randn(1, 32, 69, 69).cuda(),\n torch.randn(1, 64, 35, 35).cuda(),\n torch.randn(1, 160, 18, 18).cuda(),\n ]\n else:\n raise ValueError(\"Backbone: {} is not currently supported with TensorRT.\".format(cfg.backbone.name))\n\n self.trt_load_if(\"fpn_phase_1\", trt_fn, x, int8_mode, batch_size=batch_size)\n\n if cfg.backbone.name == \"ResNet50\" or cfg.backbone.name == \"ResNet101\":\n x = [\n torch.randn(1, 256, 69, 69).cuda(),\n torch.randn(1, 256, 35, 35).cuda(),\n torch.randn(1, 256, 18, 18).cuda(),\n ]\n elif cfg.backbone.name == \"MobileNetV2\":\n x = [\n torch.randn(1, 256, 69, 69).cuda(),\n torch.randn(1, 256, 35, 35).cuda(),\n torch.randn(1, 256, 18, 18).cuda(),\n ]\n else:\n raise ValueError(\"Backbone: {} is not currently supported with TensorRT.\".format(cfg.backbone.name))\n\n self.trt_load_if(\"fpn_phase_2\", trt_fn, x, int8_mode, batch_size=batch_size)\n\n trt_fn = partial(torch2trt, fp16_mode=True, strict_type_constraints=True)\n\n if cfg.backbone.name == \"ResNet50\" or cfg.backbone.name == \"ResNet101\":\n x = torch.randn(1, 512, 69, 69).cuda()\n elif cfg.backbone.name == \"MobileNetV2\":\n x = torch.randn(1, 32, 69, 69).cuda()\n else:\n raise ValueError(\"Backbone: {} is not currently supported with TensorRT.\".format(cfg.backbone.name))\n\n self.trt_load_if(\"lat_layer\", trt_fn, [x], int8_mode=False, batch_size=batch_size)\n\n def to_tensorrt_prediction_head(self, int8_mode=False, calibration_dataset=None, batch_size=1):\n \"\"\"Converts Prediction Head to a TRTModule.\n \"\"\"\n if int8_mode:\n trt_fn = partial(torch2trt, int8_mode=True, int8_calib_dataset=calibration_dataset, strict_type_constraints=True, max_batch_size=batch_size)\n else:\n trt_fn = partial(torch2trt, fp16_mode=True, strict_type_constraints=True, max_batch_size=batch_size)\n\n for idx, pred_layer in enumerate(self.prediction_layers):\n pred_layer = PredictionModuleTRTWrapper(pred_layer)\n pred_layer.to_tensorrt(batch_size=batch_size)\n self.prediction_layers[idx] = pred_layer\n\n def to_tensorrt_spa(self, int8_mode=False, calibration_dataset=None, batch_size=1):\n \"\"\"Converts SPA to a TRTModule.\n \"\"\"\n if int8_mode:\n trt_fn = partial(torch2trt, int8_mode=True, int8_calib_dataset=calibration_dataset, strict_type_constraints=True, max_batch_size=batch_size)\n else:\n trt_fn = partial(torch2trt, fp16_mode=True, strict_type_constraints=True, max_batch_size=batch_size)\n\n c3 = torch.ones((1, 256, 69, 69)).cuda()\n f2 = torch.ones((1, 256, 35, 35)).cuda()\n f3 = torch.ones((1, 256, 18, 18)).cuda()\n\n self.trt_load_if(\"spa\", trt_fn, [c3, f2, f3], int8_mode, parent=self.spa, batch_size=batch_size)\n\n def to_tensorrt_flow_net(self, int8_mode=False, calibration_dataset=None, batch_size=1):\n \"\"\"Converts FlowNet to a TRTModule.\n \"\"\"\n if int8_mode:\n trt_fn = partial(torch2trt, int8_mode=True, int8_calib_dataset=calibration_dataset, strict_type_constraints=True, max_batch_size=batch_size)\n else:\n trt_fn = partial(torch2trt, fp16_mode=True, strict_type_constraints=True, max_batch_size=batch_size)\n\n\n lateral_channels = cfg.fpn.num_features\n if len(cfg.flow.reduce_channels) > 0:\n lateral_channels = cfg.flow.reduce_channels[-1]\n x = torch.ones((1, lateral_channels * 2, 69, 69)).cuda()\n self.trt_load_if(\"flow_net\", trt_fn, [x], int8_mode, parent=self.flow_net, batch_size=batch_size)\n\n def forward(self, x, extras=None):\n \"\"\" The input should be of size [batch_size, 3, img_h, img_w] \"\"\"\n\n if cfg.flow.train_flow:\n return self.forward_flow(extras)\n\n outs_wrapper = {}\n\n with timer.env('backbone'):\n if cfg.flow is None or extras is None or extras[\"backbone\"] == \"full\":\n outs = self.backbone(x)\n\n elif extras is not None and extras[\"backbone\"] == \"partial\":\n if hasattr(self, 'partial_backbone'):\n outs = self.partial_backbone(x)\n else:\n outs = self.backbone(x, partial=True)\n \n else:\n raise NotImplementedError\n\n if cfg.flow is not None:\n with timer.env('fpn'):\n assert type(extras) == dict\n if extras[\"backbone\"] == \"full\":\n outs = [outs[i] for i in cfg.backbone.selected_layers]\n outs_fpn_phase_1_wrapper = self.fpn_phase_1(*outs)\n outs_phase_1, lats_phase_1 = outs_fpn_phase_1_wrapper[:len(outs)], outs_fpn_phase_1_wrapper[len(outs):]\n lateral = lats_phase_1[0].detach()\n moving_statistics = extras[\"moving_statistics\"]\n\n if extras.get(\"keep_statistics\", False):\n outs_wrapper[\"feats\"] = [out.detach() for out in outs_phase_1]\n outs_wrapper[\"lateral\"] = lateral\n\n outs_wrapper[\"outs_phase_1\"] = [out.detach() for out in outs_phase_1]\n else:\n assert extras[\"moving_statistics\"] is not None\n moving_statistics = extras[\"moving_statistics\"]\n outs_phase_1 = moving_statistics[\"feats\"].copy()\n\n if cfg.flow.warp_mode != 'take':\n src_conv = outs[-1].detach()\n src_lat_layer = self.lat_layer if hasattr(self, 'lat_layer') else self.fpn_phase_1.lat_layers[-1]\n lateral = src_lat_layer(src_conv).detach()\n\n if cfg.flow.warp_mode == \"flow\":\n with timer.env('flow'):\n flows = self.flow_net(self.flow_net_pre_convs(lateral), self.flow_net_pre_convs(moving_statistics[\"lateral\"]))\n preds_feat = list()\n if cfg.flow.flow_layer == 'top':\n flows = [flows[0] for _ in flows]\n if cfg.flow.warp_layers == 'P4P5':\n flows = flows[1:]\n outs_phase_1 = outs_phase_1[1:]\n for (flow, scale_factor, scale_bias), feat in zip(flows, outs_phase_1):\n if cfg.flow.flow_layer == 'top':\n _, _, h, w = feat.size()\n _, _, h_, w_ = flow.size()\n if (h, w) != (h_, w_):\n flow = F.interpolate(flow, size=(h, w), mode=\"area\")\n scale_factor = F.interpolate(scale_factor, size=(h, w), mode=\"area\")\n scale_bias = F.interpolate(scale_bias, size=(h, w), mode=\"area\")\n pred_feat = deform_op(feat, flow)\n if cfg.flow.use_scale_factor:\n pred_feat *= scale_factor\n if cfg.flow.use_scale_bias:\n pred_feat += scale_bias\n preds_feat.append(pred_feat)\n outs_wrapper[\"preds_flow\"] = [[x.detach() for x in flow] for flow in flows]\n outs_phase_1 = preds_feat\n\n if cfg.flow.warp_layers == 'P4P5':\n with timer.env('p3'):\n _, _, h, w = src_conv.size()\n src_fpn = outs_phase_1[0]\n src_fpn = F.interpolate(src_fpn, size=(h, w), mode=cfg.fpn.interpolation_mode, align_corners=False)\n p3 = src_fpn + lateral\n\n outs_phase_1 = [p3] + outs_phase_1\n\n if cfg.flow.use_spa:\n with timer.env('spa'):\n fpn_outs = outs_phase_1.copy()\n outs_phase_1 = [fpn_outs[0]]\n outs_ = self.spa(lateral, *fpn_outs[1:])\n outs_phase_1.extend(outs_)\n\n outs_wrapper[\"outs_phase_1\"] = outs_phase_1.copy()\n\n outs = self.fpn_phase_2(*outs_phase_1)\n if extras[\"backbone\"] == \"partial\":\n outs_wrapper[\"outs_phase_2\"] = [out for out in outs]\n else:\n outs_wrapper[\"outs_phase_2\"] = [out.detach() for out in outs]\n elif cfg.fpn is not None:\n with timer.env('fpn'):\n # Use backbone.selected_layers because we overwrote self.selected_layers\n outs = [outs[i] for i in cfg.backbone.selected_layers]\n outs = self.fpn(outs)\n\n if extras is not None and extras.get(\"interrupt\", None):\n return outs_wrapper\n\n proto_out = None\n if cfg.mask_type == mask_type.lincomb and cfg.eval_mask_branch:\n with timer.env('proto'):\n proto_x = x if self.proto_src is None else outs[self.proto_src]\n \n if self.num_grids > 0:\n grids = self.grid.repeat(proto_x.size(0), 1, 1, 1)\n proto_x = torch.cat([proto_x, grids], dim=1)\n\n proto_out = self.proto_net(proto_x)\n\n proto_out = cfg.mask_proto_prototype_activation(proto_out)\n\n if cfg.mask_proto_prototypes_as_features:\n # Clone here because we don't want to permute this, though idk if contiguous makes this unnecessary\n proto_downsampled = proto_out.clone()\n\n if cfg.mask_proto_prototypes_as_features_no_grad:\n proto_downsampled = proto_out.detach()\n \n # Move the features last so the multiplication is easy\n proto_out = proto_out.permute(0, 2, 3, 1).contiguous()\n\n if cfg.mask_proto_bias:\n bias_shape = [x for x in proto_out.size()]\n bias_shape[-1] = 1\n proto_out = torch.cat([proto_out, torch.ones(*bias_shape)], -1)\n\n with timer.env('pred_heads'):\n pred_outs = { 'loc': [], 'conf': [], 'mask': [], 'priors': [] }\n\n if cfg.use_instance_coeff:\n pred_outs['inst'] = []\n\n for idx, pred_layer in zip(self.selected_layers, self.prediction_layers):\n pred_x = outs[idx]\n\n if cfg.mask_type == mask_type.lincomb and cfg.mask_proto_prototypes_as_features:\n # Scale the prototypes down to the current prediction layer's size and add it as inputs\n proto_downsampled = F.interpolate(proto_downsampled, size=outs[idx].size()[2:], mode='bilinear', align_corners=False)\n pred_x = torch.cat([pred_x, proto_downsampled], dim=1)\n\n # This is re-enabled during training or non-TRT inference.\n if self.training or not (cfg.torch2trt_prediction_module or cfg.torch2trt_prediction_module_int8):\n # A hack for the way dataparallel works\n if cfg.share_prediction_module and pred_layer is not self.prediction_layers[0]:\n pred_layer.parent = [self.prediction_layers[0]]\n\n p = pred_layer(pred_x)\n \n for k, v in p.items():\n pred_outs[k].append(v)\n\n for k, v in pred_outs.items():\n pred_outs[k] = torch.cat(v, -2)\n\n if proto_out is not None:\n pred_outs['proto'] = proto_out\n\n if self.training:\n # For the extra loss functions\n if cfg.use_class_existence_loss:\n pred_outs['classes'] = self.class_existence_fc(outs[-1].mean(dim=(2, 3)))\n\n if cfg.use_semantic_segmentation_loss:\n pred_outs['segm'] = self.semantic_seg_conv(outs[0])\n\n outs_wrapper[\"pred_outs\"] = pred_outs\n else:\n if cfg.use_sigmoid_focal_loss:\n # Note: even though conf[0] exists, this mode doesn't train it so don't use it\n pred_outs['conf'] = torch.sigmoid(pred_outs['conf'])\n elif cfg.use_objectness_score:\n # See focal_loss_sigmoid in multibox_loss.py for details\n objectness = torch.sigmoid(pred_outs['conf'][:, :, 0])\n pred_outs['conf'][:, :, 1:] = objectness[:, :, None] * F.softmax(pred_outs['conf'][:, :, 1:], -1)\n pred_outs['conf'][:, :, 0 ] = 1 - objectness\n else:\n pred_outs['conf'] = F.softmax(pred_outs['conf'], -1)\n\n outs_wrapper[\"pred_outs\"] = self.detect(pred_outs)\n return outs_wrapper\n\n\n# Some testing code\nif __name__ == '__main__':\n from utils.functions import init_console\n init_console()\n\n # Use the first argument to set the config if you want\n import sys\n if len(sys.argv) > 1:\n from data.config import set_cfg\n set_cfg(sys.argv[1])\n\n net = Yolact()\n net.train()\n net.init_weights(backbone_path='weights/' + cfg.backbone.path)\n\n # GPU\n net = net.cuda()\n cudnn.benchmark = True\n torch.set_default_tensor_type('torch.cuda.FloatTensor')\n\n x = torch.zeros((1, 3, cfg.max_size, cfg.max_size))\n y = net(x)\n\n for p in net.prediction_layers:\n print(p.last_conv_size)\n\n print()\n for k, a in y.items():\n print(k + ': ', a.size(), torch.sum(a))\n exit()\n \n net(x)\n # timer.disable('pass2')\n avg = MovingAverage()\n try:\n while True:\n timer.reset()\n with timer.env('everything else'):\n net(x)\n avg.add(timer.total_time())\n print('\\033[2J') # Moves console cursor to 0,0\n timer.print_stats()\n print('Avg fps: %.2f\\tAvg ms: %.2f ' % (1/avg.get_avg(), avg.get_avg()*1000))\n except KeyboardInterrupt:\n pass\n"
]
| [
[
"torch.set_default_tensor_type",
"torch.nn.functional.softmax",
"torch.zeros",
"torch.cat",
"torch.load",
"torch.sum",
"torch.nn.functional.interpolate",
"torch.nn.functional.smooth_l1_loss",
"torch.ones",
"torch.randn",
"torch.tensor",
"torch.nn.functional.relu",
"numpy.load",
"torch.nn.functional.max_pool2d",
"torch.nn.Sequential",
"torch.sigmoid",
"numpy.log",
"torch.nn.ConvTranspose2d",
"torch.cuda.current_device",
"torch.nn.init.constant_",
"torch.nn.ModuleList",
"torch.nn.Conv2d",
"torch.nn.Linear",
"torch.nn.functional.cosine_similarity",
"torch.nn.LeakyReLU",
"torch.nn.BatchNorm2d",
"torch.cuda.device_count",
"torch.nn.functional.normalize",
"torch.Tensor",
"torch.nn.Tanh",
"torch.nn.Upsample",
"torch.nn.init.xavier_uniform_",
"torch.chunk",
"torch.nn.ReLU",
"torch.nn.init.kaiming_normal_"
]
]
|
ssayyah/cudf | [
"b5ffdf5ffb398adef25435bc696df3ff30c4aa9a"
]
| [
"python/dask_cudf/dask_cudf/backends.py"
]
| [
"# Copyright (c) 2020-2021, NVIDIA CORPORATION.\n\nimport cupy as cp\nimport numpy as np\nimport pandas as pd\nimport pyarrow as pa\n\nfrom dask.dataframe.categorical import categorical_dtype_dispatch\nfrom dask.dataframe.core import get_parallel_type, meta_nonempty\nfrom dask.dataframe.methods import (\n concat_dispatch,\n is_categorical_dtype_dispatch,\n tolist_dispatch,\n)\nfrom dask.dataframe.utils import (\n UNKNOWN_CATEGORIES,\n _nonempty_scalar,\n _scalar_from_dtype,\n is_arraylike,\n is_scalar,\n make_meta,\n)\n\ntry:\n from dask.dataframe.utils import make_meta_obj as make_meta_obj\nexcept ImportError:\n from dask.dataframe.utils import make_meta as make_meta_obj\n\nimport cudf\nfrom cudf.utils.dtypes import is_string_dtype\n\nfrom .core import DataFrame, Index, Series\n\nget_parallel_type.register(cudf.DataFrame, lambda _: DataFrame)\nget_parallel_type.register(cudf.Series, lambda _: Series)\nget_parallel_type.register(cudf.Index, lambda _: Index)\n\n\n@meta_nonempty.register(cudf.Index)\ndef _nonempty_index(idx):\n if isinstance(idx, cudf.core.index.RangeIndex):\n return cudf.core.index.RangeIndex(2, name=idx.name)\n elif isinstance(idx, cudf.core.index.DatetimeIndex):\n start = \"1970-01-01\"\n data = np.array([start, \"1970-01-02\"], dtype=idx.dtype)\n values = cudf.core.column.as_column(data)\n return cudf.core.index.DatetimeIndex(values, name=idx.name)\n elif isinstance(idx, cudf.core.index.StringIndex):\n return cudf.core.index.StringIndex([\"cat\", \"dog\"], name=idx.name)\n elif isinstance(idx, cudf.core.index.CategoricalIndex):\n key = tuple(idx._data.keys())\n assert len(key) == 1\n categories = idx._data[key[0]].categories\n codes = [0, 0]\n ordered = idx._data[key[0]].ordered\n values = cudf.core.column.build_categorical_column(\n categories=categories, codes=codes, ordered=ordered\n )\n return cudf.core.index.CategoricalIndex(values, name=idx.name)\n elif isinstance(idx, cudf.core.index.GenericIndex):\n return cudf.core.index.GenericIndex(\n np.arange(2, dtype=idx.dtype), name=idx.name\n )\n elif isinstance(idx, cudf.core.MultiIndex):\n levels = [meta_nonempty(lev) for lev in idx.levels]\n codes = [[0, 0] for i in idx.levels]\n return cudf.core.MultiIndex(\n levels=levels, codes=codes, names=idx.names\n )\n\n raise TypeError(f\"Don't know how to handle index of type {type(idx)}\")\n\n\ndef _get_non_empty_data(s):\n if isinstance(s._column, cudf.core.column.CategoricalColumn):\n categories = (\n s._column.categories\n if len(s._column.categories)\n else [UNKNOWN_CATEGORIES]\n )\n codes = cudf.core.column.full(size=2, fill_value=0, dtype=\"int32\")\n ordered = s._column.ordered\n data = cudf.core.column.build_categorical_column(\n categories=categories, codes=codes, ordered=ordered\n )\n elif is_string_dtype(s.dtype):\n data = pa.array([\"cat\", \"dog\"])\n else:\n if pd.api.types.is_numeric_dtype(s.dtype):\n data = cudf.core.column.as_column(\n cp.arange(start=0, stop=2, dtype=s.dtype)\n )\n else:\n data = cudf.core.column.as_column(\n cp.arange(start=0, stop=2, dtype=\"int64\")\n ).astype(s.dtype)\n return data\n\n\n@meta_nonempty.register(cudf.Series)\ndef _nonempty_series(s, idx=None):\n if idx is None:\n idx = _nonempty_index(s.index)\n data = _get_non_empty_data(s)\n\n return cudf.Series(data, name=s.name, index=idx)\n\n\n@meta_nonempty.register(cudf.DataFrame)\ndef meta_nonempty_cudf(x):\n idx = meta_nonempty(x.index)\n columns_with_dtype = dict()\n res = cudf.DataFrame(index=idx)\n for col in x._data.names:\n dtype = str(x._data[col].dtype)\n if dtype not in columns_with_dtype:\n columns_with_dtype[dtype] = cudf.core.column.as_column(\n _get_non_empty_data(x[col])\n )\n res._data[col] = columns_with_dtype[dtype]\n return res\n\n\n@make_meta.register((cudf.Series, cudf.DataFrame))\ndef make_meta_cudf(x, index=None):\n return x.head(0)\n\n\n@make_meta.register(cudf.Index)\ndef make_meta_cudf_index(x, index=None):\n return x[:0]\n\n\ndef _empty_series(name, dtype, index=None):\n if isinstance(dtype, str) and dtype == \"category\":\n return cudf.Series(\n [UNKNOWN_CATEGORIES], dtype=dtype, name=name, index=index\n ).iloc[:0]\n return cudf.Series([], dtype=dtype, name=name, index=index)\n\n\n@make_meta_obj.register(object)\ndef make_meta_object_cudf(x, index=None):\n \"\"\"Create an empty cudf object containing the desired metadata.\n\n Parameters\n ----------\n x : dict, tuple, list, cudf.Series, cudf.DataFrame, cudf.Index,\n dtype, scalar\n To create a DataFrame, provide a `dict` mapping of `{name: dtype}`, or\n an iterable of `(name, dtype)` tuples. To create a `Series`, provide a\n tuple of `(name, dtype)`. If a cudf object, names, dtypes, and index\n should match the desired output. If a dtype or scalar, a scalar of the\n same dtype is returned.\n index : cudf.Index, optional\n Any cudf index to use in the metadata. If none provided, a\n `RangeIndex` will be used.\n\n Examples\n --------\n >>> make_meta([('a', 'i8'), ('b', 'O')])\n Empty DataFrame\n Columns: [a, b]\n Index: []\n >>> make_meta(('a', 'f8'))\n Series([], Name: a, dtype: float64)\n >>> make_meta('i8')\n 1\n \"\"\"\n if hasattr(x, \"_meta\"):\n return x._meta\n elif is_arraylike(x) and x.shape:\n return x[:0]\n\n if index is not None:\n index = make_meta(index)\n\n if isinstance(x, dict):\n return cudf.DataFrame(\n {c: _empty_series(c, d, index=index) for (c, d) in x.items()},\n index=index,\n )\n if isinstance(x, tuple) and len(x) == 2:\n return _empty_series(x[0], x[1], index=index)\n elif isinstance(x, (list, tuple)):\n if not all(isinstance(i, tuple) and len(i) == 2 for i in x):\n raise ValueError(\n f\"Expected iterable of tuples of (name, dtype), got {x}\"\n )\n return cudf.DataFrame(\n {c: _empty_series(c, d, index=index) for (c, d) in x},\n columns=[c for c, d in x],\n index=index,\n )\n elif not hasattr(x, \"dtype\") and x is not None:\n # could be a string, a dtype object, or a python type. Skip `None`,\n # because it is implictly converted to `dtype('f8')`, which we don't\n # want here.\n try:\n dtype = np.dtype(x)\n return _scalar_from_dtype(dtype)\n except Exception:\n # Continue on to next check\n pass\n\n if is_scalar(x):\n return _nonempty_scalar(x)\n\n raise TypeError(f\"Don't know how to create metadata from {x}\")\n\n\n@concat_dispatch.register((cudf.DataFrame, cudf.Series, cudf.Index))\ndef concat_cudf(\n dfs,\n axis=0,\n join=\"outer\",\n uniform=False,\n filter_warning=True,\n sort=None,\n ignore_index=False,\n **kwargs,\n):\n assert join == \"outer\"\n\n ignore_order = kwargs.get(\"ignore_order\", False)\n if ignore_order:\n raise NotImplementedError(\n \"ignore_order parameter is not yet supported in dask-cudf\"\n )\n\n return cudf.concat(dfs, axis=axis, ignore_index=ignore_index)\n\n\n@categorical_dtype_dispatch.register((cudf.DataFrame, cudf.Series, cudf.Index))\ndef categorical_dtype_cudf(categories=None, ordered=None):\n return cudf.CategoricalDtype(categories=categories, ordered=ordered)\n\n\n@tolist_dispatch.register((cudf.Series, cudf.Index))\ndef tolist_cudf(obj):\n return obj.to_arrow().to_pylist()\n\n\n@is_categorical_dtype_dispatch.register(\n (cudf.Series, cudf.Index, cudf.CategoricalDtype, Series)\n)\ndef is_categorical_dtype_cudf(obj):\n return cudf.utils.dtypes.is_categorical_dtype(obj)\n\n\ntry:\n from dask.dataframe.dispatch import union_categoricals_dispatch\n\n @union_categoricals_dispatch.register((cudf.Series, cudf.Index))\n def union_categoricals_cudf(\n to_union, sort_categories=False, ignore_order=False\n ):\n return cudf.api.types._union_categoricals(\n to_union, sort_categories=False, ignore_order=False\n )\n\n\nexcept ImportError:\n pass\n\ntry:\n\n from dask.dataframe.core import group_split_dispatch, hash_object_dispatch\n\n def safe_hash(frame):\n index = frame.index\n if isinstance(frame, cudf.DataFrame):\n return cudf.Series(frame.hash_columns(), index=index)\n else:\n return cudf.Series(frame.hash_values(), index=index)\n\n @hash_object_dispatch.register((cudf.DataFrame, cudf.Series))\n def hash_object_cudf(frame, index=True):\n if index:\n return safe_hash(frame.reset_index())\n return safe_hash(frame)\n\n @hash_object_dispatch.register(cudf.Index)\n def hash_object_cudf_index(ind, index=None):\n\n if isinstance(ind, cudf.MultiIndex):\n return safe_hash(ind.to_frame(index=False))\n\n col = cudf.core.column.as_column(ind)\n return safe_hash(cudf.Series(col))\n\n @group_split_dispatch.register((cudf.Series, cudf.DataFrame))\n def group_split_cudf(df, c, k, ignore_index=False):\n return dict(\n zip(\n range(k),\n df.scatter_by_map(\n c.astype(np.int32, copy=False),\n map_size=k,\n keep_index=not ignore_index,\n ),\n )\n )\n\n\nexcept ImportError:\n pass\n"
]
| [
[
"numpy.dtype",
"numpy.arange",
"numpy.array",
"pandas.api.types.is_numeric_dtype"
]
]
|
masroorhasan/seldon-core | [
"674e00cd4b740ee21ac3de00ab145ebd6ebf8b9e"
]
| [
"components/outlier-detection/isolation-forest/OutlierIsolationForest.py"
]
| [
"import numpy as np\nimport pickle\nfrom sklearn.ensemble import IsolationForest\n\nfrom utils import flatten, performance, outlier_stats\n\nclass OutlierIsolationForest(object):\n \"\"\" Outlier detection using Isolation Forests.\n \n Arguments:\n - threshold (float): anomaly score threshold; scores below threshold are outliers\n \n Functions:\n - predict: detect and return outliers\n - send_feedback: add target labels as part of the feedback loop\n - metrics: return custom metrics\n \"\"\"\n def __init__(self,threshold=0.,load_path='./models/'):\n \n self.threshold = threshold\n self.N = 0 # total sample count up until now\n \n # load pre-trained model\n with open(load_path + 'model.pickle', 'rb') as f:\n self.clf = pickle.load(f)\n \n self._predictions = []\n self._labels = []\n self._anomaly_score = []\n self.roll_window = 100\n self.metric = [float('nan') for i in range(18)]\n \n def predict(self,X,feature_names):\n \"\"\" Detect outliers from mse using the threshold. \n \n Arguments:\n - X: input data\n - feature_names\n \"\"\"\n self.decision_val = self.clf.decision_function(X) # anomaly scores\n self._anomaly_score.append(self.decision_val)\n self._anomaly_score = flatten(self._anomaly_score)\n \n # make prediction\n self.prediction = (self.decision_val < self.threshold).astype(int) # scores below threshold are outliers\n self._predictions.append(self.prediction)\n self._predictions = flatten(self._predictions)\n \n self.N+=self.prediction.shape[0] # update counter\n \n return self.prediction\n \n def send_feedback(self,X,feature_names,reward,truth):\n \"\"\" Return outlier labels as part of the feedback loop.\n \n Arguments:\n - X: input data\n - feature_names\n - reward\n - truth: outlier labels\n \"\"\"\n self.label = truth\n self._labels.append(self.label)\n self._labels = flatten(self._labels)\n \n scores = performance(self._labels,self._predictions,roll_window=self.roll_window)\n stats = outlier_stats(self._labels,self._predictions,roll_window=self.roll_window)\n \n convert = flatten([scores,stats])\n metric = []\n for c in convert: # convert from np to native python type to jsonify\n metric.append(np.asscalar(np.asarray(c)))\n self.metric = metric\n \n return\n \n def metrics(self):\n \"\"\" Return custom metrics.\n Printed with a delay of 1 prediction because the labels are returned in the feedback step. \n \"\"\"\n \n if self.prediction.shape[0]>1:\n raise ValueError('Metrics can only handle single observations.')\n \n if self.N==1:\n pred = float('nan')\n dec_val = float('nan')\n y_true = float('nan')\n else:\n pred = int(self._predictions[-2])\n dec_val = self._anomaly_score[-2]\n y_true = int(self.label[0])\n \n is_outlier = {\"type\":\"GAUGE\",\"key\":\"is_outlier\",\"value\":pred}\n anomaly_score = {\"type\":\"GAUGE\",\"key\":\"anomaly_score\",\"value\":dec_val}\n obs = {\"type\":\"GAUGE\",\"key\":\"observation\",\"value\":self.N - 1}\n threshold = {\"type\":\"GAUGE\",\"key\":\"threshold\",\"value\":self.threshold}\n \n label = {\"type\":\"GAUGE\",\"key\":\"label\",\"value\":y_true}\n \n accuracy_tot = {\"type\":\"GAUGE\",\"key\":\"accuracy_tot\",\"value\":self.metric[4]}\n precision_tot = {\"type\":\"GAUGE\",\"key\":\"precision_tot\",\"value\":self.metric[5]}\n recall_tot = {\"type\":\"GAUGE\",\"key\":\"recall_tot\",\"value\":self.metric[6]}\n f1_score_tot = {\"type\":\"GAUGE\",\"key\":\"f1_tot\",\"value\":self.metric[7]}\n f2_score_tot = {\"type\":\"GAUGE\",\"key\":\"f2_tot\",\"value\":self.metric[8]}\n \n accuracy_roll = {\"type\":\"GAUGE\",\"key\":\"accuracy_roll\",\"value\":self.metric[9]}\n precision_roll = {\"type\":\"GAUGE\",\"key\":\"precision_roll\",\"value\":self.metric[10]}\n recall_roll = {\"type\":\"GAUGE\",\"key\":\"recall_roll\",\"value\":self.metric[11]}\n f1_score_roll = {\"type\":\"GAUGE\",\"key\":\"f1_roll\",\"value\":self.metric[12]}\n f2_score_roll = {\"type\":\"GAUGE\",\"key\":\"f2_roll\",\"value\":self.metric[13]}\n \n true_negative = {\"type\":\"GAUGE\",\"key\":\"true_negative\",\"value\":self.metric[0]}\n false_positive = {\"type\":\"GAUGE\",\"key\":\"false_positive\",\"value\":self.metric[1]}\n false_negative = {\"type\":\"GAUGE\",\"key\":\"false_negative\",\"value\":self.metric[2]}\n true_positive = {\"type\":\"GAUGE\",\"key\":\"true_positive\",\"value\":self.metric[3]}\n \n nb_outliers_roll = {\"type\":\"GAUGE\",\"key\":\"nb_outliers_roll\",\"value\":self.metric[14]}\n nb_labels_roll = {\"type\":\"GAUGE\",\"key\":\"nb_labels_roll\",\"value\":self.metric[15]}\n nb_outliers_tot = {\"type\":\"GAUGE\",\"key\":\"nb_outliers_tot\",\"value\":self.metric[16]}\n nb_labels_tot = {\"type\":\"GAUGE\",\"key\":\"nb_labels_tot\",\"value\":self.metric[17]}\n \n return [is_outlier,anomaly_score,obs,threshold,label,\n accuracy_tot,precision_tot,recall_tot,f1_score_tot,f2_score_tot,\n accuracy_roll,precision_roll,recall_roll,f1_score_roll,f2_score_roll,\n true_negative,false_positive,false_negative,true_positive,\n nb_outliers_roll,nb_labels_roll,nb_outliers_tot,nb_labels_tot]"
]
| [
[
"numpy.asarray"
]
]
|
dmitryhits/charting | [
"c76f6bc047224ebfcce7e0965c4cd35905cb98f1"
]
| [
"ts_charting/charting.py"
]
| [
"import pandas as pd\nfrom pandas.util.decorators import Appender\n\nfrom ts_charting import Figure\nimport ts_charting.styles as cstyler\n\nCURRENT_FIGURE = None\n\ndef reset_figure(*args):\n \"\"\"\n In ipython notebook, clear the figure after each cell execute.\n This negates the need to specify a Figure for each plot\n \"\"\"\n global CURRENT_FIGURE\n CURRENT_FIGURE = None\n\ndef gcf(reset=False):\n global CURRENT_FIGURE\n if reset:\n CURRENT_FIGURE = None\n return CURRENT_FIGURE\n\n if CURRENT_FIGURE is None:\n CURRENT_FIGURE = figure(1)\n return CURRENT_FIGURE\n\ndef scf(figure):\n global CURRENT_FIGURE\n CURRENT_FIGURE = figure\n\n_fplot_doc = \"\"\"\n Keyword Parameters\n ----------\n secondary_y : bool\n Plot on a secondary y-axis\n yax : string:\n named y-axis plot. \n\"\"\"\n# Monkey Patches, no good reason for this to be here...\n@Appender(_fplot_doc)\ndef series_plot(self, label=None, *args, **kwargs):\n label = plot_label(self, label, **kwargs)\n\n fig = gcf()\n fig.plot(str(label), self, *args, **kwargs)\n\npd.Series.fplot = series_plot\n#pd.Series.fplot = series_plot\n\ndef df_plot(self, *args, **kwargs):\n force_plot = kwargs.pop('force_plot', False)\n styler = kwargs.pop('styler', cstyler.marker_styler())\n\n if len(self.columns) > 20 and not force_plot:\n raise Exception(\"Are you crazy? Too many columns\")\n\n # pass styler to each series plot\n kwargs['styler'] = styler\n for col in self.columns:\n series = self[col]\n series.fplot(*args, **kwargs)\n\npd.DataFrame.fplot = df_plot\n\ndef series_plot_markers(self, label=None, yvalues=None, *args, **kwargs):\n \"\"\"\n Really just an automated way of calling gcf\n \"\"\"\n fig = gcf()\n label = plot_label(self, label, **kwargs)\n fig.plot_markers(str(label), self, yvalues=yvalues, *args, **kwargs)\n\npd.Series.fplot_markers = series_plot_markers\n\ndef figure(*args, **kwargs):\n \"\"\" create Figure and set as current \"\"\"\n kwargs['warn'] = False\n fig = Figure(*args, **kwargs)\n scf(fig)\n return fig\n\ndef plot_label(self, label=None, **kwargs):\n \"\"\"\n Logic to grab plot label\n\n Note that this both takes label as a positional argument and a keyword. \n\n This is a legacy issue where instead of grabbing label from kwargs, \n which is how matplotlib handles it, I decided to make it a positional\n argument, under the assumption that you would almost always need a label. \n\n While this is true, it makes it so I have to check check both types of \n args.\n \"\"\"\n label = label or kwargs.get('label')\n if label is None: # allow series to define non `.name` label\n label = getattr(self, 'plot_label', None)\n label = label or self.name\n\n prefix = kwargs.pop('prefix', None)\n if prefix:\n label = prefix +' '+label\n\n return label\n\n# try to monkey patch pandas_composition\n# we do this to get access to the subclass self\n# get around: https://github.com/dalejung/pandas-composition/issues/19\ntry:\n import pandas_composition as pc\n pc.UserFrame.fplot = df_plot\n pc.UserSeries.fplot = series_plot\n pc.UserSeries.fplot_markers = series_plot_markers\nexcept ImportError:\n pass\n"
]
| [
[
"pandas.util.decorators.Appender"
]
]
|
irgroup/repro_eval | [
"35a4cf083dbb5f4b29d6ef602a604f0686a537c9"
]
| [
"example/rpd_arp.py"
]
| [
"import pytrec_eval\nfrom repro_eval.Evaluator import RpdEvaluator\nfrom repro_eval.util import arp, arp_scores\nfrom repro_eval.util import trim\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nimport seaborn as sns\nsns.set()\nsns.set_style('whitegrid')\n# palette = sns.color_palette(\"GnBu_d\")\n# sns.set_palette(palette)\ncolors = sns.color_palette()\n\nORIG_B = './data/runs/orig/input.WCrobust04'\nORIG_A = './data/runs/orig/input.WCrobust0405'\nQREL = 'data/qrels/core17.txt'\n\nruns_rpd = {\n 'rpd_wcr04_tf_1':\n {'path': './data/runs/rpd/45/irc_task1_WCrobust04_001'},\n 'rpd_wcr0405_tf_1':\n {'path': './data/runs/rpd/45/irc_task1_WCrobust0405_001'},\n 'rpd_wcr04_tf_2':\n {'path': './data/runs/rpd/46/irc_task1_WCrobust04_001'},\n 'rpd_wcr0405_tf_2':\n {'path': './data/runs/rpd/46/irc_task1_WCrobust0405_001'},\n 'rpd_wcr04_tf_3':\n {'path': './data/runs/rpd/47/irc_task1_WCrobust04_001'},\n 'rpd_wcr0405_tf_3':\n {'path': './data/runs/rpd/47/irc_task1_WCrobust0405_001'},\n 'rpd_wcr04_tf_4':\n {'path': './data/runs/rpd/48/irc_task1_WCrobust04_001'},\n 'rpd_wcr0405_tf_4':\n {'path': './data/runs/rpd/48/irc_task1_WCrobust0405_001'},\n 'rpd_wcr04_tf_5':\n {'path': './data/runs/rpd/49/irc_task1_WCrobust04_001'},\n 'rpd_wcr0405_tf_5':\n {'path': './data/runs/rpd/49/irc_task1_WCrobust0405_001'}\n}\n\n\n\ndef average_retrieval_performance(baseline_scores, reproduced_scores: dict, measures: list, xlabel: str, ylabel: str, outfile: str):\n reproduced_scores_arp = [arp_scores(topic_scores) for idx, topic_scores in reproduced_scores.items()]\n baseline_scores_arp = arp_scores(baseline_scores)\n index = list(reproduced_scores.keys())\n df_content = {}\n for measure in measures:\n df_content[measure] = [scores.get(measure) for scores in reproduced_scores_arp]\n df = pd.DataFrame(df_content, index=index)\n\n ax = df.plot.bar(rot=0)\n for num, measure in enumerate(measures):\n orig_val = baseline_scores_arp.get(measure)\n ax.hlines(orig_val, -.5, 5.5, linestyles='dashed', color=colors[num])\n ax.annotate(' ', (num, orig_val), color=colors[num])\n ax.set_ylim(0.0, 1.0)\n\n legend_content = [measure + ' (orig)' for measure in measures] + [measure + ' (rpl)' for measure in measures]\n ax.legend(legend_content, loc='lower left')\n\n ax.set_xlabel(xlabel)\n ax.set_ylabel(ylabel)\n ax.get_figure().savefig(outfile, format='pdf', bbox_inches='tight')\n plt.show()\n\n\ndef main():\n rpd_eval = RpdEvaluator(qrel_orig_path=QREL,\n run_b_orig_path=ORIG_B,\n run_a_orig_path=ORIG_A,\n run_b_rep_path=None,\n run_a_rep_path=None)\n\n rpd_eval.trim()\n rpd_eval.evaluate()\n\n for run_name, info in runs_rpd.items():\n with open(info.get('path')) as run_file:\n info['run'] = pytrec_eval.parse_run(run_file)\n trim(info['run'])\n info['scores'] = rpd_eval.evaluate(info['run'])\n\n average_retrieval_performance(rpd_eval.run_b_orig_score,\n {\n 'tf_1': runs_rpd.get('rpd_wcr04_tf_1').get('scores'),\n 'tf_2': runs_rpd.get('rpd_wcr04_tf_2').get('scores'),\n 'tf_3': runs_rpd.get('rpd_wcr04_tf_3').get('scores'),\n 'tf_4': runs_rpd.get('rpd_wcr04_tf_4').get('scores'),\n 'tf_5': runs_rpd.get('rpd_wcr04_tf_5').get('scores'),\n },\n measures=['P_10', 'ndcg', 'bpref', 'map'],\n xlabel='Reproduced run (wcr04)',\n ylabel='Score',\n outfile='data/plots/rpd_b_arp.pdf')\n\n average_retrieval_performance(rpd_eval.run_a_orig_score,\n {\n 'tf_1': runs_rpd.get('rpd_wcr0405_tf_1').get('scores'),\n 'tf_2': runs_rpd.get('rpd_wcr0405_tf_2').get('scores'),\n 'tf_3': runs_rpd.get('rpd_wcr0405_tf_3').get('scores'),\n 'tf_4': runs_rpd.get('rpd_wcr0405_tf_4').get('scores'),\n 'tf_5': runs_rpd.get('rpd_wcr0405_tf_5').get('scores'),\n },\n measures=['P_10', 'ndcg', 'bpref', 'map'],\n xlabel='Reproduced run (wcr0405)',\n ylabel='Score',\n outfile='data/plots/rpd_a_arp.pdf')\n\n\nif __name__ == \"__main__\":\n main()"
]
| [
[
"matplotlib.pyplot.show",
"pandas.DataFrame"
]
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.