code
stringlengths
31
1.05M
apis
list
extract_api
stringlengths
97
1.91M
import os import numpy as np import matplotlib.pyplot as plt from ovencontrol import open_sys_id_data as open_data TEMPERATURE_ORIGIN = 0 def reset_origin(temperature): current_origin = np.min(temperature[:5]) temperature[:] = temperature - (current_origin - TEMPERATURE_ORIGIN) def plot_signals(ax=None, export=False): tests = open_data.retrieve_data_single_inputs(os.path.join('..', 'data', 'system_identification')) if ax is None: fig, ax = plt.subplots() for key in sorted(tests.keys()): res = tests[key] reset_origin(res.temperature) ax.plot(res.time, res.temperature, label=key) ax.legend() ax.set_ylabel('Temperature increase (deg C)') ax.set_xlabel('Seconds since start') if export: save(fig, filename='tests') def plot_linearity(export=False): tests = open_data.retrieve_data_single_inputs(os.path.join('..', 'data', 'system_identification')) fig, ax = plt.subplots() for key in sorted(tests.keys()): res = tests[key] max_output = np.max(res.temperature) ax.plot(res.duty_cycle, max_output, 'x', label=key, markersize=12, markeredgewidth=2) ax.legend() ax.set_xlabel('duty cycle') ax.set_ylabel('highest temperature') ax.set_title('Steady-state gain over input') if export: save(fig, filename='linearity.png') def save(fig, filename=None, path=None): """Save the figure to disk as PNG.""" fig.tight_layout() if filename is None: filename = '_fig.png' if path is None: path = os.path.join('..', 'graphs') if not os.path.exists(path): os.makedirs(path) fig.savefig(os.path.join(path, filename), dpi=300) if __name__ == '__main__': plot_signals() plot_linearity() plt.show()
[ "os.path.exists", "os.makedirs", "os.path.join", "numpy.max", "numpy.min", "matplotlib.pyplot.subplots", "matplotlib.pyplot.show" ]
[((195, 218), 'numpy.min', 'np.min', (['temperature[:5]'], {}), '(temperature[:5])\n', (201, 218), True, 'import numpy as np\n'), ((955, 969), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (967, 969), True, 'import matplotlib.pyplot as plt\n'), ((1799, 1809), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1807, 1809), True, 'import matplotlib.pyplot as plt\n'), ((385, 436), 'os.path.join', 'os.path.join', (['""".."""', '"""data"""', '"""system_identification"""'], {}), "('..', 'data', 'system_identification')\n", (397, 436), False, 'import os\n'), ((475, 489), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (487, 489), True, 'import matplotlib.pyplot as plt\n'), ((888, 939), 'os.path.join', 'os.path.join', (['""".."""', '"""data"""', '"""system_identification"""'], {}), "('..', 'data', 'system_identification')\n", (900, 939), False, 'import os\n'), ((1053, 1076), 'numpy.max', 'np.max', (['res.temperature'], {}), '(res.temperature)\n', (1059, 1076), True, 'import numpy as np\n'), ((1583, 1611), 'os.path.join', 'os.path.join', (['""".."""', '"""graphs"""'], {}), "('..', 'graphs')\n", (1595, 1611), False, 'import os\n'), ((1623, 1643), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (1637, 1643), False, 'import os\n'), ((1653, 1670), 'os.makedirs', 'os.makedirs', (['path'], {}), '(path)\n', (1664, 1670), False, 'import os\n'), ((1687, 1715), 'os.path.join', 'os.path.join', (['path', 'filename'], {}), '(path, filename)\n', (1699, 1715), False, 'import os\n')]
#!/usr/bin/env python # -*- coding: utf-8 -*- """This module declares the different meanings that the Orbit 6 components can take and their conversions """ from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh import numpy as np from ..errors import UnknownFormError from ..utils.node import Node class Form(Node): """Base class for orbital form definition """ alt = { "theta": "θ", "phi": "φ", "raan": "Ω", "Omega": "Ω", "omega": "ω", "nu": "ν", "theta_dot": "θ_dot", "phi_dot": "φ_dot", "aol": "u", "H": "E", # The hyperbolic anomaly is available under the eccentric anomaly } def __init__(self, name, param_names): super().__init__(name) self.param_names = param_names def __str__(self): # pragma: no cover return self.name def __call__(self, orbit, new_form): """Gives the result of the transformation without in-place modifications Args: orbit (Orbit): new_form (str or Form): Returns: Coord """ if isinstance(new_form, Form): new_form = new_form.name coord = orbit.copy() if new_form != orbit.form.name: for a, b in self.steps(new_form): coord = getattr( self, "_{}_to_{}".format(a.name.lower(), b.name.lower()) )(coord, orbit.frame.center) return coord @classmethod def _cartesian_to_keplerian(cls, coord, center): """Conversion from cartesian (position and velocity) to keplerian The keplerian form is * a : semi-major axis * e : eccentricity * i : inclination * Ω : right-ascension of ascending node * ω : Argument of perigee * ν : True anomaly """ r, v = coord[:3], coord[3:] h = np.cross(r, v) # angular momentum vector h_norm = np.linalg.norm(h) r_norm = np.linalg.norm(r) v_norm = np.linalg.norm(v) K = v_norm ** 2 / 2 - center.µ / r_norm # specific energy a = -center.µ / (2 * K) # semi-major axis e = sqrt(1 - h_norm ** 2 / (a * center.µ)) # eccentricity p = a * (1 - e ** 2) # semi parameter i = arccos(h[2] / h_norm) # inclination Ω = arctan2(h[0], -h[1]) % (2 * np.pi) # right ascension of the ascending node ω_ν = arctan2(r[2] / sin(i), r[0] * cos(Ω) + r[1] * sin(Ω)) ν = arctan2(sqrt(p / center.µ) * np.dot(v, r), p - r_norm) % (2 * np.pi) ω = (ω_ν - ν) % (2 * np.pi) # argument of the perigee return np.array([a, e, i, Ω, ω, ν], dtype=float) @classmethod def _keplerian_to_cartesian(cls, coord, center): """Conversion from Keplerian to Cartesian coordinates """ a, e, i, Ω, ω, ν = coord p = a * (1 - e ** 2) r = p / (1 + e * cos(ν)) h = sqrt(center.µ * p) x = r * (cos(Ω) * cos(ω + ν) - sin(Ω) * sin(ω + ν) * cos(i)) y = r * (sin(Ω) * cos(ω + ν) + cos(Ω) * sin(ω + ν) * cos(i)) z = r * sin(i) * sin(ω + ν) vx = x * h * e / (r * p) * sin(ν) - h / r * ( cos(Ω) * sin(ω + ν) + sin(Ω) * cos(ω + ν) * cos(i) ) vy = y * h * e / (r * p) * sin(ν) - h / r * ( sin(Ω) * sin(ω + ν) - cos(Ω) * cos(ω + ν) * cos(i) ) vz = z * h * e / (r * p) * sin(ν) + h / r * sin(i) * cos(ω + ν) return np.array([x, y, z, vx, vy, vz], dtype=float) @classmethod def _keplerian_to_keplerian_eccentric(cls, coord, center): """Conversion from Keplerian to Keplerian Eccentric """ a, e, i, Ω, ω, ν = coord if e < 1: # Elliptic case cos_E = (e + cos(ν)) / (1 + e * cos(ν)) sin_E = (sin(ν) * sqrt(1 - e ** 2)) / (1 + e * cos(ν)) E = arctan2(sin_E, cos_E) % (2 * np.pi) else: # Hyperbolic case, E usually marked as H cosh_E = (e + cos(ν)) / (1 + e * cos(ν)) sinh_E = (sin(ν) * sqrt(e ** 2 - 1)) / (1 + e * cos(ν)) E = arctanh(sinh_E / cosh_E) return np.array([a, e, i, Ω, ω, E], dtype=float) @classmethod def _keplerian_eccentric_to_keplerian_mean(cls, coord, center): """Conversion from Keplerian Eccentric to Keplerian Mean """ a, e, i, Ω, ω, E = coord if e < 1: M = E - e * sin(E) else: # Hyperbolic case, E usually marked as H M = e * sinh(E) - E return np.array([a, e, i, Ω, ω, M], dtype=float) @classmethod def _keplerian_mean_to_keplerian_eccentric(cls, coord, center): """Conversion from Mean Keplerian to Keplerian Eccentric """ a, e, i, Ω, ω, M = coord E = cls.M2E(e, M) return np.array([a, e, i, Ω, ω, E], dtype=float) @classmethod def _keplerian_eccentric_to_keplerian(cls, coord, center): """Conversion from Mean Keplerian to True Keplerian """ a, e, i, Ω, ω, E = coord if e < 1: cos_ν = (cos(E) - e) / (1 - e * cos(E)) sin_ν = (sin(E) * sqrt(1 - e ** 2)) / (1 - e * cos(E)) else: # Hyperbolic case, E usually marked as H cos_ν = (cosh(E) - e) / (1 - e * cosh(E)) sin_ν = -(sinh(E) * sqrt(e ** 2 - 1)) / (1 - e * cosh(E)) ν = arctan2(sin_ν, cos_ν) % (np.pi * 2) return np.array([a, e, i, Ω, ω, ν], dtype=float) @classmethod def M2E(cls, e, M): """Conversion from Mean Anomaly to Eccentric anomaly, or Hyperbolic anomaly. from Vallado """ tol = 1e-8 if e < 1: # Ellipse if -np.pi < M < 0 or M > np.pi: E = M - e else: E = M + e def next_E(E, e, M): return E + (M - E + e * sin(E)) / (1 - e * cos(E)) E1 = next_E(E, e, M) while abs(E1 - E) >= tol: E = E1 E1 = next_E(E, e, M) return E1 else: # Hyperbolic if e < 1.6: if -np.pi < M < 0 or M > np.pi: H = M - e else: H = M + e else: if e < 3.6 and abs(M) > np.pi: H = M - np.sign(M) * e else: H = M / (e - 1) def next_H(H, e, M): return H + (M - e * sinh(H) + H) / (e * cosh(H) - 1) H1 = next_H(H, e, M) while abs(H1 - H) >= tol: H = H1 H1 = next_H(H, e, M) return H1 @classmethod def _e_e_sin_e(cls, e, E): x = (1 - e) * sin(E) term = float(E) d = 0 x0 = np.nan while x != x0: d += 2 term *= -(E ** 2) / (d * (d + 1)) x0 = x x = x - term return x @classmethod def _keplerian_circular_to_keplerian(cls, coord, center): """Conversion from Keplerian near-circular elements to Mean Keplerian """ a, ex, ey, i, Ω, u = coord e = sqrt(ex ** 2 + ey ** 2) ω = arctan2(ey / e, ex / e) ν = u - ω return np.array([a, e, i, Ω, ω, ν], dtype=float) @classmethod def _keplerian_to_keplerian_circular(cls, coord, center): """Conversion from Mean Keplerian to Keplerian near-circular elements """ a, e, i, Ω, ω, ν = coord ex = e * cos(ω) ey = e * sin(ω) u = (ω + ν) % (np.pi * 2) return np.array([a, ex, ey, i, Ω, u], dtype=float) @classmethod def _tle_to_keplerian_mean(cls, coord, center): """Conversion from the TLE standard format to the Mean Keplerian see :py:class:`Tle` for more information. """ i, Ω, e, ω, M, n = coord a = (center.µ / n ** 2) ** (1 / 3) return np.array([a, e, i, Ω, ω, M], dtype=float) @classmethod def _keplerian_mean_to_tle(cls, coord, center): """Mean Keplerian to TLE format conversion """ a, e, i, Ω, ω, M = coord n = sqrt(center.µ / a ** 3) return np.array([i, Ω, e, ω, M, n], dtype=float) @classmethod def _cartesian_to_spherical(cls, coord, center): """Cartesian to Spherical conversion .. warning:: The spherical form is equatorial, not zenithal """ x, y, z, vx, vy, vz = coord r = np.linalg.norm(coord[:3]) phi = arcsin(z / r) theta = arctan2(y, x) r_dot = (x * vx + y * vy + z * vz) / r phi_dot = (vz * (x ** 2 + y ** 2) - z * (x * vx + y * vy)) / ( r ** 2 * sqrt(x ** 2 + y ** 2) ) theta_dot = (x * vy - y * vx) / (x ** 2 + y ** 2) return np.array([r, theta, phi, r_dot, theta_dot, phi_dot], dtype=float) @classmethod def _spherical_to_cartesian(cls, coord, center): """Spherical to cartesian conversion """ r, theta, phi, r_dot, theta_dot, phi_dot = coord x = r * cos(phi) * cos(theta) y = r * cos(phi) * sin(theta) z = r * sin(phi) vx = r_dot * x / r - y * theta_dot - z * phi_dot * cos(theta) vy = r_dot * y / r + x * theta_dot - z * phi_dot * sin(theta) vz = r_dot * z / r + r * phi_dot * cos(phi) return np.array([x, y, z, vx, vy, vz], dtype=float) TLE = Form("tle", ["i", "Ω", "e", "ω", "M", "n"]) """TLE special form * i : inclination * Ω : right-ascension of ascending node * e : eccentricity * ω : argument of perigee * M : mean anomaly * n : mean motion see :py:class:`~beyond.orbits.tle.Tle` for details """ KEPL_C = Form("keplerian_circular", ["a", "ex", "ey", "i", "Ω", "u"]) """Special case for near-circular orbits * a : semi-major axis * ex : e * cos(ω) * ey : e * sin(ω) * i : inclination * Ω : right-ascension of ascending node * u : argument of latitude (ω + ν) """ KEPL_E = Form("keplerian_eccentric", ["a", "e", "i", "Ω", "ω", "E"]) """Same as Keplerian, but replaces True anomaly with `Eccentric anomaly <https://en.wikipedia.org/wiki/Eccentric_anomaly>`__ """ KEPL_M = Form("keplerian_mean", ["a", "e", "i", "Ω", "ω", "M"]) """Same as Keplerian, but replaces True anomaly with `Mean anomaly <https://en.wikipedia.org/wiki/Mean_anomaly>`__ """ KEPL = Form("keplerian", ["a", "e", "i", "Ω", "ω", "ν"]) """The keplerian form is * a : semi-major axis * e : eccentricity * i : inclination * Ω : right-ascension of ascending node * ω : Argument of perigee * ν : True anomaly see `wikipedia <https://en.wikipedia.org/wiki/Orbital_elements>`__ for details """ SPHE = Form("spherical", ["r", "θ", "φ", "r_dot", "θ_dot", "φ_dot"]) """Spherical form * r : radial distance / altitude * θ : azimuth / longitude * φ : elevation / latitude * r_dot : first derivative of radial distance / altitude * θ_dot : first derivative of azimuth / longitude * φ_dot : first derivative of elevation / latitude """ CART = Form("cartesian", ["x", "y", "z", "vx", "vy", "vz"]) """Cartesian form""" SPHE + CART + KEPL + KEPL_E + KEPL_M + TLE KEPL + KEPL_C _cache = { "tle": TLE, "keplerian_circular": KEPL_C, "keplerian_mean": KEPL_M, "keplerian_eccentric": KEPL_E, "keplerian": KEPL, "spherical": SPHE, "cartesian": CART, } def get_form(form): # pragma: no cover if form.lower() not in _cache: raise UnknownFormError(form) return _cache[form.lower()]
[ "numpy.arctanh", "numpy.arccos", "numpy.sqrt", "numpy.cross", "numpy.arcsin", "numpy.sinh", "numpy.array", "numpy.dot", "numpy.arctan2", "numpy.cos", "numpy.cosh", "numpy.linalg.norm", "numpy.sin", "numpy.sign" ]
[((1964, 1978), 'numpy.cross', 'np.cross', (['r', 'v'], {}), '(r, v)\n', (1972, 1978), True, 'import numpy as np\n'), ((2023, 2040), 'numpy.linalg.norm', 'np.linalg.norm', (['h'], {}), '(h)\n', (2037, 2040), True, 'import numpy as np\n'), ((2058, 2075), 'numpy.linalg.norm', 'np.linalg.norm', (['r'], {}), '(r)\n', (2072, 2075), True, 'import numpy as np\n'), ((2093, 2110), 'numpy.linalg.norm', 'np.linalg.norm', (['v'], {}), '(v)\n', (2107, 2110), True, 'import numpy as np\n'), ((2242, 2280), 'numpy.sqrt', 'sqrt', (['(1 - h_norm ** 2 / (a * center.μ))'], {}), '(1 - h_norm ** 2 / (a * center.μ))\n', (2246, 2280), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((2356, 2377), 'numpy.arccos', 'arccos', (['(h[2] / h_norm)'], {}), '(h[2] / h_norm)\n', (2362, 2377), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((2710, 2751), 'numpy.array', 'np.array', (['[a, e, i, Ω, ω, ν]'], {'dtype': 'float'}), '([a, e, i, Ω, ω, ν], dtype=float)\n', (2718, 2751), True, 'import numpy as np\n'), ((3006, 3024), 'numpy.sqrt', 'sqrt', (['(center.μ * p)'], {}), '(center.μ * p)\n', (3010, 3024), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((3541, 3585), 'numpy.array', 'np.array', (['[x, y, z, vx, vy, vz]'], {'dtype': 'float'}), '([x, y, z, vx, vy, vz], dtype=float)\n', (3549, 3585), True, 'import numpy as np\n'), ((4235, 4276), 'numpy.array', 'np.array', (['[a, e, i, Ω, ω, E]'], {'dtype': 'float'}), '([a, e, i, Ω, ω, E], dtype=float)\n', (4243, 4276), True, 'import numpy as np\n'), ((4638, 4679), 'numpy.array', 'np.array', (['[a, e, i, Ω, ω, M]'], {'dtype': 'float'}), '([a, e, i, Ω, ω, M], dtype=float)\n', (4646, 4679), True, 'import numpy as np\n'), ((4918, 4959), 'numpy.array', 'np.array', (['[a, e, i, Ω, ω, E]'], {'dtype': 'float'}), '([a, e, i, Ω, ω, E], dtype=float)\n', (4926, 4959), True, 'import numpy as np\n'), ((5541, 5582), 'numpy.array', 'np.array', (['[a, e, i, Ω, ω, ν]'], {'dtype': 'float'}), '([a, e, i, Ω, ω, ν], dtype=float)\n', (5549, 5582), True, 'import numpy as np\n'), ((7307, 7330), 'numpy.sqrt', 'sqrt', (['(ex ** 2 + ey ** 2)'], {}), '(ex ** 2 + ey ** 2)\n', (7311, 7330), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((7344, 7367), 'numpy.arctan2', 'arctan2', (['(ey / e)', '(ex / e)'], {}), '(ey / e, ex / e)\n', (7351, 7367), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((7401, 7442), 'numpy.array', 'np.array', (['[a, e, i, Ω, ω, ν]'], {'dtype': 'float'}), '([a, e, i, Ω, ω, ν], dtype=float)\n', (7409, 7442), True, 'import numpy as np\n'), ((7745, 7788), 'numpy.array', 'np.array', (['[a, ex, ey, i, Ω, u]'], {'dtype': 'float'}), '([a, ex, ey, i, Ω, u], dtype=float)\n', (7753, 7788), True, 'import numpy as np\n'), ((8087, 8128), 'numpy.array', 'np.array', (['[a, e, i, Ω, ω, M]'], {'dtype': 'float'}), '([a, e, i, Ω, ω, M], dtype=float)\n', (8095, 8128), True, 'import numpy as np\n'), ((8307, 8330), 'numpy.sqrt', 'sqrt', (['(center.μ / a ** 3)'], {}), '(center.μ / a ** 3)\n', (8311, 8330), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((8347, 8388), 'numpy.array', 'np.array', (['[i, Ω, e, ω, M, n]'], {'dtype': 'float'}), '([i, Ω, e, ω, M, n], dtype=float)\n', (8355, 8388), True, 'import numpy as np\n'), ((8634, 8659), 'numpy.linalg.norm', 'np.linalg.norm', (['coord[:3]'], {}), '(coord[:3])\n', (8648, 8659), True, 'import numpy as np\n'), ((8674, 8687), 'numpy.arcsin', 'arcsin', (['(z / r)'], {}), '(z / r)\n', (8680, 8687), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((8704, 8717), 'numpy.arctan2', 'arctan2', (['y', 'x'], {}), '(y, x)\n', (8711, 8717), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((8964, 9029), 'numpy.array', 'np.array', (['[r, theta, phi, r_dot, theta_dot, phi_dot]'], {'dtype': 'float'}), '([r, theta, phi, r_dot, theta_dot, phi_dot], dtype=float)\n', (8972, 9029), True, 'import numpy as np\n'), ((9525, 9569), 'numpy.array', 'np.array', (['[x, y, z, vx, vy, vz]'], {'dtype': 'float'}), '([x, y, z, vx, vy, vz], dtype=float)\n', (9533, 9569), True, 'import numpy as np\n'), ((2406, 2426), 'numpy.arctan2', 'arctan2', (['h[0]', '(-h[1])'], {}), '(h[0], -h[1])\n', (2413, 2426), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((3188, 3198), 'numpy.sin', 'sin', (['(ω + ν)'], {}), '(ω + ν)\n', (3191, 3198), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((4194, 4218), 'numpy.arctanh', 'arctanh', (['(sinh_E / cosh_E)'], {}), '(sinh_E / cosh_E)\n', (4201, 4218), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((5490, 5511), 'numpy.arctan2', 'arctan2', (['sin_ν', 'cos_ν'], {}), '(sin_ν, cos_ν)\n', (5497, 5511), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((6875, 6881), 'numpy.sin', 'sin', (['E'], {}), '(E)\n', (6878, 6881), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((7664, 7670), 'numpy.cos', 'cos', (['ω'], {}), '(ω)\n', (7667, 7670), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((7688, 7694), 'numpy.sin', 'sin', (['ω'], {}), '(ω)\n', (7691, 7694), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((9242, 9252), 'numpy.cos', 'cos', (['theta'], {}), '(theta)\n', (9245, 9252), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((9280, 9290), 'numpy.sin', 'sin', (['theta'], {}), '(theta)\n', (9283, 9290), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((9307, 9315), 'numpy.sin', 'sin', (['phi'], {}), '(phi)\n', (9310, 9315), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((2513, 2519), 'numpy.sin', 'sin', (['i'], {}), '(i)\n', (2516, 2519), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((3179, 3185), 'numpy.sin', 'sin', (['i'], {}), '(i)\n', (3182, 3185), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((3234, 3240), 'numpy.sin', 'sin', (['ν'], {}), '(ν)\n', (3237, 3240), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((3361, 3367), 'numpy.sin', 'sin', (['ν'], {}), '(ν)\n', (3364, 3367), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((3488, 3494), 'numpy.sin', 'sin', (['ν'], {}), '(ν)\n', (3491, 3494), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((3515, 3525), 'numpy.cos', 'cos', (['(ω + ν)'], {}), '(ω + ν)\n', (3518, 3525), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((3954, 3975), 'numpy.arctan2', 'arctan2', (['sin_E', 'cos_E'], {}), '(sin_E, cos_E)\n', (3961, 3975), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((8858, 8879), 'numpy.sqrt', 'sqrt', (['(x ** 2 + y ** 2)'], {}), '(x ** 2 + y ** 2)\n', (8862, 8879), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((9231, 9239), 'numpy.cos', 'cos', (['phi'], {}), '(phi)\n', (9234, 9239), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((9269, 9277), 'numpy.cos', 'cos', (['phi'], {}), '(phi)\n', (9272, 9277), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((9376, 9386), 'numpy.cos', 'cos', (['theta'], {}), '(theta)\n', (9379, 9386), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((9446, 9456), 'numpy.sin', 'sin', (['theta'], {}), '(theta)\n', (9449, 9456), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((9500, 9508), 'numpy.cos', 'cos', (['phi'], {}), '(phi)\n', (9503, 9508), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((2528, 2534), 'numpy.cos', 'cos', (['Ω'], {}), '(Ω)\n', (2531, 2534), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((2545, 2551), 'numpy.sin', 'sin', (['Ω'], {}), '(Ω)\n', (2548, 2551), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((2571, 2589), 'numpy.sqrt', 'sqrt', (['(p / center.μ)'], {}), '(p / center.μ)\n', (2575, 2589), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((2593, 2605), 'numpy.dot', 'np.dot', (['v', 'r'], {}), '(v, r)\n', (2599, 2605), True, 'import numpy as np\n'), ((2986, 2992), 'numpy.cos', 'cos', (['ν'], {}), '(ν)\n', (2989, 2992), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((3042, 3048), 'numpy.cos', 'cos', (['Ω'], {}), '(Ω)\n', (3045, 3048), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((3052, 3062), 'numpy.cos', 'cos', (['(ω + ν)'], {}), '(ω + ν)\n', (3055, 3062), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((3092, 3098), 'numpy.cos', 'cos', (['i'], {}), '(i)\n', (3095, 3098), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((3111, 3117), 'numpy.sin', 'sin', (['Ω'], {}), '(Ω)\n', (3114, 3117), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((3121, 3131), 'numpy.cos', 'cos', (['(ω + ν)'], {}), '(ω + ν)\n', (3124, 3131), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((3161, 3167), 'numpy.cos', 'cos', (['i'], {}), '(i)\n', (3164, 3167), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((3506, 3512), 'numpy.sin', 'sin', (['i'], {}), '(i)\n', (3509, 3512), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((3844, 3850), 'numpy.cos', 'cos', (['ν'], {}), '(ν)\n', (3847, 3850), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((3892, 3898), 'numpy.sin', 'sin', (['ν'], {}), '(ν)\n', (3895, 3898), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((3902, 3918), 'numpy.sqrt', 'sqrt', (['(1 - e ** 2)'], {}), '(1 - e ** 2)\n', (3906, 3918), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((4083, 4089), 'numpy.cos', 'cos', (['ν'], {}), '(ν)\n', (4086, 4089), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((4132, 4138), 'numpy.sin', 'sin', (['ν'], {}), '(ν)\n', (4135, 4138), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((4142, 4158), 'numpy.sqrt', 'sqrt', (['(e ** 2 - 1)'], {}), '(e ** 2 - 1)\n', (4146, 4158), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((4516, 4522), 'numpy.sin', 'sin', (['E'], {}), '(E)\n', (4519, 4522), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((4610, 4617), 'numpy.sinh', 'sinh', (['E'], {}), '(E)\n', (4614, 4617), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((5188, 5194), 'numpy.cos', 'cos', (['E'], {}), '(E)\n', (5191, 5194), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((5240, 5246), 'numpy.sin', 'sin', (['E'], {}), '(E)\n', (5243, 5246), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((5249, 5265), 'numpy.sqrt', 'sqrt', (['(1 - e ** 2)'], {}), '(1 - e ** 2)\n', (5253, 5265), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((5374, 5381), 'numpy.cosh', 'cosh', (['E'], {}), '(E)\n', (5378, 5381), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((3067, 3073), 'numpy.sin', 'sin', (['Ω'], {}), '(Ω)\n', (3070, 3073), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((3077, 3087), 'numpy.sin', 'sin', (['(ω + ν)'], {}), '(ω + ν)\n', (3080, 3087), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((3136, 3142), 'numpy.cos', 'cos', (['Ω'], {}), '(Ω)\n', (3139, 3142), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((3146, 3156), 'numpy.sin', 'sin', (['(ω + ν)'], {}), '(ω + ν)\n', (3149, 3156), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((3265, 3271), 'numpy.cos', 'cos', (['Ω'], {}), '(Ω)\n', (3268, 3271), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((3275, 3285), 'numpy.sin', 'sin', (['(ω + ν)'], {}), '(ω + ν)\n', (3278, 3285), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((3315, 3321), 'numpy.cos', 'cos', (['i'], {}), '(i)\n', (3318, 3321), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((3392, 3398), 'numpy.sin', 'sin', (['Ω'], {}), '(Ω)\n', (3395, 3398), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((3402, 3412), 'numpy.sin', 'sin', (['(ω + ν)'], {}), '(ω + ν)\n', (3405, 3412), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((3442, 3448), 'numpy.cos', 'cos', (['i'], {}), '(i)\n', (3445, 3448), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((3864, 3870), 'numpy.cos', 'cos', (['ν'], {}), '(ν)\n', (3867, 3870), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((3931, 3937), 'numpy.cos', 'cos', (['ν'], {}), '(ν)\n', (3934, 3937), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((4103, 4109), 'numpy.cos', 'cos', (['ν'], {}), '(ν)\n', (4106, 4109), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((4171, 4177), 'numpy.cos', 'cos', (['ν'], {}), '(ν)\n', (4174, 4177), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((5211, 5217), 'numpy.cos', 'cos', (['E'], {}), '(E)\n', (5214, 5217), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((5278, 5284), 'numpy.cos', 'cos', (['E'], {}), '(E)\n', (5281, 5284), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((5398, 5405), 'numpy.cosh', 'cosh', (['E'], {}), '(E)\n', (5402, 5405), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((5429, 5436), 'numpy.sinh', 'sinh', (['E'], {}), '(E)\n', (5433, 5436), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((5439, 5455), 'numpy.sqrt', 'sqrt', (['(e ** 2 - 1)'], {}), '(e ** 2 - 1)\n', (5443, 5455), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((5468, 5475), 'numpy.cosh', 'cosh', (['E'], {}), '(E)\n', (5472, 5475), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((3290, 3296), 'numpy.sin', 'sin', (['Ω'], {}), '(Ω)\n', (3293, 3296), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((3300, 3310), 'numpy.cos', 'cos', (['(ω + ν)'], {}), '(ω + ν)\n', (3303, 3310), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((3417, 3423), 'numpy.cos', 'cos', (['Ω'], {}), '(Ω)\n', (3420, 3423), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((3427, 3437), 'numpy.cos', 'cos', (['(ω + ν)'], {}), '(ω + ν)\n', (3430, 3437), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((6473, 6483), 'numpy.sign', 'np.sign', (['M'], {}), '(M)\n', (6480, 6483), True, 'import numpy as np\n'), ((6005, 6011), 'numpy.sin', 'sin', (['E'], {}), '(E)\n', (6008, 6011), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((6024, 6030), 'numpy.cos', 'cos', (['E'], {}), '(E)\n', (6027, 6030), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((6636, 6643), 'numpy.cosh', 'cosh', (['H'], {}), '(H)\n', (6640, 6643), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n'), ((6616, 6623), 'numpy.sinh', 'sinh', (['H'], {}), '(H)\n', (6620, 6623), False, 'from numpy import cos, arccos, sin, arcsin, arctan2, sqrt, arctanh, sinh, cosh\n')]
import pdb import os import cv2 import time from glob import glob import torch import scipy import pandas as pd import numpy as np from tqdm import tqdm import torch.backends.cudnn as cudnn from torch.utils.data import DataLoader from argparse import ArgumentParser import albumentations from albumentations import torch as AT from torchvision.datasets.folder import pil_loader import torch.utils.data as data from sklearn.model_selection import KFold, StratifiedKFold from sklearn.metrics import cohen_kappa_score from models import Model, get_model from utils import * from image_utils import * def get_parser(): parser = ArgumentParser() parser.add_argument( "-c", "--model_folder_path", dest="model_folder_path", help="relative path to the folder where model checkpoints are saved", ) parser.add_argument( "-p", "--predict_on", dest="predict_on", help="predict on train or test set, options: test or train", default="resnext101_32x4d", ) return parser class TestDataset(data.Dataset): def __init__(self, root, df, size, mean, std, tta=4): self.root = root self.size = size self.fnames = list(df["id_code"]) self.num_samples = len(self.fnames) self.tta = tta self.TTA = albumentations.Compose( [ albumentations.Rotate(limit=180, p=0.5), albumentations.Transpose(p=0.5), albumentations.Flip(p=0.5), albumentations.RandomScale(scale_limit=0.1), ] ) self.transform = albumentations.Compose( [ albumentations.Normalize(mean=mean, std=std, p=1), albumentations.Resize(size, size), AT.ToTensor() ] ) def __getitem__(self, idx): fname = self.fnames[idx] path = os.path.join(self.root, fname + ".png") # image = load_image(path, size) # image = load_ben_gray(path) image = load_ben_color(path, size=self.size, crop=True) images = [self.transform(image=image)["image"]] for _ in range(self.tta): # perform ttas aug_img = self.TTA(image=image)["image"] aug_img = self.transform(image=aug_img)["image"] images.append(aug_img) return torch.stack(images, dim=0) def __len__(self): return self.num_samples def get_predictions(model, testset, tta): """return all predictions on testset in a list""" num_images = len(testset) predictions = [] for i, batch in enumerate(tqdm(testset)): if tta: for images in batch: # images.shape [n, 3, 96, 96] where n is num of 1+tta preds = model(images.to(device)) # [n, num_classes] predictions.append(preds.mean(dim=0).detach().tolist()) else: preds = model(batch[:, 0].to(device)) preds = preds.detach().tolist() #[1] predictions.extend(preds) return np.array(predictions) def get_model_name_fold(model_folder_path): # example ckpt_path = weights/9-7_{modelname}_fold0_text/ model_folder = model_folder_path.split("/")[1] # 9-7_{modelname}_fold0_text model_name = "_".join(model_folder.split("_")[1:-2]) # modelname fold = model_folder.split("_")[-2] # fold0 fold = fold.split("fold")[-1] # 0 return model_name, int(fold) if __name__ == "__main__": ''' Generates predictions on train/test set using the ckpts saved in the model folder path and saves them in npy_folder in npy format which can be analyses later for different thresholds ''' parser = get_parser() args = parser.parse_args() model_folder_path = args.model_folder_path predict_on = args.predict_on model_name, fold = get_model_name_fold(model_folder_path) if predict_on == "test": sample_submission_path = "data/sample_submission.csv" else: sample_submission_path = "data/train.csv" tta = 4 # number of augs in tta start_epoch = 0 end_epoch = 26 root = f"data/{predict_on}_images/" size = 300 mean = (0.485, 0.456, 0.406) std = (0.229, 0.224, 0.225) #mean = (0, 0, 0) #std = (1, 1, 1) use_cuda = True num_classes = 1 num_workers = 8 batch_size = 16 device = torch.device("cuda" if use_cuda else "cpu") if use_cuda: cudnn.benchmark = True torch.set_default_tensor_type("torch.cuda.FloatTensor") else: torch.set_default_tensor_type("torch.FloatTensor") df = pd.read_csv(sample_submission_path) testset = DataLoader( TestDataset(root, df, size, mean, std, tta), batch_size=batch_size, shuffle=False, num_workers=num_workers, pin_memory=True if use_cuda else False, ) model = get_model(model_name, num_classes, pretrained=None) model.to(device) model.eval() npy_folder = os.path.join(model_folder_path, "%s_npy" % predict_on) mkdir(npy_folder) print(f"\nUsing model: {model_name} | fold: {fold}") print(f"Predicting on: {predict_on} set") print(f"Root: {root}") print(f"size: {size}") print(f"mean: {mean}") print(f"std: {std}") print(f"Saving predictions at: {npy_folder}") print(f"From epoch {start_epoch} to {end_epoch}") print(f"Using tta: {tta}\n") for epoch in range(start_epoch, end_epoch+1): print(f"Using ckpt{epoch}.pth") ckpt_path = os.path.join(model_folder_path, "ckpt%d.pth" % epoch) state = torch.load(ckpt_path, map_location=lambda storage, loc: storage) model.load_state_dict(state["state_dict"]) best_thresholds = state["best_thresholds"] print(f"Best thresholds: {best_thresholds}") preds = get_predictions(model, testset, tta) pred_labels = predict(preds, best_thresholds) print(np.unique(pred_labels, return_counts=True)) mat_to_save = [preds, best_thresholds] np.save(os.path.join(npy_folder, f"{predict_on}_ckpt{epoch}.npy"), mat_to_save) print("Predictions saved!") ''' Footnotes [1] a cuda variable can be converted to python list with .detach() (i.e., grad no longer required) then .tolist(), apart from that a cuda variable can be converted to numpy variable only by copying the tensor to host memory by .cpu() and then .numpy '''
[ "numpy.unique", "pandas.read_csv", "argparse.ArgumentParser", "models.get_model", "torch.load", "torch.stack", "os.path.join", "tqdm.tqdm", "torch.set_default_tensor_type", "albumentations.Rotate", "albumentations.Flip", "numpy.array", "albumentations.Normalize", "albumentations.Resize", ...
[((630, 646), 'argparse.ArgumentParser', 'ArgumentParser', ([], {}), '()\n', (644, 646), False, 'from argparse import ArgumentParser\n'), ((3053, 3074), 'numpy.array', 'np.array', (['predictions'], {}), '(predictions)\n', (3061, 3074), True, 'import numpy as np\n'), ((4378, 4421), 'torch.device', 'torch.device', (["('cuda' if use_cuda else 'cpu')"], {}), "('cuda' if use_cuda else 'cpu')\n", (4390, 4421), False, 'import torch\n'), ((4613, 4648), 'pandas.read_csv', 'pd.read_csv', (['sample_submission_path'], {}), '(sample_submission_path)\n', (4624, 4648), True, 'import pandas as pd\n'), ((4882, 4933), 'models.get_model', 'get_model', (['model_name', 'num_classes'], {'pretrained': 'None'}), '(model_name, num_classes, pretrained=None)\n', (4891, 4933), False, 'from models import Model, get_model\n'), ((4990, 5044), 'os.path.join', 'os.path.join', (['model_folder_path', "('%s_npy' % predict_on)"], {}), "(model_folder_path, '%s_npy' % predict_on)\n", (5002, 5044), False, 'import os\n'), ((1915, 1954), 'os.path.join', 'os.path.join', (['self.root', "(fname + '.png')"], {}), "(self.root, fname + '.png')\n", (1927, 1954), False, 'import os\n'), ((2368, 2394), 'torch.stack', 'torch.stack', (['images'], {'dim': '(0)'}), '(images, dim=0)\n', (2379, 2394), False, 'import torch\n'), ((2630, 2643), 'tqdm.tqdm', 'tqdm', (['testset'], {}), '(testset)\n', (2634, 2643), False, 'from tqdm import tqdm\n'), ((4478, 4533), 'torch.set_default_tensor_type', 'torch.set_default_tensor_type', (['"""torch.cuda.FloatTensor"""'], {}), "('torch.cuda.FloatTensor')\n", (4507, 4533), False, 'import torch\n'), ((4552, 4602), 'torch.set_default_tensor_type', 'torch.set_default_tensor_type', (['"""torch.FloatTensor"""'], {}), "('torch.FloatTensor')\n", (4581, 4602), False, 'import torch\n'), ((5525, 5578), 'os.path.join', 'os.path.join', (['model_folder_path', "('ckpt%d.pth' % epoch)"], {}), "(model_folder_path, 'ckpt%d.pth' % epoch)\n", (5537, 5578), False, 'import os\n'), ((5595, 5659), 'torch.load', 'torch.load', (['ckpt_path'], {'map_location': '(lambda storage, loc: storage)'}), '(ckpt_path, map_location=lambda storage, loc: storage)\n', (5605, 5659), False, 'import torch\n'), ((5937, 5979), 'numpy.unique', 'np.unique', (['pred_labels'], {'return_counts': '(True)'}), '(pred_labels, return_counts=True)\n', (5946, 5979), True, 'import numpy as np\n'), ((6045, 6102), 'os.path.join', 'os.path.join', (['npy_folder', 'f"""{predict_on}_ckpt{epoch}.npy"""'], {}), "(npy_folder, f'{predict_on}_ckpt{epoch}.npy')\n", (6057, 6102), False, 'import os\n'), ((1379, 1418), 'albumentations.Rotate', 'albumentations.Rotate', ([], {'limit': '(180)', 'p': '(0.5)'}), '(limit=180, p=0.5)\n', (1400, 1418), False, 'import albumentations\n'), ((1436, 1467), 'albumentations.Transpose', 'albumentations.Transpose', ([], {'p': '(0.5)'}), '(p=0.5)\n', (1460, 1467), False, 'import albumentations\n'), ((1485, 1511), 'albumentations.Flip', 'albumentations.Flip', ([], {'p': '(0.5)'}), '(p=0.5)\n', (1504, 1511), False, 'import albumentations\n'), ((1529, 1572), 'albumentations.RandomScale', 'albumentations.RandomScale', ([], {'scale_limit': '(0.1)'}), '(scale_limit=0.1)\n', (1555, 1572), False, 'import albumentations\n'), ((1678, 1727), 'albumentations.Normalize', 'albumentations.Normalize', ([], {'mean': 'mean', 'std': 'std', 'p': '(1)'}), '(mean=mean, std=std, p=1)\n', (1702, 1727), False, 'import albumentations\n'), ((1745, 1778), 'albumentations.Resize', 'albumentations.Resize', (['size', 'size'], {}), '(size, size)\n', (1766, 1778), False, 'import albumentations\n'), ((1796, 1809), 'albumentations.torch.ToTensor', 'AT.ToTensor', ([], {}), '()\n', (1807, 1809), True, 'from albumentations import torch as AT\n')]
import matplotlib.pyplot as plt import numpy as np from selfdrive.config import Conversions as CV x = [0.0, 1.4082, 2.8031, 4.2266, 5.3827, 6.1656, 7.2478, 8.2831, 10.2447, 12.964, 15.423, 18.119, 20.117, 24.4661, 29.0581, 32.7101, 35.7633] y = [0.218, 0.222, 0.233, 0.25, 0.273, 0.294, 0.337, 0.362, 0.38, 0.389, 0.398, 0.41, 0.421, 0.459, 0.512, 0.564, 0.621] y = [np.interp(i, [0.218, (0.218 + 0.398) / 2, 0.398], [1.075 * i, i * 1.05, i]) for i in y] # more gas at lower speeds up until ~40 mph plt.plot(x, y, 'o-', label='corolla old') y2 = [0.1969, 0.2045, 0.2183, 0.238, 0.2625, 0.2841, 0.3242, 0.3476, 0.3651, 0.3772, 0.3889, 0.4061, 0.421, 0.459, 0.5144, 0.5756, 0.6421] plt.plot(x, y2, 'o-', label='corolla new') y = np.array(y) * 0.6 + np.array(y2) * 0.4 plt.plot(x, y, 'o-', label='corolla new new') # plt.plot([min(x), max(x)], [0, 0], 'r--') # plt.plot([0, 0], [min(y), max(y)], 'r--') # plt.xlabel('mph') # plt.ylabel('feet') # poly = np.polyfit(x, y, 6) # x = np.linspace(min(x), max(x), 100) # y = np.polyval(poly, x) # plt.plot(x, y, label='poly fit') # to_round = True # if to_round: # x = np.round(x, 4) # y = np.round(y, 5) # print('x = {}'.format(x.tolist())) # print('y = {}'.format(y.tolist())) plt.legend() plt.show()
[ "matplotlib.pyplot.plot", "numpy.array", "numpy.interp", "matplotlib.pyplot.legend", "matplotlib.pyplot.show" ]
[((502, 543), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y', '"""o-"""'], {'label': '"""corolla old"""'}), "(x, y, 'o-', label='corolla old')\n", (510, 543), True, 'import matplotlib.pyplot as plt\n'), ((684, 726), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y2', '"""o-"""'], {'label': '"""corolla new"""'}), "(x, y2, 'o-', label='corolla new')\n", (692, 726), True, 'import matplotlib.pyplot as plt\n'), ((772, 817), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y', '"""o-"""'], {'label': '"""corolla new new"""'}), "(x, y, 'o-', label='corolla new new')\n", (780, 817), True, 'import matplotlib.pyplot as plt\n'), ((1240, 1252), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (1250, 1252), True, 'import matplotlib.pyplot as plt\n'), ((1253, 1263), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1261, 1263), True, 'import matplotlib.pyplot as plt\n'), ((368, 443), 'numpy.interp', 'np.interp', (['i', '[0.218, (0.218 + 0.398) / 2, 0.398]', '[1.075 * i, i * 1.05, i]'], {}), '(i, [0.218, (0.218 + 0.398) / 2, 0.398], [1.075 * i, i * 1.05, i])\n', (377, 443), True, 'import numpy as np\n'), ((732, 743), 'numpy.array', 'np.array', (['y'], {}), '(y)\n', (740, 743), True, 'import numpy as np\n'), ((752, 764), 'numpy.array', 'np.array', (['y2'], {}), '(y2)\n', (760, 764), True, 'import numpy as np\n')]
import random import numpy as np import cv2 import matplotlib.pyplot as plt # from matplotlib import pyplot as plt import scipy from scipy import signal from PIL import Image from scipy.ndimage import median_filter # 由于卷积核的大小一般是奇数,因此这里假设卷积核是奇数的 ''' #################### 图像处理的基本函数 #################### ''' # 图像加框 def addBoundary(img, kernel): ''' 给图像添加边界 :param img: 输入图像 :param kernel:卷积核 :return: 加边界后的图像 ''' kernel_size = kernel.shape[0] addLine = (int)((kernel_size - 1) / 2) img_ = cv2.copyMakeBorder(img, addLine, addLine, addLine, addLine, cv2.BORDER_CONSTANT, value=0); return img_ def convolve1(img, kernel, filter_type, mode='same'): ''' 单通道图像与卷积核的卷积,主要用于灰度图 :param img: 输入单通道图像矩阵 :param kernel: 卷积核 :param model: medium,gauss,mean, 即选择中值滤波、高斯滤波、还是均值滤波,其他滤波方式以后添加 :return: 卷积后的图像 ''' if mode == 'same': img_ = addBoundary(img, kernel) kernel_height = kernel.shape[0] kernel_width = kernel.shape[1] # 横向卷积、纵向卷积的次数 conv_height = img_.shape[0] - kernel_height + 1 conv_width = img_.shape[1] - kernel_width + 1 # 卷积结果存储在conv中 conv = np.zeros((conv_height, conv_width), dtype='uint8') for i in range(conv_height): for j in range(conv_width): conv[i][j] = wise_element_sum(img_[i:i + kernel_height, j:j + kernel_width], kernel, filter_type) return conv def wise_element_sum(img, kernel, filter_type): ''' 对于某一次卷积结果的取值 :param img: 输入的图片片段矩阵 :param kernel: 卷积核 :param modle: medium,gauss,mean, 即选择中值滤波、高斯滤波、还是均值滤波,其他滤波方式以后添加 :return: 返回该像素值 ''' if filter_type == 'medium_Filter': temp = img * kernel list = [] for i in range(temp.shape[0]): for j in range(temp.shape[1]): list.append(temp[i][j]) list.sort() if list[int(len(list) / 2)] > 255: return 255 elif list[int(len(list) / 2)] < 0: return 0 else: return list[int(len(list) / 2)] # 均值、高斯滤波等 else: result = (img * kernel).sum() if result < 0: return 0 elif result > 255: return 255 else: return result def convolve(img, kernel, filter_type, mode='same'): ''' 三通道卷积,主要用于彩色图 :param img: 输入图像矩阵 :param kernel: 卷积核 :param mode: medium,gauss,mean, 即选择中值滤波、高斯滤波、还是均值滤波,其他滤波方式以后添加 :return: 卷积后的图像矩阵 ''' R = np.mat(img[:, :, 0]) G = np.mat(img[:, :, 1]) B = np.mat(img[:, :, 2]) conv_B = convolve1(img[:, :, 0], kernel, filter_type, mode) conv_G = convolve1(img[:, :, 1], kernel, filter_type, mode) conv_R = convolve1(img[:, :, 2], kernel, filter_type, mode) conv_img = np.dstack([conv_B, conv_G, conv_R]) return conv_img ''' ############################################ 噪声函数 脉冲噪声:add_PulseNoise(img, SNR) 椒盐噪声:add_Salt_PepperNoise(img, SNR) 高斯噪声:add_Gauss_Noise(img, mean, sigma) ############################################# ''' # 添加脉冲噪声 def add_PulseNoise(img, SNR): ''' 给图像添加脉冲噪声 :param img: 输入图像 :param SNR: 信噪比,决定添加多少噪声 :return: 添加噪声后的图像 ''' rows, cols, dims = img.shape # 创建与图像大小一样的矩阵 R = np.mat(img[:, :, 0]) G = np.mat(img[:, :, 1]) B = np.mat(img[:, :, 2]) # RGB图转换为灰度图的著名公式: Grap = R*0.299+G*0.587+B*0.114 Grey = R * 0.299 + G * 0.587 + B * 0.114 # 噪声点数目 noise = int((1 - SNR) * rows * cols) # 添加噪声 for i in range(noise): # 随机选择图片矩阵的一个格子,设置为脉冲噪声值 rand_rows = random.randint(0, rows - 1) rand_cols = random.randint(0, cols - 1) Grey[rand_rows, rand_cols] = 255 # img[rand_rows, rand_cols] = 255 return Grey # 添加椒盐噪声 def add_Salt_PepperNoise(img, SNR): ''' 给图像添加椒盐噪声 :param img: 输入图像 :param SNR: 输入信噪比,决定添加多少噪声 :return: 输出添加噪声后的图像 ''' rows, cols, dims = img.shape # 创建与图像大小一样的矩阵 R = np.mat(img[:, :, 0]) G = np.mat(img[:, :, 1]) B = np.mat(img[:, :, 2]) # RGB图转换为灰度图的著名公式: Grap = R*0.299+G*0.587+B*0.114 Grey = R * 0.299 + G * 0.587 + B * 0.114 # 噪声点数目 noise = int((1 - SNR) * rows * cols) # 添加噪声 for i in range(noise): # 随机选择图片矩阵的一个格子,设置为椒盐噪声值 rand_rows = random.randint(0, rows - 1) rand_cols = random.randint(0, cols - 1) if random.randint(0, 1) == 0: Grey[rand_rows, rand_cols] = 0 # 盐噪声为255 else: Grey[rand_rows, rand_cols] = 255 # 椒噪声为0 return Grey def add_Gauss_Noise(img, mean, sigma): ''' 添加高斯噪声 :param img:输入图像 :param mean: 高斯分布的均值 :param sigma: 高斯分布的标准差 :return: 添加高斯噪声后的图像 ''' rows, cols, dims = img.shape R = np.mat(img[:, :, 0]) G = np.mat(img[:, :, 1]) B = np.mat(img[:, :, 2]) # 产生灰度图 Grey = R * 0.299 + G * 0.587 + B * 0.114 # numpy.random.normal(mean,sigma,shape)是正态分布函数,mean是均值,sigma是标准差,shape表示输出值放在size里 noise = np.random.normal(mean, sigma, Grey.shape) # 将噪声和图片叠加 Grey = noise + Grey # np.min(Grey):取Grey中的最小值;np.full(arry,num):给arry全部赋值num Grey = Grey - np.full(Grey.shape, np.min(Grey)) Grey = Grey * 255 / np.max(Grey) Grey_p = Grey.astype(np.uint8) # 类型转换 return Grey ''' ################## 均值滤波器:mean_Fileter(img, size) 中值滤波器: medium_Fileter(img, size) 高斯滤波器:gauss_Kernel(mean, sigma, kernel_size) ''' def mean_Fileter(img, kernel_size): ''' 均值滤波器 :param img: 输入图像 :param kernel_size:卷积核大小 :return: 均值滤波后的图像 ''' # kernel_size * kernel_size 滤波器, 每个系数都是 1/9 kernel = np.ones((kernel_size, kernel_size)) / (kernel_size ** 2) # mode = same 表示输出尺寸等于输入尺寸 # boundary 表示采用对称边界条件处理图像边缘 # img_out = scipy.signal.convolve2d(img, kernel, mode='same', boundary='symm') img_out = convolve1(img, kernel, filter_type='mean_Fileter', mode='same') return img_out.astype(np.uint8) def medium_Filter(img, kernel_size): ''' 中值滤波器 :param img: 输入图像 :param size: 卷积核大小 :return: 中值滤波后的图像 ''' kernel = np.ones((kernel_size, kernel_size)) # mode = same 表示输出尺寸等于输入尺寸 # boundary 表示采用对称边界条件处理图像边缘 img_out = convolve1(img, kernel, filter_type='medium_Filter', mode="same") # img_out = scipy.signal.convolve2d(img, kernel, mode='same', boundary='symm') return img_out.astype(np.uint8) def Gauss_Fileter(img, kernel_size, sigma): ''' 高斯滤波器 :param img: 输入图像 :param kernel_size: 卷积核大小 :param sigma: 高斯函数的标准差 :return: 高斯滤波后的图片 ''' #避免除0 if sigma == 0: sigma = 6 kernel = np.zeros([kernel_size, kernel_size]) kernel_center = (int)(kernel_size / 2) # 卷积核中心位置 sum_val = 0 # 记录卷积核中数字之和 for i in range(0, kernel_size): for j in range(0, kernel_size): kernel[i, j] = np.exp(-((i - kernel_center) ** 2 + (j - kernel_center) ** 2) / (2 * (sigma ** 2))) sum_val += kernel[i, j] # 得到卷积核 kernel = kernel / sum_val img_out = convolve1(img, kernel, filter_type='Gauss_Fileter', mode='same') # img_out = scipy.signal.convolve2d(img, kernel, mode='same', boundary='symm') # 返回图片 return img_out def main(): img = np.array(Image.open('LenaRGB.bmp')) # 加上各种噪声 img1 = add_PulseNoise(img, 0.9) img2 = add_Salt_PepperNoise(img, 0.9) img3 = add_Gauss_Noise(img, 0, 8) plt.subplot(321) plt.title('PulseNoise') plt.imshow(img1, cmap='gray') plt.subplot(322) plt.title('Salt_PepperNoise') plt.imshow(img2, cmap='gray') plt.subplot(323) plt.title('GaussNoise') plt.imshow(img3, cmap='gray') ''' #三种滤波器对脉冲噪声的效果 img1_1 = mean_Fileter(img1, 3) img1_2 = medium_Filter(img1, 3) img1_3 = Gauss_Fileter(img1, 3, 8) plt.subplot(324) plt.title('PauseNoise_meanfilter') plt.imshow(img1_1, cmap='gray') plt.subplot(325) plt.title('PauseNoise_mediumfilter') plt.imshow(img1_2, cmap='gray') plt.subplot(326) plt.title('PauseNoise_Gaussfilter') plt.imshow(img1_3, cmap='gray') plt.show() #三种滤波器对椒盐噪声的效果 img2_1 = mean_Fileter(img2, 3) img2_2 = medium_Filter(img2, 3) img2_3 = Gauss_Fileter(img2, 3, 8) plt.subplot(327) plt.title('Salt_Pepper_Noise_meanfilter') plt.imshow(img2_1, cmap='gray') plt.subplot(328) plt.title('Salt_Pepper_Noise_mediumfilter') plt.imshow(img2_2, cmap='gray') plt.subplot(329) plt.title('Salt_PepperNoise_Gaussfilter') plt.imshow(img2_3, cmap='gray') #三种滤波器对高斯噪声的效果 img3_1 = mean_Fileter(img3, 3) img3_2 = medium_Filter(img3, 3) img3_3 = Gauss_Fileter(img3, 3, 8) plt.subplot(330) plt.title('GaussNoise_meanfilter') plt.imshow(img3_1, cmap='gray') plt.subplot(331) plt.title('GaussNoise_mediumfilter') plt.imshow(img3_2, cmap='gray') plt.subplot(332) plt.title('GaussNoise_Gaussfilter') plt.imshow(img3_3, cmap='gray') plt.show() ''' # 不同尺寸的box filter对噪声图片的效果 createVar = locals() num = [3, 5, 7] j = 324 for i in num: createVar['kernel_' + str(i)]=97 print('kernel_' + str(i)) kerral_num = [] for i in num: kerral_num.append(Gauss_Fileter(img1, i, 6)) plt.subplot(j) plt.title('GaussNoise_meanfilter_kernel_' + str(i)) plt.imshow(kerral_num.pop(), cmap='gray') j = j + 1 plt.show() ''' img = np.array(Image.open('LenaRGB.bmp')) img1 = add_Gauss_Noise(img, 0, 6.5) plt.subplot(321) plt.title('Gauss') plt.imshow(img1, cmap='gray') plt.subplot(322) plt.title('Grey gauss noise') plt.imshow(img2, cmap='gray') # plt.show() img3 = add_Salt_PepperNoise(img, 0.99) plt.subplot(323) plt.title('Salt_Pepper') plt.imshow(img3, cmap='gray') # 中值滤波 img1_mf = scipy.ndimage.median_filter(img1, (8, 8)) img3_mf = scipy.ndimage.median_filter(img3, (8, 8)) #高斯滤波 img1_gf = cv2.GaussianBlur(img1, (3, 3), 0) # 均值滤波 plt.subplot(324) plt.title('Salt_pepper_no') plt.imshow(img3_mf, cmap='gray') plt.subplot(325) plt.title('Gauss_no') plt.imshow(img1_mf, cmap='gray') plt.show() ''' if __name__ == '__main__': main()
[ "numpy.random.normal", "numpy.mat", "numpy.dstack", "matplotlib.pyplot.imshow", "PIL.Image.open", "numpy.ones", "cv2.copyMakeBorder", "numpy.max", "numpy.exp", "numpy.zeros", "numpy.min", "matplotlib.pyplot.title", "matplotlib.pyplot.subplot", "random.randint", "matplotlib.pyplot.show" ]
[((540, 634), 'cv2.copyMakeBorder', 'cv2.copyMakeBorder', (['img', 'addLine', 'addLine', 'addLine', 'addLine', 'cv2.BORDER_CONSTANT'], {'value': '(0)'}), '(img, addLine, addLine, addLine, addLine, cv2.\n BORDER_CONSTANT, value=0)\n', (558, 634), False, 'import cv2\n'), ((1166, 1216), 'numpy.zeros', 'np.zeros', (['(conv_height, conv_width)'], {'dtype': '"""uint8"""'}), "((conv_height, conv_width), dtype='uint8')\n", (1174, 1216), True, 'import numpy as np\n'), ((2478, 2498), 'numpy.mat', 'np.mat', (['img[:, :, 0]'], {}), '(img[:, :, 0])\n', (2484, 2498), True, 'import numpy as np\n'), ((2507, 2527), 'numpy.mat', 'np.mat', (['img[:, :, 1]'], {}), '(img[:, :, 1])\n', (2513, 2527), True, 'import numpy as np\n'), ((2536, 2556), 'numpy.mat', 'np.mat', (['img[:, :, 2]'], {}), '(img[:, :, 2])\n', (2542, 2556), True, 'import numpy as np\n'), ((2765, 2800), 'numpy.dstack', 'np.dstack', (['[conv_B, conv_G, conv_R]'], {}), '([conv_B, conv_G, conv_R])\n', (2774, 2800), True, 'import numpy as np\n'), ((3269, 3289), 'numpy.mat', 'np.mat', (['img[:, :, 0]'], {}), '(img[:, :, 0])\n', (3275, 3289), True, 'import numpy as np\n'), ((3298, 3318), 'numpy.mat', 'np.mat', (['img[:, :, 1]'], {}), '(img[:, :, 1])\n', (3304, 3318), True, 'import numpy as np\n'), ((3327, 3347), 'numpy.mat', 'np.mat', (['img[:, :, 2]'], {}), '(img[:, :, 2])\n', (3333, 3347), True, 'import numpy as np\n'), ((3980, 4000), 'numpy.mat', 'np.mat', (['img[:, :, 0]'], {}), '(img[:, :, 0])\n', (3986, 4000), True, 'import numpy as np\n'), ((4009, 4029), 'numpy.mat', 'np.mat', (['img[:, :, 1]'], {}), '(img[:, :, 1])\n', (4015, 4029), True, 'import numpy as np\n'), ((4038, 4058), 'numpy.mat', 'np.mat', (['img[:, :, 2]'], {}), '(img[:, :, 2])\n', (4044, 4058), True, 'import numpy as np\n'), ((4760, 4780), 'numpy.mat', 'np.mat', (['img[:, :, 0]'], {}), '(img[:, :, 0])\n', (4766, 4780), True, 'import numpy as np\n'), ((4789, 4809), 'numpy.mat', 'np.mat', (['img[:, :, 1]'], {}), '(img[:, :, 1])\n', (4795, 4809), True, 'import numpy as np\n'), ((4818, 4838), 'numpy.mat', 'np.mat', (['img[:, :, 2]'], {}), '(img[:, :, 2])\n', (4824, 4838), True, 'import numpy as np\n'), ((4995, 5036), 'numpy.random.normal', 'np.random.normal', (['mean', 'sigma', 'Grey.shape'], {}), '(mean, sigma, Grey.shape)\n', (5011, 5036), True, 'import numpy as np\n'), ((6097, 6132), 'numpy.ones', 'np.ones', (['(kernel_size, kernel_size)'], {}), '((kernel_size, kernel_size))\n', (6104, 6132), True, 'import numpy as np\n'), ((6626, 6662), 'numpy.zeros', 'np.zeros', (['[kernel_size, kernel_size]'], {}), '([kernel_size, kernel_size])\n', (6634, 6662), True, 'import numpy as np\n'), ((7399, 7415), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(321)'], {}), '(321)\n', (7410, 7415), True, 'import matplotlib.pyplot as plt\n'), ((7420, 7443), 'matplotlib.pyplot.title', 'plt.title', (['"""PulseNoise"""'], {}), "('PulseNoise')\n", (7429, 7443), True, 'import matplotlib.pyplot as plt\n'), ((7448, 7477), 'matplotlib.pyplot.imshow', 'plt.imshow', (['img1'], {'cmap': '"""gray"""'}), "(img1, cmap='gray')\n", (7458, 7477), True, 'import matplotlib.pyplot as plt\n'), ((7482, 7498), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(322)'], {}), '(322)\n', (7493, 7498), True, 'import matplotlib.pyplot as plt\n'), ((7503, 7532), 'matplotlib.pyplot.title', 'plt.title', (['"""Salt_PepperNoise"""'], {}), "('Salt_PepperNoise')\n", (7512, 7532), True, 'import matplotlib.pyplot as plt\n'), ((7537, 7566), 'matplotlib.pyplot.imshow', 'plt.imshow', (['img2'], {'cmap': '"""gray"""'}), "(img2, cmap='gray')\n", (7547, 7566), True, 'import matplotlib.pyplot as plt\n'), ((7571, 7587), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(323)'], {}), '(323)\n', (7582, 7587), True, 'import matplotlib.pyplot as plt\n'), ((7592, 7615), 'matplotlib.pyplot.title', 'plt.title', (['"""GaussNoise"""'], {}), "('GaussNoise')\n", (7601, 7615), True, 'import matplotlib.pyplot as plt\n'), ((7620, 7649), 'matplotlib.pyplot.imshow', 'plt.imshow', (['img3'], {'cmap': '"""gray"""'}), "(img3, cmap='gray')\n", (7630, 7649), True, 'import matplotlib.pyplot as plt\n'), ((9413, 9423), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (9421, 9423), True, 'import matplotlib.pyplot as plt\n'), ((3592, 3619), 'random.randint', 'random.randint', (['(0)', '(rows - 1)'], {}), '(0, rows - 1)\n', (3606, 3619), False, 'import random\n'), ((3640, 3667), 'random.randint', 'random.randint', (['(0)', '(cols - 1)'], {}), '(0, cols - 1)\n', (3654, 3667), False, 'import random\n'), ((4303, 4330), 'random.randint', 'random.randint', (['(0)', '(rows - 1)'], {}), '(0, rows - 1)\n', (4317, 4330), False, 'import random\n'), ((4351, 4378), 'random.randint', 'random.randint', (['(0)', '(cols - 1)'], {}), '(0, cols - 1)\n', (4365, 4378), False, 'import random\n'), ((5214, 5226), 'numpy.max', 'np.max', (['Grey'], {}), '(Grey)\n', (5220, 5226), True, 'import numpy as np\n'), ((5636, 5671), 'numpy.ones', 'np.ones', (['(kernel_size, kernel_size)'], {}), '((kernel_size, kernel_size))\n', (5643, 5671), True, 'import numpy as np\n'), ((7237, 7262), 'PIL.Image.open', 'Image.open', (['"""LenaRGB.bmp"""'], {}), "('LenaRGB.bmp')\n", (7247, 7262), False, 'from PIL import Image\n'), ((9265, 9279), 'matplotlib.pyplot.subplot', 'plt.subplot', (['j'], {}), '(j)\n', (9276, 9279), True, 'import matplotlib.pyplot as plt\n'), ((4390, 4410), 'random.randint', 'random.randint', (['(0)', '(1)'], {}), '(0, 1)\n', (4404, 4410), False, 'import random\n'), ((5176, 5188), 'numpy.min', 'np.min', (['Grey'], {}), '(Grey)\n', (5182, 5188), True, 'import numpy as np\n'), ((6850, 6935), 'numpy.exp', 'np.exp', (['(-((i - kernel_center) ** 2 + (j - kernel_center) ** 2) / (2 * sigma ** 2))'], {}), '(-((i - kernel_center) ** 2 + (j - kernel_center) ** 2) / (2 * sigma **\n 2))\n', (6856, 6935), True, 'import numpy as np\n')]
import sys import numpy as np import matplotlib.pyplot as plt import random import sys sys.path.append("/home/z840/caffe-tmp/caffe/python") import caffe from datasets.cityscapes import cityscapes from lib import run_net from lib import score_util from lib import plot_util class DataCityscapes(object): def __init__(self): # paint plt.rcParams['image.cmap'] = 'gray' plt.rcParams['image.interpolation'] = 'nearest' plt.rcParams['figure.figsize'] = (12, 12) # config caffe.set_device(0) caffe.set_mode_gpu() # data self.cityscapes = cityscapes('C:/ALISURE/Data/cityscapes') self.class_count = len(self.cityscapes.classes) self.valset = self.cityscapes.get_dset('val') # net self.net = self.get_net() pass @staticmethod def get_net(): return caffe.Net('../model/cityscapes-fcn8s.prototxt', '../model/cityscapes-fcn8s-heavy.caffemodel', caffe.TEST) def run_sigle_item(self, item): im, gt = self.cityscapes.load_image('val', *item), self.cityscapes.load_label('val', *item) out = run_net.segrun(self.net, self.cityscapes.preprocess(im)) return im, gt, out def test_one(self): # 选择一个数据测试 item = random.choice(self.valset) im, gt, out = self.run_sigle_item(item) plot_util.segshow(im, self.cityscapes.palette(gt), self.cityscapes.palette(out)) def test_all(self): # 测试所有数据 hist = np.zeros((self.class_count, self.class_count)) for i, item in enumerate(self.valset): if i % 100 == 0: print('running {}/{}'.format(i, len(self.valset))) sys.stdout.flush() im, gt, out = self.run_sigle_item(item) hist += score_util.score_out_gt(out, gt, n_cl=self.class_count) acc, cl_acc, iu, fw_iu = score_util.get_scores(hist) print('val results: acc {:.3f} class acc {:.3f} iu {:.3f} fw iu {:.3f}'.format(acc, cl_acc, iu, fw_iu)) def run(self): self.test_one() self.test_all() pass pass if __name__ == '__main__': data_city_scapes = DataCityscapes() data_city_scapes.run() pass
[ "random.choice", "lib.score_util.get_scores", "lib.score_util.score_out_gt", "caffe.set_mode_gpu", "caffe.set_device", "numpy.zeros", "datasets.cityscapes.cityscapes", "caffe.Net", "sys.stdout.flush", "sys.path.append" ]
[((88, 140), 'sys.path.append', 'sys.path.append', (['"""/home/z840/caffe-tmp/caffe/python"""'], {}), "('/home/z840/caffe-tmp/caffe/python')\n", (103, 140), False, 'import sys\n'), ((526, 545), 'caffe.set_device', 'caffe.set_device', (['(0)'], {}), '(0)\n', (542, 545), False, 'import caffe\n'), ((554, 574), 'caffe.set_mode_gpu', 'caffe.set_mode_gpu', ([], {}), '()\n', (572, 574), False, 'import caffe\n'), ((617, 657), 'datasets.cityscapes.cityscapes', 'cityscapes', (['"""C:/ALISURE/Data/cityscapes"""'], {}), "('C:/ALISURE/Data/cityscapes')\n", (627, 657), False, 'from datasets.cityscapes import cityscapes\n'), ((883, 992), 'caffe.Net', 'caffe.Net', (['"""../model/cityscapes-fcn8s.prototxt"""', '"""../model/cityscapes-fcn8s-heavy.caffemodel"""', 'caffe.TEST'], {}), "('../model/cityscapes-fcn8s.prototxt',\n '../model/cityscapes-fcn8s-heavy.caffemodel', caffe.TEST)\n", (892, 992), False, 'import caffe\n'), ((1283, 1309), 'random.choice', 'random.choice', (['self.valset'], {}), '(self.valset)\n', (1296, 1309), False, 'import random\n'), ((1504, 1550), 'numpy.zeros', 'np.zeros', (['(self.class_count, self.class_count)'], {}), '((self.class_count, self.class_count))\n', (1512, 1550), True, 'import numpy as np\n'), ((1891, 1918), 'lib.score_util.get_scores', 'score_util.get_scores', (['hist'], {}), '(hist)\n', (1912, 1918), False, 'from lib import score_util\n'), ((1801, 1856), 'lib.score_util.score_out_gt', 'score_util.score_out_gt', (['out', 'gt'], {'n_cl': 'self.class_count'}), '(out, gt, n_cl=self.class_count)\n', (1824, 1856), False, 'from lib import score_util\n'), ((1710, 1728), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (1726, 1728), False, 'import sys\n')]
# coding: utf8 from .jogadores import Jogador import numpy as np class MeuJogador(Jogador): def escolha_de_cacada(self, rodada, comida_atual, reputacao_atual, m, reputacoes_dos_jogadores): if len(reputacoes_dos_jogadores) > 5: escolhas = [np.random.choice(['c', 'd', 'c', 'c', 'd', 'c']) for x in reputacoes_dos_jogadores] else: escolhas = ['d' for x in reputacoes_dos_jogadores] return escolhas
[ "numpy.random.choice" ]
[((265, 313), 'numpy.random.choice', 'np.random.choice', (["['c', 'd', 'c', 'c', 'd', 'c']"], {}), "(['c', 'd', 'c', 'c', 'd', 'c'])\n", (281, 313), True, 'import numpy as np\n')]
import numpy as np # from svmlight_loader import load_svmlight_file, dump_svmlight_file from sklearn.datasets import load_svmlight_file, dump_svmlight_file import networkx as nx import scipy import pickle import os import os.path from scipy.sparse import csr_matrix def mkdir_if_not_exists(dir_path): try: if not os.path.exists(dir_path): os.makedirs(dir_path) except: pass def safe_operation(old_func): '''Decorator to make dicey operations repeat 3 times if they fail''' def new_func(*args,**kwargs): max_attempts = 3 for i in range(max_attempts): try: result = old_func(*args, **kwargs) return result except Exception as e: print("Failed once", old_func) caught_excption = e continue else: print(args, kwargs) raise IOError("function failed "+ str(old_func), caught_excption) return new_func def read_svmlight_file_multilabel(file_path, n_features=None): '''Reads multi-label svmlight file''' with open(file_path) as fin: line_index = 0 data_indices = list() data = list() labels = [] for line in fin: lbl_feat_str, sep, comment = line.strip().partition("#") tokens1 = lbl_feat_str.split(',') tokens2 = tokens1[-1].split() line_labels = [int(i) for i in tokens1[:-1] + tokens2[:1]] labels.append(line_labels) features = tokens2[1:] for f in features: fid, fval = f.split(':') data_indices.append([line_index, int(fid)-1]) data.append(float(fval)) line_index += 1 if n_features == None: X = csr_matrix((np.array(data), np.array(data_indices).T)) else: X = csr_matrix((np.array(data), np.array(data_indices).T), shape = (line_index, n_features)) return X, labels def dump_svmlight_file_multilabel(X, y, file_path): y_temp = np.zeros(len(y)) dump_svmlight_file(X, y_temp, file_path, zero_based=False) data = [] with open(file_path) as fin: counter = 0 for line in fin: lbl_str = ",".join([str(lbl) for lbl in y[counter]]) if line[0] == '0': out_line = lbl_str + line[1:] data.append(out_line) else: raise Exception("unexpected label") counter += 1 with open(file_path,'w') as fout: fout.write("".join(data)) @safe_operation def safe_read_graph(graph_path): '''Load a networkx.DiGraph from a file in edgelist format''' return nx.read_edgelist(graph_path, create_using=nx.DiGraph(),nodetype=int) @safe_operation def safe_read_svmlight_file_multilabel(data_path, num_features=None): return read_svmlight_file_multilabel(data_path, num_features) @safe_operation def safe_read_svmlight_file(data_path, num_features=None): '''Reads dataset from file in libsvm sparse format, single label''' # X, y = load_svmlight_file(data_path, num_features, buffer_mb=300) X, y = load_svmlight_file(data_path, num_features) return X, y @safe_operation def safe_pickle_load(pickle_path): '''Reads a pickled object from file''' with open( pickle_path, "rb" ) as fin: model = pickle.load(fin) return model @safe_operation def safe_pickle_dump(pickle_object, output_path): '''Writes a pickled object to file''' with open( output_path, "wb" ) as fout: pickle.dump(pickle_object, fout, protocol=2) def get_root_node(graph): root_cand = [n for n in graph.nodes() if not graph.predecessors(n)] if len(root_cand) > 1: raise Exception("Too many roots") else: return root_cand[0]
[ "os.path.exists", "pickle.dump", "os.makedirs", "sklearn.datasets.load_svmlight_file", "networkx.DiGraph", "pickle.load", "numpy.array", "sklearn.datasets.dump_svmlight_file" ]
[((2080, 2138), 'sklearn.datasets.dump_svmlight_file', 'dump_svmlight_file', (['X', 'y_temp', 'file_path'], {'zero_based': '(False)'}), '(X, y_temp, file_path, zero_based=False)\n', (2098, 2138), False, 'from sklearn.datasets import load_svmlight_file, dump_svmlight_file\n'), ((3162, 3205), 'sklearn.datasets.load_svmlight_file', 'load_svmlight_file', (['data_path', 'num_features'], {}), '(data_path, num_features)\n', (3180, 3205), False, 'from sklearn.datasets import load_svmlight_file, dump_svmlight_file\n'), ((3377, 3393), 'pickle.load', 'pickle.load', (['fin'], {}), '(fin)\n', (3388, 3393), False, 'import pickle\n'), ((3572, 3616), 'pickle.dump', 'pickle.dump', (['pickle_object', 'fout'], {'protocol': '(2)'}), '(pickle_object, fout, protocol=2)\n', (3583, 3616), False, 'import pickle\n'), ((327, 351), 'os.path.exists', 'os.path.exists', (['dir_path'], {}), '(dir_path)\n', (341, 351), False, 'import os\n'), ((365, 386), 'os.makedirs', 'os.makedirs', (['dir_path'], {}), '(dir_path)\n', (376, 386), False, 'import os\n'), ((2750, 2762), 'networkx.DiGraph', 'nx.DiGraph', ([], {}), '()\n', (2760, 2762), True, 'import networkx as nx\n'), ((1817, 1831), 'numpy.array', 'np.array', (['data'], {}), '(data)\n', (1825, 1831), True, 'import numpy as np\n'), ((1894, 1908), 'numpy.array', 'np.array', (['data'], {}), '(data)\n', (1902, 1908), True, 'import numpy as np\n'), ((1833, 1855), 'numpy.array', 'np.array', (['data_indices'], {}), '(data_indices)\n', (1841, 1855), True, 'import numpy as np\n'), ((1910, 1932), 'numpy.array', 'np.array', (['data_indices'], {}), '(data_indices)\n', (1918, 1932), True, 'import numpy as np\n')]
from PIL import ImageFont, Image, ImageDraw import numpy as np import cv2 # bg_path = '/home/cwq/code/ocr_end2end/text_gen/bg/000000088218.jpg' from gists.outline import draw_border_text bg_path = '/home/cwq/code/text_renderer/data/bg/paper1.png' font_path = '/home/cwq/code/ocr_end2end/text_gen/fonts/chn/msyh.ttc' COLOR = 200 SEAMLESS_OFFSET = 9 BORDER_COLOR = COLOR + 20 BORDER_THICKNESS = 0.5 FONT_SIZE = 45 word = '测试图像的无缝融合' font = ImageFont.truetype(font_path, FONT_SIZE) offset = font.getoffset(word) size = font.getsize(word) print(offset) word_height = size[1] - offset[1] word_width = size[0] # bg = np.ones((size[1] - offset[1], size[0] - offset[0]), np.uint8) * 255 bg = cv2.imread(bg_path) bg_gray = cv2.cvtColor(bg, cv2.COLOR_BGR2GRAY) bg_height = bg.shape[0] bg_width = bg.shape[1] white_bg = np.ones((word_height + SEAMLESS_OFFSET, word_width + SEAMLESS_OFFSET)) * 255 text_img = Image.fromarray(np.uint8(white_bg)) draw = ImageDraw.Draw(text_img) draw_border_text(draw=draw, text=word, x=0 + SEAMLESS_OFFSET // 2, y=0 - offset[1] + SEAMLESS_OFFSET // 2, font=font, thickness=BORDER_THICKNESS, border_color=BORDER_COLOR, text_color=COLOR) # draw.text((0 + SEAMLESS_OFFSET // 2, 0 - offset[1] + SEAMLESS_OFFSET // 2), word, fill=COLOR, font=font) bg_gray = Image.fromarray(np.uint8(bg_gray)) graw_draw = ImageDraw.Draw(bg_gray) # graw_draw.text((text_x, text_y), word, fill=COLOR, font=font) draw_border_text(draw=graw_draw, text=word, x=(bg_width - word_width) // 2, y=(bg_height - word_height) // 2, font=font, thickness=BORDER_THICKNESS, border_color=BORDER_COLOR, text_color=COLOR) bg_gray.save('direct.jpg') text_img.save('text.jpg') text_img = np.array(text_img).astype(np.uint8) text_mask = 255 * np.ones(text_img.shape, text_img.dtype) # This is where the CENTER of the airplane will be placed center = (bg_width // 2, bg_height // 2) text_img_bgr = np.ones((text_img.shape[0], text_img.shape[1], 3), np.uint8) cv2.cvtColor(text_img, cv2.COLOR_GRAY2BGR, text_img_bgr) print(text_img_bgr.shape) print(bg.shape) print(text_mask.shape) mixed_clone = cv2.seamlessClone(text_img_bgr, bg, text_mask, center, cv2.MONOCHROME_TRANSFER) result = cv2.cvtColor(mixed_clone, cv2.COLOR_BGR2GRAY) cv2.imwrite('seamless.jpg', result)
[ "numpy.uint8", "cv2.imwrite", "numpy.ones", "cv2.seamlessClone", "PIL.ImageFont.truetype", "numpy.array", "PIL.ImageDraw.Draw", "cv2.cvtColor", "cv2.imread", "gists.outline.draw_border_text" ]
[((442, 482), 'PIL.ImageFont.truetype', 'ImageFont.truetype', (['font_path', 'FONT_SIZE'], {}), '(font_path, FONT_SIZE)\n', (460, 482), False, 'from PIL import ImageFont, Image, ImageDraw\n'), ((690, 709), 'cv2.imread', 'cv2.imread', (['bg_path'], {}), '(bg_path)\n', (700, 709), False, 'import cv2\n'), ((720, 756), 'cv2.cvtColor', 'cv2.cvtColor', (['bg', 'cv2.COLOR_BGR2GRAY'], {}), '(bg, cv2.COLOR_BGR2GRAY)\n', (732, 756), False, 'import cv2\n'), ((947, 971), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['text_img'], {}), '(text_img)\n', (961, 971), False, 'from PIL import ImageFont, Image, ImageDraw\n'), ((973, 1171), 'gists.outline.draw_border_text', 'draw_border_text', ([], {'draw': 'draw', 'text': 'word', 'x': '(0 + SEAMLESS_OFFSET // 2)', 'y': '(0 - offset[1] + SEAMLESS_OFFSET // 2)', 'font': 'font', 'thickness': 'BORDER_THICKNESS', 'border_color': 'BORDER_COLOR', 'text_color': 'COLOR'}), '(draw=draw, text=word, x=0 + SEAMLESS_OFFSET // 2, y=0 -\n offset[1] + SEAMLESS_OFFSET // 2, font=font, thickness=BORDER_THICKNESS,\n border_color=BORDER_COLOR, text_color=COLOR)\n', (989, 1171), False, 'from gists.outline import draw_border_text\n'), ((1397, 1420), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['bg_gray'], {}), '(bg_gray)\n', (1411, 1420), False, 'from PIL import ImageFont, Image, ImageDraw\n'), ((1486, 1687), 'gists.outline.draw_border_text', 'draw_border_text', ([], {'draw': 'graw_draw', 'text': 'word', 'x': '((bg_width - word_width) // 2)', 'y': '((bg_height - word_height) // 2)', 'font': 'font', 'thickness': 'BORDER_THICKNESS', 'border_color': 'BORDER_COLOR', 'text_color': 'COLOR'}), '(draw=graw_draw, text=word, x=(bg_width - word_width) // 2,\n y=(bg_height - word_height) // 2, font=font, thickness=BORDER_THICKNESS,\n border_color=BORDER_COLOR, text_color=COLOR)\n', (1502, 1687), False, 'from gists.outline import draw_border_text\n'), ((2025, 2085), 'numpy.ones', 'np.ones', (['(text_img.shape[0], text_img.shape[1], 3)', 'np.uint8'], {}), '((text_img.shape[0], text_img.shape[1], 3), np.uint8)\n', (2032, 2085), True, 'import numpy as np\n'), ((2086, 2142), 'cv2.cvtColor', 'cv2.cvtColor', (['text_img', 'cv2.COLOR_GRAY2BGR', 'text_img_bgr'], {}), '(text_img, cv2.COLOR_GRAY2BGR, text_img_bgr)\n', (2098, 2142), False, 'import cv2\n'), ((2223, 2302), 'cv2.seamlessClone', 'cv2.seamlessClone', (['text_img_bgr', 'bg', 'text_mask', 'center', 'cv2.MONOCHROME_TRANSFER'], {}), '(text_img_bgr, bg, text_mask, center, cv2.MONOCHROME_TRANSFER)\n', (2240, 2302), False, 'import cv2\n'), ((2313, 2358), 'cv2.cvtColor', 'cv2.cvtColor', (['mixed_clone', 'cv2.COLOR_BGR2GRAY'], {}), '(mixed_clone, cv2.COLOR_BGR2GRAY)\n', (2325, 2358), False, 'import cv2\n'), ((2359, 2394), 'cv2.imwrite', 'cv2.imwrite', (['"""seamless.jpg"""', 'result'], {}), "('seamless.jpg', result)\n", (2370, 2394), False, 'import cv2\n'), ((816, 886), 'numpy.ones', 'np.ones', (['(word_height + SEAMLESS_OFFSET, word_width + SEAMLESS_OFFSET)'], {}), '((word_height + SEAMLESS_OFFSET, word_width + SEAMLESS_OFFSET))\n', (823, 886), True, 'import numpy as np\n'), ((920, 938), 'numpy.uint8', 'np.uint8', (['white_bg'], {}), '(white_bg)\n', (928, 938), True, 'import numpy as np\n'), ((1366, 1383), 'numpy.uint8', 'np.uint8', (['bg_gray'], {}), '(bg_gray)\n', (1374, 1383), True, 'import numpy as np\n'), ((1869, 1908), 'numpy.ones', 'np.ones', (['text_img.shape', 'text_img.dtype'], {}), '(text_img.shape, text_img.dtype)\n', (1876, 1908), True, 'import numpy as np\n'), ((1814, 1832), 'numpy.array', 'np.array', (['text_img'], {}), '(text_img)\n', (1822, 1832), True, 'import numpy as np\n')]
import numpy as np import astropy.constants as const import astropy.units as u from astropy.cosmology import FlatLambdaCDM import warnings def lensing_efficiency(zl,zs,cosmo): ''' computes the lensing ratio for a defined LambdaCDM cosmology ''' if zs == float('inf') or zs == 'inf': return 1.0 dls = cosmo.angular_diameter_distance_z1z2(zl,zs).value ds = cosmo.angular_diameter_distance(zs).value return dls/ds def dlsds(zl,zs,cosmo=FlatLambdaCDM(H0=70,Om0=0.3)): ''' computes the lensing ratio for a defined cosmology ''' if zs == float('inf') or zs == 'inf' or zs == np.inf: return 1.0 dls = cosmo.angular_diameter_distance_z1z2(zl,zs).value ds = cosmo.angular_diameter_distance(zs).value return dls/ds def critical_density(zl,zs,cosmo=FlatLambdaCDM(H0=70,Om0=0.3)): ''' computes critical surface mass density for a defined LambdaCDM cosmology ''' ratio = dlsds(zl,zs,cosmo=cosmo) dl = cosmo.angular_diameter_distance(zl) cd = (const.c**2)/(4*np.pi*const.G*ratio*dl) return cd.to('M_sun/kpc2').value def jacobian_kg(kappa,gamma,ratio=1): ''' computes the determanant of the Jacobian matrix from kappa and gamma matrices ''' A = (1-kappa*ratio)**2-(gamma*ratio)**2 return A def jacobian_dxdy(deflectx,deflecty,ratio=1,dunit=1): ''' computes the determanant of the Jacobian matrix from deflection matrices ''' with warnings.catch_warnings(): warnings.simplefilter('ignore') dDXdy,dDXdx = np.gradient(deflectx*ratio/dunit) dDYdy,dDYdx = np.gradient(deflecty*ratio/dunit) A = (1-dDXdx)*(1-dDYdy)-dDXdy*dDYdx return A def radial_eigenvalue_kg(kappa,gamma,ratio=1): ''' computes the radial eigenvalue of the Jacobian matrix from kappa and gamma ''' return (1-kappa*ratio+gamma*ratio) def tangential_eigenvalue_kg(kappa,gamma,ratio=1): ''' computes the tangential eigenvalue of the Jacobian matrix from kappa and gamma ''' return (1-kappa*ratio-gamma*ratio) def radial_eigenvalue_dxdy(deflectx,deflecty,ratio=1,dunit=1): ''' computes the radial eigenvalue of the Jacobian matrix from the deflection matrices ''' kappa,gamma = get_maps(deflectx,deflecty,ratio=ratio,dunit=dunit) return (1-kappa*ratio+gamma*ratio) def tangential_eigenvalue_dxdy(deflectx,deflecty,ratio=1,dunit=1): ''' computes the tangential eigenvalue of the Jacobian matrix from the deflection matrices ''' kappa,gamma = get_maps(deflectx,deflecty,ratio=ratio,dunit=dunit) return (1-kappa*ratio-gamma*ratio) def magnification_kg(kappa,gamma,ratio=1,absolute=True): ''' computes the magnification from kappa and gamma matrices ''' with warnings.catch_warnings(): warnings.simplefilter('ignore') A = (1-kappa*ratio)**2-(gamma*ratio)**2 if absolute: A = np.abs(A) return 1.0/A def magnification_dxdy(deflectx,deflecty,ratio=1,dunit=1,absolute=True): ''' computes the magnification from deflection matrices (in units of pixels) ''' with warnings.catch_warnings(): warnings.simplefilter('ignore') dDXdy,dDXdx = np.gradient(deflectx*ratio/dunit) dDYdy,dDYdx = np.gradient(deflecty*ratio/dunit) A = (1-dDXdx)*(1-dDYdy)-dDXdy*dDYdx if absolute: A = np.abs(A) return 1.0/A def get_kappa(deflectx,deflecty,ratio=1,dunit=1): ''' computes kappa from deflection matrices ''' dDXdy,dDXdx = np.gradient(deflectx*ratio/dunit) dDYdy,dDYdx = np.gradient(deflecty*ratio/dunit) return 0.5*(dDXdx+dDYdy) def get_gamma1(deflectx,deflecty,ratio=1,dunit=1): ''' computes first component of gamma from deflection matrices ''' dDXdy,dDXdx = np.gradient(deflectx*ratio/dunit) dDYdy,dDYdx = np.gradient(deflecty*ratio/dunit) return 0.5*(dDXdx-dDYdy) def get_gamma2(deflectx,deflecty,ratio=1,dunit=1): ''' computes second component of gamma from deflection matrices ''' dDXdy,dDXdx = np.gradient(deflectx*ratio/dunit) return dDXdy def get_gamma(deflectx,deflecty,ratio=1,dunit=1): ''' computes gamma from deflection matrices ''' dDXdy,dDXdx = np.gradient(deflectx*ratio/dunit) dDYdy,dDYdx = np.gradient(deflecty*ratio/dunit) gamma1 = 0.5*(dDXdx-dDYdy) gamma2 = dDXdy return np.sqrt(gamma1**2+gamma2**2) def get_maps(deflectx,deflecty,ratio=1,dunit=1,return_all=False): ''' computes kappa and gamma (and gamma1,gamma2) from deflection matrices ''' dDXdy,dDXdx = np.gradient(deflectx*ratio/dunit) dDYdy,dDYdx = np.gradient(deflecty*ratio/dunit) kappa = 0.5*(dDXdx+dDYdy) gamma1 = 0.5*(dDXdx-dDYdy) gamma2 = dDXdy gamma = np.sqrt(gamma1**2+gamma2**2) if return_all: return kappa,gamma,gamma1,gamma2 else: return kappa,gamma def fermat_potential(sx,sy,deflectx,deflecty,psi,zl,zs,ratio=1,cosmo=FlatLambdaCDM(Om0=0.3,H0=70),dx=0,dy=0,ps=0.03*u.arcsec): ''' computes the time delays in seconds in the image plane originating from a single source plane position ''' thetaX,thetaY = np.meshgrid(np.arange(psi.shape[1])+1,np.arange(psi.shape[0])+1) sep = (np.sqrt((thetaX-sx)**2+(thetaY-sy)**2))*ps dls = cosmo.angular_diameter_distance_z1z2(zl,zs) ds = cosmo.angular_diameter_distance(zs) dl = cosmo.angular_diameter_distance(zl) fermat = ((1+zl)/const.c * (dl*ds)/dls * (0.5*sep**2 - psi*(u.arcsec)**2*ratio)).to('rad**2 s') return fermat
[ "numpy.abs", "numpy.sqrt", "warnings.catch_warnings", "astropy.cosmology.FlatLambdaCDM", "warnings.simplefilter", "numpy.gradient", "numpy.arange" ]
[((463, 492), 'astropy.cosmology.FlatLambdaCDM', 'FlatLambdaCDM', ([], {'H0': '(70)', 'Om0': '(0.3)'}), '(H0=70, Om0=0.3)\n', (476, 492), False, 'from astropy.cosmology import FlatLambdaCDM\n'), ((797, 826), 'astropy.cosmology.FlatLambdaCDM', 'FlatLambdaCDM', ([], {'H0': '(70)', 'Om0': '(0.3)'}), '(H0=70, Om0=0.3)\n', (810, 826), False, 'from astropy.cosmology import FlatLambdaCDM\n'), ((3516, 3553), 'numpy.gradient', 'np.gradient', (['(deflectx * ratio / dunit)'], {}), '(deflectx * ratio / dunit)\n', (3527, 3553), True, 'import numpy as np\n'), ((3568, 3605), 'numpy.gradient', 'np.gradient', (['(deflecty * ratio / dunit)'], {}), '(deflecty * ratio / dunit)\n', (3579, 3605), True, 'import numpy as np\n'), ((3780, 3817), 'numpy.gradient', 'np.gradient', (['(deflectx * ratio / dunit)'], {}), '(deflectx * ratio / dunit)\n', (3791, 3817), True, 'import numpy as np\n'), ((3832, 3869), 'numpy.gradient', 'np.gradient', (['(deflecty * ratio / dunit)'], {}), '(deflecty * ratio / dunit)\n', (3843, 3869), True, 'import numpy as np\n'), ((4045, 4082), 'numpy.gradient', 'np.gradient', (['(deflectx * ratio / dunit)'], {}), '(deflectx * ratio / dunit)\n', (4056, 4082), True, 'import numpy as np\n'), ((4225, 4262), 'numpy.gradient', 'np.gradient', (['(deflectx * ratio / dunit)'], {}), '(deflectx * ratio / dunit)\n', (4236, 4262), True, 'import numpy as np\n'), ((4277, 4314), 'numpy.gradient', 'np.gradient', (['(deflecty * ratio / dunit)'], {}), '(deflecty * ratio / dunit)\n', (4288, 4314), True, 'import numpy as np\n'), ((4372, 4406), 'numpy.sqrt', 'np.sqrt', (['(gamma1 ** 2 + gamma2 ** 2)'], {}), '(gamma1 ** 2 + gamma2 ** 2)\n', (4379, 4406), True, 'import numpy as np\n'), ((4577, 4614), 'numpy.gradient', 'np.gradient', (['(deflectx * ratio / dunit)'], {}), '(deflectx * ratio / dunit)\n', (4588, 4614), True, 'import numpy as np\n'), ((4629, 4666), 'numpy.gradient', 'np.gradient', (['(deflecty * ratio / dunit)'], {}), '(deflecty * ratio / dunit)\n', (4640, 4666), True, 'import numpy as np\n'), ((4755, 4789), 'numpy.sqrt', 'np.sqrt', (['(gamma1 ** 2 + gamma2 ** 2)'], {}), '(gamma1 ** 2 + gamma2 ** 2)\n', (4762, 4789), True, 'import numpy as np\n'), ((4951, 4980), 'astropy.cosmology.FlatLambdaCDM', 'FlatLambdaCDM', ([], {'Om0': '(0.3)', 'H0': '(70)'}), '(Om0=0.3, H0=70)\n', (4964, 4980), False, 'from astropy.cosmology import FlatLambdaCDM\n'), ((1445, 1470), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {}), '()\n', (1468, 1470), False, 'import warnings\n'), ((1480, 1511), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""'], {}), "('ignore')\n", (1501, 1511), False, 'import warnings\n'), ((1534, 1571), 'numpy.gradient', 'np.gradient', (['(deflectx * ratio / dunit)'], {}), '(deflectx * ratio / dunit)\n', (1545, 1571), True, 'import numpy as np\n'), ((1590, 1627), 'numpy.gradient', 'np.gradient', (['(deflecty * ratio / dunit)'], {}), '(deflecty * ratio / dunit)\n', (1601, 1627), True, 'import numpy as np\n'), ((2761, 2786), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {}), '()\n', (2784, 2786), False, 'import warnings\n'), ((2796, 2827), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""'], {}), "('ignore')\n", (2817, 2827), False, 'import warnings\n'), ((3108, 3133), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {}), '()\n', (3131, 3133), False, 'import warnings\n'), ((3143, 3174), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""'], {}), "('ignore')\n", (3164, 3174), False, 'import warnings\n'), ((3197, 3234), 'numpy.gradient', 'np.gradient', (['(deflectx * ratio / dunit)'], {}), '(deflectx * ratio / dunit)\n', (3208, 3234), True, 'import numpy as np\n'), ((3253, 3290), 'numpy.gradient', 'np.gradient', (['(deflecty * ratio / dunit)'], {}), '(deflecty * ratio / dunit)\n', (3264, 3290), True, 'import numpy as np\n'), ((5229, 5277), 'numpy.sqrt', 'np.sqrt', (['((thetaX - sx) ** 2 + (thetaY - sy) ** 2)'], {}), '((thetaX - sx) ** 2 + (thetaY - sy) ** 2)\n', (5236, 5277), True, 'import numpy as np\n'), ((2901, 2910), 'numpy.abs', 'np.abs', (['A'], {}), '(A)\n', (2907, 2910), True, 'import numpy as np\n'), ((3356, 3365), 'numpy.abs', 'np.abs', (['A'], {}), '(A)\n', (3362, 3365), True, 'import numpy as np\n'), ((5165, 5188), 'numpy.arange', 'np.arange', (['psi.shape[1]'], {}), '(psi.shape[1])\n', (5174, 5188), True, 'import numpy as np\n'), ((5191, 5214), 'numpy.arange', 'np.arange', (['psi.shape[0]'], {}), '(psi.shape[0])\n', (5200, 5214), True, 'import numpy as np\n')]
import re from collections import defaultdict import numpy as np import pandas as pd from terminaltables import DoubleTable from pathlib import Path def weather_table(weather_dict, path): table_data = [] for weather, seeds in weather_dict.items(): successes = [] totals = [] collisions = [] collided_and_success = [] total_lights = [] total_lights_ran = [] for seed in seeds: successes.append(seeds[seed]["success"]) totals.append(seeds[seed]["total"]) collisions.append(seeds[seed]["collided"]) collided_and_success.append(seeds[seed]["collided_and_success"]) total_lights.append(seeds[seed]["total_lights"]) total_lights_ran.append(seeds[seed]["total_lights_ran"]) successes = np.array(successes) totals = np.array(totals) collisions = np.array(collisions) collided_and_success = np.array(collided_and_success) total_lights = np.array(total_lights) total_lights_ran = np.array(total_lights_ran) success_rates = successes / totals * 100 lights_ran_rates = total_lights_ran / total_lights * 100 timeouts = totals - successes - collisions + collided_and_success collision_rates = collisions / totals * 100 timeout_rates = timeouts / totals * 100 collided_and_success_rates= collided_and_success / totals * 100 for elem in abs(timeout_rates + collision_rates + success_rates - collided_and_success_rates): assert 99.9 < elem < 100.1, "rates do not sum to 100" if len(seeds) > 1: table_data.append([weather, "%.1f ± %.1f" % (np.mean(success_rates), np.std(success_rates, ddof=1)), "%d/%d" % (sum(successes), sum(totals)), ','.join(sorted(seeds.keys())), "%.1f ± %.1f" % (np.mean(collision_rates), np.std(collision_rates, ddof=1)), "%.1f ± %.1f" % (np.mean(timeout_rates), np.std(timeout_rates, ddof=1)), "%.1f ± %.1f" % (np.mean(lights_ran_rates), np.std(lights_ran_rates, ddof=1)), "%d" % np.sum(collided_and_success)]) else: table_data.append([weather, "%.1f" % np.mean(success_rates), "%d/%d" % (sum(successes), sum(totals)), ','.join(sorted(seeds.keys())), "%.1f" % collision_rates, "%.1f" % timeout_rates, "%.1f" % lights_ran_rates, "%.d" % collided_and_success]) table_data = sorted(table_data, key=lambda row: row[0]) table_data = [('Weather', 'Success Rate %', 'Total', 'Seeds', "Collision %", "Timeout %", "Lights ran %", "Collided+Success")] + table_data table = DoubleTable(table_data, "Performance of %s" % path.name) print(table.table) def main(path_name, separate_seeds=False, create_weather_table=False): performance = dict() weather_dict = defaultdict(lambda: defaultdict(lambda: defaultdict(float))) path = Path(path_name) for summary_path in path.glob('*/summary.csv'): name = summary_path.parent.name match = re.search('^(?P<suite_name>.*Town.*-v[0-9]+.*)_seed(?P<seed>[0-9]+)', name) suite_name = match.group('suite_name') seed = match.group('seed') summary = pd.read_csv(summary_path) if suite_name not in performance: performance[suite_name] = dict() collided_and_success_dataframe = np.logical_and(summary["success"], summary["collided"]) performance[suite_name][seed] = (summary['success'].sum(), len(summary), summary["collided"].sum(), collided_and_success_dataframe.sum(), summary["total_lights"].sum(), summary["total_lights_ran"].sum()) if create_weather_table: # need to iterate over each route for i in range(len(summary)): weather_dict[summary["weather"][i]][seed]["success"] += summary["success"][i] weather_dict[summary["weather"][i]][seed]["total"] += 1 weather_dict[summary["weather"][i]][seed]["collided"] += summary["collided"][i] weather_dict[summary["weather"][i]][seed]["collided_and_success"] += np.logical_and(summary["success"][i], summary["collided"][i]) weather_dict[summary["weather"][i]][seed]["total_lights"] += summary["total_lights"][i] weather_dict[summary["weather"][i]][seed]["total_lights_ran"] += summary["total_lights_ran"][i] if create_weather_table: weather_table(weather_dict, path) return table_data = [] for suite_name, seeds in performance.items(): if separate_seeds: for seed in seeds: successes, totals, collisions, collided_and_success, total_lights, total_lights_ran = np.array(seeds[seed]) success_rates = successes / totals * 100 lights_ran_rates = total_lights_ran / total_lights * 100 timeouts = totals - successes - collisions + collided_and_success collision_rates = collisions / totals * 100 timeout_rates = timeouts / totals * 100 table_data.append( [suite_name+"-seed-"+seed, "%.1f" % success_rates, "%d/%d" % (successes, totals), ','.join(seed), "%.1f" % collision_rates, "%.1f" % timeout_rates, "%.1f" % lights_ran_rates, "%d" % collided_and_success]) else: successes, totals, collisions, collided_and_success, total_lights, total_lights_ran = np.array(list(zip(*seeds.values()))) success_rates = successes / totals * 100 lights_ran_rates = total_lights_ran / total_lights * 100 timeouts = totals - successes - collisions + collided_and_success collision_rates = collisions / totals * 100 timeout_rates = timeouts / totals * 100 if len(seeds) > 1: table_data.append([suite_name, "%.1f ± %.1f"%(np.mean(success_rates), np.std(success_rates, ddof=1)), "%d/%d"%(sum(successes),sum(totals)), ','.join(sorted(seeds.keys())), "%.1f ± %.1f"%(np.mean(collision_rates), np.std(collision_rates, ddof=1)), "%.1f ± %.1f"%(np.mean(timeout_rates), np.std(timeout_rates, ddof=1)), "%.1f ± %.1f"%(np.mean(lights_ran_rates), np.std(lights_ran_rates, ddof=1)), "%d"%np.sum(collided_and_success)]) else: table_data.append([suite_name, "%.1f"%np.mean(success_rates), "%d/%d"%(sum(successes),sum(totals)), ','.join(sorted(seeds.keys())), "%.1f"%collision_rates, "%.1f"%timeout_rates, "%.1f"%lights_ran_rates, "%d"%collided_and_success]) table_data = sorted(table_data, key=lambda row: row[0]) table_data = [('Suite Name', 'Success Rate %', 'Total', 'Seeds', "Collision %", "Timeout %", "Lights ran %", "Collided+Success")] + table_data table = DoubleTable(table_data, "Performance of %s"%path.name) print(table.table) if __name__ == '__main__': import argparse parser = argparse.ArgumentParser() parser.add_argument('--path', help='path of benchmark folder') parser.add_argument("--separate-seeds", action="store_true") parser.add_argument("--weather", action="store_true") args = parser.parse_args() main(args.path, args.separate_seeds, create_weather_table=args.weather)
[ "numpy.mean", "argparse.ArgumentParser", "pathlib.Path", "pandas.read_csv", "numpy.logical_and", "numpy.array", "numpy.sum", "terminaltables.DoubleTable", "collections.defaultdict", "numpy.std", "re.search" ]
[((2446, 2502), 'terminaltables.DoubleTable', 'DoubleTable', (['table_data', "('Performance of %s' % path.name)"], {}), "(table_data, 'Performance of %s' % path.name)\n", (2457, 2502), False, 'from terminaltables import DoubleTable\n'), ((2705, 2720), 'pathlib.Path', 'Path', (['path_name'], {}), '(path_name)\n', (2709, 2720), False, 'from pathlib import Path\n'), ((6239, 6295), 'terminaltables.DoubleTable', 'DoubleTable', (['table_data', "('Performance of %s' % path.name)"], {}), "(table_data, 'Performance of %s' % path.name)\n", (6250, 6295), False, 'from terminaltables import DoubleTable\n'), ((6372, 6397), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (6395, 6397), False, 'import argparse\n'), ((722, 741), 'numpy.array', 'np.array', (['successes'], {}), '(successes)\n', (730, 741), True, 'import numpy as np\n'), ((753, 769), 'numpy.array', 'np.array', (['totals'], {}), '(totals)\n', (761, 769), True, 'import numpy as np\n'), ((785, 805), 'numpy.array', 'np.array', (['collisions'], {}), '(collisions)\n', (793, 805), True, 'import numpy as np\n'), ((831, 861), 'numpy.array', 'np.array', (['collided_and_success'], {}), '(collided_and_success)\n', (839, 861), True, 'import numpy as np\n'), ((879, 901), 'numpy.array', 'np.array', (['total_lights'], {}), '(total_lights)\n', (887, 901), True, 'import numpy as np\n'), ((923, 949), 'numpy.array', 'np.array', (['total_lights_ran'], {}), '(total_lights_ran)\n', (931, 949), True, 'import numpy as np\n'), ((2814, 2889), 're.search', 're.search', (['"""^(?P<suite_name>.*Town.*-v[0-9]+.*)_seed(?P<seed>[0-9]+)"""', 'name'], {}), "('^(?P<suite_name>.*Town.*-v[0-9]+.*)_seed(?P<seed>[0-9]+)', name)\n", (2823, 2889), False, 'import re\n'), ((2973, 2998), 'pandas.read_csv', 'pd.read_csv', (['summary_path'], {}), '(summary_path)\n', (2984, 2998), True, 'import pandas as pd\n'), ((3108, 3163), 'numpy.logical_and', 'np.logical_and', (["summary['success']", "summary['collided']"], {}), "(summary['success'], summary['collided'])\n", (3122, 3163), True, 'import numpy as np\n'), ((3791, 3852), 'numpy.logical_and', 'np.logical_and', (["summary['success'][i]", "summary['collided'][i]"], {}), "(summary['success'][i], summary['collided'][i])\n", (3805, 3852), True, 'import numpy as np\n'), ((4318, 4339), 'numpy.array', 'np.array', (['seeds[seed]'], {}), '(seeds[seed])\n', (4326, 4339), True, 'import numpy as np\n'), ((2675, 2693), 'collections.defaultdict', 'defaultdict', (['float'], {}), '(float)\n', (2686, 2693), False, 'from collections import defaultdict\n'), ((1917, 1945), 'numpy.sum', 'np.sum', (['collided_and_success'], {}), '(collided_and_success)\n', (1923, 1945), True, 'import numpy as np\n'), ((1996, 2018), 'numpy.mean', 'np.mean', (['success_rates'], {}), '(success_rates)\n', (2003, 2018), True, 'import numpy as np\n'), ((1503, 1525), 'numpy.mean', 'np.mean', (['success_rates'], {}), '(success_rates)\n', (1510, 1525), True, 'import numpy as np\n'), ((1527, 1556), 'numpy.std', 'np.std', (['success_rates'], {'ddof': '(1)'}), '(success_rates, ddof=1)\n', (1533, 1556), True, 'import numpy as np\n'), ((1669, 1693), 'numpy.mean', 'np.mean', (['collision_rates'], {}), '(collision_rates)\n', (1676, 1693), True, 'import numpy as np\n'), ((1695, 1726), 'numpy.std', 'np.std', (['collision_rates'], {'ddof': '(1)'}), '(collision_rates, ddof=1)\n', (1701, 1726), True, 'import numpy as np\n'), ((1756, 1778), 'numpy.mean', 'np.mean', (['timeout_rates'], {}), '(timeout_rates)\n', (1763, 1778), True, 'import numpy as np\n'), ((1780, 1809), 'numpy.std', 'np.std', (['timeout_rates'], {'ddof': '(1)'}), '(timeout_rates, ddof=1)\n', (1786, 1809), True, 'import numpy as np\n'), ((1839, 1864), 'numpy.mean', 'np.mean', (['lights_ran_rates'], {}), '(lights_ran_rates)\n', (1846, 1864), True, 'import numpy as np\n'), ((1866, 1898), 'numpy.std', 'np.std', (['lights_ran_rates'], {'ddof': '(1)'}), '(lights_ran_rates, ddof=1)\n', (1872, 1898), True, 'import numpy as np\n'), ((5744, 5772), 'numpy.sum', 'np.sum', (['collided_and_success'], {}), '(collided_and_success)\n', (5750, 5772), True, 'import numpy as np\n'), ((5826, 5848), 'numpy.mean', 'np.mean', (['success_rates'], {}), '(success_rates)\n', (5833, 5848), True, 'import numpy as np\n'), ((5336, 5358), 'numpy.mean', 'np.mean', (['success_rates'], {}), '(success_rates)\n', (5343, 5358), True, 'import numpy as np\n'), ((5360, 5389), 'numpy.std', 'np.std', (['success_rates'], {'ddof': '(1)'}), '(success_rates, ddof=1)\n', (5366, 5389), True, 'import numpy as np\n'), ((5499, 5523), 'numpy.mean', 'np.mean', (['collision_rates'], {}), '(collision_rates)\n', (5506, 5523), True, 'import numpy as np\n'), ((5525, 5556), 'numpy.std', 'np.std', (['collision_rates'], {'ddof': '(1)'}), '(collision_rates, ddof=1)\n', (5531, 5556), True, 'import numpy as np\n'), ((5585, 5607), 'numpy.mean', 'np.mean', (['timeout_rates'], {}), '(timeout_rates)\n', (5592, 5607), True, 'import numpy as np\n'), ((5609, 5638), 'numpy.std', 'np.std', (['timeout_rates'], {'ddof': '(1)'}), '(timeout_rates, ddof=1)\n', (5615, 5638), True, 'import numpy as np\n'), ((5667, 5692), 'numpy.mean', 'np.mean', (['lights_ran_rates'], {}), '(lights_ran_rates)\n', (5674, 5692), True, 'import numpy as np\n'), ((5694, 5726), 'numpy.std', 'np.std', (['lights_ran_rates'], {'ddof': '(1)'}), '(lights_ran_rates, ddof=1)\n', (5700, 5726), True, 'import numpy as np\n')]
import numpy as np import cv2 from sklearn.utils import shuffle from sklearn.model_selection import cross_val_score from sklearn.neighbors import KNeighborsClassifier import matplotlib.pyplot as plt import pandas as pd def single_ch_hist(image, channels, bins, chrange, color): hist = cv2.calcHist(image, channels, None, bins, chrange) return hist def plot_hist(image,bins,r1,r2,r3): histarr = [] histarr.append(single_ch_hist(image, [0], [bins], [0, r1], 'r')) histarr.append(single_ch_hist(image, [1], [bins], [0, r2], 'g')) histarr.append(single_ch_hist(image, [2], [bins], [0, r3], 'y')) histarr = np.asarray(histarr) histarr = histarr.reshape((3, bins)) plt.show() return histarr folderarr = ["landscape","night","portrait"] finarr = [] for i in folderarr: for j in range(1,44): img = cv2.imread(i + "/" + str(j) + ".jpg"); print(i + "/" + str(j) + ".jpg") img_new = cv2.resize(img, (500, 500)); img_hsv = cv2.cvtColor(img_new, cv2.COLOR_BGR2HSV) arr = plot_hist(img_hsv,32,179,255,255) arr1 = plot_hist(img_new,32,255,255,255) finarr.append(arr) #Adding histogram of HSV image finarr.append(arr1)#Adding histogram of BGR image z = np.asarray(finarr) z = z.reshape(129, 192) features = pd.DataFrame(z) features.columns = [str(col) + '_col' for col in data.columns] labels = [] for i in folderarr: for j in range(43): labels.append((i)) label = pd.DataFrame(labels, columns=["labels"]) data = pd.concat([features, label], axis = 1) data = shuffle(data) X=data[ ['0_col', '1_col', '2_col', '3_col', '4_col', '5_col', '6_col', '7_col', '8_col', '9_col', '10_col', '11_col', '12_col', '13_col', '14_col', '15_col', '16_col', '17_col', '18_col', '19_col', '20_col', '21_col', '22_col', '23_col', '24_col', '25_col', '26_col', '27_col', '28_col', '29_col', '30_col', '31_col', '32_col', '33_col', '34_col', '35_col', '36_col', '37_col', '38_col', '39_col', '40_col', '41_col', '42_col', '43_col', '44_col', '45_col', '46_col', '47_col', '48_col', '49_col', '50_col', '51_col', '52_col', '53_col', '54_col', '55_col', '56_col', '57_col', '58_col', '59_col', '60_col', '61_col', '62_col', '63_col', '64_col', '65_col', '66_col', '67_col', '68_col', '69_col', '70_col', '71_col', '72_col', '73_col', '74_col', '75_col', '76_col', '77_col', '78_col', '79_col', '80_col', '81_col', '82_col', '83_col', '84_col', '85_col', '86_col', '87_col', '88_col', '89_col', '90_col', '91_col', '92_col', '93_col', '94_col', '95_col', '96_col', '97_col', '98_col', '99_col', '100_col', '101_col', '102_col', '103_col', '104_col', '105_col', '106_col', '107_col', '108_col', '109_col', '110_col', '111_col', '112_col', '113_col', '114_col', '115_col', '116_col', '117_col', '118_col', '119_col', '120_col', '121_col', '122_col', '123_col', '124_col', '125_col', '126_col', '127_col', '128_col', '129_col', '130_col', '131_col', '132_col', '133_col', '134_col', '135_col', '136_col', '137_col', '138_col', '139_col', '140_col', '141_col', '142_col', '143_col', '144_col', '145_col', '146_col', '147_col', '148_col', '149_col', '150_col', '151_col', '152_col', '153_col', '154_col', '155_col', '156_col', '157_col', '158_col', '159_col', '160_col', '161_col', '162_col', '163_col', '164_col', '165_col', '166_col', '167_col', '168_col', '169_col', '170_col', '171_col', '172_col', '173_col', '174_col', '175_col', '176_col', '177_col', '178_col', '179_col', '180_col', '181_col', '182_col', '183_col', '184_col', '185_col', '186_col', '187_col', '188_col', '189_col', '190_col', '191_col' ]] y=data['labels'] scores=[] knn = KNeighborsClassifier(algorithm='auto', metric_params=None, n_jobs=None, n_neighbors=3,weights='uniform') cv_score = np.mean(cross_val_score(knn, X, y, cv=6)) scores.append(cv_score) print(scores)
[ "cv2.calcHist", "sklearn.utils.shuffle", "sklearn.model_selection.cross_val_score", "numpy.asarray", "sklearn.neighbors.KNeighborsClassifier", "cv2.cvtColor", "pandas.DataFrame", "cv2.resize", "pandas.concat", "matplotlib.pyplot.show" ]
[((1249, 1267), 'numpy.asarray', 'np.asarray', (['finarr'], {}), '(finarr)\n', (1259, 1267), True, 'import numpy as np\n'), ((1303, 1318), 'pandas.DataFrame', 'pd.DataFrame', (['z'], {}), '(z)\n', (1315, 1318), True, 'import pandas as pd\n'), ((1475, 1515), 'pandas.DataFrame', 'pd.DataFrame', (['labels'], {'columns': "['labels']"}), "(labels, columns=['labels'])\n", (1487, 1515), True, 'import pandas as pd\n'), ((1523, 1559), 'pandas.concat', 'pd.concat', (['[features, label]'], {'axis': '(1)'}), '([features, label], axis=1)\n', (1532, 1559), True, 'import pandas as pd\n'), ((1569, 1582), 'sklearn.utils.shuffle', 'shuffle', (['data'], {}), '(data)\n', (1576, 1582), False, 'from sklearn.utils import shuffle\n'), ((3823, 3932), 'sklearn.neighbors.KNeighborsClassifier', 'KNeighborsClassifier', ([], {'algorithm': '"""auto"""', 'metric_params': 'None', 'n_jobs': 'None', 'n_neighbors': '(3)', 'weights': '"""uniform"""'}), "(algorithm='auto', metric_params=None, n_jobs=None,\n n_neighbors=3, weights='uniform')\n", (3843, 3932), False, 'from sklearn.neighbors import KNeighborsClassifier\n'), ((291, 341), 'cv2.calcHist', 'cv2.calcHist', (['image', 'channels', 'None', 'bins', 'chrange'], {}), '(image, channels, None, bins, chrange)\n', (303, 341), False, 'import cv2\n'), ((633, 652), 'numpy.asarray', 'np.asarray', (['histarr'], {}), '(histarr)\n', (643, 652), True, 'import numpy as np\n'), ((698, 708), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (706, 708), True, 'import matplotlib.pyplot as plt\n'), ((3947, 3979), 'sklearn.model_selection.cross_val_score', 'cross_val_score', (['knn', 'X', 'y'], {'cv': '(6)'}), '(knn, X, y, cv=6)\n', (3962, 3979), False, 'from sklearn.model_selection import cross_val_score\n'), ((944, 971), 'cv2.resize', 'cv2.resize', (['img', '(500, 500)'], {}), '(img, (500, 500))\n', (954, 971), False, 'import cv2\n'), ((991, 1031), 'cv2.cvtColor', 'cv2.cvtColor', (['img_new', 'cv2.COLOR_BGR2HSV'], {}), '(img_new, cv2.COLOR_BGR2HSV)\n', (1003, 1031), False, 'import cv2\n')]
"""run_experiment. Usage: run_experiment_slac.py run [--env=<kn>] [--steps=<kn>] [--seed=<kn>] [--render] run_experiment_slac.py (-h | --help) Options: -h --help Show this screen. --env=<kn> Environment (see readme.txt) [default: PendulumV]. --steps=<kn> How many steps to run [default: 50000]. --seed=<kn> Random seed [default: 0]. """ from docopt import docopt import numpy as np import gym import torch from torch.nn.utils.rnn import pad_sequence import torch.nn as nn from torch.autograd import Variable import time, os, argparse, warnings import scipy.io as sio from copy import deepcopy from slac import SLAC arguments = docopt(__doc__, version="1.0") def test_performance(agent_test, env_test, action_filter, times=5): EpiTestRet = 0 for _ in range(times): # reset each episode sp_seq = np.zeros([seq_len, env.observation_space.shape[0] + 1]) s = env_test.reset() sp_seq[-1, :-1] = s sp_seq[-1, -1] = 0.0 # reward padding a = agent.select(sp_seq) for _ in range(max_steps): if np.any(np.isnan(a)): raise ValueError sp, r, done, _ = env_test.step(action_filter(a)) sp_seq[:-1] = deepcopy(sp_seq[1:]) sp_seq[-1, :-1] = deepcopy(sp) sp_seq[-1, -1] = r a = agent_test.select( sp_seq, action_return="normal" ) # use tanh(mu_a) for evaluating performance EpiTestRet += r if done: break EpiTestRet_mean = 0 for _ in range(times): # reset each episode sp_seq = np.zeros([seq_len, env.observation_space.shape[0] + 1]) s = env_test.reset() sp_seq[-1, :-1] = s sp_seq[-1, -1] = 0.0 # reward padding a = agent.select(sp_seq) for _ in range(max_steps): if np.any(np.isnan(a)): raise ValueError sp, r, done, _ = env_test.step(action_filter(a)) sp_seq[:-1] = deepcopy(sp_seq[1:]) sp_seq[-1, :-1] = deepcopy(sp) sp_seq[-1, -1] = r a = agent_test.select( sp_seq, action_return="mean" ) # use tanh(mu_a) for evaluating performance EpiTestRet_mean += r if done: break return EpiTestRet / times, EpiTestRet_mean / times savepath = "./data/" if os.path.exists(savepath): warnings.warn("{} exists (possibly so do data).".format(savepath)) else: os.makedirs(savepath) seed = int(arguments["--seed"]) # random seed np.random.seed(seed) torch.manual_seed(seed) # Shared computation_mode = "implicit" beta_h = "auto_1.0" optimizer = "adam" batch_size = 32 seq_len = 8 reward_scale = 1.0 action_feedback = True grad_clip = False gamma = 0.99 equal_pad = True pre_train = True nc = False model_act_fn = nn.Tanh sigx = "auto" max_all_steps = int(arguments["--steps"]) # total steps to learn step_perf_eval = 2000 # how many steps to do evaluation env_name = arguments["--env"] step_start_rl = 1000 step_start_st = 1000 train_step_rl = 1 train_freq_rl = 1.0 / train_step_rl train_step_st = 1 train_freq_st = 1.0 / train_step_st if arguments["--render"]: rendering = True else: rendering = False if env_name == "Sequential": from task import TaskT env = TaskT(3) env_test = TaskT(3) action_filter = lambda a: a.reshape([-1]) max_steps = 128 est_min_steps = 10 elif env_name == "CartPole": from task import ContinuousCartPoleEnv env = ContinuousCartPoleEnv() env_test = ContinuousCartPoleEnv() action_filter = lambda a: a.reshape([-1]) max_steps = 1000 est_min_steps = 5 elif env_name == "CartPoleP": from task import CartPoleP env = CartPoleP() env_test = CartPoleP() action_filter = lambda a: a.reshape([-1]) max_steps = 1000 est_min_steps = 10 elif env_name == "CartPoleV": from task import CartPoleV env = CartPoleV() env_test = CartPoleV() action_filter = lambda a: a.reshape([-1]) max_steps = 1000 est_min_steps = 10 elif env_name == "Pendulum": import gym env = gym.make("Pendulum-v0") env_test = gym.make("Pendulum-v0") action_filter = ( lambda a: a.reshape([-1]) * 2 ) # because range of pendulum's action is [-2, 2]. For other environments, * 2 is not needed max_steps = 200 est_min_steps = 199 elif env_name == "PendulumP": from task import PendulumP env = PendulumP() env_test = PendulumP() action_filter = lambda a: a.reshape([-1]) * 2 max_steps = 200 est_min_steps = 199 elif env_name == "PendulumV": from task import PendulumV env = PendulumV() env_test = PendulumV() action_filter = lambda a: a.reshape([-1]) * 2 max_steps = 200 est_min_steps = 199 elif env_name == "Hopper": import gym import roboschool env = gym.make("RoboschoolHopper-v1") env_test = gym.make("RoboschoolHopper-v1") action_filter = lambda a: a.reshape([-1]) max_steps = 1000 est_min_steps = 5 elif env_name == "HopperP": from task import RsHopperP env = RsHopperP() env_test = RsHopperP() action_filter = lambda a: a.reshape([-1]) max_steps = 1000 est_min_steps = 5 elif env_name == "HopperV": from task import RsHopperV env = RsHopperV() env_test = RsHopperV() action_filter = lambda a: a.reshape([-1]) max_steps = 1000 est_min_steps = 5 elif env_name == "Walker2d": import gym import roboschool env = gym.make("RoboschoolWalker2d-v1") env_test = gym.make("RoboschoolWalker2d-v1") action_filter = lambda a: a.reshape([-1]) max_steps = 1000 est_min_steps = 5 elif env_name == "Walker2dV": from task import RsWalker2dV env = RsWalker2dV() env_test = RsWalker2dV() action_filter = lambda a: a.reshape([-1]) max_steps = 1000 est_min_steps = 5 elif env_name == "Walker2dP": from task import RsWalker2dP env = RsWalker2dP() env_test = RsWalker2dP() action_filter = lambda a: a.reshape([-1]) max_steps = 1000 est_min_steps = 5 elif env_name == "Ant": import gym import roboschool env = gym.make("RoboschoolAnt-v1") env_test = gym.make("RoboschoolAnt-v1") action_filter = lambda a: a.reshape([-1]) max_steps = 1000 est_min_steps = 20 elif env_name == "AntV": from task import RsAntV env = RsAntV() env_test = RsAntV() action_filter = lambda a: a.reshape([-1]) max_steps = 1000 est_min_steps = 20 elif env_name == "AntP": from task import RsAntP env = RsAntP() env_test = RsAntP() action_filter = lambda a: a.reshape([-1]) max_steps = 1000 est_min_steps = 20 # ----------------initialize------------- max_episodes = int(max_all_steps / est_min_steps) + 1 # for replay buffer agent = SLAC( input_size=env.observation_space.shape[0] + 1, action_size=env.action_space.shape[0], seq_len=seq_len, beta_h=beta_h, model_act_fn=model_act_fn, sigx=sigx, ) agent_test = SLAC( input_size=env.observation_space.shape[0] + 1, action_size=env.action_space.shape[0], seq_len=seq_len, beta_h=beta_h, model_act_fn=model_act_fn, sigx=sigx, ) S_real = np.zeros( [max_episodes, max_steps + 1, env.observation_space.shape[0]], dtype=np.float32 ) A_real = np.zeros( [max_episodes, max_steps, env.action_space.shape[0]], dtype=np.float32 ) R_real = np.zeros([max_episodes, max_steps], dtype=np.float32) D_real = np.zeros([max_episodes, max_steps], dtype=np.float32) # done V_real = np.zeros( [max_episodes, max_steps], dtype=np.float32 ) # whether a step is valid value: 1 (compute gradient at this step) or 0 (stop gradient at this step) performance_wrt_step = [] performance_mean_action_wrt_step = [] global_steps = [] e_real = 0 global_step = 0 t_just = 0 while global_step < max_all_steps: sp_seq = np.zeros([seq_len, env.observation_space.shape[0] + 1]) s = env.reset() S_real[e_real, 0] = s.reshape([-1]) sp_seq[-1, :-1] = s sp_seq[-1, -1] = 0.0 if equal_pad: for tau in range(seq_len - 1): sp_seq[tau, :-1] = s a = agent.select(sp_seq) for t in range(max_steps): if global_step == max_all_steps: break sp, r, done, _ = env.step(action_filter(a)) sp_seq[:-1] = deepcopy(sp_seq[1:]) sp_seq[-1, :-1] = deepcopy(sp) sp_seq[-1, -1] = r A_real[e_real, t] = a S_real[e_real, t + 1] = sp.reshape([-1]) R_real[e_real, t] = r D_real[e_real, t] = 1 if done else 0 V_real[e_real, t] = 1 a = agent.select(sp_seq) global_step += 1 s = deepcopy(sp) if pre_train and global_step == step_start_st + 1: for _ in range(5000): weights = np.sum(V_real[:e_real], axis=-1) + 2 * seq_len - 2 sample_es = np.random.choice( e_real, batch_size, p=weights / weights.sum() ) SP = S_real[sample_es, 1:].reshape( [batch_size, -1, env.observation_space.shape[0]] ) A = A_real[sample_es].reshape( [batch_size, -1, env.action_space.shape[0]] ) R = R_real[sample_es].reshape([batch_size, -1, 1]) V = V_real[sample_es].reshape([batch_size, -1, 1]) agent.train_st( x_obs=np.concatenate((SP, R), axis=-1), a_obs=A, r_obs=R, validity=V ) if global_step > step_start_st and np.random.rand() < train_freq_st: for _ in range(max(1, int(train_freq_st))): weights = np.sum(V_real[:e_real], axis=-1) + 2 * seq_len - 2 sample_es = np.random.choice( e_real, batch_size, p=weights / weights.sum() ) SP = S_real[sample_es, 1:].reshape( [batch_size, -1, env.observation_space.shape[0]] ) A = A_real[sample_es].reshape( [batch_size, -1, env.action_space.shape[0]] ) R = R_real[sample_es].reshape([batch_size, -1, 1]) V = V_real[sample_es].reshape([batch_size, -1, 1]) agent.train_st( x_obs=np.concatenate((SP, R), axis=-1), a_obs=A, r_obs=R, validity=V ) if global_step > step_start_rl and np.random.rand() < train_freq_rl: for _ in range(max(1, int(train_freq_rl))): weights = np.sum(V_real[:e_real], axis=-1) + 2 * seq_len - 2 sample_es = np.random.choice( e_real, batch_size, p=weights / weights.sum() ) SP = S_real[sample_es, 1:].reshape( [batch_size, -1, env.observation_space.shape[0]] ) S0 = S_real[sample_es, 0].reshape( [batch_size, env.observation_space.shape[0]] ) A = A_real[sample_es].reshape( [batch_size, -1, env.action_space.shape[0]] ) R = R_real[sample_es].reshape([batch_size, -1, 1]) D = D_real[sample_es].reshape([batch_size, -1, 1]) V = V_real[sample_es].reshape([batch_size, -1, 1]) agent.train_rl_sac( x_obs=np.concatenate((SP, R), axis=-1), s_0=S0, a_obs=A, r_obs=R, d_obs=D, validity=V, gamma=0.99, equal_pad=equal_pad, ) if global_step % step_perf_eval == 0: agent_test.load_state_dict(agent.state_dict()) # update agent_test EpiTestRet, EpiTestRet_mean = test_performance( agent_test, env_test, action_filter, times=5 ) performance_wrt_step.append(EpiTestRet) performance_mean_action_wrt_step.append(EpiTestRet_mean) global_steps.append(global_step) warnings.warn( env_name + ": global step: {}, : steps {}, test return {}".format( global_step, t, EpiTestRet ) ) if done: break print( env_name + " -- episode {} : steps {}, mean reward {}".format( e_real, t, np.mean(R_real[e_real]) ) ) e_real += 1 performance_wrt_step = np.reshape(performance_wrt_step, [-1]).astype(np.float64) performance_mean_action_wrt_step_array = np.reshape( performance_mean_action_wrt_step, [-1] ).astype(np.float64) global_steps = np.reshape(global_steps, [-1]).astype(np.float64) data = { "seq_len": seq_len, "sigx": sigx, "beta_h": beta_h, "gamma": gamma, "max_steps": max_steps, "max_episodes": max_episodes, "step_start_st": step_start_st, "step_start_rl": step_start_rl, "batch_size": batch_size, "train_step_rl": train_step_rl, "train_step_st": train_step_st, "R": np.sum(R_real, axis=-1).astype(np.float64), "steps": np.sum(V_real, axis=-1).astype(np.float64), "performance_wrt_step": performance_wrt_step, "performance_mean_action_wrt_step": performance_mean_action_wrt_step_array, "global_steps": global_steps, } sio.savemat(savepath + env_name + "_" + "slac" + ".mat", data) torch.save(agent, savepath + env_name + "_" + "slac" + ".model")
[ "scipy.io.savemat", "numpy.random.rand", "task.RsAntP", "copy.deepcopy", "task.PendulumP", "task.RsHopperP", "docopt.docopt", "gym.make", "os.path.exists", "numpy.mean", "numpy.reshape", "task.PendulumV", "task.ContinuousCartPoleEnv", "slac.SLAC", "numpy.random.seed", "numpy.concatenat...
[((649, 679), 'docopt.docopt', 'docopt', (['__doc__'], {'version': '"""1.0"""'}), "(__doc__, version='1.0')\n", (655, 679), False, 'from docopt import docopt\n'), ((2415, 2439), 'os.path.exists', 'os.path.exists', (['savepath'], {}), '(savepath)\n', (2429, 2439), False, 'import time, os, argparse, warnings\n'), ((2592, 2612), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (2606, 2612), True, 'import numpy as np\n'), ((2613, 2636), 'torch.manual_seed', 'torch.manual_seed', (['seed'], {}), '(seed)\n', (2630, 2636), False, 'import torch\n'), ((6939, 7109), 'slac.SLAC', 'SLAC', ([], {'input_size': '(env.observation_space.shape[0] + 1)', 'action_size': 'env.action_space.shape[0]', 'seq_len': 'seq_len', 'beta_h': 'beta_h', 'model_act_fn': 'model_act_fn', 'sigx': 'sigx'}), '(input_size=env.observation_space.shape[0] + 1, action_size=env.\n action_space.shape[0], seq_len=seq_len, beta_h=beta_h, model_act_fn=\n model_act_fn, sigx=sigx)\n', (6943, 7109), False, 'from slac import SLAC\n'), ((7141, 7311), 'slac.SLAC', 'SLAC', ([], {'input_size': '(env.observation_space.shape[0] + 1)', 'action_size': 'env.action_space.shape[0]', 'seq_len': 'seq_len', 'beta_h': 'beta_h', 'model_act_fn': 'model_act_fn', 'sigx': 'sigx'}), '(input_size=env.observation_space.shape[0] + 1, action_size=env.\n action_space.shape[0], seq_len=seq_len, beta_h=beta_h, model_act_fn=\n model_act_fn, sigx=sigx)\n', (7145, 7311), False, 'from slac import SLAC\n'), ((7339, 7432), 'numpy.zeros', 'np.zeros', (['[max_episodes, max_steps + 1, env.observation_space.shape[0]]'], {'dtype': 'np.float32'}), '([max_episodes, max_steps + 1, env.observation_space.shape[0]],\n dtype=np.float32)\n', (7347, 7432), True, 'import numpy as np\n'), ((7444, 7529), 'numpy.zeros', 'np.zeros', (['[max_episodes, max_steps, env.action_space.shape[0]]'], {'dtype': 'np.float32'}), '([max_episodes, max_steps, env.action_space.shape[0]], dtype=np.float32\n )\n', (7452, 7529), True, 'import numpy as np\n'), ((7540, 7593), 'numpy.zeros', 'np.zeros', (['[max_episodes, max_steps]'], {'dtype': 'np.float32'}), '([max_episodes, max_steps], dtype=np.float32)\n', (7548, 7593), True, 'import numpy as np\n'), ((7603, 7656), 'numpy.zeros', 'np.zeros', (['[max_episodes, max_steps]'], {'dtype': 'np.float32'}), '([max_episodes, max_steps], dtype=np.float32)\n', (7611, 7656), True, 'import numpy as np\n'), ((7674, 7727), 'numpy.zeros', 'np.zeros', (['[max_episodes, max_steps]'], {'dtype': 'np.float32'}), '([max_episodes, max_steps], dtype=np.float32)\n', (7682, 7727), True, 'import numpy as np\n'), ((13538, 13600), 'scipy.io.savemat', 'sio.savemat', (["(savepath + env_name + '_' + 'slac' + '.mat')", 'data'], {}), "(savepath + env_name + '_' + 'slac' + '.mat', data)\n", (13549, 13600), True, 'import scipy.io as sio\n'), ((13601, 13665), 'torch.save', 'torch.save', (['agent', "(savepath + env_name + '_' + 'slac' + '.model')"], {}), "(agent, savepath + env_name + '_' + 'slac' + '.model')\n", (13611, 13665), False, 'import torch\n'), ((2522, 2543), 'os.makedirs', 'os.makedirs', (['savepath'], {}), '(savepath)\n', (2533, 2543), False, 'import time, os, argparse, warnings\n'), ((3353, 3361), 'task.TaskT', 'TaskT', (['(3)'], {}), '(3)\n', (3358, 3361), False, 'from task import TaskT\n'), ((3377, 3385), 'task.TaskT', 'TaskT', (['(3)'], {}), '(3)\n', (3382, 3385), False, 'from task import TaskT\n'), ((8008, 8063), 'numpy.zeros', 'np.zeros', (['[seq_len, env.observation_space.shape[0] + 1]'], {}), '([seq_len, env.observation_space.shape[0] + 1])\n', (8016, 8063), True, 'import numpy as np\n'), ((845, 900), 'numpy.zeros', 'np.zeros', (['[seq_len, env.observation_space.shape[0] + 1]'], {}), '([seq_len, env.observation_space.shape[0] + 1])\n', (853, 900), True, 'import numpy as np\n'), ((1637, 1692), 'numpy.zeros', 'np.zeros', (['[seq_len, env.observation_space.shape[0] + 1]'], {}), '([seq_len, env.observation_space.shape[0] + 1])\n', (1645, 1692), True, 'import numpy as np\n'), ((3561, 3584), 'task.ContinuousCartPoleEnv', 'ContinuousCartPoleEnv', ([], {}), '()\n', (3582, 3584), False, 'from task import ContinuousCartPoleEnv\n'), ((3600, 3623), 'task.ContinuousCartPoleEnv', 'ContinuousCartPoleEnv', ([], {}), '()\n', (3621, 3623), False, 'from task import ContinuousCartPoleEnv\n'), ((8461, 8481), 'copy.deepcopy', 'deepcopy', (['sp_seq[1:]'], {}), '(sp_seq[1:])\n', (8469, 8481), False, 'from copy import deepcopy\n'), ((8508, 8520), 'copy.deepcopy', 'deepcopy', (['sp'], {}), '(sp)\n', (8516, 8520), False, 'from copy import deepcopy\n'), ((8805, 8817), 'copy.deepcopy', 'deepcopy', (['sp'], {}), '(sp)\n', (8813, 8817), False, 'from copy import deepcopy\n'), ((12691, 12729), 'numpy.reshape', 'np.reshape', (['performance_wrt_step', '[-1]'], {}), '(performance_wrt_step, [-1])\n', (12701, 12729), True, 'import numpy as np\n'), ((12790, 12840), 'numpy.reshape', 'np.reshape', (['performance_mean_action_wrt_step', '[-1]'], {}), '(performance_mean_action_wrt_step, [-1])\n', (12800, 12840), True, 'import numpy as np\n'), ((12881, 12911), 'numpy.reshape', 'np.reshape', (['global_steps', '[-1]'], {}), '(global_steps, [-1])\n', (12891, 12911), True, 'import numpy as np\n'), ((1230, 1250), 'copy.deepcopy', 'deepcopy', (['sp_seq[1:]'], {}), '(sp_seq[1:])\n', (1238, 1250), False, 'from copy import deepcopy\n'), ((1281, 1293), 'copy.deepcopy', 'deepcopy', (['sp'], {}), '(sp)\n', (1289, 1293), False, 'from copy import deepcopy\n'), ((2022, 2042), 'copy.deepcopy', 'deepcopy', (['sp_seq[1:]'], {}), '(sp_seq[1:])\n', (2030, 2042), False, 'from copy import deepcopy\n'), ((2073, 2085), 'copy.deepcopy', 'deepcopy', (['sp'], {}), '(sp)\n', (2081, 2085), False, 'from copy import deepcopy\n'), ((3789, 3800), 'task.CartPoleP', 'CartPoleP', ([], {}), '()\n', (3798, 3800), False, 'from task import CartPoleP\n'), ((3816, 3827), 'task.CartPoleP', 'CartPoleP', ([], {}), '()\n', (3825, 3827), False, 'from task import CartPoleP\n'), ((13270, 13293), 'numpy.sum', 'np.sum', (['R_real'], {'axis': '(-1)'}), '(R_real, axis=-1)\n', (13276, 13293), True, 'import numpy as np\n'), ((13327, 13350), 'numpy.sum', 'np.sum', (['V_real'], {'axis': '(-1)'}), '(V_real, axis=-1)\n', (13333, 13350), True, 'import numpy as np\n'), ((1096, 1107), 'numpy.isnan', 'np.isnan', (['a'], {}), '(a)\n', (1104, 1107), True, 'import numpy as np\n'), ((1888, 1899), 'numpy.isnan', 'np.isnan', (['a'], {}), '(a)\n', (1896, 1899), True, 'import numpy as np\n'), ((3994, 4005), 'task.CartPoleV', 'CartPoleV', ([], {}), '()\n', (4003, 4005), False, 'from task import CartPoleV\n'), ((4021, 4032), 'task.CartPoleV', 'CartPoleV', ([], {}), '()\n', (4030, 4032), False, 'from task import CartPoleV\n'), ((9706, 9722), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (9720, 9722), True, 'import numpy as np\n'), ((10591, 10607), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (10605, 10607), True, 'import numpy as np\n'), ((12611, 12634), 'numpy.mean', 'np.mean', (['R_real[e_real]'], {}), '(R_real[e_real])\n', (12618, 12634), True, 'import numpy as np\n'), ((4182, 4205), 'gym.make', 'gym.make', (['"""Pendulum-v0"""'], {}), "('Pendulum-v0')\n", (4190, 4205), False, 'import gym\n'), ((4221, 4244), 'gym.make', 'gym.make', (['"""Pendulum-v0"""'], {}), "('Pendulum-v0')\n", (4229, 4244), False, 'import gym\n'), ((4523, 4534), 'task.PendulumP', 'PendulumP', ([], {}), '()\n', (4532, 4534), False, 'from task import PendulumP\n'), ((4550, 4561), 'task.PendulumP', 'PendulumP', ([], {}), '()\n', (4559, 4561), False, 'from task import PendulumP\n'), ((8938, 8970), 'numpy.sum', 'np.sum', (['V_real[:e_real]'], {'axis': '(-1)'}), '(V_real[:e_real], axis=-1)\n', (8944, 8970), True, 'import numpy as np\n'), ((9581, 9613), 'numpy.concatenate', 'np.concatenate', (['(SP, R)'], {'axis': '(-1)'}), '((SP, R), axis=-1)\n', (9595, 9613), True, 'import numpy as np\n'), ((9823, 9855), 'numpy.sum', 'np.sum', (['V_real[:e_real]'], {'axis': '(-1)'}), '(V_real[:e_real], axis=-1)\n', (9829, 9855), True, 'import numpy as np\n'), ((10466, 10498), 'numpy.concatenate', 'np.concatenate', (['(SP, R)'], {'axis': '(-1)'}), '((SP, R), axis=-1)\n', (10480, 10498), True, 'import numpy as np\n'), ((10708, 10740), 'numpy.sum', 'np.sum', (['V_real[:e_real]'], {'axis': '(-1)'}), '(V_real[:e_real], axis=-1)\n', (10714, 10740), True, 'import numpy as np\n'), ((11556, 11588), 'numpy.concatenate', 'np.concatenate', (['(SP, R)'], {'axis': '(-1)'}), '((SP, R), axis=-1)\n', (11570, 11588), True, 'import numpy as np\n'), ((4732, 4743), 'task.PendulumV', 'PendulumV', ([], {}), '()\n', (4741, 4743), False, 'from task import PendulumV\n'), ((4759, 4770), 'task.PendulumV', 'PendulumV', ([], {}), '()\n', (4768, 4770), False, 'from task import PendulumV\n'), ((4944, 4975), 'gym.make', 'gym.make', (['"""RoboschoolHopper-v1"""'], {}), "('RoboschoolHopper-v1')\n", (4952, 4975), False, 'import gym\n'), ((4991, 5022), 'gym.make', 'gym.make', (['"""RoboschoolHopper-v1"""'], {}), "('RoboschoolHopper-v1')\n", (4999, 5022), False, 'import gym\n'), ((5186, 5197), 'task.RsHopperP', 'RsHopperP', ([], {}), '()\n', (5195, 5197), False, 'from task import RsHopperP\n'), ((5213, 5224), 'task.RsHopperP', 'RsHopperP', ([], {}), '()\n', (5222, 5224), False, 'from task import RsHopperP\n'), ((5388, 5399), 'task.RsHopperV', 'RsHopperV', ([], {}), '()\n', (5397, 5399), False, 'from task import RsHopperV\n'), ((5415, 5426), 'task.RsHopperV', 'RsHopperV', ([], {}), '()\n', (5424, 5426), False, 'from task import RsHopperV\n'), ((5597, 5630), 'gym.make', 'gym.make', (['"""RoboschoolWalker2d-v1"""'], {}), "('RoboschoolWalker2d-v1')\n", (5605, 5630), False, 'import gym\n'), ((5646, 5679), 'gym.make', 'gym.make', (['"""RoboschoolWalker2d-v1"""'], {}), "('RoboschoolWalker2d-v1')\n", (5654, 5679), False, 'import gym\n'), ((5847, 5860), 'task.RsWalker2dV', 'RsWalker2dV', ([], {}), '()\n', (5858, 5860), False, 'from task import RsWalker2dV\n'), ((5876, 5889), 'task.RsWalker2dV', 'RsWalker2dV', ([], {}), '()\n', (5887, 5889), False, 'from task import RsWalker2dV\n'), ((6057, 6070), 'task.RsWalker2dP', 'RsWalker2dP', ([], {}), '()\n', (6068, 6070), False, 'from task import RsWalker2dP\n'), ((6086, 6099), 'task.RsWalker2dP', 'RsWalker2dP', ([], {}), '()\n', (6097, 6099), False, 'from task import RsWalker2dP\n'), ((6265, 6293), 'gym.make', 'gym.make', (['"""RoboschoolAnt-v1"""'], {}), "('RoboschoolAnt-v1')\n", (6273, 6293), False, 'import gym\n'), ((6309, 6337), 'gym.make', 'gym.make', (['"""RoboschoolAnt-v1"""'], {}), "('RoboschoolAnt-v1')\n", (6317, 6337), False, 'import gym\n'), ((6496, 6504), 'task.RsAntV', 'RsAntV', ([], {}), '()\n', (6502, 6504), False, 'from task import RsAntV\n'), ((6520, 6528), 'task.RsAntV', 'RsAntV', ([], {}), '()\n', (6526, 6528), False, 'from task import RsAntV\n'), ((6687, 6695), 'task.RsAntP', 'RsAntP', ([], {}), '()\n', (6693, 6695), False, 'from task import RsAntP\n'), ((6711, 6719), 'task.RsAntP', 'RsAntP', ([], {}), '()\n', (6717, 6719), False, 'from task import RsAntP\n')]
# -*- coding: utf-8 -*- from __future__ import unicode_literals import numpy as np import matplotlib.pyplot as mp x = np.array([ [3, 1], [2, 5], [1, 8], [6, 4], [5, 2], [3, 5], [4, 7], [4, -1]]) y = np.array([0, 1, 1, 0, 0, 1, 1, 0]) l, r, h = x[:, 0].min() - 1, x[:, 0].max() + 1, 0.005 b, t, v = x[:, 1].min() - 1, x[:, 1].max() + 1, 0.005 grid_x = np.meshgrid(np.arange(l, r, h), np.arange(b, t, v)) flat_x = np.c_[grid_x[0].ravel(), grid_x[1].ravel()] flat_y = np.zeros(len(flat_x), dtype=int) flat_y[flat_x[:, 0] < flat_x[:, 1]] = 1 grid_y = flat_y.reshape(grid_x[0].shape) mp.figure('Simple Classification', facecolor='lightgray') mp.title('Simple Classification', fontsize=20) mp.xlabel('x', fontsize=14) mp.ylabel('y', fontsize=14) mp.tick_params(labelsize=10) mp.pcolormesh(grid_x[0], grid_x[1], grid_y, cmap='gray') mp.scatter(x[:, 0], x[:, 1], c=y, cmap='brg', s=60) mp.show()
[ "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.tick_params", "matplotlib.pyplot.pcolormesh", "numpy.array", "matplotlib.pyplot.figure", "matplotlib.pyplot.scatter", "matplotlib.pyplot.title", "numpy.arange", "matplotlib.pyplot.show" ]
[((118, 193), 'numpy.array', 'np.array', (['[[3, 1], [2, 5], [1, 8], [6, 4], [5, 2], [3, 5], [4, 7], [4, -1]]'], {}), '([[3, 1], [2, 5], [1, 8], [6, 4], [5, 2], [3, 5], [4, 7], [4, -1]])\n', (126, 193), True, 'import numpy as np\n'), ((231, 265), 'numpy.array', 'np.array', (['[0, 1, 1, 0, 0, 1, 1, 0]'], {}), '([0, 1, 1, 0, 0, 1, 1, 0])\n', (239, 265), True, 'import numpy as np\n'), ((632, 689), 'matplotlib.pyplot.figure', 'mp.figure', (['"""Simple Classification"""'], {'facecolor': '"""lightgray"""'}), "('Simple Classification', facecolor='lightgray')\n", (641, 689), True, 'import matplotlib.pyplot as mp\n'), ((700, 746), 'matplotlib.pyplot.title', 'mp.title', (['"""Simple Classification"""'], {'fontsize': '(20)'}), "('Simple Classification', fontsize=20)\n", (708, 746), True, 'import matplotlib.pyplot as mp\n'), ((747, 774), 'matplotlib.pyplot.xlabel', 'mp.xlabel', (['"""x"""'], {'fontsize': '(14)'}), "('x', fontsize=14)\n", (756, 774), True, 'import matplotlib.pyplot as mp\n'), ((775, 802), 'matplotlib.pyplot.ylabel', 'mp.ylabel', (['"""y"""'], {'fontsize': '(14)'}), "('y', fontsize=14)\n", (784, 802), True, 'import matplotlib.pyplot as mp\n'), ((803, 831), 'matplotlib.pyplot.tick_params', 'mp.tick_params', ([], {'labelsize': '(10)'}), '(labelsize=10)\n', (817, 831), True, 'import matplotlib.pyplot as mp\n'), ((832, 888), 'matplotlib.pyplot.pcolormesh', 'mp.pcolormesh', (['grid_x[0]', 'grid_x[1]', 'grid_y'], {'cmap': '"""gray"""'}), "(grid_x[0], grid_x[1], grid_y, cmap='gray')\n", (845, 888), True, 'import matplotlib.pyplot as mp\n'), ((889, 940), 'matplotlib.pyplot.scatter', 'mp.scatter', (['x[:, 0]', 'x[:, 1]'], {'c': 'y', 'cmap': '"""brg"""', 's': '(60)'}), "(x[:, 0], x[:, 1], c=y, cmap='brg', s=60)\n", (899, 940), True, 'import matplotlib.pyplot as mp\n'), ((941, 950), 'matplotlib.pyplot.show', 'mp.show', ([], {}), '()\n', (948, 950), True, 'import matplotlib.pyplot as mp\n'), ((395, 413), 'numpy.arange', 'np.arange', (['l', 'r', 'h'], {}), '(l, r, h)\n', (404, 413), True, 'import numpy as np\n'), ((436, 454), 'numpy.arange', 'np.arange', (['b', 't', 'v'], {}), '(b, t, v)\n', (445, 454), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- import json import os import numpy as np from monty.json import MontyEncoder, MSONable from monty.serialization import loadfn from pydefect.util.logger import get_logger from pydefect.util.tools import make_symmetric_matrix from pymatgen.electronic_structure.core import Spin from pymatgen.io.vasp.outputs import Outcar, Vasprun, Poscar from vise.analyzer.band_gap import band_gap_properties logger = get_logger(__name__) class UnitcellCalcResults(MSONable): """Container class with DFT results for a unitcell. """ def __init__(self, band_edge: list = None, static_dielectric_tensor: list = None, ionic_dielectric_tensor: list = None, total_dos: list = None, volume: float = None, is_direct: bool = None): """ Args: band_edge (list): [VBM, CBM]. static_dielectric_tensor (3x3 list): Electronic part of dielectric tensol. ionic_dielectric_tensor (3x3 list): Ionic part of dielectric tensol. total_dos (list): Total DOS, [[dos1, dos2, ...], [energy1, energy2, ...]] volume (float): Volume in A-3. """ self._band_edge = band_edge[:] if band_edge else None self._static_dielectric_tensor = static_dielectric_tensor self._ionic_dielectric_tensor = ionic_dielectric_tensor self._total_dos = total_dos self._volume = volume self.is_direct = is_direct def __repr__(self): if self._band_edge: band_edge = [round(i, 3) for i in self._band_edge] else: band_edge = [None, None] volume = round(self._volume, 2) if self._volume else None is_total_dos = "Exists" if self._total_dos else "None" if isinstance(self.static_dielectric_tensor, list): static_dielectric = "\n ".join( [str([round(i, 2) for i in j]) for j in self.static_dielectric_tensor]) else: static_dielectric = "None" if isinstance(self.static_dielectric_tensor, list): ionic_dielectric = "\n ".join( [str([round(i, 2) for i in j]) for j in self.ionic_dielectric_tensor]) else: ionic_dielectric = "None" if isinstance(self.total_dielectric_tensor, list): total_dielectric = "\n ".join( [str([round(i, 2) for i in j]) for j in self.total_dielectric_tensor]) else: total_dielectric = "None" outs = [f"vbm (eV): {band_edge[0]}", f"cbm (eV): {band_edge[1]}", f"static dielectric tensor: \n {static_dielectric}", f"ionic dielectric tensor: \n {ionic_dielectric}", f"total dielectric tensor: \n {total_dielectric}", f"volume (A^3): {volume}", f"Total DOS: {is_total_dos}"] return "\n".join(outs) @classmethod def load_json(cls, filename): return loadfn(filename) @staticmethod def check_attribute(name, attr): if attr is None: logger.warning(f"{name}: is None.") return return attr @property def band_edge(self): return self.check_attribute("band edge", self._band_edge) @property def static_dielectric_tensor(self): return self.check_attribute("static dielectric tensor", self._static_dielectric_tensor) @property def ionic_dielectric_tensor(self): return self.check_attribute("ionic dielectric tensor", self._ionic_dielectric_tensor) @property def total_dielectric_tensor(self): try: return (np.array(self.static_dielectric_tensor) + np.array(self.ionic_dielectric_tensor)).tolist() except TypeError: return @property def total_dos(self): return self.check_attribute("total dos", self._total_dos) @property def volume(self): return self.check_attribute("volume", self._volume) @property def is_set_all(self): return all([self._band_edge, self._static_dielectric_tensor, self._ionic_dielectric_tensor, self._total_dos, self._volume]) @band_edge.setter def band_edge(self, band_edge: float): self._band_edge = band_edge @static_dielectric_tensor.setter def static_dielectric_tensor(self, d: list): self._static_dielectric_tensor = make_symmetric_matrix(d) @ionic_dielectric_tensor.setter def ionic_dielectric_tensor(self, d: list): self._ionic_dielectric_tensor = make_symmetric_matrix(d) @total_dos.setter def total_dos(self, total_dos): self._total_dos = total_dos @volume.setter def volume(self, volume: float): self._volume = volume # setter from vasp results def set_band_edge_from_vasp(self, directory_path: str, vasprun_name: str = "vasprun.xml", outcar_name: str = "OUTCAR") -> None: vasprun = Vasprun(os.path.join(directory_path, vasprun_name)) outcar = Outcar(os.path.join(directory_path, outcar_name)) # 2019/7/13 NEVER USE Vasprun.eigenvalue_band_properties # THERE IS A BUG TO ESTIMATE VBM AND CBM of lower band gap materials. _, vbm_info, cbm_info = band_gap_properties(vasprun, outcar) self.is_direct = vbm_info["kpoints"] == cbm_info["kpoints"] self._band_edge = [vbm_info["energy"], cbm_info["energy"]] def set_static_dielectric_tensor_from_vasp(self, directory_path: str, outcar_name: str = "OUTCAR" ) -> None: outcar = Outcar(os.path.join(directory_path, outcar_name)) outcar.read_lepsilon() self._static_dielectric_tensor = outcar.dielectric_tensor def set_ionic_dielectric_tensor_from_vasp(self, directory_path: str, outcar_name: str = "OUTCAR" ) -> None: outcar = Outcar(os.path.join(directory_path, outcar_name)) outcar.read_lepsilon_ionic() self._ionic_dielectric_tensor = outcar.dielectric_ionic_tensor def set_total_dos_and_volume_from_vasp(self, directory_path: str, vasprun_name: str = "vasprun.xml" ) -> None: vasprun = Vasprun(os.path.join(directory_path, vasprun_name)) # DOS of the sum of all spins. dos = list(vasprun.tdos.get_densities()) energies = list(vasprun.tdos.energies) self._total_dos = [dos, energies] self._volume = vasprun.final_structure.volume def to_json_file(self, filename: str = "unitcell.json") -> None: with open(filename, 'w') as fw: json.dump(self.as_dict(), fw, indent=2, cls=MontyEncoder)
[ "pydefect.util.tools.make_symmetric_matrix", "os.path.join", "monty.serialization.loadfn", "numpy.array", "vise.analyzer.band_gap.band_gap_properties", "pydefect.util.logger.get_logger" ]
[((432, 452), 'pydefect.util.logger.get_logger', 'get_logger', (['__name__'], {}), '(__name__)\n', (442, 452), False, 'from pydefect.util.logger import get_logger\n'), ((3148, 3164), 'monty.serialization.loadfn', 'loadfn', (['filename'], {}), '(filename)\n', (3154, 3164), False, 'from monty.serialization import loadfn\n'), ((4739, 4763), 'pydefect.util.tools.make_symmetric_matrix', 'make_symmetric_matrix', (['d'], {}), '(d)\n', (4760, 4763), False, 'from pydefect.util.tools import make_symmetric_matrix\n'), ((4889, 4913), 'pydefect.util.tools.make_symmetric_matrix', 'make_symmetric_matrix', (['d'], {}), '(d)\n', (4910, 4913), False, 'from pydefect.util.tools import make_symmetric_matrix\n'), ((5669, 5705), 'vise.analyzer.band_gap.band_gap_properties', 'band_gap_properties', (['vasprun', 'outcar'], {}), '(vasprun, outcar)\n', (5688, 5705), False, 'from vise.analyzer.band_gap import band_gap_properties\n'), ((5382, 5424), 'os.path.join', 'os.path.join', (['directory_path', 'vasprun_name'], {}), '(directory_path, vasprun_name)\n', (5394, 5424), False, 'import os\n'), ((5450, 5491), 'os.path.join', 'os.path.join', (['directory_path', 'outcar_name'], {}), '(directory_path, outcar_name)\n', (5462, 5491), False, 'import os\n'), ((6120, 6161), 'os.path.join', 'os.path.join', (['directory_path', 'outcar_name'], {}), '(directory_path, outcar_name)\n', (6132, 6161), False, 'import os\n'), ((6535, 6576), 'os.path.join', 'os.path.join', (['directory_path', 'outcar_name'], {}), '(directory_path, outcar_name)\n', (6547, 6576), False, 'import os\n'), ((6957, 6999), 'os.path.join', 'os.path.join', (['directory_path', 'vasprun_name'], {}), '(directory_path, vasprun_name)\n', (6969, 6999), False, 'import os\n'), ((3897, 3936), 'numpy.array', 'np.array', (['self.static_dielectric_tensor'], {}), '(self.static_dielectric_tensor)\n', (3905, 3936), True, 'import numpy as np\n'), ((3959, 3997), 'numpy.array', 'np.array', (['self.ionic_dielectric_tensor'], {}), '(self.ionic_dielectric_tensor)\n', (3967, 3997), True, 'import numpy as np\n')]
# Copyright (C) 2018-2022 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import numpy as np import pytest from common.onnx_layer_test_class import OnnxRuntimeLayerTest class TestSum(OnnxRuntimeLayerTest): def create_net(self, dyn_shapes, const_shapes, precision, ir_version, opset=None): """ ONNX net IR net Inputs->Sum with consts->Output => Input->Eltwise """ # # Create ONNX model # from onnx import helper from onnx import TensorProto inputs = list() input_names = list() out_shape_len = 0 for i, shape in enumerate(dyn_shapes): input_name = 'input{}'.format(i + 1) inputs.append(helper.make_tensor_value_info(input_name, TensorProto.FLOAT, shape)) input_names.append(input_name) if len(shape) > out_shape_len: out_shape_len = len(shape) output_shape = shape output = helper.make_tensor_value_info('output', TensorProto.FLOAT, output_shape) nodes = list() consts = list() for i, shape in enumerate(const_shapes): const = np.random.randint(-127, 127, shape).astype(np.float) const_name = 'const{}'.format(i + 1) nodes.append(helper.make_node( 'Constant', inputs=[], outputs=[const_name], value=helper.make_tensor( name='const_tensor', data_type=TensorProto.FLOAT, dims=const.shape, vals=const.flatten(), ), )) input_names.append(const_name) consts.append(const) nodes.append(helper.make_node( 'Sum', inputs=input_names, outputs=['output'] )) # Create the graph (GraphProto) graph_def = helper.make_graph( nodes, 'test_model', inputs, [output], ) # Create the model (ModelProto) args = dict(producer_name='test_model') if opset: args['opset_imports'] = [helper.make_opsetid("", opset)] onnx_net = helper.make_model(graph_def, **args) # Create reference IR net ref_net = None # Too complicated IR to generate by hand return onnx_net, ref_net def create_const_net(self, const_shapes, ir_version, opset=None): """ ONNX net IR net Inputs->Concat with Sum of consts->Output => Input->Concat with consts """ # # Create ONNX model # from onnx import helper from onnx import TensorProto shape_len = 0 for shape in const_shapes: if len(shape) > shape_len: shape_len = len(shape) input_shape = shape concat_axis = 0 output_shape = input_shape.copy() output_shape[concat_axis] *= 2 input = helper.make_tensor_value_info('input', TensorProto.FLOAT, input_shape) output = helper.make_tensor_value_info('output', TensorProto.FLOAT, output_shape) nodes = list() input_names = list() consts = list() for i, shape in enumerate(const_shapes): const = np.random.randint(-127, 127, shape).astype(np.float) const_name = 'const{}'.format(i + 1) nodes.append(helper.make_node( 'Constant', inputs=[], outputs=[const_name], value=helper.make_tensor( name='const_tensor', data_type=TensorProto.FLOAT, dims=const.shape, vals=const.flatten(), ), )) input_names.append(const_name) consts.append(const) nodes.append(helper.make_node( 'Sum', inputs=input_names, outputs=['sum'] )) nodes.append(helper.make_node( 'Concat', inputs=['input', 'sum'], outputs=['output'], axis=concat_axis )) # Create the graph (GraphProto) graph_def = helper.make_graph( nodes, 'test_model', [input], [output], ) # Create the model (ModelProto) args = dict(producer_name='test_model') if opset: args['opset_imports'] = [helper.make_opsetid("", opset)] onnx_net = helper.make_model(graph_def, **args) # Create reference IR net ref_net = None return onnx_net, ref_net test_data_precommit = [ dict(dyn_shapes=[[4, 6, 8], [4, 6, 8], [4, 6, 8]], const_shapes=[[4, 6, 8], [4, 6, 8], [4, 6, 8]]), dict(dyn_shapes=[[4, 6, 8, 10, 12]], const_shapes=[[4, 6, 8, 10, 12], [4, 6, 8, 10, 12]]), dict(dyn_shapes=[[4, 6, 8, 10, 12], [4, 6, 8, 10, 12], [4, 6, 8, 10, 12]], const_shapes=[[4, 6, 8, 10, 12], [4, 6, 8, 10, 12], [4, 6, 8, 10, 12]])] test_data = [ # TODO: Add broadcasting tests. Note: Sum-6 doesn't support broadcasting dict(dyn_shapes=[[4, 6]], const_shapes=[[4, 6]]), dict(dyn_shapes=[[4, 6]], const_shapes=[[4, 6], [4, 6]]), dict(dyn_shapes=[[4, 6]], const_shapes=[[4, 6], [4, 6], [4, 6]]), dict(dyn_shapes=[[4, 6], [4, 6]], const_shapes=[]), dict(dyn_shapes=[[4, 6], [4, 6]], const_shapes=[[4, 6]]), dict(dyn_shapes=[[4, 6], [4, 6]], const_shapes=[[4, 6], [4, 6]]), dict(dyn_shapes=[[4, 6], [4, 6]], const_shapes=[[4, 6], [4, 6], [4, 6]]), dict(dyn_shapes=[[4, 6], [4, 6], [4, 6]], const_shapes=[]), dict(dyn_shapes=[[4, 6], [4, 6], [4, 6]], const_shapes=[[4, 6]]), dict(dyn_shapes=[[4, 6], [4, 6], [4, 6]], const_shapes=[[4, 6], [4, 6]]), dict(dyn_shapes=[[4, 6], [4, 6], [4, 6]], const_shapes=[[4, 6], [4, 6], [4, 6]]), dict(dyn_shapes=[[4, 6, 8]], const_shapes=[[4, 6, 8]]), dict(dyn_shapes=[[4, 6, 8]], const_shapes=[[4, 6, 8], [4, 6, 8]]), dict(dyn_shapes=[[4, 6, 8]], const_shapes=[[4, 6, 8], [4, 6, 8], [4, 6, 8]]), dict(dyn_shapes=[[4, 6, 8], [4, 6, 8]], const_shapes=[]), dict(dyn_shapes=[[4, 6, 8], [4, 6, 8]], const_shapes=[[4, 6, 8]]), dict(dyn_shapes=[[4, 6, 8], [4, 6, 8]], const_shapes=[[4, 6, 8], [4, 6, 8]]), dict(dyn_shapes=[[4, 6, 8], [4, 6, 8]], const_shapes=[[4, 6, 8], [4, 6, 8], [4, 6, 8]]), dict(dyn_shapes=[[4, 6, 8], [4, 6, 8], [4, 6, 8]], const_shapes=[]), dict(dyn_shapes=[[4, 6, 8], [4, 6, 8], [4, 6, 8]], const_shapes=[[4, 6, 8]]), dict(dyn_shapes=[[4, 6, 8], [4, 6, 8], [4, 6, 8]], const_shapes=[[4, 6, 8], [4, 6, 8]]), dict(dyn_shapes=[[4, 6, 8], [4, 6, 8], [4, 6, 8]], const_shapes=[[4, 6, 8], [4, 6, 8], [4, 6, 8]]), dict(dyn_shapes=[[4, 6, 8, 10]], const_shapes=[[4, 6, 8, 10]]), dict(dyn_shapes=[[4, 6, 8, 10]], const_shapes=[[4, 6, 8, 10], [4, 6, 8, 10]]), dict(dyn_shapes=[[4, 6, 8, 10]], const_shapes=[[4, 6, 8, 10], [4, 6, 8, 10], [4, 6, 8, 10]]), dict(dyn_shapes=[[4, 6, 8, 10], [4, 6, 8, 10]], const_shapes=[]), dict(dyn_shapes=[[4, 6, 8, 10], [4, 6, 8, 10]], const_shapes=[[4, 6, 8, 10]]), dict(dyn_shapes=[[4, 6, 8, 10], [4, 6, 8, 10]], const_shapes=[[4, 6, 8, 10], [4, 6, 8, 10]]), dict(dyn_shapes=[[4, 6, 8, 10], [4, 6, 8, 10]], const_shapes=[[4, 6, 8, 10], [4, 6, 8, 10], [4, 6, 8, 10]]), dict(dyn_shapes=[[4, 6, 8, 10], [4, 6, 8, 10], [4, 6, 8, 10]], const_shapes=[]), dict(dyn_shapes=[[4, 6, 8, 10], [4, 6, 8, 10], [4, 6, 8, 10]], const_shapes=[[4, 6, 8, 10]]), dict(dyn_shapes=[[4, 6, 8, 10], [4, 6, 8, 10], [4, 6, 8, 10]], const_shapes=[[4, 6, 8, 10], [4, 6, 8, 10]]), dict(dyn_shapes=[[4, 6, 8, 10], [4, 6, 8, 10], [4, 6, 8, 10]], const_shapes=[[4, 6, 8, 10], [4, 6, 8, 10], [4, 6, 8, 10]]), dict(dyn_shapes=[[4, 6, 8, 10, 12]], const_shapes=[[4, 6, 8, 10, 12]]), dict(dyn_shapes=[[4, 6, 8, 10, 12]], const_shapes=[[4, 6, 8, 10, 12], [4, 6, 8, 10, 12]]), dict(dyn_shapes=[[4, 6, 8, 10, 12]], const_shapes=[[4, 6, 8, 10, 12], [4, 6, 8, 10, 12], [4, 6, 8, 10, 12]]), dict(dyn_shapes=[[4, 6, 8, 10, 12], [4, 6, 8, 10, 12]], const_shapes=[]), dict(dyn_shapes=[[4, 6, 8, 10, 12], [4, 6, 8, 10, 12]], const_shapes=[[4, 6, 8, 10, 12]]), dict(dyn_shapes=[[4, 6, 8, 10, 12], [4, 6, 8, 10, 12]], const_shapes=[[4, 6, 8, 10, 12], [4, 6, 8, 10, 12]]), dict(dyn_shapes=[[4, 6, 8, 10, 12], [4, 6, 8, 10, 12]], const_shapes=[[4, 6, 8, 10, 12], [4, 6, 8, 10, 12], [4, 6, 8, 10, 12]]), dict(dyn_shapes=[[4, 6, 8, 10, 12], [4, 6, 8, 10, 12], [4, 6, 8, 10, 12]], const_shapes=[]), dict(dyn_shapes=[[4, 6, 8, 10, 12], [4, 6, 8, 10, 12], [4, 6, 8, 10, 12]], const_shapes=[[4, 6, 8, 10, 12]]), dict(dyn_shapes=[[4, 6, 8, 10, 12], [4, 6, 8, 10, 12], [4, 6, 8, 10, 12]], const_shapes=[[4, 6, 8, 10, 12], [4, 6, 8, 10, 12]]), dict(dyn_shapes=[[4, 6, 8, 10, 12], [4, 6, 8, 10, 12], [4, 6, 8, 10, 12]], const_shapes=[[4, 6, 8, 10, 12], [4, 6, 8, 10, 12], [4, 6, 8, 10, 12]])] const_test_data_precommit = [ dict(const_shapes=[[4, 6, 8, 10], [4, 6, 8, 10], [4, 6, 8, 10]]), dict(const_shapes=[[4, 6, 8, 10, 12], [4, 6, 8, 10, 12], [4, 6, 8, 10, 12], [4, 6, 8, 10, 12]]) ] const_test_data = [ dict(const_shapes=[[4, 6], [4, 6]]), dict(const_shapes=[[4, 6], [4, 6], [4, 6]]), dict(const_shapes=[[4, 6], [4, 6], [4, 6], [4, 6]]), dict(const_shapes=[[4, 6, 8], [4, 6, 8]]), dict(const_shapes=[[4, 6, 8], [4, 6, 8], [4, 6, 8]]), dict(const_shapes=[[4, 6, 8], [4, 6, 8], [4, 6, 8], [4, 6, 8]]), dict(const_shapes=[[4, 6, 8, 10], [4, 6, 8, 10]]), dict(const_shapes=[[4, 6, 8, 10], [4, 6, 8, 10], [4, 6, 8, 10]]), dict(const_shapes=[[4, 6, 8, 10], [4, 6, 8, 10], [4, 6, 8, 10], [4, 6, 8, 10]]), dict(const_shapes=[[4, 6, 8, 10, 12], [4, 6, 8, 10, 12]]), dict(const_shapes=[[4, 6, 8, 10, 12], [4, 6, 8, 10, 12], [4, 6, 8, 10, 12]]), dict(const_shapes=[[4, 6, 8, 10, 12], [4, 6, 8, 10, 12], [4, 6, 8, 10, 12], [4, 6, 8, 10, 12]]) ] const_test_data_broadcasting_precommit = [ dict(const_shapes=[[4, 6, 8, 10], [10], [10], [10]]), dict(const_shapes=[[4, 6, 8, 10, 12], [4, 6, 8, 10, 12], [12]]), dict(const_shapes=[[4, 6, 8, 10, 12], [4, 6, 8, 10, 12], [4, 6, 8, 10, 12], [12]]) ] const_test_data_broadcasting = [ dict(const_shapes=[[4, 6], [6]]), dict(const_shapes=[[4, 6], [6], [6]]), dict(const_shapes=[[4, 6], [4, 6], [6]]), dict(const_shapes=[[4, 6], [6], [6], [6]]), dict(const_shapes=[[4, 6], [4, 6], [6], [6]]), dict(const_shapes=[[4, 6], [4, 6], [4, 6], [6]]), dict(const_shapes=[[4, 6, 8], [8]]), dict(const_shapes=[[4, 6, 8], [8], [8]]), dict(const_shapes=[[4, 6, 8], [4, 6, 8], [8]]), dict(const_shapes=[[4, 6, 8], [8], [8], [8]]), dict(const_shapes=[[4, 6, 8], [4, 6, 8], [8], [8]]), dict(const_shapes=[[4, 6, 8], [4, 6, 8], [4, 6, 8], [8]]), dict(const_shapes=[[4, 6, 8, 10], [10]]), dict(const_shapes=[[4, 6, 8, 10], [10], [10]]), dict(const_shapes=[[4, 6, 8, 10], [4, 6, 8, 10], [10]]), dict(const_shapes=[[4, 6, 8, 10], [10], [10], [10]]), dict(const_shapes=[[4, 6, 8, 10], [4, 6, 8, 10], [10], [10]]), dict(const_shapes=[[4, 6, 8, 10], [4, 6, 8, 10], [4, 6, 8, 10], [10]]), dict(const_shapes=[[4, 6, 8, 10, 12], [12]]), dict(const_shapes=[[4, 6, 8, 10, 12], [12], [12]]), dict(const_shapes=[[4, 6, 8, 10, 12], [4, 6, 8, 10, 12], [12]]), dict(const_shapes=[[4, 6, 8, 10, 12], [12], [12], [12]]), dict(const_shapes=[[4, 6, 8, 10, 12], [4, 6, 8, 10, 12], [12], [12]]), dict(const_shapes=[[4, 6, 8, 10, 12], [4, 6, 8, 10, 12], [4, 6, 8, 10, 12], [12]]) ] @pytest.mark.parametrize("params", test_data) @pytest.mark.nightly def test_sum_opset6(self, params, ie_device, precision, ir_version, temp_dir): self._test(*self.create_net(**params, precision=precision, opset=6, ir_version=ir_version), ie_device, precision, ir_version, temp_dir=temp_dir) @pytest.mark.parametrize("params", test_data_precommit) @pytest.mark.precommit def test_sum_precommit(self, params, ie_device, precision, ir_version, temp_dir): self._test(*self.create_net(**params, precision=precision, ir_version=ir_version), ie_device, precision, ir_version, temp_dir=temp_dir) @pytest.mark.parametrize("params", test_data) @pytest.mark.nightly def test_sum(self, params, ie_device, precision, ir_version, temp_dir): self._test( *self.create_net(**params, precision=precision, ir_version=ir_version), ie_device, precision, ir_version, temp_dir=temp_dir) @pytest.mark.parametrize("params", const_test_data) @pytest.mark.nightly def test_sum_const_opset6(self, params, ie_device, precision, ir_version, temp_dir): self._test(*self.create_const_net(**params, opset=6, ir_version=ir_version), ie_device, precision, ir_version, temp_dir=temp_dir) @pytest.mark.parametrize("params", const_test_data_precommit) @pytest.mark.precommit def test_sum_const_precommit(self, params, ie_device, precision, ir_version, temp_dir): self._test(*self.create_const_net(**params, ir_version=ir_version), ie_device, precision, ir_version, temp_dir=temp_dir) @pytest.mark.parametrize("params", const_test_data) @pytest.mark.nightly def test_sum_const(self, params, ie_device, precision, ir_version, temp_dir): self._test(*self.create_const_net(**params, ir_version=ir_version), ie_device, precision, ir_version, temp_dir=temp_dir) @pytest.mark.parametrize("params", const_test_data_broadcasting_precommit) @pytest.mark.precommit def test_sum_const_broadcasting_precommit(self, params, ie_device, precision, ir_version, temp_dir): self._test(*self.create_const_net(**params, ir_version=ir_version), ie_device, precision, ir_version, temp_dir=temp_dir) @pytest.mark.parametrize("params", const_test_data_broadcasting) @pytest.mark.nightly def test_sum_const_broadcasting(self, params, ie_device, precision, ir_version, temp_dir): self._test(*self.create_const_net(**params, ir_version=ir_version), ie_device, precision, ir_version, temp_dir=temp_dir)
[ "onnx.helper.make_graph", "onnx.helper.make_node", "onnx.helper.make_tensor_value_info", "onnx.helper.make_model", "pytest.mark.parametrize", "numpy.random.randint", "onnx.helper.make_opsetid" ]
[((12278, 12322), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""params"""', 'test_data'], {}), "('params', test_data)\n", (12301, 12322), False, 'import pytest\n'), ((12609, 12663), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""params"""', 'test_data_precommit'], {}), "('params', test_data_precommit)\n", (12632, 12663), False, 'import pytest\n'), ((12946, 12990), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""params"""', 'test_data'], {}), "('params', test_data)\n", (12969, 12990), False, 'import pytest\n'), ((13267, 13317), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""params"""', 'const_test_data'], {}), "('params', const_test_data)\n", (13290, 13317), False, 'import pytest\n'), ((13595, 13655), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""params"""', 'const_test_data_precommit'], {}), "('params', const_test_data_precommit)\n", (13618, 13655), False, 'import pytest\n'), ((13929, 13979), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""params"""', 'const_test_data'], {}), "('params', const_test_data)\n", (13952, 13979), False, 'import pytest\n'), ((14241, 14314), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""params"""', 'const_test_data_broadcasting_precommit'], {}), "('params', const_test_data_broadcasting_precommit)\n", (14264, 14314), False, 'import pytest\n'), ((14601, 14664), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""params"""', 'const_test_data_broadcasting'], {}), "('params', const_test_data_broadcasting)\n", (14624, 14664), False, 'import pytest\n'), ((1031, 1103), 'onnx.helper.make_tensor_value_info', 'helper.make_tensor_value_info', (['"""output"""', 'TensorProto.FLOAT', 'output_shape'], {}), "('output', TensorProto.FLOAT, output_shape)\n", (1060, 1103), False, 'from onnx import helper\n'), ((1975, 2031), 'onnx.helper.make_graph', 'helper.make_graph', (['nodes', '"""test_model"""', 'inputs', '[output]'], {}), "(nodes, 'test_model', inputs, [output])\n", (1992, 2031), False, 'from onnx import helper\n'), ((2286, 2322), 'onnx.helper.make_model', 'helper.make_model', (['graph_def'], {}), '(graph_def, **args)\n', (2303, 2322), False, 'from onnx import helper\n'), ((3136, 3206), 'onnx.helper.make_tensor_value_info', 'helper.make_tensor_value_info', (['"""input"""', 'TensorProto.FLOAT', 'input_shape'], {}), "('input', TensorProto.FLOAT, input_shape)\n", (3165, 3206), False, 'from onnx import helper\n'), ((3224, 3296), 'onnx.helper.make_tensor_value_info', 'helper.make_tensor_value_info', (['"""output"""', 'TensorProto.FLOAT', 'output_shape'], {}), "('output', TensorProto.FLOAT, output_shape)\n", (3253, 3296), False, 'from onnx import helper\n'), ((4365, 4422), 'onnx.helper.make_graph', 'helper.make_graph', (['nodes', '"""test_model"""', '[input]', '[output]'], {}), "(nodes, 'test_model', [input], [output])\n", (4382, 4422), False, 'from onnx import helper\n'), ((4677, 4713), 'onnx.helper.make_model', 'helper.make_model', (['graph_def'], {}), '(graph_def, **args)\n', (4694, 4713), False, 'from onnx import helper\n'), ((1803, 1866), 'onnx.helper.make_node', 'helper.make_node', (['"""Sum"""'], {'inputs': 'input_names', 'outputs': "['output']"}), "('Sum', inputs=input_names, outputs=['output'])\n", (1819, 1866), False, 'from onnx import helper\n'), ((4025, 4085), 'onnx.helper.make_node', 'helper.make_node', (['"""Sum"""'], {'inputs': 'input_names', 'outputs': "['sum']"}), "('Sum', inputs=input_names, outputs=['sum'])\n", (4041, 4085), False, 'from onnx import helper\n'), ((4155, 4248), 'onnx.helper.make_node', 'helper.make_node', (['"""Concat"""'], {'inputs': "['input', 'sum']", 'outputs': "['output']", 'axis': 'concat_axis'}), "('Concat', inputs=['input', 'sum'], outputs=['output'],\n axis=concat_axis)\n", (4171, 4248), False, 'from onnx import helper\n'), ((779, 846), 'onnx.helper.make_tensor_value_info', 'helper.make_tensor_value_info', (['input_name', 'TensorProto.FLOAT', 'shape'], {}), '(input_name, TensorProto.FLOAT, shape)\n', (808, 846), False, 'from onnx import helper\n'), ((2235, 2265), 'onnx.helper.make_opsetid', 'helper.make_opsetid', (['""""""', 'opset'], {}), "('', opset)\n", (2254, 2265), False, 'from onnx import helper\n'), ((4626, 4656), 'onnx.helper.make_opsetid', 'helper.make_opsetid', (['""""""', 'opset'], {}), "('', opset)\n", (4645, 4656), False, 'from onnx import helper\n'), ((1221, 1256), 'numpy.random.randint', 'np.random.randint', (['(-127)', '(127)', 'shape'], {}), '(-127, 127, shape)\n', (1238, 1256), True, 'import numpy as np\n'), ((3443, 3478), 'numpy.random.randint', 'np.random.randint', (['(-127)', '(127)', 'shape'], {}), '(-127, 127, shape)\n', (3460, 3478), True, 'import numpy as np\n')]
from __future__ import print_function import numpy as np import tensorflow as tf from edward.stats import multinomial from scipy.special import gammaln sess = tf.Session() def multinomial_logpmf(x, n, p): """ Arguments ---------- x: np.array vector of length K, where x[i] is the number of outcomes in the ith bucket n: int number of outcomes equal to sum x[i] p: np.array vector of probabilities summing to 1 """ return gammaln(n + 1.0) - \ np.sum(gammaln(x + 1.0)) + \ np.sum(x * np.log(p)) def _assert_eq(val_ed, val_true): with sess.as_default(): # NOTE: since Tensorflow has no special functions, the values here are # only an approximation assert np.allclose(val_ed.eval(), val_true, atol=1e-4) def _test_logpdf(x, n, p): xtf = tf.constant(x) val_true = multinomial_logpmf(x, n, p) _assert_eq(multinomial.logpmf(xtf, n, p), val_true) _assert_eq(multinomial.logpmf(xtf, n, tf.constant(p, dtype=tf.float32)), val_true) _assert_eq(multinomial.logpmf(xtf, n, p), val_true) _assert_eq(multinomial.logpmf(xtf, n, tf.constant(p, dtype=tf.float32)), val_true) def test_logpdf_int_1d(): _test_logpdf(np.array([0, 1]), 1, np.array([0.5, 0.5])) _test_logpdf(np.array([1, 0]), 1, np.array([0.75, 0.25])) def test_logpdf_float_1d(): _test_logpdf(np.array([0.0, 1.0]), 1, np.array([0.5, 0.5])) _test_logpdf(np.array([1.0, 0.0]), 1, np.array([0.75, 0.25]))
[ "tensorflow.Session", "numpy.log", "numpy.array", "edward.stats.multinomial.logpmf", "tensorflow.constant", "scipy.special.gammaln" ]
[((161, 173), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (171, 173), True, 'import tensorflow as tf\n'), ((857, 871), 'tensorflow.constant', 'tf.constant', (['x'], {}), '(x)\n', (868, 871), True, 'import tensorflow as tf\n'), ((930, 959), 'edward.stats.multinomial.logpmf', 'multinomial.logpmf', (['xtf', 'n', 'p'], {}), '(xtf, n, p)\n', (948, 959), False, 'from edward.stats import multinomial\n'), ((1103, 1132), 'edward.stats.multinomial.logpmf', 'multinomial.logpmf', (['xtf', 'n', 'p'], {}), '(xtf, n, p)\n', (1121, 1132), False, 'from edward.stats import multinomial\n'), ((1305, 1321), 'numpy.array', 'np.array', (['[0, 1]'], {}), '([0, 1])\n', (1313, 1321), True, 'import numpy as np\n'), ((1326, 1346), 'numpy.array', 'np.array', (['[0.5, 0.5]'], {}), '([0.5, 0.5])\n', (1334, 1346), True, 'import numpy as np\n'), ((1365, 1381), 'numpy.array', 'np.array', (['[1, 0]'], {}), '([1, 0])\n', (1373, 1381), True, 'import numpy as np\n'), ((1386, 1408), 'numpy.array', 'np.array', (['[0.75, 0.25]'], {}), '([0.75, 0.25])\n', (1394, 1408), True, 'import numpy as np\n'), ((1456, 1476), 'numpy.array', 'np.array', (['[0.0, 1.0]'], {}), '([0.0, 1.0])\n', (1464, 1476), True, 'import numpy as np\n'), ((1481, 1501), 'numpy.array', 'np.array', (['[0.5, 0.5]'], {}), '([0.5, 0.5])\n', (1489, 1501), True, 'import numpy as np\n'), ((1520, 1540), 'numpy.array', 'np.array', (['[1.0, 0.0]'], {}), '([1.0, 0.0])\n', (1528, 1540), True, 'import numpy as np\n'), ((1545, 1567), 'numpy.array', 'np.array', (['[0.75, 0.25]'], {}), '([0.75, 0.25])\n', (1553, 1567), True, 'import numpy as np\n'), ((488, 504), 'scipy.special.gammaln', 'gammaln', (['(n + 1.0)'], {}), '(n + 1.0)\n', (495, 504), False, 'from scipy.special import gammaln\n'), ((1028, 1060), 'tensorflow.constant', 'tf.constant', (['p'], {'dtype': 'tf.float32'}), '(p, dtype=tf.float32)\n', (1039, 1060), True, 'import tensorflow as tf\n'), ((1201, 1233), 'tensorflow.constant', 'tf.constant', (['p'], {'dtype': 'tf.float32'}), '(p, dtype=tf.float32)\n', (1212, 1233), True, 'import tensorflow as tf\n'), ((527, 543), 'scipy.special.gammaln', 'gammaln', (['(x + 1.0)'], {}), '(x + 1.0)\n', (534, 543), False, 'from scipy.special import gammaln\n'), ((571, 580), 'numpy.log', 'np.log', (['p'], {}), '(p)\n', (577, 580), True, 'import numpy as np\n')]
__all__ = ["CorruptedMNIST", "dataloaders"] from pathlib import Path import numpy as np import torch from dotenv import find_dotenv from torch.utils.data import DataLoader, Dataset def _find_data_path(): return Path(find_dotenv(), "..", "data", "processed") class CorruptedMNIST(Dataset): def __init__(self, mode="train") -> None: super().__init__() parent_path = _find_data_path() images, labels = [], [] for path in parent_path.glob(f"{mode}*.npz"): npz = np.load(path) images.append(npz["images"]) labels.append(npz["labels"]) self.images = np.concatenate(images) self.labels = np.concatenate(labels) def __len__(self): return self.images.shape[0] def __getitem__(self, idx): image = torch.Tensor(self.images[idx, np.newaxis]) label = torch.LongTensor(self.labels[[idx]]) return image, label def dataloaders(batch_size=64): train_dataloader = DataLoader(CorruptedMNIST(), batch_size=batch_size, shuffle=True) test_dataloader = DataLoader(CorruptedMNIST("test"), batch_size=batch_size) return train_dataloader, test_dataloader
[ "dotenv.find_dotenv", "torch.LongTensor", "torch.Tensor", "numpy.concatenate", "numpy.load" ]
[((224, 237), 'dotenv.find_dotenv', 'find_dotenv', ([], {}), '()\n', (235, 237), False, 'from dotenv import find_dotenv\n'), ((634, 656), 'numpy.concatenate', 'np.concatenate', (['images'], {}), '(images)\n', (648, 656), True, 'import numpy as np\n'), ((679, 701), 'numpy.concatenate', 'np.concatenate', (['labels'], {}), '(labels)\n', (693, 701), True, 'import numpy as np\n'), ((811, 853), 'torch.Tensor', 'torch.Tensor', (['self.images[idx, np.newaxis]'], {}), '(self.images[idx, np.newaxis])\n', (823, 853), False, 'import torch\n'), ((870, 906), 'torch.LongTensor', 'torch.LongTensor', (['self.labels[[idx]]'], {}), '(self.labels[[idx]])\n', (886, 906), False, 'import torch\n'), ((516, 529), 'numpy.load', 'np.load', (['path'], {}), '(path)\n', (523, 529), True, 'import numpy as np\n')]
""" After training with p1_training_inverse_model.py, run this for p1 Then run p1_make_vids.py to generate the videos """ import torch import logging import torch.nn as nn from dataset import ObjPushDataset from model_learners import InverseModel from torch.utils.data import Dataset, DataLoader from push_env import PushingEnv import numpy as np import pandas as pd device = "cuda" if torch.cuda.is_available() else "cpu" logger = logging.getLogger(__name__) logging.basicConfig() logger.setLevel(logging.INFO) ##### HYPERPARAMETERS ###### start_state_dims = 2 next_state_dims = 2 action_dims = 4 nn_layer_1_size = 64 nn_layer_2_size = 32 criterion = nn.MSELoss() lr = 8e-4 seed = 0 num_epochs = 140 bsize = 512 num_pushes = 10 ############################ def main(): logger.info("Instantiating model and importing weights") # instantiate forward model and import pretrained weights inv_model = InverseModel(start_state_dims=start_state_dims, next_state_dims=next_state_dims, action_dims=action_dims, latent_var_1=nn_layer_1_size, latent_var_2=nn_layer_2_size, criterion=criterion, lr=lr, seed=seed) inv_model.load_state_dict(torch.load("invmodel_learned_params.pt")) # Load in data logger.info("Importing test data") test_dir = 'push_dataset/test' # only want 1 push each time, so set batch_size to 1 test_loader = DataLoader(ObjPushDataset(test_dir), batch_size=1, shuffle=True) env = PushingEnv() errors = [] true_pushes = [] pred_pushes = [] logger.info("Running loop") for i, (start_state, goal_state, true_action) in enumerate(test_loader): logger.info(f'Iteration #{i}') # Convert inputs to floats start_state = start_state.float() goal_state = goal_state.float() true_action = true_action.float() # Use inverse model to predict action given the start and goal states combined_input = torch.cat((start_state, goal_state), dim=1) pred_action = inv_model(combined_input) # Switch output from tensors to numpy for easy use later start_state = start_state.data.numpy()[0] goal_state = goal_state.data.numpy()[0] true_action = true_action.data.numpy()[0] pred_action = pred_action.data.numpy()[0] start_x, start_y, end_x, end_y = pred_action _, end_state = env.execute_push(start_x, start_y, end_x, end_y) end_state = np.array(end_state) # Calculate errors action_error = np.linalg.norm(true_action - pred_action) state_error = np.linalg.norm(goal_state - end_state) # Keep the results errors.append(dict(action_error=action_error, state_error=state_error)) true_pushes.append(dict(obj_x=start_state[0], obj_y=start_state[1], start_push_x=true_action[0], start_push_y=true_action[1], end_push_x=true_action[2], end_push_y=true_action[3])) pred_pushes.append(dict(obj_x=start_state[0], obj_y=start_state[1], start_push_x=pred_action[0], start_push_y=pred_action[1], end_push_x=pred_action[2], end_push_y=pred_action[3])) if i > num_pushes - 1: break pd.DataFrame(errors).to_csv("results/P1/inverse_model_errors.csv") pd.DataFrame(true_pushes).to_csv("results/P1/true_pushes.csv") pd.DataFrame(pred_pushes).to_csv("results/P1/pred_pushes.csv") if __name__ == '__main__': main()
[ "logging.getLogger", "logging.basicConfig", "torch.load", "push_env.PushingEnv", "numpy.linalg.norm", "dataset.ObjPushDataset", "torch.nn.MSELoss", "numpy.array", "torch.cuda.is_available", "model_learners.InverseModel", "pandas.DataFrame", "torch.cat" ]
[((434, 461), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (451, 461), False, 'import logging\n'), ((462, 483), 'logging.basicConfig', 'logging.basicConfig', ([], {}), '()\n', (481, 483), False, 'import logging\n'), ((655, 667), 'torch.nn.MSELoss', 'nn.MSELoss', ([], {}), '()\n', (665, 667), True, 'import torch.nn as nn\n'), ((388, 413), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (411, 413), False, 'import torch\n'), ((917, 1130), 'model_learners.InverseModel', 'InverseModel', ([], {'start_state_dims': 'start_state_dims', 'next_state_dims': 'next_state_dims', 'action_dims': 'action_dims', 'latent_var_1': 'nn_layer_1_size', 'latent_var_2': 'nn_layer_2_size', 'criterion': 'criterion', 'lr': 'lr', 'seed': 'seed'}), '(start_state_dims=start_state_dims, next_state_dims=\n next_state_dims, action_dims=action_dims, latent_var_1=nn_layer_1_size,\n latent_var_2=nn_layer_2_size, criterion=criterion, lr=lr, seed=seed)\n', (929, 1130), False, 'from model_learners import InverseModel\n'), ((1643, 1655), 'push_env.PushingEnv', 'PushingEnv', ([], {}), '()\n', (1653, 1655), False, 'from push_env import PushingEnv\n'), ((1356, 1396), 'torch.load', 'torch.load', (['"""invmodel_learned_params.pt"""'], {}), "('invmodel_learned_params.pt')\n", (1366, 1396), False, 'import torch\n'), ((1578, 1602), 'dataset.ObjPushDataset', 'ObjPushDataset', (['test_dir'], {}), '(test_dir)\n', (1592, 1602), False, 'from dataset import ObjPushDataset\n'), ((2127, 2170), 'torch.cat', 'torch.cat', (['(start_state, goal_state)'], {'dim': '(1)'}), '((start_state, goal_state), dim=1)\n', (2136, 2170), False, 'import torch\n'), ((2629, 2648), 'numpy.array', 'np.array', (['end_state'], {}), '(end_state)\n', (2637, 2648), True, 'import numpy as np\n'), ((2700, 2741), 'numpy.linalg.norm', 'np.linalg.norm', (['(true_action - pred_action)'], {}), '(true_action - pred_action)\n', (2714, 2741), True, 'import numpy as np\n'), ((2764, 2802), 'numpy.linalg.norm', 'np.linalg.norm', (['(goal_state - end_state)'], {}), '(goal_state - end_state)\n', (2778, 2802), True, 'import numpy as np\n'), ((3412, 3432), 'pandas.DataFrame', 'pd.DataFrame', (['errors'], {}), '(errors)\n', (3424, 3432), True, 'import pandas as pd\n'), ((3487, 3512), 'pandas.DataFrame', 'pd.DataFrame', (['true_pushes'], {}), '(true_pushes)\n', (3499, 3512), True, 'import pandas as pd\n'), ((3558, 3583), 'pandas.DataFrame', 'pd.DataFrame', (['pred_pushes'], {}), '(pred_pushes)\n', (3570, 3583), True, 'import pandas as pd\n')]
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2018 <NAME> <<EMAIL>> # # Distributed under terms of the MIT license. """ trajOptMultiPhaseCollocationProblem.py This class implements methods for solving problem with multiple phases. I will also change code style to suppress those warnings. """ from __future__ import division import numpy as np from .trajOptBase import LinearPointObj as linearPointObj from .trajOptBase import LinearPointConstr as linearPointConstr from .trajOptBase import NonLinearPointObj as nonLinearPointObj, NonLinearObj as nonLinearObj from .trajOptBase import NonLinearPointConstr as nonLinearPointConstr, NonLinearConstr as nonLinearConstr from .trajOptBase import AddX as addX from pyoptsolver import OptProblem, OptResult as result from .utility import random_gen_in_bound as randomGenInBound from scipy.sparse import coo_matrix, csr_matrix from .trajOptCollocationProblem import TrajOptCollocProblem class NonLinearConnectConstr(object): """Class for defining point constraint function. :currentmodule: .. automethod:: __callg__ .. exclude-members:: find_time_gradient """ def __init__(self, phase1, phase2, nc, lb=None, ub=None, nG=None, index1=-1, index2=0, addx_index=None): """Constructor for nonlinear point constraint. Also serve as path constraint. :param phase1/phase2: int, phase number that constraint is imposed. We read data from them :param nc: int, dimension of constraint function :param lb, ub: lower and upper bound of the constraint function. None means equal to 0 :param nG: int, number of nnz of Jacobian :param index1/index2: int, by default we connect last point of phase 1 with first point of phase 2. However, we allow manual assignment of them. :param addx_index: int, which additional x we use to connect those two phases """ self.phases = (phase1, phase2) self.indexes = (index1, index2) self.nf = nc self.nG = nG self.human = False # if we call __callhumang__ instead of __callg__ self.autonomous = (False, False) self.timeindex = (None, None) self.addx_index = addx_index if lb is None: self.lb = np.zeros(self.nf) else: self.lb = lb if ub is None: self.ub = np.zeros(self.nf) else: self.ub = ub def __callg__(self, x1, x2, F, G, row, col, rec, needg, addx=None): """Call and evaluate the constraint function. x1 and x2 are points in phase 1 and phase 2. I return them together in G, row, col since it might be derived from sympy so thay are together. But, human derived formulas love the previous one better """ raise NotImplementedError def __callhumang__(self, x1, x2, needg, addx=None): """Call and evaluate the constraint function. x1 and x2 are points in phase 1 and phase 2. I return them together in G, row, col since it might be derived from sympy so thay are together. But, human derived formulas love the previous one better :param x1: ndarray, a (t, x, u, p) tuple from phase 1 :param x2: ndarray, a (t, x, u, p) tuple from phase 2 :param needg: if we return those G, too :param addx: additional parameters passed in :return F: where constraint functions are evaluated and stored :return G1, G2, G3: Jacobian of F w.r.t x1, x2, and optionally addx (G3 empty if addx is None) """ raise NotImplementedError def find_time_gradient(self, x1, x2, addx=None): """Find where the gradients are w.r.t time.""" if self.human: rvalue = self.__callhumang__(x1, x2, True, addx) if self.addxindex is None: F, G1, G2, = rvalue if self.nG is None: self.nG = G1.nnz + G2.nnz else: F, G1, G2, Ga = rvalue if self.nG is None: self.nG = G1.nnz + G2.nnz + Ga.nnz tindex1 = np.where(G1.col == 0)[0] tindex2 = np.where(G2.col == 0)[0] else: tmpy = np.zeros(self.nf) tmpG = np.zeros(self.nG) tmprow = np.zeros(self.nG, dtype=int) tmpcol = np.zeros(self.nG, dtype=int) self.__callg__(x1, x2, tmpy, tmpG, tmprow, tmpcol, True, True, addx) len1 = len(x1) tindex1 = np.where(tmpcol == 0)[0] tindex2 = np.where(tmpcol == len1)[0] auto1 = len(tindex1) == 0 auto2 = len(tindex2) == 0 self.timeindex = (tindex1, tindex2) self.autonomous = (auto1, auto2) if self.lb is None: self.lb = np.zeros(self.nf) if self.ub is None: self.ub = np.zeros(self.nf) class LinearConnectConstr(object): """Class for defining linear constraint functions. :currentmodule: .. exclude-members:: find_time_gradient """ def __init__(self, phase1, phase2, a1, a2, lb=None, ub=None, index1=-1, index2=0, adda=None, addx_index=None): """Constructor for linear point constraint. Also serve as path constraint. :param phase1/phase2: int, phase number that constraint is imposed. We read data from them :param a1/a2: ndarray, the constraint, :math: `l \le A_1 x_1 + A_2 x_2 \le u` :param lb/ub: lower and upper bound of the constraint function. None means equal to 0 :param index1/index2: int, by default we connect last point of phase 1 with first point of phase 2. However, we allow manual assignment of them. :param adda: ndarray, if additional parameter comes into play, we use this :param addx_index: int, index of the additional parameters """ self.phases = (phase1, phase2) self.indexes = (index1, index2) assert a1.shape[0] == a2.shape[0] self.a = (coo_matrix(a1), coo_matrix(a2)) # since everything is in pair self.nf = a1.shape[0] self.adda = coo_matrix(adda) self.addx_index = addx_index self.find_time_gradient() if lb is None: self.lb = np.zeros(self.nf) else: self.lb = lb if ub is None: self.ub = np.zeros(self.nf) else: self.ub = ub def find_time_gradient(self): """For a matrix, find column 0 indice.""" timeindex1 = np.where(self.a[0].col == 0)[0] auto1 = len(timeindex1) == 0 timeindex2 = np.where(self.a[1].col == 0)[0] auto2 = len(timeindex2) == 0 self.timeindex = (timeindex1, timeindex2) self.autonomous = (auto1, auto2) class TrajOptMultiPhaseCollocProblem(OptProblem): """A class for definition of trajectory optimization problem using collocation constraints with support for phase transition. The support of multiple phase is implemented by calling functions defined in trajOptCollocProblem since I do not want to reinvent the wheels. I can conveniently add support for other constraints that connects two phases. :currentmodule: .. exclude-members:: change_connect_time_constr_bound """ def __init__(self, probs, addx=None, process_args={}): """Initialize a multi-phase problem by a list of trajOptColloProblem objects. :param probs: a list of trajOptCollocProblem :param addx: a list of addX :param process_args: arguments for preprocess used in each problem """ assert isinstance(probs, list) for prob in probs: assert isinstance(prob, TrajOptCollocProblem) prob.pre_process(**process_args) self.__parseAddX(addx) self.phases = probs self.num_phase = len(probs) # additional constraints, linear or nonlinear self.connect_nonlinear_constr = [] # general nonlinear constraint functions self.connect_linear_constr = [] # can be used for time self.nonlinear_constr = [] # a general constraint function, do not use it until necessary self.addx_nonlinear_constr = [] # constraints on addx, this might be useful self.addx_linear_constr = [] # linear constraints on addx, this is cheap and not a big deal # additional objective functions on addx or general self.addx_nonlinear_obj = [] # cost function associated addx self.addx_linear_obj = [] # always extends functions that probably no one uses self.nonlinear_obj = [] # a general objective function on the whole x # data for determining size of the problem vec_num_sol = np.array([prob.nx for prob in self.phases]) self.accum_num_sol = np.insert(np.cumsum(vec_num_sol), 0, 0) vec_num_f = np.array([prob.nf - 1 for prob in self.phases]) # -1 to remove objf row self.accum_num_f = np.insert(np.cumsum(vec_num_f), 0, 0) self.sum_num_f = self.accum_num_f[-1] self.__add_connect_time_constr() def pre_process(self): """Initialize the instances of probFun now we are ready. Call this function after the objectives and constraints have been set appropriately. It calculate the space required for SNOPT and allocates sparsity structure if necessary. """ est_num_F = 1 + self.sum_num_f # without additional param for objective, this is # get additional constraints number linear_F = 0 nonlinear_F = 0 for constr in self.connect_linear_constr: est_num_F += constr.nf linear_F += constr.nf for constr in self.connect_nonlinear_constr: est_num_F += constr.nf nonlinear_F += constr.nf for constr in self.nonlinear_constr: est_num_F += constr.nf nonlinear_F += constr.nf for constr in self.addx_nonlinear_constr: est_num_F += constr.nf nonlinear_F += constr.nf for constr in self.addx_linear_constr: est_num_F += constr.nf linear_F += constr.nf est_num_sol = self.accum_num_sol[-1] + self.len_addX # see previous line OptProblem.__init__(self, est_num_F, est_num_sol) # we have to allocate A related variables self.__set_A_pattern(est_num_sol, est_num_F) # we can determine num_f and num_sol for this class self.num_f = est_num_F + self.num_aux_obj_var self.num_sol = est_num_sol + self.num_aux_obj_var self.num_linear_constr = linear_F self.num_nonlinear_constr = nonlinear_F self.nx = self.num_sol self.nf = self.num_f self.spA = csr_matrix((self.Aval, (self.Arow, self.Acol)), shape=(self.nf, self.nx)) self.spA_coo = self.spA.tocoo() # find number of G rdx = self.random_gen_x() nG = self.__find_num_G(rdx) # TODO: allow user not to give nG if given in human-mode? self.numG = nG self.nG = nG self.grad = True self.__set_x_bound() self.__set_f_bound() def random_gen_x(self): """Generate a random guess to the problem.""" randX = np.zeros(self.num_sol) for i, phase in enumerate(self.phases): piecex = self.__get_phase_sol_piece(randX, i) piecex[:] = phase.randomGenX() # randomly generate for addX if self.len_addX > 0: for field, addx in zip(self.__parseAddX__(randX), self.addX): field[:] = randomGenInBound([addx.lb, addx.ub], addx.n) # the num_aux_obj_var auxiliary variables need no effort return randX def guess_gen_from_phase_sol(self, phase_sols, addX=[]): """Generate an initial guess for the multi-phase problem by concatenating solutions from single phases. :param phase_sols: list of dict, a list of guess of solutions to each phase """ guess = np.zeros(self.num_sol) assert len(phase_sols) == len(self.phases) assert len(addX) == self.len_addX for i, phase in enumerate(self.phases): piecex = self.__get_phase_sol_piece(guess, i) piecex[:] = phase_sols[i] # assign addX if self.len_addX > 0: for field, addx in zip(self.__parseAddX__(guess), addX): field[:] = addx return guess def guess_gen_from_phase_traj(self, X=None, U=None, P=None, t0=None, tf=None, addx=None, tstamp=None, obj=None, addX=None, interp_kind='linear'): """Generate a guess from the trajectory in other phases. The parameters are the same with .. py:classmethod::`trajOptCollocation.genGuessFromTraj` but a list version. """ def _check_var(*args): """Check a variable. Return a list of None if necessary.""" narg = len(args) output = [] for x in args: if x is None: output.append([None] * self.num_phase) else: assert len(x) == self.num_phase output.append(x) if narg == 1: return output[0] else: return output X, U, P, t0, tf, addx, tstamp, obj = _check_var(X, U, P, t0, tf, addx, tstamp, obj) guess = np.zeros(self.num_sol) # for each phase, we generate a guess for i, phase in enumerate(self.phases): piecex = self.__get_phase_sol_piece(guess, i) piecex[:] = phase.genGuessFromTraj(X[i], U[i], P[i], t0[i], tf[i], addx[i], tstamp[i], obj[i]) # finally for addx as a whole problem if self.len_addX > 0: if addX is None: for field, addx_ in zip(self.__parseAddX__(guess), self.addX): field[:] = randomGenInBound([addx_.lb, addx_.ub], addx_.n) else: assert len(addX) == len(self.phases) for field, addx in zip(self.__parseAddX__(guess), addX): field[:] = addx return guess def __callg__(self, x, y, G, row, col, rec, needg): """Evaluate those constraints, objective functions, and constraints. It simultaneously allocates sparsity matrix. We do this in several parts: - for each phase, we call the private functions explicitly. Ugly hack - call the connection nonlinear constraints - call the nonlinear objective functions associated with addx :param x: ndarray, the solution to the problem :param y: ndarray, return F :param G, row, col: ndarray, information of gradient :param rec, needg: if we record / if we need gradient """ curRow = 1 curNg = 0 for phase_num, phase in enumerate(self.phases): xi = self.__get_phase_sol_piece(x, phase_num) h, useT = phase.__get_time_grid__(xi) useX, useU, useP = phase.__parseX__(xi) # loop over all system dynamics constraint Ng0 = curNg curRow, curNg = phase.__dynconstr_mode_g__(curRow, curNg, h, useT, useX, useU, useP, y, G, row, col, rec, needg) curRow, curNg = phase.__constr_mode_g__(curRow, curNg, h, useT, useX, useU, useP, x, y, G, row, col, rec, needg) y[curRow: curRow + phase.numLinCon] = 0 curRow += phase.numLinCon curRow, curNg = phase.__obj_mode_g__(curRow, curNg, h, useT, useX, useU, useP, x, y, G, row, col, rec, needg) col[Ng0: curNg] += self.accum_num_sol[phase_num] y[curRow: curRow + self.num_linear_constr] = 0 curRow += self.num_linear_constr # evaluate the nonlinear constraints curRow, curNg = self.__calc_nonlinear_constr(curRow, curNg, x, y, G, row, col, rec, needg) # evaluate additional nonlinear objective functions if self.num_aux_obj_var > 0: curRow, curNg = self.__calc_nonlinear_obj(curRow, curNg, x, y, G, row, col, rec, needg) else: y[0] = 0 # just to make sure return curRow, curNg # interface functions for ipopt def __cost__(self, x): """The eval_f function required by ipopt. :param x: a guess/solution of the problem :return f: float, objective function """ row0 = self.spA.getrow(0) return np.dot(row0.data, x[row0.indices]) def __gradient__(self, x, g): """Evaluation of the gradient of objective function. :param x: guess/solution to the problem :return grad: gradient of objective function w.r.t x """ g[:] = self.spA.getrow(0).toarray().flatten() return True def __constr__(self, x, y): """Evaluation of the constraint function. :param x: ndarray, guess/solution to the problem. :return g: constraint function """ G = np.zeros(1) row = np.zeros(1, dtype=int) col = np.zeros(1, dtype=int) self.__callg__(x, y, G, row, col, False, False) # y should plus A times x y += self.spA.dot(x) return 0 def __jacobian__(self, x, g, row, col, flag): """Evaluate jacobian of constraints. I simply call __callg__ :param x: ndarray, guess / solution to the problem :param flag: bool, True return row/col, False return values """ y = np.zeros(self.num_f) if flag: row = np.ones(self.nG + self.spA.nnz, dtype=int) col = np.ones(self.nG + self.spA.nnz, dtype=int) tmpx = self.randomGenX() self.__callg__(tmpx, y, g, row, col, True, True) # good news is there is no overlap of A and G row[self.nG:] = self.spA_coo.row col[self.nG:] = self.spA_coo.col return 0 else: row = np.ones(1, dtype=int) col = np.ones(1, dtype=int) self.__callg__(x, y, g, row, col, False, True) g[self.nG:] = self.spA_coo.data return 0 def parse_sol(self, sol): """Given a solution, we parse and return readable data structure. :param sol: ndarray or result object returned by SNOPT. :return traj: a dict of keys 't', 'x', 'u', 'p', 'phases'. - 't' is a concatenated time grid (might not be equidistant, but piecewise equidistant - 'x' ndarray, (\*, dimx) is the concatenated state vector of all phases - 'u' ndarray, (\*, dimu) is the concatenated control vector of all phases - 'p' ndarray, (\*, dimp) is the concatenated parameter vector of all phases - 'phases' list of dictionaries composed of keys 't', 'x', 'u', 'p', 'addx' where 'addx' is additional optimization variables. """ if isinstance(sol, np.ndarray): assert len(sol) == self.nx x = sol elif isinstance(sol, result): assert len(sol.sol) == self.nx x = sol.sol else: raise NotImplementedError traj = {'t': [], 'x': [], 'u': [], 'p': None} phases = [] # this is a list of parsed solution for phase_num, phase in enumerate(self.phases): soli = self.__get_phase_sol_piece(x, phase_num) rsti = phase.parse_sol(soli) phases.append(rsti) traj['t'].append(rsti['t']) traj['x'].append(rsti['x']) traj['u'].append(rsti['u']) if rsti['p'] is not None: if traj['p'] is None: traj['p'] = [rsti['p']] else: traj['p'].append(rsti['p']) # concatenate them and get solution for key in traj.keys(): if traj[key] is not None: traj[key] = np.concatenate(traj[key], axis=0) traj['phases'] = phases # parse addx if self.len_addX > 0: traj['addx'] = self.__parseAddX__(sol) return traj def parse_f(self, sol): """Use the solution and evaluate on all constraints. Check which are active and analyze why we are not converging. :param sol: ndarray, the solution we want to analyze """ assert len(sol) == self.num_sol rst = [] for phase_num, phase in enumerate(self.phases): piece = self.__get_phase_sol_piece(sol, phase_num) subrst = phase.parseF(piece) rst.append(subrst) # parse the rest of constraints, we do not care about linear ones y = np.zeros(self.num_nonlinear_constr) # evaluate the nonlinear constraints curRow = 0 curNg = 0 curRow, curNg = self.__calc_nonlinear_constr(curRow, curNg, sol, y, np.zeros(1), np.zeros(1), np.zeros(1), False, False) # evaluate additional nonlinear objective functions connect_nonlinear_constr = [] curRow = 0 for i, constr in enumerate(self.connect_nonlinear_constr): connect_nonlinear_constr.append((i, y[curRow: curRow + constr.nf])) curRow += constr.nf addx_nonlinear_constr = [] for i, constr in enumerate(self.addx_nonlinear_constr): addx_nonlinear_constr.append((i, y[curRow: curRow + constr.nf])) curRow += constr.nf nonlinear_constr = [] for i, constr in enumerate(self.nonlinear_constr): nonlinear_constr.append((i, y[curRow: curRow + constr.nf])) curRow += constr.nf # append those constraints evaluation dct = {'con_con': connect_nonlinear_constr, 'addx_con': addx_nonlinear_constr, 'nonlin_con': nonlinear_constr} # append parsed addx if self.len_addX > 0: for i, addx in enumerate(self.addX): dct['addx_%d' % i] = self.__get_addx_by_index(sol, i) rst.append(dct) return rst def add_obj(self, obj): """Add a objective function to the problem. :param obj: a general objective function object. """ if isinstance(obj, nonLinearObj): self.add_nonlinear_obj(obj) elif isinstance(obj, (nonLinearPointObj, linearPointObj)): self.add_addx_obj(obj) else: raise NotImplementedError def add_constr(self, constr): """Add a constraint to the problem. :param constr: a general constraint function object. """ if isinstance(constr, nonLinearObj): self.add_nonlinear_constr(constr) elif isinstance(constr, (nonLinearPointConstr, linearPointConstr)): self.add_addx_constr(constr) elif isinstance(constr, (LinearConnectConstr, NonLinearConnectConstr)): self.add_connect_constr(constr) else: raise NotImplementedError def add_connect_constr(self, constr): """Add a linear constraint that connects two phases. :param constr: a connect constraint object. """ if isinstance(constr, LinearConnectConstr): self.connect_linear_constr.append(constr) elif isinstance(constr, NonLinearConnectConstr): self.connect_nonlinear_constr.append(constr) else: raise NotImplementedError def add_connect_linear_constr(self, constr): """Add a linear connection constraint to the problem. :param constr: a LinearConnectConstr object. """ assert isinstance(constr, LinearConnectConstr) self.connect_linear_constr.append(constr) def add_connect_nonlinear_constr(self, constr): """Add a nonlinear connect constraint to the problem. :param constr: a NonLinearConnectConstr object. """ assert isinstance(constr, NonLinearConnectConstr) self.connect_nonlinear_constr.append(constr) def add_addx_constr(self, constr): """Add a linear or nonlinear constraint associated with addx. :param constr: a point constraint. """ if isinstance(constr, linearPointConstr): self.addx_linear_constr.append(constr) elif isinstance(constr, nonLinearPointConstr): self.addx_nonlinear_constr.append(constr) else: raise NotImplementedError def add_nonlinear_constr(self, constr): """Add a general nonlinear constraint to the problem. :param constr: a nonLinearConstr object. """ assert isinstance(constr, nonLinearConstr) self.nonlinear_constr.append(constr) def add_addx_obj(self, obj): """Add an objective evaluated at addx to the problem. :param obj: a point objective object """ if isinstance(obj, linearPointObj): self.addx_linear_obj.append(obj) if isinstance(obj, nonLinearPointObj): self.addx_nonlinear_obj.append(obj) else: raise NotImplementedError def add_nonlinear_obj(self, obj): """Add a nonlinear objective to the problem. :param obj: a nonLinearObj object. """ assert isinstance(obj, nonLinearObj) self.nonlinear_obj.append(obj) def change_connect_time_constr_bound(self, num, xl, xu): """Change the connect time constraint if other specification are required.""" assert isinstance(num, int) assert isinstance(xl, (int, float)) and isinstance(xu, (int, float)) if num >= len(self.phases): print('Possible range of num is 0 - %d' % (len(self.phases) - 1)) return if xl > xu: print('xl should be smaller than xu') return self.connect_linear_constr[num].lb[:] = xl self.connect_linear_constr[num].ub[:] = xu def __parseAddX(self, addx): """Parse addx""" if addx is None: self.len_addX = 0 else: if not isinstance(addx, list): addx = [addx] for tmp in addx: assert isinstance(tmp, addX) self.addX = addx vec_len_addX = [tmp.n for tmp in addx] self.len_addX = np.sum(vec_len_addX) # total length of addx self.accum_len_addX = np.insert(np.cumsum(vec_len_addX), 0, 0) def __parseAddX__(self, x): """Return a list of addX values.""" numTraj = self.__get_addx_leading_column(0) addX = [] for addx in self.addX: addX.append(x[numTraj: numTraj + addx.n]) numTraj += addx.n return addX def __get_leading_column(self, phase, index): """For the vector in phase at index, return column index of first element.""" if index >= 0: return self.accum_num_sol[phase] + index * self.phases[phase].dimpoint else: return self.accum_num_sol[phase] + (self.phases[phase].nPoint + index) * self.phases[phase].dimpoint def __get_t0_ind(self, phase): """Return the index of t0 for selected phase.""" return self.accum_num_sol[phase] + self.phases[phase].t0ind def __get_tf_ind(self, phase): """Return the index of t0 for selected phase.""" return self.accum_num_sol[phase] + self.phases[phase].tfind def __get_addx_leading_column(self, addxindex): """Return the column index of selected addx.""" return self.accum_len_addX[addxindex] + self.accum_num_sol[-1] def __get_phase_sol_piece(self, x, phase_num): """Return the long vector belonging to certain phase.""" return x[self.accum_num_sol[phase_num]: self.accum_num_sol[phase_num + 1]] def __get_phase_f_piece(self, f, phase_num): """Return the piece that collects constraint function in certain phases""" n1 = self.accum_num_f[phase_num] n2 = self.accum_num_f[phase_num + 1] return f[1 + n1: 1 + n2] def __get_addx_by_index(self, x, index): """Return the piece of addx.""" i0 = self.__get_addx_leading_column(index) return x[i0: i0 + self.addX[index].n] def __extract_func_arguments(self, x, constr): """Extract arguments for connect_nonlinear_constr""" phase1, phase2 = constr.phases index1, index2 = constr.indexes x1, x2 = self.__get_phase_sol_piece(x, phase1), self.__get_phase_sol_piece(x, phase2) h1, useT1 = self.phases[phase1].__get_time_grid__(x1) useX1, useU1, useP1 = self.phases[phase1].__parseX__(x1) h2, useT2 = self.phases[phase2].__get_time_grid__(x2) useX2, useU2, useP2 = self.phases[phase2].__parseX__(x2) if constr.addx_index is not None: n0 = self.__get_addx_leading_column(constr.addx_index) addx = x[n0: n0 + self.addX[constr.addx_index].n] else: addx = None x1 = np.concatenate(([[useT1[index1]], useX1[index1], useU1[index1], useP1[index1]])) x2 = np.concatenate(([[useT2[index2]], useX2[index2], useU2[index2], useP2[index2]])) return x1, x2, addx def __add_connect_time_constr(self): """Add linear constraints that limits t0 and tf of two connecting phases. This is done by automatically add connect linear constraints. It basically requires the continuity of time. """ num_phase = self.num_phase for i in range(num_phase - 1): a1 = np.ones(1) a2 = -a1 constr = LinearConnectConstr(i, i + 1, a1, a2, lb=np.zeros(1), ub=np.zeros(1)) self.add_connect_linear_constr(constr) def __set_x_bound(self): """Set xlb and xub for this new structure. Basically it copies and creates.""" xlb = -1e20 * np.ones(self.num_sol) xub = -xlb for phase_num, phase in enumerate(self.phases): tmplb = self.__get_phase_sol_piece(xlb, phase_num) tmpub = self.__get_phase_sol_piece(xub, phase_num) tmplb[:] = phase.xlb tmpub[:] = phase.xub # set bounds for addx cur_col = self.accum_num_sol[-1] if self.len_addX > 0: for addx in self.addX: if addx.lb is None: addx.lb = np.zeros(addx.n) if addx.ub is None: addx.ub = np.zeros(addx.n) xlb[cur_col: cur_col + addx.n] = addx.lb xub[cur_col: cur_col + addx.n] = addx.ub cur_col += addx.n # I do not care about auxiliary variables since they are unbounded self.xlb = xlb self.xub = xub def __set_f_bound(self): """Set lb and ub for constraint functions.""" lb = np.zeros(self.num_f) ub = np.zeros(self.num_f) lb[0] = -1e20 ub[0] = 1e20 # loop over all prob for phase_num, phase in enumerate(self.phases): tmplb = self.__get_phase_f_piece(lb, phase_num) tmpub = self.__get_phase_f_piece(ub, phase_num) tmplb[:] = phase.lb[1:] tmpub[:] = phase.ub[1:] # loop over linear constraints curRow = self.accum_num_f[-1] + 1 for constr in self.connect_linear_constr: lb[curRow: curRow + constr.nf] = constr.lb ub[curRow: curRow + constr.nf] = constr.ub curRow += constr.nf for constr in self.addx_linear_constr: # actually I can list + list for simplicity lb[curRow: curRow + constr.nf] = constr.lb ub[curRow: curRow + constr.nf] = constr.ub curRow += constr.nf # loop over nonlinear constraints for constr in self.connect_nonlinear_constr + self.addx_nonlinear_constr + self.nonlinear_constr: lb[curRow: curRow + constr.nf] = constr.lb ub[curRow: curRow + constr.nf] = constr.ub curRow += constr.nf # for auxiliary variables the bounds are zero so I am good self.lb = lb self.ub = ub def __set_A_pattern(self, est_num_F, est_num_sol): """Set the pattern of A. We do three things: - analyze the linear constraints, generate a list of sparse-like matrix - analyze the additional cost functions such as penalty on addX - change row/col of the Aval/Arow/Acol for each phase :param est_num_F: estimated number of F (including objective) with all constraints considered :param est_num_sol: estimated length of x (including addx) but without auxiliary ones """ # analyze the linear connect constraints lstA, lstArow, lstAcol = self.__analyze_linear_constr() lstA2, lstArow2, lstAcol2 = self.__analyze_cost_function(est_num_F, est_num_sol) lstA3, lstArow3, lstAcol3 = self.__analyze_existing_A() self.Aval = np.concatenate(lstA + lstA2 + lstA3) self.Arow = np.concatenate(lstArow + lstArow2 + lstArow3) self.Acol = np.concatenate(lstAcol + lstAcol2 + lstAcol3) def __analyze_linear_constr(self): """Detect the sparse A for linear constraints. returns lstA, lstArow, lstAcol: list of sparse matrix A from linear constraints. """ lstA = [] lstArow = [] lstAcol = [] curRow = 1 + self.sum_num_f def process_one_matrix(constr, auto1, phase1, index1, a1, tidx1, curRow): # for first constraint col1 = self.__get_leading_column(phase1, index1) if auto1: # actually this part can be merged lstA.append(a1.data) lstArow.append(curRow + a1.row) lstAcol.append(col1 + a1.col - 1) # note this -1, since our definition else: timemask = np.zeros(a1.nnz, dtype=bool) timemask[tidx1] = True statemask = np.logical_not(timemask) # whatever happens, state related are processed lstA.append(a1.data[statemask]) lstArow.append(a1.row[statemask] + curRow) lstAcol.append(col1 + a1.col[statemask] - 1) phase = self.phases[phase1] if index1 >= 0: t0factor = (phase.N - 1 - index1) / (phase.N - 1) tffactor = (index1) / (phase.N - 1) else: t0factor = (-index1 - 1) / (phase.N - 1) tffactor = (phase.N + index1) / (phase.N - 1) if phase.t0ind > 0: lstA.append(a1.data[timemask] * t0factor) lstArow.append(a1.row[timemask] + curRow) lstAcol.append(np.sum(timemask) * [self.__get_t0_ind(phase1)]) else: # we have constraints on it but it is fixed, we change lb and ub value = -t0factor * a1.data[timemask] * self.phases[phase1].t0 constr.lb[a1.row[tidx1]] += value constr.ub[a1.row[tidx1]] += value if phase.tfind > 0: lstA.append(a1.data[timemask] * tffactor) lstArow.append(a1.row[timemask] + curRow) lstAcol.append(np.sum(timemask) * [self.__get_tf_ind(phase1)]) else: value = -tffactor * a1.data[timemask] * self.phases[phase1].tf constr.lb[a1.row[tidx1]] += value constr.ub[a1.row[tidx1]] += value def process_adda_matrix(constr): if constr.addx_index is not None: lstA.append(constr.adda.data) lstArow.append(constr.adda.row + curRow) lstAcol.append(constr.adda.col + self.__get_addx_leading_column(constr.addx_index)) for constr in self.connect_linear_constr: # constr.find_time_gradient() phase1, phase2 = constr.phases index1, index2 = constr.indexes a1, a2 = constr.a tidx1, tidx2 = constr.timeindex auto1, auto2 = constr.autonomous process_one_matrix(constr, auto1, phase1, index1, a1, tidx1, curRow) process_one_matrix(constr, auto2, phase2, index2, a2, tidx2, curRow) process_adda_matrix(constr) curRow += constr.nf for constr in self.addx_linear_constr: lstA.append(constr.A.data) lstArow.append(constr.A.row + curRow) lstAcol.append(constr.A.col + self.__get_addx_leading_column(constr.index)) curRow += constr.nf return lstA, lstArow, lstAcol def __analyze_cost_function(self, est_num_F, est_num_sol): """Analyze the cost functions. It has two things to do""" lstA = [] lstArow = [] lstAcol = [] for phase_num, phase in enumerate(self.phases): col_index = phase.Acol[phase.Arow == 0] n_col_index = len(col_index) lstAcol.append(col_index + self.accum_num_sol[phase_num]) lstA.append(np.ones(n_col_index)) lstArow.append(np.zeros(n_col_index)) # append linear objectives to first row if len(self.addx_linear_constr) > 0: tmpA = np.zeros(self.len_addX) basecol = self.accum_num_sol[-1] for obj in self.addx_linear_obj: leadcol = np.__get_addx_leading_column(obj.index) tmpA[leadcol - basecol + obj.A.col] += obj.A.data tmpA_ = coo_matrix(tmpA) lstA.append(tmpA_.data) lstArow.append(np.zeros(tmpA_.nnz)) lstAcol.append(tmpA_.col + basecol) # check all nonlinear objectives on addx num_addx_obj = len(self.addx_nonlinear_obj) # this is the number of auxiliary variables num_non_linear_obj = len(self.nonlinear_obj) self.num_aux_obj_var = num_addx_obj + num_non_linear_obj # the upper right corner lstAcol.append(np.arange(num_addx_obj) + est_num_sol) lstArow.append(np.zeros(num_addx_obj)) lstA.append(np.ones(num_addx_obj)) # the bottom right corner lstAcol.append(np.arange(num_addx_obj) + est_num_sol) lstArow.append(est_num_F + np.arange(num_addx_obj)) lstA.append(-np.ones(num_addx_obj)) return lstA, lstArow, lstAcol def __analyze_existing_A(self): """Loop over all phases, change row indexes of them.""" lstA = [] lstArow = [] lstAcol = [] sumf = 1 # record how many f we have used for phase_num, phase in enumerate(self.phases): # find non-zero row number mask = phase.Arow > 0 lstA.append(phase.Aval[mask]) lstArow.append(phase.Arow[mask] - 1 + sumf) sumf += phase.numF - 1 lstAcol.append(phase.Acol[mask] + self.accum_num_sol[phase_num]) return lstA, lstArow, lstAcol def __find_num_G(self, x): """Find number of G for this huge problem.""" nG = 0 maxnG = 0 for phase in self.phases: nG += phase.nG for constr in self.connect_nonlinear_constr: nG += constr.nG maxnG = max(maxnG, constr.nG) x1, x2, addx = self.__extract_func_arguments(x, constr) constr.find_time_gradient(x1, x2, addx) n_time_related_0 = len(constr.timeindex[0]) n_time_related_1 = len(constr.timeindex[1]) nG += (self.phases[constr.phases[0]].numT - 1) * n_time_related_0 nG += (self.phases[constr.phases[1]].numT - 1) * n_time_related_1 for obj in self.addx_nonlinear_obj: nG += obj.nG maxnG = max(maxnG, obj.nG) self.maxnG = maxnG self.G = np.zeros(maxnG) self.row = np.zeros(maxnG, dtype=int) self.col = np.zeros(maxnG, dtype=int) return nG def __calc_nonlinear_obj(self, x, y, G, row, col, curRow, curNg, rec, needg): """Calculate the nonlinear functions. See :func:`trajOptMultiPhaseCollocationProblem.trajOptMultiPhaseCollocProblem.__calc_nonlinear_constr` """ tmpout = np.zeros(1) y[0] = 0 # since this row is purely linear curRow = self.num_f - self.num_aux_obj_var # loop over addx_nonlinear_obj, it is a pointObj with index information inside it for obj in self.addx_nonlinear_obj: idx = obj.index i0 = self.__get_addx_leading_column(idx) addx = x[i0: i0 + self.addX[idx].n] Gpiece = G[curNg: curNg + obj.nG] rowpiece = row[curNg: curNg + obj.nG] colpiece = col[curNg: curNg + obj.nG] obj.__callg__(self, addx, y[curRow: curRow + 1], Gpiece, rowpiece, colpiece, rec, needg) if rec: rowpiece[:] = curRow colpiece[:] += i0 curNg += obj.nG curRow += 1 # loop over nonlinear_obj for obj in self.nonlinear_obj: obj.__callg__(self, x, y[curRow: curRow + 1], G[curNg: curNg + obj.nG], row[curNg: curNg + obj.nG], col[curNg: curNg + obj.nG], rec, needg) if rec: row[curNg: curNg + obj.nG] = curRow curRow += 1 curNg += obj.nG return curRow, curNg # TODO: add support for def __calc_nonlinear_constr(self, curRow, curNg, x, y, G, row, col, rec, needg): """Calculation of nonlinear constraints. :param x: the long vector of solution :param y: where to store constraint function evaluation :param G, row, col: the sparse Jacobian is stored here :param curRow, curNg: accumulated number of y/G :return curRow, curNg: updated number of used y/G """ # loop over connect_nonlinear_constr for constr in self.connect_nonlinear_constr: # get arguments for calling this function x1, x2, addx = self.__extract_func_arguments(x, constr) phase1 = self.phases[constr.phases[0]] phase2 = self.phases[constr.phases[1]] phase_num1, phase_num2 = constr.phases index1, index2 = constr.indexes offset1 = self.__get_leading_column(phase_num1, index1) offset2 = self.__get_leading_column(phase_num2, index2) if constr.human: rst = constr.__callhumang__(x1, x2, needg, addx) tmpy, G1, G2, G3 = rst y[curRow: curRow + constr.nf] = tmpy if needg: # for phase 1 if constr.autonomous[0]: # we are happy G[curNg: curNg + G1.nnz] = G1.data # np.concatenate((G1.data, G2.data, G3.data)) if rec: row[curNg: curNg + G1.nnz] = np.concatenate((G1.row)) + curRow col[curNg: curNg + G1.nnz] = phase1.__patchCol__(index1, G1.col, offset1) curNg += G1.nnz else: curNg = phase1.__copy_into_g__(index1, G, row, col, curRow, curNg, G1.nnz, constr.timeindex[0], False, rec, G1.data, G1.row, G1.col, offset1) # for phase 2 if constr.autonomous[1]: # we are happy G[curNg: curNg + G2.nnz] = G2.data if rec: row[curNg: curNg + G2.nnz] = np.concatenate((G2.row)) + curRow col[curNg: curNg + G2.nnz] = phase1.__patchCol__(index2, G2.col, offset2) curNg += G2.nnz else: curNg = phase2.__copy_into_g__(index2, G, row, col, curRow, curNg, G2.nnz, constr.timeindex[1], False, rec, G2.data, G2.row, G2.col, offset2) # for phase a, if applicable if constr.addx_index is not None: G[curNg: curNg + G3.nnz] = G3.data if rec: row[curNg: curNg + G3.nnz] = curRow + G3.row col[curNg: curNg + G3.nnz] = self.__get_addx_leading_column(constr.addx_index) + G3.col else: if constr.autonomous[0] and constr.autonomous[1]: # we are sure it is within bound and we are fine Gpiece = G[curNg: curNg + constr.nG] rowpiece = row[curNg: curNg + constr.nG] colpiece = col[curNg: curNg + constr.nG] tmpcol = self.col[:constr.nG] constr.__callg__(x1, x2, y[curRow: curRow + constr.nf], Gpiece, rowpiece, tmpcol, rec, needg, addx) if rec: rowpiece[:] += curRow # assign self.col to correct place index1_ = np.where(tmpcol < len(x1))[0] colpiece[index1_] = phase1.__patchCol__(0, tmpcol[index1_], offset1) # why use 0? Because offset1 accounts for them index2_ = np.where((tmpcol >= len(x1)) & (tmpcol < len(x1) + len(x2)))[0] colpiece[index2_] = phase2.__patchCol__(0, tmpcol[index2_] - len(x1), offset2) if constr.addx_index is not None: index3_ = np.where(tmpcol >= len(x1) + len(x2))[0] colpiece[index3_] = tmpcol[index3_] - len(x1) - len(x2) + self.__get_addx_leading_column(constr.addx_index) curNg += constr.nG else: constr.__callg__(x1, x2, y[curRow: curRow + constr.nf], self.G, self.row, self.col, rec, needg, addx) mask1 = self.col < len(x1) ng1 = np.sum(mask1) curNg = phase1.__copy_into_g__(index1, G, row, col, curRow, curNg, ng1, constr.timeindex[0], False, rec, self.G[mask1], self.row[mask1], self.col[mask1], offset1) mask2 = (self.col >= len(x1)) & (self.col < len(x1) + len(x2)) ng2 = np.sum(mask2) curNg = phase2.__copy_into_g__(index2, G, row, col, curRow, curNg, ng2, constr.timeindex[1], False, rec, self.G[mask2], self.row[mask2], self.col[mask2] - len(x1), offset2) if constr.timeindex is not None: mask3 = self.col >= len(x1) + len(x2) ng3 = np.sum(mask3) G[curNg: curNg + ng3] = self.G[mask3] if rec: row[curNg: curNg + ng3] = self.row[mask3] + curRow col[curNg: curNg + ng3] = self.col[mask3] - len(x1) - len(x2) + self.__get_addx_leading_column(constr.addx_index) curNg += ng3 curRow += constr.nf for constr in self.addx_nonlinear_constr: usex = self.__get_addx_by_index(x, constr.index) constr.__callg__(usex, y[curRow: curRow + constr.nf], G[curNg: curNg + constr.nG], row[curNg: curNg + constr.nG], col[curNg: curNg + constr.nG], rec, needg) if rec: row[curNg: curNg + constr.nG] += curRow col[curNg: curNg + constr.nG] += self.__get_addx_leading_column(constr.index) curRow += constr.nf curNg += constr.nG for constr in self.nonlinear_constr: constr.__callg__(x, y[curRow: curRow + constr.nf], G[curNg: curNg + constr.nG], row[curNg: curNg + constr.nG], col[curNg: curNg + constr.nG], rec, needg) if rec: row[curNg: curNg + constr.nG] += curRow curRow += constr.nf curNg += constr.nG return curRow, curNg def __checkGError(self, G, row, col, curNg): """For debug purpose. Check if G and A overlap. Due to incorrect assignment of Jacobian row and column numbers. It uses bool operation. :param G, row, col: the Jacobian matrix to check :param curNg: accumulated G. """ boolMat1 = np.zeros((self.nf, self.nx), dtype=bool) boolMat1[self.Arow, self.Acol] = True boolMat2 = np.zeros((self.nf, self.nx), dtype=bool) boolMat2[row[:curNg], col[:curNg]] = True # find both true badMat = boolMat1 & boolMat2 nRepeat = np.sum(badMat) print('%d %d %d' % (np.sum(boolMat1), np.sum(boolMat2), nRepeat)) if nRepeat > 0: print(np.sum(badMat)) pass
[ "pyoptsolver.OptProblem.__init__", "numpy.ones", "numpy.where", "numpy.__get_addx_leading_column", "numpy.logical_not", "numpy.array", "numpy.zeros", "numpy.dot", "numpy.sum", "numpy.concatenate", "scipy.sparse.coo_matrix", "numpy.cumsum", "scipy.sparse.csr_matrix", "numpy.arange" ]
[((6075, 6091), 'scipy.sparse.coo_matrix', 'coo_matrix', (['adda'], {}), '(adda)\n', (6085, 6091), False, 'from scipy.sparse import coo_matrix, csr_matrix\n'), ((8668, 8711), 'numpy.array', 'np.array', (['[prob.nx for prob in self.phases]'], {}), '([prob.nx for prob in self.phases])\n', (8676, 8711), True, 'import numpy as np\n'), ((8801, 8850), 'numpy.array', 'np.array', (['[(prob.nf - 1) for prob in self.phases]'], {}), '([(prob.nf - 1) for prob in self.phases])\n', (8809, 8850), True, 'import numpy as np\n'), ((10191, 10240), 'pyoptsolver.OptProblem.__init__', 'OptProblem.__init__', (['self', 'est_num_F', 'est_num_sol'], {}), '(self, est_num_F, est_num_sol)\n', (10210, 10240), False, 'from pyoptsolver import OptProblem, OptResult as result\n'), ((10678, 10751), 'scipy.sparse.csr_matrix', 'csr_matrix', (['(self.Aval, (self.Arow, self.Acol))'], {'shape': '(self.nf, self.nx)'}), '((self.Aval, (self.Arow, self.Acol)), shape=(self.nf, self.nx))\n', (10688, 10751), False, 'from scipy.sparse import coo_matrix, csr_matrix\n'), ((11175, 11197), 'numpy.zeros', 'np.zeros', (['self.num_sol'], {}), '(self.num_sol)\n', (11183, 11197), True, 'import numpy as np\n'), ((11933, 11955), 'numpy.zeros', 'np.zeros', (['self.num_sol'], {}), '(self.num_sol)\n', (11941, 11955), True, 'import numpy as np\n'), ((13315, 13337), 'numpy.zeros', 'np.zeros', (['self.num_sol'], {}), '(self.num_sol)\n', (13323, 13337), True, 'import numpy as np\n'), ((16357, 16391), 'numpy.dot', 'np.dot', (['row0.data', 'x[row0.indices]'], {}), '(row0.data, x[row0.indices])\n', (16363, 16391), True, 'import numpy as np\n'), ((16891, 16902), 'numpy.zeros', 'np.zeros', (['(1)'], {}), '(1)\n', (16899, 16902), True, 'import numpy as np\n'), ((16917, 16939), 'numpy.zeros', 'np.zeros', (['(1)'], {'dtype': 'int'}), '(1, dtype=int)\n', (16925, 16939), True, 'import numpy as np\n'), ((16954, 16976), 'numpy.zeros', 'np.zeros', (['(1)'], {'dtype': 'int'}), '(1, dtype=int)\n', (16962, 16976), True, 'import numpy as np\n'), ((17386, 17406), 'numpy.zeros', 'np.zeros', (['self.num_f'], {}), '(self.num_f)\n', (17394, 17406), True, 'import numpy as np\n'), ((20526, 20561), 'numpy.zeros', 'np.zeros', (['self.num_nonlinear_constr'], {}), '(self.num_nonlinear_constr)\n', (20534, 20561), True, 'import numpy as np\n'), ((28763, 28841), 'numpy.concatenate', 'np.concatenate', (['[[useT1[index1]], useX1[index1], useU1[index1], useP1[index1]]'], {}), '([[useT1[index1]], useX1[index1], useU1[index1], useP1[index1]])\n', (28777, 28841), True, 'import numpy as np\n'), ((28857, 28935), 'numpy.concatenate', 'np.concatenate', (['[[useT2[index2]], useX2[index2], useU2[index2], useP2[index2]]'], {}), '([[useT2[index2]], useX2[index2], useU2[index2], useP2[index2]])\n', (28871, 28935), True, 'import numpy as np\n'), ((30589, 30609), 'numpy.zeros', 'np.zeros', (['self.num_f'], {}), '(self.num_f)\n', (30597, 30609), True, 'import numpy as np\n'), ((30623, 30643), 'numpy.zeros', 'np.zeros', (['self.num_f'], {}), '(self.num_f)\n', (30631, 30643), True, 'import numpy as np\n'), ((32697, 32733), 'numpy.concatenate', 'np.concatenate', (['(lstA + lstA2 + lstA3)'], {}), '(lstA + lstA2 + lstA3)\n', (32711, 32733), True, 'import numpy as np\n'), ((32754, 32799), 'numpy.concatenate', 'np.concatenate', (['(lstArow + lstArow2 + lstArow3)'], {}), '(lstArow + lstArow2 + lstArow3)\n', (32768, 32799), True, 'import numpy as np\n'), ((32820, 32865), 'numpy.concatenate', 'np.concatenate', (['(lstAcol + lstAcol2 + lstAcol3)'], {}), '(lstAcol + lstAcol2 + lstAcol3)\n', (32834, 32865), True, 'import numpy as np\n'), ((39568, 39583), 'numpy.zeros', 'np.zeros', (['maxnG'], {}), '(maxnG)\n', (39576, 39583), True, 'import numpy as np\n'), ((39603, 39629), 'numpy.zeros', 'np.zeros', (['maxnG'], {'dtype': 'int'}), '(maxnG, dtype=int)\n', (39611, 39629), True, 'import numpy as np\n'), ((39649, 39675), 'numpy.zeros', 'np.zeros', (['maxnG'], {'dtype': 'int'}), '(maxnG, dtype=int)\n', (39657, 39675), True, 'import numpy as np\n'), ((39965, 39976), 'numpy.zeros', 'np.zeros', (['(1)'], {}), '(1)\n', (39973, 39976), True, 'import numpy as np\n'), ((48009, 48049), 'numpy.zeros', 'np.zeros', (['(self.nf, self.nx)'], {'dtype': 'bool'}), '((self.nf, self.nx), dtype=bool)\n', (48017, 48049), True, 'import numpy as np\n'), ((48115, 48155), 'numpy.zeros', 'np.zeros', (['(self.nf, self.nx)'], {'dtype': 'bool'}), '((self.nf, self.nx), dtype=bool)\n', (48123, 48155), True, 'import numpy as np\n'), ((48286, 48300), 'numpy.sum', 'np.sum', (['badMat'], {}), '(badMat)\n', (48292, 48300), True, 'import numpy as np\n'), ((2268, 2285), 'numpy.zeros', 'np.zeros', (['self.nf'], {}), '(self.nf)\n', (2276, 2285), True, 'import numpy as np\n'), ((2370, 2387), 'numpy.zeros', 'np.zeros', (['self.nf'], {}), '(self.nf)\n', (2378, 2387), True, 'import numpy as np\n'), ((4215, 4232), 'numpy.zeros', 'np.zeros', (['self.nf'], {}), '(self.nf)\n', (4223, 4232), True, 'import numpy as np\n'), ((4252, 4269), 'numpy.zeros', 'np.zeros', (['self.nG'], {}), '(self.nG)\n', (4260, 4269), True, 'import numpy as np\n'), ((4291, 4319), 'numpy.zeros', 'np.zeros', (['self.nG'], {'dtype': 'int'}), '(self.nG, dtype=int)\n', (4299, 4319), True, 'import numpy as np\n'), ((4341, 4369), 'numpy.zeros', 'np.zeros', (['self.nG'], {'dtype': 'int'}), '(self.nG, dtype=int)\n', (4349, 4369), True, 'import numpy as np\n'), ((4778, 4795), 'numpy.zeros', 'np.zeros', (['self.nf'], {}), '(self.nf)\n', (4786, 4795), True, 'import numpy as np\n'), ((4846, 4863), 'numpy.zeros', 'np.zeros', (['self.nf'], {}), '(self.nf)\n', (4854, 4863), True, 'import numpy as np\n'), ((5962, 5976), 'scipy.sparse.coo_matrix', 'coo_matrix', (['a1'], {}), '(a1)\n', (5972, 5976), False, 'from scipy.sparse import coo_matrix, csr_matrix\n'), ((5978, 5992), 'scipy.sparse.coo_matrix', 'coo_matrix', (['a2'], {}), '(a2)\n', (5988, 5992), False, 'from scipy.sparse import coo_matrix, csr_matrix\n'), ((6208, 6225), 'numpy.zeros', 'np.zeros', (['self.nf'], {}), '(self.nf)\n', (6216, 6225), True, 'import numpy as np\n'), ((6310, 6327), 'numpy.zeros', 'np.zeros', (['self.nf'], {}), '(self.nf)\n', (6318, 6327), True, 'import numpy as np\n'), ((6473, 6501), 'numpy.where', 'np.where', (['(self.a[0].col == 0)'], {}), '(self.a[0].col == 0)\n', (6481, 6501), True, 'import numpy as np\n'), ((6563, 6591), 'numpy.where', 'np.where', (['(self.a[1].col == 0)'], {}), '(self.a[1].col == 0)\n', (6571, 6591), True, 'import numpy as np\n'), ((8751, 8773), 'numpy.cumsum', 'np.cumsum', (['vec_num_sol'], {}), '(vec_num_sol)\n', (8760, 8773), True, 'import numpy as np\n'), ((8911, 8931), 'numpy.cumsum', 'np.cumsum', (['vec_num_f'], {}), '(vec_num_f)\n', (8920, 8931), True, 'import numpy as np\n'), ((17442, 17484), 'numpy.ones', 'np.ones', (['(self.nG + self.spA.nnz)'], {'dtype': 'int'}), '(self.nG + self.spA.nnz, dtype=int)\n', (17449, 17484), True, 'import numpy as np\n'), ((17503, 17545), 'numpy.ones', 'np.ones', (['(self.nG + self.spA.nnz)'], {'dtype': 'int'}), '(self.nG + self.spA.nnz, dtype=int)\n', (17510, 17545), True, 'import numpy as np\n'), ((17845, 17866), 'numpy.ones', 'np.ones', (['(1)'], {'dtype': 'int'}), '(1, dtype=int)\n', (17852, 17866), True, 'import numpy as np\n'), ((17885, 17906), 'numpy.ones', 'np.ones', (['(1)'], {'dtype': 'int'}), '(1, dtype=int)\n', (17892, 17906), True, 'import numpy as np\n'), ((20720, 20731), 'numpy.zeros', 'np.zeros', (['(1)'], {}), '(1)\n', (20728, 20731), True, 'import numpy as np\n'), ((20733, 20744), 'numpy.zeros', 'np.zeros', (['(1)'], {}), '(1)\n', (20741, 20744), True, 'import numpy as np\n'), ((20746, 20757), 'numpy.zeros', 'np.zeros', (['(1)'], {}), '(1)\n', (20754, 20757), True, 'import numpy as np\n'), ((26092, 26112), 'numpy.sum', 'np.sum', (['vec_len_addX'], {}), '(vec_len_addX)\n', (26098, 26112), True, 'import numpy as np\n'), ((29319, 29329), 'numpy.ones', 'np.ones', (['(1)'], {}), '(1)\n', (29326, 29329), True, 'import numpy as np\n'), ((29632, 29653), 'numpy.ones', 'np.ones', (['self.num_sol'], {}), '(self.num_sol)\n', (29639, 29653), True, 'import numpy as np\n'), ((37034, 37057), 'numpy.zeros', 'np.zeros', (['self.len_addX'], {}), '(self.len_addX)\n', (37042, 37057), True, 'import numpy as np\n'), ((37300, 37316), 'scipy.sparse.coo_matrix', 'coo_matrix', (['tmpA'], {}), '(tmpA)\n', (37310, 37316), False, 'from scipy.sparse import coo_matrix, csr_matrix\n'), ((37831, 37853), 'numpy.zeros', 'np.zeros', (['num_addx_obj'], {}), '(num_addx_obj)\n', (37839, 37853), True, 'import numpy as np\n'), ((37875, 37896), 'numpy.ones', 'np.ones', (['num_addx_obj'], {}), '(num_addx_obj)\n', (37882, 37896), True, 'import numpy as np\n'), ((4110, 4131), 'numpy.where', 'np.where', (['(G1.col == 0)'], {}), '(G1.col == 0)\n', (4118, 4131), True, 'import numpy as np\n'), ((4157, 4178), 'numpy.where', 'np.where', (['(G2.col == 0)'], {}), '(G2.col == 0)\n', (4165, 4178), True, 'import numpy as np\n'), ((4500, 4521), 'numpy.where', 'np.where', (['(tmpcol == 0)'], {}), '(tmpcol == 0)\n', (4508, 4521), True, 'import numpy as np\n'), ((4547, 4571), 'numpy.where', 'np.where', (['(tmpcol == len1)'], {}), '(tmpcol == len1)\n', (4555, 4571), True, 'import numpy as np\n'), ((19769, 19802), 'numpy.concatenate', 'np.concatenate', (['traj[key]'], {'axis': '(0)'}), '(traj[key], axis=0)\n', (19783, 19802), True, 'import numpy as np\n'), ((26181, 26204), 'numpy.cumsum', 'np.cumsum', (['vec_len_addX'], {}), '(vec_len_addX)\n', (26190, 26204), True, 'import numpy as np\n'), ((33615, 33643), 'numpy.zeros', 'np.zeros', (['a1.nnz'], {'dtype': 'bool'}), '(a1.nnz, dtype=bool)\n', (33623, 33643), True, 'import numpy as np\n'), ((33711, 33735), 'numpy.logical_not', 'np.logical_not', (['timemask'], {}), '(timemask)\n', (33725, 33735), True, 'import numpy as np\n'), ((36850, 36870), 'numpy.ones', 'np.ones', (['n_col_index'], {}), '(n_col_index)\n', (36857, 36870), True, 'import numpy as np\n'), ((36899, 36920), 'numpy.zeros', 'np.zeros', (['n_col_index'], {}), '(n_col_index)\n', (36907, 36920), True, 'import numpy as np\n'), ((37174, 37213), 'numpy.__get_addx_leading_column', 'np.__get_addx_leading_column', (['obj.index'], {}), '(obj.index)\n', (37202, 37213), True, 'import numpy as np\n'), ((37380, 37399), 'numpy.zeros', 'np.zeros', (['tmpA_.nnz'], {}), '(tmpA_.nnz)\n', (37388, 37399), True, 'import numpy as np\n'), ((37769, 37792), 'numpy.arange', 'np.arange', (['num_addx_obj'], {}), '(num_addx_obj)\n', (37778, 37792), True, 'import numpy as np\n'), ((37955, 37978), 'numpy.arange', 'np.arange', (['num_addx_obj'], {}), '(num_addx_obj)\n', (37964, 37978), True, 'import numpy as np\n'), ((38029, 38052), 'numpy.arange', 'np.arange', (['num_addx_obj'], {}), '(num_addx_obj)\n', (38038, 38052), True, 'import numpy as np\n'), ((38075, 38096), 'numpy.ones', 'np.ones', (['num_addx_obj'], {}), '(num_addx_obj)\n', (38082, 38096), True, 'import numpy as np\n'), ((48417, 48431), 'numpy.sum', 'np.sum', (['badMat'], {}), '(badMat)\n', (48423, 48431), True, 'import numpy as np\n'), ((29413, 29424), 'numpy.zeros', 'np.zeros', (['(1)'], {}), '(1)\n', (29421, 29424), True, 'import numpy as np\n'), ((29429, 29440), 'numpy.zeros', 'np.zeros', (['(1)'], {}), '(1)\n', (29437, 29440), True, 'import numpy as np\n'), ((30123, 30139), 'numpy.zeros', 'np.zeros', (['addx.n'], {}), '(addx.n)\n', (30131, 30139), True, 'import numpy as np\n'), ((30206, 30222), 'numpy.zeros', 'np.zeros', (['addx.n'], {}), '(addx.n)\n', (30214, 30222), True, 'import numpy as np\n'), ((45628, 45641), 'numpy.sum', 'np.sum', (['mask1'], {}), '(mask1)\n', (45634, 45641), True, 'import numpy as np\n'), ((45962, 45975), 'numpy.sum', 'np.sum', (['mask2'], {}), '(mask2)\n', (45968, 45975), True, 'import numpy as np\n'), ((48329, 48345), 'numpy.sum', 'np.sum', (['boolMat1'], {}), '(boolMat1)\n', (48335, 48345), True, 'import numpy as np\n'), ((48347, 48363), 'numpy.sum', 'np.sum', (['boolMat2'], {}), '(boolMat2)\n', (48353, 48363), True, 'import numpy as np\n'), ((46342, 46355), 'numpy.sum', 'np.sum', (['mask3'], {}), '(mask3)\n', (46348, 46355), True, 'import numpy as np\n'), ((34514, 34530), 'numpy.sum', 'np.sum', (['timemask'], {}), '(timemask)\n', (34520, 34530), True, 'import numpy as np\n'), ((35036, 35052), 'numpy.sum', 'np.sum', (['timemask'], {}), '(timemask)\n', (35042, 35052), True, 'import numpy as np\n'), ((42651, 42673), 'numpy.concatenate', 'np.concatenate', (['G1.row'], {}), '(G1.row)\n', (42665, 42673), True, 'import numpy as np\n'), ((43294, 43316), 'numpy.concatenate', 'np.concatenate', (['G2.row'], {}), '(G2.row)\n', (43308, 43316), True, 'import numpy as np\n')]
import os import numpy as np from sklearn.cluster import KMeans,MeanShift, estimate_bandwidth from sklearn.decomposition import PCA import pandas as pd import matplotlib.pyplot as plt '''设定参数''' # PCA降维维度 pca_dimensions = 2 # K-Means聚类数 n_clusters = 8 # 聚类完成后储存文件位置 cluster_path = 'results/kmeans.xlsx' '''程序入口''' # 读入数据 data = np.loadtxt("results/output.txt") data = data.reshape((77440, 2*2*8)) print("load success") pca = PCA(n_components = pca_dimensions) lo_data = pca.fit_transform(data) # 输出pca结果对于方差的比例 print(pca.explained_variance_ratio_) print("pca success", lo_data.shape) # 建立模型 # model = MeanShift(n_jobs = -2, bin_seeding = True) model = KMeans(n_clusters = n_clusters, random_state = 0) print("model success") # 应用模型 model.fit(lo_data) print("fit success") col = ['x' + str(i) for i in range(0, 2) ] #labels为分类的标签 labels = model.labels_ clusters = dict(zip(*np.unique(labels, return_counts=True))) print("stat success", clusters) '''绘制聚类图''' colors = [['red','green','blue','grey','yellow','black','cyan','magenta'][label] for label in labels] plt.scatter(lo_data[:,0],lo_data[:,1],c=colors,s=10) plt.title('KMeans') plt.show() #把标签加入到矩阵中用DataFrame生成新的df,index为类别的编号,这里是0,1,2 df = pd.DataFrame(lo_data,index=labels,columns=col) #数据保存在excel文件中 writer = pd.ExcelWriter(cluster_path) # writer = pd.ExcelWriter('results/meanshift.xlsx') df.to_excel(writer,'page_1',float_format='%.5f') # float_format 控制精度 writer.save() print("save success")
[ "sklearn.cluster.KMeans", "pandas.ExcelWriter", "numpy.unique", "sklearn.decomposition.PCA", "matplotlib.pyplot.scatter", "pandas.DataFrame", "matplotlib.pyplot.title", "numpy.loadtxt", "matplotlib.pyplot.show" ]
[((330, 362), 'numpy.loadtxt', 'np.loadtxt', (['"""results/output.txt"""'], {}), "('results/output.txt')\n", (340, 362), True, 'import numpy as np\n'), ((428, 460), 'sklearn.decomposition.PCA', 'PCA', ([], {'n_components': 'pca_dimensions'}), '(n_components=pca_dimensions)\n', (431, 460), False, 'from sklearn.decomposition import PCA\n'), ((656, 701), 'sklearn.cluster.KMeans', 'KMeans', ([], {'n_clusters': 'n_clusters', 'random_state': '(0)'}), '(n_clusters=n_clusters, random_state=0)\n', (662, 701), False, 'from sklearn.cluster import KMeans, MeanShift, estimate_bandwidth\n'), ((1066, 1123), 'matplotlib.pyplot.scatter', 'plt.scatter', (['lo_data[:, 0]', 'lo_data[:, 1]'], {'c': 'colors', 's': '(10)'}), '(lo_data[:, 0], lo_data[:, 1], c=colors, s=10)\n', (1077, 1123), True, 'import matplotlib.pyplot as plt\n'), ((1119, 1138), 'matplotlib.pyplot.title', 'plt.title', (['"""KMeans"""'], {}), "('KMeans')\n", (1128, 1138), True, 'import matplotlib.pyplot as plt\n'), ((1139, 1149), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1147, 1149), True, 'import matplotlib.pyplot as plt\n'), ((1204, 1252), 'pandas.DataFrame', 'pd.DataFrame', (['lo_data'], {'index': 'labels', 'columns': 'col'}), '(lo_data, index=labels, columns=col)\n', (1216, 1252), True, 'import pandas as pd\n'), ((1275, 1303), 'pandas.ExcelWriter', 'pd.ExcelWriter', (['cluster_path'], {}), '(cluster_path)\n', (1289, 1303), True, 'import pandas as pd\n'), ((879, 916), 'numpy.unique', 'np.unique', (['labels'], {'return_counts': '(True)'}), '(labels, return_counts=True)\n', (888, 916), True, 'import numpy as np\n')]
from slac_services.services.scheduling import MountPoint from slac_services.utils import isotime from slac_services import service_container import argparse import numpy as np import os dir_path = os.path.dirname(os.path.realpath(__file__)) LUME_CONFIGURATION_FILE = os.environ["LUME_ORCHESTRATION_CLUSTER_CONFIG"] distgen_input_filename = f"{dir_path}/files/distgen.yaml" # we need to create mount points for each of these # use the scheduling MountPoint utility distgen_input_mount = MountPoint( name="distgen-input-mount", host_path=distgen_input_filename, mount_type="File" ) # format inputs vcc_array = np.load(f"{dir_path}/files/default_vcc_array.npy") distgen_pv_values = { "CAMR:IN20:186:RESOLUTION" : 9, "CAMR:IN20:186:RESOLUTION.EGU" : "um", "CAMR:IN20:186:N_OF_ROW" : 480, "CAMR:IN20:186:N_OF_COL": 640, "CAMR:IN20:186:IMAGE": vcc_array.tolist(), # neet to convert to json serializable input for passed data "BPMS:IN20:221:TMIT": 1.51614e+09 } distgen_configuration = {} distgen_settings = { 'n_particle': 10000, "t_dist:length:value": 4 * 1.65 # Inferred pulse stacker FWHM: 4 ps, converted to tukey length } distgen_pvname_to_input_map = { "CAMR:IN20:186:RESOLUTION" : "vcc_resolution", "CAMR:IN20:186:RESOLUTION.EGU" : "vcc_resolution_units", "CAMR:IN20:186:N_OF_ROW" : "vcc_size_y", "CAMR:IN20:186:N_OF_COL": "vcc_size_x", "CAMR:IN20:186:IMAGE": "vcc_array", "BPMS:IN20:221:TMIT":"total_charge" } workdir = f"{dir_path}/files/output" # will want to create a directory so use DirectoryOrCreate mount type workdir_mount = MountPoint( name="workdir-mount", host_path=workdir, mount_type="DirectoryOrCreate" ) # in this case, will be using conda installation of impact command="ImpactTexe" command_mpi="" use_mpi=False mpi_run="mpirun -n {nproc} --use-hwthread-cpus {command_mpi}" impact_configuration = { "command": command, "command_mpi": command_mpi, "use_mpi": use_mpi, "workdir": workdir, "mpi_run": mpi_run } impact_settings = { "header:Nx": 32, "header:Ny": 32, "header:Nz": 32, "stop": 16.5, # "stop": 8, "numprocs": 1, "timeout": 1000, "total_charge": 0, # for debugging } impact_archive_file = f"{dir_path}/files/archive.h5" impact_archive_input_mount = MountPoint( name="impact-archive-input-mount", host_path=impact_archive_file, mount_type="File" ) impact_pv_values = {"SOLN:IN20:121:BACT": 0.47235, "QUAD:IN20:121:BACT": -0.00133705, "QUAD:IN20:122:BACT": 0.000769202, "ACCL:IN20:300:L0A_PDES": 0, "ACCL:IN20:400:L0B_PDES": -2.5, "ACCL:IN20:300:L0A_ADES": 58, "ACCL:IN20:400:L0B_ADES": 69.9586, "QUAD:IN20:361:BACT": -3.25386, "QUAD:IN20:371:BACT": 2.5843, "QUAD:IN20:425:BACT": -1.54514, "QUAD:IN20:441:BACT": -0.671809, "QUAD:IN20:511:BACT": 3.22537, "QUAD:IN20:525:BACT": -3.20496, } impact_pvname_to_input_map = {"SOLN:IN20:121:BACT": "SOL1:solenoid_field_scale", "QUAD:IN20:121:BACT": "CQ01:b1_gradient", "QUAD:IN20:122:BACT": "SQ01:b1_gradient", "ACCL:IN20:300:L0A_PDES": "L0A_phase:dtheta0_deg", "ACCL:IN20:400:L0B_PDES": "L0B_phase:dtheta0_deg", "ACCL:IN20:300:L0A_ADES": "L0A_scale:voltage", "ACCL:IN20:400:L0B_ADES": "L0B_scale:voltage", "QUAD:IN20:361:BACT": "QA01:b1_gradient", "QUAD:IN20:371:BACT": "QA02:b1_gradient", "QUAD:IN20:425:BACT": "QE01:b1_gradient", "QUAD:IN20:441:BACT": "QE02:b1_gradient", "QUAD:IN20:511:BACT": "QE03:b1_gradient", "QUAD:IN20:525:BACT": "QE04:b1_gradient", } # DirectoryOrCreate for archive and dashboard archive_dir = f"{dir_path}/files/output/archive" impact_archive_mount = MountPoint( name="archive-mount", host_path=archive_dir, mount_type="DirectoryOrCreate" ) dashboard_dir = f"{dir_path}/files/output/dashboard" dashboard_mount = MountPoint( name="dashboard-mount", host_path=dashboard_dir, mount_type="DirectoryOrCreate" ) data = { "distgen_input_filename": distgen_input_filename, "distgen_settings": distgen_settings, "distgen_configuration": distgen_configuration, "distgen_pv_values": distgen_pv_values, "distgen_pvname_to_input_map": distgen_pvname_to_input_map, "impact_configuration": impact_configuration, "impact_pv_values": impact_pv_values, "impact_settings": impact_settings, "impact_pvname_to_input_map": impact_pvname_to_input_map, "impact_archive_file": impact_archive_file, "pv_collection_isotime": isotime(), "impact_archive_dir": archive_dir, "dashboard_dir": dashboard_dir } # get remote modeling service remote_modeling_service = service_container.remote_modeling_service() mount_points = [distgen_input_mount, workdir_mount, impact_archive_input_mount, impact_archive_mount, dashboard_mount] remote_modeling_service.predict(model_id=1, data=data, mount_points=mount_points, lume_configuration_file=LUME_CONFIGURATION_FILE) #from distgen_impact_cu_inj_ex.flow.flow import get_flow #flow = get_flow() #flow.run(**data)
[ "slac_services.utils.isotime", "slac_services.service_container.remote_modeling_service", "slac_services.services.scheduling.MountPoint", "os.path.realpath", "numpy.load" ]
[((492, 587), 'slac_services.services.scheduling.MountPoint', 'MountPoint', ([], {'name': '"""distgen-input-mount"""', 'host_path': 'distgen_input_filename', 'mount_type': '"""File"""'}), "(name='distgen-input-mount', host_path=distgen_input_filename,\n mount_type='File')\n", (502, 587), False, 'from slac_services.services.scheduling import MountPoint\n'), ((620, 670), 'numpy.load', 'np.load', (['f"""{dir_path}/files/default_vcc_array.npy"""'], {}), "(f'{dir_path}/files/default_vcc_array.npy')\n", (627, 670), True, 'import numpy as np\n'), ((1612, 1700), 'slac_services.services.scheduling.MountPoint', 'MountPoint', ([], {'name': '"""workdir-mount"""', 'host_path': 'workdir', 'mount_type': '"""DirectoryOrCreate"""'}), "(name='workdir-mount', host_path=workdir, mount_type=\n 'DirectoryOrCreate')\n", (1622, 1700), False, 'from slac_services.services.scheduling import MountPoint\n'), ((2312, 2411), 'slac_services.services.scheduling.MountPoint', 'MountPoint', ([], {'name': '"""impact-archive-input-mount"""', 'host_path': 'impact_archive_file', 'mount_type': '"""File"""'}), "(name='impact-archive-input-mount', host_path=impact_archive_file,\n mount_type='File')\n", (2322, 2411), False, 'from slac_services.services.scheduling import MountPoint\n'), ((4111, 4203), 'slac_services.services.scheduling.MountPoint', 'MountPoint', ([], {'name': '"""archive-mount"""', 'host_path': 'archive_dir', 'mount_type': '"""DirectoryOrCreate"""'}), "(name='archive-mount', host_path=archive_dir, mount_type=\n 'DirectoryOrCreate')\n", (4121, 4203), False, 'from slac_services.services.scheduling import MountPoint\n'), ((4277, 4373), 'slac_services.services.scheduling.MountPoint', 'MountPoint', ([], {'name': '"""dashboard-mount"""', 'host_path': 'dashboard_dir', 'mount_type': '"""DirectoryOrCreate"""'}), "(name='dashboard-mount', host_path=dashboard_dir, mount_type=\n 'DirectoryOrCreate')\n", (4287, 4373), False, 'from slac_services.services.scheduling import MountPoint\n'), ((5058, 5101), 'slac_services.service_container.remote_modeling_service', 'service_container.remote_modeling_service', ([], {}), '()\n', (5099, 5101), False, 'from slac_services import service_container\n'), ((214, 240), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (230, 240), False, 'import os\n'), ((4913, 4922), 'slac_services.utils.isotime', 'isotime', ([], {}), '()\n', (4920, 4922), False, 'from slac_services.utils import isotime\n')]
import time, random import numpy as np import csv from absl import app, flags, logging from absl.flags import FLAGS import cv2 import matplotlib.pyplot as plt import tensorflow as tf import pandas as pd from yolov3_tf2.models import ( YoloV3, YoloV3Tiny ) from yolov3_tf2.dataset import transform_images from yolov3_tf2.utils import draw_outputs, convert_boxes from deep_sort import preprocessing from deep_sort import nn_matching from deep_sort.detection import Detection from deep_sort.tracker import Tracker from tools import generate_detections as gdet # Fuse Funtion import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' import argparse import warnings from PIL import Image flags.DEFINE_string('classes', './data/labels/coco.names', 'path to classes file') flags.DEFINE_string('weights', './weights/yolov3.tf', 'path to weights file') flags.DEFINE_boolean('tiny', False, 'yolov3 or yolov3-tiny') flags.DEFINE_integer('size', 416, 'resize images to') flags.DEFINE_string('video', './data/video/testbb.mp4', 'path to video file or number for webcam)') flags.DEFINE_string('output', None, 'path to output video') flags.DEFINE_string('output_format', 'XVID', 'codec used in VideoWriter when saving video to file') flags.DEFINE_integer('num_classes', 80, 'number of classes in the model') # Arguments # ap = argparse.ArgumentParser() # ap.add_argument('--input', type=str, help="Path Video Input") # ap.add_argument('--number', type = str, help= 'Number of sample') # args = vars(ap.parse_args()) # warnings.filterwarnings("ignore") # writeVideo_flag = True # video_capture = cv2.VideoCapture(args.input) # if writeVideo_flag: # w = int(video_capture.get(3)) # h = int(video_capture.get(4)) # fourcc = cv2.VideoWriter_fourcc(*'MJPG') # out = cv2.VideoWriter('Sample_Video{}.avi'.format(args.number), fourcc, 15, (w, h)) # list_file = open('detection.txt', 'w') # frame_index = -1 def main(_argv): # Definition of the parameters max_cosine_distance = 0.5 nn_budget = None nms_max_overlap = 1.0 # initialize deep sort model_filename = 'model_data/mars-small128.pb' encoder = gdet.create_box_encoder(model_filename, batch_size=1) metric = nn_matching.NearestNeighborDistanceMetric("cosine", max_cosine_distance, nn_budget) tracker = Tracker(metric) physical_devices = tf.config.experimental.list_physical_devices('GPU') if len(physical_devices) > 0: tf.config.experimental.set_memory_growth(physical_devices[0], True) if FLAGS.tiny: yolo = YoloV3Tiny(classes=FLAGS.num_classes) else: yolo = YoloV3(classes=FLAGS.num_classes) yolo.load_weights(FLAGS.weights) logging.info('weights loaded') class_names = [c.strip() for c in open(FLAGS.classes).readlines()] logging.info('classes loaded') try: vid = cv2.VideoCapture(int(FLAGS.video)) except: vid = cv2.VideoCapture(FLAGS.video) out = None if FLAGS.output: # by default VideoCapture returns float instead of int width = int(vid.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(vid.get(cv2.CAP_PROP_FRAME_HEIGHT)) fps = int(vid.get(cv2.CAP_PROP_FPS)) codec = cv2.VideoWriter_fourcc(*FLAGS.output_format) out = cv2.VideoWriter(FLAGS.output, codec, fps, (width, height)) list_file = open('detection.txt', 'w') frame_index = -1 fps = 0.0 count = 0 peopleOut = 0 peopleIn = 0 W = None H = None a_list = [0, 0] d_list = [0, 0] print(a_list) frame_num = 0 while True: _, img = vid.read() # frame = video_capture.read() # if W is None or H is None: # (H, W) = frame.shape[:2] if img is None: logging.warning("Empty Frame") time.sleep(0.1) count += 1 if count < 3: continue else: break frame_num += 1 img_in = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img_in = tf.expand_dims(img_in, 0) img_in = transform_images(img_in, FLAGS.size) t1 = time.time() boxes, scores, classes, nums = yolo.predict(img_in) classes = classes[0] names = [] for i in range(len(classes)): names.append(class_names[int(classes[i])]) names = np.array(names) converted_boxes = convert_boxes(img, boxes[0]) features = encoder(img, converted_boxes) detections = [Detection(bbox, score, class_name, feature) for bbox, score, class_name, feature in zip(converted_boxes, scores[0], names, features)] # initialize color map cmap = plt.get_cmap('tab20b') colors = [cmap(i)[:3] for i in np.linspace(0, 1, 20)] # run non-maxima suppresion boxs = np.array([d.tlwh for d in detections]) scores = np.array([d.confidence for d in detections]) classes = np.array([d.class_name for d in detections]) indices = preprocessing.non_max_suppression(boxs, classes, nms_max_overlap, scores) detections = [detections[i] for i in indices] # Call the tracker tracker.predict() tracker.update(detections) for track in tracker.tracks: if not track.is_confirmed() or track.time_since_update > 1: # bbox = track.to_tlbr() continue bbox = track.to_tlbr() return_value, frame = vid.read() if return_value: frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) image = Image.fromarray(frame) else: print('Video has ended or failed, try a different video format!') break c1 = (int(bbox[0]) + int(bbox[2]))>>1 # c2 = (int(bbox[1]) + int(bbox[3])) / 2 c3 = int(bbox[3]) c4 = int(bbox[1]) # centerPoint = (int(c1), int(c2)) buttonPoint = (int(c1), c3) # topPoint = (int(c1),c4) cv2.circle(img, buttonPoint, 4, (255, 255, 0), 1) class_name = track.get_class() color = colors[int(track.track_id) % len(colors)] color = [i * 255 for i in color] cv2.rectangle(img, (int(bbox[0]), int(bbox[1])), (int(bbox[2]), int(bbox[3])), color, 2) cv2.rectangle(img, (int(bbox[0]), int(bbox[1] - 30)), (int(bbox[0]) + (len(class_name) + len(str(track.track_id))) * 17, int(bbox[1])), color, -1) cv2.putText(img, class_name + "-" + str(track.track_id), (int(bbox[0]), int(bbox[1] - 10)), 0, 0.75, (255, 255, 255), 2) a_list.insert(1, str(track.track_id) + 'x:') a_list.insert(2, c1) a_list.insert(3, str(track.track_id) + 'y:') a_list.insert(4, c3) # a_list.insert(5, str(track.track_id) + 'y2:') # a_list.insert(6, c4) # Output Data Df = pd.DataFrame(a_list) Df.to_csv('P6.csv', index=False) # print(a_list) ##像素框大小計算 Target_width = abs((int(bbox[2]) - int(bbox[0]))) Target_height = abs((int(bbox[3]) - int(bbox[1]))) Target_Pixel = Target_height * Target_width Distance = 3 * 166.5 / Target_height # print(str(track.track_id)+':'+str(Target_height)+'/'+str(Distance)) #print(str(track.track_id) + ',' + str(Distance) + ',' + str(c1) + ',' + str(frame_num)+','+str(c1)+','+ str(c3)) #360路徑偵測用 print(str(track.track_id) + ',' +str(class_name)+ ',' + str(c1) + ',' + str(c3)+','+str(frame_num)) #棒球軌跡偵測用 #print(str(track.track_id) + ',' + str(Distance) + ',' + str(c1) + ',' + str(frame_num)) d_list.insert(1, str(track.track_id) + ':' + str(Distance)) Dis = pd.DataFrame(d_list) Dis.to_csv('Distance.csv', index=False) # print(str(track.track_id)+':'+str(Target_Pixel)) # cv2.putText(img,tracker) # print(track.track_id, track.stateOutMetro) ## Route # cv2.line(img, (0, H // 2 + 50), (W, H // 2 + 50), (0, 0, 255), 2) ### UNCOMMENT BELOW IF YOU WANT CONSTANTLY CHANGING YOLO DETECTIONS TO BE SHOWN ON SCREEN # for det in detections: # bbox = det.to_tlbr() # c1 = (int(bbox[0]) + int(bbox[2])) / 2 # c2 = (int(bbox[1]) + int(bbox[3])) / 2 # centerPoint = (int(c1), int(c2)) # cv2.rectangle(img,(int(bbox[0]), int(bbox[1])), (int(bbox[2]), int(bbox[3])),(255,0,0), 2) # cv2.circle(img,centerPoint,2,(0, 0, 255), 1) # cv2.circle(img, (int(a_list[1]), int(a_list[2])), 2, (0, 255, 255), 2) """centerPoint_Save = (int(axv), int(byv)) cv2.circle(img, centerPoint_Save, 2, (0, 255, 255), 1)""" # print fps on screen fps = (fps + (1. / (time.time() - t1))) / 2 cv2.putText(img, "FPS: {:.2f}".format(fps), (0, 30), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 0, 255), 2) cv2.imshow('output', img) if FLAGS.output: out.write(img) frame_index = frame_index + 1 list_file.write(str(frame_index) + ' ') if len(converted_boxes) != 0: for i in range(0, len(converted_boxes)): list_file.write(str(converted_boxes[i][0]) + ' ' + str(converted_boxes[i][1]) + ' ' + str( converted_boxes[i][2]) + ' ' + str(converted_boxes[i][3]) + ' ') list_file.write('\n') # press q to quit if cv2.waitKey(1) == ord('q'): break vid.release() if FLAGS.ouput: out.release() list_file.close() cv2.destroyAllWindows() ##with open('Data.csv',newline='') as csvFile: # writer = csv.writer(csvFile, quoting = csv.QUOTE_ALL) # writer.writerow(a_list) if __name__ == '__main__': try: app.run(main) except SystemExit: pass
[ "absl.logging.info", "time.sleep", "cv2.imshow", "numpy.array", "tools.generate_detections.create_box_encoder", "cv2.destroyAllWindows", "yolov3_tf2.models.YoloV3", "absl.flags.DEFINE_boolean", "cv2.VideoWriter", "absl.app.run", "numpy.linspace", "cv2.VideoWriter_fourcc", "yolov3_tf2.utils.c...
[((716, 802), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""classes"""', '"""./data/labels/coco.names"""', '"""path to classes file"""'], {}), "('classes', './data/labels/coco.names',\n 'path to classes file')\n", (735, 802), False, 'from absl import app, flags, logging\n'), ((800, 877), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""weights"""', '"""./weights/yolov3.tf"""', '"""path to weights file"""'], {}), "('weights', './weights/yolov3.tf', 'path to weights file')\n", (819, 877), False, 'from absl import app, flags, logging\n'), ((900, 960), 'absl.flags.DEFINE_boolean', 'flags.DEFINE_boolean', (['"""tiny"""', '(False)', '"""yolov3 or yolov3-tiny"""'], {}), "('tiny', False, 'yolov3 or yolov3-tiny')\n", (920, 960), False, 'from absl import app, flags, logging\n'), ((962, 1015), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""size"""', '(416)', '"""resize images to"""'], {}), "('size', 416, 'resize images to')\n", (982, 1015), False, 'from absl import app, flags, logging\n'), ((1017, 1120), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""video"""', '"""./data/video/testbb.mp4"""', '"""path to video file or number for webcam)"""'], {}), "('video', './data/video/testbb.mp4',\n 'path to video file or number for webcam)')\n", (1036, 1120), False, 'from absl import app, flags, logging\n'), ((1139, 1198), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""output"""', 'None', '"""path to output video"""'], {}), "('output', None, 'path to output video')\n", (1158, 1198), False, 'from absl import app, flags, logging\n'), ((1200, 1303), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""output_format"""', '"""XVID"""', '"""codec used in VideoWriter when saving video to file"""'], {}), "('output_format', 'XVID',\n 'codec used in VideoWriter when saving video to file')\n", (1219, 1303), False, 'from absl import app, flags, logging\n'), ((1301, 1374), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""num_classes"""', '(80)', '"""number of classes in the model"""'], {}), "('num_classes', 80, 'number of classes in the model')\n", (1321, 1374), False, 'from absl import app, flags, logging\n'), ((2220, 2273), 'tools.generate_detections.create_box_encoder', 'gdet.create_box_encoder', (['model_filename'], {'batch_size': '(1)'}), '(model_filename, batch_size=1)\n', (2243, 2273), True, 'from tools import generate_detections as gdet\n'), ((2288, 2375), 'deep_sort.nn_matching.NearestNeighborDistanceMetric', 'nn_matching.NearestNeighborDistanceMetric', (['"""cosine"""', 'max_cosine_distance', 'nn_budget'], {}), "('cosine', max_cosine_distance,\n nn_budget)\n", (2329, 2375), False, 'from deep_sort import nn_matching\n'), ((2387, 2402), 'deep_sort.tracker.Tracker', 'Tracker', (['metric'], {}), '(metric)\n', (2394, 2402), False, 'from deep_sort.tracker import Tracker\n'), ((2429, 2480), 'tensorflow.config.experimental.list_physical_devices', 'tf.config.experimental.list_physical_devices', (['"""GPU"""'], {}), "('GPU')\n", (2473, 2480), True, 'import tensorflow as tf\n'), ((2775, 2805), 'absl.logging.info', 'logging.info', (['"""weights loaded"""'], {}), "('weights loaded')\n", (2787, 2805), False, 'from absl import app, flags, logging\n'), ((2885, 2915), 'absl.logging.info', 'logging.info', (['"""classes loaded"""'], {}), "('classes loaded')\n", (2897, 2915), False, 'from absl import app, flags, logging\n'), ((10066, 10089), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (10087, 10089), False, 'import cv2\n'), ((2525, 2592), 'tensorflow.config.experimental.set_memory_growth', 'tf.config.experimental.set_memory_growth', (['physical_devices[0]', '(True)'], {}), '(physical_devices[0], True)\n', (2565, 2592), True, 'import tensorflow as tf\n'), ((2631, 2668), 'yolov3_tf2.models.YoloV3Tiny', 'YoloV3Tiny', ([], {'classes': 'FLAGS.num_classes'}), '(classes=FLAGS.num_classes)\n', (2641, 2668), False, 'from yolov3_tf2.models import YoloV3, YoloV3Tiny\n'), ((2696, 2729), 'yolov3_tf2.models.YoloV3', 'YoloV3', ([], {'classes': 'FLAGS.num_classes'}), '(classes=FLAGS.num_classes)\n', (2702, 2729), False, 'from yolov3_tf2.models import YoloV3, YoloV3Tiny\n'), ((3319, 3363), 'cv2.VideoWriter_fourcc', 'cv2.VideoWriter_fourcc', (['*FLAGS.output_format'], {}), '(*FLAGS.output_format)\n', (3341, 3363), False, 'import cv2\n'), ((3379, 3437), 'cv2.VideoWriter', 'cv2.VideoWriter', (['FLAGS.output', 'codec', 'fps', '(width, height)'], {}), '(FLAGS.output, codec, fps, (width, height))\n', (3394, 3437), False, 'import cv2\n'), ((4133, 4169), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2RGB'], {}), '(img, cv2.COLOR_BGR2RGB)\n', (4145, 4169), False, 'import cv2\n'), ((4188, 4213), 'tensorflow.expand_dims', 'tf.expand_dims', (['img_in', '(0)'], {}), '(img_in, 0)\n', (4202, 4213), True, 'import tensorflow as tf\n'), ((4232, 4268), 'yolov3_tf2.dataset.transform_images', 'transform_images', (['img_in', 'FLAGS.size'], {}), '(img_in, FLAGS.size)\n', (4248, 4268), False, 'from yolov3_tf2.dataset import transform_images\n'), ((4285, 4296), 'time.time', 'time.time', ([], {}), '()\n', (4294, 4296), False, 'import time, random\n'), ((4520, 4535), 'numpy.array', 'np.array', (['names'], {}), '(names)\n', (4528, 4535), True, 'import numpy as np\n'), ((4563, 4591), 'yolov3_tf2.utils.convert_boxes', 'convert_boxes', (['img', 'boxes[0]'], {}), '(img, boxes[0])\n', (4576, 4591), False, 'from yolov3_tf2.utils import draw_outputs, convert_boxes\n'), ((4872, 4894), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""tab20b"""'], {}), "('tab20b')\n", (4884, 4894), True, 'import matplotlib.pyplot as plt\n'), ((5013, 5051), 'numpy.array', 'np.array', (['[d.tlwh for d in detections]'], {}), '([d.tlwh for d in detections])\n', (5021, 5051), True, 'import numpy as np\n'), ((5070, 5114), 'numpy.array', 'np.array', (['[d.confidence for d in detections]'], {}), '([d.confidence for d in detections])\n', (5078, 5114), True, 'import numpy as np\n'), ((5134, 5178), 'numpy.array', 'np.array', (['[d.class_name for d in detections]'], {}), '([d.class_name for d in detections])\n', (5142, 5178), True, 'import numpy as np\n'), ((5198, 5271), 'deep_sort.preprocessing.non_max_suppression', 'preprocessing.non_max_suppression', (['boxs', 'classes', 'nms_max_overlap', 'scores'], {}), '(boxs, classes, nms_max_overlap, scores)\n', (5231, 5271), False, 'from deep_sort import preprocessing\n'), ((9369, 9394), 'cv2.imshow', 'cv2.imshow', (['"""output"""', 'img'], {}), "('output', img)\n", (9379, 9394), False, 'import cv2\n'), ((10285, 10298), 'absl.app.run', 'app.run', (['main'], {}), '(main)\n', (10292, 10298), False, 'from absl import app, flags, logging\n'), ((3006, 3035), 'cv2.VideoCapture', 'cv2.VideoCapture', (['FLAGS.video'], {}), '(FLAGS.video)\n', (3022, 3035), False, 'import cv2\n'), ((3908, 3938), 'absl.logging.warning', 'logging.warning', (['"""Empty Frame"""'], {}), "('Empty Frame')\n", (3923, 3938), False, 'from absl import app, flags, logging\n'), ((3952, 3967), 'time.sleep', 'time.sleep', (['(0.1)'], {}), '(0.1)\n', (3962, 3967), False, 'import time, random\n'), ((4665, 4708), 'deep_sort.detection.Detection', 'Detection', (['bbox', 'score', 'class_name', 'feature'], {}), '(bbox, score, class_name, feature)\n', (4674, 4708), False, 'from deep_sort.detection import Detection\n'), ((6264, 6313), 'cv2.circle', 'cv2.circle', (['img', 'buttonPoint', '(4)', '(255, 255, 0)', '(1)'], {}), '(img, buttonPoint, 4, (255, 255, 0), 1)\n', (6274, 6313), False, 'import cv2\n'), ((7242, 7262), 'pandas.DataFrame', 'pd.DataFrame', (['a_list'], {}), '(a_list)\n', (7254, 7262), True, 'import pandas as pd\n'), ((8137, 8157), 'pandas.DataFrame', 'pd.DataFrame', (['d_list'], {}), '(d_list)\n', (8149, 8157), True, 'import pandas as pd\n'), ((9924, 9938), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (9935, 9938), False, 'import cv2\n'), ((4935, 4956), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(20)'], {}), '(0, 1, 20)\n', (4946, 4956), True, 'import numpy as np\n'), ((5742, 5780), 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_BGR2RGB'], {}), '(frame, cv2.COLOR_BGR2RGB)\n', (5754, 5780), False, 'import cv2\n'), ((5806, 5828), 'PIL.Image.fromarray', 'Image.fromarray', (['frame'], {}), '(frame)\n', (5821, 5828), False, 'from PIL import Image\n'), ((9202, 9213), 'time.time', 'time.time', ([], {}), '()\n', (9211, 9213), False, 'import time, random\n')]
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from auto_scan_test import PassAutoScanTest, IgnoreReasons from program_config import TensorConfig, ProgramConfig, OpConfig import numpy as np import paddle.inference as paddle_infer from functools import partial from typing import Optional, List, Callable, Dict, Any, Set import unittest import hypothesis from hypothesis import given, settings, seed, example, assume, reproduce_failure import hypothesis.strategies as st class TestFcFusePass(PassAutoScanTest): """ x_var / \ / reduce_mean "u(x)" \ / elementwise_sub "x - u(x)" / \ sqr_pow_var(persistable) = 2 | \ / | elementwise_pow "(x - u(x))^2" | | | reduce_mean "sigma^2 = 1/C*Sum{(x - u(x))^2}" | | eps_var(persistable) | | / | elementwise_add "sigma^2 + epsilon" \ | \ sqrt "sqrt(sigma^2 + epsilon)" \ / \ / elementwise_div "lnorm = {x-u(x)}/{sqrt(sigma^2 + epsilon)}" | | gamma_var(persistable) | / elementwise_mul "scale: gamma(C) * lnorm" | | beta_var(persistable) | / elementwise_add "shift: gamma(C) * lnorm + beta(C)" """ def sample_predictor_configs(self, program_config): # cpu config = self.create_inference_config(use_gpu=False) yield config, ["layer_norm"], (1e-5, 1e-5) def add_ignore_pass_case(self): # Here we put some skip rules to avoid known bugs def teller1(program_config, predictor_config): x_shape = list(program_config.inputs["x"].shape) reduce_mean_dim = program_config.ops[0].attrs["dim"] if reduce_mean_dim[-1] != len(x_shape) - 1: return True for i in range(1, len(reduce_mean_dim)): if reduce_mean_dim[i] - reduce_mean_dim[i - 1] != 1: return True return False self.add_ignore_check_case( teller1, IgnoreReasons.PASS_ACCURACY_ERROR, "Use bad case to test pass.", ) def sample_program_config(self, draw): # 1. Generate shape of input:X x_shape = draw( st.lists( st.integers( min_value=1, max_value=8), min_size=4, max_size=5)) x_shape_rank = len(x_shape) # 2. Generate attrs of reduce_mean keep_dim = draw(st.booleans()) reduce_all = False begin_norm_axis = draw( st.integers( min_value=1, max_value=x_shape_rank - 1)) if begin_norm_axis == x_shape_rank - 1 and draw(st.booleans()): reduce_mean_dim = [-1] else: reduce_mean_dim = [i for i in range(x_shape_rank)] reduce_mean_dim = reduce_mean_dim[begin_norm_axis:] error_test_ratio = draw(st.integers(min_value=1, max_value=10)) if error_test_ratio > 9: keep_dim = True reduce_mean_dim = [1, ] elif error_test_ratio > 8: keep_dim = True begin_norm_axis = 1 reduce_mean_dim = [1, x_shape_rank - 1] # 3. Generate attrs of elementwise_sub sub_axis = 0 if keep_dim and draw(st.booleans()): sub_axis = -1 # 4. Generate data of pow pow_axis = -1 def generate_pow_data(): return np.array([2, ], dtype="float32") # 5. Generate attrs of elementwise_add if keep_dim: add_axis = draw( st.integers( min_value=-1, max_value=x_shape_rank - 1)) else: add_axis = draw( st.integers( min_value=-1, max_value=begin_norm_axis - 1)) def generate_epsilon_data(): return np.array([1e-5, ], dtype="float32") # 6. Generate attrs of elementwise_div div_axis = 0 if keep_dim and draw(st.booleans()): sub_axis = -1 # 6. Generate attrs gamma、beta mul_axis = -1 if draw(st.booleans()): mul_axis = begin_norm_axis add_axis2 = -1 if draw(st.booleans()): add_axis2 = begin_norm_axis gamma_shape = x_shape[begin_norm_axis:] beta_shape = gamma_shape[:] mean_op1 = OpConfig( "reduce_mean", inputs={"X": ["x"], }, outputs={"Out": ["mean_out"]}, dim=reduce_mean_dim, keep_dim=keep_dim, reduce_all=reduce_all, ) sub_op = OpConfig( "elementwise_sub", inputs={"X": ["x"], "Y": ["mean_out"]}, outputs={"Out": ["sub_out"]}, axis=sub_axis, ) pow_op = OpConfig( "elementwise_pow", inputs={"X": ["sub_out"], "Y": ["pow_y"]}, outputs={"Out": ["pow_out"]}, axis=pow_axis, ) mean_op2 = OpConfig( "reduce_mean", inputs={"X": ["pow_out"], }, outputs={"Out": ["mean_out2"]}, dim=reduce_mean_dim, keep_dim=keep_dim, reduce_all=reduce_all, ) add_op = OpConfig( "elementwise_add", inputs={"X": ["mean_out2"], "Y": ["epsilon_var"]}, outputs={"Out": ["add_out"]}, axis=add_axis, ) sqrt_op = OpConfig( "sqrt", inputs={"X": ["add_out"], }, outputs={"Out": ["sqrt_out"]}, ) div_op = OpConfig( "elementwise_div", inputs={"X": ["sub_out"], "Y": ["sqrt_out"]}, outputs={"Out": ["div_out"]}, axis=div_axis, ) mul_op = OpConfig( "elementwise_mul", inputs={"X": ["div_out"], "Y": ["gamma_var"]}, outputs={"Out": ["mul_out"]}, axis=mul_axis, ) add_op2 = OpConfig( "elementwise_add", inputs={"X": ["mul_out"], "Y": ["beta_var"]}, outputs={"Out": ["add_out2"]}, axis=add_axis2, ) ops = [ mean_op1, sub_op, pow_op, mean_op2, add_op, sqrt_op, div_op, mul_op, add_op2 ] program_config = ProgramConfig( ops=ops, weights={ "pow_y": TensorConfig(data_gen=generate_pow_data), "epsilon_var": TensorConfig(data_gen=generate_epsilon_data), "gamma_var": TensorConfig(shape=gamma_shape), "beta_var": TensorConfig(shape=beta_shape), }, inputs={"x": TensorConfig(shape=x_shape), }, outputs=ops[-1].outputs["Out"], ) return program_config def test(self): self.run_and_statis( quant=False, max_examples=300, passes=["layer_norm_fuse_pass"], ) if __name__ == "__main__": unittest.main()
[ "hypothesis.strategies.integers", "program_config.TensorConfig", "numpy.array", "hypothesis.strategies.booleans", "unittest.main", "program_config.OpConfig" ]
[((7829, 7844), 'unittest.main', 'unittest.main', ([], {}), '()\n', (7842, 7844), False, 'import unittest\n'), ((5184, 5326), 'program_config.OpConfig', 'OpConfig', (['"""reduce_mean"""'], {'inputs': "{'X': ['x']}", 'outputs': "{'Out': ['mean_out']}", 'dim': 'reduce_mean_dim', 'keep_dim': 'keep_dim', 'reduce_all': 'reduce_all'}), "('reduce_mean', inputs={'X': ['x']}, outputs={'Out': ['mean_out']},\n dim=reduce_mean_dim, keep_dim=keep_dim, reduce_all=reduce_all)\n", (5192, 5326), False, 'from program_config import TensorConfig, ProgramConfig, OpConfig\n'), ((5417, 5534), 'program_config.OpConfig', 'OpConfig', (['"""elementwise_sub"""'], {'inputs': "{'X': ['x'], 'Y': ['mean_out']}", 'outputs': "{'Out': ['sub_out']}", 'axis': 'sub_axis'}), "('elementwise_sub', inputs={'X': ['x'], 'Y': ['mean_out']}, outputs\n ={'Out': ['sub_out']}, axis=sub_axis)\n", (5425, 5534), False, 'from program_config import TensorConfig, ProgramConfig, OpConfig\n'), ((5618, 5737), 'program_config.OpConfig', 'OpConfig', (['"""elementwise_pow"""'], {'inputs': "{'X': ['sub_out'], 'Y': ['pow_y']}", 'outputs': "{'Out': ['pow_out']}", 'axis': 'pow_axis'}), "('elementwise_pow', inputs={'X': ['sub_out'], 'Y': ['pow_y']},\n outputs={'Out': ['pow_out']}, axis=pow_axis)\n", (5626, 5737), False, 'from program_config import TensorConfig, ProgramConfig, OpConfig\n'), ((5824, 5979), 'program_config.OpConfig', 'OpConfig', (['"""reduce_mean"""'], {'inputs': "{'X': ['pow_out']}", 'outputs': "{'Out': ['mean_out2']}", 'dim': 'reduce_mean_dim', 'keep_dim': 'keep_dim', 'reduce_all': 'reduce_all'}), "('reduce_mean', inputs={'X': ['pow_out']}, outputs={'Out': [\n 'mean_out2']}, dim=reduce_mean_dim, keep_dim=keep_dim, reduce_all=\n reduce_all)\n", (5832, 5979), False, 'from program_config import TensorConfig, ProgramConfig, OpConfig\n'), ((6064, 6192), 'program_config.OpConfig', 'OpConfig', (['"""elementwise_add"""'], {'inputs': "{'X': ['mean_out2'], 'Y': ['epsilon_var']}", 'outputs': "{'Out': ['add_out']}", 'axis': 'add_axis'}), "('elementwise_add', inputs={'X': ['mean_out2'], 'Y': ['epsilon_var'\n ]}, outputs={'Out': ['add_out']}, axis=add_axis)\n", (6072, 6192), False, 'from program_config import TensorConfig, ProgramConfig, OpConfig\n'), ((6277, 6351), 'program_config.OpConfig', 'OpConfig', (['"""sqrt"""'], {'inputs': "{'X': ['add_out']}", 'outputs': "{'Out': ['sqrt_out']}"}), "('sqrt', inputs={'X': ['add_out']}, outputs={'Out': ['sqrt_out']})\n", (6285, 6351), False, 'from program_config import TensorConfig, ProgramConfig, OpConfig\n'), ((6410, 6532), 'program_config.OpConfig', 'OpConfig', (['"""elementwise_div"""'], {'inputs': "{'X': ['sub_out'], 'Y': ['sqrt_out']}", 'outputs': "{'Out': ['div_out']}", 'axis': 'div_axis'}), "('elementwise_div', inputs={'X': ['sub_out'], 'Y': ['sqrt_out']},\n outputs={'Out': ['div_out']}, axis=div_axis)\n", (6418, 6532), False, 'from program_config import TensorConfig, ProgramConfig, OpConfig\n'), ((6617, 6740), 'program_config.OpConfig', 'OpConfig', (['"""elementwise_mul"""'], {'inputs': "{'X': ['div_out'], 'Y': ['gamma_var']}", 'outputs': "{'Out': ['mul_out']}", 'axis': 'mul_axis'}), "('elementwise_mul', inputs={'X': ['div_out'], 'Y': ['gamma_var']},\n outputs={'Out': ['mul_out']}, axis=mul_axis)\n", (6625, 6740), False, 'from program_config import TensorConfig, ProgramConfig, OpConfig\n'), ((6826, 6950), 'program_config.OpConfig', 'OpConfig', (['"""elementwise_add"""'], {'inputs': "{'X': ['mul_out'], 'Y': ['beta_var']}", 'outputs': "{'Out': ['add_out2']}", 'axis': 'add_axis2'}), "('elementwise_add', inputs={'X': ['mul_out'], 'Y': ['beta_var']},\n outputs={'Out': ['add_out2']}, axis=add_axis2)\n", (6834, 6950), False, 'from program_config import TensorConfig, ProgramConfig, OpConfig\n'), ((3290, 3303), 'hypothesis.strategies.booleans', 'st.booleans', ([], {}), '()\n', (3301, 3303), True, 'import hypothesis.strategies as st\n'), ((3376, 3428), 'hypothesis.strategies.integers', 'st.integers', ([], {'min_value': '(1)', 'max_value': '(x_shape_rank - 1)'}), '(min_value=1, max_value=x_shape_rank - 1)\n', (3387, 3428), True, 'import hypothesis.strategies as st\n'), ((3727, 3765), 'hypothesis.strategies.integers', 'st.integers', ([], {'min_value': '(1)', 'max_value': '(10)'}), '(min_value=1, max_value=10)\n', (3738, 3765), True, 'import hypothesis.strategies as st\n'), ((4259, 4289), 'numpy.array', 'np.array', (['[2]'], {'dtype': '"""float32"""'}), "([2], dtype='float32')\n", (4267, 4289), True, 'import numpy as np\n'), ((4677, 4711), 'numpy.array', 'np.array', (['[1e-05]'], {'dtype': '"""float32"""'}), "([1e-05], dtype='float32')\n", (4685, 4711), True, 'import numpy as np\n'), ((4930, 4943), 'hypothesis.strategies.booleans', 'st.booleans', ([], {}), '()\n', (4941, 4943), True, 'import hypothesis.strategies as st\n'), ((5024, 5037), 'hypothesis.strategies.booleans', 'st.booleans', ([], {}), '()\n', (5035, 5037), True, 'import hypothesis.strategies as st\n'), ((3102, 3139), 'hypothesis.strategies.integers', 'st.integers', ([], {'min_value': '(1)', 'max_value': '(8)'}), '(min_value=1, max_value=8)\n', (3113, 3139), True, 'import hypothesis.strategies as st\n'), ((3503, 3516), 'hypothesis.strategies.booleans', 'st.booleans', ([], {}), '()\n', (3514, 3516), True, 'import hypothesis.strategies as st\n'), ((4108, 4121), 'hypothesis.strategies.booleans', 'st.booleans', ([], {}), '()\n', (4119, 4121), True, 'import hypothesis.strategies as st\n'), ((4406, 4459), 'hypothesis.strategies.integers', 'st.integers', ([], {'min_value': '(-1)', 'max_value': '(x_shape_rank - 1)'}), '(min_value=-1, max_value=x_shape_rank - 1)\n', (4417, 4459), True, 'import hypothesis.strategies as st\n'), ((4541, 4597), 'hypothesis.strategies.integers', 'st.integers', ([], {'min_value': '(-1)', 'max_value': '(begin_norm_axis - 1)'}), '(min_value=-1, max_value=begin_norm_axis - 1)\n', (4552, 4597), True, 'import hypothesis.strategies as st\n'), ((4811, 4824), 'hypothesis.strategies.booleans', 'st.booleans', ([], {}), '()\n', (4822, 4824), True, 'import hypothesis.strategies as st\n'), ((7255, 7295), 'program_config.TensorConfig', 'TensorConfig', ([], {'data_gen': 'generate_pow_data'}), '(data_gen=generate_pow_data)\n', (7267, 7295), False, 'from program_config import TensorConfig, ProgramConfig, OpConfig\n'), ((7328, 7372), 'program_config.TensorConfig', 'TensorConfig', ([], {'data_gen': 'generate_epsilon_data'}), '(data_gen=generate_epsilon_data)\n', (7340, 7372), False, 'from program_config import TensorConfig, ProgramConfig, OpConfig\n'), ((7403, 7434), 'program_config.TensorConfig', 'TensorConfig', ([], {'shape': 'gamma_shape'}), '(shape=gamma_shape)\n', (7415, 7434), False, 'from program_config import TensorConfig, ProgramConfig, OpConfig\n'), ((7464, 7494), 'program_config.TensorConfig', 'TensorConfig', ([], {'shape': 'beta_shape'}), '(shape=beta_shape)\n', (7476, 7494), False, 'from program_config import TensorConfig, ProgramConfig, OpConfig\n'), ((7536, 7563), 'program_config.TensorConfig', 'TensorConfig', ([], {'shape': 'x_shape'}), '(shape=x_shape)\n', (7548, 7563), False, 'from program_config import TensorConfig, ProgramConfig, OpConfig\n')]
__author__ = 'yzhu' __version__ = '0.1' import json import datetime import time import matplotlib.pyplot as plt from matplotlib.collections import PatchCollection from matplotlib.patches import Polygon import numpy as np from skimage.draw import polygon import urllib import copy import itertools import os from pycocotools.coco import COCO from pycocotools import mask import PIL.ImageDraw as ImageDraw import PIL.Image as Image import cv2 class Amodal(COCO): def __init__(self, annotation_file=None, verbose=True): """ Constructor of Microsoft COCO helper class for reading and visualizing annotations. :param annotation_file (str): location of annotation file :param image_folder (str): location to the folder that hosts images. :return: """ COCO.__init__(self, annotation_file) self.verbose = verbose def createIndex(self): # create index print('creating index...') anns = {} imgToAnns = {} imgs = {} regions = [] if 'annotations' in self.dataset: imgToAnns = {ann['image_id']: [] for ann in self.dataset['annotations']} anns = {ann['id']: [] for ann in self.dataset['annotations']} for ann in self.dataset['annotations']: imgToAnns[ann['image_id']] += [ann] anns[ann['id']] = ann for region in ann['regions']: region['image_id'] = ann['image_id'] regions.append(region) if 'images' in self.dataset: imgs = {im['id']: {} for im in self.dataset['images']} for img in self.dataset['images']: imgs[img['id']] = img print('index created!') # create class members self.anns = anns self.imgToAnns = imgToAnns self.imgs = imgs self.regions = regions def getAmodalAnnIds(self, imgIds=[]): """ Get amodal ann id that satisfy given fiter conditions. :param imgIds (int array): get anns for given imgs :return: ids (int array) : integer array of ann ids """ imgIds = imgIds if type(imgIds) == list else [imgIds] if len(imgIds) == 0: anns = self.dataset['annotations'] else: lists = [self.imgToAnns[imgId] for imgId in imgIds if imgId in self.imgToAnns] anns = list(itertools.chain.from_iterable(lists)) ids = [ann['id'] for ann in anns] return ids def getImgIds(self, imgIds=[], catIds=[]): ''' Get img ids that satisfy given filter conditions. :param imgIds (int array) : get imgs for given ids :param catIds (int array) : get imgs with all given cats :return: ids (int array) : integer array of img ids ''' imgIds = imgIds if type(imgIds) == list else [imgIds] catIds = catIds if type(catIds) == list else [catIds] if len(imgIds) == len(catIds) == 0: ids = self.imgs.keys() else: ids = set(imgIds) for i, catId in enumerate(catIds): if i == 0 and len(ids) == 0: ids = set(self.catToImgs[catId]) else: ids &= set(self.catToImgs[catId]) return list(ids) def showAmodalAnns(self, anns): """ Display a set of amodal Ann object. :param anns: a dict object return: None """ if type(anns) == list: print("anns cannot be a list! Should be a dict.") return 0 ax = plt.gca() polygons = [] lines = [] color = [] for ann in reversed(anns['regions']): c = np.random.random((1, 3)).tolist()[0] if type(ann['segmentation']) == list: # polygon seg = ann['segmentation'] poly = np.array(seg).reshape((len(seg)//2, 2)) polygons.append(Polygon(poly, True, alpha=0.2)) color.append(c) p = PatchCollection(polygons, facecolors=color, edgecolors=(1,1,1,1), linewidths=3, alpha=0.2) ax.add_collection(p) #color.append(c) else: self.showMask(ann['segmentation'], ax,c) #raise NotImplementedError def showEdgeMap(self, anns): """ Show edge map for an annontation :param anns: a dict object return: None """ if type(anns) == list: print("anns cannot be a list! Should be a dict") return 0 ax = plt.gca() polygons = [] lines = [] color = [] for ann in reversed(anns['regions']): c = np.zeros([1, 3]).tolist()[0] if type(ann['segmentation']) == list: # polygon seg = ann['segmentation'] poly = np.array(seg).reshape((len(seg)//2, 2)) polygons.append(Polygon(poly, True, alpha=0.2)) p = PatchCollection(polygons, facecolors=color, edgecolors=(1,1,1,1), linewidths=1, alpha=1) ax.add_collection(p) #color.append(c) else: self.showMask(ann['segmentation'], ax) def getMask(self, M): m = mask.decode([M]) img = np.ones( (m.shape[0], m.shape[1], 3) ) # get boundary quickly kernel_size = m.shape[0]//40 kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (kernel_size, kernel_size)) dilation = cv2.dilate(m, kernel) B = dilation[:,:,None] - m # B = np.zeros( (m.shape[0], m.shape[1]) ) # for aa in range(m.shape[0]-1): # for bb in range(m.shape[1]-1): # #kk = aa*m.shape[1]+bb # if m[aa,bb] != m[aa,bb+1]: # B[aa,bb], B[aa,bb+1] = 1,1 # if m[aa,bb] != m[aa+1,bb]: # B[aa,bb], B[aa+1,bb] = 1,1 # if m[aa,bb] != m[aa+1,bb+1]: # B[aa,bb], B[aa+1,bb+1] = 1,1 return m,B def showMask(self, M, ax, c = [0, 1, 0]): m,B = self.getMask(M) img = np.ones( (m.shape[0], m.shape[1], 3) ) for i in range(3): img[:, :, i] = c[i];ax.imshow(np.dstack( (img, m*0.5) )) img[:, :, i] = 1;ax.imshow(np.dstack( (img, B*1) )) def getAnnMask(self,ann,w,h,fill_color=255): if type(ann['segmentation']) == list: # polygon seg = ann['segmentation'] img = Image.new("L", (w, h)) draw = ImageDraw.Draw(img) draw.polygon(seg, fill= int(fill_color)) all_mask = np.asarray( img, dtype="uint8" ) else: all_mask,B = self.getMask(ann['segmentation']) all_mask = np.squeeze(all_mask) if 'invisible_mask' in ann: invisible_mask,boundary = self.getMask(ann['invisible_mask']) invisible_mask[invisible_mask>0] = fill_color invisible_mask = np.squeeze(invisible_mask) invisible_mask = np.squeeze(invisible_mask) return all_mask,invisible_mask.astype('uint8') else: return all_mask,[] def getAnnMask2(self,ann,w,h,fill_color=255): if type(ann['segmentation']) == list: # polygon seg = ann['segmentation'] img = Image.new("L", (w, h)) draw = ImageDraw.Draw(img) draw.polygon(seg, fill= int(fill_color)) all_mask = np.asarray( img, dtype="uint8" ) else: all_mask,B = self.getMask(ann['segmentation']) all_mask = np.squeeze(all_mask) if 'visible_mask' in ann: visible_mask,boundary = self.getMask(ann['visible_mask']) visible_mask[visible_mask>0] = fill_color visible_mask = np.squeeze(visible_mask) visible_mask = np.squeeze(visible_mask) return all_mask,visible_mask.astype('uint8') else: return all_mask,[] def getAmodalInstance(self,anns,w,h,k=-1): """ return k-th visualable/unvisualable mask k: the depth order of anns, 1-index. If k = -1, just visulize mask """ fill_color = 255 if type(anns) == list: print("ann cannot be a list! Should be a dict") return 0 if k < 0: layer_visible_mask = np.ones((h,w))*255 for ann in anns['regions']: all_mask,invisible_mask,_ = self.getAnnMask(ann,w,h,fill_color) if type(invisible_mask)==list: layer_visible_mask += all_mask else: layer_visible_mask += all_mask-invisible_mask return layer_visible_mask.astype('uint8') else: ann = anns['regions'][k] return self.getAnnMask(ann,w,h,fill_color) def showAmodalInstance(self, anns, k=-1): """ Display k-th instance only: print segmentation first, then print invisible_mask anns: a single annotation k: the depth order of anns, 1-index. If k = -1, just visulize input """ ax = plt.gca() c = np.random.random((1,3)).tolist()[0] c = [0.0, 1.0, 0.0] # green if k < 0: self.showMask(anns['segmentation'], ax) return if type(anns) == list: print("ann cannot be a list! Should be a dict") return 0 ann = anns['regions'][k] polygons = [] color = [] # draw whole mask if type(ann['segmentation']) == list: # polygon seg = ann['segmentation'] poly = np.array(seg).reshape((len(seg)//2, 2)) polygons.append(Polygon(poly, True, alpha=0.2)) color.append(c) p = PatchCollection(polygons, facecolors=color, edgecolors=(1,1,1,1), linewidths=3, alpha=0.2) ax.add_collection(p) else: self.showMask(ann['segmentation'], ax) # draw invisible_mask if 'visible_mask' in ann: self.showMask(ann['visible_mask'], ax, [0, 0, 0]) def showModalInstance(self, anns, k): """ Display k-th instance: print its visible mask anns: a single annotation k: the depth order of anns, 1-index """ if type(anns) == list: print("ann cannot be a list! Should be a dict") return 0 ax = plt.gca() c = np.random.random((1,3)).tolist()[0] c = [0.0, 1.0, 0.0] # green ann = anns['regions'][k-1] polygons = [] color = [] # draw whole mask if 'visible_mask' in ann: mm = mask.decode([ann['visible_mask']]) img = np.ones( (mm.shape[0], mm.shape[1], 3) ) color_mask = c for i in range(3): img[:, :, i] = color_mask[i] ax.imshow(np.dstack( (img, mm*0.6) )) else: if type(ann['segmentation']) == list: # polygon seg = ann['segmentation'] poly = np.array(seg).reshape((len(seg)//2, 2)) polygons.append(Polygon(poly, True, alpha=0.2)) color.append(c) else: #mask mm = mask.decode([ann['segmentation']]) img = np.ones( (mm.shape[0], mm.shape[1], 3) ) color_mask = c for i in range(3): img[:, :, i] = color_mask[i] ax.imshow(np.dstack( (img, mm*0.6) )) p = PatchCollection(polygons, facecolors=color, edgecolors=(0,0,0,1), linewidths=3, alpha=0.4) ax.add_collection(p) def loadRes(self, resFile): """ Load result file and return a result api object. :param resFile (str) : file name of result file :return: res (obj) : result api object """ res = Amodal() res.dataset['images'] = [img for img in self.dataset['images']] if self.verbose: print('Loading and preparing results...') tic = time.time() anns = json.load(open(resFile)) assert type(anns) == list, 'results in not an array of objects' annsImgIds = [ann['image_id'] for ann in anns] assert set(annsImgIds) == (set(annsImgIds) & set(self.getImgIds())), \ 'Results do not correspond to current coco set' if self.verbose: print('DONE (t=%0.2fs)'%(time.time()- tic)) res.dataset['annotations'] = anns res.createIndex() return res
[ "numpy.dstack", "numpy.ones", "numpy.random.random", "matplotlib.pyplot.gca", "pycocotools.mask.decode", "PIL.Image.new", "numpy.asarray", "numpy.squeeze", "matplotlib.collections.PatchCollection", "itertools.chain.from_iterable", "PIL.ImageDraw.Draw", "numpy.array", "numpy.zeros", "time.t...
[((807, 843), 'pycocotools.coco.COCO.__init__', 'COCO.__init__', (['self', 'annotation_file'], {}), '(self, annotation_file)\n', (820, 843), False, 'from pycocotools.coco import COCO\n'), ((3631, 3640), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (3638, 3640), True, 'import matplotlib.pyplot as plt\n'), ((4660, 4669), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (4667, 4669), True, 'import matplotlib.pyplot as plt\n'), ((5376, 5392), 'pycocotools.mask.decode', 'mask.decode', (['[M]'], {}), '([M])\n', (5387, 5392), False, 'from pycocotools import mask\n'), ((5407, 5443), 'numpy.ones', 'np.ones', (['(m.shape[0], m.shape[1], 3)'], {}), '((m.shape[0], m.shape[1], 3))\n', (5414, 5443), True, 'import numpy as np\n'), ((5540, 5609), 'cv2.getStructuringElement', 'cv2.getStructuringElement', (['cv2.MORPH_RECT', '(kernel_size, kernel_size)'], {}), '(cv2.MORPH_RECT, (kernel_size, kernel_size))\n', (5565, 5609), False, 'import cv2\n'), ((5629, 5650), 'cv2.dilate', 'cv2.dilate', (['m', 'kernel'], {}), '(m, kernel)\n', (5639, 5650), False, 'import cv2\n'), ((6260, 6296), 'numpy.ones', 'np.ones', (['(m.shape[0], m.shape[1], 3)'], {}), '((m.shape[0], m.shape[1], 3))\n', (6267, 6296), True, 'import numpy as np\n'), ((6927, 6947), 'numpy.squeeze', 'np.squeeze', (['all_mask'], {}), '(all_mask)\n', (6937, 6947), True, 'import numpy as np\n'), ((7776, 7796), 'numpy.squeeze', 'np.squeeze', (['all_mask'], {}), '(all_mask)\n', (7786, 7796), True, 'import numpy as np\n'), ((9337, 9346), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (9344, 9346), True, 'import matplotlib.pyplot as plt\n'), ((10657, 10666), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (10664, 10666), True, 'import matplotlib.pyplot as plt\n'), ((12342, 12353), 'time.time', 'time.time', ([], {}), '()\n', (12351, 12353), False, 'import time\n'), ((6660, 6682), 'PIL.Image.new', 'Image.new', (['"""L"""', '(w, h)'], {}), "('L', (w, h))\n", (6669, 6682), True, 'import PIL.Image as Image\n'), ((6702, 6721), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['img'], {}), '(img)\n', (6716, 6721), True, 'import PIL.ImageDraw as ImageDraw\n'), ((6798, 6828), 'numpy.asarray', 'np.asarray', (['img'], {'dtype': '"""uint8"""'}), "(img, dtype='uint8')\n", (6808, 6828), True, 'import numpy as np\n'), ((7146, 7172), 'numpy.squeeze', 'np.squeeze', (['invisible_mask'], {}), '(invisible_mask)\n', (7156, 7172), True, 'import numpy as np\n'), ((7202, 7228), 'numpy.squeeze', 'np.squeeze', (['invisible_mask'], {}), '(invisible_mask)\n', (7212, 7228), True, 'import numpy as np\n'), ((7509, 7531), 'PIL.Image.new', 'Image.new', (['"""L"""', '(w, h)'], {}), "('L', (w, h))\n", (7518, 7531), True, 'import PIL.Image as Image\n'), ((7551, 7570), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['img'], {}), '(img)\n', (7565, 7570), True, 'import PIL.ImageDraw as ImageDraw\n'), ((7647, 7677), 'numpy.asarray', 'np.asarray', (['img'], {'dtype': '"""uint8"""'}), "(img, dtype='uint8')\n", (7657, 7677), True, 'import numpy as np\n'), ((7983, 8007), 'numpy.squeeze', 'np.squeeze', (['visible_mask'], {}), '(visible_mask)\n', (7993, 8007), True, 'import numpy as np\n'), ((8035, 8059), 'numpy.squeeze', 'np.squeeze', (['visible_mask'], {}), '(visible_mask)\n', (8045, 8059), True, 'import numpy as np\n'), ((10009, 10106), 'matplotlib.collections.PatchCollection', 'PatchCollection', (['polygons'], {'facecolors': 'color', 'edgecolors': '(1, 1, 1, 1)', 'linewidths': '(3)', 'alpha': '(0.2)'}), '(polygons, facecolors=color, edgecolors=(1, 1, 1, 1),\n linewidths=3, alpha=0.2)\n', (10024, 10106), False, 'from matplotlib.collections import PatchCollection\n'), ((10904, 10938), 'pycocotools.mask.decode', 'mask.decode', (["[ann['visible_mask']]"], {}), "([ann['visible_mask']])\n", (10915, 10938), False, 'from pycocotools import mask\n'), ((10957, 10995), 'numpy.ones', 'np.ones', (['(mm.shape[0], mm.shape[1], 3)'], {}), '((mm.shape[0], mm.shape[1], 3))\n', (10964, 10995), True, 'import numpy as np\n'), ((11799, 11896), 'matplotlib.collections.PatchCollection', 'PatchCollection', (['polygons'], {'facecolors': 'color', 'edgecolors': '(0, 0, 0, 1)', 'linewidths': '(3)', 'alpha': '(0.4)'}), '(polygons, facecolors=color, edgecolors=(0, 0, 0, 1),\n linewidths=3, alpha=0.4)\n', (11814, 11896), False, 'from matplotlib.collections import PatchCollection\n'), ((2434, 2470), 'itertools.chain.from_iterable', 'itertools.chain.from_iterable', (['lists'], {}), '(lists)\n', (2463, 2470), False, 'import itertools\n'), ((4098, 4195), 'matplotlib.collections.PatchCollection', 'PatchCollection', (['polygons'], {'facecolors': 'color', 'edgecolors': '(1, 1, 1, 1)', 'linewidths': '(3)', 'alpha': '(0.2)'}), '(polygons, facecolors=color, edgecolors=(1, 1, 1, 1),\n linewidths=3, alpha=0.2)\n', (4113, 4195), False, 'from matplotlib.collections import PatchCollection\n'), ((5103, 5198), 'matplotlib.collections.PatchCollection', 'PatchCollection', (['polygons'], {'facecolors': 'color', 'edgecolors': '(1, 1, 1, 1)', 'linewidths': '(1)', 'alpha': '(1)'}), '(polygons, facecolors=color, edgecolors=(1, 1, 1, 1),\n linewidths=1, alpha=1)\n', (5118, 5198), False, 'from matplotlib.collections import PatchCollection\n'), ((6380, 6405), 'numpy.dstack', 'np.dstack', (['(img, m * 0.5)'], {}), '((img, m * 0.5))\n', (6389, 6405), True, 'import numpy as np\n'), ((6446, 6469), 'numpy.dstack', 'np.dstack', (['(img, B * 1)'], {}), '((img, B * 1))\n', (6455, 6469), True, 'import numpy as np\n'), ((8557, 8572), 'numpy.ones', 'np.ones', (['(h, w)'], {}), '((h, w))\n', (8564, 8572), True, 'import numpy as np\n'), ((9933, 9963), 'matplotlib.patches.Polygon', 'Polygon', (['poly', '(True)'], {'alpha': '(0.2)'}), '(poly, True, alpha=0.2)\n', (9940, 9963), False, 'from matplotlib.patches import Polygon\n'), ((11123, 11149), 'numpy.dstack', 'np.dstack', (['(img, mm * 0.6)'], {}), '((img, mm * 0.6))\n', (11132, 11149), True, 'import numpy as np\n'), ((11503, 11537), 'pycocotools.mask.decode', 'mask.decode', (["[ann['segmentation']]"], {}), "([ann['segmentation']])\n", (11514, 11537), False, 'from pycocotools import mask\n'), ((11560, 11598), 'numpy.ones', 'np.ones', (['(mm.shape[0], mm.shape[1], 3)'], {}), '((mm.shape[0], mm.shape[1], 3))\n', (11567, 11598), True, 'import numpy as np\n'), ((4014, 4044), 'matplotlib.patches.Polygon', 'Polygon', (['poly', '(True)'], {'alpha': '(0.2)'}), '(poly, True, alpha=0.2)\n', (4021, 4044), False, 'from matplotlib.patches import Polygon\n'), ((5034, 5064), 'matplotlib.patches.Polygon', 'Polygon', (['poly', '(True)'], {'alpha': '(0.2)'}), '(poly, True, alpha=0.2)\n', (5041, 5064), False, 'from matplotlib.patches import Polygon\n'), ((9359, 9383), 'numpy.random.random', 'np.random.random', (['(1, 3)'], {}), '((1, 3))\n', (9375, 9383), True, 'import numpy as np\n'), ((9865, 9878), 'numpy.array', 'np.array', (['seg'], {}), '(seg)\n', (9873, 9878), True, 'import numpy as np\n'), ((10679, 10703), 'numpy.random.random', 'np.random.random', (['(1, 3)'], {}), '((1, 3))\n', (10695, 10703), True, 'import numpy as np\n'), ((11378, 11408), 'matplotlib.patches.Polygon', 'Polygon', (['poly', '(True)'], {'alpha': '(0.2)'}), '(poly, True, alpha=0.2)\n', (11385, 11408), False, 'from matplotlib.patches import Polygon\n'), ((11742, 11768), 'numpy.dstack', 'np.dstack', (['(img, mm * 0.6)'], {}), '((img, mm * 0.6))\n', (11751, 11768), True, 'import numpy as np\n'), ((3763, 3787), 'numpy.random.random', 'np.random.random', (['(1, 3)'], {}), '((1, 3))\n', (3779, 3787), True, 'import numpy as np\n'), ((3942, 3955), 'numpy.array', 'np.array', (['seg'], {}), '(seg)\n', (3950, 3955), True, 'import numpy as np\n'), ((4792, 4808), 'numpy.zeros', 'np.zeros', (['[1, 3]'], {}), '([1, 3])\n', (4800, 4808), True, 'import numpy as np\n'), ((4962, 4975), 'numpy.array', 'np.array', (['seg'], {}), '(seg)\n', (4970, 4975), True, 'import numpy as np\n'), ((11306, 11319), 'numpy.array', 'np.array', (['seg'], {}), '(seg)\n', (11314, 11319), True, 'import numpy as np\n'), ((12737, 12748), 'time.time', 'time.time', ([], {}), '()\n', (12746, 12748), False, 'import time\n')]
## # Copyright 2021 IBM Corp. All Rights Reserved. # # SPDX-License-Identifier: Apache-2.0 ## from typing import Tuple, List, Union import torch import numpy as np from ..._utils import val_clamp from ..parameters.node import _NodeParameters """ Node level activation """ class _NodeActivation(_NodeParameters): def __init__(self, *args, **kwds): super().__init__(*args, **kwds) self.Yt = self.alpha self.Yf = 1 - self.alpha def aggregate_bounds( self, grounding_rows: List[int] = None, new_bounds: torch.Tensor = None, bound: str = None, **kwds, ) -> torch.Tensor: """Proof aggregation to tighten existing bounds towards new bounds **Parameters** bound: ['lower', 'upper', None] specify individual bound to aggregate from if None [default], then both 'lower' and 'upper' bounds aggregate """ prev_bounds = self.get_facts(grounding_rows).clone() if kwds.get("logical_aggregation", False): raise NotImplementedError( "should not end here, logical" "aggregation not yet implemented" ) else: L = ( torch.max(prev_bounds[..., 0], new_bounds[..., 0]) if (bound in [None, "lower"]) else prev_bounds[..., 0] ) U = ( torch.min(prev_bounds[..., 1], new_bounds[..., 1]) if (bound in [None, "upper"]) else prev_bounds[..., 1] ) aggregate = torch.stack([L, U], dim=-1) self.update_bounds(grounding_rows, val_clamp(aggregate)) return (aggregate - prev_bounds).abs().sum() def output_regions(self, y: torch.Tensor) -> torch.Tensor: """classical region of outputs for the given node inputs Evaluates the classical region for a given y value (per bound) typically given as the output of a neuron activation function Regions: 1 - False 2 - Fuzzy False 3 - Midpoint (0.5) 4 - Fuzzy True 5 - True """ result = torch.zeros_like(y) result = result.masked_fill(y <= self.Yf, 1) result = result.masked_fill(bool_and(self.Yf < y, y < 0.5), 2) result = result.masked_fill(y == 0.5, 3) result = result.masked_fill(bool_and(0.5 < y, y < self.Yt), 4) result = result.masked_fill(self.Yt <= y, 5) if (result == 0).sum() > 0: raise Exception(f"output not in the feasible region [0, 1] for: {result}") return result def _get_state_vars( self, bounds: torch.Tensor = None ) -> Tuple[ torch.Tensor, np.ndarray, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor ]: bounds = self.get_facts() if bounds is None else bounds regions = self.output_regions(bounds).numpy().astype(dtype="<U3") L, U = regions[..., 0], regions[..., 1] result = np.zeros_like(L, dtype=float).astype(dtype="<U3") L_bounds, U_bounds = bounds[..., 0], bounds[..., 1] return bounds, result, L, U, L_bounds, U_bounds def is_contradiction( self, bounds: torch.Tensor = None, args: Tuple[ torch.Tensor, np.ndarray, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, ] = None, ) -> torch.BoolTensor: """check which bounds are in contradiction classical contradiction removed from states: F, T""" *_, L, U, L_bounds, U_bounds = args if args else (self._get_state_vars(bounds)) contradictions = bool_and( L_bounds > U_bounds, bool_and(L == "1.0", U == "1.0").logical_not(), bool_and(L == "5.0", U == "5.0").logical_not(), ) return contradictions def state(self, bounds: torch.Tensor = None) -> np.ndarray: """classical state of formula bounds. Combines the output regions of Lower, Upper bounds to determine the overall node state and collapses the bounds dimension **Returns** numpy char array: classical states: 'T' = True 'F' = False 'U' = Unknown 'C' = Contradiction fuzzy states: '~T' = More True than not True '~F' = More False than not False '~U' = Unknown but not classical '=U' = Unknown, exact midpoint Warning ------- Only works for output state of node bounds, not inputs to connectives """ args = self._get_state_vars(bounds) bounds, result, L, U, *_ = args result = np.where(bool_and(L == "1.0", U == "5.0"), "U", result) result = np.where(bool_and(L == "1.0", U == "1.0"), "F", result) result = np.where(bool_and(L == "5.0", U == "5.0"), "T", result) result = np.where(bool_and(L == "3.0", U == "3.0"), "=U", result) result = np.where(self.is_contradiction(args=args), "C", result) result = np.where(bool_and(L in ["1.0", "2.0"], U == "2.0"), "~F", result) result = np.where(bool_and(L == "4.0", U in ["4.0", "5.0"]), "~T", result) result = np.where( bool_or( bool_and(L == "1.0", U in ["3.0", "4.0"]), bool_and(L == "2.0", U in ["3.0", "4.0", "5.0"]), bool_and(L == "3.0", U in ["4.0", "5.0"]), ), "~U", result, ) if result == "0.0": raise Exception(f"bounds {L,U} fell in an unquantified state") return result def tensorise(t: Union[bool, torch.Tensor]) -> torch.Tensor: return ( t.clone().detach() if isinstance(t, torch.Tensor) else (torch.tensor(t).detach()) ) def bool_and(*args: bool) -> torch.BoolTensor: return bool_tensor("and", *args) def bool_or(*args: bool) -> torch.BoolTensor: return bool_tensor("or", *args) def bool_tensor(func: str, *args: bool) -> torch.BoolTensor: """""" tensor = tensorise(args[0]).to(dtype=torch.int8) for a in args[1:]: if func == "and": tensor = tensor * a elif func == "or": tensor = tensor + a return tensor.type(torch.bool)
[ "torch.stack", "torch.max", "torch.min", "torch.tensor", "torch.zeros_like", "numpy.zeros_like" ]
[((2189, 2208), 'torch.zeros_like', 'torch.zeros_like', (['y'], {}), '(y)\n', (2205, 2208), False, 'import torch\n'), ((1591, 1618), 'torch.stack', 'torch.stack', (['[L, U]'], {'dim': '(-1)'}), '([L, U], dim=-1)\n', (1602, 1618), False, 'import torch\n'), ((1229, 1279), 'torch.max', 'torch.max', (['prev_bounds[..., 0]', 'new_bounds[..., 0]'], {}), '(prev_bounds[..., 0], new_bounds[..., 0])\n', (1238, 1279), False, 'import torch\n'), ((1415, 1465), 'torch.min', 'torch.min', (['prev_bounds[..., 1]', 'new_bounds[..., 1]'], {}), '(prev_bounds[..., 1], new_bounds[..., 1])\n', (1424, 1465), False, 'import torch\n'), ((3034, 3063), 'numpy.zeros_like', 'np.zeros_like', (['L'], {'dtype': 'float'}), '(L, dtype=float)\n', (3047, 3063), True, 'import numpy as np\n'), ((5910, 5925), 'torch.tensor', 'torch.tensor', (['t'], {}), '(t)\n', (5922, 5925), False, 'import torch\n')]
# ___________________________________________________________________________ # # Prescient # Copyright 2020 National Technology & Engineering Solutions of Sandia, LLC # (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S. # Government retains certain rights in this software. # This software is distributed under the Revised BSD License. # ___________________________________________________________________________ """ markov_chains.py This will house the machinery used to make random walks using Markov Chains. For this purpose, it will export a MarkovChain Class which can be used to create random walks. """ import datetime from collections import OrderedDict import numpy as np from .markov_chains import states from .. import sources class MarkovError(Exception): pass class MarkovChain: """ This class represents a Markov Chain from which random walks can be generated. The user passes in a list of states, a transition mapping and a start state. This class overloads the __iter__ and __next__ methods, so it can be iterated over using all the list methods. Attributes: current_state: The current state of the process Args: states (List[State]): A list of states of the process, can be State objects, but just needs to be a hashable object with an equality operator defined. transition_func: One of three things: 1. A function from the state space to itself 2. A dictionary mapping states to another dictionary mapping states to transition probabilities. {State -> {State -> probability}} In this way if A is this dictionary, A[S1][S2] is the probability of transitioning from state S1 to state S2. 3. A numpy matrix of probabilities, the order of rows must match order of states passed in start_state (State): Optional, This specifies the start state, It can be a function which when called returns the start state. If not passed in, the first state in the list is assumed to be the start state end_state (State): Optional, this specifies what state to end at, can be a list of states, or a function to test if at an end state. """ def __init__(self, states, transition_func, start_state=None, end_state=None): self.states = states if callable(transition_func): self.transition_function = transition_func elif isinstance(transition_func, dict): self.transition_function = self._func_from_dict(transition_func) elif isinstance(transition_func, np.matrix): self.transition_function = self._func_from_matrix(transition_func) # current_state being None means has not gotten to start state self.current_state = None self.start_state = start_state self.end_state = end_state def _func_from_matrix(self, matrix): """ Generates a transition function from a transition matrix. This is necessarily probabilistic. It generates a number uniformly on [0,1] and then iterates through the states accumulating probabilities. Once the accumulated probability is greater than the random number, iteration stops and the current state is returned. """ # To find the next state, # We generate a random number between 0 and 1 self.n, _ = matrix.shape self.matrix = matrix def f(state): random_number = np.random.rand() cum_prob = 0 curr_index = self.states.index(self.current_state) # Then we accumulate the probabilities over the current state row for i in range(self.n): state_prob = self.matrix[curr_index,i] cum_prob += state_prob if random_number < cum_prob: next_index = i return self.states[next_index] else: raise MarkovError("There is no transition from state {}" .format(state)) return f def _func_from_dict(self, mapping): """ Generates a transition function from a mapping of the form {State -> {State -> probability}} This is necessarily probabilistic. It generates a number uniformly on [0,1] and then iterates through the states accumulating probabilities. Once the accumulated probability is greater than the random number, iteration stops and the current state is returned. """ self.mapping = mapping def f(state): # To find the next state, # We generate a random number between 0 and 1 random_number = np.random.rand() cum_prob = 0 # Then we accumulate the probabilities over the current state row for state in self.mapping[self.current_state]: state_probability = self.mapping[self.current_state][state] cum_prob += state_probability if random_number < cum_prob: return state else: raise MarkovError("There is no transition from state {}" .format(state)) return f def _pick_start_state(self): """ Sets the current state attribute to the start state """ start_state = self.start_state if start_state is None: # If no start_state passed in, we assume first state is start self.current_state = self.states[0] elif callable(start_state): # If start_state is a function, we call it to get first state self.current_state = start_state() else: # Otherwise, what is passed in is a state self.current_state = start_state def step(self): """ Moves the current state attribute to the next state according to the function. Picks a start state if current state is None. """ if self.current_state is None: self._pick_start_state() else: if self.is_end_state(self.current_state): raise StopIteration self.current_state = self.transition_function(self.current_state) def is_end_state(self, state): """ This function checks if the passed in state is an end state. """ if self.end_state is None: return False elif isinstance(self.end_state, states.State): return state == self.end_state elif isinstance(self.end_state, list): return state in self.end_state elif callable(self.end_state): return self.end_state(state) else: return state == self.end_state def reset(self): """ Sets the current state attribute to None, so the Markov Chain can be run again. """ self.current_state = None def random_walk(self, n=None): """ This generates states and yields them (so it does not create a list in memory). This should not be called in conjunction with other methods which change the current state as then the walk generated may not correspond to an actual walk. This resets the current state whenever it is called. Args: n (int): The number of steps taken in the random walk, not passed in if want to generate states indefinitely """ self.reset() if n is None: while True: self.step() yield self.current_state else: for _ in range(n): self.step() yield self.current_state def __iter__(self): return self def __next__(self): self.step() return self.current_state def increment(mapping, state, next_state, count=1): """ Increments mapping[state][next_state], creating entries if need be Specify count you want to increment by something other than 1. Args: mapping (dict[State,dict[State,int]]): The transition counts state (State): The state of first state next_state (State): The state to transition to count (int): The amount to increment by """ if state in mapping: if next_state in mapping[state]: mapping[state][next_state] += count else: mapping[state][next_state] = count else: mapping[state] = {next_state:count} def mapping_from_walk(walk, memory=1): """ From a sequence of states, generates the count map from which one state transitions to another. This is stored as a dictionary of the form {State -> {State -> count}}. The memory argument means to consider the frequency n states transition to the next n states. For example, if we have states [A, B, A, A] and set memory = 2, our mapping would be {(A, B): {(B, A): 1}, (B, A): {(A, A): 1}} If memory > 1, the keys in the dictionary will be tuples of states Args: walk (List[State]): A sequence of states memory (int): A number representing how many states to use for memory """ count_map = {} if memory == 1: for (state, next_state) in zip(walk, walk[1:]): increment(count_map, state, next_state) else: offsets = [walk[i:] for i in range(memory)] state_tuples = list(zip(*offsets)) for (state, next_state) in zip(state_tuples, state_tuples[1:]): increment(count_map, state, next_state) return count_map def merge_maps(maps): """ Merges counts of transitions from multiple different mappings into a single mapping. Args: maps (List[dict]): A list of mappings, these should be dictionaries of States mapped to dictionaries of States mapped to numbers {State -> {State -> int}} Returns: dict: A dictionary of the merged counts """ merged = {} for mapping in maps: for state in mapping: for next_state in mapping[state]: count = mapping[state][next_state] increment(merged, state, next_state, count) return merged def normalize_map(mapping): """ Creates a new dictionary with the frequency of each transition. Each state transition count is normalized by the total number of transitions out of a given state. Args: maps (List[dict]): A list of mappings, these should be dictionaries of States mapped to dictionaries of States mapped to numbers {State -> {State -> int}} Returns: dict: A dictionary of the normalized counts """ normalized_dict = {} for word in mapping: normalized_dict[word] = {} count = sum(mapping[word].values()) for other in mapping[word]: normalized_dict[word][other] = mapping[word][other] / count return normalized_dict def matrix_from_mapping(mapping): """ From a mapping of the form {State -> {State -> probability}}, it creates an equivalent transition matrix. Note if the mapping is just a dictionary, not an OrderedDict, the ordering of the rows on the matrix will be nondeterministic. Args: mapping (dict): A dictionary mapping pairs of states to probabilities Returns: (np.Matrix): A numpy transition matrix """ states = list(mapping) n = len(states) matrix = np.matrix(np.zeros((n,n))) for i, state in enumerate(states): for j, next_state in enumerate(states): matrix[i,j] = mapping[state].get(next_state, 0) return matrix def generate_equal_probability_matrix(n): """ Generates a nxn transition matrix where the probability of any given transition is the same Args: n (int): The dimensions of the matrix Returns: np.matrix: The matrix desired """ num_array = np.ones((n,n)) * (1/n) return np.matrix(num_array) def sort_dictionary(dictionary): """ This function will turn a dictionary with sortable keys into an OrderedDict with keys in the ordering of the keys. This dictionary will have two levels of nesting as it will be a mapping of the sort {State -> {State -> value}} Args: dictionary (dict): The dictionary to be sorted Returns: OrderedDict: The sorted dictionary """ ordered = OrderedDict() for outer_key in sorted(dictionary): inner_ordered = OrderedDict() for inner_key in sorted(dictionary[outer_key]): inner_ordered[inner_key] = dictionary[outer_key][inner_key] ordered[outer_key] = inner_ordered return ordered def matrix_from_walk(state_walk, memory=1): """ This function will construct a transition matrix from a sequence of states encoded in an OrderedDict. The state_walk is an OrderedDict which maps datetimes to States, and this function will count how many times between consecutive hours, one state switches to another. From this, we compute the frequency of each transition and compute the matrix. In addition, we can consider transitions from combinations of states to other combinations of states. How many states is specified by the memory argument. For example if we had the states [A, B, C] with memory=2, we would record one transition from (A, B) to (B, C). This will attempt to sort the states. Args: state_walk (OrderedDict[datetime,State]): A mapping from datetimes to states memory (int): How many states to consider as a single state. Returns: (List[State], np.matrix): The order of the states and the matrix """ segments = create_consecutive_segments(state_walk) mappings = [mapping_from_walk(list(segment.values()), memory) for segment in segments] merged = merge_maps(mappings) normalized_map = normalize_map(merged) final_mapping = sort_dictionary(normalized_map) return list(final_mapping), matrix_from_mapping(final_mapping) def date_range(start, end): """ Generates all datetimes between the start and end date. This function should work with any datetime object which supports addition with datetime.timedelta. Datetimes are separated by one hour each. Args: start (datetime-like): The start datetime end (datetime-like): The end datetime """ current_datetime = start while current_datetime != end: yield current_datetime current_datetime += datetime.timedelta(hours=1) yield current_datetime def create_consecutive_segments(date_indexed_dict): """ This function breaks up a datetime indexed dictionary into the consecutive segments of datetimes. While iterating through the datetimes, if it finds any hourly gap in the data, it breaks the dictionary into two dictionaries. At the end, it will have a list of dictionaries, where each dictionary has no gaps. Args: date_indexed_dict (dict[datetime,State]): A datetime indexed dictionary Returns: List[dict]: List of dictionaries for which the indices are consecutive and are separated by one hour """ min_date = min(date_indexed_dict) max_date = max(date_indexed_dict) segments = [] # We have a flag for when we need to start a new dictionary create_new = True for dt in date_range(min_date, max_date): if create_new: current_dictionary = OrderedDict() segments.append(current_dictionary) create_new = False # We create a new dictionary whenever we reach a datetime which is # not in the original dictionary, but the next datetime is if (dt not in date_indexed_dict and dt+datetime.timedelta(hours=1) in date_indexed_dict): create_new = True else: if dt in date_indexed_dict: current_dictionary[dt] = date_indexed_dict[dt] return segments
[ "collections.OrderedDict", "numpy.ones", "numpy.random.rand", "datetime.timedelta", "numpy.zeros", "numpy.matrix" ]
[((12523, 12543), 'numpy.matrix', 'np.matrix', (['num_array'], {}), '(num_array)\n', (12532, 12543), True, 'import numpy as np\n'), ((12975, 12988), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (12986, 12988), False, 'from collections import OrderedDict\n'), ((12022, 12038), 'numpy.zeros', 'np.zeros', (['(n, n)'], {}), '((n, n))\n', (12030, 12038), True, 'import numpy as np\n'), ((12489, 12504), 'numpy.ones', 'np.ones', (['(n, n)'], {}), '((n, n))\n', (12496, 12504), True, 'import numpy as np\n'), ((13054, 13067), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (13065, 13067), False, 'from collections import OrderedDict\n'), ((15126, 15153), 'datetime.timedelta', 'datetime.timedelta', ([], {'hours': '(1)'}), '(hours=1)\n', (15144, 15153), False, 'import datetime\n'), ((3955, 3971), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (3969, 3971), True, 'import numpy as np\n'), ((5188, 5204), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (5202, 5204), True, 'import numpy as np\n'), ((16089, 16102), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (16100, 16102), False, 'from collections import OrderedDict\n'), ((16384, 16411), 'datetime.timedelta', 'datetime.timedelta', ([], {'hours': '(1)'}), '(hours=1)\n', (16402, 16411), False, 'import datetime\n')]
# SPDX-License-Identifier: BSD-3-Clause # Copyright (c) 2022 Osyris contributors (https://github.com/osyris-project/osyris) from common import arrayclose, arraytrue, arrayequal from osyris import Array, units from copy import copy, deepcopy import numpy as np from pint.errors import DimensionalityError import pytest def test_constructor_ndarray(): a = np.arange(100.) array = Array(values=a, unit='m') assert array.unit == units('m') assert len(array) == len(a) assert array.shape == a.shape assert np.array_equal(array.values, a) def test_constructor_list(): alist = [1., 2., 3., 4., 5.] array = Array(values=alist, unit='s') assert array.unit == units('s') assert np.array_equal(array.values, alist) def test_constructor_int(): num = 15 array = Array(values=num, unit='m') assert array.unit == units('m') assert np.array_equal(array.values, np.array(num)) def test_constructor_float(): num = 154.77 array = Array(values=num, unit='m') assert array.unit == units('m') assert np.array_equal(array.values, np.array(num)) def test_constructor_quantity(): q = 6.7 * units('K') array = Array(values=q) assert array.unit == units('K') assert np.array_equal(array.values, np.array(q.magnitude)) def test_bad_constructor_quantity_with_unit(): q = 6.7 * units('K') with pytest.raises(ValueError): _ = Array(values=q, unit='s') def test_constructor_masked_array(): a = np.arange(5.) b = np.ma.masked_where(a > 2, a) array = Array(values=b, unit='m') assert array.unit == units('m') assert len(array) == len(b) assert array.shape == b.shape assert np.array_equal(array.values, b) assert np.array_equal(array.values.mask, [False, False, False, True, True]) def test_addition(): a = Array(values=[1., 2., 3., 4., 5.], unit='m') b = Array(values=[6., 7., 8., 9., 10.], unit='m') expected = Array(values=[7., 9., 11., 13., 15.], unit='m') assert arrayclose(a + b, expected) def test_addition_conversion(): a = Array(values=[1., 2., 3., 4., 5.], unit='m') b = Array(values=[6., 7., 8., 9., 10.], unit='cm') expected = Array(values=[1.06, 2.07, 3.08, 4.09, 5.1], unit='m') assert arrayclose(a + b, expected) def test_addition_bad_units(): a = Array(values=[1., 2., 3., 4., 5.], unit='m') b = Array(values=[6., 7., 8., 9., 10.], unit='s') with pytest.raises(DimensionalityError): _ = a + b with pytest.raises(TypeError): _ = a + 3.0 def test_addition_quantity(): a = Array(values=[1., 2., 3., 4., 5.], unit='m') b = 3.5 * units('m') expected = Array(values=[4.5, 5.5, 6.5, 7.5, 8.5], unit='m') assert arrayclose(a + b, expected) def test_addition_inplace(): a = Array(values=[1., 2., 3., 4., 5.], unit='m') b = Array(values=[6., 7., 8., 9., 10.], unit='m') expected = Array(values=[7., 9., 11., 13., 15.], unit='m') a += b assert arrayclose(a, expected) def test_addition_quantity_inplace(): a = Array(values=[1., 2., 3., 4., 5.], unit='m') b = 3.5 * units('m') expected = Array(values=[4.5, 5.5, 6.5, 7.5, 8.5], unit='m') a += b assert arrayclose(a, expected) def test_subtraction(): a = Array(values=[1., 2., 3., 4., 5.], unit='m') b = Array(values=[6., 7., 8., 9., 10.], unit='m') expected = Array(values=[5., 5., 5., 5., 5.], unit='m') assert arrayclose(b - a, expected) def test_subtraction_bad_units(): a = Array(values=[1., 2., 3., 4., 5.], unit='m') b = Array(values=[6., 7., 8., 9., 10.], unit='s') with pytest.raises(DimensionalityError): _ = a - b with pytest.raises(TypeError): _ = a - 3.0 def test_subtraction_quantity(): a = Array(values=[1., 2., 3., 4., 5.], unit='m') b = 3.5 * units('m') expected = Array(values=[-2.5, -1.5, -0.5, 0.5, 1.5], unit='m') assert arrayclose(a - b, expected) def test_subtraction_inplace(): a = Array(values=[1., 2., 3., 4., 5.], unit='m') b = Array(values=[6., 7., 8., 9., 10.], unit='m') expected = Array(values=[5., 5., 5., 5., 5.], unit='m') b -= a assert arrayclose(b, expected) def test_subtraction_quantity_inplace(): a = Array(values=[1., 2., 3., 4., 5.], unit='m') b = 3.5 * units('m') expected = Array(values=[-2.5, -1.5, -0.5, 0.5, 1.5], unit='m') a -= b assert arrayclose(a, expected) def test_multiplication(): a = Array(values=[1., 2., 3., 4., 5.], unit='m') b = Array(values=[6., 7., 8., 9., 10.], unit='m') expected = Array(values=[6., 14., 24., 36., 50.], unit='m*m') assert arrayclose(a * b, expected) def test_multiplication_conversion(): a = Array(values=[1., 2., 3., 4., 5.], unit='m') b = Array(values=[6., 7., 8., 9., 10.], unit='cm') expected = Array(values=[0.06, 0.14, 0.24, 0.36, 0.5], unit='m*m') assert arrayclose(a * b, expected) def test_multiplication_float(): a = Array(values=[1., 2., 3., 4., 5.], unit='m') b = 3.0 expected = Array(values=[3., 6., 9., 12., 15.], unit='m') assert arrayclose(a * b, expected) assert arrayclose(b * a, expected) def test_multiplication_ndarray(): a = Array(values=[1., 2., 3., 4., 5.], unit='m') b = np.arange(5.) expected = Array(values=[0., 2., 6., 12., 20.], unit='m') assert arrayclose(a * b, expected) assert arrayclose(b * a, expected) def test_multiplication_quantity(): a = Array(values=[1., 2., 3., 4., 5.], unit='m') b = 3.5 * units('s') expected = Array(values=[3.5, 7.0, 10.5, 14.0, 17.5], unit='m*s') assert arrayclose(a * b, expected) def test_multiplication_inplace(): a = Array(values=[1., 2., 3., 4., 5.], unit='m') b = Array(values=[6., 7., 8., 9., 10.], unit='m') expected = Array(values=[6., 14., 24., 36., 50.], unit='m*m') a *= b assert arrayclose(a, expected) def test_multiplication_float_inplace(): a = Array(values=[1., 2., 3., 4., 5.], unit='m') b = 3.0 expected = Array(values=[3., 6., 9., 12., 15.], unit='m') a *= b assert arrayclose(a, expected) def test_multiplication_ndarray_inplace(): a = Array(values=[1., 2., 3., 4., 5.], unit='m') b = np.arange(5.) expected = Array(values=[0., 2., 6., 12., 20.], unit='m') a *= b assert arrayclose(a, expected) def test_multiplication_quantity_inplace(): a = Array(values=[1., 2., 3., 4., 5.], unit='m') b = 3.5 * units('s') expected = Array(values=[3.5, 7.0, 10.5, 14.0, 17.5], unit='m*s') a *= b assert arrayclose(a, expected) def test_division(): a = Array(values=[1., 2., 3., 4., 5.], unit='s') b = Array(values=[6., 7., 8., 9., 10.], unit='m') expected = Array(values=[6., 3.5, 8. / 3., 2.25, 2.], unit='m/s') assert arrayclose(b / a, expected) def test_division_float(): a = Array(values=[1., 2., 3., 4., 5.], unit='s') b = 3.0 expected = Array(values=[1. / 3., 2. / 3., 1., 4. / 3., 5. / 3.], unit='s') assert arrayclose(a / b, expected) expected = Array(values=[3., 3. / 2., 1., 3. / 4., 3. / 5.], unit='1/s') assert arrayclose(b / a, expected) def test_division_ndarray(): a = Array(values=[1., 2., 3., 4., 5.], unit='s') b = np.arange(5., 10.) expected = Array(values=[1. / 5., 2. / 6., 3. / 7., 4. / 8., 5. / 9.], unit='s') assert arrayclose(a / b, expected) # expected = Array(values=[3., 3. / 2., 1., 3. / 4., 3. / 5.], unit='1/s') # assert arrayclose(b / a, expected) def test_division_quantity(): a = Array(values=[0., 2., 4., 6., 200.], unit='s') b = 2.0 * units('s') expected = Array(values=[0., 1., 2., 3., 100.], unit='dimensionless') assert arrayclose(a / b, expected) def test_division_inplace(): a = Array(values=[1., 2., 3., 4., 5.], unit='s') b = Array(values=[6., 7., 8., 9., 10.], unit='m') expected = Array(values=[6., 3.5, 8. / 3., 2.25, 2.], unit='m/s') b /= a assert arrayclose(b, expected) def test_division_float_inplace(): a = Array(values=[1., 2., 3., 4., 5.], unit='s') b = 3.0 expected = Array(values=[1. / 3., 2. / 3., 1., 4. / 3., 5. / 3.], unit='s') a /= b assert arrayclose(a, expected) def test_division_ndarray_inplace(): a = Array(values=[1., 2., 3., 4., 5.], unit='s') b = np.arange(5., 10.) expected = Array(values=[1. / 5., 2. / 6., 3. / 7., 4. / 8., 5. / 9.], unit='s') a /= b assert arrayclose(a, expected) # expected = Array(values=[3., 3. / 2., 1., 3. / 4., 3. / 5.], unit='1/s') # assert arrayclose(b / a, expected) def test_division_quantity_inplace(): a = Array(values=[0., 2., 4., 6., 200.], unit='s') b = 2.0 * units('s') expected = Array(values=[0., 1., 2., 3., 100.], unit='dimensionless') a /= b assert arrayclose(a, expected) def test_power(): a = Array(values=[1., 2., 4., 6., 200.], unit='s') expected = Array(values=[1., 8., 64., 216., 8.0e6], unit='s**3') assert arrayclose(a**3, expected) def test_negative(): a = Array(values=[1., 2., 4., 6., 200.], unit='s') expected = Array(values=[-1., -2., -4., -6., -200.], unit='s') assert arrayequal(-a, expected) def test_equal(): a = Array(values=[1., 2., 3., 4., 5.], unit='m') b = Array(values=[11., 2., 3., 4.1, 5.], unit='m') expected = [False, True, True, False, True] assert all((a == b).values == expected) def test_equal_conversion(): a = Array(values=[1., 2., 3., 4., 5.], unit='m') b = Array(values=[1100., 200., 300., 410., 500.], unit='cm') expected = [False, True, True, False, True] assert all((a == b).values == expected) def test_equal_bad_units(): a = Array(values=[1., 2., 3., 4., 5.], unit='m') b = Array(values=[11., 2., 3., 4.1, 5.], unit='s') with pytest.raises(DimensionalityError): _ = a == b def test_equal_ndarray(): a = Array(values=[1., 2., 3., 4., 5.]) b = np.array([11., 2., 3., 4.1, 5.]) expected = [False, True, True, False, True] assert all((a == b).values == expected) a.unit = 'm' with pytest.raises(DimensionalityError): _ = a == b def test_equal_float(): a = Array(values=[1., 2., 3., 4., 5.]) b = 3. expected = [False, False, True, False, False] assert all((a == b).values == expected) a.unit = 'm' with pytest.raises(DimensionalityError): _ = a == b def test_equal_quantity(): a = Array(values=[1., 2., 3., 4., 5.], unit='m') b = 3. * units('m') expected = [False, False, True, False, False] assert all((a == b).values == expected) b = 3. * units('s') with pytest.raises(DimensionalityError): _ = a == b def test_not_equal(): a = Array(values=[1., 2., 3., 4., 5.], unit='m') b = Array(values=[11., 2., 3., 4.1, 5.], unit='m') expected = [True, False, False, True, False] assert all((a != b).values == expected) def test_not_equal_conversion(): a = Array(values=[1., 2., 3., 4., 5.], unit='m') b = Array(values=[1100., 200., 300., 410., 500.], unit='cm') expected = [True, False, False, True, False] assert all((a != b).values == expected) def test_not_equal_bad_units(): a = Array(values=[1., 2., 3., 4., 5.], unit='m') b = Array(values=[11., 2., 3., 4.1, 5.], unit='s') with pytest.raises(DimensionalityError): _ = a != b def test_not_equal_ndarray(): a = Array(values=[1., 2., 3., 4., 5.]) b = np.array([11., 2., 3., 4.1, 5.]) expected = [True, False, False, True, False] assert all((a != b).values == expected) a.unit = 'm' with pytest.raises(DimensionalityError): _ = a != b def test_not_equal_float(): a = Array(values=[1., 2., 3., 4., 5.]) b = 3. expected = [True, True, False, True, True] assert all((a != b).values == expected) a.unit = 'm' with pytest.raises(DimensionalityError): _ = a != b def test_not_equal_quantity(): a = Array(values=[1., 2., 3., 4., 5.], unit='m') b = 3. * units('m') expected = [True, True, False, True, True] assert all((a != b).values == expected) b = 3. * units('s') with pytest.raises(DimensionalityError): _ = a != b def test_less_than(): a = Array(values=[1., 2., 3., 4., 5.], unit='s') b = Array(values=[6., 7., 1., 4., 10.], unit='s') expected = [True, True, False, False, True] assert all((a < b).values == expected) def test_less_than_conversion(): a = Array(values=[1., 2., 3., 4., 5.], unit='m') b = Array(values=[600., 700., 100., 400., 1000.], unit='cm') expected = [True, True, False, False, True] assert all((a < b).values == expected) def test_less_than_bad_units(): a = Array(values=[1., 2., 3., 4., 5.], unit='s') b = Array(values=[6., 7., 1., 4., 10.], unit='m') with pytest.raises(DimensionalityError): _ = a < b def test_less_than_ndarray(): a = Array(values=[1., 2., 3., 4., 5.]) b = np.array([6., 7., 1., 4., 10.]) expected = [True, True, False, False, True] assert all((a < b).values == expected) a.unit = 'm' with pytest.raises(DimensionalityError): _ = a < b def test_less_than_float(): a = Array(values=[1., 2., 3., 4., 5.]) b = 3. expected = [True, True, False, False, False] assert all((a < b).values == expected) a.unit = 'm' with pytest.raises(DimensionalityError): _ = a < b def test_less_than_quantity(): a = Array(values=[1., 2., 3., 4., 5.], unit='m') b = 3. * units('m') expected = [True, True, False, False, False] assert all((a < b).values == expected) b = 3. * units('s') with pytest.raises(DimensionalityError): _ = a < b def test_less_equal(): a = Array(values=[1., 2., 3., 4., 5.], unit='s') b = Array(values=[6., 7., 1., 4., 10.], unit='s') expected = [True, True, False, True, True] assert all((a <= b).values == expected) def test_less_equal_bad_units(): a = Array(values=[1., 2., 3., 4., 5.], unit='s') b = Array(values=[6., 7., 1., 4., 10.], unit='m') with pytest.raises(DimensionalityError): _ = a <= b def test_less_equal_ndarray(): a = Array(values=[1., 2., 3., 4., 5.]) b = np.array([6., 7., 1., 4., 10.]) expected = [True, True, False, True, True] assert all((a <= b).values == expected) a.unit = 'm' with pytest.raises(DimensionalityError): _ = a < b def test_less_equal_float(): a = Array(values=[1., 2., 3., 4., 5.]) b = 3. expected = [True, True, True, False, False] assert all((a <= b).values == expected) a.unit = 'm' with pytest.raises(DimensionalityError): _ = a < b def test_less_equal_quantity(): a = Array(values=[1., 2., 3., 4., 5.], unit='m') b = 3. * units('m') expected = [True, True, True, False, False] assert all((a <= b).values == expected) b = 3. * units('s') with pytest.raises(DimensionalityError): _ = a < b def test_greater_than(): a = Array(values=[1., 2., 3., 4., 5.], unit='s') b = Array(values=[6., 7., 1., 4., 10.], unit='s') expected = [True, True, False, False, True] assert all((b > a).values == expected) def test_greater_than_bad_units(): a = Array(values=[1., 2., 3., 4., 5.], unit='s') b = Array(values=[6., 7., 1., 4., 10.], unit='K') with pytest.raises(DimensionalityError): _ = b > a def test_greater_than_ndarray(): a = Array(values=[1., 2., 3., 4., 5.]) b = np.array([6., 7., 1., 4., 10.]) expected = [False, False, True, False, False] assert all((a > b).values == expected) a.unit = 'm' with pytest.raises(DimensionalityError): _ = a > b def test_greater_than_float(): a = Array(values=[1., 2., 3., 4., 5.]) b = 3. expected = [False, False, False, True, True] assert all((a > b).values == expected) a.unit = 'm' with pytest.raises(DimensionalityError): _ = a > b def test_greater_than_quantity(): a = Array(values=[1., 2., 3., 4., 5.], unit='m') b = 3. * units('m') expected = [False, False, False, True, True] assert all((a > b).values == expected) b = 3. * units('s') with pytest.raises(DimensionalityError): _ = a > b def test_greater_equal(): a = Array(values=[1., 2., 3., 4., 5.], unit='s') b = Array(values=[6., 7., 1., 4., 10.], unit='s') expected = [True, True, False, True, True] assert all((b >= a).values == expected) def test_greater_equal_bad_units(): a = Array(values=[1., 2., 3., 4., 5.], unit='s') b = Array(values=[6., 7., 1., 4., 10.], unit='K') with pytest.raises(DimensionalityError): _ = b >= a def test_greater_equal_ndarray(): a = Array(values=[1., 2., 3., 4., 5.]) b = np.array([6., 7., 1., 4., 10.]) expected = [False, False, True, True, False] assert all((a >= b).values == expected) a.unit = 'm' with pytest.raises(DimensionalityError): _ = a >= b def test_greater_equal_float(): a = Array(values=[1., 2., 3., 4., 5.]) b = 3. expected = [False, False, True, True, True] assert all((a >= b).values == expected) a.unit = 'm' with pytest.raises(DimensionalityError): _ = a >= b def test_greater_equal_quantity(): a = Array(values=[1., 2., 3., 4., 5.], unit='m') b = 3. * units('m') expected = [False, False, True, True, True] assert all((a >= b).values == expected) b = 3. * units('s') with pytest.raises(DimensionalityError): _ = a >= b def test_logical_and(): a = Array(values=[True, True, True, False, False, False]) b = Array(values=[True, False, True, False, True, False]) expected = [True, False, True, False, False, False] assert all((b & a).values == expected) def test_logical_or(): a = Array(values=[True, True, True, False, False, False]) b = Array(values=[True, False, True, False, True, False]) expected = [True, True, True, False, True, False] assert all((b | a).values == expected) def test_logical_xor(): a = Array(values=[True, True, True, False, False, False]) b = Array(values=[True, False, True, False, True, False]) expected = [False, True, False, False, True, False] assert all((b ^ a).values == expected) def test_logical_invert(): a = Array(values=[True, True, False, False, True, False]) expected = [False, False, True, True, False, True] assert all((~a).values == expected) def test_to(): a = Array(values=[1., 2., 3., 4., 5.], unit='m') b = Array(values=[1.0e-3, 2.0e-3, 3.0e-3, 4.0e-3, 5.0e-3], unit='km') assert arrayclose(a.to('km'), b) assert a.unit == units('m') def test_to_bad_units(): a = Array(values=[1., 2., 3., 4., 5.], unit='m') with pytest.raises(DimensionalityError): _ = a.to('s') def test_min(): a = Array(values=[1., -2., 3., 0.4, 0.5, 0.6], unit='m') assert (a.min() == Array(values=-2., unit='m')).values b = Array(values=np.array([1., -2., 3., 0.4, 0.5, 0.6]).reshape(2, 3), unit='m') assert (b.min() == Array(values=-2., unit='m')).values def test_max(): a = Array(values=[1., 2., 3., -15., 5., 6.], unit='m') assert (a.max() == Array(values=6.0, unit='m')).values b = Array(values=np.array([1., 2., 3., -15., 5., 6.]).reshape(2, 3), unit='m') assert (b.max() == Array(values=6.0, unit='m')).values def test_reshape(): a = Array(values=[1., 2., 3., 4., 5., 6.], unit='m') expected = Array(values=[[1., 2., 3.], [4., 5., 6.]], unit='m') assert arraytrue(np.ravel(a.reshape(2, 3) == expected)) def test_slicing(): a = Array(values=[11., 12., 13., 14., 15.], unit='m') assert a[2] == Array(values=[13.], unit='m') assert arraytrue(a[:4] == Array(values=[11., 12., 13., 14.], unit='m')) assert arraytrue(a[2:4] == Array(values=[13., 14.], unit='m')) def test_slicing_vector(): a = Array(values=np.arange(12.).reshape(4, 3), unit='m') assert arraytrue(np.ravel(a[2:3] == Array(values=[[6., 7., 8.]], unit='m'))) assert a[2:3].shape == (1, 3) assert arraytrue( np.ravel(a[:2] == Array(values=[[0., 1., 2.], [3., 4., 5.]], unit='m'))) def test_copy(): a = Array(values=[11., 12., 13., 14., 15.], unit='m') b = a.copy() a *= 10. assert arraytrue(b == Array(values=[11., 12., 13., 14., 15.], unit='m')) def test_copy_overload(): a = Array(values=[11., 12., 13., 14., 15.], unit='m') b = copy(a) a *= 10. assert arraytrue(b == Array(values=[11., 12., 13., 14., 15.], unit='m')) def test_deepcopy(): a = Array(values=[11., 12., 13., 14., 15.], unit='m') b = deepcopy(a) a *= 10. assert arraytrue(b == Array(values=[11., 12., 13., 14., 15.], unit='m')) def test_numpy_unary(): values = [1., 2., 3., 4., 5.] a = Array(values=values, unit='m') expected = np.log10(values) result = np.log10(a) assert np.allclose(result.values, expected) assert result.unit == units('m') def test_numpy_sqrt(): values = [1., 2., 3., 4., 5.] a = Array(values=values, unit='m*m') expected = np.sqrt(values) result = np.sqrt(a) assert np.allclose(result.values, expected) assert result.unit == units('m') def test_numpy_binary(): a_buf = [1., 2., 3., 4., 5.] b_buf = [6., 7., 8., 9., 10.] a = Array(values=a_buf, unit='m') b = Array(values=b_buf, unit='m') expected = np.dot(a_buf, b_buf) result = np.dot(a, b) assert result.values == expected assert result.unit == units('m') def test_numpy_iterable(): a_buf = [1., 2., 3., 4., 5.] b_buf = [6., 7., 8., 9., 10.] a = Array(values=a_buf, unit='m') b = Array(values=b_buf, unit='m') expected = np.concatenate([a_buf, b_buf]) result = np.concatenate([a, b]) assert np.array_equal(result.values, expected) assert result.unit == units('m') def test_numpy_multiply_with_ndarray(): a_buf = [1., 2., 3., 4., 5.] a = Array(values=a_buf, unit='m') b = np.array([6., 7., 8., 9., 10.]) expected = np.multiply(a_buf, b) result = np.multiply(a, b) assert np.array_equal(result.values, expected) assert result.unit == units('m') result = np.multiply(b, a) assert np.array_equal(result.values, expected) assert result.unit == units('m') def test_numpy_multiply_with_quantity(): a_buf = [1., 2., 3., 4., 5.] a = Array(values=a_buf, unit='m') b = 3.5 * units('s') expected = np.multiply(a_buf, b.magnitude) result = np.multiply(a, b) assert np.array_equal(result.values, expected) assert result.unit == units('m*s') def test_numpy_multiply_with_float(): a_buf = [1., 2., 3., 4., 5.] a = Array(values=a_buf, unit='m') b = 3.5 expected = np.multiply(a_buf, b) result = np.multiply(a, b) assert np.array_equal(result.values, expected) assert result.unit == units('m') result = np.multiply(b, a) assert np.array_equal(result.values, expected) assert result.unit == units('m') def test_numpy_divide_with_ndarray(): a_buf = [1., 2., 3., 4., 5.] a = Array(values=a_buf, unit='m') b = np.array([6., 7., 8., 9., 10.]) expected = np.divide(a_buf, b) result = np.divide(a, b) assert np.array_equal(result.values, expected) assert result.unit == units('m') expected = np.divide(b, a_buf) result = np.divide(b, a) assert np.array_equal(result.values, expected) assert result.unit == units('1/m') def test_numpy_divide_with_quantity(): a_buf = [1., 2., 3., 4., 5.] a = Array(values=a_buf, unit='m') b = 3.5 * units('s') expected = np.divide(a_buf, b.magnitude) result = np.divide(a, b) assert np.array_equal(result.values, expected) assert result.unit == units('m/s') def test_numpy_divide_with_float(): a_buf = [1., 2., 3., 4., 5.] a = Array(values=a_buf, unit='m') b = 3.5 expected = np.divide(a_buf, b) result = np.divide(a, b) assert np.array_equal(result.values, expected) assert result.unit == units('m') expected = np.divide(b, a_buf) result = np.divide(b, a) assert np.array_equal(result.values, expected) assert result.unit == units('1/m')
[ "numpy.multiply", "numpy.log10", "copy.deepcopy", "numpy.allclose", "numpy.sqrt", "numpy.divide", "numpy.ma.masked_where", "osyris.Array", "numpy.array", "numpy.dot", "common.arrayclose", "numpy.array_equal", "numpy.concatenate", "common.arrayequal", "pytest.raises", "copy.copy", "os...
[((360, 376), 'numpy.arange', 'np.arange', (['(100.0)'], {}), '(100.0)\n', (369, 376), True, 'import numpy as np\n'), ((388, 413), 'osyris.Array', 'Array', ([], {'values': 'a', 'unit': '"""m"""'}), "(values=a, unit='m')\n", (393, 413), False, 'from osyris import Array, units\n'), ((527, 558), 'numpy.array_equal', 'np.array_equal', (['array.values', 'a'], {}), '(array.values, a)\n', (541, 558), True, 'import numpy as np\n'), ((635, 664), 'osyris.Array', 'Array', ([], {'values': 'alist', 'unit': '"""s"""'}), "(values=alist, unit='s')\n", (640, 664), False, 'from osyris import Array, units\n'), ((712, 747), 'numpy.array_equal', 'np.array_equal', (['array.values', 'alist'], {}), '(array.values, alist)\n', (726, 747), True, 'import numpy as np\n'), ((803, 830), 'osyris.Array', 'Array', ([], {'values': 'num', 'unit': '"""m"""'}), "(values=num, unit='m')\n", (808, 830), False, 'from osyris import Array, units\n'), ((983, 1010), 'osyris.Array', 'Array', ([], {'values': 'num', 'unit': '"""m"""'}), "(values=num, unit='m')\n", (988, 1010), False, 'from osyris import Array, units\n'), ((1174, 1189), 'osyris.Array', 'Array', ([], {'values': 'q'}), '(values=q)\n', (1179, 1189), False, 'from osyris import Array, units\n'), ((1484, 1498), 'numpy.arange', 'np.arange', (['(5.0)'], {}), '(5.0)\n', (1493, 1498), True, 'import numpy as np\n'), ((1506, 1534), 'numpy.ma.masked_where', 'np.ma.masked_where', (['(a > 2)', 'a'], {}), '(a > 2, a)\n', (1524, 1534), True, 'import numpy as np\n'), ((1547, 1572), 'osyris.Array', 'Array', ([], {'values': 'b', 'unit': '"""m"""'}), "(values=b, unit='m')\n", (1552, 1572), False, 'from osyris import Array, units\n'), ((1686, 1717), 'numpy.array_equal', 'np.array_equal', (['array.values', 'b'], {}), '(array.values, b)\n', (1700, 1717), True, 'import numpy as np\n'), ((1729, 1797), 'numpy.array_equal', 'np.array_equal', (['array.values.mask', '[False, False, False, True, True]'], {}), '(array.values.mask, [False, False, False, True, True])\n', (1743, 1797), True, 'import numpy as np\n'), ((1829, 1878), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]', 'unit': '"""m"""'}), "(values=[1.0, 2.0, 3.0, 4.0, 5.0], unit='m')\n", (1834, 1878), False, 'from osyris import Array, units\n'), ((1882, 1932), 'osyris.Array', 'Array', ([], {'values': '[6.0, 7.0, 8.0, 9.0, 10.0]', 'unit': '"""m"""'}), "(values=[6.0, 7.0, 8.0, 9.0, 10.0], unit='m')\n", (1887, 1932), False, 'from osyris import Array, units\n'), ((1943, 1995), 'osyris.Array', 'Array', ([], {'values': '[7.0, 9.0, 11.0, 13.0, 15.0]', 'unit': '"""m"""'}), "(values=[7.0, 9.0, 11.0, 13.0, 15.0], unit='m')\n", (1948, 1995), False, 'from osyris import Array, units\n'), ((2002, 2029), 'common.arrayclose', 'arrayclose', (['(a + b)', 'expected'], {}), '(a + b, expected)\n', (2012, 2029), False, 'from common import arrayclose, arraytrue, arrayequal\n'), ((2072, 2121), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]', 'unit': '"""m"""'}), "(values=[1.0, 2.0, 3.0, 4.0, 5.0], unit='m')\n", (2077, 2121), False, 'from osyris import Array, units\n'), ((2125, 2176), 'osyris.Array', 'Array', ([], {'values': '[6.0, 7.0, 8.0, 9.0, 10.0]', 'unit': '"""cm"""'}), "(values=[6.0, 7.0, 8.0, 9.0, 10.0], unit='cm')\n", (2130, 2176), False, 'from osyris import Array, units\n'), ((2187, 2240), 'osyris.Array', 'Array', ([], {'values': '[1.06, 2.07, 3.08, 4.09, 5.1]', 'unit': '"""m"""'}), "(values=[1.06, 2.07, 3.08, 4.09, 5.1], unit='m')\n", (2192, 2240), False, 'from osyris import Array, units\n'), ((2252, 2279), 'common.arrayclose', 'arrayclose', (['(a + b)', 'expected'], {}), '(a + b, expected)\n', (2262, 2279), False, 'from common import arrayclose, arraytrue, arrayequal\n'), ((2321, 2370), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]', 'unit': '"""m"""'}), "(values=[1.0, 2.0, 3.0, 4.0, 5.0], unit='m')\n", (2326, 2370), False, 'from osyris import Array, units\n'), ((2374, 2424), 'osyris.Array', 'Array', ([], {'values': '[6.0, 7.0, 8.0, 9.0, 10.0]', 'unit': '"""s"""'}), "(values=[6.0, 7.0, 8.0, 9.0, 10.0], unit='s')\n", (2379, 2424), False, 'from osyris import Array, units\n'), ((2578, 2627), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]', 'unit': '"""m"""'}), "(values=[1.0, 2.0, 3.0, 4.0, 5.0], unit='m')\n", (2583, 2627), False, 'from osyris import Array, units\n'), ((2663, 2712), 'osyris.Array', 'Array', ([], {'values': '[4.5, 5.5, 6.5, 7.5, 8.5]', 'unit': '"""m"""'}), "(values=[4.5, 5.5, 6.5, 7.5, 8.5], unit='m')\n", (2668, 2712), False, 'from osyris import Array, units\n'), ((2724, 2751), 'common.arrayclose', 'arrayclose', (['(a + b)', 'expected'], {}), '(a + b, expected)\n', (2734, 2751), False, 'from common import arrayclose, arraytrue, arrayequal\n'), ((2791, 2840), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]', 'unit': '"""m"""'}), "(values=[1.0, 2.0, 3.0, 4.0, 5.0], unit='m')\n", (2796, 2840), False, 'from osyris import Array, units\n'), ((2844, 2894), 'osyris.Array', 'Array', ([], {'values': '[6.0, 7.0, 8.0, 9.0, 10.0]', 'unit': '"""m"""'}), "(values=[6.0, 7.0, 8.0, 9.0, 10.0], unit='m')\n", (2849, 2894), False, 'from osyris import Array, units\n'), ((2905, 2957), 'osyris.Array', 'Array', ([], {'values': '[7.0, 9.0, 11.0, 13.0, 15.0]', 'unit': '"""m"""'}), "(values=[7.0, 9.0, 11.0, 13.0, 15.0], unit='m')\n", (2910, 2957), False, 'from osyris import Array, units\n'), ((2975, 2998), 'common.arrayclose', 'arrayclose', (['a', 'expected'], {}), '(a, expected)\n', (2985, 2998), False, 'from common import arrayclose, arraytrue, arrayequal\n'), ((3047, 3096), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]', 'unit': '"""m"""'}), "(values=[1.0, 2.0, 3.0, 4.0, 5.0], unit='m')\n", (3052, 3096), False, 'from osyris import Array, units\n'), ((3132, 3181), 'osyris.Array', 'Array', ([], {'values': '[4.5, 5.5, 6.5, 7.5, 8.5]', 'unit': '"""m"""'}), "(values=[4.5, 5.5, 6.5, 7.5, 8.5], unit='m')\n", (3137, 3181), False, 'from osyris import Array, units\n'), ((3204, 3227), 'common.arrayclose', 'arrayclose', (['a', 'expected'], {}), '(a, expected)\n', (3214, 3227), False, 'from common import arrayclose, arraytrue, arrayequal\n'), ((3262, 3311), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]', 'unit': '"""m"""'}), "(values=[1.0, 2.0, 3.0, 4.0, 5.0], unit='m')\n", (3267, 3311), False, 'from osyris import Array, units\n'), ((3315, 3365), 'osyris.Array', 'Array', ([], {'values': '[6.0, 7.0, 8.0, 9.0, 10.0]', 'unit': '"""m"""'}), "(values=[6.0, 7.0, 8.0, 9.0, 10.0], unit='m')\n", (3320, 3365), False, 'from osyris import Array, units\n'), ((3376, 3425), 'osyris.Array', 'Array', ([], {'values': '[5.0, 5.0, 5.0, 5.0, 5.0]', 'unit': '"""m"""'}), "(values=[5.0, 5.0, 5.0, 5.0, 5.0], unit='m')\n", (3381, 3425), False, 'from osyris import Array, units\n'), ((3432, 3459), 'common.arrayclose', 'arrayclose', (['(b - a)', 'expected'], {}), '(b - a, expected)\n', (3442, 3459), False, 'from common import arrayclose, arraytrue, arrayequal\n'), ((3504, 3553), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]', 'unit': '"""m"""'}), "(values=[1.0, 2.0, 3.0, 4.0, 5.0], unit='m')\n", (3509, 3553), False, 'from osyris import Array, units\n'), ((3557, 3607), 'osyris.Array', 'Array', ([], {'values': '[6.0, 7.0, 8.0, 9.0, 10.0]', 'unit': '"""s"""'}), "(values=[6.0, 7.0, 8.0, 9.0, 10.0], unit='s')\n", (3562, 3607), False, 'from osyris import Array, units\n'), ((3764, 3813), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]', 'unit': '"""m"""'}), "(values=[1.0, 2.0, 3.0, 4.0, 5.0], unit='m')\n", (3769, 3813), False, 'from osyris import Array, units\n'), ((3849, 3901), 'osyris.Array', 'Array', ([], {'values': '[-2.5, -1.5, -0.5, 0.5, 1.5]', 'unit': '"""m"""'}), "(values=[-2.5, -1.5, -0.5, 0.5, 1.5], unit='m')\n", (3854, 3901), False, 'from osyris import Array, units\n'), ((3913, 3940), 'common.arrayclose', 'arrayclose', (['(a - b)', 'expected'], {}), '(a - b, expected)\n', (3923, 3940), False, 'from common import arrayclose, arraytrue, arrayequal\n'), ((3983, 4032), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]', 'unit': '"""m"""'}), "(values=[1.0, 2.0, 3.0, 4.0, 5.0], unit='m')\n", (3988, 4032), False, 'from osyris import Array, units\n'), ((4036, 4086), 'osyris.Array', 'Array', ([], {'values': '[6.0, 7.0, 8.0, 9.0, 10.0]', 'unit': '"""m"""'}), "(values=[6.0, 7.0, 8.0, 9.0, 10.0], unit='m')\n", (4041, 4086), False, 'from osyris import Array, units\n'), ((4097, 4146), 'osyris.Array', 'Array', ([], {'values': '[5.0, 5.0, 5.0, 5.0, 5.0]', 'unit': '"""m"""'}), "(values=[5.0, 5.0, 5.0, 5.0, 5.0], unit='m')\n", (4102, 4146), False, 'from osyris import Array, units\n'), ((4164, 4187), 'common.arrayclose', 'arrayclose', (['b', 'expected'], {}), '(b, expected)\n', (4174, 4187), False, 'from common import arrayclose, arraytrue, arrayequal\n'), ((4239, 4288), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]', 'unit': '"""m"""'}), "(values=[1.0, 2.0, 3.0, 4.0, 5.0], unit='m')\n", (4244, 4288), False, 'from osyris import Array, units\n'), ((4324, 4376), 'osyris.Array', 'Array', ([], {'values': '[-2.5, -1.5, -0.5, 0.5, 1.5]', 'unit': '"""m"""'}), "(values=[-2.5, -1.5, -0.5, 0.5, 1.5], unit='m')\n", (4329, 4376), False, 'from osyris import Array, units\n'), ((4399, 4422), 'common.arrayclose', 'arrayclose', (['a', 'expected'], {}), '(a, expected)\n', (4409, 4422), False, 'from common import arrayclose, arraytrue, arrayequal\n'), ((4460, 4509), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]', 'unit': '"""m"""'}), "(values=[1.0, 2.0, 3.0, 4.0, 5.0], unit='m')\n", (4465, 4509), False, 'from osyris import Array, units\n'), ((4513, 4563), 'osyris.Array', 'Array', ([], {'values': '[6.0, 7.0, 8.0, 9.0, 10.0]', 'unit': '"""m"""'}), "(values=[6.0, 7.0, 8.0, 9.0, 10.0], unit='m')\n", (4518, 4563), False, 'from osyris import Array, units\n'), ((4574, 4629), 'osyris.Array', 'Array', ([], {'values': '[6.0, 14.0, 24.0, 36.0, 50.0]', 'unit': '"""m*m"""'}), "(values=[6.0, 14.0, 24.0, 36.0, 50.0], unit='m*m')\n", (4579, 4629), False, 'from osyris import Array, units\n'), ((4636, 4663), 'common.arrayclose', 'arrayclose', (['(a * b)', 'expected'], {}), '(a * b, expected)\n', (4646, 4663), False, 'from common import arrayclose, arraytrue, arrayequal\n'), ((4712, 4761), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]', 'unit': '"""m"""'}), "(values=[1.0, 2.0, 3.0, 4.0, 5.0], unit='m')\n", (4717, 4761), False, 'from osyris import Array, units\n'), ((4765, 4816), 'osyris.Array', 'Array', ([], {'values': '[6.0, 7.0, 8.0, 9.0, 10.0]', 'unit': '"""cm"""'}), "(values=[6.0, 7.0, 8.0, 9.0, 10.0], unit='cm')\n", (4770, 4816), False, 'from osyris import Array, units\n'), ((4827, 4882), 'osyris.Array', 'Array', ([], {'values': '[0.06, 0.14, 0.24, 0.36, 0.5]', 'unit': '"""m*m"""'}), "(values=[0.06, 0.14, 0.24, 0.36, 0.5], unit='m*m')\n", (4832, 4882), False, 'from osyris import Array, units\n'), ((4894, 4921), 'common.arrayclose', 'arrayclose', (['(a * b)', 'expected'], {}), '(a * b, expected)\n', (4904, 4921), False, 'from common import arrayclose, arraytrue, arrayequal\n'), ((4965, 5014), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]', 'unit': '"""m"""'}), "(values=[1.0, 2.0, 3.0, 4.0, 5.0], unit='m')\n", (4970, 5014), False, 'from osyris import Array, units\n'), ((5037, 5088), 'osyris.Array', 'Array', ([], {'values': '[3.0, 6.0, 9.0, 12.0, 15.0]', 'unit': '"""m"""'}), "(values=[3.0, 6.0, 9.0, 12.0, 15.0], unit='m')\n", (5042, 5088), False, 'from osyris import Array, units\n'), ((5095, 5122), 'common.arrayclose', 'arrayclose', (['(a * b)', 'expected'], {}), '(a * b, expected)\n', (5105, 5122), False, 'from common import arrayclose, arraytrue, arrayequal\n'), ((5134, 5161), 'common.arrayclose', 'arrayclose', (['(b * a)', 'expected'], {}), '(b * a, expected)\n', (5144, 5161), False, 'from common import arrayclose, arraytrue, arrayequal\n'), ((5207, 5256), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]', 'unit': '"""m"""'}), "(values=[1.0, 2.0, 3.0, 4.0, 5.0], unit='m')\n", (5212, 5256), False, 'from osyris import Array, units\n'), ((5260, 5274), 'numpy.arange', 'np.arange', (['(5.0)'], {}), '(5.0)\n', (5269, 5274), True, 'import numpy as np\n'), ((5289, 5340), 'osyris.Array', 'Array', ([], {'values': '[0.0, 2.0, 6.0, 12.0, 20.0]', 'unit': '"""m"""'}), "(values=[0.0, 2.0, 6.0, 12.0, 20.0], unit='m')\n", (5294, 5340), False, 'from osyris import Array, units\n'), ((5347, 5374), 'common.arrayclose', 'arrayclose', (['(a * b)', 'expected'], {}), '(a * b, expected)\n', (5357, 5374), False, 'from common import arrayclose, arraytrue, arrayequal\n'), ((5386, 5413), 'common.arrayclose', 'arrayclose', (['(b * a)', 'expected'], {}), '(b * a, expected)\n', (5396, 5413), False, 'from common import arrayclose, arraytrue, arrayequal\n'), ((5460, 5509), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]', 'unit': '"""m"""'}), "(values=[1.0, 2.0, 3.0, 4.0, 5.0], unit='m')\n", (5465, 5509), False, 'from osyris import Array, units\n'), ((5545, 5599), 'osyris.Array', 'Array', ([], {'values': '[3.5, 7.0, 10.5, 14.0, 17.5]', 'unit': '"""m*s"""'}), "(values=[3.5, 7.0, 10.5, 14.0, 17.5], unit='m*s')\n", (5550, 5599), False, 'from osyris import Array, units\n'), ((5611, 5638), 'common.arrayclose', 'arrayclose', (['(a * b)', 'expected'], {}), '(a * b, expected)\n', (5621, 5638), False, 'from common import arrayclose, arraytrue, arrayequal\n'), ((5684, 5733), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]', 'unit': '"""m"""'}), "(values=[1.0, 2.0, 3.0, 4.0, 5.0], unit='m')\n", (5689, 5733), False, 'from osyris import Array, units\n'), ((5737, 5787), 'osyris.Array', 'Array', ([], {'values': '[6.0, 7.0, 8.0, 9.0, 10.0]', 'unit': '"""m"""'}), "(values=[6.0, 7.0, 8.0, 9.0, 10.0], unit='m')\n", (5742, 5787), False, 'from osyris import Array, units\n'), ((5798, 5853), 'osyris.Array', 'Array', ([], {'values': '[6.0, 14.0, 24.0, 36.0, 50.0]', 'unit': '"""m*m"""'}), "(values=[6.0, 14.0, 24.0, 36.0, 50.0], unit='m*m')\n", (5803, 5853), False, 'from osyris import Array, units\n'), ((5871, 5894), 'common.arrayclose', 'arrayclose', (['a', 'expected'], {}), '(a, expected)\n', (5881, 5894), False, 'from common import arrayclose, arraytrue, arrayequal\n'), ((5946, 5995), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]', 'unit': '"""m"""'}), "(values=[1.0, 2.0, 3.0, 4.0, 5.0], unit='m')\n", (5951, 5995), False, 'from osyris import Array, units\n'), ((6018, 6069), 'osyris.Array', 'Array', ([], {'values': '[3.0, 6.0, 9.0, 12.0, 15.0]', 'unit': '"""m"""'}), "(values=[3.0, 6.0, 9.0, 12.0, 15.0], unit='m')\n", (6023, 6069), False, 'from osyris import Array, units\n'), ((6087, 6110), 'common.arrayclose', 'arrayclose', (['a', 'expected'], {}), '(a, expected)\n', (6097, 6110), False, 'from common import arrayclose, arraytrue, arrayequal\n'), ((6164, 6213), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]', 'unit': '"""m"""'}), "(values=[1.0, 2.0, 3.0, 4.0, 5.0], unit='m')\n", (6169, 6213), False, 'from osyris import Array, units\n'), ((6217, 6231), 'numpy.arange', 'np.arange', (['(5.0)'], {}), '(5.0)\n', (6226, 6231), True, 'import numpy as np\n'), ((6246, 6297), 'osyris.Array', 'Array', ([], {'values': '[0.0, 2.0, 6.0, 12.0, 20.0]', 'unit': '"""m"""'}), "(values=[0.0, 2.0, 6.0, 12.0, 20.0], unit='m')\n", (6251, 6297), False, 'from osyris import Array, units\n'), ((6315, 6338), 'common.arrayclose', 'arrayclose', (['a', 'expected'], {}), '(a, expected)\n', (6325, 6338), False, 'from common import arrayclose, arraytrue, arrayequal\n'), ((6393, 6442), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]', 'unit': '"""m"""'}), "(values=[1.0, 2.0, 3.0, 4.0, 5.0], unit='m')\n", (6398, 6442), False, 'from osyris import Array, units\n'), ((6478, 6532), 'osyris.Array', 'Array', ([], {'values': '[3.5, 7.0, 10.5, 14.0, 17.5]', 'unit': '"""m*s"""'}), "(values=[3.5, 7.0, 10.5, 14.0, 17.5], unit='m*s')\n", (6483, 6532), False, 'from osyris import Array, units\n'), ((6555, 6578), 'common.arrayclose', 'arrayclose', (['a', 'expected'], {}), '(a, expected)\n', (6565, 6578), False, 'from common import arrayclose, arraytrue, arrayequal\n'), ((6610, 6659), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]', 'unit': '"""s"""'}), "(values=[1.0, 2.0, 3.0, 4.0, 5.0], unit='s')\n", (6615, 6659), False, 'from osyris import Array, units\n'), ((6663, 6713), 'osyris.Array', 'Array', ([], {'values': '[6.0, 7.0, 8.0, 9.0, 10.0]', 'unit': '"""m"""'}), "(values=[6.0, 7.0, 8.0, 9.0, 10.0], unit='m')\n", (6668, 6713), False, 'from osyris import Array, units\n'), ((6724, 6782), 'osyris.Array', 'Array', ([], {'values': '[6.0, 3.5, 8.0 / 3.0, 2.25, 2.0]', 'unit': '"""m/s"""'}), "(values=[6.0, 3.5, 8.0 / 3.0, 2.25, 2.0], unit='m/s')\n", (6729, 6782), False, 'from osyris import Array, units\n'), ((6790, 6817), 'common.arrayclose', 'arrayclose', (['(b / a)', 'expected'], {}), '(b / a, expected)\n', (6800, 6817), False, 'from common import arrayclose, arraytrue, arrayequal\n'), ((6855, 6904), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]', 'unit': '"""s"""'}), "(values=[1.0, 2.0, 3.0, 4.0, 5.0], unit='s')\n", (6860, 6904), False, 'from osyris import Array, units\n'), ((6927, 7000), 'osyris.Array', 'Array', ([], {'values': '[1.0 / 3.0, 2.0 / 3.0, 1.0, 4.0 / 3.0, 5.0 / 3.0]', 'unit': '"""s"""'}), "(values=[1.0 / 3.0, 2.0 / 3.0, 1.0, 4.0 / 3.0, 5.0 / 3.0], unit='s')\n", (6932, 7000), False, 'from osyris import Array, units\n'), ((7003, 7030), 'common.arrayclose', 'arrayclose', (['(a / b)', 'expected'], {}), '(a / b, expected)\n', (7013, 7030), False, 'from common import arrayclose, arraytrue, arrayequal\n'), ((7046, 7115), 'osyris.Array', 'Array', ([], {'values': '[3.0, 3.0 / 2.0, 1.0, 3.0 / 4.0, 3.0 / 5.0]', 'unit': '"""1/s"""'}), "(values=[3.0, 3.0 / 2.0, 1.0, 3.0 / 4.0, 3.0 / 5.0], unit='1/s')\n", (7051, 7115), False, 'from osyris import Array, units\n'), ((7119, 7146), 'common.arrayclose', 'arrayclose', (['(b / a)', 'expected'], {}), '(b / a, expected)\n', (7129, 7146), False, 'from common import arrayclose, arraytrue, arrayequal\n'), ((7186, 7235), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]', 'unit': '"""s"""'}), "(values=[1.0, 2.0, 3.0, 4.0, 5.0], unit='s')\n", (7191, 7235), False, 'from osyris import Array, units\n'), ((7239, 7259), 'numpy.arange', 'np.arange', (['(5.0)', '(10.0)'], {}), '(5.0, 10.0)\n', (7248, 7259), True, 'import numpy as np\n'), ((7273, 7352), 'osyris.Array', 'Array', ([], {'values': '[1.0 / 5.0, 2.0 / 6.0, 3.0 / 7.0, 4.0 / 8.0, 5.0 / 9.0]', 'unit': '"""s"""'}), "(values=[1.0 / 5.0, 2.0 / 6.0, 3.0 / 7.0, 4.0 / 8.0, 5.0 / 9.0], unit='s')\n", (7278, 7352), False, 'from osyris import Array, units\n'), ((7354, 7381), 'common.arrayclose', 'arrayclose', (['(a / b)', 'expected'], {}), '(a / b, expected)\n', (7364, 7381), False, 'from common import arrayclose, arraytrue, arrayequal\n'), ((7542, 7593), 'osyris.Array', 'Array', ([], {'values': '[0.0, 2.0, 4.0, 6.0, 200.0]', 'unit': '"""s"""'}), "(values=[0.0, 2.0, 4.0, 6.0, 200.0], unit='s')\n", (7547, 7593), False, 'from osyris import Array, units\n'), ((7629, 7692), 'osyris.Array', 'Array', ([], {'values': '[0.0, 1.0, 2.0, 3.0, 100.0]', 'unit': '"""dimensionless"""'}), "(values=[0.0, 1.0, 2.0, 3.0, 100.0], unit='dimensionless')\n", (7634, 7692), False, 'from osyris import Array, units\n'), ((7699, 7726), 'common.arrayclose', 'arrayclose', (['(a / b)', 'expected'], {}), '(a / b, expected)\n', (7709, 7726), False, 'from common import arrayclose, arraytrue, arrayequal\n'), ((7766, 7815), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]', 'unit': '"""s"""'}), "(values=[1.0, 2.0, 3.0, 4.0, 5.0], unit='s')\n", (7771, 7815), False, 'from osyris import Array, units\n'), ((7819, 7869), 'osyris.Array', 'Array', ([], {'values': '[6.0, 7.0, 8.0, 9.0, 10.0]', 'unit': '"""m"""'}), "(values=[6.0, 7.0, 8.0, 9.0, 10.0], unit='m')\n", (7824, 7869), False, 'from osyris import Array, units\n'), ((7880, 7938), 'osyris.Array', 'Array', ([], {'values': '[6.0, 3.5, 8.0 / 3.0, 2.25, 2.0]', 'unit': '"""m/s"""'}), "(values=[6.0, 3.5, 8.0 / 3.0, 2.25, 2.0], unit='m/s')\n", (7885, 7938), False, 'from osyris import Array, units\n'), ((7957, 7980), 'common.arrayclose', 'arrayclose', (['b', 'expected'], {}), '(b, expected)\n', (7967, 7980), False, 'from common import arrayclose, arraytrue, arrayequal\n'), ((8026, 8075), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]', 'unit': '"""s"""'}), "(values=[1.0, 2.0, 3.0, 4.0, 5.0], unit='s')\n", (8031, 8075), False, 'from osyris import Array, units\n'), ((8098, 8171), 'osyris.Array', 'Array', ([], {'values': '[1.0 / 3.0, 2.0 / 3.0, 1.0, 4.0 / 3.0, 5.0 / 3.0]', 'unit': '"""s"""'}), "(values=[1.0 / 3.0, 2.0 / 3.0, 1.0, 4.0 / 3.0, 5.0 / 3.0], unit='s')\n", (8103, 8171), False, 'from osyris import Array, units\n'), ((8185, 8208), 'common.arrayclose', 'arrayclose', (['a', 'expected'], {}), '(a, expected)\n', (8195, 8208), False, 'from common import arrayclose, arraytrue, arrayequal\n'), ((8256, 8305), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]', 'unit': '"""s"""'}), "(values=[1.0, 2.0, 3.0, 4.0, 5.0], unit='s')\n", (8261, 8305), False, 'from osyris import Array, units\n'), ((8309, 8329), 'numpy.arange', 'np.arange', (['(5.0)', '(10.0)'], {}), '(5.0, 10.0)\n', (8318, 8329), True, 'import numpy as np\n'), ((8343, 8422), 'osyris.Array', 'Array', ([], {'values': '[1.0 / 5.0, 2.0 / 6.0, 3.0 / 7.0, 4.0 / 8.0, 5.0 / 9.0]', 'unit': '"""s"""'}), "(values=[1.0 / 5.0, 2.0 / 6.0, 3.0 / 7.0, 4.0 / 8.0, 5.0 / 9.0], unit='s')\n", (8348, 8422), False, 'from osyris import Array, units\n'), ((8435, 8458), 'common.arrayclose', 'arrayclose', (['a', 'expected'], {}), '(a, expected)\n', (8445, 8458), False, 'from common import arrayclose, arraytrue, arrayequal\n'), ((8627, 8678), 'osyris.Array', 'Array', ([], {'values': '[0.0, 2.0, 4.0, 6.0, 200.0]', 'unit': '"""s"""'}), "(values=[0.0, 2.0, 4.0, 6.0, 200.0], unit='s')\n", (8632, 8678), False, 'from osyris import Array, units\n'), ((8714, 8777), 'osyris.Array', 'Array', ([], {'values': '[0.0, 1.0, 2.0, 3.0, 100.0]', 'unit': '"""dimensionless"""'}), "(values=[0.0, 1.0, 2.0, 3.0, 100.0], unit='dimensionless')\n", (8719, 8777), False, 'from osyris import Array, units\n'), ((8795, 8818), 'common.arrayclose', 'arrayclose', (['a', 'expected'], {}), '(a, expected)\n', (8805, 8818), False, 'from common import arrayclose, arraytrue, arrayequal\n'), ((8847, 8898), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 4.0, 6.0, 200.0]', 'unit': '"""s"""'}), "(values=[1.0, 2.0, 4.0, 6.0, 200.0], unit='s')\n", (8852, 8898), False, 'from osyris import Array, units\n'), ((8909, 8970), 'osyris.Array', 'Array', ([], {'values': '[1.0, 8.0, 64.0, 216.0, 8000000.0]', 'unit': '"""s**3"""'}), "(values=[1.0, 8.0, 64.0, 216.0, 8000000.0], unit='s**3')\n", (8914, 8970), False, 'from osyris import Array, units\n'), ((8974, 9002), 'common.arrayclose', 'arrayclose', (['(a ** 3)', 'expected'], {}), '(a ** 3, expected)\n', (8984, 9002), False, 'from common import arrayclose, arraytrue, arrayequal\n'), ((9032, 9083), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 4.0, 6.0, 200.0]', 'unit': '"""s"""'}), "(values=[1.0, 2.0, 4.0, 6.0, 200.0], unit='s')\n", (9037, 9083), False, 'from osyris import Array, units\n'), ((9094, 9150), 'osyris.Array', 'Array', ([], {'values': '[-1.0, -2.0, -4.0, -6.0, -200.0]', 'unit': '"""s"""'}), "(values=[-1.0, -2.0, -4.0, -6.0, -200.0], unit='s')\n", (9099, 9150), False, 'from osyris import Array, units\n'), ((9157, 9181), 'common.arrayequal', 'arrayequal', (['(-a)', 'expected'], {}), '(-a, expected)\n', (9167, 9181), False, 'from common import arrayclose, arraytrue, arrayequal\n'), ((9210, 9259), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]', 'unit': '"""m"""'}), "(values=[1.0, 2.0, 3.0, 4.0, 5.0], unit='m')\n", (9215, 9259), False, 'from osyris import Array, units\n'), ((9263, 9313), 'osyris.Array', 'Array', ([], {'values': '[11.0, 2.0, 3.0, 4.1, 5.0]', 'unit': '"""m"""'}), "(values=[11.0, 2.0, 3.0, 4.1, 5.0], unit='m')\n", (9268, 9313), False, 'from osyris import Array, units\n'), ((9441, 9490), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]', 'unit': '"""m"""'}), "(values=[1.0, 2.0, 3.0, 4.0, 5.0], unit='m')\n", (9446, 9490), False, 'from osyris import Array, units\n'), ((9494, 9555), 'osyris.Array', 'Array', ([], {'values': '[1100.0, 200.0, 300.0, 410.0, 500.0]', 'unit': '"""cm"""'}), "(values=[1100.0, 200.0, 300.0, 410.0, 500.0], unit='cm')\n", (9499, 9555), False, 'from osyris import Array, units\n'), ((9681, 9730), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]', 'unit': '"""m"""'}), "(values=[1.0, 2.0, 3.0, 4.0, 5.0], unit='m')\n", (9686, 9730), False, 'from osyris import Array, units\n'), ((9734, 9784), 'osyris.Array', 'Array', ([], {'values': '[11.0, 2.0, 3.0, 4.1, 5.0]', 'unit': '"""s"""'}), "(values=[11.0, 2.0, 3.0, 4.1, 5.0], unit='s')\n", (9739, 9784), False, 'from osyris import Array, units\n'), ((9881, 9920), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]'}), '(values=[1.0, 2.0, 3.0, 4.0, 5.0])\n', (9886, 9920), False, 'from osyris import Array, units\n'), ((9924, 9960), 'numpy.array', 'np.array', (['[11.0, 2.0, 3.0, 4.1, 5.0]'], {}), '([11.0, 2.0, 3.0, 4.1, 5.0])\n', (9932, 9960), True, 'import numpy as np\n'), ((10164, 10203), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]'}), '(values=[1.0, 2.0, 3.0, 4.0, 5.0])\n', (10169, 10203), False, 'from osyris import Array, units\n'), ((10422, 10471), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]', 'unit': '"""m"""'}), "(values=[1.0, 2.0, 3.0, 4.0, 5.0], unit='m')\n", (10427, 10471), False, 'from osyris import Array, units\n'), ((10705, 10754), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]', 'unit': '"""m"""'}), "(values=[1.0, 2.0, 3.0, 4.0, 5.0], unit='m')\n", (10710, 10754), False, 'from osyris import Array, units\n'), ((10758, 10808), 'osyris.Array', 'Array', ([], {'values': '[11.0, 2.0, 3.0, 4.1, 5.0]', 'unit': '"""m"""'}), "(values=[11.0, 2.0, 3.0, 4.1, 5.0], unit='m')\n", (10763, 10808), False, 'from osyris import Array, units\n'), ((10941, 10990), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]', 'unit': '"""m"""'}), "(values=[1.0, 2.0, 3.0, 4.0, 5.0], unit='m')\n", (10946, 10990), False, 'from osyris import Array, units\n'), ((10994, 11055), 'osyris.Array', 'Array', ([], {'values': '[1100.0, 200.0, 300.0, 410.0, 500.0]', 'unit': '"""cm"""'}), "(values=[1100.0, 200.0, 300.0, 410.0, 500.0], unit='cm')\n", (10999, 11055), False, 'from osyris import Array, units\n'), ((11186, 11235), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]', 'unit': '"""m"""'}), "(values=[1.0, 2.0, 3.0, 4.0, 5.0], unit='m')\n", (11191, 11235), False, 'from osyris import Array, units\n'), ((11239, 11289), 'osyris.Array', 'Array', ([], {'values': '[11.0, 2.0, 3.0, 4.1, 5.0]', 'unit': '"""s"""'}), "(values=[11.0, 2.0, 3.0, 4.1, 5.0], unit='s')\n", (11244, 11289), False, 'from osyris import Array, units\n'), ((11390, 11429), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]'}), '(values=[1.0, 2.0, 3.0, 4.0, 5.0])\n', (11395, 11429), False, 'from osyris import Array, units\n'), ((11433, 11469), 'numpy.array', 'np.array', (['[11.0, 2.0, 3.0, 4.1, 5.0]'], {}), '([11.0, 2.0, 3.0, 4.1, 5.0])\n', (11441, 11469), True, 'import numpy as np\n'), ((11678, 11717), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]'}), '(values=[1.0, 2.0, 3.0, 4.0, 5.0])\n', (11683, 11717), False, 'from osyris import Array, units\n'), ((11937, 11986), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]', 'unit': '"""m"""'}), "(values=[1.0, 2.0, 3.0, 4.0, 5.0], unit='m')\n", (11942, 11986), False, 'from osyris import Array, units\n'), ((12217, 12266), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]', 'unit': '"""s"""'}), "(values=[1.0, 2.0, 3.0, 4.0, 5.0], unit='s')\n", (12222, 12266), False, 'from osyris import Array, units\n'), ((12270, 12320), 'osyris.Array', 'Array', ([], {'values': '[6.0, 7.0, 1.0, 4.0, 10.0]', 'unit': '"""s"""'}), "(values=[6.0, 7.0, 1.0, 4.0, 10.0], unit='s')\n", (12275, 12320), False, 'from osyris import Array, units\n'), ((12450, 12499), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]', 'unit': '"""m"""'}), "(values=[1.0, 2.0, 3.0, 4.0, 5.0], unit='m')\n", (12455, 12499), False, 'from osyris import Array, units\n'), ((12503, 12564), 'osyris.Array', 'Array', ([], {'values': '[600.0, 700.0, 100.0, 400.0, 1000.0]', 'unit': '"""cm"""'}), "(values=[600.0, 700.0, 100.0, 400.0, 1000.0], unit='cm')\n", (12508, 12564), False, 'from osyris import Array, units\n'), ((12693, 12742), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]', 'unit': '"""s"""'}), "(values=[1.0, 2.0, 3.0, 4.0, 5.0], unit='s')\n", (12698, 12742), False, 'from osyris import Array, units\n'), ((12746, 12796), 'osyris.Array', 'Array', ([], {'values': '[6.0, 7.0, 1.0, 4.0, 10.0]', 'unit': '"""m"""'}), "(values=[6.0, 7.0, 1.0, 4.0, 10.0], unit='m')\n", (12751, 12796), False, 'from osyris import Array, units\n'), ((12895, 12934), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]'}), '(values=[1.0, 2.0, 3.0, 4.0, 5.0])\n', (12900, 12934), False, 'from osyris import Array, units\n'), ((12938, 12974), 'numpy.array', 'np.array', (['[6.0, 7.0, 1.0, 4.0, 10.0]'], {}), '([6.0, 7.0, 1.0, 4.0, 10.0])\n', (12946, 12974), True, 'import numpy as np\n'), ((13179, 13218), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]'}), '(values=[1.0, 2.0, 3.0, 4.0, 5.0])\n', (13184, 13218), False, 'from osyris import Array, units\n'), ((13438, 13487), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]', 'unit': '"""m"""'}), "(values=[1.0, 2.0, 3.0, 4.0, 5.0], unit='m')\n", (13443, 13487), False, 'from osyris import Array, units\n'), ((13719, 13768), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]', 'unit': '"""s"""'}), "(values=[1.0, 2.0, 3.0, 4.0, 5.0], unit='s')\n", (13724, 13768), False, 'from osyris import Array, units\n'), ((13772, 13822), 'osyris.Array', 'Array', ([], {'values': '[6.0, 7.0, 1.0, 4.0, 10.0]', 'unit': '"""s"""'}), "(values=[6.0, 7.0, 1.0, 4.0, 10.0], unit='s')\n", (13777, 13822), False, 'from osyris import Array, units\n'), ((13952, 14001), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]', 'unit': '"""s"""'}), "(values=[1.0, 2.0, 3.0, 4.0, 5.0], unit='s')\n", (13957, 14001), False, 'from osyris import Array, units\n'), ((14005, 14055), 'osyris.Array', 'Array', ([], {'values': '[6.0, 7.0, 1.0, 4.0, 10.0]', 'unit': '"""m"""'}), "(values=[6.0, 7.0, 1.0, 4.0, 10.0], unit='m')\n", (14010, 14055), False, 'from osyris import Array, units\n'), ((14156, 14195), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]'}), '(values=[1.0, 2.0, 3.0, 4.0, 5.0])\n', (14161, 14195), False, 'from osyris import Array, units\n'), ((14199, 14235), 'numpy.array', 'np.array', (['[6.0, 7.0, 1.0, 4.0, 10.0]'], {}), '([6.0, 7.0, 1.0, 4.0, 10.0])\n', (14207, 14235), True, 'import numpy as np\n'), ((14441, 14480), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]'}), '(values=[1.0, 2.0, 3.0, 4.0, 5.0])\n', (14446, 14480), False, 'from osyris import Array, units\n'), ((14701, 14750), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]', 'unit': '"""m"""'}), "(values=[1.0, 2.0, 3.0, 4.0, 5.0], unit='m')\n", (14706, 14750), False, 'from osyris import Array, units\n'), ((14984, 15033), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]', 'unit': '"""s"""'}), "(values=[1.0, 2.0, 3.0, 4.0, 5.0], unit='s')\n", (14989, 15033), False, 'from osyris import Array, units\n'), ((15037, 15087), 'osyris.Array', 'Array', ([], {'values': '[6.0, 7.0, 1.0, 4.0, 10.0]', 'unit': '"""s"""'}), "(values=[6.0, 7.0, 1.0, 4.0, 10.0], unit='s')\n", (15042, 15087), False, 'from osyris import Array, units\n'), ((15219, 15268), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]', 'unit': '"""s"""'}), "(values=[1.0, 2.0, 3.0, 4.0, 5.0], unit='s')\n", (15224, 15268), False, 'from osyris import Array, units\n'), ((15272, 15322), 'osyris.Array', 'Array', ([], {'values': '[6.0, 7.0, 1.0, 4.0, 10.0]', 'unit': '"""K"""'}), "(values=[6.0, 7.0, 1.0, 4.0, 10.0], unit='K')\n", (15277, 15322), False, 'from osyris import Array, units\n'), ((15424, 15463), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]'}), '(values=[1.0, 2.0, 3.0, 4.0, 5.0])\n', (15429, 15463), False, 'from osyris import Array, units\n'), ((15467, 15503), 'numpy.array', 'np.array', (['[6.0, 7.0, 1.0, 4.0, 10.0]'], {}), '([6.0, 7.0, 1.0, 4.0, 10.0])\n', (15475, 15503), True, 'import numpy as np\n'), ((15713, 15752), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]'}), '(values=[1.0, 2.0, 3.0, 4.0, 5.0])\n', (15718, 15752), False, 'from osyris import Array, units\n'), ((15975, 16024), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]', 'unit': '"""m"""'}), "(values=[1.0, 2.0, 3.0, 4.0, 5.0], unit='m')\n", (15980, 16024), False, 'from osyris import Array, units\n'), ((16259, 16308), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]', 'unit': '"""s"""'}), "(values=[1.0, 2.0, 3.0, 4.0, 5.0], unit='s')\n", (16264, 16308), False, 'from osyris import Array, units\n'), ((16312, 16362), 'osyris.Array', 'Array', ([], {'values': '[6.0, 7.0, 1.0, 4.0, 10.0]', 'unit': '"""s"""'}), "(values=[6.0, 7.0, 1.0, 4.0, 10.0], unit='s')\n", (16317, 16362), False, 'from osyris import Array, units\n'), ((16495, 16544), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]', 'unit': '"""s"""'}), "(values=[1.0, 2.0, 3.0, 4.0, 5.0], unit='s')\n", (16500, 16544), False, 'from osyris import Array, units\n'), ((16548, 16598), 'osyris.Array', 'Array', ([], {'values': '[6.0, 7.0, 1.0, 4.0, 10.0]', 'unit': '"""K"""'}), "(values=[6.0, 7.0, 1.0, 4.0, 10.0], unit='K')\n", (16553, 16598), False, 'from osyris import Array, units\n'), ((16702, 16741), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]'}), '(values=[1.0, 2.0, 3.0, 4.0, 5.0])\n', (16707, 16741), False, 'from osyris import Array, units\n'), ((16745, 16781), 'numpy.array', 'np.array', (['[6.0, 7.0, 1.0, 4.0, 10.0]'], {}), '([6.0, 7.0, 1.0, 4.0, 10.0])\n', (16753, 16781), True, 'import numpy as np\n'), ((16993, 17032), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]'}), '(values=[1.0, 2.0, 3.0, 4.0, 5.0])\n', (16998, 17032), False, 'from osyris import Array, units\n'), ((17257, 17306), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]', 'unit': '"""m"""'}), "(values=[1.0, 2.0, 3.0, 4.0, 5.0], unit='m')\n", (17262, 17306), False, 'from osyris import Array, units\n'), ((17540, 17593), 'osyris.Array', 'Array', ([], {'values': '[True, True, True, False, False, False]'}), '(values=[True, True, True, False, False, False])\n', (17545, 17593), False, 'from osyris import Array, units\n'), ((17602, 17655), 'osyris.Array', 'Array', ([], {'values': '[True, False, True, False, True, False]'}), '(values=[True, False, True, False, True, False])\n', (17607, 17655), False, 'from osyris import Array, units\n'), ((17788, 17841), 'osyris.Array', 'Array', ([], {'values': '[True, True, True, False, False, False]'}), '(values=[True, True, True, False, False, False])\n', (17793, 17841), False, 'from osyris import Array, units\n'), ((17850, 17903), 'osyris.Array', 'Array', ([], {'values': '[True, False, True, False, True, False]'}), '(values=[True, False, True, False, True, False])\n', (17855, 17903), False, 'from osyris import Array, units\n'), ((18035, 18088), 'osyris.Array', 'Array', ([], {'values': '[True, True, True, False, False, False]'}), '(values=[True, True, True, False, False, False])\n', (18040, 18088), False, 'from osyris import Array, units\n'), ((18097, 18150), 'osyris.Array', 'Array', ([], {'values': '[True, False, True, False, True, False]'}), '(values=[True, False, True, False, True, False])\n', (18102, 18150), False, 'from osyris import Array, units\n'), ((18287, 18340), 'osyris.Array', 'Array', ([], {'values': '[True, True, False, False, True, False]'}), '(values=[True, True, False, False, True, False])\n', (18292, 18340), False, 'from osyris import Array, units\n'), ((18461, 18510), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]', 'unit': '"""m"""'}), "(values=[1.0, 2.0, 3.0, 4.0, 5.0], unit='m')\n", (18466, 18510), False, 'from osyris import Array, units\n'), ((18514, 18574), 'osyris.Array', 'Array', ([], {'values': '[0.001, 0.002, 0.003, 0.004, 0.005]', 'unit': '"""km"""'}), "(values=[0.001, 0.002, 0.003, 0.004, 0.005], unit='km')\n", (18519, 18574), False, 'from osyris import Array, units\n'), ((18684, 18733), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0]', 'unit': '"""m"""'}), "(values=[1.0, 2.0, 3.0, 4.0, 5.0], unit='m')\n", (18689, 18733), False, 'from osyris import Array, units\n'), ((18822, 18877), 'osyris.Array', 'Array', ([], {'values': '[1.0, -2.0, 3.0, 0.4, 0.5, 0.6]', 'unit': '"""m"""'}), "(values=[1.0, -2.0, 3.0, 0.4, 0.5, 0.6], unit='m')\n", (18827, 18877), False, 'from osyris import Array, units\n'), ((19104, 19160), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, -15.0, 5.0, 6.0]', 'unit': '"""m"""'}), "(values=[1.0, 2.0, 3.0, -15.0, 5.0, 6.0], unit='m')\n", (19109, 19160), False, 'from osyris import Array, units\n'), ((19386, 19440), 'osyris.Array', 'Array', ([], {'values': '[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]', 'unit': '"""m"""'}), "(values=[1.0, 2.0, 3.0, 4.0, 5.0, 6.0], unit='m')\n", (19391, 19440), False, 'from osyris import Array, units\n'), ((19450, 19508), 'osyris.Array', 'Array', ([], {'values': '[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]', 'unit': '"""m"""'}), "(values=[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], unit='m')\n", (19455, 19508), False, 'from osyris import Array, units\n'), ((19593, 19647), 'osyris.Array', 'Array', ([], {'values': '[11.0, 12.0, 13.0, 14.0, 15.0]', 'unit': '"""m"""'}), "(values=[11.0, 12.0, 13.0, 14.0, 15.0], unit='m')\n", (19598, 19647), False, 'from osyris import Array, units\n'), ((20170, 20224), 'osyris.Array', 'Array', ([], {'values': '[11.0, 12.0, 13.0, 14.0, 15.0]', 'unit': '"""m"""'}), "(values=[11.0, 12.0, 13.0, 14.0, 15.0], unit='m')\n", (20175, 20224), False, 'from osyris import Array, units\n'), ((20363, 20417), 'osyris.Array', 'Array', ([], {'values': '[11.0, 12.0, 13.0, 14.0, 15.0]', 'unit': '"""m"""'}), "(values=[11.0, 12.0, 13.0, 14.0, 15.0], unit='m')\n", (20368, 20417), False, 'from osyris import Array, units\n'), ((20421, 20428), 'copy.copy', 'copy', (['a'], {}), '(a)\n', (20425, 20428), False, 'from copy import copy, deepcopy\n'), ((20550, 20604), 'osyris.Array', 'Array', ([], {'values': '[11.0, 12.0, 13.0, 14.0, 15.0]', 'unit': '"""m"""'}), "(values=[11.0, 12.0, 13.0, 14.0, 15.0], unit='m')\n", (20555, 20604), False, 'from osyris import Array, units\n'), ((20608, 20619), 'copy.deepcopy', 'deepcopy', (['a'], {}), '(a)\n', (20616, 20619), False, 'from copy import copy, deepcopy\n'), ((20778, 20808), 'osyris.Array', 'Array', ([], {'values': 'values', 'unit': '"""m"""'}), "(values=values, unit='m')\n", (20783, 20808), False, 'from osyris import Array, units\n'), ((20824, 20840), 'numpy.log10', 'np.log10', (['values'], {}), '(values)\n', (20832, 20840), True, 'import numpy as np\n'), ((20854, 20865), 'numpy.log10', 'np.log10', (['a'], {}), '(a)\n', (20862, 20865), True, 'import numpy as np\n'), ((20877, 20913), 'numpy.allclose', 'np.allclose', (['result.values', 'expected'], {}), '(result.values, expected)\n', (20888, 20913), True, 'import numpy as np\n'), ((21018, 21050), 'osyris.Array', 'Array', ([], {'values': 'values', 'unit': '"""m*m"""'}), "(values=values, unit='m*m')\n", (21023, 21050), False, 'from osyris import Array, units\n'), ((21066, 21081), 'numpy.sqrt', 'np.sqrt', (['values'], {}), '(values)\n', (21073, 21081), True, 'import numpy as np\n'), ((21095, 21105), 'numpy.sqrt', 'np.sqrt', (['a'], {}), '(a)\n', (21102, 21105), True, 'import numpy as np\n'), ((21117, 21153), 'numpy.allclose', 'np.allclose', (['result.values', 'expected'], {}), '(result.values, expected)\n', (21128, 21153), True, 'import numpy as np\n'), ((21293, 21322), 'osyris.Array', 'Array', ([], {'values': 'a_buf', 'unit': '"""m"""'}), "(values=a_buf, unit='m')\n", (21298, 21322), False, 'from osyris import Array, units\n'), ((21331, 21360), 'osyris.Array', 'Array', ([], {'values': 'b_buf', 'unit': '"""m"""'}), "(values=b_buf, unit='m')\n", (21336, 21360), False, 'from osyris import Array, units\n'), ((21376, 21396), 'numpy.dot', 'np.dot', (['a_buf', 'b_buf'], {}), '(a_buf, b_buf)\n', (21382, 21396), True, 'import numpy as np\n'), ((21410, 21422), 'numpy.dot', 'np.dot', (['a', 'b'], {}), '(a, b)\n', (21416, 21422), True, 'import numpy as np\n'), ((21601, 21630), 'osyris.Array', 'Array', ([], {'values': 'a_buf', 'unit': '"""m"""'}), "(values=a_buf, unit='m')\n", (21606, 21630), False, 'from osyris import Array, units\n'), ((21639, 21668), 'osyris.Array', 'Array', ([], {'values': 'b_buf', 'unit': '"""m"""'}), "(values=b_buf, unit='m')\n", (21644, 21668), False, 'from osyris import Array, units\n'), ((21684, 21714), 'numpy.concatenate', 'np.concatenate', (['[a_buf, b_buf]'], {}), '([a_buf, b_buf])\n', (21698, 21714), True, 'import numpy as np\n'), ((21728, 21750), 'numpy.concatenate', 'np.concatenate', (['[a, b]'], {}), '([a, b])\n', (21742, 21750), True, 'import numpy as np\n'), ((21762, 21801), 'numpy.array_equal', 'np.array_equal', (['result.values', 'expected'], {}), '(result.values, expected)\n', (21776, 21801), True, 'import numpy as np\n'), ((21922, 21951), 'osyris.Array', 'Array', ([], {'values': 'a_buf', 'unit': '"""m"""'}), "(values=a_buf, unit='m')\n", (21927, 21951), False, 'from osyris import Array, units\n'), ((21960, 21996), 'numpy.array', 'np.array', (['[6.0, 7.0, 8.0, 9.0, 10.0]'], {}), '([6.0, 7.0, 8.0, 9.0, 10.0])\n', (21968, 21996), True, 'import numpy as np\n'), ((22007, 22028), 'numpy.multiply', 'np.multiply', (['a_buf', 'b'], {}), '(a_buf, b)\n', (22018, 22028), True, 'import numpy as np\n'), ((22042, 22059), 'numpy.multiply', 'np.multiply', (['a', 'b'], {}), '(a, b)\n', (22053, 22059), True, 'import numpy as np\n'), ((22071, 22110), 'numpy.array_equal', 'np.array_equal', (['result.values', 'expected'], {}), '(result.values, expected)\n', (22085, 22110), True, 'import numpy as np\n'), ((22161, 22178), 'numpy.multiply', 'np.multiply', (['b', 'a'], {}), '(b, a)\n', (22172, 22178), True, 'import numpy as np\n'), ((22190, 22229), 'numpy.array_equal', 'np.array_equal', (['result.values', 'expected'], {}), '(result.values, expected)\n', (22204, 22229), True, 'import numpy as np\n'), ((22351, 22380), 'osyris.Array', 'Array', ([], {'values': 'a_buf', 'unit': '"""m"""'}), "(values=a_buf, unit='m')\n", (22356, 22380), False, 'from osyris import Array, units\n'), ((22421, 22452), 'numpy.multiply', 'np.multiply', (['a_buf', 'b.magnitude'], {}), '(a_buf, b.magnitude)\n', (22432, 22452), True, 'import numpy as np\n'), ((22466, 22483), 'numpy.multiply', 'np.multiply', (['a', 'b'], {}), '(a, b)\n', (22477, 22483), True, 'import numpy as np\n'), ((22495, 22534), 'numpy.array_equal', 'np.array_equal', (['result.values', 'expected'], {}), '(result.values, expected)\n', (22509, 22534), True, 'import numpy as np\n'), ((22655, 22684), 'osyris.Array', 'Array', ([], {'values': 'a_buf', 'unit': '"""m"""'}), "(values=a_buf, unit='m')\n", (22660, 22684), False, 'from osyris import Array, units\n'), ((22712, 22733), 'numpy.multiply', 'np.multiply', (['a_buf', 'b'], {}), '(a_buf, b)\n', (22723, 22733), True, 'import numpy as np\n'), ((22747, 22764), 'numpy.multiply', 'np.multiply', (['a', 'b'], {}), '(a, b)\n', (22758, 22764), True, 'import numpy as np\n'), ((22776, 22815), 'numpy.array_equal', 'np.array_equal', (['result.values', 'expected'], {}), '(result.values, expected)\n', (22790, 22815), True, 'import numpy as np\n'), ((22866, 22883), 'numpy.multiply', 'np.multiply', (['b', 'a'], {}), '(b, a)\n', (22877, 22883), True, 'import numpy as np\n'), ((22895, 22934), 'numpy.array_equal', 'np.array_equal', (['result.values', 'expected'], {}), '(result.values, expected)\n', (22909, 22934), True, 'import numpy as np\n'), ((23053, 23082), 'osyris.Array', 'Array', ([], {'values': 'a_buf', 'unit': '"""m"""'}), "(values=a_buf, unit='m')\n", (23058, 23082), False, 'from osyris import Array, units\n'), ((23091, 23127), 'numpy.array', 'np.array', (['[6.0, 7.0, 8.0, 9.0, 10.0]'], {}), '([6.0, 7.0, 8.0, 9.0, 10.0])\n', (23099, 23127), True, 'import numpy as np\n'), ((23138, 23157), 'numpy.divide', 'np.divide', (['a_buf', 'b'], {}), '(a_buf, b)\n', (23147, 23157), True, 'import numpy as np\n'), ((23171, 23186), 'numpy.divide', 'np.divide', (['a', 'b'], {}), '(a, b)\n', (23180, 23186), True, 'import numpy as np\n'), ((23198, 23237), 'numpy.array_equal', 'np.array_equal', (['result.values', 'expected'], {}), '(result.values, expected)\n', (23212, 23237), True, 'import numpy as np\n'), ((23290, 23309), 'numpy.divide', 'np.divide', (['b', 'a_buf'], {}), '(b, a_buf)\n', (23299, 23309), True, 'import numpy as np\n'), ((23323, 23338), 'numpy.divide', 'np.divide', (['b', 'a'], {}), '(b, a)\n', (23332, 23338), True, 'import numpy as np\n'), ((23350, 23389), 'numpy.array_equal', 'np.array_equal', (['result.values', 'expected'], {}), '(result.values, expected)\n', (23364, 23389), True, 'import numpy as np\n'), ((23511, 23540), 'osyris.Array', 'Array', ([], {'values': 'a_buf', 'unit': '"""m"""'}), "(values=a_buf, unit='m')\n", (23516, 23540), False, 'from osyris import Array, units\n'), ((23581, 23610), 'numpy.divide', 'np.divide', (['a_buf', 'b.magnitude'], {}), '(a_buf, b.magnitude)\n', (23590, 23610), True, 'import numpy as np\n'), ((23624, 23639), 'numpy.divide', 'np.divide', (['a', 'b'], {}), '(a, b)\n', (23633, 23639), True, 'import numpy as np\n'), ((23651, 23690), 'numpy.array_equal', 'np.array_equal', (['result.values', 'expected'], {}), '(result.values, expected)\n', (23665, 23690), True, 'import numpy as np\n'), ((23809, 23838), 'osyris.Array', 'Array', ([], {'values': 'a_buf', 'unit': '"""m"""'}), "(values=a_buf, unit='m')\n", (23814, 23838), False, 'from osyris import Array, units\n'), ((23866, 23885), 'numpy.divide', 'np.divide', (['a_buf', 'b'], {}), '(a_buf, b)\n', (23875, 23885), True, 'import numpy as np\n'), ((23899, 23914), 'numpy.divide', 'np.divide', (['a', 'b'], {}), '(a, b)\n', (23908, 23914), True, 'import numpy as np\n'), ((23926, 23965), 'numpy.array_equal', 'np.array_equal', (['result.values', 'expected'], {}), '(result.values, expected)\n', (23940, 23965), True, 'import numpy as np\n'), ((24018, 24037), 'numpy.divide', 'np.divide', (['b', 'a_buf'], {}), '(b, a_buf)\n', (24027, 24037), True, 'import numpy as np\n'), ((24051, 24066), 'numpy.divide', 'np.divide', (['b', 'a'], {}), '(b, a)\n', (24060, 24066), True, 'import numpy as np\n'), ((24078, 24117), 'numpy.array_equal', 'np.array_equal', (['result.values', 'expected'], {}), '(result.values, expected)\n', (24092, 24117), True, 'import numpy as np\n'), ((439, 449), 'osyris.units', 'units', (['"""m"""'], {}), "('m')\n", (444, 449), False, 'from osyris import Array, units\n'), ((690, 700), 'osyris.units', 'units', (['"""s"""'], {}), "('s')\n", (695, 700), False, 'from osyris import Array, units\n'), ((856, 866), 'osyris.units', 'units', (['"""m"""'], {}), "('m')\n", (861, 866), False, 'from osyris import Array, units\n'), ((907, 920), 'numpy.array', 'np.array', (['num'], {}), '(num)\n', (915, 920), True, 'import numpy as np\n'), ((1036, 1046), 'osyris.units', 'units', (['"""m"""'], {}), "('m')\n", (1041, 1046), False, 'from osyris import Array, units\n'), ((1087, 1100), 'numpy.array', 'np.array', (['num'], {}), '(num)\n', (1095, 1100), True, 'import numpy as np\n'), ((1151, 1161), 'osyris.units', 'units', (['"""K"""'], {}), "('K')\n", (1156, 1161), False, 'from osyris import Array, units\n'), ((1215, 1225), 'osyris.units', 'units', (['"""K"""'], {}), "('K')\n", (1220, 1225), False, 'from osyris import Array, units\n'), ((1266, 1287), 'numpy.array', 'np.array', (['q.magnitude'], {}), '(q.magnitude)\n', (1274, 1287), True, 'import numpy as np\n'), ((1352, 1362), 'osyris.units', 'units', (['"""K"""'], {}), "('K')\n", (1357, 1362), False, 'from osyris import Array, units\n'), ((1372, 1397), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (1385, 1397), False, 'import pytest\n'), ((1411, 1436), 'osyris.Array', 'Array', ([], {'values': 'q', 'unit': '"""s"""'}), "(values=q, unit='s')\n", (1416, 1436), False, 'from osyris import Array, units\n'), ((1598, 1608), 'osyris.units', 'units', (['"""m"""'], {}), "('m')\n", (1603, 1608), False, 'from osyris import Array, units\n'), ((2429, 2463), 'pytest.raises', 'pytest.raises', (['DimensionalityError'], {}), '(DimensionalityError)\n', (2442, 2463), False, 'import pytest\n'), ((2492, 2516), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (2505, 2516), False, 'import pytest\n'), ((2637, 2647), 'osyris.units', 'units', (['"""m"""'], {}), "('m')\n", (2642, 2647), False, 'from osyris import Array, units\n'), ((3106, 3116), 'osyris.units', 'units', (['"""m"""'], {}), "('m')\n", (3111, 3116), False, 'from osyris import Array, units\n'), ((3612, 3646), 'pytest.raises', 'pytest.raises', (['DimensionalityError'], {}), '(DimensionalityError)\n', (3625, 3646), False, 'import pytest\n'), ((3675, 3699), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (3688, 3699), False, 'import pytest\n'), ((3823, 3833), 'osyris.units', 'units', (['"""m"""'], {}), "('m')\n", (3828, 3833), False, 'from osyris import Array, units\n'), ((4298, 4308), 'osyris.units', 'units', (['"""m"""'], {}), "('m')\n", (4303, 4308), False, 'from osyris import Array, units\n'), ((5519, 5529), 'osyris.units', 'units', (['"""s"""'], {}), "('s')\n", (5524, 5529), False, 'from osyris import Array, units\n'), ((6452, 6462), 'osyris.units', 'units', (['"""s"""'], {}), "('s')\n", (6457, 6462), False, 'from osyris import Array, units\n'), ((7603, 7613), 'osyris.units', 'units', (['"""s"""'], {}), "('s')\n", (7608, 7613), False, 'from osyris import Array, units\n'), ((8688, 8698), 'osyris.units', 'units', (['"""s"""'], {}), "('s')\n", (8693, 8698), False, 'from osyris import Array, units\n'), ((9790, 9824), 'pytest.raises', 'pytest.raises', (['DimensionalityError'], {}), '(DimensionalityError)\n', (9803, 9824), False, 'import pytest\n'), ((10075, 10109), 'pytest.raises', 'pytest.raises', (['DimensionalityError'], {}), '(DimensionalityError)\n', (10088, 10109), False, 'import pytest\n'), ((10330, 10364), 'pytest.raises', 'pytest.raises', (['DimensionalityError'], {}), '(DimensionalityError)\n', (10343, 10364), False, 'import pytest\n'), ((10480, 10490), 'osyris.units', 'units', (['"""m"""'], {}), "('m')\n", (10485, 10490), False, 'from osyris import Array, units\n'), ((10598, 10608), 'osyris.units', 'units', (['"""s"""'], {}), "('s')\n", (10603, 10608), False, 'from osyris import Array, units\n'), ((10618, 10652), 'pytest.raises', 'pytest.raises', (['DimensionalityError'], {}), '(DimensionalityError)\n', (10631, 10652), False, 'import pytest\n'), ((11295, 11329), 'pytest.raises', 'pytest.raises', (['DimensionalityError'], {}), '(DimensionalityError)\n', (11308, 11329), False, 'import pytest\n'), ((11585, 11619), 'pytest.raises', 'pytest.raises', (['DimensionalityError'], {}), '(DimensionalityError)\n', (11598, 11619), False, 'import pytest\n'), ((11841, 11875), 'pytest.raises', 'pytest.raises', (['DimensionalityError'], {}), '(DimensionalityError)\n', (11854, 11875), False, 'import pytest\n'), ((11995, 12005), 'osyris.units', 'units', (['"""m"""'], {}), "('m')\n", (12000, 12005), False, 'from osyris import Array, units\n'), ((12110, 12120), 'osyris.units', 'units', (['"""s"""'], {}), "('s')\n", (12115, 12120), False, 'from osyris import Array, units\n'), ((12130, 12164), 'pytest.raises', 'pytest.raises', (['DimensionalityError'], {}), '(DimensionalityError)\n', (12143, 12164), False, 'import pytest\n'), ((12801, 12835), 'pytest.raises', 'pytest.raises', (['DimensionalityError'], {}), '(DimensionalityError)\n', (12814, 12835), False, 'import pytest\n'), ((13087, 13121), 'pytest.raises', 'pytest.raises', (['DimensionalityError'], {}), '(DimensionalityError)\n', (13100, 13121), False, 'import pytest\n'), ((13343, 13377), 'pytest.raises', 'pytest.raises', (['DimensionalityError'], {}), '(DimensionalityError)\n', (13356, 13377), False, 'import pytest\n'), ((13496, 13506), 'osyris.units', 'units', (['"""m"""'], {}), "('m')\n", (13501, 13506), False, 'from osyris import Array, units\n'), ((13612, 13622), 'osyris.units', 'units', (['"""s"""'], {}), "('s')\n", (13617, 13622), False, 'from osyris import Array, units\n'), ((13632, 13666), 'pytest.raises', 'pytest.raises', (['DimensionalityError'], {}), '(DimensionalityError)\n', (13645, 13666), False, 'import pytest\n'), ((14060, 14094), 'pytest.raises', 'pytest.raises', (['DimensionalityError'], {}), '(DimensionalityError)\n', (14073, 14094), False, 'import pytest\n'), ((14348, 14382), 'pytest.raises', 'pytest.raises', (['DimensionalityError'], {}), '(DimensionalityError)\n', (14361, 14382), False, 'import pytest\n'), ((14605, 14639), 'pytest.raises', 'pytest.raises', (['DimensionalityError'], {}), '(DimensionalityError)\n', (14618, 14639), False, 'import pytest\n'), ((14759, 14769), 'osyris.units', 'units', (['"""m"""'], {}), "('m')\n", (14764, 14769), False, 'from osyris import Array, units\n'), ((14875, 14885), 'osyris.units', 'units', (['"""s"""'], {}), "('s')\n", (14880, 14885), False, 'from osyris import Array, units\n'), ((14895, 14929), 'pytest.raises', 'pytest.raises', (['DimensionalityError'], {}), '(DimensionalityError)\n', (14908, 14929), False, 'import pytest\n'), ((15327, 15361), 'pytest.raises', 'pytest.raises', (['DimensionalityError'], {}), '(DimensionalityError)\n', (15340, 15361), False, 'import pytest\n'), ((15618, 15652), 'pytest.raises', 'pytest.raises', (['DimensionalityError'], {}), '(DimensionalityError)\n', (15631, 15652), False, 'import pytest\n'), ((15877, 15911), 'pytest.raises', 'pytest.raises', (['DimensionalityError'], {}), '(DimensionalityError)\n', (15890, 15911), False, 'import pytest\n'), ((16033, 16043), 'osyris.units', 'units', (['"""m"""'], {}), "('m')\n", (16038, 16043), False, 'from osyris import Array, units\n'), ((16149, 16159), 'osyris.units', 'units', (['"""s"""'], {}), "('s')\n", (16154, 16159), False, 'from osyris import Array, units\n'), ((16169, 16203), 'pytest.raises', 'pytest.raises', (['DimensionalityError'], {}), '(DimensionalityError)\n', (16182, 16203), False, 'import pytest\n'), ((16603, 16637), 'pytest.raises', 'pytest.raises', (['DimensionalityError'], {}), '(DimensionalityError)\n', (16616, 16637), False, 'import pytest\n'), ((16896, 16930), 'pytest.raises', 'pytest.raises', (['DimensionalityError'], {}), '(DimensionalityError)\n', (16909, 16930), False, 'import pytest\n'), ((17157, 17191), 'pytest.raises', 'pytest.raises', (['DimensionalityError'], {}), '(DimensionalityError)\n', (17170, 17191), False, 'import pytest\n'), ((17315, 17325), 'osyris.units', 'units', (['"""m"""'], {}), "('m')\n", (17320, 17325), False, 'from osyris import Array, units\n'), ((17431, 17441), 'osyris.units', 'units', (['"""s"""'], {}), "('s')\n", (17436, 17441), False, 'from osyris import Array, units\n'), ((17451, 17485), 'pytest.raises', 'pytest.raises', (['DimensionalityError'], {}), '(DimensionalityError)\n', (17464, 17485), False, 'import pytest\n'), ((18638, 18648), 'osyris.units', 'units', (['"""m"""'], {}), "('m')\n", (18643, 18648), False, 'from osyris import Array, units\n'), ((18738, 18772), 'pytest.raises', 'pytest.raises', (['DimensionalityError'], {}), '(DimensionalityError)\n', (18751, 18772), False, 'import pytest\n'), ((19662, 19692), 'osyris.Array', 'Array', ([], {'values': '[13.0]', 'unit': '"""m"""'}), "(values=[13.0], unit='m')\n", (19667, 19692), False, 'from osyris import Array, units\n'), ((20940, 20950), 'osyris.units', 'units', (['"""m"""'], {}), "('m')\n", (20945, 20950), False, 'from osyris import Array, units\n'), ((21180, 21190), 'osyris.units', 'units', (['"""m"""'], {}), "('m')\n", (21185, 21190), False, 'from osyris import Array, units\n'), ((21486, 21496), 'osyris.units', 'units', (['"""m"""'], {}), "('m')\n", (21491, 21496), False, 'from osyris import Array, units\n'), ((21828, 21838), 'osyris.units', 'units', (['"""m"""'], {}), "('m')\n", (21833, 21838), False, 'from osyris import Array, units\n'), ((22137, 22147), 'osyris.units', 'units', (['"""m"""'], {}), "('m')\n", (22142, 22147), False, 'from osyris import Array, units\n'), ((22256, 22266), 'osyris.units', 'units', (['"""m"""'], {}), "('m')\n", (22261, 22266), False, 'from osyris import Array, units\n'), ((22395, 22405), 'osyris.units', 'units', (['"""s"""'], {}), "('s')\n", (22400, 22405), False, 'from osyris import Array, units\n'), ((22561, 22573), 'osyris.units', 'units', (['"""m*s"""'], {}), "('m*s')\n", (22566, 22573), False, 'from osyris import Array, units\n'), ((22842, 22852), 'osyris.units', 'units', (['"""m"""'], {}), "('m')\n", (22847, 22852), False, 'from osyris import Array, units\n'), ((22961, 22971), 'osyris.units', 'units', (['"""m"""'], {}), "('m')\n", (22966, 22971), False, 'from osyris import Array, units\n'), ((23264, 23274), 'osyris.units', 'units', (['"""m"""'], {}), "('m')\n", (23269, 23274), False, 'from osyris import Array, units\n'), ((23416, 23428), 'osyris.units', 'units', (['"""1/m"""'], {}), "('1/m')\n", (23421, 23428), False, 'from osyris import Array, units\n'), ((23555, 23565), 'osyris.units', 'units', (['"""s"""'], {}), "('s')\n", (23560, 23565), False, 'from osyris import Array, units\n'), ((23717, 23729), 'osyris.units', 'units', (['"""m/s"""'], {}), "('m/s')\n", (23722, 23729), False, 'from osyris import Array, units\n'), ((23992, 24002), 'osyris.units', 'units', (['"""m"""'], {}), "('m')\n", (23997, 24002), False, 'from osyris import Array, units\n'), ((24144, 24156), 'osyris.units', 'units', (['"""1/m"""'], {}), "('1/m')\n", (24149, 24156), False, 'from osyris import Array, units\n'), ((18898, 18926), 'osyris.Array', 'Array', ([], {'values': '(-2.0)', 'unit': '"""m"""'}), "(values=-2.0, unit='m')\n", (18903, 18926), False, 'from osyris import Array, units\n'), ((19042, 19070), 'osyris.Array', 'Array', ([], {'values': '(-2.0)', 'unit': '"""m"""'}), "(values=-2.0, unit='m')\n", (19047, 19070), False, 'from osyris import Array, units\n'), ((19178, 19205), 'osyris.Array', 'Array', ([], {'values': '(6.0)', 'unit': '"""m"""'}), "(values=6.0, unit='m')\n", (19183, 19205), False, 'from osyris import Array, units\n'), ((19320, 19347), 'osyris.Array', 'Array', ([], {'values': '(6.0)', 'unit': '"""m"""'}), "(values=6.0, unit='m')\n", (19325, 19347), False, 'from osyris import Array, units\n'), ((19722, 19770), 'osyris.Array', 'Array', ([], {'values': '[11.0, 12.0, 13.0, 14.0]', 'unit': '"""m"""'}), "(values=[11.0, 12.0, 13.0, 14.0], unit='m')\n", (19727, 19770), False, 'from osyris import Array, units\n'), ((19799, 19835), 'osyris.Array', 'Array', ([], {'values': '[13.0, 14.0]', 'unit': '"""m"""'}), "(values=[13.0, 14.0], unit='m')\n", (19804, 19835), False, 'from osyris import Array, units\n'), ((20276, 20330), 'osyris.Array', 'Array', ([], {'values': '[11.0, 12.0, 13.0, 14.0, 15.0]', 'unit': '"""m"""'}), "(values=[11.0, 12.0, 13.0, 14.0, 15.0], unit='m')\n", (20281, 20330), False, 'from osyris import Array, units\n'), ((20468, 20522), 'osyris.Array', 'Array', ([], {'values': '[11.0, 12.0, 13.0, 14.0, 15.0]', 'unit': '"""m"""'}), "(values=[11.0, 12.0, 13.0, 14.0, 15.0], unit='m')\n", (20473, 20522), False, 'from osyris import Array, units\n'), ((20659, 20713), 'osyris.Array', 'Array', ([], {'values': '[11.0, 12.0, 13.0, 14.0, 15.0]', 'unit': '"""m"""'}), "(values=[11.0, 12.0, 13.0, 14.0, 15.0], unit='m')\n", (20664, 20713), False, 'from osyris import Array, units\n'), ((19965, 20006), 'osyris.Array', 'Array', ([], {'values': '[[6.0, 7.0, 8.0]]', 'unit': '"""m"""'}), "(values=[[6.0, 7.0, 8.0]], unit='m')\n", (19970, 20006), False, 'from osyris import Array, units\n'), ((20088, 20146), 'osyris.Array', 'Array', ([], {'values': '[[0.0, 1.0, 2.0], [3.0, 4.0, 5.0]]', 'unit': '"""m"""'}), "(values=[[0.0, 1.0, 2.0], [3.0, 4.0, 5.0]], unit='m')\n", (20093, 20146), False, 'from osyris import Array, units\n'), ((18955, 18996), 'numpy.array', 'np.array', (['[1.0, -2.0, 3.0, 0.4, 0.5, 0.6]'], {}), '([1.0, -2.0, 3.0, 0.4, 0.5, 0.6])\n', (18963, 18996), True, 'import numpy as np\n'), ((19235, 19277), 'numpy.array', 'np.array', (['[1.0, 2.0, 3.0, -15.0, 5.0, 6.0]'], {}), '([1.0, 2.0, 3.0, -15.0, 5.0, 6.0])\n', (19243, 19277), True, 'import numpy as np\n'), ((19885, 19900), 'numpy.arange', 'np.arange', (['(12.0)'], {}), '(12.0)\n', (19894, 19900), True, 'import numpy as np\n')]
#!/usr/bin/env python import numpy as np import mirheo as mir ranks = (1, 1, 1) domain = [4., 6., 8.] u = mir.Mirheo(ranks, tuple(domain), dt=0, debug_level=3, log_filename='log', no_splash=True) a=(0.1, 0.2, 0.3) coords = [[-a[0], -a[1], -a[2]], [-a[0], -a[1], a[2]], [-a[0], a[1], -a[2]], [-a[0], a[1], a[2]], [ a[0], a[1], -a[2]], [ a[0], a[1], a[2]]] com_q = [[ 1., 0., 0., 1.0, 0.0, 0.0, 0.0], [ 3., 0., 0., 1.0, 2.0, 0.0, 0.0], [-1., 0., 0., 1.0, 0.0, 3.0, 0.0], # out of the domain [ 2., 0., 0., 1.0, 0.0, 0.0, 1.0]] pv = mir.ParticleVectors.RigidEllipsoidVector('ellipsoid', mass=1, object_size=len(coords), semi_axes=a) ic = mir.InitialConditions.Rigid(com_q, coords) u.registerParticleVector(pv, ic) u.run(2) if pv: icpos = pv.getCoordinates() icvel = pv.getVelocities() np.savetxt("pos.ic.txt", icpos) np.savetxt("vel.ic.txt", icvel) # TEST: ic.rigid # cd ic # rm -rf pos*.txt vel*.txt # mir.run --runargs "-n 2" ./rigid.py # paste pos.ic.txt vel.ic.txt | LC_ALL=en_US.utf8 sort > ic.out.txt
[ "numpy.savetxt", "mirheo.InitialConditions.Rigid" ]
[((738, 780), 'mirheo.InitialConditions.Rigid', 'mir.InitialConditions.Rigid', (['com_q', 'coords'], {}), '(com_q, coords)\n', (765, 780), True, 'import mirheo as mir\n'), ((899, 930), 'numpy.savetxt', 'np.savetxt', (['"""pos.ic.txt"""', 'icpos'], {}), "('pos.ic.txt', icpos)\n", (909, 930), True, 'import numpy as np\n'), ((935, 966), 'numpy.savetxt', 'np.savetxt', (['"""vel.ic.txt"""', 'icvel'], {}), "('vel.ic.txt', icvel)\n", (945, 966), True, 'import numpy as np\n')]
import sys import typing import numba as nb import numpy as np @nb.njit((nb.i8[:], nb.i8[:]), cache=True) def solve(w: np.ndarray, b: np.ndarray) -> typing.NoReturn: n = len(w) m = 50 w_mx = m b_mx = m + m * (m + 1) // 2 g = np.zeros((w_mx + 1, b_mx + 1), np.int64) cnt = np.zeros(b_mx // 2 + 1, np.int64) def compute_grundy(w, b): if w > 0 and b + w <= b_mx: cnt[g[w - 1, b + w]] += 1 for k in range(1, b // 2 + 1): cnt[g[w, b - k]] += 1 mex = 0 while cnt[mex]: mex += 1 g[w, b] = mex for k in range(1, b // 2 + 1): cnt[g[w, b - k]] -= 1 if w > 0 and b + w <= b_mx: cnt[g[w - 1, b + w]] -= 1 for i in range(w_mx + 1): for j in range(b_mx - i * (i + 1) // 2 + 1): compute_grundy(i, j) v = 0 for i in range(n): v ^= g[w[i], b[i]] ans = 'First' if v != 0 else 'Second' print(ans) def main() -> typing.NoReturn: n = int(input()) w = np.array( sys.stdin.readline().split(), dtype=np.int64, ) b = np.array( sys.stdin.readline().split(), dtype=np.int64, ) solve(w, b) main()
[ "sys.stdin.readline", "numpy.zeros", "numba.njit" ]
[((74, 115), 'numba.njit', 'nb.njit', (['(nb.i8[:], nb.i8[:])'], {'cache': '(True)'}), '((nb.i8[:], nb.i8[:]), cache=True)\n', (81, 115), True, 'import numba as nb\n'), ((251, 291), 'numpy.zeros', 'np.zeros', (['(w_mx + 1, b_mx + 1)', 'np.int64'], {}), '((w_mx + 1, b_mx + 1), np.int64)\n', (259, 291), True, 'import numpy as np\n'), ((301, 334), 'numpy.zeros', 'np.zeros', (['(b_mx // 2 + 1)', 'np.int64'], {}), '(b_mx // 2 + 1, np.int64)\n', (309, 334), True, 'import numpy as np\n'), ((963, 983), 'sys.stdin.readline', 'sys.stdin.readline', ([], {}), '()\n', (981, 983), False, 'import sys\n'), ((1041, 1061), 'sys.stdin.readline', 'sys.stdin.readline', ([], {}), '()\n', (1059, 1061), False, 'import sys\n')]
from torch.utils.data import Dataset from torch.utils.data import Dataset, DataLoader from torch.utils.data.sampler import RandomSampler, SequentialSampler, WeightedRandomSampler from torch.utils.data.distributed import DistributedSampler import torch import cv2 import numpy as np import pandas as pd import numpy as np import os import time from utilities import * from augmentations import * ####### DATASET class LeafData(Dataset): # initialization def __init__(self, data, directory, transform = None, labeled = False): self.data = data self.directory = directory self.transform = transform self.labeled = labeled # length def __len__(self): return len(self.data) # get item def __getitem__(self, idx): # import path = os.path.join(self.directory, self.data.iloc[idx]['image_id']) image = cv2.imread(path) if image is None: raise FileNotFoundError(path) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # augmentations if self.transform is not None: image = self.transform(image = image)['image'] # output if self.labeled: labels = torch.tensor(self.data.iloc[idx]['label']).long() return image, labels else: return image ####### DATA PREP def get_data(df, fold, CFG, df_2019 = None, df_no = None, df_pl = None, df_ext = None, epoch = None, list_dupl = [], list_noise = []): ##### EPOCH-BASED PARAMS # image size if (CFG['step_size']) and (epoch is not None): image_size = CFG['step_size'][epoch] else: image_size = CFG['image_size'] # augmentation probability if (CFG['step_p_aug']) and (epoch is not None): p_augment = CFG['step_p_aug'][epoch] else: p_augment = CFG['p_augment'] ##### PARTITIONING # load splits df_train = df.loc[df.fold != fold].reset_index(drop = True) df_valid = df.loc[df.fold == fold].reset_index(drop = True) if epoch is None: smart_print('-- no. images: train - {}, valid - {}'.format(len(df_train), len(df_valid)), CFG) # flip labels if epoch is not None: if CFG['flip_prob']: list_noise = [img for img in df_no['image_id'].values if img in df_train['image_id'].values] flip_idx = (np.random.binomial(1, CFG['flip_prob'], len(list_noise)) == 1) for img_idx, img in enumerate(list_noise): if flip_idx[img_idx]: df_train.loc[df_train.image_id == img, 'label'] = df_no.loc[df_no.image_id == img, 'pred'].astype('int').values smart_print('- flipping {} labels...'.format(np.sum(flip_idx)), CFG) # 2019 labeled data if CFG['data_2019']: df_train = pd.concat([df_train, df_2019], axis = 0).reset_index(drop = True) if epoch is None: smart_print('- appending 2019 labeled data to train...', CFG) smart_print('-- no. images: train - {}, valid - {}'.format(len(df_train), len(df_valid)), CFG) # 2019 psueudo-labeled data if CFG['data_pl']: df_train = pd.concat([df_train, df_pl], axis = 0).reset_index(drop = True) if epoch is None: smart_print('- appending 2019 pseudo-labeled data to train...', CFG) smart_print('-- no. images: train - {}, valid - {}'.format(len(df_train), len(df_valid)), CFG) # external data if CFG['data_ext']: df_train = pd.concat([df_train, df_ext], axis = 0).reset_index(drop = True) if epoch is None: smart_print('- appending external data to train...', CFG) smart_print('-- no. images: train - {}, valid - {}'.format(len(df_train), len(df_valid)), CFG) ##### SUBSETTING # removing bad examples if CFG['drop_dupl']: df_train = df_train.loc[~df_train.image_id.isin(list_dupl)].reset_index(drop = True) if CFG['drop_outs']: df_train = df_train.loc[~df_train.image_id.isin(list_outs)].reset_index(drop = True) if CFG['drop_noise']: list_noise = list(df_no['image_id'].values) df_train = df_train.loc[~df_train.image_id.isin(list_noise)].reset_index(drop = True) if CFG['flip_noise']: list_noise = [img for img in df_no['image_id'].values if img in df_train['image_id'].values] for img in list_noise: df_train.loc[df_train.image_id == img, 'label'] = df_no.loc[df_no.image_id == img, 'pred'].astype('int').values if epoch is None: smart_print('- dealing with bad images from train...', CFG) smart_print('-- no. images: train - {}, valid - {}'.format(len(df_train), len(df_valid)), CFG) # subset for debug mode if CFG['debug']: df_train = df_train.sample(CFG['batch_size'] * 5, random_state = CFG['seed']).reset_index(drop = True) df_valid = df_valid.sample(CFG['batch_size'] * 5, random_state = CFG['seed']).reset_index(drop = True) ##### DATASETS # augmentations train_augs, test_augs = get_augs(CFG, image_size, p_augment) # datasets train_dataset = LeafData(data = df_train, directory = CFG['data_path'] + 'train_images/', transform = train_augs, labeled = True) valid_dataset = LeafData(data = df_valid, directory = CFG['data_path'] + 'train_images/', transform = test_augs, labeled = True) ##### DATA SAMPLERS ### GPU SAMPLERS if CFG['device'] != 'TPU': # with oversampling if CFG['oversample']: weights = 1. / torch.tensor(df_train['label'].value_counts(sort = False).values, dtype = torch.float) sample_weights = weights[df_train['label']] train_sampler = WeightedRandomSampler(weights = sample_weights, num_samples = len(sample_weights), replacement = True) valid_sampler = SequentialSampler(valid_dataset) # ordinary samplers else: train_sampler = RandomSampler(train_dataset) valid_sampler = SequentialSampler(valid_dataset) ### TPU SAMPLERS if CFG['device'] == 'TPU': # distributed samplers train_sampler = DistributedSampler(train_dataset, num_replicas = xm.xrt_world_size(), rank = xm.get_ordinal(), shuffle = True) valid_sampler = DistributedSampler(valid_dataset, num_replicas = xm.xrt_world_size(), rank = xm.get_ordinal(), shuffle = False) ##### DATA LOADERS # data loaders train_loader = DataLoader(dataset = train_dataset, batch_size = CFG['batch_size'], sampler = train_sampler, num_workers = CFG['num_workers'], pin_memory = True) valid_loader = DataLoader(dataset = valid_dataset, batch_size = CFG['batch_size'], sampler = valid_sampler, num_workers = CFG['num_workers'], pin_memory = True) # feedback smart_print('- image size: {}x{}, p(augment): {}'.format(image_size, image_size, p_augment), CFG) if epoch is None: smart_print('-' * 55, CFG) # output return train_loader, valid_loader, df_train, df_valid
[ "torch.utils.data.sampler.SequentialSampler", "os.path.join", "torch.tensor", "numpy.sum", "pandas.concat", "torch.utils.data.sampler.RandomSampler", "cv2.cvtColor", "torch.utils.data.DataLoader", "cv2.imread" ]
[((7368, 7508), 'torch.utils.data.DataLoader', 'DataLoader', ([], {'dataset': 'train_dataset', 'batch_size': "CFG['batch_size']", 'sampler': 'train_sampler', 'num_workers': "CFG['num_workers']", 'pin_memory': '(True)'}), "(dataset=train_dataset, batch_size=CFG['batch_size'], sampler=\n train_sampler, num_workers=CFG['num_workers'], pin_memory=True)\n", (7378, 7508), False, 'from torch.utils.data import Dataset, DataLoader\n'), ((7665, 7805), 'torch.utils.data.DataLoader', 'DataLoader', ([], {'dataset': 'valid_dataset', 'batch_size': "CFG['batch_size']", 'sampler': 'valid_sampler', 'num_workers': "CFG['num_workers']", 'pin_memory': '(True)'}), "(dataset=valid_dataset, batch_size=CFG['batch_size'], sampler=\n valid_sampler, num_workers=CFG['num_workers'], pin_memory=True)\n", (7675, 7805), False, 'from torch.utils.data import Dataset, DataLoader\n'), ((930, 991), 'os.path.join', 'os.path.join', (['self.directory', "self.data.iloc[idx]['image_id']"], {}), "(self.directory, self.data.iloc[idx]['image_id'])\n", (942, 991), False, 'import os\n'), ((1008, 1024), 'cv2.imread', 'cv2.imread', (['path'], {}), '(path)\n', (1018, 1024), False, 'import cv2\n'), ((1109, 1147), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_BGR2RGB'], {}), '(image, cv2.COLOR_BGR2RGB)\n', (1121, 1147), False, 'import cv2\n'), ((6434, 6466), 'torch.utils.data.sampler.SequentialSampler', 'SequentialSampler', (['valid_dataset'], {}), '(valid_dataset)\n', (6451, 6466), False, 'from torch.utils.data.sampler import RandomSampler, SequentialSampler, WeightedRandomSampler\n'), ((6538, 6566), 'torch.utils.data.sampler.RandomSampler', 'RandomSampler', (['train_dataset'], {}), '(train_dataset)\n', (6551, 6566), False, 'from torch.utils.data.sampler import RandomSampler, SequentialSampler, WeightedRandomSampler\n'), ((6595, 6627), 'torch.utils.data.sampler.SequentialSampler', 'SequentialSampler', (['valid_dataset'], {}), '(valid_dataset)\n', (6612, 6627), False, 'from torch.utils.data.sampler import RandomSampler, SequentialSampler, WeightedRandomSampler\n'), ((3073, 3111), 'pandas.concat', 'pd.concat', (['[df_train, df_2019]'], {'axis': '(0)'}), '([df_train, df_2019], axis=0)\n', (3082, 3111), True, 'import pandas as pd\n'), ((3423, 3459), 'pandas.concat', 'pd.concat', (['[df_train, df_pl]'], {'axis': '(0)'}), '([df_train, df_pl], axis=0)\n', (3432, 3459), True, 'import pandas as pd\n'), ((3767, 3804), 'pandas.concat', 'pd.concat', (['[df_train, df_ext]'], {'axis': '(0)'}), '([df_train, df_ext], axis=0)\n', (3776, 3804), True, 'import pandas as pd\n'), ((1355, 1397), 'torch.tensor', 'torch.tensor', (["self.data.iloc[idx]['label']"], {}), "(self.data.iloc[idx]['label'])\n", (1367, 1397), False, 'import torch\n'), ((2980, 2996), 'numpy.sum', 'np.sum', (['flip_idx'], {}), '(flip_idx)\n', (2986, 2996), True, 'import numpy as np\n')]
#/usr/bin/env python # This code calculates the instantaneous energy deposition due to radioactive # decay in a SN Ia (called "S_dot" in PHOENIX), using as input a handful of # parameters as described in Stritzinger,+(2006). # Starting about 1 month after explosion, the bolometric luminosity (L_bol) of # a SN Ia at a given time is equal to the energy deposition at that time, # because the opacity in the ejecta is low enough that almost all of the energy # released from Ni56 and Co56 decay escapes immediately as radiation. # This code is therefore useful to estimate L_bol when trying to calulate # late-time spectra of SNe Ia with PHOENIX. Just provide parameters such as the # total ejected mass (M_ej), the total Ni56 mass (M_Ni56), and the age of the # SN, and it will return L_bol. from astropy import units as u import math import numpy as np from scipy.constants import N_A, golden as golden_ratio from matplotlib import pyplot as plt, gridspec from matplotlib.ticker import MultipleLocator, FormatStrFormatter # Decay constants for Ni56 and Co56, of the form dN/dt = -lambda*N. lambda_Ni = ( 8.8 * u.day )**(-1) lambda_Co = ( 111.3 * u.day )**(-1) Q_Ni_gamma = 1.75e+6 * u.eV # Energy released from gamma-rays per Ni56 -> Co56 decay (there are no positrons from Ni56). Q_Co_gamma = 3.61e+6 * u.eV # Energy released from gamma-rays per Co56 -> Fe56 decay. Q_Co_pos = 0.12e+6 * u.eV # Energy released from positrons per Co56 -> Fe56 decay. Ni56_atomic_mass = 55.942 * u.gram # Molar mass of Ni56. # Instantaneous energy deposition due to gamma-rays and positrons, a la Eq. 2 of Stritzinger,+(2006). def E_dep( t, \ M_Ni56 = 0.5 * u.solMass, \ M_ej = 1.3 * u.solMass, \ kappa = 0.025 * u.cm**2 / u.gram, \ q = 1.0/3.0 * u.dimensionless_unscaled, \ v_e = 3000.0 * u.km / u.second ): N_Ni_0 = M_Ni56.to(u.gram) * N_A / Ni56_atomic_mass # Convert mass of Ni56 to # of Ni56 atoms. M_ej = M_ej.to(u.gram) v_e = v_e.to(u.cm/u.second) t_0 = np.sqrt(M_ej * kappa * q / (8.0 * math.pi)) t_0 /= v_e # This completes Eq. 4 of Stritzinger,+(2006). t_0 = t_0.to(u.day) tau = np.power(t_0, 2) / np.power(t, 2) return ( (lambda_Ni * N_Ni_0 * math.exp(-lambda_Ni * t) * Q_Ni_gamma) \ + lambda_Co * N_Ni_0 * (lambda_Ni / (lambda_Ni - lambda_Co)) * ( (math.exp(-lambda_Co * t) - math.exp(-lambda_Ni * t)) \ * (Q_Co_pos + Q_Co_gamma * (1.0 - math.exp(-tau))) ) ) t = np.arange(1.0, 500.0, 1.0) * u.day # Create grid of days. # Set parameters. M_Ni56 = 0.50 * u.solMass M_ej = 1.38 * u.solMass kappa = 0.025 * u.cm**2 / u.gram q = 1.0/3.0 * u.dimensionless_unscaled v_e = 3000.0 * u.km / u.second E_dep_array = [] time_array = [] for i, time in enumerate(t): time_array.append ( time.value ) E_dep_array.append( E_dep( time, M_Ni56, M_ej, kappa, q, v_e ).to( u.erg / u.second ).value ) gs = gridspec.GridSpec(1, 1) fig = plt.figure(figsize=(11.0, 11.0 / golden_ratio)) ax = fig.add_subplot(gs[0, 0]) ax.plot(time_array, E_dep_array) ax.set_yscale('log') xmajorLocator = MultipleLocator(100) # Major ticks every 100 days. xminorLocator = MultipleLocator(20) # Minor ticks every 20 days. xmajorFormatter = FormatStrFormatter('%d') ax.xaxis.set_major_locator(xmajorLocator) ax.xaxis.set_minor_locator(xminorLocator) ax.xaxis.set_major_formatter(xmajorFormatter) # Use different grid line styles for major and minor ticks (for clarity). plt.grid(b=True, which='major', color='b', linestyle='-') plt.grid(b=True, which='minor', color='r', linestyle='--') title = 'M_Ni56 = %.2f %s; M_ej = %.2f %s; \n kappa = %.3f %s; q = %.2f; v_e = %.1f %s' % (M_Ni56.value, M_Ni56.unit, M_ej.value, M_ej.unit, kappa.value, kappa.unit, q.value, v_e.value, v_e.unit) ax.set_xlabel('time (days)') ax.set_ylabel('energy deposition (erg/s)') ax.set_title('instantaneous energy deposition due to Ni56 and Co56 decay:\n' + title) plt.show() figname = 'edep_M_Ni56_%.2f_M_ej_%.2f_kappa_%.3f_q_%.2f_v_e_%.1f' % (M_Ni56.value, M_ej.value, kappa.value, q.value, v_e.value) fig.savefig(figname + '.png', dpi=300) fig.savefig(figname + '.eps', dpi=300) plt.close()
[ "matplotlib.pyplot.grid", "numpy.sqrt", "numpy.power", "matplotlib.ticker.MultipleLocator", "matplotlib.pyplot.close", "matplotlib.gridspec.GridSpec", "matplotlib.pyplot.figure", "math.exp", "matplotlib.ticker.FormatStrFormatter", "numpy.arange", "matplotlib.pyplot.show" ]
[((2942, 2965), 'matplotlib.gridspec.GridSpec', 'gridspec.GridSpec', (['(1)', '(1)'], {}), '(1, 1)\n', (2959, 2965), False, 'from matplotlib import pyplot as plt, gridspec\n'), ((2973, 3020), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(11.0, 11.0 / golden_ratio)'}), '(figsize=(11.0, 11.0 / golden_ratio))\n', (2983, 3020), True, 'from matplotlib import pyplot as plt, gridspec\n'), ((3124, 3144), 'matplotlib.ticker.MultipleLocator', 'MultipleLocator', (['(100)'], {}), '(100)\n', (3139, 3144), False, 'from matplotlib.ticker import MultipleLocator, FormatStrFormatter\n'), ((3191, 3210), 'matplotlib.ticker.MultipleLocator', 'MultipleLocator', (['(20)'], {}), '(20)\n', (3206, 3210), False, 'from matplotlib.ticker import MultipleLocator, FormatStrFormatter\n'), ((3258, 3282), 'matplotlib.ticker.FormatStrFormatter', 'FormatStrFormatter', (['"""%d"""'], {}), "('%d')\n", (3276, 3282), False, 'from matplotlib.ticker import MultipleLocator, FormatStrFormatter\n'), ((3488, 3545), 'matplotlib.pyplot.grid', 'plt.grid', ([], {'b': '(True)', 'which': '"""major"""', 'color': '"""b"""', 'linestyle': '"""-"""'}), "(b=True, which='major', color='b', linestyle='-')\n", (3496, 3545), True, 'from matplotlib import pyplot as plt, gridspec\n'), ((3546, 3604), 'matplotlib.pyplot.grid', 'plt.grid', ([], {'b': '(True)', 'which': '"""minor"""', 'color': '"""r"""', 'linestyle': '"""--"""'}), "(b=True, which='minor', color='r', linestyle='--')\n", (3554, 3604), True, 'from matplotlib import pyplot as plt, gridspec\n'), ((3962, 3972), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3970, 3972), True, 'from matplotlib import pyplot as plt, gridspec\n'), ((4181, 4192), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (4190, 4192), True, 'from matplotlib import pyplot as plt, gridspec\n'), ((2043, 2086), 'numpy.sqrt', 'np.sqrt', (['(M_ej * kappa * q / (8.0 * math.pi))'], {}), '(M_ej * kappa * q / (8.0 * math.pi))\n', (2050, 2086), True, 'import numpy as np\n'), ((2503, 2529), 'numpy.arange', 'np.arange', (['(1.0)', '(500.0)', '(1.0)'], {}), '(1.0, 500.0, 1.0)\n', (2512, 2529), True, 'import numpy as np\n'), ((2188, 2204), 'numpy.power', 'np.power', (['t_0', '(2)'], {}), '(t_0, 2)\n', (2196, 2204), True, 'import numpy as np\n'), ((2207, 2221), 'numpy.power', 'np.power', (['t', '(2)'], {}), '(t, 2)\n', (2215, 2221), True, 'import numpy as np\n'), ((2257, 2281), 'math.exp', 'math.exp', (['(-lambda_Ni * t)'], {}), '(-lambda_Ni * t)\n', (2265, 2281), False, 'import math\n'), ((2376, 2400), 'math.exp', 'math.exp', (['(-lambda_Co * t)'], {}), '(-lambda_Co * t)\n', (2384, 2400), False, 'import math\n'), ((2403, 2427), 'math.exp', 'math.exp', (['(-lambda_Ni * t)'], {}), '(-lambda_Ni * t)\n', (2411, 2427), False, 'import math\n'), ((2477, 2491), 'math.exp', 'math.exp', (['(-tau)'], {}), '(-tau)\n', (2485, 2491), False, 'import math\n')]
import numpy as np import sympy as sp from scipy.integrate import ode, complex_ode from .qtools import Timer from .qstate import asQuantumState, QuantumStateError from .qoperator import asOperator, OperatorError, _t class QuantumSystem: """n-level quantum system""" def __init__(self, ham): self._H = asOperator(ham) if isinstance(ham, sp.MatrixBase): self._Hdot = asOperator(ham.diff(_t)) else: self._Hdot = None self._state = None self._mixed = None @property def N(self): """number of dimensions""" return self._H.N @property def H(self): """time-dependent Hamiltonian""" return self._H @property def H_dot(self): """temporal derivative of Hamiltonian""" return self._Hdot @H_dot.setter def H_dot(self, ham_dot): self._Hdot = asOperator(ham_dot) @property def state(self): """current state""" return self._state @state.setter def state(self, state): qstate = asQuantumState(state) if qstate.N != self.N: raise QuantumStateError self._state = qstate @property def is_ensemble(self): if self._state: return self._state.is_ensemble def eigenstates(self, time): """numerical eigenstates""" w, v = np.linalg.eigh(self.H(time)) indices = np.argsort(w) return v[::, indices] def eigenenergies(self, time): """numeric eigenvalues""" w, v = np.linalg.eigh(self.H(time)) indices = np.argsort(w) return w[indices] def propagate(self, t0, t1, N, integrator='zvode', integrator_params={}): """Propagate current state. --> ndarray times, ndarray states, float runtime Keyword arguments: integrator -- string in ['zvode', 'lsode', 'dop853'] integrator_params -- dict """ if self.state is None: raise QuantumStateError('Initial state not set') # setup I = self._setup_integrator(t0, integrator, **integrator_params) is_endtime = _wrap_term_crit(t0, t1) dt = (t1 - t0)/N #negative for backward propagation # integrate print_stats(t0, self.state, 2, 'initial') states, times = [], [] with Timer() as timer: while I.successful() and not is_endtime(I.t): states.append(I.y) times.append(I.t) I.integrate(I.t + dt) #print_stats(I.t, I.y, 1) # evaluate states, times = map(np.array, [states, times]) if self.is_ensemble: states = states.reshape(states.shape[0], self.N, self.N) #states = list(map(asQuantumState, states)) self.state = states[-1] print_stats(I.t, self.state, 2, 'final') print('runtime:\t{:.5f}'.format(timer.interval)) if not is_endtime(I.t): raise RuntimeError('error time: {}'.format(I.t)) return times, states, timer.interval def spectrum(self, t0=-10, t1=10, N=1e3): """compute adiabatic and diabatic spectrum""" times = np.linspace(t0, t1, int(N)) diabates = np.ndarray((times.shape[0], self.N)) adiabates = np.ndarray((times.shape[0], self.N)) for i in range(times.shape[0]): diabates[i] = self.H(times[i]).diagonal().real adiabates[i] = self.eigenenergies(times[i]).real return times, diabates, adiabates def make_transitionless(self): """superadiabatic control -- Berry theory""" return QuantumSystem(self.H + self.get_CD()) def get_CD(self): """compute counter diabatic Hamiltonian""" if (self.H_dot is None): raise OperatorError('H_dot not set') def H_control(t): H0 = self.H(t) H0_dot = self.H_dot(t) w, v = np.linalg.eigh(H0) # v -- unitary transformation matrix v_inv = v.conj().T H1 = np.dot(v_inv, np.dot(H0_dot, v)) n = H1.shape[0] for i in range(n): for j in range(n): if (i == j): H1[i, j] = 0 else: H1[i, j] /= (w[j] - w[i]) return 1j*np.dot(v, np.dot(H1, v_inv)) return asOperator(H_control) def _setup_integrator(self, t0, name, **params): if (self.is_ensemble): func = vonNeumann else: func = schroedinger if (name == 'zvode'): I = ode(_wrap(func, self.H)) else: I = complex_ode(_wrap(func, self.H)) I.set_integrator(name, **params) I.set_initial_value(self.state.as_vector(), t0) return I def print_stats(t, state, verbosity=1, prefix='current'): """monitor internal processes""" np.set_printoptions(precision=5) text = '' if (verbosity > 0): text += prefix + ' time:' text += '\t{:.5f}'.format(t) if (verbosity > 1): text += '\n' text += prefix + ' state:' text += '\t{}\n'.format(state) text += prefix + ' probability:' text += '\t{}\n'.format(state.probabilities) text += prefix + ' probability conservation -- numerical error:' text += '\t{}'.format(abs(1 - state.fidelity)) if (text): print(text) def _wrap_term_crit(t_begin, t_end): """termination criterion for integrator""" SAFETY_MARGIN = 1e-10 def is_endtime_forward(t): return (t > t_end + SAFETY_MARGIN) def is_endtime_backward(t): return (t < t_end - SAFETY_MARGIN) if (t_begin < t_end): return is_endtime_forward else: return is_endtime_backward # https://github.com/scipy/scipy/issues/4781 def _wrap(f, *f_params): """wrapper function -- bug workaround""" def f_wrapped(t, y): return f(t, y, *f_params) return f_wrapped def schroedinger(t, psi, H): """Schroedinger equation""" return -1j*np.dot(H(t), psi) def vonNeumann(t, rho, H): """(quantum Liouville-)von Neumann equation""" H = H(t) rho = rho.reshape(H.shape) rho_dot = -1j*(np.dot(H, rho) - np.dot(rho, H)) return rho_dot.flatten()
[ "numpy.argsort", "numpy.dot", "numpy.ndarray", "numpy.linalg.eigh", "numpy.set_printoptions" ]
[((4938, 4970), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'precision': '(5)'}), '(precision=5)\n', (4957, 4970), True, 'import numpy as np\n'), ((1430, 1443), 'numpy.argsort', 'np.argsort', (['w'], {}), '(w)\n', (1440, 1443), True, 'import numpy as np\n'), ((1606, 1619), 'numpy.argsort', 'np.argsort', (['w'], {}), '(w)\n', (1616, 1619), True, 'import numpy as np\n'), ((3253, 3289), 'numpy.ndarray', 'np.ndarray', (['(times.shape[0], self.N)'], {}), '((times.shape[0], self.N))\n', (3263, 3289), True, 'import numpy as np\n'), ((3310, 3346), 'numpy.ndarray', 'np.ndarray', (['(times.shape[0], self.N)'], {}), '((times.shape[0], self.N))\n', (3320, 3346), True, 'import numpy as np\n'), ((3957, 3975), 'numpy.linalg.eigh', 'np.linalg.eigh', (['H0'], {}), '(H0)\n', (3971, 3975), True, 'import numpy as np\n'), ((6257, 6271), 'numpy.dot', 'np.dot', (['H', 'rho'], {}), '(H, rho)\n', (6263, 6271), True, 'import numpy as np\n'), ((6274, 6288), 'numpy.dot', 'np.dot', (['rho', 'H'], {}), '(rho, H)\n', (6280, 6288), True, 'import numpy as np\n'), ((4078, 4095), 'numpy.dot', 'np.dot', (['H0_dot', 'v'], {}), '(H0_dot, v)\n', (4084, 4095), True, 'import numpy as np\n'), ((4370, 4387), 'numpy.dot', 'np.dot', (['H1', 'v_inv'], {}), '(H1, v_inv)\n', (4376, 4387), True, 'import numpy as np\n')]
import tensorflow as tf import math import numpy as np import os import json from utils import create_cell_starts, normalize_image, colors_to_int, COLOR_DIMS DIR = os.path.join('.', 'dataset', 'processed') class Dataset: def __init__(self, image_size, grid_size, validation_split=0.15, max_crop=0.1, saturation=0.5, exposure=0.2, noise_dev=0.1, hue=0.1): self.image_size = image_size self.grid_size = grid_size self.validation_split = validation_split self.max_crop = max_crop self.saturation = saturation self.exposure = exposure self.noise_dev = noise_dev self.hue = hue self.images = [ os.path.join(DIR, f) for f in os.listdir(DIR) if f.endswith('.jpg') ] self.base_hashes = sorted( list(set([ f.split('_', 1)[0] for f in self.images ]))) self.polygons = [] self.colors = [] max_polys = 0 for image_file in self.images: json_file = image_file[:-4] + '.json' with open(json_file, 'r') as f: raw_labels = json.load(f) image_polys = [] image_colors = [] for resistor in raw_labels['resistors']: poly = resistor['polygon'] colors = resistor['colors'] if len(poly) != 4 or len(colors) != 6: continue poly_points = [ [ float(p['x']), float(p['y']) ] for p in poly ] image_polys.append(poly_points) image_colors.append(colors_to_int(colors)) self.polygons.append(image_polys) self.colors.append(image_colors) max_polys = max(max_polys, len(image_polys)) # Pad polygons for image_polys in self.polygons: while (len(image_polys) < max_polys): image_polys.append(4 * [ [ -1000.0, -1000.0 ] ]) for image_colors in self.colors: while (len(image_colors) < max_polys): image_colors.append(6 * [ 0 ]) # Just to have stable shape for empty validation data self.polygons = np.array(self.polygons) self.colors = np.array(self.colors) def load(self): validation_count = int(len(self.base_hashes) * self.validation_split) validation_hashes = set(self.base_hashes[:validation_count]) validation_images = [] validation_indices = [] training_images = [] training_indices = [] for i, image in enumerate(self.images): if image.split('_', 1)[0] in validation_hashes: validation_images.append(image) validation_indices.append(i) else: training_images.append(image) training_indices.append(i) print('Training dataset has {} images'.format(len(training_images))) print('Validation dataset has {} images'.format(len(validation_images))) # Do this trick to preserve shape training_polygons = self.polygons[training_indices] training_colors = self.colors[training_indices] validation_polygons = self.polygons[validation_indices] validation_colors = self.colors[validation_indices] validation = self.load_single(validation_images, validation_polygons, \ validation_colors) training = self.load_single(training_images, training_polygons, \ training_colors) training = training.map(lambda img, polys, colors: \ self.process_image(img, polys, colors, True)) validation = validation.map(lambda img, polys, colors: \ self.process_image(img, polys, colors, False)) return training, validation def load_single(self, images, polygons, colors): dataset = tf.data.Dataset.from_tensor_slices( \ (tf.constant(images, dtype=tf.string), \ tf.constant(polygons, dtype=tf.float32), \ tf.constant(colors, dtype=tf.int32),)) dataset = dataset.map(lambda img, polys, colors: \ (self.load_image(img), polys, colors,)) dataset.cache() return dataset.shuffle(buffer_size=10000) def load_image(self, image): image = tf.read_file(image) image = tf.image.decode_jpeg(image, channels=3) return image def process_image(self, image, polygons, colors, training): # # Do a major crop to fit image into a square # image, polygons = self.major_crop(image, polygons, training) if training: # # Do a rotation on full-size image # image, polygons = self.random_rotate(image, polygons) # # Do a minor crop # image, polygons = self.minor_crop(image, polygons) # # Resize all images to target size # crop_size = tf.shape(image)[0] check_size = tf.assert_greater_equal(crop_size, self.image_size) with tf.control_dependencies([ check_size ]): image = tf.image.resize_images(image, [ self.image_size, self.image_size ], method=tf.image.ResizeMethod.NEAREST_NEIGHBOR) polygons = polygons * float(self.image_size) / \ tf.cast(crop_size, dtype=tf.float32) # # Change image's type and value range # image = tf.cast(image, dtype=tf.float32) image /= 255.0 # # Color/exposure manipulation, rotation # if training: image = tf.image.rgb_to_hsv(image) # Color h, s, v = tf.split(image, [ 1, 1, 1 ], axis=-1) # Saturation saturation_coeff = tf.random_uniform([], 1.0 - self.saturation, 1.0 + self.saturation) s *= saturation_coeff s = tf.clip_by_value(s, 0.0, 1.0) # Exposure exposure_coeff = tf.random_uniform([], 1.0 - self.exposure, 1.0 + self.exposure) v *= exposure_coeff v = tf.clip_by_value(v, 0.0, 1.0) image = tf.concat([ h, s, v ], axis=-1) image = tf.image.hsv_to_rgb(image) # TODO(indutny): change hue above too image = tf.image.random_hue(image, self.hue) # Rotation rot_count = tf.random_uniform([], 0, 4, dtype=tf.int32) image = tf.image.rot90(image, rot_count) polygons = self.rot90_polygons(image, polygons, rot_count) # # Add gaussian noise # if training: image += tf.random_normal(shape=tf.shape(image), stddev=self.noise_dev) image = tf.clip_by_value(image, 0.0, 1.0) image = normalize_image(image) polygons, colors = self.filter_polygons(polygons, colors, self.image_size) return image, self.create_grid(polygons, colors) def random_rotate(self, image, polygons): angle = tf.random_uniform([], 0.0, math.pi / 2.0) image = tf.contrib.image.rotate(image, angle) polygons = self.rotate_polygons(image, polygons, angle) return image, polygons def major_crop(self, image, polygons, training): size = tf.shape(image)[:2] width = size[1] height = size[0] crop_size = tf.reduce_min(size, axis=-1, name='crop_size') size_delta = size - crop_size if training: # Random crop for training crop_off = tf.cast(size_delta, dtype=tf.float32) * \ tf.random_uniform([ 2 ]) crop_off = tf.cast(crop_off, dtype=tf.int32) else: # Central crop for validation crop_off = size_delta // 2 image = tf.image.crop_to_bounding_box(image, crop_off[0], crop_off[1], \ crop_size, crop_size) polygons = self.crop_polygons(polygons, crop_off, crop_size) return image, polygons def minor_crop(self, image, polygons): width = tf.shape(image)[0] float_width = tf.cast(width, dtype=tf.float32) max_allowed_crop = 1 - self.image_size / (float_width + 1e-23) max_allowed_crop /= 2.0 max_allowed_crop = tf.minimum(self.max_crop, max_allowed_crop) crop_off = tf.random_uniform([], 0.0, max_allowed_crop) * float_width crop_off = tf.cast(crop_off, dtype=tf.int32) crop_size = width - 2 * crop_off image = tf.image.crop_to_bounding_box(image, crop_off, crop_off, crop_size, crop_size) # `crop_polygons` expend 2-dim off and size crop_off = tf.tile(tf.expand_dims(crop_off, axis=0), [ 2 ]) crop_size = tf.tile(tf.expand_dims(crop_size, axis=0), [ 2 ]) polygons = self.crop_polygons(polygons, crop_off, crop_size) return image, polygons def crop_polygons(self, polygons, crop_off, crop_size): # NOTE: `crop_off = [ height, width ]` polygons -= tf.cast(tf.gather(crop_off, [ 1, 0 ]), dtype=tf.float32) return polygons def filter_polygons(self, polygons, colors, image_size): polygon_centers = tf.reduce_mean(polygons, axis=1) # Coordinate-wise mask polygon_mask = tf.logical_and(polygon_centers >= 0.0, \ polygon_centers <= tf.cast(image_size, dtype=tf.float32)) # Polygon-wise mask polygon_mask = tf.logical_and(polygon_mask[:, 0], polygon_mask[:, 1]) return tf.where(polygon_mask, polygons, -tf.ones_like(polygons)), \ tf.where(polygon_mask, colors, tf.zeros_like(colors)) def rot90_polygons(self, image, polygons, rot_count): angle = (math.pi / 2.0) * tf.cast(rot_count, dtype=tf.float32) return self.rotate_polygons(image, polygons, angle) def rotate_polygons(self, image, polygons, angle): cos = tf.cos(angle) sin = tf.sin(angle) matrix = tf.reshape(tf.stack([ cos, -sin, sin, cos ]), shape=[ 2, 2 ]) # Flatten old_shape = polygons.shape polygons = tf.reshape(polygons, [ old_shape[0] * old_shape[1], 2 ]) # Rotate center = tf.cast(tf.gather(tf.shape(image)[:2], [ 1, 0 ]), dtype=tf.float32) / 2.0 polygons = tf.matmul(polygons - center, matrix) + center # Restore shape polygons = tf.reshape(polygons, old_shape) return polygons def create_grid(self, polygons, colors): rects = self.polygons_to_rects(polygons, colors) cell_starts = create_cell_starts(self.grid_size) # Broadcast center = tf.expand_dims(rects['center'], axis=0) center = tf.expand_dims(center, axis=0, name='broadcast_center') center -= cell_starts rect_count = rects['center'].shape[0] # Test is_in_cell = tf.logical_and(center >= 0.0, center < 1 / self.grid_size) is_in_cell = tf.reduce_min(tf.cast(is_in_cell, dtype=tf.float32), axis=-1, name='is_in_cell') is_non_empty_cell = tf.reduce_max(is_in_cell, axis=-1, keepdims=True, name='is_non_empty_cell') first_in_cell = tf.one_hot(tf.argmax(is_in_cell, axis=-1), depth=rect_count, axis=-1, name='first_in_cell') * is_non_empty_cell # Tile sizes, angles, and confidence rest = rects['rest'] rest = tf.reshape(rest, [ 1, 1, rest.shape[0], rest.shape[-1] ]) rest = tf.tile(rest, [ self.grid_size, self.grid_size, 1, 1 ], name='broadcast_rest') # Rescale center so that it would be in [ 0, 1) range center *= float(self.grid_size) rect = tf.concat([ center, rest ], axis=-1) grid = tf.expand_dims(first_in_cell, axis=-1) * rect grid = tf.reduce_sum(grid, axis=2, name='shallow_grid') # Add extra dimension for grid depth grid = tf.expand_dims(grid, axis=2, name='grid') return grid def polygons_to_rects(self, polygons, colors): center = tf.reduce_mean(polygons, axis=1) p0, p1, p2, p3 = \ polygons[:, 0], polygons[:, 1], polygons[:, 2], polygons[:, 3] diag02 = p0 - p2 diag13 = p1 - p3 diag = (tf.norm(diag02, axis=-1) + tf.norm(diag13, axis=-1)) / 2.0 v01 = p0 - p1 v03 = p0 - p3 v21 = p2 - p1 v23 = p2 - p3 area = self.triangle_area(v01, v03) + self.triangle_area(v21, v23) # Compute box width/height using quadratic equation disc = tf.sqrt(diag ** 4 - 4 * area ** 2) # NOTE: `abs` is added just in case, to prevent nan on disc close to 0 width = tf.sqrt(tf.abs(diag ** 2 + disc) / 2.0) height = tf.sqrt(tf.abs(diag ** 2 - disc) / 2.0) size = tf.stack([ width, height ], axis=1) # Find longest side sides = tf.stack([ v01, v03, v21, v23 ], axis=1) side_lens = tf.norm(sides, axis=-1) max_side_i = tf.argmax(side_lens, axis=1) max_side_hot = tf.expand_dims(tf.one_hot(max_side_i, 4), axis=-1) max_side = tf.reduce_sum(max_side_hot * sides, axis=1) angle = tf.atan2(max_side[:, 1], max_side[:, 0]) angle = tf.where(angle < 0.0, angle + math.pi, angle) angle = tf.stack([ tf.cos(angle), tf.sin(angle) ], axis=-1, name='angle') # Rescale offsets, sizes to be a percent of image size center /= float(self.image_size) size /= float(self.image_size) rect_count = center.shape[0] confidence = tf.ones([ rect_count, 1 ], dtype=tf.float32) rest = [ size, angle, confidence ] for i, max_val in enumerate(COLOR_DIMS): color = tf.one_hot(colors[:, i], max_val, dtype=tf.float32) rest.append(color) rest = tf.concat(rest, axis=-1) return { 'center': center, 'rest': rest } def triangle_area(self, side1, side2): return tf.abs(side1[:, 0] * side2[:, 1] - side1[:, 1] * side2[:, 0]) / 2.0
[ "tensorflow.tile", "tensorflow.atan2", "tensorflow.image.resize_images", "tensorflow.shape", "tensorflow.reduce_sum", "tensorflow.split", "tensorflow.norm", "tensorflow.assert_greater_equal", "numpy.array", "tensorflow.control_dependencies", "tensorflow.ones_like", "tensorflow.reduce_mean", ...
[((166, 207), 'os.path.join', 'os.path.join', (['"""."""', '"""dataset"""', '"""processed"""'], {}), "('.', 'dataset', 'processed')\n", (178, 207), False, 'import os\n'), ((1957, 1980), 'numpy.array', 'np.array', (['self.polygons'], {}), '(self.polygons)\n', (1965, 1980), True, 'import numpy as np\n'), ((1999, 2020), 'numpy.array', 'np.array', (['self.colors'], {}), '(self.colors)\n', (2007, 2020), True, 'import numpy as np\n'), ((3888, 3907), 'tensorflow.read_file', 'tf.read_file', (['image'], {}), '(image)\n', (3900, 3907), True, 'import tensorflow as tf\n'), ((3920, 3959), 'tensorflow.image.decode_jpeg', 'tf.image.decode_jpeg', (['image'], {'channels': '(3)'}), '(image, channels=3)\n', (3940, 3959), True, 'import tensorflow as tf\n'), ((4504, 4555), 'tensorflow.assert_greater_equal', 'tf.assert_greater_equal', (['crop_size', 'self.image_size'], {}), '(crop_size, self.image_size)\n', (4527, 4555), True, 'import tensorflow as tf\n'), ((4921, 4953), 'tensorflow.cast', 'tf.cast', (['image'], {'dtype': 'tf.float32'}), '(image, dtype=tf.float32)\n', (4928, 4953), True, 'import tensorflow as tf\n'), ((6099, 6121), 'utils.normalize_image', 'normalize_image', (['image'], {}), '(image)\n', (6114, 6121), False, 'from utils import create_cell_starts, normalize_image, colors_to_int, COLOR_DIMS\n'), ((6311, 6352), 'tensorflow.random_uniform', 'tf.random_uniform', (['[]', '(0.0)', '(math.pi / 2.0)'], {}), '([], 0.0, math.pi / 2.0)\n', (6328, 6352), True, 'import tensorflow as tf\n'), ((6365, 6402), 'tensorflow.contrib.image.rotate', 'tf.contrib.image.rotate', (['image', 'angle'], {}), '(image, angle)\n', (6388, 6402), True, 'import tensorflow as tf\n'), ((6631, 6677), 'tensorflow.reduce_min', 'tf.reduce_min', (['size'], {'axis': '(-1)', 'name': '"""crop_size"""'}), "(size, axis=-1, name='crop_size')\n", (6644, 6677), True, 'import tensorflow as tf\n'), ((6999, 7087), 'tensorflow.image.crop_to_bounding_box', 'tf.image.crop_to_bounding_box', (['image', 'crop_off[0]', 'crop_off[1]', 'crop_size', 'crop_size'], {}), '(image, crop_off[0], crop_off[1], crop_size,\n crop_size)\n', (7028, 7087), True, 'import tensorflow as tf\n'), ((7277, 7309), 'tensorflow.cast', 'tf.cast', (['width'], {'dtype': 'tf.float32'}), '(width, dtype=tf.float32)\n', (7284, 7309), True, 'import tensorflow as tf\n'), ((7429, 7472), 'tensorflow.minimum', 'tf.minimum', (['self.max_crop', 'max_allowed_crop'], {}), '(self.max_crop, max_allowed_crop)\n', (7439, 7472), True, 'import tensorflow as tf\n'), ((7563, 7596), 'tensorflow.cast', 'tf.cast', (['crop_off'], {'dtype': 'tf.int32'}), '(crop_off, dtype=tf.int32)\n', (7570, 7596), True, 'import tensorflow as tf\n'), ((7648, 7726), 'tensorflow.image.crop_to_bounding_box', 'tf.image.crop_to_bounding_box', (['image', 'crop_off', 'crop_off', 'crop_size', 'crop_size'], {}), '(image, crop_off, crop_off, crop_size, crop_size)\n', (7677, 7726), True, 'import tensorflow as tf\n'), ((8283, 8315), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['polygons'], {'axis': '(1)'}), '(polygons, axis=1)\n', (8297, 8315), True, 'import tensorflow as tf\n'), ((8514, 8568), 'tensorflow.logical_and', 'tf.logical_and', (['polygon_mask[:, 0]', 'polygon_mask[:, 1]'], {}), '(polygon_mask[:, 0], polygon_mask[:, 1])\n', (8528, 8568), True, 'import tensorflow as tf\n'), ((8948, 8961), 'tensorflow.cos', 'tf.cos', (['angle'], {}), '(angle)\n', (8954, 8961), True, 'import tensorflow as tf\n'), ((8972, 8985), 'tensorflow.sin', 'tf.sin', (['angle'], {}), '(angle)\n', (8978, 8985), True, 'import tensorflow as tf\n'), ((9123, 9177), 'tensorflow.reshape', 'tf.reshape', (['polygons', '[old_shape[0] * old_shape[1], 2]'], {}), '(polygons, [old_shape[0] * old_shape[1], 2])\n', (9133, 9177), True, 'import tensorflow as tf\n'), ((9386, 9417), 'tensorflow.reshape', 'tf.reshape', (['polygons', 'old_shape'], {}), '(polygons, old_shape)\n', (9396, 9417), True, 'import tensorflow as tf\n'), ((9554, 9588), 'utils.create_cell_starts', 'create_cell_starts', (['self.grid_size'], {}), '(self.grid_size)\n', (9572, 9588), False, 'from utils import create_cell_starts, normalize_image, colors_to_int, COLOR_DIMS\n'), ((9619, 9658), 'tensorflow.expand_dims', 'tf.expand_dims', (["rects['center']"], {'axis': '(0)'}), "(rects['center'], axis=0)\n", (9633, 9658), True, 'import tensorflow as tf\n'), ((9672, 9727), 'tensorflow.expand_dims', 'tf.expand_dims', (['center'], {'axis': '(0)', 'name': '"""broadcast_center"""'}), "(center, axis=0, name='broadcast_center')\n", (9686, 9727), True, 'import tensorflow as tf\n'), ((9826, 9884), 'tensorflow.logical_and', 'tf.logical_and', (['(center >= 0.0)', '(center < 1 / self.grid_size)'], {}), '(center >= 0.0, center < 1 / self.grid_size)\n', (9840, 9884), True, 'import tensorflow as tf\n'), ((10015, 10090), 'tensorflow.reduce_max', 'tf.reduce_max', (['is_in_cell'], {'axis': '(-1)', 'keepdims': '(True)', 'name': '"""is_non_empty_cell"""'}), "(is_in_cell, axis=-1, keepdims=True, name='is_non_empty_cell')\n", (10028, 10090), True, 'import tensorflow as tf\n'), ((10318, 10373), 'tensorflow.reshape', 'tf.reshape', (['rest', '[1, 1, rest.shape[0], rest.shape[-1]]'], {}), '(rest, [1, 1, rest.shape[0], rest.shape[-1]])\n', (10328, 10373), True, 'import tensorflow as tf\n'), ((10387, 10463), 'tensorflow.tile', 'tf.tile', (['rest', '[self.grid_size, self.grid_size, 1, 1]'], {'name': '"""broadcast_rest"""'}), "(rest, [self.grid_size, self.grid_size, 1, 1], name='broadcast_rest')\n", (10394, 10463), True, 'import tensorflow as tf\n'), ((10581, 10615), 'tensorflow.concat', 'tf.concat', (['[center, rest]'], {'axis': '(-1)'}), '([center, rest], axis=-1)\n', (10590, 10615), True, 'import tensorflow as tf\n'), ((10687, 10735), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['grid'], {'axis': '(2)', 'name': '"""shallow_grid"""'}), "(grid, axis=2, name='shallow_grid')\n", (10700, 10735), True, 'import tensorflow as tf\n'), ((10789, 10830), 'tensorflow.expand_dims', 'tf.expand_dims', (['grid'], {'axis': '(2)', 'name': '"""grid"""'}), "(grid, axis=2, name='grid')\n", (10803, 10830), True, 'import tensorflow as tf\n'), ((10911, 10943), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['polygons'], {'axis': '(1)'}), '(polygons, axis=1)\n', (10925, 10943), True, 'import tensorflow as tf\n'), ((11367, 11401), 'tensorflow.sqrt', 'tf.sqrt', (['(diag ** 4 - 4 * area ** 2)'], {}), '(diag ** 4 - 4 * area ** 2)\n', (11374, 11401), True, 'import tensorflow as tf\n'), ((11594, 11627), 'tensorflow.stack', 'tf.stack', (['[width, height]'], {'axis': '(1)'}), '([width, height], axis=1)\n', (11602, 11627), True, 'import tensorflow as tf\n'), ((11667, 11705), 'tensorflow.stack', 'tf.stack', (['[v01, v03, v21, v23]'], {'axis': '(1)'}), '([v01, v03, v21, v23], axis=1)\n', (11675, 11705), True, 'import tensorflow as tf\n'), ((11724, 11747), 'tensorflow.norm', 'tf.norm', (['sides'], {'axis': '(-1)'}), '(sides, axis=-1)\n', (11731, 11747), True, 'import tensorflow as tf\n'), ((11765, 11793), 'tensorflow.argmax', 'tf.argmax', (['side_lens'], {'axis': '(1)'}), '(side_lens, axis=1)\n', (11774, 11793), True, 'import tensorflow as tf\n'), ((11879, 11922), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(max_side_hot * sides)'], {'axis': '(1)'}), '(max_side_hot * sides, axis=1)\n', (11892, 11922), True, 'import tensorflow as tf\n'), ((11936, 11976), 'tensorflow.atan2', 'tf.atan2', (['max_side[:, 1]', 'max_side[:, 0]'], {}), '(max_side[:, 1], max_side[:, 0])\n', (11944, 11976), True, 'import tensorflow as tf\n'), ((11989, 12034), 'tensorflow.where', 'tf.where', (['(angle < 0.0)', '(angle + math.pi)', 'angle'], {}), '(angle < 0.0, angle + math.pi, angle)\n', (11997, 12034), True, 'import tensorflow as tf\n'), ((12296, 12338), 'tensorflow.ones', 'tf.ones', (['[rect_count, 1]'], {'dtype': 'tf.float32'}), '([rect_count, 1], dtype=tf.float32)\n', (12303, 12338), True, 'import tensorflow as tf\n'), ((12529, 12553), 'tensorflow.concat', 'tf.concat', (['rest'], {'axis': '(-1)'}), '(rest, axis=-1)\n', (12538, 12553), True, 'import tensorflow as tf\n'), ((670, 690), 'os.path.join', 'os.path.join', (['DIR', 'f'], {}), '(DIR, f)\n', (682, 690), False, 'import os\n'), ((4467, 4482), 'tensorflow.shape', 'tf.shape', (['image'], {}), '(image)\n', (4475, 4482), True, 'import tensorflow as tf\n'), ((4565, 4602), 'tensorflow.control_dependencies', 'tf.control_dependencies', (['[check_size]'], {}), '([check_size])\n', (4588, 4602), True, 'import tensorflow as tf\n'), ((4620, 4737), 'tensorflow.image.resize_images', 'tf.image.resize_images', (['image', '[self.image_size, self.image_size]'], {'method': 'tf.image.ResizeMethod.NEAREST_NEIGHBOR'}), '(image, [self.image_size, self.image_size], method=tf\n .image.ResizeMethod.NEAREST_NEIGHBOR)\n', (4642, 4737), True, 'import tensorflow as tf\n'), ((4817, 4853), 'tensorflow.cast', 'tf.cast', (['crop_size'], {'dtype': 'tf.float32'}), '(crop_size, dtype=tf.float32)\n', (4824, 4853), True, 'import tensorflow as tf\n'), ((5061, 5087), 'tensorflow.image.rgb_to_hsv', 'tf.image.rgb_to_hsv', (['image'], {}), '(image)\n', (5080, 5087), True, 'import tensorflow as tf\n'), ((5119, 5154), 'tensorflow.split', 'tf.split', (['image', '[1, 1, 1]'], {'axis': '(-1)'}), '(image, [1, 1, 1], axis=-1)\n', (5127, 5154), True, 'import tensorflow as tf\n'), ((5202, 5269), 'tensorflow.random_uniform', 'tf.random_uniform', (['[]', '(1.0 - self.saturation)', '(1.0 + self.saturation)'], {}), '([], 1.0 - self.saturation, 1.0 + self.saturation)\n', (5219, 5269), True, 'import tensorflow as tf\n'), ((5318, 5347), 'tensorflow.clip_by_value', 'tf.clip_by_value', (['s', '(0.0)', '(1.0)'], {}), '(s, 0.0, 1.0)\n', (5334, 5347), True, 'import tensorflow as tf\n'), ((5389, 5452), 'tensorflow.random_uniform', 'tf.random_uniform', (['[]', '(1.0 - self.exposure)', '(1.0 + self.exposure)'], {}), '([], 1.0 - self.exposure, 1.0 + self.exposure)\n', (5406, 5452), True, 'import tensorflow as tf\n'), ((5499, 5528), 'tensorflow.clip_by_value', 'tf.clip_by_value', (['v', '(0.0)', '(1.0)'], {}), '(v, 0.0, 1.0)\n', (5515, 5528), True, 'import tensorflow as tf\n'), ((5544, 5573), 'tensorflow.concat', 'tf.concat', (['[h, s, v]'], {'axis': '(-1)'}), '([h, s, v], axis=-1)\n', (5553, 5573), True, 'import tensorflow as tf\n'), ((5590, 5616), 'tensorflow.image.hsv_to_rgb', 'tf.image.hsv_to_rgb', (['image'], {}), '(image)\n', (5609, 5616), True, 'import tensorflow as tf\n'), ((5676, 5712), 'tensorflow.image.random_hue', 'tf.image.random_hue', (['image', 'self.hue'], {}), '(image, self.hue)\n', (5695, 5712), True, 'import tensorflow as tf\n'), ((5749, 5792), 'tensorflow.random_uniform', 'tf.random_uniform', (['[]', '(0)', '(4)'], {'dtype': 'tf.int32'}), '([], 0, 4, dtype=tf.int32)\n', (5766, 5792), True, 'import tensorflow as tf\n'), ((5807, 5839), 'tensorflow.image.rot90', 'tf.image.rot90', (['image', 'rot_count'], {}), '(image, rot_count)\n', (5821, 5839), True, 'import tensorflow as tf\n'), ((6052, 6085), 'tensorflow.clip_by_value', 'tf.clip_by_value', (['image', '(0.0)', '(1.0)'], {}), '(image, 0.0, 1.0)\n', (6068, 6085), True, 'import tensorflow as tf\n'), ((6553, 6568), 'tensorflow.shape', 'tf.shape', (['image'], {}), '(image)\n', (6561, 6568), True, 'import tensorflow as tf\n'), ((6873, 6906), 'tensorflow.cast', 'tf.cast', (['crop_off'], {'dtype': 'tf.int32'}), '(crop_off, dtype=tf.int32)\n', (6880, 6906), True, 'import tensorflow as tf\n'), ((7240, 7255), 'tensorflow.shape', 'tf.shape', (['image'], {}), '(image)\n', (7248, 7255), True, 'import tensorflow as tf\n'), ((7489, 7533), 'tensorflow.random_uniform', 'tf.random_uniform', (['[]', '(0.0)', 'max_allowed_crop'], {}), '([], 0.0, max_allowed_crop)\n', (7506, 7533), True, 'import tensorflow as tf\n'), ((7807, 7839), 'tensorflow.expand_dims', 'tf.expand_dims', (['crop_off'], {'axis': '(0)'}), '(crop_off, axis=0)\n', (7821, 7839), True, 'import tensorflow as tf\n'), ((7872, 7905), 'tensorflow.expand_dims', 'tf.expand_dims', (['crop_size'], {'axis': '(0)'}), '(crop_size, axis=0)\n', (7886, 7905), True, 'import tensorflow as tf\n'), ((8132, 8159), 'tensorflow.gather', 'tf.gather', (['crop_off', '[1, 0]'], {}), '(crop_off, [1, 0])\n', (8141, 8159), True, 'import tensorflow as tf\n'), ((8791, 8827), 'tensorflow.cast', 'tf.cast', (['rot_count'], {'dtype': 'tf.float32'}), '(rot_count, dtype=tf.float32)\n', (8798, 8827), True, 'import tensorflow as tf\n'), ((9011, 9042), 'tensorflow.stack', 'tf.stack', (['[cos, -sin, sin, cos]'], {}), '([cos, -sin, sin, cos])\n', (9019, 9042), True, 'import tensorflow as tf\n'), ((9304, 9340), 'tensorflow.matmul', 'tf.matmul', (['(polygons - center)', 'matrix'], {}), '(polygons - center, matrix)\n', (9313, 9340), True, 'import tensorflow as tf\n'), ((9916, 9953), 'tensorflow.cast', 'tf.cast', (['is_in_cell'], {'dtype': 'tf.float32'}), '(is_in_cell, dtype=tf.float32)\n', (9923, 9953), True, 'import tensorflow as tf\n'), ((10630, 10668), 'tensorflow.expand_dims', 'tf.expand_dims', (['first_in_cell'], {'axis': '(-1)'}), '(first_in_cell, axis=-1)\n', (10644, 10668), True, 'import tensorflow as tf\n'), ((11828, 11853), 'tensorflow.one_hot', 'tf.one_hot', (['max_side_i', '(4)'], {}), '(max_side_i, 4)\n', (11838, 11853), True, 'import tensorflow as tf\n'), ((12440, 12491), 'tensorflow.one_hot', 'tf.one_hot', (['colors[:, i]', 'max_val'], {'dtype': 'tf.float32'}), '(colors[:, i], max_val, dtype=tf.float32)\n', (12450, 12491), True, 'import tensorflow as tf\n'), ((12654, 12715), 'tensorflow.abs', 'tf.abs', (['(side1[:, 0] * side2[:, 1] - side1[:, 1] * side2[:, 0])'], {}), '(side1[:, 0] * side2[:, 1] - side1[:, 1] * side2[:, 0])\n', (12660, 12715), True, 'import tensorflow as tf\n'), ((708, 723), 'os.listdir', 'os.listdir', (['DIR'], {}), '(DIR)\n', (718, 723), False, 'import os\n'), ((1057, 1069), 'json.load', 'json.load', (['f'], {}), '(f)\n', (1066, 1069), False, 'import json\n'), ((3534, 3570), 'tensorflow.constant', 'tf.constant', (['images'], {'dtype': 'tf.string'}), '(images, dtype=tf.string)\n', (3545, 3570), True, 'import tensorflow as tf\n'), ((3583, 3622), 'tensorflow.constant', 'tf.constant', (['polygons'], {'dtype': 'tf.float32'}), '(polygons, dtype=tf.float32)\n', (3594, 3622), True, 'import tensorflow as tf\n'), ((3635, 3670), 'tensorflow.constant', 'tf.constant', (['colors'], {'dtype': 'tf.int32'}), '(colors, dtype=tf.int32)\n', (3646, 3670), True, 'import tensorflow as tf\n'), ((6779, 6816), 'tensorflow.cast', 'tf.cast', (['size_delta'], {'dtype': 'tf.float32'}), '(size_delta, dtype=tf.float32)\n', (6786, 6816), True, 'import tensorflow as tf\n'), ((6831, 6853), 'tensorflow.random_uniform', 'tf.random_uniform', (['[2]'], {}), '([2])\n', (6848, 6853), True, 'import tensorflow as tf\n'), ((8431, 8468), 'tensorflow.cast', 'tf.cast', (['image_size'], {'dtype': 'tf.float32'}), '(image_size, dtype=tf.float32)\n', (8438, 8468), True, 'import tensorflow as tf\n'), ((8681, 8702), 'tensorflow.zeros_like', 'tf.zeros_like', (['colors'], {}), '(colors)\n', (8694, 8702), True, 'import tensorflow as tf\n'), ((10131, 10161), 'tensorflow.argmax', 'tf.argmax', (['is_in_cell'], {'axis': '(-1)'}), '(is_in_cell, axis=-1)\n', (10140, 10161), True, 'import tensorflow as tf\n'), ((11095, 11119), 'tensorflow.norm', 'tf.norm', (['diag02'], {'axis': '(-1)'}), '(diag02, axis=-1)\n', (11102, 11119), True, 'import tensorflow as tf\n'), ((11122, 11146), 'tensorflow.norm', 'tf.norm', (['diag13'], {'axis': '(-1)'}), '(diag13, axis=-1)\n', (11129, 11146), True, 'import tensorflow as tf\n'), ((11498, 11522), 'tensorflow.abs', 'tf.abs', (['(diag ** 2 + disc)'], {}), '(diag ** 2 + disc)\n', (11504, 11522), True, 'import tensorflow as tf\n'), ((11551, 11575), 'tensorflow.abs', 'tf.abs', (['(diag ** 2 - disc)'], {}), '(diag ** 2 - disc)\n', (11557, 11575), True, 'import tensorflow as tf\n'), ((12058, 12071), 'tensorflow.cos', 'tf.cos', (['angle'], {}), '(angle)\n', (12064, 12071), True, 'import tensorflow as tf\n'), ((12073, 12086), 'tensorflow.sin', 'tf.sin', (['angle'], {}), '(angle)\n', (12079, 12086), True, 'import tensorflow as tf\n'), ((1443, 1464), 'utils.colors_to_int', 'colors_to_int', (['colors'], {}), '(colors)\n', (1456, 1464), False, 'from utils import create_cell_starts, normalize_image, colors_to_int, COLOR_DIMS\n'), ((5998, 6013), 'tensorflow.shape', 'tf.shape', (['image'], {}), '(image)\n', (6006, 6013), True, 'import tensorflow as tf\n'), ((8615, 8637), 'tensorflow.ones_like', 'tf.ones_like', (['polygons'], {}), '(polygons)\n', (8627, 8637), True, 'import tensorflow as tf\n'), ((9225, 9240), 'tensorflow.shape', 'tf.shape', (['image'], {}), '(image)\n', (9233, 9240), True, 'import tensorflow as tf\n')]
# -*- coding: utf-8 -*- """Tests for calculating the spherical projection.""" import numpy as np from numpy.testing import assert_allclose from pylode.lib.spherical_harmonics import evaluate_spherical_harmonics class TestSphericalHarmonics: """Test correct behavior of spherical harmonics code""" def test_spherical_harmonics(self): """Start by evaluating spherical harmonics at some special points""" vectors_zdir = np.array([[0, 0, 1], [0, 0, 2]]) lmax = 8 coeffs = evaluate_spherical_harmonics(vectors_zdir, lmax) # spherical harmonics should be independent of length assert np.linalg.norm(coeffs[0] - coeffs[1]) < 1e-14 # Compare to exact values of Y_lm for vectors in +z-direction nonzero_indices = np.array([l**2 + l for l in range(lmax + 1)]) coeffs_nonzero = coeffs[0, nonzero_indices] exact_vals = np.sqrt((2 * np.arange(lmax + 1) + 1) / 4 / np.pi) assert np.linalg.norm(coeffs_nonzero - exact_vals) < 1e-14 # Make sure that all other values are (essentially) zero assert abs(np.sum(coeffs[0]**2) - np.sum(exact_vals**2)) < 1e-14 def test_spherical_harmonics_x_y(self): """use vectors confined on x-y plane""" rng = np.random.default_rng(3218932) N = 10 lmax = 8 vectors_xy = np.zeros((N, 3)) vectors_xy[:, :2] = rng.normal(0, 1, (N, 2)) # Certain coefficients need to vanish by symmetry coeffs = evaluate_spherical_harmonics(vectors_xy, lmax) for l in range(lmax + 1): for im, m in enumerate(np.arange(-l, l + 1)): if l + m % 2 == 1: assert np.linalg.norm(coeffs[:, l**2 + im]) / N < 1e-14 def test_spherical_harmonics_addition(self): """Verify addition theorem of spherical harmonics evaluated at large number of random points """ N = 1000 lmax = 8 rng = np.random.default_rng(3218932) vectors = rng.normal(0, 1, (N, 3)) coeffs = evaluate_spherical_harmonics(vectors, lmax) num_coeffs = (lmax + 1)**2 assert coeffs.shape == (N, num_coeffs) # Verify addition theorem exact_vals = (2 * np.arange(lmax + 1) + 1) / (4. * np.pi) for l in range(lmax + 1): prod = np.sum(coeffs[:, l**2:(l + 1)**2]**2, axis=1) error = np.linalg.norm(prod - exact_vals[l]) assert error / N < 1e-15 # In the limit of infinitely many points, the columns should # be orthonormal. Reuse the values from above for a Monte Carlo # integration (if this was the sole purpose, there would be much # more efficient methods for quadrature) innerprod_matrix = coeffs.T @ coeffs / N * np.pi * 4 difference = innerprod_matrix - np.eye(num_coeffs) assert np.linalg.norm(difference) / num_coeffs**2 < 1e-2 def test_spherical_harmonics_orthogonality(self): """ The spherical harmonics form an orthonormal basis of the L2 space of functions defined on the 2-sphere S2. In simpler terms, any reasonable function f(theta, phi) that only depends on the two spherical angles can be expressed as a linear combination of spherical harmonics, which need to satisfy certain orthogonality relations that are expressed in terms of integrals over the two angles. In this test, we perform a numerical integration to verify the orthogonality of the used spherical harmonics. """ # Define the two spherical angles over a grid N_theta = 200 N_phi = 200 phis = np.linspace(0, 2*np.pi, N_phi, endpoint=False) thetas = np.arccos(np.linspace(-1,1,N_theta+1, endpoint=True)) thetas = 0.5 * (thetas[1:] + thetas[:-1]) #thetas = np.arccos(np.linspace(-1,1,N_theta, endpoint=True)) phis_2d, thetas_2d = np.meshgrid(phis, thetas, indexing='ij') assert phis_2d.shape == (N_phi, N_theta) # first index is for phis # Generate unit vectors along the specified directions unit_vectors = np.zeros((N_phi, N_theta, 3)) unit_vectors[:,:,0] = np.cos(phis_2d) * np.sin(thetas_2d) unit_vectors[:,:,1] = np.sin(phis_2d) * np.sin(thetas_2d) unit_vectors[:,:,2] = np.cos(thetas_2d) # Evaluate the real spherical harmonics using the general code # from the library lmax = 5 sph_harm_values = np.zeros(((lmax+1)**2, N_phi * N_theta)) for i, vecs in enumerate(unit_vectors): # Pass a 2D array of unit vectors for each fixed value of theta sph_harm_values[:,i*N_theta:(i+1)*N_theta] = evaluate_spherical_harmonics(vecs, lmax=lmax).T # Orthogonality matrix: prefac = 4 * np.pi / (N_phi * N_theta) ortho_matrix = prefac * sph_harm_values @ sph_harm_values.T ortho_matrix_ref = np.eye((lmax+1)**2) assert_allclose(ortho_matrix, ortho_matrix_ref, atol=1e-2, rtol=1e-2) def test_spherical_harmonics_analytical_small_l(self): """ For small values of l=0,1,2 we compare the obtained values for the spherical harmonics evaluated at various points with the analytical expressions. l=0 is mostly a sanity check, while l=1,2 are the first nontrivial spherical harmonics of odd / even degree, respectively. Perfect agreement of these 1+3+5=9 functions is highly likely to catch any potential discrepancies in the used conventions of the spherical harmonics. """ # Define the two spherical angles over a grid N_theta = 53 N_phi = 119 phis = np.linspace(0, 2*np.pi, N_phi) thetas = np.arccos(np.linspace(-1,1,N_theta)) phis_2d, thetas_2d = np.meshgrid(phis, thetas, indexing='ij') assert phis_2d.shape == (N_phi, N_theta) # first index is for phis # Generate unit vectors along the specified directions unit_vectors = np.zeros((N_phi, N_theta, 3)) unit_vectors[:,:,0] = np.cos(phis_2d) * np.sin(thetas_2d) unit_vectors[:,:,1] = np.sin(phis_2d) * np.sin(thetas_2d) unit_vectors[:,:,2] = np.cos(thetas_2d) # Define exact spherical harmonics prefac1 = 1./np.sqrt(4*np.pi) prefac2 = np.sqrt(3 / (4 * np.pi)) prefac3 = np.sqrt(15 / (4 * np.pi)) prefac20 = np.sqrt(5 / (16 * np.pi)) prefac21 = np.sqrt(15 / (4 * np.pi)) prefac22 = np.sqrt(15/ (16 * np.pi)) cart_x = lambda theta, phi: np.cos(phi) * np.sin(theta) cart_y = lambda theta, phi: np.sin(phi) * np.sin(theta) cart_z = lambda theta, phi: np.cos(theta) Y00 = lambda theta, phi: prefac1 * np.ones_like(theta) Y1m = lambda theta, phi: prefac2 * np.sin(theta) * np.sin(phi) Y10 = lambda theta, phi: prefac2 * np.cos(theta) Y11 = lambda theta, phi: prefac2 * np.sin(theta) * np.cos(phi) Y2n = lambda theta, phi: prefac21 * cart_y(theta, phi) * cart_x(theta, phi) Y2m = lambda theta, phi: prefac21 * cart_y(theta, phi) * cart_z(theta, phi) Y20 = lambda theta, phi: prefac20 * (3 * np.cos(theta)**2 - 1) Y21 = lambda theta, phi: prefac21 * cart_x(theta, phi) * cart_z(theta, phi) Y22 = lambda theta, phi: prefac22 * (cart_x(theta, phi)**2 - cart_y(theta, phi)**2) # Evaluate the real spherical harmonics using the # analytical expressions sph_harm_exact = np.zeros((9, N_phi, N_theta)) sph_harm_exact[0] = Y00(thetas_2d, phis_2d) sph_harm_exact[1] = Y1m(thetas_2d, phis_2d) sph_harm_exact[2] = Y10(thetas_2d, phis_2d) sph_harm_exact[3] = Y11(thetas_2d, phis_2d) sph_harm_exact[4] = Y2n(thetas_2d, phis_2d) sph_harm_exact[5] = Y2m(thetas_2d, phis_2d) sph_harm_exact[6] = Y20(thetas_2d, phis_2d) sph_harm_exact[7] = Y21(thetas_2d, phis_2d) sph_harm_exact[8] = Y22(thetas_2d, phis_2d) # Evaluate the real spherical harmonics using the general code # from the library sph_harm_check = np.zeros_like(sph_harm_exact) for i, vecs in enumerate(unit_vectors): # Pass a 2D array of unit vectors for each fixed value of theta sph_harm_check[:,i] = evaluate_spherical_harmonics(vecs, lmax=2).T # Check agreement of the pyLODE spherical harmonics with the exact values assert_allclose(sph_harm_exact, sph_harm_check, rtol=1e-15, atol=3e-16)
[ "numpy.ones_like", "numpy.eye", "numpy.sqrt", "numpy.random.default_rng", "numpy.testing.assert_allclose", "pylode.lib.spherical_harmonics.evaluate_spherical_harmonics", "numpy.array", "numpy.zeros", "numpy.linspace", "numpy.sum", "numpy.cos", "numpy.linalg.norm", "numpy.sin", "numpy.meshg...
[((460, 492), 'numpy.array', 'np.array', (['[[0, 0, 1], [0, 0, 2]]'], {}), '([[0, 0, 1], [0, 0, 2]])\n', (468, 492), True, 'import numpy as np\n'), ((529, 577), 'pylode.lib.spherical_harmonics.evaluate_spherical_harmonics', 'evaluate_spherical_harmonics', (['vectors_zdir', 'lmax'], {}), '(vectors_zdir, lmax)\n', (557, 577), False, 'from pylode.lib.spherical_harmonics import evaluate_spherical_harmonics\n'), ((1298, 1328), 'numpy.random.default_rng', 'np.random.default_rng', (['(3218932)'], {}), '(3218932)\n', (1319, 1328), True, 'import numpy as np\n'), ((1385, 1401), 'numpy.zeros', 'np.zeros', (['(N, 3)'], {}), '((N, 3))\n', (1393, 1401), True, 'import numpy as np\n'), ((1535, 1581), 'pylode.lib.spherical_harmonics.evaluate_spherical_harmonics', 'evaluate_spherical_harmonics', (['vectors_xy', 'lmax'], {}), '(vectors_xy, lmax)\n', (1563, 1581), False, 'from pylode.lib.spherical_harmonics import evaluate_spherical_harmonics\n'), ((2008, 2038), 'numpy.random.default_rng', 'np.random.default_rng', (['(3218932)'], {}), '(3218932)\n', (2029, 2038), True, 'import numpy as np\n'), ((2101, 2144), 'pylode.lib.spherical_harmonics.evaluate_spherical_harmonics', 'evaluate_spherical_harmonics', (['vectors', 'lmax'], {}), '(vectors, lmax)\n', (2129, 2144), False, 'from pylode.lib.spherical_harmonics import evaluate_spherical_harmonics\n'), ((3766, 3814), 'numpy.linspace', 'np.linspace', (['(0)', '(2 * np.pi)', 'N_phi'], {'endpoint': '(False)'}), '(0, 2 * np.pi, N_phi, endpoint=False)\n', (3777, 3814), True, 'import numpy as np\n'), ((4037, 4077), 'numpy.meshgrid', 'np.meshgrid', (['phis', 'thetas'], {'indexing': '"""ij"""'}), "(phis, thetas, indexing='ij')\n", (4048, 4077), True, 'import numpy as np\n'), ((4244, 4273), 'numpy.zeros', 'np.zeros', (['(N_phi, N_theta, 3)'], {}), '((N_phi, N_theta, 3))\n', (4252, 4273), True, 'import numpy as np\n'), ((4439, 4456), 'numpy.cos', 'np.cos', (['thetas_2d'], {}), '(thetas_2d)\n', (4445, 4456), True, 'import numpy as np\n'), ((4604, 4648), 'numpy.zeros', 'np.zeros', (['((lmax + 1) ** 2, N_phi * N_theta)'], {}), '(((lmax + 1) ** 2, N_phi * N_theta))\n', (4612, 4648), True, 'import numpy as np\n'), ((5058, 5081), 'numpy.eye', 'np.eye', (['((lmax + 1) ** 2)'], {}), '((lmax + 1) ** 2)\n', (5064, 5081), True, 'import numpy as np\n'), ((5087, 5156), 'numpy.testing.assert_allclose', 'assert_allclose', (['ortho_matrix', 'ortho_matrix_ref'], {'atol': '(0.01)', 'rtol': '(0.01)'}), '(ortho_matrix, ortho_matrix_ref, atol=0.01, rtol=0.01)\n', (5102, 5156), False, 'from numpy.testing import assert_allclose\n'), ((5853, 5885), 'numpy.linspace', 'np.linspace', (['(0)', '(2 * np.pi)', 'N_phi'], {}), '(0, 2 * np.pi, N_phi)\n', (5864, 5885), True, 'import numpy as np\n'), ((5969, 6009), 'numpy.meshgrid', 'np.meshgrid', (['phis', 'thetas'], {'indexing': '"""ij"""'}), "(phis, thetas, indexing='ij')\n", (5980, 6009), True, 'import numpy as np\n'), ((6176, 6205), 'numpy.zeros', 'np.zeros', (['(N_phi, N_theta, 3)'], {}), '((N_phi, N_theta, 3))\n', (6184, 6205), True, 'import numpy as np\n'), ((6371, 6388), 'numpy.cos', 'np.cos', (['thetas_2d'], {}), '(thetas_2d)\n', (6377, 6388), True, 'import numpy as np\n'), ((6493, 6517), 'numpy.sqrt', 'np.sqrt', (['(3 / (4 * np.pi))'], {}), '(3 / (4 * np.pi))\n', (6500, 6517), True, 'import numpy as np\n'), ((6537, 6562), 'numpy.sqrt', 'np.sqrt', (['(15 / (4 * np.pi))'], {}), '(15 / (4 * np.pi))\n', (6544, 6562), True, 'import numpy as np\n'), ((6583, 6608), 'numpy.sqrt', 'np.sqrt', (['(5 / (16 * np.pi))'], {}), '(5 / (16 * np.pi))\n', (6590, 6608), True, 'import numpy as np\n'), ((6629, 6654), 'numpy.sqrt', 'np.sqrt', (['(15 / (4 * np.pi))'], {}), '(15 / (4 * np.pi))\n', (6636, 6654), True, 'import numpy as np\n'), ((6675, 6701), 'numpy.sqrt', 'np.sqrt', (['(15 / (16 * np.pi))'], {}), '(15 / (16 * np.pi))\n', (6682, 6701), True, 'import numpy as np\n'), ((7689, 7718), 'numpy.zeros', 'np.zeros', (['(9, N_phi, N_theta)'], {}), '((9, N_phi, N_theta))\n', (7697, 7718), True, 'import numpy as np\n'), ((8324, 8353), 'numpy.zeros_like', 'np.zeros_like', (['sph_harm_exact'], {}), '(sph_harm_exact)\n', (8337, 8353), True, 'import numpy as np\n'), ((8655, 8726), 'numpy.testing.assert_allclose', 'assert_allclose', (['sph_harm_exact', 'sph_harm_check'], {'rtol': '(1e-15)', 'atol': '(3e-16)'}), '(sph_harm_exact, sph_harm_check, rtol=1e-15, atol=3e-16)\n', (8670, 8726), False, 'from numpy.testing import assert_allclose\n'), ((659, 696), 'numpy.linalg.norm', 'np.linalg.norm', (['(coeffs[0] - coeffs[1])'], {}), '(coeffs[0] - coeffs[1])\n', (673, 696), True, 'import numpy as np\n'), ((993, 1036), 'numpy.linalg.norm', 'np.linalg.norm', (['(coeffs_nonzero - exact_vals)'], {}), '(coeffs_nonzero - exact_vals)\n', (1007, 1036), True, 'import numpy as np\n'), ((2388, 2439), 'numpy.sum', 'np.sum', (['(coeffs[:, l ** 2:(l + 1) ** 2] ** 2)'], {'axis': '(1)'}), '(coeffs[:, l ** 2:(l + 1) ** 2] ** 2, axis=1)\n', (2394, 2439), True, 'import numpy as np\n'), ((2455, 2491), 'numpy.linalg.norm', 'np.linalg.norm', (['(prod - exact_vals[l])'], {}), '(prod - exact_vals[l])\n', (2469, 2491), True, 'import numpy as np\n'), ((2902, 2920), 'numpy.eye', 'np.eye', (['num_coeffs'], {}), '(num_coeffs)\n', (2908, 2920), True, 'import numpy as np\n'), ((3841, 3887), 'numpy.linspace', 'np.linspace', (['(-1)', '(1)', '(N_theta + 1)'], {'endpoint': '(True)'}), '(-1, 1, N_theta + 1, endpoint=True)\n', (3852, 3887), True, 'import numpy as np\n'), ((4305, 4320), 'numpy.cos', 'np.cos', (['phis_2d'], {}), '(phis_2d)\n', (4311, 4320), True, 'import numpy as np\n'), ((4323, 4340), 'numpy.sin', 'np.sin', (['thetas_2d'], {}), '(thetas_2d)\n', (4329, 4340), True, 'import numpy as np\n'), ((4372, 4387), 'numpy.sin', 'np.sin', (['phis_2d'], {}), '(phis_2d)\n', (4378, 4387), True, 'import numpy as np\n'), ((4390, 4407), 'numpy.sin', 'np.sin', (['thetas_2d'], {}), '(thetas_2d)\n', (4396, 4407), True, 'import numpy as np\n'), ((5912, 5939), 'numpy.linspace', 'np.linspace', (['(-1)', '(1)', 'N_theta'], {}), '(-1, 1, N_theta)\n', (5923, 5939), True, 'import numpy as np\n'), ((6237, 6252), 'numpy.cos', 'np.cos', (['phis_2d'], {}), '(phis_2d)\n', (6243, 6252), True, 'import numpy as np\n'), ((6255, 6272), 'numpy.sin', 'np.sin', (['thetas_2d'], {}), '(thetas_2d)\n', (6261, 6272), True, 'import numpy as np\n'), ((6304, 6319), 'numpy.sin', 'np.sin', (['phis_2d'], {}), '(phis_2d)\n', (6310, 6319), True, 'import numpy as np\n'), ((6322, 6339), 'numpy.sin', 'np.sin', (['thetas_2d'], {}), '(thetas_2d)\n', (6328, 6339), True, 'import numpy as np\n'), ((6457, 6475), 'numpy.sqrt', 'np.sqrt', (['(4 * np.pi)'], {}), '(4 * np.pi)\n', (6464, 6475), True, 'import numpy as np\n'), ((6868, 6881), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (6874, 6881), True, 'import numpy as np\n'), ((1653, 1673), 'numpy.arange', 'np.arange', (['(-l)', '(l + 1)'], {}), '(-l, l + 1)\n', (1662, 1673), True, 'import numpy as np\n'), ((2937, 2963), 'numpy.linalg.norm', 'np.linalg.norm', (['difference'], {}), '(difference)\n', (2951, 2963), True, 'import numpy as np\n'), ((4830, 4875), 'pylode.lib.spherical_harmonics.evaluate_spherical_harmonics', 'evaluate_spherical_harmonics', (['vecs'], {'lmax': 'lmax'}), '(vecs, lmax=lmax)\n', (4858, 4875), False, 'from pylode.lib.spherical_harmonics import evaluate_spherical_harmonics\n'), ((6738, 6749), 'numpy.cos', 'np.cos', (['phi'], {}), '(phi)\n', (6744, 6749), True, 'import numpy as np\n'), ((6752, 6765), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (6758, 6765), True, 'import numpy as np\n'), ((6803, 6814), 'numpy.sin', 'np.sin', (['phi'], {}), '(phi)\n', (6809, 6814), True, 'import numpy as np\n'), ((6817, 6830), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (6823, 6830), True, 'import numpy as np\n'), ((6926, 6945), 'numpy.ones_like', 'np.ones_like', (['theta'], {}), '(theta)\n', (6938, 6945), True, 'import numpy as np\n'), ((7006, 7017), 'numpy.sin', 'np.sin', (['phi'], {}), '(phi)\n', (7012, 7017), True, 'import numpy as np\n'), ((7062, 7075), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (7068, 7075), True, 'import numpy as np\n'), ((7136, 7147), 'numpy.cos', 'np.cos', (['phi'], {}), '(phi)\n', (7142, 7147), True, 'import numpy as np\n'), ((8516, 8558), 'pylode.lib.spherical_harmonics.evaluate_spherical_harmonics', 'evaluate_spherical_harmonics', (['vecs'], {'lmax': '(2)'}), '(vecs, lmax=2)\n', (8544, 8558), False, 'from pylode.lib.spherical_harmonics import evaluate_spherical_harmonics\n'), ((1133, 1155), 'numpy.sum', 'np.sum', (['(coeffs[0] ** 2)'], {}), '(coeffs[0] ** 2)\n', (1139, 1155), True, 'import numpy as np\n'), ((1156, 1179), 'numpy.sum', 'np.sum', (['(exact_vals ** 2)'], {}), '(exact_vals ** 2)\n', (1162, 1179), True, 'import numpy as np\n'), ((2293, 2312), 'numpy.arange', 'np.arange', (['(lmax + 1)'], {}), '(lmax + 1)\n', (2302, 2312), True, 'import numpy as np\n'), ((6990, 7003), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (6996, 7003), True, 'import numpy as np\n'), ((7120, 7133), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (7126, 7133), True, 'import numpy as np\n'), ((939, 958), 'numpy.arange', 'np.arange', (['(lmax + 1)'], {}), '(lmax + 1)\n', (948, 958), True, 'import numpy as np\n'), ((1740, 1778), 'numpy.linalg.norm', 'np.linalg.norm', (['coeffs[:, l ** 2 + im]'], {}), '(coeffs[:, l ** 2 + im])\n', (1754, 1778), True, 'import numpy as np\n'), ((7368, 7381), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (7374, 7381), True, 'import numpy as np\n')]
############################################################################### # normalizer.py: top-level class for normalizer ############################################################################### import warnings import numpy as np from astroNN.config import MAGIC_NUMBER from astroNN.nn.numpy import sigmoid_inv, sigmoid from astroNN.shared.dict_tools import list_to_dict, to_iterable class Normalizer(object): """Top-level class for a normalizer""" def __init__(self, mode=None): """ NAME: __init__ PURPOSE: To define a normalizer HISTORY: 2018-Jan-06 - Written - <NAME> (University of Toronto) """ self.normalization_mode = mode self.featurewise_center = {} self.datasetwise_center = {} self.featurewise_stdalization = {} self.datasetwise_stdalization = {} self.mean_labels = {} self.std_labels = {} self._custom_norm_func = None self._custom_denorm_func = None def mode_checker(self, data): if type(data) is not dict: dict_flag = False data = {"Temp": data} self.mean_labels = {"Temp": self.mean_labels} self.std_labels = {"Temp": self.std_labels} else: dict_flag = True master_data = {} if type(self.normalization_mode) is not dict: self.normalization_mode = list_to_dict(data.keys(), to_iterable(self.normalization_mode)) for name in data.keys(): # normalize data for each named inputs if data[name].ndim == 1: data_array = np.expand_dims(data[name], 1) else: data_array = np.array(data[name]) self.normalization_mode.update({name: str(self.normalization_mode[name])}) # just to prevent unnecessary type issue if data_array.dtype == bool: if self.normalization_mode[name] != '0': # binary classification case warnings.warn("Data type is detected as bool, setting normalization_mode to 0 which is " "doing nothing because no normalization can be done on bool") self.normalization_mode[name] = '0' data_array = data_array.astype(np.float32, copy=False) # need to convert data to float in every case if self.normalization_mode[name] == '0': self.featurewise_center.update({name: False}) self.datasetwise_center.update({name: False}) self.featurewise_stdalization.update({name: False}) self.datasetwise_stdalization.update({name: False}) self.mean_labels.update({name: np.array([0.])}) self.std_labels.update({name: np.array([1.])}) elif self.normalization_mode[name] == '1': self.featurewise_center.update({name: False}) self.datasetwise_center.update({name: True}) self.featurewise_stdalization.update({name: False}) self.datasetwise_stdalization.update({name: True}) elif self.normalization_mode[name] == '2': self.featurewise_center.update({name: True}) self.datasetwise_center.update({name: False}) self.featurewise_stdalization.update({name: True}) self.datasetwise_stdalization.update({name: False}) elif self.normalization_mode[name] == '3': self.featurewise_center.update({name: True}) self.datasetwise_center.update({name: False}) self.featurewise_stdalization.update({name: False}) self.datasetwise_stdalization.update({name: False}) elif self.normalization_mode[name] == '3s': # allow custom function, default to use sigmoid to normalize self.featurewise_center.update({name: False}) self.datasetwise_center.update({name: False}) self.featurewise_stdalization.update({name: False}) self.datasetwise_stdalization.update({name: False}) if self._custom_norm_func is None: self._custom_norm_func = sigmoid if self._custom_denorm_func is None: self._custom_denorm_func = sigmoid_inv self.mean_labels.update({name: np.array([0.])}) self.std_labels.update({name: np.array([1.])}) elif self.normalization_mode[name] == '4': self.featurewise_center.update({name: False}) self.datasetwise_center.update({name: False}) self.featurewise_stdalization.update({name: True}) self.datasetwise_stdalization.update({name: False}) elif self.normalization_mode[name] == '255': # Used to normalize 8bit images self.featurewise_center.update({name: False}) self.datasetwise_center.update({name: False}) self.featurewise_stdalization.update({name: False}) self.datasetwise_stdalization.update({name: False}) self.mean_labels.update({name: np.array([0.])}) self.std_labels.update({name: np.array([255.])}) else: raise ValueError(f"Unknown Mode -> {self.normalization_mode[name]}") master_data.update({name: data_array}) return master_data, dict_flag def normalize(self, data, calc=True): data_array, dict_flag = self.mode_checker(data) for name in data_array.keys(): # normalize data for each named inputs magic_mask = [(data_array[name] == MAGIC_NUMBER)] try: self.mean_labels[name] except KeyError: self.mean_labels.update({name: np.array([0.])}) try: self.std_labels[name] except KeyError: self.std_labels.update({name: np.array([1.])}) if calc is True: # check if normalizing with predefine values or get a new one print( f"""====Message from {self.__class__.__name__}==== \n You selected mode: {self.normalization_mode[name]} \n Featurewise Center: {self.featurewise_center} \n Datawise Center: {self.datasetwise_center} \n Featurewise std Center: {self.featurewise_stdalization} \n Datawise std Center: {self.datasetwise_stdalization} \n ====Message ends====""") if self.featurewise_center[name] is True: self.mean_labels.update({name: np.ma.array(data_array[name], mask=magic_mask).mean(axis=0)}) data_array[name] -= self.mean_labels[name] elif self.datasetwise_center[name] is True: self.mean_labels.update({name: np.ma.array(data_array[name], mask=magic_mask).mean()}) data_array[name] -= self.mean_labels[name] if self.featurewise_stdalization[name] is True: self.std_labels.update({name: np.ma.array(data_array[name], mask=magic_mask).std(axis=0)}) data_array[name] /= self.std_labels[name] elif self.datasetwise_stdalization[name] is True: self.std_labels.update({name: np.ma.array(data_array[name], mask=magic_mask).std()}) data_array[name] /= self.std_labels[name] if self.normalization_mode[name] == '255': data_array[name] -= self.mean_labels[name] data_array[name] /= self.std_labels[name] else: data_array[name] -= self.mean_labels[name] data_array[name] /= self.std_labels[name] if self._custom_norm_func is not None: data_array.update({name: self._custom_norm_func(data_array[name])}) np.place(data_array[name], magic_mask, MAGIC_NUMBER) if not dict_flag: data_array = data_array['Temp'] self.mean_labels = self.mean_labels['Temp'] self.std_labels = self.std_labels['Temp'] return data_array def denormalize(self, data): data_array, dict_flag = self.mode_checker(data) for name in data_array.keys(): # normalize data for each named inputs magic_mask = [data_array[name] == MAGIC_NUMBER] if self._custom_denorm_func is not None: data_array[name] = self._custom_denorm_func(data_array[name]) data_array[name] *= self.std_labels[name] data_array[name] += self.mean_labels[name] np.place(data_array[name], magic_mask, MAGIC_NUMBER) if not dict_flag: data_array = data_array["Temp"] self.mean_labels = self.mean_labels['Temp'] self.std_labels = self.std_labels['Temp'] return data_array
[ "numpy.ma.array", "numpy.place", "numpy.array", "astroNN.shared.dict_tools.to_iterable", "numpy.expand_dims", "warnings.warn" ]
[((7911, 7963), 'numpy.place', 'np.place', (['data_array[name]', 'magic_mask', 'MAGIC_NUMBER'], {}), '(data_array[name], magic_mask, MAGIC_NUMBER)\n', (7919, 7963), True, 'import numpy as np\n'), ((8655, 8707), 'numpy.place', 'np.place', (['data_array[name]', 'magic_mask', 'MAGIC_NUMBER'], {}), '(data_array[name], magic_mask, MAGIC_NUMBER)\n', (8663, 8707), True, 'import numpy as np\n'), ((1478, 1514), 'astroNN.shared.dict_tools.to_iterable', 'to_iterable', (['self.normalization_mode'], {}), '(self.normalization_mode)\n', (1489, 1514), False, 'from astroNN.shared.dict_tools import list_to_dict, to_iterable\n'), ((1655, 1684), 'numpy.expand_dims', 'np.expand_dims', (['data[name]', '(1)'], {}), '(data[name], 1)\n', (1669, 1684), True, 'import numpy as np\n'), ((1732, 1752), 'numpy.array', 'np.array', (['data[name]'], {}), '(data[name])\n', (1740, 1752), True, 'import numpy as np\n'), ((2032, 2189), 'warnings.warn', 'warnings.warn', (['"""Data type is detected as bool, setting normalization_mode to 0 which is doing nothing because no normalization can be done on bool"""'], {}), "(\n 'Data type is detected as bool, setting normalization_mode to 0 which is doing nothing because no normalization can be done on bool'\n )\n", (2045, 2189), False, 'import warnings\n'), ((2748, 2763), 'numpy.array', 'np.array', (['[0.0]'], {}), '([0.0])\n', (2756, 2763), True, 'import numpy as np\n'), ((2811, 2826), 'numpy.array', 'np.array', (['[1.0]'], {}), '([1.0])\n', (2819, 2826), True, 'import numpy as np\n'), ((5864, 5879), 'numpy.array', 'np.array', (['[0.0]'], {}), '([0.0])\n', (5872, 5879), True, 'import numpy as np\n'), ((6011, 6026), 'numpy.array', 'np.array', (['[1.0]'], {}), '([1.0])\n', (6019, 6026), True, 'import numpy as np\n'), ((6617, 6663), 'numpy.ma.array', 'np.ma.array', (['data_array[name]'], {'mask': 'magic_mask'}), '(data_array[name], mask=magic_mask)\n', (6628, 6663), True, 'import numpy as np\n'), ((7087, 7133), 'numpy.ma.array', 'np.ma.array', (['data_array[name]'], {'mask': 'magic_mask'}), '(data_array[name], mask=magic_mask)\n', (7098, 7133), True, 'import numpy as np\n'), ((4409, 4424), 'numpy.array', 'np.array', (['[0.0]'], {}), '([0.0])\n', (4417, 4424), True, 'import numpy as np\n'), ((4472, 4487), 'numpy.array', 'np.array', (['[1.0]'], {}), '([1.0])\n', (4480, 4487), True, 'import numpy as np\n'), ((6853, 6899), 'numpy.ma.array', 'np.ma.array', (['data_array[name]'], {'mask': 'magic_mask'}), '(data_array[name], mask=magic_mask)\n', (6864, 6899), True, 'import numpy as np\n'), ((7326, 7372), 'numpy.ma.array', 'np.ma.array', (['data_array[name]'], {'mask': 'magic_mask'}), '(data_array[name], mask=magic_mask)\n', (7337, 7372), True, 'import numpy as np\n'), ((5215, 5230), 'numpy.array', 'np.array', (['[0.0]'], {}), '([0.0])\n', (5223, 5230), True, 'import numpy as np\n'), ((5278, 5295), 'numpy.array', 'np.array', (['[255.0]'], {}), '([255.0])\n', (5286, 5295), True, 'import numpy as np\n')]
#!/usr/bin/env python2 import rospy from tf import TransformBroadcaster, TransformerROS, transformations as tfs import tf from geometry_msgs.msg import Transform import numpy as np rospy.init_node('handeye_calibration_publisher') print("Publishing handeye matrix!") while rospy.get_time() == 0.0: pass d = np.load("calibration_data.npz") observed_pts = d['arr_0'] measured_pts = d['arr_1'] def get_rigid_transform(A, B): assert len(A) == len(B) N = A.shape[0]; # Total points centroid_A = np.mean(A, axis=0) centroid_B = np.mean(B, axis=0) AA = A - np.tile(centroid_A, (N, 1)) # Centre the points BB = B - np.tile(centroid_B, (N, 1)) H = np.dot(np.transpose(AA), BB) # Dot is matrix multiplication for array U, S, Vt = np.linalg.svd(H) R = np.dot(Vt.T, U.T) if np.linalg.det(R) < 0: # Special reflection case Vt[2,:] *= -1 R = np.dot(Vt.T, U.T) t = np.dot(-R, centroid_A.T) + centroid_B.T return R, t R, t = get_rigid_transform(observed_pts, measured_pts) # q = tf.transformations.quaternion_from_matrix(R) al, be, ga = tf.transformations.euler_from_matrix(R, 'sxyz') q = tf.transformations.quaternion_from_euler(al, be, ga, axes='sxyz') broad = TransformBroadcaster() rate = rospy.Rate(50) while not rospy.is_shutdown(): broad.sendTransform((t[0],t[1],t[2]), (q[0],q[1],q[2],q[3]), rospy.Time.now(), "camera_color_optical_frame", "base_link") # takes ..., child, parent rate.sleep()
[ "tf.TransformBroadcaster", "numpy.mean", "numpy.tile", "numpy.transpose", "rospy.is_shutdown", "rospy.init_node", "rospy.get_time", "tf.transformations.euler_from_matrix", "numpy.linalg.det", "rospy.Time.now", "numpy.dot", "tf.transformations.quaternion_from_euler", "rospy.Rate", "numpy.li...
[((183, 231), 'rospy.init_node', 'rospy.init_node', (['"""handeye_calibration_publisher"""'], {}), "('handeye_calibration_publisher')\n", (198, 231), False, 'import rospy\n'), ((313, 344), 'numpy.load', 'np.load', (['"""calibration_data.npz"""'], {}), "('calibration_data.npz')\n", (320, 344), True, 'import numpy as np\n'), ((1091, 1138), 'tf.transformations.euler_from_matrix', 'tf.transformations.euler_from_matrix', (['R', '"""sxyz"""'], {}), "(R, 'sxyz')\n", (1127, 1138), False, 'import tf\n'), ((1143, 1208), 'tf.transformations.quaternion_from_euler', 'tf.transformations.quaternion_from_euler', (['al', 'be', 'ga'], {'axes': '"""sxyz"""'}), "(al, be, ga, axes='sxyz')\n", (1183, 1208), False, 'import tf\n'), ((1218, 1240), 'tf.TransformBroadcaster', 'TransformBroadcaster', ([], {}), '()\n', (1238, 1240), False, 'from tf import TransformBroadcaster, TransformerROS, transformations as tfs\n'), ((1249, 1263), 'rospy.Rate', 'rospy.Rate', (['(50)'], {}), '(50)\n', (1259, 1263), False, 'import rospy\n'), ((274, 290), 'rospy.get_time', 'rospy.get_time', ([], {}), '()\n', (288, 290), False, 'import rospy\n'), ((508, 526), 'numpy.mean', 'np.mean', (['A'], {'axis': '(0)'}), '(A, axis=0)\n', (515, 526), True, 'import numpy as np\n'), ((544, 562), 'numpy.mean', 'np.mean', (['B'], {'axis': '(0)'}), '(B, axis=0)\n', (551, 562), True, 'import numpy as np\n'), ((758, 774), 'numpy.linalg.svd', 'np.linalg.svd', (['H'], {}), '(H)\n', (771, 774), True, 'import numpy as np\n'), ((783, 800), 'numpy.dot', 'np.dot', (['Vt.T', 'U.T'], {}), '(Vt.T, U.T)\n', (789, 800), True, 'import numpy as np\n'), ((1275, 1294), 'rospy.is_shutdown', 'rospy.is_shutdown', ([], {}), '()\n', (1292, 1294), False, 'import rospy\n'), ((576, 603), 'numpy.tile', 'np.tile', (['centroid_A', '(N, 1)'], {}), '(centroid_A, (N, 1))\n', (583, 603), True, 'import numpy as np\n'), ((637, 664), 'numpy.tile', 'np.tile', (['centroid_B', '(N, 1)'], {}), '(centroid_B, (N, 1))\n', (644, 664), True, 'import numpy as np\n'), ((680, 696), 'numpy.transpose', 'np.transpose', (['AA'], {}), '(AA)\n', (692, 696), True, 'import numpy as np\n'), ((808, 824), 'numpy.linalg.det', 'np.linalg.det', (['R'], {}), '(R)\n', (821, 824), True, 'import numpy as np\n'), ((888, 905), 'numpy.dot', 'np.dot', (['Vt.T', 'U.T'], {}), '(Vt.T, U.T)\n', (894, 905), True, 'import numpy as np\n'), ((914, 938), 'numpy.dot', 'np.dot', (['(-R)', 'centroid_A.T'], {}), '(-R, centroid_A.T)\n', (920, 938), True, 'import numpy as np\n'), ((1361, 1377), 'rospy.Time.now', 'rospy.Time.now', ([], {}), '()\n', (1375, 1377), False, 'import rospy\n')]
from enum import Enum import os from threading import Thread from tkinter import ( Frame, Scrollbar, StringVar, Canvas, Event, VERTICAL, TRUE, FALSE, RIGHT, Y, NW, LEFT, BOTH, Listbox, SINGLE, Widget, END, TclError, ) from typing import Any, Optional, Union import time import numpy as np import psutil from tanager_tcp.tanager_client import TanagerClient AZIMUTH_HOME = 0 INTERVAL = 0.25 BUFFER = 15 PI_BUFFER = 20 # These are related to the region of spectra that are sensitive to polarization artifacts. This is at high phase # angles between 1000 and 1400 nm. MIN_WAVELENGTH_ARTIFACT_FREE = 1000 MAX_WAVELENGTH_ARTIFACT_FREE = 1400 MIN_G_ARTIFACT_FREE = -20 MAX_G_ARTIFACT_FREE = 40 computer = "new" NUMLEN = None # number of digits in the raw data filename. Could change from one version of software to next. if computer == "old": # Number of digits in spectrum number for spec save config NUMLEN = 3 elif computer == "desktop": # Number of digits in spectrum number for spec save config NUMLEN = 5 # Time added to timeouts to account for time to read/write files elif computer == "new": # Number of digits in spectrum number for spec save config NUMLEN = 5 class ConnectionManager: LISTEN_FOR_PI_PORT = 12345 LISTEN_FOR_SPEC_PORT = 54321 REMOTE_PORT = 12345 def __init__(self, spec_ip="192.168.86.50", pi_ip="raspberrypi"): self.spec_offline = True self.pi_offline = True self._spec_ip = spec_ip self._pi_ip = pi_ip self.spec_client = TanagerClient((spec_ip, self.REMOTE_PORT), self.LISTEN_FOR_SPEC_PORT) self.pi_client = TanagerClient((pi_ip, self.REMOTE_PORT), self.LISTEN_FOR_PI_PORT) @property def spec_ip(self): return self._spec_ip @spec_ip.setter def spec_ip(self, new_ip): self._spec_ip = new_ip self.spec_client = TanagerClient((new_ip, self.REMOTE_PORT), self.LISTEN_FOR_SPEC_PORT) @property def pi_ip(self): return self._pi_ip @pi_ip.setter def pi_ip(self, new_ip): self._pi_ip = new_ip self.pi_client = TanagerClient((new_ip, self.REMOTE_PORT), self.LISTEN_FOR_PI_PORT) def send_to_spec(self, message: str, connect_timeout=5) -> bool: if self.spec_offline: self.connect_spec(connect_timeout) if not self.spec_offline: sent = self.spec_client.send(message) if not sent: self.spec_offline = True return sent return False def send_to_pi(self, message: str, connect_timeout=5) -> bool: if self.pi_offline: self.connect_pi(connect_timeout) if not self.pi_offline: sent = self.pi_client.send(message) if not sent: self.pi_offline = True return sent return False def connect_spec(self, timeout: float): self.spec_offline = not self.spec_client.connect(timeout) return not self.spec_offline def connect_pi(self, timeout: float): self.pi_offline = not self.pi_client.connect(timeout) return not self.pi_offline class ConfigInfo: def __init__(self, local_config_loc, global_config_loc, icon_loc, num_len, opsys): self.local_config_loc = local_config_loc self.global_config_loc = global_config_loc self.icon_loc = icon_loc self.opsys = opsys self.num_len = num_len class ControllerType: """This class, which is extended by Controller, is defined so as to avoid circular imports when adding type hints to classes that are imported by Controller and also reference an instance of Controller""" def __init__(self, connection_tracker, config_info): self.connection_tracker = connection_tracker self.config_info = config_info self.tk_format = None self.view_notebook = None self.master = None self.incidence_entries = None self.azimuth_entries = None self.emission_entries = None self.opt = None self.wr = None self.min_science_i = None self.max_science_i = None self.min_science_e = None self.max_science_e = None self.min_science_az = None self.max_science_az = None self.check_viewing_geom_for_manual_operation = None self.spec_config_count = None self.sample_label_entries = None self.current_sample_gui_index = None self.validate_sample_name = None self.log = None self.instrument_config_entry = None self.manual_automatic = None # for plot_manager self.plot = None self.plotter = None self.goniometer_view = None # for process_manager self.remote_directory_worker = None self.process_cmd = None self.plot_manager = None self.script_running = None self.spec_listener = None self.spec_commander = None self.text_only = None self.next_in_queue = None # for console self.execute_cmd = None self.control_frame = None self.view_frame = None # for cli_manager self.set_manual_automatic = None self.fail_script_command = None self.min_motor_i = None self.max_motor_i = None self.min_motor_e = None self.max_motor_e = None self.min_motor_az = None self.max_motor_az = None self.configure_pi = None self.take_spectrum = None self.acquire = None self.add_geometry = None self.set_individual_range = None self.individual_range = None self.light_start_entry = None self.light_end_entry = None self.detector_start_entry = None self.detector_end_entry = None self.azimuth_start_entry = None self.azimuth_end_entry = None self.light_increment_entry = None self.detector_increment_entry = None self.azimuth_increment_entry = None self.incidence_entries = None self.emission_entries = None self.azimuth_entries = None self.sample_frames = None self.available_sample_positions = None self.taken_sample_positions = None self.remove_sample = None self.add_sample = None self.set_taken_sample_positions = None self.unfreeze = None self.spec_save_dir_entry = None self.sample_pos_vars = None self.spec_basename_entry = None self.spec_startnum_entry = None self.set_save_config = None self.configure_instrument = None self.wait_dialog = None self.move_tray = None self.set_emission = None self.set_incidence = None self.set_azimuth = None self.get_movements = None self.console = None # Which spectrometer computer are you using? This should probably be desktop, but could be 'new' for the new lappy or # 'old' for the ancient laptop. computer = "desktop" computer = "new" def limit_len(input_str, max_len): return input_str[:max_len] def validate_int_input(input_int: Any, min_int: int, max_int: int): try: input_int = int(input_int) except (ValueError, TypeError): # TODO: all valueerror exception catching should probably be value, type return False if input_int > max_int: return False if input_int < min_int: return False return True def validate_float_input(input_float: Any, min_float: float, max_float: float): try: input_float = float(input_float) except ValueError: return False if input_float > max_float: return False if input_float < min_float: return False return True def decrypt(encrypted): cmd = encrypted.split("&")[0] params = encrypted.split("&")[1:] i = 0 for param in params: params[i] = param i = i + 1 return cmd, params def rm_reserved_chars(input_str): output = ( input_str.replace("&", "") .replace("+", "") .replace("=", "") .replace("$", "") .replace("^", "") .replace("*", "") .replace("(", "") .replace(",", "") .replace(")", "") .replace("@", "") .replace("!", "") .replace("#", "") .replace("{", "") .replace("}", "") .replace("[", "") .replace("]", "") .replace("|", "") .replace(",", "") .replace("?", "") .replace("~", "") .replace('"', "") .replace("'", "") .replace(";", "") .replace("`", "") ) return output def numbers_only(input_str): output = "" for digit in input_str: if digit in ("1", "2", "3", "4", "5", "6", "7", "8", "9", "0"): output += digit return output class PretendEvent: def __init__(self, widget, width, height): self.widget = widget self.width = width self.height = height class PrivateEntry: def __init__(self, text): self.text = text def get(self): return self.text class SampleFrame: def __init__(self): self.position = "Sample 1" class TkFormat: def __init__(self, config_info=None): # Yay formatting. Might not work for Macs. self.bg = "#333333" self.textcolor = "light gray" self.buttontextcolor = "white" self.bd = 2 self.padx = 3 self.pady = 3 self.border_color = "light gray" self.button_width = 15 self.buttonbackgroundcolor = "#888888" self.highlightbackgroundcolor = "#222222" self.entry_background = "light gray" if config_info is None or config_info.opsys == "Windows": self.listboxhighlightcolor = "darkgray" else: self.listboxhighlightcolor = "white" self.selectbackground = "#555555" self.selectforeground = "white" self.check_bg = "#444444" # http://tkinter.unpythonic.net/wiki/VerticalScrolledFrame class VerticalScrolledFrame(Frame): # Use the 'interior' attribute to place widgets inside the scrollable frame # Construct and pack/place/grid normally # This frame only allows vertical scrolling # pylint: disable = keyword-arg-before-vararg def __init__(self, controller, parent, min_height=600, width=468, *args, **kw): Frame.__init__(self, parent, *args, **kw) self.controller = controller self.min_height = min_height # Miniumum height for interior frame to show all elements. Changes as new samples # or viewing geometries are added. # create a canvas object and a vertical scrollbar for scrolling it self.scrollbar = Scrollbar(self, orient=VERTICAL) self.canvas = canvas = Canvas(self, bd=0, highlightthickness=0, yscrollcommand=self.scrollbar.set) canvas.pack(side=LEFT, fill=BOTH, expand=TRUE) canvas.config(width=width) # canvas.config(height=height) self.scrollbar.config(command=canvas.yview) # reset the view canvas.xview_moveto(0) canvas.yview_moveto(0) # create a frame inside the canvas which will be scrolled with it # initialize height to the bigger of 1) screen height 2) 700 px self.interior = interior = Frame(canvas) interior.pack_propagate( 0 ) # This makes it so we can easily manually set the interior frame's size as needed. See _configure_canvas() # for how it's done. self.interior_id = canvas.create_window(0, 0, window=interior, anchor=NW) self.canvas.bind("<Configure>", self._configure_canvas) self.width = width def _configure_canvas(self, event: Optional[Event] = None): # pylint: disable = unused-argument if self.canvas.winfo_height() > self.min_height: self.interior.config(height=self.canvas.winfo_height()) if self.scrollbar.winfo_ismapped(): self.scrollbar.pack_forget() else: self.interior.config(height=self.min_height) try: self.scrollbar.pack(fill=Y, side=RIGHT, expand=FALSE) except TclError: # Happens on shutdown if plots are open print("TclError configuring scrollbar in VerticalScrolledFrame") return self.canvas.config(scrollregion=self.canvas.bbox("all")) if self.interior.winfo_reqwidth() != self.canvas.winfo_width(): # update the inner frame's width to fill the canvas if self.canvas.winfo_height() < self.min_height: self.canvas.config(width=self.width - 20) else: self.canvas.config(width=self.width) self.canvas.itemconfigure(self.interior_id, width=self.canvas.winfo_width()) def update(self, controller_resize=True): self._configure_canvas(None) if controller_resize: self.controller.resize() class StringVarWithEntry(StringVar): def __init__(self): super().__init__() self.entry = None class ScrollableListbox(Listbox): def __init__(self, frame, bg, entry_background, listboxhighlightcolor, selectmode=SINGLE): self.scroll_frame = Frame(frame, bg=bg) self.scroll_frame.pack(fill=BOTH, expand=True) self.scrollbar = Scrollbar(self.scroll_frame, orient=VERTICAL) self.scrollbar.pack(side=RIGHT, fill=Y, padx=(0, 10)) self.scrollbar.config(command=self.yview) super().__init__( self.scroll_frame, yscrollcommand=self.scrollbar.set, selectmode=selectmode, bg=entry_background, selectbackground=listboxhighlightcolor, height=15, exportselection=0, ) self.pack(side=LEFT, expand=True, fill=BOTH, padx=(10, 0)) self.bind("<Control-c>", self.copy) def destroy(self): self.scrollbar.destroy() super().destroy() def copy(self, event=None): self.clipboard_clear() all_items = self.get(0, END) # tuple with text of all items in Listbox sel_idx = self.curselection() # tuple with indexes of selected items sel_list = [all_items[item] for item in sel_idx] # list with text of all selected items for i, text in enumerate(sel_list): if i < len(sel_list) - 1: self.clipboard_append(text + ",\n") else: self.clipboard_append(text) def exit_func(): print("Exiting TANAGER Feeder.") current_system_pid = os.getpid() tanager_feeder_process = psutil.Process(current_system_pid) tanager_feeder_process.terminate() class MovementUnits(Enum): ANGLE = "angle" STEPS = "steps" POSITION = "position" class CompyTypes(Enum): SPEC_COMPY = "spec compy" PI = "pi" def cos(theta): return np.cos(theta * 3.14159 / 180) def sin(theta): return np.sin(theta * 3.14159 / 180) def arccos(ratio): return np.arccos(ratio) * 180 / 3.14159 def arctan2(y, x): return np.arctan2(y, x) * 180 / 3.14159 def arctan(ratio): return np.arctan(ratio) * 180 / 3.14159 def get_lat1_lat2_delta_long(i: Union[int, float], e: Union[int, float], az: Union[int, float]): if np.sign(i) == np.sign(e): delta_long = az else: delta_long = 180 - az lat1 = 90 - np.abs(i) lat2 = 90 - np.abs(e) return lat1, lat2, delta_long def get_phase_angle(i: int, e: int, az: Optional[int]): if az is None: az = 0 lat1, lat2, delta_long = get_lat1_lat2_delta_long(i, e, az) dist = np.abs(arccos(sin(lat1) * sin(lat2) + cos(lat1) * cos(lat2) * cos(delta_long))) return dist def get_initial_bearing(e: int): lat2 = 90 - np.abs(e) bearing = arctan2(cos(lat2), sin(lat2)) return bearing class NotScrolledFrame(Frame): def __init__(self, parent, *args, **kw): Frame.__init__(self, parent, *args, **kw) self.interior = self self.scrollbar = NotScrollbar() class NotScrollbar: def __init__(self): pass def pack_forget(self): pass def set_text(widget: Widget, text: str): state = widget.cget("state") widget.configure(state="normal") widget.delete(0, "end") widget.insert(0, text) widget.configure(state=state) def lift_widget(widget: Widget): time.sleep(5) print("LIFTING WIDGET IN UTILS") widget.focus_set() widget.lift() def thread_lift_widget(widget: Widget): time.sleep(3) print("LIFTING") thread = Thread(target=lift_widget, args=(widget,)) thread.start() def get_i_e_az(geom): try: i = float(geom[0]) except (ValueError, TypeError): i = None try: e = float(geom[1]) except (ValueError, TypeError): e = None try: az = float(geom[2]) except (ValueError, TypeError): az = None return i, e, az
[ "numpy.abs", "tkinter.Frame.__init__", "numpy.arccos", "tanager_tcp.tanager_client.TanagerClient", "psutil.Process", "time.sleep", "tkinter.Canvas", "tkinter.Scrollbar", "numpy.arctan2", "numpy.cos", "os.getpid", "numpy.sign", "numpy.sin", "threading.Thread", "tkinter.Frame", "numpy.ar...
[((14757, 14768), 'os.getpid', 'os.getpid', ([], {}), '()\n', (14766, 14768), False, 'import os\n'), ((14798, 14832), 'psutil.Process', 'psutil.Process', (['current_system_pid'], {}), '(current_system_pid)\n', (14812, 14832), False, 'import psutil\n'), ((15066, 15095), 'numpy.cos', 'np.cos', (['(theta * 3.14159 / 180)'], {}), '(theta * 3.14159 / 180)\n', (15072, 15095), True, 'import numpy as np\n'), ((15125, 15154), 'numpy.sin', 'np.sin', (['(theta * 3.14159 / 180)'], {}), '(theta * 3.14159 / 180)\n', (15131, 15154), True, 'import numpy as np\n'), ((16557, 16570), 'time.sleep', 'time.sleep', (['(5)'], {}), '(5)\n', (16567, 16570), False, 'import time\n'), ((16695, 16708), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)\n', (16705, 16708), False, 'import time\n'), ((16743, 16785), 'threading.Thread', 'Thread', ([], {'target': 'lift_widget', 'args': '(widget,)'}), '(target=lift_widget, args=(widget,))\n', (16749, 16785), False, 'from threading import Thread\n'), ((1607, 1676), 'tanager_tcp.tanager_client.TanagerClient', 'TanagerClient', (['(spec_ip, self.REMOTE_PORT)', 'self.LISTEN_FOR_SPEC_PORT'], {}), '((spec_ip, self.REMOTE_PORT), self.LISTEN_FOR_SPEC_PORT)\n', (1620, 1676), False, 'from tanager_tcp.tanager_client import TanagerClient\n'), ((1702, 1767), 'tanager_tcp.tanager_client.TanagerClient', 'TanagerClient', (['(pi_ip, self.REMOTE_PORT)', 'self.LISTEN_FOR_PI_PORT'], {}), '((pi_ip, self.REMOTE_PORT), self.LISTEN_FOR_PI_PORT)\n', (1715, 1767), False, 'from tanager_tcp.tanager_client import TanagerClient\n'), ((1945, 2013), 'tanager_tcp.tanager_client.TanagerClient', 'TanagerClient', (['(new_ip, self.REMOTE_PORT)', 'self.LISTEN_FOR_SPEC_PORT'], {}), '((new_ip, self.REMOTE_PORT), self.LISTEN_FOR_SPEC_PORT)\n', (1958, 2013), False, 'from tanager_tcp.tanager_client import TanagerClient\n'), ((2179, 2245), 'tanager_tcp.tanager_client.TanagerClient', 'TanagerClient', (['(new_ip, self.REMOTE_PORT)', 'self.LISTEN_FOR_PI_PORT'], {}), '((new_ip, self.REMOTE_PORT), self.LISTEN_FOR_PI_PORT)\n', (2192, 2245), False, 'from tanager_tcp.tanager_client import TanagerClient\n'), ((10515, 10556), 'tkinter.Frame.__init__', 'Frame.__init__', (['self', 'parent', '*args'], {}), '(self, parent, *args, **kw)\n', (10529, 10556), False, 'from tkinter import Frame, Scrollbar, StringVar, Canvas, Event, VERTICAL, TRUE, FALSE, RIGHT, Y, NW, LEFT, BOTH, Listbox, SINGLE, Widget, END, TclError\n'), ((10858, 10890), 'tkinter.Scrollbar', 'Scrollbar', (['self'], {'orient': 'VERTICAL'}), '(self, orient=VERTICAL)\n', (10867, 10890), False, 'from tkinter import Frame, Scrollbar, StringVar, Canvas, Event, VERTICAL, TRUE, FALSE, RIGHT, Y, NW, LEFT, BOTH, Listbox, SINGLE, Widget, END, TclError\n'), ((10923, 10998), 'tkinter.Canvas', 'Canvas', (['self'], {'bd': '(0)', 'highlightthickness': '(0)', 'yscrollcommand': 'self.scrollbar.set'}), '(self, bd=0, highlightthickness=0, yscrollcommand=self.scrollbar.set)\n', (10929, 10998), False, 'from tkinter import Frame, Scrollbar, StringVar, Canvas, Event, VERTICAL, TRUE, FALSE, RIGHT, Y, NW, LEFT, BOTH, Listbox, SINGLE, Widget, END, TclError\n'), ((11451, 11464), 'tkinter.Frame', 'Frame', (['canvas'], {}), '(canvas)\n', (11456, 11464), False, 'from tkinter import Frame, Scrollbar, StringVar, Canvas, Event, VERTICAL, TRUE, FALSE, RIGHT, Y, NW, LEFT, BOTH, Listbox, SINGLE, Widget, END, TclError\n'), ((13418, 13437), 'tkinter.Frame', 'Frame', (['frame'], {'bg': 'bg'}), '(frame, bg=bg)\n', (13423, 13437), False, 'from tkinter import Frame, Scrollbar, StringVar, Canvas, Event, VERTICAL, TRUE, FALSE, RIGHT, Y, NW, LEFT, BOTH, Listbox, SINGLE, Widget, END, TclError\n'), ((13518, 13563), 'tkinter.Scrollbar', 'Scrollbar', (['self.scroll_frame'], {'orient': 'VERTICAL'}), '(self.scroll_frame, orient=VERTICAL)\n', (13527, 13563), False, 'from tkinter import Frame, Scrollbar, StringVar, Canvas, Event, VERTICAL, TRUE, FALSE, RIGHT, Y, NW, LEFT, BOTH, Listbox, SINGLE, Widget, END, TclError\n'), ((15456, 15466), 'numpy.sign', 'np.sign', (['i'], {}), '(i)\n', (15463, 15466), True, 'import numpy as np\n'), ((15470, 15480), 'numpy.sign', 'np.sign', (['e'], {}), '(e)\n', (15477, 15480), True, 'import numpy as np\n'), ((15562, 15571), 'numpy.abs', 'np.abs', (['i'], {}), '(i)\n', (15568, 15571), True, 'import numpy as np\n'), ((15588, 15597), 'numpy.abs', 'np.abs', (['e'], {}), '(e)\n', (15594, 15597), True, 'import numpy as np\n'), ((15946, 15955), 'numpy.abs', 'np.abs', (['e'], {}), '(e)\n', (15952, 15955), True, 'import numpy as np\n'), ((16105, 16146), 'tkinter.Frame.__init__', 'Frame.__init__', (['self', 'parent', '*args'], {}), '(self, parent, *args, **kw)\n', (16119, 16146), False, 'from tkinter import Frame, Scrollbar, StringVar, Canvas, Event, VERTICAL, TRUE, FALSE, RIGHT, Y, NW, LEFT, BOTH, Listbox, SINGLE, Widget, END, TclError\n'), ((15187, 15203), 'numpy.arccos', 'np.arccos', (['ratio'], {}), '(ratio)\n', (15196, 15203), True, 'import numpy as np\n'), ((15252, 15268), 'numpy.arctan2', 'np.arctan2', (['y', 'x'], {}), '(y, x)\n', (15262, 15268), True, 'import numpy as np\n'), ((15317, 15333), 'numpy.arctan', 'np.arctan', (['ratio'], {}), '(ratio)\n', (15326, 15333), True, 'import numpy as np\n')]
import cv2 import math import numpy as np import h5py import sys import uuid from joblib import Parallel, delayed from bisect import bisect_left from datetime import datetime, timedelta from sklearn.model_selection import train_test_split from cloudseg.utils.files import get_contained_dirs, get_contained_files from cloudseg.datasets.optimization import optimize_dataset from cloudseg.datasets.preprocessing import ( process_irccam_img, process_vis_img, sun_correction, process_irccam_label, ) from cloudseg.datasets.masking import apply_full_mask from cloudseg.datasets.filtering import ( filter_sun, filter_sparse, filter_manual, ) from cloudseg.datasets.labeling import create_label_rb_threshold, create_label_adaptive from cloudseg.utils.constants import * def create_dataset( dataset_name, test=False, sizes=(0.6, 0.2, 0.2), changelog="", use_manual_filter=True, raw_data_path=RAW_DATA_PATH, output_path=DATASET_PATH, ): """ Create an H5 based dataset from the raw IRCCAM and RGB image data. Read in the raw IRRCCAM and RGB image data and create a training dataset with an H5 file for each day. For each timestamp, the raw data is preprocessed, aligned, and the training labels are created. The data is split into train, val, and test splits and the split information is stored in text files in the dataset directory. The split is done per day, to minimize leakage between training and test sets. Parameters ---------- dataset_name : str Name of the dataset to output test : bool Create a test dataset in a test folder (used for testing the function) sizes : tuple[float, float, float] Fraction of days to allocate to the training, validation, and test sets, resp. use_manual_filter: Whether to filter out timestamps from the final dataset, based on the manually created CSV file stored at `cloudseg/datasets/resources/filter_manual.csv` raw_data_path: Path to directory where the raw IRCCAM and RGB data is stored output_path: Where to store the created dataset Returns ------- None """ assert sum(sizes) == 1, "Split sizes to not sum up to 1" print("Creating dataset") days = get_days(raw_data_path) if test: days = days[:6] dataset_name = dataset_name + "_" + str(uuid.uuid4()) path = os.path.join(output_path, "../test/", dataset_name) else: path = os.path.join(output_path, dataset_name) # Create data/previews directories if it doesn't exist yet previews_path = os.path.join(path, "previews") if not os.path.exists(previews_path): os.makedirs(previews_path) if not test: with open(os.path.join(path, "changes.txt"), "w") as f: f.write(changelog) success = Parallel(n_jobs=6)( delayed(process_day)(path, d, i, len(days), use_manual_filter, raw_data_path=raw_data_path) for i, d in enumerate(days) ) print("Successfully added {}/{} days to the dataset".format(sum(success), len(days))) # Save splits days_ok = [x for x, y in zip(days, success) if y] train, test, val = sizes days_train, days_testval = train_test_split(days_ok, test_size=test + val, train_size=train) days_val, days_test = train_test_split(days_testval, test_size=test / (test + val), train_size=val / (test + val)) np.savetxt(os.path.join(path, "train.txt"), days_train, fmt="%s") np.savetxt(os.path.join(path, "test.txt"), days_test, fmt="%s") np.savetxt(os.path.join(path, "val.txt"), days_val, fmt="%s") def process_day(data_path, day, i, n, use_manual_filter, raw_data_path=RAW_DATA_PATH): print("Processing day {} - {}/{}".format(day, i + 1, n)) # Create output directory data_filename = os.path.join(data_path, "{}.h5".format(day)) if os.path.exists(data_filename): return True # Read raw data for day and apply processing with h5py.File(os.path.join(raw_data_path, "irccam", "irccam_{}_rad.mat".format(day)), "r") as fr: irc_raw = fr["BT"] clear_sky_raw = fr["TB"] ir_labels_raw = fr["CLOUDS"] irc_timestamps = get_irc_timestamps(day, fr) vis_timestamps = get_vis_timestamps(day, raw_data_path) matching_timestamps = match_timestamps(irc_timestamps, vis_timestamps) filtered_timestamps = filter_sun(matching_timestamps, day) filtered_timestamps = filter_sparse(filtered_timestamps) label_selected = 3 if use_manual_filter: filtered_timestamps, label_selected = filter_manual(day, filtered_timestamps) n = len(filtered_timestamps) if n == 0: return False timestamps = [] vis_images = np.empty((n, 420, 420, 3), dtype="float32") irc_images = np.empty((n, 420, 420), dtype="float32") clear_skies = np.empty((n, 420, 420), dtype="float32") labels_out = [np.empty((n, 420, 420), dtype="byte") for _ in range(4)] ir_labels = np.empty((n, 420, 420), dtype="byte") sun_masks = np.empty((n, 420, 420), dtype="bool") # We'll output a preview video preview_filename = os.path.join(data_path, "previews", "{}_preview.mp4".format(day)) fourcc = cv2.VideoWriter_fourcc(*"mp4v") # Be sure to use lower case video_out = cv2.VideoWriter(preview_filename, fourcc, 3, (420 * 4, 420 * 2)) print("Processing images") for i, (vis_ts, (irc_ts, irc_idx)) in enumerate(filtered_timestamps): # lets just keep one timestamp, time sync will have to be done in this file anyway timestamps.append(irc_ts.strftime(TIMESTAMP_FORMAT)) irc_img = irc_raw[irc_idx, :, :] irc_img = process_irccam_img(irc_img) vis_img = get_vis_img(vis_ts, raw_data_path) vis_img = process_vis_img(vis_img) clear_sky = clear_sky_raw[irc_idx, :, :] clear_sky = process_irccam_img(clear_sky) ir_label = ir_labels_raw[irc_idx, :, :] ir_label = process_irccam_label(ir_label) # Create labels labels = [ create_label_rb_threshold(vis_img, cloud_ref=2.35), create_label_rb_threshold(vis_img, cloud_ref=2.7), create_label_rb_threshold(vis_img, cloud_ref=3), create_label_adaptive(vis_img), ] sun_mask = sun_correction(vis_img, irc_img) label_images = [create_label_image(i) for i in labels] ir_label_image = create_label_image(ir_label) # apply common mask to vis, cannot do it before to not mess with adaptive labeling apply_full_mask(vis_img) comparison_image = concat_images( { "irccam": irc_img, "rgb": vis_img, "ir_label": ir_label_image, "tresh 2.35": label_images[0], "tresh 2.7": label_images[1], "tresh 3": label_images[2], "adaptive": label_images[3], "selected " + str(label_selected): label_images[label_selected], } ) cv2.putText( comparison_image, irc_ts.strftime(PRETTY_FORMAT), (10, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2, ) video_out.write(comparison_image) # Write out frame to video vis_images[i, :, :, :] = vis_img irc_images[i, :, :] = irc_img clear_skies[i, :, :] = clear_sky ir_labels[i, :, :] = ir_label sun_masks[i, :, :] = sun_mask for j, label in enumerate(labels): labels_out[j][i, :, :] = label video_out.release() print("Saving data") with h5py.File(data_filename, "w") as fw: fw.create_dataset("timestamp", data=timestamps) fw.create_dataset("irc", data=irc_images, chunks=(1, 420, 420), compression="lzf") fw.create_dataset("vis", data=vis_images, chunks=(1, 420, 420, 3), compression="lzf") fw.create_dataset("clear_sky", data=clear_skies, chunks=(1, 420, 420), compression="lzf") fw.create_dataset("ir_label", data=ir_labels, chunks=(1, 420, 420), compression="lzf") fw.create_dataset( "selected_label", data=labels_out[label_selected], chunks=(1, 420, 420), compression="lzf" ) fw.create_dataset("sun_mask", data=sun_masks, chunks=(1, 420, 420), compression="lzf") for j, data in enumerate(labels_out): fw.create_dataset("labels" + str(j), data=data, chunks=(1, 420, 420), compression="lzf") return True def save_arrays_to_dataset(data, path, timestamp): filename = os.path.join(path, "{}.npz".format(timestamp[0].strftime(TIMESTAMP_FORMAT_MINUTE))) np.savez(filename, **data) def save_image_to_dataset(img, path, timestamp, extension): filename = os.path.join(path, "{}_{}.jpg".format(timestamp.strftime(TIMESTAMP_FORMAT_MINUTE), extension)) saved = cv2.imwrite(filename, img) if not saved: raise Exception("Failed to save image {}".format(filename)) def concat_images(images): processed = [] for name, img in images.items(): i = np.nan_to_num(img, copy=True, nan=255) if i.ndim == 2: i = cv2.cvtColor(i, cv2.COLOR_GRAY2RGB) i = i.astype(np.uint8) cv2.putText(i, name, (10, 410), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (50, 0, 50), 2) processed.append(i) n = len(processed) // 2 a, b = processed[:n], processed[n:] return cv2.vconcat((cv2.hconcat(a), cv2.hconcat(b))) def create_label_image(labels): img = np.zeros((labels.shape[0], labels.shape[1], 3)) img[:, :, 0] = labels * 255 img[np.where(labels == -1)] = float("nan") return img def match_timestamps(ir_ts, vis_ts): """ intersection is not enough since the timestamps do not match exactly """ valid = [] for t_vis in vis_ts: # find closes timestamp idx = take_closest(ir_ts, t_vis) if abs(t_vis - ir_ts[idx]) < timedelta(seconds=25): valid.append((t_vis, (ir_ts[idx], idx))) return valid def get_days(raw_data_path): vis_days = get_contained_dirs(os.path.join(raw_data_path, "rgb")) ir_days = [f[7:-8] for f in get_contained_files(os.path.join(raw_data_path, "irccam"))] valid = list(sorted(set(vis_days).intersection(ir_days))) return valid def get_vis_timestamps(day, raw_data_path): filenames = [ file for file in get_contained_files(os.path.join(raw_data_path, "rgb", day)) if file.endswith("_0.jpg") ] timestamps = [TIMEZONE.localize(datetime.strptime(filename[:-6], TIMESTAMP_FORMAT)) for filename in filenames] timestamps.sort() return timestamps def get_irc_timestamps(day, irc_file): return [convert_timestamp(day, x) for x in irc_file["TM"][0, :]] def convert_timestamp(day, timestamp): """ Converts irccam timestamps in double format (e.g. 737653.55976907) to timestamps capped to the nearest second (e.g. 20190816132643) """ seconds = round(24 * 60 * 60 * (timestamp - math.floor(timestamp))) seconds_delta = timedelta(0, seconds) day_timestamp = datetime.strptime(day, "%Y%m%d") return TIMEZONE.localize(day_timestamp + seconds_delta) def get_vis_img(timestamp, raw_data_path): file_path = os.path.join( raw_data_path, "rgb", timestamp.strftime(TIMESTAMP_FORMAT_DAY), "{}_0.jpg".format(timestamp.strftime(TIMESTAMP_FORMAT)), ) img_vis = cv2.imread(file_path) if img_vis is None: raise FileNotFoundError("Image {} not found".format(file_path)) return img_vis # https://stackoverflow.com/questions/12141150/from-list-of-integers-get-number-closest-to-a-given-value def take_closest(array, number): pos = bisect_left(array, number) if pos == 0: return 0 if pos == len(array): return len(array) - 1 before = array[pos - 1] after = array[pos] if after - number < number - before: return pos else: return pos - 1 if __name__ == "__main__": if len(sys.argv) > 1 and sys.argv[1] == "test": create_dataset(dataset_name="test", test=True) else: name = "main_" optimize = False print("Dataset classifier: ", end="") classifier = input().strip() print("Dataset changes: ", end="") changes = input().strip() print("Would you also like to generate an training optimized version (y)/n: ", end="") if input().strip() != "n": optimize = True create_dataset(dataset_name=name + classifier, changelog=changes) if optimize: optimize_dataset(name + classifier, "optimized_" + classifier)
[ "cloudseg.datasets.filtering.filter_manual", "math.floor", "cloudseg.datasets.preprocessing.process_irccam_label", "cloudseg.datasets.filtering.filter_sun", "datetime.timedelta", "cloudseg.datasets.optimization.optimize_dataset", "numpy.savez", "numpy.where", "cv2.VideoWriter", "numpy.empty", "c...
[((3261, 3326), 'sklearn.model_selection.train_test_split', 'train_test_split', (['days_ok'], {'test_size': '(test + val)', 'train_size': 'train'}), '(days_ok, test_size=test + val, train_size=train)\n', (3277, 3326), False, 'from sklearn.model_selection import train_test_split\n'), ((3353, 3450), 'sklearn.model_selection.train_test_split', 'train_test_split', (['days_testval'], {'test_size': '(test / (test + val))', 'train_size': '(val / (test + val))'}), '(days_testval, test_size=test / (test + val), train_size=\n val / (test + val))\n', (3369, 3450), False, 'from sklearn.model_selection import train_test_split\n'), ((9083, 9109), 'numpy.savez', 'np.savez', (['filename'], {}), '(filename, **data)\n', (9091, 9109), True, 'import numpy as np\n'), ((9294, 9320), 'cv2.imwrite', 'cv2.imwrite', (['filename', 'img'], {}), '(filename, img)\n', (9305, 9320), False, 'import cv2\n'), ((9935, 9982), 'numpy.zeros', 'np.zeros', (['(labels.shape[0], labels.shape[1], 3)'], {}), '((labels.shape[0], labels.shape[1], 3))\n', (9943, 9982), True, 'import numpy as np\n'), ((11463, 11484), 'datetime.timedelta', 'timedelta', (['(0)', 'seconds'], {}), '(0, seconds)\n', (11472, 11484), False, 'from datetime import datetime, timedelta\n'), ((11505, 11537), 'datetime.datetime.strptime', 'datetime.strptime', (['day', '"""%Y%m%d"""'], {}), "(day, '%Y%m%d')\n", (11522, 11537), False, 'from datetime import datetime, timedelta\n'), ((11846, 11867), 'cv2.imread', 'cv2.imread', (['file_path'], {}), '(file_path)\n', (11856, 11867), False, 'import cv2\n'), ((12133, 12159), 'bisect.bisect_left', 'bisect_left', (['array', 'number'], {}), '(array, number)\n', (12144, 12159), False, 'from bisect import bisect_left\n'), ((2877, 2895), 'joblib.Parallel', 'Parallel', ([], {'n_jobs': '(6)'}), '(n_jobs=6)\n', (2885, 2895), False, 'from joblib import Parallel, delayed\n'), ((4431, 4467), 'cloudseg.datasets.filtering.filter_sun', 'filter_sun', (['matching_timestamps', 'day'], {}), '(matching_timestamps, day)\n', (4441, 4467), False, 'from cloudseg.datasets.filtering import filter_sun, filter_sparse, filter_manual\n'), ((4498, 4532), 'cloudseg.datasets.filtering.filter_sparse', 'filter_sparse', (['filtered_timestamps'], {}), '(filtered_timestamps)\n', (4511, 4532), False, 'from cloudseg.datasets.filtering import filter_sun, filter_sparse, filter_manual\n'), ((4809, 4852), 'numpy.empty', 'np.empty', (['(n, 420, 420, 3)'], {'dtype': '"""float32"""'}), "((n, 420, 420, 3), dtype='float32')\n", (4817, 4852), True, 'import numpy as np\n'), ((4874, 4914), 'numpy.empty', 'np.empty', (['(n, 420, 420)'], {'dtype': '"""float32"""'}), "((n, 420, 420), dtype='float32')\n", (4882, 4914), True, 'import numpy as np\n'), ((4937, 4977), 'numpy.empty', 'np.empty', (['(n, 420, 420)'], {'dtype': '"""float32"""'}), "((n, 420, 420), dtype='float32')\n", (4945, 4977), True, 'import numpy as np\n'), ((5077, 5114), 'numpy.empty', 'np.empty', (['(n, 420, 420)'], {'dtype': '"""byte"""'}), "((n, 420, 420), dtype='byte')\n", (5085, 5114), True, 'import numpy as np\n'), ((5135, 5172), 'numpy.empty', 'np.empty', (['(n, 420, 420)'], {'dtype': '"""bool"""'}), "((n, 420, 420), dtype='bool')\n", (5143, 5172), True, 'import numpy as np\n'), ((5323, 5354), 'cv2.VideoWriter_fourcc', 'cv2.VideoWriter_fourcc', (["*'mp4v'"], {}), "(*'mp4v')\n", (5345, 5354), False, 'import cv2\n'), ((5404, 5468), 'cv2.VideoWriter', 'cv2.VideoWriter', (['preview_filename', 'fourcc', '(3)', '(420 * 4, 420 * 2)'], {}), '(preview_filename, fourcc, 3, (420 * 4, 420 * 2))\n', (5419, 5468), False, 'import cv2\n'), ((9504, 9542), 'numpy.nan_to_num', 'np.nan_to_num', (['img'], {'copy': '(True)', 'nan': '(255)'}), '(img, copy=True, nan=255)\n', (9517, 9542), True, 'import numpy as np\n'), ((9658, 9736), 'cv2.putText', 'cv2.putText', (['i', 'name', '(10, 410)', 'cv2.FONT_HERSHEY_SIMPLEX', '(0.7)', '(50, 0, 50)', '(2)'], {}), '(i, name, (10, 410), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (50, 0, 50), 2)\n', (9669, 9736), False, 'import cv2\n'), ((10023, 10045), 'numpy.where', 'np.where', (['(labels == -1)'], {}), '(labels == -1)\n', (10031, 10045), True, 'import numpy as np\n'), ((4641, 4680), 'cloudseg.datasets.filtering.filter_manual', 'filter_manual', (['day', 'filtered_timestamps'], {}), '(day, filtered_timestamps)\n', (4654, 4680), False, 'from cloudseg.datasets.filtering import filter_sun, filter_sparse, filter_manual\n'), ((5000, 5037), 'numpy.empty', 'np.empty', (['(n, 420, 420)'], {'dtype': '"""byte"""'}), "((n, 420, 420), dtype='byte')\n", (5008, 5037), True, 'import numpy as np\n'), ((5811, 5838), 'cloudseg.datasets.preprocessing.process_irccam_img', 'process_irccam_img', (['irc_img'], {}), '(irc_img)\n', (5829, 5838), False, 'from cloudseg.datasets.preprocessing import process_irccam_img, process_vis_img, sun_correction, process_irccam_label\n'), ((5919, 5943), 'cloudseg.datasets.preprocessing.process_vis_img', 'process_vis_img', (['vis_img'], {}), '(vis_img)\n', (5934, 5943), False, 'from cloudseg.datasets.preprocessing import process_irccam_img, process_vis_img, sun_correction, process_irccam_label\n'), ((6022, 6051), 'cloudseg.datasets.preprocessing.process_irccam_img', 'process_irccam_img', (['clear_sky'], {}), '(clear_sky)\n', (6040, 6051), False, 'from cloudseg.datasets.preprocessing import process_irccam_img, process_vis_img, sun_correction, process_irccam_label\n'), ((6128, 6158), 'cloudseg.datasets.preprocessing.process_irccam_label', 'process_irccam_label', (['ir_label'], {}), '(ir_label)\n', (6148, 6158), False, 'from cloudseg.datasets.preprocessing import process_irccam_img, process_vis_img, sun_correction, process_irccam_label\n'), ((6497, 6529), 'cloudseg.datasets.preprocessing.sun_correction', 'sun_correction', (['vis_img', 'irc_img'], {}), '(vis_img, irc_img)\n', (6511, 6529), False, 'from cloudseg.datasets.preprocessing import process_irccam_img, process_vis_img, sun_correction, process_irccam_label\n'), ((6764, 6788), 'cloudseg.datasets.masking.apply_full_mask', 'apply_full_mask', (['vis_img'], {}), '(vis_img)\n', (6779, 6788), False, 'from cloudseg.datasets.masking import apply_full_mask\n'), ((8009, 8038), 'h5py.File', 'h5py.File', (['data_filename', '"""w"""'], {}), "(data_filename, 'w')\n", (8018, 8038), False, 'import h5py\n'), ((9583, 9618), 'cv2.cvtColor', 'cv2.cvtColor', (['i', 'cv2.COLOR_GRAY2RGB'], {}), '(i, cv2.COLOR_GRAY2RGB)\n', (9595, 9618), False, 'import cv2\n'), ((9858, 9872), 'cv2.hconcat', 'cv2.hconcat', (['a'], {}), '(a)\n', (9869, 9872), False, 'import cv2\n'), ((9874, 9888), 'cv2.hconcat', 'cv2.hconcat', (['b'], {}), '(b)\n', (9885, 9888), False, 'import cv2\n'), ((10355, 10376), 'datetime.timedelta', 'timedelta', ([], {'seconds': '(25)'}), '(seconds=25)\n', (10364, 10376), False, 'from datetime import datetime, timedelta\n'), ((10941, 10991), 'datetime.datetime.strptime', 'datetime.strptime', (['filename[:-6]', 'TIMESTAMP_FORMAT'], {}), '(filename[:-6], TIMESTAMP_FORMAT)\n', (10958, 10991), False, 'from datetime import datetime, timedelta\n'), ((13016, 13078), 'cloudseg.datasets.optimization.optimize_dataset', 'optimize_dataset', (['(name + classifier)', "('optimized_' + classifier)"], {}), "(name + classifier, 'optimized_' + classifier)\n", (13032, 13078), False, 'from cloudseg.datasets.optimization import optimize_dataset\n'), ((2411, 2423), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (2421, 2423), False, 'import uuid\n'), ((2905, 2925), 'joblib.delayed', 'delayed', (['process_day'], {}), '(process_day)\n', (2912, 2925), False, 'from joblib import Parallel, delayed\n'), ((6227, 6277), 'cloudseg.datasets.labeling.create_label_rb_threshold', 'create_label_rb_threshold', (['vis_img'], {'cloud_ref': '(2.35)'}), '(vis_img, cloud_ref=2.35)\n', (6252, 6277), False, 'from cloudseg.datasets.labeling import create_label_rb_threshold, create_label_adaptive\n'), ((6295, 6344), 'cloudseg.datasets.labeling.create_label_rb_threshold', 'create_label_rb_threshold', (['vis_img'], {'cloud_ref': '(2.7)'}), '(vis_img, cloud_ref=2.7)\n', (6320, 6344), False, 'from cloudseg.datasets.labeling import create_label_rb_threshold, create_label_adaptive\n'), ((6362, 6409), 'cloudseg.datasets.labeling.create_label_rb_threshold', 'create_label_rb_threshold', (['vis_img'], {'cloud_ref': '(3)'}), '(vis_img, cloud_ref=3)\n', (6387, 6409), False, 'from cloudseg.datasets.labeling import create_label_rb_threshold, create_label_adaptive\n'), ((6427, 6457), 'cloudseg.datasets.labeling.create_label_adaptive', 'create_label_adaptive', (['vis_img'], {}), '(vis_img)\n', (6448, 6457), False, 'from cloudseg.datasets.labeling import create_label_rb_threshold, create_label_adaptive\n'), ((11419, 11440), 'math.floor', 'math.floor', (['timestamp'], {}), '(timestamp)\n', (11429, 11440), False, 'import math\n')]
# from sklearn.metrics import accuracy_score # from sklearn.metrics import f1_score # from sklearn.metrics import precision_score # from sklearn.metrics import recall_score from .DataPreparation import DataPreparation from sklearn.metrics import plot_confusion_matrix from matplotlib import pyplot as plt import numpy as np from sklearn import svm from sklearn.neighbors import KNeighborsClassifier from sklearn.naive_bayes import GaussianNB from sklearn.tree import DecisionTreeClassifier from sklearn.neural_network import MLPClassifier from sklearn.metrics import cohen_kappa_score from sklearn.metrics import classification_report from sklearn.metrics import accuracy_score import os from sklearn.preprocessing import normalize # from time import process_time import time import pandas as pd import warnings warnings.filterwarnings('ignore') classifiers = {'knn': KNeighborsClassifier(), 'svm': svm.SVC(), 'naive_bayers': GaussianNB(), 'decision_tree': DecisionTreeClassifier(), 'neural_network': MLPClassifier()} # classify_metrics = {"accuracy": accuracy_score, # "f1": f1_score, # "precision": precision_score, # "recall": recall_score} class Raport(): """Class responsible for creating summary of the classification results for the original and reduced data It uses DataPreparation instance and arrays of reduced data and labels for reduced data - _Reduction attributes. Attributes: original (DataPreparation): instance representing original data reduced_data (np.ndarray): array with reduced data of training dataset reduced_label (np.ndarray): array with labels for the reduced data of training dataset """ def __init__(self, original :DataPreparation, reduced_data: np.ndarray, reduced_label: np.ndarray): """Constructor of Raport Args: original (DataPreparation): instance representing original data reduced_data (np.ndarray): array with reduced data of training dataset reduced_label (np.ndarray): array with labels for the reduced data of training dataset Raises: Exception: when reduced_data or reduced_label is empty """ self.original = original self.reduced_data = reduced_data self.reduced_label = reduced_label if 0 in [len(reduced_data), len(reduced_label)]: raise Exception("Cannot create raport for empty reduced data") def draw_plots(self, colx: str, coly: str, path = None, show:bool = True, save:bool = False): """Function creating scatter plots with reduced and original data for given feature names Args: colx (str): name of column from dataset coly (str): name of column from dataset path: path where plots will be saved if parameter :save is True. Defaults to None. If :save is True and path has not been given, plots will save in dir 'plots' in working directory show (bool, optional): parameter for showing windows with plots. Defaults to True. save (bool, optional): parameter for saving plots in :path. Defaults to False. """ #prepare labels orig = [] for i in self.original.data_label_train: orig.append(self.original.class_dict[i]) orig = np.array(orig) red = [] for i in self.reduced_label: red.append(self.original.class_dict[i]) red = np.array(red) #get indexes of features idx = self.original.features.index(colx) idy = self.original.features.index(coly) #create plots for name, obj, col in [('Original dataset', self.original.data_all_train, orig), ('Reduced dataset', self.reduced_data, red)]: fig, ax = plt.subplots() scatter = ax.scatter(obj[:,idx], obj[:,idy], c = col) legend = ax.legend(*scatter.legend_elements(), title="Classes") ax.add_artist(legend) plt.xlabel(self.original.features[idx]) plt.ylabel(self.original.features[idy]) #set same scale if name == 'Original dataset': bottom_y, top_y = plt.ylim() bottom_x, top_x = plt.xlim() else: plt.xlim(bottom_x, top_x) plt.ylim(bottom_y, top_y) plt.title(name) if save: if path == None: path = os.path.join(os.getcwd(), 'plots') if not os.path.exists(path): os.makedirs(path) filename = "{} {}({})".format(name, self.original.features[idx], self.original.features[idy]) plt.savefig(os.path.join(path, filename)) if show: plt.show() @staticmethod def create_confusion_matrix(classifier, test_set, test_labels, title:str, filename:str, path, show:bool, save:bool): """Function creating confusion matrix for given parametres Args: classifier: sklearn classifier, given from the available ones test_set: test dataset test_labels: labels for test dataset title (str): title of plot filename (str): name of the file that will be saved if :save is True path: path where plot show (bool): parameter for showing window with created plot save (bool): parameter for saving plot as file with name :filename in :path """ plot = plot_confusion_matrix(classifier, test_set, test_labels, cmap=plt.cm.Blues) #title = "Confusion matrix\n reduced data - classifier: " + str(c_type) plot.ax_.set_title(title) if save: if path == None: path = os.path.join(os.getcwd(), 'plots') if not os.path.exists(path): os.makedirs(path) # else if not os.path.isabs(filepath): # path = os.path.join(os.getcwd(), path) plot.figure_.savefig(os.path.join(path,filename)) if show: plt.show() def _raport(self, original_set, original_labels, reduced_set, reduced_labels, test_set, test_labels, c_type, show_cf_matrix :bool, path, save_cf_matrix: bool, norm: bool): """Main function in Raport class. It is responsible for : - classify with original and reduced dataset, - printing results of classification quality - creating confusion matrices - time measurement for classification and prediction Args: original_set: array with original dataset original_labels: array with labels for original datase reduced_set: array with reduced dataset reduced_labels: array with labels for reduced dataset test_set: array with test dataset test_labels: array with labels for test dataset c_type (str): type of classifier. If 'all' - creates raport for all available classifiers show_cf_matrix (bool): parameter for showing windows with created confusion matrices path: path to save in created confusion matrices save_cf_matrix (bool): parameter for saving created confusion matrices Raises: Exception: when given value classifier type not exist in dictionary of available types """ if (c_type !='all') and (c_type not in classifiers): raise Exception("Classifier type not exist in available set!") else: if c_type == 'all': for c_t in classifiers: self._raport(original_set, original_labels, reduced_set, reduced_labels, test_set, test_labels, c_t, show_cf_matrix, path, save_cf_matrix, norm) else: #select classifier classifier = classifiers[c_type] #normalize data: if norm: original_set = normalize(original_set) reduced_set = normalize(reduced_set) #train with original dataset and time measure start = time.clock() classifier.fit(original_set, original_labels) end = time.clock() training_time = end - start #make predictions and time measure start = time.clock() predict = classifier.predict(test_set) end = time.clock() prediction_time = end - start #create confusion matrix if (save_cf_matrix or show_cf_matrix) is not False: title = "Confusion matrix\n original data - classifier: {}".format(str(c_type)) self.create_confusion_matrix(classifier, test_set, test_labels, title, "Original - " + c_type, path, show_cf_matrix, save_cf_matrix) #print raport with metrics for original training data print('=============') print("Classifier: ", c_type) print('=============') print("Raport for original dataset") print('Count of instances: ', len(original_labels)) print(classification_report(test_labels, predict, digits=4)) print("Cohen's Kappa: {:.2f}".format(cohen_kappa_score(test_labels, predict))) print('===') print("Training time: ", training_time) print("Predicting time: ", prediction_time) #same for reduced training dataset classifier = classifiers[c_type] #train start = time.clock() classifier.fit(reduced_set, reduced_labels) end = time.clock() training_time = end - start #predict start = time.clock() predict = classifier.predict(test_set) end = time.clock() prediction_time = end - start #create confusion matrix if (save_cf_matrix or show_cf_matrix) is not False: title = "Confusion matrix\n reduced data - classifier: {}".format(str(c_type)) self.create_confusion_matrix(classifier, test_set, test_labels, title, "Reduced - " + c_type, path, show_cf_matrix, save_cf_matrix) print("\nRaport for reduced dataset") print('Count of instances: ', len(reduced_labels)) print(classification_report(test_labels, predict, digits = 4)) print("Cohen's Kappa: {:.2f}".format(cohen_kappa_score(test_labels, predict))) print('===') print("Training time: ", training_time) print("Predicting time: ", prediction_time, "\n") print('Reduction factor: {:.2f} %'.format((len(original_labels) - len(reduced_labels))/len(original_labels)*100)) print('===') row = pd.Series([c_type, accuracy_score(test_labels, predict), cohen_kappa_score(test_labels, predict), training_time, prediction_time ]) def print_raport(self, c_type= 'all', show_cf_matrix = True, path = None, save_cf_matrix = False, norm = False): """Function responssible for call function printing raport with apriopriate arguments. Args: c_type (str, optional): Type of classifier. One from dictionary :classifiers:. Defaults to 'all'. It means that raport will be created for all available classifiers. Possible values: 'knn': KNeighborsClassifier(), 'svm': svm.SVC(), 'naive_bayers': GaussianNB(), 'decision_tree': DecisionTreeClassifier(), 'neutral_network': MLPClassifier(). show_cf_matrix (bool, optional): Parameter for showing windows with confusion matrices. Defaults to True. path (optional): Path for saving created confusion matrices. Defaults to None. save_cf_matrix (bool, optional): Parameter for saving created confusion matrices. Defaults to False. """ self._raport(self.original.data_all_train, self.original.data_label_train, self.reduced_data, self.reduced_label, self.original.data_all_test, self.original.data_label_test, c_type, show_cf_matrix, path, save_cf_matrix, norm)
[ "time.clock", "matplotlib.pyplot.ylabel", "sklearn.metrics.classification_report", "sklearn.neighbors.KNeighborsClassifier", "numpy.array", "os.path.exists", "matplotlib.pyplot.xlabel", "sklearn.tree.DecisionTreeClassifier", "matplotlib.pyplot.ylim", "matplotlib.pyplot.title", "sklearn.naive_bay...
[((816, 849), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (839, 849), False, 'import warnings\n'), ((873, 895), 'sklearn.neighbors.KNeighborsClassifier', 'KNeighborsClassifier', ([], {}), '()\n', (893, 895), False, 'from sklearn.neighbors import KNeighborsClassifier\n'), ((921, 930), 'sklearn.svm.SVC', 'svm.SVC', ([], {}), '()\n', (928, 930), False, 'from sklearn import svm\n'), ((965, 977), 'sklearn.naive_bayes.GaussianNB', 'GaussianNB', ([], {}), '()\n', (975, 977), False, 'from sklearn.naive_bayes import GaussianNB\n'), ((1013, 1037), 'sklearn.tree.DecisionTreeClassifier', 'DecisionTreeClassifier', ([], {}), '()\n', (1035, 1037), False, 'from sklearn.tree import DecisionTreeClassifier\n'), ((1073, 1088), 'sklearn.neural_network.MLPClassifier', 'MLPClassifier', ([], {}), '()\n', (1086, 1088), False, 'from sklearn.neural_network import MLPClassifier\n'), ((3416, 3430), 'numpy.array', 'np.array', (['orig'], {}), '(orig)\n', (3424, 3430), True, 'import numpy as np\n'), ((3552, 3565), 'numpy.array', 'np.array', (['red'], {}), '(red)\n', (3560, 3565), True, 'import numpy as np\n'), ((5623, 5698), 'sklearn.metrics.plot_confusion_matrix', 'plot_confusion_matrix', (['classifier', 'test_set', 'test_labels'], {'cmap': 'plt.cm.Blues'}), '(classifier, test_set, test_labels, cmap=plt.cm.Blues)\n', (5644, 5698), False, 'from sklearn.metrics import plot_confusion_matrix\n'), ((3879, 3893), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (3891, 3893), True, 'from matplotlib import pyplot as plt\n'), ((4095, 4134), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['self.original.features[idx]'], {}), '(self.original.features[idx])\n', (4105, 4134), True, 'from matplotlib import pyplot as plt\n'), ((4147, 4186), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['self.original.features[idy]'], {}), '(self.original.features[idy])\n', (4157, 4186), True, 'from matplotlib import pyplot as plt\n'), ((4462, 4477), 'matplotlib.pyplot.title', 'plt.title', (['name'], {}), '(name)\n', (4471, 4477), True, 'from matplotlib import pyplot as plt\n'), ((6199, 6209), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6207, 6209), True, 'from matplotlib import pyplot as plt\n'), ((4292, 4302), 'matplotlib.pyplot.ylim', 'plt.ylim', ([], {}), '()\n', (4300, 4302), True, 'from matplotlib import pyplot as plt\n'), ((4337, 4347), 'matplotlib.pyplot.xlim', 'plt.xlim', ([], {}), '()\n', (4345, 4347), True, 'from matplotlib import pyplot as plt\n'), ((4382, 4407), 'matplotlib.pyplot.xlim', 'plt.xlim', (['bottom_x', 'top_x'], {}), '(bottom_x, top_x)\n', (4390, 4407), True, 'from matplotlib import pyplot as plt\n'), ((4424, 4449), 'matplotlib.pyplot.ylim', 'plt.ylim', (['bottom_y', 'top_y'], {}), '(bottom_y, top_y)\n', (4432, 4449), True, 'from matplotlib import pyplot as plt\n'), ((4890, 4900), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4898, 4900), True, 'from matplotlib import pyplot as plt\n'), ((5936, 5956), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (5950, 5956), False, 'import os\n'), ((5974, 5991), 'os.makedirs', 'os.makedirs', (['path'], {}), '(path)\n', (5985, 5991), False, 'import os\n'), ((6141, 6169), 'os.path.join', 'os.path.join', (['path', 'filename'], {}), '(path, filename)\n', (6153, 6169), False, 'import os\n'), ((8260, 8272), 'time.clock', 'time.clock', ([], {}), '()\n', (8270, 8272), False, 'import time\n'), ((8357, 8369), 'time.clock', 'time.clock', ([], {}), '()\n', (8367, 8369), False, 'import time\n'), ((8490, 8502), 'time.clock', 'time.clock', ([], {}), '()\n', (8500, 8502), False, 'import time\n'), ((8580, 8592), 'time.clock', 'time.clock', ([], {}), '()\n', (8590, 8592), False, 'import time\n'), ((9785, 9797), 'time.clock', 'time.clock', ([], {}), '()\n', (9795, 9797), False, 'import time\n'), ((9880, 9892), 'time.clock', 'time.clock', ([], {}), '()\n', (9890, 9892), False, 'import time\n'), ((9986, 9998), 'time.clock', 'time.clock', ([], {}), '()\n', (9996, 9998), False, 'import time\n'), ((10076, 10088), 'time.clock', 'time.clock', ([], {}), '()\n', (10086, 10088), False, 'import time\n'), ((4617, 4637), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (4631, 4637), False, 'import os\n'), ((4659, 4676), 'os.makedirs', 'os.makedirs', (['path'], {}), '(path)\n', (4670, 4676), False, 'import os\n'), ((4823, 4851), 'os.path.join', 'os.path.join', (['path', 'filename'], {}), '(path, filename)\n', (4835, 4851), False, 'import os\n'), ((5895, 5906), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (5904, 5906), False, 'import os\n'), ((8076, 8099), 'sklearn.preprocessing.normalize', 'normalize', (['original_set'], {}), '(original_set)\n', (8085, 8099), False, 'from sklearn.preprocessing import normalize\n'), ((8134, 8156), 'sklearn.preprocessing.normalize', 'normalize', (['reduced_set'], {}), '(reduced_set)\n', (8143, 8156), False, 'from sklearn.preprocessing import normalize\n'), ((9341, 9394), 'sklearn.metrics.classification_report', 'classification_report', (['test_labels', 'predict'], {'digits': '(4)'}), '(test_labels, predict, digits=4)\n', (9362, 9394), False, 'from sklearn.metrics import classification_report\n'), ((10640, 10693), 'sklearn.metrics.classification_report', 'classification_report', (['test_labels', 'predict'], {'digits': '(4)'}), '(test_labels, predict, digits=4)\n', (10661, 10693), False, 'from sklearn.metrics import classification_report\n'), ((4572, 4583), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (4581, 4583), False, 'import os\n'), ((9450, 9489), 'sklearn.metrics.cohen_kappa_score', 'cohen_kappa_score', (['test_labels', 'predict'], {}), '(test_labels, predict)\n', (9467, 9489), False, 'from sklearn.metrics import cohen_kappa_score\n'), ((10750, 10789), 'sklearn.metrics.cohen_kappa_score', 'cohen_kappa_score', (['test_labels', 'predict'], {}), '(test_labels, predict)\n', (10767, 10789), False, 'from sklearn.metrics import cohen_kappa_score\n'), ((11180, 11216), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['test_labels', 'predict'], {}), '(test_labels, predict)\n', (11194, 11216), False, 'from sklearn.metrics import accuracy_score\n'), ((11254, 11293), 'sklearn.metrics.cohen_kappa_score', 'cohen_kappa_score', (['test_labels', 'predict'], {}), '(test_labels, predict)\n', (11271, 11293), False, 'from sklearn.metrics import cohen_kappa_score\n')]
import face_recognition import cv2 import numpy as np import pandas as pd import datetime from datetime import timedelta #Melhoria: # Tirar nova foto a pessoas que já tiraram foto mas continuam a não ser reconhecidas # This is a demo of running face recognition on live video from your webcam. It's a little more complicated than the # other example, but it includes some basic performance tweaks to make things run a lot faster: # 1. Process each video frame at 1/4 resolution (though still display it at full resolution) # 2. Only detect faces in every other frame of video. # PLEASE NOTE: This example requires OpenCV (the `cv2` library) to be installed only to read from your webcam. # OpenCV is *not* required to use the face_recognition library. It's only required if you want to run this # specific demo. If you have trouble installing it, try any of the other demos that don't require it instead. # Vars globais # Criar Dataframe para guardar registos de entrada e saida time_df = pd.DataFrame(columns = ["nome", "data"]) # Get a reference to webcam #0 (the default one) video_capture = cv2.VideoCapture(0) # Load a sample picture and learn how to recognize it. pai_image = face_recognition.load_image_file("saved_img.jpg") pai_face_encoding = face_recognition.face_encodings(pai_image)[0] eu_image = face_recognition.load_image_file("eu.jpg") eu_face_encoding = face_recognition.face_encodings(eu_image)[0] bea_image = face_recognition.load_image_file("bea.jpg") bea_face_encoding = face_recognition.face_encodings(bea_image)[0] # Create arrays of known face encodings and their names known_face_encodings = [ pai_face_encoding, eu_face_encoding, bea_face_encoding ] known_face_names = [ "<NAME>", "<NAME>", "<NAME>" ] # Initialize some variables face_locations = [] face_encodings = [] face_names = [] process_this_frame = True df = pd.DataFrame() while True: # Grab a single frame of video ret, frame = video_capture.read() # Resize frame of video to 1/4 size for faster face recognition processing small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25) # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses) rgb_small_frame = small_frame[:, :, ::-1] # Only process every other frame of video to save time if process_this_frame: # Find all the faces and face encodings in the current frame of video face_locations = face_recognition.face_locations(rgb_small_frame) face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations) face_names = [] for face_encoding in face_encodings: # See if the face is a match for the known face(s) matches = face_recognition.compare_faces(known_face_encodings, face_encoding) name = "Unknown" # # If a match was found in known_face_encodings, just use the first one. # if True in matches: # first_match_index = matches.index(True) # name = known_face_names[first_match_index] # Or instead, use the known face with the smallest distance to the new face face_distances = face_recognition.face_distance(known_face_encodings, face_encoding) best_match_index = np.argmin(face_distances) # Se houve match if matches[best_match_index]: name = known_face_names[best_match_index] now = datetime.datetime.now() # Contar 1 minuto desde que entrou até poder ser detetado outra vez threshold = timedelta(seconds = 10) final_time = now + threshold # Adicionar aqui código para guardar registo da pessoa # Se o DF está vazio (sem registos, faz primeiro registo) if time_df.empty: now = datetime.datetime.now() aux_df = pd.DataFrame({"nome": name, "data": now, "registo": "entrada", "ok_time": final_time}, index = [0]) time_df = time_df.append(aux_df) print(time_df) else: # ir ao dataframe buscar ultimo registo para aquele nome # Se esse registo for para a mesma hora/dia, quer dizer que é repetido # Mudar para um timer de 30 minutos (threads?) auxiliar_df = time_df[time_df.nome == name] # Primeiro registo de cada pessoa - sempre "entrada" if auxiliar_df.empty: aux_df = pd.DataFrame({"nome": name, "data": now, "registo": "entrada", "ok_time": final_time, "horas_trabalho": 0}, index = [0]) time_df = time_df.append(aux_df) entrada_saida_flag = "entrada" print(time_df) else: ultimo_registo_df = auxiliar_df.iloc[-1] entrada_saida_flag = ultimo_registo_df.registo # Se ainda não passou o threshold dessa pessoa if (ultimo_registo_df.nome == name) & (ultimo_registo_df.ok_time >= now): break else: # se o último registo foi uma entrada if entrada_saida_flag == "entrada": aux_df = pd.DataFrame({"nome": name, "data": now, "registo": "saida", "ok_time": final_time, "horas_trabalho": datetime.datetime.now() - ultimo_registo_df.data}, index=[0]) else: aux_df = pd.DataFrame({"nome": name, "data": now, "registo": "entrada", "ok_time": final_time, "horas_trabalho": 0}, index = [0]) time_df = time_df.append(aux_df) print(time_df) face_names.append(name) process_this_frame = not process_this_frame # Display the results for (top, right, bottom, left), name in zip(face_locations, face_names): # Scale back up face locations since the frame we detected in was scaled to 1/4 size top *= 4 right *= 4 bottom *= 4 left *= 4 # Draw a box around the face cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2) # Draw a label with a name below the face cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED) font = cv2.FONT_HERSHEY_DUPLEX cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1) # Display the resulting image cv2.imshow('Video', frame) # Hit 'q' on the keyboard to quit! if cv2.waitKey(1) & 0xFF == ord('q'): #print(time_df) for emp in known_face_names: aux = time_df[time_df.nome == emp] hr_emp = pd.to_timedelta(aux.horas_trabalho) print(emp) print(hr_emp) time_df = time_df.drop(columns=["ok_time"], axis = 1) time_df.to_csv("/Users/miguelroque/Documents/Startup/FaceDetect-master/bd_registos.csv") break # Release handle to the webcam video_capture.release() cv2.destroyAllWindows()
[ "cv2.rectangle", "face_recognition.face_locations", "pandas.to_timedelta", "cv2.imshow", "cv2.putText", "datetime.datetime.now", "face_recognition.face_distance", "datetime.timedelta", "cv2.destroyAllWindows", "cv2.VideoCapture", "face_recognition.load_image_file", "face_recognition.face_encod...
[((999, 1037), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['nome', 'data']"}), "(columns=['nome', 'data'])\n", (1011, 1037), True, 'import pandas as pd\n'), ((1106, 1125), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (1122, 1125), False, 'import cv2\n'), ((1194, 1243), 'face_recognition.load_image_file', 'face_recognition.load_image_file', (['"""saved_img.jpg"""'], {}), "('saved_img.jpg')\n", (1226, 1243), False, 'import face_recognition\n'), ((1321, 1363), 'face_recognition.load_image_file', 'face_recognition.load_image_file', (['"""eu.jpg"""'], {}), "('eu.jpg')\n", (1353, 1363), False, 'import face_recognition\n'), ((1440, 1483), 'face_recognition.load_image_file', 'face_recognition.load_image_file', (['"""bea.jpg"""'], {}), "('bea.jpg')\n", (1472, 1483), False, 'import face_recognition\n'), ((1882, 1896), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (1894, 1896), True, 'import pandas as pd\n'), ((7411, 7434), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (7432, 7434), False, 'import cv2\n'), ((1264, 1306), 'face_recognition.face_encodings', 'face_recognition.face_encodings', (['pai_image'], {}), '(pai_image)\n', (1295, 1306), False, 'import face_recognition\n'), ((1383, 1424), 'face_recognition.face_encodings', 'face_recognition.face_encodings', (['eu_image'], {}), '(eu_image)\n', (1414, 1424), False, 'import face_recognition\n'), ((1504, 1546), 'face_recognition.face_encodings', 'face_recognition.face_encodings', (['bea_image'], {}), '(bea_image)\n', (1535, 1546), False, 'import face_recognition\n'), ((2081, 2124), 'cv2.resize', 'cv2.resize', (['frame', '(0, 0)'], {'fx': '(0.25)', 'fy': '(0.25)'}), '(frame, (0, 0), fx=0.25, fy=0.25)\n', (2091, 2124), False, 'import cv2\n'), ((6858, 6884), 'cv2.imshow', 'cv2.imshow', (['"""Video"""', 'frame'], {}), "('Video', frame)\n", (6868, 6884), False, 'import cv2\n'), ((2464, 2512), 'face_recognition.face_locations', 'face_recognition.face_locations', (['rgb_small_frame'], {}), '(rgb_small_frame)\n', (2495, 2512), False, 'import face_recognition\n'), ((2538, 2602), 'face_recognition.face_encodings', 'face_recognition.face_encodings', (['rgb_small_frame', 'face_locations'], {}), '(rgb_small_frame, face_locations)\n', (2569, 2602), False, 'import face_recognition\n'), ((6482, 6548), 'cv2.rectangle', 'cv2.rectangle', (['frame', '(left, top)', '(right, bottom)', '(0, 0, 255)', '(2)'], {}), '(frame, (left, top), (right, bottom), (0, 0, 255), 2)\n', (6495, 6548), False, 'import cv2\n'), ((6608, 6696), 'cv2.rectangle', 'cv2.rectangle', (['frame', '(left, bottom - 35)', '(right, bottom)', '(0, 0, 255)', 'cv2.FILLED'], {}), '(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2\n .FILLED)\n', (6621, 6696), False, 'import cv2\n'), ((6739, 6818), 'cv2.putText', 'cv2.putText', (['frame', 'name', '(left + 6, bottom - 6)', 'font', '(1.0)', '(255, 255, 255)', '(1)'], {}), '(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)\n', (6750, 6818), False, 'import cv2\n'), ((2758, 2825), 'face_recognition.compare_faces', 'face_recognition.compare_faces', (['known_face_encodings', 'face_encoding'], {}), '(known_face_encodings, face_encoding)\n', (2788, 2825), False, 'import face_recognition\n'), ((3213, 3280), 'face_recognition.face_distance', 'face_recognition.face_distance', (['known_face_encodings', 'face_encoding'], {}), '(known_face_encodings, face_encoding)\n', (3243, 3280), False, 'import face_recognition\n'), ((3312, 3337), 'numpy.argmin', 'np.argmin', (['face_distances'], {}), '(face_distances)\n', (3321, 3337), True, 'import numpy as np\n'), ((6931, 6945), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (6942, 6945), False, 'import cv2\n'), ((7095, 7130), 'pandas.to_timedelta', 'pd.to_timedelta', (['aux.horas_trabalho'], {}), '(aux.horas_trabalho)\n', (7110, 7130), True, 'import pandas as pd\n'), ((3491, 3514), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (3512, 3514), False, 'import datetime\n'), ((3627, 3648), 'datetime.timedelta', 'timedelta', ([], {'seconds': '(10)'}), '(seconds=10)\n', (3636, 3648), False, 'from datetime import timedelta\n'), ((3901, 3924), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (3922, 3924), False, 'import datetime\n'), ((3955, 4056), 'pandas.DataFrame', 'pd.DataFrame', (["{'nome': name, 'data': now, 'registo': 'entrada', 'ok_time': final_time}"], {'index': '[0]'}), "({'nome': name, 'data': now, 'registo': 'entrada', 'ok_time':\n final_time}, index=[0])\n", (3967, 4056), True, 'import pandas as pd\n'), ((4613, 4735), 'pandas.DataFrame', 'pd.DataFrame', (["{'nome': name, 'data': now, 'registo': 'entrada', 'ok_time': final_time,\n 'horas_trabalho': 0}"], {'index': '[0]'}), "({'nome': name, 'data': now, 'registo': 'entrada', 'ok_time':\n final_time, 'horas_trabalho': 0}, index=[0])\n", (4625, 4735), True, 'import pandas as pd\n'), ((5796, 5918), 'pandas.DataFrame', 'pd.DataFrame', (["{'nome': name, 'data': now, 'registo': 'entrada', 'ok_time': final_time,\n 'horas_trabalho': 0}"], {'index': '[0]'}), "({'nome': name, 'data': now, 'registo': 'entrada', 'ok_time':\n final_time, 'horas_trabalho': 0}, index=[0])\n", (5808, 5918), True, 'import pandas as pd\n'), ((5657, 5680), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (5678, 5680), False, 'import datetime\n')]
import pytest import numpy as np from BlueKumquatAutoDiff.autodiff import * def test_node_init(): x = Node(2) assert x.var == 2 assert x.partials() == 1 x = Node(2.) assert x.var == 2 assert x.partials() == 1 with pytest.raises(TypeError): x = Node("abc") def test_node_get_derivatives(): x = Node(2) z = Node(3) y = x * z assert y.get_derivatives([x,z])[0] == 6 assert y.get_derivatives([x,z])[1][0] == 3 assert y.get_derivatives([x,z])[1][1] == 2 def test_node_partials(): pass def test_node_str(): x = Node(2) assert str(x) == "value = 2, derivative = 1" def test_node_repr(): x = Node(2) assert repr(x) == "value = 2, derivative = 1" def test_node_add(): # add two Node objects x = Node(1) y = x+Node(2) assert y.var == 3 assert y.partials() == 1 # add a int/float to Node object x = Node(1) y = 2. + x assert y.var == 3 assert y.partials() == 1. # add a int/float to Node object x = Node(1) y = x + 2. assert y.var == 3 assert y.partials() == 1. # add a int/float to Node object x = Node(1) y = 2. + x + Node(2) assert y.var == 5 assert y.partials() == 1 # add an invalid type of input to Node object with pytest.raises(TypeError): x = Node(1) y = x + "a" with pytest.raises(TypeError): x = Node(1) y = "a" + x def test_node_neg(): x = Node(1) y = -x assert y.var == -1 assert y.partials() == 1 assert x.partials() == -1 def test_node_sub(): # subtract two Node objects x = Node(1) y = x - Node(2) assert y.var == -1 assert y.partials() == 1 # subtract a int/float to Node object x = Node(1) y = x - 2. assert y.var == -1 assert y.partials() == 1 x = Node(1) y = 2. - x assert y.var == 1 assert y.partials() == 1 assert x.partials() == -1 # subtract an invalid type of input with Node object with pytest.raises(TypeError): x = Node(1) y = x - "a" def test_node_mul(): # multiply two Node objects x = Node(1) y = x * Node(2) assert y.var == 2 assert y.partials() == 1 assert x.partials() == 2 # multiply a int/float to Node object x = Node(1) y = x * 2. assert y.var == 2 assert y.partials() == 1 assert x.partials() == 2 x = Node(1) y = 2. * x assert y.var == 2 assert x.partials() == 2 assert y.partials() == 1 x = Node(1) y = x * -2. assert y.var == -2 assert x.partials() == -2 assert y.partials() == 1 x = Node(1) y = -2. * x assert y.var == -2 assert x.partials() == -2 assert y.partials() == 1 # multiply an invalid type of input with Node object with pytest.raises(TypeError): x = Node(1) y = x * "a" def test_node_truediv(): # divide two Node objects x = Node(1) y = Node(2) / x assert y.var == 2 assert y.partials() == 1 assert x.partials() == -2 # divide a int/float by Node object x = Node(1) y = 5. / x assert y.var == 5 assert x.partials() == -5 # divide a int/float by Node object x = Node(1) y = x / 5. assert y.var == 1/5 assert x.partials() == 1/5 assert y.partials() == 1 # divide Node object by an invalid type of input with pytest.raises(TypeError): x = Node(1) y = x / "a" with pytest.raises(TypeError): x = Node(1) y = "a" / x def test_node_lt(): x = Node(1) y = Node(2) assert (x < y) == True x = Node(1) assert (x < 1) == False with pytest.raises(TypeError): x = Node(1) check = "a" < x def test_node_gt(): x = Node(1) y = Node(2) assert (y > x) == True x = Node(1) assert (x > 1) == False with pytest.raises(TypeError): x = Node(1) check = "a" > x def test_node_le(): x = Node(1) y = Node(2) assert (x <= y) == True x = Node(1) assert (x <= 1) == True with pytest.raises(TypeError): x = Node(1) check = "a" <= x def test_node_ge(): x = Node(1) y = Node(2) assert (y >= x) == True x = Node(1) assert (x >= 1) == True with pytest.raises(TypeError): x = Node(1) check = "a" >= x def test_node_eq(): x = Node(1) y = Node(2) assert (y == x) == False with pytest.raises(TypeError): x = Node(1) check = x == 1 def test_node_ne(): x = Node(1) y = Node(2) assert (y != x) == True with pytest.raises(TypeError): x = Node(1) check = x != 1 def test_node_abs(): x = abs(Node(1)) assert x.var == 1 assert x.partials() == 1 y = abs(Node(-2)) assert y.var == 2 assert y.partials() == 1 def test_node_pow(): x = Node(2) y = x ** 4 assert y.var == 2 ** 4 assert x.partials() == 4 * (2 ** 3) assert y.partials() == 1 x = Node(2) y = x ** -4 assert y.var == 2 ** -4 assert x.partials() == -4 * (2 ** -5) assert y.partials() == 1 x = Node(2) y = x ** x assert y.var == 2 ** 2 assert x.partials() == 2 ** 2 * (np.log(2) * 1 / 1 + 2 / 2) assert y.partials() == 1 x = Node(2) y = x ** (x * 2) assert y.var == 2 ** (2 * 2) assert x.partials() == 2 ** (2 * 2) * (np.log(2) * 2 / 1 + (2 * 2) / 2) assert y.partials() == 1 with pytest.raises(TypeError): x = Node(1) check = x ** 1.2 with pytest.raises(TypeError): x = Node(1) check = x ** -1.2 def test_node_rpow(): x = Node(2) y = 4 ** x assert y.var == 4 ** 2 assert x.partials() == 4 ** 2 * np.log(4) assert y.partials() == 1 with pytest.raises(Exception): x = Node(2) y = -4 ** x assert y.var == 4 ** 2 x = Node(2) y = 4 ** (x * 2) assert y.var == 4 ** (2 * 2) assert x.partials() == 2 ** (4 * 2 + 1) * np.log(4) with pytest.raises(ValueError): x = Node(2) y = "a" ** x def test_node_log(): x = Node(2) y = Node.log(x) assert y.var == np.log(2) assert x.partials() == 1 / 2 assert y.partials() == 1 x = Node(2) y = Node.log(2 * x) assert y.var == 2 * np.log(2) assert x.partials() == 1 / 2 assert y.partials() == 1 with pytest.raises(TypeError): x = Node(-2) y = Node.log(x) with pytest.raises(TypeError): x = Node(-2) y = Node.log(2 * x) with pytest.raises(TypeError): y = Node.log(2) def test_node_sqrt(): x = Node(2) y = Node.sqrt(x) assert y.var == np.sqrt(2) assert x.partials() == 1/2 * 2 ** (-1/2) x = Node(2) y = Node.sqrt(2 * x) assert y.var == np.sqrt(2 * 2) assert x.partials() == 1/ np.sqrt(2) * 2 ** (-1/2) with pytest.raises(ValueError): x = Node(-2) y = Node.sqrt(x) with pytest.raises(TypeError): y = Node.sqrt("a") with pytest.raises(TypeError): y = Node.sqrt(2) def test_node_exp(): x = Node(2) y = Node.exp(x) assert y.var == np.exp(2) assert x.partials() == np.exp(2) x = Node(2) y = Node.exp(2 * x) assert y.var == np.exp(2 * 2) assert x.partials() == 2 * np.exp(2 * 2) with pytest.raises(TypeError): y = Node.exp("a") y = Node.exp(2) assert y == np.exp(2) def test_node_sin(): x = Node(np.pi/2) y = Node.sin(x) assert y.var == np.sin(np.pi/2) assert x.partials() == np.cos(np.pi/2) x = Node(np.pi/2) y = Node.sin(2 * x) assert y.var == np.sin(2 * np.pi/2) assert x.partials() == 2 * np.cos(2 * np.pi/2) with pytest.raises(TypeError): y = Node.sin("a") y = Node.sin(np.pi/2) assert y == np.sin(np.pi/2) def test_node_cos(): x = Node(np.pi/2) y = Node.cos(x) assert y.var == np.cos(np.pi/2) assert x.partials() == -np.sin(np.pi/2) with pytest.raises(TypeError): y = Node.cos("a") y = Node.cos(np.pi) assert y == np.cos(np.pi) def test_node_tan(): x = Node(np.pi/3) y = Node.tan(x) assert y.var == np.tan(np.pi/3) assert x.partials() == 1/np.cos(np.pi/3)**2 with pytest.raises(TypeError): y = Node.tan("a") y = Node.tan(np.pi/3) assert y == np.tan(np.pi/3) def test_node_arcsin(): x = Node(1/2) y = Node.arcsin(x) assert y.var == np.arcsin(1/2) assert x.partials() == 1 / np.sqrt(1 - (1/2) ** 2) with pytest.raises(TypeError): y = Node.arcsin("a") with pytest.raises(TypeError): x = Node(-2) y = Node.arcsin(x) y = Node.arcsin(1/2) assert y == np.arcsin(1/2) def test_node_arccos(): x = Node(1/2) y = Node.arccos(x) assert y.var == np.arccos(1/2) assert x.partials() == -1 / np.sqrt(1 - (1/2) ** 2) with pytest.raises(TypeError): y = Node.arccos("a") with pytest.raises(TypeError): x = Node(-2) y = Node.arccos(x) assert Node.arccos(1/2) == np.arccos(1/2) def test_node_arctan(): x = Node(1/2) y = Node.arctan(x) assert y.var == np.arctan(1/2) assert x.partials() == 1 / (1 + np.power(1/2, 2)) with pytest.raises(TypeError): y = Node.arctan("a") assert Node.arctan(1/2) == np.arctan(1/2) def test_node_sinh(): x = Node(1/2) y = Node.sinh(x) assert y.var == np.sinh(1/2) assert x.partials() == np.cosh(1/2) with pytest.raises(TypeError): y = Node.sinh("a") assert Node.sinh(1/2) == np.sinh(1/2) def test_node_cosh(): x = Node(1/2) y = Node.cosh(x) assert y.var == np.cosh(1/2) assert x.partials() == np.sinh(1/2) with pytest.raises(TypeError): y = Node.cosh("a") assert Node.cosh(1/2) == np.cosh(1/2) def test_node_tanh(): x = Node(1/2) y = Node.tanh(x) assert y.var == np.tanh(1/2) assert y.partials() == 1 with pytest.raises(TypeError): y = Node.tanh("a") assert Node.tanh(1/2) == np.tanh(1/2) def test_node_sigmoid(): x = Node(2) y = Node.sigmoid(x) assert y.var == 1 / (1 + np.exp(-2)) assert x.partials() == 1 / (1 + np.exp(-2)) * (1 - 1 / (1 + np.exp(-2))) with pytest.raises(TypeError): y = Node.sigmoid("a")
[ "numpy.sqrt", "numpy.tan", "numpy.arccos", "numpy.power", "numpy.log", "numpy.arcsin", "numpy.tanh", "numpy.sinh", "numpy.exp", "pytest.raises", "numpy.cos", "numpy.cosh", "numpy.sin", "numpy.arctan" ]
[((246, 270), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (259, 270), False, 'import pytest\n'), ((1306, 1330), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (1319, 1330), False, 'import pytest\n'), ((1382, 1406), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (1395, 1406), False, 'import pytest\n'), ((2033, 2057), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (2046, 2057), False, 'import pytest\n'), ((2841, 2865), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (2854, 2865), False, 'import pytest\n'), ((3427, 3451), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (3440, 3451), False, 'import pytest\n'), ((3503, 3527), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (3516, 3527), False, 'import pytest\n'), ((3705, 3729), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (3718, 3729), False, 'import pytest\n'), ((3911, 3935), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (3924, 3935), False, 'import pytest\n'), ((4118, 4142), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (4131, 4142), False, 'import pytest\n'), ((4326, 4350), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (4339, 4350), False, 'import pytest\n'), ((4491, 4515), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (4504, 4515), False, 'import pytest\n'), ((4652, 4676), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (4665, 4676), False, 'import pytest\n'), ((5510, 5534), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (5523, 5534), False, 'import pytest\n'), ((5591, 5615), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (5604, 5615), False, 'import pytest\n'), ((5830, 5854), 'pytest.raises', 'pytest.raises', (['Exception'], {}), '(Exception)\n', (5843, 5854), False, 'import pytest\n'), ((6064, 6089), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (6077, 6089), False, 'import pytest\n'), ((6210, 6219), 'numpy.log', 'np.log', (['(2)'], {}), '(2)\n', (6216, 6219), True, 'import numpy as np\n'), ((6429, 6453), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (6442, 6453), False, 'import pytest\n'), ((6510, 6534), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (6523, 6534), False, 'import pytest\n'), ((6595, 6619), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (6608, 6619), False, 'import pytest\n'), ((6726, 6736), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (6733, 6736), True, 'import numpy as np\n'), ((6844, 6858), 'numpy.sqrt', 'np.sqrt', (['(2 * 2)'], {}), '(2 * 2)\n', (6851, 6858), True, 'import numpy as np\n'), ((6923, 6948), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (6936, 6948), False, 'import pytest\n'), ((7006, 7030), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (7019, 7030), False, 'import pytest\n'), ((7069, 7093), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (7082, 7093), False, 'import pytest\n'), ((7199, 7208), 'numpy.exp', 'np.exp', (['(2)'], {}), '(2)\n', (7205, 7208), True, 'import numpy as np\n'), ((7236, 7245), 'numpy.exp', 'np.exp', (['(2)'], {}), '(2)\n', (7242, 7245), True, 'import numpy as np\n'), ((7307, 7320), 'numpy.exp', 'np.exp', (['(2 * 2)'], {}), '(2 * 2)\n', (7313, 7320), True, 'import numpy as np\n'), ((7376, 7400), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (7389, 7400), False, 'import pytest\n'), ((7465, 7474), 'numpy.exp', 'np.exp', (['(2)'], {}), '(2)\n', (7471, 7474), True, 'import numpy as np\n'), ((7560, 7577), 'numpy.sin', 'np.sin', (['(np.pi / 2)'], {}), '(np.pi / 2)\n', (7566, 7577), True, 'import numpy as np\n'), ((7603, 7620), 'numpy.cos', 'np.cos', (['(np.pi / 2)'], {}), '(np.pi / 2)\n', (7609, 7620), True, 'import numpy as np\n'), ((7686, 7707), 'numpy.sin', 'np.sin', (['(2 * np.pi / 2)'], {}), '(2 * np.pi / 2)\n', (7692, 7707), True, 'import numpy as np\n'), ((7767, 7791), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (7780, 7791), False, 'import pytest\n'), ((7862, 7879), 'numpy.sin', 'np.sin', (['(np.pi / 2)'], {}), '(np.pi / 2)\n', (7868, 7879), True, 'import numpy as np\n'), ((7963, 7980), 'numpy.cos', 'np.cos', (['(np.pi / 2)'], {}), '(np.pi / 2)\n', (7969, 7980), True, 'import numpy as np\n'), ((8033, 8057), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (8046, 8057), False, 'import pytest\n'), ((8126, 8139), 'numpy.cos', 'np.cos', (['np.pi'], {}), '(np.pi)\n', (8132, 8139), True, 'import numpy as np\n'), ((8225, 8242), 'numpy.tan', 'np.tan', (['(np.pi / 3)'], {}), '(np.pi / 3)\n', (8231, 8242), True, 'import numpy as np\n'), ((8299, 8323), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (8312, 8323), False, 'import pytest\n'), ((8394, 8411), 'numpy.tan', 'np.tan', (['(np.pi / 3)'], {}), '(np.pi / 3)\n', (8400, 8411), True, 'import numpy as np\n'), ((8497, 8513), 'numpy.arcsin', 'np.arcsin', (['(1 / 2)'], {}), '(1 / 2)\n', (8506, 8513), True, 'import numpy as np\n'), ((8577, 8601), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (8590, 8601), False, 'import pytest\n'), ((8642, 8666), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (8655, 8666), False, 'import pytest\n'), ((8758, 8774), 'numpy.arcsin', 'np.arcsin', (['(1 / 2)'], {}), '(1 / 2)\n', (8767, 8774), True, 'import numpy as np\n'), ((8860, 8876), 'numpy.arccos', 'np.arccos', (['(1 / 2)'], {}), '(1 / 2)\n', (8869, 8876), True, 'import numpy as np\n'), ((8941, 8965), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (8954, 8965), False, 'import pytest\n'), ((9006, 9030), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (9019, 9030), False, 'import pytest\n'), ((9112, 9128), 'numpy.arccos', 'np.arccos', (['(1 / 2)'], {}), '(1 / 2)\n', (9121, 9128), True, 'import numpy as np\n'), ((9214, 9230), 'numpy.arctan', 'np.arctan', (['(1 / 2)'], {}), '(1 / 2)\n', (9223, 9230), True, 'import numpy as np\n'), ((9293, 9317), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (9306, 9317), False, 'import pytest\n'), ((9380, 9396), 'numpy.arctan', 'np.arctan', (['(1 / 2)'], {}), '(1 / 2)\n', (9389, 9396), True, 'import numpy as np\n'), ((9478, 9492), 'numpy.sinh', 'np.sinh', (['(1 / 2)'], {}), '(1 / 2)\n', (9485, 9492), True, 'import numpy as np\n'), ((9518, 9532), 'numpy.cosh', 'np.cosh', (['(1 / 2)'], {}), '(1 / 2)\n', (9525, 9532), True, 'import numpy as np\n'), ((9541, 9565), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (9554, 9565), False, 'import pytest\n'), ((9624, 9638), 'numpy.sinh', 'np.sinh', (['(1 / 2)'], {}), '(1 / 2)\n', (9631, 9638), True, 'import numpy as np\n'), ((9720, 9734), 'numpy.cosh', 'np.cosh', (['(1 / 2)'], {}), '(1 / 2)\n', (9727, 9734), True, 'import numpy as np\n'), ((9760, 9774), 'numpy.sinh', 'np.sinh', (['(1 / 2)'], {}), '(1 / 2)\n', (9767, 9774), True, 'import numpy as np\n'), ((9783, 9807), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (9796, 9807), False, 'import pytest\n'), ((9866, 9880), 'numpy.cosh', 'np.cosh', (['(1 / 2)'], {}), '(1 / 2)\n', (9873, 9880), True, 'import numpy as np\n'), ((9962, 9976), 'numpy.tanh', 'np.tanh', (['(1 / 2)'], {}), '(1 / 2)\n', (9969, 9976), True, 'import numpy as np\n'), ((10013, 10037), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (10026, 10037), False, 'import pytest\n'), ((10096, 10110), 'numpy.tanh', 'np.tanh', (['(1 / 2)'], {}), '(1 / 2)\n', (10103, 10110), True, 'import numpy as np\n'), ((10304, 10328), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (10317, 10328), False, 'import pytest\n'), ((5781, 5790), 'numpy.log', 'np.log', (['(4)'], {}), '(4)\n', (5787, 5790), True, 'import numpy as np\n'), ((6044, 6053), 'numpy.log', 'np.log', (['(4)'], {}), '(4)\n', (6050, 6053), True, 'import numpy as np\n'), ((6347, 6356), 'numpy.log', 'np.log', (['(2)'], {}), '(2)\n', (6353, 6356), True, 'import numpy as np\n'), ((7352, 7365), 'numpy.exp', 'np.exp', (['(2 * 2)'], {}), '(2 * 2)\n', (7358, 7365), True, 'import numpy as np\n'), ((7737, 7758), 'numpy.cos', 'np.cos', (['(2 * np.pi / 2)'], {}), '(2 * np.pi / 2)\n', (7743, 7758), True, 'import numpy as np\n'), ((8007, 8024), 'numpy.sin', 'np.sin', (['(np.pi / 2)'], {}), '(np.pi / 2)\n', (8013, 8024), True, 'import numpy as np\n'), ((8543, 8568), 'numpy.sqrt', 'np.sqrt', (['(1 - (1 / 2) ** 2)'], {}), '(1 - (1 / 2) ** 2)\n', (8550, 8568), True, 'import numpy as np\n'), ((8907, 8932), 'numpy.sqrt', 'np.sqrt', (['(1 - (1 / 2) ** 2)'], {}), '(1 - (1 / 2) ** 2)\n', (8914, 8932), True, 'import numpy as np\n'), ((6889, 6899), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (6896, 6899), True, 'import numpy as np\n'), ((8270, 8287), 'numpy.cos', 'np.cos', (['(np.pi / 3)'], {}), '(np.pi / 3)\n', (8276, 8287), True, 'import numpy as np\n'), ((9265, 9283), 'numpy.power', 'np.power', (['(1 / 2)', '(2)'], {}), '(1 / 2, 2)\n', (9273, 9283), True, 'import numpy as np\n'), ((10205, 10215), 'numpy.exp', 'np.exp', (['(-2)'], {}), '(-2)\n', (10211, 10215), True, 'import numpy as np\n'), ((10253, 10263), 'numpy.exp', 'np.exp', (['(-2)'], {}), '(-2)\n', (10259, 10263), True, 'import numpy as np\n'), ((5268, 5277), 'numpy.log', 'np.log', (['(2)'], {}), '(2)\n', (5274, 5277), True, 'import numpy as np\n'), ((5438, 5447), 'numpy.log', 'np.log', (['(2)'], {}), '(2)\n', (5444, 5447), True, 'import numpy as np\n'), ((10281, 10291), 'numpy.exp', 'np.exp', (['(-2)'], {}), '(-2)\n', (10287, 10291), True, 'import numpy as np\n')]
""" MBD-LLBorder """ from functools import partial from itertools import combinations import numpy as np import pandas as pd from joblib import Parallel, delayed from ..base import BaseMiner, DiscovererMixin from ..itemsets.lcm import LCMMax from ..utils import _check_growth_rate, _check_min_supp, filter_maximal, filter_minimal def border_diff(U, S): """ Given a pair of borders <{∅}, {U}> and <{∅}, {S}>, ``border_diff`` derives another border <L2, {U}> such that [L2, {U}] = [{∅}, {U}] - [{∅}, {S}] Parameters ---------- U : set non empty part from the border to differentiate S : list of set non-empty part of a border. Noted as ``R1`` in the original paper References ---------- .. [1] <NAME> Efficient Mining of Emerging Patterns Discovering Notes ----- See ``BORDER-DIFF`` in section 4.1 """ # assert len(R1) < len(U) # assert we iterate on the smallest ensemble L2 = [{x} for x in U - S[0]] for i in range(1, len(S)): _L2 = [X | {x} for x in U - S[i] for X in L2] L2 = list(filter_minimal(_L2)) return L2, U def mbdllborder(isets1, isets2): """ References ---------- .. [1] <NAME> Efficient Mining of Emerging Patterns Discovering Notes ----- main algorithm, as explained in section 4.2 """ borders = list() for iset in isets2: if any((e > iset for e in isets1)): continue inter = (iset & e for e in isets1) R = filter_maximal(inter) diff = border_diff(iset, R) borders.append(diff) return borders def borders_to_patterns(left, right, min_size=None): """ Operates in a bread-first manner, outputting all valid patterns of a given size for each level. Bigger patterns first. Parameters ---------- left: list of set right: set min_size: int only accepts patterns with greater or equal size Returns ------- pd.Series """ min_size = min_size or min(map(len, left)) patterns = list() for size in range(len(right) - 1, min_size - 1, -1): # bigger patterns first combs = combinations(right, size) for pat in combs: if any((e.issuperset(set(pat)) for e in left)): continue patterns.append(pat) return pd.Series(patterns) class MBDLLBorder(BaseMiner, DiscovererMixin): """ MBD-LLBorder aims at discovering patterns characterizing the difference between two collections of data. It first discovers ``two sets of maximal itemsets``, one for each collection. It then looks for borders of these sets, and characterizes the difference by only manipulating theses borders. This results in the algorithm only keeping a ``concise description (borders)`` as an internal state. Last but not least, it enumerates the set of emerging patterns from the borders. Parameters ---------- min_growth_rate: int or float, default=2 A pattern is considered as emerging iff its support in the first collection is at least min_growth_rate times its support in the second collection. min_supp: int or float, default=.1 Minimum support in each of the collection Must be a relative support between 0 and 1 Default to 0.1 (10%) n_jobs : int, default=1 The number of jobs to use for the computation. Attributes ---------- borders_: list of tuple[list[set], set] List of pairs representing left and right borders For every pair, emerging patterns will be uncovered by enumerating itemsets from the right side, while checking for non membership in the left side References ---------- .. [1] <NAME>, <NAME> "Efficient Mining of Emerging Patterns : Discovering Trends and Differences", 1999 """ def __init__(self, min_growth_rate=2, min_supp=0.1, n_jobs=1): self.min_supp = _check_min_supp(min_supp, accept_absolute=False) self.min_growth_rate = _check_growth_rate(min_growth_rate) self.borders_ = None self.n_jobs = n_jobs def fit(self, D, y): """ fit MBD-LLBorder on D, splitted on y This is done in two steps 1. Discover maximal itemsets for the two disinct collections contained in D 2. Mine borders from these maximal itemsets Parameters ---------- D : pd.Series The input transactional database Where every entry contains singular items Items must be both hashable and comparable y : array-like of shape (n_samples,) Targets on which to split D Must contain only two disctinct values, i.e len(np.unique(y)) == 2 """ labels = np.unique(y) assert len(labels) == 2 assert isinstance(D, pd.Series) # TODO : accept tabular data D1, D2 = D[y == labels[0]], D[y == labels[1]] # TODO : replace LCMMax by some more efficient method right_border_d1 = LCMMax(min_supp=self.min_supp).fit_discover(D1) right_border_d2 = LCMMax( min_supp=self.min_growth_rate * self.min_supp ).fit_discover(D2) right_border_d1 = right_border_d1.itemset.map(set).tolist() right_border_d2 = right_border_d2.itemset.map(set).tolist() self.borders_ = mbdllborder(right_border_d1, right_border_d2) return self def discover(self, min_size=3): """ Enumerate emerging patterns from borders Subsets are drawn from the right borders, and are accepted iff they do not belong to the corresponding left border. This implementation is parallel, we consider every couple of right/left border in a separate worker and run the computation Parameters ---------- min_size: int minimum size for an itemset to be valid """ btp = delayed(partial(borders_to_patterns, min_size=min_size)) series = Parallel(n_jobs=self.n_jobs, prefer="processes")( btp(L, R) for L, R in self.borders_ ) return pd.concat(series) if series else pd.Series(dtype="object")
[ "pandas.Series", "numpy.unique", "itertools.combinations", "joblib.Parallel", "functools.partial", "pandas.concat" ]
[((2400, 2419), 'pandas.Series', 'pd.Series', (['patterns'], {}), '(patterns)\n', (2409, 2419), True, 'import pandas as pd\n'), ((2218, 2243), 'itertools.combinations', 'combinations', (['right', 'size'], {}), '(right, size)\n', (2230, 2243), False, 'from itertools import combinations\n'), ((4886, 4898), 'numpy.unique', 'np.unique', (['y'], {}), '(y)\n', (4895, 4898), True, 'import numpy as np\n'), ((6059, 6106), 'functools.partial', 'partial', (['borders_to_patterns'], {'min_size': 'min_size'}), '(borders_to_patterns, min_size=min_size)\n', (6066, 6106), False, 'from functools import partial\n'), ((6125, 6173), 'joblib.Parallel', 'Parallel', ([], {'n_jobs': 'self.n_jobs', 'prefer': '"""processes"""'}), "(n_jobs=self.n_jobs, prefer='processes')\n", (6133, 6173), False, 'from joblib import Parallel, delayed\n'), ((6248, 6265), 'pandas.concat', 'pd.concat', (['series'], {}), '(series)\n', (6257, 6265), True, 'import pandas as pd\n'), ((6281, 6306), 'pandas.Series', 'pd.Series', ([], {'dtype': '"""object"""'}), "(dtype='object')\n", (6290, 6306), True, 'import pandas as pd\n')]
from __future__ import print_function import numpy as np import scipy.sparse as sp import hashlib import warnings import time # from gcn.utils import normalize_adj cupy_is_available = False try: import cupy as cp cupy_is_available = True except ImportError: warnings.warn("cupy is not imported, some operations may not use GPU.", ImportWarning) def normalize_adj(adj, type='sym'): """Symmetrically normalize adjacency matrix.""" if type == 'sym': adj = sp.coo_matrix(adj) rowsum = np.array(adj.sum(1)) # d_inv_sqrt = np.power(rowsum, -0.5) # d_inv_sqrt[np.isinf(d_inv_sqrt)] = 0. # return adj*d_inv_sqrt*d_inv_sqrt.flatten() d_inv_sqrt = np.power(rowsum, -0.5).flatten() d_inv_sqrt[np.isinf(d_inv_sqrt)] = 0. d_mat_inv_sqrt = sp.diags(d_inv_sqrt) return adj.dot(d_mat_inv_sqrt).transpose().dot(d_mat_inv_sqrt).tocoo() elif type == 'rw': rowsum = np.array(adj.sum(1)) d_inv = np.power(rowsum, -1.0).flatten() d_inv[np.isinf(d_inv)] = 0. d_mat_inv = sp.diags(d_inv) adj_normalized = d_mat_inv.dot(adj) return adj_normalized def md5(*args): fingerprint = b'' for arg in args: if isinstance(arg, str): fingerprint += arg.encode() elif isinstance(arg, (float, int, complex, list, tuple, dict, bool)) or arg is None: fingerprint += str(arg).encode() elif isinstance(arg, np.ndarray): fingerprint += arg.tobytes() else: raise NotImplementedError('Type:', str(type(arg)), 'Value:', arg) return hashlib.md5(fingerprint).hexdigest() def smooth(features, adj, smoothing, model_config, stored_A=None, fetch=None): def cache_file(*args): return "data/cache/{}.npz".format(md5(*args)) print(smoothing, 'Smoothing...') cache = True if model_config['cache'] else None if smoothing is None: return features, 0. elif smoothing == 'taubin': if cache: cache = cache_file(model_config['dataset'], model_config['taubin_lambda'], model_config['taubin_mu'], model_config['taubin_repeat'], fetch) return taubin_smoothing(adj, model_config['taubin_lambda'], model_config['taubin_mu'], model_config['taubin_repeat'], features, fetch=fetch, cache=cache) elif smoothing == 'ap_appro': k = int(np.ceil(4 / model_config['smooth_alpha'])) if cache: cache = cache_file(model_config['dataset'], model_config['smooth_alpha'], k, fetch) return ap_approximate(adj, features, model_config['smooth_alpha'], k, fetch=fetch, cache=cache) else: raise ValueError("smoothing must be one of 'poly' | 'ap' | 'taubin' | 'test21' | 'test27' ") import os def npz_cache(func): def func_with_cache(*args, cache=None, **kwargs): if cache is not None and os.path.isfile(cache): print('loading', cache, '...') loader = np.load(cache) if loader['multi_return']: n = len(list(loader.iterkeys()))-1 results = (loader['arr_'+str(i)] for i in range(n)) else: results = loader['results'] print('success', cache) else: results = func(*args, **kwargs) if cache is not None: print('save to', cache) if isinstance(results, (list, tuple)): np.savez_compressed(cache, *results, multi_return=True) else: np.savez_compressed(cache, results=results, multi_return=False) return results return func_with_cache def gpu_taubin_smoothing(step_transformor, features, repeat, fetch): #TODO: transfer sparse features to GPU #TODO: only fetch necessary data smooth_time = 0 step_transformor = cp.sparse.csr_matrix(step_transformor) step_transformor.sum_duplicates() tile_width = 1024**3//4//4//features.shape[0] #initialzie new_features if fetch is None: new_features = features else: new_features = features[fetch] if sp.issparse(new_features): new_features = new_features.todense() for i in range(0, features.shape[1], tile_width): low = i high = min(features.shape[1], i+tile_width) # transfer data to GPU if sp.issparse(features): tile = cp.sparse.csr_matrix(features[:, low:high]) tile = tile.todense() else: tile = cp.asarray(features[:, low:high]) tile = cp.asfortranarray(tile) tile.device.synchronize() # calculate begin = time.time() for i in range(repeat): tile = cp.cusparse.csrmm2(step_transformor, tile, tile) # tile = step_transformor.dot(tile) tile.device.synchronize() smooth_time += time.time()-begin # fetch if fetch is None: new_features[:, low:high] = tile.get() else: new_features[:, low:high] = tile[fetch].get() return new_features, smooth_time @npz_cache def taubin_smoothing(adj, lam, mu, repeat, features, fetch=None): smooth_time = 0 n = adj.shape[0] # adj = normalize(adj + sp.eye(adj.shape[0]), norm='l1', axis=1) adj = normalize_adj(adj + sp.eye(adj.shape[0]), 'rw') smoothor = sp.eye(n) * (1 - lam) + lam * adj inflator = sp.eye(n) * (1 - mu) + mu * adj step_transformor = smoothor * inflator step_transformor = step_transformor.astype(np.float32) features = features.astype(np.float32) if cupy_is_available: print('USE GPU') features, smooth_time = gpu_taubin_smoothing(step_transformor, features, repeat, fetch) else: if sp.issparse(features): features = features.toarray() begin = time.time() for i in range(repeat): features = step_transformor.dot(features) smooth_time += time.time()-begin if fetch is not None: features = features[fetch] if sp.issparse(features): features = features.toarray() return features, smooth_time # RNM def taubin_smoothor(adj, lam, mu, repeat): n = adj.shape[0] # adj = normalize(adj + sp.eye(adj.shape[0]), norm='l1', axis=1) adj = normalize_adj(adj + sp.eye(adj.shape[0]), 'rw') smoothor = sp.eye(n) * (1 - lam) + lam * adj inflator = sp.eye(n) * (1 - mu) + mu * adj step_transformor = smoothor * inflator transformor = sp.eye(n) base = step_transformor while repeat != 0: if repeat % 2: transformor *= base base *= base repeat //= 2 # print(repeat) return transformor def gpu_ap_approximate(adj, features, alpha, k, fetch): features = features.astype(np.float32) if fetch is None: new_features = features else: new_features = features[fetch] if sp.issparse(new_features): new_features = new_features.todense() smooth_time = 0 adj = cp.sparse.csr_matrix(adj) adj.sum_duplicates() tile_width = 1024**3//4//2//features.shape[0] for i in range(0, features.shape[1], tile_width): low = i high = min(features.shape[1], i+tile_width) # transfer data to GPU if sp.issparse(features): new_features_tile = cp.sparse.csr_matrix(features[:, low:high]) features_tile = cp.sparse.csr_matrix(features[:, low:high]) new_features_tile = new_features_tile.todense() features_tile = features_tile.todense() else: new_features_tile = cp.asarray(features[:, low:high]) features_tile = cp.asarray(features[:, low:high]) new_features_tile = cp.asfortranarray(new_features_tile) new_features_tile.device.synchronize() #calculate begin = time.time() for _ in range(k - 1): # new_feature = adj.dot(new_feature) + features new_features_tile = cp.cusparse.csrmm2(adj, new_features_tile, new_features_tile) new_features_tile += features_tile new_features_tile *= alpha / (alpha + 1) new_features_tile.device.synchronize() smooth_time += time.time()-begin # fetch if fetch is None: new_features[:, low:high] = new_features_tile.get() else: new_features[:, low:high] = new_features_tile[fetch].get() return new_features, smooth_time @npz_cache def ap_approximate(adj, features, alpha, k, fetch=None): smooth_time = 0 # adj = normalize(adj + sp.eye(adj.shape[0]), 'l1', axis=1) / (alpha + 1) adj = normalize_adj(adj + sp.eye(adj.shape[0]), 'sym') / (alpha + 1) adj = adj.astype(np.float32) if cupy_is_available: print('USE GPU') new_feature, smooth_time = gpu_ap_approximate(adj, features, alpha, k, fetch=fetch) else: if sp.issparse(features): features = features.toarray() features = features.astype(np.float32) new_feature = np.zeros(features.shape, dtype=features.dtype) begin = time.time() for _ in range(k): new_feature = adj.dot(new_feature) new_feature += features new_feature *= alpha / (alpha + 1) smooth_time += time.time()-begin if fetch is not None: new_feature = new_feature[fetch] return new_feature, smooth_time # @npz_cache # def md(adj, features, alpha, k, repeat): # smoothing_time = time.time() # for i in range(repeat): # features, _ = ap_approximate(adj, features, alpha, int(np.ceil(4 / alpha))) # adj = construct_knn_graph(features, k) # return adj, time.time()-smoothing_time # def test21(adj, alpha, beta, stored_a=None): # p = absorption_probability(adj + sp.eye(adj.shape[0]), alpha, stored_A=stored_a) # p *= alpha # # p = (p > (beta / alpha)).astype(np.float32) # lines = np.min([100, p.shape[0]]) # idx = np.arange(p.shape[0]) # np.random.shuffle(idx) # idx = idx[:lines] # p_flat = p[idx].flat # p_index = np.argsort(p_flat) # p_acc = np.add.accumulate(p_flat[p_index]) / lines # percentage = 1 - p_acc[-beta * lines] # # num = np.sum(p_acc <= (1-beta)) # # gate = p_flat[p_index[np.maximum(num-1, 0)]] # # num = beta * lines # gate = p_flat[p_index[len(p_index) - num]] # p = (p > [gate]).astype(np.float32) # # # global all_labels # c = np.argmax(all_labels, axis=1) # c = c == np.expand_dims(c, 1) # num = np.sum(p) # print("neighbor accuracy = ", np.sum(c * p) / num, 'average #neighbors = ', num / p.shape[0], 'energy reserved=', # percentage) # # normalize(p, norm='l1', axis=1, copy=False) # return sp.csr_matrix(p / beta) # def test27(adj, features, alpha, beta, stored_a=None): # p = absorption_probability(adj + sp.eye(adj.shape[0]), alpha, stored_A=stored_a) # # np.sort(p) # p *= alpha # # p = np.array([ # # [0.1, 0.5, 0.4], # # [0.2, 0.7, 0.1], # # [0.4, 0.3, 0.3] # # ]) # p_index = np.argsort(p, axis=1) # p_acc = np.add.accumulate(np.sort(p, axis=1), axis=1) # # plt.plot(np.add.accumulate(np.sort(p, axis=None))) # # plt.grid() # # plt.show() # num = np.sum(p_acc <= (1 - beta), axis=1) # gate = p[np.arange(p.shape[0]), p_index[np.arange(p.shape[0]), np.maximum(num - 1, 0)]] # # p[p <= [gate]]=0 # p = (p > [gate]).astype(np.float32) # p = normalize(p, norm='l1', axis=1, copy=False) # return sp.csr_matrix(p * features) def model_name_modify(model_name, model_config): if model_config['smoothing'] == 'ap': model_name += '_' + 'ap_smoothing' + '_' + str(model_config['smooth_alpha']) if model_config['smoothing'] == 'ap_appro': model_name += '_' + 'ap_appro' + '_' + str(model_config['smooth_alpha']) elif model_config['smoothing'] == 'test21': model_name += '_' + 'test21' + '_' + str(model_config['smooth_alpha']) + '_' + str(model_config['beta']) elif model_config['smoothing'] == 'test21_norm': model_name += '_' + 'test21_norm' + '_' + str(model_config['smooth_alpha']) + '_' + str(model_config['beta']) elif model_config['smoothing'] == 'test27': model_name += '_' + 'test27' + '_' + str(model_config['smooth_alpha']) + '_' + str(model_config['beta']) elif model_config['smoothing'] == 'poly': model_name += '_' + 'poly_smoothing' for a in model_config['poly_parameters']: model_name += '_' + str(a) elif model_config['smoothing'] == 'taubin': model_name += '_taubin' + str(model_config['taubin_lambda']) \ + '_' + str(model_config['taubin_mu']) \ + '_' + str(model_config['taubin_repeat']) elif model_config['smoothing'] == 'sparse_encoding': model_name += '_sparse_encoding' elif model_config['smoothing'] is 'manifold_denoising': model_name += '_manifold_denoising' + '_' + str(model_config['smooth_alpha']) + '_' + str( model_config['md_repeat']) elif model_config['smoothing'] is None: pass else: raise ValueError('invalid smoothing') return model_name
[ "cupy.asfortranarray", "numpy.ceil", "scipy.sparse.diags", "scipy.sparse.eye", "hashlib.md5", "numpy.power", "cupy.cusparse.csrmm2", "cupy.sparse.csr_matrix", "scipy.sparse.issparse", "os.path.isfile", "numpy.zeros", "scipy.sparse.coo_matrix", "warnings.warn", "numpy.savez_compressed", "...
[((3907, 3945), 'cupy.sparse.csr_matrix', 'cp.sparse.csr_matrix', (['step_transformor'], {}), '(step_transformor)\n', (3927, 3945), True, 'import cupy as cp\n'), ((4173, 4198), 'scipy.sparse.issparse', 'sp.issparse', (['new_features'], {}), '(new_features)\n', (4184, 4198), True, 'import scipy.sparse as sp\n'), ((6097, 6118), 'scipy.sparse.issparse', 'sp.issparse', (['features'], {}), '(features)\n', (6108, 6118), True, 'import scipy.sparse as sp\n'), ((6546, 6555), 'scipy.sparse.eye', 'sp.eye', (['n'], {}), '(n)\n', (6552, 6555), True, 'import scipy.sparse as sp\n'), ((6961, 6986), 'scipy.sparse.issparse', 'sp.issparse', (['new_features'], {}), '(new_features)\n', (6972, 6986), True, 'import scipy.sparse as sp\n'), ((7065, 7090), 'cupy.sparse.csr_matrix', 'cp.sparse.csr_matrix', (['adj'], {}), '(adj)\n', (7085, 7090), True, 'import cupy as cp\n'), ((272, 362), 'warnings.warn', 'warnings.warn', (['"""cupy is not imported, some operations may not use GPU."""', 'ImportWarning'], {}), "('cupy is not imported, some operations may not use GPU.',\n ImportWarning)\n", (285, 362), False, 'import warnings\n'), ((484, 502), 'scipy.sparse.coo_matrix', 'sp.coo_matrix', (['adj'], {}), '(adj)\n', (497, 502), True, 'import scipy.sparse as sp\n'), ((813, 833), 'scipy.sparse.diags', 'sp.diags', (['d_inv_sqrt'], {}), '(d_inv_sqrt)\n', (821, 833), True, 'import scipy.sparse as sp\n'), ((4411, 4432), 'scipy.sparse.issparse', 'sp.issparse', (['features'], {}), '(features)\n', (4422, 4432), True, 'import scipy.sparse as sp\n'), ((4613, 4636), 'cupy.asfortranarray', 'cp.asfortranarray', (['tile'], {}), '(tile)\n', (4630, 4636), True, 'import cupy as cp\n'), ((4708, 4719), 'time.time', 'time.time', ([], {}), '()\n', (4717, 4719), False, 'import time\n'), ((5801, 5822), 'scipy.sparse.issparse', 'sp.issparse', (['features'], {}), '(features)\n', (5812, 5822), True, 'import scipy.sparse as sp\n'), ((5882, 5893), 'time.time', 'time.time', ([], {}), '()\n', (5891, 5893), False, 'import time\n'), ((7330, 7351), 'scipy.sparse.issparse', 'sp.issparse', (['features'], {}), '(features)\n', (7341, 7351), True, 'import scipy.sparse as sp\n'), ((7783, 7819), 'cupy.asfortranarray', 'cp.asfortranarray', (['new_features_tile'], {}), '(new_features_tile)\n', (7800, 7819), True, 'import cupy as cp\n'), ((7903, 7914), 'time.time', 'time.time', ([], {}), '()\n', (7912, 7914), False, 'import time\n'), ((8950, 8971), 'scipy.sparse.issparse', 'sp.issparse', (['features'], {}), '(features)\n', (8961, 8971), True, 'import scipy.sparse as sp\n'), ((9084, 9130), 'numpy.zeros', 'np.zeros', (['features.shape'], {'dtype': 'features.dtype'}), '(features.shape, dtype=features.dtype)\n', (9092, 9130), True, 'import numpy as np\n'), ((9147, 9158), 'time.time', 'time.time', ([], {}), '()\n', (9156, 9158), False, 'import time\n'), ((761, 781), 'numpy.isinf', 'np.isinf', (['d_inv_sqrt'], {}), '(d_inv_sqrt)\n', (769, 781), True, 'import numpy as np\n'), ((1079, 1094), 'scipy.sparse.diags', 'sp.diags', (['d_inv'], {}), '(d_inv)\n', (1087, 1094), True, 'import scipy.sparse as sp\n'), ((1626, 1650), 'hashlib.md5', 'hashlib.md5', (['fingerprint'], {}), '(fingerprint)\n', (1637, 1650), False, 'import hashlib\n'), ((2937, 2958), 'os.path.isfile', 'os.path.isfile', (['cache'], {}), '(cache)\n', (2951, 2958), False, 'import os\n'), ((3024, 3038), 'numpy.load', 'np.load', (['cache'], {}), '(cache)\n', (3031, 3038), True, 'import numpy as np\n'), ((4453, 4496), 'cupy.sparse.csr_matrix', 'cp.sparse.csr_matrix', (['features[:, low:high]'], {}), '(features[:, low:high])\n', (4473, 4496), True, 'import cupy as cp\n'), ((4564, 4597), 'cupy.asarray', 'cp.asarray', (['features[:, low:high]'], {}), '(features[:, low:high])\n', (4574, 4597), True, 'import cupy as cp\n'), ((4771, 4819), 'cupy.cusparse.csrmm2', 'cp.cusparse.csrmm2', (['step_transformor', 'tile', 'tile'], {}), '(step_transformor, tile, tile)\n', (4789, 4819), True, 'import cupy as cp\n'), ((4925, 4936), 'time.time', 'time.time', ([], {}), '()\n', (4934, 4936), False, 'import time\n'), ((5364, 5384), 'scipy.sparse.eye', 'sp.eye', (['adj.shape[0]'], {}), '(adj.shape[0])\n', (5370, 5384), True, 'import scipy.sparse as sp\n'), ((5407, 5416), 'scipy.sparse.eye', 'sp.eye', (['n'], {}), '(n)\n', (5413, 5416), True, 'import scipy.sparse as sp\n'), ((5456, 5465), 'scipy.sparse.eye', 'sp.eye', (['n'], {}), '(n)\n', (5462, 5465), True, 'import scipy.sparse as sp\n'), ((6003, 6014), 'time.time', 'time.time', ([], {}), '()\n', (6012, 6014), False, 'import time\n'), ((6361, 6381), 'scipy.sparse.eye', 'sp.eye', (['adj.shape[0]'], {}), '(adj.shape[0])\n', (6367, 6381), True, 'import scipy.sparse as sp\n'), ((6404, 6413), 'scipy.sparse.eye', 'sp.eye', (['n'], {}), '(n)\n', (6410, 6413), True, 'import scipy.sparse as sp\n'), ((6453, 6462), 'scipy.sparse.eye', 'sp.eye', (['n'], {}), '(n)\n', (6459, 6462), True, 'import scipy.sparse as sp\n'), ((7385, 7428), 'cupy.sparse.csr_matrix', 'cp.sparse.csr_matrix', (['features[:, low:high]'], {}), '(features[:, low:high])\n', (7405, 7428), True, 'import cupy as cp\n'), ((7457, 7500), 'cupy.sparse.csr_matrix', 'cp.sparse.csr_matrix', (['features[:, low:high]'], {}), '(features[:, low:high])\n', (7477, 7500), True, 'import cupy as cp\n'), ((7659, 7692), 'cupy.asarray', 'cp.asarray', (['features[:, low:high]'], {}), '(features[:, low:high])\n', (7669, 7692), True, 'import cupy as cp\n'), ((7721, 7754), 'cupy.asarray', 'cp.asarray', (['features[:, low:high]'], {}), '(features[:, low:high])\n', (7731, 7754), True, 'import cupy as cp\n'), ((8038, 8099), 'cupy.cusparse.csrmm2', 'cp.cusparse.csrmm2', (['adj', 'new_features_tile', 'new_features_tile'], {}), '(adj, new_features_tile, new_features_tile)\n', (8056, 8099), True, 'import cupy as cp\n'), ((8266, 8277), 'time.time', 'time.time', ([], {}), '()\n', (8275, 8277), False, 'import time\n'), ((9335, 9346), 'time.time', 'time.time', ([], {}), '()\n', (9344, 9346), False, 'import time\n'), ((709, 731), 'numpy.power', 'np.power', (['rowsum', '(-0.5)'], {}), '(rowsum, -0.5)\n', (717, 731), True, 'import numpy as np\n'), ((1037, 1052), 'numpy.isinf', 'np.isinf', (['d_inv'], {}), '(d_inv)\n', (1045, 1052), True, 'import numpy as np\n'), ((8710, 8730), 'scipy.sparse.eye', 'sp.eye', (['adj.shape[0]'], {}), '(adj.shape[0])\n', (8716, 8730), True, 'import scipy.sparse as sp\n'), ((990, 1012), 'numpy.power', 'np.power', (['rowsum', '(-1.0)'], {}), '(rowsum, -1.0)\n', (998, 1012), True, 'import numpy as np\n'), ((2446, 2487), 'numpy.ceil', 'np.ceil', (["(4 / model_config['smooth_alpha'])"], {}), "(4 / model_config['smooth_alpha'])\n", (2453, 2487), True, 'import numpy as np\n'), ((3502, 3557), 'numpy.savez_compressed', 'np.savez_compressed', (['cache', '*results'], {'multi_return': '(True)'}), '(cache, *results, multi_return=True)\n', (3521, 3557), True, 'import numpy as np\n'), ((3600, 3663), 'numpy.savez_compressed', 'np.savez_compressed', (['cache'], {'results': 'results', 'multi_return': '(False)'}), '(cache, results=results, multi_return=False)\n', (3619, 3663), True, 'import numpy as np\n')]
#!/usr/bin/env python3 import sys import argparse import logging import h5py import numpy as np import librosa import matplotlib.pyplot as plt def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('-i', '--input', type=str, required=True) parser.add_argument('-o', '--output', type=str, required=True) parser.add_argument('--n-basis', type=int, default=0) parser.add_argument('--with-deformation', action='store_true') parser.add_argument('-v', '--verbose', action='store_true') return parser.parse_args() def main(): args = parse_args() logging.getLogger().setLevel(10 if args.verbose else 20) logging.debug('loading sep info from {}'.format(args.input)) with h5py.File(args.input, 'r') as f: F = f['F'][()] D = f['D'][()] G = f['G'][()] H = f['H'][()] U = f['U'][()] Phase = f['Phase'][()] sr = f['sr'][()] n_fft = f['n_fft'][()] n_mel = f['n_mel'][()] f_min = f['f_min'][()] f_max = f['f_max'][()] channel = f['channel'][()] program = f['program'][()] note = f['note_list'][()] if 0 < args.n_basis < F.shape[1]: F = F[:, :args.n_basis] D = D[:, :args.n_basis] G = G[:args.n_basis, :] plt.imshow(F, origin='lower', aspect='auto') plt.xlabel('Note') plt.ylabel('Mel bin') plt.savefig('F.png', dpi=96) plt.imshow(D, origin='lower', aspect='auto') plt.xlabel('Note') plt.ylabel('Mel bin') plt.savefig('D.png', dpi=96) plt.imshow(G, origin='lower', aspect='auto') plt.xlabel('Time frame') plt.ylabel('Note') plt.savefig('G.png', dpi=96) plt.imshow(H, origin='lower', aspect='auto') plt.xlabel('Basis') plt.ylabel('Mel bin') plt.savefig('H.png', dpi=96) plt.imshow(U, origin='lower', aspect='auto') plt.xlabel('Time frame') plt.ylabel('Basis') plt.savefig('U.png', dpi=96) plt.imshow(F+D, origin='lower', aspect='auto') plt.xlabel('Note') plt.ylabel('Mel bin') plt.savefig('FD.png', dpi=96) plt.imshow(np.dot(F+D, G), origin='lower', aspect='auto') plt.xlabel('Time frame') plt.ylabel('Mel bin') plt.savefig('FDG.png', dpi=96) plt.imshow(np.dot(H, U), origin='lower', aspect='auto') plt.xlabel('Time frame') plt.ylabel('Mel bin') plt.savefig('HU.png', dpi=96) plt.imshow(np.dot(F+D, G)+np.dot(H, U), origin='lower', aspect='auto') plt.xlabel('Time frame') plt.ylabel('Mel bin') plt.savefig('R.png', dpi=96) if args.with_deformation: R = np.dot(F+D, G) else: R = np.dot(F, G) if n_mel > 0: mel_basis = librosa.filters.mel(sr, n_fft, n_mel, f_min, f_max) mel_basis_inv = np.linalg.pinv(mel_basis) R = np.dot(mel_basis_inv, R) x = librosa.istft(Phase * R) librosa.output.write_wav(args.output, x, sr) if __name__ == '__main__': main()
[ "matplotlib.pyplot.imshow", "librosa.istft", "logging.getLogger", "matplotlib.pyplot.savefig", "librosa.output.write_wav", "argparse.ArgumentParser", "matplotlib.pyplot.ylabel", "numpy.linalg.pinv", "matplotlib.pyplot.xlabel", "h5py.File", "numpy.dot", "librosa.filters.mel" ]
[((175, 200), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (198, 200), False, 'import argparse\n'), ((1297, 1341), 'matplotlib.pyplot.imshow', 'plt.imshow', (['F'], {'origin': '"""lower"""', 'aspect': '"""auto"""'}), "(F, origin='lower', aspect='auto')\n", (1307, 1341), True, 'import matplotlib.pyplot as plt\n'), ((1346, 1364), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Note"""'], {}), "('Note')\n", (1356, 1364), True, 'import matplotlib.pyplot as plt\n'), ((1369, 1390), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Mel bin"""'], {}), "('Mel bin')\n", (1379, 1390), True, 'import matplotlib.pyplot as plt\n'), ((1395, 1423), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""F.png"""'], {'dpi': '(96)'}), "('F.png', dpi=96)\n", (1406, 1423), True, 'import matplotlib.pyplot as plt\n'), ((1429, 1473), 'matplotlib.pyplot.imshow', 'plt.imshow', (['D'], {'origin': '"""lower"""', 'aspect': '"""auto"""'}), "(D, origin='lower', aspect='auto')\n", (1439, 1473), True, 'import matplotlib.pyplot as plt\n'), ((1478, 1496), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Note"""'], {}), "('Note')\n", (1488, 1496), True, 'import matplotlib.pyplot as plt\n'), ((1501, 1522), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Mel bin"""'], {}), "('Mel bin')\n", (1511, 1522), True, 'import matplotlib.pyplot as plt\n'), ((1527, 1555), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""D.png"""'], {'dpi': '(96)'}), "('D.png', dpi=96)\n", (1538, 1555), True, 'import matplotlib.pyplot as plt\n'), ((1561, 1605), 'matplotlib.pyplot.imshow', 'plt.imshow', (['G'], {'origin': '"""lower"""', 'aspect': '"""auto"""'}), "(G, origin='lower', aspect='auto')\n", (1571, 1605), True, 'import matplotlib.pyplot as plt\n'), ((1610, 1634), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Time frame"""'], {}), "('Time frame')\n", (1620, 1634), True, 'import matplotlib.pyplot as plt\n'), ((1639, 1657), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Note"""'], {}), "('Note')\n", (1649, 1657), True, 'import matplotlib.pyplot as plt\n'), ((1662, 1690), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""G.png"""'], {'dpi': '(96)'}), "('G.png', dpi=96)\n", (1673, 1690), True, 'import matplotlib.pyplot as plt\n'), ((1696, 1740), 'matplotlib.pyplot.imshow', 'plt.imshow', (['H'], {'origin': '"""lower"""', 'aspect': '"""auto"""'}), "(H, origin='lower', aspect='auto')\n", (1706, 1740), True, 'import matplotlib.pyplot as plt\n'), ((1745, 1764), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Basis"""'], {}), "('Basis')\n", (1755, 1764), True, 'import matplotlib.pyplot as plt\n'), ((1769, 1790), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Mel bin"""'], {}), "('Mel bin')\n", (1779, 1790), True, 'import matplotlib.pyplot as plt\n'), ((1795, 1823), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""H.png"""'], {'dpi': '(96)'}), "('H.png', dpi=96)\n", (1806, 1823), True, 'import matplotlib.pyplot as plt\n'), ((1829, 1873), 'matplotlib.pyplot.imshow', 'plt.imshow', (['U'], {'origin': '"""lower"""', 'aspect': '"""auto"""'}), "(U, origin='lower', aspect='auto')\n", (1839, 1873), True, 'import matplotlib.pyplot as plt\n'), ((1878, 1902), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Time frame"""'], {}), "('Time frame')\n", (1888, 1902), True, 'import matplotlib.pyplot as plt\n'), ((1907, 1926), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Basis"""'], {}), "('Basis')\n", (1917, 1926), True, 'import matplotlib.pyplot as plt\n'), ((1931, 1959), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""U.png"""'], {'dpi': '(96)'}), "('U.png', dpi=96)\n", (1942, 1959), True, 'import matplotlib.pyplot as plt\n'), ((1965, 2013), 'matplotlib.pyplot.imshow', 'plt.imshow', (['(F + D)'], {'origin': '"""lower"""', 'aspect': '"""auto"""'}), "(F + D, origin='lower', aspect='auto')\n", (1975, 2013), True, 'import matplotlib.pyplot as plt\n'), ((2016, 2034), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Note"""'], {}), "('Note')\n", (2026, 2034), True, 'import matplotlib.pyplot as plt\n'), ((2039, 2060), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Mel bin"""'], {}), "('Mel bin')\n", (2049, 2060), True, 'import matplotlib.pyplot as plt\n'), ((2065, 2094), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""FD.png"""'], {'dpi': '(96)'}), "('FD.png', dpi=96)\n", (2076, 2094), True, 'import matplotlib.pyplot as plt\n'), ((2162, 2186), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Time frame"""'], {}), "('Time frame')\n", (2172, 2186), True, 'import matplotlib.pyplot as plt\n'), ((2191, 2212), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Mel bin"""'], {}), "('Mel bin')\n", (2201, 2212), True, 'import matplotlib.pyplot as plt\n'), ((2217, 2247), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""FDG.png"""'], {'dpi': '(96)'}), "('FDG.png', dpi=96)\n", (2228, 2247), True, 'import matplotlib.pyplot as plt\n'), ((2313, 2337), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Time frame"""'], {}), "('Time frame')\n", (2323, 2337), True, 'import matplotlib.pyplot as plt\n'), ((2342, 2363), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Mel bin"""'], {}), "('Mel bin')\n", (2352, 2363), True, 'import matplotlib.pyplot as plt\n'), ((2368, 2397), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""HU.png"""'], {'dpi': '(96)'}), "('HU.png', dpi=96)\n", (2379, 2397), True, 'import matplotlib.pyplot as plt\n'), ((2478, 2502), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Time frame"""'], {}), "('Time frame')\n", (2488, 2502), True, 'import matplotlib.pyplot as plt\n'), ((2507, 2528), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Mel bin"""'], {}), "('Mel bin')\n", (2517, 2528), True, 'import matplotlib.pyplot as plt\n'), ((2533, 2561), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""R.png"""'], {'dpi': '(96)'}), "('R.png', dpi=96)\n", (2544, 2561), True, 'import matplotlib.pyplot as plt\n'), ((2840, 2864), 'librosa.istft', 'librosa.istft', (['(Phase * R)'], {}), '(Phase * R)\n', (2853, 2864), False, 'import librosa\n'), ((2869, 2913), 'librosa.output.write_wav', 'librosa.output.write_wav', (['args.output', 'x', 'sr'], {}), '(args.output, x, sr)\n', (2893, 2913), False, 'import librosa\n'), ((726, 752), 'h5py.File', 'h5py.File', (['args.input', '"""r"""'], {}), "(args.input, 'r')\n", (735, 752), False, 'import h5py\n'), ((2111, 2127), 'numpy.dot', 'np.dot', (['(F + D)', 'G'], {}), '(F + D, G)\n', (2117, 2127), True, 'import numpy as np\n'), ((2264, 2276), 'numpy.dot', 'np.dot', (['H', 'U'], {}), '(H, U)\n', (2270, 2276), True, 'import numpy as np\n'), ((2605, 2621), 'numpy.dot', 'np.dot', (['(F + D)', 'G'], {}), '(F + D, G)\n', (2611, 2621), True, 'import numpy as np\n'), ((2642, 2654), 'numpy.dot', 'np.dot', (['F', 'G'], {}), '(F, G)\n', (2648, 2654), True, 'import numpy as np\n'), ((2693, 2744), 'librosa.filters.mel', 'librosa.filters.mel', (['sr', 'n_fft', 'n_mel', 'f_min', 'f_max'], {}), '(sr, n_fft, n_mel, f_min, f_max)\n', (2712, 2744), False, 'import librosa\n'), ((2769, 2794), 'numpy.linalg.pinv', 'np.linalg.pinv', (['mel_basis'], {}), '(mel_basis)\n', (2783, 2794), True, 'import numpy as np\n'), ((2807, 2831), 'numpy.dot', 'np.dot', (['mel_basis_inv', 'R'], {}), '(mel_basis_inv, R)\n', (2813, 2831), True, 'import numpy as np\n'), ((595, 614), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (612, 614), False, 'import logging\n'), ((2414, 2430), 'numpy.dot', 'np.dot', (['(F + D)', 'G'], {}), '(F + D, G)\n', (2420, 2430), True, 'import numpy as np\n'), ((2429, 2441), 'numpy.dot', 'np.dot', (['H', 'U'], {}), '(H, U)\n', (2435, 2441), True, 'import numpy as np\n')]
import random import glob import os from cv2 import sort import random from graspnetAPI.grasp import RectGrasp import numpy as np from numpy.lib.type_check import imag import torch import torch.utils.data from graspnetAPI import GraspNet from utils.dataset_processing import grasp, image from detectron2.layers import nms_rotated class GraspNetDataBase(object): def __init__(self, file_path="/home/hilbertxu/dataset/graspnet/scenes", camera="realsense", random_crop=True) -> None: super().__init__() self.camera = camera self.random_crop = random_crop self.g = GraspNet('/home/hilbertxu/dataset/graspnet', camera=camera, split='train') self.output_size = 720 self.grasp_files = glob.glob(os.path.join(file_path, "*", camera, "rect","*.npy")) self.grasp_files = glob.glob(os.path.join(file_path, "*", camera, "rect","*.npy")) self.grasp_files.sort() self.length = len(self.grasp_files) if self.length == 0: raise FileNotFoundError('No dataset files found. Check path: {}'.format(file_path)) self.depth_files = [f.replace('.npy', '.png').replace('rect', 'depth') for f in self.grasp_files] self.rgb_files = [f.replace('.npy', '.png').replace('rect', 'rgb') for f in self.grasp_files] def _apply_nms(self, rects): center_x, center_y, open_x, open_y, height, scores, cls_ids = rects[:,0], rects[:,1], rects[:,2], rects[:,3], rects[:,4], rects[:,5], rects[:,6] # Calculate rotated bbox and apply NMS tmp = np.array([open_x - center_x, open_y - center_y]) width = (np.sqrt(np.sum(np.square(tmp), axis=0)) * 2).reshape(-1,1) center = np.array([center_x, center_y]) left = np.array([open_x, open_y]) axis = left - center normal = np.array([-axis[1], axis[0]]) # Calculate normal to determine the angle of bbox normal = normal / np.linalg.norm(normal) * height / 2 tan = normal[0] / normal[1] # angle: [-pi/2, pi/2] angle = np.arctan(tan) * 180.0 / 3.14159 r_box = np.concatenate([ center_x.reshape(-1,1), center_y.reshape(-1,1), width.reshape(-1,1), height.reshape(-1,1), angle.reshape(-1,1) ], axis=1) keep = nms_rotated(torch.from_numpy(r_box), torch.from_numpy(scores), 0.05).cpu().numpy() return keep def _load_from_graspnet_file(self, idx): grasp_file = self.grasp_files[idx] grasp_file_split = grasp_file.split('/') scene_id, ann_id = int(grasp_file_split[-4][-4:]), int(grasp_file_split[-1][:-4]) rect_grasp_group = self.g.loadGrasp(sceneId=scene_id, camera=self.camera, annId=ann_id, fric_coef_thresh=0.2, format='rect') rects = rect_grasp_group.rect_grasp_group_array keep = self._apply_nms(rect_grasp_group.rect_grasp_group_array) grs = [] # print("normal", normal) for i in list(keep): center_x, center_y, open_x, open_y, height, score, object_id = rects[i,:] center = np.array([center_x, center_y]) left = np.array([open_x, open_y]) axis = left - center normal = np.array([-axis[1], axis[0]]) normal = normal / np.linalg.norm(normal) * height / 2 p1 = center + normal + axis p2 = center + normal - axis p3 = center - normal - axis p4 = center - normal + axis gr = np.array([ (int(p1[1]), int(p1[0])), (int(p2[1]), int(p2[0])), (int(p3[1]), int(p3[0])), (int(p4[1]), int(p4[0])) ]) grs.append(grasp.GraspRectangle(gr)) return grasp.GraspRectangles(grs) def _mask_bb_out_of_range(self, gtbbs, crop_range=None): print(crop_range) keep = [] for gr in gtbbs.grs: points = gr.points if ((points[:,0] <= crop_range[1][0]).all() and (points[:,0] >= crop_range[0][0]).all()) & ((points[:,1] <=crop_range[1][1]).all() and (points[:,1] >= crop_range[0][1]).all()): keep.append(gr) return grasp.GraspRectangles(keep) def _get_crop_attrs(self, idx): gtbbs = self._load_from_graspnet_file(idx) center = gtbbs.center left = max(0, min(center[1] - self.output_size // 2, 1280 - self.output_size)) top = max(0, min(center[0] - self.output_size // 2, 720 - self.output_size)) return center, left, top def get_gtbb(self, idx, rot=0, zoom=1.0): gtbbs = self._load_from_graspnet_file(idx) center, left, top = self._get_crop_attrs(idx) crop_range = [(0, 0), (720, 720)] gtbbs.rotate(rot, center) gtbbs.offset((-top, -left)) gtbbs.zoom(zoom, (self.output_size // 2, self.output_size // 2)) masked_gtbbs = self._mask_bb_out_of_range(gtbbs, crop_range) return masked_gtbbs def get_rgb(self, idx, rot=0, zoom=1.0, normalise=True): rgb_file = self.rgb_files[idx] rgb_file_split = rgb_file.split('/') scene_id, ann_id = int(rgb_file_split[-4][-4:]), int(rgb_file_split[-1][:-4]) rgb = self.g.loadRGB(sceneId=scene_id, camera=self.camera, annId=ann_id) print(rgb.shape) rgb_img = image.Image(rgb) center, left, top = self._get_crop_attrs(idx) rgb_img.rotate(rot, center) rgb_img.crop((top, left), (min(720, top + self.output_size), min(1280, left + self.output_size))) rgb_img.zoom(zoom) rgb_img.resize((self.output_size, self.output_size)) if normalise: rgb_img.normalise() rgb_img.img = rgb_img.img.transpose((2, 0, 1)) return rgb_img.img def get_depth(self, idx, rot=0, zoom=1.0): depth_file = self.depth_files[idx] depth_file_split = depth_file.split('/') scene_id, ann_id = int(depth_file_split[-4][-4:]), int(depth_file_split[-1][:-4]) depth = self.g.loadDepth(sceneId=scene_id, camera=self.camera, annId=ann_id) depth_img = image.DepthImage(depth) center, left, top = self._get_crop_attrs(idx) depth_img.rotate(rot, center) depth_img.crop((top, left), (min(480, top + self.output_size), min(640, left + self.output_size))) depth_img.normalise() depth_img.zoom(zoom) depth_img.resize((self.output_size, self.output_size)) return depth_img.img if __name__ == "__main__": import matplotlib.pyplot as plt dataset = GraspNetDataBase() gtbb = dataset.get_gtbb(0) rgb = dataset.get_rgb(0, normalise=False) depth = dataset.get_depth(0) fig, ax = plt.subplots(figsize=(7,7)) ax.imshow(rgb) gtbb.show(ax=ax) plt.show() # file_path="/home/hilbertxu/dataset/graspnet/scenes" # camera="realsense" # grasp_files = glob.glob(os.path.join(file_path, "*", camera, "rect","*.npy")) # grasp_files.sort() # print(grasp_files) # depth_files = [f.replace('.npy', '.png').replace('rect', 'depth') for f in grasp_files] # rgb_files = [f.replace('.npy', '.png').replace('rect', 'rgb') for f in grasp_files] # print(len(grasp_files)) # print(len(depth_files)) # print(len(rgb_files)) # # Grasp: [Center-x, center-y, open-x, open-y, height, score, class_id] # import cv2 # from graspnetAPI import GraspNet # import math # g = GraspNet('/home/hilbertxu/dataset/graspnet', camera=camera, split='train') # print(grasp_files[0]) # # g.showSceneGrasp(sceneId=0, camera=camera, annId=0, format='rect', class_wise_topk_k=3, threshold=0.5) # # a = "/home/hilbertxu/dataset/graspnet/scenes/scene_0090/realsense/rect/0101.npy" # # print(a.split("/")) # # a_split = a.split('/') # # print(a_split[-4][-4:]) # # print(a_split[-1][:-4]) # # scene_id, ann_id = int(a_split[-4][-4:]), int(a_split[-1][:-4]) # # print(scene_id, ann_id) # # rects = np.load(grasp_files[0]) # # scores = rects[:, 5] # # print(np.sort(scores)) # # print(scores.shape) # # sort_idx = np.argsort(scores) # # print(sort_idx) # # rects = rects[sort_idx,:] # # bgr = cv2.imread(grasp_files[0]) # # print(rects.shape) # bgr = g.loadBGR(sceneId=0, camera=camera, annId=0) # # _6d_grasp_group = g.loadGrasp(sceneId=0, camera=camera, annId=0, fric_coef_thresh=0.2, format='6d') # # nms_grasp = _6d_grasp_group.nms(translation_thresh=0.1, rotation_thresh= 30 / 180.0 * 3.1416) # # nms_rect_group = nms_grasp.to_rect_grasp_group(camera) # rect_grasp_group = g.loadGrasp(sceneId=0, camera=camera, annId=0, fric_coef_thresh=0.2, format='rect') # # print(nms_rect_group.rect_grasp_group_array) # _rect_grasps = rect_grasp_group.rect_grasp_group_array # print(_rect_grasps.shape) # center_x, center_y, open_x, open_y, height = _rect_grasps[:, 0], _rect_grasps[:, 1], _rect_grasps[:, 2], _rect_grasps[:,3], _rect_grasps[:,4] # tmp = np.array([open_x - center_x, open_y - center_y]) # width = (np.sqrt(np.sum(np.square(tmp), axis=0)) * 2).reshape(-1,1) # print(width.shape) # # print(width) # print(center_x.reshape(-1,1).shape) # box = np.concatenate([center_x.reshape(-1,1), center_y.reshape(-1,1), width.reshape(-1,1), height.reshape(-1,1)], axis=1) # center = np.array([center_x, center_y]) # left = np.array([open_x, open_y]) # axis = left - center # normal = np.array([-axis[1], axis[0]]) # normal = normal / np.linalg.norm(normal) * height / 2 # tan = normal[0] / normal[1] # angle = np.arctan(tan) * 180.0 / 3.14159 # r_box = np.concatenate([box, angle.reshape(-1,1)], axis=1) # print(r_box.shape) # scores = _rect_grasps[:,5] # from detectron2.layers import nms_rotated # keep = nms_rotated(torch.from_numpy(r_box), torch.from_numpy(scores), 0.05).cpu().numpy() # print(keep.shape, keep) # rect_grasp_group.rect_grasp_group_array = rect_grasp_group.rect_grasp_group_array[keep, :] # img = rect_grasp_group.to_opencv_image(bgr) # # # # cv2.circle(bgr, (int(center_x), int(center_y)), 3, (255,255,255), 4) # # cv2.circle(bgr, (int(open_x), int(open_y)), 3, (0, 255, 0), 4) # # center = np.array([center_x, center_y]) # # left = np.array([open_x, open_y]) # # axis = left - center # # print(axis) # # normal = np.array([-axis[1], axis[0]]) # # print(normal) # # normal = normal / np.linalg.norm(normal) * height / 2 # # print(height, normal) # # img = nms_rect_group.to_opencv_image(bgr) # cv2.imshow('rect grasps', img) # cv2.waitKey(0) # cv2.destroyAllWindows()
[ "utils.dataset_processing.grasp.GraspRectangles", "utils.dataset_processing.grasp.GraspRectangle", "utils.dataset_processing.image.DepthImage", "os.path.join", "graspnetAPI.GraspNet", "numpy.square", "torch.from_numpy", "numpy.array", "utils.dataset_processing.image.Image", "numpy.arctan", "nump...
[((6803, 6831), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(7, 7)'}), '(figsize=(7, 7))\n', (6815, 6831), True, 'import matplotlib.pyplot as plt\n'), ((6877, 6887), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6885, 6887), True, 'import matplotlib.pyplot as plt\n'), ((602, 676), 'graspnetAPI.GraspNet', 'GraspNet', (['"""/home/hilbertxu/dataset/graspnet"""'], {'camera': 'camera', 'split': '"""train"""'}), "('/home/hilbertxu/dataset/graspnet', camera=camera, split='train')\n", (610, 676), False, 'from graspnetAPI import GraspNet\n'), ((1590, 1638), 'numpy.array', 'np.array', (['[open_x - center_x, open_y - center_y]'], {}), '([open_x - center_x, open_y - center_y])\n', (1598, 1638), True, 'import numpy as np\n'), ((1733, 1763), 'numpy.array', 'np.array', (['[center_x, center_y]'], {}), '([center_x, center_y])\n', (1741, 1763), True, 'import numpy as np\n'), ((1779, 1805), 'numpy.array', 'np.array', (['[open_x, open_y]'], {}), '([open_x, open_y])\n', (1787, 1805), True, 'import numpy as np\n'), ((1852, 1881), 'numpy.array', 'np.array', (['[-axis[1], axis[0]]'], {}), '([-axis[1], axis[0]])\n', (1860, 1881), True, 'import numpy as np\n'), ((3812, 3838), 'utils.dataset_processing.grasp.GraspRectangles', 'grasp.GraspRectangles', (['grs'], {}), '(grs)\n', (3833, 3838), False, 'from utils.dataset_processing import grasp, image\n'), ((4255, 4282), 'utils.dataset_processing.grasp.GraspRectangles', 'grasp.GraspRectangles', (['keep'], {}), '(keep)\n', (4276, 4282), False, 'from utils.dataset_processing import grasp, image\n'), ((5414, 5430), 'utils.dataset_processing.image.Image', 'image.Image', (['rgb'], {}), '(rgb)\n', (5425, 5430), False, 'from utils.dataset_processing import grasp, image\n'), ((6192, 6215), 'utils.dataset_processing.image.DepthImage', 'image.DepthImage', (['depth'], {}), '(depth)\n', (6208, 6215), False, 'from utils.dataset_processing import grasp, image\n'), ((755, 808), 'os.path.join', 'os.path.join', (['file_path', '"""*"""', 'camera', '"""rect"""', '"""*.npy"""'], {}), "(file_path, '*', camera, 'rect', '*.npy')\n", (767, 808), False, 'import os\n'), ((846, 899), 'os.path.join', 'os.path.join', (['file_path', '"""*"""', 'camera', '"""rect"""', '"""*.npy"""'], {}), "(file_path, '*', camera, 'rect', '*.npy')\n", (858, 899), False, 'import os\n'), ((3140, 3170), 'numpy.array', 'np.array', (['[center_x, center_y]'], {}), '([center_x, center_y])\n', (3148, 3170), True, 'import numpy as np\n'), ((3190, 3216), 'numpy.array', 'np.array', (['[open_x, open_y]'], {}), '([open_x, open_y])\n', (3198, 3216), True, 'import numpy as np\n'), ((3271, 3300), 'numpy.array', 'np.array', (['[-axis[1], axis[0]]'], {}), '([-axis[1], axis[0]])\n', (3279, 3300), True, 'import numpy as np\n'), ((2085, 2099), 'numpy.arctan', 'np.arctan', (['tan'], {}), '(tan)\n', (2094, 2099), True, 'import numpy as np\n'), ((3762, 3786), 'utils.dataset_processing.grasp.GraspRectangle', 'grasp.GraspRectangle', (['gr'], {}), '(gr)\n', (3782, 3786), False, 'from utils.dataset_processing import grasp, image\n'), ((1966, 1988), 'numpy.linalg.norm', 'np.linalg.norm', (['normal'], {}), '(normal)\n', (1980, 1988), True, 'import numpy as np\n'), ((3331, 3353), 'numpy.linalg.norm', 'np.linalg.norm', (['normal'], {}), '(normal)\n', (3345, 3353), True, 'import numpy as np\n'), ((1671, 1685), 'numpy.square', 'np.square', (['tmp'], {}), '(tmp)\n', (1680, 1685), True, 'import numpy as np\n'), ((2347, 2370), 'torch.from_numpy', 'torch.from_numpy', (['r_box'], {}), '(r_box)\n', (2363, 2370), False, 'import torch\n'), ((2372, 2396), 'torch.from_numpy', 'torch.from_numpy', (['scores'], {}), '(scores)\n', (2388, 2396), False, 'import torch\n')]
import sys, os, plotly import numpy as np script_path = os.path.realpath(__file__) script_dir = os.path.split(script_path)[0] sys.path.insert(0, '%s/../python' % script_dir) from vaxxer.models import VaxxerClassifier from vaxxer.utils import show_dynamic_auc from sklearn.metrics import roc_auc_score prepared_data_dir = "%s/../data/covid_vaxxer_representations/" % script_dir classifier = VaxxerClassifier("tfidf", "Vax-skeptic", True) config = {"model":"newton-cg"} def load_and_evaluate(use_text, use_history, use_network): X_train, X_test = classifier.load(prepared_data_dir, use_text=use_text, use_history=use_history, use_network=use_network) model, tr_pred, te_pred = classifier.fit_vaxxer_classifier(X_train, X_test, config) auc_score = roc_auc_score(te_pred["label"], te_pred["proba"]) return X_train, auc_score def test_text_representation(): X_train, auc_score = load_and_evaluate(True, False, False) assert X_train.shape[1] == 1000 assert np.abs(0.8385-auc_score) < 0.0001 def test_text_history_representation(): X_train, auc_score = load_and_evaluate(True, True, False) assert X_train.shape[1] == 1004 assert np.abs(0.8743-auc_score) < 0.0001 def test_text_network_representation(): X_train, auc_score = load_and_evaluate(True, False, True) assert X_train.shape[1] == 1128 assert np.abs(0.9024-auc_score) < 0.0001 def test_text_history_network_representation(): X_train, auc_score = load_and_evaluate(True, True, True) assert X_train.shape[1] == 1132 assert np.abs(0.9110-auc_score) < 0.0001 def test_dynamic_auc(): configs = { "text":(True, False, False), "text+history":(True, True, False), "text+embedding":(True, False, True), "text+embedding+history":(True, True, True) } predictions = [] for key, config in configs.items(): text, history, network = config X_tr, X_te = classifier.load(prepared_data_dir, use_text=text, use_history=history, use_network=network) clf, tr_pred, te_pred = classifier.fit_vaxxer_classifier(X_tr, X_te, {"model":"newton-cg"}) te_pred["experiment_id"] = key predictions.append(te_pred) print(key, "AUC:", roc_auc_score(te_pred["label"], te_pred["proba"])) print() badrate = te_pred.groupby("date")["label"].mean() time_window = 7*86400 fig = show_dynamic_auc(configs, predictions, badrate, time_window) assert isinstance(fig, plotly.graph_objs._figure.Figure)
[ "numpy.abs", "vaxxer.models.VaxxerClassifier", "sys.path.insert", "sklearn.metrics.roc_auc_score", "os.path.realpath", "os.path.split", "vaxxer.utils.show_dynamic_auc" ]
[((56, 82), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (72, 82), False, 'import sys, os, plotly\n'), ((126, 173), 'sys.path.insert', 'sys.path.insert', (['(0)', "('%s/../python' % script_dir)"], {}), "(0, '%s/../python' % script_dir)\n", (141, 173), False, 'import sys, os, plotly\n'), ((391, 437), 'vaxxer.models.VaxxerClassifier', 'VaxxerClassifier', (['"""tfidf"""', '"""Vax-skeptic"""', '(True)'], {}), "('tfidf', 'Vax-skeptic', True)\n", (407, 437), False, 'from vaxxer.models import VaxxerClassifier\n'), ((96, 122), 'os.path.split', 'os.path.split', (['script_path'], {}), '(script_path)\n', (109, 122), False, 'import sys, os, plotly\n'), ((759, 808), 'sklearn.metrics.roc_auc_score', 'roc_auc_score', (["te_pred['label']", "te_pred['proba']"], {}), "(te_pred['label'], te_pred['proba'])\n", (772, 808), False, 'from sklearn.metrics import roc_auc_score\n'), ((2386, 2446), 'vaxxer.utils.show_dynamic_auc', 'show_dynamic_auc', (['configs', 'predictions', 'badrate', 'time_window'], {}), '(configs, predictions, badrate, time_window)\n', (2402, 2446), False, 'from vaxxer.utils import show_dynamic_auc\n'), ((982, 1008), 'numpy.abs', 'np.abs', (['(0.8385 - auc_score)'], {}), '(0.8385 - auc_score)\n', (988, 1008), True, 'import numpy as np\n'), ((1170, 1196), 'numpy.abs', 'np.abs', (['(0.8743 - auc_score)'], {}), '(0.8743 - auc_score)\n', (1176, 1196), True, 'import numpy as np\n'), ((1354, 1380), 'numpy.abs', 'np.abs', (['(0.9024 - auc_score)'], {}), '(0.9024 - auc_score)\n', (1360, 1380), True, 'import numpy as np\n'), ((1549, 1574), 'numpy.abs', 'np.abs', (['(0.911 - auc_score)'], {}), '(0.911 - auc_score)\n', (1555, 1574), True, 'import numpy as np\n'), ((2229, 2278), 'sklearn.metrics.roc_auc_score', 'roc_auc_score', (["te_pred['label']", "te_pred['proba']"], {}), "(te_pred['label'], te_pred['proba'])\n", (2242, 2278), False, 'from sklearn.metrics import roc_auc_score\n')]
import os import sys import argparse import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split,StratifiedShuffleSplit import click import logging from pathlib import Path from dotenv import find_dotenv, load_dotenv import yaml import pickle from sklearn.impute import SimpleImputer from sklearn.preprocessing import OrdinalEncoder,OneHotEncoder,StandardScaler from sklearn.base import BaseEstimator, TransformerMixin from sklearn.pipeline import Pipeline from sklearn.compose import ColumnTransformer def data_feat(config_path): config = read_params(config_path) vis_config = config["vis_data"] train_data_path = config["split_data"]["train_path"] prep_data_path = config["prepro_data"]["prepro_train"] pipeline_path = config["prepro_data"]["pipeline_path"] df = pd.read_csv(train_data_path, sep=",") df = df.drop('median_house_value',axis=1) sys.stderr.write(f'The input data frame size is {df.shape}\n') housing_num = df.drop('ocean_proximity', axis=1) housing_cat = df[['ocean_proximity']] num_pipeline = Pipeline([ ('imputer', SimpleImputer(strategy='median')), ('std_scaler', StandardScaler()) ]) num_attribs = list(housing_num) cat_attribs = ['ocean_proximity'] full_pipeline = ColumnTransformer([ ('num', num_pipeline, num_attribs), ('cat', OneHotEncoder(), cat_attribs) ]) housing_prepared = full_pipeline.fit_transform(df) sys.stderr.write(f'The processed data frame size is {housing_prepared.shape}\n') with open(pipeline_path, 'wb') as fd: pickle.dump(full_pipeline, fd) np.save(prep_data_path,housing_prepared) # sys.stderr.write(f'The processed data frame size is {housing_prepared.shape}\n') def read_params(config_path): with open(config_path) as yaml_file: config = yaml.safe_load(yaml_file) return config if __name__=="__main__": args = argparse.ArgumentParser() args.add_argument("--config", default="params.yaml") parsed_args = args.parse_args() data_feat(config_path=parsed_args.config)
[ "pickle.dump", "argparse.ArgumentParser", "pandas.read_csv", "sklearn.preprocessing.OneHotEncoder", "sklearn.preprocessing.StandardScaler", "sys.stderr.write", "yaml.safe_load", "sklearn.impute.SimpleImputer", "numpy.save" ]
[((859, 896), 'pandas.read_csv', 'pd.read_csv', (['train_data_path'], {'sep': '""","""'}), "(train_data_path, sep=',')\n", (870, 896), True, 'import pandas as pd\n'), ((947, 1010), 'sys.stderr.write', 'sys.stderr.write', (['f"""The input data frame size is {df.shape}\n"""'], {}), "(f'The input data frame size is {df.shape}\\n')\n", (963, 1010), False, 'import sys\n'), ((1515, 1601), 'sys.stderr.write', 'sys.stderr.write', (['f"""The processed data frame size is {housing_prepared.shape}\n"""'], {}), "(\n f'The processed data frame size is {housing_prepared.shape}\\n')\n", (1531, 1601), False, 'import sys\n'), ((1682, 1723), 'numpy.save', 'np.save', (['prep_data_path', 'housing_prepared'], {}), '(prep_data_path, housing_prepared)\n', (1689, 1723), True, 'import numpy as np\n'), ((1986, 2011), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (2009, 2011), False, 'import argparse\n'), ((1647, 1677), 'pickle.dump', 'pickle.dump', (['full_pipeline', 'fd'], {}), '(full_pipeline, fd)\n', (1658, 1677), False, 'import pickle\n'), ((1903, 1928), 'yaml.safe_load', 'yaml.safe_load', (['yaml_file'], {}), '(yaml_file)\n', (1917, 1928), False, 'import yaml\n'), ((1160, 1192), 'sklearn.impute.SimpleImputer', 'SimpleImputer', ([], {'strategy': '"""median"""'}), "(strategy='median')\n", (1173, 1192), False, 'from sklearn.impute import SimpleImputer\n'), ((1218, 1234), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (1232, 1234), False, 'from sklearn.preprocessing import OrdinalEncoder, OneHotEncoder, StandardScaler\n'), ((1419, 1434), 'sklearn.preprocessing.OneHotEncoder', 'OneHotEncoder', ([], {}), '()\n', (1432, 1434), False, 'from sklearn.preprocessing import OrdinalEncoder, OneHotEncoder, StandardScaler\n')]
''' ______ _ ______ _ | ___ \ | | | ___| | | | |_/ /__ _ _ __ __| | ___ _ __ ___ | |_ ___ _ __ ___ ___| |_ | // _` | '_ \ / _` |/ _ \| '_ ` _ \| _/ _ \| '__/ _ \/ __| __| | |\ \ (_| | | | | (_| | (_) | | | | | | || (_) | | | __/\__ \ |_ \_| \_\__,_|_| |_|\__,_|\___/|_| |_| |_\_| \___/|_| \___||___/\__| ''' import numpy as np from scipy import stats import random from sklearn.tree import DecisionTreeClassifier class RandomForest: def __init__(self, num_features, num_trees, max_depth=None): if num_features<1 or num_trees<1: raise ValueError self.num_features = num_features self.num_trees = num_trees self.max_depth = max_depth def fit(self, X, r): trees = [] #number of bootstrapped datasets for dataset in range(self.num_trees): dtc = DecisionTreeClassifier(criterion='entropy', random_state=0, max_depth=self.max_depth, max_features=self.num_features) dataset_X = np.zeros( X.shape[1] , dtype=int ) dataset_r = [0] #number of elements in each dataset for element in range(X.shape[0]): #random element from X,r idx = random.randint(0, X.shape[0]-1) #add random datapoint dataset_X = np.vstack( (dataset_X,X[idx]) ) #add random datapoint's class dataset_r.append(r[idx]) trees.append( dtc.fit(dataset_X[1:], dataset_r[1:]) ) self.trees = trees return trees def predict(self,X): r_pred = [] for k in range(self.num_trees): # make predictions based on the first k tree classifiers class_preds = np.zeros( X.shape[0], dtype=int ) for clf in range(k+1): class_preds = np.vstack( (class_preds , self.trees[clf].predict( X )) ) modes,counts = stats.mode(class_preds,axis=0) r_pred.append( modes ) return r_pred
[ "scipy.stats.mode", "sklearn.tree.DecisionTreeClassifier", "numpy.zeros", "numpy.vstack", "random.randint" ]
[((1079, 1201), 'sklearn.tree.DecisionTreeClassifier', 'DecisionTreeClassifier', ([], {'criterion': '"""entropy"""', 'random_state': '(0)', 'max_depth': 'self.max_depth', 'max_features': 'self.num_features'}), "(criterion='entropy', random_state=0, max_depth=self.\n max_depth, max_features=self.num_features)\n", (1101, 1201), False, 'from sklearn.tree import DecisionTreeClassifier\n'), ((1370, 1401), 'numpy.zeros', 'np.zeros', (['X.shape[1]'], {'dtype': 'int'}), '(X.shape[1], dtype=int)\n', (1378, 1401), True, 'import numpy as np\n'), ((2149, 2180), 'numpy.zeros', 'np.zeros', (['X.shape[0]'], {'dtype': 'int'}), '(X.shape[0], dtype=int)\n', (2157, 2180), True, 'import numpy as np\n'), ((2334, 2365), 'scipy.stats.mode', 'stats.mode', (['class_preds'], {'axis': '(0)'}), '(class_preds, axis=0)\n', (2344, 2365), False, 'from scipy import stats\n'), ((1594, 1627), 'random.randint', 'random.randint', (['(0)', '(X.shape[0] - 1)'], {}), '(0, X.shape[0] - 1)\n', (1608, 1627), False, 'import random\n'), ((1701, 1731), 'numpy.vstack', 'np.vstack', (['(dataset_X, X[idx])'], {}), '((dataset_X, X[idx]))\n', (1710, 1731), True, 'import numpy as np\n')]
import numpy as np import matplotlib.pyplot as plt from scipy.optimize import minimize, shgo import matplotlib.animation as animation def convex_function(x): return np.sum(np.array(x)**2, axis=0) def order_vertices(f, vertices): N = vertices.shape[0] f_evals = np.array([f(vertices[i]) for i in range(N)]) ind = np.argsort(f_evals) return vertices[ind], f_evals[ind] def nm_line(t, centroid, worst): return centroid + t * (worst - centroid) def centroid(vertices): x = vertices[0] for i in range(1, vertices.shape[0]-1): x += vertices[i] return x/(vertices.shape[0]-1) def nelder_mead(f, x0, tol=1e-5, max_iter=1000): n = len(x0) # MATLAB fminsearch initialisation routine vertices = np.empty([n+1, n], dtype=x0.dtype) vertices[0, :] = x0 for i in range(1, n+1): vertices[i, :] = x0 if x0[i-1] == 0: vertices[i, i-1] += 0.00025 else: vertices[i, i-1] += 0.05 saved_vertices = np.empty([n+1, n, max_iter], dtype=x0.dtype) # Nelder–Mead algorithm from: # Numerical optimization # by <NAME>; <NAME>., 1960-, # Chapter 9 for step in range(max_iter): vertices, f_evals = order_vertices(f, vertices) saved_vertices[:, :, step] = vertices if np.std(f_evals) < tol: break cent = centroid(vertices) reflect = nm_line(-1, cent, vertices[-1]) f_reflect = f(reflect) if f_evals[0] <= f_reflect and f_reflect < f_evals[-2]: vertices[-1] = reflect elif f_reflect < f_evals[0]: expansion = nm_line(-2, cent, vertices[-1]) f_expansion = f(expansion) if f_expansion < f_reflect: vertices[-1] = expansion else: vertices[-1] = reflect elif f_reflect >= f_evals[-2]: contraction_successful = False if f_evals[-2] <= f_reflect and f_reflect < f_evals[-1]: out_contract = nm_line(-0.5, cent, vertices[-1]) f_out_contract = f(out_contract) if f_out_contract <= f_reflect: vertices[-1] = out_contract contraction_successful = True else: in_contract = nm_line(0.5, cent, vertices[-1]) f_in_contract = f(in_contract) if f_in_contract <= f_reflect: vertices[-1] = in_contract contraction_successful = True if not contraction_successful: for i in range(1, n+1): vertices[i] = 0.5*(vertices[0] + vertices[i]) return saved_vertices[:, :, 0:step+1] if __name__ == '__main__': for f in [convex_function]: x0 = np.array([1.0, 1.0]) x_min = np.array([-1.0, -1.0]) x_max = np.array([1.0, 1.0]) saved_vertices = nelder_mead(f, x0) print('Complete after', saved_vertices.shape[2], 'iterations') nx, ny = (100, 100) x = np.linspace(x_min[0], x_max[0], nx) y = np.linspace(x_min[1], x_max[1], ny) xv, yv = np.meshgrid(x, y) eval_f = f([xv, yv]) fig, ax = plt.subplots() c = plt.contourf(x, y, eval_f) ln, = plt.plot( np.append( saved_vertices[:, 0, 0], saved_vertices[0, 0, 0] ), np.append( saved_vertices[:, 1, 0], saved_vertices[0, 1, 0] ) ) def init(): ax.set_xlim(x_min[0], x_max[0]) ax.set_ylim(x_min[1], x_max[1]) return ln, def update(i): ln.set_data( np.append( saved_vertices[:, 0, i], saved_vertices[0, 0, i] ), np.append( saved_vertices[:, 1, i], saved_vertices[0, 1, i] ) ) return ln, ani = animation.FuncAnimation( fig, update, range(1, saved_vertices.shape[2]), init_func=init, blit=True ) plt.show()
[ "matplotlib.pyplot.contourf", "numpy.argsort", "numpy.array", "numpy.linspace", "numpy.append", "numpy.empty", "numpy.std", "numpy.meshgrid", "matplotlib.pyplot.subplots", "matplotlib.pyplot.show" ]
[((332, 351), 'numpy.argsort', 'np.argsort', (['f_evals'], {}), '(f_evals)\n', (342, 351), True, 'import numpy as np\n'), ((751, 787), 'numpy.empty', 'np.empty', (['[n + 1, n]'], {'dtype': 'x0.dtype'}), '([n + 1, n], dtype=x0.dtype)\n', (759, 787), True, 'import numpy as np\n'), ((1004, 1050), 'numpy.empty', 'np.empty', (['[n + 1, n, max_iter]'], {'dtype': 'x0.dtype'}), '([n + 1, n, max_iter], dtype=x0.dtype)\n', (1012, 1050), True, 'import numpy as np\n'), ((2790, 2810), 'numpy.array', 'np.array', (['[1.0, 1.0]'], {}), '([1.0, 1.0])\n', (2798, 2810), True, 'import numpy as np\n'), ((2827, 2849), 'numpy.array', 'np.array', (['[-1.0, -1.0]'], {}), '([-1.0, -1.0])\n', (2835, 2849), True, 'import numpy as np\n'), ((2866, 2886), 'numpy.array', 'np.array', (['[1.0, 1.0]'], {}), '([1.0, 1.0])\n', (2874, 2886), True, 'import numpy as np\n'), ((3044, 3079), 'numpy.linspace', 'np.linspace', (['x_min[0]', 'x_max[0]', 'nx'], {}), '(x_min[0], x_max[0], nx)\n', (3055, 3079), True, 'import numpy as np\n'), ((3092, 3127), 'numpy.linspace', 'np.linspace', (['x_min[1]', 'x_max[1]', 'ny'], {}), '(x_min[1], x_max[1], ny)\n', (3103, 3127), True, 'import numpy as np\n'), ((3145, 3162), 'numpy.meshgrid', 'np.meshgrid', (['x', 'y'], {}), '(x, y)\n', (3156, 3162), True, 'import numpy as np\n'), ((3210, 3224), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (3222, 3224), True, 'import matplotlib.pyplot as plt\n'), ((3237, 3263), 'matplotlib.pyplot.contourf', 'plt.contourf', (['x', 'y', 'eval_f'], {}), '(x, y, eval_f)\n', (3249, 3263), True, 'import matplotlib.pyplot as plt\n'), ((4191, 4201), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4199, 4201), True, 'import matplotlib.pyplot as plt\n'), ((178, 189), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (186, 189), True, 'import numpy as np\n'), ((1316, 1331), 'numpy.std', 'np.std', (['f_evals'], {}), '(f_evals)\n', (1322, 1331), True, 'import numpy as np\n'), ((3301, 3360), 'numpy.append', 'np.append', (['saved_vertices[:, 0, 0]', 'saved_vertices[0, 0, 0]'], {}), '(saved_vertices[:, 0, 0], saved_vertices[0, 0, 0])\n', (3310, 3360), True, 'import numpy as np\n'), ((3420, 3479), 'numpy.append', 'np.append', (['saved_vertices[:, 1, 0]', 'saved_vertices[0, 1, 0]'], {}), '(saved_vertices[:, 1, 0], saved_vertices[0, 1, 0])\n', (3429, 3479), True, 'import numpy as np\n'), ((3733, 3792), 'numpy.append', 'np.append', (['saved_vertices[:, 0, i]', 'saved_vertices[0, 0, i]'], {}), '(saved_vertices[:, 0, i], saved_vertices[0, 0, i])\n', (3742, 3792), True, 'import numpy as np\n'), ((3868, 3927), 'numpy.append', 'np.append', (['saved_vertices[:, 1, i]', 'saved_vertices[0, 1, i]'], {}), '(saved_vertices[:, 1, i], saved_vertices[0, 1, i])\n', (3877, 3927), True, 'import numpy as np\n')]
import os import keras import h5py import math import numpy as np import datetime as dt from glob import glob from PIL import Image import cv2 import matplotlib.pyplot as plt import io class Hdf5Sequence(keras.utils.Sequence): def __init__(self, myHd5File, idlist, batch_size): self.srcFile, self.Ids = myHd5File, idlist self.batch_size = batch_size self.hh = h5py.File(myHd5File, "r") # call these only once self.data_size = self.hh["vectors"].shape[0] # self.size_per_batch = self.data_size / batch_size self.img_size = (160, 160) # always for this case/project def __len__(self): return math.ceil(self.data_size / self.batch_size) def my_preprocess_img(self, img): return img def __getitem__(self, idx): """Return tuple(input, id) or (img, id) correspondidng to batch #idx single Call to getitem will return batch_size length of data""" # start = current * size_per_batch # end = (current + 1) * size_per_batch startIndex = idx * self.batch_size stopIndex = startIndex + self.batch_size descs = [] names = [] descs.append(np.array(self.hh["vectors"][startIndex:stopIndex])) names += np.array(self.hh["image_names"][startIndex:stopIndex], dtype=object).astype(str).tolist() ''' batch_ip_img_paths = self.input_img_paths[startIndex: stopIndex] batch_ip_mask_paths = self.input_mask_paths[startIndex: stopIndex] batch_imgs = np.zeros((self.batch_size,) + self.img_size + (3,), dtype="float32") # both input_img and target_img will have size of img_size=(160,160) # x shape =(32,H,W,3) NHWC format i.e. 4D tensor for ii in range(self.batch_size): img = read_image(batch_ip_img_paths[ii]) mask = read_mask(batch_ip_mask_paths[ii]) if self.aug != None: img, mask = augment_image_and_mask(img, mask, self.aug) img = normalize_img(img) batch_imgs[ii] = img batch_masks[ii] = mask return batch_imgs ''' return names, np.vstack(descs) def my_test_size(): img_dir = "C:/Users/parajav/PycharmProjects/isc/reference/reference" image_fullnames = glob(os.path.join(img_dir, "*.jpg")) img_path = image_fullnames[0] print("imagename: ", img_path) print("****************case1: read and save file as numpy array") save_path = '../numpy.hdf5' imgsz=os.path.getsize(img_path) print('image size: %d bytes' % imgsz) hf = h5py.File(save_path, 'w') # open a hdf5 file start = dt.datetime.now() img_np = np.array(Image.open(img_path)) dset = hf.create_dataset('default', data=img_np) # write the data to hdf5 file hf.close() # close the hdf5 file end = dt.datetime.now() print(" total time, ", (end - start).microseconds/1000, "milliseconds") print('hdf5 file size: %d bytes; ratio: hdf5/origImg %f' % (os.path.getsize(save_path), os.path.getsize(save_path)/imgsz)) print("****************case2: read and save file as numpy array(uint8)") save_path = '../numpyuint8.hdf5' imgsz = os.path.getsize(img_path) print('image size: %d bytes' % imgsz) hf = h5py.File(save_path, 'w') # open a hdf5 file start = dt.datetime.now() img_np = np.array(Image.open(img_path),dtype='uint8') dset = hf.create_dataset('default', data=img_np) # write the data to hdf5 file hf.close() # close the hdf5 file end = dt.datetime.now() print(" total time, ", (end - start).microseconds/1000, "milliseconds") print('hdf5 file size: %d bytes; ratio: hdf5/origImg %f' % (os.path.getsize(save_path), os.path.getsize(save_path) / imgsz)) print("****************case3: read and save file as python binary file") save_path = '../test.hdf5' hf = h5py.File(save_path, 'w') # open a hdf5 file start = dt.datetime.now() with open(img_path, 'rb') as img_f: binary_data = img_f.read() # read the image as python binary binary_data_np = np.asarray(binary_data) dset = hf.create_dataset('default', data=binary_data_np) # write the data to hdf5 file hf.close() # close the hdf5 file end = dt.datetime.now() print(" total time, ", (end - start).microseconds/1000, "milliseconds") print('hdf5 file size: %d bytes; ratio: hdf5/origImg %f' % (os.path.getsize(save_path), os.path.getsize(save_path) / imgsz)) print("****************case3b: read and save resized file as python binary file") save_path = '../test3b.hdf5' hf = h5py.File(save_path, 'w') # open a hdf5 file start = dt.datetime.now() with open(img_path, 'rb') as img_f: binary_data = img_f.read() # read the image as python binary #binary_data_np = np.asarray(binary_data) im = Image.open(io.BytesIO(binary_data)) resizedImage = im.resize((160, 160)) buf = io.BytesIO() #resizedImage.save(buf, format='JPEG') dset = hf.create_dataset('default', data=np.asarray(resizedImage)) # write the data to hdf5 file hf.close() # close the hdf5 file end = dt.datetime.now() #to retrieve data use the following: #hf = h5py.File(hdf5_file, 'r') # open a hdf5 file #data = np.array(hf[key]) # write the data to hdf5 file #img = Image.open(io.BytesIO(data)) #byte_im = buf.getvalue() print(" total time, ", (end - start).microseconds / 1000, "milliseconds") print('hdf5 file size: %d bytes; ratio: hdf5/origImg %f' % (os.path.getsize(save_path), os.path.getsize(save_path) / imgsz)) print("****************case4: opencv2 img with uint8") save_path = '../testopencv2.hdf5' hf = h5py.File(save_path, 'w') # open a hdf5 file start = dt.datetime.now() image = np.array(cv2.imread(img_path)) #binary_data_np = np.asarray(binary_data) vectors = np.ascontiguousarray(image, dtype='uint8') dset = hf.create_dataset('default', data=vectors) # write the data to hdf5 file hf.close() # close the hdf5 file end = dt.datetime.now() print(" total time, ", (end - start).microseconds/1000, "milliseconds") print('hdf5 file size: %d bytes; ratio: hdf5/origImg %f' % (os.path.getsize(save_path), os.path.getsize(save_path) / imgsz)) print("image shape from opencv: ",image.shape ) print("****************case5: opencv2 img with resize") save_path = '../testopencv2resized.hdf5' hf = h5py.File(save_path, 'w') # open a hdf5 file start = dt.datetime.now() image = cv2.imread(img_path) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) image = cv2.resize(image, (160,160), interpolation=cv2.INTER_AREA) # binary_data_np = np.asarray(binary_data) vectors = np.ascontiguousarray(image, dtype ='uint8') dset = hf.create_dataset('default', data=vectors)#,shape=(160,160,3), #maxshape=(160,160,3),compression="gzip",compression_opts=9) hf.close() # close the hdf5 file end = dt.datetime.now() print("image type: ", image.dtype) print(" total time, ", (end - start).microseconds / 1000, "milliseconds") print('hdf5 file size: %d bytes; ratio: hdf5/origImg %f' % (os.path.getsize(save_path), os.path.getsize(save_path) / imgsz)) print("image shape from opencv: ", image.shape) my_test_size()
[ "os.path.getsize", "PIL.Image.open", "math.ceil", "numpy.asarray", "io.BytesIO", "os.path.join", "h5py.File", "numpy.ascontiguousarray", "datetime.datetime.now", "numpy.array", "numpy.vstack", "cv2.cvtColor", "cv2.resize", "cv2.imread" ]
[((2583, 2608), 'os.path.getsize', 'os.path.getsize', (['img_path'], {}), '(img_path)\n', (2598, 2608), False, 'import os\n'), ((2662, 2687), 'h5py.File', 'h5py.File', (['save_path', '"""w"""'], {}), "(save_path, 'w')\n", (2671, 2687), False, 'import h5py\n'), ((2721, 2738), 'datetime.datetime.now', 'dt.datetime.now', ([], {}), '()\n', (2736, 2738), True, 'import datetime as dt\n'), ((2919, 2936), 'datetime.datetime.now', 'dt.datetime.now', ([], {}), '()\n', (2934, 2936), True, 'import datetime as dt\n'), ((3324, 3349), 'os.path.getsize', 'os.path.getsize', (['img_path'], {}), '(img_path)\n', (3339, 3349), False, 'import os\n'), ((3403, 3428), 'h5py.File', 'h5py.File', (['save_path', '"""w"""'], {}), "(save_path, 'w')\n", (3412, 3428), False, 'import h5py\n'), ((3462, 3479), 'datetime.datetime.now', 'dt.datetime.now', ([], {}), '()\n', (3477, 3479), True, 'import datetime as dt\n'), ((3674, 3691), 'datetime.datetime.now', 'dt.datetime.now', ([], {}), '()\n', (3689, 3691), True, 'import datetime as dt\n'), ((4089, 4114), 'h5py.File', 'h5py.File', (['save_path', '"""w"""'], {}), "(save_path, 'w')\n", (4098, 4114), False, 'import h5py\n'), ((4148, 4165), 'datetime.datetime.now', 'dt.datetime.now', ([], {}), '()\n', (4163, 4165), True, 'import datetime as dt\n'), ((4300, 4323), 'numpy.asarray', 'np.asarray', (['binary_data'], {}), '(binary_data)\n', (4310, 4323), True, 'import numpy as np\n'), ((4467, 4484), 'datetime.datetime.now', 'dt.datetime.now', ([], {}), '()\n', (4482, 4484), True, 'import datetime as dt\n'), ((4889, 4914), 'h5py.File', 'h5py.File', (['save_path', '"""w"""'], {}), "(save_path, 'w')\n", (4898, 4914), False, 'import h5py\n'), ((4948, 4965), 'datetime.datetime.now', 'dt.datetime.now', ([], {}), '()\n', (4963, 4965), True, 'import datetime as dt\n'), ((5224, 5236), 'io.BytesIO', 'io.BytesIO', ([], {}), '()\n', (5234, 5236), False, 'import io\n'), ((5434, 5451), 'datetime.datetime.now', 'dt.datetime.now', ([], {}), '()\n', (5449, 5451), True, 'import datetime as dt\n'), ((6071, 6096), 'h5py.File', 'h5py.File', (['save_path', '"""w"""'], {}), "(save_path, 'w')\n", (6080, 6096), False, 'import h5py\n'), ((6130, 6147), 'datetime.datetime.now', 'dt.datetime.now', ([], {}), '()\n', (6145, 6147), True, 'import datetime as dt\n'), ((6254, 6296), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['image'], {'dtype': '"""uint8"""'}), "(image, dtype='uint8')\n", (6274, 6296), True, 'import numpy as np\n'), ((6433, 6450), 'datetime.datetime.now', 'dt.datetime.now', ([], {}), '()\n', (6448, 6450), True, 'import datetime as dt\n'), ((6894, 6919), 'h5py.File', 'h5py.File', (['save_path', '"""w"""'], {}), "(save_path, 'w')\n", (6903, 6919), False, 'import h5py\n'), ((6953, 6970), 'datetime.datetime.now', 'dt.datetime.now', ([], {}), '()\n', (6968, 6970), True, 'import datetime as dt\n'), ((6984, 7004), 'cv2.imread', 'cv2.imread', (['img_path'], {}), '(img_path)\n', (6994, 7004), False, 'import cv2\n'), ((7018, 7056), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_BGR2RGB'], {}), '(image, cv2.COLOR_BGR2RGB)\n', (7030, 7056), False, 'import cv2\n'), ((7070, 7129), 'cv2.resize', 'cv2.resize', (['image', '(160, 160)'], {'interpolation': 'cv2.INTER_AREA'}), '(image, (160, 160), interpolation=cv2.INTER_AREA)\n', (7080, 7129), False, 'import cv2\n'), ((7192, 7234), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['image'], {'dtype': '"""uint8"""'}), "(image, dtype='uint8')\n", (7212, 7234), True, 'import numpy as np\n'), ((7439, 7456), 'datetime.datetime.now', 'dt.datetime.now', ([], {}), '()\n', (7454, 7456), True, 'import datetime as dt\n'), ((411, 436), 'h5py.File', 'h5py.File', (['myHd5File', '"""r"""'], {}), "(myHd5File, 'r')\n", (420, 436), False, 'import h5py\n'), ((687, 730), 'math.ceil', 'math.ceil', (['(self.data_size / self.batch_size)'], {}), '(self.data_size / self.batch_size)\n', (696, 730), False, 'import math\n'), ((2365, 2395), 'os.path.join', 'os.path.join', (['img_dir', '"""*.jpg"""'], {}), "(img_dir, '*.jpg')\n", (2377, 2395), False, 'import os\n'), ((2762, 2782), 'PIL.Image.open', 'Image.open', (['img_path'], {}), '(img_path)\n', (2772, 2782), False, 'from PIL import Image\n'), ((3503, 3523), 'PIL.Image.open', 'Image.open', (['img_path'], {}), '(img_path)\n', (3513, 3523), False, 'from PIL import Image\n'), ((5146, 5169), 'io.BytesIO', 'io.BytesIO', (['binary_data'], {}), '(binary_data)\n', (5156, 5169), False, 'import io\n'), ((6170, 6190), 'cv2.imread', 'cv2.imread', (['img_path'], {}), '(img_path)\n', (6180, 6190), False, 'import cv2\n'), ((1234, 1284), 'numpy.array', 'np.array', (["self.hh['vectors'][startIndex:stopIndex]"], {}), "(self.hh['vectors'][startIndex:stopIndex])\n", (1242, 1284), True, 'import numpy as np\n'), ((2223, 2239), 'numpy.vstack', 'np.vstack', (['descs'], {}), '(descs)\n', (2232, 2239), True, 'import numpy as np\n'), ((5327, 5351), 'numpy.asarray', 'np.asarray', (['resizedImage'], {}), '(resizedImage)\n', (5337, 5351), True, 'import numpy as np\n'), ((3080, 3106), 'os.path.getsize', 'os.path.getsize', (['save_path'], {}), '(save_path)\n', (3095, 3106), False, 'import os\n'), ((3835, 3861), 'os.path.getsize', 'os.path.getsize', (['save_path'], {}), '(save_path)\n', (3850, 3861), False, 'import os\n'), ((4628, 4654), 'os.path.getsize', 'os.path.getsize', (['save_path'], {}), '(save_path)\n', (4643, 4654), False, 'import os\n'), ((5830, 5856), 'os.path.getsize', 'os.path.getsize', (['save_path'], {}), '(save_path)\n', (5845, 5856), False, 'import os\n'), ((6594, 6620), 'os.path.getsize', 'os.path.getsize', (['save_path'], {}), '(save_path)\n', (6609, 6620), False, 'import os\n'), ((7642, 7668), 'os.path.getsize', 'os.path.getsize', (['save_path'], {}), '(save_path)\n', (7657, 7668), False, 'import os\n'), ((3160, 3186), 'os.path.getsize', 'os.path.getsize', (['save_path'], {}), '(save_path)\n', (3175, 3186), False, 'import os\n'), ((3928, 3954), 'os.path.getsize', 'os.path.getsize', (['save_path'], {}), '(save_path)\n', (3943, 3954), False, 'import os\n'), ((4721, 4747), 'os.path.getsize', 'os.path.getsize', (['save_path'], {}), '(save_path)\n', (4736, 4747), False, 'import os\n'), ((5923, 5949), 'os.path.getsize', 'os.path.getsize', (['save_path'], {}), '(save_path)\n', (5938, 5949), False, 'import os\n'), ((6687, 6713), 'os.path.getsize', 'os.path.getsize', (['save_path'], {}), '(save_path)\n', (6702, 6713), False, 'import os\n'), ((7735, 7761), 'os.path.getsize', 'os.path.getsize', (['save_path'], {}), '(save_path)\n', (7750, 7761), False, 'import os\n'), ((1304, 1372), 'numpy.array', 'np.array', (["self.hh['image_names'][startIndex:stopIndex]"], {'dtype': 'object'}), "(self.hh['image_names'][startIndex:stopIndex], dtype=object)\n", (1312, 1372), True, 'import numpy as np\n')]
""" Module containing higher-level detector-related classes. The classes in this module are responsible for higher-level operations of the antennas and detectors than in the antenna module. This includes functions like front-end electronics chains and trigger systems. """ from collections.abc import Iterable import inspect import logging import numpy as np from pyrex.internal_functions import flatten, mirror_func logger = logging.getLogger(__name__) class AntennaSystem: """ Base class for antenna system with front-end processing. Behaves similarly to an antenna by passing some functionality downward to an antenna class, but additionally applies some front-end processing (e.g. an electronics chain) to the signals received. Parameters ---------- antenna : Antenna ``Antenna`` class or subclass to be extended with a front end. Can also accept an ``Antenna`` object directly. Attributes ---------- antenna : Antenna ``Antenna`` object extended by the front end. lead_in_time : float Lead-in time (s) required for the front end to equilibrate. Automatically added in before calculation of signals and waveforms. is_hit is_hit_mc_truth signals waveforms all_waveforms See Also -------- pyrex.Antenna : Base class for antennas. """ lead_in_time = 0 def __init__(self, antenna): if inspect.isclass(antenna): self._antenna_class = antenna else: self.antenna = antenna self._antenna_class = antenna.__class__ self._signals = [] self._all_waves = [] self._triggers = [] def __str__(self): return (self.__class__.__name__+"(position="+ repr(self.antenna.position)+")") @property def _metadata(self): """Metadata dictionary for writing `AntennaSystem` information.""" return self.antenna._metadata def setup_antenna(self, *args, **kwargs): """ Setup the antenna by passing along its init arguments. Any arguments passed to this method are directly passed to the ``__init__`` methods of the ``antenna``'s class. This function can be overridden if desired, just make sure to assign the ``self.antenna`` attribute in the function. """ self.antenna = self._antenna_class(*args, **kwargs) def set_orientation(self, z_axis=(0,0,1), x_axis=(1,0,0)): """ Sets the orientation of the antenna system. Sets up the z-axis and the x-axis of the antenna according to the given parameters. Fails if the z-axis and x-axis aren't perpendicular. Parameters ---------- z_axis : array_like, optional Vector direction of the z-axis of the antenna. x_axis : array_like, optional Vector direction of the x-axis of the antenna. Raises ------ ValueError If the z-axis and x-axis aren't perpendicular. """ self.antenna.set_orientation(z_axis=z_axis, x_axis=x_axis) def front_end(self, signal): """ Apply front-end processes to a signal and return the output. This function defines the front end of the antenna (e.g. electronics chain). It is expected to be overridden in subclasses, as for the base class it simply passes along the given `signal`. Parameters ---------- signal : Signal ``Signal`` object on which to apply the front-end processes. Returns ------- Signal Signal processed by the antenna front end. See Also -------- pyrex.Signal : Base class for time-domain signals. """ logger.debug("Using default front_end from "+ "pyrex.detector.AntennaSystem") return signal def _calculate_lead_in_times(self, times): t0 = times[0] t_min = t0-self.lead_in_time t_max = times[-1] dt = times[1]-t0 # Number of points in the lead-in array n_pts = int((t_max-t_min)/dt)+2 - len(times) # Proper starting point of lead-in array to preserve dt t_min = t0-n_pts*dt return np.concatenate( (np.linspace(t_min, t0, n_pts, endpoint=False), times) ) @property def is_hit(self): """Boolean of whether the antenna system has been triggered.""" return len(self.waveforms)>0 @property def is_hit_mc_truth(self): """ Boolean of whether the antenna has been triggered by signal. The decision is based on the Monte Carlo truth of whether noise would have triggered without the signal. If a signal triggered, but the noise alone in the same timeframe would have triggered as well, the trigger is not counted. """ for wave in self.waveforms: if not self.trigger(self.make_noise(wave.times)): return True return False def is_hit_during(self, times): """ Check if the antenna system is triggered in a time range. Generate the full waveform of the antenna system over the given `times` array and check whether it triggers the antenna system. Parameters ---------- times : array_like 1D array of times during which to check for a trigger. Returns ------- boolean Whether or not the antenna system triggered during the given `times`. See Also -------- pyrex.Antenna.is_hit_during : Check if an antenna is triggered in a time range. """ return self.trigger(self.full_waveform(times)) def clear(self, reset_noise=False): """ Reset the antenna system to an empty state. Clears all signals, noises, and triggers from the antenna state. Can also optionally recalibrate the noise so that a new signal arriving at the same times as a previous signal will not have the same noise. Parameters ---------- reset_noise : boolean, optional Whether or not to recalibrate the noise. See Also -------- pyrex.Antenna.clear : Reset an antenna to an empty state. """ self._signals.clear() self._all_waves.clear() self._triggers.clear() self.antenna.clear(reset_noise=reset_noise) @property def signals(self): """The signals received by the antenna with front-end processing.""" # Process any unprocessed antenna signals, including the appropriate # amount of front-end lead-in time while len(self._signals)<len(self.antenna.signals): signal = self.antenna.signals[len(self._signals)] long_times = self._calculate_lead_in_times(signal.times) preprocessed = signal.with_times(long_times) processed = self.front_end(preprocessed) self._signals.append(processed.with_times(signal.times)) # Return processed antenna signals return self._signals @property def waveforms(self): """The antenna system signal + noise for each triggered hit.""" # Process any unprocessed triggers all_waves = self.all_waveforms while len(self._triggers)<len(all_waves): waveform = all_waves[len(self._triggers)] self._triggers.append(self.trigger(waveform)) return [wave for wave, triggered in zip(all_waves, self._triggers) if triggered] @property def all_waveforms(self): """The antenna system signal + noise for all hits.""" # Process any unprocessed antenna signals, including the appropriate # amount of front-end lead-in time while len(self._all_waves)<len(self.antenna.signals): self._all_waves.append( self.full_waveform( self.antenna.signals[len(self._all_waves)].times ) ) return self._all_waves def full_waveform(self, times): """ Signal + noise for the antenna system for the given times. Creates the complete waveform of the antenna system including noise and all received signals for the given `times` array. Includes front-end processing with the required lead-in time. Parameters ---------- times : array_like 1D array of times during which to produce the full waveform. Returns ------- Signal Complete waveform with noise and all signals. See Also -------- pyrex.Antenna.full_waveform : Signal + noise for an antenna for the given times. """ # Process full antenna waveform long_times = self._calculate_lead_in_times(times) preprocessed = self.antenna.full_waveform(long_times) processed = self.front_end(preprocessed) return processed.with_times(times) def make_noise(self, times): """ Creates a noise signal over the given times. Passes a noise signal of the antenna through the front-end. Parameters ---------- times : array_like 1D array of times during which to produce noise values. Returns ------- Signal Antenna system noise values during the `times` array. Raises ------ ValueError If not enough noise-related attributes are defined for the antenna. """ long_times = self._calculate_lead_in_times(times) preprocessed = self.antenna.make_noise(long_times) processed = self.front_end(preprocessed) return processed.with_times(times) def trigger(self, signal): """ Check if the antenna system triggers on a given signal. By default just matches the antenna's trigger. It may be overridden in subclasses. Parameters ---------- signal : Signal ``Signal`` object on which to test the trigger condition. Returns ------- boolean Whether or not the antenna triggers on `signal`. See Also -------- pyrex.Antenna.trigger : Check if an antenna triggers on a given signal. pyrex.Signal : Base class for time-domain signals. """ return self.antenna.trigger(signal) def apply_response(self, signal, direction=None, polarization=None, force_real=False): """ Process the complete antenna response for an incoming signal. Processes the incoming signal by passing the call along to the ``antenna`` object. Parameters ---------- signal : Signal Incoming ``Signal`` object to process. direction : array_like, optional Vector denoting the direction of travel of the signal as it reaches the antenna (in the global coordinate frame). If ``None`` no directional response will be applied. polarization : array_like, optional Vector denoting the signal's polarization direction (in the global coordinate frame). If ``None`` no polarization gain will be applied. force_real : boolean, optional Whether or not the frequency response should be redefined in the negative-frequency domain to keep the values of the filtered signal real. Returns ------- Signal Processed ``Signal`` object after the complete antenna response has been applied. Should have a ``value_type`` of ``voltage``. Raises ------ ValueError If the given `signal` does not have a ``value_type`` of ``voltage`` or ``field``. See Also -------- pyrex.Signal : Base class for time-domain signals. """ return self.antenna.apply_response(signal, direction=direction, polarization=polarization, force_real=force_real) def receive(self, signal, direction=None, polarization=None, force_real=False): """ Process and store one or more incoming (polarized) signals. Processes the incoming signal(s) by passing the call along to the ``antenna`` object. Parameters ---------- signal : Signal or array_like Incoming ``Signal`` object(s) to process and store. May be separate polarization representations, but therefore should have the same times. direction : array_like, optional Vector denoting the direction of travel of the signal(s) as they reach the antenna (in the global coordinate frame). If ``None`` no directional gain will be applied. polarization : array_like, optional Vector(s) denoting the signal's polarization direction (in the global coordinate frame). Number of vectors should match the number of elements in `signal` argument. If ``None`` no polarization gain will be applied. force_real : boolean, optional Whether or not the frequency response should be redefined in the negative-frequency domain to keep the values of the filtered signal real. Raises ------ ValueError If the number of polarizations does not match the number of signals. Or if the signals do not have the same `times` array. See Also -------- pyrex.Antenna.receive : Process and store one or more incoming (polarized) signals. pyrex.Signal : Base class for time-domain signals. """ return self.antenna.receive(signal, direction=direction, polarization=polarization, force_real=force_real) class Detector: """ Base class for detectors for easily building up sets of antennas. Designed for automatically generating antenna positions based on geometry parameters, then building all the antennas with some properties. Any parameters to the ``__init__`` method are automatically passed on to the `set_positions` method. Once the antennas have been built, the object can be directly iterated over to iterate over the antennas (as if the object were just a list of the antennas). Attributes ---------- antenna_positions : list List (potentially with sub-lists) of the positions of the antennas generated by the `set_positions` method. subsets : list List of the antenna or detector objects which make up the detector. test_antenna_positions : boolean Class attribute for whether or not an error should be raised if antenna positions are found above the surface of the ice (where simulation behavior is ill-defined). Defaults to ``True``. Raises ------ ValueError If ``test_antenna_positions`` is ``True`` and an antenna is found to be above the ice surface. See Also -------- pyrex.Antenna : Base class for antennas. AntennaSystem : Base class for antenna system with front-end processing. Notes ----- When this class is subclassed, the ``__init__`` method will mirror the signature of the `set_positions` method so that parameters can be easily discovered. The class is designed to be flexible in what defines a "detector". This should allow for easier modularization by defining detectors whose subsets are detectors themselves, and so on. For example, a string of antennas could be set up as a subclass of `Detector` which sets up some antennas in a vertical line. Then a station could be set up as a subclass of `Detector` which sets up multiple instances of the string class at different positions. Then a final overarching detector class can subclass `Detector` and set up multiple instances of the station class at different positions. In this example the ``subsets`` of the overarching detector class would be the station objects, the ``subsets`` of the station objects would be the string objects, and the ``subsets`` of the string objects would finally be the antenna objects. But the way the iteration of the `Detector` class is built, iterating over that overarching detector class would iterate directly over each antenna in each string in each station as a simple 1D list. """ test_antenna_positions = True def __init__(self, *args, **kwargs): self.antenna_positions = [] self.subsets = [] self.set_positions(*args, **kwargs) # Pull antenna positions from any subsets if not self._is_base_subset: self.antenna_positions = [sub.antenna_positions for sub in self.subsets] self._test_positions() self._mirror_build_function() def __init_subclass__(cls, mirror_set_positions=True, **kwargs): """ Automates function mirroring when subclasses are created. When this class is subclassed, set the subclass's ``__init__`` method to mirror its ``set_positions`` method (since all ``__init__`` arguments are passed to ``set_positions`` anyway). Parameters ---------- mirror_set_positions : boolean, optional Whether or not to mirror the set_positions method. Warnings -------- If `mirror_set_positions` is ``True``, the ``__init__`` method of the class is replaced by ``super().__init__``. """ super().__init_subclass__(**kwargs) if mirror_set_positions: cls.__init__ = mirror_func(cls.set_positions, Detector.__init__) def __add__(self, other): """ Adds two detectors into a ``CombinedDetector``. Supports addition of ``Detector`` objects, ``Antenna``-like objects, or lists of ``Antenna``-like objects. """ return CombinedDetector(self, other) def __radd__(self, other): """ Allows for adding ``Detector`` object to 0. Since the python ``sum`` function starts by adding the first element to 0, to use ``sum`` with ``Detector`` objects we need to be able to add a ``Detector`` object to 0. If adding to anything else, perform the usual addition. """ if other==0: return self else: return CombinedDetector(other, self) @property def _metadata(self): """List of metadata dictionaries of the `Antenna` objects.""" return [antenna._metadata for antenna in self] def set_positions(self, *args, **kwargs): """ Sets the positions of antennas in the detector. For the base `Detector` class, this method is not implemented. Subclasses should override this method with their own procedure for setting antenna positions based on some parameters. Raises ------ NotImplementedError Always, unless a subclass overrides the function. """ logger.debug("Using default set_positions from "+ "pyrex.detector.Detector") raise NotImplementedError("set_positions method must be implemented " +"by inheriting class") def build_antennas(self, *args, **kwargs): """ Creates antenna objects at the set antenna positions. This method takes an antenna class and, for each position in the ``antenna_positions`` attribute, creates an antenna object of that class with the position as the `position` argument, followed by any other arguments that were passed to the method. These antenna objects are stored to the ``subsets`` attribute with the same list structure. Subclasses may extend this method, but generally shouldn't need to as subset `build_antennas` methods are automatically called as needed. """ if self._is_base_subset: logger.debug("Using default build_antennas from "+ "pyrex.detector.Detector") if "antenna_class" in kwargs: antenna_class = kwargs["antenna_class"] kwargs.pop("antenna_class") else: if len(args)<1: raise TypeError("build_antennas() missing 1 required "+ "positional argument: 'antenna_class'") antenna_class = args[0] args = args[1:] self.subsets = [] for p in self.antenna_positions: self.subsets.append(antenna_class(position=p, *args, **kwargs)) else: if self._subset_builds_match: # If the signatures match, passing down args is fine for sub in self.subsets: if hasattr(sub, 'build_antennas'): sub.build_antennas(*args, **kwargs) else: # If the signatures don't match, only pass down kwargs as needed if len(args)>0: raise TypeError("Detector build_antennas cannot handle "+ "positional arguments when its subsets "+ "aren't identical") for sub in self.subsets: if hasattr(sub, 'build_antennas'): sig = inspect.signature(sub.build_antennas) keys = sig.parameters.keys() sub_kwargs = {key: val for key, val in kwargs.items() if key in keys} sub.build_antennas(**sub_kwargs) def triggered(self, *args, require_mc_truth=False, **kwargs): """ Check if the detector is triggered based on its current state. By default just checks whether any antenna in the detector is hit. This method may be overridden in subclasses. Parameters ---------- require_mc_truth : boolean, optional Whether or not the trigger should be based on the Monte-Carlo truth. If ``True``, noise-only triggers are removed. Returns ------- boolean Whether or not the detector is triggered in its current state. See Also -------- pyrex.Antenna.trigger : Check if an antenna triggers on a given signal. pyrex.AntennaSystem.trigger : Check if an antenna system triggers on a given signal. """ for ant in self: if ((require_mc_truth and ant.is_hit_mc_truth) or (not require_mc_truth and ant.is_hit)): return True return False def clear(self, reset_noise=False): """ Reset the detector to an empty state. Convenience method to clear all signals, noises, and triggers from all antennas in the detector. Can also optionally recalibrate the noise for all antennas as well. Parameters ---------- reset_noise : boolean, optional Whether or not to recalibrate the noise. See Also -------- pyrex.Antenna.clear : Reset an antenna to an empty state. pyrex.AntennaSystem.clear : Reset an antenna system to an empty state. """ for ant in self: ant.clear(reset_noise=reset_noise) @property def _is_base_subset(self): """Whether the detector is a base subset.""" return (len(self.subsets)==0 or True not in [isinstance(sub, Iterable) for sub in self.subsets]) @property def _subset_builds_match(self): """ Whether the subsets of the detector have the same ``build_antennas``. """ return (self._is_base_subset or len(set([inspect.signature(sub.build_antennas) for sub in self.subsets if hasattr(sub, 'build_antennas')])) == 1) def _test_positions(self): """ Check that all antenna positions are below the ice surface. Tests each antenna position to ensure no antennas are unexpectedly placed above the ice. Also pulls all antenna positions up from subsets. Raises ------ ValueError If an antenna position is found above the ice surface. """ if not self.test_antenna_positions: return if self._is_base_subset: for pos in self.antenna_positions: if pos[2]>0: raise ValueError("Antenna placed outside of ice may cause " +"unexpected issues") else: for sub in self.subsets: if hasattr(sub, '_test_positions'): sub._test_positions() elif isinstance(sub, Iterable): for ant in sub: if ant.position[2]>0: raise ValueError("Antenna placed outside of ice "+ "may cause unexpected issues") else: if sub.position[2]>0: raise ValueError("Antenna placed outside of ice "+ "may cause unexpected issues") def _mirror_build_function(self): """ Mirror the build function of the subsets. For a detector comprised of subsets which hasn't overwritten the default ``build_antennas`` method, mirrors the function signature of ``build_antennas`` from the base subset (as long as the signature is the same for all subsets). """ if hasattr(self, '_actual_build'): self.build_antennas = self._actual_build if (not self._is_base_subset and self.build_antennas.__func__==Detector.build_antennas and self._subset_builds_match): self._actual_build = self.build_antennas for sub in self.subsets: if hasattr(sub, 'build_antennas'): break self.build_antennas = mirror_func(sub.build_antennas, Detector.build_antennas, self=self) else: self._actual_build = self.build_antennas # Allow direct iteration of the detector to be treated as iteration over # the flat list of all its antennas def __iter__(self): yield from flatten(self.subsets) def __len__(self): return len(list(flatten(self.subsets))) def __getitem__(self, key): return list(flatten(self.subsets))[key] class CombinedDetector(Detector, mirror_set_positions=False): """ Class for detectors which have been added together. Designed to allow addition of ``Detector`` and ``Antenna``-like objects which can still build all antennas and trigger by smartly passing down keyword arguments to the subsets. Maintains all other properties of the ``Detector`` objects. Attributes ---------- antenna_positions : list List (potentially with sub-lists) of the positions of the antennas generated by the `set_positions` method. subsets : list List of the antenna or detector objects which make up the detector. test_antenna_positions : boolean Class attribute for whether or not an error should be raised if antenna positions are found above the surface of the ice (where simulation behavior is ill-defined). Defaults to ``True``. Raises ------ ValueError If ``test_antenna_positions`` is ``True`` and an antenna is found to be above the ice surface. See Also -------- pyrex.Antenna : Base class for antennas. AntennaSystem : Base class for antenna system with front-end processing. Detector : Base class for detectors for easily building up sets of antennas. """ def __init__(self, *detectors): self.subsets = list(detectors) self._test_positions() self._mirror_build_function() @property def antenna_positions(self): """List of the positions of the antennas in the detector.""" positions = [] for sub in self.subsets: if hasattr(sub, 'antenna_positions'): positions.append(sub.antenna_positions) elif isinstance(sub, Iterable): positions.append([ant.position for ant in sub]) else: positions.append(sub.position) return positions def __add__(self, other): """ Adds two detectors into a ``CombinedDetector``. Supports addition of ``Detector`` objects, ``Antenna``-like objects, or lists of ``Antenna``-like objects. Adds additional support for adding ``CombinedDetector`` objects so the subsets of the two are treated on equal footing. """ if isinstance(other, CombinedDetector): return CombinedDetector(*self.subsets, *other.subsets) else: return CombinedDetector(*self.subsets, other) def __radd__(self, other): """ Allows for adding ``CombinedDetector`` object to 0. Since the python ``sum`` function starts by adding the first element to 0, to use ``sum`` with ``CombinedDetector`` objects we need to be able to add a ``CombinedDetector`` object to 0. If adding to anything else, perform the usual addition. """ if other==0: return self elif isinstance(other, CombinedDetector): return CombinedDetector(*other.subsets, *self.subsets) else: return CombinedDetector(other, *self.subsets) def __iadd__(self, other): """ Adds a detector in-place. Supports addition of ``Detector`` objects, ``Antenna``-like objects, or lists of ``Antenna``-like objects. Adds additional support for adding ``CombinedDetector`` objects so the subsets of the two are treated on equal footing. """ if isinstance(other, CombinedDetector): self.subsets.extend(other.subsets) else: self.subsets.append(other) self._test_positions() self._mirror_build_function() return self @property def _subset_triggers_match(self): """Whether the subsets of the detector have the same triggered.""" return len(set([inspect.signature(sub.triggered) for sub in self.subsets if hasattr(sub, 'triggered')])) == 1 def triggered(self, *args, require_mc_truth=False, **kwargs): """ Check if the detector is triggered based on its current state. By default triggers if any subset of the detector is triggered. Passes arguments down to the appropriate subsets if the subsets are ``Detector`` objects, or checks for any triggering waveforms in ``Antenna``-like objects. Parameters ---------- require_mc_truth : boolean, optional Whether or not the trigger should be based on the Monte-Carlo truth. If ``True``, noise-only triggers are removed. *args, **kwargs Positional and keyword arguments to be passed down to `triggered` methods of the detector subsets. Returns ------- boolean Whether or not the detector is triggered in its current state. See Also -------- pyrex.Antenna.trigger : Check if an antenna triggers on a given signal. pyrex.AntennaSystem.trigger : Check if an antenna system triggers on a given signal. pyrex.Detector.triggered : Check if the detector is triggered based on its current state. """ if not self._subset_triggers_match and len(args)>0: raise TypeError("Combined detector trigger cannot handle "+ "positional arguments when its subsets "+ "aren't identical") # Add require_mc_truth to kwargs for ease of use kwargs['require_mc_truth'] = require_mc_truth for sub in self.subsets: if hasattr(sub, 'triggered'): if self._subset_triggers_match: # If the signatures match, passing down args is fine logger.debug("Called %s with args %s and kwargs %s", sub.triggered, args, kwargs) if sub.triggered(*args, **kwargs): return True else: # Keep trying the subset trigger, removing keyword # arguments which cause errors one by one sub_kwargs = kwargs while True: prev_kwargs = sub_kwargs try: triggered = sub.triggered(**sub_kwargs) except TypeError as e: # Remove the problematic argument from sub_kwargs msg = e.args[0] if 'got an unexpected keyword argument' in msg: parts = msg.split("'") bad_kw = parts[1] sub_kwargs = {key: val for key, val in sub_kwargs.items() if key!=bad_kw} else: raise e else: logger.debug("Called %s with kwargs %s", sub.triggered, sub_kwargs) if triggered: return True else: break if sub_kwargs==prev_kwargs: raise TypeError("Unable to pass keyword arguments"+ " down to subset triggers") elif isinstance(sub, Iterable): # Check for any antenna trigger in the subset for ant in sub: if ((require_mc_truth and ant.is_hit_mc_truth) or (not require_mc_truth and ant.is_hit)): return True else: # Check for single antenna trigger if ((require_mc_truth and sub.is_hit_mc_truth) or (not require_mc_truth and sub.is_hit)): return True return False
[ "logging.getLogger", "pyrex.internal_functions.mirror_func", "pyrex.internal_functions.flatten", "inspect.signature", "numpy.linspace", "inspect.isclass" ]
[((430, 457), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (447, 457), False, 'import logging\n'), ((1437, 1461), 'inspect.isclass', 'inspect.isclass', (['antenna'], {}), '(antenna)\n', (1452, 1461), False, 'import inspect\n'), ((18214, 18263), 'pyrex.internal_functions.mirror_func', 'mirror_func', (['cls.set_positions', 'Detector.__init__'], {}), '(cls.set_positions, Detector.__init__)\n', (18225, 18263), False, 'from pyrex.internal_functions import flatten, mirror_func\n'), ((26877, 26944), 'pyrex.internal_functions.mirror_func', 'mirror_func', (['sub.build_antennas', 'Detector.build_antennas'], {'self': 'self'}), '(sub.build_antennas, Detector.build_antennas, self=self)\n', (26888, 26944), False, 'from pyrex.internal_functions import flatten, mirror_func\n'), ((27265, 27286), 'pyrex.internal_functions.flatten', 'flatten', (['self.subsets'], {}), '(self.subsets)\n', (27272, 27286), False, 'from pyrex.internal_functions import flatten, mirror_func\n'), ((4331, 4376), 'numpy.linspace', 'np.linspace', (['t_min', 't0', 'n_pts'], {'endpoint': '(False)'}), '(t_min, t0, n_pts, endpoint=False)\n', (4342, 4376), True, 'import numpy as np\n'), ((27335, 27356), 'pyrex.internal_functions.flatten', 'flatten', (['self.subsets'], {}), '(self.subsets)\n', (27342, 27356), False, 'from pyrex.internal_functions import flatten, mirror_func\n'), ((27412, 27433), 'pyrex.internal_functions.flatten', 'flatten', (['self.subsets'], {}), '(self.subsets)\n', (27419, 27433), False, 'from pyrex.internal_functions import flatten, mirror_func\n'), ((22024, 22061), 'inspect.signature', 'inspect.signature', (['sub.build_antennas'], {}), '(sub.build_antennas)\n', (22041, 22061), False, 'import inspect\n'), ((31284, 31316), 'inspect.signature', 'inspect.signature', (['sub.triggered'], {}), '(sub.triggered)\n', (31301, 31316), False, 'import inspect\n'), ((24539, 24576), 'inspect.signature', 'inspect.signature', (['sub.build_antennas'], {}), '(sub.build_antennas)\n', (24556, 24576), False, 'import inspect\n')]
import os import pytest from freezegun import freeze_time import numpy as np # The line below is absolutely necessary. Fixtures are passed as arguments to test functions. That is why IDE could # not recognized them. from api.tests.utils.fixtures_tests import config_rollback_cameras, heatmap_simulation, config_rollback HEATMAP_PATH_PREFIX = "/repo/api/tests/data/mocked_data/data/processor/static/data/sources/" # pytest -v api/tests/app/test_camera_metrics.py::TestsGetHeatmap class TestsGetHeatmap: """ Get Heatmap, GET /metrics/cameras/{camera_id}/heatmap """ """ Returns a heatmap image displaying the violations/detections detected by the camera <camera_id>. """ def test_get_one_heatmap_properly(self, config_rollback_cameras, heatmap_simulation): # Make the request camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id = camera["id"] response = client.get(f"/metrics/cameras/{camera_id}/heatmap?from_date=2020-09-19&to_date=2020-09-19") # Get the heatmap heatmap_path = os.path.join(HEATMAP_PATH_PREFIX, camera_id, "heatmaps", "violations_heatmap_2020-09-19.npy") heatmap = np.load(heatmap_path).tolist() # Compare results assert response.status_code == 200 assert response.json()["heatmap"] == heatmap def test_try_get_two_heatmaps(self, config_rollback_cameras, heatmap_simulation): camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id = camera["id"] response = client.get(f"/metrics/cameras/{camera_id}/heatmap?from_date=2020-09-19&to_date=2020-09-20") heatmap_path = os.path.join(HEATMAP_PATH_PREFIX, camera_id, "heatmaps", "violations_heatmap_2020-09-19.npy") heatmap = np.load(heatmap_path).tolist() assert response.status_code == 200 assert response.json()["heatmap"] == heatmap assert response.json()["not_found_dates"] == ["2020-09-20"] def test_get_two_valid_heatmaps(self, config_rollback_cameras, heatmap_simulation): camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id = camera["id"] response = client.get(f"/metrics/cameras/{camera_id}/heatmap?from_date=2020-09-19&to_date=2020-09-22") heatmap_path_1 = os.path.join(HEATMAP_PATH_PREFIX, camera_id, "heatmaps", "violations_heatmap_2020-09-19.npy") heatmap_path_2 = os.path.join(HEATMAP_PATH_PREFIX, camera_id, "heatmaps", "violations_heatmap_2020-09-22.npy") heatmap_1 = np.load(heatmap_path_1) heatmap_2 = np.load(heatmap_path_2) final_heatmap = np.add(heatmap_1, heatmap_2).tolist() assert response.status_code == 200 assert response.json()["not_found_dates"] == ['2020-09-20', '2020-09-21'] assert response.json()['heatmap'] == final_heatmap def test_get_one_heatmap_properly_detections(self, config_rollback_cameras, heatmap_simulation): camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id = camera["id"] response = client.get( f"/metrics/cameras/{camera_id}/heatmap?from_date=2020-09-19&to_date=2020-09-19&report_type=detections") heatmap_path = os.path.join(HEATMAP_PATH_PREFIX, camera_id, "heatmaps", "detections_heatmap_2020-09-19.npy") heatmap = np.load(heatmap_path).tolist() assert response.status_code == 200 assert response.json()["heatmap"] == heatmap def test_try_get_one_heatmap_bad_camera_id(self, config_rollback_cameras, heatmap_simulation): camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id = "wrong_id" response = client.get(f"/metrics/cameras/{camera_id}/heatmap?from_date=2020-09-19&to_date=2020-09-19") assert response.status_code == 404 assert response.json() == {'detail': "Camera with id 'wrong_id' does not exist"} def test_try_get_one_heatmap_bad_report_type(self, config_rollback_cameras, heatmap_simulation): camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id = camera["id"] response = client.get( f"/metrics/cameras/{camera_id}/heatmap?from_date=2020-09-19&to_date=2020-09-19&report_type" f"=non_existent_report_type") assert response.status_code == 400 assert response.json() == {'detail': [{'loc': [], 'msg': 'Invalid report_type', 'type': 'invalid config'}]} def test_try_get_one_heatmap_bad_dates(self, config_rollback_cameras, heatmap_simulation): camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id = camera["id"] response = client.get(f"/metrics/cameras/{camera_id}/heatmap?from_date=today&to_date=tomorrow") assert response.status_code == 400 assert response.json() == {'detail': [{'loc': ['query', 'from_date'], 'msg': '' 'invalid date format', 'type': 'value_error.date'}, {'loc': ['query', 'to_date'], 'msg': 'invalid date format', 'type': 'value_error.date'}], 'body': None} def test_try_get_one_heatmap_wrong_dates(self, config_rollback_cameras, heatmap_simulation): """from_date is after to_date""" camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id = camera["id"] response = client.get(f"/metrics/cameras/{camera_id}/heatmap?from_date=2020-09-20&to_date=2020-09-19") assert response.status_code == 400 def test_try_get_one_heatmap_only_from_date(self, config_rollback_cameras, heatmap_simulation): """ Note that here as we do not send to_date, default value will take place, and to_date will be date.today(). WARNING: We could not mock the date.today() when the function is called within default query parameters. So, we must be careful because the data range will be: "2021-01-10" - "today". """ camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id = camera["id"] from_date = "2021-01-10" response = client.get(f"/metrics/cameras/{camera_id}/heatmap?from_date={from_date}") assert response.status_code == 200 def test_try_get_one_heatmap_only_to_date(self, config_rollback_cameras, heatmap_simulation): """ Note that here as we do not send from_date, default value will take place, and from_date will be date.today(). WARNING: We could not mock the date.today() when the function is called within default query parameters. So, we must be careful because the data range will be: "date.today() - timedelta(days=date.today().weekday(), weeks=4)" - "2020-09-20" and this date range is probably wrong because from_date will be later than to_date. """ camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id = camera["id"] to_date = "2020-09-20" response = client.get(f"/metrics/cameras/{camera_id}/heatmap?to_date={to_date}") assert response.status_code == 400 # pytest -v api/tests/app/test_camera_metrics.py::TestsGetCameraDistancingLive class TestsGetCameraDistancingLive: """ Get Camera Distancing Live, GET /metrics/cameras/social-distancing/live """ """ Returns a report with live information about the social distancing infractions detected in the cameras. """ @pytest.mark.parametrize( "metric,expected", [ ("social-distancing", { 'time': '2021-02-19 13:37:58', 'trend': 0.05, 'detected_objects': 6, 'no_infringement': 5, 'low_infringement': 0, 'high_infringement': 1, 'critical_infringement': 0 }), ("face-mask-detections", { 'time': '2021-02-19 13:37:58', 'trend': 0.0, 'no_face': 10, 'face_with_mask': 0, 'face_without_mask': 0 }) ] ) def test_get_a_report_properly(self, config_rollback_cameras, metric, expected): camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id = camera["id"] response = client.get(f"/metrics/cameras/{metric}/live?cameras={camera_id}") assert response.json() == expected assert response.status_code == 200 @pytest.mark.parametrize( "metric,expected", [ ("social-distancing", { 'time': '2021-02-19 13:37:58', 'trend': 0.72, 'detected_objects': 20, 'no_infringement': 9, 'low_infringement': 7, 'high_infringement': 2, 'critical_infringement': 3 }), ("face-mask-detections", { 'time': '2021-02-19 13:37:58', 'trend': 0.52, 'no_face': 24, 'face_with_mask': 8, 'face_without_mask': 1 }) ] ) def test_get_a_report_two_valid_cameras(self, config_rollback_cameras, metric, expected): camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id_1 = camera["id"] camera_id_2 = camera_2["id"] response = client.get(f"/metrics/cameras/{metric}/live?cameras={camera_id_1},{camera_id_2}") assert response.json() == expected assert response.status_code == 200 @pytest.mark.parametrize( "metric,expected", [ ("social-distancing", {'detail': "Camera with id 'BAD_ID' does not exist"}), ("face-mask-detections", {'detail': "Camera with id 'BAD_ID' does not exist"}) ] ) def test_try_get_a_report_bad_id_camera(self, config_rollback_cameras, metric, expected): camera, camera_2, client, config_sample_path = config_rollback_cameras response = client.get(f"/metrics/cameras/{metric}/live?cameras=BAD_ID") assert response.json() == expected assert response.status_code == 404 # pytest -v api/tests/app/test_camera_metrics.py::TestsGetCameraDistancingHourlyReport class TestsGetCameraDistancingHourlyReport: """ Get Camera Distancing Hourly Report , GET /metrics/cameras/social-distancing/hourly """ """ Returns a hourly report (for the date specified) with information about the social distancing infractions detected in the cameras . """ @pytest.mark.parametrize( "metric,expected", [ ("social-distancing", { 'detected_objects': [54, 30, 19, 37, 27, 39, 44, 25, 51, 31, 47, 39, 16, 26, 67, 29, 36, 17, 31, 32, 19, 38, 34, 50], 'no_infringement': [13, 5, 2, 18, 5, 11, 10, 6, 14, 6, 17, 18, 4, 8, 17, 11, 3, 6, 7, 4, 6, 10, 11, 18], 'low_infringement': [10, 14, 4, 19, 11, 15, 7, 7, 11, 2, 1, 3, 10, 10, 19, 7, 15, 5, 5, 16, 4, 12, 13, 17], 'high_infringement': [16, 2, 3, 0, 8, 1, 16, 11, 12, 6, 15, 0, 0, 1, 14, 7, 10, 2, 1, 9, 8, 13, 0, 15], 'critical_infringement': [15, 9, 10, 0, 3, 12, 11, 1, 14, 17, 14, 18, 2, 7, 17, 4, 8, 4, 18, 3, 1, 3, 10, 0], 'hours': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23] }), ("face-mask-detections", { 'no_face': [3, 3, 9, 2, 8, 2, 9, 8, 8, 0, 1, 2, 4, 6, 6, 2, 5, 2, 0, 0, 8, 3, 1, 2], 'face_with_mask': [5, 4, 6, 9, 2, 3, 9, 7, 7, 3, 8, 3, 6, 7, 4, 2, 0, 1, 4, 1, 9, 5, 1, 4], 'face_without_mask': [2, 6, 0, 8, 7, 7, 9, 1, 9, 8, 6, 4, 5, 7, 1, 0, 7, 5, 3, 3, 3, 8, 6, 5], 'hours': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23] }) ] ) def test_get_an_hourly_report_properly(self, config_rollback_cameras, metric, expected): camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id = camera["id"] date = "2021-02-25" response = client.get(f"/metrics/cameras/{metric}/hourly?cameras={camera_id}&date={date}") assert response.status_code == 200 assert response.json() == expected @pytest.mark.parametrize( "metric,expected", [ ("social-distancing", { 'detected_objects': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'no_infringement': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'low_infringement': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'high_infringement': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'critical_infringement': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'hours': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23] }), ("face-mask-detections", { 'no_face': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'face_with_mask': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'face_without_mask': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'hours': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23] }) ] ) def test_get_an_hourly_report_properly_II_less_than_23_hours(self, config_rollback_cameras, metric, expected): camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id = camera["id"] date = "2021-02-19" response = client.get(f"/metrics/cameras/{metric}/hourly?cameras={camera_id}&date={date}") assert response.status_code == 200 assert response.json() == expected @pytest.mark.parametrize( "metric,expected", [ ("social-distancing", { 'detected_objects': [108, 60, 38, 74, 54, 78, 88, 50, 102, 62, 94, 78, 32, 52, 134, 58, 72, 34, 62, 64, 38, 76, 68, 100], 'no_infringement': [26, 10, 4, 36, 10, 22, 20, 12, 28, 12, 34, 36, 8, 16, 34, 22, 6, 12, 14, 8, 12, 20, 22, 36], 'low_infringement': [20, 28, 8, 38, 22, 30, 14, 14, 22, 4, 2, 6, 20, 20, 38, 14, 30, 10, 10, 32, 8, 24, 26, 34], 'high_infringement': [32, 4, 6, 0, 16, 2, 32, 22, 24, 12, 30, 0, 0, 2, 28, 14, 20, 4, 2, 18, 16, 26, 0, 30], 'critical_infringement': [30, 18, 20, 0, 6, 24, 22, 2, 28, 34, 28, 36, 4, 14, 34, 8, 16, 8, 36, 6, 2, 6, 20, 0], 'hours': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]} ), ("face-mask-detections", { 'no_face': [6, 6, 18, 4, 16, 4, 18, 16, 16, 0, 2, 4, 8, 12, 12, 4, 10, 4, 0, 0, 16, 6, 2, 4], 'face_with_mask': [10, 8, 12, 18, 4, 6, 18, 14, 14, 6, 16, 6, 12, 14, 8, 4, 0, 2, 8, 2, 18, 10, 2, 8], 'face_without_mask': [4, 12, 0, 16, 14, 14, 18, 2, 18, 16, 12, 8, 10, 14, 2, 0, 14, 10, 6, 6, 6, 16, 12, 10], 'hours': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23] }) ] ) def test_get_hourly_report_two_dates(self, config_rollback_cameras, metric, expected): camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id = camera["id"] camera_id_2 = camera["id"] date = "2021-02-25" response = client.get(f"/metrics/cameras/{metric}/hourly?cameras={camera_id},{camera_id_2}&date={date}") assert response.status_code == 200 assert response.json() == expected @pytest.mark.parametrize( "metric,expected", [ ("social-distancing", {'detail': "Camera with id 'BAD_ID' does not exist"}), ("face-mask-detections", {'detail': "Camera with id 'BAD_ID' does not exist"}) ] ) def test_try_get_hourly_report_non_existent_id(self, config_rollback_cameras, metric, expected): camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id = 'BAD_ID' date = "2021-02-25" response = client.get(f"/metrics/cameras/{metric}/hourly?cameras={camera_id}&date={date}") assert response.status_code == 404 assert response.json() == expected @pytest.mark.parametrize( "metric", ["social-distancing", "face-mask-detections"] ) def test_try_get_hourly_report_bad_date_format(self, config_rollback_cameras, metric): camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id = camera['id'] date = "WRONG_DATE" response = client.get(f"/metrics/cameras/{metric}/hourly?cameras={camera_id}&date={date}") assert response.status_code == 400 @pytest.mark.parametrize( "metric,expected", [ ("social-distancing", { 'detected_objects': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'no_infringement': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'low_infringement': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'high_infringement': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'critical_infringement': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'hours': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23] }), ("face-mask-detections", { 'no_face': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'face_with_mask': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'face_without_mask': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'hours': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23] }) ] ) def test_try_get_hourly_report_non_existent_date(self, config_rollback_cameras, metric, expected): camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id = camera['id'] date = "2003-05-24" response = client.get(f"/metrics/cameras/{metric}/hourly?cameras={camera_id}&date={date}") assert response.status_code == 200 # Since no files with the specified date were found, no objects were added to the report. assert response.json() == expected @pytest.mark.parametrize( "metric,expected", [ ("social-distancing", {'detail': "Camera with id 'BAD_ID' does not exist"}), ("face-mask-detections", {'detail': "Camera with id 'BAD_ID' does not exist"}) ] ) def test_try_get_hourly_report_two_dates_one_of_them_bad_id(self, config_rollback_cameras, metric, expected): camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id = camera["id"] camera_id_2 = 'BAD_ID' date = "2021-02-25" response = client.get(f"/metrics/cameras/{metric}/hourly?cameras={camera_id},{camera_id_2}&date={date}") assert response.status_code == 404 assert response.json() == expected # pytest -v api/tests/app/test_camera_metrics.py::TestsGetCameraDistancingDailyReport class TestsGetCameraDistancingDailyReport: """ Get Camera Distancing Daily Report , GET /metrics/cameras/social-distancing/daily""" """ Returns a daily report (for the date range specified) with information about the social distancing infractions detected in the cameras. """ @pytest.mark.parametrize( "metric,expected", [ ("social-distancing", { 'detected_objects': [0, 0, 148, 179], 'no_infringement': [0, 0, 136, 139], 'low_infringement': [0, 0, 0, 19], 'high_infringement': [0, 0, 5, 17], 'critical_infringement': [0, 0, 7, 4], 'dates': ['2020-09-20', '2020-09-21', '2020-09-22', '2020-09-23'] }), ("face-mask-detections", { 'no_face': [0, 0, 18, 18], 'face_with_mask': [0, 0, 106, 135], 'face_without_mask': [0, 0, 26, 30], 'dates': ['2020-09-20', '2020-09-21', '2020-09-22', '2020-09-23']}) ] ) def test_get_a_daily_report_properly(self, config_rollback_cameras, metric, expected): camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id = camera["id"] to_date = "2020-09-23" from_date = "2020-09-20" response = client.get( f"/metrics/cameras/{metric}/daily?cameras={camera_id}&from_date={from_date}&to_date={to_date}") assert response.status_code == 200 assert response.json() == expected @pytest.mark.parametrize( "metric,expected", [ ("social-distancing", { 'detected_objects': [0], 'no_infringement': [0], 'low_infringement': [0], 'high_infringement': [0], 'critical_infringement': [0], 'dates': ['2020-09-20'] }), ("face-mask-detections", { 'no_face': [0], 'face_with_mask': [0], 'face_without_mask': [0], 'dates': ['2020-09-20']}) ] ) def test_get_a_daily_report_properly_one_day(self, config_rollback_cameras, metric, expected): camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id = camera["id"] date = "2020-09-20" response = client.get( f"/metrics/cameras/{metric}/daily?cameras={camera_id}&from_date={date}&to_date={date}") assert response.status_code == 200 assert response.json() == expected @pytest.mark.parametrize( "metric,expected", [ ("social-distancing", { 'detected_objects': [104, 120, 161, 301], 'no_infringement': [5, 35, 143, 183], 'low_infringement': [57, 42, 2, 87], 'high_infringement': [42, 43, 9, 27], 'critical_infringement': [0, 0, 7, 4], 'dates': ['2020-09-20', '2020-09-21', '2020-09-22', '2020-09-23'] }), ("face-mask-detections", { 'no_face': [85, 77, 114, 41], 'face_with_mask': [36, 76, 188, 170], 'face_without_mask': [23, 33, 39, 128], 'dates': ['2020-09-20', '2020-09-21', '2020-09-22', '2020-09-23'] }) ] ) def test_get_a_daily_report_properly_two_cameras(self, config_rollback_cameras, metric, expected): camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id = camera["id"] camera_id_2 = camera_2["id"] to_date = "2020-09-23" from_date = "2020-09-20" response = client.get( f"/metrics/cameras/{metric}/daily?cameras={camera_id},{camera_id_2}&from_date={from_date}&to_date={to_date}" ) assert response.status_code == 200 assert response.json() == expected @pytest.mark.parametrize( "metric,expected", [ ("social-distancing", {'detail': "Camera with id 'BAD_ID' does not exist"}), ("face-mask-detections", {'detail': "Camera with id 'BAD_ID' does not exist"}) ] ) def test_try_get_a_daily_report_bad_id(self, config_rollback_cameras, metric, expected): camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id = 'BAD_ID' response = client.get( f"/metrics/cameras/{metric}/daily?cameras={camera_id}&from_date=2020-09-20&to_date=2020-09-23") assert response.status_code == 404 assert response.json() == expected @pytest.mark.parametrize( "metric", ["social-distancing", "face-mask-detections"] ) def test_try_get_a_daily_report_bad_dates(self, config_rollback_cameras, metric): camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id = camera["id"] from_date = "BAD_DATE" to_date = "BAD_DATE" response = client.get( f"/metrics/cameras/{metric}/daily?cameras={camera_id}&from_date={from_date}&to_date={to_date}") assert response.status_code == 400 @pytest.mark.parametrize( "metric,expected", [ ("social-distancing", { 'detected_objects': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'no_infringement': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'low_infringement': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'high_infringement': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'critical_infringement': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'dates': ['2003-05-18', '2003-05-19', '2003-05-20', '2003-05-21', '2003-05-22', '2003-05-23', '2003-05-24', '2003-05-25', '2003-05-26', '2003-05-27', '2003-05-28'] }), ("face-mask-detections", { 'no_face': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'face_with_mask': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'face_without_mask': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'dates': ['2003-05-18', '2003-05-19', '2003-05-20', '2003-05-21', '2003-05-22', '2003-05-23', '2003-05-24', '2003-05-25', '2003-05-26', '2003-05-27', '2003-05-28'] }) ] ) def test_try_get_a_daily_report_no_reports_for_dates(self, config_rollback_cameras, metric, expected): camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id = camera["id"] from_date = "2003-05-18" to_date = "2003-05-28" response = client.get( f"/metrics/cameras/{metric}/daily?cameras={camera_id}&from_date={from_date}&to_date={to_date}") assert response.status_code == 200 assert response.json() == expected @pytest.mark.parametrize( "metric", ["social-distancing", "face-mask-detections"] ) def test_try_get_a_daily_report_wrong_dates(self, config_rollback_cameras, metric): """from_date doesn't come before to_date""" camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id = camera["id"] from_date = "2020-09-20" to_date = "2020-09-10" response = client.get( f"/metrics/cameras/{metric}/daily?cameras={camera_id}&from_date={from_date}&to_date={to_date}") assert response.status_code == 400 @pytest.mark.parametrize( "metric", ["social-distancing", "face-mask-detections"] ) def test_try_get_a_daily_report_only_from_date(self, config_rollback_cameras, metric): """ Note that here as we do not send to_date, default value will take place, and to_date will be date.today(). WARNING: We could not mock the date.today() when the function is called within default query parameters. So, we must be careful because the data range will be: "2021-01-10" - "today". """ camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id = camera["id"] from_date = "2021-01-10" response = client.get(f"/metrics/cameras/{metric}/daily?cameras={camera_id}&from_date={from_date}") assert response.status_code == 200 @pytest.mark.parametrize( "metric", ["social-distancing", "face-mask-detections"] ) def test_try_get_a_daily_report_only_to_date(self, config_rollback_cameras, metric): """ Note that here as we do not send from_date, default value will take place, and from_date will be date.today(). WARNING: We could not mock the date.today() when the function is called within default query parameters. So, we must be careful because the data range will be: "date.today() - timedelta(days=3)" - "2020-09-20" and this date range is probably wrong because from_date will be later than to_date. """ camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id = camera["id"] to_date = "2020-09-20" response = client.get(f"/metrics/cameras/{metric}/daily?cameras={camera_id}&to_date={to_date}") assert response.status_code == 400 # pytest -v api/tests/app/test_camera_metrics.py::TestsGetCameraDistancingWeeklyReport class TestsGetCameraDistancingWeeklyReport: """ Get Camera Distancing Weekly Report , GET /metrics/cameras/social-distancing/weekly """ """ Returns a weekly report (for the date range specified) with information about the social distancing infractions detected in the cameras. If weeks is provided and is a positive number: from_date and to_date are ignored. Report spans from weeks*7 + 1 days ago to yesterday. Taking yesterday as the end of week. Else: Report spans from from_Date to to_date. Taking Sunday as the end of week """ @pytest.mark.parametrize( "metric,expected", [ ("social-distancing", { 'detected_objects': [0, 327], 'no_infringement': [0, 275], 'low_infringement': [0, 19], 'high_infringement': [0, 22], 'critical_infringement': [0, 11], 'weeks': ['2020-09-20 2020-09-20', '2020-09-21 2020-09-23'] }), ("face-mask-detections", { 'no_face': [0, 36], 'face_with_mask': [0, 241], 'face_without_mask': [0, 56], 'weeks': ['2020-09-20 2020-09-20', '2020-09-21 2020-09-23'] }) ] ) def test_get_a_weekly_report_properly(self, config_rollback_cameras, metric, expected): """ Given date range spans two weeks. Week 1: 2020-9-14 2020-9-20 Week 2: 2020-9-21 2020-9-27 """ camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id = camera["id"] from_date = "2020-09-20" to_date = "2020-09-23" response = client.get( f"/metrics/cameras/{metric}/weekly?cameras={camera_id}&from_date={from_date}&to_date={to_date}") assert response.status_code == 200 assert response.json() == expected @pytest.mark.parametrize( "metric,expected", [ ("social-distancing", { 'detected_objects': [714], 'no_infringement': [555], 'low_infringement': [73], 'high_infringement': [55], 'critical_infringement': [30], 'weeks': ['2020-09-21 2020-09-27'] }), ("face-mask-detections", { 'no_face': [85], 'face_with_mask': [519], 'face_without_mask': [171], 'weeks': ['2020-09-21 2020-09-27'] }) ] ) def test_get_a_weekly_report_properly_II(self, config_rollback_cameras, metric, expected): """ Given date range spans only one whole week. Week 1: 2020-9-21 2020-9-27 """ camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id = camera["id"] from_date = "2020-09-21" to_date = "2020-09-27" response = client.get( f"/metrics/cameras/{metric}/weekly?cameras={camera_id}&from_date={from_date}&to_date={to_date}") assert response.status_code == 200 assert response.json() == expected @pytest.mark.parametrize( "metric,expected", [ ("social-distancing", { 'detected_objects': [535, 754, 714, 714], 'no_infringement': [416, 622, 555, 555], 'low_infringement': [54, 59, 73, 73], 'high_infringement': [38, 56, 55, 55], 'critical_infringement': [26, 19, 30, 30], 'weeks': ['2020-09-02 2020-09-08', '2020-09-09 2020-09-15', '2020-09-16 2020-09-22', '2020-09-23 2020-09-29'] }), ("face-mask-detections", { 'no_face': [88, 85, 106, 85], 'face_with_mask': [310, 519, 445, 519], 'face_without_mask': [150, 171, 180, 171], 'weeks': ['2020-09-02 2020-09-08', '2020-09-09 2020-09-15', '2020-09-16 2020-09-22', '2020-09-23 2020-09-29'] }) ] ) @freeze_time("2020-09-30") def test_get_a_weekly_report_properly_weeks_value(self, config_rollback_cameras, metric, expected): """ Here we mock datetime.date.today() to a more convenient date set in @freeze_time("2020-09-30") """ camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id = camera["id"] weeks = 4 response = client.get( f"/metrics/cameras/{metric}/weekly?cameras={camera_id}&weeks={weeks}") assert response.status_code == 200 assert response.json() == expected @pytest.mark.parametrize( "metric,expected", [ ("social-distancing", { 'detected_objects': [0, 0, 0, 0, 0], 'no_infringement': [0, 0, 0, 0, 0], 'low_infringement': [0, 0, 0, 0, 0], 'high_infringement': [0, 0, 0, 0, 0], 'critical_infringement': [0, 0, 0, 0, 0] }), ("face-mask-detections", { 'no_face': [0, 0, 0, 0, 0], 'face_with_mask': [0, 0, 0, 0, 0], 'face_without_mask': [0, 0, 0, 0, 0] }) ] ) def test_get_a_weekly_report_no_dates_or_week_values(self, config_rollback_cameras, metric, expected): """ WARNING: We could not mock the date.today() when the function is called within default query parameters. So, we must be careful because the data range will be: "date.today() - timedelta(days=date.today().weekday(), weeks=4)" - "date.today()" and this date range (4 weeks ago from today) should never have values for any camera in order to pass the test. Moreover, we do not assert response.json()["weeks"] because will change depending on the date. """ camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id = camera["id"] response = client.get( f"/metrics/cameras/{metric}/weekly?cameras={camera_id}") assert response.status_code == 200 for key in expected: assert response.json()[key] == expected[key] @pytest.mark.parametrize( "metric", ["social-distancing", "face-mask-detections"] ) @freeze_time("2020-09-30") def test_try_get_a_weekly_report_properly_weeks_value_wrong(self, config_rollback_cameras, metric): """ Here we mock datetime.date.today() to a more convenient date set in @freeze_time("2020-09-30") """ camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id = camera["id"] weeks = "WRONG" response = client.get( f"/metrics/cameras/{metric}/weekly?cameras={camera_id}&weeks={weeks}") assert response.status_code == 400 @pytest.mark.parametrize( "metric,expected", [ ("social-distancing", { 'detected_objects': [535, 754, 714, 714], 'no_infringement': [416, 622, 555, 555], 'low_infringement': [54, 59, 73, 73], 'high_infringement': [38, 56, 55, 55], 'critical_infringement': [26, 19, 30, 30], 'weeks': ['2020-09-02 2020-09-08', '2020-09-09 2020-09-15', '2020-09-16 2020-09-22', '2020-09-23 2020-09-29'] }), ("face-mask-detections", { 'no_face': [88, 85, 106, 85], 'face_with_mask': [310, 519, 445, 519], 'face_without_mask': [150, 171, 180, 171], 'weeks': ['2020-09-02 2020-09-08', '2020-09-09 2020-09-15', '2020-09-16 2020-09-22', '2020-09-23 2020-09-29'] }) ] ) @freeze_time("2020-09-30") def test_get_a_weekly_report_properly_weeks_value_and_dates(self, config_rollback_cameras, metric, expected): """ Here we mock datetime.date.today() to a more convenient date set in @freeze_time("2012-01-01") In addition, query string weeks is given, but also from_date and to_date. So dates should be ignored. """ camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id = camera["id"] weeks = 4 from_date = "2020-09-21" to_date = "2020-09-27" response = client.get( f"/metrics/cameras/{metric}/weekly?cameras={camera_id}&weeks={weeks}&from_date={from_date}&" f"to_date={to_date}") assert response.status_code == 200 assert response.json() == expected @pytest.mark.parametrize( "metric,expected", [ ("social-distancing", {'detail': "Camera with id 'BAD_ID' does not exist"}), ("face-mask-detections", {'detail': "Camera with id 'BAD_ID' does not exist"}) ] ) def test_try_get_a_weekly_report_bad_id(self, config_rollback_cameras, metric, expected): camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id = 'BAD_ID' from_date = "2020-09-20" to_date = "2020-09-23" response = client.get( f"/metrics/cameras/{metric}/weekly?cameras={camera_id}&from_date={from_date}&to_date={to_date}") assert response.status_code == 404 assert response.json() == expected @pytest.mark.parametrize( "metric,expected", [ ("social-distancing", { 'detected_objects': [0, 0, 0, 0, 0], 'no_infringement': [0, 0, 0, 0, 0], 'low_infringement': [0, 0, 0, 0, 0], 'high_infringement': [0, 0, 0, 0, 0], 'critical_infringement': [0, 0, 0, 0, 0] }), ("face-mask-detections", { 'no_face': [0, 0, 0, 0, 0], 'face_with_mask': [0, 0, 0, 0, 0], 'face_without_mask': [0, 0, 0, 0, 0] }) ] ) def test_get_a_weekly_report_no_query_string(self, config_rollback_cameras, metric, expected): """ If no camera is provided, it will search all IDs for each existing camera. WARNING: We could not mock the date.today() when the function is called within default query parameters. So, we must be careful because the data range will be: "date.today() - timedelta(days=date.today().weekday(), weeks=4)" - "date.today()" and this date range (4 weeks ago from today) should never have values for any camera in order to pass the test. Moreover, we do not assert response.json()["weeks"] because will change depending on the date. """ camera, camera_2, client, config_sample_path = config_rollback_cameras response = client.get( f"/metrics/cameras/{metric}/weekly") assert response.status_code == 200 for key in expected: assert response.json()[key] == expected[key] @pytest.mark.parametrize( "metric", ["social-distancing", "face-mask-detections"] ) def test_try_get_a_weekly_report_bad_dates_format(self, config_rollback_cameras, metric): camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id = camera["id"] from_date = "BAD_DATE" to_date = "BAD_DATE" response = client.get( f"/metrics/cameras/{metric}/weekly?cameras={camera_id}&from_date={from_date}&to_date={to_date}") assert response.status_code == 400 @pytest.mark.parametrize( "metric,expected", [ ("social-distancing", { 'detected_objects': [0, 0, 0, 0, 0, 0], 'no_infringement': [0, 0, 0, 0, 0, 0], 'low_infringement': [0, 0, 0, 0, 0, 0], 'high_infringement': [0, 0, 0, 0, 0, 0], 'critical_infringement': [0, 0, 0, 0, 0, 0], 'weeks': ['2012-04-12 2012-04-15', '2012-04-16 2012-04-22', '2012-04-23 2012-04-29', '2012-04-30 2012-05-06', '2012-05-07 2012-05-13', '2012-05-14 2012-05-18'] }), ("face-mask-detections", { 'no_face': [0, 0, 0, 0, 0, 0], 'face_with_mask': [0, 0, 0, 0, 0, 0], 'face_without_mask': [0, 0, 0, 0, 0, 0], 'weeks': ['2012-04-12 2012-04-15', '2012-04-16 2012-04-22', '2012-04-23 2012-04-29', '2012-04-30 2012-05-06', '2012-05-07 2012-05-13', '2012-05-14 2012-05-18'] }) ] ) def test_try_get_a_weekly_report_non_existent_dates(self, config_rollback_cameras, metric, expected): camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id = camera["id"] from_date = "2012-04-12" to_date = "2012-05-18" response = client.get( f"/metrics/cameras/{metric}/weekly?cameras={camera_id}&from_date={from_date}&to_date={to_date}") assert response.status_code == 200 assert response.json() == expected @pytest.mark.parametrize( "metric", ["social-distancing", "face-mask-detections"] ) def test_try_get_a_weekly_report_invalid_range_of_dates(self, config_rollback_cameras, metric): """from_date is after to_date""" camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id = camera["id"] from_date = "2020-09-25" to_date = "2020-09-18" response = client.get( f"/metrics/cameras/{metric}/weekly?cameras={camera_id}&from_date={from_date}&to_date={to_date}") assert response.status_code == 400 @pytest.mark.parametrize( "metric,expected", [ ("social-distancing", { 'detected_objects': [104, 582], 'no_infringement': [5, 361], 'low_infringement': [57, 131], 'high_infringement': [42, 79], 'critical_infringement': [0, 11], 'weeks': ['2020-09-20 2020-09-20', '2020-09-21 2020-09-23'] }), ("face-mask-detections", { 'no_face': [85, 232], 'face_with_mask': [36, 434], 'face_without_mask': [23, 200], 'weeks': ['2020-09-20 2020-09-20', '2020-09-21 2020-09-23'] }) ] ) def test_try_get_a_weekly_report_no_id(self, config_rollback_cameras, metric, expected): """ If no camera is provided, it will search all IDs for each existing camera. No problem because we are mocking the date and we have the control over every existent camera. Unit is not broke. Our existing cameras are the ones that appeared in the config file of 'config_rollback_cameras' -> the ones from 'config-x86-openvino_MAIN' -> the ones with ids 49, 50 (cameras with ids 51 and 52 appear in another config file, so will not play here) """ camera, camera_2, client, config_sample_path = config_rollback_cameras from_date = "2020-09-20" to_date = "2020-09-23" response = client.get( f"/metrics/cameras/{metric}/weekly?from_date={from_date}&to_date={to_date}") assert response.status_code == 200 assert response.json() == expected @pytest.mark.parametrize( "metric", ["social-distancing", "face-mask-detections"] ) def test_try_get_a_weekly_report_only_from_date(self, config_rollback_cameras, metric): """ Note that here as we do not send to_date, default value will take place, and to_date will be date.today(). WARNING: We could not mock the date.today() when the function is called within default query parameters. So, we must be careful because the data range will be: "2021-01-10" - "today". """ camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id = camera["id"] from_date = "2021-01-10" response = client.get(f"/metrics/cameras/{metric}/weekly?cameras={camera_id}&from_date={from_date}") assert response.status_code == 200 @pytest.mark.parametrize( "metric", ["social-distancing", "face-mask-detections"] ) def test_try_get_a_weekly_report_only_to_date(self, config_rollback_cameras, metric): """ Note that here as we do not send from_date, default value will take place, and from_date will be date.today(). WARNING: We could not mock the date.today() when the function is called within default query parameters. So, we must be careful because the data range will be: "date.today() - timedelta(days=date.today().weekday(), weeks=4)" - "2020-09-20" and this date range is probably wrong because from_date will be later than to_date. """ camera, camera_2, client, config_sample_path = config_rollback_cameras camera_id = camera["id"] to_date = "2020-09-20" response = client.get(f"/metrics/cameras/{metric}/weekly?cameras={camera_id}&to_date={to_date}") assert response.status_code == 400
[ "numpy.add", "os.path.join", "pytest.mark.parametrize", "freezegun.freeze_time", "numpy.load" ]
[((7664, 8052), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""metric,expected"""', "[('social-distancing', {'time': '2021-02-19 13:37:58', 'trend': 0.05,\n 'detected_objects': 6, 'no_infringement': 5, 'low_infringement': 0,\n 'high_infringement': 1, 'critical_infringement': 0}), (\n 'face-mask-detections', {'time': '2021-02-19 13:37:58', 'trend': 0.0,\n 'no_face': 10, 'face_with_mask': 0, 'face_without_mask': 0})]"], {}), "('metric,expected', [('social-distancing', {'time':\n '2021-02-19 13:37:58', 'trend': 0.05, 'detected_objects': 6,\n 'no_infringement': 5, 'low_infringement': 0, 'high_infringement': 1,\n 'critical_infringement': 0}), ('face-mask-detections', {'time':\n '2021-02-19 13:37:58', 'trend': 0.0, 'no_face': 10, 'face_with_mask': 0,\n 'face_without_mask': 0})])\n", (7687, 8052), False, 'import pytest\n'), ((8685, 9076), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""metric,expected"""', "[('social-distancing', {'time': '2021-02-19 13:37:58', 'trend': 0.72,\n 'detected_objects': 20, 'no_infringement': 9, 'low_infringement': 7,\n 'high_infringement': 2, 'critical_infringement': 3}), (\n 'face-mask-detections', {'time': '2021-02-19 13:37:58', 'trend': 0.52,\n 'no_face': 24, 'face_with_mask': 8, 'face_without_mask': 1})]"], {}), "('metric,expected', [('social-distancing', {'time':\n '2021-02-19 13:37:58', 'trend': 0.72, 'detected_objects': 20,\n 'no_infringement': 9, 'low_infringement': 7, 'high_infringement': 2,\n 'critical_infringement': 3}), ('face-mask-detections', {'time':\n '2021-02-19 13:37:58', 'trend': 0.52, 'no_face': 24, 'face_with_mask': \n 8, 'face_without_mask': 1})])\n", (8708, 9076), False, 'import pytest\n'), ((9628, 9838), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""metric,expected"""', '[(\'social-distancing\', {\'detail\': "Camera with id \'BAD_ID\' does not exist"}\n ), (\'face-mask-detections\', {\'detail\':\n "Camera with id \'BAD_ID\' does not exist"})]'], {}), '(\'metric,expected\', [(\'social-distancing\', {\'detail\':\n "Camera with id \'BAD_ID\' does not exist"}), (\'face-mask-detections\', {\n \'detail\': "Camera with id \'BAD_ID\' does not exist"})])\n', (9651, 9838), False, 'import pytest\n'), ((10619, 11792), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""metric,expected"""', "[('social-distancing', {'detected_objects': [54, 30, 19, 37, 27, 39, 44, 25,\n 51, 31, 47, 39, 16, 26, 67, 29, 36, 17, 31, 32, 19, 38, 34, 50],\n 'no_infringement': [13, 5, 2, 18, 5, 11, 10, 6, 14, 6, 17, 18, 4, 8, 17,\n 11, 3, 6, 7, 4, 6, 10, 11, 18], 'low_infringement': [10, 14, 4, 19, 11,\n 15, 7, 7, 11, 2, 1, 3, 10, 10, 19, 7, 15, 5, 5, 16, 4, 12, 13, 17],\n 'high_infringement': [16, 2, 3, 0, 8, 1, 16, 11, 12, 6, 15, 0, 0, 1, 14,\n 7, 10, 2, 1, 9, 8, 13, 0, 15], 'critical_infringement': [15, 9, 10, 0, \n 3, 12, 11, 1, 14, 17, 14, 18, 2, 7, 17, 4, 8, 4, 18, 3, 1, 3, 10, 0],\n 'hours': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,\n 18, 19, 20, 21, 22, 23]}), ('face-mask-detections', {'no_face': [3, 3, \n 9, 2, 8, 2, 9, 8, 8, 0, 1, 2, 4, 6, 6, 2, 5, 2, 0, 0, 8, 3, 1, 2],\n 'face_with_mask': [5, 4, 6, 9, 2, 3, 9, 7, 7, 3, 8, 3, 6, 7, 4, 2, 0, 1,\n 4, 1, 9, 5, 1, 4], 'face_without_mask': [2, 6, 0, 8, 7, 7, 9, 1, 9, 8, \n 6, 4, 5, 7, 1, 0, 7, 5, 3, 3, 3, 8, 6, 5], 'hours': [0, 1, 2, 3, 4, 5, \n 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]})]"], {}), "('metric,expected', [('social-distancing', {\n 'detected_objects': [54, 30, 19, 37, 27, 39, 44, 25, 51, 31, 47, 39, 16,\n 26, 67, 29, 36, 17, 31, 32, 19, 38, 34, 50], 'no_infringement': [13, 5,\n 2, 18, 5, 11, 10, 6, 14, 6, 17, 18, 4, 8, 17, 11, 3, 6, 7, 4, 6, 10, 11,\n 18], 'low_infringement': [10, 14, 4, 19, 11, 15, 7, 7, 11, 2, 1, 3, 10,\n 10, 19, 7, 15, 5, 5, 16, 4, 12, 13, 17], 'high_infringement': [16, 2, 3,\n 0, 8, 1, 16, 11, 12, 6, 15, 0, 0, 1, 14, 7, 10, 2, 1, 9, 8, 13, 0, 15],\n 'critical_infringement': [15, 9, 10, 0, 3, 12, 11, 1, 14, 17, 14, 18, 2,\n 7, 17, 4, 8, 4, 18, 3, 1, 3, 10, 0], 'hours': [0, 1, 2, 3, 4, 5, 6, 7, \n 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]}), (\n 'face-mask-detections', {'no_face': [3, 3, 9, 2, 8, 2, 9, 8, 8, 0, 1, 2,\n 4, 6, 6, 2, 5, 2, 0, 0, 8, 3, 1, 2], 'face_with_mask': [5, 4, 6, 9, 2, \n 3, 9, 7, 7, 3, 8, 3, 6, 7, 4, 2, 0, 1, 4, 1, 9, 5, 1, 4],\n 'face_without_mask': [2, 6, 0, 8, 7, 7, 9, 1, 9, 8, 6, 4, 5, 7, 1, 0, 7,\n 5, 3, 3, 3, 8, 6, 5], 'hours': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, \n 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]})])\n", (10642, 11792), False, 'import pytest\n'), ((12593, 13692), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""metric,expected"""', "[('social-distancing', {'detected_objects': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, \n 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'no_infringement': [0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n 'low_infringement': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0], 'high_infringement': [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], 'critical_infringement':\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0\n ], 'hours': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, \n 17, 18, 19, 20, 21, 22, 23]}), ('face-mask-detections', {'no_face': [0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n 'face_with_mask': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0], 'face_without_mask': [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], 'hours': [0, 1, 2, 3, 4, 5, \n 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]})]"], {}), "('metric,expected', [('social-distancing', {\n 'detected_objects': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0], 'no_infringement': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'low_infringement': [0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n 'high_infringement': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0], 'critical_infringement': [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], 'hours': [0, 1, 2, 3, \n 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, \n 23]}), ('face-mask-detections', {'no_face': [0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'face_with_mask': [0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n 'face_without_mask': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0], 'hours': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, \n 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]})])\n", (12616, 13692), False, 'import pytest\n'), ((14325, 15562), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""metric,expected"""', "[('social-distancing', {'detected_objects': [108, 60, 38, 74, 54, 78, 88, \n 50, 102, 62, 94, 78, 32, 52, 134, 58, 72, 34, 62, 64, 38, 76, 68, 100],\n 'no_infringement': [26, 10, 4, 36, 10, 22, 20, 12, 28, 12, 34, 36, 8, \n 16, 34, 22, 6, 12, 14, 8, 12, 20, 22, 36], 'low_infringement': [20, 28,\n 8, 38, 22, 30, 14, 14, 22, 4, 2, 6, 20, 20, 38, 14, 30, 10, 10, 32, 8, \n 24, 26, 34], 'high_infringement': [32, 4, 6, 0, 16, 2, 32, 22, 24, 12, \n 30, 0, 0, 2, 28, 14, 20, 4, 2, 18, 16, 26, 0, 30],\n 'critical_infringement': [30, 18, 20, 0, 6, 24, 22, 2, 28, 34, 28, 36, \n 4, 14, 34, 8, 16, 8, 36, 6, 2, 6, 20, 0], 'hours': [0, 1, 2, 3, 4, 5, 6,\n 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]}), (\n 'face-mask-detections', {'no_face': [6, 6, 18, 4, 16, 4, 18, 16, 16, 0,\n 2, 4, 8, 12, 12, 4, 10, 4, 0, 0, 16, 6, 2, 4], 'face_with_mask': [10, 8,\n 12, 18, 4, 6, 18, 14, 14, 6, 16, 6, 12, 14, 8, 4, 0, 2, 8, 2, 18, 10, 2,\n 8], 'face_without_mask': [4, 12, 0, 16, 14, 14, 18, 2, 18, 16, 12, 8, \n 10, 14, 2, 0, 14, 10, 6, 6, 6, 16, 12, 10], 'hours': [0, 1, 2, 3, 4, 5,\n 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]})]"], {}), "('metric,expected', [('social-distancing', {\n 'detected_objects': [108, 60, 38, 74, 54, 78, 88, 50, 102, 62, 94, 78, \n 32, 52, 134, 58, 72, 34, 62, 64, 38, 76, 68, 100], 'no_infringement': [\n 26, 10, 4, 36, 10, 22, 20, 12, 28, 12, 34, 36, 8, 16, 34, 22, 6, 12, 14,\n 8, 12, 20, 22, 36], 'low_infringement': [20, 28, 8, 38, 22, 30, 14, 14,\n 22, 4, 2, 6, 20, 20, 38, 14, 30, 10, 10, 32, 8, 24, 26, 34],\n 'high_infringement': [32, 4, 6, 0, 16, 2, 32, 22, 24, 12, 30, 0, 0, 2, \n 28, 14, 20, 4, 2, 18, 16, 26, 0, 30], 'critical_infringement': [30, 18,\n 20, 0, 6, 24, 22, 2, 28, 34, 28, 36, 4, 14, 34, 8, 16, 8, 36, 6, 2, 6, \n 20, 0], 'hours': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n 16, 17, 18, 19, 20, 21, 22, 23]}), ('face-mask-detections', {'no_face':\n [6, 6, 18, 4, 16, 4, 18, 16, 16, 0, 2, 4, 8, 12, 12, 4, 10, 4, 0, 0, 16,\n 6, 2, 4], 'face_with_mask': [10, 8, 12, 18, 4, 6, 18, 14, 14, 6, 16, 6,\n 12, 14, 8, 4, 0, 2, 8, 2, 18, 10, 2, 8], 'face_without_mask': [4, 12, 0,\n 16, 14, 14, 18, 2, 18, 16, 12, 8, 10, 14, 2, 0, 14, 10, 6, 6, 6, 16, 12,\n 10], 'hours': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,\n 17, 18, 19, 20, 21, 22, 23]})])\n", (14348, 15562), False, 'import pytest\n'), ((16592, 16802), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""metric,expected"""', '[(\'social-distancing\', {\'detail\': "Camera with id \'BAD_ID\' does not exist"}\n ), (\'face-mask-detections\', {\'detail\':\n "Camera with id \'BAD_ID\' does not exist"})]'], {}), '(\'metric,expected\', [(\'social-distancing\', {\'detail\':\n "Camera with id \'BAD_ID\' does not exist"}), (\'face-mask-detections\', {\n \'detail\': "Camera with id \'BAD_ID\' does not exist"})])\n', (16615, 16802), False, 'import pytest\n'), ((17280, 17365), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""metric"""', "['social-distancing', 'face-mask-detections']"], {}), "('metric', ['social-distancing', 'face-mask-detections']\n )\n", (17303, 17365), False, 'import pytest\n'), ((17764, 18863), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""metric,expected"""', "[('social-distancing', {'detected_objects': [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], 'no_infringement': [0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n 'low_infringement': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0], 'high_infringement': [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], 'critical_infringement':\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0\n ], 'hours': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, \n 17, 18, 19, 20, 21, 22, 23]}), ('face-mask-detections', {'no_face': [0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n 'face_with_mask': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0], 'face_without_mask': [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], 'hours': [0, 1, 2, 3, 4, 5, \n 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]})]"], {}), "('metric,expected', [('social-distancing', {\n 'detected_objects': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0], 'no_infringement': [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], 'low_infringement': [0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n 'high_infringement': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0], 'critical_infringement': [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], 'hours': [0, 1, 2, 3, \n 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, \n 23]}), ('face-mask-detections', {'no_face': [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], 'face_with_mask': [0, 0, \n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n 'face_without_mask': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0], 'hours': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, \n 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]})])\n", (17787, 18863), False, 'import pytest\n'), ((19581, 19791), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""metric,expected"""', '[(\'social-distancing\', {\'detail\': "Camera with id \'BAD_ID\' does not exist"}\n ), (\'face-mask-detections\', {\'detail\':\n "Camera with id \'BAD_ID\' does not exist"})]'], {}), '(\'metric,expected\', [(\'social-distancing\', {\'detail\':\n "Camera with id \'BAD_ID\' does not exist"}), (\'face-mask-detections\', {\n \'detail\': "Camera with id \'BAD_ID\' does not exist"})])\n', (19604, 19791), False, 'import pytest\n'), ((20715, 21262), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""metric,expected"""', "[('social-distancing', {'detected_objects': [0, 0, 148, 179],\n 'no_infringement': [0, 0, 136, 139], 'low_infringement': [0, 0, 0, 19],\n 'high_infringement': [0, 0, 5, 17], 'critical_infringement': [0, 0, 7, \n 4], 'dates': ['2020-09-20', '2020-09-21', '2020-09-22', '2020-09-23']}),\n ('face-mask-detections', {'no_face': [0, 0, 18, 18], 'face_with_mask':\n [0, 0, 106, 135], 'face_without_mask': [0, 0, 26, 30], 'dates': [\n '2020-09-20', '2020-09-21', '2020-09-22', '2020-09-23']})]"], {}), "('metric,expected', [('social-distancing', {\n 'detected_objects': [0, 0, 148, 179], 'no_infringement': [0, 0, 136, \n 139], 'low_infringement': [0, 0, 0, 19], 'high_infringement': [0, 0, 5,\n 17], 'critical_infringement': [0, 0, 7, 4], 'dates': ['2020-09-20',\n '2020-09-21', '2020-09-22', '2020-09-23']}), ('face-mask-detections', {\n 'no_face': [0, 0, 18, 18], 'face_with_mask': [0, 0, 106, 135],\n 'face_without_mask': [0, 0, 26, 30], 'dates': ['2020-09-20',\n '2020-09-21', '2020-09-22', '2020-09-23']})])\n", (20738, 21262), False, 'import pytest\n'), ((21883, 22249), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""metric,expected"""', "[('social-distancing', {'detected_objects': [0], 'no_infringement': [0],\n 'low_infringement': [0], 'high_infringement': [0],\n 'critical_infringement': [0], 'dates': ['2020-09-20']}), (\n 'face-mask-detections', {'no_face': [0], 'face_with_mask': [0],\n 'face_without_mask': [0], 'dates': ['2020-09-20']})]"], {}), "('metric,expected', [('social-distancing', {\n 'detected_objects': [0], 'no_infringement': [0], 'low_infringement': [0\n ], 'high_infringement': [0], 'critical_infringement': [0], 'dates': [\n '2020-09-20']}), ('face-mask-detections', {'no_face': [0],\n 'face_with_mask': [0], 'face_without_mask': [0], 'dates': ['2020-09-20']})]\n )\n", (21906, 22249), False, 'import pytest\n'), ((22809, 23376), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""metric,expected"""', "[('social-distancing', {'detected_objects': [104, 120, 161, 301],\n 'no_infringement': [5, 35, 143, 183], 'low_infringement': [57, 42, 2, \n 87], 'high_infringement': [42, 43, 9, 27], 'critical_infringement': [0,\n 0, 7, 4], 'dates': ['2020-09-20', '2020-09-21', '2020-09-22',\n '2020-09-23']}), ('face-mask-detections', {'no_face': [85, 77, 114, 41],\n 'face_with_mask': [36, 76, 188, 170], 'face_without_mask': [23, 33, 39,\n 128], 'dates': ['2020-09-20', '2020-09-21', '2020-09-22', '2020-09-23']})]"], {}), "('metric,expected', [('social-distancing', {\n 'detected_objects': [104, 120, 161, 301], 'no_infringement': [5, 35, \n 143, 183], 'low_infringement': [57, 42, 2, 87], 'high_infringement': [\n 42, 43, 9, 27], 'critical_infringement': [0, 0, 7, 4], 'dates': [\n '2020-09-20', '2020-09-21', '2020-09-22', '2020-09-23']}), (\n 'face-mask-detections', {'no_face': [85, 77, 114, 41], 'face_with_mask':\n [36, 76, 188, 170], 'face_without_mask': [23, 33, 39, 128], 'dates': [\n '2020-09-20', '2020-09-21', '2020-09-22', '2020-09-23']})])\n", (22832, 23376), False, 'import pytest\n'), ((24095, 24305), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""metric,expected"""', '[(\'social-distancing\', {\'detail\': "Camera with id \'BAD_ID\' does not exist"}\n ), (\'face-mask-detections\', {\'detail\':\n "Camera with id \'BAD_ID\' does not exist"})]'], {}), '(\'metric,expected\', [(\'social-distancing\', {\'detail\':\n "Camera with id \'BAD_ID\' does not exist"}), (\'face-mask-detections\', {\n \'detail\': "Camera with id \'BAD_ID\' does not exist"})])\n', (24118, 24305), False, 'import pytest\n'), ((24787, 24872), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""metric"""', "['social-distancing', 'face-mask-detections']"], {}), "('metric', ['social-distancing', 'face-mask-detections']\n )\n", (24810, 24872), False, 'import pytest\n'), ((25338, 26255), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""metric,expected"""', "[('social-distancing', {'detected_objects': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, \n 0], 'no_infringement': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n 'low_infringement': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n 'high_infringement': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n 'critical_infringement': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'dates': [\n '2003-05-18', '2003-05-19', '2003-05-20', '2003-05-21', '2003-05-22',\n '2003-05-23', '2003-05-24', '2003-05-25', '2003-05-26', '2003-05-27',\n '2003-05-28']}), ('face-mask-detections', {'no_face': [0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0], 'face_with_mask': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n 'face_without_mask': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'dates': [\n '2003-05-18', '2003-05-19', '2003-05-20', '2003-05-21', '2003-05-22',\n '2003-05-23', '2003-05-24', '2003-05-25', '2003-05-26', '2003-05-27',\n '2003-05-28']})]"], {}), "('metric,expected', [('social-distancing', {\n 'detected_objects': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n 'no_infringement': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n 'low_infringement': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n 'high_infringement': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n 'critical_infringement': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'dates': [\n '2003-05-18', '2003-05-19', '2003-05-20', '2003-05-21', '2003-05-22',\n '2003-05-23', '2003-05-24', '2003-05-25', '2003-05-26', '2003-05-27',\n '2003-05-28']}), ('face-mask-detections', {'no_face': [0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0], 'face_with_mask': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n 'face_without_mask': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'dates': [\n '2003-05-18', '2003-05-19', '2003-05-20', '2003-05-21', '2003-05-22',\n '2003-05-23', '2003-05-24', '2003-05-25', '2003-05-26', '2003-05-27',\n '2003-05-28']})])\n", (25361, 26255), False, 'import pytest\n'), ((26997, 27082), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""metric"""', "['social-distancing', 'face-mask-detections']"], {}), "('metric', ['social-distancing', 'face-mask-detections']\n )\n", (27020, 27082), False, 'import pytest\n'), ((27607, 27692), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""metric"""', "['social-distancing', 'face-mask-detections']"], {}), "('metric', ['social-distancing', 'face-mask-detections']\n )\n", (27630, 27692), False, 'import pytest\n'), ((28445, 28530), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""metric"""', "['social-distancing', 'face-mask-detections']"], {}), "('metric', ['social-distancing', 'face-mask-detections']\n )\n", (28468, 28530), False, 'import pytest\n'), ((30070, 30546), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""metric,expected"""', "[('social-distancing', {'detected_objects': [0, 327], 'no_infringement': [0,\n 275], 'low_infringement': [0, 19], 'high_infringement': [0, 22],\n 'critical_infringement': [0, 11], 'weeks': ['2020-09-20 2020-09-20',\n '2020-09-21 2020-09-23']}), ('face-mask-detections', {'no_face': [0, 36\n ], 'face_with_mask': [0, 241], 'face_without_mask': [0, 56], 'weeks': [\n '2020-09-20 2020-09-20', '2020-09-21 2020-09-23']})]"], {}), "('metric,expected', [('social-distancing', {\n 'detected_objects': [0, 327], 'no_infringement': [0, 275],\n 'low_infringement': [0, 19], 'high_infringement': [0, 22],\n 'critical_infringement': [0, 11], 'weeks': ['2020-09-20 2020-09-20',\n '2020-09-21 2020-09-23']}), ('face-mask-detections', {'no_face': [0, 36\n ], 'face_with_mask': [0, 241], 'face_without_mask': [0, 56], 'weeks': [\n '2020-09-20 2020-09-20', '2020-09-21 2020-09-23']})])\n", (30093, 30546), False, 'import pytest\n'), ((31372, 31770), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""metric,expected"""', "[('social-distancing', {'detected_objects': [714], 'no_infringement': [555],\n 'low_infringement': [73], 'high_infringement': [55],\n 'critical_infringement': [30], 'weeks': ['2020-09-21 2020-09-27']}), (\n 'face-mask-detections', {'no_face': [85], 'face_with_mask': [519],\n 'face_without_mask': [171], 'weeks': ['2020-09-21 2020-09-27']})]"], {}), "('metric,expected', [('social-distancing', {\n 'detected_objects': [714], 'no_infringement': [555], 'low_infringement':\n [73], 'high_infringement': [55], 'critical_infringement': [30], 'weeks':\n ['2020-09-21 2020-09-27']}), ('face-mask-detections', {'no_face': [85],\n 'face_with_mask': [519], 'face_without_mask': [171], 'weeks': [\n '2020-09-21 2020-09-27']})])\n", (31395, 31770), False, 'import pytest\n'), ((32575, 33250), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""metric,expected"""', "[('social-distancing', {'detected_objects': [535, 754, 714, 714],\n 'no_infringement': [416, 622, 555, 555], 'low_infringement': [54, 59, \n 73, 73], 'high_infringement': [38, 56, 55, 55], 'critical_infringement':\n [26, 19, 30, 30], 'weeks': ['2020-09-02 2020-09-08',\n '2020-09-09 2020-09-15', '2020-09-16 2020-09-22',\n '2020-09-23 2020-09-29']}), ('face-mask-detections', {'no_face': [88, \n 85, 106, 85], 'face_with_mask': [310, 519, 445, 519],\n 'face_without_mask': [150, 171, 180, 171], 'weeks': [\n '2020-09-02 2020-09-08', '2020-09-09 2020-09-15',\n '2020-09-16 2020-09-22', '2020-09-23 2020-09-29']})]"], {}), "('metric,expected', [('social-distancing', {\n 'detected_objects': [535, 754, 714, 714], 'no_infringement': [416, 622,\n 555, 555], 'low_infringement': [54, 59, 73, 73], 'high_infringement': [\n 38, 56, 55, 55], 'critical_infringement': [26, 19, 30, 30], 'weeks': [\n '2020-09-02 2020-09-08', '2020-09-09 2020-09-15',\n '2020-09-16 2020-09-22', '2020-09-23 2020-09-29']}), (\n 'face-mask-detections', {'no_face': [88, 85, 106, 85], 'face_with_mask':\n [310, 519, 445, 519], 'face_without_mask': [150, 171, 180, 171],\n 'weeks': ['2020-09-02 2020-09-08', '2020-09-09 2020-09-15',\n '2020-09-16 2020-09-22', '2020-09-23 2020-09-29']})])\n", (32598, 33250), False, 'import pytest\n'), ((33464, 33489), 'freezegun.freeze_time', 'freeze_time', (['"""2020-09-30"""'], {}), "('2020-09-30')\n", (33475, 33489), False, 'from freezegun import freeze_time\n'), ((34113, 34523), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""metric,expected"""', "[('social-distancing', {'detected_objects': [0, 0, 0, 0, 0],\n 'no_infringement': [0, 0, 0, 0, 0], 'low_infringement': [0, 0, 0, 0, 0],\n 'high_infringement': [0, 0, 0, 0, 0], 'critical_infringement': [0, 0, 0,\n 0, 0]}), ('face-mask-detections', {'no_face': [0, 0, 0, 0, 0],\n 'face_with_mask': [0, 0, 0, 0, 0], 'face_without_mask': [0, 0, 0, 0, 0]})]"], {}), "('metric,expected', [('social-distancing', {\n 'detected_objects': [0, 0, 0, 0, 0], 'no_infringement': [0, 0, 0, 0, 0],\n 'low_infringement': [0, 0, 0, 0, 0], 'high_infringement': [0, 0, 0, 0, \n 0], 'critical_infringement': [0, 0, 0, 0, 0]}), ('face-mask-detections',\n {'no_face': [0, 0, 0, 0, 0], 'face_with_mask': [0, 0, 0, 0, 0],\n 'face_without_mask': [0, 0, 0, 0, 0]})])\n", (34136, 34523), False, 'import pytest\n'), ((35620, 35705), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""metric"""', "['social-distancing', 'face-mask-detections']"], {}), "('metric', ['social-distancing', 'face-mask-detections']\n )\n", (35643, 35705), False, 'import pytest\n'), ((35728, 35753), 'freezegun.freeze_time', 'freeze_time', (['"""2020-09-30"""'], {}), "('2020-09-30')\n", (35739, 35753), False, 'from freezegun import freeze_time\n'), ((36286, 36961), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""metric,expected"""', "[('social-distancing', {'detected_objects': [535, 754, 714, 714],\n 'no_infringement': [416, 622, 555, 555], 'low_infringement': [54, 59, \n 73, 73], 'high_infringement': [38, 56, 55, 55], 'critical_infringement':\n [26, 19, 30, 30], 'weeks': ['2020-09-02 2020-09-08',\n '2020-09-09 2020-09-15', '2020-09-16 2020-09-22',\n '2020-09-23 2020-09-29']}), ('face-mask-detections', {'no_face': [88, \n 85, 106, 85], 'face_with_mask': [310, 519, 445, 519],\n 'face_without_mask': [150, 171, 180, 171], 'weeks': [\n '2020-09-02 2020-09-08', '2020-09-09 2020-09-15',\n '2020-09-16 2020-09-22', '2020-09-23 2020-09-29']})]"], {}), "('metric,expected', [('social-distancing', {\n 'detected_objects': [535, 754, 714, 714], 'no_infringement': [416, 622,\n 555, 555], 'low_infringement': [54, 59, 73, 73], 'high_infringement': [\n 38, 56, 55, 55], 'critical_infringement': [26, 19, 30, 30], 'weeks': [\n '2020-09-02 2020-09-08', '2020-09-09 2020-09-15',\n '2020-09-16 2020-09-22', '2020-09-23 2020-09-29']}), (\n 'face-mask-detections', {'no_face': [88, 85, 106, 85], 'face_with_mask':\n [310, 519, 445, 519], 'face_without_mask': [150, 171, 180, 171],\n 'weeks': ['2020-09-02 2020-09-08', '2020-09-09 2020-09-15',\n '2020-09-16 2020-09-22', '2020-09-23 2020-09-29']})])\n", (36309, 36961), False, 'import pytest\n'), ((37175, 37200), 'freezegun.freeze_time', 'freeze_time', (['"""2020-09-30"""'], {}), "('2020-09-30')\n", (37186, 37200), False, 'from freezegun import freeze_time\n'), ((38010, 38220), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""metric,expected"""', '[(\'social-distancing\', {\'detail\': "Camera with id \'BAD_ID\' does not exist"}\n ), (\'face-mask-detections\', {\'detail\':\n "Camera with id \'BAD_ID\' does not exist"})]'], {}), '(\'metric,expected\', [(\'social-distancing\', {\'detail\':\n "Camera with id \'BAD_ID\' does not exist"}), (\'face-mask-detections\', {\n \'detail\': "Camera with id \'BAD_ID\' does not exist"})])\n', (38033, 38220), False, 'import pytest\n'), ((38768, 39178), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""metric,expected"""', "[('social-distancing', {'detected_objects': [0, 0, 0, 0, 0],\n 'no_infringement': [0, 0, 0, 0, 0], 'low_infringement': [0, 0, 0, 0, 0],\n 'high_infringement': [0, 0, 0, 0, 0], 'critical_infringement': [0, 0, 0,\n 0, 0]}), ('face-mask-detections', {'no_face': [0, 0, 0, 0, 0],\n 'face_with_mask': [0, 0, 0, 0, 0], 'face_without_mask': [0, 0, 0, 0, 0]})]"], {}), "('metric,expected', [('social-distancing', {\n 'detected_objects': [0, 0, 0, 0, 0], 'no_infringement': [0, 0, 0, 0, 0],\n 'low_infringement': [0, 0, 0, 0, 0], 'high_infringement': [0, 0, 0, 0, \n 0], 'critical_infringement': [0, 0, 0, 0, 0]}), ('face-mask-detections',\n {'no_face': [0, 0, 0, 0, 0], 'face_with_mask': [0, 0, 0, 0, 0],\n 'face_without_mask': [0, 0, 0, 0, 0]})])\n", (38791, 39178), False, 'import pytest\n'), ((40347, 40432), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""metric"""', "['social-distancing', 'face-mask-detections']"], {}), "('metric', ['social-distancing', 'face-mask-detections']\n )\n", (40370, 40432), False, 'import pytest\n'), ((40907, 41688), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""metric,expected"""', "[('social-distancing', {'detected_objects': [0, 0, 0, 0, 0, 0],\n 'no_infringement': [0, 0, 0, 0, 0, 0], 'low_infringement': [0, 0, 0, 0,\n 0, 0], 'high_infringement': [0, 0, 0, 0, 0, 0], 'critical_infringement':\n [0, 0, 0, 0, 0, 0], 'weeks': ['2012-04-12 2012-04-15',\n '2012-04-16 2012-04-22', '2012-04-23 2012-04-29',\n '2012-04-30 2012-05-06', '2012-05-07 2012-05-13',\n '2012-05-14 2012-05-18']}), ('face-mask-detections', {'no_face': [0, 0,\n 0, 0, 0, 0], 'face_with_mask': [0, 0, 0, 0, 0, 0], 'face_without_mask':\n [0, 0, 0, 0, 0, 0], 'weeks': ['2012-04-12 2012-04-15',\n '2012-04-16 2012-04-22', '2012-04-23 2012-04-29',\n '2012-04-30 2012-05-06', '2012-05-07 2012-05-13',\n '2012-05-14 2012-05-18']})]"], {}), "('metric,expected', [('social-distancing', {\n 'detected_objects': [0, 0, 0, 0, 0, 0], 'no_infringement': [0, 0, 0, 0,\n 0, 0], 'low_infringement': [0, 0, 0, 0, 0, 0], 'high_infringement': [0,\n 0, 0, 0, 0, 0], 'critical_infringement': [0, 0, 0, 0, 0, 0], 'weeks': [\n '2012-04-12 2012-04-15', '2012-04-16 2012-04-22',\n '2012-04-23 2012-04-29', '2012-04-30 2012-05-06',\n '2012-05-07 2012-05-13', '2012-05-14 2012-05-18']}), (\n 'face-mask-detections', {'no_face': [0, 0, 0, 0, 0, 0],\n 'face_with_mask': [0, 0, 0, 0, 0, 0], 'face_without_mask': [0, 0, 0, 0,\n 0, 0], 'weeks': ['2012-04-12 2012-04-15', '2012-04-16 2012-04-22',\n '2012-04-23 2012-04-29', '2012-04-30 2012-05-06',\n '2012-05-07 2012-05-13', '2012-05-14 2012-05-18']})])\n", (40930, 41688), False, 'import pytest\n'), ((42462, 42547), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""metric"""', "['social-distancing', 'face-mask-detections']"], {}), "('metric', ['social-distancing', 'face-mask-detections']\n )\n", (42485, 42547), False, 'import pytest\n'), ((43133, 43618), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""metric,expected"""', "[('social-distancing', {'detected_objects': [104, 582], 'no_infringement':\n [5, 361], 'low_infringement': [57, 131], 'high_infringement': [42, 79],\n 'critical_infringement': [0, 11], 'weeks': ['2020-09-20 2020-09-20',\n '2020-09-21 2020-09-23']}), ('face-mask-detections', {'no_face': [85, \n 232], 'face_with_mask': [36, 434], 'face_without_mask': [23, 200],\n 'weeks': ['2020-09-20 2020-09-20', '2020-09-21 2020-09-23']})]"], {}), "('metric,expected', [('social-distancing', {\n 'detected_objects': [104, 582], 'no_infringement': [5, 361],\n 'low_infringement': [57, 131], 'high_infringement': [42, 79],\n 'critical_infringement': [0, 11], 'weeks': ['2020-09-20 2020-09-20',\n '2020-09-21 2020-09-23']}), ('face-mask-detections', {'no_face': [85, \n 232], 'face_with_mask': [36, 434], 'face_without_mask': [23, 200],\n 'weeks': ['2020-09-20 2020-09-20', '2020-09-21 2020-09-23']})])\n", (43156, 43618), False, 'import pytest\n'), ((44718, 44803), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""metric"""', "['social-distancing', 'face-mask-detections']"], {}), "('metric', ['social-distancing', 'face-mask-detections']\n )\n", (44741, 44803), False, 'import pytest\n'), ((45566, 45651), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""metric"""', "['social-distancing', 'face-mask-detections']"], {}), "('metric', ['social-distancing', 'face-mask-detections']\n )\n", (45589, 45651), False, 'import pytest\n'), ((1080, 1177), 'os.path.join', 'os.path.join', (['HEATMAP_PATH_PREFIX', 'camera_id', '"""heatmaps"""', '"""violations_heatmap_2020-09-19.npy"""'], {}), "(HEATMAP_PATH_PREFIX, camera_id, 'heatmaps',\n 'violations_heatmap_2020-09-19.npy')\n", (1092, 1177), False, 'import os\n'), ((1681, 1778), 'os.path.join', 'os.path.join', (['HEATMAP_PATH_PREFIX', 'camera_id', '"""heatmaps"""', '"""violations_heatmap_2020-09-19.npy"""'], {}), "(HEATMAP_PATH_PREFIX, camera_id, 'heatmaps',\n 'violations_heatmap_2020-09-19.npy')\n", (1693, 1778), False, 'import os\n'), ((2328, 2425), 'os.path.join', 'os.path.join', (['HEATMAP_PATH_PREFIX', 'camera_id', '"""heatmaps"""', '"""violations_heatmap_2020-09-19.npy"""'], {}), "(HEATMAP_PATH_PREFIX, camera_id, 'heatmaps',\n 'violations_heatmap_2020-09-19.npy')\n", (2340, 2425), False, 'import os\n'), ((2447, 2544), 'os.path.join', 'os.path.join', (['HEATMAP_PATH_PREFIX', 'camera_id', '"""heatmaps"""', '"""violations_heatmap_2020-09-22.npy"""'], {}), "(HEATMAP_PATH_PREFIX, camera_id, 'heatmaps',\n 'violations_heatmap_2020-09-22.npy')\n", (2459, 2544), False, 'import os\n'), ((2561, 2584), 'numpy.load', 'np.load', (['heatmap_path_1'], {}), '(heatmap_path_1)\n', (2568, 2584), True, 'import numpy as np\n'), ((2605, 2628), 'numpy.load', 'np.load', (['heatmap_path_2'], {}), '(heatmap_path_2)\n', (2612, 2628), True, 'import numpy as np\n'), ((3262, 3359), 'os.path.join', 'os.path.join', (['HEATMAP_PATH_PREFIX', 'camera_id', '"""heatmaps"""', '"""detections_heatmap_2020-09-19.npy"""'], {}), "(HEATMAP_PATH_PREFIX, camera_id, 'heatmaps',\n 'detections_heatmap_2020-09-19.npy')\n", (3274, 3359), False, 'import os\n'), ((1192, 1213), 'numpy.load', 'np.load', (['heatmap_path'], {}), '(heatmap_path)\n', (1199, 1213), True, 'import numpy as np\n'), ((1793, 1814), 'numpy.load', 'np.load', (['heatmap_path'], {}), '(heatmap_path)\n', (1800, 1814), True, 'import numpy as np\n'), ((2653, 2681), 'numpy.add', 'np.add', (['heatmap_1', 'heatmap_2'], {}), '(heatmap_1, heatmap_2)\n', (2659, 2681), True, 'import numpy as np\n'), ((3374, 3395), 'numpy.load', 'np.load', (['heatmap_path'], {}), '(heatmap_path)\n', (3381, 3395), True, 'import numpy as np\n')]
import numpy as np import pandas as pd from scipy.stats import norm ############################################################################### #Non-Standard Imports ############################################################################### try: from . import curvefitting as cf from .models import settings_handler as sh except: import curvefitting as cf from models import settings_handler as sh ############################################################################### #AIC Calculation ############################################################################### def calculate_aic(data, models, params, priors={}): '''Calculates AIC of model calculating posterior and than applying AIC formula. Returns a DataFrame of the AIC Values. Parameters ---------- data : dict Curve-fitting data. models : dict The models used for curve-fitting. params : pandas.DataFrame The parameters with which to integrate the models with. priors : dict, optional Priors if any. The default is {}. Returns ------- table : pandas.DataFrame A DataFrame with AIC values. ''' aic = {} #Standardize format try: params1 = pd.DataFrame(params) except: params1 = pd.DataFrame([params]) #Set up arguments posterior_args = get_posterior_args(data, models, params1, priors) n_points, n_params = get_aic_args(data, models) aic = [] for name, row in params1.iterrows(): log_posterior = get_posterior_for_each_model(params_series=row, **posterior_args) model_aic = n_points*np.log(-log_posterior/n_points) + 2*n_params aic.append(model_aic) aic = pd.DataFrame(aic, columns=models.keys(), index=params1.index) table = pd.DataFrame(aic.stack().reset_index()) table.columns = ['row', 'model_num', 'AIC Value'] return table def get_aic_args(data, models): ''' Supporting function for calculate_aic. Do not run. :meta private: ''' n_points = {} n_params = [] for model_num in data: n_points[model_num] = 0 n_params.append( len(models[model_num]['params']) ) for state in data[model_num]: for scenario in data[model_num][state]: if scenario < 1: continue else: n_points[model_num] += len(data[model_num][state][scenario]) return np.array(list(n_points.values())), np.array(n_params) def get_posterior_args(data, models, params, priors): ''' Supporting function for calculate_aic. Do not run. :meta private: ''' t_indices = cf.get_t_indices(data, models) prior_distribution = {model_num: np.array([priors[param] for param in models[model_num]['params'] if param in priors]) for model_num in models} prior_distribution = {model_num: norm(prior_distribution[model_num][:,0], prior_distribution[model_num][:,1]) for model_num in models if len(prior_distribution[model_num])} prior_index = {model_num: [param for param in models[model_num]['params'] if param in priors] for model_num in models} result = {'data' : data, 'models' : models, 't_indices' : t_indices, 'prior_distribution' : prior_distribution, 'prior_index' : prior_index } return result def get_posterior_for_each_model(data, models, params_series, prior_distribution, prior_index, t_indices={}): ''' Supporting function for calculate_aic. Do not run. :meta private: ''' log_posterior = [] for model_num in data: #Log likelihood #SSE negated due to definition of log likelihood params_ = params_series[models[model_num]['params']].values model_likelihood = -cf.get_SSE_dataset(model_num, data, models, params_, t_indices) #Log prior if len(prior_index[model_num]): params__ = params_series[prior_index[model_num]] model_prior = np.sum(prior_distribution[model_num].pdf(params__)) else: model_prior = 0 model_posterior = model_likelihood + model_prior log_posterior.append(model_posterior) return np.array(log_posterior) def normalize_aic(aic_values): ''' Accepts a list-like array of aic values and returns a normalized array where the lowest value is zero. ''' return np.array(aic_values) - np.min(aic_values) ############################################################################### #AIC Tables/DataFrames ############################################################################### def rank_aic(aic_dataframe, aic_column_name='AIC Value', inplace=True): ''' Accepts a dataframe where each row corresponds to one model aic_dataframe cannot have any columns named 'Evidence'. ''' daic = normalize_aic(aic_dataframe[aic_column_name]) evidence = ['Substantial support' if daic[i] < 2 else 'Weak support' if daic[i] < 10 else 'No support' for i in range(len(daic))] loc = len(aic_dataframe.columns) ranked_table = aic_dataframe if inplace else aic_dataframe.copy() ranked_table.insert(loc = loc, column ='d(' + aic_column_name + ')', value = daic ) ranked_table.insert(loc = loc, column ='Evidence', value = evidence ) ranked_table = ranked_table.sort_values(aic_column_name) return ranked_table
[ "scipy.stats.norm", "numpy.log", "numpy.array", "curvefitting.get_SSE_dataset", "numpy.min", "pandas.DataFrame", "curvefitting.get_t_indices" ]
[((2862, 2892), 'curvefitting.get_t_indices', 'cf.get_t_indices', (['data', 'models'], {}), '(data, models)\n', (2878, 2892), True, 'import curvefitting as cf\n'), ((4626, 4649), 'numpy.array', 'np.array', (['log_posterior'], {}), '(log_posterior)\n', (4634, 4649), True, 'import numpy as np\n'), ((1316, 1336), 'pandas.DataFrame', 'pd.DataFrame', (['params'], {}), '(params)\n', (1328, 1336), True, 'import pandas as pd\n'), ((2666, 2684), 'numpy.array', 'np.array', (['n_params'], {}), '(n_params)\n', (2674, 2684), True, 'import numpy as np\n'), ((2933, 3022), 'numpy.array', 'np.array', (["[priors[param] for param in models[model_num]['params'] if param in priors]"], {}), "([priors[param] for param in models[model_num]['params'] if param in\n priors])\n", (2941, 3022), True, 'import numpy as np\n'), ((3082, 3160), 'scipy.stats.norm', 'norm', (['prior_distribution[model_num][:, 0]', 'prior_distribution[model_num][:, 1]'], {}), '(prior_distribution[model_num][:, 0], prior_distribution[model_num][:, 1])\n', (3086, 3160), False, 'from scipy.stats import norm\n'), ((4838, 4858), 'numpy.array', 'np.array', (['aic_values'], {}), '(aic_values)\n', (4846, 4858), True, 'import numpy as np\n'), ((4861, 4879), 'numpy.min', 'np.min', (['aic_values'], {}), '(aic_values)\n', (4867, 4879), True, 'import numpy as np\n'), ((1369, 1391), 'pandas.DataFrame', 'pd.DataFrame', (['[params]'], {}), '([params])\n', (1381, 1391), True, 'import pandas as pd\n'), ((4166, 4229), 'curvefitting.get_SSE_dataset', 'cf.get_SSE_dataset', (['model_num', 'data', 'models', 'params_', 't_indices'], {}), '(model_num, data, models, params_, t_indices)\n', (4184, 4229), True, 'import curvefitting as cf\n'), ((1746, 1779), 'numpy.log', 'np.log', (['(-log_posterior / n_points)'], {}), '(-log_posterior / n_points)\n', (1752, 1779), True, 'import numpy as np\n')]
#! /usr/bin/env python """Applies a ccbid model to new data """ import sys import numpy as np import pandas as pd import ccbid from ccbid import args from ccbid import prnt from sklearn.preprocessing import StandardScaler # set up the argument parser to read command line inputs def parse_args(): """Function to read CCB-ID command line arguments Args: None - reads from sys.argv Returns: an argparse object """ # create the argument parser parser = args.create_parser(description='Apply a CCB-ID species classification model to csv or image data.') # set up the arguments for dealing with file i/o args.input(parser) args.mask(parser) args.output(parser) args.ecodse(parser) args.models(parser, help='path to the ccbid model to apply', default=None, required=True) # arguments to turn on certian flags or set specific parameters args.remove_outliers(parser) args.aggregate(parser) args.labels(parser) args.cpus(parser) # maybe add function to model object to update the n_cpus in each model args.verbose(parser) # parse the inputs from sys.argv return parser.parse_args(sys.argv[1:]) # set up the logic to parse command line arguments and ensure consistent logic def arg_logic(argv): """Parses the command line arguments to ensure consistency prior to running the main script Args: args - the arguments returned from the argparse object Returns: None. This function updates the args object """ # if the ECODSE flag is set, override whatever is set at the command line if args.ecodse: argv.input = args.path_testing argv.remove_outliers = 'PCA' argv.threshold = 4 argv.aggregate = 'average' # args.feature_selection = False # set up the main script function def main(): """The main function for ccbid apply Args: None - just let it fly Returns: None - this runs the dang script """ # first read the command line arguments argv = parse_args() # parse the logic to make sure everything runs smoothly arg_logic(argv) # set the seed for reproducibility (to the year the CCB was founded) np.random.seed(1984) # ----- # step 1. reading data # ----- if argv.verbose: prnt.line_break() prnt.status("Reading input data") # first read the model data model = ccbid.read.pck(argv.model[0]) # get base data from the model sp_labels = model.labels_ # set up a dummy variable to determine if data should be output on a per-crown or per-=pixel basis # then read the feature data, which may come as a raster or a csv if ccbid.read.is_csv(argv.input): id_labels, features, newFeatures = ccbid.read.training_data(argv.input) elif ccbid.read.is_raster(args.input): raster = ccbid.read.raster(argv.input) raster.read_all() # if a mask is set, just apply the model to those data if argv.mask is not None: mask = ccbid.read.raster(argv.mask) mask_ind = mask.read_band(1).data == 1 features = raster.data[mask_ind] mask.data = None # if no mask is set, just use the straight image data else: # first, check for no-data values if raster.no_data is not None: features = raster.data[raster.data != raster.no_data] # otherwise, flatten the data from [x, y, features] to [rows, features] else: features = raster.data.reshape((raster.nx * raster.ny, raster.nb)) # and clear memory raster.data = None # work on this later else: prnt.error("Unsupported file format. Must be a csv or a raster file.") sys.exit(1) # subset the features by band if the model contains a good bands attribute if model.good_bands_ is not None: features = features[:, model.good_bands_] # ----- # step 2. outlier removal # ----- if argv.remove_outliers: if argv.verbose: prnt.status("Removing outliers using {}".format(argv.remove_outliers)) # currently only one version of outlier removal if argv.remove_outliers == 'PCA': mask = ccbid.outliers.with_pca(features, thresh=argv.threshold) # subset all data using the mask for future analyses features = features[mask, :] id_labels = id_labels[mask] newFeatures = newFeatures[mask, :] # report on the number of samples removed if argv.verbose: n_removed = mask.shape[0] - mask.sum() prnt.status("Removed {} samples".format(n_removed)) # ----- # step 3: data transformation # ----- if model.reducer is not None: if argv.verbose: prnt.status("Transforming feature data") features = np.hstack([features, newFeatures]) #features = StandardScaler().fit_transform(features) features = model.reducer.transform(features) # then supbset the transformed features if model.n_features_ is not None: features = features[:, 0:model.n_features_] # ----- # step 4: applying the model # ----- if argv.verbose: prnt.line_break() prnt.status("Applying CCBID model to input features") # pred = model.predict(features) prob = model.predict_proba(features, average_proba=True) # ensemble the pixels to the crown scale if argv.aggregate is not None: # do it differently for csv vs raster if ccbid.read.is_csv(argv.input): # calculate the crown ensemble if argv.aggregate == 'average': output_pr = ccbid.crown_ensemble.average(prob, id_labels, sp_labels) # create the crown id labels (also, create the model.labels property) id_rows, sp_rows = ccbid.crown_ensemble.get_csv_labels(id_labels, sp_labels) # add everything to a pandas dataframe and save the result df = pd.DataFrame.from_items((('crown', id_rows), ('species', sp_rows), ('probability', output_pr))) df.to_csv(argv.output, index=False) elif ccbid.read.is_raster(argv.input): # get the crown IDs from a separate raster try: testing_id = ccbid.read.raster(argv.labels) except: prnt.error("Unable to read label file: {}".format(argv.labels)) prnt.error("Check the file path or run without --aggregate to obtain pixel-scale predictions") # or, output the raw predictions if not aggregating else: # do it differently for csv vs raster if ccbid.read.is_csv(argv.input): # write out results as a pandas dataframe df_id = pd.DataFrame.from_items(('id', id_labels)) df_pr = pd.DataFrame(prob, columns=sp_labels) df = df_id.append(df_pr) df.to_csv(argv.output, index=False) prnt.line_break() prnt.status("CCB-ID model application complete!") prnt.status("Please see the final output file:") prnt.status(" {}".format(argv.output)) prnt.line_break() # phew # just run the dang script, will ya? if __name__ == "__main__": main()
[ "ccbid.args.cpus", "ccbid.args.aggregate", "numpy.hstack", "ccbid.read.is_csv", "ccbid.prnt.status", "sys.exit", "ccbid.args.verbose", "ccbid.outliers.with_pca", "ccbid.args.remove_outliers", "ccbid.args.ecodse", "ccbid.args.input", "numpy.random.seed", "ccbid.read.training_data", "pandas....
[((510, 614), 'ccbid.args.create_parser', 'args.create_parser', ([], {'description': '"""Apply a CCB-ID species classification model to csv or image data."""'}), "(description=\n 'Apply a CCB-ID species classification model to csv or image data.')\n", (528, 614), False, 'from ccbid import args\n'), ((668, 686), 'ccbid.args.input', 'args.input', (['parser'], {}), '(parser)\n', (678, 686), False, 'from ccbid import args\n'), ((691, 708), 'ccbid.args.mask', 'args.mask', (['parser'], {}), '(parser)\n', (700, 708), False, 'from ccbid import args\n'), ((713, 732), 'ccbid.args.output', 'args.output', (['parser'], {}), '(parser)\n', (724, 732), False, 'from ccbid import args\n'), ((737, 756), 'ccbid.args.ecodse', 'args.ecodse', (['parser'], {}), '(parser)\n', (748, 756), False, 'from ccbid import args\n'), ((761, 854), 'ccbid.args.models', 'args.models', (['parser'], {'help': '"""path to the ccbid model to apply"""', 'default': 'None', 'required': '(True)'}), "(parser, help='path to the ccbid model to apply', default=None,\n required=True)\n", (772, 854), False, 'from ccbid import args\n'), ((924, 952), 'ccbid.args.remove_outliers', 'args.remove_outliers', (['parser'], {}), '(parser)\n', (944, 952), False, 'from ccbid import args\n'), ((957, 979), 'ccbid.args.aggregate', 'args.aggregate', (['parser'], {}), '(parser)\n', (971, 979), False, 'from ccbid import args\n'), ((984, 1003), 'ccbid.args.labels', 'args.labels', (['parser'], {}), '(parser)\n', (995, 1003), False, 'from ccbid import args\n'), ((1008, 1025), 'ccbid.args.cpus', 'args.cpus', (['parser'], {}), '(parser)\n', (1017, 1025), False, 'from ccbid import args\n'), ((1103, 1123), 'ccbid.args.verbose', 'args.verbose', (['parser'], {}), '(parser)\n', (1115, 1123), False, 'from ccbid import args\n'), ((2275, 2295), 'numpy.random.seed', 'np.random.seed', (['(1984)'], {}), '(1984)\n', (2289, 2295), True, 'import numpy as np\n'), ((2483, 2512), 'ccbid.read.pck', 'ccbid.read.pck', (['argv.model[0]'], {}), '(argv.model[0])\n', (2497, 2512), False, 'import ccbid\n'), ((2761, 2790), 'ccbid.read.is_csv', 'ccbid.read.is_csv', (['argv.input'], {}), '(argv.input)\n', (2778, 2790), False, 'import ccbid\n'), ((7138, 7155), 'ccbid.prnt.line_break', 'prnt.line_break', ([], {}), '()\n', (7153, 7155), False, 'from ccbid import prnt\n'), ((7160, 7209), 'ccbid.prnt.status', 'prnt.status', (['"""CCB-ID model application complete!"""'], {}), "('CCB-ID model application complete!')\n", (7171, 7209), False, 'from ccbid import prnt\n'), ((7214, 7262), 'ccbid.prnt.status', 'prnt.status', (['"""Please see the final output file:"""'], {}), "('Please see the final output file:')\n", (7225, 7262), False, 'from ccbid import prnt\n'), ((7311, 7328), 'ccbid.prnt.line_break', 'prnt.line_break', ([], {}), '()\n', (7326, 7328), False, 'from ccbid import prnt\n'), ((2378, 2395), 'ccbid.prnt.line_break', 'prnt.line_break', ([], {}), '()\n', (2393, 2395), False, 'from ccbid import prnt\n'), ((2404, 2437), 'ccbid.prnt.status', 'prnt.status', (['"""Reading input data"""'], {}), "('Reading input data')\n", (2415, 2437), False, 'from ccbid import prnt\n'), ((2835, 2871), 'ccbid.read.training_data', 'ccbid.read.training_data', (['argv.input'], {}), '(argv.input)\n', (2859, 2871), False, 'import ccbid\n'), ((2882, 2914), 'ccbid.read.is_raster', 'ccbid.read.is_raster', (['args.input'], {}), '(args.input)\n', (2902, 2914), False, 'import ccbid\n'), ((4973, 5007), 'numpy.hstack', 'np.hstack', (['[features, newFeatures]'], {}), '([features, newFeatures])\n', (4982, 5007), True, 'import numpy as np\n'), ((5358, 5375), 'ccbid.prnt.line_break', 'prnt.line_break', ([], {}), '()\n', (5373, 5375), False, 'from ccbid import prnt\n'), ((5384, 5437), 'ccbid.prnt.status', 'prnt.status', (['"""Applying CCBID model to input features"""'], {}), "('Applying CCBID model to input features')\n", (5395, 5437), False, 'from ccbid import prnt\n'), ((5676, 5705), 'ccbid.read.is_csv', 'ccbid.read.is_csv', (['argv.input'], {}), '(argv.input)\n', (5693, 5705), False, 'import ccbid\n'), ((6842, 6871), 'ccbid.read.is_csv', 'ccbid.read.is_csv', (['argv.input'], {}), '(argv.input)\n', (6859, 6871), False, 'import ccbid\n'), ((2933, 2962), 'ccbid.read.raster', 'ccbid.read.raster', (['argv.input'], {}), '(argv.input)\n', (2950, 2962), False, 'import ccbid\n'), ((3785, 3855), 'ccbid.prnt.error', 'prnt.error', (['"""Unsupported file format. Must be a csv or a raster file."""'], {}), "('Unsupported file format. Must be a csv or a raster file.')\n", (3795, 3855), False, 'from ccbid import prnt\n'), ((3864, 3875), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (3872, 3875), False, 'import sys\n'), ((4355, 4411), 'ccbid.outliers.with_pca', 'ccbid.outliers.with_pca', (['features'], {'thresh': 'argv.threshold'}), '(features, thresh=argv.threshold)\n', (4378, 4411), False, 'import ccbid\n'), ((4912, 4952), 'ccbid.prnt.status', 'prnt.status', (['"""Transforming feature data"""'], {}), "('Transforming feature data')\n", (4923, 4952), False, 'from ccbid import prnt\n'), ((5994, 6051), 'ccbid.crown_ensemble.get_csv_labels', 'ccbid.crown_ensemble.get_csv_labels', (['id_labels', 'sp_labels'], {}), '(id_labels, sp_labels)\n', (6029, 6051), False, 'import ccbid\n'), ((6141, 6241), 'pandas.DataFrame.from_items', 'pd.DataFrame.from_items', (["(('crown', id_rows), ('species', sp_rows), ('probability', output_pr))"], {}), "((('crown', id_rows), ('species', sp_rows), (\n 'probability', output_pr)))\n", (6164, 6241), True, 'import pandas as pd\n'), ((6341, 6373), 'ccbid.read.is_raster', 'ccbid.read.is_raster', (['argv.input'], {}), '(argv.input)\n', (6361, 6373), False, 'import ccbid\n'), ((6947, 6989), 'pandas.DataFrame.from_items', 'pd.DataFrame.from_items', (["('id', id_labels)"], {}), "(('id', id_labels))\n", (6970, 6989), True, 'import pandas as pd\n'), ((7010, 7047), 'pandas.DataFrame', 'pd.DataFrame', (['prob'], {'columns': 'sp_labels'}), '(prob, columns=sp_labels)\n', (7022, 7047), True, 'import pandas as pd\n'), ((3106, 3134), 'ccbid.read.raster', 'ccbid.read.raster', (['argv.mask'], {}), '(argv.mask)\n', (3123, 3134), False, 'import ccbid\n'), ((5823, 5879), 'ccbid.crown_ensemble.average', 'ccbid.crown_ensemble.average', (['prob', 'id_labels', 'sp_labels'], {}), '(prob, id_labels, sp_labels)\n', (5851, 5879), False, 'import ccbid\n'), ((6476, 6506), 'ccbid.read.raster', 'ccbid.read.raster', (['argv.labels'], {}), '(argv.labels)\n', (6493, 6506), False, 'import ccbid\n'), ((6623, 6727), 'ccbid.prnt.error', 'prnt.error', (['"""Check the file path or run without --aggregate to obtain pixel-scale predictions"""'], {}), "(\n 'Check the file path or run without --aggregate to obtain pixel-scale predictions'\n )\n", (6633, 6727), False, 'from ccbid import prnt\n')]
import os import numpy as np import matplotlib.pyplot as plt import pylab #%matplotlib inline path = os.getcwd() + "/data/ex1data1.txt" data = np.loadtxt(path, delimiter=",") temp = np.ones((97,1), dtype=np.float64) data = np.append(temp, data, axis=1) ''' print(data.itemsize) print(data.ndim) print(data.shape) print(data.size) ''' def partial(data, theta0, theta1, i): temp = 0.0 for row in data: temp += (theta0 * row[0] + theta1 * row[1] - row[2]) * row[i] temp /= (data.shape)[0] return temp def J(theta0, theta1, data): j = 0.0; for row in data: j += (theta0 * row[0] + theta1 * row[1] - row[2]) ** 2 j /= (2 * (data.shape)[0]) return j def regression(data): #for plotting error vs training epoch #count = 0 alpha = 0.01 m, n = (data.shape)[0], (data.shape)[1] theta0, theta1 = 0.0, 0.0 j = J(theta0, theta1, data) j_prev = j + 1 epsilon = 0.0001 while (abs(j - j_prev) >= epsilon): temp0 = theta0 - alpha * partial(data, theta0, theta1, 0) temp1 = theta1 - alpha * partial(data, theta0, theta1, 1) theta0 = temp0 theta1 = temp1 j_prev = j j = J(theta0, theta1, data) #plt.plot(count, j, "b.") #count += 1 return theta0, theta1 def abline(slope, intercept): #Plot a line from slope and intercept axes = plt.gca() x_vals = np.array(axes.get_xlim()) y_vals = intercept + slope * x_vals plt.plot(x_vals, y_vals, '-') theta0, theta1 = regression(data) temp1 = [theta0, theta0 + theta1] plt.plot(data[:,1], data[:,2], "r.") abline(theta1, theta0) plt.ylabel('some numbers') plt.show()
[ "numpy.ones", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.gca", "matplotlib.pyplot.plot", "os.getcwd", "numpy.append", "numpy.loadtxt", "matplotlib.pyplot.show" ]
[((149, 180), 'numpy.loadtxt', 'np.loadtxt', (['path'], {'delimiter': '""","""'}), "(path, delimiter=',')\n", (159, 180), True, 'import numpy as np\n'), ((188, 222), 'numpy.ones', 'np.ones', (['(97, 1)'], {'dtype': 'np.float64'}), '((97, 1), dtype=np.float64)\n', (195, 222), True, 'import numpy as np\n'), ((229, 258), 'numpy.append', 'np.append', (['temp', 'data'], {'axis': '(1)'}), '(temp, data, axis=1)\n', (238, 258), True, 'import numpy as np\n'), ((1459, 1497), 'matplotlib.pyplot.plot', 'plt.plot', (['data[:, 1]', 'data[:, 2]', '"""r."""'], {}), "(data[:, 1], data[:, 2], 'r.')\n", (1467, 1497), True, 'import matplotlib.pyplot as plt\n'), ((1519, 1545), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""some numbers"""'], {}), "('some numbers')\n", (1529, 1545), True, 'import matplotlib.pyplot as plt\n'), ((1546, 1556), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1554, 1556), True, 'import matplotlib.pyplot as plt\n'), ((107, 118), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (116, 118), False, 'import os\n'), ((1266, 1275), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (1273, 1275), True, 'import matplotlib.pyplot as plt\n'), ((1359, 1388), 'matplotlib.pyplot.plot', 'plt.plot', (['x_vals', 'y_vals', '"""-"""'], {}), "(x_vals, y_vals, '-')\n", (1367, 1388), True, 'import matplotlib.pyplot as plt\n')]
# -*- coding: utf-8 -*- """ Created March 18, 2019 @author: <NAME>; @Description: Train dataset using tensorflow """ import numpy as np import load_training_image as fi import tensorflow as tf #The image size of all_faces is 92*112; path = ".\\att_faces"; classes = 41 display = 0 face_image = fi.LoadTrainingImage(path, classes) face_image.load(display) width = face_image.default_image_width height = face_image.default_image_height print("Info: Image size (w:%d, h:%d)"%(width, height)) test_x = face_image.image_data test_y = face_image.label_data ################################################################################################################## #CNN Model below, do not tough it. Make sure that this mode is the same as training model; #The reason why same piece of code in traning and validation is to implement save/load function; #There is one other solution to implement save/load function without same piece of code but not implemented here; #CNN Model start here: ################################################################################################################## input_x = tf.placeholder(tf.float32,[None, width*height])/255. output_y=tf.placeholder(tf.int32,[None, classes]) input_x_images = tf.reshape(input_x,[-1, width, height, 1]) conv1=tf.layers.conv2d( inputs=input_x_images, filters=32, kernel_size=[5,5], strides=1, padding='same', activation=tf.nn.relu ) print(conv1) pool1=tf.layers.max_pooling2d( inputs=conv1, pool_size=[2,2], strides=2 ) print(pool1) conv2=tf.layers.conv2d( inputs=pool1, filters=64, kernel_size=[5,5], strides=1, padding='same', activation=tf.nn.relu ) pool2=tf.layers.max_pooling2d( inputs=conv2, pool_size=[2,2], strides=2 ) w0 = int(width/4); h0 = int(height/4); flat=tf.reshape(pool2,[-1,w0*h0*64]) dense=tf.layers.dense( inputs=flat, units=1024, activation=tf.nn.relu ) print(dense) dropout=tf.layers.dropout( inputs=dense, rate=0.5 ) print(dropout) logits=tf.layers.dense( inputs=dropout, units=classes ) print(logits) ################################################################################################################## #CNN Model end here: ################################################################################################################ loss=tf.losses.softmax_cross_entropy(onehot_labels=output_y,logits=logits) print(loss) train_op=tf.train.GradientDescentOptimizer(learning_rate=0.001).minimize(loss) accuracy_op=tf.metrics.accuracy( labels=tf.argmax(output_y,axis=1), predictions=tf.argmax(logits,axis=1) )[1] tf.device('/gpu:0') sess=tf.Session() init=tf.group(tf.global_variables_initializer(), tf.local_variables_initializer()) sess.run(init) ckpt_file_path = "./models/face" saver = tf.train.Saver() for i in range(30000): [batch_data, batch_target]= face_image.next_batch(100) train_loss,train_op_ = sess.run([loss,train_op],{input_x:batch_data,output_y:batch_target}) if i%100==0: test_accuracy=sess.run(accuracy_op,{input_x:test_x,output_y:test_y}) print("Step=%d, Train loss=%.4f,[Test accuracy=%.2f]"%(i,train_loss,test_accuracy)) x=55; y=75; test_output = sess.run(logits,{input_x:test_x[x:y]}) inferenced_y = np.argmax(test_output,1) print(inferenced_y,'Inferenced numbers')#推测的数字 print(np.argmax(test_y[x:y],1),'Real numbers') saver.save(sess, ckpt_file_path) sess.close()
[ "tensorflow.local_variables_initializer", "load_training_image.LoadTrainingImage", "tensorflow.device", "tensorflow.layers.max_pooling2d", "tensorflow.losses.softmax_cross_entropy", "tensorflow.placeholder", "tensorflow.Session", "tensorflow.train.Saver", "numpy.argmax", "tensorflow.global_variabl...
[((296, 331), 'load_training_image.LoadTrainingImage', 'fi.LoadTrainingImage', (['path', 'classes'], {}), '(path, classes)\n', (316, 331), True, 'import load_training_image as fi\n'), ((1183, 1224), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[None, classes]'], {}), '(tf.int32, [None, classes])\n', (1197, 1224), True, 'import tensorflow as tf\n'), ((1241, 1284), 'tensorflow.reshape', 'tf.reshape', (['input_x', '[-1, width, height, 1]'], {}), '(input_x, [-1, width, height, 1])\n', (1251, 1284), True, 'import tensorflow as tf\n'), ((1291, 1416), 'tensorflow.layers.conv2d', 'tf.layers.conv2d', ([], {'inputs': 'input_x_images', 'filters': '(32)', 'kernel_size': '[5, 5]', 'strides': '(1)', 'padding': '"""same"""', 'activation': 'tf.nn.relu'}), "(inputs=input_x_images, filters=32, kernel_size=[5, 5],\n strides=1, padding='same', activation=tf.nn.relu)\n", (1307, 1416), True, 'import tensorflow as tf\n'), ((1458, 1524), 'tensorflow.layers.max_pooling2d', 'tf.layers.max_pooling2d', ([], {'inputs': 'conv1', 'pool_size': '[2, 2]', 'strides': '(2)'}), '(inputs=conv1, pool_size=[2, 2], strides=2)\n', (1481, 1524), True, 'import tensorflow as tf\n'), ((1558, 1674), 'tensorflow.layers.conv2d', 'tf.layers.conv2d', ([], {'inputs': 'pool1', 'filters': '(64)', 'kernel_size': '[5, 5]', 'strides': '(1)', 'padding': '"""same"""', 'activation': 'tf.nn.relu'}), "(inputs=pool1, filters=64, kernel_size=[5, 5], strides=1,\n padding='same', activation=tf.nn.relu)\n", (1574, 1674), True, 'import tensorflow as tf\n'), ((1703, 1769), 'tensorflow.layers.max_pooling2d', 'tf.layers.max_pooling2d', ([], {'inputs': 'conv2', 'pool_size': '[2, 2]', 'strides': '(2)'}), '(inputs=conv2, pool_size=[2, 2], strides=2)\n', (1726, 1769), True, 'import tensorflow as tf\n'), ((1828, 1865), 'tensorflow.reshape', 'tf.reshape', (['pool2', '[-1, w0 * h0 * 64]'], {}), '(pool2, [-1, w0 * h0 * 64])\n', (1838, 1865), True, 'import tensorflow as tf\n'), ((1867, 1930), 'tensorflow.layers.dense', 'tf.layers.dense', ([], {'inputs': 'flat', 'units': '(1024)', 'activation': 'tf.nn.relu'}), '(inputs=flat, units=1024, activation=tf.nn.relu)\n', (1882, 1930), True, 'import tensorflow as tf\n'), ((1967, 2008), 'tensorflow.layers.dropout', 'tf.layers.dropout', ([], {'inputs': 'dense', 'rate': '(0.5)'}), '(inputs=dense, rate=0.5)\n', (1984, 2008), True, 'import tensorflow as tf\n'), ((2042, 2088), 'tensorflow.layers.dense', 'tf.layers.dense', ([], {'inputs': 'dropout', 'units': 'classes'}), '(inputs=dropout, units=classes)\n', (2057, 2088), True, 'import tensorflow as tf\n'), ((2369, 2439), 'tensorflow.losses.softmax_cross_entropy', 'tf.losses.softmax_cross_entropy', ([], {'onehot_labels': 'output_y', 'logits': 'logits'}), '(onehot_labels=output_y, logits=logits)\n', (2400, 2439), True, 'import tensorflow as tf\n'), ((2651, 2670), 'tensorflow.device', 'tf.device', (['"""/gpu:0"""'], {}), "('/gpu:0')\n", (2660, 2670), True, 'import tensorflow as tf\n'), ((2676, 2688), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (2686, 2688), True, 'import tensorflow as tf\n'), ((2844, 2860), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (2858, 2860), True, 'import tensorflow as tf\n'), ((3314, 3339), 'numpy.argmax', 'np.argmax', (['test_output', '(1)'], {}), '(test_output, 1)\n', (3323, 3339), True, 'import numpy as np\n'), ((1121, 1171), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, width * height]'], {}), '(tf.float32, [None, width * height])\n', (1135, 1171), True, 'import tensorflow as tf\n'), ((2703, 2736), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (2734, 2736), True, 'import tensorflow as tf\n'), ((2752, 2784), 'tensorflow.local_variables_initializer', 'tf.local_variables_initializer', ([], {}), '()\n', (2782, 2784), True, 'import tensorflow as tf\n'), ((3392, 3417), 'numpy.argmax', 'np.argmax', (['test_y[x:y]', '(1)'], {}), '(test_y[x:y], 1)\n', (3401, 3417), True, 'import numpy as np\n'), ((2460, 2514), 'tensorflow.train.GradientDescentOptimizer', 'tf.train.GradientDescentOptimizer', ([], {'learning_rate': '(0.001)'}), '(learning_rate=0.001)\n', (2493, 2514), True, 'import tensorflow as tf\n'), ((2575, 2602), 'tensorflow.argmax', 'tf.argmax', (['output_y'], {'axis': '(1)'}), '(output_y, axis=1)\n', (2584, 2602), True, 'import tensorflow as tf\n'), ((2619, 2644), 'tensorflow.argmax', 'tf.argmax', (['logits'], {'axis': '(1)'}), '(logits, axis=1)\n', (2628, 2644), True, 'import tensorflow as tf\n')]
import lightgbm as lgb import pandas as pd import numpy as np num_boost_round = 300 train_master = pd.read_csv('train.csv') test_master = pd.read_csv('test.csv') # train_master.describe() np.random.seed(3) model_scores = {} # Drop binary columns with almost all zeros. # Why now? Just follow along for now. We have a lot of experimentation to be done train = train_master.drop(['ps_ind_10_bin', 'ps_ind_11_bin', 'ps_ind_13_bin'], axis=1) test = test_master.drop(['ps_ind_10_bin', 'ps_ind_11_bin', 'ps_ind_13_bin'], axis=1) # Drop calculated features # But WHY??? # Because we are assuming that tree can generate any complicated function # of base features and calculated features add no more information # Is this assumption valid? Results will tell calc_columns = [s for s in list(train_master.columns.values) if '_calc' in s] train = train.drop(calc_columns, axis=1) test = test.drop(calc_columns, axis=1) # Get categorical columns for encoding later categorical_columns = [s for s in list(train_master.columns.values) if '_cat' in s] target_column = 'target' # Replace missing values with NaN train = train.replace(-1, np.nan) test = test.replace(-1, np.nan) # Initialize DS to store validation fold predictions y_val_fold = np.empty(len(train)) # Initialize DS to store test predictions with aggregate model and individual models y_test = np.zeros(len(test)) y_test_model_1 = np.zeros(len(test)) y_test_model_2 = np.zeros(len(test)) y_test_model_3 = np.zeros(len(test)) def encode_cat_features(train_df, test_df, cat_cols, target_col_name, smoothing=1): prior = train_df[target_col_name].mean() probs_dict = {} for c in cat_cols: probs = train_df.groupby(c, as_index=False)[target_col_name].mean() probs['counts'] = train_df.groupby(c, as_index=False)[target_col_name].count()[[target_col_name]] probs['smoothing'] = 1 / (1 + np.exp(-(probs['counts'] - 1) / smoothing)) probs['enc'] = prior * (1 - probs['smoothing']) + probs['target'] * probs['smoothing'] probs_dict[c] = probs[[c, 'enc']] return probs_dict # Encode categorical variables using training fold encoding_dict = encode_cat_features(train, 1, categorical_columns, target_column) for c, encoding in encoding_dict.items(): train = pd.merge(train, encoding[[c, 'enc']], how='left', on=c, sort=False, suffixes=('', '_' + c)) train = train.drop(c, axis=1) train = train.rename(columns={'enc': 'enc_' + c}) test = pd.merge(test, encoding[[c, 'enc']], how='left', on=c, sort=False, suffixes=('', '_' + c)) test = test.drop(c, axis=1) test = test.rename(columns={'enc': 'enc_' + c}) from sklearn.model_selection import train_test_split X_train, X_eval, y_train, y_eval = train_test_split(train.iloc[:, 2:].values, train.iloc[:, 1].values, test_size=0.2, random_state=0) X_test = test.iloc[:, 1:].values # Define parameters of GBM as explained before for 3 trees params_1 = { 'task': 'train', 'boosting_type': 'gbdt', 'objective': 'regression', 'metric': 'auc', 'max_depth': 3, 'learning_rate': 0.05, 'feature_fraction': 1, 'bagging_fraction': 1, 'bagging_freq': 10, 'verbose': 0, 'scale_pos_weight': 4 } params_2 = { 'task': 'train', 'boosting_type': 'gbdt', 'objective': 'regression', 'metric': 'auc', 'max_depth': 4, 'learning_rate': 0.05, 'feature_fraction': 0.9, 'bagging_fraction': 0.9, 'bagging_freq': 2, 'verbose': 0, 'scale_pos_weight': 4 } params_3 = { 'task': 'train', 'boosting_type': 'gbdt', 'objective': 'regression', 'metric': 'auc', 'max_depth': 5, 'learning_rate': 0.05, 'feature_fraction': 0.3, 'bagging_fraction': 0.7, 'bagging_freq': 10, 'verbose': 0, 'scale_pos_weight': 4 } # Create appropriate format for training and evaluation data lgb_train = lgb.Dataset(X_train, y_train) lgb_eval = lgb.Dataset(X_eval, y_eval, reference=lgb_train) # Create the 3 classifiers with 1000 rounds and a window of 100 for early stopping clf_1 = lgb.train(params_1, lgb_train, num_boost_round=num_boost_round, valid_sets=lgb_eval, early_stopping_rounds=100, verbose_eval=50) clf_2 = lgb.train(params_2, lgb_train, num_boost_round=num_boost_round, valid_sets=lgb_eval, early_stopping_rounds=100, verbose_eval=50) clf_3 = lgb.train(params_3, lgb_train, num_boost_round=num_boost_round, valid_sets=lgb_eval, early_stopping_rounds=100, verbose_eval=50) from util import gini_normalized # Predict raw scores for validation ids y_eval_pred_1 = clf_1.predict(X_eval, raw_score=True) y_eval_pred_2 = clf_2.predict(X_eval, raw_score=True) y_eval_pred_3 = clf_3.predict(X_eval, raw_score=True) y_eval_pred = (y_eval_pred_1 + y_eval_pred_2 + y_eval_pred_3) / 3 print("Gini eval number 1: ") print(gini_normalized(y_eval, y_eval_pred_1)) print("Gini eval number 2: ") print(gini_normalized(y_eval, y_eval_pred_2)) print("Gini eval number 3: ") print(gini_normalized(y_eval, y_eval_pred_3)) print("Gini eval mean on all trees: ") print(gini_normalized(y_eval, y_eval_pred)) y_train_pred_1 = clf_1.predict(X_train, raw_score=True) y_train_pred_2 = clf_2.predict(X_train, raw_score=True) y_train_pred_3 = clf_3.predict(X_train, raw_score=True) y_train_pred = (y_train_pred_1 + y_train_pred_2 + y_train_pred_3) / 3 print("Gini train number 1: ") print(gini_normalized(y_train, y_train_pred_1)) print("Gini train number 2: ") print(gini_normalized(y_train, y_train_pred_2)) print("Gini train number 3: ") print(gini_normalized(y_train, y_train_pred_3)) print("Gini train mean on all trees: ") print(gini_normalized(y_train, y_train_pred)) y_test_pred = (clf_1.predict(X_test, raw_score=True) + clf_2.predict(X_test, raw_score=True) + clf_3.predict(X_test, raw_score=True) ) / 3 clf_1.save_model('clf_1.txt') clf_1.save_model('clf_2.txt') clf_1.save_model('clf_3.txt') print(y_test_pred) np.savetxt("y_test_pred", y_test_pred) ids = test.iloc[:, 0].values from tools import to_csv to_csv(y_test_pred, ids)
[ "pandas.read_csv", "util.gini_normalized", "sklearn.model_selection.train_test_split", "tools.to_csv", "lightgbm.train", "pandas.merge", "numpy.exp", "lightgbm.Dataset", "numpy.random.seed", "numpy.savetxt" ]
[((102, 126), 'pandas.read_csv', 'pd.read_csv', (['"""train.csv"""'], {}), "('train.csv')\n", (113, 126), True, 'import pandas as pd\n'), ((141, 164), 'pandas.read_csv', 'pd.read_csv', (['"""test.csv"""'], {}), "('test.csv')\n", (152, 164), True, 'import pandas as pd\n'), ((192, 209), 'numpy.random.seed', 'np.random.seed', (['(3)'], {}), '(3)\n', (206, 209), True, 'import numpy as np\n'), ((2727, 2829), 'sklearn.model_selection.train_test_split', 'train_test_split', (['train.iloc[:, 2:].values', 'train.iloc[:, 1].values'], {'test_size': '(0.2)', 'random_state': '(0)'}), '(train.iloc[:, 2:].values, train.iloc[:, 1].values,\n test_size=0.2, random_state=0)\n', (2743, 2829), False, 'from sklearn.model_selection import train_test_split\n'), ((3859, 3888), 'lightgbm.Dataset', 'lgb.Dataset', (['X_train', 'y_train'], {}), '(X_train, y_train)\n', (3870, 3888), True, 'import lightgbm as lgb\n'), ((3900, 3948), 'lightgbm.Dataset', 'lgb.Dataset', (['X_eval', 'y_eval'], {'reference': 'lgb_train'}), '(X_eval, y_eval, reference=lgb_train)\n', (3911, 3948), True, 'import lightgbm as lgb\n'), ((4041, 4174), 'lightgbm.train', 'lgb.train', (['params_1', 'lgb_train'], {'num_boost_round': 'num_boost_round', 'valid_sets': 'lgb_eval', 'early_stopping_rounds': '(100)', 'verbose_eval': '(50)'}), '(params_1, lgb_train, num_boost_round=num_boost_round, valid_sets=\n lgb_eval, early_stopping_rounds=100, verbose_eval=50)\n', (4050, 4174), True, 'import lightgbm as lgb\n'), ((4196, 4329), 'lightgbm.train', 'lgb.train', (['params_2', 'lgb_train'], {'num_boost_round': 'num_boost_round', 'valid_sets': 'lgb_eval', 'early_stopping_rounds': '(100)', 'verbose_eval': '(50)'}), '(params_2, lgb_train, num_boost_round=num_boost_round, valid_sets=\n lgb_eval, early_stopping_rounds=100, verbose_eval=50)\n', (4205, 4329), True, 'import lightgbm as lgb\n'), ((4351, 4484), 'lightgbm.train', 'lgb.train', (['params_3', 'lgb_train'], {'num_boost_round': 'num_boost_round', 'valid_sets': 'lgb_eval', 'early_stopping_rounds': '(100)', 'verbose_eval': '(50)'}), '(params_3, lgb_train, num_boost_round=num_boost_round, valid_sets=\n lgb_eval, early_stopping_rounds=100, verbose_eval=50)\n', (4360, 4484), True, 'import lightgbm as lgb\n'), ((5977, 6015), 'numpy.savetxt', 'np.savetxt', (['"""y_test_pred"""', 'y_test_pred'], {}), "('y_test_pred', y_test_pred)\n", (5987, 6015), True, 'import numpy as np\n'), ((6073, 6097), 'tools.to_csv', 'to_csv', (['y_test_pred', 'ids'], {}), '(y_test_pred, ids)\n', (6079, 6097), False, 'from tools import to_csv\n'), ((2271, 2366), 'pandas.merge', 'pd.merge', (['train', "encoding[[c, 'enc']]"], {'how': '"""left"""', 'on': 'c', 'sort': '(False)', 'suffixes': "('', '_' + c)"}), "(train, encoding[[c, 'enc']], how='left', on=c, sort=False,\n suffixes=('', '_' + c))\n", (2279, 2366), True, 'import pandas as pd\n'), ((2463, 2558), 'pandas.merge', 'pd.merge', (['test', "encoding[[c, 'enc']]"], {'how': '"""left"""', 'on': 'c', 'sort': '(False)', 'suffixes': "('', '_' + c)"}), "(test, encoding[[c, 'enc']], how='left', on=c, sort=False, suffixes\n =('', '_' + c))\n", (2471, 2558), True, 'import pandas as pd\n'), ((4840, 4878), 'util.gini_normalized', 'gini_normalized', (['y_eval', 'y_eval_pred_1'], {}), '(y_eval, y_eval_pred_1)\n', (4855, 4878), False, 'from util import gini_normalized\n'), ((4916, 4954), 'util.gini_normalized', 'gini_normalized', (['y_eval', 'y_eval_pred_2'], {}), '(y_eval, y_eval_pred_2)\n', (4931, 4954), False, 'from util import gini_normalized\n'), ((4992, 5030), 'util.gini_normalized', 'gini_normalized', (['y_eval', 'y_eval_pred_3'], {}), '(y_eval, y_eval_pred_3)\n', (5007, 5030), False, 'from util import gini_normalized\n'), ((5077, 5113), 'util.gini_normalized', 'gini_normalized', (['y_eval', 'y_eval_pred'], {}), '(y_eval, y_eval_pred)\n', (5092, 5113), False, 'from util import gini_normalized\n'), ((5394, 5434), 'util.gini_normalized', 'gini_normalized', (['y_train', 'y_train_pred_1'], {}), '(y_train, y_train_pred_1)\n', (5409, 5434), False, 'from util import gini_normalized\n'), ((5473, 5513), 'util.gini_normalized', 'gini_normalized', (['y_train', 'y_train_pred_2'], {}), '(y_train, y_train_pred_2)\n', (5488, 5513), False, 'from util import gini_normalized\n'), ((5552, 5592), 'util.gini_normalized', 'gini_normalized', (['y_train', 'y_train_pred_3'], {}), '(y_train, y_train_pred_3)\n', (5567, 5592), False, 'from util import gini_normalized\n'), ((5640, 5678), 'util.gini_normalized', 'gini_normalized', (['y_train', 'y_train_pred'], {}), '(y_train, y_train_pred)\n', (5655, 5678), False, 'from util import gini_normalized\n'), ((1878, 1920), 'numpy.exp', 'np.exp', (["(-(probs['counts'] - 1) / smoothing)"], {}), "(-(probs['counts'] - 1) / smoothing)\n", (1884, 1920), True, 'import numpy as np\n')]
import numpy as np import random import tensorflow as tf from lwau import LWAU from tensorflow.python.platform import flags import os from task_generator import TaskGenerator FLAGS = flags.FLAGS flags.DEFINE_integer('metatrain_iterations', 60000, 'number of metatraining iterations.') # Training options flags.DEFINE_integer('num_classes', 5, 'number of classes used in classification') flags.DEFINE_integer('meta_batch_size', 4, 'number of tasks sampled per meta-training iteration') flags.DEFINE_float('meta_lr', 0.001, 'the meta learning rate') flags.DEFINE_float('update_lr', 0.01, 'the inner-update learning rate') flags.DEFINE_integer('update_batch_size', 1, 'K for K-shot learning.') flags.DEFINE_integer('num_updates', 5, 'number of inner update steps during training.') flags.DEFINE_integer('num_train_tasks', 20, 'number of meta training tasks.') flags.DEFINE_float('l2_alpha', 0.001, 'param of the l2_norm') flags.DEFINE_float('l1_alpha', 0.001, 'param of the l1_norm') flags.DEFINE_float('dropout_rate', 0, 'dropout_rate of the FC layer') flags.DEFINE_integer('base_num_filters', 16, 'number of filters for conv nets.') flags.DEFINE_integer('test_num_updates', 10, 'number of inner update steps during testing') ## Logging, saving, and testing options flags.DEFINE_bool('log', True, 'if false, do not log summaries, for debugging code.') flags.DEFINE_string('logdir', 'logs/miniimagenet1shot/', 'directory for summaries and checkpoints.') flags.DEFINE_bool('resume', False, 'resume training if there is a model available') flags.DEFINE_bool('train', True, 'True to train, False to test.') flags.DEFINE_integer('test_iter', -1, 'iteration to load model (-1 for latest model)') flags.DEFINE_bool('test_set', False, 'Set to true to test on the the test set, False for the validation set.') flags.DEFINE_bool('data_aug', False, 'whether use the data augmentation.') flags.DEFINE_string('backbone', 'Conv4', 'Conv4 or ResNet12 backone.') if FLAGS.train: NUM_TEST_POINTS = int(600/FLAGS.meta_batch_size) else: NUM_TEST_POINTS = 600 LEN_MODELS = 50 PRINT_INTERVAL = 50 TEST_PRINT_INTERVAL = PRINT_INTERVAL*6 def train(model, saver, sess, exp_string, task_generator, resume_itr=0): print('Done initializing, starting training.') print(exp_string) prelosses, postlosses = [], [] models = {} for itr in range(resume_itr, FLAGS.metatrain_iterations): if FLAGS.backbone == 'Conv4': feed_dict = {model.meta_lr: FLAGS.meta_lr} else: lr = FLAGS.meta_lr * 0.5 ** int(itr / 15000) feed_dict = {model.meta_lr: lr} inputa, labela, inputb, labelb = task_generator.get_data_n_tasks(FLAGS.meta_batch_size, train=True) feed_dict[model.inputa] = inputa feed_dict[model.labela] = labela feed_dict[model.inputb] = inputb feed_dict[model.labelb] = labelb input_tensors = [model.metatrain_op] input_tensors.extend([model.total_loss1, model.total_losses2[FLAGS.num_updates-1]]) input_tensors.extend([model.total_accuracy1, model.total_accuracies2[FLAGS.num_updates-1]]) result = sess.run(input_tensors, feed_dict) prelosses.append(result[-2]) postlosses.append(result[-1]) if (itr!=0) and itr % PRINT_INTERVAL == 0: print_str = 'Iteration ' + str(itr) print_str += ': ' + str(np.mean(prelosses)) + ', ' + str(np.mean(postlosses)) print(print_str) prelosses, postlosses = [], [] # sinusoid is infinite data, so no need to test on meta-validation set. if (itr!=0) and itr % TEST_PRINT_INTERVAL == 0: metaval_accuracies = [] for _ in range(NUM_TEST_POINTS): feed_dict = {} inputa, labela, inputb, labelb = task_generator.get_data_n_tasks(FLAGS.meta_batch_size, train=False) feed_dict[model.inputa] = inputa feed_dict[model.labela] = labela feed_dict[model.inputb] = inputb feed_dict[model.labelb] = labelb input_tensors = [[model.metaval_total_accuracy1] + model.metaval_total_accuracies2] result = sess.run(input_tensors, feed_dict) metaval_accuracies.append(result[0]) metaval_accuracies = np.array(metaval_accuracies) means = np.mean(metaval_accuracies, 0) stds = np.std(metaval_accuracies, 0) ci95 = 1.96 * stds / np.sqrt(NUM_TEST_POINTS) print('----------------------------------------', itr) print('Mean validation accuracy:', means) print('Mean validation loss:', stds) print('Mean validation stddev', ci95) print('----------------------------------------', ) val_postaccs = max(means) model_name = FLAGS.logdir + '/' + exp_string + '/model' + str(itr) if len(models) >= LEN_MODELS: min_acc, min_model = min(zip(models.values(), models.keys())) if val_postaccs > min_acc: del models[min_model] models[model_name] = val_postaccs saver.save(sess, model_name) # os.remove(min_model+'.meta') os.remove(min_model + '.data-00000-of-00001') os.remove(min_model + '.index') os.remove(model_name + '.meta') else: pass max_acc, max_model = max(zip(models.values(), models.keys())) print(max_model, ':', max_acc) else: models[model_name] = val_postaccs saver.save(sess, model_name) os.remove(model_name + '.meta') saver.save(sess, FLAGS.logdir + '/' + exp_string + '/model' + str(itr)) def test(model, sess, task_generator): np.random.seed(1) random.seed(1) metaval_accuracies = [] max_acc = 0 print(NUM_TEST_POINTS) for _ in range(NUM_TEST_POINTS): feed_dict = {model.meta_lr : 0.0} inputa, labela, inputb, labelb = task_generator.get_data_n_tasks(FLAGS.meta_batch_size, train=False) feed_dict[model.inputa] = inputa feed_dict[model.labela] = labela feed_dict[model.inputb] = inputb feed_dict[model.labelb] = labelb result = sess.run([model.metaval_total_accuracy1] + model.metaval_total_accuracies2, feed_dict) metaval_accuracies.append(result) metaval_accuracies = np.array(metaval_accuracies) means = np.mean(metaval_accuracies, 0) stds = np.std(metaval_accuracies, 0) ci95 = 1.96*stds/np.sqrt(NUM_TEST_POINTS) for mean_acc in means: if mean_acc> max_acc: max_acc=mean_acc print('Mean validation accuracy:', means) print('Mean validation loss:', stds) print('Mean validation stddev', ci95) return max_acc def main(): FLAGS.logdir = 'logs/miniimagenet' + str(FLAGS.update_batch_size) + 'shot/' if FLAGS.train == False: orig_meta_batch_size = FLAGS.meta_batch_size FLAGS.meta_batch_size = 1 orig_update_batch_size = FLAGS.update_batch_size task_generator = TaskGenerator(FLAGS.update_batch_size+15, FLAGS.meta_batch_size) dim_output = task_generator.dim_output dim_input = task_generator.dim_input model = LWAU(dim_input, dim_output) if FLAGS.train : model.construct_model(num_updates=FLAGS.num_updates, train=True) model.construct_model(num_updates=FLAGS.test_num_updates, train=False) # model.summ_op = tf.summary.merge_all() saver = loader = tf.train.Saver(tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES), max_to_keep=0) sess = tf.InteractiveSession() if FLAGS.train == False: # change to original meta batch size when loading model. FLAGS.meta_batch_size = orig_meta_batch_size FLAGS.update_batch_size = orig_update_batch_size exp_string = str(FLAGS.num_classes)+'.mbs_'+str(FLAGS.meta_batch_size) exp_string += '.nstep_' + str(FLAGS.num_updates) + '.tnstep_' + str(FLAGS.test_num_updates) exp_string += '.ubs_' + str(FLAGS.update_batch_size) + '.nts_' + str(FLAGS.num_train_tasks) exp_string += '.l1_' + str(FLAGS.l1_alpha) +'.l2_' + str(FLAGS.l2_alpha) exp_string += '.lr_' + str(FLAGS.meta_lr) + '.ulr_' + str(FLAGS.update_lr) exp_string += '.drop_' + str(FLAGS.dropout_rate) + '.nfs_' + str(FLAGS.base_num_filters) resume_itr = 0 model_file = None tf.global_variables_initializer().run() tf.train.start_queue_runners() if FLAGS.resume: model_file = tf.train.latest_checkpoint(FLAGS.logdir + '/' + exp_string) if FLAGS.test_iter > 0: model_file = model_file[:model_file.index('model')] + 'model' + str(FLAGS.test_iter) if model_file: ind1 = model_file.index('model') resume_itr = int(model_file[ind1+5:]) print("Restoring model weights from " + model_file) saver.restore(sess, model_file) if FLAGS.train: train(model, saver, sess, exp_string, task_generator, resume_itr) else: import os max_accs = 0 models = os.listdir(FLAGS.logdir + exp_string) model_epochs = [] for model_file in models: if 'model' in model_file and 'index' in model_file: i = model_file.find('del') j = model_file.find('.') model_epoch = model_file[i + 3:j] model_epochs.append(int(model_epoch)) model_epochs.sort() max_epoch = 0 for epoch in model_epochs: if epoch > float(FLAGS.metatrain_iterations) / 20: model_file = FLAGS.logdir + exp_string + '/model' + str(epoch) saver.restore(sess, model_file) print("testing model: " + model_file) acc = test(model, sess, task_generator) if acc > max_accs: max_accs = acc max_epoch = epoch print('----------max_acc:', max_accs, '-----------max_model:', max_epoch) else: pass if __name__ == "__main__": main()
[ "numpy.sqrt", "numpy.array", "os.remove", "numpy.mean", "os.listdir", "numpy.random.seed", "tensorflow.InteractiveSession", "tensorflow.python.platform.flags.DEFINE_integer", "tensorflow.train.start_queue_runners", "task_generator.TaskGenerator", "numpy.std", "tensorflow.train.latest_checkpoin...
[((197, 290), 'tensorflow.python.platform.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""metatrain_iterations"""', '(60000)', '"""number of metatraining iterations."""'], {}), "('metatrain_iterations', 60000,\n 'number of metatraining iterations.')\n", (217, 290), False, 'from tensorflow.python.platform import flags\n'), ((307, 393), 'tensorflow.python.platform.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""num_classes"""', '(5)', '"""number of classes used in classification"""'], {}), "('num_classes', 5,\n 'number of classes used in classification')\n", (327, 393), False, 'from tensorflow.python.platform import flags\n'), ((390, 491), 'tensorflow.python.platform.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""meta_batch_size"""', '(4)', '"""number of tasks sampled per meta-training iteration"""'], {}), "('meta_batch_size', 4,\n 'number of tasks sampled per meta-training iteration')\n", (410, 491), False, 'from tensorflow.python.platform import flags\n'), ((488, 550), 'tensorflow.python.platform.flags.DEFINE_float', 'flags.DEFINE_float', (['"""meta_lr"""', '(0.001)', '"""the meta learning rate"""'], {}), "('meta_lr', 0.001, 'the meta learning rate')\n", (506, 550), False, 'from tensorflow.python.platform import flags\n'), ((551, 622), 'tensorflow.python.platform.flags.DEFINE_float', 'flags.DEFINE_float', (['"""update_lr"""', '(0.01)', '"""the inner-update learning rate"""'], {}), "('update_lr', 0.01, 'the inner-update learning rate')\n", (569, 622), False, 'from tensorflow.python.platform import flags\n'), ((623, 693), 'tensorflow.python.platform.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""update_batch_size"""', '(1)', '"""K for K-shot learning."""'], {}), "('update_batch_size', 1, 'K for K-shot learning.')\n", (643, 693), False, 'from tensorflow.python.platform import flags\n'), ((694, 785), 'tensorflow.python.platform.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""num_updates"""', '(5)', '"""number of inner update steps during training."""'], {}), "('num_updates', 5,\n 'number of inner update steps during training.')\n", (714, 785), False, 'from tensorflow.python.platform import flags\n'), ((782, 859), 'tensorflow.python.platform.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""num_train_tasks"""', '(20)', '"""number of meta training tasks."""'], {}), "('num_train_tasks', 20, 'number of meta training tasks.')\n", (802, 859), False, 'from tensorflow.python.platform import flags\n'), ((860, 921), 'tensorflow.python.platform.flags.DEFINE_float', 'flags.DEFINE_float', (['"""l2_alpha"""', '(0.001)', '"""param of the l2_norm"""'], {}), "('l2_alpha', 0.001, 'param of the l2_norm')\n", (878, 921), False, 'from tensorflow.python.platform import flags\n'), ((922, 983), 'tensorflow.python.platform.flags.DEFINE_float', 'flags.DEFINE_float', (['"""l1_alpha"""', '(0.001)', '"""param of the l1_norm"""'], {}), "('l1_alpha', 0.001, 'param of the l1_norm')\n", (940, 983), False, 'from tensorflow.python.platform import flags\n'), ((984, 1053), 'tensorflow.python.platform.flags.DEFINE_float', 'flags.DEFINE_float', (['"""dropout_rate"""', '(0)', '"""dropout_rate of the FC layer"""'], {}), "('dropout_rate', 0, 'dropout_rate of the FC layer')\n", (1002, 1053), False, 'from tensorflow.python.platform import flags\n'), ((1054, 1139), 'tensorflow.python.platform.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""base_num_filters"""', '(16)', '"""number of filters for conv nets."""'], {}), "('base_num_filters', 16, 'number of filters for conv nets.'\n )\n", (1074, 1139), False, 'from tensorflow.python.platform import flags\n'), ((1135, 1230), 'tensorflow.python.platform.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""test_num_updates"""', '(10)', '"""number of inner update steps during testing"""'], {}), "('test_num_updates', 10,\n 'number of inner update steps during testing')\n", (1155, 1230), False, 'from tensorflow.python.platform import flags\n'), ((1268, 1357), 'tensorflow.python.platform.flags.DEFINE_bool', 'flags.DEFINE_bool', (['"""log"""', '(True)', '"""if false, do not log summaries, for debugging code."""'], {}), "('log', True,\n 'if false, do not log summaries, for debugging code.')\n", (1285, 1357), False, 'from tensorflow.python.platform import flags\n'), ((1354, 1458), 'tensorflow.python.platform.flags.DEFINE_string', 'flags.DEFINE_string', (['"""logdir"""', '"""logs/miniimagenet1shot/"""', '"""directory for summaries and checkpoints."""'], {}), "('logdir', 'logs/miniimagenet1shot/',\n 'directory for summaries and checkpoints.')\n", (1373, 1458), False, 'from tensorflow.python.platform import flags\n'), ((1455, 1542), 'tensorflow.python.platform.flags.DEFINE_bool', 'flags.DEFINE_bool', (['"""resume"""', '(False)', '"""resume training if there is a model available"""'], {}), "('resume', False,\n 'resume training if there is a model available')\n", (1472, 1542), False, 'from tensorflow.python.platform import flags\n'), ((1539, 1604), 'tensorflow.python.platform.flags.DEFINE_bool', 'flags.DEFINE_bool', (['"""train"""', '(True)', '"""True to train, False to test."""'], {}), "('train', True, 'True to train, False to test.')\n", (1556, 1604), False, 'from tensorflow.python.platform import flags\n'), ((1605, 1695), 'tensorflow.python.platform.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""test_iter"""', '(-1)', '"""iteration to load model (-1 for latest model)"""'], {}), "('test_iter', -1,\n 'iteration to load model (-1 for latest model)')\n", (1625, 1695), False, 'from tensorflow.python.platform import flags\n'), ((1692, 1806), 'tensorflow.python.platform.flags.DEFINE_bool', 'flags.DEFINE_bool', (['"""test_set"""', '(False)', '"""Set to true to test on the the test set, False for the validation set."""'], {}), "('test_set', False,\n 'Set to true to test on the the test set, False for the validation set.')\n", (1709, 1806), False, 'from tensorflow.python.platform import flags\n'), ((1804, 1878), 'tensorflow.python.platform.flags.DEFINE_bool', 'flags.DEFINE_bool', (['"""data_aug"""', '(False)', '"""whether use the data augmentation."""'], {}), "('data_aug', False, 'whether use the data augmentation.')\n", (1821, 1878), False, 'from tensorflow.python.platform import flags\n'), ((1879, 1949), 'tensorflow.python.platform.flags.DEFINE_string', 'flags.DEFINE_string', (['"""backbone"""', '"""Conv4"""', '"""Conv4 or ResNet12 backone."""'], {}), "('backbone', 'Conv4', 'Conv4 or ResNet12 backone.')\n", (1898, 1949), False, 'from tensorflow.python.platform import flags\n'), ((5918, 5935), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (5932, 5935), True, 'import numpy as np\n'), ((5940, 5954), 'random.seed', 'random.seed', (['(1)'], {}), '(1)\n', (5951, 5954), False, 'import random\n'), ((6552, 6580), 'numpy.array', 'np.array', (['metaval_accuracies'], {}), '(metaval_accuracies)\n', (6560, 6580), True, 'import numpy as np\n'), ((6593, 6623), 'numpy.mean', 'np.mean', (['metaval_accuracies', '(0)'], {}), '(metaval_accuracies, 0)\n', (6600, 6623), True, 'import numpy as np\n'), ((6635, 6664), 'numpy.std', 'np.std', (['metaval_accuracies', '(0)'], {}), '(metaval_accuracies, 0)\n', (6641, 6664), True, 'import numpy as np\n'), ((7238, 7304), 'task_generator.TaskGenerator', 'TaskGenerator', (['(FLAGS.update_batch_size + 15)', 'FLAGS.meta_batch_size'], {}), '(FLAGS.update_batch_size + 15, FLAGS.meta_batch_size)\n', (7251, 7304), False, 'from task_generator import TaskGenerator\n'), ((7400, 7427), 'lwau.LWAU', 'LWAU', (['dim_input', 'dim_output'], {}), '(dim_input, dim_output)\n', (7404, 7427), False, 'from lwau import LWAU\n'), ((7760, 7783), 'tensorflow.InteractiveSession', 'tf.InteractiveSession', ([], {}), '()\n', (7781, 7783), True, 'import tensorflow as tf\n'), ((8598, 8628), 'tensorflow.train.start_queue_runners', 'tf.train.start_queue_runners', ([], {}), '()\n', (8626, 8628), True, 'import tensorflow as tf\n'), ((6686, 6710), 'numpy.sqrt', 'np.sqrt', (['NUM_TEST_POINTS'], {}), '(NUM_TEST_POINTS)\n', (6693, 6710), True, 'import numpy as np\n'), ((7680, 7731), 'tensorflow.get_collection', 'tf.get_collection', (['tf.GraphKeys.TRAINABLE_VARIABLES'], {}), '(tf.GraphKeys.TRAINABLE_VARIABLES)\n', (7697, 7731), True, 'import tensorflow as tf\n'), ((8672, 8731), 'tensorflow.train.latest_checkpoint', 'tf.train.latest_checkpoint', (["(FLAGS.logdir + '/' + exp_string)"], {}), "(FLAGS.logdir + '/' + exp_string)\n", (8698, 8731), True, 'import tensorflow as tf\n'), ((9248, 9285), 'os.listdir', 'os.listdir', (['(FLAGS.logdir + exp_string)'], {}), '(FLAGS.logdir + exp_string)\n', (9258, 9285), False, 'import os\n'), ((4344, 4372), 'numpy.array', 'np.array', (['metaval_accuracies'], {}), '(metaval_accuracies)\n', (4352, 4372), True, 'import numpy as np\n'), ((4393, 4423), 'numpy.mean', 'np.mean', (['metaval_accuracies', '(0)'], {}), '(metaval_accuracies, 0)\n', (4400, 4423), True, 'import numpy as np\n'), ((4443, 4472), 'numpy.std', 'np.std', (['metaval_accuracies', '(0)'], {}), '(metaval_accuracies, 0)\n', (4449, 4472), True, 'import numpy as np\n'), ((8554, 8587), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (8585, 8587), True, 'import tensorflow as tf\n'), ((4506, 4530), 'numpy.sqrt', 'np.sqrt', (['NUM_TEST_POINTS'], {}), '(NUM_TEST_POINTS)\n', (4513, 4530), True, 'import numpy as np\n'), ((5763, 5794), 'os.remove', 'os.remove', (["(model_name + '.meta')"], {}), "(model_name + '.meta')\n", (5772, 5794), False, 'import os\n'), ((3424, 3443), 'numpy.mean', 'np.mean', (['postlosses'], {}), '(postlosses)\n', (3431, 3443), True, 'import numpy as np\n'), ((5312, 5357), 'os.remove', 'os.remove', (["(min_model + '.data-00000-of-00001')"], {}), "(min_model + '.data-00000-of-00001')\n", (5321, 5357), False, 'import os\n'), ((5378, 5409), 'os.remove', 'os.remove', (["(min_model + '.index')"], {}), "(min_model + '.index')\n", (5387, 5409), False, 'import os\n'), ((5430, 5461), 'os.remove', 'os.remove', (["(model_name + '.meta')"], {}), "(model_name + '.meta')\n", (5439, 5461), False, 'import os\n'), ((3391, 3409), 'numpy.mean', 'np.mean', (['prelosses'], {}), '(prelosses)\n', (3398, 3409), True, 'import numpy as np\n')]
from __future__ import absolute_import, division, print_function import os import os.path as osp import pprint import time import numpy as np import torch import yaml from torch.autograd import Variable from torch.utils.data import DataLoader from sacred import Experiment from tracktor.config import get_output_dir from tracktor.datasets.factory import Datasets from tracktor.oracle_tracker import OracleTracker from tracktor.resnet import resnet50 from tracktor.tracker import Tracker from tracktor.utils import interpolate, plot_sequence ex = Experiment() ex.add_config('experiments/cfgs/tracktor.yaml') # hacky workaround to load the corresponding configs and not having to hardcode paths here ex.add_config(ex.configurations[0]._conf['tracktor']['reid_network_config']) ex.add_config(ex.configurations[0]._conf['tracktor']['obj_detect_config']) ex.add_named_config('oracle', 'experiments/cfgs/oracle_tracktor.yaml') # Tracker = ex.capture(Tracker, prefix='tracker.tracker') @ex.automain # 相当于讲my_main()作为参数,传入automain()并执行 def my_main(tracktor, siamese, _config): # set all seeds torch.manual_seed(tracktor['seed']) torch.cuda.manual_seed(tracktor['seed']) np.random.seed(tracktor['seed']) torch.backends.cudnn.deterministic = True output_dir = osp.join(get_output_dir(tracktor['module_name']), tracktor['name']) sacred_config = osp.join(output_dir, 'sacred_config.yaml') if not osp.exists(output_dir): os.makedirs(output_dir) with open(sacred_config, 'w') as outfile: yaml.dump(_config, outfile, default_flow_style=False) ########################## # Initialize the modules # ########################## # object detection print("[*] Building object detector") if tracktor['network'].startswith('frcnn'): # FRCNN from tracktor.frcnn import FRCNN from frcnn.model import config if _config['frcnn']['cfg_file']: config.cfg_from_file(_config['frcnn']['cfg_file']) if _config['frcnn']['set_cfgs']: config.cfg_from_list(_config['frcnn']['set_cfgs']) obj_detect = FRCNN(num_layers=101) obj_detect.create_architecture(2, tag='default', anchor_scales=config.cfg.ANCHOR_SCALES, anchor_ratios=config.cfg.ANCHOR_RATIOS) obj_detect.load_state_dict(torch.load(tracktor['obj_detect_weights'])) elif tracktor['network'].startswith('fpn'): # FPN from tracktor.fpn import FPN from fpn.model.utils import config config.cfg.TRAIN.USE_FLIPPED = False config.cfg.CUDA = True config.cfg.TRAIN.USE_FLIPPED = False checkpoint = torch.load(tracktor['obj_detect_weights']) if 'pooling_mode' in checkpoint.keys(): config.cfg.POOLING_MODE = checkpoint['pooling_mode'] set_cfgs = ['ANCHOR_SCALES', '[4, 8, 16, 32]', 'ANCHOR_RATIOS', '[0.5,1,2]'] config.cfg_from_file(_config['tracktor']['obj_detect_config']) config.cfg_from_list(set_cfgs) obj_detect = FPN(('__background__', 'pedestrian'), 101, pretrained=False) obj_detect.create_architecture() obj_detect.load_state_dict(checkpoint['model']) else: raise NotImplementedError(f"Object detector type not known: {tracktor['network']}") pprint.pprint(config.cfg) obj_detect.eval() obj_detect.cuda() # reid reid_network = resnet50(pretrained=False, **siamese['cnn']) reid_network.load_state_dict(torch.load(tracktor['reid_network_weights'])) reid_network.eval() reid_network.cuda() # tracktor if 'oracle' in tracktor: tracker = OracleTracker(obj_detect, reid_network, tracktor['tracker'], tracktor['oracle']) else: tracker = Tracker(obj_detect, reid_network, tracktor['tracker']) print("[*] Beginning evaluation...") time_total = 0 for sequence in Datasets(tracktor['dataset']): tracker.reset() now = time.time() print("[*] Evaluating: {}".format(sequence)) data_loader = DataLoader(sequence, batch_size=1, shuffle=False) for i, frame in enumerate(data_loader): # frame_split = [0.0, 1.0] if i >= len(sequence) * tracktor['frame_split'][0] and i <= len(sequence) * tracktor['frame_split'][1]: tracker.step(frame) results = tracker.get_results() time_total += time.time() - now print("[*] Tracks found: {}".format(len(results))) print("[*] Time needed for {} evaluation: {:.3f} s".format(sequence, time.time() - now)) if tracktor['interpolate']: results = interpolate(results) sequence.write_results(results, osp.join(output_dir)) if tracktor['write_images']: plot_sequence(results, sequence, osp.join(output_dir, tracktor['dataset'], str(sequence))) print("[*] Evaluation for all sets (without image generation): {:.3f} s".format(time_total))
[ "tracktor.oracle_tracker.OracleTracker", "pprint.pprint", "os.path.exists", "fpn.model.utils.config.cfg_from_list", "numpy.random.seed", "tracktor.tracker.Tracker", "tracktor.frcnn.FRCNN", "tracktor.datasets.factory.Datasets", "tracktor.resnet.resnet50", "yaml.dump", "sacred.Experiment", "time...
[((550, 562), 'sacred.Experiment', 'Experiment', ([], {}), '()\n', (560, 562), False, 'from sacred import Experiment\n'), ((1102, 1137), 'torch.manual_seed', 'torch.manual_seed', (["tracktor['seed']"], {}), "(tracktor['seed'])\n", (1119, 1137), False, 'import torch\n'), ((1142, 1182), 'torch.cuda.manual_seed', 'torch.cuda.manual_seed', (["tracktor['seed']"], {}), "(tracktor['seed'])\n", (1164, 1182), False, 'import torch\n'), ((1187, 1219), 'numpy.random.seed', 'np.random.seed', (["tracktor['seed']"], {}), "(tracktor['seed'])\n", (1201, 1219), True, 'import numpy as np\n'), ((1372, 1414), 'os.path.join', 'osp.join', (['output_dir', '"""sacred_config.yaml"""'], {}), "(output_dir, 'sacred_config.yaml')\n", (1380, 1414), True, 'import os.path as osp\n'), ((3333, 3358), 'pprint.pprint', 'pprint.pprint', (['config.cfg'], {}), '(config.cfg)\n', (3346, 3358), False, 'import pprint\n'), ((3434, 3478), 'tracktor.resnet.resnet50', 'resnet50', ([], {'pretrained': '(False)'}), "(pretrained=False, **siamese['cnn'])\n", (3442, 3478), False, 'from tracktor.resnet import resnet50\n'), ((3915, 3944), 'tracktor.datasets.factory.Datasets', 'Datasets', (["tracktor['dataset']"], {}), "(tracktor['dataset'])\n", (3923, 3944), False, 'from tracktor.datasets.factory import Datasets\n'), ((1293, 1332), 'tracktor.config.get_output_dir', 'get_output_dir', (["tracktor['module_name']"], {}), "(tracktor['module_name'])\n", (1307, 1332), False, 'from tracktor.config import get_output_dir\n'), ((1427, 1449), 'os.path.exists', 'osp.exists', (['output_dir'], {}), '(output_dir)\n', (1437, 1449), True, 'import os.path as osp\n'), ((1459, 1482), 'os.makedirs', 'os.makedirs', (['output_dir'], {}), '(output_dir)\n', (1470, 1482), False, 'import os\n'), ((1537, 1590), 'yaml.dump', 'yaml.dump', (['_config', 'outfile'], {'default_flow_style': '(False)'}), '(_config, outfile, default_flow_style=False)\n', (1546, 1590), False, 'import yaml\n'), ((2126, 2147), 'tracktor.frcnn.FRCNN', 'FRCNN', ([], {'num_layers': '(101)'}), '(num_layers=101)\n', (2131, 2147), False, 'from tracktor.frcnn import FRCNN\n'), ((3512, 3556), 'torch.load', 'torch.load', (["tracktor['reid_network_weights']"], {}), "(tracktor['reid_network_weights'])\n", (3522, 3556), False, 'import torch\n'), ((3669, 3754), 'tracktor.oracle_tracker.OracleTracker', 'OracleTracker', (['obj_detect', 'reid_network', "tracktor['tracker']", "tracktor['oracle']"], {}), "(obj_detect, reid_network, tracktor['tracker'], tracktor['oracle']\n )\n", (3682, 3754), False, 'from tracktor.oracle_tracker import OracleTracker\n'), ((3778, 3832), 'tracktor.tracker.Tracker', 'Tracker', (['obj_detect', 'reid_network', "tracktor['tracker']"], {}), "(obj_detect, reid_network, tracktor['tracker'])\n", (3785, 3832), False, 'from tracktor.tracker import Tracker\n'), ((3985, 3996), 'time.time', 'time.time', ([], {}), '()\n', (3994, 3996), False, 'import time\n'), ((4074, 4123), 'torch.utils.data.DataLoader', 'DataLoader', (['sequence'], {'batch_size': '(1)', 'shuffle': '(False)'}), '(sequence, batch_size=1, shuffle=False)\n', (4084, 4123), False, 'from torch.utils.data import DataLoader\n'), ((1949, 1999), 'fpn.model.utils.config.cfg_from_file', 'config.cfg_from_file', (["_config['frcnn']['cfg_file']"], {}), "(_config['frcnn']['cfg_file'])\n", (1969, 1999), False, 'from fpn.model.utils import config\n'), ((2053, 2103), 'fpn.model.utils.config.cfg_from_list', 'config.cfg_from_list', (["_config['frcnn']['set_cfgs']"], {}), "(_config['frcnn']['set_cfgs'])\n", (2073, 2103), False, 'from fpn.model.utils import config\n'), ((2344, 2386), 'torch.load', 'torch.load', (["tracktor['obj_detect_weights']"], {}), "(tracktor['obj_detect_weights'])\n", (2354, 2386), False, 'import torch\n'), ((2672, 2714), 'torch.load', 'torch.load', (["tracktor['obj_detect_weights']"], {}), "(tracktor['obj_detect_weights'])\n", (2682, 2714), False, 'import torch\n'), ((2943, 3005), 'fpn.model.utils.config.cfg_from_file', 'config.cfg_from_file', (["_config['tracktor']['obj_detect_config']"], {}), "(_config['tracktor']['obj_detect_config'])\n", (2963, 3005), False, 'from fpn.model.utils import config\n'), ((3014, 3044), 'fpn.model.utils.config.cfg_from_list', 'config.cfg_from_list', (['set_cfgs'], {}), '(set_cfgs)\n', (3034, 3044), False, 'from fpn.model.utils import config\n'), ((3067, 3127), 'tracktor.fpn.FPN', 'FPN', (["('__background__', 'pedestrian')", '(101)'], {'pretrained': '(False)'}), "(('__background__', 'pedestrian'), 101, pretrained=False)\n", (3070, 3127), False, 'from tracktor.fpn import FPN\n'), ((4444, 4455), 'time.time', 'time.time', ([], {}), '()\n', (4453, 4455), False, 'import time\n'), ((4678, 4698), 'tracktor.utils.interpolate', 'interpolate', (['results'], {}), '(results)\n', (4689, 4698), False, 'from tracktor.utils import interpolate, plot_sequence\n'), ((4740, 4760), 'os.path.join', 'osp.join', (['output_dir'], {}), '(output_dir)\n', (4748, 4760), True, 'import os.path as osp\n'), ((4599, 4610), 'time.time', 'time.time', ([], {}), '()\n', (4608, 4610), False, 'import time\n')]
from datetime import datetime from dateutil.tz import tzlocal, tzutc import pandas as pd import numpy as np from hdmf.backends.hdf5 import HDF5IO from hdmf.common import DynamicTable from pynwb import NWBFile, TimeSeries, NWBHDF5IO, get_manager from pynwb.file import Subject from pynwb.epoch import TimeIntervals from pynwb.ecephys import ElectricalSeries from pynwb.testing import NWBH5IOMixin, TestCase, remove_test_file class TestNWBFileHDF5IO(TestCase): """ Test reading/writing an NWBFile using HDF5IO """ def setUp(self): """ Set up an NWBFile object with an acquisition TimeSeries, analysis TimeSeries, and a processing module """ self.start_time = datetime(1970, 1, 1, 12, tzinfo=tzutc()) self.ref_time = datetime(1979, 1, 1, 0, tzinfo=tzutc()) self.create_date = datetime(2017, 4, 15, 12, tzinfo=tzlocal()) self.manager = get_manager() self.filename = 'test_nwbfileio.h5' self.nwbfile = NWBFile(session_description='a test NWB File', identifier='TEST123', session_start_time=self.start_time, timestamps_reference_time=self.ref_time, file_create_date=self.create_date, experimenter='test experimenter', stimulus_notes='test stimulus notes', data_collection='test data collection notes', experiment_description='test experiment description', institution='nomad', lab='nolab', notes='nonotes', pharmacology='nopharmacology', protocol='noprotocol', related_publications='nopubs', session_id='007', slices='noslices', source_script='nosources', surgery='nosurgery', virus='novirus', source_script_file_name='nofilename') self.ts = TimeSeries(name='test_timeseries', data=list(range(100, 200, 10)), unit='SIunit', timestamps=np.arange(10.), resolution=0.1) self.nwbfile.add_acquisition(self.ts) self.ts2 = TimeSeries(name='test_timeseries2', data=list(range(200, 300, 10)), unit='SIunit', timestamps=np.arange(10.), resolution=0.1) self.nwbfile.add_analysis(self.ts2) self.mod = self.nwbfile.create_processing_module('test_module', 'a test module') self.ts3 = TimeSeries(name='test_timeseries2', data=list(range(100, 200, 10)), unit='SIunit', timestamps=np.arange(10.), resolution=0.1) self.mod.add(self.ts3) def tearDown(self): """ Delete the created test file """ remove_test_file(self.filename) def test_children(self): """ Test that the TimeSeries and processing module are children of their respective parents """ self.assertIn(self.ts, self.nwbfile.children) self.assertIn(self.ts2, self.nwbfile.children) self.assertIn(self.mod, self.nwbfile.children) self.assertIn(self.ts3, self.mod.children) def test_write(self): """ Test writing the NWBFile using HDF5IO """ hdf5io = HDF5IO(self.filename, manager=self.manager, mode='a') hdf5io.write(self.nwbfile) hdf5io.close() # TODO add some asserts def test_read(self): """ Test reading the NWBFile using HDF5IO """ hdf5io = HDF5IO(self.filename, manager=self.manager, mode='w') hdf5io.write(self.nwbfile) hdf5io.close() hdf5io = HDF5IO(self.filename, manager=self.manager, mode='r') container = hdf5io.read() self.assertIsInstance(container, NWBFile) self.assertEqual(len(container.acquisition), 1) self.assertEqual(len(container.analysis), 1) for v in container.acquisition.values(): self.assertIsInstance(v, TimeSeries) self.assertContainerEqual(container, self.nwbfile) hdf5io.close() class TestNWBFileIO(NWBH5IOMixin, TestCase): """ Test writing an NWBFile to disk and reading back the file """ # this uses methods tearDown, test_roundtrip, and validate from NWBH5IOMixin. the rest are overridden def setUp(self): super().setUp() self.start_time = datetime(1970, 1, 1, 12, tzinfo=tzutc()) self.ref_time = datetime(1979, 1, 1, 0, tzinfo=tzutc()) self.create_dates = [datetime(2017, 5, 1, 12, tzinfo=tzlocal()), datetime(2017, 5, 2, 13, 0, 0, 1, tzinfo=tzutc()), datetime(2017, 5, 2, 14, tzinfo=tzutc())] def setUpContainer(self): """ Return a placeholder NWBFile """ return NWBFile('placeholder', 'placeholder', datetime(1970, 1, 1, 12, tzinfo=tzutc())) def build_nwbfile(self): """ Create an NWB file """ self.container = NWBFile(session_description='a test session description for a test NWBFile', identifier='FILE123', session_start_time=self.start_time, file_create_date=self.create_dates, timestamps_reference_time=self.ref_time, experimenter='A test experimenter', lab='a test lab', institution='a test institution', experiment_description='a test experiment description', session_id='test1', notes='my notes', pharmacology='drugs', protocol='protocol', related_publications='my pubs', slices='my slices', surgery='surgery', virus='a virus', source_script='noscript', source_script_file_name='nofilename', stimulus_notes='test stimulus notes', data_collection='test data collection notes', keywords=('these', 'are', 'keywords')) def roundtripContainer(self, cache_spec=False): """ Build and write an NWBFile to disk, read the file, and return the NWBFile """ self.build_nwbfile() self.writer = NWBHDF5IO(self.filename, mode='w') self.writer.write(self.container, cache_spec=cache_spec) self.writer.close() self.reader = NWBHDF5IO(self.filename, mode='r') self.read_nwbfile = self.reader.read() return self.read_nwbfile def addContainer(self, nwbfile): """ No-op. roundtripContainer is overridden and no longer uses addContainer """ pass def getContainer(self, nwbfile): """ Get the NWBFile object from the given NWBFile """ return nwbfile class TestExperimentersConstructorRoundtrip(TestNWBFileIO): """ Test that a list of multiple experimenters in a constructor is written to and read from file """ def build_nwbfile(self): description = 'test nwbfile experimenter' identifier = 'TEST_experimenter' self.nwbfile = NWBFile(session_description=description, identifier=identifier, session_start_time=self.start_time, experimenter=('experimenter1', 'experimenter2')) class TestExperimentersSetterRoundtrip(TestNWBFileIO): """ Test that a list of multiple experimenters in a setter is written to and read from file """ def build_nwbfile(self): description = 'test nwbfile experimenter' identifier = 'TEST_experimenter' self.nwbfile = NWBFile(session_description=description, identifier=identifier, session_start_time=self.start_time) self.nwbfile.experimenter = ('experimenter1', 'experimenter2') class TestPublicationsConstructorRoundtrip(TestNWBFileIO): """ Test that a list of multiple publications in a constructor is written to and read from file """ def build_nwbfile(self): description = 'test nwbfile publications' identifier = 'TEST_publications' self.nwbfile = NWBFile(session_description=description, identifier=identifier, session_start_time=self.start_time, related_publications=('pub1', 'pub2')) class TestPublicationsSetterRoundtrip(TestNWBFileIO): """ Test that a list of multiple publications in a setter is written to and read from file """ def build_nwbfile(self): description = 'test nwbfile publications' identifier = 'TEST_publications' self.nwbfile = NWBFile(session_description=description, identifier=identifier, session_start_time=self.start_time) self.nwbfile.related_publications = ('pub1', 'pub2') class TestSubjectIO(NWBH5IOMixin, TestCase): def setUpContainer(self): """ Return the test Subject """ return Subject(age='P90D', description='An unfortunate rat', genotype='WT', sex='M', species='Rattus norvegicus', subject_id='RAT123', weight='2 kg', date_of_birth=datetime(1970, 1, 1, 12, tzinfo=tzutc()), strain='my_strain') def addContainer(self, nwbfile): """ Add the test Subject to the given NWBFile """ nwbfile.subject = self.container def getContainer(self, nwbfile): """ Return the test Subject from the given NWBFile """ return nwbfile.subject class TestEmptySubjectIO(TestSubjectIO): def setUpContainer(self): return Subject() class TestEpochsIO(NWBH5IOMixin, TestCase): def setUpContainer(self): """ Return placeholder epochs object. Tested epochs are added directly to the NWBFile in addContainer """ return TimeIntervals('epochs') def addContainer(self, nwbfile): """ Add the test epochs to the given NWBFile """ nwbfile.add_epoch_column( name='temperature', description='average temperture (c) during epoch' ) nwbfile.add_epoch( start_time=5.3, stop_time=6.1, timeseries=[], tags='ambient', temperature=26.4, ) # reset the thing self.container = nwbfile.epochs def getContainer(self, nwbfile): """ Return the test epochs from the given NWBFile """ return nwbfile.epochs class TestEpochsIODf(TestEpochsIO): def addContainer(self, nwbfile): """ Add the test epochs with TimeSeries objects to the given NWBFile """ tsa, tsb = [ TimeSeries(name='a', data=np.arange(11), unit='flubs', timestamps=np.linspace(0, 1, 11)), TimeSeries(name='b', data=np.arange(13), unit='flubs', timestamps=np.linspace(0.1, 5, 13)), ] nwbfile.add_acquisition(tsa) nwbfile.add_acquisition(tsb) nwbfile.epochs = TimeIntervals.from_dataframe( pd.DataFrame({ 'foo': [1, 2, 3, 4], 'bar': ['fish', 'fowl', 'dog', 'cat'], 'start_time': [0.2, 0.25, 0.30, 0.35], 'stop_time': [0.25, 0.30, 0.40, 0.45], 'timeseries': [[(2, 1, tsa)], [(3, 1, tsa)], [(3, 1, tsa)], [(4, 1, tsa)]], 'tags': [[''], [''], ['fizz', 'buzz'], ['qaz']] }), 'epochs', columns=[ {'name': 'foo', 'description': 'a column of integers'}, {'name': 'bar', 'description': 'a column of strings'}, ] ) # reset the thing self.container = nwbfile.epochs def test_df_comparison(self): """ Test that the epochs read from file converted to a data frame are the same as the data frame converted from the original epochs and the timeseries columns within them are the same """ self.read_container = self.roundtripContainer() df_obt = self.read_container.to_dataframe() tsa = self.read_nwbfile.get_acquisition('a') df_exp = pd.DataFrame({ 'foo': [1, 2, 3, 4], 'bar': ['fish', 'fowl', 'dog', 'cat'], 'start_time': [0.2, 0.25, 0.30, 0.35], 'stop_time': [0.25, 0.30, 0.40, 0.45], 'timeseries': [[(2, 1, tsa)], [(3, 1, tsa)], [(3, 1, tsa)], [(4, 1, tsa)]], 'tags': [[''], [''], ['fizz', 'buzz'], ['qaz']] }, index=pd.Index(np.arange(4), name='id') ) # pop the timeseries column out because ts_obt has rows of lists of tuples and ts_exp has rows of lists of lists ts_obt = df_obt.pop('timeseries') ts_exp = df_exp.pop('timeseries') pd.testing.assert_frame_equal(df_exp, df_obt, check_like=True, check_dtype=False) # check the timeseries columns match for ex, obt in zip(ts_exp, ts_obt): self.assertEqual(ex[0][0], obt[0][0]) self.assertEqual(ex[0][1], obt[0][1]) self.assertContainerEqual(ex[0][2], obt[0][2]) def test_df_comparison_no_ts(self): """ Test that the epochs read from file converted to a data frame are the same as the data frame converted from the original epochs without a timeseries column """ self.read_container = self.roundtripContainer() df_exp = pd.DataFrame({ 'foo': [1, 2, 3, 4], 'bar': ['fish', 'fowl', 'dog', 'cat'], 'start_time': [0.2, 0.25, 0.30, 0.35], 'stop_time': [0.25, 0.30, 0.40, 0.45], 'tags': [[''], [''], ['fizz', 'buzz'], ['qaz']] }, index=pd.Index(np.arange(4), name='id') ) df_obt = self.read_container.to_dataframe(exclude=set(['timeseries', 'timeseries_index'])) pd.testing.assert_frame_equal(df_exp, df_obt, check_like=True, check_dtype=False) class TestTrials(NWBH5IOMixin, TestCase): def setUpContainer(self): """ Return placeholder Table for trials. Tested trials are added directly to the NWBFile in addContainer """ return DynamicTable(name='trials', description='a placeholder table') # this will get ignored def addContainer(self, nwbfile): """ Add trials and trial columns to the given NWBFile """ nwbfile.add_trial_column('foo', 'an int column') nwbfile.add_trial_column('bar', 'a float column') nwbfile.add_trial_column('baz', 'a string column') nwbfile.add_trial_column('qux', 'a boolean column') nwbfile.add_trial(start_time=0., stop_time=1., foo=27, bar=28.0, baz="29", qux=True) nwbfile.add_trial(start_time=2., stop_time=3., foo=37, bar=38.0, baz="39", qux=False) self.container = nwbfile.trials # override self.container which has the placeholder def getContainer(self, nwbfile): """ Return the test trials table from the given NWBFile """ return nwbfile.trials class TestInvalidTimes(NWBH5IOMixin, TestCase): def setUpContainer(self): """ Return placeholder Table for trials. Tested invalid times are added directly to the NWBFile in addContainer """ return DynamicTable(name='invalid times', description='a placeholder table') def addContainer(self, nwbfile): """ Add invalid times and invalid times columns to the given NWBFile """ nwbfile.add_invalid_times_column('foo', 'an int column') nwbfile.add_invalid_times_column('bar', 'a float column') nwbfile.add_invalid_times_column('baz', 'a string column') nwbfile.add_invalid_times_column('qux', 'a boolean column') nwbfile.add_invalid_time_interval(start_time=0., stop_time=1., foo=27, bar=28.0, baz="29", qux=True) nwbfile.add_invalid_time_interval(start_time=2., stop_time=3., foo=37, bar=38.0, baz="39", qux=False) self.container = nwbfile.invalid_times # override self.container which has the placeholder def getContainer(self, nwbfile): """ Return the test invalid times table from the given NWBFile """ return nwbfile.invalid_times class TestUnits(NWBH5IOMixin, TestCase): def setUpContainer(self): """ Return placeholder table for Units. Tested units are added directly to the NWBFile in addContainer """ return DynamicTable(name='units', description='a placeholder table') def addContainer(self, nwbfile): """ Add units and unit columns to the given NWBFile """ nwbfile.add_unit_column('foo', 'an int column') nwbfile.add_unit_column('my_bool', 'a bool column') nwbfile.add_unit(foo=27, my_bool=True) nwbfile.add_unit(foo=37, my_bool=False) self.container = nwbfile.units # override self.container which has the placeholder def getContainer(self, nwbfile): """ Return the test units table from the given NWBFile """ return nwbfile.units class TestDynamicTableFromDataframeIO(NWBH5IOMixin, TestCase): def setUpContainer(self): return DynamicTable.from_dataframe(pd.DataFrame({ 'a': [[1, 2, 3], [1, 2, 3], [1, 2, 3]], 'b': ['4', '5', '6'] }), 'test_table') def addContainer(self, nwbfile): test_mod = nwbfile.create_processing_module('test', 'desc') test_mod.add(self.container) def getContainer(self, nwbfile): dyn_tab = nwbfile.processing['test'].data_interfaces['test_table'] return dyn_tab def test_to_dataframe(self): dyn_tab = self.roundtripContainer() dyn_tab.to_dataframe() # also test 2D column round-trip class TestElectrodes(NWBH5IOMixin, TestCase): def setUpContainer(self): """ Return placeholder table for electrodes. Tested electrodes are added directly to the NWBFile in addContainer """ return DynamicTable('electrodes', 'a placeholder table') def addContainer(self, nwbfile): """ Add electrodes and related objects to the given NWBFile """ self.dev1 = nwbfile.create_device(name='dev1') self.group = nwbfile.create_electrode_group( name='tetrode1', description='tetrode description', location='tetrode location', device=self.dev1 ) nwbfile.add_electrode( id=1, x=1.0, y=2.0, z=3.0, imp=-1.0, location='CA1', filtering='none', group=self.group, group_name='tetrode1' ) nwbfile.add_electrode( id=2, x=1.0, y=2.0, z=3.0, imp=-2.0, location='CA1', filtering='none', group=self.group, group_name='tetrode1' ) self.container = nwbfile.electrodes # override self.container which has the placeholder def getContainer(self, nwbfile): """ Return the test electrodes table from the given NWBFile """ return nwbfile.electrodes def test_roundtrip(self): super().test_roundtrip() # When comparing the pandas dataframes for the row we drop the 'group' column since the # ElectrodeGroup object after reading will naturally have a different address pd.testing.assert_frame_equal(self.read_container[0].drop('group', axis=1), self.container[0].drop('group', axis=1)) class TestElectrodesOptColumns(NWBH5IOMixin, TestCase): def setUpContainer(self): """ Return placeholder table for electrodes. Tested electrodes are added directly to the NWBFile in addContainer """ return DynamicTable('electrodes', 'a placeholder table') def addContainer(self, nwbfile): """ Add electrodes and related objects to the given NWBFile """ self.dev1 = nwbfile.create_device(name='dev1') self.group = nwbfile.create_electrode_group( name='tetrode1', description='tetrode description', location='tetrode location', device=self.dev1 ) nwbfile.add_electrode( id=1, x=1.0, y=2.0, z=3.0, imp=-1.0, location='CA1', filtering='none', group=self.group, group_name='tetrode1', rel_x=4.0, rel_y=5.0, rel_z=6.0, reference='ref1' ) nwbfile.add_electrode( id=2, x=1.0, y=2.0, z=3.0, imp=-2.0, location='CA1', filtering='none', group=self.group, group_name='tetrode1', rel_x=4.0, rel_y=5.0, rel_z=6.0, reference='ref1' ) self.container = nwbfile.electrodes # override self.container which has the placeholder def getContainer(self, nwbfile): """ Return the test electrodes table from the given NWBFile """ return nwbfile.electrodes def test_roundtrip(self): super().test_roundtrip() # When comparing the pandas dataframes for the row we drop the 'group' column since the # ElectrodeGroup object after reading will naturally have a different address pd.testing.assert_frame_equal(self.read_container[0].drop('group', axis=1), self.container[0].drop('group', axis=1)) class TestElectrodesRegion(NWBH5IOMixin, TestCase): def setUpContainer(self): """ Return placeholder table for electrodes. Tested electrodes are added directly to the NWBFile in addContainer """ return DynamicTable('electrodes', 'a placeholder table') def addContainer(self, nwbfile): """ Add electrode table region and related objects to the given NWBFile """ self.dev1 = nwbfile.create_device(name='dev1') self.group = nwbfile.create_electrode_group(name='tetrode1', description='tetrode description', location='tetrode location', device=self.dev1) nwbfile.add_electrode(id=1, x=1.0, y=2.0, z=3.0, imp=-1.0, location='CA1', filtering='none', group=self.group, group_name='tetrode1') nwbfile.add_electrode(id=2, x=1.0, y=2.0, z=3.0, imp=-2.0, location='CA1', filtering='none', group=self.group, group_name='tetrode1') nwbfile.add_electrode(id=3, x=1.0, y=2.0, z=3.0, imp=-3.0, location='CA1', filtering='none', group=self.group, group_name='tetrode1') nwbfile.add_electrode(id=4, x=1.0, y=2.0, z=3.0, imp=-4.0, location='CA1', filtering='none', group=self.group, group_name='tetrode1') region = nwbfile.create_electrode_table_region( region=tuple([1, 2, 3]), name='electrodes', description='desc' ) nwbfile.add_acquisition(ElectricalSeries( name='test_data', data=np.arange(10), timestamps=np.arange(10.), electrodes=region )) self.container = region # override self.container which has the placeholder def getContainer(self, nwbfile): """ Return the test electrodes table from the given NWBFile """ self.table = nwbfile.electrodes return nwbfile.get_acquisition('test_data').electrodes def test_roundtrip(self): super().test_roundtrip() for ii, item in enumerate(self.read_container): pd.testing.assert_frame_equal(self.table[ii+1], item)
[ "dateutil.tz.tzlocal", "pynwb.file.Subject", "numpy.arange", "hdmf.common.DynamicTable", "dateutil.tz.tzutc", "pynwb.NWBHDF5IO", "hdmf.backends.hdf5.HDF5IO", "numpy.linspace", "pynwb.testing.remove_test_file", "pandas.DataFrame", "pandas.testing.assert_frame_equal", "pynwb.epoch.TimeIntervals"...
[((885, 898), 'pynwb.get_manager', 'get_manager', ([], {}), '()\n', (896, 898), False, 'from pynwb import NWBFile, TimeSeries, NWBHDF5IO, get_manager\n'), ((966, 1634), 'pynwb.NWBFile', 'NWBFile', ([], {'session_description': '"""a test NWB File"""', 'identifier': '"""TEST123"""', 'session_start_time': 'self.start_time', 'timestamps_reference_time': 'self.ref_time', 'file_create_date': 'self.create_date', 'experimenter': '"""test experimenter"""', 'stimulus_notes': '"""test stimulus notes"""', 'data_collection': '"""test data collection notes"""', 'experiment_description': '"""test experiment description"""', 'institution': '"""nomad"""', 'lab': '"""nolab"""', 'notes': '"""nonotes"""', 'pharmacology': '"""nopharmacology"""', 'protocol': '"""noprotocol"""', 'related_publications': '"""nopubs"""', 'session_id': '"""007"""', 'slices': '"""noslices"""', 'source_script': '"""nosources"""', 'surgery': '"""nosurgery"""', 'virus': '"""novirus"""', 'source_script_file_name': '"""nofilename"""'}), "(session_description='a test NWB File', identifier='TEST123',\n session_start_time=self.start_time, timestamps_reference_time=self.\n ref_time, file_create_date=self.create_date, experimenter=\n 'test experimenter', stimulus_notes='test stimulus notes',\n data_collection='test data collection notes', experiment_description=\n 'test experiment description', institution='nomad', lab='nolab', notes=\n 'nonotes', pharmacology='nopharmacology', protocol='noprotocol',\n related_publications='nopubs', session_id='007', slices='noslices',\n source_script='nosources', surgery='nosurgery', virus='novirus',\n source_script_file_name='nofilename')\n", (973, 1634), False, 'from pynwb import NWBFile, TimeSeries, NWBHDF5IO, get_manager\n'), ((3025, 3056), 'pynwb.testing.remove_test_file', 'remove_test_file', (['self.filename'], {}), '(self.filename)\n', (3041, 3056), False, 'from pynwb.testing import NWBH5IOMixin, TestCase, remove_test_file\n'), ((3504, 3557), 'hdmf.backends.hdf5.HDF5IO', 'HDF5IO', (['self.filename'], {'manager': 'self.manager', 'mode': '"""a"""'}), "(self.filename, manager=self.manager, mode='a')\n", (3510, 3557), False, 'from hdmf.backends.hdf5 import HDF5IO\n'), ((3745, 3798), 'hdmf.backends.hdf5.HDF5IO', 'HDF5IO', (['self.filename'], {'manager': 'self.manager', 'mode': '"""w"""'}), "(self.filename, manager=self.manager, mode='w')\n", (3751, 3798), False, 'from hdmf.backends.hdf5 import HDF5IO\n'), ((3875, 3928), 'hdmf.backends.hdf5.HDF5IO', 'HDF5IO', (['self.filename'], {'manager': 'self.manager', 'mode': '"""r"""'}), "(self.filename, manager=self.manager, mode='r')\n", (3881, 3928), False, 'from hdmf.backends.hdf5 import HDF5IO\n'), ((5187, 5942), 'pynwb.NWBFile', 'NWBFile', ([], {'session_description': '"""a test session description for a test NWBFile"""', 'identifier': '"""FILE123"""', 'session_start_time': 'self.start_time', 'file_create_date': 'self.create_dates', 'timestamps_reference_time': 'self.ref_time', 'experimenter': '"""A test experimenter"""', 'lab': '"""a test lab"""', 'institution': '"""a test institution"""', 'experiment_description': '"""a test experiment description"""', 'session_id': '"""test1"""', 'notes': '"""my notes"""', 'pharmacology': '"""drugs"""', 'protocol': '"""protocol"""', 'related_publications': '"""my pubs"""', 'slices': '"""my slices"""', 'surgery': '"""surgery"""', 'virus': '"""a virus"""', 'source_script': '"""noscript"""', 'source_script_file_name': '"""nofilename"""', 'stimulus_notes': '"""test stimulus notes"""', 'data_collection': '"""test data collection notes"""', 'keywords': "('these', 'are', 'keywords')"}), "(session_description='a test session description for a test NWBFile',\n identifier='FILE123', session_start_time=self.start_time,\n file_create_date=self.create_dates, timestamps_reference_time=self.\n ref_time, experimenter='A test experimenter', lab='a test lab',\n institution='a test institution', experiment_description=\n 'a test experiment description', session_id='test1', notes='my notes',\n pharmacology='drugs', protocol='protocol', related_publications=\n 'my pubs', slices='my slices', surgery='surgery', virus='a virus',\n source_script='noscript', source_script_file_name='nofilename',\n stimulus_notes='test stimulus notes', data_collection=\n 'test data collection notes', keywords=('these', 'are', 'keywords'))\n", (5194, 5942), False, 'from pynwb import NWBFile, TimeSeries, NWBHDF5IO, get_manager\n'), ((6786, 6820), 'pynwb.NWBHDF5IO', 'NWBHDF5IO', (['self.filename'], {'mode': '"""w"""'}), "(self.filename, mode='w')\n", (6795, 6820), False, 'from pynwb import NWBFile, TimeSeries, NWBHDF5IO, get_manager\n'), ((6937, 6971), 'pynwb.NWBHDF5IO', 'NWBHDF5IO', (['self.filename'], {'mode': '"""r"""'}), "(self.filename, mode='r')\n", (6946, 6971), False, 'from pynwb import NWBFile, TimeSeries, NWBHDF5IO, get_manager\n'), ((7625, 7781), 'pynwb.NWBFile', 'NWBFile', ([], {'session_description': 'description', 'identifier': 'identifier', 'session_start_time': 'self.start_time', 'experimenter': "('experimenter1', 'experimenter2')"}), "(session_description=description, identifier=identifier,\n session_start_time=self.start_time, experimenter=('experimenter1',\n 'experimenter2'))\n", (7632, 7781), False, 'from pynwb import NWBFile, TimeSeries, NWBHDF5IO, get_manager\n'), ((8168, 8271), 'pynwb.NWBFile', 'NWBFile', ([], {'session_description': 'description', 'identifier': 'identifier', 'session_start_time': 'self.start_time'}), '(session_description=description, identifier=identifier,\n session_start_time=self.start_time)\n', (8175, 8271), False, 'from pynwb import NWBFile, TimeSeries, NWBHDF5IO, get_manager\n'), ((8710, 8852), 'pynwb.NWBFile', 'NWBFile', ([], {'session_description': 'description', 'identifier': 'identifier', 'session_start_time': 'self.start_time', 'related_publications': "('pub1', 'pub2')"}), "(session_description=description, identifier=identifier,\n session_start_time=self.start_time, related_publications=('pub1', 'pub2'))\n", (8717, 8852), False, 'from pynwb import NWBFile, TimeSeries, NWBHDF5IO, get_manager\n'), ((9241, 9344), 'pynwb.NWBFile', 'NWBFile', ([], {'session_description': 'description', 'identifier': 'identifier', 'session_start_time': 'self.start_time'}), '(session_description=description, identifier=identifier,\n session_start_time=self.start_time)\n', (9248, 9344), False, 'from pynwb import NWBFile, TimeSeries, NWBHDF5IO, get_manager\n'), ((10358, 10367), 'pynwb.file.Subject', 'Subject', ([], {}), '()\n', (10365, 10367), False, 'from pynwb.file import Subject\n'), ((10574, 10597), 'pynwb.epoch.TimeIntervals', 'TimeIntervals', (['"""epochs"""'], {}), "('epochs')\n", (10587, 10597), False, 'from pynwb.epoch import TimeIntervals\n'), ((13693, 13779), 'pandas.testing.assert_frame_equal', 'pd.testing.assert_frame_equal', (['df_exp', 'df_obt'], {'check_like': '(True)', 'check_dtype': '(False)'}), '(df_exp, df_obt, check_like=True, check_dtype=\n False)\n', (13722, 13779), True, 'import pandas as pd\n'), ((14801, 14887), 'pandas.testing.assert_frame_equal', 'pd.testing.assert_frame_equal', (['df_exp', 'df_obt'], {'check_like': '(True)', 'check_dtype': '(False)'}), '(df_exp, df_obt, check_like=True, check_dtype=\n False)\n', (14830, 14887), True, 'import pandas as pd\n'), ((15090, 15152), 'hdmf.common.DynamicTable', 'DynamicTable', ([], {'name': '"""trials"""', 'description': '"""a placeholder table"""'}), "(name='trials', description='a placeholder table')\n", (15102, 15152), False, 'from hdmf.common import DynamicTable\n'), ((16169, 16238), 'hdmf.common.DynamicTable', 'DynamicTable', ([], {'name': '"""invalid times"""', 'description': '"""a placeholder table"""'}), "(name='invalid times', description='a placeholder table')\n", (16181, 16238), False, 'from hdmf.common import DynamicTable\n'), ((17298, 17359), 'hdmf.common.DynamicTable', 'DynamicTable', ([], {'name': '"""units"""', 'description': '"""a placeholder table"""'}), "(name='units', description='a placeholder table')\n", (17310, 17359), False, 'from hdmf.common import DynamicTable\n'), ((18878, 18927), 'hdmf.common.DynamicTable', 'DynamicTable', (['"""electrodes"""', '"""a placeholder table"""'], {}), "('electrodes', 'a placeholder table')\n", (18890, 18927), False, 'from hdmf.common import DynamicTable\n'), ((20671, 20720), 'hdmf.common.DynamicTable', 'DynamicTable', (['"""electrodes"""', '"""a placeholder table"""'], {}), "('electrodes', 'a placeholder table')\n", (20683, 20720), False, 'from hdmf.common import DynamicTable\n'), ((22610, 22659), 'hdmf.common.DynamicTable', 'DynamicTable', (['"""electrodes"""', '"""a placeholder table"""'], {}), "('electrodes', 'a placeholder table')\n", (22622, 22659), False, 'from hdmf.common import DynamicTable\n'), ((11743, 12030), 'pandas.DataFrame', 'pd.DataFrame', (["{'foo': [1, 2, 3, 4], 'bar': ['fish', 'fowl', 'dog', 'cat'], 'start_time':\n [0.2, 0.25, 0.3, 0.35], 'stop_time': [0.25, 0.3, 0.4, 0.45],\n 'timeseries': [[(2, 1, tsa)], [(3, 1, tsa)], [(3, 1, tsa)], [(4, 1, tsa\n )]], 'tags': [[''], [''], ['fizz', 'buzz'], ['qaz']]}"], {}), "({'foo': [1, 2, 3, 4], 'bar': ['fish', 'fowl', 'dog', 'cat'],\n 'start_time': [0.2, 0.25, 0.3, 0.35], 'stop_time': [0.25, 0.3, 0.4, \n 0.45], 'timeseries': [[(2, 1, tsa)], [(3, 1, tsa)], [(3, 1, tsa)], [(4,\n 1, tsa)]], 'tags': [[''], [''], ['fizz', 'buzz'], ['qaz']]})\n", (11755, 12030), True, 'import pandas as pd\n'), ((18039, 18115), 'pandas.DataFrame', 'pd.DataFrame', (["{'a': [[1, 2, 3], [1, 2, 3], [1, 2, 3]], 'b': ['4', '5', '6']}"], {}), "({'a': [[1, 2, 3], [1, 2, 3], [1, 2, 3]], 'b': ['4', '5', '6']})\n", (18051, 18115), True, 'import pandas as pd\n'), ((24518, 24573), 'pandas.testing.assert_frame_equal', 'pd.testing.assert_frame_equal', (['self.table[ii + 1]', 'item'], {}), '(self.table[ii + 1], item)\n', (24547, 24573), True, 'import pandas as pd\n'), ((718, 725), 'dateutil.tz.tzutc', 'tzutc', ([], {}), '()\n', (723, 725), False, 'from dateutil.tz import tzlocal, tzutc\n'), ((782, 789), 'dateutil.tz.tzutc', 'tzutc', ([], {}), '()\n', (787, 789), False, 'from dateutil.tz import tzlocal, tzutc\n'), ((851, 860), 'dateutil.tz.tzlocal', 'tzlocal', ([], {}), '()\n', (858, 860), False, 'from dateutil.tz import tzlocal, tzutc\n'), ((2355, 2370), 'numpy.arange', 'np.arange', (['(10.0)'], {}), '(10.0)\n', (2364, 2370), True, 'import numpy as np\n'), ((2576, 2591), 'numpy.arange', 'np.arange', (['(10.0)'], {}), '(10.0)\n', (2585, 2591), True, 'import numpy as np\n'), ((2884, 2899), 'numpy.arange', 'np.arange', (['(10.0)'], {}), '(10.0)\n', (2893, 2899), True, 'import numpy as np\n'), ((4629, 4636), 'dateutil.tz.tzutc', 'tzutc', ([], {}), '()\n', (4634, 4636), False, 'from dateutil.tz import tzlocal, tzutc\n'), ((4693, 4700), 'dateutil.tz.tzutc', 'tzutc', ([], {}), '()\n', (4698, 4700), False, 'from dateutil.tz import tzlocal, tzutc\n'), ((4763, 4772), 'dateutil.tz.tzlocal', 'tzlocal', ([], {}), '()\n', (4770, 4772), False, 'from dateutil.tz import tzlocal, tzutc\n'), ((4845, 4852), 'dateutil.tz.tzutc', 'tzutc', ([], {}), '()\n', (4850, 4852), False, 'from dateutil.tz import tzlocal, tzutc\n'), ((4916, 4923), 'dateutil.tz.tzutc', 'tzutc', ([], {}), '()\n', (4921, 4923), False, 'from dateutil.tz import tzlocal, tzutc\n'), ((5087, 5094), 'dateutil.tz.tzutc', 'tzutc', ([], {}), '()\n', (5092, 5094), False, 'from dateutil.tz import tzlocal, tzutc\n'), ((11422, 11435), 'numpy.arange', 'np.arange', (['(11)'], {}), '(11)\n', (11431, 11435), True, 'import numpy as np\n'), ((11462, 11483), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(11)'], {}), '(0, 1, 11)\n', (11473, 11483), True, 'import numpy as np\n'), ((11524, 11537), 'numpy.arange', 'np.arange', (['(13)'], {}), '(13)\n', (11533, 11537), True, 'import numpy as np\n'), ((11564, 11587), 'numpy.linspace', 'np.linspace', (['(0.1)', '(5)', '(13)'], {}), '(0.1, 5, 13)\n', (11575, 11587), True, 'import numpy as np\n'), ((13445, 13457), 'numpy.arange', 'np.arange', (['(4)'], {}), '(4)\n', (13454, 13457), True, 'import numpy as np\n'), ((14658, 14670), 'numpy.arange', 'np.arange', (['(4)'], {}), '(4)\n', (14667, 14670), True, 'import numpy as np\n'), ((23992, 24005), 'numpy.arange', 'np.arange', (['(10)'], {}), '(10)\n', (24001, 24005), True, 'import numpy as np\n'), ((24030, 24045), 'numpy.arange', 'np.arange', (['(10.0)'], {}), '(10.0)\n', (24039, 24045), True, 'import numpy as np\n'), ((9947, 9954), 'dateutil.tz.tzutc', 'tzutc', ([], {}), '()\n', (9952, 9954), False, 'from dateutil.tz import tzlocal, tzutc\n')]
import matplotlib, sys matplotlib.use('TkAgg') from numpy import arange, sin, pi #from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import matplotlib.pyplot as plt from tkinter import * import tkinter as tk import skimage.io import pickle #from investigate_particles import * import pysilcam.postprocess as scpp from pysilcam.config import load_config, PySilcamSettings import pandas as pd import os import numpy as np from shutil import copyfile DATABASE_PATH = '/mnt/ARRAY/silcam_classification_database' config_file = '/mnt/ARRAY/ENTICE/Data/configs/config.ini' stats_csv_file = '/mnt/ARRAY/ENTICE/Data/proc/STN10-STATS.csv' filepath = '/mnt/ARRAY/ENTICE/Data/export/' def find_classes(d=DATABASE_PATH): classes = [o for o in os.listdir(d) if os.path.isdir(os.path.join(d,o))] print(classes) return classes def particle_generator(): conf = load_config(config_file) settings = PySilcamSettings(conf) stats = pd.read_csv(stats_csv_file) print('all stats:', len(stats)) index = 0 while True: # if np.random.choice([0,1]): stats_ = scpp.extract_nth_largest(stats,settings,n=index) # else: # stats_ = scpp.extract_nth_longest(stats,settings,n=index) print(stats_) filename = os.path.join(filepath, stats_['export name']) im = skimage.io.imread(filename) im = scpp.explode_contrast(im) im = scpp.bright_norm(im) # scplt.show_imc(im) # plt.title(selected_stats['export name'] + ('\nDepth: # {0:.1f}'.format(selected_stats['depth'])) + 'm\n') index += 1 filename = stats_['export name'] yield im, filepath, filename class guiclass: def __init__(self, master): classes = find_classes() self.master = master master.title("Class builder") self.toolbar = tk.Frame(self.master) self.quit = tk.Button(self.toolbar, text="Close",command=master.quit) self.quit.pack(side="left") # left side of parent, the toolbar frame self.next = tk.Button(self.toolbar, text="Next",command=self.update_image) self.next.pack(side="right") # left side of parent, the toolbar frame self.choice = StringVar(self.master) self.choice.set(classes[0]) self.w = OptionMenu(self.toolbar, self.choice, *classes) self.w.pack(side='right') #self.build_buttons(classes) # self.other = tk.Button(self.toolbar, # text="Other",command=self.other) # self.other.pack(side="left") # left side of parent, the toolbar frame # # self.copepod = tk.Button(self.toolbar, # text="Copepod",command=self.copepod) # self.copepod.pack(side="left") # left side of parent, the toolbar frame # # self.diatom_chain = tk.Button(self.toolbar, # text="Diatom chain",command=self.diatom_chain) # self.diatom_chain.pack(side="left") # left side of parent, the toolbar frame f,self.a = plt.subplots(1,1,figsize=(5,5), dpi=100) self.dataPlot = FigureCanvasTkAgg(f, master=self.master) self.pgen = particle_generator() self.im, self.imfilepath, self.imfilename = next(self.pgen) plt.sca(self.a) plt.imshow(self.im) plt.axis('off') self.X_blank = np.zeros([1, 32, 32, 3],dtype='uint8') self.X = np.zeros([0, 32, 32, 3],dtype='uint8') self.Y = np.zeros((0,3),dtype='uint8') self.toolbar.pack(side=TOP, fill="x") # top of parent, the master window self.dataPlot.show() self.dataPlot.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1) def update_image(self): self.dump_data() plt.sca(self.a) plt.cla() self.im, self.imfilepath, self.imfilename = next(self.pgen) plt.imshow(self.im) plt.axis('off') self.dataPlot.show() def dump_data(self): choice = self.choice.get() print('from:') print(os.path.join(self.imfilepath, self.imfilename)) print('to:') print(os.path.join(DATABASE_PATH, choice, self.imfilename)) copyfile(os.path.join(self.imfilepath, self.imfilename), os.path.join(DATABASE_PATH, choice, self.imfilename)) return root = Tk() my_gui = guiclass(root) root.mainloop()
[ "matplotlib.pyplot.imshow", "pysilcam.config.load_config", "os.listdir", "pandas.read_csv", "matplotlib.use", "pysilcam.postprocess.extract_nth_largest", "os.path.join", "matplotlib.pyplot.sca", "pysilcam.postprocess.bright_norm", "tkinter.Button", "matplotlib.pyplot.axis", "numpy.zeros", "p...
[((23, 46), 'matplotlib.use', 'matplotlib.use', (['"""TkAgg"""'], {}), "('TkAgg')\n", (37, 46), False, 'import matplotlib, sys\n'), ((966, 990), 'pysilcam.config.load_config', 'load_config', (['config_file'], {}), '(config_file)\n', (977, 990), False, 'from pysilcam.config import load_config, PySilcamSettings\n'), ((1006, 1028), 'pysilcam.config.PySilcamSettings', 'PySilcamSettings', (['conf'], {}), '(conf)\n', (1022, 1028), False, 'from pysilcam.config import load_config, PySilcamSettings\n'), ((1042, 1069), 'pandas.read_csv', 'pd.read_csv', (['stats_csv_file'], {}), '(stats_csv_file)\n', (1053, 1069), True, 'import pandas as pd\n'), ((1194, 1244), 'pysilcam.postprocess.extract_nth_largest', 'scpp.extract_nth_largest', (['stats', 'settings'], {'n': 'index'}), '(stats, settings, n=index)\n', (1218, 1244), True, 'import pysilcam.postprocess as scpp\n'), ((1369, 1414), 'os.path.join', 'os.path.join', (['filepath', "stats_['export name']"], {}), "(filepath, stats_['export name'])\n", (1381, 1414), False, 'import os\n'), ((1471, 1496), 'pysilcam.postprocess.explode_contrast', 'scpp.explode_contrast', (['im'], {}), '(im)\n', (1492, 1496), True, 'import pysilcam.postprocess as scpp\n'), ((1510, 1530), 'pysilcam.postprocess.bright_norm', 'scpp.bright_norm', (['im'], {}), '(im)\n', (1526, 1530), True, 'import pysilcam.postprocess as scpp\n'), ((1968, 1989), 'tkinter.Frame', 'tk.Frame', (['self.master'], {}), '(self.master)\n', (1976, 1989), True, 'import tkinter as tk\n'), ((2010, 2068), 'tkinter.Button', 'tk.Button', (['self.toolbar'], {'text': '"""Close"""', 'command': 'master.quit'}), "(self.toolbar, text='Close', command=master.quit)\n", (2019, 2068), True, 'import tkinter as tk\n'), ((2182, 2245), 'tkinter.Button', 'tk.Button', (['self.toolbar'], {'text': '"""Next"""', 'command': 'self.update_image'}), "(self.toolbar, text='Next', command=self.update_image)\n", (2191, 2245), True, 'import tkinter as tk\n'), ((3143, 3186), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(5, 5)', 'dpi': '(100)'}), '(1, 1, figsize=(5, 5), dpi=100)\n', (3155, 3186), True, 'import matplotlib.pyplot as plt\n'), ((3208, 3248), 'matplotlib.backends.backend_tkagg.FigureCanvasTkAgg', 'FigureCanvasTkAgg', (['f'], {'master': 'self.master'}), '(f, master=self.master)\n', (3225, 3248), False, 'from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\n'), ((3367, 3382), 'matplotlib.pyplot.sca', 'plt.sca', (['self.a'], {}), '(self.a)\n', (3374, 3382), True, 'import matplotlib.pyplot as plt\n'), ((3391, 3410), 'matplotlib.pyplot.imshow', 'plt.imshow', (['self.im'], {}), '(self.im)\n', (3401, 3410), True, 'import matplotlib.pyplot as plt\n'), ((3419, 3434), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (3427, 3434), True, 'import matplotlib.pyplot as plt\n'), ((3459, 3498), 'numpy.zeros', 'np.zeros', (['[1, 32, 32, 3]'], {'dtype': '"""uint8"""'}), "([1, 32, 32, 3], dtype='uint8')\n", (3467, 3498), True, 'import numpy as np\n'), ((3515, 3554), 'numpy.zeros', 'np.zeros', (['[0, 32, 32, 3]'], {'dtype': '"""uint8"""'}), "([0, 32, 32, 3], dtype='uint8')\n", (3523, 3554), True, 'import numpy as np\n'), ((3571, 3602), 'numpy.zeros', 'np.zeros', (['(0, 3)'], {'dtype': '"""uint8"""'}), "((0, 3), dtype='uint8')\n", (3579, 3602), True, 'import numpy as np\n'), ((3848, 3863), 'matplotlib.pyplot.sca', 'plt.sca', (['self.a'], {}), '(self.a)\n', (3855, 3863), True, 'import matplotlib.pyplot as plt\n'), ((3872, 3881), 'matplotlib.pyplot.cla', 'plt.cla', ([], {}), '()\n', (3879, 3881), True, 'import matplotlib.pyplot as plt\n'), ((3958, 3977), 'matplotlib.pyplot.imshow', 'plt.imshow', (['self.im'], {}), '(self.im)\n', (3968, 3977), True, 'import matplotlib.pyplot as plt\n'), ((3986, 4001), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (3994, 4001), True, 'import matplotlib.pyplot as plt\n'), ((839, 852), 'os.listdir', 'os.listdir', (['d'], {}), '(d)\n', (849, 852), False, 'import os\n'), ((4130, 4176), 'os.path.join', 'os.path.join', (['self.imfilepath', 'self.imfilename'], {}), '(self.imfilepath, self.imfilename)\n', (4142, 4176), False, 'import os\n'), ((4213, 4265), 'os.path.join', 'os.path.join', (['DATABASE_PATH', 'choice', 'self.imfilename'], {}), '(DATABASE_PATH, choice, self.imfilename)\n', (4225, 4265), False, 'import os\n'), ((4284, 4330), 'os.path.join', 'os.path.join', (['self.imfilepath', 'self.imfilename'], {}), '(self.imfilepath, self.imfilename)\n', (4296, 4330), False, 'import os\n'), ((4348, 4400), 'os.path.join', 'os.path.join', (['DATABASE_PATH', 'choice', 'self.imfilename'], {}), '(DATABASE_PATH, choice, self.imfilename)\n', (4360, 4400), False, 'import os\n'), ((870, 888), 'os.path.join', 'os.path.join', (['d', 'o'], {}), '(d, o)\n', (882, 888), False, 'import os\n')]
import torch import numpy as np import copy from torch.distributions.normal import Normal from torch.distributions.cauchy import Cauchy from .rk_parametric_order4stage4 import RKOrder4Stage4 from .rk_parametric_order3stage3 import RKOrder3Stage3 from .rk_parametric_order2stage2 import RKOrder2Stage2 from .euler import Euler def create_solver(method, parameterization, n_steps, step_size, u0, v0, dtype, device): ''' method: str parameterization: str n_steps: int step_size: Decimal u0: Decimal v0: Decimal dtype: torch dtype ''' if n_steps == -1: n_steps = None if step_size == -1: step_size = None if dtype == torch.float64: u0, v0 = map(lambda el : np.float64(el), [u0, v0]) elif dtype == torch.float32: u0, v0 = map(lambda el : np.float32(el), [u0, v0]) if method == 'euler': return Euler(n_steps = n_steps, step_size = step_size, parameterization=parameterization, u0 = u0, v0 = v0, dtype =dtype, device = device) elif method == 'rk2': return RKOrder2Stage2(n_steps = n_steps, step_size = step_size, parameterization=parameterization, u0 = u0, v0 = v0, dtype =dtype, device = device) elif method == 'rk3': return RKOrder3Stage3(n_steps = n_steps, step_size = step_size, parameterization=parameterization, u0 = u0, v0 = v0, dtype =dtype, device = device) elif method == 'rk4': return RKOrder4Stage4(n_steps = n_steps, step_size = step_size, parameterization=parameterization, u0 = u0, v0 = v0, dtype =dtype, device = device) def sample_noise(mu, sigma, noise_type='cauchy', size=1, device='cpu', minimize_rk2_error=False): if not minimize_rk2_error: if noise_type == 'cauchy': d = Cauchy(torch.tensor([mu]), torch.tensor([sigma])) elif noise_type == 'normal': d = Normal(torch.tensor([mu]), torch.tensor([sigma])) else: if noise_type == 'cauchy': d = Cauchy(torch.tensor([2/3.]), torch.tensor([2/3. * sigma])) elif noise_type == 'normal': d = Normal(torch.tensor([2/3.]), torch.tensor([2/3. * sigma])) return torch.tensor([d.sample() for _ in range(size)], device=device) def noise_params(mean_u, mean_v=None, std=0.01, bernoulli_p=1.0, noise_type='cauchy', minimize_rk2_error=False): ''' Noise solver paramers with Cauchy/Normal noise with probability p ''' d = torch.distributions.Bernoulli(torch.tensor([bernoulli_p], dtype=torch.float32)) v = None device = mean_u.device eps = torch.finfo(mean_u.dtype).eps if d.sample(): std = torch.abs(torch.tensor(std, device=device)) u = sample_noise(mean_u, std, noise_type=noise_type, size=1, device=device, minimize_rk2_error=minimize_rk2_error) if u <= mean_u - 2*std or u >= mean_u + 2*std: u = mean_u # u = min(max(u, mean_u - 2*std,0), mean_u + 2*std, 1.) if mean_v is not None: v = sample_noise(mean_v, std, noise_type=noise_type, size=1, device=device, minimize_rk2_error=minimize_rk2_error) else: u = mean_u if mean_v is not None: v = mean_v return u, v def sample_solver_by_noising_params(solver, std=0.01, bernoulli_p=1., noise_type='cauchy', minimize_rk2_error=False): new_solver = copy.deepcopy(solver) new_solver.u, new_solver.v = noise_params(mean_u=new_solver.u0, mean_v=new_solver.v0, std=std, bernoulli_p=bernoulli_p, noise_type=noise_type, minimize_rk2_error=minimize_rk2_error) new_solver.build_ButcherTableau() print(new_solver.u, new_solver.v) return new_solver def create_solver_ensemble_by_noising_params(solver, ensemble_size=1, kwargs_noise={}): solver_ensemble = [solver] for _ in range(1, ensemble_size): new_solver = sample_solver_by_noising_params(solver, **kwargs_noise) solver_ensemble.append(new_solver) return solver_ensemble
[ "numpy.float64", "torch.tensor", "torch.finfo", "copy.deepcopy", "numpy.float32" ]
[((3902, 3923), 'copy.deepcopy', 'copy.deepcopy', (['solver'], {}), '(solver)\n', (3915, 3923), False, 'import copy\n'), ((3021, 3069), 'torch.tensor', 'torch.tensor', (['[bernoulli_p]'], {'dtype': 'torch.float32'}), '([bernoulli_p], dtype=torch.float32)\n', (3033, 3069), False, 'import torch\n'), ((3121, 3146), 'torch.finfo', 'torch.finfo', (['mean_u.dtype'], {}), '(mean_u.dtype)\n', (3132, 3146), False, 'import torch\n'), ((3195, 3227), 'torch.tensor', 'torch.tensor', (['std'], {'device': 'device'}), '(std, device=device)\n', (3207, 3227), False, 'import torch\n'), ((774, 788), 'numpy.float64', 'np.float64', (['el'], {}), '(el)\n', (784, 788), True, 'import numpy as np\n'), ((2280, 2298), 'torch.tensor', 'torch.tensor', (['[mu]'], {}), '([mu])\n', (2292, 2298), False, 'import torch\n'), ((2300, 2321), 'torch.tensor', 'torch.tensor', (['[sigma]'], {}), '([sigma])\n', (2312, 2321), False, 'import torch\n'), ((2514, 2537), 'torch.tensor', 'torch.tensor', (['[2 / 3.0]'], {}), '([2 / 3.0])\n', (2526, 2537), False, 'import torch\n'), ((2536, 2567), 'torch.tensor', 'torch.tensor', (['[2 / 3.0 * sigma]'], {}), '([2 / 3.0 * sigma])\n', (2548, 2567), False, 'import torch\n'), ((866, 880), 'numpy.float32', 'np.float32', (['el'], {}), '(el)\n', (876, 880), True, 'import numpy as np\n'), ((2391, 2409), 'torch.tensor', 'torch.tensor', (['[mu]'], {}), '([mu])\n', (2403, 2409), False, 'import torch\n'), ((2411, 2432), 'torch.tensor', 'torch.tensor', (['[sigma]'], {}), '([sigma])\n', (2423, 2432), False, 'import torch\n'), ((2634, 2657), 'torch.tensor', 'torch.tensor', (['[2 / 3.0]'], {}), '([2 / 3.0])\n', (2646, 2657), False, 'import torch\n'), ((2656, 2687), 'torch.tensor', 'torch.tensor', (['[2 / 3.0 * sigma]'], {}), '([2 / 3.0 * sigma])\n', (2668, 2687), False, 'import torch\n')]
# Importing the Keras libraries and packages from keras.models import Sequential from keras.layers import Conv2D from keras.layers import MaxPooling2D from keras.layers import Flatten from keras.layers import Dense # Initialising the CNN classifier = Sequential() # Step 1 - Convolution classifier.add(Conv2D(32, (3, 3), input_shape = (64, 64, 3), activation = 'relu')) # Step 2 - Pooling classifier.add(MaxPooling2D(pool_size = (2, 2))) # Adding a second convolutional layer classifier.add(Conv2D(32, (3, 3), activation = 'relu')) classifier.add(MaxPooling2D(pool_size = (2, 2))) # Step 3 - Flattening classifier.add(Flatten()) # Step 4 - Full connection classifier.add(Dense(units = 128, activation = 'relu')) classifier.add(Dense(units = 1, activation = 'sigmoid')) # Compiling the CNN classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy']) # Part 2 - Fitting the CNN to the images from keras.preprocessing.image import ImageDataGenerator train_datagen = ImageDataGenerator(rescale = 1./255, shear_range = 0.2, zoom_range = 0.2, horizontal_flip = True) test_datagen = ImageDataGenerator(rescale = 1./255) training_set = train_datagen.flow_from_directory('dataset/training_set', target_size = (64, 64), batch_size = 32, class_mode = 'binary') test_set = test_datagen.flow_from_directory('dataset/test_set', target_size = (64, 64), batch_size = 32, class_mode = 'binary') classifier.fit_generator(training_set, steps_per_epoch = 8000, epochs = 25, validation_data = test_set, validation_steps = 2000) # Part 3 - Making new predictions import numpy as np from keras.preprocessing import image test_image = image.load_img('dataset/single_prediction/cat_or_dog_1.jpg', target_size = (64, 64)) test_image = image.img_to_array(test_image) test_image = np.expand_dims(test_image, axis = 0) result = classifier.predict(test_image) training_set.class_indices if result[0][0] == 1: prediction = 'dog' else: prediction = 'cat'
[ "keras.preprocessing.image.img_to_array", "keras.layers.Conv2D", "keras.layers.Flatten", "keras.layers.MaxPooling2D", "keras.preprocessing.image.ImageDataGenerator", "keras.models.Sequential", "numpy.expand_dims", "keras.layers.Dense", "keras.preprocessing.image.load_img" ]
[((258, 270), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (268, 270), False, 'from keras.models import Sequential\n'), ((1020, 1116), 'keras.preprocessing.image.ImageDataGenerator', 'ImageDataGenerator', ([], {'rescale': '(1.0 / 255)', 'shear_range': '(0.2)', 'zoom_range': '(0.2)', 'horizontal_flip': '(True)'}), '(rescale=1.0 / 255, shear_range=0.2, zoom_range=0.2,\n horizontal_flip=True)\n', (1038, 1116), False, 'from keras.preprocessing.image import ImageDataGenerator\n'), ((1137, 1174), 'keras.preprocessing.image.ImageDataGenerator', 'ImageDataGenerator', ([], {'rescale': '(1.0 / 255)'}), '(rescale=1.0 / 255)\n', (1155, 1174), False, 'from keras.preprocessing.image import ImageDataGenerator\n'), ((1689, 1776), 'keras.preprocessing.image.load_img', 'image.load_img', (['"""dataset/single_prediction/cat_or_dog_1.jpg"""'], {'target_size': '(64, 64)'}), "('dataset/single_prediction/cat_or_dog_1.jpg', target_size=(\n 64, 64))\n", (1703, 1776), False, 'from keras.preprocessing import image\n'), ((1788, 1818), 'keras.preprocessing.image.img_to_array', 'image.img_to_array', (['test_image'], {}), '(test_image)\n', (1806, 1818), False, 'from keras.preprocessing import image\n'), ((1833, 1867), 'numpy.expand_dims', 'np.expand_dims', (['test_image'], {'axis': '(0)'}), '(test_image, axis=0)\n', (1847, 1867), True, 'import numpy as np\n'), ((311, 373), 'keras.layers.Conv2D', 'Conv2D', (['(32)', '(3, 3)'], {'input_shape': '(64, 64, 3)', 'activation': '"""relu"""'}), "(32, (3, 3), input_shape=(64, 64, 3), activation='relu')\n", (317, 373), False, 'from keras.layers import Conv2D\n'), ((415, 445), 'keras.layers.MaxPooling2D', 'MaxPooling2D', ([], {'pool_size': '(2, 2)'}), '(pool_size=(2, 2))\n', (427, 445), False, 'from keras.layers import MaxPooling2D\n'), ((504, 541), 'keras.layers.Conv2D', 'Conv2D', (['(32)', '(3, 3)'], {'activation': '"""relu"""'}), "(32, (3, 3), activation='relu')\n", (510, 541), False, 'from keras.layers import Conv2D\n'), ((561, 591), 'keras.layers.MaxPooling2D', 'MaxPooling2D', ([], {'pool_size': '(2, 2)'}), '(pool_size=(2, 2))\n', (573, 591), False, 'from keras.layers import MaxPooling2D\n'), ((634, 643), 'keras.layers.Flatten', 'Flatten', ([], {}), '()\n', (641, 643), False, 'from keras.layers import Flatten\n'), ((689, 724), 'keras.layers.Dense', 'Dense', ([], {'units': '(128)', 'activation': '"""relu"""'}), "(units=128, activation='relu')\n", (694, 724), False, 'from keras.layers import Dense\n'), ((746, 782), 'keras.layers.Dense', 'Dense', ([], {'units': '(1)', 'activation': '"""sigmoid"""'}), "(units=1, activation='sigmoid')\n", (751, 782), False, 'from keras.layers import Dense\n')]
#!/usr/bin/env python3 import argparse from pathlib import Path import numpy as np import statsmodels.api as sm from scipy import stats from matplotlib import pyplot as plt parser = argparse.ArgumentParser( description="Train generalized linear model to get coefficient for each variable." ) parser.add_argument( "cvat_path", type=Path, help="the path to the folder from cvat containing annotations and images." ) parser.add_argument( "out", help="the path to the file containing the json files generated to match the formats of preds and ground truth, as well as the output stats file" ) parser.add_argument( "texture_cache", type=Path, help= """ The path to an npy file containing the texture of the image if already calculated. (Providing this option can speed up repeated executions of this script on the same input.) If this file does not exist, it will be created when the texture is calculated. """ ) args = parser.parse_args() from pycocotools.coco import COCO import os, sys, zipfile import urllib.request import shutil import pandas as pd import skimage.io as io import matplotlib.pyplot as plt import pylab import json import cv2 as cv # CONSTANTS PARAMS = { 'texture': { 'window_radius': 2, 'num_features': 6, 'inverse_resolution': 50 # arya's value: 30 }, 'blur': { 'green_kernel_size': 5, 'green_strength': 60, 'contrast_kernel_size': 24 # potentially deletable }, 'threshold': { 'block_size': 2001, 'C': 10, }, # Tom's addition: 'num_of_features': { 'high': 4, 'low': 2 }, # 'num_of_color_features': { # 'high': 3, # 'low': 2 # }, # 'num_of_texture_features': { # 'high': 2, # 'low': 1 # }, # TODO: will be useful in closing holes 'morho': { 'big_kernel_size': 24, 'small_kernel_size': 5, 'high': { 'closing': 7, 'opening': 4+15 }, 'low': { 'closing': 7, 'opening': 4+7, 'closing2': 14 }, 'noise_removal': { 'strength': 17, 'templateWindowSize': 7, 'searchWindowSize': 21 }, } } #json the address of the file needs to be set manually json_file=str(args.cvat_path)+'/annotations/instances_default.json' # person_keypoints_val2017.json # Object Keypoint annotation format for types # captions_val2017.json # Image Caption annotation format of data=json.load(open(json_file,'r')) num_of_images = len(data['images']) # i'm going to set the number of images that need to be extracted 82000 zhang for i in range(num_of_images): data_2 = {} data_2['info'] = data['info'] data_2['licenses'] = data['licenses'] data_2['images'] = [data['images'][i]] # extract only the first image data_2['categories'] = data['categories'] annotation = [] # find all its objects by imgid imgID = data_2['images'][0]['id'] for ann in data['annotations']: if ann['image_id'] == imgID: annotation.append(ann) data_2['annotations'] = annotation # save to the new json file , easy to view data features #img_file get image name img_file=data_2['images'][0]['file_name'] img_first=img_file.split(".")[0] # set store directory my store is in the current directory coco_single_object you need to manually create an empty folder under the folder json.dump(data_2, open(str(args.cvat_path)+'/annotations/'+img_first+'.json', 'w'), indent=4) # indent=4 more beautiful display import os def sliding_window(img, fnctn, size, num_features=1, skip=0): """ run fnctn over each sliding, square window of width 2*size+1, skipping every skip pixel store the result in a np arr of equal size as the img but with depth equal to num_features """ # make a shape x num_features array, since there are num_features features new = np.empty(img.shape+(num_features,)) # run a sliding window over the i and j indices for i in range(0, img.shape[0], skip): # we adjust for windows that would otherwise go over the edge of the frame i1 = max(0, i-size) i2 = min(i+size+1, img.shape[0]) next_i = min(i+skip, img.shape[0]) for j in range(0, img.shape[1], skip): j1 = max(0, j-size) j2 = min(j+size+1, img.shape[1]) next_j = min(j+skip, img.shape[1]) # call the function new[i:next_i,j:next_j,:] = fnctn(img[i1:i2,j1:j2]) return new def get_single_binaryImg(json_path,img_path,binary_img_save): endog_df = None exog_df = None dir=os.listdir(json_path) binary_img_l = [] features_l = [] for jfile in dir: if 'instances_default' not in jfile: annFile =os.path.join(json_path,jfile) coco = COCO(annFile) imgIds = coco.getImgIds() img = coco.loadImgs(imgIds[0])[0] # dataDir = img_path # shutil.copy(os.path.join(dataDir, img['file_name']), color_img_save) # load and display instance annotations # load the instance mask catIds = [] for ann in coco.dataset['annotations']: if ann['image_id'] == imgIds[0]: catIds.append(ann['category_id']) annIds = coco.getAnnIds(imgIds=img['id'], catIds=catIds, iscrowd=None) width = img['width'] height = img['height'] anns = coco.loadAnns(annIds) mask_pic = np.zeros((height, width)) for single in anns: mask_single = coco.annToMask(single) mask_pic += mask_single for row in range(height): for col in range(width): if (mask_pic[row][col] > 0): mask_pic[row][col] = 255 print(np.unique(mask_pic)) imgs = np.zeros(shape=(height, width, 3), dtype=np.float32) imgs = mask_pic binary_endog = imgs.flatten() print(binary_endog.shape, binary_endog) if endog_df is None: endog_df = pd.DataFrame(binary_endog, columns = ['binary_endog']) else: endog_df = endog_df.append(pd.DataFrame(binary_endog, columns = ['binary_endog'])) # binary_endog = list(binary_endog) # print(binary_endog) print(endog_df.head()) # imgs = imgs.astype(np.uint8) binary_img_l.append(imgs) # imgs = imgs.astype(np.int8) name_img = img['file_name'].split(".")[0] print(name_img) # calculate all the features img = cv.imread(str(args.cvat_path)+'/images/'+name_img+'.JPG') # print(img.shape) # name_img = str(args.image).split("/")[-1].split(".")[-2] gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) if args.texture_cache is not None: texture_cache = str(args.texture_cache) + '/' + name_img + '.npy' if Path(texture_cache).exists(): texture = np.load(texture_cache) else: print('calculating texture (this may take a while)') texture = sliding_window(gray, features.glcm, *tuple([PARAMS['texture'][i] for i in ['window_radius', 'num_features', 'inverse_resolution']])) str(args.texture_cache).mkdir(parents=True, exist_ok=True) np.save(texture_cache, texture) # plt.imsave(binary_img_save + "/binary_" + img_name + ".png", imgs) # blur image to remove noise from grass print('blurring image to remove noise in the green and contrast values') blur_colors = cv.GaussianBlur(img, (PARAMS['blur']['green_kernel_size'],)*2, PARAMS['blur']['green_strength']) # 1. get all feature values ## colors; note that opencv uses bgr color format blur_blue = blur_colors[:,:,0] blur_green = blur_colors[:,:,1] blur_red = blur_colors[:,:,2] ## textural features blur_gradient = cv.Laplacian(gray, cv.CV_8UC1) blur_contrast = np.uint8(texture[:,:,0]*255/texture[:,:,0].max()) blur_correlation = np.uint8(texture[:,:,4]*255) blur_energy = np.uint8(texture[:,:,3]*255/texture[:,:,3].max()) blur_homogeneity = np.uint8(texture[:,:,2]*255) # 2. adaptive guassian thresholding ### TODO: as of 3/1 night the only feature that doesn't work at all is correlation. th_blue = 255- cv.adaptiveThreshold(blur_blue,255,cv.ADAPTIVE_THRESH_GAUSSIAN_C,\ cv.THRESH_BINARY,PARAMS['threshold']['block_size'],PARAMS['threshold']['C']) th_green = 255- cv.adaptiveThreshold(blur_green,255,cv.ADAPTIVE_THRESH_GAUSSIAN_C,\ cv.THRESH_BINARY,PARAMS['threshold']['block_size'],PARAMS['threshold']['C']) th_red = 255- cv.adaptiveThreshold(blur_red,255,cv.ADAPTIVE_THRESH_GAUSSIAN_C,\ cv.THRESH_BINARY,PARAMS['threshold']['block_size'],PARAMS['threshold']['C']) th_gradient = 255- cv.adaptiveThreshold(blur_gradient,255,cv.ADAPTIVE_THRESH_GAUSSIAN_C,\ cv.THRESH_BINARY,PARAMS['threshold']['block_size'],PARAMS['threshold']['C']) th_contrast = 255 - cv.adaptiveThreshold(blur_contrast,255,cv.ADAPTIVE_THRESH_GAUSSIAN_C,\ cv.THRESH_BINARY,PARAMS['threshold']['block_size'],PARAMS['threshold']['C']) th_homogeneity = 255- cv.adaptiveThreshold(blur_homogeneity,255,cv.ADAPTIVE_THRESH_GAUSSIAN_C,\ cv.THRESH_BINARY,PARAMS['threshold']['block_size'],PARAMS['threshold']['C']) th_blue_1 = (th_blue/255).flatten() th_green_1 = (th_green/255).flatten() th_red_1 = (th_red/255).flatten() th_gradient_1 = (th_gradient/255).flatten() th_contrast_1 = (th_contrast/255).flatten() # th_correlation_1 = th_correlation/255 # th_energy_1 = th_energy/255 th_homogeneity_1 = (th_homogeneity/255).flatten() features_np = np.stack((th_blue_1, th_green_1, th_red_1, th_gradient_1, th_contrast_1, th_homogeneity_1)).T if exog_df is None: exog_df = pd.DataFrame(features_np, columns = ['th_blue', 'th_green', 'th_red', 'th_gradient', 'th_contrast', 'th_homogeneity']) else: exog_df = exog_df.append(pd.DataFrame(features_np, columns = ['th_blue', 'th_green', 'th_red', 'th_gradient', 'th_contrast', 'th_homogeneity'])) print(exog_df.head()) # # store all feature values # features_l.append([th_blue_1, th_green_1, th_red_1, th_gradient_1, th_contrast_1, th_homogeneity_1]) return endog_df, exog_df # return binary_img_l, features_l json_path = str(args.cvat_path)+'/annotations' img_path = str(args.cvat_path)+'/images' binary_img_save = str(args.cvat_path)+'/binary_images' Path(binary_img_save).mkdir(parents=True, exist_ok=True) endog_df, exog_df = get_single_binaryImg(json_path, img_path, binary_img_save) # train glm glm_binom = sm.GLM(endog_df, exog_df) # use the default gauassian family res = glm_binom.fit() print(res.summary()) print("PARAMS") print(res.params)
[ "numpy.uint8", "cv2.Laplacian", "os.listdir", "numpy.unique", "argparse.ArgumentParser", "pathlib.Path", "os.path.join", "pycocotools.coco.COCO", "numpy.stack", "numpy.zeros", "cv2.adaptiveThreshold", "numpy.empty", "cv2.cvtColor", "numpy.save", "pandas.DataFrame", "statsmodels.api.GLM...
[((184, 296), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Train generalized linear model to get coefficient for each variable."""'}), "(description=\n 'Train generalized linear model to get coefficient for each variable.')\n", (207, 296), False, 'import argparse\n'), ((11411, 11436), 'statsmodels.api.GLM', 'sm.GLM', (['endog_df', 'exog_df'], {}), '(endog_df, exog_df)\n', (11417, 11436), True, 'import statsmodels.api as sm\n'), ((4015, 4052), 'numpy.empty', 'np.empty', (['(img.shape + (num_features,))'], {}), '(img.shape + (num_features,))\n', (4023, 4052), True, 'import numpy as np\n'), ((4734, 4755), 'os.listdir', 'os.listdir', (['json_path'], {}), '(json_path)\n', (4744, 4755), False, 'import os\n'), ((11249, 11270), 'pathlib.Path', 'Path', (['binary_img_save'], {}), '(binary_img_save)\n', (11253, 11270), False, 'from pathlib import Path\n'), ((4886, 4916), 'os.path.join', 'os.path.join', (['json_path', 'jfile'], {}), '(json_path, jfile)\n', (4898, 4916), False, 'import os\n'), ((4935, 4948), 'pycocotools.coco.COCO', 'COCO', (['annFile'], {}), '(annFile)\n', (4939, 4948), False, 'from pycocotools.coco import COCO\n'), ((5636, 5661), 'numpy.zeros', 'np.zeros', (['(height, width)'], {}), '((height, width))\n', (5644, 5661), True, 'import numpy as np\n'), ((6023, 6075), 'numpy.zeros', 'np.zeros', ([], {'shape': '(height, width, 3)', 'dtype': 'np.float32'}), '(shape=(height, width, 3), dtype=np.float32)\n', (6031, 6075), True, 'import numpy as np\n'), ((6994, 7029), 'cv2.cvtColor', 'cv.cvtColor', (['img', 'cv.COLOR_BGR2GRAY'], {}), '(img, cv.COLOR_BGR2GRAY)\n', (7005, 7029), True, 'import cv2 as cv\n'), ((7903, 8006), 'cv2.GaussianBlur', 'cv.GaussianBlur', (['img', "((PARAMS['blur']['green_kernel_size'],) * 2)", "PARAMS['blur']['green_strength']"], {}), "(img, (PARAMS['blur']['green_kernel_size'],) * 2, PARAMS[\n 'blur']['green_strength'])\n", (7918, 8006), True, 'import cv2 as cv\n'), ((8294, 8324), 'cv2.Laplacian', 'cv.Laplacian', (['gray', 'cv.CV_8UC1'], {}), '(gray, cv.CV_8UC1)\n', (8306, 8324), True, 'import cv2 as cv\n'), ((8434, 8466), 'numpy.uint8', 'np.uint8', (['(texture[:, :, 4] * 255)'], {}), '(texture[:, :, 4] * 255)\n', (8442, 8466), True, 'import numpy as np\n'), ((8570, 8602), 'numpy.uint8', 'np.uint8', (['(texture[:, :, 2] * 255)'], {}), '(texture[:, :, 2] * 255)\n', (8578, 8602), True, 'import numpy as np\n'), ((5983, 6002), 'numpy.unique', 'np.unique', (['mask_pic'], {}), '(mask_pic)\n', (5992, 6002), True, 'import numpy as np\n'), ((6259, 6311), 'pandas.DataFrame', 'pd.DataFrame', (['binary_endog'], {'columns': "['binary_endog']"}), "(binary_endog, columns=['binary_endog'])\n", (6271, 6311), True, 'import pandas as pd\n'), ((8771, 8922), 'cv2.adaptiveThreshold', 'cv.adaptiveThreshold', (['blur_blue', '(255)', 'cv.ADAPTIVE_THRESH_GAUSSIAN_C', 'cv.THRESH_BINARY', "PARAMS['threshold']['block_size']", "PARAMS['threshold']['C']"], {}), "(blur_blue, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.\n THRESH_BINARY, PARAMS['threshold']['block_size'], PARAMS['threshold']['C'])\n", (8791, 8922), True, 'import cv2 as cv\n'), ((8967, 9119), 'cv2.adaptiveThreshold', 'cv.adaptiveThreshold', (['blur_green', '(255)', 'cv.ADAPTIVE_THRESH_GAUSSIAN_C', 'cv.THRESH_BINARY', "PARAMS['threshold']['block_size']", "PARAMS['threshold']['C']"], {}), "(blur_green, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.\n THRESH_BINARY, PARAMS['threshold']['block_size'], PARAMS['threshold']['C'])\n", (8987, 9119), True, 'import cv2 as cv\n'), ((9162, 9312), 'cv2.adaptiveThreshold', 'cv.adaptiveThreshold', (['blur_red', '(255)', 'cv.ADAPTIVE_THRESH_GAUSSIAN_C', 'cv.THRESH_BINARY', "PARAMS['threshold']['block_size']", "PARAMS['threshold']['C']"], {}), "(blur_red, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.\n THRESH_BINARY, PARAMS['threshold']['block_size'], PARAMS['threshold']['C'])\n", (9182, 9312), True, 'import cv2 as cv\n'), ((9360, 9515), 'cv2.adaptiveThreshold', 'cv.adaptiveThreshold', (['blur_gradient', '(255)', 'cv.ADAPTIVE_THRESH_GAUSSIAN_C', 'cv.THRESH_BINARY', "PARAMS['threshold']['block_size']", "PARAMS['threshold']['C']"], {}), "(blur_gradient, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.\n THRESH_BINARY, PARAMS['threshold']['block_size'], PARAMS['threshold']['C'])\n", (9380, 9515), True, 'import cv2 as cv\n'), ((9564, 9719), 'cv2.adaptiveThreshold', 'cv.adaptiveThreshold', (['blur_contrast', '(255)', 'cv.ADAPTIVE_THRESH_GAUSSIAN_C', 'cv.THRESH_BINARY', "PARAMS['threshold']['block_size']", "PARAMS['threshold']['C']"], {}), "(blur_contrast, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.\n THRESH_BINARY, PARAMS['threshold']['block_size'], PARAMS['threshold']['C'])\n", (9584, 9719), True, 'import cv2 as cv\n'), ((9770, 9932), 'cv2.adaptiveThreshold', 'cv.adaptiveThreshold', (['blur_homogeneity', '(255)', 'cv.ADAPTIVE_THRESH_GAUSSIAN_C', 'cv.THRESH_BINARY', "PARAMS['threshold']['block_size']", "PARAMS['threshold']['C']"], {}), "(blur_homogeneity, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C,\n cv.THRESH_BINARY, PARAMS['threshold']['block_size'], PARAMS['threshold'\n ]['C'])\n", (9790, 9932), True, 'import cv2 as cv\n'), ((10385, 10480), 'numpy.stack', 'np.stack', (['(th_blue_1, th_green_1, th_red_1, th_gradient_1, th_contrast_1,\n th_homogeneity_1)'], {}), '((th_blue_1, th_green_1, th_red_1, th_gradient_1, th_contrast_1,\n th_homogeneity_1))\n', (10393, 10480), True, 'import numpy as np\n'), ((10550, 10670), 'pandas.DataFrame', 'pd.DataFrame', (['features_np'], {'columns': "['th_blue', 'th_green', 'th_red', 'th_gradient', 'th_contrast',\n 'th_homogeneity']"}), "(features_np, columns=['th_blue', 'th_green', 'th_red',\n 'th_gradient', 'th_contrast', 'th_homogeneity'])\n", (10562, 10670), True, 'import pandas as pd\n'), ((6375, 6427), 'pandas.DataFrame', 'pd.DataFrame', (['binary_endog'], {'columns': "['binary_endog']"}), "(binary_endog, columns=['binary_endog'])\n", (6387, 6427), True, 'import pandas as pd\n'), ((7238, 7260), 'numpy.load', 'np.load', (['texture_cache'], {}), '(texture_cache)\n', (7245, 7260), True, 'import numpy as np\n'), ((7618, 7649), 'numpy.save', 'np.save', (['texture_cache', 'texture'], {}), '(texture_cache, texture)\n', (7625, 7649), True, 'import numpy as np\n'), ((10728, 10848), 'pandas.DataFrame', 'pd.DataFrame', (['features_np'], {'columns': "['th_blue', 'th_green', 'th_red', 'th_gradient', 'th_contrast',\n 'th_homogeneity']"}), "(features_np, columns=['th_blue', 'th_green', 'th_red',\n 'th_gradient', 'th_contrast', 'th_homogeneity'])\n", (10740, 10848), True, 'import pandas as pd\n'), ((7178, 7197), 'pathlib.Path', 'Path', (['texture_cache'], {}), '(texture_cache)\n', (7182, 7197), False, 'from pathlib import Path\n')]
import hits import numpy as np ''' Two similar graphs with different indices''' a = np.array([[0., 1., 1., 0.], \ [0., 0., 0., 0.], \ [0., 1., 0., 1.], \ [1., 1., 0., 1.]]) # b = np.array([[0., 1., 1., 0.], \ # [0., 0., 0., 0.], \ # [0., 1., 0., 1.], \ # [1., 1., 0., 1.]]) b = np.array(([[1., 1., 1., 0.], \ [0., 0., 1., 1.], \ [0., 0., 0., 0.], \ [1., 0., 1., 0.]])) print(a) # ascoreA = 0.0 # hscoreA = 0.0 # step = 40 # normalize = True # # ascoreA, hscoreA = hits.hits(a, step, normalize) # # ascoreB = 0.0 # hscoreB = 0.0 # # step = 1 # # normalize = True # # ascoreB, hscoreB = hits.hits(b, step, normalize) # print('Authority score for A are {0} with {1} step(s)'.format(ascoreA, step)) # print('Hub score for A are {0} with {1} step(s)'.format(hscoreA, step)) # # print('Authority score for B are {0} with {1} step(s)'.format(ascoreB, step)) # print('Hub score for B are {0} with {1} step(s)'.format(hscoreB, step)) hits.comparison(a, b, steps=50, normalize=True)
[ "numpy.array", "hits.comparison" ]
[((85, 187), 'numpy.array', 'np.array', (['[[0.0, 1.0, 1.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 1.0], [1.0, \n 1.0, 0.0, 1.0]]'], {}), '([[0.0, 1.0, 1.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 1.0],\n [1.0, 1.0, 0.0, 1.0]])\n', (93, 187), True, 'import numpy as np\n'), ((365, 467), 'numpy.array', 'np.array', (['[[1.0, 1.0, 1.0, 0.0], [0.0, 0.0, 1.0, 1.0], [0.0, 0.0, 0.0, 0.0], [1.0, \n 0.0, 1.0, 0.0]]'], {}), '([[1.0, 1.0, 1.0, 0.0], [0.0, 0.0, 1.0, 1.0], [0.0, 0.0, 0.0, 0.0],\n [1.0, 0.0, 1.0, 0.0]])\n', (373, 467), True, 'import numpy as np\n'), ((1061, 1108), 'hits.comparison', 'hits.comparison', (['a', 'b'], {'steps': '(50)', 'normalize': '(True)'}), '(a, b, steps=50, normalize=True)\n', (1076, 1108), False, 'import hits\n')]
import numpy as np import pytest from cognigraph.nodes.processors import MNE from cognigraph.nodes.sources import FileSource from cognigraph.nodes.tests.prepare_tests_data import (info, # noqa fwd_model_path, data_path) @pytest.fixture def inv_model(info, fwd_model_path, data_path): # noqa snr = 1 method = 'MNE' inv_model = MNE( snr=snr, fwd_path=fwd_model_path, method=method) inv_model.mne_info = info N_SEN = len(info['ch_names']) inv_model.input = np.random.rand(N_SEN) parent = FileSource(data_path) parent.output = np.random.rand(info['nchan'], 1) parent.mne_info = info inv_model.parent = parent return inv_model @pytest.fixture def inv_model_def(info): # noqa inv_model_def = MNE() parent = FileSource() parent.mne_info = info parent.output = np.random.rand(info['nchan'], 1) inv_model_def.parent = parent return inv_model_def def test_defaults(inv_model_def): assert(inv_model_def.fwd_path is None) assert(inv_model_def.mne_info is None) def test_initialize(inv_model): inv_model.initialize() def test_change_api_attributes(inv_model): inv_model.initialize() l2_old = inv_model._lambda2 snr_old = inv_model.snr arbitrary_value = 1 inv_model.snr += arbitrary_value inv_model.update() assert l2_old != inv_model._lambda2 assert inv_model._lambda2 == 1 / (snr_old + arbitrary_value) ** 2 def test_input_hist_invalidation_defined(inv_model): """ Change source attribute which triggers on_upstream_change and see if inv_model fails """ inv_model.parent.initialize() inv_model.initialize() inv_model.parent.source_name = 'new_name' # triggers reset for source def test_update(inv_model): inv_model._initialize() inv_model._update() def test_check_value(inv_model): with pytest.raises(ValueError): inv_model.snr = -1
[ "cognigraph.nodes.processors.MNE", "pytest.raises", "numpy.random.rand", "cognigraph.nodes.sources.FileSource" ]
[((453, 505), 'cognigraph.nodes.processors.MNE', 'MNE', ([], {'snr': 'snr', 'fwd_path': 'fwd_model_path', 'method': 'method'}), '(snr=snr, fwd_path=fwd_model_path, method=method)\n', (456, 505), False, 'from cognigraph.nodes.processors import MNE\n'), ((601, 622), 'numpy.random.rand', 'np.random.rand', (['N_SEN'], {}), '(N_SEN)\n', (615, 622), True, 'import numpy as np\n'), ((636, 657), 'cognigraph.nodes.sources.FileSource', 'FileSource', (['data_path'], {}), '(data_path)\n', (646, 657), False, 'from cognigraph.nodes.sources import FileSource\n'), ((678, 710), 'numpy.random.rand', 'np.random.rand', (["info['nchan']", '(1)'], {}), "(info['nchan'], 1)\n", (692, 710), True, 'import numpy as np\n'), ((860, 865), 'cognigraph.nodes.processors.MNE', 'MNE', ([], {}), '()\n', (863, 865), False, 'from cognigraph.nodes.processors import MNE\n'), ((879, 891), 'cognigraph.nodes.sources.FileSource', 'FileSource', ([], {}), '()\n', (889, 891), False, 'from cognigraph.nodes.sources import FileSource\n'), ((939, 971), 'numpy.random.rand', 'np.random.rand', (["info['nchan']", '(1)'], {}), "(info['nchan'], 1)\n", (953, 971), True, 'import numpy as np\n'), ((1970, 1995), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (1983, 1995), False, 'import pytest\n')]
'Class for a Pyomo vector and a Spin object which is derived from PyomoVector' from __future__ import division from pyomo.environ import sqrt, value, cos, sin, acos, atan import numpy as np class PyomoVector(object): '''Generic vector object which stores both the Cartesian and Spherical components of the vector''' def __init__(self, cart_comp=None, sph_comp=None): '''Initialised the vector either in Cartesian components or Spherical components. If both are given, only looks at cart_comp''' if cart_comp is not None: self.x = cart_comp[0] self.y = cart_comp[1] self.z = cart_comp[2] self.length = sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2) if value(self.length) == 0: self.azi = 0.0 self.pol = 0.0 else: self.pol = acos(self.z / self.length) if value(self.x) != 0: self.azi = atan(self.y / self.x) else: self.azi = 0.0 elif sph_comp is not None: self.length = sph_comp[0] self.azi = sph_comp[1] self.pol = sph_comp[2] self.x = self.length * cos(self.azi) * sin(self.pol) self.y = self.length * sin(self.azi) * sin(self.pol) self.z = self.length * cos(self.pol) else: raise Exception('''Must give either Cartesian or Spherical components''') def _config_sph(self): 'Configures the spherical components from the Cartesian' self.length = sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2) if value(self.length) == 0: self.azi = 0.0 self.pol = 0.0 else: self.pol = acos(self.z / self.length) if value(self.x) != 0: self.azi = atan(self.y / self.x) else: self.azi = 0.0 def _config_cart(self): 'Configures the Cartesian components from the spherical' self.x = self.length * cos(self.azi) * sin(self.pol) self.y = self.length * sin(self.azi) * sin(self.pol) self.z = self.length * cos(self.pol) def set_x(self, comp_value): 'Sets the x-component to the specified value' self.x = comp_value self._config_sph() def set_y(self, comp_value): 'Sets the y-component to the specified value' self.y = comp_value self._config_sph() def set_z(self, comp_value): 'Sets the z-component to the specified value' self.z = comp_value self._config_sph() def set_length(self, comp_value): 'Sets the length component to the specified value' self.length = comp_value self._config_cart() def set_azi(self, comp_value): 'Sets the azi component to the specified value' self.azi = comp_value self._config_cart() def set_pol(self, comp_value): 'Sets the pol component to the specified value' self.pol = comp_value self._config_cart() def add(self, vector): 'Returns the addition of itself with another PyomoVector' return PyomoVector(cart_comp=(self.x + vector.x, self.y + vector.y, self.z + vector.z)) def __add__(self, vector): 'Overrides the addition operator' if isinstance(vector, PyomoVector): return self.add(vector) return NotImplemented def multiply(self, scalar): 'Returns the result of the vector being multiplied by a scalar' return PyomoVector(cart_comp=(scalar * self.x, scalar * self.y, scalar * self.z)) def __mul__(self, scalar): 'Overrides the multiplication operator for scalars' return self.multiply(scalar) def __rmul__(self, scalar): 'Overrides the reverse multiplication for scalars' return self * scalar def __sub__(self, vector): 'Overrides the subtraction of vectors' if isinstance(vector, PyomoVector): neg_vector = -1 * vector return self + neg_vector return NotImplemented def __pos_(self): 'Overrides the "+" operand in front of a vector' return self def __neg__(self): 'Overrides the "-" operand in front of a vector' return -1 * self def __abs__(self): 'Overrides the abs() function' return self.length def scalar_product(self, vector): 'Returns the scalar product of itself with another PyomoVector' return self.x * vector.x + self.y * vector.y + self.z * vector.z def vector_product(self, vector): 'Returns the vector product of itself with another PyomoVector' x_comp = self.y * vector.z - self.z * vector.y y_comp = self.z * vector.x - self.x * vector.z z_comp = self.x * vector.y - self.y * vector.x return PyomoVector(cart_comp=(x_comp, y_comp, z_comp)) def normalise(self, new_length): 'Returns a vector parallel to itself with given length' if value(abs(self)) == 0: return self else: factor = new_length / abs(self) return self * factor def cart_tuple(self): 'Returns the Cartesian components in a tuple' return (value(self.x), value(self.y), value(self.z)) def sph_tuple(self): 'Returns the Spherical components in a tuple' return (value(self.length), value(self.azi), value(self.pol)) def __eq__(self, vector): 'Overides the equals method' if isinstance(vector, PyomoVector): return self.x == vector.x and\ self.y == vector.y and\ self.z == vector.z return NotImplemented class Spin(PyomoVector): '''Object for a spin, which is a unit vector and defined by an azimuth and polar angle.''' def __init__(self, azi, pol): 'Azimuth and polar angles passed in to define the spin.' PyomoVector.__init__(self, sph_comp=(1.0, azi, pol)) # Unit vectors in x, y, z directions X_UNIT = PyomoVector(cart_comp=(1.0, 0.0, 0.0)) Y_UNIT = PyomoVector(cart_comp=(0.0, 1.0, 0.0)) Z_UNIT = PyomoVector(cart_comp=(0.0, 0.0, 1.0)) # Zero vector ZERO_VECTOR = PyomoVector(cart_comp=(0.0, 0.0, 0.0)) # Standard cubic lattice basis vectors CUBIC_BASIS_VECTORS = (X_UNIT, Y_UNIT, Z_UNIT) # Hexagonal lattice basis vectors HEX_BASIS_1 = X_UNIT HEX_BASIS_2 = PyomoVector(cart_comp=(np.cos(np.radians(120)), np.sin(np.radians(120)), 0.0)) HEX_BASIS_3 = Z_UNIT HEX_BASIS_VECTORS = (HEX_BASIS_1, HEX_BASIS_2, HEX_BASIS_3)
[ "numpy.radians", "pyomo.environ.value", "pyomo.environ.sin", "pyomo.environ.cos", "pyomo.environ.atan", "pyomo.environ.sqrt", "pyomo.environ.acos" ]
[((1626, 1671), 'pyomo.environ.sqrt', 'sqrt', (['(self.x ** 2 + self.y ** 2 + self.z ** 2)'], {}), '(self.x ** 2 + self.y ** 2 + self.z ** 2)\n', (1630, 1671), False, 'from pyomo.environ import sqrt, value, cos, sin, acos, atan\n'), ((691, 736), 'pyomo.environ.sqrt', 'sqrt', (['(self.x ** 2 + self.y ** 2 + self.z ** 2)'], {}), '(self.x ** 2 + self.y ** 2 + self.z ** 2)\n', (695, 736), False, 'from pyomo.environ import sqrt, value, cos, sin, acos, atan\n'), ((1683, 1701), 'pyomo.environ.value', 'value', (['self.length'], {}), '(self.length)\n', (1688, 1701), False, 'from pyomo.environ import sqrt, value, cos, sin, acos, atan\n'), ((1799, 1825), 'pyomo.environ.acos', 'acos', (['(self.z / self.length)'], {}), '(self.z / self.length)\n', (1803, 1825), False, 'from pyomo.environ import sqrt, value, cos, sin, acos, atan\n'), ((2100, 2113), 'pyomo.environ.sin', 'sin', (['self.pol'], {}), '(self.pol)\n', (2103, 2113), False, 'from pyomo.environ import sqrt, value, cos, sin, acos, atan\n'), ((2161, 2174), 'pyomo.environ.sin', 'sin', (['self.pol'], {}), '(self.pol)\n', (2164, 2174), False, 'from pyomo.environ import sqrt, value, cos, sin, acos, atan\n'), ((2206, 2219), 'pyomo.environ.cos', 'cos', (['self.pol'], {}), '(self.pol)\n', (2209, 2219), False, 'from pyomo.environ import sqrt, value, cos, sin, acos, atan\n'), ((5473, 5486), 'pyomo.environ.value', 'value', (['self.x'], {}), '(self.x)\n', (5478, 5486), False, 'from pyomo.environ import sqrt, value, cos, sin, acos, atan\n'), ((5488, 5501), 'pyomo.environ.value', 'value', (['self.y'], {}), '(self.y)\n', (5493, 5501), False, 'from pyomo.environ import sqrt, value, cos, sin, acos, atan\n'), ((5503, 5516), 'pyomo.environ.value', 'value', (['self.z'], {}), '(self.z)\n', (5508, 5516), False, 'from pyomo.environ import sqrt, value, cos, sin, acos, atan\n'), ((5614, 5632), 'pyomo.environ.value', 'value', (['self.length'], {}), '(self.length)\n', (5619, 5632), False, 'from pyomo.environ import sqrt, value, cos, sin, acos, atan\n'), ((5634, 5649), 'pyomo.environ.value', 'value', (['self.azi'], {}), '(self.azi)\n', (5639, 5649), False, 'from pyomo.environ import sqrt, value, cos, sin, acos, atan\n'), ((5651, 5666), 'pyomo.environ.value', 'value', (['self.pol'], {}), '(self.pol)\n', (5656, 5666), False, 'from pyomo.environ import sqrt, value, cos, sin, acos, atan\n'), ((752, 770), 'pyomo.environ.value', 'value', (['self.length'], {}), '(self.length)\n', (757, 770), False, 'from pyomo.environ import sqrt, value, cos, sin, acos, atan\n'), ((884, 910), 'pyomo.environ.acos', 'acos', (['(self.z / self.length)'], {}), '(self.z / self.length)\n', (888, 910), False, 'from pyomo.environ import sqrt, value, cos, sin, acos, atan\n'), ((1841, 1854), 'pyomo.environ.value', 'value', (['self.x'], {}), '(self.x)\n', (1846, 1854), False, 'from pyomo.environ import sqrt, value, cos, sin, acos, atan\n'), ((1888, 1909), 'pyomo.environ.atan', 'atan', (['(self.y / self.x)'], {}), '(self.y / self.x)\n', (1892, 1909), False, 'from pyomo.environ import sqrt, value, cos, sin, acos, atan\n'), ((2084, 2097), 'pyomo.environ.cos', 'cos', (['self.azi'], {}), '(self.azi)\n', (2087, 2097), False, 'from pyomo.environ import sqrt, value, cos, sin, acos, atan\n'), ((2145, 2158), 'pyomo.environ.sin', 'sin', (['self.azi'], {}), '(self.azi)\n', (2148, 2158), False, 'from pyomo.environ import sqrt, value, cos, sin, acos, atan\n'), ((6651, 6666), 'numpy.radians', 'np.radians', (['(120)'], {}), '(120)\n', (6661, 6666), True, 'import numpy as np\n'), ((6713, 6728), 'numpy.radians', 'np.radians', (['(120)'], {}), '(120)\n', (6723, 6728), True, 'import numpy as np\n'), ((930, 943), 'pyomo.environ.value', 'value', (['self.x'], {}), '(self.x)\n', (935, 943), False, 'from pyomo.environ import sqrt, value, cos, sin, acos, atan\n'), ((981, 1002), 'pyomo.environ.atan', 'atan', (['(self.y / self.x)'], {}), '(self.y / self.x)\n', (985, 1002), False, 'from pyomo.environ import sqrt, value, cos, sin, acos, atan\n'), ((1255, 1268), 'pyomo.environ.sin', 'sin', (['self.pol'], {}), '(self.pol)\n', (1258, 1268), False, 'from pyomo.environ import sqrt, value, cos, sin, acos, atan\n'), ((1320, 1333), 'pyomo.environ.sin', 'sin', (['self.pol'], {}), '(self.pol)\n', (1323, 1333), False, 'from pyomo.environ import sqrt, value, cos, sin, acos, atan\n'), ((1369, 1382), 'pyomo.environ.cos', 'cos', (['self.pol'], {}), '(self.pol)\n', (1372, 1382), False, 'from pyomo.environ import sqrt, value, cos, sin, acos, atan\n'), ((1239, 1252), 'pyomo.environ.cos', 'cos', (['self.azi'], {}), '(self.azi)\n', (1242, 1252), False, 'from pyomo.environ import sqrt, value, cos, sin, acos, atan\n'), ((1304, 1317), 'pyomo.environ.sin', 'sin', (['self.azi'], {}), '(self.azi)\n', (1307, 1317), False, 'from pyomo.environ import sqrt, value, cos, sin, acos, atan\n')]
# -*- coding: utf-8 -*- """ Created on Tue Aug 21 13:03:42 2018 @author: <NAME> """ import numpy as np import matplotlib.pyplot as plt from IPython.display import SVG, display #Import Keras objects from keras.models import Model from keras.layers import Input, Flatten, Reshape, Softmax from keras.layers import Dense, UpSampling1D from keras.layers import Conv1D, MaxPool1D from keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, TensorBoard, EarlyStopping from keras.utils.vis_utils import model_to_dot from keras.utils import multi_gpu_model from keras.regularizers import l1 from tensorboard.backend.event_processing.event_accumulator import EventAccumulator import keras.backend as K from os import listdir from os.path import isfile, join class ModelMGPU(Model): def __init__(self, ser_model, gpus): pmodel = multi_gpu_model(ser_model, gpus) self.__dict__.update(pmodel.__dict__) self._smodel = ser_model def __getattribute__(self, attrname): '''Override load and save methods to be used from the serial-model. The serial-model holds references to the weights in the multi-gpu model. ''' # return Model.__getattribute__(self, attrname) if 'load' in attrname or 'save' in attrname: return getattr(self._smodel, attrname) return super(ModelMGPU, self).__getattribute__(attrname) def jaccard(yt, yp, sm=1e-6): yt=K.batch_flatten(yt) yp=K.batch_flatten(yp) intr = K.sum(yt*yp,axis=-1) sum_ = K.sum(yt + yp,axis=-1) jac = (intr + sm) / (sum_ - intr + sm) return K.mean(jac) def jaccard_loss(y_true, y_pred, sm=1e-6): return (1.0 - jaccard(y_true,y_pred,sm)) def dice(y_true, y_pred, sm=1e-6): yp=K.batch_flatten(y_pred) yt=K.batch_flatten(y_true) intr = K.sum(yt*yp,axis=-1) sum_ = K.sum(K.square(yt)+K.square(yp),axis=-1) + sm dce = (2.0 * intr + sm) / sum_ return K.mean(dce) def dice_loss(y_true, y_pred, sm=1e-6): return 1.0 - dice(y_true, y_pred, sm) def Wo(W,F=2,S=2): P = W % 2 return (W-F+2*P)//S+1 class CNAE: def __init__(self,smt,lrep=4, nEL=1,opt='adam', ngpu=1,reg=0.001,kern=5,flt=32,batch=256,EPO=1): self.ngpu=ngpu self.EPO=EPO self.batch=batch smiLen = smt.smiLen codeLen = smt.codeLen k = smiLen inputs = Input(shape=(smiLen,codeLen,),name='IN1') for L in range(nEL): if L==0: x = Conv1D(flt,kern,name='C1',activation='relu',padding='same')(inputs) else: x = Conv1D(flt,kern,name=f'C{L+1}',activation='relu',padding='same')(x) x = MaxPool1D(2,padding='same')(x) k = Wo(k) x = Conv1D(flt,kern,name=f'C{nEL+1}',activation='relu',padding='same')(x) x = MaxPool1D(2,padding='same')(x) k = Wo(k) x = Flatten()(x) enc = Dense(lrep,name='Encoded',activation='relu',activity_regularizer=l1(reg))(x) x = Dense(k*flt)(enc) x = Reshape((k,flt,))(x) k2 = k for L in range(nEL): x = Conv1D(flt,kern,name=f'D{L+1}',activation='relu',padding='same')(x) x = UpSampling1D(2)(x) k2 = k2 * 2 x = Conv1D(smt.codeLen,kern,name=f'D{nEL+1}',activation='relu',padding='same')(x) x = UpSampling1D(2)(x) k2 = k2 * 2 f = k2 - smt.smiLen + 1 x = Conv1D(smt.codeLen,f,name='outp',padding='valid')(x) op = Softmax(axis=-1)(x) self.enc = Model(inputs,enc) self.aen = Model(inputs,op) N = 6 + nEL * 2 inp2 = Input(shape=(lrep,),name='IN2') for L in range(N): if L==0: deco = self.aen.layers[L-N](inp2) else: deco = self.aen.layers[L-N](deco) self.dec = Model(inp2,deco) if self.ngpu>1: self.mgm = ModelMGPU(self.aen,gpus=self.ngpu) self.mgm.compile(optimizer=opt, loss='binary_crossentropy',metrics=['acc',jaccard,dice_loss]) else: self.aen.compile(optimizer=opt, loss='binary_crossentropy',metrics=['acc',jaccard,dice_loss]) self.mgm = None def aeTrain(self,trn,fn,vb=0,mdelta=0.0002,esp=10,EPO=None): if EPO is None: epo = self.EPO else: epo = EPO bat=self.batch modsave = f'data/{fn}.hdf5' chkptr = ModelCheckpoint(filepath = modsave, verbose = 0, save_best_only = True) rlr = ReduceLROnPlateau(monitor = 'val_loss', factor = 0.2, patience = 2, min_lr = 0.000001) lgd = f'logs/{fn}' tb = TensorBoard(log_dir=lgd) estp = EarlyStopping(patience=esp,restore_best_weights=True,min_delta=mdelta) cblist=[chkptr,estp,tb,rlr] if self.mgm is None: self.aen.fit(trn, trn, shuffle = True, epochs = epo, batch_size = bat, callbacks = cblist, validation_split = 0.2,verbose=vb) self.aen.load_weights(modsave) else: self.mgm.fit(trn, trn, shuffle = True, epochs = epo, batch_size = bat, callbacks = cblist, validation_split = 0.2,verbose=vb) self.mgm.load_weights(modsave) return modsave,lgd def loadw(self,modsave): if self.mgm is None: self.aen.load_weights(modsave) else: self.mgm.load_weights(modsave) def evaluate(self,x): if self.mgm is None: sc = self.aen.evaluate(x,x) else: sc = self.mgm.evaluate(x,x) return sc #0 -> loss def plotm(model): display(SVG(model_to_dot(model,show_shapes=True).create(prog='dot', format='svg'))) def getFileList(mypath): return [f for f in listdir(mypath) if isfile(join(mypath, f))] def tbHistoryPlot(lgd): fn = getFileList(lgd) fn = fn[-1] eacc = EventAccumulator(lgd+'/'+fn) eacc.Reload() tj = eacc.Scalars('loss') vj = eacc.Scalars('val_loss') steps = len(tj) x = np.arange(steps) y = np.zeros([steps, 2]) for i in range(steps): y[i, 0] = tj[i][2] # value y[i, 1] = vj[i][2] plt.plot(x, y[:,0], label='training loss') plt.plot(x, y[:,1], label='validation loss') plt.xlabel("Steps") plt.ylabel("Loss") plt.title("Re-Training Progress") plt.legend(loc='upper right', frameon=True) plt.show() #%% if __name__ == "__main__": pass
[ "keras.backend.sum", "matplotlib.pyplot.ylabel", "keras.layers.MaxPool1D", "keras.layers.Softmax", "keras.backend.batch_flatten", "keras.layers.Dense", "numpy.arange", "os.listdir", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "keras.utils.multi_gpu_model", "keras.backend.square", "...
[((1430, 1449), 'keras.backend.batch_flatten', 'K.batch_flatten', (['yt'], {}), '(yt)\n', (1445, 1449), True, 'import keras.backend as K\n'), ((1457, 1476), 'keras.backend.batch_flatten', 'K.batch_flatten', (['yp'], {}), '(yp)\n', (1472, 1476), True, 'import keras.backend as K\n'), ((1488, 1511), 'keras.backend.sum', 'K.sum', (['(yt * yp)'], {'axis': '(-1)'}), '(yt * yp, axis=-1)\n', (1493, 1511), True, 'import keras.backend as K\n'), ((1520, 1543), 'keras.backend.sum', 'K.sum', (['(yt + yp)'], {'axis': '(-1)'}), '(yt + yp, axis=-1)\n', (1525, 1543), True, 'import keras.backend as K\n'), ((1597, 1608), 'keras.backend.mean', 'K.mean', (['jac'], {}), '(jac)\n', (1603, 1608), True, 'import keras.backend as K\n'), ((1741, 1764), 'keras.backend.batch_flatten', 'K.batch_flatten', (['y_pred'], {}), '(y_pred)\n', (1756, 1764), True, 'import keras.backend as K\n'), ((1772, 1795), 'keras.backend.batch_flatten', 'K.batch_flatten', (['y_true'], {}), '(y_true)\n', (1787, 1795), True, 'import keras.backend as K\n'), ((1807, 1830), 'keras.backend.sum', 'K.sum', (['(yt * yp)'], {'axis': '(-1)'}), '(yt * yp, axis=-1)\n', (1812, 1830), True, 'import keras.backend as K\n'), ((1931, 1942), 'keras.backend.mean', 'K.mean', (['dce'], {}), '(dce)\n', (1937, 1942), True, 'import keras.backend as K\n'), ((5894, 5926), 'tensorboard.backend.event_processing.event_accumulator.EventAccumulator', 'EventAccumulator', (["(lgd + '/' + fn)"], {}), "(lgd + '/' + fn)\n", (5910, 5926), False, 'from tensorboard.backend.event_processing.event_accumulator import EventAccumulator\n'), ((6033, 6049), 'numpy.arange', 'np.arange', (['steps'], {}), '(steps)\n', (6042, 6049), True, 'import numpy as np\n'), ((6058, 6078), 'numpy.zeros', 'np.zeros', (['[steps, 2]'], {}), '([steps, 2])\n', (6066, 6078), True, 'import numpy as np\n'), ((6172, 6215), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y[:, 0]'], {'label': '"""training loss"""'}), "(x, y[:, 0], label='training loss')\n", (6180, 6215), True, 'import matplotlib.pyplot as plt\n'), ((6219, 6264), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y[:, 1]'], {'label': '"""validation loss"""'}), "(x, y[:, 1], label='validation loss')\n", (6227, 6264), True, 'import matplotlib.pyplot as plt\n'), ((6269, 6288), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Steps"""'], {}), "('Steps')\n", (6279, 6288), True, 'import matplotlib.pyplot as plt\n'), ((6293, 6311), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Loss"""'], {}), "('Loss')\n", (6303, 6311), True, 'import matplotlib.pyplot as plt\n'), ((6316, 6349), 'matplotlib.pyplot.title', 'plt.title', (['"""Re-Training Progress"""'], {}), "('Re-Training Progress')\n", (6325, 6349), True, 'import matplotlib.pyplot as plt\n'), ((6354, 6397), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper right"""', 'frameon': '(True)'}), "(loc='upper right', frameon=True)\n", (6364, 6397), True, 'import matplotlib.pyplot as plt\n'), ((6402, 6412), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6410, 6412), True, 'import matplotlib.pyplot as plt\n'), ((842, 874), 'keras.utils.multi_gpu_model', 'multi_gpu_model', (['ser_model', 'gpus'], {}), '(ser_model, gpus)\n', (857, 874), False, 'from keras.utils import multi_gpu_model\n'), ((2384, 2426), 'keras.layers.Input', 'Input', ([], {'shape': '(smiLen, codeLen)', 'name': '"""IN1"""'}), "(shape=(smiLen, codeLen), name='IN1')\n", (2389, 2426), False, 'from keras.layers import Input, Flatten, Reshape, Softmax\n'), ((3540, 3558), 'keras.models.Model', 'Model', (['inputs', 'enc'], {}), '(inputs, enc)\n', (3545, 3558), False, 'from keras.models import Model\n'), ((3577, 3594), 'keras.models.Model', 'Model', (['inputs', 'op'], {}), '(inputs, op)\n', (3582, 3594), False, 'from keras.models import Model\n'), ((3635, 3667), 'keras.layers.Input', 'Input', ([], {'shape': '(lrep,)', 'name': '"""IN2"""'}), "(shape=(lrep,), name='IN2')\n", (3640, 3667), False, 'from keras.layers import Input, Flatten, Reshape, Softmax\n'), ((3853, 3870), 'keras.models.Model', 'Model', (['inp2', 'deco'], {}), '(inp2, deco)\n', (3858, 3870), False, 'from keras.models import Model\n'), ((4436, 4501), 'keras.callbacks.ModelCheckpoint', 'ModelCheckpoint', ([], {'filepath': 'modsave', 'verbose': '(0)', 'save_best_only': '(True)'}), '(filepath=modsave, verbose=0, save_best_only=True)\n', (4451, 4501), False, 'from keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, TensorBoard, EarlyStopping\n'), ((4522, 4597), 'keras.callbacks.ReduceLROnPlateau', 'ReduceLROnPlateau', ([], {'monitor': '"""val_loss"""', 'factor': '(0.2)', 'patience': '(2)', 'min_lr': '(1e-06)'}), "(monitor='val_loss', factor=0.2, patience=2, min_lr=1e-06)\n", (4539, 4597), False, 'from keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, TensorBoard, EarlyStopping\n'), ((4649, 4673), 'keras.callbacks.TensorBoard', 'TensorBoard', ([], {'log_dir': 'lgd'}), '(log_dir=lgd)\n', (4660, 4673), False, 'from keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, TensorBoard, EarlyStopping\n'), ((4689, 4761), 'keras.callbacks.EarlyStopping', 'EarlyStopping', ([], {'patience': 'esp', 'restore_best_weights': '(True)', 'min_delta': 'mdelta'}), '(patience=esp, restore_best_weights=True, min_delta=mdelta)\n', (4702, 4761), False, 'from keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, TensorBoard, EarlyStopping\n'), ((2751, 2823), 'keras.layers.Conv1D', 'Conv1D', (['flt', 'kern'], {'name': 'f"""C{nEL + 1}"""', 'activation': '"""relu"""', 'padding': '"""same"""'}), "(flt, kern, name=f'C{nEL + 1}', activation='relu', padding='same')\n", (2757, 2823), False, 'from keras.layers import Conv1D, MaxPool1D\n'), ((2833, 2861), 'keras.layers.MaxPool1D', 'MaxPool1D', (['(2)'], {'padding': '"""same"""'}), "(2, padding='same')\n", (2842, 2861), False, 'from keras.layers import Conv1D, MaxPool1D\n'), ((2895, 2904), 'keras.layers.Flatten', 'Flatten', ([], {}), '()\n', (2902, 2904), False, 'from keras.layers import Input, Flatten, Reshape, Softmax\n'), ((3011, 3025), 'keras.layers.Dense', 'Dense', (['(k * flt)'], {}), '(k * flt)\n', (3016, 3025), False, 'from keras.layers import Dense, UpSampling1D\n'), ((3041, 3058), 'keras.layers.Reshape', 'Reshape', (['(k, flt)'], {}), '((k, flt))\n', (3048, 3058), False, 'from keras.layers import Input, Flatten, Reshape, Softmax\n'), ((3261, 3346), 'keras.layers.Conv1D', 'Conv1D', (['smt.codeLen', 'kern'], {'name': 'f"""D{nEL + 1}"""', 'activation': '"""relu"""', 'padding': '"""same"""'}), "(smt.codeLen, kern, name=f'D{nEL + 1}', activation='relu', padding='same'\n )\n", (3267, 3346), False, 'from keras.layers import Conv1D, MaxPool1D\n'), ((3351, 3366), 'keras.layers.UpSampling1D', 'UpSampling1D', (['(2)'], {}), '(2)\n', (3363, 3366), False, 'from keras.layers import Dense, UpSampling1D\n'), ((3434, 3486), 'keras.layers.Conv1D', 'Conv1D', (['smt.codeLen', 'f'], {'name': '"""outp"""', 'padding': '"""valid"""'}), "(smt.codeLen, f, name='outp', padding='valid')\n", (3440, 3486), False, 'from keras.layers import Conv1D, MaxPool1D\n'), ((3500, 3516), 'keras.layers.Softmax', 'Softmax', ([], {'axis': '(-1)'}), '(axis=-1)\n', (3507, 3516), False, 'from keras.layers import Input, Flatten, Reshape, Softmax\n'), ((5772, 5787), 'os.listdir', 'listdir', (['mypath'], {}), '(mypath)\n', (5779, 5787), False, 'from os import listdir\n'), ((1845, 1857), 'keras.backend.square', 'K.square', (['yt'], {}), '(yt)\n', (1853, 1857), True, 'import keras.backend as K\n'), ((1858, 1870), 'keras.backend.square', 'K.square', (['yp'], {}), '(yp)\n', (1866, 1870), True, 'import keras.backend as K\n'), ((2686, 2714), 'keras.layers.MaxPool1D', 'MaxPool1D', (['(2)'], {'padding': '"""same"""'}), "(2, padding='same')\n", (2695, 2714), False, 'from keras.layers import Conv1D, MaxPool1D\n'), ((3122, 3192), 'keras.layers.Conv1D', 'Conv1D', (['flt', 'kern'], {'name': 'f"""D{L + 1}"""', 'activation': '"""relu"""', 'padding': '"""same"""'}), "(flt, kern, name=f'D{L + 1}', activation='relu', padding='same')\n", (3128, 3192), False, 'from keras.layers import Conv1D, MaxPool1D\n'), ((3206, 3221), 'keras.layers.UpSampling1D', 'UpSampling1D', (['(2)'], {}), '(2)\n', (3218, 3221), False, 'from keras.layers import Dense, UpSampling1D\n'), ((5798, 5813), 'os.path.join', 'join', (['mypath', 'f'], {}), '(mypath, f)\n', (5802, 5813), False, 'from os.path import isfile, join\n'), ((2496, 2559), 'keras.layers.Conv1D', 'Conv1D', (['flt', 'kern'], {'name': '"""C1"""', 'activation': '"""relu"""', 'padding': '"""same"""'}), "(flt, kern, name='C1', activation='relu', padding='same')\n", (2502, 2559), False, 'from keras.layers import Conv1D, MaxPool1D\n'), ((2602, 2672), 'keras.layers.Conv1D', 'Conv1D', (['flt', 'kern'], {'name': 'f"""C{L + 1}"""', 'activation': '"""relu"""', 'padding': '"""same"""'}), "(flt, kern, name=f'C{L + 1}', activation='relu', padding='same')\n", (2608, 2672), False, 'from keras.layers import Conv1D, MaxPool1D\n'), ((2987, 2994), 'keras.regularizers.l1', 'l1', (['reg'], {}), '(reg)\n', (2989, 2994), False, 'from keras.regularizers import l1\n'), ((5651, 5688), 'keras.utils.vis_utils.model_to_dot', 'model_to_dot', (['model'], {'show_shapes': '(True)'}), '(model, show_shapes=True)\n', (5663, 5688), False, 'from keras.utils.vis_utils import model_to_dot\n')]
import numpy as np import torch def getIndeices(shape,height,width,stride,dialation, offset): H, W = shape outHeight = (H - dialation*(height-1)-1) // stride +1 outWidth = (W - dialation*(width-1)-1) // stride +1 i0 = np.repeat(np.arange(height)*dialation, width) i1 = stride * np.repeat(np.arange(outHeight), outWidth) j0 = np.tile(np.arange(width)*dialation, height) j1 = stride * np.tile(np.arange(outWidth), outHeight) i = i0.reshape(-1, 1) + i1.reshape(1, -1) j = j0.reshape(-1, 1) + j1.reshape(1, -1) return (i.transpose(1,0)+offset)%H, (j.transpose(1,0)+offset)%W def dispatch(i,j,x): x_ = x[:,:,i,j].reshape(x.shape[0],x.shape[1],i.shape[0],i.shape[1]) return x, x_ def collect(i,j,x,x_): xi = x.clone() xi[:,:,i,j]=x_.reshape(x.shape[0],-1,i.shape[0],i.shape[1]) return xi
[ "numpy.arange" ]
[((246, 263), 'numpy.arange', 'np.arange', (['height'], {}), '(height)\n', (255, 263), True, 'import numpy as np\n'), ((310, 330), 'numpy.arange', 'np.arange', (['outHeight'], {}), '(outHeight)\n', (319, 330), True, 'import numpy as np\n'), ((359, 375), 'numpy.arange', 'np.arange', (['width'], {}), '(width)\n', (368, 375), True, 'import numpy as np\n'), ((421, 440), 'numpy.arange', 'np.arange', (['outWidth'], {}), '(outWidth)\n', (430, 440), True, 'import numpy as np\n')]
#!/usr/bin/env python3.7 # -*- coding: utf8 -*- import numpy as np import scipy.stats as stats import numpy.random as rnd import scipy.fftpack as fftp import ROOT import root_numpy as rnp import time import datetime import argparse import os parser=argparse.ArgumentParser() parser.add_argument('amp', help='select amp',type=int) parser.add_argument('degree', help='filter order',type=int) parser.add_argument('nfile', help='select file',type=int) args=parser.parse_args() amp=args.amp degree=args.degree nfile=args.nfile t1=time.time() home=os.environ['HOME'] dir='nphe_shaping' name='{0}/{1}/scibar_photons-s{2}.csv'.format(home,dir,nfile) f=open(name,'r') dt=0.2 Fs=1.0/dt tend=1000.0 M=25000 Nz=50000 R=5000 ntime=np.arange(dt,100.0,dt) N=np.size(ntime) p=np.zeros([M,N]) n0,pnum,t0=np.array(f.readline().split()[0:3],dtype=np.float) iphe=np.zeros([M,R]) nphe=np.zeros(M,dtype=np.uint16) alpha=2.0 t=np.arange(0,tend,dt) tconv=np.arange(0,2.0*tend-dt,dt) Qpmt,sqpmt=0.938888,0.146729 mtau,stau=0.377159,0.0157205 tfun='TMath::Landau(x,{0},{1},1)'.format(mtau,stau) taud=ROOT.TF1('tau0',tfun,0.1,2.0) cf=['100p','200p','400p'] rf=['3k','6k','12k'] tpeaks=[75,100,125,150,175] mpar=np.size(cf)*np.size(rf)*np.size(tpeaks) j=0 jphoton=0 for line in f: p[j,jphoton]=t0 nphe[j]=jphoton+1 k=np.fromstring(line,dtype=np.float,count=4,sep=' ') nevent=k[0] t0=k[2] if n0!=nevent: n0=nevent ptimes=p[j,p[j,:]!=0] if np.all(ptimes<200.0): rnd_tau=rnp.random_sample(taud,jphoton+1) q=stats.norm.rvs(loc=Qpmt,scale=sqpmt,size=jphoton+1) k=q/(2.0*rnd_tau) tnorm=(t-np.transpose(ptimes[np.newaxis]))/np.transpose(rnd_tau[np.newaxis]) u=t>np.transpose(ptimes[np.newaxis]) izero=np.transpose(k[np.newaxis])*np.power(tnorm,alpha)*np.exp(-1.0*tnorm)*u iphe[j,:]=np.sum(izero,axis=0) j+=1 jphoton=0 else: jphoton+=1 test=np.logical_and(nphe!=0,np.sum(p!=0,axis=1)>=1.0) nphe=nphe[test] p=p[test] iphe=iphe[test,:] Mevent=np.size(iphe,0) pe_stats=np.zeros([Mevent,mpar+1]) pe_stats[:,0]=nphe print(Mevent) print(np.amin(nphe),np.amax(nphe)) elem=199 pe=np.arange(0,elem) pe_hist,bi=np.histogram(nphe,bins=np.arange(0,elem+1)) pe=bi[np.nonzero(pe_hist)] Npe=np.size(pe) kpar=0 Nhalf=int(Nz/2) i_freq=fftp.fft(iphe,2*R-1,axis=1) for tp in tpeaks: for c in cf: for r in rf: kpar+=1 name='{0}/{1}/electronics-sim/trans-{2}_tp{3}d{4}-{5}{6}.dat'.format(home,dir,amp,tp,degree,c,r) zl_freq=np.loadtxt(name,usecols=(1,3),skiprows=2) zl_full=np.zeros((Nz,2)) zl_full[0:Nhalf+1,0]=zl_freq[:,0] zl_full[0:Nhalf+1,1]=zl_freq[:,1] zl_full[Nhalf+1:Nz,0]=np.flip(zl_freq[1:Nhalf,0],0) zl_full[Nhalf+1:Nz,1]=-1.0*np.flip(zl_freq[1:Nhalf,1],0) zl_time=np.real(fftp.ifft(zl_full[:,0]+1j*zl_full[:,1]))[:R] z_conv=fftp.fft(zl_time,2*R-1) vint=np.real(fftp.ifft(i_freq*z_conv,axis=1))[:,:R] pe_stats[:,kpar]=np.amax(vint,axis=1) nout='{0}/{1}/pe_stats-b{2}_d{3}-{4}.dat'.format(home,dir,amp,degree,nfile) np.savetxt(nout,pe_stats) t2=time.time() dtime=datetime.timedelta(seconds=(t2-t1)) print('Tiempo total {0:1.2f} seg.'.format(dtime.total_seconds()))
[ "scipy.stats.norm.rvs", "numpy.loadtxt", "scipy.fftpack.fft", "datetime.timedelta", "numpy.arange", "numpy.flip", "argparse.ArgumentParser", "scipy.fftpack.ifft", "numpy.exp", "numpy.fromstring", "numpy.amax", "numpy.amin", "numpy.size", "numpy.savetxt", "numpy.nonzero", "numpy.transpo...
[((251, 276), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (274, 276), False, 'import argparse\n'), ((528, 539), 'time.time', 'time.time', ([], {}), '()\n', (537, 539), False, 'import time\n'), ((722, 746), 'numpy.arange', 'np.arange', (['dt', '(100.0)', 'dt'], {}), '(dt, 100.0, dt)\n', (731, 746), True, 'import numpy as np\n'), ((747, 761), 'numpy.size', 'np.size', (['ntime'], {}), '(ntime)\n', (754, 761), True, 'import numpy as np\n'), ((764, 780), 'numpy.zeros', 'np.zeros', (['[M, N]'], {}), '([M, N])\n', (772, 780), True, 'import numpy as np\n'), ((847, 863), 'numpy.zeros', 'np.zeros', (['[M, R]'], {}), '([M, R])\n', (855, 863), True, 'import numpy as np\n'), ((868, 896), 'numpy.zeros', 'np.zeros', (['M'], {'dtype': 'np.uint16'}), '(M, dtype=np.uint16)\n', (876, 896), True, 'import numpy as np\n'), ((908, 930), 'numpy.arange', 'np.arange', (['(0)', 'tend', 'dt'], {}), '(0, tend, dt)\n', (917, 930), True, 'import numpy as np\n'), ((935, 968), 'numpy.arange', 'np.arange', (['(0)', '(2.0 * tend - dt)', 'dt'], {}), '(0, 2.0 * tend - dt, dt)\n', (944, 968), True, 'import numpy as np\n'), ((1078, 1110), 'ROOT.TF1', 'ROOT.TF1', (['"""tau0"""', 'tfun', '(0.1)', '(2.0)'], {}), "('tau0', tfun, 0.1, 2.0)\n", (1086, 1110), False, 'import ROOT\n'), ((1991, 2007), 'numpy.size', 'np.size', (['iphe', '(0)'], {}), '(iphe, 0)\n', (1998, 2007), True, 'import numpy as np\n'), ((2016, 2044), 'numpy.zeros', 'np.zeros', (['[Mevent, mpar + 1]'], {}), '([Mevent, mpar + 1])\n', (2024, 2044), True, 'import numpy as np\n'), ((2123, 2141), 'numpy.arange', 'np.arange', (['(0)', 'elem'], {}), '(0, elem)\n', (2132, 2141), True, 'import numpy as np\n'), ((2227, 2238), 'numpy.size', 'np.size', (['pe'], {}), '(pe)\n', (2234, 2238), True, 'import numpy as np\n'), ((2270, 2303), 'scipy.fftpack.fft', 'fftp.fft', (['iphe', '(2 * R - 1)'], {'axis': '(1)'}), '(iphe, 2 * R - 1, axis=1)\n', (2278, 2303), True, 'import scipy.fftpack as fftp\n'), ((3036, 3062), 'numpy.savetxt', 'np.savetxt', (['nout', 'pe_stats'], {}), '(nout, pe_stats)\n', (3046, 3062), True, 'import numpy as np\n'), ((3065, 3076), 'time.time', 'time.time', ([], {}), '()\n', (3074, 3076), False, 'import time\n'), ((3083, 3118), 'datetime.timedelta', 'datetime.timedelta', ([], {'seconds': '(t2 - t1)'}), '(seconds=t2 - t1)\n', (3101, 3118), False, 'import datetime\n'), ((1212, 1227), 'numpy.size', 'np.size', (['tpeaks'], {}), '(tpeaks)\n', (1219, 1227), True, 'import numpy as np\n'), ((1300, 1353), 'numpy.fromstring', 'np.fromstring', (['line'], {'dtype': 'np.float', 'count': '(4)', 'sep': '""" """'}), "(line, dtype=np.float, count=4, sep=' ')\n", (1313, 1353), True, 'import numpy as np\n'), ((2081, 2094), 'numpy.amin', 'np.amin', (['nphe'], {}), '(nphe)\n', (2088, 2094), True, 'import numpy as np\n'), ((2095, 2108), 'numpy.amax', 'np.amax', (['nphe'], {}), '(nphe)\n', (2102, 2108), True, 'import numpy as np\n'), ((2202, 2221), 'numpy.nonzero', 'np.nonzero', (['pe_hist'], {}), '(pe_hist)\n', (2212, 2221), True, 'import numpy as np\n'), ((1188, 1199), 'numpy.size', 'np.size', (['cf'], {}), '(cf)\n', (1195, 1199), True, 'import numpy as np\n'), ((1200, 1211), 'numpy.size', 'np.size', (['rf'], {}), '(rf)\n', (1207, 1211), True, 'import numpy as np\n'), ((1439, 1461), 'numpy.all', 'np.all', (['(ptimes < 200.0)'], {}), '(ptimes < 200.0)\n', (1445, 1461), True, 'import numpy as np\n'), ((1914, 1936), 'numpy.sum', 'np.sum', (['(p != 0)'], {'axis': '(1)'}), '(p != 0, axis=1)\n', (1920, 1936), True, 'import numpy as np\n'), ((2175, 2197), 'numpy.arange', 'np.arange', (['(0)', '(elem + 1)'], {}), '(0, elem + 1)\n', (2184, 2197), True, 'import numpy as np\n'), ((1475, 1511), 'root_numpy.random_sample', 'rnp.random_sample', (['taud', '(jphoton + 1)'], {}), '(taud, jphoton + 1)\n', (1492, 1511), True, 'import root_numpy as rnp\n'), ((1517, 1572), 'scipy.stats.norm.rvs', 'stats.norm.rvs', ([], {'loc': 'Qpmt', 'scale': 'sqpmt', 'size': '(jphoton + 1)'}), '(loc=Qpmt, scale=sqpmt, size=jphoton + 1)\n', (1531, 1572), True, 'import scipy.stats as stats\n'), ((1818, 1839), 'numpy.sum', 'np.sum', (['izero'], {'axis': '(0)'}), '(izero, axis=0)\n', (1824, 1839), True, 'import numpy as np\n'), ((2479, 2523), 'numpy.loadtxt', 'np.loadtxt', (['name'], {'usecols': '(1, 3)', 'skiprows': '(2)'}), '(name, usecols=(1, 3), skiprows=2)\n', (2489, 2523), True, 'import numpy as np\n'), ((2535, 2552), 'numpy.zeros', 'np.zeros', (['(Nz, 2)'], {}), '((Nz, 2))\n', (2543, 2552), True, 'import numpy as np\n'), ((2660, 2691), 'numpy.flip', 'np.flip', (['zl_freq[1:Nhalf, 0]', '(0)'], {}), '(zl_freq[1:Nhalf, 0], 0)\n', (2667, 2691), True, 'import numpy as np\n'), ((2833, 2861), 'scipy.fftpack.fft', 'fftp.fft', (['zl_time', '(2 * R - 1)'], {}), '(zl_time, 2 * R - 1)\n', (2841, 2861), True, 'import scipy.fftpack as fftp\n'), ((2938, 2959), 'numpy.amax', 'np.amax', (['vint'], {'axis': '(1)'}), '(vint, axis=1)\n', (2945, 2959), True, 'import numpy as np\n'), ((1642, 1675), 'numpy.transpose', 'np.transpose', (['rnd_tau[np.newaxis]'], {}), '(rnd_tau[np.newaxis])\n', (1654, 1675), True, 'import numpy as np\n'), ((1686, 1718), 'numpy.transpose', 'np.transpose', (['ptimes[np.newaxis]'], {}), '(ptimes[np.newaxis])\n', (1698, 1718), True, 'import numpy as np\n'), ((2723, 2754), 'numpy.flip', 'np.flip', (['zl_freq[1:Nhalf, 1]', '(0)'], {}), '(zl_freq[1:Nhalf, 1], 0)\n', (2730, 2754), True, 'import numpy as np\n'), ((1608, 1640), 'numpy.transpose', 'np.transpose', (['ptimes[np.newaxis]'], {}), '(ptimes[np.newaxis])\n', (1620, 1640), True, 'import numpy as np\n'), ((1781, 1801), 'numpy.exp', 'np.exp', (['(-1.0 * tnorm)'], {}), '(-1.0 * tnorm)\n', (1787, 1801), True, 'import numpy as np\n'), ((2775, 2822), 'scipy.fftpack.ifft', 'fftp.ifft', (['(zl_full[:, 0] + 1.0j * zl_full[:, 1])'], {}), '(zl_full[:, 0] + 1.0j * zl_full[:, 1])\n', (2784, 2822), True, 'import scipy.fftpack as fftp\n'), ((2876, 2910), 'scipy.fftpack.ifft', 'fftp.ifft', (['(i_freq * z_conv)'], {'axis': '(1)'}), '(i_freq * z_conv, axis=1)\n', (2885, 2910), True, 'import scipy.fftpack as fftp\n'), ((1731, 1758), 'numpy.transpose', 'np.transpose', (['k[np.newaxis]'], {}), '(k[np.newaxis])\n', (1743, 1758), True, 'import numpy as np\n'), ((1759, 1781), 'numpy.power', 'np.power', (['tnorm', 'alpha'], {}), '(tnorm, alpha)\n', (1767, 1781), True, 'import numpy as np\n')]
''' Copyright 2022 Airbus SAS Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ''' from sos_trades_core.study_manager.study_manager import StudyManager from numpy import array import pandas as pd class Study(StudyManager): def __init__(self, execution_engine=None): super().__init__(__file__, execution_engine=execution_engine) def setup_usecase(self): ns = f'{self.study_name}' sc_name = "SellarDoeScenario" dspace_dict = {'variable': ['x', 'z', 'y_1', 'y_2'], 'value': [[1.], [5., 2.], [5.], [1.]], 'lower_bnd': [[0.], [-10., 0.], [-100.], [-100.]], 'upper_bnd': [[10.], [10., 10.], [100.], [100.]], 'enable_variable': [True, True, True, True], 'activated_elem': [[True], [True, True], [True], [True]]} # 'type' : ['float',['float','float'],'float','float'] dspace = pd.DataFrame(dspace_dict) disc_dict = {} # Optim inputs disc_dict[f'{ns}.SellarDoeScenario.n_samples'] = 100 # SLSQP, NLOPT_SLSQP disc_dict[f'{ns}.SellarDoeScenario.algo'] = "lhs" disc_dict[f'{ns}.SellarDoeScenario.design_space'] = dspace # TODO: what's wrong with IDF disc_dict[f'{ns}.SellarDoeScenario.formulation'] = 'MDF' # f'{ns}.SellarDoeScenario.obj' disc_dict[f'{ns}.SellarDoeScenario.objective_name'] = 'obj' # disc_dict[f'{ns}.SellarDoeScenario.ineq_constraints'] = ['c_1', 'c_2'] # TBC_DM # f'{ns}.SellarDoeScenario.c_1', f'{ns}.SellarDoeScenario.c_2'] disc_dict[f'{ns}.SellarDoeScenario.algo_options'] = {"ftol_rel": 1e-10, "ineq_tolerance": 2e-3, "normalize_design_space": False} # Sellar inputs disc_dict[f'{ns}.{sc_name}.x'] = 1. # array([1.]) disc_dict[f'{ns}.{sc_name}.y_1'] = array([1.]) disc_dict[f'{ns}.{sc_name}.y_2'] = array([1.]) disc_dict[f'{ns}.{sc_name}.z'] = array([1., 1.]) disc_dict[f'{ns}.{sc_name}.Sellar_Problem.local_dv'] = 10. return [disc_dict] if '__main__' == __name__: uc_cls = Study() uc_cls.load_data() uc_cls.execution_engine.display_treeview_nodes(display_variables=True) uc_cls.run()
[ "pandas.DataFrame", "numpy.array" ]
[((1438, 1463), 'pandas.DataFrame', 'pd.DataFrame', (['dspace_dict'], {}), '(dspace_dict)\n', (1450, 1463), True, 'import pandas as pd\n'), ((2486, 2498), 'numpy.array', 'array', (['[1.0]'], {}), '([1.0])\n', (2491, 2498), False, 'from numpy import array\n'), ((2541, 2553), 'numpy.array', 'array', (['[1.0]'], {}), '([1.0])\n', (2546, 2553), False, 'from numpy import array\n'), ((2594, 2611), 'numpy.array', 'array', (['[1.0, 1.0]'], {}), '([1.0, 1.0])\n', (2599, 2611), False, 'from numpy import array\n')]
""" Script to convert Qualtrics results to more manageable format. Author: XXXXX Usage: python convert_data.py Required files: - writtendescriptions.csv - list_mapping.csv Generates: - written_annotations.json - written_plain.txt - duration_stats.json """ # Stdlib import csv import json import os from collections import defaultdict # Installe: from numpy import std, median, mean def get_entries(filename): "Load the entries from the file, representing each participant as a dictionary." with open(filename, encoding='cp1252') as f: reader = csv.reader(f) keys = next(reader) # Skip next two lines. for i in range(2): next(reader) entries = [dict(zip(keys,row)) for row in reader] return entries def duration_statistics(entries): "Generate duration statistics." durations = [int(entry['Duration (in seconds)']) for entry in entries] return dict(mean_seconds=mean(durations), median_seconds=median(durations), std_seconds=std(durations), min_seconds=min(durations), max_seconds=max(durations), mean_minutes=mean(durations)/60, median_minutes=median(durations)/60, std_minutes=std(durations)/60, min_minutes=min(durations)/60, max_minutes=max(durations)/60, durations=durations) def load_mappings(filename): "Load mappings from file." with open(filename) as f: reader = csv.reader(f,delimiter=';') header = next(reader) question_to_image = dict() image_to_partition = dict() for image, question, partition in reader: question_to_image[question] = image image_to_partition[image] = partition return question_to_image, image_to_partition def write_json(object,filename): "Write JSON to a file." with open(filename,'w') as f: json.dump(object, f, indent=4) def get_items(entries): "Get basic items (to be enriched later)." items = [] for i, entry in enumerate(entries, start=1000): response_id = entry['ResponseId'] for key, value in entry.items(): if key == 'Q319': # Practice question: Ignore. continue elif key.startswith('Q') and value: item = dict(participant=i, description=value.strip(), question=key, response_id=response_id) items.append(item) return items def enrich_items(items, question2img, img2part): "Enrich items with information about their partition and the image." for item in items: question = item['question'] image = question2img[question] partition = img2part[image] item['image'] = image item['partition'] = partition # This function modifies the list in place, so it returns nothing. return None def participant_index(items): "Build an index: identifier -> descriptions" description_index = defaultdict(list) image_index = defaultdict(list) for item in items: participant = item['participant'] description = item['description'] + '\n' image = item['image'] description_index[participant].append(description) image_index[participant].append(image) return description_index, image_index def extract_lines(items): "Extract lines to create a plaintext corpus." lines = [item['description'] + '\n' for item in items] return lines def ensure_folder(folder_name): "Make sure a folder exists. If not, create it." if not os.path.exists(folder_name): os.mkdir(folder_name) def create_participant_files(items, folder='Participants/Plain/'): "Create files with descriptions per participant." description_index, image_index = participant_index(items) ensure_folder(folder) for participant, lines in description_index.items(): with open(folder + str(participant) + '.txt', 'w') as f: f.writelines(lines) with open(folder + 'participant_lines_image_mapping.json', 'w') as f: json.dump(image_index, f, indent=2) if __name__ == "__main__": entries = get_entries('./writtendescriptions.csv') items = get_items(entries) question_to_image, image_to_partition = load_mappings('./list_mapping.csv') enrich_items(items, question_to_image, image_to_partition) write_json(items, 'written_annotations.json') lines = extract_lines(items) with open('written_plain.txt','w') as f: f.writelines(lines) create_participant_files(items) duration_stats = duration_statistics(entries) write_json(duration_stats,"duration_stats.json")
[ "os.path.exists", "numpy.mean", "numpy.median", "collections.defaultdict", "os.mkdir", "numpy.std", "csv.reader", "json.dump" ]
[((3127, 3144), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (3138, 3144), False, 'from collections import defaultdict\n'), ((3163, 3180), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (3174, 3180), False, 'from collections import defaultdict\n'), ((566, 579), 'csv.reader', 'csv.reader', (['f'], {}), '(f)\n', (576, 579), False, 'import csv\n'), ((1532, 1560), 'csv.reader', 'csv.reader', (['f'], {'delimiter': '""";"""'}), "(f, delimiter=';')\n", (1542, 1560), False, 'import csv\n'), ((1963, 1993), 'json.dump', 'json.dump', (['object', 'f'], {'indent': '(4)'}), '(object, f, indent=4)\n', (1972, 1993), False, 'import json\n'), ((3724, 3751), 'os.path.exists', 'os.path.exists', (['folder_name'], {}), '(folder_name)\n', (3738, 3751), False, 'import os\n'), ((3761, 3782), 'os.mkdir', 'os.mkdir', (['folder_name'], {}), '(folder_name)\n', (3769, 3782), False, 'import os\n'), ((4231, 4266), 'json.dump', 'json.dump', (['image_index', 'f'], {'indent': '(2)'}), '(image_index, f, indent=2)\n', (4240, 4266), False, 'import json\n'), ((944, 959), 'numpy.mean', 'mean', (['durations'], {}), '(durations)\n', (948, 959), False, 'from numpy import std, median, mean\n'), ((992, 1009), 'numpy.median', 'median', (['durations'], {}), '(durations)\n', (998, 1009), False, 'from numpy import std, median, mean\n'), ((1039, 1053), 'numpy.std', 'std', (['durations'], {}), '(durations)\n', (1042, 1053), False, 'from numpy import std, median, mean\n'), ((1172, 1187), 'numpy.mean', 'mean', (['durations'], {}), '(durations)\n', (1176, 1187), False, 'from numpy import std, median, mean\n'), ((1223, 1240), 'numpy.median', 'median', (['durations'], {}), '(durations)\n', (1229, 1240), False, 'from numpy import std, median, mean\n'), ((1273, 1287), 'numpy.std', 'std', (['durations'], {}), '(durations)\n', (1276, 1287), False, 'from numpy import std, median, mean\n')]
import numpy as np import torch from timm.models.layers import trunc_normal_ from torch import nn as nn from everything_at_once.model.utils.utils import normalize_embeddings from everything_at_once.model.utils.layers import get_projection from everything_at_once.model.utils.fusion_transformer import FusionTransformer from everything_at_once.model.utils.davenet import load_DAVEnet class EverythingAtOnceModel(nn.Module): def __init__(self, video_embed_dim, text_embed_dim, fusion_params, video_max_tokens=None, text_max_tokens=None, audio_max_num_STFT_frames=None, projection_dim=6144, token_projection='gated', projection='gated', cross_modal=True, strategy_audio_pooling='none', davenet_v2=True, individual_projections=True, use_positional_emb=False, ): super().__init__() self.fusion = FusionTransformer(**fusion_params) self.individual_projections = individual_projections self.use_positional_emb = use_positional_emb self.strategy_audio_pooling = strategy_audio_pooling self.cross_modal = cross_modal embed_dim = fusion_params['embed_dim'] self.video_norm_layer = nn.LayerNorm(embed_dim, eps=1e-6) self.text_norm_layer = nn.LayerNorm(embed_dim, eps=1e-6) self.audio_norm_layer = nn.LayerNorm(embed_dim, eps=1e-6) # audio token preprocess self.davenet = load_DAVEnet(v2=davenet_v2) if audio_max_num_STFT_frames is not None: if davenet_v2: audio_max_tokens = int(audio_max_num_STFT_frames / 64) else: audio_max_tokens = int(audio_max_num_STFT_frames / 16) self.audio_max_tokens = audio_max_tokens else: self.audio_max_tokens = None if self.use_positional_emb: assert video_max_tokens is not None assert text_max_tokens is not None assert audio_max_num_STFT_frames is not None self.video_pos_embed = nn.Parameter(torch.zeros(1, video_max_tokens, embed_dim)) self.text_pos_embed = nn.Parameter(torch.zeros(1, text_max_tokens, embed_dim)) self.audio_pos_embed = nn.Parameter(torch.zeros(1, self.audio_max_tokens, embed_dim)) else: self.video_pos_embed = None self.text_pos_embed = None self.audio_pos_embed = None audio_embed_dim = 4096 if davenet_v2 else 1024 self.video_token_proj = get_projection(video_embed_dim, embed_dim, token_projection) self.text_token_proj = get_projection(text_embed_dim, embed_dim, token_projection) self.audio_token_proj = get_projection(audio_embed_dim, embed_dim, token_projection) if not self.individual_projections: self.proj = get_projection(embed_dim, projection_dim, projection) else: self.video_proj = get_projection(embed_dim, projection_dim, projection) self.text_proj = get_projection(embed_dim, projection_dim, projection) self.audio_proj = get_projection(embed_dim, projection_dim, projection) self.init_weights() def init_weights(self): for weights in [self.video_pos_embed, self.audio_pos_embed, self.text_pos_embed]: if weights is not None: trunc_normal_(weights, std=.02) def _check_and_fix_if_input_empty(self, x, attention_mask): nonempty_input_mask = attention_mask.sum(-1) != 0 # if all tokens of modality is empty, add one masking token empty_input_mask = nonempty_input_mask == 0 n_masking_tokens = 1 x[empty_input_mask, :n_masking_tokens] = self.fusion.masking_token.type(x.dtype) attention_mask[empty_input_mask, :n_masking_tokens] = 1 return x, attention_mask, nonempty_input_mask def extract_video_tokens(self, video, attention_mask): x = self.video_token_proj(video) x = self.video_norm_layer(x) x, attention_mask, nonempty_input_mask = self._check_and_fix_if_input_empty(x, attention_mask) special_token_mask = attention_mask == 0 return {'all_tokens': x, 'attention_mask': attention_mask, 'special_token_mask': special_token_mask, 'nonempty_input_mask': nonempty_input_mask} def extract_audio_tokens(self, audio, attention_mask, audio_STFT_nframes): audio = self.davenet(audio) audio = audio.permute(0, 2, 1) coef = int(np.ceil(attention_mask.shape[1] / audio.shape[1])) attention_mask = torch.nn.functional.max_pool1d(attention_mask.unsqueeze(0), kernel_size=coef).squeeze(0) audio_STFT_nframes = (audio_STFT_nframes / coef).int() if (self.audio_max_tokens is not None) and (audio.shape[1] > self.audio_max_tokens): new_audio, new_audio_mask = [], [] for i in range(len(audio)): cur_audio, cur_audio_mask = create_audio_tokens( audio[i], attention_mask[i], audio_STFT_nframes[i], self.audio_max_tokens, strategy=self.strategy_audio_pooling) new_audio.append(cur_audio) new_audio_mask.append(cur_audio_mask) audio = torch.stack(new_audio, dim=0) attention_mask = torch.stack(new_audio_mask, dim=0) audio = self.audio_token_proj(audio) audio = self.audio_norm_layer(audio) audio, attention_mask, nonempty_input_mask = self._check_and_fix_if_input_empty(audio, attention_mask) special_token_mask = attention_mask == 0 return {'all_tokens': audio, 'attention_mask': attention_mask, 'special_token_mask': special_token_mask, 'nonempty_input_mask': nonempty_input_mask} def extract_text_tokens(self, text, attention_mask): x = self.text_token_proj(text) x = self.text_norm_layer(x) x, attention_mask, nonempty_input_mask = self._check_and_fix_if_input_empty(x, attention_mask) special_token_mask = attention_mask == 0 return {'all_tokens': x, 'attention_mask': attention_mask, 'special_token_mask': special_token_mask, 'nonempty_input_mask': nonempty_input_mask} def forward(self, data, force_cross_modal=False): output = {} text_raw_embed = self.extract_text_tokens(data['text'], data['text_mask']) video_raw_embed = self.extract_video_tokens(data['video'], data['video_mask']) audio_raw_embed = self.extract_audio_tokens(data['audio'], data['audio_mask'], data['audio_STFT_nframes']) output['text_nonempty_input_mask'] = text_raw_embed['nonempty_input_mask'] output['video_nonempty_input_mask'] = video_raw_embed['nonempty_input_mask'] output['audio_nonempty_input_mask'] = audio_raw_embed['nonempty_input_mask'] # add positional embedding after masking if self.use_positional_emb: text_raw_embed['all_tokens'] = text_raw_embed['all_tokens'] + self.text_pos_embed video_raw_embed['all_tokens'] = video_raw_embed['all_tokens'] + self.video_pos_embed audio_raw_embed['all_tokens'] = audio_raw_embed['all_tokens'] + self.audio_pos_embed text = self.fusion(text=text_raw_embed)['text'] video = self.fusion(video=video_raw_embed)['video'] audio = self.fusion(audio=audio_raw_embed)['audio'] if self.individual_projections: text_proj, video_proj, audio_proj = self.text_proj, self.video_proj, self.audio_proj else: text_proj, video_proj, audio_proj = self.proj, self.proj, self.proj output["text_embed"] = text_proj(text['embed']) output["video_embed"] = video_proj(video['embed']) output["audio_embed"] = audio_proj(audio['embed']) if self.cross_modal or force_cross_modal: tv = self.fusion(text=text_raw_embed, video=video_raw_embed) ta = self.fusion(text=text_raw_embed, audio=audio_raw_embed) va = self.fusion(video=video_raw_embed, audio=audio_raw_embed) if self.fusion.cls_token is not None: assert not self.individual_projections output["tv_embed"] = self.proj(tv['text_video']['embed']) output["ta_embed"] = self.proj(ta['text_audio']['embed']) output["va_embed"] = self.proj(va['video_audio']['embed']) else: output["tv_embed"] = (normalize_embeddings(text_proj(tv['text']['embed'])) + normalize_embeddings(video_proj(tv['video']['embed']))) / 2 output["ta_embed"] = (normalize_embeddings(text_proj(ta['text']['embed'])) + normalize_embeddings(audio_proj(ta['audio']['embed']))) / 2 output["va_embed"] = (normalize_embeddings(video_proj(va['video']['embed'])) + normalize_embeddings(audio_proj(va['audio']['embed']))) / 2 if force_cross_modal: # needed for ablation output["t+v_embed"] = (normalize_embeddings(output["text_embed"]) + normalize_embeddings(output["video_embed"])) / 2 output["t+a_embed"] = (normalize_embeddings(output["text_embed"]) + normalize_embeddings(output["audio_embed"])) / 2 output["v+a_embed"] = (normalize_embeddings(output["video_embed"]) + normalize_embeddings(output["audio_embed"])) / 2 return output class EverythingAtOnceModel_TV_Only(EverythingAtOnceModel): def forward(self, data, force_cross_modal=False): output = {} text_raw_embed = self.extract_text_tokens(data['text'], data['text_mask']) video_raw_embed = self.extract_video_tokens(data['video'], data['video_mask']) audio_raw_embed = self.extract_audio_tokens(data['audio'], data['audio_mask'], data['audio_STFT_nframes']) output['text_nonempty_input_mask'] = text_raw_embed['nonempty_input_mask'] output['video_nonempty_input_mask'] = video_raw_embed['nonempty_input_mask'] output['audio_nonempty_input_mask'] = audio_raw_embed['nonempty_input_mask'] # add positional embedding after masking if self.use_positional_emb: text_raw_embed['all_tokens'] = text_raw_embed['all_tokens'] + self.text_pos_embed video_raw_embed['all_tokens'] = video_raw_embed['all_tokens'] + self.video_pos_embed text = self.fusion(text=text_raw_embed)['text'] video = self.fusion(video=video_raw_embed)['video'] if not self.individual_projections: output["text_embed"] = self.proj(text['embed']) output["video_embed"] = self.proj(video['embed']) else: output["text_embed"] = self.text_proj(text['embed']) output["video_embed"] = self.video_proj(video['embed']) return output class TransformerPerModalityModel(EverythingAtOnceModel): def __init__(self, video_embed_dim, text_embed_dim, fusion_params, video_max_tokens=None, text_max_tokens=None, audio_max_num_STFT_frames=None, projection_dim=6144, token_projection='gated', projection='gated', strategy_audio_pooling='none', davenet_v2=True, use_positional_emb=False, ): super().__init__(video_embed_dim, text_embed_dim, fusion_params, video_max_tokens=video_max_tokens, text_max_tokens=text_max_tokens, audio_max_num_STFT_frames=audio_max_num_STFT_frames, projection_dim=projection_dim, token_projection=token_projection, projection=projection, cross_modal=False, strategy_audio_pooling=strategy_audio_pooling, davenet_v2=davenet_v2, individual_projections=True, use_positional_emb=use_positional_emb, ) self.fusion_text = self.fusion self.fusion_video = FusionTransformer(**fusion_params) self.fusion_audio = FusionTransformer(**fusion_params) def forward(self, data, force_cross_modal=False): output = {} text_raw_embed = self.extract_text_tokens(data['text'], data['text_mask']) video_raw_embed = self.extract_video_tokens(data['video'], data['video_mask']) audio_raw_embed = self.extract_audio_tokens(data['audio'], data['audio_mask'], data['audio_STFT_nframes']) output['text_nonempty_input_mask'] = text_raw_embed['nonempty_input_mask'] output['video_nonempty_input_mask'] = video_raw_embed['nonempty_input_mask'] output['audio_nonempty_input_mask'] = audio_raw_embed['nonempty_input_mask'] text = self.fusion_text(text=text_raw_embed)['text'] output["text_embed"] = self.text_proj(text['embed']) video = self.fusion_video(video=video_raw_embed)['video'] output["video_embed"] = self.video_proj(video['embed']) audio = self.fusion_audio(audio=audio_raw_embed)['audio'] output["audio_embed"] = self.audio_proj(audio['embed']) if force_cross_modal: # needed for ablation output["t+v_embed"] = (normalize_embeddings(output["text_embed"]) + normalize_embeddings(output["video_embed"])) / 2 output["t+a_embed"] = (normalize_embeddings(output["text_embed"]) + normalize_embeddings(output["audio_embed"])) / 2 output["v+a_embed"] = (normalize_embeddings(output["video_embed"]) + normalize_embeddings(output["audio_embed"])) / 2 return output def create_audio_tokens(audio, audio_mask, audio_STFT_nframes, n_tokens, strategy='avg_pool'): if torch.is_tensor(audio_STFT_nframes): audio_STFT_nframes = int(audio_STFT_nframes.cpu().item()) if strategy == 'clip': return audio[:n_tokens], audio_mask[:n_tokens] elif strategy == 'nearest': if audio_STFT_nframes <= n_tokens: return create_audio_tokens(audio, audio_mask, audio_STFT_nframes, n_tokens, strategy='clip') audio = audio[:audio_STFT_nframes] audio = torch.nn.functional.interpolate( audio.permute(1, 0).unsqueeze(0), size=n_tokens, mode='nearest').squeeze(0).permute(1, 0) return audio, audio_mask[:n_tokens] elif strategy == 'max_pool': if audio_STFT_nframes <= n_tokens: return create_audio_tokens(audio, audio_mask, audio_STFT_nframes, n_tokens, strategy='clip') audio = audio[:audio_STFT_nframes] audio = torch.nn.functional.adaptive_max_pool1d( audio.permute(1, 0).unsqueeze(0), output_size=n_tokens).squeeze(0).permute(1, 0) return audio, audio_mask[:n_tokens] elif strategy == 'avg_pool': if audio_STFT_nframes <= n_tokens: return create_audio_tokens(audio, audio_mask, audio_STFT_nframes, n_tokens, strategy='clip') audio = audio[:audio_STFT_nframes] audio = torch.nn.functional.adaptive_avg_pool1d( audio.permute(1, 0).unsqueeze(0), output_size=n_tokens).squeeze(0).permute(1, 0) return audio, audio_mask[:n_tokens] elif strategy == 'none': return audio, audio_mask else: raise NotImplementedError
[ "numpy.ceil", "timm.models.layers.trunc_normal_", "everything_at_once.model.utils.utils.normalize_embeddings", "torch.nn.LayerNorm", "torch.stack", "everything_at_once.model.utils.davenet.load_DAVEnet", "everything_at_once.model.utils.fusion_transformer.FusionTransformer", "torch.is_tensor", "everyt...
[((14436, 14471), 'torch.is_tensor', 'torch.is_tensor', (['audio_STFT_nframes'], {}), '(audio_STFT_nframes)\n', (14451, 14471), False, 'import torch\n'), ((1070, 1104), 'everything_at_once.model.utils.fusion_transformer.FusionTransformer', 'FusionTransformer', ([], {}), '(**fusion_params)\n', (1087, 1104), False, 'from everything_at_once.model.utils.fusion_transformer import FusionTransformer\n'), ((1401, 1435), 'torch.nn.LayerNorm', 'nn.LayerNorm', (['embed_dim'], {'eps': '(1e-06)'}), '(embed_dim, eps=1e-06)\n', (1413, 1435), True, 'from torch import nn as nn\n'), ((1466, 1500), 'torch.nn.LayerNorm', 'nn.LayerNorm', (['embed_dim'], {'eps': '(1e-06)'}), '(embed_dim, eps=1e-06)\n', (1478, 1500), True, 'from torch import nn as nn\n'), ((1532, 1566), 'torch.nn.LayerNorm', 'nn.LayerNorm', (['embed_dim'], {'eps': '(1e-06)'}), '(embed_dim, eps=1e-06)\n', (1544, 1566), True, 'from torch import nn as nn\n'), ((1623, 1650), 'everything_at_once.model.utils.davenet.load_DAVEnet', 'load_DAVEnet', ([], {'v2': 'davenet_v2'}), '(v2=davenet_v2)\n', (1635, 1650), False, 'from everything_at_once.model.utils.davenet import load_DAVEnet\n'), ((2689, 2749), 'everything_at_once.model.utils.layers.get_projection', 'get_projection', (['video_embed_dim', 'embed_dim', 'token_projection'], {}), '(video_embed_dim, embed_dim, token_projection)\n', (2703, 2749), False, 'from everything_at_once.model.utils.layers import get_projection\n'), ((2781, 2840), 'everything_at_once.model.utils.layers.get_projection', 'get_projection', (['text_embed_dim', 'embed_dim', 'token_projection'], {}), '(text_embed_dim, embed_dim, token_projection)\n', (2795, 2840), False, 'from everything_at_once.model.utils.layers import get_projection\n'), ((2873, 2933), 'everything_at_once.model.utils.layers.get_projection', 'get_projection', (['audio_embed_dim', 'embed_dim', 'token_projection'], {}), '(audio_embed_dim, embed_dim, token_projection)\n', (2887, 2933), False, 'from everything_at_once.model.utils.layers import get_projection\n'), ((12652, 12686), 'everything_at_once.model.utils.fusion_transformer.FusionTransformer', 'FusionTransformer', ([], {}), '(**fusion_params)\n', (12669, 12686), False, 'from everything_at_once.model.utils.fusion_transformer import FusionTransformer\n'), ((12715, 12749), 'everything_at_once.model.utils.fusion_transformer.FusionTransformer', 'FusionTransformer', ([], {}), '(**fusion_params)\n', (12732, 12749), False, 'from everything_at_once.model.utils.fusion_transformer import FusionTransformer\n'), ((3011, 3064), 'everything_at_once.model.utils.layers.get_projection', 'get_projection', (['embed_dim', 'projection_dim', 'projection'], {}), '(embed_dim, projection_dim, projection)\n', (3025, 3064), False, 'from everything_at_once.model.utils.layers import get_projection\n'), ((3109, 3162), 'everything_at_once.model.utils.layers.get_projection', 'get_projection', (['embed_dim', 'projection_dim', 'projection'], {}), '(embed_dim, projection_dim, projection)\n', (3123, 3162), False, 'from everything_at_once.model.utils.layers import get_projection\n'), ((3192, 3245), 'everything_at_once.model.utils.layers.get_projection', 'get_projection', (['embed_dim', 'projection_dim', 'projection'], {}), '(embed_dim, projection_dim, projection)\n', (3206, 3245), False, 'from everything_at_once.model.utils.layers import get_projection\n'), ((3276, 3329), 'everything_at_once.model.utils.layers.get_projection', 'get_projection', (['embed_dim', 'projection_dim', 'projection'], {}), '(embed_dim, projection_dim, projection)\n', (3290, 3329), False, 'from everything_at_once.model.utils.layers import get_projection\n'), ((4678, 4727), 'numpy.ceil', 'np.ceil', (['(attention_mask.shape[1] / audio.shape[1])'], {}), '(attention_mask.shape[1] / audio.shape[1])\n', (4685, 4727), True, 'import numpy as np\n'), ((5403, 5432), 'torch.stack', 'torch.stack', (['new_audio'], {'dim': '(0)'}), '(new_audio, dim=0)\n', (5414, 5432), False, 'import torch\n'), ((5462, 5496), 'torch.stack', 'torch.stack', (['new_audio_mask'], {'dim': '(0)'}), '(new_audio_mask, dim=0)\n', (5473, 5496), False, 'import torch\n'), ((2234, 2277), 'torch.zeros', 'torch.zeros', (['(1)', 'video_max_tokens', 'embed_dim'], {}), '(1, video_max_tokens, embed_dim)\n', (2245, 2277), False, 'import torch\n'), ((2326, 2368), 'torch.zeros', 'torch.zeros', (['(1)', 'text_max_tokens', 'embed_dim'], {}), '(1, text_max_tokens, embed_dim)\n', (2337, 2368), False, 'import torch\n'), ((2418, 2466), 'torch.zeros', 'torch.zeros', (['(1)', 'self.audio_max_tokens', 'embed_dim'], {}), '(1, self.audio_max_tokens, embed_dim)\n', (2429, 2466), False, 'import torch\n'), ((3530, 3562), 'timm.models.layers.trunc_normal_', 'trunc_normal_', (['weights'], {'std': '(0.02)'}), '(weights, std=0.02)\n', (3543, 3562), False, 'from timm.models.layers import trunc_normal_\n'), ((9333, 9375), 'everything_at_once.model.utils.utils.normalize_embeddings', 'normalize_embeddings', (["output['text_embed']"], {}), "(output['text_embed'])\n", (9353, 9375), False, 'from everything_at_once.model.utils.utils import normalize_embeddings\n'), ((9413, 9456), 'everything_at_once.model.utils.utils.normalize_embeddings', 'normalize_embeddings', (["output['video_embed']"], {}), "(output['video_embed'])\n", (9433, 9456), False, 'from everything_at_once.model.utils.utils import normalize_embeddings\n'), ((9497, 9539), 'everything_at_once.model.utils.utils.normalize_embeddings', 'normalize_embeddings', (["output['text_embed']"], {}), "(output['text_embed'])\n", (9517, 9539), False, 'from everything_at_once.model.utils.utils import normalize_embeddings\n'), ((9577, 9620), 'everything_at_once.model.utils.utils.normalize_embeddings', 'normalize_embeddings', (["output['audio_embed']"], {}), "(output['audio_embed'])\n", (9597, 9620), False, 'from everything_at_once.model.utils.utils import normalize_embeddings\n'), ((9661, 9704), 'everything_at_once.model.utils.utils.normalize_embeddings', 'normalize_embeddings', (["output['video_embed']"], {}), "(output['video_embed'])\n", (9681, 9704), False, 'from everything_at_once.model.utils.utils import normalize_embeddings\n'), ((9742, 9785), 'everything_at_once.model.utils.utils.normalize_embeddings', 'normalize_embeddings', (["output['audio_embed']"], {}), "(output['audio_embed'])\n", (9762, 9785), False, 'from everything_at_once.model.utils.utils import normalize_embeddings\n'), ((13851, 13893), 'everything_at_once.model.utils.utils.normalize_embeddings', 'normalize_embeddings', (["output['text_embed']"], {}), "(output['text_embed'])\n", (13871, 13893), False, 'from everything_at_once.model.utils.utils import normalize_embeddings\n'), ((13931, 13974), 'everything_at_once.model.utils.utils.normalize_embeddings', 'normalize_embeddings', (["output['video_embed']"], {}), "(output['video_embed'])\n", (13951, 13974), False, 'from everything_at_once.model.utils.utils import normalize_embeddings\n'), ((14015, 14057), 'everything_at_once.model.utils.utils.normalize_embeddings', 'normalize_embeddings', (["output['text_embed']"], {}), "(output['text_embed'])\n", (14035, 14057), False, 'from everything_at_once.model.utils.utils import normalize_embeddings\n'), ((14095, 14138), 'everything_at_once.model.utils.utils.normalize_embeddings', 'normalize_embeddings', (["output['audio_embed']"], {}), "(output['audio_embed'])\n", (14115, 14138), False, 'from everything_at_once.model.utils.utils import normalize_embeddings\n'), ((14179, 14222), 'everything_at_once.model.utils.utils.normalize_embeddings', 'normalize_embeddings', (["output['video_embed']"], {}), "(output['video_embed'])\n", (14199, 14222), False, 'from everything_at_once.model.utils.utils import normalize_embeddings\n'), ((14260, 14303), 'everything_at_once.model.utils.utils.normalize_embeddings', 'normalize_embeddings', (["output['audio_embed']"], {}), "(output['audio_embed'])\n", (14280, 14303), False, 'from everything_at_once.model.utils.utils import normalize_embeddings\n')]
import h5py import numpy as np import xarray as xr from pathlib import Path import brainio_collection from brainio_base.assemblies import NeuronRecordingAssembly from brainio_contrib.packaging import package_data_assembly from mkgu_packaging.dicarlo.kar2018 import filter_neuroids def load_responses(response_file, additional_coords): responses = h5py.File(response_file, 'r') assemblies = [] neuroid_id_offset = 0 for monkey in responses.keys(): spike_rates = responses[monkey]['rates'] assembly = xr.DataArray(spike_rates.value, coords={**{ 'image_num': ('image_id', list(range(spike_rates.shape[0]))), 'neuroid_id': ('neuroid', list( range(neuroid_id_offset, neuroid_id_offset + spike_rates.shape[1]))), 'region': ('neuroid', ['IT'] * spike_rates.shape[1]), 'monkey': ('neuroid', [monkey] * spike_rates.shape[1]), 'repetition': list(range(spike_rates.shape[2])), }, **additional_coords}, dims=['image_id', 'neuroid', 'repetition']) assemblies.append(assembly) neuroid_id_offset += spike_rates.shape[1] assembly = xr.concat(assemblies, 'neuroid') assembly = assembly.stack(presentation=['image_id', 'repetition']) assembly = NeuronRecordingAssembly(assembly) assert len(assembly['presentation']) == 640 * 63 assert len(np.unique(assembly['image_id'])) == 640 assert len(assembly.sel(monkey='nano')['neuroid']) == len(assembly.sel(monkey='magneto')['neuroid']) == 288 assert len(assembly['neuroid']) == len(np.unique(assembly['neuroid_id'])) == 288 * 2 # filter noisy electrodes assembly = filter_neuroids(assembly, threshold=.7) # add time info assembly = assembly.expand_dims('time_bin') assembly['time_bin_start'] = 'time_bin', [70] assembly['time_bin_end'] = 'time_bin', [170] assembly = assembly.transpose('presentation', 'neuroid', 'time_bin') return assembly def load_stimuli_ids(data_dir): # these stimuli_ids are SHA1 hashes on generative parameters stimuli_ids = h5py.File(data_dir / 'hvm640_ids.mat', 'r') stimuli_ids = [''.join(chr(c) for c in stimuli_ids[stimuli_ids['hvm640_ids'].value[0, i]]) for i in range(stimuli_ids['hvm640_ids'].value[0].size)] # we use the filenames to reference into our packaged StimulusSet ids stimuli_filenames = h5py.File(data_dir / 'hvm640_names.mat', 'r') stimuli_filenames = [''.join(chr(c) for c in stimuli_filenames[stimuli_filenames['hvm640_img_names'].value[0, i]]) for i in range(stimuli_filenames['hvm640_img_names'].value[0].size)] # the stimuli_ids in our packaged StimulusSets are SHA1 hashes on pixels. # we thus need to reference between those two ids. packaged_stimuli = brainio_collection.get_stimulus_set('dicarlo.hvm') reference_table = {row.image_file_name: row.image_id for row in packaged_stimuli.itertuples()} referenced_ids = [reference_table[filename] for filename in stimuli_filenames] return {'image_id': ('image_id', referenced_ids), 'image_generative_id': ('image_id', stimuli_ids)} def main(): data_dir = Path(__file__).parent / 'hvm' stimuli_ids = load_stimuli_ids(data_dir) assembly = load_responses(data_dir / 'hvm640_neural.h5', additional_coords=stimuli_ids) assembly.name = 'dicarlo.Kar2018hvm' package_data_assembly(assembly, data_assembly_name=assembly.name, stimulus_set_name='dicarlo.hvm', bucket_name='brainio-dicarlo') if __name__ == '__main__': main()
[ "numpy.unique", "pathlib.Path", "brainio_collection.get_stimulus_set", "h5py.File", "xarray.concat", "brainio_base.assemblies.NeuronRecordingAssembly", "brainio_contrib.packaging.package_data_assembly", "mkgu_packaging.dicarlo.kar2018.filter_neuroids" ]
[((354, 383), 'h5py.File', 'h5py.File', (['response_file', '"""r"""'], {}), "(response_file, 'r')\n", (363, 383), False, 'import h5py\n'), ((1387, 1419), 'xarray.concat', 'xr.concat', (['assemblies', '"""neuroid"""'], {}), "(assemblies, 'neuroid')\n", (1396, 1419), True, 'import xarray as xr\n'), ((1506, 1539), 'brainio_base.assemblies.NeuronRecordingAssembly', 'NeuronRecordingAssembly', (['assembly'], {}), '(assembly)\n', (1529, 1539), False, 'from brainio_base.assemblies import NeuronRecordingAssembly\n'), ((1894, 1934), 'mkgu_packaging.dicarlo.kar2018.filter_neuroids', 'filter_neuroids', (['assembly'], {'threshold': '(0.7)'}), '(assembly, threshold=0.7)\n', (1909, 1934), False, 'from mkgu_packaging.dicarlo.kar2018 import filter_neuroids\n'), ((2311, 2354), 'h5py.File', 'h5py.File', (["(data_dir / 'hvm640_ids.mat')", '"""r"""'], {}), "(data_dir / 'hvm640_ids.mat', 'r')\n", (2320, 2354), False, 'import h5py\n'), ((2624, 2669), 'h5py.File', 'h5py.File', (["(data_dir / 'hvm640_names.mat')", '"""r"""'], {}), "(data_dir / 'hvm640_names.mat', 'r')\n", (2633, 2669), False, 'import h5py\n'), ((3039, 3089), 'brainio_collection.get_stimulus_set', 'brainio_collection.get_stimulus_set', (['"""dicarlo.hvm"""'], {}), "('dicarlo.hvm')\n", (3074, 3089), False, 'import brainio_collection\n'), ((3631, 3764), 'brainio_contrib.packaging.package_data_assembly', 'package_data_assembly', (['assembly'], {'data_assembly_name': 'assembly.name', 'stimulus_set_name': '"""dicarlo.hvm"""', 'bucket_name': '"""brainio-dicarlo"""'}), "(assembly, data_assembly_name=assembly.name,\n stimulus_set_name='dicarlo.hvm', bucket_name='brainio-dicarlo')\n", (3652, 3764), False, 'from brainio_contrib.packaging import package_data_assembly\n'), ((1608, 1639), 'numpy.unique', 'np.unique', (["assembly['image_id']"], {}), "(assembly['image_id'])\n", (1617, 1639), True, 'import numpy as np\n'), ((1803, 1836), 'numpy.unique', 'np.unique', (["assembly['neuroid_id']"], {}), "(assembly['neuroid_id'])\n", (1812, 1836), True, 'import numpy as np\n'), ((3417, 3431), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (3421, 3431), False, 'from pathlib import Path\n')]
# Copyright (c) 2019 Capital Fund Management # SPDX-License-Identifier: MIT import numpy as np import pandas as pd import json from timeit import default_timer as timer import jupytab def test_data_schema(): arrays = [ ['A', 'A', 'a', 'a', 0, 0, 'a$_!#àz', 'a$_!#àz' ], ['A', 'A', 0, 1, 'z$_"_àéça"', 'z_èà[|]a', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', 'abcdefghijklmnopqrstuvwxyz0123456789' ] ] tuples = list(zip(*arrays)) index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second']) complex_df = pd.DataFrame(np.random.randn(len(index), len(index)), index=index, columns=index) tables = jupytab.Tables() tables['complex_df_no_index_{}[]#!'] = \ jupytab.DataFrameTable('A multi-index Dataframe ({}[]#!)', dataframe=complex_df) tables['complex_df_with_index_{}[]#!'] = \ jupytab.DataFrameTable('A multi-index Dataframe ({}[]#!)', dataframe=complex_df, include_index=True) schema = tables.schema() assert schema[0]['id'] == 'complex_df_no_index_{}[]#!' assert schema[0]['alias'] == 'A multi-index Dataframe ({}[]#!)' assert schema[1]['id'] == 'complex_df_with_index_{}[]#!' assert schema[1]['alias'] == 'A multi-index Dataframe ({}[]#!)' raw_output = '[{"id": "complex_df_no_index_{}[]#!", "alias": "A multi-index Dataframe ({}[]#!' \ ')", "columns": [{"id": "A_A_1", "dataType": "float"}, {"id": "A_A_2", "dataType' \ '": "float"}, {"id": "a_0", "dataType": "float"}, {"id": "a_1", "dataType": "flo' \ 'at"}, {"id": "0_z____aeca_", "dataType": "float"}, {"id": "0_z_ea_a", "dataType' \ '": "float"}, {"id": "a___az_ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", "dataType": ' \ '"float"}, {"id": "a___az_abcdefghijklmnopqrstuvwxyz0123456789", "dataType": "fl' \ 'oat"}]}, {"id": "complex_df_with_index_{}[]#!", "alias": "A multi-index Datafra' \ 'me ({}[]#!)", "columns": [{"id": "first_", "dataType": "string"}, {"id": "secon' \ 'd_", "dataType": "string"}, {"id": "A_A_1", "dataType": "float"}, {"id": "A_A_2' \ '", "dataType": "float"}, {"id": "a_0", "dataType": "float"}, {"id": "a_1", "dat' \ 'aType": "float"}, {"id": "0_z____aeca_", "dataType": "float"}, {"id": "0_z_ea_a' \ '", "dataType": "float"}, {"id": "a___az_ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", ' \ '"dataType": "float"}, {"id": "a___az_abcdefghijklmnopqrstuvwxyz0123456789", "da' \ 'taType": "float"}]}]' raw_schema = tables.render_schema(do_print=False) assert raw_output == raw_schema def test_large_data_content(): row_count = 1000000 col_count = 10 np.random.seed(0) large_df = pd.DataFrame(np.random.randn(row_count, col_count)) tables = jupytab.Tables() tables['large_df'] = \ jupytab.DataFrameTable('A very large Dataframe', dataframe=large_df) request = json.dumps({ 'args': { 'table_name': ['large_df'], 'format': ['json'], 'from': [5100], 'to': [5102] } }) start = timer() raw_data = tables.render_data(request, do_print=False) end = timer() print(f"Elapsed time in second to retrieve one row in a large dataframe : {(end - start)} s") assert (end - start) < 0.1 print(raw_data) assert raw_data == '[{"0":0.2307805099,"1":0.7823326556,"2":0.9507107694,"3":1.4595805778,' \ '"4":0.6798091111,"5":-0.8676077457,"6":0.3908489554,"7":1.0838125793,' \ '"8":0.6227587338,"9":0.0919146565},{"0":0.6267312321,"1":0.7369835911,' \ '"2":-0.4665488934,"3":1.5379716957,"4":-1.0313145219,"5":1.0398963231,' \ '"6":0.8687854819,"7":0.2055855947,"8":-1.7716643336,"9":0.2428264886}]'
[ "timeit.default_timer", "json.dumps", "jupytab.DataFrameTable", "numpy.random.seed", "pandas.MultiIndex.from_tuples", "numpy.random.randn", "jupytab.Tables" ]
[((540, 600), 'pandas.MultiIndex.from_tuples', 'pd.MultiIndex.from_tuples', (['tuples'], {'names': "['first', 'second']"}), "(tuples, names=['first', 'second'])\n", (565, 600), True, 'import pandas as pd\n'), ((714, 730), 'jupytab.Tables', 'jupytab.Tables', ([], {}), '()\n', (728, 730), False, 'import jupytab\n'), ((784, 869), 'jupytab.DataFrameTable', 'jupytab.DataFrameTable', (['"""A multi-index Dataframe ({}[]#!)"""'], {'dataframe': 'complex_df'}), "('A multi-index Dataframe ({}[]#!)', dataframe=complex_df\n )\n", (806, 869), False, 'import jupytab\n'), ((951, 1056), 'jupytab.DataFrameTable', 'jupytab.DataFrameTable', (['"""A multi-index Dataframe ({}[]#!)"""'], {'dataframe': 'complex_df', 'include_index': '(True)'}), "('A multi-index Dataframe ({}[]#!)', dataframe=\n complex_df, include_index=True)\n", (973, 1056), False, 'import jupytab\n'), ((2928, 2945), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (2942, 2945), True, 'import numpy as np\n'), ((3027, 3043), 'jupytab.Tables', 'jupytab.Tables', ([], {}), '()\n', (3041, 3043), False, 'import jupytab\n'), ((3079, 3147), 'jupytab.DataFrameTable', 'jupytab.DataFrameTable', (['"""A very large Dataframe"""'], {'dataframe': 'large_df'}), "('A very large Dataframe', dataframe=large_df)\n", (3101, 3147), False, 'import jupytab\n'), ((3194, 3298), 'json.dumps', 'json.dumps', (["{'args': {'table_name': ['large_df'], 'format': ['json'], 'from': [5100],\n 'to': [5102]}}"], {}), "({'args': {'table_name': ['large_df'], 'format': ['json'], 'from':\n [5100], 'to': [5102]}})\n", (3204, 3298), False, 'import json\n'), ((3380, 3387), 'timeit.default_timer', 'timer', ([], {}), '()\n', (3385, 3387), True, 'from timeit import default_timer as timer\n'), ((3457, 3464), 'timeit.default_timer', 'timer', ([], {}), '()\n', (3462, 3464), True, 'from timeit import default_timer as timer\n'), ((2975, 3012), 'numpy.random.randn', 'np.random.randn', (['row_count', 'col_count'], {}), '(row_count, col_count)\n', (2990, 3012), True, 'import numpy as np\n')]
# ------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. # ------------------------------------------------------------------------------------------- """ Each optimization strategy is a whole pipeline: it loads the data, builds models, and generates new batches of experiments. Steps that are used by all of them are collected in this submodule. """ import abc import logging from pathlib import Path from typing import Dict, Optional, Tuple import numpy as np import pandas as pd from abex.dataset import Dataset from abex import transforms from abex.settings import OptimizerConfig class OptimizerBase(abc.ABC): def __init__(self, config: OptimizerConfig): """ Args: config: configuration, which should not be modified once assigned here. """ self.config = config.copy(deep=True) # Each subclass of OptimizerBase should have a distinct non-None value for this attribute, which should # be the value of one of the members of OptimizationStrategy. strategy_name: Optional[str] = None @abc.abstractmethod def run(self) -> Tuple[Optional[Path], Optional[pd.DataFrame]]: """ Must be implemented in each subclass. Returns: path to the file with suggested samples. If batch size is 0, None is returned instead data frame with suggested samples. If batch size is 0, None is returned instead """ pass # pragma: no cover def run_with_adjusted_config(self, extension: str, file_dict: Dict[str, str]): sub_config = self.config.with_adjustments(extension, file_dict) return self.__class__(sub_config).run() def construct_dataset(self) -> Dataset: """Constructs data step, building the data set from the config. Returns: dataset """ logging.info("-----------------") logging.info("Preparing data") logging.info("- Loading DataFrame and converting to a Dataset") dataset = Dataset.from_data_settings(self.config.data) return dataset @staticmethod def suggestions_to_original_space(dataset: Dataset, new_samples: np.ndarray) -> pd.DataFrame: """Applies postprocessing to suggestions of new samples (i.e. transforms the points backwards to the original space and clips them to the bounds). Returns: data frame with samples in the original space """ # Array to data frame expt = pd.DataFrame(np.atleast_2d(new_samples), columns=dataset.transformed_input_names) # Move categorical inputs to the original space # TODO: Test if this works as we expect. expt = dataset.onehot_transform.backward(expt) if dataset.onehot_transform else expt # Move continuous inputs into the original space if not isinstance(dataset.preprocessing_transform, transforms.InvertibleTransform): raise AttributeError("The preprocessing must be invertible to generate a batch.") # pragma: no cover expt_original_space: pd.DataFrame = dataset.preprocessing_transform.backward(expt) # Clip the experiments to the bounds _clip_to_parameter_bounds(expt_original_space, dataset.pretransform_cont_param_bounds, tol=1e-3) return expt_original_space @classmethod def from_strategy(cls, config: OptimizerConfig, strategy: Optional[str] = None) -> "OptimizerBase": """Returns the run function of an instance of the subclass with the matching strategy name""" if strategy is None: strategy = config.optimization_strategy for sub in cls.__subclasses__(): assert sub.strategy_name is not None if sub.strategy_name.lower() == strategy.lower(): return sub(config) raise ValueError(f"Optimization strategy {strategy} not recognized.") # pragma: no cover def _clip_to_parameter_bounds( df: pd.DataFrame, continuous_param_bounds: Dict[str, Tuple[float, float]], tol: float = 1e-3 ) -> None: """Clips the continuous inputs in bounds to parameter bounds, as long as they are outside of the parameter bounds only by the specified tolerance (tol * parameter_bounds_range). This is needed as, for inputs at the boundary, the pre-processing can introduce slight numerical errors. Performs the clipping in place. Args: df: The DataFrame with (a batch of) inputs to perform clipping on continuous_param_bounds: Dictionary from continuous column tol (optional): The percentage of the input parameter range that the parameter is allowed to deviate outside of said range. Defaults to 1e-3. Raises: ValueError: If the input parameters go outside bound given by an amount larger than specified by `tol` parameter. """ for input_column, (lower_bound, upper_bound) in continuous_param_bounds.items(): param_range = upper_bound - lower_bound # Calculate the range of the values of this input input_min: float = df[input_column].min() # type: ignore # auto input_max: float = df[input_column].max() # type: ignore # auto # If any values are out of bounds by more than tol * param_range, raise an exception if input_min < lower_bound - tol * param_range: raise ValueError( # pragma: no cover f"Value {input_min} in column {input_column} in batch is outside of the " f"parameter's bounds: {(lower_bound, upper_bound)}. This is outside the specified " f"tolerance of {tol}, so the value can't be clipped to range." ) if input_max > upper_bound + tol * param_range: raise ValueError( # pragma: no cover f"Value {input_max} in column {input_column} in batch is outside of the " f"parameter's bounds: {(lower_bound, upper_bound)}. This is outside the specified " f"tolerance of {tol}, so the value can't be clipped to range." ) # Otherwise, clip to range # Log a warning if the input is being clipped: if (input_min < lower_bound) or (input_max > upper_bound): logging.debug( # pragma: no cover f"Clipped some values in column {input_column} in batch. The original range was " f"{(input_min, input_max)}, and the points are being clipped to: " f"{(lower_bound, upper_bound)}" ) # Perform clipping in place df[input_column].clip(lower=lower_bound, upper=upper_bound, inplace=True)
[ "numpy.atleast_2d", "abex.dataset.Dataset.from_data_settings", "logging.info", "logging.debug" ]
[((2022, 2055), 'logging.info', 'logging.info', (['"""-----------------"""'], {}), "('-----------------')\n", (2034, 2055), False, 'import logging\n'), ((2064, 2094), 'logging.info', 'logging.info', (['"""Preparing data"""'], {}), "('Preparing data')\n", (2076, 2094), False, 'import logging\n'), ((2104, 2167), 'logging.info', 'logging.info', (['"""- Loading DataFrame and converting to a Dataset"""'], {}), "('- Loading DataFrame and converting to a Dataset')\n", (2116, 2167), False, 'import logging\n'), ((2186, 2230), 'abex.dataset.Dataset.from_data_settings', 'Dataset.from_data_settings', (['self.config.data'], {}), '(self.config.data)\n', (2212, 2230), False, 'from abex.dataset import Dataset\n'), ((2680, 2706), 'numpy.atleast_2d', 'np.atleast_2d', (['new_samples'], {}), '(new_samples)\n', (2693, 2706), True, 'import numpy as np\n'), ((6401, 6594), 'logging.debug', 'logging.debug', (['f"""Clipped some values in column {input_column} in batch. The original range was {input_min, input_max}, and the points are being clipped to: {lower_bound, upper_bound}"""'], {}), "(\n f'Clipped some values in column {input_column} in batch. The original range was {input_min, input_max}, and the points are being clipped to: {lower_bound, upper_bound}'\n )\n", (6414, 6594), False, 'import logging\n')]
import unittest import numpy as np from blmath.geometry.apex import apex from blmath.geometry.apex import farthest class TestApex(unittest.TestCase): def test_apex(self): points = np.array([ [-0.97418884, -0.79808404, -0.18545491], [0.60675227, 0.32673201, -0.20369793], [0.67040405, 0.19267665, -0.56983579], [-0.68038753, -0.90011588, 0.4649872], [-0.62813991, -0.23947753, 0.07933854], [0.26348356, 0.23701114, -0.38230596], [0.08302473, 0.2784907, 0.09308946], [0.58695587, -0.33253376, -0.33493078], [-0.39221704, -0.45240036, 0.25284163], [0.46270635, -0.3865265, -0.98106526], ]) np.testing.assert_array_equal(apex(points, [1, 0, 0]), [0.67040405, 0.19267665, -0.56983579]) np.testing.assert_array_equal(apex(points, [-1, 0, 0]), [-0.97418884, -0.79808404, -0.18545491]) np.testing.assert_array_equal(apex(points, [0, 1, 0]), [0.60675227, 0.32673201, -0.20369793]) np.testing.assert_array_equal(apex(points, [0, -1, 0]), [-0.68038753, -0.90011588, 0.4649872]) np.testing.assert_array_equal(apex(points, [0, 0, 1]), [-0.68038753, -0.90011588, 0.4649872]) np.testing.assert_array_equal(apex(points, [0, 0, -1]), [0.46270635, -0.3865265, -0.98106526]) v = [1/3 ** .5] * 3 expected = points[np.argmax(points.sum(axis=1))] np.testing.assert_array_equal(apex(points, v), expected) # Test non-normalized too. np.testing.assert_array_equal(apex(points, [1, 1, 1]), expected) def test_farthest(self): from_point = np.array([-1., 0., 0.]) to_points = np.array([ [1., -2., -3.], [-1., -20., -30.], ]) point, index = farthest(from_point, to_points) np.testing.assert_array_equal(point, to_points[1]) np.testing.assert_array_equal(index, 1)
[ "numpy.array", "blmath.geometry.apex.apex", "numpy.testing.assert_array_equal", "blmath.geometry.apex.farthest" ]
[((194, 621), 'numpy.array', 'np.array', (['[[-0.97418884, -0.79808404, -0.18545491], [0.60675227, 0.32673201, -\n 0.20369793], [0.67040405, 0.19267665, -0.56983579], [-0.68038753, -\n 0.90011588, 0.4649872], [-0.62813991, -0.23947753, 0.07933854], [\n 0.26348356, 0.23701114, -0.38230596], [0.08302473, 0.2784907, \n 0.09308946], [0.58695587, -0.33253376, -0.33493078], [-0.39221704, -\n 0.45240036, 0.25284163], [0.46270635, -0.3865265, -0.98106526]]'], {}), '([[-0.97418884, -0.79808404, -0.18545491], [0.60675227, 0.32673201,\n -0.20369793], [0.67040405, 0.19267665, -0.56983579], [-0.68038753, -\n 0.90011588, 0.4649872], [-0.62813991, -0.23947753, 0.07933854], [\n 0.26348356, 0.23701114, -0.38230596], [0.08302473, 0.2784907, \n 0.09308946], [0.58695587, -0.33253376, -0.33493078], [-0.39221704, -\n 0.45240036, 0.25284163], [0.46270635, -0.3865265, -0.98106526]])\n', (202, 621), True, 'import numpy as np\n'), ((1658, 1684), 'numpy.array', 'np.array', (['[-1.0, 0.0, 0.0]'], {}), '([-1.0, 0.0, 0.0])\n', (1666, 1684), True, 'import numpy as np\n'), ((1703, 1754), 'numpy.array', 'np.array', (['[[1.0, -2.0, -3.0], [-1.0, -20.0, -30.0]]'], {}), '([[1.0, -2.0, -3.0], [-1.0, -20.0, -30.0]])\n', (1711, 1754), True, 'import numpy as np\n'), ((1808, 1839), 'blmath.geometry.apex.farthest', 'farthest', (['from_point', 'to_points'], {}), '(from_point, to_points)\n', (1816, 1839), False, 'from blmath.geometry.apex import farthest\n'), ((1849, 1899), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['point', 'to_points[1]'], {}), '(point, to_points[1])\n', (1878, 1899), True, 'import numpy as np\n'), ((1908, 1947), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['index', '(1)'], {}), '(index, 1)\n', (1937, 1947), True, 'import numpy as np\n'), ((768, 791), 'blmath.geometry.apex.apex', 'apex', (['points', '[1, 0, 0]'], {}), '(points, [1, 0, 0])\n', (772, 791), False, 'from blmath.geometry.apex import apex\n'), ((870, 894), 'blmath.geometry.apex.apex', 'apex', (['points', '[-1, 0, 0]'], {}), '(points, [-1, 0, 0])\n', (874, 894), False, 'from blmath.geometry.apex import apex\n'), ((975, 998), 'blmath.geometry.apex.apex', 'apex', (['points', '[0, 1, 0]'], {}), '(points, [0, 1, 0])\n', (979, 998), False, 'from blmath.geometry.apex import apex\n'), ((1077, 1101), 'blmath.geometry.apex.apex', 'apex', (['points', '[0, -1, 0]'], {}), '(points, [0, -1, 0])\n', (1081, 1101), False, 'from blmath.geometry.apex import apex\n'), ((1180, 1203), 'blmath.geometry.apex.apex', 'apex', (['points', '[0, 0, 1]'], {}), '(points, [0, 0, 1])\n', (1184, 1203), False, 'from blmath.geometry.apex import apex\n'), ((1282, 1306), 'blmath.geometry.apex.apex', 'apex', (['points', '[0, 0, -1]'], {}), '(points, [0, 0, -1])\n', (1286, 1306), False, 'from blmath.geometry.apex import apex\n'), ((1471, 1486), 'blmath.geometry.apex.apex', 'apex', (['points', 'v'], {}), '(points, v)\n', (1475, 1486), False, 'from blmath.geometry.apex import apex\n'), ((1572, 1595), 'blmath.geometry.apex.apex', 'apex', (['points', '[1, 1, 1]'], {}), '(points, [1, 1, 1])\n', (1576, 1595), False, 'from blmath.geometry.apex import apex\n')]
import argparse import json import logging import random import numpy as np import torch from decouple import config from tqdm import tqdm from GPT2.config import GPT2Config from GPT2.encoder import get_encoder from GPT2.model import GPT2LMHeadModel from GPT2.utils import load_weight # import os # import torch.nn.functional as F # from array import array parser = argparse.ArgumentParser(description="Validity Tensor Estimation") parser.add_argument( "-gs", default="data/groundStrings.json", type=str, help="sets the input grond string file", ) parser.add_argument( "-pt", default="data/perterbationTensor.json", type=str, help="sets the input perterbation tensor file.", ) parser.add_argument( "-gvi", default="data/groundValidityTensor.json", type=str, help="sets the input ground validity tensor file.", ) parser.add_argument( "-gvo", default="data/groundValidityTensor.json", type=str, help="sets the output ground validity tensor file.", ) parser.add_argument( "-vo", default="data/validityTensor.json", type=str, help="sets the output validity tensor file.", ) parser.add_argument( "-d", type=str, help="Sets the device to use.\n" "Choices: 'gpu' for GPU, 'cpu' for CPU\n" "(If left blank defaults to 'DEVICE' entry in .env file.)\n", ) parser.add_argument( "-checkpoint", default=None, type=str, help="Begin again from end of partial validity tensor file.\n" "Accepts: file path to .json containing validity tensor.\n", ) args = vars(parser.parse_args()) logging.basicConfig( filename="logs/validtyTensor.log", level=logging.DEBUG, format="[%(asctime)s|%(name)s|make_validity_tensor.py|%(levelname)s] %(message)s", ) if args["d"]: device_choice = args["d"] else: device_choice = config("DEVICE") print("\nDEVICE:", device_choice, "\n") if device_choice == "gpu" and not torch.cuda.is_available(): print("CUDA unavailable, defaulting to CPU.") device_choice = "cpu" if device_choice == "gpu": print("gpu accellerated") else: print("cpu bound") state_dict = torch.load( config("MODEL_LOCATION"), map_location="cpu" if (not torch.cuda.is_available() or device_choice == "cpu") else None, ) print("\nValidity Tensor Estimation\n") # -- Setting up PyTorch Information -- # seed = random.randint(0, 2147483647) np.random.seed(seed) torch.random.manual_seed(seed) torch.cuda.manual_seed(seed) # device = torch.device("cpu") device = torch.device( "cuda" if (torch.cuda.is_available() and device_choice == "gpu") else "cpu" ) known_configurations = { "s_ai": GPT2Config(), "xl_ai": GPT2Config( vocab_size_or_config_json_file=50257, n_positions=1024, n_ctx=1024, n_embd=1600, n_layer=48, n_head=25, layer_norm_epsilon=1e-5, initializer_range=0.02, ), } # -- Load Model -- # gpt2_config = known_configurations[config("MODEL_NAME")] model = GPT2LMHeadModel(gpt2_config) model = load_weight(model, state_dict) model.share_memory() model.to(device) model.eval() # -- serving BrainSqueeze resources. --# def tokenize(text: str): enc = get_encoder() tokens = enc.encode(text) return tokens def detokenize(tokens: iter): enc = get_encoder() text = enc.decode(tokens) return text def firstMismatch(tokensA: iter, tokensB: iter): # assumes tokensA is shorter than, or as long as, tokensB. for i in range(len(tokensA)): if tokensA[i] != tokensB[i]: return i return None def firstMismatchInclusive(tokensA: iter, tokensB: iter): # makes no assumptions about the lengths of tokensA and tokensB. for i in range(min(len(tokensA), len(tokensB))): if tokensA[i] != tokensB[i]: return i return min(len(tokensA), len(tokensB)) def predictedDistribution( model=model, start_token=50256, batch_size=1, tokens=None, temperature: float = None, top_k=1, device=device, ): """returns a probability distribution for the next byte-pair encoding""" if tokens is None: context = torch.full( (batch_size, 1), start_token, device=device, dtype=torch.long ) elif type(tokens) is torch.Tensor: context = tokens.unsqueeze(0).repeat(batch_size, 1) else: context = ( torch.tensor(tokens, device=device, dtype=torch.long) .unsqueeze(0) .repeat(batch_size, 1) ) prev = context past = None with torch.no_grad(): logits, past = model(prev, past=past) logits = logits[:, -1, :] return logits[0] def errorSeries(tokens: list, pbar: tqdm): radii = [] # get first radius (special case) logits = predictedDistribution(start_token=50256) # 50256 => <|endoftext|> prob = logits[tokens[0]] clamped = torch.clamp(logits, min=prob, max=None) clamped.add_(-prob) radius = torch.count_nonzero(clamped).item() radii.append(radius) if pbar is not None: pbar.update(1) # get all following radii for i in range(1, len(tokens)): logits = predictedDistribution(tokens=tokens[:i]) prob = logits[tokens[i]] clamped = torch.clamp(logits, min=prob, max=None) clamped.add_(-prob) radius = torch.count_nonzero(clamped).item() radii.append(radius) if pbar is not None: pbar.update(1) return radii def partialErrorSeries(tokens: list, start: int): def getRadius(logits, token): prob = logits[token] clamped = torch.clamp(logits, min=prob, max=None) clamped.add_(-prob) radius = torch.count_nonzero(clamped).item() return radius radii = [] if start == 0: # get first radius (special case) logits = predictedDistribution(start_token=50256) # 50256 => <|endoftext|> radius = getRadius(logits, tokens[0]) radii.append(radius) # then get all following radii for i in range(1, len(tokens)): logits = predictedDistribution(tokens=tokens[:i]) radius = getRadius(logits, tokens[i]) radii.append(radius) return radii else: for i in range(start, len(tokens)): logits = predictedDistribution(tokens=tokens[:i]) radius = getRadius(logits, tokens[i]) radii.append(radius) return radii def calculateGroundValidityTensor(groundStrings: iter): gvBar = tqdm(total=len(groundStrings), desc="GroundValidity", position=0) gvTen = [] coder = get_encoder() for gs in groundStrings: tokens = coder.encode(gs) radii = errorSeries(tokens, None) gvTen.append(radii) gvBar.update() return gvTen def calculateValidityTensor( groundTokens: iter, groundValidityTensor: iter, perterbationTensor: iter, checkpoint: str = None, ): validityTensor = [] totalBar = tqdm(total=len(perterbationTensor), desc="Total", position=0) symbolBar = tqdm(total=len(perterbationTensor[0][1]), desc="TBD", position=1) vectorBar = tqdm(total=len(perterbationTensor[0][1][0]), desc="Vector", position=2) if checkpoint: with open(checkpoint, "r") as f: validityTensor = json.load(f) # don't recalculate any symbols that have already been done already = len(validityTensor) perterbationTensor = perterbationTensor[already::] totalBar.update(already) coder = get_encoder() for sym, plane in perterbationTensor: logging.info("Started Symbol: " + sym) symbolBar.reset() symbolBar.set_description(sym) vPlane = [] for i, vector in enumerate(plane): vVector = [] vectorBar.reset(total=len(vector)) for pString in vector: # tokenize pString pTokens = coder.encode(pString) # locate departure form ground tokens departure = firstMismatch(pTokens, groundTokens[i]) if departure is not None: # sum error up to agreement with groundTokens agreement = sum(groundValidityTensor[i][:departure]) # calculate validity of peterbed string from departure onward departureValidity = partialErrorSeries(pTokens, departure) # calculate total validity validity = agreement + sum(departureValidity) # compare to ground validity validity_delta = ( sum(groundValidityTensor[i]) - validity ) # lower validity is better else: validity_delta = 0 vVector.append(validity_delta) vectorBar.update() vPlane.append(vVector) symbolBar.update() validityTensor.append((sym, vPlane)) totalBar.update() logging.info("Finished Symbol: " + sym) with open(args["vo"], "w") as f: # save checkpoint json.dump(validityTensor, f) vectorBar.close() symbolBar.close() totalBar.close() return validityTensor if __name__ == "__main__": # with open(args["gs"], "r") as f: # groundStrings = json.load(f) # gvTen = calculateGroundValidityTensor(groundStrings) # with open(args["gvo"], "w") as f: # json.dump(gvTen, f) with open(args["gs"], "r") as f: groundStrings = json.load(f) groundTokens = [] coder = get_encoder() for gs in groundStrings: groundTokens.append(coder.encode(gs)) with open(args["gvi"], "r") as f: groundValidity = json.load(f) with open(args["pt"], "r") as f: perterbationTensor = json.load(f) vt = calculateValidityTensor( groundTokens, groundValidity, perterbationTensor, checkpoint=args["checkpoint"] ) print("\n\n\n### --- SUCCESS! --- ###\n\n\n")
[ "torch.cuda.is_available", "GPT2.model.GPT2LMHeadModel", "logging.info", "torch.random.manual_seed", "argparse.ArgumentParser", "decouple.config", "numpy.random.seed", "GPT2.encoder.get_encoder", "torch.count_nonzero", "random.randint", "GPT2.config.GPT2Config", "GPT2.utils.load_weight", "to...
[((373, 438), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Validity Tensor Estimation"""'}), "(description='Validity Tensor Estimation')\n", (396, 438), False, 'import argparse\n'), ((1593, 1760), 'logging.basicConfig', 'logging.basicConfig', ([], {'filename': '"""logs/validtyTensor.log"""', 'level': 'logging.DEBUG', 'format': '"""[%(asctime)s|%(name)s|make_validity_tensor.py|%(levelname)s] %(message)s"""'}), "(filename='logs/validtyTensor.log', level=logging.DEBUG,\n format=\n '[%(asctime)s|%(name)s|make_validity_tensor.py|%(levelname)s] %(message)s')\n", (1612, 1760), False, 'import logging\n'), ((2372, 2401), 'random.randint', 'random.randint', (['(0)', '(2147483647)'], {}), '(0, 2147483647)\n', (2386, 2401), False, 'import random\n'), ((2402, 2422), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (2416, 2422), True, 'import numpy as np\n'), ((2423, 2453), 'torch.random.manual_seed', 'torch.random.manual_seed', (['seed'], {}), '(seed)\n', (2447, 2453), False, 'import torch\n'), ((2454, 2482), 'torch.cuda.manual_seed', 'torch.cuda.manual_seed', (['seed'], {}), '(seed)\n', (2476, 2482), False, 'import torch\n'), ((3009, 3037), 'GPT2.model.GPT2LMHeadModel', 'GPT2LMHeadModel', (['gpt2_config'], {}), '(gpt2_config)\n', (3024, 3037), False, 'from GPT2.model import GPT2LMHeadModel\n'), ((3046, 3076), 'GPT2.utils.load_weight', 'load_weight', (['model', 'state_dict'], {}), '(model, state_dict)\n', (3057, 3076), False, 'from GPT2.utils import load_weight\n'), ((1838, 1854), 'decouple.config', 'config', (['"""DEVICE"""'], {}), "('DEVICE')\n", (1844, 1854), False, 'from decouple import config\n'), ((2151, 2175), 'decouple.config', 'config', (['"""MODEL_LOCATION"""'], {}), "('MODEL_LOCATION')\n", (2157, 2175), False, 'from decouple import config\n'), ((2657, 2669), 'GPT2.config.GPT2Config', 'GPT2Config', ([], {}), '()\n', (2667, 2669), False, 'from GPT2.config import GPT2Config\n'), ((2684, 2857), 'GPT2.config.GPT2Config', 'GPT2Config', ([], {'vocab_size_or_config_json_file': '(50257)', 'n_positions': '(1024)', 'n_ctx': '(1024)', 'n_embd': '(1600)', 'n_layer': '(48)', 'n_head': '(25)', 'layer_norm_epsilon': '(1e-05)', 'initializer_range': '(0.02)'}), '(vocab_size_or_config_json_file=50257, n_positions=1024, n_ctx=\n 1024, n_embd=1600, n_layer=48, n_head=25, layer_norm_epsilon=1e-05,\n initializer_range=0.02)\n', (2694, 2857), False, 'from GPT2.config import GPT2Config\n'), ((2979, 2999), 'decouple.config', 'config', (['"""MODEL_NAME"""'], {}), "('MODEL_NAME')\n", (2985, 2999), False, 'from decouple import config\n'), ((3207, 3220), 'GPT2.encoder.get_encoder', 'get_encoder', ([], {}), '()\n', (3218, 3220), False, 'from GPT2.encoder import get_encoder\n'), ((3311, 3324), 'GPT2.encoder.get_encoder', 'get_encoder', ([], {}), '()\n', (3322, 3324), False, 'from GPT2.encoder import get_encoder\n'), ((4910, 4949), 'torch.clamp', 'torch.clamp', (['logits'], {'min': 'prob', 'max': 'None'}), '(logits, min=prob, max=None)\n', (4921, 4949), False, 'import torch\n'), ((6636, 6649), 'GPT2.encoder.get_encoder', 'get_encoder', ([], {}), '()\n', (6647, 6649), False, 'from GPT2.encoder import get_encoder\n'), ((7556, 7569), 'GPT2.encoder.get_encoder', 'get_encoder', ([], {}), '()\n', (7567, 7569), False, 'from GPT2.encoder import get_encoder\n'), ((9629, 9642), 'GPT2.encoder.get_encoder', 'get_encoder', ([], {}), '()\n', (9640, 9642), False, 'from GPT2.encoder import get_encoder\n'), ((1931, 1956), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (1954, 1956), False, 'import torch\n'), ((4164, 4237), 'torch.full', 'torch.full', (['(batch_size, 1)', 'start_token'], {'device': 'device', 'dtype': 'torch.long'}), '((batch_size, 1), start_token, device=device, dtype=torch.long)\n', (4174, 4237), False, 'import torch\n'), ((4570, 4585), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (4583, 4585), False, 'import torch\n'), ((5272, 5311), 'torch.clamp', 'torch.clamp', (['logits'], {'min': 'prob', 'max': 'None'}), '(logits, min=prob, max=None)\n', (5283, 5311), False, 'import torch\n'), ((5628, 5667), 'torch.clamp', 'torch.clamp', (['logits'], {'min': 'prob', 'max': 'None'}), '(logits, min=prob, max=None)\n', (5639, 5667), False, 'import torch\n'), ((7620, 7658), 'logging.info', 'logging.info', (["('Started Symbol: ' + sym)"], {}), "('Started Symbol: ' + sym)\n", (7632, 7658), False, 'import logging\n'), ((9044, 9083), 'logging.info', 'logging.info', (["('Finished Symbol: ' + sym)"], {}), "('Finished Symbol: ' + sym)\n", (9056, 9083), False, 'import logging\n'), ((9581, 9593), 'json.load', 'json.load', (['f'], {}), '(f)\n', (9590, 9593), False, 'import json\n'), ((9782, 9794), 'json.load', 'json.load', (['f'], {}), '(f)\n', (9791, 9794), False, 'import json\n'), ((9862, 9874), 'json.load', 'json.load', (['f'], {}), '(f)\n', (9871, 9874), False, 'import json\n'), ((2552, 2577), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (2575, 2577), False, 'import torch\n'), ((4987, 5015), 'torch.count_nonzero', 'torch.count_nonzero', (['clamped'], {}), '(clamped)\n', (5006, 5015), False, 'import torch\n'), ((7332, 7344), 'json.load', 'json.load', (['f'], {}), '(f)\n', (7341, 7344), False, 'import json\n'), ((9156, 9184), 'json.dump', 'json.dump', (['validityTensor', 'f'], {}), '(validityTensor, f)\n', (9165, 9184), False, 'import json\n'), ((5357, 5385), 'torch.count_nonzero', 'torch.count_nonzero', (['clamped'], {}), '(clamped)\n', (5376, 5385), False, 'import torch\n'), ((5713, 5741), 'torch.count_nonzero', 'torch.count_nonzero', (['clamped'], {}), '(clamped)\n', (5732, 5741), False, 'import torch\n'), ((2212, 2237), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (2235, 2237), False, 'import torch\n'), ((4401, 4454), 'torch.tensor', 'torch.tensor', (['tokens'], {'device': 'device', 'dtype': 'torch.long'}), '(tokens, device=device, dtype=torch.long)\n', (4413, 4454), False, 'import torch\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jun 21 13:46:35 2021 @author: dmattox """ import pickle import umap import random import collections import re import itertools import plotnine as p9 import matplotlib.pyplot as plt import numpy as np import pandas as pd import networkx as nx import cbk.sugarTrees.bin.sugarTrees as SugarTrees import cbk.sugarTrees.bin.getStats as SugarStats pd.set_option('display.max_columns', None) pd.set_option('display.max_rows', None) homeDir = '/Users/dmattox/cbk/sugarTrees/' # homeDir = '/Users/f002tsy/sugarTrees/' # Load data with open(homeDir + 'immunoFiles/allimmu_gen.pkl', 'rb') as inFH: allemb3 = pickle.load(inFH) with open(homeDir + 'immunoFiles/allimmu_gen_label.pkl', 'rb') as inFH: allemblabel3 = pickle.load(inFH) with open(homeDir + 'immunoFiles/npp.pkl', 'rb') as inFH: # Encoding of the generated glycans, overlap with allemblabel3 npp = pickle.load(inFH) with open(homeDir + 'immunoFiles/pls.pkl', 'rb') as inFH: pls = pickle.load(inFH) pls = pls[::-1] # list of sizes of blocks of glycans generated along the same path, originally in reverse order starting at the backend of the dataframe with open(homeDir + 'immunoFiles/path_encoding.pkl', 'rb') as inFH: encs = pickle.load(inFH) encs = encs[::-1] encs = [sublst[::-1] for sublst in encs] # lists of lists of the monosaccharides comprising the glycans at each step of each generative path with open(homeDir + 'immunoFiles/id-path.pkl', 'rb') as inFH: pathIDs = pickle.load(inFH) with open(homeDir + 'immunoFiles/probofemb.pkl', 'rb') as inFH: immProb = pickle.load(inFH) # Probabilities of being immunogenic/not immunogenic at each step of each generative path # 1st col : probability of being not immunogenic # 2nd col : probability of being immunogenic immProb[:,0] + immProb[:,1] # Same order as encs immProb = immProb[::-1,1] # Reversed to match embedding order, using only the immunogenic column monoDict = pickle.load(open('/Users/dmattox/Documents/qbs/cbk/sugarTrees/pickles/commonMonoDict.pickle', 'rb')) revMonoDict = {v:k for k,v in monoDict.items()} with open(homeDir + 'pickles/matchedTrees_andLinks_andAno_immuno.pickle', 'rb') as inFH: matchedTrees = pickle.load(inFH) gDict = {g.sbID : g for g in SugarStats.commonGlys} immDict = {0 : 'Non-immunogenic', 1 : 'Immunogenic', 2 : 'Generated'} # 3 : 'Non-imm. \n -- Generative Start'} # generative paths len(pls) # 20 paths in total genPaths = [] for i, pathLen in enumerate(pls): # index paths from 1-20 and rep for path length to match glycan embeddings genPaths.extend([i+1] * pathLen) print(len(genPaths) == npp.shape[0]) genPaths = [0] * sum(np.array(allemblabel3) != 2) + genPaths # Add 0 to all other existing points print(len(genPaths) == len(allemblabel3)) # First glycan in each generative path is the starting, exisiting glycan, set label as such prev = 1 for i in range(1,len(allemblabel3)): if allemblabel3[i-1] == 2 and genPaths[i] != prev: prev = genPaths[i] allemblabel3[i-1] = 0 allemblabel3[-1] = 0 # Full immProbs - get list of length matching full embedding array allImmProbs = [0] * (allemb3.shape[0] - npp.shape[0]) # rep 0 for all exisiting glycan embeddings not used in paths allImmProbs += list(immProb) random.seed(27) reducer = umap.UMAP().fit(allemb3) # fit UMAP to known & generated glycans # reducer = umap.UMAP().fit(allemb3[np.array(allemblabel3) != 2,:]) # fit UMAP to known glycans uu = reducer.embedding_ # uuGen = reducer.transform(allemb3[np.array(allemblabel3) == 2,:]) # Fit generated glycans to UMAP embedding built around known glycans # uuGenp = pd.DataFrame(uuGen, columns = ['UMAP1', 'UMAP2']) # uuGenp['Glycan Type'] = [immDict[lab] for lab in allemblabel3 if lab == 2] uup = pd.DataFrame(uu, columns = ['UMAP1', 'UMAP2']) # uup['Glycan Type'] = [immDict[lab] for lab in allemblabel3 if lab != 2] uup['Glycan Type'] = [immDict[lab] for lab in allemblabel3] # uup = pd.concat([uup, uuGenp]) p9.ggplot(uup) + p9.aes(x = 'UMAP1', y = 'UMAP2', fill = 'Glycan Type') + p9.geom_point(alpha = 0.5, size = 3, color = '#ffffff') + \ p9.scale_fill_manual(values = ['magenta','#a84c3e', '#3e6ca8']) uup['Generative Path'] = [str(i) for i in genPaths] # uup['Generative Path'] = genPaths pathCols = [('#%06X' % random.randint(0, 0xFFFFFF)) for i in range(len(pls))] immPathPlt = p9.ggplot(uup) + p9.aes(x = 'UMAP1', y = 'UMAP2', fill = 'Glycan Type', color = 'Generative Path', group = 'Generative Path') + \ p9.geom_point(alpha = 0.5, size = 3, color = '#ffffff') + \ p9.scale_fill_manual(values = ['magenta','#a84c3e', '#3e6ca8']) + \ p9.geom_path() + \ p9.scale_color_manual(values=['#FFFFFF00'] + pathCols, guide=False) + \ p9.theme_minimal() immPathPlt.save('/Users/dmattox/Documents/qbs/cbk/sugarTrees/plots/immGenPaths.pdf', dpi = 600) # add in probability of immunogenicity uup['Immuno Probability'] = allImmProbs # add in monosaccharide info encsFlat = [subLst for lst in encs for subLst in lst] len(encsFlat) allEncs = [[] for i in range(allemb3.shape[0] - npp.shape[0])] # rep 0 for all exisiting glycan embeddings not used in paths allEncs += encsFlat uup['Monosaccs'] = allEncs # Try and match paths to starting glycans for sbGly in pathIDs.keys(): if pathIDs[sbGly]: print(sbGly) for p in pathIDs[sbGly]: print('\t', p) print() for i in range(1,21): print(uup[uup['Generative Path'] == str(i)]) print('\n\n') path2glyID = {'SBID6185': ['18','19', '20'], 'SBID7112': ['16', '17'], 'SBID10624': ['15'], 'SBID12056': ['12', '13', '14'], 'SBID13034': ['7', '8', '9', '10', '11'], 'SBID17909': ['4', '5', '6'], 'SBID4739': ['1', '2', '3']} # Could've done this ^^ programatically but didn't realize it was ordered so nicely until I started doing it manually len(pathIDs) for p in pathIDs.keys(): print(gDict[p].iupac) print(p, [d for d in matchedTrees if p in d['No']], 'paths:', path2glyID.get(p)) dLst = [d for p in pathIDs.keys() for d in matchedTrees if p in d['No']] dLstNonGlys = set([g for d in dLst for g in d['No']]) dLstImmGlys = set([g for d in dLst for g in d['Yes']]) len(dLstNonGlys) len(dLstImmGlys) startingGlys = [] for p in genPaths: if p == 0: startingGlys.append('') else: for k,v in path2glyID.items(): if str(p) in v: sGly = k startingGlys.append(sGly) uup['Starting Glycan'] = startingGlys # Update monosaccs with actual monosaccharide names for i in range(len(allEncs)): if allEncs[i]: newEnc = [revMonoDict[m-2] for m in allEncs[i]] allEncs[i] = newEnc[::-1] uup['Monosaccs'] = allEncs sGly2iupac = {} for k in path2glyID.keys(): print(k) s = [sug for sug in SugarStats.commonGlys if sug.sbID == k][0] s.print() print('\n\n---------------\n') sGly2iupac[k] = s.iupac for i in range(1,21): print(uup[uup['Generative Path'] == str(i)]) print('\n_________________\n') # Find IUPAC strings for each glycan ## Not built to handle branched glycans as all test cases here are linear glycans iupacs = [] for monoLst, sGly in zip(allEncs, startingGlys): if sGly != '': sGly = sGly2iupac[sGly] decomposedGly = re.split(r'(\([a,b][0-9]-[0-9]\))', sGly) for mInd,gInd in zip(range(len(monoLst)), range(0, len(decomposedGly), 2)): decomposedGly[gInd] = monoLst[mInd] iupacs.append(''.join(decomposedGly)) else: iupacs.append('') uup['IUPAC'] = iupacs # Check which generated glycans exist as labelled glycans ## Not built to handle branched glycans as all test cases here are linear glycans knownGlycans = [] for gly,gType in zip(iupacs,allemblabel3): if gly != '': # print(gly, '\n\t', immDict[gType], '\n') s = [sug for sug in SugarStats.commonGlys if sug.iupac == gly] if s: # s[0].print() if len(s)> 1: print('Warning: Multiple matches, breaking loop...') break if s[0].immunogenic != 'Unknown': knownGlycans.append(s[0].immunogenic) else: # Check if unlabeled glycans are close to any known immunogenic glycans (same monos and links but different anomeric state) decomposedGly = re.split(r'(\([a,b][0-9]-[0-9]\)[\[,\]]?)', gly) glyProds = [] for m in decomposedGly: if re.match(r'\([a,b][0-9]-[0-9]\)', m): out = [re.sub(r'\(b', '(a', m)] out.append(re.sub(r'\(a', '(b', m)) glyProds.append(out) else: glyProds.append([m]) glyProds = [''.join(g) for g in list(itertools.product(*glyProds))] matchedProds = [[sug for sug in SugarStats.commonGlys if sug.iupac == g] for g in glyProds] matchedLabs = [] for s in matchedProds: if s: matchedLabs.append(s[0].immunogenic) if 'Yes' in matchedLabs: knownGlycans.append('Unknown - Imm ano mismatch') else: knownGlycans.append('Unknown') else: # print('NOVEL') decomposedGly = re.split(r'(\([a,b][0-9]-[0-9]\)[\[,\]]?)', gly) glyProds = [] for m in decomposedGly: if re.match(r'\([a,b][0-9]-[0-9]\)', m): out = [re.sub(r'\(b', '(a', m)] out.append(re.sub(r'\(a', '(b', m)) glyProds.append(out) else: glyProds.append([m]) glyProds = [''.join(g) for g in list(itertools.product(*glyProds))] matchedProds = [[sug for sug in SugarStats.commonGlys if sug.iupac == g] for g in glyProds] matchedLabs = [] for s in matchedProds: if s: matchedLabs.append(s[0].immunogenic) if 'Yes' in matchedLabs: knownGlycans.append('Novel - Imm ano mismatch') else: knownGlycans.append('Novel') # print('----------------------') else: knownGlycans.append('') knownGlycans = [g if g != 'No' else 'Non-immunogenic' for g in knownGlycans] knownGlycans = [g if g != 'Yes' else 'Immunogenic' for g in knownGlycans] uup['Existing glycan'] = knownGlycans uup[uup['Starting Glycan'] == 'SBID4739'] matches = [d for d in matchedTrees if 'SBID4739' in d['No']][0] [gDict[g].print() for g in matches['Yes']] with open('/Users/dmattox/Documents/qbs/cbk/sugarTrees/pickles/immGenUMAPall.pkl', 'wb') as outFH: pickle.dump(uup, outFH) uup.to_csv(homeDir + 'immGenDF.tsv', sep="\t", index=False) ############################################## # Draw network for i in range(1,21): print(uup[uup['Generative Path'] == str(i)]) print('\n_________________\n') allGenGlys = list(set(uup[uup['IUPAC'] != '']['IUPAC'])) len(allGenGlys) set(uup[uup['Generative Path'] == '19']['IUPAC']) G = nx.DiGraph() G.add_nodes_from(set(uup[uup['Generative Path'] == '19']['IUPAC'])) G.add_weighted_edges_from([('NeuNAc(a2-3)Gal(b1-3)GalNAc', 'GalNAc(a2-3)Gal(b1-3)GalNAc', 1.0), ('GalNAc(a2-3)Gal(b1-3)GalNAc', 'NeuNAc(a2-3)Gal(b1-3)GalNAc', 1.0), ('NeuNAc(a2-3)Gal(b1-3)GalNAc', 'NeuNAc(a2-3)Gal(b1-3)GlcNAc', 1.0)]) nx.draw_networkx(G, node_color='r', edge_color='b', pos = {'NeuNAc(a2-3)Gal(b1-3)GalNAc' : (0.852186,0), 'GalNAc(a2-3)Gal(b1-3)GalNAc' : (0.855664, 1), 'NeuNAc(a2-3)Gal(b1-3)GlcNAc' : (0.993761, -1)}) G = nx.DiGraph() G.add_nodes_from([2, 3]) ##################### encs # monosacc code here -2 = monoDict key ; sublists reordered from imm to non-imm to match array rows (reverse from rows of array) pls i=19 print(encs[i-1]) print(uup[np.array(genPaths) == i]) p9.ggplot(uup[np.array(genPaths) == i]) + p9.aes(x = 'UMAP1', y = 'UMAP2', fill = 'Glycan Type', color = 'Generative Path', group = 'Generative Path') + p9.geom_point(alpha = 0.5, size = 3, color = '#ffffff') + \ p9.scale_fill_manual(values = ['magenta','#3e6ca8']) + \ p9.geom_path() # fig, ax = plt.subplots() # ax.scatter(uup[np.array(genPaths) == i]['UMAP1'], uup[np.array(genPaths) == i]['UMAP2']) # for j,pos in enumerate(zip(uup[np.array(genPaths) == i]['UMAP1'], uup[np.array(genPaths) == i]['UMAP2'])): # ax.annotate(str(j+1), xy = pos) # plt.show() changeDict = collections.defaultdict(list) for p in range(1,21): glys = encs[p-1] print(p, '\n', glys) maxDelt = 0 maxGlyDiff = () for i in range(1,len(glys)): for m1,m2 in zip(glys[i],glys[i-1]): if m1 != m2: diff = (m1,m2) delt = np.sqrt(sum((uup[np.array(genPaths) == p].iloc[i-1, [0,1]] - uup[np.array(genPaths) == p].iloc[i, [0,1]])**2)) distFromNonImmStart = [np.sqrt(sum((uup[np.array(genPaths) == p].iloc[-1, [0,1]] - uup[np.array(genPaths) == p].iloc[i, [0,1]])**2)), np.sqrt(sum((uup[np.array(genPaths) == p].iloc[-1, [0,1]] - uup[np.array(genPaths) == p].iloc[i-1, [0,1]])**2))] direction = 1 if np.argmax(distFromNonImmStart) == 1 else -1 print('\t\t',revMonoDict[diff[0]-2], '-->', revMonoDict[diff[1]-2], delt * direction) changeDict[diff].append(delt*direction) if delt > maxDelt: maxDelt = delt maxGlyDiff = diff print('\t',revMonoDict[maxGlyDiff[0]-2], '-->', revMonoDict[maxGlyDiff[1]-2], maxDelt * direction) print() changeDict with open('/Users/dmattox/Documents/qbs/cbk/sugarTrees/immunoFiles/glyChanges.csv', 'w') as outFH: outFH.write('old,new,distance\n') for monoPair, distLst in changeDict.items(): for d in distLst: outFH.write(','.join([revMonoDict[monoPair[0] - 2], revMonoDict[monoPair[1] - 2], str(d)]) + '\n') for k,v in changeDict.items(): print(revMonoDict[k[0]-2], '-->', revMonoDict[k[1]-2]) print(sorted(v)) print() meanChanges = [(k, np.mean(v)) for k,v in changeDict.items()] meanChanges.sort(key = lambda x: x[1]) meanChanges for k,score in meanChanges: print(revMonoDict[k[0]-2], '-->', revMonoDict[k[1]-2], score) changeDictNew = collections.defaultdict(list) for k,v in changeDict.items(): changeDictNew[k[1]].extend(sorted(v)) meanChangesNew = [(k, np.mean(v)) for k,v in changeDictNew.items()] meanChangesNew.sort(key = lambda x: x[1]) meanChangesNew glyDiff = [] dists = [] for k,v in meanChanges: glyDiff.extend([revMonoDict[k[0]-2] + '>' + revMonoDict[k[1]-2]] * len(changeDict[k])) # glyDiff.extend([(revMonoDict[k[0]-2], revMonoDict[k[1]-2])] * len(changeDict[k])) dists.extend(sorted(changeDict[k])) gdp = pd.DataFrame(list(zip(glyDiff, dists)), columns = ['Change', 'Distance']) # gdp = pd.DataFrame(glyDiff, columns = ['Old', 'New']) # gdp['Distance'] = dists # gdpMean = p9.ggplot(gdp) + p9.aes(x = 'Change', y = 'Distance', fill = 'Distance') + \ p9.geom_bar(stat = 'identity', position = 'dodge', color = 'black') + \ p9.theme(axis_text_x = p9.element_text(angle = 45, vjust = 1, hjust=1, face = 'bold')) + \ p9.scale_x_discrete(limits = [revMonoDict[g[0]-2]+'>'+revMonoDict[g[1]-2] for g,s in meanChanges]) + \ p9.scale_fill_gradient(high = '#a84c3e', low = '#3e6ca8')
[ "plotnine.scale_x_discrete", "plotnine.ggplot", "plotnine.scale_fill_gradient", "plotnine.geom_bar", "plotnine.aes", "numpy.array", "umap.UMAP", "plotnine.scale_color_manual", "re.split", "plotnine.theme_minimal", "numpy.mean", "networkx.DiGraph", "itertools.product", "pandas.set_option", ...
[((414, 456), 'pandas.set_option', 'pd.set_option', (['"""display.max_columns"""', 'None'], {}), "('display.max_columns', None)\n", (427, 456), True, 'import pandas as pd\n'), ((457, 496), 'pandas.set_option', 'pd.set_option', (['"""display.max_rows"""', 'None'], {}), "('display.max_rows', None)\n", (470, 496), True, 'import pandas as pd\n'), ((3358, 3373), 'random.seed', 'random.seed', (['(27)'], {}), '(27)\n', (3369, 3373), False, 'import random\n'), ((3856, 3900), 'pandas.DataFrame', 'pd.DataFrame', (['uu'], {'columns': "['UMAP1', 'UMAP2']"}), "(uu, columns=['UMAP1', 'UMAP2'])\n", (3868, 3900), True, 'import pandas as pd\n'), ((11275, 11287), 'networkx.DiGraph', 'nx.DiGraph', ([], {}), '()\n', (11285, 11287), True, 'import networkx as nx\n'), ((11645, 11854), 'networkx.draw_networkx', 'nx.draw_networkx', (['G'], {'node_color': '"""r"""', 'edge_color': '"""b"""', 'pos': "{'NeuNAc(a2-3)Gal(b1-3)GalNAc': (0.852186, 0),\n 'GalNAc(a2-3)Gal(b1-3)GalNAc': (0.855664, 1),\n 'NeuNAc(a2-3)Gal(b1-3)GlcNAc': (0.993761, -1)}"}), "(G, node_color='r', edge_color='b', pos={\n 'NeuNAc(a2-3)Gal(b1-3)GalNAc': (0.852186, 0),\n 'GalNAc(a2-3)Gal(b1-3)GalNAc': (0.855664, 1),\n 'NeuNAc(a2-3)Gal(b1-3)GlcNAc': (0.993761, -1)})\n", (11661, 11854), True, 'import networkx as nx\n'), ((11916, 11928), 'networkx.DiGraph', 'nx.DiGraph', ([], {}), '()\n', (11926, 11928), True, 'import networkx as nx\n'), ((12776, 12805), 'collections.defaultdict', 'collections.defaultdict', (['list'], {}), '(list)\n', (12799, 12805), False, 'import collections\n'), ((14560, 14589), 'collections.defaultdict', 'collections.defaultdict', (['list'], {}), '(list)\n', (14583, 14589), False, 'import collections\n'), ((678, 695), 'pickle.load', 'pickle.load', (['inFH'], {}), '(inFH)\n', (689, 695), False, 'import pickle\n'), ((791, 808), 'pickle.load', 'pickle.load', (['inFH'], {}), '(inFH)\n', (802, 808), False, 'import pickle\n'), ((945, 962), 'pickle.load', 'pickle.load', (['inFH'], {}), '(inFH)\n', (956, 962), False, 'import pickle\n'), ((1032, 1049), 'pickle.load', 'pickle.load', (['inFH'], {}), '(inFH)\n', (1043, 1049), False, 'import pickle\n'), ((1283, 1300), 'pickle.load', 'pickle.load', (['inFH'], {}), '(inFH)\n', (1294, 1300), False, 'import pickle\n'), ((1537, 1554), 'pickle.load', 'pickle.load', (['inFH'], {}), '(inFH)\n', (1548, 1554), False, 'import pickle\n'), ((1634, 1651), 'pickle.load', 'pickle.load', (['inFH'], {}), '(inFH)\n', (1645, 1651), False, 'import pickle\n'), ((2254, 2271), 'pickle.load', 'pickle.load', (['inFH'], {}), '(inFH)\n', (2265, 2271), False, 'import pickle\n'), ((4211, 4273), 'plotnine.scale_fill_manual', 'p9.scale_fill_manual', ([], {'values': "['magenta', '#a84c3e', '#3e6ca8']"}), "(values=['magenta', '#a84c3e', '#3e6ca8'])\n", (4231, 4273), True, 'import plotnine as p9\n'), ((4870, 4888), 'plotnine.theme_minimal', 'p9.theme_minimal', ([], {}), '()\n', (4886, 4888), True, 'import plotnine as p9\n'), ((10890, 10913), 'pickle.dump', 'pickle.dump', (['uup', 'outFH'], {}), '(uup, outFH)\n', (10901, 10913), False, 'import pickle\n'), ((12466, 12480), 'plotnine.geom_path', 'p9.geom_path', ([], {}), '()\n', (12478, 12480), True, 'import plotnine as p9\n'), ((15619, 15672), 'plotnine.scale_fill_gradient', 'p9.scale_fill_gradient', ([], {'high': '"""#a84c3e"""', 'low': '"""#3e6ca8"""'}), "(high='#a84c3e', low='#3e6ca8')\n", (15641, 15672), True, 'import plotnine as p9\n'), ((3385, 3396), 'umap.UMAP', 'umap.UMAP', ([], {}), '()\n', (3394, 3396), False, 'import umap\n'), ((4147, 4196), 'plotnine.geom_point', 'p9.geom_point', ([], {'alpha': '(0.5)', 'size': '(3)', 'color': '"""#ffffff"""'}), "(alpha=0.5, size=3, color='#ffffff')\n", (4160, 4196), True, 'import plotnine as p9\n'), ((4391, 4418), 'random.randint', 'random.randint', (['(0)', '(16777215)'], {}), '(0, 16777215)\n', (4405, 4418), False, 'import random\n'), ((4778, 4845), 'plotnine.scale_color_manual', 'p9.scale_color_manual', ([], {'values': "(['#FFFFFF00'] + pathCols)", 'guide': '(False)'}), "(values=['#FFFFFF00'] + pathCols, guide=False)\n", (4799, 4845), True, 'import plotnine as p9\n'), ((7389, 7431), 're.split', 're.split', (['"""(\\\\([a,b][0-9]-[0-9]\\\\))"""', 'sGly'], {}), "('(\\\\([a,b][0-9]-[0-9]\\\\))', sGly)\n", (7397, 7431), False, 'import re\n'), ((12401, 12452), 'plotnine.scale_fill_manual', 'p9.scale_fill_manual', ([], {'values': "['magenta', '#3e6ca8']"}), "(values=['magenta', '#3e6ca8'])\n", (12421, 12452), True, 'import plotnine as p9\n'), ((14354, 14364), 'numpy.mean', 'np.mean', (['v'], {}), '(v)\n', (14361, 14364), True, 'import numpy as np\n'), ((14686, 14696), 'numpy.mean', 'np.mean', (['v'], {}), '(v)\n', (14693, 14696), True, 'import numpy as np\n'), ((15500, 15611), 'plotnine.scale_x_discrete', 'p9.scale_x_discrete', ([], {'limits': "[(revMonoDict[g[0] - 2] + '>' + revMonoDict[g[1] - 2]) for g, s in meanChanges]"}), "(limits=[(revMonoDict[g[0] - 2] + '>' + revMonoDict[g[1] -\n 2]) for g, s in meanChanges])\n", (15519, 15611), True, 'import plotnine as p9\n'), ((4073, 4087), 'plotnine.ggplot', 'p9.ggplot', (['uup'], {}), '(uup)\n', (4082, 4087), True, 'import plotnine as p9\n'), ((4090, 4138), 'plotnine.aes', 'p9.aes', ([], {'x': '"""UMAP1"""', 'y': '"""UMAP2"""', 'fill': '"""Glycan Type"""'}), "(x='UMAP1', y='UMAP2', fill='Glycan Type')\n", (4096, 4138), True, 'import plotnine as p9\n'), ((4743, 4757), 'plotnine.geom_path', 'p9.geom_path', ([], {}), '()\n', (4755, 4757), True, 'import plotnine as p9\n'), ((9460, 9511), 're.split', 're.split', (['"""(\\\\([a,b][0-9]-[0-9]\\\\)[\\\\[,\\\\]]?)"""', 'gly'], {}), "('(\\\\([a,b][0-9]-[0-9]\\\\)[\\\\[,\\\\]]?)', gly)\n", (9468, 9511), False, 'import re\n'), ((12157, 12175), 'numpy.array', 'np.array', (['genPaths'], {}), '(genPaths)\n', (12165, 12175), True, 'import numpy as np\n'), ((12337, 12386), 'plotnine.geom_point', 'p9.geom_point', ([], {'alpha': '(0.5)', 'size': '(3)', 'color': '"""#ffffff"""'}), "(alpha=0.5, size=3, color='#ffffff')\n", (12350, 12386), True, 'import plotnine as p9\n'), ((2748, 2770), 'numpy.array', 'np.array', (['allemblabel3'], {}), '(allemblabel3)\n', (2756, 2770), True, 'import numpy as np\n'), ((4663, 4725), 'plotnine.scale_fill_manual', 'p9.scale_fill_manual', ([], {'values': "['magenta', '#a84c3e', '#3e6ca8']"}), "(values=['magenta', '#a84c3e', '#3e6ca8'])\n", (4683, 4725), True, 'import plotnine as p9\n'), ((8442, 8493), 're.split', 're.split', (['"""(\\\\([a,b][0-9]-[0-9]\\\\)[\\\\[,\\\\]]?)"""', 'gly'], {}), "('(\\\\([a,b][0-9]-[0-9]\\\\)[\\\\[,\\\\]]?)', gly)\n", (8450, 8493), False, 'import re\n'), ((9590, 9627), 're.match', 're.match', (['"""\\\\([a,b][0-9]-[0-9]\\\\)"""', 'm'], {}), "('\\\\([a,b][0-9]-[0-9]\\\\)', m)\n", (9598, 9627), False, 'import re\n'), ((12226, 12328), 'plotnine.aes', 'p9.aes', ([], {'x': '"""UMAP1"""', 'y': '"""UMAP2"""', 'fill': '"""Glycan Type"""', 'color': '"""Generative Path"""', 'group': '"""Generative Path"""'}), "(x='UMAP1', y='UMAP2', fill='Glycan Type', color='Generative Path',\n group='Generative Path')\n", (12232, 12328), True, 'import plotnine as p9\n'), ((13481, 13511), 'numpy.argmax', 'np.argmax', (['distFromNonImmStart'], {}), '(distFromNonImmStart)\n', (13490, 13511), True, 'import numpy as np\n'), ((15317, 15378), 'plotnine.geom_bar', 'p9.geom_bar', ([], {'stat': '"""identity"""', 'position': '"""dodge"""', 'color': '"""black"""'}), "(stat='identity', position='dodge', color='black')\n", (15328, 15378), True, 'import plotnine as p9\n'), ((4595, 4644), 'plotnine.geom_point', 'p9.geom_point', ([], {'alpha': '(0.5)', 'size': '(3)', 'color': '"""#ffffff"""'}), "(alpha=0.5, size=3, color='#ffffff')\n", (4608, 4644), True, 'import plotnine as p9\n'), ((8584, 8621), 're.match', 're.match', (['"""\\\\([a,b][0-9]-[0-9]\\\\)"""', 'm'], {}), "('\\\\([a,b][0-9]-[0-9]\\\\)', m)\n", (8592, 8621), False, 'import re\n'), ((15236, 15250), 'plotnine.ggplot', 'p9.ggplot', (['gdp'], {}), '(gdp)\n', (15245, 15250), True, 'import plotnine as p9\n'), ((15253, 15302), 'plotnine.aes', 'p9.aes', ([], {'x': '"""Change"""', 'y': '"""Distance"""', 'fill': '"""Distance"""'}), "(x='Change', y='Distance', fill='Distance')\n", (15259, 15302), True, 'import plotnine as p9\n'), ((15420, 15476), 'plotnine.element_text', 'p9.element_text', ([], {'angle': '(45)', 'vjust': '(1)', 'hjust': '(1)', 'face': '"""bold"""'}), "(angle=45, vjust=1, hjust=1, face='bold')\n", (15435, 15476), True, 'import plotnine as p9\n'), ((4461, 4475), 'plotnine.ggplot', 'p9.ggplot', (['uup'], {}), '(uup)\n', (4470, 4475), True, 'import plotnine as p9\n'), ((4478, 4580), 'plotnine.aes', 'p9.aes', ([], {'x': '"""UMAP1"""', 'y': '"""UMAP2"""', 'fill': '"""Glycan Type"""', 'color': '"""Generative Path"""', 'group': '"""Generative Path"""'}), "(x='UMAP1', y='UMAP2', fill='Glycan Type', color='Generative Path',\n group='Generative Path')\n", (4484, 4580), True, 'import plotnine as p9\n'), ((9655, 9678), 're.sub', 're.sub', (['"""\\\\(b"""', '"""(a"""', 'm'], {}), "('\\\\(b', '(a', m)\n", (9661, 9678), False, 'import re\n'), ((9711, 9734), 're.sub', 're.sub', (['"""\\\\(a"""', '"""(b"""', 'm'], {}), "('\\\\(a', '(b', m)\n", (9717, 9734), False, 'import re\n'), ((9889, 9917), 'itertools.product', 'itertools.product', (['*glyProds'], {}), '(*glyProds)\n', (9906, 9917), False, 'import itertools\n'), ((8653, 8676), 're.sub', 're.sub', (['"""\\\\(b"""', '"""(a"""', 'm'], {}), "('\\\\(b', '(a', m)\n", (8659, 8676), False, 'import re\n'), ((8713, 8736), 're.sub', 're.sub', (['"""\\\\(a"""', '"""(b"""', 'm'], {}), "('\\\\(a', '(b', m)\n", (8719, 8736), False, 'import re\n'), ((8907, 8935), 'itertools.product', 'itertools.product', (['*glyProds'], {}), '(*glyProds)\n', (8924, 8935), False, 'import itertools\n'), ((12198, 12216), 'numpy.array', 'np.array', (['genPaths'], {}), '(genPaths)\n', (12206, 12216), True, 'import numpy as np\n'), ((13076, 13094), 'numpy.array', 'np.array', (['genPaths'], {}), '(genPaths)\n', (13084, 13094), True, 'import numpy as np\n'), ((13124, 13142), 'numpy.array', 'np.array', (['genPaths'], {}), '(genPaths)\n', (13132, 13142), True, 'import numpy as np\n'), ((13218, 13236), 'numpy.array', 'np.array', (['genPaths'], {}), '(genPaths)\n', (13226, 13236), True, 'import numpy as np\n'), ((13265, 13283), 'numpy.array', 'np.array', (['genPaths'], {}), '(genPaths)\n', (13273, 13283), True, 'import numpy as np\n'), ((13360, 13378), 'numpy.array', 'np.array', (['genPaths'], {}), '(genPaths)\n', (13368, 13378), True, 'import numpy as np\n'), ((13407, 13425), 'numpy.array', 'np.array', (['genPaths'], {}), '(genPaths)\n', (13415, 13425), True, 'import numpy as np\n')]
import logging import os import warnings import datetime import imutils import time from imutils.object_detection import non_max_suppression from imutils import paths import numpy as np import cv2 warnings.filterwarnings("ignore") def hog_video(): cap = cv2.VideoCapture("vtest.avi") hog = cv2.HOGDescriptor() hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector()) while True: ret, frame = cap.read() image=frame #cv2.imshow("capture",image) orig = image.copy() (rects, weights) = hog.detectMultiScale(image, winStride=(4,4), padding=(8,8), scale=0.5) rects = np.array([[x, y, x + w, y + h] for (x, y, w, h) in rects]) pick = non_max_suppression(rects, probs=None, overlapThresh=0.65) for (xA, yA, xB, yB) in pick: cv2.rectangle(image, (xA, yA), (xB, yB), (0, 255, 0), 2) cv2.imshow("After NMS", image) if cv2.waitKey(100)==27: break cap.release() cv2.destroyAllWindows() def main(): hog_video() if __name__=="__main__": main()
[ "cv2.rectangle", "cv2.HOGDescriptor", "cv2.imshow", "numpy.array", "imutils.object_detection.non_max_suppression", "cv2.destroyAllWindows", "cv2.VideoCapture", "cv2.HOGDescriptor_getDefaultPeopleDetector", "cv2.waitKey", "warnings.filterwarnings" ]
[((200, 233), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (223, 233), False, 'import warnings\n'), ((261, 290), 'cv2.VideoCapture', 'cv2.VideoCapture', (['"""vtest.avi"""'], {}), "('vtest.avi')\n", (277, 290), False, 'import cv2\n'), ((302, 321), 'cv2.HOGDescriptor', 'cv2.HOGDescriptor', ([], {}), '()\n', (319, 321), False, 'import cv2\n'), ((1056, 1079), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (1077, 1079), False, 'import cv2\n'), ((345, 389), 'cv2.HOGDescriptor_getDefaultPeopleDetector', 'cv2.HOGDescriptor_getDefaultPeopleDetector', ([], {}), '()\n', (387, 389), False, 'import cv2\n'), ((687, 743), 'numpy.array', 'np.array', (['[[x, y, x + w, y + h] for x, y, w, h in rects]'], {}), '([[x, y, x + w, y + h] for x, y, w, h in rects])\n', (695, 743), True, 'import numpy as np\n'), ((761, 819), 'imutils.object_detection.non_max_suppression', 'non_max_suppression', (['rects'], {'probs': 'None', 'overlapThresh': '(0.65)'}), '(rects, probs=None, overlapThresh=0.65)\n', (780, 819), False, 'from imutils.object_detection import non_max_suppression\n'), ((949, 979), 'cv2.imshow', 'cv2.imshow', (['"""After NMS"""', 'image'], {}), "('After NMS', image)\n", (959, 979), False, 'import cv2\n'), ((883, 939), 'cv2.rectangle', 'cv2.rectangle', (['image', '(xA, yA)', '(xB, yB)', '(0, 255, 0)', '(2)'], {}), '(image, (xA, yA), (xB, yB), (0, 255, 0), 2)\n', (896, 939), False, 'import cv2\n'), ((992, 1008), 'cv2.waitKey', 'cv2.waitKey', (['(100)'], {}), '(100)\n', (1003, 1008), False, 'import cv2\n')]
import numpy as np from collections import namedtuple import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D class AnalyticalKinematicsSolver: """ Analytical inverse kinematics solver for 6-axis industrial serial manipulators """ def __init__(self, robot_type, custom_paramset=None): """ Create robot instance with parameters """ ParamSet = namedtuple('ParamSet', ('a1', 'a2', 'b', 'c1', 'c2', 'c3', 'c4')) if robot_type == "kuka_youbot_arm": self.param_set = ParamSet(0.033, 0.0, 0.0, 0.147, 0.155, 0.135, 0.2175) elif robot_type == "katana_450_6M180": self.param_set = ParamSet(0.0, 0.0, 0.0, 0.2015, 0.190, 0.139, 0.1883) elif robot_type == "adept_viper_s650": self.param_set = ParamSet(0.075, -0.09, 0.0, 0.335, 0.270, 0.295, 0.08) elif robot_type == "custom": self.param_set = custom_paramset else: raise ValueError("Given robot type %s is not supported" % robot_type) def getWristCenterOrientation(self, theta): """ Return rotation matrix of wrist center R0c """ r11 = np.cos(theta[0])*np.cos(theta[1])*np.cos(theta[2]) - np.cos(theta[0])*np.sin(theta[1])*np.sin(theta[2]) r12 = -np.sin(theta[0]) r13 = np.cos(theta[0])*np.cos(theta[1])*np.sin(theta[2]) + np.cos(theta[0])*np.sin(theta[1])*np.cos(theta[2]) r21 = np.sin(theta[0])*np.cos(theta[1])*np.cos(theta[2]) - np.sin(theta[0])*np.sin(theta[1])*np.sin(theta[2]) r22 = np.cos(theta[0]) r23 = np.sin(theta[0])*np.cos(theta[1])*np.sin(theta[2]) + np.sin(theta[0])*np.sin(theta[1])*np.cos(theta[2]) r31 = -np.sin(theta[1])*np.cos(theta[2]) - np.cos(theta[1])*np.sin(theta[2]) r32 = 0.0 r33 = -np.sin(theta[1])*np.sin(theta[2]) + np.cos(theta[1])*np.cos(theta[2]) R = np.matrix([[r11, r12, r13], [r21, r22, r23], [r31, r32, r33]]) return R def getEndEffectorRelativeOrientation(self, theta): """ Return rotation matrix of end effecter w.r.t. wrist center Rce """ r11 = np.cos(theta[3]) * np.cos(theta[4]) * np.cos(theta[5]) - np.sin(theta[3]) * np.sin(theta[5]) r12 = - np.cos(theta[3]) * np.cos(theta[4]) * np.sin(theta[5]) - np.sin(theta[3]) * np.cos(theta[5]) r13 = np.cos(theta[3]) * np.sin(theta[4]) r21 = np.sin(theta[3]) * np.cos(theta[4]) * np.cos(theta[5]) + np.cos(theta[3]) * np.sin(theta[5]) r22 = -np.sin(theta[3]) * np.cos(theta[4]) * np.sin(theta[5]) + np.cos(theta[3]) * np.cos(theta[5]) r23 = np.sin(theta[3]) * np.sin(theta[4]) r31 = -np.sin(theta[4]) * np.cos(theta[5]) r32 = np.sin(theta[4]) * np.sin(theta[5]) r33 = np.cos(theta[4]) R = np.matrix([[r11, r12, r13], [r21, r22, r23], [r31, r32, r33]]) return R def getRollPitchYawOrientationMatrix(self, roll, pitch, yaw): """ Get rotation matrix """ r11 = np.cos(yaw) * np.cos(pitch) r12 = np.cos(yaw) * np.sin(pitch) * np.sin(roll) - np.sin(yaw) * np.cos(roll) r13 = np.cos(yaw) * np.sin(pitch) * np.cos(roll) + np.sin(yaw) * np.sin(roll) r21 = np.sin(yaw) * np.cos(pitch) r22 = np.sin(yaw) * np.sin(pitch) * np.sin(roll) + np.cos(yaw) * np.cos(roll) r23 = np.sin(yaw) * np.sin(pitch) * np.cos(roll) - np.cos(yaw) * np.sin(roll) r31 = - np.sin(pitch) r32 = np.cos(pitch) * np.sin(roll) r33 = np.cos(pitch) * np.cos(roll) R = np.matrix([[r11, r12, r13], [r21, r22, r23], [r31, r32, r33]]) return R def getRollPitchYawAngle(self, R): """ Get roll, pitch and yaw angle from rotation matrix """ yaw = np.arctan2(R[1, 0], R[0, 0]) #yaw = np.arctan2(R[1, 0], R[0, 0]) + np.pi #yaw = np.arctan2(R[1, 0], R[0, 0]) - np.pi pitch = np.arctan2(-R[2, 0], R[0, 0] * np.cos(yaw) + R[1, 0] * np.sin(yaw)) roll = np.arctan2(R[0, 2] * np.sin(yaw) - R[1, 2] * np.cos(yaw), -R[0, 1] * np.sin(yaw) + R[1, 1] * np.cos(yaw) ) return roll, pitch, yaw # TODO: Implement quartanion def solveForwardKinematics(self, theta): """ Return end-effector position vector (ux, uy, uz) and orientation matrix R0e """ R0c = self.getWristCenterOrientation(theta) Rce = self.getEndEffectorRelativeOrientation(theta) R0e = R0c * Rce phi3 = np.arctan2(self.param_set.a2, self.param_set.c3) k = np.sqrt(self.param_set.a2**2 + self.param_set.c3**2) cx1 = self.param_set.c2 * np.sin(theta[1]) + k * np.sin(theta[1] + theta[2] + phi3) + self.param_set.a1 cy1 = self.param_set.b cz1 = self.param_set.c2 * np.cos(theta[1]) + k * np.cos(theta[1] + theta[2] + phi3) c1 = np.matrix([[cx1], [cy1], [cz1]]) cx0 = c1[0, 0] * np.cos(theta[0]) - c1[1, 0] * np.sin(theta[0]) cy0 = c1[0, 0] * np.sin(theta[0]) + c1[1, 0] * np.cos(theta[0]) cz0 = c1[2, 0] + self.param_set.c1 c0 = np.matrix([[cx0], [cy0], [cz0]]) u = c0 + self.param_set.c4 * R0e * np.matrix([[0], [0], [1]]) return u, R0e def solveInverseKinematics(self, u, R0e): """ Return inverse kinematics solution given u and R0e """ c = u - self.param_set.c4 * R0e * np.matrix([[0], [0], [1]]) n_x1 = np.sqrt(c[0, 0]**2 + c[1, 0]**2 - self.param_set.b**2) - self.param_set.a1 s1_sq = n_x1**2 + (c[2, 0] - self.param_set.c1)**2 s2_sq = (n_x1 + 2.0 * self.param_set.a1)**2 + (c[2, 0] - self.param_set.c1)**2 k_sq = self.param_set.a2**2 + self.param_set.c3**2 theta1_1 = np.arctan2(c[1, 0], c[0, 0]) - np.arctan2(self.param_set.b, n_x1 + self.param_set.a1) theta1_2 = np.arctan2(c[1, 0], c[0, 0]) + np.arctan2(self.param_set.b, n_x1 + self.param_set.a1) - np.pi theta2_1 = -np.arccos( (s1_sq + self.param_set.c2**2 - k_sq) / (2.0 * np.sqrt(s1_sq) * self.param_set.c2 ) ) + np.arctan2(n_x1, c[2, 0] - self.param_set.c1) theta2_2 = np.arccos( (s1_sq + self.param_set.c2**2 - k_sq) / (2.0 * np.sqrt(s1_sq) * self.param_set.c2 ) ) + np.arctan2(n_x1, c[2, 0] - self.param_set.c1) theta2_3 = -np.arccos( (s2_sq + self.param_set.c2**2 - k_sq) / (2.0 * np.sqrt(s2_sq) * self.param_set.c2 ) ) - np.arctan2(n_x1+2.0*self.param_set.a1, c[2, 0] - self.param_set.c1) theta2_4 = np.arccos( (s2_sq + self.param_set.c2**2 - k_sq) / (2.0 * np.sqrt(s2_sq) * self.param_set.c2 ) ) - np.arctan2(n_x1+2.0*self.param_set.a1, c[2, 0] - self.param_set.c1) theta3_1 = np.arccos( (s1_sq - self.param_set.c2**2 - k_sq) / (2.0 * self.param_set.c2 * np.sqrt(k_sq) ) ) - np.arctan2(self.param_set.a2, self.param_set.c3) theta3_2 = -np.arccos( (s1_sq - self.param_set.c2**2 - k_sq) / (2.0 * self.param_set.c2 * np.sqrt(k_sq) ) ) - np.arctan2(self.param_set.a2, self.param_set.c3) theta3_3 = np.arccos( (s2_sq - self.param_set.c2**2 - k_sq) / (2.0 * self.param_set.c2 * np.sqrt(k_sq) ) ) - np.arctan2(self.param_set.a2, self.param_set.c3) theta3_4 = -np.arccos( (s2_sq - self.param_set.c2**2 - k_sq) / (2.0 * self.param_set.c2 * np.sqrt(k_sq) ) ) - np.arctan2(self.param_set.a2, self.param_set.c3) s1_1 = np.sin(theta1_1) s1_2 = np.sin(theta1_2) s1_3 = np.sin(theta1_1) s1_4 = np.sin(theta1_2) c1_1 = np.cos(theta1_1) c1_2 = np.cos(theta1_2) c1_3 = np.cos(theta1_1) c1_4 = np.cos(theta1_2) s23_1 = np.sin(theta2_1 + theta3_1) s23_2 = np.sin(theta2_2 + theta3_2) s23_3 = np.sin(theta2_3 + theta3_3) s23_4 = np.sin(theta2_4 + theta3_4) c23_1 = np.cos(theta2_1 + theta3_1) c23_2 = np.cos(theta2_2 + theta3_2) c23_3 = np.cos(theta2_3 + theta3_3) c23_4 = np.cos(theta2_4 + theta3_4) m1 = R0e[0, 2] * s23_1 * c1_1 + R0e[1, 2] * s23_1 * s1_1 + R0e[2, 2] * c23_1 m2 = R0e[0, 2] * s23_2 * c1_2 + R0e[1, 2] * s23_2 * s1_2 + R0e[2, 2] * c23_2 m3 = R0e[0, 2] * s23_3 * c1_3 + R0e[1, 2] * s23_3 * s1_3 + R0e[2, 2] * c23_3 m4 = R0e[0, 2] * s23_4 * c1_4 + R0e[1, 2] * s23_4 * s1_4 + R0e[2, 2] * c23_4 theta4_1 = np.arctan2(R0e[1, 2] * c1_1 - R0e[0, 2] * s1_1, R0e[0, 2] * c23_1 * c1_1 + R0e[1, 2] * c23_1 * s1_1 - R0e[2, 2] * s23_1) theta4_2 = np.arctan2(R0e[1, 2] * c1_2 - R0e[0, 2] * s1_2, R0e[0, 2] * c23_2 * c1_2 + R0e[1, 2] * c23_2 * s1_2 - R0e[2, 2] * s23_2) theta4_3 = np.arctan2(R0e[1, 2] * c1_3 - R0e[0, 2] * s1_3, R0e[0, 2] * c23_3 * c1_3 + R0e[1, 2] * c23_3 * s1_3 - R0e[2, 2] * s23_3) theta4_4 = np.arctan2(R0e[1, 2] * c1_4 - R0e[0, 2] * s1_4, R0e[0, 2] * c23_4 * c1_4 + R0e[1, 2] * c23_4 * s1_4 - R0e[2, 2] * s23_4) theta4_5 = theta4_1 + np.pi theta4_6 = theta4_2 + np.pi theta4_7 = theta4_3 + np.pi theta4_8 = theta4_4 + np.pi theta5_1 = np.arctan2(np.sqrt(1-m1**2), m1) theta5_2 = np.arctan2(np.sqrt(1-m2**2), m2) theta5_3 = np.arctan2(np.sqrt(1-m3**2), m3) theta5_4 = np.arctan2(np.sqrt(1-m4**2), m4) theta5_5 = -theta5_1 theta5_6 = -theta5_2 theta5_7 = -theta5_3 theta5_8 = -theta5_4 theta6_1 = np.arctan2(R0e[0, 1] * s23_1 * c1_1 + R0e[1, 1] * s23_1 * s1_1 + R0e[2, 1] * c23_1, -R0e[0, 0] * s23_1 * c1_1 - R0e[1, 0] * s23_1 * s1_1 - R0e[2, 0] * c23_1) theta6_2 = np.arctan2(R0e[0, 1] * s23_2 * c1_2 + R0e[1, 1] * s23_2 * s1_2 + R0e[2, 1] * c23_2, -R0e[0, 0] * s23_2 * c1_2 - R0e[1, 0] * s23_2 * s1_2 - R0e[2, 0] * c23_2) theta6_3 = np.arctan2(R0e[0, 1] * s23_3 * c1_3 + R0e[1, 1] * s23_3 * s1_3 + R0e[2, 1] * c23_3, -R0e[0, 0] * s23_3 * c1_3 - R0e[1, 0] * s23_3 * s1_3 - R0e[2, 0] * c23_3) theta6_4 = np.arctan2(R0e[0, 1] * s23_4 * c1_4 + R0e[1, 1] * s23_4 * s1_4 + R0e[2, 1] * c23_4, -R0e[0, 0] * s23_4 * c1_4 - R0e[1, 0] * s23_4 * s1_4 - R0e[2, 0] * c23_4) theta6_5 = theta6_1 - np.pi theta6_6 = theta6_2 - np.pi theta6_7 = theta6_3 - np.pi theta6_8 = theta6_4 - np.pi theta_set1 = [theta1_1, theta2_1, theta3_1, theta4_1, theta5_1, theta6_1] # lefty - above - nonflip theta_set2 = [theta1_1, theta2_2, theta3_2, theta4_2, theta5_2, theta6_2] # lefty - bellow - nonflip theta_set3 = [theta1_2, theta2_3, theta3_3, theta4_3, theta5_3, theta6_3] # righty - bellow - nonflip theta_set4 = [theta1_2, theta2_4, theta3_4, theta4_4, theta5_4, theta6_4] # righty - above - flip theta_set5 = [theta1_1, theta2_1, theta3_1, theta4_5, theta5_5, theta6_5] # lefty - above - flip theta_set6 = [theta1_1, theta2_2, theta3_2, theta4_6, theta5_6, theta6_6] # lefty - bellow - flip theta_set7 = [theta1_2, theta2_3, theta3_3, theta4_7, theta5_7, theta6_7] # righty - bellow - flip theta_set8 = [theta1_2, theta2_4, theta3_4, theta4_8, theta5_8, theta6_8] # righty - above - nonflip return theta_set1, theta_set2, theta_set3, theta_set4, theta_set5, theta_set6, theta_set7, theta_set8 if __name__ == '__main__': # Instanciation kinematics_solver = AnalyticalKinematicsSolver("adept_viper_s650") # Set angles theta = [0.0*np.pi/180.0, 30.0*np.pi/180.0, 90.0*np.pi/180.0, 0.0, 10.0*np.pi/180.0, 0.0] # (lefty, above, nonflip) # Calcuate forward kinematics solution pos_fk, R_fk = kinematics_solver.solveForwardKinematics(theta) # Get roll, pitch, yaw angle roll, pitch, yaw = kinematics_solver.getRollPitchYawAngle(R_fk) # Get roll, pitch, yaw orientation matrix R_rpy = kinematics_solver.getRollPitchYawOrientationMatrix(roll, pitch, yaw) # Verify the forward kinematics solution by inverse kinematics theta_ik1, theta_ik2, theta_ik3, theta_ik4, theta_ik5, theta_ik6, theta_ik7, theta_ik8 = kinematics_solver.solveInverseKinematics(pos_fk, R_rpy) print(pos_fk) print(theta) print(theta_ik1)
[ "collections.namedtuple", "numpy.sqrt", "numpy.arctan2", "numpy.cos", "numpy.sin", "numpy.matrix" ]
[((409, 474), 'collections.namedtuple', 'namedtuple', (['"""ParamSet"""', "('a1', 'a2', 'b', 'c1', 'c2', 'c3', 'c4')"], {}), "('ParamSet', ('a1', 'a2', 'b', 'c1', 'c2', 'c3', 'c4'))\n", (419, 474), False, 'from collections import namedtuple\n'), ((1573, 1589), 'numpy.cos', 'np.cos', (['theta[0]'], {}), '(theta[0])\n', (1579, 1589), True, 'import numpy as np\n'), ((1908, 1970), 'numpy.matrix', 'np.matrix', (['[[r11, r12, r13], [r21, r22, r23], [r31, r32, r33]]'], {}), '([[r11, r12, r13], [r21, r22, r23], [r31, r32, r33]])\n', (1917, 1970), True, 'import numpy as np\n'), ((2788, 2804), 'numpy.cos', 'np.cos', (['theta[4]'], {}), '(theta[4])\n', (2794, 2804), True, 'import numpy as np\n'), ((2817, 2879), 'numpy.matrix', 'np.matrix', (['[[r11, r12, r13], [r21, r22, r23], [r31, r32, r33]]'], {}), '([[r11, r12, r13], [r21, r22, r23], [r31, r32, r33]])\n', (2826, 2879), True, 'import numpy as np\n'), ((3573, 3635), 'numpy.matrix', 'np.matrix', (['[[r11, r12, r13], [r21, r22, r23], [r31, r32, r33]]'], {}), '([[r11, r12, r13], [r21, r22, r23], [r31, r32, r33]])\n', (3582, 3635), True, 'import numpy as np\n'), ((3792, 3820), 'numpy.arctan2', 'np.arctan2', (['R[1, 0]', 'R[0, 0]'], {}), '(R[1, 0], R[0, 0])\n', (3802, 3820), True, 'import numpy as np\n'), ((4510, 4558), 'numpy.arctan2', 'np.arctan2', (['self.param_set.a2', 'self.param_set.c3'], {}), '(self.param_set.a2, self.param_set.c3)\n', (4520, 4558), True, 'import numpy as np\n'), ((4571, 4627), 'numpy.sqrt', 'np.sqrt', (['(self.param_set.a2 ** 2 + self.param_set.c3 ** 2)'], {}), '(self.param_set.a2 ** 2 + self.param_set.c3 ** 2)\n', (4578, 4627), True, 'import numpy as np\n'), ((4873, 4905), 'numpy.matrix', 'np.matrix', (['[[cx1], [cy1], [cz1]]'], {}), '([[cx1], [cy1], [cz1]])\n', (4882, 4905), True, 'import numpy as np\n'), ((5111, 5143), 'numpy.matrix', 'np.matrix', (['[[cx0], [cy0], [cz0]]'], {}), '([[cx0], [cy0], [cz0]])\n', (5120, 5143), True, 'import numpy as np\n'), ((7343, 7359), 'numpy.sin', 'np.sin', (['theta1_1'], {}), '(theta1_1)\n', (7349, 7359), True, 'import numpy as np\n'), ((7375, 7391), 'numpy.sin', 'np.sin', (['theta1_2'], {}), '(theta1_2)\n', (7381, 7391), True, 'import numpy as np\n'), ((7407, 7423), 'numpy.sin', 'np.sin', (['theta1_1'], {}), '(theta1_1)\n', (7413, 7423), True, 'import numpy as np\n'), ((7439, 7455), 'numpy.sin', 'np.sin', (['theta1_2'], {}), '(theta1_2)\n', (7445, 7455), True, 'import numpy as np\n'), ((7472, 7488), 'numpy.cos', 'np.cos', (['theta1_1'], {}), '(theta1_1)\n', (7478, 7488), True, 'import numpy as np\n'), ((7504, 7520), 'numpy.cos', 'np.cos', (['theta1_2'], {}), '(theta1_2)\n', (7510, 7520), True, 'import numpy as np\n'), ((7536, 7552), 'numpy.cos', 'np.cos', (['theta1_1'], {}), '(theta1_1)\n', (7542, 7552), True, 'import numpy as np\n'), ((7568, 7584), 'numpy.cos', 'np.cos', (['theta1_2'], {}), '(theta1_2)\n', (7574, 7584), True, 'import numpy as np\n'), ((7602, 7629), 'numpy.sin', 'np.sin', (['(theta2_1 + theta3_1)'], {}), '(theta2_1 + theta3_1)\n', (7608, 7629), True, 'import numpy as np\n'), ((7646, 7673), 'numpy.sin', 'np.sin', (['(theta2_2 + theta3_2)'], {}), '(theta2_2 + theta3_2)\n', (7652, 7673), True, 'import numpy as np\n'), ((7690, 7717), 'numpy.sin', 'np.sin', (['(theta2_3 + theta3_3)'], {}), '(theta2_3 + theta3_3)\n', (7696, 7717), True, 'import numpy as np\n'), ((7734, 7761), 'numpy.sin', 'np.sin', (['(theta2_4 + theta3_4)'], {}), '(theta2_4 + theta3_4)\n', (7740, 7761), True, 'import numpy as np\n'), ((7779, 7806), 'numpy.cos', 'np.cos', (['(theta2_1 + theta3_1)'], {}), '(theta2_1 + theta3_1)\n', (7785, 7806), True, 'import numpy as np\n'), ((7823, 7850), 'numpy.cos', 'np.cos', (['(theta2_2 + theta3_2)'], {}), '(theta2_2 + theta3_2)\n', (7829, 7850), True, 'import numpy as np\n'), ((7867, 7894), 'numpy.cos', 'np.cos', (['(theta2_3 + theta3_3)'], {}), '(theta2_3 + theta3_3)\n', (7873, 7894), True, 'import numpy as np\n'), ((7911, 7938), 'numpy.cos', 'np.cos', (['(theta2_4 + theta3_4)'], {}), '(theta2_4 + theta3_4)\n', (7917, 7938), True, 'import numpy as np\n'), ((8308, 8433), 'numpy.arctan2', 'np.arctan2', (['(R0e[1, 2] * c1_1 - R0e[0, 2] * s1_1)', '(R0e[0, 2] * c23_1 * c1_1 + R0e[1, 2] * c23_1 * s1_1 - R0e[2, 2] * s23_1)'], {}), '(R0e[1, 2] * c1_1 - R0e[0, 2] * s1_1, R0e[0, 2] * c23_1 * c1_1 + \n R0e[1, 2] * c23_1 * s1_1 - R0e[2, 2] * s23_1)\n', (8318, 8433), True, 'import numpy as np\n'), ((8448, 8573), 'numpy.arctan2', 'np.arctan2', (['(R0e[1, 2] * c1_2 - R0e[0, 2] * s1_2)', '(R0e[0, 2] * c23_2 * c1_2 + R0e[1, 2] * c23_2 * s1_2 - R0e[2, 2] * s23_2)'], {}), '(R0e[1, 2] * c1_2 - R0e[0, 2] * s1_2, R0e[0, 2] * c23_2 * c1_2 + \n R0e[1, 2] * c23_2 * s1_2 - R0e[2, 2] * s23_2)\n', (8458, 8573), True, 'import numpy as np\n'), ((8588, 8713), 'numpy.arctan2', 'np.arctan2', (['(R0e[1, 2] * c1_3 - R0e[0, 2] * s1_3)', '(R0e[0, 2] * c23_3 * c1_3 + R0e[1, 2] * c23_3 * s1_3 - R0e[2, 2] * s23_3)'], {}), '(R0e[1, 2] * c1_3 - R0e[0, 2] * s1_3, R0e[0, 2] * c23_3 * c1_3 + \n R0e[1, 2] * c23_3 * s1_3 - R0e[2, 2] * s23_3)\n', (8598, 8713), True, 'import numpy as np\n'), ((8728, 8853), 'numpy.arctan2', 'np.arctan2', (['(R0e[1, 2] * c1_4 - R0e[0, 2] * s1_4)', '(R0e[0, 2] * c23_4 * c1_4 + R0e[1, 2] * c23_4 * s1_4 - R0e[2, 2] * s23_4)'], {}), '(R0e[1, 2] * c1_4 - R0e[0, 2] * s1_4, R0e[0, 2] * c23_4 * c1_4 + \n R0e[1, 2] * c23_4 * s1_4 - R0e[2, 2] * s23_4)\n', (8738, 8853), True, 'import numpy as np\n'), ((9340, 9505), 'numpy.arctan2', 'np.arctan2', (['(R0e[0, 1] * s23_1 * c1_1 + R0e[1, 1] * s23_1 * s1_1 + R0e[2, 1] * c23_1)', '(-R0e[0, 0] * s23_1 * c1_1 - R0e[1, 0] * s23_1 * s1_1 - R0e[2, 0] * c23_1)'], {}), '(R0e[0, 1] * s23_1 * c1_1 + R0e[1, 1] * s23_1 * s1_1 + R0e[2, 1] *\n c23_1, -R0e[0, 0] * s23_1 * c1_1 - R0e[1, 0] * s23_1 * s1_1 - R0e[2, 0] *\n c23_1)\n', (9350, 9505), True, 'import numpy as np\n'), ((9517, 9682), 'numpy.arctan2', 'np.arctan2', (['(R0e[0, 1] * s23_2 * c1_2 + R0e[1, 1] * s23_2 * s1_2 + R0e[2, 1] * c23_2)', '(-R0e[0, 0] * s23_2 * c1_2 - R0e[1, 0] * s23_2 * s1_2 - R0e[2, 0] * c23_2)'], {}), '(R0e[0, 1] * s23_2 * c1_2 + R0e[1, 1] * s23_2 * s1_2 + R0e[2, 1] *\n c23_2, -R0e[0, 0] * s23_2 * c1_2 - R0e[1, 0] * s23_2 * s1_2 - R0e[2, 0] *\n c23_2)\n', (9527, 9682), True, 'import numpy as np\n'), ((9694, 9859), 'numpy.arctan2', 'np.arctan2', (['(R0e[0, 1] * s23_3 * c1_3 + R0e[1, 1] * s23_3 * s1_3 + R0e[2, 1] * c23_3)', '(-R0e[0, 0] * s23_3 * c1_3 - R0e[1, 0] * s23_3 * s1_3 - R0e[2, 0] * c23_3)'], {}), '(R0e[0, 1] * s23_3 * c1_3 + R0e[1, 1] * s23_3 * s1_3 + R0e[2, 1] *\n c23_3, -R0e[0, 0] * s23_3 * c1_3 - R0e[1, 0] * s23_3 * s1_3 - R0e[2, 0] *\n c23_3)\n', (9704, 9859), True, 'import numpy as np\n'), ((9871, 10036), 'numpy.arctan2', 'np.arctan2', (['(R0e[0, 1] * s23_4 * c1_4 + R0e[1, 1] * s23_4 * s1_4 + R0e[2, 1] * c23_4)', '(-R0e[0, 0] * s23_4 * c1_4 - R0e[1, 0] * s23_4 * s1_4 - R0e[2, 0] * c23_4)'], {}), '(R0e[0, 1] * s23_4 * c1_4 + R0e[1, 1] * s23_4 * s1_4 + R0e[2, 1] *\n c23_4, -R0e[0, 0] * s23_4 * c1_4 - R0e[1, 0] * s23_4 * s1_4 - R0e[2, 0] *\n c23_4)\n', (9881, 10036), True, 'import numpy as np\n'), ((1306, 1322), 'numpy.sin', 'np.sin', (['theta[0]'], {}), '(theta[0])\n', (1312, 1322), True, 'import numpy as np\n'), ((2372, 2388), 'numpy.cos', 'np.cos', (['theta[3]'], {}), '(theta[3])\n', (2378, 2388), True, 'import numpy as np\n'), ((2391, 2407), 'numpy.sin', 'np.sin', (['theta[4]'], {}), '(theta[4])\n', (2397, 2407), True, 'import numpy as np\n'), ((2637, 2653), 'numpy.sin', 'np.sin', (['theta[3]'], {}), '(theta[3])\n', (2643, 2653), True, 'import numpy as np\n'), ((2656, 2672), 'numpy.sin', 'np.sin', (['theta[4]'], {}), '(theta[4])\n', (2662, 2672), True, 'import numpy as np\n'), ((2707, 2723), 'numpy.cos', 'np.cos', (['theta[5]'], {}), '(theta[5])\n', (2713, 2723), True, 'import numpy as np\n'), ((2738, 2754), 'numpy.sin', 'np.sin', (['theta[4]'], {}), '(theta[4])\n', (2744, 2754), True, 'import numpy as np\n'), ((2757, 2773), 'numpy.sin', 'np.sin', (['theta[5]'], {}), '(theta[5])\n', (2763, 2773), True, 'import numpy as np\n'), ((3031, 3042), 'numpy.cos', 'np.cos', (['yaw'], {}), '(yaw)\n', (3037, 3042), True, 'import numpy as np\n'), ((3045, 3058), 'numpy.cos', 'np.cos', (['pitch'], {}), '(pitch)\n', (3051, 3058), True, 'import numpy as np\n'), ((3245, 3256), 'numpy.sin', 'np.sin', (['yaw'], {}), '(yaw)\n', (3251, 3256), True, 'import numpy as np\n'), ((3259, 3272), 'numpy.cos', 'np.cos', (['pitch'], {}), '(pitch)\n', (3265, 3272), True, 'import numpy as np\n'), ((3461, 3474), 'numpy.sin', 'np.sin', (['pitch'], {}), '(pitch)\n', (3467, 3474), True, 'import numpy as np\n'), ((3489, 3502), 'numpy.cos', 'np.cos', (['pitch'], {}), '(pitch)\n', (3495, 3502), True, 'import numpy as np\n'), ((3505, 3517), 'numpy.sin', 'np.sin', (['roll'], {}), '(roll)\n', (3511, 3517), True, 'import numpy as np\n'), ((3532, 3545), 'numpy.cos', 'np.cos', (['pitch'], {}), '(pitch)\n', (3538, 3545), True, 'import numpy as np\n'), ((3548, 3560), 'numpy.cos', 'np.cos', (['roll'], {}), '(roll)\n', (3554, 3560), True, 'import numpy as np\n'), ((5455, 5515), 'numpy.sqrt', 'np.sqrt', (['(c[0, 0] ** 2 + c[1, 0] ** 2 - self.param_set.b ** 2)'], {}), '(c[0, 0] ** 2 + c[1, 0] ** 2 - self.param_set.b ** 2)\n', (5462, 5515), True, 'import numpy as np\n'), ((5755, 5783), 'numpy.arctan2', 'np.arctan2', (['c[1, 0]', 'c[0, 0]'], {}), '(c[1, 0], c[0, 0])\n', (5765, 5783), True, 'import numpy as np\n'), ((5786, 5840), 'numpy.arctan2', 'np.arctan2', (['self.param_set.b', '(n_x1 + self.param_set.a1)'], {}), '(self.param_set.b, n_x1 + self.param_set.a1)\n', (5796, 5840), True, 'import numpy as np\n'), ((6074, 6119), 'numpy.arctan2', 'np.arctan2', (['n_x1', '(c[2, 0] - self.param_set.c1)'], {}), '(n_x1, c[2, 0] - self.param_set.c1)\n', (6084, 6119), True, 'import numpy as np\n'), ((6238, 6283), 'numpy.arctan2', 'np.arctan2', (['n_x1', '(c[2, 0] - self.param_set.c1)'], {}), '(n_x1, c[2, 0] - self.param_set.c1)\n', (6248, 6283), True, 'import numpy as np\n'), ((6404, 6475), 'numpy.arctan2', 'np.arctan2', (['(n_x1 + 2.0 * self.param_set.a1)', '(c[2, 0] - self.param_set.c1)'], {}), '(n_x1 + 2.0 * self.param_set.a1, c[2, 0] - self.param_set.c1)\n', (6414, 6475), True, 'import numpy as np\n'), ((6590, 6661), 'numpy.arctan2', 'np.arctan2', (['(n_x1 + 2.0 * self.param_set.a1)', '(c[2, 0] - self.param_set.c1)'], {}), '(n_x1 + 2.0 * self.param_set.a1, c[2, 0] - self.param_set.c1)\n', (6600, 6661), True, 'import numpy as np\n'), ((6776, 6824), 'numpy.arctan2', 'np.arctan2', (['self.param_set.a2', 'self.param_set.c3'], {}), '(self.param_set.a2, self.param_set.c3)\n', (6786, 6824), True, 'import numpy as np\n'), ((6943, 6991), 'numpy.arctan2', 'np.arctan2', (['self.param_set.a2', 'self.param_set.c3'], {}), '(self.param_set.a2, self.param_set.c3)\n', (6953, 6991), True, 'import numpy as np\n'), ((7110, 7158), 'numpy.arctan2', 'np.arctan2', (['self.param_set.a2', 'self.param_set.c3'], {}), '(self.param_set.a2, self.param_set.c3)\n', (7120, 7158), True, 'import numpy as np\n'), ((7277, 7325), 'numpy.arctan2', 'np.arctan2', (['self.param_set.a2', 'self.param_set.c3'], {}), '(self.param_set.a2, self.param_set.c3)\n', (7287, 7325), True, 'import numpy as np\n'), ((9025, 9045), 'numpy.sqrt', 'np.sqrt', (['(1 - m1 ** 2)'], {}), '(1 - m1 ** 2)\n', (9032, 9045), True, 'import numpy as np\n'), ((9077, 9097), 'numpy.sqrt', 'np.sqrt', (['(1 - m2 ** 2)'], {}), '(1 - m2 ** 2)\n', (9084, 9097), True, 'import numpy as np\n'), ((9129, 9149), 'numpy.sqrt', 'np.sqrt', (['(1 - m3 ** 2)'], {}), '(1 - m3 ** 2)\n', (9136, 9149), True, 'import numpy as np\n'), ((9181, 9201), 'numpy.sqrt', 'np.sqrt', (['(1 - m4 ** 2)'], {}), '(1 - m4 ** 2)\n', (9188, 9201), True, 'import numpy as np\n'), ((1221, 1237), 'numpy.cos', 'np.cos', (['theta[2]'], {}), '(theta[2])\n', (1227, 1237), True, 'import numpy as np\n'), ((1274, 1290), 'numpy.sin', 'np.sin', (['theta[2]'], {}), '(theta[2])\n', (1280, 1290), True, 'import numpy as np\n'), ((1371, 1387), 'numpy.sin', 'np.sin', (['theta[2]'], {}), '(theta[2])\n', (1377, 1387), True, 'import numpy as np\n'), ((1424, 1440), 'numpy.cos', 'np.cos', (['theta[2]'], {}), '(theta[2])\n', (1430, 1440), True, 'import numpy as np\n'), ((1489, 1505), 'numpy.cos', 'np.cos', (['theta[2]'], {}), '(theta[2])\n', (1495, 1505), True, 'import numpy as np\n'), ((1542, 1558), 'numpy.sin', 'np.sin', (['theta[2]'], {}), '(theta[2])\n', (1548, 1558), True, 'import numpy as np\n'), ((1638, 1654), 'numpy.sin', 'np.sin', (['theta[2]'], {}), '(theta[2])\n', (1644, 1654), True, 'import numpy as np\n'), ((1691, 1707), 'numpy.cos', 'np.cos', (['theta[2]'], {}), '(theta[2])\n', (1697, 1707), True, 'import numpy as np\n'), ((1740, 1756), 'numpy.cos', 'np.cos', (['theta[2]'], {}), '(theta[2])\n', (1746, 1756), True, 'import numpy as np\n'), ((1759, 1775), 'numpy.cos', 'np.cos', (['theta[1]'], {}), '(theta[1])\n', (1765, 1775), True, 'import numpy as np\n'), ((1776, 1792), 'numpy.sin', 'np.sin', (['theta[2]'], {}), '(theta[2])\n', (1782, 1792), True, 'import numpy as np\n'), ((1843, 1859), 'numpy.sin', 'np.sin', (['theta[2]'], {}), '(theta[2])\n', (1849, 1859), True, 'import numpy as np\n'), ((1862, 1878), 'numpy.cos', 'np.cos', (['theta[1]'], {}), '(theta[1])\n', (1868, 1878), True, 'import numpy as np\n'), ((1879, 1895), 'numpy.cos', 'np.cos', (['theta[2]'], {}), '(theta[2])\n', (1885, 1895), True, 'import numpy as np\n'), ((2194, 2210), 'numpy.cos', 'np.cos', (['theta[5]'], {}), '(theta[5])\n', (2200, 2210), True, 'import numpy as np\n'), ((2213, 2229), 'numpy.sin', 'np.sin', (['theta[3]'], {}), '(theta[3])\n', (2219, 2229), True, 'import numpy as np\n'), ((2232, 2248), 'numpy.sin', 'np.sin', (['theta[5]'], {}), '(theta[5])\n', (2238, 2248), True, 'import numpy as np\n'), ((2303, 2319), 'numpy.sin', 'np.sin', (['theta[5]'], {}), '(theta[5])\n', (2309, 2319), True, 'import numpy as np\n'), ((2322, 2338), 'numpy.sin', 'np.sin', (['theta[3]'], {}), '(theta[3])\n', (2328, 2338), True, 'import numpy as np\n'), ((2341, 2357), 'numpy.cos', 'np.cos', (['theta[5]'], {}), '(theta[5])\n', (2347, 2357), True, 'import numpy as np\n'), ((2460, 2476), 'numpy.cos', 'np.cos', (['theta[5]'], {}), '(theta[5])\n', (2466, 2476), True, 'import numpy as np\n'), ((2479, 2495), 'numpy.cos', 'np.cos', (['theta[3]'], {}), '(theta[3])\n', (2485, 2495), True, 'import numpy as np\n'), ((2498, 2514), 'numpy.sin', 'np.sin', (['theta[5]'], {}), '(theta[5])\n', (2504, 2514), True, 'import numpy as np\n'), ((2568, 2584), 'numpy.sin', 'np.sin', (['theta[5]'], {}), '(theta[5])\n', (2574, 2584), True, 'import numpy as np\n'), ((2587, 2603), 'numpy.cos', 'np.cos', (['theta[3]'], {}), '(theta[3])\n', (2593, 2603), True, 'import numpy as np\n'), ((2606, 2622), 'numpy.cos', 'np.cos', (['theta[5]'], {}), '(theta[5])\n', (2612, 2622), True, 'import numpy as np\n'), ((2688, 2704), 'numpy.sin', 'np.sin', (['theta[4]'], {}), '(theta[4])\n', (2694, 2704), True, 'import numpy as np\n'), ((3103, 3115), 'numpy.sin', 'np.sin', (['roll'], {}), '(roll)\n', (3109, 3115), True, 'import numpy as np\n'), ((3118, 3129), 'numpy.sin', 'np.sin', (['yaw'], {}), '(yaw)\n', (3124, 3129), True, 'import numpy as np\n'), ((3132, 3144), 'numpy.cos', 'np.cos', (['roll'], {}), '(roll)\n', (3138, 3144), True, 'import numpy as np\n'), ((3189, 3201), 'numpy.cos', 'np.cos', (['roll'], {}), '(roll)\n', (3195, 3201), True, 'import numpy as np\n'), ((3204, 3215), 'numpy.sin', 'np.sin', (['yaw'], {}), '(yaw)\n', (3210, 3215), True, 'import numpy as np\n'), ((3218, 3230), 'numpy.sin', 'np.sin', (['roll'], {}), '(roll)\n', (3224, 3230), True, 'import numpy as np\n'), ((3317, 3329), 'numpy.sin', 'np.sin', (['roll'], {}), '(roll)\n', (3323, 3329), True, 'import numpy as np\n'), ((3332, 3343), 'numpy.cos', 'np.cos', (['yaw'], {}), '(yaw)\n', (3338, 3343), True, 'import numpy as np\n'), ((3346, 3358), 'numpy.cos', 'np.cos', (['roll'], {}), '(roll)\n', (3352, 3358), True, 'import numpy as np\n'), ((3403, 3415), 'numpy.cos', 'np.cos', (['roll'], {}), '(roll)\n', (3409, 3415), True, 'import numpy as np\n'), ((3418, 3429), 'numpy.cos', 'np.cos', (['yaw'], {}), '(yaw)\n', (3424, 3429), True, 'import numpy as np\n'), ((3432, 3444), 'numpy.sin', 'np.sin', (['roll'], {}), '(roll)\n', (3438, 3444), True, 'import numpy as np\n'), ((4802, 4818), 'numpy.cos', 'np.cos', (['theta[1]'], {}), '(theta[1])\n', (4808, 4818), True, 'import numpy as np\n'), ((4825, 4859), 'numpy.cos', 'np.cos', (['(theta[1] + theta[2] + phi3)'], {}), '(theta[1] + theta[2] + phi3)\n', (4831, 4859), True, 'import numpy as np\n'), ((4934, 4950), 'numpy.cos', 'np.cos', (['theta[0]'], {}), '(theta[0])\n', (4940, 4950), True, 'import numpy as np\n'), ((4965, 4981), 'numpy.sin', 'np.sin', (['theta[0]'], {}), '(theta[0])\n', (4971, 4981), True, 'import numpy as np\n'), ((5007, 5023), 'numpy.sin', 'np.sin', (['theta[0]'], {}), '(theta[0])\n', (5013, 5023), True, 'import numpy as np\n'), ((5038, 5054), 'numpy.cos', 'np.cos', (['theta[0]'], {}), '(theta[0])\n', (5044, 5054), True, 'import numpy as np\n'), ((5190, 5216), 'numpy.matrix', 'np.matrix', (['[[0], [0], [1]]'], {}), '([[0], [0], [1]])\n', (5199, 5216), True, 'import numpy as np\n'), ((5413, 5439), 'numpy.matrix', 'np.matrix', (['[[0], [0], [1]]'], {}), '([[0], [0], [1]])\n', (5422, 5439), True, 'import numpy as np\n'), ((5860, 5888), 'numpy.arctan2', 'np.arctan2', (['c[1, 0]', 'c[0, 0]'], {}), '(c[1, 0], c[0, 0])\n', (5870, 5888), True, 'import numpy as np\n'), ((5891, 5945), 'numpy.arctan2', 'np.arctan2', (['self.param_set.b', '(n_x1 + self.param_set.a1)'], {}), '(self.param_set.b, n_x1 + self.param_set.a1)\n', (5901, 5945), True, 'import numpy as np\n'), ((1187, 1203), 'numpy.cos', 'np.cos', (['theta[0]'], {}), '(theta[0])\n', (1193, 1203), True, 'import numpy as np\n'), ((1204, 1220), 'numpy.cos', 'np.cos', (['theta[1]'], {}), '(theta[1])\n', (1210, 1220), True, 'import numpy as np\n'), ((1240, 1256), 'numpy.cos', 'np.cos', (['theta[0]'], {}), '(theta[0])\n', (1246, 1256), True, 'import numpy as np\n'), ((1257, 1273), 'numpy.sin', 'np.sin', (['theta[1]'], {}), '(theta[1])\n', (1263, 1273), True, 'import numpy as np\n'), ((1337, 1353), 'numpy.cos', 'np.cos', (['theta[0]'], {}), '(theta[0])\n', (1343, 1353), True, 'import numpy as np\n'), ((1354, 1370), 'numpy.cos', 'np.cos', (['theta[1]'], {}), '(theta[1])\n', (1360, 1370), True, 'import numpy as np\n'), ((1390, 1406), 'numpy.cos', 'np.cos', (['theta[0]'], {}), '(theta[0])\n', (1396, 1406), True, 'import numpy as np\n'), ((1407, 1423), 'numpy.sin', 'np.sin', (['theta[1]'], {}), '(theta[1])\n', (1413, 1423), True, 'import numpy as np\n'), ((1455, 1471), 'numpy.sin', 'np.sin', (['theta[0]'], {}), '(theta[0])\n', (1461, 1471), True, 'import numpy as np\n'), ((1472, 1488), 'numpy.cos', 'np.cos', (['theta[1]'], {}), '(theta[1])\n', (1478, 1488), True, 'import numpy as np\n'), ((1508, 1524), 'numpy.sin', 'np.sin', (['theta[0]'], {}), '(theta[0])\n', (1514, 1524), True, 'import numpy as np\n'), ((1525, 1541), 'numpy.sin', 'np.sin', (['theta[1]'], {}), '(theta[1])\n', (1531, 1541), True, 'import numpy as np\n'), ((1604, 1620), 'numpy.sin', 'np.sin', (['theta[0]'], {}), '(theta[0])\n', (1610, 1620), True, 'import numpy as np\n'), ((1621, 1637), 'numpy.cos', 'np.cos', (['theta[1]'], {}), '(theta[1])\n', (1627, 1637), True, 'import numpy as np\n'), ((1657, 1673), 'numpy.sin', 'np.sin', (['theta[0]'], {}), '(theta[0])\n', (1663, 1673), True, 'import numpy as np\n'), ((1674, 1690), 'numpy.sin', 'np.sin', (['theta[1]'], {}), '(theta[1])\n', (1680, 1690), True, 'import numpy as np\n'), ((1723, 1739), 'numpy.sin', 'np.sin', (['theta[1]'], {}), '(theta[1])\n', (1729, 1739), True, 'import numpy as np\n'), ((1826, 1842), 'numpy.sin', 'np.sin', (['theta[1]'], {}), '(theta[1])\n', (1832, 1842), True, 'import numpy as np\n'), ((2156, 2172), 'numpy.cos', 'np.cos', (['theta[3]'], {}), '(theta[3])\n', (2162, 2172), True, 'import numpy as np\n'), ((2175, 2191), 'numpy.cos', 'np.cos', (['theta[4]'], {}), '(theta[4])\n', (2181, 2191), True, 'import numpy as np\n'), ((2284, 2300), 'numpy.cos', 'np.cos', (['theta[4]'], {}), '(theta[4])\n', (2290, 2300), True, 'import numpy as np\n'), ((2422, 2438), 'numpy.sin', 'np.sin', (['theta[3]'], {}), '(theta[3])\n', (2428, 2438), True, 'import numpy as np\n'), ((2441, 2457), 'numpy.cos', 'np.cos', (['theta[4]'], {}), '(theta[4])\n', (2447, 2457), True, 'import numpy as np\n'), ((2549, 2565), 'numpy.cos', 'np.cos', (['theta[4]'], {}), '(theta[4])\n', (2555, 2565), True, 'import numpy as np\n'), ((3073, 3084), 'numpy.cos', 'np.cos', (['yaw'], {}), '(yaw)\n', (3079, 3084), True, 'import numpy as np\n'), ((3087, 3100), 'numpy.sin', 'np.sin', (['pitch'], {}), '(pitch)\n', (3093, 3100), True, 'import numpy as np\n'), ((3159, 3170), 'numpy.cos', 'np.cos', (['yaw'], {}), '(yaw)\n', (3165, 3170), True, 'import numpy as np\n'), ((3173, 3186), 'numpy.sin', 'np.sin', (['pitch'], {}), '(pitch)\n', (3179, 3186), True, 'import numpy as np\n'), ((3287, 3298), 'numpy.sin', 'np.sin', (['yaw'], {}), '(yaw)\n', (3293, 3298), True, 'import numpy as np\n'), ((3301, 3314), 'numpy.sin', 'np.sin', (['pitch'], {}), '(pitch)\n', (3307, 3314), True, 'import numpy as np\n'), ((3373, 3384), 'numpy.sin', 'np.sin', (['yaw'], {}), '(yaw)\n', (3379, 3384), True, 'import numpy as np\n'), ((3387, 3400), 'numpy.sin', 'np.sin', (['pitch'], {}), '(pitch)\n', (3393, 3400), True, 'import numpy as np\n'), ((3975, 3986), 'numpy.cos', 'np.cos', (['yaw'], {}), '(yaw)\n', (3981, 3986), True, 'import numpy as np\n'), ((4000, 4011), 'numpy.sin', 'np.sin', (['yaw'], {}), '(yaw)\n', (4006, 4011), True, 'import numpy as np\n'), ((4050, 4061), 'numpy.sin', 'np.sin', (['yaw'], {}), '(yaw)\n', (4056, 4061), True, 'import numpy as np\n'), ((4074, 4085), 'numpy.cos', 'np.cos', (['yaw'], {}), '(yaw)\n', (4080, 4085), True, 'import numpy as np\n'), ((4098, 4109), 'numpy.sin', 'np.sin', (['yaw'], {}), '(yaw)\n', (4104, 4109), True, 'import numpy as np\n'), ((4122, 4133), 'numpy.cos', 'np.cos', (['yaw'], {}), '(yaw)\n', (4128, 4133), True, 'import numpy as np\n'), ((4659, 4675), 'numpy.sin', 'np.sin', (['theta[1]'], {}), '(theta[1])\n', (4665, 4675), True, 'import numpy as np\n'), ((4682, 4716), 'numpy.sin', 'np.sin', (['(theta[1] + theta[2] + phi3)'], {}), '(theta[1] + theta[2] + phi3)\n', (4688, 4716), True, 'import numpy as np\n'), ((2265, 2281), 'numpy.cos', 'np.cos', (['theta[3]'], {}), '(theta[3])\n', (2271, 2281), True, 'import numpy as np\n'), ((2530, 2546), 'numpy.sin', 'np.sin', (['theta[3]'], {}), '(theta[3])\n', (2536, 2546), True, 'import numpy as np\n'), ((6756, 6769), 'numpy.sqrt', 'np.sqrt', (['k_sq'], {}), '(k_sq)\n', (6763, 6769), True, 'import numpy as np\n'), ((7090, 7103), 'numpy.sqrt', 'np.sqrt', (['k_sq'], {}), '(k_sq)\n', (7097, 7103), True, 'import numpy as np\n'), ((6197, 6211), 'numpy.sqrt', 'np.sqrt', (['s1_sq'], {}), '(s1_sq)\n', (6204, 6211), True, 'import numpy as np\n'), ((6549, 6563), 'numpy.sqrt', 'np.sqrt', (['s2_sq'], {}), '(s2_sq)\n', (6556, 6563), True, 'import numpy as np\n'), ((6923, 6936), 'numpy.sqrt', 'np.sqrt', (['k_sq'], {}), '(k_sq)\n', (6930, 6936), True, 'import numpy as np\n'), ((7257, 7270), 'numpy.sqrt', 'np.sqrt', (['k_sq'], {}), '(k_sq)\n', (7264, 7270), True, 'import numpy as np\n'), ((6033, 6047), 'numpy.sqrt', 'np.sqrt', (['s1_sq'], {}), '(s1_sq)\n', (6040, 6047), True, 'import numpy as np\n'), ((6363, 6377), 'numpy.sqrt', 'np.sqrt', (['s2_sq'], {}), '(s2_sq)\n', (6370, 6377), True, 'import numpy as np\n')]
import unittest import import_ipynb import numpy as np import numpy.testing as np_testing import os class Test(unittest.TestCase): def setUp(self): import Exercise2_03 self.exercise = Exercise2_03 self.mat1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]) self.mat2 = np.array([[2, 1, 4], [4, 1, 7], [4, 2, 9], [5, 21, 1]]) self.mat3 = self.mat1.dot(self.mat2.T) self.mat4 = self.mat1.T.dot(self.mat2) self.mat5 = np.reshape(self.mat1, [3,4]).dot(self.mat2) def test_matrix_multiplication1(self): ex2_03_mat3 = np.array([[ 16, 27, 35, 50], [ 37, 63, 80, 131], [ 58, 99, 125, 212], [ 79, 135, 170, 293]]) np_testing.assert_equal(ex2_03_mat3, self.mat3) def test_matrix_multiplication2(self): ex2_03_mat4 = np.array([[ 96, 229, 105], [111, 254, 126], [126, 279, 147]]) np_testing.assert_equal(ex2_03_mat4, self.mat4) def test_matrix_multiplication3(self): ex2_03_mat5 = np.array([[ 42, 93, 49], [102, 193, 133], [162, 293, 217]]) np_testing.assert_equal(ex2_03_mat5, self.mat5) if __name__ == '__main__': unittest.main()
[ "unittest.main", "numpy.array", "numpy.reshape", "numpy.testing.assert_equal" ]
[((1201, 1216), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1214, 1216), False, 'import unittest\n'), ((253, 310), 'numpy.array', 'np.array', (['[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]'], {}), '([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])\n', (261, 310), True, 'import numpy as np\n'), ((331, 386), 'numpy.array', 'np.array', (['[[2, 1, 4], [4, 1, 7], [4, 2, 9], [5, 21, 1]]'], {}), '([[2, 1, 4], [4, 1, 7], [4, 2, 9], [5, 21, 1]])\n', (339, 386), True, 'import numpy as np\n'), ((617, 709), 'numpy.array', 'np.array', (['[[16, 27, 35, 50], [37, 63, 80, 131], [58, 99, 125, 212], [79, 135, 170, 293]]'], {}), '([[16, 27, 35, 50], [37, 63, 80, 131], [58, 99, 125, 212], [79, 135,\n 170, 293]])\n', (625, 709), True, 'import numpy as np\n'), ((753, 800), 'numpy.testing.assert_equal', 'np_testing.assert_equal', (['ex2_03_mat3', 'self.mat3'], {}), '(ex2_03_mat3, self.mat3)\n', (776, 800), True, 'import numpy.testing as np_testing\n'), ((867, 927), 'numpy.array', 'np.array', (['[[96, 229, 105], [111, 254, 126], [126, 279, 147]]'], {}), '([[96, 229, 105], [111, 254, 126], [126, 279, 147]])\n', (875, 927), True, 'import numpy as np\n'), ((937, 984), 'numpy.testing.assert_equal', 'np_testing.assert_equal', (['ex2_03_mat4', 'self.mat4'], {}), '(ex2_03_mat4, self.mat4)\n', (960, 984), True, 'import numpy.testing as np_testing\n'), ((1051, 1109), 'numpy.array', 'np.array', (['[[42, 93, 49], [102, 193, 133], [162, 293, 217]]'], {}), '([[42, 93, 49], [102, 193, 133], [162, 293, 217]])\n', (1059, 1109), True, 'import numpy as np\n'), ((1121, 1168), 'numpy.testing.assert_equal', 'np_testing.assert_equal', (['ex2_03_mat5', 'self.mat5'], {}), '(ex2_03_mat5, self.mat5)\n', (1144, 1168), True, 'import numpy.testing as np_testing\n'), ((501, 530), 'numpy.reshape', 'np.reshape', (['self.mat1', '[3, 4]'], {}), '(self.mat1, [3, 4])\n', (511, 530), True, 'import numpy as np\n')]
import os import numpy as np import json from PIL import Image def detect_red_light_simple(I): ''' This function takes a numpy array <I> and returns a list <bounding_boxes>. The list <bounding_boxes> should have one element for each red light in the image. Each element of <bounding_boxes> should itself be a list, containing four integers that specify a bounding box: the row and column index of the top left corner and the row and column index of the bottom right corner (in that order). See the code below for an example. Note that PIL loads images in RGB order, so: I[:,:,0] is the red channel I[:,:,1] is the green channel I[:,:,2] is the blue channel ''' bounding_boxes = [] # This should be a list of lists, each of length 4. See format example below. ''' BEGIN YOUR CODE ''' data_path = 'data/kernel' kernel = Image.open(os.path.join(data_path,'kernel1.jpg')) kernel = np.asarray(kernel) box_height = kernel.shape[0] box_width = kernel.shape[1] r_kernel = kernel[:,:,0] r_kernel = r_kernel / np.linalg.norm(r_kernel) # normalize r_I = I[:,:,0] threshold = 0.96 for row in range(r_I.shape[0]-box_height): for col in range(r_I.shape[1]-box_width): r_I_part = r_I[row:row+box_height,col:col+box_width] r_I_part = r_I_part / np.linalg.norm(r_I_part) # normalize convolution = np.sum(np.multiply(r_kernel,r_I_part)) # to avoid overlapped boxes if convolution > threshold and (not bounding_boxes or (row > tl_row + 5 and col > tl_col+5)): tl_row = row tl_col = col br_row = tl_row + box_height br_col = tl_col + box_width bounding_boxes.append([tl_row,tl_col,br_row,br_col]) # ''' # As an example, here's code that generates between 1 and 5 random boxes # of fixed size and returns the results in the proper format. # ''' # # box_height = 8 # box_width = 6 # # num_boxes = np.random.randint(1,5) # # for i in range(num_boxes): # (n_rows,n_cols,n_channels) = np.shape(I) # # tl_row = np.random.randint(n_rows - box_height) # tl_col = np.random.randint(n_cols - box_width) # br_row = tl_row + box_height # br_col = tl_col + box_width # # bounding_boxes.append([tl_row,tl_col,br_row,br_col]) ''' END YOUR CODE ''' for i in range(len(bounding_boxes)): assert len(bounding_boxes[i]) == 4 return bounding_boxes def detect_red_light_random(I): ''' This function takes a numpy array <I> and returns a list <bounding_boxes>. The list <bounding_boxes> should have one element for each red light in the image. Each element of <bounding_boxes> should itself be a list, containing four integers that specify a bounding box: the row and column index of the top left corner and the row and column index of the bottom right corner (in that order). See the code below for an example. Note that PIL loads images in RGB order, so: I[:,:,0] is the red channel I[:,:,1] is the green channel I[:,:,2] is the blue channel ''' bounding_boxes = [] # This should be a list of lists, each of length 4. See format example below. ''' BEGIN YOUR CODE ''' data_path = 'data/kernel' idx = np.random.randint(172) kernel = Image.open(os.path.join(data_path,'kernel'+str(idx+1)+'.jpg')) kernel = np.asarray(kernel) box_height = kernel.shape[0] box_width = kernel.shape[1] r_kernel = kernel[:,:,0] r_kernel = r_kernel / np.linalg.norm(r_kernel) # normalize r_I = I[:,:,0] threshold = 0.9 for row in range(r_I.shape[0]-box_height): for col in range(r_I.shape[1]-box_width): r_I_part = r_I[row:row+box_height,col:col+box_width] r_I_part = r_I_part / np.linalg.norm(r_I_part) # normalize convolution = np.sum(np.multiply(r_kernel,r_I_part)) # to avoid overlapped boxes if convolution > threshold and (not bounding_boxes or (row > tl_row + 5 and col > tl_col+5)): tl_row = row tl_col = col br_row = tl_row + box_height br_col = tl_col + box_width bounding_boxes.append([tl_row,tl_col,br_row,br_col]) ''' END YOUR CODE ''' for i in range(len(bounding_boxes)): assert len(bounding_boxes[i]) == 4 return bounding_boxes def detect_red_light_average(I): ''' This function takes a numpy array <I> and returns a list <bounding_boxes>. The list <bounding_boxes> should have one element for each red light in the image. Each element of <bounding_boxes> should itself be a list, containing four integers that specify a bounding box: the row and column index of the top left corner and the row and column index of the bottom right corner (in that order). See the code below for an example. Note that PIL loads images in RGB order, so: I[:,:,0] is the red channel I[:,:,1] is the green channel I[:,:,2] is the blue channel ''' bounding_boxes = [] # This should be a list of lists, each of length 4. See format example below. ''' BEGIN YOUR CODE ''' data_path = 'data/kernel_resized' kernel = Image.open(os.path.join(data_path,'kernel_ave.jpg')) kernel = np.asarray(kernel) box_height = kernel.shape[0] box_width = kernel.shape[1] r_kernel = kernel[:,:,0] r_kernel = r_kernel / np.linalg.norm(r_kernel) # normalize r_I = I[:,:,0] threshold = 0.96 for row in range(r_I.shape[0]-box_height): for col in range(r_I.shape[1]-box_width): r_I_part = r_I[row:row+box_height,col:col+box_width] r_I_part = r_I_part / np.linalg.norm(r_I_part) # normalize convolution = np.sum(np.multiply(r_kernel,r_I_part)) # to avoid overlapped boxes if convolution > threshold and (not bounding_boxes or (row > tl_row + 5 and col > tl_col+5)): tl_row = row tl_col = col br_row = tl_row + box_height br_col = tl_col + box_width bounding_boxes.append([tl_row,tl_col,br_row,br_col]) ''' END YOUR CODE ''' for i in range(len(bounding_boxes)): assert len(bounding_boxes[i]) == 4 return bounding_boxes # set the path to the downloaded data: data_path = 'data/RedLights2011_Medium' # set a path for saving predictions: preds_path = 'data/hw01_preds' os.makedirs(preds_path,exist_ok=True) # create directory if needed # get sorted list of files: file_names = sorted(os.listdir(data_path)) # remove any non-JPEG files: file_names = [f for f in file_names if '.jpg' in f] preds = {} for i in range(len(file_names)): print(i) # read image using PIL: I = Image.open(os.path.join(data_path,file_names[i])) # convert to numpy array: I = np.asarray(I) preds[file_names[i]] = detect_red_light_average(I) print(preds[file_names[i]]) # save preds (overwrites any previous predictions!) with open(os.path.join(preds_path,'preds_average.json'),'w') as f: json.dump(preds,f) # with open("data_file.json", "r") as read_file: # data = json.load(read_file)
[ "numpy.multiply", "os.listdir", "os.makedirs", "numpy.asarray", "os.path.join", "numpy.random.randint", "numpy.linalg.norm", "json.dump" ]
[((6679, 6717), 'os.makedirs', 'os.makedirs', (['preds_path'], {'exist_ok': '(True)'}), '(preds_path, exist_ok=True)\n', (6690, 6717), False, 'import os\n'), ((978, 996), 'numpy.asarray', 'np.asarray', (['kernel'], {}), '(kernel)\n', (988, 996), True, 'import numpy as np\n'), ((3460, 3482), 'numpy.random.randint', 'np.random.randint', (['(172)'], {}), '(172)\n', (3477, 3482), True, 'import numpy as np\n'), ((3572, 3590), 'numpy.asarray', 'np.asarray', (['kernel'], {}), '(kernel)\n', (3582, 3590), True, 'import numpy as np\n'), ((5503, 5521), 'numpy.asarray', 'np.asarray', (['kernel'], {}), '(kernel)\n', (5513, 5521), True, 'import numpy as np\n'), ((6797, 6818), 'os.listdir', 'os.listdir', (['data_path'], {}), '(data_path)\n', (6807, 6818), False, 'import os\n'), ((7097, 7110), 'numpy.asarray', 'np.asarray', (['I'], {}), '(I)\n', (7107, 7110), True, 'import numpy as np\n'), ((7327, 7346), 'json.dump', 'json.dump', (['preds', 'f'], {}), '(preds, f)\n', (7336, 7346), False, 'import json\n'), ((926, 964), 'os.path.join', 'os.path.join', (['data_path', '"""kernel1.jpg"""'], {}), "(data_path, 'kernel1.jpg')\n", (938, 964), False, 'import os\n'), ((1118, 1142), 'numpy.linalg.norm', 'np.linalg.norm', (['r_kernel'], {}), '(r_kernel)\n', (1132, 1142), True, 'import numpy as np\n'), ((3712, 3736), 'numpy.linalg.norm', 'np.linalg.norm', (['r_kernel'], {}), '(r_kernel)\n', (3726, 3736), True, 'import numpy as np\n'), ((5448, 5489), 'os.path.join', 'os.path.join', (['data_path', '"""kernel_ave.jpg"""'], {}), "(data_path, 'kernel_ave.jpg')\n", (5460, 5489), False, 'import os\n'), ((5643, 5667), 'numpy.linalg.norm', 'np.linalg.norm', (['r_kernel'], {}), '(r_kernel)\n', (5657, 5667), True, 'import numpy as np\n'), ((7015, 7053), 'os.path.join', 'os.path.join', (['data_path', 'file_names[i]'], {}), '(data_path, file_names[i])\n', (7027, 7053), False, 'import os\n'), ((7266, 7312), 'os.path.join', 'os.path.join', (['preds_path', '"""preds_average.json"""'], {}), "(preds_path, 'preds_average.json')\n", (7278, 7312), False, 'import os\n'), ((1392, 1416), 'numpy.linalg.norm', 'np.linalg.norm', (['r_I_part'], {}), '(r_I_part)\n', (1406, 1416), True, 'import numpy as np\n'), ((1462, 1493), 'numpy.multiply', 'np.multiply', (['r_kernel', 'r_I_part'], {}), '(r_kernel, r_I_part)\n', (1473, 1493), True, 'import numpy as np\n'), ((3985, 4009), 'numpy.linalg.norm', 'np.linalg.norm', (['r_I_part'], {}), '(r_I_part)\n', (3999, 4009), True, 'import numpy as np\n'), ((4055, 4086), 'numpy.multiply', 'np.multiply', (['r_kernel', 'r_I_part'], {}), '(r_kernel, r_I_part)\n', (4066, 4086), True, 'import numpy as np\n'), ((5917, 5941), 'numpy.linalg.norm', 'np.linalg.norm', (['r_I_part'], {}), '(r_I_part)\n', (5931, 5941), True, 'import numpy as np\n'), ((5987, 6018), 'numpy.multiply', 'np.multiply', (['r_kernel', 'r_I_part'], {}), '(r_kernel, r_I_part)\n', (5998, 6018), True, 'import numpy as np\n')]
import numpy as np np.random.seed(1337) # for reproducibility from keras.preprocessing import sequence from keras.utils import np_utils from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, Embedding, LSTM, GRU, SimpleRNN from keras.optimizers import Adam from keras.datasets import imdb max_features = 20000 maxlen = 80 # cut texts after this number of words (among top max_features most common words) batch_size = 32 (X, Y), (Xv, Yv) = imdb.load_data(nb_words=max_features) X = sequence.pad_sequences(X, maxlen=maxlen) Xv = sequence.pad_sequences(Xv, maxlen=maxlen) model = Sequential() model.add(Embedding(max_features, 128, dropout=0.2)) model.add(GRU(128)) # try using a GRU instead, for fun model.add(Dense(1)) model.add(Activation('sigmoid')) # try using different optimizers and different optimizer configs model.compile(loss='binary_crossentropy', optimizer=Adam(), metrics=['accuracy']) model.fit(X, Y, batch_size=batch_size, nb_epoch=15, validation_data=(Xv, Yv)) score, acc = model.evaluate(Xv, Yv, batch_size=batch_size) print('Test score:', score) print('Test accuracy:', acc)
[ "keras.optimizers.Adam", "keras.datasets.imdb.load_data", "keras.models.Sequential", "numpy.random.seed", "keras.layers.Activation", "keras.layers.Dense", "keras.layers.GRU", "keras.preprocessing.sequence.pad_sequences", "keras.layers.Embedding" ]
[((19, 39), 'numpy.random.seed', 'np.random.seed', (['(1337)'], {}), '(1337)\n', (33, 39), True, 'import numpy as np\n'), ((478, 515), 'keras.datasets.imdb.load_data', 'imdb.load_data', ([], {'nb_words': 'max_features'}), '(nb_words=max_features)\n', (492, 515), False, 'from keras.datasets import imdb\n'), ((521, 561), 'keras.preprocessing.sequence.pad_sequences', 'sequence.pad_sequences', (['X'], {'maxlen': 'maxlen'}), '(X, maxlen=maxlen)\n', (543, 561), False, 'from keras.preprocessing import sequence\n'), ((567, 608), 'keras.preprocessing.sequence.pad_sequences', 'sequence.pad_sequences', (['Xv'], {'maxlen': 'maxlen'}), '(Xv, maxlen=maxlen)\n', (589, 608), False, 'from keras.preprocessing import sequence\n'), ((618, 630), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (628, 630), False, 'from keras.models import Sequential\n'), ((641, 682), 'keras.layers.Embedding', 'Embedding', (['max_features', '(128)'], {'dropout': '(0.2)'}), '(max_features, 128, dropout=0.2)\n', (650, 682), False, 'from keras.layers import Dense, Dropout, Activation, Embedding, LSTM, GRU, SimpleRNN\n'), ((694, 702), 'keras.layers.GRU', 'GRU', (['(128)'], {}), '(128)\n', (697, 702), False, 'from keras.layers import Dense, Dropout, Activation, Embedding, LSTM, GRU, SimpleRNN\n'), ((750, 758), 'keras.layers.Dense', 'Dense', (['(1)'], {}), '(1)\n', (755, 758), False, 'from keras.layers import Dense, Dropout, Activation, Embedding, LSTM, GRU, SimpleRNN\n'), ((770, 791), 'keras.layers.Activation', 'Activation', (['"""sigmoid"""'], {}), "('sigmoid')\n", (780, 791), False, 'from keras.layers import Dense, Dropout, Activation, Embedding, LSTM, GRU, SimpleRNN\n'), ((925, 931), 'keras.optimizers.Adam', 'Adam', ([], {}), '()\n', (929, 931), False, 'from keras.optimizers import Adam\n')]
# build a classifier import json import random import os from time import time import numpy as np from scipy.stats import randint as sp_randint from sklearn.ensemble import RandomForestClassifier from sklearn.linear_model import LogisticRegression from sklearn.neural_network import MLPClassifier from sklearn.metrics import f1_score, make_scorer from sklearn.model_selection import RandomizedSearchCV import warnings warnings.filterwarnings("ignore") def report(results, n_top=3): # Utility function to report best scores for i in range(1, n_top + 1): candidates = np.flatnonzero(results['rank_test_score'] == i) for candidate in candidates: print("Model with rank:" + str(i)) print("Mean validation score: {0:.3f} (std: {1:.3f})".format( results['mean_test_score'][candidate], results['std_test_score'][candidate])) print("Parameters: {0}\n".format(results['params'][candidate])) def get_random_layer_sizes(): hidden_layers = [] depth = random.randint(1, 6) for i in range(0, depth): hidden_layers.append(random.randint(20, 300)) return tuple(hidden_layers) def run_search(clf, param_dist, X, y): # run randomized search, due to memory limits on developer machine, RandomizedSearchCV must run single-threaded. print("Starting randomized search for", type(clf).__name__, "...") n_iter_search = 50 random_search = RandomizedSearchCV(clf, param_distributions=param_dist, n_iter=n_iter_search, n_jobs=1, cv=5, scoring=make_scorer(f1_score, labels=[0, 1])) start = time() random_search.fit(X, y) print("Random search took %.2f seconds, %d parameter settings tested." % ((time() - start), n_iter_search)) report(random_search.cv_results_) def main(filename): print("Loading data...") with open(os.path.join(os.path.dirname(__file__), "../feature_generation/data/" + filename), "r") as f: X = json.load(f) with open(os.path.join(os.path.dirname(__file__), "../feature_generation/data/labels.json"), "r") as f: y = json.load(f) n_features = len(X[0]) configurations = [ [ RandomForestClassifier(n_estimators=20, n_jobs=-1), { "max_depth": sp_randint(1, n_features), "max_features": sp_randint(100, n_features), "min_samples_split": sp_randint(200, n_features), "min_samples_leaf": sp_randint(100, n_features), "bootstrap": [True, False], "criterion": ["gini", "entropy"] } ], [ LogisticRegression(n_jobs=-1, max_iter=100, multi_class="ovr"), { "solver": ["newton-cg", "lbfgs", "liblinear", "sag", "saga"], "penalty": ["l2"], "dual": [0], "C": np.random.uniform(low=0.01, high=5, size=(200,)), "class_weight": ["balanced", None] } ], [ MLPClassifier(), { "activation": ["identity", "logistic", "tanh", "relu"], "solver": ["lbfgs", "sgd", "adam"], "alpha": np.random.uniform(low=0.000001, high=0.01, size=(200,)), "tol": np.random.uniform(low=0.000001, high=0.01, size=(200,)), "hidden_layer_sizes": get_random_layer_sizes() } ] ] for clf, param_dist in configurations: run_search(clf, param_dist, X, y) if __name__ == "__main__": for i in range(1, 4): print("ngram: " + str(i)) main("ngram_l%d_u%d.json" % (i, i)) print("ngram: " + str(i) + " tfidf") main("ngram_l%d_u%d_t.json" % (i, i)) print("hashed: " + str(i)) main("hashed_10000_l" + str(i) + "_u" + str(i) + ".json")
[ "warnings.filterwarnings", "scipy.stats.randint", "sklearn.neural_network.MLPClassifier", "numpy.flatnonzero", "sklearn.metrics.make_scorer", "sklearn.ensemble.RandomForestClassifier", "sklearn.linear_model.LogisticRegression", "os.path.dirname", "numpy.random.uniform", "json.load", "time.time",...
[((422, 455), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (445, 455), False, 'import warnings\n'), ((976, 996), 'random.randint', 'random.randint', (['(1)', '(6)'], {}), '(1, 6)\n', (990, 996), False, 'import random\n'), ((1547, 1553), 'time.time', 'time', ([], {}), '()\n', (1551, 1553), False, 'from time import time\n'), ((576, 623), 'numpy.flatnonzero', 'np.flatnonzero', (["(results['rank_test_score'] == i)"], {}), "(results['rank_test_score'] == i)\n", (590, 623), True, 'import numpy as np\n'), ((1882, 1894), 'json.load', 'json.load', (['f'], {}), '(f)\n', (1891, 1894), False, 'import json\n'), ((2006, 2018), 'json.load', 'json.load', (['f'], {}), '(f)\n', (2015, 2018), False, 'import json\n'), ((1047, 1070), 'random.randint', 'random.randint', (['(20)', '(300)'], {}), '(20, 300)\n', (1061, 1070), False, 'import random\n'), ((1499, 1535), 'sklearn.metrics.make_scorer', 'make_scorer', (['f1_score'], {'labels': '[0, 1]'}), '(f1_score, labels=[0, 1])\n', (1510, 1535), False, 'from sklearn.metrics import f1_score, make_scorer\n'), ((2071, 2121), 'sklearn.ensemble.RandomForestClassifier', 'RandomForestClassifier', ([], {'n_estimators': '(20)', 'n_jobs': '(-1)'}), '(n_estimators=20, n_jobs=-1)\n', (2093, 2121), False, 'from sklearn.ensemble import RandomForestClassifier\n'), ((2414, 2476), 'sklearn.linear_model.LogisticRegression', 'LogisticRegression', ([], {'n_jobs': '(-1)', 'max_iter': '(100)', 'multi_class': '"""ovr"""'}), "(n_jobs=-1, max_iter=100, multi_class='ovr')\n", (2432, 2476), False, 'from sklearn.linear_model import LogisticRegression\n'), ((2704, 2719), 'sklearn.neural_network.MLPClassifier', 'MLPClassifier', ([], {}), '()\n', (2717, 2719), False, 'from sklearn.neural_network import MLPClassifier\n'), ((1795, 1820), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (1810, 1820), False, 'import os\n'), ((1919, 1944), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (1934, 1944), False, 'import os\n'), ((2145, 2170), 'scipy.stats.randint', 'sp_randint', (['(1)', 'n_features'], {}), '(1, n_features)\n', (2155, 2170), True, 'from scipy.stats import randint as sp_randint\n'), ((2192, 2219), 'scipy.stats.randint', 'sp_randint', (['(100)', 'n_features'], {}), '(100, n_features)\n', (2202, 2219), True, 'from scipy.stats import randint as sp_randint\n'), ((2246, 2273), 'scipy.stats.randint', 'sp_randint', (['(200)', 'n_features'], {}), '(200, n_features)\n', (2256, 2273), True, 'from scipy.stats import randint as sp_randint\n'), ((2299, 2326), 'scipy.stats.randint', 'sp_randint', (['(100)', 'n_features'], {}), '(100, n_features)\n', (2309, 2326), True, 'from scipy.stats import randint as sp_randint\n'), ((2598, 2646), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(0.01)', 'high': '(5)', 'size': '(200,)'}), '(low=0.01, high=5, size=(200,))\n', (2615, 2646), True, 'import numpy as np\n'), ((2839, 2891), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(1e-06)', 'high': '(0.01)', 'size': '(200,)'}), '(low=1e-06, high=0.01, size=(200,))\n', (2856, 2891), True, 'import numpy as np\n'), ((2907, 2959), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(1e-06)', 'high': '(0.01)', 'size': '(200,)'}), '(low=1e-06, high=0.01, size=(200,))\n', (2924, 2959), True, 'import numpy as np\n'), ((1655, 1661), 'time.time', 'time', ([], {}), '()\n', (1659, 1661), False, 'from time import time\n')]
import numpy as np import scipy.spatial as spatial import scipy.sparse as sparse #Construct robin boundary condition matrix def robin_bc_matrix(X,nu,eps,gamma): n = X.shape[0] Xtree = spatial.cKDTree(X) _,nn_ind = Xtree.query(X + eps*nu) #nn_dist = np.linalg.norm(X - X[nn_ind,:],axis=1) nn_dist = eps*np.ones((n,)) #Robin matrix A = sparse.spdiags(gamma + (1-gamma)/nn_dist,0,n,n) B = sparse.coo_matrix(((1-gamma)/nn_dist, (range(n),nn_ind)),shape=(n,n)) R = (A - B).tocsr() return R
[ "scipy.sparse.spdiags", "numpy.ones", "scipy.spatial.cKDTree" ]
[((194, 212), 'scipy.spatial.cKDTree', 'spatial.cKDTree', (['X'], {}), '(X)\n', (209, 212), True, 'import scipy.spatial as spatial\n'), ((365, 419), 'scipy.sparse.spdiags', 'sparse.spdiags', (['(gamma + (1 - gamma) / nn_dist)', '(0)', 'n', 'n'], {}), '(gamma + (1 - gamma) / nn_dist, 0, n, n)\n', (379, 419), True, 'import scipy.sparse as sparse\n'), ((324, 337), 'numpy.ones', 'np.ones', (['(n,)'], {}), '((n,))\n', (331, 337), True, 'import numpy as np\n')]
from __future__ import absolute_import, division, print_function import pickle import argparse import logging import os import random import wget import json import time import numpy as np import torch from torch.utils.data import (DataLoader, RandomSampler, SequentialSampler, TensorDataset) from torch.utils.data.distributed import DistributedSampler from tqdm import tqdm, trange from file_utils import PYTORCH_PRETRAINED_BERT_CACHE import modeling from tokenization import BertTokenizer from optimization import BertAdam, warmup_linear from schedulers import LinearWarmUpScheduler from apex import amp from sklearn.metrics import matthews_corrcoef, f1_score from utils import (is_main_process, mkdir_by_main_process, format_step, get_world_size) from helpers.arg_parser import parse_args torch._C._jit_set_profiling_mode(False) torch._C._jit_set_profiling_executor(False) logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO) logger = logging.getLogger(__name__) def accuracy(out, labels): outputs = np.argmax(out, axis=1) return np.sum(outputs == labels) def init_optimizer_and_amp(model, learning_rate, loss_scale, warmup_proportion, num_train_optimization_steps, use_fp16): param_optimizer = list(model.named_parameters()) no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight'] optimizer_grouped_parameters = [ { 'params': [ p for n, p in param_optimizer if not any(nd in n for nd in no_decay) ], 'weight_decay': 0.01 }, { 'params': [ p for n, p in param_optimizer if any(nd in n for nd in no_decay) ], 'weight_decay': 0.0 }, ] optimizer, scheduler = None, None if use_fp16: logger.info("using fp16") try: from apex.optimizers import FusedAdam except ImportError: raise ImportError("Please install apex from " "https://www.github.com/nvidia/apex to use " "distributed and fp16 training.") if num_train_optimization_steps is not None: optimizer = FusedAdam( optimizer_grouped_parameters, lr=learning_rate, bias_correction=False, ) amp_inits = amp.initialize( model, optimizers=optimizer, opt_level="O2", keep_batchnorm_fp32=False, loss_scale="dynamic" if loss_scale == 0 else loss_scale, ) model, optimizer = (amp_inits if num_train_optimization_steps is not None else (amp_inits, None)) if num_train_optimization_steps is not None: scheduler = LinearWarmUpScheduler( optimizer, warmup=warmup_proportion, total_steps=num_train_optimization_steps, ) else: logger.info("using fp32") if num_train_optimization_steps is not None: optimizer = BertAdam( optimizer_grouped_parameters, lr=learning_rate, warmup=warmup_proportion, t_total=num_train_optimization_steps, ) return model, optimizer, scheduler def dump_predictions(path, label_map, preds, examples): label_rmap = {label_idx: label for label, label_idx in label_map.items()} predictions = { example.guid: label_rmap[preds[i]] for i, example in enumerate(examples) } with open(path, "w") as writer: json.dump(predictions, writer) def main(args): args.fp16 = args.fp16 or args.amp if args.server_ip and args.server_port: # Distant debugging - see # https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd logger.info("Waiting for debugger attach") ptvsd.enable_attach( address=(args.server_ip, args.server_port), redirect_output=True, ) ptvsd.wait_for_attach() if args.local_rank == -1 or args.no_cuda: device = torch.device( "cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu") n_gpu = torch.cuda.device_count() else: torch.cuda.set_device(args.local_rank) device = torch.device("cuda", args.local_rank) n_gpu = 1 # Initializes the distributed backend which will take care of # sychronizing nodes/GPUs. if not torch.distributed.is_initialized(): torch.distributed.init_process_group(backend='nccl') logger.info("device: {} n_gpu: {}, distributed training: {}, " "16-bits training: {}".format( device, n_gpu, bool(args.local_rank != -1), args.fp16, )) if not args.do_train and not args.do_eval and not args.do_predict: raise ValueError("At least one of `do_train`, `do_eval` or " "`do_predict` must be True.") if is_main_process(): if (os.path.exists(args.output_dir) and os.listdir(args.output_dir) and args.do_train): logger.warning("Output directory ({}) already exists and is not " "empty.".format(args.output_dir)) mkdir_by_main_process(args.output_dir) if args.gradient_accumulation_steps < 1: raise ValueError("Invalid gradient_accumulation_steps parameter: {}, " "should be >= 1".format( args.gradient_accumulation_steps)) if args.gradient_accumulation_steps > args.train_batch_size: raise ValueError("gradient_accumulation_steps ({}) cannot be larger " "train_batch_size ({}) - there cannot be a fraction " "of one sample.".format( args.gradient_accumulation_steps, args.train_batch_size, )) args.train_batch_size = (args.train_batch_size // args.gradient_accumulation_steps) random.seed(args.seed) np.random.seed(args.seed) torch.manual_seed(args.seed) if n_gpu > 0: torch.cuda.manual_seed_all(args.seed) #tokenizer = BertTokenizer.from_pretrained(args.bert_model, do_lower_case=args.do_lower_case) tokenizer = BertTokenizer( args.vocab_file, do_lower_case=args.do_lower_case, max_len=512, ) # for bert large num_train_optimization_steps = None if args.do_train: train_features = get_train_features( args.data_dir, args.bert_model, args.max_seq_length, args.do_lower_case, args.local_rank, args.train_batch_size, args.gradient_accumulation_steps, args.num_train_epochs, tokenizer, processor, ) num_train_optimization_steps = int( len(train_features) / args.train_batch_size / args.gradient_accumulation_steps) * args.num_train_epochs if args.local_rank != -1: num_train_optimization_steps = (num_train_optimization_steps // torch.distributed.get_world_size()) # Prepare model config = modeling.BertConfig.from_json_file(args.config_file) # Padding for divisibility by 8 if config.vocab_size % 8 != 0: config.vocab_size += 8 - (config.vocab_size % 8) modeling.ACT2FN["bias_gelu"] = modeling.bias_gelu_training model = modeling.BertForSequenceClassification( config, num_labels=num_labels, ) logger.info("USING CHECKPOINT from {}".format(args.init_checkpoint)) model.load_state_dict( torch.load(args.init_checkpoint, map_location='cpu')["model"], strict=False, ) logger.info("USED CHECKPOINT from {}".format(args.init_checkpoint)) model.to(device) # Prepare optimizer model, optimizer, scheduler = init_optimizer_and_amp( model, args.learning_rate, args.loss_scale, args.warmup_proportion, num_train_optimization_steps, args.fp16, ) if args.local_rank != -1: try: from apex.parallel import DistributedDataParallel as DDP except ImportError: raise ImportError("Please install apex from " "https://www.github.com/nvidia/apex to use " "distributed and fp16 training.") model = DDP(model) elif n_gpu > 1: model = torch.nn.DataParallel(model) loss_fct = torch.nn.CrossEntropyLoss() results = {} if args.do_train: logger.info("***** Running training *****") logger.info(" Num examples = %d", len(train_features)) logger.info(" Batch size = %d", args.train_batch_size) logger.info(" Num steps = %d", num_train_optimization_steps) train_data = gen_tensor_dataset(train_features) if args.local_rank == -1: train_sampler = RandomSampler(train_data) else: train_sampler = DistributedSampler(train_data) train_dataloader = DataLoader( train_data, sampler=train_sampler, batch_size=args.train_batch_size, ) global_step = 0 nb_tr_steps = 0 tr_loss = 0 latency_train = 0.0 nb_tr_examples = 0 model.train() tic_train = time.perf_counter() for _ in trange(int(args.num_train_epochs), desc="Epoch"): tr_loss, nb_tr_steps = 0, 0 for step, batch in enumerate( tqdm(train_dataloader, desc="Iteration")): if args.max_steps > 0 and global_step > args.max_steps: break batch = tuple(t.to(device) for t in batch) input_ids, input_mask, segment_ids, label_ids = batch logits = model(input_ids, segment_ids, input_mask) loss = loss_fct( logits.view(-1, num_labels), label_ids.view(-1), ) if n_gpu > 1: loss = loss.mean() # mean() to average on multi-gpu. if args.gradient_accumulation_steps > 1: loss = loss / args.gradient_accumulation_steps if args.fp16: with amp.scale_loss(loss, optimizer) as scaled_loss: scaled_loss.backward() else: loss.backward() tr_loss += loss.item() nb_tr_examples += input_ids.size(0) nb_tr_steps += 1 if (step + 1) % args.gradient_accumulation_steps == 0: if args.fp16: # modify learning rate with special warm up for BERT # which FusedAdam doesn't do scheduler.step() optimizer.step() optimizer.zero_grad() global_step += 1 latency_train = time.perf_counter() - tic_train tr_loss = tr_loss / nb_tr_steps results.update({ 'global_step': global_step, 'train:loss': tr_loss, 'train:latency': latency_train, 'train:num_samples_per_gpu': nb_tr_examples, 'train:num_steps': nb_tr_steps, 'train:throughput': get_world_size() * nb_tr_examples / latency_train, }) if is_main_process() and not args.skip_checkpoint: model_to_save = model.module if hasattr(model, 'module') else model torch.save( {"model": model_to_save.state_dict()}, os.path.join(args.output_dir, modeling.WEIGHTS_NAME), ) with open( os.path.join(args.output_dir, modeling.CONFIG_NAME), 'w', ) as f: f.write(model_to_save.config.to_json_string()) if (args.do_eval or args.do_predict) and is_main_process(): eval_examples = processor.get_dev_examples(args.data_dir) eval_features, label_map = convert_examples_to_features( eval_examples, processor.get_labels(), args.max_seq_length, tokenizer, ) logger.info("***** Running evaluation *****") logger.info(" Num examples = %d", len(eval_examples)) logger.info(" Batch size = %d", args.eval_batch_size) eval_data = gen_tensor_dataset(eval_features) # Run prediction for full data eval_sampler = SequentialSampler(eval_data) eval_dataloader = DataLoader( eval_data, sampler=eval_sampler, batch_size=args.eval_batch_size, ) model.eval() preds = None out_label_ids = None eval_loss = 0 nb_eval_steps, nb_eval_examples = 0, 0 cuda_events = [(torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)) for _ in range(len(eval_dataloader))] for i, (input_ids, input_mask, segment_ids, label_ids) in tqdm( enumerate(eval_dataloader), desc="Evaluating", ): input_ids = input_ids.to(device) input_mask = input_mask.to(device) segment_ids = segment_ids.to(device) label_ids = label_ids.to(device) with torch.no_grad(): cuda_events[i][0].record() logits = model(input_ids, segment_ids, input_mask) cuda_events[i][1].record() if args.do_eval: eval_loss += loss_fct( logits.view(-1, num_labels), label_ids.view(-1), ).mean().item() nb_eval_steps += 1 nb_eval_examples += input_ids.size(0) if preds is None: preds = logits.detach().cpu().numpy() out_label_ids = label_ids.detach().cpu().numpy() else: preds = np.append(preds, logits.detach().cpu().numpy(), axis=0) out_label_ids = np.append( out_label_ids, label_ids.detach().cpu().numpy(), axis=0, ) torch.cuda.synchronize() eval_latencies = [ event_start.elapsed_time(event_end) for event_start, event_end in cuda_events ] eval_latencies = list(sorted(eval_latencies)) def infer_latency_sli(threshold): index = int(len(eval_latencies) * threshold) - 1 index = min(max(index, 0), len(eval_latencies) - 1) return eval_latencies[index] eval_throughput = (args.eval_batch_size / (np.mean(eval_latencies) / 1000)) results.update({ 'eval:num_samples_per_gpu': nb_eval_examples, 'eval:num_steps': nb_eval_steps, 'infer:latency(ms):50%': infer_latency_sli(0.5), 'infer:latency(ms):90%': infer_latency_sli(0.9), 'infer:latency(ms):95%': infer_latency_sli(0.95), 'infer:latency(ms):99%': infer_latency_sli(0.99), 'infer:latency(ms):100%': infer_latency_sli(1.0), 'infer:latency(ms):avg': np.mean(eval_latencies), 'infer:latency(ms):std': np.std(eval_latencies), 'infer:latency(ms):sum': np.sum(eval_latencies), 'infer:throughput(samples/s):avg': eval_throughput, }) preds = np.argmax(preds, axis=1) if args.do_predict: dump_predictions( os.path.join(args.output_dir, 'predictions.json'), label_map, preds, eval_examples, ) if args.do_eval: results['eval:loss'] = eval_loss / nb_eval_steps eval_result = compute_metrics(args.task_name, preds, out_label_ids) results.update(eval_result) if is_main_process(): logger.info("***** Results *****") for key in sorted(results.keys()): logger.info(" %s = %s", key, str(results[key])) with open(os.path.join(args.output_dir, "results.txt"), "w") as writer: json.dump(results, writer) return results if __name__ == "__main__": main(parse_args())
[ "logging.getLogger", "apex.amp.scale_loss", "torch.nn.CrossEntropyLoss", "tokenization.BertTokenizer", "torch.cuda.device_count", "optimization.BertAdam", "torch.cuda.synchronize", "torch.utils.data.distributed.DistributedSampler", "apex.amp.initialize", "torch.cuda.is_available", "torch._C._jit...
[((847, 886), 'torch._C._jit_set_profiling_mode', 'torch._C._jit_set_profiling_mode', (['(False)'], {}), '(False)\n', (879, 886), False, 'import torch\n'), ((887, 930), 'torch._C._jit_set_profiling_executor', 'torch._C._jit_set_profiling_executor', (['(False)'], {}), '(False)\n', (923, 930), False, 'import torch\n'), ((933, 1076), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)s - %(levelname)s - %(name)s - %(message)s"""', 'datefmt': '"""%m/%d/%Y %H:%M:%S"""', 'level': 'logging.INFO'}), "(format=\n '%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt=\n '%m/%d/%Y %H:%M:%S', level=logging.INFO)\n", (952, 1076), False, 'import logging\n'), ((1116, 1143), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1133, 1143), False, 'import logging\n'), ((1187, 1209), 'numpy.argmax', 'np.argmax', (['out'], {'axis': '(1)'}), '(out, axis=1)\n', (1196, 1209), True, 'import numpy as np\n'), ((1221, 1246), 'numpy.sum', 'np.sum', (['(outputs == labels)'], {}), '(outputs == labels)\n', (1227, 1246), True, 'import numpy as np\n'), ((5316, 5333), 'utils.is_main_process', 'is_main_process', ([], {}), '()\n', (5331, 5333), False, 'from utils import is_main_process, mkdir_by_main_process, format_step, get_world_size\n'), ((5590, 5628), 'utils.mkdir_by_main_process', 'mkdir_by_main_process', (['args.output_dir'], {}), '(args.output_dir)\n', (5611, 5628), False, 'from utils import is_main_process, mkdir_by_main_process, format_step, get_world_size\n'), ((6405, 6427), 'random.seed', 'random.seed', (['args.seed'], {}), '(args.seed)\n', (6416, 6427), False, 'import random\n'), ((6432, 6457), 'numpy.random.seed', 'np.random.seed', (['args.seed'], {}), '(args.seed)\n', (6446, 6457), True, 'import numpy as np\n'), ((6462, 6490), 'torch.manual_seed', 'torch.manual_seed', (['args.seed'], {}), '(args.seed)\n', (6479, 6490), False, 'import torch\n'), ((6671, 6748), 'tokenization.BertTokenizer', 'BertTokenizer', (['args.vocab_file'], {'do_lower_case': 'args.do_lower_case', 'max_len': '(512)'}), '(args.vocab_file, do_lower_case=args.do_lower_case, max_len=512)\n', (6684, 6748), False, 'from tokenization import BertTokenizer\n'), ((7624, 7676), 'modeling.BertConfig.from_json_file', 'modeling.BertConfig.from_json_file', (['args.config_file'], {}), '(args.config_file)\n', (7658, 7676), False, 'import modeling\n'), ((7881, 7950), 'modeling.BertForSequenceClassification', 'modeling.BertForSequenceClassification', (['config'], {'num_labels': 'num_labels'}), '(config, num_labels=num_labels)\n', (7919, 7950), False, 'import modeling\n'), ((8958, 8985), 'torch.nn.CrossEntropyLoss', 'torch.nn.CrossEntropyLoss', ([], {}), '()\n', (8983, 8985), False, 'import torch\n'), ((16567, 16584), 'utils.is_main_process', 'is_main_process', ([], {}), '()\n', (16582, 16584), False, 'from utils import is_main_process, mkdir_by_main_process, format_step, get_world_size\n'), ((2541, 2692), 'apex.amp.initialize', 'amp.initialize', (['model'], {'optimizers': 'optimizer', 'opt_level': '"""O2"""', 'keep_batchnorm_fp32': '(False)', 'loss_scale': "('dynamic' if loss_scale == 0 else loss_scale)"}), "(model, optimizers=optimizer, opt_level='O2',\n keep_batchnorm_fp32=False, loss_scale='dynamic' if loss_scale == 0 else\n loss_scale)\n", (2555, 2692), False, 'from apex import amp\n'), ((3806, 3836), 'json.dump', 'json.dump', (['predictions', 'writer'], {}), '(predictions, writer)\n', (3815, 3836), False, 'import json\n'), ((4139, 4228), 'ptvsd.enable_attach', 'ptvsd.enable_attach', ([], {'address': '(args.server_ip, args.server_port)', 'redirect_output': '(True)'}), '(address=(args.server_ip, args.server_port),\n redirect_output=True)\n', (4158, 4228), False, 'import ptvsd\n'), ((4268, 4291), 'ptvsd.wait_for_attach', 'ptvsd.wait_for_attach', ([], {}), '()\n', (4289, 4291), False, 'import ptvsd\n'), ((4467, 4492), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\n', (4490, 4492), False, 'import torch\n'), ((4511, 4549), 'torch.cuda.set_device', 'torch.cuda.set_device', (['args.local_rank'], {}), '(args.local_rank)\n', (4532, 4549), False, 'import torch\n'), ((4567, 4604), 'torch.device', 'torch.device', (['"""cuda"""', 'args.local_rank'], {}), "('cuda', args.local_rank)\n", (4579, 4604), False, 'import torch\n'), ((6517, 6554), 'torch.cuda.manual_seed_all', 'torch.cuda.manual_seed_all', (['args.seed'], {}), '(args.seed)\n', (6543, 6554), False, 'import torch\n'), ((8866, 8876), 'apex.parallel.DistributedDataParallel', 'DDP', (['model'], {}), '(model)\n', (8869, 8876), True, 'from apex.parallel import DistributedDataParallel as DDP\n'), ((9520, 9599), 'torch.utils.data.DataLoader', 'DataLoader', (['train_data'], {'sampler': 'train_sampler', 'batch_size': 'args.train_batch_size'}), '(train_data, sampler=train_sampler, batch_size=args.train_batch_size)\n', (9530, 9599), False, 'from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset\n'), ((9813, 9832), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (9830, 9832), False, 'import time\n'), ((12517, 12534), 'utils.is_main_process', 'is_main_process', ([], {}), '()\n', (12532, 12534), False, 'from utils import is_main_process, mkdir_by_main_process, format_step, get_world_size\n'), ((13092, 13120), 'torch.utils.data.SequentialSampler', 'SequentialSampler', (['eval_data'], {}), '(eval_data)\n', (13109, 13120), False, 'from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset\n'), ((13147, 13223), 'torch.utils.data.DataLoader', 'DataLoader', (['eval_data'], {'sampler': 'eval_sampler', 'batch_size': 'args.eval_batch_size'}), '(eval_data, sampler=eval_sampler, batch_size=args.eval_batch_size)\n', (13157, 13223), False, 'from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset\n'), ((14857, 14881), 'torch.cuda.synchronize', 'torch.cuda.synchronize', ([], {}), '()\n', (14879, 14881), False, 'import torch\n'), ((16108, 16132), 'numpy.argmax', 'np.argmax', (['preds'], {'axis': '(1)'}), '(preds, axis=1)\n', (16117, 16132), True, 'import numpy as np\n'), ((16909, 16921), 'helpers.arg_parser.parse_args', 'parse_args', ([], {}), '()\n', (16919, 16921), False, 'from helpers.arg_parser import parse_args\n'), ((2377, 2462), 'apex.optimizers.FusedAdam', 'FusedAdam', (['optimizer_grouped_parameters'], {'lr': 'learning_rate', 'bias_correction': '(False)'}), '(optimizer_grouped_parameters, lr=learning_rate, bias_correction=False\n )\n', (2386, 2462), False, 'from apex.optimizers import FusedAdam\n'), ((2995, 3100), 'schedulers.LinearWarmUpScheduler', 'LinearWarmUpScheduler', (['optimizer'], {'warmup': 'warmup_proportion', 'total_steps': 'num_train_optimization_steps'}), '(optimizer, warmup=warmup_proportion, total_steps=\n num_train_optimization_steps)\n', (3016, 3100), False, 'from schedulers import LinearWarmUpScheduler\n'), ((3280, 3405), 'optimization.BertAdam', 'BertAdam', (['optimizer_grouped_parameters'], {'lr': 'learning_rate', 'warmup': 'warmup_proportion', 't_total': 'num_train_optimization_steps'}), '(optimizer_grouped_parameters, lr=learning_rate, warmup=\n warmup_proportion, t_total=num_train_optimization_steps)\n', (3288, 3405), False, 'from optimization import BertAdam, warmup_linear\n'), ((4743, 4777), 'torch.distributed.is_initialized', 'torch.distributed.is_initialized', ([], {}), '()\n', (4775, 4777), False, 'import torch\n'), ((4791, 4843), 'torch.distributed.init_process_group', 'torch.distributed.init_process_group', ([], {'backend': '"""nccl"""'}), "(backend='nccl')\n", (4827, 4843), False, 'import torch\n'), ((5347, 5378), 'os.path.exists', 'os.path.exists', (['args.output_dir'], {}), '(args.output_dir)\n', (5361, 5378), False, 'import os\n'), ((5383, 5410), 'os.listdir', 'os.listdir', (['args.output_dir'], {}), '(args.output_dir)\n', (5393, 5410), False, 'import os\n'), ((8082, 8134), 'torch.load', 'torch.load', (['args.init_checkpoint'], {'map_location': '"""cpu"""'}), "(args.init_checkpoint, map_location='cpu')\n", (8092, 8134), False, 'import torch\n'), ((8913, 8941), 'torch.nn.DataParallel', 'torch.nn.DataParallel', (['model'], {}), '(model)\n', (8934, 8941), False, 'import torch\n'), ((9394, 9419), 'torch.utils.data.RandomSampler', 'RandomSampler', (['train_data'], {}), '(train_data)\n', (9407, 9419), False, 'from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset\n'), ((9462, 9492), 'torch.utils.data.distributed.DistributedSampler', 'DistributedSampler', (['train_data'], {}), '(train_data)\n', (9480, 9492), False, 'from torch.utils.data.distributed import DistributedSampler\n'), ((11458, 11477), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (11475, 11477), False, 'import time\n'), ((11976, 11993), 'utils.is_main_process', 'is_main_process', ([], {}), '()\n', (11991, 11993), False, 'from utils import is_main_process, mkdir_by_main_process, format_step, get_world_size\n'), ((16825, 16851), 'json.dump', 'json.dump', (['results', 'writer'], {}), '(results, writer)\n', (16834, 16851), False, 'import json\n'), ((7554, 7588), 'torch.distributed.get_world_size', 'torch.distributed.get_world_size', ([], {}), '()\n', (7586, 7588), False, 'import torch\n'), ((10002, 10042), 'tqdm.tqdm', 'tqdm', (['train_dataloader'], {'desc': '"""Iteration"""'}), "(train_dataloader, desc='Iteration')\n", (10006, 10042), False, 'from tqdm import tqdm, trange\n'), ((12199, 12251), 'os.path.join', 'os.path.join', (['args.output_dir', 'modeling.WEIGHTS_NAME'], {}), '(args.output_dir, modeling.WEIGHTS_NAME)\n', (12211, 12251), False, 'import os\n'), ((13436, 13472), 'torch.cuda.Event', 'torch.cuda.Event', ([], {'enable_timing': '(True)'}), '(enable_timing=True)\n', (13452, 13472), False, 'import torch\n'), ((13498, 13534), 'torch.cuda.Event', 'torch.cuda.Event', ([], {'enable_timing': '(True)'}), '(enable_timing=True)\n', (13514, 13534), False, 'import torch\n'), ((13963, 13978), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (13976, 13978), False, 'import torch\n'), ((15363, 15386), 'numpy.mean', 'np.mean', (['eval_latencies'], {}), '(eval_latencies)\n', (15370, 15386), True, 'import numpy as np\n'), ((15870, 15893), 'numpy.mean', 'np.mean', (['eval_latencies'], {}), '(eval_latencies)\n', (15877, 15893), True, 'import numpy as np\n'), ((15932, 15954), 'numpy.std', 'np.std', (['eval_latencies'], {}), '(eval_latencies)\n', (15938, 15954), True, 'import numpy as np\n'), ((15993, 16015), 'numpy.sum', 'np.sum', (['eval_latencies'], {}), '(eval_latencies)\n', (15999, 16015), True, 'import numpy as np\n'), ((16207, 16256), 'os.path.join', 'os.path.join', (['args.output_dir', '"""predictions.json"""'], {}), "(args.output_dir, 'predictions.json')\n", (16219, 16256), False, 'import os\n'), ((16751, 16795), 'os.path.join', 'os.path.join', (['args.output_dir', '"""results.txt"""'], {}), "(args.output_dir, 'results.txt')\n", (16763, 16795), False, 'import os\n'), ((4392, 4417), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (4415, 4417), False, 'import torch\n'), ((12310, 12361), 'os.path.join', 'os.path.join', (['args.output_dir', 'modeling.CONFIG_NAME'], {}), '(args.output_dir, modeling.CONFIG_NAME)\n', (12322, 12361), False, 'import os\n'), ((10763, 10794), 'apex.amp.scale_loss', 'amp.scale_loss', (['loss', 'optimizer'], {}), '(loss, optimizer)\n', (10777, 10794), False, 'from apex import amp\n'), ((11903, 11919), 'utils.get_world_size', 'get_world_size', ([], {}), '()\n', (11917, 11919), False, 'from utils import is_main_process, mkdir_by_main_process, format_step, get_world_size\n')]
# use accumulated_freq approach and nearest_neighbor regression for making forecasts import os import sys import logging import logging.handlers as handlers import json import itertools as it import pandas as pd import numpy as np from sklearn.metrics import mean_squared_error from sklearn import neighbors # open local settings with open('./settings.json') as local_json_file: local_submodule_settings = json.loads(local_json_file.read()) local_json_file.close() # log setup current_script_name = os.path.basename(__file__).split('.')[0] log_path_filename = ''.join([local_submodule_settings['log_path'], current_script_name, '.log']) logging.basicConfig(filename=log_path_filename, level=logging.DEBUG, format='%(asctime)s %(levelname)s %(name)s %(message)s') logger = logging.getLogger(__name__) logHandler = handlers.RotatingFileHandler(log_path_filename, maxBytes=10485760, backupCount=5) logger.addHandler(logHandler) # load custom libraries sys.path.insert(1, local_submodule_settings['custom_library_path']) from mini_module_submission_generator import save_submission from stochastic_model_obtain_results import stochastic_simulation_results_analysis from save_forecast_and_make_submission import save_forecast_and_submission # functions definitions def acc_freq_nearest_neighbor_regressor(local_afnnr_settings, local_afnnr_hyperparameters, local_acc_freq_array): try: print('training acc_freq approach nearest_neighbor_regression model') nof_time_series = local_afnnr_settings['number_of_time_series'] nof_days = local_afnnr_hyperparameters['days_in_focus_frame'] local_afnnr_forecast_horizon_days = local_afnnr_settings['forecast_horizon_days'] + 1 local_y_pred = np.zeros(shape=(nof_time_series, local_afnnr_forecast_horizon_days), dtype=np.dtype('float32')) # applying nearest neighbor regression n_neighbors = local_afnnr_hyperparameters['n_neighbors'] nof_samples = local_afnnr_hyperparameters['nof_samples'] for local_time_serie in range(nof_time_series): # creating training data local_x_train, local_y_train = [], [] for sample in range(0, nof_samples): local_x_train.append( local_acc_freq_array[local_time_serie: local_time_serie + 1, -sample - 1 - local_afnnr_forecast_horizon_days + nof_days: -sample - 1 + nof_days]) local_y_train.append(local_acc_freq_array[local_time_serie: local_time_serie + 1, -sample - local_afnnr_forecast_horizon_days + nof_days: -sample + nof_days]) local_x_train = np.array(local_x_train) local_x_train = local_x_train.reshape(local_x_train.shape[0], local_x_train.shape[2]) local_y_train = np.array(local_y_train) local_y_train = local_y_train.reshape(local_y_train.shape[0], local_y_train.shape[2]) local_x_input = local_y_train[-1].reshape(1, -1) # regression based in nearest_neighbor for i, weights in enumerate(['uniform', 'distance']): knn = neighbors.KNeighborsRegressor(n_neighbors, weights=weights) local_y_output = knn.fit(local_x_train, local_y_train).predict(local_x_input) local_y_pred[local_time_serie, :] = local_y_output except Exception as acc_freq_nearest_neighbor_error: print('acc_freq nearest neighbor regression function error: ', acc_freq_nearest_neighbor_error) logger.info('error in acc_freq nearest neighbor regression function') logger.error(str(acc_freq_nearest_neighbor_error), exc_info=True) return False return local_y_pred # classes definitions class generate_forecast_and_calculate_mse: def execute(self, local_settings, local_raw_unit_sales, local_raw_unit_sales_ground_truth): try: print('executing acc_freq and nearest_neighbor regression (ninth model)') # opening hyperparameters with open(''.join([local_settings['hyperparameters_path'], 'acc_freq_and_nearest_neighbor_model_hyperparameters.json'])) \ as local_r_json_file: local_grc_model_hyperparameters = json.loads(local_r_json_file.read()) local_r_json_file.close() local_forecast_name = 'ninth_model_acc_freq_and_nearest_neighbor_regression_forecast' local_nof_time_series = local_settings['number_of_time_series'] local_forecast_horizon_days = local_settings['forecast_horizon_days'] local_forecasts = np.zeros(shape=(local_nof_time_series * 2, local_forecast_horizon_days), dtype=np.dtype('float32')) # generate accumulated_frequencies (transform) local_days_in_focus = local_grc_model_hyperparameters['days_in_focus_frame'] accumulated_frequency_array = \ np.zeros(shape=(local_nof_time_series, local_days_in_focus), dtype=np.dtype('float32')) local_unit_sales_data = local_raw_unit_sales[:, -local_days_in_focus:] for local_day in range(local_days_in_focus): if local_day != 0: accumulated_frequency_array[:, local_day] = \ np.add(accumulated_frequency_array[:, local_day - 1], local_unit_sales_data[:, local_day]) else: accumulated_frequency_array[:, 0] = local_unit_sales_data[:, 0] # apply regression to acc_freq acc_freq_and_nearest_neighbor_forecast_aggregated = \ acc_freq_nearest_neighbor_regressor(local_settings, local_grc_model_hyperparameters, accumulated_frequency_array) # de-transform to unit_sales forecasts # passing from predicted accumulated absolute frequencies to sales for day y_pred = np.zeros(shape=(local_nof_time_series, local_forecast_horizon_days), dtype=np.dtype('float32')) print(acc_freq_and_nearest_neighbor_forecast_aggregated.shape) for day in range(local_forecast_horizon_days): next_acc_freq = acc_freq_and_nearest_neighbor_forecast_aggregated[:, day + 1: day + 2] next_acc_freq = next_acc_freq.reshape(next_acc_freq.shape[0], 1) y_pred[:, day: day + 1] = \ np.add(next_acc_freq, -acc_freq_and_nearest_neighbor_forecast_aggregated[:, day: day + 1]).clip(0) print('y_pred shape:', y_pred.shape) print(y_pred) # generating correct best fixed forecasts local_forecasts[:local_nof_time_series, :] = y_pred # dealing with Validation stage or Evaluation stage if local_settings['competition_stage'] == 'submitting_after_June_1th_using_1941days': local_forecasts[:local_nof_time_series, :] = local_raw_unit_sales[:, -local_forecast_horizon_days:] local_forecasts[local_nof_time_series:, :] = y_pred # save forecast and submission store_and_submit_ninth_model_forecast = save_forecast_and_submission() ninth_model_save_review = \ store_and_submit_ninth_model_forecast.store_and_submit(''.join([local_forecast_name,'_data']), local_settings, y_pred) if ninth_model_save_review: print('acc_freq nearest neighbor regression generation successfully completed') else: print('error at acc_freq nearest neighbor regression forecast generation') # calculate mse and save results calculate_mse = stochastic_simulation_results_analysis() calculate_mse_time_series_not_improved = \ calculate_mse.evaluate_stochastic_simulation(local_settings, local_grc_model_hyperparameters, local_raw_unit_sales, local_raw_unit_sales_ground_truth, local_forecast_name) print('number of ts not improved with acc_freq nearest neighbor regression ', len(calculate_mse_time_series_not_improved)) except Exception as submodule_error: print('acc_freq nearest neighbor regression forecast generation submodule_error: ', submodule_error) logger.info('error in acc_freq nearest neighbor regression generation submodule') logger.error(str(submodule_error), exc_info=True) return False return True
[ "logging.basicConfig", "logging.getLogger", "numpy.dtype", "sys.path.insert", "numpy.add", "sklearn.neighbors.KNeighborsRegressor", "logging.handlers.RotatingFileHandler", "stochastic_model_obtain_results.stochastic_simulation_results_analysis", "numpy.array", "os.path.basename", "save_forecast_...
[((647, 777), 'logging.basicConfig', 'logging.basicConfig', ([], {'filename': 'log_path_filename', 'level': 'logging.DEBUG', 'format': '"""%(asctime)s %(levelname)s %(name)s %(message)s"""'}), "(filename=log_path_filename, level=logging.DEBUG, format\n ='%(asctime)s %(levelname)s %(name)s %(message)s')\n", (666, 777), False, 'import logging\n'), ((802, 829), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (819, 829), False, 'import logging\n'), ((843, 928), 'logging.handlers.RotatingFileHandler', 'handlers.RotatingFileHandler', (['log_path_filename'], {'maxBytes': '(10485760)', 'backupCount': '(5)'}), '(log_path_filename, maxBytes=10485760,\n backupCount=5)\n', (871, 928), True, 'import logging.handlers as handlers\n'), ((980, 1047), 'sys.path.insert', 'sys.path.insert', (['(1)', "local_submodule_settings['custom_library_path']"], {}), "(1, local_submodule_settings['custom_library_path'])\n", (995, 1047), False, 'import sys\n'), ((509, 535), 'os.path.basename', 'os.path.basename', (['__file__'], {}), '(__file__)\n', (525, 535), False, 'import os\n'), ((2752, 2775), 'numpy.array', 'np.array', (['local_x_train'], {}), '(local_x_train)\n', (2760, 2775), True, 'import numpy as np\n'), ((2902, 2925), 'numpy.array', 'np.array', (['local_y_train'], {}), '(local_y_train)\n', (2910, 2925), True, 'import numpy as np\n'), ((7307, 7337), 'save_forecast_and_make_submission.save_forecast_and_submission', 'save_forecast_and_submission', ([], {}), '()\n', (7335, 7337), False, 'from save_forecast_and_make_submission import save_forecast_and_submission\n'), ((7974, 8014), 'stochastic_model_obtain_results.stochastic_simulation_results_analysis', 'stochastic_simulation_results_analysis', ([], {}), '()\n', (8012, 8014), False, 'from stochastic_model_obtain_results import stochastic_simulation_results_analysis\n'), ((1861, 1880), 'numpy.dtype', 'np.dtype', (['"""float32"""'], {}), "('float32')\n", (1869, 1880), True, 'import numpy as np\n'), ((3224, 3283), 'sklearn.neighbors.KNeighborsRegressor', 'neighbors.KNeighborsRegressor', (['n_neighbors'], {'weights': 'weights'}), '(n_neighbors, weights=weights)\n', (3253, 3283), False, 'from sklearn import neighbors\n'), ((4861, 4880), 'numpy.dtype', 'np.dtype', (['"""float32"""'], {}), "('float32')\n", (4869, 4880), True, 'import numpy as np\n'), ((5158, 5177), 'numpy.dtype', 'np.dtype', (['"""float32"""'], {}), "('float32')\n", (5166, 5177), True, 'import numpy as np\n'), ((5444, 5539), 'numpy.add', 'np.add', (['accumulated_frequency_array[:, local_day - 1]', 'local_unit_sales_data[:, local_day]'], {}), '(accumulated_frequency_array[:, local_day - 1], local_unit_sales_data\n [:, local_day])\n', (5450, 5539), True, 'import numpy as np\n'), ((6169, 6188), 'numpy.dtype', 'np.dtype', (['"""float32"""'], {}), "('float32')\n", (6177, 6188), True, 'import numpy as np\n'), ((6572, 6665), 'numpy.add', 'np.add', (['next_acc_freq', '(-acc_freq_and_nearest_neighbor_forecast_aggregated[:, day:day + 1])'], {}), '(next_acc_freq, -acc_freq_and_nearest_neighbor_forecast_aggregated[:,\n day:day + 1])\n', (6578, 6665), True, 'import numpy as np\n')]
#!/usr/bin/env python # coding: utf8 """ Unit testing for audio adapter. """ __email__ = '<EMAIL>' __author__ = '<NAME>' __license__ = 'MIT License' from os.path import join from tempfile import TemporaryDirectory # pylint: disable=import-error from pytest import fixture, raises import numpy as np import ffmpeg # pylint: enable=import-error from spleeter import SpleeterError from spleeter.audio.adapter import AudioAdapter from spleeter.audio.adapter import get_default_audio_adapter from spleeter.audio.adapter import get_audio_adapter from spleeter.audio.ffmpeg import FFMPEGProcessAudioAdapter TEST_AUDIO_DESCRIPTOR = 'audio_example.mp3' TEST_OFFSET = 0 TEST_DURATION = 600. TEST_SAMPLE_RATE = 44100 @fixture(scope='session') def adapter(): """ Target test audio adapter fixture. """ return get_default_audio_adapter() @fixture(scope='session') def audio_data(adapter): """ Audio data fixture based on sample loading from adapter. """ return adapter.load( TEST_AUDIO_DESCRIPTOR, TEST_OFFSET, TEST_DURATION, TEST_SAMPLE_RATE) def test_default_adapter(adapter): """ Test adapter as default adapter. """ assert isinstance(adapter, FFMPEGProcessAudioAdapter) assert adapter is AudioAdapter.DEFAULT def test_load(audio_data): """ Test audio loading. """ waveform, sample_rate = audio_data assert sample_rate == TEST_SAMPLE_RATE assert waveform is not None assert waveform.dtype == np.dtype('float32') assert len(waveform.shape) == 2 assert waveform.shape[0] == 479832 assert waveform.shape[1] == 2 def test_load_error(adapter): """ Test load ffprobe exception """ with raises(SpleeterError): adapter.load( 'Paris City Jazz', TEST_OFFSET, TEST_DURATION, TEST_SAMPLE_RATE) def test_save(adapter, audio_data): """ Test audio saving. """ with TemporaryDirectory() as directory: path = join(directory, 'ffmpeg-save.mp3') adapter.save( path, audio_data[0], audio_data[1]) probe = ffmpeg.probe(TEST_AUDIO_DESCRIPTOR) assert len(probe['streams']) == 1 stream = probe['streams'][0] assert stream['codec_type'] == 'audio' assert stream['channels'] == 2 assert stream['duration'] == '10.919184'
[ "tempfile.TemporaryDirectory", "os.path.join", "ffmpeg.probe", "spleeter.audio.adapter.get_default_audio_adapter", "pytest.raises", "pytest.fixture", "numpy.dtype" ]
[((716, 740), 'pytest.fixture', 'fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (723, 740), False, 'from pytest import fixture, raises\n'), ((845, 869), 'pytest.fixture', 'fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (852, 869), False, 'from pytest import fixture, raises\n'), ((814, 841), 'spleeter.audio.adapter.get_default_audio_adapter', 'get_default_audio_adapter', ([], {}), '()\n', (839, 841), False, 'from spleeter.audio.adapter import get_default_audio_adapter\n'), ((1477, 1496), 'numpy.dtype', 'np.dtype', (['"""float32"""'], {}), "('float32')\n", (1485, 1496), True, 'import numpy as np\n'), ((1687, 1708), 'pytest.raises', 'raises', (['SpleeterError'], {}), '(SpleeterError)\n', (1693, 1708), False, 'from pytest import fixture, raises\n'), ((1923, 1943), 'tempfile.TemporaryDirectory', 'TemporaryDirectory', ([], {}), '()\n', (1941, 1943), False, 'from tempfile import TemporaryDirectory\n'), ((1973, 2007), 'os.path.join', 'join', (['directory', '"""ffmpeg-save.mp3"""'], {}), "(directory, 'ffmpeg-save.mp3')\n", (1977, 2007), False, 'from os.path import join\n'), ((2118, 2153), 'ffmpeg.probe', 'ffmpeg.probe', (['TEST_AUDIO_DESCRIPTOR'], {}), '(TEST_AUDIO_DESCRIPTOR)\n', (2130, 2153), False, 'import ffmpeg\n')]
# Copyright 2021 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================= """Auditing a model which computes the mean of a synthetic dataset. This gives an example for instrumenting the auditor to audit a user-given sample.""" import numpy as np import tensorflow.compat.v1 as tf from tensorflow_privacy.privacy.analysis.rdp_accountant import compute_rdp from tensorflow_privacy.privacy.analysis.rdp_accountant import get_privacy_spent from tensorflow_privacy.privacy.optimizers import dp_optimizer_vectorized from absl import app from absl import flags import audit #### FLAGS FLAGS = flags.FLAGS flags.DEFINE_float('learning_rate', 0.15, 'Learning rate for training') flags.DEFINE_float('noise_multiplier', 1.1, 'Ratio of the standard deviation to the clipping norm') flags.DEFINE_float('l2_norm_clip', 1.0, 'Clipping norm') flags.DEFINE_integer('batch_size', 250, 'Batch size') flags.DEFINE_integer('d', 250, 'Data dimension') flags.DEFINE_integer('epochs', 1, 'Number of epochs') flags.DEFINE_integer( 'microbatches', 250, 'Number of microbatches ' '(must evenly divide batch_size)') flags.DEFINE_string('attack_type', "clip_aware", 'clip_aware or bkdr') flags.DEFINE_integer('num_trials', 100, 'Number of trials for auditing') flags.DEFINE_float('attack_l2_norm', 10, 'Size of poisoning data') flags.DEFINE_float('alpha', 0.05, '1-confidence') FLAGS = flags.FLAGS def compute_epsilon(train_size): """Computes epsilon value for given hyperparameters.""" if FLAGS.noise_multiplier == 0.0: return float('inf') orders = [1 + x / 10. for x in range(1, 100)] + list(range(12, 64)) sampling_probability = FLAGS.batch_size / train_size steps = FLAGS.epochs * train_size / FLAGS.batch_size rdp = compute_rdp(q=sampling_probability, noise_multiplier=FLAGS.noise_multiplier, steps=steps, orders=orders) # Delta is set to approximate 1 / (number of training points). return get_privacy_spent(orders, rdp, target_delta=1e-5)[0] def build_model(x, y): del x, y model = tf.keras.Sequential([tf.keras.layers.Dense( 1, input_shape=(FLAGS.d,), use_bias=False, kernel_initializer=tf.keras.initializers.Zeros())]) return model def train_model(model, train_x, train_y): """Train the model on given data.""" optimizer = dp_optimizer_vectorized.VectorizedDPSGD( l2_norm_clip=FLAGS.l2_norm_clip, noise_multiplier=FLAGS.noise_multiplier, num_microbatches=FLAGS.microbatches, learning_rate=FLAGS.learning_rate) # gradient of (.5-x.w)^2 is 2(.5-x.w)x loss = tf.keras.losses.MeanSquaredError(reduction=tf.losses.Reduction.NONE) # Compile model with Keras model.compile(optimizer=optimizer, loss=loss, metrics=['mse']) # Train model with Keras model.fit(train_x, train_y, epochs=FLAGS.epochs, validation_data=(train_x, train_y), batch_size=FLAGS.batch_size, verbose=0) return model def membership_test(model, pois_x, pois_y): """Membership inference - detect poisoning.""" del pois_y return model.predict(pois_x) def gen_data(n, d): """Make binomial dataset.""" x = np.random.normal(size=(n, d)) y = np.ones(shape=(n,))/2. return x, y def train_and_score(dataset): """Complete training run with membership inference score.""" x, y, pois_x, pois_y, i = dataset np.random.seed(i) tf.set_random_seed(i) model = build_model(x, y) model = train_model(model, x, y) return membership_test(model, pois_x, pois_y) def main(unused_argv): del unused_argv # Load training and test data. np.random.seed(0) x, y = gen_data(1 + FLAGS.batch_size, FLAGS.d) auditor = audit.AuditAttack(x, y, train_and_score) # we will instrument the auditor to simply bkdr the last feature pois_x1, pois_x2 = x[:-1].copy(), x[:-1].copy() pois_x1[-1] = x[-1] pois_y = y[:-1] target_x = x[-1][None, :] assert np.unique(np.nonzero(pois_x1 - pois_x2)[0]).size == 1 pois_data = (pois_x1, pois_y), (pois_x2, pois_y), (target_x, y[-1]) poisoning = {} poisoning["data"] = (pois_data[0], pois_data[1]) poisoning["pois"] = pois_data[2] auditor.poisoning = poisoning thresh, _, _ = auditor.run(1, None, FLAGS.num_trials, alpha=FLAGS.alpha) _, eps, acc = auditor.run(1, None, FLAGS.num_trials, alpha=FLAGS.alpha, threshold=thresh) epsilon_upper_bound = compute_epsilon(FLAGS.batch_size) print("Analysis epsilon is {}.".format(epsilon_upper_bound)) print("At threshold={}, epsilon={}.".format(thresh, eps)) print("The best accuracy at distinguishing poisoning is {}.".format(acc)) if __name__ == '__main__': app.run(main)
[ "numpy.random.normal", "numpy.ones", "tensorflow.compat.v1.keras.losses.MeanSquaredError", "absl.flags.DEFINE_integer", "absl.app.run", "tensorflow_privacy.privacy.analysis.rdp_accountant.get_privacy_spent", "tensorflow_privacy.privacy.analysis.rdp_accountant.compute_rdp", "tensorflow.compat.v1.keras....
[((1221, 1292), 'absl.flags.DEFINE_float', 'flags.DEFINE_float', (['"""learning_rate"""', '(0.15)', '"""Learning rate for training"""'], {}), "('learning_rate', 0.15, 'Learning rate for training')\n", (1239, 1292), False, 'from absl import flags\n'), ((1293, 1396), 'absl.flags.DEFINE_float', 'flags.DEFINE_float', (['"""noise_multiplier"""', '(1.1)', '"""Ratio of the standard deviation to the clipping norm"""'], {}), "('noise_multiplier', 1.1,\n 'Ratio of the standard deviation to the clipping norm')\n", (1311, 1396), False, 'from absl import flags\n'), ((1412, 1468), 'absl.flags.DEFINE_float', 'flags.DEFINE_float', (['"""l2_norm_clip"""', '(1.0)', '"""Clipping norm"""'], {}), "('l2_norm_clip', 1.0, 'Clipping norm')\n", (1430, 1468), False, 'from absl import flags\n'), ((1469, 1522), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""batch_size"""', '(250)', '"""Batch size"""'], {}), "('batch_size', 250, 'Batch size')\n", (1489, 1522), False, 'from absl import flags\n'), ((1523, 1571), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""d"""', '(250)', '"""Data dimension"""'], {}), "('d', 250, 'Data dimension')\n", (1543, 1571), False, 'from absl import flags\n'), ((1572, 1625), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""epochs"""', '(1)', '"""Number of epochs"""'], {}), "('epochs', 1, 'Number of epochs')\n", (1592, 1625), False, 'from absl import flags\n'), ((1626, 1729), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""microbatches"""', '(250)', '"""Number of microbatches (must evenly divide batch_size)"""'], {}), "('microbatches', 250,\n 'Number of microbatches (must evenly divide batch_size)')\n", (1646, 1729), False, 'from absl import flags\n'), ((1738, 1808), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""attack_type"""', '"""clip_aware"""', '"""clip_aware or bkdr"""'], {}), "('attack_type', 'clip_aware', 'clip_aware or bkdr')\n", (1757, 1808), False, 'from absl import flags\n'), ((1809, 1881), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""num_trials"""', '(100)', '"""Number of trials for auditing"""'], {}), "('num_trials', 100, 'Number of trials for auditing')\n", (1829, 1881), False, 'from absl import flags\n'), ((1882, 1948), 'absl.flags.DEFINE_float', 'flags.DEFINE_float', (['"""attack_l2_norm"""', '(10)', '"""Size of poisoning data"""'], {}), "('attack_l2_norm', 10, 'Size of poisoning data')\n", (1900, 1948), False, 'from absl import flags\n'), ((1949, 1998), 'absl.flags.DEFINE_float', 'flags.DEFINE_float', (['"""alpha"""', '(0.05)', '"""1-confidence"""'], {}), "('alpha', 0.05, '1-confidence')\n", (1967, 1998), False, 'from absl import flags\n'), ((2360, 2468), 'tensorflow_privacy.privacy.analysis.rdp_accountant.compute_rdp', 'compute_rdp', ([], {'q': 'sampling_probability', 'noise_multiplier': 'FLAGS.noise_multiplier', 'steps': 'steps', 'orders': 'orders'}), '(q=sampling_probability, noise_multiplier=FLAGS.noise_multiplier,\n steps=steps, orders=orders)\n', (2371, 2468), False, 'from tensorflow_privacy.privacy.analysis.rdp_accountant import compute_rdp\n'), ((2960, 3154), 'tensorflow_privacy.privacy.optimizers.dp_optimizer_vectorized.VectorizedDPSGD', 'dp_optimizer_vectorized.VectorizedDPSGD', ([], {'l2_norm_clip': 'FLAGS.l2_norm_clip', 'noise_multiplier': 'FLAGS.noise_multiplier', 'num_microbatches': 'FLAGS.microbatches', 'learning_rate': 'FLAGS.learning_rate'}), '(l2_norm_clip=FLAGS.l2_norm_clip,\n noise_multiplier=FLAGS.noise_multiplier, num_microbatches=FLAGS.\n microbatches, learning_rate=FLAGS.learning_rate)\n', (2999, 3154), False, 'from tensorflow_privacy.privacy.optimizers import dp_optimizer_vectorized\n'), ((3222, 3290), 'tensorflow.compat.v1.keras.losses.MeanSquaredError', 'tf.keras.losses.MeanSquaredError', ([], {'reduction': 'tf.losses.Reduction.NONE'}), '(reduction=tf.losses.Reduction.NONE)\n', (3254, 3290), True, 'import tensorflow.compat.v1 as tf\n'), ((3802, 3831), 'numpy.random.normal', 'np.random.normal', ([], {'size': '(n, d)'}), '(size=(n, d))\n', (3818, 3831), True, 'import numpy as np\n'), ((4008, 4025), 'numpy.random.seed', 'np.random.seed', (['i'], {}), '(i)\n', (4022, 4025), True, 'import numpy as np\n'), ((4028, 4049), 'tensorflow.compat.v1.set_random_seed', 'tf.set_random_seed', (['i'], {}), '(i)\n', (4046, 4049), True, 'import tensorflow.compat.v1 as tf\n'), ((4239, 4256), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (4253, 4256), True, 'import numpy as np\n'), ((4320, 4360), 'audit.AuditAttack', 'audit.AuditAttack', (['x', 'y', 'train_and_score'], {}), '(x, y, train_and_score)\n', (4337, 4360), False, 'import audit\n'), ((5302, 5315), 'absl.app.run', 'app.run', (['main'], {}), '(main)\n', (5309, 5315), False, 'from absl import app\n'), ((2599, 2649), 'tensorflow_privacy.privacy.analysis.rdp_accountant.get_privacy_spent', 'get_privacy_spent', (['orders', 'rdp'], {'target_delta': '(1e-05)'}), '(orders, rdp, target_delta=1e-05)\n', (2616, 2649), False, 'from tensorflow_privacy.privacy.analysis.rdp_accountant import get_privacy_spent\n'), ((3838, 3857), 'numpy.ones', 'np.ones', ([], {'shape': '(n,)'}), '(shape=(n,))\n', (3845, 3857), True, 'import numpy as np\n'), ((2815, 2844), 'tensorflow.compat.v1.keras.initializers.Zeros', 'tf.keras.initializers.Zeros', ([], {}), '()\n', (2842, 2844), True, 'import tensorflow.compat.v1 as tf\n'), ((4566, 4595), 'numpy.nonzero', 'np.nonzero', (['(pois_x1 - pois_x2)'], {}), '(pois_x1 - pois_x2)\n', (4576, 4595), True, 'import numpy as np\n')]
from __future__ import print_function from collections import OrderedDict import vtk from vtk import vtkQuad from numpy import zeros, array, cross from numpy.linalg import norm # type: ignore from pyNastran.converters.dev.plot3d.plot3d import Plot3d from pyNastran.gui.gui_objects.gui_result import GuiResult raise NotImplementedError() class Plot3d_io(object): # pragma: no cover def __init__(self, gui): self.gui = gui def get_plot3d_wildcard_geometry_results_functions(self): data = ('Plot3D', 'Plot3D (*.p3d; *.p3da)', self.load_plot3d_geometry, None, None) return data def load_plot3d_geometry(self, p3d_filename, name='main'): print("load_plot3d_geometry") self.nid_map = {} #key = self.case_keys[self.icase] #case = self.result_cases[key] skip_reading = self._remove_old_geometry(p3d_filename) if skip_reading: return model = Plot3d(log=self.log, debug=self.debug) #self.model_type = model.model_type model.read_plot3d(p3d_filename) npoints = 0 nelements = 0 for iblock, shape in sorted(model.block_shapes.items()): npoints += shape[0] * shape[1] * shape[2] nelements += (shape[0] - 1) * (shape[1] - 1) * (shape[2] - 1) nblocks = len(model.block_shapes) self.nnodes = npoints self.nelements = nelements #nodes, elements, regions = model.get_points_elements_regions() #for nid,node in enumerate(nodes): #print "node[%s] = %s" % (nid, str(node)) self.grid.Allocate(self.nelements, 1000) points = vtk.vtkPoints() points.SetNumberOfPoints(self.nnodes) nid = 0 nid_base = 0 eid_base = 0 elem = vtkQuad() quad_type = elem.GetCellType() #nblocks = len(model.x) for iblock in range(nblocks): print("iblock =", iblock) nid_base = nid x = model.x[iblock] y = model.y[iblock] z = model.z[iblock] print("x.shape[%s] =" % iblock, x.shape) print(x) (ni, nj, nk) = x.shape assert nk == 1 for k in range(nk): for j in range(nj): for i in range(ni): points.InsertPoint( nid, x[i, j, 0], y[i, j, 0], z[i, j, 0]) nid += 1 for j in range(nj - 1): jstart = nid_base + j * ni for i in range(ni - 1): elem = vtkQuad() p1 = jstart + (i) p2 = jstart + (i + 1) p3 = jstart + (ni) + (i + 1) p4 = jstart + (ni) + (i) elem.GetPointIds().SetId(0, p1) elem.GetPointIds().SetId(1, p2) elem.GetPointIds().SetId(2, p3) elem.GetPointIds().SetId(3, p4) element = [p1, p2, p3, p4] self.grid.InsertNextCell(quad_type, elem.GetPointIds()) print(element) #jstart += ni #nid_base += ni * nj * nk eid_base += (ni-1) * (nj-1) * (nk-1) break #print("eid = ", eid) grid = self.gui.grid grid.SetPoints(points) grid.Modified() grid.Update() self.log_info("updated grid") #return # loadPlot3dResults - regions/loads self.gui.scalar_bar_actor.VisibilityOn() self.gui.scalar_bar_actor.Modified() self.gui.isubcase_name_map = {1: ['Plot3d', '']} cases = OrderedDict() ID = 1 #cases = self._fill_stl_case(cases, ID, elements) self.result_cases = cases self.case_keys = sorted(cases.keys()) #print "case_keys = ",self.case_keys #print "type(case_keys) = ",type(self.case_keys) self.ncases = min(0, len(self.result_cases) - 1) # number of keys in dictionary self.icase = 0 if self.ncases == 0 else -1 self.cycle_results() # start at ncase=0 def fill_plot3d_geometry_case(self, cases, ID, nodes, elements, regions, loads): #print "regions**** = ",regions #nNodes = self.nnodes #nElements = self.nelements #result_names = ['Cp', 'Mach', 'U', 'V', 'W', 'E', 'rho', #'rhoU', 'rhoV', 'rhoW', 'rhoE'] #nelements, three = elements.shape #print regions icase = 0 itime = 0 region_res = GuiResult(ID, header='Region', title='Region', location='centroid', scalar=regions) cases[icase] = region_res(nid_res, (itime, 'Region')) icase += 1 # centroidal Xc = zeros(len(elements), 'float64') Yc = zeros(len(elements), 'float64') Zc = zeros(len(elements), 'float64') area = zeros(len(elements), 'float64') Xn = zeros(len(nodes), 'float64') Yn = zeros(len(nodes), 'float64') Zn = zeros(len(nodes), 'float64') for i, element in enumerate(elements): p1, p2, p3, p4 = element P1 = array(nodes[p1]) P2 = array(nodes[p2]) P3 = array(nodes[p3]) P4 = array(nodes[p4]) a = P3 - P1 b = P4 - P2 A = 0.5 * norm(cross(a, b)) x, y, z = (P1 + P2 + P3 + P4) / 4.0 Xc[i] = x Yc[i] = y Zc[i] = z area[i] = A for i, node in enumerate(nodes): Xn[i] = node[0] Yn[i] = node[1] Zn[i] = node[2] cases[(ID, icase, 'node_x', 1, 'node', '%.2f', '')] = Xn cases[(ID, icase + 1, 'node_y', 1, 'node', '%.2f', '')] = Yn cases[(ID, icase + 2, 'node_z', 1, 'node', '%.2f', '')] = Zn cases[(ID, icase + 3, 'centroid_x', 1, 'centroid', '%.2f', '')] = Xc cases[(ID, icase + 4, 'centroid_y', 1, 'centroid', '%.2f', '')] = Yc cases[(ID, icase + 5, 'centroid_z', 1, 'centroid', '%.2f', '')] = Zc cases[(ID, icase + 6, 'Area', 1, 'centroid', '%.2f', '')] = area icase += 7 #print("load.keys() = ", loads.keys()) #for key in result_names: #if key in loads: #nodal_data = loads[key] #cases[(ID, key, 1, 'node', '%.3f')] = nodal_data return cases
[ "collections.OrderedDict", "vtk.vtkQuad", "numpy.cross", "pyNastran.converters.dev.plot3d.plot3d.Plot3d", "vtk.vtkPoints", "numpy.array", "pyNastran.gui.gui_objects.gui_result.GuiResult" ]
[((980, 1018), 'pyNastran.converters.dev.plot3d.plot3d.Plot3d', 'Plot3d', ([], {'log': 'self.log', 'debug': 'self.debug'}), '(log=self.log, debug=self.debug)\n', (986, 1018), False, 'from pyNastran.converters.dev.plot3d.plot3d import Plot3d\n'), ((1687, 1702), 'vtk.vtkPoints', 'vtk.vtkPoints', ([], {}), '()\n', (1700, 1702), False, 'import vtk\n'), ((1825, 1834), 'vtk.vtkQuad', 'vtkQuad', ([], {}), '()\n', (1832, 1834), False, 'from vtk import vtkQuad\n'), ((3735, 3748), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (3746, 3748), False, 'from collections import OrderedDict\n'), ((4648, 4736), 'pyNastran.gui.gui_objects.gui_result.GuiResult', 'GuiResult', (['ID'], {'header': '"""Region"""', 'title': '"""Region"""', 'location': '"""centroid"""', 'scalar': 'regions'}), "(ID, header='Region', title='Region', location='centroid', scalar=\n regions)\n", (4657, 4736), False, 'from pyNastran.gui.gui_objects.gui_result import GuiResult\n'), ((5277, 5293), 'numpy.array', 'array', (['nodes[p1]'], {}), '(nodes[p1])\n', (5282, 5293), False, 'from numpy import zeros, array, cross\n'), ((5311, 5327), 'numpy.array', 'array', (['nodes[p2]'], {}), '(nodes[p2])\n', (5316, 5327), False, 'from numpy import zeros, array, cross\n'), ((5345, 5361), 'numpy.array', 'array', (['nodes[p3]'], {}), '(nodes[p3])\n', (5350, 5361), False, 'from numpy import zeros, array, cross\n'), ((5379, 5395), 'numpy.array', 'array', (['nodes[p4]'], {}), '(nodes[p4])\n', (5384, 5395), False, 'from numpy import zeros, array, cross\n'), ((2642, 2651), 'vtk.vtkQuad', 'vtkQuad', ([], {}), '()\n', (2649, 2651), False, 'from vtk import vtkQuad\n'), ((5471, 5482), 'numpy.cross', 'cross', (['a', 'b'], {}), '(a, b)\n', (5476, 5482), False, 'from numpy import zeros, array, cross\n')]
import argparse import numpy as np import tensorflow as tf import os import sys import scipy.io as sio baseDir = os.path.dirname(os.path.abspath(__file__)) rootDir = os.path.dirname(baseDir) sys.path.append(baseDir) sys.path.append(os.path.join(rootDir, 'models')) sys.path.append(os.path.join(rootDir, 'utils')) parser = argparse.ArgumentParser() parser.add_argument('--gpu', type=int, default=0, help='GPU to use [default: GPU 0]') parser.add_argument('--batch_size', type=int, default=16, help='Batch Size during training [default: 16]') FLAGS = parser.parse_args() BATCH_SIZE = FLAGS.batch_size GPU_INDEX = FLAGS.gpu LOG_DIR = os.path.join(rootDir,'log_scannet') def parse_block_scene(datapath, scene_names): f = open(os.path.join(datapath,'log_block.txt'), 'r') blocklist = f.read().splitlines() block2scene = [] ordered_testlist = [] for line in blocklist: str = line.split(', ') if str[0] in scene_names: block2scene.append(tuple(str)) tfrecord_name = os.path.join(datapath,'%s.tfrecord'%str[0]) if not tfrecord_name in ordered_testlist: ordered_testlist.append(tfrecord_name) return block2scene, ordered_testlist def parse_fn(item): features = tf.parse_single_example( item, features={'index_label':tf.FixedLenFeature([], dtype=tf.string)}) index_label = tf.decode_raw(features['index_label'], tf.int32) index_label = tf.reshape(index_label, [-1, 1]) index_label = tf.cast(index_label,tf.float32) return index_label def input_fn(filelist, batch_size=16): dataset = tf.data.TFRecordDataset(filelist) dataset = dataset.map(parse_fn, num_parallel_calls=4) dataset = dataset.padded_batch(batch_size, padded_shapes=(None,1), padding_values=-1.0, drop_remainder=False) return dataset if __name__ == "__main__": dataDir = os.path.join(rootDir, 'data/scannet_3cm') blockindexDir = os.path.join(LOG_DIR, 'block_index') if not os.path.exists(blockindexDir): os.mkdir(blockindexDir) testlist = [line.rstrip() for line in open(os.path.join(dataDir, 'val_files.txt'))] SCENE_NAMES = [os.path.basename(item).replace('.tfrecord', '') for item in testlist] BLOCK2SCENE, TESTLIST = parse_block_scene(dataDir, SCENE_NAMES) print('block2scenes num:%d, testlist size:%d'%(len(BLOCK2SCENE), len(TESTLIST))) # ===============================Prepare the Dataset=============================== testset = input_fn(TESTLIST, BATCH_SIZE) test_iterator = testset.make_initializable_iterator() next_test_element = test_iterator.get_next() # =====================================The End===================================== # =================================Start a Session================================ config = tf.ConfigProto() config.gpu_options.allow_growth = True config.allow_soft_placement = True config.log_device_placement = False with tf.Session(config=config) as sess: sess.run(test_iterator.initializer) batch_idx = 0 while True: try: padded_all = sess.run(next_test_element) bsize = padded_all.shape[0] print(padded_all.shape) for b in range(bsize): # to write out the block data, and its predictions num = np.int32(BLOCK2SCENE[batch_idx*BATCH_SIZE+b][-1]) temp_out_data = padded_all[b, 0:num, -1] scene_name = BLOCK2SCENE[batch_idx*BATCH_SIZE+b][0] block_name = '%s_%d.mat'%(scene_name, batch_idx*BATCH_SIZE+b) print(os.path.join(blockindexDir, block_name)) sio.savemat(os.path.join(blockindexDir, block_name), {'index':temp_out_data}) batch_idx += 1 except tf.errors.OutOfRangeError: break # =====================================The End=====================================
[ "tensorflow.data.TFRecordDataset", "os.path.exists", "argparse.ArgumentParser", "tensorflow.Session", "numpy.int32", "os.path.join", "tensorflow.decode_raw", "os.path.dirname", "os.mkdir", "os.path.basename", "tensorflow.reshape", "os.path.abspath", "tensorflow.ConfigProto", "tensorflow.ca...
[((167, 191), 'os.path.dirname', 'os.path.dirname', (['baseDir'], {}), '(baseDir)\n', (182, 191), False, 'import os\n'), ((192, 216), 'sys.path.append', 'sys.path.append', (['baseDir'], {}), '(baseDir)\n', (207, 216), False, 'import sys\n'), ((324, 349), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (347, 349), False, 'import argparse\n'), ((635, 671), 'os.path.join', 'os.path.join', (['rootDir', '"""log_scannet"""'], {}), "(rootDir, 'log_scannet')\n", (647, 671), False, 'import os\n'), ((130, 155), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (145, 155), False, 'import os\n'), ((233, 264), 'os.path.join', 'os.path.join', (['rootDir', '"""models"""'], {}), "(rootDir, 'models')\n", (245, 264), False, 'import os\n'), ((282, 312), 'os.path.join', 'os.path.join', (['rootDir', '"""utils"""'], {}), "(rootDir, 'utils')\n", (294, 312), False, 'import os\n'), ((1390, 1438), 'tensorflow.decode_raw', 'tf.decode_raw', (["features['index_label']", 'tf.int32'], {}), "(features['index_label'], tf.int32)\n", (1403, 1438), True, 'import tensorflow as tf\n'), ((1457, 1489), 'tensorflow.reshape', 'tf.reshape', (['index_label', '[-1, 1]'], {}), '(index_label, [-1, 1])\n', (1467, 1489), True, 'import tensorflow as tf\n'), ((1508, 1540), 'tensorflow.cast', 'tf.cast', (['index_label', 'tf.float32'], {}), '(index_label, tf.float32)\n', (1515, 1540), True, 'import tensorflow as tf\n'), ((1619, 1652), 'tensorflow.data.TFRecordDataset', 'tf.data.TFRecordDataset', (['filelist'], {}), '(filelist)\n', (1642, 1652), True, 'import tensorflow as tf\n'), ((1923, 1964), 'os.path.join', 'os.path.join', (['rootDir', '"""data/scannet_3cm"""'], {}), "(rootDir, 'data/scannet_3cm')\n", (1935, 1964), False, 'import os\n'), ((1985, 2021), 'os.path.join', 'os.path.join', (['LOG_DIR', '"""block_index"""'], {}), "(LOG_DIR, 'block_index')\n", (1997, 2021), False, 'import os\n'), ((2857, 2873), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {}), '()\n', (2871, 2873), True, 'import tensorflow as tf\n'), ((732, 771), 'os.path.join', 'os.path.join', (['datapath', '"""log_block.txt"""'], {}), "(datapath, 'log_block.txt')\n", (744, 771), False, 'import os\n'), ((2033, 2062), 'os.path.exists', 'os.path.exists', (['blockindexDir'], {}), '(blockindexDir)\n', (2047, 2062), False, 'import os\n'), ((2072, 2095), 'os.mkdir', 'os.mkdir', (['blockindexDir'], {}), '(blockindexDir)\n', (2080, 2095), False, 'import os\n'), ((3006, 3031), 'tensorflow.Session', 'tf.Session', ([], {'config': 'config'}), '(config=config)\n', (3016, 3031), True, 'import tensorflow as tf\n'), ((1026, 1072), 'os.path.join', 'os.path.join', (['datapath', "('%s.tfrecord' % str[0])"], {}), "(datapath, '%s.tfrecord' % str[0])\n", (1038, 1072), False, 'import os\n'), ((1329, 1368), 'tensorflow.FixedLenFeature', 'tf.FixedLenFeature', (['[]'], {'dtype': 'tf.string'}), '([], dtype=tf.string)\n', (1347, 1368), True, 'import tensorflow as tf\n'), ((2144, 2182), 'os.path.join', 'os.path.join', (['dataDir', '"""val_files.txt"""'], {}), "(dataDir, 'val_files.txt')\n", (2156, 2182), False, 'import os\n'), ((2204, 2226), 'os.path.basename', 'os.path.basename', (['item'], {}), '(item)\n', (2220, 2226), False, 'import os\n'), ((3424, 3477), 'numpy.int32', 'np.int32', (['BLOCK2SCENE[batch_idx * BATCH_SIZE + b][-1]'], {}), '(BLOCK2SCENE[batch_idx * BATCH_SIZE + b][-1])\n', (3432, 3477), True, 'import numpy as np\n'), ((3715, 3754), 'os.path.join', 'os.path.join', (['blockindexDir', 'block_name'], {}), '(blockindexDir, block_name)\n', (3727, 3754), False, 'import os\n'), ((3788, 3827), 'os.path.join', 'os.path.join', (['blockindexDir', 'block_name'], {}), '(blockindexDir, block_name)\n', (3800, 3827), False, 'import os\n')]
import gym import numpy as np import matplotlib.pyplot as plt # for continuous (non-discretized) state space import sklearn from sklearn.linear_model import SGDRegressor import sklearn.pipeline from sklearn.kernel_approximation import RBFSampler discrete = True on_policy = True env = gym.make('MountainCar-v0') env.reset() # Feature Preprocessing: Normalize to zero mean and unit variance # We use a few samples from the observation space to do this observation_examples = np.array([env.observation_space.sample() for x in range(10000)]) scaler = sklearn.preprocessing.StandardScaler() scaler.fit(observation_examples) # Used to convert a state to a featurizes represenation. # We use RBF kernels with different variances to cover different parts of the space featurizer = sklearn.pipeline.FeatureUnion([ ("rbf1", RBFSampler(gamma=5.0, n_components=100)), ("rbf2", RBFSampler(gamma=2.0, n_components=100)), ("rbf3", RBFSampler(gamma=1.0, n_components=100)), ("rbf4", RBFSampler(gamma=0.5, n_components=100)) ]) featurizer.fit(scaler.transform(observation_examples)) def featurize_state(state): scaled = scaler.transform([state]) featurized = featurizer.transform(scaled) return featurized[0] max_state = env.observation_space.high min_state = env.observation_space.low if discrete: state_space_size = 2 state_buckets = [20] * state_space_size state_deltas = [(max_state[i] - min_state[i]) / state_buckets[i] for i in range(state_space_size)] episodes = 1000 alpha = 0.1 epsilon = 0.9 gamma = 0.95 if discrete: Q = np.random.uniform(low=-2, high=0, size=state_buckets + [env.action_space.n]) else: state = env.reset() Q = [SGDRegressor() for _ in range(env.action_space.n)] Q = [q.partial_fit([featurize_state(state)], [0]) for q in Q] def discretize_state(state): return [int(state[i] / state_deltas[i]) for i in range(state_space_size)] def eps_greedy_action(Q, state, epsilon): if np.random.random() < epsilon: return env.action_space.sample() if discrete: s1, s2 = discretize_state(state) return np.argmax(Q[s1, s2, :]) else: return np.argmax([q.predict([featurize_state(state)]) for q in Q]) rewards = [] for episode in range(episodes): if episode > 0 and episode % 100 == 0: print(episode) epsilon /= 2 state = env.reset() action = eps_greedy_action(Q, state, epsilon) done = False episode_reward = 0 while not done: # if episode % 50 == 0: # env.render() if not on_policy: action = eps_greedy_action(Q, state, epsilon) new_state, reward, done, _ = env.step(action) new_action = eps_greedy_action(Q, new_state, epsilon) if discrete: s1, s2 = discretize_state(state) new_s1, new_s2 = discretize_state(new_state) if on_policy: td_target = reward + gamma * Q[new_s1, new_s2, new_action] - Q[s1, s2, action] else: td_target = reward + gamma * np.max(Q[new_s1, new_s2, :]) - Q[s1, s2, action] Q[s1, s2, action] += alpha * td_target else: td_target = reward + gamma * Q[new_action].predict([featurize_state(new_state)]) Q[action] = Q[action].partial_fit([featurize_state(state)], td_target) state = new_state if on_policy: action = new_action episode_reward += reward # possible use # if state[0] >= env.goal_position: # s1, s2 = discretize_state(state) # Q[s1, s2, action] = 0 rewards.append(episode_reward) # final "evaluation" run done = False state = env.reset() while not done: env.render() action = eps_greedy_action(Q, state, 0) state, _, done, _ = env.step(action) plt.plot(range(len(rewards)), rewards) plt.show()
[ "sklearn.linear_model.SGDRegressor", "numpy.random.random", "sklearn.kernel_approximation.RBFSampler", "numpy.argmax", "numpy.max", "sklearn.preprocessing.StandardScaler", "numpy.random.uniform", "gym.make", "matplotlib.pyplot.show" ]
[((289, 315), 'gym.make', 'gym.make', (['"""MountainCar-v0"""'], {}), "('MountainCar-v0')\n", (297, 315), False, 'import gym\n'), ((553, 591), 'sklearn.preprocessing.StandardScaler', 'sklearn.preprocessing.StandardScaler', ([], {}), '()\n', (589, 591), False, 'import sklearn\n'), ((3874, 3884), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3882, 3884), True, 'import matplotlib.pyplot as plt\n'), ((1595, 1671), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(-2)', 'high': '(0)', 'size': '(state_buckets + [env.action_space.n])'}), '(low=-2, high=0, size=state_buckets + [env.action_space.n])\n', (1612, 1671), True, 'import numpy as np\n'), ((1712, 1726), 'sklearn.linear_model.SGDRegressor', 'SGDRegressor', ([], {}), '()\n', (1724, 1726), False, 'from sklearn.linear_model import SGDRegressor\n'), ((1987, 2005), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (2003, 2005), True, 'import numpy as np\n'), ((2132, 2155), 'numpy.argmax', 'np.argmax', (['Q[s1, s2, :]'], {}), '(Q[s1, s2, :])\n', (2141, 2155), True, 'import numpy as np\n'), ((829, 868), 'sklearn.kernel_approximation.RBFSampler', 'RBFSampler', ([], {'gamma': '(5.0)', 'n_components': '(100)'}), '(gamma=5.0, n_components=100)\n', (839, 868), False, 'from sklearn.kernel_approximation import RBFSampler\n'), ((888, 927), 'sklearn.kernel_approximation.RBFSampler', 'RBFSampler', ([], {'gamma': '(2.0)', 'n_components': '(100)'}), '(gamma=2.0, n_components=100)\n', (898, 927), False, 'from sklearn.kernel_approximation import RBFSampler\n'), ((947, 986), 'sklearn.kernel_approximation.RBFSampler', 'RBFSampler', ([], {'gamma': '(1.0)', 'n_components': '(100)'}), '(gamma=1.0, n_components=100)\n', (957, 986), False, 'from sklearn.kernel_approximation import RBFSampler\n'), ((1006, 1045), 'sklearn.kernel_approximation.RBFSampler', 'RBFSampler', ([], {'gamma': '(0.5)', 'n_components': '(100)'}), '(gamma=0.5, n_components=100)\n', (1016, 1045), False, 'from sklearn.kernel_approximation import RBFSampler\n'), ((3080, 3108), 'numpy.max', 'np.max', (['Q[new_s1, new_s2, :]'], {}), '(Q[new_s1, new_s2, :])\n', (3086, 3108), True, 'import numpy as np\n')]
import time import numpy as np from tensorflow.keras.wrappers.scikit_learn import KerasClassifier, KerasRegressor from sklearn.model_selection import StratifiedKFold, KFold, cross_val_score from sklearn.preprocessing import LabelEncoder from . import prep, io, train def kfold_cross_val(df, target_col, bucket_mod, data_path, verbose, n_jobs): # evaluate using 10-fold cross validation X, y = prep.split_Xy(df, target_col) # run estimator if target_col == "mem_bin": # Y = y.reshape(-1, 1) encoder = LabelEncoder() y = encoder.fit_transform(y) # y_enc = keras.utils.to_categorical(y) estimator = KerasClassifier(build_fn=train.memory_classifier, epochs=60, batch_size=32, verbose=verbose) kfold = StratifiedKFold(n_splits=10, shuffle=True) elif target_col == "memory": estimator = KerasRegressor(build_fn=train.memory_regressor, epochs=60, batch_size=32, verbose=verbose) kfold = KFold(n_splits=10, shuffle=True) elif target_col == "wallclock": estimator = KerasRegressor(build_fn=train.wallclock_regressor, epochs=150, batch_size=64, verbose=verbose) kfold = KFold(n_splits=10, shuffle=True) print("\nStarting KFOLD Cross-Validation...") start = time.time() results = cross_val_score(estimator, X, y, cv=kfold, n_jobs=n_jobs) end = time.time() duration = io.proc_time(start, end) if target_col == "mem_bin": score = np.mean(results) else: score = np.sqrt(np.abs(np.mean(results))) print(f"\nKFOLD scores: {results}\n") print(f"\nMean Score: {score}\n") print("\nProcess took ", duration) kfold_dict = {"kfold": {"results": list(results), "score": score, "time": duration}} keys = io.save_to_pickle(kfold_dict, target_col=target_col) io.s3_upload(keys, bucket_mod, f"{data_path}/results") def run_kfold(df, bucket_mod, data_path, models, verbose, n_jobs): for target in models: kfold_cross_val(df, target, bucket_mod, data_path, verbose, n_jobs)
[ "tensorflow.keras.wrappers.scikit_learn.KerasClassifier", "sklearn.preprocessing.LabelEncoder", "numpy.mean", "sklearn.model_selection.StratifiedKFold", "tensorflow.keras.wrappers.scikit_learn.KerasRegressor", "sklearn.model_selection.KFold", "time.time", "sklearn.model_selection.cross_val_score" ]
[((1261, 1272), 'time.time', 'time.time', ([], {}), '()\n', (1270, 1272), False, 'import time\n'), ((1287, 1344), 'sklearn.model_selection.cross_val_score', 'cross_val_score', (['estimator', 'X', 'y'], {'cv': 'kfold', 'n_jobs': 'n_jobs'}), '(estimator, X, y, cv=kfold, n_jobs=n_jobs)\n', (1302, 1344), False, 'from sklearn.model_selection import StratifiedKFold, KFold, cross_val_score\n'), ((1355, 1366), 'time.time', 'time.time', ([], {}), '()\n', (1364, 1366), False, 'import time\n'), ((534, 548), 'sklearn.preprocessing.LabelEncoder', 'LabelEncoder', ([], {}), '()\n', (546, 548), False, 'from sklearn.preprocessing import LabelEncoder\n'), ((654, 750), 'tensorflow.keras.wrappers.scikit_learn.KerasClassifier', 'KerasClassifier', ([], {'build_fn': 'train.memory_classifier', 'epochs': '(60)', 'batch_size': '(32)', 'verbose': 'verbose'}), '(build_fn=train.memory_classifier, epochs=60, batch_size=32,\n verbose=verbose)\n', (669, 750), False, 'from tensorflow.keras.wrappers.scikit_learn import KerasClassifier, KerasRegressor\n'), ((763, 805), 'sklearn.model_selection.StratifiedKFold', 'StratifiedKFold', ([], {'n_splits': '(10)', 'shuffle': '(True)'}), '(n_splits=10, shuffle=True)\n', (778, 805), False, 'from sklearn.model_selection import StratifiedKFold, KFold, cross_val_score\n'), ((1455, 1471), 'numpy.mean', 'np.mean', (['results'], {}), '(results)\n', (1462, 1471), True, 'import numpy as np\n'), ((859, 953), 'tensorflow.keras.wrappers.scikit_learn.KerasRegressor', 'KerasRegressor', ([], {'build_fn': 'train.memory_regressor', 'epochs': '(60)', 'batch_size': '(32)', 'verbose': 'verbose'}), '(build_fn=train.memory_regressor, epochs=60, batch_size=32,\n verbose=verbose)\n', (873, 953), False, 'from tensorflow.keras.wrappers.scikit_learn import KerasClassifier, KerasRegressor\n'), ((966, 998), 'sklearn.model_selection.KFold', 'KFold', ([], {'n_splits': '(10)', 'shuffle': '(True)'}), '(n_splits=10, shuffle=True)\n', (971, 998), False, 'from sklearn.model_selection import StratifiedKFold, KFold, cross_val_score\n'), ((1055, 1154), 'tensorflow.keras.wrappers.scikit_learn.KerasRegressor', 'KerasRegressor', ([], {'build_fn': 'train.wallclock_regressor', 'epochs': '(150)', 'batch_size': '(64)', 'verbose': 'verbose'}), '(build_fn=train.wallclock_regressor, epochs=150, batch_size=\n 64, verbose=verbose)\n', (1069, 1154), False, 'from tensorflow.keras.wrappers.scikit_learn import KerasClassifier, KerasRegressor\n'), ((1166, 1198), 'sklearn.model_selection.KFold', 'KFold', ([], {'n_splits': '(10)', 'shuffle': '(True)'}), '(n_splits=10, shuffle=True)\n', (1171, 1198), False, 'from sklearn.model_selection import StratifiedKFold, KFold, cross_val_score\n'), ((1513, 1529), 'numpy.mean', 'np.mean', (['results'], {}), '(results)\n', (1520, 1529), True, 'import numpy as np\n')]
from abc import ABC import torch import numpy as np from tqdm import tqdm from utils.cuda import get_device from utils.huggingface import get_tokens_from_sentences from sklearn.preprocessing import OrdinalEncoder class DeepShapWrapper(torch.nn.Module, ABC): def __init__(self, model): super(DeepShapWrapper, self).__init__() self.model = model self.device = get_device() def forward(self, data): self.model.to(self.device) data_len = len(data) batch_size = 32 iterations = data_len//batch_size + 1 total_prediction = torch.empty((data_len, 2)) for i in tqdm(range(iterations)): offset_0 = i * batch_size offset_1 = (i + 1) * batch_size batch_ids = data[offset_0:offset_1] real_size = len(batch_ids) if real_size == 0: continue mask_ids = torch.from_numpy(np.array((0,)*64*real_size).reshape(real_size, -1)).to(self.device) batch_ids = batch_ids.to(self.device) self.model.eval() outputs = self.model( inputs_embeds=batch_ids, attention_mask=mask_ids, token_type_ids=None, labels=None, return_dict=True, output_attentions=True ) total_prediction[offset_0:offset_1] = outputs.logits total_prediction = torch.softmax(total_prediction, dim=1) print(total_prediction) return total_prediction.to(self.device)
[ "torch.softmax", "numpy.array", "torch.empty", "utils.cuda.get_device" ]
[((390, 402), 'utils.cuda.get_device', 'get_device', ([], {}), '()\n', (400, 402), False, 'from utils.cuda import get_device\n'), ((596, 622), 'torch.empty', 'torch.empty', (['(data_len, 2)'], {}), '((data_len, 2))\n', (607, 622), False, 'import torch\n'), ((1443, 1481), 'torch.softmax', 'torch.softmax', (['total_prediction'], {'dim': '(1)'}), '(total_prediction, dim=1)\n', (1456, 1481), False, 'import torch\n'), ((933, 964), 'numpy.array', 'np.array', (['((0,) * 64 * real_size)'], {}), '((0,) * 64 * real_size)\n', (941, 964), True, 'import numpy as np\n')]
import serial import numpy as np import cv2 def send_commends(ser, motors, commands): for motor in motors: for direction_cmd in commands: command_string = bytes(2) command_string = bytearray(command_string) command_string[0] = motor # 2 motor 1, 4 motor 2, 8 motor 3 command_string[1] = direction_cmd # 2 forward, 4 backward, 8 release print(command_string) command_string = bytes(command_string) ser.write(command_string) # write a string def test_dc_motors(): motors = set() commands = [] # ser = serial.Serial('COM5') # open serial port ser = serial.Serial('/dev/ttyUSB1') # open serial port print(ser.name) # check which port was really used while True: img = np.zeros((200, 200), np.uint8) cv2.imshow('Main', img) key = cv2.waitKey(2) if key > 0: key = chr(key) if key in [ord('q')]: break if key in ['2', '4', '8']: motor = int(key) if motor in motors: motors.remove(motor) else: motors.add(motor) if key == 'w': commands = [2] if key == 's': commands = [8] if key == 'x': commands = [4] print(key, list(motors), commands) send_commends(ser, motors, commands) ser.close() test_dc_motors()
[ "cv2.waitKey", "numpy.zeros", "serial.Serial", "cv2.imshow" ]
[((666, 695), 'serial.Serial', 'serial.Serial', (['"""/dev/ttyUSB1"""'], {}), "('/dev/ttyUSB1')\n", (679, 695), False, 'import serial\n'), ((803, 833), 'numpy.zeros', 'np.zeros', (['(200, 200)', 'np.uint8'], {}), '((200, 200), np.uint8)\n', (811, 833), True, 'import numpy as np\n'), ((842, 865), 'cv2.imshow', 'cv2.imshow', (['"""Main"""', 'img'], {}), "('Main', img)\n", (852, 865), False, 'import cv2\n'), ((880, 894), 'cv2.waitKey', 'cv2.waitKey', (['(2)'], {}), '(2)\n', (891, 894), False, 'import cv2\n')]
""" ================== "SVG":-`graphics_` ================== Make sure we can embed SVG graphics. Use title that has punctuation marks. """ import numpy as np import matplotlib.pyplot as plt from local_module import N # N = 1000 t = np.arange(N) / float(N) win = np.hanning(N) plt.figure() plt.plot(t, win, color='r') plt.text(0, 1, 'svg', size=40, va='top')
[ "numpy.hanning", "matplotlib.pyplot.text", "matplotlib.pyplot.plot", "matplotlib.pyplot.figure", "numpy.arange" ]
[((268, 281), 'numpy.hanning', 'np.hanning', (['N'], {}), '(N)\n', (278, 281), True, 'import numpy as np\n'), ((282, 294), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (292, 294), True, 'import matplotlib.pyplot as plt\n'), ((295, 322), 'matplotlib.pyplot.plot', 'plt.plot', (['t', 'win'], {'color': '"""r"""'}), "(t, win, color='r')\n", (303, 322), True, 'import matplotlib.pyplot as plt\n'), ((323, 363), 'matplotlib.pyplot.text', 'plt.text', (['(0)', '(1)', '"""svg"""'], {'size': '(40)', 'va': '"""top"""'}), "(0, 1, 'svg', size=40, va='top')\n", (331, 363), True, 'import matplotlib.pyplot as plt\n'), ((238, 250), 'numpy.arange', 'np.arange', (['N'], {}), '(N)\n', (247, 250), True, 'import numpy as np\n')]
from queue import Empty, Queue import threading, time, uuid, os from flask import ( Flask, send_file, request, Response, render_template, ) import torch from data import colorize_image as CI from skimage import color as skiColor import numpy as np from io import BytesIO from PIL import Image, ImageColor colorModel = CI.ColorizeImageTorch(Xd=256) gpu_id = 0 if torch.cuda.is_available() else None colorModel.prep_net(gpu_id=gpu_id, path='./models/pytorch/caffemodel.pth') app = Flask(__name__) requestsQueue = Queue() BATCH_SIZE = 1 CHECK_INTERVAL = 0.1 def handle_requests_by_batch(): while True: requestsBatch = [] while not (len(requestsBatch) >= BATCH_SIZE): try: requestsBatch.append(requestsQueue.get(timeout=CHECK_INTERVAL)) except Empty: continue for request in requestsBatch: request['output'] = run(request['input'][0], request['input'][1], request['input'][2]) threading.Thread(target=handle_requests_by_batch).start() def put_point(inputAb, mask, loc, p, val): inputAb[:, loc[0] - p: loc[0] + p + 1, loc[1] - p : loc[1] + p + 1] = np.array(val)[:, np.newaxis, np.newaxis] mask[:, loc[0] - p : loc[0] + p + 1, loc[1] - p : loc[1] + p + 1] = 1 return (inputAb, mask) def run(file, labArr, position): try: filename = uuid.uuid1() tempFilePath = f'./input/{filename}.{file.content_type.split("/")[-1]}' image = Image.open(file) image = image.resize([256, 256]) image.save(tempFilePath) colorModel.load_image(tempFilePath) inputAb = np.zeros((2, 256, 256)) mask = np.zeros((1, 256, 256)) (inputAb, mask) = put_point(inputAb, mask, position, 3, [labArr[1], labArr[2]]) colorModel.net_forward(inputAb, mask) imgOutFullRes = colorModel.get_img_fullres() pilImage = Image.fromarray(np.uint8(imgOutFullRes)).convert('RGB') result = BytesIO() pilImage.save(result, format=file.content_type.split("/")[-1]) result.seek(0) os.remove(tempFilePath) return result except Exception as e: return "error" @app.route('/ideepcolor', methods=['POST']) def ideepcolor(): if requestsQueue.qsize() > BATCH_SIZE: return Response('Too Many Requests', status=429) try: file = request.files['image'] color = request.form['color'] positionX = request.form['positionX'] positionY = request.form['positionY'] except: return Response("Bad Request", status=400) rgbArray = ImageColor.getrgb(color) rgbNumpyArr = np.array((rgbArray[0], rgbArray[1], rgbArray[2])).astype('uint8') labArr = skiColor.rgb2lab(rgbNumpyArr[np.newaxis, np.newaxis, :]).flatten() position = [int(positionY), int(positionX)] req = { 'input': [file, labArr, position] } requestsQueue.put(req) while 'output' not in req: time.sleep(CHECK_INTERVAL) io = req['output'] if io == "error": return Response('Server Error', status=500) return send_file(io, mimetype=f'image/{file.content_type.split("/")[-1]}') @app.route('/test_imgs/<file_path>') def get_test_image(file_path: str): return send_file('./test_imgs/' + file_path) @app.route('/', methods=['GET']) def main(): return render_template('index.html') @app.route('/healthz', methods=['GET']) def healthz(): return 'ok' if __name__ == "__main__": app.run(host="0.0.0.0", port="5000")
[ "flask.render_template", "numpy.uint8", "PIL.Image.open", "skimage.color.rgb2lab", "data.colorize_image.ColorizeImageTorch", "flask.Flask", "io.BytesIO", "time.sleep", "uuid.uuid1", "numpy.array", "numpy.zeros", "torch.cuda.is_available", "flask.send_file", "PIL.ImageColor.getrgb", "flas...
[((324, 353), 'data.colorize_image.ColorizeImageTorch', 'CI.ColorizeImageTorch', ([], {'Xd': '(256)'}), '(Xd=256)\n', (345, 353), True, 'from data import colorize_image as CI\n'), ((488, 503), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (493, 503), False, 'from flask import Flask, send_file, request, Response, render_template\n'), ((521, 528), 'queue.Queue', 'Queue', ([], {}), '()\n', (526, 528), False, 'from queue import Empty, Queue\n'), ((369, 394), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (392, 394), False, 'import torch\n'), ((2612, 2636), 'PIL.ImageColor.getrgb', 'ImageColor.getrgb', (['color'], {}), '(color)\n', (2629, 2636), False, 'from PIL import Image, ImageColor\n'), ((3274, 3311), 'flask.send_file', 'send_file', (["('./test_imgs/' + file_path)"], {}), "('./test_imgs/' + file_path)\n", (3283, 3311), False, 'from flask import Flask, send_file, request, Response, render_template\n'), ((3369, 3398), 'flask.render_template', 'render_template', (['"""index.html"""'], {}), "('index.html')\n", (3384, 3398), False, 'from flask import Flask, send_file, request, Response, render_template\n'), ((990, 1039), 'threading.Thread', 'threading.Thread', ([], {'target': 'handle_requests_by_batch'}), '(target=handle_requests_by_batch)\n', (1006, 1039), False, 'import threading, time, uuid, os\n'), ((1166, 1179), 'numpy.array', 'np.array', (['val'], {}), '(val)\n', (1174, 1179), True, 'import numpy as np\n'), ((1370, 1382), 'uuid.uuid1', 'uuid.uuid1', ([], {}), '()\n', (1380, 1382), False, 'import threading, time, uuid, os\n'), ((1480, 1496), 'PIL.Image.open', 'Image.open', (['file'], {}), '(file)\n', (1490, 1496), False, 'from PIL import Image, ImageColor\n'), ((1635, 1658), 'numpy.zeros', 'np.zeros', (['(2, 256, 256)'], {}), '((2, 256, 256))\n', (1643, 1658), True, 'import numpy as np\n'), ((1674, 1697), 'numpy.zeros', 'np.zeros', (['(1, 256, 256)'], {}), '((1, 256, 256))\n', (1682, 1697), True, 'import numpy as np\n'), ((1978, 1987), 'io.BytesIO', 'BytesIO', ([], {}), '()\n', (1985, 1987), False, 'from io import BytesIO\n'), ((2090, 2113), 'os.remove', 'os.remove', (['tempFilePath'], {}), '(tempFilePath)\n', (2099, 2113), False, 'import threading, time, uuid, os\n'), ((2308, 2349), 'flask.Response', 'Response', (['"""Too Many Requests"""'], {'status': '(429)'}), "('Too Many Requests', status=429)\n", (2316, 2349), False, 'from flask import Flask, send_file, request, Response, render_template\n'), ((2978, 3004), 'time.sleep', 'time.sleep', (['CHECK_INTERVAL'], {}), '(CHECK_INTERVAL)\n', (2988, 3004), False, 'import threading, time, uuid, os\n'), ((3070, 3106), 'flask.Response', 'Response', (['"""Server Error"""'], {'status': '(500)'}), "('Server Error', status=500)\n", (3078, 3106), False, 'from flask import Flask, send_file, request, Response, render_template\n'), ((2555, 2590), 'flask.Response', 'Response', (['"""Bad Request"""'], {'status': '(400)'}), "('Bad Request', status=400)\n", (2563, 2590), False, 'from flask import Flask, send_file, request, Response, render_template\n'), ((2655, 2704), 'numpy.array', 'np.array', (['(rgbArray[0], rgbArray[1], rgbArray[2])'], {}), '((rgbArray[0], rgbArray[1], rgbArray[2]))\n', (2663, 2704), True, 'import numpy as np\n'), ((2734, 2790), 'skimage.color.rgb2lab', 'skiColor.rgb2lab', (['rgbNumpyArr[np.newaxis, np.newaxis, :]'], {}), '(rgbNumpyArr[np.newaxis, np.newaxis, :])\n', (2750, 2790), True, 'from skimage import color as skiColor\n'), ((1921, 1944), 'numpy.uint8', 'np.uint8', (['imgOutFullRes'], {}), '(imgOutFullRes)\n', (1929, 1944), True, 'import numpy as np\n')]
# Copyright (c) SenseTime. All Rights Reserved. from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import argparse import os import cv2 import torch import numpy as np from pysot.core.config import cfg from pysot.models.model_builder import ModelBuilder from pysot.tracker.tracker_builder import build_tracker from pysot.utils.bbox import get_axis_aligned_bbox from pysot.utils.model_load import load_pretrain from toolkit.datasets import DatasetFactory from toolkit.utils.region import vot_overlap, vot_float2str from pysot.models.backbone.alexnet import AlexNet root_dir ='/home/rainzsy/projects/Pytorch/Pysot/' datasets_root ='/home/rainzsy/datasets/vot/' parser = argparse.ArgumentParser(description='siamrpn tracking') parser.add_argument('--dataset', default='VOT2018', type=str, help='datasets') parser.add_argument('--config', default=root_dir+'experiments/siamrpn_alex_dwxcorr_16gpu/config_gru.yaml', type=str, help='config file') parser.add_argument('--snapshot', default=root_dir+'experiments/siamrpn_alex_dwxcorr_16gpu/gru_snapshot/checkpoint_e37_fitune.pth', type=str, help='snapshot of models to eval') parser.add_argument('--video', default='', type=str, help='eval one special video') parser.add_argument('--vis', default=True, action='store_true', help='whether visualzie result') args = parser.parse_args() torch.set_num_threads(1) # parser = argparse.ArgumentParser(description='siamrpn tracking') # parser.add_argument('--dataset', default='VOT2018', # type=str, help='datasets') # parser.add_argument('--config', default=root_dir+'experiments/siamrpn_r50_l234_dwxcorr/config.yaml', # type=str, help='config file') # parser.add_argument('--snapshot', default=root_dir+'experiments/siamrpn_r50_l234_dwxcorr/model.pth', # type=str, help='snapshot of models to eval') # parser.add_argument('--video', default='', # type=str, help='eval one special video') # parser.add_argument('--vis', default=True, # action='store_true', help='whether visualzie result') # args = parser.parse_args() # # torch.set_num_threads(1) def save_backbone(siamese): alexnet =AlexNet() alexnet_state_dict = alexnet.state_dict() siamese_state_dict =siamese.state_dict() for key in siamese_state_dict: print(key) for key in alexnet_state_dict: alexnet_state_dict[key]=siamese_state_dict['backbone.'+key] print(key) torch.save(alexnet_state_dict,"siamese_alexnet_backbone.pth") def save_siamese_rpn(): # load config rpn_path = root_dir + 'experiments/siamrpn_alex_dwxcorr_16gpu/pre_train/checkpoint_e45.pth' gru_rpn = root_dir + 'experiments/siamrpn_alex_dwxcorr_16gpu/config.yaml' cfg.merge_from_file(gru_rpn) # create model model_rpn = ModelBuilder() model_rpn = load_pretrain(model_rpn, rpn_path).cuda().eval() gru_path = root_dir + 'experiments/siamrpn_alex_dwxcorr_16gpu/gru_snapshot/gru_10.pth' gru_cfg=root_dir + 'experiments/siamrpn_alex_dwxcorr_16gpu/config_gru.yaml' cfg.merge_from_file(gru_cfg) # create model model_gru= ModelBuilder() model_gru = load_pretrain(model_gru, gru_path).cuda().eval() for key ,item in model_gru.named_parameters(): # print(key.find("grus")) print(key,item.shape) for key, item in model_rpn.named_parameters(): # print(key.find("grus")) print(key, item.shape) model_gru_dict = model_gru.state_dict() model_rpn_dict = model_rpn.state_dict() for key in model_gru_dict: if key.find("grus") !=-1: print("fix:",key) else: print("change:",key) model_gru_dict[key]=model_rpn_dict[key] # name_map={} # model_legacy_dict = model_legacy.state_dict() # model_alexnet_dict = model_alexnet.state_dict() # for para1,para2 in zip(model_legacy.named_parameters(),model_alexnet.named_parameters()): # # print(para1[0],para1[1].shape) # print(para1[0]) # print(para2[0]) # print(para1[1].shape) # print(para2[1].shape) # print("--"*40) # # print("['{}'--->'{}']".format(para1[0], para2[0]),para1[1].shape, para2[1].shape) # name_map[para1[0]]=para2[0] # print(name_map) # # # for key,val in name_map.items(): # model_alexnet_dict[val]=model_legacy_dict[key] torch.save(model_gru_dict, "siamese_gru10_rpn45.pth") def main(): # load config # save_siamese_rpn() cfg.merge_from_file(args.config) cur_dir = os.path.dirname(os.path.realpath(__file__)) # dataset_root = os.path.join(cur_dir, '../testing_dataset', args.dataset) dataset_root = datasets_root+ args.dataset # create model model = ModelBuilder() # load model model = load_pretrain(model, args.snapshot).cuda().eval() # save_backbone(model) # build tracker tracker = build_tracker(model) # create dataset dataset = DatasetFactory.create_dataset(name=args.dataset, dataset_root=dataset_root, load_img=False) model_name = args.snapshot.split('/')[-1].split('.')[0] total_lost = 0 #multi-pass tracking,跟踪丢失后重新初始化的测试方法 if args.dataset in ['VOT2016', 'VOT2018', 'VOT2019']: # restart tracking for v_idx, video in enumerate(dataset): if args.video != '': # test one special video if video.name != args.video: continue frame_counter = 0 lost_number = 0 toc = 0 # pred_bboxes包含两种类型的数据,类型1:整型数据,有1,2,0,三个值,分别表示跟踪开始,跟踪结束(丢失),跟踪丢失之后,间隔帧的占位符 # 类型2:浮点类型的bbox,也就是跟踪结果 pred_bboxes = [] gru_seq_len=tracker.model.grus.seq_in_len video_len =len(video) for idx, (img, gt_bbox) in enumerate(video): if len(gt_bbox) == 4: #如果gt是【x,y,w,h】的方式,转化为8个坐标信息(x1,y1,x2,y2,x3,y3,x4,y4) gt_bbox = [gt_bbox[0], gt_bbox[1], gt_bbox[0], gt_bbox[1]+gt_bbox[3]-1, gt_bbox[0]+gt_bbox[2]-1, gt_bbox[1]+gt_bbox[3]-1, gt_bbox[0]+gt_bbox[2]-1, gt_bbox[1]] tic = cv2.getTickCount() #跟踪初始化 if idx == frame_counter:# 跟踪第一帧初始化 idxs = list(map(lambda x, y: x + y, [idx] * gru_seq_len, list(range(0, gru_seq_len)))) # 取出idx后面的gru_seq_len个序列的索引号 idxs = list(map(lambda x: min(x, video_len - 1), idxs)) # 避免索引号越界 tracker.template_idx=0 #模板初始化的第一帧 for k in idxs: init_img, init_gt_bbox = video[k] #连续gru_seq_len帧初始化 #init_img, init_gt_bbox =video[idxs[0]] #只用一帧作为初始化参数 cx, cy, w, h = get_axis_aligned_bbox(np.array(init_gt_bbox)) #将倾斜框4个点坐标,转化为bbox,x,y为中心点形式(cx,cy,w,h) init_gt_bbox = [cx-(w-1)/2, cy-(h-1)/2, w, h] #x,y,中心点形式,转化为左上角形式 tracker.init_gru(init_img, init_gt_bbox,k) if k==0: pred_bbox = init_gt_bbox pred_bboxes.append(1) #持续的后续跟踪 elif idx > frame_counter: outputs = tracker.track(img) #对于下面的帧 pred_bbox = outputs['bbox'] #只有输出概率很高的时候才更新模板 if outputs['best_score']>0.95: tracker.init_gru(img, pred_bbox, idx) if cfg.MASK.MASK: pred_bbox = outputs['polygon'] overlap = vot_overlap(pred_bbox, gt_bbox, (img.shape[1], img.shape[0])) #查看初始化后的第一帧检测iou和score之间的关系 # if tracker.template_idx==4: # print("{:3.2f}\t{:3.2f}".format(overlap,outputs['best_score'])) if overlap > 0: # not lost pred_bboxes.append(pred_bbox) else: # lost object pred_bboxes.append(2) frame_counter = idx + 5 # skip 5 frames lost_number += 1 else: pred_bboxes.append(0) toc += cv2.getTickCount() - tic if idx == 0: cv2.destroyAllWindows() #绘制输出框,gt和mask都按照多边形来绘制,跟踪的bbox按照矩形来绘制 if args.vis and idx > frame_counter: #绘制多边形的gt cv2.polylines(img, [np.array(gt_bbox, np.int).reshape((-1, 1, 2))], True, (0, 255, 0), 3) #绘制siamesemask输出的多边形 if cfg.MASK.MASK: cv2.polylines(img, [np.array(pred_bbox, np.int).reshape((-1, 1, 2))], True, (0, 255, 255), 3) #绘制输出矩形框 else: bbox = list(map(int, pred_bbox)) cv2.rectangle(img, (bbox[0], bbox[1]), (bbox[0]+bbox[2], bbox[1]+bbox[3]), (0, 255, 255), 3) #添加图像标注,帧号和丢失次数 cv2.putText(img, str(idx), (40, 40), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 255), 2) cv2.putText(img, str(lost_number), (40, 80), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2) cv2.imshow(video.name, img) cv2.waitKey(1) toc /= cv2.getTickFrequency() # save results video_path = os.path.join('results', args.dataset, model_name,'baseline', video.name) if not os.path.isdir(video_path): os.makedirs(video_path) #结果路径的构成: ./results/VOT2018/model/baseline/ants1/ants1_001.txt result_path = os.path.join(video_path, '{}_001.txt'.format(video.name)) #pred_bboxes包含两种类型的数据,类型1:整型数据,有1,2,0,三个值,分别表示跟踪开始,跟踪结束(丢失),跟踪丢失之后,间隔帧的占位符 # 类型2:浮点类型的bbox,也就是跟踪结果 with open(result_path, 'w') as f: for x in pred_bboxes: if isinstance(x, int): #整数代表开始,或者有丢失 f.write("{:d}\n".format(x)) else: #浮点数才是bbox f.write(','.join([vot_float2str("%.4f", i) for i in x])+'\n') print('({:3d}) Video: {:12s} Time: {:4.1f}s Speed: {:3.1f}fps Lost: {:d}'.format( v_idx+1, video.name, toc, idx / toc, lost_number)) total_lost += lost_number print("{:s} total lost: {:d}".format(model_name, total_lost)) #oetracking,跟踪丢失后不再重新初始化的测试方法 else: # OPE tracking for v_idx, video in enumerate(dataset): if args.video != '': # test one special video if video.name != args.video: continue toc = 0 pred_bboxes = [] scores = [] track_times = [] for idx, (img, gt_bbox) in enumerate(video): tic = cv2.getTickCount() if idx == 0: cx, cy, w, h = get_axis_aligned_bbox(np.array(gt_bbox)) gt_bbox_ = [cx-(w-1)/2, cy-(h-1)/2, w, h] tracker.init(img, gt_bbox_) pred_bbox = gt_bbox_ scores.append(None) if 'VOT2018-LT' == args.dataset: pred_bboxes.append([1]) else: pred_bboxes.append(pred_bbox) else: outputs = tracker.track(img) pred_bbox = outputs['bbox'] pred_bboxes.append(pred_bbox) scores.append(outputs['best_score']) toc += cv2.getTickCount() - tic track_times.append((cv2.getTickCount() - tic)/cv2.getTickFrequency()) if idx == 0: cv2.destroyAllWindows() if args.vis and idx > 0: gt_bbox = list(map(int, gt_bbox)) pred_bbox = list(map(int, pred_bbox)) cv2.rectangle(img, (gt_bbox[0], gt_bbox[1]), (gt_bbox[0]+gt_bbox[2], gt_bbox[1]+gt_bbox[3]), (0, 255, 0), 3) cv2.rectangle(img, (pred_bbox[0], pred_bbox[1]), (pred_bbox[0]+pred_bbox[2], pred_bbox[1]+pred_bbox[3]), (0, 255, 255), 3) cv2.putText(img, str(idx), (40, 40), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 255), 2) cv2.imshow(video.name, img) cv2.waitKey(1) toc /= cv2.getTickFrequency() # save results if 'VOT2018-LT' == args.dataset: video_path = os.path.join('results', args.dataset, model_name, 'longterm', video.name) if not os.path.isdir(video_path): os.makedirs(video_path) result_path = os.path.join(video_path, '{}_001.txt'.format(video.name)) with open(result_path, 'w') as f: for x in pred_bboxes: f.write(','.join([str(i) for i in x])+'\n') result_path = os.path.join(video_path, '{}_001_confidence.value'.format(video.name)) with open(result_path, 'w') as f: for x in scores: f.write('\n') if x is None else f.write("{:.6f}\n".format(x)) result_path = os.path.join(video_path, '{}_time.txt'.format(video.name)) with open(result_path, 'w') as f: for x in track_times: f.write("{:.6f}\n".format(x)) elif 'GOT-10k' == args.dataset: video_path = os.path.join('results', args.dataset, model_name, video.name) if not os.path.isdir(video_path): os.makedirs(video_path) result_path = os.path.join(video_path, '{}_001.txt'.format(video.name)) with open(result_path, 'w') as f: for x in pred_bboxes: f.write(','.join([str(i) for i in x])+'\n') result_path = os.path.join(video_path, '{}_time.txt'.format(video.name)) with open(result_path, 'w') as f: for x in track_times: f.write("{:.6f}\n".format(x)) else: model_path = os.path.join('results', args.dataset, model_name) if not os.path.isdir(model_path): os.makedirs(model_path) result_path = os.path.join(model_path, '{}.txt'.format(video.name)) with open(result_path, 'w') as f: for x in pred_bboxes: f.write(','.join([str(i) for i in x])+'\n') print('({:3d}) Video: {:12s} Time: {:5.1f}s Speed: {:3.1f}fps'.format( v_idx+1, video.name, toc, idx / toc)) if __name__ == '__main__': main()
[ "cv2.rectangle", "cv2.imshow", "numpy.array", "cv2.destroyAllWindows", "pysot.tracker.tracker_builder.build_tracker", "argparse.ArgumentParser", "torch.set_num_threads", "toolkit.utils.region.vot_overlap", "pysot.core.config.cfg.merge_from_file", "os.path.isdir", "pysot.models.model_builder.Mode...
[((775, 830), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""siamrpn tracking"""'}), "(description='siamrpn tracking')\n", (798, 830), False, 'import argparse\n'), ((1540, 1564), 'torch.set_num_threads', 'torch.set_num_threads', (['(1)'], {}), '(1)\n', (1561, 1564), False, 'import torch\n'), ((2400, 2409), 'pysot.models.backbone.alexnet.AlexNet', 'AlexNet', ([], {}), '()\n', (2407, 2409), False, 'from pysot.models.backbone.alexnet import AlexNet\n'), ((2683, 2745), 'torch.save', 'torch.save', (['alexnet_state_dict', '"""siamese_alexnet_backbone.pth"""'], {}), "(alexnet_state_dict, 'siamese_alexnet_backbone.pth')\n", (2693, 2745), False, 'import torch\n'), ((2970, 2998), 'pysot.core.config.cfg.merge_from_file', 'cfg.merge_from_file', (['gru_rpn'], {}), '(gru_rpn)\n', (2989, 2998), False, 'from pysot.core.config import cfg\n'), ((3034, 3048), 'pysot.models.model_builder.ModelBuilder', 'ModelBuilder', ([], {}), '()\n', (3046, 3048), False, 'from pysot.models.model_builder import ModelBuilder\n'), ((3291, 3319), 'pysot.core.config.cfg.merge_from_file', 'cfg.merge_from_file', (['gru_cfg'], {}), '(gru_cfg)\n', (3310, 3319), False, 'from pysot.core.config import cfg\n'), ((3354, 3368), 'pysot.models.model_builder.ModelBuilder', 'ModelBuilder', ([], {}), '()\n', (3366, 3368), False, 'from pysot.models.model_builder import ModelBuilder\n'), ((4635, 4688), 'torch.save', 'torch.save', (['model_gru_dict', '"""siamese_gru10_rpn45.pth"""'], {}), "(model_gru_dict, 'siamese_gru10_rpn45.pth')\n", (4645, 4688), False, 'import torch\n'), ((4753, 4785), 'pysot.core.config.cfg.merge_from_file', 'cfg.merge_from_file', (['args.config'], {}), '(args.config)\n', (4772, 4785), False, 'from pysot.core.config import cfg\n'), ((5005, 5019), 'pysot.models.model_builder.ModelBuilder', 'ModelBuilder', ([], {}), '()\n', (5017, 5019), False, 'from pysot.models.model_builder import ModelBuilder\n'), ((5168, 5188), 'pysot.tracker.tracker_builder.build_tracker', 'build_tracker', (['model'], {}), '(model)\n', (5181, 5188), False, 'from pysot.tracker.tracker_builder import build_tracker\n'), ((5225, 5320), 'toolkit.datasets.DatasetFactory.create_dataset', 'DatasetFactory.create_dataset', ([], {'name': 'args.dataset', 'dataset_root': 'dataset_root', 'load_img': '(False)'}), '(name=args.dataset, dataset_root=dataset_root,\n load_img=False)\n', (5254, 5320), False, 'from toolkit.datasets import DatasetFactory\n'), ((4819, 4845), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (4835, 4845), False, 'import os\n'), ((9882, 9904), 'cv2.getTickFrequency', 'cv2.getTickFrequency', ([], {}), '()\n', (9902, 9904), False, 'import cv2\n'), ((9957, 10030), 'os.path.join', 'os.path.join', (['"""results"""', 'args.dataset', 'model_name', '"""baseline"""', 'video.name'], {}), "('results', args.dataset, model_name, 'baseline', video.name)\n", (9969, 10030), False, 'import os\n'), ((13105, 13127), 'cv2.getTickFrequency', 'cv2.getTickFrequency', ([], {}), '()\n', (13125, 13127), False, 'import cv2\n'), ((6557, 6575), 'cv2.getTickCount', 'cv2.getTickCount', ([], {}), '()\n', (6573, 6575), False, 'import cv2\n'), ((10049, 10074), 'os.path.isdir', 'os.path.isdir', (['video_path'], {}), '(video_path)\n', (10062, 10074), False, 'import os\n'), ((10092, 10115), 'os.makedirs', 'os.makedirs', (['video_path'], {}), '(video_path)\n', (10103, 10115), False, 'import os\n'), ((11476, 11494), 'cv2.getTickCount', 'cv2.getTickCount', ([], {}), '()\n', (11492, 11494), False, 'import cv2\n'), ((13229, 13302), 'os.path.join', 'os.path.join', (['"""results"""', 'args.dataset', 'model_name', '"""longterm"""', 'video.name'], {}), "('results', args.dataset, model_name, 'longterm', video.name)\n", (13241, 13302), False, 'import os\n'), ((3065, 3099), 'pysot.utils.model_load.load_pretrain', 'load_pretrain', (['model_rpn', 'rpn_path'], {}), '(model_rpn, rpn_path)\n', (3078, 3099), False, 'from pysot.utils.model_load import load_pretrain\n'), ((3385, 3419), 'pysot.utils.model_load.load_pretrain', 'load_pretrain', (['model_gru', 'gru_path'], {}), '(model_gru, gru_path)\n', (3398, 3419), False, 'from pysot.utils.model_load import load_pretrain\n'), ((5050, 5085), 'pysot.utils.model_load.load_pretrain', 'load_pretrain', (['model', 'args.snapshot'], {}), '(model, args.snapshot)\n', (5063, 5085), False, 'from pysot.utils.model_load import load_pretrain\n'), ((8756, 8774), 'cv2.getTickCount', 'cv2.getTickCount', ([], {}), '()\n', (8772, 8774), False, 'import cv2\n'), ((8830, 8853), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (8851, 8853), False, 'import cv2\n'), ((9800, 9827), 'cv2.imshow', 'cv2.imshow', (['video.name', 'img'], {}), '(video.name, img)\n', (9810, 9827), False, 'import cv2\n'), ((9848, 9862), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (9859, 9862), False, 'import cv2\n'), ((12222, 12240), 'cv2.getTickCount', 'cv2.getTickCount', ([], {}), '()\n', (12238, 12240), False, 'import cv2\n'), ((12382, 12405), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (12403, 12405), False, 'import cv2\n'), ((12579, 12696), 'cv2.rectangle', 'cv2.rectangle', (['img', '(gt_bbox[0], gt_bbox[1])', '(gt_bbox[0] + gt_bbox[2], gt_bbox[1] + gt_bbox[3])', '(0, 255, 0)', '(3)'], {}), '(img, (gt_bbox[0], gt_bbox[1]), (gt_bbox[0] + gt_bbox[2], \n gt_bbox[1] + gt_bbox[3]), (0, 255, 0), 3)\n', (12592, 12696), False, 'import cv2\n'), ((12742, 12873), 'cv2.rectangle', 'cv2.rectangle', (['img', '(pred_bbox[0], pred_bbox[1])', '(pred_bbox[0] + pred_bbox[2], pred_bbox[1] + pred_bbox[3])', '(0, 255, 255)', '(3)'], {}), '(img, (pred_bbox[0], pred_bbox[1]), (pred_bbox[0] + pred_bbox[\n 2], pred_bbox[1] + pred_bbox[3]), (0, 255, 255), 3)\n', (12755, 12873), False, 'import cv2\n'), ((13023, 13050), 'cv2.imshow', 'cv2.imshow', (['video.name', 'img'], {}), '(video.name, img)\n', (13033, 13050), False, 'import cv2\n'), ((13071, 13085), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (13082, 13085), False, 'import cv2\n'), ((13350, 13375), 'os.path.isdir', 'os.path.isdir', (['video_path'], {}), '(video_path)\n', (13363, 13375), False, 'import os\n'), ((13397, 13420), 'os.makedirs', 'os.makedirs', (['video_path'], {}), '(video_path)\n', (13408, 13420), False, 'import os\n'), ((14323, 14384), 'os.path.join', 'os.path.join', (['"""results"""', 'args.dataset', 'model_name', 'video.name'], {}), "('results', args.dataset, model_name, video.name)\n", (14335, 14384), False, 'import os\n'), ((15033, 15082), 'os.path.join', 'os.path.join', (['"""results"""', 'args.dataset', 'model_name'], {}), "('results', args.dataset, model_name)\n", (15045, 15082), False, 'import os\n'), ((8074, 8135), 'toolkit.utils.region.vot_overlap', 'vot_overlap', (['pred_bbox', 'gt_bbox', '(img.shape[1], img.shape[0])'], {}), '(pred_bbox, gt_bbox, (img.shape[1], img.shape[0]))\n', (8085, 8135), False, 'from toolkit.utils.region import vot_overlap, vot_float2str\n'), ((9436, 9537), 'cv2.rectangle', 'cv2.rectangle', (['img', '(bbox[0], bbox[1])', '(bbox[0] + bbox[2], bbox[1] + bbox[3])', '(0, 255, 255)', '(3)'], {}), '(img, (bbox[0], bbox[1]), (bbox[0] + bbox[2], bbox[1] + bbox[3\n ]), (0, 255, 255), 3)\n', (9449, 9537), False, 'import cv2\n'), ((11582, 11599), 'numpy.array', 'np.array', (['gt_bbox'], {}), '(gt_bbox)\n', (11590, 11599), True, 'import numpy as np\n'), ((12309, 12331), 'cv2.getTickFrequency', 'cv2.getTickFrequency', ([], {}), '()\n', (12329, 12331), False, 'import cv2\n'), ((14408, 14433), 'os.path.isdir', 'os.path.isdir', (['video_path'], {}), '(video_path)\n', (14421, 14433), False, 'import os\n'), ((14455, 14478), 'os.makedirs', 'os.makedirs', (['video_path'], {}), '(video_path)\n', (14466, 14478), False, 'import os\n'), ((15106, 15131), 'os.path.isdir', 'os.path.isdir', (['model_path'], {}), '(model_path)\n', (15119, 15131), False, 'import os\n'), ((15153, 15176), 'os.makedirs', 'os.makedirs', (['model_path'], {}), '(model_path)\n', (15164, 15176), False, 'import os\n'), ((7242, 7264), 'numpy.array', 'np.array', (['init_gt_bbox'], {}), '(init_gt_bbox)\n', (7250, 7264), True, 'import numpy as np\n'), ((12283, 12301), 'cv2.getTickCount', 'cv2.getTickCount', ([], {}), '()\n', (12299, 12301), False, 'import cv2\n'), ((9033, 9058), 'numpy.array', 'np.array', (['gt_bbox', 'np.int'], {}), '(gt_bbox, np.int)\n', (9041, 9058), True, 'import numpy as np\n'), ((9226, 9253), 'numpy.array', 'np.array', (['pred_bbox', 'np.int'], {}), '(pred_bbox, np.int)\n', (9234, 9253), True, 'import numpy as np\n'), ((10714, 10738), 'toolkit.utils.region.vot_float2str', 'vot_float2str', (['"""%.4f"""', 'i'], {}), "('%.4f', i)\n", (10727, 10738), False, 'from toolkit.utils.region import vot_overlap, vot_float2str\n')]