repo_name
stringlengths 6
130
| hexsha
list | file_path
list | code
list | apis
list |
---|---|---|---|---|
rknop/amuse
|
[
"85d5bdcc29cfc87dc69d91c264101fafd6658aec",
"3ac3b6b8f922643657279ddee5c8ab3fc0440d5e",
"3ac3b6b8f922643657279ddee5c8ab3fc0440d5e"
] |
[
"src/amuse/ic/_limepy/limepy.py",
"examples/syllabus/stellar_simple.py",
"src/amuse/ext/orbital_elements.py"
] |
[
"# -*- coding: utf-8 -*-\n\nimport numpy\nimport scipy\nfrom numpy import exp, sqrt, pi, sin\nfrom scipy.interpolate import PiecewisePolynomial, interp1d\nfrom scipy.special import gamma, gammainc, dawsn, hyp1f1\nfrom scipy.integrate import ode, quad, simps\nfrom math import factorial\n\n# Authors: Mark Gieles, Alice Zocchi (Surrey 2015)\n\nclass limepy:\n def __init__(self, phi0, g, **kwargs):\n r\"\"\"\n\n (MM, A) LIMEPY\n\n (Multi-Mass, Anisotropic) Lowered Isothermal Model Explorer in Python\n\n This code solves the models presented in Gieles & Zocchi 2015 (GZ15),\n and calculates radial profiles for some useful quantities. The models\n are defined by the distribution function (DF) of equation (1) in GZ15.\n\n Model parameters:\n =================\n\n phi0 : scalar, required\n Central dimensionless potential\n g : scalar, required\n Order of truncation (0<= g < 3.5; 0=Woolley, 1=King, 2=Wilson)\n\n ra : scalar, required for anisotropic models\n Anisotropy radius; default=1e8\n mj : list, required for multi-mass system\n Mean mass of each component; default=None\n Mj : list, required for multi-mass system\n Total mass of each component; default=None\n delta : scalar, optional\n Index in s_j = s x mu_j^-delta; default=0.5\n See equation (24) in GZ15\n eta : scalar, optional\n Index in ra_j = ra x mu_j^eta; default=0\n See equation (25) in GZ15\n\n Input for scaling:\n ==================\n\n scale : bool, optional\n Scale model to desired G=GS, M=MS, R=RS; default=False\n MS : scalar, optional\n Final scaled mass; default=10^5 [Msun]\n RS : scalar, optional\n Final scaled radius, half-mass or virial (see below); default=3 [pc]\n GS : scalar, optional\n Final scaled gravitationsl const; default=0.004302 [(km/s)^2 pc/Msun]\n scale_radius : str, optional\n Radius to scale ['rv' or 'rh']; default='rh'\n\n Options:\n ========\n\n project : bool, optional\n Compute model properties in projection; default=False\n potonly : bool, optional\n Fast solution by solving potential only; default=False\n max_step : scalar, optional\n Maximum step size for ode output; default=1e10\n verbose : bool, optional\n Print diagnostics; default=False\n ode_atol : absolute tolerance parameter for ode solver; default=1e-7\n ode_rtol : relative tolerance parameter for ode solver; default=1e-7\n\n Output variables:\n =================\n\n All models:\n -----------\n rhat, phihat, rhohat : radius, potential and density in model units\n r, phi, rho : as above, in scaled units (if scale=True)\n v2, v2r, v2t : total, radial and tangential mean-square velocity\n beta : anisotropy profile (equation 32, GZ15)\n mc : enclosed mass profile\n r0, rh, rv, rt : radii (King, half-mass, virial, truncation)\n K, Kr, Kt : kinetic energy: total, radial, tangential\n U, Q : potential energy, virial ratio\n A : constant in DF (equation 1, GZ15)\n volume : phase-space volume occupied by model\n nstep : number of integration steps (depends on ode_rtol & ode_atol)\n converged : bool flag to indicate whether model was solved\n\n Projected models:\n -----------------\n Sigma : surface (mass) density\n v2z : line-of-sight mean-square velocity\n v2R, v2T : radial and tangential component of mean-square velocity\n on plane of the sky\n\n Multi-mass models:\n ------------------\n Properties of each component:\n phi0j : dimensionless central potential\n rhohatj : dimensionless density\n rhoj : density profile\n v2j : mean-square velocity profile\n v2rj, v2tj : radial and tangential component of mean-square velocity\n profile\n r0j, raj : radii (King, anisotropy)\n Kj : kinetic energy\n Krj, Ktj : radial/tangential component of kinetic energy\n\n Projected multi-mass models:\n ---------------------------\n Properties of each component:\n Sigmaj : surface (mass) density\n v2zj : line-of-sight mean-square velocity profile\n v2Rj, v2Tj : radial and tangential component on the plane of the sky\n of the mean-square velocity profile\n\n Examples:\n =========\n\n Construct a Woolley model with phi0 = 7 and print r_t/r_0 and r_v/r_h\n\n >>> k = limepy(7, 0)\n >>> print k.rt/k.r0, k.rv/k.rh\n >>> 19.1293426415 1.17783663028\n\n Construct a Michie-King model and print ratio of anisotropy radius over\n half-mass radius and the Polyachenko & Shukhman (1981) anisotropy\n parameter\n\n >>> a = limepy(7, 1, ra=5)\n >>> print a.ra/a.rh, 2*a.Kr/a.Kt\n >>> 1.03377960149 1.36280949941\n\n Create a Wilson model with phi0 = 12 in Henon/N-body units: G = M =\n r_v = 1 and print the normalisation constant A of the DF and the\n value of the DF in the centre:\n\n >>> w = limepy(12, 2, scale=True, GS=1, MS=1, RS=1, scale_radius='rv')\n >>> print w.A, w.df(0,0)\n >>> [ 0.00800902] [ 1303.40270676]\n\n Multi-mass model in physical units with r_h = 3 pc and M = 10^5 M_sun\n and print central densities of each bin over the total central density\n and the half-mass radius + half-mass radius in projection\n\n >>> m = limepy(7, 1, mj=[0.3,1,5], Mj=[9,3,1], scale=True, project=True)\n >>> print m.alpha, m.rh, m.rhp\n >>> [ 0.30721416 0.14103549 0.55175035] 3.0 2.25494426759\n\n \"\"\"\n\n # Set parameters and scales\n self._set_kwargs(phi0, g, **kwargs)\n self.rhoint0 = [self._rhoint(self.phi0, 0, self.ramax)]\n\n # In case of multi-mass model, iterate to find central densities\n # (see Section 2.2 in GZ15)\n if (self.multi):\n self._init_multi(self.mj, self.Mj)\n\n while self.diff > self.diffcrit:\n self._poisson(True)\n\n if (not self.converged):\n error = \"Error: model did not converge in first iteration,\"\n error += \" try larger r_a / smaller phi_0\"\n raise ValueError(error)\n else:\n self._set_alpha()\n if self.niter > self.max_mf_iter:\n self.converged=False\n error = \"Error: mass function did not converge, \"\n errpr += \" try larger phi_0\"\n raise ValueError(error)\n\n self.r0 = 1.0\n if (self.multi): self.r0j = sqrt(self.s2j)*self.r0\n\n # Solve Poisson equation to get the potential\n self._poisson(self.potonly)\n if (self.multi): self.Mj = self._Mjtot\n\n # Optional scaling\n if (self.scale): self._scale()\n\n # Optional computation of model properties in projection\n if (self.project): self._project()\n\n # Optional output\n if (self.verbose):\n print(\"\\n Model properties: \")\n print(\" ----------------- \")\n print(\" phi0 = %5.2f; g = %4.2f\"%(self.phi0, self.g))\n print(\" Converged = %s\"%(self.converged))\n if (self.potonly):\n print(\" M = %10.3f; U = %10.4f \"%(self.M, self.U))\n else:\n out1 = (self.M,self.U,self.K,-self.K/self.U,2*self.Kr/self.Kt)\n frm = \" M = %10.3e; U = %9.3e; K = %9.3e; Q = %6.4f; \"\n frm += \" 2Kr/Kt = %5.3f\"\n print(frm%out1)\n\n out2 = (self.rv/self.rh, self.rh/self.r0)\n out2 += (self.rt/self.r0, self.ra/self.rh)\n frm = \" rv/rh = %4.3f; rh/r0 = %6.3f; \"\n frm += \"rt/r0 = %7.3f; ra/rh = %7.3f\"\n print(frm%out2)\n\n def _set_kwargs(self, phi0, g, **kwargs):\n \"\"\" Set parameters and scales \"\"\"\n\n if (g<0): raise ValueError(\"Error: g must be larger or equal to 0\")\n if (g>=3.5): raise ValueError(\"Error: for g>=3.5 models are infinite\")\n\n self.phi0, self.g = phi0, g\n\n self.MS, self.RS, self.GS = 1e5, 3, 0.004302\n self.scale_radius = 'rh'\n self.scale = False\n self.project = False\n self.maxr = 1e10\n self.max_step = self.maxr\n self.diffcrit = 1e-8\n self.max_arg_exp = 700 # Maximum argument for exponent and hyp1f1 func\n self.max_mf_iter = 200 # Maximum number of iterations to find rho0j\n self.minimum_phi = 1e-8 # Stop criterion for integrator\n self.mf_iter_index = 0.5\n self.ode_atol = 1e-7\n self.ode_rtol = 1e-7\n self.nmbin, self.delta, self.eta = 1, 0.5, 0.0\n\n self.G = 9.0/(4.0*pi)\n self.mu, self.alpha = numpy.array([1.0]), numpy.array([1.0])\n self.s2 = 1.0\n self.s2j = numpy.array([1.0])\n self.niter = 0\n\n self.potonly, self.multi, self.verbose = [False]*3\n self.ra, self.ramax = 1e8, 1e8\n\n self.nstep=1\n self.converged=True\n self._interpolator_set=False\n\n if kwargs is not None:\n for key, value in kwargs.items():\n setattr(self, key, value)\n if 'mj' in kwargs and 'Mj' in kwargs:\n self.multi=True\n if len(self.Mj) is not len(self.mj):\n raise ValueError(\"Error: Mj and mj must have same length\")\n if ('mj' not in kwargs and 'Mj' in kwargs) or \\\n ('Mj' not in kwargs and 'mj' in kwargs):\n raise ValueError(\"Error: Supply both mj and Mj\")\n self.raj = numpy.array([self.ra])\n\n return\n\n def _logcheck(self, t, y):\n \"\"\" Logs steps and checks for final values \"\"\"\n\n if (t>0): self.r, self._y = numpy.r_[self.r, t], numpy.c_[self._y, y]\n self.nstep+=1\n return 0 if (y[0]>self.minimum_phi) else -1\n\n def _set_mass_function_variables(self):\n \"\"\" Multi-mass models: Set properties for each mass bin \"\"\"\n\n self.mmean = sum(self.mj*self.alpha) # equation (26) GZ15\n self.mu = self.mj/self.mmean\n self.s2j = self.mu**(-2*self.delta) # equation (24) GZ15\n self.raj = self.ra*self.mu**self.eta # equation (25) GZ15\n\n self.phi0j = self.phi0/self.s2j\n self.rhoint0 = numpy.zeros(self.nmbin)\n\n for j in range(self.nmbin):\n self.rhoint0[j] = self._rhoint(self.phi0j[j], 0, self.ramax)\n\n\n def _init_multi(self, mj, Mj):\n \"\"\"\n Initialise parameters and arrays for multi-mass system\n (Section 2.2 in GZ15)\n \"\"\"\n\n self.multi=True\n self.mj = numpy.array(mj)\n self.Mj = numpy.array(Mj)\n self.nmbin = len(mj)\n\n # Set trial value for alpha_j array, will be updated in iterations\n self.alpha = self.Mj/sum(self.Mj)\n self._set_mass_function_variables()\n self.diff = 1\n\n def _set_alpha(self):\n \"\"\" Set central rho_j for next iteration \"\"\"\n\n # The power of mf_iter_index < 1 is used. This is different from the\n # recommendation of Da Costa & Freeman 1976 and Gunn & Griffin 1979:\n # mf_iter_index = 1, a smaller value leads to better convergens for\n # low phi0 and wide MFs (i.e. when black-holes are considered), which\n # can fail with an index of 1 (see Section 2.2, GZ15)\n\n self.alpha *= (self.Mj/self._Mjtot)**self.mf_iter_index\n self.alpha/=sum(self.alpha)\n\n self._set_mass_function_variables()\n self.diff = sum((self._Mjtot/sum(self._Mjtot) -\n self.Mj/sum(self.Mj))**2)/len(self._Mjtot)\n self.niter+=1\n self.nstep=1\n if (self.verbose):\n fracd,Mjit=\"\", \"\"\n for j in range(self.nmbin):\n M1 = self._Mjtot[j]/sum(self._Mjtot)\n M2 = self.Mj[j]/sum(self.Mj)\n fracd=fracd+\"%7.3f \"%(( M1 - M2)/M2)\n Mjit=Mjit+\"%7.3f \"%(self._Mjtot[j]/sum(self._Mjtot))\n out = (self.niter, self.diff, self.converged, fracd, Mjit)\n frm = \" Iter %3i; diff = %8.1e; conv = %s;\"\n frm += \" frac diff=%s; Mjtot=%s\"\n print(frm%out)\n\n def _poisson(self, potonly):\n \"\"\" Solves Poisson equation \"\"\"\n # y = [phi, u_j, U, K_j], where u = -M(<r)/G\n\n # Initialize\n self.r = numpy.array([0])\n self._y = numpy.r_[self.phi0, numpy.zeros(self.nmbin+1)]\n if (not potonly): self._y = numpy.r_[self._y,numpy.zeros(2*self.nmbin)]\n self._y = numpy.r_[self._y, 0]\n\n # Ode solving using Runge-Kutta integator of order 4(5) 'dopri5'\n # (Hairor, Norsett& Wanner 1993)\n max_step = self.maxr if (potonly) else self.max_step\n sol = ode(self._odes)\n sol.set_integrator('dopri5',nsteps=1e6,max_step=max_step,\n atol=self.ode_atol,rtol=self.ode_rtol)\n sol.set_solout(self._logcheck)\n sol.set_f_params(potonly)\n sol.set_initial_value(self._y,0)\n sol.integrate(self.maxr)\n\n # Extrapolate to r_t:\n # phi(r) =~ a(r_t -r)\n # a = GM/r_t^2\n GM = -self.G*sum(sol.y[1:1+self.nmbin])\n p = 2*sol.y[0]*self.r[-1]/GM\n\n if (p<=0.5):\n rtfac = (1 - sqrt(1-2*p))/p\n self.rt = rtfac*self.r[-1] if (rtfac > 1) else 1.0000001*self.r[-1]\n else:\n self.rt = 1.000001*self.r[-1]\n\n # Set the converged flag to True if successful\n if (self.rt < self.maxr)&(sol.successful()):\n self.converged=True\n else:\n self.converged=False\n\n # Calculate the phase space volume occupied by the model\n dvol = (4./3*pi)**2*(self.rt**3-self.r[-1]**3)*0.5\n dvol *= (2*self._y[0,-1])**1.5\n self.volume = self._y[-1][-1]+dvol\n\n # Fill arrays needed if potonly=True\n self.r = numpy.r_[self.r, self.rt]\n self.rhat = self.r*1.0\n\n self.phihat = numpy.r_[self._y[0,:], 0]\n self.phi = self.phihat*1.0\n\n self._Mjtot = -sol.y[1:1+self.nmbin]/self.G\n\n self.M = sum(self._Mjtot)\n\n # Save the derivative of the potential for the potential interpolater\n dphidr = numpy.sum(self._y[1:1+self.nmbin,1:],axis=0)/self.r[1:-1]**2\n self.dphidrhat1 = numpy.r_[0, dphidr, -self.G*self.M/self.rt**2]\n\n self.A = self.alpha/(2*pi*self.s2j)**1.5/self.rhoint0\n\n if (not self.multi):\n self.mc = -numpy.r_[self._y[1,:], self._y[1,-1]]/self.G\n\n if (self.multi):\n self.mc = sum(-self._y[1:1+self.nmbin,:]/self.G)\n self.mc = numpy.r_[self.mc, self.mc[-1]]\n\n # Compute radii to be able to scale in case potonly=True\n self.U = self._y[1+self.nmbin,-1] - 0.5*self.G*self.M**2/self.rt\n\n # Get half-mass radius from cubic interpolation, because the half-mass\n # radius can be used as a scale length, this needs to be done\n # accurately, a linear interpolation does not suffice. Because the\n # density array is not known yet at this point, we need a temporary\n # evaluation of density in the vicinity of r_h\n ih = numpy.searchsorted(self.mc, 0.5*self.mc[-1])-1\n rhotmp=numpy.zeros(2)\n for j in range(self.nmbin):\n phi = self.phihat[ih:ih+2]/self.s2j[j]\n rhotmp += self.alpha[j]*self._rhohat(phi, self.r[ih:ih+2], j)\n drdm = 1./(4*pi*self.r[ih:ih+2]**2*rhotmp)\n rmc_and_derivs = numpy.vstack([[self.r[ih:ih+2]],[drdm]]).T\n self.rh = float(PiecewisePolynomial(self.mc[ih:ih+2], rmc_and_derivs,\n direction=1)(0.5*self.mc[-1]))\n\n self.rv = -0.5*self.G*self.M**2/self.U\n\n # Additional stuff\n if (not potonly):\n # Calculate kinetic energy (total, radial, tangential)\n self.K = numpy.sum(sol.y[2+self.nmbin:2+2*self.nmbin])\n self.Kr = numpy.sum(sol.y[2+2*self.nmbin:2+3*self.nmbin])\n self.Kt = self.K - self.Kr\n\n # Calculate density and velocity dispersion components\n if (not self.multi):\n self.rhohat = self._rhohat(self.phihat, self.r, 0)\n self.rho = self.rhohat*1.0\n self.v2, self.v2r, self.v2t = \\\n self._get_v2(self.phihat, self.r, self.rhohat, 0)\n\n # For multi-mass models, calculate quantities for each mass bin\n if (self.multi):\n for j in range(self.nmbin):\n phi = self.phihat/self.s2j[j]\n rhohatj = self._rhohat(phi, self.r, j)\n v2j, v2rj, v2tj = self._get_v2(phi, self.r, rhohatj, j)\n v2j, v2rj, v2tj = (q*self.s2j[j] for q in [v2j,v2rj,v2tj])\n betaj = self._beta(self.r, v2rj, v2tj)\n\n kj = self._y[2+self.nmbin+j,:]\n krj = self._y[2+2*self.nmbin+j,:]\n ktj = kj - krj\n\n mcj = -numpy.r_[self._y[1+j,:], self._y[1+j,-1]]/self.G\n rhj = numpy.interp(0.5*mcj[-1], mcj, self.r)\n\n if (j==0):\n self.rhohatj = rhohatj\n self.rhohat = self.alpha[0] * self.rhohatj\n self.v2j, self.v2rj, self.v2tj = v2j, v2rj, v2tj\n self.v2 = self._Mjtot[j]*v2j/self.M\n self.v2r = self._Mjtot[j]*v2rj/self.M\n self.v2t = self._Mjtot[j]*v2tj/self.M\n\n self.betaj = betaj\n self.kj, self.krj, self.ktj = kj, krj, ktj\n self.Kj, self.Krj = kj[-1], krj[-1]\n self.ktj = self.kj - self.krj\n self.Ktj = self.Kj - self.Krj\n self.rhj, self.mcj = rhj, mcj\n else:\n self.rhohatj = numpy.vstack((self.rhohatj, rhohatj))\n self.rhohat += self.alpha[j]*rhohatj\n\n self.v2j = numpy.vstack((self.v2j, v2j))\n self.v2rj = numpy.vstack((self.v2rj, v2rj))\n self.v2tj = numpy.vstack((self.v2tj, v2tj))\n self.v2 += self._Mjtot[j]*v2j/self.M\n self.v2r += self._Mjtot[j]*v2rj/self.M\n self.v2t += self._Mjtot[j]*v2tj/self.M\n\n self.betaj = numpy.vstack((self.betaj, betaj))\n self.kj = numpy.vstack((self.kj, kj))\n self.krj = numpy.vstack((self.krj, krj))\n self.ktj = numpy.vstack((self.ktj, ktj))\n self.Kj = numpy.r_[self.Kj, kj[-1]]\n self.Krj = numpy.r_[self.Krj, krj[-1]]\n self.Ktj = numpy.r_[self.Ktj, ktj[-1]]\n self.rhj = numpy.r_[self.rhj,rhj]\n self.mcj = numpy.vstack((self.mcj, mcj))\n\n self.rho = self.rhohat*1.0\n self.rhoj = self.rhohatj*1.0\n\n # Calculate anisotropy profile (equation 32 of GZ15)\n self.beta = self._beta(self.r, self.v2r, self.v2t)\n\n\n def _rhohat(self, phi, r, j):\n \"\"\"\n Wrapper for _rhoint when either: both phi or r are arrays, or both\n are scalar\n \"\"\"\n if not hasattr(phi,\"__len__\"): phi = numpy.array([phi])\n if not hasattr(r,\"__len__\"): r = numpy.array([r])\n\n n = max([phi.size, r.size])\n rhohat = numpy.zeros(n)\n\n for i in range(n):\n if (phi[i]<self.max_arg_exp) or (numpy.isnan(phi[i])):\n rhohat[i] = self._rhoint(phi[i], r[i], self.raj[j])\n rhohat[i] /= self.rhoint0[j]\n else:\n # For large phi compute the ratio in one go (Section 4.1, GZ15)\n rhohat[i] = exp(phi[i]-self.phi0j[j]) if (self.multi) else 0\n\n return rhohat\n\n def _rhoint(self, phi, r, ra):\n \"\"\"\n Dimensionless density integral as a function of phi and r (scalar)\n \"\"\"\n\n # Isotropic case first (equation 8, GZ15)\n rhoint = exp(phi)*gammainc(self.g + 1.5, phi)\n\n # Anisotropic case, add r-dependent part explicitly (equation 11, GZ15)\n if (self.ra < self.ramax) and (phi>0) and (r>0):\n p, g = r/ra, self.g\n p2 = p**2\n g3, g5, fp2 = g+1.5, g+2.5, phi*p2\n\n func = hyp1f1(1, g5, -fp2) if fp2 < self.max_arg_exp else g3/fp2\n rhoint += p2*phi**(g+1.5)*func/gamma(g5)\n rhoint /= (1+p2)\n return rhoint\n\n def _get_v2(self, phi, r, rho, j):\n v2 = numpy.zeros(r.size)\n v2r, v2t = numpy.zeros(r.size), numpy.zeros(r.size)\n for i in range(r.size-1):\n v2[i], v2r[i], v2t[i] = self._rhov2int(phi[i], r[i], self.raj[j])\n v2[i] /= rho[i]*self.rhoint0[j]\n v2r[i] /= rho[i]*self.rhoint0[j]\n v2t[i] /= rho[i]*self.rhoint0[j]\n\n return v2, v2r, v2t\n\n def _rhov2int(self, phi, r, ra):\n \"\"\"Compute dimensionless pressure integral for phi, r \"\"\"\n\n # Isotropic case first (equation 9, GZ15)\n rhov2r = exp(phi)*gammainc(self.g + 2.5, phi)\n rhov2 = 3*rhov2r\n rhov2t = 2*rhov2r\n\n # Add anisotropy, add parts depending explicitly on r\n # (see equations 12, 13, and 14 of GZ15)\n if (ra < self.ramax) and (r>0) and (phi>0):\n p, g = r/ra, self.g\n p2 = p**2\n p12 = 1+p2\n g3, g5, g7, fp2 = g+1.5, g+2.5, g+3.5, phi*p2\n\n P1 = p2*phi**g5/gamma(g7)\n H1 = hyp1f1(1, g7, -fp2) if fp2 <self.max_arg_exp else g5/fp2\n H2 = hyp1f1(2, g7, -fp2) if fp2 <self.max_arg_exp else g5*g3/fp2**2\n\n rhov2r += P1*H1\n rhov2r /= p12\n\n rhov2t /= p12\n rhov2t += 2*P1*(H1/p12 + H2)\n rhov2t /= p12\n\n rhov2 = rhov2r + rhov2t\n return rhov2, rhov2r, rhov2t\n\n def _beta(self, r, v2r, v2t):\n \"\"\" Calculate the anisotropy profile \"\"\"\n\n beta = numpy.zeros(r.size)\n if (self.ra < self.ramax):\n c = (v2r>0.)\n # Equation (32), GZ15\n beta[c] = 1.0 - 0.5*v2t[c]/v2r[c]\n return beta\n\n def _odes(self, x, y, potonly):\n \"\"\" Solve ODEs \"\"\"\n # y = [phi, u_j, U, K_j], where u = -M(<r)/G\n if (self.multi):\n derivs = [numpy.sum(y[1:1+self.nmbin])/x**2] if (x>0) else [0]\n for j in range(self.nmbin):\n phi = y[0]/self.s2j[j]\n derivs.append(-9.0*x**2*self.alpha[j]*self._rhohat(phi, x, j))\n\n dUdx = 2.0*pi*numpy.sum(derivs[1:1+self.nmbin])*y[0]/9.\n else:\n derivs = [y[1]/x**2] if (x>0) else [0]\n derivs.append(-9.0*x**2*self._rhohat(y[0], x, 0))\n\n dUdx = 2.0*pi*derivs[1]*y[0]/9.\n\n derivs.append(dUdx)\n\n # Calculate pressure tensor components for all the mass bins\n if (not potonly): #dK_j/dx\n rhov2j, rhov2rj = [], []\n for j in range(self.nmbin):\n rv2, rv2r, rv2t = self._rhov2int(y[0]/self.s2j[j],\n x, self.raj[j])\n P = self.alpha[j]*self.s2j[j]*2*pi*x**2*rv2/self.rhoint0[j]\n rhov2j.append(P)\n\n Pr = self.alpha[j]*self.s2j[j]*2*pi*x**2*rv2r/self.rhoint0[j]\n rhov2rj.append(Pr)\n\n for j in range(self.nmbin):\n derivs.append(rhov2j[j])\n\n for j in range(self.nmbin):\n derivs.append(rhov2rj[j])\n\n dVdvdr = (4*pi)**2*x**2 * (2*y[0])**1.5/3 if (x>0) and (y[0]>0) else 0\n derivs.append(dVdvdr)\n\n return derivs\n\n def _setup_phi_interpolator(self):\n \"\"\" Setup interpolater for phi, works on scalar and arrays \"\"\"\n\n # Generate piecewise 3th order polynomials to connect the discrete\n # values of phi obtained from from Poisson, using dphi/dr\n self._interpolator_set = True\n\n if (self.scale):\n phi_and_derivs = numpy.vstack([[self.phi],[self.dphidr1]]).T\n else:\n phi_and_derivs = numpy.vstack([[self.phihat],[self.dphidrhat1]]).T\n self._phi_poly = PiecewisePolynomial(self.r,phi_and_derivs,direction=1)\n\n def _scale(self):\n \"\"\" Scales the model to the units set in the input: GS, MS, RS \"\"\"\n\n Mstar = self.MS/self.M\n Gstar = self.GS/self.G\n if (self.scale_radius=='rh'): Rstar = self.RS/self.rh\n if (self.scale_radius=='rv'): Rstar = self.RS/self.rv\n v2star = Gstar*Mstar/Rstar\n\n # Update the scales that define the system (see Section 2.1.2 of GZ15)\n\n self.G *= Gstar\n self.rs = Rstar\n self.s2 *= v2star\n self.s2j *= v2star\n\n # Anisotropy radii\n self.ra, self.raj, self.ramax = (q*Rstar for q in [self.ra,\n self.raj,\n self.ramax])\n\n # Scale all variable needed when run with potonly=True\n self.r, self.r0, self.rt = (q*Rstar for q in [self.rhat,\n self.r0, self.rt])\n self.rh, self.rv = (q*Rstar for q in [self.rh,self.rv])\n\n self.M *= Mstar\n self.phi = self.phihat * v2star\n self.dphidr1 = self.dphidrhat1 * v2star/Rstar\n self.mc *= Mstar\n self.U *= Mstar*v2star\n self.A *= Mstar/(v2star**1.5*Rstar**3)\n self.volume *= v2star**1.5*Rstar**3\n\n if (self.multi):\n self.Mj *= Mstar\n self.r0j *= Rstar\n\n # Scale density, velocity dispersion components, kinetic energy\n if (not self.potonly):\n self.rho = self.rhohat*Mstar/Rstar**3\n self.v2, self.v2r, self.v2t = (q*v2star for q in [self.v2,\n self.v2r,self.v2t])\n self.K,self.Kr,self.Kt=(q*Mstar*v2star for q in [self.K, self.Kr,\n self.Kt])\n\n if (self.multi):\n self.rhoj = self.rhohatj * Mstar/Rstar**3\n for j in range(self.nmbin):\n self.rhoj[j] *= self.alpha[j]\n self.mcj *= Mstar\n self.rhj *= Rstar\n self.v2j,self.v2rj,self.v2tj=(q*v2star for q in\n [self.v2j, self.v2rj,self.v2tj])\n\n self.kj *= Mstar*v2star\n self.Krj *= Mstar*v2star\n self.Ktj *= Mstar*v2star\n self.Kj *= Mstar*v2star\n\n def _tonp(self, q):\n q = numpy.array([q]) if not hasattr(q,\"__len__\") else numpy.array(q)\n return q\n\n def _project(self):\n \"\"\"\n Compute projected mass density (Sigma) and projected <v2> profiles\n \"\"\"\n\n # Initialise the projected quantities:\n # R is the projected (2d) distance from the center, Sigma is the\n # projected density, v2z is the line-of-sight velocity dispersion,\n # v2R and v2T are the radial and tangential velocity dispersion\n # components projected on the plane of the sky\n\n # Initialise some arrays\n R = self.r\n Sigma = numpy.zeros(self.nstep)\n v2z = numpy.zeros(self.nstep)\n v2R = numpy.zeros(self.nstep)\n v2T = numpy.zeros(self.nstep)\n mcp = numpy.zeros(self.nstep)\n\n if (self.multi):\n Sigmaj = numpy.zeros((self.nmbin, self.nstep))\n v2zj = numpy.zeros((self.nmbin, self.nstep))\n v2Rj = numpy.zeros((self.nmbin, self.nstep))\n v2Tj = numpy.zeros((self.nmbin, self.nstep))\n mcpj = numpy.zeros((self.nmbin, self.nstep)) # TBD\n\n # Project model properties for each R\n for i in range(self.nstep-1):\n c = (self.r >= R[i])\n r = self.r[c]\n z = sqrt(abs(r**2 - R[i]**2)) # avoid small neg. values\n\n Sigma[i] = 2.0*simps(self.rho[c], x=z)\n betaterm1 = 1 if i==0 else 1-self.beta[c]*R[i]**2/self.r[c]**2\n betaterm2 = 1 if i==0 else 1-self.beta[c]*(1-R[i]**2/self.r[c]**2)\n v2z[i] = abs(2.0*simps(betaterm1*self.rho[c]*self.v2r[c], x=z))\n v2z[i] /= Sigma[i]\n\n v2R[i] = abs(2.0*simps(betaterm2*self.rho[c]*self.v2r[c], x=z))\n v2R[i] /= Sigma[i]\n\n v2T[i] = abs(2.0*simps(self.rho[c]*self.v2t[c]/2., x=z)/Sigma[i])\n\n # Cumulative mass in projection\n if (i>0):\n x = self.r[i-1:i+1]\n mcp[i] = mcp[i-1] + 2*pi*simps(x*Sigma[i-1:i+1], x=x)\n mcp[-1] = mcp[-2]\n\n # Radius containing half the mass in projection\n self.rhp = numpy.interp(0.5*mcp[-1], mcp, self.r)\n\n if (self.multi):\n for j in range(self.nmbin):\n Sigmaj[j,i] = 2.0*simps(self.rhoj[j,c], x=z)\n if (i==0):\n betaterm1 = 1\n betaterm2 = 1\n else:\n betaterm1 = 1-self.betaj[j,c]*R[i]**2/self.r[c]**2\n betaterm2 = 1-self.betaj[j,c]*(1-R[i]**2)/self.r[c]**2\n\n v2int = simps(betaterm1*self.rhoj[j,c]*self.v2rj[j,c], x=z)\n v2zj[j,i] = abs(2.0*v2int)\n v2zj[j,i] /= Sigmaj[j,i]\n\n v2int = simps(betaterm2*self.rhoj[j,c]*self.v2rj[j,c], x=z)\n v2Rj[j,i] = abs(2.0*v2int)\n v2Rj[j,i] /= Sigmaj[j,i]\n\n v2Tj[j,i] = abs(simps(self.rhoj[j,c]*self.v2tj[j,c], x=z))\n v2Tj[j,i] /= Sigmaj[j,i]\n\n self.R, self.Sigma = R, Sigma\n self.v2z, self.v2R, self.v2T = v2z, v2R, v2T\n self.mcp = mcp\n\n # Compute half-mass radii in projection\n\n if (self.multi):\n self.Sigmaj = Sigmaj\n self.v2zj, self.v2RjR, self.v2Tj = v2zj, v2Rj, v2Tj\n return\n\n def interp_phi(self, r):\n \"\"\" Returns interpolated potential at r, works on scalar and arrays \"\"\"\n\n if not hasattr(r,\"__len__\"): r = numpy.array([r])\n if (not self._interpolator_set): self._setup_phi_interpolator()\n\n phi = numpy.zeros([r.size])\n inrt = (r<self.rt)\n # Use 3th order polynomials to interp, using phi'\n if (sum(inrt)>0): phi[inrt] = self._phi_poly(r[inrt])\n return phi\n\n def df(self, *arg):\n \"\"\"\n Returns the value of the normalised DF at a given position in phase\n space, can only be called after solving Poisson's equation\n\n Arguments can be:\n - r, v (isotropic single-mass models)\n - r, v, j (isotropic multi-mass models)\n - r, v, theta, j (anisotropic models)\n - x, y, z, vx, vy, vz, j (all models)\n\n Here j specifies the mass bin, j=0 for single mass\n Works with scalar and array input\n\n \"\"\"\n\n if (len(arg)<2) or (len(arg)==5) or (len(arg)==6) or (len(arg)>7):\n raise ValueError(\"Error: df needs 2, 3, 4 or 7 arguments\")\n\n if (len(arg)<=3) and (self.ra<self.ramax):\n raise ValueError(\"Error: model is anisotropy, more input needed\")\n\n if len(arg) == 2:\n r, v = (self._tonp(q) for q in arg)\n j = 0\n\n if len(arg) == 3:\n r, v = (self._tonp(q) for q in arg[:-1])\n j = arg[-1]\n\n if len(arg) == 4:\n r, v, theta = (self._tonp(q) for q in arg[:-1])\n j = arg[-1]\n\n if len(arg) < 7: r2, v2 = r**2, v**2\n\n if len(arg) == 7:\n x, y, z, vx, vy, vz = (self._tonp(q) for q in arg[:-1])\n j = arg[-1]\n r2 = x**2 + y**2 + z**2\n v2 = vx**2 + vy**2 + vz**2\n r, v = sqrt(r2), sqrt(v2)\n\n # Interpolate potential and calculate escape velocity as a\n # function of the distance from the center\n phi = self.interp_phi(r)\n vesc2 = 2.0*phi # Note: phi > 0\n\n DF = numpy.zeros([max(r.size, v.size)])\n\n if (len(r) == len(v2)):\n c = (r<self.rt) and (v2<vesc2)\n\n if (len(r) == 1) and (len(v2) > 1):\n c = (v2<vesc2)\n if (r>self.rt): c=False\n\n if (len(r) > 1) and (len(v2) == 1):\n c = (r<self.rt) and (numpy.zeros(len(r))+v2<vesc2)\n\n if (sum(c)>0):\n # Compute the DF: equation (1), GZ15\n\n E = (phi-0.5*v2)/self.s2j[j] # Dimensionless positive energy\n DF[c] = exp(E[c])\n\n if (self.g>0): DF[c] *= gammainc(self.g, E[c])\n\n if (len(arg)==7): J2 = v2*r2 - (x*vx + y*vy + z*vz)**2\n if (len(arg)==4): J2 = sin(theta)**2*v2*r2\n if (len(arg)<=3): J2 = numpy.zeros(len(c))\n\n DF[c] *= exp(-J2[c]/(2*self.raj[j]**2*self.s2j[j]))\n\n DF[c] *= self.A[j]\n\n else:\n DF = numpy.zeros(max(len(r),len(v)))\n\n return DF\n\n\n\n",
"\"\"\"\n Evolve a population of N stars.\n initial mass function between Mmin and Mmax and with stellar evolution with\n metalicity z.\n\"\"\"\nfrom __future__ import print_function\nimport sys\nimport numpy\nfrom amuse.lab import *\nfrom amuse.units.optparse import OptionParser\nfrom matplotlib import pyplot\nfrom amuse.plot import scatter, xlabel, ylabel\n\nfrom amuse.community.seba.interface import SeBa\n \ndef main(N=10, t_end=10|units.Myr, dt=1|units.Myr, filename=\"stellar.hdf5\", \n Mmin=1.0|units.MSun, Mmax= 100|units.MSun, z=0.02, C=\"SeBa\"):\n\n if C.find(\"SeBa\")>=0:\n print(\"SeBa\")\n stellar = SeBa()\n elif C.find(\"SSE\")>=0:\n print(\"SSE\")\n stellar = SSE()\n elif C.find(\"MESA\")>=0:\n stellar = MESA()\n elif C.find(\"EVtwin\")>=0:\n stellar = EVtwin()\n else:\n print(\"No stellar model specified.\")\n return\n stellar.parameters.metallicity = z\n\n mZAMS = new_salpeter_mass_distribution(N, Mmin, Mmax)\n mZAMS = mZAMS.sorted()\n bodies = Particles(mass=mZAMS)\n stellar.particles.add_particles(bodies)\n stellar.commit_particles()\n\n write_set_to_file(stellar.particles, filename, 'hdf5')\n\n Mtot_init = stellar.particles.mass.sum()\n time = 0.0 | t_end.unit\n while time < t_end:\n time += dt\n\n stellar.evolve_model(time)\n write_set_to_file(stellar.particles, filename, 'hdf5')\n\n Mtot = stellar.particles.mass.sum()\n\n print(\"T=\", time, end=' ') \n print(\"M=\", Mtot, \"dM[SE]=\", Mtot/Mtot_init) #, stellar.particles[0].stellar_type\n\n T = [] \n L = [] \n r = []\n import math\n for si in stellar.particles:\n T.append(math.log10(si.temperature.value_in(units.K)))\n L.append(math.log10(si.luminosity.value_in(units.LSun)))\n r.append(1.0+10*si.radius.value_in(units.RSun))\n stellar.stop()\n pyplot.xlim(4.5, 3.3)\n pyplot.ylim(-4.0, 3.0)\n scatter(T, L, s=r)\n pyplot.xlabel(\"$log_{10}(T/K)$\")\n pyplot.ylabel(\"$log_{10}(L/L_\\odot)$\")\n pyplot.show()\n \ndef new_option_parser():\n result = OptionParser()\n result.add_option(\"-C\", dest=\"C\", default = \"SeBa\",\n help=\"stellar evolution code [SeBa]\")\n result.add_option(\"-d\", unit=units.Myr,\n dest=\"dt\", type=\"float\", default = 100.0 |units.Myr,\n help=\"diagnostics time step [%defailt]\")\n result.add_option(\"-f\", dest=\"filename\", default = \"stellar.hdf5\",\n help=\"output filename [stellar.hdf5]\")\n result.add_option(\"-N\", dest=\"N\", type=\"int\",default = 100,\n help=\"number of stars [%defailt]\")\n result.add_option(\"-M\", unit=units.MSun,\n dest=\"Mmax\", type=\"float\",default = 100|units.MSun,\n help=\"maximal stellar mass [%defailt]\")\n result.add_option(\"-m\", unit=units.MSun,\n dest=\"Mmin\", type=\"float\",default = 1.0 |units.MSun,\n help=\"minimal stellar mass [%defailt]\")\n result.add_option(\"-t\", unit=units.Myr,\n dest=\"t_end\", type=\"float\", default = 100.0 |units.Myr,\n help=\"end time of the simulation [%defailt]\")\n result.add_option(\"-z\", dest=\"z\", type=\"float\", default = 0.02,\n help=\"metalicity [%defailt]\")\n return result\n\nif __name__ in ('__main__', '__plot__'):\n o, arguments = new_option_parser().parse_args()\n main(**o.__dict__)\n\n",
"\"\"\"\norbital element conversion and utility functions\n\nthis module provides:\n\ngenerate_binaries\norbital_elements\nget_orbital_elements_from_binary\nget_orbital_elements_from_binaries\nget_orbital_elements_from_arrays\n\nand the following deprecated functions (assume input\nor output angle floats to be degrees):\n\nnew_binary_from_orbital_elements\norbital_elements_from_binary\norbital_elements_for_rel_posvel_arrays\n\n\"\"\"\n\nimport numpy\n\nimport warnings\n\nfrom amuse.units import units, nbody_system\nfrom amuse.units.trigo import cos, sin, arccos, arctan2\nfrom amuse.datamodel import Particles, Particle\n\nfrom amuse.units.quantities import to_quantity, VectorQuantity\n\n\ndef newton(f, x0, fprime=None, args=(), tol=1.48e-8, maxiter=50):\n if fprime is None:\n warnings.warn(\"provide fprime\")\n return x0\n i = 0\n x = x0\n while (i < maxiter):\n fv = f(x, *args)\n dfv = fprime(x, *args)\n if(dfv == 0):\n return x0, -2\n delta = -fv/dfv\n if(abs(delta) < tol):\n return x+delta, 0\n x = x+delta\n i = i+1\n return x, -1\n\n\ndef true_anomaly_from_eccentric_anomaly(E, e):\n return 2*arctan2((1+e)**0.5*sin(E/2), (1-e)**0.5*cos(E/2))\n\n\ndef equal_length_array_or_scalar(\n array, length=1, mode=\"continue\"\n ):\n \"\"\"\n Returns 'array' if its length is equal to 'length'. If this is not the\n case, returns an array of length 'length' with values equal to the first\n value of the array (or if 'array' is a scalar, that value. If mode is\n \"warn\", issues a warning if this happens; if mode is \"exception\" raises an\n exception in this case.\n \"\"\"\n try:\n array_length = len(array)\n if array_length == length:\n return array\n else:\n if mode == \"warn\":\n warnings.warn(\"Length of array is not equal to %i. Using only\\\n the first value.\" % length)\n try:\n unit = array.unit\n value = array[0].value_in(unit)\n except:\n unit = units.none\n value = array[0]\n array = VectorQuantity(\n array=numpy.ones(length) * value,\n unit=unit,\n )\n return array\n elif mode == \"exception\":\n raise Exception(\"Length of array is not equal to %i. This is\\\n not supported.\" % length)\n except:\n try:\n unit = array.unit\n value = array.value_in(unit)\n except:\n unit = units.none\n value = array\n array = VectorQuantity(\n array=numpy.ones(length) * value,\n unit=unit,\n )\n if mode == \"warn\":\n warnings.warn(\"Using single value for all cases.\")\n return array\n\n\ndef center_of_mass_array(\n vectors,\n primary_mass,\n secondary_mass,\n ):\n \"\"\"\n Returns array of center_of_mass vectors, where primaries are considered to\n be at (0,0,0) and secondaries at 'vectors'.\n \"\"\"\n total_mass = (primary_mass + secondary_mass).reshape(\n (len(primary_mass), 1)\n )\n center_of_mass_array = (\n (\n vectors\n * secondary_mass.reshape(\n (len(secondary_mass), 1)\n )\n )\n / total_mass\n )\n return center_of_mass_array\n\n\ndef orbital_period_to_semimajor_axis(\n T, M1, M2, G=nbody_system.G\n ):\n mu = G * (M1 + M2)\n semi_major_axis = ((T / (2*numpy.pi))**2 * mu)**(1./3.)\n\n return semi_major_axis\n\n\ndef rel_posvel_arrays_from_orbital_elements(\n primary_mass,\n secondary_mass,\n semi_major_axis,\n eccentricity=0 | units.rad,\n true_anomaly=0 | units.rad,\n inclination=0 | units.rad,\n longitude_of_the_ascending_node=0 | units.rad,\n argument_of_periapsis=0 | units.rad,\n G=nbody_system.G\n ):\n \"\"\"\n Returns relative positions/velocities for secondaries orbiting primaries.\n If primary_mass is a scalar, assumes the same primary for all secondaries.\n \"\"\"\n try:\n number_of_secondaries = len(secondary_mass)\n except:\n number_of_secondaries = 1\n\n # arrays need to be equal to number of secondaries, or have just one value\n primary_mass = equal_length_array_or_scalar(\n primary_mass, length=number_of_secondaries)\n semi_major_axis = equal_length_array_or_scalar(\n semi_major_axis, length=number_of_secondaries)\n eccentricity = equal_length_array_or_scalar(\n eccentricity, length=number_of_secondaries)\n true_anomaly = equal_length_array_or_scalar(\n true_anomaly, length=number_of_secondaries)\n inclination = equal_length_array_or_scalar(\n inclination, length=number_of_secondaries)\n longitude_of_the_ascending_node = equal_length_array_or_scalar(\n longitude_of_the_ascending_node, length=number_of_secondaries)\n argument_of_periapsis = equal_length_array_or_scalar(\n argument_of_periapsis, length=number_of_secondaries)\n\n cos_true_anomaly = cos(true_anomaly)\n sin_true_anomaly = sin(true_anomaly)\n\n cos_inclination = cos(inclination)\n sin_inclination = sin(inclination)\n\n cos_arg_per = cos(argument_of_periapsis)\n sin_arg_per = sin(argument_of_periapsis)\n\n cos_long_asc_nodes = cos(longitude_of_the_ascending_node)\n sin_long_asc_nodes = sin(longitude_of_the_ascending_node)\n\n # alpha is a unit vector directed along the line of node\n alphax = (\n cos_long_asc_nodes*cos_arg_per\n - sin_long_asc_nodes*sin_arg_per*cos_inclination\n )\n alphay = (\n sin_long_asc_nodes*cos_arg_per\n + cos_long_asc_nodes*sin_arg_per*cos_inclination\n )\n alphaz = sin_arg_per*sin_inclination\n alpha = numpy.array([alphax, alphay, alphaz])\n\n # beta is a unit vector perpendicular to alpha and the orbital angular\n # momentum vector\n betax = (\n - cos_long_asc_nodes*sin_arg_per\n - sin_long_asc_nodes*cos_arg_per*cos_inclination\n )\n betay = (\n - sin_long_asc_nodes*sin_arg_per\n + cos_long_asc_nodes*cos_arg_per*cos_inclination\n )\n betaz = cos_arg_per*sin_inclination\n beta = numpy.array([betax, betay, betaz])\n\n # Relative position and velocity\n separation = ( # Compute the relative separation\n semi_major_axis*(1.0 - eccentricity**2)\n / (1.0 + eccentricity*cos_true_anomaly)\n )\n position_vector = (\n separation*cos_true_anomaly*alpha\n + separation*sin_true_anomaly*beta\n ).T\n velocity_tilde = (\n (\n G*(primary_mass + secondary_mass)\n / (semi_major_axis*(1.0 - eccentricity**2))\n )**0.5\n ) # Common factor\n velocity_vector = (\n -1.0 * velocity_tilde * sin_true_anomaly * alpha\n + velocity_tilde*(eccentricity + cos_true_anomaly)*beta\n ).T\n\n return position_vector, velocity_vector\n\n\ndef generate_binaries(\n primary_mass,\n secondary_mass,\n semi_major_axis,\n eccentricity=0 | units.rad,\n true_anomaly=0 | units.rad,\n inclination=0 | units.rad,\n longitude_of_the_ascending_node=0 | units.rad,\n argument_of_periapsis=0 | units.rad,\n G=nbody_system.G\n ):\n \"\"\"\n returns two particlesets, which contain the primaries and the secondaries\n in binary pairs.\n \"\"\"\n mass_unit = primary_mass.unit\n try:\n number_of_primaries = len(primary_mass)\n except:\n number_of_primaries = 1\n primary_mass = numpy.array(\n [primary_mass.value_in(mass_unit)]\n ) | mass_unit\n try:\n number_of_secondaries = len(secondary_mass)\n except:\n number_of_secondaries = 1\n secondary_mass = numpy.array(\n [secondary_mass.value_in(mass_unit)]\n ) | mass_unit\n\n # mass arrays need to be the same length\n if number_of_secondaries != number_of_primaries:\n raise Exception(\"The number of primaries is not the same as the number\\\n of secondaries, this is not supported.\")\n\n position_vector, velocity_vector = rel_posvel_arrays_from_orbital_elements(\n primary_mass,\n secondary_mass,\n semi_major_axis,\n eccentricity=eccentricity,\n true_anomaly=true_anomaly,\n inclination=inclination,\n longitude_of_the_ascending_node=longitude_of_the_ascending_node,\n argument_of_periapsis=argument_of_periapsis,\n G=G\n )\n number_of_primaries\n\n primaries = Particles(number_of_primaries)\n secondaries = Particles(number_of_secondaries)\n primaries.mass = primary_mass\n secondaries.mass = secondary_mass\n\n centers_of_mass = center_of_mass_array(\n position_vector, primary_mass, secondary_mass)\n centers_of_mass_velocity = center_of_mass_array(\n velocity_vector, primary_mass, secondary_mass)\n\n primaries.position = - centers_of_mass\n secondaries.position = position_vector - centers_of_mass\n primaries.velocity = - centers_of_mass_velocity\n secondaries.velocity = velocity_vector - centers_of_mass_velocity\n return primaries, secondaries\n\n\ndef new_binary_from_orbital_elements(\n mass1,\n mass2,\n semimajor_axis,\n eccentricity=0,\n true_anomaly=0 | units.deg,\n inclination=0 | units.deg,\n longitude_of_the_ascending_node=0 | units.deg,\n argument_of_periapsis=0 | units.deg,\n G=nbody_system.G\n ):\n \"\"\"\n returns a two-particle Particle set, with the second particle's position\n and velocities computed from the input orbital elements.\n inclination is given between 0 and 180 deg.\n angles are assumed to be in deg if no unit is given.\n \"\"\"\n def angle_with_unit(angle, default_unit=units.deg):\n try:\n default_unit = angle.unit\n except:\n angle = angle | default_unit\n return angle\n\n # If no unit is given for angles, assume they are in degrees\n true_anomaly = angle_with_unit(true_anomaly, default_unit=units.deg)\n inclination = angle_with_unit(inclination, default_unit=units.deg)\n argument_of_periapsis = angle_with_unit(\n argument_of_periapsis,\n default_unit=units.deg\n )\n longitude_of_the_ascending_node = angle_with_unit(\n longitude_of_the_ascending_node,\n default_unit=units.deg\n )\n primary, secondary = generate_binaries(\n mass1, mass2, semimajor_axis,\n eccentricity=eccentricity,\n true_anomaly=true_anomaly,\n inclination=inclination,\n longitude_of_the_ascending_node=longitude_of_the_ascending_node,\n argument_of_periapsis=argument_of_periapsis,\n G=G\n )\n\n result = Particles()\n result.add_particle(primary[0])\n result.add_particle(secondary[0])\n return result\n\n\ndef get_orbital_elements_from_binary(binary, G=nbody_system.G):\n \"\"\"\n Function that computes orbital elements from given two-particle set.\n Elements are computed for the second particle in this set and the\n return values are: mass1, mass2, semimajor axis, eccentricity,\n cosine of true anomaly, cosine of inclination, cosine of the\n longitude of the ascending node and the cosine of the argument of\n pericenter. In case of a perfectly circular orbit the true anomaly\n and argument of pericenter cannot be determined; in this case the\n return values are 1.0 for both cosines.\n \"\"\"\n primaries = Particles()\n secondaries = Particles()\n if len(binary) > 2:\n raise Exception(\"expects binary or single part\")\n elif len(binary) == 2:\n primaries.add_particle(binary[0])\n secondaries.add_particle(binary[1])\n else:\n # FIXME: in case of one particle, what do we calculate the orbit of?\n # The method below is what was default before.\n primaries.add_particle(binary[0])\n primaries[0].position *= 0\n primaries[0].velocity *= 0\n secondaries.add_particle(Particle())\n secondaries[0].mass = 0 * primaries[0].mass\n secondaries[0].position = binary.position\n secondaries[0].velocity = binary.velocity\n\n (\n mass1, mass2, semimajor_axis, eccentricity, true_anomaly,\n inclination, long_asc_node, arg_per\n ) = get_orbital_elements_from_binaries(primaries, secondaries, G=G)\n return (\n mass1[0], mass2[0], semimajor_axis[0], eccentricity[0],\n true_anomaly[0], inclination[0], long_asc_node[0], arg_per[0])\n\n\ndef orbital_elements_from_binary(binary, G=nbody_system.G):\n (\n mass1, mass2, semimajor_axis, eccentricity, true_anomaly,\n inclination, long_asc_node, arg_per\n ) = get_orbital_elements_from_binary(binary, G=G)\n return (\n mass1, mass2, semimajor_axis, eccentricity,\n true_anomaly.value_in(units.deg),\n inclination.value_in(units.deg),\n long_asc_node.value_in(units.deg),\n arg_per.value_in(units.deg))\n\n\ndef get_orbital_elements_from_binaries(\n primaries, secondaries, G=nbody_system.G):\n \"\"\"\n Function that computes orbital elements from given primaries and\n secondaries.\n Elements are computed for the second particle in this set and the\n return values are: mass1, mass2, semimajor axis, eccentricity,\n cosine of true anomaly, cosine of inclination, cosine of the\n longitude of the ascending node and the cosine of the argument of\n pericenter. In case of a perfectly circular orbit the true anomaly\n and argument of pericenter cannot be determined; in this case the\n return values are 1.0 for both cosines.\n \"\"\"\n\n position = secondaries.position - primaries.position\n velocity = secondaries.velocity - primaries.velocity\n mass1 = primaries.mass\n mass2 = secondaries.mass\n total_mass = mass1 + mass2\n semimajor_axis, eccentricity, true_anomaly, inclination, long_asc_node, \\\n arg_per = get_orbital_elements_from_arrays(\n position, velocity, total_mass, G=G)\n\n return (\n mass1, mass2, semimajor_axis, eccentricity, true_anomaly,\n inclination, long_asc_node, arg_per)\n\n\ndef get_orbital_elements_from_arrays(\n rel_position_raw, rel_velocity_raw,\n total_masses, G=nbody_system.G):\n \"\"\"\n Orbital elements from array of relative positions and velocities vectors,\n based on orbital_elements_from_binary and adapted to work for arrays (each\n line characterises a two body problem).\n\n For circular orbits (eccentricity=0): returns argument of pericenter = 0.,\n true anomaly = 0.\n\n For equatorial orbits (inclination=0): longitude of ascending node = 0,\n argument of pericenter = arctan2(e_y,e_x).\n\n :argument rel_position: array of vectors of relative positions of the\n two-body systems\n :argument rel_velocity: array of vectors of relative velocities of the\n two-body systems\n :argument total_masses: array of total masses for two-body systems\n :argument G: gravitational constant\n\n :output semimajor_axis: array of semi-major axes\n :output eccentricity: array of eccentricities\n :output period: array of orbital periods\n :output inc: array of inclinations [radians]\n :output long_asc_node: array of longitude of ascending nodes [radians]\n :output arg_per_mat: array of argument of pericenters [radians]\n :output true_anomaly: array of true anomalies [radians]\n \"\"\"\n if len(numpy.shape(rel_position_raw)) == 1:\n rel_position = numpy.zeros([1, 3]) * rel_position_raw[0]\n rel_position[0, 0] = rel_position_raw[0]\n rel_position[0, 1] = rel_position_raw[1]\n rel_position[0, 2] = rel_position_raw[2]\n rel_velocity = numpy.zeros([1, 3]) * rel_velocity_raw[0]\n rel_velocity[0, 0] = rel_velocity_raw[0]\n rel_velocity[0, 1] = rel_velocity_raw[1]\n rel_velocity[0, 2] = rel_velocity_raw[2]\n else:\n rel_position = rel_position_raw\n rel_velocity = rel_velocity_raw\n\n separation = (rel_position**2).sum(axis=1)**0.5\n n_vec = len(rel_position)\n\n speed_squared = (rel_velocity**2).sum(axis=1)\n\n semimajor_axis = (\n G * total_masses * separation\n / (2. * G * total_masses - separation * speed_squared)\n )\n\n neg_ecc_arg = (\n (\n to_quantity(rel_position).cross(rel_velocity)**2\n ).sum(axis=-1)\n / (G * total_masses * semimajor_axis)\n )\n filter_ecc0 = (1. <= neg_ecc_arg)\n eccentricity = numpy.zeros(separation.shape)\n eccentricity[~filter_ecc0] = numpy.sqrt(1.0 - neg_ecc_arg[~filter_ecc0])\n eccentricity[filter_ecc0] = 0.\n\n # angular momentum\n mom = to_quantity(rel_position).cross(rel_velocity)\n\n # inclination\n inc = arccos(mom[:, 2]/to_quantity(mom).lengths())\n\n # Longitude of ascending nodes, with reference direction along x-axis\n asc_node_matrix_unit = numpy.zeros(rel_position.shape)\n z_vectors = numpy.zeros([n_vec, 3])\n z_vectors[:, 2] = 1.\n z_vectors = z_vectors | units.none\n ascending_node_vectors = z_vectors.cross(mom)\n filter_non0_incl = (\n to_quantity(ascending_node_vectors).lengths().number > 0.)\n asc_node_matrix_unit[~filter_non0_incl] = numpy.array([1., 0., 0.])\n an_vectors_len = to_quantity(\n ascending_node_vectors[filter_non0_incl]).lengths()\n asc_node_matrix_unit[filter_non0_incl] = normalize_vector(\n ascending_node_vectors[filter_non0_incl],\n an_vectors_len)\n long_asc_node = arctan2(\n asc_node_matrix_unit[:, 1],\n asc_node_matrix_unit[:, 0])\n\n # Argument of periapsis using eccentricity a.k.a. Laplace-Runge-Lenz vector\n mu = G*total_masses\n pos_unit_vecs = normalize_vector(rel_position, separation)\n mom_len = to_quantity(mom).lengths()\n mom_unit_vecs = normalize_vector(mom, mom_len)\n e_vecs = (\n normalize_vector(\n to_quantity(rel_velocity).cross(mom), mu)\n - pos_unit_vecs\n )\n\n # Argument of pericenter cannot be determined for e = 0,\n # in this case return 0.0 and 1.0 for the cosines\n e_vecs_norm = (e_vecs**2).sum(axis=1)**0.5\n filter_non0_ecc = (e_vecs_norm > 1.e-15)\n arg_per_mat = VectorQuantity(\n array=numpy.zeros(long_asc_node.shape),\n unit=units.rad)\n cos_arg_per = numpy.zeros(long_asc_node.shape)\n arg_per_mat[~filter_non0_ecc] = 0. | units.rad\n cos_arg_per[~filter_non0_ecc] = 1.\n\n e_vecs_unit = numpy.zeros(rel_position.shape)\n e_vecs_unit[filter_non0_ecc] = normalize_vector(\n e_vecs[filter_non0_ecc],\n e_vecs_norm[filter_non0_ecc]\n )\n cos_arg_per[filter_non0_ecc] = (\n e_vecs_unit[filter_non0_ecc]\n * asc_node_matrix_unit[filter_non0_ecc]\n ).sum(axis=-1)\n e_cross_an = numpy.zeros(e_vecs_unit.shape)\n e_cross_an[filter_non0_ecc] = numpy.cross(\n e_vecs_unit[filter_non0_ecc],\n asc_node_matrix_unit[filter_non0_ecc]\n )\n e_cross_an_norm = (e_cross_an**2).sum(axis=1)**0.5\n filter_non0_e_cross_an = (e_cross_an_norm != 0.)\n ss = -numpy.sign(\n (\n mom_unit_vecs[filter_non0_e_cross_an]\n * e_cross_an[filter_non0_e_cross_an]\n ).sum(axis=-1)\n )\n # note change in size in sin_arg_per and cos_arg_per; they are not used further \n sin_arg_per = ss*e_cross_an_norm[filter_non0_e_cross_an]\n cos_arg_per = cos_arg_per[filter_non0_e_cross_an]\n arg_per_mat[filter_non0_e_cross_an] = arctan2(sin_arg_per, cos_arg_per)\n\n # in case longitude of ascending node is 0, omega=arctan2(e_y,e_x)\n arg_per_mat[~filter_non0_e_cross_an & filter_non0_ecc] = (\n arctan2(\n e_vecs[~filter_non0_e_cross_an & filter_non0_ecc, 1],\n e_vecs[~filter_non0_e_cross_an & filter_non0_ecc, 0]\n )\n )\n filter_negative_zmom = (\n ~filter_non0_e_cross_an\n & filter_non0_ecc\n & (mom[:, 2] < 0.*mom[0, 0])\n )\n arg_per_mat[filter_negative_zmom] = (\n 2. * numpy.pi\n - arg_per_mat[filter_negative_zmom]\n )\n\n # true anomaly\n cos_true_anomaly = (e_vecs_unit*pos_unit_vecs).sum(axis=-1)\n e_cross_pos = numpy.cross(e_vecs_unit, pos_unit_vecs)\n ss2 = numpy.sign((mom_unit_vecs*e_cross_pos).sum(axis=-1))\n sin_true_anomaly = ss2*(e_cross_pos**2).sum(axis=1)**0.5\n true_anomaly = arctan2(sin_true_anomaly, cos_true_anomaly)\n\n return (\n semimajor_axis, eccentricity, true_anomaly,\n inc, long_asc_node, arg_per_mat\n )\n\n\ndef orbital_elements(*args, **kwargs):\n try:\n if len(args) == 1:\n return get_orbital_elements_from_binary(*args, **kwargs)\n elif len(args) == 2:\n return get_orbital_elements_from_binaries(*args, **kwargs)\n elif len(args) == 3:\n return get_orbital_elements_from_arrays(*args, **kwargs)\n else:\n raise Exception\n except Exception as ex:\n if not ex.args: \n ex.args=()\n ex.args = ex.args + (\"\"\"\n note: orbital elements takes as input either:\n - single two particle set,\n - two sets of primaries and secondaries\n - arrays of rel. position, rel. velocity and masses\n \"\"\",)\n raise\n\ndef orbital_elements_for_rel_posvel_arrays(\n rel_position_raw, rel_velocity_raw,\n total_masses, G=nbody_system.G):\n (semimajor_axis, eccentricity, true_anomaly, inc, long_asc_node,\n arg_per_mat) = get_orbital_elements_from_arrays(\n rel_position_raw, rel_velocity_raw, total_masses, G)\n\n true_anomaly = true_anomaly.value_in(units.deg)\n inc = inc.value_in(units.deg)\n long_asc_node = long_asc_node.value_in(units.deg)\n arg_per_mat = arg_per_mat.value_in(units.deg)\n\n return (\n semimajor_axis, eccentricity, true_anomaly,\n inc, long_asc_node, arg_per_mat\n )\n\n\ndef normalize_vector(vecs, norm, one_dim=False):\n \"\"\"\n normalize array of vector quantities\n \"\"\"\n if one_dim:\n vecs_norm = numpy.zeros(vecs.shape)\n vecs_norm[0] = vecs[0]/norm\n vecs_norm[1] = vecs[1]/norm\n vecs_norm[2] = vecs[2]/norm\n else:\n vecs_norm = numpy.zeros(vecs.shape)\n vecs_norm[:, 0] = vecs[:, 0]/norm\n vecs_norm[:, 1] = vecs[:, 1]/norm\n vecs_norm[:, 2] = vecs[:, 2]/norm\n return vecs_norm\n"
] |
[
[
"numpy.array",
"scipy.special.gammainc",
"numpy.isnan",
"scipy.special.gamma",
"numpy.zeros",
"scipy.integrate.simps",
"scipy.special.hyp1f1",
"numpy.sum",
"numpy.sin",
"scipy.interpolate.PiecewisePolynomial",
"numpy.exp",
"numpy.interp",
"numpy.sqrt",
"numpy.searchsorted",
"scipy.integrate.ode",
"numpy.vstack"
],
[
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.show"
],
[
"numpy.array",
"numpy.zeros",
"numpy.ones",
"numpy.shape",
"numpy.sqrt",
"numpy.cross"
]
] |
toandaominh1997/pipelineservice
|
[
"2946fc6b61cc73f8695eff03f5d2066e6064ad3f"
] |
[
"pipelineservice/tf/tabnet.py"
] |
[
"import numpy as np\nimport tensorflow as tf\n\ndef sparsemax(logits, axis: int = -1):\n r\"\"\"Sparsemax activation function.\n For each batch $i$, and class $j$,\n compute sparsemax activation function:\n $$\n \\mathrm{sparsemax}(x)[i, j] = \\max(\\mathrm{logits}[i, j] - \\tau(\\mathrm{logits}[i, :]), 0).\n $$\n See [From Softmax to Sparsemax: A Sparse Model of Attention and Multi-Label Classification](https://arxiv.org/abs/1602.02068).\n Usage:\n >>> x = tf.constant([[-1.0, 0.0, 1.0], [-5.0, 1.0, 2.0]])\n >>> tfa.activations.sparsemax(x)\n <tf.Tensor: shape=(2, 3), dtype=float32, numpy=\n array([[0., 0., 1.],\n [0., 0., 1.]], dtype=float32)>\n Args:\n logits: A `Tensor`.\n axis: `int`, axis along which the sparsemax operation is applied.\n Returns:\n A `Tensor`, output of sparsemax transformation. Has the same type and\n shape as `logits`.\n Raises:\n ValueError: In case `dim(logits) == 1`.\n \"\"\"\n logits = tf.convert_to_tensor(logits, name=\"logits\")\n\n # We need its original shape for shape inference.\n shape = logits.get_shape()\n rank = shape.rank\n is_last_axis = (axis == -1) or (axis == rank - 1)\n\n if is_last_axis:\n output = _compute_2d_sparsemax(logits)\n output.set_shape(shape)\n return output\n\n # If dim is not the last dimension, we have to do a transpose so that we can\n # still perform softmax on its last dimension.\n\n # Swap logits' dimension of dim and its last dimension.\n rank_op = tf.rank(logits)\n axis_norm = axis % rank\n logits = _swap_axis(logits, axis_norm, tf.math.subtract(rank_op, 1))\n\n # Do the actual softmax on its last dimension.\n output = _compute_2d_sparsemax(logits)\n output = _swap_axis(output, axis_norm, tf.math.subtract(rank_op, 1))\n\n # Make shape inference work since transpose may erase its static shape.\n output.set_shape(shape)\n return output\n\n\ndef _swap_axis(logits, dim_index, last_index, **kwargs):\n return tf.transpose(\n logits,\n tf.concat(\n [\n tf.range(dim_index),\n [last_index],\n tf.range(dim_index + 1, last_index),\n [dim_index],\n ],\n 0,\n ),\n **kwargs,\n )\n\n\ndef _compute_2d_sparsemax(logits):\n \"\"\"Performs the sparsemax operation when axis=-1.\"\"\"\n shape_op = tf.shape(logits)\n obs = tf.math.reduce_prod(shape_op[:-1])\n dims = shape_op[-1]\n\n # In the paper, they call the logits z.\n # The mean(logits) can be substracted from logits to make the algorithm\n # more numerically stable. the instability in this algorithm comes mostly\n # from the z_cumsum. Substacting the mean will cause z_cumsum to be close\n # to zero. However, in practise the numerical instability issues are very\n # minor and substacting the mean causes extra issues with inf and nan\n # input.\n # Reshape to [obs, dims] as it is almost free and means the remanining\n # code doesn't need to worry about the rank.\n z = tf.reshape(logits, [obs, dims])\n\n # sort z\n z_sorted, _ = tf.nn.top_k(z, k=dims)\n\n # calculate k(z)\n z_cumsum = tf.math.cumsum(z_sorted, axis=-1)\n k = tf.range(1, tf.cast(dims, logits.dtype) + 1, dtype=logits.dtype)\n z_check = 1 + k * z_sorted > z_cumsum\n # because the z_check vector is always [1,1,...1,0,0,...0] finding the\n # (index + 1) of the last `1` is the same as just summing the number of 1.\n k_z = tf.math.reduce_sum(tf.cast(z_check, tf.int32), axis=-1)\n\n # calculate tau(z)\n # If there are inf values or all values are -inf, the k_z will be zero,\n # this is mathematically invalid and will also cause the gather_nd to fail.\n # Prevent this issue for now by setting k_z = 1 if k_z = 0, this is then\n # fixed later (see p_safe) by returning p = nan. This results in the same\n # behavior as softmax.\n k_z_safe = tf.math.maximum(k_z, 1)\n indices = tf.stack([tf.range(0, obs), tf.reshape(k_z_safe, [-1]) - 1], axis=1)\n tau_sum = tf.gather_nd(z_cumsum, indices)\n tau_z = (tau_sum - 1) / tf.cast(k_z, logits.dtype)\n\n # calculate p\n p = tf.math.maximum(tf.cast(0, logits.dtype), z - tf.expand_dims(tau_z, -1))\n # If k_z = 0 or if z = nan, then the input is invalid\n p_safe = tf.where(\n tf.expand_dims(\n tf.math.logical_or(tf.math.equal(k_z, 0), tf.math.is_nan(z_cumsum[:, -1])),\n axis=-1,\n ),\n tf.fill([obs, dims], tf.cast(float(\"nan\"), logits.dtype)),\n p,\n )\n\n # Reshape back to original size\n p_safe = tf.reshape(p_safe, shape_op)\n return p_safe\n\ndef glu(act, n_units):\n return act[:, :n_units] * tf.nn.sigmoid(act[:, n_units:])\nclass TransformBlock(tf.keras.Model):\n def __init__(self,\n features,\n norm_type,\n momentum = 0.9,\n virtual_batch_size = None,\n groups = 2,\n block_name = '',\n **kwargs\n ):\n super().__init__()\n self.transform = tf.keras.layers.Dense(features, use_bias = False, name = f'transformblock_dense_{block_name}')\n if norm_type == 'batch':\n self.bn = tf.keras.layers.BatchNormalization(axis = -1, momentum = momentum,\n virtual_batch_size = virtual_batch_size,\n name = f'transformerblock_bn_{block_name}')\n\n def call(self, x, training = None):\n x = self.transform(x)\n x = self.bn(x, training = training)\n return x\n\n\n\n\nclass TabNet(tf.keras.Model):\n def __init__(self,\n columns,\n feature_dim = 64,\n output_dim = 64,\n num_features=None,\n num_decision_steps=5,\n relaxation_factor=1.5,\n momentum=0.98,\n virtual_batch_size=None,\n sparsity_coefficient=1e-5,\n norm_type='batch',\n num_groups=2,\n epsilon=1e-5,\n\n ):\n super().__init__()\n if columns is not None:\n try:\n self.num_features = len(columns)\n except:\n self.num_features = int(columns)\n self.num_decision_steps = num_decision_steps\n self.feature_dim = feature_dim\n self.output_dim = output_dim\n self.virtual_batch_size = virtual_batch_size\n self.relaxation_factor = relaxation_factor\n self.epsilon = epsilon\n if columns is not None:\n if isinstance(columns, list):\n self.input_features = tf.keras.layers.DenseFeatures(columns, trainable=True)\n else:\n self.input_features = tf.keras.layers.Dense(columns)\n if norm_type == 'batch':\n self.input_bn = tf.keras.layers.BatchNormalization(axis = -1, momentum = momentum, name = 'input_bn')\n else:\n self.input_features = None\n self.input_bn = None\n self.transform_f1 = TransformBlock(features = 2*feature_dim,\n norm_type = norm_type,\n momentum = momentum,\n virtual_batch_size = virtual_batch_size,\n groups = num_groups,\n block_name = 'f1'\n )\n self.transform_f2 = TransformBlock(features = 2*feature_dim,\n norm_type = norm_type,\n momentum = momentum,\n virtual_batch_size = virtual_batch_size,\n groups = num_groups,\n block_name = 'f2'\n )\n self.transform_f3_list = [\n TransformBlock(features = 2*feature_dim,\n norm_type = norm_type,\n momentum = momentum,\n virtual_batch_size = virtual_batch_size,\n groups = num_groups,\n block_name = f'f3_{i}'\n )\n for i in range(self.num_decision_steps)\n ]\n self.transform_f4_list = [\n TransformBlock(features = 2*feature_dim,\n norm_type = norm_type,\n momentum = momentum,\n virtual_batch_size = virtual_batch_size,\n groups = num_groups,\n block_name = f'f4_{i}'\n )\n for i in range(self.num_decision_steps)\n ]\n self.transform_coef_list = [\n TransformBlock(features = self.num_features,\n norm_type = norm_type,\n momentum = momentum,\n virtual_batch_size = virtual_batch_size,\n groups = num_groups,\n block_name = f'coef_{i}'\n )\n for i in range(self.num_decision_steps)\n ]\n\n def call(self, x, is_training = None):\n if self.input_features is not None:\n features = self.input_features(x)\n features = self.input_bn(features, training = is_training)\n else:\n features = inputs\n batch_size = tf.shape(features)[0]\n\n # Initializes decision-step dependent variables.\n output_aggregated = tf.zeros([batch_size, self.output_dim])\n masked_features = features\n mask_values = tf.zeros([batch_size, self.num_features])\n aggregated_mask_values = tf.zeros([batch_size, self.num_features])\n complemantary_aggregated_mask_values = tf.ones([batch_size, self.num_features])\n total_entropy = 0\n\n if is_training:\n v_b = self.virtual_batch_size\n else:\n v_b = 1\n\n\n for ni in range(self.num_decision_steps):\n transform_f1 = self.transform_f1(features, training = is_training)\n transform_f1 = glu(transform_f1, self.feature_dim)\n\n transform_f2 = self.transform_f2(transform_f1, training = is_training)\n transform_f2 = (glu(transform_f2, self.feature_dim) + transform_f1)* tf.math.sqrt(0.5)\n\n transform_f3 = self.transform_f3_list[ni](transform_f2, training = is_training)\n transform_f3 = (glu(transform_f3, self.feature_dim) + transform_f2) * tf.math.sqrt(0.5)\n\n transform_f4 = self.transform_f4_list[ni](transform_f3, training = is_training)\n transform_f4 = (glu(transform_f4, self.feature_dim) + transform_f3) * tf.math.sqrt(0.5)\n\n if ni > 0:\n decision_out = tf.nn.relu(transform_f4[:, :self.output_dim])\n output_aggregated +=decision_out\n scale_agg = tf.reduce_sum(decision_out, axis=1, keepdims=True) / (self.num_decision_steps - 1)\n aggregated_mask_values += mask_values * scale_agg\n features_for_coef = transform_f4[:, self.output_dim:]\n if ni < (self.num_decision_steps - 1):\n mask_values = self.transform_coef_list[ni](features_for_coef, training = is_training)\n mask_values *= complemantary_aggregated_mask_values\n mask_values = sparsemax(mask_values)\n\n # Relaxation factor controls the amount of reuse of features between\n # different decision blocks and updated with the values of\n # coefficients.\n complemantary_aggregated_mask_values *= (self.relaxation_factor - mask_values)\n\n # Entropy is used to penalize the amount of sparsity in feature\n # selection.\n total_entropy += tf.reduce_mean(tf.reduce_sum(-mask_values * tf.math.log(mask_values + self.epsilon),axis=1)) / (self.num_decision_steps - 1)\n # Feature selection.\n masked_features = tf.multiply(mask_values, features)\n return output_aggregated, total_entropy\n\nif __name__ == '__main__':\n inputs = np.random.randn(16, 400)\n model = TabNet(columns = 400)\n out, loss = model(inputs)\n print('output: ', out.shape, loss)\n"
] |
[
[
"tensorflow.ones",
"tensorflow.reshape",
"tensorflow.keras.layers.Dense",
"tensorflow.math.sqrt",
"tensorflow.keras.layers.BatchNormalization",
"tensorflow.math.equal",
"tensorflow.cast",
"tensorflow.rank",
"tensorflow.shape",
"tensorflow.math.cumsum",
"tensorflow.keras.layers.DenseFeatures",
"tensorflow.math.log",
"tensorflow.math.is_nan",
"tensorflow.nn.sigmoid",
"tensorflow.zeros",
"tensorflow.range",
"tensorflow.nn.relu",
"tensorflow.expand_dims",
"tensorflow.gather_nd",
"numpy.random.randn",
"tensorflow.math.maximum",
"tensorflow.reduce_sum",
"tensorflow.nn.top_k",
"tensorflow.convert_to_tensor",
"tensorflow.multiply",
"tensorflow.math.subtract",
"tensorflow.math.reduce_prod"
]
] |
vishalbelsare/OpenMatch
|
[
"84b25502bf52c58b9e71bd0754b2fc192d9b448f",
"84b25502bf52c58b9e71bd0754b2fc192d9b448f"
] |
[
"train.py",
"OpenMatch/modules/embedders/embedder.py"
] |
[
"import argparse\nimport datetime\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.distributions import Categorical\n\nfrom transformers import AutoTokenizer, get_linear_schedule_with_warmup\nimport OpenMatch as om\nfrom transformers import AdamW\n\nimport torch.distributed as dist\nfrom torch.utils.data.distributed import DistributedSampler\nfrom torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset\nfrom utils import is_first_worker, DistributedEvalSampler, merge_resfile, set_dist_args, optimizer_to\nfrom contextlib import nullcontext # from contextlib import suppress as nullcontext # for python < 3.7\ntorch.multiprocessing.set_sharing_strategy('file_system')\nimport logging\nimport random\nimport numpy as np\nlogger = logging.getLogger(__name__)\n# from torch.utils.tensorboard import SummaryWriter\n\n# writer = SummaryWriter(log_dir='logs')\n\n\ndef dev(args, model, metric, dev_loader, device):\n rst_dict = {}\n for dev_batch in dev_loader:\n query_id, doc_id, label, retrieval_score = dev_batch['query_id'], dev_batch['doc_id'], dev_batch['label'], dev_batch['retrieval_score']\n with torch.no_grad():\n if args.model == 'bert':\n batch_score, _ = model(dev_batch['input_ids'].to(device), dev_batch['input_mask'].to(device), dev_batch['segment_ids'].to(device))\n elif args.model == 'roberta':\n batch_score, _ = model(dev_batch['input_ids'].to(device), dev_batch['input_mask'].to(device))\n elif args.model == 'edrm':\n batch_score, _ = model(dev_batch['query_wrd_idx'].to(device), dev_batch['query_wrd_mask'].to(device),\n dev_batch['doc_wrd_idx'].to(device), dev_batch['doc_wrd_mask'].to(device),\n dev_batch['query_ent_idx'].to(device), dev_batch['query_ent_mask'].to(device),\n dev_batch['doc_ent_idx'].to(device), dev_batch['doc_ent_mask'].to(device),\n dev_batch['query_des_idx'].to(device), dev_batch['doc_des_idx'].to(device))\n else:\n batch_score, _ = model(dev_batch['query_idx'].to(device), dev_batch['query_mask'].to(device),\n dev_batch['doc_idx'].to(device), dev_batch['doc_mask'].to(device))\n if args.task == 'classification':\n batch_score = batch_score.softmax(dim=-1)[:, 1].squeeze(-1)\n batch_score = batch_score.detach().cpu().tolist()\n for (q_id, d_id, b_s, l) in zip(query_id, doc_id, batch_score, label):\n if q_id not in rst_dict:\n rst_dict[q_id] = {}\n if d_id not in rst_dict[q_id] or b_s > rst_dict[q_id][d_id][0]:\n rst_dict[q_id][d_id] = [b_s, l]\n return rst_dict\n\ndef train_reinfoselect(args, model, policy, loss_fn, m_optim, m_scheduler, p_optim, metric, train_loader, dev_loader, device):\n best_mes = 0.0\n with torch.no_grad():\n rst_dict = dev(args, model, metric, dev_loader, device)\n om.utils.save_trec(args.res, rst_dict)\n if args.metric.split('_')[0] == 'mrr':\n mes = metric.get_mrr(args.qrels, args.res, args.metric)\n else:\n mes = metric.get_metric(args.qrels, args.res, args.metric)\n if mes >= best_mes:\n best_mes = mes\n print('save_model...')\n if args.n_gpu > 1:\n torch.save(model.module.state_dict(), args.save)\n else:\n torch.save(model.state_dict(), args.save)\n print('initial result: ', mes)\n last_mes = mes\n for epoch in range(args.epoch):\n avg_loss = 0.0\n log_prob_ps = []\n log_prob_ns = []\n for step, train_batch in enumerate(train_loader):\n if args.model == 'bert':\n if args.task == 'ranking':\n batch_probs, _ = policy(train_batch['input_ids_pos'].to(device), train_batch['input_mask_pos'].to(device), train_batch['segment_ids_pos'].to(device))\n elif args.task == 'classification':\n batch_probs, _ = policy(train_batch['input_ids'].to(device), train_batch['input_mask'].to(device), train_batch['segment_ids'].to(device))\n else:\n raise ValueError('Task must be `ranking` or `classification`.')\n elif args.model == 'roberta':\n if args.task == 'ranking':\n batch_probs, _ = policy(train_batch['input_ids_pos'].to(device), train_batch['input_mask_pos'].to(device))\n elif args.task == 'classification':\n batch_probs, _ = policy(train_batch['input_ids'].to(device), train_batch['input_mask'].to(device))\n else:\n raise ValueError('Task must be `ranking` or `classification`.')\n elif args.model == 'edrm':\n if args.task == 'ranking':\n batch_probs, _ = policy(train_batch['query_wrd_idx'].to(device), train_batch['query_wrd_mask'].to(device),\n train_batch['doc_pos_wrd_idx'].to(device), train_batch['doc_pos_wrd_mask'].to(device))\n elif args.task == 'classification':\n batch_probs, _ = policy(train_batch['query_wrd_idx'].to(device), train_batch['query_wrd_mask'].to(device),\n train_batch['doc_wrd_idx'].to(device), train_batch['doc_wrd_mask'].to(device))\n else:\n raise ValueError('Task must be `ranking` or `classification`.')\n else:\n if args.task == 'ranking':\n batch_probs, _ = policy(train_batch['query_idx'].to(device), train_batch['query_mask'].to(device),\n train_batch['doc_pos_idx'].to(device), train_batch['doc_pos_mask'].to(device))\n elif args.task == 'classification':\n batch_probs, _ = policy(train_batch['query_idx'].to(device), train_batch['query_mask'].to(device),\n train_batch['doc_idx'].to(device), train_batch['doc_mask'].to(device))\n else:\n raise ValueError('Task must be `ranking` or `classification`.')\n batch_probs = F.gumbel_softmax(batch_probs, tau=args.tau)\n m = Categorical(batch_probs)\n action = m.sample()\n if action.sum().item() < 1:\n #m_scheduler.step()\n if (step+1) % args.eval_every == 0 and len(log_prob_ps) > 0:\n with torch.no_grad():\n rst_dict = dev(args, model, metric, dev_loader, device)\n om.utils.save_trec(args.res, rst_dict)\n if args.metric.split('_')[0] == 'mrr':\n mes = metric.get_mrr(args.qrels, args.res, args.metric)\n else:\n mes = metric.get_metric(args.qrels, args.res, args.metric)\n if mes >= best_mes:\n best_mes = mes\n print('save_model...')\n if args.n_gpu > 1:\n torch.save(model.module.state_dict(), args.save)\n else:\n torch.save(model.state_dict(), args.save)\n \n print(step+1, avg_loss/len(log_prob_ps), mes, best_mes)\n avg_loss = 0.0\n\n reward = mes - last_mes\n last_mes = mes\n if reward >= 0:\n policy_loss = [(-log_prob_p * reward).sum().unsqueeze(-1) for log_prob_p in log_prob_ps]\n else:\n policy_loss = [(log_prob_n * reward).sum().unsqueeze(-1) for log_prob_n in log_prob_ns]\n policy_loss = torch.cat(policy_loss).sum()\n policy_loss.backward()\n p_optim.step()\n p_optim.zero_grad()\n\n if args.reset:\n state_dict = torch.load(args.save)\n model.load_state_dict(state_dict)\n last_mes = best_mes\n log_prob_ps = []\n log_prob_ns = []\n continue\n\n filt = action.nonzero().squeeze(-1).cpu()\n if args.model == 'bert':\n if args.task == 'ranking':\n batch_score_pos, _ = model(train_batch['input_ids_pos'].index_select(0, filt).to(device),\n train_batch['input_mask_pos'].index_select(0, filt).to(device),\n train_batch['segment_ids_pos'].index_select(0, filt).to(device))\n batch_score_neg, _ = model(train_batch['input_ids_neg'].index_select(0, filt).to(device),\n train_batch['input_mask_neg'].index_select(0, filt).to(device),\n train_batch['segment_ids_neg'].index_select(0, filt).to(device))\n elif args.task == 'classification':\n batch_score, _ = model(train_batch['input_ids'].index_select(0, filt).to(device),\n train_batch['input_mask'].index_select(0, filt).to(device),\n train_batch['segment_ids'].index_select(0, filt).to(device))\n else:\n raise ValueError('Task must be `ranking` or `classification`.')\n elif args.model == 'roberta':\n if args.task == 'ranking':\n batch_score_pos, _ = model(train_batch['input_ids_pos'].index_select(0, filt).to(device), train_batch['input_mask_pos'].index_select(0, filt).to(device))\n batch_score_neg, _ = model(train_batch['input_ids_neg'].index_select(0, filt).to(device), train_batch['input_mask_neg'].index_select(0, filt).to(device))\n elif args.task == 'classification':\n batch_score, _ = model(train_batch['input_ids'].index_select(0, filt).to(device), train_batch['input_mask'].index_select(0, filt).to(device))\n else:\n raise ValueError('Task must be `ranking` or `classification`.')\n elif args.model == 'edrm':\n if args.task == 'ranking':\n batch_score_pos, _ = model(train_batch['query_wrd_idx'].index_select(0, filt).to(device), train_batch['query_wrd_mask'].index_select(0, filt).to(device),\n train_batch['doc_pos_wrd_idx'].index_select(0, filt).to(device), train_batch['doc_pos_wrd_mask'].index_select(0, filt).to(device),\n train_batch['query_ent_idx'].index_select(0, filt).to(device), train_batch['query_ent_mask'].index_select(0, filt).to(device),\n train_batch['doc_pos_ent_idx'].index_select(0, filt).to(device), train_batch['doc_pos_ent_mask'].index_select(0, filt).to(device),\n train_batch['query_des_idx'].index_select(0, filt).to(device), train_batch['doc_pos_des_idx'].index_select(0, filt).to(device))\n batch_score_neg, _ = model(train_batch['query_wrd_idx'].index_select(0, filt).to(device), train_batch['query_wrd_mask'].index_select(0, filt).to(device),\n train_batch['doc_neg_wrd_idx'].index_select(0, filt).to(device), train_batch['doc_neg_wrd_mask'].index_select(0, filt).to(device),\n train_batch['query_ent_idx'].index_select(0, filt).to(device), train_batch['query_ent_mask'].index_select(0, filt).to(device),\n train_batch['doc_neg_ent_idx'].index_select(0, filt).to(device), train_batch['doc_neg_ent_mask'].index_select(0, filt).to(device),\n train_batch['query_des_idx'].index_select(0, filt).to(device), train_batch['doc_neg_des_idx'].index_select(0, filt).to(device))\n elif args.task == 'classification':\n batch_score, _ = model(train_batch['query_wrd_idx'].index_select(0, filt).to(device), train_batch['query_wrd_mask'].index_select(0, filt).to(device),\n train_batch['doc_wrd_idx'].index_select(0, filt).to(device), train_batch['doc_wrd_mask'].index_select(0, filt).to(device),\n train_batch['query_ent_idx'].index_select(0, filt).to(device), train_batch['query_ent_mask'].index_select(0, filt).to(device),\n train_batch['doc_ent_idx'].index_select(0, filt).to(device), train_batch['doc_ent_mask'].index_select(0, filt).to(device),\n train_batch['query_des_idx'].index_select(0, filt).to(device), train_batch['doc_des_idx'].index_select(0, filt).to(device))\n else:\n raise ValueError('Task must be `ranking` or `classification`.')\n else:\n if args.task == 'ranking':\n batch_score_pos, _ = model(train_batch['query_idx'].index_select(0, filt).to(device), train_batch['query_mask'].index_select(0, filt).to(device),\n train_batch['doc_pos_idx'].index_select(0, filt).to(device), train_batch['doc_pos_mask'].index_select(0, filt).to(device))\n batch_score_neg, _ = model(train_batch['query_idx'].index_select(0, filt).to(device), train_batch['query_mask'].index_select(0, filt).to(device),\n train_batch['doc_neg_idx'].index_select(0, filt).to(device), train_batch['doc_neg_mask'].index_select(0, filt).to(device))\n elif args.task == 'classification':\n batch_score, _ = model(train_batch['query_idx'].index_select(0, filt).to(device), train_batch['query_mask'].index_select(0, filt).to(device),\n train_batch['doc_idx'].index_select(0, filt).to(device), train_batch['doc_mask'].index_select(0, filt).to(device))\n else:\n raise ValueError('Task must be `ranking` or `classification`.')\n\n mask = action.ge(0.5)\n log_prob_p = m.log_prob(action)\n log_prob_n = m.log_prob(1-action)\n log_prob_ps.append(torch.masked_select(log_prob_p, mask))\n log_prob_ns.append(torch.masked_select(log_prob_n, mask))\n\n if args.task == 'ranking':\n batch_loss = loss_fn(batch_score_pos.tanh(), batch_score_neg.tanh(), torch.ones(batch_score_pos.size()).to(device))\n elif args.task == 'classification':\n batch_loss = loss_fn(batch_score, train_batch['label'].to(device))\n else:\n raise ValueError('Task must be `ranking` or `classification`.')\n \n if args.n_gpu > 1:\n batch_loss = batch_loss.mean(-1)\n batch_loss = batch_loss.mean()\n avg_loss += batch_loss.item()\n \n batch_loss.backward()\n m_optim.step()\n m_scheduler.step()\n m_optim.zero_grad()\n\n if (step+1) % args.eval_every == 0:\n with torch.no_grad():\n rst_dict = dev(args, model, metric, dev_loader, device)\n om.utils.save_trec(args.res, rst_dict)\n if args.metric.split('_')[0] == 'mrr':\n mes = metric.get_mrr(args.qrels, args.res, args.metric)\n else:\n mes = metric.get_metric(args.qrels, args.res, args.metric)\n if mes >= best_mes:\n best_mes = mes\n print('save_model...')\n if args.n_gpu > 1:\n torch.save(model.module.state_dict(), args.save)\n else:\n torch.save(model.state_dict(), args.save)\n print(step+1, avg_loss/len(log_prob_ps), mes, best_mes)\n avg_loss = 0.0\n\n reward = mes - last_mes\n last_mes = mes\n if reward >= 0:\n policy_loss = [(-log_prob_p * reward).sum().unsqueeze(-1) for log_prob_p in log_prob_ps]\n else:\n policy_loss = [(log_prob_n * reward).sum().unsqueeze(-1) for log_prob_n in log_prob_ns]\n policy_loss = torch.cat(policy_loss).sum()\n policy_loss.backward()\n p_optim.step()\n p_optim.zero_grad()\n\n if args.reset:\n state_dict = torch.load(args.save)\n model.load_state_dict(state_dict)\n last_mes = best_mes\n log_prob_ps = []\n log_prob_ns = []\n\ndef train(args, model, loss_fn, m_optim, m_scheduler, metric, train_loader, dev_loader, device, train_sampler=None):\n best_mes = 0.0\n global_step = 0 # steps that outside epoches\n for epoch in range(args.epoch):\n if args.local_rank != -1:\n train_sampler.set_epoch(epoch) # shuffle data for distributed\n logger.warning(\"current gpu local_rank {}\".format(args.local_rank))\n\n avg_loss = 0.0\n for step, train_batch in enumerate(train_loader):\n \n sync_context = model.no_sync if (args.local_rank != -1 and (step+1) % args.gradient_accumulation_steps != 0) else nullcontext\n\n if args.model == 'bert':\n if args.task == 'ranking':\n # sync gradients only at gradient accumulation step\n with sync_context():\n batch_score_pos, _ = model(train_batch['input_ids_pos'].to(device), train_batch['input_mask_pos'].to(device), train_batch['segment_ids_pos'].to(device))\n batch_score_neg, _ = model(train_batch['input_ids_neg'].to(device), train_batch['input_mask_neg'].to(device), train_batch['segment_ids_neg'].to(device))\n elif args.task == 'classification':\n with sync_context():\n batch_score, _ = model(train_batch['input_ids'].to(device), train_batch['input_mask'].to(device), train_batch['segment_ids'].to(device))\n else:\n raise ValueError('Task must be `ranking` or `classification`.')\n elif args.model == 'roberta':\n if args.task == 'ranking':\n batch_score_pos, _ = model(train_batch['input_ids_pos'].to(device), train_batch['input_mask_pos'].to(device))\n batch_score_neg, _ = model(train_batch['input_ids_neg'].to(device), train_batch['input_mask_neg'].to(device))\n elif args.task == 'classification':\n batch_score, _ = model(train_batch['input_ids'].to(device), train_batch['input_mask'].to(device))\n else:\n raise ValueError('Task must be `ranking` or `classification`.')\n elif args.model == 'edrm':\n if args.task == 'ranking':\n batch_score_pos, _ = model(train_batch['query_wrd_idx'].to(device), train_batch['query_wrd_mask'].to(device),\n train_batch['doc_pos_wrd_idx'].to(device), train_batch['doc_pos_wrd_mask'].to(device),\n train_batch['query_ent_idx'].to(device), train_batch['query_ent_mask'].to(device),\n train_batch['doc_pos_ent_idx'].to(device), train_batch['doc_pos_ent_mask'].to(device),\n train_batch['query_des_idx'].to(device), train_batch['doc_pos_des_idx'].to(device))\n batch_score_neg, _ = model(train_batch['query_wrd_idx'].to(device), train_batch['query_wrd_mask'].to(device),\n train_batch['doc_neg_wrd_idx'].to(device), train_batch['doc_neg_wrd_mask'].to(device),\n train_batch['query_ent_idx'].to(device), train_batch['query_ent_mask'].to(device),\n train_batch['doc_neg_ent_idx'].to(device), train_batch['doc_neg_ent_mask'].to(device),\n train_batch['query_des_idx'].to(device), train_batch['doc_neg_des_idx'].to(device))\n elif args.task == 'classification':\n batch_score, _ = model(train_batch['query_wrd_idx'].to(device), train_batch['query_wrd_mask'].to(device),\n train_batch['doc_wrd_idx'].to(device), train_batch['doc_wrd_mask'].to(device),\n train_batch['query_ent_idx'].to(device), train_batch['query_ent_mask'].to(device),\n train_batch['doc_ent_idx'].to(device), train_batch['doc_ent_mask'].to(device),\n train_batch['query_des_idx'].to(device), train_batch['doc_des_idx'].to(device))\n else:\n raise ValueError('Task must be `ranking` or `classification`.')\n else:\n if args.task == 'ranking':\n with sync_context():\n batch_score_pos, _ = model(train_batch['query_idx'].to(device), train_batch['query_mask'].to(device),\n train_batch['doc_pos_idx'].to(device), train_batch['doc_pos_mask'].to(device))\n batch_score_neg, _ = model(train_batch['query_idx'].to(device), train_batch['query_mask'].to(device),\n train_batch['doc_neg_idx'].to(device), train_batch['doc_neg_mask'].to(device))\n elif args.task == 'classification':\n batch_score, _ = model(train_batch['query_idx'].to(device), train_batch['query_mask'].to(device),\n train_batch['doc_idx'].to(device), train_batch['doc_mask'].to(device))\n else:\n raise ValueError('Task must be `ranking` or `classification`.')\n\n if args.task == 'ranking':\n with sync_context():\n if args.ranking_loss == 'margin_loss':\n batch_loss = loss_fn(batch_score_pos.tanh(), batch_score_neg.tanh(), torch.ones(batch_score_pos.size()).to(device))\n elif args.ranking_loss == 'CE_loss':\n batch_loss = loss_fn(torch.sigmoid(batch_score_pos-batch_score_neg),torch.ones(batch_score_neg.size()).to(device))\n elif args.ranking_loss == 'triplet_loss':\n logit_matrix = torch.cat([batch_score_pos.reshape([-1,1]),batch_score_neg.reshape([-1,1])], dim=1)\n lsm = F.log_softmax(input=logit_matrix,dim=1)\n batch_loss = torch.mean(-1.0 * lsm[:, 0])\n elif args.ranking_loss == 'LCE_loss':\n pass\n elif args.task == 'classification':\n with sync_context():\n batch_loss = loss_fn(batch_score, train_batch['label'].to(device))\n else:\n raise ValueError('Task must be `ranking` or `classification`.')\n\n if args.n_gpu > 1:\n batch_loss = batch_loss.mean()\n if args.gradient_accumulation_steps > 1:\n batch_loss = batch_loss / args.gradient_accumulation_steps\n avg_loss += batch_loss.item()\n\n with sync_context():\n batch_loss.backward()\n # if args.local_rank != -1:\n # if (step+1) % args.gradient_accumulation_steps == 0:\n # batch_loss.backward()\n # else:\n # with model.no_sync():\n # batch_loss.backward()\n # else:\n # batch_loss.backward()\n\n if (step+1) % args.gradient_accumulation_steps == 0:\n torch.nn.utils.clip_grad_norm_(\n model.parameters(), args.max_grad_norm)\n m_optim.step()\n m_scheduler.step()\n m_optim.zero_grad()\n global_step += 1\n\n if args.logging_step > 0 and ((global_step+1) % args.logging_step == 0 or (args.test_init_log and global_step==0)):\n # if is_first_worker():\n if args.local_rank in [-1,0]:\n logger.info( \"training gpu {}:, global step: {}, local step: {}, loss: {}\".format(args.local_rank,global_step+1, step+1, avg_loss/args.logging_step))\n # writer.add_scalar('avg_loss',avg_loss/args.logging_step, step)\n # writer.add_scalar('dev', mes, step)\n avg_loss = 0.0 \n\n if (global_step+1) % args.eval_every == 0 or (args.test_init_log and global_step==0): \n model.eval()\n with torch.no_grad():\n rst_dict = dev(args, model, metric, dev_loader, device)\n model.train()\n\n if args.local_rank != -1:\n # distributed mode, save dicts and merge\n om.utils.save_trec(args.res + \"_rank_{:03}\".format(args.local_rank), rst_dict)\n dist.barrier()\n # if is_first_worker():\n if args.local_rank in [-1,0]:\n merge_resfile(args.res + \"_rank_*\", args.res)\n\n else:\n om.utils.save_trec(args.res, rst_dict)\n \n # if is_first_worker():\n if args.local_rank in [-1,0]:\n if args.metric.split('_')[0] == 'mrr':\n mes = metric.get_mrr(args.qrels, args.res, args.metric)\n else:\n mes = metric.get_metric(args.qrels, args.res, args.metric)\n\n best_mes = mes if mes >= best_mes else best_mes\n logger.info( 'save_model at step {}'.format(global_step+1))\n if args.n_gpu > 1:\n torch.save(model.module.state_dict(), args.save + \"_step-{}\".format(global_step+1))\n else:\n torch.save(model.state_dict(), args.save + \"_step-{}\".format(global_step+1))\n logger.info( \"global step: {}, messure: {}, best messure: {}\".format(global_step+1, mes, best_mes))\n # dist.barrier() \n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('-task', type=str, default='ranking')\n parser.add_argument('-ranking_loss', type=str, default='margin_loss')\n parser.add_argument('-model', type=str, default='bert')\n parser.add_argument('-optimizer', type=str, default='adam')\n parser.add_argument('-reinfoselect', action='store_true', default=False)\n parser.add_argument('-reset', action='store_true', default=False)\n parser.add_argument('-train', action=om.utils.DictOrStr, default='./data/train_toy.jsonl')\n parser.add_argument('-max_input', type=int, default=1280000)\n parser.add_argument('-save', type=str, default='./checkpoints/bert.bin')\n parser.add_argument('-dev', action=om.utils.DictOrStr, default='./data/dev_toy.jsonl')\n parser.add_argument('-qrels', type=str, default='./data/qrels_toy')\n parser.add_argument('-vocab', type=str, default='allenai/scibert_scivocab_uncased')\n parser.add_argument('-ent_vocab', type=str, default='')\n parser.add_argument('-pretrain', type=str, default='allenai/scibert_scivocab_uncased')\n parser.add_argument('-checkpoint', type=str, default=None)\n parser.add_argument('-res', type=str, default='./results/bert.trec')\n parser.add_argument('-metric', type=str, default='ndcg_cut_10')\n parser.add_argument('-mode', type=str, default='cls')\n parser.add_argument('-n_kernels', type=int, default=21)\n parser.add_argument('-max_query_len', type=int, default=20)\n parser.add_argument('-max_doc_len', type=int, default=150)\n parser.add_argument('-maxp', action='store_true', default=False)\n parser.add_argument('-epoch', type=int, default=1)\n parser.add_argument('-batch_size', type=int, default=8)\n parser.add_argument('-dev_eval_batch_size', type=int, default=128)\n parser.add_argument('-lr', type=float, default=2e-5)\n parser.add_argument('-tau', type=float, default=1)\n parser.add_argument('-n_warmup_steps', type=int, default=1000)\n parser.add_argument('-gradient_accumulation_steps', type=int, default=4) \n parser.add_argument(\"-max_grad_norm\", default=1.0,type=float,help=\"Max gradient norm.\",)\n parser.add_argument('-eval_every', type=int, default=1000)\n parser.add_argument('-logging_step', type=int, default=100)\n parser.add_argument('-test_init_log', action='store_true', default=False)\n parser.add_argument('--no_cuda', action='store_true', default=False)\n parser.add_argument('--local_rank', type=int, default=-1) # for distributed mode\n parser.add_argument( \"--server_ip\",type=str,default=\"\", help=\"For distant debugging.\",) \n parser.add_argument( \"--server_port\",type=str, default=\"\",help=\"For distant debugging.\",)\n\n args = parser.parse_args()\n\n set_dist_args(args) # get local cpu/gpu device\n\n args.model = args.model.lower()\n if args.model == 'bert':\n tokenizer = AutoTokenizer.from_pretrained(args.vocab)\n logger.info('reading training data...')\n if args.maxp:\n train_set = om.data.datasets.BertMaxPDataset(\n dataset=args.train,\n tokenizer=tokenizer,\n mode='train',\n query_max_len=args.max_query_len,\n doc_max_len=args.max_doc_len,\n max_input=args.max_input,\n task=args.task\n )\n else:\n train_set = om.data.datasets.BertDataset(\n dataset=args.train,\n tokenizer=tokenizer,\n mode='train',\n query_max_len=args.max_query_len,\n doc_max_len=args.max_doc_len,\n max_input=args.max_input,\n task=args.task\n )\n logger.info('reading dev data...')\n if args.maxp:\n dev_set = om.data.datasets.BertMaxPDataset(\n dataset=args.dev,\n tokenizer=tokenizer,\n mode='dev',\n query_max_len=args.max_query_len,\n doc_max_len=args.max_doc_len,\n max_input=args.max_input,\n task=args.task\n )\n else:\n dev_set = om.data.datasets.BertDataset(\n dataset=args.dev,\n tokenizer=tokenizer,\n mode='dev',\n query_max_len=args.max_query_len,\n doc_max_len=args.max_doc_len,\n max_input=args.max_input,\n task=args.task\n )\n elif args.model == 'roberta':\n tokenizer = AutoTokenizer.from_pretrained(args.vocab)\n print('reading training data...')\n train_set = om.data.datasets.RobertaDataset(\n dataset=args.train,\n tokenizer=tokenizer,\n mode='train',\n query_max_len=args.max_query_len,\n doc_max_len=args.max_doc_len,\n max_input=args.max_input,\n task=args.task\n )\n print('reading dev data...')\n dev_set = om.data.datasets.RobertaDataset(\n dataset=args.dev,\n tokenizer=tokenizer,\n mode='dev',\n query_max_len=args.max_query_len,\n doc_max_len=args.max_doc_len,\n max_input=args.max_input,\n task=args.task\n )\n elif args.model == 'edrm':\n tokenizer = om.data.tokenizers.WordTokenizer(\n pretrained=args.vocab\n )\n ent_tokenizer = om.data.tokenizers.WordTokenizer(\n vocab=args.ent_vocab\n )\n print('reading training data...')\n train_set = om.data.datasets.EDRMDataset(\n dataset=args.train,\n wrd_tokenizer=tokenizer,\n ent_tokenizer=ent_tokenizer,\n mode='train',\n query_max_len=args.max_query_len,\n doc_max_len=args.max_doc_len,\n des_max_len=20,\n max_ent_num=3,\n max_input=args.max_input,\n task=args.task\n )\n print('reading dev data...')\n dev_set = om.data.datasets.EDRMDataset(\n dataset=args.dev,\n wrd_tokenizer=tokenizer,\n ent_tokenizer=ent_tokenizer,\n mode='dev',\n query_max_len=args.max_query_len,\n doc_max_len=args.max_doc_len,\n des_max_len=20,\n max_ent_num=3,\n max_input=args.max_input,\n task=args.task\n )\n else:\n tokenizer = om.data.tokenizers.WordTokenizer(\n pretrained=args.vocab\n )\n print('reading training data...')\n train_set = om.data.datasets.Dataset(\n dataset=args.train,\n tokenizer=tokenizer,\n mode='train',\n query_max_len=args.max_query_len,\n doc_max_len=args.max_doc_len,\n max_input=args.max_input,\n task=args.task\n )\n print('reading dev data...')\n dev_set = om.data.datasets.Dataset(\n dataset=args.dev,\n tokenizer=tokenizer,\n mode='dev',\n query_max_len=args.max_query_len,\n doc_max_len=args.max_doc_len,\n max_input=args.max_input,\n task=args.task\n )\n\n if args.local_rank != -1:\n # train_sampler = DistributedSampler(train_set, args.world_size, args.local_rank)\n train_sampler = DistributedSampler(train_set)\n train_loader = om.data.DataLoader(\n dataset=train_set,\n batch_size=args.batch_size,\n shuffle=False,\n num_workers=1,\n sampler=train_sampler\n )\n #dev_sampler = DistributedSampler(dev_set)\n dev_sampler = DistributedEvalSampler(dev_set)\n dev_loader = om.data.DataLoader(\n dataset=dev_set,\n batch_size=args.batch_size * 16 if args.dev_eval_batch_size <= 0 else args.dev_eval_batch_size,\n shuffle=False,\n num_workers=1,\n sampler=dev_sampler\n )\n dist.barrier()\n\n else:\n train_loader = om.data.DataLoader(\n dataset=train_set,\n batch_size=args.batch_size,\n shuffle=True,\n num_workers=8\n )\n dev_loader = om.data.DataLoader(\n dataset=dev_set,\n batch_size=args.batch_size * 16,\n shuffle=False,\n num_workers=8\n )\n train_sampler = None\n\n if args.model == 'bert' or args.model == 'roberta':\n if args.maxp:\n model = om.models.BertMaxP(\n pretrained=args.pretrain,\n max_query_len=args.max_query_len,\n max_doc_len=args.max_doc_len,\n mode=args.mode,\n task=args.task\n )\n else:\n model = om.models.Bert(\n pretrained=args.pretrain,\n mode=args.mode,\n task=args.task\n )\n if args.reinfoselect:\n policy = om.models.Bert(\n pretrained=args.pretrain,\n mode=args.mode,\n task='classification'\n )\n elif args.model == 'edrm':\n model = om.models.EDRM(\n wrd_vocab_size=tokenizer.get_vocab_size(),\n ent_vocab_size=ent_tokenizer.get_vocab_size(),\n wrd_embed_dim=tokenizer.get_embed_dim(),\n ent_embed_dim=128,\n max_des_len=20,\n max_ent_num=3,\n kernel_num=args.n_kernels,\n kernel_dim=128,\n kernel_sizes=[1, 2, 3],\n wrd_embed_matrix=tokenizer.get_embed_matrix(),\n ent_embed_matrix=None,\n task=args.task\n )\n elif args.model == 'tk':\n model = om.models.TK(\n vocab_size=tokenizer.get_vocab_size(),\n embed_dim=tokenizer.get_embed_dim(),\n head_num=10,\n hidden_dim=100,\n layer_num=2,\n kernel_num=args.n_kernels,\n dropout=0.0,\n embed_matrix=tokenizer.get_embed_matrix(),\n task=args.task\n )\n elif args.model == 'cknrm':\n model = om.models.ConvKNRM(\n vocab_size=tokenizer.get_vocab_size(),\n embed_dim=tokenizer.get_embed_dim(),\n kernel_num=args.n_kernels,\n kernel_dim=128,\n kernel_sizes=[1, 2, 3],\n embed_matrix=tokenizer.get_embed_matrix(),\n task=args.task\n )\n elif args.model == 'knrm':\n model = om.models.KNRM(\n vocab_size=tokenizer.get_vocab_size(),\n embed_dim=tokenizer.get_embed_dim(),\n kernel_num=args.n_kernels,\n embed_matrix=tokenizer.get_embed_matrix(),\n task=args.task\n )\n else:\n raise ValueError('model name error.')\n\n if args.reinfoselect and args.model != 'bert':\n policy = om.models.ConvKNRM(\n vocab_size=tokenizer.get_vocab_size(),\n embed_dim=tokenizer.get_embed_dim(),\n kernel_num=args.n_kernels,\n kernel_dim=128,\n kernel_sizes=[1, 2, 3],\n embed_matrix=tokenizer.get_embed_matrix(),\n task='classification'\n )\n\n if args.checkpoint is not None:\n state_dict = torch.load(args.checkpoint)\n if args.model == 'bert':\n st = {}\n for k in state_dict:\n if k.startswith('bert'):\n st['_model'+k[len('bert'):]] = state_dict[k]\n elif k.startswith('classifier'):\n st['_dense'+k[len('classifier'):]] = state_dict[k]\n else:\n st[k] = state_dict[k]\n model.load_state_dict(st)\n else:\n model.load_state_dict(state_dict)\n\n # device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n device = args.device\n\n if args.reinfoselect:\n if args.task == 'ranking':\n loss_fn = nn.MarginRankingLoss(margin=1, reduction='none')\n elif args.task == 'classification':\n loss_fn = nn.CrossEntropyLoss(reduction='none')\n else:\n raise ValueError('Task must be `ranking` or `classification`.')\n else:\n if args.task == 'ranking':\n if args.ranking_loss == 'margin_loss':\n loss_fn = nn.MarginRankingLoss(margin=1)\n elif args.ranking_loss == 'CE_loss':\n loss_fn = nn.BCELoss()\n elif args.ranking_loss == 'triplet_loss':\n loss_fn = nn.BCELoss() # dummpy loss for occupation\n # loss_fn = F.log_softmax(dim=1)\n elif args.ranking_loss == 'LCE_loss':\n print(\"LCE loss TODO\")\n # nn.CrossEntropyLoss()\n\n elif args.task == 'classification':\n loss_fn = nn.CrossEntropyLoss()\n else:\n raise ValueError('Task must be `ranking` or `classification`.')\n\n\n model.to(device)\n if args.reinfoselect:\n policy.to(device)\n loss_fn.to(device)\n if args.n_gpu > 1:\n model = nn.DataParallel(model)\n loss_fn = nn.DataParallel(loss_fn)\n\n if args.local_rank != -1:\n model = torch.nn.parallel.DistributedDataParallel(\n model,\n device_ids=[\n args.local_rank],\n output_device=args.local_rank,\n find_unused_parameters=True,\n )\n dist.barrier()\n\n model.zero_grad()\n model.train()\n if args.optimizer.lower() == 'adam':\n m_optim = torch.optim.Adam(filter(lambda p: p.requires_grad, model.parameters()), lr=args.lr)\n elif args.optimizer.lower() == 'adamw':\n m_optim = AdamW(filter(lambda p: p.requires_grad, model.parameters()), lr=args.lr)\n\n if args.local_rank == -1:\n m_scheduler = get_linear_schedule_with_warmup(m_optim, num_warmup_steps=args.n_warmup_steps, num_training_steps=len(train_set)*args.epoch//args.batch_size)\n else:\n m_scheduler = get_linear_schedule_with_warmup(m_optim, num_warmup_steps=args.n_warmup_steps, num_training_steps=len(train_set)*args.epoch//(args.batch_size*args.world_size*args.gradient_accumulation_steps))\n if args.reinfoselect:\n p_optim = torch.optim.Adam(filter(lambda p: p.requires_grad, policy.parameters()), lr=args.lr)\n\n optimizer_to(m_optim,device)\n \n\n metric = om.metrics.Metric()\n\n logger.info(args)\n if args.reinfoselect:\n train_reinfoselect(args, model, policy, loss_fn, m_optim, m_scheduler, p_optim, metric, train_loader, dev_loader, device)\n else:\n train(args, model, loss_fn, m_optim, m_scheduler, metric, train_loader, dev_loader, device, train_sampler=train_sampler)\n\nif __name__ == \"__main__\":\n main()",
"from typing import List\n\nimport torch\nimport torch.nn as nn\n\nclass Embedder(nn.Module):\n def __init__(\n self,\n vocab_size: int,\n embed_dim: int,\n embed_matrix: List[float] = None\n ) -> None:\n super(Embedder, self).__init__()\n self._vocab_size = vocab_size\n self._embed_dim = embed_dim\n\n self._embedder = nn.Embedding(self._vocab_size, self._embed_dim, padding_idx=0)\n if embed_matrix is not None:\n self._embed_matrix = torch.tensor(embed_matrix)\n self._embedder.weight = nn.Parameter(self._embed_matrix, requires_grad=True)\n\n def forward(self, idx: torch.Tensor) -> torch.Tensor:\n embed = self._embedder(idx)\n return embed\n"
] |
[
[
"torch.nn.functional.gumbel_softmax",
"torch.nn.MarginRankingLoss",
"torch.cat",
"torch.distributions.Categorical",
"torch.sigmoid",
"torch.nn.DataParallel",
"torch.no_grad",
"torch.nn.parallel.DistributedDataParallel",
"torch.nn.functional.log_softmax",
"torch.utils.data.distributed.DistributedSampler",
"torch.load",
"torch.nn.BCELoss",
"torch.mean",
"torch.distributed.barrier",
"torch.nn.CrossEntropyLoss",
"torch.multiprocessing.set_sharing_strategy",
"torch.masked_select"
],
[
"torch.tensor",
"torch.nn.Embedding",
"torch.nn.Parameter"
]
] |
thunder95/Paddle
|
[
"27cb52a4cda29184851a53d63ea45d436c632e59"
] |
[
"python/paddle/fluid/tests/unittests/ipu/test_model_parallel_ipu.py"
] |
[
"# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport unittest\n\nimport numpy as np\nimport paddle\nimport paddle.static\nfrom paddle.fluid.tests.unittests.ipu.op_test_ipu import IPUOpTest\n\n\n@unittest.skipIf(not paddle.is_compiled_with_ipu(),\n \"core is not compiled with IPU\")\nclass TestBase(IPUOpTest):\n def setUp(self):\n self.set_atol()\n self.set_training()\n self.set_attrs()\n self.set_data_feed()\n\n def set_training(self):\n self.is_training = False\n self.epoch = 10\n\n def set_attrs(self):\n self.ipu_options = {\n \"batches_per_step\": 1,\n \"enable_pipelining\": False,\n \"enable_gradient_accumulation\": False,\n \"accumulation_factor\": 1,\n \"enable_replicated_graphs\": False,\n \"replicated_graph_count\": 1,\n }\n self.cpu_bs = 1\n self.ipu_bs = 1\n\n def set_data_feed(self):\n np_image = np.random.rand(1, 3, 10, 10).astype(np.float32)\n self.feed_cpu = {\"image\": np_image}\n self.feed_ipu = {\"image\": np_image}\n\n def _test_base(self, run_ipu=True):\n scope = paddle.static.Scope()\n main_prog = paddle.static.Program()\n startup_prog = paddle.static.Program()\n main_prog.random_seed = self.SEED\n startup_prog.random_seed = self.SEED\n\n bs = self.ipu_bs if run_ipu else self.cpu_bs\n with paddle.static.scope_guard(scope):\n with paddle.static.program_guard(main_prog, startup_prog):\n image = paddle.static.data(\n name='image', shape=[bs, 3, 10, 10], dtype='float32')\n with paddle.static.ipu_shard_guard(index=0):\n conv1 = paddle.static.nn.conv2d(\n image, num_filters=3, filter_size=3, bias_attr=False)\n with paddle.static.ipu_shard_guard(index=1):\n conv2 = paddle.static.nn.conv2d(\n conv1, num_filters=3, filter_size=3, bias_attr=False)\n # should consider influence of bs\n loss = paddle.mean(conv2)\n\n if self.is_training:\n if self.optimizer == 'sgd':\n opt = paddle.optimizer.SGD(learning_rate=1e-2)\n elif self.optimizer == 'adam':\n opt = paddle.optimizer.Adam(learning_rate=1e-2)\n elif self.optimizer == 'lamb':\n opt = paddle.optimizer.Lamb(learning_rate=1e-2)\n else:\n raise Exception('optimizer must be sgd, adam or lamb')\n\n opt.minimize(loss)\n\n if run_ipu:\n place = paddle.IPUPlace()\n else:\n place = paddle.CPUPlace()\n executor = paddle.static.Executor(place)\n executor.run(startup_prog)\n\n if run_ipu:\n feed_list = [image.name]\n fetch_list = [loss.name]\n ipu_strategy = paddle.static.IpuStrategy()\n ipu_strategy.set_graph_config(\n num_ipus=2 * self.ipu_options['replicated_graph_count'],\n is_training=self.is_training,\n enable_manual_shard=True)\n ipu_strategy.set_options(self.ipu_options)\n program = paddle.static.IpuCompiledProgram(\n main_prog,\n ipu_strategy=ipu_strategy).compile(feed_list, fetch_list)\n else:\n program = main_prog\n\n feed = self.feed_ipu if run_ipu else self.feed_cpu\n epoch = self.epoch\n if not run_ipu:\n epoch *= self.ipu_options['replicated_graph_count']\n epoch *= self.ipu_options['batches_per_step']\n epoch *= self.ipu_options['accumulation_factor']\n epoch = epoch / (self.cpu_bs / self.ipu_bs)\n result = []\n for i in range(int(epoch)):\n loss_res = executor.run(program, feed=feed, fetch_list=[loss])\n result.append(loss_res)\n return np.array(result).flatten()\n\n def test(self):\n cpu_outputs = self._test_base(False)\n ipu_outputs = self._test_base(True)\n\n self.assertTrue(np.allclose(cpu_outputs, ipu_outputs, atol=self.atol))\n\n\nclass TestReplicaInference(TestBase):\n def set_attrs(self):\n self.ipu_options = {\n \"batches_per_step\": 1,\n \"enable_pipelining\": False,\n \"enable_gradient_accumulation\": False,\n \"accumulation_factor\": 1,\n \"enable_replicated_graphs\": True,\n \"replicated_graph_count\": 2,\n }\n self.cpu_bs = 1\n self.ipu_bs = 1\n\n def set_data_feed(self):\n np_image = np.random.rand(1, 3, 10, 10).astype(np.float32)\n self.feed_cpu = {\"image\": np_image}\n self.feed_ipu = {\n \"image\":\n np.tile(np_image,\n [self.ipu_options['replicated_graph_count'], 1, 1, 1])\n }\n\n\nclass TestPipelineInference(TestBase):\n def set_attrs(self):\n self.ipu_options = {\n \"batches_per_step\": 2,\n \"enable_pipelining\": True,\n \"enable_gradient_accumulation\": False,\n \"accumulation_factor\": 1,\n \"enable_replicated_graphs\": False,\n \"replicated_graph_count\": 1,\n }\n self.cpu_bs = 1\n self.ipu_bs = 1\n\n def set_data_feed(self):\n np_image = np.random.rand(1, 3, 10, 10).astype(np.float32)\n self.feed_cpu = {\"image\": np_image}\n self.feed_ipu = {\n \"image\": np.tile(np_image,\n [self.ipu_options['batches_per_step'], 1, 1, 1])\n }\n\n\nclass TestTrainBase(TestBase):\n def set_training(self):\n self.is_training = True\n self.epoch = 10\n\n def set_attrs(self):\n self.ipu_options = {\n \"batches_per_step\": 1,\n \"enable_pipelining\": False,\n \"enable_gradient_accumulation\": False,\n \"accumulation_factor\": 1,\n \"enable_replicated_graphs\": False,\n \"replicated_graph_count\": 1,\n }\n self.cpu_bs = 1\n self.ipu_bs = 1\n self.optimizer = 'sgd'\n\n\nclass TestReplicaTrain(TestTrainBase):\n def set_attrs(self):\n self.ipu_options = {\n \"batches_per_step\": 1,\n \"enable_pipelining\": False,\n \"enable_gradient_accumulation\": False,\n \"accumulation_factor\": 1,\n \"enable_replicated_graphs\": True,\n \"replicated_graph_count\": 2,\n }\n self.cpu_bs = 2\n self.ipu_bs = 1\n self.optimizer = 'sgd'\n\n def set_data_feed(self):\n np_image = np.random.rand(1, 3, 10, 10).astype(np.float32)\n self.feed_cpu = {\"image\": np.tile(np_image, [self.cpu_bs, 1, 1, 1])}\n self.feed_ipu = {\n \"image\":\n np.tile(np_image,\n [self.ipu_options['replicated_graph_count'], 1, 1, 1])\n }\n\n def test(self):\n cpu_outputs = self._test_base(False)\n ipu_outputs = self._test_base(True)[::2]\n\n self.assertTrue(np.allclose(cpu_outputs, ipu_outputs, atol=self.atol))\n\n\nclass TestPipelineTrain(TestTrainBase):\n def set_attrs(self):\n self.ipu_options = {\n \"batches_per_step\": 3,\n \"enable_pipelining\": True,\n \"enable_gradient_accumulation\": True,\n \"accumulation_factor\": 3,\n \"enable_replicated_graphs\": False,\n \"replicated_graph_count\": 1,\n }\n self.cpu_bs = 3\n self.ipu_bs = 1\n self.optimizer = 'sgd'\n\n def set_data_feed(self):\n np_image = np.random.rand(1, 3, 10, 10).astype(np.float32)\n self.feed_cpu = {\"image\": np.tile(np_image, [self.cpu_bs, 1, 1, 1])}\n bps_acc = self.ipu_options['batches_per_step'] * self.ipu_options[\n 'accumulation_factor']\n self.feed_ipu = {\"image\": np.tile(np_image, [bps_acc, 1, 1, 1])}\n\n def test(self):\n cpu_outputs = self._test_base(False)\n ipu_outputs = self._test_base(True)[::3]\n\n self.assertTrue(np.allclose(cpu_outputs, ipu_outputs, atol=self.atol))\n\n\nclass TestAdamTrain(TestTrainBase):\n def set_attrs(self):\n self.ipu_options = {\n \"batches_per_step\": 1,\n \"enable_pipelining\": False,\n \"enable_gradient_accumulation\": False,\n \"accumulation_factor\": 1,\n \"enable_replicated_graphs\": False,\n \"replicated_graph_count\": 1,\n }\n self.cpu_bs = 1\n self.ipu_bs = 1\n self.optimizer = 'adam'\n\n\nclass TestAdamReplicaTrain(TestReplicaTrain):\n def set_attrs(self):\n self.ipu_options = {\n \"batches_per_step\": 1,\n \"enable_pipelining\": False,\n \"enable_gradient_accumulation\": False,\n \"accumulation_factor\": 1,\n \"enable_replicated_graphs\": True,\n \"replicated_graph_count\": 2,\n }\n self.cpu_bs = 2\n self.ipu_bs = 1\n self.optimizer = 'adam'\n\n\nclass TestAdamPipelineTrain(TestPipelineTrain):\n def set_attrs(self):\n self.ipu_options = {\n \"batches_per_step\": 3,\n \"enable_pipelining\": True,\n \"enable_gradient_accumulation\": True,\n \"accumulation_factor\": 3,\n \"enable_replicated_graphs\": False,\n \"replicated_graph_count\": 1,\n }\n self.cpu_bs = 3\n self.ipu_bs = 1\n self.optimizer = 'adam'\n\n\nclass TestAdamRecomputationTrain(TestPipelineTrain):\n def set_attrs(self):\n self.ipu_options = {\n \"batches_per_step\": 3,\n \"enable_pipelining\": True,\n \"enable_gradient_accumulation\": True,\n \"accumulation_factor\": 3,\n \"enable_replicated_graphs\": False,\n \"replicated_graph_count\": 1,\n \"auto_recomputation\": 3,\n }\n self.cpu_bs = 3\n self.ipu_bs = 1\n self.optimizer = 'adam'\n\n\nclass TestLambTrain(TestAdamTrain):\n def set_attrs(self):\n self.ipu_options = {\n \"batches_per_step\": 1,\n \"enable_pipelining\": False,\n \"enable_gradient_accumulation\": False,\n \"accumulation_factor\": 1,\n \"enable_replicated_graphs\": False,\n \"replicated_graph_count\": 1,\n }\n self.cpu_bs = 1\n self.ipu_bs = 1\n self.optimizer = 'lamb'\n\n\nclass TestLambReplicaTrain(TestAdamReplicaTrain):\n def set_attrs(self):\n self.ipu_options = {\n \"batches_per_step\": 1,\n \"enable_pipelining\": False,\n \"enable_gradient_accumulation\": False,\n \"accumulation_factor\": 1,\n \"enable_replicated_graphs\": True,\n \"replicated_graph_count\": 2,\n }\n self.cpu_bs = 2\n self.ipu_bs = 1\n self.optimizer = 'lamb'\n\n\nclass TestLambPipelineTrain(TestAdamPipelineTrain):\n def set_attrs(self):\n self.ipu_options = {\n \"batches_per_step\": 3,\n \"enable_pipelining\": True,\n \"enable_gradient_accumulation\": True,\n \"accumulation_factor\": 3,\n \"enable_replicated_graphs\": False,\n \"replicated_graph_count\": 1,\n }\n self.cpu_bs = 3\n self.ipu_bs = 1\n self.optimizer = 'lamb'\n\n\nif __name__ == \"__main__\":\n unittest.main()\n"
] |
[
[
"numpy.allclose",
"numpy.array",
"numpy.tile",
"numpy.random.rand"
]
] |
usuaero/MachUp_Py
|
[
"381d160afd8bff46cb1d3cd37c5b9b97e1e670e6"
] |
[
"test/use_cases/u1_from_file/test_from_file_u1.py"
] |
[
"\"\"\"Use Case #1: Read in from .json file\n\nThe following is an example of how to construct an Airplane object from\nan inputfile using the Machup geometry module.\n\nOne of the simplest ways to build an Airplane object is to read in an\nexisting Airplane from a .json file. These files can be exported from\nthe web version of Machup (see aero.go.usu.edu).\n\nDue to its handy graphical interface, one might want to construct the\nAirplane in the web version and then later export the .json file to be\nused in a python script that performs more complicated analysis.\n\"\"\"\n\nimport machup.geometry as geom\nfrom machup import LLModel\nimport numpy as np\n\n\ndef test_u1_read_in_from_file():\n # Generate airplane from file\n filename = \"test/use_cases/u1_from_file/use_case_1.json\"\n myPlane = geom.Airplane(inputfile=filename)\n\n # Generate lifting-line model for airplane\n myLLModel = LLModel(myPlane)\n\n # Solve the lifting-line model for the given condition\n controls = {\n \"aileron\": 10.,\n \"elevator\": 5.,\n }\n aero_state = {\n \"V_mag\": 100.,\n \"alpha\": 5.,\n \"rho\": 1.\n }\n results = myLLModel.solve(stype=\"linear\",\n control_state=controls,\n aero_state=aero_state)\n\n # compare results with expected values\n if myLLModel._machup_compare:\n test = np.array([498.563823789387015,\n -355.559967409590001,\n -22164.650382783511304,\n -15767.900012819352924,\n -6069.667491323640206,\n -485.172664364582431])\n else:\n test = np.array([488.73383601455544,\n -355.57437639926093,\n -22143.208875850567,\n -15767.798773697272,\n -6079.3470120008151,\n -485.09007262607491])\n\n assert np.allclose(results[\"FX\"], test[0], rtol=0., atol=1e-10) is True\n assert np.allclose(results[\"FY\"], test[1], rtol=0., atol=1e-10) is True\n assert np.allclose(results[\"FZ\"], test[2], rtol=0., atol=1e-10) is True\n assert np.allclose(results[\"l\"], test[3], rtol=0., atol=1e-10) is True\n assert np.allclose(results[\"m\"], test[4], rtol=0., atol=1e-10) is True\n assert np.allclose(results[\"n\"], test[5], rtol=0., atol=1e-10) is True\n"
] |
[
[
"numpy.allclose",
"numpy.array"
]
] |
lxc86739795/vehicle_reid_by_parsing
|
[
"a96496e11124d47d08a478696e0d3deb1e9b0c1a"
] |
[
"engine/trainer_selfgcn.py"
] |
[
"# encoding: utf-8\n\"\"\"\n@author: l1aoxingyu\n@contact: sherlockliao01@gmail.com\n\"\"\"\n\nimport os\nimport shutil\nimport time\nimport random\n\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nfrom torch import nn\n\n# Changed by Xinchen Liu\n\nfrom data import get_dataloader_mask\nfrom data.datasets.eval_reid import evaluate\nfrom data.prefetcher import data_prefetcher_mask\nfrom modeling import build_model_selfgcn\nfrom modeling.losses import TripletLoss\nfrom solver.build import make_lr_scheduler, make_optimizer\nfrom utils.meters import AverageMeter\n\n\ndef L_Matrix(adj_npy, adj_size):\n\n D =np.zeros((adj_size, adj_size))\n for i in range(adj_size):\n tmp = adj_npy[i,:]\n count = np.sum(tmp==1)\n if count>0:\n number = count ** (-1/2)\n D[i,i] = number\n\n x = np.matmul(D,adj_npy)\n L = np.matmul(x,D)\n return L\n\n\ncoarse_adj_list = [\n # 1 2 3 4 5 6 7 8 9\n [ 1, 1, 0, 1, 0, 1, 0, 1, 0], #1\n [ 1, 1, 1, 1, 0, 1, 0, 0, 0], #2\n [ 0, 1, 1, 0, 1, 0, 1, 0, 0], #3\n [ 1, 1, 0, 1, 1, 0, 0, 1, 0], #4\n [ 0, 0, 1, 1, 1, 0, 0, 0, 1], #5\n [ 1, 1, 0, 0, 0, 1, 1, 1, 0], #6\n [ 0, 0, 1, 0, 0, 1, 1, 0, 1], #7\n [ 1, 0, 0, 1, 0, 1, 0, 1, 1], #8\n [ 0, 0, 0, 0, 1, 0, 1, 1, 1] #9\n]\ncoarse_adj_npy = np.array(coarse_adj_list)\ncoarse_adj_npy = L_Matrix(coarse_adj_npy, len(coarse_adj_npy))\n\n\nclass ReidSystem():\n def __init__(self, cfg, logger, writer):\n self.cfg, self.logger, self.writer = cfg, logger, writer\n # Define dataloader\n self.tng_dataloader, self.val_dataloader_collection, self.num_classes, self.num_query_len_collection = get_dataloader_mask(cfg)\n # networks\n self.use_part_erasing = False\n self.num_parts = cfg.MODEL.NUM_PARTS\n self.model = build_model_selfgcn(cfg, self.num_classes)\n self.adj = torch.from_numpy(coarse_adj_npy).float()\n # loss function\n self.ce_loss = nn.CrossEntropyLoss()\n self.triplet = TripletLoss(cfg.SOLVER.MARGIN)\n self.mse_loss = nn.MSELoss()\n # optimizer and scheduler\n self.opt = make_optimizer(self.cfg, self.model)\n self.lr_sched = make_lr_scheduler(self.cfg, self.opt)\n\n self.loss_weight = [1.0, 1.0, 0.5, 0.5, 0.5, 0.5, 0.4]\n self.logger.info(f\"Loss weights: {self.loss_weight}, use_pe: {self.use_part_erasing}, use_bnfeat: {True}\")\n self._construct()\n\n def _construct(self):\n self.global_step = 0\n self.current_epoch = 0\n self.batch_nb = 0\n self.max_epochs = self.cfg.SOLVER.MAX_EPOCHS\n self.log_interval = self.cfg.SOLVER.LOG_INTERVAL\n self.eval_period = self.cfg.SOLVER.EVAL_PERIOD\n self.use_dp = False\n self.use_ddp = False\n\n def loss_fns(self, outputs, labels_global, labels_gcn):\n loss_dict = {}\n\n if 'softmax' in list(self.cfg.SOLVER.LOSSTYPE):\n loss_dict['ce_g'] = self.ce_loss(outputs[0], labels_global)*self.loss_weight[0]\n loss_dict['ce_l1'] = self.ce_loss(outputs[2], labels_gcn)*self.loss_weight[2]\n loss_dict['ce_l2'] = self.ce_loss(outputs[4], labels_gcn)*self.loss_weight[4]\n if 'triplet' in list(self.cfg.SOLVER.LOSSTYPE):\n loss_dict['tr_g'] = self.triplet(outputs[1], labels_global)[0]*self.loss_weight[1]\n loss_dict['tr_l1'] = self.triplet(outputs[3], labels_gcn)[0]*self.loss_weight[3]\n loss_dict['tr_l2'] = self.triplet(outputs[5], labels_gcn)[0]*self.loss_weight[5]\n \n# target_gcn_feat = outputs[6].clone().detach().requires_grad_(False)\n# loss_dict['mse'] = self.mse_loss(target_gcn_feat, outputs[7])*self.loss_weight[6]\n loss_dict['mse'] = self.mse_loss(outputs[6], outputs[7])*self.loss_weight[6]\n \n return loss_dict\n\n def on_train_begin(self):\n self.best_mAP = -np.inf\n self.running_loss = AverageMeter()\n log_save_dir = os.path.join(self.cfg.OUTPUT_DIR, '-'.join(self.cfg.DATASETS.TEST_NAMES), self.cfg.MODEL.VERSION)\n self.model_save_dir = os.path.join(log_save_dir, 'ckpts')\n if not os.path.exists(self.model_save_dir): os.makedirs(self.model_save_dir)\n\n self.gpus = os.environ['CUDA_VISIBLE_DEVICES'].split(',')\n self.use_dp = (len(self.gpus) > 0) and (self.cfg.MODEL.DIST_BACKEND == 'dp')\n\n if self.use_dp:\n self.model = nn.DataParallel(self.model)\n\n self.model = self.model.cuda()\n self.model.train()\n self.adj = self.adj.cuda()\n\n def on_epoch_begin(self):\n self.batch_nb = 0\n self.current_epoch += 1\n self.t0 = time.time()\n self.running_loss.reset()\n\n self.tng_prefetcher = data_prefetcher_mask(self.tng_dataloader)\n\n def training_step(self, batch):\n\n inputs, masks, labels, _ = batch\n adj_batch = self.adj.repeat(inputs.size(0), 1, 1)\n \n inputs_global = inputs\n inputs_selfgcn = inputs\n labels_global = labels\n labels_selfgcn = labels\n \n if self.use_part_erasing:\n# inputs_masked = torch.zeros(inputs.size(), dtype=inputs.dtype)\n \n # random part erasing\n for i in range(inputs.size(0)):\n input = inputs[i]\n mask = masks[i]\n part_list = []\n for c in range(1, self.num_parts):\n part = (mask.long() == c)\n if part.any():\n part_list.append(c)\n drop_part = random.choice(part_list)\n mask = (mask.long() != drop_part)\n if random.uniform(0, 1) > 0.5:\n inputs_selfgcn[i] = mask.float()*input\n# inputs_masked[i] = mask.float()*input\n \n# inputs_masked = inputs_masked.cuda()\n# inputs_global = torch.cat([inputs, inputs_masked], dim=0)\n# labels_global = torch.cat([labels, labels], dim=0)\n\n outputs = self.model(inputs_global, inputs_selfgcn, masks, adj_batch)\n\n loss_dict = self.loss_fns(outputs, labels_global, labels_selfgcn)\n\n total_loss = 0\n print_str = f'\\r Epoch {self.current_epoch} Iter {self.batch_nb}/{len(self.tng_dataloader)} '\n for loss_name, loss_value in loss_dict.items():\n total_loss += loss_value\n print_str += (loss_name+f': {loss_value.item():.3f} ')\n loss_dict['total_loss'] = total_loss.item()\n print_str += f'Total loss: {total_loss.item():.3f} '\n print(print_str, end=' ')\n \n if (self.global_step+1) % self.log_interval == 0:\n for loss_name, loss_value in loss_dict.items():\n self.writer.add_scalar(loss_name, loss_value, self.global_step)\n self.writer.add_scalar('total_loss', loss_dict['total_loss'], self.global_step)\n\n self.running_loss.update(total_loss.item())\n\n self.opt.zero_grad()\n total_loss.backward()\n self.opt.step()\n\n self.global_step += 1\n self.batch_nb += 1\n \n def on_epoch_end(self):\n elapsed = time.time() - self.t0\n mins = int(elapsed) // 60\n seconds = int(elapsed - mins * 60)\n print('')\n self.logger.info(f'Epoch {self.current_epoch} Total loss: {self.running_loss.avg:.3f} '\n f'lr: {self.opt.param_groups[0][\"lr\"]:.2e} During {mins:d}min:{seconds:d}s')\n # update learning rate\n self.lr_sched.step()\n\n def test(self):\n # convert to eval mode\n self.model.eval()\n \n metric_dict = list()\n for val_dataset_name, val_dataloader, num_query in zip(self.cfg.DATASETS.TEST_NAMES, self.val_dataloader_collection, self.num_query_len_collection):\n feats, pids, camids = [], [], []\n val_prefetcher = data_prefetcher_mask(val_dataloader)\n batch = val_prefetcher.next()\n while batch[0] is not None:\n img, mask, pid, camid = batch\n adj_batch = self.adj.repeat(img.size(0), 1, 1)\n \n with torch.no_grad():\n output = self.model(img, img, mask, adj_batch)\n \n# feat = output[1]\n feat = torch.cat([output[1], output[3]], dim=1)\n \n feats.append(feat)\n pids.extend(pid.cpu().numpy())\n camids.extend(np.asarray(camid))\n\n batch = val_prefetcher.next()\n\n feats = torch.cat(feats, dim=0)\n if self.cfg.TEST.NORM:\n feats = F.normalize(feats, p=2, dim=1)\n # query\n qf = feats[:num_query]\n q_pids = np.asarray(pids[:num_query])\n q_camids = np.asarray(camids[:num_query])\n # gallery\n gf = feats[num_query:]\n g_pids = np.asarray(pids[num_query:])\n g_camids = np.asarray(camids[num_query:])\n\n # m, n = qf.shape[0], gf.shape[0]\n distmat = torch.mm(qf, gf.t()).cpu().numpy()\n # distmat = torch.pow(qf, 2).sum(dim=1, keepdim=True).expand(m, n) + \\\n # torch.pow(gf, 2).sum(dim=1, keepdim=True).expand(n, m).t()\n # distmat.addmm_(1, -2, qf, gf.t())\n # distmat = distmat.numpy()\n cmc, mAP = evaluate(-distmat, q_pids, g_pids, q_camids, g_camids)\n self.logger.info(f\"Test Results on {val_dataset_name} - Epoch: {self.current_epoch}\")\n self.logger.info(f\"mAP: {mAP:.1%}\")\n for r in [1, 5, 10]:\n self.logger.info(f\"CMC curve, Rank-{r:<3}:{cmc[r - 1]:.1%}\")\n\n self.writer.add_scalar('rank1', cmc[0], self.global_step)\n self.writer.add_scalar('mAP', mAP, self.global_step)\n metric_dict.append({'rank1': cmc[0], 'mAP': mAP})\n # convert to train mode\n self.model.train()\n return metric_dict[0]\n\n def train(self):\n self.on_train_begin()\n# self.test()\n for epoch in range(self.max_epochs):\n self.on_epoch_begin()\n batch = self.tng_prefetcher.next()\n while batch[0] is not None:\n self.training_step(batch)\n batch = self.tng_prefetcher.next()\n self.on_epoch_end()\n if (epoch+1) % self.eval_period == 0:\n metric_dict = self.test()\n if metric_dict['mAP'] > self.best_mAP:\n is_best = True\n self.best_mAP = metric_dict['mAP']\n else:\n is_best = False\n self.save_checkpoints(is_best)\n\n torch.cuda.empty_cache()\n\n def save_checkpoints(self, is_best):\n if self.use_dp:\n state_dict = self.model.module.state_dict()\n else:\n state_dict = self.model.state_dict()\n \n # TODO: add optimizer state dict and lr scheduler\n filepath = os.path.join(self.model_save_dir, f'model_epoch{self.current_epoch}.pth')\n torch.save(state_dict, filepath)\n if is_best:\n best_filepath = os.path.join(self.model_save_dir, 'model_best.pth')\n shutil.copyfile(filepath, best_filepath)\n"
] |
[
[
"torch.nn.functional.normalize",
"numpy.array",
"torch.cat",
"numpy.matmul",
"numpy.zeros",
"torch.nn.MSELoss",
"numpy.asarray",
"numpy.sum",
"torch.save",
"torch.no_grad",
"torch.from_numpy",
"torch.cuda.empty_cache",
"torch.nn.CrossEntropyLoss",
"torch.nn.DataParallel"
]
] |
marsbroshok/imgaug-doc
|
[
"7443efbf66263c0c44581ed62501fae6f88b047a"
] |
[
"scripts/generate_rtd_images/gen_segmentation_maps.py"
] |
[
"from __future__ import print_function, division\n\nfrom .utils import save\n\n\ndef main():\n \"\"\"Generate all example images for the chapter `Examples: Segmentation Maps`\n in the documentation.\"\"\"\n chapter_examples_segmentation_maps_simple()\n # chapter_examples_segmentation_maps_bool_full()\n chapter_examples_segmentation_maps_bool_small()\n chapter_examples_segmentation_maps_array()\n\n\ndef chapter_examples_segmentation_maps_simple():\n import imageio\n import numpy as np\n import imgaug as ia\n import imgaug.augmenters as iaa\n from imgaug.augmentables.segmaps import SegmentationMapsOnImage\n\n ia.seed(1)\n\n # Load an example image (uint8, 128x128x3).\n image = ia.quokka(size=(128, 128), extract=\"square\")\n\n # Define an example segmentation map (int32, 128x128).\n # Here, we arbitrarily place some squares on the image.\n # Class 0 is our intended background class.\n segmap = np.zeros((128, 128, 1), dtype=np.int32)\n segmap[28:71, 35:85, 0] = 1\n segmap[10:25, 30:45, 0] = 2\n segmap[10:25, 70:85, 0] = 3\n segmap[10:110, 5:10, 0] = 4\n segmap[118:123, 10:110, 0] = 5\n segmap = SegmentationMapsOnImage(segmap, shape=image.shape)\n\n # Define our augmentation pipeline.\n seq = iaa.Sequential([\n iaa.Dropout([0.05, 0.2]), # drop 5% or 20% of all pixels\n iaa.Sharpen((0.0, 1.0)), # sharpen the image\n iaa.Affine(rotate=(-45, 45)), # rotate by -45 to 45 degrees (affects segmaps)\n iaa.ElasticTransformation(alpha=50, sigma=5) # apply water effect (affects segmaps)\n ], random_order=True)\n\n # Augment images and segmaps.\n images_aug = []\n segmaps_aug = []\n for _ in range(5):\n images_aug_i, segmaps_aug_i = seq(image=image, segmentation_maps=segmap)\n images_aug.append(images_aug_i)\n segmaps_aug.append(segmaps_aug_i)\n\n # We want to generate an image containing the original input image and\n # segmentation maps before/after augmentation. (Both multiple times for\n # multiple augmentations.)\n #\n # The whole image is supposed to have five columns:\n # (1) original image,\n # (2) original image with segmap,\n # (3) augmented image,\n # (4) augmented segmap on augmented image,\n # (5) augmented segmap on its own in.\n #\n # We now generate the cells of these columns.\n #\n # Note that draw_on_image() and draw() both return lists of drawn\n # images. Assuming that the segmentation map array has shape (H,W,C),\n # the list contains C items.\n cells = []\n for image_aug, segmap_aug in zip(images_aug, segmaps_aug):\n cells.append(image) # column 1\n cells.append(segmap.draw_on_image(image)[0]) # column 2\n cells.append(image_aug) # column 3\n cells.append(segmap_aug.draw_on_image(image_aug)[0]) # column 4\n cells.append(segmap_aug.draw(size=image_aug.shape[:2])[0]) # column 5\n\n # Convert cells to a grid image and save.\n grid_image = ia.draw_grid(cells, cols=5)\n # imageio.imwrite(\"example_segmaps.jpg\", grid_image)\n\n save(\n \"examples_segmentation_maps\",\n \"simple.jpg\",\n grid_image,\n quality=90\n )\n\n\ndef chapter_examples_segmentation_maps_bool_full():\n import imgaug as ia\n from imgaug import augmenters as iaa\n import imageio\n import numpy as np\n\n ia.seed(1)\n\n # Load an example image (uint8, 128x128x3).\n image = ia.quokka(size=(128, 128), extract=\"square\")\n\n # Create an example mask (bool, 128x128).\n # Here, we just randomly place a square on the image.\n segmap = np.zeros((128, 128), dtype=bool)\n segmap[28:71, 35:85] = True\n segmap = ia.SegmentationMapOnImage(segmap, shape=image.shape)\n\n # Define our augmentation pipeline.\n seq = iaa.Sequential([\n iaa.Dropout([0.05, 0.2]), # drop 5% or 20% of all pixels\n iaa.Sharpen((0.0, 1.0)), # sharpen the image\n iaa.Affine(rotate=(-45, 45)), # rotate by -45 to 45 degrees (affects heatmaps)\n iaa.ElasticTransformation(alpha=50, sigma=5) # apply water effect (affects heatmaps)\n ], random_order=True)\n\n # Augment images and heatmaps.\n images_aug = []\n segmaps_aug = []\n for _ in range(5):\n seq_det = seq.to_deterministic()\n images_aug.append(seq_det.augment_image(image))\n segmaps_aug.append(seq_det.augment_segmentation_maps([segmap])[0])\n\n # We want to generate an image of original input images and heatmaps before/after augmentation.\n # It is supposed to have five columns: (1) original image, (2) augmented image,\n # (3) augmented heatmap on top of augmented image, (4) augmented heatmap on its own in jet\n # color map, (5) augmented heatmap on its own in intensity colormap,\n # We now generate the cells of these columns.\n #\n # Note that we add a [0] after each heatmap draw command. That's because the heatmaps object\n # can contain many sub-heatmaps and hence we draw command returns a list of drawn sub-heatmaps.\n # We only used one sub-heatmap, so our lists always have one entry.\n cells = []\n for image_aug, segmap_aug in zip(images_aug, segmaps_aug):\n cells.append(image) # column 1\n cells.append(segmap.draw_on_image(image)) # column 2\n cells.append(image_aug) # column 3\n cells.append(segmap_aug.draw_on_image(image_aug)) # column 4\n cells.append(segmap_aug.draw(size=image_aug.shape[:2])) # column 5\n\n # Convert cells to grid image and save.\n grid_image = ia.draw_grid(cells, cols=5)\n #imageio.imwrite(\"example_segmaps_bool.jpg\", grid_image)\n\n save(\n \"examples_segmentation_maps\",\n \"bool_full.jpg\",\n grid_image,\n quality=90\n )\n\n\ndef chapter_examples_segmentation_maps_bool_small():\n import imageio\n import numpy as np\n import imgaug as ia\n from imgaug.augmentables.segmaps import SegmentationMapsOnImage\n\n # Load an example image (uint8, 128x128x3).\n image = ia.quokka(size=(128, 128), extract=\"square\")\n\n # Create an example mask (bool, 128x128).\n # Here, we arbitrarily place a square on the image.\n segmap = np.zeros((128, 128, 1), dtype=bool)\n segmap[28:71, 35:85, 0] = True\n segmap = SegmentationMapsOnImage(segmap, shape=image.shape)\n\n # Draw three columns: (1) original image,\n # (2) original image with mask on top, (3) only mask\n cells = [\n image,\n segmap.draw_on_image(image)[0],\n segmap.draw(size=image.shape[:2])[0]\n ]\n\n # Convert cells to a grid image and save.\n grid_image = ia.draw_grid(cells, cols=3)\n # imageio.imwrite(\"example_segmaps_bool.jpg\", grid_image)\n\n save(\n \"examples_segmentation_maps\",\n \"bool_small.jpg\",\n grid_image,\n quality=90\n )\n\n\ndef chapter_examples_segmentation_maps_array():\n import imageio\n import numpy as np\n import imgaug as ia\n from imgaug.augmentables.segmaps import SegmentationMapsOnImage\n\n # Load an example image (uint8, 128x128x3).\n image = ia.quokka(size=(128, 128), extract=\"square\")\n\n # Create an example segmentation map (int32, 128x128).\n # Here, we arbitrarily place some squares on the image.\n # Class 0 is the background class.\n segmap = np.zeros((128, 128, 1), dtype=np.int32)\n segmap[28:71, 35:85, 0] = 1\n segmap[10:25, 30:45, 0] = 2\n segmap[10:25, 70:85, 0] = 3\n segmap[10:110, 5:10, 0] = 4\n segmap[118:123, 10:110, 0] = 5\n segmap1 = SegmentationMapsOnImage(segmap, shape=image.shape)\n\n # Read out the segmentation map's array, change it and create a new\n # segmentation map\n arr = segmap1.get_arr()\n arr[10:110, 5:10, 0] = 5\n segmap2 = ia.SegmentationMapsOnImage(arr, shape=image.shape)\n\n # Draw three columns: (1) original image, (2) original image with\n # unaltered segmentation map on top, (3) original image with altered\n # segmentation map on top\n cells = [\n image,\n segmap1.draw_on_image(image)[0],\n segmap2.draw_on_image(image)[0]\n ]\n\n # Convert cells to grid image and save.\n grid_image = ia.draw_grid(cells, cols=3)\n # imageio.imwrite(\"example_segmaps_array.jpg\", grid_image)\n\n save(\n \"examples_segmentation_maps\",\n \"array.jpg\",\n grid_image,\n quality=90\n )\n\n\nif __name__ == \"__main__\":\n main()\n"
] |
[
[
"numpy.zeros"
]
] |
Taiki-Ishigaki/ERIC
|
[
"81a0eb3cbfdadfdb1f4efde711fe1c3b26ba876a"
] |
[
"bipedal_robot/lipm/lipm_simulate.py"
] |
[
"#!/usr/bin/env python3\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nimport matplotlib.patches as patches\n\nclass LinearInvertedPendulum(object):\n gravity = 9.8 # gravity\n\n def __init__(self, height = 1.5, weight = 50):\n self.height = height\n self.omega2 = self.gravity / self.height\n self.omega = np.sqrt(self.omega2)\n\n self.A = np.array([[0, 1],[self.omega2, 0]]) # state matrix\n self.B = np.array([[0],[-self.omega2]]) # input matrix\n\n \n def init_state(self, x, x_ref, u_ref, dt = 0.01, x_dot = 0., x_ddot = 0):\n self.X = np.array([[x], [x_dot]])\n self.X_dot = np.array([[x_dot], [x_ddot]])\n self.u = self.bestCOG_Regulator(x_ref, u_ref)\n self.dT = dt\n\n def do_action(self, x_ref, u_ref):\n self.u = self.bestCOG_Regulator(x_ref, u_ref)\n self.update_state()\n\n def update_state(self):\n self.X_dot = self.A @ self.X + self.B @ self.u\n self.X =self.X + self.X_dot * self.dT \n\n def bestCOG_Regulator(self, x_ref, u_ref):\n self.alpha = 3.0\n self.F = self.alpha * np.array([[1.0, 1.0/self.omega2]])\n return u_ref - self.F @ (x_ref - self.X)\n\n def get_X(self):\n return self.X\n \n def get_u(self):\n return self.u\n\ndef video(x_hs, u_hs, h, t, fig):\n ax = fig.add_subplot(221, aspect='equal', autoscale_on=False, xlim=(-2, 2), ylim=(-0.5, 3.5))\n ax.grid()\n\n #line\n line, = ax.plot([], [], '-r', lw=2)\n time_text = ax.text(0.02, 0.95, 'time = 0.0', transform=ax.transAxes)\n\n # cog circle\n circle, = ax.plot([], [], '-r', lw=2)\n radius = 0.1\n angles = np.arange(0.0, np.pi * 2.0, np.radians(3.0))\n ox = radius * np.cos(angles) \n oy = radius * np.sin(angles)\n\n rectangle = ax.add_patch(patches.Rectangle(xy=(u_hs[0]-0.25/2, -0.25/2), width=0.25, height=0.25, ec='r', fill=False, lw=2))\n\n def init():\n line.set_data([], [])\n circle.set_data([], [])\n rectangle.set_xy([u_hs[0]-0.25/2, -0.25/2])\n time_text.set_text('')\n return line, time_text\n\n def animate(i):\n line.set_data([u_hs[i], x_hs[i]],[0, h])\n circle.set_data([ox + x_hs[i]],[ oy + h])\n rectangle.set_xy([u_hs[i]-0.25/2, -0.25/2])\n time_text.set_text('time = {0:.2f}'.format(i*t))\n return line, time_text\n\n ani = animation.FuncAnimation(fig, animate, frames=range(len(x_hs)),\n interval=t*1000, blit=False, init_func=init)\n plt.show()\n #ani.save(\"output.gif\", writer=\"imagemagick\")\n\nif __name__ == '__main__':\n x_ref = np.array([[0.5],[0.]])\n u_ref = np.array([[0.5]])\n x_start = 0.0\n dt = 0.01\n period = 4\n height = 1.5\n time_step = (int) (period / dt)\n plant = LinearInvertedPendulum(height)\n plant.init_state(x_start, x_ref, u_ref, dt)\n X_history = np.array(plant.get_X())\n u_history = np.array(plant.get_u())\n for i in range(time_step-1):\n plant.do_action(x_ref, u_ref)\n u_history = np.append(u_history, plant.get_u(), axis=1)\n X_history = np.append(X_history, plant.get_X(), axis=1)\n\n t = np.linspace(0, time_step*dt, time_step)\n\n fig = plt.figure()\n\n plt.subplot(212)\n plt.plot(t, X_history[0], label=\"COG position\")\n plt.plot(t, X_history[1], label=\"COG velosity\")\n plt.plot(t, u_history[0], label=\"ZMP position\")\n plt.legend()\n \n video(X_history[0], u_history[0], plant.height, dt, fig)\n"
] |
[
[
"numpy.array",
"numpy.sin",
"matplotlib.patches.Rectangle",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.figure",
"numpy.radians",
"numpy.sqrt",
"numpy.cos",
"matplotlib.pyplot.show",
"numpy.linspace",
"matplotlib.pyplot.subplot"
]
] |
ttthomaschan/cptn-crnn-pytorch
|
[
"396ffd8fe92bcc766c0c43e51bb3fb4c339098e7"
] |
[
"train_code/train_ctpn/ctpn_train.py"
] |
[
"#-*- coding:utf-8 -*-\n#'''\n# Created on 18-12-27 上午10:31\n#\n#'''\nimport os\nos.environ['CUDA_VISIBLE_DEVICES'] = '0'\nimport torch\nfrom torch.utils.data import DataLoader\nfrom torch import optim\nimport torchvision\nimport numpy as np\nimport argparse\n\nimport config\nfrom ctpn_model import CTPN_Model, RPN_CLS_Loss, RPN_REGR_Loss\nfrom data.dataset import ICDARDataset\n\nimport cv2\nfrom tensorboardX import SummaryWriter\n \nwriter = SummaryWriter('runs/exp-1')\n\nrandom_seed = 2019\ntorch.random.manual_seed(random_seed)\nnp.random.seed(random_seed)\n\nepochs = 20\nlr = 1e-3\nresume_epoch = 0\n\n\ndef save_checkpoint(state, epoch, loss_cls, loss_regr, loss, ext='pth'):\n check_path = os.path.join(config.checkpoints_dir,\n f'v3_ctpn_ep{epoch:02d}_'\n f'best.{ext}')\n\n try:\n torch.save(state, check_path)\n except BaseException as e:\n print(e)\n print('fail to save to {}'.format(check_path))\n print('saving to {}'.format(check_path))\n\n\n# 权重初始化常规方法为调用torch.nn.init中:\n# constant(tensor,val)\n# normal(tensor,mean=0,std=1)\n# xavier_uniform(tensor,gain)\n# 此处为权重初始化的特别设置\ndef weights_init(m):\n classname = m.__class__.__name__\n if classname.find('Conv') != -1:\n m.weight.data.normal_(0.0, 0.02)\n elif classname.find('BatchNorm') != -1:\n m.weight.data.normal_(1.0, 0.02)\n m.bias.data.fill_(0)\n\n\nif __name__ == '__main__':\n device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n print(\"device:\")\n print(torch.cuda.is_available())\n checkpoints_weight = config.pretrained_weights\n print('exist pretrained ',os.path.exists(checkpoints_weight))\n if os.path.exists(checkpoints_weight):\n pretrained = False\n\n dataset = ICDARDataset(config.icdar19_mlt_img_dir, config.icdar19_mlt_gt_dir)\n dataloader = DataLoader(dataset, batch_size=1, shuffle=True, num_workers=config.num_workers)\n model = CTPN_Model()\n model.to(device)\n \n if os.path.exists(checkpoints_weight):\n print('using pretrained weight: {}'.format(checkpoints_weight))\n cc = torch.load(checkpoints_weight, map_location=device)\n model.load_state_dict(cc['model_state_dict'])\n resume_epoch = cc['epoch']\n else:\n model.apply(weights_init) ## 函数-Module.apply(fn):会递归地搜索网络内的所有module并把参数表示的函数应用到所有的module上。\n\n params_to_update = model.parameters()\n optimizer = optim.SGD(params_to_update, lr=lr, momentum=0.9)\n \n critetion_cls = RPN_CLS_Loss(device)\n critetion_regr = RPN_REGR_Loss(device)\n \n best_loss_cls = 100\n best_loss_regr = 100\n best_loss = 100\n best_model = None\n epochs += resume_epoch\n scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=10, gamma=0.1)\n \n # image, clsss, regrss = next(iter(dataloader))\n # image = image.to(device)\n # print(image.shape)\n\n # print(image.device)\n # print(next(model.parameters()).device)\n # with writer:\n # writer.add_images('images', image)\n # writer.add_graph(model,image)\n\n\n for epoch in range(resume_epoch+1, epochs):\n print(f'Epoch {epoch}/{epochs}')\n print('#'*50)\n epoch_size = len(dataset) // 1\n model.train()\n epoch_loss_cls = 0\n epoch_loss_regr = 0\n epoch_loss = 0\n scheduler.step(epoch)\n \n for batch_i, (imgs, clss, regrs) in enumerate(dataloader):\n print(imgs.shape)\n imgs = imgs.to(device)\n clss = clss.to(device)\n regrs = regrs.to(device)\n \n optimizer.zero_grad()\n \n out_cls, out_regr = model(imgs)\n #with writer:\n # writer.add_graph(model,imgs)\n\n loss_cls = critetion_cls(out_cls, clss)\n loss_regr = critetion_regr(out_regr, regrs)\n \n loss = loss_cls + loss_regr # total loss\n loss.backward()\n optimizer.step()\n \n epoch_loss_cls += loss_cls.item()\n epoch_loss_regr += loss_regr.item()\n epoch_loss += loss.item()\n mmp = batch_i+1\n \n \n print(f'Ep:{epoch}/{epochs-1}--'\n f'Batch:{batch_i}/{epoch_size}\\n'\n f'batch: loss_cls:{loss_cls.item():.4f}--loss_regr:{loss_regr.item():.4f}--loss:{loss.item():.4f}\\n'\n f'Epoch: loss_cls:{epoch_loss_cls/mmp:.4f}--loss_regr:{epoch_loss_regr/mmp:.4f}--'\n f'loss:{epoch_loss/mmp:.4f}\\n')\n\n #if epoch == 1 and batch_i == 0:\n # writer.add_graph(model,imgs)\n # print(\"writing graph to tensorboardx \\n\")\n # print(imgs.device)\n # print(next(model.parameters()).is_cuda)\n \n epoch_loss_cls /= epoch_size\n epoch_loss_regr /= epoch_size\n epoch_loss /= epoch_size\n writer.add_scalar('loss_cls', epoch_loss_cls, epoch)\n writer.add_scalar('loss_regs', epoch_loss_regr, epoch)\n print(f'Epoch:{epoch}--{epoch_loss_cls:.4f}--{epoch_loss_regr:.4f}--{epoch_loss:.4f}')\n \n if best_loss_cls > epoch_loss_cls or best_loss_regr > epoch_loss_regr or best_loss > epoch_loss:\n best_loss = epoch_loss\n best_loss_regr = epoch_loss_regr\n best_loss_cls = epoch_loss_cls\n best_model = model\n save_checkpoint({'model_state_dict': best_model.state_dict(),\n 'epoch': epoch},\n epoch,\n best_loss_cls,\n best_loss_regr,\n best_loss)\n \n if torch.cuda.is_available():\n torch.cuda.empty_cache()\n\n"
] |
[
[
"torch.optim.lr_scheduler.StepLR",
"numpy.random.seed",
"torch.save",
"torch.optim.SGD",
"torch.random.manual_seed",
"torch.cuda.empty_cache",
"torch.cuda.is_available",
"torch.utils.data.DataLoader",
"torch.load"
]
] |
HappyKL/mindspore
|
[
"c3d1f54c7f6d6f514e5748430d24b16a4f9ee9e5"
] |
[
"tests/ut/python/parallel/test_reshape_unexpand.py"
] |
[
"# Copyright 2020 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport numpy as np\n\nimport mindspore as ms\nimport mindspore.nn as nn\nfrom mindspore import Tensor\nfrom mindspore import context\nfrom mindspore.common.api import _executor\nfrom mindspore.common.parameter import Parameter\nfrom mindspore.ops import composite as C\nfrom mindspore.ops import operations as P\nfrom tests.ut.python.ops.test_math_ops import VirtualLoss\n\n\ngrad_all = C.GradOperation(get_all=True)\n\n\nclass NetWithLoss(nn.Cell):\n def __init__(self, network):\n super(NetWithLoss, self).__init__()\n self.loss = VirtualLoss()\n self.network = network\n\n def construct(self, x):\n predict = self.network(x)\n return self.loss(predict)\n\n\nclass GradWrap(nn.Cell):\n def __init__(self, network):\n super(GradWrap, self).__init__()\n self.network = network\n\n def construct(self, x):\n return grad_all(self.network)(x)\n\ndef test_reshape_unexpand():\n class Net(nn.Cell):\n def __init__(self):\n super().__init__()\n self.reshape = P.Reshape()\n self.mul = P.Mul().shard(((1, 8), (1, 1, 8)))\n self.mul_weight = Parameter(Tensor(np.ones([96, 128]), dtype=ms.float32), name=\"weight\")\n\n def construct(self, x):\n weight = self.reshape(self.mul_weight, (1, 128, 96))\n out = self.mul(x, weight)\n return out\n\n size = 8\n context.set_auto_parallel_context(device_num=size, global_rank=0)\n x = Tensor(np.ones([128, 96]), dtype=ms.float32)\n\n net = GradWrap(NetWithLoss(Net()))\n context.set_auto_parallel_context(parallel_mode=\"semi_auto_parallel\")\n net.set_auto_parallel()\n _executor.compile(net, x)\n\ndef test_reshape_unexpand_1():\n class Net(nn.Cell):\n def __init__(self):\n super().__init__()\n self.reshape = P.Reshape()\n self.mul = P.Mul().shard(((1, 8), (1, 1, 8)))\n self.mul_weight = Parameter(Tensor(np.ones([96, 128]), dtype=ms.float32), name=\"weight\")\n\n def construct(self, x):\n weight = self.reshape(self.mul_weight, (1, 128, 96))\n out = self.mul(x, weight)\n return out\n\n size = 8\n context.set_auto_parallel_context(device_num=size, global_rank=0)\n x = Tensor(np.ones([128, 96]), dtype=ms.float32)\n\n net = GradWrap(NetWithLoss(Net()))\n context.set_auto_parallel_context(parallel_mode=\"semi_auto_parallel\")\n net.set_auto_parallel()\n _executor.compile(net, x)\n\ndef test_reshape_unexpand_2():\n class Net(nn.Cell):\n def __init__(self):\n super().__init__()\n self.reshape = P.Reshape()\n self.mul = P.Mul().shard(((1, 4, 2), (4, 2)))\n self.mul_weight = Parameter(Tensor(np.ones([128, 96]), dtype=ms.float32), name=\"weight\")\n\n def construct(self, data):\n x = self.reshape(self.mul_weight, (1, 128, 96))\n out = self.mul(x, self.mul_weight)\n return out\n\n size = 8\n context.set_auto_parallel_context(device_num=size, global_rank=0)\n x = Tensor(np.ones([128, 96]), dtype=ms.float32)\n\n net = GradWrap(NetWithLoss(Net()))\n context.set_auto_parallel_context(parallel_mode=\"semi_auto_parallel\")\n net.set_auto_parallel()\n _executor.compile(net, x)\n\ndef test_reshape_unexpand_3():\n class Net(nn.Cell):\n def __init__(self):\n super().__init__()\n self.reshape = P.Reshape()\n self.relu1 = P.ReLU().shard(((4, 1),))\n self.relu2 = P.ReLU().shard(((1, 4),))\n\n def construct(self, data):\n x = self.relu1(data)\n x = self.reshape(x, (3, 4))\n x = self.relu2(x)\n return x\n\n size = 4\n context.set_auto_parallel_context(device_num=size, global_rank=0)\n x = Tensor(np.ones([4, 3]), dtype=ms.float32)\n\n net = GradWrap(NetWithLoss(Net()))\n context.set_auto_parallel_context(parallel_mode=\"semi_auto_parallel\")\n net.set_auto_parallel()\n _executor.compile(net, x)\n\ndef test_reshape_unexpand_4():\n class Net(nn.Cell):\n def __init__(self):\n super().__init__()\n self.reshape = P.Reshape()\n self.relu1 = P.ReLU().shard(((4, 1),))\n self.relu2 = P.ReLU().shard(((1, 2, 2),))\n\n def construct(self, data):\n x = self.relu1(data)\n x = self.reshape(x, (3, 2, 2))\n x = self.relu2(x)\n return x\n\n size = 4\n context.set_auto_parallel_context(device_num=size, global_rank=0)\n x = Tensor(np.ones([4, 3]), dtype=ms.float32)\n\n net = GradWrap(NetWithLoss(Net()))\n context.set_auto_parallel_context(parallel_mode=\"semi_auto_parallel\")\n net.set_auto_parallel()\n _executor.compile(net, x)\n\ndef test_reshape_unexpand_5():\n class Net(nn.Cell):\n def __init__(self):\n super().__init__()\n self.reshape = P.Reshape()\n self.relu1 = P.ReLU().shard(((2, 2, 1),))\n self.relu2 = P.ReLU().shard(((1, 4),))\n\n def construct(self, data):\n x = self.relu1(data)\n x = self.reshape(x, (3, 4))\n x = self.relu2(x)\n return x\n\n size = 4\n context.set_auto_parallel_context(device_num=size, global_rank=0)\n x = Tensor(np.ones([2, 2, 3]), dtype=ms.float32)\n\n net = GradWrap(NetWithLoss(Net()))\n context.set_auto_parallel_context(parallel_mode=\"semi_auto_parallel\")\n net.set_auto_parallel()\n _executor.compile(net, x)\n\ndef test_reshape_unexpand_6():\n class Net(nn.Cell):\n def __init__(self):\n super().__init__()\n self.reshape = P.Reshape()\n self.relu1 = P.ReLU().shard(((2, 1),))\n self.relu2 = P.ReLU().shard(((1, 1, 4),))\n\n def construct(self, data):\n x = self.relu1(data)\n x = self.reshape(x, (1, 3, 4))\n x = self.relu2(x)\n return x\n\n size = 4\n context.set_auto_parallel_context(device_num=size, global_rank=0)\n x = Tensor(np.ones([4, 3]), dtype=ms.float32)\n\n net = GradWrap(NetWithLoss(Net()))\n context.set_auto_parallel_context(parallel_mode=\"semi_auto_parallel\")\n net.set_auto_parallel()\n _executor.compile(net, x)\n\ndef test_reshape_unexpand_7():\n class Net(nn.Cell):\n def __init__(self, in_channel=3, out_channel=8, axis=1, input_shape=(32, 4, 110, -1),\n mul_size=(32, 1, 220, 220)):\n super().__init__()\n mul_np = np.full(mul_size, 0.5, dtype=np.float32)\n self.mul_weight = Parameter(Tensor(mul_np), name=\"mul_weight\")\n self.mul = P.Mul()\n self.conv = nn.Conv2d(in_channels=in_channel, out_channels=out_channel,\n kernel_size=5, has_bias=True, weight_init='ones',\n bias_init='ones', pad_mode='valid')\n self.softmax = nn.Softmax(axis=axis)\n self.relu = nn.ReLU()\n self.reshape = P.Reshape()\n self.input_shape = input_shape\n\n def construct(self, inputs):\n x = self.conv(inputs)\n x = self.softmax(x)\n x = self.relu(x)\n x = self.mul(x, self.mul_weight)\n x = self.reshape(x, self.input_shape)\n return x\n\n size = 8\n context.set_auto_parallel_context(device_num=size, global_rank=0)\n context.set_auto_parallel_context(parallel_mode=\"auto_parallel\")\n x = Tensor(np.ones([32, 3, 224, 224]), dtype=ms.float32)\n net = GradWrap(NetWithLoss(Net()))\n net.set_auto_parallel()\n _executor.compile(net, x)\n"
] |
[
[
"numpy.full",
"numpy.ones"
]
] |
shauncameron/ChatBot
|
[
"0b3168204788e3e44369c0a96f8e0321f74790ad"
] |
[
"venv/Lib/site-packages/nltk/metrics/segmentation.py"
] |
[
"# Natural Language Toolkit: Text Segmentation Metrics\n#\n# Copyright (C) 2001-2021 NLTK Project\n# Author: Edward Loper <edloper@gmail.com>\n# Steven Bird <stevenbird1@gmail.com>\n# David Doukhan <david.doukhan@gmail.com>\n# URL: <http://nltk.org/>\n# For license information, see LICENSE.TXT\n\n\n\"\"\"\nText Segmentation Metrics\n\n1. Windowdiff\n\nPevzner, L., and Hearst, M., A Critique and Improvement of\n an Evaluation Metric for Text Segmentation,\nComputational Linguistics 28, 19-36\n\n\n2. Generalized Hamming Distance\n\nBookstein A., Kulyukin V.A., Raita T.\nGeneralized Hamming Distance\nInformation Retrieval 5, 2002, pp 353-375\n\nBaseline implementation in C++\nhttp://digital.cs.usu.edu/~vkulyukin/vkweb/software/ghd/ghd.html\n\nStudy describing benefits of Generalized Hamming Distance Versus\nWindowDiff for evaluating text segmentation tasks\nBegsten, Y. Quel indice pour mesurer l'efficacite en segmentation de textes ?\nTALN 2009\n\n\n3. Pk text segmentation metric\n\nBeeferman D., Berger A., Lafferty J. (1999)\nStatistical Models for Text Segmentation\nMachine Learning, 34, 177-210\n\"\"\"\n\ntry:\n import numpy as np\nexcept ImportError:\n pass\n\n\ndef windowdiff(seg1, seg2, k, boundary=\"1\", weighted=False):\n \"\"\"\n Compute the windowdiff score for a pair of segmentations. A\n segmentation is any sequence over a vocabulary of two items\n (e.g. \"0\", \"1\"), where the specified boundary value is used to\n mark the edge of a segmentation.\n\n >>> s1 = \"000100000010\"\n >>> s2 = \"000010000100\"\n >>> s3 = \"100000010000\"\n >>> '%.2f' % windowdiff(s1, s1, 3)\n '0.00'\n >>> '%.2f' % windowdiff(s1, s2, 3)\n '0.30'\n >>> '%.2f' % windowdiff(s2, s3, 3)\n '0.80'\n\n :param seg1: a segmentation\n :type seg1: str or list\n :param seg2: a segmentation\n :type seg2: str or list\n :param k: window width\n :type k: int\n :param boundary: boundary value\n :type boundary: str or int or bool\n :param weighted: use the weighted variant of windowdiff\n :type weighted: boolean\n :rtype: float\n \"\"\"\n\n if len(seg1) != len(seg2):\n raise ValueError(\"Segmentations have unequal length\")\n if k > len(seg1):\n raise ValueError(\n \"Window width k should be smaller or equal than segmentation lengths\"\n )\n wd = 0\n for i in range(len(seg1) - k + 1):\n ndiff = abs(seg1[i : i + k].count(boundary) - seg2[i : i + k].count(boundary))\n if weighted:\n wd += ndiff\n else:\n wd += min(1, ndiff)\n return wd / (len(seg1) - k + 1.0)\n\n\n# Generalized Hamming Distance\n\n\ndef _init_mat(nrows, ncols, ins_cost, del_cost):\n mat = np.empty((nrows, ncols))\n mat[0, :] = ins_cost * np.arange(ncols)\n mat[:, 0] = del_cost * np.arange(nrows)\n return mat\n\n\ndef _ghd_aux(mat, rowv, colv, ins_cost, del_cost, shift_cost_coeff):\n for i, rowi in enumerate(rowv):\n for j, colj in enumerate(colv):\n shift_cost = shift_cost_coeff * abs(rowi - colj) + mat[i, j]\n if rowi == colj:\n # boundaries are at the same location, no transformation required\n tcost = mat[i, j]\n elif rowi > colj:\n # boundary match through a deletion\n tcost = del_cost + mat[i, j + 1]\n else:\n # boundary match through an insertion\n tcost = ins_cost + mat[i + 1, j]\n mat[i + 1, j + 1] = min(tcost, shift_cost)\n\n\ndef ghd(ref, hyp, ins_cost=2.0, del_cost=2.0, shift_cost_coeff=1.0, boundary=\"1\"):\n \"\"\"\n Compute the Generalized Hamming Distance for a reference and a hypothetical\n segmentation, corresponding to the cost related to the transformation\n of the hypothetical segmentation into the reference segmentation\n through boundary insertion, deletion and shift operations.\n\n A segmentation is any sequence over a vocabulary of two items\n (e.g. \"0\", \"1\"), where the specified boundary value is used to\n mark the edge of a segmentation.\n\n Recommended parameter values are a shift_cost_coeff of 2.\n Associated with a ins_cost, and del_cost equal to the mean segment\n length in the reference segmentation.\n\n >>> # Same examples as Kulyukin C++ implementation\n >>> ghd('1100100000', '1100010000', 1.0, 1.0, 0.5)\n 0.5\n >>> ghd('1100100000', '1100000001', 1.0, 1.0, 0.5)\n 2.0\n >>> ghd('011', '110', 1.0, 1.0, 0.5)\n 1.0\n >>> ghd('1', '0', 1.0, 1.0, 0.5)\n 1.0\n >>> ghd('111', '000', 1.0, 1.0, 0.5)\n 3.0\n >>> ghd('000', '111', 1.0, 2.0, 0.5)\n 6.0\n\n :param ref: the reference segmentation\n :type ref: str or list\n :param hyp: the hypothetical segmentation\n :type hyp: str or list\n :param ins_cost: insertion cost\n :type ins_cost: float\n :param del_cost: deletion cost\n :type del_cost: float\n :param shift_cost_coeff: constant used to compute the cost of a shift.\n shift cost = shift_cost_coeff * |i - j| where i and j are\n the positions indicating the shift\n :type shift_cost_coeff: float\n :param boundary: boundary value\n :type boundary: str or int or bool\n :rtype: float\n \"\"\"\n\n ref_idx = [i for (i, val) in enumerate(ref) if val == boundary]\n hyp_idx = [i for (i, val) in enumerate(hyp) if val == boundary]\n\n nref_bound = len(ref_idx)\n nhyp_bound = len(hyp_idx)\n\n if nref_bound == 0 and nhyp_bound == 0:\n return 0.0\n elif nref_bound > 0 and nhyp_bound == 0:\n return nref_bound * ins_cost\n elif nref_bound == 0 and nhyp_bound > 0:\n return nhyp_bound * del_cost\n\n mat = _init_mat(nhyp_bound + 1, nref_bound + 1, ins_cost, del_cost)\n _ghd_aux(mat, hyp_idx, ref_idx, ins_cost, del_cost, shift_cost_coeff)\n return mat[-1, -1]\n\n\n# Beeferman's Pk text segmentation evaluation metric\n\n\ndef pk(ref, hyp, k=None, boundary=\"1\"):\n \"\"\"\n Compute the Pk metric for a pair of segmentations A segmentation\n is any sequence over a vocabulary of two items (e.g. \"0\", \"1\"),\n where the specified boundary value is used to mark the edge of a\n segmentation.\n\n >>> '%.2f' % pk('0100'*100, '1'*400, 2)\n '0.50'\n >>> '%.2f' % pk('0100'*100, '0'*400, 2)\n '0.50'\n >>> '%.2f' % pk('0100'*100, '0100'*100, 2)\n '0.00'\n\n :param ref: the reference segmentation\n :type ref: str or list\n :param hyp: the segmentation to evaluate\n :type hyp: str or list\n :param k: window size, if None, set to half of the average reference segment length\n :type boundary: str or int or bool\n :param boundary: boundary value\n :type boundary: str or int or bool\n :rtype: float\n \"\"\"\n\n if k is None:\n k = int(round(len(ref) / (ref.count(boundary) * 2.0)))\n\n err = 0\n for i in range(len(ref) - k + 1):\n r = ref[i : i + k].count(boundary) > 0\n h = hyp[i : i + k].count(boundary) > 0\n if r != h:\n err += 1\n return err / (len(ref) - k + 1.0)\n\n\n# skip doctests if numpy is not installed\ndef setup_module(module):\n import pytest\n\n try:\n import numpy\n except ImportError:\n pytest.skip(\"numpy is required for nltk.metrics.segmentation\")\n"
] |
[
[
"numpy.arange",
"numpy.empty"
]
] |
lithomas1/fastparquet
|
[
"089a592ebf9eca72b7ef16134d89749ff5454936"
] |
[
"fastparquet/test/test_overwrite.py"
] |
[
"\"\"\"\n test_overwrite.py\n Tests for overwriting parquet files.\n\"\"\"\n\nimport pandas as pd\nimport pytest\nfrom fastparquet import write, ParquetFile\nfrom fastparquet.test.util import tempdir\n\n\ndef test_write_with_rgp_by_date_as_index(tempdir):\n\n # Step 1 - Writing of a 1st df, with `row_group_offsets=0`,\n # `file_scheme=hive` and `partition_on=['location', 'color`].\n df1 = pd.DataFrame({'humidity': [0.3, 0.8, 0.9],\n 'pressure': [1e5, 1.1e5, 0.95e5],\n 'location': ['Paris', 'Paris', 'Milan'],\n 'color': ['red', 'black', 'blue']})\n write(tempdir, df1, row_group_offsets=0, file_scheme='hive',\n partition_on=['location', 'color'])\n\n # Step 2 - Overwriting with a 2nd df having overlapping data, in\n # 'overwrite' mode:\n # `row_group_offsets=0`, `file_scheme=hive`,\n # `partition_on=['location', 'color`] and `append=True`.\n df2 = pd.DataFrame({'humidity': [0.5, 0.3, 0.4, 0.8, 1.1],\n 'pressure': [9e4, 1e5, 1.1e5, 1.1e5, 0.95e5],\n 'location': ['Milan', 'Paris', 'Paris', 'Paris', 'Paris'],\n 'color': ['red', 'black', 'black', 'green', 'green' ]})\n\n write(tempdir, df2, row_group_offsets=0, file_scheme='hive', append='overwrite',\n partition_on=['location', 'color'])\n\n expected = pd.DataFrame({'humidity': [0.9, 0.5, 0.3, 0.4, 0.8, 1.1, 0.3],\n 'pressure': [9.5e4, 9e4, 1e5, 1.1e5, 1.1e5, 9.5e4, 1e5],\n 'location': ['Milan', 'Milan', 'Paris', 'Paris', 'Paris', 'Paris', 'Paris'],\n 'color': ['blue', 'red', 'black', 'black', 'green', 'green', 'red']})\\\n .astype({'location': 'category', 'color': 'category'})\n recorded = ParquetFile(tempdir).to_pandas()\n # df1 is 3 rows, df2 is 5 rows. Because of overlapping data with keys\n # 'location' = 'Paris' & 'color' = 'black' (1 row in df2, 2 rows in df2)\n # resulting df contains for this combination values of df2 and not that of\n # df1. Total resulting number of rows is 7.\n assert expected.equals(recorded)\n\ndef test_several_existing_parts_in_folder_exception(tempdir):\n\n df1 = pd.DataFrame({'humidity': [0.3, 0.8, 0.9, 0.7],\n 'pressure': [1e5, 1.1e5, 0.95e5, 1e5],\n 'location': ['Paris', 'Paris', 'Milan', 'Paris'],\n 'exterior': ['yes', 'no', 'yes', 'yes']})\n\n write(tempdir, df1, row_group_offsets = 1, file_scheme='hive',\n write_index=False, partition_on=['location', 'exterior'])\n\n with pytest.raises(ValueError, match=\"^Some partition folders\"):\n write(tempdir, df1, row_group_offsets = 0, file_scheme='hive',\n write_index=False, partition_on=['location', 'exterior'],\n append='overwrite')\n\n"
] |
[
[
"pandas.DataFrame"
]
] |
MinRegret/TigerControl
|
[
"b1ca0617cbb2198f9d5cb37f725f3d7accbab08f"
] |
[
"deprecated/environments/pybullet/tests/test_humanoid.py"
] |
[
"\"\"\"\nAn example to run of the half cheetah gym environment with random gaits.\n\"\"\"\n\nimport tigercontrol\nimport numpy as np\nimport time\n\ndef test_humanoid(steps=1000, verbose=False):\n environment = tigercontrol.environment(\"PyBullet-Humanoid\")\n environment.reset(render=verbose)\n\n sum_reward = 0\n amplitude1 = 0.5\n amplitude2 = 0.5\n speed = 40\n\n action = np.random.normal(size=environment.action_space)\n\n for step_counter in range(steps):\n action = 0.95 * action + np.random.normal(size=environment.action_space)\n _, reward, done, _ = environment.step(action)\n time.sleep(1. / 100.)\n\n sum_reward += reward\n if done:\n environment.reset()\n \n environment.close()\n print(\"test_humanoid passed\")\n\n\nif __name__ == '__main__':\n #test_humanoid(verbose=True)\n pass\n\n"
] |
[
[
"numpy.random.normal"
]
] |
zqNiu/Rollout_algorithm_for_3D_assignment
|
[
"a658c5198376e30f2997d907608382c6c5a7a167"
] |
[
"Rollout_for_Three_Dimensional_Assignment.py"
] |
[
"import numpy as np\r\nimport time\r\nimport gurobipy as gp\r\nfrom gurobipy import GRB\r\n\r\nN=99999\r\ndef rollout_3D_assignment(cost_matrix,maximize=False):\r\n \"\"\"Solve the 3D assignment using the rollout algorithm according to Bertsekas's paper\r\n\r\n parameters\r\n ----------\r\n cost_matrix : 3D-array j-m-w job-machine-worker\r\n The cost matrix of the assignment group.\r\n maximize : bool (default: False)\r\n Calculates a maximum weight matching if true.\r\n Returns\r\n -------\r\n assign : 2D-array \r\n corresponding indices giving the optimal assignment\r\n index: job index col: machine index value: worker index\r\n obj: float\r\n objective function \r\n\r\n References\r\n ----------\r\n 1. [Bertsekas's Rollout Algorithm]\r\n (http://web.mit.edu/dimitrib/www/Rollout_Constrained_Multiagent.pdf). \r\n \"\"\"\r\n cost_matrix = np.asarray(cost_matrix)\r\n if cost_matrix.ndim != 3:\r\n raise ValueError(\"expected a matrix (3-D array), got a %r array\"\r\n % (cost_matrix.shape,))\r\n\r\n if not (np.issubdtype(cost_matrix.dtype, np.number) or\r\n cost_matrix.dtype == np.dtype(np.bool_)):\r\n raise ValueError(\"expected a matrix containing numerical entries, got %s\"\r\n % (cost_matrix.dtype,))\r\n\r\n #get the initial solution \r\n num_job=num_machine=num_worker=cost_matrix.shape[0]\r\n assign_jm=-np.ones(num_job)\r\n current_assign_jm=enforced_separation_heuristics(assign_jm,cost_matrix)[\"assign_jm\"]\r\n current_obj=enforced_separation_heuristics(assign_jm,cost_matrix)[\"obj\"]\r\n\r\n for j in range(num_job):\r\n current_branch_solutions=np.zeros(num_machine)\r\n current_branch_assign=dict()\r\n for m in range(num_machine):\r\n temp_assign_jm=assign_jm.copy().astype(int)\r\n if (temp_assign_jm== m).any():\r\n continue\r\n temp_assign_jm[j]=m\r\n current_branch_solutions[m]=enforced_separation_heuristics(temp_assign_jm,cost_matrix)[\"obj\"]\r\n current_branch_assign[m]=enforced_separation_heuristics(temp_assign_jm,cost_matrix)[\"assign_jm\"]\r\n\r\n min_solution=np.min(current_branch_solutions)\r\n min_m_index=np.where(current_branch_solutions==min_solution)[0][0]\r\n if min_solution<=current_obj and min_solution!=0:\r\n current_obj=min_solution\r\n assign_jm[j]=min_m_index\r\n current_assign_jm=current_branch_assign[min_m_index]\r\n\r\n else:\r\n if not (assign_jm==current_assign_jm[j]).any():\r\n assign_jm[j]=current_assign_jm[j]\r\n\r\n \r\n final_assign=enforced_separation_heuristics(assign_jm,cost_matrix)[\"assign_2D\"]\r\n final_solution=enforced_separation_heuristics(assign_jm,cost_matrix)[\"obj\"]\r\n\r\n print(\"rollout result:\",final_solution,final_assign)\r\n\r\n\r\n\r\n\r\ndef enforced_separation_heuristics(assign_jm,cost_matrix,maximize=False):\r\n \"\"\"\r\n parameters\r\n ----------\r\n assign_jm: 1D-array j-m job-machine\r\n some j-m pairs are fixed \r\n cost_matrix : 3D-array j-m-w job-machine-worker\r\n The cost matrix of the assignment group.\r\n maximize : bool (default: False)\r\n Calculates a maximum weight matching if true.\r\n Returns\r\n -------\r\n assign : 2D-array \r\n corresponding indices giving the optimal assignment\r\n index: job index col: machine index value: worker index\r\n obj: float\r\n objective function \r\n\r\n get the solution by using enforced separation heuristics \r\n the core thought is decoupling the assignment cost\r\n by first focusing on assigning machines to workers\r\n then focusing on assigning jobs to machines\r\n \"\"\"\r\n\r\n num_job=num_machine=num_worker=cost_matrix.shape[0]\r\n job_index_2_real_job=dict()\r\n machine_index_2_real_machine=dict()\r\n job_index=machine_index=0\r\n #step1 decouple the cost\r\n cost_matrix_m_w=-np.ones((num_machine,num_worker)) \r\n #row: machine col:worker\r\n for j in range(num_job):\r\n for m in range(num_machine):\r\n for w in range(num_worker):\r\n if assign_jm[j]>0:\r\n #the j-m pair is fixed c_mw=c_jmw\r\n cost_matrix_m_w[m][w]=cost_matrix[j,int(assign_jm[j]),w]\r\n else:\r\n # c_mw=min{j,c_jmw}\r\n cost_matrix_m_w[m][w]=np.min(cost_matrix[:,m,w])\r\n\r\n #step2 solve the assignment between machines and workers\r\n assign_m_w=auction_asy(cost_matrix_m_w,True)[\"assign\"]\r\n #step3 calculate the cost between jobs and machines\r\n job_index=0\r\n for j in range(num_job):\r\n if (assign_jm[j]<0):\r\n # not fixed\r\n job_index_2_real_job[job_index]=j\r\n job_index+=1\r\n machine_index=0 \r\n for m in range(num_machine):\r\n if not (assign_jm==m).any():\r\n # not fixed\r\n machine_index_2_real_machine[machine_index]=m\r\n machine_index+=1\r\n assert(job_index==machine_index)\r\n cost_matrix_j_m=np.zeros((job_index,machine_index))\r\n\r\n for j in range(job_index):\r\n for m in range(job_index):\r\n real_job=job_index_2_real_job[j]\r\n real_machine=machine_index_2_real_machine[m]\r\n cost_matrix_j_m[j][m]=cost_matrix[real_job,int(real_machine),int(assign_m_w[int(real_machine)])]\r\n #step4 solve the assignment between jobs and machines\r\n if not (assign_jm>-1).all():\r\n assign_j_m=auction_asy(cost_matrix_j_m,True)[\"assign\"]\r\n for j in range(job_index):\r\n real_job=job_index_2_real_job[j]\r\n real_machine=machine_index_2_real_machine[assign_j_m[j]]\r\n assign_jm[real_job]=real_machine\r\n \r\n \r\n #step5 calculate objective fuction and output 3D assignment result\r\n assign_2D=-np.ones((num_job,num_machine))\r\n for j in range(num_job):\r\n assign_2D[j][int(assign_jm[j])]=assign_m_w[int(assign_jm[j])]\r\n\r\n obj=0\r\n for j in range(num_job):\r\n for m in range(num_machine):\r\n for w in range(num_worker):\r\n if(assign_2D[j][m]==w):\r\n obj+=cost_matrix[j][m][w]\r\n\r\n return {\"assign_2D\":assign_2D,\"obj\":obj,\"assign_jm\":assign_jm}\r\n\r\n\r\n\r\n \r\n\r\ndef auction_asy(cost_matrix,minimize=False):\r\n \"\"\"\r\n Python Implemention of Bertsekas's Auction Algorithm by Zhiqiang Niu\r\n the source code can be found in https://github.com/zqNiu/Auction-Algorithm-python\r\n\r\n arameters\r\n ----------\r\n cost_matrix : array\r\n The cost matrix of the assignment.\r\n minimize : bool (default: False)\r\n Calculates a minimize weight matching if true.\r\n Returns\r\n -------\r\n assign : array\r\n corresponding indices giving the optimal assignment\r\n index: row index value: col index. \r\n obj: float\r\n objective function \r\n \"\"\"\r\n cost_matrix = np.asarray(cost_matrix)\r\n if cost_matrix.ndim != 2:\r\n raise ValueError(\"expected a matrix (2-D array), got a %r array\"\r\n % (cost_matrix.shape,))\r\n\r\n if not (np.issubdtype(cost_matrix.dtype, np.number) or\r\n cost_matrix.dtype == np.dtype(np.bool_)):\r\n raise ValueError(\"expected a matrix containing numerical entries, got %s\"\r\n % (cost_matrix.dtype,))\r\n\r\n if minimize:\r\n cost_matrix = -cost_matrix\r\n \r\n cost_matrix = cost_matrix.astype(np.double)\r\n\r\n # auction algorithm implement \r\n \r\n num_person=num_object=cost_matrix.shape[0]\r\n assign=np.asarray([-N]*(num_person))\r\n epsilon=abs(np.min(cost_matrix))+1\r\n price=np.asarray([np.min(cost_matrix)]*(num_object))\r\n \r\n while(abs(epsilon) >1/num_person):\r\n assign=np.asarray([-N]*(num_person))\r\n time_start=time.time()\r\n while ((assign<0).any()):\r\n #bidding phase\r\n #Compute the bids of each unassigned individual person and store them in temp array\r\n bid_value=np.zeros((num_person,num_object)) # row:person col:object\r\n best_margin=-N \r\n best_margin_j_index=-N\r\n second_margin=-N\r\n second_margin_j_index=-N\r\n for i in range(num_person):\r\n if assign[i]<0:\r\n # unassigned\r\n # Need calculate the best(max) and second best(max) value of each object to this person\r\n for j in range(num_object):\r\n margin=cost_matrix[i][j]-price[j]\r\n if margin>best_margin:\r\n best_margin=margin\r\n best_margin_j_index=j\r\n elif margin>second_margin:\r\n second_margin=margin\r\n second_margin_j_index=j\r\n\r\n if (second_margin==-N): # only one positive bid for j\r\n second_margin=best_margin\r\n\r\n bid_value[i][best_margin_j_index]=cost_matrix[i][best_margin_j_index]-\\\r\n second_margin+epsilon\r\n # also =price[best_margin_j_index]+best_margin-second_margin+epsilon\r\n #assignment phase\r\n #Each object which has received a bid determines the highest bidder and \r\n #updates its price accordingly\r\n bid_value_T=np.transpose(bid_value) # row:object col:person\r\n for j in range(num_object):\r\n bid_for_j=bid_value_T[j]\r\n if((bid_for_j>0).any()):\r\n max_bid=np.max(bid_for_j)\r\n max_bid_person=np.where(bid_for_j==np.max(bid_for_j))[0][0]\r\n if np.where(assign==j)[0].shape[0]>0:\r\n # j has been assigned, corresponding i need be set to unassigned \r\n i_index=np.where(assign==j)[0][0]\r\n assign[i_index]=-N\r\n assign[max_bid_person]=j\r\n price[j]=max_bid\r\n\r\n epsilon=epsilon/2\r\n \r\n obj=0\r\n for i in range(num_person):\r\n obj+=cost_matrix[i][assign[i]]\r\n\r\n if minimize:\r\n obj=-obj\r\n return {\"assign\":assign,\"obj\":obj,\"price\":price}\r\n\r\ndef gurobi_solve(cost_matrix):\r\n \"\"\" Three-Dimensional Assignment problem\r\n sum(c_jmw*x_jmw)\r\n s.t.\r\n sum(j,x_jmw)=e=1 for each (m,w) \r\n sum(m,x_jmw)=e=1 for each (j,w)\r\n sum(w,x_jmw)=e=1 for each (j,m)\r\n \"\"\"\r\n #变量\r\n model=gp.Model('three_dimensional_assing_problem')\r\n model.setParam('OutputFlag', 0)\r\n num_job=num_machine=num_worker=cost_matrix.shape[0]\r\n x=[[[0 for j in range(num_job)] for m in range(num_machine)] for w in range(num_worker)]\r\n for j in range(num_job):\r\n for m in range(num_machine):\r\n for w in range(num_worker):\r\n x[j][m][w]=model.addVar(lb=0,ub=1,vtype=GRB.BINARY)\r\n #目标 \r\n obj=gp.LinExpr()\r\n for j in range(num_job):\r\n for m in range(num_machine):\r\n for w in range(num_worker):\r\n obj+= cost_matrix[j][m][w]*x[j][m][w]\r\n\r\n model.setObjective(obj,GRB.MINIMIZE)\r\n #约束\r\n for j in range(num_job):\r\n sum_1=gp.LinExpr()\r\n for m in range(num_machine):\r\n for w in range(num_worker):\r\n sum_1+=x[j][m][w]\r\n \r\n model.addConstr(sum_1==1)\r\n\r\n for m in range(num_machine):\r\n sum_2=gp.LinExpr()\r\n for j in range(num_job):\r\n for w in range(num_worker):\r\n sum_2+=x[j][m][w]\r\n \r\n model.addConstr(sum_2==1)\r\n\r\n for w in range(num_worker):\r\n sum_3=gp.LinExpr()\r\n for j in range(num_job):\r\n for m in range(num_machine):\r\n sum_3+=x[j][m][w]\r\n \r\n model.addConstr(sum_3==1)\r\n #求解 \r\n model.write('3D_assign.lp')\r\n model.optimize()\r\n\r\n assign=-np.ones((num_job,num_machine))\r\n for j in range(num_job):\r\n for m in range(num_machine):\r\n for w in range(num_worker):\r\n if (x[j][m][w].x>0):\r\n assign[j][m]=w\r\n \r\n obj=obj.getValue()\r\n print(\"gurobi result:\",obj,assign)\r\n return {\"assign\":assign,\"obj\":obj}\r\n\r\n\r\nif __name__==\"__main__\":\r\n cost_matrix = np.random.randint(low=0,high=100,size=(5,5,5))\r\n print(cost_matrix)\r\n gurobi_solve(cost_matrix)\r\n rollout_3D_assignment(cost_matrix)\r\n"
] |
[
[
"numpy.max",
"numpy.asarray",
"numpy.zeros",
"numpy.ones",
"numpy.min",
"numpy.where",
"numpy.random.randint",
"numpy.transpose",
"numpy.issubdtype",
"numpy.dtype"
]
] |
mimbres/SeqSkip
|
[
"031add5ba22cad1665d76b2cb21e8f6c1e1357e5",
"031add5ba22cad1665d76b2cb21e8f6c1e1357e5"
] |
[
"seqskip_train_S_seq1eH_eMSE.py",
"seqskip_train_seq1H_genlog128.py"
] |
[
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Dec 29 13:44:03 2018\nStudent Net\nS_seq1eH_e\n\n- non-autoregressive (not feeding predicted labels)\n- instance Norm.\n- G: GLU version\n- H: Highway-net version\n\n@author: mimbres\n\"\"\"\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom torch.optim.lr_scheduler import StepLR\nfrom torch.backends import cudnn\nimport numpy as np\nimport glob, os\nimport argparse\nfrom tqdm import trange, tqdm \nfrom spotify_data_loader import SpotifyDataloader\nfrom utils.eval import evaluate\nfrom blocks.highway_glu_dil_conv_v2 import HighwayDCBlock\nfrom copy import deepcopy\n#from blocks.multihead_attention import MultiHeadAttention\ncudnn.benchmark = True\n\n\nparser = argparse.ArgumentParser(description=\"Sequence Skip Prediction\")\nparser.add_argument(\"-c\",\"--config\",type=str, default=\"./config_init_dataset.json\")\nparser.add_argument(\"-s\",\"--save_path\",type=str, default=\"./save/exp_S_seq1eH_eMSE/\")\nparser.add_argument(\"-l\",\"--load_continue_latest\",type=str, default=None)\nparser.add_argument(\"-t\",\"--load_teacher_net_fpath\",type=str, default=\"./save/exp_T_seq1eH/check_8_48811.pth\")\nparser.add_argument(\"-glu\",\"--use_glu\", type=bool, default=False)\nparser.add_argument(\"-w\",\"--class_num\",type=int, default = 2)\nparser.add_argument(\"-e\",\"--epochs\",type=int, default= 10)\nparser.add_argument(\"-lr\",\"--learning_rate\", type=float, default = 0.001)\nparser.add_argument(\"-b\",\"--train_batch_size\", type=int, default = 2048)\nparser.add_argument(\"-tsb\",\"--test_batch_size\", type=int, default = 1024)\nparser.add_argument(\"-g\",\"--gpu\",type=int, default=0)\nargs = parser.parse_args()\n\n\n# Hyper Parameters\nFPATH_T_NET_CHECKPOINT = args.load_teacher_net_fpath\nUSE_GLU = args.use_glu\nINPUT_DIM = 72 \n\nCLASS_NUM = args.class_num\nEPOCHS = args.epochs\nLEARNING_RATE = args.learning_rate\nTR_BATCH_SZ = args.train_batch_size\nTS_BATCH_SZ = args.test_batch_size\nGPU = args.gpu\n\n# Model-save directory\nMODEL_SAVE_PATH = args.save_path\nos.makedirs(os.path.dirname(MODEL_SAVE_PATH), exist_ok=True)\n\n\nhist_trloss = list()\nhist_tracc = list()\nhist_vloss = list()\nhist_vacc = list()\nnp.set_printoptions(precision=3)\n \nclass SeqEncoder(nn.Module):\n def __init__(self, input_ch, e_ch,\n h_k_szs=[2,2,2,3,1,1], #h_k_szs=[2,2,5,1,1],\n h_dils=[1,2,4,8,1,1],\n causality=True,\n use_glu=False):\n super(SeqEncoder, self).__init__()\n h_io_chs = [e_ch]*len(h_k_szs)\n self.front_1x1 = nn.Conv1d(input_ch, e_ch,1)\n self.h_block = HighwayDCBlock(h_io_chs, h_k_szs, h_dils, causality=causality, use_glu=use_glu)\n self.mid_1x1 = nn.Sequential(nn.Conv1d(e_ch,e_ch,1), nn.ReLU(),\n nn.Conv1d(e_ch,e_ch,1), nn.ReLU())\n self.last_1x1 = nn.Sequential(nn.Conv1d(e_ch,e_ch,1))\n\n def forward(self, x): # Input:bx(input_dim)*20\n x = self.front_1x1(x) # bx128*20\n x = self.h_block(x) # bx128*20\n x = self.mid_1x1(x) # bx128*20\n return self.last_1x1(x) # bx128*20\n \n\nclass SeqModel(nn.Module):\n def __init__(self, input_dim=INPUT_DIM, e_ch=128, d_ch=128, use_glu=USE_GLU):\n super(SeqModel, self).__init__()\n self.e_ch = e_ch\n self.d_ch = d_ch\n self.enc = SeqEncoder(input_ch=input_dim, e_ch=e_ch,\n h_k_szs=[2,2,2,3,1,1], #h_k_szs=[2,2,2,3,1,1],\n h_dils=[1,2,4,8,1,1], #h_dils=[1,2,4,8,1,1],\n use_glu=use_glu) # bx128*10\n \n self.feature = nn.Sequential(nn.Conv1d(d_ch,d_ch,1), nn.ReLU(),\n nn.Conv1d(d_ch,d_ch,1), nn.ReLU())\n self.classifier = nn.Conv1d(d_ch,1,1)\n \n def forward(self, x):\n x = self.enc(x) # bx128*10 \n x = self.feature(x)\n x = self.classifier(x).squeeze(1) # bx256*10 --> b*10\n return x# bx20\n \nclass SeqModel_Student(nn.Module):\n def __init__(self, input_dim=INPUT_DIM, e_ch=128, d_ch=128, use_glu=USE_GLU):\n super(SeqModel_Student, self).__init__()\n self.e_ch = e_ch\n self.d_ch = d_ch\n self.enc = SeqEncoder(input_ch=input_dim, e_ch=e_ch,\n h_k_szs=[2,2,2,3,1,1], #h_k_szs=[2,2,2,3,1,1],\n h_dils=[1,2,4,8,1,1], #h_dils=[1,2,4,8,1,1],\n use_glu=use_glu) # bx128*10\n \n self.feature = nn.Sequential(nn.Conv1d(d_ch,d_ch,1), nn.ReLU(),\n nn.Conv1d(d_ch,d_ch,1), nn.ReLU())\n self.classifier = nn.Conv1d(d_ch,1,1)\n \n def forward(self, x):\n enc_out = self.enc(x) # bx128*10 \n x = self.feature(enc_out)\n x = self.classifier(x).squeeze(1) # bx256*10 --> b*10\n return enc_out, x# bx20\n\n#%%\n\n\ndef validate(mval_loader, SM, eval_mode, GPU):\n tqdm.write(\"Validation...\")\n submit = []\n gt = []\n total_vloss = 0\n total_vcorrects = 0\n total_vquery = 0\n val_sessions_iter = iter(mval_loader)\n \n for val_session in trange(len(val_sessions_iter), desc='val-sessions', position=2, ascii=True):\n SM.eval() \n x, labels, y_mask, num_items, index = val_sessions_iter.next() # FIXED 13.Dec. SEPARATE LOGS. QUERY SHOULT NOT INCLUDE LOGS\n # Sample data for 'support' and 'query': ex) 15 items = 7 sup, 8 queries... \n num_support = num_items[:,0].detach().numpy().flatten() # If num_items was odd number, query has one more item. \n num_query = num_items[:,1].detach().numpy().flatten()\n batch_sz = num_items.shape[0]\n \n # x: the first 10 items out of 20 are support items left-padded with zeros. The last 10 are queries right-padded.\n x = x.permute(0,2,1) # bx70*20\n x_feat = torch.zeros(batch_sz, 72, 20)\n x_feat[:,:70,:] = x.clone()\n x_feat[:, 70,:10] = 1 \n x_feat[:, 71,:10] = labels[:,:10].clone()\n x_feat = Variable(x_feat, requires_grad=False).cuda(GPU)\n \n # y\n y = labels.clone()\n \n # y_mask\n y_mask_que = y_mask.clone()\n y_mask_que[:,:10] = 0\n \n # Forward & update\n _, y_hat = SM(x_feat) # y_hat: b*20\n\n# if USE_PRED_LABEL is True:\n# # Predict\n# li = 70 if USE_SUPLOG is True else 29 # the label's dimension indice\n# _x = x[:,:,:11] # bx72*11\n# for q in range(11,20):\n# y_hat = SM(Variable(_x, requires_grad=False)) # will be bx11 at the first round \n# # Append next features\n# _x = torch.cat((_x, x[:,:,q].unsqueeze(2)), 2) # now bx72*12\n# _x[:,li,q] = torch.sigmoid(y_hat[:,-1])\n# y_hat = SM(Variable(_x, requires_grad=False)) # y_hat(final): bx20\n# del _x\n# else:\n# y_hat = SM(x)\n \n # Calcultate BCE loss: 뒤에q만 봄\n loss = F.binary_cross_entropy_with_logits(input=y_hat*y_mask_que.cuda(GPU), target=y.cuda(GPU)*y_mask_que.cuda(GPU))\n total_vloss += loss.item()\n \n # Decision\n y_prob = torch.sigmoid(y_hat*y_mask_que.cuda(GPU)).detach().cpu().numpy() # bx20 \n y_pred = (y_prob[:,10:]>0.5).astype(np.int) # bx10\n y_numpy = labels[:,10:].numpy() # bx10\n # Acc\n total_vcorrects += np.sum((y_pred==y_numpy)*y_mask_que[:,10:].numpy())\n total_vquery += np.sum(num_query)\n \n # Eval, Submission\n if eval_mode is not 0:\n for b in np.arange(batch_sz):\n submit.append(y_pred[b,:num_query[b]].flatten())\n gt.append(y_numpy[b,:num_query[b]].flatten())\n \n if (val_session+1)%400 == 0:\n sample_sup = labels[0,(10-num_support[0]):10].long().numpy().flatten() \n sample_que = y_numpy[0,:num_query[0]].astype(int)\n sample_pred = y_pred[0,:num_query[0]]\n sample_prob = y_prob[0,10:10+num_query[0]]\n tqdm.write(\"S:\" + np.array2string(sample_sup) +'\\n'+\n \"Q:\" + np.array2string(sample_que) + '\\n' +\n \"P:\" + np.array2string(sample_pred) + '\\n' +\n \"prob:\" + np.array2string(sample_prob))\n tqdm.write(\"val_session:{0:} vloss:{1:.6f} vacc:{2:.4f}\".format(val_session,loss.item(), total_vcorrects/total_vquery))\n del loss, y_hat, x # Restore GPU memory\n \n # Avg.Acc\n if eval_mode==1:\n aacc = evaluate(submit, gt)\n tqdm.write(\"AACC={0:.6f}, FirstAcc={1:.6f}\".format(aacc[0], aacc[1])) \n \n hist_vloss.append(total_vloss/val_session)\n hist_vacc.append(total_vcorrects/total_vquery)\n return submit\n \n\n# Main\ndef main(): \n # Trainset stats: 2072002577 items from 124950714 sessions\n print('Initializing dataloader...')\n mtrain_loader = SpotifyDataloader(config_fpath=args.config,\n mtrain_mode=True,\n data_sel=(0, 99965071), # 80% 트레인\n batch_size=TR_BATCH_SZ,\n shuffle=True,\n seq_mode=True) # seq_mode implemented \n \n mval_loader = SpotifyDataloader(config_fpath=args.config,\n mtrain_mode=True, # True, because we use part of trainset as testset\n data_sel=(99965071, 104965071),#(99965071, 124950714), # 20%를 테스트\n batch_size=TS_BATCH_SZ,\n shuffle=False,\n seq_mode=True) \n \n # Load Teacher net\n SMT = SeqModel().cuda(GPU) \n checkpoint = torch.load(FPATH_T_NET_CHECKPOINT, map_location='cuda:{}'.format(GPU))\n tqdm.write(\"Loading saved teacher model from '{0:}'... loss: {1:.6f}\".format(FPATH_T_NET_CHECKPOINT,checkpoint['loss']))\n SMT.load_state_dict(checkpoint['SM_state'])\n \n SMT_Enc = nn.Sequential(*list(SMT.children())[:1]).cuda(GPU)\n #SMT_EncFeat = nn.Sequential(*list(SMT.children())[:2])\n \n \n # Init Student net --> copy classifier from the Teacher net\n SM = SeqModel_Student().cuda(GPU)\n SM.feature = deepcopy(SMT.feature)\n for p in list(SM.feature.parameters()):\n p.requires_grad = False\n SM.classifier = deepcopy(SMT.classifier)\n SM.classifier.weight.requires_grad = False\n SM.classifier.bias.requires_grad = False\n SM = SM.cuda(GPU)\n \n SM_optim = torch.optim.Adam(filter(lambda p: p.requires_grad, SM.parameters()), lr=LEARNING_RATE)\n SM_scheduler = StepLR(SM_optim, step_size=1, gamma=0.9) \n \n \n \n \n # Load checkpoint\n if args.load_continue_latest is None:\n START_EPOCH = 0 \n else:\n latest_fpath = max(glob.iglob(MODEL_SAVE_PATH + \"check*.pth\"),key=os.path.getctime) \n checkpoint = torch.load(latest_fpath, map_location='cuda:{}'.format(GPU))\n tqdm.write(\"Loading saved model from '{0:}'... loss: {1:.6f}\".format(latest_fpath,checkpoint['loss']))\n SM.load_state_dict(checkpoint['SM_state'])\n SM_optim.load_state_dict(checkpoint['SM_opt_state'])\n SM_scheduler.load_state_dict(checkpoint['SM_sch_state'])\n START_EPOCH = checkpoint['ep']\n \n # Train \n for epoch in trange(START_EPOCH, EPOCHS, desc='epochs', position=0, ascii=True):\n tqdm.write('Train...')\n tr_sessions_iter = iter(mtrain_loader)\n total_corrects = 0\n total_query = 0\n total_trloss = 0\n for session in trange(len(tr_sessions_iter), desc='sessions', position=1, ascii=True):\n SMT.eval(); # Teacher-net\n SM.train(); # Student-net\n x, labels, y_mask, num_items, index = tr_sessions_iter.next() # FIXED 13.Dec. SEPARATE LOGS. QUERY SHOULT NOT INCLUDE LOGS \n \n # Sample data for 'support' and 'query': ex) 15 items = 7 sup, 8 queries... \n num_support = num_items[:,0].detach().numpy().flatten() # If num_items was odd number, query has one more item. \n num_query = num_items[:,1].detach().numpy().flatten()\n batch_sz = num_items.shape[0]\n \n # x: the first 10 items out of 20 are support items left-padded with zeros. The last 10 are queries right-padded.\n x = x.permute(0,2,1) # bx70*20\n \n # x_feat_T: Teacher-net input, x_feat_S: Student-net input(que-log is excluded)\n x_feat_T = torch.zeros(batch_sz, 72, 20)\n x_feat_T[:,:70,:] = x.clone()\n x_feat_T[:, 70,:10] = 1 # Sup/Que state indicator \n x_feat_T[:, 71,:10] = labels[:,:10].clone()\n \n x_feat_S = x_feat_T.clone()\n x_feat_S[:, :41, 10:] = 0 # remove que-log\n \n x_feat_T = x_feat_T.cuda(GPU)\n x_feat_S = Variable(x_feat_S).cuda(GPU)\n \n \n # Target: Prepare Teacher's intermediate output \n enc_target = SMT_Enc(x_feat_T)\n #target = SMT_EncFeat(x_feat_T)\n \n \n # y_mask\n y_mask_que = y_mask.clone()\n y_mask_que[:,:10] = 0\n \n # Forward & update\n y_hat_enc, y_hat = SM(x_feat_S) # y_hat: b*20\n \n # Calcultate Distillation loss\n loss = F.mse_loss(input=y_hat_enc, target=enc_target.cuda(GPU))\n #loss = F.binary_cross_entropy_with_logits(input=y_hat_enc, target=torch.sigmoid(enc_target.cuda(GPU)))\n #loss2 = F.l1_loss(input=y_hat_enc, target=enc_target.cuda(GPU))\n total_trloss += loss.item()\n SM.zero_grad()\n loss.backward()\n # Gradient Clipping\n #torch.nn.utils.clip_grad_norm_(SM.parameters(), 0.5)\n SM_optim.step()\n \n # Decision\n SM.eval();\n y_prob = torch.sigmoid(y_hat*y_mask_que.cuda(GPU)).detach().cpu().numpy() # bx20 \n y_pred = (y_prob[:,10:]>0.5).astype(np.int) # bx10\n y_numpy = labels[:,10:].numpy() # bx10\n # Acc\n total_corrects += np.sum((y_pred==y_numpy)*y_mask_que[:,10:].numpy())\n total_query += np.sum(num_query)\n \n # Restore GPU memory\n del loss, y_hat, y_hat_enc\n \n if (session+1)%500 == 0:\n hist_trloss.append(total_trloss/900)\n hist_tracc.append(total_corrects/total_query)\n # Prepare display\n sample_sup = labels[0,(10-num_support[0]):10].long().numpy().flatten() \n sample_que = y_numpy[0,:num_query[0]].astype(int)\n sample_pred = y_pred[0,:num_query[0]]\n sample_prob = y_prob[0,10:10+num_query[0]]\n\n tqdm.write(\"S:\" + np.array2string(sample_sup) +'\\n'+\n \"Q:\" + np.array2string(sample_que) + '\\n' +\n \"P:\" + np.array2string(sample_pred) + '\\n' +\n \"prob:\" + np.array2string(sample_prob))\n tqdm.write(\"tr_session:{0:} tr_loss:{1:.6f} tr_acc:{2:.4f}\".format(session, hist_trloss[-1], hist_tracc[-1]))\n total_corrects = 0\n total_query = 0\n total_trloss = 0\n \n \n if (session+1)%25000 == 0:\n # Validation\n validate(mval_loader, SM, eval_mode=True, GPU=GPU)\n # Save\n torch.save({'ep': epoch, 'sess':session, 'SM_state': SM.state_dict(),'loss': hist_trloss[-1], 'hist_vacc': hist_vacc,\n 'hist_vloss': hist_vloss, 'hist_trloss': hist_trloss, 'SM_opt_state': SM_optim.state_dict(),\n 'SM_sch_state': SM_scheduler.state_dict()}, MODEL_SAVE_PATH + \"check_{0:}_{1:}.pth\".format(epoch, session))\n # Validation\n validate(mval_loader, SM, eval_mode=True, GPU=GPU)\n # Save\n torch.save({'ep': epoch, 'sess':session, 'SM_state': SM.state_dict(),'loss': hist_trloss[-1], 'hist_vacc': hist_vacc,\n 'hist_vloss': hist_vloss, 'hist_trloss': hist_trloss, 'SM_opt_state': SM_optim.state_dict(),\n 'SM_sch_state': SM_scheduler.state_dict()}, MODEL_SAVE_PATH + \"check_{0:}_{1:}.pth\".format(epoch, session))\n SM_scheduler.step()\n \nif __name__ == '__main__':\n main() \n",
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Dec 11 00:45:08 2018\n\nseq1H_genlog: seqeunce learning model 2stack conv enc\n- q(x), l(x)\n- non-autoregressive (not feeding predicted labels)\n- instance Norm.\n- G: GLU version\n- H: Highway-net version\n\n기존 버그 완전 수정!\n\n@author: mimbres\n\"\"\"\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom torch.optim.lr_scheduler import StepLR\nfrom torch.backends import cudnn\nimport numpy as np\nimport glob, os\nimport argparse\nfrom tqdm import trange, tqdm \nfrom spotify_data_loader import SpotifyDataloader\nfrom utils.eval import evaluate\nfrom blocks.highway_dil_conv import HighwayDCBlock\ncudnn.benchmark = True\n\n\nparser = argparse.ArgumentParser(description=\"Sequence Skip Prediction\")\nparser.add_argument(\"-c\",\"--config\",type=str, default=\"./config_init_dataset.json\")\nparser.add_argument(\"-s\",\"--save_path\",type=str, default=\"./save/exp_seq1H_genlog128/\")\nparser.add_argument(\"-l\",\"--load_continue_latest\",type=str, default=None)\nparser.add_argument(\"-spl\",\"--use_suplog_as_feat\", type=bool, default=True)\nparser.add_argument(\"-pl\",\"--use_predicted_label\", type=bool, default=False)\nparser.add_argument(\"-glu\",\"--use_glu\", type=bool, default=False)\nparser.add_argument(\"-w\",\"--class_num\",type=int, default = 2)\nparser.add_argument(\"-e\",\"--epochs\",type=int, default= 15)\nparser.add_argument(\"-lr\",\"--learning_rate\", type=float, default = 0.001)\nparser.add_argument(\"-b\",\"--train_batch_size\", type=int, default = 2048)\nparser.add_argument(\"-tsb\",\"--test_batch_size\", type=int, default = 1024)\nparser.add_argument(\"-g\",\"--gpu\",type=int, default=0)\nargs = parser.parse_args()\n\n\n# Hyper Parameters\nUSE_SUPLOG = args.use_suplog_as_feat\nUSE_PRED_LABEL = args.use_predicted_label\nUSE_GLU = args.use_glu\nINPUT_DIM = 72 if USE_SUPLOG else 31\n\nCLASS_NUM = args.class_num\nEPOCHS = args.epochs\nLEARNING_RATE = args.learning_rate\nTR_BATCH_SZ = args.train_batch_size\nTS_BATCH_SZ = args.test_batch_size\nGPU = args.gpu\n\n# Model-save directory\nMODEL_SAVE_PATH = args.save_path\nos.makedirs(os.path.dirname(MODEL_SAVE_PATH), exist_ok=True)\n\n\nhist_trloss = list()\nhist_tracc = list()\nhist_vloss = list()\nhist_vacc = list()\n\nhist_trloss_qlog = list()\nhist_trloss_skip = list()\nhist_vloss_qlog = list()\nhist_vloss_skip = list()\nnp.set_printoptions(precision=3)\n\nclass SeqFeatEnc(nn.Module): \n def __init__(self, input_dim, e_ch, #d_ch=256,\n #h_io_chs=[256, 256, 256, 256, 256, 256, 256],\n d_ch,\n h_io_chs=[1,1,1,1,1,1,1],\n h_k_szs=[2,2,2,2,2,1,1],\n h_dils=[1,2,4,8,16,1,1],\n# h_dils=[1,2,4,1,2,4,1,2,4,1,1,1,1], #이것도 Receptive Field가 20인데 왜 안되는걸까??????\n use_glu=False):\n super(SeqFeatEnc, self).__init__()\n h_io_chs[:] = [n * d_ch for n in h_io_chs]\n # Layers:\n self.mlp = nn.Sequential(nn.Conv1d(input_dim,e_ch,1),\n nn.ReLU(),\n nn.Conv1d(e_ch,d_ch,1))\n self.h_block = HighwayDCBlock(h_io_chs, h_k_szs, h_dils, causality=True, use_glu=use_glu)\n return None\n \n def forward(self, x):\n # Input={{x_sup,x_que};{label_sup,label_que}} BxC*T (Bx(29+1)*20), audio feat dim=29, label dim=1, n_sup+n_que=20\n # Input bx30x20\n x = self.mlp(x) # bx128*20\n x = self.h_block(x) #bx256*20, 여기서 attention 쓰려면 split 128,128\n return x#x[:,:128,:]\n \nclass SeqClassifier(nn.Module):\n def __init__(self, input_ch, e_ch,\n h_io_chs=[1,1,1,1,1,1,1],\n h_k_szs=[2,2,2,2,2,1,1],\n h_dils=[1,2,4,8,16,1,1],\n use_glu=False):\n super(SeqClassifier, self).__init__()\n h_io_chs[:] = [n * e_ch for n in h_io_chs]\n self.front_1x1 = nn.Conv1d(input_ch, e_ch,1)\n self.h_block = HighwayDCBlock(h_io_chs, h_k_szs, h_dils, causality=True, use_glu=use_glu)\n self.last_1x1 = nn.Sequential(nn.Conv1d(e_ch,e_ch,1), nn.ReLU(),\n nn.Conv1d(e_ch,e_ch,1), nn.ReLU()) \n self.classifier = nn.Sequential(nn.Conv1d(e_ch,e_ch,1), nn.ReLU(),\n nn.Conv1d(e_ch,e_ch,1))#nn.Conv1d(e_ch,1,1))\n def forward(self, x): # Input:bx256*20\n x = self.front_1x1(x) # bx128*20\n x = self.h_block(x) # bx128*20\n x = self.last_1x1(x) # bx64*20\n return self.classifier(x).squeeze(1) # bx20\n\n \n\nclass SeqModel(nn.Module):\n def __init__(self, input_dim=INPUT_DIM, e_ch=128, d_ch=128, use_glu=USE_GLU):\n super(SeqModel, self).__init__()\n self.enc = SeqFeatEnc(input_dim=input_dim, e_ch=e_ch, d_ch=d_ch, use_glu=use_glu)\n self.clf = SeqClassifier(input_ch=d_ch, e_ch=e_ch, use_glu=use_glu)\n self.qlog_classifier = nn.Sequential(nn.Conv1d(e_ch,e_ch,1), nn.ReLU(),\n nn.Conv1d(e_ch,41,1))#nn.Conv1d(e_ch,1,1))\n self.skip_classifier = nn.Sequential(nn.Conv1d(e_ch,e_ch,1), nn.ReLU(),\n nn.Conv1d(e_ch,1,1))#nn.Conv1d(e_ch,1,1))\n \n def forward(self, x):\n x = self.enc(x) # bx128x20\n x = self.clf(x) # bx128x20\n #x_qlog, x_skip = x[:,:41,:], x[:,41,:] \n x_qlog = self.qlog_classifier(x) # bx41*20\n x_skip = self.skip_classifier(x).squeeze(1) # bx20\n return x_qlog, x_skip \n\n#%%\n\n\ndef validate(mval_loader, SM, eval_mode, GPU):\n tqdm.write(\"Validation...\")\n submit = []\n gt = []\n total_vloss = 0\n total_vloss_qlog = 0\n total_vloss_skip = 0\n total_vcorrects = 0\n total_vquery = 0\n val_sessions_iter = iter(mval_loader)\n for val_session in trange(len(val_sessions_iter), desc='val-sessions', position=2, ascii=True):\n SM.eval() \n x, labels, y_mask, num_items, index = val_sessions_iter.next() # FIXED 13.Dec. SEPARATE LOGS. QUERY SHOULT NOT INCLUDE LOGS\n \n # Sample data for 'support' and 'query': ex) 15 items = 7 sup, 8 queries... \n num_support = num_items[:,0].detach().numpy().flatten() # If num_items was odd number, query has one more item. \n num_query = num_items[:,1].detach().numpy().flatten()\n batch_sz = num_items.shape[0]\n\n # x: bx70*20\n x = x.permute(0,2,1)\n \n # Prepare ground truth log and label, y\n y_qlog = x[:,:41,:].clone() # bx41*20\n y_skip = labels.clone() #bx20\n y_mask_qlog = y_mask.unsqueeze(1).repeat(1,41,1) #bx41*20\n y_mask_skip = y_mask #bx20\n\n # log shift: bx41*20\n log_shift = torch.zeros(batch_sz,41,20)\n log_shift[:,:,1:] = x[:,:41,:-1]\n log_shift[:,:,11:] = 0 # DELETE LOG QUE\n \n # labels_shift: bx1*20(model can only observe past labels)\n labels_shift = torch.zeros(batch_sz,1,20)\n labels_shift[:,0,1:] = labels[:,:-1].float()\n labels_shift[:,0,11:] = 0 #!!! NOLABEL for previous QUERY\n \n # support/query state labels: bx1*20\n sq_state = torch.zeros(batch_sz,1,20)\n sq_state[:,0,:11] = 1\n \n # Pack x: bx72*20 (or bx32*20 if not using sup_logs)\n x = torch.cat((log_shift, x[:,41:,:], labels_shift, sq_state), 1).cuda(GPU) # x: bx72*20\n \n if USE_PRED_LABEL is True:\n # Predict\n li = 70 # the label's dimension indice\n _x = x[:,:,:11].clone() # bx72*11\n for q in range(11,20):\n y_hat_qlog, y_hat_skip = SM(Variable(_x, requires_grad=False)) # will be bx11 at the first round \n # Append next features\n _x = torch.cat((_x, x[:,:,q].unsqueeze(2)), 2) # now bx72*12\n _x[:,li,q] = torch.sigmoid(y_hat_skip[:,-1]) # replace with predicted label\n _x[:,:41,q] = torch.sigmoid(y_hat_qlog[:,-1])\n y_hat_qlog, y_hat_skip = SM(Variable(_x, requires_grad=False)) # y_hat(final): bx20\n del _x\n else:\n y_hat_qlog, y_hat_skip = SM(x) # y_hat_qlog: bx41*20, y_hat_skip: b*20\n \n # Calcultate BCE loss\n loss_qlog = F.binary_cross_entropy_with_logits(input=y_hat_qlog.cuda(GPU)*y_mask_qlog.cuda(GPU),\n target=y_qlog.cuda(GPU)*y_mask_qlog.cuda(GPU))\n loss_skip = F.binary_cross_entropy_with_logits(input=y_hat_skip.cuda(GPU)*y_mask_skip.cuda(GPU),\n target=y_skip.cuda(GPU)*y_mask_skip.cuda(GPU))\n loss = loss_qlog + loss_skip\n total_vloss_qlog += loss_qlog.item()\n total_vloss_skip += loss_skip.item()\n total_vloss += loss.item()\n \n # Decision\n y_prob = torch.sigmoid(y_hat_skip.detach()*y_mask_skip.cuda(GPU)).cpu().numpy() # bx20 \n y_pred = (y_prob[:,10:]>=0.5).astype(np.int) # bx10\n y_numpy = y_skip[:,10:].numpy() # bx10\n # Acc\n total_vcorrects += np.sum((y_pred==y_numpy)*y_mask_skip[:,10:].numpy())\n total_vquery += np.sum(num_query)\n \n # Restore GPU memory\n del loss, loss_qlog, loss_skip, y_hat_qlog, y_hat_skip\n \n # Eval, Submission\n if eval_mode is not 0:\n for b in np.arange(batch_sz):\n submit.append(y_pred[b,:num_query[b]].flatten())\n gt.append(y_numpy[b,:num_query[b]].flatten())\n \n if (val_session+1)%400 == 0:\n sample_sup = labels[0,(10-num_support[0]):10].long().numpy().flatten() \n sample_que = y_numpy[0,:num_query[0]].astype(int)\n sample_pred = y_pred[0,:num_query[0]]\n sample_prob = y_prob[0,10:10+num_query[0]]\n tqdm.write(\"S:\" + np.array2string(sample_sup) +'\\n'+\n \"Q:\" + np.array2string(sample_que) + '\\n' +\n \"P:\" + np.array2string(sample_pred) + '\\n' +\n \"prob:\" + np.array2string(sample_prob))\n tqdm.write(\"val_session:{0:} vloss(qlog|skip):{1:.6f}({2:.6f}|{3:.6f}) vacc:{4:.4f}\".format(val_session,\n total_vloss/total_vquery, total_vloss_qlog/total_vquery, \n total_vloss_skip/total_vquery, total_vcorrects/total_vquery))\n \n # Avg.Acc (skip labels only, log-generation acc is not implemented yet!)\n if eval_mode==1:\n aacc = evaluate(submit, gt)\n tqdm.write(\"AACC={0:.6f}, FirstAcc={1:.6f}\".format(aacc[0], aacc[1])) \n \n hist_vloss.append(total_vloss/total_vquery)\n hist_vloss_qlog.append(total_vloss_qlog/total_vquery)\n hist_vloss_skip.append(total_vloss_skip/total_vquery)\n hist_vacc.append(total_vcorrects/total_vquery)\n return submit\n \n\n# Main\ndef main(): \n # Trainset stats: 2072002577 items from 124950714 sessions\n print('Initializing dataloader...')\n mtrain_loader = SpotifyDataloader(config_fpath=args.config,\n mtrain_mode=True,\n data_sel=(0, 99965071), # 80% 트레인\n batch_size=TR_BATCH_SZ,\n shuffle=True,\n seq_mode=True) # seq_mode implemented \n \n mval_loader = SpotifyDataloader(config_fpath=args.config,\n mtrain_mode=True, # True, because we use part of trainset as testset\n data_sel=(99965071, 101065071),#104965071),#(99965071, 124950714), # 20%를 테스트\n batch_size=TS_BATCH_SZ,\n shuffle=False,\n seq_mode=True) \n \n # Init neural net\n SM = SeqModel().cuda(GPU)\n SM_optim = torch.optim.Adam(SM.parameters(), lr=LEARNING_RATE)\n SM_scheduler = StepLR(SM_optim, step_size=1, gamma=0.8) \n \n # Load checkpoint\n if args.load_continue_latest is None:\n START_EPOCH = 0 \n else:\n latest_fpath = max(glob.iglob(MODEL_SAVE_PATH + \"check*.pth\"),key=os.path.getctime) \n checkpoint = torch.load(latest_fpath, map_location='cuda:{}'.format(GPU))\n tqdm.write(\"Loading saved model from '{0:}'... loss: {1:.6f}\".format(latest_fpath,checkpoint['loss']))\n SM.load_state_dict(checkpoint['SM_state'])\n SM_optim.load_state_dict(checkpoint['SM_opt_state'])\n SM_scheduler.load_state_dict(checkpoint['SM_sch_state'])\n START_EPOCH = checkpoint['ep']\n \n # Train \n for epoch in trange(START_EPOCH, EPOCHS, desc='epochs', position=0, ascii=True):\n tqdm.write('Train...')\n tr_sessions_iter = iter(mtrain_loader)\n total_corrects = 0\n total_query = 0\n total_trloss_qlog = 0\n total_trloss_skip = 0\n total_trloss = 0\n for session in trange(len(tr_sessions_iter), desc='sessions', position=1, ascii=True):\n SM.train();\n x, labels, y_mask, num_items, index = tr_sessions_iter.next() # FIXED 13.Dec. SEPARATE LOGS. QUERY SHOULT NOT INCLUDE LOGS\n \n # Sample data for 'support' and 'query': ex) 15 items = 7 sup, 8 queries... \n num_support = num_items[:,0].detach().numpy().flatten() # If num_items was odd number, query has one more item. \n num_query = num_items[:,1].detach().numpy().flatten()\n batch_sz = num_items.shape[0]\n \n # x: bx70*20\n x = x.permute(0,2,1)\n \n # Prepare ground truth log and label, y\n y_qlog = x[:,:41,:].clone() # bx41*20\n y_skip = labels.clone() #bx20\n y_mask_qlog = y_mask.unsqueeze(1).repeat(1,41,1) #bx41*20\n y_mask_skip = y_mask #bx20\n \n # log shift: bx41*20\n log_shift = torch.zeros(batch_sz,41,20)\n log_shift[:,:,1:] = x[:,:41,:-1]\n log_shift[:,:,11:] = 0 # DELETE LOG QUE\n \n # labels_shift: bx1*20(model can only observe past labels)\n labels_shift = torch.zeros(batch_sz,1,20)\n labels_shift[:,0,1:] = labels[:,:-1].float()\n labels_shift[:,0,11:] = 0 #!!! NOLABEL for previous QUERY\n \n # support/query state labels: bx1*20\n sq_state = torch.zeros(batch_sz,1,20)\n sq_state[:,0,:11] = 1\n \n # Pack x: bx72*20 (or bx32*20 if not using sup_logs)\n x = Variable(torch.cat((log_shift, x[:,41:,:], labels_shift, sq_state), 1)).cuda(GPU) # x: bx72*20\n \n # Forward & update\n y_hat_qlog, y_hat_skip = SM(x) # y_hat: b*20\n \n # Calcultate BCE loss\n loss_qlog = F.binary_cross_entropy_with_logits(input=y_hat_qlog.cuda(GPU)*y_mask_qlog.cuda(GPU),\n target=y_qlog.cuda(GPU)*y_mask_qlog.cuda(GPU))\n loss_skip = F.binary_cross_entropy_with_logits(input=y_hat_skip.cuda(GPU)*y_mask_skip.cuda(GPU),\n target=y_skip.cuda(GPU)*y_mask_skip.cuda(GPU))\n loss = loss_qlog + loss_skip\n total_trloss_qlog += loss_qlog.item()\n total_trloss_skip += loss_skip.item()\n total_trloss += loss.item()\n SM.zero_grad()\n loss.backward()\n # Gradient Clipping\n #torch.nn.utils.clip_grad_norm_(SM.parameters(), 0.5)\n SM_optim.step()\n \n # Decision\n y_prob = torch.sigmoid(y_hat_skip.detach()*y_mask_skip.cuda(GPU)).cpu().numpy() # bx20 \n y_pred = (y_prob[:,10:]>=0.5).astype(np.int) # bx10\n y_numpy = y_skip[:,10:].numpy() # bx10\n \n # Label Acc*\n total_corrects += np.sum((y_pred==y_numpy)*y_mask_skip[:,10:].numpy())\n total_query += np.sum(num_query)\n# # Log generation Acc*\n# y_qlog_mask = y_mask[:,:41,10:]\n \n # Restore GPU memory\n del loss, loss_qlog, loss_skip, y_hat_qlog, y_hat_skip \n \n if (session+1)%500 == 0:\n hist_trloss_qlog.append(total_trloss_qlog/500) #!\n hist_trloss_skip.append(total_trloss_skip/500) #!\n hist_trloss.append(total_trloss/500)\n hist_tracc.append(total_corrects/total_query)\n # Prepare display\n sample_sup = labels[0,(10-num_support[0]):10].long().numpy().flatten() \n sample_que = y_numpy[0,:num_query[0]].astype(int)\n sample_pred = y_pred[0,:num_query[0]]\n sample_prob = y_prob[0,10:10+num_query[0]]\n tqdm.write(\"S:\" + np.array2string(sample_sup) +'\\n'+\n \"Q:\" + np.array2string(sample_que) + '\\n' +\n \"P:\" + np.array2string(sample_pred) + '\\n' +\n \"prob:\" + np.array2string(sample_prob))\n tqdm.write(\"tr_session:{0:} tr_loss(qlog|skip):{1:.6f}({2:.6f}|{3:.6f}) tr_acc:{4:.4f}\".format(session,\n hist_trloss[-1], hist_trloss_qlog[-1], hist_trloss_skip[-1], hist_tracc[-1]))\n total_corrects = 0\n total_query = 0\n total_trloss = 0\n total_trloss_qlog = 0\n total_trloss_skip = 0\n \n if (session+1)%8000 == 0:\n # Validation\n validate(mval_loader, SM, eval_mode=True, GPU=GPU)\n # Save\n torch.save({'ep': epoch, 'sess':session, 'SM_state': SM.state_dict(),'loss': hist_trloss[-1], \n 'hist_trloss_qlog': hist_trloss_qlog, 'hist_trloss_skip': hist_trloss_skip, 'hist_vacc': hist_vacc,\n 'hist_vloss': hist_vloss, 'hist_trloss': hist_trloss, 'SM_opt_state': SM_optim.state_dict(),\n 'SM_sch_state': SM_scheduler.state_dict()}, MODEL_SAVE_PATH + \"check_{0:}_{1:}.pth\".format(epoch, session))\n # Validation\n validate(mval_loader, SM, eval_mode=True, GPU=GPU)\n # Save\n torch.save({'ep': epoch, 'sess':session, 'SM_state': SM.state_dict(),'loss': hist_trloss[-1],\n 'hist_trloss_qlog': hist_trloss_qlog, 'hist_trloss_skip': hist_trloss_skip, 'hist_vacc': hist_vacc,\n 'hist_vloss': hist_vloss, 'hist_trloss': hist_trloss, 'SM_opt_state': SM_optim.state_dict(),\n 'SM_sch_state': SM_scheduler.state_dict()}, MODEL_SAVE_PATH + \"check_{0:}_{1:}.pth\".format(epoch, session))\n SM_scheduler.step()\n \nif __name__ == '__main__':\n main() \n"
] |
[
[
"torch.zeros",
"torch.optim.lr_scheduler.StepLR",
"torch.nn.Conv1d",
"torch.autograd.Variable",
"numpy.set_printoptions",
"numpy.sum",
"torch.nn.ReLU",
"numpy.arange",
"numpy.array2string"
],
[
"torch.zeros",
"torch.sigmoid",
"torch.cat",
"torch.optim.lr_scheduler.StepLR",
"torch.nn.Conv1d",
"torch.autograd.Variable",
"numpy.set_printoptions",
"numpy.sum",
"torch.nn.ReLU",
"numpy.arange",
"numpy.array2string"
]
] |
ericchen321/DMGNN
|
[
"759adf63d97d8b69fb30ccaaed0332e66699a1fa"
] |
[
"v-dmgnn-gan_cmu/processor/recognition.py"
] |
[
"import os\nimport sys\nimport argparse\nimport yaml\nimport time\nimport numpy as np\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\n\nimport torchlight\nfrom torchlight import str2bool\nfrom torchlight import DictAction\nfrom torchlight import import_class\n\nfrom .processor import Processor\nfrom .data_tools import *\n\nfrom copy import deepcopy\nfrom torch.distributions.uniform import Uniform\n\n\n\ndef weights_init(m):\n classname = m.__class__.__name__\n if classname.find('Conv1d') != -1:\n m.weight.data.normal_(0.0, 0.02)\n if m.bias is not None:\n m.bias.data.fill_(0)\n elif classname.find('Conv2d') != -1:\n m.weight.data.normal_(0.0, 0.02)\n if m.bias is not None:\n m.bias.data.fill_(0)\n elif classname.find('BatchNorm') != -1:\n m.weight.data.normal_(1.0, 0.02)\n m.bias.data.fill_(0)\n\n\nclass REC_Processor(Processor):\n\n def load_model(self):\n self.model = self.io.load_model(self.arg.model, **(self.arg.model_args))\n self.model.apply(weights_init)\n V, W, U = 26, 10, 5\n off_diag_joint, off_diag_part, off_diag_body = np.ones([V, V])-np.eye(V, V), np.ones([W, W])-np.eye(W, W), np.ones([U, U])-np.eye(U, U)\n self.relrec_joint = torch.FloatTensor(np.array(encode_onehot(np.where(off_diag_joint)[1]), dtype=np.float32)).to(self.dev)\n self.relsend_joint = torch.FloatTensor(np.array(encode_onehot(np.where(off_diag_joint)[0]), dtype=np.float32)).to(self.dev)\n self.relrec_part = torch.FloatTensor(np.array(encode_onehot(np.where(off_diag_part)[1]), dtype=np.float32)).to(self.dev)\n self.relsend_part = torch.FloatTensor(np.array(encode_onehot(np.where(off_diag_part)[0]), dtype=np.float32)).to(self.dev)\n self.relrec_body = torch.FloatTensor(np.array(encode_onehot(np.where(off_diag_body)[1]), dtype=np.float32)).to(self.dev)\n self.relsend_body = torch.FloatTensor(np.array(encode_onehot(np.where(off_diag_body)[0]), dtype=np.float32)).to(self.dev)\n self.lower_body_joints = [1,2,3]# [1,2,3,4,5]# [1,2,3]#[0, 1, 2, 3, 4, 5, 6, 7]\n\n\n self.dismodel_args = deepcopy(self.arg.model_args)\n d_mode =3\n if d_mode == 2:\n self.dismodel_args.pop('n_in_dec', None)\n self.dismodel_args.pop('n_hid_dec', None)\n self.dismodel_args.pop('n_hid_enc', None)\n self.dismodel_args['edge_weighting'] =True\n self.dismodel_args['fusion_layer'] = 0\n\n\n self.discriminator = self.io.load_model('net.model.Discriminatorv2', **(self.dismodel_args))\n else:\n self.dismodel_args.pop('n_in_enc', None)\n self.dismodel_args.pop('n_hid_enc', None)\n self.dismodel_args.pop('fusion_layer', None)\n self.dismodel_args.pop('cross_w', None)\n self.dismodel_args.pop('graph_args_p', None)\n self.dismodel_args.pop('graph_args_b', None)\n self.discriminator = self.io.load_model('net.model.Discriminatorv3', **(self.dismodel_args))\n \n # self.dismodel_args['edge_weighting'] =True\n # self.dismodel_args['fusion_layer'] = 0\n\n \n self.discriminator.apply(weights_init)\n self.discriminator.cuda()\n self.criterion = nn.BCEWithLogitsLoss()# nn.BCELoss()\n self.visual_sigmoid = nn.Sigmoid()\n \n def load_optimizer(self):\n if self.arg.optimizer == 'SGD':\n self.optimizer = optim.SGD(params=self.model.parameters(),\n lr=self.arg.base_lr,\n momentum=0.9,\n nesterov=self.arg.nesterov,\n weight_decay=self.arg.weight_decay)\n elif self.arg.optimizer == 'Adam':\n self.optimizer = optim.Adam(params=self.model.parameters(),\n lr=self.arg.base_lr,\n weight_decay=self.arg.weight_decay)\n\n self.netD_optimizer =optim.Adam(params=self.discriminator.parameters(),\n lr=0.000004,\n weight_decay=self.arg.weight_decay)\n\n\n def adjust_lr(self):\n if self.arg.optimizer == 'SGD' and self.arg.step:\n lr = self.arg.base_lr * (0.5**np.sum(self.meta_info['iter']>= np.array(self.arg.step)))\n for param_group in self.optimizer.param_groups:\n param_group['lr'] = lr\n self.lr = lr\n elif self.arg.optimizer == 'Adam' and self.arg.step:\n lr = self.arg.base_lr * (0.98**np.sum(self.meta_info['iter']>= np.array(self.arg.step)))\n for param_group in self.optimizer.param_groups:\n param_group['lr'] = lr\n self.lr = lr\n\n for param_group in self.netD_optimizer.param_groups:\n param_group['lr'] = self.lr\n\n else:\n raise ValueError('No such Optimizer')\n\n def loss_l1(self, pred, target, mask=None):\n dist = torch.abs(pred-target).mean(-1).mean(1).mean(0)\n if mask is not None:\n dist = dist * mask\n loss = torch.mean(dist)\n return loss\n\n def vae_loss_function(self, pred, target, mean_val, log_var):\n assert pred.shape == target.shape\n reconstruction_loss = self.loss_l1(pred, target)\n mean_val = mean_val.mean(-1).mean(1).mean(0)\n log_var = log_var.mean(-1).mean(1).mean(0)\n KLD = - 0.5 * torch.sum(1+ log_var - mean_val.pow(2) - log_var.exp())\n return reconstruction_loss + 0.1*KLD\n\n '''\n def build_masking_matrix_add_noise(self, unmasked_matrix, joint_indices):\n r\"\"\"\n Build masking matrix with same shape as `unmasked_matrix`\n \"\"\"\n M = np.zeros_like(unmasked_matrix)\n M = M.reshape(M.shape[0], M.shape[1], -1, 3) # batch size, T, J, 3\n for i in range(M.shape[0]):\n for j in range(M.shape[1]):\n for k in range(M.shape[2]):\n if k in joint_indices:\n M[i, j, k, :] = np.random.normal(0,0.5,1) \n #M[:, :, joint_indices, :] = np.random.normal(0,0.5,3)\n M = M.reshape(unmasked_matrix.shape)\n return M\n '''\n\n def build_masking_matrix(self, unmasked_matrix, joint_indices):\n r\"\"\"\n Build masking matrix with same shape as `unmasked_matrix`\n \"\"\"\n M = np.ones_like(unmasked_matrix)\n M = M.reshape(M.shape[0], M.shape[1], -1, 3) # batch size, T, J, 3\n M[:, :, joint_indices, :] = np.zeros((3,))\n M = M.reshape(unmasked_matrix.shape)\n return M\n\n def build_noise_matrix(self, pose_matrix, masking_matrix):\n r\"\"\"\n Build noise matrix with same shape as `pose_matrix`. We replace\n each masked joint angle by an IID Gaussian noise signal following\n distribution N(0, 0.5)\n :param pose_matrix: matrix of poses\n :param masking_matrix: binary masking matrix for `pose_matrix`\n\n Return:\n Noise matrix with same shape as `pose_matrix`\n \"\"\"\n M = np.random.normal(loc=0, scale=0.5, size=pose_matrix.shape)\n inverted_mask_matrix = (~masking_matrix.astype(np.bool)).astype(np.float32)\n M = np.multiply(M, inverted_mask_matrix)\n return M\n \n def build_lower_body_masking_matrices(self, lower_body_joints, encoder_inputs, decoder_inputs):\n # build encoder input mask\n M_enc_in = self.build_masking_matrix(encoder_inputs, lower_body_joints)\n # build decoder input mask\n M_dec_in = self.build_masking_matrix(decoder_inputs, lower_body_joints)\n # build decoder output / target mask\n #M_dec_out = self.build_masking_matrix(targets, lower_body_joints)\n return M_enc_in, M_dec_in\n\n def build_random_masking_matrices(self, encoder_inputs, decoder_inputs, seed=None, p=0.8):\n # set seed\n if seed is not None:\n np.random.seed(seed)\n # build encoder input mask\n M_enc_in = np.random.binomial(n=1, p=p, size=encoder_inputs.shape).astype(np.float32)\n # build decoder input mask\n M_dec_in = np.random.binomial(n=1, p=p, size=decoder_inputs.shape).astype(np.float32)\n return M_enc_in, M_dec_in\n \n def train(self, masking_type=\"lower-body\"):\n\n if self.meta_info['iter'] % 2 == 0:\n with torch.no_grad():\n mean, var, gan_decoder_inputs, \\\n gan_targets, gan_decoder_inputs_previous, \\\n gan_decoder_inputs_previous2, \\\n gan_disc_encoder_inputs = self.train_generator(\n mode='discriminator', masking_type=masking_type)\n\n self.train_decoderv3(\n mean,\n var,\n gan_decoder_inputs,\n gan_targets,\n gan_decoder_inputs_previous,\n gan_decoder_inputs_previous2,\n gan_disc_encoder_inputs)\n \n else:\n self.train_generator(mode='generator', masking_type=masking_type)\n \n def train_decoder(self, mean, var, gan_decoder_inputs, gan_targets, gan_decoder_inputs_previous, gan_decoder_inputs_previous2):\n with torch.no_grad():\n dec_mean = mean.clone()\n dec_var = var.clone()\n dec_var = torch.exp(0.5 * dec_var) # TBD\n epsilon = torch.randn_like(dec_var)\n z = dec_mean + dec_var * epsilon\n dis_pred = self.model.generate_from_decoder(z, gan_decoder_inputs, gan_decoder_inputs_previous, \\\n gan_decoder_inputs_previous2,self.arg.target_seq_len) #[32, 26, 10, 3]\n\n dis_pred = dis_pred.detach()\n dis_pred = dis_pred.requires_grad_()\n\n dis_pred = dis_pred.permute(0, 2, 1, 3).contiguous().view(32, 10, -1)\n dis_o = self.discriminator(dis_pred, self.relrec_joint,\n self.relsend_joint,\n self.relrec_part,\n self.relsend_part,\n self.relrec_body,\n self.relsend_body,\n self.arg.lamda)# .view(-1)\n\n # dis_o = dis_o.detach()\n # dis_o =dis_o.requires_grad_()\n\n\n\n self.netD_optimizer.zero_grad()\n N = dis_o.size()[0]\n # label = torch.full((N,), 0.0, dtype=torch.float, device='cuda:0')\n # label = Uniform(0.0, 0.1).sample((N,1)).cuda()\n fake_labels = torch.FloatTensor(1).fill_(0.0)\n fake_labels = fake_labels.requires_grad_(False)\n fake_labels = fake_labels.expand_as(dis_o).cuda()\n # print(fake_labels.size())\n # print(dis_o.size())\n errD_fake= self.criterion(dis_o, fake_labels)\n # Calculate gradients for D in backward pass\n # errD_fake.backward()\n D_x_fake = dis_o.mean().item() # to display\n\n # for the real\n targets = gan_targets#.permute(0, 2, 1, 3).contiguous().view(32, 10, -1)\n\n\n\n dis_oreal = self.discriminator(targets, self.relrec_joint,\n self.relsend_joint,\n self.relrec_part,\n self.relsend_part,\n self.relrec_body,\n self.relsend_body,\n self.arg.lamda)# .view(-1)\n # real_labels = torch.full((N,), 1.0, dtype=torch.float, device='cuda:0')\n # real_labels = Uniform(0.9, 1.0).sample((N,1)).cuda()\n real_labels = torch.FloatTensor(1).fill_(1.0)\n real_labels = real_labels.requires_grad_(False)\n real_labels = real_labels.expand_as(dis_oreal).cuda()\n # print(real_labels.requires_grad)\n errD_real= self.criterion(dis_oreal, real_labels)\n # errD_real.backward()\n errD = 0.5*(errD_real + errD_fake)\n errD.backward()\n self.netD_optimizer.step()\n D_x_real = dis_oreal.mean().item()\n\n\n\n self.iter_info['discriminator loss'] = errD\n self.iter_info['discriminator real out'] = D_x_real\n self.iter_info['discriminator fake out'] = D_x_fake\n self.iter_info['discriminator real loss'] = errD_real\n self.iter_info['discriminator fake loss'] = errD_fake\n\n self.show_iter_info()\n self.meta_info['iter'] += 1\n # writer.add_scalar(\"Loss/train\", loss, epoch)\n\n def train_decoderv3(self, mean, var, gan_decoder_inputs, gan_targets, gan_decoder_inputs_previous, gan_decoder_inputs_previous2, gan_disc_encoder_inputs):\n with torch.no_grad():\n dec_mean = mean.clone()\n dec_var = var.clone()\n dec_var = torch.exp(0.5 * dec_var) # TBD\n epsilon = torch.randn_like(dec_var)\n z = dec_mean + dec_var * epsilon\n dis_pred = self.model.generate_from_decoder(z, gan_decoder_inputs, gan_decoder_inputs_previous, \\\n gan_decoder_inputs_previous2, self.arg.target_seq_len) #[32, 26, 10, 3]\n\n dis_pred = dis_pred.detach()\n dis_pred = dis_pred.requires_grad_()\n\n dis_pred = dis_pred.permute(0, 2, 1, 3).contiguous().view(32, 10, -1)\n disc_in = torch.cat([gan_disc_encoder_inputs.clone(), dis_pred], dim=1)\n\n dis_o = self.discriminator(disc_in)# .view(-1)\n\n # dis_o = dis_o.detach()\n # dis_o =dis_o.requires_grad_()\n\n\n\n self.netD_optimizer.zero_grad()\n N = dis_o.size()[0]\n # label = torch.full((N,), 0.0, dtype=torch.float, device='cuda:0')\n # label = Uniform(0.0, 0.1).sample((N,1)).cuda()\n fake_labels = torch.FloatTensor(1).fill_(0.0)\n fake_labels = fake_labels.requires_grad_(False)\n fake_labels = fake_labels.expand_as(dis_o).cuda()\n # print(fake_labels.size())\n # print(dis_o.size())\n errD_fake= self.criterion(dis_o, fake_labels)\n # Calculate gradients for D in backward pass\n # errD_fake.backward()\n D_x_fake = dis_o.mean().item() # to display\n\n # for the real\n targets = gan_targets#.permute(0, 2, 1, 3).contiguous().view(32, 10, -1)\n disc_targets_in = torch.cat([gan_disc_encoder_inputs.clone(), targets], dim=1)\n\n\n\n dis_oreal = self.discriminator(disc_targets_in)# .view(-1)\n # real_labels = torch.full((N,), 1.0, dtype=torch.float, device='cuda:0')\n # real_labels = Uniform(0.9, 1.0).sample((N,1)).cuda()\n real_labels = torch.FloatTensor(1).fill_(1.0)\n real_labels = real_labels.requires_grad_(False)\n real_labels = real_labels.expand_as(dis_oreal).cuda()\n # print(real_labels.requires_grad)\n errD_real= self.criterion(dis_oreal, real_labels)\n # errD_real.backward()\n errD = 0.5*(errD_real + errD_fake)\n errD.backward()\n self.netD_optimizer.step()\n for p in self.discriminator.parameters():\n p.data.clamp_(-0.25, 0.25)\n # nn.utils.clip_grad_norm_(self.discriminator.parameters(), 0.1)\n D_x_real = dis_oreal.mean().item()\n\n\n\n self.iter_info['discriminator_loss'] = errD\n self.iter_info['discriminator real out'] = D_x_real\n self.iter_info['discriminator fake out'] = D_x_fake\n self.iter_info['discriminator real loss'] = errD_real\n self.iter_info['discriminator fake loss'] = errD_fake\n\n self.show_iter_info()\n self.meta_info['iter'] += 1\n\n def train_generator(self, mode='generator', masking_type=\"lower-body\"):\n self.model.train()\n self.adjust_lr()\n loss_value = []\n normed_train_dict = normalize_data(self.train_dict, self.data_mean, self.data_std, self.dim_use)\n\n encoder_inputs, decoder_inputs, targets = train_sample(normed_train_dict, \n self.arg.batch_size, \n self.arg.source_seq_len, \n self.arg.target_seq_len, \n len(self.dim_use))\n\n # unmasked\n gan_disc_encoder_inputs = torch.Tensor(encoder_inputs).float().to(self.dev) #encoder_inputs #.clone().detach().requires_grad_(True)\n gan_disc_en_in = torch.Tensor(encoder_inputs).float().to(self.dev) # encoder_inputs_p.clone().detach().requires_grad_(True)\n\n\n #build masking matrices\n if masking_type == \"lower-body\":\n self.M_enc_in, self.M_dec_in = self.build_lower_body_masking_matrices(\n self.lower_body_joints,\n encoder_inputs,\n decoder_inputs\n )\n elif masking_type == \"random\":\n self.M_enc_in, self.M_dec_in = self.build_random_masking_matrices(\n encoder_inputs,\n decoder_inputs,\n p=0.8\n )\n else:\n raise NotImplementedError\n \n # mask encoder inputs and decoder inputs\n encoder_inputs = np.multiply(self.M_enc_in, encoder_inputs)\n decoder_inputs = np.multiply(self.M_dec_in, decoder_inputs)\n\n # add noise to masked encoder/decoder inputs\n encoder_noise = self.build_noise_matrix(encoder_inputs, self.M_enc_in)\n decoder_noise = self.build_noise_matrix(decoder_inputs, self.M_dec_in)\n encoder_inputs = np.add(encoder_inputs, encoder_noise)\n decoder_inputs = np.add(decoder_inputs, decoder_noise)\n\n encoder_inputs_v = np.zeros_like(encoder_inputs)\n encoder_inputs_v[:, 1:, :] = encoder_inputs[:, 1:, :]-encoder_inputs[:, :-1, :]\n encoder_inputs_a = np.zeros_like(encoder_inputs)\n encoder_inputs_a[:, :-1, :] = encoder_inputs_v[:, 1:, :]-encoder_inputs_v[:, :-1, :]\n\n encoder_inputs_p = torch.Tensor(encoder_inputs).float().to(self.dev)\n encoder_inputs_v = torch.Tensor(encoder_inputs_v).float().to(self.dev)\n encoder_inputs_a = torch.Tensor(encoder_inputs_a).float().to(self.dev)\n\n decoder_inputs = torch.Tensor(decoder_inputs).float().to(self.dev)\n decoder_inputs_previous = torch.Tensor(encoder_inputs[:, -1, :]).unsqueeze(1).to(self.dev)\n decoder_inputs_previous2 = torch.Tensor(encoder_inputs[:, -2, :]).unsqueeze(1).to(self.dev)\n targets = torch.Tensor(targets).float().to(self.dev)\n\n gan_targets = targets.clone().detach().requires_grad_(True)\n N, T, D = targets.size() # N = 64(batchsize), T=10, D=63\n targets = targets.contiguous().view(N, T, -1, 3).permute(0, 2, 1, 3) # [64, 21, 10, 3]\n\n gan_decoder_inputs = decoder_inputs.clone().detach().requires_grad_(True)\n gan_decoder_inputs_previous = decoder_inputs_previous.clone().detach().requires_grad_(True)\n gan_decoder_inputs_previous2 = decoder_inputs_previous2.clone().detach().requires_grad_(True)\n # v3\n # gan_disc_encoder_inputs = encoder_inputs_p.clone().detach().requires_grad_(True)\n # gan_disc_en_in = encoder_inputs_p.clone().detach().requires_grad_(True)\n\n\n outputs, mean, log_var = self.model(encoder_inputs_p,\n encoder_inputs_v,\n encoder_inputs_a,\n decoder_inputs,\n decoder_inputs_previous,\n decoder_inputs_previous2,\n self.arg.target_seq_len,\n self.relrec_joint,\n self.relsend_joint,\n self.relrec_part,\n self.relsend_part,\n self.relrec_body,\n self.relsend_body,\n self.arg.lamda)\n\n # convert spatio-temporal masking matrix to a tensor\n #st_mask = torch.from_numpy(self.M_dec_out).to(self.dev)\n #loss = self.vae_loss_function(outputs, targets, mean, log_var, st_mask = st_mask)\n\n if mode =='generator':\n loss = self.vae_loss_function(outputs, targets, mean, log_var)\n\n outputs = outputs.permute(0, 2, 1, 3).contiguous().view(32, 10, -1)\n \n if True:\n disc_in = torch.cat([gan_disc_en_in, outputs], dim=1)\n gen_disco = self.discriminator(disc_in)\n\n # adversrial loss\n real_labels = torch.FloatTensor(1).fill_(1.0)\n real_labels = real_labels.requires_grad_(False)\n real_labels = real_labels.expand_as(gen_disco).cuda()\n # print(real_labels.requires_grad)\n gan_loss = self.criterion(gen_disco, real_labels)\n loss = 0.93* loss + 0.07*gan_loss\n \n\n\n self.optimizer.zero_grad()\n loss.backward()\n # # Clip weights of discriminator\n # for p in self.discriminator.parameters():\n # p.data.clamp_(-0.25, 0.25)\n nn.utils.clip_grad_norm_(self.model.parameters(), 0.5)\n self.optimizer.step()\n\n self.iter_info['generator_loss'] = loss.data.item()\n if False:\n self.iter_info['gan_loss'] = gan_loss.data.item()\n self.show_iter_info()\n self.meta_info['iter'] += 1\n\n self.epoch_info['mean_loss'] = np.mean(loss_value)\n\n return mean, log_var, gan_decoder_inputs, gan_targets, gan_decoder_inputs_previous, gan_decoder_inputs_previous2, gan_disc_encoder_inputs\n\n def test(\n self,\n evaluation=True,\n iter_time=0,\n save_motion=False,\n phase=False,\n masking_type=\"lower-body\",\n fix_rand_masking_seed=False):\n\n self.model.eval()\n loss_value = []\n normed_test_dict = normalize_data(self.test_dict, self.data_mean, self.data_std, self.dim_use)\n self.actions = [\"basketball\", \"basketball_signal\", \"directing_traffic\", \n \"jumping\", \"running\", \"soccer\", \"walking\", \"washwindow\"]\n\n self.io.print_log(' ')\n print_str = \"{0: <16} |\".format(\"milliseconds\")\n for ms in [40, 80, 120, 160, 200, 240, 280, 320, 360, 400, 560, 1000]:\n print_str = print_str + \" {0:5d} |\".format(ms)\n self.io.print_log(print_str)\n\n for action_num, action in enumerate(self.actions):\n encoder_inputs, decoder_inputs, targets = srnn_sample(normed_test_dict, action,\n self.arg.source_seq_len, \n self.arg.target_seq_len, \n len(self.dim_use))\n\n #build masking matrices\n if masking_type == \"lower-body\":\n self.M_enc_in, self.M_dec_in = self.build_lower_body_masking_matrices(\n self.lower_body_joints,\n encoder_inputs,\n decoder_inputs\n )\n elif masking_type == \"random\":\n rand_masking_seed = None\n if fix_rand_masking_seed:\n rand_masking_seed = 0\n self.M_enc_in, self.M_dec_in = self.build_random_masking_matrices(\n encoder_inputs,\n decoder_inputs,\n seed=rand_masking_seed,\n p=0.8\n )\n else:\n raise NotImplementedError\n \n # mask encoder inputs and decoder inputs\n encoder_inputs = np.multiply(self.M_enc_in, encoder_inputs)\n decoder_inputs = np.multiply(self.M_dec_in, decoder_inputs)\n\n # add noise to masked encoder/decoder inputs\n encoder_noise = self.build_noise_matrix(encoder_inputs, self.M_enc_in)\n decoder_noise = self.build_noise_matrix(decoder_inputs, self.M_dec_in)\n encoder_inputs = np.add(encoder_inputs, encoder_noise)\n decoder_inputs = np.add(decoder_inputs, decoder_noise)\n\n encoder_inputs_v = np.zeros_like(encoder_inputs)\n encoder_inputs_v[:, 1:, :] = encoder_inputs[:, 1:, :]-encoder_inputs[:, :-1, :]\n encoder_inputs_a = np.zeros_like(encoder_inputs)\n encoder_inputs_a[:, :-1, :] = encoder_inputs_v[:, 1:, :]-encoder_inputs_v[:, :-1, :]\n\n encoder_inputs_p = torch.Tensor(encoder_inputs).float().to(self.dev)\n encoder_inputs_v = torch.Tensor(encoder_inputs_v).float().to(self.dev)\n encoder_inputs_a = torch.Tensor(encoder_inputs_a).float().to(self.dev)\n\n # for saving motion\n N, T, D = encoder_inputs_p.shape\n encoder_inputs_p_4d = encoder_inputs_p.view(N, T, -1, 3).permute(0, 2, 1, 3) # Eric: [N, V, T, 3] same with targets for saving motion\n \n decoder_inputs = torch.Tensor(decoder_inputs).float().to(self.dev)\n decoder_inputs_previous = torch.Tensor(encoder_inputs[:, -1, :]).unsqueeze(1).to(self.dev)\n decoder_inputs_previous2 = torch.Tensor(encoder_inputs[:, -2, :]).unsqueeze(1).to(self.dev) \n targets = torch.Tensor(targets).float().to(self.dev)\n\n N, T, D = targets.size() \n targets = targets.contiguous().view(N, T, -1, 3).permute(0, 2, 1, 3) # [64, 21, 25, 3] same with outputs for validation loss\n\n start_time = time.time()\n with torch.no_grad():\n outputs, mean, var = self.model(encoder_inputs_p,\n encoder_inputs_v,\n encoder_inputs_a,\n decoder_inputs,\n decoder_inputs_previous,\n decoder_inputs_previous2,\n self.arg.target_seq_len,\n self.relrec_joint,\n self.relsend_joint,\n self.relrec_part,\n self.relsend_part,\n self.relrec_body,\n self.relsend_body,\n self.arg.lamda)\n\n '''\n p = self.model.cal_posterior(encoder_inputs_p,\n encoder_inputs_v,\n encoder_inputs_a,\n decoder_inputs,\n decoder_inputs_previous,\n decoder_inputs_previous2,\n self.arg.target_seq_len,\n self.relrec_joint,\n self.relsend_joint,\n self.relrec_part,\n self.relsend_part,\n self.relrec_body,\n self.relsend_body,\n self.arg.lamda)\n print(\"posterior {}\".format(p))\n '''\n if evaluation:\n num_samples_per_action = encoder_inputs_p_4d.shape[0]\n mean_errors = np.zeros(\n (num_samples_per_action, self.arg.target_seq_len), dtype=np.float32)\n # Eric: create data structs to save unnormalized inputs, outputs and targets\n inputs_denorm = np.zeros(\n [num_samples_per_action,\n encoder_inputs_p_4d.shape[2],\n int(self.data_mean.shape[0]/3),\n 3]) # num_samples_per_action, t_in, 39, 3\n outputs_denorm = np.zeros(\n [num_samples_per_action,\n outputs.shape[2],\n int(self.data_mean.shape[0]/3),\n 3]) # [num_samples_per_action, t_out, 39, 3]\n targets_denorm = np.zeros(\n [num_samples_per_action,\n targets.shape[2],\n int(self.data_mean.shape[0]/3),\n 3]) # [num_samples_per_action, t_out, V, 3]\n \n for i in np.arange(num_samples_per_action):\n input = encoder_inputs_p_4d[i] # V, t_in, d\n V, t, d = input.shape\n input = input.permute(1,0,2).contiguous().view(t, V*d)\n input_denorm = unnormalize_data(\n input.cpu().numpy(), self.data_mean, self.data_std, self.dim_ignore, self.dim_use, self.dim_zero)\n inputs_denorm[i] = input_denorm.reshape((t, -1, 3))\n \n output = outputs[i] # output: [V, t, d] = [21, 25, 3]\n V, t, d = output.shape\n output = output.permute(1,0,2).contiguous().view(t, V*d)\n output_denorm = unnormalize_data(\n output.cpu().numpy(), self.data_mean, self.data_std, self.dim_ignore, self.dim_use, self.dim_zero)\n outputs_denorm[i] = output_denorm.reshape((t, -1, 3))\n t, D = output_denorm.shape\n output_euler = np.zeros((t,D) , dtype=np.float32) # [21, 99]\n for j in np.arange(t):\n for k in np.arange(0,115,3):\n output_euler[j,k:k+3] = rotmat2euler(expmap2rotmat(output_denorm[j,k:k+3]))\n\n target = targets[i]\n target = target.permute(1,0,2).contiguous().view(t, V*d)\n target_denorm = unnormalize_data(\n target.cpu().numpy(), self.data_mean, self.data_std, self.dim_ignore, self.dim_use, self.dim_zero)\n targets_denorm[i] = target_denorm.reshape((t, -1, 3))\n target_euler = np.zeros((t,D) , dtype=np.float32)\n for j in np.arange(t):\n for k in np.arange(0,115,3):\n target_euler[j,k:k+3] = rotmat2euler(expmap2rotmat(target_denorm[j,k:k+3]))\n\n target_euler[:,0:6] = 0\n idx_to_use1 = np.where(np.std(target_euler,0)>1e-4)[0]\n idx_to_use2 = self.dim_nonzero\n idx_to_use = idx_to_use1[np.in1d(idx_to_use1,idx_to_use2)]\n \n euc_error = np.power(target_euler[:,idx_to_use]-output_euler[:,idx_to_use], 2)\n euc_error = np.sqrt(np.sum(euc_error, 1)) # [25]\n mean_errors[i,:euc_error.shape[0]] = euc_error\n mean_mean_errors = np.mean(np.array(mean_errors), 0)\n\n if save_motion==True:\n save_dir = os.path.join(self.save_dir,'motions_exp'+str(iter_time*self.arg.savemotion_interval))\n if not os.path.exists(save_dir):\n os.makedirs(save_dir)\n # save unnormalized inputs\n np.save(save_dir+f\"/motions_{action}_inputs.npy\", inputs_denorm)\n # save unnormalized outputs\n np.save(save_dir+f\"/motions_{action}_outputs.npy\", outputs_denorm)\n # save unnormalized targets\n np.save(save_dir+f\"/motions_{action}_targets.npy\", targets_denorm)\n\n print_str = \"{0: <16} |\".format(action)\n for ms_idx, ms in enumerate([0,1,2,3,4,5,6,7,8,9,13,24]):\n if self.arg.target_seq_len >= ms+1:\n print_str = print_str + \" {0:.3f} |\".format(mean_mean_errors[ms])\n if phase is not True:\n self.MAE_tensor[iter_time, action_num, ms_idx] = mean_mean_errors[ms]\n else:\n print_str = print_str + \" n/a |\"\n if phase is not True:\n self.MAE_tensor[iter_time, action_num, ms_idx] = 0\n print_str = print_str + 'T: {0:.3f} ms |'.format((time.time()-start_time)*1000/8)\n self.io.print_log(print_str)\n self.io.print_log(' ')\n\n\n @staticmethod\n def get_parser(add_help=False):\n\n parent_parser = Processor.get_parser(add_help=False)\n parser = argparse.ArgumentParser(add_help=add_help, parents=[parent_parser], description='Spatial Temporal Graph Convolution Network')\n\n parser.add_argument('--base_lr', type=float, default=0.01, help='initial learning rate')\n parser.add_argument('--step', type=int, default=[], nargs='+', help='the epoch where optimizer reduce the learning rate')\n parser.add_argument('--optimizer', default='SGD', help='type of optimizer')\n parser.add_argument('--nesterov', type=str2bool, default=True, help='use nesterov or not')\n parser.add_argument('--weight_decay', type=float, default=0.0001, help='weight decay for optimizer')\n\n parser.add_argument('--lamda', type=float, default=1.0, help='adjust part feature')\n parser.add_argument('--fusion_layer_dir', type=str, default='fusion_1', help='lamda a dir')\n parser.add_argument('--learning_rate_dir', type=str, default='adam_1e-4', help='lamda a dir')\n parser.add_argument('--lamda_dir', type=str, default='nothing', help='adjust part feature')\n parser.add_argument('--crossw_dir', type=str, default='nothing', help='adjust part feature')\n parser.add_argument('--note', type=str, default='nothing', help='whether seperate')\n\n parser.add_argument('--debug', type=bool, default=False, help='whether seperate')\n\n return parser"
] |
[
[
"torch.cat",
"numpy.ones_like",
"numpy.mean",
"numpy.multiply",
"numpy.where",
"torch.nn.BCEWithLogitsLoss",
"torch.exp",
"numpy.random.normal",
"numpy.zeros_like",
"numpy.random.binomial",
"torch.FloatTensor",
"numpy.save",
"numpy.eye",
"torch.abs",
"torch.randn_like",
"numpy.arange",
"numpy.in1d",
"torch.Tensor",
"matplotlib.use",
"numpy.array",
"numpy.zeros",
"numpy.std",
"numpy.power",
"numpy.add",
"torch.nn.Sigmoid",
"numpy.random.seed",
"numpy.sum",
"torch.no_grad",
"numpy.ones",
"torch.mean"
]
] |
luigiberducci/dirl
|
[
"5f7997aea20dfb7347ebdee66de9bea4e6cd3c62"
] |
[
"spectrl/util/io.py"
] |
[
"import argparse\nimport os\nimport pathlib\n\nimport cv2\nimport pickle\nimport numpy as np\n\nfrom matplotlib import pyplot as plt\nfrom PIL import Image\nfrom numpy import genfromtxt\n\n\ndef parse_command_line_options(print_options=False):\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-n\", type=int, default=-1)\n parser.add_argument(\"-d\", type=pathlib.Path)\n parser.add_argument(\"-s\", type=int, choices=[0], default=0)\n parser.add_argument(\"-e\", type=int, default=0)\n parser.add_argument(\"-a\", type=str, default=\"ars\")\n parser.add_argument(\"-i\", type=int, default=100)\n parser.add_argument(\"-g\", action=\"store_true\")\n parser.add_argument(\"-r\", action=\"store_true\")\n args = parser.parse_args()\n\n flags = {\n \"itno\": args.n,\n \"folder\": str(args.d),\n \"spec_num\": args.s,\n \"env_num\": args.e,\n \"alg\": args.a,\n \"num_iter\": args.i,\n \"gpu_flag\": args.g,\n \"render\": args.r\n }\n\n if print_options:\n print('**** Command Line Options ****')\n for key in flags:\n print('{}: {}'.format(key, flags[key]))\n return flags\n\n\ndef open_log_file(itno, folder):\n '''\n Open a log file to periodically flush data.\n\n Parameters:\n itno: int\n folder: str\n '''\n fname = _get_prefix(folder) + 'log' + _get_suffix(itno) + '.txt'\n open(fname, 'w').close()\n file = open(fname, 'a')\n return file\n\n\ndef save_object(name, object, itno, folder):\n '''\n Save any pickle-able object.\n\n Parameters:\n name: str\n object: Object\n itno: int\n folder: str\n '''\n file = open(_get_prefix(folder) + name + _get_suffix(itno) + '.pkl', 'wb')\n pickle.dump(object, file)\n file.close()\n\n\ndef load_object(name, itno, folder):\n '''\n Load pickled object.\n\n Parameters:\n name: str\n itno: int\n folder: str\n '''\n file = open(_get_prefix(folder) + name + _get_suffix(itno) + '.pkl', 'rb')\n object = pickle.load(file)\n file.close()\n return object\n\n\ndef save_log_info(log_info, itno, folder):\n np.save(_get_prefix(folder) + 'log' + _get_suffix(itno) + '.npy', log_info)\n\n\ndef load_log_info(itno, folder, csv=False):\n if csv:\n return genfromtxt(_get_prefix(folder) + 'log' + _get_suffix(itno) + '.csv', delimiter=',')\n else:\n return np.load(_get_prefix(folder) + 'log' + _get_suffix(itno) + '.npy')\n\n\ndef log_to_file(file, iter, num_transitions, reward, prob, additional_data={}):\n '''\n Log data to file.\n\n Parameters:\n file: file_handle\n iter: int\n num_transitions: int (number of simulation steps in each iter)\n reward: float\n prob: float (satisfaction probability)\n additional_data: dict\n '''\n file.write('**** Iteration Number {} ****\\n'.format(iter))\n file.write('Environment Steps Taken: {}\\n'.format(num_transitions))\n file.write('Reward: {}\\n'.format(reward))\n file.write('Satisfaction Probability: {}\\n'.format(prob))\n for key in additional_data:\n file.write('{}: {}\\n'.format(key, additional_data[key]))\n file.write('\\n')\n file.flush()\n\n\ndef get_image_dir(itno, folder):\n image_dir = '{}img{}'.format(_get_prefix(folder), _get_suffix(itno))\n if os.path.exists(image_dir) is False:\n os.mkdir(image_dir)\n return image_dir\n\n\ndef generate_video(env, policy, itno, folder, max_step=10000):\n image_dir = get_image_dir(itno, folder)\n\n done = False\n state = env.reset()\n step = 0\n while not done:\n img_arr = env.render(mode='rgb_array')\n img = Image.fromarray(img_arr)\n img.save(image_dir + '/' + str(step) + '.png')\n action = policy.get_action(state)\n state, _, done, _ = env.step(action)\n step += 1\n if step > max_step:\n done = True\n\n video_name = image_dir + '/' + 'video.avi'\n images_temp = [img for img in os.listdir(image_dir)]\n images = []\n for i in range(len(images_temp)):\n for j in images_temp:\n directory = str(i) + '.png'\n if directory == j:\n images.append(j)\n\n frame = cv2.imread(os.path.join(image_dir, images_temp[0]))\n height, width, _ = frame.shape\n video = cv2.VideoWriter(\n video_name, cv2.VideoWriter_fourcc(*'XVID'), 20, (width, height))\n\n for image in images:\n video.write(cv2.imread(os.path.join(image_dir, image)))\n\n cv2.destroyAllWindows()\n video.release()\n\n\ndef plot_for_threshold(itno, folders, xs, threshold, color):\n ys = []\n for folder in folders:\n val = 0\n count = 0\n for j in range(itno):\n data = load_log_info(j, folder)\n for pos in range(len(data)):\n if data[pos][-1] >= threshold:\n val += data[pos][0]\n count += 1\n break\n ys.append(val / count)\n plt.subplots_adjust(bottom=0.145, left=0.13)\n plt.rcParams.update({'font.size': 18})\n plt.plot(xs, ys, '-ok', label='z = {}'.format(threshold), color=color)\n\n\ndef plot_error_bar(x, data, color, label, points=False):\n '''\n Plot the error bar from the data.\n\n Parameters:\n samples_per_iter: int (number of sample rollouts per iteration of the algorithm)\n data: (3+)-tuple of np.array (curve, lower error bar, upper error bar, ...)\n color: color of the plot\n label: string\n '''\n plt.subplots_adjust(bottom=0.126)\n plt.rcParams.update({'font.size': 18})\n if points:\n plt.errorbar(x, data[0], data[0] - data[1], fmt='--o', color=color, label=label)\n else:\n plt.plot(x, data[0], color=color, label=label)\n plt.fill_between(x, data[1], data[2], color=color, alpha=0.15)\n\n\ndef extract_plot_data(folder, column_num, low, up, csv=False):\n '''\n Load and parse log_info to generate error bars\n\n Parameters:\n folder: string (name of folder)\n column_num: int (column number in log.npy to use)\n l: int (lower limit on run number)\n u: int (upper limit on run number)\n\n Returns:\n 4-tuple of numpy arrays (curve, lower error bar, upper error bar, max_over_runs)\n '''\n log_infos = []\n min_length = 1000000\n for itno in range(low, up):\n log_info = np.transpose(load_log_info(\n itno, folder, csv=csv))[column_num]\n log_info = np.append([0], log_info)\n min_length = min(min_length, len(log_info))\n log_infos.append(log_info)\n log_infos = [log_info[:min_length] for log_info in log_infos]\n data = np.array(log_infos)\n curve = np.mean(data, axis=0)\n std = np.std(data, axis=0)\n max_curve = np.amax(data, axis=0)\n return curve, (curve - std), (curve + std), max_curve\n\n\n# save and render current plot\ndef save_plot(folder, name, show=True, scientific=True):\n plt.rcParams.update({'font.size': 14})\n plt.legend()\n ax = plt.gca()\n ax.xaxis.major.formatter._useMathText = True\n if scientific:\n plt.ticklabel_format(style='sci', axis='x', scilimits=(0, 0))\n plt.savefig(_get_prefix(folder) + name + '.pdf', format='pdf')\n if show:\n plt.show()\n\n\n# get prefix for file name\ndef _get_prefix(folder):\n if folder == '':\n return ''\n else:\n return folder + '/'\n\n\n# get suffix from itno\ndef _get_suffix(itno):\n if itno < 0:\n return ''\n else:\n return str(itno)\n"
] |
[
[
"matplotlib.pyplot.rcParams.update",
"numpy.array",
"matplotlib.pyplot.errorbar",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.legend",
"numpy.mean",
"numpy.std",
"numpy.amax",
"matplotlib.pyplot.fill_between",
"numpy.append",
"matplotlib.pyplot.show",
"matplotlib.pyplot.gca",
"matplotlib.pyplot.subplots_adjust",
"matplotlib.pyplot.ticklabel_format"
]
] |
DataBiosphere/data-browser
|
[
"de981a83a51ad936e184e81727c708b04f94d901"
] |
[
"analytics/hdgar-book/analytics_charts.py"
] |
[
"import analytics_api as ga\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom google.cloud import bigquery\nimport json\nimport requests\nfrom functools import cache\n# from IPython.core.display import HTML\nimport re\n\n\ndef authenticate_ga():\n\tga.authenticate();\n\n# def display_link(url, text):\n# \tdisplay(HTML('<a href=\"{}\" target=\"_blank\">{}</a>'.format(url, text)))\n\n@cache\ndef get_project_name(id):\n\tinfo = requests.get(\"https://service.azul.data.humancellatlas.org/index/projects/\" + id).json()\n\tif \"projects\" in info:\n\t\treturn info[\"projects\"][0][\"projectTitle\"]\n\telse:\n\t\treturn id\n\n# def display_project_link(id):\n# \tdisplay_link(\"https://data.humancellatlas.org/explore/projects/\" + id, get_project_name(id))\n\ndef percent_change(valfrom, valto):\n\treturn (valto - valfrom)/valfrom * 100\n\ndef format_export_url_info(type, secondary_type, filter):\n\tresult = type.replace(\"-\", \" \")\n\tif secondary_type:\n\t\tresult += \", \" + secondary_type.replace(\"-\", \" \")\n\tfor facet in json.loads(filter):\n\t\tif facet[\"facetName\"] == \"projectId\":\n\t\t\tresult += \"\\r\\nProject: \" + \", \".join([get_project_name(id) for id in facet[\"terms\"]])\n\t\telse:\n\t\t\tresult += \"\\r\\n\" + facet[\"facetName\"] + \": \" + \", \".join(facet[\"terms\"])\n\treturn result\n\ndef adjust_table_index_key(val):\n\tif isinstance(val, str):\n\t\tmatch = re.search(\"\\\\/explore\\\\/(?:projects\\\\/([^\\\\/#?]+)|export\\\\/(export-to-terra|get-curl-command|download-manifest)(?:\\\\/(select-species))?\\\\?filter=(.+))\", val)\n\t\tif match:\n\t\t\tif match.group(1):\n\t\t\t\treturn get_project_name(match.group(1)) + \"\\r\\n\" + val\n\t\t\telse:\n\t\t\t\treturn format_export_url_info(match.group(2), match.group(3), match.group(4))\n\treturn val\n\ndef format_pc_change_table(df, include_plus=False, cell_classes=None, hide_index=False, hide_columns=False):\n\t# Expects pairs of columns in a 2D multi-index where the second column is named \"% Change\"\n\t\n\tchange_cols = [name for name in df.columns if name[1] == '% Change']\n\t\n\tchange_format = '({:+.2f}%)' if include_plus else '({:.2f}%)'\n\t\n\ts = df.style\n\tif hide_index:\n\t\ts = s.hide(axis=\"index\")\n\telse:\n\t\ts = s.format_index(adjust_table_index_key)\n\tif hide_columns:\n\t\ts = s.hide(axis=\"columns\")\n\ts = s.format(na_rep='', formatter=lambda v: '' if v == np.inf else change_format.format(v), subset=change_cols)\n\ts = s.applymap(lambda v: 'color: red' if v < 0 else 'color: green' if v > 0 else None, subset=change_cols)\n\tif not cell_classes is None:\n\t\ts = s.set_td_classes(cell_classes)\n\ts = s.set_table_styles([\n\t\t{'selector': '', 'props': 'width: 100%; table-layout: auto; display: table'},\n\t\t{'selector': 'th.col_heading', 'props': 'text-align: center'},\n\t\t{'selector': 'thead > tr:nth-child(2)', 'props': 'display: none'},\n\t\t{'selector': 'th.index_name', 'props': 'text-align: left'},\n\t\t{'selector': 'th.row_heading', 'props': 'text-align: left; white-space: pre-wrap; line-break: anywhere; font-weight: normal'},\n\t\t{'selector': ', '.join([\"td.col%i\" % (i * 2 + 1) for i in range(len(change_cols))]), 'props': 'text-align: left; padding-left: 0'},\n\t\t{'selector': '.up::before', 'props': 'content: \"↑\\\\00a0\"; color: gray'},\n\t\t{'selector': '.down::before', 'props': 'content: \"↓\\\\00a0\"; color: gray'},\n\t\t{'selector': '.new::before', 'props': 'content: \"+\\\\00a0\"; color: gray'}\n\t], overwrite=False)\n\n\treturn s\n\ndef format_change_over_time_table(df):\n\tdf2 = df.copy(deep=True)\n\t\n\tdata_cols = [c for c in df2.columns]\n\t\n\tdf2['Quarter'] = df2.index.quarter\n\tdf2['Year'] = df2.index.year\n\n\tdf2 = df2.groupby(['Year','Quarter']).sum()\n\t\n\tdf2.columns = pd.MultiIndex.from_tuples([(name, 'Value') for name in data_cols])\n\t\n\tfor name in data_cols:\n\t\tdf2[(name, '% Change')] = df2[name].pct_change().mul(100)\n\t\n\tdf2 = df2[[(a, b) for a in data_cols for b in ['Value', '% Change']]]\n\t\n\treturn format_pc_change_table(df2, include_plus=True)\n\ndef format_table_with_change(df, df_prev, hide_index=False, show_direction=True, hide_columns=False):\n\t# The data frames must have the same column names but may have some different rows\n\t\n\tdf_joined = df.join(df_prev, rsuffix=\"_prev\")\n\tdf_change = pd.concat([v for name in df.columns for v in (df_joined[name], percent_change(df_joined[name + \"_prev\"], df_joined[name]))], axis=1)\n\tdf_change.columns = pd.MultiIndex.from_tuples([(df_change.columns[i - i%2], \"Value\" if i%2 == 0 else \"% Change\") for (i, name) in enumerate(df_change.columns)])\n\t\n\tindices = pd.DataFrame(index=df.index)\n\tindices[\"index\"] = range(indices.shape[0])\n\tindices_prev = pd.DataFrame(index=df_prev.index)\n\tindices_prev[\"index\"] = range(indices_prev.shape[0])\n\tindices_combined = indices.join(indices_prev, rsuffix=\"_prev\")\n\t\n\tindices_diff = indices_combined[\"index\"] - indices_combined[\"index_prev\"]\n\tclasses_series = indices_diff.map(lambda v: \"new\" if pd.isna(v) else None if not show_direction or v == 0 else \"up\" if v < 0 else \"down\") # lower index = higher in chart\n\t\n\tclasses = pd.DataFrame(index=df_change.index, columns=df_change.columns)\n\tclasses[:] = None\n\tclasses.iloc[:, [0]] = classes_series\n\t\n\treturn format_pc_change_table(df_change, include_plus=True, cell_classes=classes, hide_index=hide_index, hide_columns=hide_columns)\n\ndef plot_users_over_time(ga_property, start_date, end_date):\n\n\tmetrics = 'ga:1dayUsers, ga:uniquePageviews'\n\tdimensions = 'ga:date'\n\tdf = ga.get_metrics_by_dimensions(ga_property, metrics,dimensions, start_date, end_date)\n\n\t# Convert date to datetime object\n\tdf[\"ga:date\"] = pd.to_datetime(df['ga:date'])\n\tdf.set_index('ga:date', inplace=True)\n\n\t# Convert strings returned by API to integers. Can we do this earlier!\n\t# If not numeric data the series won't graph\n\tdf[\"ga:1dayUsers\"] = df['ga:1dayUsers'].astype(str).astype(int)\n\tdf[\"ga:uniquePageviews\"] = df['ga:uniquePageviews'].astype(str).astype(int)\n\n\n\t# Rename for display\n\tdf.rename(columns={'ga:1dayUsers':'Total Daily Users', 'ga:uniquePageviews':'Total Unique Pageviews'}, inplace=True)\n\n\t#Smooth (coiuld we not just use 7 day users then?)\n\t# df = df.rolling(window=1).mean()\n\n\t# Notes: Linking Mandas and Matplotlib\n\t# https://stackoverflow.com/questions/29568110/how-to-use-ax-with-pandas-and-matplotlib\n\n\tfontsize=16\n\tfig, ax = plt.subplots(figsize=(16, 9))\n\tdf.plot(ax=ax) #Link the df with the axis\n\n\tax.set_xlabel('Time', fontsize=fontsize)\n\tax.set_ylabel('Count', fontsize=fontsize)\n\n\tfor label in (ax.get_xticklabels() + ax.get_yticklabels()):\n\t\tlabel.set_fontsize(fontsize)\n\n\tplt.rcParams['font.size'] = fontsize\n\tfig.suptitle('Daily Activity Overview')\n\tplt.show()\n\n\t# Average per qurter\n\n\tdfmean = df.rolling(window=30).mean()\n\tfig, ax = plt.subplots(figsize=(16, 9))\n\tdfmean.plot(ax=ax) #Link the df with the axis\n\n\tax.set_xlabel('Time', fontsize=fontsize)\n\tax.set_ylabel('Count', fontsize=fontsize)\n\n\tfor label in (ax.get_xticklabels() + ax.get_yticklabels()):\n\t\tlabel.set_fontsize(fontsize)\n\n\tplt.rcParams['font.size'] = fontsize\n\tfig.suptitle('Daily Activity Overview 30 Day average')\n\tplt.show()\n\n\n\treturn format_change_over_time_table(df)\n\ndef get_top_ga_df(ga_property, metrics, dimensions, start_date, end_date, ascending=True, limit=20, filters=None, num_keep_dimensions=1):\n\tdf = ga.get_metrics_by_dimensions(ga_property, \",\".join(metrics), dimensions and \",\".join(dimensions), start_date, end_date, filters=filters)\n\t\n\tif dimensions:\n\t\tif len(dimensions) > 1:\n\t\t\tdf.drop(columns=dimensions[num_keep_dimensions:], inplace=True);\n\t\tdf.set_index(dimensions[:num_keep_dimensions], inplace=True)\n\tfor metric in metrics:\n\t\tdf[metric] = df[metric].astype(str).astype(int)\n\tif ascending != None:\n\t\tdf = df.sort_values(by=metrics, ascending=ascending)\n\t\n\tif not limit is None:\n\t\tdf = df.tail(limit) if ascending else df.head(limit)\n\t\n\treturn df\n\ndef plot_hbar(ga_property, title, xlabel, ylabel, metric, dimension, start_date, end_date):\n\n\tdf = get_top_ga_df(ga_property, [metric], dimension and [dimension], start_date, end_date)\n\n\tfontsize=16\n\t# position = list(range(1, 20))\n\n\tfig, ax = plt.subplots(figsize=(16, 9))\n\tplt.barh(df.index, df[metric]) #Link the df with the axis\n\n\tfig.suptitle(title)\n\tax.set_ylabel(ylabel)\n\tax.set_xlabel(xlabel)\n\n\n\tfor index, value in enumerate(df[metric]):\n\t\tplt.text(value, index,\n\t\t\t' ('+ str(value)+')')\n\n\tplt.rcParams['font.size'] = fontsize\n\tplt.show()\n\ndef show_difference_table(ga_property, xlabels, ylabels, metrics, dimensions, period, prev_period, filters=None, ordered=True):\n\tif isinstance(xlabels, str):\n\t\txlabels = [xlabels]\n\tif isinstance(metrics, str):\n\t\tmetrics = [metrics]\n\tif isinstance(dimensions, str):\n\t\tdimensions = [dimensions]\n\t\n\tperiod = pd.Period(period)\n\tprev_period = pd.Period(prev_period)\n\t\n\tshared_params = {\n\t\t\"ga_property\": ga_property,\n\t\t\"metrics\": metrics,\n\t\t\"dimensions\": dimensions,\n\t\t\"filters\": filters,\n\t\t\"ascending\": False if ordered else None,\n\t\t\"num_keep_dimensions\": len(ylabels) if isinstance(ylabels, list) else 1\n\t}\n\tdf = get_top_ga_df(start_date=period.start_time.isoformat()[:10], end_date=period.end_time.isoformat()[:10], **shared_params)\n\tdf_prev = get_top_ga_df(start_date=prev_period.start_time.isoformat()[:10], end_date=prev_period.end_time.isoformat()[:10], **shared_params)\n\t\n\tis_single_cell = df.shape[0] == 1 and df.shape[1] == 1 and df_prev.shape[0] == 1 and df_prev.shape[1] == 1\n\t\n\tif is_single_cell and not dimensions:\n\t\tdf.index = pd.Index(xlabels)\n\t\tdf_prev.index = pd.Index(xlabels)\n\telse:\n\t\txlabels_dict = {metric: xlabel for metric, xlabel in zip(metrics, xlabels)}\n\t\tdf.rename(columns=xlabels_dict, inplace=True)\n\t\tdf_prev.rename(columns=xlabels_dict, inplace=True)\n\t\tif dimensions:\n\t\t\tdf.index.rename(ylabels, inplace=True)\n\t\t\tdf_prev.index.rename(ylabels, inplace=True)\n\t\n\tdisplay(format_table_with_change(df, df_prev, show_direction=ordered, hide_index=not dimensions and not is_single_cell, hide_columns=is_single_cell))\n\n\ndef plot_downloads():\n\tQUERY = \"\"\"\n\t\tSELECT\n\t\t\tday,\n\t\t\tCOUNT(*) AS totalSessionCount,\n\t\t\tCOUNTIF(\"fastq\" IN UNNEST(fileTypes)) AS fastqSessionCount,\n\t\t\tCOUNTIF(\"bam\" IN UNNEST(fileTypes)) AS bamSessionCount,\n\t\t\tCOUNTIF(\"matrix\" IN UNNEST(fileTypes)) AS matrixSessionCount,\n\t\t\tCOUNTIF(\"other\" IN UNNEST(fileTypes)) AS otherSessionCount,\n\t\t\tCOUNTIF(\".loom\" IN UNNEST(matrixTypes)) AS loomMatrixSessionCount,\n\t\t\tCOUNTIF(ARRAY_LENGTH(matrixTypes) > 1 OR (ARRAY_LENGTH(matrixTypes) = 1 AND matrixTypes[OFFSET(0)] != \".loom\")) AS otherMatrixSessionCount\n\t\tFROM (\n\t\t\tSELECT\n\t\t\t\tDATE_TRUNC(timestamp, DAY) AS day,\n\t\t\t\tprotopayload_auditlog.requestMetadata.callerIp,\n\t\t\t\tARRAY_AGG(\n\t\t\t\t\tDISTINCT\n\t\t\t\t\tIF(\n\t\t\t\t\t\tREGEXP_CONTAINS(protopayload_auditlog.resourceName, \"(?i)\\\\\\\\.fastq(?:\\\\\\\\.|$)\"),\n\t\t\t\t\t\t\"fastq\",\n\t\t\t\t\t\tIF(\n\t\t\t\t\t\t\tREGEXP_CONTAINS(protopayload_auditlog.resourceName, \"(?i)\\\\\\\\.bam(?:\\\\\\\\.|$)\"),\n\t\t\t\t\t\t\t\"bam\",\n\t\t\t\t\t\t\tIF(\n\t\t\t\t\t\t\t\tREGEXP_CONTAINS(protopayload_auditlog.resourceName, \"(?i)\\\\\\\\.(?:h5ad|loom|mtx)(?:\\\\\\\\.|$)\"),\n\t\t\t\t\t\t\t\t\"matrix\",\n\t\t\t\t\t\t\t\t\"other\"\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t\t\t\t) AS fileTypes,\n\t\t\t\tARRAY_AGG(\n\t\t\t\t\tDISTINCT\n\t\t\t\t\tREGEXP_EXTRACT(protopayload_auditlog.resourceName, \"(?i)\\\\\\\\.(?:(?:h5ad|mtx)(?:\\\\\\\\.|$)|loom$|loom\\\\\\\\.)\")\n\t\t\t\t\tIGNORE NULLS\n\t\t\t\t) AS matrixTypes\n\t\t\tFROM `broad-datarepo-terra-prod-hca2.accesslogs.cloudaudit_googleapis_com_data_access_*`\n\t\t\tGROUP BY day, callerIp\n\t\t)\n\t\tGROUP BY day ORDER BY day\n\t\"\"\"\n\n\tclient = bigquery.Client()\n\n\tdf = client.query(QUERY).result().to_dataframe(create_bqstorage_client=False)\n\tdf.set_index(\"day\", inplace=True)\n\t\n\tdef plot_total():\n\t\tplt.rc(\"font\", size=16)\n\n\t\tax_total = df[\"totalSessionCount\"].plot(title='Number of sessions per day downloading files', legend=False, xlabel='', figsize=(16, 9))\n\t\tplt.show()\n\t\n\tdef plot_a():\n\t\tplt.rc(\"font\", size=16)\n\n\t\tdf_a = df[[\"fastqSessionCount\", \"bamSessionCount\", \"matrixSessionCount\", \"otherSessionCount\"]].rolling(\"7d\").mean()\n\t\t\n\t\taxs_a = df_a.plot(subplots=True, ylim=(0, df_a.max().max() + 5), title=\"Number of sessions per day downloading given file types\", xlabel=\"\", figsize=(16, 9))\n\t\taxs_a[0].legend([\"FASTQ\"])\n\t\taxs_a[1].legend([\"BAM\"])\n\t\taxs_a[2].legend([\"Matrix\"])\n\t\taxs_a[3].legend([\"Other\"])\n\t\tplt.tight_layout()\n\t\tplt.show()\n\n\tdef plot_b():\n\t\tplt.rc(\"font\", size=16)\n\n\t\tdf_b = pd.concat([\n\t\t\t(df[\"matrixSessionCount\"] - df[\"loomMatrixSessionCount\"]).rename(\"CGMs only\"),\n\t\t\t(df[\"loomMatrixSessionCount\"] + df[\"otherMatrixSessionCount\"] - df[\"matrixSessionCount\"]).rename(\"CGMs and DCP matrices\"),\n\t\t\t(df[\"matrixSessionCount\"] - df[\"otherMatrixSessionCount\"]).rename(\"DCP matrices only\")\n\t\t], axis=1).rolling(\"7d\").mean()\n\t\tax_b = df_b.plot(kind=\"area\", stacked=True, title=\"Number of sessions per day downloading matrices\", xlabel=\"\", figsize=(16, 9))\n\t\tplt.tight_layout()\n\t\tplt.show()\n\t\n\treturn plot_total, plot_a, plot_b\n\ndef plot_ethnicity():\n\tcatalog = \"dcp15\"\n\n\tdef get_sources_expr():\n\t\tsources = requests.get(\"https://service.azul.data.humancellatlas.org/repository/sources?catalog=\" + catalog).json()[\"sources\"]\n\t\treturn \"(\" + \" UNION ALL \".join([\"SELECT * FROM `\" + get_table_name(source[\"sourceSpec\"]) + \"`\" for source in sources]) + \")\"\n\n\tdef get_table_name(spec):\n\t\tparts = [p.split(\":\") for p in spec.split(\"/\")]\n\t\treturn parts[0][1] + \".\" + parts[1][0] + \".donor_organism\"\n\n\tQUERY = \"\"\"\n\t\tselect\n\t\t\tIFNULL(ethnicity, \"[Missing]\") as Ethnicity,\n\t\t\tCode,\n\t\t\tcount(*) as Count\n\t\tfrom (\n\t\t\tselect\n\t\t\t\tdatarepo_row_id,\n\t\t\t\tjson_extract_scalar(gs, \"$.ontology\") as species,\n\t\t\t\tjson_extract_scalar(eth, \"$.ontology_label\") as ethnicity, \n\t\t\t\tjson_extract_scalar(eth, \"$.ontology\") as Code,\n\t\t\t\tcontent,\n\t\t\t\tjson_extract_scalar(content, \"$.provenance.document_id\") AS did\n\t\t\tfrom\n\t\t\t\t%s\n\t\t\t\tLEFT JOIN UNNEST(JSON_EXTRACT_ARRAY(content, \"$.genus_species\")) as gs\n\t\t\t\tLEFT JOIN UNNEST(JSON_EXTRACT_ARRAY(content, \"$.human_specific.ethnicity\")) AS eth\n\t\t) as T\n\t\twhere species = \"NCBITaxon:9606\"\n\t\tGROUP BY T.ethnicity, T.Code\n\t\tORDER BY Count DESC \n\t\t\"\"\" % get_sources_expr()\n\t\n\tclient = bigquery.Client()\n\n\tdf = client.query(QUERY).result().to_dataframe(create_bqstorage_client=False)\n\tdf.set_index(\"Ethnicity\", inplace=True)\n\t\n\tseries_a = df[\"Count\"].groupby(lambda eth: \"Unspecified\" if eth == \"[Missing]\" else \"Specified\").sum()\n\tseries_b = df.loc[df.index != \"[Missing]\"][\"Count\"]\n\t\n\tseries_a.sort_values(inplace=True, ascending=False)\n\t\n\tdef plot_a():\n\t\tplt.rc(\"font\", size=16)\n\n\t\tax_a = series_a.plot(kind=\"barh\", title=\"Donor ethnicity (\" + catalog.upper() + \") - Specified vs. Unspecified\", xlabel=\"\", figsize=(16, 9))\n\t\tax_a.set_xlabel(\"Donors\")\n\t\tplt.tight_layout()\n\t\tplt.show()\n\t\n\tdef plot_b():\n\t\tplt.rc(\"font\", size=16)\n\t\n\t\tax_b = series_b.plot(kind=\"barh\", title=\"Donor ethnicity (\" + catalog.upper() + \")\", xlabel=\"\", figsize=(16, 9))\n\t\tax_b.set_xlabel(\"Donors\")\n\t\tplt.tight_layout()\n\t\tplt.show()\n\t\n\treturn plot_a, plot_b\n\n"
] |
[
[
"pandas.to_datetime",
"pandas.Index",
"pandas.isna",
"pandas.DataFrame",
"pandas.MultiIndex.from_tuples",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.rc",
"matplotlib.pyplot.barh",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.show",
"pandas.Period"
]
] |
intendo/pygbe
|
[
"6ac43ebfb3a4d342a380d7938af119cfba587746"
] |
[
"pygbe/projection.py"
] |
[
"\"\"\"\nIt contains the functions to calculate the different potentials:\n-The single and double layer potential.\n-The adjoint double layer potential.\n-The reaction potential.\n\"\"\"\nimport numpy\nfrom numpy import pi\n\nfrom pygbe.classes import Event\nfrom pygbe.quadrature import getWeights\nfrom pygbe.tree.direct import direct_c\nfrom pygbe.tree.FMMutils import (getMultipole, upwardSweep, M2P_sort, M2PKt_sort,\n M2P_gpu, M2PKt_gpu, P2P_sort, P2PKt_sort, P2P_gpu,\n P2PKt_gpu, M2P_nonvec, P2P_nonvec, P2P_nonvec_derivative)\n\ntry:\n import pycuda.autoinit\n import pycuda.driver as cuda\nexcept:\n pass\n\nimport time\n\n\ndef project(XK, XV, LorY, surfSrc, surfTar, K_diag, V_diag, IorE, self, param,\n ind0, timing, kernel):\n \"\"\"\n It computes the single and double layer potentials.\n\n Arguments\n ----------\n XK : array, input for the double layer potential.\n XV : array, input for the single layer potential.\n LorY : int, Laplace (1) or Yukawa (2).\n surfSrc: class, source surface, the one that contains the gauss points.\n surfTar: class, target surface, the one that contains the collocation\n points.\n K_diag : array, diagonal elements of the double layer integral operator.\n V_diag : array, diagonal elements of the single layer integral operator.\n IorE : int, internal (1) or external (2).\n self : int, position in the surface array of the source surface.\n param : class, parameters related to the surface.\n ind0 : array, it contains the indices related to the treecode computation.\n timing : class, it contains timing information for different parts of the\n code.\n kernel : pycuda source module.\n\n Returns\n --------\n K_lyr : array, double layer potential.\n V_lyr : array, single layer potential.\n \"\"\"\n\n if param.GPU == 1:\n tic = cuda.Event()\n toc = cuda.Event()\n else:\n tic = Event()\n toc = Event()\n\n REAL = param.REAL\n Ns = len(surfSrc.triangle)\n L = numpy.sqrt(2 * surfSrc.area) # Representative length\n\n tic.record()\n K = param.K\n w = getWeights(K)\n X_V = numpy.zeros(Ns * K)\n X_Kx = numpy.zeros(Ns * K)\n X_Ky = numpy.zeros(Ns * K)\n X_Kz = numpy.zeros(Ns * K)\n X_Kc = numpy.zeros(Ns * K)\n X_Vc = numpy.zeros(Ns * K)\n\n NsK = numpy.arange(Ns * K)\n X_V[:] = XV[NsK // K] * w[NsK % K] * surfSrc.area[NsK // K]\n X_Kx[:] = XK[NsK // K] * w[NsK % K] * surfSrc.area[\n NsK // K] * surfSrc.normal[NsK // K, 0]\n X_Ky[:] = XK[NsK // K] * w[NsK % K] * surfSrc.area[\n NsK // K] * surfSrc.normal[NsK // K, 1]\n X_Kz[:] = XK[NsK // K] * w[NsK % K] * surfSrc.area[\n NsK // K] * surfSrc.normal[NsK // K, 2]\n X_Kc[:] = XK[NsK // K]\n X_Vc[:] = XV[NsK // K]\n\n toc.record()\n toc.synchronize()\n timing.time_mass += tic.time_till(toc) * 1e-3\n\n tic.record()\n C = 0\n getMultipole(surfSrc.tree, C, surfSrc.xj, surfSrc.yj, surfSrc.zj, X_V,\n X_Kx, X_Ky, X_Kz, ind0, param.P, param.NCRIT)\n toc.record()\n toc.synchronize()\n timing.time_P2M += tic.time_till(toc) * 1e-3\n\n tic.record()\n for C in reversed(range(1, len(surfSrc.tree))):\n PC = surfSrc.tree[C].parent\n upwardSweep(surfSrc.tree, C, PC, param.P, ind0.II, ind0.JJ, ind0.KK,\n ind0.index, ind0.combII, ind0.combJJ, ind0.combKK,\n ind0.IImii, ind0.JJmjj, ind0.KKmkk, ind0.index_small,\n ind0.index_ptr)\n toc.record()\n toc.synchronize()\n timing.time_M2M += tic.time_till(toc) * 1e-3\n\n tic.record()\n X_V = X_V[surfSrc.sortSource]\n X_Kx = X_Kx[surfSrc.sortSource]\n X_Ky = X_Ky[surfSrc.sortSource]\n X_Kz = X_Kz[surfSrc.sortSource]\n X_Kc = X_Kc[surfSrc.sortSource]\n X_Vc = X_Vc[surfSrc.sortSource]\n toc.record()\n toc.synchronize()\n timing.time_sort += tic.time_till(toc) * 1e-3\n\n param.Nround = len(surfTar.twig) * param.NCRIT\n K_aux = numpy.zeros(param.Nround)\n V_aux = numpy.zeros(param.Nround)\n\n ### CPU code\n if param.GPU == 0:\n if surfTar.offsetMlt[self, len(surfTar.twig)] > 0:\n \tK_aux, V_aux = M2P_sort(surfSrc, surfTar, K_aux, V_aux, self,\n ind0.index_large, param, LorY, timing)\n\n K_aux, V_aux = P2P_sort(surfSrc, surfTar, X_V, X_Kx, X_Ky, X_Kz, X_Kc,\n X_Vc, K_aux, V_aux, self, LorY, K_diag, V_diag,\n IorE, L, w, param, timing)\n\n ### GPU code\n elif param.GPU == 1:\n K_gpu = cuda.to_device(K_aux.astype(REAL))\n V_gpu = cuda.to_device(V_aux.astype(REAL))\n\n if surfTar.offsetMlt[self, len(surfTar.twig)] > 0:\n K_gpu, V_gpu = M2P_gpu(surfSrc, surfTar, K_gpu, V_gpu, self, ind0,\n param, LorY, timing, kernel)\n\n K_gpu, V_gpu = P2P_gpu(surfSrc, surfTar, X_V, X_Kx, X_Ky, X_Kz, X_Kc,\n X_Vc, K_gpu, V_gpu, self, LorY, K_diag, IorE, L,\n w, param, timing, kernel)\n\n tic.record()\n K_aux = cuda.from_device(K_gpu, len(K_aux), dtype=REAL)\n V_aux = cuda.from_device(V_gpu, len(V_aux), dtype=REAL)\n toc.record()\n toc.synchronize()\n timing.time_trans += tic.time_till(toc) * 1e-3\n\n tic.record()\n K_lyr = K_aux[surfTar.unsort]\n V_lyr = V_aux[surfTar.unsort]\n toc.record()\n toc.synchronize()\n timing.time_sort += tic.time_till(toc) * 1e-3\n\n return K_lyr, V_lyr\n\n\ndef project_Kt(XKt, LorY, surfSrc, surfTar, Kt_diag, self, param, ind0, timing,\n kernel):\n \"\"\"\n It computes the adjoint double layer potential.\n\n Arguments\n ----------\n XKt : array, input for the adjoint double layer potential.\n LorY : int, Laplace (1) or Yukawa (2).\n surfSrc: class, source surface, the one that contains the gauss points.\n surfTar: class, target surface, the one that contains the collocation points.\n Kt_diag: array, diagonal elements of the adjoint double layer integral\n operator.\n self : int, position in the surface array of the source surface.\n param : class, parameters related to the surface.\n ind0 : array, it contains the indices related to the treecode computation.\n timing : class, it contains timing information for different parts of the\n code.\n kernel : pycuda source module.\n\n Returns\n --------\n Kt_lyr: array, adjoint double layer potential.\n \"\"\"\n\n if param.GPU == 1:\n tic = cuda.Event()\n toc = cuda.Event()\n else:\n tic = Event()\n toc = Event()\n\n REAL = param.REAL\n Ns = len(surfSrc.triangle)\n\n tic.record()\n K = param.K\n w = getWeights(K)\n X_Kt = numpy.zeros(Ns * K)\n X_Ktc = numpy.zeros(Ns * K)\n\n NsK = numpy.arange(Ns * K)\n X_Kt[:] = XKt[NsK // K] * w[NsK % K] * surfSrc.area[NsK // K]\n X_Ktc[:] = XKt[NsK // K]\n\n toc.record()\n toc.synchronize()\n timing.time_mass += tic.time_till(toc) * 1e-3\n\n tic.record()\n C = 0\n X_aux = numpy.zeros(Ns * K)\n getMultipole(surfSrc.tree, C, surfSrc.xj, surfSrc.yj, surfSrc.zj, X_Kt,\n X_aux, X_aux, X_aux, ind0, param.P, param.NCRIT)\n toc.record()\n toc.synchronize()\n timing.time_P2M += tic.time_till(toc) * 1e-3\n\n tic.record()\n for C in reversed(range(1, len(surfSrc.tree))):\n PC = surfSrc.tree[C].parent\n upwardSweep(surfSrc.tree, C, PC, param.P, ind0.II, ind0.JJ, ind0.KK,\n ind0.index, ind0.combII, ind0.combJJ, ind0.combKK,\n ind0.IImii, ind0.JJmjj, ind0.KKmkk, ind0.index_small,\n ind0.index_ptr)\n toc.record()\n toc.synchronize()\n timing.time_M2M += tic.time_till(toc) * 1e-3\n\n tic.record()\n X_Kt = X_Kt[surfSrc.sortSource]\n X_Ktc = X_Ktc[surfSrc.sortSource]\n toc.record()\n toc.synchronize()\n timing.time_sort += tic.time_till(toc) * 1e-3\n\n param.Nround = len(surfTar.twig) * param.NCRIT\n Ktx_aux = numpy.zeros(param.Nround)\n Kty_aux = numpy.zeros(param.Nround)\n Ktz_aux = numpy.zeros(param.Nround)\n\n ### CPU code\n if param.GPU == 0:\n if surfTar.offsetMlt[self, len(surfTar.twig)] > 0:\n Ktx_aux, Kty_aux, Ktz_aux = M2PKt_sort(\n surfSrc, surfTar, Ktx_aux, Kty_aux, Ktz_aux, self,\n ind0.index_large, param, LorY, timing)\n\n Ktx_aux, Kty_aux, Ktz_aux = P2PKt_sort(surfSrc, surfTar, X_Kt, X_Ktc,\n Ktx_aux, Kty_aux, Ktz_aux, self,\n LorY, w, param, timing)\n\n ### GPU code\n elif param.GPU == 1:\n Ktx_gpu = cuda.to_device(Ktx_aux.astype(REAL))\n Kty_gpu = cuda.to_device(Kty_aux.astype(REAL))\n Ktz_gpu = cuda.to_device(Ktz_aux.astype(REAL))\n\n if surfTar.offsetMlt[self, len(surfTar.twig)] > 0:\n Ktx_gpu, Kty_gpu, Ktz_gpu = M2PKt_gpu(surfSrc, surfTar, Ktx_gpu,\n Kty_gpu, Ktz_gpu, self, ind0,\n param, LorY, timing, kernel)\n\n Ktx_gpu, Kty_gpu, Ktz_gpu = P2PKt_gpu(surfSrc, surfTar, X_Kt, X_Ktc,\n Ktx_gpu, Kty_gpu, Ktz_gpu, self,\n LorY, w, param, timing, kernel)\n\n tic.record()\n Ktx_aux = cuda.from_device(Ktx_gpu, len(Ktx_aux), dtype=REAL)\n Kty_aux = cuda.from_device(Kty_gpu, len(Kty_aux), dtype=REAL)\n Ktz_aux = cuda.from_device(Ktz_gpu, len(Ktz_aux), dtype=REAL)\n toc.record()\n toc.synchronize()\n timing.time_trans += tic.time_till(toc) * 1e-3\n\n tic.record()\n Kt_lyr = (Ktx_aux[surfTar.unsort]*surfTar.normal[:,0] +\n Kty_aux[surfTar.unsort]*surfTar.normal[:,1] +\n Ktz_aux[surfTar.unsort]*surfTar.normal[:,2])\n\n if abs(Kt_diag) > 1e-12: # if same surface\n Kt_lyr += Kt_diag * XKt\n\n toc.record()\n toc.synchronize()\n timing.time_sort += tic.time_till(toc) * 1e-3\n\n return Kt_lyr\n\n\ndef get_phir_tree(XK, XV, surface, xq, Cells, par_reac, ind_reac):\n \"\"\"\n It computes the reaction potential using treecode.\n To compute this potential we need more terms in the Taylor expansion, that\n is the reason why we need fine parameters (par_reac class) and a different\n array of indices (ind_reac) than ind0.\n\n Arguments\n ----------\n XK : array, input for the double layer potential.\n XV : array, input for the single layer potential.\n surface : class, surface where we are computing the reaction potential.\n xq : array, it contains the position of the charges.\n Cells : array, it contains the tree cells.\n par_reac: class, fine parameters related to the surface.\n ind_reac: array, it contains the indices related to the treecode\n computation.\n\n Returns\n --------\n phi_reac: array, reaction potential.\n AI_int : int, counter of the amount of near singular integrals solved.\n \"\"\"\n\n N = len(XK)\n AI_int = 0\n\n # Setup vector\n K = par_reac.K\n tic = time.time()\n w = getWeights(K)\n X_V = numpy.zeros(N * K)\n X_Kx = numpy.zeros(N * K)\n X_Ky = numpy.zeros(N * K)\n X_Kz = numpy.zeros(N * K)\n X_Kc = numpy.zeros(N * K)\n X_Vc = numpy.zeros(N * K)\n\n for i in range(N * K):\n X_V[i] = XV[i // K] * w[i % K] * surface.area[i // K]\n X_Kx[i] = XK[i // K] * w[i % K] * surface.area[\n i // K] * surface.normal[i // K, 0]\n X_Ky[i] = XK[i // K] * w[i % K] * surface.area[\n i // K] * surface.normal[i // K, 1]\n X_Kz[i] = XK[i // K] * w[i % K] * surface.area[\n i // K] * surface.normal[i // K, 2]\n X_Kc[i] = XK[i // K]\n X_Vc[i] = XV[i // K]\n\n toc = time.time()\n\n # P2M\n tic = time.time()\n C = 0\n getMultipole(Cells, C, surface.xj, surface.yj, surface.zj, X_V, X_Kx, X_Ky,\n X_Kz, ind_reac, par_reac.P, par_reac.NCRIT)\n toc = time.time()\n time_P2M = toc - tic\n\n # M2M\n tic = time.time()\n for C in reversed(range(1, len(Cells))):\n PC = Cells[C].parent\n upwardSweep(Cells, C, PC, par_reac.P, ind_reac.II, ind_reac.JJ,\n ind_reac.KK, ind_reac.index, ind_reac.combII,\n ind_reac.combJJ, ind_reac.combKK, ind_reac.IImii,\n ind_reac.JJmjj, ind_reac.KKmkk, ind_reac.index_small,\n ind_reac.index_ptr)\n toc = time.time()\n time_M2M = toc - tic\n\n # Evaluation\n IorE = 0 # This evaluation is on charge points, no self-operator\n # 0 means it doesn't matter if it is internal or external.\n AI_int = 0\n phi_reac = numpy.zeros(len(xq))\n time_P2P = 0.\n time_M2P = 0.\n for i in range(len(xq)):\n CJ = 0\n Kval = 0.\n Vval = 0.\n source = []\n Kval, Vval, source, time_M2P = M2P_nonvec(Cells, CJ, xq[i], Kval, Vval,\n ind_reac.index_large,\n par_reac, source, time_M2P)\n if len(source) != 0:\n Kval, Vval, AI_int, time_P2P = P2P_nonvec(\n Cells, surface, X_V, X_Kx, X_Ky, X_Kz, X_Kc, X_Vc, xq[i], Kval,\n Vval, IorE, par_reac, w, source, AI_int, time_P2P)\n phi_reac[i] = (-Kval + Vval) / (4 * pi)\n\n return phi_reac, AI_int\n\n\ndef get_phir(XK, XV, surface, xq, Cells, par_reac, ind_reac):\n \"\"\"\n It computes the reaction potential using direct interacion.\n To compute this potential we need more terms in the Taylor expansion, that\n is the reason why we need fine parameters (par_reac class) and a different\n array of indices (ind_reac) than ind0.\n\n Arguments\n ----------\n XK : array, input for the double layer potential.\n XV : array, input for the single layer potential.\n surface : class, surface where we are computing the reaction potential.\n xq : array, it contains the position of the charges.\n Cells : array, it contains the tree cells.\n par_reac: class, fine parameters related to the surface.\n ind_reac: array, it contains the indices related to the treecode\n computation.\n\n Returns\n --------\n phi_reac: array, reaction potential.\n AI_int : int, counter of the amount of near singular integrals solved.\n \"\"\"\n\n N = len(XK)\n AI_int = 0\n\n # Setup vector\n K = par_reac.K\n tic = time.time()\n w = getWeights(K)\n X_V = numpy.zeros(N * K)\n X_Kx = numpy.zeros(N * K)\n X_Ky = numpy.zeros(N * K)\n X_Kz = numpy.zeros(N * K)\n X_Kc = numpy.zeros(N * K)\n X_Vc = numpy.zeros(N * K)\n\n for i in range(N * K):\n X_V[i] = XV[i // K] * w[i % K] * surface.area[i // K]\n X_Kx[i] = XK[i // K] * w[i % K] * surface.area[\n i // K] * surface.normal[i // K, 0]\n X_Ky[i] = XK[i // K] * w[i % K] * surface.area[\n i // K] * surface.normal[i // K, 1]\n X_Kz[i] = XK[i // K] * w[i % K] * surface.area[\n i // K] * surface.normal[i // K, 2]\n X_Kc[i] = XK[i // K]\n X_Vc[i] = XV[i // K]\n\n # Evaluation\n IorE = 0 # This evaluation is on charge points, no self-operator\n # 0 means it doesn't matter if it is internal or external.\n\n \n AI_int = 0\n phi_reac = numpy.zeros(len(xq))\n source = list(range(len(surface.xj)))\n source = numpy.int32(numpy.array(source))\n\n m, mx, my, mz, mKc, mVc = X_V, X_Kx, X_Ky, X_Kz, X_Kc, X_Vc\n\n LorY = 1\n \n s_xj = surface.xj[source]\n s_yj = surface.yj[source]\n s_zj = surface.zj[source]\n s_m = m[source]\n s_mx = mx[source]\n s_my = my[source]\n s_mz = mz[source]\n s_mKc = mKc[source]\n s_mVc = mVc[source]\n\n tri = source / par_reac.K # Triangle\n k = source % par_reac.K # Gauss point\n\n K_diag = 0\n V_diag = 0\n\n xq_arr = numpy.ravel(numpy.array([xq[:, 0]]))\n yq_arr = numpy.ravel(numpy.array([xq[:, 1]]))\n zq_arr = numpy.ravel(numpy.array([xq[:, 2]]))\n\n direct_c(int(LorY),\n K_diag,\n V_diag,\n int(IorE),\n numpy.ravel(surface.vertex[surface.triangle[:]]),\n numpy.int32(tri),\n numpy.int32(k),\n surface.xi,\n surface.yi,\n surface.zi,\n s_xj,\n s_yj,\n s_zj,\n xq_arr,\n yq_arr,\n zq_arr,\n s_m,\n s_mx,\n s_my,\n s_mz,\n s_mKc,\n s_mVc,\n numpy.array(\n [-1], dtype=numpy.int32),\n surface.area,\n surface.sglInt_int,\n surface.sglInt_ext,\n surface.xk,\n surface.wk,\n surface.Xsk,\n surface.Wsk,\n par_reac.kappa,\n par_reac.threshold,\n par_reac.eps,\n w[0], AI_int, numpy.ravel(phi_reac))\n\n return phi_reac, AI_int\n\n\ndef get_phir_gpu(XK, XV, surface, field, par_reac, kernel):\n \"\"\"\n It computes the reaction potential on the GPU and it brings the data\n to the cpu.\n\n Arguments\n ----------\n XK : array, input for the double layer potential.\n XV : array, input for the single layer potential.\n surface : class, surface where we are computing the reaction potential.\n field : class, information about the different regions in the molecule.\n par_reac: class, fine parameters related to the surface.\n\n Returns\n --------\n phir_cpu: array, reaction potential brought from the GPU to the cpu.\n AI_int : int, counter of the amount of near singular integrals solved.\n \"\"\"\n\n REAL = par_reac.REAL\n Nq = len(field.xq)\n N = len(XK)\n AI_int = 0\n\n # Setup vector\n K = par_reac.K\n tic = time.time()\n w = getWeights(K)\n X_V = numpy.zeros(N * K)\n X_Kx = numpy.zeros(N * K)\n X_Ky = numpy.zeros(N * K)\n X_Kz = numpy.zeros(N * K)\n X_Kc = numpy.zeros(N * K)\n X_Vc = numpy.zeros(N * K)\n\n for i in range(N * K):\n X_V[i] = XV[i // K] * w[i % K] * surface.area[i // K]\n X_Kx[i] = XK[i // K] * w[i % K] * surface.area[\n i // K] * surface.normal[i // K, 0]\n X_Ky[i] = XK[i // K] * w[i % K] * surface.area[\n i // K] * surface.normal[i // K, 1]\n X_Kz[i] = XK[i // K] * w[i % K] * surface.area[\n i // K] * surface.normal[i // K, 2]\n X_Kc[i] = XK[i // K]\n X_Vc[i] = XV[i // K]\n\n toc = time.time()\n sort = surface.sortSource\n phir = cuda.to_device(numpy.zeros(Nq, dtype=REAL))\n m_gpu = cuda.to_device(X_V[sort].astype(REAL))\n mx_gpu = cuda.to_device(X_Kx[sort].astype(REAL))\n my_gpu = cuda.to_device(X_Ky[sort].astype(REAL))\n mz_gpu = cuda.to_device(X_Kz[sort].astype(REAL))\n mKc_gpu = cuda.to_device(X_Kc[sort].astype(REAL))\n mVc_gpu = cuda.to_device(X_Vc[sort].astype(REAL))\n AI_int_gpu = cuda.to_device(numpy.zeros(Nq, dtype=numpy.int32))\n xkDev = cuda.to_device(surface.xk.astype(REAL))\n wkDev = cuda.to_device(surface.wk.astype(REAL))\n\n get_phir = kernel.get_function(\"get_phir\")\n GSZ = int(numpy.ceil(float(Nq) / par_reac.BSZ))\n\n get_phir(phir,\n field.xq_gpu,\n field.yq_gpu,\n field.zq_gpu,\n m_gpu,\n mx_gpu,\n my_gpu,\n mz_gpu,\n mKc_gpu,\n mVc_gpu,\n surface.xjDev,\n surface.yjDev,\n surface.zjDev,\n surface.AreaDev,\n surface.kDev,\n surface.vertexDev,\n numpy.int32(len(surface.xj)),\n numpy.int32(Nq),\n numpy.int32(par_reac.K),\n xkDev,\n wkDev,\n REAL(par_reac.threshold),\n AI_int_gpu,\n numpy.int32(len(surface.xk)),\n surface.XskDev,\n surface.WskDev,\n block=(par_reac.BSZ, 1, 1),\n grid=(GSZ, 1))\n\n AI_aux = numpy.zeros(Nq, dtype=numpy.int32)\n AI_aux = cuda.from_device(AI_int_gpu, Nq, dtype=numpy.int32)\n AI_int = numpy.sum(AI_aux)\n\n phir_cpu = numpy.zeros(Nq, dtype=REAL)\n phir_cpu = cuda.from_device(phir, Nq, dtype=REAL)\n\n return phir_cpu, AI_int\n\ndef get_dphirdr (XK, XV, surface, xq, Cells, par_reac, ind_reac):\n\n REAL = par_reac.REAL\n N = len(XK)\n MV = numpy.zeros(len(XK))\n L = numpy.sqrt(2*surface.area) # Representative length\n AI_int = 0\n\n # Setup vector\n K = par_reac.K\n tic = time.time()\n w = getWeights(K)\n X_V = numpy.zeros(N*K)\n X_Kx = numpy.zeros(N*K)\n X_Ky = numpy.zeros(N*K)\n X_Kz = numpy.zeros(N*K)\n X_Kc = numpy.zeros(N*K)\n X_Vc = numpy.zeros(N*K)\n\n for i in range(N*K):\n X_V[i] = XV[i//K]*w[i%K]*surface.area[i//K]\n X_Kx[i] = XK[i//K]*w[i%K]*surface.area[i//K]*surface.normal[i//K,0]\n X_Ky[i] = XK[i//K]*w[i%K]*surface.area[i//K]*surface.normal[i//K,1]\n X_Kz[i] = XK[i//K]*w[i%K]*surface.area[i//K]*surface.normal[i//K,2]\n X_Kc[i] = XK[i//K]\n X_Vc[i] = XV[i//K]\n \n toc = time.time()\n time_set = toc - tic\n\n # Evaluation\n IorE = 0 # This evaluation is on charge points, no self-operator\n AI_int = 0\n dphix_reac = numpy.zeros(len(xq))\n dphiy_reac = numpy.zeros(len(xq))\n dphiz_reac = numpy.zeros(len(xq))\n time_P2P = 0.\n time_M2P = 0.\n for i in range(len(xq)):\n CJ = 0\n dKxval = 0.\n dKyval = 0.\n dKzval = 0.\n dVxval = 0.\n dVyval = 0.\n dVzval = 0.\n source = []\n dKxval, dVxval, source, time_M2P = M2P_nonvec(Cells, CJ, xq[i], dKxval, dVxval,\n ind_reac.index_large, par_reac, source, time_M2P)\n\n dKxval, dKyval, dKzval, dVxval, \\\n dVyval, dVzval, AI_int, time_P2P = P2P_nonvec_derivative(Cells, surface, X_V, X_Kx, X_Ky, X_Kz, X_Kc, X_Vc,\n xq[i], dKxval, dKyval, dKzval, dVxval, dVyval, dVzval, IorE, par_reac, w, source, AI_int, time_P2P)\n dphix_reac[i] = (-dKxval + dVxval)/(4*pi)\n dphiy_reac[i] = (-dKyval + dVyval)/(4*pi)\n dphiz_reac[i] = (-dKzval + dVzval)/(4*pi)\n# print '\\tTime set: %f'%time_P2M\n# print '\\tTime P2M: %f'%time_P2M\n# print '\\tTime M2M: %f'%time_M2M\n# print '\\tTime M2P: %f'%time_M2P\n# print '\\tTime P2P: %f'%time_P2P\n\n return dphix_reac, dphiy_reac, dphiz_reac, AI_int\n\ndef get_dphirdr_gpu (XK, XV, surface, field, par_reac, kernel):\n\n REAL = par_reac.REAL\n Nq = len(field.xq)\n N = len(XK)\n MV = numpy.zeros(len(XK))\n L = numpy.sqrt(2*surface.area) # Representative length\n AI_int = 0\n\n # Setup vector\n K = par_reac.K\n tic = time.time()\n w = getWeights(K)\n X_V = numpy.zeros(N*K)\n X_Kx = numpy.zeros(N*K)\n X_Ky = numpy.zeros(N*K)\n X_Kz = numpy.zeros(N*K)\n X_Kc = numpy.zeros(N*K)\n X_Vc = numpy.zeros(N*K)\n\n for i in range(N*K):\n X_V[i] = XV[i//K]*w[i%K]*surface.area[i//K]\n X_Kx[i] = XK[i//K]*w[i%K]*surface.area[i//K]*surface.normal[i//K,0]\n X_Ky[i] = XK[i//K]*w[i%K]*surface.area[i//K]*surface.normal[i//K,1]\n X_Kz[i] = XK[i//K]*w[i%K]*surface.area[i//K]*surface.normal[i//K,2]\n X_Kc[i] = XK[i//K]\n X_Vc[i] = XV[i//K]\n\n toc = time.time()\n time_set = toc - tic\n sort = surface.sortSource\n dphir_x = cuda.to_device(numpy.zeros(Nq, dtype=REAL))\n dphir_y = cuda.to_device(numpy.zeros(Nq, dtype=REAL))\n dphir_z = cuda.to_device(numpy.zeros(Nq, dtype=REAL))\n m_gpu = cuda.to_device(X_V[sort].astype(REAL))\n mx_gpu = cuda.to_device(X_Kx[sort].astype(REAL))\n my_gpu = cuda.to_device(X_Ky[sort].astype(REAL))\n mz_gpu = cuda.to_device(X_Kz[sort].astype(REAL))\n mKc_gpu = cuda.to_device(X_Kc[sort].astype(REAL))\n mVc_gpu = cuda.to_device(X_Vc[sort].astype(REAL))\n AI_int_gpu = cuda.to_device(numpy.zeros(Nq, dtype=numpy.int32))\n xkDev = cuda.to_device(surface.xk.astype(REAL))\n wkDev = cuda.to_device(surface.wk.astype(REAL))\n\n\n get_dphirdr = kernel.get_function(\"get_dphirdr\")\n GSZ = int(numpy.ceil(float(Nq)/par_reac.BSZ))\n\n get_dphirdr(dphir_x, dphir_y, dphir_z, field.xq_gpu, field.yq_gpu, field.zq_gpu, m_gpu, mx_gpu, my_gpu, mz_gpu, \n mKc_gpu, mVc_gpu, surface.xjDev, surface.yjDev, surface.zjDev, surface.AreaDev, surface.kDev, surface.vertexDev, \n numpy.int32(len(surface.xj)), numpy.int32(Nq), numpy.int32(par_reac.K), xkDev, wkDev, REAL(par_reac.threshold),\n AI_int_gpu, numpy.int32(len(surface.xk)), surface.XskDev, surface.WskDev, block=(par_reac.BSZ,1,1), grid=(GSZ,1))\n\n AI_aux = numpy.zeros(Nq, dtype=numpy.int32)\n AI_aux = cuda.from_device(AI_int_gpu, Nq, dtype=numpy.int32)\n AI_int = numpy.sum(AI_aux)\n\n dphir_x_cpu = numpy.zeros(Nq, dtype=REAL)\n dphir_x_cpu = cuda.from_device(dphir_x, Nq, dtype=REAL)\n dphir_y_cpu = numpy.zeros(Nq, dtype=REAL)\n dphir_y_cpu = cuda.from_device(dphir_y, Nq, dtype=REAL)\n dphir_z_cpu = numpy.zeros(Nq, dtype=REAL)\n dphir_z_cpu = cuda.from_device(dphir_z, Nq, dtype=REAL)\n\n return dphir_x_cpu, dphir_y_cpu, dphir_z_cpu, AI_int\n"
] |
[
[
"numpy.array",
"numpy.zeros",
"numpy.sum",
"numpy.arange",
"numpy.ravel",
"numpy.sqrt",
"numpy.int32"
]
] |
PKU-DAIR/2021_CCF_BDCI_LargeBERT_Rank1st
|
[
"6382433cda69c655f03c3cc284dc076407f18dc9"
] |
[
"code/fused_ops/fused_ops/layernorm_module/fused_layer_norm.py"
] |
[
"import math\nimport torch\nimport numbers\nfrom torch.nn.parameter import Parameter\nfrom torch.nn import init\nfrom torch.nn import functional as F\nimport fused_layernorm_fast_cuda\nimport fused_layernorm_backward_gamma_beta_cuda\n\nclass FusedLayerNormFastFunction(torch.autograd.Function):\n\n @staticmethod\n def forward(ctx, input, weight, bias, normalized_shape, eps):\n ctx.normalized_shape = normalized_shape\n ctx.eps = eps\n input_ = input.contiguous()\n weight_ = weight.contiguous()\n bias_ = bias.contiguous()\n output, mean, invvar = fused_layernorm_fast_cuda.forward(\n input_, ctx.normalized_shape, weight_, bias_, ctx.eps)\n ctx.save_for_backward(input_, weight_, bias_, mean, invvar)\n return output\n\n @staticmethod\n def backward(ctx, grad_output):\n input_, weight_, bias_, mean, invvar = ctx.saved_tensors\n grad_input = grad_weight = grad_bias = None\n grad_input = fused_layernorm_fast_cuda.backward(\n grad_output.contiguous(), mean, invvar,\n input_, ctx.normalized_shape,\n weight_, bias_, ctx.eps)\n grad_weight, grad_bias = fused_layernorm_backward_gamma_beta_cuda.backward_gamma_beta(\n grad_output.contiguous(), mean, invvar,\n input_, ctx.normalized_shape,\n weight_, bias_, ctx.eps)\n return grad_input, grad_weight, grad_bias, None, None\n\nclass FusedLayerNorm(torch.nn.Module):\n def __init__(self, normalized_shape, eps=1e-5, elementwise_affine=True):\n super(FusedLayerNorm, self).__init__()\n if isinstance(normalized_shape, numbers.Integral):\n normalized_shape = (normalized_shape,)\n self.normalized_shape = torch.Size(normalized_shape)\n self.eps = eps\n assert elementwise_affine\n self.weight = Parameter(torch.Tensor(*normalized_shape))\n self.bias = Parameter(torch.Tensor(*normalized_shape))\n self.reset_parameters()\n\n def reset_parameters(self):\n init.ones_(self.weight)\n init.zeros_(self.bias)\n\n def forward(self, input):\n if not input.is_cuda:\n return F.layer_norm(\n input, self.normalized_shape, self.weight, self.bias, self.eps)\n return FusedLayerNormFastFunction.apply(\n input, self.weight, self.bias, self.normalized_shape, self.eps)\n\n def extra_repr(self):\n return '{normalized_shape}, eps={eps}, ' \\\n 'elementwise_affine=True'.format(**self.__dict__)\n"
] |
[
[
"torch.Size",
"torch.nn.functional.layer_norm",
"torch.nn.init.ones_",
"torch.nn.init.zeros_",
"torch.Tensor"
]
] |
carterbox/jeweler
|
[
"9f78a2f5580db613f691061c72c4601a1699e76e"
] |
[
"src/jeweler/objective.py"
] |
[
"\"\"\"Defines objective functions for rating codes.\"\"\"\n\nimport numpy as np\n\n__all__ = [\n 'spectral_flatness',\n 'minimal_variance',\n 'coded_factor',\n]\n\n\ndef minimal_variance(code, axis=-1):\n \"\"\"Return an objective function that minimizes variance of the FFT.\n\n We chose a code that (i) maximizes the minimum of the magnitude of the DFT\n values and (ii) minimizes the variance of the magnitude of the DFT values.\n Using a rating parameter, score = magnitude - variance.\n\n References\n ----------\n Raskar, R., Agrawal, A., & Tumblin, J. (2006). Coded exposure photography:\n Motion deblurring using fluttered shutter. Acm Transactions on Graphics,\n 25(3), 795–804. https://doi.org/10.1145/1179352.1141957\n\n \"\"\"\n # TODO: For future 2D arrays use np.fft.rfftn\n dft_mag = np.abs(np.fft.rfft(code, axis=axis))\n return np.min(dft_mag, axis=axis) - np.var(dft_mag, axis=axis)\n\n\ndef spectral_flatness(code, axis=-1):\n \"\"\"Return the spectral flatness of the code. Flat is 1.0. Tonal is 0.0.\n\n The spectral flatness is the geometric mean of the power spectrum divided\n by the arithmetic mean of the power spectrum.\n\n \"\"\"\n dft = np.fft.rfft(code, axis=axis)\n power_spectrum = np.square(np.abs(dft))\n N = power_spectrum.shape[-1]\n return np.prod(power_spectrum, axis=axis)**(1 / N) / np.mean(\n power_spectrum, axis=axis)\n\n\ndef _cui_criterion(code, axis=-1, alpha=[2, 1, 0.075, 0.024]):\n \"\"\"Return the binary fluttering sequence criterion from Cui et al (2021).\n\n References\n ----------\n Cui, Guangmang, Xiaojie Ye, Jufeng Zhao, Liyao Zhu, Ying Chen,\n and Yu Zhang. 2021. “An Effective Coded Exposure Photography Framework\n Using Optimal Fluttering Pattern Generation.” Optics and Lasers in\n Engineering 139 (November 2020): 106489.\n https://doi.org/10.1016/j.optlaseng.2020.106489.\n \"\"\"\n L = code.shape[axis]\n mtf = np.abs(np.fft.rfft(code, axis=axis))\n raise NotImplementedError()\n # FIXME: Signal-to-noise objective requires information about camera\n # P = [1]\n # H = np.sqrt(np.trace(np.inv(P.T @ P)) / L)\n # snr = (I0 * t * R / L) / H * np.sqrt()\n return (\n # minimum MTF amplitude\n + alpha[0] * np.min(mtf, axis=axis)\n # sequence autocorrelation\n + alpha[1] * np.var(L * L / mtf, axis=axis)\n # signal to noise of captured image\n + alpha[2] * snr\n # image low frequency components\n + alpha[3] * np.mean(mtf / np.square(code + 1), axis=axis))\n\n\ndef coded_factor(code, axis=-1, λ=8.5):\n \"\"\"Return the coded factor from Jeon et al (2017).\n\n This coded factor aims to preserve the spatial frequency in a blurred image\n and minimize the variance of the MTF of the code (which is related to the\n deconvolution noise).\n\n It is defined as: (L * L) / var(MTF) + λ min(log(MTF)) where L is the\n length of the code, λ is an arbitrary weighting factor, and MTF is the\n modulation transfer function of the code (the magnitude of the Fourier\n Transform).\n\n References\n ----------\n Jeon, Hae Gon, Joon Young Lee, Yudeog Han, Seon Joo Kim, and In So Kweon.\n 2017. “Generating Fluttering Patterns with Low Autocorrelation for Coded\n Exposure Imaging.” International Journal of Computer Vision 123 (2):\n 1–18. https://doi.org/10.1007/s11263-016-0976-4.\n \"\"\"\n L = code.shape[axis]\n mtf = np.abs(np.fft.rfft(code, axis=axis))\n return L * L / np.var(mtf, axis=axis) + λ * np.min(np.log(mtf), axis=axis)\n"
] |
[
[
"numpy.square",
"numpy.fft.rfft",
"numpy.log",
"numpy.min",
"numpy.mean",
"numpy.prod",
"numpy.abs",
"numpy.var"
]
] |
mehtajinesh/MultipurposeChatBot
|
[
"b51c7f1d91a48cccc3d6f7b9782ec21d0e4fc74b"
] |
[
"rasa_test/share/doc/networkx-2.3/examples/drawing/plot_unix_email.py"
] |
[
"#!/usr/bin/env python\n\"\"\"\n==========\nUnix Email\n==========\n\nCreate a directed graph, allowing multiple edges and self loops, from\na unix mailbox. The nodes are email addresses with links\nthat point from the sender to the receivers. The edge data\nis a Python email.Message object which contains all of\nthe email message data.\n\nThis example shows the power of `DiGraph` to hold edge data\nof arbitrary Python objects (in this case a list of email messages).\n\nThe sample unix email mailbox called \"unix_email.mbox\" may be found here:\nhttps://raw.githubusercontent.com/networkx/networkx/master/examples/drawing/unix_email.mbox\n\n\"\"\"\n# Author: Aric Hagberg (hagberg@lanl.gov)\n\n# Copyright (C) 2005-2019 by\n# Aric Hagberg <hagberg@lanl.gov>\n# Dan Schult <dschult@colgate.edu>\n# Pieter Swart <swart@lanl.gov>\n# All rights reserved.\n# BSD license.\n\nfrom email.utils import getaddresses, parseaddr\nimport mailbox\nimport sys\n\nimport matplotlib.pyplot as plt\nimport networkx as nx\n\n# unix mailbox recipe\n# see https://docs.python.org/3/library/mailbox.html\n\ndef mbox_graph():\n mbox = mailbox.mbox(\"unix_email.mbox\") # parse unix mailbox\n\n G = nx.MultiDiGraph() # create empty graph\n\n # parse each messages and build graph\n for msg in mbox: # msg is python email.Message.Message object\n (source_name, source_addr) = parseaddr(msg['From']) # sender\n # get all recipients\n # see https://docs.python.org/3/library/email.html\n tos = msg.get_all('to', [])\n ccs = msg.get_all('cc', [])\n resent_tos = msg.get_all('resent-to', [])\n resent_ccs = msg.get_all('resent-cc', [])\n all_recipients = getaddresses(tos + ccs + resent_tos + resent_ccs)\n # now add the edges for this mail message\n for (target_name, target_addr) in all_recipients:\n G.add_edge(source_addr, target_addr, message=msg)\n\n return G\n\n\nif __name__ == '__main__':\n\n G = mbox_graph()\n\n # print edges with message subject\n for (u, v, d) in G.edges(data=True):\n print(\"From: %s To: %s Subject: %s\" % (u, v, d['message'][\"Subject\"]))\n\n pos = nx.spring_layout(G, iterations=10)\n nx.draw(G, pos, node_size=0, alpha=0.4, edge_color='r', font_size=16, with_labels=True)\n plt.show()\n"
] |
[
[
"matplotlib.pyplot.show"
]
] |
Helicopt/EOD
|
[
"a45b74430070d82d9248a10fb5e1116bb7ababe1"
] |
[
"eod/__init__.py"
] |
[
"# flake8: noqa F401\nimport os\nimport sys\nimport importlib\n\n\"\"\"Set matplotlib up.\"\"\"\n# Import from third library\nimport matplotlib\n\n__version__ = \"0.0.1\" # Available for other modules to import\n\n# import for register\n\nfrom .commands import *\nfrom .runner import * \nfrom .data import *\nfrom .models import * \nfrom .utils import *\nfrom .plugins import *\nfrom .apis import *\n\nmatplotlib.use('Agg') # Use a non-interactive backend\n\n\ndef import_plugin():\n _PPPATH = 'PLUGINPATH'\n\n if _PPPATH not in os.environ:\n return\n path_list = os.environ[_PPPATH].split(':')\n for path in path_list:\n if path.find('/') >= 0:\n base, module = path.rsplit('/', 1)\n sys.path.insert(0, base)\n importlib.import_module(module)\n else:\n importlib.import_module(path)\n\n\n# import other auxiliary packages\nimport_plugin()\n"
] |
[
[
"matplotlib.use"
]
] |
idamfadilah/belajarpython
|
[
"72c5108a7f44d8b8f33dc5d5b1bd4f8a83f8b811"
] |
[
"kelas_2b/dyning.py"
] |
[
"import sqlite3\nimport csv\nfrom selenium import webdriver \nimport matplotlib.pyplot as plt\nimport requests\n\nclass Dyning(object):\n def __init__(self, kelas, npm, hari):\n self.kelas = kelas\n self.npm = npm\n self.hari = hari\n \n def angkatan(self):\n if len(str(self.npm)) == 7:\n print(self.npm)\n if self.npm[2] == \"8\":\n print(\"Merupakan mahasiswa angkatan 2018\")\n elif self.npm[2] == \"7\":\n print(\"Merupakan mahasiswa angkatan 2017\")\n elif self.npm[2] == \"9\":\n print(\"Merupakan mahasiswa angkatan 2019\")\n else: \n print(\"Merupakan angkatan sebelum 2017\")\n else:\n print(\"cek kembali npm anda\")\n \n\n def jurusan(self):\n if len(self.npm)/2 == 3.5:\n try:\n if self.npm[0] == \"1\":\n print(\"teknik informatika\")\n elif self.npm[0] == \"2\":\n print(\"manajemen informatika\")\n elif self.npm[0] == \"3\":\n print(\"manajemen bisnis\")\n elif self.npm[0] == \"4\":\n print(\"logistik bisnis\")\n except Exception as e:\n print(e)\n else:\n print(\"coba cek ke npm lagi\")\n\n def bacacsv(self):\n with open('kelas_2b/dyning.csv', 'r') as jadwal:\n reader = csv.reader(jadwal)\n for row in reader:\n if str(row[0]) == self.hari:\n if str(row[1]) == self.kelas:\n if len(str(row[1]))%2 == 0:\n try:\n print(\"jadwal\", self.kelas)\n print(\"pada hari\",row[0], \"di kelas\", row[1], \"ada matkul\", row[2],\"pada jam\", row[3])\n except Exception as e:\n print(e)\n print(\"coba cek penulisan kelas kembali\")\n \n def db(self):\n koneksi = sqlite3.connect('kelas_2b/dyning.db')\n cursor = koneksi.cursor()\n cursor.execute('CREATE TABLE IF NOT EXISTS \\\n NILAI_MAHASISWA(NPM INTEGER PRIMARY KEY, Nama TEXT, Kelas TEXT, Nilai REAL)')\n tampil = \"SELECT * FROM NILAI_MAHASISWA \"\n try:\n cursor.execute(\"INSERT INTO NILAI_MAHASISWA VALUES(1184051,'Alifia Zahra', 'D4TI2B', 91)\")\n koneksi.commit()\n except Exception:\n print(\"Recordnya sudah adaa\")\n cursor.execute(tampil)\n results = cursor.fetchall()\n for row in results:\n NPM = row[0]\n Nama = row[1]\n Kelas = row[2]\n Nilai = row[3]\n print (\"NPM %s, dengan nama %s, dari kelas %s, nilainya %s\" % \\\n (NPM, Nama, Kelas, Nilai))\n\n def nilaismt(self):\n print(\"nilai tiap semesternya yaitu\")\n nilaii = [87, 90, 95, 93, 85, 86, 90, 97]\n x = 1\n for i in nilaii:\n if x < 9 :\n print(\"Nilai semester\",x, \"yaitu\", i)\n x = x+1\n def rata(self):\n nilaii = [87, 90, 95, 93, 85, 86, 90, 97]\n x = 0\n if x < 9 :\n try:\n print(\"nilai rata-rata total ialah\",(nilaii[1] + nilaii[0] + nilaii[2]+ nilaii[3]+ nilaii[4]+ nilaii[5]+ nilaii[6]+ nilaii[7])/8)\n except Exception as e:\n print(e)\n \n def grafiknilai(self):\n print(\"Berikut ini merupakan grafik perkembangan nilai tiap semester, tunggu sebentar yaa..\")\n try:\n plt.plot([1,2,3,4,5,6,7,8],[87, 90, 95, 93, 85, 86, 90, 97])\n plt.xlabel('Semester')\n plt.ylabel('Nilai')\n plt.title('Grafik Perkembangan rata-rata nilai tiap semester')\n plt.show()\n except Exception as e:\n print(e)\n def reqq(self):\n req = requests.get('https://id.pinterest.com/aidabatrishya/')\n req.encoding \n req.status_code \n req.elapsed \n req.url \n req.history \n req.headers['Content-Type']\n try:\n print(req.status_code)\n print(req.encoding)\n print(req.headers)\n print(req.url)\n print(req.elapsed)\n print(req.history)\n except Exception as e:\n print(e)\n def login(self): \n self.options = webdriver.ChromeOptions()\n self.options.add_argument(\"--headless\")\n self.driver = webdriver.Chrome(chrome_options=self.options)\n self.driver.get('http://siap.poltekpos.ac.id/siap/besan.depan.php')\n self.driver.find_element_by_name('user_name').send_keys(self.npm)\n self.driver.find_element_by_name('user_pass').send_keys(\"Dyning2902\")\n self.driver.find_element_by_xpath('/html/body/table/tbody/tr[5]/td/table[1]/tbody/tr/td[2]/table[2]/tbody/tr[1]/td[2]/div/form/input[4]').click()\n self.driver.find_element_by_link_text('Ubah Profil').click()\n self.nomer = self.driver.find_element_by_xpath(\"//input[@name='Handphone']\")\n self.nomers = self.nomer.get_attribute('value')\n print(\"Nomor telepon mahasiwa dengan NPM \", self.npm, \"ialah\", self.nomers)\n self.driver.close()\n def jalan(self):\n print(\"Dengan NPM\")\n self.angkatan()\n self.jurusan()\n self.bacacsv()\n self.db()\n self.nilaismt()\n self.rata()\n self.reqq()\n self.login()\n self.grafiknilai()\n "
] |
[
[
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.title",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.show"
]
] |
nick-cheatwood7/spotify-recommend-python
|
[
"5d00756d1d4ff973f74e73841ae5640742c7745e"
] |
[
"src/main.py"
] |
[
"# Import needed packages\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# Import custom module\nimport spotify as sp\n\n\ndef main():\n # Init seaborn\n sns.set()\n\n # Read in data\n data = pd.read_csv(\"./data/tracks.csv\")\n\n # Get metrics on the data\n # data.info()\n\n # Test for empty values\n data.isnull().sum()\n\n # Clean the data\n data[\"name\"].fillna(\"Unknown Title\", inplace=True)\n\n # Test for empty values again\n data.isnull().sum()\n\n # Init the recommender instance\n recommender = sp.SpotifyRecommender(data)\n\n # Get recommendation by Track title\n print(recommender.get_recommendations(\"Re: Stacks\", 20))\n\n # Get recommendation by Track Id\n print(recommender.get_recommendations_byId(\"2LthqyP0MLhGUBICwR1535\", 20))\n\n\nif __name__ == \"__main__\":\n main()\n"
] |
[
[
"pandas.read_csv"
]
] |
rajatvd/rigl
|
[
"59f6e8351177b62a6dabb8303e4cb371d35eb7c9",
"59f6e8351177b62a6dabb8303e4cb371d35eb7c9"
] |
[
"rigl/rigl_tf2/networks.py",
"rigl/sparse_utils_test.py"
] |
[
"# coding=utf-8\n# Copyright 2020 RigL Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Lint as: python3\n\"\"\"This module has networks used in experiments.\n\"\"\"\nfrom typing import Optional, Tuple # Non-expensive-to-import types.\nimport gin\n\nimport tensorflow.compat.v2 as tf\n\n\n@gin.configurable(whitelist=['hidden_sizes', 'use_batch_norm'])\ndef lenet5(input_shape,\n num_classes,\n activation,\n kernel_regularizer,\n use_batch_norm = False,\n hidden_sizes = (6, 16, 120, 84)):\n \"\"\"Lenet5 implementation.\"\"\"\n network = tf.keras.Sequential()\n kwargs = {\n 'activation': activation,\n 'kernel_regularizer': kernel_regularizer,\n }\n def maybe_add_batchnorm():\n if use_batch_norm:\n network.add(tf.keras.layers.BatchNormalization())\n network.add(tf.keras.layers.Conv2D(\n hidden_sizes[0], 5, input_shape=input_shape, **kwargs))\n network.add(tf.keras.layers.MaxPool2D(pool_size=(2, 2)))\n maybe_add_batchnorm()\n network.add(tf.keras.layers.Conv2D(hidden_sizes[1], 5, **kwargs))\n network.add(tf.keras.layers.MaxPool2D(pool_size=(2, 2)))\n maybe_add_batchnorm()\n network.add(tf.keras.layers.Flatten())\n network.add(tf.keras.layers.Dense(hidden_sizes[2], **kwargs))\n maybe_add_batchnorm()\n network.add(tf.keras.layers.Dense(hidden_sizes[3], **kwargs))\n maybe_add_batchnorm()\n kwargs['activation'] = None\n network.add(tf.keras.layers.Dense(num_classes, **kwargs))\n return network\n\n\n@gin.configurable(whitelist=['hidden_sizes', 'use_batch_norm'])\ndef mlp(input_shape,\n num_classes,\n activation,\n kernel_regularizer,\n use_batch_norm = False,\n hidden_sizes = (300, 100)):\n \"\"\"Lenet5 implementation.\"\"\"\n network = tf.keras.Sequential()\n kwargs = {\n 'activation': activation,\n 'kernel_regularizer': kernel_regularizer\n }\n def maybe_add_batchnorm():\n if use_batch_norm:\n network.add(tf.keras.layers.BatchNormalization())\n network.add(tf.keras.layers.Flatten(input_shape=input_shape))\n network.add(tf.keras.layers.Dense(hidden_sizes[0], **kwargs))\n maybe_add_batchnorm()\n network.add(tf.keras.layers.Dense(hidden_sizes[1], **kwargs))\n maybe_add_batchnorm()\n kwargs['activation'] = None\n network.add(tf.keras.layers.Dense(num_classes, **kwargs))\n return network\n",
"# coding=utf-8\n# Copyright 2020 RigL Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Tests for the data_helper input pipeline and the training process.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n\nimport absl.testing.parameterized as parameterized\nimport numpy as np\nfrom rigl import sparse_utils\nimport tensorflow.compat.v1 as tf\n\n\nclass GetMaskRandomTest(tf.test.TestCase, parameterized.TestCase):\n\n def _setup_session(self):\n \"\"\"Resets the graph and returns a fresh session.\"\"\"\n tf.reset_default_graph()\n sess = tf.Session()\n return sess\n\n @parameterized.parameters(((30, 40), 0.5), ((1, 2, 1, 4), 0.8), ((3,), 0.1))\n def testMaskConnectionDeterminism(self, shape, sparsity):\n sess = self._setup_session()\n mask = tf.ones(shape)\n mask1 = sparse_utils.get_mask_random(mask, sparsity, tf.int32)\n mask2 = sparse_utils.get_mask_random(mask, sparsity, tf.int32)\n mask1_array, = sess.run([mask1])\n mask2_array, = sess.run([mask2])\n self.assertEqual(np.sum(mask1_array), np.sum(mask2_array))\n\n @parameterized.parameters(((30, 4), 0.5, 60), ((1, 2, 1, 4), 0.8, 1),\n ((30,), 0.1, 27))\n def testMaskFraction(self, shape, sparsity, expected_ones):\n sess = self._setup_session()\n mask = tf.ones(shape)\n mask1 = sparse_utils.get_mask_random(mask, sparsity, tf.int32)\n mask1_array, = sess.run([mask1])\n\n self.assertEqual(np.sum(mask1_array), expected_ones)\n\n @parameterized.parameters(tf.int32, tf.float32, tf.int64, tf.float64)\n def testMaskDtype(self, dtype):\n _ = self._setup_session()\n mask = tf.ones((3, 2))\n mask1 = sparse_utils.get_mask_random(mask, 0.5, dtype)\n self.assertEqual(mask1.dtype, dtype)\n\n\nclass GetSparsitiesTest(tf.test.TestCase, parameterized.TestCase):\n\n def _setup_session(self):\n \"\"\"Resets the graph and returns a fresh session.\"\"\"\n tf.reset_default_graph()\n sess = tf.Session()\n return sess\n\n @parameterized.parameters(0., 0.4, 0.9)\n def testSparsityDictRandom(self, default_sparsity):\n _ = self._setup_session()\n all_masks = [tf.get_variable(shape=(2, 3), name='var1/mask'),\n tf.get_variable(shape=(2, 3), name='var2/mask'),\n tf.get_variable(shape=(1, 1, 3), name='var3/mask')]\n custom_sparsity = {'var1': 0.8}\n sparsities = sparse_utils.get_sparsities(\n all_masks, 'random', default_sparsity, custom_sparsity)\n self.assertEqual(sparsities[all_masks[0].name], 0.8)\n self.assertEqual(sparsities[all_masks[1].name], default_sparsity)\n self.assertEqual(sparsities[all_masks[2].name], default_sparsity)\n\n @parameterized.parameters(0.1, 0.4, 0.9)\n def testSparsityDictErdosRenyiCustom(self, default_sparsity):\n _ = self._setup_session()\n all_masks = [tf.get_variable(shape=(2, 4), name='var1/mask'),\n tf.get_variable(shape=(2, 3), name='var2/mask'),\n tf.get_variable(shape=(1, 1, 3), name='var3/mask')]\n custom_sparsity = {'var3': 0.8}\n sparsities = sparse_utils.get_sparsities(\n all_masks, 'erdos_renyi', default_sparsity, custom_sparsity)\n self.assertEqual(sparsities[all_masks[2].name], 0.8)\n\n @parameterized.parameters(0.1, 0.4, 0.9)\n def testSparsityDictErdosRenyiError(self, default_sparsity):\n _ = self._setup_session()\n all_masks = [tf.get_variable(shape=(2, 4), name='var1/mask'),\n tf.get_variable(shape=(2, 3), name='var2/mask'),\n tf.get_variable(shape=(1, 1, 3), name='var3/mask')]\n custom_sparsity = {'var3': 0.8}\n sparsities = sparse_utils.get_sparsities(\n all_masks, 'erdos_renyi', default_sparsity, custom_sparsity)\n self.assertEqual(sparsities[all_masks[2].name], 0.8)\n\n @parameterized.parameters(((2, 3), (2, 3), 0.5),\n ((1, 1, 2, 3), (1, 1, 2, 3), 0.3),\n ((8, 6), (4, 3), 0.7),\n ((80, 4), (20, 20), 0.8),\n ((2, 6), (2, 3), 0.8))\n def testSparsityDictErdosRenyiSparsitiesScale(\n self, shape1, shape2, default_sparsity):\n _ = self._setup_session()\n all_masks = [tf.get_variable(shape=shape1, name='var1/mask'),\n tf.get_variable(shape=shape2, name='var2/mask')]\n custom_sparsity = {}\n sparsities = sparse_utils.get_sparsities(\n all_masks, 'erdos_renyi', default_sparsity, custom_sparsity)\n sparsity1 = sparsities[all_masks[0].name]\n size1 = np.prod(shape1)\n sparsity2 = sparsities[all_masks[1].name]\n size2 = np.prod(shape2)\n # Ensure that total number of connections are similar.\n expected_zeros_uniform = (\n sparse_utils.get_n_zeros(size1, default_sparsity) +\n sparse_utils.get_n_zeros(size2, default_sparsity))\n # Ensure that total number of connections are similar.\n expected_zeros_current = (\n sparse_utils.get_n_zeros(size1, sparsity1) +\n sparse_utils.get_n_zeros(size2, sparsity2))\n # Due to rounding we can have some difference. This is expected but should\n # be less than number of rounding operations we make.\n diff = abs(expected_zeros_uniform - expected_zeros_current)\n tolerance = 2\n self.assertLessEqual(diff, tolerance)\n\n # Ensure that ErdosRenyi proportions are preserved.\n factor1 = (shape1[-1] + shape1[-2]) / float(shape1[-1] * shape1[-2])\n factor2 = (shape2[-1] + shape2[-2]) / float(shape2[-1] * shape2[-2])\n self.assertAlmostEqual((1 - sparsity1) / factor1,\n (1 - sparsity2) / factor2)\n\n\nif __name__ == '__main__':\n tf.test.main()\n"
] |
[
[
"tensorflow.compat.v2.keras.layers.MaxPool2D",
"tensorflow.compat.v2.keras.layers.Dense",
"tensorflow.compat.v2.keras.layers.Flatten",
"tensorflow.compat.v2.keras.Sequential",
"tensorflow.compat.v2.keras.layers.Conv2D",
"tensorflow.compat.v2.keras.layers.BatchNormalization"
],
[
"tensorflow.compat.v1.get_variable",
"numpy.sum",
"tensorflow.compat.v1.Session",
"numpy.prod",
"tensorflow.compat.v1.reset_default_graph",
"tensorflow.compat.v1.test.main",
"tensorflow.compat.v1.ones"
]
] |
markpp/pl_bolts
|
[
"d11b684b9c03dd6ab9dedae034fdf39cf0b8c63f"
] |
[
"datamodules/sewer_datamodule.py"
] |
[
"import torch\nfrom torch.utils.data import DataLoader\nimport torchvision\nimport pytorch_lightning as pl\n\nimport os, sys\n\nsys.path.append('../')\n\nclass SewerDataModule(pl.LightningDataModule):\n def __init__(self, data_dir, dataset, batch_size, image_size, in_channels, n_workers):\n super().__init__()\n self.data_dir = data_dir\n self.dataset = dataset\n self.batch_size = batch_size\n self.image_size = image_size\n self.in_channels = in_channels\n self.n_workers = n_workers\n\n def setup(self, stage=None):\n from transforms.augmentation import basic_augmentation\n\n if stage == 'fit' or stage is None:\n '''\n #from datasets.sewer_dataset import SewerImageDataset\n self.data_train = SewerImageDataset(root_dir=os.path.join(self.data_dir,self.dataset),\n transform=basic_augmentation(img_height=self.image_size,\n img_width=self.image_size,\n img_pad=30,\n in_channels=self.in_channels))\n self.data_val = SewerImageDataset(root_dir=os.path.join(self.data_dir,'validation'),\n transform=basic_augmentation(img_height=self.image_size,\n img_width=self.image_size,\n in_channels=self.in_channels))\n '''\n from datasets.sewer_dataset import SewerLabelDataset\n self.data_train = SewerLabelDataset(root_dir=self.data_dir,\n dataset=self.dataset,\n transform=basic_augmentation(img_height=self.image_size,\n img_width=self.image_size,\n img_pad=30,\n in_channels=self.in_channels))\n self.data_val = SewerLabelDataset(root_dir=self.data_dir,\n dataset='validation',\n transform=basic_augmentation(img_height=self.image_size,\n img_width=self.image_size,\n in_channels=self.in_channels))\n\n def train_dataloader(self):\n return DataLoader(self.data_train, batch_size=self.batch_size, num_workers=self.n_workers, pin_memory=True, shuffle=True)\n\n def val_dataloader(self):\n return DataLoader(self.data_val, batch_size=self.batch_size, num_workers=self.n_workers, pin_memory=True, shuffle=False)\n\n\nif __name__ == '__main__':\n\n import cv2\n from transforms.normalization import denormalize\n\n\n dm = SewerDataModule(data_dir='/home/aau/github/data/sewer/paper/',\n dataset='mlp',\n batch_size=16,\n image_size=144,\n in_channels=3,\n n_workers=1)\n\n dm.setup()\n\n # cleanup output dir\n import os, shutil\n output_root = \"output/\"\n if os.path.exists(output_root):\n shutil.rmtree(output_root)\n os.makedirs(output_root)\n\n sample_idx = 0\n for batch_id, batch in enumerate(dm.train_dataloader()):\n if len(batch) == 1: # images\n imgs = batch\n for img in imgs:\n img = denormalize(img).mul(255).permute(1, 2, 0).byte().numpy()\n img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)\n output_dir = os.path.join(output_root,str(batch_id).zfill(6))\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n filename = \"id-{}.png\".format(str(sample_idx).zfill(6))\n cv2.imwrite(os.path.join(output_dir,filename),img)\n sample_idx = sample_idx + 1\n else:\n imgs, labels = batch\n for img, label in zip(imgs,labels):\n img = denormalize(img).mul(255).permute(1, 2, 0).byte().numpy()\n img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)\n label = label.numpy()\n cv2.putText(img,\"label: {:.2f}\".format(label), (5, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,0), 2)\n output_dir = os.path.join(output_root,str(batch_id).zfill(6))\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n filename = \"id-{}.png\".format(str(sample_idx).zfill(6))\n cv2.imwrite(os.path.join(output_dir,filename),img)\n sample_idx = sample_idx + 1\n if batch_id > 1:\n break\n '''\n else: # image pairs\n imgs, imgs_ = batch\n for img, img_ in zip(imgs,imgs_):\n img = img.mul(255).permute(1, 2, 0).byte().numpy()\n img_ = img_.mul(255).permute(1, 2, 0).byte().numpy()\n output_dir = os.path.join(output_root,str(batch_id).zfill(6))\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n filename = \"id-{}.png\".format(str(sample_idx).zfill(6))\n cv2.imwrite(os.path.join(output_dir,filename),img[:,:,0])\n filename = \"id-{}_.png\".format(str(sample_idx).zfill(6))\n cv2.imwrite(os.path.join(output_dir,filename),img_[:,:,0])\n sample_idx = sample_idx + 1\n '''\n"
] |
[
[
"torch.utils.data.DataLoader"
]
] |
justinhchae/app_courts
|
[
"c46d48c4fa02cec91bda6fc3818ab677d6a83281"
] |
[
"analyze_data/network.py"
] |
[
"import numpy as np\nimport pandas as pd\nimport sidetable\n\nimport plotly.graph_objects as go\nimport plotly_express as px\nfrom plotly.subplots import make_subplots\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom clean_data.cleaner import Cleaner\nfrom do_data.getter import Reader\nfrom do_data.writer import Writer\nfrom do_data.config import Columns\nname = Columns()\n\n# from pandasgui import show\nfrom analyze_data.colors import Colors\nfrom scipy import stats\n\nimport networkx as nx\n\nfrom collections import Counter\nimport math\nfrom sklearn import preprocessing\n\ncolors = Colors()\n\nclass Network():\n def __init__(self):\n self.G = nx.DiGraph()\n self.hubs = None\n self.blue = '#1f77b4' # muted blue\n self.orange = '#ff7f0e' # safety orange\n self.green = '#2ca02c' # cooked asparagus green\n self.red = '#d62728' # brick red\n self.purple = '#9467bd' # muted purple\n self.brown = '#8c564b' # chestnut brown\n self.pink = '#e377c2' # raspberry yogurt pink\n self.gray = '#7f7f7f' # middle gray\n self.yellow_green = '#bcbd22' # curry yellow-green\n self.teal = '#17becf'\n\n self.sentence_color = {\n 'Prison': self.red\n , 'Conversion': self.blue\n , 'Probation': self.blue\n , 'Jail': self.red\n , 'Conditional Discharge': self.green\n , 'Supervision': self.blue\n , 'Cook County Boot Camp': self.green\n , 'Probation Terminated Satisfactorily': self.green\n , 'Inpatient Mental Health Services': self.blue\n , 'Death': self.red\n , 'Conditional Release': self.green\n , 'Probation Terminated Instanter': self.orange\n , 'Probation Terminated Unsatisfactorily': self.orange\n , '2nd Chance Probation': self.orange\n }\n\n def ingest_df(self, df, filename):\n self.G.clear()\n judge_df = df.groupby(name.sentence_judge)\n edges = []\n counter = 0\n # df['sentence_color'] = df[name.sentence_type].apply(lambda x: self.sentence_color[x])\n df['sentence_color'] = df[name.sentence_type].cat.codes\n scaler = preprocessing.MinMaxScaler(feature_range=(.5, 15.))\n\n # https://towardsdatascience.com/data-normalization-with-pandas-and-scikit-learn-7c1cc6ed6475\n df['scaled_commitment_days'] = pd.DataFrame(scaler.fit_transform(df[[name.commitment_days]]))\n\n self.hubs = list(df[name.sentence_court_name].unique())\n sentence_types = list(df[name.sentence_type].unique())\n sentence_facs = list(df[name.sentence_court_facility].unique())\n mean_scaled_commitment_days = []\n self.hubs.extend(sentence_types)\n self.hubs.extend(sentence_facs)\n self.hubs = list(set(self.hubs))\n self.hubs.remove(np.nan)\n self.hubs.sort()\n\n for df1_name, df1 in judge_df:\n counter +=1\n\n if len(df1) > 0:\n n_cases = len(df1)\n node_record = tuple((df1_name, {'n_cases':n_cases}))\n self.G.add_nodes_from([node_record])\n court_df = df1.groupby(name.sentence_court_name)\n\n for df2_name, df2 in court_df:\n df2[name.sentence_court_facility] = df2[name.sentence_court_facility].cat.remove_unused_categories()\n\n if len(df2) > 0:\n n_cases = len(df2)\n node_record = tuple((df2_name, {'n_cases': n_cases}))\n self.G.add_nodes_from([node_record])\n fac_df = df2.groupby(name.sentence_court_facility)\n\n for df3_name, df3 in fac_df:\n df3[name.sentence_court_name] = df2[name.sentence_court_name].cat.remove_unused_categories()\n\n if len(df3) > 0:\n # nx.add_path(self.G, [df1_name, df3_name, df2_name])\n sentence_df = df3.groupby(name.sentence_type)\n n_cases = len(df3)\n node_record = tuple((df3_name, {'n_cases': n_cases}))\n self.G.add_nodes_from([node_record])\n\n for df4_name, df4 in sentence_df:\n df4[name.sentence_type] = df4[name.sentence_type].cat.remove_unused_categories()\n\n if len(df4) > 0:\n n_cases = len(df4)\n node_record = tuple((df4_name, {'n_cases': n_cases}))\n self.G.add_nodes_from([node_record])\n color = df4['sentence_color'].unique()[0]\n msc_day = df4['scaled_commitment_days'].fillna(0).median()\n n_cases = len(df4)\n nx.add_path(self.G, [df1_name, df3_name, df2_name, df4_name]\n , color=color\n , label=df4_name\n , msc_day=msc_day\n , judge=df1_name\n , n_cases=n_cases\n )\n\n if filename:\n saved_name = str('data/'+filename+'.gpickle')\n nx.write_gpickle(self.G, saved_name, protocol=2)\n\n def graph_network(self, df=None, filename=None):\n\n if filename:\n read_name = str('data/'+filename+'.gpickle')\n self.G = nx.read_gpickle(read_name)\n\n if df is not None:\n self.hubs = list(df[name.sentence_court_name].unique())\n self.types = list(set(df[name.sentence_type].unique()))\n sentence_facs = list(df[name.sentence_court_facility].unique())\n mean_scaled_commitment_days = []\n # self.hubs.extend(sentence_types)\n # self.hubs.extend(sentence_facs)\n self.hubs = list(set(self.hubs))\n self.hubs.remove(np.nan)\n self.hubs.sort()\n self.judges = list(set(df[name.sentence_judge].unique()))\n self.judges.remove(np.nan)\n\n d = dict(self.G.degree)\n pos = nx.spring_layout(self.G, k=5 / math.sqrt(self.G.order()), seed=0)\n\n node_values = np.array([v for v in d.values()]).reshape(-1, 1)\n scaler = preprocessing.MinMaxScaler(feature_range=(5, 30))\n scaled_node_values = scaler.fit_transform(node_values)\n vmin = min(scaled_node_values)\n vmax = max(scaled_node_values)\n\n # colors = [self.G[u][v]['color'] for u, v in self.G.edges()]\n edge_values = [self.G[n1][n2]['color'] for n1, n2 in self.G.edges()]\n edge_vmin = min(edge_values)\n edge_vmax = max(edge_values)\n\n plt.figure(figsize=(10, 10))\n\n labels = {}\n for node in self.G.nodes():\n if node in self.hubs:\n labels[node] = node\n\n nx.draw_networkx_nodes(self.G\n , cmap=plt.get_cmap('coolwarm')\n , node_color=scaled_node_values\n , pos=pos\n , vmin=vmin\n , vmax=vmax\n , node_size=scaled_node_values\n , label=False\n )\n\n edge_widths=[self.G[n1][n2]['msc_day'] for n1, n2 in self.G.edges()]\n\n nx.draw_networkx_edges(self.G\n , edge_cmap=plt.get_cmap('tab20')\n , pos=pos\n , width=edge_widths\n , alpha =.8\n , edge_vmin=edge_vmin\n , edge_vmax=edge_vmax\n , edge_color=edge_values\n )\n\n edge_labels = nx.get_edge_attributes(self.G, 'label')\n\n # nx.draw_networkx_edge_labels(self.G\n # , pos=pos\n # , edge_labels=edge_labels\n # , font_size=4\n # )\n\n nx.draw_networkx_labels(self.G\n , pos=pos\n , labels=labels\n , font_size=8\n , font_color='black'\n , font_weight='medium'\n )\n # plt.show()\n\n return self.G, pos, edge_widths, scaled_node_values, self.hubs, self.judges, self.types\n\n\n def make_network(self):\n # neo 4 j\n\n # https://stackoverflow.com/questions/44611449/cannot-create-a-directed-graph-using-from-pandas-dataframe-from-networkx\n # types https://networkx.org/documentation/stable//reference/drawing.html\n \"\"\"\n https://stackoverflow.com/questions/45350222/select-nodes-and-edges-form-networkx-graph-with-attributes\n selected_nodes = [n for n, v in G.nodes(data=True) if v['ej_status'] == 'EM']\n print(selected_nodes)\n\n https://stackoverflow.com/questions/13517614/draw-different-color-for-nodes-in-networkx-based-on-their-node-value\n\n \"\"\"\n\n G = nx.DiGraph()\n H = nx.DiGraph()\n\n df = pd.read_csv('data/testing.csv', index_col=0)\n df = df[df['ir'] != 'NOT ASSIGNED.']\n df = df.dropna(subset=['ir'])\n\n df = df[(df['detainee_status_date']=='2020-07-15') | (df['detainee_status_date']=='2020-06-30')]\n df['detainee_status_date'] = pd.to_datetime(df['detainee_status_date'])\n\n df = df.groupby('ir')\n\n attrs = {}\n nodes = []\n seen_nodes = []\n edges = []\n node = []\n weight = 0\n person_records = []\n path_records = []\n\n counter = 0\n\n for ir, node_df in df:\n counter +=1\n\n person_record = tuple((ir, node_df))\n G.add_nodes_from([person_record])\n\n edge_df = node_df.groupby('detainee_status_date')\n\n for detainee_status_date, status_df in edge_df:\n\n status_record = tuple(zip(status_df['ej_status'], status_df['detainee_status']))[0]\n edges.append(status_record)\n\n if 'Jail' in status_record[0]:\n G.add_edge(ir, status_record, color='tomato')\n elif 'Out' in status_record[0]:\n G.add_edge(ir, status_record, color='mediumseagreen')\n elif 'EM' in status_record[0]:\n G.add_edge(ir, status_record, color='gold')\n else:\n G.add_edge(ir, status_record, color='gray')\n\n if counter == 1000:\n break\n\n test_time = np.datetime64('2020-07-15')\n # selected_edges = [(u,v) for u,v,e in G.edges(data=True) if e['status_date'] == test_time]\n # print(selected_edges)\n\n # test = G.nodes(data=True)['1000878']\n\n # print(G.nodes['1000878'])\n\n # test_nodes = [(x, y) for x, y in G.nodes(data=True)]\n # print(test_nodes)\n\n\n d = dict(G.degree)\n hubs = list(set(edges))\n # pos = nx.circular_layout(G)\n # https://stackoverflow.com/questions/34630621/how-do-i-draw-non-overlapping-edge-labels-in-networkx\n pos = nx.spring_layout(G, k=7/math.sqrt(G.order()), seed=42)\n\n # plt.figure(figsize=(10, 10))\n # nx.draw(G, pos=pos, with_labels=True)\n # plt.tight_layout()\n # plt.show()\n\n values = np.array([v for v in d.values()]).reshape(-1,1)\n scaler = preprocessing.MinMaxScaler(feature_range=(5, 1000))\n # https://towardsdatascience.com/data-normalization-with-pandas-and-scikit-learn-7c1cc6ed6475\n scaled_values = scaler.fit_transform(values)\n # print(test.ravel())\n\n colors = [G[u][v]['color'] for u, v in G.edges()]\n\n plt.figure(figsize=(10, 10))\n # https://stackoverflow.com/questions/14665767/networkx-specific-nodes-labeling\n labels = {}\n for node in G.nodes():\n if node in hubs:\n # set the node name as the key and the label as its value\n labels[node] = node\n # set the argument 'with labels' to False so you have unlabeled graph\n nx.draw(G, with_labels=False, pos=pos\n , node_size=scaled_values\n , edge_color=colors)\n # Now only add labels to the nodes you require (the hubs in my case)\n nx.draw_networkx_labels(G, pos, labels, font_size=10, font_color='black')\n plt.show()\n\n G.clear()\n\n\n # G.add_nodes_from(person_records)\n\n # G.add_edge('1000878', tuple(('Jail', 'Penitentiary Hold')))\n\n # print(G.edges())\n\n # print(G.nodes['1000878']['detainee_status'])\n\n\n\n # for df1_name, df1 in df:\n # df2 = df1.groupby('ej_status')\n #\n # for df2_name, df3 in df2:\n # df4 = df3.groupby('detainee_status')\n #\n # for df4_name, df4 in df4:\n # df5 = df4.groupby('ir')\n #\n # for node_id, df6 in df5:\n # # node_name = str('n'+ node_id)\n #\n # records = df6[['detainee_status_date', 'ej_status', 'detainee_status']].to_dict('records')\n #\n # if node_id in seen_nodes:\n # for i in nodes:\n # if node_id == i[0]:\n #\n # ## working with dicts\n # # p1 = [x for x in i[1][node_id]][0]['ej_status']\n # # p1_status = [x for x in i[1][node_id]][0]['detainee_status']\n # # p2 = records[0]['ej_status']\n # # p2_date = records[0]['detainee_status_date']\n # # p2_status = records[0]['detainee_status']\n #\n # ## working with dfs\n #\n # # if p1 == 'Out' and p2 == 'Out':\n # # path = tuple((p1, p2))\n # #\n # # elif p1 == 'Out':\n # # path = tuple((p1, (p2, p2_status)))\n # #\n # # elif p2 == 'Out':\n # # path = tuple(((p1, p1_status), p2))\n # #\n # # else:\n # # path = tuple(((p1, p1_status), (p2, p2_status)))\n # #\n # # edges.append(path)\n #\n # try:\n # i[1][node_id].append(df6)\n # print(i[1][node_id])\n # except:\n # print('error', node_id, df6)\n #\n # else:\n # ## working with dicts\n # # node = tuple((node_id, {node_id: records}))\n #\n # ## working with dfs\n #\n # node = tuple((node_id, {node_id: df6}))\n # nodes.append(node)\n # seen_nodes.append(node_id)\n # # break\n # # break\n # # break\n\n # G.add_nodes_from(nodes)\n\n # print(G.nodes['1170077'])\n\n # weighted_edges = list(Counter(edges).items())\n\n # weighted_edges = [tuple((lis[0][0], lis[0][1], lis[1])) for lis in weighted_edges]\n\n # H.add_weighted_edges_from(weighted_edges)\n\n # for i in nodes:\n # print(i)\n\n # print(G.edges())\n\n # selected_nodes = [n for n, v in G.nodes(data=True)]\n # print(len(selected_nodes))\n # print(nodes[0])\n\n # new = {'detainee_status': 'Something Else', 'detainee_status_date': '2020-06-30', 'ej_status': 'Jail'}\n\n # print([i['n1163614']['1163614'] for i in nodes if 'n1163614' in i][0])\n\n # for i in nodes:\n # if 'n1163614' in i:\n # old = i['n1163614']['1163614']\n # old.append(new)\n # i.update({'n1163614':old})\n\n # d = dict(H.degree)\n\n # values = [d.get(node, 0.25) for node in H.nodes()]\n\n # pos=nx.circular_layout(H)\n # pos=nx.spring_layout(H, k=5.)\n # cmap=plt.get_cmap('nipy_spectral')\n\n\n\n # vmin = min(values)\n # vmax = max(values)\n #\n # for edge in G.edges():\n # # print(H.nodes[0])\n # print(G.nodes[edge[0]])\n #\n # break\n\n # plt.figure(figsize=(10, 8))\n # plt.title('Prototype Model EM-Jail Flow (2021-01-15)\\nGiven a Roster of EM and Jail Populations by IR, Date, and Detainee Status')\n # nx.draw(H\n # , with_labels=True\n # , pos=pos\n # , node_size=[v * 100 for v in d.values()]\n # , cmap=cmap\n # , node_color=values\n # )\n #\n # # https://stackoverflow.com/questions/26739248/how-to-add-a-simple-colorbar-to-a-network-graph-plot-in-python\n # # https://stackoverflow.com/questions/33737427/top-label-for-matplotlib-colorbars/33740567\n # sm = plt.cm.ScalarMappable(cmap=cmap, norm=plt.Normalize(vmin=vmin, vmax=vmax))\n # sm._A = []\n # cbar = plt.colorbar(sm)\n # cbar.ax.set_ylabel('Normalized Count of Population Movement Destinations')\n #\n # plt.savefig('figures/em_jail_flow.png')\n # plt.show()\n\n # edge_x = []\n # edge_y = []\n # for edge in H.edges():\n # x0, y0 = H.nodes[edge[0]]['pos']\n # x1, y1 = H.nodes[edge[1]]['pos']\n # edge_x.append(x0)\n # edge_x.append(x1)\n # edge_x.append(None)\n # edge_y.append(y0)\n # edge_y.append(y1)\n # edge_y.append(None)\n #\n # edge_trace = go.Scatter(\n # x=edge_x, y=edge_y,\n # line=dict(width=0.5, color='#888'),\n # hoverinfo='none',\n # mode='lines')\n #\n # node_x = []\n # node_y = []\n # for node in H.nodes():\n # x, y = H.nodes[node]['pos']\n # node_x.append(x)\n # node_y.append(y)\n #\n # node_trace = go.Scatter(\n # x=node_x, y=node_y,\n # mode='markers',\n # hoverinfo='text',\n # marker=dict(\n # showscale=True,\n # # colorscale options\n # # 'Greys' | 'YlGnBu' | 'Greens' | 'YlOrRd' | 'Bluered' | 'RdBu' |\n # # 'Reds' | 'Blues' | 'Picnic' | 'Rainbow' | 'Portland' | 'Jet' |\n # # 'Hot' | 'Blackbody' | 'Earth' | 'Electric' | 'Viridis' |\n # colorscale='YlGnBu',\n # reversescale=True,\n # color=[],\n # size=10,\n # colorbar=dict(\n # thickness=15,\n # title='Node Connections',\n # xanchor='left',\n # titleside='right'\n # ),\n # line_width=2))\n\n # https://stackoverflow.com/questions/16566871/node-size-dependent-on-the-node-degree-on-networkx\n\n # plt.figure(figsize=(10, 8))\n # nx.draw(H, nodelist=d.keys(), node_size=[v * 100 for v in d.values()])\n # plt.show()\n\n # print(G.nodes())\n\n import gc\n del G\n del H\n gc.collect()\n\n\n\n\n # G = nx.Graph()\n # time1 = pd.to_datetime('2020-05-13')\n # time2 = pd.to_datetime('2020-06-30')\n\n # print(df)\n\n # G = nx.from_pandas_edgelist(df, 'ir', 'ej_status', create_using=nx.DiGraph())\n #\n # plt.figure(figsize=(10, 8))\n # nx.draw(G, with_labels=True, pos=nx.spring_layout(G))\n # plt.show()\n # print(G.edges())\n\n # edges = pd.DataFrame({'source': [0, 1],\n # 'target': [1, 2],\n # 'weight': [100, 50]})\n #\n # nodes = pd.DataFrame({'node': [0, 1, 2],\n # 'name': ['Foo', 'Bar', 'Baz'],\n # 'gender': ['M', 'F', 'M']})\n #\n # G = nx.from_(edges, 'source', 'target', 'weight')\n\n\n def organize(self):\n df = pd.read_csv('data/em_testing.csv')\n\n df = df[df['ir'] != 'NOT ASSIGNED.']\n df = df.dropna(subset=['ir'])\n\n df['detainee_status'] = df['detainee_status'].str.title()\n cols = ['ir', 'detainee_status', 'ej_status']\n df[cols] = df[cols].astype('category')\n df['detainee_status_date'] = pd.to_datetime(df['detainee_status_date'])\n\n status_col = df[['detainee_status', 'detainee_status_date', 'ir']].copy()\n\n df = df.pivot(index=['ir'], columns=['detainee_status_date'], values=['ej_status'])\n df.columns = df.columns.get_level_values(1)\n df = df.fillna(value='Out')\n\n df = df.unstack().reset_index(name='ej_status')\n\n df = pd.merge(df, status_col, how='left', on=['ir', 'detainee_status_date'])\n\n df['detainee_status'].cat.add_categories(['None'], inplace=True)\n df['detainee_status'].fillna('None', inplace=True)\n df['detainee_status'].cat.remove_categories(np.nan, inplace=True)\n\n df = df[['ir', 'detainee_status', 'detainee_status_date', 'ej_status']]\n\n df = df.sort_values(by=['detainee_status_date'])\n\n df = df.reset_index(drop=True)\n\n df = self.length_of_stay(df)\n\n self.df = df\n\n self.df.to_csv('data/testing.csv')\n\n def length_of_stay(self, df):\n\n grouped = df.groupby('ir')\n\n frames = []\n\n for ir, df1 in grouped:\n df1['status_length'] = (\n df1['detainee_status_date'] - df1['detainee_status_date'].shift()).fillna(\n pd.Timedelta(seconds=0))\n\n frames.append(df1)\n\n df = pd.concat(frames)\n\n return df\n\n"
] |
[
[
"pandas.to_datetime",
"pandas.Timedelta",
"pandas.merge",
"matplotlib.pyplot.get_cmap",
"matplotlib.pyplot.figure",
"sklearn.preprocessing.MinMaxScaler",
"pandas.concat",
"matplotlib.pyplot.show",
"pandas.read_csv",
"numpy.datetime64"
]
] |
SuccessMary/graduation
|
[
"0c63d21386442b4b4a1c10e7ddf91da73f723ce8"
] |
[
"core/test.py"
] |
[
"\"\"\"Test script to classify target data.\"\"\"\r\n\r\nimport torch\r\nimport torch.nn as nn\r\n\r\nfrom utils import make_variable\r\nimport params\r\n\r\n\r\ndef eval_tgt(encoder, classifier, data_loader):\r\n \"\"\"Evaluation for target encoder by source classifier on target dataset.\"\"\"\r\n # set eval state for Dropout and BN layers\r\n encoder.eval()\r\n classifier.eval()\r\n\r\n # init loss and accuracy\r\n # loss = 0\r\n # acc = 0\r\n loss1 = 0\r\n loss2 = 0\r\n loss3 = 0\r\n acc1 = 0\r\n acc2 = 0\r\n acc3 = 0\r\n\r\n # set loss function\r\n # criterion = nn.CrossEntropyLoss()\r\n #my\r\n criterion = nn.MSELoss(reduce=True, size_average=True)\r\n\r\n # evaluate network\r\n for (images, labels) in data_loader:\r\n images = make_variable(images, volatile=True) #为True表示不需要反向传播\r\n labels = make_variable(labels) #.squeeze_()\r\n # print('标签:',labels)\r\n\r\n preds = classifier(encoder(images))\r\n\r\n # print('预测值是:',preds)\r\n # loss += criterion(preds, labels).item()\r\n # print('loss:',loss)\r\n loss1 += criterion(preds[:,0], labels[:,0]).item()\r\n loss2 += criterion(preds[:,1], labels[:,1]).item()\r\n loss3 += criterion(preds[:,2], labels[:,2]).item()\r\n\r\n\r\n # pred_cls = preds.data.max(1)[1]\r\n # acc += pred_cls.eq(labels.data).cpu().sum()\r\n # acc += ((preds - labels) ** 2).cpu().sum()\r\n # print('acc:',acc)\r\n acc1 += ((preds[:,0] - labels[:,0]) ** 2).cpu().sum()\r\n acc2 += ((preds[:,1] - labels[:,1]) ** 2).cpu().sum()\r\n acc3 += ((preds[:,2] - labels[:,2]) ** 2).cpu().sum()\r\n\r\n\r\n # loss /= len(data_loader)\r\n # acc /= len(data_loader.dataset)\r\n loss1 /= len(data_loader)\r\n loss2 /= len(data_loader)\r\n loss3 /= len(data_loader)\r\n acc1 /= len(data_loader.dataset)\r\n acc2 /= len(data_loader.dataset)\r\n acc3 /= len(data_loader.dataset)\r\n\r\n\r\n # print(\"Avg Loss = {}, Avg Accuracy = {}\".format(loss, acc**0.5))\r\n print('Avg loss1: {}, Avg loss2: {}, Avg loss3: {}'.format(loss1,loss2,loss3))\r\n print('Avg Acc1: {}, Avg Acc2: {}, Avg Acc3: {}'.format(acc1, acc2, acc3))\r\n"
] |
[
[
"torch.nn.MSELoss"
]
] |
WayGang/DataMining_IMDB_movies
|
[
"cedc7c3f6c1a1e8aa8b1741da2c9e650055d04de"
] |
[
"kmeans.py"
] |
[
"# Copyright2019 Gang Wei wg0502@bu.edu\n\nimport random\nfrom copy import deepcopy\nimport numpy as np\nimport time\nfrom numpy.random import choice\n\n\ndef getCluster(X, U):\n \"\"\"\n :param X: X is a set of x\n :param u: u is a set of u\n :return: [category,category,....]\n \"\"\"\n error = 0\n\n # allocate = [0] * len(X)\n x_in_k = {}\n for i in range(len(U)):\n x_in_k[i] = []\n for n in range(len(X)): # Traverse all n points\n curr_min_d = 9999\n closest = '#'\n for k in range(len(U)): # Traverse all k centers\n # d = np.sum([np.sum(np.square(np.array(X[n][i]) - np.array(U[k][i]))) for i in range(len(U[k]))])\n d = sum([getDistance(X[n][i], U[k][i]) for i in range(len(U[k]))]) # calculate d\n if d < curr_min_d:\n curr_min_d = d\n closest = k\n # allocate[n] = k\n x_in_k[closest].append(X[n])\n error += curr_min_d\n error /= len(X[0])\n for i in range(len(U)):\n if not x_in_k[i]:\n x_in_k[i].append(x_in_k[0].pop())\n return x_in_k, error\n # return allocate, error\n\n\ndef iteration(data, U):\n \"\"\"\n :param data: data is all x in X\n :return: allocation\n \"\"\"\n Uprior = []\n Ucurr = deepcopy(U)\n it = 0\n while True:\n it += 1\n print(\"iteration:\", it)\n Uprior = deepcopy(Ucurr)\n dict, er = getCluster(data, Ucurr)\n mean_d = 0\n for k in range(len(U)):\n '''Xk = []\n for i in range(len(al)):\n if al[i] == k:\n Xk.append(data[i])\n Ucurr[k] = getmean(Xk)\n print(k, len(Xk))'''\n Ucurr[k] = getmean(dict[k])\n print(k, len(dict[k]))\n for f in range(len(Ucurr[k])):\n mean_d += getDistance(Ucurr[k][f], Uprior[k][f])\n if mean_d <= 0.01 or it >= 50:\n break\n return dict, er\n # return al, er\n\n\ndef getmean(X):\n \"\"\"\n :param X: X is a set of x\n :return: the mean of set X\n \"\"\"\n if not X:\n print(\"empty X\")\n # jnumber = len(X) # number of points in it\n\n u = deepcopy(X[0]) # initialize u\n if len(u) == 0:\n return 0\n for i in range(len(u)):\n if type(u[i])==list:\n for j in range(len(u[i])):\n s = sum([X[point][i][j] for point in range(len(X))])\n avg = s / len(X)\n u[i][j] = avg\n else:\n s = sum([X[point][i] for point in range(len(X))])\n avg = s / len(X)\n u[i] = avg\n\n return u\n\n\ndef getDistance(x1, x2):\n \"\"\"\n x1,x2 should be same length\n x1,x2 are 1-d vectors\n :param x1: a vector\n :param x2: a vector\n :return: the 2-norm distance between x1 and x2\n \"\"\"\n if type(x1)==list:\n l1 = len(x1)\n l2 = len(x2)\n if l1 != l2:\n print('Error! Unequal vectors.')\n return False\n nx1 = np.array(x1)\n nx2 = np.array(x2)\n d = np.sum(abs(nx1 - nx2))\n '''d = 0\n for i in range(0,l1):\n d += (float(x1[i]) - float(x2[i]))**2\n d = d / l1'''\n return d\n else:\n return abs(x1 - x2)\n\n\ndef get_k_means_pp(X, U):\n Ufix = deepcopy(U)\n for k in range(len(U)-1):\n d = [0] * len(X)\n indx = [i for i in range(len(X))]\n for n in range(len(X)):\n s = sum([getDistance(X[n][i], Ufix[k][i]) for i in range(len(X[n]))])\n d[n] = np.square(s)\n d_sum = sum(d)\n for n in range(len(X)):\n d[n] /= d_sum\n ch = choice(indx, p=d)\n Ufix[k+1] = X[ch]\n return Ufix\n\n\n# if __name__ == '__main__':\n # data = randomData()\n # number = len(data)\n # print(iteration(data))\n # print(getmean(data))\n\n\n"
] |
[
[
"numpy.square",
"numpy.array",
"numpy.random.choice"
]
] |
nishanthkoganti-gep/product_classify
|
[
"75f3cbd23aa508e5ad9b1c0bb59c2dc758530336"
] |
[
"data_loader/data_loaders.py"
] |
[
"# import modules\nimport torch\nimport pickle\nimport numpy as np\nimport pandas as pd\nfrom os.path import join\nfrom torch.utils.data import Dataset\nfrom sklearn.utils.class_weight import compute_class_weight\n\n# relative imports\nfrom base import BaseDataLoader\nfrom IPython.terminal.debugger import set_trace as keyboard\n\n\nclass AmazonDataset(Dataset):\n \"\"\"Amazon Labels Dataset.\"\"\"\n\n def __init__(self, pkl_file, level=1):\n with open(pkl_file, 'rb') as f:\n data = pickle.load(f)\n\n # obtain valid rows for level\n self.level = f'level{level}'\n valid_rows = data[self.level] >= 0\n\n # compute n_samples and n_labels\n self.n_samples = valid_rows.sum()\n self.n_labels = np.unique(data[self.level].values)\n\n # obtain titles and descriptions\n self.titles = data['title'][valid_rows]\n self.descriptions = data['description'][valid_rows]\n\n self.titles = self.titles.astype(np.int64)\n self.descriptions = self.descriptions.astype(np.int64)\n\n # obtain labels\n self.labels = data[self.level][valid_rows].values\n self.labels = self.labels.astype(np.int64)\n\n # compute class weights\n self.weights = compute_class_weight('balanced',\n np.unique(self.labels),\n self.labels)\n\n def __len__(self):\n return self.n_samples\n\n def __getitem__(self, idx):\n if torch.is_tensor(idx):\n idx = idx.tolist()\n\n title = self.titles[idx]\n description = self.descriptions[idx]\n label = self.labels[idx]\n return title, description, label\n\n\nclass AmazonDataLoader(BaseDataLoader):\n \"\"\"\n amazon data loader inherited from BaseDataLoader\n \"\"\"\n def __init__(self, data_dir, batch_size, shuffle=True,\n validation_split=0.0, num_workers=1, training=True,\n level=1):\n\n # set data directory\n self.data_dir = data_dir\n\n # setup pickle file\n if training:\n pkl_file = 'train.pkl'\n else:\n pkl_file = 'test.pkl'\n pkl_file = join(self.data_dir, pkl_file)\n\n self.dataset = AmazonDataset(pkl_file, level)\n\n super().__init__(self.dataset, batch_size, shuffle,\n validation_split, num_workers)\n"
] |
[
[
"torch.is_tensor",
"numpy.unique"
]
] |
retzger/tensorflow
|
[
"9aaf74d733a38cf587a75f2ffaa05d8a51d8c32b"
] |
[
"tensorflow/lite/testing/generate_examples_lib.py"
] |
[
"# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"Generate a series of TensorFlow graphs that become tflite test cases.\n\nUsage:\n\ngenerate_examples <output directory>\n\nbazel run //tensorflow/lite/testing:generate_examples\n\nTo more easily debug failures use (or override) the --save_graphdefs flag to\nplace text proto graphdefs into the generated zip files.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport datetime\nimport functools\nimport itertools\nimport operator\nimport os\nimport random\nimport re\nimport string\nimport tempfile\nimport traceback\nimport zipfile\nimport numpy as np\nfrom six import StringIO\nfrom six.moves import xrange\n\n# TODO(aselle): Disable GPU for now\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"-1\"\n\n# pylint: disable=g-import-not-at-top\nimport tensorflow as tf\nfrom google.protobuf import text_format\n# TODO(aselle): switch to TensorFlow's resource_loader\nfrom tensorflow.lite.testing import generate_examples_report as report_lib\nfrom tensorflow.lite.testing import string_util_wrapper\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.framework import graph_util as tf_graph_util\nfrom tensorflow.python.ops import rnn\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import spectral_ops_test_util\n\n\nRANDOM_SEED = 342\nTEST_INPUT_DEPTH = 3\n\n\n# A map from regular expression to bug number. Any test failure with label\n# matching the expression will be considered due to the corresponding bug.\nKNOWN_BUGS = {\n # TOCO doesn't support scalars as input.\n # Concat doesn't work with a single input tensor\n r\"concat.*num_tensors=1\": \"67378344\",\n # Transposition in MatMul is not fully supported.\n \"fully_connected.*transpose_a=True\": \"67586970\",\n # Softmax graphs are too complex.\n r\"softmax.*dim=0\": \"67749831\",\n # BatchToSpaceND only supports 4D tensors.\n r\"batch_to_space_nd.*input_shape=\\[8,2,2,2,1,1\\]\": \"70594733\",\n # Div will use floordiv.\n r\"div.*int32\": \"72051395\",\n # Strided slice cannot handle new_axis_mask.\n r\"strided_slice.*new_axis_num=1|2\": \"137470173\",\n}\n\n\nclass Options(object):\n \"\"\"All options for example generation.\"\"\"\n\n def __init__(self):\n # Directory where the outputs will be go.\n self.output_path = None\n # Particular zip to output.\n self.zip_to_output = None\n # Path to toco tool.\n self.toco = None\n # If a particular model is affected by a known bug count it as a Toco\n # error.\n self.known_bugs_are_errors = False\n # Raise an exception if any converter error is encountered.\n self.ignore_converter_errors = False\n # Include intermediate graphdefs in the output zip files.\n self.save_graphdefs = False\n # Whether the TFLite Flex converter is being used.\n self.run_with_flex = False\n # Whether to generate test cases for edgetpu.\n self.make_edgetpu_tests = False\n # The function to convert a TensorFLow model to TFLite model.\n # See the document for `toco_convert` function for its required signature.\n # TODO(ycling): Decouple `toco_convert` function from this module, and\n # remove the `toco` attribute in this class.\n self.tflite_convert_function = toco_convert\n # A map from regular expression to bug number. Any test failure with label\n # matching the expression will be considered due to the corresponding bug.\n self.known_bugs = KNOWN_BUGS\n # Make tests by setting TF forward compatibility horizon to the future.\n self.make_forward_compat_test = False\n\n\n# A map from names to functions which make test cases.\n_MAKE_TEST_FUNCTIONS_MAP = {}\n\n\n# A decorator to register the make test functions.\n# Usage:\n# All the make_*_test should be registered. Example:\n# @register_make_test_function()\n# def make_conv_tests(options):\n# # ...\n# If a function is decorated by other decorators, it's required to specify the\n# name explicitly. Example:\n# @register_make_test_function(name=\"make_unidirectional_sequence_lstm_tests\")\n# @test_util.enable_control_flow_v2\n# def make_unidirectional_sequence_lstm_tests(options):\n# # ...\ndef register_make_test_function(name=None):\n def decorate(function, name=name):\n if name is None:\n name = function.__name__\n _MAKE_TEST_FUNCTIONS_MAP[name] = function\n return decorate\n\n\nclass ExtraTocoOptions(object):\n \"\"\"Additional toco options besides input, output, shape.\"\"\"\n\n def __init__(self):\n # Whether to ignore control dependency nodes.\n self.drop_control_dependency = False\n # Allow custom ops in the toco conversion.\n self.allow_custom_ops = False\n # Rnn states that are used to support rnn / lstm cells.\n self.rnn_states = None\n # Split the LSTM inputs from 5 inoputs to 18 inputs for TFLite.\n self.split_tflite_lstm_inputs = None\n # The inference input type passed to TFLiteConvert.\n self.inference_input_type = None\n # The inference output type passed to TFLiteConvert.\n self.inference_output_type = None\n\n\ndef toco_options(data_types,\n input_arrays,\n output_arrays,\n shapes,\n extra_toco_options=ExtraTocoOptions()):\n \"\"\"Create TOCO options to process a model.\n\n Args:\n data_types: input and inference types used by TOCO.\n input_arrays: names of the input tensors\n output_arrays: name of the output tensors\n shapes: shapes of the input tensors\n extra_toco_options: additional toco options\n Returns:\n the options in a string.\n \"\"\"\n shape_str = \":\".join([\",\".join(str(y) for y in x) for x in shapes if x])\n inference_type = \"FLOAT\"\n # TODO(ahentz): if we get multi-input quantization to work we need this\n # to change\n if data_types[0] == \"QUANTIZED_UINT8\":\n inference_type = \"QUANTIZED_UINT8\"\n s = (\" --input_data_types=%s\" % \",\".join(data_types) +\n \" --inference_type=%s\" % inference_type +\n \" --input_format=TENSORFLOW_GRAPHDEF\" + \" --output_format=TFLITE\" +\n \" --input_arrays=%s\" % \",\".join(input_arrays) +\n \" --output_arrays=%s\" % \",\".join(output_arrays))\n if shape_str:\n s += (\" --input_shapes=%s\" % shape_str)\n if extra_toco_options.drop_control_dependency:\n s += \" --drop_control_dependency\"\n if extra_toco_options.allow_custom_ops:\n s += \" --allow_custom_ops\"\n if extra_toco_options.rnn_states:\n s += (\" --rnn_states='\" + extra_toco_options.rnn_states + \"'\")\n if extra_toco_options.split_tflite_lstm_inputs is not None:\n if extra_toco_options.split_tflite_lstm_inputs:\n s += \" --split_tflite_lstm_inputs=true\"\n else:\n s += \" --split_tflite_lstm_inputs=false\"\n return s\n\n\ndef format_result(t):\n \"\"\"Convert a tensor to a format that can be used in test specs.\"\"\"\n if t.dtype.kind not in [np.dtype(np.string_).kind, np.dtype(np.object_).kind]:\n # Output 9 digits after the point to ensure the precision is good enough.\n values = [\"{:.9f}\".format(value) for value in list(t.flatten())]\n return \",\".join(values)\n else:\n return string_util_wrapper.SerializeAsHexString(t.flatten())\n\n\ndef write_examples(fp, examples):\n \"\"\"Given a list `examples`, write a text format representation.\n\n The file format is csv like with a simple repeated pattern. We would ike\n to use proto here, but we can't yet due to interfacing with the Android\n team using this format.\n\n Args:\n fp: File-like object to write to.\n examples: Example dictionary consiting of keys \"inputs\" and \"outputs\"\n \"\"\"\n\n def write_tensor(fp, x):\n \"\"\"Write tensor in file format supported by TFLITE example.\"\"\"\n fp.write(\"dtype,%s\\n\" % x.dtype)\n fp.write(\"shape,\" + \",\".join(map(str, x.shape)) + \"\\n\")\n fp.write(\"values,\" + format_result(x) + \"\\n\")\n\n fp.write(\"test_cases,%d\\n\" % len(examples))\n for example in examples:\n fp.write(\"inputs,%d\\n\" % len(example[\"inputs\"]))\n for i in example[\"inputs\"]:\n write_tensor(fp, i)\n fp.write(\"outputs,%d\\n\" % len(example[\"outputs\"]))\n for i in example[\"outputs\"]:\n write_tensor(fp, i)\n\n\ndef write_test_cases(fp, model_name, examples):\n \"\"\"Given a dictionary of `examples`, write a text format representation.\n\n The file format is protocol-buffer-like, even though we don't use proto due\n to the needs of the Android team.\n\n Args:\n fp: File-like object to write to.\n model_name: Filename where the model was written to, relative to filename.\n examples: Example dictionary consiting of keys \"inputs\" and \"outputs\"\n \"\"\"\n\n fp.write(\"load_model: %s\\n\" % os.path.basename(model_name))\n for example in examples:\n fp.write(\"reshape {\\n\")\n for t in example[\"inputs\"]:\n fp.write(\" input: \\\"\" + \",\".join(map(str, t.shape)) + \"\\\"\\n\")\n fp.write(\"}\\n\")\n fp.write(\"invoke {\\n\")\n\n for t in example[\"inputs\"]:\n fp.write(\" input: \\\"\" + format_result(t) + \"\\\"\\n\")\n for t in example[\"outputs\"]:\n fp.write(\" output: \\\"\" + format_result(t) + \"\\\"\\n\")\n fp.write(\" output_shape: \\\"\" + \",\".join([str(dim) for dim in t.shape]) +\n \"\\\"\\n\")\n fp.write(\"}\\n\")\n\n\n_TF_TYPE_INFO = {\n tf.float32: (np.float32, \"FLOAT\"),\n tf.float16: (np.float16, \"FLOAT\"),\n tf.int32: (np.int32, \"INT32\"),\n tf.uint8: (np.uint8, \"QUANTIZED_UINT8\"),\n tf.int16: (np.int16, \"QUANTIZED_INT16\"),\n tf.int64: (np.int64, \"INT64\"),\n tf.bool: (np.bool, \"BOOL\"),\n tf.string: (np.string_, \"STRING\"),\n}\n\n\ndef create_tensor_data(dtype, shape, min_value=-100, max_value=100):\n \"\"\"Build tensor data spreading the range [min_value, max_value).\"\"\"\n\n if dtype in _TF_TYPE_INFO:\n dtype = _TF_TYPE_INFO[dtype][0]\n\n if dtype in (tf.float32, tf.float16):\n value = (max_value-min_value)*np.random.random_sample(shape)+min_value\n elif dtype in (tf.int32, tf.uint8, tf.int64, tf.int16):\n value = np.random.randint(min_value, max_value+1, shape)\n elif dtype == tf.bool:\n value = np.random.choice([True, False], size=shape)\n elif dtype == np.string_:\n # Not the best strings, but they will do for some basic testing.\n letters = list(string.ascii_uppercase)\n return np.random.choice(letters, size=shape).astype(dtype)\n return np.dtype(dtype).type(value) if np.isscalar(value) else value.astype(\n dtype)\n\n\ndef create_scalar_data(dtype, min_value=-100, max_value=100):\n \"\"\"Build scalar tensor data range from min_value to max_value exclusively.\"\"\"\n\n if dtype in _TF_TYPE_INFO:\n dtype = _TF_TYPE_INFO[dtype][0]\n\n if dtype in (tf.float32, tf.float16):\n value = (max_value - min_value) * np.random.random() + min_value\n elif dtype in (tf.int32, tf.uint8, tf.int64, tf.int16):\n value = np.random.randint(min_value, max_value + 1)\n return np.array(value, dtype=dtype)\n\n\ndef freeze_graph(session, outputs):\n \"\"\"Freeze the current graph.\n\n Args:\n session: Tensorflow sessions containing the graph\n outputs: List of output tensors\n\n Returns:\n The frozen graph_def.\n \"\"\"\n return tf_graph_util.convert_variables_to_constants(\n session, session.graph.as_graph_def(), [x.op.name for x in outputs])\n\n\n@register_make_test_function()\ndef make_control_dep_tests(options):\n \"\"\"Make a set of tests that use control dependencies.\"\"\"\n\n test_parameters = [{\n \"input_shape\": [[], [1, 1, 1, 1], [1, 15, 14, 1], [3, 15, 14, 3]],\n }]\n\n def build_graph(parameters):\n input_tensor = tf.placeholder(\n dtype=tf.float32, name=\"input\", shape=parameters[\"input_shape\"])\n filter_value = tf.zeros((3, 3, TEST_INPUT_DEPTH, 8), tf.float32)\n assert_op = tf.assert_greater_equal(input_tensor, input_tensor - 1)\n with tf.control_dependencies([assert_op]):\n out = tf.nn.conv2d(input_tensor, filter_value,\n strides=(1, 1, 1, 1), padding=\"SAME\")\n return [input_tensor], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_values = create_tensor_data(tf.float32, parameters[\"input_shape\"])\n return [input_values], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_values])))\n\n extra_toco_options = ExtraTocoOptions()\n extra_toco_options.drop_control_dependency = True\n make_zip_of_tests(\n options,\n test_parameters,\n build_graph,\n build_inputs,\n extra_toco_options,\n expected_tf_failures=3)\n\n\ndef toco_convert(options, graph_def, input_tensors, output_tensors, **kwargs):\n \"\"\"Convert a model's graph def into a tflite model.\n\n NOTE: this currently shells out to the toco binary, but we would like\n convert to Python API tooling in the future.\n\n Args:\n options: An Options instance.\n graph_def: A GraphDef object.\n input_tensors: List of input tensor tuples `(name, shape, type)`.\n output_tensors: List of output tensors (names).\n **kwargs: Extra options to be passed.\n\n Returns:\n output tflite model, log_txt from conversion\n or None, log_txt if it did not convert properly.\n \"\"\"\n # Convert ophint ops if presented.\n graph_def = tf.lite.experimental.convert_op_hints_to_stubs(\n graph_def=graph_def)\n graph_def_str = graph_def.SerializeToString()\n\n extra_toco_options = kwargs.get(\"extra_toco_options\", ExtraTocoOptions())\n test_params = kwargs.get(\"test_params\", {})\n input_arrays = [x[0] for x in input_tensors]\n data_types = [_TF_TYPE_INFO[x[2]][1] for x in input_tensors]\n\n if test_params.get(\"fully_quantize\", False):\n with tempfile.NamedTemporaryFile() as graphdef_file:\n graphdef_file.write(graph_def_str)\n graphdef_file.flush()\n\n input_shapes = get_input_shapes_map(input_tensors)\n converter = tf.lite.TocoConverter.from_frozen_graph(\n graphdef_file.name, input_arrays, output_tensors, input_shapes)\n\n def representative_dataset(input_tensors):\n calibration_inputs = []\n for _, shape, _ in input_tensors:\n if shape:\n dims = [dim.value for dim in shape.dims]\n calibration_inputs.append(\n np.random.uniform(-1, 1, tuple(dims)).astype(np.float32))\n return calibration_inputs\n\n def representative_dataset_gen():\n for _ in range(100):\n yield representative_dataset(input_tensors)\n\n converter.target_spec.supported_ops = [\n tf.lite.OpsSet.TFLITE_BUILTINS_INT8\n ]\n converter.representative_dataset = representative_dataset_gen\n if extra_toco_options.inference_input_type:\n converter.inference_input_type = (\n extra_toco_options.inference_input_type)\n if extra_toco_options.inference_output_type:\n converter.inference_output_type = (\n extra_toco_options.inference_output_type)\n\n try:\n tflite_model = converter.convert()\n return tflite_model, \"\"\n except Exception as e:\n log = \"{0}\\n{1}\".format(str(e), traceback.format_exc())\n return None, log\n\n else:\n opts = toco_options(\n data_types=data_types,\n input_arrays=input_arrays,\n shapes=[x[1] for x in input_tensors],\n output_arrays=output_tensors,\n extra_toco_options=extra_toco_options)\n\n with tempfile.NamedTemporaryFile() as graphdef_file, \\\n tempfile.NamedTemporaryFile() as output_file, \\\n tempfile.NamedTemporaryFile(\"w+\") as stdout_file:\n graphdef_file.write(graph_def_str)\n graphdef_file.flush()\n\n # TODO(aselle): Switch this to subprocess at some point.\n if options.run_with_flex:\n opts += \" --enable_select_tf_ops --force_select_tf_ops\"\n cmd = (\"%s --input_file=%s --output_file=%s %s > %s 2>&1\" %\n (bin_path, graphdef_file.name, output_file.name, opts,\n stdout_file.name))\n exit_code = os.system(cmd)\n log = (\n cmd + \"exited with code %d\" % exit_code + \"\\n------------------\\n\" +\n stdout_file.read())\n return (None if exit_code != 0 else output_file.read()), log\n\n\ndef get_input_shapes_map(input_tensors):\n \"\"\"Gets a map of input names to shapes.\n\n Args:\n input_tensors: List of input tensor tuples `(name, shape, type)`.\n\n Returns:\n {string : list of integers}.\n \"\"\"\n input_arrays = [tensor[0] for tensor in input_tensors]\n input_shapes_list = []\n\n for _, shape, _ in input_tensors:\n dims = None\n if shape:\n dims = [dim.value for dim in shape.dims]\n input_shapes_list.append(dims)\n\n input_shapes = {\n name: shape\n for name, shape in zip(input_arrays, input_shapes_list)\n if shape\n }\n return input_shapes\n\n\ndef normalize_output_name(output_name):\n \"\"\"Remove :0 suffix from tensor names.\"\"\"\n return output_name.split(\":\")[0] if output_name.endswith(\n \":0\") else output_name\n\n\n# How many test cases we may have in a zip file. Too many test cases will\n# slow down the test data generation process.\n_MAX_TESTS_PER_ZIP = 500\n\n\ndef make_zip_of_tests(options,\n test_parameters,\n make_graph,\n make_test_inputs,\n extra_toco_options=ExtraTocoOptions(),\n use_frozen_graph=False,\n expected_tf_failures=0):\n \"\"\"Helper to make a zip file of a bunch of TensorFlow models.\n\n This does a cartestian product of the dictionary of test_parameters and\n calls make_graph() for each item in the cartestian product set.\n If the graph is built successfully, then make_test_inputs() is called to\n build expected input/output value pairs. The model is then converted to tflite\n with toco, and the examples are serialized with the tflite model into a zip\n file (2 files per item in the cartesian product set).\n\n Args:\n options: An Options instance.\n test_parameters: Dictionary mapping to lists for each parameter.\n e.g. `{\"strides\": [[1,3,3,1], [1,2,2,1]], \"foo\": [1.2, 1.3]}`\n make_graph: function that takes current parameters and returns tuple\n `[input1, input2, ...], [output1, output2, ...]`\n make_test_inputs: function taking `curr_params`, `session`, `input_tensors`,\n `output_tensors` and returns tuple `(input_values, output_values)`.\n extra_toco_options: Additional toco options.\n use_frozen_graph: Whether or not freeze graph before toco converter.\n expected_tf_failures: Number of times tensorflow is expected to fail in\n executing the input graphs. In some cases it is OK for TensorFlow to\n fail because the one or more combination of parameters is invalid.\n\n Raises:\n RuntimeError: if there are converter errors that can't be ignored.\n \"\"\"\n zip_path = os.path.join(options.output_path, options.zip_to_output)\n parameter_count = 0\n for parameters in test_parameters:\n parameter_count += functools.reduce(\n operator.mul, [len(values) for values in parameters.values()])\n\n if parameter_count > _MAX_TESTS_PER_ZIP:\n raise RuntimeError(\n \"Too many parameter combinations for generating '%s'.\\n\"\n \"There are %d combinations while the upper limit is %d.\\n\"\n \"Having too many combinations will slow down the tests.\\n\"\n \"Please consider splitting the test into multiple functions.\\n\"\n % (zip_path, parameter_count, _MAX_TESTS_PER_ZIP))\n\n # TODO(aselle): Make this allow multiple inputs outputs.\n archive = zipfile.PyZipFile(zip_path, \"w\")\n zip_manifest = []\n convert_report = []\n toco_errors = 0\n\n processed_labels = set()\n\n if options.make_edgetpu_tests:\n extra_toco_options.inference_input_type = tf.lite.constants.QUANTIZED_UINT8\n extra_toco_options.inference_output_type = tf.lite.constants.QUANTIZED_UINT8\n\n for parameters in test_parameters:\n keys = parameters.keys()\n for curr in itertools.product(*parameters.values()):\n label = zip_path.replace(\".zip\", \"_\") + (\",\".join(\n \"%s=%r\" % z for z in sorted(zip(keys, curr))).replace(\" \", \"\"))\n if label[0] == \"/\":\n label = label[1:]\n if label in processed_labels:\n # Do not populate data for the same label more than once. It will cause\n # errors when unzipping.\n continue\n processed_labels.add(label)\n\n param_dict = dict(zip(keys, curr))\n\n if options.make_edgetpu_tests and not param_dict.get(\n \"fully_quantize\", False):\n continue\n\n def build_tflite_inputs(tflite_model_binary):\n # Build input values and output values of the given tflite model.\n interpreter = tf.lite.Interpreter(model_content=tflite_model_binary)\n interpreter.allocate_tensors()\n\n input_details = interpreter.get_input_details()\n input_values = []\n for input_detail in input_details:\n # TODO(yunluli): Set proper min max value according to dtype.\n input_value = create_tensor_data(\n input_detail[\"dtype\"],\n input_detail[\"shape\"],\n min_value=0,\n max_value=255)\n interpreter.set_tensor(input_detail[\"index\"], input_value)\n input_values.append(input_value)\n\n interpreter.invoke()\n\n output_details = interpreter.get_output_details()\n output_values = []\n for output_detail in output_details:\n output_values.append(interpreter.get_tensor(output_detail[\"index\"]))\n\n return input_values, output_values\n\n def build_example(label, param_dict_real):\n \"\"\"Build the model with parameter values set in param_dict_real.\n\n Args:\n label: Label of the model (i.e. the filename in the zip).\n param_dict_real: Parameter dictionary (arguments to the factories\n make_graph and make_test_inputs)\n Returns:\n (tflite_model_binary, report) where tflite_model_binary is the\n serialized flatbuffer as a string and report is a dictionary with\n keys `toco_log` (log of toco conversion), `tf_log` (log of tf\n conversion), `toco` (a string of success status of the conversion),\n `tf` (a string success status of the conversion).\n \"\"\"\n\n np.random.seed(RANDOM_SEED)\n report = {\"toco\": report_lib.NOTRUN, \"tf\": report_lib.FAILED}\n\n # Build graph\n report[\"tf_log\"] = \"\"\n report[\"toco_log\"] = \"\"\n tf.reset_default_graph()\n\n with tf.device(\"/cpu:0\"):\n try:\n inputs, outputs = make_graph(param_dict_real)\n except (tf.errors.UnimplementedError, tf.errors.InvalidArgumentError,\n ValueError):\n report[\"tf_log\"] += traceback.format_exc()\n return None, report\n\n sess = tf.compat.v1.Session()\n try:\n baseline_inputs, baseline_outputs = (make_test_inputs(\n param_dict_real, sess, inputs, outputs))\n except (tf.errors.UnimplementedError, tf.errors.InvalidArgumentError,\n ValueError):\n report[\"tf_log\"] += traceback.format_exc()\n return None, report\n report[\"toco\"] = report_lib.FAILED\n report[\"tf\"] = report_lib.SUCCESS\n # Convert graph to toco\n input_tensors = [(input_tensor.name.split(\":\")[0], input_tensor.shape,\n input_tensor.dtype) for input_tensor in inputs]\n output_tensors = [normalize_output_name(out.name) for out in outputs]\n graph_def = freeze_graph(\n sess,\n tf.global_variables() + inputs +\n outputs) if use_frozen_graph else sess.graph_def\n\n if \"split_tflite_lstm_inputs\" in param_dict_real:\n extra_toco_options.split_tflite_lstm_inputs = param_dict_real[\n \"split_tflite_lstm_inputs\"]\n\n tflite_model_binary, toco_log = options.tflite_convert_function(\n options,\n graph_def,\n input_tensors,\n output_tensors,\n extra_toco_options=extra_toco_options,\n test_params=param_dict_real)\n report[\"toco\"] = (report_lib.SUCCESS if tflite_model_binary is not None\n else report_lib.FAILED)\n report[\"toco_log\"] = toco_log\n\n if options.save_graphdefs:\n archive.writestr(label + \".pbtxt\",\n text_format.MessageToString(graph_def),\n zipfile.ZIP_DEFLATED)\n\n if tflite_model_binary:\n if options.make_edgetpu_tests:\n baseline_inputs, baseline_outputs = build_tflite_inputs(\n tflite_model_binary)\n archive.writestr(label + \".bin\", tflite_model_binary,\n zipfile.ZIP_DEFLATED)\n example = {\"inputs\": baseline_inputs, \"outputs\": baseline_outputs}\n\n example_fp = StringIO()\n write_examples(example_fp, [example])\n archive.writestr(label + \".inputs\",\n example_fp.getvalue(), zipfile.ZIP_DEFLATED)\n\n example_fp2 = StringIO()\n write_test_cases(example_fp2, label + \".bin\", [example])\n archive.writestr(label + \"_tests.txt\",\n example_fp2.getvalue(), zipfile.ZIP_DEFLATED)\n\n zip_manifest.append(label + \"\\n\")\n\n return tflite_model_binary, report\n\n _, report = build_example(label, param_dict)\n\n if report[\"toco\"] == report_lib.FAILED:\n ignore_error = False\n if not options.known_bugs_are_errors:\n for pattern, bug_number in options.known_bugs.items():\n if re.search(pattern, label):\n print(\"Ignored converter error due to bug %s\" % bug_number)\n ignore_error = True\n if not ignore_error:\n toco_errors += 1\n print(\"-----------------\\nconverter error!\\n%s\\n-----------------\\n\" %\n report[\"toco_log\"])\n\n convert_report.append((param_dict, report))\n\n report_io = StringIO()\n report_lib.make_report_table(report_io, zip_path, convert_report)\n archive.writestr(\"report.html\", report_io.getvalue())\n\n archive.writestr(\"manifest.txt\", \"\".join(zip_manifest), zipfile.ZIP_DEFLATED)\n\n # Log statistics of what succeeded\n total_conversions = len(convert_report)\n tf_success = sum(1 for x in convert_report\n if x[1][\"tf\"] == report_lib.SUCCESS)\n toco_success = sum(1 for x in convert_report\n if x[1][\"toco\"] == report_lib.SUCCESS)\n percent = 0\n if tf_success > 0:\n percent = float(toco_success) / float(tf_success) * 100.\n tf.logging.info((\"Archive %s Considered %d graphs, %d TF evaluated graphs \"\n \" and %d TOCO converted graphs (%.1f%%\"), zip_path,\n total_conversions, tf_success, toco_success, percent)\n\n tf_failures = parameter_count - tf_success\n\n if tf_failures / parameter_count > 0.8:\n raise RuntimeError((\"Test for '%s' is not very useful. \"\n \"TensorFlow fails in %d percent of the cases.\") %\n (zip_path, int(100 * tf_failures / parameter_count)))\n\n if not options.make_edgetpu_tests and tf_failures != expected_tf_failures:\n raise RuntimeError((\"Expected TF to fail %d times while generating '%s', \"\n \"but that happened %d times\") % (expected_tf_failures,\n zip_path, tf_failures))\n\n if not options.ignore_converter_errors and toco_errors > 0:\n raise RuntimeError(\n \"Found %d errors while generating toco models\" % toco_errors)\n\ndef make_pool_tests(pool_op_in):\n \"\"\"Make a set of tests to do average pooling.\n\n Args:\n pool_op_in: TensorFlow pooling operation to test i.e. `tf.nn.avg_pool2d`.\n\n Returns:\n A function representing the true generator (after curried pool_op_in).\n \"\"\"\n\n pool_op = pool_op_in\n\n def f(options, expected_tf_failures=0):\n \"\"\"Actual function that generates examples.\n\n Args:\n options: An Options instance.\n expected_tf_failures: number of expected tensorflow failures.\n \"\"\"\n\n # Chose a set of parameters\n test_parameters = [{\n \"ksize\": [[2, 1, 1, 2], [1, 1, 1, 1], [1, 1, 2, 1], [1, 10, 11, 1]],\n \"strides\": [[2, 1, 1, 2], [1, 1, 1, 1], [1, 1, 2, 1], [1, 10, 11, 1]],\n # TODO(aselle): should add in a degenerate shape (e.g. [1, 0, 1, 1]).\n \"input_shape\": [[], [1, 1, 1, 1], [1, 15, 14, 1], [3, 15, 14, 3]],\n \"padding\": [\"SAME\", \"VALID\"],\n \"data_format\": [\"NHWC\"], # TODO(aselle): NCHW would be good\n }]\n\n def build_graph(parameters):\n input_tensor = tf.placeholder(\n dtype=tf.float32, name=\"input\", shape=parameters[\"input_shape\"])\n out = pool_op(\n input_tensor,\n ksize=parameters[\"ksize\"],\n strides=parameters[\"strides\"],\n data_format=parameters[\"data_format\"],\n padding=parameters[\"padding\"])\n return [input_tensor], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_values = create_tensor_data(tf.float32, parameters[\"input_shape\"])\n return [input_values], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_values])))\n\n make_zip_of_tests(\n options,\n test_parameters,\n build_graph,\n build_inputs,\n expected_tf_failures=expected_tf_failures)\n\n return f\n\n\n@register_make_test_function()\ndef make_l2_pool_tests(options):\n make_pool_tests(make_l2_pool)(options, expected_tf_failures=80)\n\n\n@register_make_test_function()\ndef make_avg_pool_tests(options):\n make_pool_tests(tf.nn.avg_pool)(options, expected_tf_failures=80)\n\n\n@register_make_test_function()\ndef make_max_pool_tests(options):\n make_pool_tests(tf.nn.max_pool)(options, expected_tf_failures=80)\n\n\n@register_make_test_function()\ndef make_abs_tests(options):\n \"\"\"Make a set of tests to do relu.\"\"\"\n\n # Chose a set of parameters\n test_parameters = [{\n \"input_shape\": [[], [1], [2, 3], [1, 1, 1, 1], [1, 3, 4, 3],\n [3, 15, 14, 3], [3, 1, 2, 4, 6], [2, 2, 3, 4, 5, 6]],\n }]\n\n def build_graph(parameters):\n input_tensor = tf.placeholder(\n dtype=tf.float32, name=\"input\", shape=parameters[\"input_shape\"])\n out = tf.abs(input_tensor)\n return [input_tensor], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_values = create_tensor_data(\n np.float32, parameters[\"input_shape\"], min_value=-10, max_value=10)\n return [input_values], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_values])))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n@register_make_test_function()\ndef make_elu_tests(options):\n \"\"\"Make a set of tests to do (float) tf.nn.elu.\"\"\"\n\n test_parameters = [\n {\n \"input_shape\": [[], [1], [2, 3], [1, 1, 1, 1], [1, 3, 4, 3],\n [3, 15, 14, 3], [3, 1, 2, 4, 6], [2, 2, 3, 4, 5, 6]],\n },\n ]\n\n def build_graph(parameters):\n \"\"\"Build the graph for the test case.\"\"\"\n\n input_tensor = tf.placeholder(\n dtype=tf.float32, name=\"input\", shape=parameters[\"input_shape\"])\n out = tf.nn.elu(input_tensor)\n return [input_tensor], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n \"\"\"Build the inputs for the test case.\"\"\"\n input_values = create_tensor_data(\n np.float32, parameters[\"input_shape\"], min_value=-4, max_value=10)\n return [input_values], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_values])))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n@register_make_test_function()\ndef make_identity_tests(options):\n \"\"\"Make a set of tests to do identity.\"\"\"\n\n # Chose a set of parameters\n test_parameters = [{\n \"input_shape\": [[], [1], [3, 3]],\n \"use_snapshot\": [False, True],\n }]\n\n def build_graph(parameters):\n input_tensor = tf.placeholder(\n dtype=tf.float32, name=\"input\", shape=parameters[\"input_shape\"])\n # We add the Multiply before Identity just as a walk-around to make the test\n # pass when input_shape is scalar.\n # During graph transformation, TOCO will replace the Identity op with\n # Reshape when input has shape. However, currently TOCO can't distinguish\n # between missing shape and scalar shape. As a result, when input has scalar\n # shape, this conversion still fails.\n # TODO(b/129197312), remove the walk-around code once the bug is fixed.\n input_doubled = input_tensor * 2.0\n if parameters[\"use_snapshot\"]:\n identity_output = array_ops.snapshot(input_doubled)\n else:\n identity_output = tf.identity(input_doubled)\n return [input_tensor], [identity_output]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_values = create_tensor_data(\n np.float32, parameters[\"input_shape\"], min_value=-4, max_value=10)\n return [input_values], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_values])))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n@register_make_test_function()\ndef make_relu_tests(options):\n \"\"\"Make a set of tests to do relu.\"\"\"\n\n # Chose a set of parameters\n test_parameters = [{\n \"input_shape\": [[], [1], [2, 3], [1, 1, 1, 1], [1, 3, 4, 3],\n [3, 15, 14, 3], [3, 1, 2, 4, 6], [2, 2, 3, 4, 5, 6]],\n }]\n\n def build_graph(parameters):\n input_tensor = tf.placeholder(\n dtype=tf.float32, name=\"input\", shape=parameters[\"input_shape\"])\n out = tf.nn.relu(input_tensor)\n return [input_tensor], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_values = create_tensor_data(\n np.float32, parameters[\"input_shape\"], min_value=-4, max_value=10)\n return [input_values], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_values])))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n@register_make_test_function()\ndef make_relu1_tests(options):\n \"\"\"Make a set of tests to do relu1.\"\"\"\n\n # Chose a set of parameters\n test_parameters = [{\n \"input_shape\": [[], [1, 1, 1, 1], [1, 3, 4, 3], [3, 15, 14, 3],\n [3, 1, 2, 4, 6], [2, 2, 3, 4, 5, 6]],\n }]\n\n def build_graph(parameters):\n input_tensor = tf.placeholder(\n dtype=tf.float32, name=\"input\", shape=parameters[\"input_shape\"])\n # Note that the following is not supported:\n # out = tf.maximum(-1.0, tf.minimum(input_tensor, 1.0))\n out = tf.minimum(1.0, tf.maximum(input_tensor, -1.0))\n return [input_tensor], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_values = create_tensor_data(\n np.float32, parameters[\"input_shape\"], min_value=-3, max_value=10)\n return [input_values], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_values])))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n@register_make_test_function()\ndef make_relu6_tests(options):\n \"\"\"Make a set of tests to do relu6.\"\"\"\n\n # Chose a set of parameters\n test_parameters = [{\n \"input_shape\": [[], [1, 1, 1, 1], [1, 3, 4, 3], [3, 15, 14, 3],\n [3, 1, 2, 4, 6], [2, 2, 3, 4, 5, 6]],\n }]\n\n def build_graph(parameters):\n input_tensor = tf.placeholder(\n dtype=tf.float32, name=\"input\", shape=parameters[\"input_shape\"])\n out = tf.nn.relu(input_tensor)\n return [input_tensor], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_values = create_tensor_data(\n np.float32, parameters[\"input_shape\"], min_value=-3, max_value=10)\n return [input_values], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_values])))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n@register_make_test_function()\ndef make_prelu_tests(options):\n \"\"\"Make a set of tests to do PReLU.\"\"\"\n\n test_parameters = [\n {\n # The canonical case for image processing is having a 4D `input`\n # (NHWC)and `shared_axes`=[1, 2], so the alpha parameter is per\n # channel.\n \"input_shape\": [[1, 10, 10, 3], [3, 3, 3, 3]],\n \"shared_axes\": [[1, 2], [1]],\n },\n {\n # 2D-3D example. Share the 2nd axis.\n \"input_shape\": [[20, 20], [20, 20, 20]],\n \"shared_axes\": [[1]],\n }\n ]\n\n def build_graph(parameters):\n \"\"\"Build the graph for the test case.\"\"\"\n\n input_tensor = tf.placeholder(\n dtype=tf.float32, name=\"input\", shape=parameters[\"input_shape\"])\n prelu = tf.keras.layers.PReLU(shared_axes=parameters[\"shared_axes\"])\n out = prelu(input_tensor)\n return [input_tensor], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n \"\"\"Build the inputs for the test case.\"\"\"\n\n input_shape = parameters[\"input_shape\"]\n input_values = create_tensor_data(\n np.float32, input_shape, min_value=-10, max_value=10)\n shared_axes = parameters[\"shared_axes\"]\n\n alpha_shape = []\n for dim in range(1, len(input_shape)):\n alpha_shape.append(1 if dim in shared_axes else input_shape[dim])\n\n alpha_values = create_tensor_data(np.float32, alpha_shape)\n\n # There should be only 1 trainable variable tensor.\n variables = tf.all_variables()\n assert len(variables) == 1\n sess.run(variables[0].assign(alpha_values))\n\n return [input_values], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_values])))\n\n make_zip_of_tests(\n options,\n test_parameters,\n build_graph,\n build_inputs,\n use_frozen_graph=True)\n\n\n@register_make_test_function()\ndef make_leaky_relu_tests(options):\n \"\"\"Make a set of tests to do LeakyRelu.\"\"\"\n\n test_parameters = [\n {\n \"input_shape\": [[], [1], [5], [1, 10, 10, 3], [3, 3, 3, 3]],\n \"alpha\": [0.1, 1.0, 2.0, -0.1, -1.0, -2.0],\n },\n ]\n\n def build_graph(parameters):\n \"\"\"Build the graph for the test case.\"\"\"\n\n input_tensor = tf.placeholder(\n dtype=tf.float32, name=\"input\", shape=parameters[\"input_shape\"])\n out = tf.nn.leaky_relu(input_tensor, alpha=parameters[\"alpha\"])\n return [input_tensor], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n \"\"\"Build the inputs for the test case.\"\"\"\n input_values = create_tensor_data(\n np.float32, parameters[\"input_shape\"], min_value=-3, max_value=10)\n return [input_values], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_values])))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n# This function tests various TensorFLow functions that generates Const op,\n# including `tf.ones`, `tf.zeros` and random functions.\n@register_make_test_function()\ndef make_constant_tests(options):\n \"\"\"Make a set of tests to do constant ops.\"\"\"\n\n test_parameters = [{\n \"dtype\": [tf.float32, tf.int32],\n \"input_shape\": [[], [1], [2], [1, 1, 1, 1], [2, 2, 2, 2]],\n \"constant_is_also_output\": [True, False],\n # This is a regression test for a bug where Toco rejects models with\n # unread inputs.\n \"has_unread_input\": [True, False],\n }]\n\n def build_graph(parameters):\n dummy_input = tf.placeholder(\n dtype=parameters[\"dtype\"],\n name=\"input1\",\n shape=parameters[\"input_shape\"])\n constant = tf.constant(\n create_tensor_data(parameters[\"dtype\"], parameters[\"input_shape\"]))\n outputs = [tf.maximum(dummy_input, constant)]\n if parameters[\"constant_is_also_output\"]:\n outputs.append(constant)\n inputs = [dummy_input]\n if parameters[\"has_unread_input\"]:\n unread_input = tf.placeholder(\n dtype=parameters[\"dtype\"],\n name=\"unread_input\",\n shape=parameters[\"input_shape\"])\n inputs.append(unread_input)\n\n return inputs, outputs\n\n def build_inputs(parameters, sess, inputs, outputs):\n dummy_input = np.zeros(\n parameters[\"input_shape\"], dtype=_TF_TYPE_INFO[parameters[\"dtype\"]][0])\n return [dummy_input], sess.run(outputs, feed_dict={inputs[0]: dummy_input})\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\ndef make_binary_op_tests(options, binary_operator, expected_tf_failures=0):\n \"\"\"Make a set of tests to do binary ops with and without broadcast.\"\"\"\n\n test_parameters = [\n # Avoid creating all combinations to keep the test size small.\n {\n \"dtype\": [tf.float32, tf.int32],\n \"input_shape_1\": [[1, 3, 4, 3]],\n \"input_shape_2\": [[1, 3, 4, 3]],\n \"activation\": [True],\n },\n {\n \"dtype\": [tf.float32],\n \"input_shape_1\": [[5]],\n \"input_shape_2\": [[5]],\n \"activation\": [False, True],\n },\n {\n \"dtype\": [tf.float32, tf.int32, tf.int64],\n \"input_shape_1\": [[1, 3, 4, 3]],\n \"input_shape_2\": [[3]],\n \"activation\": [True, False],\n },\n {\n \"dtype\": [tf.float32, tf.int32],\n \"input_shape_1\": [[3]],\n \"input_shape_2\": [[1, 3, 4, 3]],\n \"activation\": [True, False],\n },\n {\n \"dtype\": [tf.float32],\n \"input_shape_1\": [[]],\n \"input_shape_2\": [[]],\n \"activation\": [False],\n },\n {\n \"dtype\": [tf.float32],\n \"input_shape_1\": [[0]],\n \"input_shape_2\": [[1]],\n \"activation\": [False],\n }\n ]\n\n def build_graph(parameters):\n \"\"\"Builds the graph given the current parameters.\"\"\"\n input1 = tf.placeholder(\n dtype=parameters[\"dtype\"],\n name=\"input1\",\n shape=parameters[\"input_shape_1\"])\n input2 = tf.placeholder(\n dtype=parameters[\"dtype\"],\n name=\"input2\",\n shape=parameters[\"input_shape_2\"])\n out = binary_operator(input1, input2)\n if parameters[\"activation\"]:\n out = tf.nn.relu(out)\n return [input1, input2], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n \"\"\"Builds operand inputs for op.\"\"\"\n input1 = create_tensor_data(parameters[\"dtype\"],\n parameters[\"input_shape_1\"])\n input2 = create_tensor_data(parameters[\"dtype\"],\n parameters[\"input_shape_2\"])\n return [input1, input2], sess.run(\n outputs, feed_dict={\n inputs[0]: input1,\n inputs[1]: input2\n })\n\n make_zip_of_tests(\n options,\n test_parameters,\n build_graph,\n build_inputs,\n expected_tf_failures=expected_tf_failures)\n\n\ndef make_reduce_tests(reduce_op,\n min_value=-10,\n max_value=10,\n boolean_tensor_only=False):\n \"\"\"Make a set of tests to do reduce operation.\n\n Args:\n reduce_op: TensorFlow reduce operation to test, i.e. `tf.reduce_mean`.\n min_value: min value for created tensor data.\n max_value: max value for created tensor data.\n boolean_tensor_only: If true, will only generate tensor with boolean value.\n\n Returns:\n a function representing the true generator with `reduce_op_in` curried.\n \"\"\"\n\n def f(options):\n \"\"\"Actual function that generates examples.\"\"\"\n\n test_parameters = [\n {\n \"input_dtype\": [tf.float32, tf.int32, tf.int64],\n \"input_shape\": [[3, 3, 2, 4]],\n \"axis\": [\n 0, 1, 2, [0, 1], [0, 2], [1, 2], [0, 1, 2], [1, 0], [2, 0],\n [2, 1], [2, 1, 0], [2, 0, 1], -1, -2, -3, [1, -1], [0, -1],\n [-1, 0], [-1, -2, -3], [0, 0, 0], [2, 2, 0], [1, 0, -3, -3]\n ],\n \"const_axis\": [True, False],\n \"keepdims\": [True, False],\n },\n {\n \"input_dtype\": [tf.float32],\n \"input_shape\": [[1, 8, 8, 3]],\n \"axis\": [\n 0, 1, 2, 3, [1, 2], [0, 3], [1, 2, 3], [0, 1, 2,\n 3], [3, 2, 1, 0],\n [3, 1, 0, 2], [2, 0], [3, 0], [3, 1], [1, 0], -1, -2, -3, -4,\n [0, -2], [2, 3, -1, 0], [3, 1, 2, -3], [3, -4], [2, 2, 2],\n [2, 2, 3], [-3, -3, -4], [-3, 2, 1]\n ],\n \"const_axis\": [True, False],\n \"keepdims\": [True, False],\n },\n {\n \"input_dtype\": [tf.float32],\n \"input_shape\": [[], [1, 8, 8, 3], [3, 2, 4]],\n \"axis\": [[]], # shape is: [0]\n \"const_axis\": [False],\n \"keepdims\": [True, False],\n },\n {\n \"input_dtype\": [tf.float32],\n \"input_shape\": [[], [1, 8, 8, 3], [3, 2, 4]],\n \"axis\": [None], # shape is: []\n \"const_axis\": [True],\n \"keepdims\": [True, False],\n }\n ]\n\n def build_graph(parameters):\n \"\"\"Build the mean op testing graph.\"\"\"\n dtype = parameters[\"input_dtype\"]\n if boolean_tensor_only:\n dtype = tf.bool\n input_tensor = tf.placeholder(\n dtype=dtype, name=\"input\", shape=parameters[\"input_shape\"])\n\n # Get axis as either a placeholder or constants.\n if parameters[\"const_axis\"]:\n axis = parameters[\"axis\"]\n input_tensors = [input_tensor]\n else:\n if isinstance(parameters[\"axis\"], list):\n shape = [len(parameters[\"axis\"])]\n else:\n shape = [] # shape for None or integers.\n axis = tf.placeholder(dtype=tf.int32, name=\"axis\", shape=shape)\n input_tensors = [input_tensor, axis]\n\n out = reduce_op(\n input_tensor, axis=axis, keepdims=parameters[\"keepdims\"])\n return input_tensors, [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n dtype = parameters[\"input_dtype\"]\n if boolean_tensor_only:\n dtype = tf.bool\n values = [\n create_tensor_data(\n dtype,\n parameters[\"input_shape\"],\n min_value=min_value,\n max_value=max_value)\n ]\n if not parameters[\"const_axis\"]:\n values.append(np.array(parameters[\"axis\"]))\n return values, sess.run(outputs, feed_dict=dict(zip(inputs, values)))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n return f\n\n\n@register_make_test_function()\ndef make_mean_tests(options):\n \"\"\"Make a set of tests to do mean.\"\"\"\n return make_reduce_tests(tf.reduce_mean)(options)\n\n\n@register_make_test_function()\ndef make_sum_tests(options):\n \"\"\"Make a set of tests to do sum.\"\"\"\n return make_reduce_tests(tf.reduce_sum)(options)\n\n\n@register_make_test_function()\ndef make_reduce_prod_tests(options):\n \"\"\"Make a set of tests to do prod.\"\"\"\n # set min max value to be -2, 2 to avoid overflow.\n return make_reduce_tests(tf.reduce_prod, -2, 2)(options)\n\n\n@register_make_test_function()\ndef make_reduce_max_tests(options):\n \"\"\"Make a set of tests to do max.\"\"\"\n return make_reduce_tests(tf.reduce_max)(options)\n\n\n@register_make_test_function()\ndef make_reduce_min_tests(options):\n \"\"\"Make a set of tests to do min.\"\"\"\n return make_reduce_tests(tf.reduce_min)(options)\n\n\n@register_make_test_function()\ndef make_reduce_any_tests(options):\n \"\"\"Make a set of tests to do any.\"\"\"\n return make_reduce_tests(tf.reduce_any, boolean_tensor_only=True)(options)\n\n\n@register_make_test_function()\ndef make_exp_tests(options):\n \"\"\"Make a set of tests to do exp.\"\"\"\n\n test_parameters = [{\n \"input_dtype\": [tf.float32],\n \"input_shape\": [[], [3], [1, 100], [4, 2, 3], [5, 224, 224, 3]],\n }]\n\n def build_graph(parameters):\n \"\"\"Build the exp op testing graph.\"\"\"\n input_tensor = tf.placeholder(\n dtype=parameters[\"input_dtype\"],\n name=\"input\",\n shape=parameters[\"input_shape\"])\n\n out = tf.exp(input_tensor)\n return [input_tensor], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n values = [\n create_tensor_data(parameters[\"input_dtype\"], parameters[\"input_shape\"],\n min_value=-100, max_value=9)\n ]\n return values, sess.run(outputs, feed_dict=dict(zip(inputs, values)))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n@register_make_test_function()\ndef make_cos_tests(options):\n \"\"\"Make a set of tests to do cos.\"\"\"\n\n test_parameters = [{\n \"input_dtype\": [tf.float32],\n \"input_shape\": [[], [3], [1, 100], [4, 2, 3], [5, 224, 224, 3]],\n }]\n\n def build_graph(parameters):\n \"\"\"Build the cos op testing graph.\"\"\"\n input_tensor = tf.placeholder(\n dtype=parameters[\"input_dtype\"],\n name=\"input\",\n shape=parameters[\"input_shape\"])\n\n out = tf.cos(input_tensor)\n return [input_tensor], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n values = [\n create_tensor_data(parameters[\"input_dtype\"], parameters[\"input_shape\"],\n min_value=-np.pi, max_value=np.pi)\n ]\n return values, sess.run(outputs, feed_dict=dict(zip(inputs, values)))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n@register_make_test_function()\ndef make_log_softmax_tests(options):\n \"\"\"Make a set of tests to do log_softmax.\"\"\"\n\n test_parameters = [{\n \"input_dtype\": [tf.float32],\n \"input_shape\": [[1, 100], [4, 2], [5, 224]],\n }]\n\n def build_graph(parameters):\n \"\"\"Build the log_softmax op testing graph.\"\"\"\n input_tensor = tf.placeholder(\n dtype=parameters[\"input_dtype\"],\n name=\"input\",\n shape=parameters[\"input_shape\"])\n\n out = tf.nn.log_softmax(input_tensor)\n return [input_tensor], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n values = [\n create_tensor_data(\n parameters[\"input_dtype\"],\n parameters[\"input_shape\"],\n min_value=-100,\n max_value=9)\n ]\n return values, sess.run(outputs, feed_dict=dict(zip(inputs, values)))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n@register_make_test_function()\ndef make_maximum_tests(options):\n \"\"\"Make a set of tests to do maximum.\"\"\"\n\n test_parameters = [{\n \"input_dtype\": [tf.float32],\n \"input_shape_1\": [[], [3], [1, 100], [4, 2, 3], [5, 224, 224, 3]],\n \"input_shape_2\": [[], [3], [1, 100], [4, 2, 3], [5, 224, 224, 3]],\n }]\n\n def build_graph(parameters):\n \"\"\"Build the maximum op testing graph.\"\"\"\n input_tensor_1 = tf.placeholder(\n dtype=parameters[\"input_dtype\"],\n name=\"input_1\",\n shape=parameters[\"input_shape_1\"])\n input_tensor_2 = tf.placeholder(\n dtype=parameters[\"input_dtype\"],\n name=\"input_2\",\n shape=parameters[\"input_shape_2\"])\n\n out = tf.maximum(input_tensor_1, input_tensor_2)\n return [input_tensor_1, input_tensor_2], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n values = [\n create_tensor_data(parameters[\"input_dtype\"],\n parameters[\"input_shape_1\"]),\n create_tensor_data(parameters[\"input_dtype\"],\n parameters[\"input_shape_2\"])\n ]\n return values, sess.run(outputs, feed_dict=dict(zip(inputs, values)))\n\n make_zip_of_tests(\n options,\n test_parameters,\n build_graph,\n build_inputs,\n expected_tf_failures=8)\n\n\n@register_make_test_function()\ndef make_minimum_tests(options):\n \"\"\"Make a set of tests to do minimum.\"\"\"\n\n test_parameters = [{\n \"input_dtype\": [tf.float32],\n \"input_shape_1\": [[], [3], [1, 100], [4, 2, 3], [5, 224, 224, 3]],\n \"input_shape_2\": [[], [3], [1, 100], [4, 2, 3], [5, 224, 224, 3]],\n }]\n\n def build_graph(parameters):\n \"\"\"Build the minimum op testing graph.\"\"\"\n input_tensor_1 = tf.placeholder(\n dtype=parameters[\"input_dtype\"],\n name=\"input_1\",\n shape=parameters[\"input_shape_1\"])\n input_tensor_2 = tf.placeholder(\n dtype=parameters[\"input_dtype\"],\n name=\"input_2\",\n shape=parameters[\"input_shape_2\"])\n\n out = tf.minimum(input_tensor_1, input_tensor_2)\n return [input_tensor_1, input_tensor_2], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n values = [\n create_tensor_data(parameters[\"input_dtype\"],\n parameters[\"input_shape_1\"]),\n create_tensor_data(parameters[\"input_dtype\"],\n parameters[\"input_shape_2\"])\n ]\n return values, sess.run(outputs, feed_dict=dict(zip(inputs, values)))\n\n make_zip_of_tests(\n options,\n test_parameters,\n build_graph,\n build_inputs,\n expected_tf_failures=8)\n\n\ndef make_binary_op_tests_func(binary_operator):\n \"\"\"Return a function that does a test on a binary operator.\"\"\"\n return lambda options: make_binary_op_tests(options, binary_operator)\n\n\n@register_make_test_function()\ndef make_add_tests(options):\n make_binary_op_tests(options, tf.add)\n\n\n@register_make_test_function()\ndef make_add_n_tests(options):\n \"\"\"Make a set of tests for AddN op.\"\"\"\n\n test_parameters = [\n {\n \"dtype\": [tf.float32, tf.int32],\n \"input_shape\": [[2, 5, 3, 1]],\n \"num_inputs\": [2, 3, 4, 5],\n },\n {\n \"dtype\": [tf.float32, tf.int32],\n \"input_shape\": [[5]],\n \"num_inputs\": [2, 3, 4, 5],\n },\n {\n \"dtype\": [tf.float32, tf.int32],\n \"input_shape\": [[]],\n \"num_inputs\": [2, 3, 4, 5],\n },\n ]\n\n def build_graph(parameters):\n \"\"\"Builds the graph given the current parameters.\"\"\"\n input_tensors = []\n for i in range(parameters[\"num_inputs\"]):\n input_tensors.append(\n tf.placeholder(\n dtype=parameters[\"dtype\"],\n name=\"input_{}\".format(i),\n shape=parameters[\"input_shape\"]))\n out = tf.add_n(input_tensors)\n return input_tensors, [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n \"\"\"Builds operand inputs for op.\"\"\"\n input_data = []\n for i in range(parameters[\"num_inputs\"]):\n input_data.append(\n create_tensor_data(parameters[\"dtype\"], parameters[\"input_shape\"]))\n return input_data, sess.run(\n outputs, feed_dict={i: d for i, d in zip(inputs, input_data)})\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n@register_make_test_function()\ndef make_div_tests(options):\n make_binary_op_tests(options, tf.div)\n\n\n@register_make_test_function()\ndef make_sub_tests(options):\n make_binary_op_tests(options, tf.subtract)\n\n\n@register_make_test_function()\ndef make_mul_tests(options):\n make_binary_op_tests(options, tf.multiply)\n\n\n@register_make_test_function()\ndef make_pow_tests(options):\n make_binary_op_tests(options, tf.pow, expected_tf_failures=7)\n\n\n@register_make_test_function()\ndef make_floor_div_tests(options):\n make_binary_op_tests(options, tf.floor_div)\n\n\n@register_make_test_function()\ndef make_floor_mod_tests(options):\n make_binary_op_tests(options, tf.floormod)\n\n\n@register_make_test_function()\ndef make_squared_difference_tests(options):\n make_binary_op_tests(options, tf.squared_difference)\n\n\n@register_make_test_function()\ndef make_gather_tests(options):\n \"\"\"Make a set of tests to do gather.\"\"\"\n\n test_parameters = [\n {\n \"params_dtype\": [tf.float32, tf.int32, tf.int64],\n \"params_shape\": [[10], [1, 2, 20]],\n \"indices_dtype\": [tf.int32, tf.int64],\n \"indices_shape\": [[3], [5]],\n \"axis\": [-1, 0, 1],\n },\n {\n # TODO(b/123895910): add Nd support for strings.\n \"params_dtype\": [tf.string],\n \"params_shape\": [[8]],\n \"indices_dtype\": [tf.int32],\n \"indices_shape\": [[3]],\n \"axis\": [0],\n }\n ]\n\n def build_graph(parameters):\n \"\"\"Build the gather op testing graph.\"\"\"\n params = tf.placeholder(\n dtype=parameters[\"params_dtype\"],\n name=\"params\",\n shape=parameters[\"params_shape\"])\n indices = tf.placeholder(\n dtype=parameters[\"indices_dtype\"],\n name=\"indices\",\n shape=parameters[\"indices_shape\"])\n axis = min(len(parameters[\"params_shape\"]), parameters[\"axis\"])\n out = tf.gather(params, indices, axis=axis)\n return [params, indices], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n params = create_tensor_data(parameters[\"params_dtype\"],\n parameters[\"params_shape\"])\n indices = create_tensor_data(parameters[\"indices_dtype\"],\n parameters[\"indices_shape\"], 0,\n parameters[\"params_shape\"][0] - 1)\n return [params, indices], sess.run(\n outputs, feed_dict=dict(zip(inputs, [params, indices])))\n\n # Note that TF can't execute with index=1 and params_shape=[10].\n make_zip_of_tests(\n options,\n test_parameters,\n build_graph,\n build_inputs,\n expected_tf_failures=12)\n\n\n@register_make_test_function()\ndef make_gather_nd_tests(options):\n \"\"\"Make a set of tests to do gather_nd.\"\"\"\n\n test_parameters = [\n {\n \"params_dtype\": [tf.float32, tf.int32, tf.int64],\n \"params_shape\": [[5, 1]],\n \"indices_dtype\": [tf.int32, tf.int64],\n \"indices_shape\": [[1, 1]],\n },\n {\n \"params_dtype\": [tf.float32, tf.int32, tf.int64],\n \"params_shape\": [[5, 5]],\n \"indices_dtype\": [tf.int32, tf.int64],\n \"indices_shape\": [[2, 1], [2, 2]],\n },\n {\n \"params_dtype\": [tf.float32, tf.int32, tf.int64],\n \"params_shape\": [[5, 5, 10]],\n \"indices_dtype\": [tf.int32, tf.int64],\n \"indices_shape\": [[3, 1], [2, 2], [2, 3], [2, 1, 3]],\n },\n ]\n\n def build_graph(parameters):\n \"\"\"Build the gather_nd op testing graph.\"\"\"\n params = tf.placeholder(\n dtype=parameters[\"params_dtype\"],\n name=\"params\",\n shape=parameters[\"params_shape\"])\n indices = tf.placeholder(\n dtype=parameters[\"indices_dtype\"],\n name=\"indices\",\n shape=parameters[\"indices_shape\"])\n out = tf.gather_nd(params, indices)\n return [params, indices], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n params = create_tensor_data(parameters[\"params_dtype\"],\n parameters[\"params_shape\"])\n indices = create_tensor_data(parameters[\"indices_dtype\"],\n parameters[\"indices_shape\"], 0,\n parameters[\"params_shape\"][0] - 1)\n return [params, indices], sess.run(\n outputs, feed_dict=dict(zip(inputs, [params, indices])))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n@register_make_test_function()\ndef make_gather_with_constant_tests(options):\n \"\"\"Make a set of test which feed a constant to gather toco.\"\"\"\n\n test_parameters = [{\n \"input_shape\": [[3]],\n \"reference_shape\": [[2]],\n }, {\n \"input_shape\": [[2, 3]],\n \"reference_shape\": [[2, 3]],\n }]\n\n def build_graph(parameters):\n \"\"\"Build a graph where the inputs to Gather are constants.\"\"\"\n reference = tf.placeholder(\n dtype=tf.int32, shape=parameters[\"reference_shape\"])\n gather_input = tf.constant(\n create_tensor_data(tf.int32, parameters[\"input_shape\"]))\n gather_indices = tf.constant([0, 1], tf.int32)\n out = tf.equal(reference, tf.gather(gather_input, gather_indices))\n return [reference], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n reference_values = np.zeros(parameters[\"reference_shape\"], dtype=np.int32)\n return [reference_values], sess.run(\n outputs, feed_dict={inputs[0]: reference_values})\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n@register_make_test_function()\ndef make_embedding_lookup_tests(options):\n \"\"\"Make a set of tests to do gather.\"\"\"\n\n test_parameters = [\n {\n \"params_dtype\": [tf.float32],\n \"params_shape\": [[10], [10, 10]],\n \"ids_dtype\": [tf.int32],\n \"ids_shape\": [[3], [5]],\n },\n ]\n\n def build_graph(parameters):\n \"\"\"Build the gather op testing graph.\"\"\"\n params = tf.placeholder(\n dtype=parameters[\"params_dtype\"],\n name=\"params\",\n shape=parameters[\"params_shape\"])\n ids = tf.placeholder(\n dtype=parameters[\"ids_dtype\"],\n name=\"ids\",\n shape=parameters[\"ids_shape\"])\n out = tf.nn.embedding_lookup(params, ids)\n return [params, ids], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n params = create_tensor_data(parameters[\"params_dtype\"],\n parameters[\"params_shape\"])\n ids = create_tensor_data(parameters[\"ids_dtype\"],\n parameters[\"ids_shape\"], 0,\n parameters[\"params_shape\"][0] - 1)\n return [params, ids], sess.run(\n outputs, feed_dict=dict(zip(inputs, [params, ids])))\n\n make_zip_of_tests(\n options,\n test_parameters,\n build_graph,\n build_inputs)\n\n\n@register_make_test_function()\ndef make_global_batch_norm_tests(options):\n \"\"\"Make a set of tests to do batch_norm_with_global_normalization.\"\"\"\n\n test_parameters = [{\n \"dtype\": [tf.float32],\n \"input_shape\": [[1, 1, 6, 2], [3, 4, 5, 4]],\n \"epsilon\": [0.1, 0.0001],\n \"scale_after\": [True, False],\n }]\n\n def build_graph(parameters):\n \"\"\"Build the global batch norm testing graph.\"\"\"\n input_shape = parameters[\"input_shape\"]\n scale_shape = input_shape[3]\n\n scale = create_tensor_data(parameters[\"dtype\"], scale_shape)\n offset = create_tensor_data(parameters[\"dtype\"], scale_shape)\n mean = create_tensor_data(parameters[\"dtype\"], scale_shape)\n variance = create_tensor_data(parameters[\"dtype\"], scale_shape)\n\n x = create_tensor_data(parameters[\"dtype\"], parameters[\"input_shape\"])\n x_norm = tf.nn.batch_norm_with_global_normalization(\n x, mean, variance, scale, offset,\n parameters[\"epsilon\"], parameters[\"scale_after\"])\n\n input_tensor = tf.placeholder(dtype=parameters[\"dtype\"], name=\"input\",\n shape=parameters[\"input_shape\"])\n out = tf.add(input_tensor, x_norm)\n return [input_tensor], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_value = create_tensor_data(parameters[\"dtype\"],\n parameters[\"input_shape\"])\n return [input_value], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_value])))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n@register_make_test_function()\ndef make_fused_batch_norm_tests(options):\n \"\"\"Make a set of tests to do fused_batch_norm.\"\"\"\n\n test_parameters = [{\n \"dtype\": [tf.float32],\n \"input_shape\": [[1, 1, 6, 2]],\n \"epsilon\": [0.001, 0.1],\n }]\n\n def build_graph(parameters):\n \"\"\"Build the testing graph for fused batch normalization.\"\"\"\n input_shape = parameters[\"input_shape\"]\n scale_shape = input_shape[3]\n\n scale = create_tensor_data(parameters[\"dtype\"], scale_shape)\n offset = create_tensor_data(parameters[\"dtype\"], scale_shape)\n mean = create_tensor_data(parameters[\"dtype\"], scale_shape)\n variance = create_tensor_data(parameters[\"dtype\"], scale_shape)\n\n x = create_tensor_data(parameters[\"dtype\"], parameters[\"input_shape\"])\n [x_norm, _, _] = tf.nn.fused_batch_norm(\n x, scale, offset, mean, variance,\n parameters[\"epsilon\"], data_format=\"NHWC\", is_training=False)\n\n input_tensor = tf.placeholder(dtype=parameters[\"dtype\"], name=\"input\",\n shape=parameters[\"input_shape\"])\n out = tf.add(input_tensor, x_norm)\n return [input_tensor], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_value = create_tensor_data(parameters[\"dtype\"],\n parameters[\"input_shape\"])\n return [input_value], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_value])))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n@register_make_test_function()\ndef make_conv_tests(options):\n \"\"\"Make a set of tests to do convolution.\"\"\"\n\n test_parameters = [\n {\n \"input_shape\": [[1, 3, 4, 3], [4, 6, 6, 1]],\n \"filter_shape\": [[1, 1], [2, 3], [3, 3]],\n \"strides\": [[1, 1, 1, 1], [1, 2, 3, 1]],\n \"dilations\": [[1, 1, 1, 1], [1, 3, 2, 1], [1, 2, 2, 1]],\n \"padding\": [\"SAME\", \"VALID\"],\n \"data_format\": [\"NHWC\"], # TODO(aselle): NCHW would be good\n \"constant_filter\": [True, False],\n \"channel_multiplier\": [1, 2],\n \"fully_quantize\": [False],\n },\n # TODO(b/134702301): The fully_quantize param is just ignored by the MLIR\n # testing path now, resulting in duplicate tests. Either ignore these\n # tests or handle it properly in the mlir_convert() function.\n {\n \"input_shape\": [[1, 3, 4, 3], [4, 6, 6, 1]],\n \"filter_shape\": [[1, 1], [2, 3], [3, 3]],\n \"strides\": [[1, 1, 1, 1], [1, 2, 3, 1]],\n \"dilations\": [[1, 1, 1, 1], [1, 3, 2, 1], [1, 2, 2, 1]],\n \"padding\": [\"SAME\", \"VALID\"],\n \"data_format\": [\"NHWC\"], # TODO(aselle): NCHW would be good\n \"constant_filter\": [True],\n \"channel_multiplier\": [1, 2],\n \"fully_quantize\": [True],\n }\n ]\n\n def get_tensor_shapes(parameters):\n input_shape = parameters[\"input_shape\"]\n filter_size = parameters[\"filter_shape\"]\n filter_shape = filter_size + [\n input_shape[3], parameters[\"channel_multiplier\"]\n ]\n return [input_shape, filter_shape]\n\n def build_graph(parameters):\n \"\"\"Build a conv graph given `parameters`.\"\"\"\n input_shape, filter_shape = get_tensor_shapes(parameters)\n input_tensor = tf.placeholder(\n dtype=tf.float32, name=\"input\", shape=input_shape)\n\n # Get filter input either as a placeholder or constants. Also get a list of\n # the input tensors that are represented as placeholders.\n if parameters[\"constant_filter\"]:\n filter_input = create_tensor_data(\n np.float32, filter_shape, min_value=-10, max_value=10)\n input_tensors = [input_tensor]\n else:\n filter_input = tf.placeholder(\n dtype=tf.float32, name=\"filter\", shape=filter_shape)\n input_tensors = [input_tensor, filter_input]\n\n out = tf.nn.conv2d(\n input_tensor,\n filter_input,\n strides=parameters[\"strides\"],\n dilations=parameters[\"dilations\"],\n padding=parameters[\"padding\"],\n data_format=parameters[\"data_format\"])\n return input_tensors, [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n # Build list of input values either containing 1 tensor (input) or 2 tensors\n # (input, filter) based on whether filter is constant or variable input.\n input_shape, filter_shape = get_tensor_shapes(parameters)\n values = [\n create_tensor_data(np.float32, input_shape, min_value=-1, max_value=1)\n ]\n if not parameters[\"constant_filter\"]:\n values.append(create_tensor_data(np.float32, filter_shape))\n return values, sess.run(outputs, feed_dict=dict(zip(inputs, values)))\n\n make_zip_of_tests(\n options,\n test_parameters,\n build_graph,\n build_inputs,\n expected_tf_failures=60)\n\n\n# Note: This is a regression test for a bug (b/122651451) that Toco incorrectly\n# erases the reduction indices array while it's shared with other ops.\n@register_make_test_function()\ndef make_l2norm_shared_epsilon_tests(options):\n \"\"\"Regression test for a bug (b/122651451).\"\"\"\n\n # Chose a set of parameters\n test_parameters = [{\n \"input_shape\": [[5, 7]],\n \"dim\": [1],\n \"epsilon\": [1e-8],\n }]\n\n def build_graph(parameters):\n input_tensor = tf.placeholder(\n dtype=tf.float32, name=\"input\", shape=parameters[\"input_shape\"])\n epsilon = tf.constant(parameters[\"epsilon\"])\n out1 = tf.nn.l2_normalize(input_tensor, parameters[\"dim\"], epsilon=epsilon)\n out2 = tf.nn.l2_normalize(input_tensor, parameters[\"dim\"], epsilon=epsilon)\n out = out1 + out2\n return [input_tensor], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_values = create_tensor_data(\n np.float32, parameters[\"input_shape\"], min_value=-4, max_value=10)\n return [input_values], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_values])))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n# Note: This is a regression test for a bug (b/112436267) that Toco incorrectly\n# fuses weights when multiple Conv2D/FULLY_CONNECTED ops share the same constant\n# weight tensor.\n@register_make_test_function()\ndef make_conv_with_shared_weights_tests(options):\n \"\"\"Make a test where 2 Conv ops shared the same constant weight tensor.\"\"\"\n\n test_parameters = [{\n \"input_shape\": [[1, 10, 10, 3]],\n \"filter_shape\": [[3, 3]],\n \"strides\": [[1, 1, 1, 1]],\n \"dilations\": [[1, 1, 1, 1]],\n \"padding\": [\"SAME\"],\n \"data_format\": [\"NHWC\"],\n \"channel_multiplier\": [1],\n }]\n\n def get_tensor_shapes(parameters):\n input_shape = parameters[\"input_shape\"]\n filter_size = parameters[\"filter_shape\"]\n filter_shape = filter_size + [\n input_shape[3], parameters[\"channel_multiplier\"]\n ]\n return [input_shape, filter_shape]\n\n def build_graph(parameters):\n \"\"\"Build a conv graph given `parameters`.\"\"\"\n input_shape, filter_shape = get_tensor_shapes(parameters)\n input_tensor = tf.placeholder(\n dtype=tf.float32, name=\"input\", shape=input_shape)\n input_tensors = [input_tensor]\n\n # Construct a constant weights tensor which will be used by both Conv2D.\n filter_tensor = tf.constant(\n create_tensor_data(np.float32, filter_shape), dtype=tf.float32)\n\n # Ensure that FuseBinaryIntoFollowingAffine works with an input which\n # is shared by multiple affine ops.\n conv_input = input_tensor + 0.1\n\n # Construct 2 Conv2D operations which use exactly the same input and\n # weights.\n result1 = tf.nn.conv2d(\n conv_input,\n filter_tensor,\n strides=parameters[\"strides\"],\n dilations=parameters[\"dilations\"],\n padding=parameters[\"padding\"],\n data_format=parameters[\"data_format\"])\n result2 = tf.nn.conv2d(\n conv_input,\n filter_tensor,\n strides=parameters[\"strides\"],\n dilations=parameters[\"dilations\"],\n padding=parameters[\"padding\"],\n data_format=parameters[\"data_format\"])\n # Add MUL ops after Conv2D ops. These MUL ops should be fused into the\n # weights of Conv2D.\n result1 = result1 * 2\n result2 = result2 * 3\n # Add the 2 results up.\n out = result1 + result2\n return input_tensors, [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n # Build list of input values either containing 1 tensor (input) or 2 tensors\n # (input, filter) based on whether filter is constant or variable input.\n input_shape, unused_filter_shape = get_tensor_shapes(parameters)\n values = [create_tensor_data(np.float32, input_shape)]\n return values, sess.run(outputs, feed_dict=dict(zip(inputs, values)))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n# Note: This is a regression test for a bug (b/112303004) that Toco incorrectly\n# transforms Conv into DepthwiseConv when two Conv ops share the same constant\n# weight tensor.\n@register_make_test_function()\ndef make_conv_to_depthwiseconv_with_shared_weights_tests(options):\n \"\"\"Make a test where 2 Conv ops shared the same constant weight tensor.\"\"\"\n\n test_parameters = [{\n \"input_shape\": [[1, 10, 10, 1]],\n \"filter_shape\": [[3, 3]],\n \"strides\": [[1, 1, 1, 1]],\n \"dilations\": [[1, 1, 1, 1]],\n \"padding\": [\"SAME\"],\n \"data_format\": [\"NHWC\"],\n \"channel_multiplier\": [3],\n }]\n\n def get_tensor_shapes(parameters):\n input_shape = parameters[\"input_shape\"]\n filter_size = parameters[\"filter_shape\"]\n filter_shape = filter_size + [\n input_shape[3], parameters[\"channel_multiplier\"]\n ]\n return [input_shape, filter_shape]\n\n def build_graph(parameters):\n \"\"\"Build a conv graph given `parameters`.\"\"\"\n input_shape, filter_shape = get_tensor_shapes(parameters)\n input_tensor = tf.placeholder(\n dtype=tf.float32, name=\"input\", shape=input_shape)\n\n # Construct a constant weights tensor which will be used by both Conv2D.\n filter_tensor = tf.constant(\n create_tensor_data(np.float32, filter_shape), dtype=tf.float32)\n input_tensors = [input_tensor]\n\n # Construct 2 Conv2D operations which use exactly the same input and\n # weights.\n result1 = tf.nn.conv2d(\n input_tensor,\n filter_tensor,\n strides=parameters[\"strides\"],\n dilations=parameters[\"dilations\"],\n padding=parameters[\"padding\"],\n data_format=parameters[\"data_format\"])\n result2 = tf.nn.conv2d(\n input_tensor,\n filter_tensor,\n strides=parameters[\"strides\"],\n dilations=parameters[\"dilations\"],\n padding=parameters[\"padding\"],\n data_format=parameters[\"data_format\"])\n # Add the 2 results up.\n out = result1 + result2\n return input_tensors, [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n # Build list of input values either containing 1 tensor (input) or 2 tensors\n # (input, filter) based on whether filter is constant or variable input.\n input_shape, unused_filter_shape = get_tensor_shapes(parameters)\n values = [create_tensor_data(np.float32, input_shape)]\n return values, sess.run(outputs, feed_dict=dict(zip(inputs, values)))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n@register_make_test_function()\ndef make_depthwiseconv_tests(options):\n \"\"\"Make a set of tests to do convolution.\"\"\"\n\n # Tensorflow only supports equal strides\n test_parameters = [\n {\n \"input_shape\": [[1, 3, 4, 3], [1, 10, 10, 3]],\n \"filter_size\": [[1, 1], [1, 2], [3, 3]],\n \"strides\": [[1, 1, 1, 1], [1, 3, 3, 1]],\n \"dilations\": [[1, 1, 1, 1], [1, 3, 2, 1], [1, 2, 2, 1]],\n \"channel_multiplier\": [1, 2],\n \"rate\": [[1, 1]],\n \"padding\": [\"SAME\", \"VALID\"],\n \"data_format\": [\"NHWC\"],\n \"constant_filter\": [True, False],\n },\n {\n \"input_shape\": [[1, 3, 4, 3]],\n \"filter_size\": [[1, 1]],\n \"strides\": [[1, 1, 2, 1]], # TF needs [1, x, x, 1]\n \"dilations\": [[1, 1, 1, 1], [1, 2, 2, 1]],\n \"channel_multiplier\": [2],\n \"rate\": [[2, 2]], # Only [1, 1] is supported\n \"padding\": [\"SAME\"],\n \"data_format\": [\"NHWC\"],\n \"constant_filter\": [True, False],\n }\n ]\n\n def get_tensor_shapes(parameters):\n input_shape = parameters[\"input_shape\"]\n filter_size = parameters[\"filter_size\"]\n filter_shape = filter_size + [\n input_shape[3], parameters[\"channel_multiplier\"]\n ]\n return [input_shape, filter_shape]\n\n def build_graph(parameters):\n \"\"\"Build a depthwise conv graph given `parameters`.\"\"\"\n input_shape, filter_shape = get_tensor_shapes(parameters)\n input_tensor = tf.placeholder(\n dtype=tf.float32, name=\"input\", shape=input_shape)\n\n # Get filter input either as a placeholder or constants. Also get a list of\n # the input tensors that are represented as placeholders.\n if parameters[\"constant_filter\"]:\n filter_input = create_tensor_data(np.float32, filter_shape)\n input_tensors = [input_tensor]\n else:\n filter_input = tf.placeholder(\n dtype=tf.float32, name=\"filter\", shape=filter_shape)\n input_tensors = [input_tensor, filter_input]\n\n out = tf.nn.depthwise_conv2d(\n input_tensor,\n filter_input,\n strides=parameters[\"strides\"],\n rate=parameters[\"rate\"],\n padding=parameters[\"padding\"],\n data_format=parameters[\"data_format\"])\n return input_tensors, [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n # Build list of input values either containing 1 tensor (input) or 2 tensors\n # (input, filter) based on whether filter is constant or variable input.\n input_shape, filter_shape = get_tensor_shapes(parameters)\n values = [create_tensor_data(np.float32, input_shape)]\n if not parameters[\"constant_filter\"]:\n values.append(create_tensor_data(np.float32, filter_shape))\n return values, sess.run(outputs, feed_dict=dict(zip(inputs, values)))\n\n make_zip_of_tests(\n options,\n test_parameters,\n build_graph,\n build_inputs,\n expected_tf_failures=4)\n\n\n@register_make_test_function()\ndef make_split_tests(options):\n \"\"\"Make a set of tests to do tf.split.\"\"\"\n\n test_parameters = [{\n \"input_shape\": [[1, 3, 4, 6], [2, 4, 1], [6, 4], [8]],\n \"num_or_size_splits\": [1, 2, 3, 4, 5],\n \"axis\": [0, 1, 2, 3, -4, -3, -2, -1],\n }]\n\n def build_graph(parameters):\n input_tensor = tf.placeholder(\n dtype=tf.float32, name=\"input\", shape=parameters[\"input_shape\"])\n out = tf.split(\n input_tensor, parameters[\"num_or_size_splits\"], parameters[\"axis\"])\n return [input_tensor], [out[0]]\n\n def build_inputs(parameters, sess, inputs, outputs):\n values = [create_tensor_data(np.float32, parameters[\"input_shape\"])]\n return values, sess.run(outputs, feed_dict=dict(zip(inputs, values)))\n\n make_zip_of_tests(\n options,\n test_parameters,\n build_graph,\n build_inputs,\n expected_tf_failures=112)\n\n\n@register_make_test_function()\ndef make_splitv_tests(options):\n \"\"\"Make a set of tests to do tf.split_v.\"\"\"\n\n test_parameters = [{\n \"input_shape\": [[1, 3, 4, 6], [2, 4, 1], [6, 4], [8]],\n \"size_splits\": [[2, 2], [1, 3], [4, 2], [5, 3],\n [-1, 1], [-1, 2], [-1, 4]],\n \"axis\": [0, 1, 2, 3, -4, -3, -2, -1],\n }]\n\n def build_graph(parameters):\n input_tensor = tf.placeholder(\n dtype=tf.float32, name=\"input\", shape=parameters[\"input_shape\"])\n out = tf.split(input_tensor, parameters[\"size_splits\"], parameters[\"axis\"])\n return [input_tensor], [out[0]]\n\n def build_inputs(parameters, sess, inputs, outputs):\n values = [create_tensor_data(np.float32, parameters[\"input_shape\"])]\n return values, sess.run(outputs, feed_dict=dict(zip(inputs, values)))\n\n make_zip_of_tests(\n options,\n test_parameters,\n build_graph,\n build_inputs,\n expected_tf_failures=158)\n\n\n@register_make_test_function()\ndef make_concat_tests(options):\n \"\"\"Make a set of tests to do concatenation.\"\"\"\n\n test_parameters = [{\n \"base_shape\": [[1, 3, 4, 3], [3, 4]],\n \"num_tensors\": [1, 2, 3, 4, 5, 6],\n \"axis\": [0, 1, 2, 3, -3, -2, -1],\n \"type\": [tf.float32, tf.uint8, tf.int32, tf.int64],\n }]\n\n def get_shape(parameters, delta):\n \"\"\"Return a tweaked version of 'base_shape'.\"\"\"\n axis = parameters[\"axis\"]\n shape = parameters[\"base_shape\"][:]\n if axis < 0:\n axis += len(shape)\n if axis < len(shape):\n shape[axis] += delta\n return shape\n\n def build_graph(parameters):\n all_tensors = []\n for n in range(0, parameters[\"num_tensors\"]):\n input_tensor = tf.placeholder(dtype=parameters[\"type\"],\n name=(\"input%d\" % n),\n shape=get_shape(parameters, n))\n all_tensors.append(input_tensor)\n out = tf.concat(all_tensors, parameters[\"axis\"])\n return all_tensors, [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n all_values = []\n for n in range(0, parameters[\"num_tensors\"]):\n input_values = create_tensor_data(\n parameters[\"type\"], get_shape(parameters, n))\n all_values.append(input_values)\n return all_values, sess.run(\n outputs, feed_dict=dict(zip(inputs, all_values)))\n\n make_zip_of_tests(\n options,\n test_parameters,\n build_graph,\n build_inputs,\n expected_tf_failures=60)\n\n\n@register_make_test_function()\ndef make_fully_connected_tests(options):\n \"\"\"Make a set of tests to do fully_connected.\"\"\"\n\n test_parameters = [{\n \"shape1\": [[3, 3]],\n \"shape2\": [[3, 3]],\n \"transpose_a\": [True, False],\n \"transpose_b\": [True, False],\n \"constant_filter\": [True, False],\n }, {\n \"shape1\": [[4, 4], [1, 4], [4]],\n \"shape2\": [[4, 4], [4, 1], [4]],\n \"transpose_a\": [False],\n \"transpose_b\": [False],\n \"constant_filter\": [True, False],\n }, {\n \"shape1\": [[40, 37]],\n \"shape2\": [[37, 40]],\n \"transpose_a\": [False],\n \"transpose_b\": [False],\n \"constant_filter\": [True, False],\n }, {\n \"shape1\": [[40, 37]],\n \"shape2\": [[40, 37]],\n \"transpose_a\": [False],\n \"transpose_b\": [True],\n \"constant_filter\": [True, False],\n }]\n\n def build_graph(parameters):\n \"\"\"Build a matmul graph given `parameters`.\"\"\"\n input_tensor1 = tf.placeholder(dtype=tf.float32, name=\"input1\",\n shape=parameters[\"shape1\"])\n\n # Get input_tensor2 either as a placeholder or constants. Also get a list of\n # the input tensors that are represented as placeholders.\n if parameters[\"constant_filter\"]:\n input_tensor2 = create_tensor_data(np.float32, parameters[\"shape2\"])\n input_tensors = [input_tensor1]\n else:\n input_tensor2 = tf.placeholder(\n dtype=tf.float32, name=\"input2\", shape=parameters[\"shape2\"])\n input_tensors = [input_tensor1, input_tensor2]\n\n out = tf.matmul(input_tensor1, input_tensor2,\n transpose_a=parameters[\"transpose_a\"],\n transpose_b=parameters[\"transpose_b\"])\n return input_tensors, [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n # Build list of input values either containing 1 tensor (input_values1) or 2\n # tensors (input_values1, input_values2) based on whether the second input\n # is a constant or variable input.\n values = [create_tensor_data(np.float32, shape=parameters[\"shape1\"])]\n if not parameters[\"constant_filter\"]:\n values.append(create_tensor_data(np.float32, parameters[\"shape2\"]))\n return values, sess.run(outputs, feed_dict=dict(zip(inputs, values)))\n\n make_zip_of_tests(\n options,\n test_parameters,\n build_graph,\n build_inputs,\n expected_tf_failures=10)\n\n\n@register_make_test_function()\ndef make_l2norm_tests(options):\n \"\"\"Make a set of tests to do l2norm.\"\"\"\n\n # Chose a set of parameters\n test_parameters = [{\n \"input_shape\": [[5, 7], [1, 1, 1, 1], [1, 3, 4, 3], [3, 15, 14, 3],\n [3, 1, 2, 4, 6], [2, 2, 3, 4, 5, 6]],\n \"dim\": [0, 1, 2, 3, [2, 3], -2],\n \"epsilon\": [None, 1e-12, 1e-3],\n }]\n\n def build_graph(parameters):\n input_tensor = tf.placeholder(\n dtype=tf.float32, name=\"input\", shape=parameters[\"input_shape\"])\n if parameters[\"epsilon\"]:\n out = tf.nn.l2_normalize(\n input_tensor, parameters[\"dim\"], epsilon=parameters[\"epsilon\"])\n else:\n out = tf.nn.l2_normalize(input_tensor, parameters[\"dim\"])\n return [input_tensor], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_values = create_tensor_data(\n np.float32, parameters[\"input_shape\"], min_value=-4, max_value=10)\n return [input_values], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_values])))\n\n make_zip_of_tests(\n options,\n test_parameters,\n build_graph,\n build_inputs,\n expected_tf_failures=9)\n\n\n@register_make_test_function()\ndef make_local_response_norm_tests(options):\n \"\"\"Make a set of tests to do local_response_norm.\"\"\"\n\n # Chose a set of parameters\n test_parameters = [{\n \"input_shape\": [[1, 1, 1, 1], [1, 3, 4, 3], [3, 15, 14, 3]],\n \"depth_radius\": [None, 0, 1, 3, 5],\n \"bias\": [None, 0.3, -0.1],\n \"alpha\": [None, 2, -3],\n \"beta\": [None, 0.25, 2],\n }]\n\n def build_graph(parameters):\n input_tensor = tf.placeholder(\n dtype=tf.float32, name=\"input\", shape=parameters[\"input_shape\"])\n out = tf.nn.local_response_normalization(\n input_tensor, depth_radius=parameters[\"depth_radius\"],\n bias=parameters[\"bias\"], alpha=parameters[\"alpha\"],\n beta=parameters[\"beta\"])\n return [input_tensor], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_values = create_tensor_data(\n np.float32, parameters[\"input_shape\"], min_value=-4, max_value=10)\n return [input_values], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_values])))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n@register_make_test_function()\ndef make_pad_tests(options):\n \"\"\"Make a set of tests to do pad.\"\"\"\n\n # TODO(nupurgarg): Add test for tf.uint8.\n test_parameters = [\n # 4D:\n {\n \"dtype\": [tf.int32, tf.int64, tf.float32],\n \"input_shape\": [[1, 1, 2, 1], [2, 1, 1, 1]],\n \"paddings\": [[[0, 0], [0, 1], [2, 3], [0, 0]], [[0, 1], [0, 0],\n [0, 0], [2, 3]]],\n \"constant_paddings\": [True, False],\n },\n # 2D:\n {\n \"dtype\": [tf.int32, tf.int64, tf.float32],\n \"input_shape\": [[1, 2]],\n \"paddings\": [[[0, 1], [2, 3]]],\n \"constant_paddings\": [True, False],\n },\n # 1D:\n {\n \"dtype\": [tf.int32],\n \"input_shape\": [[1]],\n \"paddings\": [[[1, 2]]],\n \"constant_paddings\": [False],\n },\n ]\n\n def build_graph(parameters):\n \"\"\"Build a pad graph given `parameters`.\"\"\"\n input_tensor = tf.placeholder(\n dtype=parameters[\"dtype\"],\n name=\"input\",\n shape=parameters[\"input_shape\"])\n\n # Get paddings as either a placeholder or constants.\n if parameters[\"constant_paddings\"]:\n paddings = parameters[\"paddings\"]\n input_tensors = [input_tensor]\n else:\n shape = [len(parameters[\"paddings\"]), 2]\n paddings = tf.placeholder(dtype=tf.int32, name=\"padding\", shape=shape)\n input_tensors = [input_tensor, paddings]\n\n out = tf.pad(input_tensor, paddings=paddings)\n return input_tensors, [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n values = [\n create_tensor_data(parameters[\"dtype\"], parameters[\"input_shape\"])\n ]\n if not parameters[\"constant_paddings\"]:\n values.append(np.array(parameters[\"paddings\"]))\n return values, sess.run(outputs, feed_dict=dict(zip(inputs, values)))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n@register_make_test_function()\ndef make_padv2_tests(options):\n \"\"\"Make a set of tests to do padv2.\"\"\"\n\n # TODO(nupurgarg): Add test for tf.uint8.\n test_parameters = [\n # 4D:\n {\n \"dtype\": [tf.int32, tf.int64, tf.float32],\n \"input_shape\": [[1, 1, 2, 1], [2, 1, 1, 1]],\n \"paddings\": [[[0, 0], [0, 1], [2, 3], [0, 0]], [[0, 1], [0, 0],\n [0, 0], [2, 3]]],\n \"constant_paddings\": [True, False],\n \"constant_values\": [0, 2],\n },\n # 2D:\n {\n \"dtype\": [tf.int32, tf.int64, tf.float32],\n \"input_shape\": [[1, 2]],\n \"paddings\": [[[0, 1], [2, 3]]],\n \"constant_paddings\": [True, False],\n \"constant_values\": [0, 2],\n },\n # 1D:\n {\n \"dtype\": [tf.int32],\n \"input_shape\": [[1]],\n \"paddings\": [[[0, 1]]],\n \"constant_paddings\": [False],\n \"constant_values\": [0, 2],\n },\n ]\n\n def build_graph(parameters):\n \"\"\"Build a pad graph given `parameters`.\"\"\"\n input_tensor = tf.placeholder(\n dtype=parameters[\"dtype\"],\n name=\"input\",\n shape=parameters[\"input_shape\"])\n\n # Get paddings as either a placeholder or constants.\n if parameters[\"constant_paddings\"]:\n paddings = parameters[\"paddings\"]\n input_tensors = [input_tensor]\n else:\n shape = [len(parameters[\"paddings\"]), 2]\n paddings = tf.placeholder(dtype=tf.int32, name=\"padding\", shape=shape)\n input_tensors = [input_tensor, paddings]\n\n out = tf.pad(input_tensor, paddings=paddings,\n constant_values=parameters[\"constant_values\"])\n return input_tensors, [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n values = [\n create_tensor_data(parameters[\"dtype\"], parameters[\"input_shape\"])\n ]\n if not parameters[\"constant_paddings\"]:\n values.append(np.array(parameters[\"paddings\"]))\n return values, sess.run(outputs, feed_dict=dict(zip(inputs, values)))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n@register_make_test_function()\ndef make_reshape_tests(options):\n \"\"\"Make a set of tests to do reshape.\"\"\"\n\n # All shapes below are suitable for tensors with 420 elements.\n test_parameters = [{\n \"dtype\": [tf.float32, tf.int32],\n \"input_shape\": [[3, 4, 5, 7], [4, 105], [21, 5, 2, 2], [420]],\n \"output_shape\": [[15, 28], [420], [1, -1, 5, 7], [-1]],\n \"constant_shape\": [True, False],\n }, {\n \"dtype\": [tf.float32],\n \"input_shape\": [[1]],\n \"output_shape\": [[]],\n \"constant_shape\": [True, False],\n }]\n\n def build_graph(parameters):\n input_tensor = tf.placeholder(dtype=parameters[\"dtype\"], name=\"input\",\n shape=parameters[\"input_shape\"])\n\n # Get shape as either a placeholder or constants.\n if parameters[\"constant_shape\"]:\n output_shape = parameters[\"output_shape\"]\n input_tensors = [input_tensor]\n else:\n # The shape of the shape tensor.\n shape_tensor_shape = [len(parameters[\"output_shape\"])]\n output_shape = tf.placeholder(\n dtype=tf.int32, name=\"output_shape\", shape=shape_tensor_shape)\n input_tensors = [input_tensor, output_shape]\n out = tf.reshape(input_tensor, shape=output_shape)\n return input_tensors, [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n values = [\n create_tensor_data(parameters[\"dtype\"], parameters[\"input_shape\"])\n ]\n if not parameters[\"constant_shape\"]:\n values.append(np.array(parameters[\"output_shape\"]))\n\n return values, sess.run(outputs, feed_dict=dict(zip(inputs, values)))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n@register_make_test_function()\ndef make_shape_tests(options):\n \"\"\"Make a set of tests to do shape.\"\"\"\n\n test_parameters = [{\n \"input_dtype\": [tf.float32, tf.int32],\n \"input_shape\": [[], [0], [1, 1, 1, 3], [2, 3, 4, 5], [5, 5], [10]],\n \"out_type\": [tf.int32, tf.int64],\n }]\n\n def build_graph(parameters):\n \"\"\"Build the shape op testing graph.\"\"\"\n # Note that we intentionally leave out the shape from the input placeholder\n # to prevent the Shape operation from being optimized out during conversion.\n input_value = tf.placeholder(dtype=parameters[\"input_dtype\"], name=\"input\")\n out = tf.shape(input_value, out_type=parameters[\"out_type\"])\n return [input_value], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_value = create_tensor_data(parameters[\"input_dtype\"],\n parameters[\"input_shape\"])\n return [input_value], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_value])))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n@register_make_test_function()\ndef make_rank_tests(options):\n \"\"\"Make a set of tests to do rank.\"\"\"\n\n test_parameters = [{\n \"input_dtype\": [tf.float32, tf.int32],\n \"input_shape\": [[], [0], [1, 1, 1, 3], [2, 3, 4, 5], [5, 5], [10]],\n }]\n\n def build_graph(parameters):\n \"\"\"Build the rank op testing graph.\"\"\"\n input_value = tf.placeholder(dtype=parameters[\"input_dtype\"], name=\"input\")\n out = tf.rank(input_value)\n return [input_value], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_value = create_tensor_data(parameters[\"input_dtype\"],\n parameters[\"input_shape\"])\n return [input_value], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_value])))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n@register_make_test_function()\ndef make_one_hot_tests(options):\n \"\"\"Make a set of tests to do one_hot.\"\"\"\n\n test_parameters = [{\n \"indices_type\": [tf.int32, tf.int64],\n \"indices_shape\": [[3], [4, 4], [1, 5], [5, 1]],\n \"axis\": [0, 1],\n \"dtype\": [tf.int32, tf.int64, tf.float32],\n \"provide_optional_inputs\": [True, False],\n }]\n\n def build_graph(parameters):\n indices = tf.placeholder(\n dtype=parameters[\"indices_type\"],\n name=\"indices\",\n shape=parameters[\"indices_shape\"])\n depth = tf.placeholder(dtype=tf.int32, name=\"depth\", shape=())\n\n if not parameters[\"provide_optional_inputs\"]:\n out = tf.one_hot(indices=indices, depth=depth)\n return [indices, depth], [out]\n\n on_value = tf.placeholder(\n dtype=parameters[\"dtype\"], name=\"on_value\", shape=())\n off_value = tf.placeholder(\n dtype=parameters[\"dtype\"], name=\"off_value\", shape=())\n out = tf.one_hot(\n indices=indices,\n depth=depth,\n on_value=on_value,\n off_value=off_value,\n axis=parameters[\"axis\"],\n dtype=parameters[\"dtype\"])\n return [indices, depth, on_value, off_value], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_values = [\n create_tensor_data(\n parameters[\"indices_type\"],\n shape=parameters[\"indices_shape\"],\n min_value=-1,\n max_value=10),\n create_tensor_data(tf.int32, shape=None, min_value=1, max_value=10),\n ]\n\n if parameters[\"provide_optional_inputs\"]:\n input_values.append(\n create_tensor_data(\n parameters[\"dtype\"], shape=None, min_value=1, max_value=10))\n input_values.append(\n create_tensor_data(\n parameters[\"dtype\"], shape=None, min_value=-1, max_value=0))\n\n return input_values, sess.run(\n outputs, feed_dict=dict(zip(inputs, input_values)))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n@register_make_test_function()\ndef make_resize_bilinear_tests(options):\n \"\"\"Make a set of tests to do resize_bilinear.\"\"\"\n\n test_parameters = [{\n \"dtype\": [tf.float32, tf.int32],\n \"input_shape\": [[1, 3, 4, 3], [1, 10, 2, 1]],\n \"size\": [[1, 1], [4, 3], [2, 2], [5, 6]],\n \"align_corners\": [None, True, False],\n }]\n\n def build_graph(parameters):\n input_tensor = tf.placeholder(dtype=parameters[\"dtype\"], name=\"input\",\n shape=parameters[\"input_shape\"])\n out = tf.image.resize_bilinear(input_tensor, size=parameters[\"size\"],\n align_corners=parameters[\"align_corners\"])\n return [input_tensor], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_values = create_tensor_data(parameters[\"dtype\"],\n parameters[\"input_shape\"])\n return [input_values], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_values])))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n@register_make_test_function()\ndef make_resize_nearest_neighbor_tests(options):\n \"\"\"Make a set of tests to do resize_nearest_neighbor.\"\"\"\n\n test_parameters = [{\n \"dtype\": [tf.float32, tf.int32],\n \"input_shape\": [[1, 3, 4, 3], [1, 10, 2, 1]],\n \"size\": [[1, 1], [4, 3], [2, 2], [5, 6]],\n \"align_corners\": [False],\n }]\n\n def build_graph(parameters):\n input_tensor = tf.placeholder(\n dtype=parameters[\"dtype\"],\n name=\"input\",\n shape=parameters[\"input_shape\"])\n out = tf.image.resize_nearest_neighbor(\n input_tensor,\n size=parameters[\"size\"],\n align_corners=parameters[\"align_corners\"])\n return [input_tensor], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_values = create_tensor_data(parameters[\"dtype\"],\n parameters[\"input_shape\"])\n return [input_values], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_values])))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n@register_make_test_function()\ndef make_sigmoid_tests(options):\n \"\"\"Make a set of tests to do sigmoid.\"\"\"\n\n test_parameters = [{\n \"dtype\": [tf.float32],\n \"input_shape\": [[1, 3, 4, 3], [4], [], [1, 2, 3, 4, 5, 6]],\n }]\n\n def build_graph(parameters):\n input_tensor = tf.placeholder(dtype=parameters[\"dtype\"], name=\"input\",\n shape=parameters[\"input_shape\"])\n out = tf.sigmoid(input_tensor)\n return [input_tensor], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_values = create_tensor_data(parameters[\"dtype\"],\n parameters[\"input_shape\"])\n return [input_values], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_values])))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n@register_make_test_function()\ndef make_softmax_tests(options):\n \"\"\"Make a set of tests to do softmax.\"\"\"\n\n test_parameters = [{\n \"dtype\": [tf.float32],\n \"input_shape\": [[1, 3, 4, 3], [2, 3]],\n \"dim\": [-1, 0],\n }, {\n \"dtype\": [tf.float32],\n \"input_shape\": [[4, 7]],\n \"dim\": [-1, 1],\n }]\n\n def build_graph(parameters):\n input_tensor = tf.placeholder(dtype=parameters[\"dtype\"], name=\"input\",\n shape=parameters[\"input_shape\"])\n out = tf.nn.softmax(input_tensor, dim=parameters[\"dim\"])\n return [input_tensor], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_values = create_tensor_data(parameters[\"dtype\"],\n parameters[\"input_shape\"])\n return [input_values], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_values])))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n@register_make_test_function()\ndef make_space_to_depth_tests(options):\n \"\"\"Make a set of tests to do space_to_depth.\"\"\"\n\n test_parameters = [{\n \"dtype\": [tf.float32, tf.int32, tf.uint8, tf.int64],\n \"input_shape\": [[2, 12, 24, 1]],\n \"block_size\": [2, 3, 4],\n }]\n\n def build_graph(parameters):\n input_tensor = tf.placeholder(dtype=parameters[\"dtype\"], name=\"input\",\n shape=parameters[\"input_shape\"])\n out = tf.space_to_depth(input_tensor, block_size=parameters[\"block_size\"])\n return [input_tensor], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_values = create_tensor_data(parameters[\"dtype\"],\n parameters[\"input_shape\"])\n return [input_values], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_values])))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n@register_make_test_function()\ndef make_space_to_batch_nd_tests(options):\n \"\"\"Make a set of tests to do space_to_batch_nd.\"\"\"\n\n # TODO(nupurgarg): Add test for uint8.\n test_parameters = [\n {\n \"dtype\": [tf.int32, tf.int64, tf.float32],\n \"input_shape\": [[1, 2, 2, 3], [2, 2, 4, 1]],\n \"block_shape\": [[1, 3], [2, 2]],\n \"paddings\": [[[0, 0], [0, 0]], [[0, 0], [2, 0]], [[1, 1], [1, 1]]],\n \"constant_block_shape\": [True, False],\n \"constant_paddings\": [True, False],\n },\n {\n \"dtype\": [tf.float32],\n \"input_shape\": [[2, 3, 7, 3]],\n \"block_shape\": [[1, 3], [2, 2]],\n \"paddings\": [[[0, 0], [2, 0]], [[1, 0], [1, 0]]],\n \"constant_block_shape\": [True, False],\n \"constant_paddings\": [True, False],\n },\n # Non-4D use case: 1 bath dimension, 3 spatial dimensions, 2 others.\n {\n \"dtype\": [tf.float32],\n \"input_shape\": [[1, 4, 4, 4, 1, 1]],\n \"block_shape\": [[2, 2, 2]],\n \"paddings\": [[[0, 0], [0, 0], [0, 0]]],\n \"constant_block_shape\": [True, False],\n \"constant_paddings\": [True, False],\n },\n ]\n\n def build_graph(parameters):\n \"\"\"Build a space_to_batch graph given `parameters`.\"\"\"\n input_tensor = tf.placeholder(\n dtype=parameters[\"dtype\"],\n name=\"input\",\n shape=parameters[\"input_shape\"])\n input_tensors = [input_tensor]\n\n # Get block_shape either as a const or as a placeholder (tensor).\n if parameters[\"constant_block_shape\"]:\n block_shape = parameters[\"block_shape\"]\n else:\n shape = [len(parameters[\"block_shape\"])]\n block_shape = tf.placeholder(dtype=tf.int32, name=\"shape\", shape=shape)\n input_tensors.append(block_shape)\n\n # Get paddings either as a const or as a placeholder (tensor).\n if parameters[\"constant_paddings\"]:\n paddings = parameters[\"paddings\"]\n else:\n shape = [len(parameters[\"paddings\"]), 2]\n paddings = tf.placeholder(dtype=tf.int32, name=\"paddings\", shape=shape)\n input_tensors.append(paddings)\n\n out = tf.space_to_batch_nd(input_tensor, block_shape, paddings)\n return input_tensors, [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n values = [\n create_tensor_data(parameters[\"dtype\"], parameters[\"input_shape\"])\n ]\n if not parameters[\"constant_block_shape\"]:\n values.append(np.array(parameters[\"block_shape\"]))\n if not parameters[\"constant_paddings\"]:\n values.append(np.array(parameters[\"paddings\"]))\n return values, sess.run(outputs, feed_dict=dict(zip(inputs, values)))\n\n make_zip_of_tests(\n options,\n test_parameters,\n build_graph,\n build_inputs,\n expected_tf_failures=56)\n\n\n@register_make_test_function()\ndef make_batch_to_space_nd_tests(options):\n \"\"\"Make a set of tests to do batch_to_space_nd.\"\"\"\n\n test_parameters = [\n {\n \"dtype\": [tf.float32, tf.int64, tf.int32],\n \"input_shape\": [[12, 3, 3, 1]],\n \"block_shape\": [[1, 4], [2, 2], [3, 4]],\n \"crops\": [[[0, 0], [0, 0]], [[1, 1], [1, 1]]],\n \"constant_block_shape\": [True, False],\n \"constant_crops\": [True, False],\n },\n # Single batch (no-op)\n {\n \"dtype\": [tf.float32],\n \"input_shape\": [[1, 3, 3, 1]],\n \"block_shape\": [[1, 1]],\n \"crops\": [[[0, 0], [0, 0]], [[1, 1], [1, 1]]],\n \"constant_block_shape\": [True],\n \"constant_crops\": [True],\n },\n # Non-4D use case: 1 batch dimension, 3 spatial dimensions, 2 others.\n {\n \"dtype\": [tf.float32],\n \"input_shape\": [[8, 2, 2, 2, 1, 1]],\n \"block_shape\": [[2, 2, 2]],\n \"crops\": [[[0, 0], [0, 0], [0, 0]]],\n \"constant_block_shape\": [True, False],\n \"constant_crops\": [True, False],\n },\n ]\n\n def build_graph(parameters):\n \"\"\"Build a batch_to_space graph given `parameters`.\"\"\"\n input_tensor = tf.placeholder(\n dtype=parameters[\"dtype\"],\n name=\"input\",\n shape=parameters[\"input_shape\"])\n input_tensors = [input_tensor]\n\n # Get block_shape either as a const or as a placeholder (tensor).\n if parameters[\"constant_block_shape\"]:\n block_shape = parameters[\"block_shape\"]\n else:\n shape = [len(parameters[\"block_shape\"])]\n block_shape = tf.placeholder(dtype=tf.int32, name=\"shape\", shape=shape)\n input_tensors.append(block_shape)\n\n # Get crops either as a const or as a placeholder (tensor).\n if parameters[\"constant_crops\"]:\n crops = parameters[\"crops\"]\n else:\n shape = [len(parameters[\"crops\"]), 2]\n crops = tf.placeholder(dtype=tf.int32, name=\"crops\", shape=shape)\n input_tensors.append(crops)\n\n out = tf.batch_to_space_nd(input_tensor, block_shape, crops)\n return input_tensors, [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n values = [\n create_tensor_data(parameters[\"dtype\"], parameters[\"input_shape\"])\n ]\n if not parameters[\"constant_block_shape\"]:\n values.append(np.array(parameters[\"block_shape\"]))\n if not parameters[\"constant_crops\"]:\n values.append(np.array(parameters[\"crops\"]))\n return values, sess.run(outputs, feed_dict=dict(zip(inputs, values)))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n@register_make_test_function()\ndef make_transpose_tests(options):\n \"\"\"Make a set of tests to do transpose.\"\"\"\n\n # TODO(nupurgarg): Add test for uint8.\n test_parameters = [{\n \"dtype\": [tf.int32, tf.int64, tf.float32],\n \"input_shape\": [[2, 2, 3]],\n \"perm\": [[0, 1, 2], [0, 2, 1]],\n \"constant_perm\": [True, False],\n }, {\n \"dtype\": [tf.float32],\n \"input_shape\": [[1, 2, 3, 4]],\n \"perm\": [[0, 1, 2, 3], [3, 0, 1, 2]],\n \"constant_perm\": [True, False],\n }, {\n \"dtype\": [tf.float32],\n \"input_shape\": [[1, 2, 3, 4, 5]],\n \"perm\": [[4, 3, 2, 1, 0]],\n \"constant_perm\": [True, False],\n }]\n\n def build_graph(parameters):\n \"\"\"Build a transpose graph given `parameters`.\"\"\"\n input_tensor = tf.placeholder(\n dtype=parameters[\"dtype\"],\n name=\"input\",\n shape=parameters[\"input_shape\"])\n\n if parameters[\"constant_perm\"]:\n perm = parameters[\"perm\"]\n input_tensors = [input_tensor]\n else:\n shape = [len(parameters[\"perm\"]), 2]\n perm = tf.placeholder(dtype=tf.int32, name=\"perm\", shape=shape)\n input_tensors = [input_tensor, perm]\n\n out = tf.transpose(input_tensor, perm=perm)\n return input_tensors, [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n values = [\n create_tensor_data(parameters[\"dtype\"], parameters[\"input_shape\"])\n ]\n if not parameters[\"constant_perm\"]:\n values.append(np.array(parameters[\"perm\"]))\n return values, sess.run(outputs, feed_dict=dict(zip(inputs, values)))\n\n make_zip_of_tests(\n options,\n test_parameters,\n build_graph,\n build_inputs,\n expected_tf_failures=9)\n\n\n@register_make_test_function()\ndef make_squeeze_tests(options):\n \"\"\"Make a set of tests to do squeeze.\"\"\"\n\n test_parameters = [{\n \"dtype\": [tf.int32, tf.float32, tf.int64],\n \"input_shape\": [[1, 2, 1, 3, 1, 4, 1, 1]],\n \"axis\": [\n None, [], [0, 2], [4, 7], [-1, 0, 2, 0, 7, -6], [1], [2, 3, 2],\n [-1, -2, -4, -6, -8], [0, 2, 4, 6, 7], [7, 6, 4, 2, 0], [6, 6],\n [0, 1, 2, 3, 4, 5, 6, 7], [-2, -3, 1, 0, 7, -5]\n ],\n }, {\n \"dtype\": [tf.int32, tf.float32, tf.int64],\n \"input_shape\": [[1]],\n \"axis\": [None, [], [0], [-1]],\n }, {\n \"dtype\": [tf.int32, tf.float32, tf.int64],\n \"input_shape\": [[1, 1, 1, 1, 1]],\n \"axis\": [None, [], [0], [3, 0], [-2, 0, 3, 2]],\n }]\n\n def build_graph(parameters):\n input_tensor = tf.placeholder(\n dtype=parameters[\"dtype\"],\n name=\"input\",\n shape=parameters[\"input_shape\"])\n out = tf.squeeze(input_tensor, axis=parameters[\"axis\"])\n return [input_tensor], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_values = create_tensor_data(parameters[\"dtype\"],\n parameters[\"input_shape\"])\n return [input_values], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_values])))\n\n make_zip_of_tests(\n options,\n test_parameters,\n build_graph,\n build_inputs,\n expected_tf_failures=12)\n\n\n@register_make_test_function()\ndef make_squeeze_transpose_tests(options):\n \"\"\"Make a set of tests to do squeeze followed by transpose.\"\"\"\n\n test_parameters = [{\n \"dtype\": [tf.int32, tf.float32, tf.int64],\n \"input_shape\": [[1, 4, 10, 1]],\n \"axis\": [[-1], [3]],\n }]\n\n def build_graph(parameters):\n input_tensor = tf.placeholder(\n dtype=parameters[\"dtype\"],\n name=\"input\",\n shape=parameters[\"input_shape\"])\n out = tf.squeeze(input_tensor, axis=parameters[\"axis\"])\n out = tf.transpose(out, perm=[1, 2])\n return [input_tensor], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_values = create_tensor_data(parameters[\"dtype\"],\n parameters[\"input_shape\"])\n return [input_values], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_values])))\n\n make_zip_of_tests(\n options,\n test_parameters,\n build_graph,\n build_inputs,\n expected_tf_failures=0)\n\n\ndef _make_strided_slice_tests(options, test_parameters,\n expected_tf_failures=0):\n \"\"\"Utility function to make strided_slice_tests based on parameters.\"\"\"\n\n def build_graph(parameters):\n \"\"\"Build graph for stride_slice test.\"\"\"\n input_tensor = tf.placeholder(\n dtype=parameters[\"dtype\"],\n name=\"input\",\n shape=parameters[\"input_shape\"])\n if parameters[\"constant_indices\"]:\n begin = parameters[\"begin\"]\n end = parameters[\"end\"]\n strides = parameters[\"strides\"]\n tensors = [input_tensor]\n else:\n begin = tf.placeholder(\n dtype=parameters[\"index_type\"],\n name=\"begin\",\n shape=[len(parameters[\"input_shape\"])])\n end = tf.placeholder(\n dtype=parameters[\"index_type\"],\n name=\"end\",\n shape=[len(parameters[\"input_shape\"])])\n strides = (\n tf.placeholder(\n dtype=parameters[\"index_type\"],\n name=\"strides\",\n shape=[len(parameters[\"input_shape\"])])\n if parameters[\"strides\"] is not None else None)\n tensors = [input_tensor, begin, end]\n if strides is not None:\n tensors.append(strides)\n out = tf.strided_slice(\n input_tensor,\n begin,\n end,\n strides,\n begin_mask=parameters[\"begin_mask\"],\n end_mask=parameters[\"end_mask\"])\n return tensors, [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n \"\"\"Build inputs for stride_slice test.\"\"\"\n input_values = create_tensor_data(parameters[\"dtype\"],\n parameters[\"input_shape\"])\n index_type = _TF_TYPE_INFO[parameters[\"index_type\"]][0]\n values = [input_values]\n if not parameters[\"constant_indices\"]:\n begin_values = np.array(parameters[\"begin\"]).astype(index_type)\n end_values = np.array(parameters[\"end\"]).astype(index_type)\n stride_values = (\n np.array(parameters[\"strides\"]).astype(index_type)\n if parameters[\"strides\"] is not None else None)\n values.append(begin_values)\n values.append(end_values)\n if stride_values is not None:\n values.append(stride_values)\n\n return values, sess.run(outputs, feed_dict=dict(zip(inputs, values)))\n\n make_zip_of_tests(\n options,\n test_parameters,\n build_graph,\n build_inputs,\n expected_tf_failures=expected_tf_failures)\n\n\n@register_make_test_function()\ndef make_strided_slice_tests(options):\n \"\"\"Make a set of tests to do strided_slice.\"\"\"\n\n # TODO(soroosh): add test/support for uint8.\n test_parameters = [\n # 4-D (basic cases with const/non-const indices).\n {\n \"dtype\": [tf.float32, tf.int32, tf.int64],\n \"index_type\": [tf.int32],\n \"input_shape\": [[12, 2, 2, 5]],\n \"strides\": [None, [2, 1, 3, 1]],\n \"begin\": [[0, 0, 0, 0]],\n \"end\": [[12, 2, 2, 5]],\n \"begin_mask\": [None],\n \"end_mask\": [None],\n \"shrink_axis_mask\": [None],\n \"constant_indices\": [False, True],\n },\n # 4-D with non-trivial begin & end.\n {\n \"dtype\": [tf.float32],\n \"index_type\": [tf.int32],\n \"input_shape\": [[12, 2, 2, 5]],\n \"begin\": [[0, 0, 0, 0], [1, 0, 1, 0]],\n \"end\": [[8, 2, 2, 3], [12, 2, 2, 5]],\n \"strides\": [None, [2, 1, 3, 1]],\n \"begin_mask\": [None, 8],\n \"end_mask\": [None, 3],\n \"shrink_axis_mask\": [None, 15, -1],\n \"constant_indices\": [True],\n },\n # Begin, end, strides dim are different from input shape\n {\n \"dtype\": [tf.float32],\n \"index_type\": [tf.int32],\n \"input_shape\": [[12, 2, 2, 5]],\n \"begin\": [[0]],\n \"end\": [[1]],\n \"strides\": [None, [1]],\n \"begin_mask\": [0],\n \"end_mask\": [0],\n \"shrink_axis_mask\": [1],\n \"constant_indices\": [True],\n },\n # 2-D\n {\n \"dtype\": [tf.float32],\n \"index_type\": [tf.int32],\n \"input_shape\": [[2, 3]],\n \"begin\": [[0, 0]],\n \"end\": [[2, 2]],\n \"strides\": [None, [2, 2]],\n \"begin_mask\": [None, 1, 2],\n \"end_mask\": [None, 1, 2],\n \"shrink_axis_mask\": [None, 1, 2, 3, -1],\n \"constant_indices\": [False, True],\n },\n # Negative strides\n {\n \"dtype\": [tf.float32],\n \"index_type\": [tf.int32],\n \"input_shape\": [[2, 3]],\n \"begin\": [[0, -1]],\n \"end\": [[2, -3]],\n \"strides\": [[1, -1]],\n \"begin_mask\": [None, 1, 2],\n \"end_mask\": [None, 1, 2],\n \"shrink_axis_mask\": [None, 1, 2, 3, -1],\n \"constant_indices\": [False],\n },\n ]\n _make_strided_slice_tests(options, test_parameters, expected_tf_failures=2)\n\n\n@register_make_test_function()\ndef make_strided_slice_1d_exhaustive_tests(options):\n \"\"\"Make a set of exhaustive tests for 1D strided_slice.\"\"\"\n test_parameters = [\n # 1-D Exhaustive\n {\n \"dtype\": [tf.float32],\n \"index_type\": [tf.int32],\n \"input_shape\": [[3]],\n \"begin\": [[-2], [-1], [0], [1], [2]],\n \"end\": [[-2], [-1], [0], [1], [2]],\n \"strides\": [[-2], [-1], [1], [2]],\n \"begin_mask\": [0, 1],\n \"end_mask\": [0, 1],\n \"shrink_axis_mask\": [0],\n \"constant_indices\": [False],\n },\n ]\n _make_strided_slice_tests(options, test_parameters)\n\n\n# TODO(b/137615945): Expand the test coverage of this one and remove the old\n# ones.\n@register_make_test_function()\ndef make_strided_slice_np_style_tests(options):\n \"\"\"Make a set of tests to test strided_slice in np style.\"\"\"\n\n test_parameters = [\n {\n \"dtype\": [tf.float32],\n \"new_axis_num\": [0, 1, 2],\n \"shape\": [[12, 7], [33]],\n \"stride\": [1, 2, 3],\n \"use_begin_end_mask\": [True, False],\n # share between begin and end to avoid creating too many combinations.\n \"begin_end_offset\": [0, 1, 3]\n },\n ]\n\n def build_strided_slice_spec(parameters):\n \"\"\"Build strided_slice spec.\n\n Args:\n parameters: Test configurations.\n\n Returns:\n strided_slice spec, e.g., [2:3, :] or [tf.newaxis, :, tf.newaxis].\n \"\"\"\n shape = parameters[\"shape\"]\n new_axis_num = parameters[\"new_axis_num\"]\n insert_new_axis_array = [False] * len(shape)\n for _ in range(new_axis_num):\n insert_loc = np.random.randint(0, len(insert_new_axis_array) + 1)\n insert_new_axis_array.insert(insert_loc, True)\n slice_spec = []\n index = 0\n for insert_new_axis in insert_new_axis_array:\n if insert_new_axis:\n slice_spec.append(tf.newaxis)\n else:\n # Random pop up begin/end/strides or just use \":\"\n if parameters[\"use_begin_end_mask\"]:\n # use slice(None), means use all values, equivalent of \":\".\n slice_spec.append(slice(None))\n else:\n # Begin.\n begin = parameters[\"begin_end_offset\"]\n # End.\n end = shape[index] - parameters[\"begin_end_offset\"]\n # Strides.\n stride = parameters[\"stride\"]\n slice_spec.append(slice(begin, end, stride))\n index += 1\n return slice_spec\n\n def build_graph(parameters):\n \"\"\"Build a simple graph with np style strided_slice.\"\"\"\n input_value = tf.placeholder(\n dtype=parameters[\"dtype\"], shape=parameters[\"shape\"])\n out = input_value.__getitem__(build_strided_slice_spec(parameters))\n return [input_value], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_value = create_tensor_data(parameters[\"dtype\"], parameters[\"shape\"])\n return [input_value], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_value])))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n# For verifying https://github.com/tensorflow/tensorflow/issues/23599\n# TODO(chaomei): refactor the test to cover more cases, like negative stride,\n# negative array index etc.\n@register_make_test_function()\ndef make_resolve_constant_strided_slice_tests(options):\n \"\"\"Make a set of tests to show strided_slice yields incorrect results.\"\"\"\n\n test_parameters = [{\n \"unused_iteration_counter\": [1],\n }]\n\n def build_graph(parameters):\n \"\"\"Build the strided_slice op testing graph.\"\"\"\n del parameters\n input_values = tf.placeholder(dtype=tf.float32, shape=[4, 2])\n data = tf.constant([[0, 1, 2, 3],\n [4, 5, 6, 7],\n [8, 9, 10, 11],\n [12, 13, 14, 15]], tf.float32)\n return [input_values], [input_values + data[:, :2]]\n\n def build_inputs(parameters, sess, inputs, outputs):\n del parameters\n input_values = np.zeros([4, 2], dtype=np.float32)\n return [input_values], sess.run(\n outputs, feed_dict={inputs[0]: input_values})\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n@register_make_test_function()\ndef make_lstm_tests(options):\n \"\"\"Make a set of tests to do basic Lstm cell.\"\"\"\n\n test_parameters = [\n {\n \"dtype\": [tf.float32],\n \"num_batchs\": [1],\n \"time_step_size\": [1],\n \"input_vec_size\": [3],\n \"num_cells\": [4],\n \"split_tflite_lstm_inputs\": [False],\n },\n ]\n\n def build_graph(parameters):\n \"\"\"Build a simple graph with BasicLSTMCell.\"\"\"\n\n num_batchs = parameters[\"num_batchs\"]\n time_step_size = parameters[\"time_step_size\"]\n input_vec_size = parameters[\"input_vec_size\"]\n num_cells = parameters[\"num_cells\"]\n inputs_after_split = []\n for i in xrange(time_step_size):\n one_timestamp_input = tf.placeholder(\n dtype=parameters[\"dtype\"],\n name=\"split_{}\".format(i),\n shape=[num_batchs, input_vec_size])\n inputs_after_split.append(one_timestamp_input)\n # Currently lstm identifier has a few limitations: only supports\n # forget_bias == 0, inner state activation == tanh.\n # TODO(zhixianyan): Add another test with forget_bias == 1.\n # TODO(zhixianyan): Add another test with relu as activation.\n lstm_cell = tf.contrib.rnn.BasicLSTMCell(\n num_cells, forget_bias=0.0, state_is_tuple=True)\n cell_outputs, _ = rnn.static_rnn(\n lstm_cell, inputs_after_split, dtype=tf.float32)\n out = cell_outputs[-1]\n return inputs_after_split, [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n \"\"\"Feed inputs, assign variables, and freeze graph.\"\"\"\n\n with tf.variable_scope(\"\", reuse=True):\n kernel = tf.get_variable(\"rnn/basic_lstm_cell/kernel\")\n bias = tf.get_variable(\"rnn/basic_lstm_cell/bias\")\n kernel_values = create_tensor_data(\n parameters[\"dtype\"], [kernel.shape[0], kernel.shape[1]], -1, 1)\n bias_values = create_tensor_data(parameters[\"dtype\"], [bias.shape[0]], 0,\n 1)\n sess.run(tf.group(kernel.assign(kernel_values), bias.assign(bias_values)))\n\n num_batchs = parameters[\"num_batchs\"]\n time_step_size = parameters[\"time_step_size\"]\n input_vec_size = parameters[\"input_vec_size\"]\n input_values = []\n for _ in xrange(time_step_size):\n tensor_data = create_tensor_data(parameters[\"dtype\"],\n [num_batchs, input_vec_size], 0, 1)\n input_values.append(tensor_data)\n out = sess.run(outputs, feed_dict=dict(zip(inputs, input_values)))\n return input_values, out\n\n # TODO(zhixianyan): Automatically generate rnn_states for lstm cell.\n extra_toco_options = ExtraTocoOptions()\n extra_toco_options.rnn_states = (\n \"{state_array:rnn/BasicLSTMCellZeroState/zeros,\"\n \"back_edge_source_array:rnn/basic_lstm_cell/Add_1,size:4},\"\n \"{state_array:rnn/BasicLSTMCellZeroState/zeros_1,\"\n \"back_edge_source_array:rnn/basic_lstm_cell/Mul_2,size:4}\")\n\n make_zip_of_tests(\n options,\n test_parameters,\n build_graph,\n build_inputs,\n extra_toco_options,\n use_frozen_graph=True)\n\n\ndef make_l2_pool(input_tensor, ksize, strides, padding, data_format):\n \"\"\"Given an input perform a sequence of TensorFlow ops to produce l2pool.\"\"\"\n return tf.sqrt(tf.nn.avg_pool(\n tf.square(input_tensor), ksize=ksize, strides=strides,\n padding=padding, data_format=data_format))\n\n\n@register_make_test_function()\ndef make_topk_tests(options):\n \"\"\"Make a set of tests to do topk.\"\"\"\n\n test_parameters = [{\n \"input_dtype\": [tf.float32, tf.int32],\n \"input_shape\": [[10], [5, 20]],\n \"input_k\": [None, 1, 3],\n }]\n\n def build_graph(parameters):\n \"\"\"Build the topk op testing graph.\"\"\"\n input_value = tf.placeholder(\n dtype=parameters[\"input_dtype\"],\n name=\"input\",\n shape=parameters[\"input_shape\"])\n if parameters[\"input_k\"] is not None:\n k = tf.placeholder(dtype=tf.int32, name=\"input_k\", shape=[])\n inputs = [input_value, k]\n else:\n k = tf.constant(3, name=\"k\")\n inputs = [input_value]\n out = tf.nn.top_k(input_value, k)\n return inputs, [out[1]]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_value = create_tensor_data(parameters[\"input_dtype\"],\n parameters[\"input_shape\"])\n if parameters[\"input_k\"] is not None:\n k = np.array(parameters[\"input_k\"], dtype=np.int32)\n return [input_value, k], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_value, k])))\n else:\n return [input_value], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_value])))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n@register_make_test_function()\ndef make_arg_min_max_tests(options):\n \"\"\"Make a set of tests to do arg_max.\"\"\"\n\n test_parameters = [{\n \"input_dtype\": [tf.float32, tf.int32],\n \"input_shape\": [[], [1, 1, 1, 3], [2, 3, 4, 5], [2, 3, 3], [5, 5], [10]],\n \"output_type\": [tf.int32, tf.int64],\n \"is_arg_max\": [True],\n }]\n\n def build_graph(parameters):\n \"\"\"Build the topk op testing graph.\"\"\"\n input_value = tf.placeholder(\n dtype=parameters[\"input_dtype\"],\n name=\"input\",\n shape=parameters[\"input_shape\"])\n axis = random.randint(0, max(len(parameters[\"input_shape\"]) - 1, 0))\n if parameters[\"is_arg_max\"]:\n out = tf.arg_max(input_value, axis, output_type=parameters[\"output_type\"])\n else:\n out = tf.arg_min(input_value, axis, output_type=parameters[\"output_type\"])\n return [input_value], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_value = create_tensor_data(parameters[\"input_dtype\"],\n parameters[\"input_shape\"])\n return [input_value], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_value])))\n\n make_zip_of_tests(\n options,\n test_parameters,\n build_graph,\n build_inputs,\n expected_tf_failures=4)\n\n\n@register_make_test_function()\ndef make_equal_tests(options):\n \"\"\"Make a set of tests to do equal.\"\"\"\n\n test_parameters = [{\n \"input_dtype\": [tf.float32, tf.int32, tf.int64],\n \"input_shape_pair\": [([], []),\n ([1, 1, 1, 3], [1, 1, 1, 3]),\n ([2, 3, 4, 5], [2, 3, 4, 5]), ([2, 3, 3], [2, 3]),\n ([5, 5], [1]), ([10], [2, 4, 10])],\n }]\n\n def build_graph(parameters):\n \"\"\"Build the equal op testing graph.\"\"\"\n input_value1 = tf.placeholder(\n dtype=parameters[\"input_dtype\"],\n name=\"input1\",\n shape=parameters[\"input_shape_pair\"][0])\n input_value2 = tf.placeholder(\n dtype=parameters[\"input_dtype\"],\n name=\"input2\",\n shape=parameters[\"input_shape_pair\"][1])\n out = tf.equal(input_value1, input_value2)\n return [input_value1, input_value2], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_value1 = create_tensor_data(parameters[\"input_dtype\"],\n parameters[\"input_shape_pair\"][0])\n input_value2 = create_tensor_data(parameters[\"input_dtype\"],\n parameters[\"input_shape_pair\"][1])\n return [input_value1, input_value2], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_value1, input_value2])))\n\n make_zip_of_tests(\n options,\n test_parameters,\n build_graph,\n build_inputs,\n expected_tf_failures=3)\n\n\n@register_make_test_function()\ndef make_not_equal_tests(options):\n \"\"\"Make a set of tests to do not equal.\"\"\"\n\n test_parameters = [{\n \"input_dtype\": [tf.float32, tf.int32, tf.int64],\n \"input_shape_pair\": [([1, 1, 1, 3], [1, 1, 1, 3]),\n ([2, 3, 4, 5], [2, 3, 4, 5]), ([2, 3, 3], [2, 3]),\n ([5, 5], [1]), ([10], [2, 4, 10])],\n }]\n\n def build_graph(parameters):\n \"\"\"Build the not euqal op testing graph.\"\"\"\n input_value1 = tf.placeholder(\n dtype=parameters[\"input_dtype\"],\n name=\"input1\",\n shape=parameters[\"input_shape_pair\"][0])\n input_value2 = tf.placeholder(\n dtype=parameters[\"input_dtype\"],\n name=\"input2\",\n shape=parameters[\"input_shape_pair\"][1])\n out = tf.not_equal(input_value1, input_value2)\n return [input_value1, input_value2], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_value1 = create_tensor_data(parameters[\"input_dtype\"],\n parameters[\"input_shape_pair\"][0])\n input_value2 = create_tensor_data(parameters[\"input_dtype\"],\n parameters[\"input_shape_pair\"][1])\n return [input_value1, input_value2], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_value1, input_value2])))\n\n make_zip_of_tests(\n options,\n test_parameters,\n build_graph,\n build_inputs,\n expected_tf_failures=3)\n\n\n@register_make_test_function()\ndef make_greater_tests(options):\n \"\"\"Make a set of tests to do greater.\"\"\"\n\n test_parameters = [{\n \"input_dtype\": [tf.float32, tf.int32, tf.int64],\n \"input_shape_pair\": [([1, 1, 1, 3], [1, 1, 1, 3]),\n ([2, 3, 4, 5], [2, 3, 4, 5]), ([2, 3, 3], [2, 3]),\n ([5, 5], [1]), ([10], [2, 4, 10])],\n }]\n\n def build_graph(parameters):\n \"\"\"Build the greater op testing graph.\"\"\"\n input_value1 = tf.placeholder(\n dtype=parameters[\"input_dtype\"],\n name=\"input1\",\n shape=parameters[\"input_shape_pair\"][0])\n input_value2 = tf.placeholder(\n dtype=parameters[\"input_dtype\"],\n name=\"input2\",\n shape=parameters[\"input_shape_pair\"][1])\n out = tf.greater(input_value1, input_value2)\n return [input_value1, input_value2], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_value1 = create_tensor_data(parameters[\"input_dtype\"],\n parameters[\"input_shape_pair\"][0])\n input_value2 = create_tensor_data(parameters[\"input_dtype\"],\n parameters[\"input_shape_pair\"][1])\n return [input_value1, input_value2], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_value1, input_value2])))\n\n make_zip_of_tests(\n options,\n test_parameters,\n build_graph,\n build_inputs,\n expected_tf_failures=3)\n\n\n@register_make_test_function()\ndef make_greater_equal_tests(options):\n \"\"\"Make a set of tests to do greater_equal.\"\"\"\n\n test_parameters = [{\n \"input_dtype\": [tf.float32, tf.int32, tf.int64],\n \"input_shape_pair\": [([1, 1, 1, 3], [1, 1, 1, 3]),\n ([2, 3, 4, 5], [2, 3, 4, 5]), ([2, 3, 3], [2, 3]),\n ([5, 5], [1]), ([10], [2, 4, 10])],\n }]\n\n def build_graph(parameters):\n \"\"\"Build the greater_equal op testing graph.\"\"\"\n input_value1 = tf.placeholder(\n dtype=parameters[\"input_dtype\"],\n name=\"input1\",\n shape=parameters[\"input_shape_pair\"][0])\n input_value2 = tf.placeholder(\n dtype=parameters[\"input_dtype\"],\n name=\"input2\",\n shape=parameters[\"input_shape_pair\"][1])\n out = tf.greater_equal(input_value1, input_value2)\n return [input_value1, input_value2], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_value1 = create_tensor_data(parameters[\"input_dtype\"],\n parameters[\"input_shape_pair\"][0])\n input_value2 = create_tensor_data(parameters[\"input_dtype\"],\n parameters[\"input_shape_pair\"][1])\n return [input_value1, input_value2], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_value1, input_value2])))\n\n make_zip_of_tests(\n options,\n test_parameters,\n build_graph,\n build_inputs,\n expected_tf_failures=3)\n\n\n@register_make_test_function()\ndef make_less_tests(options):\n \"\"\"Make a set of tests to do less.\"\"\"\n\n test_parameters = [{\n \"input_dtype\": [tf.float32, tf.int32, tf.int64],\n \"input_shape_pair\": [([1, 1, 1, 3], [1, 1, 1, 3]),\n ([2, 3, 4, 5], [2, 3, 4, 5]), ([2, 3, 3], [2, 3]),\n ([5, 5], [1]), ([10], [2, 4, 10])],\n }]\n\n def build_graph(parameters):\n \"\"\"Build the less op testing graph.\"\"\"\n input_value1 = tf.placeholder(\n dtype=parameters[\"input_dtype\"],\n name=\"input1\",\n shape=parameters[\"input_shape_pair\"][0])\n input_value2 = tf.placeholder(\n dtype=parameters[\"input_dtype\"],\n name=\"input2\",\n shape=parameters[\"input_shape_pair\"][1])\n out = tf.less(input_value1, input_value2)\n return [input_value1, input_value2], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_value1 = create_tensor_data(parameters[\"input_dtype\"],\n parameters[\"input_shape_pair\"][0])\n input_value2 = create_tensor_data(parameters[\"input_dtype\"],\n parameters[\"input_shape_pair\"][1])\n return [input_value1, input_value2], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_value1, input_value2])))\n\n make_zip_of_tests(\n options,\n test_parameters,\n build_graph,\n build_inputs,\n expected_tf_failures=3)\n\n\n@register_make_test_function()\ndef make_less_equal_tests(options):\n \"\"\"Make a set of tests to do less_equal.\"\"\"\n\n test_parameters = [{\n \"input_dtype\": [tf.float32, tf.int32, tf.int64],\n \"input_shape_pair\": [([1, 1, 1, 3], [1, 1, 1, 3]),\n ([2, 3, 4, 5], [2, 3, 4, 5]), ([2, 3, 3], [2, 3]),\n ([5, 5], [1]), ([10], [2, 4, 10])],\n }]\n\n def build_graph(parameters):\n \"\"\"Build the less_equal op testing graph.\"\"\"\n input_value1 = tf.placeholder(\n dtype=parameters[\"input_dtype\"],\n name=\"input1\",\n shape=parameters[\"input_shape_pair\"][0])\n input_value2 = tf.placeholder(\n dtype=parameters[\"input_dtype\"],\n name=\"input2\",\n shape=parameters[\"input_shape_pair\"][1])\n out = tf.less_equal(input_value1, input_value2)\n return [input_value1, input_value2], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_value1 = create_tensor_data(parameters[\"input_dtype\"],\n parameters[\"input_shape_pair\"][0])\n input_value2 = create_tensor_data(parameters[\"input_dtype\"],\n parameters[\"input_shape_pair\"][1])\n return [input_value1, input_value2], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_value1, input_value2])))\n\n make_zip_of_tests(\n options,\n test_parameters,\n build_graph,\n build_inputs,\n expected_tf_failures=3)\n\n\n@register_make_test_function()\ndef make_floor_tests(options):\n \"\"\"Make a set of tests to do floor.\"\"\"\n\n test_parameters = [{\n \"input_dtype\": [tf.float32],\n \"input_shape\": [[], [1], [1, 2], [5, 6, 7, 8], [3, 4, 5, 6]],\n }]\n\n def build_graph(parameters):\n \"\"\"Build the floor op testing graph.\"\"\"\n input_value = tf.placeholder(\n dtype=parameters[\"input_dtype\"],\n name=\"input1\",\n shape=parameters[\"input_shape\"])\n out = tf.floor(input_value)\n return [input_value], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_value = create_tensor_data(parameters[\"input_dtype\"],\n parameters[\"input_shape\"])\n return [input_value], sess.run(outputs, feed_dict={inputs[0]: input_value})\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n@register_make_test_function()\ndef make_ceil_tests(options):\n \"\"\"Make a set of tests to do ceil.\"\"\"\n\n test_parameters = [{\n \"input_dtype\": [tf.float32],\n \"input_shape\": [[], [1], [1, 2], [5, 6, 7, 8], [3, 4, 5, 6]],\n }]\n\n def build_graph(parameters):\n \"\"\"Build the ceil op testing graph.\"\"\"\n input_value = tf.placeholder(\n dtype=parameters[\"input_dtype\"],\n name=\"input1\",\n shape=parameters[\"input_shape\"])\n out = tf.ceil(input_value)\n return [input_value], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_value = create_tensor_data(parameters[\"input_dtype\"],\n parameters[\"input_shape\"])\n return [input_value], sess.run(\n outputs, feed_dict={inputs[0]: input_value})\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n@register_make_test_function()\ndef make_round_tests(options):\n \"\"\"Build the round op testing graph.\"\"\"\n\n test_parameters = [{\n \"input_dtype\": [tf.float32],\n \"input_shape\": [[], [1], [1, 2], [5, 6, 7, 8], [3, 4, 5, 6]],\n }]\n\n def build_graph(parameters):\n \"\"\"Build the round op testing graph.\"\"\"\n input_value = tf.placeholder(\n dtype=parameters[\"input_dtype\"],\n name=\"input1\",\n shape=parameters[\"input_shape\"])\n out = tf.round(input_value)\n return [input_value], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_value = create_tensor_data(parameters[\"input_dtype\"],\n parameters[\"input_shape\"])\n return [input_value], sess.run(outputs, feed_dict={inputs[0]: input_value})\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n@register_make_test_function()\ndef make_neg_tests(options):\n \"\"\"Make a set of tests to do neg.\"\"\"\n\n test_parameters = [{\n \"input_dtype\": [tf.float32, tf.int32],\n \"input_shape\": [[1, 3, 4, 3], [5], []],\n }]\n\n def build_graph(parameters):\n \"\"\"Build the neg op testing graph.\"\"\"\n input_tensor = tf.placeholder(\n dtype=parameters[\"input_dtype\"],\n name=\"input\",\n shape=parameters[\"input_shape\"])\n out = tf.negative(input_tensor)\n return [input_tensor], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n values = create_tensor_data(parameters[\"input_dtype\"],\n parameters[\"input_shape\"])\n return [values], sess.run(outputs, feed_dict=dict(zip(inputs, [values])))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n@register_make_test_function()\ndef make_zeros_like_tests(options):\n \"\"\"Make a set of tests to do zeros_like.\"\"\"\n\n test_parameters = [{\n \"input_dtype\": [tf.float32, tf.int32, tf.int64],\n \"input_shape\": [[], [1], [1, 2], [5, 6, 7, 8], [3, 4, 5, 6]],\n }]\n\n def build_graph(parameters):\n \"\"\"Build the zeros_like op testing graph.\"\"\"\n input_tensor = tf.placeholder(\n dtype=parameters[\"input_dtype\"],\n name=\"input\",\n shape=parameters[\"input_shape\"])\n zeros = tf.zeros_like(input_tensor)\n # This maximum node is so that toco can perform the constants-propagation\n # through the above zeros_like, which it can't do if the output of the\n # zeros_like as an output of the whole graphs (graph outputs can't be\n # constants). If toco does not perform such constants-propagation then\n # the resulting tflite graph retains the zeros_like as a Fill op, which\n # is unsupported by TFLite, even as a custom op.\n out = tf.maximum(zeros, input_tensor)\n return [input_tensor], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n values = create_tensor_data(parameters[\"input_dtype\"],\n parameters[\"input_shape\"])\n return [values], sess.run(outputs, feed_dict=dict(zip(inputs, [values])))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n@register_make_test_function()\ndef make_cast_tests(options):\n \"\"\"Generate examples for cast.\"\"\"\n test_parameters = [{\n \"input_dtype\": [tf.int32],\n \"output_dtype\": [tf.float32],\n \"input_shape\": [[], [1], [1, 2], [5, 6, 7, 8], [3, 4, 5, 6]],\n }]\n\n def build_graph(parameters):\n \"\"\"Build the cast testing graph.\"\"\"\n input_value = tf.placeholder(\n dtype=parameters[\"input_dtype\"],\n name=\"input\",\n shape=parameters[\"input_shape\"])\n out = tf.cast(input_value, parameters[\"output_dtype\"])\n return [input_value], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_value = create_tensor_data(parameters[\"input_dtype\"],\n parameters[\"input_shape\"])\n return [input_value], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_value])))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\ndef _make_elementwise_tests(op):\n \"\"\"Make a set of tests to do element-wise operations.\"\"\"\n\n def f(options):\n \"\"\"Actual function that generates examples.\"\"\"\n test_parameters = [{\n \"input_dtype\": [tf.float32],\n \"input_shape\": [[], [1], [1, 2], [5, 6, 7, 8], [3, 4, 5, 6]],\n }]\n\n def build_graph(parameters):\n \"\"\"Build the unary op testing graph.\"\"\"\n input_value = tf.placeholder(\n dtype=parameters[\"input_dtype\"],\n name=\"input1\",\n shape=parameters[\"input_shape\"])\n out = op(input_value)\n return [input_value], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_value = create_tensor_data(parameters[\"input_dtype\"],\n parameters[\"input_shape\"])\n return [input_value], sess.run(\n outputs, feed_dict={inputs[0]: input_value})\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n return f\n\n\n@register_make_test_function()\ndef make_sin_tests(options):\n \"\"\"Make a set of tests to do sin.\"\"\"\n return _make_elementwise_tests(tf.sin)(options)\n\n\n@register_make_test_function()\ndef make_log_tests(options):\n \"\"\"Make a set of tests to do log.\"\"\"\n return _make_elementwise_tests(tf.log)(options)\n\n\n@register_make_test_function()\ndef make_sqrt_tests(options):\n \"\"\"Make a set of tests to do sqrt.\"\"\"\n return _make_elementwise_tests(tf.sqrt)(options)\n\n\n@register_make_test_function()\ndef make_rsqrt_tests(options):\n \"\"\"Make a set of tests to do 1/sqrt.\"\"\"\n return _make_elementwise_tests(tf.rsqrt)(options)\n\n\n@register_make_test_function()\ndef make_square_tests(options):\n \"\"\"Make a set of tests to do square.\"\"\"\n return _make_elementwise_tests(tf.square)(options)\n\n\n@register_make_test_function()\ndef make_where_tests(options):\n \"\"\"Make a set of tests to do where.\"\"\"\n\n test_parameters = [\n {\n \"input_dtype\": [tf.float32, tf.int32],\n \"input_shape_set\": [([1, 2, 3, 4], [1, 2, 3, 4]),],\n \"use_where_v2\": [False, True],\n },\n {\n \"input_dtype\": [tf.float32, tf.int32],\n \"input_shape_set\": [([1, 2, 3, 4], [1, 2, 3, 1]),],\n \"use_where_v2\": [True],\n },\n ]\n\n def build_graph(parameters):\n \"\"\"Build the where op testing graph.\"\"\"\n input_value1 = tf.placeholder(\n dtype=parameters[\"input_dtype\"],\n name=\"input2\",\n shape=parameters[\"input_shape_set\"][0])\n input_value2 = tf.placeholder(\n dtype=parameters[\"input_dtype\"],\n name=\"input3\",\n shape=parameters[\"input_shape_set\"][1])\n less = tf.less(input_value1, input_value2)\n where = tf.where_v2 if parameters[\"use_where_v2\"] else tf.where\n out = where(less, input_value1, input_value2)\n return [input_value1, input_value2], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_value1 = create_tensor_data(parameters[\"input_dtype\"],\n parameters[\"input_shape_set\"][0])\n input_value2 = create_tensor_data(parameters[\"input_dtype\"],\n parameters[\"input_shape_set\"][1])\n return [input_value1, input_value2], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_value1, input_value2])))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n@register_make_test_function()\ndef make_slice_tests(options):\n \"\"\"Make a set of tests to do slice.\"\"\"\n\n # TODO(renjieliu): add test/support for uint8.\n test_parameters = [\n # 4-D\n {\n \"dtype\": [tf.float32, tf.int32, tf.int64, tf.string],\n \"index_type\": [tf.int32, tf.int64],\n \"input_shape\": [[12, 2, 2, 5]],\n \"begin\": [[0, 0, 0, 0], [1, 0, 1, 0]],\n \"size\": [[8, 2, 2, 3], [11, 2, 1, 5]],\n },\n # 2-D\n {\n \"dtype\": [tf.float32, tf.int32, tf.int64, tf.string],\n \"index_type\": [tf.int32, tf.int64],\n \"input_shape\": [[2, 3]],\n \"begin\": [[0, 0], [1, 0]],\n \"size\": [[2, 3], [2, 2]],\n },\n # 4-D with size -1\n {\n \"dtype\": [tf.float32],\n \"index_type\": [tf.int32],\n \"input_shape\": [[4, 4, 4, 4]],\n \"begin\": [[0, 0, 0, 0], [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0],\n [0, 0, 0, 1]],\n \"size\": [[-1, 1, 1, 1], [1, -1, 1, 1], [1, 1, -1, 1], [1, 1, 1, -1]],\n },\n # last dimension out of index\n {\n \"dtype\": [tf.float32],\n \"index_type\": [tf.int32],\n \"input_shape\": [[4, 4, 4]],\n \"begin\": [[3, 3, 4]],\n \"size\": [[-1, -1, -1]],\n },\n ]\n\n def build_graph(parameters):\n \"\"\"Build graph for slice test.\"\"\"\n input_tensor = tf.placeholder(\n dtype=parameters[\"dtype\"],\n name=\"input\",\n shape=parameters[\"input_shape\"])\n begin = tf.placeholder(\n dtype=parameters[\"index_type\"],\n name=\"begin\",\n shape=[len(parameters[\"input_shape\"])])\n size = tf.placeholder(\n dtype=parameters[\"index_type\"],\n name=\"size\",\n shape=[len(parameters[\"input_shape\"])])\n tensors = [input_tensor, begin, size]\n out = tf.slice(input_tensor, begin, size)\n return tensors, [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n \"\"\"Build inputs for slice test.\"\"\"\n input_values = create_tensor_data(parameters[\"dtype\"],\n parameters[\"input_shape\"])\n index_type = _TF_TYPE_INFO[parameters[\"index_type\"]][0]\n\n begin_values = np.array(parameters[\"begin\"]).astype(index_type)\n size_values = np.array(parameters[\"size\"]).astype(index_type)\n values = [input_values, begin_values, size_values]\n\n return values, sess.run(outputs, feed_dict=dict(zip(inputs, values)))\n\n make_zip_of_tests(\n options,\n test_parameters,\n build_graph,\n build_inputs,\n expected_tf_failures=24)\n\n\n@register_make_test_function()\ndef make_conv2d_transpose_tests(options):\n \"\"\"Make a set of tests to do transpose_conv.\"\"\"\n\n test_parameters = [{\n \"input_shape\": [[1, 50, 54, 3]],\n \"filter_shape\": [[1, 1, 8, 3], [1, 2, 8, 3], [1, 3, 8, 3], [1, 4, 8, 3]],\n \"output_shape\": [[1, 100, 108, 8]],\n \"dynamic_output_shape\": [True, False],\n }, {\n \"input_shape\": [[1, 16, 1, 512]],\n \"filter_shape\": [[4, 1, 512, 512]],\n \"output_shape\": [[1, 32, 1, 512]],\n \"dynamic_output_shape\": [True, False],\n }, {\n \"input_shape\": [[1, 128, 128, 1]],\n \"filter_shape\": [[4, 4, 1, 1]],\n \"output_shape\": [[1, 256, 256, 1]],\n \"dynamic_output_shape\": [True, False],\n }]\n\n def build_graph(parameters):\n \"\"\"Build a transpose_conv graph given `parameters`.\"\"\"\n input_tensor = tf.placeholder(\n dtype=tf.float32, name=\"input\", shape=parameters[\"input_shape\"])\n\n filter_tensor = tf.placeholder(\n dtype=tf.float32, name=\"filter\", shape=parameters[\"filter_shape\"])\n\n input_tensors = [input_tensor, filter_tensor]\n\n if parameters[\"dynamic_output_shape\"]:\n output_shape = tf.placeholder(dtype=tf.int32, shape=[4])\n input_tensors.append(output_shape)\n else:\n output_shape = parameters[\"output_shape\"]\n\n out = tf.nn.conv2d_transpose(\n input_tensor,\n filter_tensor,\n output_shape=output_shape,\n padding=\"SAME\",\n strides=(1, 2, 2, 1))\n\n return input_tensors, [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n values = [\n create_tensor_data(np.float32, parameters[\"input_shape\"]),\n create_tensor_data(np.float32, parameters[\"filter_shape\"])\n ]\n if parameters[\"dynamic_output_shape\"]:\n values.append(np.array(parameters[\"output_shape\"]))\n\n return values, sess.run(outputs, feed_dict=dict(zip(inputs, values)))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n# Since compute output_shape is fairly complicated for\n# tf.nn.conv2d_transpose input_sizes argument, so we here first perform a\n# \"conv2d\" operation to get the output, then we use the output to feed in\n# tf.nn.conv2d_backprop_input.\n# This test will depend on the \"conv2d\" operation's correctness.\n@register_make_test_function()\ndef make_transpose_conv_tests(options):\n \"\"\"Make a set of tests to do transpose_conv.\"\"\"\n\n # Tensorflow only supports equal strides\n test_parameters = [{\n \"input_shape\": [[1, 3, 4, 1], [1, 10, 10, 3], [3, 20, 20, 1]],\n \"filter_size\": [[1, 1], [1, 2], [3, 3]],\n \"strides\": [[1, 1, 1, 1], [1, 3, 3, 1]],\n \"padding\": [\"SAME\", \"VALID\"],\n \"data_format\": [\"NHWC\"],\n \"channel_multiplier\": [1, 2],\n }]\n\n def get_tensor_shapes(parameters):\n input_shape = parameters[\"input_shape\"]\n filter_size = parameters[\"filter_size\"]\n filter_shape = filter_size + [\n input_shape[3], parameters[\"channel_multiplier\"]\n ]\n return [input_shape, filter_shape]\n\n def build_graph(parameters):\n \"\"\"Build a transpose_conv graph given `parameters`.\"\"\"\n input_shape, filter_shape = get_tensor_shapes(parameters)\n input_tensor = tf.placeholder(\n dtype=tf.float32, name=\"input\", shape=input_shape)\n\n filter_input = tf.placeholder(\n dtype=tf.float32, name=\"filter\", shape=filter_shape)\n\n conv_outputs = tf.nn.conv2d(\n input_tensor,\n filter_input,\n strides=parameters[\"strides\"],\n padding=parameters[\"padding\"],\n data_format=parameters[\"data_format\"])\n out = tf.nn.conv2d_backprop_input(\n input_shape,\n filter_input,\n conv_outputs,\n strides=parameters[\"strides\"],\n padding=parameters[\"padding\"],\n data_format=parameters[\"data_format\"])\n input_tensors = [input_tensor, filter_input]\n return input_tensors, [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_shape, filter_shape = get_tensor_shapes(parameters)\n values = [\n create_tensor_data(np.float32, input_shape),\n create_tensor_data(np.float32, filter_shape)\n ]\n return values, sess.run(outputs, feed_dict=dict(zip(inputs, values)))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n@register_make_test_function()\ndef make_tile_tests(options):\n \"\"\"Make a set of tests to do tile.\"\"\"\n test_parameters = [{\n \"input_dtype\": [tf.float32, tf.int32, tf.bool],\n \"input_shape\": [[3, 2, 1], [2, 2, 2]],\n \"multiplier_dtype\": [tf.int32, tf.int64],\n \"multiplier_shape\": [[3]]\n }]\n\n def build_graph(parameters):\n \"\"\"Build the tile op testing graph.\"\"\"\n input_value = tf.placeholder(\n dtype=parameters[\"input_dtype\"],\n shape=parameters[\"input_shape\"],\n name=\"input\")\n multiplier_value = tf.placeholder(\n dtype=parameters[\"multiplier_dtype\"],\n shape=parameters[\"multiplier_shape\"],\n name=\"multiplier\")\n out = tf.tile(input_value, multiplier_value)\n return [input_value, multiplier_value], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_value = create_tensor_data(parameters[\"input_dtype\"],\n parameters[\"input_shape\"])\n multipliers_value = create_tensor_data(\n parameters[\"multiplier_dtype\"],\n parameters[\"multiplier_shape\"],\n min_value=0)\n return [input_value, multipliers_value], sess.run(\n outputs,\n feed_dict={\n inputs[0]: input_value,\n inputs[1]: multipliers_value\n })\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n@register_make_test_function()\ndef make_expand_dims_tests(options):\n \"\"\"Make a set of tests to do expand_dims.\"\"\"\n\n test_parameters = [{\n \"input_type\": [tf.float32, tf.int32],\n \"input_shape\": [[5, 4]],\n \"axis_value\": [0, 1, 2, -1, -2, -3],\n \"constant_axis\": [True, False],\n }]\n\n def build_graph(parameters):\n \"\"\"Build the where op testing graph.\"\"\"\n inputs = []\n input_value = tf.placeholder(\n dtype=parameters[\"input_type\"],\n name=\"input\",\n shape=parameters[\"input_shape\"])\n inputs.append(input_value)\n\n if parameters[\"constant_axis\"]:\n axis_value = tf.constant(\n parameters[\"axis_value\"], dtype=tf.int32, shape=[1])\n else:\n axis_value = tf.placeholder(dtype=tf.int32, name=\"axis\", shape=[1])\n inputs.append(axis_value)\n\n out = tf.expand_dims(input_value, axis=axis_value)\n return inputs, [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_values = []\n input_values.append(\n create_tensor_data(parameters[\"input_type\"], parameters[\"input_shape\"]))\n if not parameters[\"constant_axis\"]:\n input_values.append(np.array([parameters[\"axis_value\"]], dtype=np.int32))\n return input_values, sess.run(\n outputs, feed_dict=dict(zip(inputs, input_values)))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n@register_make_test_function()\ndef make_sparse_to_dense_tests(options):\n \"\"\"Make a set of tests to do sparse to dense.\"\"\"\n\n test_parameters = [{\n \"value_dtype\": [tf.float32, tf.int32, tf.int64],\n \"index_dtype\": [tf.int32, tf.int64],\n \"value_count\": [1, 3, 6, 8],\n \"dense_shape\": [[15], [3, 10], [4, 4, 4, 4], [7, 10, 9]],\n \"default_value\": [0, -1],\n \"value_is_scalar\": [True, False],\n }]\n\n # Return a single value for 1-D dense shape, but a tuple for other shapes.\n def generate_index(dense_shape):\n if len(dense_shape) == 1:\n return np.random.randint(dense_shape[0])\n else:\n index = []\n for shape in dense_shape:\n index.append(np.random.randint(shape))\n return tuple(index)\n\n def build_graph(parameters):\n \"\"\"Build the sparse_to_dense op testing graph.\"\"\"\n dense_shape = parameters[\"dense_shape\"]\n\n # Special handle for value_is_scalar case.\n # value_count must be 1.\n if parameters[\"value_is_scalar\"] and parameters[\"value_count\"] == 1:\n value = tf.placeholder(\n name=\"value\", dtype=parameters[\"value_dtype\"], shape=())\n else:\n value = tf.placeholder(\n name=\"value\",\n dtype=parameters[\"value_dtype\"],\n shape=[parameters[\"value_count\"]])\n indices = set()\n while len(indices) < parameters[\"value_count\"]:\n indices.add(generate_index(dense_shape))\n indices = tf.constant(tuple(indices), dtype=parameters[\"index_dtype\"])\n # TODO(renjieliu): Add test for validate_indices case.\n out = tf.sparse_to_dense(\n indices,\n dense_shape,\n value,\n parameters[\"default_value\"],\n validate_indices=False)\n\n return [value], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n if parameters[\"value_is_scalar\"] and parameters[\"value_count\"] == 1:\n input_value = create_scalar_data(parameters[\"value_dtype\"])\n else:\n input_value = create_tensor_data(parameters[\"value_dtype\"],\n [parameters[\"value_count\"]])\n return [input_value], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_value])))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n@register_make_test_function()\ndef make_pack_tests(options):\n \"\"\"Make a set of tests to do stack.\"\"\"\n\n test_parameters = [\n # Avoid creating all combinations to keep the test size small.\n {\n \"dtype\": [tf.float32],\n \"base_shape\": [[3, 4, 3], [3, 4], [5]],\n \"num_tensors\": [1, 2, 3, 4, 5, 6],\n \"axis\": [0, 1, 2, 3],\n \"additional_shape\": [1, 2, 3],\n },\n {\n \"dtype\": [tf.int32],\n \"base_shape\": [[3, 4, 3], [3, 4], [5]],\n \"num_tensors\": [6],\n \"axis\": [0, 1, 2, 3],\n \"additional_shape\": [1, 2, 3],\n },\n {\n \"dtype\": [tf.int64],\n \"base_shape\": [[3, 4, 3], [3, 4], [5]],\n \"num_tensors\": [5],\n \"axis\": [0, 1, 2, 3],\n \"additional_shape\": [1, 2, 3],\n }\n ]\n\n def get_shape(parameters):\n \"\"\"Return a tweaked version of 'base_shape'.\"\"\"\n axis = parameters[\"axis\"]\n shape = parameters[\"base_shape\"][:]\n if axis < len(shape):\n shape[axis] += parameters[\"additional_shape\"]\n return shape\n\n def build_graph(parameters):\n all_tensors = []\n for n in range(0, parameters[\"num_tensors\"]):\n input_tensor = tf.placeholder(\n dtype=parameters[\"dtype\"],\n name=(\"input%d\" % n),\n shape=get_shape(parameters))\n all_tensors.append(input_tensor)\n out = tf.stack(all_tensors, parameters[\"axis\"])\n return all_tensors, [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n all_values = []\n for _ in range(0, parameters[\"num_tensors\"]):\n input_values = create_tensor_data(np.float32, get_shape(parameters))\n all_values.append(input_values)\n return all_values, sess.run(\n outputs, feed_dict=dict(zip(inputs, all_values)))\n\n make_zip_of_tests(\n options,\n test_parameters,\n build_graph,\n build_inputs,\n expected_tf_failures=72)\n\n\n@register_make_test_function()\ndef make_unpack_tests(options):\n \"\"\"Make a set of tests to do unstack.\"\"\"\n\n test_parameters = [{\n \"base_shape\": [[3, 4, 3], [3, 4], [5, 6, 7, 8]],\n \"axis\": [0, 1, 2, 3],\n }]\n\n def get_valid_axis(parameters):\n \"\"\"Return a tweaked version of 'axis'.\"\"\"\n axis = parameters[\"axis\"]\n shape = parameters[\"base_shape\"][:]\n while axis > len(shape) - 1:\n axis -= 1\n return axis\n\n def build_graph(parameters):\n input_tensor = tf.placeholder(\n dtype=tf.float32, name=(\"input\"), shape=parameters[\"base_shape\"])\n outs = tf.unstack(input_tensor, axis=get_valid_axis(parameters))\n return [input_tensor], [outs[0]]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_value = create_tensor_data(np.float32, shape=parameters[\"base_shape\"])\n return [input_value], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_value])))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n@register_make_test_function()\ndef make_range_tests(options):\n \"\"\"Make a set of tests to do range.\"\"\"\n\n test_parameters = [{\n \"dtype\": [tf.int32, tf.float32],\n \"offset\": [10, 100, 1000],\n \"delta\": [1, 2, 3, 4, -1, -2, -3, -4],\n }]\n\n def build_graph(parameters):\n \"\"\"Build the range op testing graph.\"\"\"\n input_tensor = tf.placeholder(\n dtype=parameters[\"dtype\"], name=(\"start\"), shape=[])\n if parameters[\"delta\"] < 0:\n offset = parameters[\"offset\"] * -1\n else:\n offset = parameters[\"offset\"]\n delta = parameters[\"delta\"]\n limit_tensor = input_tensor + offset\n delta_tensor = tf.constant(delta, dtype=parameters[\"dtype\"])\n out = tf.range(input_tensor, limit_tensor, delta_tensor)\n return [input_tensor], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_value = create_scalar_data(parameters[\"dtype\"])\n return [input_value], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_value])))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n@register_make_test_function()\ndef make_fill_tests(options):\n \"\"\"Make a set of tests to do fill.\"\"\"\n\n test_parameters = [{\n \"dims_dtype\": [tf.int32, tf.int64],\n \"dims_shape\": [[], [1], [3], [3, 3]],\n \"value_dtype\": [tf.int32, tf.int64, tf.float32],\n }]\n\n def build_graph(parameters):\n \"\"\"Build the fill op testing graph.\"\"\"\n input1 = tf.placeholder(\n dtype=parameters[\"dims_dtype\"],\n name=\"dims\",\n shape=parameters[\"dims_shape\"])\n input2 = tf.placeholder(\n dtype=parameters[\"value_dtype\"], name=\"value\", shape=[])\n out = tf.fill(input1, input2)\n return [input1, input2], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input1 = create_tensor_data(parameters[\"dims_dtype\"],\n parameters[\"dims_shape\"], 1)\n input2 = create_scalar_data(parameters[\"value_dtype\"])\n return [input1, input2], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input1, input2])))\n\n make_zip_of_tests(\n options,\n test_parameters,\n build_graph,\n build_inputs,\n expected_tf_failures=12)\n\n\ndef _make_logical_tests(op):\n \"\"\"Make a set of tests to do logical operations.\"\"\"\n\n def logical(options, expected_tf_failures=0):\n \"\"\"Generate examples.\"\"\"\n test_parameters = [{\n \"input_shape_pair\": [([], []), ([1, 1, 1, 3], [1, 1, 1, 3]),\n ([2, 3, 4, 5], [2, 3, 4, 5]), ([2, 3, 3], [2, 3]),\n ([5, 5], [1]), ([10], [2, 4, 10])],\n }]\n\n def build_graph(parameters):\n \"\"\"Build the logical testing graph.\"\"\"\n input_value1 = tf.placeholder(\n dtype=tf.bool, name=\"input1\", shape=parameters[\"input_shape_pair\"][0])\n input_value2 = tf.placeholder(\n dtype=tf.bool, name=\"input2\", shape=parameters[\"input_shape_pair\"][1])\n out = op(input_value1, input_value2)\n return [input_value1, input_value2], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_value1 = create_tensor_data(tf.bool,\n parameters[\"input_shape_pair\"][0])\n input_value2 = create_tensor_data(tf.bool,\n parameters[\"input_shape_pair\"][1])\n return [input_value1, input_value2], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_value1, input_value2])))\n\n make_zip_of_tests(\n options,\n test_parameters,\n build_graph,\n build_inputs,\n expected_tf_failures=expected_tf_failures)\n\n return logical\n\n\n@register_make_test_function()\ndef make_logical_or_tests(options):\n \"\"\"Make a set of tests to do logical_or.\"\"\"\n return _make_logical_tests(tf.logical_or)(options, expected_tf_failures=1)\n\n\n@register_make_test_function()\ndef make_logical_and_tests(options):\n \"\"\"Make a set of tests to do logical_and.\"\"\"\n return _make_logical_tests(tf.logical_and)(options, expected_tf_failures=1)\n\n\n@register_make_test_function()\ndef make_logical_xor_tests(options):\n \"\"\"Make a set of tests to do logical_xor.\n\n Test logical_not as well.\n \"\"\"\n return _make_logical_tests(tf.logical_xor)(options, expected_tf_failures=1)\n\n\n@register_make_test_function()\ndef make_mirror_pad_tests(options):\n \"\"\"Make a set of tests to do mirror_pad.\"\"\"\n\n test_parameters = [\n {\n \"input_shape\": [[2, 3]],\n \"padding_matrix\": [[[1, 1], [2, 1]]],\n \"mode\": [\"REFLECT\"],\n \"type\": [\"const\"]\n },\n {\n \"input_shape\": [[2, 3]],\n \"padding_matrix\": [[[1, 1], [1, 1]]],\n \"mode\": [\"REFLECT\"],\n \"type\": [\"const\"]\n },\n {\n \"input_shape\": [[2, 3]],\n \"padding_matrix\": [[[1, 1], [2, 1]]],\n \"mode\": [\"SYMMETRIC\"],\n \"type\": [\"placeholder\"]\n },\n {\n \"input_shape\": [[2, 3]],\n \"padding_matrix\": [[[1, 1], [2, 1]]],\n \"mode\": [\"REFLECT\"],\n \"type\": [\"placeholder\"]\n },\n {\n \"input_shape\": [[3]],\n \"padding_matrix\": [[[0, 2]]],\n \"mode\": [\"SYMMETRIC\"],\n \"type\": [\"placeholder\"]\n },\n {\n \"input_shape\": [[3]],\n \"padding_matrix\": [[[0, 2]]],\n \"mode\": [\"SYMMETRIC\"],\n \"type\": [\"const\"]\n },\n {\n \"input_shape\": [[3]],\n \"padding_matrix\": [[[0, 2]]],\n \"mode\": [\"REFLECT\"],\n \"type\": [\"const\"]\n },\n {\n \"input_shape\": [[3, 2, 4, 5]],\n \"padding_matrix\": [[[1, 1], [2, 2], [1, 1], [1, 1]]],\n \"mode\": [\"SYMMETRIC\"],\n \"type\": [\"placeholder\"]\n },\n ]\n\n def build_graph(parameters):\n \"\"\"Build the graph for the test case.\"\"\"\n\n input_tensor = tf.placeholder(\n dtype=tf.int32, name=\"input\", shape=parameters[\"input_shape\"])\n if parameters[\"type\"] != \"const\":\n padding_matrix = tf.placeholder(\n dtype=tf.int32,\n name=\"padding\",\n shape=[len(parameters[\"input_shape\"]), 2])\n input_tensors = [input_tensor, padding_matrix]\n else:\n padding_matrix = tf.constant(np.array(parameters[\"padding_matrix\"]))\n input_tensors = [input_tensor]\n output = tf.pad(\n input_tensor, paddings=padding_matrix, mode=parameters[\"mode\"])\n\n return input_tensors, [output]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_values = [create_tensor_data(tf.int32, parameters[\"input_shape\"])]\n if parameters[\"type\"] != \"const\":\n input_values.append(np.array(parameters[\"padding_matrix\"]))\n return input_values, sess.run(\n outputs, feed_dict=dict(zip(inputs, input_values)))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n@register_make_test_function()\ndef make_unroll_batch_matmul_tests(options):\n \"\"\"Make a set of tests to test unroll_batch_matmul.\"\"\"\n\n # The test cases below requires broadcasting support (BatchMatMulV2 semantic),\n # whis isn't supported as of this change.\n broadcast_shape_params = [\n # Simple broadcast.\n [(1, 2, 3), (3, 5), False, False],\n # Empty batch broadcast.\n [(2, 5, 3), (3, 7), False, False],\n # Single batch with non-empty batch broadcast.\n [(1, 5, 3), (4, 3, 7), False, False],\n # Broadcast both operands\n [(3, 1, 5, 3), (1, 4, 3, 7), False, False],\n ]\n\n test_parameters = [{\n \"dtype\": [tf.float32],\n \"shape\": [\n [(2, 2, 3), (2, 3, 2), False, False],\n [(2, 2, 3), (2, 3, 2), True, True],\n [(2, 2, 3), (2, 2, 3), False, True],\n [(2, 2, 3), (2, 2, 3), True, False],\n [(4, 2, 2, 3), (4, 2, 3, 2), False, False],\n [(4, 2, 2, 3), (4, 2, 3, 2), True, True],\n [(4, 2, 2, 3), (4, 2, 2, 3), False, True],\n [(4, 2, 2, 3), (4, 2, 2, 3), True, False]\n ] + broadcast_shape_params,\n # TODO(b/130887442): Improve the forward compatibility tests for every\n # ops.\n \"forward_compatibility_test\": [False, True],\n }]\n\n def build_graph(parameters):\n \"\"\"Build the batch_matmul op testing graph.\"\"\"\n def _build_graph():\n input_tensor1 = tf.placeholder(\n dtype=parameters[\"dtype\"], shape=parameters[\"shape\"][0])\n input_tensor2 = tf.placeholder(\n dtype=parameters[\"dtype\"], shape=parameters[\"shape\"][1])\n # Should be unrolled and replaced with fully_connected ops in the end.\n out = tf.matmul(\n input_tensor1,\n input_tensor2,\n transpose_a=parameters[\"shape\"][2],\n transpose_b=parameters[\"shape\"][3])\n return [input_tensor1, input_tensor2], [out]\n if parameters[\"forward_compatibility_test\"]:\n # This is hardcoded to the date after MatMulV2 is activated.\n # TODO(b/130887442): Improve the forward compatibility tests for every\n # ops, and remove the hardcoded date.\n with tf.compat.forward_compatibility_horizon(2019, 4, 26):\n return _build_graph()\n else:\n return _build_graph()\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_value1 = create_tensor_data(\n parameters[\"dtype\"], shape=parameters[\"shape\"][0])\n input_value2 = create_tensor_data(\n parameters[\"dtype\"], shape=parameters[\"shape\"][1])\n return [input_value1, input_value2], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_value1, input_value2])))\n\n make_zip_of_tests(\n options, test_parameters, build_graph, build_inputs)\n\n\n@register_make_test_function()\ndef make_placeholder_with_default_tests(options):\n \"\"\"Make a set of tests to test placeholder_with_default.\"\"\"\n\n test_parameters = [{\n \"dtype\": [tf.float32, tf.int32, tf.int64],\n }]\n\n def build_graph(parameters):\n \"\"\"Build the placeholder_with_default testing graph.\"\"\"\n const_node = tf.constant(\n [1, 2, 2, 0], shape=[2, 2], dtype=parameters[\"dtype\"])\n input_tensor = tf.placeholder_with_default(\n const_node, shape=[2, 2], name=\"input\")\n out = tf.equal(input_tensor, const_node, name=\"output\")\n\n return [input_tensor], [out]\n\n def build_inputs(parameters, sess, inputs, outputs):\n numpy_type = _TF_TYPE_INFO[parameters[\"dtype\"]][0]\n input_value = np.array([[1, 0], [2, 1]], numpy_type)\n return [input_value], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_value])))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n@register_make_test_function()\ndef make_unique_tests(options):\n \"\"\"Make a set of tests for Unique op.\"\"\"\n\n test_parameters = [\n {\n \"input_shape\": [[1]],\n \"index_type\": [tf.int32, tf.int64, None],\n \"input_values\": [3]\n },\n {\n \"input_shape\": [[5]],\n \"index_type\": [tf.int32, tf.int64],\n \"input_values\": [[3, 2, 1, 2, 3]]\n },\n {\n \"input_shape\": [[7]],\n \"index_type\": [tf.int32, tf.int64],\n \"input_values\": [[1, 1, 1, 1, 1, 1, 1]]\n },\n {\n \"input_shape\": [[5]],\n \"index_type\": [tf.int32, tf.int64],\n \"input_values\": [[3, 2, 1, 0, -1]]\n }]\n\n def build_graph(parameters):\n \"\"\"Build the graph for the test case.\"\"\"\n\n input_tensor = tf.placeholder(\n dtype=tf.int32, name=\"input\", shape=parameters[\"input_shape\"])\n if parameters[\"index_type\"] is None:\n output = tf.unique(input_tensor)\n else:\n output = tf.unique(input_tensor, parameters[\"index_type\"])\n\n return [input_tensor], output\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_values = [create_tensor_data(tf.int32, parameters[\"input_shape\"])]\n return input_values, sess.run(\n outputs, feed_dict=dict(zip(inputs, input_values)))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n@register_make_test_function()\ndef make_reverse_v2_tests(options):\n \"\"\"Make a set of tests to do reverse_v2.\"\"\"\n\n test_parameters = [{\n \"base_shape\": [[3, 4, 3], [3, 4], [5, 6, 7, 8]],\n \"axis\": [0, 1, 2, 3],\n }]\n\n def get_valid_axis(parameters):\n \"\"\"Return a tweaked version of 'axis'.\"\"\"\n axis = parameters[\"axis\"]\n shape = parameters[\"base_shape\"][:]\n while axis > len(shape) - 1:\n axis -= 1\n return axis\n\n def build_graph(parameters):\n input_tensor = tf.placeholder(\n dtype=tf.float32, name=(\"input\"), shape=parameters[\"base_shape\"])\n outs = tf.reverse(input_tensor, axis=[get_valid_axis(parameters)])\n return [input_tensor], [outs]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_value = create_tensor_data(np.float32, shape=parameters[\"base_shape\"])\n return [input_value], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_value])))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n@register_make_test_function()\ndef make_reverse_sequence_tests(options):\n \"\"\"Make a set of tests to do reverse_sequence.\"\"\"\n\n test_parameters = [\n {\n \"input_dtype\": [tf.float32, tf.int32, tf.int64],\n \"input_shape\": [[8, 4, 5, 5, 6], [4, 4, 3, 5]],\n \"seq_lengths\": [[2, 2, 2, 2], [2, 1, 1, 0]],\n \"seq_axis\": [0, 3],\n \"batch_axis\": [1]\n },\n {\n \"input_dtype\": [tf.float32],\n \"input_shape\": [[2, 4, 5, 5, 6]],\n \"seq_lengths\": [[2, 1]],\n \"seq_axis\": [2],\n \"batch_axis\": [0]\n },\n {\n \"input_dtype\": [tf.float32],\n \"input_shape\": [[4, 2]],\n \"seq_lengths\": [[3, 1]],\n \"seq_axis\": [0],\n \"batch_axis\": [1]\n }]\n\n def build_graph(parameters):\n input_value = tf.placeholder(\n dtype=parameters[\"input_dtype\"],\n name=\"input\",\n shape=parameters[\"input_shape\"])\n outs = tf.reverse_sequence(\n input_value,\n seq_lengths=parameters[\"seq_lengths\"],\n batch_axis=parameters[\"batch_axis\"],\n seq_axis=parameters[\"seq_axis\"])\n return [input_value], [outs]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_value = create_tensor_data(parameters[\"input_dtype\"],\n parameters[\"input_shape\"])\n return [input_value], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_value])))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n@register_make_test_function()\ndef make_matrix_diag_tests(options):\n \"\"\"Make a set of tests for tf.linalg.diag op.\"\"\"\n\n test_parameters = [\n {\n \"input_shape\": [[3], [2, 3], [3, 4, 5], [2, 4, 6, 8]],\n \"input_dtype\": [tf.int32, tf.float32],\n },\n ]\n\n def build_graph(parameters):\n input_tensor = tf.placeholder(\n dtype=parameters[\"input_dtype\"],\n name=\"input\",\n shape=parameters[\"input_shape\"])\n outs = tf.matrix_diag(input_tensor)\n return [input_tensor], [outs]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_values = create_tensor_data(parameters[\"input_dtype\"],\n parameters[\"input_shape\"])\n return [input_values], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_values])))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n@register_make_test_function()\ndef make_matrix_set_diag_tests(options):\n \"\"\"Make a set of tests for tf.linalg.set_diag op.\"\"\"\n\n test_parameters = [\n {\n \"input_diag_shapes\": [([3, 3], [3]), ([2, 3], [2]), ([2, 4, 4],\n [2, 4]),\n ([3, 4, 5, 6], [3, 4, 5])],\n \"input_dtype\": [tf.int32, tf.float32, tf.uint8],\n },\n ]\n\n def build_graph(parameters):\n input_shape = parameters[\"input_diag_shapes\"][0]\n diag_shape = parameters[\"input_diag_shapes\"][1]\n input_tensor = tf.placeholder(\n dtype=parameters[\"input_dtype\"], name=\"input\", shape=input_shape)\n diag_tensor = tf.placeholder(\n dtype=parameters[\"input_dtype\"], name=\"diagonal\", shape=diag_shape)\n outs = tf.matrix_set_diag(input_tensor, diag_tensor)\n return [input_tensor, diag_tensor], [outs]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_shape = parameters[\"input_diag_shapes\"][0]\n diag_shape = parameters[\"input_diag_shapes\"][1]\n input_values = create_tensor_data(parameters[\"input_dtype\"], input_shape)\n diag_values = create_tensor_data(parameters[\"input_dtype\"], diag_shape)\n return [input_values, diag_values], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_values, diag_values])))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n@register_make_test_function()\ndef make_eye_tests(options):\n \"\"\"Make a set of tests for tf.eye op.\"\"\"\n\n test_parameters = [{\n \"num_rows_shape\": [[]],\n \"num_cols_shape\": [[]],\n \"batch_shape\": [[3], [2, 4], [4, 5, 6], None],\n \"use_num_cols\": [True, False],\n \"dtype\": [tf.float32, tf.int32],\n }]\n\n def build_graph(parameters):\n input_tensor0 = tf.placeholder(\n dtype=tf.int32, name=\"num_rows\", shape=parameters[\"num_rows_shape\"])\n input_tensor1 = tf.placeholder(\n dtype=tf.int32, name=\"num_columns\", shape=parameters[\"num_cols_shape\"])\n if parameters[\"use_num_cols\"]:\n outs = tf.eye(\n num_rows=input_tensor0,\n num_columns=input_tensor1,\n batch_shape=parameters[\"batch_shape\"],\n dtype=parameters[\"dtype\"])\n return [input_tensor0, input_tensor1], [outs]\n else:\n outs = tf.eye(num_rows=input_tensor0, dtype=parameters[\"dtype\"])\n return [input_tensor0], [outs]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_value0 = create_scalar_data(dtype=np.int32, min_value=1)\n input_value1 = create_scalar_data(dtype=np.int32, min_value=1)\n if parameters[\"use_num_cols\"]:\n return [input_value0, input_value1], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_value0, input_value1])))\n else:\n return [input_value0], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_value0])))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n\n\n@register_make_test_function(name=\"make_unidirectional_sequence_lstm_tests\")\n@test_util.enable_control_flow_v2\ndef make_unidirectional_sequence_lstm_tests(options):\n \"\"\"Make a set of tests to do unidirectional_sequence_lstm.\"\"\"\n\n test_parameters = [{\n \"batch_size\": [2, 4, 6],\n \"seq_length\": [1, 3],\n \"units\": [4, 5],\n \"use_peepholes\": [False, True],\n \"is_dynamic_rnn\": [False, True]\n }]\n\n def build_graph(parameters):\n input_values = []\n if parameters[\"is_dynamic_rnn\"]:\n shape = [\n parameters[\"seq_length\"], parameters[\"batch_size\"],\n parameters[\"units\"]\n ]\n input_value = tf.placeholder(dtype=tf.float32, name=\"input\", shape=shape)\n input_values.append(input_value)\n lstm_cell = tf.lite.experimental.nn.TFLiteLSTMCell(\n parameters[\"units\"],\n use_peepholes=parameters[\"use_peepholes\"])\n outs, _ = tf.lite.experimental.nn.dynamic_rnn(\n lstm_cell, input_value, dtype=tf.float32, time_major=True)\n outs = tf.unstack(outs, axis=1)\n else:\n shape = [parameters[\"batch_size\"], parameters[\"units\"]]\n for i in range(parameters[\"seq_length\"]):\n input_value = tf.placeholder(\n dtype=tf.float32, name=(\"input_%d\" % i), shape=shape)\n input_values.append(input_value)\n lstm_cell = tf.lite.experimental.nn.TFLiteLSTMCell(\n parameters[\"units\"], use_peepholes=parameters[\"use_peepholes\"])\n outs, _ = tf.nn.static_rnn(lstm_cell, input_values, dtype=tf.float32)\n\n real_output = tf.zeros([1], dtype=tf.float32) + outs[-1]\n return input_values, [real_output]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_values = []\n if parameters[\"is_dynamic_rnn\"]:\n shape = [\n parameters[\"seq_length\"], parameters[\"batch_size\"],\n parameters[\"units\"]\n ]\n input_value = create_tensor_data(tf.float32, shape)\n input_values.append(input_value)\n else:\n shape = [parameters[\"batch_size\"], parameters[\"units\"]]\n for i in range(parameters[\"seq_length\"]):\n input_value = create_tensor_data(tf.float32, shape)\n input_values.append(input_value)\n init = tf.global_variables_initializer()\n sess.run(init)\n # Tflite fused kernel takes input as [time, batch, input].\n # For static unidirectional sequence lstm, the input is an array sized of\n # time, and pack the array together, however, for time = 1, the input is\n # not packed.\n tflite_input_values = input_values\n if not parameters[\"is_dynamic_rnn\"] and parameters[\"seq_length\"] == 1:\n tflite_input_values = [\n input_values[0].reshape((1, parameters[\"batch_size\"],\n parameters[\"units\"]))\n ]\n return tflite_input_values, sess.run(\n outputs, feed_dict=dict(zip(inputs, input_values)))\n\n make_zip_of_tests(\n options,\n test_parameters,\n build_graph,\n build_inputs,\n use_frozen_graph=True)\n\n\n@register_make_test_function(name=\"make_unidirectional_sequence_rnn_tests\")\n@test_util.enable_control_flow_v2\ndef make_unidirectional_sequence_rnn_tests(options):\n \"\"\"Make a set of tests to do unidirectional_sequence_rnn.\"\"\"\n\n test_parameters = [{\n \"batch_size\": [2, 4, 6],\n \"seq_length\": [1, 3],\n \"units\": [4, 5],\n \"is_dynamic_rnn\": [False, True]\n }]\n\n def build_graph(parameters):\n input_values = []\n if parameters[\"is_dynamic_rnn\"]:\n shape = [\n parameters[\"seq_length\"], parameters[\"batch_size\"],\n parameters[\"units\"]\n ]\n input_value = tf.placeholder(dtype=tf.float32, name=\"input\", shape=shape)\n input_values.append(input_value)\n rnn_cell = tf.lite.experimental.nn.TfLiteRNNCell(parameters[\"units\"])\n outs, _ = tf.lite.experimental.nn.dynamic_rnn(\n rnn_cell, input_value, dtype=tf.float32, time_major=True)\n outs = tf.unstack(outs, axis=1)\n else:\n shape = [parameters[\"batch_size\"], parameters[\"units\"]]\n for i in range(parameters[\"seq_length\"]):\n input_value = tf.placeholder(\n dtype=tf.float32, name=(\"input_%d\" % i), shape=shape)\n input_values.append(input_value)\n rnn_cell = tf.lite.experimental.nn.TfLiteRNNCell(parameters[\"units\"])\n outs, _ = tf.nn.static_rnn(rnn_cell, input_values, dtype=tf.float32)\n\n real_output = tf.zeros([1], dtype=tf.float32) + outs[-1]\n return input_values, [real_output]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_values = []\n if parameters[\"is_dynamic_rnn\"]:\n shape = [\n parameters[\"seq_length\"], parameters[\"batch_size\"],\n parameters[\"units\"]\n ]\n input_value = create_tensor_data(tf.float32, shape)\n input_values.append(input_value)\n else:\n shape = [parameters[\"batch_size\"], parameters[\"units\"]]\n for i in range(parameters[\"seq_length\"]):\n input_value = create_tensor_data(tf.float32, shape)\n input_values.append(input_value)\n init = tf.global_variables_initializer()\n sess.run(init)\n # Tflite fused kernel takes input as [time, batch, input].\n # For static unidirectional sequence rnn, the input is an array sized of\n # time, and pack the array together, however, for time = 1, the input is\n # not packed.\n tflite_input_values = input_values\n if not parameters[\"is_dynamic_rnn\"] and parameters[\"seq_length\"] == 1:\n tflite_input_values = [\n input_values[0].reshape((1, parameters[\"batch_size\"],\n parameters[\"units\"]))\n ]\n return tflite_input_values, sess.run(\n outputs, feed_dict=dict(zip(inputs, input_values)))\n\n make_zip_of_tests(\n options,\n test_parameters,\n build_graph,\n build_inputs,\n use_frozen_graph=True)\n\n\n@register_make_test_function()\ndef make_unfused_gru_tests(options):\n \"\"\"Make a set of tests for unfused gru op.\"\"\"\n\n test_parameters = [{\n \"units\": [2, 5],\n \"batch_size\": [1, 2],\n \"time\": [3],\n }]\n\n def build_graph(parameters):\n inputs = [\n tf.placeholder(tf.float32,\n [parameters[\"batch_size\"], parameters[\"units\"]])\n for _ in range(parameters[\"time\"])\n ]\n cell_fw = tf.nn.rnn_cell.GRUCell(parameters[\"units\"])\n cell_bw = tf.nn.rnn_cell.GRUCell(parameters[\"units\"])\n outputs, _, _ = tf.nn.static_bidirectional_rnn(\n cell_fw, cell_bw, inputs, dtype=tf.float32)\n\n return inputs, outputs\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_values = [\n create_tensor_data(tf.float32,\n [parameters[\"batch_size\"], parameters[\"units\"]])\n for _ in range(parameters[\"time\"])\n ]\n init = tf.global_variables_initializer()\n sess.run(init)\n return input_values, sess.run(\n outputs, feed_dict=dict(zip(inputs, input_values)))\n\n make_zip_of_tests(\n options,\n test_parameters,\n build_graph,\n build_inputs,\n use_frozen_graph=True)\n\n\n@register_make_test_function()\ndef make_rfft2d_tests(options):\n \"\"\"Make a set of tests to do rfft2d.\"\"\"\n\n test_parameters = [{\n \"input_dtype\": [tf.float32],\n \"input_shape\": [[8, 8], [3, 8, 8]],\n \"fft_length\": [\n None, [4, 4], [4, 8], [8, 4], [8, 8], [8, 16], [16, 8], [16, 16]\n ]\n }]\n\n def build_graph(parameters):\n input_value = tf.placeholder(\n dtype=parameters[\"input_dtype\"],\n name=\"input\",\n shape=parameters[\"input_shape\"])\n with spectral_ops_test_util.fft_kernel_label_map():\n outs = tf.signal.rfft2d(input_value, fft_length=parameters[\"fft_length\"])\n return [input_value], [outs]\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_value = create_tensor_data(parameters[\"input_dtype\"],\n parameters[\"input_shape\"])\n return [input_value], sess.run(\n outputs, feed_dict=dict(zip(inputs, [input_value])))\n\n extra_toco_options = ExtraTocoOptions()\n extra_toco_options.allow_custom_ops = True\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs,\n extra_toco_options)\n\n# Toco binary path provided by the generate rule.\nbin_path = None\n\n\ndef generate_examples(options):\n global bin_path\n\n def mkdir_if_not_exist(x):\n if not os.path.isdir(x):\n os.mkdir(x)\n if not os.path.isdir(x):\n raise RuntimeError(\"Failed to create dir %r\" % x)\n\n opstest_path = os.path.join(options.output_path)\n mkdir_if_not_exist(opstest_path)\n\n out = options.zip_to_output\n bin_path = options.toco\n # Some zip filenames contain a postfix identifying the conversion mode. The\n # list of valid conversion modes is defined in\n # generated_test_conversion_modes() in build_def.bzl.\n\n # Remove suffixes to extract the test name from the output name.\n test_name = re.sub(r\"(_(|toco-flex|forward-compat))?\\.zip$\", \"\", out, count=1)\n\n test_function_name = \"make_%s_tests\" % test_name\n if test_function_name not in _MAKE_TEST_FUNCTIONS_MAP:\n raise RuntimeError(\"Can't find a test function to create %r. Tried %r\" %\n (out, test_function_name))\n test_function = _MAKE_TEST_FUNCTIONS_MAP[test_function_name]\n\n if options.make_forward_compat_test:\n future_date = datetime.date.today() + datetime.timedelta(days=30)\n with tf.compat.forward_compatibility_horizon(future_date.year,\n future_date.month,\n future_date.day):\n test_function(options)\n else:\n test_function(options)\n"
] |
[
[
"numpy.random.choice",
"tensorflow.nn.conv2d",
"tensorflow.space_to_depth",
"tensorflow.zeros_like",
"tensorflow.lite.testing.generate_examples_report.make_report_table",
"tensorflow.greater",
"tensorflow.stack",
"numpy.random.random",
"tensorflow.assert_greater_equal",
"tensorflow.sigmoid",
"tensorflow.image.resize_nearest_neighbor",
"tensorflow.constant",
"tensorflow.nn.static_rnn",
"tensorflow.pad",
"tensorflow.add",
"tensorflow.less_equal",
"tensorflow.nn.conv2d_transpose",
"tensorflow.all_variables",
"tensorflow.expand_dims",
"tensorflow.fill",
"numpy.random.random_sample",
"tensorflow.get_variable",
"tensorflow.unstack",
"tensorflow.signal.rfft2d",
"tensorflow.matrix_diag",
"tensorflow.greater_equal",
"tensorflow.reset_default_graph",
"tensorflow.strided_slice",
"tensorflow.square",
"tensorflow.image.resize_bilinear",
"tensorflow.nn.static_bidirectional_rnn",
"tensorflow.python.ops.rnn.static_rnn",
"tensorflow.tile",
"tensorflow.global_variables_initializer",
"tensorflow.identity",
"tensorflow.nn.conv2d_backprop_input",
"tensorflow.shape",
"tensorflow.batch_to_space_nd",
"tensorflow.nn.leaky_relu",
"tensorflow.global_variables",
"tensorflow.transpose",
"tensorflow.lite.experimental.nn.TFLiteLSTMCell",
"tensorflow.squeeze",
"numpy.array",
"tensorflow.zeros",
"tensorflow.minimum",
"tensorflow.range",
"numpy.zeros",
"tensorflow.round",
"tensorflow.lite.Interpreter",
"tensorflow.nn.top_k",
"tensorflow.placeholder_with_default",
"tensorflow.nn.batch_norm_with_global_normalization",
"numpy.random.seed",
"tensorflow.gather",
"tensorflow.matrix_set_diag",
"tensorflow.slice",
"tensorflow.lite.experimental.convert_op_hints_to_stubs",
"tensorflow.contrib.rnn.BasicLSTMCell",
"tensorflow.reshape",
"tensorflow.keras.layers.PReLU",
"tensorflow.nn.embedding_lookup",
"tensorflow.ceil",
"tensorflow.one_hot",
"tensorflow.cast",
"tensorflow.rank",
"tensorflow.concat",
"tensorflow.less",
"tensorflow.arg_min",
"tensorflow.logging.info",
"tensorflow.variable_scope",
"tensorflow.abs",
"tensorflow.nn.relu",
"tensorflow.eye",
"tensorflow.python.ops.array_ops.snapshot",
"tensorflow.python.ops.spectral_ops_test_util.fft_kernel_label_map",
"tensorflow.compat.v1.Session",
"numpy.isscalar",
"tensorflow.nn.depthwise_conv2d",
"tensorflow.arg_max",
"tensorflow.nn.local_response_normalization",
"tensorflow.reverse_sequence",
"tensorflow.maximum",
"tensorflow.nn.l2_normalize",
"tensorflow.lite.TocoConverter.from_frozen_graph",
"tensorflow.exp",
"tensorflow.matmul",
"tensorflow.unique",
"tensorflow.compat.forward_compatibility_horizon",
"tensorflow.control_dependencies",
"tensorflow.nn.softmax",
"tensorflow.space_to_batch_nd",
"numpy.dtype",
"tensorflow.add_n",
"tensorflow.negative",
"numpy.random.randint",
"tensorflow.split",
"tensorflow.nn.log_softmax",
"tensorflow.floor",
"tensorflow.gather_nd",
"tensorflow.cos",
"tensorflow.placeholder",
"tensorflow.sparse_to_dense",
"tensorflow.nn.fused_batch_norm",
"tensorflow.not_equal",
"tensorflow.equal",
"tensorflow.nn.rnn_cell.GRUCell",
"tensorflow.lite.experimental.nn.dynamic_rnn",
"tensorflow.nn.elu",
"tensorflow.device",
"tensorflow.lite.experimental.nn.TfLiteRNNCell"
]
] |
mariajcb/migrahack
|
[
"c4a4728703fe8a68e99c0dbcb71ee5bb5aae5cf9"
] |
[
"scrape/ice_clean.py"
] |
[
"import pandas as pd\nfrom pandas.tseries.offsets import MonthEnd\nimport csv\nimport json\n\n\ndef clean_for_db(df, lat_key):\n df = df.loc[df.County != \"All\"]\n df = df.loc[df.MonthYear != \"All\"]\n df = df.assign(\n startTime=df.MonthYear.apply(lambda x: pd.to_datetime(x).isoformat()),\n endTime=(df.MonthYear.apply(lambda z: pd.to_datetime(z) + MonthEnd()))\n )\n df = pd.merge(df, lat_key, on=\"County\")\n df = df.assign(\n endTime=df.endTime.apply(lambda y: y.isoformat()),\n numArrests=df.Arrests.astype(float),\n locationName=df.County\n )\n df = df.loc[:, [\"startTime\", \"endTime\", \"numArrests\", \"latitude\", \"longitude\", \"locationName\"]]\n return df\n\n\ndef main():\n arrests = pd.read_csv('month_year_co_counties.csv')\n lat_key = pd.read_csv('centroids.csv')\n new = clean_for_db(arrests, lat_key)\n\n new.to_csv('final_arrests.csv', index=False)\n\n csvfile = open('final_arrests.csv', 'r')\n jsonfile = open('final_arrests3.json', 'w')\n\n fieldnames = (\"startTime\", \"endTime\", \"numArrests\", \"latitude\", \"longitude\", \"locationName\")\n reader = csv.DictReader(csvfile, fieldnames)\n for row in reader:\n print(row)\n json.dump(row, jsonfile)\n jsonfile.write(',\\n')\n\n\n\n"
] |
[
[
"pandas.to_datetime",
"pandas.read_csv",
"pandas.tseries.offsets.MonthEnd",
"pandas.merge"
]
] |
ExplorerFreda/ResDAVEnet-VQ
|
[
"93c5e63bff3a1827b43435461b029b0dc14c9ded",
"93c5e63bff3a1827b43435461b029b0dc14c9ded"
] |
[
"run_unit_analysis.py",
"run_ResDavenetVQ.py"
] |
[
"# Author: Wei-Ning Hsu, David Harwath\nimport argparse\nimport json\nimport numpy as np\nimport os\nimport pickle\nimport sys\nimport time\nimport torch\n\nimport dataloaders\nimport models\nfrom steps.unit_analysis import (comp_code_to_wordprec, comp_word_to_coderecall,\n get_high_prec_words, comp_code_norms,\n print_analysis, get_feats_codes,\n SparseAlignment, DenseAlignment, STOP_WORDS)\nfrom run_utils import load_audio_model_and_state\n\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n#################\n# Dataset Utils #\n#################\ndef get_inp_feat(dataset, index):\n if isinstance(dataset, dataloaders.ImageCaptionDataset):\n index = os.path.join(dataset.audio_base_path, dataset.data[index]['wav'])\n mels, nframes = dataset._LoadAudio(index)\n mels = mels[:, :nframes]\n # print('FEAT : idx=%d, mel=%s, nframes=%s' % (index, mels.size(), nframes))\n return mels, nframes\n\n\ndef get_word_ali(json_data, index):\n \"\"\"\n raw_ali is a string like 'start1__word1__end1 start2__word2__end2 ...'\n \"\"\"\n raw_ali = json_data[index].get('text_alignment', None)\n if raw_ali is None:\n return None\n \n data = []\n meta_toks = raw_ali.split()\n for meta_tok in meta_toks:\n toks = meta_tok.split('__')\n if len(toks) == 3:\n data.append((float(toks[0]), float(toks[2]), toks[1]))\n \n if len(data) == 0:\n return None\n else:\n return SparseAlignment(data)\n\n\ndef get_code_ali(audio_model, layer, dataset, index, device):\n mels, _ = get_inp_feat(dataset, index)\n _, _, codes, spf = get_feats_codes(audio_model, layer, mels, device)\n code_list = codes.detach().cpu().tolist()\n return DenseAlignment(code_list, spf)\n\n\n###########################\n# Prepare data and outpus #\n###########################\ndef prepare_data(audio_model, layer, dataset, json_data, max_n_utts):\n utt2codes = {}\n utt2words = {}\n tot_nframes = 0\n n_utts = min(len(dataset), max_n_utts)\n \n t0 = time.time()\n for utt_index in range(n_utts):\n utt2codes[utt_index] = get_code_ali(audio_model, layer, dataset,\n utt_index, device)\n utt2words[utt_index] = get_word_ali(json_data, utt_index)\n tot_nframes += len(utt2codes[utt_index])\n if (utt_index+1) % 1000 == 0:\n print(\"processing %d / %d; accumulated %d frames; took %.fs\" \n % (utt_index+1, len(dataset), tot_nframes, time.time()-t0),\n flush=True)\n t1 = time.time()\n \n print('')\n print('Took %.fs to dump %d code frames for %d utts'\n % (t1 - t0, tot_nframes, n_utts))\n return utt2codes, utt2words\n\n\n#############\n# Exp Utils #\n#############\ndef load_dataset(json_path, hdf5_path):\n dataset = dataloaders.ImageCaptionDatasetHDF5(hdf5_path, audio_conf={})\n with open(json_path) as f:\n json_data = json.load(f)['data']\n return dataset, json_data\n\n\ndef run_analysis(utt2codes, utt2words, stop_words, output_dir):\n code_to_wordprec = load_or_run_and_dump(\n '%s/code_to_wordprec.pkl' % output_dir,\n comp_code_to_wordprec,\n [utt2codes, utt2words, 0.04, stop_words], {})\n\n word_to_coderecall = load_or_run_and_dump(\n '%s/word_to_coderecall.pkl' % output_dir,\n comp_word_to_coderecall,\n [utt2codes, utt2words, []], {})\n\n high_prec_words = load_or_run_and_dump(\n '%s/high_prec_words.pkl' % output_dir,\n get_high_prec_words,\n [code_to_wordprec], {'threshold': 0.35})\n return code_to_wordprec, word_to_coderecall, high_prec_words\n\n\ndef load_or_run_and_dump(filename, fn, args, kwargs):\n if os.path.exists(filename):\n print('Load from %s' % filename)\n with open(filename, 'rb') as f:\n return pickle.load(f)\n else:\n print('Run %s and dump to %s' % (fn.__name__, filename))\n x = fn(*args, **kwargs)\n with open(filename, 'wb') as f:\n pickle.dump(x, f)\n return x\n\n\nif __name__ == '__main__':\n print('Current time : %s' % time.asctime())\n parser = argparse.ArgumentParser()\n parser.add_argument('--exp_dir', default='', type=str, required=True)\n parser.add_argument('--json_path', default='', type=str, required=True)\n parser.add_argument('--hdf5_path', default='', type=str, required=True)\n parser.add_argument('--layer', default='quant3', type=str)\n parser.add_argument('--max_n_utts', default=20000, type=int)\n parser.add_argument('--output_dir', default='./outputs', type=str)\n parser.add_argument('--min_occ', default=1, type=int)\n args = parser.parse_args()\n print(args)\n\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n output_dir = args.output_dir\n os.makedirs(output_dir, exist_ok=True)\n\n max_n_utts = args.max_n_utts\n min_occ = args.min_occ\n layer = args.layer\n \n # Load data and model\n dataset, json_data = load_dataset(args.json_path, args.hdf5_path)\n audio_model = load_audio_model_and_state(exp_dir=args.exp_dir)\n audio_model = audio_model.to(device)\n audio_model.eval()\n print(audio_model)\n\n # run\n utt2codes, utt2words = load_or_run_and_dump(\n '%s/utt2codes_utt2words.pkl' % output_dir,\n prepare_data, [audio_model, layer, dataset, json_data, max_n_utts], {})\n code_norms = load_or_run_and_dump(\n '%s/code_norms.pkl' % output_dir,\n comp_code_norms, [audio_model, layer], {})\n\n c2wp, w2cr, hp_ws = run_analysis(utt2codes, utt2words,\n STOP_WORDS, output_dir)\n \n rank_range = list(range(40)) + list(range(180, 200))\n print_analysis(c2wp, w2cr, code_norms, hp_ws, min_occ, rank_range)\n",
"# Author: David Harwath, Wei-Ning Hsu\nimport argparse\nimport numpy as np\nimport os\nimport pickle\nimport shutil\nimport sys\nimport time\nimport torch\nfrom collections import OrderedDict\n\nimport dataloaders\nfrom steps.traintest import train, validate\nfrom run_utils import str2bool, set_seeds, create_audio_model, create_image_model, load_state_dict\n\n\ndef load_args(old_args, exp_dir):\n \"\"\"\n If resuming, load args.pkl from the experiment directory, and overwrite\n `data_train`/`data_val`/`resume`.\n \"\"\"\n print('loading arguments from %s/args.pkl' % exp_dir)\n with open('%s/args.pkl' % exp_dir, 'rb') as f:\n tmp_args = pickle.load(f)\n for k in vars(old_args):\n if hasattr(tmp_args, k):\n setattr(old_args, k, getattr(tmp_args, k))\n else:\n print('...missing arg: %s' % k)\n return old_args\n\n\ndef load_dataloaders(data_train, data_val, batch_size, num_workers):\n print('loading data from %s / %s' % (data_train, data_val))\n train_dset = dataloaders.ImageCaptionDatasetHDF5(data_train)\n train_loader = torch.utils.data.dataloader.DataLoader(\n train_dset, batch_size=batch_size, shuffle=True, \n num_workers=num_workers, pin_memory=True)\n \n val_dset = dataloaders.ImageCaptionDatasetHDF5(\n data_val, image_conf={'center_crop':True})\n val_loader = torch.utils.data.dataloader.DataLoader(\n val_dset, batch_size=batch_size, shuffle=False,\n num_workers=0, pin_memory=True)\n\n return train_loader, val_loader\n\n\ndef load_state_dicts(audio_model, image_model, seed_dir, seed_epoch):\n if seed_epoch > 0:\n audio_states = torch.load(\n '%s/models/audio_model.e%d.pth' % (seed_dir, seed_epoch))\n image_states = torch.load(\n '%s/models/image_model.e%d.pth' % (seed_dir, seed_epoch))\n else:\n audio_states = torch.load(\n '%s/models/best_audio_model.pth' % seed_dir)\n image_states = torch.load(\n '%s/models/best_image_model.pth' % seed_dir)\n\n load_state_dict(audio_model, audio_states)\n load_state_dict(image_model, image_states)\n print('loaded parameters from %s/models/' % seed_dir)\n\n\ndef get_default_parser(parser=None):\n if parser is None:\n parser = argparse.ArgumentParser(\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n \n # ResDavenet args\n parser.add_argument('--audio-model', type=str, default='ResDavenetVQ', \n choices=['ResDavenetVQ'], help='audio model architecture')\n parser.add_argument('--image-model', type=str, default='Resnet50', \n choices=['Resnet50'], help='image model architecture')\n parser.add_argument('--freeze-image-model', type=str2bool, default=False,\n help='Freeze image model parameters.')\n parser.add_argument('--pretrained-image-model', type=str2bool, default=True, \n help='Use an image network pretrained on ImageNet')\n parser.add_argument('--seed-dir', type=str, default='',\n help=('Load image and audio model weights from a seed model. Overrides' \n ' using an image model pretrained on ImageNet'))\n parser.add_argument('--seed-epoch', type=int, default=-1, \n help='Load snapshot from this epoch')\n parser.add_argument('--margin', type=float, default=1.0, \n help='Margin paramater for triplet loss')\n parser.add_argument('--layer-widths', type=str, default='128,256,256,512,1024', \n help='ResDavenet layer/block sizes')\n parser.add_argument('--layer-depths', type=str, default='2,2,2,2', \n help='ResDavenet depth of each residual block')\n parser.add_argument('--convsize', type=int, default=9,\n help='ResDavenet 1-D convolution width')\n parser.add_argument('--seed', type=int, default=8675309, help='Random seed')\n \n # VQ args\n parser.add_argument('--VQ-commitment-cost', default=1, type=float, \n help='VQ commitment cost')\n parser.add_argument('--VQ-turnon', type=str, default='0,0,0,0,0', \n help=('Comma-separated list of integers representing which VQ layers' \n ' are turned on.'))\n parser.add_argument('--VQ-sizes', type=str, default='1024,1024,1024,1024,1024', \n help=('Comma-separated list of integers representing the codebook sizes' \n ' for the quantization layers.'))\n parser.add_argument('--nonneg-init', type=str2bool, default=False,\n help='Clamp the initial VQ codebooks at 0')\n parser.add_argument('--init-std', default=1, type=float, \n help='VQ codebook initialization standard deviation')\n parser.add_argument('--init-ema-mass', default=1, type=float,\n help='EMA mass for the initial codebook')\n parser.add_argument('--jitter', type=float, default=0.12, \n help='Temporal jitter probability (equal for both left and right)')\n\n return parser\n \n\ndef get_train_parser(parser=None):\n if parser is None:\n parser = argparse.ArgumentParser(\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\n # training and optimization args\n parser.add_argument('--optim', type=str, default='adam',\n help='training optimizer', choices=['sgd', 'adam'])\n parser.add_argument('--batch-size', type=int, default=64, metavar='N', \n help='mini-batch size')\n parser.add_argument('--lr', type=float, default=2e-4, metavar='LR', \n help='initial learning rate')\n parser.add_argument('--lr-decay', type=int, default=3, metavar='LRDECAY',\n help=('Multiply the learning rate by lr-decay-multiplier every lr-decay'\n ' number of epochs'))\n parser.add_argument('--lr-decay-multiplier', type=float, default=0.95,\n metavar='LRDECAYMULT',\n help='Multiply the learning rate by this factor every lr-decay epochs')\n parser.add_argument('--momentum', type=float, default=0.9, metavar='M',\n help='momentum')\n parser.add_argument('--weight-decay', type=float, default=5e-7, metavar='W', \n help='weight decay')\n parser.add_argument('--force-start-epoch', type=int, default=0, \n metavar='force_start_epoch', \n help=('Start on this epoch number (for controlling the position in the'\n ' learning rate schedule)'))\n parser.add_argument('--n-epochs', type=int, default=150,\n help='number of maximum training epochs')\n parser.add_argument('--n-print-steps', type=int, default=100,\n help='number of steps to print statistics')\n parser.add_argument('--save-every', type=int, default=10,\n help=('Keep a model checkpoint every this many epochs. Set to -1 to'\n ' deactivate'))\n\n return parser\n\n\ndef get_run_parser(parser=None):\n if parser is None:\n parser = argparse.ArgumentParser(\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\n # I/O args\n parser.add_argument('--data-train', type=str, default='',\n help='training data json')\n parser.add_argument('--data-val', type=str, default='',\n help='validation data json')\n parser.add_argument('--exp-dir', type=str, default='',\n help='directory to dump experiments')\n parser.add_argument('--resume', type=str2bool, default=False,\n help='load from exp_dir if True')\n parser.add_argument('--mode', type=str, default='eval',\n choices=['train', 'eval'],\n help='Train the model; otherwise, perform validation')\n parser.add_argument('--num-workers', type=int, default=8,\n help='number of dataloading workers')\n\n return parser\n\n\nif __name__ == '__main__':\n print('I am process %s, running on %s: starting (%s)' % (\n os.getpid(), os.uname()[1], time.asctime()))\n \n parser = get_default_parser()\n parser = get_train_parser(parser)\n parser = get_run_parser(parser)\n \n args = parser.parse_args()\n set_seeds(args.seed)\n\n def get_and_del_attr(name):\n val = getattr(args, name)\n delattr(args, name)\n return val\n\n exp_dir = get_and_del_attr('exp_dir')\n resume = get_and_del_attr('resume')\n data_train = get_and_del_attr('data_train')\n data_val = get_and_del_attr('data_val')\n mode = get_and_del_attr('mode')\n if resume:\n args = load_args(args, exp_dir)\n\n for k in vars(args):\n print('%-40s : %s' % (k, getattr(args, k)))\n \n train_loader, val_loader = load_dataloaders(\n data_train, data_val, args.batch_size, args.num_workers)\n \n audio_model = create_audio_model(\n args.audio_model, args.VQ_sizes, args.layer_widths, args.layer_depths,\n args.VQ_turnon, args.convsize, args.VQ_commitment_cost,\n args.jitter, args.init_ema_mass, args.init_std, args.nonneg_init)\n image_model = create_image_model(args.image_model, args.pretrained_image_model)\n \n # Start Training\n if mode == 'train':\n if args.seed_dir:\n load_state_dicts(audio_model, image_model,\n args.seed_dir, args.seed_epoch)\n \n if not resume:\n print('\\nCreating experiment directory: %s' % exp_dir)\n os.makedirs('%s/models' % exp_dir)\n with open('%s/args.pkl' % exp_dir, 'wb') as f:\n pickle.dump(args, f)\n \n train(audio_model, image_model, train_loader, val_loader,\n args, exp_dir, resume)\n elif mode == 'eval':\n load_state_dicts(audio_model, image_model, exp_dir, -1)\n validate(audio_model, image_model, val_loader, args)\n else:\n raise ValueError('Unsupported mode %s' % mode)\n"
] |
[
[
"torch.cuda.is_available"
],
[
"torch.utils.data.dataloader.DataLoader",
"torch.load"
]
] |
codelover-without-talent/GPflow
|
[
"1af7b1ca7da6687974150a1440d821a106b2159d"
] |
[
"gpflow/multioutput/features.py"
] |
[
"# Copyright 2018 GPflow authors\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport tensorflow as tf\n\nfrom .. import settings\nfrom ..dispatch import dispatch\nfrom ..features import InducingPoints, InducingFeature, Kuu, Kuf\nfrom ..decors import params_as_tensors_for\nfrom ..params import ParamList\nfrom .kernels import Mok, SharedIndependentMok, SeparateIndependentMok, SeparateMixedMok\n\n\nlogger = settings.logger()\n\n\nclass Mof(InducingFeature):\n \"\"\"\n Class used to indicate that we are dealing with\n features that are used for multiple outputs.\n \"\"\"\n pass\n\n\nclass SharedIndependentMof(Mof):\n \"\"\"\n Same feature is used for each output.\n \"\"\"\n def __init__(self, feat):\n Mof.__init__(self)\n self.feat = feat\n\n def __len__(self):\n return len(self.feat)\n\n\nclass SeparateIndependentMof(Mof):\n \"\"\"\n A different feature is used for each output.\n Note: each feature should have the same number of points, M.\n \"\"\"\n def __init__(self, feat_list):\n Mof.__init__(self)\n self.feat_list = ParamList(feat_list)\n\n def __len__(self):\n return len(self.feat_list[0])\n\n\nclass MixedKernelSharedMof(SharedIndependentMof):\n \"\"\"\n This Mof is used in combination with the `SeparateMixedMok`.\n Using this feature with the `SeparateMixedMok` leads to the most efficient code.\n \"\"\"\n pass\n\nclass MixedKernelSeparateMof(SeparateIndependentMof):\n \"\"\"\n This Mof is used in combination with the `SeparateMixedMok`.\n Using this feature with the `SeparateMixedMok` leads to the most efficient code.\n \"\"\"\n pass\n\n\n# ---\n# Kuf\n# ---\n\ndef debug_kuf(feat, kern):\n msg = \"Dispatch to Kuf(feat: {}, kern: {})\"\n logger.debug(msg.format(\n feat.__class__.__name__,\n kern.__class__.__name__))\n\n@dispatch(InducingPoints, Mok, object)\ndef Kuf(feat, kern, Xnew):\n debug_kuf(feat, kern)\n return kern.K(feat.Z, Xnew, full_output_cov=True) # M x P x N x P\n\n\n@dispatch(SharedIndependentMof, SharedIndependentMok, object)\ndef Kuf(feat, kern, Xnew):\n debug_kuf(feat, kern)\n return Kuf(feat.feat, kern.kern, Xnew) # M x N\n\n\n@dispatch(SeparateIndependentMof, SharedIndependentMok, object)\ndef Kuf(feat, kern, Xnew):\n debug_kuf(feat, kern)\n return tf.stack([Kuf(f, kern.kern, Xnew) for f in feat.feat_list], axis=0) # L x M x N\n\n\n@dispatch(SharedIndependentMof, SeparateIndependentMok, object)\ndef Kuf(feat, kern, Xnew):\n debug_kuf(feat, kern)\n return tf.stack([Kuf(feat.feat, k, Xnew) for k in kern.kernels], axis=0) # L x M x N\n\n\n@dispatch(SeparateIndependentMof, SeparateIndependentMok, object)\ndef Kuf(feat, kern, Xnew):\n debug_kuf(feat, kern)\n return tf.stack([Kuf(f, k, Xnew) for f, k in zip(feat.feat_list, kern.kernels)], axis=0) # L x M x N\n\n\n@dispatch((SeparateIndependentMof, SharedIndependentMof), SeparateMixedMok, object)\ndef Kuf(feat, kern, Xnew):\n debug_kuf(feat, kern)\n kuf_impl = Kuf.dispatch(type(feat), SeparateIndependentMok, object)\n K = tf.transpose(kuf_impl(feat, kern, Xnew), [1, 0, 2]) # M x L x N\n with params_as_tensors_for(kern):\n return K[:, :, :, None] * tf.transpose(kern.W)[None, :, None, :] # M x L x N x P\n\n\n@dispatch(MixedKernelSharedMof, SeparateMixedMok, object)\ndef Kuf(feat, kern, Xnew):\n debug_kuf(feat, kern)\n return tf.stack([Kuf(feat.feat, k, Xnew) for k in kern.kernels], axis=0) # L x M x N\n\n@dispatch(MixedKernelSeparateMof, SeparateMixedMok, object)\ndef Kuf(feat, kern, Xnew):\n debug_kuf(feat, kern)\n return tf.stack([Kuf(f, k, Xnew) for f, k in zip(feat.feat_list, kern.kernels)], axis=0) # L x M x N\n\n# ---\n# Kuu\n# ---\n\n\ndef debug_kuu(feat, kern, jitter):\n msg = \"Dispatch to Kuu(feat: {}, kern: {}) with jitter={}\"\n logger.debug(msg.format(\n feat.__class__.__name__,\n kern.__class__.__name__,\n jitter))\n\n\n@dispatch(InducingPoints, Mok)\ndef Kuu(feat, kern, *, jitter=0.0):\n debug_kuu(feat, kern, jitter)\n Kmm = kern.K(feat.Z, full_output_cov=True) # M x P x M x P\n M = tf.shape(Kmm)[0] * tf.shape(Kmm)[1]\n jittermat = jitter * tf.reshape(tf.eye(M, dtype=settings.float_type), tf.shape(Kmm))\n return Kmm + jittermat\n\n\n@dispatch(SharedIndependentMof, SharedIndependentMok)\ndef Kuu(feat, kern, *, jitter=0.0):\n debug_kuu(feat, kern, jitter)\n Kmm = Kuu(feat.feat, kern.kern) # M x M\n jittermat = tf.eye(len(feat), dtype=settings.float_type) * jitter\n return Kmm + jittermat\n\n\n@dispatch(SharedIndependentMof, (SeparateIndependentMok, SeparateMixedMok))\ndef Kuu(feat, kern, *, jitter=0.0):\n debug_kuu(feat, kern, jitter)\n Kmm = tf.stack([Kuu(feat.feat, k) for k in kern.kernels], axis=0) # L x M x M\n jittermat = tf.eye(len(feat), dtype=settings.float_type)[None, :, :] * jitter\n return Kmm + jittermat\n\n\n@dispatch(SeparateIndependentMof, SharedIndependentMok)\ndef Kuu(feat, kern, *, jitter):\n debug_kuu(feat, kern, jitter)\n Kmm = tf.stack([Kuu(f, kern.kern) for f in feat.feat_list], axis=0) # L x M x M\n jittermat = tf.eye(len(feat), dtype=settings.float_type)[None, :, :] * jitter\n return Kmm + jittermat\n\n\n@dispatch((SeparateIndependentMof,MixedKernelSeparateMof), (SeparateIndependentMok, SeparateMixedMok))\ndef Kuu(feat, kern, *, jitter=0.0):\n debug_kuu(feat, kern, jitter)\n Kmm = tf.stack([Kuu(f, k) for f, k in zip(feat.feat_list, kern.kernels)], axis=0) # L x M x M\n jittermat = tf.eye(len(feat), dtype=settings.float_type)[None, :, :] * jitter\n return Kmm + jittermat\n\n\n@dispatch(MixedKernelSharedMof, SeparateMixedMok)\ndef Kuu(feat, kern, *, jitter=0.0):\n debug_kuu(feat, kern, jitter)\n Kmm = tf.stack([Kuu(feat.feat, k) for k in kern.kernels], axis=0) # L x M x M\n jittermat = tf.eye(len(feat), dtype=settings.float_type)[None, :, :] * jitter\n return Kmm + jittermat\n"
] |
[
[
"tensorflow.shape",
"tensorflow.transpose",
"tensorflow.eye"
]
] |
v-mehta/kapture
|
[
"b95a15b83032d667282ab96fa5be5327b2c99ec7"
] |
[
"kapture/converter/opensfm/import_opensfm.py"
] |
[
"# Copyright 2020-present NAVER Corp. Under BSD 3-clause license\n\n\"\"\"\nOpenSfM to kapture import functions.\n\"\"\"\n\nimport logging\nimport os\nimport os.path as path\nimport numpy as np\nimport quaternion\nimport gzip\nimport pickle\nimport json\nfrom tqdm import tqdm\nfrom typing import Any, Dict, Optional, Tuple\n# kapture\nimport kapture\nfrom kapture.io.csv import kapture_to_dir\nimport kapture.io.features\nfrom kapture.io.records import TransferAction, import_record_data_from_dir_auto\nfrom kapture.io.structure import delete_existing_kapture_files\n\nlogger = logging.getLogger('opensfm')\n\n\"\"\"\nopensfm_project/\n├── config.yaml\n├── images/\n├── masks/\n├── gcp_list.txt\n├── exif/\n├── camera_models.json\n├── features/\n├── matches/\n├── tracks.csv\n├── reconstruction.json\n├── reconstruction.meshed.json\n└── undistorted/\n ├── images/\n ├── masks/\n ├── tracks.csv\n ├── reconstruction.json\n └── depthmaps/\n └── merged.ply\n\"\"\"\n\n\"\"\"\nreconstruction.json: [RECONSTRUCTION, ...]\n\nRECONSTRUCTION: {\n \"cameras\": {\n CAMERA_ID: CAMERA,\n ...\n },\n \"shots\": {\n SHOT_ID: SHOT,\n ...\n },\n \"points\": {\n POINT_ID: POINT,\n ...\n }\n}\n\nCAMERA: {\n \"projection_type\": \"perspective\", # Can be perspective, brown, fisheye or equirectangular\n \"width\": NUMBER, # Image width in pixels\n \"height\": NUMBER, # Image height in pixels\n\n # Depending on the projection type more parameters are stored.\n # These are the parameters of the perspective camera.\n \"focal\": NUMBER, # Estimated focal length\n \"k1\": NUMBER, # Estimated distortion coefficient\n \"k2\": NUMBER, # Estimated distortion coefficient\n}\n\nSHOT: {\n \"camera\": CAMERA_ID,\n \"rotation\": [X, Y, Z], # Estimated rotation as an angle-axis vector\n \"translation\": [X, Y, Z], # Estimated translation\n \"gps_position\": [X, Y, Z], # GPS coordinates in the reconstruction reference frame\n \"gps_dop\": METERS, # GPS accuracy in meters\n \"orientation\": NUMBER, # EXIF orientation tag (can be 1, 3, 6 or 8)\n \"capture_time\": SECONDS # Capture time as a UNIX timestamp\n}\n\nPOINT: {\n \"coordinates\": [X, Y, Z], # Estimated position of the point\n \"color\": [R, G, B], # Color of the point\n}\n\"\"\"\n\n\ndef import_camera(\n opensfm_camera: Dict[str, Any],\n name: Optional[str] = None\n) -> kapture.Camera:\n \"\"\"\n Converts OpenSfM camera to kapture.\n\n :param opensfm_camera: openSfM camera definition in a dictionary\n :param name: camera name\n :return: kapture camera definition\n \"\"\"\n\n # opensfm_camera['projection_type'] can be perspective, brown, fisheye or equirectangular\n\n if 'perspective' == opensfm_camera['projection_type']:\n # convert to CameraType.RADIAL [w, h, f, cx, cy, k1, k2]\n # missing principal point, just fake it at image center\n largest_side_in_pixel = float(max(opensfm_camera['width'], opensfm_camera['height']))\n camera_params = [\n # w, h:\n opensfm_camera['width'], opensfm_camera['height'],\n # f: The focal length provided by the EXIF metadata divided by the sensor width\n opensfm_camera['focal'] * largest_side_in_pixel,\n # cx, cy: no principal point, guess one at image center\n opensfm_camera['width'] / 2, opensfm_camera['height'] / 2,\n # k1, k2\n opensfm_camera.get('k1', 0.0), opensfm_camera.get('k2', 0.0),\n ]\n return kapture.Camera(kapture.CameraType.RADIAL, camera_params, name)\n\n else:\n raise ValueError(f'unable to convert camera of type {opensfm_camera[\"projection_type\"]}')\n\n\ndef _import_gnss(opensfm_root_dir, kapture_sensors, image_sensors, image_timestamps, disable_tqdm) \\\n -> Optional[kapture.RecordsGnss]:\n \"\"\"\n Imports the GNSS info from the images exif.\n\n \"\"\"\n # gps from pre-extracted exif, in exif/image_name.jpg.exif\n kapture_gnss = None\n opensfm_exif_dir_path = path.join(opensfm_root_dir, 'exif')\n opensfm_exif_suffix = '.exif'\n if path.isdir(opensfm_exif_dir_path):\n logger.info('importing GNSS from exif ...')\n camera_ids = set(image_sensors.values())\n # add a gps sensor for each camera\n map_cam_to_gnss_sensor = {cam_id: 'GPS_' + cam_id for cam_id in camera_ids}\n for gnss_id in map_cam_to_gnss_sensor.values():\n kapture_sensors[gnss_id] = kapture.Sensor(kapture.SensorType.gnss.name, ['EPSG:4326'])\n # build epsg_code for all cameras\n kapture_gnss = kapture.RecordsGnss()\n opensfm_exif_filepath_list = (path.join(dir_path, filename)\n for dir_path, _, filename_list in os.walk(opensfm_exif_dir_path)\n for filename in filename_list\n if filename.endswith(opensfm_exif_suffix))\n for opensfm_exif_filepath in tqdm(opensfm_exif_filepath_list, disable=disable_tqdm):\n image_filename = path.relpath(opensfm_exif_filepath, opensfm_exif_dir_path)[:-len(opensfm_exif_suffix)]\n image_timestamp = image_timestamps[image_filename]\n image_sensor_id = image_sensors[image_filename]\n gnss_timestamp = image_timestamp\n gnss_sensor_id = map_cam_to_gnss_sensor[image_sensor_id]\n with open(opensfm_exif_filepath, 'rt') as f:\n js_root = json.load(f)\n if 'gps' not in js_root:\n logger.warning(f'NO GPS data in \"{opensfm_exif_filepath}\"')\n continue\n\n gps_coords = {\n 'x': js_root['gps']['longitude'],\n 'y': js_root['gps']['latitude'],\n 'z': js_root['gps'].get('altitude', 0.0),\n 'dop': js_root['gps'].get('dop', 0),\n 'utc': 0,\n }\n logger.debug(f'found GPS data for ({gnss_timestamp}, {gnss_sensor_id}) in \"{opensfm_exif_filepath}\"')\n kapture_gnss[gnss_timestamp, gnss_sensor_id] = kapture.RecordGnss(**gps_coords)\n return kapture_gnss\n\n\ndef _import_features_and_matches(opensfm_root_dir, kapture_root_dir, disable_tqdm,\n keypoints_type: str = 'HessianAffine',\n descriptors_type: str = 'HOG')\\\n -> Tuple[Optional[kapture.Descriptors],\n Optional[kapture.Keypoints],\n Optional[kapture.Matches]]:\n # import features (keypoints + descriptors)\n kapture_keypoints = None # kapture.Keypoints(type_name='opensfm', dsize=4, dtype=np.float64)\n kapture_descriptors = None # kapture.Descriptors(type_name='opensfm', dsize=128, dtype=np.uint8)\n opensfm_features_dir_path = path.join(opensfm_root_dir, 'features')\n opensfm_features_suffix = '.features.npz'\n if path.isdir(opensfm_features_dir_path):\n logger.info('importing keypoints and descriptors ...')\n opensfm_features_file_list = (path.join(dp, fn)\n for dp, _, fs in os.walk(opensfm_features_dir_path) for fn in fs)\n opensfm_features_file_list = (filepath\n for filepath in opensfm_features_file_list\n if filepath.endswith(opensfm_features_suffix))\n for opensfm_feature_filename in tqdm(opensfm_features_file_list, disable=disable_tqdm):\n image_filename = path.relpath(opensfm_feature_filename, opensfm_features_dir_path)[\n :-len(opensfm_features_suffix)]\n opensfm_image_features = np.load(opensfm_feature_filename)\n opensfm_image_keypoints = opensfm_image_features['points']\n opensfm_image_descriptors = opensfm_image_features['descriptors']\n logger.debug(f'parsing keypoints and descriptors in {opensfm_feature_filename}')\n if kapture_keypoints is None:\n # print(type(opensfm_image_keypoints.dtype))\n # HAHOG = Hessian Affine feature point detector + HOG descriptor\n kapture_keypoints = kapture.Keypoints(\n type_name=keypoints_type,\n dsize=opensfm_image_keypoints.shape[1],\n dtype=opensfm_image_keypoints.dtype)\n if kapture_descriptors is None:\n kapture_descriptors = kapture.Descriptors(\n type_name=descriptors_type,\n dsize=opensfm_image_descriptors.shape[1],\n dtype=opensfm_image_descriptors.dtype,\n keypoints_type=keypoints_type,\n metric_type='L2')\n\n # convert keypoints file\n keypoint_file_path = kapture.io.features.get_features_fullpath(\n data_type=kapture.Keypoints,\n feature_type=keypoints_type,\n kapture_dirpath=kapture_root_dir,\n image_filename=image_filename)\n kapture.io.features.image_keypoints_to_file(keypoint_file_path, opensfm_image_keypoints)\n # register the file\n kapture_keypoints.add(image_filename)\n\n # convert descriptors file\n descriptor_file_path = kapture.io.features.get_features_fullpath(\n data_type=kapture.Descriptors,\n feature_type=descriptors_type,\n kapture_dirpath=kapture_root_dir,\n image_filename=image_filename)\n kapture.io.features.image_descriptors_to_file(\n filepath=descriptor_file_path, image_descriptors=opensfm_image_descriptors)\n # register the file\n kapture_descriptors.add(image_filename)\n # import matches\n kapture_matches = kapture.Matches()\n opensfm_matches_suffix = '_matches.pkl.gz'\n opensfm_matches_dir_path = path.join(opensfm_root_dir, 'matches')\n if path.isdir(opensfm_matches_dir_path):\n logger.info('importing matches ...')\n opensfm_matches_file_list = (path.join(dp, fn)\n for dp, _, fs in os.walk(opensfm_matches_dir_path) for fn in fs)\n opensfm_matches_file_list = (filepath\n for filepath in opensfm_matches_file_list\n if filepath.endswith(opensfm_matches_suffix))\n\n for opensfm_matches_filename in tqdm(opensfm_matches_file_list, disable=disable_tqdm):\n image_filename_1 = path.relpath(opensfm_matches_filename, opensfm_matches_dir_path)[\n :-len(opensfm_matches_suffix)]\n logger.debug(f'parsing matches in {image_filename_1}')\n with gzip.open(opensfm_matches_filename, 'rb') as f:\n opensfm_matches = pickle.load(f)\n for image_filename_2, opensfm_image_matches in opensfm_matches.items():\n image_pair = (image_filename_1, image_filename_2)\n # register the pair to kapture\n kapture_matches.add(*image_pair)\n # convert the bin file to kapture\n kapture_matches_filepath = kapture.io.features.get_matches_fullpath(\n image_filename_pair=image_pair,\n keypoints_type=keypoints_type,\n kapture_dirpath=kapture_root_dir)\n kapture_image_matches = np.hstack([\n opensfm_image_matches.astype(np.float64),\n # no matches scoring = assume all to one\n np.ones(shape=(opensfm_image_matches.shape[0], 1), dtype=np.float64)])\n kapture.io.features.image_matches_to_file(kapture_matches_filepath, kapture_image_matches)\n return kapture_descriptors, kapture_keypoints, kapture_matches\n\n\ndef import_opensfm(opensfm_root_dir: str,\n kapture_root_dir: str,\n force_overwrite_existing: bool = False,\n images_import_method: TransferAction = TransferAction.copy,\n keypoints_type: str = 'HessianAffine',\n descriptors_type: str = 'HOG'):\n \"\"\"\n Convert an openSfM structure to a kapture on disk. Also copy, move or link the images files if necessary.\n\n :param opensfm_root_dir: the openSfM top directory\n :param kapture_root_dir: top directory of kapture created\n :param force_overwrite_existing: if true, will remove existing kapture data without prompting the user\n :param images_import_method: action to apply on images: link, copy, move or do nothing.\n :param keypoints_type: keypoints type\n :param descriptors_type: descriptors type\n :return: the constructed kapture object\n \"\"\"\n disable_tqdm = logger.getEffectiveLevel() != logging.INFO\n # load reconstruction\n opensfm_reconstruction_filepath = path.join(opensfm_root_dir, 'reconstruction.json')\n with open(opensfm_reconstruction_filepath, 'rt') as f:\n opensfm_reconstruction = json.load(f)\n # remove the single list @ root\n opensfm_reconstruction = opensfm_reconstruction[0]\n\n # prepare space for output\n os.makedirs(kapture_root_dir, exist_ok=True)\n delete_existing_kapture_files(kapture_root_dir, force_erase=force_overwrite_existing)\n\n # import cameras\n kapture_sensors = kapture.Sensors()\n assert 'cameras' in opensfm_reconstruction\n # import cameras\n for osfm_camera_id, osfm_camera in opensfm_reconstruction['cameras'].items():\n camera = import_camera(osfm_camera, name=osfm_camera_id)\n kapture_sensors[osfm_camera_id] = camera\n\n # import shots\n logger.info('importing images and trajectories ...')\n kapture_images = kapture.RecordsCamera()\n kapture_trajectories = kapture.Trajectories()\n opensfm_image_dir_path = path.join(opensfm_root_dir, 'images')\n assert 'shots' in opensfm_reconstruction\n image_timestamps, image_sensors = {}, {} # used later to retrieve the timestamp of an image.\n for timestamp, (image_filename, shot) in enumerate(opensfm_reconstruction['shots'].items()):\n sensor_id = shot['camera']\n image_timestamps[image_filename] = timestamp\n image_sensors[image_filename] = sensor_id\n # in OpenSfm, (sensor, timestamp) is not unique.\n rotation_vector = shot['rotation']\n q = quaternion.from_rotation_vector(rotation_vector)\n translation = shot['translation']\n # capture_time = shot['capture_time'] # may be invalid\n # gps_position = shot['gps_position']\n kapture_images[timestamp, sensor_id] = image_filename\n kapture_trajectories[timestamp, sensor_id] = kapture.PoseTransform(r=q, t=translation)\n\n # copy image files\n filename_list = [f for _, _, f in kapture.flatten(kapture_images)]\n import_record_data_from_dir_auto(\n source_record_dirpath=opensfm_image_dir_path,\n destination_kapture_dirpath=kapture_root_dir,\n filename_list=filename_list,\n copy_strategy=images_import_method)\n\n # Imports Gnss\n kapture_gnss = _import_gnss(opensfm_root_dir, kapture_sensors, image_sensors, image_timestamps, disable_tqdm)\n # Imports descriptors, keypoints and matches\n kapture_descriptors, kapture_keypoints, kapture_matches = _import_features_and_matches(opensfm_root_dir,\n kapture_root_dir,\n disable_tqdm,\n keypoints_type,\n descriptors_type)\n\n # import 3-D points\n if 'points' in opensfm_reconstruction:\n logger.info('importing points 3-D')\n opensfm_points = opensfm_reconstruction['points']\n points_data = []\n for point_id in sorted(opensfm_points):\n point_data = opensfm_points[point_id]\n point_data = point_data['coordinates'] + point_data['color']\n points_data.append(point_data)\n kapture_points = kapture.Points3d(points_data)\n else:\n kapture_points = None\n\n # saving kapture csv files\n logger.info('saving kapture files')\n kapture_data = kapture.Kapture(\n sensors=kapture_sensors,\n records_camera=kapture_images,\n records_gnss=kapture_gnss,\n trajectories=kapture_trajectories,\n keypoints={keypoints_type: kapture_keypoints} if kapture_keypoints is not None else None,\n descriptors={descriptors_type: kapture_descriptors} if kapture_descriptors is not None else None,\n matches={keypoints_type: kapture_matches} if kapture_matches is not None else None,\n points3d=kapture_points\n )\n kapture_to_dir(kapture_root_dir, kapture_data)\n"
] |
[
[
"numpy.ones",
"numpy.load"
]
] |
Green-Resilience/wfRunner
|
[
"df5cff4e51484ac8b8a0fbdb4ec3ad6d05586817"
] |
[
"gsr/gs/objects/TransmittedSolar.py"
] |
[
"#-------------------------------------------------------------------------------\r\n# Name: TransmittedSolar.py\r\n# Purpose: Green Scale Tool TM Transmitted Solar Module (handles transmittance through a surface)\r\n#\r\n# Author: Holly Tina Ferguson\r\n#\r\n# Created: 15/09/2013\r\n# Copyright: (c) Holly Tina Ferguson 2013\r\n# Licence: The University of Notre Dame\r\n#-------------------------------------------------------------------------------\r\nimport math\r\nfrom objects.BaseElement import BaseElement\r\nfrom objects.Area import Area\r\nimport numpy\r\nimport scipy\r\nfrom GSUtility import GSUtility\r\nfrom scipy.interpolate import interp1d\r\nimport logging\r\n\r\nclass TransmittedSolar(BaseElement):\r\n\r\n #surface = Surface()\r\n\r\n def get_transmitted_solar(self, weather, surface, AreaShadowOnlyWin, areaWinDict):\r\n conversion = math.pi/180\r\n tilt = surface.tilt * conversion\r\n transmitted_win = 0\r\n azimuth_sun = weather[\"az_sun\"]\r\n #if azimuth_sun < 0: # This was only part of matlab version 2 and 3 but not currently version 4\r\n #azimuth_sun += (2*math.pi)\r\n azimuth_surface = surface.azimuth * conversion\r\n az_d = math.fabs(azimuth_sun - azimuth_surface)\r\n\r\n # Incidence = acos(sin(Alt_sun)*cos(tilt)+cos(az_d)*cos(Alt_sun)*sin(tilt));\r\n alt_sun = weather[\"alt_sun\"]\r\n incidence = math.acos( math.sin(alt_sun)*math.cos(tilt) + math.cos(az_d)*math.cos(alt_sun)*math.sin(tilt) )\r\n #print incidence\r\n check = math.cos(incidence)\r\n # Incidence_angle=sin(Alt_sun)*cos(tilt)+cos(az_d)*cos(Alt_sun)*sin(tilt);\r\n #incidence_angle = (math.sin(alt_sun)*math.cos(tilt)) + (math.cos(az_d)*math.cos(alt_sun)*math.sin(tilt))\r\n #angle = (math.fabs(incidence_angle)) / (math.pi/180)\r\n #print \"incidence_angle: \", angle\r\n # But according to above, needs to be of weather+1 ???\r\n Is = self.get_is_surface(surface, tilt, incidence, az_d, alt_sun, weather)\r\n\r\n # If there is an opening here, the U-value will need to be adjusted:\r\n # If the opening is a window, there is transmitted energy\r\n for opening in surface.openings:\r\n if opening.obj_type == \"OperableWindow\" or opening.obj_type == \"FixedWindow\" or opening.obj_type == \"OperableSkylight\":\r\n # Takes the surface number and opening number in that surface\r\n shgc = 1\r\n #area = Area()\r\n #A_this_window = area.surfaceArea(opening.ocps, surface.azimuth, surface.tilt, surface)\r\n A_this_window = areaWinDict[opening.obj_id]\r\n #A_this_window = opening.height * opening.width * 0.3048 * 0.3048\r\n A_this_opening = A_this_window - AreaShadowOnlyWin\r\n # From 0 to upper limit of math.cos(math.pi/2)\r\n if 0 < check < 0.999624216859:\r\n # Used to be using the shgc_dictionary set up in 3gbxml.py\r\n #incidence = 80*math.pi/180\r\n #shgc = self.get_shgc_opening(angle, shgc_dictionary) # before version 3 y is decsending, x is ascending\r\n # (0, 0.698, 0.873, 1.047, 1.222, 1.396 )\r\n x = (0, 40*math.pi/180, 50*math.pi/180, 60*math.pi/180, 70*math.pi/180, 80*math.pi/180, 90*math.pi/180)\r\n #y = (0.42, 0.67, 0.78, 0.82, 0.84, 0.86, 0.90)\r\n y = (0.86, 0.84, 0.82, 0.78, 0.67, 0.42, 0)\r\n f = scipy.interpolate.interp1d(x, y, kind='cubic') #, bounds_error='false', fill_value=0.86\r\n shgc = f(abs(incidence))\r\n\r\n else:\r\n shgc = 1\r\n #print shgc\r\n #shgc = 1\r\n\r\n transmitted = A_this_opening * shgc * Is\r\n #print A_this_opening\r\n # The summation of every opening on that surface added to the transmitted_win variable\r\n transmitted_win += transmitted\r\n #print transmitted_win\r\n return transmitted_win, Is\r\n\r\n def get_is_surface(self, surface, tilt, incidence, az_d, alt_sun, weather):\r\n Is = 0\r\n I_dn = weather[\"I_dn\"] # 0\r\n I_df = weather[\"I_df\"] # 0\r\n # The following comments are a note from the Matlab model:\r\n # if cos(Incidence)> -0.2\r\n # Y = 0.55+0.437*cos(Incidence)+0.313*(cos(Incidence))^2;\r\n # else\r\n # Y= 0.45;\r\n y = 1 # This will probably be replaced with the above if/else statements\r\n c = 0.118\r\n rho = 0.2\r\n #Ig = I_dn*(c + math.sin(alt_sun))*rho*(1 - math.cos(tilt))/2\r\n\r\n # Roof is different from walls - cases for Roof, RaisedFloor, and Other\r\n if surface.obj_type == \"Roof\":\r\n if tilt == 0:\r\n Is = I_dn*math.fabs(math.cos(incidence)) + I_df*(1 + math.cos(tilt))/2\r\n else:\r\n # else tilt > 0\r\n if az_d < math.pi/2 or az_d > 3*math.pi/2:\r\n # Means this is toward the sun\r\n Is = I_dn*math.fabs(math.cos(incidence)) + I_df*(1 + math.cos(tilt))/2\r\n else:\r\n # Else is standing against the sun\r\n Is = I_df*(1 + math.cos(tilt))/2\r\n elif surface.obj_type == \"RaisedFloor\":\r\n if az_d < math.pi/2 or az_d > 3*math.pi/2:\r\n # Means this is toward the sun\r\n Is = I_dn*abs(math.cos(incidence))+I_df*(1+math.cos(tilt))/2/y\r\n else:\r\n # Else is standing against the sun\r\n Is = I_df*(1+math.cos(tilt))/2/y\r\n else:\r\n # It is a normal wall surface toward the sun\r\n if az_d < math.pi/2 or az_d > 3*math.pi/2:\r\n Is = I_dn*abs(math.cos(incidence))+I_df*(1+math.cos(tilt))/2/y\r\n # It is a normal wall surface against the sun\r\n else:\r\n Is = I_df*(1+math.cos(tilt))/2/y\r\n\r\n return Is\r\n\r\n #def get_shgc_opening(self, incidence_angle, shgc_dictionary):\r\n # This was changed to a matching of a tuple in the dictionary \"hgcs_dictionary\" created in gbXML.py\r\n # Find the closest value to compare in the dictionary tuple values: 0,40,50,60,70,80\r\n\r\n # gives floating point answer, but if there are only 6 answers, a switch case may be simpler with less errors\r\n # options = [0, 40, 50, 60, 70, 80]\r\n # round(float(incidence_angle), -1) # This was one found way to round to the nearest 10\r\n # This leaves the same window for each value except 0, will need to check if first should be 35.5 OR 20.0\r\n\r\n # 0 = 0, 40*pi/180 = 0.6981, 50 = 0.8727, 60 = 1.0472, 70 = 1.2217, 80 = 1.3963\r\n\r\n #if incidence_angle < 35.5:\r\n # closest_sia = 0\r\n #elif incidence_angle >= 35 and incidence_angle < 45:\r\n # closest_sia = 40\r\n #elif incidence_angle >= 45 and incidence_angle < 55:\r\n # closest_sia = 50\r\n #elif incidence_angle >= 55 and incidence_angle < 65:\r\n # closest_sia = 60\r\n #elif incidence_angle >= 65 and incidence_angle < 75:\r\n # closest_sia = 70\r\n #elif incidence_angle >= 75: # Does it follow to leave this out? \"and incidence_angle < 85.5\"\r\n # closest_sia = 80\r\n #else:\r\n # closest_sia = 0 # giving it the smallest angle and thus largest-default heat-gain-coefficient for now\r\n\r\n #this_shgc = None\r\n #this_shgc = shgc_dictionary[closest_sia][1]\r\n #return this_shgc\r\n\r\n\r\n\r\n"
] |
[
[
"scipy.interpolate.interp1d"
]
] |
aitikgupta/swi-ml
|
[
"c7a44c71683a9bfb4adb13c7eb6117e652177807"
] |
[
"swi_ml/utils/manipulations.py"
] |
[
"from itertools import combinations_with_replacement\n\ntry:\n import numpy as np\nexcept ImportError:\n # exception already handled in backend\n pass\n\n\ndef index_combinations(degree, num_features):\n combinations = [\n combinations_with_replacement(range(num_features), i)\n for i in range(0, degree + 1)\n ]\n flat_combinations = [item for sublist in combinations for item in sublist]\n return flat_combinations\n\n\ndef transform_polynomial(X, degree):\n n_samples, n_features = np.shape(X)\n combinations = index_combinations(degree, n_features)\n n_output_features = len(combinations)\n\n X_new = np.empty((n_samples, n_output_features))\n\n for i, index_combs in enumerate(combinations):\n X_new[:, i] = np.prod(X[:, index_combs], axis=-1)\n\n return X_new\n\n\ndef normalize(X):\n X[:, 1:] = (X[:, 1:] - np.mean(X[:, 1:], axis=0)) / np.std(\n X[:, 1:], axis=0\n )\n return X\n"
] |
[
[
"numpy.empty",
"numpy.mean",
"numpy.shape",
"numpy.std",
"numpy.prod"
]
] |
ogomezr/concept-drift-simulator
|
[
"0de37e816fc57693bcfce1cf53d5719bb3eb207d"
] |
[
"modules/GenData.py"
] |
[
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jan 27 13:20:01 2020\n\n@author: Oscar\n\"\"\"\nimport numpy as np\n\ndef straighLine(x, m, n):\n y = m * x + n\n return y\n\n\ndef polFunc(x, a, b, c, d):\n y = (a * x**3) + (b * x**2) + c * x + d\n return y\n\n\ndef sinFunc(x, m, n, a, w, ph):\n y = m * x + a * (np.sin(w * x + ph)) + n\n return y\n\n\ndef genData(typeData,X,slope,axisY,a,b,c,d,amplitude,angular,phase):\n func = {\n 'straighLine': straighLine(X, slope, axisY),\n 'polinomial': polFunc(X, a, b, c, d),\n 'senoidal': sinFunc(X, slope, axisY, amplitude, angular, phase)\n } \n return func[typeData] "
] |
[
[
"numpy.sin"
]
] |
Musketeer-H2020/MMLL-Robust
|
[
"ccc0a7674a04ae0d00bedc38893b33184c5f68c6",
"ccc0a7674a04ae0d00bedc38893b33184c5f68c6"
] |
[
"MMLL/preprocessors/pca.py",
"MMLL/models/POM1/CommonML/POM1_CommonML.py"
] |
[
"# -*- coding: utf-8 -*-\r\n'''\r\nPreprocessing object for PCA extraction\r\n@author: Angel Navia Vázquez\r\n'''\r\n__author__ = \"Angel Navia Vázquez, UC3M.\"\r\n\r\nimport numpy as np\r\n\r\nclass PCA_model():\r\n\r\n def __init__(self):\r\n \"\"\"\r\n Parameters\r\n ----------\r\n None\r\n \"\"\"\r\n self.P = None\r\n self.name = 'PCA'\r\n\r\n def fit(self, Rxx, NF):\r\n \"\"\"\r\n Parameters\r\n ----------\r\n Rxx: matrix\r\n Cross-correlation matrix\r\n\r\n NF: int\r\n Number of features to extract\r\n \"\"\"\r\n self.NF = NF\r\n #self.eig_vals, self.eig_vecs = np.linalg.eig(Rxx)\r\n #self.P = self.eig_vecs[:, 0:NF]\r\n # More stable, equivalent\r\n U, self.s, V = np.linalg.svd(Rxx)\r\n self.P = V[0:NF, :].T\r\n\r\n def transform(self, X):\r\n\r\n \"\"\"\r\n Transform data reducing its dimensionality using PCA\r\n\r\n Parameters\r\n ----------\r\n X: ndarray\r\n Matrix with the input values\r\n\r\n Returns\r\n -------\r\n transformed values: ndarray\r\n\r\n \"\"\"\r\n try:\r\n X_transf = np.dot(X, self.P)\r\n except:\r\n print('ERROR AT PCA model transform')\r\n raise\r\n '''\r\n import code\r\n code.interact(local=locals())\r\n '''\r\n return X_transf",
"# -*- coding: utf-8 -*-\r\n'''\r\nCommon ML operations to be used by all algorithms in POM1.\r\n'''\r\n\r\n__author__ = \"Marcos Fernández Díaz\"\r\n__date__ = \"December 2020\"\r\n\r\n\r\nimport numpy as np\r\n\r\nfrom MMLL.models.Common_to_POMs_123 import Common_to_POMs_123_Master, Common_to_POMs_123_Worker\r\n\r\n\r\n\r\nclass POM1_CommonML_Master(Common_to_POMs_123_Master):\r\n \"\"\"\r\n This class implements the Common ML operations, run at Master node. It inherits from :class:`Common_to_POMs_123_Master`.\r\n \"\"\"\r\n\r\n def __init__(self, comms, logger, verbose=False):\r\n \"\"\"\r\n Create a :class:`POM1_CommonML_Master` instance.\r\n\r\n Parameters\r\n ----------\r\n comms: :class:`Comms_master`\r\n Object providing communications functionalities.\r\n\r\n logger: :class:`mylogging.Logger`\r\n Logging object instance.\r\n\r\n verbose: boolean\r\n Indicates whether to print messages on screen nor not.\r\n \"\"\"\r\n self.comms = comms\r\n self.logger = logger\r\n self.verbose = verbose\r\n\r\n self.name = 'POM1_CommonML_Master' # Name\r\n self.platform = comms.name # String with the platform to use (either 'pycloudmessenger' or 'local_flask')\r\n self.all_workers_addresses = comms.workers_ids # All addresses of the workers\r\n self.workers_addresses = comms.workers_ids # Addresses of the workers used to send messages to (can be adapted dynamically during the execution)\r\n self.Nworkers = len(self.workers_addresses) # Nworkers\r\n self.reset() # Reset variables\r\n self.state_dict = {} # Dictionary storing the execution state\r\n for worker in self.workers_addresses:\r\n self.state_dict.update({worker: ''})\r\n\r\n\r\n\r\n def reset(self):\r\n \"\"\"\r\n Create/reset some variables needed by the Master Node.\r\n\r\n Parameters\r\n ----------\r\n None\r\n \"\"\"\r\n self.display(self.name + ': Resetting local data')\r\n self.list_centroids = []\r\n self.list_counts = []\r\n self.list_dists = []\r\n self.list_public_keys = []\r\n self.dict_gradients = dict()\r\n self.dict_weights = dict()\r\n self.list_costs = []\r\n self.C_reconstruct = []\r\n self.rx = []\r\n\r\n \r\n \r\n\r\n#===============================================================\r\n# Worker \r\n#===============================================================\r\n\r\nclass POM1_CommonML_Worker(Common_to_POMs_123_Worker):\r\n '''\r\n Class implementing the POM1 Common operations, run at Worker node. It inherits from :class:`Common_to_POMs_123_Worker`.\r\n '''\r\n\r\n def __init__(self, master_address, comms, logger, verbose=False):\r\n \"\"\"\r\n Create a :class:`POM1_CommonML_Worker` instance.\r\n\r\n Parameters\r\n ----------\r\n master_address: string\r\n Identifier of the master instance.\r\n\r\n comms: :class:`Comms_worker`\r\n Object providing communication functionalities.\r\n\r\n logger: :class:`mylogging.Logger`\r\n Logging object instance.\r\n\r\n verbose: boolean\r\n Indicates whether to print messages on screen nor not.\r\n \"\"\"\r\n self.master_address = master_address\r\n self.comms = comms\r\n self.logger = logger\r\n self.verbose = verbose \r\n\r\n self.name = 'POM1_CommonML_Worker' # Name\r\n self.worker_address = comms.id # Id identifying the current worker\r\n self.platform = comms.name # String with the platform to use (either 'pycloudmessenger' or 'local_flask')\r\n self.preprocessors = [] # List to store all the preprocessors to be applied in sequential order to new data\r\n\r\n\r\n\r\n def ProcessPreprocessingPacket(self, packet):\r\n \"\"\"\r\n Process the received packet at worker.\r\n\r\n Parameters\r\n ----------\r\n packet: dictionary\r\n Packet received from master.\r\n \"\"\" \r\n if packet['action'] == 'SEND_MEANS':\r\n self.display(self.name + ' %s: Obtaining means' %self.worker_address)\r\n self.data_description = np.array(packet['data']['data_description'])\r\n means = np.mean(self.Xtr_b, axis=0)\r\n counts = self.Xtr_b.shape[0]\r\n action = 'COMPUTE_MEANS'\r\n data = {'means': means, 'counts':counts}\r\n packet = {'action': action, 'data': data} \r\n self.comms.send(packet, self.master_address)\r\n self.display(self.name + ' %s: Sent %s to master' %(self.worker_address, action)) \r\n\r\n if packet['action'] == 'SEND_STDS':\r\n self.display(self.name + ' %s: Obtaining stds' %self.worker_address)\r\n self.global_means = np.array(packet['data']['global_means'])\r\n X_without_mean = self.Xtr_b-self.global_means \r\n var = np.mean(X_without_mean*X_without_mean, axis=0)\r\n counts = self.Xtr_b.shape[0]\r\n\r\n action = 'COMPUTE_STDS'\r\n data = {'var': var, 'counts':counts}\r\n packet = {'action': action, 'data': data} \r\n self.comms.send(packet, self.master_address)\r\n self.display(self.name + ' %s: Sent %s to master' %(self.worker_address, action))\r\n \r\n if packet['action'] == 'SEND_MIN_MAX':\r\n self.display(self.name + ' %s: Obtaining means' %self.worker_address)\r\n self.data_description = np.array(packet['data']['data_description'])\r\n mins = np.min(self.Xtr_b, axis=0)\r\n maxs = np.max(self.Xtr_b, axis=0)\r\n\r\n action = 'COMPUTE_MIN_MAX'\r\n data = {'mins': mins, 'maxs':maxs}\r\n packet = {'action': action, 'data': data} \r\n self.comms.send(packet, self.master_address)\r\n self.display(self.name + ' %s: Sent %s to master' %(self.worker_address, action))\r\n \r\n if packet['action'] == 'SEND_PREPROCESSOR':\r\n self.display(self.name + ' %s: Receiving preprocessor' %self.worker_address)\r\n\r\n # Retrieve the preprocessing object\r\n prep_model = packet['data']['prep_model']\r\n\r\n # Apply the received object to Xtr_b and store back the result\r\n Xtr = np.copy(self.Xtr_b)\r\n X_prep = prep_model.transform(Xtr)\r\n self.Xtr_b = np.copy(X_prep)\r\n self.display(self.name + ' %s: Training set transformed using preprocessor' %self.worker_address)\r\n\r\n # Store the preprocessing object\r\n self.preprocessors.append(prep_model)\r\n self.display(self.name + ' %s: Final preprocessor stored' %self.worker_address)\r\n\r\n action = 'ACK_SEND_PREPROCESSOR'\r\n packet = {'action': action} \r\n self.comms.send(packet, self.master_address)\r\n self.display(self.name + ' %s: Sent %s to master' %(self.worker_address, action))\r\n\r\n"
] |
[
[
"numpy.dot",
"numpy.linalg.svd"
],
[
"numpy.max",
"numpy.array",
"numpy.copy",
"numpy.min",
"numpy.mean"
]
] |
Potopoles/pgw-python
|
[
"72b279725d7baf470403005a423a32217cb09402"
] |
[
"Preprocess_CCLM/PP_to_P.py"
] |
[
"# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport xarray as xr\n\n\"\"\"\nPreprocessing script to convert PP from COSMO-CLM to absolute pressure. This is only necessary if one subsequently wants to compute the mearelative Humidity from Specific humidity. \n\"\"\"\n\n#enter paths\nsuperpath='/project/pr04/robro/inputfiles_for_surrogate_hadgem/inputfiles/'\n\n#enter path to pp\nppname = 'HadGEM2-ES_Hist_RCP85_cosmo4-8_17_new_PP_2070-2099_ydaymean.nc'\nsavename = 'HadGEM2-ES_Hist_RCP85_cosmo4-8_17_new_P_2070-2099_ydaymean.nc'\n\nconst = xr.open_dataset('/store/c2sm/ch4/robro/surrogate_input/lffd1969120100c.nc')\nhsurf = const['HSURF'].squeeze()\n\n\nvcflat=11430. #altitude where coordinate system becomes flat (you can find that in runscripts)\n\n#CCLM uses a referece pressure system, to compute the actual pressure it PP needs to be added to the reference. These are the height levels for the 50km simulations!\n\nheight_flat=np.asanyarray([22700.0, 20800.0000, 19100.0, 17550.0, 16150.0, 14900.0, 13800.0, 12785.0, 11875.0, 11020.0, 10205.0, \t\t9440.0, 8710.0, 8015.0, 7355.0, 6725.0, 6130.0, 5565.0, 5035.0, 4530.0, 4060.0, 3615.0, 3200.0, 2815.0, 2455.0, 2125.0, 1820.0, 1545.0, 1295.0, 1070.0, 870.0, 695.0, 542.0, 412.0, 303.0, 214.0, 143.0, 89.0, 49.0, 20.0])\n\nsmoothing = (vcflat - height_flat) / vcflat\nsmoothing = np.where(smoothing > 0, smoothing, 0)\n\n\n#the height at which the reference pressure needs to be computed needs to be derived form the terrain \tfollowing coordinates:\nnewheights = np.zeros((len(height_flat), hsurf.shape[0], hsurf.shape[1]))\n\n#add the surface height but respect the terrain following coordinates\nfor x in range(hsurf.shape[0]):\n\tfor y in range(hsurf.shape[1]):\n\t\tnewheights[:,x,y] = height_flat + hsurf[x,y].values * smoothing\n\t\t\n#simple old equation\n#pref = 100000*np.exp(-(9.80665*0.0289644*newheights/(8.31447*288.15)))\n\n#New formulation as researched by Christian Steger (untested)\n# Constants\np0sl = 100000.0 # sea-level pressure [Pa]\nt0sl = 288.15 # sea-level temperature [K]\n# Source: COSMO description Part I, page 29\ng = 9.80665 # gravitational acceleration [m s-2]\nR_d = 287.05 # gas constant for dry air [J K-1 kg-1]\n# Source: COSMO source code, data_constants.f90\n\n# irefatm = 2\ndelta_t = 75.0\nh_scal = 10000.0\n# Source: COSMO description Part VII, page 66\nt00 = t0sl - delta_t\n\t\npref = p0sl * np.exp (-g / R_d * h_scal / t00 * \\\n np.log((np.exp(newheights / h_scal) * t00 + delta_t) / \\\n (t00 + delta_t)) )\n\nPP = xr.open_dataset(superpath+ppname)['PP']\n\np = PP + pref\n\t\np = p.astype('float32')\npds = p.to_dataset(name='P')\npds.to_netcdf(superpath+savename)\n\t\n"
] |
[
[
"numpy.where",
"numpy.asanyarray",
"numpy.exp"
]
] |
qychen13/ClusterAlignReID
|
[
"9dca1a39b7f1035c9579d80bbb73aa45480a616c"
] |
[
"utils/construct_engine.py"
] |
[
"import time\nimport os\nimport torch\nimport torch.nn as nn\nfrom torch.utils.tensorboard import SummaryWriter\n\nfrom .engine import Engine\nfrom .evaluation import test\nfrom .center import calculate_id_features, update_id_features\n\n\ndef construct_engine(engine_args, log_freq, log_dir, checkpoint_dir, checkpoint_freq, lr_scheduler, lr_scheduler_iter, metric_dict, query_iterator, gallary_iterator, id_feature_params, id_iterator, test_params):\n if lr_scheduler is not None and lr_scheduler_iter is not None:\n raise RuntimeError(\n 'Either lr_scheduler or lr_scheduler_iter can be used')\n engine = Engine(**engine_args)\n\n # tensorboard log setting\n writer = SummaryWriter(log_dir)\n\n # id features\n global id_features\n id_features = None\n\n ########## helper functions ##########\n # TODO: serialization of id feature training\n def save_model(state, filename):\n torch.save({\n 'state_dict': state['network'].state_dict(),\n 'optimizer': state['optimizer'].state_dict(),\n 'metrics': {key: metric_dict[key].value() for key in metric_dict},\n 'id_features': id_features\n }, filename)\n\n def reset_metrics():\n for key in metric_dict:\n metric_dict[key].reset()\n\n def update_metrics(state):\n paras = dict(logits=state['output'],\n target=state['sample'][1], loss=state['loss'])\n with torch.no_grad():\n for key in metric_dict:\n metric_dict[key](**paras)\n\n def wrap_data(state):\n if state['gpu_ids'] is not None:\n if len(state['gpu_ids']) == 1:\n state['sample'][0] = state['sample'][0].cuda(\n state['gpu_ids'][0], non_blocking=True)\n for key in state['sample'][1]:\n if isinstance(state['sample'][1][key], list):\n continue\n state['sample'][1][key] = state['sample'][1][key].cuda(\n state['gpu_ids'][0], non_blocking=True)\n\n ########## callback functions ##########\n def on_start(state):\n reset_metrics()\n if state['train']:\n if state['gpu_ids'] is None:\n print('Training/Validating without gpus ...')\n else:\n if not torch.cuda.is_available():\n raise RuntimeError('Cuda is not available')\n print(\n 'Training/Validating on gpu: {}'.format(state['gpu_ids']))\n\n if state['iteration'] == 0:\n filename = os.path.join(checkpoint_dir, 'init_model.pth.tar')\n save_model(state, filename)\n else:\n print('-------------Start Validation at {} For Epoch {}-------------'.format(\n time.strftime('%c'), state['epoch']))\n\n def on_start_epoch(state):\n print('-------------Start Training at {} For Epoch {}------------'.format(\n time.strftime('%c'), state['epoch']))\n if lr_scheduler is not None:\n scheduler = lr_scheduler\n else:\n scheduler = lr_scheduler_iter\n lr_scheduler_iter.step(state['iteration'])\n\n for i, lr in enumerate(scheduler.get_lr()):\n writer.add_scalar(\n 'global/learning_rate_{}'.format(i), lr, state['epoch'])\n reset_metrics()\n if id_feature_params['warm_up_epochs'] is not None and state['epoch'] > id_feature_params['warm_up_epochs']:\n global id_features\n if id_feature_params['update_freq'] == 'epoch' or id_features is None:\n id_features = calculate_id_features(\n state['network'], id_iterator, state['gpu_ids'], method=id_feature_params['method'])\n\n def on_end_sample(state):\n wrap_data(state)\n global id_features\n if state['train'] and id_features is not None: # add id feature as label\n state['sample'][1]['id_features'] = id_features[[\n state['sample'][1]['pid']]]\n state['sample'][1]['id_feature_dict'] = id_features\n\n if lr_scheduler_iter is not None:\n lr_scheduler_iter.step(state['iteration'])\n for i, lr in enumerate(lr_scheduler_iter.get_lr()):\n writer.add_scalar(\n 'training_iter/learning_rate_{}'.format(i), lr, state['iteration'])\n\n def on_end_forward(state):\n update_metrics(state)\n global id_features\n if state['train'] and id_features is not None and id_feature_params['update_freq'] == 'iteration':\n id_features = update_id_features(state['output'], state['sample'][1])\n\n def on_end_update(state):\n if state['iteration'] % log_freq == 0:\n for key in metric_dict:\n writer.add_scalar('training_iter/{}'.format(key),\n metric_dict[key].value(), state['iteration'])\n\n if lr_scheduler_iter is not None:\n lr_scheduler_iter.step(state['iteration']+1)\n\n\n def on_end_epoch(state):\n for key in metric_dict:\n writer.add_scalar('training/{}'.format(key),\n metric_dict[key].value(), state['epoch'])\n\n if (state['epoch'] + 1) % checkpoint_freq == 0:\n file_name = 'e{}t{}.pth.tar'.format(\n state['epoch'], state['iteration'])\n file_name = os.path.join(checkpoint_dir, file_name)\n save_model(state, file_name)\n # start testing\n t = time.strftime('%c')\n print(\n '*************************Start testing at {}**********************'.format(t))\n result = test(state['network'], query_iterator,\n gallary_iterator, state['gpu_ids'],**test_params)\n\n for key in result:\n writer.add_scalar('test/{}'.format(key),\n result[key], state['epoch'])\n\n # Note: adjust learning after calling optimizer.step() as required by update after pytorch 1.1.0\n if lr_scheduler is not None:\n lr_scheduler.step(state['epoch']+1)\n\n def on_end(state):\n t = time.strftime('%c')\n if state['train']:\n save_model(state, os.path.join(\n checkpoint_dir, 'final_model.pth.tar'))\n print(\n '*********************Training done at {}***********************'.format(t))\n writer.close()\n else:\n for key in metric_dict:\n writer.add_scalar('validation/{}'.format(key),\n metric_dict[key].value(), state['epoch'])\n\n engine.hooks['on_start'] = on_start\n engine.hooks['on_start_epoch'] = on_start_epoch\n engine.hooks['on_end_sample'] = on_end_sample\n engine.hooks['on_end_forward'] = on_end_forward\n engine.hooks['on_end_update'] = on_end_update\n engine.hooks['on_end_epoch'] = on_end_epoch\n engine.hooks['on_end'] = on_end\n\n return engine\n"
] |
[
[
"torch.no_grad",
"torch.cuda.is_available",
"torch.utils.tensorboard.SummaryWriter"
]
] |
Hridai/Fantasy-Premier-League
|
[
"60028688104f7c1ff7eceaa74e42ec7f54b9a6cb"
] |
[
"ht_analysis/appTemplate.py"
] |
[
"__doc__ = \"\"\"\ncurve_fitter_app.py is a plotly dash dashboard which allows hyperparameter tweaking\n============================================================\nChoose the existing curve and the country for which it has been fitted on for a\ndate and tweak the hyperparameters to see how the curve would behave.\nNote: The outlier detection methods do not work as of yet as the developer\nran out of time, and would definitely reccommend this be finished. The alpha\nand l1_ratio parameters are the pertinent ones.\nThe initial hyperparameters for each curves are read from the ModelHyperparameters\ntable.\n\"\"\"\nfrom warnings import filterwarnings\nfilterwarnings('ignore')\nfrom threading import Timer\nimport dash\nimport numpy as np # CAN REMOVE THIS?\nfrom datetime import datetime\nfrom statutils import StatUtil\nimport webbrowser\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport plotly.graph_objects as go\nimport pandas as pd\n\n\ndef open_browser(port):\n webbrowser.open_new(f'http://127.0.0.1:{port}/')\n\n# Global Variables - These can be abstracted to a 'User\" table if everyone has different preferences\n# spread_curvename = 'Sector Treasury'\n# scores = [0,10,20,30,40,50,60,70,80,90,100]\nexternal_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']\n# current_isin = 'AU3CB0249357'\ncurrent_curve = 'Industry AU Banks'\navailable_indicators_countries = ('AU','NZ')\ncurrent_country = 'AU'\n\nalpha_marks = {-3: '0.001',-2: '0.01',-1: '0.1',0: '1',0.5: '5',1: '10',\n 2: '100'}\n\napp = dash.Dash(__name__, external_stylesheets=external_stylesheets)\nserver = app.server\n\napp_color = {\"graph_bg\": \"#ffd5cc\", \"graph_line\": \"#007ACE\"}\n\n# To change the page background color:\n# app.layout = html.Div(style={'backgroundColor': app_color['graph_bg']},children=[\napp.layout = html.Div([\n html.Div([\n html.Div(\n [\n html.H4(\"Curve Calibration Dashboard\"),\n html.P(\n \"A dashboard which will let you re-model existing curves \" \\\n \"by tweaking model hyperparameters and outlier parameters.\"\n ),],\n ),\n ]),\n html.Div([\n html.Div([\n dcc.Dropdown(\n id='crossfilter-curvename',\n options=[{'label': i, 'value': i} for i in [1,2,3]],\n value=1\n )\n ],\n style={'width': '38%', 'display': 'inline-block'}),\n \n html.Div([\n dcc.Dropdown(\n id='crossfilter-country',\n options=[{'label': i, 'value': i} for i in \n available_indicators_countries],\n value=current_country\n )\n ], style={'width': '22%', 'float': 'centre', 'display': 'inline-block'}),\n \n html.Div([\n dcc.Dropdown(\n id='crossfilter-date',\n options=[{'label': i, 'value': i} for i in [1,2,3,4]],\n value = 2\n )\n ], style={'width': '40%', 'float': 'right', 'display': 'inline-block'})\n \n ], style={\n 'borderBottom': 'thin lightgrey solid',\n 'backgroundColor': 'rgb(250, 250, 250)',\n 'padding': '10px 5px'\n }),\n\n html.Div([\n dcc.Graph(\n id='crossfilter-indicator-scatter'\n )\n ], style={'width': '60%', 'height': '100%', 'display': 'inline-block',\n 'padding': '0 20'}),\n \n html.Div([\n html.H4(\"Hyperparameters\"),\n html.Plaintext(\"Alpha\"),\n dcc.Slider(\n id='slider-alpha',\n marks=alpha_marks,\n min=-3,\n max=2,\n step=None,\n value = -2\n ),\n html.Plaintext(\"L1 Ratio\"),\n dcc.Slider(\n id='slider-l1-ratio',\n min = 0,\n max = 1,\n value = 0.,\n marks={0: '0', 0.1: '0.1', 0.2: '0.2', 0.3: '0.3', 0.4: '0.4',\n 0.5: '0.5',0.6: '0.6',0.7: '0.7',0.8: '0.8',0.9: '0.9',\n 1: '1',\n },\n # marks={\"{:.1f}\".format(score): \"{:.1f}\".format(score) for score\n # in np.linspace(0,1,11)}, # no work.\n step=0.1\n ),\n html.Plaintext(\"Polynomial Degree\"),\n dcc.Slider(\n id='slider-polynomial-degree',\n min = 1,\n max = 10,\n value = 3,\n marks={1: '1',2: '2',3: '3',4: '4',5: '5',6: '6',7: '7',8: '8',\n 9: '9',10: '10',\n },\n step=1\n ),\n html.H4('Outlier Parameters'),\n html.Plaintext(\"X Axis Threshold\"),\n dcc.Slider(\n id='slider-outlier-x-axis-threshold',\n min = 0,\n max = 4,\n value = 1,\n marks={0: '0',0.5: '0.5',1: '1',1.5: '1.5',2: '2',2.5: '2.5',\n 3: '3',3.5: '3.5',4: '4'},\n step=0.5\n ),\n html.Plaintext(\"Std Error Threshold\"),\n dcc.Slider(\n id='slider-std-error-threshold',\n min = 0,\n max = 3,\n value = 2.,\n marks={0: '0',0.5: '0.5',1: '1',1.5: '1.5',2: '2',2.5: '2.5',\n 3: '3'},\n step=0.5\n ),\n html.Plaintext(\"DBScan EPS\"),\n dcc.Slider(\n id='slider-dbscan-eps',\n min = 0,\n max = 5,\n value = 2,\n marks={0: '0',1: '1',2: '2',3: '3',4: '4',5: '5'},\n step=1\n ),\n html.Plaintext(\"DBScan Min Samples\"),\n dcc.Slider(\n id='slider-dbscan-min-samples',\n min = 0,\n max = 6,\n value = 2,\n marks={0: '0',1: '1',2: '2',3: '3',4: '4',5: '5',6: '6'},\n step=1\n ),\n dcc.Checklist(\n options=[\n {'label': 'Parametric', 'value': 'outlier_parametric'},\n {'label': 'DBSCAN', 'value': 'outlier_dbscan'},\n {'label': 'X Axis Threshold', 'value': 'outlier_xthreshold'},\n {'label': 'Contamination', 'value': 'outlier_contamination'}\n ],\n value=['outlier_parametric', 'outlier_contamination'],\n labelStyle={'display': 'inline-block', 'padding': '30 50'},\n inputStyle={\"margin-left\": \"20px\"}\n ),\n # html.Button('Run', id='btn-run', n_clicks=0, \n # style={'margin-left': '1px'}),\n # html.Button('Reset', id='btn-reset', style={'background-color':'#b31200',\n # 'color':'white',\n # 'margin-left': '5px'}),\n ], style={'display': 'inline-block', 'width': '40%',\n 'height': '100%',\"verticalAlign\": \"top\"}),\n\n html.Div(id='rvcurves-full-df', style={'display': 'none'}),\n html.Div(id='durcurve-yield-history-df', style={'display': 'none'}),\n html.Div(id='hyperparams-df', style={'display': 'none'}),\n # Hyperparam values save in memory\n html.Div(id='adj-hyperparams-df', style={'display': 'none'}),\n])\n\n@app.callback(\n dash.dependencies.Output('adj-hyperparams-df', 'children'),\n [dash.dependencies.Input('slider-alpha', 'value'),\n dash.dependencies.Input('slider-l1-ratio', 'value'),\n dash.dependencies.Input('slider-polynomial-degree', 'value'),\n dash.dependencies.Input('slider-outlier-x-axis-threshold', 'value'),\n dash.dependencies.Input('slider-std-error-threshold', 'value'),\n dash.dependencies.Input('slider-dbscan-eps', 'value'),\n dash.dependencies.Input('slider-dbscan-min-samples', 'value'),\n ])\ndef load_adjusted_hyperparameters(alpha, l1ratio, polydeg, xaxisthresh,\n stderrorthresh, dbscaneps, dbscanminsamples):\n adjusted_hyperparams_dict = {\n 'alpha' : alpha_marks.get(alpha),\n 'l1_ratio' : l1ratio,\n 'polynomial_degree' : polydeg,\n 'x_axis_threshold' : xaxisthresh,\n 'std_error_threshold' : stderrorthresh,\n 'dbscan_eps' : dbscaneps,\n 'dbscan_min_samples' : dbscanminsamples,\n }\n df_res = pd.DataFrame(adjusted_hyperparams_dict.values(), \n index = adjusted_hyperparams_dict.keys())\n return df_res.to_json(orient='split')\n \n@app.callback(\n [dash.dependencies.Output('rvcurves-full-df', 'children'),\n dash.dependencies.Output('durcurve-yield-history-df', 'children'),\n dash.dependencies.Output('hyperparams-df', 'children')],\n [dash.dependencies.Input('crossfilter-curvename', 'value'),\n dash.dependencies.Input('crossfilter-country', 'value'),\n dash.dependencies.Input('crossfilter-date', 'value')\n ])\ndef load_dataframes(curvename, country, date):\n # date_object = datetime.strptime(date,'%Y-%m-%d')\n return pd.DataFrame().to_json(orient='split'), \\\n pd.DataFrame().to_json(orient='split'), \\\n pd.DataFrame().to_json(orient='split')\n\n@app.callback(\n dash.dependencies.Output('crossfilter-indicator-scatter', 'figure'),\n [dash.dependencies.Input('rvcurves-full-df', 'children'),\n dash.dependencies.Input('durcurve-yield-history-df', 'children'),\n dash.dependencies.Input('hyperparams-df', 'children'),\n dash.dependencies.Input('crossfilter-country', 'value'),\n dash.dependencies.Input('crossfilter-curvename', 'value'),\n dash.dependencies.Input('adj-hyperparams-df', 'children')])\ndef update_main_scatter_graph(json_rvcurves_full, json_durcurve_hist,\n json_hyperparams, country, curvename, json_adj_hyperparams):\n \n return 0\n\nif __name__ == '__main__':\n port = '8050'\n Timer(2, open_browser(port)).start();\n app.run_server(port=port, debug=False, dev_tools_hot_reload=False)"
] |
[
[
"pandas.DataFrame"
]
] |
HappyBall/tacotron
|
[
"52acd76485f2119475b7323a127beffc97db1074"
] |
[
"utils.py"
] |
[
"# -*- coding: utf-8 -*-\n'''\nBy kyubyong park. kbpark.linguist@gmail.com.\nhttps://www.github.com/kyubyong/dc_tts\n'''\nfrom __future__ import print_function, division\n\nfrom hyperparams import Hyperparams as hp\nimport numpy as np\nimport tensorflow as tf\nimport librosa\nimport copy\nimport matplotlib\nmatplotlib.use('pdf')\nimport matplotlib.pyplot as plt\nfrom scipy import signal\nimport os\n\n\ndef get_spectrograms(fpath):\n '''Returns normalized log(melspectrogram) and log(magnitude) from `sound_file`.\n Args:\n sound_file: A string. The full path of a sound file.\n\n Returns:\n mel: A 2d array of shape (T, n_mels) <- Transposed\n mag: A 2d array of shape (T, 1+n_fft/2) <- Transposed\n '''\n # num = np.random.randn()\n # if num < .2:\n # y, sr = librosa.load(fpath, sr=hp.sr)\n # else:\n # if num < .4:\n # tempo = 1.1\n # elif num < .6:\n # tempo = 1.2\n # elif num < .8:\n # tempo = 0.9\n # else:\n # tempo = 0.8\n # cmd = \"ffmpeg -i {} -y ar {} -hide_banner -loglevel panic -ac 1 -filter:a atempo={} -vn temp.wav\".format(fpath, hp.sr, tempo)\n # os.system(cmd)\n # y, sr = librosa.load('temp.wav', sr=hp.sr)\n\n # Loading sound file\n y, sr = librosa.load(fpath, sr=hp.sr)\n\n\n # Trimming\n y, _ = librosa.effects.trim(y)\n\n # Preemphasis\n y = np.append(y[0], y[1:] - hp.preemphasis * y[:-1])\n\n # stft\n linear = librosa.stft(y=y,\n n_fft=hp.n_fft,\n hop_length=hp.hop_length,\n win_length=hp.win_length)\n\n # magnitude spectrogram\n mag = np.abs(linear) # (1+n_fft//2, T)\n\n # mel spectrogram\n mel_basis = librosa.filters.mel(hp.sr, hp.n_fft, hp.n_mels) # (n_mels, 1+n_fft//2)\n mel = np.dot(mel_basis, mag) # (n_mels, t)\n\n # to decibel\n mel = 20 * np.log10(np.maximum(1e-5, mel))\n mag = 20 * np.log10(np.maximum(1e-5, mag))\n\n # normalize\n mel = np.clip((mel - hp.ref_db + hp.max_db) / hp.max_db, 1e-8, 1)\n mag = np.clip((mag - hp.ref_db + hp.max_db) / hp.max_db, 1e-8, 1)\n\n # Transpose\n mel = mel.T.astype(np.float32) # (T, n_mels)\n mag = mag.T.astype(np.float32) # (T, 1+n_fft//2)\n\n return mel, mag\n\n\ndef spectrogram2wav(mag):\n '''# Generate wave file from spectrogram'''\n # transpose\n mag = mag.T\n\n # de-noramlize\n mag = (np.clip(mag, 0, 1) * hp.max_db) - hp.max_db + hp.ref_db\n\n # to amplitude\n mag = np.power(10.0, mag * 0.05)\n\n # wav reconstruction\n wav = griffin_lim(mag)\n\n # de-preemphasis\n wav = signal.lfilter([1], [1, -hp.preemphasis], wav)\n\n # trim\n wav, _ = librosa.effects.trim(wav)\n\n return wav.astype(np.float32)\n\n\ndef griffin_lim(spectrogram):\n '''Applies Griffin-Lim's raw.\n '''\n X_best = copy.deepcopy(spectrogram)\n for i in range(hp.n_iter):\n X_t = invert_spectrogram(X_best)\n est = librosa.stft(X_t, hp.n_fft, hp.hop_length, win_length=hp.win_length)\n phase = est / np.maximum(1e-8, np.abs(est))\n X_best = spectrogram * phase\n X_t = invert_spectrogram(X_best)\n y = np.real(X_t)\n\n return y\n\n\ndef invert_spectrogram(spectrogram):\n '''\n spectrogram: [f, t]\n '''\n return librosa.istft(spectrogram, hp.hop_length, win_length=hp.win_length, window=\"hann\")\n\n\ndef plot_alignment(alignment, gs):\n \"\"\"Plots the alignment\n alignments: A list of (numpy) matrix of shape (encoder_steps, decoder_steps)\n gs : (int) global step\n \"\"\"\n fig, ax = plt.subplots()\n im = ax.imshow(alignment)\n\n # cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7])\n fig.colorbar(im)\n plt.title('{} Steps'.format(gs))\n plt.savefig('{}/alignment_{}k.png'.format(hp.logdir, gs//1000), format='png')\n\ndef learning_rate_decay(init_lr, global_step, warmup_steps=4000.):\n '''Noam scheme from tensor2tensor'''\n step = tf.cast(global_step + 1, dtype=tf.float32)\n return init_lr * warmup_steps ** 0.5 * tf.minimum(step * warmup_steps ** -1.5, step ** -0.5)\n\ndef load_spectrograms(fpath):\n fname = os.path.basename(fpath)\n mel, mag = get_spectrograms(fpath)\n t = mel.shape[0]\n num_paddings = hp.r - (t % hp.r) if t % hp.r != 0 else 0 # for reduction\n mel = np.pad(mel, [[0, num_paddings], [0, 0]], mode=\"constant\")\n mag = np.pad(mag, [[0, num_paddings], [0, 0]], mode=\"constant\")\n return fname, mel.reshape((-1, hp.n_mels*hp.r)), mag\n"
] |
[
[
"matplotlib.use",
"numpy.append",
"numpy.pad",
"numpy.dot",
"tensorflow.minimum",
"numpy.real",
"matplotlib.pyplot.subplots",
"scipy.signal.lfilter",
"numpy.power",
"numpy.abs",
"numpy.clip",
"tensorflow.cast",
"numpy.maximum"
]
] |
T-Almeida/mmnrm
|
[
"f67441a4e2cb0a8335b5e96f3ea9ea0a0eba080a"
] |
[
"mmnrm/utils.py"
] |
[
"import numpy as np\nimport random\nimport tensorflow as tf\nimport h5py\nimport pickle\nimport mmnrm.modelsv2\nimport math\n\nfrom datetime import datetime as dt\n\n\ndef set_random_seed(seed_value=42):\n tf.random.set_seed(seed_value)\n random.seed(seed_value)\n np.random.seed(seed_value)\n \n \ndef save_model_weights(file_name, model):\n with h5py.File(file_name+\".h5\", 'w') as f:\n weight = model.get_weights()\n for i in range(len(weight)):\n f.create_dataset('weight'+str(i), data=weight[i])\n\ndef load_model_weights(file_name, model):\n with h5py.File(file_name+\".h5\", 'r') as f:\n weight = []\n for i in range(len(f.keys())):\n weight.append(f['weight'+str(i)][:])\n model.set_weights(weight)\n\ndef load_sentence_generator(cfg, tk=None, return_tk=False):\n\n if tk is None:\n tk = load_tokenizer(cfg)\n \n model_cfg = cfg[\"model\"]\n \n max_input_query = model_cfg[\"max_q_length\"]\n max_input_sentence = model_cfg[\"max_s_length\"]\n max_s_per_q_term = model_cfg[\"max_s_per_q_term\"]\n \n # redundant code... replace\n max_sentences_per_query = model_cfg[\"max_s_per_q_term\"]\n\n pad_query = lambda x, dtype='int32': tf.keras.preprocessing.sequence.pad_sequences(x, \n maxlen=max_input_query,\n dtype=dtype, \n padding='post', \n truncating='post', \n value=0)\n\n pad_sentences = lambda x, dtype='int32': tf.keras.preprocessing.sequence.pad_sequences(x, \n maxlen=max_input_sentence,\n dtype=dtype, \n padding='post', \n truncating='post', \n value=0)\n\n pad_docs = lambda x, max_lim, dtype='int32': x[:max_lim] + [[]]*(max_lim-len(x))\n\n idf_from_id_token = lambda x: math.log(tk.document_count/tk.word_docs[tk.index_word[x]])\n\n # inline import\n from mmnrm.dataset import sentence_splitter_builderV2\n train_sentence_generator, test_sentence_generator = sentence_splitter_builderV2(tk, \n max_sentence_size=max_input_sentence,\n mode=4)\n \n def train_input_generator(data_generator):\n data_generator = train_sentence_generator(data_generator)\n\n while True:\n query, pos_docs, pos_extra_features, neg_docs, neg_extra_features = next(data_generator)\n\n query_idf = np.array([list(map(lambda x: idf_from_id_token(x), t_q)) for t_q in query])\n\n # padding\n for i in range(len(pos_docs)):\n pos_docs[i] = pad_docs(pos_docs[i], max_lim=model_cfg['max_q_length'])\n neg_docs[i] = pad_docs(neg_docs[i], max_lim=model_cfg['max_q_length'])\n\n for q in range(len(pos_docs[i])):\n\n pos_docs[i][q] = pad_docs(pos_docs[i][q], max_lim=model_cfg['max_s_per_q_term'])\n neg_docs[i][q] = pad_docs(neg_docs[i][q], max_lim=model_cfg['max_s_per_q_term'])\n\n pos_docs[i][q] = pad_sentences(pos_docs[i][q])\n neg_docs[i][q] = pad_sentences(neg_docs[i][q])\n\n query = pad_query(query)\n query_idf = pad_query(query_idf, dtype=\"float32\")\n \n yield [query, np.array(pos_docs), query_idf], [query, np.array(neg_docs), query_idf]\n \n \n def test_input_generator(data_generator):\n\n data_generator = test_sentence_generator(data_generator)\n\n for ids, queries, l_docs in data_generator:\n \n tokenized_docs = []\n ids_docs = []\n offsets_docs = []\n ids_queries = []\n queries_idf = []\n tokenized_queries = []\n for i in range(len(ids)):\n #tokenization\n query_idf = list(map(lambda x: idf_from_id_token(x), queries[i]))\n\n for doc in l_docs[i]:\n\n padded_doc = pad_docs(doc[\"text\"], max_lim=max_input_query)\n for q in range(len(padded_doc)):\n padded_doc[q] = pad_docs(padded_doc[q], max_lim=max_sentences_per_query)\n padded_doc[q] = pad_sentences(padded_doc[q])\n tokenized_docs.append(padded_doc)\n ids_docs.append(doc[\"id\"])\n offsets_docs.append(doc[\"offset\"])\n \n\n # padding\n query = pad_query([queries[i]])[0]\n query = [query] * len(l_docs[i])\n tokenized_queries.append(query)\n \n query_idf = pad_query([query_idf], dtype=\"float32\")[0]\n query_idf = [query_idf] * len(l_docs[i])\n queries_idf.append(query_idf)\n ids_queries.append([ids[i]]*len(l_docs[i]))\n \n yield flat_list(ids_queries), [np.array(flat_list(tokenized_queries)), np.array(tokenized_docs), np.array(flat_list(queries_idf))], ids_docs, offsets_docs\n \n \n if return_tk:\n return train_input_generator, test_input_generator, tk\n else:\n return train_input_generator, test_input_generator\n \n \n\ndef load_neural_model(path_to_weights, return_snippets_score=True):\n \n rank_model = load_model(path_to_weights, change_config={\"return_snippets_score\":return_snippets_score})\n tk = rank_model.tokenizer \n\n return rank_model, load_sentence_generator(rank_model.savable_config, tk)\n \ndef save_model(file_name, model):\n cfg = model.savable_config\n with open(file_name+\".cfg\",\"wb\") as f:\n pickle.dump(model.savable_config ,f)\n \n # keep using h5py for weights\n save_model_weights(file_name, model)\n \ndef load_model(file_name, change_config={}, auxiliar_module_source=None):\n \n with open(file_name+\".cfg\",\"rb\") as f:\n cfg = pickle.load(f)\n \n cfg[\"model\"] = merge_dicts(cfg[\"model\"], change_config)\n \n if auxiliar_module_source is None:\n # create the model with the correct configuration\n model = getattr(mmnrm.modelsv2, cfg['func_name'])(**cfg)\n else:\n model = getattr(auxiliar_module_source, cfg['func_name'])(**cfg)\n \n # load weights\n load_model_weights(file_name, model)\n \n return model\n\ndef load_model_config(file_name):\n with open(file_name+\".cfg\",\"rb\") as f:\n cfg = pickle.load(f)\n \n return cfg\n\ndef load_tokenizer(cfg):\n \n tk = cfg['tokenizer']['class'].load_from_json(**cfg['tokenizer']['attr'])\n tk.update_min_word_frequency(cfg['tokenizer']['min_freq'])\n \n return tk\n\ndef merge_dicts(*list_of_dicts):\n # fast merge according to https://stackoverflow.com/questions/1781571/how-to-concatenate-two-dictionaries-to-create-a-new-one-in-python\n \n temp = dict(list_of_dicts[0], **list_of_dicts[1])\n \n for i in range(2, len(list_of_dicts)):\n temp.update(list_of_dicts[i])\n \n return temp\n\ndef flat_list(x):\n return sum(x, [])\n\ndef index_from_list(searchable_list, comparison):\n for i,item in enumerate(searchable_list):\n if comparison(item):\n return i\n return -1\n\ndef overlap(snippetA, snippetB):\n \"\"\"\n snippetA: goldSTD\n \"\"\"\n if snippetA[0]>snippetB[1] or snippetA[1] < snippetB[0]:\n return 0\n else:\n if snippetA[0]>=snippetB[0] and snippetA[1] <= snippetB[1]:\n return snippetA[1] - snippetA[0] + 1\n if snippetA[0]>=snippetB[0] and snippetA[1] > snippetB[1]:\n return snippetB[1] - snippetA[0] + 1\n if snippetA[0]<snippetB[0] and snippetA[1] <= snippetB[1]:\n return snippetA[1] - snippetB[0] + 1\n if snippetA[0]<snippetB[0] and snippetA[1] > snippetB[1]:\n return snippetB[1] - snippetA[0] + 1\n \n return 0\n\ndef to_date(_str):\n for fmt in (\"%Y-%m\", \"%Y-%m-%d\", \"%Y\"):\n try:\n return dt.strptime(_str, fmt)\n except ValueError:\n pass\n raise ValueError(\"No format found\")\n"
] |
[
[
"tensorflow.random.set_seed",
"tensorflow.keras.preprocessing.sequence.pad_sequences",
"numpy.array",
"numpy.random.seed"
]
] |
mrajart/dlcourse_ai
|
[
"ff0c82f0e9f6c1abbb1f1daa5e40a480091f79f2"
] |
[
"assignments/assignment3/layers.py"
] |
[
"import numpy as np\nimport math\n\ndef l2_regularization(W, reg_strength):\n '''\n Computes L2 regularization loss on weights and its gradient\n\n Arguments:\n W, np array - weights\n reg_strength - float value\n\n Returns:\n loss, single value - l2 regularization loss\n gradient, np.array same shape as W - gradient of weight by l2 loss\n '''\n # TODO: Copy from previous assignment\n loss = reg_strength * np.trace(np.matmul(W.T, W)) # L2(W) = λ * tr(W.T * W)\n grad = 2 * reg_strength * W # dL2(W)/dW = 2 * λ * W\n \n return loss, grad\n\n\ndef softmax(predictions):\n '''\n Computes probabilities from scores\n\n Arguments:\n predictions, np array, shape is either (N) or (batch_size, N) -\n classifier output\n\n Returns:\n probs, np array of the same shape as predictions - \n probability for every class, 0..1\n '''\n # TODO implement softmax\n # Your final implementation shouldn't have any loops\n single = (predictions.ndim == 1)\n\n if single:\n predictions = predictions.reshape(1, predictions.shape[0])\n\n maximums = np.amax(predictions, axis=1).reshape(predictions.shape[0], 1)\n predictions_ts = predictions - maximums\n\n predictions_exp = np.exp(predictions_ts)\n sums = np.sum(predictions_exp, axis=1).reshape(predictions_exp.shape[0], 1)\n result = predictions_exp / sums\n\n if single:\n result = result.reshape(result.size)\n\n return result \n\n\ndef cross_entropy_loss(probs, target_index):\n '''\n Computes cross-entropy loss\n\n Arguments:\n probs, np array, shape is either (N) or (batch_size, N) -\n probabilities for every class\n target_index: np array of int, shape is (1) or (batch_size) -\n index of the true class for given sample(s)\n\n Returns:\n loss: single value\n '''\n # TODO implement cross-entropy\n # Your final implementation shouldn't have any loops\n new_loss = np.vectorize(lambda x: -math.log(x))\n if len(probs.shape) == 1:\n probs_target = probs[target_index]\n size_target = 1\n else:\n batch_size = np.arange(target_index.shape[0])\n probs_target = probs[batch_size,target_index.flatten()]\n size_target = target_index.shape[0]\n loss = np.sum(new_loss(probs_target)) / size_target\n return loss\n\ndef softmax_with_cross_entropy(predictions, target_index):\n '''\n Computes softmax and cross-entropy loss for model predictions,\n including the gradient\n\n Arguments:\n predictions, np array, shape is either (N) or (batch_size, N) -\n classifier output\n target_index: np array of int, shape is (1) or (batch_size) -\n index of the true class for given sample(s)\n\n Returns:\n loss, single value - cross-entropy loss\n dprediction, np array same shape as predictions - gradient of predictions by loss value\n '''\n # TODO copy from the previous assignment\n prediction = predictions.copy()\n probs = softmax(prediction) \n loss = cross_entropy_loss(probs, target_index)\n d_preds = probs\n if len(predictions.shape)==1:\n d_preds[target_index] -= 1\n else:\n batch_size = np.arange(target_index.shape[0])\n d_preds[batch_size,target_index.flatten()] -= 1\n d_preds = d_preds/target_index.shape[0]\n\n return loss, d_preds\n\n\nclass Param:\n '''\n Trainable parameter of the model\n Captures both parameter value and the gradient\n '''\n def __init__(self, value):\n self.value = value\n self.grad = np.zeros_like(value)\n\n \nclass ReLULayer:\n def __init__(self):\n pass\n\n def forward(self, X):\n # TODO copy from the previous assignment\n self.d_out_result = np.greater(X, 0).astype(float) # dZ/dX\n return np.maximum(X, 0) # Z\n\n def backward(self, d_out):\n # TODO copy from the previous assignment\n d_result = np.multiply(d_out, self.d_out_result) # dL/dX = dL/dZ * dZ/dX\n return d_result # dL/dX\n\n def params(self):\n return {}\n def reset_grad(self):\n pass\n\n\nclass FullyConnectedLayer:\n def __init__(self, n_input, n_output):\n self.W = Param(0.001 * np.random.randn(n_input, n_output))\n self.B = Param(0.001 * np.random.randn(1, n_output))\n self.X = None\n self.dw = None\n\n def forward(self, X):\n # TODO copy from the previous assignment\n self.X = X\n return np.matmul(X, self.W.value) + self.B.value\n\n def backward(self, d_out):\n # TODO copy from the previous assignment\n \n d_input = np.matmul(d_out, self.W.value.T) # dL/dX = dL/dZ * dZ/dX = dL/dZ * W.T\n dLdW = np.matmul(self.X.T, d_out) # dL/dW = dL/dZ * dZ/dW = X.T * dL/dZ\n dLdB = 2 * np.mean(d_out, axis=0) # dL/dB = dL/dZ * dZ/dB = I * dL/dZ\n\n self.W.grad += dLdW\n self.B.grad += dLdB\n\n return d_input # dL/dX\n\n def params(self):\n return { 'W': self.W, 'B': self.B }\n def reset_grad(self):\n self.W.grad = np.zeros_like(self.W.value)\n self.B.grad = np.zeros_like(self.B.value)\n\n \nclass ConvolutionalLayer:\n def __init__(self, in_channels, out_channels,\n filter_size, padding):\n '''\n Initializes the layer\n \n Arguments:\n in_channels, int - number of input channels\n out_channels, int - number of output channels\n filter_size, int - size of the conv filter\n padding, int - number of 'pixels' to pad on each side\n '''\n\n self.filter_size = filter_size\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.W = Param(\n np.random.randn(filter_size, filter_size,\n in_channels, out_channels)\n )\n\n self.B = Param(np.zeros(out_channels))\n\n self.padding = padding\n\n\n def forward(self, X):\n batch_size, height, width, channels = X.shape\n\n self.X = X\n\n if self.padding:\n self.X = np.zeros((batch_size,\n height + 2 * self.padding,\n width + 2 * self.padding,\n channels), dtype=X.dtype)\n self.X[:, self.padding: -self.padding, self.padding: -self.padding, :] = X\n\n _, height, width, channels = self.X.shape\n\n out_height = height - self.filter_size + 1\n out_width = width - self.filter_size + 1\n\n output = []\n\n # TODO: Implement forward pass\n # Hint: setup variables that hold the result\n # and one x/y location at a time in the loop below\n # It's ok to use loops for going over width and height\n # but try to avoid having any other loops\n for y in range(out_height):\n row = []\n for x in range(out_width):\n x_filter = self.X[:, y: y + self.filter_size, x: x + self.filter_size, :]\n x_filter = np.transpose(x_filter, axes=[0, 3, 2, 1]).reshape((batch_size, self.filter_size * self.filter_size * channels))\n \n W_filter = np.transpose(self.W.value, axes=[2, 0, 1, 3])\n out = x_filter.dot(W_filter.reshape((self.filter_size * self.filter_size * self.in_channels, self.out_channels)))\n \n # out has shape (batch_size, out_channel)\n row.append(np.array([out], dtype=self.W.value.dtype).reshape((batch_size, 1, 1, self.out_channels)))\n output.append(np.dstack(row))\n output = np.hstack(output)\n output += self.B.value\n\n return output\n\n\n def backward(self, d_out):\n # Hint: Forward pass was reduced to matrix multiply\n # You already know how to backprop through that\n # when you implemented FullyConnectedLayer\n # Just do it the same number of times and accumulate gradients\n\n batch_size, height, width, channels = self.X.shape\n _, out_height, out_width, out_channels = d_out.shape\n\n # TODO: Implement backward pass\n # Same as forward, setup variables of the right shape that\n # aggregate input gradient and fill them for every location\n # of the output\n d_in = np.zeros(self.X.shape)\n # Try to avoid having any other loops here too\n for y in range(out_height):\n for x in range(out_width):\n # TODO: Implement backward pass for specific location\n # Aggregate gradients for both the input and\n # the parameters (W and B)\n d_filter = d_out[:, y, x, :]\n\n X_filter = self.X[:, y: y + self.filter_size, x: x + self.filter_size, :]\n\n X_filter = np.transpose(X_filter, axes=[0, 3, 1, 2])\n X_filter = X_filter.reshape((batch_size, self.filter_size * self.filter_size * channels))\n X_transpose = X_filter.transpose()\n\n W_filter = np.transpose(self.W.value, axes=[2, 0, 1, 3])\n W_filter = W_filter.reshape((self.filter_size * self.filter_size * self.in_channels, self.out_channels))\n W_transpose = W_filter.transpose()\n\n d_W_filter = np.dot(X_transpose, d_filter)\n d_W_filter = d_W_filter.reshape(self.in_channels, self.filter_size, self.filter_size, self.out_channels)\n d_W_transpose = np.transpose(d_W_filter, axes=[2, 1, 0, 3])\n\n self.W.grad += d_W_transpose\n E = np.ones(shape=(1, batch_size))\n B = np.dot(E, d_filter)\n B = B.reshape((d_filter.shape[1]))\n self.B.grad += B\n\n d_in_xy = np.dot(d_filter, W_transpose)#d_filter.dot(w_filter.transpose())\n d_in_xy = d_in_xy.reshape((batch_size, channels, self.filter_size, self.filter_size))\n\n d_in_xy = np.transpose(d_in_xy, axes=[0, 3, 2, 1])\n\n d_in[:, y: y + self.filter_size, x: x + self.filter_size, :] += d_in_xy\n\n if self.padding:\n d_in = d_in[:, self.padding: -self.padding, self.padding: -self.padding, :]\n\n return d_in\n\n\n def params(self):\n return { 'W': self.W, 'B': self.B }\n def reset_grad(self):\n self.W.grad = np.zeros_like(self.W.value)\n self.B.grad = np.zeros_like(self.B.value)\n\n\nclass MaxPoolingLayer:\n def __init__(self, pool_size, stride):\n '''\n Initializes the max pool\n\n Arguments:\n pool_size, int - area to pool\n stride, int - step size between pooling windows\n '''\n self.pool_size = pool_size\n self.stride = stride\n self.X = None\n\n def forward(self, X):\n batch_size, height, width, channels = X.shape\n # TODO: Implement maxpool forward pass\n # Hint: Similarly to Conv layer, loop on\n # output x/y dimension\n\n self.X = X\n\n output = []\n for y in range(0, height, self.stride):\n row = []\n for x in range(0, width, self.stride):\n X_filter = X[:, y: y + self.pool_size, x: x + self.pool_size, :]\n row.append(X_filter.max(axis=1).max(axis=1).reshape(batch_size, 1, 1, channels))\n row = np.dstack(row)\n output.append(row)\n output = np.hstack(output)\n\n return output\n\n def backward(self, d_out):\n # TODO: Implement maxpool backward pass\n batch_size, height, width, channels = self.X.shape\n\n output = np.zeros(self.X.shape)\n \n for y_num, y in enumerate(range(0, height, self.stride)):\n for x_num, x in enumerate(range(0, width, self.stride)):\n d_filter = d_out[:, y_num, x_num, :]\n d_filter = d_filter.reshape(batch_size, 1, 1, channels)\n X_filter = self.X[:, y: y + self.pool_size, x: x + self.pool_size, :]\n d_filter_out = (X_filter == X_filter.max(axis=1).max(axis=1).reshape(batch_size, 1, 1, channels)) * d_filter\n output[:, y: y + self.pool_size, x: x + self.pool_size, :] += d_filter_out.astype(np.float32)\n return output\n\n def params(self):\n return {}\n def reset_grad(self):\n pass\n\n\nclass Flattener:\n def __init__(self):\n self.X_shape = None\n\n def forward(self, X):\n batch_size, height, width, channels = X.shape\n\n # TODO: Implement forward pass\n # Layer should return array with dimensions\n # [batch_size, hight*width*channels]\n self.X_shape = X.shape\n return X.reshape((batch_size, height * width * channels))\n\n def backward(self, d_out):\n # TODO: Implement backward pass\n return d_out.reshape(self.X_shape)\n\n def params(self):\n # No params!\n return {}\n def reset_grad(self):\n pass\n"
] |
[
[
"numpy.zeros_like",
"numpy.dot",
"numpy.array",
"numpy.matmul",
"numpy.zeros",
"numpy.sum",
"numpy.ones",
"numpy.random.randn",
"numpy.exp",
"numpy.mean",
"numpy.multiply",
"numpy.arange",
"numpy.amax",
"numpy.transpose",
"numpy.greater",
"numpy.dstack",
"numpy.hstack",
"numpy.maximum"
]
] |
ntaylorwss/megatron
|
[
"a6c572e04583e21715f3eaf35630cb4d75f686f7"
] |
[
"megatron/layers/shaping.py"
] |
[
"import numpy as np\nimport pandas as pd\nfrom .core import StatelessLayer, StatefulLayer\n\n\nclass Cast(StatelessLayer):\n \"\"\"Re-defines the data type for a Numpy array's contents.\n\n Parameters\n ----------\n new_type : type\n the new type for the array to be cast to.\n \"\"\"\n def __init__(self, new_type):\n if not isinstance(new_type, type):\n raise TypeError(\"new_type must be a valid datatype\")\n super().__init__(new_type=new_type)\n\n def transform(self, X):\n return X.astype(self.kwargs['new_type'])\n\n\nclass AddDim(StatelessLayer):\n \"\"\"Add a dimension to an array.\n\n Parameters\n ----------\n axis : int\n the axis along which to place the new dimension.\n \"\"\"\n def __init__(self, axis=-1):\n super().__init__(axis=axis)\n\n def transform(self, X):\n if self.kwargs['axis'] > len(X.shape):\n raise ValueError(\"Axis out of range for new dimension\")\n return np.expand_dims(X, axis=self.kwargs['axis'])\n\n\nclass OneHotRange(StatefulLayer):\n \"\"\"One-hot encode a numeric array where the values are a sequence.\"\"\"\n def __init__(self, strict=False):\n super().__init__(strict=strict)\n\n def partial_fit(self, X):\n try:\n X.astype(int)\n except ValueError:\n raise TypeError(\"Array must be ints only\")\n if not np.array_equal(X, X.astype(int)):\n raise TypeError(\"Array must be ints only\")\n\n if self.metadata:\n self.metadata['min_val'] = min([self.metadata['min_val'], X.min()])\n self.metadata['max_val'] = max([self.metadata['max_val'], X.max()])\n else:\n self.metadata['min_val'] = X.min()\n self.metadata['max_val'] = X.max()\n\n def transform(self, X):\n out = (np.arange(self.metadata['min_val'], self.metadata['max_val']+1) == X[..., None]) * 1\n if self.kwargs['strict'] and (out.sum(axis=-1) == 0).any():\n raise ValueError(\"New value encountered in transform that was not present in fit\")\n return out\n\n\nclass OneHotLabels(StatefulLayer):\n \"\"\"One-hot encode an array of categorical values, or non-consecutive numeric values.\"\"\"\n def __init__(self, strict=False):\n super().__init__(strict=strict)\n\n def partial_fit(self, X):\n if self.metadata:\n self.metadata['categories'] = np.append(self.metadata['categories'], np.unique(X))\n self.metadata['categories'] = np.unique(self.metadata['categories'])\n else:\n self.metadata['categories'] = np.unique(X)\n\n def transform(self, X):\n out = (self.metadata['categories'] == X[..., None]) * 1\n if self.kwargs['strict'] and (out.sum(axis=-1) == 0).any():\n raise ValueError(\"New value encountered in transform that was not present in fit\")\n return out\n\n\nclass Reshape(StatelessLayer):\n \"\"\"Reshape an array to a given new shape.\n\n Parameters\n ----------\n new_shape : tuple of int\n desired new shape for array.\n \"\"\"\n def __init__(self, new_shape):\n super().__init__(new_shape=new_shape)\n\n def transform(self, X):\n return np.reshape(X, self.kwargs['new_shape'])\n\n\nclass Flatten(StatelessLayer):\n \"\"\"Reshape an array to be 1D.\"\"\"\n def transform(self, X):\n return X.flatten()\n\n\nclass SplitDict(StatelessLayer):\n \"\"\"Split dictionary data into separate nodes, with one node per key in the dictionary.\n\n Parameters\n ----------\n fields : list of str\n list of fields, dictionary keys, to be pulled out into their own nodes.\n \"\"\"\n def __init__(self, fields):\n super().__init__(n_outputs=len(fields), fields=fields)\n\n def transform(self, dicts):\n out = []\n as_df = pd.DataFrame(dicts.tolist())\n for key in self.kwargs['fields']:\n out.append(as_df[key].values)\n return out\n\n\nclass TimeSeries(StatefulLayer):\n \"\"\"Adds a time dimension to a dataset by rolling a window over the data.\n\n Parameters\n ----------\n window_size : int\n length of the window; number of timesteps in the time series.\n time_axis : int\n on which axis in the array to place the time dimension.\n reverse : bool (default: False)\n if True, oldest data is first; if False, newest data is first.\n \"\"\"\n def __init__(self, window_size, time_axis=1, reverse=False):\n if window_size <= 1:\n raise ValueError(\"Window size must be greater than 1\")\n super().__init__(window_size=window_size, time_axis=time_axis, reverse=reverse)\n\n def partial_fit(self, X):\n self.metadata['shape'] = list(X.shape[1:])\n self.metadata['previous'] = np.zeros([self.kwargs['window_size']-1] + self.metadata['shape'])\n\n def transform(self, X):\n internal = [np.roll(X, i, axis=0) for i in range(self.kwargs['window_size'])]\n internal = np.moveaxis(np.stack(internal), 0, self.kwargs['time_axis'])\n internal = internal[self.kwargs['window_size']:]\n begin = np.concatenate([X[:self.kwargs['window_size']], self.metadata['previous']])\n begin = [np.roll(begin, i, axis=0) for i in range(self.kwargs['window_size'])]\n begin = np.moveaxis(np.stack(begin), 0, self.kwargs['time_axis'])\n begin = begin[:self.kwargs['window_size']]\n\n self.metadata['previous'] = X[-self.kwargs['window_size']:]\n out = np.concatenate([begin, internal])\n if self.kwargs['reverse']:\n slices = [slice(None) for i in range(len(X.shape))]\n slices[self.kwargs['time_axis']] = slice(None, None, -1)\n out = out[tuple(slices)]\n return out\n\n\nclass Concatenate(StatelessLayer):\n \"\"\"Combine arrays along a given axis. Does not create a new axis, unless all 1D inputs.\n\n Parameters\n ----------\n axis : int (default: -1)\n axis along which to concatenate arrays. -1 means the last axis.\n \"\"\"\n def __init__(self, axis=-1):\n super().__init__(axis=axis)\n\n def transform(self, *arrays):\n arrays = list(arrays)\n for i, a in enumerate(arrays):\n if len(a.shape) == 1:\n arrays[i] = np.expand_dims(a, -1)\n return np.concatenate(arrays, axis=self.kwargs['axis'])\n\n\nclass Slice(StatelessLayer):\n \"\"\"Apply Numpy array slicing. Each slice corresponds to a dimension.\n\n Slices (passed as hyperparameters) are constructed by the following procedure:\n - To get just N: provide the integer N as the slice\n - To slice from N to the end: provide a 1-tuple of the integer N, e.g. (5,).\n - To slice from M to N exclusive: provide a 2-tuple of the integers M and N, e.g. (3, 6).\n - To slice from M to N with skip P: provide a 3-tuple of the integers M, N, and P.\n\n Parameters\n ----------\n *slices : int(s) or tuple(s)\n the slices to be applied. Must not overlap. Formatting discussed above.\n \"\"\"\n def __init__(self, *slices):\n if isinstance(slices, list):\n raise ValueError(\"Slices for each dimension are passed as separate arguments, not in a list\")\n super().__init__(slices=slices)\n\n def transform(self, X):\n if len(X.shape) != len(self.kwargs['slices']):\n raise ValueError(\"Number of dimensions in X must match number of slices\")\n new_slices = []\n for i, s in enumerate(self.kwargs['slices']):\n if s is None:\n new_slices.append(slice(None))\n elif isinstance(s, int):\n new_slices.append(s)\n elif len(s) == 1:\n new_slices.append(slice(s[0], None))\n else:\n new_slices.append(slice(*s))\n return X[tuple(new_slices)]\n\n\nclass Filter(StatelessLayer):\n \"\"\"Apply given mask to given array along the first axis to filter out observations.\"\"\"\n def transform(self, X, mask):\n if mask.sum() == 0:\n raise ValueError(\"Mask must retain at least one observation\")\n return X[mask.astype(bool)]\n"
] |
[
[
"numpy.concatenate",
"numpy.reshape",
"numpy.zeros",
"numpy.roll",
"numpy.stack",
"numpy.arange",
"numpy.expand_dims",
"numpy.unique"
]
] |
RoyLQ/Advanced_IDE_Recommendation
|
[
"c1d2739ab9bea701dd8c70db9d63687fbc96e479"
] |
[
"src/NN/data_prep.py"
] |
[
"#!/usr/bin/python3\nfrom src import storage_connection as sc\nimport numpy as np\n\n\"\"\"\nLast edited by : Shawn\nLast edited time : 29/11/2021\nVersion Status: dev\nTO DO:\nThe functions in this file are for reading and preparing the inputs for the NN.\nRequired: Path to NN_input.txt\n Path to vector.csv\n\"\"\"\n\n\ndef get_input_vectors_and_labels(credential_path):\n \"\"\"\n @ input : path to NN_input.txt, path to vectors.csv\n @ output: input vectors, labels as numpy arrays\n \"\"\"\n inputs = []\n labels = []\n\n # Get the word embedding table as a df\n word_embedding_df = sc.storage_connection_embedding(credential_path, \"pca_lookup_table.csv\")\n # Get the sequence list\n sequence_list = sc.storage_connection_sequence(credential_path, \"NN_input.txt\")\n\n for seq in sequence_list:\n # Replace the current integer with its corresponding vector in the word embedding table if > 0,\n # else use vector of all 0's\n inputs.append([list(word_embedding_df.loc[val - 1]) if val > 0 else [0] * 34 for val in seq[:-1]])\n # Store the last integer in each sequence as the label\n labels.append([list(word_embedding_df.loc[val - 1]) if val > 0 else [0] * 34 for val in seq[-1:]])\n\n # Convert the inputs and labels to numpy arrays\n inputs = np.array(inputs, dtype=float)\n labels = np.array(labels, dtype=float)\n\n return inputs, labels\n"
] |
[
[
"numpy.array"
]
] |
sgowda/brain-python-interface
|
[
"708e2a5229d0496a8ce9de32bda66f0925d366d9"
] |
[
"riglib/motiontracker.py"
] |
[
"'''\nBase code for 'motiontracker' feature, compatible with PhaseSpace motiontracker\n'''\n\nimport os\nimport time\nimport numpy as np\n\ntry:\n from OWL import *\nexcept:\n OWL_MODE2 = False\n print(\"Cannot find phasespace driver\")\n\ncwd = os.path.split(os.path.abspath(__file__))[0]\n\nclass Simulate(object):\n '''\n Docstring\n\n Parameters\n ----------\n\n Returns\n -------\n '''\n update_freq = 240\n def __init__(self, marker_count=8, radius=(10, 2, 5), offset=(-20,0,0), speed=(5,5,4)):\n '''\n Docstring\n\n Parameters\n ----------\n\n Returns\n -------\n '''\n self.n = marker_count\n self.radius = radius\n self.offset = np.array(offset)\n self.speed = speed\n\n self.offsets = np.random.rand(self.n)*np.pi\n\n def start(self):\n '''\n Docstring\n\n Parameters\n ----------\n\n Returns\n -------\n '''\n self.stime = time.time()\n\n def get(self):\n '''\n Docstring\n\n Parameters\n ----------\n\n Returns\n -------\n '''\n time.sleep(1./self.update_freq)\n ts = (time.time() - self.stime)\n data = np.zeros((self.n, 3))\n for i, p in enumerate(self.offsets):\n x = self.radius[0] * np.cos(ts / self.speed[0] * 2*np.pi + p)\n y = self.radius[1] * np.sin(ts / self.speed[1] * 2*np.pi + p)\n z = self.radius[2] * np.sin(ts / self.speed[2] * 2*np.pi + p)\n data[i] = x,y,z\n\n return np.hstack([data + np.random.randn(self.n, 3)*0.1, np.ones((self.n,1))])\n\n def stop(self):\n '''\n Docstring\n\n Parameters\n ----------\n\n Returns\n -------\n '''\n return \n\n\nclass System(object):\n '''\n Docstring\n\n Parameters\n ----------\n\n Returns\n -------\n '''\n update_freq = 240\n def __init__(self, marker_count=8, server_name='10.0.0.11', init_flags=OWL_MODE2):\n '''\n Docstring\n\n Parameters\n ----------\n\n Returns\n -------\n '''\n self.marker_count = marker_count\n if(owlInit(server_name, init_flags) < 0):\n raise Exception(owl_get_error(\"init error\",owlGetError()))\n \n # flush requests and check for errors fix\n if(owlGetStatus() == 0):\n raise Exception(owl_get_error(\"error in point tracker setup\", owlGetError()))\n \n # set define frequency\n owlSetFloat(OWL_FREQUENCY, OWL_MAX_FREQUENCY)\n \n #create a point tracker\n self.tracker = 0\n owlTrackeri(self.tracker, OWL_CREATE, OWL_POINT_TRACKER)\n self._init_markers()\n\n def _init_markers(self):\n '''\n Docstring\n\n Parameters\n ----------\n\n Returns\n -------\n '''\n # set markers\n for i in range(self.marker_count):\n owlMarkeri(MARKER(self.tracker, i), OWL_SET_LED, i)\n owlTracker(self.tracker, OWL_ENABLE)\n self.coords = np.zeros((self.marker_count, 4))\n \n def start(self, filename=None):\n '''\n Docstring\n\n Parameters\n ----------\n\n Returns\n -------\n '''\n self.filename = filename\n if filename is not None:\n #figure out command to tell phasespace to start a recording\n pass\n owlSetInteger(OWL_STREAMING, OWL_ENABLE)\n #owlSetInteger(OWL_INTERPOLATION, 4)\n\n def stop(self):\n '''\n Docstring\n\n Parameters\n ----------\n\n Returns\n -------\n '''\n if self.filename is not None:\n #tell phasespace to stop recording\n pass\n owlSetInteger(OWL_STREAMING, OWL_DISABLE)\n \n def get(self):\n '''\n Docstring\n\n Parameters\n ----------\n\n Returns\n -------\n '''\n markers = []\n n = owlGetMarkers(markers, self.marker_count)\n while n == 0:\n time.sleep(.001)\n n = owlGetMarkers(markers, self.marker_count)\n \n for i, m in enumerate(markers):\n self.coords[i] = m.x, m.y, m.z, m.cond\n\n return self.coords\n\n def __del__(self):\n '''\n Docstring\n\n Parameters\n ----------\n\n Returns\n -------\n '''\n for i in range(self.marker_count):\n owlMarker(MARKER(self.tracker, i), OWL_CLEAR_MARKER) \n owlTracker(self.tracker, OWL_DESTROY)\n owlDone()\n\nclass AligningSystem(System):\n '''\n Docstring\n\n Parameters\n ----------\n\n Returns\n -------\n '''\n def _init_markers(self):\n '''\n Docstring\n\n Parameters\n ----------\n\n Returns\n -------\n '''\n MAX = 32\n for i in range(self.marker_count):\n owlMarkeri(MARKER(self.tracker, i), OWL_SET_LED, i)\n for i in range(6):\n owlMarkeri(MARKER(self.tracker, self.marker_count+i), OWL_SET_LED, MAX+i)\n self.marker_count += 6\n owlTracker(self.tracker, OWL_ENABLE)\n self.coords = np.zeros((self.marker_count, 4))\n\ndef owl_get_error(s, n):\n \"\"\"\n Print OWL error.\n Docstring\n\n Parameters\n ----------\n\n Returns\n -------\n \"\"\"\n if(n < 0): return \"%s: %d\" % (s, n)\n elif(n == OWL_NO_ERROR): return \"%s: No Error\" % s\n elif(n == OWL_INVALID_VALUE): return \"%s: Invalid Value\" % s\n elif(n == OWL_INVALID_ENUM): return \"%s: Invalid Enum\" % s\n elif(n == OWL_INVALID_OPERATION): return \"%s: Invalid Operation\" % s\n else: return \"%s: 0x%x\" % (s, n)\n\n\ndef make(marker_count, cls=System, **kwargs):\n \"\"\"This ridiculous function dynamically creates a class with a new init function\n Docstring\n\n Parameters\n ----------\n\n Returns\n -------\n \"\"\"\n def init(self, **kwargs):\n super(self.__class__, self).__init__(marker_count=marker_count, **kwargs)\n \n dtype = np.dtype((np.float, (marker_count, 4)))\n if cls == AligningSystem:\n dtype = np.dtype((np.float, (marker_count+6, 4)))\n return type(cls.__name__, (cls,), dict(dtype=dtype, __init__=init))\n\n\ndef make_autoalign_reference(data, filename=os.path.join(cwd, \"alignment2.npz\")):\n '''Creates an alignment that can be used with the autoaligner\n Docstring\n\n Parameters\n ----------\n\n Returns\n -------\n '''\n from .stereo_opengl import xfm\n assert data.shape[1:] == (6, 3)\n mdata = np.median(data,0)\n cdata = mdata - mdata[0]\n rot1 = xfm.Quaternion.rotate_vecs(np.cross(cdata[2], cdata[1]), [0,1,0])\n rdata = rot1*cdata\n rot2 = xfm.Quaternion.rotate_vecs(rdata[1], [1, 0, 0])\n np.savez(filename, data=data, reference=rot2*rot1*cdata)\n"
] |
[
[
"numpy.array",
"numpy.sin",
"numpy.random.rand",
"numpy.zeros",
"numpy.median",
"numpy.ones",
"numpy.random.randn",
"numpy.savez",
"numpy.cos",
"numpy.cross",
"numpy.dtype"
]
] |
JuliaSun623/dgl
|
[
"4ca706e1b4e15d6cb8b0df574e44b9d2dd92996e"
] |
[
"benchmarks/benchmarks/api/bench_udf_multi_update_all.py"
] |
[
"\nimport time\nimport dgl\nimport torch\nimport numpy as np\nimport dgl.function as fn\n\n\nfrom .. import utils\n\n\n@utils.benchmark('time', timeout=600)\n@utils.parametrize('feat_size', [32, 128, 512])\n@utils.parametrize('num_relations', [5, 50, 500])\n@utils.parametrize('multi_reduce_type', [\"sum\", \"stuck\"])\ndef track_time(feat_size, num_relations, multi_reduce_type):\n device = utils.get_bench_device()\n dd = {}\n candidate_edges = [dgl.data.CoraGraphDataset(verbose=False)[0].edges(), dgl.data.PubmedGraphDataset(verbose=False)[\n 0].edges(), dgl.data.CiteseerGraphDataset(verbose=False)[0].edges()]\n for i in range(num_relations):\n dd[('n1', 'e_{}'.format(i), 'n2')] = candidate_edges[i %\n len(candidate_edges)]\n graph = dgl.heterograph(dd)\n\n graph = graph.to(device)\n graph.nodes['n1'].data['h'] = torch.randn(\n (graph.num_nodes('n1'), feat_size), device=device)\n graph.nodes['n2'].data['h'] = torch.randn(\n (graph.num_nodes('n2'), feat_size), device=device)\n\n # dry run\n update_dict = {}\n for i in range(num_relations):\n update_dict['e_{}'.format(i)] = (\n lambda edges: {'x': edges.src['h']}, lambda nodes: {'h_new': torch.sum(nodes.mailbox['x'], dim=1)})\n graph.multi_update_all(\n update_dict,\n multi_reduce_type)\n\n # timing\n t0 = time.time()\n for i in range(3):\n graph.multi_update_all(\n update_dict,\n multi_reduce_type)\n t1 = time.time()\n\n return (t1 - t0) / 3\n"
] |
[
[
"torch.sum"
]
] |
damo-cv/MMP_Track1_ICCV21
|
[
"a71d6067851d41b16b683a4c1b2c2f1ca51964ec"
] |
[
"detection/gen_detections.py"
] |
[
"import argparse\nimport itertools\nimport json\nimport logging\nimport pickle\nimport sys\nimport os\nfrom collections import defaultdict\nfrom multiprocessing import Pool\nfrom pathlib import Path\nimport numpy as np\nimport torch\nfrom torchvision.ops import nms\nfrom tqdm import tqdm\nimport pandas as pd\n# Add current directory to path\nsys.path.insert(0, str(Path(__file__).resolve().parent))\n\ndef save_detections(det, output, score_threshold, nms_thresh):\n fids = np.unique(det[:, 0])\n res = []\n for fid in fids:\n sub_det = det[det[:, 0] == fid].copy()\n if score_threshold > 0:\n sub_det = sub_det[sub_det[:, 5] >= score_threshold]\n if nms_thresh >= 0:\n bboxes = sub_det[:, 1:5].copy()\n bboxes[:, 2:4] += bboxes[:, :2]\n nms_keep = nms(torch.from_numpy(bboxes),\n torch.from_numpy(sub_det[:, 5]),\n iou_threshold=nms_thresh).numpy()\n sub_det = sub_det[nms_keep]\n res.append(sub_det)\n res = np.vstack(res)\n cat_pad = np.zeros((res.shape[0], 1))\n res = np.hstack((res[:, 0:1], cat_pad, res[:, 1:])) #'image_id', 'category', 'bb_left','bb_top', 'bb_width', 'bb_height', 'conf'\n output.parent.mkdir(exist_ok=True,parents=True)\n det_dfs = pd.DataFrame(res)\n det_dfs.to_csv(str(output), header=False, index=False)\n\ndef save_detections_star(args):\n save_detections(*args)\n\ndef main():\n # Use first line of file docstring as description if it exists.\n parser = argparse.ArgumentParser(\n description=__doc__.split('\\n')[0] if __doc__ else '',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument('--split',\n type=str,\n default='train',\n choices=['train', 'validation', 'test'])\n parser.add_argument('--detections-file',\n type=Path,\n default='results/comp4_det_test_320_False__person.txt',\n help='results file in txt format')\n parser.add_argument(\n '--output-dir',\n type=Path,\n required=True,\n help=('Output directory'))\n\n parser.add_argument('--score-threshold',\n default=-1,\n help='threshold to filter detections')\n\n parser.add_argument('--nms-thresh', type=float, default=-1, help='nms threshold')\n parser.add_argument('--workers', default=8, type=int)\n\n args = parser.parse_args()\n \n args.score_threshold = (-float('inf') if args.score_threshold == 'none'\n else float(args.score_threshold))\n\n def get_name(video_name):\n video_name_parse = video_name.split('/')\n camera_id = video_name_parse[-1].split('_')[-1]\n video_name_parse = video_name_parse[:-1]\n video_name_parse.append(video_name_parse[-1] + '_' + camera_id)\n return '/'.join(video_name_parse)\n\n def get_fid(video_name):\n video_name_parse = video_name.split('/')\n fid = int(video_name_parse[-1].split('_')[-2])\n return fid\n \n df = pd.read_csv(os.path.join(args.detections_file), delimiter=' ',header=None)\n df.columns = ['video_name', 'score', 'x1', 'y1', 'x2', 'y2']\n df['name'] = df['video_name'].apply(get_name)\n print('finish get name')\n df['fid'] = df['video_name'].apply(get_fid)\n print('finish get fid')\n df['w'] = df['x2'] - df['x1']\n df['h'] = df['y2'] - df['y1']\n unique_names = np.unique(df['name'].values)\n\n tasks = []\n for name in unique_names:\n sub_df = df[df['name'] == name]\n res = sub_df[['fid', 'x1', 'y1', 'w', 'h', 'score']].values\n output = args.output_dir / (name + '.txt')\n output = Path(str(output).replace('images', 'det_video')) \n tasks.append((res, output, args.score_threshold, args.nms_thresh))\n \n if args.workers > 0:\n pool = Pool(args.workers)\n list(\n tqdm(pool.imap_unordered(save_detections_star, tasks),\n total=len(tasks),\n desc='Save Detections'))\n else:\n for task in tqdm(tasks):\n save_detections(*task)\n \n print('Finished')\n\nif __name__ == \"__main__\":\n main()\n"
] |
[
[
"numpy.zeros",
"pandas.DataFrame",
"torch.from_numpy",
"numpy.unique",
"numpy.hstack",
"numpy.vstack"
]
] |
JeremyCJM/Ensemble
|
[
"9a68920c68639d4ea8b233bdc497481508cf4745"
] |
[
"imagenet_ens_new.py"
] |
[
"import numpy as np\nimport torch\nimport pdb\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport itertools\n\nnum_data = 50000\nnum_classes = 1000\n\n# Temps = [0.001, 0.01, 0.1, 5, 10, 50, 100, 500, 1000, 5000, 10000]\n# Temps = [1.2, 1.4, 1.6, 1.8, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5]\n# Temps = np.arange(1.01, 1.2 ,0.02)\nTemps = [1,2,3,4,5]\n\nmodels = ['vgg19_bn', 'resnet152', 'densenet161', 'densenet121', 'densenet201', 'resnet101', 'densenet169', 'resnet50']\n\ntarget = torch.load('Ensemble/imagenet/vgg19_bn/Targets of vgg19_bn.pt')\n\ndata = {}\nfor m in models:\n data[m] = torch.load('Ensemble/imagenet/{}/Logit Outputs of {}.pt'.format(m, m))\n\ndef logit_ensemble(models, data, target):\n output = torch.zeros(num_data, num_classes).cuda()\n for m in models:\n output += data[m]\n\n target_exp = target.view(-1, 1).expand(-1, num_classes).cuda()\n _, pred = output.topk(num_classes, 1, True, True)\n correct = pred.data.eq(target_exp).t()\n correct_1 = torch.sum(correct[:1])\n correct_5 = torch.sum(correct[:5])\n\n V = torch.Tensor([range(1, num_classes+1)]).t().cuda()\n gesNum = V * correct.float()\n zero_map = gesNum == 0\n zero_map = zero_map.float() * 999\n # pdb.set_trace()\n gesNum = gesNum + zero_map\n gesNum, _ = torch.min(gesNum,0)\n\n # pdb.set_trace()\n AverGesNum = torch.mean(gesNum)\n\n if AverGesNum > 50:\n pdb.set_trace()\n\n return correct_1 / len(target), correct_5 / len(target), AverGesNum\n\ndef temperature_ensemble(models, data, target, Temps):\n softmax = nn.Softmax().cuda()\n output = Variable(torch.zeros(num_data, num_classes).cuda())\n for m,T in zip(models,Temps):\n output += softmax(Variable(data[m])/T)\n # pdb.set_trace()\n\n target_exp = target.view(-1, 1).expand(-1, num_classes).cuda()\n _, pred = output.topk(num_classes, 1, True, True)\n correct = pred.data.eq(target_exp).t()\n correct_1 = torch.sum(correct[:1])\n correct_5 = torch.sum(correct[:5])\n\n V = torch.Tensor([range(1, num_classes+1)]).t().cuda()\n gesNum = V * correct.float()\n zero_map = gesNum == 0\n zero_map = zero_map.float() * 999\n # pdb.set_trace()\n gesNum = gesNum + zero_map\n gesNum, _ = torch.min(gesNum,0)\n\n # pdb.set_trace()\n AverGesNum = torch.mean(gesNum)\n\n # if AverGesNum > 50:\n # pdb.set_trace()\n\n return correct_1 / len(target), correct_5 / len(target), AverGesNum\n\n\ndef geometric_ensemble(models, data, target):\n softmax = nn.Softmax().cuda()\n output = Variable(torch.ones(num_data, num_classes).cuda())\n for m in models:\n output *= softmax(Variable(data[m]))\n\n target = target.view(-1, 1).expand(-1, 5).cuda()\n _, pred = output.topk(5, 1, True, True)\n correct = pred.data.eq(target).t()\n correct_1 = torch.sum(correct[:1])\n correct_5 = torch.sum(correct[:5])\n\n return correct_1 / len(target), correct_5 / len(target)\n\n\n \n\n\nResult = {}\ncompare_top1 = {}\ncompare_top5 = {}\n# for T in Temps:\n # print(T)\ncompare_top1 = {}\ncompare_top5 = {}\ncompare_top1['better'], compare_top1['worse'], compare_top1['equal'], compare_top1['improve'], compare_top1['gesNum'] = 0, 0, 0, [], (-1,-1)\ncompare_top1['gNumBetter'], compare_top1['gNumWorse'], compare_top1['gNumEqual'] = 0, 0, 0\ncompare_top5['better'], compare_top5['worse'], compare_top5['equal'], compare_top5['improve'] = 0, 0, 0, []\nground_gesNum = []\ngesNum = []\n## average improvement\n# for r in range(2, len(models)+1):\nfor submodels in itertools.combinations(models, 5):\n submodels = list(submodels)\n A1, A5, Anum = temperature_ensemble(submodels, data, target, [1,1,1,1,1])\n C1, C5, Cnum = temperature_ensemble(submodels, data, target, Temps)\n compare_top1['improve'].append(C1 - A1)\n compare_top5['improve'].append(C5 - A5)\n ground_gesNum.append(Anum)\n gesNum.append(Cnum)\n # print('T = {}: ({},{})'.format(T, Anum, Cnum))\n \n if C1 > A1:\n compare_top1['better'] += 1\n elif C1 < A1:\n compare_top1['worse'] += 1\n elif C1 == A1:\n compare_top1['equal'] += 1\n if C5 > A5:\n compare_top5['better'] += 1\n elif C5 < A5:\n compare_top5['worse'] += 1\n elif C5 == A5:\n compare_top5['equal'] += 1\n if Cnum < Anum:\n compare_top1['gNumBetter'] += 1\n elif Cnum > Anum:\n compare_top1['gNumWorse'] += 1\n elif Cnum == Anum:\n compare_top1['gNumEqual'] += 1\ncompare_top1['improve'] = sum(compare_top1['improve']) / len(compare_top1['improve'])\ncompare_top5['improve'] = sum(compare_top5['improve']) / len(compare_top5['improve'])\ncompare_top1['accBetterRate'] = compare_top1['better'] / (compare_top1['better']+compare_top1['equal']+compare_top1['worse'])\ncompare_top5['accBetterRate'] = compare_top5['better'] / (compare_top5['better']+compare_top5['equal']+compare_top5['worse'])\ncompare_top1['numBetterRate'] = compare_top1['gNumBetter'] / (compare_top1['gNumBetter']+compare_top1['gNumEqual']+compare_top1['gNumWorse'])\nground_gesNum = np.mean(ground_gesNum)#sum(ground_gesNum) / len(ground_gesNum)\ngesNum = np.mean(gesNum)#sum(gesNum) / len(gesNum)\ncompare_top1['gesNum'] = (ground_gesNum, gesNum)\n# pdb.set_trace()\nResult['top1'] = compare_top1\nResult['top5'] = compare_top5\n\ntorch.save(Result, 'Ensemble/ImageNet_Result_new.pt')\n\n\n"
] |
[
[
"torch.zeros",
"torch.min",
"torch.nn.Softmax",
"torch.autograd.Variable",
"torch.save",
"numpy.mean",
"torch.ones",
"torch.load",
"torch.mean",
"torch.sum"
]
] |
AtsushiHashimoto/KinectOnTheCeiling
|
[
"116448e706da8b4e87e5402310747f46821beb4a",
"116448e706da8b4e87e5402310747f46821beb4a"
] |
[
"PoseEstimation/Script/Main/body_part_classification.py",
"PoseEstimation/Script/Preprocessing/RealData/xtion_io.py"
] |
[
"# -*- coding: utf-8 -*-\n\nimport time, cv2, os\nimport numpy as np\nimport multiprocessing as mp\nfrom scipy import stats\nimport pandas as pd\nfrom sklearn.externals import joblib\nfrom sklearn.ensemble import RandomForestClassifier\nfrom Modules.data_preparation import prepare_train_data, prepare_test_data, prepare_offsets\nfrom Modules.utils import get_parameter, get_args, figure_disappears, bvh_exists, enum_train_files, enum_test_files\n\n__all__ = [\"BodyPartClassification\"]\n\n\nclass BodyPartClassification:\n\n def __init__(self, n_train_images=2000, n_target_pixels_per_image=2000, n_offsets=500, n_sep=1):\n self.n_target_pixels_per_image = n_target_pixels_per_image\n self.n_offsets = n_offsets\n self.train_setting_str = \"_\" + str(n_train_images)\n self.test_setting_str = \"_\" + str(n_train_images)\n self.n_sep = n_sep\n self.compression_type = \"gzip\"\n self.offsets = None\n self.rf = []\n self.part_labels = np.array([(63,0,0), (0,63,0), (255,0,0), (127,0,63), (127,255,0), (191,255,191), (255,255,191), (127,255,127), (191,191,191), (63,127,0),\n (0,191,63), (255,255,0), (255,191,0), (0,255,255), (0,191,255), (127,63,0), (0,63,127), (255,63,255), (63,255,255), (255,63,0),\n (0,63,255), (127,63,255), (127,63,63), (63,127,255), (255,63,63), (63,0,63), (63,0,127), (255,127,127), (63,255,63), (191,127,63),\n (63,63,0), (255,255,255), (0,0,0)])\n\n def train(self, train_filenames):\n\n n_train_images = train_filenames.shape[0]\n\n bpc_path = \"/\".join(train_filenames[0].split(\"/\")[:-3]) + \"/\"\n intermediate_path = bpc_path + \"Intermediate/\"\n evaluation_path = bpc_path + \"Evaluation/\"\n offset_path = intermediate_path + \"offsets.csv\"\n pkl_path = intermediate_path + \"pkl/RF\" + self.train_setting_str + \"_not_balanced.gz\"\n fitting_time_path = \"%strain_time_%d\" % (evaluation_path, n_train_images)\n\n self.offsets = prepare_offsets(offset_path, self.n_offsets)\n\n if os.path.exists(pkl_path):\n print(\"Loading Random Forest...\")\n self.rf = joblib.load(pkl_path)\n #self.rf = None\n else:\n fitting_time = 0\n self.rf = []\n # n_sep > 1の時は学習データ分割によるメモリ消費量削減\n stride = int(n_train_images / self.n_sep)\n n_rem_estimators = 10\n n_rem_sep = self.n_sep\n n_jobs = int(mp.cpu_count() / 2)\n for i in range(0, n_train_images, stride):\n features, labels, sample_weight = \\\n prepare_train_data(train_filenames[i: min(i+stride, n_train_images)],\n self.offsets, self.n_target_pixels_per_image, self.compression_type)\n print(\"Training Random Forest...\")\n n_estimators = int(n_rem_estimators / n_rem_sep)\n n_rem_estimators -= n_estimators\n n_rem_sep -= 1\n rf = RandomForestClassifier(n_estimators=n_estimators, random_state=1, max_depth=17,\n class_weight=None, criterion=\"entropy\", n_jobs=n_jobs)\n #rf = RandomForestClassifier(n_estimators=n_estimators, random_state=1, max_depth=17,\n # class_weight=\"balanced\", criterion=\"entropy\", n_jobs=mp.cpu_count())\n fit_start = time.time()\n rf.fit(features, np.ravel(labels), sample_weight)\n fit_end = time.time()\n fitting_time += fit_end - fit_start\n print(\"Took %fsec for fitting random forest.\" % (fit_end - fit_start))\n\n del features, labels, sample_weight\n\n self.rf.append(rf)\n\n print(\"Saving Random Forest...\")\n tmp = time.time()\n joblib.dump(self.rf, pkl_path, compress=3)\n print(\"Took %fsec for saving random forest.\" % (time.time() - tmp))\n\n pd.DataFrame([fitting_time]).to_csv(fitting_time_path, header=False, index=False, mode='a')\n\n def predict(self, test_filename, save=True):\n\n bpc_path = \"/\".join(test_filename.split(\"/\")[:-3]) + \"/\"\n intermediate_path = bpc_path + \"Intermediate/\"\n out_path = bpc_path + \"Output/\"\n\n n_part_labels = self.part_labels.shape[0] - 1\n\n test_filename_id = \"/\".join(test_filename.split(\"/\")[-2:])\n test_feature_path = intermediate_path + test_filename_id + \"_features.gz\"\n target_pixels_path = intermediate_path + test_filename_id + \"_target_pixels.gz\"\n\n test_BPC_image_path = out_path + test_filename_id + self.test_setting_str + \"_nb_BPC.png\"\n test_BPC_proba_path = out_path + test_filename_id + self.test_setting_str + \"_nb_BPC_proba.gz\"\n if os.path.exists(test_BPC_proba_path) and os.path.exists(test_BPC_image_path):\n return None, None, None\n\n features, image_shape, target_pixels = prepare_test_data(test_filename, test_feature_path, target_pixels_path,\n self.offsets, self.compression_type)\n\n height, width = image_shape\n\n test_predict = np.ones((height, width, self.n_sep), dtype=np.uint8) * 31\n test_predict_proba = np.zeros((height, width, n_part_labels))\n test_predict_proba[:, :, 31] = 1\n test_predict_proba[target_pixels[:, 0], target_pixels[:, 1], 31] = 0\n\n # n_sep > 1の時はメモリ消費量削減のための分割処理\n print(\"Predicting test data label...\")\n tmp = time.time()\n for s, rf in enumerate(self.rf):\n\n tmp_predicts = rf.predict(features)\n tmp_predict_probas = rf.predict_proba(features)\n for i, target_pixel in enumerate(target_pixels):\n test_predict[target_pixel[0], target_pixel[1], s] = tmp_predicts[i]\n test_predict_proba[target_pixel[0], target_pixel[1], :] += tmp_predict_probas[i, :]\n\n print(\"Took %fsec for predict.\" % (time.time() - tmp))\n test_predict_proba /= self.n_sep\n\n # 分類結果の描画\n predict_px = np.ones((image_shape[0], image_shape[1], 3), dtype=np.uint8) * 255\n for v, h in target_pixels:\n predict_px[v, h, :] = self.part_labels[int(stats.mode(test_predict[v, h, :])[0])]\n\n if save:\n cv2.imwrite(test_BPC_image_path, predict_px[:, :, ::-1])\n\n # 分類結果の確率分布をデータで保存\n test_predict_proba = test_predict_proba.reshape((height * width, n_part_labels))\n if save:\n pd.DataFrame(test_predict_proba).to_csv(test_BPC_proba_path, compression=self.compression_type, header=False, index=False)\n\n return predict_px, test_predict_proba, target_pixels\n\n def video_predict(self, test_filename):\n\n bpc_path = \"/\".join(test_filename.split(\"/\")[:-3]) + \"/\"\n intermediate_path = bpc_path + \"Intermediate/\"\n out_path = bpc_path + \"Output/\"\n\n n_part_labels = self.part_labels.shape[0] - 1\n\n test_filename_id = \"/\".join(test_filename.split(\"/\")[-2:])\n print(test_filename_id)\n test_feature_path = intermediate_path + test_filename_id + \"_features.gz\"\n target_pixels_path = intermediate_path + test_filename_id + \"_target_pixels.gz\"\n test_BPC_video_path = out_path + test_filename_id + self.test_setting_str + \"_BPC.mov\"\n test_BPC_proba_path = out_path + test_filename_id + self.test_setting_str + \"_BPC_proba.gz\"\n\n features, video_shape, target_pixels = prepare_test_data(test_filename, test_feature_path, target_pixels_path,\n self.offsets, self.compression_type)\n\n n_frames, height, width = video_shape\n\n test_predict = np.ones((n_frames, height, width, self.n_sep), dtype=np.uint8) * 31\n test_predict_proba = np.zeros((n_frames, height, width, n_part_labels))\n test_predict_proba[:, :, :, 31] = 1\n for f, v, h in target_pixels:\n test_predict_proba[f, v, h, 31] = 0\n\n # n_sep > 1の時はメモリ消費量削減のための分割処理\n for s in range(self.n_sep):\n rf = self.rf[s]\n\n print(\"Predicting test data label...\")\n rf.n_jobs = 1\n tmp_predicts = rf.predict(features)\n tmp_predict_probas = rf.predict_proba(features)\n for i, target_pixel in enumerate(target_pixels):\n f, v, h = target_pixel\n test_predict[f, v, h, s] = tmp_predicts[i]\n test_predict_proba[f, v, h, :] += tmp_predict_probas[i, :]\n\n test_predict_proba /= self.n_sep\n\n # 分類結果の描画\n predict_px = np.ones((n_frames, height, width, 3), dtype=np.uint8) * 255\n tmp = -1\n for f, v, h in target_pixels:\n if tmp < f:\n tmp = f\n print(\"frame%d\" % f)\n predict_px[f, v, h, :] = self.part_labels[int(stats.mode(test_predict[f, v, h, :])[0])]\n\n fourcc = cv2.VideoWriter_fourcc(*'mp4v')\n predict_out = cv2.VideoWriter(test_BPC_video_path, fourcc, 30.0, (width, height))\n for frame_px in predict_px[:, :, :, ::-1]:\n predict_out.write(frame_px)\n\n # 分類結果の確率分布をデータで保存\n test_predict_proba = test_predict_proba.reshape((n_frames * height * width, n_part_labels))\n pd.DataFrame(test_predict_proba).to_csv(test_BPC_proba_path, compression=self.compression_type, header=False, index=False)\n\n return predict_px, test_predict_proba, target_pixels\n\n\ndef run_bpc(bpc_model=BodyPartClassification):\n\n args = get_args()\n\n bpc_args = {\"n_sep\": args.n_sep, \"n_train_images\": args.n_train_images, }\n\n n_train_images = args.n_train_images\n n_test_images = args.n_test_images\n full_rotation = args.full_rotation\n if bpc_model is not BodyPartClassification:\n bpc_args[\"discr_setting_type\"] = args.discr_setting_type\n data_path = args.data_path\n\n train_filenames = enum_train_files(data_path, n_train_images, bpc_model, full_rotation)\n\n if bpc_model is not None:\n print(\"====%s====\" % bpc_model.__name__)\n bpc = bpc_model(**bpc_args)\n else:\n raise ValueError\n\n bpc.train(train_filenames)\n\n test_filenames = enum_test_files(data_path, args.test_path, n_test_images)\n\n if \"CapturedVideos\" in args.test_path:\n for i, test_filename in enumerate(test_filenames):\n test_filename_id = \"/\".join(test_filename.split(\"/\")[-2:])\n print(\"%d: %s\" % (i, test_filename_id))\n _, _, _ = bpc.video_predict(test_filename)\n elif \"CapturedImages\" in args.test_path or \"SyntheticImages\" in args.test_path:\n for i, test_filename in enumerate(test_filenames):\n test_filename_id = \"/\".join(test_filename.split(\"/\")[-2:])\n print(\"%d: %s\" % (i, test_filename_id))\n _, _, _ = bpc.predict(test_filename)\n else:\n raise ValueError(\"Invalid test path.\")\n\nif __name__ == \"__main__\":\n run_bpc(BodyPartClassification)\n\n",
"# -*- coding=utf8 -*-\n\nimport cv2, time, argparse\nimport numpy as np\nfrom primesense import openni2\n\n\nclass XtionIO:\n # 入力の際の深度の単位はmm\n\n def __init__(self, data_path=\"../../../Data/Main/BodyPartClassification/CapturedVideos/\"):\n self.videos_path = data_path\n self.depth_stream = None\n self.frame_shape = None\n self.fourcc = None\n\n def initialize(self):\n openni2.initialize() # can also accept the path of the OpenNI redistribution\n dev = openni2.Device.open_any()\n depth_stream = dev.create_depth_stream()\n depth_stream.start()\n rgb_stream = dev.create_color_stream()\n rgb_stream.start()\n frame = depth_stream.read_frame()\n self.depth_stream = depth_stream\n self.rgb_stream = rgb_stream\n self.frame_shape = (frame.width, frame.height)\n self.fourcc = cv2.VideoWriter_fourcc(*'FFV1')\n\n def capture_bg_rgb_image(self, bg_img_name):\n\n bg_img_filename = self.videos_path + bg_img_name\n\n frame = self.rgb_stream.read_frame()\n frame_data = frame.get_buffer_as_uint8()\n\n bg_array = np.ndarray((self.frame_shape[1], self.frame_shape[0], 3),\n dtype=np.uint8, buffer=frame_data)[:, :, ::-1]\n\n cv2.imwrite(bg_img_filename, bg_array.astype(np.uint8))\n\n def capture_bg_depth_image(self, bg_img_name):\n\n time.sleep(5)\n bg_img_filename = self.videos_path + bg_img_name\n\n frame = self.depth_stream.read_frame()\n frame_data = frame.get_buffer_as_uint16()\n\n bg_array = np.ndarray(self.frame_shape[::-1], dtype=np.uint16, buffer=frame_data)\n\n cv2.imwrite(bg_img_filename, (bg_array / 10000. * 255).astype(np.uint8))\n\n def capture_rgb_video(self, video_name):\n time.sleep(10)\n video_out_filename = self.videos_path + video_name\n raw_out = cv2.VideoWriter(video_out_filename, self.fourcc, 30.0, self.frame_shape, isColor=True)\n start = time.time()\n while True:\n\n frame = self.rgb_stream.read_frame()\n frame_data = frame.get_buffer_as_uint8()\n\n raw_array = np.ndarray((self.frame_shape[1], self.frame_shape[0], 3), dtype=np.uint8, buffer=frame_data)[:, :, ::-1]\n cv2.imshow(\"Raw\", raw_array.astype(np.uint8))\n raw_out.write(raw_array.astype(np.uint8))\n\n if (cv2.waitKey(1) & 0xFF == ord('q')) or (time.time() - start > 10):\n break\n\n raw_out.release()\n cv2.destroyAllWindows()\n\n def capture_depth_video(self, video_name):\n\n video_out_filename = self.videos_path + video_name\n raw_out = cv2.VideoWriter(video_out_filename, self.fourcc, 30.0, self.frame_shape, isColor=False)\n while True:\n\n frame = self.depth_stream.read_frame()\n frame_data = frame.get_buffer_as_uint16()\n\n raw_array = np.ndarray(self.frame_shape[::-1], dtype=np.uint16, buffer=frame_data)\n rounded_array = (raw_array / 10000. * 255).astype(np.uint8)\n cv2.imshow(\"Raw\", rounded_array)\n\n raw_out.write(rounded_array)\n\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n raw_out.release()\n cv2.destroyAllWindows()\n\n def release(self):\n self.depth_stream.stop()\n self.rgb_stream.stop()\n openni2.unload()\n\n\n"
] |
[
[
"scipy.stats.mode",
"numpy.array",
"numpy.zeros",
"sklearn.ensemble.RandomForestClassifier",
"pandas.DataFrame",
"sklearn.externals.joblib.dump",
"numpy.ones",
"sklearn.externals.joblib.load",
"numpy.ravel"
],
[
"numpy.ndarray"
]
] |
JamesNgo3781/vietocr
|
[
"9d311bbeb18c51c8ff90022f07c0463b204407dc"
] |
[
"vietocr/model/transformer.py"
] |
[
"from einops import rearrange\nfrom torchvision import models\nimport math\nimport torch\nfrom torch import nn\n\nclass LanguageTransformer(nn.Module):\n def __init__(self, vocab_size, \n d_model, nhead, \n num_encoder_layers, num_decoder_layers, \n dim_feedforward, max_seq_length, \n pos_dropout, trans_dropout):\n super().__init__()\n \n self.d_model = d_model\n self.embed_tgt = nn.Embedding(vocab_size, d_model)\n self.pos_enc = PositionalEncoding(d_model, pos_dropout, max_seq_length)\n# self.learned_pos_enc = LearnedPositionalEncoding(d_model, pos_dropout, max_seq_length)\n\n self.transformer = nn.Transformer(d_model, nhead, \n num_encoder_layers, num_decoder_layers, \n dim_feedforward, trans_dropout)\n \n self.fc = nn.Linear(d_model, vocab_size)\n \n def forward(self, src, tgt, src_key_padding_mask=None, tgt_key_padding_mask=None, memory_key_padding_mask=None):\n \"\"\"\n Shape:\n - src: (W, N, C)\n - tgt: (T, N) \n - src_key_padding_mask: (N, S)\n - tgt_key_padding_mask: (N, T)\n - memory_key_padding_mask: (N, S)\n - output: (N, T, E)\n \n \"\"\"\n tgt_mask = self.gen_nopeek_mask(tgt.shape[0]).to(src.device)\n \n src = self.pos_enc(src*math.sqrt(self.d_model))\n# src = self.learned_pos_enc(src*math.sqrt(self.d_model))\n\n tgt = self.pos_enc(self.embed_tgt(tgt) * math.sqrt(self.d_model))\n \n output = self.transformer(src, tgt, tgt_mask=tgt_mask, src_key_padding_mask=src_key_padding_mask,\n tgt_key_padding_mask=tgt_key_padding_mask, memory_key_padding_mask=memory_key_padding_mask)\n# output = rearrange(output, 't n e -> n t e')\n output = output.transpose(0, 1)\n return self.fc(output)\n\n def gen_nopeek_mask(self, length):\n mask = (torch.triu(torch.ones(length, length)) == 1).transpose(0, 1)\n mask = mask.float().masked_fill(mask == 0, float('-inf')).masked_fill(mask == 1, float(0.0))\n\n return mask\n \n def forward_encoder(self, src):\n src = self.pos_enc(src*math.sqrt(self.d_model))\n memory = self.transformer.encoder(src)\n return memory\n \n def forward_decoder(self, tgt, memory):\n tgt_mask = self.gen_nopeek_mask(tgt.shape[0]).to(tgt.device)\n tgt = self.pos_enc(self.embed_tgt(tgt) * math.sqrt(self.d_model))\n \n output = self.transformer.decoder(tgt, memory, tgt_mask=tgt_mask)\n# output = rearrange(output, 't n e -> n t e')\n output = output.transpose(0, 1)\n\n return self.fc(output)\n\nclass PositionalEncoding(nn.Module):\n def __init__(self, d_model, dropout=0.1, max_len=100):\n super(PositionalEncoding, self).__init__()\n self.dropout = nn.Dropout(p=dropout)\n\n pe = torch.zeros(max_len, d_model)\n position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)\n div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))\n pe[:, 0::2] = torch.sin(position * div_term)\n pe[:, 1::2] = torch.cos(position * div_term)\n pe = pe.unsqueeze(0).transpose(0, 1)\n self.register_buffer('pe', pe)\n\n def forward(self, x):\n x = x + self.pe[:x.size(0), :]\n\n return self.dropout(x)\n \nclass LearnedPositionalEncoding(nn.Module):\n def __init__(self, d_model, dropout=0.1, max_len=100):\n super(LearnedPositionalEncoding, self).__init__()\n self.dropout = nn.Dropout(p=dropout)\n\n self.pos_embed = nn.Embedding(max_len, d_model)\n self.layernorm = LayerNorm(d_model)\n\n def forward(self, x):\n seq_len = x.size(0)\n pos = torch.arange(seq_len, dtype=torch.long, device=x.device)\n pos = pos.unsqueeze(-1).expand(x.size()[:2])\n x = x + self.pos_embed(pos)\n return self.dropout(self.layernorm(x))\n\nclass LayerNorm(nn.Module):\n \"A layernorm module in the TF style (epsilon inside the square root).\"\n def __init__(self, d_model, variance_epsilon=1e-12):\n super().__init__()\n self.gamma = nn.Parameter(torch.ones(d_model))\n self.beta = nn.Parameter(torch.zeros(d_model))\n self.variance_epsilon = variance_epsilon\n\n def forward(self, x):\n u = x.mean(-1, keepdim=True)\n s = (x - u).pow(2).mean(-1, keepdim=True)\n x = (x - u) / torch.sqrt(s + self.variance_epsilon)\n return self.gamma * x + self.beta \n"
] |
[
[
"torch.nn.Linear",
"torch.zeros",
"torch.nn.Dropout",
"torch.cos",
"torch.sqrt",
"torch.sin",
"torch.nn.Transformer",
"torch.arange",
"torch.ones",
"torch.nn.Embedding"
]
] |
jkx19/MRQA
|
[
"c4195db7d68002739ed2aeee6fcee718a56bc9f7"
] |
[
"model/prefix.py"
] |
[
"import torch\nimport torch.nn\nfrom torch.nn import CrossEntropyLoss\nfrom transformers import BertPreTrainedModel, BertModel\nfrom transformers.modeling_outputs import QuestionAnsweringModelOutput\n\nfrom model.deberta import DebertaModel, DebertaPreTrainedModel\n\nclass BertForQuestionAnswering(BertPreTrainedModel):\n\n _keys_to_ignore_on_load_unexpected = [r\"pooler\"]\n\n def __init__(self, config):\n super().__init__(config)\n self.num_labels = config.num_labels\n\n self.bert = BertModel(config, add_pooling_layer=False)\n self.qa_outputs = torch.nn.Linear(config.hidden_size, config.num_labels)\n\n for param in self.bert.parameters():\n param.requires_grad = False\n\n self.init_weights()\n\n def forward(\n self,\n input_ids=None,\n attention_mask=None,\n token_type_ids=None,\n position_ids=None,\n head_mask=None,\n inputs_embeds=None,\n start_positions=None,\n end_positions=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n ):\n r\"\"\"\n start_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):\n Labels for position (index) of the start of the labelled span for computing the token classification loss.\n Positions are clamped to the length of the sequence (:obj:`sequence_length`). Position outside of the\n sequence are not taken into account for computing the loss.\n end_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):\n Labels for position (index) of the end of the labelled span for computing the token classification loss.\n Positions are clamped to the length of the sequence (:obj:`sequence_length`). Position outside of the\n sequence are not taken into account for computing the loss.\n \"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n outputs = self.bert(\n input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n sequence_output = outputs[0]\n\n logits = self.qa_outputs(sequence_output)\n start_logits, end_logits = logits.split(1, dim=-1)\n start_logits = start_logits.squeeze(-1).contiguous()\n end_logits = end_logits.squeeze(-1).contiguous()\n\n total_loss = None\n if start_positions is not None and end_positions is not None:\n # If we are on multi-GPU, split add a dimension\n if len(start_positions.size()) > 1:\n start_positions = start_positions.squeeze(-1)\n if len(end_positions.size()) > 1:\n end_positions = end_positions.squeeze(-1)\n # sometimes the start/end positions are outside our model inputs, we ignore these terms\n ignored_index = start_logits.size(1)\n start_positions = start_positions.clamp(0, ignored_index)\n end_positions = end_positions.clamp(0, ignored_index)\n\n loss_fct = CrossEntropyLoss(ignore_index=ignored_index)\n start_loss = loss_fct(start_logits, start_positions)\n end_loss = loss_fct(end_logits, end_positions)\n total_loss = (start_loss + end_loss) / 2\n\n if not return_dict:\n output = (start_logits, end_logits) + outputs[2:]\n return ((total_loss,) + output) if total_loss is not None else output\n\n return QuestionAnsweringModelOutput(\n loss=total_loss,\n start_logits=start_logits,\n end_logits=end_logits,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n )\n\n\nclass PrefixEncoder(torch.nn.Module):\n def __init__(self, config):\n super().__init__()\n self.embedding = torch.nn.Embedding(config.pre_seq_len, config.num_hidden_layers * 2 * config.hidden_size)\n # self.trans = torch.nn.Sequential(\n # torch.nn.Linear(config.hidden_size, config.mid_dim),\n # torch.nn.Tanh(),\n # torch.nn.Linear(config.mid_dim, config.num_hidden_layers * 2 * config.hidden_size)\n # )\n \n def forward(self, prefix: torch.Tensor):\n # prefix_tokens = self.embedding(prefix)\n # past_key_values = self.trans(prefix_tokens)\n past_key_values = self.embedding(prefix)\n return past_key_values\n\n\n\nclass BertPrefixModel(BertPreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n self.num_labels = config.num_labels\n\n self.pre_seq_len = config.pre_seq_len\n self.mid_dim = config.mid_dim\n self.n_layer = config.num_hidden_layers\n self.n_head = config.num_attention_heads\n self.n_embd = config.hidden_size // config.num_attention_heads\n\n self.bert = BertModel(config, add_pooling_layer=False)\n self.qa_outputs = torch.nn.Linear(config.hidden_size, config.num_labels)\n self.dropout = torch.nn.Dropout(config.dropout)\n self.prefix_encoder = PrefixEncoder(config)\n self.prefix_tokens = torch.arange(self.pre_seq_len).long()\n\n for param in self.bert.parameters():\n param.requires_grad = False\n\n self.init_weights()\n\n def get_prompt(self, batch_size):\n prefix_tokens = self.prefix_tokens.unsqueeze(0).expand(batch_size, -1).to(self.bert.device)\n past_key_values = self.prefix_encoder(prefix_tokens)\n bsz, seqlen, _ = past_key_values.shape\n past_key_values = past_key_values.view(\n bsz,\n seqlen,\n self.n_layer * 2, \n self.n_head,\n self.n_embd\n )\n past_key_values = self.dropout(past_key_values)\n past_key_values = past_key_values.permute([2, 0, 3, 1, 4]).split(2)\n return past_key_values\n\n def forward(\n self,\n input_ids=None,\n attention_mask=None,\n token_type_ids=None,\n position_ids=None,\n head_mask=None,\n inputs_embeds=None,\n start_positions=None,\n end_positions=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n ):\n r\"\"\"\n start_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):\n Labels for position (index) of the start of the labelled span for computing the token classification loss.\n Positions are clamped to the length of the sequence (:obj:`sequence_length`). Position outside of the\n sequence are not taken into account for computing the loss.\n end_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):\n Labels for position (index) of the end of the labelled span for computing the token classification loss.\n Positions are clamped to the length of the sequence (:obj:`sequence_length`). Position outside of the\n sequence are not taken into account for computing the loss.\n \"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n batch_size = input_ids.shape[0]\n past_key_values = self.get_prompt(batch_size=batch_size)\n prefix_attention_mask = torch.ones(batch_size, self.pre_seq_len).to(self.bert.device)\n attention_mask = torch.cat((prefix_attention_mask, attention_mask), dim=1)\n\n outputs = self.bert(\n input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n past_key_values=past_key_values,\n )\n\n sequence_output = outputs[0]\n\n logits = self.qa_outputs(sequence_output)\n start_logits, end_logits = logits.split(1, dim=-1)\n start_logits = start_logits.squeeze(-1).contiguous()\n end_logits = end_logits.squeeze(-1).contiguous()\n\n total_loss = None\n if start_positions is not None and end_positions is not None:\n # If we are on multi-GPU, split add a dimension\n if len(start_positions.size()) > 1:\n start_positions = start_positions.squeeze(-1)\n if len(end_positions.size()) > 1:\n end_positions = end_positions.squeeze(-1)\n # sometimes the start/end positions are outside our model inputs, we ignore these terms\n ignored_index = start_logits.size(1)\n start_positions = start_positions.clamp(0, ignored_index)\n end_positions = end_positions.clamp(0, ignored_index)\n\n loss_fct = CrossEntropyLoss(ignore_index=ignored_index)\n start_loss = loss_fct(start_logits, start_positions)\n end_loss = loss_fct(end_logits, end_positions)\n total_loss = (start_loss + end_loss) / 2\n\n if not return_dict:\n output = (start_logits, end_logits) + outputs[2:]\n return ((total_loss,) + output) if total_loss is not None else output\n\n return QuestionAnsweringModelOutput(\n loss=total_loss,\n start_logits=start_logits,\n end_logits=end_logits,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n )\n\n\nclass DebertaPrefixModel(DebertaPreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n self.num_labels = config.num_labels\n self.deberta = DebertaModel(config)\n self.dropout = torch.nn.Dropout(config.hidden_dropout_prob)\n self.qa_outputs = torch.nn.Linear(config.hidden_size, config.num_labels)\n self.init_weights()\n\n for param in self.deberta.parameters():\n param.requires_grad = False\n \n self.pre_seq_len = config.pre_seq_len\n self.mid_dim = config.mid_dim\n self.n_layer = config.num_hidden_layers\n self.n_head = config.num_attention_heads\n self.n_embd = config.hidden_size // config.num_attention_heads\n\n # Use a two layered MLP to encode the prefix\n self.prefix_tokens = torch.arange(self.pre_seq_len).long()\n self.prefix_encoder = PrefixEncoder(config)\n\n deberta_param = 0\n for name, param in self.deberta.named_parameters():\n deberta_param += param.numel()\n all_param = 0\n for name, param in self.named_parameters():\n all_param += param.numel()\n total_param = all_param - deberta_param\n print('total param is {}'.format(total_param)) # 9860105\n \n def get_prompt(self, batch_size):\n prefix_tokens = self.prefix_tokens.unsqueeze(0).expand(batch_size, -1).to(self.deberta.device)\n past_key_values = self.prefix_encoder(prefix_tokens)\n # bsz, seqlen, _ = past_key_values.shape\n past_key_values = past_key_values.view(\n batch_size,\n self.pre_seq_len,\n self.n_layer * 2, \n self.n_head,\n self.n_embd\n )\n past_key_values = self.dropout(past_key_values)\n past_key_values = past_key_values.permute([2, 0, 3, 1, 4]).split(2)\n return past_key_values\n\n def forward(\n self,\n input_ids=None,\n attention_mask=None,\n token_type_ids=None,\n position_ids=None,\n # head_mask=None,\n inputs_embeds=None,\n start_positions=None,\n end_positions=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n ):\n r\"\"\"\n start_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):\n Labels for position (index) of the start of the labelled span for computing the token classification loss.\n Positions are clamped to the length of the sequence (:obj:`sequence_length`). Position outside of the\n sequence are not taken into account for computing the loss.\n end_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):\n Labels for position (index) of the end of the labelled span for computing the token classification loss.\n Positions are clamped to the length of the sequence (:obj:`sequence_length`). Position outside of the\n sequence are not taken into account for computing the loss.\n \"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n batch_size = input_ids.shape[0]\n past_key_values = self.get_prompt(batch_size=batch_size)\n prefix_attention_mask = torch.ones(batch_size, self.pre_seq_len).to(self.deberta.device)\n attention_mask = torch.cat((prefix_attention_mask, attention_mask), dim=1)\n\n outputs = self.deberta(\n input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n past_key_values=past_key_values,\n )\n\n sequence_output = outputs[0]\n\n logits = self.qa_outputs(sequence_output)\n start_logits, end_logits = logits.split(1, dim=-1)\n start_logits = start_logits.squeeze(-1).contiguous()\n end_logits = end_logits.squeeze(-1).contiguous()\n\n total_loss = None\n if start_positions is not None and end_positions is not None:\n # If we are on multi-GPU, split add a dimension\n if len(start_positions.size()) > 1:\n start_positions = start_positions.squeeze(-1)\n if len(end_positions.size()) > 1:\n end_positions = end_positions.squeeze(-1)\n # sometimes the start/end positions are outside our model inputs, we ignore these terms\n ignored_index = start_logits.size(1)\n start_positions = start_positions.clamp(0, ignored_index)\n end_positions = end_positions.clamp(0, ignored_index)\n\n loss_fct = CrossEntropyLoss(ignore_index=ignored_index)\n start_loss = loss_fct(start_logits, start_positions)\n end_loss = loss_fct(end_logits, end_positions)\n total_loss = (start_loss + end_loss) / 2\n\n if not return_dict:\n output = (start_logits, end_logits) + outputs[2:]\n return ((total_loss,) + output) if total_loss is not None else output\n\n return QuestionAnsweringModelOutput(\n loss=total_loss,\n start_logits=start_logits,\n end_logits=end_logits,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n )"
] |
[
[
"torch.nn.Linear",
"torch.nn.Dropout",
"torch.cat",
"torch.arange",
"torch.nn.CrossEntropyLoss",
"torch.ones",
"torch.nn.Embedding"
]
] |
DingLi23/s2search
|
[
"54edff4aa21ec4be8891a27d0a04f9f578e771a9"
] |
[
"s2search_score.py"
] |
[
"from s2search.rank import S2Ranker\nimport os\nimport json\nimport numpy as np\nfrom pathlib import Path\n\n# data_dir = './s2search_data'\ns2_dir = './s2search_data'\nroot_dir = '/Users/ayuee/Documents/GitHub/XAI_PROJECT/data_process/masking'\nfeatures = ['title', 'abstract', 'venue', 'authors', 'year', 'n_citations', 'full']\npapers_example = [\n {\n 'title': 'Jumping NLP Curves: A Review of Natural Language Processing Research',\n 'abstract': 'Natural language processing (NLP) is a theory-motivated range of computational techniques for '\n 'the automatic analysis and representation of human language. NLP research has evolved from the '\n 'era of punch cards and batch processing (in which the analysis of a sentence could take up to 7 '\n 'minutes) to the era of Google and the likes of it (in which millions of webpages can be '\n 'processed in less than a second). This review paper draws on recent developments in NLP research '\n 'to look at the past, present, and future of NLP technology in a new light. Borrowing the '\n 'paradigm of jumping curves from the field of business management and marketing prediction, '\n 'this survey article reinterprets the evolution of NLP research as the intersection of three '\n 'overlapping curves-namely Syntactics, Semantics, and Pragmatics Curveswhich will eventually lead '\n 'NLP research to evolve into natural language understanding.',\n 'venue': 'IEEE Computational intelligence ',\n 'authors': ['E Cambria', 'B White'],\n 'year': 2014,\n 'n_citations': 900,\n }\n]\n\n\ndef S2_Rank(related_keywords, paper_dict_list, file=s2_dir):\n s2ranker = S2Ranker(file)\n score = s2ranker.score(related_keywords, paper_dict_list)\n return score\n\n\ndef S2_open_json(path):\n data = []\n with open(path) as f:\n Lines = f.readlines()\n for line in Lines:\n line_strip = line.strip()\n jso = json.loads(line_strip, strict=False)\n data.append(jso)\n return S2_Rank('machine learning', data, s2_dir)\n\n\ndef S2_save_score_as_np(s2score, feature):\n base_dir = str(Path(__file__).resolve().parent)\n data_dir = os.path.join(base_dir)\n os.environ.setdefault(\"DATA_DIR\", data_dir)\n output_data_file_name = os.path.join(os.environ.get(\"DATA_DIR\"), \"score\" + feature)\n np.save(output_data_file_name, s2score)\n\n\ndef S2_get_score(root_dir):\n score = []\n for root, dirs, files in os.walk(root_dir):\n for name in files:\n if name.endswith((\".json\")):\n for feature in features:\n if feature in name:\n full_path = os.path.join(root, name)\n print(full_path)\n score = S2_open_json(full_path)\n score = np.array(score)\n S2_save_score_as_np(score, feature)\n\n\nS2_get_score(root_dir)\n# print(S2_Rank('NLP', papers_example, s2_dir))\n# score = np.load('/Users/ayuee/Documents/GitHub/XAI_PROJECT/data_process/masking/full_Score.npy')\n# print(score, np.shape(score))\n"
] |
[
[
"numpy.array",
"numpy.save"
]
] |
GautamSridhar/FCN-implementation-on-Pytorch
|
[
"37a1f24f276ab43928038f899d58813a6c6c5dd3"
] |
[
"FCN8s_wVGG_mk2/FCN_VGG.py"
] |
[
"\"\"\"\nArchitecture definition for Fully Convolutional Neural Networks (FCN8s)\nInitialised with pretrained VGG weights\nWeights initialised by bilinear upsampling for convolutional transpose layers\n\"\"\"\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport numpy as np\nimport math\nimport os\nimport time\n\n#os.environ[\"CUDA_VISIBLE_DEVICES\"]= \"4\"\n\nuse_gpu = torch.cuda.is_available()\nnum_gpu = list(range(torch.cuda.device_count()))\n\n\t\ndef get_upsampling_weight(in_channels,out_channels,kernel_size):\n\t\"\"\" Make a 2D bilinear kernel suitable for upsampling\"\"\"\n\tfactor = (kernel_size+1)//2\n\tif kernel_size%2 == 1:\n\t\tcenter = factor-1\n\telse:\n\t\tcenter = factor-1\n\tog = np.ogrid[:kernel_size, :kernel_size]\n\tfilt = (1 - abs(og[0] - center)/factor) * (1 - abs(og[1] - center)/factor)\n\tweight = np.zeros((in_channels,out_channels,kernel_size,kernel_size), dtype = np.float64)\n\tweight[range(in_channels), range(out_channels),:,: ]\n\treturn torch.from_numpy(weight).float()\n\t\nclass FCN8s(nn.Module):\n\tdef __init__(self,n_class,vgg):\n\t\t\n\t\tsuper(FCN8s,self).__init__()\n\t\tself.vgg = vgg #VGG architecture definition \n\t\t#conv1\n\t\tself.conv1_1 = nn.Conv2d(3,64,3,padding=100)\n\t\tself.relu1_1 = nn.ReLU(inplace=True)\n\t\tself.conv1_2 = nn.Conv2d(64,64,3,padding = 1)\n\t\tself.relu1_2 = nn.ReLU(inplace=True)\n\t\tself.pool1 = nn.MaxPool2d(2, stride=2, ceil_mode=True) #1/2 dimension reduction\n\t\t\n\t\t#conv2\n\t\tself.conv2_1 = nn.Conv2d(64,128,3,padding = 1)\n\t\tself.relu2_1 = nn.ReLU(inplace=True)\n\t\tself.conv2_2 = nn.Conv2d(128,128,3,padding=1)\n\t\tself.relu2_2 = nn.ReLU(inplace=True)\n\t\tself.pool2 = nn.MaxPool2d(2, stride=2, ceil_mode=True) # 1/4 dimension reduction \n\t\t\n\t\t\n\t\t#conv3 \n\t\tself.conv3_1 = nn.Conv2d(128,256,3,padding=1)\n\t\tself.relu3_1 = nn.ReLU(inplace = True)\n\t\tself.conv3_2 = nn.Conv2d(256,256,3,padding=1)\n\t\tself.relu3_2 = nn.ReLU(inplace = True)\n\t\tself.conv3_3 = nn.Conv2d(256,256,3,padding=1)\n\t\tself.relu3_3 = nn.ReLU(inplace = True)\n\t\tself.pool3 = nn.MaxPool2d(2, stride=2, ceil_mode=True) # 1/8 dimension reduction\n\t\t\n\t\t#conv4\n\t\tself.conv4_1 = nn.Conv2d(256, 512, 3, padding=1)\n\t\tself.relu4_1 = nn.ReLU(inplace=True)\n\t\tself.conv4_2 = nn.Conv2d(512, 512, 3, padding=1)\n\t\tself.relu4_2 = nn.ReLU(inplace=True)\n\t\tself.conv4_3 = nn.Conv2d(512, 512, 3, padding=1)\n\t\tself.relu4_3 = nn.ReLU(inplace=True)\n\t\tself.pool4 = nn.MaxPool2d(2, stride=2, ceil_mode=True) # 1/16 dimension reduction\n\t\t\n\t\t#conv5\n\t\tself.conv5_1 = nn.Conv2d(512, 512, 3, padding=1)\n\t\tself.relu5_1 = nn.ReLU(inplace=True)\n\t\tself.conv5_2 = nn.Conv2d(512, 512, 3, padding=1)\n\t\tself.relu5_2 = nn.ReLU(inplace=True)\n\t\tself.conv5_3 = nn.Conv2d(512, 512, 3, padding=1)\n\t\tself.relu5_3 = nn.ReLU(inplace=True)\n\t\tself.pool5 = nn.MaxPool2d(2, stride=2, ceil_mode=True) # 1/32 dimension reduction\n\t\t\n\t\t#fc6\n\t\tself.fc6 = nn.Conv2d(512,4096,7)\n\t\tself.relu6 = nn.ReLU(inplace=True)\n\t\tself.drop6 = nn.Dropout2d()\n\t\t\n\t\t#fc7\n\t\tself.fc7 = nn.Conv2d(4096,4096,1)\n\t\tself.relu7 = nn.ReLU(inplace = True)\n\t\tself.drop7 = nn.Dropout2d()\n\t\t\n\t\tself.score_fr = nn.Conv2d(4096,n_class,1) #Skip Layer defintions\n\t\tself.score_pool3 = nn.Conv2d(256,n_class,1)\n\t\tself.score_pool4 = nn.Conv2d(512,n_class,1)\n\t\t\n\t\tself.upscore2 = nn.ConvTranspose2d(n_class,n_class,4,stride=2,bias=False) #Upsampling layer defintions\n\t\tself.upscore8 = nn.ConvTranspose2d(n_class,n_class,16,stride=8,bias=False)\n\t\tself.upscore_pool4 = nn.ConvTranspose2d(n_class,n_class,4,stride=2,bias=False)\n\t\t\n\t\tself._copy_params_from_vgg16()\n\t\t\t\t\t\t\t\t\t\n\tdef forward(self,x):\n\t\th = x\n\t\th = self.relu1_1(self.conv1_1(h))\n\t\th = self.relu1_2(self.conv1_2(h))\n\t\th = self.pool1(h)\n\t\t\t\n\t\th = self.relu2_1(self.conv2_1(h))\n\t\th = self.relu2_2(self.conv2_2(h))\n\t\th = self.pool2(h)\n\t\t\t\n\t\th = self.relu3_1(self.conv3_1(h))\n\t\th = self.relu3_2(self.conv3_2(h))\n\t\th = self.relu3_3(self.conv3_3(h))\n\t\th = self.pool3(h)\n\t\tpool3 = h # 1/8\n\t\t\t\n\t\th = self.relu4_1(self.conv4_1(h))\n\t\th = self.relu4_2(self.conv4_2(h))\n\t\th = self.relu4_3(self.conv4_3(h))\n\t\th = self.pool4(h)\n\t\tpool4 = h # 1/16\n\t\t\t\n\t\th = self.relu5_1(self.conv5_1(h))\n\t\th = self.relu5_2(self.conv5_2(h))\n\t\th = self.relu5_3(self.conv5_3(h))\n\t\th = self.pool5(h)\n\t\t\n\t\t\t\n\t\th = self.relu6(self.fc6(h))\n\t\th = self.drop6(h)\n\t\t\t\n\t\th = self.relu7(self.fc7(h))\n\t\th = self.drop7(h)\n\t\t\t\n\t\th = self.score_fr(h)\n\t\th = self.upscore2(h)\n\t\tupscore2 = h # 1/16\n\t\t\t\n\t\th = self.score_pool4(pool4)\n\t\th = h[:, :, 5:5 + upscore2.size()[2], 5:5 + upscore2.size()[3]]\n\t\tscore_pool4c = h\n\t\t\t\n\t\th = upscore2 + score_pool4c # 1/16\n\t\th = self.upscore_pool4(h)\n\t\tupscore_pool4 = h # 1/8\n\t\t\t\n\t\th = self.score_pool3(pool3)\n\t\th = h[:,:,9:9+upscore_pool4.size()[2],9:9+upscore_pool4.size()[3]]\n\t\tscore_pool3c = h\n\t\t\t\n\t\th = upscore_pool4 + score_pool3c\n\t\t\t\n\t\th = self.upscore8(h)\n\t\th = h[:, :, 31:31 + x.size()[2], 31:31 + x.size()[3]].contiguous()\n\t\t\t\t\n\t\treturn h\n\t\n\tdef _copy_params_from_vgg16(self):\n #Copy VGG parameters from a pretrained VGG16 net available on Pytorch\n #Generate weights for all layers not part of VGG16 by either Xavier or Bilinear upsampling\n\n\t\tfeatures = [self.conv1_1, self.relu1_1, self.conv1_2, self.relu1_2, self.pool1, self.conv2_1, self.relu2_1, self.conv2_2, self.relu2_2, self.pool2,self.conv3_1, self.relu3_1, self.conv3_2, self.relu3_2, self.conv3_3, self.relu3_3, self.pool3,self.conv4_1, self.relu4_1, self.conv4_2, self.relu4_2, self.conv4_3, self.relu4_3, self.pool4, self.conv5_1, self.relu5_1, self.conv5_2, self.relu5_2, self.conv5_3, self.relu5_3, self.pool5,]\n\t\tfor l1,l2 in zip(self.vgg.features,features):\n\t\t\tif isinstance(l1,nn.Conv2d) and isinstance(l2,nn.Conv2d):\n\t\t\t\tassert l1.weight.size() == l2.weight.size()\n\t\t\t\tassert l1.bias.size() == l2.bias.size()\n\t\t\t\tl2.weight.data.copy_(l1.weight.data).double()\n\t\t\t\tl2.bias.data.copy_(l1.bias.data).double()\n\t\t\t\tl2.bias.data.copy_(l1.bias.data).double()\n\n\t\tclassifier = [self.fc6,self.relu6,self.drop6,self.fc7,self.relu7,self.drop7,self.score_fr,self.score_pool3,self.score_pool4,self.upscore2,self.upscore8,self.upscore_pool4]\n\t\tfor i in classifier:\n\t\t\tif isinstance(i,nn.Conv2d):\n\t\t\t\tn = i.kernel_size[0] * i.kernel_size[1] *i.out_channels\n\t\t\t\ti.weight.data.normal_(0,math.sqrt(2./n))\n\t\t\t\tif i.bias is not None:\n\t\t\t\t\ti.bias.data.zero_()\n\t\t\tif isinstance(i,nn.ConvTranspose2d):\n\t\t\t\tassert i.kernel_size[0] == i.kernel_size[1]\n\t\t\t\tinitial_weight = get_upsampling_weight(i.in_channels,i.out_channels,i.kernel_size[0])\n\t\t\t\ti.weight.data.copy_(initial_weight)\n\t\t\t\t\t \t\n\"\"\"\n#Test Code\t\t\t\nif __name__ == \"__main__\":\n\tbatch_size, n_class, h,w = 5,11,224,224\n\t\n\t#test the output size\n\t\n\tfcn_model = FCN8s(n_class)\n\tif use_gpu:\n\t\tts = time.time()\n\t\tfcn_model = fcn_model.cuda()\n\t\tprint (\"Finsished loading CUDA, time elapsed {}\".format(time.time()-ts))\n\t\n\tinput = torch.autograd.Variable(torch.randn(batch_size,3,h,w).cuda())\n\tprint(\"hello\")\n\toutput = fcn_model(input)\n\tprint(output.size())\n\t\n\t#To check whether training properly\n\ty = torch.autograd.Variable(torch.randn(batch_size,n_class,h,w).cuda())\n\tcriterion = nn.BCEWithLogitsLoss()\n\toptimiser = optim.SGD(fcn_model.parameters(),lr=1e-3,momentum=0.9)\n\tfor iter in range(10):\n\t\toptimiser.zero_grad()\n\t\toutput = fcn_model(input)\n\t\tloss = criterion(output,y)\n\t\tloss.backward()\n\t\tprint(\"iter {}, loss {}\".format(iter, loss.data[0]))\n\t\toptimiser.step()\n\"\"\""
] |
[
[
"numpy.zeros",
"torch.nn.MaxPool2d",
"torch.nn.ConvTranspose2d",
"torch.cuda.device_count",
"torch.nn.ReLU",
"torch.from_numpy",
"torch.nn.Conv2d",
"torch.cuda.is_available",
"torch.nn.Dropout2d"
]
] |
samaloney/sunpy
|
[
"89142033a7a76bcd3b2791b779b8b43fac65a7f4"
] |
[
"sunpy/sun/sun.py"
] |
[
"\"\"\"\nThis module provides Sun-related parameters.\n\"\"\"\nimport numpy as np\n\nimport astropy.units as u\nfrom astropy.coordinates import Angle, Latitude, Longitude\n\nfrom sunpy.sun import constants\nfrom sunpy.time import julian_centuries, parse_time\nfrom sunpy.time.time import _variables_for_parse_time_docstring\nfrom sunpy.util.decorators import add_common_docstring\n\n__all__ = [\n \"print_params\", \"apparent_declination\",\n \"apparent_rightascension\", \"apparent_obliquity_of_ecliptic\", \"true_declination\",\n \"true_rightascension\", \"true_obliquity_of_ecliptic\", \"apparent_latitude\", \"true_latitude\",\n \"apparent_longitude\", \"true_anomaly\", \"true_longitude\",\n \"equation_of_center\", \"geometric_mean_longitude\", \"carrington_rotation_number\", \"mean_anomaly\",\n \"longitude_sun_perigee\", \"mean_ecliptic_longitude\", \"eccentricity_sun_earth_orbit\", \"position\",\n \"solar_semidiameter_angular_size\", \"solar_cycle_number\"\n]\n\n\n@add_common_docstring(**_variables_for_parse_time_docstring())\ndef solar_cycle_number(t='now'):\n \"\"\"\n Return the solar cycle number.\n\n Parameters\n ----------\n t : {parse_time_types}\n A time (usually the start time) specified as a parse_time-compatible\n time string, number, or a datetime object.\n \"\"\"\n time = parse_time(t)\n result = (int(time.strftime('%Y')) + 8) % 28 + 1\n return result\n\n\n@add_common_docstring(**_variables_for_parse_time_docstring())\ndef solar_semidiameter_angular_size(t='now'):\n \"\"\"\n Return the angular size of the semi-diameter of the Sun as a function of\n time as viewed from Earth (in arcsec)\n\n Parameters\n ----------\n t : {parse_time_types}\n A time (usually the start time) specified as a parse_time-compatible\n time string, number, or a datetime object.\n \"\"\"\n # Import here to avoid a circular import\n from sunpy.coordinates import get_sunearth_distance\n solar_semidiameter_rad = (constants.radius.to(u.AU)) / get_sunearth_distance(t)\n return Angle(solar_semidiameter_rad.to(u.arcsec, equivalencies=u.dimensionless_angles()))\n\n\n@add_common_docstring(**_variables_for_parse_time_docstring())\ndef position(t='now'):\n \"\"\"\n Returns the position of the Sun (right ascension and declination) on the\n celestial sphere using the equatorial coordinate system in arcsec.\n\n Parameters\n ----------\n t : {parse_time_types}\n A time (usually the start time) specified as a parse_time-compatible\n time string, number, or a datetime object.\n \"\"\"\n ra = true_rightascension(t)\n dec = true_declination(t)\n return ra, dec\n\n\n@add_common_docstring(**_variables_for_parse_time_docstring())\ndef eccentricity_sun_earth_orbit(t='now'):\n \"\"\"\n Returns the eccentricity of the Sun Earth Orbit.\n\n Parameters\n ----------\n t : {parse_time_types}\n A time (usually the start time) specified as a palongitude_Sun_perigee, true_latitude and apparent_latitude need to be fixedrse_time-compatible\n time string, number, or a datetime object.\n \"\"\"\n T = julian_centuries(t)\n result = 0.016751040 - 0.00004180 * T - 0.0000001260 * T**2\n return result\n\n\n@add_common_docstring(**_variables_for_parse_time_docstring())\ndef mean_ecliptic_longitude(t='now'):\n \"\"\"\n Returns the mean ecliptic longitude.\n\n Parameters\n ----------\n t : {parse_time_types}\n A time (usually the start time) specified as a parse_time-compatible\n time string, number, or a datetime object.\n \"\"\"\n T = julian_centuries(t)\n result = 279.696680 + 36000.76892 * T + 0.0003025 * T**2\n result = result * u.deg\n return Longitude(result)\n\n\n@add_common_docstring(**_variables_for_parse_time_docstring())\ndef longitude_sun_perigee(t='now'):\n \"\"\"\n Returns the current solar perigee.\n\n Parameters\n ----------\n t : {parse_time_types}\n A time (usually the start time) specified as a parse_time-compatible\n time string, number, or a datetime object.\n \"\"\"\n # TODO: FIX THIS\n return 1\n\n\n@add_common_docstring(**_variables_for_parse_time_docstring())\ndef mean_anomaly(t='now'):\n \"\"\"\n Returns the mean anomaly (the angle through which the Sun has moved\n assuming a circular orbit) as a function of time.\n\n Parameters\n ----------\n t : {parse_time_types}\n A time (usually the start time) specified as a parse_time-compatible\n time string, number, or a datetime object.\n \"\"\"\n T = julian_centuries(t)\n result = 358.475830 + 35999.049750 * T - 0.0001500 * T**2 - 0.00000330 * T**3\n result = result * u.deg\n return Longitude(result)\n\n\n@add_common_docstring(**_variables_for_parse_time_docstring())\ndef carrington_rotation_number(t='now'):\n \"\"\"\n Return the Carrington Rotation number.\n\n Parameters\n ----------\n t : {parse_time_types}\n A time (usually the start time) specified as a parse_time-compatible\n time string, number, or a datetime object.\n \"\"\"\n jd = parse_time(t).jd\n result = (1. / 27.2753) * (jd - 2398167.0) + 1.0\n return result\n\n\n@add_common_docstring(**_variables_for_parse_time_docstring())\ndef geometric_mean_longitude(t='now'):\n \"\"\"\n Returns the geometric mean longitude (in degrees).\n\n Parameters\n ----------\n t : {parse_time_types}\n A time (usually the start time) specified as a parse_time-compatible\n time string, number, or a datetime object.\n \"\"\"\n T = julian_centuries(t)\n result = 279.696680 + 36000.76892 * T + 0.0003025 * T**2\n result = result * u.deg\n return Longitude(result)\n\n\n@add_common_docstring(**_variables_for_parse_time_docstring())\ndef equation_of_center(t='now'):\n \"\"\"\n Returns the Sun's equation of center (in degrees).\n\n Parameters\n ----------\n t : {parse_time_types}\n A time (usually the start time) specified as a parse_time-compatible\n time string, number, or a datetime object.\n \"\"\"\n T = julian_centuries(t)\n mna = mean_anomaly(t)\n result = ((1.9194600 - 0.0047890 * T - 0.0000140 * T**2) * np.sin(mna) +\n (0.0200940 - 0.0001000 * T) * np.sin(2 * mna) + 0.0002930 * np.sin(3 * mna))\n result = result * u.deg\n return Angle(result)\n\n\n@add_common_docstring(**_variables_for_parse_time_docstring())\ndef true_longitude(t='now'):\n \"\"\"\n Returns the Sun's true geometric longitude (in degrees).\n\n Referred to the mean equinox of date.\n\n Parameters\n ----------\n t : {parse_time_types}\n A time (usually the start time) specified as a parse_time-compatible\n time string, number, or a datetime object.\n \"\"\"\n # TODO: Should the higher accuracy terms from which app_long is derived be added to true_long?\n result = equation_of_center(t) + geometric_mean_longitude(t)\n return Longitude(result)\n\n\n@add_common_docstring(**_variables_for_parse_time_docstring())\ndef true_anomaly(t='now'):\n \"\"\"\n Returns the Sun's true anomaly (in degrees).\n\n Parameters\n ----------\n t : {parse_time_types}\n A time (usually the start time) specified as a parse_time-compatible\n time string, number, or a datetime object.\n \"\"\"\n result = mean_anomaly(t) + equation_of_center(t)\n return Longitude(result)\n\n\n@add_common_docstring(**_variables_for_parse_time_docstring())\ndef apparent_longitude(t='now'):\n \"\"\"\n Returns the apparent longitude of the Sun.\n\n Parameters\n ----------\n t : {parse_time_types}\n A time (usually the start time) specified as a parse_time-compatible\n time string, number, or a datetime object.\n \"\"\"\n T = julian_centuries(t)\n omega = (259.18 - 1934.142 * T) * u.deg\n true_long = true_longitude(t)\n result = true_long - (0.00569 - 0.00479 * np.sin(omega)) * u.deg\n return Longitude(result)\n\n\n@add_common_docstring(**_variables_for_parse_time_docstring())\ndef true_latitude(t='now'):\n \"\"\"\n Returns the true latitude.\n\n Never more than 1.2 arcsec from 0, set to 0 here.\n\n Parameters\n ----------\n t : {parse_time_types}\n A time (usually the start time) specified as a parse_time-compatible\n time string, number, or a datetime object.\n \"\"\"\n # TODO: FIX THIS\n return Latitude(0.0 * u.deg)\n\n\n@add_common_docstring(**_variables_for_parse_time_docstring())\ndef apparent_latitude(t='now'):\n \"\"\"\n Returns the true latitude.\n\n Set to 0 here.\n\n Parameters\n ----------\n t : {parse_time_types}\n A time (usually the start time) specified as a parse_time-compatible\n time string, number, or a datetime object.\n \"\"\"\n # TODO: FIX THIS\n return Latitude(0.0 * u.deg)\n\n\n@add_common_docstring(**_variables_for_parse_time_docstring())\ndef true_obliquity_of_ecliptic(t='now'):\n \"\"\"\n Returns the true obliquity of the ecliptic.\n\n Parameters\n ----------\n t : {parse_time_types}\n A time (usually the start time) specified as a parse_time-compatible\n time string, number, or a datetime object.\n \"\"\"\n T = julian_centuries(t)\n result = 23.452294 - 0.0130125 * T - 0.00000164 * T**2 + 0.000000503 * T**3\n return Angle(result, u.deg)\n\n\n@add_common_docstring(**_variables_for_parse_time_docstring())\ndef true_rightascension(t='now'):\n \"\"\"\n Return the true right ascension.\n\n Parameters\n ----------\n t : {parse_time_types}\n A time (usually the start time) specified as a parse_time-compatible\n time string, number, or a datetime object.\n \"\"\"\n y = np.cos(true_obliquity_of_ecliptic(t)) * np.sin(true_longitude(t))\n x = np.cos(true_longitude(t))\n true_ra = np.arctan2(y, x)\n return Longitude(true_ra.to(u.hourangle))\n\n\n@add_common_docstring(**_variables_for_parse_time_docstring())\ndef true_declination(t='now'):\n \"\"\"\n Return the true declination.\n\n Parameters\n ----------\n t : {parse_time_types}\n A time (usually the start time) specified as a parse_time-compatible\n time string, number, or a datetime object.\n \"\"\"\n result = np.arcsin(np.sin(true_obliquity_of_ecliptic(t)) * np.sin(apparent_longitude(t)))\n return Latitude(result.to(u.deg))\n\n\n@add_common_docstring(**_variables_for_parse_time_docstring())\ndef apparent_obliquity_of_ecliptic(t='now'):\n \"\"\"\n Return the apparent obliquity of the ecliptic.\n\n Parameters\n ----------\n t : {parse_time_types}\n A time (usually the start time) specified as a parse_time-compatible\n time string, number, or a datetime object.\n \"\"\"\n omega = apparent_longitude(t)\n result = true_obliquity_of_ecliptic(t) + (0.00256 * np.cos(omega)) * u.deg\n return result\n\n\n@add_common_docstring(**_variables_for_parse_time_docstring())\ndef apparent_rightascension(t='now'):\n \"\"\"\n Returns the apparent right ascension of the Sun.\n\n Parameters\n ----------\n t : {parse_time_types}\n A time (usually the start time) specified as a parse_time-compatible\n time string, number, or a datetime object.\n \"\"\"\n y = np.cos(apparent_obliquity_of_ecliptic(t)) * np.sin(apparent_longitude(t))\n x = np.cos(apparent_longitude(t))\n app_ra = np.arctan2(y, x)\n return Longitude(app_ra.to(u.hourangle))\n\n\n@add_common_docstring(**_variables_for_parse_time_docstring())\ndef apparent_declination(t='now'):\n \"\"\"\n Returns the apparent declination of the Sun.\n\n Parameters\n ----------\n t : {parse_time_types}\n A time (usually the start time) specified as a parse_time-compatible\n time string, number, or a datetime object.\n \"\"\"\n ob = apparent_obliquity_of_ecliptic(t)\n app_long = apparent_longitude(t)\n result = np.arcsin(np.sin(ob)) * np.sin(app_long)\n return Latitude(result.to(u.deg))\n\n\n@add_common_docstring(**_variables_for_parse_time_docstring())\ndef print_params(t='now'):\n \"\"\"\n Print out a summary of Solar ephemeris.\n\n Parameters\n ----------\n t : {parse_time_types}\n A time (usually the start time) specified as a parse_time-compatible\n time string, number, or a datetime object.\n \"\"\"\n # import here to avoid circular import\n from sunpy.coordinates.ephemeris import (get_sun_L0, get_sun_B0,\n get_sun_P, get_sunearth_distance)\n\n print('Solar Ephemeris for {}\\n'.format(parse_time(t).ctime()))\n print('Distance = {}'.format(get_sunearth_distance(t)))\n print('Semidiameter = {}'.format(solar_semidiameter_angular_size(t)))\n print('True (long, lat) = ({}, {})'.format(true_longitude(t), true_latitude(t)))\n print('Apparent (long, lat) = ({}, {})'.format(apparent_longitude(t), apparent_latitude(t)))\n print('True (RA, Dec) = ({}, {})'.format(true_rightascension(t), true_declination(t)))\n print('Apparent (RA, Dec) = ({}, {})'.format(apparent_rightascension(t),\n apparent_declination(t)))\n print('Heliographic long. and lat of disk center = ({}, {})'.format(get_sun_L0(t),\n get_sun_B0(t)))\n print('Position angle of north pole in = {}'.format(get_sun_P(t)))\n print('Carrington Rotation Number = {}'.format(carrington_rotation_number(t)))\n"
] |
[
[
"numpy.sin",
"numpy.arctan2",
"numpy.cos"
]
] |
IsaacYangSLA/NVFlare
|
[
"8c6582894c9a8431f64479bc9f472fefcd71e5a7"
] |
[
"tests/integration_test/tf2/trainer.py"
] |
[
"# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom nvflare.apis.dxo import DXO, DataKind, from_shareable\nfrom nvflare.apis.event_type import EventType\nfrom nvflare.apis.executor import Executor\nfrom nvflare.apis.fl_constant import ReturnCode\nfrom nvflare.apis.fl_context import FLContext\nfrom nvflare.apis.shareable import Shareable, make_reply\nfrom nvflare.apis.signal import Signal\n\nfrom .net import Net\n\n\nclass SimpleTrainer(Executor):\n def __init__(self, epochs_per_round):\n super().__init__()\n self.epochs_per_round = epochs_per_round\n self.train_images, self.train_labels = None, None\n self.test_images, self.test_labels = None, None\n self.model = None\n\n def handle_event(self, event_type: str, fl_ctx: FLContext):\n if event_type == EventType.START_RUN:\n self.setup(fl_ctx)\n\n def setup(self, fl_ctx: FLContext):\n (self.train_images, self.train_labels), (\n self.test_images,\n self.test_labels,\n ) = tf.keras.datasets.mnist.load_data()\n self.train_images, self.test_images = (\n self.train_images / 255.0,\n self.test_images / 255.0,\n )\n\n # simulate separate datasets for each client by dividing MNIST dataset in half\n client_name = fl_ctx.get_identity_name()\n if client_name == \"site-1\":\n self.train_images = self.train_images[: len(self.train_images) // 2]\n self.train_labels = self.train_labels[: len(self.train_labels) // 2]\n self.test_images = self.test_images[: len(self.test_images) // 2]\n self.test_labels = self.test_labels[: len(self.test_labels) // 2]\n elif client_name == \"site-2\":\n self.train_images = self.train_images[len(self.train_images) // 2 :]\n self.train_labels = self.train_labels[len(self.train_labels) // 2 :]\n self.test_images = self.test_images[len(self.test_images) // 2 :]\n self.test_labels = self.test_labels[len(self.test_labels) // 2 :]\n\n model = Net()\n\n loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)\n model.compile(optimizer=\"adam\", loss=loss_fn, metrics=[\"accuracy\"])\n _ = model(tf.keras.Input(shape=(28, 28)))\n self.var_list = [model.get_layer(index=index).name for index in range(len(model.get_weights()))]\n self.model = model\n\n def execute(\n self,\n task_name: str,\n shareable: Shareable,\n fl_ctx: FLContext,\n abort_signal: Signal,\n ) -> Shareable:\n \"\"\"\n This function is an extended function from the super class.\n As a supervised learning based trainer, the train function will run\n evaluate and train engines based on model weights from `shareable`.\n After finishing training, a new `Shareable` object will be submitted\n to server for aggregation.\n\n Args:\n task_name: dispatched task\n shareable: the `Shareable` object acheived from server.\n fl_ctx: the `FLContext` object achieved from server.\n abort_signal: if triggered, the training will be aborted.\n\n Returns:\n a new `Shareable` object to be submitted to server for aggregation.\n \"\"\"\n\n # retrieve model weights download from server's shareable\n if abort_signal.triggered:\n return make_reply(ReturnCode.OK)\n\n if task_name != \"train\":\n return shareable\n\n dxo = from_shareable(shareable)\n model_weights = dxo.data\n\n # use previous round's client weights to replace excluded layers from server\n prev_weights = {\n self.model.get_layer(index=key).name: value for key, value in enumerate(self.model.get_weights())\n }\n print(\"dxo\")\n ordered_model_weights = {key: model_weights.get(key) for key in prev_weights}\n for key in self.var_list:\n value = ordered_model_weights.get(key)\n if np.all(value == 0):\n ordered_model_weights[key] = prev_weights[key]\n\n # update local model weights with received weights\n self.model.set_weights(list(ordered_model_weights.values()))\n\n # adjust LR or other training time info as needed\n # such as callback in the fit function\n self.model.fit(\n self.train_images,\n self.train_labels,\n epochs=self.epochs_per_round,\n validation_data=(self.test_images, self.test_labels),\n )\n\n # report updated weights in shareable\n weights = {self.model.get_layer(index=key).name: value for key, value in enumerate(self.model.get_weights())}\n dxo = DXO(data_kind=DataKind.WEIGHTS, data=weights)\n\n self.log_info(fl_ctx, \"Local epochs finished. Returning shareable\")\n\n return dxo.update_shareable(shareable)\n"
] |
[
[
"numpy.all",
"tensorflow.keras.losses.SparseCategoricalCrossentropy",
"tensorflow.keras.Input",
"tensorflow.keras.datasets.mnist.load_data"
]
] |
coherent17/numpy_practice
|
[
"c1b3c238a1c9f49b78a10a2e9e7751f077c9a829"
] |
[
"np3.py"
] |
[
"import numpy as np\n\n#1. numpy calculation\na=np.arange(1,10).reshape(3,3)\nb=np.arange(10,19).reshape(3,3)\nprint(a)\nprint(b)\n#所有元素都加1\nprint(a+1)\n\n#所有元素都平方\nprint(a**2)\n\n#判斷式輸出boolen\nprint(a<5)\n\n#相對應的元素相加\nprint(a*b)\n\n#矩陣內積\nprint(np.dot(a,b))\n\n#2. function i numpy and statistic\nc=np.arange(1,10).reshape(3,3)\nprint(c)\n#[[1 2 3]\n# [4 5 6]\n# [7 8 9]]\n\n#最小值與最大值\nprint(np.min(c),np.max(c)) #1 9\n\n#總和 乘積 平均\nprint(np.sum(c),np.product(c),np.mean(c)) #45 362880 5.0\n\n#標準差\nprint(np.std(c)) #2.581988897471611\n\n#變異數\nprint(np.var(c)) #6.666666666666667\n\n#中位數\nprint(np.median(c)) #5.0\n\n#max-min\nprint(np.ptp(c)) #8\n\n#3. sort in numpy\nd=np.random.choice(50,size=10,replace=False)\n#before sorting\nprint(d)\n#after sorting\nprint(np.sort(d))\n#the index after sorting\nprint(np.argsort(d))\n#use the index to get the value\nfor i in np.argsort(d):\n print(d[i],end=\" \")\nprint(\"\\n\")\n\n#N dimension array sorting\ne=np.random.randint(0,10,(3,5))\nprint(e)\n#對每一直行sort\nprint(np.sort(e,axis=0))\n#對每一橫列sort\nprint(np.sort(e,axis=1))"
] |
[
[
"numpy.max",
"numpy.product",
"numpy.dot",
"numpy.random.choice",
"numpy.median",
"numpy.sum",
"numpy.min",
"numpy.mean",
"numpy.std",
"numpy.random.randint",
"numpy.sort",
"numpy.argsort",
"numpy.ptp",
"numpy.arange",
"numpy.var"
]
] |
zhangxinyi0106/graph-convnet-tsp
|
[
"dabee0764a63d81d2aec643c58d8cacd488381cb"
] |
[
"data/generate_tsp_concorde.py"
] |
[
"import time\nimport argparse\nimport pprint as pp\nimport os\n\nimport pandas as pd\nimport numpy as np\nfrom concorde.tsp import TSPSolver\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--num_samples\", type=int, default=10000)\n parser.add_argument(\"--num_nodes\", type=int, default=20)\n parser.add_argument(\"--node_dim\", type=int, default=2)\n parser.add_argument(\"--filename\", type=str, default=None)\n opts = parser.parse_args()\n \n if opts.filename is None:\n opts.filename = f\"tsp{opts.num_nodes}_concorde_new.txt\"\n \n # Pretty print the run args\n pp.pprint(vars(opts))\n \n set_nodes_coord = np.random.random([opts.num_samples, opts.num_nodes, opts.node_dim])\n scaled_set_nodes_coord = 1000*set_nodes_coord\n with open(opts.filename, \"w\") as f:\n start_time = time.time()\n for i, nodes_coord in enumerate(scaled_set_nodes_coord):\n solver = TSPSolver.from_data(nodes_coord[:,0], nodes_coord[:,1], norm=\"EUC_2D\")\n solution = solver.solve()\n f.write( \" \".join( str(x)+str(\" \")+str(y) for x,y in set_nodes_coord[i]) )\n f.write( str(\" \") + str('output') + str(\" \") )\n f.write( str(\" \").join( str(node_idx+1) for node_idx in solution.tour) )\n f.write( str(\" \") + str(solution.tour[0]+1) + str(\" \") )\n f.write( \"\\n\" )\n end_time = time.time() - start_time\n \n print(f\"Completed generation of {opts.num_samples} samples of TSP{opts.num_nodes}.\")\n print(f\"Total time: {end_time/3600:.1f}h\")\n print(f\"Average time: {(end_time/3600)/opts.num_samples:.1f}h\")\n"
] |
[
[
"numpy.random.random"
]
] |
jooner/lab
|
[
"b391c80aabfab4d9377147cdf7fcdb31da0029fd"
] |
[
"train_embedding.py"
] |
[
"\"\"\"\\\n\nWord Embedding Exercise\n\n\"\"\"\n\n\nimport numpy as np\nfrom tqdm import tqdm, tnrange, tqdm_notebook\nfrom pandas import read_csv\nfrom nltk import word_tokenize\n\nimport torch\nfrom torch import optim\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nwhitepapers = read_csv('whitepapers.csv')\n# merge description and document text\nwhitepapers['text'] = whitepapers.description + ' ' +\\\n whitepapers.document_text\n# filter down to relevant entries\ndf = whitepapers.drop(columns=['description',\n 'document_text',\n 'document_tokens'])\ndel whitepapers\n\n# tokenize (aka .split()++, thank you nltk)\ntrain_txt = ''\nfor _, row in df.iterrows():\n train_txt += row['text'].lower()\ntokens = word_tokenize(train_txt)\ndel df\n\n# word2idx and idx2word setup\nunique_tokens = set(tokens)\nw2x = {word: idx for (idx, word) in enumerate(unique_tokens)}\nx2w = {idx: word for (idx, word) in enumerate(unique_tokens)}\nindices = [w2x[w] for w in tokens]\n\n# generate training data\nwindow = 2\ntrain_data = []\nfor idx in range(len(indices)):\n for r in range(-window, window + 1):\n cxt = idx + r\n if not ((cxt < 0) or (cxt >= len(indices)) or (idx == cxt)):\n train_data.append([indices[idx], indices[cxt]])\ntrain_data = np.array(train_data)\ntrain_data = torch.LongTensor(train_data)\n\n# record vocab_size\nvocab_size = len(unique_tokens)\n# sanity check\nfor [x,y] in train_data[200100:200105]:\n print(x2w[int(x)], x2w[int(y)])\n# clean memory\ndel indices\ndel tokens\n\n\n# Continuous Bag-of-Words Model\nclass CBOW(nn.Module):\n def __init__(self, vocab_size, embedding_dim, hidden_dim,\n context_size, batch_size):\n super(CBOW, self).__init__()\n self.batch_size = batch_size\n self.embed = nn.Embedding(vocab_size, embedding_dim)\n self.fc1 = nn.Linear(embedding_dim, hidden_dim)\n self.fc2 = nn.Linear(hidden_dim, vocab_size)\n self.out = nn.Softmax(dim=2)\n \n def forward(self, x):\n x = self.embed(x).view(self.batch_size, 1, -1)\n x = F.relu(self.fc1(x))\n x = self.fc2(x)\n return self.out(x).squeeze()\n\n\nmodel = CBOW(vocab_size=vocab_size, embedding_dim=100, hidden_dim=128,\n context_size=2, batch_size=256).cuda()\n\ndef one_hot(idx_batch):\n one_hot_mat = torch.zeros((len(idx_batch), vocab_size)).float()\n indices = torch.LongTensor(idx_batch).view(-1, 1)\n one_hot_mat.scatter_(1, indices, 1.0)\n return one_hot_mat\n\ndef mat_loss(pred, gt):\n delta = pred.float() - gt.float()\n norm = torch.norm(delta, p=2, dim=1)\n return (torch.sum(norm) / gt.shape[1])\n\ndef batchify(data, batch_size, use_cuda=False):\n rm_size = len(data) % batch_size\n x, y = data[:-rm_size, 0], data[:-rm_size, 1]\n if use_cuda:\n x = x.view(-1, batch_size).cuda()\n else:\n x = x.view(-1, batch_size)\n y = y.view(-1, batch_size)\n return x, y\n\nx, y = batchify(train_data, batch_size=256, use_cuda=True)\n\ndef train(x_train, y_train, num_epochs, use_cuda=False):\n loss_fn = mat_loss\n optimizer = optim.SGD(model.parameters(), lr=1e-2)\n scheduler = optim.lr_scheduler.StepLR(optimizer,\n step_size=10,\n gamma=0.5)\n for epoch in range(num_epochs):\n total_loss = 0\n for batch_idx in tqdm(range(x_train.shape[0])):\n x = x_train[batch_idx, :]\n y = y_train[batch_idx, :]\n model.zero_grad()\n log_prob = model(x)\n gt = one_hot(y)\n if use_cuda:\n gt = gt.cuda()\n loss = loss_fn(log_prob, gt)\n loss.backward()\n scheduler.step()\n total_loss += loss.data\n print(total_loss)\n torch.save(model, 'models/model_{}'.format(total_loss))\n print(\"Successfully Saved model_{}!\".format(total_loss))\n\ntrain(x, y, num_epochs=100, use_cuda=True)\n\n"
] |
[
[
"torch.nn.Linear",
"numpy.array",
"torch.optim.lr_scheduler.StepLR",
"torch.nn.Softmax",
"torch.norm",
"torch.LongTensor",
"pandas.read_csv",
"torch.nn.Embedding",
"torch.sum"
]
] |
arnakoguzhan/machine-learning
|
[
"c0df1d1e37d001af7ddc5ae06dd3eba0788d126f"
] |
[
"1-simple-linear-regression/slr_sklearn.py"
] |
[
"import numpy as np\nimport pandas as pd\nfrom sklearn.linear_model import LinearRegression\nimport matplotlib.pyplot as plt\n\n# Data preprocessing\ndata = pd.read_csv(\"RealEstate.csv\")\n\n# Converting Pandas dataframe to numpy array\nX = data.Size.values.reshape(-1, 1)\nY = data.Price.values.reshape(-1, 1)\n\nm = X.shape[0] # number of samples\n\n# Model Intialization\nreg = LinearRegression()\n\n# Data Fitting to LinearRegression Model\nreg = reg.fit(X, Y)\n\n# Printing coefficients\nprint(f\"Coefficients theta0 = {reg.intercept_}, theta1 = {reg.coef_} \")\n\n# Predicted Values\nY_pred = reg.predict(X)\n\n\n# Model Evaluation\ndef rmse(Y, Y_pred):\n rmse = np.sqrt(sum((Y - Y_pred) ** 2) / Y.shape[0])\n return rmse\n\n\ndef r2_score(Y, Y_pred):\n mean_y = np.mean(Y)\n ss_tot = sum((Y - mean_y) ** 2)\n ss_res = sum((Y - Y_pred) ** 2)\n r2 = 1 - (ss_res / ss_tot)\n return r2\n\n\n# Print Scores\nprint(\"RMSE = \", rmse(Y, Y_pred))\nprint(\"R2 Score = \", r2_score(Y, Y_pred))\n\n# Visualization\n# Ploting Line\nplt.plot(X, Y_pred, color='#c93e4e', label='Regression Line')\n# Ploting Scatter Points\nplt.scatter(X, Y, c='#54a774', label='Scatter Plot')\nplt.xlabel('Size')\nplt.ylabel('Price')\nplt.legend()\nplt.show()\n"
] |
[
[
"sklearn.linear_model.LinearRegression",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.legend",
"numpy.mean",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.scatter",
"pandas.read_csv"
]
] |
a-vasenin/scikit-learn-intelex
|
[
"b81f81098a7f9302c6a052a5d22ecd372682844d",
"b81f81098a7f9302c6a052a5d22ecd372682844d"
] |
[
"examples/daal4py/low_order_moms_streaming.py",
"onedal/svm/tests/test_svc.py"
] |
[
"#===============================================================================\n# Copyright 2014-2022 Intel Corporation\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# daal4py low order moments example for streaming on shared memory systems\n\nimport daal4py as d4p\nimport numpy as np\n\n# let's try to use pandas' fast csv reader\ntry:\n import pandas\n\n def read_csv(f, c, s=0, n=None, t=np.float64):\n return pandas.read_csv(f, usecols=c, delimiter=',', header=None,\n skiprows=s, nrows=n, dtype=t)\nexcept:\n # fall back to numpy genfromtxt\n def read_csv(f, c, s=0, n=np.iinfo(np.int64).max):\n a = np.genfromtxt(f, usecols=c, delimiter=',', skip_header=s, max_rows=n)\n if a.shape[0] == 0:\n raise Exception(\"done\")\n if a.ndim == 1:\n return a[:, np.newaxis]\n return a\n\n\ndef main(readcsv=read_csv, method='defaultDense'):\n # read data from file\n file = \"./data/batch/covcormoments_dense.csv\"\n\n # Configure a low order moments object for streaming\n algo = d4p.low_order_moments(streaming=True)\n\n chunk_size = 55\n lines_read = 0\n # read and feed chunk by chunk\n while True:\n # Read data in chunks\n try:\n data = readcsv(file, range(10), lines_read, chunk_size)\n except:\n break\n # Now feed chunk\n algo.compute(data)\n lines_read += data.shape[0]\n\n # All files are done, now finalize the computation\n result = algo.finalize()\n\n # result provides minimum, maximum, sum, sumSquares, sumSquaresCentered,\n # mean, secondOrderRawMoment, variance, standardDeviation, variation\n return result\n\n\nif __name__ == \"__main__\":\n res = main()\n # print results\n print(\"\\nMinimum:\\n\", res.minimum)\n print(\"\\nMaximum:\\n\", res.maximum)\n print(\"\\nSum:\\n\", res.sum)\n print(\"\\nSum of squares:\\n\", res.sumSquares)\n print(\"\\nSum of squared difference from the means:\\n\", res.sumSquaresCentered)\n print(\"\\nMean:\\n\", res.mean)\n print(\"\\nSecond order raw moment:\\n\", res.secondOrderRawMoment)\n print(\"\\nVariance:\\n\", res.variance)\n print(\"\\nStandard deviation:\\n\", res.standardDeviation)\n print(\"\\nVariation:\\n\", res.variation)\n print('All looks good!')\n",
"#===============================================================================\n# Copyright 2021-2022 Intel Corporation\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\nimport pytest\nimport numpy as np\nfrom numpy.testing import assert_array_equal, assert_array_almost_equal\n\nfrom onedal.svm import SVC\n\nfrom sklearn.utils.estimator_checks import check_estimator\nimport sklearn.utils.estimator_checks\nfrom sklearn import datasets\nfrom sklearn.metrics.pairwise import rbf_kernel\nfrom sklearn.datasets import make_blobs\nfrom sklearn.model_selection import train_test_split\n\nfrom onedal.tests.utils._device_selection import (get_queues,\n pass_if_not_implemented_for_gpu)\n\n\ndef _replace_and_save(md, fns, replacing_fn):\n saved = dict()\n for check_f in fns:\n try:\n fn = getattr(md, check_f)\n setattr(md, check_f, replacing_fn)\n saved[check_f] = fn\n except RuntimeError:\n pass\n return saved\n\n\ndef _restore_from_saved(md, saved_dict):\n for check_f in saved_dict:\n setattr(md, check_f, saved_dict[check_f])\n\n\ndef test_estimator():\n def dummy(*args, **kwargs):\n pass\n\n md = sklearn.utils.estimator_checks\n saved = _replace_and_save(md, [\n 'check_sample_weights_invariance', # Max absolute difference: 0.0008\n 'check_estimators_fit_returns_self', # ValueError: empty metadata\n 'check_classifiers_train', # assert y_pred.shape == (n_samples,)\n 'check_estimators_unfitted', # Call 'fit' with appropriate arguments\n ], dummy)\n check_estimator(SVC())\n _restore_from_saved(md, saved)\n\n\ndef _test_libsvm_parameters(queue, array_constr, dtype):\n X = array_constr([[-2, -1], [-1, -1], [-1, -2],\n [1, 1], [1, 2], [2, 1]], dtype=dtype)\n y = array_constr([1, 1, 1, 2, 2, 2], dtype=dtype)\n\n clf = SVC(kernel='linear').fit(X, y, queue=queue)\n assert_array_equal(clf.dual_coef_, [[-0.25, .25]])\n assert_array_equal(clf.support_, [1, 3])\n assert_array_equal(clf.support_vectors_, (X[1], X[3]))\n assert_array_equal(clf.intercept_, [0.])\n assert_array_equal(clf.predict(X), y)\n\n\n# TODO: investigate sporadic failures on GPU\n@pytest.mark.parametrize('queue', get_queues('host,cpu'))\n@pytest.mark.parametrize('array_constr', [np.array])\n@pytest.mark.parametrize('dtype', [np.float32, np.float64])\ndef test_libsvm_parameters(queue, array_constr, dtype):\n _test_libsvm_parameters(queue, array_constr, dtype)\n\n\n@pytest.mark.parametrize('queue', get_queues('cpu') + [\n pytest.param(get_queues('gpu'),\n marks=pytest.mark.xfail(\n reason=\"class weights are not implemented \"\n \"but the error is not raised\"))])\ndef test_class_weight(queue):\n X = np.array([[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]])\n y = np.array([1, 1, 1, 2, 2, 2])\n\n clf = SVC(class_weight={1: 0.1})\n clf.fit(X, y, queue=queue)\n assert_array_almost_equal(clf.predict(X, queue=queue), [2] * 6)\n\n\n# TODO: investigate sporadic failures on GPU\n@pytest.mark.parametrize('queue', get_queues('host,cpu'))\ndef test_sample_weight(queue):\n X = np.array([[-2, 0], [-1, -1], [0, -2], [0, 2], [1, 1], [2, 2]])\n y = np.array([1, 1, 1, 2, 2, 2])\n\n clf = SVC(kernel='linear')\n clf.fit(X, y, sample_weight=[1] * 6, queue=queue)\n assert_array_almost_equal(clf.intercept_, [0.0])\n\n\n@pytest.mark.parametrize('queue', get_queues())\ndef test_decision_function(queue):\n X = np.array([[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]], dtype=np.float32)\n Y = np.array([1, 1, 1, 2, 2, 2], dtype=np.float32)\n\n clf = SVC(kernel='rbf', gamma=1, decision_function_shape='ovo')\n clf.fit(X, Y, queue=queue)\n\n rbfs = rbf_kernel(X, clf.support_vectors_, gamma=clf.gamma)\n dec = np.dot(rbfs, clf.dual_coef_.T) + clf.intercept_\n assert_array_almost_equal(dec.ravel(), clf.decision_function(X, queue=queue))\n\n\n@pass_if_not_implemented_for_gpu(reason=\"multiclass svm is not implemented\")\n@pytest.mark.parametrize('queue', get_queues())\ndef test_iris(queue):\n iris = datasets.load_iris()\n clf = SVC(kernel='linear').fit(iris.data, iris.target, queue=queue)\n assert clf.score(iris.data, iris.target, queue=queue) > 0.9\n assert_array_equal(clf.classes_, np.sort(clf.classes_))\n\n\n@pass_if_not_implemented_for_gpu(reason=\"multiclass svm is not implemented\")\n@pytest.mark.parametrize('queue', get_queues())\ndef test_decision_function_shape(queue):\n X, y = make_blobs(n_samples=80, centers=5, random_state=0)\n X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)\n\n # check shape of ovo_decition_function=True\n clf = SVC(kernel='linear',\n decision_function_shape='ovo').fit(X_train, y_train, queue=queue)\n dec = clf.decision_function(X_train, queue=queue)\n assert dec.shape == (len(X_train), 10)\n\n with pytest.raises(ValueError, match=\"must be either 'ovr' or 'ovo'\"):\n SVC(decision_function_shape='bad').fit(X_train, y_train, queue=queue)\n\n\n@pass_if_not_implemented_for_gpu(reason=\"multiclass svm is not implemented\")\n@pytest.mark.parametrize('queue', get_queues())\ndef test_pickle(queue):\n iris = datasets.load_iris()\n clf = SVC(kernel='linear').fit(iris.data, iris.target, queue=queue)\n expected = clf.decision_function(iris.data, queue=queue)\n\n import pickle\n dump = pickle.dumps(clf)\n clf2 = pickle.loads(dump)\n\n assert type(clf2) == clf.__class__\n result = clf2.decision_function(iris.data, queue=queue)\n assert_array_equal(expected, result)\n\n\n@pass_if_not_implemented_for_gpu(reason=\"sigmoid kernel is not implemented\")\n@pytest.mark.parametrize('queue', get_queues('cpu') + [\n pytest.param(get_queues('gpu'),\n marks=pytest.mark.xfail(reason=\"raises Unimplemented error \"\n \"with inconsistent error message\"))])\n@pytest.mark.parametrize('dtype', [np.float32, np.float64])\ndef test_svc_sigmoid(queue, dtype):\n X_train = np.array([[-1, 2], [0, 0], [2, -1],\n [+1, +1], [+1, +2], [+2, +1]], dtype=dtype)\n X_test = np.array([[0, 2], [0.5, 0.5],\n [0.3, 0.1], [2, 0], [-1, -1]], dtype=dtype)\n y_train = np.array([1, 1, 1, 2, 2, 2], dtype=dtype)\n svc = SVC(kernel='sigmoid').fit(X_train, y_train, queue=queue)\n\n assert_array_equal(svc.dual_coef_, [[-1, -1, -1, 1, 1, 1]])\n assert_array_equal(svc.support_, [0, 1, 2, 3, 4, 5])\n assert_array_equal(svc.predict(X_test, queue=queue), [2, 2, 1, 2, 1])\n"
] |
[
[
"numpy.iinfo",
"pandas.read_csv",
"numpy.genfromtxt"
],
[
"numpy.array",
"numpy.dot",
"sklearn.datasets.make_blobs",
"numpy.testing.assert_array_equal",
"sklearn.metrics.pairwise.rbf_kernel",
"numpy.testing.assert_array_almost_equal",
"numpy.sort",
"sklearn.model_selection.train_test_split",
"sklearn.datasets.load_iris"
]
] |
m-naumann/corridor
|
[
"2acfdf5781d4fc107a32baf6ef372800a741d2aa"
] |
[
"python_api/scripts/main_circle_polar_transformation.py"
] |
[
"import random\nimport statistics\nimport numpy as np\nimport math\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Ellipse\nimport matplotlib.transforms as transforms\nimport corridor\n\n\ndef sample_polar_data(mean, covMat, n_samples=5000):\n r, phi = np.random.multivariate_normal(mean, covMat, n_samples).T\n r = abs(r)\n np.unwrap(phi)\n return np.stack((r, phi), axis=0)\n\n\ndef confidence_ellipse(ax, mean, cov_mat, n_std=3, facecolor='none', **kwargs):\n pearson = cov_mat[0, 1]/np.sqrt(cov_mat[0, 0] * cov_mat[1, 1])\n # Using a special case to obtain the eigenvalues of this\n # two-dimensional dataset.\n ell_radius_x = np.sqrt(1 + pearson)\n ell_radius_y = np.sqrt(1 - pearson)\n ellipse = Ellipse((0, 0), width=ell_radius_x * 2, height=ell_radius_y * 2,\n facecolor=facecolor, **kwargs)\n # Calculating the stdandard deviation of x from\n # the squareroot of the variance and multiplying\n # with the given number of standard deviations.\n scale_x = np.sqrt(cov_mat[0, 0]) * n_std\n mean_x = mean[0]\n\n # calculating the stdandard deviation of y ...\n scale_y = np.sqrt(cov_mat[1, 1]) * n_std\n mean_y = mean[1]\n\n transf = transforms.Affine2D() \\\n .rotate_deg(45) \\\n .scale(scale_x, scale_y) \\\n .translate(mean_x, mean_y)\n\n ellipse.set_transform(transf + ax.transData)\n return ax.add_patch(ellipse)\n\n\n# Standard deviation for error ellipses\nn_std = 2\n\n# Figure\nfig, (ax_init_polar, ax_cart, ax_polar) = plt.subplots(1, 3)\n\n# Initial velocity value and orientation\nradius = 10\nheading = 1 * math.pi / 4.0\n\nvar_radius = 0.5\nvar_heading = 1 * math.pi / 32.0\ncov_radHead = 0\n\n# Initial 2d p vector with normal distribution\ninitial_polar_mean = [radius, heading]\ninitial_polar_covMat = [\n [var_radius, cov_radHead], [cov_radHead, var_heading]]\n\n# Convert to cartesian and calculate new mean and cov\ninitial_polar_data = sample_polar_data(\n initial_polar_mean, initial_polar_covMat, n_samples=5000)\n\n# mean and covMat from data\npolar_mean_0 = np.mean(initial_polar_data, axis=1)\npolar_cov_0 = np.cov(initial_polar_data)\n\n# Initial subplot\nax_init_polar.plot(\n initial_polar_data[0, :], initial_polar_data[1, :], 'g.', alpha=0.3)\nax_init_polar.plot(polar_mean_0[0], polar_mean_0[1], 'ro')\nconfidence_ellipse(ax_init_polar, polar_mean_0, polar_cov_0,\n n_std, facecolor='none', zorder=10, edgecolor='r')\n\n# Monte Carlo Methode for polar to cartesian transformation\nx_list = []\ny_list = []\nfor i in range(np.size(initial_polar_data, 1)):\n result = corridor.polar_to_cartesian_2d(\n initial_polar_data[0, i], initial_polar_data[1, i])\n x_list.append(result[0])\n y_list.append(result[1])\n\n# mean and covMat from data\ncart_data = np.stack((x_list, y_list), axis=0)\ncart_mean = np.mean(cart_data, axis=1)\ncart_cov = np.cov(cart_data)\n\nax_cart.plot(x_list, y_list, 'g.', alpha=0.3)\nax_cart.plot(cart_mean[0], cart_mean[1], 'ro')\nconfidence_ellipse(ax_cart, cart_mean, cart_cov,\n n_std, facecolor='none', zorder=10, edgecolor='r')\n\n# Monte Carlo Methode for cartesian to polar transformation\nr_list = []\nphi_list = []\nfor i in range(np.size(cart_data, 1)):\n result = corridor.cartesian_to_polar_2d(\n cart_data[0, i], cart_data[1, i])\n r_list.append(result[0])\n phi_list.append(result[1])\n\n# mean and covMat from data\npolar_data = np.stack((r_list, phi_list), axis=0)\npolar_mean = np.mean(polar_data, axis=1)\npolar_cov = np.cov(polar_data)\n\nax_polar.plot(r_list, phi_list, 'g.', alpha=0.3)\nax_polar.plot(polar_mean[0], polar_mean[1], 'ro')\nconfidence_ellipse(ax_polar, polar_mean, polar_cov,\n n_std, facecolor='none', zorder=10, edgecolor='r')\n\n# Unscented tranformation from cartesian to polar\ncart_state = corridor.FlatCartesianPositionAndCovMat2D()\ncart_state.x = cart_mean[0]\ncart_state.y = cart_mean[1]\ncart_state.var_x = cart_cov[0, 0]\ncart_state.var_y = cart_cov[1, 1]\ncart_state.cov_xy = cart_cov[1, 0]\n\npolar_state = corridor.ut_cartesian_to_polar_2d(cart_state)\n\n# Create mean and cov mat\nut_polar_mean = np.array([polar_state.r, polar_state.phi])\nut_polar_cov = np.array([[polar_state.var_r, polar_state.cov_rphi], [\n polar_state.cov_rphi, polar_state.var_phi]])\n\nax_polar.plot(ut_polar_mean[0], ut_polar_mean[1], 'bo')\nconfidence_ellipse(ax_polar, ut_polar_mean, ut_polar_cov,\n n_std, facecolor='none', zorder=10, edgecolor='b', linewidth=2)\n\nax_cart.axis('equal')\n\nplt.show()\n"
] |
[
[
"numpy.array",
"numpy.cov",
"numpy.mean",
"matplotlib.pyplot.subplots",
"numpy.unwrap",
"matplotlib.patches.Ellipse",
"numpy.stack",
"numpy.random.multivariate_normal",
"numpy.sqrt",
"numpy.size",
"matplotlib.pyplot.show",
"matplotlib.transforms.Affine2D"
]
] |
nikosavola/cirq-on-iqm
|
[
"990bb1f3629aaa5a8af14302335ec283dfe4eae1"
] |
[
"examples/demo_common.py"
] |
[
"# Copyright 2020–2021 Cirq on IQM developers\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\"\"\"\nDemonstrates transforming a quantum circuit into the native gateset and connectivity of a given\nIQM device, optimizing it, and then executing it on a simulator.\n\"\"\"\nimport cirq\nimport numpy as np\n\nnp.set_printoptions(precision=3)\n\n\ndef demo(device, circuit_original, do_measure, *, use_qsim=False):\n \"\"\"Tranform the given circuit to a form the given device accepts, then simulate it.\n\n Args:\n device (IQMDevice): device on which to execute the quantum circuit\n circuit_original (cirq.Circuit): quantum circuit\n do_measure (bool): Iff True, ``circuit_original`` contains measurements, in which case the\n state after the circuit is not simulated, just the measurement results.\n use_qsim (bool): Iff True, use the ``qsim`` circuit simulator instead of the Cirq builtin simulator.\n \"\"\"\n print('Source circuit:')\n print(circuit_original)\n print()\n\n # construct a new quantum circuit respecting Adonis' properties\n circuit_transformed = device.map_circuit(circuit_original)\n print('Decomposed circuit:')\n print(circuit_transformed)\n print()\n\n # clean up the circuit (in place)\n device.simplify_circuit(circuit_transformed)\n print('Simplified circuit:')\n print(circuit_transformed)\n print()\n\n # Initialize a ket-based simulator for evaluating the circuit\n if use_qsim:\n import qsimcirq\n sim = qsimcirq.QSimSimulator()\n print('Using qsim.')\n else:\n sim = cirq.Simulator()\n\n # sim.run only returns the measured values over a number of repetitions of the circuit, like a hardware QPU would\n # sim.simulate returns also the simulated state of the register\n\n if not do_measure:\n result_transformed = sim.simulate(circuit_transformed) # qubit_order=...\n print('\\nSimulate the transformed circuit:')\n print('result =', result_transformed)\n print('probabilities =', np.abs(result_transformed.state_vector()) ** 2)\n\n result_original = sim.simulate(circuit_original) # qubit_order=...\n print('\\nSimulate the original circuit:')\n print('result =', result_original)\n overlap = np.abs(np.vdot(result_original.state_vector(), result_transformed.state_vector()))\n print('\\noverlap = |<original|transformed>| =', overlap)\n assert np.abs(overlap - 1.0) < 1e-6, 'Circuits are not equivalent!'\n else:\n samples_transformed = sim.run(circuit_transformed, repetitions=10000)\n samples_original = sim.run(circuit_original, repetitions=10000)\n\n # Print a histogram of results\n # the counter interprets a multiqubit measurement result as a bit string, and converts it into an integer\n key = 'meas_1'\n print('\\nSample the transformed circuit:')\n print(samples_transformed.histogram(key=key))\n print('\\nSample the original circuit:')\n print(samples_original.histogram(key=key))\n"
] |
[
[
"numpy.set_printoptions",
"numpy.abs"
]
] |
LiWentomng/boxlevelset
|
[
"8cc40bf6ae4a343c482c676c72259cc12c29d31c"
] |
[
"mmdet/models/losses/chamfer_loss.py"
] |
[
"import torch\nimport torch.nn as nn\n\nfrom mmdet.ops.chamfer_2d import Chamfer2D\nfrom ..registry import LOSSES\n\n\n@LOSSES.register_module\nclass ChamferLoss2D(nn.Module):\n def __init__(self, use_cuda=True, loss_weight=1.0, eps=1e-12):\n super(ChamferLoss2D, self).__init__()\n self.use_cuda = use_cuda\n self.loss_weight = loss_weight\n self.eps = eps\n\n def forward(self, point_set_1, point_set_2):\n \"\"\"\n Computation of optimal transport distance via sinkhorn algorithm.\n - Input:\n - point_set_1:\ttorch.Tensor\t[..., num_points_1, point_dim] e.g. [bs, h, w, 1000, 2]; [bs, 1000, 2]; [1000, 2]\n - point_set_2:\ttorch.Tensor\t[..., num_points_2, point_dim]\n (the dimensions of point_set_2 except the last two should be the same as point_set_1)\n - Output:\n - distance:\ttorch.Tensor\t[...] e.g. [bs, h, w]; [bs]; []\n \"\"\"\n chamfer = Chamfer2D() if self.use_cuda else ChamferDistancePytorch()\n\n assert point_set_1.dim() == point_set_2.dim()\n assert point_set_1.shape[-1] == point_set_2.shape[-1]\n if point_set_1.dim() <= 3:\n if self.use_cuda:\n\n dist1, dist2, _, _ = chamfer(point_set_1, point_set_2)\n\n dist1 = torch.sqrt(torch.clamp(dist1, self.eps))\n dist2 = torch.sqrt(torch.clamp(dist2, self.eps))\n\n dist = (dist1.mean(-1) + dist2.mean(-1)) / 2.0\n\n\n else:\n dist = chamfer(point_set_1, point_set_2)\n print('no_cuda_edge_loss')\n\n return dist * self.loss_weight\n\n\n# Adapted from https://github.com/dfdazac/wassdistance\nclass ChamferDistancePytorch(nn.Module):\n r\"\"\"\n Shape:\n - Input: :math:`(N, P_1, D_1)`, :math:`(N, P_2, D_2)`\n - Output: :math:`(N)` or :math:`()`, depending on `reduction`\n \"\"\"\n\n def __init__(self, reduction='none'):\n super(ChamferDistancePytorch, self).__init__()\n self.reduction = reduction\n\n def forward(self, x, y):\n if x.shape[0] == 0:\n return x.sum()\n # The Sinkhorn algorithm takes as input three variables :\n C = self._cost_matrix(x, y) # Wasserstein cost function\n\n # compute chamfer loss\n min_x2y, _ = C.min(-1)\n d1 = min_x2y.mean(-1)\n min_y2x, _ = C.min(-2)\n d2 = min_y2x.mean(-1)\n cost = (d1 + d2) / 2.0\n\n if self.reduction == 'mean':\n cost = cost.mean()\n elif self.reduction == 'sum':\n cost = cost.sum()\n return cost\n\n @staticmethod\n def _cost_matrix(x, y, p=2):\n \"Returns the matrix of $|x_i-y_j|^p$.\"\n x_col = x.unsqueeze(-2)\n y_lin = y.unsqueeze(-3)\n C = torch.norm(x_col - y_lin, 2, -1)\n return C\n"
] |
[
[
"torch.norm",
"torch.clamp"
]
] |
Alymostafa/torch-cam
|
[
"3f30f0db90fba1b921dbe71e979001c954d245da"
] |
[
"scripts/cam_example.py"
] |
[
"#!usr/bin/python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nCAM visualization\n\"\"\"\n\nimport argparse\nfrom io import BytesIO\n\nimport matplotlib.pyplot as plt\nimport requests\nfrom PIL import Image\nimport torch\nfrom torchvision import models\nfrom torchvision.transforms.functional import normalize, resize, to_tensor, to_pil_image\n\nfrom torchcam.cams import CAM, GradCAM, GradCAMpp, SmoothGradCAMpp, ScoreCAM, SSCAM, ISSCAM\nfrom torchcam.utils import overlay_mask\n\nVGG_CONFIG = {_vgg: dict(input_layer='features', conv_layer='features')\n for _vgg in models.vgg.__dict__.keys()}\n\nRESNET_CONFIG = {_resnet: dict(input_layer='conv1', conv_layer='layer4', fc_layer='fc')\n for _resnet in models.resnet.__dict__.keys()}\n\nDENSENET_CONFIG = {_densenet: dict(input_layer='features', conv_layer='features', fc_layer='classifier')\n for _densenet in models.densenet.__dict__.keys()}\n\nMODEL_CONFIG = {\n **VGG_CONFIG, **RESNET_CONFIG, **DENSENET_CONFIG,\n 'mobilenet_v2': dict(input_layer='features', conv_layer='features')\n}\n\n\ndef main(args):\n\n if args.device is None:\n args.device = 'cuda:0' if torch.cuda.is_available() else 'cpu'\n\n device = torch.device(args.device)\n\n # Pretrained imagenet model\n model = models.__dict__[args.model](pretrained=True).eval().to(device=device)\n conv_layer = MODEL_CONFIG[args.model]['conv_layer']\n input_layer = MODEL_CONFIG[args.model]['input_layer']\n fc_layer = MODEL_CONFIG[args.model]['fc_layer']\n\n # Image\n if args.img.startswith('http'):\n img_path = BytesIO(requests.get(args.img).content)\n pil_img = Image.open(img_path, mode='r').convert('RGB')\n\n # Preprocess image\n img_tensor = normalize(to_tensor(resize(pil_img, (224, 224))),\n [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]).to(device=device)\n\n # Hook the corresponding layer in the model\n cam_extractors = [CAM(model, conv_layer, fc_layer), GradCAM(model, conv_layer),\n GradCAMpp(model, conv_layer), SmoothGradCAMpp(model, conv_layer, input_layer),\n ScoreCAM(model, conv_layer, input_layer), SSCAM(model, conv_layer, input_layer),\n ISSCAM(model, conv_layer, input_layer)]\n\n # Don't trigger all hooks\n for extractor in cam_extractors:\n extractor._hooks_enabled = False\n\n fig, axes = plt.subplots(1, len(cam_extractors), figsize=(7, 2))\n for idx, extractor in enumerate(cam_extractors):\n extractor._hooks_enabled = True\n model.zero_grad()\n scores = model(img_tensor.unsqueeze(0))\n\n # Select the class index\n class_idx = scores.squeeze(0).argmax().item() if args.class_idx is None else args.class_idx\n\n # Use the hooked data to compute activation map\n activation_map = extractor(class_idx, scores).cpu()\n # Clean data\n extractor.clear_hooks()\n extractor._hooks_enabled = False\n # Convert it to PIL image\n # The indexing below means first image in batch\n heatmap = to_pil_image(activation_map, mode='F')\n # Plot the result\n result = overlay_mask(pil_img, heatmap)\n\n axes[idx].imshow(result)\n axes[idx].axis('off')\n axes[idx].set_title(extractor.__class__.__name__, size=8)\n\n plt.tight_layout()\n if args.savefig:\n plt.savefig(args.savefig, dpi=200, transparent=True, bbox_inches='tight', pad_inches=0)\n plt.show()\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Saliency Map comparison',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument(\"--model\", type=str, default='resnet18', help=\"The name of your training\")\n parser.add_argument(\"--img\", type=str,\n default='https://www.woopets.fr/assets/races/000/066/big-portrait/border-collie.jpg',\n help=\"The image to extract CAM from\")\n parser.add_argument(\"--class-idx\", type=int, default=232, help='Index of the class to inspect')\n parser.add_argument(\"--device\", type=str, default=None, help='Default device to perform computation on')\n parser.add_argument(\"--savefig\", type=str, default=None, help=\"Path to save figure\")\n args = parser.parse_args()\n\n main(args)\n"
] |
[
[
"torch.device",
"matplotlib.pyplot.savefig",
"torch.cuda.is_available",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.show"
]
] |
ds7788/hello-world
|
[
"f16466f4d4de8cd412771415a361738ba020e568"
] |
[
"pymc3/examples/gelman_schools.py"
] |
[
"from pymc3 import HalfCauchy, Normal, sample, Model, loo\nimport numpy as np\n\n'''Original Stan model\n\ndata {\n int<lower=0> J; // number of schools \n real y[J]; // estimated treatment effects\n real<lower=0> sigma[J]; // s.e. of effect estimates \n}\nparameters {\n real mu; \n real<lower=0> tau;\n real eta[J];\n}\ntransformed parameters {\n real theta[J];\n for (j in 1:J)\n theta[j] <- mu + tau * eta[j];\n}\nmodel {\n eta ~ normal(0, 1);\n y ~ normal(theta, sigma);\n}\n'''\n\nJ = 8\ny = np.array([28, 8, -3, 7, -1, 1, 18, 12])\nsigma = np.array([15, 10, 16, 11, 9, 11, 10, 18])\n\nwith Model() as schools:\n \n eta = Normal('eta', 0, 1, shape=J)\n mu = Normal('mu', 0, sd=1e6)\n tau = HalfCauchy('tau', 25)\n \n theta = mu + tau*eta\n \n obs = Normal('obs', theta, sd=sigma, observed=y)\n \ndef run(n=1000): \n if n == \"short\":\n n = 50\n with schools:\n tr = sample(n)\n l = loo(tr)\n\nif __name__ == '__main__':\n run()"
] |
[
[
"numpy.array"
]
] |
rajeevsrao/onnx
|
[
"355a4954ea4e5836a5e943589509951c44feb6b4",
"781545783a4e2bbbda48fc64318fb2c6d8bbb3cc"
] |
[
"onnx/backend/test/case/node/asinh.py",
"onnx/backend/test/case/node/sum.py"
] |
[
"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport numpy as np # type: ignore\n\nimport onnx\nfrom ..base import Base\nfrom . import expect\n\n\nclass Asinh(Base):\n\n @staticmethod\n def export(): # type: () -> None\n node = onnx.helper.make_node(\n 'Asinh',\n inputs=['x'],\n outputs=['y'],\n )\n\n x = np.array([-1, 0, 1]).astype(np.float32)\n y = np.arcsinh(x) # expected output [-0.88137358, 0., 0.88137358]\n expect(node, inputs=[x], outputs=[y],\n name='test_asinh_example')\n\n x = np.random.randn(3, 4, 5).astype(np.float32)\n y = np.arcsinh(x)\n expect(node, inputs=[x], outputs=[y],\n name='test_asinh')\n",
"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport numpy as np # type: ignore\n\nimport onnx\nfrom ..base import Base\nfrom . import expect\n\n\nclass Sum(Base):\n\n @staticmethod\n def export(): # type: () -> None\n data_0 = np.array([3, 0, 2]).astype(np.float32)\n data_1 = np.array([1, 3, 4]).astype(np.float32)\n data_2 = np.array([2, 6, 6]).astype(np.float32)\n result = np.array([6, 9, 12]).astype(np.float32)\n node = onnx.helper.make_node(\n 'Sum',\n inputs=['data_0', 'data_1', 'data_2'],\n outputs=['result'],\n )\n expect(node, inputs=[data_0, data_1, data_2], outputs=[result],\n name='test_sum_example')\n\n node = onnx.helper.make_node(\n 'Sum',\n inputs=['data_0'],\n outputs=['result'],\n )\n expect(node, inputs=[data_0], outputs=[data_0],\n name='test_sum_one_input')\n\n result = np.add(data_0, data_1)\n node = onnx.helper.make_node(\n 'Sum',\n inputs=['data_0', 'data_1'],\n outputs=['result'],\n )\n expect(node, inputs=[data_0, data_1], outputs=[result],\n name='test_sum_two_inputs')\n"
] |
[
[
"numpy.array",
"numpy.random.randn",
"numpy.arcsinh"
],
[
"numpy.array",
"numpy.add"
]
] |
JALVARADORUIZ/DataAnalytic-PJUD
|
[
"cd063efd619eca3b7bf583f1fb00383f6f774818"
] |
[
"src/pjud/data/jurisdicciones.py"
] |
[
"import re\nimport os\nimport pandas as pd\nimport numpy as np\nimport click\n\nfrom tqdm import tqdm\nfrom unicodedata import normalize\n\nfrom pjud import data\n\ndef load_article_cot(article: str, src_path = './data/raw/cot'):\n tqdm.pandas()\n with open(f'{src_path}/{article}.txt', 'r') as file:\n contenido = ''\n for line in file.readlines():\n contenido += line\n return contenido\n\ndef garantia():\n regex_jg=r\"(?:(?P<Region>^[\\w \\']+)\\:\\n\\n)|(?P<JG>^[\\w. \\-]+)\\,\\scon\\s(?P<Jueces>[\\w.\\-]+)[a-z\\-\\s\\,]+(?P<Competencia>\\.|\\s[\\w. \\-\\,]+)\"\n matches = re.findall(regex_jg, load_article_cot('Juzgados_Garantia'), re.MULTILINE)\n\n data_jg = []\n\n for item in range(0, len(matches)):\n if matches[item][0] != '':\n region = matches[item][0].upper()\n else:\n if matches[item][1] != '':\n ciudad = matches[item][1].upper()\n if ciudad.find(\"JUZGADO\") != -1:\n juzgado = ciudad\n\n else:\n juzgado = f\"JUZGADO DE GARANTIA {ciudad}\"\n\n if matches[item][2] != '':\n cantidad_jueces = data.cleandata.transforma_numero(matches[item][2])\n\n if matches[item][3] == '.':\n competencia = ciudad\n\n else:\n if matches[item][3] != '':\n competencia = matches[item][3].upper()\n\n competencia = competencia.replace(\" Y \", \",\")\n competencia = competencia.replace(\" E \", \",\")\n competencia = competencia.replace(\".\", \"\")\n\n comunas = competencia.split(\",\")\n\n for comuna in comunas:\n data_jg.append([region, juzgado, ciudad, cantidad_jueces, comuna.strip(), 'GARANTIA'])\n\n df_juzgados_garantia = pd.DataFrame(data_jg,\n columns=['REGION', 'TRIBUNAL', 'ASIENTO', 'JUECES', 'COMUNA', 'TIPO JUZGADO'])\n\n # Elimino tildes de las columnas object\n\n cols = df_juzgados_garantia.select_dtypes(include = [\"object\"]).columns\n df_juzgados_garantia[cols] = df_juzgados_garantia[cols].progress_apply(data.cleandata.elimina_tilde)\n\n data.save_feather(df_juzgados_garantia, 'generates_JuzgadosGarantia')\n click.echo('Generado archivo Feather. Proceso Terminado')\n\ndef top():\n # Se construye una expresion regular para captar una lista con la información que se desea procesar, y así generar un dataframe.\n regex_top=r\"(?:(?P<Region>^[\\w \\']+)\\:\\n)|(?P<JG>^[\\w. \\-]+)\\,\\scon\\s(?P<Jueces>[\\w.\\-]+)[a-z\\-\\s\\,]+(?P<Competencia>\\.|\\s[\\w. \\-\\,\\']+)\"\n matches = re.findall(regex_top, load_article_cot('Tribunales_orales'), re.MULTILINE)\n\n data_top=[]\n\n for item in range(0,len(matches)):\n if matches[item][0] != '':\n region = matches[item][0].upper()\n else: \n if matches[item][1] != '':\n ciudad = matches[item][1].upper() \n if ciudad.find(\"TRIBUNAL\") != -1:\n juzgado = ciudad\n \n else:\n juzgado = f\"TRIBUNAL DE JUICIO ORAL EN LO PENAL {ciudad}\"\n\n if matches[item][2] != '':\n cantidad_jueces = data.cleandata.transforma_numero(matches[item][2])\n \n if matches[item][3] == '.':\n competencia = ciudad\n \n else: \n if matches[item][3] != '':\n competencia = matches[item][3].upper()\n \n competencia = competencia.replace(\" Y \",\",\")\n competencia = competencia.replace(\" E \",\",\")\n competencia = competencia.replace(\".\",\"\")\n \n comunas = competencia.split(\",\")\n \n for comuna in comunas:\n data_top.append([region,juzgado,ciudad,cantidad_jueces,comuna.strip(),'ORAL'])\n \n df_tribunal_oral = pd.DataFrame(data_top, columns = ['REGION','TRIBUNAL','ASIENTO','JUECES','COMUNA','TIPO JUZGADO'])\n\n df_tribunal_oral['JUECES'] = df_tribunal_oral['JUECES'].fillna(0).astype(np.int8)\n\n click.echo('Eliminando tildes')\n cols = df_tribunal_oral.select_dtypes(include = [\"object\"]).columns\n df_tribunal_oral[cols] = df_tribunal_oral[cols].progress_apply(data.cleandata.elimina_tilde)\n\n data.save_feather(df_tribunal_oral,'generates_TribunalOral')\n click.echo('Generado archivo Feather. Proceso Terminado')\n\ndef juzgados_letras():\n regex_jl = r\"(?:Art.\\s[0-9\\s(bis|ter|quáter)]+\\.\\s[\\w\\s]+\\,(?P<Region>[\\w\\s\\']+)\\,[\\w\\s]+:\\s+)|(?:(?:^[A]\\.\\-\\s[\\w\\s]+:\\s+)(?:(?:[\\w\\s\\,]+[.|\\;])+))|(?:(?:[\\-\\s][\\w\\s]+\\:\\s*)|(?:\\s*(?:(?P<cant_juzg>[\\w]+)(?:\\s[J|j][a-z\\,\\s]+)(?P<JG>[\\w\\s]+)[\\,|y]\\s[\\w]+\\s(?P<Jueces>[\\w]+)\\s[a-z\\s\\,]+(?P<Competencia>[\\w|\\s|\\,]+)[\\;|\\.]$)\\s*))\"\n matches = re.findall(regex_jl, load_article_cot('juzgadoletras'), re.MULTILINE)\n\n data_jl = []\n\n for item in range(0,len(matches)):\n\n if matches[item][0] != '':\n region = f\"REGION{matches[item][0].upper()}\"\n else: \n if matches[item][2] != '':\n ciudad = matches[item][2].upper() \n juzgado = f\"JUZGADO DE LETRAS Y GARANTIA {ciudad}\"\n\n if matches[item][3] != '':\n if matches[item][3] == 'competencia':\n cantidad_jueces = 1\n else:\n cantidad_jueces = data.cleandata.transforma_numero(matches[item][3])\n \n if matches[item][4] != '':\n if matches[item][4] == 'a':\n competencia = ciudad\n \n else: \n if matches[item][4] != '':\n competencia = matches[item][4].upper()\n\n competencia = competencia.replace(\" Y \",\",\")\n competencia = competencia.replace(\" E \",\",\")\n competencia = competencia.replace(\".\",\"\")\n \n comunas = competencia.split(\",\")\n \n for comuna in comunas:\n data_jl.append([region,juzgado,ciudad,cantidad_jueces,comuna.strip(),'LETRAS Y GARANTIA'])\n\n\n df_juzgados_letras = pd.DataFrame(data_jl,columns = ['REGION','TRIBUNAL','ASIENTO','JUECES','COMUNA','TIPO JUZGADO'])\n\n click.echo('Elimando tildes')\n cols = df_juzgados_letras.select_dtypes(include = [\"object\"]).columns\n df_juzgados_letras[cols] = df_juzgados_letras[cols].progress_apply(data.cleandata.elimina_tilde)\n\n data.save_feather(df_juzgados_letras, 'generates_JuzgadosLetras')\n click.echo('Generado archivo Feather. Proceso Terminado')\n\ndef extraccion_comunas(filtro, df):\n add_comunas = []\n\n for indice in filtro.index:\n region = filtro[\"REGION\"][indice]\n tribunal = filtro[\"TRIBUNAL\"][indice]\n asiento = filtro[\"ASIENTO\"][indice]\n jueces = filtro[\"JUECES\"][indice]\n tipo_juzgado = filtro[\"TIPO JUZGADO\"][indice]\n \n provincia = filtro[\"COMUNA\"][indice].split(\"PROVINCIA DE \")\n comunas_de_provincias = df.loc[df[\"Nombre Provincia\"] == provincia[1],\"Nombre Comuna\"]\n \n for var_comuna in range(len(comunas_de_provincias)):\n comuna = comunas_de_provincias.values[var_comuna]\n add_comunas.append([region,tribunal,asiento,jueces,comuna,tipo_juzgado])\n \n return(add_comunas)\n\ndef juzgados_penales(path_pjud = \"data/interim/pjud\", path_subdere = \"data/interim/subdere\"):\n\n tqdm.pandas()\n df_juzgados_garantia = pd.read_feather(f\"{path_pjud}/generates_JuzgadosGarantia.feather\")\n df_tribunal_oral = pd.read_feather(f\"{path_pjud}/generates_TribunalOral.feather\")\n df_juzgados_letras = pd.read_feather(f\"{path_pjud}/generates_JuzgadosLetras.feather\")\n df_provincias = pd.read_feather(f\"{path_subdere}/generates_Provincias.feather\")\n\n # Existen dos provincias en el listado.\n filtro_provincia_top = df_tribunal_oral[df_tribunal_oral['COMUNA'].str.contains(\"PROVINCIA\", case = False)]\n df_tribunal_oral.drop(filtro_provincia_top.index, axis = 0, inplace = True)\n\n # Analizo Dataframe , ya que acá estan los Juzgados de Letras con Competencia Común, y en algunos casos estos pueden\n # No corresponder a Juzgados Penales. Para saber eso, debo verificar que no existan JG en esas comunas, en el caso de \n # existir debo eliminar registro.\n\n filtro_provincia_jl = df_juzgados_letras[df_juzgados_letras['COMUNA'].str.contains(\"PROVINCIA\", case = False)]\n df_juzgados_letras.drop(filtro_provincia_jl.index, axis = 0, inplace = True)\n\n filtro_provincia_jl.loc[229,\"COMUNA\"] = 'PROVINCIA DE MELIPILLA'\n filtro_provincia_jl.drop(176, inplace = True)\n\n df_nuevas_comunas_jl = pd.DataFrame(extraccion_comunas(filtro_provincia_jl, df_provincias),\n columns = ['REGION','TRIBUNAL','ASIENTO','JUECES','COMUNA','TIPO JUZGADO']) \n\n df_juzgados_letras = df_juzgados_letras.append(df_nuevas_comunas_jl, ignore_index = True)\n\n # Exploro las provincias y extraigo las comunas -> Caso Tribunales orales\n\n df_nuevas_comunas_top = pd.DataFrame(extraccion_comunas(filtro_provincia_top, df_provincias),\n columns = ['REGION','TRIBUNAL','ASIENTO','JUECES','COMUNA','TIPO JUZGADO']) \n\n df_tribunal_oral = df_tribunal_oral.append(df_nuevas_comunas_top, ignore_index = True)\n\n # Acá debo eliminar los juzgados de letras que estan cubiertos por la competencia de un juzgado de Garantía\n\n juzgados_garantias = df_juzgados_garantia['COMUNA'].unique().tolist()\n drop_jl = []\n\n for jl in df_juzgados_letras.index:\n if df_juzgados_letras['COMUNA'][jl] in juzgados_garantias:\n drop_jl.append(jl)\n\n df_juzgados_letras.drop(drop_jl, axis = 0, inplace = True)\n\n df_juzgados_penales = pd.concat([df_juzgados_garantia,df_juzgados_letras], join = \"inner\")\n df_juzgados_penales.reset_index(inplace = True)\n\n # El caso de Alto Hospicio es particular, no aparece en el COT, ya que fue parte de una actualizacion \n # de la Ley y fue sumado como Juzgado especial. Debemos agregarlo a Juzgados Penales\n\n alto_hospicio = [('REGION DE TARAPACA','JUZGADO DE LETRAS Y GARANTIA ALTO HOSPICIO','ALTO HOSPICIO','4',\n 'ALTO HOSPICIO','LETRAS Y GARANTIA')]\n\n df_alto_hospicio = pd.DataFrame(alto_hospicio, columns = ['REGION','TRIBUNAL','ASIENTO','JUECES','COMUNA','TIPO JUZGADO']) \n df_juzgados_penales = pd.concat([df_juzgados_penales, df_alto_hospicio], join = \"inner\")\n df_juzgados_penales['JUECES'] = df_juzgados_penales['JUECES'].fillna(0).astype(np.int8)\n df_juzgados_penales.reset_index(drop = True)\n\n # Transformo las variables para que queden igual en los 3 datasets\n click.echo('Tranformación ... Separando regiones')\n df_juzgados_penales['REGION'] = df_juzgados_penales['REGION'].progress_apply(data.cleandata.separa_regiones)\n df_tribunal_oral['REGION'] = df_tribunal_oral['REGION'].progress_apply(data.cleandata.separa_regiones)\n\n click.echo('Tranformación ... Creando asiento de tribunales')\n df_juzgados_penales['ASIENTO'] = df_juzgados_penales['ASIENTO'].progress_apply(data.cleandata.transforma_asiento)\n df_tribunal_oral['ASIENTO'] = df_tribunal_oral['ASIENTO'].progress_apply(data.cleandata.transforma_asiento)\n\n # Transformo valores de Regiones a similar a BBDD Pjud\n\n regiones_subdere = df_provincias[\"Nombre Región\"].unique()\n regiones_top = df_tribunal_oral[\"REGION\"].unique()\n\n for region in regiones_subdere:\n for region_top in regiones_top:\n if region_top.find(region) != -1:\n df_provincias['Nombre Región'] = df_provincias['Nombre Región'].replace(region, region_top) \n\n click.echo('Tranformación ... Separando regiones') \n df_provincias['Nombre Región'] = df_provincias['Nombre Región'].progress_apply(data.cleandata.separa_regiones)\n\n # Creare dataframe con tribunales ORales- Garantia y Letras \n\n top = df_tribunal_oral[['REGION','TRIBUNAL','ASIENTO','COMUNA','JUECES','TIPO JUZGADO']] \n jg = df_juzgados_penales[['REGION','TRIBUNAL','ASIENTO','COMUNA','JUECES','TIPO JUZGADO']] \n\n df_listado_tribunales = pd.concat([top, jg], join = \"inner\")\n\n click.echo('Tranformación ... Cambiando Nombres') \n df_tribunal_oral['TRIBUNAL'] = df_tribunal_oral['TRIBUNAL'].progress_apply(data.cleandata.cambio_nombre_juzgados)\n df_juzgados_penales['TRIBUNAL'] = df_juzgados_penales['TRIBUNAL'].progress_apply(data.cleandata.cambio_nombre_juzgados)\n df_listado_tribunales['TRIBUNAL'] = df_listado_tribunales['TRIBUNAL'].progress_apply(data.cleandata.cambio_nombre_juzgados)\n\n data.save_feather(df_provincias, 'generates_DataRegiones', path='data/processed/subdere')\n data.save_feather(df_listado_tribunales, 'generates_ListadoTribunales', path='data/processed/pjud')\n data.save_feather(df_tribunal_oral, 'generates_TribunalesOrales', path='data/processed/pjud')\n data.save_feather(df_juzgados_penales, 'generates_JuzgadosPenales', path='data/processed/pjud')\n click.echo('Generado archivo Feather. Proceso Terminado')"
] |
[
[
"pandas.concat",
"pandas.DataFrame",
"pandas.read_feather"
]
] |
mkollo/chiminey
|
[
"a31f41d94c3725abef879269b64eb63f4f21f213"
] |
[
"slurm_filter.py"
] |
[
"# ___ _ _ ___ __ __ _____ __\n# / __| || |_ _| \\/ | _ \\ \\ / /\n# | (__| __ || || |\\/| | _/\\ V / \n# \\___|_||_|___|_| |_|_| |_| \n# \n# Copyright (c) 2020 Mihaly Kollo. All rights reserved.\n# \n# This work is licensed under the terms of the MIT license. \n# For a copy, see <https://opensource.org/licenses/MIT>. \n\nimport mpi4py\nmpi4py.rc.recv_mprobe = False\nmpi4py.rc.threads = False\nfrom mpi4py import MPI\n\nimport numpy as np\nimport sys\nimport h5py\nimport time\nimport os\nimport json\n\nfrom scipy.signal import butter\nimport sys\nsys.path.append('/home/camp/warnert')\nimport cupy\nimport cusignal\n\nfrom chimpy.ramfile import RamFile\n\nMASTER_PROCESS = 0\nSETUP_TAG = 71\nAMPS_TAG = 72\nDATA_TAG = 73\nRESULT_TAG = 74\nTEST_TAG = 76\nDIE_SIGNAL = -1\n\n# Load filter parameters\n\nwith open('params.json') as json_file:\n params = json.load(json_file)\n \nsample_chunk_size=params['sample_chunk_size']\nchannels=np.array(params['channels'])\nn_samples=params['n_samples']\norder=params['order']\nlow_cutoff=params['low_cutoff']\nhigh_cutoff=params['high_cutoff']\nscales=np.array(params['scales'])\nin_filepath=params['in_filepath']\nout_filepath=params['out_filepath']\nconnected_pixels=params['connected_pixels']\nram_copy=params['ram_copy']\n\n# Create dictionary of channel scales\nchannel_scales=dict(zip(channels,scales))\nn_channels=len(connected_pixels)\n\n# # Initialize MPI\ncomm = MPI.COMM_WORLD\nnproc = comm.Get_size()\niproc = comm.Get_rank()\ninode = MPI.Get_processor_name()\nstatus = MPI.Status()\n\n\n# Calculate filter\nsos = butter(order, [low_cutoff/10000, high_cutoff/10000], 'bandpass', output='sos')\n\nif iproc == MASTER_PROCESS:\n # Optionally save file into a tmpfs partition for processing\n if ram_copy:\n in_ramfile=RamFile(in_filepath, 'r')\n in_filepath=in_ramfile.ram_filepath\n out_ramfile=RamFile(out_filepath, 'w')\n out_filepath=out_ramfile.ram_filepath\n # Load input file\n in_fid = h5py.File(in_filepath, 'r')\n if n_samples==-1:\n n_samples=in_fid['sig'].shape[1]\n\n # Create output file\n out_fid=h5py.File(out_filepath, 'w')\n out_fid['mapping']=in_fid['mapping'][connected_in_mapping]\n in_fid.copy('/message_0', out_fid)\n in_fid.copy('/proc0', out_fid)\n in_fid.copy('/settings', out_fid)\n in_fid.copy('/time', out_fid)\n in_fid.copy('/version', out_fid)\n if 'bits' in in_fid.keys():\n in_fid.copy('/bits', out_fid)\n out_fid.create_dataset(\"sig\", (len(connected_pixels), n_samples), dtype='float32')\n\n # Create data chunks (channels and samples) for each MPI process\n in_channel_chunks=np.array_split(channels[connected_pixels], nproc-1)\n out_channel_chunks=np.array_split(list(range(n_channels)), nproc-1)\n n_sample_chunks=n_samples/sample_chunk_size\n sample_chunk_borders=np.hstack((np.arange(n_sample_chunks, dtype=int)*sample_chunk_size,n_samples))\n sample_chunks=dict(zip(np.arange(nproc-1),[np.array([sample_chunk_borders[i:i+2].copy() for i in range(len(sample_chunk_borders)-1)])]*(nproc-1)))\n # Dictionary for holding currently processed chunks for each process\n current_chunks=dict(zip(np.arange(nproc-1),[None]*(nproc-1)))\n n_total_chunks=sum([sample_chunks[i].shape[0] for i in np.arange(nproc-1)])\n n_remaining_chunks=n_total_chunks\n n_current_chunks=0\n\n # Master process main loop\n while (n_remaining_chunks+n_current_chunks)>0:\n # Checking for idle processes, and delegating chunks\n for i, _ in enumerate(current_chunks):\n if current_chunks[i] is None and sample_chunks[i].shape[0]>0:\n current_chunks[i]=sample_chunks[i][0]\n data_shape=(in_channel_chunks[i].shape[0], sample_chunk_size+current_chunks[i][1]-current_chunks[i][0])\n comm.send(data_shape, dest=i+1, tag=SETUP_TAG)\n comm.send([channel_scales[channel] for channel in in_channel_chunks[i]], dest=i+1, tag=AMPS_TAG)\n chunk=np.empty((in_channel_chunks[i].shape[0],sample_chunk_size+current_chunks[i][1]-current_chunks[i][0]))\n if current_chunks[i][0]==0:\n chunk[:,:sample_chunk_size]=np.array([in_fid['sig'][in_channel_chunks[i],0],]*sample_chunk_size).transpose()\n else:\n chunk[:,:sample_chunk_size]=in_fid['sig'][in_channel_chunks[i],(current_chunks[i][0]-sample_chunk_size):current_chunks[i][0]]\n sample_chunks[i]=np.delete(sample_chunks[i], (0), axis=0)\n chunk[:,sample_chunk_size:]=in_fid['sig'][in_channel_chunks[i],current_chunks[i][0]:current_chunks[i][1]]\n comm.send(chunk, dest=i+1, tag=DATA_TAG)\n \n # Waiting for next ready chunk\n data=comm.recv(source=MPI.ANY_SOURCE, tag=RESULT_TAG, status=status)\n rnk = status.Get_source()\n \n # Writing results to output file\n out_fid['sig'][out_channel_chunks[rnk-1],current_chunks[rnk-1][0]:current_chunks[rnk-1][1]]=data\n current_chunks[rnk-1]=None\n n_current_chunks=sum([current_chunks[cc] is not None for cc in current_chunks])\n n_remaining_chunks=sum([sample_chunks[i].shape[0] for i in np.arange(nproc-1)])\n \n # Reportint progress\n print((1-n_remaining_chunks/n_total_chunks)*990, flush=True)\n \n # After finishing the main loop, killing processes\n for proc in range(nproc-1): \n comm.send(DIE_SIGNAL, proc+1, tag=SETUP_TAG)\n# Slave process main loop\nelse: \n while True:\n # Waiting for data from master process\n chunk_shape=comm.recv(source=MASTER_PROCESS, tag=SETUP_TAG) \n if chunk_shape==-1:\n break\n else:\n amps=comm.recv(source=MASTER_PROCESS, tag=AMPS_TAG) \n chunk=comm.recv(source=MASTER_PROCESS, tag=DATA_TAG, status=status) \n tag = status.Get_tag() \n cusig=cupy.asarray(chunk, dtype=cupy.float32)\n cusig=cusig-cupy.mean(cusig)\n cusig=cusignal.sosfilt(sos,cusig)\n cusig=cupy.flipud(cusig)\n cusig=cusignal.sosfilt(sos,cusig)\n cusig=cupy.flipud(cusig)\n proc_channel_scales=cupy.asarray(chunk[:,-1], dtype=cupy.float32)[:,None]\n# cusig=cusig*proc_channel_scales\n result_array=cupy.asnumpy(cusig[:,-(chunk.shape[1]-sample_chunk_size):])\n comm.send(result_array, dest=MASTER_PROCESS, tag=RESULT_TAG)\n\nif iproc == MASTER_PROCESS:\n in_fid.close()\n out_fid.close() \n if ram_copy:\n out_ramfile.save()\n del in_ramfile, out_ramfile\n print('DONE', flush=True)"
] |
[
[
"numpy.array",
"numpy.delete",
"numpy.empty",
"scipy.signal.butter",
"numpy.arange",
"numpy.array_split"
]
] |
MatthieuSarkis/criticality
|
[
"2939d7408bcd5d3bf7f237cfe56c836cf361e64f"
] |
[
"src/CNN_classification/train.py"
] |
[
"import os\nimport numpy as np\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # for ignoring the some of tf warnings\nimport tensorflow as tf\nfrom tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, TensorBoard\nfrom sklearn.model_selection import train_test_split\n\nfrom src.CNN_classification import network\nfrom src.CNN_classification import utils\n\ndef train(X, y,\n random_state=42,\n test_size=0.20,\n stage_train_dir='.',\n patience=10,\n epochs=10,\n batch_size=None,\n dropout_rate=0.2,\n dump_model_summary=True,\n set_lr_scheduler=True,\n set_checkpoint=True,\n set_earlystopping=True,\n set_tensorboard=False,\n dump_history=True,\n save_model=True,\n **kwargs\n ):\n\n N, L = X.shape[0], X.shape[1]\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size, \n random_state=random_state, \n ) #stratify=y\n K = len(np.unique(y_train)) \n \n # design the architecture of model\n model = network.create_model((L, L, 1), K, dropout_rate=dropout_rate)\n\n # compile the model \n opt = tf.keras.optimizers.Adam(learning_rate=1e-4)\n model.compile(optimizer=opt, \n loss='sparse_categorical_crossentropy', \n metrics=['sparse_categorical_accuracy']) \n\n # Callbacks \n callbacks = []\n \n if set_lr_scheduler:\n lr_scheduler = tf.keras.callbacks.ReduceLROnPlateau(factor=0.5, patience=5)\n callbacks += [lr_scheduler]\n\n if set_checkpoint:\n checkpoint_file = utils.make_path(stage_train_dir, \"ckpt-best.h5\")\n checkpoint_cb = ModelCheckpoint(checkpoint_file, \n save_best_only=True, \n monitor='val_loss',\n save_weights_only=False) \n callbacks += [checkpoint_cb]\n \n if set_earlystopping:\n early_stopping_cb = EarlyStopping(patience=patience, restore_best_weights=True)\n callbacks += [early_stopping_cb]\n\n if set_tensorboard:\n tensor_board = TensorBoard(log_dir=stage_train_dir)\n callbacks += [tensor_board]\n\n # print model info\n if dump_model_summary:\n utils.print_model_summary(model, stage_train_dir)\n\n # training the model\n history = model.fit(X_train, y_train, \n validation_data=(X_test, y_test), \n callbacks=callbacks,\n epochs=epochs,\n batch_size=batch_size)\n\n if save_model:\n model.save(utils.make_path(stage_train_dir, 'saved-model.h5'))\n\n if dump_history:\n\n utils.write_numpy_dic_to_json(history.history, \n utils.make_path(stage_train_dir, 'history.json'))\n \n loss_test, accuracy_test = model.evaluate(X_test, y_test, verbose=0)\n print('loss_test={:.3f}, accuracy_test={:.3f}'.format(loss_test, accuracy_test))\n\n \"\"\"loaded_model = tf.keras.models.load_model(make_path(stage_train_dir, 'saved-model.h5'))\n loss_test, accuracy_test = loaded_model.evaluate(X_test, y_test, verbose=0)\n print('loaded_model_loss_test={:.3f}, loaded_model_accuracy_test={:.3f}'.format(loss_test, accuracy_test))\"\"\"\n \n \n return model, history\n \n\n#====================================================================\n"
] |
[
[
"tensorflow.keras.callbacks.TensorBoard",
"tensorflow.keras.callbacks.ModelCheckpoint",
"sklearn.model_selection.train_test_split",
"tensorflow.keras.optimizers.Adam",
"tensorflow.keras.callbacks.ReduceLROnPlateau",
"numpy.unique",
"tensorflow.keras.callbacks.EarlyStopping"
]
] |
s-weigand/work-tracker
|
[
"fe5e2c8c292ae4e040abc96897b16fcd1ffc5508"
] |
[
"tests/conftest.py"
] |
[
"import os\nfrom shutil import copyfile\n\nimport pandas as pd\nimport pytest\n\nfrom work_tracker.functions.helpfer_functions import get_abs_path\n\n\n# ###########################\n# # DATA FIXTURES #\n# ###########################\n@pytest.fixture(scope=\"module\")\ndef data_test_calc():\n\n test_data_path = get_abs_path(\"../tests/test_data/calc_worktime\")\n test_df_path_src = os.path.join(test_data_path, \"base_remote_df.tsv\")\n test_df_path_dest = os.path.join(test_data_path, \"remote_db.tsv\")\n copyfile(test_df_path_src, test_df_path_dest)\n test_df = pd.read_csv(test_df_path_src, sep=\"\\t\", parse_dates=[\"start\", \"end\"]) # type:ignore\n result = pd.read_csv(\n os.path.join(test_data_path, \"base_result.tsv\"),\n sep=\"\\t\",\n parse_dates=[\"start\", \"end\"], # type:ignore\n )\n manual_df_path = os.path.join(test_data_path, \"result_manual_db.tsv\")\n manual_df = pd.read_csv(manual_df_path, parse_dates=[\"start\", \"end\"], sep=\"\\t\") # type:ignore\n yield {\n \"result\": result,\n \"test_df\": test_df,\n \"test_df_path\": test_df_path_dest,\n \"manual_df\": manual_df,\n }\n # file_cleanup\n if os.path.isfile(test_df_path_dest):\n os.remove(test_df_path_dest)\n\n\n@pytest.fixture(scope=\"function\")\ndef test_data_base():\n test_data_path = get_abs_path(\"../tests/test_data/update_data\")\n offline_df_path_src = os.path.join(test_data_path, \"baseclass_offline_df.tsv\")\n online_df_path_src = os.path.join(test_data_path, \"baseclass_online_df.tsv\")\n offline_df_path_dest = os.path.join(test_data_path, \"local_db.tsv\")\n online_df_path_dest = os.path.join(test_data_path, \"remote_db.tsv\")\n copyfile(offline_df_path_src, offline_df_path_dest)\n copyfile(online_df_path_src, online_df_path_dest)\n offline_df = pd.read_csv(\n offline_df_path_src, sep=\"\\t\", parse_dates=[\"start\", \"end\"] # type:ignore\n ) # type:ignore\n online_df = pd.read_csv(\n online_df_path_src, sep=\"\\t\", parse_dates=[\"start\", \"end\"] # type:ignore\n )\n result = pd.read_csv(\n os.path.join(test_data_path, \"baseclass_result.tsv\"),\n sep=\"\\t\",\n parse_dates=[\"start\", \"end\"], # type:ignore\n )\n yield {\n \"result\": result,\n \"offline_df\": offline_df,\n \"offline_df_path\": offline_df_path_dest,\n \"online_df\": online_df,\n \"online_df_path\": online_df_path_dest,\n }\n # file_cleanup\n if os.path.isfile(offline_df_path_dest):\n os.remove(offline_df_path_dest)\n if os.path.isfile(online_df_path_dest):\n os.remove(online_df_path_dest)\n"
] |
[
[
"pandas.read_csv"
]
] |
chncwang/mindspore
|
[
"bc38590e5300588aa551355836043af0ea092a72",
"bc38590e5300588aa551355836043af0ea092a72",
"bc38590e5300588aa551355836043af0ea092a72",
"6dac92aedf0aa1541d181e6aedab29aaadc2dafb"
] |
[
"model_zoo/official/cv/faster_rcnn/src/FasterRcnn/faster_rcnn_r50.py",
"tests/ut/python/pipeline/parse/test_tuple_index_by_negative.py",
"tests/ut/python/parallel/test_pack.py",
"mindspore/dataset/engine/samplers.py"
] |
[
"# Copyright 2020-2021 Huawei Technologies Co., Ltd\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\"\"\"FasterRcnn based on ResNet50.\"\"\"\n\nimport numpy as np\nimport mindspore.nn as nn\nfrom mindspore.ops import operations as P\nfrom mindspore.common.tensor import Tensor\nimport mindspore.common.dtype as mstype\nfrom mindspore.ops import functional as F\nfrom .resnet50 import ResNetFea, ResidualBlockUsing\nfrom .bbox_assign_sample_stage2 import BboxAssignSampleForRcnn\nfrom .fpn_neck import FeatPyramidNeck\nfrom .proposal_generator import Proposal\nfrom .rcnn import Rcnn\nfrom .rpn import RPN\nfrom .roi_align import SingleRoIExtractor\nfrom .anchor_generator import AnchorGenerator\n\n\nclass Faster_Rcnn_Resnet50(nn.Cell):\n \"\"\"\n FasterRcnn Network.\n\n Note:\n backbone = resnet50\n\n Returns:\n Tuple, tuple of output tensor.\n rpn_loss: Scalar, Total loss of RPN subnet.\n rcnn_loss: Scalar, Total loss of RCNN subnet.\n rpn_cls_loss: Scalar, Classification loss of RPN subnet.\n rpn_reg_loss: Scalar, Regression loss of RPN subnet.\n rcnn_cls_loss: Scalar, Classification loss of RCNN subnet.\n rcnn_reg_loss: Scalar, Regression loss of RCNN subnet.\n\n Examples:\n net = Faster_Rcnn_Resnet50()\n \"\"\"\n def __init__(self, config):\n super(Faster_Rcnn_Resnet50, self).__init__()\n self.dtype = np.float32\n self.ms_type = mstype.float32\n self.train_batch_size = config.batch_size\n self.num_classes = config.num_classes\n self.anchor_scales = config.anchor_scales\n self.anchor_ratios = config.anchor_ratios\n self.anchor_strides = config.anchor_strides\n self.target_means = tuple(config.rcnn_target_means)\n self.target_stds = tuple(config.rcnn_target_stds)\n\n # Anchor generator\n anchor_base_sizes = None\n self.anchor_base_sizes = list(\n self.anchor_strides) if anchor_base_sizes is None else anchor_base_sizes\n\n self.anchor_generators = []\n for anchor_base in self.anchor_base_sizes:\n self.anchor_generators.append(\n AnchorGenerator(anchor_base, self.anchor_scales, self.anchor_ratios))\n\n self.num_anchors = len(self.anchor_ratios) * len(self.anchor_scales)\n\n featmap_sizes = config.feature_shapes\n assert len(featmap_sizes) == len(self.anchor_generators)\n\n self.anchor_list = self.get_anchors(featmap_sizes)\n\n # Backbone resnet50\n self.backbone = ResNetFea(ResidualBlockUsing,\n config.resnet_block,\n config.resnet_in_channels,\n config.resnet_out_channels,\n False)\n\n # Fpn\n self.fpn_ncek = FeatPyramidNeck(config.fpn_in_channels,\n config.fpn_out_channels,\n config.fpn_num_outs)\n\n # Rpn and rpn loss\n self.gt_labels_stage1 = Tensor(np.ones((self.train_batch_size, config.num_gts)).astype(np.uint8))\n self.rpn_with_loss = RPN(config,\n self.train_batch_size,\n config.rpn_in_channels,\n config.rpn_feat_channels,\n config.num_anchors,\n config.rpn_cls_out_channels)\n\n # Proposal\n self.proposal_generator = Proposal(config,\n self.train_batch_size,\n config.activate_num_classes,\n config.use_sigmoid_cls)\n self.proposal_generator.set_train_local(config, True)\n self.proposal_generator_test = Proposal(config,\n config.test_batch_size,\n config.activate_num_classes,\n config.use_sigmoid_cls)\n self.proposal_generator_test.set_train_local(config, False)\n\n # Assign and sampler stage two\n self.bbox_assigner_sampler_for_rcnn = BboxAssignSampleForRcnn(config, self.train_batch_size,\n config.num_bboxes_stage2, True)\n self.decode = P.BoundingBoxDecode(max_shape=(config.img_height, config.img_width), means=self.target_means, \\\n stds=self.target_stds)\n # Roi\n self.roi_init(config)\n\n # Rcnn\n self.rcnn = Rcnn(config, config.rcnn_in_channels * config.roi_layer['out_size'] * config.roi_layer['out_size'],\n self.train_batch_size, self.num_classes)\n\n # Op declare\n self.squeeze = P.Squeeze()\n self.cast = P.Cast()\n\n self.concat = P.Concat(axis=0)\n self.concat_1 = P.Concat(axis=1)\n self.concat_2 = P.Concat(axis=2)\n self.reshape = P.Reshape()\n self.select = P.Select()\n self.greater = P.Greater()\n self.transpose = P.Transpose()\n\n # Improve speed\n self.concat_start = min(self.num_classes - 2, 55)\n self.concat_end = (self.num_classes - 1)\n\n # Test mode\n self.test_mode_init(config)\n\n # Init tensor\n self.init_tensor(config)\n\n def roi_init(self, config):\n self.roi_align = SingleRoIExtractor(config,\n config.roi_layer,\n config.roi_align_out_channels,\n config.roi_align_featmap_strides,\n self.train_batch_size,\n config.roi_align_finest_scale)\n self.roi_align.set_train_local(config, True)\n self.roi_align_test = SingleRoIExtractor(config,\n config.roi_layer,\n config.roi_align_out_channels,\n config.roi_align_featmap_strides,\n 1,\n config.roi_align_finest_scale)\n self.roi_align_test.set_train_local(config, False)\n\n def test_mode_init(self, config):\n self.test_batch_size = config.test_batch_size\n self.split = P.Split(axis=0, output_num=self.test_batch_size)\n self.split_shape = P.Split(axis=0, output_num=4)\n self.split_scores = P.Split(axis=1, output_num=self.num_classes)\n self.split_cls = P.Split(axis=0, output_num=self.num_classes-1)\n self.tile = P.Tile()\n self.gather = P.GatherNd()\n\n self.rpn_max_num = config.rpn_max_num\n\n self.zeros_for_nms = Tensor(np.zeros((self.rpn_max_num, 3)).astype(self.dtype))\n self.ones_mask = np.ones((self.rpn_max_num, 1)).astype(np.bool)\n self.zeros_mask = np.zeros((self.rpn_max_num, 1)).astype(np.bool)\n self.bbox_mask = Tensor(np.concatenate((self.ones_mask, self.zeros_mask,\n self.ones_mask, self.zeros_mask), axis=1))\n self.nms_pad_mask = Tensor(np.concatenate((self.ones_mask, self.ones_mask,\n self.ones_mask, self.ones_mask, self.zeros_mask), axis=1))\n\n self.test_score_thresh = Tensor(np.ones((self.rpn_max_num, 1)).astype(self.dtype) * config.test_score_thr)\n self.test_score_zeros = Tensor(np.ones((self.rpn_max_num, 1)).astype(self.dtype) * 0)\n self.test_box_zeros = Tensor(np.ones((self.rpn_max_num, 4)).astype(self.dtype) * -1)\n self.test_iou_thr = Tensor(np.ones((self.rpn_max_num, 1)).astype(self.dtype) * config.test_iou_thr)\n self.test_max_per_img = config.test_max_per_img\n self.nms_test = P.NMSWithMask(config.test_iou_thr)\n self.softmax = P.Softmax(axis=1)\n self.logicand = P.LogicalAnd()\n self.oneslike = P.OnesLike()\n self.test_topk = P.TopK(sorted=True)\n self.test_num_proposal = self.test_batch_size * self.rpn_max_num\n\n def init_tensor(self, config):\n roi_align_index = [np.array(np.ones((config.num_expected_pos_stage2 + config.num_expected_neg_stage2, 1)) * i,\n dtype=self.dtype) for i in range(self.train_batch_size)]\n\n roi_align_index_test = [np.array(np.ones((config.rpn_max_num, 1)) * i, dtype=self.dtype) \\\n for i in range(self.test_batch_size)]\n\n self.roi_align_index_tensor = Tensor(np.concatenate(roi_align_index))\n self.roi_align_index_test_tensor = Tensor(np.concatenate(roi_align_index_test))\n\n def construct(self, img_data, img_metas, gt_bboxes, gt_labels, gt_valids):\n x = self.backbone(img_data)\n x = self.fpn_ncek(x)\n\n rpn_loss, cls_score, bbox_pred, rpn_cls_loss, rpn_reg_loss, _ = self.rpn_with_loss(x,\n img_metas,\n self.anchor_list,\n gt_bboxes,\n self.gt_labels_stage1,\n gt_valids)\n\n if self.training:\n proposal, proposal_mask = self.proposal_generator(cls_score, bbox_pred, self.anchor_list)\n else:\n proposal, proposal_mask = self.proposal_generator_test(cls_score, bbox_pred, self.anchor_list)\n\n gt_labels = self.cast(gt_labels, mstype.int32)\n gt_valids = self.cast(gt_valids, mstype.int32)\n bboxes_tuple = ()\n deltas_tuple = ()\n labels_tuple = ()\n mask_tuple = ()\n if self.training:\n for i in range(self.train_batch_size):\n gt_bboxes_i = self.squeeze(gt_bboxes[i:i + 1:1, ::])\n\n gt_labels_i = self.squeeze(gt_labels[i:i + 1:1, ::])\n gt_labels_i = self.cast(gt_labels_i, mstype.uint8)\n\n gt_valids_i = self.squeeze(gt_valids[i:i + 1:1, ::])\n gt_valids_i = self.cast(gt_valids_i, mstype.bool_)\n\n bboxes, deltas, labels, mask = self.bbox_assigner_sampler_for_rcnn(gt_bboxes_i,\n gt_labels_i,\n proposal_mask[i],\n proposal[i][::, 0:4:1],\n gt_valids_i)\n bboxes_tuple += (bboxes,)\n deltas_tuple += (deltas,)\n labels_tuple += (labels,)\n mask_tuple += (mask,)\n\n bbox_targets = self.concat(deltas_tuple)\n rcnn_labels = self.concat(labels_tuple)\n bbox_targets = F.stop_gradient(bbox_targets)\n rcnn_labels = F.stop_gradient(rcnn_labels)\n rcnn_labels = self.cast(rcnn_labels, mstype.int32)\n else:\n mask_tuple += proposal_mask\n bbox_targets = proposal_mask\n rcnn_labels = proposal_mask\n for p_i in proposal:\n bboxes_tuple += (p_i[::, 0:4:1],)\n\n if self.training:\n if self.train_batch_size > 1:\n bboxes_all = self.concat(bboxes_tuple)\n else:\n bboxes_all = bboxes_tuple[0]\n rois = self.concat_1((self.roi_align_index_tensor, bboxes_all))\n else:\n if self.test_batch_size > 1:\n bboxes_all = self.concat(bboxes_tuple)\n else:\n bboxes_all = bboxes_tuple[0]\n rois = self.concat_1((self.roi_align_index_test_tensor, bboxes_all))\n\n rois = self.cast(rois, mstype.float32)\n rois = F.stop_gradient(rois)\n\n if self.training:\n roi_feats = self.roi_align(rois,\n self.cast(x[0], mstype.float32),\n self.cast(x[1], mstype.float32),\n self.cast(x[2], mstype.float32),\n self.cast(x[3], mstype.float32))\n else:\n roi_feats = self.roi_align_test(rois,\n self.cast(x[0], mstype.float32),\n self.cast(x[1], mstype.float32),\n self.cast(x[2], mstype.float32),\n self.cast(x[3], mstype.float32))\n\n roi_feats = self.cast(roi_feats, self.ms_type)\n rcnn_masks = self.concat(mask_tuple)\n rcnn_masks = F.stop_gradient(rcnn_masks)\n rcnn_mask_squeeze = self.squeeze(self.cast(rcnn_masks, mstype.bool_))\n rcnn_loss, rcnn_cls_loss, rcnn_reg_loss, _ = self.rcnn(roi_feats,\n bbox_targets,\n rcnn_labels,\n rcnn_mask_squeeze)\n\n output = ()\n if self.training:\n output += (rpn_loss, rcnn_loss, rpn_cls_loss, rpn_reg_loss, rcnn_cls_loss, rcnn_reg_loss)\n else:\n output = self.get_det_bboxes(rcnn_cls_loss, rcnn_reg_loss, rcnn_masks, bboxes_all, img_metas)\n\n return output\n\n def get_det_bboxes(self, cls_logits, reg_logits, mask_logits, rois, img_metas):\n \"\"\"Get the actual detection box.\"\"\"\n scores = self.softmax(cls_logits)\n\n boxes_all = ()\n for i in range(self.num_classes):\n k = i * 4\n reg_logits_i = self.squeeze(reg_logits[::, k:k+4:1])\n out_boxes_i = self.decode(rois, reg_logits_i)\n boxes_all += (out_boxes_i,)\n\n img_metas_all = self.split(img_metas)\n scores_all = self.split(scores)\n mask_all = self.split(self.cast(mask_logits, mstype.int32))\n\n boxes_all_with_batchsize = ()\n for i in range(self.test_batch_size):\n scale = self.split_shape(self.squeeze(img_metas_all[i]))\n scale_h = scale[2]\n scale_w = scale[3]\n boxes_tuple = ()\n for j in range(self.num_classes):\n boxes_tmp = self.split(boxes_all[j])\n out_boxes_h = boxes_tmp[i] / scale_h\n out_boxes_w = boxes_tmp[i] / scale_w\n boxes_tuple += (self.select(self.bbox_mask, out_boxes_w, out_boxes_h),)\n boxes_all_with_batchsize += (boxes_tuple,)\n\n output = self.multiclass_nms(boxes_all_with_batchsize, scores_all, mask_all)\n\n return output\n\n def multiclass_nms(self, boxes_all, scores_all, mask_all):\n \"\"\"Multiscale postprocessing.\"\"\"\n all_bboxes = ()\n all_labels = ()\n all_masks = ()\n\n for i in range(self.test_batch_size):\n bboxes = boxes_all[i]\n scores = scores_all[i]\n masks = self.cast(mask_all[i], mstype.bool_)\n\n res_boxes_tuple = ()\n res_labels_tuple = ()\n res_masks_tuple = ()\n\n for j in range(self.num_classes - 1):\n k = j + 1\n _cls_scores = scores[::, k:k + 1:1]\n _bboxes = self.squeeze(bboxes[k])\n _mask_o = self.reshape(masks, (self.rpn_max_num, 1))\n\n cls_mask = self.greater(_cls_scores, self.test_score_thresh)\n _mask = self.logicand(_mask_o, cls_mask)\n\n _reg_mask = self.cast(self.tile(self.cast(_mask, mstype.int32), (1, 4)), mstype.bool_)\n\n _bboxes = self.select(_reg_mask, _bboxes, self.test_box_zeros)\n _cls_scores = self.select(_mask, _cls_scores, self.test_score_zeros)\n __cls_scores = self.squeeze(_cls_scores)\n scores_sorted, topk_inds = self.test_topk(__cls_scores, self.rpn_max_num)\n topk_inds = self.reshape(topk_inds, (self.rpn_max_num, 1))\n scores_sorted = self.reshape(scores_sorted, (self.rpn_max_num, 1))\n _bboxes_sorted = self.gather(_bboxes, topk_inds)\n _mask_sorted = self.gather(_mask, topk_inds)\n\n scores_sorted = self.tile(scores_sorted, (1, 4))\n cls_dets = self.concat_1((_bboxes_sorted, scores_sorted))\n cls_dets = P.Slice()(cls_dets, (0, 0), (self.rpn_max_num, 5))\n\n cls_dets, _index, _mask_nms = self.nms_test(cls_dets)\n _index = self.reshape(_index, (self.rpn_max_num, 1))\n _mask_nms = self.reshape(_mask_nms, (self.rpn_max_num, 1))\n\n _mask_n = self.gather(_mask_sorted, _index)\n\n _mask_n = self.logicand(_mask_n, _mask_nms)\n cls_labels = self.oneslike(_index) * j\n res_boxes_tuple += (cls_dets,)\n res_labels_tuple += (cls_labels,)\n res_masks_tuple += (_mask_n,)\n\n res_boxes_start = self.concat(res_boxes_tuple[:self.concat_start])\n res_labels_start = self.concat(res_labels_tuple[:self.concat_start])\n res_masks_start = self.concat(res_masks_tuple[:self.concat_start])\n\n res_boxes_end = self.concat(res_boxes_tuple[self.concat_start:self.concat_end])\n res_labels_end = self.concat(res_labels_tuple[self.concat_start:self.concat_end])\n res_masks_end = self.concat(res_masks_tuple[self.concat_start:self.concat_end])\n\n res_boxes = self.concat((res_boxes_start, res_boxes_end))\n res_labels = self.concat((res_labels_start, res_labels_end))\n res_masks = self.concat((res_masks_start, res_masks_end))\n\n reshape_size = (self.num_classes - 1) * self.rpn_max_num\n res_boxes = self.reshape(res_boxes, (1, reshape_size, 5))\n res_labels = self.reshape(res_labels, (1, reshape_size, 1))\n res_masks = self.reshape(res_masks, (1, reshape_size, 1))\n\n all_bboxes += (res_boxes,)\n all_labels += (res_labels,)\n all_masks += (res_masks,)\n\n all_bboxes = self.concat(all_bboxes)\n all_labels = self.concat(all_labels)\n all_masks = self.concat(all_masks)\n return all_bboxes, all_labels, all_masks\n\n def get_anchors(self, featmap_sizes):\n \"\"\"Get anchors according to feature map sizes.\n\n Args:\n featmap_sizes (list[tuple]): Multi-level feature map sizes.\n img_metas (list[dict]): Image meta info.\n\n Returns:\n tuple: anchors of each image, valid flags of each image\n \"\"\"\n num_levels = len(featmap_sizes)\n\n # since feature map sizes of all images are the same, we only compute\n # anchors for one time\n multi_level_anchors = ()\n for i in range(num_levels):\n anchors = self.anchor_generators[i].grid_anchors(\n featmap_sizes[i], self.anchor_strides[i])\n multi_level_anchors += (Tensor(anchors.astype(self.dtype)),)\n\n return multi_level_anchors\n\nclass FasterRcnn_Infer(nn.Cell):\n def __init__(self, config):\n super(FasterRcnn_Infer, self).__init__()\n self.network = Faster_Rcnn_Resnet50(config)\n self.network.set_train(False)\n\n def construct(self, img_data, img_metas):\n output = self.network(img_data, img_metas, None, None, None)\n return output\n",
"# Copyright 2021 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\" test tuple index by negative number\"\"\"\nimport numpy as np\nimport pytest\n\nfrom mindspore import nn\nfrom mindspore import Tensor\nfrom mindspore import context\nfrom mindspore.ops import operations as P\n\ncontext.set_context(mode=context.GRAPH_MODE, save_graphs=True)\n\n\ndef test_tuple_index_by_negative_number():\n class Net(nn.Cell):\n def __init__(self):\n super(Net, self).__init__()\n self.index = -1\n self.split = P.Split(axis=0, output_num=4)\n\n def construct(self, x):\n out = self.split(x)\n ret = [out[-1], out[-2], out[-3], out[-4]]\n ret[-1] = 100\n return ret\n\n net = Net()\n x = Tensor(np.ones((4, 2, 3)))\n net(x)\n\n\ndef Ttest_tuple_index_by_negative_number_out_bound():\n class Net(nn.Cell):\n def __init__(self):\n super(Net, self).__init__()\n self.index = -1\n self.split = P.Split(axis=0, output_num=2)\n\n def construct(self, x):\n out = self.split(x)\n return out[-1], out[-2], out[-3]\n\n net = Net()\n x = Tensor(np.ones((2, 2, 3)))\n with pytest.raises(IndexError) as err:\n net(x)\n assert \"TupleGetItem evaluator index should be in range[-2, 2), but got -3\" in str(err.value)\n",
"# Copyright 2020 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\nimport numpy as np\nimport mindspore as ms\nimport mindspore.context as context\nfrom mindspore import Tensor, Parameter\nimport mindspore.nn as nn\nfrom mindspore.common.api import _executor\nfrom mindspore.nn import TrainOneStepCell, Momentum\nfrom mindspore.ops import operations as P\nfrom mindspore.nn import Dense, Flatten\n\n\nclass Net(nn.Cell):\n def __init__(self, weight1, weight2, axis=0, strategy1=None, strategy2=None, is_parameter=True):\n super(Net, self).__init__()\n self.pack = P.Stack(axis=axis).shard(strategy1)\n self.mul = P.Mul().shard(strategy2)\n if is_parameter:\n self.weight1 = Parameter(weight1, \"w1\")\n else:\n self.weight1 = weight1\n self.weight2 = Parameter(weight2, \"w2\")\n\n def construct(self, x):\n out = self.pack([self.weight1, self.weight2])\n out = self.mul(x, out)\n return out\n\n\nclass Net1(nn.Cell):\n def __init__(self, weight1, weight2, axis=0, strategy1=None, strategy2=None):\n super(Net1, self).__init__()\n self.pack = P.Stack(axis=axis).shard(strategy1)\n self.mul = P.Mul().shard(strategy2)\n self.weight1 = Parameter(weight1, \"w1\")\n self.weight2 = Parameter(weight2, \"w2\")\n\n def construct(self, x):\n out = self.mul(x, self.weight1)\n out = self.pack([out, self.weight2])\n return out\n\n\nclass Net2(nn.Cell):\n def __init__(self, weight1, weight2, weight3, axis=0, strategy1=None, strategy2=None, is_parameter=True):\n super(Net2, self).__init__()\n self.pack = P.Stack(axis=axis).shard(strategy1)\n self.mul = P.Mul().shard(strategy2)\n if is_parameter:\n self.weight1 = Parameter(weight1, \"w1\")\n else:\n self.weight1 = weight1\n self.weight2 = Parameter(weight2, \"w2\")\n self.weight3 = Parameter(weight2, \"w3\")\n\n def construct(self, x):\n out = self.pack([self.weight1, self.weight2, self.weight3])\n out = self.mul(x, out)\n return out\n\n\nclass PackConstantNet1(nn.Cell):\n def __init__(self, dense_in_channel, dense_out_channel, axis=0, shape=None, strategy=None):\n super().__init__()\n weight_np = np.full((dense_out_channel, dense_in_channel), 0.01, dtype=np.float32)\n bias_np = np.full((dense_out_channel), 0.01, dtype=np.float32)\n self.pack_con = Tensor(np.full(shape, 0.01, dtype=np.float32))\n self.flat = Flatten()\n self.dense = Dense(in_channels=dense_in_channel,\n out_channels=dense_out_channel,\n weight_init=Tensor(weight_np),\n bias_init=Tensor(bias_np),\n has_bias=True)\n self.mul = P.Mul()\n self.pack = P.Stack(axis)\n if strategy is not None:\n self.pack.shard(strategy)\n\n def construct(self, inputs):\n x = self.pack([self.pack_con, self.pack_con, self.pack_con, self.pack_con,\n self.pack_con, self.pack_con, self.pack_con, self.pack_con])\n x1 = self.flat(x)\n x2 = self.flat(inputs)\n x = self.mul(x1, x2)\n x = self.dense(x)\n return x\n\n\nclass PackConstantNet2(nn.Cell):\n def __init__(self, dense_in_channel, dense_out_channel, axis=0, shape=None, strategy=None):\n super().__init__()\n weight_np = np.full((dense_out_channel, dense_in_channel), 0.01, dtype=np.float32)\n bias_np = np.full((dense_out_channel), 0.01, dtype=np.float32)\n self.pack_con = Tensor(np.full(shape, 0.01, dtype=np.float32))\n self.flat = Flatten()\n self.dense = Dense(in_channels=dense_in_channel,\n out_channels=dense_out_channel,\n weight_init=Tensor(weight_np),\n bias_init=Tensor(bias_np),\n has_bias=True)\n self.mul = P.Mul()\n self.pack = P.Stack(axis)\n if strategy is not None:\n self.pack.shard(strategy)\n\n def construct(self, inputs):\n x = self.pack((self.pack_con, self.pack_con, self.pack_con, self.pack_con,\n self.pack_con, self.pack_con, self.pack_con, self.pack_con))\n x1 = self.flat(x)\n x2 = self.flat(inputs)\n x = self.mul(x1, x2)\n x = self.dense(x)\n return x\n\n\n_w1 = Tensor(np.ones([48, 64]), dtype=ms.float32)\n_w2 = Tensor(np.ones([48, 64]), dtype=ms.float32)\n_w3 = Tensor(np.ones([48, 64]), dtype=ms.float32)\n_x = Tensor(np.ones([2, 48, 64]), dtype=ms.float32)\n_x1 = Tensor(np.ones([48, 64]), dtype=ms.float32)\n_x2 = Tensor(np.ones([3, 48, 64]), dtype=ms.float32)\n_x_c = Tensor(np.ones([8, 8, 8]), dtype=ms.float32)\n\n\ndef compile_net(net):\n context.set_context(mode=context.GRAPH_MODE, save_graphs=True)\n optimizer = Momentum(net.trainable_params(), learning_rate=0.1, momentum=0.9)\n train_net = TrainOneStepCell(net, optimizer)\n train_net.set_auto_parallel()\n train_net.set_train()\n _executor.compile(train_net, _x)\n context.reset_auto_parallel_context()\n\n\ndef compile_net1(net):\n context.set_context(mode=context.GRAPH_MODE, save_graphs=True)\n optimizer = Momentum(net.trainable_params(), learning_rate=0.1, momentum=0.9)\n train_net = TrainOneStepCell(net, optimizer)\n train_net.set_auto_parallel()\n train_net.set_train()\n _executor.compile(train_net, _x1)\n context.reset_auto_parallel_context()\n\n\ndef compile_net2(net):\n context.set_context(mode=context.GRAPH_MODE, save_graphs=True)\n optimizer = Momentum(net.trainable_params(), learning_rate=0.1, momentum=0.9)\n train_net = TrainOneStepCell(net, optimizer)\n train_net.set_auto_parallel()\n train_net.set_train()\n _executor.compile(train_net, _x2)\n context.reset_auto_parallel_context()\n\n\ndef compile_net_con(net):\n context.set_context(mode=context.GRAPH_MODE, save_graphs=True)\n optimizer = Momentum(net.trainable_params(), learning_rate=0.1, momentum=0.9)\n train_net = TrainOneStepCell(net, optimizer)\n train_net.set_auto_parallel()\n _executor.compile(train_net, _x_c)\n context.reset_auto_parallel_context()\n\n\ndef test_pack_parameter():\n context.set_auto_parallel_context(parallel_mode=\"semi_auto_parallel\", device_num=8, global_rank=0)\n strategy1 = ((4, 2), (4, 2))\n strategy2 = ((1, 4, 2), (1, 4, 2))\n net = Net(_w1, _w2, 0, strategy1, strategy2)\n compile_net(net)\n\n\ndef test_pack_parameter_no_full_split():\n context.set_auto_parallel_context(parallel_mode=\"semi_auto_parallel\", device_num=8, global_rank=0)\n strategy1 = ((2, 2), (2, 2))\n strategy2 = ((1, 4, 2), (1, 4, 2))\n net = Net(_w1, _w2, 0, strategy1, strategy2)\n compile_net(net)\n\n\ndef test_pack_tensor_and_parameter():\n context.set_auto_parallel_context(parallel_mode=\"semi_auto_parallel\", device_num=8, global_rank=0)\n strategy1 = ((4, 2), (4, 2))\n strategy2 = ((1, 4, 2), (1, 4, 2))\n net = Net(_w1, _w2, 0, strategy1, strategy2, False)\n compile_net(net)\n\n\ndef test_pack_output():\n context.set_auto_parallel_context(parallel_mode=\"semi_auto_parallel\", device_num=8, global_rank=0)\n strategy1 = ((4, 2), (4, 2))\n strategy2 = ((4, 2), (4, 2))\n net = Net1(_w1, _w2, 0, strategy1, strategy2)\n compile_net1(net)\n\n\ndef test_pack_output_axis1():\n context.set_auto_parallel_context(parallel_mode=\"semi_auto_parallel\", device_num=8, global_rank=0)\n strategy1 = ((4, 2), (4, 2))\n strategy2 = ((4, 2), (4, 2))\n net = Net1(_w1, _w2, 1, strategy1, strategy2)\n compile_net1(net)\n\n\ndef test_pack_output_no_full_split():\n context.set_auto_parallel_context(parallel_mode=\"semi_auto_parallel\", device_num=8, global_rank=0)\n strategy1 = ((2, 2), (2, 2))\n strategy2 = ((4, 2), (4, 2))\n net = Net1(_w1, _w2, 0, strategy1, strategy2)\n compile_net1(net)\n\n\ndef test_pack_no_strategy():\n context.set_auto_parallel_context(parallel_mode=\"semi_auto_parallel\", device_num=8, global_rank=0)\n strategy1 = None\n strategy2 = ((4, 2), (4, 2))\n net = Net1(_w1, _w2, 0, strategy1, strategy2)\n compile_net1(net)\n\n\ndef test_pack_no_strategy_axis1():\n context.set_auto_parallel_context(parallel_mode=\"semi_auto_parallel\", device_num=8, global_rank=0)\n strategy1 = None\n strategy2 = ((4, 2), (4, 2))\n net = Net1(_w1, _w2, 1, strategy1, strategy2)\n compile_net1(net)\n\n\ndef test_pack_auto_parallel():\n context.set_auto_parallel_context(parallel_mode=\"auto_parallel\", device_num=8, global_rank=0)\n net = Net1(_w1, _w2, 0)\n compile_net1(net)\n\n\ndef test_pack_auto_parallel_axis1():\n context.set_auto_parallel_context(parallel_mode=\"auto_parallel\", device_num=8, global_rank=0)\n net = Net1(_w1, _w2, 1)\n compile_net1(net)\n\n\ndef test_pack_auto_parallel_3_tensor():\n context.set_auto_parallel_context(parallel_mode=\"auto_parallel\", device_num=8, global_rank=0)\n net = Net2(_w1, _w2, _w3)\n compile_net2(net)\n\n\ndef test_pack_constant1():\n context.set_auto_parallel_context(parallel_mode=\"semi_auto_parallel\", device_num=8, global_rank=0)\n net = PackConstantNet1(dense_in_channel=64, dense_out_channel=4, axis=0, shape=(8, 8),\n strategy=((4, 1), (4, 1), (4, 1), (4, 1), (4, 1), (4, 1), (4, 1), (4, 1)))\n compile_net_con(net)\n\n\ndef test_pack_constant2():\n context.set_auto_parallel_context(parallel_mode=\"semi_auto_parallel\", device_num=8, global_rank=0)\n net = PackConstantNet2(dense_in_channel=64, dense_out_channel=4, axis=0, shape=(8, 8),\n strategy=((4, 1), (4, 1), (4, 1), (4, 1), (4, 1), (4, 1), (4, 1), (4, 1)))\n compile_net_con(net)\n\n\ndef test_pack_auto_constant():\n context.set_auto_parallel_context(parallel_mode=\"auto_parallel\", device_num=8, global_rank=0)\n net = PackConstantNet1(dense_in_channel=64, dense_out_channel=4, axis=0, shape=(8, 8),\n strategy=((8, 1), (8, 1), (8, 1), (8, 1), (8, 1), (8, 1), (8, 1), (8, 1)))\n compile_net_con(net)\n",
"# Copyright 2019-2021 Huawei Technologies Co., Ltd\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\"\"\"\nThe sampler module provides several samplers to generate data from datasets.\nThe provided samplers include: DistributedSampler, PKSampler, RandomSampler,\nSequentialSampler, SubsetRandomSampler, and WeightedRandomSampler.\nUsers can also define a custom sampler by extending from the Sampler class.\n\"\"\"\n\nimport numbers\nimport numpy as np\nimport mindspore._c_dataengine as cde\nimport mindspore.dataset as ds\nfrom ..core import validator_helpers as validator\n\n\ndef select_sampler(num_samples, input_sampler, shuffle, num_shards, shard_id):\n \"\"\"\n Create sampler based on user input.\n\n Args:\n num_samples (int): Number of samples.\n input_sampler (Union[Iterable, Sampler]): Sampler from user.\n shuffle (bool): Shuffle.\n num_shards (int): Number of shard for sharding.\n shard_id (int): Shard ID.\n\n Returns:\n Sampler, sampler selected based on user input.\n \"\"\"\n\n def _is_iterable(obj):\n try:\n iter(obj)\n except TypeError:\n return False\n return True\n\n def _get_sample_ids_as_list(sampler, number_of_samples=None):\n if number_of_samples is None:\n return list(sampler)\n\n if isinstance(sampler, list):\n return sampler[:number_of_samples]\n\n return [sample_id for sample_id, _ in zip(sampler, range(number_of_samples))]\n\n if input_sampler is not None:\n # If the user provided a sampler, then it doesn't matter what the other args are because\n # we are being asked specifically to use the given sampler.\n # That means the following arguments: num_shards, shard_id, shuffle, num_samples should all\n # be None. Consider this example:\n # sampler = ds.DistributedSampler(num_shards=8, shard_id=3, shuffle=shuffle)\n # data1 = ds.VOCDataset(voc_dir, decode=True, sampler=sampler, num_shards=4, shard_id=1)\n # In this case, the user has given different sample-related arguments that contradict each other.\n # To prevent this, only allow the user to manually specify the sampler if those arguments are all None\n if (isinstance(input_sampler, BuiltinSampler) and\n (any(arg is not None for arg in [num_shards, shard_id, shuffle, num_samples]))):\n raise ValueError(\n 'Conflicting arguments during sampler assignments. num_samples: {}, num_shards: {},'\n ' shard_id: {}, shuffle: {}.'.format(num_samples, num_shards, shard_id, shuffle))\n if isinstance(input_sampler, BuiltinSampler):\n return input_sampler\n if not isinstance(input_sampler, str) and _is_iterable(input_sampler):\n return SubsetSampler(_get_sample_ids_as_list(input_sampler, num_samples))\n if isinstance(input_sampler, int):\n return SubsetSampler([input_sampler])\n raise TypeError('Unsupported sampler object of type ({})'.format(type(input_sampler)))\n if shuffle is None:\n if num_shards is not None:\n # If shuffle is not specified, sharding enabled, use distributed random sampler\n shuffle = True\n return DistributedSampler(num_shards, shard_id, shuffle=shuffle, num_samples=num_samples)\n # If shuffle is not specified, sharding disabled, use random sampler\n if num_samples is not None and num_samples != 0:\n return RandomSampler(replacement=True, num_samples=num_samples)\n return RandomSampler(num_samples=num_samples)\n if shuffle is True:\n if num_shards is not None:\n # If shuffle enabled, sharding enabled, use distributed random sampler\n return DistributedSampler(num_shards, shard_id, shuffle=shuffle, num_samples=num_samples)\n # If shuffle enabled, sharding disabled, use random sampler\n if num_samples is not None:\n return RandomSampler(replacement=True, num_samples=num_samples)\n return RandomSampler(num_samples=num_samples)\n if num_shards is not None:\n # If shuffle disabled, sharding enabled, use distributed sequential sampler\n return DistributedSampler(num_shards, shard_id, shuffle=shuffle, num_samples=num_samples)\n # If shuffle disabled, sharding disabled, use sequential sampler\n return SequentialSampler(num_samples=num_samples)\n\n\nclass BuiltinSampler:\n \"\"\"\n Base class for BuiltinSampler.\n\n User should not extend this class.\n \"\"\"\n\n def __init__(self, num_samples=None):\n self.child_sampler = None\n self.num_samples = num_samples\n\n def parse(self):\n pass\n\n def add_child(self, sampler):\n \"\"\"\n Add a sub-sampler for given sampler. The sub-sampler will receive all data from the\n output of parent sampler and apply its sample logic to return new samples.\n\n Args:\n sampler (Sampler): Object used to choose samples from the dataset. Only builtin\n samplers(DistributedSampler, PKSampler, RandomSampler, SequentialSampler,\n SubsetRandomSampler, WeightedRandomSampler) are supported.\n\n Examples:\n >>> sampler = ds.SequentialSampler(start_index=0, num_samples=3)\n >>> sampler.add_child(ds.RandomSampler(num_samples=2))\n >>> dataset = ds.Cifar10Dataset(cifar10_dataset_dir, sampler=sampler)\n \"\"\"\n self.child_sampler = sampler\n\n def get_child(self):\n return self.child_sampler\n\n def parse_child(self):\n c_child_sampler = None\n if self.child_sampler is not None:\n c_child_sampler = self.child_sampler.parse()\n return c_child_sampler\n\n def parse_child_for_minddataset(self):\n c_child_sampler = None\n if self.child_sampler is not None:\n c_child_sampler = self.child_sampler.parse_for_minddataset()\n return c_child_sampler\n\n def is_shuffled(self):\n raise NotImplementedError(\"Sampler must implement is_shuffled.\")\n\n def is_sharded(self):\n raise NotImplementedError(\"Sampler must implement is_sharded.\")\n\n def get_num_samples(self):\n \"\"\"\n All samplers can contain a numeric num_samples value (or it can be set to None).\n A child sampler can exist or be None.\n If a child sampler exists, then the child sampler count can be a numeric value or None.\n These conditions impact the resultant sampler count that is used.\n The following table shows the possible results from calling this function.\n\n .. list-table::\n :widths: 25 25 25 25\n :header-rows: 1\n\n * - child sampler\n - num_samples\n - child_samples\n - result\n * - T\n - x\n - y\n - min(x, y)\n * - T\n - x\n - None\n - x\n * - T\n - None\n - y\n - y\n * - T\n - None\n - None\n - None\n * - None\n - x\n - n/a\n - x\n * - None\n - None\n - n/a\n - None\n\n Returns:\n int, the number of samples, or None\n \"\"\"\n if self.child_sampler is not None:\n child_samples = self.child_sampler.get_num_samples()\n if self.num_samples is not None:\n if child_samples is not None:\n return min(self.num_samples, child_samples)\n\n return self.num_samples\n\n return child_samples\n\n return self.num_samples\n\n\nclass Sampler(BuiltinSampler):\n \"\"\"\n Base class for user defined sampler.\n A user defined sampler can be used with any existing dataset with sampler support.\n\n A required _iter_() method should by overridden by the user for sample index generation.\n An optional reset() method can be overridden for per repeat reset,\n\n dataset_size and num_samples will be set by dataset once a dataset iterator is created.\n\n Examples:\n >>> import mindspore.dataset as ds\n >>>\n >>> class ReverseSampler(ds,Sampler):\n >>> def __iter__(self):\n >>> for i in range(self.dataset_size - 1, -1, -1):\n >>> yield i\n >>>\n >>> ds = ds.ImageFolderDataset(path, sampler=ReverseSampler())\n \"\"\"\n\n def __init__(self, num_samples=None):\n super().__init__(num_samples)\n self.dataset_size = 0\n self.child_sampler = None\n self.num_samples = num_samples\n\n def __iter__(self):\n \"\"\"\n User defined iterator, must be overridden.\n _handshake is guaranteed to be called prior to iterator construction.\n \"\"\"\n raise NotImplementedError\n\n def reset(self):\n \"\"\"\n Per repeat reset callback, override this method if necessary\n \"\"\"\n\n # Initialization handshake callback\n # Do not override this method!\n def _handshake(self, ds_size, num_samples):\n self.dataset_size = ds_size\n self.num_samples = num_samples\n\n # Indices fetcher\n # Do not override this method!\n def _get_indices(self):\n sampler_iter = iter(self)\n ret = []\n for _ in range(self.num_samples):\n try:\n idx = next(sampler_iter)\n ret.append(idx)\n except StopIteration:\n break\n return np.array(ret)\n\n # Instance fetcher\n # Do not override this method!\n def parse(self):\n num_samples = self.num_samples if self.num_samples is not None else 0\n c_sampler = cde.PreBuiltSamplerObj(num_samples, self)\n c_child_sampler = self.parse_child()\n c_sampler.add_child(c_child_sampler)\n return c_sampler\n\n def add_child(self, sampler):\n self.child_sampler = sampler\n\n def get_child(self):\n return self.child_sampler\n\n def parse_child(self):\n c_child_sampler = None\n if self.child_sampler is not None:\n c_child_sampler = self.child_sampler.parse()\n\n return c_child_sampler\n\n def is_shuffled(self):\n if self.child_sampler is None:\n return False\n\n return self.child_sampler.is_shuffled()\n\n def is_sharded(self):\n if self.child_sampler is None:\n return False\n\n return self.child_sampler.is_sharded()\n\n def get_num_samples(self):\n if self.num_samples is None:\n return None\n return self._get_indices().size\n\n\nclass DistributedSampler(BuiltinSampler):\n \"\"\"\n A sampler that accesses a shard of the dataset.\n\n Args:\n num_shards (int): Number of shards to divide the dataset into.\n shard_id (int): Shard ID of the current shard within num_shards.\n shuffle (bool, optional): If True, the indices are shuffled (default=True).\n num_samples (int, optional): The number of samples to draw (default=None, all elements).\n offset(int, optional): The starting shard ID where the elements in the dataset are sent to (default=-1), which\n should be no more than num_shards.\n\n Examples:\n >>> # creates a distributed sampler with 10 shards in total. This shard is shard 5.\n >>> sampler = ds.DistributedSampler(10, 5)\n >>> dataset = ds.ImageFolderDataset(image_folder_dataset_dir,\n ... num_parallel_workers=8,\n ... sampler=sampler)\n\n Raises:\n TypeError: If num_shards is not an integer value.\n TypeError: If shard_id is not an integer value.\n TypeError: If shuffle is not a boolean value.\n TypeError: If num_samples is not an integer value.\n TypeError: If offset is not an integer value.\n RuntimeError: If num_shards is not a positive value.\n RuntimeError: If shard_id is smaller than 0 or equal to num_shards or larger than num_shards.\n RuntimeError: If num_samples is a negative value.\n RuntimeError: If offset is greater than num_shards.\n \"\"\"\n\n def __init__(self, num_shards, shard_id, shuffle=True, num_samples=None, offset=-1):\n if not isinstance(num_shards, int):\n raise TypeError(\"num_shards must be integer but was: {}.\".format(num_shards))\n\n if not isinstance(shard_id, int):\n raise TypeError(\"shard_id must be integer but was: {}.\".format(shard_id))\n\n if not isinstance(shuffle, bool):\n raise TypeError(\"shuffle must be a boolean value but was: {}.\".format(shuffle))\n\n if num_samples is not None:\n if not isinstance(num_samples, int):\n raise TypeError(\"num_samples must be integer but was: {}.\".format(num_samples))\n if num_samples < 0 or num_samples > validator.INT64_MAX:\n raise ValueError(\"num_samples exceeds the boundary between {} and {}(INT64_MAX)!\"\n .format(0, validator.INT64_MAX))\n\n if not isinstance(offset, int):\n raise TypeError(\"offset must be integer but was: {}.\".format(offset))\n\n self.num_shards = num_shards\n self.shard_id = shard_id\n self.shuffle = shuffle\n self.seed = 0\n self.offset = offset\n super().__init__(num_samples)\n\n def parse(self):\n num_samples = self.num_samples if self.num_samples is not None else 0\n shuffle = self.shuffle if self.shuffle is not None else True\n offset = self.offset if self.offset is not None else -1\n # each time user calls create_dict_iterator() (to do repeat) sampler would get a different seed to shuffle\n self.seed += 1\n c_sampler = cde.DistributedSamplerObj(self.num_shards, self.shard_id,\n shuffle, num_samples, self.seed, offset, True)\n c_child_sampler = self.parse_child()\n c_sampler.add_child(c_child_sampler)\n return c_sampler\n\n def parse_for_minddataset(self):\n num_samples = self.num_samples if self.num_samples is not None else 0\n c_sampler = cde.MindrecordDistributedSampler(self.num_shards, self.shard_id, self.shuffle,\n self.seed, num_samples, self.offset)\n c_child_sampler = self.parse_child_for_minddataset()\n c_sampler.add_child(c_child_sampler)\n return c_sampler\n\n def is_shuffled(self):\n if self.child_sampler is None:\n return self.shuffle\n\n return self.child_sampler.is_shuffled()\n\n def is_sharded(self):\n if self.child_sampler is None:\n return self.num_shards > 1\n\n return self.child_sampler.is_sharded()\n\n def set_offset(self, offset):\n self.offset = offset\n return self\n\n\nclass PKSampler(BuiltinSampler):\n \"\"\"\n Samples K elements for each P class in the dataset.\n\n Args:\n num_val (int): Number of elements to sample for each class.\n num_class (int, optional): Number of classes to sample (default=None, all classes).\n The parameter does not supported to specify currently.\n shuffle (bool, optional): If True, the class IDs are shuffled (default=False).\n class_column (str, optional): Name of column with class labels for MindDataset (default='label').\n num_samples (int, optional): The number of samples to draw (default=None, all elements).\n\n Examples:\n >>> # creates a PKSampler that will get 3 samples from every class.\n >>> sampler = ds.PKSampler(3)\n >>> dataset = ds.ImageFolderDataset(image_folder_dataset_dir,\n ... num_parallel_workers=8,\n ... sampler=sampler)\n\n Raises:\n TypeError: If num_val is not a positive value.\n TypeError: If shuffle is not a boolean value.\n TypeError: If class_column is not a str value.\n TypeError: If num_samples is not an integer value.\n NotImplementedError: If num_class is not None.\n RuntimeError: If num_val is not a positive value.\n RuntimeError: If num_samples is a negative value.\n \"\"\"\n\n def __init__(self, num_val, num_class=None, shuffle=False, class_column='label', num_samples=None):\n if not isinstance(num_val, int):\n raise TypeError(\"num_val must be integer but was: {}.\".format(num_val))\n\n if num_class is not None:\n raise NotImplementedError(\"Not supported to specify num_class for PKSampler.\")\n\n if not isinstance(shuffle, bool):\n raise TypeError(\"shuffle must be a boolean value but was: {}.\".format(shuffle))\n\n if not isinstance(class_column, str):\n raise TypeError(\"class_column must be a str value but was: {}.\".format(class_column))\n\n if num_samples is not None:\n if not isinstance(num_samples, int):\n raise TypeError(\"num_samples must be integer but was: {}.\".format(num_samples))\n if num_samples < 0 or num_samples > validator.INT64_MAX:\n raise ValueError(\"num_samples exceeds the boundary between {} and {}(INT64_MAX)!\"\n .format(0, validator.INT64_MAX))\n\n self.num_val = num_val\n self.shuffle = shuffle\n self.class_column = class_column # work for minddataset\n super().__init__(num_samples)\n\n def parse(self):\n num_samples = self.num_samples if self.num_samples is not None else 0\n shuffle = self.shuffle if self.shuffle is not None else False\n c_sampler = cde.PKSamplerObj(self.num_val, shuffle, num_samples)\n c_child_sampler = self.parse_child()\n c_sampler.add_child(c_child_sampler)\n return c_sampler\n\n def is_shuffled(self):\n if self.child_sampler is None:\n return self.shuffle\n\n return self.child_sampler.is_shuffled()\n\n def is_sharded(self):\n if self.child_sampler is None:\n return False\n\n return self.child_sampler.is_sharded()\n\n def parse_for_minddataset(self):\n if not self.class_column or not isinstance(self.class_column, str):\n raise ValueError(\"class_column should be a not empty string value, \\\n but got class_column: {}.\".format(class_column))\n num_samples = self.num_samples if self.num_samples is not None else 0\n c_sampler = cde.MindrecordPkSampler(self.num_val, self.class_column, self.shuffle, num_samples)\n c_child_sampler = self.parse_child_for_minddataset()\n c_sampler.add_child(c_child_sampler)\n return c_sampler\n\n\nclass RandomSampler(BuiltinSampler):\n \"\"\"\n Samples the elements randomly.\n\n Args:\n replacement (bool, optional): If True, put the sample ID back for the next draw (default=False).\n num_samples (int, optional): Number of elements to sample (default=None, all elements).\n\n Examples:\n >>> # creates a RandomSampler\n >>> sampler = ds.RandomSampler()\n >>> dataset = ds.ImageFolderDataset(image_folder_dataset_dir,\n ... num_parallel_workers=8,\n ... sampler=sampler)\n\n Raises:\n TypeError: If replacement is not a boolean value.\n TypeError: If num_samples is not an integer value.\n RuntimeError: If num_samples is a negative value.\n \"\"\"\n\n def __init__(self, replacement=False, num_samples=None):\n if not isinstance(replacement, bool):\n raise TypeError(\"replacement must be a boolean value but was: {}.\".format(replacement))\n\n if num_samples is not None:\n if not isinstance(num_samples, int):\n raise TypeError(\"num_samples must be integer but was: {}.\".format(num_samples))\n if num_samples < 0 or num_samples > validator.INT64_MAX:\n raise ValueError(\"num_samples exceeds the boundary between {} and {}(INT64_MAX)!\"\n .format(0, validator.INT64_MAX))\n\n self.deterministic = False\n self.replacement = replacement\n self.reshuffle_each_epoch = True\n super().__init__(num_samples)\n\n def parse(self):\n num_samples = self.num_samples if self.num_samples is not None else 0\n replacement = self.replacement if self.replacement is not None else False\n c_sampler = cde.RandomSamplerObj(replacement, num_samples, self.reshuffle_each_epoch)\n c_child_sampler = self.parse_child()\n c_sampler.add_child(c_child_sampler)\n return c_sampler\n\n def parse_for_minddataset(self):\n num_samples = self.num_samples if self.num_samples is not None else 0\n c_sampler = cde.MindrecordRandomSampler(num_samples, self.replacement, self.reshuffle_each_epoch)\n c_child_sampler = self.parse_child_for_minddataset()\n c_sampler.add_child(c_child_sampler)\n return c_sampler\n\n def is_shuffled(self):\n return True\n\n def is_sharded(self):\n if self.child_sampler is None:\n return False\n\n return self.child_sampler.is_sharded()\n\n\nclass SequentialSampler(BuiltinSampler):\n \"\"\"\n Samples the dataset elements sequentially, same as not having a sampler.\n\n Args:\n start_index (int, optional): Index to start sampling at. (default=None, start at first ID)\n num_samples (int, optional): Number of elements to sample (default=None, all elements).\n\n Examples:\n >>> # creates a SequentialSampler\n >>> sampler = ds.SequentialSampler()\n >>> dataset = ds.ImageFolderDataset(image_folder_dataset_dir,\n ... num_parallel_workers=8,\n ... sampler=sampler)\n\n Raises:\n TypeError: If start_index is not an integer value.\n TypeError: If num_samples is not an integer value.\n RuntimeError: If start_index is a negative value.\n RuntimeError: If num_samples is a negative value.\n \"\"\"\n\n def __init__(self, start_index=None, num_samples=None):\n if start_index is not None and not isinstance(start_index, int):\n raise TypeError(\"start_index must be integer but was: {}.\".format(start_index))\n\n if num_samples is not None:\n if not isinstance(num_samples, int):\n raise TypeError(\"num_samples must be integer but was: {}.\".format(num_samples))\n if num_samples < 0 or num_samples > validator.INT64_MAX:\n raise ValueError(\"num_samples exceeds the boundary between {} and {}(INT64_MAX)!\"\n .format(0, validator.INT64_MAX))\n\n self.start_index = start_index\n super().__init__(num_samples)\n\n def parse(self):\n start_index = self.start_index if self.start_index is not None else 0\n num_samples = self.num_samples if self.num_samples is not None else 0\n c_sampler = cde.SequentialSamplerObj(start_index, num_samples)\n c_child_sampler = self.parse_child()\n c_sampler.add_child(c_child_sampler)\n return c_sampler\n\n def parse_for_minddataset(self):\n start_index = self.start_index if self.start_index is not None else 0\n num_samples = self.num_samples if self.num_samples is not None else 0\n c_sampler = cde.MindrecordSequentialSampler(num_samples, start_index)\n c_child_sampler = self.parse_child_for_minddataset()\n c_sampler.add_child(c_child_sampler)\n return c_sampler\n\n def is_shuffled(self):\n if self.child_sampler is None:\n return False\n\n return self.child_sampler.is_shuffled()\n\n def is_sharded(self):\n if self.child_sampler is None:\n return False\n\n return self.child_sampler.is_sharded()\n\n\nclass SubsetSampler(BuiltinSampler):\n \"\"\"\n Samples the elements from a sequence of indices.\n\n Args:\n indices (list[int]): A sequence of indices.\n num_samples (int, optional): Number of elements to sample (default=None, all elements).\n\n Examples:\n >>> indices = [0, 1, 2, 3, 4, 5]\n >>>\n >>> # creates a SubsetRandomSampler, will sample from the provided indices\n >>> sampler = ds.SubsetRandomSampler(indices)\n >>> dataset = ds.ImageFolderDataset(image_folder_dataset_dir,\n ... num_parallel_workers=8,\n ... sampler=sampler)\n\n Raises:\n TypeError: If type of indices element is not a number.\n TypeError: If num_samples is not an integer value.\n RuntimeError: If num_samples is a negative value.\n \"\"\"\n\n def __init__(self, indices, num_samples=None):\n if not isinstance(indices, list):\n indices = [indices]\n\n for i, item in enumerate(indices):\n if not isinstance(item, int):\n raise TypeError(\"SubsetSampler: Type of indices element must be int, \"\n \"but got list[{}]: {}, type: {}.\".format(i, item, type(item)))\n\n if num_samples is not None:\n if not isinstance(num_samples, int):\n raise TypeError(\"num_samples must be integer but was: {}.\".format(num_samples))\n if num_samples < 0 or num_samples > validator.INT64_MAX:\n raise ValueError(\"num_samples exceeds the boundary between {} and {}(INT64_MAX)!\"\n .format(0, validator.INT64_MAX))\n\n self.indices = indices\n super().__init__(num_samples)\n\n def parse(self):\n num_samples = self.num_samples if self.num_samples is not None else 0\n c_sampler = cde.SubsetSamplerObj(self.indices, num_samples)\n c_child_sampler = self.parse_child()\n c_sampler.add_child(c_child_sampler)\n return c_sampler\n\n def is_shuffled(self):\n return False\n\n def is_sharded(self):\n if self.child_sampler is None:\n return False\n\n return self.child_sampler.is_sharded()\n\n def parse_for_minddataset(self):\n c_sampler = cde.MindrecordSubsetSampler(self.indices)\n c_child_sampler = self.parse_child_for_minddataset()\n c_sampler.add_child(c_child_sampler)\n return c_sampler\n\n def get_num_samples(self):\n num_samples = super().get_num_samples()\n if num_samples is None:\n return len(self.indices)\n\n return min(len(self.indices), num_samples)\n\n\nclass SubsetRandomSampler(SubsetSampler):\n \"\"\"\n Samples the elements randomly from a sequence of indices.\n\n Args:\n indices (list[int]): A sequence of indices.\n num_samples (int, optional): Number of elements to sample (default=None, all elements).\n\n Examples:\n >>> import mindspore.dataset as ds\n >>>\n >>> dataset_dir = \"path/to/imagefolder_directory\"\n >>>\n >>> indices = [0, 1, 2, 3, 7, 88, 119]\n >>>\n >>> # creates a SubsetRandomSampler, will sample from the provided indices\n >>> sampler = ds.SubsetRandomSampler(indices)\n >>> data = ds.ImageFolderDataset(dataset_dir, num_parallel_workers=8, sampler=sampler)\n\n Raises:\n TypeError: If type of indices element is not a number.\n TypeError: If num_samples is not an integer value.\n RuntimeError: If num_samples is a negative value.\n \"\"\"\n\n def parse(self):\n num_samples = self.num_samples if self.num_samples is not None else 0\n c_sampler = cde.SubsetRandomSamplerObj(self.indices, num_samples)\n c_child_sampler = self.parse_child()\n c_sampler.add_child(c_child_sampler)\n return c_sampler\n\n def is_shuffled(self):\n return True\n\n def parse_for_minddataset(self):\n c_sampler = cde.MindrecordSubsetSampler(self.indices, ds.config.get_seed())\n c_child_sampler = self.parse_child_for_minddataset()\n c_sampler.add_child(c_child_sampler)\n return c_sampler\n\n\nclass WeightedRandomSampler(BuiltinSampler):\n \"\"\"\n Samples the elements from [0, len(weights) - 1] randomly with the given weights (probabilities).\n\n Args:\n weights (list[float, int]): A sequence of weights, not necessarily summing up to 1.\n num_samples (int, optional): Number of elements to sample (default=None, all elements).\n replacement (bool): If True, put the sample ID back for the next draw (default=True).\n\n Examples:\n >>> weights = [0.9, 0.01, 0.4, 0.8, 0.1, 0.1, 0.3]\n >>>\n >>> # creates a WeightedRandomSampler that will sample 4 elements without replacement\n >>> sampler = ds.WeightedRandomSampler(weights, 4)\n >>> dataset = ds.ImageFolderDataset(image_folder_dataset_dir,\n ... num_parallel_workers=8,\n ... sampler=sampler)\n\n Raises:\n TypeError: If type of weights element is not a number.\n TypeError: If num_samples is not an integer value.\n TypeError: If replacement is not a boolean value.\n RuntimeError: If weights is empty or all zero.\n RuntimeError: If num_samples is a negative value.\n \"\"\"\n\n def __init__(self, weights, num_samples=None, replacement=True):\n if not isinstance(weights, list):\n weights = [weights]\n\n for ind, w in enumerate(weights):\n if not isinstance(w, numbers.Number):\n raise TypeError(\"type of weights element must be number, \"\n \"but got w[{}]: {}, type: {}.\".format(ind, w, type(w)))\n\n if num_samples is not None:\n if not isinstance(num_samples, int):\n raise TypeError(\"num_samples must be integer but was: {}.\".format(num_samples))\n if num_samples < 0 or num_samples > validator.INT64_MAX:\n raise ValueError(\"num_samples exceeds the boundary between {} and {}(INT64_MAX)!\"\n .format(0, validator.INT64_MAX))\n\n if not isinstance(replacement, bool):\n raise TypeError(\"replacement must be a boolean value but was: {}.\".format(replacement))\n\n self.weights = weights\n self.replacement = replacement\n super().__init__(num_samples)\n\n def parse(self):\n num_samples = self.num_samples if self.num_samples is not None else 0\n replacement = self.replacement if self.replacement is not None else True\n c_sampler = cde.WeightedRandomSamplerObj(self.weights, num_samples, replacement)\n c_child_sampler = self.parse_child()\n c_sampler.add_child(c_child_sampler)\n return c_sampler\n\n def is_shuffled(self):\n return True\n\n def is_sharded(self):\n if self.child_sampler is None:\n return False\n\n return self.child_sampler.is_sharded()\n"
] |
[
[
"numpy.concatenate",
"numpy.ones",
"numpy.zeros"
],
[
"numpy.ones"
],
[
"numpy.full",
"numpy.ones"
],
[
"numpy.array"
]
] |
imskr/Machine-Learning-with-Maths
|
[
"ca8e7565bb01a2164fba1a1dc3de617b81c88116"
] |
[
"Linear Regression/univariate_Linear_Regression.py"
] |
[
"import numpy as np\n\nclass univariate_Linear_Regression:\n # initialize slope and intercept\n def __init__(self):\n self.m = 0.0 # slope\n self.b = 0.0 # intercept\n\n# sum of square deviation for single variable\n def ss_x(self, x):\n return sum((x-np.mean(x))**2)\n\n # sum of square deviation for two variables x and y\n def ss_xy(self, x, y):\n x_mean = np.mean(x)\t\t\t# mean of x\n y_mean = np.mean(y)\t\t\t# mean of y\n return sum((x-x_mean)*(y-y_mean))\n\n # Train our regression model based on shape and size\n def train(self, x, y):\n\n # verify the features and labels are of same size\n assert(len(x) == len(y))\n\n # calculate the slope\n ss_x = self.ss_x(x)\n ss_xy = self.ss_xy(x, y)\n self.m = ss_xy/ss_x\n\n # calculate the intercept\n self.b = (np.mean(y)) - (self.m)*(np.mean(x))\n\n # return the predicted values based on feature and weights\n def predict(self, x):\n predictions = np.zeros(len(x))\n for i in range(len(x)):\n predictions[i] = self.m * x[i] + self.b # Y = mx + b\n return predictions\n\n\n# Dataset to train model\nx = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])\ny = np.array([1.1, 1.9, 2.8, 4, 5.2, 5.8, 6.9, 8.1, 9, 9.9])\n\n# Initialize our model\nreg = univariate_Linear_Regression()\n\n# Train our model with the data\nreg.train(x, y)\n\n# Make a prediction\nprint(reg.predict(x))"
] |
[
[
"numpy.array",
"numpy.mean"
]
] |
bigfoolliu/liu_aistuff
|
[
"aa661d37c05c257ee293285dd0868fb7e8227628"
] |
[
"ai/opencv/image_processing/edge_dectection.py"
] |
[
"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n# author: bigfoolliu\n\n\n\"\"\"\n边缘检测\n\"\"\"\n\nimport cv2\nfrom matplotlib import pyplot as plt\n\nimg = cv2.imread(\"../images/person.jpeg\")\n\n# 检测边缘之后的图像\nedge_img = cv2.Canny(img, 100, 200)\nedge_img1 = cv2.Canny(img, 100, 100)\nedge_img2 = cv2.Canny(img, 200, 200)\n\nimages = [img, edge_img, edge_img1, edge_img2]\n\nfor i in range(len(images)):\n plt.subplot(2, 2, i + 1)\n plt.imshow(images[i])\n\nplt.show()\n"
] |
[
[
"matplotlib.pyplot.show",
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.subplot"
]
] |
icewing1996/self-attentive-parser
|
[
"35ba70951eddefa63a294186077373fbe3e74185"
] |
[
"src/parser/commands/train.py"
] |
[
"# -*- coding: utf-8 -*-\n\nfrom parser import BiaffineParser, Model\nfrom parser.utils import Corpus, TextDataset, Vocab, collate_fn\n\nimport torch\nfrom torch.utils.data import DataLoader\nfrom torch.utils.data.distributed import DistributedSampler\n\nfrom config import Config\n\nimport os\nimport subprocess\nfrom datetime import datetime, timedelta\n\n\nclass Train(object):\n\n def add_subparser(self, name, parser):\n subparser = parser.add_parser(\n name, help='Train a model.'\n )\n subparser.add_argument('--ftrain', default='data/train.conllx',\n help='path to train file')\n subparser.add_argument('--fdev', default='data/dev.conllx',\n help='path to dev file')\n # subparser.add_argument('--ftest', default='data/test.conllx',\n # help='path to test file')\n subparser.add_argument('--ftrain_cache', default='data/binary/trainset',\n help='path to train file cache')\n subparser.add_argument('--fdev_cache', default='data/binary/devset',\n help='path to dev file cache')\n # subparser.add_argument('--ftest_cache', default='testset',\n # help='path to test file cache')\n subparser.set_defaults(func=self)\n\n return subparser\n\n def __call__(self, args):\n\n if args.local_rank == 0:\n print(\"***Start preprocessing the data at {}***\".format(datetime.now()))\n \n train = Corpus.load(args.ftrain)\n dev = Corpus.load(args.fdev)\n # test = Corpus.load(args.ftest)\n\n if not os.path.isfile(args.vocab):\n FNULL = open(os.devnull, 'w')\n cloud_address = os.path.join(args.cloud_address, args.vocab)\n # subprocess.call(['gsutil', 'cp', cloud_address, args.vocab],\n # stdout=FNULL, stderr=subprocess.STDOUT)\n if not os.path.isfile(args.vocab):\n vocab = Vocab.from_corpus(corpus=train, min_freq=2)\n torch.save(vocab, args.vocab)\n FNULL = open(os.devnull, 'w')\n cloud_address = os.path.join(args.cloud_address, args.vocab)\n # subprocess.call(['gsutil', 'cp', args.vocab, cloud_address],\n # stdout=FNULL, stderr=subprocess.STDOUT)\n else:\n vocab = torch.load(args.vocab)\n\n if args.local_rank == 0:\n print(vocab)\n\n print(\"Load the dataset.\")\n\n if not os.path.isfile(args.ftrain_cache):\n if args.local_rank == 0:\n print('Loading trainset from scratch.')\n trainset = TextDataset(vocab.numericalize(train, args.ftrain_cache))\n else:\n if args.local_rank == 0:\n print('Loading trainset from checkpoint.')\n trainset = TextDataset(torch.load(args.ftrain_cache))\n\n if args.local_rank == 0:\n print('***Trainset loaded at {}***'.format(datetime.now()))\n\n if not os.path.isfile(args.fdev_cache):\n if args.local_rank == 0:\n print('Loading devset from scratch.')\n devset = TextDataset(vocab.numericalize(dev, args.fdev_cache))\n else:\n if args.local_rank == 0:\n print('Loading devset from checkpoint.')\n devset = TextDataset(torch.load(args.fdev_cache))\n if args.local_rank == 0:\n print('***Devset loaded at {}***'.format(datetime.now()))\n\n # if not os.path.isfile(args.ftest_cache):\n # if args.local_rank == 0:\n # print('Loading testset from scratch.')\n # testset = TextDataset(vocab.numericalize(test, args.ftest_cache))\n # else:\n # if args.local_rank == 0:\n # print('Loading testset from checkpoint.')\n # testset = TextDataset(torch.load(args.ftest_cache))\n # if args.local_rank == 0:\n # print('***Testset loaded at {}***'.format(datetime.now()))\n\n \n # set the data loaders\n train_sampler = None\n dev_sampler = None\n # test_sampler = None\n \n if args.distributed:\n if args.local_rank == 0:\n print('Building distributed samplers.')\n train_sampler = DistributedSampler(trainset)\n dev_sampler = DistributedSampler(devset)\n # test_sampler = DistributedSampler(testset)\n\n train_loader = DataLoader(dataset=trainset,\n batch_size=Config.batch_size // Config.gradient_accumulation_steps,\n num_workers=0,\n shuffle=(train_sampler is None),\n # pin_memory=True,\n sampler =train_sampler,\n collate_fn=collate_fn)\n dev_loader = DataLoader(dataset=devset,\n batch_size=Config.batch_size,\n num_workers=0,\n shuffle=False,\n # pin_memory=True,\n sampler=dev_sampler,\n collate_fn=collate_fn)\n # test_loader = DataLoader(dataset=testset,\n # batch_size=Config.batch_size,\n # shuffle=False,\n # pin_memory=True,\n # sampler=test_sampler,\n # collate_fn=collate_fn)\n\n if args.local_rank == 0:\n print(f\" size of trainset: {len(trainset)}\")\n print(f\" size of devset: {len(devset)}\")\n # print(f\" size of testset: {len(testset)}\")\n\n print(\"Create the model.\")\n params = {\n 'n_words': vocab.n_train_words,\n 'n_chars': vocab.n_chars,\n 'word_dropout': Config.word_dropout,\n 'n_bert_hidden': Config.n_bert_hidden,\n 'bert_dropout': Config.bert_dropout,\n 'n_mlp_arc': Config.n_mlp_arc,\n 'n_mlp_rel': Config.n_mlp_rel,\n 'mlp_dropout': Config.mlp_dropout,\n 'n_rels': vocab.n_rels,\n 'pad_index': vocab.pad_index\n }\n if args.local_rank == 0:\n for k, v in params.items():\n print(f\" {k}: {v}\")\n network = BiaffineParser(params)\n if torch.cuda.is_available():\n network.to(torch.device('cuda'))\n\n # if args.local_rank == 0:\n # print(f\"{network}\\n\")\n\n last_epoch = 0\n max_metric = 0.0\n # Start training from checkpoint if one exists\n if not os.path.isfile(args.file):\n FNULL = open(os.devnull, 'w')\n cloud_address = os.path.join(args.cloud_address, args.file)\n # subprocess.call(['gsutil', 'cp', cloud_address, args.file], stdout=FNULL, stderr=subprocess.STDOUT)\n \n state = None\n if os.path.isfile(args.file):\n state = torch.load(args.file, map_location='cpu')\n last_epoch = state['last_epoch']\n network = network.load(args.file, args.cloud_address, args.local_rank)\n\n if args.distributed:\n from apex.parallel import DistributedDataParallel\n if args.local_rank == 0:\n print(\"Using {} GPUs for distributed parallel training.\".format(torch.cuda.device_count()))\n network = DistributedDataParallel(network)\n\n elif torch.cuda.device_count() > 1:\n print('Using {} GPUs for data parallel training'.format(torch.cuda.device_count()))\n network = torch.nn.DataParallel(network)\n\n # Scale learning rate based on global batch size ????????\n # args.lr = args.lr*float(args.batch_size*args.world_size)/256.\n\n model = Model(vocab, network)\n if os.path.isfile(args.file):\n try:\n max_metric = state['max_metric']\n print('Resume training for optimizer')\n model.optimizer.load_state_dict(state['optimizer'])\n except:\n print('Optimizer failed to load')\n\n\n model(loaders=(train_loader, dev_loader, dev_loader),\n epochs=Config.epochs,\n patience=Config.patience,\n lr=Config.lr,\n betas=(Config.beta_1, Config.beta_2),\n epsilon=Config.epsilon,\n weight_decay=Config.weight_decay,\n annealing=lambda x: Config.decay ** (x / Config.decay_steps),\n file=args.file,\n last_epoch=last_epoch,\n cloud_address=args.cloud_address,\n args=args,\n gradient_accumulation_steps=Config.gradient_accumulation_steps,\n max_metric=max_metric)\n"
] |
[
[
"torch.device",
"torch.save",
"torch.cuda.device_count",
"torch.cuda.is_available",
"torch.utils.data.DataLoader",
"torch.utils.data.distributed.DistributedSampler",
"torch.load",
"torch.nn.DataParallel"
]
] |
adamwkraft/imgaug
|
[
"6c143483810629b7efee13afd8c93bc647b9df35"
] |
[
"test/test_imgaug.py"
] |
[
"from __future__ import print_function, division, absolute_import\n\nimport time\nimport warnings\n\nimport matplotlib\nmatplotlib.use('Agg') # fix execution of tests involving matplotlib on travis\nimport numpy as np\nimport six.moves as sm\nimport cv2\nimport shapely\nimport shapely.geometry\n\nimport imgaug as ia\nfrom imgaug.imgaug import (\n _quokka_normalize_extract, _compute_resized_shape,\n _convert_points_to_shapely_line_string, _interpolate_point_pair, _interpolate_point_pair,\n _interpolate_points, _interpolate_points_by_max_distance\n)\nfrom imgaug import dtypes as iadt\nfrom imgaug.testutils import reseed\n\n\ndef main():\n time_start = time.time()\n\n test_is_np_array()\n test_is_single_integer()\n test_is_single_float()\n test_is_single_number()\n test_is_iterable()\n test_is_string()\n test_is_single_bool()\n test_is_integer_array()\n test_is_float_array()\n test_is_callable()\n test_caller_name()\n test_seed()\n test_current_random_state()\n test_new_random_state()\n test_dummy_random_state()\n test_copy_random_state()\n test_derive_random_state()\n test_derive_random_states()\n test_forward_random_state()\n test__quokka_normalize_extract()\n test__compute_resized_shape()\n test_quokka()\n test_quokka_square()\n test_quokka_heatmap()\n test_quokka_segmentation_map()\n test_quokka_keypoints()\n test_quokka_bounding_boxes()\n # test_angle_between_vectors()\n test_compute_line_intersection_point()\n test_draw_text()\n test_imresize_many_images()\n test_imresize_single_image()\n test_pad()\n test_compute_paddings_for_aspect_ratio()\n test_pad_to_aspect_ratio()\n test_pool()\n test_avg_pool()\n test_max_pool()\n test_draw_grid()\n # test_show_grid()\n # test_do_assert()\n # test_HooksImages_is_activated()\n # test_HooksImages_is_propagating()\n # test_HooksImages_preprocess()\n # test_HooksImages_postprocess()\n test_Keypoint()\n test_KeypointsOnImage()\n test_BoundingBox()\n test_BoundingBoxesOnImage()\n # test_HeatmapsOnImage_get_arr()\n # test_HeatmapsOnImage_find_global_maxima()\n test_HeatmapsOnImage_draw()\n test_HeatmapsOnImage_draw_on_image()\n test_HeatmapsOnImage_invert()\n test_HeatmapsOnImage_pad()\n test_HeatmapsOnImage_pad_to_aspect_ratio()\n test_HeatmapsOnImage_avg_pool()\n test_HeatmapsOnImage_max_pool()\n test_HeatmapsOnImage_scale()\n # test_HeatmapsOnImage_to_uint8()\n test_HeatmapsOnImage_from_uint8()\n # test_HeatmapsOnImage_from_0to1()\n test_HeatmapsOnImage_change_normalization()\n # test_HeatmapsOnImage_copy()\n # test_HeatmapsOnImage_deepcopy()\n test_SegmentationMapOnImage_bool()\n test_SegmentationMapOnImage_get_arr_int()\n # test_SegmentationMapOnImage_get_arr_bool()\n test_SegmentationMapOnImage_draw()\n test_SegmentationMapOnImage_draw_on_image()\n test_SegmentationMapOnImage_pad()\n test_SegmentationMapOnImage_pad_to_aspect_ratio()\n test_SegmentationMapOnImage_scale()\n test_SegmentationMapOnImage_to_heatmaps()\n test_SegmentationMapOnImage_from_heatmaps()\n test_SegmentationMapOnImage_copy()\n test_SegmentationMapOnImage_deepcopy()\n test_Polygon___init__()\n test_Polygon_xx()\n test_Polygon_yy()\n test_Polygon_xx_int()\n test_Polygon_yy_int()\n test_Polygon_is_valid()\n test_Polygon_area()\n test_Polygon_project()\n test_Polygon_find_closest_point_idx()\n test_Polygon__compute_inside_image_point_mask()\n test_Polygon_is_fully_within_image()\n test_Polygon_is_partly_within_image()\n test_Polygon_is_out_of_image()\n test_Polygon_cut_out_of_image()\n test_Polygon_clip_out_of_image()\n test_Polygon_shift()\n test_Polygon_draw_on_image()\n test_Polygon_extract_from_image()\n test_Polygon_to_shapely_polygon()\n test_Polygon_to_bounding_box()\n test_Polygon_from_shapely()\n test_Polygon_copy()\n test_Polygon_deepcopy()\n test_Polygon___repr__()\n test_Polygon___str__()\n test___convert_points_to_shapely_line_string()\n test__interpolate_point_pair()\n test__interpolate_points()\n test__interpolate_points_by_max_distance()\n # test_Batch()\n\n time_end = time.time()\n print(\"<%s> Finished without errors in %.4fs.\" % (__file__, time_end - time_start,))\n\n\ndef test_is_np_array():\n class _Dummy(object):\n pass\n values_true = [\n np.zeros((1, 2), dtype=np.uint8),\n np.zeros((64, 64, 3), dtype=np.uint8),\n np.zeros((1, 2), dtype=np.float32),\n np.zeros((100,), dtype=np.float64)\n ]\n values_false = [\n \"A\", \"BC\", \"1\", True, False, (1.0, 2.0), [1.0, 2.0], _Dummy(),\n -100, 1, 0, 1, 100, -1.2, -0.001, 0.0, 0.001, 1.2, 1e-4\n ]\n for value in values_true:\n assert ia.is_np_array(value) is True\n for value in values_false:\n assert ia.is_np_array(value) is False\n\n\ndef test_is_single_integer():\n assert ia.is_single_integer(\"A\") is False\n assert ia.is_single_integer(None) is False\n assert ia.is_single_integer(1.2) is False\n assert ia.is_single_integer(1.0) is False\n assert ia.is_single_integer(np.ones((1,), dtype=np.float32)[0]) is False\n assert ia.is_single_integer(1) is True\n assert ia.is_single_integer(1234) is True\n assert ia.is_single_integer(np.ones((1,), dtype=np.uint8)[0]) is True\n assert ia.is_single_integer(np.ones((1,), dtype=np.int32)[0]) is True\n\n\ndef test_is_single_float():\n assert ia.is_single_float(\"A\") is False\n assert ia.is_single_float(None) is False\n assert ia.is_single_float(1.2) is True\n assert ia.is_single_float(1.0) is True\n assert ia.is_single_float(np.ones((1,), dtype=np.float32)[0]) is True\n assert ia.is_single_float(1) is False\n assert ia.is_single_float(1234) is False\n assert ia.is_single_float(np.ones((1,), dtype=np.uint8)[0]) is False\n assert ia.is_single_float(np.ones((1,), dtype=np.int32)[0]) is False\n\n\ndef test_caller_name():\n assert ia.caller_name() == 'test_caller_name'\n\n\ndef test_is_single_number():\n class _Dummy(object):\n pass\n values_true = [-100, 1, 0, 1, 100, -1.2, -0.001, 0.0, 0.001, 1.2, 1e-4]\n values_false = [\"A\", \"BC\", \"1\", True, False, (1.0, 2.0), [1.0, 2.0], _Dummy(), np.zeros((1, 2), dtype=np.uint8)]\n for value in values_true:\n assert ia.is_single_number(value) is True\n for value in values_false:\n assert ia.is_single_number(value) is False\n\n\ndef test_is_iterable():\n class _Dummy(object):\n pass\n values_true = [\n [0, 1, 2],\n [\"A\", \"X\"],\n [[123], [456, 789]],\n [],\n (1, 2, 3),\n (1,),\n tuple(),\n \"A\",\n \"ABC\",\n \"\",\n np.zeros((100,), dtype=np.uint8)\n ]\n values_false = [1, 100, 0, -100, -1, 1.2, -1.2, True, False, _Dummy()]\n for value in values_true:\n assert ia.is_iterable(value) is True, value\n for value in values_false:\n assert ia.is_iterable(value) is False\n\n\ndef test_is_string():\n class _Dummy(object):\n pass\n values_true = [\"A\", \"BC\", \"1\", \"\"]\n values_false = [-100, 1, 0, 1, 100, -1.2, -0.001, 0.0, 0.001, 1.2, 1e-4, True, False, (1.0, 2.0), [1.0, 2.0],\n _Dummy(), np.zeros((1, 2), dtype=np.uint8)]\n for value in values_true:\n assert ia.is_string(value) is True\n for value in values_false:\n assert ia.is_string(value) is False\n\n\ndef test_is_single_bool():\n class _Dummy(object):\n pass\n values_true = [False, True]\n values_false = [-100, 1, 0, 1, 100, -1.2, -0.001, 0.0, 0.001, 1.2, 1e-4, (1.0, 2.0), [1.0, 2.0], _Dummy(),\n np.zeros((1, 2), dtype=np.uint8), np.zeros((1,), dtype=bool)]\n for value in values_true:\n assert ia.is_single_bool(value) is True\n for value in values_false:\n assert ia.is_single_bool(value) is False\n\n\ndef test_is_integer_array():\n class _Dummy(object):\n pass\n values_true = [\n np.zeros((1, 2), dtype=np.uint8),\n np.zeros((100,), dtype=np.uint8),\n np.zeros((1, 2), dtype=np.uint16),\n np.zeros((1, 2), dtype=np.int32),\n np.zeros((1, 2), dtype=np.int64)\n ]\n values_false = [\n \"A\", \"BC\", \"1\", \"\", -100, 1, 0, 1, 100, -1.2, -0.001, 0.0, 0.001, 1.2, 1e-4, True, False,\n (1.0, 2.0), [1.0, 2.0], _Dummy(),\n np.zeros((1, 2), dtype=np.float16),\n np.zeros((100,), dtype=np.float32),\n np.zeros((1, 2), dtype=np.float64),\n np.zeros((1, 2), dtype=np.bool)\n ]\n for value in values_true:\n assert ia.is_integer_array(value) is True\n for value in values_false:\n assert ia.is_integer_array(value) is False\n\n\ndef test_is_float_array():\n class _Dummy(object):\n pass\n\n values_true = [\n np.zeros((1, 2), dtype=np.float16),\n np.zeros((100,), dtype=np.float32),\n np.zeros((1, 2), dtype=np.float64)\n ]\n values_false = [\n \"A\", \"BC\", \"1\", \"\", -100, 1, 0, 1, 100, -1.2, -0.001, 0.0, 0.001, 1.2, 1e-4, True, False,\n (1.0, 2.0), [1.0, 2.0], _Dummy(),\n np.zeros((1, 2), dtype=np.uint8),\n np.zeros((100,), dtype=np.uint8),\n np.zeros((1, 2), dtype=np.uint16),\n np.zeros((1, 2), dtype=np.int32),\n np.zeros((1, 2), dtype=np.int64),\n np.zeros((1, 2), dtype=np.bool)\n ]\n for value in values_true:\n assert ia.is_float_array(value) is True\n for value in values_false:\n assert ia.is_float_array(value) is False\n\n\ndef test_is_callable():\n def _dummy_func():\n pass\n\n _dummy_func2 = lambda x: x\n\n class _Dummy1(object):\n pass\n\n class _Dummy2(object):\n def __call__(self):\n pass\n\n values_true = [_dummy_func, _dummy_func2, _Dummy2()]\n values_false = [\"A\", \"BC\", \"1\", \"\", -100, 1, 0, 1, 100, -1.2, -0.001, 0.0, 0.001, 1.2, 1e-4, True, False,\n (1.0, 2.0), [1.0, 2.0], _Dummy1(), np.zeros((1, 2), dtype=np.uint8)]\n for value in values_true:\n assert ia.is_callable(value) == True\n for value in values_false:\n assert ia.is_callable(value) == False\n\n\ndef test_seed():\n ia.seed(10017)\n rs = np.random.RandomState(10017)\n assert ia.CURRENT_RANDOM_STATE.randint(0, 1000*1000) == rs.randint(0, 1000*1000)\n reseed()\n\n\ndef test_current_random_state():\n assert ia.current_random_state() == ia.CURRENT_RANDOM_STATE\n\n\ndef test_new_random_state():\n seed = 1000\n ia.seed(seed)\n\n rs_observed = ia.new_random_state(seed=None, fully_random=False)\n rs_expected = np.random.RandomState(\n np.random.RandomState(seed).randint(ia.SEED_MIN_VALUE, ia.SEED_MAX_VALUE, 1)[0]\n )\n assert rs_observed.randint(0, 10**6) == rs_expected.randint(0, 10**6)\n rs_observed1 = ia.new_random_state(seed=None, fully_random=False)\n rs_observed2 = ia.new_random_state(seed=None, fully_random=False)\n assert rs_observed1.randint(0, 10**6) != rs_observed2.randint(0, 10**6)\n\n ia.seed(seed)\n np.random.seed(seed)\n rs_observed = ia.new_random_state(seed=None, fully_random=True)\n rs_not_expected = np.random.RandomState(\n np.random.RandomState(seed).randint(ia.SEED_MIN_VALUE, ia.SEED_MAX_VALUE, 1)[0]\n )\n assert rs_observed.randint(0, 10**6) != rs_not_expected.randint(0, 10**6)\n\n rs_observed1 = ia.new_random_state(seed=None, fully_random=True)\n rs_observed2 = ia.new_random_state(seed=None, fully_random=True)\n assert rs_observed1.randint(0, 10**6) != rs_observed2.randint(0, 10**6)\n\n rs_observed1 = ia.new_random_state(seed=1234)\n rs_observed2 = ia.new_random_state(seed=1234)\n rs_expected = np.random.RandomState(1234)\n assert rs_observed1.randint(0, 10**6) == rs_observed2.randint(0, 10**6) == rs_expected.randint(0, 10**6)\n\n\ndef test_dummy_random_state():\n assert ia.dummy_random_state().randint(0, 10**6) == np.random.RandomState(1).randint(0, 10**6)\n\n\ndef test_copy_random_state():\n rs = np.random.RandomState(1017)\n rs_copy = ia.copy_random_state(rs)\n assert rs != rs_copy\n assert rs.randint(0, 10**6) == rs_copy.randint(0, 10**6)\n\n assert ia.copy_random_state(np.random) == np.random\n assert ia.copy_random_state(np.random, force_copy=True) != np.random\n\n\ndef test_derive_random_state():\n rs_observed = ia.derive_random_state(np.random.RandomState(1017))\n rs_expected = np.random.RandomState(np.random.RandomState(1017).randint(ia.SEED_MIN_VALUE, ia.SEED_MAX_VALUE))\n assert rs_observed.randint(0, 10**6) == rs_expected.randint(0, 10**6)\n\n\ndef test_derive_random_states():\n rs_observed1, rs_observed2 = ia.derive_random_states(np.random.RandomState(1017), n=2)\n seed = np.random.RandomState(1017).randint(ia.SEED_MIN_VALUE, ia.SEED_MAX_VALUE)\n rs_expected1 = np.random.RandomState(seed+0)\n rs_expected2 = np.random.RandomState(seed+1)\n assert rs_observed1.randint(0, 10**6) == rs_expected1.randint(0, 10**6)\n assert rs_observed2.randint(0, 10**6) == rs_expected2.randint(0, 10**6)\n\n\ndef test_forward_random_state():\n rs1 = np.random.RandomState(1017)\n rs2 = np.random.RandomState(1017)\n ia.forward_random_state(rs1)\n rs2.uniform()\n assert rs1.randint(0, 10**6) == rs2.randint(0, 10**6)\n\n\ndef test__quokka_normalize_extract():\n observed = _quokka_normalize_extract(\"square\")\n assert isinstance(observed, ia.BoundingBox)\n assert observed.x1 == 0\n assert observed.y1 == 0\n assert observed.x2 == 643\n assert observed.y2 == 643\n\n observed = _quokka_normalize_extract((1, 1, 644, 642))\n assert isinstance(observed, ia.BoundingBox)\n assert observed.x1 == 1\n assert observed.y1 == 1\n assert observed.x2 == 644\n assert observed.y2 == 642\n\n observed = _quokka_normalize_extract(ia.BoundingBox(x1=1, y1=1, x2=644, y2=642))\n assert isinstance(observed, ia.BoundingBox)\n assert observed.x1 == 1\n assert observed.y1 == 1\n assert observed.x2 == 644\n assert observed.y2 == 642\n\n observed = _quokka_normalize_extract(\n ia.BoundingBoxesOnImage([ia.BoundingBox(x1=1, y1=1, x2=644, y2=642)], shape=(643, 960, 3))\n )\n assert isinstance(observed, ia.BoundingBox)\n assert observed.x1 == 1\n assert observed.y1 == 1\n assert observed.x2 == 644\n assert observed.y2 == 642\n\n got_exception = False\n try:\n _ = _quokka_normalize_extract(False)\n except Exception as exc:\n assert \"Expected 'square' or tuple\" in str(exc)\n got_exception = True\n assert got_exception\n\n\ndef test__compute_resized_shape():\n # tuple of ints\n from_shape = (10, 15, 3)\n to_shape = (20, 30)\n observed = _compute_resized_shape(from_shape, to_shape)\n assert observed == (20, 30, 3)\n\n from_shape = (10, 15, 3)\n to_shape = (20, 30, 3)\n observed = _compute_resized_shape(from_shape, to_shape)\n assert observed == (20, 30, 3)\n\n # tuple of floats\n from_shape = (10, 15, 3)\n to_shape = (2.0, 3.0)\n observed = _compute_resized_shape(from_shape, to_shape)\n assert observed == (20, 45, 3)\n\n # tuple of int and float\n from_shape = (10, 15, 3)\n to_shape = (2.0, 25)\n observed = _compute_resized_shape(from_shape, to_shape)\n assert observed == (20, 25, 3)\n\n from_shape = (10, 17, 3)\n to_shape = (15, 2.0)\n observed = _compute_resized_shape(from_shape, to_shape)\n assert observed == (15, 34, 3)\n\n # None\n from_shape = (10, 10, 3)\n to_shape = None\n observed = _compute_resized_shape(from_shape, to_shape)\n assert observed == from_shape\n\n # tuple containing None\n from_shape = (10, 15, 3)\n to_shape = (2.0, None)\n observed = _compute_resized_shape(from_shape, to_shape)\n assert observed == (20, 15, 3)\n\n from_shape = (10, 15, 3)\n to_shape = (None, 25)\n observed = _compute_resized_shape(from_shape, to_shape)\n assert observed == (10, 25, 3)\n\n # single int\n from_shape = (10, 15, 3)\n to_shape = 20\n observed = _compute_resized_shape(from_shape, to_shape)\n assert observed == (20, 20, 3)\n\n # single float\n from_shape = (10, 15, 3)\n to_shape = 2.0\n observed = _compute_resized_shape(from_shape, to_shape)\n assert observed == (20, 30, 3)\n\n # from/to shape as arrays\n from_shape = (10, 10, 3)\n to_shape = (20, 30, 3)\n observed = _compute_resized_shape(np.zeros(from_shape), np.zeros(to_shape))\n assert observed == to_shape\n\n # from_shape is 2D\n from_shape = (10, 15)\n to_shape = (20, 30)\n observed = _compute_resized_shape(from_shape, to_shape)\n assert observed == to_shape\n\n from_shape = (10, 15)\n to_shape = (20, 30, 3)\n observed = _compute_resized_shape(from_shape, to_shape)\n assert observed == (20, 30, 3)\n\n\ndef test_quokka():\n img = ia.quokka()\n assert img.shape == (643, 960, 3)\n assert np.allclose(\n np.average(img, axis=(0, 1)),\n [107.93576659, 118.18765066, 122.99378564]\n )\n\n img = ia.quokka(extract=\"square\")\n assert img.shape == (643, 643, 3)\n assert np.allclose(\n np.average(img, axis=(0, 1)),\n [111.25929196, 121.19431175, 125.71316898]\n )\n\n img = ia.quokka(size=(642, 959))\n assert img.shape == (642, 959, 3)\n assert np.allclose(\n np.average(img, axis=(0, 1)),\n [107.84615822, 118.09832412, 122.90446467]\n )\n\n\ndef test_quokka_square():\n img = ia.quokka_square()\n assert img.shape == (643, 643, 3)\n assert np.allclose(\n np.average(img, axis=(0, 1)),\n [111.25929196, 121.19431175, 125.71316898]\n )\n\n\ndef test_quokka_heatmap():\n hm = ia.quokka_heatmap()\n assert hm.shape == (643, 960, 3)\n assert hm.arr_0to1.shape == (643, 960, 1)\n assert np.allclose(np.average(hm.arr_0to1), 0.57618505)\n\n hm = ia.quokka_heatmap(extract=\"square\")\n assert hm.shape == (643, 643, 3)\n assert hm.arr_0to1.shape == (643, 643, 1)\n # TODO this value is 0.48026073 in python 2.7, while 0.48026952 in 3.7 -- why?\n assert np.allclose(np.average(hm.arr_0to1), 0.48026952, atol=1e-4)\n\n hm = ia.quokka_heatmap(size=(642, 959))\n assert hm.shape == (642, 959, 3)\n assert hm.arr_0to1.shape == (642, 959, 1)\n assert np.allclose(np.average(hm.arr_0to1), 0.5762454)\n\n\ndef test_quokka_segmentation_map():\n segmap = ia.quokka_segmentation_map()\n assert segmap.shape == (643, 960, 3)\n assert segmap.arr.shape == (643, 960, 1)\n assert np.allclose(np.average(segmap.arr), 0.3016427)\n\n segmap = ia.quokka_segmentation_map(extract=\"square\")\n assert segmap.shape == (643, 643, 3)\n assert segmap.arr.shape == (643, 643, 1)\n assert np.allclose(np.average(segmap.arr), 0.450353)\n\n segmap = ia.quokka_segmentation_map(size=(642, 959))\n assert segmap.shape == (642, 959, 3)\n assert segmap.arr.shape == (642, 959, 1)\n assert np.allclose(np.average(segmap.arr), 0.30160266)\n\n\ndef test_quokka_keypoints():\n kpsoi = ia.quokka_keypoints()\n assert len(kpsoi.keypoints) > 0\n assert np.allclose(kpsoi.keypoints[0].x, 163.0)\n assert np.allclose(kpsoi.keypoints[0].y, 78.0)\n assert kpsoi.shape == (643, 960, 3)\n\n img = ia.quokka()\n patches = []\n for kp in kpsoi.keypoints:\n bb = ia.BoundingBox(x1=kp.x-1, x2=kp.x+2, y1=kp.y-1, y2=kp.y+2)\n patches.append(bb.extract_from_image(img))\n\n img_square = ia.quokka(extract=\"square\")\n kpsoi_square = ia.quokka_keypoints(extract=\"square\")\n assert len(kpsoi.keypoints) == len(kpsoi_square.keypoints)\n assert kpsoi_square.shape == (643, 643, 3)\n\n for kp, patch in zip(kpsoi_square.keypoints, patches):\n bb = ia.BoundingBox(x1=kp.x-1, x2=kp.x+2, y1=kp.y-1, y2=kp.y+2)\n patch_square = bb.extract_from_image(img_square)\n assert np.average(np.abs(patch.astype(np.float32) - patch_square.astype(np.float32))) < 1.0\n\n kpsoi_resized = ia.quokka_keypoints(size=(642, 959))\n assert kpsoi_resized.shape == (642, 959, 3)\n assert len(kpsoi.keypoints) == len(kpsoi_resized.keypoints)\n for kp, kp_resized in zip(kpsoi.keypoints, kpsoi_resized.keypoints):\n d = np.sqrt((kp.x - kp_resized.x) ** 2 + (kp.y - kp_resized.y) ** 2)\n assert d < 1.0\n\n\ndef test_quokka_bounding_boxes():\n bbsoi = ia.quokka_bounding_boxes()\n assert len(bbsoi.bounding_boxes) > 0\n bb0 = bbsoi.bounding_boxes[0]\n assert np.allclose(bb0.x1, 148.0)\n assert np.allclose(bb0.y1, 50.0)\n assert np.allclose(bb0.x2, 550.0)\n assert np.allclose(bb0.y2, 642.0)\n assert bbsoi.shape == (643, 960, 3)\n\n img = ia.quokka()\n patches = []\n for bb in bbsoi.bounding_boxes:\n patches.append(bb.extract_from_image(img))\n\n img_square = ia.quokka(extract=\"square\")\n bbsoi_square = ia.quokka_bounding_boxes(extract=\"square\")\n assert len(bbsoi.bounding_boxes) == len(bbsoi_square.bounding_boxes)\n assert bbsoi_square.shape == (643, 643, 3)\n\n for bb, patch in zip(bbsoi_square.bounding_boxes, patches):\n patch_square = bb.extract_from_image(img_square)\n assert np.average(np.abs(patch.astype(np.float32) - patch_square.astype(np.float32))) < 1.0\n\n bbsoi_resized = ia.quokka_bounding_boxes(size=(642, 959))\n assert bbsoi_resized.shape == (642, 959, 3)\n assert len(bbsoi.bounding_boxes) == len(bbsoi_resized.bounding_boxes)\n for bb, bb_resized in zip(bbsoi.bounding_boxes, bbsoi_resized.bounding_boxes):\n d = np.sqrt((bb.center_x - bb_resized.center_x) ** 2 + (bb.center_y - bb_resized.center_y) ** 2)\n assert d < 1.0\n\n\ndef test_compute_line_intersection_point():\n # intersecting lines\n line1 = (0, 0, 1, 0)\n line2 = (0.5, -1, 0.5, 1)\n point = ia.compute_line_intersection_point(\n line1[0], line1[1], line1[2], line1[3],\n line2[0], line2[1], line2[2], line2[3]\n )\n assert np.allclose(point[0], 0.5)\n assert np.allclose(point[1], 0)\n\n # intersection point outside of defined interval of one line, should not change anything\n line1 = (0, 0, 1, 0)\n line2 = (0.5, -1, 0.5, -0.5)\n point = ia.compute_line_intersection_point(\n line1[0], line1[1], line1[2], line1[3],\n line2[0], line2[1], line2[2], line2[3]\n )\n assert np.allclose(point[0], 0.5)\n assert np.allclose(point[1], 0)\n\n # touching lines\n line1 = (0, 0, 1, 0)\n line2 = (0.5, -1, 0.5, 0)\n point = ia.compute_line_intersection_point(\n line1[0], line1[1], line1[2], line1[3],\n line2[0], line2[1], line2[2], line2[3]\n )\n assert np.allclose(point[0], 0.5)\n assert np.allclose(point[1], 0)\n\n # parallel, not intersecting lines\n line1 = (0, 0, 1, 0)\n line2 = (0, -0.1, 1, -0.1)\n point = ia.compute_line_intersection_point(\n line1[0], line1[1], line1[2], line1[3],\n line2[0], line2[1], line2[2], line2[3]\n )\n assert point is False\n\n # parallel and overlapping lines (infinite intersection points)\n line1 = (0, 0, 1, 0)\n line2 = (0.1, 0, 1, 0)\n point = ia.compute_line_intersection_point(\n line1[0], line1[1], line1[2], line1[3],\n line2[0], line2[1], line2[2], line2[3]\n )\n assert point is False\n\n\ndef test_draw_text():\n # make roughly sure that shape of drawn text matches expected text\n img = np.zeros((20, 50, 3), dtype=np.uint8)\n img_text = ia.draw_text(img, y=5, x=5, text=\"---------\", size=10, color=[255, 255, 255])\n assert np.max(img_text) == 255\n assert np.min(img_text) == 0\n assert np.sum(img_text == 255) / np.sum(img_text == 0)\n first_row = None\n last_row = None\n first_col = None\n last_col = None\n for i in range(img.shape[0]):\n if np.max(img_text[i, :, :]) == 255:\n first_row = i\n break\n for i in range(img.shape[0]-1, 0, -1):\n if np.max(img_text[i, :, :]) == 255:\n last_row = i\n break\n for i in range(img.shape[1]):\n if np.max(img_text[:, i, :]) == 255:\n first_col = i\n break\n for i in range(img.shape[1]-1, 0, -1):\n if np.max(img_text[:, i, :]) == 255:\n last_col = i\n break\n bb = ia.BoundingBox(x1=first_col, y1=first_row, x2=last_col, y2=last_row)\n assert bb.width > 4.0*bb.height\n\n # test x\n img = np.zeros((20, 100, 3), dtype=np.uint8)\n img_text1 = ia.draw_text(img, y=5, x=5, text=\"XXXXXXX\", size=10, color=[255, 255, 255])\n img_text2 = ia.draw_text(img, y=5, x=50, text=\"XXXXXXX\", size=10, color=[255, 255, 255])\n first_col1 = None\n first_col2 = None\n for i in range(img.shape[1]):\n if np.max(img_text1[:, i, :]) == 255:\n first_col1 = i\n break\n for i in range(img.shape[1]):\n if np.max(img_text2[:, i, :]) == 255:\n first_col2 = i\n break\n assert 0 < first_col1 < 10\n assert 45 < first_col2 < 55\n\n # test y\n img = np.zeros((100, 20, 3), dtype=np.uint8)\n img_text1 = ia.draw_text(img, y=5, x=5, text=\"XXXXXXX\", size=10, color=[255, 255, 255])\n img_text2 = ia.draw_text(img, y=50, x=5, text=\"XXXXXXX\", size=10, color=[255, 255, 255])\n first_row1 = None\n first_row2 = None\n for i in range(img.shape[0]):\n if np.max(img_text1[i, :, :]) == 255:\n first_row1 = i\n break\n for i in range(img.shape[0]):\n if np.max(img_text2[i, :, :]) == 255:\n first_row2 = i\n break\n assert 0 < first_row1 < 15\n assert 45 < first_row2 < 60\n\n # test size\n img = np.zeros((100, 100, 3), dtype=np.uint8)\n img_text_small = ia.draw_text(img, y=5, x=5, text=\"X\", size=10, color=[255, 255, 255])\n img_text_large = ia.draw_text(img, y=5, x=5, text=\"X\", size=50, color=[255, 255, 255])\n nb_filled_small = np.sum(img_text_small > 10)\n nb_filled_large = np.sum(img_text_large > 10)\n assert nb_filled_large > 2*nb_filled_small\n\n # text color\n img = np.zeros((20, 20, 3), dtype=np.uint8)\n img_text = ia.draw_text(img, y=5, x=5, text=\"X\", size=10, color=[128, 129, 130])\n maxcol = np.max(img_text, axis=(0, 1))\n assert maxcol[0] == 128\n assert maxcol[1] == 129\n assert maxcol[2] == 130\n\n\ndef test_imresize_many_images():\n interpolations = [None,\n \"nearest\", \"linear\", \"area\", \"cubic\",\n cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_AREA, cv2.INTER_CUBIC]\n\n for c in [1, 3]:\n image1 = np.zeros((16, 16, c), dtype=np.uint8) + 255\n image2 = np.zeros((16, 16, c), dtype=np.uint8)\n image3 = np.pad(\n np.zeros((8, 8, c), dtype=np.uint8) + 255,\n ((4, 4), (4, 4), (0, 0)),\n mode=\"constant\",\n constant_values=0\n )\n\n image1_small = np.zeros((8, 8, c), dtype=np.uint8) + 255\n image2_small = np.zeros((8, 8, c), dtype=np.uint8)\n image3_small = np.pad(\n np.zeros((4, 4, c), dtype=np.uint8) + 255,\n ((2, 2), (2, 2), (0, 0)),\n mode=\"constant\",\n constant_values=0\n )\n\n image1_large = np.zeros((32, 32, c), dtype=np.uint8) + 255\n image2_large = np.zeros((32, 32, c), dtype=np.uint8)\n image3_large = np.pad(\n np.zeros((16, 16, c), dtype=np.uint8) + 255,\n ((8, 8), (8, 8), (0, 0)),\n mode=\"constant\",\n constant_values=0\n )\n\n images = np.uint8([image1, image2, image3])\n images_small = np.uint8([image1_small, image2_small, image3_small])\n images_large = np.uint8([image1_large, image2_large, image3_large])\n\n for images_this_iter in [images, list(images)]: # test for ndarray and list(ndarray) input\n for interpolation in interpolations:\n images_same_observed = ia.imresize_many_images(images_this_iter, (16, 16), interpolation=interpolation)\n for image_expected, image_observed in zip(images_this_iter, images_same_observed):\n diff = np.abs(image_expected.astype(np.int32) - image_observed.astype(np.int32))\n assert np.sum(diff) == 0\n\n for interpolation in interpolations:\n images_small_observed = ia.imresize_many_images(images_this_iter, (8, 8), interpolation=interpolation)\n for image_expected, image_observed in zip(images_small, images_small_observed):\n diff = np.abs(image_expected.astype(np.int32) - image_observed.astype(np.int32))\n diff_fraction = np.sum(diff) / (image_observed.size * 255)\n assert diff_fraction < 0.5\n\n for interpolation in interpolations:\n images_large_observed = ia.imresize_many_images(images_this_iter, (32, 32), interpolation=interpolation)\n for image_expected, image_observed in zip(images_large, images_large_observed):\n diff = np.abs(image_expected.astype(np.int32) - image_observed.astype(np.int32))\n diff_fraction = np.sum(diff) / (image_observed.size * 255)\n assert diff_fraction < 0.5\n\n # test size given as single int\n images = np.zeros((1, 4, 4, 3), dtype=np.uint8)\n observed = ia.imresize_many_images(images, 8)\n assert observed.shape == (1, 8, 8, 3)\n\n # test size given as single float\n images = np.zeros((1, 4, 4, 3), dtype=np.uint8)\n observed = ia.imresize_many_images(images, 2.0)\n assert observed.shape == (1, 8, 8, 3)\n\n images = np.zeros((1, 4, 4, 3), dtype=np.uint8)\n observed = ia.imresize_many_images(images, 0.5)\n assert observed.shape == (1, 2, 2, 3)\n\n # test size given as (float, float)\n images = np.zeros((1, 4, 4, 3), dtype=np.uint8)\n observed = ia.imresize_many_images(images, (2.0, 2.0))\n assert observed.shape == (1, 8, 8, 3)\n\n images = np.zeros((1, 4, 4, 3), dtype=np.uint8)\n observed = ia.imresize_many_images(images, (0.5, 0.5))\n assert observed.shape == (1, 2, 2, 3)\n\n images = np.zeros((1, 4, 4, 3), dtype=np.uint8)\n observed = ia.imresize_many_images(images, (2.0, 0.5))\n assert observed.shape == (1, 8, 2, 3)\n\n images = np.zeros((1, 4, 4, 3), dtype=np.uint8)\n observed = ia.imresize_many_images(images, (0.5, 2.0))\n assert observed.shape == (1, 2, 8, 3)\n\n # test size given as int+float or float+int\n images = np.zeros((1, 4, 4, 3), dtype=np.uint8)\n observed = ia.imresize_many_images(images, (11, 2.0))\n assert observed.shape == (1, 11, 8, 3)\n\n images = np.zeros((1, 4, 4, 3), dtype=np.uint8)\n observed = ia.imresize_many_images(images, (2.0, 11))\n assert observed.shape == (1, 8, 11, 3)\n\n # test no channels\n images = np.zeros((1, 4, 4), dtype=np.uint8)\n images_rs = ia.imresize_many_images(images, (2, 2))\n assert images_rs.shape == (1, 2, 2)\n\n images = [np.zeros((4, 4), dtype=np.uint8)]\n images_rs = ia.imresize_many_images(images, (2, 2))\n assert isinstance(images_rs, list)\n assert images_rs[0].shape == (2, 2)\n\n # test len 0 input\n observed = ia.imresize_many_images(np.zeros((0, 8, 8, 3), dtype=np.uint8), (4, 4))\n assert ia.is_np_array(observed)\n assert observed.dtype.type == np.uint8\n assert len(observed) == 0\n\n observed = ia.imresize_many_images([], (4, 4))\n assert isinstance(observed, list)\n assert len(observed) == 0\n\n # test images with zero height/width\n images = [np.zeros((0, 4, 3), dtype=np.uint8)]\n got_exception = False\n try:\n _ = ia.imresize_many_images(images, sizes=(2, 2))\n except Exception as exc:\n assert \"Cannot resize images, because at least one image has a height and/or width of zero.\" in str(exc)\n got_exception = True\n assert got_exception\n\n images = [np.zeros((4, 0, 3), dtype=np.uint8)]\n got_exception = False\n try:\n _ = ia.imresize_many_images(images, sizes=(2, 2))\n except Exception as exc:\n assert \"Cannot resize images, because at least one image has a height and/or width of zero.\" in str(exc)\n got_exception = True\n assert got_exception\n\n images = [np.zeros((0, 0, 3), dtype=np.uint8)]\n got_exception = False\n try:\n _ = ia.imresize_many_images(images, sizes=(2, 2))\n except Exception as exc:\n assert \"Cannot resize images, because at least one image has a height and/or width of zero.\" in str(exc)\n got_exception = True\n assert got_exception\n\n # test invalid sizes\n sizes_all = [(-1, 2), (0, 2)]\n sizes_all = sizes_all\\\n + [(float(a), b) for a, b in sizes_all]\\\n + [(a, float(b)) for a, b in sizes_all]\\\n + [(float(a), float(b)) for a, b in sizes_all]\\\n + [(-a, -b) for a, b in sizes_all]\\\n + [(-float(a), -b) for a, b in sizes_all]\\\n + [(-a, -float(b)) for a, b in sizes_all]\\\n + [(-float(a), -float(b)) for a, b in sizes_all]\n sizes_all = sizes_all\\\n + [(b, a) for a, b in sizes_all]\n sizes_all = sizes_all\\\n + [-1.0, 0.0, -1, 0]\n for sizes in sizes_all:\n images = [np.zeros((4, 4, 3), dtype=np.uint8)]\n got_exception = False\n try:\n _ = ia.imresize_many_images(images, sizes=sizes)\n except Exception as exc:\n assert \"value is zero or lower than zero.\" in str(exc)\n got_exception = True\n assert got_exception\n\n # test list input but all with same shape\n images = [np.zeros((8, 8, 3), dtype=np.uint8) for _ in range(2)]\n observed = ia.imresize_many_images(images, (4, 4))\n assert isinstance(observed, list)\n assert all([image.shape == (4, 4, 3) for image in observed])\n assert all([image.dtype.type == np.uint8 for image in observed])\n\n # test multiple shapes\n images = [np.zeros((8, 8, 3), dtype=np.uint8), np.zeros((4, 4), dtype=np.uint8)]\n observed = ia.imresize_many_images(images, (4, 4))\n assert observed[0].shape == (4, 4, 3)\n assert observed[1].shape == (4, 4)\n assert observed[0].dtype == np.uint8\n assert observed[1].dtype == np.uint8\n\n ###################\n # test other dtypes\n ###################\n # interpolation=\"nearest\"\n image = np.zeros((4, 4), dtype=bool)\n image[1, :] = True\n image[2, :] = True\n expected = np.zeros((3, 3), dtype=bool)\n expected[1, :] = True\n expected[2, :] = True\n image_rs = ia.imresize_many_images([image], (3, 3), interpolation=\"nearest\")[0]\n assert image_rs.dtype.type == image.dtype.type\n assert np.all(image_rs == expected)\n\n for dtype in [np.uint8, np.uint16, np.int8, np.int16, np.int32]:\n min_value, center_value, max_value = iadt.get_value_range_of_dtype(dtype)\n for value in [min_value, max_value]:\n image = np.zeros((4, 4), dtype=dtype)\n image[1, :] = value\n image[2, :] = value\n expected = np.zeros((3, 3), dtype=dtype)\n expected[1, :] = value\n expected[2, :] = value\n image_rs = ia.imresize_many_images([image], (3, 3), interpolation=\"nearest\")[0]\n assert image_rs.dtype.type == dtype\n assert np.all(image_rs == expected)\n\n for dtype in [np.float16, np.float32, np.float64]:\n isize = np.dtype(dtype).itemsize\n for value in [0.5, -0.5, 1.0, -1.0, 10.0, -10.0, -1000 ** (isize-1), 1000 * (isize+1)]:\n image = np.zeros((4, 4), dtype=dtype)\n image[1, :] = value\n image[2, :] = value\n expected = np.zeros((3, 3), dtype=dtype)\n expected[1, :] = value\n expected[2, :] = value\n image_rs = ia.imresize_many_images([image], (3, 3), interpolation=\"nearest\")[0]\n assert image_rs.dtype.type == dtype\n assert np.allclose(image_rs, expected, rtol=0, atol=1e-8)\n\n # other interpolations\n for ip in [\"linear\", \"cubic\", \"area\"]:\n mask = np.zeros((4, 4), dtype=np.uint8)\n mask[1, :] = 255\n mask[2, :] = 255\n mask = ia.imresize_many_images([mask], (3, 3), interpolation=ip)[0]\n mask = mask.astype(np.float128) / 255.0\n\n image = np.zeros((4, 4), dtype=bool)\n image[1, :] = True\n image[2, :] = True\n expected = mask > 0.5\n image_rs = ia.imresize_many_images([image], (3, 3), interpolation=ip)[0]\n assert image_rs.dtype.type == image.dtype.type\n assert np.all(image_rs == expected)\n\n for dtype in [np.uint8, np.uint16, np.int8, np.int16]:\n min_value, center_value, max_value = iadt.get_value_range_of_dtype(dtype)\n dynamic_range = max_value - min_value\n for value in [min_value+1, max_value-1]:\n image = np.zeros((4, 4), dtype=dtype)\n image[1, :] = value\n image[2, :] = value\n expected = np.round(mask * value).astype(dtype)\n image_rs = ia.imresize_many_images([image], (3, 3), interpolation=ip)[0]\n assert image_rs.dtype.type == dtype\n diff = np.abs(image_rs.astype(np.int64) - expected.astype(np.int64))\n assert np.all(diff < 2 * (1/255) * dynamic_range)\n\n mask = np.zeros((4, 4), dtype=np.float64)\n mask[1, :] = 1.0\n mask[2, :] = 1.0\n mask = ia.imresize_many_images([mask], (3, 3), interpolation=ip)[0]\n mask = mask.astype(np.float128)\n\n for dtype in [np.float16, np.float32, np.float64]:\n isize = np.dtype(dtype).itemsize\n\n for value in [0.5, -0.5, 1.0, -1.0, 10.0, -10.0, -1000 ** (isize-1), 1000 * (isize+1)]:\n image = np.zeros((4, 4), dtype=dtype)\n image[1, :] = value\n image[2, :] = value\n expected = (mask * np.float128(value)).astype(dtype)\n image_rs = ia.imresize_many_images([image], (3, 3), interpolation=ip)[0]\n assert image_rs.dtype.type == dtype\n # Our basis for the expected image is derived from uint8 as that is most likely to work, so we will\n # have to accept here deviations of around 1/255.\n atol = np.float128(1 / 255) * np.abs(np.float128(value)) + 1e-8\n assert np.allclose(image_rs, expected, rtol=0, atol=atol)\n # Expect at least one cell to have a difference between observed and expected image of approx. 0,\n # currently we seem to be able to get away with this despite the above mentioned inaccuracy.\n assert np.any(np.isclose(image_rs, expected, rtol=0, atol=1e-4))\n\n\ndef test_imresize_single_image():\n for c in [-1, 1, 3]:\n image1 = np.zeros((16, 16, abs(c)), dtype=np.uint8) + 255\n image2 = np.zeros((16, 16, abs(c)), dtype=np.uint8)\n image3 = np.pad(\n np.zeros((8, 8, abs(c)), dtype=np.uint8) + 255,\n ((4, 4), (4, 4), (0, 0)),\n mode=\"constant\",\n constant_values=0\n )\n\n image1_small = np.zeros((8, 8, abs(c)), dtype=np.uint8) + 255\n image2_small = np.zeros((8, 8, abs(c)), dtype=np.uint8)\n image3_small = np.pad(\n np.zeros((4, 4, abs(c)), dtype=np.uint8) + 255,\n ((2, 2), (2, 2), (0, 0)),\n mode=\"constant\",\n constant_values=0\n )\n\n image1_large = np.zeros((32, 32, abs(c)), dtype=np.uint8) + 255\n image2_large = np.zeros((32, 32, abs(c)), dtype=np.uint8)\n image3_large = np.pad(\n np.zeros((16, 16, abs(c)), dtype=np.uint8) + 255,\n ((8, 8), (8, 8), (0, 0)),\n mode=\"constant\",\n constant_values=0\n )\n\n images = np.uint8([image1, image2, image3])\n images_small = np.uint8([image1_small, image2_small, image3_small])\n images_large = np.uint8([image1_large, image2_large, image3_large])\n\n if c == -1:\n images = images[:, :, 0]\n images_small = images_small[:, :, 0]\n images_large = images_large[:, :, 0]\n\n interpolations = [None,\n \"nearest\", \"linear\", \"area\", \"cubic\",\n cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_AREA, cv2.INTER_CUBIC]\n\n for interpolation in interpolations:\n for image in images:\n image_observed = ia.imresize_single_image(image, (16, 16), interpolation=interpolation)\n diff = np.abs(image.astype(np.int32) - image_observed.astype(np.int32))\n assert np.sum(diff) == 0\n\n for interpolation in interpolations:\n for image, image_expected in zip(images, images_small):\n image_observed = ia.imresize_single_image(image, (8, 8), interpolation=interpolation)\n diff = np.abs(image_expected.astype(np.int32) - image_observed.astype(np.int32))\n diff_fraction = np.sum(diff) / (image_observed.size * 255)\n assert diff_fraction < 0.5\n\n for interpolation in interpolations:\n for image, image_expected in zip(images, images_large):\n image_observed = ia.imresize_single_image(image, (32, 32), interpolation=interpolation)\n diff = np.abs(image_expected.astype(np.int32) - image_observed.astype(np.int32))\n diff_fraction = np.sum(diff) / (image_observed.size * 255)\n assert diff_fraction < 0.5\n\n\ndef test_pad():\n # -------\n # uint, int\n # -------\n for dtype in [np.uint8, np.uint16, np.uint32, np.int8, np.int16, np.int32, np.int64]:\n min_value, center_value, max_value = iadt.get_value_range_of_dtype(dtype)\n\n arr = np.zeros((3, 3), dtype=dtype) + max_value\n\n arr_pad = ia.pad(arr)\n assert arr_pad.shape == (3, 3)\n # For some reason, arr_pad.dtype.type == dtype fails here for int64 but not for the other dtypes,\n # even though int64 is the dtype of arr_pad. Also checked .name and .str for them -- all same value.\n assert arr_pad.dtype == np.dtype(dtype)\n assert np.array_equal(arr_pad, arr)\n\n arr_pad = ia.pad(arr, top=1)\n assert arr_pad.shape == (4, 3)\n assert arr_pad.dtype == np.dtype(dtype)\n assert np.all(arr_pad[0, :] == 0)\n\n arr_pad = ia.pad(arr, right=1)\n assert arr_pad.shape == (3, 4)\n assert arr_pad.dtype == np.dtype(dtype)\n assert np.all(arr_pad[:, -1] == 0)\n\n arr_pad = ia.pad(arr, bottom=1)\n assert arr_pad.shape == (4, 3)\n assert arr_pad.dtype == np.dtype(dtype)\n assert np.all(arr_pad[-1, :] == 0)\n\n arr_pad = ia.pad(arr, left=1)\n assert arr_pad.shape == (3, 4)\n assert arr_pad.dtype == np.dtype(dtype)\n assert np.all(arr_pad[:, 0] == 0)\n\n arr_pad = ia.pad(arr, top=1, right=2, bottom=3, left=4)\n assert arr_pad.shape == (3+(1+3), 3+(2+4))\n assert arr_pad.dtype == np.dtype(dtype)\n assert np.all(arr_pad[0, :] == 0)\n assert np.all(arr_pad[:, -2:] == 0)\n assert np.all(arr_pad[-3:, :] == 0)\n assert np.all(arr_pad[:, :4] == 0)\n\n arr_pad = ia.pad(arr, top=1, cval=10)\n assert arr_pad.shape == (4, 3)\n assert arr_pad.dtype == np.dtype(dtype)\n assert np.all(arr_pad[0, :] == 10)\n\n arr = np.zeros((3, 3, 3), dtype=dtype) + 127\n arr_pad = ia.pad(arr, top=1)\n assert arr_pad.shape == (4, 3, 3)\n assert arr_pad.dtype == np.dtype(dtype)\n assert np.all(arr_pad[0, :, 0] == 0)\n assert np.all(arr_pad[0, :, 1] == 0)\n assert np.all(arr_pad[0, :, 2] == 0)\n\n v1 = int(center_value + 0.25 * max_value)\n v2 = int(center_value + 0.40 * max_value)\n arr = np.zeros((3, 3), dtype=dtype) + v1\n arr[1, 1] = v2\n arr_pad = ia.pad(arr, top=1, mode=\"maximum\")\n assert arr_pad.shape == (4, 3)\n assert arr_pad.dtype == np.dtype(dtype)\n assert arr_pad[0, 0] == v1\n assert arr_pad[0, 1] == v2\n assert arr_pad[0, 2] == v1\n\n v1 = int(center_value + 0.25 * max_value)\n arr = np.zeros((3, 3), dtype=dtype)\n arr_pad = ia.pad(arr, top=1, mode=\"constant\", cval=v1)\n assert arr_pad.shape == (4, 3)\n assert arr_pad.dtype == np.dtype(dtype)\n assert arr_pad[0, 0] == v1\n assert arr_pad[0, 1] == v1\n assert arr_pad[0, 2] == v1\n assert arr_pad[1, 0] == 0\n\n for nb_channels in [1, 2, 3, 4, 5]:\n v1 = int(center_value + 0.25 * max_value)\n arr = np.zeros((3, 3, nb_channels), dtype=dtype)\n arr_pad = ia.pad(arr, top=1, mode=\"constant\", cval=v1)\n assert arr_pad.shape == (4, 3, nb_channels)\n assert arr_pad.dtype == np.dtype(dtype)\n assert np.all(arr_pad[0, 0, :] == v1)\n assert np.all(arr_pad[0, 1, :] == v1)\n assert np.all(arr_pad[0, 2, :] == v1)\n assert np.all(arr_pad[1, 0, :] == 0)\n\n arr = np.zeros((1, 1), dtype=dtype) + 0\n arr_pad = ia.pad(arr, top=4, mode=\"linear_ramp\", cval=100)\n assert arr_pad.shape == (5, 1)\n assert arr_pad.dtype == np.dtype(dtype)\n assert arr_pad[0, 0] == 100\n assert arr_pad[1, 0] == 75\n assert arr_pad[2, 0] == 50\n assert arr_pad[3, 0] == 25\n assert arr_pad[4, 0] == 0\n\n # test other channel numbers\n value = int(center_value + 0.25 * max_value)\n for nb_channels in [None, 1, 2, 3, 4, 5, 7, 11]:\n arr = np.full((3, 3), value, dtype=dtype)\n if nb_channels is not None:\n arr = arr[..., np.newaxis]\n arr = np.tile(arr, (1, 1, nb_channels))\n for c in sm.xrange(nb_channels):\n arr[..., c] += c\n arr_pad = ia.pad(arr, top=1, mode=\"constant\", cval=0)\n assert arr_pad.dtype.name == np.dtype(dtype).name\n if nb_channels is None:\n assert arr_pad.shape == (4, 3)\n assert np.all(arr_pad[0, :] == 0)\n assert np.all(arr_pad[1:, :] == arr)\n else:\n assert arr_pad.shape == (4, 3, nb_channels)\n assert np.all(arr_pad[0, :, :] == 0)\n assert np.all(arr_pad[1:, :, :] == arr)\n\n # -------\n # float\n # -------\n for dtype in [np.float16, np.float32, np.float64, np.float128]:\n arr = np.zeros((3, 3), dtype=dtype) + 1.0\n\n def _allclose(a, b):\n atol = 1e-3 if dtype == np.float16 else 1e-7\n return np.allclose(a, b, atol=atol, rtol=0)\n\n arr_pad = ia.pad(arr)\n assert arr_pad.shape == (3, 3)\n assert arr_pad.dtype == np.dtype(dtype)\n assert _allclose(arr_pad, arr)\n\n arr_pad = ia.pad(arr, top=1)\n assert arr_pad.shape == (4, 3)\n assert arr_pad.dtype == np.dtype(dtype)\n assert _allclose(arr_pad[0, :], dtype([0, 0, 0]))\n\n arr_pad = ia.pad(arr, right=1)\n assert arr_pad.shape == (3, 4)\n assert arr_pad.dtype == np.dtype(dtype)\n assert _allclose(arr_pad[:, -1], dtype([0, 0, 0]))\n\n arr_pad = ia.pad(arr, bottom=1)\n assert arr_pad.shape == (4, 3)\n assert arr_pad.dtype == np.dtype(dtype)\n assert _allclose(arr_pad[-1, :], dtype([0, 0, 0]))\n\n arr_pad = ia.pad(arr, left=1)\n assert arr_pad.shape == (3, 4)\n assert arr_pad.dtype == np.dtype(dtype)\n assert _allclose(arr_pad[:, 0], dtype([0, 0, 0]))\n\n arr_pad = ia.pad(arr, top=1, right=2, bottom=3, left=4)\n assert arr_pad.shape == (3+(1+3), 3+(2+4))\n assert arr_pad.dtype == np.dtype(dtype)\n assert _allclose(np.max(arr_pad[0, :]), 0)\n assert _allclose(np.max(arr_pad[:, -2:]), 0)\n assert _allclose(np.max(arr_pad[-3, :]), 0)\n assert _allclose(np.max(arr_pad[:, :4]), 0)\n\n arr_pad = ia.pad(arr, top=1, cval=0.2)\n assert arr_pad.shape == (4, 3)\n assert arr_pad.dtype == np.dtype(dtype)\n assert _allclose(arr_pad[0, :], dtype([0.2, 0.2, 0.2]))\n\n v1 = 1000 ** (np.dtype(dtype).itemsize - 1)\n arr_pad = ia.pad(arr, top=1, cval=v1)\n assert arr_pad.shape == (4, 3)\n assert arr_pad.dtype == np.dtype(dtype)\n assert _allclose(arr_pad[0, :], dtype([v1, v1, v1]))\n\n v1 = (-1000) ** (np.dtype(dtype).itemsize - 1)\n arr_pad = ia.pad(arr, top=1, cval=v1)\n assert arr_pad.shape == (4, 3)\n assert arr_pad.dtype == np.dtype(dtype)\n assert _allclose(arr_pad[0, :], dtype([v1, v1, v1]))\n\n arr = np.zeros((3, 3, 3), dtype=dtype) + 0.5\n arr_pad = ia.pad(arr, top=1)\n assert arr_pad.shape == (4, 3, 3)\n assert arr_pad.dtype == np.dtype(dtype)\n assert _allclose(arr_pad[0, :, 0], dtype([0, 0, 0]))\n assert _allclose(arr_pad[0, :, 1], dtype([0, 0, 0]))\n assert _allclose(arr_pad[0, :, 2], dtype([0, 0, 0]))\n\n arr = np.zeros((3, 3), dtype=dtype) + 0.5\n arr[1, 1] = 0.75\n arr_pad = ia.pad(arr, top=1, mode=\"maximum\")\n assert arr_pad.shape == (4, 3)\n assert arr_pad.dtype == np.dtype(dtype)\n assert _allclose(arr_pad[0, 0], 0.5)\n assert _allclose(arr_pad[0, 1], 0.75)\n assert _allclose(arr_pad[0, 2], 0.50)\n\n arr = np.zeros((3, 3), dtype=dtype)\n arr_pad = ia.pad(arr, top=1, mode=\"constant\", cval=0.4)\n assert arr_pad.shape == (4, 3)\n assert arr_pad.dtype == np.dtype(dtype)\n assert _allclose(arr_pad[0, 0], 0.4)\n assert _allclose(arr_pad[0, 1], 0.4)\n assert _allclose(arr_pad[0, 2], 0.4)\n assert _allclose(arr_pad[1, 0], 0.0)\n\n for nb_channels in [1, 2, 3, 4, 5]:\n arr = np.zeros((3, 3, nb_channels), dtype=dtype)\n arr_pad = ia.pad(arr, top=1, mode=\"constant\", cval=0.4)\n assert arr_pad.shape == (4, 3, nb_channels)\n assert arr_pad.dtype == np.dtype(dtype)\n assert _allclose(arr_pad[0, 0, :], 0.4)\n assert _allclose(arr_pad[0, 1, :], 0.4)\n assert _allclose(arr_pad[0, 2, :], 0.4)\n assert _allclose(arr_pad[1, 0, :], 0.0)\n\n arr = np.zeros((1, 1), dtype=dtype) + 0.6\n arr_pad = ia.pad(arr, top=4, mode=\"linear_ramp\", cval=1.0)\n assert arr_pad.shape == (5, 1)\n assert arr_pad.dtype == np.dtype(dtype)\n assert _allclose(arr_pad[0, 0], 1.0)\n assert _allclose(arr_pad[1, 0], 0.9)\n assert _allclose(arr_pad[2, 0], 0.8)\n assert _allclose(arr_pad[3, 0], 0.7)\n assert _allclose(arr_pad[4, 0], 0.6)\n\n # test other channel numbers\n value = 1000 ** (np.dtype(dtype).itemsize - 1)\n for nb_channels in [None, 1, 2, 3, 4, 5, 7, 11]:\n arr = np.full((3, 3), value, dtype=dtype)\n if nb_channels is not None:\n arr = arr[..., np.newaxis]\n arr = np.tile(arr, (1, 1, nb_channels))\n for c in sm.xrange(nb_channels):\n arr[..., c] += c\n arr_pad = ia.pad(arr, top=1, mode=\"constant\", cval=0)\n assert arr_pad.dtype.name == np.dtype(dtype).name\n if nb_channels is None:\n assert arr_pad.shape == (4, 3)\n assert _allclose(arr_pad[0, :], 0)\n assert _allclose(arr_pad[1:, :], arr)\n else:\n assert arr_pad.shape == (4, 3, nb_channels)\n assert _allclose(arr_pad[0, :, :], 0)\n assert _allclose(arr_pad[1:, :, :], arr)\n\n # -------\n # bool\n # -------\n dtype = bool\n arr = np.zeros((3, 3), dtype=dtype)\n arr_pad = ia.pad(arr)\n assert arr_pad.shape == (3, 3)\n # For some reason, arr_pad.dtype.type == dtype fails here for int64 but not for the other dtypes,\n # even though int64 is the dtype of arr_pad. Also checked .name and .str for them -- all same value.\n assert arr_pad.dtype == np.dtype(dtype)\n assert np.all(arr_pad == arr)\n\n arr_pad = ia.pad(arr, top=1)\n assert arr_pad.shape == (4, 3)\n assert arr_pad.dtype == np.dtype(dtype)\n assert np.all(arr_pad[0, :] == 0)\n\n arr_pad = ia.pad(arr, top=1, cval=True)\n assert arr_pad.shape == (4, 3)\n assert arr_pad.dtype == np.dtype(dtype)\n assert np.all(arr_pad[0, :] == 1)\n\n\ndef test_compute_paddings_for_aspect_ratio():\n arr = np.zeros((4, 4), dtype=np.uint8)\n top, right, bottom, left = ia.compute_paddings_for_aspect_ratio(arr, 1.0)\n assert top == 0\n assert right == 0\n assert bottom == 0\n assert left == 0\n\n arr = np.zeros((1, 4), dtype=np.uint8)\n top, right, bottom, left = ia.compute_paddings_for_aspect_ratio(arr, 1.0)\n assert top == 1\n assert right == 0\n assert bottom == 2\n assert left == 0\n\n arr = np.zeros((4, 1), dtype=np.uint8)\n top, right, bottom, left = ia.compute_paddings_for_aspect_ratio(arr, 1.0)\n assert top == 0\n assert right == 2\n assert bottom == 0\n assert left == 1\n\n arr = np.zeros((2, 4), dtype=np.uint8)\n top, right, bottom, left = ia.compute_paddings_for_aspect_ratio(arr, 1.0)\n assert top == 1\n assert right == 0\n assert bottom == 1\n assert left == 0\n\n arr = np.zeros((4, 2), dtype=np.uint8)\n top, right, bottom, left = ia.compute_paddings_for_aspect_ratio(arr, 1.0)\n assert top == 0\n assert right == 1\n assert bottom == 0\n assert left == 1\n\n arr = np.zeros((4, 4), dtype=np.uint8)\n top, right, bottom, left = ia.compute_paddings_for_aspect_ratio(arr, 0.5)\n assert top == 2\n assert right == 0\n assert bottom == 2\n assert left == 0\n\n arr = np.zeros((4, 4), dtype=np.uint8)\n top, right, bottom, left = ia.compute_paddings_for_aspect_ratio(arr, 2.0)\n assert top == 0\n assert right == 2\n assert bottom == 0\n assert left == 2\n\n\ndef test_pad_to_aspect_ratio():\n for dtype in [np.uint8, np.int32, np.float32]:\n # aspect_ratio = 1.0\n arr = np.zeros((4, 4), dtype=dtype)\n arr_pad = ia.pad_to_aspect_ratio(arr, 1.0)\n assert arr_pad.dtype.type == dtype\n assert arr_pad.shape[0] == 4\n assert arr_pad.shape[1] == 4\n\n arr = np.zeros((1, 4), dtype=dtype)\n arr_pad = ia.pad_to_aspect_ratio(arr, 1.0)\n assert arr_pad.dtype.type == dtype\n assert arr_pad.shape[0] == 4\n assert arr_pad.shape[1] == 4\n\n arr = np.zeros((4, 1), dtype=dtype)\n arr_pad = ia.pad_to_aspect_ratio(arr, 1.0)\n assert arr_pad.dtype.type == dtype\n assert arr_pad.shape[0] == 4\n assert arr_pad.shape[1] == 4\n\n arr = np.zeros((2, 4), dtype=dtype)\n arr_pad = ia.pad_to_aspect_ratio(arr, 1.0)\n assert arr_pad.dtype.type == dtype\n assert arr_pad.shape[0] == 4\n assert arr_pad.shape[1] == 4\n\n arr = np.zeros((4, 2), dtype=dtype)\n arr_pad = ia.pad_to_aspect_ratio(arr, 1.0)\n assert arr_pad.dtype.type == dtype\n assert arr_pad.shape[0] == 4\n assert arr_pad.shape[1] == 4\n\n # aspect_ratio != 1.0\n arr = np.zeros((4, 4), dtype=dtype)\n arr_pad = ia.pad_to_aspect_ratio(arr, 2.0)\n assert arr_pad.dtype.type == dtype\n assert arr_pad.shape[0] == 4\n assert arr_pad.shape[1] == 8\n\n arr = np.zeros((4, 4), dtype=dtype)\n arr_pad = ia.pad_to_aspect_ratio(arr, 0.5)\n assert arr_pad.dtype.type == dtype\n assert arr_pad.shape[0] == 8\n assert arr_pad.shape[1] == 4\n\n # 3d arr\n arr = np.zeros((4, 2, 3), dtype=dtype)\n arr_pad = ia.pad_to_aspect_ratio(arr, 1.0)\n assert arr_pad.dtype.type == dtype\n assert arr_pad.shape[0] == 4\n assert arr_pad.shape[1] == 4\n assert arr_pad.shape[2] == 3\n\n # cval\n arr = np.zeros((4, 4), dtype=np.uint8) + 128\n arr_pad = ia.pad_to_aspect_ratio(arr, 2.0)\n assert arr_pad.shape[0] == 4\n assert arr_pad.shape[1] == 8\n assert np.max(arr_pad[:, 0:2]) == 0\n assert np.max(arr_pad[:, -2:]) == 0\n assert np.max(arr_pad[:, 2:-2]) == 128\n\n arr = np.zeros((4, 4), dtype=np.uint8) + 128\n arr_pad = ia.pad_to_aspect_ratio(arr, 2.0, cval=10)\n assert arr_pad.shape[0] == 4\n assert arr_pad.shape[1] == 8\n assert np.max(arr_pad[:, 0:2]) == 10\n assert np.max(arr_pad[:, -2:]) == 10\n assert np.max(arr_pad[:, 2:-2]) == 128\n\n arr = np.zeros((4, 4), dtype=np.float32) + 0.5\n arr_pad = ia.pad_to_aspect_ratio(arr, 2.0, cval=0.0)\n assert arr_pad.shape[0] == 4\n assert arr_pad.shape[1] == 8\n assert 0 - 1e-6 <= np.max(arr_pad[:, 0:2]) <= 0 + 1e-6\n assert 0 - 1e-6 <= np.max(arr_pad[:, -2:]) <= 0 + 1e-6\n assert 0.5 - 1e-6 <= np.max(arr_pad[:, 2:-2]) <= 0.5 + 1e-6\n\n arr = np.zeros((4, 4), dtype=np.float32) + 0.5\n arr_pad = ia.pad_to_aspect_ratio(arr, 2.0, cval=0.1)\n assert arr_pad.shape[0] == 4\n assert arr_pad.shape[1] == 8\n assert 0.1 - 1e-6 <= np.max(arr_pad[:, 0:2]) <= 0.1 + 1e-6\n assert 0.1 - 1e-6 <= np.max(arr_pad[:, -2:]) <= 0.1 + 1e-6\n assert 0.5 - 1e-6 <= np.max(arr_pad[:, 2:-2]) <= 0.5 + 1e-6\n\n # mode\n arr = np.zeros((4, 4), dtype=np.uint8) + 128\n arr[1:3, 1:3] = 200\n arr_pad = ia.pad_to_aspect_ratio(arr, 2.0, mode=\"maximum\")\n assert arr_pad.shape[0] == 4\n assert arr_pad.shape[1] == 8\n assert np.max(arr_pad[0:1, 0:2]) == 128\n assert np.max(arr_pad[1:3, 0:2]) == 200\n assert np.max(arr_pad[3:, 0:2]) == 128\n assert np.max(arr_pad[0:1, -2:]) == 128\n assert np.max(arr_pad[1:3, -2:]) == 200\n assert np.max(arr_pad[3:, -2:]) == 128\n\n # TODO add tests for return_pad_values=True\n\n\ndef test_pool():\n # -----\n # uint, int\n # -----\n for dtype in [np.uint8, np.uint16, np.uint32, np.int8, np.int16, np.int32]:\n min_value, center_value, max_value = iadt.get_value_range_of_dtype(dtype)\n\n for func in [np.min, np.average, np.max]:\n arr = np.array([\n [0, 1, 2, 3],\n [4, 5, 6, 7],\n [8, 9, 10, 11],\n [12, 13, 14, 15]\n ], dtype=dtype)\n arr_pooled = ia.pool(arr, 2, func)\n assert arr_pooled.shape == (2, 2)\n assert arr_pooled.dtype == np.dtype(dtype)\n assert arr_pooled[0, 0] == int(func([0, 1, 4, 5]))\n assert arr_pooled[0, 1] == int(func([2, 3, 6, 7]))\n assert arr_pooled[1, 0] == int(func([8, 9, 12, 13]))\n assert arr_pooled[1, 1] == int(func([10, 11, 14, 15]))\n\n arr = np.array([\n [0, 1, 2, 3],\n [4, 5, 6, 7],\n [8, 9, 10, 11],\n [12, 13, 14, 15]\n ], dtype=dtype)\n arr = np.tile(arr[:, :, np.newaxis], (1, 1, 3))\n arr[..., 1] += 1\n arr[..., 2] += 2\n arr_pooled = ia.pool(arr, 2, func)\n assert arr_pooled.shape == (2, 2, 3)\n assert arr_pooled.dtype == np.dtype(dtype)\n for c in sm.xrange(3):\n assert arr_pooled[0, 0, c] == int(func([0, 1, 4, 5])) + c\n assert arr_pooled[0, 1, c] == int(func([2, 3, 6, 7])) + c\n assert arr_pooled[1, 0, c] == int(func([8, 9, 12, 13])) + c\n assert arr_pooled[1, 1, c] == int(func([10, 11, 14, 15])) + c\n\n for value in [min_value, min_value+50, min_value+100, 0, 10, max_value,\n int(center_value + 0.10*max_value),\n int(center_value + 0.20*max_value),\n int(center_value + 0.25*max_value),\n int(center_value + 0.33*max_value)]:\n arr = np.full((4, 4), value, dtype=dtype)\n arr_pooled = ia.pool(arr, 2, func)\n assert arr_pooled.shape == (2, 2)\n assert arr_pooled.dtype == np.dtype(dtype)\n assert np.all(arr_pooled == value)\n\n arr = np.full((4, 4, 3), value, dtype=dtype)\n arr_pooled = ia.pool(arr, 2, func)\n assert arr_pooled.shape == (2, 2, 3)\n assert arr_pooled.dtype == np.dtype(dtype)\n assert np.all(arr_pooled == value)\n\n # -----\n # float\n # -----\n for dtype in [np.float16, np.float32, np.float64, np.float128]:\n def _allclose(a, b):\n atol = 1e-4 if dtype == np.float16 else 1e-8\n return np.allclose(a, b, atol=atol, rtol=0)\n\n for func in [np.min, np.average, np.max]:\n arr = np.array([\n [0, 1, 2, 3],\n [4, 5, 6, 7],\n [8, 9, 10, 11],\n [12, 13, 14, 15]\n ], dtype=dtype)\n arr_pooled = ia.pool(arr, 2, func)\n assert arr_pooled.shape == (2, 2)\n assert arr_pooled.dtype == np.dtype(dtype)\n assert arr_pooled[0, 0] == func([0, 1, 4, 5])\n assert arr_pooled[0, 1] == func([2, 3, 6, 7])\n assert arr_pooled[1, 0] == func([8, 9, 12, 13])\n assert arr_pooled[1, 1] == func([10, 11, 14, 15])\n\n arr = np.array([\n [0, 1, 2, 3],\n [4, 5, 6, 7],\n [8, 9, 10, 11],\n [12, 13, 14, 15]\n ], dtype=dtype)\n arr = np.tile(arr[:, :, np.newaxis], (1, 1, 3))\n arr[..., 1] += 1\n arr[..., 2] += 2\n arr_pooled = ia.pool(arr, 2, func)\n assert arr_pooled.shape == (2, 2, 3)\n assert arr_pooled.dtype == np.dtype(dtype)\n for c in sm.xrange(3):\n assert arr_pooled[0, 0, c] == func([0, 1, 4, 5]) + c\n assert arr_pooled[0, 1, c] == func([2, 3, 6, 7]) + c\n assert arr_pooled[1, 0, c] == func([8, 9, 12, 13]) + c\n assert arr_pooled[1, 1, c] == func([10, 11, 14, 15]) + c\n\n isize = np.dtype(dtype).itemsize\n for value in [(-1) * (1000 ** (isize-1)), -50.0, 0.0, 50.0, 1000 ** (isize-1)]:\n arr = np.full((4, 4), value, dtype=dtype)\n arr_pooled = ia.pool(arr, 2, func)\n dt = np.result_type(arr_pooled, 1.)\n y = np.array(arr_pooled, dtype=dt, copy=False, subok=True)\n assert arr_pooled.shape == (2, 2)\n assert arr_pooled.dtype == np.dtype(dtype)\n assert _allclose(arr_pooled, float(value))\n\n arr = np.full((4, 4, 3), value, dtype=dtype)\n arr_pooled = ia.pool(arr, 2, func)\n assert arr_pooled.shape == (2, 2, 3)\n assert arr_pooled.dtype == np.dtype(dtype)\n assert _allclose(arr_pooled, float(value))\n\n # ----\n # bool\n # ----\n arr = np.zeros((4, 4), dtype=bool)\n arr[0, 0] = True\n arr[0, 1] = True\n arr[1, 0] = True\n arr_pooled = ia.pool(arr, 2, np.min)\n assert arr_pooled.dtype == arr.dtype\n assert np.all(arr_pooled == 0)\n\n arr_pooled = ia.pool(arr, 2, np.average)\n assert arr_pooled.dtype == arr.dtype\n assert np.all(arr_pooled[0, 0] == 1)\n assert np.all(arr_pooled[:, 1] == 0)\n assert np.all(arr_pooled[1, :] == 0)\n\n arr_pooled = ia.pool(arr, 2, np.max)\n assert arr_pooled.dtype == arr.dtype\n assert np.all(arr_pooled[0, 0] == 1)\n assert np.all(arr_pooled[:, 1] == 0)\n assert np.all(arr_pooled[1, :] == 0)\n\n # preserve_dtype off\n arr = np.uint8([\n [0, 1, 2, 3],\n [4, 5, 6, 7],\n [8, 9, 10, 11],\n [12, 13, 14, 15]\n ])\n arr_pooled = ia.pool(arr, 2, np.average, preserve_dtype=False)\n assert arr_pooled.shape == (2, 2)\n assert arr_pooled.dtype == np.float64\n assert np.allclose(arr_pooled[0, 0], np.average([0, 1, 4, 5]))\n assert np.allclose(arr_pooled[0, 1], np.average([2, 3, 6, 7]))\n assert np.allclose(arr_pooled[1, 0], np.average([8, 9, 12, 13]))\n assert np.allclose(arr_pooled[1, 1], np.average([10, 11, 14, 15]))\n\n # maximum function\n arr = np.uint8([\n [0, 1, 2, 3],\n [4, 5, 6, 7],\n [8, 9, 10, 11],\n [12, 13, 14, 15]\n ])\n arr_pooled = ia.pool(arr, 2, np.max)\n assert arr_pooled.shape == (2, 2)\n assert arr_pooled.dtype == arr.dtype.type\n assert arr_pooled[0, 0] == int(np.max([0, 1, 4, 5]))\n assert arr_pooled[0, 1] == int(np.max([2, 3, 6, 7]))\n assert arr_pooled[1, 0] == int(np.max([8, 9, 12, 13]))\n assert arr_pooled[1, 1] == int(np.max([10, 11, 14, 15]))\n\n # 3d array\n arr = np.uint8([\n [0, 1, 2, 3],\n [4, 5, 6, 7],\n [8, 9, 10, 11],\n [12, 13, 14, 15]\n ])\n arr = np.tile(arr[..., np.newaxis], (1, 1, 3))\n arr_pooled = ia.pool(arr, 2, np.average)\n assert arr_pooled.shape == (2, 2, 3)\n assert np.array_equal(arr_pooled[..., 0], arr_pooled[..., 1])\n assert np.array_equal(arr_pooled[..., 1], arr_pooled[..., 2])\n arr_pooled = arr_pooled[..., 0]\n assert arr_pooled.dtype == arr.dtype.type\n assert arr_pooled[0, 0] == int(np.average([0, 1, 4, 5]))\n assert arr_pooled[0, 1] == int(np.average([2, 3, 6, 7]))\n assert arr_pooled[1, 0] == int(np.average([8, 9, 12, 13]))\n assert arr_pooled[1, 1] == int(np.average([10, 11, 14, 15]))\n\n # block_size per axis\n arr = np.float32([\n [0, 1, 2, 3],\n [4, 5, 6, 7],\n [8, 9, 10, 11],\n [12, 13, 14, 15]\n ])\n arr_pooled = ia.pool(arr, (2, 1), np.average)\n assert arr_pooled.shape == (2, 4)\n assert arr_pooled.dtype == arr.dtype.type\n assert np.allclose(arr_pooled[0, 0], np.average([0, 4]))\n assert np.allclose(arr_pooled[0, 1], np.average([1, 5]))\n assert np.allclose(arr_pooled[0, 2], np.average([2, 6]))\n assert np.allclose(arr_pooled[0, 3], np.average([3, 7]))\n assert np.allclose(arr_pooled[1, 0], np.average([8, 12]))\n assert np.allclose(arr_pooled[1, 1], np.average([9, 13]))\n assert np.allclose(arr_pooled[1, 2], np.average([10, 14]))\n assert np.allclose(arr_pooled[1, 3], np.average([11, 15]))\n\n # cval\n arr = np.uint8([\n [0, 1, 2],\n [4, 5, 6],\n [8, 9, 10]\n ])\n arr_pooled = ia.pool(arr, 2, np.average)\n assert arr_pooled.shape == (2, 2)\n assert arr_pooled.dtype == arr.dtype.type\n assert arr_pooled[0, 0] == int(np.average([0, 1, 4, 5]))\n assert arr_pooled[0, 1] == int(np.average([2, 0, 6, 0]))\n assert arr_pooled[1, 0] == int(np.average([8, 9, 0, 0]))\n assert arr_pooled[1, 1] == int(np.average([10, 0, 0, 0]))\n\n arr = np.uint8([\n [0, 1],\n [4, 5]\n ])\n arr_pooled = ia.pool(arr, (4, 1), np.average)\n assert arr_pooled.shape == (1, 2)\n assert arr_pooled.dtype == arr.dtype.type\n assert arr_pooled[0, 0] == int(np.average([0, 4, 0, 0]))\n assert arr_pooled[0, 1] == int(np.average([1, 5, 0, 0]))\n\n arr = np.uint8([\n [0, 1, 2],\n [4, 5, 6],\n [8, 9, 10]\n ])\n arr_pooled = ia.pool(arr, 2, np.average, cval=22)\n assert arr_pooled.shape == (2, 2)\n assert arr_pooled.dtype == arr.dtype.type\n assert arr_pooled[0, 0] == int(np.average([0, 1, 4, 5]))\n assert arr_pooled[0, 1] == int(np.average([2, 22, 6, 22]))\n assert arr_pooled[1, 0] == int(np.average([8, 9, 22, 22]))\n assert arr_pooled[1, 1] == int(np.average([10, 22, 22, 22]))\n\n\ndef test_avg_pool():\n # very basic test, as avg_pool() just calls pool(), which is tested in test_pool()\n arr = np.uint8([\n [0, 1, 2, 3],\n [4, 5, 6, 7],\n [8, 9, 10, 11],\n [12, 13, 14, 15]\n ])\n arr_pooled = ia.avg_pool(arr, 2)\n assert arr_pooled.shape == (2, 2)\n assert arr_pooled.dtype == arr.dtype.type\n assert arr_pooled[0, 0] == int(np.average([0, 1, 4, 5]))\n assert arr_pooled[0, 1] == int(np.average([2, 3, 6, 7]))\n assert arr_pooled[1, 0] == int(np.average([8, 9, 12, 13]))\n assert arr_pooled[1, 1] == int(np.average([10, 11, 14, 15]))\n\n\ndef test_max_pool():\n # very basic test, as avg_pool() just calls pool(), which is tested in test_pool()\n arr = np.uint8([\n [0, 1, 2, 3],\n [4, 5, 6, 7],\n [8, 9, 10, 11],\n [12, 13, 14, 15]\n ])\n arr_pooled = ia.max_pool(arr, 2)\n assert arr_pooled.shape == (2, 2)\n assert arr_pooled.dtype == arr.dtype.type\n assert arr_pooled[0, 0] == int(np.max([0, 1, 4, 5]))\n assert arr_pooled[0, 1] == int(np.max([2, 3, 6, 7]))\n assert arr_pooled[1, 0] == int(np.max([8, 9, 12, 13]))\n assert arr_pooled[1, 1] == int(np.max([10, 11, 14, 15]))\n\n\ndef test_draw_grid():\n # bool\n dtype = bool\n image = np.zeros((2, 2, 3), dtype=dtype)\n\n image[0, 0] = False\n image[0, 1] = True\n image[1, 0] = True\n image[1, 1] = False\n\n grid = ia.draw_grid([image], rows=1, cols=1)\n assert grid.dtype == np.dtype(dtype)\n assert np.array_equal(grid, image)\n\n grid = ia.draw_grid(np.array([image], dtype=dtype), rows=1, cols=1)\n assert grid.dtype == np.dtype(dtype)\n assert np.array_equal(grid, image)\n\n grid = ia.draw_grid([image, image, image, image], rows=2, cols=2)\n expected = np.vstack([\n np.hstack([image, image]),\n np.hstack([image, image])\n ])\n assert grid.dtype == np.dtype(dtype)\n assert np.array_equal(grid, expected)\n\n grid = ia.draw_grid([image, image], rows=1, cols=2)\n expected = np.hstack([image, image])\n assert grid.dtype == np.dtype(dtype)\n assert np.array_equal(grid, expected)\n\n grid = ia.draw_grid([image, image, image, image], rows=2, cols=None)\n expected = np.vstack([\n np.hstack([image, image]),\n np.hstack([image, image])\n ])\n assert grid.dtype == np.dtype(dtype)\n assert np.array_equal(grid, expected)\n\n grid = ia.draw_grid([image, image, image, image], rows=None, cols=2)\n expected = np.vstack([\n np.hstack([image, image]),\n np.hstack([image, image])\n ])\n assert grid.dtype == np.dtype(dtype)\n assert np.array_equal(grid, expected)\n\n grid = ia.draw_grid([image, image, image, image], rows=None, cols=None)\n expected = np.vstack([\n np.hstack([image, image]),\n np.hstack([image, image])\n ])\n assert grid.dtype == np.dtype(dtype)\n assert np.array_equal(grid, expected)\n\n # int, uint\n for dtype in [np.uint8, np.uint16, np.uint32, np.uint64, np.int8, np.int16, np.int32, np.int64]:\n min_value, center_value, max_value = iadt.get_value_range_of_dtype(dtype)\n\n image = np.zeros((2, 2, 3), dtype=dtype)\n\n image[0, 0] = min_value\n image[0, 1] = center_value\n image[1, 0] = center_value + int(0.3 * max_value)\n image[1, 1] = max_value\n\n grid = ia.draw_grid([image], rows=1, cols=1)\n assert grid.dtype == np.dtype(dtype)\n assert np.array_equal(grid, image)\n\n grid = ia.draw_grid(np.array([image], dtype=dtype), rows=1, cols=1)\n assert grid.dtype == np.dtype(dtype)\n assert np.array_equal(grid, image)\n\n grid = ia.draw_grid([image, image, image, image], rows=2, cols=2)\n expected = np.vstack([\n np.hstack([image, image]),\n np.hstack([image, image])\n ])\n assert np.array_equal(grid, expected)\n\n grid = ia.draw_grid([image, image], rows=1, cols=2)\n expected = np.hstack([image, image])\n assert grid.dtype == np.dtype(dtype)\n assert np.array_equal(grid, expected)\n\n grid = ia.draw_grid([image, image, image, image], rows=2, cols=None)\n expected = np.vstack([\n np.hstack([image, image]),\n np.hstack([image, image])\n ])\n assert grid.dtype == np.dtype(dtype)\n assert np.array_equal(grid, expected)\n\n grid = ia.draw_grid([image, image, image, image], rows=None, cols=2)\n expected = np.vstack([\n np.hstack([image, image]),\n np.hstack([image, image])\n ])\n assert grid.dtype == np.dtype(dtype)\n assert np.array_equal(grid, expected)\n\n grid = ia.draw_grid([image, image, image, image], rows=None, cols=None)\n expected = np.vstack([\n np.hstack([image, image]),\n np.hstack([image, image])\n ])\n assert grid.dtype == np.dtype(dtype)\n assert np.array_equal(grid, expected)\n\n # float\n for dtype in [np.float16, np.float32, np.float64, np.float128]:\n def _allclose(a, b):\n atol = 1e-4 if dtype == np.float16 else 1e-8\n return np.allclose(a, b, atol=atol, rtol=0)\n\n image = np.zeros((2, 2, 3), dtype=dtype)\n\n isize = np.dtype(dtype).itemsize\n image[0, 0] = (-1) * (1000 ** (isize-1))\n image[0, 1] = -10.0\n image[1, 0] = 10.0\n image[1, 1] = 1000 ** (isize-1)\n\n grid = ia.draw_grid([image], rows=1, cols=1)\n assert grid.dtype == np.dtype(dtype)\n assert _allclose(grid, image)\n\n grid = ia.draw_grid(np.array([image], dtype=dtype), rows=1, cols=1)\n assert grid.dtype == np.dtype(dtype)\n assert _allclose(grid, image)\n\n grid = ia.draw_grid([image, image, image, image], rows=2, cols=2)\n expected = np.vstack([\n np.hstack([image, image]),\n np.hstack([image, image])\n ])\n assert grid.dtype == np.dtype(dtype)\n assert _allclose(grid, expected)\n\n grid = ia.draw_grid([image, image], rows=1, cols=2)\n expected = np.hstack([image, image])\n assert grid.dtype == np.dtype(dtype)\n assert _allclose(grid, expected)\n\n grid = ia.draw_grid([image, image, image, image], rows=2, cols=None)\n expected = np.vstack([\n np.hstack([image, image]),\n np.hstack([image, image])\n ])\n assert grid.dtype == np.dtype(dtype)\n assert _allclose(grid, expected)\n\n grid = ia.draw_grid([image, image, image, image], rows=None, cols=2)\n expected = np.vstack([\n np.hstack([image, image]),\n np.hstack([image, image])\n ])\n assert grid.dtype == np.dtype(dtype)\n assert _allclose(grid, expected)\n\n grid = ia.draw_grid([image, image, image, image], rows=None, cols=None)\n expected = np.vstack([\n np.hstack([image, image]),\n np.hstack([image, image])\n ])\n assert grid.dtype == np.dtype(dtype)\n assert _allclose(grid, expected)\n\n\ndef test_Keypoint():\n eps = 1e-8\n\n # x/y/x_int/y_int\n kp = ia.Keypoint(y=1, x=2)\n assert kp.y == 1\n assert kp.x == 2\n assert kp.y_int == 1\n assert kp.x_int == 2\n kp = ia.Keypoint(y=1.1, x=2.7)\n assert 1.1 - eps < kp.y < 1.1 + eps\n assert 2.7 - eps < kp.x < 2.7 + eps\n assert kp.y_int == 1\n assert kp.x_int == 3\n\n # project\n kp = ia.Keypoint(y=1, x=2)\n kp2 = kp.project((10, 10), (10, 10))\n assert kp2.y == 1\n assert kp2.x == 2\n kp2 = kp.project((10, 10), (20, 10))\n assert kp2.y == 2\n assert kp2.x == 2\n kp2 = kp.project((10, 10), (10, 20))\n assert kp2.y == 1\n assert kp2.x == 4\n kp2 = kp.project((10, 10), (20, 20))\n assert kp2.y == 2\n assert kp2.x == 4\n\n # shift\n kp = ia.Keypoint(y=1, x=2)\n kp2 = kp.shift(y=1)\n assert kp2.y == 2\n assert kp2.x == 2\n kp2 = kp.shift(y=-1)\n assert kp2.y == 0\n assert kp2.x == 2\n kp2 = kp.shift(x=1)\n assert kp2.y == 1\n assert kp2.x == 3\n kp2 = kp.shift(x=-1)\n assert kp2.y == 1\n assert kp2.x == 1\n kp2 = kp.shift(y=1, x=2)\n assert kp2.y == 2\n assert kp2.x == 4\n\n # generate_similar_points_manhattan\n kp = ia.Keypoint(y=4, x=5)\n kps_manhatten = kp.generate_similar_points_manhattan(0, 1.0, return_array=False)\n assert len(kps_manhatten) == 1\n assert kps_manhatten[0].y == 4\n assert kps_manhatten[0].x == 5\n\n kps_manhatten = kp.generate_similar_points_manhattan(1, 1.0, return_array=False)\n assert len(kps_manhatten) == 5\n expected = [(4, 5), (3, 5), (4, 6), (5, 5), (4, 4)]\n for y, x in expected:\n assert any([np.allclose([y, x], [kp_manhatten.y, kp_manhatten.x]) for kp_manhatten in kps_manhatten])\n\n kps_manhatten = kp.generate_similar_points_manhattan(1, 1.0, return_array=True)\n assert kps_manhatten.shape == (5, 2)\n expected = [(4, 5), (3, 5), (4, 6), (5, 5), (4, 4)]\n for y, x in expected:\n assert any([np.allclose([y, x], [kp_manhatten_y, kp_manhatten_x])\n for kp_manhatten_x, kp_manhatten_y in kps_manhatten])\n\n # __repr__ / __str_\n kp = ia.Keypoint(y=1, x=2)\n assert kp.__repr__() == kp.__str__() == \"Keypoint(x=2.00000000, y=1.00000000)\"\n kp = ia.Keypoint(y=1.2, x=2.7)\n assert kp.__repr__() == kp.__str__() == \"Keypoint(x=2.70000000, y=1.20000000)\"\n\n\ndef test_KeypointsOnImage():\n eps = 1e-8\n\n kps = [ia.Keypoint(x=1, y=2), ia.Keypoint(x=3, y=4)]\n\n # height/width\n kpi = ia.KeypointsOnImage(keypoints=kps, shape=(10, 20, 3))\n assert kpi.height == 10\n assert kpi.width == 20\n\n # image instead of shape\n kpi = ia.KeypointsOnImage(keypoints=kps, shape=np.zeros((10, 20, 3), dtype=np.uint8))\n assert kpi.shape == (10, 20, 3)\n\n # on()\n kpi2 = kpi.on((10, 20, 3))\n assert all([kp_i.x == kp_j.x and kp_i.y == kp_j.y for kp_i, kp_j in zip(kpi.keypoints, kpi2.keypoints)])\n\n kpi2 = kpi.on((20, 40, 3))\n assert kpi2.keypoints[0].x == 2\n assert kpi2.keypoints[0].y == 4\n assert kpi2.keypoints[1].x == 6\n assert kpi2.keypoints[1].y == 8\n\n kpi2 = kpi.on(np.zeros((20, 40, 3), dtype=np.uint8))\n assert kpi2.keypoints[0].x == 2\n assert kpi2.keypoints[0].y == 4\n assert kpi2.keypoints[1].x == 6\n assert kpi2.keypoints[1].y == 8\n\n # draw_on_image\n kpi = ia.KeypointsOnImage(keypoints=kps, shape=(5, 5, 3))\n image = np.zeros((5, 5, 3), dtype=np.uint8) + 10\n kps_mask = np.zeros(image.shape[0:2], dtype=np.bool)\n kps_mask[2, 1] = 1\n kps_mask[4, 3] = 1\n image_kps = kpi.draw_on_image(image, color=[0, 255, 0], size=1, copy=True, raise_if_out_of_image=False)\n assert np.all(image_kps[kps_mask] == [0, 255, 0])\n assert np.all(image_kps[~kps_mask] == [10, 10, 10])\n\n image_kps = kpi.draw_on_image(image, color=[0, 255, 0], size=3, copy=True, raise_if_out_of_image=False)\n kps_mask_size3 = np.copy(kps_mask)\n kps_mask_size3[2-1:2+1+1, 1-1:1+1+1] = 1\n kps_mask_size3[4-1:4+1+1, 3-1:3+1+1] = 1\n assert np.all(image_kps[kps_mask_size3] == [0, 255, 0])\n assert np.all(image_kps[~kps_mask_size3] == [10, 10, 10])\n\n image_kps = kpi.draw_on_image(image, color=[0, 0, 255], size=1, copy=True, raise_if_out_of_image=False)\n assert np.all(image_kps[kps_mask] == [0, 0, 255])\n assert np.all(image_kps[~kps_mask] == [10, 10, 10])\n\n image_kps = kpi.draw_on_image(image, color=255, size=1, copy=True, raise_if_out_of_image=False)\n assert np.all(image_kps[kps_mask] == [255, 255, 255])\n assert np.all(image_kps[~kps_mask] == [10, 10, 10])\n\n image2 = np.copy(image)\n image_kps = kpi.draw_on_image(image2, color=[0, 255, 0], size=1, copy=False, raise_if_out_of_image=False)\n assert np.all(image2 == image_kps)\n assert np.all(image_kps[kps_mask] == [0, 255, 0])\n assert np.all(image_kps[~kps_mask] == [10, 10, 10])\n assert np.all(image2[kps_mask] == [0, 255, 0])\n assert np.all(image2[~kps_mask] == [10, 10, 10])\n\n kpi = ia.KeypointsOnImage(keypoints=kps + [ia.Keypoint(x=100, y=100)], shape=(5, 5, 3))\n image = np.zeros((5, 5, 3), dtype=np.uint8) + 10\n kps_mask = np.zeros(image.shape[0:2], dtype=np.bool)\n kps_mask[2, 1] = 1\n kps_mask[4, 3] = 1\n image_kps = kpi.draw_on_image(image, color=[0, 255, 0], size=1, copy=True, raise_if_out_of_image=False)\n assert np.all(image_kps[kps_mask] == [0, 255, 0])\n assert np.all(image_kps[~kps_mask] == [10, 10, 10])\n\n kpi = ia.KeypointsOnImage(keypoints=kps + [ia.Keypoint(x=100, y=100)], shape=(5, 5, 3))\n image = np.zeros((5, 5, 3), dtype=np.uint8) + 10\n got_exception = False\n try:\n image_kps = kpi.draw_on_image(image, color=[0, 255, 0], size=1, copy=True, raise_if_out_of_image=True)\n assert np.all(image_kps[kps_mask] == [0, 255, 0])\n assert np.all(image_kps[~kps_mask] == [10, 10, 10])\n except Exception:\n got_exception = True\n assert got_exception\n\n kpi = ia.KeypointsOnImage(keypoints=kps + [ia.Keypoint(x=5, y=5)], shape=(5, 5, 3))\n image = np.zeros((5, 5, 3), dtype=np.uint8) + 10\n kps_mask = np.zeros(image.shape[0:2], dtype=np.bool)\n kps_mask[2, 1] = 1\n kps_mask[4, 3] = 1\n image_kps = kpi.draw_on_image(image, color=[0, 255, 0], size=1, copy=True, raise_if_out_of_image=False)\n assert np.all(image_kps[kps_mask] == [0, 255, 0])\n assert np.all(image_kps[~kps_mask] == [10, 10, 10])\n\n got_exception = False\n try:\n image_kps = kpi.draw_on_image(image, color=[0, 255, 0], size=1, copy=True, raise_if_out_of_image=True)\n assert np.all(image_kps[kps_mask] == [0, 255, 0])\n assert np.all(image_kps[~kps_mask] == [10, 10, 10])\n except Exception:\n got_exception = True\n assert got_exception\n\n # shift\n kpi = ia.KeypointsOnImage(keypoints=kps, shape=(5, 5, 3))\n kpi2 = kpi.shift(x=0, y=0)\n assert kpi2.keypoints[0].x == kpi.keypoints[0].x\n assert kpi2.keypoints[0].y == kpi.keypoints[0].y\n assert kpi2.keypoints[1].x == kpi.keypoints[1].x\n assert kpi2.keypoints[1].y == kpi.keypoints[1].y\n\n kpi2 = kpi.shift(x=1)\n assert kpi2.keypoints[0].x == kpi.keypoints[0].x + 1\n assert kpi2.keypoints[0].y == kpi.keypoints[0].y\n assert kpi2.keypoints[1].x == kpi.keypoints[1].x + 1\n assert kpi2.keypoints[1].y == kpi.keypoints[1].y\n\n kpi2 = kpi.shift(x=-1)\n assert kpi2.keypoints[0].x == kpi.keypoints[0].x - 1\n assert kpi2.keypoints[0].y == kpi.keypoints[0].y\n assert kpi2.keypoints[1].x == kpi.keypoints[1].x - 1\n assert kpi2.keypoints[1].y == kpi.keypoints[1].y\n\n kpi2 = kpi.shift(y=1)\n assert kpi2.keypoints[0].x == kpi.keypoints[0].x\n assert kpi2.keypoints[0].y == kpi.keypoints[0].y + 1\n assert kpi2.keypoints[1].x == kpi.keypoints[1].x\n assert kpi2.keypoints[1].y == kpi.keypoints[1].y + 1\n\n kpi2 = kpi.shift(y=-1)\n assert kpi2.keypoints[0].x == kpi.keypoints[0].x\n assert kpi2.keypoints[0].y == kpi.keypoints[0].y - 1\n assert kpi2.keypoints[1].x == kpi.keypoints[1].x\n assert kpi2.keypoints[1].y == kpi.keypoints[1].y - 1\n\n kpi2 = kpi.shift(x=1, y=2)\n assert kpi2.keypoints[0].x == kpi.keypoints[0].x + 1\n assert kpi2.keypoints[0].y == kpi.keypoints[0].y + 2\n assert kpi2.keypoints[1].x == kpi.keypoints[1].x + 1\n assert kpi2.keypoints[1].y == kpi.keypoints[1].y + 2\n\n # get_coords_array\n kpi = ia.KeypointsOnImage(keypoints=kps, shape=(5, 5, 3))\n observed = kpi.get_coords_array()\n expected = np.float32([\n [1, 2],\n [3, 4]\n ])\n assert np.allclose(observed, expected)\n\n # from_coords_array\n arr = np.float32([\n [1, 2],\n [3, 4]\n ])\n kpi = ia.KeypointsOnImage.from_coords_array(arr, shape=(5, 5, 3))\n assert 1 - eps < kpi.keypoints[0].x < 1 + eps\n assert 2 - eps < kpi.keypoints[0].y < 2 + eps\n assert 3 - eps < kpi.keypoints[1].x < 3 + eps\n assert 4 - eps < kpi.keypoints[1].y < 4 + eps\n\n # to_keypoint_image\n kpi = ia.KeypointsOnImage(keypoints=kps, shape=(5, 5, 3))\n image = kpi.to_keypoint_image(size=1)\n image_size3 = kpi.to_keypoint_image(size=3)\n kps_mask = np.zeros((5, 5, 2), dtype=np.bool)\n kps_mask[2, 1, 0] = 1\n kps_mask[4, 3, 1] = 1\n kps_mask_size3 = np.zeros_like(kps_mask)\n kps_mask_size3[2-1:2+1+1, 1-1:1+1+1, 0] = 1\n kps_mask_size3[4-1:4+1+1, 3-1:3+1+1, 1] = 1\n assert np.all(image[kps_mask] == 255)\n assert np.all(image[~kps_mask] == 0)\n assert np.all(image_size3[kps_mask] == 255)\n assert np.all(image_size3[kps_mask_size3] >= 128)\n assert np.all(image_size3[~kps_mask_size3] == 0)\n\n # from_keypoint_image()\n kps_image = np.zeros((5, 5, 2), dtype=np.uint8)\n kps_image[2, 1, 0] = 255\n kps_image[4, 3, 1] = 255\n kpi2 = ia.KeypointsOnImage.from_keypoint_image(kps_image, nb_channels=3)\n assert kpi2.shape == (5, 5, 3)\n assert len(kpi2.keypoints) == 2\n assert kpi2.keypoints[0].y == 2\n assert kpi2.keypoints[0].x == 1\n assert kpi2.keypoints[1].y == 4\n assert kpi2.keypoints[1].x == 3\n\n kps_image = np.zeros((5, 5, 2), dtype=np.uint8)\n kps_image[2, 1, 0] = 255\n kps_image[4, 3, 1] = 10\n kpi2 = ia.KeypointsOnImage.from_keypoint_image(kps_image, if_not_found_coords={\"x\": -1, \"y\": -2}, threshold=20,\n nb_channels=3)\n assert kpi2.shape == (5, 5, 3)\n assert len(kpi2.keypoints) == 2\n assert kpi2.keypoints[0].y == 2\n assert kpi2.keypoints[0].x == 1\n assert kpi2.keypoints[1].y == -2\n assert kpi2.keypoints[1].x == -1\n\n kps_image = np.zeros((5, 5, 2), dtype=np.uint8)\n kps_image[2, 1, 0] = 255\n kps_image[4, 3, 1] = 10\n kpi2 = ia.KeypointsOnImage.from_keypoint_image(kps_image, if_not_found_coords=(-1, -2), threshold=20,\n nb_channels=3)\n assert kpi2.shape == (5, 5, 3)\n assert len(kpi2.keypoints) == 2\n assert kpi2.keypoints[0].y == 2\n assert kpi2.keypoints[0].x == 1\n assert kpi2.keypoints[1].y == -2\n assert kpi2.keypoints[1].x == -1\n\n kps_image = np.zeros((5, 5, 2), dtype=np.uint8)\n kps_image[2, 1, 0] = 255\n kps_image[4, 3, 1] = 10\n kpi2 = ia.KeypointsOnImage.from_keypoint_image(kps_image, if_not_found_coords=None, threshold=20, nb_channels=3)\n assert kpi2.shape == (5, 5, 3)\n assert len(kpi2.keypoints) == 1\n assert kpi2.keypoints[0].y == 2\n assert kpi2.keypoints[0].x == 1\n\n got_exception = False\n try:\n kps_image = np.zeros((5, 5, 2), dtype=np.uint8)\n kps_image[2, 1, 0] = 255\n kps_image[4, 3, 1] = 10\n _ = ia.KeypointsOnImage.from_keypoint_image(kps_image, if_not_found_coords=\"exception-please\", threshold=20,\n nb_channels=3)\n except Exception as exc:\n assert \"Expected if_not_found_coords to be\" in str(exc)\n got_exception = True\n assert got_exception\n\n # to_distance_maps()\n kpi = ia.KeypointsOnImage(keypoints=[ia.Keypoint(x=2, y=3)], shape=(5, 5, 3))\n distance_map = kpi.to_distance_maps()\n expected_xx = np.float32([\n [0, 1, 2, 3, 4],\n [0, 1, 2, 3, 4],\n [0, 1, 2, 3, 4],\n [0, 1, 2, 3, 4],\n [0, 1, 2, 3, 4]\n ])\n expected_yy = np.float32([\n [0, 0, 0, 0, 0],\n [1, 1, 1, 1, 1],\n [2, 2, 2, 2, 2],\n [3, 3, 3, 3, 3],\n [4, 4, 4, 4, 4]\n ])\n expected = np.sqrt((expected_xx - 2)**2 + (expected_yy - 3)**2)\n assert distance_map.shape == (5, 5, 1)\n assert np.allclose(distance_map, expected[..., np.newaxis])\n\n distance_map_inv = kpi.to_distance_maps(inverted=True)\n expected_inv = np.divide(np.ones_like(expected), expected+1)\n assert np.allclose(distance_map_inv, expected_inv[..., np.newaxis])\n\n # to_distance_maps() with two keypoints\n # positions on (4, 4) map (X=position, 1=KP 1 is closest, 2=KP 2 is closest, B=close to both)\n # [1, X, 1, 1]\n # [1, 1, 1, B]\n # [B, 2, 2, 2]\n # [2, 2, X, 2]\n # this test could have been done a bit better by simply splitting the distance maps, one per keypoint, considering\n # the function returns one distance map per keypoint\n kpi = ia.KeypointsOnImage(keypoints=[ia.Keypoint(x=2, y=3), ia.Keypoint(x=1, y=0)], shape=(4, 4, 3))\n expected = np.float32([\n [(0-1)**2 + (0-0)**2, (1-1)**2 + (0-0)**2, (2-1)**2 + (0-0)**2, (3-1)**2 + (0-0)**2],\n [(0-1)**2 + (1-0)**2, (1-1)**2 + (1-0)**2, (2-1)**2 + (1-0)**2, (3-1)**2 + (1-0)**2],\n [(0-1)**2 + (2-0)**2, (1-2)**2 + (2-3)**2, (2-2)**2 + (2-3)**2, (3-2)**2 + (2-3)**2],\n [(0-2)**2 + (3-3)**2, (1-2)**2 + (3-3)**2, (2-2)**2 + (3-3)**2, (3-2)**2 + (3-3)**2],\n ])\n distance_map = kpi.to_distance_maps()\n expected = np.sqrt(expected)\n assert np.allclose(np.min(distance_map, axis=2), expected)\n\n distance_map_inv = kpi.to_distance_maps(inverted=True)\n expected_inv = np.divide(np.ones_like(expected), expected+1)\n assert np.allclose(np.max(distance_map_inv, axis=2), expected_inv)\n\n # from_distance_maps()\n distance_map1 = np.float32([\n [2, 2, 2, 2, 2],\n [2, 1, 1, 1, 2],\n [2, 1, 0, 1, 2],\n [2, 1, 1, 1, 2]\n ])\n distance_map2 = np.float32([\n [4, 3, 2, 2, 2],\n [4, 3, 2, 1, 1],\n [4, 3, 2, 1, 0.1],\n [4, 3, 2, 1, 1]\n ])\n distance_maps = np.concatenate([distance_map1[..., np.newaxis], distance_map2[..., np.newaxis]], axis=2)\n kpi = ia.KeypointsOnImage.from_distance_maps(distance_maps, nb_channels=4)\n assert len(kpi.keypoints) == 2\n assert kpi.keypoints[0].x == 2\n assert kpi.keypoints[0].y == 2\n assert kpi.keypoints[1].x == 4\n assert kpi.keypoints[1].y == 2\n assert kpi.shape == (4, 5, 4)\n\n kpi = ia.KeypointsOnImage.from_distance_maps(np.divide(np.ones_like(distance_maps), distance_maps+1),\n inverted=True)\n assert len(kpi.keypoints) == 2\n assert kpi.keypoints[0].x == 2\n assert kpi.keypoints[0].y == 2\n assert kpi.keypoints[1].x == 4\n assert kpi.keypoints[1].y == 2\n assert kpi.shape == (4, 5)\n\n kpi = ia.KeypointsOnImage.from_distance_maps(distance_maps, if_not_found_coords=(1, 1), threshold=0.09)\n assert len(kpi.keypoints) == 2\n assert kpi.keypoints[0].x == 2\n assert kpi.keypoints[0].y == 2\n assert kpi.keypoints[1].x == 1\n assert kpi.keypoints[1].y == 1\n assert kpi.shape == (4, 5)\n\n kpi = ia.KeypointsOnImage.from_distance_maps(distance_maps, if_not_found_coords={\"x\": 1, \"y\": 2}, threshold=0.09)\n assert len(kpi.keypoints) == 2\n assert kpi.keypoints[0].x == 2\n assert kpi.keypoints[0].y == 2\n assert kpi.keypoints[1].x == 1\n assert kpi.keypoints[1].y == 2\n assert kpi.shape == (4, 5)\n\n kpi = ia.KeypointsOnImage.from_distance_maps(distance_maps, if_not_found_coords=None, threshold=0.09)\n assert len(kpi.keypoints) == 1\n assert kpi.keypoints[0].x == 2\n assert kpi.keypoints[0].y == 2\n assert kpi.shape == (4, 5)\n\n got_exception = False\n try:\n _ = ia.KeypointsOnImage.from_distance_maps(distance_maps, if_not_found_coords=False, threshold=0.09)\n except Exception as exc:\n assert \"Expected if_not_found_coords to be\" in str(exc)\n got_exception = True\n assert got_exception\n\n # copy()\n kps = [ia.Keypoint(x=1, y=2), ia.Keypoint(x=3, y=4)]\n kpi = ia.KeypointsOnImage(keypoints=kps, shape=(5, 5, 3))\n kpi2 = kpi.copy()\n assert kpi2.keypoints[0].x == 1\n assert kpi2.keypoints[0].y == 2\n assert kpi2.keypoints[1].x == 3\n assert kpi2.keypoints[1].y == 4\n kps[0].x = 100\n assert kpi2.keypoints[0].x == 100\n assert kpi2.keypoints[0].y == 2\n assert kpi2.keypoints[1].x == 3\n assert kpi2.keypoints[1].y == 4\n\n # deepcopy()\n kps = [ia.Keypoint(x=1, y=2), ia.Keypoint(x=3, y=4)]\n kpi = ia.KeypointsOnImage(keypoints=kps, shape=(5, 5, 3))\n kpi2 = kpi.deepcopy()\n assert kpi2.keypoints[0].x == 1\n assert kpi2.keypoints[0].y == 2\n assert kpi2.keypoints[1].x == 3\n assert kpi2.keypoints[1].y == 4\n kps[0].x = 100\n assert kpi2.keypoints[0].x == 1\n assert kpi2.keypoints[0].y == 2\n assert kpi2.keypoints[1].x == 3\n assert kpi2.keypoints[1].y == 4\n\n # repr/str\n kps = [ia.Keypoint(x=1, y=2), ia.Keypoint(x=3, y=4)]\n kpi = ia.KeypointsOnImage(keypoints=kps, shape=(5, 5, 3))\n expected = \"KeypointsOnImage([Keypoint(x=1.00000000, y=2.00000000), Keypoint(x=3.00000000, y=4.00000000)], \" \\\n + \"shape=(5, 5, 3))\"\n assert kpi.__repr__() == kpi.__str__() == expected\n\n\ndef test_BoundingBox():\n eps = 1e-8\n\n # properties with ints\n bb = ia.BoundingBox(y1=10, x1=20, y2=30, x2=40, label=None)\n assert bb.y1_int == 10\n assert bb.x1_int == 20\n assert bb.y2_int == 30\n assert bb.x2_int == 40\n assert bb.width == 40 - 20\n assert bb.height == 30 - 10\n center_x = bb.x1 + (bb.x2 - bb.x1)/2\n center_y = bb.y1 + (bb.y2 - bb.y1)/2\n assert center_x - eps < bb.center_x < center_x + eps\n assert center_y - eps < bb.center_y < center_y + eps\n\n # wrong order of y1/y2, x1/x2\n bb = ia.BoundingBox(y1=30, x1=40, y2=10, x2=20, label=None)\n assert bb.y1_int == 10\n assert bb.x1_int == 20\n assert bb.y2_int == 30\n assert bb.x2_int == 40\n\n # properties with floats\n bb = ia.BoundingBox(y1=10.1, x1=20.1, y2=30.9, x2=40.9, label=None)\n assert bb.y1_int == 10\n assert bb.x1_int == 20\n assert bb.y2_int == 31\n assert bb.x2_int == 41\n assert bb.width == 40.9 - 20.1\n assert bb.height == 30.9 - 10.1\n center_x = bb.x1 + (bb.x2 - bb.x1)/2\n center_y = bb.y1 + (bb.y2 - bb.y1)/2\n assert center_x - eps < bb.center_x < center_x + eps\n assert center_y - eps < bb.center_y < center_y + eps\n\n # area\n bb = ia.BoundingBox(y1=10, x1=20, y2=30, x2=40, label=None)\n assert bb.area == (30-10) * (40-20)\n\n # contains\n bb = ia.BoundingBox(y1=1, x1=2, y2=1+4, x2=2+5, label=None)\n assert bb.contains(ia.Keypoint(x=2.5, y=1.5)) is True\n assert bb.contains(ia.Keypoint(x=2, y=1)) is True\n assert bb.contains(ia.Keypoint(x=0, y=0)) is False\n\n # project\n bb = ia.BoundingBox(y1=10, x1=20, y2=30, x2=40, label=None)\n bb2 = bb.project((10, 10), (10, 10))\n assert 10 - eps < bb2.y1 < 10 + eps\n assert 20 - eps < bb2.x1 < 20 + eps\n assert 30 - eps < bb2.y2 < 30 + eps\n assert 40 - eps < bb2.x2 < 40 + eps\n\n bb = ia.BoundingBox(y1=10, x1=20, y2=30, x2=40, label=None)\n bb2 = bb.project((10, 10), (20, 20))\n assert 10*2 - eps < bb2.y1 < 10*2 + eps\n assert 20*2 - eps < bb2.x1 < 20*2 + eps\n assert 30*2 - eps < bb2.y2 < 30*2 + eps\n assert 40*2 - eps < bb2.x2 < 40*2 + eps\n\n bb2 = bb.project((10, 10), (5, 5))\n assert 10*0.5 - eps < bb2.y1 < 10*0.5 + eps\n assert 20*0.5 - eps < bb2.x1 < 20*0.5 + eps\n assert 30*0.5 - eps < bb2.y2 < 30*0.5 + eps\n assert 40*0.5 - eps < bb2.x2 < 40*0.5 + eps\n\n bb2 = bb.project((10, 10), (10, 20))\n assert 10*1 - eps < bb2.y1 < 10*1 + eps\n assert 20*2 - eps < bb2.x1 < 20*2 + eps\n assert 30*1 - eps < bb2.y2 < 30*1 + eps\n assert 40*2 - eps < bb2.x2 < 40*2 + eps\n\n bb2 = bb.project((10, 10), (20, 10))\n assert 10*2 - eps < bb2.y1 < 10*2 + eps\n assert 20*1 - eps < bb2.x1 < 20*1 + eps\n assert 30*2 - eps < bb2.y2 < 30*2 + eps\n assert 40*1 - eps < bb2.x2 < 40*1 + eps\n\n # extend\n bb = ia.BoundingBox(y1=10, x1=20, y2=30, x2=40, label=None)\n bb2 = bb.extend(all_sides=1)\n assert bb2.y1 == 10-1\n assert bb2.y2 == 30+1\n assert bb2.x1 == 20-1\n assert bb2.x2 == 40+1\n\n bb2 = bb.extend(all_sides=-1)\n assert bb2.y1 == 10-(-1)\n assert bb2.y2 == 30+(-1)\n assert bb2.x1 == 20-(-1)\n assert bb2.x2 == 40+(-1)\n\n bb2 = bb.extend(top=1)\n assert bb2.y1 == 10-1\n assert bb2.y2 == 30+0\n assert bb2.x1 == 20-0\n assert bb2.x2 == 40+0\n\n bb2 = bb.extend(right=1)\n assert bb2.y1 == 10-0\n assert bb2.y2 == 30+0\n assert bb2.x1 == 20-0\n assert bb2.x2 == 40+1\n\n bb2 = bb.extend(bottom=1)\n assert bb2.y1 == 10-0\n assert bb2.y2 == 30+1\n assert bb2.x1 == 20-0\n assert bb2.x2 == 40+0\n\n bb2 = bb.extend(left=1)\n assert bb2.y1 == 10-0\n assert bb2.y2 == 30+0\n assert bb2.x1 == 20-1\n assert bb2.x2 == 40+0\n\n # intersection\n bb1 = ia.BoundingBox(y1=10, x1=20, y2=30, x2=40, label=None)\n bb2 = ia.BoundingBox(y1=10, x1=39, y2=30, x2=59, label=None)\n bb_inter = bb1.intersection(bb2)\n assert bb_inter.x1 == 39\n assert bb_inter.x2 == 40\n assert bb_inter.y1 == 10\n assert bb_inter.y2 == 30\n\n bb1 = ia.BoundingBox(y1=10, x1=20, y2=30, x2=40, label=None)\n bb2 = ia.BoundingBox(y1=10, x1=41, y2=30, x2=61, label=None)\n bb_inter = bb1.intersection(bb2, default=False)\n assert bb_inter is False\n\n # union\n bb1 = ia.BoundingBox(y1=10, x1=20, y2=30, x2=40, label=None)\n bb2 = ia.BoundingBox(y1=10, x1=39, y2=30, x2=59, label=None)\n bb_union = bb1.union(bb2)\n assert bb_union.x1 == 20\n assert bb_union.x2 == 59\n assert bb_union.y1 == 10\n assert bb_union.y2 == 30\n\n # iou\n bb1 = ia.BoundingBox(y1=10, x1=20, y2=30, x2=40, label=None)\n bb2 = ia.BoundingBox(y1=10, x1=20, y2=30, x2=40, label=None)\n iou = bb1.iou(bb2)\n assert 1.0 - eps < iou < 1.0 + eps\n\n bb1 = ia.BoundingBox(y1=10, x1=20, y2=30, x2=40, label=None)\n bb2 = ia.BoundingBox(y1=10, x1=41, y2=30, x2=61, label=None)\n iou = bb1.iou(bb2)\n assert 0.0 - eps < iou < 0.0 + eps\n\n bb1 = ia.BoundingBox(y1=10, x1=10, y2=20, x2=20, label=None)\n bb2 = ia.BoundingBox(y1=15, x1=15, y2=25, x2=25, label=None)\n iou = bb1.iou(bb2)\n area_union = 10 * 10 + 10 * 10 - 5 * 5\n area_intersection = 5 * 5\n iou_expected = area_intersection / area_union\n assert iou_expected - eps < iou < iou_expected + eps\n\n # is_fully_within_image\n bb = ia.BoundingBox(y1=10, x1=20, y2=30, x2=40, label=None)\n assert bb.is_fully_within_image((100, 100, 3)) is True\n assert bb.is_fully_within_image((20, 100, 3)) is False\n assert bb.is_fully_within_image((100, 30, 3)) is False\n assert bb.is_fully_within_image((1, 1, 3)) is False\n\n # is_partly_within_image\n bb = ia.BoundingBox(y1=10, x1=20, y2=30, x2=40, label=None)\n assert bb.is_partly_within_image((100, 100, 3)) is True\n assert bb.is_partly_within_image((20, 100, 3)) is True\n assert bb.is_partly_within_image((100, 30, 3)) is True\n assert bb.is_partly_within_image((1, 1, 3)) is False\n\n # is_out_of_image()\n bb = ia.BoundingBox(y1=10, x1=20, y2=30, x2=40, label=None)\n assert bb.is_out_of_image((100, 100, 3), partly=True, fully=True) is False\n assert bb.is_out_of_image((100, 100, 3), partly=False, fully=True) is False\n assert bb.is_out_of_image((100, 100, 3), partly=True, fully=False) is False\n assert bb.is_out_of_image((20, 100, 3), partly=True, fully=True) is True\n assert bb.is_out_of_image((20, 100, 3), partly=False, fully=True) is False\n assert bb.is_out_of_image((20, 100, 3), partly=True, fully=False) is True\n assert bb.is_out_of_image((100, 30, 3), partly=True, fully=True) is True\n assert bb.is_out_of_image((100, 30, 3), partly=False, fully=True) is False\n assert bb.is_out_of_image((100, 30, 3), partly=True, fully=False) is True\n assert bb.is_out_of_image((1, 1, 3), partly=True, fully=True) is True\n assert bb.is_out_of_image((1, 1, 3), partly=False, fully=True) is True\n assert bb.is_out_of_image((1, 1, 3), partly=True, fully=False) is False\n\n # clip_out_of_image\n bb = ia.BoundingBox(y1=10, x1=20, y2=30, x2=40, label=None)\n bb_cut = bb.clip_out_of_image((100, 100, 3))\n eps = np.finfo(np.float32).eps\n assert bb_cut.y1 == 10\n assert bb_cut.x1 == 20\n assert bb_cut.y2 == 30\n assert bb_cut.x2 == 40\n bb_cut = bb.clip_out_of_image(np.zeros((100, 100, 3), dtype=np.uint8))\n assert bb_cut.y1 == 10\n assert bb_cut.x1 == 20\n assert bb_cut.y2 == 30\n assert bb_cut.x2 == 40\n bb_cut = bb.clip_out_of_image((20, 100, 3))\n assert bb_cut.y1 == 10\n assert bb_cut.x1 == 20\n assert 20 - 2*eps < bb_cut.y2 < 20\n assert bb_cut.x2 == 40\n bb_cut = bb.clip_out_of_image((100, 30, 3))\n assert bb_cut.y1 == 10\n assert bb_cut.x1 == 20\n assert bb_cut.y2 == 30\n assert 30 - 2*eps < bb_cut.x2 < 30\n\n # shift\n bb = ia.BoundingBox(y1=10, x1=20, y2=30, x2=40, label=None)\n bb_top = bb.shift(top=0)\n bb_right = bb.shift(right=0)\n bb_bottom = bb.shift(bottom=0)\n bb_left = bb.shift(left=0)\n assert bb_top.y1 == 10\n assert bb_top.x1 == 20\n assert bb_top.y2 == 30\n assert bb_top.x2 == 40\n assert bb_right.y1 == 10\n assert bb_right.x1 == 20\n assert bb_right.y2 == 30\n assert bb_right.x2 == 40\n assert bb_bottom.y1 == 10\n assert bb_bottom.x1 == 20\n assert bb_bottom.y2 == 30\n assert bb_bottom.x2 == 40\n assert bb_left.y1 == 10\n assert bb_left.x1 == 20\n assert bb_left.y2 == 30\n assert bb_left.x2 == 40\n bb_top = bb.shift(top=1)\n bb_right = bb.shift(right=1)\n bb_bottom = bb.shift(bottom=1)\n bb_left = bb.shift(left=1)\n assert bb_top.y1 == 10+1\n assert bb_top.x1 == 20\n assert bb_top.y2 == 30+1\n assert bb_top.x2 == 40\n assert bb_right.y1 == 10\n assert bb_right.x1 == 20-1\n assert bb_right.y2 == 30\n assert bb_right.x2 == 40-1\n assert bb_bottom.y1 == 10-1\n assert bb_bottom.x1 == 20\n assert bb_bottom.y2 == 30-1\n assert bb_bottom.x2 == 40\n assert bb_left.y1 == 10\n assert bb_left.x1 == 20+1\n assert bb_left.y2 == 30\n assert bb_left.x2 == 40+1\n bb_top = bb.shift(top=-1)\n bb_right = bb.shift(right=-1)\n bb_bottom = bb.shift(bottom=-1)\n bb_left = bb.shift(left=-1)\n assert bb_top.y1 == 10-1\n assert bb_top.x1 == 20\n assert bb_top.y2 == 30-1\n assert bb_top.x2 == 40\n assert bb_right.y1 == 10\n assert bb_right.x1 == 20+1\n assert bb_right.y2 == 30\n assert bb_right.x2 == 40+1\n assert bb_bottom.y1 == 10+1\n assert bb_bottom.x1 == 20\n assert bb_bottom.y2 == 30+1\n assert bb_bottom.x2 == 40\n assert bb_left.y1 == 10\n assert bb_left.x1 == 20-1\n assert bb_left.y2 == 30\n assert bb_left.x2 == 40-1\n bb_mix = bb.shift(top=1, bottom=2, left=3, right=4)\n assert bb_mix.y1 == 10+1-2\n assert bb_mix.x1 == 20+3-4\n assert bb_mix.y2 == 30+3-4\n assert bb_mix.x2 == 40+1-2\n\n # draw_on_image()\n image = np.zeros((10, 10, 3), dtype=np.uint8)\n bb = ia.BoundingBox(y1=1, x1=1, y2=3, x2=3, label=None)\n bb_mask = np.zeros(image.shape[0:2], dtype=np.bool)\n bb_mask[1:3+1, 1] = True\n bb_mask[1:3+1, 3] = True\n bb_mask[1, 1:3+1] = True\n bb_mask[3, 1:3+1] = True\n image_bb = bb.draw_on_image(image, color=[255, 255, 255], alpha=1.0, thickness=1, copy=True,\n raise_if_out_of_image=False)\n assert np.all(image_bb[bb_mask] == [255, 255, 255])\n assert np.all(image_bb[~bb_mask] == [0, 0, 0])\n assert np.all(image == 0)\n\n image_bb = bb.draw_on_image(image, color=[255, 0, 0], alpha=1.0, thickness=1, copy=True,\n raise_if_out_of_image=False)\n assert np.all(image_bb[bb_mask] == [255, 0, 0])\n assert np.all(image_bb[~bb_mask] == [0, 0, 0])\n\n image_bb = bb.draw_on_image(image, color=128, alpha=1.0, thickness=1, copy=True, raise_if_out_of_image=False)\n assert np.all(image_bb[bb_mask] == [128, 128, 128])\n assert np.all(image_bb[~bb_mask] == [0, 0, 0])\n\n image_bb = bb.draw_on_image(image+100, color=[200, 200, 200], alpha=0.5, thickness=1, copy=True,\n raise_if_out_of_image=False)\n assert np.all(image_bb[bb_mask] == [150, 150, 150])\n assert np.all(image_bb[~bb_mask] == [100, 100, 100])\n\n image_bb = bb.draw_on_image((image+100).astype(np.float32), color=[200, 200, 200], alpha=0.5, thickness=1,\n copy=True, raise_if_out_of_image=False)\n assert np.sum(np.abs((image_bb - [150, 150, 150])[bb_mask])) < 0.1\n assert np.sum(np.abs((image_bb - [100, 100, 100])[~bb_mask])) < 0.1\n\n image_bb = bb.draw_on_image(image, color=[255, 255, 255], alpha=1.0, thickness=1, copy=False,\n raise_if_out_of_image=False)\n assert np.all(image_bb[bb_mask] == [255, 255, 255])\n assert np.all(image_bb[~bb_mask] == [0, 0, 0])\n assert np.all(image[bb_mask] == [255, 255, 255])\n assert np.all(image[~bb_mask] == [0, 0, 0])\n\n image = np.zeros_like(image)\n bb = ia.BoundingBox(y1=-1, x1=-1, y2=2, x2=2, label=None)\n bb_mask = np.zeros(image.shape[0:2], dtype=np.bool)\n bb_mask[2, 0:3] = True\n bb_mask[0:3, 2] = True\n image_bb = bb.draw_on_image(image, color=[255, 255, 255], alpha=1.0, thickness=1, copy=True,\n raise_if_out_of_image=False)\n assert np.all(image_bb[bb_mask] == [255, 255, 255])\n assert np.all(image_bb[~bb_mask] == [0, 0, 0])\n\n bb = ia.BoundingBox(y1=1, x1=1, y2=3, x2=3, label=None)\n bb_mask = np.zeros(image.shape[0:2], dtype=np.bool)\n bb_mask[0:5, 0:5] = True\n bb_mask[2, 2] = False\n image_bb = bb.draw_on_image(image, color=[255, 255, 255], alpha=1.0, thickness=2, copy=True,\n raise_if_out_of_image=False)\n assert np.all(image_bb[bb_mask] == [255, 255, 255])\n assert np.all(image_bb[~bb_mask] == [0, 0, 0])\n\n bb = ia.BoundingBox(y1=-1, x1=-1, y2=1, x2=1, label=None)\n bb_mask = np.zeros(image.shape[0:2], dtype=np.bool)\n bb_mask[0:1+1, 1] = True\n bb_mask[1, 0:1+1] = True\n image_bb = bb.draw_on_image(image, color=[255, 255, 255], alpha=1.0, thickness=1, copy=True,\n raise_if_out_of_image=False)\n assert np.all(image_bb[bb_mask] == [255, 255, 255])\n assert np.all(image_bb[~bb_mask] == [0, 0, 0])\n\n bb = ia.BoundingBox(y1=-1, x1=-1, y2=1, x2=1, label=None)\n got_exception = False\n try:\n _ = bb.draw_on_image(image, color=[255, 255, 255], alpha=1.0, thickness=1, copy=True,\n raise_if_out_of_image=True)\n except Exception:\n got_exception = True\n assert got_exception is False\n\n bb = ia.BoundingBox(y1=-5, x1=-5, y2=-1, x2=-1, label=None)\n got_exception = False\n try:\n _ = bb.draw_on_image(image, color=[255, 255, 255], alpha=1.0, thickness=1, copy=True,\n raise_if_out_of_image=True)\n except Exception:\n got_exception = True\n assert got_exception is True\n\n # extract_from_image()\n image = np.random.RandomState(1234).randint(0, 255, size=(10, 10, 3))\n bb = ia.BoundingBox(y1=1, y2=3, x1=1, x2=3, label=None)\n image_sub = bb.extract_from_image(image)\n assert np.array_equal(image_sub, image[1:3, 1:3, :])\n\n image = np.random.RandomState(1234).randint(0, 255, size=(10, 10))\n bb = ia.BoundingBox(y1=1, y2=3, x1=1, x2=3, label=None)\n image_sub = bb.extract_from_image(image)\n assert np.array_equal(image_sub, image[1:3, 1:3])\n\n image = np.random.RandomState(1234).randint(0, 255, size=(10, 10))\n bb = ia.BoundingBox(y1=1, y2=3, x1=1, x2=3, label=None)\n image_sub = bb.extract_from_image(image)\n assert np.array_equal(image_sub, image[1:3, 1:3])\n\n image = np.random.RandomState(1234).randint(0, 255, size=(10, 10, 3))\n image_pad = np.pad(image, ((0, 1), (0, 1), (0, 0)), mode=\"constant\", constant_values=0)\n bb = ia.BoundingBox(y1=8, y2=11, x1=8, x2=11, label=None)\n image_sub = bb.extract_from_image(image)\n assert np.array_equal(image_sub, image_pad[8:11, 8:11, :])\n\n image = np.random.RandomState(1234).randint(0, 255, size=(10, 10))\n image_pad = np.pad(image, ((0, 1), (0, 1)), mode=\"constant\", constant_values=0)\n bb = ia.BoundingBox(y1=8, y2=11, x1=8, x2=11, label=None)\n image_sub = bb.extract_from_image(image)\n assert np.array_equal(image_sub, image_pad[8:11, 8:11])\n\n image = np.random.RandomState(1234).randint(0, 255, size=(10, 10, 3))\n image_pad = np.pad(image, ((1, 0), (1, 0), (0, 0)), mode=\"constant\", constant_values=0)\n bb = ia.BoundingBox(y1=-1, y2=3, x1=-1, x2=4, label=None)\n image_sub = bb.extract_from_image(image)\n assert np.array_equal(image_sub, image_pad[0:4, 0:5, :])\n\n image = np.random.RandomState(1234).randint(0, 255, size=(10, 10, 3))\n bb = ia.BoundingBox(y1=1, y2=1.99999, x1=1, x2=1.99999, label=None)\n image_sub = bb.extract_from_image(image)\n assert np.array_equal(image_sub, image[1:1+1, 1:1+1, :])\n\n image = np.random.RandomState(1234).randint(0, 255, size=(10, 10, 3))\n bb = ia.BoundingBox(y1=1, y2=1, x1=2, x2=4, label=None)\n image_sub = bb.extract_from_image(image)\n assert np.array_equal(image_sub, image[1:1+1, 2:4, :])\n\n image = np.random.RandomState(1234).randint(0, 255, size=(10, 10, 3))\n bb = ia.BoundingBox(y1=1, y2=1, x1=2, x2=2, label=None)\n image_sub = bb.extract_from_image(image)\n assert np.array_equal(image_sub, image[1:1+1, 2:2+1, :])\n\n # to_keypoints()\n bb = ia.BoundingBox(y1=1, y2=3, x1=1, x2=3, label=None)\n kps = bb.to_keypoints()\n assert kps[0].y == 1\n assert kps[0].x == 1\n assert kps[1].y == 1\n assert kps[1].x == 3\n assert kps[2].y == 3\n assert kps[2].x == 3\n assert kps[3].y == 3\n assert kps[3].x == 1\n\n # copy()\n bb = ia.BoundingBox(y1=1, y2=3, x1=1, x2=3, label=\"test\")\n bb2 = bb.copy()\n assert bb2.y1 == 1\n assert bb2.y2 == 3\n assert bb2.x1 == 1\n assert bb2.x2 == 3\n assert bb2.label == \"test\"\n\n bb2 = bb.copy(y1=10, x1=20, y2=30, x2=40, label=\"test2\")\n assert bb2.y1 == 10\n assert bb2.x1 == 20\n assert bb2.y2 == 30\n assert bb2.x2 == 40\n assert bb2.label == \"test2\"\n\n # deepcopy()\n bb = ia.BoundingBox(y1=1, y2=3, x1=1, x2=3, label=[\"test\"])\n bb2 = bb.deepcopy()\n assert bb2.y1 == 1\n assert bb2.y2 == 3\n assert bb2.x1 == 1\n assert bb2.x2 == 3\n assert bb2.label[0] == \"test\"\n\n # BoundingBox_repr()\n bb = ia.BoundingBox(y1=1, y2=3, x1=1, x2=3, label=None)\n assert bb.__repr__() == \"BoundingBox(x1=1.0000, y1=1.0000, x2=3.0000, y2=3.0000, label=None)\"\n\n # test_BoundingBox_str()\n bb = ia.BoundingBox(y1=1, y2=3, x1=1, x2=3, label=None)\n assert bb.__str__() == \"BoundingBox(x1=1.0000, y1=1.0000, x2=3.0000, y2=3.0000, label=None)\"\n\n\ndef test_BoundingBoxesOnImage():\n reseed()\n\n # test height/width\n bb1 = ia.BoundingBox(y1=10, x1=20, y2=30, x2=40, label=None)\n bb2 = ia.BoundingBox(y1=15, x1=25, y2=35, x2=45, label=None)\n bbsoi = ia.BoundingBoxesOnImage([bb1, bb2], shape=(40, 50, 3))\n assert bbsoi.height == 40\n assert bbsoi.width == 50\n\n bb1 = ia.BoundingBox(y1=10, x1=20, y2=30, x2=40, label=None)\n bb2 = ia.BoundingBox(y1=15, x1=25, y2=35, x2=45, label=None)\n bbsoi = ia.BoundingBoxesOnImage([bb1, bb2], shape=np.zeros((40, 50, 3), dtype=np.uint8))\n assert bbsoi.height == 40\n assert bbsoi.width == 50\n\n # empty\n bb = ia.BoundingBox(y1=10, x1=20, y2=30, x2=40, label=None)\n bbsoi = ia.BoundingBoxesOnImage([bb], shape=(40, 50, 3))\n assert not bbsoi.empty\n\n bbsoi = ia.BoundingBoxesOnImage([], shape=(40, 50, 3))\n assert bbsoi.empty\n\n # on()\n bb1 = ia.BoundingBox(y1=10, x1=20, y2=30, x2=40, label=None)\n bb2 = ia.BoundingBox(y1=15, x1=25, y2=35, x2=45, label=None)\n bbsoi = ia.BoundingBoxesOnImage([bb1, bb2], shape=np.zeros((40, 50, 3), dtype=np.uint8))\n\n bbsoi_projected = bbsoi.on((40, 50))\n assert bbsoi_projected.bounding_boxes[0].y1 == 10\n assert bbsoi_projected.bounding_boxes[0].x1 == 20\n assert bbsoi_projected.bounding_boxes[0].y2 == 30\n assert bbsoi_projected.bounding_boxes[0].x2 == 40\n assert bbsoi_projected.bounding_boxes[1].y1 == 15\n assert bbsoi_projected.bounding_boxes[1].x1 == 25\n assert bbsoi_projected.bounding_boxes[1].y2 == 35\n assert bbsoi_projected.bounding_boxes[1].x2 == 45\n\n bbsoi_projected = bbsoi.on((40*2, 50*2, 3))\n assert bbsoi_projected.bounding_boxes[0].y1 == 10*2\n assert bbsoi_projected.bounding_boxes[0].x1 == 20*2\n assert bbsoi_projected.bounding_boxes[0].y2 == 30*2\n assert bbsoi_projected.bounding_boxes[0].x2 == 40*2\n assert bbsoi_projected.bounding_boxes[1].y1 == 15*2\n assert bbsoi_projected.bounding_boxes[1].x1 == 25*2\n assert bbsoi_projected.bounding_boxes[1].y2 == 35*2\n assert bbsoi_projected.bounding_boxes[1].x2 == 45*2\n\n bbsoi_projected = bbsoi.on(np.zeros((40*2, 50*2, 3), dtype=np.uint8))\n assert bbsoi_projected.bounding_boxes[0].y1 == 10*2\n assert bbsoi_projected.bounding_boxes[0].x1 == 20*2\n assert bbsoi_projected.bounding_boxes[0].y2 == 30*2\n assert bbsoi_projected.bounding_boxes[0].x2 == 40*2\n assert bbsoi_projected.bounding_boxes[1].y1 == 15*2\n assert bbsoi_projected.bounding_boxes[1].x1 == 25*2\n assert bbsoi_projected.bounding_boxes[1].y2 == 35*2\n assert bbsoi_projected.bounding_boxes[1].x2 == 45*2\n\n # from_xyxy_array()\n bbsoi = ia.BoundingBoxesOnImage.from_xyxy_array(\n np.float32([\n [0.0, 0.0, 1.0, 1.0],\n [1.0, 2.0, 3.0, 4.0]\n ]),\n shape=(40, 50, 3)\n )\n assert len(bbsoi.bounding_boxes) == 2\n assert np.allclose(bbsoi.bounding_boxes[0].x1, 0.0)\n assert np.allclose(bbsoi.bounding_boxes[0].y1, 0.0)\n assert np.allclose(bbsoi.bounding_boxes[0].x2, 1.0)\n assert np.allclose(bbsoi.bounding_boxes[0].y2, 1.0)\n assert np.allclose(bbsoi.bounding_boxes[1].x1, 1.0)\n assert np.allclose(bbsoi.bounding_boxes[1].y1, 2.0)\n assert np.allclose(bbsoi.bounding_boxes[1].x2, 3.0)\n assert np.allclose(bbsoi.bounding_boxes[1].y2, 4.0)\n assert bbsoi.shape == (40, 50, 3)\n\n bbsoi = ia.BoundingBoxesOnImage.from_xyxy_array(\n np.int32([\n [0, 0, 1, 1],\n [1, 2, 3, 4]\n ]),\n shape=(40, 50, 3)\n )\n assert len(bbsoi.bounding_boxes) == 2\n assert np.allclose(bbsoi.bounding_boxes[0].x1, 0.0)\n assert np.allclose(bbsoi.bounding_boxes[0].y1, 0.0)\n assert np.allclose(bbsoi.bounding_boxes[0].x2, 1.0)\n assert np.allclose(bbsoi.bounding_boxes[0].y2, 1.0)\n assert np.allclose(bbsoi.bounding_boxes[1].x1, 1.0)\n assert np.allclose(bbsoi.bounding_boxes[1].y1, 2.0)\n assert np.allclose(bbsoi.bounding_boxes[1].x2, 3.0)\n assert np.allclose(bbsoi.bounding_boxes[1].y2, 4.0)\n assert bbsoi.shape == (40, 50, 3)\n\n bbsoi = ia.BoundingBoxesOnImage.from_xyxy_array(\n np.zeros((0, 4), dtype=np.float32),\n shape=(40, 50, 3)\n )\n assert len(bbsoi.bounding_boxes) == 0\n assert bbsoi.shape == (40, 50, 3)\n\n # to_xyxy_array()\n xyxy_arr = np.float32([\n [0.0, 0.0, 1.0, 1.0],\n [1.0, 2.0, 3.0, 4.0]\n ])\n bbsoi = ia.BoundingBoxesOnImage.from_xyxy_array(xyxy_arr, shape=(40, 50, 3))\n xyxy_arr_out = bbsoi.to_xyxy_array()\n assert np.allclose(xyxy_arr, xyxy_arr_out)\n assert xyxy_arr_out.dtype == np.float32\n\n xyxy_arr_out = bbsoi.to_xyxy_array(dtype=np.int32)\n assert np.allclose(xyxy_arr.astype(np.int32), xyxy_arr_out)\n assert xyxy_arr_out.dtype == np.int32\n\n xyxy_arr_out = ia.BoundingBoxesOnImage([], shape=(40, 50, 3)).to_xyxy_array(dtype=np.int32)\n assert xyxy_arr_out.shape == (0, 4)\n\n # draw_on_image()\n bb1 = ia.BoundingBox(y1=10, x1=20, y2=30, x2=40, label=None)\n bb2 = ia.BoundingBox(y1=15, x1=25, y2=35, x2=45, label=None)\n bbsoi = ia.BoundingBoxesOnImage([bb1, bb2], shape=(40, 50, 3))\n image = bbsoi.draw_on_image(np.zeros(bbsoi.shape, dtype=np.uint8), color=[0, 255, 0], alpha=1.0, thickness=1,\n copy=True, raise_if_out_of_image=False)\n assert np.all(image[10-1, 20-1, :] == [0, 0, 0])\n assert np.all(image[10-1, 20-0, :] == [0, 0, 0])\n assert np.all(image[10-0, 20-1, :] == [0, 0, 0])\n assert np.all(image[10-0, 20-0, :] == [0, 255, 0])\n assert np.all(image[10+1, 20+1, :] == [0, 0, 0])\n\n assert np.all(image[30-1, 40-1, :] == [0, 0, 0])\n assert np.all(image[30+1, 40-0, :] == [0, 0, 0])\n assert np.all(image[30+0, 40+1, :] == [0, 0, 0])\n assert np.all(image[30+0, 40+0, :] == [0, 255, 0])\n assert np.all(image[30+1, 40+1, :] == [0, 0, 0])\n\n assert np.all(image[15-1, 25-1, :] == [0, 0, 0])\n assert np.all(image[15-1, 25-0, :] == [0, 0, 0])\n assert np.all(image[15-0, 25-1, :] == [0, 0, 0])\n assert np.all(image[15-0, 25-0, :] == [0, 255, 0])\n assert np.all(image[15+1, 25+1, :] == [0, 0, 0])\n\n assert np.all(image[35-1, 45-1, :] == [0, 0, 0])\n assert np.all(image[35+1, 45+0, :] == [0, 0, 0])\n assert np.all(image[35+0, 45+1, :] == [0, 0, 0])\n assert np.all(image[35+0, 45+0, :] == [0, 255, 0])\n assert np.all(image[35+1, 45+1, :] == [0, 0, 0])\n\n # remove_out_of_image()\n bb1 = ia.BoundingBox(y1=10, x1=20, y2=30, x2=40, label=None)\n bb2 = ia.BoundingBox(y1=15, x1=25, y2=35, x2=51, label=None)\n bbsoi = ia.BoundingBoxesOnImage([bb1, bb2], shape=(40, 50, 3))\n bbsoi_slim = bbsoi.remove_out_of_image(fully=True, partly=True)\n assert len(bbsoi_slim.bounding_boxes) == 1\n assert bbsoi_slim.bounding_boxes[0] == bb1\n\n # clip_out_of_image()\n bb1 = ia.BoundingBox(y1=10, x1=20, y2=30, x2=40, label=None)\n bb2 = ia.BoundingBox(y1=15, x1=25, y2=35, x2=51, label=None)\n bbsoi = ia.BoundingBoxesOnImage([bb1, bb2], shape=(40, 50, 3))\n eps = np.finfo(np.float32).eps\n bbsoi_clip = bbsoi.clip_out_of_image()\n assert len(bbsoi_clip.bounding_boxes) == 2\n assert bbsoi_clip.bounding_boxes[0].y1 == 10\n assert bbsoi_clip.bounding_boxes[0].x1 == 20\n assert bbsoi_clip.bounding_boxes[0].y2 == 30\n assert bbsoi_clip.bounding_boxes[0].x2 == 40\n assert bbsoi_clip.bounding_boxes[1].y1 == 15\n assert bbsoi_clip.bounding_boxes[1].x1 == 25\n assert bbsoi_clip.bounding_boxes[1].y2 == 35\n assert 50 - 2*eps < bbsoi_clip.bounding_boxes[1].x2 < 50\n\n # shift()\n bb1 = ia.BoundingBox(y1=10, x1=20, y2=30, x2=40, label=None)\n bb2 = ia.BoundingBox(y1=15, x1=25, y2=35, x2=51, label=None)\n bbsoi = ia.BoundingBoxesOnImage([bb1, bb2], shape=(40, 50, 3))\n bbsoi_shifted = bbsoi.shift(right=1)\n assert len(bbsoi_shifted.bounding_boxes) == 2\n assert bbsoi_shifted.bounding_boxes[0].y1 == 10\n assert bbsoi_shifted.bounding_boxes[0].x1 == 20 - 1\n assert bbsoi_shifted.bounding_boxes[0].y2 == 30\n assert bbsoi_shifted.bounding_boxes[0].x2 == 40 - 1\n assert bbsoi_shifted.bounding_boxes[1].y1 == 15\n assert bbsoi_shifted.bounding_boxes[1].x1 == 25 - 1\n assert bbsoi_shifted.bounding_boxes[1].y2 == 35\n assert bbsoi_shifted.bounding_boxes[1].x2 == 51 - 1\n\n # copy()\n bb1 = ia.BoundingBox(y1=10, x1=20, y2=30, x2=40, label=None)\n bb2 = ia.BoundingBox(y1=15, x1=25, y2=35, x2=51, label=None)\n bbsoi = ia.BoundingBoxesOnImage([bb1, bb2], shape=(40, 50, 3))\n bbsoi_copy = bbsoi.copy()\n assert len(bbsoi.bounding_boxes) == 2\n assert bbsoi_copy.bounding_boxes[0].y1 == 10\n assert bbsoi_copy.bounding_boxes[0].x1 == 20\n assert bbsoi_copy.bounding_boxes[0].y2 == 30\n assert bbsoi_copy.bounding_boxes[0].x2 == 40\n assert bbsoi_copy.bounding_boxes[1].y1 == 15\n assert bbsoi_copy.bounding_boxes[1].x1 == 25\n assert bbsoi_copy.bounding_boxes[1].y2 == 35\n assert bbsoi_copy.bounding_boxes[1].x2 == 51\n\n bbsoi.bounding_boxes[0].y1 = 0\n assert bbsoi_copy.bounding_boxes[0].y1 == 0\n\n # deepcopy()\n bb1 = ia.BoundingBox(y1=10, x1=20, y2=30, x2=40, label=None)\n bb2 = ia.BoundingBox(y1=15, x1=25, y2=35, x2=51, label=None)\n bbsoi = ia.BoundingBoxesOnImage([bb1, bb2], shape=(40, 50, 3))\n bbsoi_copy = bbsoi.deepcopy()\n assert len(bbsoi.bounding_boxes) == 2\n assert bbsoi_copy.bounding_boxes[0].y1 == 10\n assert bbsoi_copy.bounding_boxes[0].x1 == 20\n assert bbsoi_copy.bounding_boxes[0].y2 == 30\n assert bbsoi_copy.bounding_boxes[0].x2 == 40\n assert bbsoi_copy.bounding_boxes[1].y1 == 15\n assert bbsoi_copy.bounding_boxes[1].x1 == 25\n assert bbsoi_copy.bounding_boxes[1].y2 == 35\n assert bbsoi_copy.bounding_boxes[1].x2 == 51\n\n bbsoi.bounding_boxes[0].y1 = 0\n assert bbsoi_copy.bounding_boxes[0].y1 == 10\n\n # repr() / str()\n bb1 = ia.BoundingBox(y1=10, x1=20, y2=30, x2=40, label=None)\n bb2 = ia.BoundingBox(y1=15, x1=25, y2=35, x2=51, label=None)\n bbsoi = ia.BoundingBoxesOnImage([bb1, bb2], shape=(40, 50, 3))\n bb1_expected = \"BoundingBox(x1=20.0000, y1=10.0000, x2=40.0000, y2=30.0000, label=None)\"\n bb2_expected = \"BoundingBox(x1=25.0000, y1=15.0000, x2=51.0000, y2=35.0000, label=None)\"\n expected = \"BoundingBoxesOnImage([%s, %s], shape=(40, 50, 3))\" % (bb1_expected, bb2_expected)\n assert bbsoi.__repr__() == bbsoi.__str__() == expected\n\n\ndef test_HeatmapsOnImage_draw():\n heatmaps_arr = np.float32([\n [0.5, 0.0, 0.0, 0.5],\n [0.0, 1.0, 1.0, 0.0],\n [0.0, 1.0, 1.0, 0.0],\n [0.5, 0.0, 0.0, 0.5],\n ])\n heatmaps = ia.HeatmapsOnImage(heatmaps_arr, shape=(4, 4, 3))\n\n heatmaps_drawn = heatmaps.draw()[0]\n assert heatmaps_drawn.shape == (4, 4, 3)\n v1 = heatmaps_drawn[0, 1]\n v2 = heatmaps_drawn[0, 0]\n v3 = heatmaps_drawn[1, 1]\n\n for y, x in [(0, 1), (0, 2), (1, 0), (1, 3), (2, 0), (2, 3), (3, 1), (3, 2)]:\n assert np.allclose(heatmaps_drawn[y, x], v1)\n\n for y, x in [(0, 0), (0, 3), (3, 0), (3, 3)]:\n assert np.allclose(heatmaps_drawn[y, x], v2)\n\n for y, x in [(1, 1), (1, 2), (2, 1), (2, 2)]:\n assert np.allclose(heatmaps_drawn[y, x], v3)\n\n # size differs from heatmap array size\n heatmaps_arr = np.float32([\n [0.0, 1.0],\n [0.0, 1.0]\n ])\n heatmaps = ia.HeatmapsOnImage(heatmaps_arr, shape=(2, 2, 3))\n\n heatmaps_drawn = heatmaps.draw(size=(4, 4))[0]\n assert heatmaps_drawn.shape == (4, 4, 3)\n v1 = heatmaps_drawn[0, 0]\n v2 = heatmaps_drawn[0, -1]\n\n for y in range(4):\n for x in range(2):\n assert np.allclose(heatmaps_drawn[y, x], v1)\n\n for y in range(4):\n for x in range(2, 4):\n assert np.allclose(heatmaps_drawn[y, x], v2)\n\n\ndef test_HeatmapsOnImage_draw_on_image():\n heatmaps_arr = np.float32([\n [0.0, 1.0],\n [0.0, 1.0]\n ])\n heatmaps = ia.HeatmapsOnImage(heatmaps_arr, shape=(2, 2, 3))\n\n image = np.uint8([\n [0, 0, 0, 255],\n [0, 0, 0, 255],\n [0, 0, 0, 255],\n [0, 0, 0, 255]\n ])\n image = np.tile(image[..., np.newaxis], (1, 1, 3))\n\n heatmaps_drawn = heatmaps.draw_on_image(image, alpha=0.5, cmap=None)[0]\n assert heatmaps_drawn.shape == (4, 4, 3)\n assert np.all(heatmaps_drawn[0:4, 0:2, :] == 0)\n assert np.all(heatmaps_drawn[0:4, 2:3, :] == 128) or np.all(heatmaps_drawn[0:4, 2:3, :] == 127)\n assert np.all(heatmaps_drawn[0:4, 3:4, :] == 255) or np.all(heatmaps_drawn[0:4, 3:4, :] == 254)\n\n image = np.uint8([\n [0, 0, 0, 0],\n [0, 0, 0, 0],\n [0, 0, 0, 0],\n [0, 0, 0, 0]\n ])\n image = np.tile(image[..., np.newaxis], (1, 1, 3))\n\n heatmaps_drawn = heatmaps.draw_on_image(image, alpha=0.5, resize=\"image\", cmap=None)[0]\n assert heatmaps_drawn.shape == (2, 2, 3)\n assert np.all(heatmaps_drawn[0:2, 0, :] == 0)\n assert np.all(heatmaps_drawn[0:2, 1, :] == 128) or np.all(heatmaps_drawn[0:2, 1, :] == 127)\n\n\ndef test_HeatmapsOnImage_invert():\n heatmaps_arr = np.float32([\n [0.0, 5.0, 10.0],\n [-1.0, -2.0, 7.5]\n ])\n expected = np.float32([\n [8.0, 3.0, -2.0],\n [9.0, 10.0, 0.5]\n ])\n\n # (H, W)\n heatmaps = ia.HeatmapsOnImage(heatmaps_arr, shape=(2, 3), min_value=-2.0, max_value=10.0)\n assert np.allclose(heatmaps.get_arr(), heatmaps_arr)\n assert np.allclose(heatmaps.invert().get_arr(), expected)\n\n # (H, W, 1)\n heatmaps = ia.HeatmapsOnImage(heatmaps_arr[..., np.newaxis], shape=(2, 3), min_value=-2.0, max_value=10.0)\n assert np.allclose(heatmaps.get_arr(), heatmaps_arr[..., np.newaxis])\n assert np.allclose(heatmaps.invert().get_arr(), expected[..., np.newaxis])\n\n\ndef test_HeatmapsOnImage_pad():\n heatmaps_arr = np.float32([\n [0.0, 1.0],\n [0.0, 1.0]\n ])\n heatmaps = ia.HeatmapsOnImage(heatmaps_arr, shape=(2, 2, 3))\n\n heatmaps_padded = heatmaps.pad(top=1, right=2, bottom=3, left=4)\n assert heatmaps_padded.arr_0to1.shape == (2+(1+3), 2+(4+2), 1)\n assert np.allclose(\n heatmaps_padded.arr_0to1[:, :, 0],\n np.float32([\n [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0],\n [0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0],\n [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]\n ])\n )\n\n heatmaps_padded = heatmaps.pad(top=1, right=2, bottom=3, left=4, cval=0.5)\n assert heatmaps_padded.arr_0to1.shape == (2+(1+3), 2+(4+2), 1)\n assert np.allclose(\n heatmaps_padded.arr_0to1[:, :, 0],\n np.float32([\n [0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5],\n [0.5, 0.5, 0.5, 0.5, 0.0, 1.0, 0.5, 0.5],\n [0.5, 0.5, 0.5, 0.5, 0.0, 1.0, 0.5, 0.5],\n [0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5],\n [0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5],\n [0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5]\n ])\n )\n\n heatmaps_padded = heatmaps.pad(top=1, right=2, bottom=3, left=4, mode=\"edge\")\n assert heatmaps_padded.arr_0to1.shape == (2+(1+3), 2+(4+2), 1)\n assert np.allclose(\n heatmaps_padded.arr_0to1[:, :, 0],\n np.float32([\n [0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0],\n [0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0],\n [0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0],\n [0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0],\n [0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0],\n [0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0]\n ])\n )\n\n\ndef test_HeatmapsOnImage_pad_to_aspect_ratio():\n heatmaps_arr = np.float32([\n [0.0, 0.0, 1.0],\n [0.0, 0.0, 1.0]\n ])\n heatmaps = ia.HeatmapsOnImage(heatmaps_arr, shape=(2, 2, 3))\n\n heatmaps_padded = heatmaps.pad_to_aspect_ratio(1.0)\n assert heatmaps_padded.arr_0to1.shape == (3, 3, 1)\n assert np.allclose(\n heatmaps_padded.arr_0to1[:, :, 0],\n np.float32([\n [0.0, 0.0, 1.0],\n [0.0, 0.0, 1.0],\n [0.0, 0.0, 0.0]\n ])\n )\n\n heatmaps_padded = heatmaps.pad_to_aspect_ratio(1.0, cval=0.5)\n assert heatmaps_padded.arr_0to1.shape == (3, 3, 1)\n assert np.allclose(\n heatmaps_padded.arr_0to1[:, :, 0],\n np.float32([\n [0.0, 0.0, 1.0],\n [0.0, 0.0, 1.0],\n [0.5, 0.5, 0.5]\n ])\n )\n\n heatmaps_padded = heatmaps.pad_to_aspect_ratio(1.0, mode=\"edge\")\n assert heatmaps_padded.arr_0to1.shape == (3, 3, 1)\n assert np.allclose(\n heatmaps_padded.arr_0to1[:, :, 0],\n np.float32([\n [0.0, 0.0, 1.0],\n [0.0, 0.0, 1.0],\n [0.0, 0.0, 1.0]\n ])\n )\n\n # test aspect ratio != 1.0\n heatmaps_padded = heatmaps.pad_to_aspect_ratio(2.0, cval=0.1)\n assert heatmaps_padded.arr_0to1.shape == (2, 4, 1)\n assert np.allclose(\n heatmaps_padded.arr_0to1[:, :, 0],\n np.float32([\n [0.0, 0.0, 1.0, 0.1],\n [0.0, 0.0, 1.0, 0.1]\n ])\n )\n\n heatmaps_padded = heatmaps.pad_to_aspect_ratio(0.25, cval=0.1)\n assert heatmaps_padded.arr_0to1.shape == (12, 3, 1)\n assert np.allclose(\n heatmaps_padded.arr_0to1[:, :, 0],\n np.float32([\n [0.1, 0.1, 0.1],\n [0.1, 0.1, 0.1],\n [0.1, 0.1, 0.1],\n [0.1, 0.1, 0.1],\n [0.1, 0.1, 0.1],\n [0.0, 0.0, 1.0],\n [0.0, 0.0, 1.0],\n [0.1, 0.1, 0.1],\n [0.1, 0.1, 0.1],\n [0.1, 0.1, 0.1],\n [0.1, 0.1, 0.1],\n [0.1, 0.1, 0.1]\n ])\n )\n\n\ndef test_HeatmapsOnImage_avg_pool():\n heatmaps_arr = np.float32([\n [0.0, 0.0, 0.5, 1.0],\n [0.0, 0.0, 0.5, 1.0],\n [0.0, 0.0, 0.5, 1.0],\n [0.0, 0.0, 0.5, 1.0]\n ])\n heatmaps = ia.HeatmapsOnImage(heatmaps_arr, shape=(4, 4, 3))\n\n heatmaps_pooled = heatmaps.avg_pool(2)\n assert heatmaps_pooled.arr_0to1.shape == (2, 2, 1)\n assert np.allclose(\n heatmaps_pooled.arr_0to1[:, :, 0],\n np.float32([[0.0, 0.75],\n [0.0, 0.75]])\n )\n\n\ndef test_HeatmapsOnImage_max_pool():\n heatmaps_arr = np.float32([\n [0.0, 0.0, 0.5, 1.0],\n [0.0, 0.0, 0.5, 1.0],\n [0.0, 0.0, 0.5, 1.0],\n [0.0, 0.0, 0.5, 1.0]\n ])\n heatmaps = ia.HeatmapsOnImage(heatmaps_arr, shape=(4, 4, 3))\n\n heatmaps_pooled = heatmaps.max_pool(2)\n assert heatmaps_pooled.arr_0to1.shape == (2, 2, 1)\n assert np.allclose(\n heatmaps_pooled.arr_0to1[:, :, 0],\n np.float32([[0.0, 1.0],\n [0.0, 1.0]])\n )\n\n\ndef test_HeatmapsOnImage_scale():\n heatmaps_arr = np.float32([\n [0.0, 1.0]\n ])\n heatmaps = ia.HeatmapsOnImage(heatmaps_arr, shape=(4, 4, 3))\n\n heatmaps_scaled = heatmaps.resize((4, 4), interpolation=\"nearest\")\n assert heatmaps_scaled.arr_0to1.shape == (4, 4, 1)\n assert heatmaps_scaled.arr_0to1.dtype.type == np.float32\n assert np.allclose(\n heatmaps_scaled.arr_0to1[:, :, 0],\n np.float32([\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.0, 1.0, 1.0]\n ])\n )\n\n heatmaps_arr = np.float32([\n [0.0, 1.0]\n ])\n heatmaps = ia.HeatmapsOnImage(heatmaps_arr, shape=(4, 4, 3))\n\n heatmaps_scaled = heatmaps.resize(2.0, interpolation=\"nearest\")\n assert heatmaps_scaled.arr_0to1.shape == (2, 4, 1)\n assert heatmaps_scaled.arr_0to1.dtype.type == np.float32\n assert np.allclose(\n heatmaps_scaled.arr_0to1[:, :, 0],\n np.float32([\n [0.0, 0.0, 1.0, 1.0],\n [0.0, 0.0, 1.0, 1.0]\n ])\n )\n\n\ndef test_HeatmapsOnImage_from_uint8():\n hm = ia.HeatmapsOnImage.from_uint8(\n np.uint8([\n [0, 128, 255],\n [255, 128, 0]\n ])[..., np.newaxis],\n (20, 30, 3)\n )\n assert hm.shape == (20, 30, 3)\n assert hm.arr_0to1.shape == (2, 3, 1)\n assert np.allclose(hm.arr_0to1[..., 0], np.float32([\n [0, 128/255, 1.0],\n [1.0, 128/255, 0]\n ]))\n\n # 2d uint8 arr\n hm = ia.HeatmapsOnImage.from_uint8(\n np.uint8([\n [0, 128, 255],\n [255, 128, 0]\n ]),\n (20, 30, 3)\n )\n assert hm.shape == (20, 30, 3)\n assert hm.arr_0to1.shape == (2, 3, 1)\n assert np.allclose(hm.arr_0to1[..., 0], np.float32([\n [0, 128/255, 1.0],\n [1.0, 128/255, 0]\n ]))\n\n # min_value, max_value\n hm = ia.HeatmapsOnImage.from_uint8(\n np.uint8([\n [0, 128, 255],\n [255, 128, 0]\n ])[..., np.newaxis],\n (20, 30, 3),\n min_value=-1.0,\n max_value=2.0\n )\n assert hm.shape == (20, 30, 3)\n assert hm.arr_0to1.shape == (2, 3, 1)\n assert np.allclose(hm.arr_0to1[..., 0], np.float32([\n [0, 128/255, 1.0],\n [1.0, 128/255, 0]\n ]))\n assert np.allclose(hm.min_value, -1.0)\n assert np.allclose(hm.max_value, 2.0)\n\n\ndef test_HeatmapsOnImage_change_normalization():\n # (0.0, 1.0) -> (0.0, 2.0)\n arr = np.float32([\n [0.0, 0.5, 1.0],\n [1.0, 0.5, 0.0]\n ])\n observed = ia.HeatmapsOnImage.change_normalization(arr, (0.0, 1.0), (0.0, 2.0))\n expected = np.float32([\n [0.0, 1.0, 2.0],\n [2.0, 1.0, 0.0]\n ])\n assert np.allclose(observed, expected)\n\n # (0.0, 1.0) -> (-1.0, 0.0)\n observed = ia.HeatmapsOnImage.change_normalization(arr, (0.0, 1.0), (-1.0, 0.0))\n expected = np.float32([\n [-1.0, -0.5, 0.0],\n [0.0, -0.5, -1.0]\n ])\n assert np.allclose(observed, expected)\n\n # (-1.0, 1.0) -> (1.0, 3.0)\n arr = np.float32([\n [-1.0, 0.0, 1.0],\n [1.0, 0.0, -1.0]\n ])\n observed = ia.HeatmapsOnImage.change_normalization(arr, (-1.0, 1.0), (1.0, 3.0))\n expected = np.float32([\n [1.0, 2.0, 3.0],\n [3.0, 2.0, 1.0]\n ])\n assert np.allclose(observed, expected)\n\n # (-1.0, 1.0) -> (1.0, 3.0)\n # value ranges given as HeatmapsOnImage\n arr = np.float32([\n [-1.0, 0.0, 1.0],\n [1.0, 0.0, -1.0]\n ])\n source = ia.HeatmapsOnImage(np.float32([[0.0]]), min_value=-1.0, max_value=1.0, shape=(1, 1, 3))\n target = ia.HeatmapsOnImage(np.float32([[1.0]]), min_value=1.0, max_value=3.0, shape=(1, 1, 3))\n observed = ia.HeatmapsOnImage.change_normalization(arr, source, target)\n expected = np.float32([\n [1.0, 2.0, 3.0],\n [3.0, 2.0, 1.0]\n ])\n assert np.allclose(observed, expected)\n\n\ndef test_SegmentationMapOnImage_bool():\n # Test for #189 (boolean mask inputs into SegmentationMapOnImage not working)\n arr = np.array([\n [0, 0, 0],\n [0, 1, 0],\n [0, 0, 0]\n ], dtype=bool)\n assert arr.dtype.type == np.bool_\n segmap = ia.SegmentationMapOnImage(arr, shape=(3, 3))\n observed = segmap.get_arr_int()\n assert observed.dtype.type == np.int32\n assert np.array_equal(arr, observed)\n\n arr = np.array([\n [0, 0, 0],\n [0, 1, 0],\n [0, 0, 0]\n ], dtype=np.bool)\n assert arr.dtype.type == np.bool_\n segmap = ia.SegmentationMapOnImage(arr, shape=(3, 3))\n observed = segmap.get_arr_int()\n assert observed.dtype.type == np.int32\n assert np.array_equal(arr, observed)\n\n\ndef test_SegmentationMapOnImage_get_arr_int():\n arr = np.int32([\n [0, 0, 1],\n [0, 2, 1],\n [1, 3, 1]\n ])\n segmap = ia.SegmentationMapOnImage(arr, shape=(3, 3), nb_classes=4)\n observed = segmap.get_arr_int()\n assert observed.dtype.type == np.int32\n assert np.array_equal(arr, observed)\n\n arr_c0 = np.float32([\n [0.1, 0.1, 0.1],\n [0.1, 0.9, 0.1],\n [0.0, 0.1, 0.0]\n ])\n arr_c1 = np.float32([\n [0.2, 1.0, 0.2],\n [0.2, 0.8, 0.2],\n [0.0, 0.0, 0.0]\n ])\n arr_c2 = np.float32([\n [0.0, 0.0, 0.0],\n [0.3, 0.7, 0.3],\n [0.1, 0.0, 0.0001]\n ])\n arr = np.concatenate([\n arr_c0[..., np.newaxis],\n arr_c1[..., np.newaxis],\n arr_c2[..., np.newaxis]\n ], axis=2)\n segmap = ia.SegmentationMapOnImage(arr, shape=(3, 3))\n observed = segmap.get_arr_int()\n expected = np.int32([\n [2, 2, 2],\n [3, 1, 3],\n [3, 1, 0]\n ])\n assert observed.dtype.type == np.int32\n assert np.array_equal(observed, expected)\n\n got_exception = False\n try:\n _ = segmap.get_arr_int(background_class_id=2)\n except Exception as exc:\n assert \"The background class id may only be changed if \" in str(exc)\n got_exception = True\n assert got_exception\n\n observed = segmap.get_arr_int(background_threshold=0.21)\n expected = np.int32([\n [0, 2, 0],\n [3, 1, 3],\n [0, 0, 0]\n ])\n assert observed.dtype.type == np.int32\n assert np.array_equal(observed, expected)\n\n\ndef test_SegmentationMapOnImage_draw():\n arr = np.int32([\n [0, 1, 1],\n [0, 1, 1],\n [0, 1, 1]\n ])\n segmap = ia.SegmentationMapOnImage(arr, shape=(3, 3), nb_classes=2)\n\n # simple example with 2 classes\n observed = segmap.draw()\n col0 = ia.SegmentationMapOnImage.DEFAULT_SEGMENT_COLORS[0]\n col1 = ia.SegmentationMapOnImage.DEFAULT_SEGMENT_COLORS[1]\n expected = np.uint8([\n [col0, col1, col1],\n [col0, col1, col1],\n [col0, col1, col1]\n ])\n assert np.array_equal(observed, expected)\n\n # same example, with resizing to 2x the size\n observed = segmap.draw(size=(6, 6))\n expected = ia.imresize_single_image(expected, (6, 6), interpolation=\"nearest\")\n assert np.array_equal(observed, expected)\n\n # custom choice of colors\n col0 = (10, 10, 10)\n col1 = (50, 51, 52)\n observed = segmap.draw(colors=[col0, col1])\n expected = np.uint8([\n [col0, col1, col1],\n [col0, col1, col1],\n [col0, col1, col1]\n ])\n assert np.array_equal(observed, expected)\n\n # background_threshold, background_class and foreground mask\n arr_c0 = np.float32([\n [0, 0, 0],\n [1.0, 0, 0],\n [0, 0, 0]\n ])\n arr_c1 = np.float32([\n [0, 1, 1],\n [0, 1, 1],\n [0.1, 1, 1]\n ])\n arr = np.concatenate([\n arr_c0[..., np.newaxis],\n arr_c1[..., np.newaxis]\n ], axis=2)\n segmap = ia.SegmentationMapOnImage(arr, shape=(3, 3))\n\n observed, observed_fg = segmap.draw(background_threshold=0.01, return_foreground_mask=True)\n col0 = ia.SegmentationMapOnImage.DEFAULT_SEGMENT_COLORS[0]\n col1 = ia.SegmentationMapOnImage.DEFAULT_SEGMENT_COLORS[1]\n col2 = ia.SegmentationMapOnImage.DEFAULT_SEGMENT_COLORS[2]\n expected = np.uint8([\n [col0, col2, col2],\n [col1, col2, col2],\n [col2, col2, col2]\n ])\n expected_fg = np.array([\n [False, True, True],\n [True, True, True],\n [True, True, True]\n ], dtype=np.bool)\n assert np.array_equal(observed, expected)\n assert np.array_equal(observed_fg, expected_fg)\n\n # background_threshold, background_class and foreground mask\n # here with higher threshold so that bottom left pixel switches to background\n observed, observed_fg = segmap.draw(background_threshold=0.11, return_foreground_mask=True)\n col0 = ia.SegmentationMapOnImage.DEFAULT_SEGMENT_COLORS[0]\n col1 = ia.SegmentationMapOnImage.DEFAULT_SEGMENT_COLORS[1]\n col2 = ia.SegmentationMapOnImage.DEFAULT_SEGMENT_COLORS[2]\n expected = np.uint8([\n [col0, col2, col2],\n [col1, col2, col2],\n [col0, col2, col2]\n ])\n expected_fg = np.array([\n [False, True, True],\n [True, True, True],\n [False, True, True]\n ], dtype=np.bool)\n assert np.array_equal(observed, expected)\n assert np.array_equal(observed_fg, expected_fg)\n\n\ndef test_SegmentationMapOnImage_draw_on_image():\n arr = np.int32([\n [0, 1, 1],\n [0, 1, 1],\n [0, 1, 1]\n ])\n segmap = ia.SegmentationMapOnImage(arr, shape=(3, 3), nb_classes=2)\n\n image = np.uint8([\n [0, 10, 20],\n [30, 40, 50],\n [60, 70, 80]\n ])\n image = np.tile(image[:, :, np.newaxis], (1, 1, 3))\n\n # only image visible\n observed = segmap.draw_on_image(image, alpha=0)\n assert np.array_equal(observed, image)\n\n # only segmap visible\n observed = segmap.draw_on_image(image, alpha=1.0, draw_background=True)\n col0 = ia.SegmentationMapOnImage.DEFAULT_SEGMENT_COLORS[0]\n col1 = ia.SegmentationMapOnImage.DEFAULT_SEGMENT_COLORS[1]\n expected = np.uint8([\n [col0, col1, col1],\n [col0, col1, col1],\n [col0, col1, col1]\n ])\n assert np.array_equal(observed, expected)\n\n # only segmap visible - in foreground\n observed = segmap.draw_on_image(image, alpha=1.0, draw_background=False)\n col1 = ia.SegmentationMapOnImage.DEFAULT_SEGMENT_COLORS[1]\n expected = np.uint8([\n [image[0, 0, :], col1, col1],\n [image[1, 0, :], col1, col1],\n [image[2, 0, :], col1, col1]\n ])\n assert np.array_equal(observed, expected)\n\n # overlay without background drawn\n a1 = 0.7\n a0 = 1.0 - a1\n observed = segmap.draw_on_image(image, alpha=a1, draw_background=False)\n col1 = np.uint8(ia.SegmentationMapOnImage.DEFAULT_SEGMENT_COLORS[1])\n expected = np.float32([\n [image[0, 0, :], a0*image[0, 1, :] + a1*col1, a0*image[0, 2, :] + a1*col1],\n [image[1, 0, :], a0*image[1, 1, :] + a1*col1, a0*image[1, 2, :] + a1*col1],\n [image[2, 0, :], a0*image[2, 1, :] + a1*col1, a0*image[2, 2, :] + a1*col1]\n ])\n d_max = np.max(np.abs(observed.astype(np.float32) - expected))\n assert observed.shape == expected.shape\n assert d_max <= 1.0 + 1e-4\n\n # overlay with background drawn\n a1 = 0.7\n a0 = 1.0 - a1\n observed = segmap.draw_on_image(image, alpha=a1, draw_background=True)\n col0 = ia.SegmentationMapOnImage.DEFAULT_SEGMENT_COLORS[0]\n col1 = ia.SegmentationMapOnImage.DEFAULT_SEGMENT_COLORS[1]\n expected = np.uint8([\n [col0, col1, col1],\n [col0, col1, col1],\n [col0, col1, col1]\n ])\n expected = a0 * image + a1 * expected\n d_max = np.max(np.abs(observed.astype(np.float32) - expected.astype(np.float32)))\n assert observed.shape == expected.shape\n assert d_max <= 1.0 + 1e-4\n\n # resizing of segmap to image\n arr = np.int32([\n [0, 1, 1]\n ])\n segmap = ia.SegmentationMapOnImage(arr, shape=(3, 3), nb_classes=2)\n\n image = np.uint8([\n [0, 10, 20],\n [30, 40, 50],\n [60, 70, 80]\n ])\n image = np.tile(image[:, :, np.newaxis], (1, 1, 3))\n\n a1 = 0.7\n a0 = 1.0 - a1\n observed = segmap.draw_on_image(image, alpha=a1, draw_background=True, resize=\"segmentation_map\")\n expected = np.uint8([\n [col0, col1, col1],\n [col0, col1, col1],\n [col0, col1, col1]\n ])\n expected = a0 * image + a1 * expected\n d_max = np.max(np.abs(observed.astype(np.float32) - expected.astype(np.float32)))\n assert observed.shape == expected.shape\n assert d_max <= 1.0 + 1e-4\n\n # resizing of image to segmap\n arr = np.int32([\n [0, 1, 1],\n [0, 1, 1],\n [0, 1, 1]\n ])\n segmap = ia.SegmentationMapOnImage(arr, shape=(1, 3), nb_classes=2)\n\n image = np.uint8([\n [0, 10, 20]\n ])\n image = np.tile(image[:, :, np.newaxis], (1, 1, 3))\n image_rs = ia.imresize_single_image(image, arr.shape[0:2], interpolation=\"cubic\")\n\n a1 = 0.7\n a0 = 1.0 - a1\n observed = segmap.draw_on_image(image, alpha=a1, draw_background=True, resize=\"image\")\n expected = np.uint8([\n [col0, col1, col1],\n [col0, col1, col1],\n [col0, col1, col1]\n ])\n expected = a0 * image_rs + a1 * expected\n d_max = np.max(np.abs(observed.astype(np.float32) - expected.astype(np.float32)))\n assert observed.shape == expected.shape\n assert d_max <= 1.0 + 1e-4\n\n\ndef test_SegmentationMapOnImage_pad():\n arr = np.int32([\n [0, 1, 1],\n [0, 2, 1],\n [0, 1, 3]\n ])\n segmap = ia.SegmentationMapOnImage(arr, shape=(3, 3), nb_classes=4)\n\n segmap_padded = segmap.pad(top=1, right=2, bottom=3, left=4)\n observed = segmap_padded.arr\n expected = np.pad(segmap.arr, ((1, 3), (4, 2), (0, 0)), mode=\"constant\", constant_values=0)\n assert np.allclose(observed, expected)\n\n segmap_padded = segmap.pad(top=1, right=2, bottom=3, left=4, cval=1.0)\n observed = segmap_padded.arr\n expected = np.pad(segmap.arr, ((1, 3), (4, 2), (0, 0)), mode=\"constant\", constant_values=1.0)\n assert np.allclose(observed, expected)\n\n segmap_padded = segmap.pad(top=1, right=2, bottom=3, left=4, mode=\"edge\")\n observed = segmap_padded.arr\n expected = np.pad(segmap.arr, ((1, 3), (4, 2), (0, 0)), mode=\"edge\")\n assert np.allclose(observed, expected)\n\n\ndef test_SegmentationMapOnImage_pad_to_aspect_ratio():\n arr = np.int32([\n [0, 1, 1],\n [0, 2, 1]\n ])\n segmap = ia.SegmentationMapOnImage(arr, shape=(2, 3), nb_classes=3)\n\n segmap_padded = segmap.pad_to_aspect_ratio(1.0)\n observed = segmap_padded.arr\n expected = np.pad(segmap.arr, ((0, 1), (0, 0), (0, 0)), mode=\"constant\", constant_values=0)\n assert np.allclose(observed, expected)\n\n segmap_padded = segmap.pad_to_aspect_ratio(1.0, cval=1.0)\n observed = segmap_padded.arr\n expected = np.pad(segmap.arr, ((0, 1), (0, 0), (0, 0)), mode=\"constant\", constant_values=1.0)\n assert np.allclose(observed, expected)\n\n segmap_padded = segmap.pad_to_aspect_ratio(1.0, mode=\"edge\")\n observed = segmap_padded.arr\n expected = np.pad(segmap.arr, ((0, 1), (0, 0), (0, 0)), mode=\"edge\")\n assert np.allclose(observed, expected)\n\n segmap_padded = segmap.pad_to_aspect_ratio(0.5)\n observed = segmap_padded.arr\n expected = np.pad(segmap.arr, ((2, 2), (0, 0), (0, 0)), mode=\"constant\", constant_values=0)\n assert np.allclose(observed, expected)\n\n segmap_padded, pad_amounts = segmap.pad_to_aspect_ratio(0.5, return_pad_amounts=True)\n observed = segmap_padded.arr\n expected = np.pad(segmap.arr, ((2, 2), (0, 0), (0, 0)), mode=\"constant\", constant_values=0)\n assert np.allclose(observed, expected)\n assert pad_amounts == (2, 0, 2, 0)\n\n\ndef test_SegmentationMapOnImage_scale():\n arr = np.int32([\n [0, 1],\n [0, 2]\n ])\n segmap = ia.SegmentationMapOnImage(arr, shape=(2, 2), nb_classes=3)\n\n segmap_scaled = segmap.resize((4, 4))\n observed = segmap_scaled.arr\n expected = np.clip(ia.imresize_single_image(segmap.arr, (4, 4), interpolation=\"cubic\"), 0, 1.0)\n assert np.allclose(observed, expected)\n assert np.array_equal(segmap_scaled.get_arr_int(), np.int32([\n [0, 0, 1, 1],\n [0, 0, 1, 1],\n [0, 0, 2, 2],\n [0, 0, 2, 2],\n ]))\n\n segmap_scaled = segmap.resize((4, 4), interpolation=\"nearest\")\n observed = segmap_scaled.arr\n expected = ia.imresize_single_image(segmap.arr, (4, 4), interpolation=\"nearest\")\n assert np.allclose(observed, expected)\n assert np.array_equal(segmap_scaled.get_arr_int(), np.int32([\n [0, 0, 1, 1],\n [0, 0, 1, 1],\n [0, 0, 2, 2],\n [0, 0, 2, 2],\n ]))\n\n segmap_scaled = segmap.resize(2.0)\n observed = segmap_scaled.arr\n expected = np.clip(ia.imresize_single_image(segmap.arr, 2.0, interpolation=\"cubic\"), 0, 1.0)\n assert np.allclose(observed, expected)\n assert np.array_equal(segmap_scaled.get_arr_int(), np.int32([\n [0, 0, 1, 1],\n [0, 0, 1, 1],\n [0, 0, 2, 2],\n [0, 0, 2, 2],\n ]))\n\n\ndef test_SegmentationMapOnImage_to_heatmaps():\n arr = np.int32([\n [0, 1],\n [0, 2]\n ])\n segmap = ia.SegmentationMapOnImage(arr, shape=(2, 2), nb_classes=3)\n heatmaps = segmap.to_heatmaps()\n expected_c0 = np.float32([\n [1.0, 0.0],\n [1.0, 0.0]\n ])\n expected_c1 = np.float32([\n [0.0, 1.0],\n [0.0, 0.0]\n ])\n expected_c2 = np.float32([\n [0.0, 0.0],\n [0.0, 1.0]\n ])\n expected = np.concatenate([\n expected_c0[..., np.newaxis],\n expected_c1[..., np.newaxis],\n expected_c2[..., np.newaxis]\n ], axis=2)\n assert np.allclose(heatmaps.arr_0to1, expected)\n\n # only_nonempty when all are nonempty\n heatmaps, class_indices = segmap.to_heatmaps(only_nonempty=True)\n expected_c0 = np.float32([\n [1.0, 0.0],\n [1.0, 0.0]\n ])\n expected_c1 = np.float32([\n [0.0, 1.0],\n [0.0, 0.0]\n ])\n expected_c2 = np.float32([\n [0.0, 0.0],\n [0.0, 1.0]\n ])\n expected = np.concatenate([\n expected_c0[..., np.newaxis],\n expected_c1[..., np.newaxis],\n expected_c2[..., np.newaxis]\n ], axis=2)\n assert np.allclose(heatmaps.arr_0to1, expected)\n assert len(class_indices) == 3\n assert [idx in class_indices for idx in [0, 1, 2]]\n\n # only_nonempty when one is empty and two are nonempty\n arr = np.int32([\n [0, 2],\n [0, 2]\n ])\n segmap = ia.SegmentationMapOnImage(arr, shape=(2, 2), nb_classes=3)\n heatmaps, class_indices = segmap.to_heatmaps(only_nonempty=True)\n expected_c0 = np.float32([\n [1.0, 0.0],\n [1.0, 0.0]\n ])\n expected_c2 = np.float32([\n [0.0, 1.0],\n [0.0, 1.0]\n ])\n expected = np.concatenate([\n expected_c0[..., np.newaxis],\n expected_c2[..., np.newaxis]\n ], axis=2)\n assert np.allclose(heatmaps.arr_0to1, expected)\n assert len(class_indices) == 2\n assert [idx in class_indices for idx in [0, 2]]\n\n # only_nonempty when all are empty\n arr_c0 = np.float32([\n [0.0, 0.0],\n [0.0, 0.0]\n ])\n arr = arr_c0[..., np.newaxis]\n segmap = ia.SegmentationMapOnImage(arr, shape=(2, 2), nb_classes=3)\n heatmaps, class_indices = segmap.to_heatmaps(only_nonempty=True)\n assert heatmaps is None\n assert len(class_indices) == 0\n\n # only_nonempty when all are empty and not_none_if_no_nonempty is True\n arr_c0 = np.float32([\n [0.0, 0.0],\n [0.0, 0.0]\n ])\n arr = arr_c0[..., np.newaxis]\n segmap = ia.SegmentationMapOnImage(arr, shape=(2, 2), nb_classes=3)\n heatmaps, class_indices = segmap.to_heatmaps(only_nonempty=True, not_none_if_no_nonempty=True)\n assert np.allclose(heatmaps.arr_0to1, np.zeros((2, 2), dtype=np.float32))\n assert len(class_indices) == 1\n assert [idx in class_indices for idx in [0]]\n\n\ndef test_SegmentationMapOnImage_from_heatmaps():\n arr_c0 = np.float32([\n [1.0, 0.0],\n [1.0, 0.0]\n ])\n arr_c1 = np.float32([\n [0.0, 1.0],\n [0.0, 1.0]\n ])\n arr = np.concatenate([arr_c0[..., np.newaxis], arr_c1[..., np.newaxis]], axis=2)\n heatmaps = ia.HeatmapsOnImage.from_0to1(arr, shape=(2, 2))\n\n segmap = ia.SegmentationMapOnImage.from_heatmaps(heatmaps)\n assert np.allclose(segmap.arr, arr)\n\n # with class_indices\n arr_c0 = np.float32([\n [1.0, 0.0],\n [1.0, 0.0]\n ])\n arr_c2 = np.float32([\n [0.0, 1.0],\n [0.0, 1.0]\n ])\n arr = np.concatenate([arr_c0[..., np.newaxis], arr_c2[..., np.newaxis]], axis=2)\n heatmaps = ia.HeatmapsOnImage.from_0to1(arr, shape=(2, 2))\n\n segmap = ia.SegmentationMapOnImage.from_heatmaps(heatmaps, class_indices=[0, 2], nb_classes=4)\n expected_c0 = np.copy(arr_c0)\n expected_c1 = np.zeros(arr_c0.shape)\n expected_c2 = np.copy(arr_c2)\n expected_c3 = np.zeros(arr_c0.shape)\n expected = np.concatenate([\n expected_c0[..., np.newaxis],\n expected_c1[..., np.newaxis],\n expected_c2[..., np.newaxis],\n expected_c3[..., np.newaxis]\n ], axis=2)\n assert np.allclose(segmap.arr, expected)\n\n\ndef test_SegmentationMapOnImage_copy():\n arr_c0 = np.float32([\n [1.0, 0.0],\n [1.0, 0.0]\n ])\n arr_c1 = np.float32([\n [0.0, 1.0],\n [0.0, 1.0]\n ])\n arr = np.concatenate([arr_c0[..., np.newaxis], arr_c1[..., np.newaxis]], axis=2)\n segmap = ia.SegmentationMapOnImage(arr, shape=(2, 2))\n observed = segmap.copy()\n assert np.allclose(observed.arr, segmap.arr)\n assert observed.shape == (2, 2)\n assert observed.nb_classes == segmap.nb_classes\n assert observed.input_was == segmap.input_was\n\n arr = np.int32([\n [0, 1],\n [2, 3]\n ])\n segmap = ia.SegmentationMapOnImage(arr, shape=(2, 2), nb_classes=10)\n observed = segmap.copy()\n assert np.array_equal(observed.get_arr_int(), arr)\n assert observed.shape == (2, 2)\n assert observed.nb_classes == 10\n assert observed.input_was == segmap.input_was\n\n\ndef test_SegmentationMapOnImage_deepcopy():\n arr_c0 = np.float32([\n [1.0, 0.0],\n [1.0, 0.0]\n ])\n arr_c1 = np.float32([\n [0.0, 1.0],\n [0.0, 1.0]\n ])\n arr = np.concatenate([arr_c0[..., np.newaxis], arr_c1[..., np.newaxis]], axis=2)\n segmap = ia.SegmentationMapOnImage(arr, shape=(2, 2))\n observed = segmap.deepcopy()\n assert np.allclose(observed.arr, segmap.arr)\n assert observed.shape == (2, 2)\n assert observed.nb_classes == segmap.nb_classes\n assert observed.input_was == segmap.input_was\n segmap.arr[0, 0, 0] = 0.0\n assert not np.allclose(observed.arr, segmap.arr)\n\n arr = np.int32([\n [0, 1],\n [2, 3]\n ])\n segmap = ia.SegmentationMapOnImage(arr, shape=(2, 2), nb_classes=10)\n observed = segmap.deepcopy()\n assert np.array_equal(observed.get_arr_int(), segmap.get_arr_int())\n assert observed.shape == (2, 2)\n assert observed.nb_classes == 10\n assert observed.input_was == segmap.input_was\n segmap.arr[0, 0, 0] = 0.0\n segmap.arr[0, 0, 1] = 1.0\n assert not np.array_equal(observed.get_arr_int(), segmap.get_arr_int())\n\n\ndef test_Polygon___init__():\n # exterior is list of Keypoint or\n poly = ia.Polygon([ia.Keypoint(x=0, y=0), ia.Keypoint(x=1, y=1), ia.Keypoint(x=0.5, y=2.5)])\n assert poly.exterior.dtype.type == np.float32\n assert np.allclose(\n poly.exterior,\n np.float32([\n [0.0, 0.0],\n [1.0, 1.0],\n [0.5, 2.5]\n ])\n )\n\n # exterior is list of tuple of floats\n poly = ia.Polygon([(0.0, 0.0), (1.0, 1.0), (0.5, 2.5)])\n assert poly.exterior.dtype.type == np.float32\n assert np.allclose(\n poly.exterior,\n np.float32([\n [0.0, 0.0],\n [1.0, 1.0],\n [0.5, 2.5]\n ])\n )\n\n # exterior is list of tuple of integer\n poly = ia.Polygon([(0, 0), (1, 1), (1, 3)])\n assert poly.exterior.dtype.type == np.float32\n assert np.allclose(\n poly.exterior,\n np.float32([\n [0.0, 0.0],\n [1.0, 1.0],\n [1.0, 3.0]\n ])\n )\n\n # exterior is (N,2) ndarray\n poly = ia.Polygon(\n np.float32([\n [0.0, 0.0],\n [1.0, 1.0],\n [0.5, 2.5]\n ])\n )\n assert poly.exterior.dtype.type == np.float32\n assert np.allclose(\n poly.exterior,\n np.float32([\n [0.0, 0.0],\n [1.0, 1.0],\n [0.5, 2.5]\n ])\n )\n\n # exterior is (N,2) ndarray in float64\n poly = ia.Polygon(\n np.float64([\n [0.0, 0.0],\n [1.0, 1.0],\n [0.5, 2.5]\n ])\n )\n assert poly.exterior.dtype.type == np.float32\n assert np.allclose(\n poly.exterior,\n np.float32([\n [0.0, 0.0],\n [1.0, 1.0],\n [0.5, 2.5]\n ])\n )\n\n # arrays without points\n poly = ia.Polygon([])\n assert poly.exterior.dtype.type == np.float32\n assert poly.exterior.shape == (0, 2)\n\n poly = ia.Polygon(np.zeros((0, 2), dtype=np.float32))\n assert poly.exterior.dtype.type == np.float32\n assert poly.exterior.shape == (0, 2)\n\n # bad array shape\n got_exception = False\n try:\n _ = ia.Polygon(np.zeros((8,), dtype=np.float32))\n except:\n got_exception = True\n assert got_exception\n\n # label\n poly = ia.Polygon([(0, 0)])\n assert poly.label is None\n poly = ia.Polygon([(0, 0)], label=\"test\")\n assert poly.label == \"test\"\n\n\ndef test_Polygon_xx():\n poly = ia.Polygon([(0, 0), (1, 0), (1.5, 0), (4.1, 1), (2.9, 2.0)])\n assert poly.xx.dtype.type == np.float32\n assert np.allclose(poly.xx, np.float32([0.0, 1.0, 1.5, 4.1, 2.9]))\n\n poly = ia.Polygon([])\n assert poly.xx.dtype.type == np.float32\n assert poly.xx.shape == (0,)\n\n\ndef test_Polygon_yy():\n poly = ia.Polygon([(0, 0), (0, 1), (0, 1.5), (1, 4.1), (2.0, 2.9)])\n assert poly.yy.dtype.type == np.float32\n assert np.allclose(poly.yy, np.float32([0.0, 1.0, 1.5, 4.1, 2.9]))\n\n poly = ia.Polygon([])\n assert poly.yy.dtype.type == np.float32\n assert poly.yy.shape == (0,)\n\n\ndef test_Polygon_xx_int():\n poly = ia.Polygon([(0, 0), (1, 0), (1.5, 0), (4.1, 1), (2.9, 2.0)])\n assert poly.xx_int.dtype.type == np.int32\n assert np.allclose(poly.xx_int, np.int32([0, 1, 2, 4, 3]))\n\n poly = ia.Polygon([])\n assert poly.xx_int.dtype.type == np.int32\n assert poly.xx_int.shape == (0,)\n\n\ndef test_Polygon_yy_int():\n poly = ia.Polygon([(0, 0), (0, 1), (0, 1.5), (1, 4.1), (2.0, 2.9)])\n assert poly.yy_int.dtype.type == np.int32\n assert np.allclose(poly.yy_int, np.int32([0, 1, 2, 4, 3]))\n\n poly = ia.Polygon([])\n assert poly.yy_int.dtype.type == np.int32\n assert poly.yy_int.shape == (0,)\n\n\ndef test_Polygon_is_valid():\n poly = ia.Polygon([(0, 0), (1, 0), (1, 1), (0, 1)])\n assert poly.is_valid\n\n poly = ia.Polygon([])\n assert not poly.is_valid\n\n poly = ia.Polygon([(0, 0)])\n assert not poly.is_valid\n\n poly = ia.Polygon([(0, 0), (1, 0)])\n assert not poly.is_valid\n\n poly = ia.Polygon([(0, 0), (1, 0), (-1, 0.5), (1, 1), (0, 1)])\n assert not poly.is_valid\n\n poly = ia.Polygon([(0, 0), (1, 0), (1, 0), (1, 1), (0, 1)])\n assert poly.is_valid\n\n\ndef test_Polygon_area():\n poly = ia.Polygon([(0, 0), (1, 0), (1, 1), (0, 1)])\n assert poly.area == 1\n assert 1.0 - 1e-8 < poly.area < 1.0 + 1e-8\n\n poly = ia.Polygon([(0, 0), (2, 0), (2, 1), (0, 1)])\n assert poly.area == 2\n assert 2.0 - 1e-8 < poly.area < 2.0 + 1e-8\n\n poly = ia.Polygon([(0, 0), (1, 1), (0, 1)])\n assert 1/2 - 1e-8 < poly.area < 1/2 + 1e-8\n\n poly = ia.Polygon([(0, 0), (1, 1)])\n got_exception = False\n try:\n _ = poly.area\n except Exception as exc:\n assert \"Cannot compute the polygon's area because\" in str(exc)\n got_exception = True\n assert got_exception\n\n\ndef test_Polygon_project():\n poly = ia.Polygon([(0, 0), (1, 0), (1, 1), (0, 1)])\n poly_proj = poly.project((1, 1), (1, 1))\n assert poly_proj.exterior.dtype.type == np.float32\n assert poly_proj.exterior.shape == (4, 2)\n assert np.allclose(\n poly_proj.exterior,\n np.float32([\n [0, 0],\n [1, 0],\n [1, 1],\n [0, 1]\n ])\n )\n\n poly = ia.Polygon([(0, 0), (1, 0), (1, 1), (0, 1)])\n poly_proj = poly.project((1, 1), (2, 2))\n assert poly_proj.exterior.dtype.type == np.float32\n assert poly_proj.exterior.shape == (4, 2)\n assert np.allclose(\n poly_proj.exterior,\n np.float32([\n [0, 0],\n [2, 0],\n [2, 2],\n [0, 2]\n ])\n )\n\n poly = ia.Polygon([(0, 0), (1, 0), (1, 1), (0, 1)])\n poly_proj = poly.project((1, 1), (2, 1))\n assert poly_proj.exterior.dtype.type == np.float32\n assert poly_proj.exterior.shape == (4, 2)\n assert np.allclose(\n poly_proj.exterior,\n np.float32([\n [0, 0],\n [1, 0],\n [1, 2],\n [0, 2]\n ])\n )\n\n poly = ia.Polygon([])\n poly_proj = poly.project((1, 1), (2, 2))\n assert poly_proj.exterior.dtype.type == np.float32\n assert poly_proj.exterior.shape == (0, 2)\n\n\ndef test_Polygon_find_closest_point_idx():\n poly = ia.Polygon([(0, 0), (1, 0), (1, 1), (0, 1)])\n closest_idx = poly.find_closest_point_index(x=0, y=0)\n assert closest_idx == 0\n closest_idx = poly.find_closest_point_index(x=1, y=0)\n assert closest_idx == 1\n closest_idx = poly.find_closest_point_index(x=1.0001, y=-0.001)\n assert closest_idx == 1\n closest_idx = poly.find_closest_point_index(x=0.2, y=0.2)\n assert closest_idx == 0\n\n closest_idx, distance = poly.find_closest_point_index(x=0, y=0, return_distance=True)\n assert closest_idx == 0\n assert np.allclose(distance, 0.0)\n closest_idx, distance = poly.find_closest_point_index(x=0.1, y=0.15, return_distance=True)\n assert closest_idx == 0\n assert np.allclose(distance, np.sqrt((0.1**2) + (0.15**2)))\n closest_idx, distance = poly.find_closest_point_index(x=0.9, y=0.15, return_distance=True)\n assert closest_idx == 1\n assert np.allclose(distance, np.sqrt(((1.0-0.9)**2) + (0.15**2)))\n\n\ndef test_Polygon__compute_inside_image_point_mask():\n poly = ia.Polygon([(0, 0), (0.999, 0), (0.999, 0.999), (0, 0.999)])\n mask = poly._compute_inside_image_point_mask((1, 1, 3))\n assert np.array_equal(mask, np.array([True, True, True, True], dtype=bool))\n\n poly = ia.Polygon([(0, 0), (1, 0), (1, 1), (0, 1)])\n mask = poly._compute_inside_image_point_mask((1, 1, 3))\n assert np.array_equal(mask, np.array([True, False, False, False], dtype=bool))\n\n poly = ia.Polygon([(0, 0), (1, 0), (1, 1), (0, 1)])\n mask = poly._compute_inside_image_point_mask((1, 1))\n assert np.array_equal(mask, np.array([True, False, False, False], dtype=bool))\n\n poly = ia.Polygon([(0, 0), (1, 0), (1, 1), (0, 1)])\n mask = poly._compute_inside_image_point_mask(np.zeros((1, 1, 3), dtype=np.uint8))\n assert np.array_equal(mask, np.array([True, False, False, False], dtype=bool))\n\n\ndef test_Polygon_is_fully_within_image():\n poly = ia.Polygon([(0, 0), (0.999, 0), (0.999, 0.999), (0, 0.999)])\n assert poly.is_fully_within_image((1, 1, 3))\n\n poly = ia.Polygon([(0, 0), (0.999, 0), (0.999, 0.999), (0, 0.999)])\n assert poly.is_fully_within_image((1, 1))\n\n poly = ia.Polygon([(0, 0), (0.999, 0), (0.999, 0.999), (0, 0.999)])\n assert poly.is_fully_within_image(np.zeros((1, 1, 3), dtype=np.uint8))\n\n poly = ia.Polygon([(0, 0), (1, 0), (1, 1), (0, 1)])\n assert not poly.is_fully_within_image((1, 1, 3))\n\n poly = ia.Polygon([(0, 0), (1, 0), (1, 1), (0, 1)])\n assert not poly.is_fully_within_image((1, 1))\n\n poly = ia.Polygon([(0, 0), (1, 0), (1, 1), (0, 1)])\n assert not poly.is_fully_within_image(np.zeros((1, 1, 3), dtype=np.uint8))\n\n poly = ia.Polygon([(100, 100), (101, 100), (101, 101), (100, 101)])\n assert not poly.is_fully_within_image((1, 1, 3))\n\n\ndef test_Polygon_is_partly_within_image():\n poly = ia.Polygon([(0, 0), (0.999, 0), (0.999, 0.999), (0, 0.999)])\n assert poly.is_partly_within_image((1, 1, 3))\n\n poly = ia.Polygon([(0, 0), (0.999, 0), (0.999, 0.999), (0, 0.999)])\n assert poly.is_partly_within_image((1, 1))\n\n poly = ia.Polygon([(0, 0), (0.999, 0), (0.999, 0.999), (0, 0.999)])\n assert poly.is_partly_within_image(np.zeros((1, 1, 3), dtype=np.uint8))\n\n poly = ia.Polygon([(0, 0), (1, 0), (1, 1), (0, 1)])\n assert poly.is_partly_within_image((1, 1, 3))\n\n poly = ia.Polygon([(0, 0), (1, 0), (1, 1), (0, 1)])\n assert poly.is_partly_within_image((1, 1))\n\n poly = ia.Polygon([(0, 0), (1, 0), (1, 1), (0, 1)])\n assert poly.is_partly_within_image(np.zeros((1, 1, 3), dtype=np.uint8))\n\n poly = ia.Polygon([(100, 100), (101, 100), (101, 101), (100, 101)])\n assert not poly.is_partly_within_image((1, 1, 3))\n\n poly = ia.Polygon([(100, 100), (101, 100), (101, 101), (100, 101)])\n assert not poly.is_partly_within_image((1, 1))\n\n poly = ia.Polygon([(100, 100), (101, 100), (101, 101), (100, 101)])\n assert not poly.is_partly_within_image(np.zeros((1, 1, 3), dtype=np.uint8))\n\n\ndef test_Polygon_is_out_of_image():\n for shape in [(1, 1, 3), (1, 1), np.zeros((1, 1, 3), dtype=np.uint8)]:\n poly = ia.Polygon([(0, 0), (0.999, 0), (0.999, 0.999), (0, 0.999)])\n assert not poly.is_out_of_image(shape, partly=False, fully=False)\n assert not poly.is_out_of_image(shape, partly=True, fully=False)\n assert not poly.is_out_of_image(shape, partly=False, fully=True)\n assert not poly.is_out_of_image(shape, partly=True, fully=True)\n\n poly = ia.Polygon([(0, 0), (1, 0), (1, 1), (0, 1)])\n shape = np.zeros((1, 1, 3), dtype=np.uint8)\n assert not poly.is_out_of_image(shape, partly=False, fully=False)\n assert poly.is_out_of_image(shape, partly=True, fully=False)\n assert not poly.is_out_of_image(shape, partly=False, fully=True)\n assert poly.is_out_of_image(shape, partly=True, fully=True)\n\n poly = ia.Polygon([(100, 100), (101, 100), (101, 101), (100, 101)])\n shape = (1, 1, 3)\n assert not poly.is_out_of_image(shape, partly=False, fully=False)\n assert not poly.is_out_of_image(shape, partly=True, fully=False)\n assert poly.is_out_of_image(shape, partly=False, fully=True)\n assert poly.is_out_of_image(shape, partly=True, fully=True)\n\n poly = ia.Polygon([])\n got_exception = False\n try:\n poly.is_out_of_image((1, 1, 3))\n except Exception as exc:\n assert \"Cannot determine whether the polygon is inside the image\" in str(exc)\n got_exception = True\n assert got_exception\n\n\ndef test_Polygon_cut_out_of_image():\n with warnings.catch_warnings(record=True) as caught_warnings:\n # Cause all warnings to always be triggered.\n warnings.simplefilter(\"always\")\n # Trigger a warning.\n _test_Polygon_cut_clip(lambda poly, image: poly.cut_out_of_image(image))\n # Verify\n # get multiple warnings here, one for each function call\n assert all([\n \"Use Polygon.clip_out_of_image() instead\" in str(msg.message)\n for msg in caught_warnings])\n\n\ndef test_Polygon_clip_out_of_image():\n _test_Polygon_cut_clip(lambda poly, image: poly.clip_out_of_image(image))\n\n\ndef _test_Polygon_cut_clip(func):\n # poly inside image\n poly = ia.Polygon([(0, 0), (1, 0), (1, 1), (0, 1)], label=None)\n image = np.zeros((1, 1, 3), dtype=np.uint8)\n multipoly_clipped = func(poly, image)\n assert isinstance(multipoly_clipped, ia.MultiPolygon)\n assert len(multipoly_clipped.geoms) == 1\n assert multipoly_clipped.geoms[0].exterior_almost_equals(poly.exterior)\n assert multipoly_clipped.geoms[0].label is None\n\n # square poly shifted by x=0.5, y=0.5 => half out of image\n poly = ia.Polygon([(0.5, 0.5), (1.5, 0.5), (1.5, 1.5), (0.5, 1.5)], label=\"test\")\n image = np.zeros((1, 1, 3), dtype=np.uint8)\n multipoly_clipped = func(poly, image)\n assert isinstance(multipoly_clipped, ia.MultiPolygon)\n assert len(multipoly_clipped.geoms) == 1\n assert multipoly_clipped.geoms[0].exterior_almost_equals(np.float32([\n [0.5, 0.5],\n [1.0, 0.5],\n [1.0, 1.0],\n [0.5, 1.0]\n ]))\n assert multipoly_clipped.geoms[0].label == \"test\"\n\n # non-square poly, with one rectangle on the left side of the image and one on the right side,\n # both sides are connected by a thin strip below the image\n # after clipping it should become two rectangles\n poly = ia.Polygon([(-0.1, 0.0), (0.4, 0.0), (0.4, 1.1), (0.6, 1.1), (0.6, 0.0), (1.1, 0.0),\n (1.1, 1.2), (-0.1, 1.2)],\n label=\"test\")\n image = np.zeros((1, 1, 3), dtype=np.uint8)\n multipoly_clipped = func(poly, image)\n assert isinstance(multipoly_clipped, ia.MultiPolygon)\n assert len(multipoly_clipped.geoms) == 2\n assert multipoly_clipped.geoms[0].exterior_almost_equals(np.float32([\n [0.0, 0.0],\n [0.4, 0.0],\n [0.4, 1.0],\n [0.0, 1.0]\n ]))\n assert multipoly_clipped.geoms[0].label == \"test\"\n assert multipoly_clipped.geoms[1].exterior_almost_equals(np.float32([\n [0.6, 0.0],\n [1.0, 0.0],\n [1.0, 1.0],\n [0.6, 1.0]\n ]))\n assert multipoly_clipped.geoms[0].label == \"test\"\n\n # poly outside of image\n poly = ia.Polygon([(10.0, 10.0)])\n multipoly_clipped = func(poly, (5, 5, 3))\n assert isinstance(multipoly_clipped, ia.MultiPolygon)\n assert len(multipoly_clipped.geoms) == 0\n\n\ndef test_Polygon_shift():\n poly = ia.Polygon([(0, 0), (1, 0), (1, 1), (0, 1)], label=\"test\")\n\n # make sure that shift does not change poly inplace\n poly_shifted = poly.shift(top=1)\n assert np.allclose(poly.exterior, np.float32([\n [0, 0],\n [1, 0],\n [1, 1],\n [0, 1]\n ]))\n assert np.allclose(poly_shifted.exterior, np.float32([\n [0, 1],\n [1, 1],\n [1, 2],\n [0, 2]\n ]))\n\n for v in [1, 0, -1, 0.5]:\n # top/bottom\n poly_shifted = poly.shift(top=v)\n assert np.allclose(poly_shifted.exterior, np.float32([\n [0, 0 + v],\n [1, 0 + v],\n [1, 1 + v],\n [0, 1 + v]\n ]))\n assert poly_shifted.label == \"test\"\n\n poly_shifted = poly.shift(bottom=v)\n assert np.allclose(poly_shifted.exterior, np.float32([\n [0, 0 - v],\n [1, 0 - v],\n [1, 1 - v],\n [0, 1 - v]\n ]))\n assert poly_shifted.label == \"test\"\n\n poly_shifted = poly.shift(top=v, bottom=-v)\n assert np.allclose(poly_shifted.exterior, np.float32([\n [0, 0 + 2*v],\n [1, 0 + 2*v],\n [1, 1 + 2*v],\n [0, 1 + 2*v]\n ]))\n assert poly_shifted.label == \"test\"\n\n # left/right\n poly_shifted = poly.shift(left=v)\n assert np.allclose(poly_shifted.exterior, np.float32([\n [0 + v, 0],\n [1 + v, 0],\n [1 + v, 1],\n [0 + v, 1]\n ]))\n assert poly_shifted.label == \"test\"\n\n poly_shifted = poly.shift(right=v)\n assert np.allclose(poly_shifted.exterior, np.float32([\n [0 - v, 0],\n [1 - v, 0],\n [1 - v, 1],\n [0 - v, 1]\n ]))\n assert poly_shifted.label == \"test\"\n\n poly_shifted = poly.shift(left=v, right=-v)\n assert np.allclose(poly_shifted.exterior, np.float32([\n [0 + 2 * v, 0],\n [1 + 2 * v, 0],\n [1 + 2 * v, 1],\n [0 + 2 * v, 1]\n ]))\n assert poly_shifted.label == \"test\"\n\n\ndef test_Polygon_draw_on_image():\n image = np.tile(np.arange(100).reshape(10, 10, 1), (1, 1, 3)).astype(np.uint8)\n\n # simple drawing of square\n poly = ia.Polygon([(2, 2), (8, 2), (8, 8), (2, 8)])\n image_poly = poly.draw_on_image(image,\n color=[32, 128, 32], color_perimeter=[0, 255, 0],\n alpha=1.0, alpha_perimeter=1.0,\n raise_if_out_of_image=False)\n assert image_poly.dtype.type == np.uint8\n assert image_poly.shape == (10, 10, 3)\n assert np.sum(image) == 3 * np.sum(np.arange(100)) # draw did not change original image (copy=True)\n for c_idx, value in enumerate([0, 255, 0]):\n assert np.all(image_poly[2:9, 2:3, c_idx] == np.zeros((7, 1), dtype=np.uint8) + value) # left boundary\n assert np.all(image_poly[2:9, 8:9, c_idx] == np.zeros((7, 1), dtype=np.uint8) + value) # right boundary\n assert np.all(image_poly[2:3, 2:9, c_idx] == np.zeros((1, 7), dtype=np.uint8) + value) # top boundary\n assert np.all(image_poly[8:9, 2:9, c_idx] == np.zeros((1, 7), dtype=np.uint8) + value) # bottom boundary\n expected = np.tile(np.uint8([32, 128, 32]).reshape((1, 1, 3)), (5, 5, 1))\n assert np.all(image_poly[3:8, 3:8, :] == expected)\n\n # simple drawing of square with float32 input\n poly = ia.Polygon([(2, 2), (8, 2), (8, 8), (2, 8)])\n image_poly = poly.draw_on_image(image.astype(np.float32),\n color=[32, 128, 32], color_perimeter=[0, 255, 0],\n alpha=1.0, alpha_perimeter=1.0,\n raise_if_out_of_image=False)\n assert image_poly.dtype.type == np.float32\n assert image_poly.shape == (10, 10, 3)\n for c_idx, value in enumerate([0, 255, 0]):\n assert np.allclose(image_poly[2:9, 2:3, c_idx], np.zeros((7, 1), dtype=np.float32) + value) # left boundary\n assert np.allclose(image_poly[2:9, 8:9, c_idx], np.zeros((7, 1), dtype=np.float32) + value) # right boundary\n assert np.allclose(image_poly[2:3, 2:9, c_idx], np.zeros((1, 7), dtype=np.float32) + value) # top boundary\n assert np.allclose(image_poly[8:9, 2:9, c_idx], np.zeros((1, 7), dtype=np.float32) + value) # bottom boundary\n expected = np.tile(np.float32([32, 128, 32]).reshape((1, 1, 3)), (5, 5, 1))\n assert np.allclose(image_poly[3:8, 3:8, :], expected)\n\n # drawing of poly that is half out of image\n poly = ia.Polygon([(2, 2+5), (8, 2+5), (8, 8+5), (2, 8+5)])\n image_poly = poly.draw_on_image(image,\n color=[32, 128, 32], color_perimeter=[0, 255, 0],\n alpha=1.0, alpha_perimeter=1.0,\n raise_if_out_of_image=False)\n assert image_poly.dtype.type == np.uint8\n assert image_poly.shape == (10, 10, 3)\n assert np.sum(image) == 3 * np.sum(np.arange(100)) # draw did not change original image (copy=True)\n for c_idx, value in enumerate([0, 255, 0]):\n assert np.all(image_poly[2+5:, 2:3, c_idx] == np.zeros((3, 1), dtype=np.uint8) + value) # left boundary\n assert np.all(image_poly[2+5:, 8:9, c_idx] == np.zeros((3, 1), dtype=np.uint8) + value) # right boundary\n assert np.all(image_poly[2+5:3+5, 2:9, c_idx] == np.zeros((1, 7), dtype=np.uint8) + value) # top boundary\n expected = np.tile(np.uint8([32, 128, 32]).reshape((1, 1, 3)), (2, 5, 1))\n assert np.all(image_poly[3+5:, 3:8, :] == expected)\n\n # drawing of poly that is half out of image, with raise_if_out_of_image=True\n poly = ia.Polygon([(2, 2+5), (8, 2+5), (8, 8+5), (0, 8+5)])\n got_exception = False\n try:\n _ = poly.draw_on_image(image,\n color=[32, 128, 32], color_perimeter=[0, 255, 0],\n alpha=1.0, alpha_perimeter=1.0,\n raise_if_out_of_image=True)\n except Exception as exc:\n assert \"Cannot draw polygon\" in str(exc)\n got_exception = True\n assert not got_exception # only polygons fully outside of the image plane lead to exceptions\n\n # drawing of poly that is fully out of image\n poly = ia.Polygon([(100, 100), (100+10, 100), (100+10, 100+10), (100, 100+10)])\n image_poly = poly.draw_on_image(image,\n color=[32, 128, 32], color_perimeter=[0, 255, 0],\n alpha=1.0, alpha_perimeter=1.0,\n raise_if_out_of_image=False)\n assert np.array_equal(image_poly, image)\n\n # drawing of poly that is fully out of image, with raise_if_out_of_image=True\n poly = ia.Polygon([(100, 100), (100+10, 100), (100+10, 100+10), (100, 100+10)])\n got_exception = False\n try:\n _ = poly.draw_on_image(image,\n color=[32, 128, 32], color_perimeter=[0, 255, 0],\n alpha=1.0, alpha_perimeter=1.0,\n raise_if_out_of_image=True)\n except Exception as exc:\n assert \"Cannot draw polygon\" in str(exc)\n got_exception = True\n assert got_exception\n\n # face invisible via alpha\n poly = ia.Polygon([(2, 2), (8, 2), (8, 8), (2, 8)])\n image_poly = poly.draw_on_image(image,\n color=[32, 128, 32], color_perimeter=[0, 255, 0],\n alpha=0.0, alpha_perimeter=1.0,\n raise_if_out_of_image=False)\n assert image_poly.dtype.type == np.uint8\n assert image_poly.shape == (10, 10, 3)\n assert np.sum(image) == 3 * np.sum(np.arange(100)) # draw did not change original image (copy=True)\n for c_idx, value in enumerate([0, 255, 0]):\n assert np.all(image_poly[2:9, 2:3, c_idx] == np.zeros((7, 1), dtype=np.uint8) + value) # left boundary\n assert np.all(image_poly[3:8, 3:8, :] == image[3:8, 3:8, :])\n\n # boundary invisible via alpha\n poly = ia.Polygon([(2, 2), (8, 2), (8, 8), (2, 8)])\n image_poly = poly.draw_on_image(image,\n color=[32, 128, 32], color_perimeter=[0, 255, 0],\n alpha=1.0, alpha_perimeter=0.0,\n raise_if_out_of_image=False)\n assert image_poly.dtype.type == np.uint8\n assert image_poly.shape == (10, 10, 3)\n assert np.sum(image) == 3 * np.sum(np.arange(100)) # draw did not change original image (copy=True)\n expected = np.tile(np.uint8([32, 128, 32]).reshape((1, 1, 3)), (6, 6, 1))\n assert np.all(image_poly[2:8, 2:8, :] == expected)\n\n # alpha=0.5\n poly = ia.Polygon([(2, 2), (8, 2), (8, 8), (2, 8)])\n image_poly = poly.draw_on_image(image,\n color=[32, 128, 32], color_perimeter=[0, 255, 0],\n alpha=0.5, alpha_perimeter=0.5,\n raise_if_out_of_image=False)\n assert image_poly.dtype.type == np.uint8\n assert image_poly.shape == (10, 10, 3)\n for c_idx, value in enumerate([0, 255, 0]):\n assert np.all(\n image_poly[2:9, 8:9, c_idx] ==\n (\n 0.5*image[2:9, 8:9, c_idx]\n + np.full((7, 1), 0.5*value, dtype=np.float32)\n ).astype(np.uint8)\n ) # right boundary\n expected = 0.5 * np.tile(np.uint8([32, 128, 32]).reshape((1, 1, 3)), (5, 5, 1)) \\\n + 0.5 * image[3:8, 3:8, :]\n assert np.all(image_poly[3:8, 3:8, :] == expected.astype(np.uint8))\n\n # copy=False\n # test deactivated as the function currently does not offer a copy argument\n \"\"\"\n image_cp = np.copy(image)\n poly = ia.Polygon([(2, 2), (8, 2), (8, 8), (2, 8)])\n image_poly = poly.draw_on_image(image_cp,\n color_face=[32, 128, 32], color_boundary=[0, 255, 0],\n alpha_face=1.0, alpha_boundary=1.0,\n raise_if_out_of_image=False)\n assert image_poly.dtype.type == np.uint8\n assert image_poly.shape == (10, 10, 3)\n assert np.all(image_cp == image_poly)\n assert not np.all(image_cp == image)\n for c_idx, value in enumerate([0, 255, 0]):\n assert np.all(image_poly[2:9, 2:3, c_idx] == np.zeros((6, 1, 3), dtype=np.uint8) + value) # left boundary\n assert np.all(image_cp[2:9, 2:3, c_idx] == np.zeros((6, 1, 3), dtype=np.uint8) + value) # left boundary\n expected = np.tile(np.uint8([32, 128, 32]).reshape((1, 1, 3)), (5, 5, 1))\n assert np.all(image_poly[3:8, 3:8, :] == expected)\n assert np.all(image_cp[3:8, 3:8, :] == expected)\n \"\"\"\n\n\ndef test_Polygon_extract_from_image():\n image = np.arange(20*20*2).reshape(20, 20, 2).astype(np.int32)\n\n # inside image and completely covers it\n poly = ia.Polygon([(0, 0), (10, 0), (10, 10), (0, 10)])\n subimage = poly.extract_from_image(image)\n assert np.array_equal(subimage, image[0:10, 0:10, :])\n\n # inside image, subpart of it (not all may be extracted)\n poly = ia.Polygon([(1, 1), (9, 1), (9, 9), (1, 9)])\n subimage = poly.extract_from_image(image)\n assert np.array_equal(subimage, image[1:9, 1:9, :])\n\n # inside image, two image areas that don't belong to the polygon but have to be extracted\n poly = ia.Polygon([(0, 0), (10, 0), (10, 5), (20, 5),\n (20, 20), (10, 20), (10, 5), (0, 5)])\n subimage = poly.extract_from_image(image)\n expected = np.copy(image)\n expected[:5, 10:, :] = 0 # top right block\n expected[5:, :10, :] = 0 # left bottom block\n assert np.array_equal(subimage, expected)\n\n # partially out of image\n poly = ia.Polygon([(-5, 0), (5, 0), (5, 10), (-5, 10)])\n subimage = poly.extract_from_image(image)\n expected = np.zeros((10, 10, 2), dtype=np.int32)\n expected[0:10, 5:10, :] = image[0:10, 0:5, :]\n assert np.array_equal(subimage, expected)\n\n # fully out of image\n poly = ia.Polygon([(30, 0), (40, 0), (40, 10), (30, 10)])\n subimage = poly.extract_from_image(image)\n expected = np.zeros((10, 10, 2), dtype=np.int32)\n assert np.array_equal(subimage, expected)\n\n # inside image, subpart of it\n # float coordinates, rounded so that the whole image will be extracted\n poly = ia.Polygon([(0.4, 0.4), (9.6, 0.4), (9.6, 9.6), (0.4, 9.6)])\n subimage = poly.extract_from_image(image)\n assert np.array_equal(subimage, image[0:10, 0:10, :])\n\n # inside image, subpart of it\n # float coordinates, rounded so that x/y 0<=i<9 will be extracted (instead of 0<=i<10)\n poly = ia.Polygon([(0.5, 0.5), (9.4, 0.5), (9.4, 9.4), (0.5, 9.4)])\n subimage = poly.extract_from_image(image)\n assert np.array_equal(subimage, image[0:9, 0:9, :])\n\n # inside image, subpart of it\n # float coordinates, rounded so that x/y 1<=i<9 will be extracted (instead of 0<=i<10)\n poly = ia.Polygon([(0.51, 0.51), (9.4, 0.51), (9.4, 9.4), (0.51, 9.4)])\n subimage = poly.extract_from_image(image)\n assert np.array_equal(subimage, image[1:9, 1:9, :])\n\n # error for invalid polygons\n got_exception = False\n poly = ia.Polygon([(0.51, 0.51), (9.4, 0.51)])\n try:\n _ = poly.extract_from_image(image)\n except Exception as exc:\n assert \"Polygon must be made up\" in str(exc)\n got_exception = True\n assert got_exception\n\n\ndef test_Polygon_change_first_point_by_coords():\n poly = ia.Polygon([(0, 0), (1, 0), (1, 1)])\n poly_reordered = poly.change_first_point_by_coords(x=0, y=0)\n assert np.allclose(poly.exterior, poly_reordered.exterior)\n\n poly = ia.Polygon([(0, 0), (1, 0), (1, 1)])\n poly_reordered = poly.change_first_point_by_coords(x=1, y=0)\n # make sure that it does not reorder inplace\n assert np.allclose(poly.exterior, np.float32([[0, 0], [1, 0], [1, 1]]))\n assert np.allclose(poly_reordered.exterior, np.float32([[1, 0], [1, 1], [0, 0]]))\n\n poly = ia.Polygon([(0, 0), (1, 0), (1, 1)])\n poly_reordered = poly.change_first_point_by_coords(x=1, y=1)\n assert np.allclose(poly_reordered.exterior, np.float32([[1, 1], [0, 0], [1, 0]]))\n\n # inaccurate point, but close enough\n poly = ia.Polygon([(0, 0), (1, 0), (1, 1)])\n poly_reordered = poly.change_first_point_by_coords(x=1.0, y=0.01, max_distance=0.1)\n assert np.allclose(poly_reordered.exterior, np.float32([[1, 0], [1, 1], [0, 0]]))\n\n # inaccurate point, but close enough (infinite max distance)\n poly = ia.Polygon([(0, 0), (1, 0), (1, 1)])\n poly_reordered = poly.change_first_point_by_coords(x=1.0, y=0.01, max_distance=None)\n assert np.allclose(poly_reordered.exterior, np.float32([[1, 0], [1, 1], [0, 0]]))\n\n # point too far away\n poly = ia.Polygon([(0, 0), (1, 0), (1, 1)])\n got_exception = False\n try:\n _ = poly.change_first_point_by_coords(x=1.0, y=0.01, max_distance=0.001)\n except Exception as exc:\n assert \"Closest found point \" in str(exc)\n got_exception = True\n assert got_exception\n\n # reorder with two points\n poly = ia.Polygon([(0, 0), (1, 0)])\n poly_reordered = poly.change_first_point_by_coords(x=1, y=0)\n assert np.allclose(poly_reordered.exterior, np.float32([[1, 0], [0, 0]]))\n\n # reorder with one point\n poly = ia.Polygon([(0, 0)])\n poly_reordered = poly.change_first_point_by_coords(x=0, y=0)\n assert np.allclose(poly_reordered.exterior, np.float32([[0, 0]]))\n\n # invalid polygon\n git_exception = False\n poly = ia.Polygon([])\n try:\n _ = poly.change_first_point_by_coords(x=0, y=0)\n except Exception as exc:\n assert \"Cannot reorder polygon points\" in str(exc)\n got_exception = True\n\n\ndef test_Polygon_change_first_point_by_index():\n poly = ia.Polygon([(0, 0), (1, 0), (1, 1)])\n poly_reordered = poly.change_first_point_by_index(0)\n assert np.allclose(poly.exterior, poly_reordered.exterior)\n\n poly = ia.Polygon([(0, 0), (1, 0), (1, 1)])\n poly_reordered = poly.change_first_point_by_index(1)\n # make sure that it does not reorder inplace\n assert np.allclose(poly.exterior, np.float32([[0, 0], [1, 0], [1, 1]]))\n assert np.allclose(poly_reordered.exterior, np.float32([[1, 0], [1, 1], [0, 0]]))\n\n poly = ia.Polygon([(0, 0), (1, 0), (1, 1)])\n poly_reordered = poly.change_first_point_by_index(2)\n assert np.allclose(poly_reordered.exterior, np.float32([[1, 1], [0, 0], [1, 0]]))\n\n # reorder with two points\n poly = ia.Polygon([(0, 0), (1, 0)])\n poly_reordered = poly.change_first_point_by_index(1)\n assert np.allclose(poly_reordered.exterior, np.float32([[1, 0], [0, 0]]))\n\n # reorder with one point\n poly = ia.Polygon([(0, 0)])\n poly_reordered = poly.change_first_point_by_index(0)\n assert np.allclose(poly_reordered.exterior, np.float32([[0, 0]]))\n\n # idx out of bounds\n poly = ia.Polygon([(0, 0), (1, 0), (1, 1)])\n got_exception = False\n try:\n _ = poly.change_first_point_by_index(3)\n except AssertionError:\n got_exception = True\n assert got_exception\n\n poly = ia.Polygon([(0, 0), (1, 0), (1, 1)])\n got_exception = False\n try:\n _ = poly.change_first_point_by_index(-1)\n except AssertionError:\n got_exception = True\n assert got_exception\n\n poly = ia.Polygon([(0, 0)])\n got_exception = False\n try:\n _ = poly.change_first_point_by_index(1)\n except AssertionError:\n got_exception = True\n assert got_exception\n\n poly = ia.Polygon([])\n got_exception = False\n try:\n _ = poly.change_first_point_by_index(0)\n except AssertionError:\n got_exception = True\n assert got_exception\n\n\ndef test_Polygon_to_shapely_line_string():\n poly = ia.Polygon([(0, 0), (1, 0), (1, 1)])\n ls = poly.to_shapely_line_string()\n assert np.allclose(ls.coords, np.float32([[0, 0], [1, 0], [1, 1]]))\n\n # two point polygon\n poly = ia.Polygon([(0, 0), (1, 0)])\n ls = poly.to_shapely_line_string()\n assert np.allclose(ls.coords, np.float32([[0, 0], [1, 0]]))\n\n # one point polygon\n poly = ia.Polygon([(0, 0)])\n got_exception = False\n try:\n _ = poly.to_shapely_line_string()\n except Exception as exc:\n assert \"Conversion to shapely line string requires at least two points\" in str(exc)\n got_exception = True\n assert got_exception\n\n # zero point polygon\n poly = ia.Polygon([])\n got_exception = False\n try:\n _ = poly.to_shapely_line_string()\n except Exception as exc:\n assert \"Conversion to shapely line string requires at least two points\" in str(exc)\n got_exception = True\n assert got_exception\n\n # closed line string\n poly = ia.Polygon([(0, 0), (1, 0), (1, 1)])\n ls = poly.to_shapely_line_string(closed=True)\n assert np.allclose(ls.coords, np.float32([[0, 0], [1, 0], [1, 1], [0, 0]]))\n\n # interpolation\n poly = ia.Polygon([(0, 0), (1, 0), (1, 1)])\n ls = poly.to_shapely_line_string(interpolate=1)\n assert np.allclose(ls.coords, np.float32([[0, 0], [0.5, 0], [1, 0], [1, 0.5], [1, 1], [0.5, 0.5]]))\n\n # interpolation with 2 steps\n poly = ia.Polygon([(0, 0), (1, 0), (1, 1)])\n ls = poly.to_shapely_line_string(interpolate=2)\n assert np.allclose(ls.coords, np.float32([\n [0, 0], [1/3, 0], [2/3, 0],\n [1, 0], [1, 1/3], [1, 2/3],\n [1, 1], [2/3, 2/3], [1/3, 1/3]\n ]))\n\n # interpolation with closed=True\n poly = ia.Polygon([(0, 0), (1, 0), (1, 1)])\n ls = poly.to_shapely_line_string(closed=True, interpolate=1)\n assert np.allclose(ls.coords, np.float32([[0, 0], [0.5, 0], [1, 0], [1, 0.5], [1, 1], [0.5, 0.5], [0, 0]]))\n\n\ndef test_Polygon_to_shapely_polygon():\n exterior = [(0, 0), (1, 0), (1, 1), (0, 1)]\n poly = ia.Polygon(exterior)\n poly_shapely = poly.to_shapely_polygon()\n for (x_exp, y_exp), (x_obs, y_obs) in zip(exterior, poly_shapely.exterior.coords):\n assert x_exp - 1e-8 < x_obs < x_exp + 1e-8\n assert y_exp - 1e-8 < y_obs < y_exp + 1e-8\n\n\ndef test_Polygon_to_bounding_box():\n poly = ia.Polygon([(0, 0), (1, 0), (1, 1), (0, 1)])\n bb = poly.to_bounding_box()\n assert 0 - 1e-8 < bb.x1 < 0 + 1e-8\n assert 0 - 1e-8 < bb.y1 < 0 + 1e-8\n assert 1 - 1e-8 < bb.x2 < 1 + 1e-8\n assert 1 - 1e-8 < bb.y2 < 1 + 1e-8\n\n poly = ia.Polygon([(0.5, 0), (1, 1), (0, 1)])\n bb = poly.to_bounding_box()\n assert 0 - 1e-8 < bb.x1 < 0 + 1e-8\n assert 0 - 1e-8 < bb.y1 < 0 + 1e-8\n assert 1 - 1e-8 < bb.x2 < 1 + 1e-8\n assert 1 - 1e-8 < bb.y2 < 1 + 1e-8\n\n poly = ia.Polygon([(0.5, 0.5), (2, 0.1), (1, 1)])\n bb = poly.to_bounding_box()\n assert 0.5 - 1e-8 < bb.x1 < 0.5 + 1e-8\n assert 0.1 - 1e-8 < bb.y1 < 0.1 + 1e-8\n assert 2.0 - 1e-8 < bb.x2 < 2.0 + 1e-8\n assert 1.0 - 1e-8 < bb.y2 < 1.0 + 1e-8\n\n\ndef test_Polygon_from_shapely():\n exterior = [(0, 0), (1, 0), (1, 1), (0, 1)]\n poly_shapely = shapely.geometry.Polygon(exterior)\n poly = ia.Polygon.from_shapely(poly_shapely)\n\n # shapely messes up the point ordering, so we try to correct it here\n start_idx = 0\n for i, (x, y) in enumerate(poly.exterior):\n dist = np.sqrt((exterior[0][0] - x) ** 2 + (exterior[0][1] - x) ** 2)\n if dist < 1e-4:\n start_idx = i\n break\n poly = poly.change_first_point_by_index(start_idx)\n\n for (x_exp, y_exp), (x_obs, y_obs) in zip(exterior, poly.exterior):\n assert x_exp - 1e-8 < x_obs < x_exp + 1e-8\n assert y_exp - 1e-8 < y_obs < y_exp + 1e-8\n\n # empty polygon\n poly_shapely = shapely.geometry.Polygon([])\n poly = ia.Polygon.from_shapely(poly_shapely)\n assert len(poly.exterior) == 0\n\n\ndef test_Polygon_copy():\n poly = ia.Polygon([(0, 0), (1, 0), (1, 1), (0, 1)], label=\"test\")\n poly_cp = poly.copy()\n assert poly.exterior.dtype.type == poly_cp.exterior.dtype.type\n assert poly.exterior.shape == poly_cp.exterior.shape\n assert np.allclose(poly.exterior, poly_cp.exterior)\n assert poly.label == poly_cp.label\n\n\ndef test_Polygon_deepcopy():\n poly = ia.Polygon([(0, 0), (1, 0), (1, 1), (0, 1)], label=\"test\")\n poly_cp = poly.deepcopy()\n assert poly.exterior.dtype.type == poly_cp.exterior.dtype.type\n assert poly.exterior.shape == poly_cp.exterior.shape\n assert np.allclose(poly.exterior, poly_cp.exterior)\n assert poly.label == poly_cp.label\n\n poly = ia.Polygon([(0, 0), (1, 0), (1, 1), (0, 1)], label=\"test\")\n poly_cp = poly.deepcopy()\n poly_cp.exterior[0, 0] = 100.0\n poly_cp.label = \"test2\"\n assert poly.exterior.dtype.type == poly_cp.exterior.dtype.type\n assert poly.exterior.shape == poly_cp.exterior.shape\n assert not np.allclose(poly.exterior, poly_cp.exterior)\n assert not poly.label == poly_cp.label\n\n\ndef test_Polygon___repr__():\n _test_Polygon_repr_str(lambda poly: poly.__repr__())\n\n\ndef test_Polygon___str__():\n _test_Polygon_repr_str(lambda poly: poly.__str__())\n\n\ndef _test_Polygon_repr_str(func):\n # ints\n poly = ia.Polygon([(0, 0), (1, 0), (1, 1), (0, 1)], label=\"test\")\n s = func(poly)\n assert s == \"Polygon([(x=0.000, y=0.000), (x=1.000, y=0.000), (x=1.000, y=1.000), (x=0.000, y=1.000)] \" \\\n + \"(4 points), label=test)\"\n\n # floats\n poly = ia.Polygon([(0, 0.5), (1.5, 0), (1, 1), (0, 1)], label=\"test\")\n s = func(poly)\n assert s == \"Polygon([(x=0.000, y=0.500), (x=1.500, y=0.000), (x=1.000, y=1.000), (x=0.000, y=1.000)] \" \\\n + \"(4 points), label=test)\"\n\n # label None\n poly = ia.Polygon([(0, 0), (1, 0), (1, 1), (0, 1)], label=None)\n s = func(poly)\n assert s == \"Polygon([(x=0.000, y=0.000), (x=1.000, y=0.000), (x=1.000, y=1.000), (x=0.000, y=1.000)] \" \\\n + \"(4 points), label=None)\"\n\n # no points\n poly = ia.Polygon([], label=\"test\")\n s = func(poly)\n assert s == \"Polygon([] (0 points), label=test)\"\n\n\ndef test_Polygon_exterior_almost_equals():\n # exactly same exterior\n poly_a = ia.Polygon([(0, 0), (1, 0), (1, 1), (0, 1)])\n poly_b = ia.Polygon([(0, 0), (1, 0), (1, 1), (0, 1)])\n assert poly_a.exterior_almost_equals(poly_b)\n\n # one point duplicated\n poly_a = ia.Polygon([(0, 0), (1, 0), (1, 1), (0, 1)])\n poly_b = ia.Polygon([(0, 0), (1, 0), (1, 1), (1, 1), (0, 1)])\n assert poly_a.exterior_almost_equals(poly_b)\n\n # several points added without changing geometry\n poly_a = ia.Polygon([(0, 0), (1, 0), (1, 1), (0, 1)])\n poly_b = ia.Polygon([(0, 0), (0.5, 0), (1, 0), (1, 0.5), (1, 1), (0.5, 1), (0, 1), (0, 0.5)])\n assert poly_a.exterior_almost_equals(poly_b)\n\n # different order\n poly_a = ia.Polygon([(0, 0), (1, 0), (1, 1), (0, 1)])\n poly_b = ia.Polygon([(0, 1), (1, 1), (1, 0), (0, 0)])\n assert poly_a.exterior_almost_equals(poly_b)\n\n # tiny shift below tolerance\n poly_a = ia.Polygon([(0, 0), (1, 0), (1, 1), (0, 1)])\n poly_b = ia.Polygon([(0+1e-6, 0), (1+1e-6, 0), (1+1e-6, 1), (0+1e-6, 1)])\n assert poly_a.exterior_almost_equals(poly_b, max_distance=1e-3)\n\n # tiny shift above tolerance\n poly_a = ia.Polygon([(0, 0), (1, 0), (1, 1), (0, 1)])\n poly_b = ia.Polygon([(0+1e-6, 0), (1+1e-6, 0), (1+1e-6, 1), (0+1e-6, 1)])\n assert not poly_a.exterior_almost_equals(poly_b, max_distance=1e-9)\n\n # shifted polygon towards half overlap\n poly_a = ia.Polygon([(0, 0), (1, 0), (1, 1), (0, 1)])\n poly_b = ia.Polygon([(0.5, 0), (1.5, 0), (1.5, 1), (0.5, 1)])\n assert not poly_a.exterior_almost_equals(poly_b)\n\n # shifted polygon towards no overlap at all\n poly_a = ia.Polygon([(0, 0), (1, 0), (1, 1), (0, 1)])\n poly_b = ia.Polygon([(100, 0), (101, 0), (101, 1), (100, 1)])\n assert not poly_a.exterior_almost_equals(poly_b)\n\n # both polygons without points\n poly_a = ia.Polygon([])\n poly_b = ia.Polygon([])\n assert poly_a.exterior_almost_equals(poly_b)\n\n # both polygons with one point\n poly_a = ia.Polygon([(0, 0)])\n poly_b = ia.Polygon([(0, 0)])\n assert poly_a.exterior_almost_equals(poly_b)\n\n poly_a = ia.Polygon([(0, 0)])\n poly_b = ia.Polygon([(100, 100)])\n assert not poly_a.exterior_almost_equals(poly_b)\n\n poly_a = ia.Polygon([(0, 0)])\n poly_b = ia.Polygon([(0+1e-6, 0)])\n assert poly_a.exterior_almost_equals(poly_b, max_distance=1e-2)\n\n poly_a = ia.Polygon([(0, 0)])\n poly_b = ia.Polygon([(0+1, 0)])\n assert not poly_a.exterior_almost_equals(poly_b, max_distance=1e-2)\n\n # both polygons with two points\n poly_a = ia.Polygon([(0, 0), (1, 0)])\n poly_b = ia.Polygon([(0, 0), (1, 0)])\n assert poly_a.exterior_almost_equals(poly_b)\n\n poly_a = ia.Polygon([(0, 0), (0, 0)])\n poly_b = ia.Polygon([(0, 0), (0, 0)])\n assert poly_a.exterior_almost_equals(poly_b)\n\n poly_a = ia.Polygon([(0, 0), (1, 0)])\n poly_b = ia.Polygon([(0, 0), (2, 0)])\n assert not poly_a.exterior_almost_equals(poly_b)\n\n poly_a = ia.Polygon([(0, 0), (1, 0)])\n poly_b = ia.Polygon([(0+1e-6, 0), (1+1e-6, 0)])\n assert poly_a.exterior_almost_equals(poly_b, max_distance=1e-2)\n\n # both polygons with three points\n poly_a = ia.Polygon([(0, 0), (1, 0), (0.5, 1)])\n poly_b = ia.Polygon([(0, 0), (1, 0), (0.5, 1)])\n assert poly_a.exterior_almost_equals(poly_b)\n\n poly_a = ia.Polygon([(0, 0), (1, 0), (0.5, 1)])\n poly_b = ia.Polygon([(0, 0), (1, -1), (0.5, 1)])\n assert not poly_a.exterior_almost_equals(poly_b)\n\n poly_a = ia.Polygon([(0, 0), (1, 0), (0.5, 1)])\n poly_b = ia.Polygon([(0, 0), (1+1e-6, 0), (0.5, 1)])\n assert poly_a.exterior_almost_equals(poly_b, max_distance=1e-2)\n\n # one polygon with zero points, other with one\n poly_a = ia.Polygon([])\n poly_b = ia.Polygon([(0, 0)])\n assert not poly_a.exterior_almost_equals(poly_b)\n\n poly_a = ia.Polygon([(0, 0)])\n poly_b = ia.Polygon([])\n assert not poly_a.exterior_almost_equals(poly_b)\n\n # one polygon with one point, other with two\n poly_a = ia.Polygon([(-10, -20)])\n poly_b = ia.Polygon([(0, 0), (1, 0)])\n assert not poly_a.exterior_almost_equals(poly_b)\n\n poly_a = ia.Polygon([(0, 0)])\n poly_b = ia.Polygon([(0, 0), (1, 0)])\n assert not poly_a.exterior_almost_equals(poly_b)\n\n poly_a = ia.Polygon([(0, 0), (1, 0)])\n poly_b = ia.Polygon([(0, 0)])\n assert not poly_a.exterior_almost_equals(poly_b)\n\n poly_a = ia.Polygon([(0, 0), (0, 0)])\n poly_b = ia.Polygon([(0, 0)])\n assert poly_a.exterior_almost_equals(poly_b)\n\n poly_a = ia.Polygon([(0, 0)])\n poly_b = ia.Polygon([(0, 0), (0, 0)])\n assert poly_a.exterior_almost_equals(poly_b)\n\n poly_a = ia.Polygon([(0, 0), (0+1e-6, 0)])\n poly_b = ia.Polygon([(0, 0)])\n assert poly_a.exterior_almost_equals(poly_b, max_distance=1e-2)\n\n poly_a = ia.Polygon([(0, 0), (0+1e-4, 0)])\n poly_b = ia.Polygon([(0, 0)])\n assert not poly_a.exterior_almost_equals(poly_b, max_distance=1e-9)\n\n # one polygon with one point, other with three\n poly_a = ia.Polygon([(0, 0)])\n poly_b = ia.Polygon([(0, 0), (1, 0), (0.5, 1)])\n assert not poly_a.exterior_almost_equals(poly_b)\n\n poly_a = ia.Polygon([(0, 0), (1, 0), (0.5, 1)])\n poly_b = ia.Polygon([(0, 0)])\n assert not poly_a.exterior_almost_equals(poly_b)\n\n poly_a = ia.Polygon([(0, 0)])\n poly_b = ia.Polygon([(0, 0), (0, 0), (0, 0)])\n assert poly_a.exterior_almost_equals(poly_b)\n\n poly_a = ia.Polygon([(0, 0)])\n poly_b = ia.Polygon([(0, 0), (0, 0), (1, 0)])\n assert not poly_a.exterior_almost_equals(poly_b)\n\n poly_a = ia.Polygon([(0, 0)])\n poly_b = ia.Polygon([(0, 0), (1, 0), (0, 0)])\n assert not poly_a.exterior_almost_equals(poly_b)\n\n poly_a = ia.Polygon([(0, 0)])\n poly_b = ia.Polygon([(0, 0), (0+1e-6, 0), (0, 0+1e-6)])\n assert poly_a.exterior_almost_equals(poly_b, max_distance=1e-2)\n\n poly_a = ia.Polygon([(0, 0)])\n poly_b = ia.Polygon([(0, 0), (0+1e-4, 0), (0, 0+1e-4)])\n assert not poly_a.exterior_almost_equals(poly_b, max_distance=1e-9)\n\n # two polygons that are different, but with carefully placed points so that interpolation between polygon\n # points is necessary to spot the difference\n poly_a = ia.Polygon([(1, 0), (1, 1), (0, 1)])\n poly_b = ia.Polygon([(1, 0), (1, 1), (0, 1), (1-1e-6, 1-1e-6)])\n assert poly_a.exterior_almost_equals(poly_b, max_distance=1e-4, interpolate=0)\n assert not poly_a.exterior_almost_equals(poly_b, max_distance=1e-4, interpolate=1)\n\n\ndef test_Polygon_almost_equals():\n poly_a = ia.Polygon([])\n poly_b = ia.Polygon([])\n assert poly_a.almost_equals(poly_b)\n\n poly_a = ia.Polygon([(0, 0)])\n poly_b = ia.Polygon([(0, 0)])\n assert poly_a.almost_equals(poly_b)\n\n poly_a = ia.Polygon([(0, 0)])\n poly_b = ia.Polygon([(0, 0), (0, 0)])\n assert poly_a.almost_equals(poly_b)\n\n poly_a = ia.Polygon([(0, 0)])\n poly_b = ia.Polygon([(0, 0), (0, 0), (0, 0)])\n assert poly_a.almost_equals(poly_b)\n\n poly_a = ia.Polygon([(0, 0)])\n poly_b = ia.Polygon([(0, 0), (0+1e-10, 0)])\n assert poly_a.almost_equals(poly_b)\n\n poly_a = ia.Polygon([(0, 0)], label=\"test\")\n poly_b = ia.Polygon([(0, 0)])\n assert not poly_a.almost_equals(poly_b)\n\n poly_a = ia.Polygon([(0, 0)])\n poly_b = ia.Polygon([(0, 0)], label=\"test\")\n assert not poly_a.almost_equals(poly_b)\n\n poly_a = ia.Polygon([(0, 0)], label=\"test\")\n poly_b = ia.Polygon([(0, 0)], label=\"test\")\n assert poly_a.almost_equals(poly_b)\n\n poly_a = ia.Polygon([(0, 0)], label=\"test\")\n poly_b = ia.Polygon([(1, 0)], label=\"test\")\n assert not poly_a.almost_equals(poly_b)\n\n poly_a = ia.Polygon([(0, 0)], label=\"testA\")\n poly_b = ia.Polygon([(0, 0)], label=\"testB\")\n assert not poly_a.almost_equals(poly_b)\n\n poly_a = ia.Polygon([(0, 0), (1, 0), (0.5, 1)])\n poly_b = ia.Polygon([(0, 0), (1, 0), (0.5, 1)])\n assert poly_a.almost_equals(poly_b)\n\n poly_a = ia.Polygon([(0, 0)])\n poly_b = ia.Polygon([(0, 0), (1, 0), (0.5, 1)])\n assert not poly_a.almost_equals(poly_b)\n\n poly_a = ia.Polygon([(0, 0)])\n assert not poly_a.almost_equals(\"foo\")\n\n\ndef test___convert_points_to_shapely_line_string():\n # TODO this function seems to already be covered completely by other tests, so add a proper test later\n pass\n\n\ndef test__interpolate_point_pair():\n point_a = (0, 0)\n point_b = (1, 2)\n inter = _interpolate_point_pair(point_a, point_b, 1)\n assert np.allclose(\n inter,\n np.float32([\n [0.5, 1.0]\n ])\n )\n\n inter = _interpolate_point_pair(point_a, point_b, 2)\n assert np.allclose(\n inter,\n np.float32([\n [1*1/3, 1*2/3],\n [2*1/3, 2*2/3]\n ])\n )\n\n inter = _interpolate_point_pair(point_a, point_b, 0)\n assert len(inter) == 0\n\n\ndef test__interpolate_points():\n # 2 points\n points = [\n (0, 0),\n (1, 2)\n ]\n inter = _interpolate_points(points, 0)\n assert np.allclose(\n inter,\n np.float32([\n [0, 0],\n [1, 2]\n ])\n )\n\n inter = _interpolate_points(points, 1)\n assert np.allclose(\n inter,\n np.float32([\n [0, 0],\n [0.5, 1.0],\n [1, 2],\n [0.5, 1.0]\n ])\n )\n\n inter = _interpolate_points(points, 1, closed=False)\n assert np.allclose(\n inter,\n np.float32([\n [0, 0],\n [0.5, 1.0],\n [1, 2]\n ])\n )\n\n # 3 points\n points = [\n (0, 0),\n (1, 2),\n (0.5, 3)\n ]\n\n inter = _interpolate_points(points, 0)\n assert np.allclose(\n inter,\n np.float32([\n [0, 0],\n [1, 2],\n [0.5, 3]\n ])\n )\n\n inter = _interpolate_points(points, 1)\n assert np.allclose(\n inter,\n np.float32([\n [0, 0],\n [0.5, 1.0],\n [1, 2],\n [0.75, 2.5],\n [0.5, 3],\n [0.25, 1.5]\n ])\n )\n\n inter = _interpolate_points(points, 1, closed=False)\n assert np.allclose(\n inter,\n np.float32([\n [0, 0],\n [0.5, 1.0],\n [1, 2],\n [0.75, 2.5],\n [0.5, 3]\n ])\n )\n\n # 0 points\n points = []\n inter = _interpolate_points(points, 1)\n assert len(inter) == 0\n\n # 1 point\n points = [(0, 0)]\n inter = _interpolate_points(points, 0)\n assert np.allclose(\n inter,\n np.float32([\n [0, 0]\n ])\n )\n inter = _interpolate_points(points, 1)\n assert np.allclose(\n inter,\n np.float32([\n [0, 0]\n ])\n )\n\n\ndef test__interpolate_points_by_max_distance():\n # 2 points\n points = [\n (0, 0),\n (0, 2)\n ]\n inter = _interpolate_points_by_max_distance(points, 10000)\n assert np.allclose(\n inter,\n points\n )\n\n inter = _interpolate_points_by_max_distance(points, 1.0)\n assert np.allclose(\n inter,\n np.float32([\n [0, 0],\n [0, 1.0],\n [0, 2],\n [0, 1.0]\n ])\n )\n\n inter = _interpolate_points_by_max_distance(points, 1.0, closed=False)\n assert np.allclose(\n inter,\n np.float32([\n [0, 0],\n [0, 1.0],\n [0, 2]\n ])\n )\n\n # 3 points\n points = [\n (0, 0),\n (0, 2),\n (2, 0)\n ]\n\n inter = _interpolate_points_by_max_distance(points, 1.0)\n assert np.allclose(\n inter,\n np.float32([\n [0, 0],\n [0, 1.0],\n [0, 2],\n [1.0, 1.0],\n [2, 0],\n [1.0, 0]\n ])\n )\n\n inter = _interpolate_points_by_max_distance(points, 1.0, closed=False)\n assert np.allclose(\n inter,\n np.float32([\n [0, 0],\n [0, 1.0],\n [0, 2],\n [1.0, 1.0],\n [2, 0]\n ])\n )\n\n # 0 points\n points = []\n inter = _interpolate_points_by_max_distance(points, 1.0)\n assert len(inter) == 0\n\n # 1 points\n points = [(0, 0)]\n\n inter = _interpolate_points_by_max_distance(points, 1.0)\n assert np.allclose(\n inter,\n np.float32([\n [0, 0]\n ])\n )\n\n\nif __name__ == \"__main__\":\n main()\n"
] |
[
[
"numpy.ones_like",
"numpy.array_equal",
"numpy.isclose",
"numpy.copy",
"numpy.tile",
"numpy.min",
"numpy.finfo",
"numpy.dtype",
"numpy.max",
"numpy.concatenate",
"numpy.uint8",
"numpy.zeros_like",
"numpy.full",
"numpy.arange",
"numpy.float128",
"numpy.sqrt",
"numpy.int32",
"matplotlib.use",
"numpy.pad",
"numpy.array",
"numpy.zeros",
"numpy.round",
"numpy.float64",
"numpy.allclose",
"numpy.float32",
"numpy.hstack",
"numpy.average",
"numpy.result_type",
"numpy.random.RandomState",
"numpy.random.seed",
"numpy.sum",
"numpy.ones",
"numpy.abs",
"numpy.all"
]
] |
jcampbell/scipy
|
[
"a11eef3a29ad200649edd32c0de0d0210001acb4",
"a11eef3a29ad200649edd32c0de0d0210001acb4",
"a11eef3a29ad200649edd32c0de0d0210001acb4"
] |
[
"scipy/stats/_stats_mstats_common.py",
"scipy/special/tests/test_hyp2f1.py",
"scipy/signal/_peak_finding.py"
] |
[
"import warnings\nimport numpy as np\nimport scipy.stats._stats_py\nfrom . import distributions\nfrom .._lib._bunch import _make_tuple_bunch\n\n\n__all__ = ['_find_repeats', 'linregress', 'theilslopes', 'siegelslopes']\n\n# This is not a namedtuple for backwards compatibility. See PR #12983\nLinregressResult = _make_tuple_bunch('LinregressResult',\n ['slope', 'intercept', 'rvalue',\n 'pvalue', 'stderr'],\n extra_field_names=['intercept_stderr'])\nTheilslopesResult = _make_tuple_bunch('TheilslopesResult',\n ['slope', 'intercept',\n 'low_slope', 'high_slope'])\nSiegelslopesResult = _make_tuple_bunch('SiegelslopesResult',\n ['slope', 'intercept'])\n\n\ndef linregress(x, y=None, alternative='two-sided'):\n \"\"\"\n Calculate a linear least-squares regression for two sets of measurements.\n\n Parameters\n ----------\n x, y : array_like\n Two sets of measurements. Both arrays should have the same length. If\n only `x` is given (and ``y=None``), then it must be a two-dimensional\n array where one dimension has length 2. The two sets of measurements\n are then found by splitting the array along the length-2 dimension. In\n the case where ``y=None`` and `x` is a 2x2 array, ``linregress(x)`` is\n equivalent to ``linregress(x[0], x[1])``.\n alternative : {'two-sided', 'less', 'greater'}, optional\n Defines the alternative hypothesis. Default is 'two-sided'.\n The following options are available:\n\n * 'two-sided': the slope of the regression line is nonzero\n * 'less': the slope of the regression line is less than zero\n * 'greater': the slope of the regression line is greater than zero\n\n .. versionadded:: 1.7.0\n\n Returns\n -------\n result : ``LinregressResult`` instance\n The return value is an object with the following attributes:\n\n slope : float\n Slope of the regression line.\n intercept : float\n Intercept of the regression line.\n rvalue : float\n The Pearson correlation coefficient. The square of ``rvalue``\n is equal to the coefficient of determination.\n pvalue : float\n The p-value for a hypothesis test whose null hypothesis is\n that the slope is zero, using Wald Test with t-distribution of\n the test statistic. See `alternative` above for alternative\n hypotheses.\n stderr : float\n Standard error of the estimated slope (gradient), under the\n assumption of residual normality.\n intercept_stderr : float\n Standard error of the estimated intercept, under the assumption\n of residual normality.\n\n See Also\n --------\n scipy.optimize.curve_fit :\n Use non-linear least squares to fit a function to data.\n scipy.optimize.leastsq :\n Minimize the sum of squares of a set of equations.\n\n Notes\n -----\n Missing values are considered pair-wise: if a value is missing in `x`,\n the corresponding value in `y` is masked.\n\n For compatibility with older versions of SciPy, the return value acts\n like a ``namedtuple`` of length 5, with fields ``slope``, ``intercept``,\n ``rvalue``, ``pvalue`` and ``stderr``, so one can continue to write::\n\n slope, intercept, r, p, se = linregress(x, y)\n\n With that style, however, the standard error of the intercept is not\n available. To have access to all the computed values, including the\n standard error of the intercept, use the return value as an object\n with attributes, e.g.::\n\n result = linregress(x, y)\n print(result.intercept, result.intercept_stderr)\n\n Examples\n --------\n >>> import matplotlib.pyplot as plt\n >>> from scipy import stats\n >>> rng = np.random.default_rng()\n\n Generate some data:\n\n >>> x = rng.random(10)\n >>> y = 1.6*x + rng.random(10)\n\n Perform the linear regression:\n\n >>> res = stats.linregress(x, y)\n\n Coefficient of determination (R-squared):\n\n >>> print(f\"R-squared: {res.rvalue**2:.6f}\")\n R-squared: 0.717533\n\n Plot the data along with the fitted line:\n\n >>> plt.plot(x, y, 'o', label='original data')\n >>> plt.plot(x, res.intercept + res.slope*x, 'r', label='fitted line')\n >>> plt.legend()\n >>> plt.show()\n\n Calculate 95% confidence interval on slope and intercept:\n\n >>> # Two-sided inverse Students t-distribution\n >>> # p - probability, df - degrees of freedom\n >>> from scipy.stats import t\n >>> tinv = lambda p, df: abs(t.ppf(p/2, df))\n\n >>> ts = tinv(0.05, len(x)-2)\n >>> print(f\"slope (95%): {res.slope:.6f} +/- {ts*res.stderr:.6f}\")\n slope (95%): 1.453392 +/- 0.743465\n >>> print(f\"intercept (95%): {res.intercept:.6f}\"\n ... f\" +/- {ts*res.intercept_stderr:.6f}\")\n intercept (95%): 0.616950 +/- 0.544475\n\n \"\"\"\n TINY = 1.0e-20\n if y is None: # x is a (2, N) or (N, 2) shaped array_like\n x = np.asarray(x)\n if x.shape[0] == 2:\n x, y = x\n elif x.shape[1] == 2:\n x, y = x.T\n else:\n raise ValueError(\"If only `x` is given as input, it has to \"\n \"be of shape (2, N) or (N, 2); provided shape \"\n f\"was {x.shape}.\")\n else:\n x = np.asarray(x)\n y = np.asarray(y)\n\n if x.size == 0 or y.size == 0:\n raise ValueError(\"Inputs must not be empty.\")\n\n if np.amax(x) == np.amin(x) and len(x) > 1:\n raise ValueError(\"Cannot calculate a linear regression \"\n \"if all x values are identical\")\n\n n = len(x)\n xmean = np.mean(x, None)\n ymean = np.mean(y, None)\n\n # Average sums of square differences from the mean\n # ssxm = mean( (x-mean(x))^2 )\n # ssxym = mean( (x-mean(x)) * (y-mean(y)) )\n ssxm, ssxym, _, ssym = np.cov(x, y, bias=1).flat\n\n # R-value\n # r = ssxym / sqrt( ssxm * ssym )\n if ssxm == 0.0 or ssym == 0.0:\n # If the denominator was going to be 0\n r = 0.0\n else:\n r = ssxym / np.sqrt(ssxm * ssym)\n # Test for numerical error propagation (make sure -1 < r < 1)\n if r > 1.0:\n r = 1.0\n elif r < -1.0:\n r = -1.0\n\n slope = ssxym / ssxm\n intercept = ymean - slope*xmean\n if n == 2:\n # handle case when only two points are passed in\n if y[0] == y[1]:\n prob = 1.0\n else:\n prob = 0.0\n slope_stderr = 0.0\n intercept_stderr = 0.0\n else:\n df = n - 2 # Number of degrees of freedom\n # n-2 degrees of freedom because 2 has been used up\n # to estimate the mean and standard deviation\n t = r * np.sqrt(df / ((1.0 - r + TINY)*(1.0 + r + TINY)))\n t, prob = scipy.stats._stats_py._ttest_finish(df, t, alternative)\n\n slope_stderr = np.sqrt((1 - r**2) * ssym / ssxm / df)\n\n # Also calculate the standard error of the intercept\n # The following relationship is used:\n # ssxm = mean( (x-mean(x))^2 )\n # = ssx - sx*sx\n # = mean( x^2 ) - mean(x)^2\n intercept_stderr = slope_stderr * np.sqrt(ssxm + xmean**2)\n\n return LinregressResult(slope=slope, intercept=intercept, rvalue=r,\n pvalue=prob, stderr=slope_stderr,\n intercept_stderr=intercept_stderr)\n\n\ndef theilslopes(y, x=None, alpha=0.95, method='separate'):\n r\"\"\"\n Computes the Theil-Sen estimator for a set of points (x, y).\n\n `theilslopes` implements a method for robust linear regression. It\n computes the slope as the median of all slopes between paired values.\n\n Parameters\n ----------\n y : array_like\n Dependent variable.\n x : array_like or None, optional\n Independent variable. If None, use ``arange(len(y))`` instead.\n alpha : float, optional\n Confidence degree between 0 and 1. Default is 95% confidence.\n Note that `alpha` is symmetric around 0.5, i.e. both 0.1 and 0.9 are\n interpreted as \"find the 90% confidence interval\".\n method : {'joint', 'separate'}, optional\n Method to be used for computing estimate for intercept.\n Following methods are supported,\n\n * 'joint': Uses np.median(y - slope * x) as intercept.\n * 'separate': Uses np.median(y) - slope * np.median(x)\n as intercept.\n\n The default is 'separate'.\n\n .. versionadded:: 1.8.0\n\n Returns\n -------\n result : ``TheilslopesResult`` instance\n The return value is an object with the following attributes:\n\n slope : float\n Theil slope.\n intercept : float\n Intercept of the Theil line.\n low_slope : float\n Lower bound of the confidence interval on `slope`.\n high_slope : float\n Upper bound of the confidence interval on `slope`.\n\n See Also\n --------\n siegelslopes : a similar technique using repeated medians\n\n Notes\n -----\n The implementation of `theilslopes` follows [1]_. The intercept is\n not defined in [1]_, and here it is defined as ``median(y) -\n slope*median(x)``, which is given in [3]_. Other definitions of\n the intercept exist in the literature such as ``median(y - slope*x)``\n in [4]_. The approach to compute the intercept can be determined by the\n parameter ``method``. A confidence interval for the intercept is not\n given as this question is not addressed in [1]_.\n\n For compatibility with older versions of SciPy, the return value acts\n like a ``namedtuple`` of length 4, with fields ``slope``, ``intercept``,\n ``low_slope``, and ``high_slope``, so one can continue to write::\n\n slope, intercept, low_slope, high_slope = theilslopes(y, x)\n\n References\n ----------\n .. [1] P.K. Sen, \"Estimates of the regression coefficient based on\n Kendall's tau\", J. Am. Stat. Assoc., Vol. 63, pp. 1379-1389, 1968.\n .. [2] H. Theil, \"A rank-invariant method of linear and polynomial\n regression analysis I, II and III\", Nederl. Akad. Wetensch., Proc.\n 53:, pp. 386-392, pp. 521-525, pp. 1397-1412, 1950.\n .. [3] W.L. Conover, \"Practical nonparametric statistics\", 2nd ed.,\n John Wiley and Sons, New York, pp. 493.\n .. [4] https://en.wikipedia.org/wiki/Theil%E2%80%93Sen_estimator\n\n Examples\n --------\n >>> from scipy import stats\n >>> import matplotlib.pyplot as plt\n\n >>> x = np.linspace(-5, 5, num=150)\n >>> y = x + np.random.normal(size=x.size)\n >>> y[11:15] += 10 # add outliers\n >>> y[-5:] -= 7\n\n Compute the slope, intercept and 90% confidence interval. For comparison,\n also compute the least-squares fit with `linregress`:\n\n >>> res = stats.theilslopes(y, x, 0.90, method='separate')\n >>> lsq_res = stats.linregress(x, y)\n\n Plot the results. The Theil-Sen regression line is shown in red, with the\n dashed red lines illustrating the confidence interval of the slope (note\n that the dashed red lines are not the confidence interval of the regression\n as the confidence interval of the intercept is not included). The green\n line shows the least-squares fit for comparison.\n\n >>> fig = plt.figure()\n >>> ax = fig.add_subplot(111)\n >>> ax.plot(x, y, 'b.')\n >>> ax.plot(x, res[1] + res[0] * x, 'r-')\n >>> ax.plot(x, res[1] + res[2] * x, 'r--')\n >>> ax.plot(x, res[1] + res[3] * x, 'r--')\n >>> ax.plot(x, lsq_res[1] + lsq_res[0] * x, 'g-')\n >>> plt.show()\n\n \"\"\"\n if method not in ['joint', 'separate']:\n raise ValueError((\"method must be either 'joint' or 'separate'.\"\n \"'{}' is invalid.\".format(method)))\n # We copy both x and y so we can use _find_repeats.\n y = np.array(y).flatten()\n if x is None:\n x = np.arange(len(y), dtype=float)\n else:\n x = np.array(x, dtype=float).flatten()\n if len(x) != len(y):\n raise ValueError(\"Incompatible lengths ! (%s<>%s)\" %\n (len(y), len(x)))\n\n # Compute sorted slopes only when deltax > 0\n deltax = x[:, np.newaxis] - x\n deltay = y[:, np.newaxis] - y\n slopes = deltay[deltax > 0] / deltax[deltax > 0]\n if not slopes.size:\n msg = \"All `x` coordinates are identical.\"\n warnings.warn(msg, RuntimeWarning, stacklevel=2)\n slopes.sort()\n medslope = np.median(slopes)\n if method == 'joint':\n medinter = np.median(y - medslope * x)\n else:\n medinter = np.median(y) - medslope * np.median(x)\n # Now compute confidence intervals\n if alpha > 0.5:\n alpha = 1. - alpha\n\n z = distributions.norm.ppf(alpha / 2.)\n # This implements (2.6) from Sen (1968)\n _, nxreps = _find_repeats(x)\n _, nyreps = _find_repeats(y)\n nt = len(slopes) # N in Sen (1968)\n ny = len(y) # n in Sen (1968)\n # Equation 2.6 in Sen (1968):\n sigsq = 1/18. * (ny * (ny-1) * (2*ny+5) -\n sum(k * (k-1) * (2*k + 5) for k in nxreps) -\n sum(k * (k-1) * (2*k + 5) for k in nyreps))\n # Find the confidence interval indices in `slopes`\n try:\n sigma = np.sqrt(sigsq)\n Ru = min(int(np.round((nt - z*sigma)/2.)), len(slopes)-1)\n Rl = max(int(np.round((nt + z*sigma)/2.)) - 1, 0)\n delta = slopes[[Rl, Ru]]\n except (ValueError, IndexError):\n delta = (np.nan, np.nan)\n\n return TheilslopesResult(slope=medslope, intercept=medinter,\n low_slope=delta[0], high_slope=delta[1])\n\n\ndef _find_repeats(arr):\n # This function assumes it may clobber its input.\n if len(arr) == 0:\n return np.array(0, np.float64), np.array(0, np.intp)\n\n # XXX This cast was previously needed for the Fortran implementation,\n # should we ditch it?\n arr = np.asarray(arr, np.float64).ravel()\n arr.sort()\n\n # Taken from NumPy 1.9's np.unique.\n change = np.concatenate(([True], arr[1:] != arr[:-1]))\n unique = arr[change]\n change_idx = np.concatenate(np.nonzero(change) + ([arr.size],))\n freq = np.diff(change_idx)\n atleast2 = freq > 1\n return unique[atleast2], freq[atleast2]\n\n\ndef siegelslopes(y, x=None, method=\"hierarchical\"):\n r\"\"\"\n Computes the Siegel estimator for a set of points (x, y).\n\n `siegelslopes` implements a method for robust linear regression\n using repeated medians (see [1]_) to fit a line to the points (x, y).\n The method is robust to outliers with an asymptotic breakdown point\n of 50%.\n\n Parameters\n ----------\n y : array_like\n Dependent variable.\n x : array_like or None, optional\n Independent variable. If None, use ``arange(len(y))`` instead.\n method : {'hierarchical', 'separate'}\n If 'hierarchical', estimate the intercept using the estimated\n slope ``slope`` (default option).\n If 'separate', estimate the intercept independent of the estimated\n slope. See Notes for details.\n\n Returns\n -------\n result : ``SiegelslopesResult`` instance\n The return value is an object with the following attributes:\n\n slope : float\n Estimate of the slope of the regression line.\n intercept : float\n Estimate of the intercept of the regression line.\n\n See Also\n --------\n theilslopes : a similar technique without repeated medians\n\n Notes\n -----\n With ``n = len(y)``, compute ``m_j`` as the median of\n the slopes from the point ``(x[j], y[j])`` to all other `n-1` points.\n ``slope`` is then the median of all slopes ``m_j``.\n Two ways are given to estimate the intercept in [1]_ which can be chosen\n via the parameter ``method``.\n The hierarchical approach uses the estimated slope ``slope``\n and computes ``intercept`` as the median of ``y - slope*x``.\n The other approach estimates the intercept separately as follows: for\n each point ``(x[j], y[j])``, compute the intercepts of all the `n-1`\n lines through the remaining points and take the median ``i_j``.\n ``intercept`` is the median of the ``i_j``.\n\n The implementation computes `n` times the median of a vector of size `n`\n which can be slow for large vectors. There are more efficient algorithms\n (see [2]_) which are not implemented here.\n\n For compatibility with older versions of SciPy, the return value acts\n like a ``namedtuple`` of length 2, with fields ``slope`` and\n ``intercept``, so one can continue to write::\n\n slope, intercept = siegelslopes(y, x)\n\n References\n ----------\n .. [1] A. Siegel, \"Robust Regression Using Repeated Medians\",\n Biometrika, Vol. 69, pp. 242-244, 1982.\n\n .. [2] A. Stein and M. Werman, \"Finding the repeated median regression\n line\", Proceedings of the Third Annual ACM-SIAM Symposium on\n Discrete Algorithms, pp. 409-413, 1992.\n\n Examples\n --------\n >>> from scipy import stats\n >>> import matplotlib.pyplot as plt\n\n >>> x = np.linspace(-5, 5, num=150)\n >>> y = x + np.random.normal(size=x.size)\n >>> y[11:15] += 10 # add outliers\n >>> y[-5:] -= 7\n\n Compute the slope and intercept. For comparison, also compute the\n least-squares fit with `linregress`:\n\n >>> res = stats.siegelslopes(y, x)\n >>> lsq_res = stats.linregress(x, y)\n\n Plot the results. The Siegel regression line is shown in red. The green\n line shows the least-squares fit for comparison.\n\n >>> fig = plt.figure()\n >>> ax = fig.add_subplot(111)\n >>> ax.plot(x, y, 'b.')\n >>> ax.plot(x, res[1] + res[0] * x, 'r-')\n >>> ax.plot(x, lsq_res[1] + lsq_res[0] * x, 'g-')\n >>> plt.show()\n\n \"\"\"\n if method not in ['hierarchical', 'separate']:\n raise ValueError(\"method can only be 'hierarchical' or 'separate'\")\n y = np.asarray(y).ravel()\n if x is None:\n x = np.arange(len(y), dtype=float)\n else:\n x = np.asarray(x, dtype=float).ravel()\n if len(x) != len(y):\n raise ValueError(\"Incompatible lengths ! (%s<>%s)\" %\n (len(y), len(x)))\n\n deltax = x[:, np.newaxis] - x\n deltay = y[:, np.newaxis] - y\n slopes, intercepts = [], []\n\n for j in range(len(x)):\n id_nonzero = deltax[j, :] != 0\n slopes_j = deltay[j, id_nonzero] / deltax[j, id_nonzero]\n medslope_j = np.median(slopes_j)\n slopes.append(medslope_j)\n if method == 'separate':\n z = y*x[j] - y[j]*x\n medintercept_j = np.median(z[id_nonzero] / deltax[j, id_nonzero])\n intercepts.append(medintercept_j)\n\n medslope = np.median(np.asarray(slopes))\n if method == \"separate\":\n medinter = np.median(np.asarray(intercepts))\n else:\n medinter = np.median(y - medslope*x)\n\n return SiegelslopesResult(slope=medslope, intercept=medinter)\n",
"\"\"\"Tests for hyp2f1 for complex values.\n\nAuthor: Albert Steppi, with credit to Adam Kullberg (FormerPhycisist) for\nthe implementation of mp_hyp2f1 below, which modifies mpmath's hyp2f1 to\nreturn the same branch as scipy's on the standard branch cut.\n\"\"\"\n\nimport sys\nimport pytest\nimport numpy as np\nfrom typing import NamedTuple\nfrom numpy.testing import assert_allclose\n\nfrom scipy.special import hyp2f1\nfrom scipy.special._testutils import check_version, MissingModule\n\n\ntry:\n import mpmath\nexcept ImportError:\n mpmath = MissingModule(\"mpmath\")\n\n\ndef mp_hyp2f1(a, b, c, z):\n \"\"\"Return mpmath hyp2f1 calculated on same branch as scipy hyp2f1.\n\n For most values of a,b,c mpmath returns the x - 0j branch of hyp2f1 on the\n branch cut x=(1,inf) whereas scipy's hyp2f1 calculates the x + 0j branch.\n Thus, to generate the right comparison values on the branch cut, we\n evaluate mpmath.hyp2f1 at x + 1e-15*j.\n\n The exception to this occurs when c-a=-m in which case both mpmath and\n scipy calculate the x + 0j branch on the branch cut. When this happens\n mpmath.hyp2f1 will be evaluated at the original z point.\n \"\"\"\n on_branch_cut = z.real > 1.0 and abs(z.imag) < 1.0e-15\n cond1 = abs(c - a - round(c - a)) < 1.0e-15 and round(c - a) <= 0\n cond2 = abs(c - b - round(c - b)) < 1.0e-15 and round(c - b) <= 0\n # Make sure imaginary part is *exactly* zero\n if on_branch_cut:\n z = z.real + 0.0j\n if on_branch_cut and not (cond1 or cond2):\n z_mpmath = z.real + 1.0e-15j\n else:\n z_mpmath = z\n return complex(mpmath.hyp2f1(a, b, c, z_mpmath))\n\n\nclass Hyp2f1TestCase(NamedTuple):\n a: float\n b: float\n c: float\n z: complex\n expected: complex\n rtol: float\n\n\nclass TestHyp2f1:\n \"\"\"Tests for hyp2f1 for complex values.\n\n Expected values for test cases were computed using mpmath. See\n `scipy.special._precompute.hyp2f1_data`. The verbose style of specifying\n test cases is used for readability and to make it easier to mark individual\n cases as expected to fail. Expected failures are used to highlight cases\n where improvements are needed. See\n `scipy.special._precompute.hyp2f1_data.make_hyp2f1_test_cases` for a\n function to generate the boilerplate for the test cases.\n\n Assertions have been added to each test to ensure that the test cases match\n the situations that are intended. A final test `test_test_hyp2f1` checks\n that the expected values in the test cases actually match what is computed\n by mpmath. This test is marked slow even though it isn't particularly slow\n so that it won't run by default on continuous integration builds.\n \"\"\"\n @pytest.mark.parametrize(\n \"hyp2f1_test_case\",\n [\n pytest.param(\n Hyp2f1TestCase(\n a=0.5,\n b=0.2,\n c=-10,\n z=0.2 + 0.2j,\n expected=np.inf + 0j,\n rtol=0\n )\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=0.5,\n b=0.2,\n c=-10,\n z=0 + 0j,\n expected=1 + 0j,\n rtol=0\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=0.5,\n b=0,\n c=-10,\n z=0.2 + 0.2j,\n expected=1 + 0j,\n rtol=0\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=0.5,\n b=0,\n c=0,\n z=0.2 + 0.2j,\n expected=1 + 0j,\n rtol=0,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=0.5,\n b=0.2,\n c=0,\n z=0.2 + 0.2j,\n expected=np.inf + 0j,\n rtol=0,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=0.5,\n b=0.2,\n c=0,\n z=0 + 0j,\n expected=np.nan + 0j,\n rtol=0,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=0.5,\n b=-5,\n c=-10,\n z=0.2 + 0.2j,\n expected=(1.0495404166666666+0.05708208333333334j),\n rtol=1e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=0.5,\n b=-10,\n c=-10,\n z=0.2 + 0.2j,\n expected=(1.092966013125+0.13455014673750001j),\n rtol=1e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-10,\n b=-20,\n c=-10,\n z=0.2 + 0.2j,\n expected=(-0.07712512000000005+0.12752814080000005j),\n rtol=1e-13,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-1,\n b=3.2,\n c=-1,\n z=0.2 + 0.2j,\n expected=(1.6400000000000001+0.6400000000000001j),\n rtol=1e-13,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-2,\n b=1.2,\n c=-4,\n z=1 + 0j,\n expected=1.8200000000000001 + 0j,\n rtol=1e-15,\n ),\n ),\n ]\n )\n def test_c_non_positive_int(self, hyp2f1_test_case):\n a, b, c, z, expected, rtol = hyp2f1_test_case\n assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol)\n\n @pytest.mark.parametrize(\n \"hyp2f1_test_case\",\n [\n pytest.param(\n Hyp2f1TestCase(\n a=0.5,\n b=0.2,\n c=1.5,\n z=1 + 0j,\n expected=1.1496439092239847 + 0j,\n rtol=1e-15\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=12.3,\n b=8.0,\n c=20.31,\n z=1 + 0j,\n expected=69280986.75273195 + 0j,\n rtol=1e-15\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=290.2,\n b=321.5,\n c=700.1,\n z=1 + 0j,\n expected=1.3396562400934e117 + 0j,\n rtol=1e-12,\n ),\n ),\n # Note that here even mpmath produces different results for\n # results that should be equivalent.\n pytest.param(\n Hyp2f1TestCase(\n a=9.2,\n b=621.5,\n c=700.1,\n z=(1+0j),\n expected=(952726652.4158565+0j),\n rtol=5e-13,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=621.5,\n b=9.2,\n c=700.1,\n z=(1+0j),\n expected=(952726652.4160284+0j),\n rtol=5e-12,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-101.2,\n b=-400.4,\n c=-172.1,\n z=(1+0j),\n expected=(2.2253618341394838e+37+0j),\n rtol=1e-13,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-400.4,\n b=-101.2,\n c=-172.1,\n z=(1+0j),\n expected=(2.2253618341394838e+37+0j),\n rtol=5e-13,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=172.5,\n b=-201.3,\n c=151.2,\n z=(1+0j),\n expected=(7.072266653650905e-135+0j),\n rtol=5e-13,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-201.3,\n b=172.5,\n c=151.2,\n z=(1+0j),\n expected=(7.072266653650905e-135+0j),\n rtol=5e-13,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-102.1,\n b=-20.3,\n c=1.3,\n z=1 + 0j,\n expected=2.7899070752746906e22 + 0j,\n rtol=3e-14,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-202.6,\n b=60.3,\n c=1.5,\n z=1 + 0j,\n expected=-1.3113641413099326e-56 + 0j,\n rtol=1e-12,\n ),\n ),\n ],\n )\n def test_unital_argument(self, hyp2f1_test_case):\n \"\"\"Tests for case z = 1, c - a - b > 0.\n\n Expected answers computed using mpmath.\n \"\"\"\n a, b, c, z, expected, rtol = hyp2f1_test_case\n assert z == 1 and c - a - b > 0 # Tests the test\n assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol)\n\n @pytest.mark.parametrize(\n \"hyp2f1_test_case\",\n [\n pytest.param(\n Hyp2f1TestCase(\n a=0.5,\n b=0.2,\n c=1.3,\n z=-1 + 0j,\n expected=0.9428846409614143 + 0j,\n rtol=1e-15),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=12.3,\n b=8.0,\n c=5.300000000000001,\n z=-1 + 0j,\n expected=-4.845809986595704e-06 + 0j,\n rtol=1e-15\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=221.5,\n b=90.2,\n c=132.3,\n z=-1 + 0j,\n expected=2.0490488728377282e-42 + 0j,\n rtol=1e-7,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-102.1,\n b=-20.3,\n c=-80.8,\n z=-1 + 0j,\n expected=45143784.46783885 + 0j,\n rtol=1e-7,\n ),\n marks=pytest.mark.xfail(\n condition=sys.maxsize < 2**32,\n reason=\"Fails on 32 bit.\",\n )\n ),\n ],\n )\n def test_special_case_z_near_minus_1(self, hyp2f1_test_case):\n \"\"\"Tests for case z ~ -1, c ~ 1 + a - b\n\n Expected answers computed using mpmath.\n \"\"\"\n a, b, c, z, expected, rtol = hyp2f1_test_case\n assert abs(1 + a - b - c) < 1e-15 and abs(z + 1) < 1e-15\n assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol)\n\n @pytest.mark.parametrize(\n \"hyp2f1_test_case\",\n [\n pytest.param(\n Hyp2f1TestCase(\n a=-4,\n b=2.02764642551431,\n c=1.0561196186065624,\n z=(0.9473684210526314-0.10526315789473695j),\n expected=(0.0031961077109535375-0.0011313924606557173j),\n rtol=1e-12,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-8,\n b=-7.937789122896016,\n c=-15.964218273004214,\n z=(2-0.10526315789473695j),\n expected=(0.005543763196412503-0.0025948879065698306j),\n rtol=5e-13,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-8,\n b=8.095813935368371,\n c=4.0013768449590685,\n z=(0.9473684210526314-0.10526315789473695j),\n expected=(-0.0003054674127221263-9.261359291755414e-05j),\n rtol=1e-10,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-4,\n b=-3.956227226099288,\n c=-3.9316537064827854,\n z=(1.1578947368421053-0.3157894736842106j),\n expected=(-0.0020809502580892937-0.0041877333232365095j),\n rtol=5e-12,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=2.02764642551431,\n b=-4,\n c=2.050308316530781,\n z=(0.9473684210526314-0.10526315789473695j),\n expected=(0.0011282435590058734+0.0002027062303465851j),\n rtol=5e-13,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-7.937789122896016,\n b=-8,\n c=-15.964218273004214,\n z=(1.3684210526315788+0.10526315789473673j),\n expected=(-9.134907719238265e-05-0.00040219233987390723j),\n rtol=5e-12,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=4.080187217753502,\n b=-4,\n c=4.0013768449590685,\n z=(0.9473684210526314-0.10526315789473695j),\n expected=(-0.000519013062087489-0.0005855883076830948j),\n rtol=5e-12,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-10000,\n b=2.2,\n c=93459345.3,\n z=(2+2j),\n expected=(0.9995292071559088-0.00047047067522659253j),\n rtol=1e-12,\n ),\n ),\n ]\n )\n def test_a_b_negative_int(self, hyp2f1_test_case):\n a, b, c, z, expected, rtol = hyp2f1_test_case\n assert a == int(a) and a < 0 or b == int(b) and b < 0 # Tests the test\n assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol)\n\n @pytest.mark.parametrize(\n \"hyp2f1_test_case\",\n [\n pytest.param(\n Hyp2f1TestCase(\n a=-0.5,\n b=-0.9629749245209605,\n c=-15.5,\n z=(1.1578947368421053-1.1578947368421053j),\n expected=(0.9778506962676361+0.044083801141231616j),\n rtol=1e-12,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=8.5,\n b=-3.9316537064827854,\n c=1.5,\n z=(0.9473684210526314-0.10526315789473695j),\n expected=(4.0793167523167675-10.11694246310966j),\n rtol=6e-12,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=8.5,\n b=-0.9629749245209605,\n c=2.5,\n z=(1.1578947368421053-0.10526315789473695j),\n expected=(-2.9692999501916915+0.6394599899845594j),\n rtol=1e-11,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-0.5,\n b=-0.9629749245209605,\n c=-15.5,\n z=(1.5789473684210522-1.1578947368421053j),\n expected=(0.9493076367106102-0.04316852977183447j),\n rtol=1e-11,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-0.9220024191881196,\n b=-0.5,\n c=-15.5,\n z=(0.5263157894736841+0.10526315789473673j),\n expected=(0.9844377175631795-0.003120587561483841j),\n rtol=1e-10,\n ),\n ),\n ],\n )\n def test_a_b_neg_int_after_euler_hypergeometric_transformation(\n self, hyp2f1_test_case\n ):\n a, b, c, z, expected, rtol = hyp2f1_test_case\n assert ( # Tests the test\n (abs(c - a - int(c - a)) < 1e-15 and c - a < 0) or\n (abs(c - b - int(c - b)) < 1e-15 and c - b < 0)\n )\n assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol)\n\n @pytest.mark.parametrize(\n \"hyp2f1_test_case\",\n [\n pytest.param(\n Hyp2f1TestCase(\n a=-0.9220024191881196,\n b=-0.9629749245209605,\n c=-15.963511401609862,\n z=(0.10526315789473673-0.3157894736842106j),\n expected=(0.9941449585778349+0.01756335047931358j),\n rtol=1e-14,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=1.0272592605282642,\n b=-0.9629749245209605,\n c=-15.963511401609862,\n z=(0.5263157894736841+0.5263157894736841j),\n expected=(1.0388722293372104-0.09549450380041416j),\n rtol=5e-11,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=2.02764642551431,\n b=1.0561196186065624,\n c=-7.93846038215665,\n z=(0.10526315789473673+0.7368421052631575j),\n expected=(2.1948378809826434+24.934157235172222j),\n rtol=5e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=2.02764642551431,\n b=16.088264119063613,\n c=8.031683612216888,\n z=(0.3157894736842106-0.736842105263158j),\n expected=(-0.4075277891264672-0.06819344579666956j),\n rtol=2e-12,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=4.080187217753502,\n b=2.050308316530781,\n c=8.031683612216888,\n z=(0.7368421052631575-0.10526315789473695j),\n expected=(2.833535530740603-0.6925373701408158j),\n rtol=5e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=2.02764642551431,\n b=2.050308316530781,\n c=4.078873014294075,\n z=(0.10526315789473673-0.3157894736842106j),\n expected=(1.005347176329683-0.3580736009337313j),\n rtol=5e-16,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-0.9220024191881196,\n b=-0.9629749245209605,\n c=-15.963511401609862,\n z=(0.3157894736842106-0.5263157894736843j),\n expected=(0.9824353641135369+0.029271018868990268j),\n rtol=5e-13,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-0.9220024191881196,\n b=-0.9629749245209605,\n c=-159.63511401609862,\n z=(0.3157894736842106-0.5263157894736843j),\n expected=(0.9982436200365834+0.002927268199671111j),\n rtol=1e-7,\n ),\n marks=pytest.mark.xfail(reason=\"Poor convergence.\")\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=2.02764642551431,\n b=16.088264119063613,\n c=8.031683612216888,\n z=(0.5263157894736841-0.5263157894736843j),\n expected=(-0.6906825165778091+0.8176575137504892j),\n rtol=5e-13,\n ),\n ),\n ]\n )\n def test_region1(self, hyp2f1_test_case):\n \"\"\"|z| < 0.9 and real(z) >= 0.\"\"\"\n a, b, c, z, expected, rtol = hyp2f1_test_case\n assert abs(z) < 0.9 and z.real >= 0 # Tests the test\n assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol)\n\n @pytest.mark.parametrize(\n \"hyp2f1_test_case\",\n [\n pytest.param(\n Hyp2f1TestCase(\n a=2.02764642551431,\n b=1.0561196186065624,\n c=4.078873014294075,\n z=(-0.3157894736842106+0.7368421052631575j),\n expected=(0.7751915029081136+0.24068493258607315j),\n rtol=5e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=16.087593263474208,\n b=16.088264119063613,\n c=2.0397202577726152,\n z=(-0.9473684210526316-0.3157894736842106j),\n expected=(6.564549348474962e-07+1.6761570598334562e-06j),\n rtol=5e-09,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=1.0272592605282642,\n b=2.050308316530781,\n c=16.056809865262608,\n z=(-0.10526315789473695-0.10526315789473695j),\n expected=(0.9862043298997204-0.013293151372712681j),\n rtol=5e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=4.080187217753502,\n b=8.077282662161238,\n c=16.056809865262608,\n z=(-0.3157894736842106-0.736842105263158j),\n expected=(0.16163826638754716-0.41378530376373734j),\n rtol=5e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=2.02764642551431,\n b=2.050308316530781,\n c=-0.906685989801748,\n z=(-0.5263157894736843+0.3157894736842106j),\n expected=(-6.256871535165936+0.13824973858225484j),\n rtol=1e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=2.02764642551431,\n b=8.077282662161238,\n c=-3.9924618758357022,\n z=(-0.9473684210526316-0.3157894736842106j),\n expected=(75.54672526086316+50.56157041797548j),\n rtol=5e-12,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=16.087593263474208,\n b=8.077282662161238,\n c=-1.9631175993998025,\n z=(-0.5263157894736843+0.5263157894736841j),\n expected=(282.0602536306534-82.31597306936214j),\n rtol=5e-13,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=8.095813935368371,\n b=-3.9316537064827854,\n c=8.031683612216888,\n z=(-0.5263157894736843-0.10526315789473695j),\n expected=(5.179603735575851+1.4445374002099813j),\n rtol=5e-14,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=4.080187217753502,\n b=-7.949900487447654,\n c=1.0651378143226575,\n z=(-0.3157894736842106-0.9473684210526316j),\n expected=(2317.623517606141-269.51476321010324j),\n rtol=5e-13,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=16.087593263474208,\n b=-1.92872979730171,\n c=2.0397202577726152,\n z=(-0.736842105263158-0.3157894736842106j),\n expected=(29.179154096175836+22.126690357535043j),\n rtol=5e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=8.095813935368371,\n b=-3.9316537064827854,\n c=-15.963511401609862,\n z=(-0.736842105263158-0.10526315789473695j),\n expected=(0.20820247892032057-0.04763956711248794j),\n rtol=5e-14,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=1.0272592605282642,\n b=-15.964218273004214,\n c=-1.9631175993998025,\n z=(-0.3157894736842106-0.5263157894736843j),\n expected=(-157471.63920142158+991294.0587828817j),\n rtol=5e-14,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=8.095813935368371,\n b=-7.949900487447654,\n c=-7.93846038215665,\n z=(-0.10526315789473695-0.10526315789473695j),\n expected=(0.30765349653210194-0.2979706363594157j),\n rtol=1e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-3.956227226099288,\n b=1.0561196186065624,\n c=8.031683612216888,\n z=(-0.9473684210526316-0.10526315789473695j),\n expected=(1.6787607400597109+0.10056620134616838j),\n rtol=5e-14,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-7.937789122896016,\n b=16.088264119063613,\n c=4.078873014294075,\n z=(-0.5263157894736843-0.736842105263158j),\n expected=(7062.07842506049-12768.77955655703j),\n rtol=5e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-7.937789122896016,\n b=16.088264119063613,\n c=2.0397202577726152,\n z=(-0.3157894736842106+0.7368421052631575j),\n expected=(54749.216391029935-23078.144720887536j),\n rtol=1e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-3.956227226099288,\n b=1.0561196186065624,\n c=-0.906685989801748,\n z=(-0.10526315789473695-0.10526315789473695j),\n expected=(1.21521766411428-4.449385173946672j),\n rtol=5e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-15.980848054962111,\n b=4.0013768449590685,\n c=-1.9631175993998025,\n z=(-0.736842105263158+0.5263157894736841j),\n expected=(19234693144.196907+1617913967.7294445j),\n rtol=5e-14,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-1.9214641416286231,\n b=1.0561196186065624,\n c=-15.963511401609862,\n z=(-0.5263157894736843+0.3157894736842106j),\n expected=(0.9345201094534371+0.03745712558992195j),\n rtol=5e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-7.937789122896016,\n b=-0.9629749245209605,\n c=2.0397202577726152,\n z=(-0.10526315789473695+0.10526315789473673j),\n expected=(0.605732446296829+0.398171533680972j),\n rtol=5e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-1.9214641416286231,\n b=-15.964218273004214,\n c=2.0397202577726152,\n z=(-0.10526315789473695-0.5263157894736843j),\n expected=(-9.753761888305416-4.590126012666959j),\n rtol=5e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-3.956227226099288,\n b=-1.92872979730171,\n c=2.0397202577726152,\n z=(-0.10526315789473695+0.3157894736842106j),\n expected=(0.45587226291120714+1.0694545265819797j),\n rtol=5e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-0.9220024191881196,\n b=-7.949900487447654,\n c=-0.906685989801748,\n z=(-0.736842105263158+0.3157894736842106j),\n expected=(12.334808243233418-76.26089051819054j),\n rtol=5e-14,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-0.9220024191881196,\n b=-7.949900487447654,\n c=-15.963511401609862,\n z=(-0.5263157894736843+0.10526315789473673j),\n expected=(1.2396019687632678-0.047507973161146286j),\n rtol=1e-14,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-15.980848054962111,\n b=-0.9629749245209605,\n c=-0.906685989801748,\n z=(-0.3157894736842106-0.5263157894736843j),\n expected=(97.7889554372208-18.999754543400016j),\n rtol=5e-13,\n ),\n ),\n ]\n )\n def test_region2(self, hyp2f1_test_case):\n \"\"\"|z| < 1 and real(z) < 0.\"\"\"\n a, b, c, z, expected, rtol = hyp2f1_test_case\n assert abs(z) < 1 and z.real < 0 # Tests the test\n assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol)\n\n @pytest.mark.parametrize(\n \"hyp2f1_test_case\",\n [\n pytest.param(\n Hyp2f1TestCase(\n a=16.25,\n b=4.25,\n c=2.5,\n z=(0.4931034482758623-0.7965517241379311j),\n expected=(38.41207903409937-30.510151276075792j),\n rtol=5e-14,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=2.0,\n b=16.087593263474208,\n c=16.088264119063613,\n z=(0.5689655172413794-0.7965517241379311j),\n expected=(-0.6667857912761286-1.0206224321443573j),\n rtol=1e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=8.0,\n b=1.0272592605282642,\n c=-7.949900487447654,\n z=(0.4931034482758623-0.7965517241379311j),\n expected=(1679024.1647997478-2748129.775857212j),\n rtol=5e-14,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=4.080187217753502,\n b=16.0,\n c=-7.949900487447654,\n z=(0.4931034482758623-0.7965517241379311j),\n expected=(424747226301.16986-1245539049327.2856j),\n rtol=1e-14,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=2.02764642551431,\n b=-15.964218273004214,\n c=4.0,\n z=(0.4931034482758623-0.7965517241379311j),\n expected=(-0.0057826199201757595+0.026359861999025885j),\n rtol=5e-06,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=2.02764642551431,\n b=-0.9629749245209605,\n c=2.0397202577726152,\n z=(0.5689655172413794-0.7965517241379311j),\n expected=(0.4671901063492606+0.7769632229834897j),\n rtol=5e-14,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=2.0,\n b=-3.956227226099288,\n c=-7.949900487447654,\n z=(0.4931034482758623+0.7965517241379312j),\n expected=(0.9422283708145973+1.3476905754773343j),\n rtol=5e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=1.0,\n b=-15.980848054962111,\n c=-15.964218273004214,\n z=(0.4931034482758623-0.7965517241379311j),\n expected=(0.4168719497319604-0.9770953555235625j),\n rtol=5e-10,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-0.5,\n b=16.088264119063613,\n c=2.5,\n z=(0.5689655172413794+0.7965517241379312j),\n expected=(1.279096377550619-2.173827694297929j),\n rtol=5e-12,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-1.9214641416286231,\n b=4.0013768449590685,\n c=2.0397202577726152,\n z=(0.4931034482758623+0.7965517241379312j),\n expected=(-2.071520656161738-0.7846098268395909j),\n rtol=5e-14,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-0.9220024191881196,\n b=8.0,\n c=-0.9629749245209605,\n z=(0.5689655172413794-0.7965517241379311j),\n expected=(-7.740015495862889+3.386766435696699j),\n rtol=5e-12,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-1.9214641416286231,\n b=16.088264119063613,\n c=-7.93846038215665,\n z=(0.4931034482758623+0.7965517241379312j),\n expected=(-6318.553685853241-7133.416085202879j),\n rtol=1e-10,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-15.980848054962111,\n b=-3.9316537064827854,\n c=16.056809865262608,\n z=(0.5689655172413794+0.7965517241379312j),\n expected=(-0.8854577905547399+8.135089099967278j),\n rtol=5e-14,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-1.9214641416286231,\n b=-0.9629749245209605,\n c=4.078873014294075,\n z=(0.4931034482758623+0.7965517241379312j),\n expected=(1.224291301521487+0.36014711766402485j),\n rtol=1e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-15.75,\n b=-0.75,\n c=-1.5,\n z=(0.4931034482758623+0.7965517241379312j),\n expected=(-1.5765685855028473-3.9399766961046323j),\n rtol=1e-3,\n ),\n marks=pytest.mark.xfail(\n reason=\"Unhandled parameters.\"\n )\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-15.980848054962111,\n b=-1.92872979730171,\n c=-7.93846038215665,\n z=(0.5689655172413794-0.7965517241379311j),\n expected=(56.794588688231194+4.556286783533971j),\n rtol=5e-14,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=4.5,\n b=4.5,\n c=2.050308316530781,\n z=(0.5689655172413794+0.7965517241379312j),\n expected=(-4.251456563455306+6.737837111569671j),\n rtol=5e-14,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=4.5,\n b=8.5,\n c=-1.92872979730171,\n z=(0.4931034482758623-0.7965517241379311j),\n expected=(2177143.9156599627-3313617.2748088865j),\n rtol=5e-14,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=2.5,\n b=-1.5,\n c=4.0013768449590685,\n z=(0.4931034482758623-0.7965517241379311j),\n expected=(0.45563554481603946+0.6212000158060831j),\n rtol=5e-14,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=8.5,\n b=-7.5,\n c=-15.964218273004214,\n z=(0.4931034482758623+0.7965517241379312j),\n expected=(61.03201617828073-37.185626416756214j),\n rtol=5e-14,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-15.5,\n b=16.5,\n c=4.0013768449590685,\n z=(0.4931034482758623+0.7965517241379312j),\n expected=(-33143.425963520735+20790.608514722644j),\n rtol=1e-14,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-0.5,\n b=4.5,\n c=-0.9629749245209605,\n z=(0.5689655172413794+0.7965517241379312j),\n expected=(30.778600270824423-26.65160354466787j),\n rtol=5e-13,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-0.5,\n b=-3.5,\n c=16.088264119063613,\n z=(0.5689655172413794-0.7965517241379311j),\n expected=(1.0629792615560487-0.08308454486044772j),\n rtol=1e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-3.5,\n b=-7.5,\n c=-0.9629749245209605,\n z=(0.4931034482758623-0.7965517241379311j),\n expected=(17431.571802591767+3553.7129767034507j),\n rtol=5e-14,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=2.25,\n b=8.25,\n c=16.5,\n z=(0.11379310344827598+0.9482758620689657j),\n expected=(0.4468600750211926+0.7313214934036885j),\n rtol=1e-3,\n ),\n marks=pytest.mark.xfail(\n reason=\"Unhandled parameters.\"\n )\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=8.25,\n b=16.25,\n c=4.5,\n z=(0.3413793103448277+0.8724137931034486j),\n expected=(-3.905704438293991+3.693347860329299j),\n rtol=5e-14,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=4.25,\n b=4.25,\n c=-0.5,\n z=(0.11379310344827598-0.9482758620689655j),\n expected=(-40.31777941834244-89.89852492432011j),\n rtol=5e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=1.0272592605282642,\n b=8.0,\n c=-15.964218273004214,\n z=(0.11379310344827598-0.9482758620689655j),\n expected=(52584.347773055284-109197.86244309516j),\n rtol=5e-14,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=8.095813935368371,\n b=-15.964218273004214,\n c=16.056809865262608,\n z=(0.03793103448275881+0.9482758620689657j),\n expected=(-1.187733570412592-1.5147865053584582j),\n rtol=5e-10,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=4.080187217753502,\n b=-3.9316537064827854,\n c=1.0651378143226575,\n z=(0.26551724137931054+0.9482758620689657j),\n expected=(13.077494677898947+35.071599628224966j),\n rtol=5e-13,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=4.080187217753502,\n b=-3.5,\n c=-3.5,\n z=(0.26551724137931054+0.8724137931034486j),\n expected=(-0.5359656237994614-0.2344483936591811j),\n rtol=1e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=4.25,\n b=-3.75,\n c=-1.5,\n z=(0.26551724137931054+0.9482758620689657j),\n expected=(1204.8114871663133+64.41022826840198j),\n rtol=5e-13,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-1.9214641416286231,\n b=16.0,\n c=4.0013768449590685,\n z=(0.03793103448275881-0.9482758620689655j),\n expected=(-9.85268872413994+7.011107558429154j),\n rtol=5e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-7.937789122896016,\n b=16.0,\n c=4.0013768449590685,\n z=(0.3413793103448277-0.8724137931034484j),\n expected=(528.5522951158454-1412.21630264791j),\n rtol=1e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-15.5,\n b=1.0561196186065624,\n c=-7.5,\n z=(0.4172413793103451+0.8724137931034486j),\n expected=(133306.45260685298+256510.7045225382j),\n rtol=1e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-7.937789122896016,\n b=8.077282662161238,\n c=-15.963511401609862,\n z=(0.3413793103448277-0.8724137931034484j),\n expected=(-0.998555715276967+2.774198742229889j),\n rtol=5e-11,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-7.75,\n b=-0.75,\n c=1.5,\n z=(0.11379310344827598-0.9482758620689655j),\n expected=(2.072445019723025-2.9793504811373515j),\n rtol=5e-14,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-15.5,\n b=-1.92872979730171,\n c=1.5,\n z=(0.11379310344827598-0.9482758620689655j),\n expected=(-41.87581944176649-32.52980303527139j),\n rtol=5e-13,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-3.75,\n b=-15.75,\n c=-0.5,\n z=(0.11379310344827598-0.9482758620689655j),\n expected=(-3729.6214864209774-30627.510509112635j),\n rtol=5e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-3.956227226099288,\n b=-15.964218273004214,\n c=-0.906685989801748,\n z=(0.03793103448275881+0.9482758620689657j),\n expected=(-131615.07820609974+145596.13384245415j),\n rtol=5e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=1.5,\n b=16.5,\n c=16.088264119063613,\n z=(0.26551724137931054+0.8724137931034486j),\n expected=(0.18981844071070744+0.7855036242583742j),\n rtol=1e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=16.5,\n b=8.5,\n c=-3.9316537064827854,\n z=(0.11379310344827598-0.9482758620689655j),\n expected=(110224529.2376068+128287212.04290268j),\n rtol=5e-13,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=2.5,\n b=-7.5,\n c=4.0013768449590685,\n z=(0.3413793103448277-0.8724137931034484j),\n expected=(0.2722302180888523-0.21790187837266162j),\n rtol=1e-12,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=8.5,\n b=-7.5,\n c=-15.964218273004214,\n z=(0.11379310344827598-0.9482758620689655j),\n expected=(-2.8252338010989035+2.430661949756161j),\n rtol=5e-14,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-3.5,\n b=16.5,\n c=4.0013768449590685,\n z=(0.03793103448275881+0.9482758620689657j),\n expected=(-20.604894257647945+74.5109432558078j),\n rtol=5e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-7.5,\n b=8.5,\n c=-0.9629749245209605,\n z=(0.3413793103448277+0.8724137931034486j),\n expected=(-2764422.521269463-3965966.9965808876j),\n rtol=1e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-1.5,\n b=-0.5,\n c=1.0561196186065624,\n z=(0.26551724137931054+0.9482758620689657j),\n expected=(1.2262338560994905+0.6545051266925549j),\n rtol=1e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-0.5,\n b=-15.5,\n c=-7.949900487447654,\n z=(0.4172413793103451-0.8724137931034484j),\n expected=(-2258.1590330318213+8860.193389158803j),\n rtol=1e-10,\n ),\n ),\n ]\n )\n def test_region4(self, hyp2f1_test_case):\n \"\"\"0.9 <= |z| <= 1 and |1 - z| >= 1.\n\n This region is unhandled by of the standard transformations and\n needs special care.\n \"\"\"\n a, b, c, z, expected, rtol = hyp2f1_test_case\n assert 0.9 <= abs(z) <= 1 and abs(1 - z) >= 0.9 # Tests the test\n assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol)\n\n @pytest.mark.parametrize(\n \"hyp2f1_test_case\",\n [\n pytest.param(\n Hyp2f1TestCase(\n a=4.5,\n b=16.088264119063613,\n c=8.5,\n z=(0.6448275862068968+0.8724137931034486j),\n expected=(0.018601324701770394-0.07618420586062377j),\n rtol=5e-08,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=8.25,\n b=4.25,\n c=4.5,\n z=(0.6448275862068968-0.8724137931034484j),\n expected=(-1.391549471425551-0.118036604903893j),\n rtol=5e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=2.02764642551431,\n b=2.050308316530781,\n c=-1.9631175993998025,\n z=(0.6448275862068968+0.8724137931034486j),\n expected=(-2309.178768155151-1932.7247727595172j),\n rtol=5e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=16.087593263474208,\n b=1.0,\n c=-15.964218273004214,\n z=(0.6448275862068968+0.8724137931034486j),\n expected=(85592537010.05054-8061416766688.324j),\n rtol=1e-14,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=8.095813935368371,\n b=-0.5,\n c=1.5,\n z=(0.6448275862068968+0.8724137931034486j),\n expected=(1.2334498208515172-2.1639498536219732j),\n rtol=5e-11,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=16.087593263474208,\n b=-15.964218273004214,\n c=4.0,\n z=(0.6448275862068968+0.8724137931034486j),\n expected=(102266.35398605966-44976.97828737755j),\n rtol=1e-3,\n ),\n marks=pytest.mark.xfail(\n reason=\"Unhandled parameters.\"\n )\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=4.0,\n b=-3.956227226099288,\n c=-15.964218273004214,\n z=(0.6448275862068968-0.8724137931034484j),\n expected=(-2.9590030930007236-4.190770764773225j),\n rtol=5e-13,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=4.080187217753502,\n b=-15.5,\n c=-7.5,\n z=(0.5689655172413794-0.8724137931034484j),\n expected=(-112554838.92074208+174941462.9202412j),\n rtol=5e-05,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-15.980848054962111,\n b=2.050308316530781,\n c=1.0,\n z=(0.6448275862068968-0.8724137931034484j),\n expected=(3.7519882374080145+7.360753798667486j),\n rtol=5e-13,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-7.937789122896016,\n b=2.050308316530781,\n c=4.0,\n z=(0.6448275862068968-0.8724137931034484j),\n expected=(0.000181132943964693+0.07742903103815582j),\n rtol=5e-14,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-7.937789122896016,\n b=4.0013768449590685,\n c=-1.9631175993998025,\n z=(0.5689655172413794+0.8724137931034486j),\n expected=(386338.760913596-386166.51762171905j),\n rtol=5e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-15.980848054962111,\n b=8.0,\n c=-1.92872979730171,\n z=(0.6448275862068968+0.8724137931034486j),\n expected=(1348667126.3444858-2375132427.158893j),\n rtol=5e-14,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-3.5,\n b=-0.9629749245209605,\n c=4.5,\n z=(0.5689655172413794+0.8724137931034486j),\n expected=(1.428353429538678+0.6472718120804372j),\n rtol=5e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-7.937789122896016,\n b=-0.9629749245209605,\n c=2.0397202577726152,\n z=(0.5689655172413794-0.8724137931034484j),\n expected=(3.1439267526119643-3.145305240375117j),\n rtol=5e-14,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-1.9214641416286231,\n b=-15.964218273004214,\n c=-7.93846038215665,\n z=(0.6448275862068968-0.8724137931034484j),\n expected=(75.27467675681773+144.0946946292215j),\n rtol=1e-07,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-3.75,\n b=-7.75,\n c=-7.5,\n z=(0.5689655172413794+0.8724137931034486j),\n expected=(-0.3699450626264222+0.8732812475910993j),\n rtol=1e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=1.5,\n b=16.5,\n c=1.0561196186065624,\n z=(0.5689655172413794-0.8724137931034484j),\n expected=(5.5361025821300665-2.4709693474656285j),\n rtol=5e-09,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=1.5,\n b=8.5,\n c=-3.9316537064827854,\n z=(0.6448275862068968-0.8724137931034484j),\n expected=(-782805.6699207705-537192.581278909j),\n rtol=5e-14,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=2.5,\n b=-15.5,\n c=1.0561196186065624,\n z=(0.6448275862068968+0.8724137931034486j),\n expected=(12.345113400639693-14.993248992902007j),\n rtol=0.0005,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=1.5,\n b=-0.5,\n c=-15.964218273004214,\n z=(0.6448275862068968+0.8724137931034486j),\n expected=(23.698109392667842+97.15002033534108j),\n rtol=5e-14,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-7.5,\n b=16.5,\n c=4.0013768449590685,\n z=(0.6448275862068968-0.8724137931034484j),\n expected=(1115.2978631811834+915.9212658718577j),\n rtol=5e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-15.5,\n b=16.5,\n c=-0.9629749245209605,\n z=(0.6448275862068968+0.8724137931034486j),\n expected=(642077722221.6489+535274495398.21027j),\n rtol=5e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-7.5,\n b=-3.5,\n c=4.0013768449590685,\n z=(0.5689655172413794+0.8724137931034486j),\n expected=(-5.689219222945697+16.877463062787143j),\n rtol=5e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-15.5,\n b=-1.5,\n c=-0.9629749245209605,\n z=(0.5689655172413794-0.8724137931034484j),\n expected=(-44.32070290703576+1026.9127058617403j),\n rtol=5e-14,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=16.25,\n b=2.25,\n c=4.5,\n z=(0.11379310344827598-1.024137931034483j),\n expected=(-0.021965227124574663+0.009908300237809064j),\n rtol=1e-3,\n ),\n marks=pytest.mark.xfail(\n reason=\"Unhandled parameters.\"\n )\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=2.02764642551431,\n b=1.5,\n c=16.5,\n z=(0.26551724137931054+1.024137931034483j),\n expected=(1.0046072901244183+0.19945500134119992j),\n rtol=5e-14,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=16.087593263474208,\n b=1.0,\n c=-3.9316537064827854,\n z=(0.3413793103448277+0.9482758620689657j),\n expected=(21022.30133421465+49175.98317370489j),\n rtol=5e-13,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=4.080187217753502,\n b=16.088264119063613,\n c=-1.9631175993998025,\n z=(0.4172413793103451-0.9482758620689655j),\n expected=(-7024239.358547302+2481375.02681063j),\n rtol=5e-14,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=16.25,\n b=-15.75,\n c=1.5,\n z=(0.18965517241379315+1.024137931034483j),\n expected=(92371704.94848-403546832.548352j),\n rtol=5e-06,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=8.5,\n b=-7.949900487447654,\n c=8.5,\n z=(0.26551724137931054-1.024137931034483j),\n expected=(1.9335109845308265+5.986542524829654j),\n rtol=5e-10,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=8.095813935368371,\n b=-1.92872979730171,\n c=-7.93846038215665,\n z=(0.4931034482758623+0.8724137931034486j),\n expected=(-122.52639696039328-59.72428067512221j),\n rtol=5e-14,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=16.25,\n b=-1.75,\n c=-1.5,\n z=(0.4931034482758623+0.9482758620689657j),\n expected=(-90.40642053579428+50.50649180047921j),\n rtol=5e-08,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-3.5,\n b=8.077282662161238,\n c=16.5,\n z=(0.4931034482758623+0.9482758620689657j),\n expected=(-0.2155745818150323-0.564628986876639j),\n rtol=5e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-0.9220024191881196,\n b=1.0561196186065624,\n c=8.031683612216888,\n z=(0.4172413793103451-0.9482758620689655j),\n expected=(0.9503140488280465+0.11574960074292677j),\n rtol=5e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-0.75,\n b=2.25,\n c=-15.5,\n z=(0.4172413793103451+0.9482758620689657j),\n expected=(0.9285862488442175+0.8203699266719692j),\n rtol=5e-13,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-7.75,\n b=4.25,\n c=-15.5,\n z=(0.3413793103448277-0.9482758620689655j),\n expected=(-1.0509834850116921-1.1145522325486075j),\n rtol=1e-14,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-7.937789122896016,\n b=-0.9629749245209605,\n c=2.0397202577726152,\n z=(0.4931034482758623-0.9482758620689655j),\n expected=(2.88119116536769-3.4249933450696806j),\n rtol=5e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-15.5,\n b=-15.964218273004214,\n c=16.5,\n z=(0.18965517241379315+1.024137931034483j),\n expected=(199.65868451496038+347.79384207302877j),\n rtol=1e-13,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-15.75,\n b=-15.75,\n c=-3.5,\n z=(0.4931034482758623-0.8724137931034484j),\n expected=(-208138312553.07013+58631611809.026955j),\n rtol=5e-14,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-7.937789122896016,\n b=-15.5,\n c=-7.5,\n z=(0.3413793103448277+0.9482758620689657j),\n expected=(-23032.90519856288-18256.94050457296j),\n rtol=5e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=4.5,\n b=1.5,\n c=1.0561196186065624,\n z=(0.4931034482758623-0.8724137931034484j),\n expected=(1.507342459587056+1.2332023580148403j),\n rtol=1e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=2.5,\n b=4.5,\n c=-3.9316537064827854,\n z=(0.4172413793103451+0.9482758620689657j),\n expected=(7044.766127108853-40210.365567285575j),\n rtol=5e-14,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=1.5,\n b=-1.5,\n c=1.0561196186065624,\n z=(0.03793103448275881+1.024137931034483j),\n expected=(0.2725347741628333-2.247314875514784j),\n rtol=1e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=4.5,\n b=-1.5,\n c=-7.949900487447654,\n z=(0.26551724137931054+1.024137931034483j),\n expected=(-11.250200011017546+12.597393659160472j),\n rtol=5e-14,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-7.5,\n b=8.5,\n c=16.088264119063613,\n z=(0.26551724137931054+1.024137931034483j),\n expected=(-0.18515160890991517+0.7959014164484782j),\n rtol=1e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-7.5,\n b=16.5,\n c=-3.9316537064827854,\n z=(0.3413793103448277-1.024137931034483j),\n expected=(998246378.8556538+1112032928.103645j),\n rtol=5e-14,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-1.5,\n b=-3.5,\n c=2.050308316530781,\n z=(0.03793103448275881+1.024137931034483j),\n expected=(0.5527670397711952+2.697662715303637j),\n rtol=1e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-15.5,\n b=-1.5,\n c=-0.9629749245209605,\n z=(0.4931034482758623-0.8724137931034484j),\n expected=(55.396931662136886+968.467463806326j),\n rtol=5e-14,\n ),\n ),\n ]\n )\n def test_region5(self, hyp2f1_test_case):\n \"\"\"1 < |z| < 1.1 and |1 - z| >= 0.9 and real(z) >= 0\"\"\"\n a, b, c, z, expected, rtol = hyp2f1_test_case\n assert 1 < abs(z) < 1.1 and abs(1 - z) >= 0.9 and z.real >= 0\n assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol)\n\n @pytest.mark.parametrize(\n \"hyp2f1_test_case\",\n [\n pytest.param(\n Hyp2f1TestCase(\n a=8.095813935368371,\n b=4.0013768449590685,\n c=4.078873014294075,\n z=(-0.9473684210526316+0.5263157894736841j),\n expected=(-0.0018093573941378783+0.003481887377423739j),\n rtol=5e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=16.087593263474208,\n b=2.050308316530781,\n c=1.0651378143226575,\n z=(-0.736842105263158-0.736842105263158j),\n expected=(-0.00023401243818780545-1.7983496305603562e-05j),\n rtol=1e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=1.0272592605282642,\n b=8.077282662161238,\n c=4.078873014294075,\n z=(-0.5263157894736843-0.9473684210526316j),\n expected=(0.22359773002226846-0.24092487123993353j),\n rtol=1e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=1.0272592605282642,\n b=2.050308316530781,\n c=-15.963511401609862,\n z=(-0.9473684210526316-0.5263157894736843j),\n expected=(1.191573745740011+0.14347394589721466j),\n rtol=5e-14,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=4.080187217753502,\n b=4.0013768449590685,\n c=-15.963511401609862,\n z=(-0.9473684210526316-0.5263157894736843j),\n expected=(31.822620756901784-66.09094396747611j),\n rtol=5e-14,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=4.080187217753502,\n b=8.077282662161238,\n c=-7.93846038215665,\n z=(-0.9473684210526316+0.5263157894736841j),\n expected=(207.16750179245952+34.80478274924269j),\n rtol=5e-12,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=8.095813935368371,\n b=-7.949900487447654,\n c=8.031683612216888,\n z=(-0.736842105263158+0.7368421052631575j),\n expected=(-159.62429364277145+9.154224290644898j),\n rtol=5e-14,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=1.0272592605282642,\n b=-1.92872979730171,\n c=16.056809865262608,\n z=(-0.9473684210526316+0.5263157894736841j),\n expected=(1.121122351247184-0.07170260470126685j),\n rtol=5e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=16.087593263474208,\n b=-0.9629749245209605,\n c=16.056809865262608,\n z=(-0.9473684210526316+0.5263157894736841j),\n expected=(1.9040596681316053-0.4951799449960107j),\n rtol=5e-14,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=1.0272592605282642,\n b=-1.92872979730171,\n c=-0.906685989801748,\n z=(-0.9473684210526316-0.5263157894736843j),\n expected=(-14.496623497780739-21.897524523299875j),\n rtol=5e-14,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=4.080187217753502,\n b=-3.9316537064827854,\n c=-3.9924618758357022,\n z=(-0.5263157894736843-0.9473684210526316j),\n expected=(36.33473466026878+253.88728442029577j),\n rtol=5e-14,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=1.0272592605282642,\n b=-15.964218273004214,\n c=-0.906685989801748,\n z=(-0.9473684210526316+0.5263157894736841j),\n expected=(1505052.5653144997-50820766.81043443j),\n rtol=1e-14,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-3.956227226099288,\n b=4.0013768449590685,\n c=1.0651378143226575,\n z=(-0.5263157894736843+0.9473684210526314j),\n expected=(-127.79407519260877-28.69899444941112j),\n rtol=5e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-1.9214641416286231,\n b=8.077282662161238,\n c=16.056809865262608,\n z=(-0.9473684210526316-0.5263157894736843j),\n expected=(2.0623331933754976+0.741234463565458j),\n rtol=5e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-3.956227226099288,\n b=8.077282662161238,\n c=2.0397202577726152,\n z=(-0.9473684210526316+0.5263157894736841j),\n expected=(30.729193458862525-292.5700835046965j),\n rtol=1e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-1.9214641416286231,\n b=1.0561196186065624,\n c=-1.9631175993998025,\n z=(-0.5263157894736843-0.9473684210526316j),\n expected=(1.1285917906203495-0.735264575450189j),\n rtol=5e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-0.9220024191881196,\n b=1.0561196186065624,\n c=-3.9924618758357022,\n z=(-0.736842105263158+0.7368421052631575j),\n expected=(0.6356474446678052-0.02429663008952248j),\n rtol=5e-14,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-1.9214641416286231,\n b=16.088264119063613,\n c=-7.93846038215665,\n z=(-0.736842105263158+0.7368421052631575j),\n expected=(0.4718880510273174+0.655083067736377j),\n rtol=1e-11,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-7.937789122896016,\n b=-3.9316537064827854,\n c=16.056809865262608,\n z=(-0.9473684210526316+0.5263157894736841j),\n expected=(-0.14681550942352714+0.16092206364265146j),\n rtol=5e-11,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-0.9220024191881196,\n b=-15.964218273004214,\n c=1.0651378143226575,\n z=(-0.5263157894736843+0.9473684210526314j),\n expected=(-6.436835190526225+22.883156700606182j),\n rtol=5e-14,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-0.9220024191881196,\n b=-7.949900487447654,\n c=4.078873014294075,\n z=(-0.9473684210526316-0.5263157894736843j),\n expected=(-0.7505682955068583-1.1026583264249945j),\n rtol=1e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-3.956227226099288,\n b=-3.9316537064827854,\n c=-7.93846038215665,\n z=(-0.9473684210526316-0.5263157894736843j),\n expected=(3.6247814989198166+2.596041360148318j),\n rtol=5e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-3.956227226099288,\n b=-15.964218273004214,\n c=-1.9631175993998025,\n z=(-0.5263157894736843-0.9473684210526316j),\n expected=(-59537.65287927933-669074.4342539902j),\n rtol=5e-15,\n ),\n ),\n pytest.param(\n Hyp2f1TestCase(\n a=-3.956227226099288,\n b=-15.964218273004214,\n c=-1.9631175993998025,\n z=(-0.9473684210526316-0.5263157894736843j),\n expected=(-433084.9970266166+431088.393918521j),\n rtol=5e-14,\n ),\n ),\n ]\n )\n def test_region6(self, hyp2f1_test_case):\n \"\"\"|z| > 1 but not in region 5.\"\"\"\n a, b, c, z, expected, rtol = hyp2f1_test_case\n assert (\n abs(z) > 1 and\n not (1 < abs(z) < 1.1 and abs(1 - z) >= 0.9 and z.real >= 0)\n )\n assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol)\n\n @pytest.mark.slow\n @check_version(mpmath, \"1.0.0\")\n def test_test_hyp2f1(self):\n \"\"\"Test that expected values match what is computed by mpmath.\n\n This gathers the parameters for the test cases out of the pytest marks.\n The parameters are a, b, c, z, expected, rtol, where expected should\n be the value of hyp2f1(a, b, c, z) computed with mpmath. The test\n recomputes hyp2f1(a, b, c, z) using mpmath and verifies that expected\n actually is the correct value. This allows the data for the tests to\n live within the test code instead of an external datafile, while\n avoiding having to compute the results with mpmath during the test,\n except for when slow tests are being run.\n \"\"\"\n test_methods = [\n test_method for test_method in dir(self)\n if test_method.startswith('test') and\n # Filter properties and attributes (futureproofing).\n callable(getattr(self, test_method)) and\n # Filter out this test\n test_method != 'test_test_hyp2f1'\n ]\n for test_method in test_methods:\n params = self._get_test_parameters(getattr(self, test_method))\n for a, b, c, z, expected, _ in params:\n assert_allclose(mp_hyp2f1(a, b, c, z), expected, rtol=2.25e-16)\n\n def _get_test_parameters(self, test_method):\n \"\"\"Get pytest.mark parameters for a test in this class.\"\"\"\n return [\n case.values[0] for mark in test_method.pytestmark\n if mark.name == 'parametrize'\n for case in mark.args[1]\n ]\n",
"\"\"\"\nFunctions for identifying peaks in signals.\n\"\"\"\nimport math\nimport numpy as np\n\nfrom scipy.signal._wavelets import cwt, ricker\nfrom scipy.stats import scoreatpercentile\n\nfrom ._peak_finding_utils import (\n _local_maxima_1d,\n _select_by_peak_distance,\n _peak_prominences,\n _peak_widths\n)\n\n\n__all__ = ['argrelmin', 'argrelmax', 'argrelextrema', 'peak_prominences',\n 'peak_widths', 'find_peaks', 'find_peaks_cwt']\n\n\ndef _boolrelextrema(data, comparator, axis=0, order=1, mode='clip'):\n \"\"\"\n Calculate the relative extrema of `data`.\n\n Relative extrema are calculated by finding locations where\n ``comparator(data[n], data[n+1:n+order+1])`` is True.\n\n Parameters\n ----------\n data : ndarray\n Array in which to find the relative extrema.\n comparator : callable\n Function to use to compare two data points.\n Should take two arrays as arguments.\n axis : int, optional\n Axis over which to select from `data`. Default is 0.\n order : int, optional\n How many points on each side to use for the comparison\n to consider ``comparator(n,n+x)`` to be True.\n mode : str, optional\n How the edges of the vector are treated. 'wrap' (wrap around) or\n 'clip' (treat overflow as the same as the last (or first) element).\n Default 'clip'. See numpy.take.\n\n Returns\n -------\n extrema : ndarray\n Boolean array of the same shape as `data` that is True at an extrema,\n False otherwise.\n\n See also\n --------\n argrelmax, argrelmin\n\n Examples\n --------\n >>> testdata = np.array([1,2,3,2,1])\n >>> _boolrelextrema(testdata, np.greater, axis=0)\n array([False, False, True, False, False], dtype=bool)\n\n \"\"\"\n if((int(order) != order) or (order < 1)):\n raise ValueError('Order must be an int >= 1')\n\n datalen = data.shape[axis]\n locs = np.arange(0, datalen)\n\n results = np.ones(data.shape, dtype=bool)\n main = data.take(locs, axis=axis, mode=mode)\n for shift in range(1, order + 1):\n plus = data.take(locs + shift, axis=axis, mode=mode)\n minus = data.take(locs - shift, axis=axis, mode=mode)\n results &= comparator(main, plus)\n results &= comparator(main, minus)\n if(~results.any()):\n return results\n return results\n\n\ndef argrelmin(data, axis=0, order=1, mode='clip'):\n \"\"\"\n Calculate the relative minima of `data`.\n\n Parameters\n ----------\n data : ndarray\n Array in which to find the relative minima.\n axis : int, optional\n Axis over which to select from `data`. Default is 0.\n order : int, optional\n How many points on each side to use for the comparison\n to consider ``comparator(n, n+x)`` to be True.\n mode : str, optional\n How the edges of the vector are treated.\n Available options are 'wrap' (wrap around) or 'clip' (treat overflow\n as the same as the last (or first) element).\n Default 'clip'. See numpy.take.\n\n Returns\n -------\n extrema : tuple of ndarrays\n Indices of the minima in arrays of integers. ``extrema[k]`` is\n the array of indices of axis `k` of `data`. Note that the\n return value is a tuple even when `data` is 1-D.\n\n See Also\n --------\n argrelextrema, argrelmax, find_peaks\n\n Notes\n -----\n This function uses `argrelextrema` with np.less as comparator. Therefore, it\n requires a strict inequality on both sides of a value to consider it a\n minimum. This means flat minima (more than one sample wide) are not detected.\n In case of 1-D `data` `find_peaks` can be used to detect all\n local minima, including flat ones, by calling it with negated `data`.\n\n .. versionadded:: 0.11.0\n\n Examples\n --------\n >>> from scipy.signal import argrelmin\n >>> x = np.array([2, 1, 2, 3, 2, 0, 1, 0])\n >>> argrelmin(x)\n (array([1, 5]),)\n >>> y = np.array([[1, 2, 1, 2],\n ... [2, 2, 0, 0],\n ... [5, 3, 4, 4]])\n ...\n >>> argrelmin(y, axis=1)\n (array([0, 2]), array([2, 1]))\n\n \"\"\"\n return argrelextrema(data, np.less, axis, order, mode)\n\n\ndef argrelmax(data, axis=0, order=1, mode='clip'):\n \"\"\"\n Calculate the relative maxima of `data`.\n\n Parameters\n ----------\n data : ndarray\n Array in which to find the relative maxima.\n axis : int, optional\n Axis over which to select from `data`. Default is 0.\n order : int, optional\n How many points on each side to use for the comparison\n to consider ``comparator(n, n+x)`` to be True.\n mode : str, optional\n How the edges of the vector are treated.\n Available options are 'wrap' (wrap around) or 'clip' (treat overflow\n as the same as the last (or first) element).\n Default 'clip'. See `numpy.take`.\n\n Returns\n -------\n extrema : tuple of ndarrays\n Indices of the maxima in arrays of integers. ``extrema[k]`` is\n the array of indices of axis `k` of `data`. Note that the\n return value is a tuple even when `data` is 1-D.\n\n See Also\n --------\n argrelextrema, argrelmin, find_peaks\n\n Notes\n -----\n This function uses `argrelextrema` with np.greater as comparator. Therefore,\n it requires a strict inequality on both sides of a value to consider it a\n maximum. This means flat maxima (more than one sample wide) are not detected.\n In case of 1-D `data` `find_peaks` can be used to detect all\n local maxima, including flat ones.\n\n .. versionadded:: 0.11.0\n\n Examples\n --------\n >>> from scipy.signal import argrelmax\n >>> x = np.array([2, 1, 2, 3, 2, 0, 1, 0])\n >>> argrelmax(x)\n (array([3, 6]),)\n >>> y = np.array([[1, 2, 1, 2],\n ... [2, 2, 0, 0],\n ... [5, 3, 4, 4]])\n ...\n >>> argrelmax(y, axis=1)\n (array([0]), array([1]))\n \"\"\"\n return argrelextrema(data, np.greater, axis, order, mode)\n\n\ndef argrelextrema(data, comparator, axis=0, order=1, mode='clip'):\n \"\"\"\n Calculate the relative extrema of `data`.\n\n Parameters\n ----------\n data : ndarray\n Array in which to find the relative extrema.\n comparator : callable\n Function to use to compare two data points.\n Should take two arrays as arguments.\n axis : int, optional\n Axis over which to select from `data`. Default is 0.\n order : int, optional\n How many points on each side to use for the comparison\n to consider ``comparator(n, n+x)`` to be True.\n mode : str, optional\n How the edges of the vector are treated. 'wrap' (wrap around) or\n 'clip' (treat overflow as the same as the last (or first) element).\n Default is 'clip'. See `numpy.take`.\n\n Returns\n -------\n extrema : tuple of ndarrays\n Indices of the maxima in arrays of integers. ``extrema[k]`` is\n the array of indices of axis `k` of `data`. Note that the\n return value is a tuple even when `data` is 1-D.\n\n See Also\n --------\n argrelmin, argrelmax\n\n Notes\n -----\n\n .. versionadded:: 0.11.0\n\n Examples\n --------\n >>> from scipy.signal import argrelextrema\n >>> x = np.array([2, 1, 2, 3, 2, 0, 1, 0])\n >>> argrelextrema(x, np.greater)\n (array([3, 6]),)\n >>> y = np.array([[1, 2, 1, 2],\n ... [2, 2, 0, 0],\n ... [5, 3, 4, 4]])\n ...\n >>> argrelextrema(y, np.less, axis=1)\n (array([0, 2]), array([2, 1]))\n\n \"\"\"\n results = _boolrelextrema(data, comparator,\n axis, order, mode)\n return np.nonzero(results)\n\n\ndef _arg_x_as_expected(value):\n \"\"\"Ensure argument `x` is a 1-D C-contiguous array of dtype('float64').\n\n Used in `find_peaks`, `peak_prominences` and `peak_widths` to make `x`\n compatible with the signature of the wrapped Cython functions.\n\n Returns\n -------\n value : ndarray\n A 1-D C-contiguous array with dtype('float64').\n \"\"\"\n value = np.asarray(value, order='C', dtype=np.float64)\n if value.ndim != 1:\n raise ValueError('`x` must be a 1-D array')\n return value\n\n\ndef _arg_peaks_as_expected(value):\n \"\"\"Ensure argument `peaks` is a 1-D C-contiguous array of dtype('intp').\n\n Used in `peak_prominences` and `peak_widths` to make `peaks` compatible\n with the signature of the wrapped Cython functions.\n\n Returns\n -------\n value : ndarray\n A 1-D C-contiguous array with dtype('intp').\n \"\"\"\n value = np.asarray(value)\n if value.size == 0:\n # Empty arrays default to np.float64 but are valid input\n value = np.array([], dtype=np.intp)\n try:\n # Safely convert to C-contiguous array of type np.intp\n value = value.astype(np.intp, order='C', casting='safe',\n subok=False, copy=False)\n except TypeError as e:\n raise TypeError(\"cannot safely cast `peaks` to dtype('intp')\") from e\n if value.ndim != 1:\n raise ValueError('`peaks` must be a 1-D array')\n return value\n\n\ndef _arg_wlen_as_expected(value):\n \"\"\"Ensure argument `wlen` is of type `np.intp` and larger than 1.\n\n Used in `peak_prominences` and `peak_widths`.\n\n Returns\n -------\n value : np.intp\n The original `value` rounded up to an integer or -1 if `value` was\n None.\n \"\"\"\n if value is None:\n # _peak_prominences expects an intp; -1 signals that no value was\n # supplied by the user\n value = -1\n elif 1 < value:\n # Round up to a positive integer\n if not np.can_cast(value, np.intp, \"safe\"):\n value = math.ceil(value)\n value = np.intp(value)\n else:\n raise ValueError('`wlen` must be larger than 1, was {}'\n .format(value))\n return value\n\n\ndef peak_prominences(x, peaks, wlen=None):\n \"\"\"\n Calculate the prominence of each peak in a signal.\n\n The prominence of a peak measures how much a peak stands out from the\n surrounding baseline of the signal and is defined as the vertical distance\n between the peak and its lowest contour line.\n\n Parameters\n ----------\n x : sequence\n A signal with peaks.\n peaks : sequence\n Indices of peaks in `x`.\n wlen : int, optional\n A window length in samples that optionally limits the evaluated area for\n each peak to a subset of `x`. The peak is always placed in the middle of\n the window therefore the given length is rounded up to the next odd\n integer. This parameter can speed up the calculation (see Notes).\n\n Returns\n -------\n prominences : ndarray\n The calculated prominences for each peak in `peaks`.\n left_bases, right_bases : ndarray\n The peaks' bases as indices in `x` to the left and right of each peak.\n The higher base of each pair is a peak's lowest contour line.\n\n Raises\n ------\n ValueError\n If a value in `peaks` is an invalid index for `x`.\n\n Warns\n -----\n PeakPropertyWarning\n For indices in `peaks` that don't point to valid local maxima in `x`,\n the returned prominence will be 0 and this warning is raised. This\n also happens if `wlen` is smaller than the plateau size of a peak.\n\n Warnings\n --------\n This function may return unexpected results for data containing NaNs. To\n avoid this, NaNs should either be removed or replaced.\n\n See Also\n --------\n find_peaks\n Find peaks inside a signal based on peak properties.\n peak_widths\n Calculate the width of peaks.\n\n Notes\n -----\n Strategy to compute a peak's prominence:\n\n 1. Extend a horizontal line from the current peak to the left and right\n until the line either reaches the window border (see `wlen`) or\n intersects the signal again at the slope of a higher peak. An\n intersection with a peak of the same height is ignored.\n 2. On each side find the minimal signal value within the interval defined\n above. These points are the peak's bases.\n 3. The higher one of the two bases marks the peak's lowest contour line. The\n prominence can then be calculated as the vertical difference between the\n peaks height itself and its lowest contour line.\n\n Searching for the peak's bases can be slow for large `x` with periodic\n behavior because large chunks or even the full signal need to be evaluated\n for the first algorithmic step. This evaluation area can be limited with the\n parameter `wlen` which restricts the algorithm to a window around the\n current peak and can shorten the calculation time if the window length is\n short in relation to `x`.\n However, this may stop the algorithm from finding the true global contour\n line if the peak's true bases are outside this window. Instead, a higher\n contour line is found within the restricted window leading to a smaller\n calculated prominence. In practice, this is only relevant for the highest set\n of peaks in `x`. This behavior may even be used intentionally to calculate\n \"local\" prominences.\n\n .. versionadded:: 1.1.0\n\n References\n ----------\n .. [1] Wikipedia Article for Topographic Prominence:\n https://en.wikipedia.org/wiki/Topographic_prominence\n\n Examples\n --------\n >>> from scipy.signal import find_peaks, peak_prominences\n >>> import matplotlib.pyplot as plt\n\n Create a test signal with two overlayed harmonics\n\n >>> x = np.linspace(0, 6 * np.pi, 1000)\n >>> x = np.sin(x) + 0.6 * np.sin(2.6 * x)\n\n Find all peaks and calculate prominences\n\n >>> peaks, _ = find_peaks(x)\n >>> prominences = peak_prominences(x, peaks)[0]\n >>> prominences\n array([1.24159486, 0.47840168, 0.28470524, 3.10716793, 0.284603 ,\n 0.47822491, 2.48340261, 0.47822491])\n\n Calculate the height of each peak's contour line and plot the results\n\n >>> contour_heights = x[peaks] - prominences\n >>> plt.plot(x)\n >>> plt.plot(peaks, x[peaks], \"x\")\n >>> plt.vlines(x=peaks, ymin=contour_heights, ymax=x[peaks])\n >>> plt.show()\n\n Let's evaluate a second example that demonstrates several edge cases for\n one peak at index 5.\n\n >>> x = np.array([0, 1, 0, 3, 1, 3, 0, 4, 0])\n >>> peaks = np.array([5])\n >>> plt.plot(x)\n >>> plt.plot(peaks, x[peaks], \"x\")\n >>> plt.show()\n >>> peak_prominences(x, peaks) # -> (prominences, left_bases, right_bases)\n (array([3.]), array([2]), array([6]))\n\n Note how the peak at index 3 of the same height is not considered as a\n border while searching for the left base. Instead, two minima at 0 and 2\n are found in which case the one closer to the evaluated peak is always\n chosen. On the right side, however, the base must be placed at 6 because the\n higher peak represents the right border to the evaluated area.\n\n >>> peak_prominences(x, peaks, wlen=3.1)\n (array([2.]), array([4]), array([6]))\n\n Here, we restricted the algorithm to a window from 3 to 7 (the length is 5\n samples because `wlen` was rounded up to the next odd integer). Thus, the\n only two candidates in the evaluated area are the two neighboring samples\n and a smaller prominence is calculated.\n \"\"\"\n x = _arg_x_as_expected(x)\n peaks = _arg_peaks_as_expected(peaks)\n wlen = _arg_wlen_as_expected(wlen)\n return _peak_prominences(x, peaks, wlen)\n\n\ndef peak_widths(x, peaks, rel_height=0.5, prominence_data=None, wlen=None):\n \"\"\"\n Calculate the width of each peak in a signal.\n\n This function calculates the width of a peak in samples at a relative\n distance to the peak's height and prominence.\n\n Parameters\n ----------\n x : sequence\n A signal with peaks.\n peaks : sequence\n Indices of peaks in `x`.\n rel_height : float, optional\n Chooses the relative height at which the peak width is measured as a\n percentage of its prominence. 1.0 calculates the width of the peak at\n its lowest contour line while 0.5 evaluates at half the prominence\n height. Must be at least 0. See notes for further explanation.\n prominence_data : tuple, optional\n A tuple of three arrays matching the output of `peak_prominences` when\n called with the same arguments `x` and `peaks`. This data are calculated\n internally if not provided.\n wlen : int, optional\n A window length in samples passed to `peak_prominences` as an optional\n argument for internal calculation of `prominence_data`. This argument\n is ignored if `prominence_data` is given.\n\n Returns\n -------\n widths : ndarray\n The widths for each peak in samples.\n width_heights : ndarray\n The height of the contour lines at which the `widths` where evaluated.\n left_ips, right_ips : ndarray\n Interpolated positions of left and right intersection points of a\n horizontal line at the respective evaluation height.\n\n Raises\n ------\n ValueError\n If `prominence_data` is supplied but doesn't satisfy the condition\n ``0 <= left_base <= peak <= right_base < x.shape[0]`` for each peak,\n has the wrong dtype, is not C-contiguous or does not have the same\n shape.\n\n Warns\n -----\n PeakPropertyWarning\n Raised if any calculated width is 0. This may stem from the supplied\n `prominence_data` or if `rel_height` is set to 0.\n\n Warnings\n --------\n This function may return unexpected results for data containing NaNs. To\n avoid this, NaNs should either be removed or replaced.\n\n See Also\n --------\n find_peaks\n Find peaks inside a signal based on peak properties.\n peak_prominences\n Calculate the prominence of peaks.\n\n Notes\n -----\n The basic algorithm to calculate a peak's width is as follows:\n\n * Calculate the evaluation height :math:`h_{eval}` with the formula\n :math:`h_{eval} = h_{Peak} - P \\\\cdot R`, where :math:`h_{Peak}` is the\n height of the peak itself, :math:`P` is the peak's prominence and\n :math:`R` a positive ratio specified with the argument `rel_height`.\n * Draw a horizontal line at the evaluation height to both sides, starting at\n the peak's current vertical position until the lines either intersect a\n slope, the signal border or cross the vertical position of the peak's\n base (see `peak_prominences` for an definition). For the first case,\n intersection with the signal, the true intersection point is estimated\n with linear interpolation.\n * Calculate the width as the horizontal distance between the chosen\n endpoints on both sides. As a consequence of this the maximal possible\n width for each peak is the horizontal distance between its bases.\n\n As shown above to calculate a peak's width its prominence and bases must be\n known. You can supply these yourself with the argument `prominence_data`.\n Otherwise, they are internally calculated (see `peak_prominences`).\n\n .. versionadded:: 1.1.0\n\n Examples\n --------\n >>> from scipy.signal import chirp, find_peaks, peak_widths\n >>> import matplotlib.pyplot as plt\n\n Create a test signal with two overlayed harmonics\n\n >>> x = np.linspace(0, 6 * np.pi, 1000)\n >>> x = np.sin(x) + 0.6 * np.sin(2.6 * x)\n\n Find all peaks and calculate their widths at the relative height of 0.5\n (contour line at half the prominence height) and 1 (at the lowest contour\n line at full prominence height).\n\n >>> peaks, _ = find_peaks(x)\n >>> results_half = peak_widths(x, peaks, rel_height=0.5)\n >>> results_half[0] # widths\n array([ 64.25172825, 41.29465463, 35.46943289, 104.71586081,\n 35.46729324, 41.30429622, 181.93835853, 45.37078546])\n >>> results_full = peak_widths(x, peaks, rel_height=1)\n >>> results_full[0] # widths\n array([181.9396084 , 72.99284945, 61.28657872, 373.84622694,\n 61.78404617, 72.48822812, 253.09161876, 79.36860878])\n\n Plot signal, peaks and contour lines at which the widths where calculated\n\n >>> plt.plot(x)\n >>> plt.plot(peaks, x[peaks], \"x\")\n >>> plt.hlines(*results_half[1:], color=\"C2\")\n >>> plt.hlines(*results_full[1:], color=\"C3\")\n >>> plt.show()\n \"\"\"\n x = _arg_x_as_expected(x)\n peaks = _arg_peaks_as_expected(peaks)\n if prominence_data is None:\n # Calculate prominence if not supplied and use wlen if supplied.\n wlen = _arg_wlen_as_expected(wlen)\n prominence_data = _peak_prominences(x, peaks, wlen)\n return _peak_widths(x, peaks, rel_height, *prominence_data)\n\n\ndef _unpack_condition_args(interval, x, peaks):\n \"\"\"\n Parse condition arguments for `find_peaks`.\n\n Parameters\n ----------\n interval : number or ndarray or sequence\n Either a number or ndarray or a 2-element sequence of the former. The\n first value is always interpreted as `imin` and the second, if supplied,\n as `imax`.\n x : ndarray\n The signal with `peaks`.\n peaks : ndarray\n An array with indices used to reduce `imin` and / or `imax` if those are\n arrays.\n\n Returns\n -------\n imin, imax : number or ndarray or None\n Minimal and maximal value in `argument`.\n\n Raises\n ------\n ValueError :\n If interval border is given as array and its size does not match the size\n of `x`.\n\n Notes\n -----\n\n .. versionadded:: 1.1.0\n \"\"\"\n try:\n imin, imax = interval\n except (TypeError, ValueError):\n imin, imax = (interval, None)\n\n # Reduce arrays if arrays\n if isinstance(imin, np.ndarray):\n if imin.size != x.size:\n raise ValueError('array size of lower interval border must match x')\n imin = imin[peaks]\n if isinstance(imax, np.ndarray):\n if imax.size != x.size:\n raise ValueError('array size of upper interval border must match x')\n imax = imax[peaks]\n\n return imin, imax\n\n\ndef _select_by_property(peak_properties, pmin, pmax):\n \"\"\"\n Evaluate where the generic property of peaks confirms to an interval.\n\n Parameters\n ----------\n peak_properties : ndarray\n An array with properties for each peak.\n pmin : None or number or ndarray\n Lower interval boundary for `peak_properties`. ``None`` is interpreted as\n an open border.\n pmax : None or number or ndarray\n Upper interval boundary for `peak_properties`. ``None`` is interpreted as\n an open border.\n\n Returns\n -------\n keep : bool\n A boolean mask evaluating to true where `peak_properties` confirms to the\n interval.\n\n See Also\n --------\n find_peaks\n\n Notes\n -----\n\n .. versionadded:: 1.1.0\n \"\"\"\n keep = np.ones(peak_properties.size, dtype=bool)\n if pmin is not None:\n keep &= (pmin <= peak_properties)\n if pmax is not None:\n keep &= (peak_properties <= pmax)\n return keep\n\n\ndef _select_by_peak_threshold(x, peaks, tmin, tmax):\n \"\"\"\n Evaluate which peaks fulfill the threshold condition.\n\n Parameters\n ----------\n x : ndarray\n A 1-D array which is indexable by `peaks`.\n peaks : ndarray\n Indices of peaks in `x`.\n tmin, tmax : scalar or ndarray or None\n Minimal and / or maximal required thresholds. If supplied as ndarrays\n their size must match `peaks`. ``None`` is interpreted as an open\n border.\n\n Returns\n -------\n keep : bool\n A boolean mask evaluating to true where `peaks` fulfill the threshold\n condition.\n left_thresholds, right_thresholds : ndarray\n Array matching `peak` containing the thresholds of each peak on\n both sides.\n\n Notes\n -----\n\n .. versionadded:: 1.1.0\n \"\"\"\n # Stack thresholds on both sides to make min / max operations easier:\n # tmin is compared with the smaller, and tmax with the greater thresold to\n # each peak's side\n stacked_thresholds = np.vstack([x[peaks] - x[peaks - 1],\n x[peaks] - x[peaks + 1]])\n keep = np.ones(peaks.size, dtype=bool)\n if tmin is not None:\n min_thresholds = np.min(stacked_thresholds, axis=0)\n keep &= (tmin <= min_thresholds)\n if tmax is not None:\n max_thresholds = np.max(stacked_thresholds, axis=0)\n keep &= (max_thresholds <= tmax)\n\n return keep, stacked_thresholds[0], stacked_thresholds[1]\n\n\ndef find_peaks(x, height=None, threshold=None, distance=None,\n prominence=None, width=None, wlen=None, rel_height=0.5,\n plateau_size=None):\n \"\"\"\n Find peaks inside a signal based on peak properties.\n\n This function takes a 1-D array and finds all local maxima by\n simple comparison of neighboring values. Optionally, a subset of these\n peaks can be selected by specifying conditions for a peak's properties.\n\n Parameters\n ----------\n x : sequence\n A signal with peaks.\n height : number or ndarray or sequence, optional\n Required height of peaks. Either a number, ``None``, an array matching\n `x` or a 2-element sequence of the former. The first element is\n always interpreted as the minimal and the second, if supplied, as the\n maximal required height.\n threshold : number or ndarray or sequence, optional\n Required threshold of peaks, the vertical distance to its neighboring\n samples. Either a number, ``None``, an array matching `x` or a\n 2-element sequence of the former. The first element is always\n interpreted as the minimal and the second, if supplied, as the maximal\n required threshold.\n distance : number, optional\n Required minimal horizontal distance (>= 1) in samples between\n neighbouring peaks. Smaller peaks are removed first until the condition\n is fulfilled for all remaining peaks.\n prominence : number or ndarray or sequence, optional\n Required prominence of peaks. Either a number, ``None``, an array\n matching `x` or a 2-element sequence of the former. The first\n element is always interpreted as the minimal and the second, if\n supplied, as the maximal required prominence.\n width : number or ndarray or sequence, optional\n Required width of peaks in samples. Either a number, ``None``, an array\n matching `x` or a 2-element sequence of the former. The first\n element is always interpreted as the minimal and the second, if\n supplied, as the maximal required width.\n wlen : int, optional\n Used for calculation of the peaks prominences, thus it is only used if\n one of the arguments `prominence` or `width` is given. See argument\n `wlen` in `peak_prominences` for a full description of its effects.\n rel_height : float, optional\n Used for calculation of the peaks width, thus it is only used if `width`\n is given. See argument `rel_height` in `peak_widths` for a full\n description of its effects.\n plateau_size : number or ndarray or sequence, optional\n Required size of the flat top of peaks in samples. Either a number,\n ``None``, an array matching `x` or a 2-element sequence of the former.\n The first element is always interpreted as the minimal and the second,\n if supplied as the maximal required plateau size.\n\n .. versionadded:: 1.2.0\n\n Returns\n -------\n peaks : ndarray\n Indices of peaks in `x` that satisfy all given conditions.\n properties : dict\n A dictionary containing properties of the returned peaks which were\n calculated as intermediate results during evaluation of the specified\n conditions:\n\n * 'peak_heights'\n If `height` is given, the height of each peak in `x`.\n * 'left_thresholds', 'right_thresholds'\n If `threshold` is given, these keys contain a peaks vertical\n distance to its neighbouring samples.\n * 'prominences', 'right_bases', 'left_bases'\n If `prominence` is given, these keys are accessible. See\n `peak_prominences` for a description of their content.\n * 'width_heights', 'left_ips', 'right_ips'\n If `width` is given, these keys are accessible. See `peak_widths`\n for a description of their content.\n * 'plateau_sizes', left_edges', 'right_edges'\n If `plateau_size` is given, these keys are accessible and contain\n the indices of a peak's edges (edges are still part of the\n plateau) and the calculated plateau sizes.\n\n .. versionadded:: 1.2.0\n\n To calculate and return properties without excluding peaks, provide the\n open interval ``(None, None)`` as a value to the appropriate argument\n (excluding `distance`).\n\n Warns\n -----\n PeakPropertyWarning\n Raised if a peak's properties have unexpected values (see\n `peak_prominences` and `peak_widths`).\n\n Warnings\n --------\n This function may return unexpected results for data containing NaNs. To\n avoid this, NaNs should either be removed or replaced.\n\n See Also\n --------\n find_peaks_cwt\n Find peaks using the wavelet transformation.\n peak_prominences\n Directly calculate the prominence of peaks.\n peak_widths\n Directly calculate the width of peaks.\n\n Notes\n -----\n In the context of this function, a peak or local maximum is defined as any\n sample whose two direct neighbours have a smaller amplitude. For flat peaks\n (more than one sample of equal amplitude wide) the index of the middle\n sample is returned (rounded down in case the number of samples is even).\n For noisy signals the peak locations can be off because the noise might\n change the position of local maxima. In those cases consider smoothing the\n signal before searching for peaks or use other peak finding and fitting\n methods (like `find_peaks_cwt`).\n\n Some additional comments on specifying conditions:\n\n * Almost all conditions (excluding `distance`) can be given as half-open or\n closed intervals, e.g., ``1`` or ``(1, None)`` defines the half-open\n interval :math:`[1, \\\\infty]` while ``(None, 1)`` defines the interval\n :math:`[-\\\\infty, 1]`. The open interval ``(None, None)`` can be specified\n as well, which returns the matching properties without exclusion of peaks.\n * The border is always included in the interval used to select valid peaks.\n * For several conditions the interval borders can be specified with\n arrays matching `x` in shape which enables dynamic constrains based on\n the sample position.\n * The conditions are evaluated in the following order: `plateau_size`,\n `height`, `threshold`, `distance`, `prominence`, `width`. In most cases\n this order is the fastest one because faster operations are applied first\n to reduce the number of peaks that need to be evaluated later.\n * While indices in `peaks` are guaranteed to be at least `distance` samples\n apart, edges of flat peaks may be closer than the allowed `distance`.\n * Use `wlen` to reduce the time it takes to evaluate the conditions for\n `prominence` or `width` if `x` is large or has many local maxima\n (see `peak_prominences`).\n\n .. versionadded:: 1.1.0\n\n Examples\n --------\n To demonstrate this function's usage we use a signal `x` supplied with\n SciPy (see `scipy.misc.electrocardiogram`). Let's find all peaks (local\n maxima) in `x` whose amplitude lies above 0.\n\n >>> import matplotlib.pyplot as plt\n >>> from scipy.misc import electrocardiogram\n >>> from scipy.signal import find_peaks\n >>> x = electrocardiogram()[2000:4000]\n >>> peaks, _ = find_peaks(x, height=0)\n >>> plt.plot(x)\n >>> plt.plot(peaks, x[peaks], \"x\")\n >>> plt.plot(np.zeros_like(x), \"--\", color=\"gray\")\n >>> plt.show()\n\n We can select peaks below 0 with ``height=(None, 0)`` or use arrays matching\n `x` in size to reflect a changing condition for different parts of the\n signal.\n\n >>> border = np.sin(np.linspace(0, 3 * np.pi, x.size))\n >>> peaks, _ = find_peaks(x, height=(-border, border))\n >>> plt.plot(x)\n >>> plt.plot(-border, \"--\", color=\"gray\")\n >>> plt.plot(border, \":\", color=\"gray\")\n >>> plt.plot(peaks, x[peaks], \"x\")\n >>> plt.show()\n\n Another useful condition for periodic signals can be given with the\n `distance` argument. In this case, we can easily select the positions of\n QRS complexes within the electrocardiogram (ECG) by demanding a distance of\n at least 150 samples.\n\n >>> peaks, _ = find_peaks(x, distance=150)\n >>> np.diff(peaks)\n array([186, 180, 177, 171, 177, 169, 167, 164, 158, 162, 172])\n >>> plt.plot(x)\n >>> plt.plot(peaks, x[peaks], \"x\")\n >>> plt.show()\n\n Especially for noisy signals peaks can be easily grouped by their\n prominence (see `peak_prominences`). E.g., we can select all peaks except\n for the mentioned QRS complexes by limiting the allowed prominence to 0.6.\n\n >>> peaks, properties = find_peaks(x, prominence=(None, 0.6))\n >>> properties[\"prominences\"].max()\n 0.5049999999999999\n >>> plt.plot(x)\n >>> plt.plot(peaks, x[peaks], \"x\")\n >>> plt.show()\n\n And, finally, let's examine a different section of the ECG which contains\n beat forms of different shape. To select only the atypical heart beats, we\n combine two conditions: a minimal prominence of 1 and width of at least 20\n samples.\n\n >>> x = electrocardiogram()[17000:18000]\n >>> peaks, properties = find_peaks(x, prominence=1, width=20)\n >>> properties[\"prominences\"], properties[\"widths\"]\n (array([1.495, 2.3 ]), array([36.93773946, 39.32723577]))\n >>> plt.plot(x)\n >>> plt.plot(peaks, x[peaks], \"x\")\n >>> plt.vlines(x=peaks, ymin=x[peaks] - properties[\"prominences\"],\n ... ymax = x[peaks], color = \"C1\")\n >>> plt.hlines(y=properties[\"width_heights\"], xmin=properties[\"left_ips\"],\n ... xmax=properties[\"right_ips\"], color = \"C1\")\n >>> plt.show()\n \"\"\"\n # _argmaxima1d expects array of dtype 'float64'\n x = _arg_x_as_expected(x)\n if distance is not None and distance < 1:\n raise ValueError('`distance` must be greater or equal to 1')\n\n peaks, left_edges, right_edges = _local_maxima_1d(x)\n properties = {}\n\n if plateau_size is not None:\n # Evaluate plateau size\n plateau_sizes = right_edges - left_edges + 1\n pmin, pmax = _unpack_condition_args(plateau_size, x, peaks)\n keep = _select_by_property(plateau_sizes, pmin, pmax)\n peaks = peaks[keep]\n properties[\"plateau_sizes\"] = plateau_sizes\n properties[\"left_edges\"] = left_edges\n properties[\"right_edges\"] = right_edges\n properties = {key: array[keep] for key, array in properties.items()}\n\n if height is not None:\n # Evaluate height condition\n peak_heights = x[peaks]\n hmin, hmax = _unpack_condition_args(height, x, peaks)\n keep = _select_by_property(peak_heights, hmin, hmax)\n peaks = peaks[keep]\n properties[\"peak_heights\"] = peak_heights\n properties = {key: array[keep] for key, array in properties.items()}\n\n if threshold is not None:\n # Evaluate threshold condition\n tmin, tmax = _unpack_condition_args(threshold, x, peaks)\n keep, left_thresholds, right_thresholds = _select_by_peak_threshold(\n x, peaks, tmin, tmax)\n peaks = peaks[keep]\n properties[\"left_thresholds\"] = left_thresholds\n properties[\"right_thresholds\"] = right_thresholds\n properties = {key: array[keep] for key, array in properties.items()}\n\n if distance is not None:\n # Evaluate distance condition\n keep = _select_by_peak_distance(peaks, x[peaks], distance)\n peaks = peaks[keep]\n properties = {key: array[keep] for key, array in properties.items()}\n\n if prominence is not None or width is not None:\n # Calculate prominence (required for both conditions)\n wlen = _arg_wlen_as_expected(wlen)\n properties.update(zip(\n ['prominences', 'left_bases', 'right_bases'],\n _peak_prominences(x, peaks, wlen=wlen)\n ))\n\n if prominence is not None:\n # Evaluate prominence condition\n pmin, pmax = _unpack_condition_args(prominence, x, peaks)\n keep = _select_by_property(properties['prominences'], pmin, pmax)\n peaks = peaks[keep]\n properties = {key: array[keep] for key, array in properties.items()}\n\n if width is not None:\n # Calculate widths\n properties.update(zip(\n ['widths', 'width_heights', 'left_ips', 'right_ips'],\n _peak_widths(x, peaks, rel_height, properties['prominences'],\n properties['left_bases'], properties['right_bases'])\n ))\n # Evaluate width condition\n wmin, wmax = _unpack_condition_args(width, x, peaks)\n keep = _select_by_property(properties['widths'], wmin, wmax)\n peaks = peaks[keep]\n properties = {key: array[keep] for key, array in properties.items()}\n\n return peaks, properties\n\n\ndef _identify_ridge_lines(matr, max_distances, gap_thresh):\n \"\"\"\n Identify ridges in the 2-D matrix.\n\n Expect that the width of the wavelet feature increases with increasing row\n number.\n\n Parameters\n ----------\n matr : 2-D ndarray\n Matrix in which to identify ridge lines.\n max_distances : 1-D sequence\n At each row, a ridge line is only connected\n if the relative max at row[n] is within\n `max_distances`[n] from the relative max at row[n+1].\n gap_thresh : int\n If a relative maximum is not found within `max_distances`,\n there will be a gap. A ridge line is discontinued if\n there are more than `gap_thresh` points without connecting\n a new relative maximum.\n\n Returns\n -------\n ridge_lines : tuple\n Tuple of 2 1-D sequences. `ridge_lines`[ii][0] are the rows of the\n ii-th ridge-line, `ridge_lines`[ii][1] are the columns. Empty if none\n found. Each ridge-line will be sorted by row (increasing), but the\n order of the ridge lines is not specified.\n\n References\n ----------\n .. [1] Bioinformatics (2006) 22 (17): 2059-2065.\n :doi:`10.1093/bioinformatics/btl355`\n\n Examples\n --------\n >>> rng = np.random.default_rng()\n >>> data = rng.random((5,5))\n >>> ridge_lines = _identify_ridge_lines(data, 1, 1)\n\n Notes\n -----\n This function is intended to be used in conjunction with `cwt`\n as part of `find_peaks_cwt`.\n\n \"\"\"\n if(len(max_distances) < matr.shape[0]):\n raise ValueError('Max_distances must have at least as many rows '\n 'as matr')\n\n all_max_cols = _boolrelextrema(matr, np.greater, axis=1, order=1)\n # Highest row for which there are any relative maxima\n has_relmax = np.nonzero(all_max_cols.any(axis=1))[0]\n if(len(has_relmax) == 0):\n return []\n start_row = has_relmax[-1]\n # Each ridge line is a 3-tuple:\n # rows, cols,Gap number\n ridge_lines = [[[start_row],\n [col],\n 0] for col in np.nonzero(all_max_cols[start_row])[0]]\n final_lines = []\n rows = np.arange(start_row - 1, -1, -1)\n cols = np.arange(0, matr.shape[1])\n for row in rows:\n this_max_cols = cols[all_max_cols[row]]\n\n # Increment gap number of each line,\n # set it to zero later if appropriate\n for line in ridge_lines:\n line[2] += 1\n\n # XXX These should always be all_max_cols[row]\n # But the order might be different. Might be an efficiency gain\n # to make sure the order is the same and avoid this iteration\n prev_ridge_cols = np.array([line[1][-1] for line in ridge_lines])\n # Look through every relative maximum found at current row\n # Attempt to connect them with existing ridge lines.\n for ind, col in enumerate(this_max_cols):\n # If there is a previous ridge line within\n # the max_distance to connect to, do so.\n # Otherwise start a new one.\n line = None\n if(len(prev_ridge_cols) > 0):\n diffs = np.abs(col - prev_ridge_cols)\n closest = np.argmin(diffs)\n if diffs[closest] <= max_distances[row]:\n line = ridge_lines[closest]\n if(line is not None):\n # Found a point close enough, extend current ridge line\n line[1].append(col)\n line[0].append(row)\n line[2] = 0\n else:\n new_line = [[row],\n [col],\n 0]\n ridge_lines.append(new_line)\n\n # Remove the ridge lines with gap_number too high\n # XXX Modifying a list while iterating over it.\n # Should be safe, since we iterate backwards, but\n # still tacky.\n for ind in range(len(ridge_lines) - 1, -1, -1):\n line = ridge_lines[ind]\n if line[2] > gap_thresh:\n final_lines.append(line)\n del ridge_lines[ind]\n\n out_lines = []\n for line in (final_lines + ridge_lines):\n sortargs = np.array(np.argsort(line[0]))\n rows, cols = np.zeros_like(sortargs), np.zeros_like(sortargs)\n rows[sortargs] = line[0]\n cols[sortargs] = line[1]\n out_lines.append([rows, cols])\n\n return out_lines\n\n\ndef _filter_ridge_lines(cwt, ridge_lines, window_size=None, min_length=None,\n min_snr=1, noise_perc=10):\n \"\"\"\n Filter ridge lines according to prescribed criteria. Intended\n to be used for finding relative maxima.\n\n Parameters\n ----------\n cwt : 2-D ndarray\n Continuous wavelet transform from which the `ridge_lines` were defined.\n ridge_lines : 1-D sequence\n Each element should contain 2 sequences, the rows and columns\n of the ridge line (respectively).\n window_size : int, optional\n Size of window to use to calculate noise floor.\n Default is ``cwt.shape[1] / 20``.\n min_length : int, optional\n Minimum length a ridge line needs to be acceptable.\n Default is ``cwt.shape[0] / 4``, ie 1/4-th the number of widths.\n min_snr : float, optional\n Minimum SNR ratio. Default 1. The signal is the value of\n the cwt matrix at the shortest length scale (``cwt[0, loc]``), the\n noise is the `noise_perc`th percentile of datapoints contained within a\n window of `window_size` around ``cwt[0, loc]``.\n noise_perc : float, optional\n When calculating the noise floor, percentile of data points\n examined below which to consider noise. Calculated using\n scipy.stats.scoreatpercentile.\n\n References\n ----------\n .. [1] Bioinformatics (2006) 22 (17): 2059-2065.\n :doi:`10.1093/bioinformatics/btl355`\n\n \"\"\"\n num_points = cwt.shape[1]\n if min_length is None:\n min_length = np.ceil(cwt.shape[0] / 4)\n if window_size is None:\n window_size = np.ceil(num_points / 20)\n\n window_size = int(window_size)\n hf_window, odd = divmod(window_size, 2)\n\n # Filter based on SNR\n row_one = cwt[0, :]\n noises = np.empty_like(row_one)\n for ind, val in enumerate(row_one):\n window_start = max(ind - hf_window, 0)\n window_end = min(ind + hf_window + odd, num_points)\n noises[ind] = scoreatpercentile(row_one[window_start:window_end],\n per=noise_perc)\n\n def filt_func(line):\n if len(line[0]) < min_length:\n return False\n snr = abs(cwt[line[0][0], line[1][0]] / noises[line[1][0]])\n if snr < min_snr:\n return False\n return True\n\n return list(filter(filt_func, ridge_lines))\n\n\ndef find_peaks_cwt(vector, widths, wavelet=None, max_distances=None,\n gap_thresh=None, min_length=None,\n min_snr=1, noise_perc=10, window_size=None):\n \"\"\"\n Find peaks in a 1-D array with wavelet transformation.\n\n The general approach is to smooth `vector` by convolving it with\n `wavelet(width)` for each width in `widths`. Relative maxima which\n appear at enough length scales, and with sufficiently high SNR, are\n accepted.\n\n Parameters\n ----------\n vector : ndarray\n 1-D array in which to find the peaks.\n widths : float or sequence\n Single width or 1-D array-like of widths to use for calculating\n the CWT matrix. In general,\n this range should cover the expected width of peaks of interest.\n wavelet : callable, optional\n Should take two parameters and return a 1-D array to convolve\n with `vector`. The first parameter determines the number of points\n of the returned wavelet array, the second parameter is the scale\n (`width`) of the wavelet. Should be normalized and symmetric.\n Default is the ricker wavelet.\n max_distances : ndarray, optional\n At each row, a ridge line is only connected if the relative max at\n row[n] is within ``max_distances[n]`` from the relative max at\n ``row[n+1]``. Default value is ``widths/4``.\n gap_thresh : float, optional\n If a relative maximum is not found within `max_distances`,\n there will be a gap. A ridge line is discontinued if there are more\n than `gap_thresh` points without connecting a new relative maximum.\n Default is the first value of the widths array i.e. widths[0].\n min_length : int, optional\n Minimum length a ridge line needs to be acceptable.\n Default is ``cwt.shape[0] / 4``, ie 1/4-th the number of widths.\n min_snr : float, optional\n Minimum SNR ratio. Default 1. The signal is the maximum CWT coefficient\n on the largest ridge line. The noise is `noise_perc` th percentile of\n datapoints contained within the same ridge line.\n noise_perc : float, optional\n When calculating the noise floor, percentile of data points\n examined below which to consider noise. Calculated using\n `stats.scoreatpercentile`. Default is 10.\n window_size : int, optional\n Size of window to use to calculate noise floor.\n Default is ``cwt.shape[1] / 20``.\n\n Returns\n -------\n peaks_indices : ndarray\n Indices of the locations in the `vector` where peaks were found.\n The list is sorted.\n\n See Also\n --------\n cwt\n Continuous wavelet transform.\n find_peaks\n Find peaks inside a signal based on peak properties.\n\n Notes\n -----\n This approach was designed for finding sharp peaks among noisy data,\n however with proper parameter selection it should function well for\n different peak shapes.\n\n The algorithm is as follows:\n 1. Perform a continuous wavelet transform on `vector`, for the supplied\n `widths`. This is a convolution of `vector` with `wavelet(width)` for\n each width in `widths`. See `cwt`.\n 2. Identify \"ridge lines\" in the cwt matrix. These are relative maxima\n at each row, connected across adjacent rows. See identify_ridge_lines\n 3. Filter the ridge_lines using filter_ridge_lines.\n\n .. versionadded:: 0.11.0\n\n References\n ----------\n .. [1] Bioinformatics (2006) 22 (17): 2059-2065.\n :doi:`10.1093/bioinformatics/btl355`\n\n Examples\n --------\n >>> from scipy import signal\n >>> xs = np.arange(0, np.pi, 0.05)\n >>> data = np.sin(xs)\n >>> peakind = signal.find_peaks_cwt(data, np.arange(1,10))\n >>> peakind, xs[peakind], data[peakind]\n ([32], array([ 1.6]), array([ 0.9995736]))\n\n \"\"\"\n widths = np.array(widths, copy=False, ndmin=1)\n\n if gap_thresh is None:\n gap_thresh = np.ceil(widths[0])\n if max_distances is None:\n max_distances = widths / 4.0\n if wavelet is None:\n wavelet = ricker\n\n cwt_dat = cwt(vector, wavelet, widths)\n ridge_lines = _identify_ridge_lines(cwt_dat, max_distances, gap_thresh)\n filtered = _filter_ridge_lines(cwt_dat, ridge_lines, min_length=min_length,\n window_size=window_size, min_snr=min_snr,\n noise_perc=noise_perc)\n max_locs = np.asarray([x[1][0] for x in filtered])\n max_locs.sort()\n\n return max_locs\n"
] |
[
[
"numpy.concatenate",
"numpy.array",
"numpy.cov",
"numpy.asarray",
"numpy.median",
"numpy.round",
"numpy.mean",
"numpy.diff",
"numpy.nonzero",
"numpy.amax",
"numpy.sqrt",
"numpy.amin"
],
[
"scipy.special.hyp2f1",
"scipy.special._testutils.check_version",
"scipy.special._testutils.MissingModule"
],
[
"numpy.max",
"scipy.stats.scoreatpercentile",
"numpy.array",
"numpy.ceil",
"numpy.zeros_like",
"numpy.asarray",
"numpy.argmin",
"numpy.ones",
"numpy.min",
"numpy.nonzero",
"numpy.can_cast",
"numpy.arange",
"numpy.empty_like",
"numpy.argsort",
"numpy.intp",
"numpy.abs",
"numpy.vstack",
"scipy.signal._wavelets.cwt"
]
] |
NixonZ/dnnCompiler
|
[
"1f3c89248e279c6b5625cd8cb134a4c718eb7764",
"a9df5ab0eefe0f48a1416fe504f50e2bf71aeecc"
] |
[
"test/swig/PRelu.py",
"test/swig/Mul.py"
] |
[
"# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\") you may not use this file except in compliance\n# with the License. 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,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument\n#\n# This file is part of DNN compiler maintained at\n# https://github.com/ai-techsystems/dnnCompiler\n\nimport common\n\nimport dnnc as dc\nimport numpy as np\nimport unittest\n\ndef prelu_util(x, slope):\n arr = x.copy()\n l = len(slope)\n for i, e in enumerate(arr):\n if e < 0:\n if l == 1:\n arr[i] = e * slope[0]\n else: \n arr[i] = e * slope[i]\n return arr\n\nclass PReluTest(unittest.TestCase):\n def setUp(self):\n self.len = 24\n\n self.np_a = np.random.randn(self.len).astype(np.float32)\n self.dc_a = dc.array(list(self.np_a))\n\n self.np_slope_1 = np.random.randn(1).astype(np.float32)\n self.dc_slope_1 = dc.array(list(self.np_slope_1))\n\n self.np_slope = np.random.randn(self.len).astype(np.float32)\n self.dc_slope = dc.array(list(self.np_slope))\n\n self.prelu_true = prelu_util(self.np_a, self.np_slope)\n self.prelu_true_1 = prelu_util(self.np_a, self.np_slope_1)\n\n\n def test_prelu_1d (self):\n dcr = dc.prelu(self.dc_a, self.dc_slope)\n\n np.testing.assert_allclose(self.prelu_true, np.array(dcr.data()).astype(np.float32),\n rtol=1e-3, atol=1e-3)\n\n def test_prelu_1d_broadcast (self):\n dcr = dc.prelu(self.dc_a,self.dc_slope_1)\n \n np.testing.assert_allclose(self.prelu_true_1, np.array(dcr.data()).astype(np.float32),\n rtol=1e-3, atol=1e-3)\n\n def test_prelu_2d (self):\n dc_a_reshaped = dc.reshape(self.dc_a, (6, 4))\n dc_slope_reshaped = dc.reshape(self.dc_slope, (6, 4))\n\n np_test = np.reshape(self.prelu_true, (6, 4))\n\n dc_test = dc.prelu(dc_a_reshaped, dc_slope_reshaped)\n np.testing.assert_allclose(np_test.flatten(), np.array(dc_test.data()).astype(np.float32),\n rtol=1e-3, atol=1e-3)\n\n def test_prelu_2d_broadcast (self):\n dc_a_reshaped = dc.reshape(self.dc_a, (6, 4))\n\n np_test = self.prelu_true_1.copy()\n\n dc_test = dc.prelu(dc_a_reshaped, self.dc_slope_1)\n np.testing.assert_allclose(np_test.flatten(), np.array(dc_test.data()).astype(np.float32),\n rtol=1e-3, atol=1e-3)\n\n def test_prelu_3d (self):\n dc_a_reshaped = dc.reshape(self.dc_a, (2, 4, 3))\n dc_slope_reshaped = dc.reshape(self.dc_slope, (2, 4, 3))\n\n np_test = np.reshape(self.prelu_true, (2, 4, 3))\n\n dc_test = dc.prelu(dc_a_reshaped, dc_slope_reshaped)\n np.testing.assert_allclose(np_test.flatten(), np.array(dc_test.data()).astype(np.float32),\n rtol=1e-3, atol=1e-3)\n\n def test_prelu_3d_broadcast (self):\n dc_a_reshaped = dc.reshape(self.dc_a, (2, 4, 3))\n\n np_test = self.prelu_true_1.copy()\n\n dc_test = dc.prelu(dc_a_reshaped, self.dc_slope_1)\n np.testing.assert_allclose(np_test.flatten(), np.array(dc_test.data()).astype(np.float32),\n rtol=1e-3, atol=1e-3)\n\n def test_prelu_4d (self):\n dc_a_reshaped = dc.reshape(self.dc_a, (2, 3, 2, 2))\n dc_slope_reshaped = dc.reshape(self.dc_slope, (2, 3, 2, 2))\n\n np_test = np.reshape(self.prelu_true, (2, 3, 2, 2))\n\n dc_test = dc.prelu(dc_a_reshaped, dc_slope_reshaped)\n np.testing.assert_allclose(np_test.flatten(), np.array(dc_test.data()).astype(np.float32),\n rtol=1e-3, atol=1e-3)\n\n def test_prelu_4d_broadcast (self):\n dc_a_reshaped = dc.reshape(self.dc_a, (2, 1, 4, 3))\n\n np_test = self.prelu_true_1.copy()\n\n dc_test = dc.prelu(dc_a_reshaped, self.dc_slope_1)\n np.testing.assert_allclose(np_test.flatten(), np.array(dc_test.data()).astype(np.float32),\n rtol=1e-3, atol=1e-3)\n\n def tearDown(self):\n return \"test finished\"\n\nif __name__ == '__main__':\n unittest.main()\n",
"# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. 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,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# pylint: disable=invalid-name, unused-argument\n#\n# This file is part of DNN compiler maintained at\n# https://github.com/ai-techsystems/dnnCompiler\n\nimport common\n\nimport dnnc as dc\nimport numpy as np\nimport unittest\n\nclass MulTest(unittest.TestCase):\n def setUp(self):\n self.len = 24\n self.np_a = np.random.randn(self.len).astype(np.float32)\n self.np_b = np.random.randn(self.len).astype(np.float32)\n self.dc_a = dc.array(list(self.np_a));\n self.dc_b = dc.array(list(self.np_b));\n\n def test_Mul1D (self):\n npr = np.multiply(self.np_a, self.np_b)\n dcr = dc.mul(self.dc_a, self.dc_b)\n np.testing.assert_allclose(npr, np.array(dcr.data()).astype(np.float32),\n rtol=1e-3, atol=1e-3)\n\n def test_Mul2D (self):\n np_a = np.reshape(self.np_a, (6,4))\n np_b = np.reshape(self.np_b, (6,4))\n dc_a = dc.reshape(self.dc_a, (6,4));\n dc_b = dc.reshape(self.dc_b, (6,4));\n npr = np.multiply(np_a, np_b);\n dcr = dc.mul(dc_a, dc_b);\n np.testing.assert_allclose(npr.flatten(), np.array(dcr.data()).astype(np.float32),\n rtol=1e-3, atol=1e-3)\n\n def test_Mul3D (self):\n np_a = np.reshape(self.np_a, (2,4,3))\n np_b = np.reshape(self.np_b, (2,4,3))\n dc_a = dc.reshape(self.dc_a, (2,4,3));\n dc_b = dc.reshape(self.dc_b, (2,4,3));\n\n npr = np.multiply(np_a, np_b);\n dcr = dc.mul(dc_a, dc_b);\n\n np.testing.assert_allclose(npr.flatten(), np.array(dcr.data()).astype(np.float32),\n rtol=1e-3, atol=1e-3)\n\n def test_Mul4D (self):\n np_a = np.reshape(self.np_a, (2,2,2,3))\n np_b = np.reshape(self.np_b, (2,2,2,3))\n dc_a = dc.reshape(self.dc_a, (2,2,2,3));\n dc_b = dc.reshape(self.dc_b, (2,2,2,3));\n\n npr = np.multiply(np_a, np_b);\n dcr = dc.mul(dc_a, dc_b);\n\n np.testing.assert_allclose(npr.flatten(), np.array(dcr.data()).astype(np.float32),\n rtol=1e-3, atol=1e-3)\n\n def tearDown(self):\n return \"test finished\"\n\nif __name__ == '__main__':\n unittest.main()\n\n"
] |
[
[
"numpy.random.randn",
"numpy.reshape"
],
[
"numpy.multiply",
"numpy.random.randn",
"numpy.reshape"
]
] |
nouraldinkahlous/Molecular_Dynamics_and_Free_Energy_Perturbation
|
[
"c94b024900a48884dd20a29769b62bf7096795f0"
] |
[
"deprecated/Hysterseis.py"
] |
[
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jan 6 19:51:16 2020\n\n@author: nour\n\"\"\"\n\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport itertools\nimport pandas as pd\n\nimport glob\nqfep=[]\nfor filename in glob.glob(\"qfep*.out\"):\n qfep.append(filename)\n \n \ndG=[]\nfor x in qfep: \n fo = open(x, \"r\")\n g=[]\n part1 = False \n for line in fo:\n if line.startswith(\"# Part 1\"):\n part1 = True \n elif line.startswith(\"# Min energy-gap\"):\n part1 = False \n \n if part1:\n g.append(line.strip().rstrip().split())\n \n \n del(g[0])\n del(g[-1]) \n del(g[0][0])\n dG.append(g)\n fo.close()\ndfs=[]\nfor i in dG:\n dfs.append(\"FEP_\" +str(dG.index(i)+1))\n globals()[\"FEP_\" +str(dG.index(i)+1)] = pd.DataFrame(i[1:], columns =i[0], dtype = float) \n \nfor df in dfs: \n eval(df).iloc[:,3]=eval(df).iloc[:,3].values[::-1]\n \n eval(df).iloc[:,4]=eval(df).iloc[:,4].values[::-1]\n\nfor df in dfs:\n f = df+ \"-ΔGf\"\n fc= \"C\" + str(dfs.index(df)+5)\n rc= \"C\" + str(dfs.index(df))\n r = df+ \"-ΔGr\"\n p=plt.plot(eval(df).iloc[:,2],'.',label= f,color=fc)\n p=plt.plot(eval(df).iloc[:,4],'.',label =r,color=rc)\n plt.title('Hysteresis between ΔGf and ΔGr',fontsize=16)\n plt.xlabel(\"λ\",fontsize=14)\n plt.ylabel(\"ΔG FEP (Kcal/mol)\",fontsize=14)\n plt.legend()\nplt.savefig('Hysteresis.png',dpi=200)\n\n"
] |
[
[
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.title",
"pandas.DataFrame",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.ylabel"
]
] |
pratyuksh/PolytopeMeshGen
|
[
"9eb095de94535fa4018877bd4e0c08c9f620648a"
] |
[
"generators/graded_meshes_3d.py"
] |
[
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport dolfin as df\nimport numpy as np\nfrom generators.graded_meshes_base import GradedMeshGeneratorBase\n\n\n# CLASS: Anisotropic Graded Meshes 3d, tetrahedral elements\nclass GradedMeshGenerator3d(GradedMeshGeneratorBase):\n\n def __init__(self, polyhedron):\n\n self.ndim = 3\n self.polyhedron = polyhedron\n\n self.nvc = 4 # number of vertices per cell\n self.nec = 6 # number of edges per cell\n self.ncc = 8 # number of children per cell\n\n self.nsc = polyhedron.singular_corners.shape[0] # no. of singular corners\n self.refine_weights = polyhedron.refine_weights\n\n # get weight from edge_locality\n def get_weight(self, edge_locality):\n weight = 0.5 # default\n if edge_locality[0] > 1:\n weight = self.polyhedron.refine_weights[edge_locality[1] - 1]\n return weight\n\n # get child vertex from edge_locality\n def get_child_vertex(self, edge_locality, edge_coords):\n\n weight = self.get_weight(edge_locality)\n v0 = edge_coords[0]\n v1 = edge_coords[1]\n\n if edge_locality[0] == 2 \\\n or edge_locality[0] == 3:\n if edge_locality[2] == 1:\n v0 = edge_coords[1]\n v1 = edge_coords[0]\n\n if edge_locality[0] == 4:\n if edge_locality[3] == 1:\n v0 = edge_coords[1]\n v1 = edge_coords[0]\n\n return v0 * (1 - weight) + v1 * weight\n\n # marks the edges\n # 1: interior edge or singular edge \n # 2: edge connected to a singular corner\n # 3: edge connected to a singular edge through a vertex\n # 4: edge is singular + an edge vertex is a singular\n # generates coordinates of child vertices on the edges\n def create_child_vertices(self, mesh, bool_quasiuniform):\n\n mesh.init(1)\n num_edges = mesh.num_entities(1)\n vertices = mesh.coordinates()\n\n child_vertices = np.zeros((num_edges, self.ndim)) # array of child vertices\n\n # quasi-uniform refinement\n if bool_quasiuniform:\n print(\"\\n\\tQuasi-uniform mesh refinement running...\")\n for k in range(0, num_edges):\n edge = df.Edge(mesh, k)\n edge_vertices_id_global = edge.entities(0)\n edge_coords = vertices[edge_vertices_id_global]\n child_vertices[k, :] = 0.5 * (edge_coords[0, :] + edge_coords[1, :])\n return child_vertices\n\n # anisotropic refinement\n print(\"\\n\\tAnisotropic mesh refinement running...\")\n edges_locality = []\n # mark edges, compute child vertices for interior-, v_e- , e-, ev- type edges\n for k in range(0, num_edges):\n\n edge_marked = False\n edge = df.Edge(mesh, k)\n edge_vertices_id_global = edge.entities(0)\n edge_coords = vertices[edge_vertices_id_global]\n\n for j in range(0, 2):\n sin_corner_flag, sin_corner_id = self.polyhedron.is_a_singular_corner(edge_coords[j, :])\n\n if sin_corner_flag:\n\n # sin_edge_flag = False\n v = None\n if j == 0:\n v = edge_coords[1, :]\n elif j == 1:\n v = edge_coords[0, :]\n\n sin_edge_flag, sin_edge_id = self.polyhedron.on_singular_edge_connected_to_singular_corner(\n sin_corner_id, v)\n\n if sin_edge_flag:\n edge_locality = [4, sin_corner_id, sin_edge_id + self.nsc, j] # ev-type\n else:\n edge_locality = [2, sin_corner_id, j] # v-type\n\n edge_marked = True\n edges_locality.append(edge_locality)\n break\n\n if not edge_marked:\n\n flag1, sin_edge_id = self.polyhedron.edge_lies_on_singular_edges(edge_coords)\n if flag1:\n edge_locality = [1, 0] # e-type\n edge_marked = True\n edges_locality.append(edge_locality)\n else:\n for m in range(0, 2):\n flag2, sin_edge_id = self.polyhedron.point_lies_on_singular_edges(edge_coords[m])\n if flag2:\n edge_locality = [3, sin_edge_id + self.nsc, m] # v_e-type\n edge_marked = True\n edges_locality.append(edge_locality)\n break\n\n if not edge_marked: # interior edge\n edge_locality = [1, 0]\n edge_marked = True\n edges_locality.append(edge_locality)\n\n child_vertices[k, :] = self.get_child_vertex(edges_locality[k], edge_coords)\n\n # loop over v-type elements and choose minimum weights, if an ev-type edge is present in the connected cells.\n mesh.init(0, 1) # Build connectivity between vertices and edges\n for k in range(0, num_edges):\n\n if edges_locality[k][0] == 2:\n\n edge = df.Edge(mesh, k)\n edge_vertices_id_global = edge.entities(0)\n edge_coords = vertices[edge_vertices_id_global]\n\n v0_id_local = edges_locality[k][2]\n v0_id_global = edge.entities(0)[v0_id_local]\n\n v0 = edge_coords[0]\n v1 = edge_coords[1]\n if v0_id_local == 1:\n v0 = edge_coords[1]\n v1 = edge_coords[0]\n\n # search if an edge connected to v0 is ev-type\n # if yes, then weight = min(kappa_v0, kappa_e)\n kappa_v0 = self.get_weight(edges_locality[k])\n weight = kappa_v0 # default\n\n # gather the connected edges\n vertex = df.Vertex(mesh, v0_id_global)\n connected_edges_id_global = vertex.entities(1)\n connected_edges_id_global = connected_edges_id_global.tolist()\n connected_edges_id_global.remove(k)\n # print(k, v0_id_global, connected_edges_id_global)\n\n # search for ev-type connected edges\n for j in range(0, len(connected_edges_id_global)):\n connected_edge = connected_edges_id_global[j]\n if edges_locality[connected_edge][0] == 4:\n connected_edge_locality = edges_locality[connected_edge]\n kappa_e = self.polyhedron.refine_weights[connected_edge_locality[2] - 1]\n weight = min(kappa_v0, kappa_e)\n # print(\"\\t\", connected_edge, kappa_v0, kappa_e, weight)\n break\n\n child_vertices[k, :] = v0 * (1 - weight) + v1 * weight\n\n # edge = df.Edge(mesh, k)\n # edge_vertices_id_global = edge.entities(0)\n # edge_coords = vertices[edge_vertices_id_global]\n # print(k, edge_locality, '\\n', edge_coords, '\\n', child_vertices[k,:], \"\\n\")\n\n return child_vertices\n\n # refines all the mesh cells\n # uses ufc numbering and info in cells_locality\n def refine(self, mesh, bool_quasiuniform):\n\n nn0 = mesh.num_vertices()\n vertices = mesh.coordinates()\n\n child_vertices = self.create_child_vertices(mesh, bool_quasiuniform)\n\n all_cells = np.zeros((self.ncc * mesh.num_cells(), self.nvc), dtype=np.uintp)\n for cell in df.cells(mesh):\n\n cell_id_global = cell.index()\n parent_v = cell.entities(0)\n parent_coords = vertices[parent_v]\n\n child_v = np.zeros(self.nec, dtype=np.uintp)\n child_coords = np.zeros((self.nec, self.ndim))\n id_local = 0\n for edge in df.edges(cell):\n child_v[id_local] = nn0 + edge.index()\n child_coords[id_local, :] = child_vertices[edge.index()]\n id_local += 1\n\n all_cells[self.ncc * cell_id_global: self.ncc * (cell_id_global + 1), :] \\\n = self.create_child_tetrahedrons(parent_v, parent_coords, child_v, child_coords)\n\n all_vertices = np.zeros((nn0 + child_vertices.shape[0], self.ndim))\n all_vertices[0: nn0, :] = vertices\n all_vertices[nn0:, :] = child_vertices\n\n return all_vertices, all_cells\n\n# End of file\n"
] |
[
[
"numpy.zeros"
]
] |
jiaxue1993/pytorch-material-classification
|
[
"e4a94794b0867abd7d20dfa3bfc8ecd74d5fa76f"
] |
[
"experiments/gtos.tean.mobilenet/network.py"
] |
[
"import torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\n\n\nclass TEAN(nn.Module):\n def __init__(self, nclass, model1, model2):\n super(TEAN, self).__init__()\n self.model1 = model1\n self.model2 = model2\n self.model1.classifier[1] = nn.Linear(128+128, num_classes)\n\n self.head = nn.Sequential(\n encoding.nn.Encoding(D=1280,K=n_codes),\n encoding.nn.View(-1, 1280*n_codes),\n encoding.nn.Normalize(),\n #nn.ReLU(inplace=True),\n nn.Linear(1280*n_codes, 64),\n nn.BatchNorm1d(64),\n )\n self.pool = nn.Sequential(\n nn.AvgPool2d(7),\n encoding.nn.View(-1, 1280),\n nn.Linear(1280, 64),\n nn.BatchNorm1d(64),\n )\n self.fc = nn.Sequential(\n encoding.nn.Normalize(),\n #nn.ReLU(inplace=True),\n nn.Linear(64*64, 128),\n encoding.nn.Normalize(),\n )\n self.pool2 = nn.Sequential(\n nn.AvgPool2d(7),\n encoding.nn.View(-1, 1280),\n nn.Linear(1280, 128),\n nn.BatchNorm1d(128),\n )\n\n def forward(self, img, diff_img):\n # pre-trained ResNet feature\n img_f = self.model1.features(img)\n\n # differential angular feature\n diff_img_f = self.model2.features(diff_img)\n diff_img_f = img_f + diff_img_f\n diff_img_f = self.pool2(diff_img_f)\n\n # dep feature\n x1 = self.head(img_fea)\n x2 = self.pool(img_fea)\n x1 = x1.unsqueeze(1).expand(x1.size(0),x2.size(1),x1.size(-1))\n x = x1*x2.unsqueeze(-1)\n enc_fea = x.view(-1,x1.size(-1)*x2.size(1))\n enc_fea = self.fc(enc_fea)\n\n # TEAN head\n out = torch.cat((enc_fea, ang_fea), dim=1)\n out = self.model1.classifier(out)\n\n return out\n\n\ndef test():\n net = TEAN(nclass=23).cuda()\n print(net)\n x = Variable(torch.randn(1,3,224,224)).cuda()\n y = net(x)\n print(y)\n params = net.parameters()\n sum = 0\n for param in params:\n sum += param.nelement()\n print('Total params:', sum)\n\n\nif __name__ == \"__main__\":\n test()\n"
] |
[
[
"torch.nn.Linear",
"torch.cat",
"torch.nn.AvgPool2d",
"torch.nn.BatchNorm1d",
"torch.randn"
]
] |
JunyeonL/square-attack
|
[
"624d053baa24084bce61999377db5976dd940e4f"
] |
[
"madry_cifar10/pgd_attack.py"
] |
[
"\"\"\"\r\nImplementation of attack methods. Running this file as a program will\r\napply the attack to the model specified by the config file and store\r\nthe examples in an .npy file.\r\n\"\"\"\r\nfrom __future__ import absolute_import\r\nfrom __future__ import division\r\nfrom __future__ import print_function\r\n\r\nimport tensorflow as tf\r\nimport numpy as np\r\n\r\nimport cifar10_input\r\n\r\n\r\nclass LinfPGDAttack:\r\n def __init__(self, model, epsilon, num_steps, step_size, random_start, loss_func):\r\n \"\"\"Attack parameter initialization. The attack performs k steps of\r\n size a, while always staying within epsilon from the initial\r\n point.\"\"\"\r\n self.model = model\r\n self.epsilon = epsilon\r\n self.num_steps = num_steps\r\n self.step_size = step_size\r\n self.rand = random_start\r\n\r\n if loss_func == 'xent':\r\n loss = model.xent\r\n elif loss_func == 'cw':\r\n label_mask = tf.one_hot(model.y_input,\r\n 10,\r\n on_value=1.0,\r\n off_value=0.0,\r\n dtype=tf.float32)\r\n correct_logit = tf.reduce_sum(label_mask * model.pre_softmax, axis=1)\r\n wrong_logit = tf.reduce_max((1 - label_mask) * model.pre_softmax - 1e4 * label_mask, axis=1)\r\n loss = -tf.nn.relu(correct_logit - wrong_logit + 50)\r\n else:\r\n print('Unknown loss function. Defaulting to cross-entropy')\r\n loss = model.xent\r\n\r\n self.grad = tf.gradients(loss, model.x_input)[0]\r\n\r\n def perturb(self, x_nat, y, sess):\r\n \"\"\"Given a set of examples (x_nat, y), returns a set of adversarial\r\n examples within epsilon of x_nat in l_infinity norm.\"\"\"\r\n if self.rand:\r\n x = x_nat + np.random.uniform(-self.epsilon, self.epsilon, x_nat.shape)\r\n x = np.clip(x, 0, 255) # ensure valid pixel range\r\n else:\r\n x = np.copy(x_nat)\r\n\r\n for i in range(self.num_steps):\r\n grad = sess.run(self.grad, feed_dict={self.model.x_input: x,\r\n self.model.y_input: y})\r\n\r\n x = np.add(x, self.step_size * np.sign(grad), out=x, casting='unsafe')\r\n\r\n x = np.clip(x, x_nat - self.epsilon, x_nat + self.epsilon)\r\n x = np.clip(x, 0, 255) # ensure valid pixel range\r\n\r\n return x\r\n\r\n\r\nif __name__ == '__main__':\r\n import json\r\n import sys\r\n import math\r\n\r\n from model import Model\r\n\r\n with open('config.json') as config_file:\r\n config = json.load(config_file)\r\n\r\n model_file = tf.train.latest_checkpoint(config['model_dir'])\r\n if model_file is None:\r\n print('No model found')\r\n sys.exit()\r\n\r\n model = Model(mode='eval')\r\n attack = LinfPGDAttack(model,\r\n config['epsilon'],\r\n config['num_steps'],\r\n config['step_size'],\r\n config['random_start'],\r\n config['loss_func'])\r\n saver = tf.train.Saver()\r\n\r\n data_path = config['data_path']\r\n cifar = cifar10_input.CIFAR10Data(data_path)\r\n\r\n gpu_options = tf.GPUOptions(visible_device_list='7', per_process_gpu_memory_fraction=0.5)\r\n tf_config = tf.ConfigProto(allow_soft_placement=True, gpu_options=gpu_options)\r\n with tf.Session(config=tf_config) as sess:\r\n # Restore the checkpoint\r\n saver.restore(sess, model_file)\r\n\r\n # Iterate over the samples batch-by-batch\r\n num_eval_examples = config['num_eval_examples']\r\n eval_batch_size = config['eval_batch_size']\r\n num_batches = int(math.ceil(num_eval_examples / eval_batch_size))\r\n\r\n x_adv = [] # adv accumulator\r\n\r\n print('Iterating over {} batches'.format(num_batches))\r\n\r\n for ibatch in range(num_batches):\r\n bstart = ibatch * eval_batch_size\r\n bend = min(bstart + eval_batch_size, num_eval_examples)\r\n print('batch size: {}'.format(bend - bstart))\r\n\r\n x_batch = cifar.eval_data.xs[bstart:bend, :]\r\n y_batch = cifar.eval_data.ys[bstart:bend]\r\n\r\n x_batch_adv = attack.perturb(x_batch, y_batch, sess)\r\n\r\n x_adv.append(x_batch_adv)\r\n\r\n print('Storing examples')\r\n path = config['store_adv_path']\r\n x_adv = np.concatenate(x_adv, axis=0)\r\n np.save(path, x_adv)\r\n print('Examples stored in {}'.format(path))\r\n"
] |
[
[
"numpy.concatenate",
"tensorflow.train.latest_checkpoint",
"tensorflow.nn.relu",
"numpy.copy",
"tensorflow.Session",
"tensorflow.train.Saver",
"numpy.save",
"tensorflow.gradients",
"tensorflow.ConfigProto",
"tensorflow.reduce_max",
"numpy.random.uniform",
"numpy.sign",
"tensorflow.reduce_sum",
"numpy.clip",
"tensorflow.one_hot",
"tensorflow.GPUOptions"
]
] |
xu-peng-tao/SSD-Pruning-and-quantization
|
[
"64b84dfa88a1686593addaa9941cc14579e129ee"
] |
[
"quantization/WbWtAb/models/nin_gc.py"
] |
[
"import torch.nn as nn\nfrom .util_wt_bab import activation_bin, Conv2d_Q\n\n# 通道混合\ndef channel_shuffle(x, groups):\n \"\"\"shuffle channels of a 4-D Tensor\"\"\"\n batch_size, channels, height, width = x.size()\n assert channels % groups == 0\n channels_per_group = channels // groups\n # split into groups\n x = x.view(batch_size, groups, channels_per_group, height, width)\n # transpose 1, 2 axis\n x = x.transpose(1, 2).contiguous()\n # reshape into orignal\n x = x.view(batch_size, channels, height, width)\n return x\n\n# ********************* 量化(三/二值)模块 ************************\nclass Tnn_Bin_Conv2d(nn.Module):\n # 参数:groups-卷积分组数、channel_shuffle-通道混合标志、shuffle_groups-通道混合数(本层需与上一层分组数保持一致)、last_relu|last_bin-尾层卷积输入是否二值(二值:last_relu=0,last_bin=1)\n def __init__(self, input_channels, output_channels,\n kernel_size=-1, stride=-1, padding=-1, groups=1, channel_shuffle=0, shuffle_groups=1, A=2, W=2, last_relu=0, last_bin=0):\n super(Tnn_Bin_Conv2d, self).__init__()\n self.channel_shuffle_flag = channel_shuffle\n self.shuffle_groups = shuffle_groups\n self.last_relu = last_relu\n self.last_bin = last_bin\n \n # ********************* 量化(三/二值)卷积 *********************\n self.tnn_bin_conv = Conv2d_Q(input_channels, output_channels,\n kernel_size=kernel_size, stride=stride, padding=padding, groups=groups, A=A, W=W)\n self.bn = nn.BatchNorm2d(output_channels)\n self.relu = nn.ReLU(inplace=True)\n self.bin_a = activation_bin(A=A)\n \n def forward(self, x):\n if self.channel_shuffle_flag:\n x = channel_shuffle(x, groups=self.shuffle_groups)\n x = self.tnn_bin_conv(x)\n x = self.bn(x)\n if self.last_relu:\n x = self.relu(x)\n if self.last_bin:\n x = self.bin_a(x)\n return x\n\nclass Net(nn.Module):\n def __init__(self, cfg = None, A=2, W=2):\n super(Net, self).__init__()\n # 模型结构与搭建\n if cfg is None:\n cfg = [256, 256, 256, 512, 512, 512, 1024, 1024]\n self.tnn_bin = nn.Sequential(\n nn.Conv2d(3, cfg[0], kernel_size=5, stride=1, padding=2),\n nn.BatchNorm2d(cfg[0]),\n Tnn_Bin_Conv2d(cfg[0], cfg[1], kernel_size=1, stride=1, padding=0, groups=2, channel_shuffle=0, A=A, W=W),\n Tnn_Bin_Conv2d(cfg[1], cfg[2], kernel_size=1, stride=1, padding=0, groups=2, channel_shuffle=1, shuffle_groups=2, A=A, W=W),\n nn.MaxPool2d(kernel_size=2, stride=2, padding=0),\n\n Tnn_Bin_Conv2d(cfg[2], cfg[3], kernel_size=3, stride=1, padding=1, groups=16, channel_shuffle=1, shuffle_groups=2, A=A, W=W),\n Tnn_Bin_Conv2d(cfg[3], cfg[4], kernel_size=1, stride=1, padding=0, groups=4, channel_shuffle=1, shuffle_groups=16, A=A, W=W),\n Tnn_Bin_Conv2d(cfg[4], cfg[5], kernel_size=1, stride=1, padding=0, groups=4, channel_shuffle=1, shuffle_groups=4, A=A, W=W),\n nn.MaxPool2d(kernel_size=2, stride=2, padding=0),\n\n Tnn_Bin_Conv2d(cfg[5], cfg[6], kernel_size=3, stride=1, padding=1, groups=32, channel_shuffle=1, shuffle_groups=4, A=A, W=W),\n Tnn_Bin_Conv2d(cfg[6], cfg[7], kernel_size=1, stride=1, padding=0, groups=8, channel_shuffle=1, shuffle_groups=32, A=A, W=W, last_relu=0, last_bin=1),#二值量化:last_relu=0, last_bin=1;全精度:last_relu=1, last_bin=0\n nn.Conv2d(cfg[7], 10, kernel_size=1, stride=1, padding=0),\n nn.BatchNorm2d(10),\n nn.ReLU(inplace=True),\n nn.AvgPool2d(kernel_size=8, stride=1, padding=0),\n )\n # 模型运行\n def forward(self, x):\n x = self.tnn_bin(x)\n x = x.view(x.size(0), -1)\n return x\n"
] |
[
[
"torch.nn.MaxPool2d",
"torch.nn.AvgPool2d",
"torch.nn.BatchNorm2d",
"torch.nn.ReLU",
"torch.nn.Conv2d"
]
] |
RScottLewis/WampumPy
|
[
"72ecfc6c90052aa76f61dea3cfee01174f9b4605"
] |
[
"lib/plot.py"
] |
[
"from PyQt5.QtGui import *\nfrom wampum.i18n import _\n\n\nimport datetime\nfrom collections import defaultdict\nfrom wampum.bitcoin import COIN\n\nimport matplotlib\nmatplotlib.use('Qt5Agg')\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as md\nfrom matplotlib.patches import Ellipse\nfrom matplotlib.offsetbox import AnchoredOffsetbox, TextArea, DrawingArea, HPacker\n\n\ndef plot_history(wallet, history):\n hist_in = defaultdict(int)\n hist_out = defaultdict(int)\n for item in history:\n tx_hash, height, confirmations, timestamp, value, balance = item\n if not confirmations:\n continue\n if timestamp is None:\n continue\n value = value*1./COIN\n date = datetime.datetime.fromtimestamp(timestamp)\n datenum = int(md.date2num(datetime.date(date.year, date.month, 1)))\n if value > 0:\n hist_in[datenum] += value\n else:\n hist_out[datenum] -= value\n\n f, axarr = plt.subplots(2, sharex=True)\n plt.subplots_adjust(bottom=0.2)\n plt.xticks( rotation=25 )\n ax = plt.gca()\n plt.ylabel('BTC')\n plt.xlabel('Month')\n xfmt = md.DateFormatter('%Y-%m-%d')\n ax.xaxis.set_major_formatter(xfmt)\n axarr[0].set_title('Monthly Volume')\n xfmt = md.DateFormatter('%Y-%m')\n ax.xaxis.set_major_formatter(xfmt)\n width = 20\n dates, values = zip(*sorted(hist_in.items()))\n r1 = axarr[0].bar(dates, values, width, label='incoming')\n axarr[0].legend(loc='upper left')\n dates, values = zip(*sorted(hist_out.items()))\n r2 = axarr[1].bar(dates, values, width, color='r', label='outgoing')\n axarr[1].legend(loc='upper left')\n return plt\n"
] |
[
[
"matplotlib.use",
"matplotlib.pyplot.xlabel",
"matplotlib.dates.DateFormatter",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.gca",
"matplotlib.pyplot.subplots_adjust",
"matplotlib.pyplot.xticks"
]
] |
yuanqing-wang/AFEP
|
[
"ef19148fa17bf89d0a61ad29a9510f822cd0c1db"
] |
[
"afep/test/test.py"
] |
[
"\n# coding: utf-8\n\n# In[25]:\n\n\n\"\"\"\ntest_yank_afep.py\n\n\"\"\"\nimport os\nimport sys\nimport numpy as np\nimport matplotlib\nfrom matplotlib import pyplot as plt\nimport pickle\n\nsys.path.append(\"..\")\n# /Users/yuanqingwang/Documents/GitHub/afep/afep/data/abl-imatinib/explicit/experiments/complex.nc\n\nfrom yank_afep_analyzer import YankAtomEnergyAnalyzer\nprint(\"import successful\")\nanalyzer = YankAtomEnergyAnalyzer(nc_path=os.path.abspath('../data/abl-imatinib/explicit/experiments/complex.nc'),\n nc_checkpoint_path=os.path.abspath('../data/abl-imatinib/explicit/experiments/complex_checkpoint.nc'))\nprint(\"initialize successful\")\n\n\n# In[ ]:\n\n\nanalyzer._analyze_atom_energies_with_all_checkpoint_positions()\n\n\n# In[ ]:\n\n\nlambda_shedule = analyzer.checkpoint_lambda_electrostatics_schedule\nprint(len(lambda_shedule))\n\n\n# In[ ]:\n\n\nligand_atoms = topography.solute_atoms\nprint(ligand_atoms)\ntopology = topography.topology\natoms = list(topology.atoms)\ntags = []\nfor atom in ligand_atoms:\n print(atom, atoms[atom])\n tags.append(str(atoms[atom]))\n\n\n# In[ ]:\n\n\nanalyzer._average_free_energy_weights_by_state(1,18)\n\n\n# In[ ]:\n\n\nenergies_diff_matrix = []\nfor idx in range(len(lambda_schedule)):\n energies_diff = analyzer._average_free_energy_weights_by_state(idx + 1, idx + 2)\n energies_diff_matrix.append(energies_diff)\nenergies_diff_matrix = np.array(energies_diff_matrix)\npickle.dump(energies_diff_matrix, open('m.p', 'wb'))\nprint(energies_diff_matrix)\nprint(np.sum(energies_diff_matrix, axis=1))\n\n\n# In[ ]:\n\n\nplt.clf()\nfor idx in range(len(ligand_atoms)):\n tag = tags[idx]\n x = np.array(range(17))\n y = energies_diff_matrix[:, idx]\n plt.plot(x, y, label=tag)\nplt.legend()\nplt.show()\n"
] |
[
[
"numpy.array",
"numpy.sum",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.show",
"matplotlib.pyplot.clf"
]
] |
rylaw/mne-python
|
[
"aa526c8ed7049046734ca28493d99e841672b0eb",
"aa526c8ed7049046734ca28493d99e841672b0eb",
"aa526c8ed7049046734ca28493d99e841672b0eb",
"aa526c8ed7049046734ca28493d99e841672b0eb",
"aa526c8ed7049046734ca28493d99e841672b0eb"
] |
[
"mne/preprocessing/nirs/_beer_lambert_law.py",
"mne/utils/mixin.py",
"mne/io/ctf_comp.py",
"mne/preprocessing/nirs/_scalp_coupling_index.py",
"mne/minimum_norm/_eloreta.py"
] |
[
"# Authors: Robert Luke <mail@robertluke.net>\n# Eric Larson <larson.eric.d@gmail.com>\n# Alexandre Gramfort <alexandre.gramfort@inria.fr>\n#\n# License: BSD (3-clause)\n\nimport os.path as op\n\nimport numpy as np\n\nfrom ...io import BaseRaw\nfrom ...io.constants import FIFF\nfrom ...utils import _validate_type\nfrom ..nirs import source_detector_distances, _channel_frequencies,\\\n _check_channels_ordered, _channel_chromophore\n\n\ndef beer_lambert_law(raw, ppf=0.1):\n r\"\"\"Convert NIRS optical density data to haemoglobin concentration.\n\n Parameters\n ----------\n raw : instance of Raw\n The optical density data.\n ppf : float\n The partial pathlength factor.\n\n Returns\n -------\n raw : instance of Raw\n The modified raw instance.\n \"\"\"\n from scipy import linalg\n raw = raw.copy().load_data()\n _validate_type(raw, BaseRaw, 'raw')\n\n freqs = np.unique(_channel_frequencies(raw.info))\n picks = _check_channels_ordered(raw.info, freqs)\n abs_coef = _load_absorption(freqs)\n distances = source_detector_distances(raw.info)\n\n for ii in picks[::2]:\n\n EL = abs_coef * distances[ii] * ppf\n iEL = linalg.pinv(EL)\n\n raw._data[[ii, ii + 1]] = iEL @ raw._data[[ii, ii + 1]] * 1e-3\n\n # Update channel information\n coil_dict = dict(hbo=FIFF.FIFFV_COIL_FNIRS_HBO,\n hbr=FIFF.FIFFV_COIL_FNIRS_HBR)\n for ki, kind in enumerate(('hbo', 'hbr')):\n ch = raw.info['chs'][ii + ki]\n ch.update(coil_type=coil_dict[kind], unit=FIFF.FIFF_UNIT_MOL)\n raw.rename_channels({\n ch['ch_name']: '%s %s' % (ch['ch_name'][:-4], kind)})\n\n # Validate the format of data after transformation is valid\n chroma = np.unique(_channel_chromophore(raw.info))\n _check_channels_ordered(raw.info, chroma)\n return raw\n\n\ndef _load_absorption(freqs):\n \"\"\"Load molar extinction coefficients.\"\"\"\n # Data from https://omlc.org/spectra/hemoglobin/summary.html\n # The text was copied to a text file. The text before and\n # after the table was deleted. The the following was run in\n # matlab\n # extinct_coef=importdata('extinction_coef.txt')\n # save('extinction_coef.mat', 'extinct_coef')\n #\n # Returns data as [[HbO2(freq1), Hb(freq1)],\n # [HbO2(freq2), Hb(freq2)]]\n from scipy.io import loadmat\n from scipy.interpolate import interp1d\n\n extinction_fname = op.join(op.dirname(__file__), '..', '..', 'data',\n 'extinction_coef.mat')\n a = loadmat(extinction_fname)['extinct_coef']\n\n interp_hbo = interp1d(a[:, 0], a[:, 1], kind='linear')\n interp_hb = interp1d(a[:, 0], a[:, 2], kind='linear')\n\n ext_coef = np.array([[interp_hbo(freqs[0]), interp_hb(freqs[0])],\n [interp_hbo(freqs[1]), interp_hb(freqs[1])]])\n abs_coef = ext_coef * 0.2303\n\n return abs_coef\n",
"# -*- coding: utf-8 -*-\n\"\"\"Some utility functions.\"\"\"\n# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>\n#\n# License: BSD (3-clause)\n\nfrom collections import OrderedDict\nfrom copy import deepcopy\nimport logging\nimport json\n\nimport numpy as np\n\nfrom .check import _check_pandas_installed, _check_preload, _validate_type\nfrom ._logging import warn, verbose\nfrom .numerics import object_size, object_hash\n\n\nlogger = logging.getLogger('mne') # one selection here used across mne-python\nlogger.propagate = False # don't propagate (in case of multiple imports)\n\n\nclass SizeMixin(object):\n \"\"\"Estimate MNE object sizes.\"\"\"\n\n def __eq__(self, other):\n \"\"\"Compare self to other.\n\n Parameters\n ----------\n other : object\n The object to compare to.\n\n Returns\n -------\n eq : bool\n True if the two objects are equal.\n \"\"\"\n return isinstance(other, type(self)) and hash(self) == hash(other)\n\n @property\n def _size(self):\n \"\"\"Estimate the object size.\"\"\"\n try:\n size = object_size(self.info)\n except Exception:\n warn('Could not get size for self.info')\n return -1\n if hasattr(self, 'data'):\n size += object_size(self.data)\n elif hasattr(self, '_data'):\n size += object_size(self._data)\n return size\n\n def __hash__(self):\n \"\"\"Hash the object.\n\n Returns\n -------\n hash : int\n The hash\n \"\"\"\n from ..evoked import Evoked\n from ..epochs import BaseEpochs\n from ..io.base import BaseRaw\n if isinstance(self, Evoked):\n return object_hash(dict(info=self.info, data=self.data))\n elif isinstance(self, (BaseEpochs, BaseRaw)):\n _check_preload(self, \"Hashing \")\n return object_hash(dict(info=self.info, data=self._data))\n else:\n raise RuntimeError('Hashing unknown object type: %s' % type(self))\n\n\nclass GetEpochsMixin(object):\n \"\"\"Class to add epoch selection and metadata to certain classes.\"\"\"\n\n def __getitem__(self, item):\n \"\"\"Return an Epochs object with a copied subset of epochs.\n\n Parameters\n ----------\n item : slice, array-like, str, or list\n See below for use cases.\n\n Returns\n -------\n epochs : instance of Epochs\n See below for use cases.\n\n Notes\n -----\n Epochs can be accessed as ``epochs[...]`` in several ways:\n\n 1. **Integer or slice:** ``epochs[idx]`` will return an `~mne.Epochs`\n object with a subset of epochs chosen by index (supports single\n index and Python-style slicing).\n\n 2. **String:** ``epochs['name']`` will return an `~mne.Epochs` object\n comprising only the epochs labeled ``'name'`` (i.e., epochs created\n around events with the label ``'name'``).\n\n If there are no epochs labeled ``'name'`` but there are epochs\n labeled with /-separated tags (e.g. ``'name/left'``,\n ``'name/right'``), then ``epochs['name']`` will select the epochs\n with labels that contain that tag (e.g., ``epochs['left']`` selects\n epochs labeled ``'audio/left'`` and ``'visual/left'``, but not\n ``'audio_left'``).\n\n If multiple tags are provided *as a single string* (e.g.,\n ``epochs['name_1/name_2']``), this selects epochs containing *all*\n provided tags. For example, ``epochs['audio/left']`` selects\n ``'audio/left'`` and ``'audio/quiet/left'``, but not\n ``'audio/right'``. Note that tag-based selection is insensitive to\n order: tags like ``'audio/left'`` and ``'left/audio'`` will be\n treated the same way when selecting via tag.\n\n 3. **List of strings:** ``epochs[['name_1', 'name_2', ... ]]`` will\n return an `~mne.Epochs` object comprising epochs that match *any* of\n the provided names (i.e., the list of names is treated as an\n inclusive-or condition). If *none* of the provided names match any\n epoch labels, a ``KeyError`` will be raised.\n\n If epoch labels are /-separated tags, then providing multiple tags\n *as separate list entries* will likewise act as an inclusive-or\n filter. For example, ``epochs[['audio', 'left']]`` would select\n ``'audio/left'``, ``'audio/right'``, and ``'visual/left'``, but not\n ``'visual/right'``.\n\n 4. **Pandas query:** ``epochs['pandas query']`` will return an\n `~mne.Epochs` object with a subset of epochs (and matching\n metadata) selected by the query called with\n ``self.metadata.eval``, e.g.::\n\n epochs[\"col_a > 2 and col_b == 'foo'\"]\n\n would return all epochs whose associated ``col_a`` metadata was\n greater than two, and whose ``col_b`` metadata was the string 'foo'.\n Query-based indexing only works if Pandas is installed and\n ``self.metadata`` is a :class:`pandas.DataFrame`.\n\n .. versionadded:: 0.16\n \"\"\"\n return self._getitem(item)\n\n def _item_to_select(self, item):\n if isinstance(item, str):\n item = [item]\n\n # Convert string to indices\n if isinstance(item, (list, tuple)) and len(item) > 0 and \\\n isinstance(item[0], str):\n select = self._keys_to_idx(item)\n elif isinstance(item, slice):\n select = item\n else:\n select = np.atleast_1d(item)\n if len(select) == 0:\n select = np.array([], int)\n return select\n\n def _getitem(self, item, reason='IGNORED', copy=True, drop_event_id=True,\n select_data=True, return_indices=False):\n \"\"\"\n Select epochs from current object.\n\n Parameters\n ----------\n item: slice, array-like, str, or list\n see `__getitem__` for details.\n reason: str\n entry in `drop_log` for unselected epochs\n copy: bool\n return a copy of the current object\n drop_event_id: bool\n remove non-existing event-ids after selection\n select_data: bool\n apply selection to data\n (use `select_data=False` if subclasses do not have a\n valid `_data` field, or data has already been subselected)\n return_indices: bool\n return the indices of selected epochs from the original object\n in addition to the new `Epochs` objects\n Returns\n -------\n `Epochs` or tuple(Epochs, np.ndarray) if `return_indices` is True\n subset of epochs (and optionally array with kept epoch indices)\n \"\"\"\n data = self._data\n del self._data\n inst = self.copy() if copy else self\n self._data = inst._data = data\n del self\n\n select = inst._item_to_select(item)\n has_selection = hasattr(inst, 'selection')\n if has_selection:\n key_selection = inst.selection[select]\n drop_log = list(inst.drop_log)\n if reason is not None:\n for k in np.setdiff1d(inst.selection, key_selection):\n drop_log[k] = (reason,)\n inst.drop_log = tuple(drop_log)\n inst.selection = key_selection\n del drop_log\n\n inst.events = np.atleast_2d(inst.events[select])\n if inst.metadata is not None:\n pd = _check_pandas_installed(strict=False)\n if pd:\n metadata = inst.metadata.iloc[select]\n if has_selection:\n metadata.index = inst.selection\n else:\n metadata = np.array(inst.metadata, 'object')[select].tolist()\n\n # will reset the index for us\n GetEpochsMixin.metadata.fset(inst, metadata, verbose=False)\n if inst.preload and select_data:\n # ensure that each Epochs instance owns its own data so we can\n # resize later if necessary\n inst._data = np.require(inst._data[select], requirements=['O'])\n if drop_event_id:\n # update event id to reflect new content of inst\n inst.event_id = {k: v for k, v in inst.event_id.items()\n if v in inst.events[:, 2]}\n\n if return_indices:\n return inst, select\n else:\n return inst\n\n def _keys_to_idx(self, keys):\n \"\"\"Find entries in event dict.\"\"\"\n keys = keys if isinstance(keys, (list, tuple)) else [keys]\n try:\n # Assume it's a condition name\n return np.where(np.any(\n np.array([self.events[:, 2] == self.event_id[k]\n for k in _hid_match(self.event_id, keys)]),\n axis=0))[0]\n except KeyError as err:\n # Could we in principle use metadata with these Epochs and keys?\n if (len(keys) != 1 or self.metadata is None):\n # If not, raise original error\n raise\n msg = str(err.args[0]) # message for KeyError\n pd = _check_pandas_installed(strict=False)\n # See if the query can be done\n if pd:\n md = self.metadata if hasattr(self, '_metadata') else None\n self._check_metadata(metadata=md)\n try:\n # Try metadata\n mask = self.metadata.eval(keys[0], engine='python').values\n except Exception as exp:\n msg += (' The epochs.metadata Pandas query did not '\n 'yield any results: %s' % (exp.args[0],))\n else:\n return np.where(mask)[0]\n else:\n # If not, warn this might be a problem\n msg += (' The epochs.metadata Pandas query could not '\n 'be performed, consider installing Pandas.')\n raise KeyError(msg)\n\n def __len__(self):\n \"\"\"Return the number of epochs.\n\n Returns\n -------\n n_epochs : int\n The number of remaining epochs.\n\n Notes\n -----\n This function only works if bad epochs have been dropped.\n\n Examples\n --------\n This can be used as::\n\n >>> epochs.drop_bad() # doctest: +SKIP\n >>> len(epochs) # doctest: +SKIP\n 43\n >>> len(epochs.events) # doctest: +SKIP\n 43\n \"\"\"\n from ..epochs import BaseEpochs\n if isinstance(self, BaseEpochs) and not self._bad_dropped:\n raise RuntimeError('Since bad epochs have not been dropped, the '\n 'length of the Epochs is not known. Load the '\n 'Epochs with preload=True, or call '\n 'Epochs.drop_bad(). To find the number '\n 'of events in the Epochs, use '\n 'len(Epochs.events).')\n return len(self.events)\n\n def __iter__(self):\n \"\"\"Facilitate iteration over epochs.\n\n This method resets the object iteration state to the first epoch.\n\n Notes\n -----\n This enables the use of this Python pattern::\n\n >>> for epoch in epochs: # doctest: +SKIP\n >>> print(epoch) # doctest: +SKIP\n\n Where ``epoch`` is given by successive outputs of\n :meth:`mne.Epochs.next`.\n \"\"\"\n self._current = 0\n self._current_detrend_picks = self._detrend_picks\n return self\n\n def __next__(self, return_event_id=False):\n \"\"\"Iterate over epoch data.\n\n Parameters\n ----------\n return_event_id : bool\n If True, return both the epoch data and an event_id.\n\n Returns\n -------\n epoch : array of shape (n_channels, n_times)\n The epoch data.\n event_id : int\n The event id. Only returned if ``return_event_id`` is ``True``.\n \"\"\"\n if not hasattr(self, '_current_detrend_picks'):\n self.__iter__() # ensure we're ready to iterate\n if self.preload:\n if self._current >= len(self._data):\n self._stop_iter()\n epoch = self._data[self._current]\n self._current += 1\n else:\n is_good = False\n while not is_good:\n if self._current >= len(self.events):\n self._stop_iter()\n epoch_noproj = self._get_epoch_from_raw(self._current)\n epoch_noproj = self._detrend_offset_decim(\n epoch_noproj, self._current_detrend_picks)\n epoch = self._project_epoch(epoch_noproj)\n self._current += 1\n is_good, _ = self._is_good_epoch(epoch)\n # If delayed-ssp mode, pass 'virgin' data after rejection decision.\n if self._do_delayed_proj:\n epoch = epoch_noproj\n\n if not return_event_id:\n return epoch\n else:\n return epoch, self.events[self._current - 1][-1]\n\n def _stop_iter(self):\n del self._current\n del self._current_detrend_picks\n raise StopIteration # signal the end\n\n next = __next__ # originally for Python2, now b/c public\n\n def _check_metadata(self, metadata=None, reset_index=False):\n \"\"\"Check metadata consistency.\"\"\"\n # reset_index=False will not copy!\n if metadata is None:\n return\n else:\n pd = _check_pandas_installed(strict=False)\n if pd:\n _validate_type(metadata, types=pd.DataFrame,\n item_name='metadata')\n if len(metadata) != len(self.events):\n raise ValueError('metadata must have the same number of '\n 'rows (%d) as events (%d)'\n % (len(metadata), len(self.events)))\n if reset_index:\n if hasattr(self, 'selection'):\n # makes a copy\n metadata = metadata.reset_index(drop=True)\n metadata.index = self.selection\n else:\n metadata = deepcopy(metadata)\n else:\n _validate_type(metadata, types=list,\n item_name='metadata')\n if reset_index:\n metadata = deepcopy(metadata)\n return metadata\n\n @property\n def metadata(self):\n \"\"\"Get the metadata.\"\"\"\n return self._metadata\n\n @metadata.setter\n @verbose\n def metadata(self, metadata, verbose=None):\n metadata = self._check_metadata(metadata, reset_index=True)\n if metadata is not None:\n if _check_pandas_installed(strict=False):\n n_col = metadata.shape[1]\n else:\n n_col = len(metadata[0])\n n_col = ' with %d columns' % n_col\n else:\n n_col = ''\n if hasattr(self, '_metadata') and self._metadata is not None:\n action = 'Removing' if metadata is None else 'Replacing'\n action += ' existing'\n else:\n action = 'Not setting' if metadata is None else 'Adding'\n logger.info('%s metadata%s' % (action, n_col))\n self._metadata = metadata\n\n\ndef _prepare_write_metadata(metadata):\n \"\"\"Convert metadata to JSON for saving.\"\"\"\n if metadata is not None:\n if not isinstance(metadata, list):\n metadata = metadata.to_json(orient='records')\n else: # Pandas DataFrame\n metadata = json.dumps(metadata)\n assert isinstance(metadata, str)\n return metadata\n\n\ndef _prepare_read_metadata(metadata):\n \"\"\"Convert saved metadata back from JSON.\"\"\"\n if metadata is not None:\n pd = _check_pandas_installed(strict=False)\n # use json.loads because this preserves ordering\n # (which is necessary for round-trip equivalence)\n metadata = json.loads(metadata, object_pairs_hook=OrderedDict)\n assert isinstance(metadata, list)\n if pd:\n metadata = pd.DataFrame.from_records(metadata)\n assert isinstance(metadata, pd.DataFrame)\n return metadata\n\n\ndef _hid_match(event_id, keys):\n \"\"\"Match event IDs using HID selection.\n\n Parameters\n ----------\n event_id : dict\n The event ID dictionary.\n keys : list | str\n The event ID or subset (for HID), or list of such items.\n\n Returns\n -------\n use_keys : list\n The full keys that fit the selection criteria.\n \"\"\"\n # form the hierarchical event ID mapping\n use_keys = []\n for key in keys:\n if not isinstance(key, str):\n raise KeyError('keys must be strings, got %s (%s)'\n % (type(key), key))\n use_keys.extend(k for k in event_id.keys()\n if set(key.split('/')).issubset(k.split('/')))\n if len(use_keys) == 0:\n raise KeyError('Event \"{}\" is not in Epochs. Event_ids must be one of '\n '\"{}\"'.format(key, ', '.join(event_id.keys())))\n use_keys = list(set(use_keys)) # deduplicate if necessary\n return use_keys\n\n\nclass _FakeNoPandas(object): # noqa: D101\n def __enter__(self): # noqa: D105\n\n def _check(strict=True):\n if strict:\n raise RuntimeError('Pandas not installed')\n else:\n return False\n\n import mne\n self._old_check = _check_pandas_installed\n mne.epochs._check_pandas_installed = _check\n mne.utils.mixin._check_pandas_installed = _check\n\n def __exit__(self, *args): # noqa: D105\n import mne\n mne.epochs._check_pandas_installed = self._old_check\n mne.utils.mixin._check_pandas_installed = self._old_check\n\n\nclass ShiftTimeMixin(object):\n \"\"\"Class for shift_time method (Epochs, Evoked, and DipoleFixed).\"\"\"\n\n def shift_time(self, tshift, relative=True):\n \"\"\"Shift time scale in epoched or evoked data.\n\n Parameters\n ----------\n tshift : float\n The (absolute or relative) time shift in seconds. If ``relative``\n is True, positive tshift increases the time value associated with\n each sample, while negative tshift decreases it.\n relative : bool\n If True, increase or decrease time values by ``tshift`` seconds.\n Otherwise, shift the time values such that the time of the first\n sample equals ``tshift``.\n\n Returns\n -------\n epochs : instance of Epochs\n The modified Epochs instance.\n\n Notes\n -----\n This method allows you to shift the *time* values associated with each\n data sample by an arbitrary amount. It does *not* resample the signal\n or change the *data* values in any way.\n \"\"\"\n from ..epochs import BaseEpochs\n _check_preload(self, 'shift_time')\n start = tshift + (self.times[0] if relative else 0.)\n new_times = start + np.arange(len(self.times)) / self.info['sfreq']\n if isinstance(self, BaseEpochs):\n self._set_times(new_times)\n else:\n self.times = new_times\n self._update_first_last()\n return self\n\n def _update_first_last(self):\n \"\"\"Update self.first and self.last (sample indices).\"\"\"\n self.first = int(round(self.times[0] * self.info['sfreq']))\n self.last = len(self.times) + self.first - 1\n",
"# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>\n# Matti Hämäläinen <msh@nmr.mgh.harvard.edu>\n# Denis Engemann <denis.engemann@gmail.com>\n#\n# License: BSD (3-clause)\n\nfrom copy import deepcopy\n\nimport numpy as np\n\nfrom .constants import FIFF\nfrom .tag import read_tag\nfrom .tree import dir_tree_find\nfrom .write import start_block, end_block, write_int\nfrom .matrix import write_named_matrix, _read_named_matrix\n\nfrom ..utils import logger, verbose, _pl\n\n\ndef _add_kind(one):\n \"\"\"Convert CTF kind to MNE kind.\"\"\"\n if one['ctfkind'] == int('47314252', 16):\n one['kind'] = 1\n elif one['ctfkind'] == int('47324252', 16):\n one['kind'] = 2\n elif one['ctfkind'] == int('47334252', 16):\n one['kind'] = 3\n else:\n one['kind'] = int(one['ctfkind'])\n\n\ndef _calibrate_comp(comp, chs, row_names, col_names,\n mult_keys=('range', 'cal'), flip=False):\n \"\"\"Get row and column cals.\"\"\"\n ch_names = [c['ch_name'] for c in chs]\n row_cals = np.zeros(len(row_names))\n col_cals = np.zeros(len(col_names))\n for names, cals, inv in zip((row_names, col_names), (row_cals, col_cals),\n (False, True)):\n for ii in range(len(cals)):\n p = ch_names.count(names[ii])\n if p != 1:\n raise RuntimeError('Channel %s does not appear exactly once '\n 'in data, found %d instance%s'\n % (names[ii], p, _pl(p)))\n idx = ch_names.index(names[ii])\n val = chs[idx][mult_keys[0]] * chs[idx][mult_keys[1]]\n val = float(1. / val) if inv else float(val)\n val = 1. / val if flip else val\n cals[ii] = val\n comp['rowcals'] = row_cals\n comp['colcals'] = col_cals\n comp['data']['data'] = (row_cals[:, None] *\n comp['data']['data'] * col_cals[None, :])\n\n\n@verbose\ndef read_ctf_comp(fid, node, chs, verbose=None):\n \"\"\"Read the CTF software compensation data from the given node.\n\n Parameters\n ----------\n fid : file\n The file descriptor.\n node : dict\n The node in the FIF tree.\n chs : list\n The list of channels from info['chs'] to match with\n compensators that are read.\n %(verbose)s\n\n Returns\n -------\n compdata : list\n The compensation data\n \"\"\"\n return _read_ctf_comp(fid, node, chs, None)\n\n\ndef _read_ctf_comp(fid, node, chs, ch_names_mapping):\n \"\"\"Read the CTF software compensation data from the given node.\n\n Parameters\n ----------\n fid : file\n The file descriptor.\n node : dict\n The node in the FIF tree.\n chs : list\n The list of channels from info['chs'] to match with\n compensators that are read.\n ch_names_mapping : dict | None\n The channel renaming to use.\n %(verbose)s\n\n Returns\n -------\n compdata : list\n The compensation data\n \"\"\"\n from .meas_info import _rename_comps\n ch_names_mapping = dict() if ch_names_mapping is None else ch_names_mapping\n compdata = []\n comps = dir_tree_find(node, FIFF.FIFFB_MNE_CTF_COMP_DATA)\n\n for node in comps:\n # Read the data we need\n mat = _read_named_matrix(fid, node, FIFF.FIFF_MNE_CTF_COMP_DATA)\n for p in range(node['nent']):\n kind = node['directory'][p].kind\n pos = node['directory'][p].pos\n if kind == FIFF.FIFF_MNE_CTF_COMP_KIND:\n tag = read_tag(fid, pos)\n break\n else:\n raise Exception('Compensation type not found')\n\n # Get the compensation kind and map it to a simple number\n one = dict(ctfkind=tag.data)\n del tag\n _add_kind(one)\n for p in range(node['nent']):\n kind = node['directory'][p].kind\n pos = node['directory'][p].pos\n if kind == FIFF.FIFF_MNE_CTF_COMP_CALIBRATED:\n tag = read_tag(fid, pos)\n calibrated = tag.data\n break\n else:\n calibrated = False\n\n one['save_calibrated'] = bool(calibrated)\n one['data'] = mat\n _rename_comps([one], ch_names_mapping)\n if not calibrated:\n # Calibrate...\n _calibrate_comp(one, chs, mat['row_names'], mat['col_names'])\n else:\n one['rowcals'] = np.ones(mat['data'].shape[0], dtype=np.float64)\n one['colcals'] = np.ones(mat['data'].shape[1], dtype=np.float64)\n\n compdata.append(one)\n\n if len(compdata) > 0:\n logger.info(' Read %d compensation matrices' % len(compdata))\n\n return compdata\n\n\n###############################################################################\n# Writing\n\ndef write_ctf_comp(fid, comps):\n \"\"\"Write the CTF compensation data into a fif file.\n\n Parameters\n ----------\n fid : file\n The open FIF file descriptor\n\n comps : list\n The compensation data to write\n \"\"\"\n if len(comps) <= 0:\n return\n\n # This is very simple in fact\n start_block(fid, FIFF.FIFFB_MNE_CTF_COMP)\n for comp in comps:\n start_block(fid, FIFF.FIFFB_MNE_CTF_COMP_DATA)\n # Write the compensation kind\n write_int(fid, FIFF.FIFF_MNE_CTF_COMP_KIND, comp['ctfkind'])\n if comp.get('save_calibrated', False):\n write_int(fid, FIFF.FIFF_MNE_CTF_COMP_CALIBRATED,\n comp['save_calibrated'])\n\n if not comp.get('save_calibrated', True):\n # Undo calibration\n comp = deepcopy(comp)\n data = ((1. / comp['rowcals'][:, None]) * comp['data']['data'] *\n (1. / comp['colcals'][None, :]))\n comp['data']['data'] = data\n write_named_matrix(fid, FIFF.FIFF_MNE_CTF_COMP_DATA, comp['data'])\n end_block(fid, FIFF.FIFFB_MNE_CTF_COMP_DATA)\n\n end_block(fid, FIFF.FIFFB_MNE_CTF_COMP)\n",
"# Authors: Robert Luke <mail@robertluke.net>\n# Eric Larson <larson.eric.d@gmail.com>\n# Alexandre Gramfort <alexandre.gramfort@inria.fr>\n#\n# License: BSD (3-clause)\n\nimport numpy as np\n\nfrom ... import pick_types\nfrom ...io import BaseRaw\nfrom ...utils import _validate_type, verbose\nfrom ..nirs import _channel_frequencies, _check_channels_ordered\nfrom ...filter import filter_data\n\n\n@verbose\ndef scalp_coupling_index(raw, l_freq=0.7, h_freq=1.5,\n l_trans_bandwidth=0.3, h_trans_bandwidth=0.3,\n verbose=False):\n r\"\"\"Calculate scalp coupling index.\n\n This function calculates the scalp coupling index\n :footcite:`pollonini2014auditory`. This is a measure of the quality of the\n connection between the optode and the scalp.\n\n Parameters\n ----------\n raw : instance of Raw\n The raw data.\n %(l_freq)s\n %(h_freq)s\n %(l_trans_bandwidth)s\n %(h_trans_bandwidth)s\n %(verbose)s\n\n Returns\n -------\n sci : array of float\n Array containing scalp coupling index for each channel.\n\n References\n ----------\n .. footbibliography::\n \"\"\"\n raw = raw.copy().load_data()\n _validate_type(raw, BaseRaw, 'raw')\n\n if not len(pick_types(raw.info, fnirs='fnirs_od')):\n raise RuntimeError('Scalp coupling index '\n 'should be run on optical density data.')\n\n freqs = np.unique(_channel_frequencies(raw.info))\n picks = _check_channels_ordered(raw.info, freqs)\n\n filtered_data = filter_data(raw._data, raw.info['sfreq'], l_freq, h_freq,\n picks=picks, verbose=verbose,\n l_trans_bandwidth=l_trans_bandwidth,\n h_trans_bandwidth=h_trans_bandwidth)\n\n sci = np.zeros(picks.shape)\n for ii in picks[::2]:\n c = np.corrcoef(filtered_data[ii], filtered_data[ii + 1])[0][1]\n sci[ii] = c\n sci[ii + 1] = c\n\n return sci\n",
"# Authors: Eric Larson <larson.eric.d@gmail.com>\n#\n# License: BSD (3-clause)\n\nfrom functools import partial\nimport numpy as np\n\nfrom ..defaults import _handle_default\nfrom ..fixes import _safe_svd\nfrom ..utils import warn, logger, sqrtm_sym, eigh\n\n\n# For the reference implementation of eLORETA (force_equal=False),\n# 0 < loose <= 1 all produce solutions that are (more or less)\n# the same as free orientation (loose=1) and quite different from\n# loose=0 (fixed). If we do force_equal=True, we get a visibly smooth\n# transition from 0->1. This is probably because this mode behaves more like\n# sLORETA and dSPM in that it weights each orientation for a given source\n# uniformly (which is not the case for the reference eLORETA implementation).\n#\n# If we *reapply the orientation prior* after each eLORETA iteration,\n# we can preserve the smooth transition without requiring force_equal=True,\n# which is probably more representative of what eLORETA should do. But this\n# does not produce results that pass the eye test.\n\ndef _compute_eloreta(inv, lambda2, options):\n \"\"\"Compute the eLORETA solution.\"\"\"\n from .inverse import compute_rank_inverse, _compute_reginv\n options = _handle_default('eloreta_options', options)\n eps, max_iter = options['eps'], options['max_iter']\n force_equal = bool(options['force_equal']) # None means False\n\n # Reassemble the gain matrix (should be fast enough)\n if inv['eigen_leads_weighted']:\n # We can probably relax this if we ever need to\n raise RuntimeError('eLORETA cannot be computed with weighted eigen '\n 'leads')\n G = np.dot(inv['eigen_fields']['data'].T * inv['sing'],\n inv['eigen_leads']['data'].T)\n del inv['eigen_leads']['data']\n del inv['eigen_fields']['data']\n del inv['sing']\n G = G.astype(np.float64)\n n_nzero = compute_rank_inverse(inv)\n G /= np.sqrt(inv['source_cov']['data'])\n # restore orientation prior\n source_std = np.ones(G.shape[1])\n if inv['orient_prior'] is not None:\n source_std *= np.sqrt(inv['orient_prior']['data'])\n G *= source_std\n # We do not multiply by the depth prior, as eLORETA should compensate for\n # depth bias.\n n_src = inv['nsource']\n n_chan, n_orient = G.shape\n n_orient //= n_src\n assert n_orient in (1, 3)\n logger.info(' Computing optimized source covariance (eLORETA)...')\n if n_orient == 3:\n logger.info(' Using %s orientation weights'\n % ('uniform' if force_equal else 'independent',))\n # src, sens, 3\n G_3 = _get_G_3(G, n_orient)\n if n_orient != 1 and not force_equal:\n # Outer product\n R_prior = (source_std.reshape(n_src, 1, 3) *\n source_std.reshape(n_src, 3, 1))\n else:\n R_prior = source_std ** 2\n\n # The following was adapted under BSD license by permission of Guido Nolte\n if force_equal or n_orient == 1:\n R_shape = (n_src * n_orient,)\n R = np.ones(R_shape)\n else:\n R_shape = (n_src, n_orient, n_orient)\n R = np.empty(R_shape)\n R[:] = np.eye(n_orient)[np.newaxis]\n R *= R_prior\n _this_normalize_R = partial(\n _normalize_R, n_nzero=n_nzero, force_equal=force_equal,\n n_src=n_src, n_orient=n_orient)\n G_R_Gt = _this_normalize_R(G, R, G_3)\n extra = ' (this make take a while)' if n_orient == 3 else ''\n logger.info(' Fitting up to %d iterations%s...'\n % (max_iter, extra))\n for kk in range(max_iter):\n # 1. Compute inverse of the weights (stabilized) and C\n s, u = eigh(G_R_Gt)\n s = abs(s)\n sidx = np.argsort(s)[::-1][:n_nzero]\n s, u = s[sidx], u[:, sidx]\n with np.errstate(invalid='ignore'):\n s = np.where(s > 0, 1 / (s + lambda2), 0)\n N = np.dot(u * s, u.T)\n del s\n\n # Update the weights\n R_last = R.copy()\n if n_orient == 1:\n R[:] = 1. / np.sqrt((np.dot(N, G) * G).sum(0))\n else:\n M = np.matmul(np.matmul(G_3, N[np.newaxis]), G_3.swapaxes(-2, -1))\n if force_equal:\n _, s = sqrtm_sym(M, inv=True)\n R[:] = np.repeat(1. / np.mean(s, axis=-1), 3)\n else:\n R[:], _ = sqrtm_sym(M, inv=True)\n R *= R_prior # reapply our prior, eLORETA undoes it\n G_R_Gt = _this_normalize_R(G, R, G_3)\n\n # Check for weight convergence\n delta = (np.linalg.norm(R.ravel() - R_last.ravel()) /\n np.linalg.norm(R_last.ravel()))\n logger.debug(' Iteration %s / %s ...%s (%0.1e)'\n % (kk + 1, max_iter, extra, delta))\n if delta < eps:\n logger.info(' Converged on iteration %d (%0.2g < %0.2g)'\n % (kk, delta, eps))\n break\n else:\n warn('eLORETA weight fitting did not converge (>= %s)' % eps)\n del G_R_Gt\n logger.info(' Updating inverse with weighted eigen leads')\n G /= source_std # undo our biasing\n G_3 = _get_G_3(G, n_orient)\n _this_normalize_R(G, R, G_3)\n del G_3\n if n_orient == 1 or force_equal:\n R_sqrt = np.sqrt(R)\n else:\n R_sqrt = sqrtm_sym(R)[0]\n assert R_sqrt.shape == R_shape\n A = _R_sqrt_mult(G, R_sqrt)\n del R, G # the rest will be done in terms of R_sqrt and A\n eigen_fields, sing, eigen_leads = _safe_svd(A, full_matrices=False)\n del A\n inv['sing'] = sing\n inv['reginv'] = _compute_reginv(inv, lambda2)\n inv['eigen_leads_weighted'] = True\n inv['eigen_leads']['data'] = _R_sqrt_mult(eigen_leads, R_sqrt).T\n inv['eigen_fields']['data'] = eigen_fields.T\n # XXX in theory we should set inv['source_cov'] properly.\n # For fixed ori (or free ori with force_equal=True), we can as these\n # are diagonal matrices. But for free ori without force_equal, it's a\n # block diagonal 3x3 and we have no efficient way of storing this (and\n # storing a covariance matrix with (20484 * 3) ** 2 elements is not going\n # to work. So let's just set to nan for now.\n # It's not used downstream anyway now that we set\n # eigen_leads_weighted = True.\n inv['source_cov']['data'].fill(np.nan)\n logger.info('[done]')\n\n\ndef _normalize_R(G, R, G_3, n_nzero, force_equal, n_src, n_orient):\n \"\"\"Normalize R so that lambda2 is consistent.\"\"\"\n if n_orient == 1 or force_equal:\n R_Gt = R[:, np.newaxis] * G.T\n else:\n R_Gt = np.matmul(R, G_3).reshape(n_src * 3, -1)\n G_R_Gt = G @ R_Gt\n norm = np.trace(G_R_Gt) / n_nzero\n G_R_Gt /= norm\n R /= norm\n return G_R_Gt\n\n\ndef _get_G_3(G, n_orient):\n if n_orient == 1:\n return None\n else:\n return G.reshape(G.shape[0], -1, n_orient).transpose(1, 2, 0)\n\n\ndef _R_sqrt_mult(other, R_sqrt):\n \"\"\"Do other @ R ** 0.5.\"\"\"\n if R_sqrt.ndim == 1:\n assert other.shape[1] == R_sqrt.size\n out = R_sqrt * other\n else:\n assert R_sqrt.shape[1:3] == (3, 3)\n assert other.shape[1] == np.prod(R_sqrt.shape[:2])\n assert other.ndim == 2\n n_src = R_sqrt.shape[0]\n n_chan = other.shape[0]\n out = np.matmul(\n R_sqrt, other.reshape(n_chan, n_src, 3).transpose(1, 2, 0)\n ).reshape(n_src * 3, n_chan).T\n return out\n"
] |
[
[
"scipy.linalg.pinv",
"scipy.interpolate.interp1d",
"scipy.io.loadmat"
],
[
"numpy.array",
"numpy.setdiff1d",
"numpy.where",
"numpy.require",
"numpy.atleast_1d",
"numpy.atleast_2d"
],
[
"numpy.ones"
],
[
"numpy.corrcoef",
"numpy.zeros"
],
[
"numpy.dot",
"numpy.trace",
"numpy.empty",
"numpy.errstate",
"numpy.matmul",
"numpy.ones",
"numpy.mean",
"numpy.eye",
"numpy.where",
"numpy.prod",
"numpy.sqrt",
"numpy.argsort"
]
] |
s-sajid-ali/comsyl
|
[
"f2a5d984b1e870d203a9152bbeca804c4304850e"
] |
[
"comsyl/mathcomsyl/MatrixBuilder.py"
] |
[
"# coding: utf-8\n# /*##########################################################################\n#\n# Copyright (c) 2017 European Synchrotron Radiation Facility\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n#\n# ###########################################################################*/\n__authors__ = [\"M Glass - ESRF ISDD Advanced Analysis and Modelling\"]\n__license__ = \"MIT\"\n__date__ = \"20/04/2017\"\n\n\n\nimport numpy as np\nfrom petsc4py import PETSc\n\n\nfrom comsyl.parallel.utils import barrier\nfrom comsyl.parallel.DistributionPlan import DistributionPlan\nfrom comsyl.parallel.ParallelMatrix import ParallelMatrix\nfrom comsyl.parallel.ParallelMatrixPETSc import ParallelMatrixPETSc\n\nfrom comsyl.utils.Logger import log, logProgress\n\n\nclass MatrixBuilder(object):\n def __init__(self, coordinates_x, coordinates_y):\n self._coordinates_x = coordinates_x\n self._coordinates_y = coordinates_y\n self._mode_element_wise = False\n\n def productCoordinates(self):\n product_coordinates = np.zeros((len(self._coordinates_x)*len(self._coordinates_y),2))\n\n i_c = 0\n for x in self._coordinates_x:\n for y in self._coordinates_y:\n product_coordinates[i_c, 0] = x\n product_coordinates[i_c, 1] = y\n i_c += 1\n\n return product_coordinates\n\n def _createNumpyMatrix(self, f_gamma):\n product_coordinates=self.productCoordinates()\n work_matrix = np.zeros( (product_coordinates.shape[0],product_coordinates.shape[0]),dtype=np.complex128)\n\n product_coordinates=self.productCoordinates()\n\n n_coordinates = product_coordinates.shape[0]\n for i in range(n_coordinates):\n self._printProgress(n_coordinates, i)\n\n r_i = product_coordinates[i, :]\n for j in range(n_coordinates):\n r_j = product_coordinates[j, :]\n\n work_matrix[i, j] = f_gamma(r_i, r_j)\n\n return work_matrix\n\n def _createParallelMatrixPETSc(self, f_gamma):\n product_coordinates=self.productCoordinates()\n\n n_coordinates = product_coordinates.shape[0]\n\n n_rows=product_coordinates.shape[0]\n n_columns=product_coordinates.shape[0]\n petsc_matrix = PETSc.Mat().createDense([n_rows, n_columns])\n petsc_matrix.setUp()\n\n matrix = ParallelMatrixPETSc(petsc_matrix)\n distribution_plan = matrix.distributionPlan()\n\n if self._mode_element_wise:\n for i_row in distribution_plan.localRows():\n\n self._printProgress(n_coordinates, i_row)\n\n r_i = product_coordinates[i_row, :]\n for i_column in range(n_coordinates):\n\n r_j = product_coordinates[i_column, :]\n value = f_gamma(r_i, r_j)\n\n # TODO\n #raise NotImplementedError(\"Can only handle entire rows\")\n petsc_matrix[i_row, i_column] = value\n\n else:\n for i_row in distribution_plan.localRows():\n self._printProgress(len(distribution_plan.localRows()), i_row)\n\n r_i = product_coordinates[i_row, :]\n value = f_gamma(r_i)\n value = value.reshape(value.size).conj()\n\n matrix.setRow(global_index=i_row,\n content=value)\n\n log(\"Waiting for others\")\n barrier()\n log(\"done\")\n\n log(\"PETSc matrix assembling\")\n matrix.assemble()\n# matrix.transpose()\n log(\"done\")\n return matrix\n\n\n def _createParallelMatrix(self, f_gamma):\n log(\"Building matrix\")\n return self._createParallelMatrixPETSc(f_gamma)\n\n product_coordinates=self.productCoordinates()\n\n n_coordinates = product_coordinates.shape[0]\n\n distribution_plan = DistributionPlan(communicator=mpi.COMM_WORLD,\n n_rows=product_coordinates.shape[0],\n n_columns=product_coordinates.shape[0])\n\n matrix = ParallelMatrix(distribution_plan=distribution_plan)\n\n if self._mode_element_wise:\n for i_row in distribution_plan.localRows():\n\n self._printProgress(n_coordinates, i_row)\n\n r_i = product_coordinates[i_row, :]\n for i_column in range(n_coordinates):\n\n r_j = product_coordinates[i_column, :]\n value = f_gamma(r_i, r_j)\n\n # TODO\n raise NotImplementedError(\"Can only handle entire rows\")\n # matrix.setElement(i_row, i_column, value)\n\n else:\n for i_row in distribution_plan.localRows():\n self._printProgress(len(distribution_plan.localRows()), i_row)\n\n r_i = product_coordinates[i_row, :]\n value = f_gamma(r_i)\n value = value.reshape(value.size)\n\n matrix.setRow(global_index=i_row,\n content=value)\n\n if distribution_plan.communicator().Get_rank() == 0:\n log(\"done\")\n\n return matrix\n\n def _printProgress(self, n_coordinates, index):\n logProgress(n_coordinates, index, \"Matrix building\")\n"
] |
[
[
"numpy.zeros"
]
] |
PellelNitram/WordDetectorNN
|
[
"a11f5bf4a69acc58dcf9c900d0caad17fb464d74"
] |
[
"src/dataloader.py"
] |
[
"from collections import namedtuple\n\nimport cv2\nimport numpy as np\nimport torch\n\nfrom aabb import AABB\nfrom coding import encode\nfrom utils import compute_scale_down, prob_true\n\nDataLoaderItem = namedtuple('DataLoaderItem', 'batch_imgs,batch_gt_maps,batch_aabbs')\n\n\nclass DataLoaderIAM:\n \"\"\"loader for IAM dataset\"\"\"\n\n def __init__(self, dataset, batch_size, input_size, output_size):\n self.dataset = dataset\n self.batch_size = batch_size\n self.input_size = input_size\n self.output_size = output_size\n self.scale_down = compute_scale_down(input_size, output_size)\n self.shuffled_indices = np.arange(len(self.dataset))\n self.curr_idx = 0\n self.is_random = False\n\n def __getitem__(self, item):\n batch_imgs = []\n batch_gt_maps = []\n batch_aabbs = []\n for b in range(self.batch_size):\n if self.is_random:\n shuffled_idx = self.shuffled_indices[item * self.batch_size + b]\n else:\n shuffled_idx = item * self.batch_size + b\n\n img, aabbs = self.dataset[shuffled_idx]\n\n if self.is_random:\n # geometric data augmentation (image [0..255] and gt)\n if prob_true(0.75):\n # random scale\n fx = np.random.uniform(0.5, 1.5)\n fy = np.random.uniform(0.5, 1.5)\n\n # random position around center\n txc = self.input_size[1] * (1 - fx) / 2\n tyc = self.input_size[0] * (1 - fy) / 2\n freedom_x = self.input_size[1] // 10\n freedom_y = self.input_size[0] // 10\n tx = txc + np.random.randint(-freedom_x, freedom_x)\n ty = tyc + np.random.randint(-freedom_y, freedom_y)\n\n # map image into target image\n M = np.float32([[fx, 0, tx], [0, fy, ty]])\n white_bg = np.ones(self.input_size, np.uint8) * 255\n img = cv2.warpAffine(img, M, dsize=self.input_size[::-1], dst=white_bg,\n borderMode=cv2.BORDER_TRANSPARENT)\n\n # apply the same transformations to gt, and clip/remove aabbs outside of target image\n aabb_clip = AABB(0, img.shape[1], 0, img.shape[0])\n aabbs = [aabb.scale(fx, fy).translate(tx, ty).clip(aabb_clip) for aabb in aabbs]\n aabbs = [aabb for aabb in aabbs if aabb.area() > 0]\n\n # photometric data augmentation (image [-0.5..0.5] only)\n img = (img / 255 - 0.5)\n if prob_true(0.25): # random distractors (lines)\n num_lines = np.random.randint(1, 20)\n for _ in range(num_lines):\n rand_pt = lambda: (np.random.randint(0, img.shape[1]), np.random.randint(0, img.shape[0]))\n color = np.random.triangular(-0.5, 0, 0.5)\n thickness = np.random.randint(1, 3)\n cv2.line(img, rand_pt(), rand_pt(), color, thickness)\n if prob_true(0.75): # random contrast\n img = (img - img.min()) / (img.max() - img.min()) - 0.5 # stretch\n img = img * np.random.triangular(0.1, 0.9, 1) # reduce contrast\n if prob_true(0.25): # random noise\n img = img + np.random.uniform(-0.1, 0.1, size=img.shape)\n if prob_true(0.25): # change thickness of text\n img = cv2.erode(img, np.ones((3, 3)))\n if prob_true(0.25): # change thickness of text\n img = cv2.dilate(img, np.ones((3, 3)))\n if prob_true(0.25): # invert image\n img = 0.5 - img\n\n else:\n img = (img / 255 - 0.5)\n\n gt_map = encode(self.output_size, aabbs, self.scale_down)\n\n batch_imgs.append(img[None, ...].astype(np.float32))\n batch_gt_maps.append(gt_map)\n batch_aabbs.append(aabbs)\n\n batch_imgs = np.stack(batch_imgs, axis=0)\n batch_gt_maps = np.stack(batch_gt_maps, axis=0)\n\n batch_imgs = torch.from_numpy(batch_imgs).to('cuda')\n batch_gt_maps = torch.from_numpy(batch_gt_maps.astype(np.float32)).to('cuda')\n\n return DataLoaderItem(batch_imgs, batch_gt_maps, batch_aabbs)\n\n def reset(self):\n self.curr_idx = 0\n\n def random(self, enable=True):\n np.random.shuffle(self.shuffled_indices)\n self.is_random = enable\n\n def __len__(self):\n return len(self.dataset) // self.batch_size\n\n\nclass DataLoaderImgFile:\n \"\"\"loader which simply goes through all jpg files of a directory\"\"\"\n\n def __init__(self, root_dir, input_size, device, max_side_len=1024):\n self.fn_imgs = root_dir.files('*.jpg')\n self.input_size = input_size\n self.device = device\n self.max_side_len = max_side_len\n\n def ceil32(self, val):\n if val % 32 == 0:\n return val\n val = (val // 32 + 1) * 32\n return val\n\n def __getitem__(self, item):\n orig = cv2.imread(self.fn_imgs[item], cv2.IMREAD_GRAYSCALE)\n\n f = min(self.max_side_len / orig.shape[0], self.max_side_len / orig.shape[1])\n if f < 1:\n orig = cv2.resize(orig, dsize=None, fx=f, fy=f)\n img = np.ones((self.ceil32(orig.shape[0]), self.ceil32(orig.shape[1])), np.uint8) * 255\n img[:orig.shape[0], :orig.shape[1]] = orig\n\n img = (img / 255 - 0.5).astype(np.float32)\n imgs = img[None, None, ...]\n imgs = torch.from_numpy(imgs).to(self.device)\n return DataLoaderItem(imgs, None, None)\n\n def get_scale_factor(self, item):\n img = cv2.imread(self.fn_imgs[item], cv2.IMREAD_GRAYSCALE)\n f = min(self.max_side_len / img.shape[0], self.max_side_len / img.shape[1])\n return f if f < 1 else 1\n\n def get_original_img(self, item):\n img = cv2.imread(self.fn_imgs[item], cv2.IMREAD_GRAYSCALE)\n img = (img / 255 - 0.5).astype(np.float32)\n return img\n\n def __len__(self):\n return len(self.fn_imgs)\n"
] |
[
[
"numpy.ones",
"numpy.random.shuffle",
"torch.from_numpy",
"numpy.random.triangular",
"numpy.float32",
"numpy.random.uniform",
"numpy.stack",
"numpy.random.randint"
]
] |
ixcc/federated
|
[
"3fb48ae6d019ee763c5112d23c3bdbcbaea17948"
] |
[
"tensorflow_federated/python/examples/remote_executor_example.py"
] |
[
"# Lint as: python3\n# Copyright 2018, The TensorFlow Federated 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\"\"\"Example showing how to run a multi-machine simulation.\n\nIn order to run this example, you must have a running instance of the\nExecutor Service, either locally or on Kubernetes.\n\nThe model trains EMNIST for a small number of rounds, but uses a RemoteExecutor\nto distribute the work to the ExecutorService.\n\"\"\"\n\nimport collections\nimport warnings\n\nfrom absl import app\nfrom absl import flags\nimport grpc\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow_federated as tff\n\ntf.compat.v1.enable_v2_behavior()\n\nFLAGS = flags.FLAGS\n\nflags.DEFINE_string('host', None, 'The host to connect to.')\nflags.mark_flag_as_required('host')\nflags.DEFINE_string('port', '8000', 'The port to connect to.')\nflags.DEFINE_integer('n_clients', 10, 'Number of clients.')\n\n\ndef preprocess(dataset):\n\n def element_fn(element):\n return collections.OrderedDict([\n ('x', tf.reshape(element['pixels'], [-1])),\n ('y', tf.reshape(element['label'], [1])),\n ])\n\n return dataset.repeat(NUM_EPOCHS).map(element_fn).batch(BATCH_SIZE)\n\n\ndef make_federated_data(client_data, client_ids):\n return [\n preprocess(client_data.create_tf_dataset_for_client(x))\n for x in client_ids\n ]\n\n\ndef create_compiled_keras_model():\n \"\"\"Create compiled Keras model.\"\"\"\n model = tf.keras.models.Sequential([\n tf.keras.layers.Dense(\n 10,\n activation=tf.nn.softmax,\n kernel_initializer='zeros',\n input_shape=(784,))\n ])\n\n model.compile(\n loss=tf.keras.losses.SparseCategoricalCrossentropy(),\n optimizer=tf.keras.optimizers.SGD(learning_rate=0.02),\n metrics=[tf.keras.metrics.SparseCategoricalAccuracy()])\n return model\n\n\nNUM_EPOCHS = 10\nBATCH_SIZE = 20\nN_ROUNDS = 3\n\n\ndef make_remote_executor(inferred_cardinalities):\n \"\"\"Make remote executor.\"\"\"\n\n def create_worker_stack_on(ex):\n return tff.framework.LambdaExecutor(tff.framework.ConcurrentExecutor(ex))\n\n client_ex = []\n num_clients = inferred_cardinalities.get(tff.CLIENTS, None)\n if num_clients:\n print('Inferred that there are {} clients'.format(num_clients))\n else:\n print('No CLIENTS placement provided')\n\n for _ in range(num_clients or 0):\n channel = grpc.insecure_channel('{}:{}'.format(FLAGS.host, FLAGS.port))\n client_ex.append(\n create_worker_stack_on(\n tff.framework.RemoteExecutor(channel, rpc_mode='STREAMING')))\n\n federated_ex = tff.framework.FederatedExecutor({\n None: create_worker_stack_on(tff.framework.EagerExecutor()),\n tff.SERVER: create_worker_stack_on(tff.framework.EagerExecutor()),\n tff.CLIENTS: client_ex,\n })\n\n return tff.framework.LambdaExecutor(federated_ex)\n\n\ndef main(argv):\n if len(argv) > 1:\n raise app.UsageError('Too many command-line arguments.')\n\n warnings.simplefilter('ignore')\n\n np.random.seed(0)\n\n emnist_train, _ = tff.simulation.datasets.emnist.load_data()\n\n sample_clients = emnist_train.client_ids[0:FLAGS.n_clients]\n\n federated_train_data = make_federated_data(emnist_train, sample_clients)\n\n example_dataset = emnist_train.create_tf_dataset_for_client(\n emnist_train.client_ids[0])\n\n preprocessed_example_dataset = preprocess(example_dataset)\n\n sample_batch = tf.nest.map_structure(\n lambda x: x.numpy(),\n iter(preprocessed_example_dataset).next())\n\n def model_fn():\n keras_model = create_compiled_keras_model()\n return tff.learning.from_compiled_keras_model(keras_model, sample_batch)\n\n iterative_process = tff.learning.build_federated_averaging_process(model_fn)\n\n # Set the default executor to be a RemoteExecutor\n tff.framework.set_default_executor(make_remote_executor)\n\n state = iterative_process.initialize()\n\n state, metrics = iterative_process.next(state, federated_train_data)\n print('round 1, metrics={}'.format(metrics))\n\n for round_num in range(2, N_ROUNDS + 1):\n state, metrics = iterative_process.next(state, federated_train_data)\n print('round {:2d}, metrics={}'.format(round_num, metrics))\n\n\nif __name__ == '__main__':\n app.run(main)\n"
] |
[
[
"tensorflow.keras.optimizers.SGD",
"tensorflow.compat.v1.enable_v2_behavior",
"numpy.random.seed",
"tensorflow.reshape",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.losses.SparseCategoricalCrossentropy",
"tensorflow.keras.metrics.SparseCategoricalAccuracy"
]
] |
debajit15kgp/multiagent-envs
|
[
"cc5bd1a1015636a07d8e703ee57067b315dde596",
"cc5bd1a1015636a07d8e703ee57067b315dde596",
"cc5bd1a1015636a07d8e703ee57067b315dde596"
] |
[
"multiagent/policy.py",
"multiagent/scenarios/food_collect.py",
"multiagent/scenarios/simple.py"
] |
[
"import numpy as np\nfrom pyglet.window import key\n\n# individual agent policy\nclass Policy(object):\n def __init__(self):\n pass\n def action(self, obs):\n raise NotImplementedError()\n\n# interactive policy based on keyboard input\n# hard-coded to deal only with movement, not communication\nclass InteractivePolicy(Policy):\n def __init__(self, env, agent_index):\n super(InteractivePolicy, self).__init__()\n self.env = env\n # hard-coded keyboard events\n self.move = [False for i in range(4)]\n self.pickup = np.zeros(3)\n self.comm = [False for i in range(env.world.dim_c)]\n # register keyboard events with this environment's window\n env.viewers[agent_index].window.on_key_press = self.key_press\n env.viewers[agent_index].window.on_key_release = self.key_release\n\n def action(self, obs):\n # ignore observation and just act based on keyboard events\n if self.env.discrete_action_input:\n u = 0\n if self.move[0]: u = 1\n if self.move[1]: u = 2\n if self.move[2]: u = 4\n if self.move[3]: u = 3\n return np.concatenate([np.array([u]), self.pickup, np.zeros(self.env.world.dim_c)])\n else:\n u = np.zeros(5) # 5-d because of no-move action\n if self.move[0]: u[1] += 1.0\n if self.move[1]: u[2] += 1.0\n if self.move[3]: u[3] += 1.0\n if self.move[2]: u[4] += 1.0\n if True not in self.move:\n u[0] += 1.0\n return np.concatenate([u, self.pickup, np.zeros(self.env.world.dim_c)])\n \n # keyboard event callbacks\n def key_press(self, k, mod):\n if k==key.LEFT: self.move[0] = True\n if k==key.RIGHT: self.move[1] = True\n if k==key.UP: self.move[2] = True\n if k==key.DOWN: self.move[3] = True\n if k==key.A: self.pickup[1] = 1\n if k==key.S: self.pickup[2] = 1\n def key_release(self, k, mod):\n if k==key.LEFT: self.move[0] = False\n if k==key.RIGHT: self.move[1] = False\n if k==key.UP: self.move[2] = False\n if k==key.DOWN: self.move[3] = False\n if k==key.A: self.pickup[1] = 0\n if k==key.S: self.pickup[2] = 0\n",
"import numpy as np\nfrom multiagent.core import World, Agent, Landmark\nfrom multiagent.scenario import BaseScenario\nimport os\n\nSIGHT = 100\nALPHA = 1\n\ndef softmax_dis(x):\n x = np.asarray(x)\n dis_min = np.min(x)\n return dis_min\n\n\n\n\nclass Scenario(BaseScenario):\n def __init__(self, n_good, n_adv, n_landmarks, n_food, n_forests, alpha, sight, no_wheel, ratio):\n self.n_good = n_good\n self.n_landmarks = n_landmarks\n self.n_food = n_food\n self.n_forests = n_forests\n self.alpha = alpha\n self.sight = sight\n self.no_wheel = no_wheel\n print(sight,\"sight___simple_spread_v25\")\n print(alpha,\"alpha######################\")\n\n def make_world(self):\n world = World()\n # set any world properties first\n world.collaborative = True\n world.dim_c = 2\n num_good_agents = self.n_good\n world.num_good_agents = num_good_agents\n num_agents = num_good_agents\n num_landmarks = self.n_landmarks\n num_food = self.n_food\n num_forests = self.n_forests\n # add agents\n world.agents = [Agent() for i in range(num_agents)]\n for i, agent in enumerate(world.agents):\n agent.name = 'agent %d' % i\n agent.collide = True\n agent.silent = True\n agent.adversary = False\n agent.size = 0.05\n agent.accel = 4.0\n agent.showmore = np.zeros(num_food)\n agent.max_speed = 4\n agent.live = 1\n agent.mindis = 0\n agent.time = 0\n agent.occupy = 0\n \n world.landmarks = [Landmark() for i in range(num_landmarks)]\n for i, landmark in enumerate(world.landmarks):\n landmark.name = 'landmark %d' % i\n landmark.collide = False\n landmark.movable = False\n landmark.size = 0\n landmark.boundary = False\n # make initial conditions\n world.food = [Landmark() for i in range(num_food)]\n for i, landmark in enumerate(world.food):\n landmark.name = 'food %d' % i\n landmark.collide = False\n landmark.movable = False\n landmark.size = 0.03\n landmark.boundary = False\n landmark.occupy = [0]\n landmark.mindis = 0\n world.forests = [Landmark() for i in range(num_forests)]\n for i, landmark in enumerate(world.forests):\n landmark.name = 'forest %d' % i\n landmark.collide = False\n landmark.movable = False\n landmark.size = 0.3\n landmark.boundary = False\n world.landmarks += world.food\n world.landmarks += world.forests\n self.reset_world(world)\n return world\n\n def reset_world(self, world):\n seed = int.from_bytes(os.urandom(4), byteorder='little')\n # print(\"reseed to\", seed)\n np.random.seed(seed)\n\n for i, agent in enumerate(world.agents):\n agent.color = np.array([0.6, 0.95, 0.45]) if not agent.adversary else np.array([0.95, 0.45, 0.45])\n agent.live = 1\n agent.mindis = 0\n agent.time = 0\n agent.occupy = [0]\n for i, landmark in enumerate(world.landmarks):\n landmark.color = np.array([0.25, 0.25, 0.25])\n for i, landmark in enumerate(world.food):\n landmark.color = np.array([0.15, 0.15, 0.65])\n for i, landmark in enumerate(world.forests):\n landmark.color = np.array([0.6, 0.9, 0.6])\n # set random initial states\n for agent in world.agents:\n agent.state.p_pos = np.random.uniform(-1, +1, world.dim_p)\n agent.state.p_vel = np.zeros(world.dim_p)\n agent.state.c = np.zeros(world.dim_c)\n for i, landmark in enumerate(world.landmarks):\n landmark.state.p_pos = np.random.uniform(-0.9, +0.9, world.dim_p)\n landmark.state.p_vel = np.zeros(world.dim_p)\n for i, landmark in enumerate(world.food):\n landmark.state.p_pos = np.random.uniform(-0.9, +0.9, world.dim_p)\n landmark.state.p_vel = np.zeros(world.dim_p)\n landmark.occupy = 0\n landmark.mindis = 0\n for i, landmark in enumerate(world.forests):\n landmark.state.p_pos = np.random.uniform(-0.9, +0.9, world.dim_p)\n landmark.state.p_vel = np.zeros(world.dim_p)\n \n def benchmark_data(self, agent, world):\n # returns data for benchmarking purposes\n if agent.adversary:\n collisions = 0\n for a in self.good_agents(world):\n if self.is_collision(a, agent):\n collisions += 1\n return collisions\n else:\n return 0\n\n\n def is_collision(self, agent1, agent2):\n delta_pos = agent1.state.p_pos - agent2.state.p_pos\n dist = np.sqrt(np.sum(np.square(delta_pos)))\n dist_min = agent1.size + agent2.size\n return True if dist < dist_min else False\n\n\n def done(self, agent, world):\n return 0\n\n def info(self, agent, world):\n time_grass = []\n time_live = []\n\n mark_grass = 0\n if agent.live:\n time_live.append(1)\n for food in world.food:\n if self.is_collision(agent, food):\n mark_grass = 1\n break\n else:\n time_live.append(0)\n if mark_grass:\n time_grass.append(1)\n else:\n time_grass.append(0)\n\n return np.concatenate([np.array(time_grass)]+[np.array(agent.occupy)])\n\n\n\n def reward(self, agent, world):\n # Agents are rewarded based on minimum agent distance to each landmark\n # main_reward = self.adversary_reward(agent, world) if agent.adversary else self.agent_reward(agent, world)\n main_reward = self.reward_all_in_once(agent, world)\n return main_reward\n\n def reward_all_in_once(self, agent, world):\n alpha = self.alpha\n num_agents = len(world.agents)\n reward_n = np.zeros(num_agents)\n # reward_n = [0]* num_agents\n # print(reward_n)\n \n alpha_sharing = self.alpha\n\n\n shape = True\n\n good_collide_id = []\n food_id = []\n\n for i, agent_new in enumerate(world.agents):\n agent_new.time += 1/26\n # collision reward:\n if agent_new.collide:\n for j, good in enumerate(world.agents):\n if good is not agent_new:\n if self.is_collision(good, agent_new):\n reward_n[i] = reward_n[i]-3/num_agents*(1-alpha)\n reward_buffer = -3/num_agents*(alpha)*np.ones(num_agents)\n reward_n = reward_n+reward_buffer\n \n # shape food\n full_house = []\n for food in world.food:\n if food.occupy==1:\n full_house.append(1)\n\n if not self.no_wheel:\n for i, agent_new in enumerate(world.agents):\n min_dis = min([np.sqrt(np.sum(np.square(food.state.p_pos - agent_new.state.p_pos))) for food in world.food])\n dis_change = -1*min_dis\n agent_new.mindis = min_dis\n reward_n[i] = reward_n[i]+dis_change\n \n occupy_list = []\n mark=0\n\n\n for food in world.food:\n mark=0\n for agent_new in world.agents:\n if self.is_collision(food, agent_new):\n mark=1\n occupy_list.append(1)\n reward_buffer = 6/num_agents*np.ones(num_agents)\n reward_n = reward_n+reward_buffer\n food.occupy=1\n break\n if mark==0:\n food.occupy=0\n if not self.no_wheel:\n if len(occupy_list)==len(world.food):\n reward_buffer = 10*np.ones(num_agents)-agent_new.time*2\n reward_n = reward_n+reward_buffer\n for agent_new in world.agents:\n agent_new.occupy = [len(occupy_list)/len(world.food)]\n return list(reward_n)\n\n\n\n def observation(self, agent, world):\n # get positions of all entities in this agent's reference frame\n entity_pos = []\n \n for entity in world.landmarks:\n distance = np.sqrt(np.sum(np.square(entity.state.p_pos - agent.state.p_pos)))\n if distance > self.sight:\n entity_pos.append([0,0,0])\n else:\n entity_pos.append(entity.state.p_pos - agent.state.p_pos)\n entity_pos.append([1])\n # communication of all other agents\n comm = []\n other_pos = []\n other_vel = []\n other_live = []\n other_time = []\n for other in world.agents:\n if other is agent: continue\n comm.append(other.state.c)\n distance = np.sqrt(np.sum(np.square(other.state.p_pos - agent.state.p_pos)))\n # print(distance,'distance')\n # print(other.live, 'other_live')\n if distance > self.sight or (not other.live):\n other_pos.append([0,0])\n other_vel.append([0,0])\n other_live.append([0])\n other_time.append([0])\n else:\n other_pos.append(other.state.p_pos - agent.state.p_pos)\n other_vel.append(other.state.p_vel)\n other_live.append(np.array([other.live]))\n other_time.append(np.array([other.time]))\n result = np.concatenate([agent.state.p_vel] + [agent.state.p_pos] + [np.array([agent.live])] + entity_pos + other_pos + other_vel + other_live)\n return result\n",
"import numpy as np\nimport json\nfrom multiagent.core import World, Agent, Landmark\nfrom multiagent.scenario import BaseScenario\n\nclass Scenario(BaseScenario):\n\n def make_world(self):\n world = World()\n # add agents\n world.agents = [Agent() for i in range(1)]\n for i, agent in enumerate(world.agents):\n agent.name = 'agent %d' % i\n agent.collide = False\n agent.silent = True\n # add landmarks\n world.landmarks = [Landmark() for i in range(1)]\n for i, landmark in enumerate(world.landmarks):\n landmark.name = 'landmark %d' % i\n landmark.collide = False\n landmark.movable = False\n # make initial conditions\n self.reset_world(world)\n return world\n\n def reset_world(self, world):\n # random properties for agents\n for i, agent in enumerate(world.agents):\n agent.color = np.array([0.25,0.25,0.25])\n # random properties for landmarks\n for i, landmark in enumerate(world.landmarks):\n landmark.color = np.array([0.75,0.75,0.75])\n world.landmarks[0].color = np.array([0.75,0.25,0.25])\n # set random initial states\n for agent in world.agents:\n agent.state.p_pos = np.random.uniform(-1,+1, world.dim_p)\n agent.state.p_vel = np.zeros(world.dim_p)\n agent.state.c = np.zeros(world.dim_c)\n for i, landmark in enumerate(world.landmarks):\n landmark.state.p_pos = np.random.uniform(-1,+1, world.dim_p)\n landmark.state.p_vel = np.zeros(world.dim_p)\n\n def reward(self, agent, world):\n dist2 = np.sum(np.square(agent.state.p_pos - world.landmarks[0].state.p_pos))\n return -dist2\n\n def observation(self, agent, world):\n # get positions of all entities in this agent's reference frame\n entity_pos = []\n for entity in world.landmarks:\n entity_pos.append(entity.state.p_pos - agent.state.p_pos)\n return np.concatenate([agent.state.p_vel] + entity_pos)\n"
] |
[
[
"numpy.array",
"numpy.zeros"
],
[
"numpy.square",
"numpy.array",
"numpy.asarray",
"numpy.zeros",
"numpy.random.seed",
"numpy.ones",
"numpy.min",
"numpy.random.uniform"
],
[
"numpy.concatenate",
"numpy.square",
"numpy.array",
"numpy.zeros",
"numpy.random.uniform"
]
] |
bahattin-urganci/python-training
|
[
"576956083e4ea95a76480992a022ba3a61681308"
] |
[
"MachineLearning/hello-ml-world.py"
] |
[
"#from sklearn import tree\n#features=[[140,1],[130,1],[150,0],[170,0]]\n#labels=[0,0,1,1]\n#clf=tree.DecisionTreeClassifier()\n#clf=clf.fit(features,labels)\n#print(clf.predict([[150,0]]))\n\nimport tensorflow as tf\nhello = tf.constant('Hello, TensorFlow!')\nsess = tf.Session()\nprint(sess.run(hello))\n\n"
] |
[
[
"tensorflow.constant",
"tensorflow.Session"
]
] |
onucharles/tensorized-rnn
|
[
"69fc031f1efe169ee88327d10bdf5e5bc24f03cf"
] |
[
"experiments/digit_classification/benchmarking.py"
] |
[
"\"\"\"\nBenchmarking runtime and memory usage.\nCode uses MNIST_Classifier class (an RNN + FC layer), but otherwise is independent of any experiment.\n\"\"\"\n\nimport torch\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport argparse\nfrom time import time\nimport numpy as np\nfrom mnist_classifier import MNIST_Classifier\nfrom GPUtil import showUtilization as gpu_usage\n\n\ndef testing_eval():\n print(\"Benchmarking test time...\")\n model.eval()\n all_durations = []\n _ = model(data) # do one time to wake gpu.\n\n with torch.no_grad():\n for i in np.arange(args.nruns):\n # time forward pass\n start = time()\n _ = model(data)\n gpu_usage()\n duration = time() - start\n\n # save duration\n print(f\"Run: {i} \\t Duration: {duration}\", )\n all_durations.append(duration)\n\n # print mean and std of durations.\n all_durations = np.array(all_durations)\n mean_time = np.mean(all_durations)\n std_time = np.std(all_durations)\n print(f\"mean time: {mean_time} \\t std time: {std_time}\")\n\n\ndef training_eval():\n print(\"Benchmarking training time...\")\n optimizer = getattr(optim, 'Adam')(model.parameters(), lr=0.001)\n model.train()\n all_durations = []\n out = model(data) # do one time to wake gpu.\n\n for i in np.arange(args.nruns):\n # start timer\n start = time()\n\n optimizer.zero_grad()\n out = model(data)\n loss = F.nll_loss(out, target)\n loss.backward()\n optimizer.step()\n\n # end timer.\n gpu_usage()\n duration = time() - start\n\n # print and save duration\n print(f\"Run: {i} \\t Duration: {duration}\", )\n all_durations.append(duration)\n\n # print mean and std of durations.\n all_durations = np.array(all_durations)\n mean_time = np.mean(all_durations)\n std_time = np.std(all_durations)\n print(f\"mean time: {mean_time} \\t std time: {std_time}\")\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--tt\", action='store_true')\n parser.add_argument(\"--ncores\", type=int, default=1)\n parser.add_argument(\"--ttrank\", type=int, default=1)\n parser.add_argument('--batch_size', type=int, default=512, metavar='N')\n parser.add_argument(\"--in_size\", type=int, default=256)\n parser.add_argument('--hidden_size', type=int, default=512)\n parser.add_argument('--n_layers', type=int, default=1)\n parser.add_argument(\"--seq_len\", type=int, default=160)\n parser.add_argument(\"--emb_size\", type=int, default=256)\n parser.add_argument(\"-n\", \"--nruns\", type=int, default=100)\n parser.add_argument(\"--gru\", action='store_true')\n parser.add_argument(\"--naive_tt\", action='store_true')\n parser.add_argument(\"--train\", action='store_true')\n parser.add_argument(\"--cuda\", action='store_true')\n args = parser.parse_args()\n print(args)\n\n # instantiate model\n if args.cuda:\n device = torch.device('cuda')\n else:\n device = torch.device('cpu')\n\n # Using the MNIST_Classifier class, but it's just a generic RNN with fully connected layer.\n model = MNIST_Classifier(args.in_size, args.emb_size, args.hidden_size, args.n_layers, device,\n tt=args.tt, gru=args.gru, n_cores=args.ncores, tt_rank=args.ttrank,\n naive_tt=args.naive_tt).to(device)\n\n # create random batch of data (using appropriate sizes)\n data = np.random.rand(args.batch_size, args.seq_len, args.in_size).astype('float32')\n target = np.random.randint(0, args.emb_size, args.batch_size).astype('int64')\n data = torch.from_numpy(data).to(device)\n target = torch.from_numpy(target).to(device)\n print(\"Benchmarking with input: {} and target {}\".format(data.size(), target.shape))\n\n if args.train:\n training_eval()\n else:\n testing_eval()\n\n print(f\"model has: {model.param_count()} parameters\")\n\n"
] |
[
[
"torch.device",
"numpy.array",
"numpy.random.rand",
"torch.no_grad",
"numpy.mean",
"torch.from_numpy",
"numpy.std",
"numpy.arange",
"numpy.random.randint",
"torch.nn.functional.nll_loss"
]
] |
ZhouRR/quotations-gateway-api
|
[
"ef433fe8e461344a6c59e5edec206ad4ba7eeff6"
] |
[
"app/core/gopup/life/charity.py"
] |
[
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2020/12/10 0010\n# @Author : justin.郑 3907721@qq.com\n# @File : charity.py\n# @Desc : 慈善中国\n\nimport pandas as pd\nimport requests\nfrom tqdm import tqdm\nfrom pyquery import PyQuery as pq\n\n\ndef _get_page_num_charity_organization():\n \"\"\"\n 慈善中国-慈善组织查询-总页数\n :return: 总页数\n \"\"\"\n url = \"http://cishan.chinanpo.gov.cn/biz/ma/csmh/a/csmhaDoSort.html\"\n payload_params = {\n \"aaee0102_03\": \"\",\n \"field\": \"aaex0131\",\n \"sort\": \"desc\",\n \"flag\": \"0\",\n }\n payload_data = {\"pageNo\": \"1\"}\n r = requests.post(url, params=payload_params, data=payload_data)\n pages = r.text[r.text.find(\"第1页/共\") + 5: r.text.rfind(\"页</font>\")]\n return int(pages)\n\n\ndef charity_organization():\n \"\"\"\n 慈善中国-慈善组织查询\n http://cishan.chinanpo.gov.cn/biz/ma/csmh/a/csmhaindex.html\n :return: 慈善中国-慈善组织查询\n :rtype: pandas.DataFrame\n \"\"\"\n page_num = _get_page_num_charity_organization()\n url = \"http://cishan.chinanpo.gov.cn/biz/ma/csmh/a/csmhaDoSort.html\"\n params = {\n \"field\": \"aaex0131\",\n \"sort\": \"desc\",\n \"flag\": \"0\",\n }\n outer_df = pd.DataFrame()\n for page in tqdm(range(1, page_num+1)):\n # page = 1\n params[\"pageNo\"] = str(page)\n\n r = requests.post(url, params=params)\n inner_df = pd.read_html(r.text)[0]\n outer_df = outer_df.append(inner_df, ignore_index=True)\n return outer_df\n\n\nif __name__ == \"__main__\":\n tmp = charity_organization()\n print(tmp)\n\n"
] |
[
[
"pandas.DataFrame",
"pandas.read_html"
]
] |
fluffybird2323/pyro
|
[
"9e74e499dbda76c28f12528235dac25bd17f0b1b"
] |
[
"tests/contrib/test_util.py"
] |
[
"from __future__ import absolute_import, division, print_function\n\nfrom collections import OrderedDict\nimport pytest\nimport torch\n\nfrom pyro.contrib.util import (\n get_indices, tensor_to_dict, rmv, rvv, lexpand, rexpand, rdiag, rtril\n)\nfrom tests.common import assert_equal\n\n\ndef test_get_indices_sizes():\n sizes = OrderedDict([(\"a\", 2), (\"b\", 2), (\"c\", 2)])\n assert_equal(get_indices([\"b\"], sizes=sizes), torch.tensor([2, 3]))\n assert_equal(get_indices([\"b\", \"c\"], sizes=sizes), torch.tensor([2, 3, 4, 5]))\n tensors = OrderedDict([(\"a\", torch.ones(2)), (\"b\", torch.ones(2)), (\"c\", torch.ones(2))])\n assert_equal(get_indices([\"b\"], tensors=tensors), torch.tensor([2, 3]))\n assert_equal(get_indices([\"b\", \"c\"], tensors=tensors), torch.tensor([2, 3, 4, 5]))\n\n\ndef test_tensor_to_dict():\n sizes = OrderedDict([(\"a\", 2), (\"b\", 2), (\"c\", 2)])\n vector = torch.tensor([1., 2, 3, 4, 5, 6])\n assert_equal(tensor_to_dict(sizes, vector), {\"a\": torch.tensor([1., 2.]),\n \"b\": torch.tensor([3., 4.]),\n \"c\": torch.tensor([5., 6.])})\n assert_equal(tensor_to_dict(sizes, vector, subset=[\"b\"]),\n {\"b\": torch.tensor([3., 4.])})\n\n\n@pytest.mark.parametrize(\"A,b\", [\n (torch.tensor([[1., 2.], [2., -3.]]), torch.tensor([-1., 2.]))\n ])\ndef test_rmv(A, b):\n assert_equal(rmv(A, b), A.mv(b), prec=1e-8)\n batched_A = lexpand(A, 5, 4)\n batched_b = lexpand(b, 5, 4)\n expected_Ab = lexpand(A.mv(b), 5, 4)\n assert_equal(rmv(batched_A, batched_b), expected_Ab, prec=1e-8)\n\n\n@pytest.mark.parametrize(\"a,b\", [\n (torch.tensor([1., 2.]), torch.tensor([-1., 2.]))\n ])\ndef test_rvv(a, b):\n assert_equal(rvv(a, b), torch.dot(a, b), prec=1e-8)\n batched_a = lexpand(a, 5, 4)\n batched_b = lexpand(b, 5, 4)\n expected_ab = lexpand(torch.dot(a, b), 5, 4)\n assert_equal(rvv(batched_a, batched_b), expected_ab, prec=1e-8)\n\n\ndef test_lexpand():\n A = torch.tensor([[1., 2.], [-2., 0]])\n assert_equal(lexpand(A), A, prec=1e-8)\n assert_equal(lexpand(A, 4), A.expand(4, 2, 2), prec=1e-8)\n assert_equal(lexpand(A, 4, 2), A.expand(4, 2, 2, 2), prec=1e-8)\n\n\ndef test_rexpand():\n A = torch.tensor([[1., 2.], [-2., 0]])\n assert_equal(rexpand(A), A, prec=1e-8)\n assert_equal(rexpand(A, 4), A.unsqueeze(-1).expand(2, 2, 4), prec=1e-8)\n assert_equal(rexpand(A, 4, 2), A.unsqueeze(-1).unsqueeze(-1).expand(2, 2, 4, 2), prec=1e-8)\n\n\ndef test_rtril():\n A = torch.tensor([[1., 2.], [-2., 0]])\n assert_equal(rtril(A), torch.tril(A), prec=1e-8)\n expanded = lexpand(A, 5, 4)\n expected = lexpand(torch.tril(A), 5, 4)\n assert_equal(rtril(expanded), expected, prec=1e-8)\n\n\ndef test_rdiag():\n v = torch.tensor([1., 2., -1.])\n assert_equal(rdiag(v), torch.diag(v), prec=1e-8)\n expanded = lexpand(v, 5, 4)\n expeceted = lexpand(torch.diag(v), 5, 4)\n assert_equal(rdiag(expanded), expeceted, prec=1e-8)\n"
] |
[
[
"torch.tril",
"torch.ones",
"torch.tensor",
"torch.diag",
"torch.dot"
]
] |
mrsempress/mmdetection
|
[
"cb650560c97a2fe56a9b369a1abc8ec17e06583a"
] |
[
"mmdet/core/utils/model_utils.py"
] |
[
"from tabulate import tabulate\nfrom termcolor import colored\nfrom graphviz import Digraph\nfrom collections import OrderedDict\nimport numpy as np\nimport torch\nimport torch.nn as nn\n\nfrom mmdet.core.utils import logger\n\n\ndef describe_vars(model):\n headers = ['name', 'shape', '#elements', '(M)', '(MB)', 'trainable', 'dtype']\n\n data = []\n trainable_count = 0\n total = 0\n total_size = 0\n trainable_total = 0\n\n for name, param in model.named_parameters():\n dtype = str(param.data.dtype)\n param_mb = 'NAN'\n param_bype = float(''.join([s for s in dtype if s.isdigit()])) / 8\n\n total += param.data.nelement()\n if param_bype:\n param_mb = '{:.02f}'.format(param.data.nelement() / 1024.0 ** 2 * param_bype)\n total_size += param.data.nelement() * param_bype\n data.append([name.replace('.', '/'), list(param.size()),\n '{0:,}'.format(param.data.nelement()),\n '{:.02f}'.format(param.data.nelement() / 1024.0 ** 2), param_mb,\n param.requires_grad, dtype])\n if param.requires_grad:\n trainable_count += 1\n trainable_total += param.data.nelement()\n\n table = tabulate(data, headers=headers)\n\n summary_msg = colored(\n \"\\nNumber of All variables: {}\".format(len(data)) +\n \"\\nAll parameters (elements): {:.02f}M\".format(total / 1024.0 ** 2) +\n \"\\nAll parameters (size): {:.02f}MB\".format(total_size / 1024.0 ** 2) +\n \"\\nNumber of Trainable variables: {}\".format(trainable_count) +\n \"\\nAll trainable parameters (elements): {:.02f}M\\n\".format(\n trainable_total / 1024.0 ** 2), 'cyan')\n logger.info(colored(\"List of All Variables: \\n\", 'cyan') + table + summary_msg)\n\n\ndef describe_features(model, input_size=(3, 800, 800)):\n headers = ['type', 'input', 'output', '#elements(M)', '(MB)', 'dtype', '#params(M)']\n\n def register_hook(module):\n\n def hook(module, input, output):\n class_name = str(module.__class__).split(\".\")[-1].split(\"'\")[0]\n module_idx = len(summary)\n m_key = \"%s-%i\" % (class_name, module_idx + 1)\n\n summary[m_key] = OrderedDict()\n summary[m_key][\"input_shape\"] = list(input[0].size())\n summary[m_key][\"input_shape\"][0] = -1\n if isinstance(output, (list, tuple)):\n summary[m_key][\"output_shape\"] = [\n [-1] + list(o.size())[1:] for o in output\n ]\n else:\n summary[m_key][\"output_shape\"] = list(output.size())\n summary[m_key][\"output_shape\"][0] = -1\n\n dtype = str(output.dtype)\n elements_byte = float(''.join([s for s in dtype if s.isdigit()])) / 8\n summary[m_key][\"output_dtype\"] = dtype\n summary[m_key][\"elements\"] = np.prod(\n summary[m_key][\"output_shape\"][1:]) / 1024.0 ** 2\n summary[m_key][\"elements_mb\"] = summary[m_key][\"elements\"] * elements_byte\n params = 0\n for _, param in module.named_parameters():\n params += param.data.nelement()\n summary[m_key][\"nb_params\"] = float(params)\n summary[m_key][\"children_num\"] = len(list(module.children()))\n\n if (not isinstance(module, nn.Sequential) and not isinstance(module, nn.ModuleList)\n and not (module == model)):\n hooks.append(module.register_forward_hook(hook))\n\n summary = OrderedDict()\n hooks = []\n\n # multiple inputs to the network\n if isinstance(input_size, tuple):\n input_size = [input_size]\n\n x = [torch.rand(1, *in_size).type(torch.FloatTensor) for in_size in input_size]\n model.apply(register_hook)\n model(*x)\n\n for h in hooks:\n h.remove()\n\n data = []\n total_output = 0\n total_params = 0\n total_params_size = 0\n for _, param in model.named_parameters():\n dtype = str(param.data.dtype)\n param_bype = float(''.join([s for s in dtype if s.isdigit()])) / 8\n\n total_params += param.data.nelement()\n total_params_size += param.data.nelement() * param_bype\n total_params = total_params / 1024.0 ** 2\n total_params_size = total_params_size / 1024.0 ** 2\n\n def warp(*args, lchar='', rchar=''):\n out = []\n for arg in args:\n out.append('{}{}{}'.format(lchar, arg, rchar))\n return out\n\n for layer in summary:\n input_shape = str(summary[layer][\"input_shape\"])\n output_shape = str(summary[layer][\"output_shape\"])\n elements = '{:.02f}'.format(summary[layer][\"elements\"])\n elements_mb = '{:.02f}'.format(summary[layer][\"elements_mb\"])\n output_dtype = summary[layer][\"output_dtype\"]\n params = \"{:.02f}\".format(float(summary[layer][\"nb_params\"]) / 1024.0 ** 2)\n\n if summary[layer][\"children_num\"] == 0:\n total_output += summary[layer][\"elements_mb\"]\n head = [layer]\n line = warp(input_shape, output_shape, elements, elements_mb, output_dtype, params,\n lchar=' ', rchar=' ')\n else:\n head = warp(layer, lchar='<', rchar='>')\n line = warp(input_shape, output_shape, elements, elements_mb, output_dtype, params,\n lchar='<', rchar='> ')\n head.extend(line)\n data.append(head)\n\n table = tabulate(data, headers=headers, stralign='center')\n\n # assume 4 bytes/number (float on cuda).\n total_input_size = abs(np.prod(input_size) * 4. / (1024 ** 2.))\n total_output_size = 2. * total_output # x2 for gradients\n total_size = total_params_size + total_output_size + total_input_size\n\n summary_msg = colored(\n \"\\nAll parameters (elements): {:.02f}M\".format(total_params) +\n \"\\nInput size: {:.02f}MB\".format(total_input_size) +\n \"\\nForward/backward pass size: {:.02f}MB\".format(total_output_size) +\n \"\\nParams size: {:.02f}MB\".format(total_params_size) +\n \"\\nEstimated Total Size: {:.02f}MB\\n\".format(total_size), 'cyan')\n\n logger.info(colored(\"List of All Features: \\n\", 'cyan') + table + summary_msg)\n\n\ndef _iter_graph(root, callback):\n queue = [root]\n seen = set()\n while queue:\n fn = queue.pop()\n if fn in seen:\n continue\n seen.add(fn)\n for next_fn, _ in fn.next_functions:\n if next_fn is not None:\n queue.append(next_fn)\n callback(fn)\n\n\ndef register_hooks(var, id_dict):\n fn_dict = {}\n\n def hook_cb(fn):\n def register_grad(grad_input, grad_output):\n fn_dict[fn] = grad_input\n\n fn.register_hook(register_grad)\n\n _iter_graph(var.grad_fn, hook_cb)\n\n def is_bad_grad(grad_output):\n try:\n grad_output = grad_output.data\n except:\n return False\n return grad_output.ne(grad_output).any() or grad_output.gt(1e6).any()\n\n def make_dot():\n node_attr = dict(style='filled',\n shape='box',\n align='left',\n fontsize='12',\n ranksep='0.1',\n height='0.2')\n dot = Digraph(node_attr=node_attr, graph_attr=dict(size=\"32,32\"))\n\n def size_to_str(size):\n return '(' + ', '.join(map(str, size)) + ')'\n\n def build_graph(fn):\n if hasattr(fn, 'variable'):\n u = fn.variable\n assert id(u) in id_dict\n node_name = id_dict[id(u)] + '\\n' + size_to_str(u.size())\n dot.node(str(id(u)), node_name, fillcolor='lightblue')\n else:\n if fn not in fn_dict:\n print(\"not in dict: \", fn)\n return\n assert fn in fn_dict, fn\n fillcolor = 'white'\n if any(is_bad_grad(gi) for gi in fn_dict[fn]):\n fillcolor = 'red'\n dot.node(str(id(fn)), str(type(fn).__name__), fillcolor=fillcolor)\n for next_fn, _ in fn.next_functions:\n if next_fn is not None:\n next_id = id(getattr(next_fn, 'variable', next_fn))\n dot.edge(str(id(fn)), str(next_id))\n _iter_graph(var.grad_fn, build_graph)\n return dot\n return make_dot\n"
] |
[
[
"torch.rand",
"numpy.prod"
]
] |
aikakysymys/transformers
|
[
"34e11fab167a7beb78fbe6991ff8721dc9208793"
] |
[
"src/transformers/modeling_tf_flaubert.py"
] |
[
"# coding=utf-8\n# Copyright 2019-present, Facebook, Inc and the HuggingFace 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\"\"\" TF 2.0 Flaubert model.\n\"\"\"\n\nimport random\n\nimport tensorflow as tf\n\nfrom .configuration_flaubert import FlaubertConfig\nfrom .file_utils import add_start_docstrings\nfrom .modeling_tf_outputs import TFBaseModelOutput\nfrom .modeling_tf_utils import keras_serializable, shape_list\nfrom .modeling_tf_xlm import (\n TFXLMForMultipleChoice,\n TFXLMForQuestionAnsweringSimple,\n TFXLMForSequenceClassification,\n TFXLMForTokenClassification,\n TFXLMMainLayer,\n TFXLMModel,\n TFXLMPredLayer,\n TFXLMWithLMHeadModel,\n get_masks,\n)\nfrom .tokenization_utils import BatchEncoding\nfrom .utils import logging\n\n\nlogger = logging.get_logger(__name__)\n\nTF_FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST = [\n # See all Flaubert models at https://huggingface.co/models?filter=flaubert\n]\n\nFLAUBERT_START_DOCSTRING = r\"\"\"\n\n This model is a `tf.keras.Model <https://www.tensorflow.org/api_docs/python/tf/keras/Model>`__ sub-class.\n Use it as a regular TF 2.0 Keras Model and\n refer to the TF 2.0 documentation for all matter related to general usage and behavior.\n\n Parameters:\n config (:class:`~transformers.FlaubertConfig`): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the configuration.\n Check out the :meth:`~transformers.PreTrainedModel.from_pretrained` method to load the model weights.\n\"\"\"\n\nFLAUBERT_INPUTS_DOCSTRING = r\"\"\"\n Args:\n input_ids (:obj:`tf.Tensor` or :obj:`Numpy array` of shape :obj:`(batch_size, sequence_length)`):\n Indices of input sequence tokens in the vocabulary.\n Indices can be obtained using :class:`transformers.BertTokenizer`.\n See :func:`transformers.PreTrainedTokenizer.encode` and\n :func:`transformers.PreTrainedTokenizer.__call__` for details.\n `What are input IDs? <../glossary.html#input-ids>`__\n attention_mask (:obj:`tf.Tensor` or :obj:`Numpy array` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`):\n Mask to avoid performing attention on padding token indices.\n Mask values selected in ``[0, 1]``:\n ``1`` for tokens that are NOT MASKED, ``0`` for MASKED tokens.\n `What are attention masks? <../glossary.html#attention-mask>`__\n langs (:obj:`tf.Tensor` or :obj:`Numpy array` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`):\n A parallel sequence of tokens to be used to indicate the language of each token in the input.\n Indices are languages ids which can be obtained from the language names by using two conversion mappings\n provided in the configuration of the model (only provided for multilingual models).\n More precisely, the `language name -> language id` mapping is in `model.config.lang2id` (dict str -> int) and\n the `language id -> language name` mapping is `model.config.id2lang` (dict int -> str).\n See usage examples detailed in the `multilingual documentation <https://huggingface.co/transformers/multilingual.html>`__.\n token_type_ids (:obj:`tf.Tensor` or :obj:`Numpy array` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`):\n Segment token indices to indicate first and second portions of the inputs.\n Indices are selected in ``[0, 1]``: ``0`` corresponds to a `sentence A` token, ``1``\n corresponds to a `sentence B` token\n `What are token type IDs? <../glossary.html#token-type-ids>`_\n position_ids (:obj:`tf.Tensor` or :obj:`Numpy array` of shape :obj:`(batch_size, sequence_length)`, `optional`, defaults to :obj:`None`):\n Indices of positions of each input sequence tokens in the position embeddings.\n Selected in the range ``[0, config.max_position_embeddings - 1]``.\n `What are position IDs? <../glossary.html#position-ids>`_\n lengths (:obj:`tf.Tensor` or :obj:`Numpy array` of shape :obj:`(batch_size,)`, `optional`, defaults to :obj:`None`):\n Length of each sentence that can be used to avoid performing attention on padding token indices.\n You can also use `attention_mask` for the same result (see above), kept here for compatbility.\n Indices selected in ``[0, ..., input_ids.size(-1)]``:\n cache (:obj:`Dict[str, tf.Tensor]`, `optional`, defaults to :obj:`None`):\n dictionary with ``tf.Tensor`` that contains pre-computed\n hidden-states (key and values in the attention blocks) as computed by the model\n (see `cache` output below). Can be used to speed up sequential decoding.\n The dictionary object will be modified in-place during the forward pass to add newly computed hidden-states.\n head_mask (:obj:`tf.Tensor` or :obj:`Numpy array` of shape :obj:`(num_heads,)` or :obj:`(num_layers, num_heads)`, `optional`, defaults to :obj:`None`):\n Mask to nullify selected heads of the self-attention modules.\n Mask values selected in ``[0, 1]``:\n :obj:`1` indicates the head is **not masked**, :obj:`0` indicates the head is **masked**.\n inputs_embeds (:obj:`tf.Tensor` or :obj:`Numpy array` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`, defaults to :obj:`None`):\n Optionally, instead of passing :obj:`input_ids` you can choose to directly pass an embedded representation.\n This is useful if you want more control over how to convert `input_ids` indices into associated vectors\n than the model's internal embedding lookup matrix.\n output_attentions (:obj:`bool`, `optional`, defaults to :obj:`None`):\n If set to ``True``, the attentions tensors of all attention layers are returned. See ``attentions`` under returned tensors for more detail.\n output_hidden_states (:obj:`bool`, `optional`, defaults to :obj:`None`):\n If set to ``True``, the hidden states of all layers are returned. See ``hidden_states`` under returned tensors for more detail.\n return_dict (:obj:`bool`, `optional`, defaults to :obj:`None`):\n If set to ``True``, the model will return a :class:`~transformers.file_utils.ModelOutput` instead of a\n plain tuple.\n\"\"\"\n\n\n@add_start_docstrings(\n \"The bare Flaubert Model transformer outputting raw hidden-states without any specific head on top.\",\n FLAUBERT_START_DOCSTRING,\n)\nclass TFFlaubertModel(TFXLMModel):\n config_class = FlaubertConfig\n\n def __init__(self, config, *inputs, **kwargs):\n super().__init__(config, *inputs, **kwargs)\n self.transformer = TFFlaubertMainLayer(config, name=\"transformer\")\n\n\n@keras_serializable\nclass TFFlaubertMainLayer(TFXLMMainLayer):\n def __init__(self, config, *inputs, **kwargs):\n super().__init__(config, *inputs, **kwargs)\n self.layerdrop = getattr(config, \"layerdrop\", 0.0)\n self.pre_norm = getattr(config, \"pre_norm\", False)\n self.output_attentions = config.output_attentions\n self.output_hidden_states = config.output_hidden_states\n self.return_dict = config.use_return_dict\n\n def call(\n self,\n inputs,\n attention_mask=None,\n langs=None,\n token_type_ids=None,\n position_ids=None,\n lengths=None,\n cache=None,\n head_mask=None,\n inputs_embeds=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n training=False,\n ):\n # removed: src_enc=None, src_len=None\n if isinstance(inputs, (tuple, list)):\n input_ids = inputs[0]\n attention_mask = inputs[1] if len(inputs) > 1 else attention_mask\n langs = inputs[2] if len(inputs) > 2 else langs\n token_type_ids = inputs[3] if len(inputs) > 3 else token_type_ids\n position_ids = inputs[4] if len(inputs) > 4 else position_ids\n lengths = inputs[5] if len(inputs) > 5 else lengths\n cache = inputs[6] if len(inputs) > 6 else cache\n head_mask = inputs[7] if len(inputs) > 7 else head_mask\n inputs_embeds = inputs[8] if len(inputs) > 8 else inputs_embeds\n output_attentions = inputs[9] if len(inputs) > 9 else output_attentions\n output_hidden_states = inputs[10] if len(inputs) > 10 else output_hidden_states\n return_dict = inputs[11] if len(inputs) > 11 else return_dict\n assert len(inputs) <= 12, \"Too many inputs.\"\n elif isinstance(inputs, (dict, BatchEncoding)):\n input_ids = inputs.get(\"input_ids\")\n attention_mask = inputs.get(\"attention_mask\", attention_mask)\n langs = inputs.get(\"langs\", langs)\n token_type_ids = inputs.get(\"token_type_ids\", token_type_ids)\n position_ids = inputs.get(\"position_ids\", position_ids)\n lengths = inputs.get(\"lengths\", lengths)\n cache = inputs.get(\"cache\", cache)\n head_mask = inputs.get(\"head_mask\", head_mask)\n inputs_embeds = inputs.get(\"inputs_embeds\", inputs_embeds)\n output_attentions = inputs.get(\"output_attentions\", output_attentions)\n output_hidden_states = inputs.get(\"output_hidden_states\", output_hidden_states)\n return_dict = inputs.get(\"return_dict\", return_dict)\n assert len(inputs) <= 12, \"Too many inputs.\"\n else:\n input_ids = inputs\n\n output_attentions = output_attentions if output_attentions is not None else self.output_attentions\n output_hidden_states = output_hidden_states if output_hidden_states is not None else self.output_hidden_states\n return_dict = return_dict if return_dict is not None else self.return_dict\n\n if input_ids is not None and inputs_embeds is not None:\n raise ValueError(\"You cannot specify both input_ids and inputs_embeds at the same time\")\n elif input_ids is not None:\n bs, slen = shape_list(input_ids)\n elif inputs_embeds is not None:\n bs, slen = shape_list(inputs_embeds)[:2]\n else:\n raise ValueError(\"You have to specify either input_ids or inputs_embeds\")\n\n if lengths is None:\n if input_ids is not None:\n lengths = tf.reduce_sum(tf.cast(tf.not_equal(input_ids, self.pad_index), dtype=tf.int32), axis=1)\n else:\n lengths = tf.convert_to_tensor([slen] * bs, tf.int32)\n # mask = input_ids != self.pad_index\n\n # check inputs\n # assert shape_list(lengths)[0] == bs\n tf.debugging.assert_equal(\n shape_list(lengths)[0], bs\n ), f\"Expected batch size {shape_list(lengths)[0]} and received batch size {bs} mismatched\"\n # assert lengths.max().item() <= slen\n # input_ids = input_ids.transpose(0, 1) # batch size as dimension 0\n # assert (src_enc is None) == (src_len is None)\n # if src_enc is not None:\n # assert self.is_decoder\n # assert src_enc.size(0) == bs\n\n # generate masks\n mask, attn_mask = get_masks(slen, lengths, self.causal, padding_mask=attention_mask)\n # if self.is_decoder and src_enc is not None:\n # src_mask = torch.arange(src_len.max(), dtype=torch.long, device=lengths.device) < src_len[:, None]\n\n # position_ids\n if position_ids is None:\n position_ids = tf.expand_dims(tf.range(slen), axis=0)\n else:\n # assert shape_list(position_ids) == [bs, slen] # (slen, bs)\n tf.debugging.assert_equal(\n shape_list(position_ids), [bs, slen]\n ), f\"Position id shape {shape_list(position_ids)} and input shape {[bs, slen]} mismatched\"\n # position_ids = position_ids.transpose(0, 1)\n\n # langs\n if langs is not None:\n # assert shape_list(langs) == [bs, slen] # (slen, bs)\n tf.debugging.assert_equal(\n shape_list(langs), [bs, slen]\n ), f\"Lang shape {shape_list(langs)} and input shape {[bs, slen]} mismatched\"\n # langs = langs.transpose(0, 1)\n\n # Prepare head mask if needed\n # 1.0 in head_mask indicate we keep the head\n # attention_probs has shape bsz x n_heads x N x N\n # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]\n # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x qlen x klen]\n if head_mask is not None:\n raise NotImplementedError\n else:\n head_mask = [None] * self.n_layers\n\n # do not recompute cached elements\n if cache is not None and input_ids is not None:\n _slen = slen - cache[\"slen\"]\n input_ids = input_ids[:, -_slen:]\n position_ids = position_ids[:, -_slen:]\n if langs is not None:\n langs = langs[:, -_slen:]\n mask = mask[:, -_slen:]\n attn_mask = attn_mask[:, -_slen:]\n\n # embeddings\n if inputs_embeds is None:\n inputs_embeds = self.embeddings(input_ids)\n\n tensor = inputs_embeds + self.position_embeddings(position_ids)\n if langs is not None and self.use_lang_emb:\n tensor = tensor + self.lang_embeddings(langs)\n if token_type_ids is not None:\n tensor = tensor + self.embeddings(token_type_ids)\n tensor = self.layer_norm_emb(tensor)\n tensor = self.dropout(tensor, training=training)\n tensor = tensor * mask[..., tf.newaxis]\n\n # transformer layers\n hidden_states = () if output_hidden_states else None\n attentions = () if output_attentions else None\n for i in range(self.n_layers):\n # LayerDrop\n dropout_probability = random.uniform(0, 1)\n if training and (dropout_probability < self.layerdrop):\n continue\n\n if output_hidden_states:\n hidden_states = hidden_states + (tensor,)\n\n # self attention\n if not self.pre_norm:\n attn_outputs = self.attentions[i](\n tensor, attn_mask, None, cache, head_mask[i], output_attentions, training=training\n )\n attn = attn_outputs[0]\n if output_attentions:\n attentions = attentions + (attn_outputs[1],)\n attn = self.dropout(attn, training=training)\n tensor = tensor + attn\n tensor = self.layer_norm1[i](tensor)\n else:\n tensor_normalized = self.layer_norm1[i](tensor)\n attn_outputs = self.attentions[i](\n tensor_normalized, attn_mask, None, cache, head_mask[i], output_attentions, training=training\n )\n attn = attn_outputs[0]\n if output_attentions:\n attentions = attentions + (attn_outputs[1],)\n attn = self.dropout(attn, training=training)\n tensor = tensor + attn\n\n # encoder attention (for decoder only)\n # if self.is_decoder and src_enc is not None:\n # attn = self.encoder_attn[i](tensor, src_mask, kv=src_enc, cache=cache)\n # attn = F.dropout(attn, p=self.dropout, training=self.training)\n # tensor = tensor + attn\n # tensor = self.layer_norm15[i](tensor)\n\n # FFN\n if not self.pre_norm:\n tensor = tensor + self.ffns[i](tensor)\n tensor = self.layer_norm2[i](tensor)\n else:\n tensor_normalized = self.layer_norm2[i](tensor)\n tensor = tensor + self.ffns[i](tensor_normalized)\n\n tensor = tensor * mask[..., tf.newaxis]\n\n # Add last hidden state\n if output_hidden_states:\n hidden_states = hidden_states + (tensor,)\n\n # update cache length\n if cache is not None:\n cache[\"slen\"] += tensor.size(1)\n\n # move back sequence length to dimension 0\n # tensor = tensor.transpose(0, 1)\n\n if not return_dict:\n return tuple(v for v in [tensor, hidden_states, attentions] if v is not None)\n return TFBaseModelOutput(last_hidden_state=tensor, hidden_states=hidden_states, attentions=attentions)\n\n\n@add_start_docstrings(\n \"\"\"The Flaubert Model transformer with a language modeling head on top\n (linear layer with weights tied to the input embeddings). \"\"\",\n FLAUBERT_START_DOCSTRING,\n)\nclass TFFlaubertWithLMHeadModel(TFXLMWithLMHeadModel):\n config_class = FlaubertConfig\n\n def __init__(self, config, *inputs, **kwargs):\n super().__init__(config, *inputs, **kwargs)\n self.transformer = TFFlaubertMainLayer(config, name=\"transformer\")\n self.pred_layer = TFXLMPredLayer(config, self.transformer.embeddings, name=\"pred_layer_._proj\")\n\n\n@add_start_docstrings(\n \"\"\"Flaubert Model with a sequence classification/regression head on top (a linear layer on top of\n the pooled output) e.g. for GLUE tasks. \"\"\",\n FLAUBERT_START_DOCSTRING,\n)\nclass TFFlaubertForSequenceClassification(TFXLMForSequenceClassification):\n config_class = FlaubertConfig\n\n def __init__(self, config, *inputs, **kwargs):\n super().__init__(config, *inputs, **kwargs)\n self.transformer = TFFlaubertMainLayer(config, name=\"transformer\")\n\n\n@add_start_docstrings(\n \"\"\"Flaubert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear layers on top of\n the hidden-states output to compute `span start logits` and `span end logits`). \"\"\",\n FLAUBERT_START_DOCSTRING,\n)\nclass TFFlaubertForQuestionAnsweringSimple(TFXLMForQuestionAnsweringSimple):\n config_class = FlaubertConfig\n\n def __init__(self, config, *inputs, **kwargs):\n super().__init__(config, *inputs, **kwargs)\n self.transformer = TFFlaubertMainLayer(config, name=\"transformer\")\n\n\n@add_start_docstrings(\n \"\"\"Flaubert Model with a token classification head on top (a linear layer on top of\n the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks. \"\"\",\n FLAUBERT_START_DOCSTRING,\n)\nclass TFFlaubertForTokenClassification(TFXLMForTokenClassification):\n def __init__(self, config, *inputs, **kwargs):\n super().__init__(config, *inputs, **kwargs)\n self.transformer = TFFlaubertMainLayer(config, name=\"transformer\")\n\n\n@add_start_docstrings(\n \"\"\"Flaubert Model with a multiple choice classification head on top (a linear layer on top of\n the pooled output and a softmax) e.g. for RocStories/SWAG tasks. \"\"\",\n FLAUBERT_START_DOCSTRING,\n)\nclass TFFlaubertForMultipleChoice(TFXLMForMultipleChoice):\n def __init__(self, config, *inputs, **kwargs):\n super().__init__(config, *inputs, **kwargs)\n self.transformer = TFFlaubertMainLayer(config, name=\"transformer\")\n"
] |
[
[
"tensorflow.not_equal",
"tensorflow.convert_to_tensor",
"tensorflow.range"
]
] |
DavidKatz-il/pdpipe
|
[
"5ddd066425d99886bfc51cf19ab78b2bf8c7791a"
] |
[
"tests/text_stages/test_regex_replace.py"
] |
[
"\"\"\"Test the RegexReplace pipeline stage.\"\"\"\n\nimport pandas as pd\nimport pdpipe as pdp\n\n\nDF = pd.DataFrame(\n data=[[4, \"more than 12\"], [5, \"with 5 more\"]],\n index=[1, 2],\n columns=[\"age\", \"text\"],\n)\n\n\ndef test_regex_replace():\n clean_num = pdp.RegexReplace('text', r'\\b[0-9]+\\b', \"NUM\")\n res_df = clean_num(DF)\n assert 'age' in res_df.columns\n assert 'text' in res_df.columns\n assert res_df.loc[1]['text'] == 'more than NUM'\n assert res_df.loc[2]['text'] == 'with NUM more'\n\n\ndef test_regex_replace_no_drop():\n clean_num = pdp.RegexReplace('text', r'\\b[0-9]+\\b', \"NUM\", drop=False)\n res_df = clean_num(DF)\n assert 'age' in res_df.columns\n assert 'text' in res_df.columns\n assert 'text_regex' in res_df.columns\n assert res_df.loc[1]['text'] == 'more than 12'\n assert res_df.loc[2]['text'] == 'with 5 more'\n assert res_df.loc[1]['text_regex'] == 'more than NUM'\n assert res_df.loc[2]['text_regex'] == 'with NUM more'\n"
] |
[
[
"pandas.DataFrame"
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.