code
stringlengths 31
1.05M
| apis
list | extract_api
stringlengths 97
1.91M
|
---|---|---|
import math
import numbers
import numpy as np
from skimage.filters import gaussian
from skimage import img_as_float
from scipy import ndimage
from skimage import exposure
import torch
from torch import nn
from torch.nn import functional as F
import kornia
from loguru import logger
def simple_invert(data):
"""Invert the input image
Parameters
----------
data : np.ndarray (D,H,W)
Input image
Returns
-------
np.ndarray (D,H,W)
Inverted image
"""
return 1.0 - data
def label(data):
return ndimage.label(data)
def rescale_denan(img):
img = img - np.min(img)
img = img / np.max(img)
img = np.nan_to_num(img)
return img
def gamma_adjust(data, gamma=1.0):
"""Gamma adjust filter using skimage implementation
Parameters
----------
data : np.ndarray (D,H,W)
Input image
gamma : float
Gamma
Returns
-------
np.ndarray
Gamma adjusted image
"""
return np.nan_to_num(exposure.adjust_gamma(data, gamma))
def threshold(img, thresh=0.5):
return (img > thresh) * 1.0
def invert_threshold(img, thresh=0.5):
return (img < thresh) * 1.0
|
[
"numpy.nan_to_num",
"skimage.exposure.adjust_gamma",
"numpy.min",
"scipy.ndimage.label",
"numpy.max"
] |
[((553, 572), 'scipy.ndimage.label', 'ndimage.label', (['data'], {}), '(data)\n', (566, 572), False, 'from scipy import ndimage\n'), ((665, 683), 'numpy.nan_to_num', 'np.nan_to_num', (['img'], {}), '(img)\n', (678, 683), True, 'import numpy as np\n'), ((615, 626), 'numpy.min', 'np.min', (['img'], {}), '(img)\n', (621, 626), True, 'import numpy as np\n'), ((643, 654), 'numpy.max', 'np.max', (['img'], {}), '(img)\n', (649, 654), True, 'import numpy as np\n'), ((1007, 1041), 'skimage.exposure.adjust_gamma', 'exposure.adjust_gamma', (['data', 'gamma'], {}), '(data, gamma)\n', (1028, 1041), False, 'from skimage import exposure\n')]
|
#!/usr/bin/env python
# Copyright (c) 2021, <NAME>
# See LICENSE file for details: <https://github.com/moble/spherical/blob/master/LICENSE>
import math
import cmath
import numpy as np
import quaternionic
import spherical as sf
import pytest
from .conftest import requires_sympy
slow = pytest.mark.slow
precision_Wigner_D_element = 4.e-14
def test_Wigner_D_negative_argument(Rs, ell_max, eps):
# For integer ell, D(R)=D(-R)
#
# This test passes (specifically, using these tolerances) for at least
# ell_max=100, but takes a few minutes at that level.
a = np.zeros(sf.WignerDsize(0, ell_max), dtype=complex)
b = np.zeros(sf.WignerDsize(0, ell_max), dtype=complex)
wigner = sf.Wigner(ell_max)
for R in Rs:
wigner.D(R, out=a)
wigner.D(-R, out=b)
# sf.wigner_D(R, 0, ell_max, out=a)
# sf.wigner_D(-R, 0, ell_max, out=b)
assert np.allclose(a, b, rtol=ell_max*eps, atol=2*ell_max*eps)
assert np.allclose(wigner.D(R), wigner.D(-R), rtol=ell_max*eps, atol=2*ell_max*eps)
@slow
def test_Wigner_D_representation_property(Rs, ell_max_slow, eps):
# Test the representation property for special and random angles
# For each l, 𝔇ˡₘₚ,ₘ(R1 * R2) = Σₘₚₚ 𝔇ˡₘₚ,ₘₚₚ(R1) * 𝔇ˡₘₚₚ,ₘ(R2)
import time
print("")
t1 = time.perf_counter()
D1 = np.zeros(sf.WignerDsize(0, ell_max_slow), dtype=complex)
D2 = np.zeros(sf.WignerDsize(0, ell_max_slow), dtype=complex)
D12 = np.zeros(sf.WignerDsize(0, ell_max_slow), dtype=complex)
wigner = sf.Wigner(ell_max_slow)
for i, R1 in enumerate(Rs):
print(f"\t{i+1} of {len(Rs)}: R1 = {R1}")
for j, R2 in enumerate(Rs):
# print(f"\t\t{j+1} of {len(Rs)}: R2 = {R2}")
R12 = R1 * R2
wigner.D(R1, out=D1)
wigner.D(R2, out=D2)
wigner.D(R12, out=D12)
for ell in range(ell_max_slow+1):
ϵ = (2*ell+1)**2 * eps
i1 = sf.WignerDindex(ell, -ell, -ell)
i2 = sf.WignerDindex(ell, ell, ell)
shape = (2*ell+1, 2*ell+1)
Dˡ1 = D1[i1:i2+1].reshape(shape)
Dˡ2 = D2[i1:i2+1].reshape(shape)
Dˡ12 = D12[i1:i2+1].reshape(shape)
assert np.allclose(Dˡ1 @ Dˡ2, Dˡ12, rtol=ϵ, atol=ϵ), ell
t2 = time.perf_counter()
print(f"\tFinished in {t2-t1:.4f} seconds.")
def test_Wigner_D_inverse_property(Rs, ell_max, eps):
# Test the inverse property for special and random angles
# For each l, 𝔇ˡₘₚ,ₘ(R⁻¹) should be the inverse matrix of 𝔇ˡₘₚ,ₘ(R)
D1 = np.zeros(sf.WignerDsize(0, ell_max), dtype=complex)
D2 = np.zeros(sf.WignerDsize(0, ell_max), dtype=complex)
wigner = sf.Wigner(ell_max)
for i, R in enumerate(Rs):
# print(f"\t{i+1} of {len(Rs)}: R = {R}")
wigner.D(R, out=D1)
wigner.D(R.inverse, out=D2)
for ell in range(ell_max+1):
ϵ = (2*ell+1)**2 * eps
i1 = sf.WignerDindex(ell, -ell, -ell)
i2 = sf.WignerDindex(ell, ell, ell)
shape = (2*ell+1, 2*ell+1)
Dˡ1 = D1[i1:i2+1].reshape(shape)
Dˡ2 = D2[i1:i2+1].reshape(shape)
assert np.allclose(Dˡ1 @ Dˡ2, np.identity(2*ell+1), rtol=ϵ, atol=ϵ), ell
# print(f"\t{i+1} of {len(Rs)}: R = {R}")
D1 = wigner.D(R)
D2 = wigner.D(R.inverse)
for ell in range(ell_max+1):
ϵ = (2*ell+1)**2 * eps
i1 = sf.WignerDindex(ell, -ell, -ell)
i2 = sf.WignerDindex(ell, ell, ell)
shape = (-1, 2*ell+1, 2*ell+1)
Dˡ1 = D1[..., i1:i2+1].reshape(shape)
Dˡ2 = D2[..., i1:i2+1].reshape(shape)
assert np.allclose(Dˡ1 @ Dˡ2, np.identity(2*ell+1), rtol=ϵ, atol=ϵ), ell
def test_Wigner_D_symmetries(Rs, ell_max, eps):
# We have two obvious symmetries to test. First,
#
# D_{mp,m}(R) = (-1)^{mp+m} \bar{D}_{-mp,-m}(R)
#
# Second, since D is a unitary matrix, its conjugate transpose is its
# inverse; because of the representation property, D(R) should equal the
# matrix inverse of D(R⁻¹). Thus,
#
# D_{mp,m}(R) = \bar{D}_{m,mp}(\bar{R})
ϵ = 5 * ell_max * eps
D1 = np.zeros(sf.WignerDsize(0, ell_max), dtype=complex)
D2 = np.zeros(sf.WignerDsize(0, ell_max), dtype=complex)
wigner = sf.Wigner(ell_max)
ell_mp_m = sf.WignerDrange(0, ell_max)
flipped_indices = np.array([
sf.WignerDindex(ell, -mp, -m)
for ell, mp, m in ell_mp_m
])
swapped_indices = np.array([
sf.WignerDindex(ell, m, mp)
for ell, mp, m in ell_mp_m
])
signs = (-1) ** np.abs(np.sum(ell_mp_m[:, 1:], axis=1))
for R in Rs:
wigner.D(R, out=D1)
wigner.D(R.inverse, out=D2)
# D_{mp,m}(R) = (-1)^{mp+m} \bar{D}_{-mp,-m}(R)
a = D1
b = signs * D1[flipped_indices].conjugate()
assert np.allclose(a, b, rtol=ϵ, atol=ϵ)
# D_{mp,m}(R) = \bar{D}_{m,mp}(\bar{R})
b = D2[swapped_indices].conjugate()
assert np.allclose(a, b, rtol=ϵ, atol=ϵ)
D1 = wigner.D(Rs)
D2 = wigner.D(Rs.inverse)
# D_{mp,m}(R) = (-1)^{mp+m} \bar{D}_{-mp,-m}(R)
a = D1
b = signs * D1[..., flipped_indices].conjugate()
assert np.allclose(a, b, rtol=ϵ, atol=ϵ)
# D_{mp,m}(R) = \bar{D}_{m,mp}(\bar{R})
b = D2[..., swapped_indices].conjugate()
assert np.allclose(a, b, rtol=ϵ, atol=ϵ)
def test_Wigner_D_roundoff(Rs, ell_max, eps):
# Testing rotations in special regions with simple expressions for 𝔇
ϵ = 5 * ell_max * eps
D = np.zeros(sf.WignerDsize(0, ell_max), dtype=complex)
wigner = sf.Wigner(ell_max)
# Test rotations with |Ra|<1e-15
wigner.D(quaternionic.x, out=D)
actual = D
expected = np.array([
((-1.) ** ell if mp == -m else 0.0)
for ell in range(ell_max + 1)
for mp in range(-ell, ell + 1)
for m in range(-ell, ell + 1)
])
assert np.allclose(actual, expected, rtol=ϵ, atol=ϵ)
wigner.D(quaternionic.y, out=D)
actual = D
expected = np.array([
((-1.) ** (ell + m) if mp == -m else 0.0)
for ell in range(ell_max + 1)
for mp in range(-ell, ell + 1)
for m in range(-ell, ell + 1)
])
assert np.allclose(actual, expected, rtol=ϵ, atol=ϵ)
for theta in np.linspace(0, 2 * np.pi):
wigner.D(np.cos(theta) * quaternionic.y + np.sin(theta) * quaternionic.x, out=D)
actual = D
expected = np.array([
((-1.) ** (ell + m) * (np.cos(theta) + 1j * np.sin(theta)) ** (2 * m) if mp == -m else 0.0)
for ell in range(ell_max + 1)
for mp in range(-ell, ell + 1)
for m in range(-ell, ell + 1)
])
assert np.allclose(actual, expected, rtol=ϵ, atol=ϵ)
# Test rotations with |Rb|<1e-15
wigner.D(quaternionic.one, out=D)
actual = D
expected = np.array([
(1.0 if mp == m else 0.0)
for ell in range(ell_max + 1)
for mp in range(-ell, ell + 1)
for m in range(-ell, ell + 1)
])
assert np.allclose(actual, expected, rtol=ϵ, atol=ϵ)
wigner.D(quaternionic.z, out=D)
actual = D
expected = np.array([
((-1.) ** m if mp == m else 0.0)
for ell in range(ell_max + 1)
for mp in range(-ell, ell + 1)
for m in range(-ell, ell + 1)
])
assert np.allclose(actual, expected, rtol=ϵ, atol=ϵ)
for theta in np.linspace(0, 2 * np.pi):
wigner.D(np.cos(theta) * quaternionic.one + np.sin(theta) * quaternionic.z, out=D)
actual = D
expected = np.array([
((np.cos(theta) + 1j * np.sin(theta)) ** (2 * m) if mp == m else 0.0)
for ell in range(ell_max + 1)
for mp in range(-ell, ell + 1)
for m in range(-ell, ell + 1)
])
assert np.allclose(actual, expected, rtol=ϵ, atol=ϵ)
@pytest.mark.xfail
def test_Wigner_D_underflow(Rs, ell_max, eps):
# NOTE: This is a delicate test, which depends on the result underflowing exactly when expected.
# In particular, it should underflow to 0.0 when |mp+m|>32, but should never underflow to 0.0
# when |mp+m|<32. So it's not the end of the world if this test fails, but it does mean that
# the underflow properties have changed, so it might be worth a look.
epsilon = 1.e-10
ϵ = 5 * ell_max * eps
D = np.zeros(sf.WignerDsize(0, ell_max), dtype=complex)
wigner = sf.Wigner(ell_max)
ell_mp_m = sf.WignerDrange(0, ell_max)
# Test |Ra|=1e-10
R = quaternionic.array(epsilon, 1, 0, 0).normalized
wigner.D(R, out=D)
# print(R.to_euler_angles.tolist())
# print(D.tolist())
non_underflowing_indices = np.abs(ell_mp_m[:, 1] + ell_mp_m[:, 2]) < 32
assert np.all(D[non_underflowing_indices] != 0j)
underflowing_indices = np.abs(ell_mp_m[:, 1] + ell_mp_m[:, 2]) > 32
assert np.all(D[underflowing_indices] == 0j)
# Test |Rb|=1e-10
R = quaternionic.array(1, epsilon, 0, 0).normalized
wigner.D(R, out=D)
non_underflowing_indices = np.abs(ell_mp_m[:, 1] - ell_mp_m[:, 2]) < 32
assert np.all(D[non_underflowing_indices] != 0j)
underflowing_indices = np.abs(ell_mp_m[:, 1] - ell_mp_m[:, 2]) > 32
assert np.all(D[underflowing_indices] == 0j)
def test_Wigner_D_non_overflow(ell_max):
D = np.zeros(sf.WignerDsize(0, ell_max), dtype=complex)
wigner = sf.Wigner(ell_max)
# Test |Ra|=1e-10
R = quaternionic.array(1.e-10, 1, 0, 0).normalized
assert np.all(np.isfinite(wigner.D(R, out=D)))
# Test |Rb|=1e-10
R = quaternionic.array(1, 1.e-10, 0, 0).normalized
assert np.all(np.isfinite(wigner.D(R, out=D)))
def Wigner_d_Wikipedia(beta, ell, mp, m):
# https://en.wikipedia.org/wiki/Wigner_D-matrix#Wigner_.28small.29_d-matrix
Prefactor = math.sqrt(
math.factorial(ell + mp)
* math.factorial(ell - mp)
* math.factorial(ell + m)
* math.factorial(ell - m)
)
s_min = int(round(max(0, round(m - mp))))
s_max = int(round(min(round(ell + m), round(ell - mp))))
assert isinstance(s_max, int), type(s_max)
assert isinstance(s_min, int), type(s_min)
return Prefactor * sum([
(
(-1.) ** (mp - m + s)
* math.cos(beta / 2.) ** (2 * ell + m - mp - 2 * s)
* math.sin(beta / 2.) ** (mp - m + 2 * s)
/ float(
math.factorial(ell + m - s)
* math.factorial(s)
* math.factorial(mp - m + s)
* math.factorial(ell - mp - s)
)
)
for s in range(s_min, s_max + 1)
])
def Wigner_D_Wikipedia(alpha, beta, gamma, ell, mp, m):
# https://en.wikipedia.org/wiki/Wigner_D-matrix#Definition_of_the_Wigner_D-matrix
return cmath.exp(-1j * mp * alpha) * Wigner_d_Wikipedia(beta, ell, mp, m) * cmath.exp(-1j * m * gamma)
@slow
def test_Wigner_D_vs_Wikipedia(special_angles, ell_max_slow, eps):
ell_max = ell_max_slow
ϵ = 5 * ell_max**6 * eps
D = np.zeros(sf.WignerDsize(0, ell_max), dtype=complex)
wigner = sf.Wigner(ell_max)
ell_mp_m = sf.WignerDrange(0, ell_max)
print("")
for alpha in special_angles:
print("\talpha={0}".format(alpha)) # Need to show some progress for CI
for beta in special_angles[len(special_angles)//2:]: # Skip beta < 0
print("\t\tbeta={0}".format(beta))
for gamma in special_angles:
a = np.conjugate(np.array([Wigner_D_Wikipedia(alpha, beta, gamma, ell, mp, m) for ell,mp,m in ell_mp_m]))
b = wigner.D(quaternionic.array.from_euler_angles(alpha, beta, gamma), out=D)
assert np.allclose(a, b, rtol=ϵ, atol=ϵ)
@slow
@requires_sympy
def test_Wigner_D_vs_sympy(special_angles, ell_max_slow, eps):
from sympy import S, N
from sympy.physics.quantum.spin import WignerD as Wigner_D_sympy
# Note that this does not fully respect ell_max_slow because
# this test is extraordinarily slow
ell_max = min(4, ell_max_slow)
ϵ = 2 * ell_max * eps
wigner = sf.Wigner(ell_max)
max_error = 0.0
j = 0
k = 0
print()
a = special_angles[::4]
b = special_angles[len(special_angles)//2::4]
c = special_angles[::2]
for α in a:
for β in b:
for γ in c:
R = quaternionic.array.from_euler_angles(α, β, γ)
𝔇 = wigner.D(R)
k += 1
print(f"\tAngle iteration {k} of {a.size*b.size*c.size}")
for ell in range(wigner.ell_max+1):
for mp in range(-ell, ell+1):
for m in range(-ell, ell+1):
sympyD = N(Wigner_D_sympy(ell, mp, m, α, β, γ).doit(), n=24).conjugate()
sphericalD = 𝔇[wigner.Dindex(ell, mp, m)]
error = float(abs(sympyD-sphericalD))
assert error < ϵ, (
f"Testing Wigner d recursion: ell={ell}, m'={mp}, m={m}, "
f"sympy:{sympyD}, spherical:{sphericalD}, error={error}"
)
max_error = max(error, max_error)
print(f"\tmax_error={max_error} after checking {(len(special_angles)**3)*wigner.Dsize} values")
|
[
"numpy.abs",
"numpy.sum",
"numpy.allclose",
"spherical.WignerDsize",
"numpy.sin",
"numpy.identity",
"math.cos",
"numpy.linspace",
"spherical.WignerDrange",
"time.perf_counter",
"math.sin",
"numpy.cos",
"cmath.exp",
"numpy.all",
"spherical.WignerDindex",
"spherical.Wigner",
"quaternionic.array.from_euler_angles",
"quaternionic.array",
"math.factorial",
"sympy.physics.quantum.spin.WignerD"
] |
[((706, 724), 'spherical.Wigner', 'sf.Wigner', (['ell_max'], {}), '(ell_max)\n', (715, 724), True, 'import spherical as sf\n'), ((1295, 1314), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (1312, 1314), False, 'import time\n'), ((1527, 1550), 'spherical.Wigner', 'sf.Wigner', (['ell_max_slow'], {}), '(ell_max_slow)\n', (1536, 1550), True, 'import spherical as sf\n'), ((2319, 2338), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (2336, 2338), False, 'import time\n'), ((2713, 2731), 'spherical.Wigner', 'sf.Wigner', (['ell_max'], {}), '(ell_max)\n', (2722, 2731), True, 'import spherical as sf\n'), ((4301, 4319), 'spherical.Wigner', 'sf.Wigner', (['ell_max'], {}), '(ell_max)\n', (4310, 4319), True, 'import spherical as sf\n'), ((4335, 4362), 'spherical.WignerDrange', 'sf.WignerDrange', (['(0)', 'ell_max'], {}), '(0, ell_max)\n', (4350, 4362), True, 'import spherical as sf\n'), ((5222, 5255), 'numpy.allclose', 'np.allclose', (['a', 'b'], {'rtol': 'ε', 'atol': 'ε'}), '(a, b, rtol=ε, atol=ε)\n', (5233, 5255), True, 'import numpy as np\n'), ((5356, 5389), 'numpy.allclose', 'np.allclose', (['a', 'b'], {'rtol': 'ε', 'atol': 'ε'}), '(a, b, rtol=ε, atol=ε)\n', (5367, 5389), True, 'import numpy as np\n'), ((5611, 5629), 'spherical.Wigner', 'sf.Wigner', (['ell_max'], {}), '(ell_max)\n', (5620, 5629), True, 'import spherical as sf\n'), ((5923, 5968), 'numpy.allclose', 'np.allclose', (['actual', 'expected'], {'rtol': 'ε', 'atol': 'ε'}), '(actual, expected, rtol=ε, atol=ε)\n', (5934, 5968), True, 'import numpy as np\n'), ((6230, 6275), 'numpy.allclose', 'np.allclose', (['actual', 'expected'], {'rtol': 'ε', 'atol': 'ε'}), '(actual, expected, rtol=ε, atol=ε)\n', (6241, 6275), True, 'import numpy as np\n'), ((6294, 6319), 'numpy.linspace', 'np.linspace', (['(0)', '(2 * np.pi)'], {}), '(0, 2 * np.pi)\n', (6305, 6319), True, 'import numpy as np\n'), ((7046, 7091), 'numpy.allclose', 'np.allclose', (['actual', 'expected'], {'rtol': 'ε', 'atol': 'ε'}), '(actual, expected, rtol=ε, atol=ε)\n', (7057, 7091), True, 'import numpy as np\n'), ((7344, 7389), 'numpy.allclose', 'np.allclose', (['actual', 'expected'], {'rtol': 'ε', 'atol': 'ε'}), '(actual, expected, rtol=ε, atol=ε)\n', (7355, 7389), True, 'import numpy as np\n'), ((7408, 7433), 'numpy.linspace', 'np.linspace', (['(0)', '(2 * np.pi)'], {}), '(0, 2 * np.pi)\n', (7419, 7433), True, 'import numpy as np\n'), ((8416, 8434), 'spherical.Wigner', 'sf.Wigner', (['ell_max'], {}), '(ell_max)\n', (8425, 8434), True, 'import spherical as sf\n'), ((8450, 8477), 'spherical.WignerDrange', 'sf.WignerDrange', (['(0)', 'ell_max'], {}), '(0, ell_max)\n', (8465, 8477), True, 'import spherical as sf\n'), ((8731, 8774), 'numpy.all', 'np.all', (['(D[non_underflowing_indices] != 0.0j)'], {}), '(D[non_underflowing_indices] != 0.0j)\n', (8737, 8774), True, 'import numpy as np\n'), ((8856, 8895), 'numpy.all', 'np.all', (['(D[underflowing_indices] == 0.0j)'], {}), '(D[underflowing_indices] == 0.0j)\n', (8862, 8895), True, 'import numpy as np\n'), ((9083, 9126), 'numpy.all', 'np.all', (['(D[non_underflowing_indices] != 0.0j)'], {}), '(D[non_underflowing_indices] != 0.0j)\n', (9089, 9126), True, 'import numpy as np\n'), ((9208, 9247), 'numpy.all', 'np.all', (['(D[underflowing_indices] == 0.0j)'], {}), '(D[underflowing_indices] == 0.0j)\n', (9214, 9247), True, 'import numpy as np\n'), ((9362, 9380), 'spherical.Wigner', 'sf.Wigner', (['ell_max'], {}), '(ell_max)\n', (9371, 9380), True, 'import spherical as sf\n'), ((11045, 11063), 'spherical.Wigner', 'sf.Wigner', (['ell_max'], {}), '(ell_max)\n', (11054, 11063), True, 'import spherical as sf\n'), ((11079, 11106), 'spherical.WignerDrange', 'sf.WignerDrange', (['(0)', 'ell_max'], {}), '(0, ell_max)\n', (11094, 11106), True, 'import spherical as sf\n'), ((12038, 12056), 'spherical.Wigner', 'sf.Wigner', (['ell_max'], {}), '(ell_max)\n', (12047, 12056), True, 'import spherical as sf\n'), ((590, 616), 'spherical.WignerDsize', 'sf.WignerDsize', (['(0)', 'ell_max'], {}), '(0, ell_max)\n', (604, 616), True, 'import spherical as sf\n'), ((650, 676), 'spherical.WignerDsize', 'sf.WignerDsize', (['(0)', 'ell_max'], {}), '(0, ell_max)\n', (664, 676), True, 'import spherical as sf\n'), ((901, 962), 'numpy.allclose', 'np.allclose', (['a', 'b'], {'rtol': '(ell_max * eps)', 'atol': '(2 * ell_max * eps)'}), '(a, b, rtol=ell_max * eps, atol=2 * ell_max * eps)\n', (912, 962), True, 'import numpy as np\n'), ((1333, 1364), 'spherical.WignerDsize', 'sf.WignerDsize', (['(0)', 'ell_max_slow'], {}), '(0, ell_max_slow)\n', (1347, 1364), True, 'import spherical as sf\n'), ((1399, 1430), 'spherical.WignerDsize', 'sf.WignerDsize', (['(0)', 'ell_max_slow'], {}), '(0, ell_max_slow)\n', (1413, 1430), True, 'import spherical as sf\n'), ((1466, 1497), 'spherical.WignerDsize', 'sf.WignerDsize', (['(0)', 'ell_max_slow'], {}), '(0, ell_max_slow)\n', (1480, 1497), True, 'import spherical as sf\n'), ((2596, 2622), 'spherical.WignerDsize', 'sf.WignerDsize', (['(0)', 'ell_max'], {}), '(0, ell_max)\n', (2610, 2622), True, 'import spherical as sf\n'), ((2657, 2683), 'spherical.WignerDsize', 'sf.WignerDsize', (['(0)', 'ell_max'], {}), '(0, ell_max)\n', (2671, 2683), True, 'import spherical as sf\n'), ((3438, 3470), 'spherical.WignerDindex', 'sf.WignerDindex', (['ell', '(-ell)', '(-ell)'], {}), '(ell, -ell, -ell)\n', (3453, 3470), True, 'import spherical as sf\n'), ((3484, 3514), 'spherical.WignerDindex', 'sf.WignerDindex', (['ell', 'ell', 'ell'], {}), '(ell, ell, ell)\n', (3499, 3514), True, 'import spherical as sf\n'), ((4184, 4210), 'spherical.WignerDsize', 'sf.WignerDsize', (['(0)', 'ell_max'], {}), '(0, ell_max)\n', (4198, 4210), True, 'import spherical as sf\n'), ((4245, 4271), 'spherical.WignerDsize', 'sf.WignerDsize', (['(0)', 'ell_max'], {}), '(0, ell_max)\n', (4259, 4271), True, 'import spherical as sf\n'), ((4867, 4900), 'numpy.allclose', 'np.allclose', (['a', 'b'], {'rtol': 'ε', 'atol': 'ε'}), '(a, b, rtol=ε, atol=ε)\n', (4878, 4900), True, 'import numpy as np\n'), ((5008, 5041), 'numpy.allclose', 'np.allclose', (['a', 'b'], {'rtol': 'ε', 'atol': 'ε'}), '(a, b, rtol=ε, atol=ε)\n', (5019, 5041), True, 'import numpy as np\n'), ((5555, 5581), 'spherical.WignerDsize', 'sf.WignerDsize', (['(0)', 'ell_max'], {}), '(0, ell_max)\n', (5569, 5581), True, 'import spherical as sf\n'), ((6716, 6761), 'numpy.allclose', 'np.allclose', (['actual', 'expected'], {'rtol': 'ε', 'atol': 'ε'}), '(actual, expected, rtol=ε, atol=ε)\n', (6727, 6761), True, 'import numpy as np\n'), ((7810, 7855), 'numpy.allclose', 'np.allclose', (['actual', 'expected'], {'rtol': 'ε', 'atol': 'ε'}), '(actual, expected, rtol=ε, atol=ε)\n', (7821, 7855), True, 'import numpy as np\n'), ((8360, 8386), 'spherical.WignerDsize', 'sf.WignerDsize', (['(0)', 'ell_max'], {}), '(0, ell_max)\n', (8374, 8386), True, 'import spherical as sf\n'), ((8509, 8545), 'quaternionic.array', 'quaternionic.array', (['epsilon', '(1)', '(0)', '(0)'], {}), '(epsilon, 1, 0, 0)\n', (8527, 8545), False, 'import quaternionic\n'), ((8675, 8714), 'numpy.abs', 'np.abs', (['(ell_mp_m[:, 1] + ell_mp_m[:, 2])'], {}), '(ell_mp_m[:, 1] + ell_mp_m[:, 2])\n', (8681, 8714), True, 'import numpy as np\n'), ((8800, 8839), 'numpy.abs', 'np.abs', (['(ell_mp_m[:, 1] + ell_mp_m[:, 2])'], {}), '(ell_mp_m[:, 1] + ell_mp_m[:, 2])\n', (8806, 8839), True, 'import numpy as np\n'), ((8925, 8961), 'quaternionic.array', 'quaternionic.array', (['(1)', 'epsilon', '(0)', '(0)'], {}), '(1, epsilon, 0, 0)\n', (8943, 8961), False, 'import quaternionic\n'), ((9027, 9066), 'numpy.abs', 'np.abs', (['(ell_mp_m[:, 1] - ell_mp_m[:, 2])'], {}), '(ell_mp_m[:, 1] - ell_mp_m[:, 2])\n', (9033, 9066), True, 'import numpy as np\n'), ((9152, 9191), 'numpy.abs', 'np.abs', (['(ell_mp_m[:, 1] - ell_mp_m[:, 2])'], {}), '(ell_mp_m[:, 1] - ell_mp_m[:, 2])\n', (9158, 9191), True, 'import numpy as np\n'), ((9306, 9332), 'spherical.WignerDsize', 'sf.WignerDsize', (['(0)', 'ell_max'], {}), '(0, ell_max)\n', (9320, 9332), True, 'import spherical as sf\n'), ((9412, 9446), 'quaternionic.array', 'quaternionic.array', (['(1e-10)', '(1)', '(0)', '(0)'], {}), '(1e-10, 1, 0, 0)\n', (9430, 9446), False, 'import quaternionic\n'), ((9541, 9575), 'quaternionic.array', 'quaternionic.array', (['(1)', '(1e-10)', '(0)', '(0)'], {}), '(1, 1e-10, 0, 0)\n', (9559, 9575), False, 'import quaternionic\n'), ((10813, 10841), 'cmath.exp', 'cmath.exp', (['(-1.0j * m * gamma)'], {}), '(-1.0j * m * gamma)\n', (10822, 10841), False, 'import cmath\n'), ((10989, 11015), 'spherical.WignerDsize', 'sf.WignerDsize', (['(0)', 'ell_max'], {}), '(0, ell_max)\n', (11003, 11015), True, 'import spherical as sf\n'), ((2966, 2998), 'spherical.WignerDindex', 'sf.WignerDindex', (['ell', '(-ell)', '(-ell)'], {}), '(ell, -ell, -ell)\n', (2981, 2998), True, 'import spherical as sf\n'), ((3016, 3046), 'spherical.WignerDindex', 'sf.WignerDindex', (['ell', 'ell', 'ell'], {}), '(ell, ell, ell)\n', (3031, 3046), True, 'import spherical as sf\n'), ((3686, 3710), 'numpy.identity', 'np.identity', (['(2 * ell + 1)'], {}), '(2 * ell + 1)\n', (3697, 3710), True, 'import numpy as np\n'), ((4405, 4434), 'spherical.WignerDindex', 'sf.WignerDindex', (['ell', '(-mp)', '(-m)'], {}), '(ell, -mp, -m)\n', (4420, 4434), True, 'import spherical as sf\n'), ((4518, 4545), 'spherical.WignerDindex', 'sf.WignerDindex', (['ell', 'm', 'mp'], {}), '(ell, m, mp)\n', (4533, 4545), True, 'import spherical as sf\n'), ((4615, 4646), 'numpy.sum', 'np.sum', (['ell_mp_m[:, 1:]'], {'axis': '(1)'}), '(ell_mp_m[:, 1:], axis=1)\n', (4621, 4646), True, 'import numpy as np\n'), ((9902, 9925), 'math.factorial', 'math.factorial', (['(ell - m)'], {}), '(ell - m)\n', (9916, 9925), False, 'import math\n'), ((10744, 10773), 'cmath.exp', 'cmath.exp', (['(-1.0j * mp * alpha)'], {}), '(-1.0j * mp * alpha)\n', (10753, 10773), False, 'import cmath\n'), ((1960, 1992), 'spherical.WignerDindex', 'sf.WignerDindex', (['ell', '(-ell)', '(-ell)'], {}), '(ell, -ell, -ell)\n', (1975, 1992), True, 'import spherical as sf\n'), ((2014, 2044), 'spherical.WignerDindex', 'sf.WignerDindex', (['ell', 'ell', 'ell'], {}), '(ell, ell, ell)\n', (2029, 2044), True, 'import spherical as sf\n'), ((2260, 2304), 'numpy.allclose', 'np.allclose', (['(Dl1 @ Dl2)', 'Dl12'], {'rtol': 'ε', 'atol': 'ε'}), '(Dl1 @ Dl2, Dl12, rtol=ε, atol=ε)\n', (2271, 2304), True, 'import numpy as np\n'), ((3220, 3244), 'numpy.identity', 'np.identity', (['(2 * ell + 1)'], {}), '(2 * ell + 1)\n', (3231, 3244), True, 'import numpy as np\n'), ((9868, 9891), 'math.factorial', 'math.factorial', (['(ell + m)'], {}), '(ell + m)\n', (9882, 9891), False, 'import math\n'), ((11640, 11673), 'numpy.allclose', 'np.allclose', (['a', 'b'], {'rtol': 'ε', 'atol': 'ε'}), '(a, b, rtol=ε, atol=ε)\n', (11651, 11673), True, 'import numpy as np\n'), ((12296, 12341), 'quaternionic.array.from_euler_angles', 'quaternionic.array.from_euler_angles', (['α', 'β', 'γ'], {}), '(α, β, γ)\n', (12332, 12341), False, 'import quaternionic\n'), ((6338, 6351), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (6344, 6351), True, 'import numpy as np\n'), ((6371, 6384), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (6377, 6384), True, 'import numpy as np\n'), ((7452, 7465), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (7458, 7465), True, 'import numpy as np\n'), ((7487, 7500), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (7493, 7500), True, 'import numpy as np\n'), ((9798, 9822), 'math.factorial', 'math.factorial', (['(ell + mp)'], {}), '(ell + mp)\n', (9812, 9822), False, 'import math\n'), ((9833, 9857), 'math.factorial', 'math.factorial', (['(ell - mp)'], {}), '(ell - mp)\n', (9847, 9857), False, 'import math\n'), ((11552, 11608), 'quaternionic.array.from_euler_angles', 'quaternionic.array.from_euler_angles', (['alpha', 'beta', 'gamma'], {}), '(alpha, beta, gamma)\n', (11588, 11608), False, 'import quaternionic\n'), ((7589, 7602), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (7595, 7602), True, 'import numpy as np\n'), ((10284, 10304), 'math.sin', 'math.sin', (['(beta / 2.0)'], {}), '(beta / 2.0)\n', (10292, 10304), False, 'import math\n'), ((10488, 10516), 'math.factorial', 'math.factorial', (['(ell - mp - s)'], {}), '(ell - mp - s)\n', (10502, 10516), False, 'import math\n'), ((6494, 6507), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (6500, 6507), True, 'import numpy as np\n'), ((7610, 7623), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (7616, 7623), True, 'import numpy as np\n'), ((10220, 10240), 'math.cos', 'math.cos', (['(beta / 2.0)'], {}), '(beta / 2.0)\n', (10228, 10240), False, 'import math\n'), ((10443, 10469), 'math.factorial', 'math.factorial', (['(mp - m + s)'], {}), '(mp - m + s)\n', (10457, 10469), False, 'import math\n'), ((6515, 6528), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (6521, 6528), True, 'import numpy as np\n'), ((10361, 10388), 'math.factorial', 'math.factorial', (['(ell + m - s)'], {}), '(ell + m - s)\n', (10375, 10388), False, 'import math\n'), ((10407, 10424), 'math.factorial', 'math.factorial', (['s'], {}), '(s)\n', (10421, 10424), False, 'import math\n'), ((12666, 12701), 'sympy.physics.quantum.spin.WignerD', 'Wigner_D_sympy', (['ell', 'mp', 'm', 'α', 'β', 'γ'], {}), '(ell, mp, m, α, β, γ)\n', (12680, 12701), True, 'from sympy.physics.quantum.spin import WignerD as Wigner_D_sympy\n')]
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by <NAME> | 27/09/2018 | https://y-research.github.io
"""Description
"""
import numpy as np
import torch
from org.archive.l2r_global import L2R_GLOBAL
from org.archive.ranking.run.l2r import point_run, grid_run
""" GPU acceleration if expected """
L2R_GLOBAL.global_gpu, L2R_GLOBAL.global_device = False, 'cpu'
""" Reproducible experiments """
np.random.seed(seed=L2R_GLOBAL.l2r_seed)
torch.manual_seed(seed=L2R_GLOBAL.l2r_seed)
if __name__ == '__main__':
"""
>>> Supported ranking models <<<
Pointwise: RankMSE
Pairwise: RankNet | LambdaRank
Listwise: ListNet | ListMLE | RankCosine | ApproxNDCG | LambdaMART | WassRank
>>> Supported datasets <<<
MQ2007_super | MQ2008_super | MQ2007_semi | MQ2008_semi | MSLRWEB10K | MSLRWEB30K | Yahoo_L2R_Set_1 (TBA) | Yahoo_L2R_Set_1 (TBA)
"""
dir_output = '/Users/dryuhaitao/WorkBench/CodeBench/Bench_Output/NeuralLTR/Listwise/'
data = 'MQ2007_super'
dir_data = '/Users/dryuhaitao/WorkBench/Corpus/' + 'LETOR4.0/MQ2007/'
grid_search = False
if grid_search:
to_run_models = ['RankNet_PairWeighting']
# to_run_models = ['ListNet', 'ListMLE', 'ApproxNDCG']
for model in to_run_models:
grid_run(data=data, model=model, dir_data=dir_data, dir_output=dir_output)
else:
point_run(data=data, model='ApproxNDCG', dir_data=dir_data, dir_output=dir_output)
|
[
"torch.manual_seed",
"org.archive.ranking.run.l2r.point_run",
"numpy.random.seed",
"org.archive.ranking.run.l2r.grid_run"
] |
[((406, 446), 'numpy.random.seed', 'np.random.seed', ([], {'seed': 'L2R_GLOBAL.l2r_seed'}), '(seed=L2R_GLOBAL.l2r_seed)\n', (420, 446), True, 'import numpy as np\n'), ((447, 490), 'torch.manual_seed', 'torch.manual_seed', ([], {'seed': 'L2R_GLOBAL.l2r_seed'}), '(seed=L2R_GLOBAL.l2r_seed)\n', (464, 490), False, 'import torch\n'), ((1336, 1423), 'org.archive.ranking.run.l2r.point_run', 'point_run', ([], {'data': 'data', 'model': '"""ApproxNDCG"""', 'dir_data': 'dir_data', 'dir_output': 'dir_output'}), "(data=data, model='ApproxNDCG', dir_data=dir_data, dir_output=\n dir_output)\n", (1345, 1423), False, 'from org.archive.ranking.run.l2r import point_run, grid_run\n'), ((1252, 1326), 'org.archive.ranking.run.l2r.grid_run', 'grid_run', ([], {'data': 'data', 'model': 'model', 'dir_data': 'dir_data', 'dir_output': 'dir_output'}), '(data=data, model=model, dir_data=dir_data, dir_output=dir_output)\n', (1260, 1326), False, 'from org.archive.ranking.run.l2r import point_run, grid_run\n')]
|
"""
This module implements several Raman response functions. Numerical models of
the Raman response are important for the accurate theoretical description of
the propagation of optical pulses with short duration and high peak power
[MM1986]_ [G1986]_.
The following Raman response models are currently supported:
.. autosummary::
:nosignatures:
h_BW
h_LA
h_HC
.. [MM1986] <NAME>, <NAME>, Discovery of the soliton
self-frequency shift, Opt. Lett. 11 (1986) 659,
https://doi.org/10.1364/OL.11.000659.
.. [G1986] <NAME>, Theory of the soliton self-frequency shift, Opt. Lett. 11
(1986) 662, https://doi.org/10.1364/OL.11.000662.
.. [BW1989] <NAME>, <NAME>, Theoretical description of transient
stimulated Raman scattering in optical fibers. IEEE J. Quantum Electron.,
25 (1989) 1159, https://doi.org/10.1109/3.40655.
.. [LA2006] <NAME>, <NAME>, Raman response function for silica fibers,
Optics Letters, 31 (2006) 3086, https://doi.org/10.1364/JOSAB.6.001159.
.. [HC2002] <NAME> and <NAME>, Multiple-vibrational-mode mopdel
for fiber-optic Raman gain spectrum and response function, J. Opt.
Soc. Am. B, 19 (2002) 2886, https://doi.org/10.1364/JOSAB.19.002886.
.. module:: raman_response
.. codeauthor:: <NAME> <<EMAIL>>
"""
import sys
import numpy as np
from .config import FTFREQ, FT, IFT
def h_BW(t, tau1=12.2, tau2=32.0):
r"""Blow-Wood type Raman response function [BW1989]_.
Implements simple Raman response function for silica fibers based on a
single damped harmonic oscillator with Lorentzian linewidth [BW1989]_,
given by
.. math::
h_{\mathrm{BW}}(t) = \frac{\tau_1^2 + \tau_2^2}{\tau_1\tau_2^2}\, e^{-t/\tau_2}\, \sin(t/\tau_1)\,\theta(t),
where causality is assured by the unit step fuction :math:`\theta(t)`.
This Raman response model can be adapted to fit various types of nonlinear
fibers. For example, using the parameters :math:`\tau_1=12.2\,\mathrm{fs}`,
and :math:`\tau_2=32\,\mathrm{fs}`, toghether with a fractional Raman
contribution :math:`f_R=0.18` is adequate for modeling the Raman response
of of silica fibers.
Args:
t (:obj:`numpy.ndarray`): temporal grid.
tau1 (:obj:`float`): Raman response parameter (default: 12.2 fs).
tau2 (:obj:`float`): Raman response parameter (default: 32.0 fs).
Returns:
:obj:`numpy.ndarray`: Angular-frequency representation of the Raman response.
"""
w = FTFREQ(t.size, d=t[1] - t[0]) * 2 * np.pi
hR = np.where(
t > 0,
(tau1 ** 2 + tau2 ** 2)
/ (tau1 * tau2 ** 2)
* np.exp(-t / tau2)
* np.sin(t / tau1),
0,
)
hR /= np.sum(hR)
return np.exp(1j * w * np.min(t)) * FT(hR) * t.size
def h_LA(t):
r"""Lin-Agrawal type Raman response function [LA2006]_.
Implements an improved Raman response model, taking into account the
anisotropic nature of Raman scattering [LA2006]_, given by
.. math::
h_{\mathrm{LA}}(t) = (1-f_b)\,h_{\mathrm{BW}}(t) +f_b\,\frac{2\tau_b-t}{\tau_b^2} e^{-t/\tau_b}\,\theta(t),
with :math:`h_{\mathrm{BW}}(t)` given by :class:`h_BW`, and parameters
:math:`\tau_b=96\,\mathrm{fs}`, and :math:`f_b = 0.21`.
Args:
t (:obj:`numpy.ndarray`): temporal grid.
Returns:
:obj:`numpy.ndarray`: Angular-frequency representation of the Raman response.
"""
tau1 = 12.2 # (fs)
tau2 = 32.0 # (fs)
taub = 96.0 # (fs)
fb = 0.21
w = FTFREQ(t.size, d=t[1] - t[0]) * 2 * np.pi
ha = tau1 * (tau1 ** (-2) + tau2 ** (-2)) * np.exp(-t / tau2) * np.sin(t / tau1)
hb = (2.0 * taub - t) / taub / taub * np.exp(-t / taub)
hR = np.where(t > 0, (1.0 - fb) * ha + fb * hb, 0)
hR /= np.sum(hR)
return np.exp(1j * w * np.min(t)) * FT(hR) * t.size
def h_HC(t):
r"""Hollenbeck-Cantrell type Raman response function [HC2002_].
Implements intermediate broadening model for Raman response function of
silica fibers based on multiple vibrational frequency modes of the Si-O-Si
compound [HC2002]_. The time-domain representation of this Raman
response model is given by
.. math::
h_{\mathrm{HC}}(t) = \sum_{n=1}^{13} A_n\, e^{-\gamma_n t - \Gamma_n^2 t^2/4}\,\sin(\omega_n t)\,\theta(t),
with parameter sequences :math:`\{\omega_n\}_{n=1}^{13}`,
:math:`\{A_n\}_{n=1}^{13}`, :math:`\{\gamma_n\}_{n=1}^{13}`, and
:math:`\{\Gamma_n\}_{n=1}^{13}`, summarized in the table below.
.. csv-table::
:header: n, omega_n (rad/fs), A_n (-), gamma_n (1/ps), Gamma_n (1/ps)
:widths: 10, 30, 30, 30, 30
1 , 0.01060, 1.00, 1.64, 4.91
2 , 0.01884, 11.40, 3.66, 10.40
3 , 0.04356, 36.67, 5.49, 16.48
4 , 0.06828, 67.67, 5.10, 15.30
5 , 0.08721, 74.00, 4.25, 12.75
6 , 0.09362, 4.50, 0.77, 2.31
7 , 0.11518, 6.80, 1.30, 3.91
8 , 0.13029, 4.60, 4.87, 14.60
9 , 0.14950, 4.20, 1.87, 5.60
10, 0.15728, 4.50, 2.02, 6.06
11, 0.17518, 2.70, 4.71, 14.13
12, 0.20343, 3.10, 2.86, 8.57
13, 0.22886, 3.00, 5.02, 15.07
Args:
t (:obj:`numpy.ndarray`): temporal grid.
Returns:
:obj:`numpy.ndarray`: Angular-frequency representation of the Raman response.
"""
# PARAMTERS FOR INTERMEDIATE BROADENING MODEL - TAB. 1, REF. [1]
# param: (Comp. Pos, Peak Int., Gaussian FWHM, Lorentz FWHM)
# units: ( cm^-1, a.u., cm^-1, cm^-1)
pArr = [
(56.25, 1.00, 52.10, 17.37),
(100.00, 11.40, 110.42, 38.81),
(231.25, 36.67, 175.00, 58.33),
(362.50, 67.67, 162.50, 54.17),
(463.00, 74.00, 135.33, 45.11),
(497.00, 4.50, 24.50, 8.17),
(611.50, 6.80, 41.50, 13.83),
(691.67, 4.60, 155.00, 51.67),
(793.67, 4.20, 59.50, 19.83),
(835.00, 4.50, 64.30, 21.43),
(930.00, 2.70, 150.00, 50.00),
(1080.00, 3.10, 91.00, 30.33),
(1215.00, 3.00, 160.00, 53.33),
]
pos, A, FWHMGauss, FWHMLorentz = zip(*pArr)
c0 = 0.000029979 # cm/fs
wv = 2 * np.pi * c0 * np.asarray(pos)
Gamma = np.pi * c0 * np.asarray(FWHMGauss)
gamma = np.pi * c0 * np.asarray(FWHMLorentz)
hR = np.zeros(t.size)
for i in range(len(pArr)):
hR += (
A[i]
* np.exp(-gamma[i] * t)
* np.exp(-Gamma[i] ** 2 * t ** 2 / 4)
* np.sin(wv[i] * t)
)
hR[t < 0] = 0
hR /= np.sum(hR)
w = FTFREQ(t.size, d=t[1] - t[0]) * 2 * np.pi
return np.exp(1j * w * np.min(t)) * FT(hR) * t.size
# EOF: raman_response.py
|
[
"numpy.sum",
"numpy.asarray",
"numpy.zeros",
"numpy.min",
"numpy.where",
"numpy.sin",
"numpy.exp"
] |
[((2694, 2704), 'numpy.sum', 'np.sum', (['hR'], {}), '(hR)\n', (2700, 2704), True, 'import numpy as np\n'), ((3698, 3743), 'numpy.where', 'np.where', (['(t > 0)', '((1.0 - fb) * ha + fb * hb)', '(0)'], {}), '(t > 0, (1.0 - fb) * ha + fb * hb, 0)\n', (3706, 3743), True, 'import numpy as np\n'), ((3754, 3764), 'numpy.sum', 'np.sum', (['hR'], {}), '(hR)\n', (3760, 3764), True, 'import numpy as np\n'), ((6459, 6475), 'numpy.zeros', 'np.zeros', (['t.size'], {}), '(t.size)\n', (6467, 6475), True, 'import numpy as np\n'), ((6697, 6707), 'numpy.sum', 'np.sum', (['hR'], {}), '(hR)\n', (6703, 6707), True, 'import numpy as np\n'), ((3612, 3628), 'numpy.sin', 'np.sin', (['(t / tau1)'], {}), '(t / tau1)\n', (3618, 3628), True, 'import numpy as np\n'), ((3671, 3688), 'numpy.exp', 'np.exp', (['(-t / taub)'], {}), '(-t / taub)\n', (3677, 3688), True, 'import numpy as np\n'), ((6337, 6352), 'numpy.asarray', 'np.asarray', (['pos'], {}), '(pos)\n', (6347, 6352), True, 'import numpy as np\n'), ((6378, 6399), 'numpy.asarray', 'np.asarray', (['FWHMGauss'], {}), '(FWHMGauss)\n', (6388, 6399), True, 'import numpy as np\n'), ((6425, 6448), 'numpy.asarray', 'np.asarray', (['FWHMLorentz'], {}), '(FWHMLorentz)\n', (6435, 6448), True, 'import numpy as np\n'), ((2649, 2665), 'numpy.sin', 'np.sin', (['(t / tau1)'], {}), '(t / tau1)\n', (2655, 2665), True, 'import numpy as np\n'), ((3592, 3609), 'numpy.exp', 'np.exp', (['(-t / tau2)'], {}), '(-t / tau2)\n', (3598, 3609), True, 'import numpy as np\n'), ((6640, 6657), 'numpy.sin', 'np.sin', (['(wv[i] * t)'], {}), '(wv[i] * t)\n', (6646, 6657), True, 'import numpy as np\n'), ((2621, 2638), 'numpy.exp', 'np.exp', (['(-t / tau2)'], {}), '(-t / tau2)\n', (2627, 2638), True, 'import numpy as np\n'), ((6590, 6625), 'numpy.exp', 'np.exp', (['(-Gamma[i] ** 2 * t ** 2 / 4)'], {}), '(-Gamma[i] ** 2 * t ** 2 / 4)\n', (6596, 6625), True, 'import numpy as np\n'), ((2732, 2741), 'numpy.min', 'np.min', (['t'], {}), '(t)\n', (2738, 2741), True, 'import numpy as np\n'), ((3792, 3801), 'numpy.min', 'np.min', (['t'], {}), '(t)\n', (3798, 3801), True, 'import numpy as np\n'), ((6554, 6575), 'numpy.exp', 'np.exp', (['(-gamma[i] * t)'], {}), '(-gamma[i] * t)\n', (6560, 6575), True, 'import numpy as np\n'), ((6785, 6794), 'numpy.min', 'np.min', (['t'], {}), '(t)\n', (6791, 6794), True, 'import numpy as np\n')]
|
import numpy as np
import tensorflow as tf
from tensorflow import keras
import os
import dataprocess
import fluidmodels
import losses
#python version of jupyter notebook file, just for testing the packages.
# ### Manufacturing data for trainig
# In[2]:
np.random.seed(123)
pde_data_size = 2000
bc_data_size = 400
#domain range
X_1_domain = [-2, 2]
X_2_domain = [0, 1]
#time range
T_initial = 0
T_final = 1
T_domain = [T_initial, T_final]
#space data
space_dim = 2
# X_1_tr_pde = np.random.uniform(X_1_domain[0], X_1_domain[1], pde_data_size).reshape(pde_data_size,1)
# X_2_tr_pde = np.random.uniform(X_2_domain[0], X_2_domain[1], pde_data_size).reshape(pde_data_size,1)
# # X_tr_pde = np.random.uniform(-1,1,pde_data_size*space_dim).reshape(pde_data_size,space_dim)
#
# #temporal data
# X_tr_time = np.random.uniform(T_initial, T_final, pde_data_size).reshape(pde_data_size,1)
#
# X_tr_pde = np.concatenate([X_1_tr_pde, X_2_tr_pde, X_tr_time],axis=1)
# X_1_tr_pde.shape
#
#
# # In[3]:
#
#
# X_tr_pde.shape
#
#
# # ### Looking at the scatter plot of data
#
# # In[4]:
#
#
# # ### Defining the labels(true values) for the training data
#
# # In[5]:
#
#
# Y_tr_pde = np.zeros((X_tr_pde.shape[0],1))
# # Y_tr_pde = X_tr_pde[:,0:1]
#
#
# # In[6]:
#
#
# Y_tr_pde = np.concatenate([Y_tr_pde,np.zeros((Y_tr_pde.shape[0],1))],axis=1)
# Y_tr_pde.shape
#
#
# # ## BC data
#
# # In[7]:
#
#
# # bc_data_size = 100
#
# X_bc_left = np.random.uniform(X_2_domain[0],X_2_domain[1],
# bc_data_size).reshape(bc_data_size,1)
# X_bc_left = np.concatenate([X_1_domain[0]*np.ones((bc_data_size,1)),
# X_bc_left], axis=1)
# X_bc_left = np.concatenate([X_bc_left,
# np.random.uniform(T_initial, T_final, bc_data_size).reshape(bc_data_size,1)],
# axis=1)
#
# X_bc_bottom = np.random.uniform(X_1_domain[0],X_1_domain[1],
# bc_data_size).reshape(bc_data_size,1)
# X_bc_bottom = np.concatenate([X_bc_bottom, X_2_domain[0]*np.ones((bc_data_size,1))],
# axis=1)
# X_bc_bottom = np.concatenate([X_bc_bottom,
# np.random.uniform(T_initial, T_final, bc_data_size).reshape(bc_data_size,1)], axis=1)
#
# X_bc_right = np.random.uniform(X_2_domain[0],X_2_domain[1],
# bc_data_size).reshape(bc_data_size,1)
# X_bc_right = np.concatenate([X_1_domain[1]*np.ones((bc_data_size,1)),
# X_bc_right], axis=1)
# X_bc_right = np.concatenate([X_bc_right,
# np.random.uniform(T_initial, T_final, bc_data_size).reshape(bc_data_size,1)],
# axis=1)
#
# X_bc_top = np.random.uniform(X_1_domain[0],X_1_domain[1],
# bc_data_size).reshape(bc_data_size,1)
# X_bc_top = np.concatenate([X_bc_top, X_2_domain[1]*np.ones((bc_data_size,1))],
# axis=1)
# X_bc_top = np.concatenate([X_bc_top,
# np.random.uniform(T_initial, T_final, bc_data_size).reshape(bc_data_size,1)],
# axis=1)
#
# X_bc = np.concatenate([X_bc_left, X_bc_bottom, X_bc_right, X_bc_top],axis=0)
#
# #Add iniital condition below: add them to be X_ic and finallly concatenate bc and ic to get X_bc_ic
# X_ic = np.random.uniform(X_1_domain[0],X_1_domain[1],
# bc_data_size).reshape(bc_data_size,1)
# X_ic = np.concatenate([X_ic, np.random.uniform(X_2_domain[0],X_2_domain[1],
# bc_data_size).reshape(bc_data_size,1)],
# axis=1)
# X_ic = np.concatenate([X_ic,
# T_initial*np.ones((bc_data_size,1))],
# axis=1)
#
#
# # In[8]:
#
#
# X_bc_ic = np.concatenate([X_bc, X_ic],axis=0)
#
#
# # In[9]:
#
#
# X_bc_ic
#
#
# # In[10]:
#
#
# Y_bc_ic = np.sin(X_bc_ic[:,0:1] + X_bc_ic[:,1:2]) * X_bc_ic[:,2:3]
# # Y_bc = np.concatenate([Y_bc, np.ones((Y_bc.shape[0],1))], axis=1 )
#
#
# # ### Saving the data to a csv file
#
# # In[11]:
#
#
# combined_data = np.concatenate([X_bc_ic,Y_bc_ic],axis=1)
#
#
# # In[12]:
#
#
# dataprocess.save_to_csv(combined_data, "data_manufactured/t_sin_x_plus_y")
# In[13]:
X_data, Y_data = dataprocess.imp_from_csv("data_manufactured/t_sin_x_plus_y.csv",
True,1)
# In[14]:
data_processor = dataprocess.DataPreprocess(2, dom_bounds=[X_1_domain,X_2_domain,T_domain], time_dep=True)
# In[15]:
X_tr, Y_tr = data_processor.get_training_data(X_data,Y_data, X_col_points=pde_data_size)
# In[16]:
# X_tr = np.concatenate((X_tr_pde, X_bc), axis=0)
# Y_tr = np.concatenate((Y_tr_pde, Y_bc), axis=0)
# ## Training the model
# In[18]:
def rhs_function (args, time_dep=True):
if time_dep:
space_inputs = args[:-1]
time_inputs = args[-1]
else:
space_inputs = args
return tf.sin(space_inputs[0]+space_inputs[1]) + 2*time_inputs*tf.sin(space_inputs[0]+space_inputs[1])
# In[19]:
pinn_model = fluidmodels.ForwardModel(space_dim=2, time_dep=True, rhs_func = None)
# pinn_model = FluidModels.ForwardModel(space_dim=2, time_dep=True, rhs_func = None)
# In[20]:
# #Loss coming from the boundary terms
# def u_loss(y_true, y_pred):
# # print("\n\nreached here 1 \n\n\n")
# y_true_act = y_true[:,:-1]
# at_boundary = tf.cast(y_true[:,-1:,],bool)
# u_sq_error = (1/2)*tf.square(y_true_act-y_pred)
# # print("\n\nreached here 2 \n\n\n")
# # print("\nu_loss: ",tf.where(at_boundary, u_sq_error, 0.))
# return tf.where(at_boundary, u_sq_error, 0.)
# #Loss coming from the PDE constrain
# def pde_loss(y_true, y_pred):
# y_true_act = y_true[:,:-1]
# at_boundary = tf.cast(y_true[:,-1:,],bool)
# #need to change this to just tf.square(y_pred) after pde constrain is added to grad_layer
# pde_sq_error = (1/2)*tf.square(y_pred)
# # print("\npde_loss: ",tf.where(at_boundary,0.,pde_sq_error))
# return tf.where(at_boundary,0.,pde_sq_error)
# In[21]:
# loss_1 = Losses.u_loss
# loss_2 = Losses.pde_loss
# In[22]:
pinn_model.compile(loss=[losses.u_loss, losses.pde_loss], optimizer="adam")
# pinn_model.compile(loss=u_loss, optimizer=keras.optimizers.SGD(lr=1e-3))
# In[23]:
# pinn_model.fit(x=[X_tr[:,0:1], X_tr[:,1:2], X_tr[:,2:3]], y=[Y_tr, Y_tr], epochs=10)
history = pinn_model.fit(x=X_tr, y=[Y_tr, Y_tr], epochs=10)
# In[32]:
#
#
#
#
#
# # In[27]:
#
#
# # pinn_model.compile(loss=[u_loss,pde_loss], optimizer=keras.optimizers.SGD(lr=1e-4))
# # pinn_model.fit(x=[X_tr[:,0:1], X_tr[:,1:2]], y=[Y_tr, Y_tr], epochs=10)
#
#
# # In[28]:
#
#
# pinn_model.summary()
# ### Testing the model
# In[29]:
# X_test_st = np.random.uniform(-0.5,0.5,20*dim_d).reshape(20,dim_d)
# In[30]:
#
# #space test data
# test_dat_size = 100
# X_test_st = np.random.uniform(X_1_domain[0],X_1_domain[1],test_dat_size).reshape(test_dat_size,1)
# X_test_st = np.concatenate([X_test_st, np.random.uniform(X_2_domain[0],X_2_domain[1],test_dat_size).reshape(test_dat_size,1)], axis=1)
# #temporal test data
# X_test_time = np.random.uniform(T_initial,T_final,test_dat_size).reshape(test_dat_size,1)
#
# X_test_st = np.concatenate([X_test_st, X_test_time],axis=1)
#
#
# # In[31]:
#
#
# X_test_st = data_processor.prepare_input_data(X_test_st)
#
#
# # In[32]:
#
#
# # Y_test = pinn_model.predict(x=[X_test_st[:,0:1], X_test_st[:,1:2], X_test_st[:,2:3]])
# # pinn_model.predict(x=[X_tr[0:40,0:1], X_tr[0:40,1:2], X_tr[0:40,2:3]]) [0]
# Y_test = pinn_model.predict(x=X_test_st)
# len(Y_test)
#
#
# # In[33]:
#
#
# Y_test_true = np.sin(X_test_st[0] + X_test_st[1]) * X_test_st[2]
# Y_eval = np.concatenate([Y_test_true,np.ones((Y_test_true.shape[0],1))], axis=1)
#
#
# # In[34]:
#
#
# # pinn_model.evaluate(x=[X_test_st[:,0:1], X_test_st[:,1:2]], y= Y_eval)
#
#
# # In[35]:
#
#
# np.concatenate([Y_test_true, Y_test], axis=1)
#
#
# # In[36]:
#
#
# plt.scatter(Y_test_true,Y_test)
# plt.title("true vs predicted solution")
# plt.xlabel("True solution")
# plt.ylabel("Predicted solution")
# plt.show()
#
#
# # ## Saving and loading the trained FluidLearn model
#
# # ### Saving the model
#
# # In[37]:
#
#
# os.makedirs("./saved_models", exist_ok=True)
#
# #Saving the model using .h5 extension
# pinn_model.save("./saved_models/trained_model_1")
#
#
# # In[38]:
#
#
# # loaded_model = keras.models.load_model("./save_models/trained_model_1",
# # custom_objects={"space_dim": space_dim,
# # "time_dep": time_dep, "output_dim": output_dim,
# # "n_hid_lay": n_hid_lay, "n_hid_nrn": n_hid_nrn,
# # "act_func": act_func})
# loaded_model = keras.models.load_model("./saved_models/trained_model_1",
# custom_objects={"u_loss": Losses.u_loss,
# "pde_loss": Losses.pde_loss})
#
#
# # In[39]:
#
#
# new_predicted_test=loaded_model.predict(x=X_test_st)
#
#
# # In[40]:
#
#
# np.concatenate([Y_test,new_predicted_test], axis=1)
#
#
# # In[41]:
#
#
# loaded_model.fit(x=X_tr, y=[Y_tr, Y_tr], epochs=1)
|
[
"fluidmodels.ForwardModel",
"numpy.random.seed",
"tensorflow.sin",
"dataprocess.DataPreprocess",
"dataprocess.imp_from_csv"
] |
[((260, 279), 'numpy.random.seed', 'np.random.seed', (['(123)'], {}), '(123)\n', (274, 279), True, 'import numpy as np\n'), ((4353, 4426), 'dataprocess.imp_from_csv', 'dataprocess.imp_from_csv', (['"""data_manufactured/t_sin_x_plus_y.csv"""', '(True)', '(1)'], {}), "('data_manufactured/t_sin_x_plus_y.csv', True, 1)\n", (4377, 4426), False, 'import dataprocess\n'), ((4502, 4597), 'dataprocess.DataPreprocess', 'dataprocess.DataPreprocess', (['(2)'], {'dom_bounds': '[X_1_domain, X_2_domain, T_domain]', 'time_dep': '(True)'}), '(2, dom_bounds=[X_1_domain, X_2_domain, T_domain],\n time_dep=True)\n', (4528, 4597), False, 'import dataprocess\n'), ((5175, 5242), 'fluidmodels.ForwardModel', 'fluidmodels.ForwardModel', ([], {'space_dim': '(2)', 'time_dep': '(True)', 'rhs_func': 'None'}), '(space_dim=2, time_dep=True, rhs_func=None)\n', (5199, 5242), False, 'import fluidmodels\n'), ((5052, 5093), 'tensorflow.sin', 'tf.sin', (['(space_inputs[0] + space_inputs[1])'], {}), '(space_inputs[0] + space_inputs[1])\n', (5058, 5093), True, 'import tensorflow as tf\n'), ((5108, 5149), 'tensorflow.sin', 'tf.sin', (['(space_inputs[0] + space_inputs[1])'], {}), '(space_inputs[0] + space_inputs[1])\n', (5114, 5149), True, 'import tensorflow as tf\n')]
|
import pandas as pd
from itertools import combinations
import numpy as np
import datetime
import os
dataFrame = ""
columnsWithSameValue = []
fullEmptyColumns = []
def startAnalyze(csv_path):
global dataFrame, fullEmptyColumns
# print("Importing CSV File\n")
csv = pd.read_csv(csv_path, low_memory=False)
csv_no_head = pd.read_csv(csv_path, header=None, low_memory=False)
dataFrame = pd.DataFrame(csv)
modifiedDataFrame = pd.DataFrame(csv)
dataFrameNoHead = pd.DataFrame(csv_no_head)
rows = len(dataFrame.axes[0])
columns = len(dataFrame.axes[1])
emptyCells = dataFrame.isnull()
emptyCellsCount = emptyCells.sum().sum()
missingRate = str(round((emptyCellsCount / (rows * columns)) * 100, 2))
fullEmptyColumns = [col for col in dataFrame.columns if dataFrame[col].isnull().all()]
# print(fullEmptyColumns)
anyValueMissingColumn = dataFrame.columns[dataFrame.isnull().any()]
singleValueColumnList = dataFrame.apply(pd.Series.nunique)
singleValueColumn = singleValueColumnList[singleValueColumnList == 1]
# anyValueMissingRowsByColumnName = dataFrame[anyValueMissingColumn[0]]
columnList = pd.DataFrame(dataFrameNoHead.head(1))
duplicateHeaderNames = [(i, j) for i, j in combinations(columnList, 2) if columnList[i].equals(columnList[j])]
if len(duplicateHeaderNames) > 0:
duplicateHeaderNames = duplicateHeaderNames[0]
duplicateRows = dataFrame[dataFrame.duplicated()]
anyValueMissingRow = dataFrame[dataFrame.isnull().any(axis=1)]
anyValueMissingRow = pd.DataFrame(anyValueMissingRow)
anyValueMissingRow = len(anyValueMissingRow.axes[0])
for items in fullEmptyColumns:
# print(items)
modifiedDataFrame.drop(items, axis=1, inplace=True)
# print(modifiedDataFrame)
# print(dataFrame)
mainDF = list(modifiedDataFrame.head(0))
for colIt in range(len(modifiedDataFrame.axes[1])):
for allIt in range(colIt, len(modifiedDataFrame.axes[1])):
if (modifiedDataFrame.iloc[:, colIt]).equals(modifiedDataFrame.iloc[:, allIt]) and colIt != allIt:
if mainDF[colIt] not in columnsWithSameValue:
columnsWithSameValue.append(mainDF[colIt])
# print(mainDF[colIt] + " matches with " + mainDF[allIt])
# columnsHavingSameValue = dataFrame.loc[:, ~dataFrame.columns.duplicated()]
# columnsHavingSameValue = list(columnsHavingSameValue.head(0))
# print(columnsHavingSameValue)
# columnsHavingSameValue = [(i, j) for i, j in combinations(dataFrame, 2) if dataFrame[i].equals(dataFrame[j])]
# if len(columnsHavingSameValue) > 0:
# columnsHavingSameValue = columnsHavingSameValue[0]
print("Columns: " + str(columns) + "\nRows: " + str(rows) + "\nEmpty Cells: " + str(
emptyCellsCount) + "\nMissing Rate: " + str(missingRate) + "%" + "\nFull Empty Columns: " + str(
len(fullEmptyColumns)) + "\nDuplicated Header: " + str(
len(duplicateHeaderNames)) + "\nSingle value column: " + str(
len(singleValueColumn)) + "\nColumn with Missing Data: " + str(
len(anyValueMissingColumn)) + "\nDuplicate Rows: " + str(len(duplicateRows)) + "\nIncomplete Rows: " + str(
anyValueMissingRow) + "\nColumns with Same Value: " + str(len(columnsWithSameValue)))
cellMapping = np.zeros((rows, columns))
for i in range(len(emptyCells)):
for j in range(columns):
if not emptyCells.iloc[i, j]:
cellMapping[i][j] = 1
duplicateMapping = np.zeros(columns)
# print(duplicateMapping)
for j in range(columns):
for col in duplicateHeaderNames:
if columnList[col][0] == columnList[j].any():
duplicateMapping[j] = 1
break
# print(duplicateMapping)
duplicateHeaderArray = [""] * len(duplicateHeaderNames)
# print(duplicateHeaderArray)
for key, col in enumerate(duplicateHeaderNames):
# print('Duplicate header name : ', [col][0])
# print('Duplicate header name : ', mainDF[col])
# print('Duplicate header name : ', columnList[col][0])
# duplicateHeaderArray[key] = columnList[col][0]
duplicateHeaderArray[key] = mainDF[col]
# print(duplicateHeaderArray)
# df.drop_duplicates(subset=['A', 'C'], keep=False) keep first / last
singleValueColumnArray = [""] * len(pd.DataFrame(singleValueColumn).axes[0])
# print(singleValueColumnArray)
for key, col in enumerate(pd.DataFrame(singleValueColumn).axes[0]):
# print('Single value column name : ', col)
singleValueColumnArray[key] = col
# print(singleValueColumnArray)
anyValueMissingColumnArray = [""] * len(anyValueMissingColumn)
for key, col in enumerate(anyValueMissingColumn):
# print('Missing data : ' + col + " (" + str(round((dataFrame[col].isnull().sum()/len(dataFrame[col]))*100, 2)) + "%)")
anyValueMissingColumnArray[key] = col + "," + str(
round((dataFrame[col].isnull().sum() / len(dataFrame[col])) * 100, 2))
# print(anyValueMissingColumnArray)
columnsHavingSameValueArray = [""] * len(columnsWithSameValue)
for key, col in enumerate(columnsWithSameValue):
# print('Same value column name ' + str(key+1) + ' : ', col)
columnsHavingSameValueArray[key] = col
# print(columnsHavingSameValueArray)
missingMapping = np.zeros(columns)
# print(duplicateMapping)
for j in range(columns):
for col in anyValueMissingColumn:
if col == columnList[j].any():
missingMapping[j] = round((dataFrame[col].isnull().sum() / len(dataFrame[col])) * 100, 2)
break
# print(missingMapping)
# print(date_finder(csv_path))
# print(list(dataFrame.filter(regex='date_time')))
# print(list(dataFrame.filter(regex='date')))
# print(list(dataFrame.filter(regex='time')))
# print(list(dataFrame.filter(regex='Date')))
# print(list(dataFrame.filter(regex='Time')))
# print(list(dataFrame.filter(regex='DATE')))
# print(list(dataFrame.filter(regex='TIME')))
# print(list(dataFrame.filter(regex='DATE_TIME')))
# print(list(dataFrame.filter(regex='Date_Time')))
# dataFrame = dataFrame[dataFrame.columns.drop(list(dataFrame.filter(regex='date_time')))]
# dataFrame = dataFrame[dataFrame.columns.drop(list(dataFrame.filter(regex='date')))]
# dataFrame = dataFrame[dataFrame.columns.drop(list(dataFrame.filter(regex='time')))]
# dataFrame = dataFrame[dataFrame.columns.drop(list(dataFrame.filter(regex='Date')))]
# dataFrame = dataFrame[dataFrame.columns.drop(list(dataFrame.filter(regex='Time')))]
# dataFrame = dataFrame[dataFrame.columns.drop(list(dataFrame.filter(regex='DATE')))]
# dataFrame = dataFrame[dataFrame.columns.drop(list(dataFrame.filter(regex='TIME')))]
# dataFrame = dataFrame[dataFrame.columns.drop(list(dataFrame.filter(regex='DATE_TIME')))]
# dataFrame = dataFrame[dataFrame.columns.drop(list(dataFrame.filter(regex='Date_Time')))]
return "Data Received"
def startCleansing(actions):
global dataFrame, fullEmptyColumns
print(actions)
for items in fullEmptyColumns:
# print(items)
dataFrame.drop(items, axis=1, inplace=True)
allActions = actions.split("&")
for item in allActions:
if item[:4] == "SAME":
if item[-4:] != "KEEP":
print("Remove columns with same value")
splitItem = item.split('=')[1]
splitItem = splitItem[:-6]
# print(splitItem)
if splitItem in dataFrame.columns:
dataFrame.drop(splitItem, axis=1, inplace=True)
for item in allActions:
if item[:7] == "MISSING":
# print(item)
if item[-4:] != "KEEP":
print("Remove missing data column")
splitItem = item.split('=')[1]
splitItem = splitItem[:-6]
print(splitItem)
if splitItem in dataFrame.columns:
dataFrame.drop(splitItem, axis=1, inplace=True)
for item in allActions:
if item[:6] == "SINGLE":
if item[-4:] != "KEEP":
print("Remove single value column")
splitItem = item.split('=')[1]
splitItem = splitItem[:-6]
print(splitItem)
if splitItem in dataFrame.columns:
dataFrame.drop(splitItem, axis=1, inplace=True)
for item in allActions:
if item[:9] == "DUPLICATE":
if item[-4:] != "KEEP":
print("Remove duplicate column name")
splitItem = item.split('=')[1]
splitItem = splitItem[:-6]
print(splitItem)
if splitItem in dataFrame.columns:
dataFrame.drop(splitItem, axis=1, inplace=True)
for item in allActions:
if item[:2] == "IR":
if item[-4:] != "KEEP":
print("Remove incomplete rows")
dataFrame = dataFrame.dropna()
for item in allActions:
if item[:2] == "DR":
if item[-4:] != "KEEP":
print("Remove duplicate rows")
dataFrame = dataFrame.drop_duplicates(keep='first')
dataFrame = dataFrame[dataFrame.columns.drop(list(dataFrame.filter(regex='date_time')))]
dataFrame = dataFrame[dataFrame.columns.drop(list(dataFrame.filter(regex='date')))]
dataFrame = dataFrame[dataFrame.columns.drop(list(dataFrame.filter(regex='time')))]
dataFrame = dataFrame[dataFrame.columns.drop(list(dataFrame.filter(regex='Date')))]
dataFrame = dataFrame[dataFrame.columns.drop(list(dataFrame.filter(regex='Time')))]
dataFrame = dataFrame[dataFrame.columns.drop(list(dataFrame.filter(regex='DATE')))]
dataFrame = dataFrame[dataFrame.columns.drop(list(dataFrame.filter(regex='TIME')))]
dataFrame = dataFrame[dataFrame.columns.drop(list(dataFrame.filter(regex='DATE_TIME')))]
dataFrame = dataFrame[dataFrame.columns.drop(list(dataFrame.filter(regex='Date_Time')))]
if not os.path.exists('Output'):
os.mkdir('Output')
dataFrame.to_csv(r'Output\\CSV_' + datetime.datetime.now().strftime("%d%m%Y%H%M%S") + '.csv', index=False,
header=True)
if __name__ == '__main__':
startAnalyze(
"E:\\\Tech Ninja\\CSV-File-Analyzer\\Sample Data\\100020538804102020083946.csv")
# startCleansing(
# "DUPLICATEsn_120=sn_12REMOVE&DUPLICATE1=sn_12.1KEEP&SINGLEsn_70=sn_7REMOVE&SINGLEsn_101=sn_10REMOVE&MISSINGsn_20=sn_2REMOVE&MISSINGsn_31=sn_3REMOVE&MISSINGsn_52=sn_5REMOVE&MISSINGsn_73=sn_7REMOVE&MISSINGsn_84=sn_8REMOVE&MISSINGsn_95=sn_9REMOVE&MISSINGsn_106=sn_10REMOVE&MISSINGsn_127=sn_12REMOVE&MISSINGsn_12.18=sn_12.1REMOVE&MISSINGsn_139=sn_13REMOVE&MISSINGsn_1610=sn_16REMOVE&SAMEsn_40=sn_4REMOVE&SAMEsn_141=sn_14REMOVE&DR=DR_REMOVE&IR=IR_REMOVE")
|
[
"pandas.DataFrame",
"os.mkdir",
"pandas.read_csv",
"os.path.exists",
"numpy.zeros",
"itertools.combinations",
"datetime.datetime.now"
] |
[((270, 309), 'pandas.read_csv', 'pd.read_csv', (['csv_path'], {'low_memory': '(False)'}), '(csv_path, low_memory=False)\n', (281, 309), True, 'import pandas as pd\n'), ((325, 377), 'pandas.read_csv', 'pd.read_csv', (['csv_path'], {'header': 'None', 'low_memory': '(False)'}), '(csv_path, header=None, low_memory=False)\n', (336, 377), True, 'import pandas as pd\n'), ((391, 408), 'pandas.DataFrame', 'pd.DataFrame', (['csv'], {}), '(csv)\n', (403, 408), True, 'import pandas as pd\n'), ((430, 447), 'pandas.DataFrame', 'pd.DataFrame', (['csv'], {}), '(csv)\n', (442, 447), True, 'import pandas as pd\n'), ((467, 492), 'pandas.DataFrame', 'pd.DataFrame', (['csv_no_head'], {}), '(csv_no_head)\n', (479, 492), True, 'import pandas as pd\n'), ((1479, 1511), 'pandas.DataFrame', 'pd.DataFrame', (['anyValueMissingRow'], {}), '(anyValueMissingRow)\n', (1491, 1511), True, 'import pandas as pd\n'), ((3104, 3129), 'numpy.zeros', 'np.zeros', (['(rows, columns)'], {}), '((rows, columns))\n', (3112, 3129), True, 'import numpy as np\n'), ((3271, 3288), 'numpy.zeros', 'np.zeros', (['columns'], {}), '(columns)\n', (3279, 3288), True, 'import numpy as np\n'), ((4956, 4973), 'numpy.zeros', 'np.zeros', (['columns'], {}), '(columns)\n', (4964, 4973), True, 'import numpy as np\n'), ((9060, 9084), 'os.path.exists', 'os.path.exists', (['"""Output"""'], {}), "('Output')\n", (9074, 9084), False, 'import os\n'), ((9088, 9106), 'os.mkdir', 'os.mkdir', (['"""Output"""'], {}), "('Output')\n", (9096, 9106), False, 'import os\n'), ((1190, 1217), 'itertools.combinations', 'combinations', (['columnList', '(2)'], {}), '(columnList, 2)\n', (1202, 1217), False, 'from itertools import combinations\n'), ((4121, 4152), 'pandas.DataFrame', 'pd.DataFrame', (['singleValueColumn'], {}), '(singleValueColumn)\n', (4133, 4152), True, 'import pandas as pd\n'), ((4020, 4051), 'pandas.DataFrame', 'pd.DataFrame', (['singleValueColumn'], {}), '(singleValueColumn)\n', (4032, 4051), True, 'import pandas as pd\n'), ((9144, 9167), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (9165, 9167), False, 'import datetime\n')]
|
"""
Various data import functions for training and validation of neural networks.
"""
import numpy as np
import random as rnd
from oap.__conf__ import OAP_FILE_EXTENSION, SLICE_SIZE
from oap.lib import normalize
from oap.utils import (
barycenter,
features,
adjust_y,
center_particle,
flip_x,
flip_y,
monochromatic,
move_to_x,
move_to_y
)
from oap.utils.files import filepaths, read_oap_file
def generator(directory, positive, batch_size=1, y_dim=SLICE_SIZE, balance=False, shuffle=False,
monochrome=False, center=False, move=True, flip=True, exclude=None, include=None,
file_extension=OAP_FILE_EXTENSION, slice_size=SLICE_SIZE):
"""
oap-file generator for training with neural networks.
Especially developed to train / validate a model with the Keras library.
(see Keras - Class: tf.keras.Model | Method: fit_generator).
:param directory: path to directory
:type directory: string
:param positive: list of particle types for positive labeling
:type positive: list
--- optional params ---
:param batch_size: size of the data batch
:type batch_size: int
:param y_dim: height of the particle image / optical-array
:type y_dim: int
:param balance: balances the positive data with the same number of negative data
:type balance: boolean
:param shuffle: shuffles the data before every epoch
:type shuffle: boolean
:param monochrome: converts the optical array to monochromatic shadow levels (just ones and zeros)
:type monochrome: boolean
:param center: centers the particle in the image frame (only in x-axis)
:type center: boolean
:param move: randomly moves the particle within the image frame
Warning: only works, if center == False
:type move: boolean
:param flip: randomly flips the array in x and / or y direction
:type flip: boolean
:param exclude: list of folders which should be excluded
:type exclude: list of strings
:param include: list of folders to include - ignores all other folders
:type include: list of strings
:param file_extension: file type
:type file_extension: string
:param slice_size: width of the optical array (number of diodes)
:type slice_size: integer
:return: image-tensor (shape: (batch_size, y_dim, x_dim, 1),
label-tensor (len == batch_size)
"""
positive_files = []
negative_files = []
if balance:
positive_files = filepaths(directory, exclude=exclude, include=include,
file_extension=file_extension, p_types=positive)
negative_files = [f for f in filepaths(directory, exclude=exclude, include=include,
file_extension=file_extension) if f not in positive_files]
files = rnd.sample(negative_files, len(positive_files)) + positive_files
else:
files = filepaths(directory, exclude=exclude, include=include, file_extension=file_extension)
number_of_batches = len(files) // batch_size
rnd.shuffle(files)
batch_iterator = 0
while True:
if batch_iterator >= number_of_batches:
batch_iterator = 0
if balance:
# Sample new negative files
files = rnd.sample(negative_files, len(positive_files)) + positive_files
if shuffle:
rnd.shuffle(files)
x = [] # Data
y = [] # Labels
for i in range(batch_size):
array, header = read_oap_file(filename=files[batch_iterator*batch_size+i],
as_type="ARRAY", slice_size=slice_size)
if monochrome:
array = monochromatic(array, slice_size=slice_size)
if flip:
if bool(rnd.getrandbits(1)):
array = flip_y(array, slice_size=slice_size)
if bool(rnd.getrandbits(1)):
array = flip_x(array, slice_size=slice_size)
# Unify the height of the optical array.
array = adjust_y(array, new_y=y_dim, slice_size=slice_size)
if center:
center_particle(array, slice_size=slice_size)
elif move:
feat = features(array, slice_size=slice_size)
x_bary, y_bary = barycenter(array, coordinates=True)
# Random uniform between top border and bottom border
new_y = int(rnd.uniform(y_bary, y_dim - y_bary))
array = move_to_y(array, new_y=new_y, slice_size=slice_size)
# Random uniform between left border and right border
new_x = int(rnd.uniform(x_bary-feat['min_index'], slice_size-(feat['max_index']-x_bary)))
array = move_to_x(array, new_x=new_x, slice_size=slice_size)
# Normalize!
array = normalize(array, value=1.0 if monochrome else 3.0)
label = 1.0 if header in positive else 0.0
# Reshape to Height x Width x Number of Channels
x.append(array.reshape(y_dim, slice_size, 1))
y.append(label)
batch_iterator += 1
yield np.array(x), np.array(y)
|
[
"oap.utils.move_to_y",
"oap.lib.normalize",
"oap.utils.files.filepaths",
"oap.utils.barycenter",
"oap.utils.monochromatic",
"random.uniform",
"random.shuffle",
"oap.utils.move_to_x",
"oap.utils.flip_x",
"oap.utils.adjust_y",
"oap.utils.files.read_oap_file",
"numpy.array",
"random.getrandbits",
"oap.utils.center_particle",
"oap.utils.features",
"oap.utils.flip_y"
] |
[((3363, 3381), 'random.shuffle', 'rnd.shuffle', (['files'], {}), '(files)\n', (3374, 3381), True, 'import random as rnd\n'), ((2779, 2887), 'oap.utils.files.filepaths', 'filepaths', (['directory'], {'exclude': 'exclude', 'include': 'include', 'file_extension': 'file_extension', 'p_types': 'positive'}), '(directory, exclude=exclude, include=include, file_extension=\n file_extension, p_types=positive)\n', (2788, 2887), False, 'from oap.utils.files import filepaths, read_oap_file\n'), ((3223, 3313), 'oap.utils.files.filepaths', 'filepaths', (['directory'], {'exclude': 'exclude', 'include': 'include', 'file_extension': 'file_extension'}), '(directory, exclude=exclude, include=include, file_extension=\n file_extension)\n', (3232, 3313), False, 'from oap.utils.files import filepaths, read_oap_file\n'), ((3833, 3940), 'oap.utils.files.read_oap_file', 'read_oap_file', ([], {'filename': 'files[batch_iterator * batch_size + i]', 'as_type': '"""ARRAY"""', 'slice_size': 'slice_size'}), "(filename=files[batch_iterator * batch_size + i], as_type=\n 'ARRAY', slice_size=slice_size)\n", (3846, 3940), False, 'from oap.utils.files import filepaths, read_oap_file\n'), ((4385, 4436), 'oap.utils.adjust_y', 'adjust_y', (['array'], {'new_y': 'y_dim', 'slice_size': 'slice_size'}), '(array, new_y=y_dim, slice_size=slice_size)\n', (4393, 4436), False, 'from oap.utils import barycenter, features, adjust_y, center_particle, flip_x, flip_y, monochromatic, move_to_x, move_to_y\n'), ((5190, 5240), 'oap.lib.normalize', 'normalize', (['array'], {'value': '(1.0 if monochrome else 3.0)'}), '(array, value=1.0 if monochrome else 3.0)\n', (5199, 5240), False, 'from oap.lib import normalize\n'), ((2955, 3045), 'oap.utils.files.filepaths', 'filepaths', (['directory'], {'exclude': 'exclude', 'include': 'include', 'file_extension': 'file_extension'}), '(directory, exclude=exclude, include=include, file_extension=\n file_extension)\n', (2964, 3045), False, 'from oap.utils.files import filepaths, read_oap_file\n'), ((3700, 3718), 'random.shuffle', 'rnd.shuffle', (['files'], {}), '(files)\n', (3711, 3718), True, 'import random as rnd\n'), ((4025, 4068), 'oap.utils.monochromatic', 'monochromatic', (['array'], {'slice_size': 'slice_size'}), '(array, slice_size=slice_size)\n', (4038, 4068), False, 'from oap.utils import barycenter, features, adjust_y, center_particle, flip_x, flip_y, monochromatic, move_to_x, move_to_y\n'), ((4477, 4522), 'oap.utils.center_particle', 'center_particle', (['array'], {'slice_size': 'slice_size'}), '(array, slice_size=slice_size)\n', (4492, 4522), False, 'from oap.utils import barycenter, features, adjust_y, center_particle, flip_x, flip_y, monochromatic, move_to_x, move_to_y\n'), ((5488, 5499), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (5496, 5499), True, 'import numpy as np\n'), ((5501, 5512), 'numpy.array', 'np.array', (['y'], {}), '(y)\n', (5509, 5512), True, 'import numpy as np\n'), ((4115, 4133), 'random.getrandbits', 'rnd.getrandbits', (['(1)'], {}), '(1)\n', (4130, 4133), True, 'import random as rnd\n'), ((4164, 4200), 'oap.utils.flip_y', 'flip_y', (['array'], {'slice_size': 'slice_size'}), '(array, slice_size=slice_size)\n', (4170, 4200), False, 'from oap.utils import barycenter, features, adjust_y, center_particle, flip_x, flip_y, monochromatic, move_to_x, move_to_y\n'), ((4225, 4243), 'random.getrandbits', 'rnd.getrandbits', (['(1)'], {}), '(1)\n', (4240, 4243), True, 'import random as rnd\n'), ((4274, 4310), 'oap.utils.flip_x', 'flip_x', (['array'], {'slice_size': 'slice_size'}), '(array, slice_size=slice_size)\n', (4280, 4310), False, 'from oap.utils import barycenter, features, adjust_y, center_particle, flip_x, flip_y, monochromatic, move_to_x, move_to_y\n'), ((4569, 4607), 'oap.utils.features', 'features', (['array'], {'slice_size': 'slice_size'}), '(array, slice_size=slice_size)\n', (4577, 4607), False, 'from oap.utils import barycenter, features, adjust_y, center_particle, flip_x, flip_y, monochromatic, move_to_x, move_to_y\n'), ((4641, 4676), 'oap.utils.barycenter', 'barycenter', (['array'], {'coordinates': '(True)'}), '(array, coordinates=True)\n', (4651, 4676), False, 'from oap.utils import barycenter, features, adjust_y, center_particle, flip_x, flip_y, monochromatic, move_to_x, move_to_y\n'), ((4837, 4889), 'oap.utils.move_to_y', 'move_to_y', (['array'], {'new_y': 'new_y', 'slice_size': 'slice_size'}), '(array, new_y=new_y, slice_size=slice_size)\n', (4846, 4889), False, 'from oap.utils import barycenter, features, adjust_y, center_particle, flip_x, flip_y, monochromatic, move_to_x, move_to_y\n'), ((5091, 5143), 'oap.utils.move_to_x', 'move_to_x', (['array'], {'new_x': 'new_x', 'slice_size': 'slice_size'}), '(array, new_x=new_x, slice_size=slice_size)\n', (5100, 5143), False, 'from oap.utils import barycenter, features, adjust_y, center_particle, flip_x, flip_y, monochromatic, move_to_x, move_to_y\n'), ((4776, 4811), 'random.uniform', 'rnd.uniform', (['y_bary', '(y_dim - y_bary)'], {}), '(y_bary, y_dim - y_bary)\n', (4787, 4811), True, 'import random as rnd\n'), ((4989, 5075), 'random.uniform', 'rnd.uniform', (["(x_bary - feat['min_index'])", "(slice_size - (feat['max_index'] - x_bary))"], {}), "(x_bary - feat['min_index'], slice_size - (feat['max_index'] -\n x_bary))\n", (5000, 5075), True, 'import random as rnd\n')]
|
# -*- coding: utf-8 -*-
""" Simulating what echolocating bats as they fly in groups - AKA the
'cocktail party nightmare'
Created on Tue Dec 12 21:55:48 2017
Copyright <NAME>, 2019
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
The Bridson package distributed along with this
repository is written by <NAME> and licensed under an MIT License.
"""
import os
import sys
sys.path.append('../bridson/')
sys.path.append('../acoustics/')
import pdb
import numpy as np
import pandas as pd
import scipy.misc as misc
import scipy.spatial as spl
from bridson import poisson_disc_samples
from detailed_sound_propagation import soundprop_w_acoustic_shadowing, calc_RL
def assign_random_arrival_times(sound_df, **kwargs):
'''Assigns a random arrival time to the sounds in the input sound_df.
The sound_df can be either conspecific calls or secondary echoes.
Parameters
----------
sound_df : pd.DataFrame with at least the following columns:
'start', 'stop'
Keyword Arguments
----------------
simtime_resolution
interpulse_interval
echocall_duration
Returns
-------
sound_df with values assigned to the start and stop columns
'''
num_timesteps = calc_num_timesteps_in_IPI(**kwargs)
ipi_in_timesteps = range(num_timesteps)
echocall_timesteps = int(np.around(kwargs['echocall_duration']/kwargs['simtime_resolution']))
num_sounds = sound_df.shape[0]
start_stop = place_sounds_randomly_in_IPI(ipi_in_timesteps, echocall_timesteps,
num_sounds)
sound_df['start'] = start_stop[:,0]
sound_df['stop'] = start_stop[:,1]
return(sound_df)
def calc_num_timesteps_in_IPI(**kwargs):
'''Calculates the number of time steps in an IPI given the simtime resolution
Keyword Arguments
----------------
simtime_resolution
interpulse_interval
Returns
-------
num_timesteps : integer.
'''
num_timesteps = int(np.ceil(kwargs['interpulse_interval']/kwargs['simtime_resolution']))
return(num_timesteps)
def assign_real_arrival_times(sound_df, **kwargs):
'''Assigns a random arrival time to the sounds in the input sound_df.
The sound_df can be either conspecific calls or secondary echoes.
Parameters
----------
sound_df : pd.DataFrame with at least the following columns:
'start', 'stop'
Keyword Arguments
----------------
v_sound
bats_xy : Nbats x 2 np.array
XY positions of all bats. Focal bat is on the 1st row.
simtime_resolution
interpulse_interval
echocall_duration
echoes_beyond_ipi : Boolean.
True if echoes arriving later than the ipi are tolerated
False if all echoes must arrive within the ipi.
Defaults to False.
Returns
-------
sound_df with values assigned to the start and stop columns
'''
# get the delays at which the primary echoes from all the neighbours arrive
dist_mat = spl.distance_matrix(kwargs['bats_xy'], kwargs['bats_xy'])
echo_distances = dist_mat[1:,0]*2.0
echo_arrivaltimes = echo_distances/kwargs['v_sound'] - kwargs['echocall_duration']
if not np.all(echo_arrivaltimes >= 0):
msg = 'Some echoes are arriving before the call is over! Please check call duration or neighbour distance'
raise ValueError(msg)
relative_arrivaltimes = np.float64(echo_arrivaltimes/kwargs['interpulse_interval'])
# calculate arrival time in the ipi timesteps:
num_timesteps = calc_num_timesteps_in_IPI(**kwargs)
echo_start_timesteps = np.int64(np.around(relative_arrivaltimes*num_timesteps))
echo_timesteps = np.around(kwargs['echocall_duration']/kwargs['simtime_resolution'])
echo_end_timesteps = np.int64(echo_start_timesteps + echo_timesteps -1)
# assign the start and stop timesteps
sound_df['start'] = echo_start_timesteps
sound_df['stop'] = echo_end_timesteps
if not kwargs.get('echoes_beyond_ipi', False):
check_if_echoes_fall_within_IPI(sound_df, num_timesteps)
return(sound_df)
def check_if_echoes_fall_within_IPI(sound_df, ipi_length):
'''
Parameters
----------
sound_df : pd.DataFrame with at least 2 columns, 'start' and 'stop'
ipi_length : int.
number of timesteps in the interpulse interval
Raises
------
EchoesOutOfIPI : IndexError raised if echoes_beyond_ipi is False and
the echoes fall out of the interpulse interval.
'''
echoes_arrive_later_than_ipi = np.any(sound_df['stop'] > ipi_length)
if echoes_arrive_later_than_ipi:
raise EchoesOutOfIPI('Some echoes fall out of the interpulse interval - change the IPI or reduce distance of reflecting objects')
def place_sounds_randomly_in_IPI(timeline ,calldurn_steps, Nsounds = 1):
'''Randomly places
Parameters
----------
timeline: list. range object with iteration numbers ranging from 0 to the
the number of iterations the inter pulse interval consists of.
Eg. if the temporal resolution of the simulations is 10**-6 seconds
per timeblock then the IPI of 0.1 seconds is split into 10**5 steps.
The timeline will thus be xrange(10**5) or range(10**5)
calldurn_steps : integer. the length of the calls which are arriving in the
pulse interval
Nsounds : integer. number of calls to generate per pulse interval. Defaults to 1
Outputs:
sound_times : Nsounds x 2 np.array with start and end timesteps
'''
assert len(timeline) > calldurn_steps, 'Call duration cannot be greater than ipi!!'
# Achtung: I actually assume a right truncated timeline here
# because I want to ensure the full length of the call is always
# assigned within the inter-pulse interval
actual_timeline = timeline[:-calldurn_steps]
sound_starts = np.random.choice(actual_timeline, Nsounds)
sound_stops = sound_starts + calldurn_steps - 1
if np.any(sound_stops) > len(actual_timeline):
print(actual_timeline.size, calldurn_steps, np.max(sound_stops))
raise IndexError('Echo stop times extend beyond the IPI!')
return(np.column_stack((sound_starts, sound_stops)))
def calc_pechoesheard(num_echoes_heard, total_echoes):
'''Calculates the cumulative probabilities of 1,2,3,...N echoes
being heard in the midst of a given number of calls in the pulse
interval acting as maskers
Parameters
----------
num_echoes_heard : array like. Entries are the number of echoes heard.
total_echoes : integer. Total number of echoes placed in the interpulse
interval
Returns
-------
heard_probs : 1 x (Nechoes+1). Probability of hearing 0,1,2,..N echoes
pheard_cumulative : 1 x (Nechoes + 1) np.array with probabilities
of hearing 0, <=1, <=2 ..<=N echoes.
Example:
numechoesheard = [0,2,3,4,2,2]
calc_pechoesheard(numechoesheard,3) --> heardprobs, p_heardcumul
where:
heardprobs : array([0.16666667, 0., 0.5, 0.16666667, 0.16666667, 0.])
p_heardcumul: array([ 0.16666667, 0.16666667, 0.66666667, 0.83333333, 1.
, 1. ])
'''
try:
occurence = np.bincount(num_echoes_heard, minlength = total_echoes+1)
except TypeError:
occurence = np.bincount(num_echoes_heard.astype('int64'),
minlength = total_echoes+1)
heard_probs = occurence/float(sum(occurence))
cumulative_prob = np.cumsum(heard_probs)
return(heard_probs, cumulative_prob)
def calc_echoes2Pgeqechoes(many_heardechoes, num_echoes, geqN):
'''Calculates P of hearing >= Nechoes for multiple heard_echo objects
laid row on row
Parameters
----------
many_heardechoes : ncases x Ntrials np.array. Each row contains an integer
number of values with the echoes heard for each trial.
num_echoes : integer. Number of target echoes placed in the inter-pulse
interval.
geqN : integer. The probability of hearing at least or more than geqN echoes
will be calculated for each row.
Returns :
PgeqNechoes : ncases x 1 np.array with probability of hearing at least geqN
for each simulation case.
Examples :
input_heardechoes = [ [0,1,1,2,3],
[1,1,1,1,1] ]
geq = 1
calc_multiple_PgeqNechoes(input_heardechoes,geq ) --> [0.8, 1.0]
'''
cols = None
try:
rows, cols = many_heardechoes.shape
except ValueError:
rows = many_heardechoes.shape[0] # for 1 row case
PgeqNechoes = np.zeros((rows,1))
if cols is None :
probs, cum_prob = calc_pechoesheard(many_heardechoes, num_echoes)
PgeqNechoes = calc_PgeqNechoes(probs,geqN)
else :
for rownum, each_case in enumerate(many_heardechoes):
probs, cum_prob = calc_pechoesheard(each_case, num_echoes)
PgeqNechoes[rownum] = calc_PgeqNechoes(probs,geqN)
return(PgeqNechoes)
def calc_PgeqNechoes(heard_probs,geqN):
'''Calculates probability of at least >=N echoes being heard.
Parameters
----------
heard_probs : 1 x (Nechoes+1 ) array-like. Contains probabilities of hearing
0,1,....Nechoes in that order.
geqN : integer. The number of echoes or greater for which the probability
is required.
Returns :
p_geqN : 0<=float<=1. Probability of hearing at least N echoes in the inter
pulse interval.
Example:
calc_PgeqNechoes( [0.1, 0.05, 0.55, 0.25, 0.05] , 2 ) --> 0.85
'''
if not np.isclose(sum(heard_probs),1):
raise ValueError('The input probabilities do not sum to 1')
p_geqN = sum(heard_probs[geqN:])
return(p_geqN)
def populate_sounds(time_range, sound_duration,
sound_intensityrange, sound_arrivalangles,
num_sounds = 1,**kwargs):
'''Creates properties for a set of sounds (echo/call) given the
limits in kwargs. The output is considered a 'sound' DataFrame
Parameters
----------
time_range : np.array with integer numbers of the discretised timesteps
of the pulse interval.
sound_duration: integer. number of time steps that the call occupies.
sound_intensityrange : tuple with lower value in first index. minimum and
maximum intensitiy that the sounds arrive with.
Note : This argument can be set to None if poisson disk
sampling is being used to simulate spatial arrangem-
ent
sound_arrivalangles : tuple with lower value in first index. minimum and maximum range of angles that sounds
arrive with in degrees.
Note : This argument can be set to None if poisson disk
sampling is being used to simulate spatial arrangem-
ent
num_sounds: integer. number of sounds to generate
There are optional keyword arguments to include call directionality
with particular assumptions (please refer to the other notebooks or
the published paper for the assumptions with which call directionality is
implemented)
kwargs:
with_dirnlcall: with directional call. dictionary with the following keys.
A : float>0. Asymmetry parameter of Giuggioli et al. 2015
poisson_disk : implements bats as if they were placed nearly
uniformly in space with a Poisson disk arrange-
ment. The centremost point is set as the focal
bat's location, and the source level and recei-
ved angles are calculated according to the nei-
ghbouring points around it.
Dictionary with 2 keys :
'source_level' : dictionary with two keys describing
emitted call (ref function calculate_recei
-vedlevels)
'min_nbrdist' : float >0. Minimum distance maintained be-
tween neighbouring bats.
Returns
-------
all_sounds : pd.DataFrame with the following column names :
start | stop | theta | level |
Note : All thetas and intensity values are integer values.
'''
column_names = ['start','stop','theta','level']
all_sounds = pd.DataFrame(index=range(num_sounds),columns = column_names)
# generate the start and stop times of the sounds :
# [0] index required to avoid sublisting behaviour of generate_calls_randomly
start_stop = generate_calls_randomly(time_range,sound_duration,num_sounds,
1)[0]
startstop_array = np.asarray(start_stop)
all_sounds['start'] = startstop_array[:,0]
all_sounds['stop'] = startstop_array[:,1]
# LOCATION OF SCENARIO SPECIFIC SWITCHES - FOR GEOMETRY OF THE SWARM.
if not 'poisson_disk' in kwargs.keys():
angle1,angle2 = sound_arrivalangles
all_sounds['theta'] = np.random.random_integers(angle1,angle2,
num_sounds)
level1, level2 = sound_intensityrange
all_sounds['level'] = np.random.random_integers(level1,level2,
num_sounds)
else:
min_nbrdist = kwargs['poisson_disk']['min_nbrdist']
source_level = kwargs['poisson_disk']['source_level']
pois_theta, pois_intensity = implement_poissondisk_spatial_arrangement(
num_sounds,min_nbrdist, source_level)
all_sounds['theta'] = pois_theta
all_sounds['level'] = np.around(pois_intensity)
if 'with_dirnlcall' in kwargs.keys():
implement_call_directionality(all_sounds,
kwargs['with_dirnlcall']['A'])
return(all_sounds)
def implement_call_directionality(sound_df,A):
'''Calculates the received level of a conspecific call
given a set of received levels, angles
This function assumes all bats are flying in the same direction.
Parameters
----------
sound_df: pandas dataframe with the following column names :
|start|stop|theta|level|
(see populate_sounds documentation for more details)
A : float>0. Asymmetry parameter from Giuggioli et al. 2015 The higher
this value, the more drop there is off-axis.
Returns
-------
sound_df : returns the input dataframe with altered level values post
incorporation of call directionality factor.
'''
emission_angles = np.pi - np.deg2rad(sound_df['theta'])
cd_factor = np.array([call_directionality_factor(A,em_angle)
for em_angle in emission_angles])
sound_df['level'] += cd_factor
return(sound_df)
def calculate_num_heardechoes(echoes,other_sounds,
**kwargs):
'''Given an echo and call sound dataframes, outputs the total number of
echoes that a bat might have heard.
TODO:
1) add the other echoes into the other_sounds df each time !
2) SPEEDUP BY USING APPLY ON EACH ECHO RATHER THAN ITERROWS
Parameters
----------
echoes : pandas.DataFrame.
It is a 'sound' DataFrame with >=1 echoes and 4
columns (see 'populate_sounds' for more documentation)
other_sounds : pandas.DataFrame.
It is a 'sound' DataFrame with >=1 calls and secondary echoes
and 4 columns (see 'populate_sounds' for more documentation)
temporalmasking_fn : pandas.DataFrame.
The DataFrame has 2 columns:
'time_delay_ms' & 'delta_dB':
time_delay_ms: positive values are a forward masking regime,
and stand for the time gap between the end
of the masker and beginning of the echo.
Negative values are backward masking regimes
and stand for the time gap between the start
of the echo and start of the masker.
0 time delay is in the case of simultaneous mas-
king.
delta_dB : the difference between the intensity of the echo
and masker: echo_dBSPL - masker_dBSPL
spatial_release_fn : pandas.DataFrame.
????
Keyword Arguments
----------------
interpulse_interval :
simtime_resolution
temp masking funciton
spatial unmasking function
simtime_resolution : float>0. The time resolution of each timestep in
the simulation. This needs to be commensurate to
the auditory temporal resolution of the bat
auditory system.
Returns
-------
num_echoes: integer. number of echoes that are heard.
heardechoes_id : (if one_hot is True) 1x Nechoes one-hot binary np.array.
eg. for a 5 echo situation in which echoes 2,3 are heard,
the output will be --> np.array([0,1,1,0,0])
'''
kwargs['other_sounds'] = other_sounds
echoes_heard = echoes.apply(check_if_echo_heard, axis=1,
**kwargs)
num_echoes = sum(echoes_heard)
heardechoes_id = np.array(echoes_heard).astype('int')
return(num_echoes, heardechoes_id)
def multiecho_check_if_echo_heard(echo_row, **kwargs):
'''Wrapper function that allows the usage of the apply functionality
in a pd.DataFrame
'''
this_echoheard = check_if_echo_heard(echo_row, **kwargs)
return(this_echoheard)
def check_if_echo_heard(echo,
**kwargs):
'''Check if an echo is heard by calculating the echo-masker dB difference
in the interpulse interval.
The dB difference is calculated after spatial unmasking, and if the
delata dB profile lies above the temporal masking baseline for an echo,
then the echo is heard.
Eg. if the temporal masking function is [-5,-3,-2,-1,-1,-1,-3,-4] around the echo
and the delta dB SPL profile is [-2, 0, 1,-1, 0, 0, -1, -2]
then the echo is heard as the 'signal-to-noise' ratio is high.
Parameters
----------
echo : 1 x 4 pd.DataFrame
Keyword Arguments
----------------
other_sounds : 1 x 5 pd.DataFrame.A sound DataFrame with 'post_SUM' column which
refers to the reduction in required echo-masker delta dB SPL
because of spatial unmasking.
simtime_resolution
temporalmasking_fn : Ntimepoints x 2 pd.DataFrame
with following columnspyder
names :
|timegap_ms|delta_dB|
spatial_unmasking_fn : pd.DataFrame
|deltatheta|dB_release|
Returns
----------
echo_heard : Boolean.
True if echo is heard, False if it could be masked
'''
if float(echo['level']) >= kwargs['hearing_threshold']:
apply_spatial_unmasking_on_sounds(float(echo['theta']),
kwargs['other_sounds'], **kwargs)
cumulative_spl = ipi_soundpressure_levels(kwargs['other_sounds'], 'post_SUM',
**kwargs)
cumulative_dbspl = dB(cumulative_spl)
echo_heard = check_if_cum_SPL_above_masking_threshold(echo,
cumulative_dbspl,
**kwargs)
return(echo_heard)
else:
return(False)
def check_if_cum_SPL_above_masking_threshold(echo, cumulative_dbspl,
**kwargs):
'''Check an echo is ehard or not based on whether the
echo-masker delta dB is satisfied in the temporal masking window.
ATTENTION : this function *assumes* that the echo is placed in the interpulse
interval - which is a sensible assumption for the most part -- and it
may not work for secondary echoes and other such echoes that are beyond
the ipi.
Parameters
----------
echo : 1 x 4 sound_df.
cumulative_dbspl : 1D x Ntimesteps.
Keyword Arguments
----------------
simtime_resolution : float>0. Duration of one simultation timestep
temporal_masking_thresholds : tuple with 3 np.arrays as entries (forward_deltadB, simultaneous_deltadB,
backward_deltadB) - in that order. The np.arrays have the delta dB
thresholds required for echo detection in the presence of maskers.
Each value is assumed to be the value for that time delay at
the simtime_resolution being used.
masking_tolerance : 1>float >0
This parameter is used in two contexts :
1. The duration of time as a fraction of
echo duration that the cumulative SPL can
be above the temporal masking window, and the echo is
still heard.
eg. is masking_toleration is 0.75 for a 10 ms echo,
then even if 7.5 ms of it is masked, the echo is
still considered heard.
Defaults to 0.25
2. The minimum length of an echo that must fall within
the ipi for it to be considered audible at all
and moved further to check its relative
levels with the cumulative SPL.
Returns
-------
echo_heard : Boolean . True if echo-masker SPL ratios were above the tmeporal
masking function.
Note
--------
1. If the whole echo is not in the IPI then only the portion that is within the
current IPI will be considered.
2. If more than 75 % of an echo is above the temporal masking function
it is considered heard.
'''
delta_echo_masker = float(echo['level']) - cumulative_dbspl
echo_start, echo_stop = int(echo['start']), int(echo['stop'])
fwd, simultaneous, bkwd = kwargs['temporal_masking_thresholds']
ipi_timesteps = cumulative_dbspl.size
# choose the snippet relevant to the temporal masking function:
tolerated_masking = kwargs.get('masking_tolerance', 0.25)
left_echo_edge, right_echo_edge = calculate_start_stop_points_in_ipi([echo_start, echo_stop],
ipi_timesteps)
sufficient_length_in_ipi = is_the_echo_mostly_in_the_ipi(echo_start, echo_stop,
ipi_timesteps,
**kwargs)
if sufficient_length_in_ipi:
fwd_left, fwd_right = calculate_start_stop_points_in_ipi([echo_start-fwd.size, echo_start],
ipi_timesteps)
bkwd_left, bkwd_right = calculate_start_stop_points_in_ipi([echo_stop, echo_stop+bkwd.size],
ipi_timesteps)
delta_echomasker_snippet = delta_echo_masker[fwd_left:bkwd_right+1]
fwd_masking = fwd[:fwd_right-fwd_left]
simult_masking = np.tile(simultaneous, right_echo_edge-left_echo_edge+1)
backwd_masking = bkwd[:bkwd_right-bkwd_left]
temp_masking_snippet = np.concatenate((fwd_masking,
simult_masking,
backwd_masking))
# compare to see if the overall duration above the threshold is >= echo_duration
try:
#pdb.set_trace()
timesteps_echo_below_masker = delta_echomasker_snippet < temp_masking_snippet
duration_echo_is_masked = np.sum(timesteps_echo_below_masker)*kwargs['simtime_resolution']
except:
print(delta_echomasker_snippet.shape, temp_masking_snippet.shape,
echo, ipi_timesteps)
raise
if duration_echo_is_masked <= kwargs['echocall_duration']*(tolerated_masking):
echo_heard = True
else :
echo_heard = False
else:
# if none of the echo is in the ipi or if there's very little of the echo
# falling in the ipi itself
echo_heard = False
return(echo_heard)
def is_the_echo_mostly_in_the_ipi(start_index, stop_index,
num_timesteps_in_ipi,
**kwargs):
'''Checkes to see if (mosT) of the echo is
in the ipi.
Parameters
----------
start_index, stop_index : int.
The start and stop positions
of an echo.
num_timesteps_in_ipi : int.
The number of timesteps in the ipi.
Keyword Arguments
------------------
simtime_resolution : float >0.
Amount of time that one simulation timestep represents
masking_tolerance : 1>float>0
The fraction of the echo that can be out of the
ipi for it to still be considered
mostly in the ipi.
eg. if masking tolerance is 0.25
then for a 4 ms echo, even if 3ms of it was
within the ipi - then it'd be considered to
be mostly in the ipi.
Defaults to 0.25
Returns
--------
echo_mostly_in_ipi : Boolean.
True is the echo is mostly in ipi,
False if not.
'''
all_timesteps = np.arange(num_timesteps_in_ipi)
echo_indices = np.arange(start_index, stop_index+1)
echo_region_within_ipi = np.intersect1d(echo_indices, all_timesteps)
full_echo_in_ipi = echo_indices.size == echo_region_within_ipi.size
if full_echo_in_ipi:
return(True)
else:
masking_tolerance = kwargs.get('masking_tolerance', 0.25)
region_outof_ipi = (echo_indices.size - echo_region_within_ipi.size)*kwargs['simtime_resolution']
permitted_duration_out_of_ipi = masking_tolerance*kwargs['echocall_duration']
if region_outof_ipi >= permitted_duration_out_of_ipi:
return(False)
else:
return(True)
def calculate_start_stop_points_in_ipi(indices, ipi_size):
'''Checks if the start,stop list is within the ipi indices and assign the
closest indices within the ipi timesteps.
Parameters
----------
indices : list with 2 integers. The start, stop indices are given
for the different masking zones around an echo
ipi_size : integer. The maximum possible integer size that the indices
can have.
Returns
-------
indices : modified if the indices presented are < 0 or > ipi_indices
Example
-------
check_if_in_ipi([-20, 300], 2000) --> [0,300]
'''
start, stop = indices
if start < 0:
start = 0
elif start > ipi_size -1:
start = ipi_size -1
if stop > ipi_size-1:
stop = ipi_size -1
elif stop <0:
raise ValueError('stop index cannot be <0! : '+ str(stop))
indices = [start, stop]
return(indices)
def apply_spatial_unmasking_on_sounds(echo_theta,
sound_df, **kwargs):
'''Calculate angular separation between a target echo and the surrounding sounds
in the ipi and get the spatial release obtained from the angular separation.
Parameters
----------
echo_theta : 180 <= degrees <= -180. The arrival angle of the target echo in degrees.
Sounds arriving from the left are -ve and from the right are +ve.
sound_df : pd.DataFrame. a sound DataFrame
Keyword Arguments
-----------------
spatial_release_fn : pd.DataFrame
two columns with the angular separation and the
reduction in exho-masker level due to it.
Returns
-------
sound_df : the input sound_df with an extra column 'post_SUM'. This column refers
to the effective masker received level after spatial unmasking.
'''
angular_separations = np.apply_along_axis(get_relative_echo_angular_separation, 0,
np.array(sound_df['theta']).reshape(1,-1),
echo_theta)
spatial_release_dB = np.apply_along_axis(calc_spatial_release, 0, angular_separations,
kwargs['spatial_release_fn'] )
sound_df['post_SUM'] = sound_df['level'] + spatial_release_dB
return(sound_df)
def ipi_soundpressure_levels(sound_df, spl_columnname, **kwargs):
'''add the SPL of sounds and get a 'cumulative; ipi SPL profile.
Parameters
----------
sound_df : 1 x 5 pd.DataFrame. With the columns start, stop, theta, level, post_SUM
spl_columnname : str. The kind of sound pressure level to be used for the
cumulative sound pressure level calculations. If 'level'
is used then it is the plain dB sound pressure level re 20 muPa.
If 'post_SUM' is used, then it is the effective
lowered sound pressure level modelled by spatial unmasking.
Returns
-------
ipi_soundpressure : 1 x Ntimesteps np.array.
An 1D array with the sound pressure level factor re 20muPa for
each timestep. One timestep is interpulse_interval/simtime_resolution
long. The sound pressures are added coherently first and returned in the
pressure scale
Keyword Arguments
----------------
interpulse_interval : float >0. time between one bat call and anotehr
simtime_resolution : float >0. Duration of one timestep - this decides how
many timesteps there are in an interpulse interval.
'''
ipi_soundpressure = np.zeros(int(kwargs['interpulse_interval']/kwargs['simtime_resolution']))
for start, stop, dBsound_pressure in zip( sound_df['start'],sound_df['stop'], sound_df[spl_columnname]):
try:
ipi_soundpressure[start:stop] += 10**(dBsound_pressure/20.0)
except:
print('start', start, 'stop',stop, 'size:',ipi_soundpressure.size)
raise
return(ipi_soundpressure)
def add_soundpressures(df_spl, IPI):
'''
'''
start, stop, dblevel = df_spl
IPI[start:stop] += 10**(dblevel/20.0)
def get_collocalised_deltadB(timegap_ms, temp_mask_fn):
'''Return the closest corresponding deltadB in the temporal masking function
'''
closest_indx = np.argmin(np.abs(timegap_ms-temp_mask_fn.iloc[:,0]))
return(temp_mask_fn.iloc[closest_indx,1])
def get_relative_echo_angular_separation(sound_angle, echo_angle):
'''Outputs the minimum angle between two angles of arrival.
Any sound arriving to the left of the bat is 0<angle<-180 degrees
and any sound arriving to the right of the abt is 0>angle>180 degrees.
The output is the angular separation between two sound w ref to an
echoes arrival angle.
Parameters
----------
sound_angle : -180 <= angle <= 180.Relative arrival angle of another sound
- either a conspecific call or secondary echo.
echo_angle : -180 <= angle <= 180. Relative arrival angle of an echo
Returns
-------
angular_separation : 0>= angle>=180. Angular separation in degrees, relative to
the angle of arrival of the echo.
'''
angular_separation = np.abs(echo_angle - sound_angle)
if angular_separation > 180:
return(360-angular_separation)
else:
return(angular_separation)
def calc_angular_separation(angle1,angle2):
'''Calculates the minimum separation between two angles, the 'inner' angle.
Parameters
----------
angle1: float. degrees
angle2: float. degrees
Returns
-------
diff_angle. float.
Example:
If there are two angles given, eg. 90deg and 350deg. The diff angle will be
100deg and not 260 deg.
calc_angular_separation(90,350) --> 100
'''
diff_angle = abs(float(angle1-angle2))
if diff_angle > 180:
diff_angle = 360 - diff_angle
return(diff_angle)
def calc_spatial_release(angular_separation, spatial_release):
'''Gives the spatial release value closest to the input
Parameters
----------
angular_separation: integer. angular separation in degrees.
spatial_release : 2 x Nangularseparations np.array.
The 0'th column has the angular separations
and the 1st column has the spatial release value:
|deltatheta|dB_release|
Returns
-------
dB_release: float. Amount of spatial release due to spatial unmasking in dB
Example:
let's say we have a spatial release functio with this data :
theta spatial release
0 -10
5 -20
10 -30
and the angular separation we give is 2 degrees.
calc_spatial_release(2,spatial_release) --> -10
if angular separation is 7.5 , then the function returns the first index which
is close to 7.5.
calc_spatial_release(3,spatial_release) --> -20
'''
closest_index = np.argmin(abs(spatial_release[:,0]-angular_separation))
dB_release = spatial_release[closest_index,1]
return(dB_release)
# helper functions to separate out tuples
extract_numechoesheard = lambda X : X[0]
extract_echoids = lambda X : X[1]
dB = lambda X : 20*np.log10(abs(X))
def assemble_echoids(echoids_per_calldensity, call_densities, num_echoes,
num_trials):
'''reshapes multiple 2D onehot echoids in a list into a 3D array
'''
multidensity_echoids = np.zeros((len(call_densities),num_trials,num_echoes))
for i, echoids_at_calldensity in enumerate(echoids_per_calldensity):
multidensity_echoids[i,:,:] = echoids_at_calldensity
return(multidensity_echoids)
def calculate_directionalcall_level(call_params, receiver_distance):
'''Calculates the received level of a call according to a given emission
angle, on-axis source level and distane to the receiver
Note. This calculation DOES NOT include atmospheric attenuation !
- and is therefore an overly pessimistic calculation
Parameters
----------
call_params: dictioanry with following keys:
A : float>0. Asymmetry parameter
source_level: float>0. On-axis source level of a call at 1 metre in
dB SPL re 20 microPa
emission_angle : value between -pi and pi radians.
receiver_distance: float>0. Distance of the receiving bat from the emitting
bat in metres.
Returns :
received_level : float. Intensity of sound heard by the receiver in dB SPL
re 20 microPa
'''
off_axis_factor = call_directionality_factor(call_params['A'],
call_params['emission_angle'])
directional_call_level = call_params['source_level'] + off_axis_factor
received_level = directional_call_level -20*np.log10(receiver_distance/1.0)
return(received_level)
def call_directionality_factor(A,theta):
'''Calculates the drop in source level as the angle
increases from on-axis.
The function calculates the drop using the third term
in equation 11 of Giuggioli et al. 2015
Parameters
----------
A : float >0. Asymmetry parameter
theta : float. Angle at which the call directionality factor is
to be calculated in radians. 0 radians is on-axis.
Returns
-------
call_dirn : float <=0. The amount of drop in dB which occurs when the call
is measured off-axis.
'''
if A <=0 :
raise ValueError('A should be >0 ! ')
call_dirn = A*(np.cos(theta)-1)
return(call_dirn)
def calc_num_times(Ntrials,p):
'''Calculates the probability of an event (eg. at least 3 echoes heard
in an inter-pulse interval) happening when the trial is repeated Ntrials
times.
Parameters
----------
Ntrials : integer >0. Number of trials that are played.
p : 0<=float<=1. probability of an event occuring.
Returns
-------
prob_occurence : pd.DataFrame with the following columns.
num_times : Number of times that the event could occur.
probability : Probability that an even will occur num_times
in Ntrials.
'''
if p>1 or p<0 :
raise ValueError('Probability must be >=0 and <=1 ')
if not Ntrials >0:
raise ValueError('Ntrials must be >0')
if not isinstance(Ntrials,int):
try:
isitnpinteger = Ntrials.dtype.kind == 'i'
if not isitnpinteger:
raise TypeError('Ntrials must be an integer value')
except:
raise TypeError('Ntrials must be an integer value')
probability = np.zeros(Ntrials+1)
num_times = np.arange(Ntrials+1)
for k in num_times:
probability[k] = misc.comb(Ntrials,k)*(p**(k))*(1-p)**(Ntrials-k)
prob_occurence = pd.DataFrame(index = range(Ntrials+1),
columns=['num_times','probability'])
prob_occurence['num_times'] = num_times
prob_occurence['probability'] = probability
return(prob_occurence)
def implement_hexagonal_spatial_arrangement(Nbats,nbr_distance,source_level):
'''Implements the fact that neigbouring bats in a group will occur at
different distances.
The focal bat is placed in the centre, and all neighbours are placed from
nearest to furthest ring according to the geometry of the group. By default
a hexagonal array arrangement is assumed, which means the focal bat has six
neighbours in the its first ring, followed by 12 neighbours in the second
ring, and so on.
Parameters :
Nbats : integer >0. number of bats to simulate as neighbours
nbr_distance : float>0. Distance to the nearest neighbour in the first ring
in metres.
source_level : dictionary with two keys :
'intensity' : float. Sound pressure level at which a bat calls ref
ref 20 muPa.
'ref_distamce' : float>0. distance in meters at which the call
intensity has been measured at.
Returns :
RL : 1x Nrings np.array. received level in dB SPL. The calculations are
done *without* any assumptions of atmospheric absorption - and only
considering spherical spreading. Where Nrings is the maximum number of
rings required to fill up Nbats in the hexagonal array.
num_calls : 1x Nrings np.array .number of calls at each received level that
arrive at the focal bat (without call directionality
implemented). See above for description of Nrings.
Example :
implement
'''
ring_nums, bat_nums = fillup_hexagonalrings(Nbats)
ring_distances = ring_nums * nbr_distance
RL_fromrings = calculate_receivedlevels(ring_distances, source_level)
return(RL_fromrings, bat_nums)
def fillup_hexagonalrings(numbats):
''' Fills up a given number bats in a group around a focal bat.
All the bats are placed within the centres of regular hexagonal
cells. The first ring refers to the immediate neighbours around the focal
bat. The second ring refers to the second concentric ring of cells centred
around the focal bat and so on.
All rings close to the bat need to be filled up before neighbouring bats
are added to the outer rings.
Parameters
----------
numbats : integer >0. The total number of neighbouring bats being simulated
Returns
occupied_rings : np.array with ring numbers starting from 1.
bats_in_eachring : number of bats in each ring.
Example :
fillup_hexagonalrings(10) --> np.array([1,2]) , np.array([6,4])
fillup_hexagonalrings(23) --> np.array([1,2,3]), np.array(6,12,5)
'''
if numbats <= 0 :
raise ValueError('Number of neighbouring bats must be >0')
n = np.arange(1,11)
bats_per_ring = 6*n
cumsum_bats = np.cumsum(bats_per_ring)
if numbats <= 6:
return(np.array(1),np.array(numbats))
outer_ring = np.argwhere(numbats<=cumsum_bats)[0] + 1
inner_rings = outer_ring -1
if inner_rings >1:
inner_numbats = 6*np.arange(1,inner_rings+1)
else:
inner_numbats = 6
bats_outermostring = numbats - np.sum(inner_numbats)
bats_in_eachring = np.append(inner_numbats,bats_outermostring)
occupied_rings = np.arange(1,outer_ring+1)
return(occupied_rings,bats_in_eachring)
def generate_surroundpoints_w_poissondisksampling(npoints, nbr_distance, **kwargs):
'''Generates a set of npoints+1 roughly equally placed points using the
Poisson disk sampling algorithm. The point closest to the centroid is
considered the centremost point. The closest points to the centremost point
are then chosen.
Parameters
----------
npoints: integer. Number of neighbouring points around the focal point
nbr_distance : float>0. Minimum distance between adjacent points.
Keyword Arguments
------------------
noncentral_bat : tuple with 2 entries.
entry 1 : 1 > r > 0. float.
the relative radial distance from
the centre to the bat furthest away
from the central bat
entry 2 : 0 < theta < 360. float.
The azimuthal location of the central
bat. 0 degrees is 3 o'clock and
the angles increase in a counter-clockwise
direction.
Returns
-------
nearby_points : npoints x 2 np.array. XY coordinates of neighbouring points
around the centremost point.
centremost_point : 1 x 2 np.array. XY coordinates of centremost point.
'''
if nbr_distance <= 0.0 :
raise ValueError('nbr_distance cannot be < 0')
if npoints < 1:
raise ValueError('Number of neighbouring points must be >=1 ')
insufficient_points = True
sidelength = np.ceil(np.sqrt(npoints))*2*nbr_distance
while insufficient_points:
data_np = np.array(poisson_disc_samples(sidelength,sidelength,
nbr_distance,k=30,
random=np.random.random))
rows, columns = data_np.shape
if rows <= npoints:
sidelength += nbr_distance
else :
insufficient_points = False
centremost_pt = choose_centremostpoint(data_np)
centremost_index = find_rowindex(data_np, centremost_pt)
nearby_points = find_nearbypoints(data_np, centremost_index, npoints-1)
#if the focal bat is to be placed elsewhere
noncentral_bat = kwargs.get('noncentral_bat',None)
if noncentral_bat:
new_nearby_points, focal_pt = choose_a_noncentral_bat(noncentral_bat,
nearby_points,
centremost_pt)
return(new_nearby_points, focal_pt)
else:
return(nearby_points, centremost_pt)
def choose_a_noncentral_bat(noncentral_bat,
nearby_points,
centremost_point):
'''Chooses a non central bat as the focal individual.
The auditory scene is calculated with respect to this
non central individual then.
Parameters
-------
noncentral_bat : tuple with 2 entries.
entry 1 : 1 > r > 0. float.
the relative radial distance from
the centre to the bat furthest away
from the central bat.
entry 2 : 0 < theta < 2pi radians. float.
The azimuthal location of the central
bat. 0 degrees is 3 o'clock and
the angles increase in a counter-clockwise
direction.
nearby_points : Nbats -1 x 2 array-like.
x-y coordinates of points surrounding the central point
centremost_point : 1 x 2 array-like.
Centremost point of the group.
Returns
--------
rearranged_nearby_points : Nbats-1 x 2 np.array
focal_point : 1 x 2 np.array.
The focal point chosen according to the r,theta positions
'''
r, theta = noncentral_bat
centre_and_other_pts = np.row_stack((centremost_point, nearby_points))
distances_from_centre = spl.distance_matrix(centre_and_other_pts,
centre_and_other_pts)[1:,0]
furthest_distance = np.max(distances_from_centre)
target_r = r*furthest_distance
target_xy = np.array([target_r*np.cos(theta), target_r*np.sin(theta)])
points_relative_to_centre = nearby_points - centremost_point
target_and_nearby_points = np.row_stack((target_xy, points_relative_to_centre))
distance_to_target = spl.distance_matrix(target_and_nearby_points,
target_and_nearby_points)[1:,0]
closest_point_index = np.argmin(distance_to_target)
focal_point = nearby_points[closest_point_index,:]
all_points_not_focal = np.delete(nearby_points, closest_point_index, 0)
rearranged_nearby_points = np.row_stack((centremost_point,
all_points_not_focal))
return(rearranged_nearby_points, focal_point)
def calculate_r_theta(target_points, focal_point):
'''Calculates radial distance and angle from a set of target points to the
focal point.
TODO : accept heading orientation other than 90 degrees
The angle calculated is the arrival angle for the focal point.
The focal_point is considered to be moving with a 90 degree direction by
default.
Parameters
----------
target_points: Npoints x 2 np.array. XY coordinates of the target points.
focal_point : 1 x 2 np.array. XY coordinates of the focal point.
Returns
-------
radial_distances : Npoints x 1 np.array. The radial distance between each
of the target points and the focal point.
arrival_angles : Npoints x 1 np.array. The angle of arrival at which a call
emitted from target points will arrive at the focal bat.
The angles are in degrees. Angles that are negative, imply
that the target point is on the left side of the focal poin
-t.
Example:
target_points = np.array([ [1,1],
[-1,-1]
])
focal_point = np.array([0,0])
rad_dists, angles_arrival = calculate_r_theta(target_points, focal_point)
rad_dists --> np.array([1.4142, 1.4142])
angles_arrival --> np.array([45,-45])
'''
radial_distances = np.apply_along_axis(calculate_radialdistance,1,
target_points,
focal_point)
arrival_angles = np.apply_along_axis(calculate_angleofarrival,1,
target_points,
focal_point)
return(radial_distances, arrival_angles)
def calculate_radialdistance(sourcepoint, focalpoint):
'''
Parameters
----------
sourcepoint, focalpoint : 1 x Ndimensions np.arraya with coordinates
Returns
-------
radialdist : float > 0. radial distance between sourcepoint and focalpoint
'''
radialdist = spl.distance.euclidean(sourcepoint, focalpoint)
return(radialdist)
def calculate_angleofarrival(sourcepoint_xy,focalpoint_xy,focalpoint_orientation=90.0):
'''Calculates the relative angle of arrival if a neighbouring bat were to
call.
Function based on https://tinyurl.com/y9qpq84l - thanks MK83
Parameters :
sourcepoint_xy : 1x2 np.array. xy coordinates of call emitting bat
focalpoint_xy : 1x2 np.array. xy coordinates of focal bat
focalpoint_orientation : float. heading of focal bat. 0 degrees means the
focal bat is facing 3 o'clock. Angles increase in
anti-clockwise fashion
Default is 90 degrees.
Returns :
angle_ofarrival : float. Angle of arrivals are between 0 and +/- 180 degrees
Positive angles of arrival imply the emitted sound will be
received on the right side, while negative angles of arrival
mean the sound is received on the left side.
Example :
source_xy = np.array([1,1])
focal_xy = np.array([0,0])
calculate_angleofarrival(source_xy, focal_xy) --> +45.0
'''
radagntorntn=np.radians(float(focalpoint_orientation))
p0= np.array([np.cos( radagntorntn ), np.sin( radagntorntn) ])+ focalpoint_xy
p1= focalpoint_xy
v0 = p0-p1
agentvects=(sourcepoint_xy-p1).flatten()
relangle = np.rad2deg( np.math.atan2( np.linalg.det([agentvects,v0]),
np.dot(agentvects,v0) ) )
relangle=np.around(relangle,4)
return( relangle )
def find_rowindex(multirow_array, target_array):
'''Given a multi-row array and a target 2D array which is one of the rows
from the multi-row array - gets the row index of the target array.
Parameters
----------
multirow_array : N x 2 np.array.
target_array : 1 x 2 np.array.
Returns
-------
row_index : integer. row index of the target_array within the multirow_array
'''
values_sqerror = multirow_array**2 - target_array**2
row_error = np.sum(values_sqerror,axis=1)
try:
row_index = int(np.where(row_error==0)[0])
return(row_index)
except:
raise ValueError('Multiple matching points - please check inputs')
def choose_centremostpoint(points):
'''Select the point at the centre of a set of points. This is done by calc-
ulating the centroid of a set of points and checking which of the given
points are closest to the centroid.
If there are multiple points at equal distance to the centroid, then
one of them is assigned arbitrarily.
Parameters
----------
points : Npoints x 2 np.array. With X and Y coordinates of points
Returns
-------
centremost_point : 1 x 2 np.array.
'''
centroid_point = calc_centroid(points)
centremost_point = find_closestpoint(points, centroid_point)
return(centremost_point)
def calc_centroid(data):
'''
based on code thanks to Retozi, https://tinyurl.com/ybumhquf
'''
try:
if data.shape[1] != 2:
raise ValueError('Input data must be a 2 column numpy array')
except:
raise ValueError('Input data must be a 2 column numpy array')
centroids = np.apply_along_axis(np.mean,0,data)
return(centroids)
def find_closestpoint(all_points, target_point):
'''Given a target point and a set of generated points,
outputs the point closest to the target point.
Example:
target_point = np.array([0,0])
generated_points = np.array([0,1],[2,3],[3,10])
find_closestpointindex(generated_points, target_point) --> np.array([0,1])
'''
distance2tgt = np.apply_along_axis(calc_distance,1,all_points,target_point)
closestpointindx = np.argmin(distance2tgt)
closestpoint = all_points[closestpointindx,:]
return(closestpoint)
calc_distance = lambda point1, point2 : spl.distance.euclidean(point1,point2)
def find_nearbypoints(all_points, focalpoint_index, numnearpoints):
'''Given a set of points choose a fixed number of them that are closest
to a focal point among them.
Parameters
----------
all_points : Npoints x 2 np.array. All generated points.
focalpoint_index : integer. Row index from all_points of the focal point.
numnearpoints : integer. Number of neighbouring points that must be chosen.
Returns
-------
nearbypoints : numnearpoints x 2 np.array.
Example :
all_points = np.array([ [0,0],[0,1],[1,0],[2,2],[3,5] ])
focalpoint_index = 0
numnearpoints = 3
find_nearestpoints(all_points, focalpoint_index, numnearpoints) -->
np.array([ [0,1],[1,0],[2,2] ])
'''
numrows, numcols = all_points.shape
if numnearpoints > numrows-1 :
raise ValueError('The number of neighbours requested is more than the number of points given!! ')
if not focalpoint_index in xrange(numrows):
raise IndexError('The given focalpoint index is not within the range of the array!')
validpoints = np.delete(all_points,focalpoint_index,0)
focal_point = all_points[focalpoint_index,:]
nearbypoints_dist = np.apply_along_axis(calc_distance,1,validpoints,
focal_point)
nearbypoints_indices = nearbypoints_dist.argsort()[:numnearpoints]
nearbypoints = validpoints[nearbypoints_indices,:]
return(nearbypoints)
def make_focal_first(xy_posns, focal_xy):
'''shifts the focal_xy to the 1st row
'''
row_index = find_rowindex(xy_posns, focal_xy)
focal_first = np.roll(xy_posns, np.tile(-row_index, 2))
return(focal_first)
def propagate_sounds(sound_type, **kwargs):
'''Propagates a sound and calculates the received levels and angles.
Conspecific calls and secondary echoes are placed randomly in the interpulse
interval. Primary echoes are placed according to their calculated time of
arrival by the distances at which the neighbouring bats are at.
Parameters
----------
sound_type : str.
Defines which kind of sound is being propagated.
The valid entries are either 'secondary_echoes',
'conspecific_calls' OR
'primary_echoes'
Keyword Arguments
----------------
focal_bat
bats_xy
bats_orientations
source_level
call_directionality,
hearing_directionality,
reflection_strength
shadow_strength
Returns
-------
received_sounds : pd.DataFrame
A 'sound' DataFrame - see populate_sounds
'''
sound_type_propagation = {'secondary_echoes': calculate_secondaryecho_levels,
'conspecific_calls' : calculate_conspecificcall_levels,
'primary_echoes' : calculate_primaryecho_levels}
try:
received_sounds = sound_type_propagation[sound_type](**kwargs)
return(received_sounds)
except:
print('Cannot propagate : ', sound_type)
raise
def calculate_conspecificcall_levels(**kwargs):
'''Calculates the received levels and angles of reception of conspecific calls
Keyword Arguments
----------------
focal_bat
bats_xy
bats_orientations
reflection_function
hearing_directionality
call_directionality
source_level
Returns
-------
conspecific_calls : pd.DataFrame.
A 'sound' df with received level, angle of arrival
and other related attributes of the sound :
start | stop | theta | level |
'''
if kwargs['bats_xy'].shape[0] < 2:
raise ValueError('Çonspecific calls cannot propagated for Nbats < 2')
conspecific_call_paths = calculate_conspecificcall_paths(**kwargs)
conspecific_calls = calculate_conspecificcallreceived_levels(conspecific_call_paths,
**kwargs)
return(conspecific_calls)
def calculate_secondaryecho_levels(**kwargs):
''' Calculates the received levels and angle of reception of 2ndary echoes from a conspecific call
bouncing off conspecifics once and reaching the focal bat
Keyword Arguments
----------------
focal_bat
bats_xy
bats_orientations
reflection_function
hearing_directionality
call_directionality
source_level
Returns
-------
secondary_echoes : pd.DataFrame. A 'sound' df with received level, angle of arrival
and other related attributes of the sound :
start | stop | theta | level |
'''
# There will be secondary echoes only when there are >= 3 bats
if kwargs['bats_xy'].shape[0] >= 3:
try:
# calculate the distances and angles involved in the secondary echo paths
secondary_echopaths = calculate_echopaths('secondary_echoes', **kwargs)
# calculate the sound pressure levels based on the geometry + emission-reception directionalities
secondary_echoes = calculate_echoreceived_levels(secondary_echopaths,
**kwargs)
except:
raise Exception('Unable to calculate secondary echoes!')
else:
# other wise return an empty sound df.
secondary_echoes = pd.DataFrame(data=[], index=[0],
columns=['start','stop','theta','level'])
return(secondary_echoes)
def calculate_primaryecho_levels(**kwargs):
''' Calculates the received levels and angle of reception of primary echoes from a conspecific call
bouncing off conspecifics once and reaching the focal bat
Keyword Arguments
----------------
focal_bat
bats_xy
bats_orientations
reflection_function
hearing_directionality
call_directionality
source_level
Returns
-------
secondary_echoes : pd.DataFrame.
A 'sound' df with received level, angle of arrival
and other related attributes of the sound :
start | stop | theta | level |
'''
try:
# calculate the distances and angles involved in the secondary echo paths
echopaths = calculate_echopaths('primary_echoes', **kwargs)
# calculate the sound pressure levels based on the geometry + emission-reception directionalities
primary_echoes = calculate_echoreceived_levels(echopaths,
**kwargs)
except:
raise Exception('Unable to calculate primary echoes!')
return(primary_echoes)
def calculate_conspecificcallreceived_levels(conspecificcall_paths,
**kwargs):
'''Calculates the final sound pressure levels at the focal receiver bat
of a conspecific call emitted by a group member.
Parameters
----------
conspecificall_paths : dictionary with the following keys:
call_routes
R_incoming
theta_emission
theta_reception
Keyword Arguments
----------------
call_directionality : function with one input. The call_direcitonality
function accepts one input theta_emission, which
is the relative angle of emission with reference to the
on-axis heading angle of the bat.
hearing_directionality : function with one input. The hearing_directionality
function acccepts one input theta_reception,
which is the relative angle of sound reception
with reference to the on-axis heading angle of
the bat.
source_level : dictionary with two keys:
dBSPL : float. the sound pressure level in dB SPL relative to 20 microPascals
ref_distance : float >0. the reference distance at which the bat's source
level is specified at.
implement_shadowing : Boolean. If acoustic shadowing is implemented or not.
Returns
-------
conspecific_calls : pd.DataFrame.
A 'sound' df with received level, angle of arrival
and other related attributes of the sound :
start | stop | theta | level |route|
'''
call_directionality = kwargs['call_directionality']
hearing_directionality = kwargs['hearing_directionality']
source_level = kwargs['source_level']
num_calls = len(conspecificcall_paths['call_routes'])
conspecific_calls = pd.DataFrame(data=[], index=xrange(num_calls),
columns=['start','stop','theta', 'level',
'route'])
for call_id, each_callpath in enumerate(conspecificcall_paths['call_routes']):
conspecific_calls['route'][call_id] = each_callpath
# get the reception angle and the received SPL
conspecific_calls['theta'][call_id] = conspecificcall_paths['theta_reception'][call_id]
# outgoing SPL at emitter after call directionality
outgoing_SPL = source_level['dBSPL'] + call_directionality(conspecificcall_paths['theta_emission'][call_id])
kwargs['emitted_source_level'] = {'dBSPL':outgoing_SPL,
'ref_distance':source_level['ref_distance']}
kwargs['R'] = spl.distance.euclidean(kwargs['bats_xy'][each_callpath[0],:],
kwargs['bats_xy'][each_callpath[1],:])
# SPL at focal bat after hearing directionality
incoming_SPL = calculate_acoustic_shadowing(each_callpath, **kwargs)
incoming_SPL += hearing_directionality(conspecificcall_paths['theta_reception'][call_id])
conspecific_calls['level'][call_id] = incoming_SPL
return(conspecific_calls)
def calculate_acoustic_shadowing(soundpath, **kwargs):
'''
'''
start, end = soundpath
other_inds = list(set(range(kwargs['bats_xy'].shape[0])) - set([start,end]))
total_shadow_dB = soundprop_w_acoustic_shadowing(kwargs['bats_xy'][start,:],
kwargs['bats_xy'][end,:],
kwargs['bats_xy'][other_inds,:], **kwargs)
return(total_shadow_dB)
def calculate_echoreceived_levels(echopaths,
**kwargs):
'''Calculates the final sound pressure levels at the focal receiver bat given
the geometry of the problem for primary and secondary echoes
Parameters
----------
echopaths : dictionary with geometry related entries.
See calculate_echopaths for details.
reflection_function : pd.DataFrame with the following columns:
incoming_theta : float. Angle at which the incoming sound arrives at. This
angle is with relation to the heading direciton of the target bat.
outgoing_theta : float. Angle at which the outgoing sound reflects at. This
angle is with relation to the heading direciton of the target bat.
reflection_strength : float. The ratio of incoming and outgoing sound pressure levels in dB (20log10)
see get_reflection_strength for Details.
call_directionality : function with one input. The call_direcitonality
function accepts one input theta_emission, which
is the relative angle of emission with reference to the
on-axis heading angle of the bat.
hearing_directionality : function with one input. The hearing_directionality
function acccepts one input theta_reception,
which is the relative angle of sound reception
with reference to the on-axis heading angle of
the bat.
source_level : dictionary with two keys:
dBSPL : float. the sound pressure level in dB SPL relative to 20 microPascals
ref_distance : float >0. the reference distance at which the bat's source
level is specified at.
Returns
-------
echoes : pd.DataFrame.
A 'sound' df with received level, angle of arrival
and other related attributes of the sound :
start | stop | theta | level | route|
'''
num_echoes = len(echopaths['sound_routes'])
reflection_function = kwargs['reflection_function']
hearing_directionality = kwargs['hearing_directionality']
call_directionality = kwargs['call_directionality']
source_level = kwargs['source_level']
echoes= pd.DataFrame(data={'theta':echopaths['theta_reception'],
'R_incoming':echopaths['R_incoming'],
'R_outgoing' : echopaths['R_outgoing'],
'theta_emission': echopaths['theta_emission'],
'theta_incoming' : echopaths['theta_incoming'],
'theta_outgoing' : echopaths['theta_outgoing'],
'route' : echopaths['sound_routes'],
'sourcelevel_ref_distance' : source_level['ref_distance']
})
echoes['emitted_SPL'] = np.tile(np.nan, num_echoes)
echoes['incoming_SPL'] = np.tile(np.nan, num_echoes)
# the emitted SPL and teh SPL near the target bat before reflection.
call_directionality_factor = np.apply_along_axis(call_directionality,0, np.array(echoes['theta_emission']))
# source level emitted at the reference distance, reduced due to call directionality
echoes['emitted_SPL'] = source_level['dBSPL'] + call_directionality_factor
# calculate spherical spreading
echoes['incoming_SPL'] = echoes.apply(calc_incomingSPL_by_row, axis=1, **kwargs)
# the reflection strength at each set of incoming and outgoing angles
echoes['reflection_strength'] = get_reflection_strength(reflection_function,
echoes['theta_incoming'],
echoes['theta_outgoing'])
echoes['level'] = echoes.apply(calcreceivedSPL_by_row, axis=1, **kwargs)
hearing_directionality_factor = np.apply_along_axis(hearing_directionality,0, np.array(echoes['theta']))
echoes['level'] += hearing_directionality_factor
return(echoes)
def calc_incomingSPL_by_row(row_df, **kwargs):
'''
'''
# the SPL is calculated till the ref distance only!
#emitter, target, receiver = row_df['route']
kwargs['emitted_source_level'] = {'dBSPL':row_df['emitted_SPL'],
'ref_distance':row_df['sourcelevel_ref_distance']}
kwargs['R'] = row_df['R_incoming']
#RL = calculate_acoustic_shadowing((emitter, target), **kwargs)
RL = calculate_acoustic_shadowing((row_df['route'][0], row_df['route'][1]),
**kwargs)
return(RL)
def calcreceivedSPL_by_row(row_df, **kwargs):
'''
'''
kwargs['emitted_source_level'] = {'dBSPL':row_df['incoming_SPL']+row_df['reflection_strength'] ,
'ref_distance': row_df['sourcelevel_ref_distance']}
#emitter, target, receiver = row_df['route']
kwargs['R'] = row_df['R_outgoing']
#RL = calculate_acoustic_shadowing((target, receiver), **kwargs)
RL = calculate_acoustic_shadowing((row_df['route'][1], row_df['route'][2]), **kwargs)
return(RL)
def get_reflection_strength(reflection_function,
theta_ins,
theta_outs,
max_theta_error = 50):
'''The reflection_function is a mapping between the reflection strength
and the input + output angles of the sound.
In simulatoins, the incoming and outgoing angles will likely vary continuously.
However, experimental measurements of course cannot handle all possible values.
This function tries to choose the angle pair which matches the
unmeasured theta incoming and outgoing to best possible extent.
Parameters
----------
reflection_function : pd.DataFrame
with the following columns:
ref_distance : float>0. Distance at which the reflection strength is calculated in metres.
theta_incoming : float. Angle at which the incoming sound arrives at. This
angle is with relation to the heading direciton of the target bat.
theta_outgoing : float. Angle at which the outgoing sound reflects at. This
angle is with relation to the heading direciton of the target bat.
reflection_strength : float. The ratio of incoming and outgoing sound pressure levels in dB (20log10)
For example, one row entry could be :
ref_distance incoming_theta outgoing_theta reflection_strength
0.1 30 90 -60
The above example refers to a situation where sound
arrives at the object at 30 degrees and its reflection
is received at 90 degrees. The outgoing sound id 60 dB fainter than the
incoming sound when measured at a 10 cm radius around the centre
of the target object.
theta_ins : 1 D array-like
Angle of incidence in degrees. -ve angles are when the sound
arrives onto the left side of the bat
theta_outs : 1 D array-like
Angle of exit in degrees.
max_theta_error : float>0.
The maximum difference that can be there between either
theta_in,theta_out and the incoming/outgoing angles
in the reflection function. *REPHRASE THIS PART*
Returns
-------
reflection_strengths : 1 D array-like
The ratio of incoming and outgoing sound pressure levels in dB
Example Usage :
get_reflection_strength(reflection_funciton, 90, 0) --> -50
'''
reflection_strengths = []
theta_cols = np.array(reflection_function[['theta_incoming','theta_outgoing']])
# get best fit angle pair:
for theta_in, theta_out in zip(theta_ins, theta_outs):
theta_inout = np.array([theta_in, theta_out])
# theta_diffs = np.apply_along_axis(spl.distance.euclidean, 1,
# theta_cols,
# theta_inout)
theta_diffs = get_angle_pair_distances(theta_inout, theta_cols)
abs_theta_diffs = abs(theta_diffs)
if np.min(abs_theta_diffs) > max_theta_error:
print(theta_in, theta_out, np.min(abs(theta_diffs)))
raise ValueError('Reflection function is coarser than ' + str(max_theta_error)+'..aborting calculation' )
else:
best_index = np.argmin(abs_theta_diffs)
best_reflection_strength = reflection_function['reflection_strength'][best_index]
reflection_strengths.append(best_reflection_strength)
return(np.array(reflection_strengths))
def get_angle_pair_distances(input_pair, all_pairs):
'''Gets the distance of input_pair to all_pairs
Parameters
----------
input_pair : 1D array-like
all_pairs : npairs x 2 np.array
'''
diffs = input_pair - all_pairs
angle_distance = np.sqrt(np.sum(np.square(diffs),1))
return(angle_distance)
def calculate_conspecificcall_paths(**kwargs):
'''Given the positions and orientations of all bat, the output is
the distances and angles relevant to the geometry of conspecific call
propagation.
The straight line distances are calculated without assuming any occlusion
by conspecifics.
Keyword Arguments
----------------
focal_bat :
bats_xy
bats_orientations
Returns
-------
conspecificall_paths : dictionary.
with the following keys
call_routes
R_incoming
theta_emission
theta_reception
'''
bats_xy = kwargs['bats_xy']
bats_orientations = kwargs['bats_orientations']
distance_matrix = spl.distance_matrix(bats_xy,bats_xy)
focal_bat = find_rowindex(bats_xy, kwargs['focal_bat'])
# make all emitter-target and target-receiver paths using the row indices as
# an identifier
emitters = set(range(bats_xy.shape[0])) - set([focal_bat])
conspecificcall_routes = []
# generate all possible conspecific call routes
for each_emitter in emitters:
emitter_focal = (each_emitter, focal_bat)
conspecificcall_routes.append(emitter_focal)
conspecificall_paths = {}
conspecificall_paths['call_routes'] = tuple(conspecificcall_routes)
conspecificall_paths['R_incoming'] = get_conspecificcall_Rin(distance_matrix, conspecificcall_routes)
conspecificall_paths['theta_emission'], conspecificall_paths['theta_reception'] = calc_conspecificcall_thetas(bats_xy,
bats_orientations,
conspecificcall_routes)
return(conspecificall_paths)
def calculate_echopaths(echo_type, **kwargs):
'''Given the positions and orientations of all bats, the output is the
distances, angles and and routes for primary and secondary echo routes
required to calculate the received levels at the focal bat.
For Nbats the total number of secondary echoes a focal bat will hear is:
N_emitters x N_targets --> (Nbats-1) x (Nbats-2)
Parameters
----------
echo_type : string. Either 'primary_echo' or 'secondary_echo'
Keyword Arguments
----------------
focal_bat : 1x2 np.array.
xy position of focal bat. This is the end point of all the 2ndary
paths that are calculated
bats_xy : Nbats x 2 np.array.
xy positions of bats
bats_orientations : np.array. heading directions of all bats. This direction is with reference to
a global zero which is set at 3 o'clock.
Returns
-------
echo_paths : dictionary with following 7 keys - each with
sound_routes|theta_emission|R_incoming|theta_incoming|theta_outgoing|R_outgoing|theta_reception
All theta values are in degrees.
theta_emission, theta_incoming, theta_outgoing and theta_reception are calculated
with the heading direction of the bat as the zero.
R_incoming and R_outgoing are in metres. R_incoming is the distance between
the emitting and target bat. R_outgoing is the distance between the
target and receiving bat.
'''
bats_xy = kwargs['bats_xy']
bats_orientations = kwargs['bats_orientations']
focal_bat = find_rowindex(bats_xy, kwargs['focal_bat'])
echo_routes = make_echo_paths(echo_type, focal_bat, bats_xy)
distance_matrix = spl.distance_matrix(bats_xy, bats_xy)
echo_paths = {}
echo_paths['R_incoming'], echo_paths['R_outgoing'] = calc_R_in_out(distance_matrix,
echo_routes)
echo_paths['theta_incoming'], echo_paths['theta_outgoing'] = calc_echo_thetas(bats_xy,
bats_orientations,
echo_routes,
'incoming_outgoing')
echo_paths['theta_emission'], echo_paths['theta_reception'] = calc_echo_thetas(bats_xy,
bats_orientations,
echo_routes,
'emission_reception')
echo_paths['sound_routes'] = tuple(echo_routes)
return(echo_paths)
def make_echo_paths(echo_type, focal_bat, bats_xy):
echo_paths= {'primary_echoes' : paths_1aryechoes,
'secondary_echoes': paths_2daryechoes}
echo_routes = echo_paths[echo_type](focal_bat, bats_xy)
return(echo_routes)
def paths_2daryechoes(focal_bat, bats_xy):
# make all emitter-target and target-receiver paths using the row indices as
# an identifier
emitters = set(range(bats_xy.shape[0])) - set([focal_bat])
targets = set(range(bats_xy.shape[0])) - set([focal_bat])
echo_routes = []
for an_emitter in emitters:
for a_target in targets:
if a_target != an_emitter:
emitter_target_focal = (an_emitter, a_target, focal_bat)
echo_routes.append(emitter_target_focal)
return(echo_routes)
def paths_1aryechoes(focal_bat, bats_xy):
# make all emitter-target and target-receiver paths using the row indices as
# an identifier
targets = set(range(bats_xy.shape[0])) - set([focal_bat])
echo_routes = []
for a_target in targets:
emitter_target_focal = (focal_bat, a_target, focal_bat)
echo_routes.append(emitter_target_focal)
return(echo_routes)
def calc_R_in_out(distance_matrix, sound_routes):
'''Calculates the direct path length that a sound needs to travel between
an emitter bat to target bat (R_in) and target bat to focal receiver bat (R_out)
Parameters
----------
distance_matrix : Nbats x Nbats np.array. Distance between each of the bats in metres.
sound_routes : list with (Nbats-1)x(Nbats-2) tuples of 3 entries. Each tuple refers to the path
of a call emission.
Eg. (20, 10, 5) refers to a sound emitted by bat 20 onto bat 10 and then
reflecting and reaching bat 5.
Returns
-------
R_in : tuple with (Nbats-1)x(Nbats-2) floats. Distances of sound on its inbound journey from emitter to target
R_in : tuple with (Nbats-1)x(Nbats-2) floats. Distances of sound on its outbound journey from target to receiver
'''
R_in = [distance_matrix[each_route[0],each_route[1]] for each_route in sound_routes]
R_out = [distance_matrix[each_route[1],each_route[2]] for each_route in sound_routes]
return(tuple(R_in), tuple(R_out))
def get_conspecificcall_Rin(distance_matrix, conspecificcall_routes):
'''calculate one-way radial distane between an emitter and focal bat.
'''
R_emitter_focal = []
for route in conspecificcall_routes:
emitter, focal = route
R_emitter_focal.append(distance_matrix[emitter,focal])
return(tuple(R_emitter_focal))
def calc_conspecificcall_thetas(bats_xy, bat_orientations, conspecificcall_routes):
'''Calculates the relative angle of conspecific call emission and reception.
Parameters
----------
bats_xy
bat_orientations
conspecificcall_routes
Returns
-------
theta_emission : tuple with Nbats-1 abs(floats) <= 180 . Relative angle of call emission with reference to the
heading direction of the calling bat. -ve angles are to the left and +ve are to the right
theta_reception : tuple with Nbats-1 abs(floats) <= 180 . RElative angle of call reception with reference to the
heading direction of the focal bat. -ve angles are to the left and +ve are to the right
'''
theta_emission = []
theta_reception = []
for each_callroute in conspecificcall_routes:
emitter, focal = each_callroute
theta_emitter = calculate_angleofarrival(bats_xy[focal], bats_xy[emitter], bat_orientations[emitter])
theta_emission.append(theta_emitter)
theta_receiver = calculate_angleofarrival(bats_xy[emitter], bats_xy[focal], bat_orientations[focal])
theta_reception.append(theta_receiver)
return(tuple(theta_emission), tuple(theta_reception))
def calc_echo_thetas(bats_xy, bat_orientations, sound_routes, which_angles):
'''Calculates relative angles of sound with reference to the heading direction
of the bats concerned.
The switch 'which_angles' decides if the theta_ingoing and theta_outgoing
or theta_emission and theta_reception pairs are calculated.
Parameters
----------
bats_xy : Nbats x 2 np.array. XY positions of bats.
bat_orientations : Nbats x 1 np.array. Heading directions of all bats in degrees.
Zero degrees is 3 o'clock and increases in anti clockwise manner
sound_routes : list w (Nbats-1)x(Nbats-2) tuples. Each tuple has the index number of
the emitter, target and focal receiver bat.
which_angles : str. Switch which decides which pair of angles are calculated.
If which_angles is 'emission_reception' then :
Relevant to the overall emission and reception angles of echoes
theta_towardstarget : the relative angle of emission from emitting bat to target bat
AND
theta_fromtarget : the relative angle of reception with reference to the heading
direction of the focal bat
If which_angles is 'incoming_outgoing' :
Relevant to the overall emission and reception angles of echoes
theta_towardstarget : relative angle of arrival of the emitted call for the
target bat
AND
theta_fromtarget : the relative angle of the reflected sound wrt to the
heading direction of the target bat
Returns
-------
theta_towardstarget : tuple with Nbats-1 x Nbats-2 floats. Angle of incoming sound with reference to heading direction
of target bat or emitting bat (see which_angles). Heading direction is zero and it increases off-axis till +/- 180 degrees.
theta_fromtarget : tuple with Nbats-1 x Nbats-2 floats. Angle of outgoing sound with reference to heading direction
of target bat or focal bat (see which_angles). Heading direction is zero and it increases off-axis till +/- 180 degrees.
'''
# towardstarget refers to the emission angle OR to the incoming angle
theta_towardstarget = []
theta_fromtarget = []
for route in sound_routes:
emitter, target, focal = route
theta_out = casewise_thetaout[which_angles](bats_xy,
bat_orientations, emitter, target, focal, theta_towardstarget)
theta_fromtarget.append(theta_out)
return(tuple(theta_towardstarget), tuple(theta_fromtarget))
def incoming_outgoing(bats_xy, bat_orientations, emitter, target, focal, theta_towardstarget):
theta_in = calculate_angleofarrival(bats_xy[emitter], bats_xy[target], bat_orientations[target])
theta_towardstarget.append(theta_in)
theta_out = calculate_angleofarrival(bats_xy[focal], bats_xy[target], bat_orientations[target])
return(theta_out)
def emission_reception(bats_xy, bat_orientations, emitter, target, focal, theta_towardstarget):
theta_in = calculate_angleofarrival(bats_xy[target], bats_xy[emitter], bat_orientations[emitter])
theta_towardstarget.append(theta_in)
theta_out = calculate_angleofarrival(bats_xy[target], bats_xy[focal], bat_orientations[focal])
return(theta_out)
casewise_thetaout = {'incoming_outgoing' : incoming_outgoing,
'emission_reception' : emission_reception }
def combine_sounds(sounddf_list):
'''Combine 2>= sound dfs into one df.
EAch sound df is expected to at least have the following columns:
start : start time of
stop :
level :
theta :
'''
combined_sounds = pd.concat(sounddf_list, ignore_index=True, sort=False).dropna(axis=0,thresh=3)
return(combined_sounds)
def place_bats_inspace(**kwargs):
''' Assign bats their positions and heading directions in 2D
The positions of the bats are placed randomly so that
they are at least a fixed distance away from their nearest neighbours.
This is achieved through Poisson disk sampling.
Keyword Arguments
----------------
Nbats : integer >0. Number of bats in the group
min_spacing : float> 0. Minimum distance between neighbouring bats in metres.
heading_variation : float >0. Range of heading directions in degrees.
eg. if heading_variation = 10,
then all bats will have a uniform prob. of
having headings between [90-10, 90+10] degrees.
noncentral_bat : tuple with 2 entries. See choose_a_noncentral_bat
Returns :
bat_xy : list with [Nbats x 2 np.array, focal bat XY].
XY positions of nearby and focal bats
headings : 1x Nbats np.array.
Heading direction of bats in degrees.
'''
min_heading, max_heading = 90 - kwargs['heading_variation'], 90 + kwargs['heading_variation']
headings = np.random.choice(np.arange(min_heading, max_heading+1),
kwargs['Nbats'])
nearby, focal = generate_surroundpoints_w_poissondisksampling(kwargs['Nbats'],
kwargs['min_spacing'],
**kwargs)
return([nearby, focal], headings)
def run_CPN(**kwargs):
''' Run one iteration of the spatially explicit CPN, and calculate the
number of echoes heard.
This version of the simulation places bats in space, calculates the
received conspecific call levels and the 2dary echoes that may arrive at a
focal bat.
TODO
--------
6) make switch to choose which is the focal bat
Keyword Arguments
----------------
simtime_resolution : float >0
The time resolution of the simulations in seconds.
v_sound : float>0
speed of sound in metres/second.
Nbats : integer
Number of bats in the group.
min_spacing : float>0
Minimum distance between one bat and its closest neighbour
heading_variation : float>0
Variation in heading direction of each bat in degrees.
The reference direction is 90 degrees (3 o'clock is 0 degrees), and
all bat headings are within +/- heading_variation of 90 degrees.
This is also assumed to be the direction in which the bat is calling and hearing at.
Example : a heading variation of 10 degrees will mean that all bats in the group
are facing between 100-80 degrees with uniform probability.
interpulse_interval : float>0
Duration of the interpulse interval in seconds.
echocall_duration : float>0
Duration of the echo and call in seconds.
source_level : dictionary
with the following keys and entries
'dB_SPL' : float. Sound pressure level in dB with 20microPascals as reference
'ref_distance' : float. Reference distance in metres.
Please check that the reference distance of the source
level measurement is the same as the target strength
reference distance in the reflection function.
call_directionality : function
Relates the decrease in source level in dB with emission angle
The on-axis angle is set to 0 here, and the angle right behind the bat is 180 degrees.
hearing_directionality : function. Relates the change in received level in dB with sound arrival angle
The heading angle is set to 0 here, and the angle right behind the bat is 180 degrees.
reflection_function : function.
Describes the reflection characteristics of echoes bouncing off
reception and position of emission are different.
N_echoes : integer >0.
The number of target echoes to be placed in the interpulse interval
echo_properties : pd.DatFrame.
A 'sound'df -- see previous documentation
temporal_masking_thresholds : tuple with three 1D np.arrays.
The tuple contains the following temporal masking
thresholds:
(forward_masking, simultaneous_masking, backward_masking)
Each 1 D np.array has the values of echo-masker dB ratio
at which bats can hear the echo.
The forward masking line is 'flipped' in that the
last array index refers to one timestep delay between
the start of the echo and the maskers.
The simultaneous_masking is a single value with
the echo-masker ratio when overlapped.
The backward_masking line has the 1st timestep
starting at one timestep delay between the end of the
echo and the maskers.
spatial_release_fn : Nangular_separations x 2 np.array.
0th column has
the angular separation between echo and masker sound.
Column 1 has the dB release due to the angular separation.
acoustic_shadowing_model : statsmodel object.
A statistical model that predicts the amount of
acoustic shadowing given the number of obstacles present
noncentral_bat : tuple with 2 entries. See choose_a_noncentral_bat
Returns
-------
num_echoes_heard : int.
Number of echoes heard
sim_output : list with 3 objects in the following index order.
0 : echo_ids . 1d array like. binary array showing whether echo was heard
or not.
1 : sounds_in_ipi - dictionary with the secondary echoes, target echoes
and conspecific calls as pd.DataFrames
2 : group_geometry - dictionary describing the geometry of the 2D
bat group. with the following
'''
assert kwargs['Nbats'] >= 1, 'The cocktail party nightmare has to have >= 1 bats! '
# place Nbats out and choose the centremost bat as the focal bat
bat_positions, bats_orientations = place_bats_inspace(**kwargs)
nearby_bats, focal_bat = bat_positions
bats_xy = np.row_stack((focal_bat, nearby_bats))
kwargs['bats_xy'] = bats_xy
kwargs['bats_orientations'] = bats_orientations
kwargs['focal_bat'] = focal_bat
# calculate the received levels and angles of arrivals of the sounds
conspecific_calls = propagate_sounds('conspecific_calls', **kwargs)
secondary_echoes = propagate_sounds('secondary_echoes', **kwargs)
# assign random times of arrival to the sounds :
assign_random_arrival_times(conspecific_calls, **kwargs)
assign_random_arrival_times(secondary_echoes, **kwargs)
# place the conspecific calls and 2dary echoes in the IPI
maskers = combine_sounds([conspecific_calls, secondary_echoes])
# place target echoes in the IPI and check how many of them are heard
target_echoes = propagate_sounds('primary_echoes', **kwargs)
assign_real_arrival_times(target_echoes, **kwargs)
num_echoes_heard, echo_ids = calculate_num_heardechoes(target_echoes, maskers,
**kwargs)
group_geometry = {'positions':bats_xy,
'orientations':bats_orientations }
return(num_echoes_heard,
[echo_ids,
{'2dary_echoes':secondary_echoes,
'conspecific_calls':conspecific_calls,
'target_echoes':target_echoes},
group_geometry])
class EchoesOutOfIPI(Exception):
pass
|
[
"numpy.abs",
"numpy.sum",
"numpy.argmin",
"scipy.spatial.distance_matrix",
"numpy.around",
"numpy.sin",
"numpy.arange",
"numpy.tile",
"numpy.float64",
"numpy.random.random_integers",
"sys.path.append",
"pandas.DataFrame",
"scipy.spatial.distance.euclidean",
"numpy.cumsum",
"numpy.apply_along_axis",
"numpy.append",
"numpy.max",
"numpy.random.choice",
"numpy.int64",
"numpy.linalg.det",
"numpy.intersect1d",
"numpy.bincount",
"numpy.log10",
"pandas.concat",
"bridson.poisson_disc_samples",
"numpy.ceil",
"detailed_sound_propagation.soundprop_w_acoustic_shadowing",
"numpy.asarray",
"numpy.square",
"numpy.min",
"numpy.cos",
"numpy.argwhere",
"numpy.dot",
"numpy.delete",
"numpy.all",
"numpy.concatenate",
"numpy.deg2rad",
"scipy.misc.comb",
"numpy.zeros",
"numpy.any",
"numpy.where",
"numpy.array",
"numpy.row_stack",
"numpy.column_stack",
"numpy.sqrt"
] |
[((1366, 1396), 'sys.path.append', 'sys.path.append', (['"""../bridson/"""'], {}), "('../bridson/')\n", (1381, 1396), False, 'import sys\n'), ((1397, 1429), 'sys.path.append', 'sys.path.append', (['"""../acoustics/"""'], {}), "('../acoustics/')\n", (1412, 1429), False, 'import sys\n'), ((4165, 4222), 'scipy.spatial.distance_matrix', 'spl.distance_matrix', (["kwargs['bats_xy']", "kwargs['bats_xy']"], {}), "(kwargs['bats_xy'], kwargs['bats_xy'])\n", (4184, 4222), True, 'import scipy.spatial as spl\n'), ((4584, 4645), 'numpy.float64', 'np.float64', (["(echo_arrivaltimes / kwargs['interpulse_interval'])"], {}), "(echo_arrivaltimes / kwargs['interpulse_interval'])\n", (4594, 4645), True, 'import numpy as np\n'), ((4866, 4935), 'numpy.around', 'np.around', (["(kwargs['echocall_duration'] / kwargs['simtime_resolution'])"], {}), "(kwargs['echocall_duration'] / kwargs['simtime_resolution'])\n", (4875, 4935), True, 'import numpy as np\n'), ((4959, 5010), 'numpy.int64', 'np.int64', (['(echo_start_timesteps + echo_timesteps - 1)'], {}), '(echo_start_timesteps + echo_timesteps - 1)\n', (4967, 5010), True, 'import numpy as np\n'), ((5758, 5795), 'numpy.any', 'np.any', (["(sound_df['stop'] > ipi_length)"], {}), "(sound_df['stop'] > ipi_length)\n", (5764, 5795), True, 'import numpy as np\n'), ((7140, 7182), 'numpy.random.choice', 'np.random.choice', (['actual_timeline', 'Nsounds'], {}), '(actual_timeline, Nsounds)\n', (7156, 7182), True, 'import numpy as np\n'), ((7444, 7488), 'numpy.column_stack', 'np.column_stack', (['(sound_starts, sound_stops)'], {}), '((sound_starts, sound_stops))\n', (7459, 7488), True, 'import numpy as np\n'), ((8896, 8918), 'numpy.cumsum', 'np.cumsum', (['heard_probs'], {}), '(heard_probs)\n', (8905, 8918), True, 'import numpy as np\n'), ((10034, 10053), 'numpy.zeros', 'np.zeros', (['(rows, 1)'], {}), '((rows, 1))\n', (10042, 10053), True, 'import numpy as np\n'), ((14390, 14412), 'numpy.asarray', 'np.asarray', (['start_stop'], {}), '(start_stop)\n', (14400, 14412), True, 'import numpy as np\n'), ((28048, 28079), 'numpy.arange', 'np.arange', (['num_timesteps_in_ipi'], {}), '(num_timesteps_in_ipi)\n', (28057, 28079), True, 'import numpy as np\n'), ((28099, 28137), 'numpy.arange', 'np.arange', (['start_index', '(stop_index + 1)'], {}), '(start_index, stop_index + 1)\n', (28108, 28137), True, 'import numpy as np\n'), ((28165, 28208), 'numpy.intersect1d', 'np.intersect1d', (['echo_indices', 'all_timesteps'], {}), '(echo_indices, all_timesteps)\n', (28179, 28208), True, 'import numpy as np\n'), ((30979, 31079), 'numpy.apply_along_axis', 'np.apply_along_axis', (['calc_spatial_release', '(0)', 'angular_separations', "kwargs['spatial_release_fn']"], {}), "(calc_spatial_release, 0, angular_separations, kwargs[\n 'spatial_release_fn'])\n", (30998, 31079), True, 'import numpy as np\n'), ((34266, 34298), 'numpy.abs', 'np.abs', (['(echo_angle - sound_angle)'], {}), '(echo_angle - sound_angle)\n', (34272, 34298), True, 'import numpy as np\n'), ((39768, 39789), 'numpy.zeros', 'np.zeros', (['(Ntrials + 1)'], {}), '(Ntrials + 1)\n', (39776, 39789), True, 'import numpy as np\n'), ((39804, 39826), 'numpy.arange', 'np.arange', (['(Ntrials + 1)'], {}), '(Ntrials + 1)\n', (39813, 39826), True, 'import numpy as np\n'), ((42972, 42988), 'numpy.arange', 'np.arange', (['(1)', '(11)'], {}), '(1, 11)\n', (42981, 42988), True, 'import numpy as np\n'), ((43030, 43054), 'numpy.cumsum', 'np.cumsum', (['bats_per_ring'], {}), '(bats_per_ring)\n', (43039, 43054), True, 'import numpy as np\n'), ((43411, 43455), 'numpy.append', 'np.append', (['inner_numbats', 'bats_outermostring'], {}), '(inner_numbats, bats_outermostring)\n', (43420, 43455), True, 'import numpy as np\n'), ((43476, 43504), 'numpy.arange', 'np.arange', (['(1)', '(outer_ring + 1)'], {}), '(1, outer_ring + 1)\n', (43485, 43504), True, 'import numpy as np\n'), ((47551, 47598), 'numpy.row_stack', 'np.row_stack', (['(centremost_point, nearby_points)'], {}), '((centremost_point, nearby_points))\n', (47563, 47598), True, 'import numpy as np\n'), ((47769, 47798), 'numpy.max', 'np.max', (['distances_from_centre'], {}), '(distances_from_centre)\n', (47775, 47798), True, 'import numpy as np\n'), ((48007, 48059), 'numpy.row_stack', 'np.row_stack', (['(target_xy, points_relative_to_centre)'], {}), '((target_xy, points_relative_to_centre))\n', (48019, 48059), True, 'import numpy as np\n'), ((48234, 48263), 'numpy.argmin', 'np.argmin', (['distance_to_target'], {}), '(distance_to_target)\n', (48243, 48263), True, 'import numpy as np\n'), ((48346, 48394), 'numpy.delete', 'np.delete', (['nearby_points', 'closest_point_index', '(0)'], {}), '(nearby_points, closest_point_index, 0)\n', (48355, 48394), True, 'import numpy as np\n'), ((48426, 48480), 'numpy.row_stack', 'np.row_stack', (['(centremost_point, all_points_not_focal)'], {}), '((centremost_point, all_points_not_focal))\n', (48438, 48480), True, 'import numpy as np\n'), ((50024, 50100), 'numpy.apply_along_axis', 'np.apply_along_axis', (['calculate_radialdistance', '(1)', 'target_points', 'focal_point'], {}), '(calculate_radialdistance, 1, target_points, focal_point)\n', (50043, 50100), True, 'import numpy as np\n'), ((50208, 50284), 'numpy.apply_along_axis', 'np.apply_along_axis', (['calculate_angleofarrival', '(1)', 'target_points', 'focal_point'], {}), '(calculate_angleofarrival, 1, target_points, focal_point)\n', (50227, 50284), True, 'import numpy as np\n'), ((50757, 50804), 'scipy.spatial.distance.euclidean', 'spl.distance.euclidean', (['sourcepoint', 'focalpoint'], {}), '(sourcepoint, focalpoint)\n', (50779, 50804), True, 'import scipy.spatial as spl\n'), ((52353, 52375), 'numpy.around', 'np.around', (['relangle', '(4)'], {}), '(relangle, 4)\n', (52362, 52375), True, 'import numpy as np\n'), ((52896, 52926), 'numpy.sum', 'np.sum', (['values_sqerror'], {'axis': '(1)'}), '(values_sqerror, axis=1)\n', (52902, 52926), True, 'import numpy as np\n'), ((54091, 54128), 'numpy.apply_along_axis', 'np.apply_along_axis', (['np.mean', '(0)', 'data'], {}), '(np.mean, 0, data)\n', (54110, 54128), True, 'import numpy as np\n'), ((54519, 54582), 'numpy.apply_along_axis', 'np.apply_along_axis', (['calc_distance', '(1)', 'all_points', 'target_point'], {}), '(calc_distance, 1, all_points, target_point)\n', (54538, 54582), True, 'import numpy as np\n'), ((54603, 54626), 'numpy.argmin', 'np.argmin', (['distance2tgt'], {}), '(distance2tgt)\n', (54612, 54626), True, 'import numpy as np\n'), ((54745, 54783), 'scipy.spatial.distance.euclidean', 'spl.distance.euclidean', (['point1', 'point2'], {}), '(point1, point2)\n', (54767, 54783), True, 'import scipy.spatial as spl\n'), ((55884, 55926), 'numpy.delete', 'np.delete', (['all_points', 'focalpoint_index', '(0)'], {}), '(all_points, focalpoint_index, 0)\n', (55893, 55926), True, 'import numpy as np\n'), ((55998, 56061), 'numpy.apply_along_axis', 'np.apply_along_axis', (['calc_distance', '(1)', 'validpoints', 'focal_point'], {}), '(calc_distance, 1, validpoints, focal_point)\n', (56017, 56061), True, 'import numpy as np\n'), ((65608, 65743), 'detailed_sound_propagation.soundprop_w_acoustic_shadowing', 'soundprop_w_acoustic_shadowing', (["kwargs['bats_xy'][start, :]", "kwargs['bats_xy'][end, :]", "kwargs['bats_xy'][other_inds, :]"], {}), "(kwargs['bats_xy'][start, :], kwargs[\n 'bats_xy'][end, :], kwargs['bats_xy'][other_inds, :], **kwargs)\n", (65638, 65743), False, 'from detailed_sound_propagation import soundprop_w_acoustic_shadowing, calc_RL\n'), ((68474, 68866), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': "{'theta': echopaths['theta_reception'], 'R_incoming': echopaths[\n 'R_incoming'], 'R_outgoing': echopaths['R_outgoing'], 'theta_emission':\n echopaths['theta_emission'], 'theta_incoming': echopaths[\n 'theta_incoming'], 'theta_outgoing': echopaths['theta_outgoing'],\n 'route': echopaths['sound_routes'], 'sourcelevel_ref_distance':\n source_level['ref_distance']}"}), "(data={'theta': echopaths['theta_reception'], 'R_incoming':\n echopaths['R_incoming'], 'R_outgoing': echopaths['R_outgoing'],\n 'theta_emission': echopaths['theta_emission'], 'theta_incoming':\n echopaths['theta_incoming'], 'theta_outgoing': echopaths[\n 'theta_outgoing'], 'route': echopaths['sound_routes'],\n 'sourcelevel_ref_distance': source_level['ref_distance']})\n", (68486, 68866), True, 'import pandas as pd\n'), ((69130, 69157), 'numpy.tile', 'np.tile', (['np.nan', 'num_echoes'], {}), '(np.nan, num_echoes)\n', (69137, 69157), True, 'import numpy as np\n'), ((69187, 69214), 'numpy.tile', 'np.tile', (['np.nan', 'num_echoes'], {}), '(np.nan, num_echoes)\n', (69194, 69214), True, 'import numpy as np\n'), ((74250, 74317), 'numpy.array', 'np.array', (["reflection_function[['theta_incoming', 'theta_outgoing']]"], {}), "(reflection_function[['theta_incoming', 'theta_outgoing']])\n", (74258, 74317), True, 'import numpy as np\n'), ((75235, 75265), 'numpy.array', 'np.array', (['reflection_strengths'], {}), '(reflection_strengths)\n', (75243, 75265), True, 'import numpy as np\n'), ((76451, 76488), 'scipy.spatial.distance_matrix', 'spl.distance_matrix', (['bats_xy', 'bats_xy'], {}), '(bats_xy, bats_xy)\n', (76470, 76488), True, 'import scipy.spatial as spl\n'), ((79488, 79525), 'scipy.spatial.distance_matrix', 'spl.distance_matrix', (['bats_xy', 'bats_xy'], {}), '(bats_xy, bats_xy)\n', (79507, 79525), True, 'import scipy.spatial as spl\n'), ((96522, 96560), 'numpy.row_stack', 'np.row_stack', (['(focal_bat, nearby_bats)'], {}), '((focal_bat, nearby_bats))\n', (96534, 96560), True, 'import numpy as np\n'), ((2364, 2433), 'numpy.around', 'np.around', (["(kwargs['echocall_duration'] / kwargs['simtime_resolution'])"], {}), "(kwargs['echocall_duration'] / kwargs['simtime_resolution'])\n", (2373, 2433), True, 'import numpy as np\n'), ((3034, 3103), 'numpy.ceil', 'np.ceil', (["(kwargs['interpulse_interval'] / kwargs['simtime_resolution'])"], {}), "(kwargs['interpulse_interval'] / kwargs['simtime_resolution'])\n", (3041, 3103), True, 'import numpy as np\n'), ((4361, 4391), 'numpy.all', 'np.all', (['(echo_arrivaltimes >= 0)'], {}), '(echo_arrivaltimes >= 0)\n', (4367, 4391), True, 'import numpy as np\n'), ((4792, 4840), 'numpy.around', 'np.around', (['(relative_arrivaltimes * num_timesteps)'], {}), '(relative_arrivaltimes * num_timesteps)\n', (4801, 4840), True, 'import numpy as np\n'), ((7248, 7267), 'numpy.any', 'np.any', (['sound_stops'], {}), '(sound_stops)\n', (7254, 7267), True, 'import numpy as np\n'), ((8604, 8661), 'numpy.bincount', 'np.bincount', (['num_echoes_heard'], {'minlength': '(total_echoes + 1)'}), '(num_echoes_heard, minlength=total_echoes + 1)\n', (8615, 8661), True, 'import numpy as np\n'), ((14700, 14753), 'numpy.random.random_integers', 'np.random.random_integers', (['angle1', 'angle2', 'num_sounds'], {}), '(angle1, angle2, num_sounds)\n', (14725, 14753), True, 'import numpy as np\n'), ((14899, 14952), 'numpy.random.random_integers', 'np.random.random_integers', (['level1', 'level2', 'num_sounds'], {}), '(level1, level2, num_sounds)\n', (14924, 14952), True, 'import numpy as np\n'), ((15374, 15399), 'numpy.around', 'np.around', (['pois_intensity'], {}), '(pois_intensity)\n', (15383, 15399), True, 'import numpy as np\n'), ((16372, 16401), 'numpy.deg2rad', 'np.deg2rad', (["sound_df['theta']"], {}), "(sound_df['theta'])\n", (16382, 16401), True, 'import numpy as np\n'), ((25556, 25615), 'numpy.tile', 'np.tile', (['simultaneous', '(right_echo_edge - left_echo_edge + 1)'], {}), '(simultaneous, right_echo_edge - left_echo_edge + 1)\n', (25563, 25615), True, 'import numpy as np\n'), ((25696, 25757), 'numpy.concatenate', 'np.concatenate', (['(fwd_masking, simult_masking, backwd_masking)'], {}), '((fwd_masking, simult_masking, backwd_masking))\n', (25710, 25757), True, 'import numpy as np\n'), ((33317, 33361), 'numpy.abs', 'np.abs', (['(timegap_ms - temp_mask_fn.iloc[:, 0])'], {}), '(timegap_ms - temp_mask_fn.iloc[:, 0])\n', (33323, 33361), True, 'import numpy as np\n'), ((43365, 43386), 'numpy.sum', 'np.sum', (['inner_numbats'], {}), '(inner_numbats)\n', (43371, 43386), True, 'import numpy as np\n'), ((47627, 47690), 'scipy.spatial.distance_matrix', 'spl.distance_matrix', (['centre_and_other_pts', 'centre_and_other_pts'], {}), '(centre_and_other_pts, centre_and_other_pts)\n', (47646, 47690), True, 'import scipy.spatial as spl\n'), ((48085, 48156), 'scipy.spatial.distance_matrix', 'spl.distance_matrix', (['target_and_nearby_points', 'target_and_nearby_points'], {}), '(target_and_nearby_points, target_and_nearby_points)\n', (48104, 48156), True, 'import scipy.spatial as spl\n'), ((56459, 56481), 'numpy.tile', 'np.tile', (['(-row_index)', '(2)'], {}), '(-row_index, 2)\n', (56466, 56481), True, 'import numpy as np\n'), ((60557, 60634), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': '[]', 'index': '[0]', 'columns': "['start', 'stop', 'theta', 'level']"}), "(data=[], index=[0], columns=['start', 'stop', 'theta', 'level'])\n", (60569, 60634), True, 'import pandas as pd\n'), ((64943, 65050), 'scipy.spatial.distance.euclidean', 'spl.distance.euclidean', (["kwargs['bats_xy'][each_callpath[0], :]", "kwargs['bats_xy'][each_callpath[1], :]"], {}), "(kwargs['bats_xy'][each_callpath[0], :], kwargs[\n 'bats_xy'][each_callpath[1], :])\n", (64965, 65050), True, 'import scipy.spatial as spl\n'), ((69365, 69399), 'numpy.array', 'np.array', (["echoes['theta_emission']"], {}), "(echoes['theta_emission'])\n", (69373, 69399), True, 'import numpy as np\n'), ((70171, 70196), 'numpy.array', 'np.array', (["echoes['theta']"], {}), "(echoes['theta'])\n", (70179, 70196), True, 'import numpy as np\n'), ((74433, 74464), 'numpy.array', 'np.array', (['[theta_in, theta_out]'], {}), '([theta_in, theta_out])\n', (74441, 74464), True, 'import numpy as np\n'), ((90147, 90186), 'numpy.arange', 'np.arange', (['min_heading', '(max_heading + 1)'], {}), '(min_heading, max_heading + 1)\n', (90156, 90186), True, 'import numpy as np\n'), ((7344, 7363), 'numpy.max', 'np.max', (['sound_stops'], {}), '(sound_stops)\n', (7350, 7363), True, 'import numpy as np\n'), ((19323, 19345), 'numpy.array', 'np.array', (['echoes_heard'], {}), '(echoes_heard)\n', (19331, 19345), True, 'import numpy as np\n'), ((37922, 37955), 'numpy.log10', 'np.log10', (['(receiver_distance / 1.0)'], {}), '(receiver_distance / 1.0)\n', (37930, 37955), True, 'import numpy as np\n'), ((38646, 38659), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (38652, 38659), True, 'import numpy as np\n'), ((43093, 43104), 'numpy.array', 'np.array', (['(1)'], {}), '(1)\n', (43101, 43104), True, 'import numpy as np\n'), ((43105, 43122), 'numpy.array', 'np.array', (['numbats'], {}), '(numbats)\n', (43113, 43122), True, 'import numpy as np\n'), ((43142, 43177), 'numpy.argwhere', 'np.argwhere', (['(numbats <= cumsum_bats)'], {}), '(numbats <= cumsum_bats)\n', (43153, 43177), True, 'import numpy as np\n'), ((43266, 43295), 'numpy.arange', 'np.arange', (['(1)', '(inner_rings + 1)'], {}), '(1, inner_rings + 1)\n', (43275, 43295), True, 'import numpy as np\n'), ((45246, 45340), 'bridson.poisson_disc_samples', 'poisson_disc_samples', (['sidelength', 'sidelength', 'nbr_distance'], {'k': '(30)', 'random': 'np.random.random'}), '(sidelength, sidelength, nbr_distance, k=30, random=np.\n random.random)\n', (45266, 45340), False, 'from bridson import poisson_disc_samples\n'), ((52230, 52261), 'numpy.linalg.det', 'np.linalg.det', (['[agentvects, v0]'], {}), '([agentvects, v0])\n', (52243, 52261), True, 'import numpy as np\n'), ((52314, 52336), 'numpy.dot', 'np.dot', (['agentvects', 'v0'], {}), '(agentvects, v0)\n', (52320, 52336), True, 'import numpy as np\n'), ((74772, 74795), 'numpy.min', 'np.min', (['abs_theta_diffs'], {}), '(abs_theta_diffs)\n', (74778, 74795), True, 'import numpy as np\n'), ((75037, 75063), 'numpy.argmin', 'np.argmin', (['abs_theta_diffs'], {}), '(abs_theta_diffs)\n', (75046, 75063), True, 'import numpy as np\n'), ((75559, 75575), 'numpy.square', 'np.square', (['diffs'], {}), '(diffs)\n', (75568, 75575), True, 'import numpy as np\n'), ((88848, 88902), 'pandas.concat', 'pd.concat', (['sounddf_list'], {'ignore_index': '(True)', 'sort': '(False)'}), '(sounddf_list, ignore_index=True, sort=False)\n', (88857, 88902), True, 'import pandas as pd\n'), ((26122, 26157), 'numpy.sum', 'np.sum', (['timesteps_echo_below_masker'], {}), '(timesteps_echo_below_masker)\n', (26128, 26157), True, 'import numpy as np\n'), ((30853, 30880), 'numpy.array', 'np.array', (["sound_df['theta']"], {}), "(sound_df['theta'])\n", (30861, 30880), True, 'import numpy as np\n'), ((39875, 39896), 'scipy.misc.comb', 'misc.comb', (['Ntrials', 'k'], {}), '(Ntrials, k)\n', (39884, 39896), True, 'import scipy.misc as misc\n'), ((45154, 45170), 'numpy.sqrt', 'np.sqrt', (['npoints'], {}), '(npoints)\n', (45161, 45170), True, 'import numpy as np\n'), ((47870, 47883), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (47876, 47883), True, 'import numpy as np\n'), ((47894, 47907), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (47900, 47907), True, 'import numpy as np\n'), ((52038, 52058), 'numpy.cos', 'np.cos', (['radagntorntn'], {}), '(radagntorntn)\n', (52044, 52058), True, 'import numpy as np\n'), ((52062, 52082), 'numpy.sin', 'np.sin', (['radagntorntn'], {}), '(radagntorntn)\n', (52068, 52082), True, 'import numpy as np\n'), ((52959, 52983), 'numpy.where', 'np.where', (['(row_error == 0)'], {}), '(row_error == 0)\n', (52967, 52983), True, 'import numpy as np\n')]
|
import numpy as np
import unyt as u
class APConstants:
"""Experimental data and other constants for Ammonium Perchlorate"""
def __init__(self):
assert (
self.expt_lattice_a.keys()
== self.expt_lattice_b.keys()
== self.expt_lattice_c.keys()
)
assert(
len(self.primitive_cell_elements)
== self.primitive_cell_xyz.shape[0]
)
assert(
len(self.unit_cell_elements)
== self.unit_cell_xyz.shape[0]
)
@property
def molecular_weight(self):
"""Molecular weight of the molecule in g/mol"""
return 117.49
@property
def n_params(self):
"""Number of adjustable parameters"""
return len(self.param_names)
@property
def param_names(self):
"""Adjustable parameter names"""
param_names = (
"sigma_Cl",
"sigma_H",
"sigma_N",
"sigma_O",
"epsilon_Cl",
"epsilon_H",
"epsilon_N",
"epsilon_O",
)
return param_names
@property
def param_bounds(self):
"""Bounds on sigma and epsilon in units of nm and kJ/mol"""
bounds_sigma = np.asarray(
[
[3.5, 4.5], # Cl
[0.5, 2.0], # H
[2.5, 3.8], # N
[2.5, 3.8], # O
]
)
bounds_epsilon = np.asarray(
[
[0.1, 0.8], # Cl
[0.0, 0.02], # H
[0.01, 0.2], # N
[0.02, 0.3], # O
]
)
bounds = np.vstack((bounds_sigma, bounds_epsilon))
return bounds
@property
def expt_lattice_a(self):
"""Dictionary with experimental "a" lattice constant
Temperature units K
Lattice constant units Angstrom
"""
expt_a = {
10: 8.94,
78: 9.02,
298: 9.20,
}
return expt_a
@property
def expt_lattice_b(self):
"""Dictionary with experimental "b" lattice constant
Temperature units K
Lattice constant units Angstrom
"""
expt_b = {
10: 5.89,
78: 5.85,
298: 5.82,
}
return expt_b
@property
def expt_lattice_c(self):
"""Dictionary with experimental "c" lattice constant
Temperature units K
Lattice constant units Angstrom
"""
expt_c = {
10: 7.30,
78: 7.39,
298: 7.45,
}
return expt_c
@property
def primitive_cell_elements(self):
elements = np.array([ "Cl", "O", "O", "O", "N", "H", "H", "H" ])
return elements
@property
def unit_cell_elements(self):
elements = np.array(
[ "Cl", "O", "O", "O", "N", "H", "H", "H",
"Cl", "O", "O", "O", "N", "H", "H", "H",
"O", "H",
"Cl", "O", "O", "O", "N", "H", "H", "H",
"Cl", "O", "O", "O", "N", "H", "H", "H",
"O", "H", "O", "H", "O", "H",
]
)
return elements
@property
def primitive_cell_xyz(self):
xyz = np.array(
[
[3.79592400000000, 1.47250000000000, 1.40963000000000],
[2.62836000000000, 1.47250000000000, 0.55188000000000],
[4.99388400000000, 1.47250000000000, 0.61028000000000],
[3.76463400000000, 0.29685600000000, 2.25278000000000],
[2.84739000000000, 1.47250000000000, 4.90998000000000],
[1.90770909169815, 1.47250000000000, 4.49310617653451],
[2.73888458499779, 1.47250000000000, 5.96240125991545],
[3.38685404561816, 2.29027755286932, 4.58876441060340],
]
)
return xyz
@property
def unit_cell_xyz(self):
xyz = np.array(
[
[3.79592400000000, 1.47250000000000, 1.40963000000000],
[2.62836000000000, 1.47250000000000, 0.55188000000000],
[4.99388400000000, 1.47250000000000, 0.61028000000000],
[3.76463400000000, 0.29685600000000, 2.25278000000000],
[2.84739000000000, 1.47250000000000, 4.90998000000000],
[1.90770909169815, 1.47250000000000, 4.49310617653451],
[2.73888458499779, 1.47250000000000, 5.96240125991545],
[3.38685404561816, 2.29027755286932, 4.58876441060340],
[0.67407600000000, 4.41750000000000, 5.05963000000000],
[1.84164000000000, 4.41750000000000, 4.20188000000000],
[8.41611600000000, 4.41750000000000, 4.26028000000000],
[0.70536600000000, 3.24185600000000, 5.90278000000000],
[1.62261000000000, 4.41750000000000, 1.25998000000000],
[2.56229090830185, 4.41750000000000, 0.84310617653451],
[1.73111541500221, 4.41750000000000, 2.31240125991545],
[1.08314595438184, 5.23527755286932, 0.93876441060340],
[3.76463400000000, 2.64814400000000, 2.25278000000000],
[3.38685404561816, 0.65472244713068, 4.58876441060340],
[8.26592400000000, 1.47250000000000, 2.24037000000000],
[7.09836000000000, 1.47250000000000, 3.09812000000000],
[0.52388400000000, 1.47250000000000, 3.03972000000000],
[8.23463400000000, 0.29685600000000, 1.39722000000000],
[7.31739000000000, 1.47250000000000, 6.04002000000000],
[6.37770909169815, 1.47250000000000, 6.45689382346549],
[7.20888458499779, 1.47250000000000, 4.98759874008455],
[7.85685404561816, 2.29027755286932, 6.36123558939660],
[5.14407600000000, 4.41750000000000, 5.89037000000000],
[6.31164000000000, 4.41750000000000, 6.74812000000000],
[3.94611600000000, 4.41750000000000, 6.68972000000000],
[5.17536600000000, 5.59314400000000, 5.04722000000000],
[6.09261000000000, 4.41750000000000, 2.39002000000000],
[7.03229090830185, 4.41750000000000, 2.80689382346549],
[6.20111541500221, 4.41750000000000, 1.33759874008455],
[5.55314595438184, 3.59972244713068, 2.71123558939660],
[8.23463400000000, 2.64814400000000, 1.39722000000000],
[7.85685404561816, 0.65472244713068, 6.36123558939660],
[5.17536600000000, 3.24185600000000, 5.04722000000000],
[5.55314595438184, 5.23527755286932, 2.71123558939660],
[0.70536600000000, 5.59314400000000, 5.90278000000000],
[1.08314595438184, 3.59972244713068, 0.93876441060340],
]
)
return xyz
@property
def temperature_bounds(self):
"""Bounds on temperature in units of K"""
lower_bound = np.min(list(self.expt_lattice_a.keys()))
upper_bound = np.max(list(self.expt_lattice_a.keys()))
bounds = np.asarray([lower_bound, upper_bound], dtype=np.float32)
return bounds
@property
def lattice_a_bounds(self):
"""Bounds on a lattice a constants in units of angstroms"""
lower_bound = np.min(list(self.expt_lattice_a.values()))
upper_bound = np.max(list(self.expt_lattice_a.values()))
bounds = np.asarray([lower_bound, upper_bound], dtype=np.float32)
return bounds
@property
def lattice_b_bounds(self):
"""Bounds on a lattice b constants in units of angstroms"""
lower_bound = np.min(list(self.expt_lattice_b.values()))
upper_bound = np.max(list(self.expt_lattice_b.values()))
bounds = np.asarray([lower_bound, upper_bound], dtype=np.float32)
return bounds
@property
def lattice_c_bounds(self):
"""Bounds on a lattice c constants in units of angstroms"""
lower_bound = np.min(list(self.expt_lattice_c.values()))
upper_bound = np.max(list(self.expt_lattice_c.values()))
bounds = np.asarray([lower_bound, upper_bound], dtype=np.float32)
return bounds
AP = APConstants()
|
[
"numpy.asarray",
"numpy.array",
"numpy.vstack"
] |
[((1257, 1317), 'numpy.asarray', 'np.asarray', (['[[3.5, 4.5], [0.5, 2.0], [2.5, 3.8], [2.5, 3.8]]'], {}), '([[3.5, 4.5], [0.5, 2.0], [2.5, 3.8], [2.5, 3.8]])\n', (1267, 1317), True, 'import numpy as np\n'), ((1466, 1529), 'numpy.asarray', 'np.asarray', (['[[0.1, 0.8], [0.0, 0.02], [0.01, 0.2], [0.02, 0.3]]'], {}), '([[0.1, 0.8], [0.0, 0.02], [0.01, 0.2], [0.02, 0.3]])\n', (1476, 1529), True, 'import numpy as np\n'), ((1675, 1716), 'numpy.vstack', 'np.vstack', (['(bounds_sigma, bounds_epsilon)'], {}), '((bounds_sigma, bounds_epsilon))\n', (1684, 1716), True, 'import numpy as np\n'), ((2736, 2787), 'numpy.array', 'np.array', (["['Cl', 'O', 'O', 'O', 'N', 'H', 'H', 'H']"], {}), "(['Cl', 'O', 'O', 'O', 'N', 'H', 'H', 'H'])\n", (2744, 2787), True, 'import numpy as np\n'), ((2882, 3104), 'numpy.array', 'np.array', (["['Cl', 'O', 'O', 'O', 'N', 'H', 'H', 'H', 'Cl', 'O', 'O', 'O', 'N', 'H',\n 'H', 'H', 'O', 'H', 'Cl', 'O', 'O', 'O', 'N', 'H', 'H', 'H', 'Cl', 'O',\n 'O', 'O', 'N', 'H', 'H', 'H', 'O', 'H', 'O', 'H', 'O', 'H']"], {}), "(['Cl', 'O', 'O', 'O', 'N', 'H', 'H', 'H', 'Cl', 'O', 'O', 'O', 'N',\n 'H', 'H', 'H', 'O', 'H', 'Cl', 'O', 'O', 'O', 'N', 'H', 'H', 'H', 'Cl',\n 'O', 'O', 'O', 'N', 'H', 'H', 'H', 'O', 'H', 'O', 'H', 'O', 'H'])\n", (2890, 3104), True, 'import numpy as np\n'), ((3319, 3641), 'numpy.array', 'np.array', (['[[3.795924, 1.4725, 1.40963], [2.62836, 1.4725, 0.55188], [4.993884, 1.4725,\n 0.61028], [3.764634, 0.296856, 2.25278], [2.84739, 1.4725, 4.90998], [\n 1.90770909169815, 1.4725, 4.49310617653451], [2.73888458499779, 1.4725,\n 5.96240125991545], [3.38685404561816, 2.29027755286932, 4.5887644106034]]'], {}), '([[3.795924, 1.4725, 1.40963], [2.62836, 1.4725, 0.55188], [\n 4.993884, 1.4725, 0.61028], [3.764634, 0.296856, 2.25278], [2.84739, \n 1.4725, 4.90998], [1.90770909169815, 1.4725, 4.49310617653451], [\n 2.73888458499779, 1.4725, 5.96240125991545], [3.38685404561816, \n 2.29027755286932, 4.5887644106034]])\n', (3327, 3641), True, 'import numpy as np\n'), ((4004, 5633), 'numpy.array', 'np.array', (['[[3.795924, 1.4725, 1.40963], [2.62836, 1.4725, 0.55188], [4.993884, 1.4725,\n 0.61028], [3.764634, 0.296856, 2.25278], [2.84739, 1.4725, 4.90998], [\n 1.90770909169815, 1.4725, 4.49310617653451], [2.73888458499779, 1.4725,\n 5.96240125991545], [3.38685404561816, 2.29027755286932, 4.5887644106034\n ], [0.674076, 4.4175, 5.05963], [1.84164, 4.4175, 4.20188], [8.416116, \n 4.4175, 4.26028], [0.705366, 3.241856, 5.90278], [1.62261, 4.4175, \n 1.25998], [2.56229090830185, 4.4175, 0.84310617653451], [\n 1.73111541500221, 4.4175, 2.31240125991545], [1.08314595438184, \n 5.23527755286932, 0.9387644106034], [3.764634, 2.648144, 2.25278], [\n 3.38685404561816, 0.65472244713068, 4.5887644106034], [8.265924, 1.4725,\n 2.24037], [7.09836, 1.4725, 3.09812], [0.523884, 1.4725, 3.03972], [\n 8.234634, 0.296856, 1.39722], [7.31739, 1.4725, 6.04002], [\n 6.37770909169815, 1.4725, 6.45689382346549], [7.20888458499779, 1.4725,\n 4.98759874008455], [7.85685404561816, 2.29027755286932, 6.3612355893966\n ], [5.144076, 4.4175, 5.89037], [6.31164, 4.4175, 6.74812], [3.946116, \n 4.4175, 6.68972], [5.175366, 5.593144, 5.04722], [6.09261, 4.4175, \n 2.39002], [7.03229090830185, 4.4175, 2.80689382346549], [\n 6.20111541500221, 4.4175, 1.33759874008455], [5.55314595438184, \n 3.59972244713068, 2.7112355893966], [8.234634, 2.648144, 1.39722], [\n 7.85685404561816, 0.65472244713068, 6.3612355893966], [5.175366, \n 3.241856, 5.04722], [5.55314595438184, 5.23527755286932, \n 2.7112355893966], [0.705366, 5.593144, 5.90278], [1.08314595438184, \n 3.59972244713068, 0.9387644106034]]'], {}), '([[3.795924, 1.4725, 1.40963], [2.62836, 1.4725, 0.55188], [\n 4.993884, 1.4725, 0.61028], [3.764634, 0.296856, 2.25278], [2.84739, \n 1.4725, 4.90998], [1.90770909169815, 1.4725, 4.49310617653451], [\n 2.73888458499779, 1.4725, 5.96240125991545], [3.38685404561816, \n 2.29027755286932, 4.5887644106034], [0.674076, 4.4175, 5.05963], [\n 1.84164, 4.4175, 4.20188], [8.416116, 4.4175, 4.26028], [0.705366, \n 3.241856, 5.90278], [1.62261, 4.4175, 1.25998], [2.56229090830185, \n 4.4175, 0.84310617653451], [1.73111541500221, 4.4175, 2.31240125991545],\n [1.08314595438184, 5.23527755286932, 0.9387644106034], [3.764634, \n 2.648144, 2.25278], [3.38685404561816, 0.65472244713068, \n 4.5887644106034], [8.265924, 1.4725, 2.24037], [7.09836, 1.4725, \n 3.09812], [0.523884, 1.4725, 3.03972], [8.234634, 0.296856, 1.39722], [\n 7.31739, 1.4725, 6.04002], [6.37770909169815, 1.4725, 6.45689382346549],\n [7.20888458499779, 1.4725, 4.98759874008455], [7.85685404561816, \n 2.29027755286932, 6.3612355893966], [5.144076, 4.4175, 5.89037], [\n 6.31164, 4.4175, 6.74812], [3.946116, 4.4175, 6.68972], [5.175366, \n 5.593144, 5.04722], [6.09261, 4.4175, 2.39002], [7.03229090830185, \n 4.4175, 2.80689382346549], [6.20111541500221, 4.4175, 1.33759874008455],\n [5.55314595438184, 3.59972244713068, 2.7112355893966], [8.234634, \n 2.648144, 1.39722], [7.85685404561816, 0.65472244713068, \n 6.3612355893966], [5.175366, 3.241856, 5.04722], [5.55314595438184, \n 5.23527755286932, 2.7112355893966], [0.705366, 5.593144, 5.90278], [\n 1.08314595438184, 3.59972244713068, 0.9387644106034]])\n', (4012, 5633), True, 'import numpy as np\n'), ((7195, 7251), 'numpy.asarray', 'np.asarray', (['[lower_bound, upper_bound]'], {'dtype': 'np.float32'}), '([lower_bound, upper_bound], dtype=np.float32)\n', (7205, 7251), True, 'import numpy as np\n'), ((7537, 7593), 'numpy.asarray', 'np.asarray', (['[lower_bound, upper_bound]'], {'dtype': 'np.float32'}), '([lower_bound, upper_bound], dtype=np.float32)\n', (7547, 7593), True, 'import numpy as np\n'), ((7879, 7935), 'numpy.asarray', 'np.asarray', (['[lower_bound, upper_bound]'], {'dtype': 'np.float32'}), '([lower_bound, upper_bound], dtype=np.float32)\n', (7889, 7935), True, 'import numpy as np\n'), ((8221, 8277), 'numpy.asarray', 'np.asarray', (['[lower_bound, upper_bound]'], {'dtype': 'np.float32'}), '([lower_bound, upper_bound], dtype=np.float32)\n', (8231, 8277), True, 'import numpy as np\n')]
|
from numpy import array
A = array([[1,2,3],[4,5,6],[7,8,9]])
print('A[:,0] =',A[:,0])
print('A[:,2] =',A[:,2])
|
[
"numpy.array"
] |
[((28, 68), 'numpy.array', 'array', (['[[1, 2, 3], [4, 5, 6], [7, 8, 9]]'], {}), '([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n', (33, 68), False, 'from numpy import array\n')]
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2020-12-30 10:28
# @Author : Xelawk
# @FileName: parser.py
import os
from io import BytesIO
import numpy as np
import trimesh
import open3d as o3d
import uuid
from wand import image
from PIL import Image
class MeshParser(object):
def __init__(self, **kwargs):
"""
Input:
mesh_file: self-defined file about mesh xyz, and uv coordinate
face_file: self-defined file about face index
"""
# parse kwargs
if 'mesh_file' in kwargs:
self.mesh_file = kwargs['mesh_file']
else:
self.mesh_file = None
if 'face_file' in kwargs:
self.face_file = kwargs['face_file']
else:
self.face_file = None
if 'img_file' in kwargs: # jpg or png
self.img_file = kwargs['img_file']
else:
self.img_file = None
if 'dds_file' in kwargs:
self.dds_file = kwargs['dds_file']
else:
self.dds_file = None
if 'mesh_str' in kwargs:
self.mesh_str = kwargs['mesh_str']
else:
self.mesh_str = None
if 'face_str' in kwargs:
self.face_str = kwargs['face_str']
else:
self.face_str = None
if 'dds_bin' in kwargs:
self.dds_bin = kwargs['dds_bin']
else:
self.dds_bin = None
# Declare vars
self.xyz = None
self.nxyz = None
self.uvs = None
self.faces = None
self.uvs_faces = None
self.mesh = None
self.img_texture = None
# Register files paths temporarily created
self.path_tmp = dict()
def parse_mesh(self):
# 解析得到xyz坐标,法向n_xyz, uv坐标
xyz_list = []
nxyz_list = []
uv_list = []
if self.mesh_file:
with open(self.mesh_file, 'r') as tmp:
content = tmp.read().strip()
elif self.mesh_str:
content = self.mesh_str.strip()
else:
raise Exception("Mesh info not found!")
lines = content.split('\n')
for line in lines:
if line:
xyz_str, nxyz_str, uv_str = line.split(',')
x_str, y_str, z_str = xyz_str.split(' ')
nx_str, ny_str, nz_str = nxyz_str.split(' ')
u_str, v_str = uv_str.split(' ')
xyz_list.append([float(x_str), float(y_str), float(z_str)])
nxyz_list.append([float(nx_str), float(ny_str), float(nz_str)])
uv_list.append([float(u_str), float(v_str)])
# 解析得到face索引
f_list = []
if self.face_file:
with open(self.face_file, 'r') as tmp:
content = tmp.read().strip()
elif self.face_str:
content = self.face_str.strip()
else:
raise Exception("Faces info not found!")
lines = content.split('\n')
for line in lines:
if line:
idx1_str, idx2_str, idx3_str = line.split(' ')
f_list.append([int(idx1_str), int(idx2_str), int(idx3_str)])
# convert .dds to .png obj, then read the data
if self.img_file:
img_texture = Image.open(self.img_file)
self.img_texture = img_texture.convert('RGB')
self.xyz, self.nxyz, self.uvs, self.faces = xyz_list, nxyz_list, uv_list, f_list
return True
elif self.dds_file:
img = image.Image(filename=self.dds_file)
elif self.dds_bin:
img = image.Image(file=BytesIO(self.dds_bin))
else:
raise Exception("Image info not found!")
# saving to disk then read it
img.compression = "no"
path_tmp = 'cache/' + str(uuid.uuid1()) + '.png'
img.save(filename=path_tmp)
self.path_tmp["texture_png"] = path_tmp
img_texture = Image.open(path_tmp)
self.img_texture = img_texture.convert('RGB')
self.xyz, self.nxyz, self.uvs, self.faces = xyz_list, nxyz_list, uv_list, f_list
return True
def compute_uv_face_normal(self):
uv_list = np.array(self.uvs)
u_list = uv_list[:, 0]
v_list = uv_list[:, 1]
u_list[:] = (u_list - u_list.min()) / (u_list.max() - u_list.min())
v_list[:] = (v_list - v_list.min()) / (v_list.max() - v_list.min())
uv_face = []
for idx in self.faces:
tmp = uv_list[idx].tolist()
uv_face.extend(tmp)
self.uvs_faces = uv_face
def compute_uv_face(self):
uv_list = np.array(self.uvs)
uv_face = []
for idx in self.faces:
tmp = uv_list[idx].tolist()
uv_face.extend(tmp)
self.uvs_faces = uv_face
def create_trimesh(self):
if self.xyz and self.faces:
mesh = trimesh.Trimesh(vertices=self.xyz, faces=self.faces)
self.mesh = mesh
return self.mesh
else:
raise Exception('Please parse mesh info before creating triangle mesh!')
def trimesh_show(self):
if self.mesh:
self.mesh.show()
else:
raise Exception('Please create a triangle mesh before showing!')
def open3d_show(self):
if self.xyz and self.faces and self.uvs_faces:
mesh_o3d = o3d.geometry.TriangleMesh()
mesh_o3d.vertices = o3d.utility.Vector3dVector(self.xyz)
mesh_o3d.triangles = o3d.utility.Vector3iVector(self.faces)
mesh_o3d.triangle_uvs = o3d.utility.Vector2dVector(self.uvs_faces)
if "texture_png" not in self.path_tmp:
path_tmp = 'cache' + str(uuid.uuid1()) + '.jpg'
self.img_texture.save(path_tmp)
self.path_tmp["texture_png"] = path_tmp
mesh_o3d.textures = [o3d.io.read_image(self.path_tmp["texture_png"])]
mesh_o3d.triangle_material_ids = o3d.utility.IntVector(np.zeros(len(self.faces), dtype=np.int))
o3d.visualization.draw_geometries([mesh_o3d], 'Open3D')
else:
raise Exception('Please parse mesh info before creating triangle mesh!')
def clear(self):
"""
clear all files temporarily created
"""
if self.path_tmp:
keys_list = list(self.path_tmp.keys())
for key in keys_list:
try:
os.remove(self.path_tmp[key])
except Exception as e:
print(e)
self.path_tmp.pop(key)
|
[
"trimesh.Trimesh",
"os.remove",
"io.BytesIO",
"open3d.utility.Vector3iVector",
"PIL.Image.open",
"open3d.visualization.draw_geometries",
"wand.image.Image",
"uuid.uuid1",
"open3d.geometry.TriangleMesh",
"numpy.array",
"open3d.io.read_image",
"open3d.utility.Vector3dVector",
"open3d.utility.Vector2dVector"
] |
[((3941, 3961), 'PIL.Image.open', 'Image.open', (['path_tmp'], {}), '(path_tmp)\n', (3951, 3961), False, 'from PIL import Image\n'), ((4182, 4200), 'numpy.array', 'np.array', (['self.uvs'], {}), '(self.uvs)\n', (4190, 4200), True, 'import numpy as np\n'), ((4622, 4640), 'numpy.array', 'np.array', (['self.uvs'], {}), '(self.uvs)\n', (4630, 4640), True, 'import numpy as np\n'), ((3273, 3298), 'PIL.Image.open', 'Image.open', (['self.img_file'], {}), '(self.img_file)\n', (3283, 3298), False, 'from PIL import Image\n'), ((4884, 4936), 'trimesh.Trimesh', 'trimesh.Trimesh', ([], {'vertices': 'self.xyz', 'faces': 'self.faces'}), '(vertices=self.xyz, faces=self.faces)\n', (4899, 4936), False, 'import trimesh\n'), ((5371, 5398), 'open3d.geometry.TriangleMesh', 'o3d.geometry.TriangleMesh', ([], {}), '()\n', (5396, 5398), True, 'import open3d as o3d\n'), ((5431, 5467), 'open3d.utility.Vector3dVector', 'o3d.utility.Vector3dVector', (['self.xyz'], {}), '(self.xyz)\n', (5457, 5467), True, 'import open3d as o3d\n'), ((5501, 5539), 'open3d.utility.Vector3iVector', 'o3d.utility.Vector3iVector', (['self.faces'], {}), '(self.faces)\n', (5527, 5539), True, 'import open3d as o3d\n'), ((5576, 5618), 'open3d.utility.Vector2dVector', 'o3d.utility.Vector2dVector', (['self.uvs_faces'], {}), '(self.uvs_faces)\n', (5602, 5618), True, 'import open3d as o3d\n'), ((6040, 6095), 'open3d.visualization.draw_geometries', 'o3d.visualization.draw_geometries', (['[mesh_o3d]', '"""Open3D"""'], {}), "([mesh_o3d], 'Open3D')\n", (6073, 6095), True, 'import open3d as o3d\n'), ((3520, 3555), 'wand.image.Image', 'image.Image', ([], {'filename': 'self.dds_file'}), '(filename=self.dds_file)\n', (3531, 3555), False, 'from wand import image\n'), ((5871, 5918), 'open3d.io.read_image', 'o3d.io.read_image', (["self.path_tmp['texture_png']"], {}), "(self.path_tmp['texture_png'])\n", (5888, 5918), True, 'import open3d as o3d\n'), ((3812, 3824), 'uuid.uuid1', 'uuid.uuid1', ([], {}), '()\n', (3822, 3824), False, 'import uuid\n'), ((6437, 6466), 'os.remove', 'os.remove', (['self.path_tmp[key]'], {}), '(self.path_tmp[key])\n', (6446, 6466), False, 'import os\n'), ((3618, 3639), 'io.BytesIO', 'BytesIO', (['self.dds_bin'], {}), '(self.dds_bin)\n', (3625, 3639), False, 'from io import BytesIO\n'), ((5711, 5723), 'uuid.uuid1', 'uuid.uuid1', ([], {}), '()\n', (5721, 5723), False, 'import uuid\n')]
|
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 5 23:46:02 2020
@author: sabbi
"""
#input file name to the function, data will be output into dataContainer object,
#which will have xml fopoter and wavelength calibration if applicable
#dataContainer.data will be a list of numpy arrays per ROI
import numpy as np
import xml.etree.ElementTree as ET
class ROI:
def __init__(self,width,height,stride):
self.width=width
self.height=height
self.stride=stride
class dataContainer:
def __init__(self,data,**kwargs):
self.data=data
self.__dict__.update(kwargs)
def readSpe(filePath):
dataTypes = {'MonochromeUnsigned16':np.uint16, 'MonochromeUnsigned32':np.uint32, 'MonochromeFloating32':np.float32}
with open(filePath) as f:
f.seek(678)
xmlLoc = np.fromfile(f,dtype=np.uint64,count=1)[0]
f.seek(1992)
speVer = np.fromfile(f,dtype=np.float32,count=1)[0]
if speVer==3:
with open(filePath, encoding="utf8") as f:
f.seek(xmlLoc)
xmlFooter = f.read()
xmlRoot = ET.fromstring(xmlFooter)
#print(xmlRoot[0][0].attrib)
readoutStride=np.int((xmlRoot[0][0].attrib)['stride'])
numFrames=np.int((xmlRoot[0][0].attrib)['count'])
pixFormat=(xmlRoot[0][0].attrib)['pixelFormat']
#find number of regions
#regions = list(xmlRoot[0][0])
regionList=list()
for child in xmlRoot[0][0]:
regStride=np.int((child.attrib)['stride'])
regWidth=np.int((child.attrib)['width'])
regHeight=np.int((child.attrib)['height'])
regionList.append(ROI(regWidth,regHeight,regStride))
dataList=list()
regionOffset=0
#read entire datablock
f.seek(0)
bpp = np.dtype(dataTypes[pixFormat]).itemsize
numPixels = np.int((xmlLoc-4100)/bpp)
totalBlock = np.fromfile(f,dtype=dataTypes[pixFormat],count=numPixels,offset=4100)
for i in range(0,len(regionList)):
offLen=list()
if i>0:
regionOffset += (regionList[i-1].stride)/bpp
for j in range(0,numFrames):
offLen.append((np.int(regionOffset+(j*readoutStride/bpp)),regionList[i].width*regionList[i].height))
regionData = np.concatenate([totalBlock[offset:offset+length] for offset,length in offLen])
dataList.append(np.reshape(regionData,(numFrames,regionList[i].height,regionList[i].width),order='C'))
calFlag=False
for child in xmlRoot[1]:
if 'Wavelength' in child.tag:
wavelengths=np.fromstring(child[0].text,sep=',')
calFlag=True
totalData=dataContainer(dataList,xmlFooter=xmlFooter,wavelengths=wavelengths)
if calFlag==False:
totalData=dataContainer(dataList,xmlFooter=xmlFooter)
return totalData
elif speVer<3:
dataTypes2 = {0:np.float32, 1:np.int32, 2:np.int16, 3:np.uint16, 5:np.float64, 6:np.uint8, 8:np.uint32}
with open(filePath, encoding="utf8") as f:
f.seek(108)
datatype=np.fromfile(f,dtype=np.int16,count=1)[0]
f.seek(42)
frameWidth=np.int(np.fromfile(f,dtype=np.uint16,count=1)[0])
f.seek(656)
frameHeight=np.int(np.fromfile(f,dtype=np.uint16,count=1)[0])
f.seek(1446)
numFrames=np.fromfile(f,dtype=np.int32,count=1)[0]
numPixels = frameWidth*frameHeight*numFrames
bpp = np.dtype(dataTypes2[datatype]).itemsize
dataList=list()
f.seek(0)
totalBlock = np.fromfile(f,dtype=dataTypes2[datatype],count=numPixels,offset=4100)
offLen=list()
for j in range(0,numFrames):
offLen.append((np.int((j*frameWidth*frameHeight)),frameWidth*frameHeight))
regionData = np.concatenate([totalBlock[offset:offset+length] for offset,length in offLen])
dataList.append(np.reshape(regionData,(numFrames,frameHeight,frameWidth),order='C'))
totalData=dataContainer(dataList)
return totalData
|
[
"xml.etree.ElementTree.fromstring",
"numpy.fromfile",
"numpy.dtype",
"numpy.int",
"numpy.reshape",
"numpy.fromstring",
"numpy.concatenate"
] |
[((863, 903), 'numpy.fromfile', 'np.fromfile', (['f'], {'dtype': 'np.uint64', 'count': '(1)'}), '(f, dtype=np.uint64, count=1)\n', (874, 903), True, 'import numpy as np\n'), ((945, 986), 'numpy.fromfile', 'np.fromfile', (['f'], {'dtype': 'np.float32', 'count': '(1)'}), '(f, dtype=np.float32, count=1)\n', (956, 986), True, 'import numpy as np\n'), ((1150, 1174), 'xml.etree.ElementTree.fromstring', 'ET.fromstring', (['xmlFooter'], {}), '(xmlFooter)\n', (1163, 1174), True, 'import xml.etree.ElementTree as ET\n'), ((1256, 1294), 'numpy.int', 'np.int', (["xmlRoot[0][0].attrib['stride']"], {}), "(xmlRoot[0][0].attrib['stride'])\n", (1262, 1294), True, 'import numpy as np\n'), ((1320, 1357), 'numpy.int', 'np.int', (["xmlRoot[0][0].attrib['count']"], {}), "(xmlRoot[0][0].attrib['count'])\n", (1326, 1357), True, 'import numpy as np\n'), ((2036, 2065), 'numpy.int', 'np.int', (['((xmlLoc - 4100) / bpp)'], {}), '((xmlLoc - 4100) / bpp)\n', (2042, 2065), True, 'import numpy as np\n'), ((2090, 2162), 'numpy.fromfile', 'np.fromfile', (['f'], {'dtype': 'dataTypes[pixFormat]', 'count': 'numPixels', 'offset': '(4100)'}), '(f, dtype=dataTypes[pixFormat], count=numPixels, offset=4100)\n', (2101, 2162), True, 'import numpy as np\n'), ((1601, 1631), 'numpy.int', 'np.int', (["child.attrib['stride']"], {}), "(child.attrib['stride'])\n", (1607, 1631), True, 'import numpy as np\n'), ((1660, 1689), 'numpy.int', 'np.int', (["child.attrib['width']"], {}), "(child.attrib['width'])\n", (1666, 1689), True, 'import numpy as np\n'), ((1719, 1749), 'numpy.int', 'np.int', (["child.attrib['height']"], {}), "(child.attrib['height'])\n", (1725, 1749), True, 'import numpy as np\n'), ((1971, 2001), 'numpy.dtype', 'np.dtype', (['dataTypes[pixFormat]'], {}), '(dataTypes[pixFormat])\n', (1979, 2001), True, 'import numpy as np\n'), ((2569, 2654), 'numpy.concatenate', 'np.concatenate', (['[totalBlock[offset:offset + length] for offset, length in offLen]'], {}), '([totalBlock[offset:offset + length] for offset, length in\n offLen])\n', (2583, 2654), True, 'import numpy as np\n'), ((4014, 4086), 'numpy.fromfile', 'np.fromfile', (['f'], {'dtype': 'dataTypes2[datatype]', 'count': 'numPixels', 'offset': '(4100)'}), '(f, dtype=dataTypes2[datatype], count=numPixels, offset=4100)\n', (4025, 4086), True, 'import numpy as np\n'), ((4271, 4356), 'numpy.concatenate', 'np.concatenate', (['[totalBlock[offset:offset + length] for offset, length in offLen]'], {}), '([totalBlock[offset:offset + length] for offset, length in\n offLen])\n', (4285, 4356), True, 'import numpy as np\n'), ((2681, 2775), 'numpy.reshape', 'np.reshape', (['regionData', '(numFrames, regionList[i].height, regionList[i].width)'], {'order': '"""C"""'}), "(regionData, (numFrames, regionList[i].height, regionList[i].\n width), order='C')\n", (2691, 2775), True, 'import numpy as np\n'), ((2931, 2968), 'numpy.fromstring', 'np.fromstring', (['child[0].text'], {'sep': '""","""'}), "(child[0].text, sep=',')\n", (2944, 2968), True, 'import numpy as np\n'), ((3478, 3517), 'numpy.fromfile', 'np.fromfile', (['f'], {'dtype': 'np.int16', 'count': '(1)'}), '(f, dtype=np.int16, count=1)\n', (3489, 3517), True, 'import numpy as np\n'), ((3766, 3805), 'numpy.fromfile', 'np.fromfile', (['f'], {'dtype': 'np.int32', 'count': '(1)'}), '(f, dtype=np.int32, count=1)\n', (3777, 3805), True, 'import numpy as np\n'), ((3884, 3914), 'numpy.dtype', 'np.dtype', (['dataTypes2[datatype]'], {}), '(dataTypes2[datatype])\n', (3892, 3914), True, 'import numpy as np\n'), ((4379, 4450), 'numpy.reshape', 'np.reshape', (['regionData', '(numFrames, frameHeight, frameWidth)'], {'order': '"""C"""'}), "(regionData, (numFrames, frameHeight, frameWidth), order='C')\n", (4389, 4450), True, 'import numpy as np\n'), ((3574, 3614), 'numpy.fromfile', 'np.fromfile', (['f'], {'dtype': 'np.uint16', 'count': '(1)'}), '(f, dtype=np.uint16, count=1)\n', (3585, 3614), True, 'import numpy as np\n'), ((3674, 3714), 'numpy.fromfile', 'np.fromfile', (['f'], {'dtype': 'np.uint16', 'count': '(1)'}), '(f, dtype=np.uint16, count=1)\n', (3685, 3714), True, 'import numpy as np\n'), ((2448, 2494), 'numpy.int', 'np.int', (['(regionOffset + j * readoutStride / bpp)'], {}), '(regionOffset + j * readoutStride / bpp)\n', (2454, 2494), True, 'import numpy as np\n'), ((4185, 4221), 'numpy.int', 'np.int', (['(j * frameWidth * frameHeight)'], {}), '(j * frameWidth * frameHeight)\n', (4191, 4221), True, 'import numpy as np\n')]
|
from astropy.tests.helper import pytest
import numpy as np
from .. import Model
from .test_helpers import random_id, get_test_dust
from ...grid import AMRGrid
@pytest.mark.parametrize(('direction'), ['x', 'y', 'z'])
def test_amr_differing_widths(tmpdir, direction):
# Widths of grids in same level are not the same
dust = get_test_dust()
amr = AMRGrid()
level1 = amr.add_level()
grid1 = level1.add_grid()
grid1.nx = grid1.ny = grid1.nz = 4
grid1.xmin = grid1.ymin = grid1.zmin = -10.
grid1.xmax = grid1.ymax = grid1.zmax = +10.
grid1.quantities['density'] = np.ones(grid1.shape) * 1.e-10
grid2 = level1.add_grid()
grid2.nx = grid2.ny = grid2.nz = 4
grid2.xmin = grid2.ymin = grid2.zmin = -10.
grid2.xmax = grid2.ymax = grid2.zmax = +10.
grid2.quantities['density'] = np.ones(grid2.shape) * 1.e-10
setattr(grid2, direction + 'min', -10.1)
m = Model()
m.set_grid(amr)
m.add_density_grid(amr['density'], dust)
m.set_n_photons(initial=1, imaging=0)
m.write(tmpdir.join(random_id()).strpath)
log_file = tmpdir.join(random_id()).strpath
with pytest.raises(SystemExit) as exc:
m.run(tmpdir.join(random_id()).strpath, logfile=log_file)
assert exc.value.args[0] == 'An error occurred, and the run did not ' + \
'complete'
assert ('Grids 1 and 2 in level 1 have differing cell widths in the %s \n direction ( 5.0000E+00 and 5.0250E+00 respectively)' % direction) in open(log_file).read()
@pytest.mark.parametrize(('direction'), ['x', 'y', 'z'])
def test_amr_misaligned_grids_same_level(tmpdir, direction):
# Widths of grids in same level are not the same
dust = get_test_dust()
amr = AMRGrid()
level1 = amr.add_level()
grid1 = level1.add_grid()
grid1.nx = grid1.ny = grid1.nz = 4
grid1.xmin = grid1.ymin = grid1.zmin = -10.
grid1.xmax = grid1.ymax = grid1.zmax = +10.
grid1.quantities['density'] = np.ones(grid1.shape) * 1.e-10
grid2 = level1.add_grid()
grid2.nx = grid2.ny = grid2.nz = 4
grid2.xmin = grid2.ymin = grid2.zmin = -10.
grid2.xmax = grid2.ymax = grid2.zmax = +10.
grid2.quantities['density'] = np.ones(grid2.shape) * 1.e-10
setattr(grid2, direction + 'min', -10.1)
setattr(grid2, direction + 'max', 9.9)
m = Model()
m.set_grid(amr)
m.add_density_grid(amr['density'], dust)
m.set_n_photons(initial=1, imaging=0)
m.write(tmpdir.join(random_id()).strpath)
log_file = tmpdir.join(random_id()).strpath
with pytest.raises(SystemExit) as exc:
m.run(tmpdir.join(random_id()).strpath, logfile=log_file)
assert exc.value.args[0] == 'An error occurred, and the run did not ' + \
'complete'
assert ('Grids 1 and 2 in level 1 have edges that are not separated by \n an integer number of cells in the %s direction' % direction) in open(log_file).read()
@pytest.mark.parametrize(('direction'), ['x', 'y', 'z'])
def test_amr_non_integer_refinement(tmpdir, direction):
# Widths of grids in same level are not the same
dust = get_test_dust()
amr = AMRGrid()
level1 = amr.add_level()
grid1 = level1.add_grid()
grid1.nx = grid1.ny = grid1.nz = 4
grid1.xmin = grid1.ymin = grid1.zmin = -10.
grid1.xmax = grid1.ymax = grid1.zmax = +10.
grid1.quantities['density'] = np.ones(grid1.shape) * 1.e-10
level2 = amr.add_level()
grid2 = level2.add_grid()
grid2.nx = grid2.ny = grid2.nz = 4
grid2.xmin = grid2.ymin = grid2.zmin = -5.
grid2.xmax = grid2.ymax = grid2.zmax = +5.
grid2.quantities['density'] = np.ones(grid2.shape) * 1.e-10
setattr(grid2, direction + 'min', -6.)
m = Model()
m.set_grid(amr)
m.add_density_grid(amr['density'], dust)
m.set_n_photons(initial=1, imaging=0)
m.write(tmpdir.join(random_id()).strpath)
log_file = tmpdir.join(random_id()).strpath
with pytest.raises(SystemExit) as exc:
m.run(tmpdir.join(random_id()).strpath, logfile=log_file)
assert exc.value.args[0] == 'An error occurred, and the run did not ' + \
'complete'
assert ('Refinement factor in the %s direction between level 1 and \n level 2 is not an integer (1.818)' % direction) in open(log_file).read()
@pytest.mark.parametrize(('direction'), ['x', 'y', 'z'])
def test_amr_not_aligned_across_levels(tmpdir, direction):
# Widths of grids in same level are not the same
dust = get_test_dust()
amr = AMRGrid()
level1 = amr.add_level()
grid1 = level1.add_grid()
grid1.nx = grid1.ny = grid1.nz = 4
grid1.xmin = grid1.ymin = grid1.zmin = -10.
grid1.xmax = grid1.ymax = grid1.zmax = +10.
grid1.quantities['density'] = np.ones(grid1.shape) * 1.e-10
level2 = amr.add_level()
grid2 = level2.add_grid()
grid2.nx = grid2.ny = grid2.nz = 4
grid2.xmin = grid2.ymin = grid2.zmin = -5.
grid2.xmax = grid2.ymax = grid2.zmax = +5.
grid2.quantities['density'] = np.ones(grid2.shape) * 1.e-10
setattr(grid2, direction + 'min', -6.)
setattr(grid2, direction + 'max', 4.)
m = Model()
m.set_grid(amr)
m.add_density_grid(amr['density'], dust)
m.set_n_photons(initial=1, imaging=0)
m.write(tmpdir.join(random_id()).strpath)
log_file = tmpdir.join(random_id()).strpath
with pytest.raises(SystemExit) as exc:
m.run(tmpdir.join(random_id()).strpath, logfile=log_file)
assert exc.value.args[0] == 'An error occurred, and the run did not ' + \
'complete'
assert ('Grid 1 in level 2 is not aligned with cells in level 1 in the \n %s direction' % direction) in open(log_file).read()
|
[
"astropy.tests.helper.pytest.mark.parametrize",
"astropy.tests.helper.pytest.raises",
"numpy.ones"
] |
[((163, 216), 'astropy.tests.helper.pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""direction"""', "['x', 'y', 'z']"], {}), "('direction', ['x', 'y', 'z'])\n", (186, 216), False, 'from astropy.tests.helper import pytest\n'), ((1540, 1593), 'astropy.tests.helper.pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""direction"""', "['x', 'y', 'z']"], {}), "('direction', ['x', 'y', 'z'])\n", (1563, 1593), False, 'from astropy.tests.helper import pytest\n'), ((2965, 3018), 'astropy.tests.helper.pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""direction"""', "['x', 'y', 'z']"], {}), "('direction', ['x', 'y', 'z'])\n", (2988, 3018), False, 'from astropy.tests.helper import pytest\n'), ((4351, 4404), 'astropy.tests.helper.pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""direction"""', "['x', 'y', 'z']"], {}), "('direction', ['x', 'y', 'z'])\n", (4374, 4404), False, 'from astropy.tests.helper import pytest\n'), ((602, 622), 'numpy.ones', 'np.ones', (['grid1.shape'], {}), '(grid1.shape)\n', (609, 622), True, 'import numpy as np\n'), ((832, 852), 'numpy.ones', 'np.ones', (['grid2.shape'], {}), '(grid2.shape)\n', (839, 852), True, 'import numpy as np\n'), ((1135, 1160), 'astropy.tests.helper.pytest.raises', 'pytest.raises', (['SystemExit'], {}), '(SystemExit)\n', (1148, 1160), False, 'from astropy.tests.helper import pytest\n'), ((1990, 2010), 'numpy.ones', 'np.ones', (['grid1.shape'], {}), '(grid1.shape)\n', (1997, 2010), True, 'import numpy as np\n'), ((2220, 2240), 'numpy.ones', 'np.ones', (['grid2.shape'], {}), '(grid2.shape)\n', (2227, 2240), True, 'import numpy as np\n'), ((2566, 2591), 'astropy.tests.helper.pytest.raises', 'pytest.raises', (['SystemExit'], {}), '(SystemExit)\n', (2579, 2591), False, 'from astropy.tests.helper import pytest\n'), ((3410, 3430), 'numpy.ones', 'np.ones', (['grid1.shape'], {}), '(grid1.shape)\n', (3417, 3430), True, 'import numpy as np\n'), ((3668, 3688), 'numpy.ones', 'np.ones', (['grid2.shape'], {}), '(grid2.shape)\n', (3675, 3688), True, 'import numpy as np\n'), ((3969, 3994), 'astropy.tests.helper.pytest.raises', 'pytest.raises', (['SystemExit'], {}), '(SystemExit)\n', (3982, 3994), False, 'from astropy.tests.helper import pytest\n'), ((4799, 4819), 'numpy.ones', 'np.ones', (['grid1.shape'], {}), '(grid1.shape)\n', (4806, 4819), True, 'import numpy as np\n'), ((5057, 5077), 'numpy.ones', 'np.ones', (['grid2.shape'], {}), '(grid2.shape)\n', (5064, 5077), True, 'import numpy as np\n'), ((5400, 5425), 'astropy.tests.helper.pytest.raises', 'pytest.raises', (['SystemExit'], {}), '(SystemExit)\n', (5413, 5425), False, 'from astropy.tests.helper import pytest\n')]
|
import cv2
import base64
import logging
import argparse
import numpy as np
from flask import Flask, Response, request, jsonify
from functions import DataSet
logging.basicConfig(level=logging.INFO)
app = Flask(
__name__
)
@app.route("/", methods=["POST"])
def index():
data = request.get_json()
src = data["image"]
img_decoded = base64.standard_b64decode(src)
img_buffer = np.frombuffer(img_decoded, np.uint8)
img = cv2.imdecode(img_buffer, 1)
res = DS.classify(img)
classes = DS.classes
if res ==-1:
class_name = "Not in DS"
elif res == None:
class_name = "No detection"
elif res != -1:
class_name = classes[res]
return jsonify({
"class": res,
"class_name": class_name
})
@app.route("/info", methods=["GET"])
def info():
return jsonify(DS.classes)
@app.route("/set_threshold", methods=["POST"])
def set_threshold():
data = request.get_json()
thr = float(data["threshold"])
DS.set_threshold(thr)
logging.info("Threshold set to {}".format(thr))
return Response(status=204)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--directory", "-dir", help="Dataset directory", type=str, default="datasets/LookDataSet2")
parser.add_argument("--extension", "-ext", help="Dataset images extension", type=str, default="jpg")
parser.add_argument("--images_per_class", "-ipc", help="Images to use per class", type=int, default=14)
parser.add_argument("--size", "-si", help="Image size", type=int, default=24)
parser.add_argument("--vertical", "-ve", help="Vertical splits", type=int, default=4)
parser.add_argument("--horizontal", "-ho", help="Horizontal splits", type=int, default=2)
parser.add_argument("--epsilon", "-e", help="Epsilon", type=float, default=0.0)
parser.add_argument("--threshold", "-t", help="Classification threshold", type=float, default=0.22)
parser.add_argument("--vis", "-v", help="Show aligned and crop images", type=bool,default=False)
args = parser.parse_args()
vis = False
DS = DataSet(
dir=args.directory,
ext=args.extension,
images_per_class=args.images_per_class,
size=args.size,
vertical=args.vertical,
horizontal=args.horizontal,
epsilon=args.epsilon,
threshold=args.threshold,
vis=args.vis
)
app.run(
host="0.0.0.0",
port="8000",
threaded=True,
debug=True,
use_reloader=False
)
|
[
"base64.standard_b64decode",
"logging.basicConfig",
"argparse.ArgumentParser",
"numpy.frombuffer",
"flask.Flask",
"cv2.imdecode",
"functions.DataSet",
"flask.jsonify",
"flask.Response",
"flask.request.get_json"
] |
[((159, 198), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (178, 198), False, 'import logging\n'), ((206, 221), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (211, 221), False, 'from flask import Flask, Response, request, jsonify\n'), ((288, 306), 'flask.request.get_json', 'request.get_json', ([], {}), '()\n', (304, 306), False, 'from flask import Flask, Response, request, jsonify\n'), ((350, 380), 'base64.standard_b64decode', 'base64.standard_b64decode', (['src'], {}), '(src)\n', (375, 380), False, 'import base64\n'), ((398, 434), 'numpy.frombuffer', 'np.frombuffer', (['img_decoded', 'np.uint8'], {}), '(img_decoded, np.uint8)\n', (411, 434), True, 'import numpy as np\n'), ((445, 472), 'cv2.imdecode', 'cv2.imdecode', (['img_buffer', '(1)'], {}), '(img_buffer, 1)\n', (457, 472), False, 'import cv2\n'), ((701, 750), 'flask.jsonify', 'jsonify', (["{'class': res, 'class_name': class_name}"], {}), "({'class': res, 'class_name': class_name})\n", (708, 750), False, 'from flask import Flask, Response, request, jsonify\n'), ((835, 854), 'flask.jsonify', 'jsonify', (['DS.classes'], {}), '(DS.classes)\n', (842, 854), False, 'from flask import Flask, Response, request, jsonify\n'), ((936, 954), 'flask.request.get_json', 'request.get_json', ([], {}), '()\n', (952, 954), False, 'from flask import Flask, Response, request, jsonify\n'), ((1081, 1101), 'flask.Response', 'Response', ([], {'status': '(204)'}), '(status=204)\n', (1089, 1101), False, 'from flask import Flask, Response, request, jsonify\n'), ((1144, 1169), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1167, 1169), False, 'import argparse\n'), ((2256, 2488), 'functions.DataSet', 'DataSet', ([], {'dir': 'args.directory', 'ext': 'args.extension', 'images_per_class': 'args.images_per_class', 'size': 'args.size', 'vertical': 'args.vertical', 'horizontal': 'args.horizontal', 'epsilon': 'args.epsilon', 'threshold': 'args.threshold', 'vis': 'args.vis'}), '(dir=args.directory, ext=args.extension, images_per_class=args.\n images_per_class, size=args.size, vertical=args.vertical, horizontal=\n args.horizontal, epsilon=args.epsilon, threshold=args.threshold, vis=\n args.vis)\n', (2263, 2488), False, 'from functions import DataSet\n')]
|
import json
from pathlib import Path
import numpy as np
import pandas as pd
from .utils import get_project_path, read_tsv
def _fetch_margulies_gradient():
"""Load Margulies gradients in Schaefer 100 space"""
path_dm_gradient = (
Path(get_project_path()) / "data/hcp/hcp_embed_1-10_Schaefer1000_7Networks.txt"
)
return read_tsv(path_dm_gradient, header=None, names=list(range(1, 11)))
def map_space(cap_val):
"""Calculate the correlation of CAP map and top 3 Margulies gradients."""
dm_gradient = _fetch_margulies_gradient()
gs = []
for i in range(3):
dm = dm_gradient[i + 1]
gs.append(np.corrcoef(cap_val[:1000], dm)[0, 1])
return tuple(gs)
def cap_to_gradient(data_path=None):
"""Map all cap map to gradient space on real data."""
if Path(data_path).exists:
return read_tsv(data_path)
# load data collection
path_cap_collection = Path(get_project_path()) / "data/cap.json"
with open(path_cap_collection) as json_file:
path_cap = json.load(json_file)
# load group cap and map to gradient space
path_group_cap = path_cap["group"]
group_cap = read_tsv(path_group_cap, index_col=0)
gradient_space = {
label: {"group": map_space(cap_val)} for label, cap_val in group_cap.items()
}
# load subject cap and map to gradient space
for sub, path in path_cap["subject"].items():
sub_cap = read_tsv(path, index_col=0)
for label, cap_val in sub_cap.items():
gradient_space[label][sub] = map_space(cap_val)
# covert to dataframe
collect = []
for key in gradient_space:
df = pd.DataFrame(
gradient_space[key], index=[f"Gradient {i+1}" for i in range(3)]
).T
df["CAP"] = key[-2:]
df.index.name = "participant_id"
df = df.reset_index()
collect.append(df)
gradient_space = pd.concat(collect, axis=0)
if data_path:
gradient_space.to_csv(data_path, sep="\t", index=False)
return gradient_space
|
[
"numpy.corrcoef",
"pathlib.Path",
"json.load",
"pandas.concat"
] |
[((1903, 1929), 'pandas.concat', 'pd.concat', (['collect'], {'axis': '(0)'}), '(collect, axis=0)\n', (1912, 1929), True, 'import pandas as pd\n'), ((812, 827), 'pathlib.Path', 'Path', (['data_path'], {}), '(data_path)\n', (816, 827), False, 'from pathlib import Path\n'), ((1035, 1055), 'json.load', 'json.load', (['json_file'], {}), '(json_file)\n', (1044, 1055), False, 'import json\n'), ((648, 679), 'numpy.corrcoef', 'np.corrcoef', (['cap_val[:1000]', 'dm'], {}), '(cap_val[:1000], dm)\n', (659, 679), True, 'import numpy as np\n')]
|
import jax
import jax.numpy as jnp
import numpy as onp
import haiku as hk
from jax.experimental import optix
from nsec.datasets.two_moons import get_two_moons
from nsec.datasets.gaussian_mixture import get_gm
from nsec.datasets.swiss_roll import get_swiss_roll
from nsec.utils import display_score_two_moons
from nsec.models.dae.ardae import ARDAE
from nsec.normalization import SNParamsTree as CustomSNParamsTree
from nsec.utils import display_score_error_gm, display_score_error_two_moons
from nsec.models.nflow.nsf import NeuralSplineCoupling, NeuralSplineFlow
from functools import partial
import matplotlib.pyplot as plt
import pickle
import os, os.path
# noise / delta
num_runs = len([name for name in os.listdir('./params')])
run_session = 'run-{}'.format(num_runs+1)
os.mkdir('params/{}'.format(run_session))
# Tow moons dataset
#distribution, dist_label, delta = get_two_moons(0.05), 'two_moons', 0.05
# Mixture 2 gaussian dataset
#distribution, dist_label, delta = get_gm(0.5), 'two_gaussians', 0.5
# Swiss roll
distribution, dist_label, delta = get_swiss_roll(0.5), 'swiss_roll', 0.5
#delta = 0.5
# Computing the true score of data distribution
true_score = jax.vmap(jax.grad(distribution.log_prob))
"""Creates AR-DAE model
"""
def forward(x, sigma, is_training=False):
denoiser = ARDAE(is_training=is_training)
return denoiser(x, sigma)
model_train = hk.transform_with_state(partial(forward, is_training=True))
batch_size = 512
delta = delta
def get_batch(rng_key):
y = distribution.sample(batch_size, seed=rng_key)
u = onp.random.randn(batch_size, 2)
s = delta * onp.random.randn(batch_size, 1)
x = y + s * u
# x is a noisy sample, y is a sample from the distribution
# u is the random normal noise realisation
return {'x':x, 'y':y, 'u':u, 's':s}
# Optimizer
optimizer = optix.adam(1e-3)
rng_seq = hk.PRNGSequence(42)
@jax.jit
def loss_fn(params, state, rng_key, batch):
res, state = model_train.apply(params, state, rng_key,
batch['x'], batch['s'])
loss = jnp.mean((batch['u'] + batch['s'] * res)**2)
return loss, state
@jax.jit
def update(params, state, rng_key, opt_state, batch):
(loss, state), grads = jax.value_and_grad(loss_fn, has_aux=True)(params, state, rng_key, batch)
updates, new_opt_state = optimizer.update(grads, opt_state)
new_params = optix.apply_updates(params, updates)
return loss, new_params, state, new_opt_state
params, state = model_train.init(next(rng_seq),
jnp.zeros((1, 2)),
jnp.ones((1, 1)))
opt_state = optimizer.init(params)
losses = []
print("Let's learn a denoising auto encoder")
for step in range(2000):
batch = get_batch(next(rng_seq))
loss, params, state, opt_state = update(params, state, next(rng_seq), opt_state, batch)
losses.append(loss)
if step%100==0:
print(step, loss)
os.mkdir('params/{}/{}_{}'.format(run_session, 'ardae', dist_label))
with open('params/{}/{}_{}/params.pickle'.format(run_session, 'ardae', dist_label), 'wb') as handle:
pickle.dump(params, handle, protocol=pickle.HIGHEST_PROTOCOL)
model = hk.transform_with_state(partial(forward, is_training=False))
dae_score = partial(model.apply, params, state, next(rng_seq))
"""Creates AR-DAE model with Lipschitz normalization
"""
#lipschitz_constants = [0.01, 0.1, 0.5, 1, 2, 5, 10]
l = 1.
os.mkdir('params/{}/{}_{}'.format(run_session, 'ardae_sn', dist_label))
def forward(x, sigma, is_training=False):
denoiser = ARDAE(is_training=is_training)
return denoiser(x, sigma)
lipschitz_constant = l
model_train = hk.transform_with_state(partial(forward, is_training=True))
sn_fn = hk.transform_with_state(lambda x: CustomSNParamsTree(ignore_regex='[^?!.]*b$', val=lipschitz_constant)(x))
batch_size = 512
delta = delta
def get_batch(rng_key):
y = distribution.sample(batch_size, seed=rng_key)
u = onp.random.randn(batch_size, 2)
s = delta * onp.random.randn(batch_size, 1)
x = y + s * u
# x is a noisy sample, y is a sample from the distribution
# u is the random normal noise realisation
return {'x':x, 'y':y, 'u':u, 's':s}
optimizer = optix.adam(1e-3)
rng_seq = hk.PRNGSequence(42)
@jax.jit
def loss_fn(params, state, rng_key, batch):
res, state = model_train.apply(params, state, rng_key,
batch['x'], batch['s'])
loss = jnp.mean((batch['u'] + batch['s'] * res)**2)
return loss, state
@jax.jit
def update(params, state, sn_state, rng_key, opt_state, batch):
(loss, state), grads = jax.value_and_grad(loss_fn, has_aux=True)(params, state, rng_key, batch)
updates, new_opt_state = optimizer.update(grads, opt_state)
new_params = optix.apply_updates(params, updates)
new_params, new_sn_state = sn_fn.apply(None, sn_state, None, new_params)
return loss, new_params, state, new_sn_state, new_opt_state
params, state = model_train.init(next(rng_seq),
jnp.zeros((1, 2)),
jnp.ones((1, 1)))
opt_state = optimizer.init(params)
_, sn_state = sn_fn.init(jax.random.PRNGKey(1), params)
losses = []
print("Let's learn a denoising auto encoder with spectral normalization (cte = {})".format(lipschitz_constant))
for step in range(2000):
batch = get_batch(next(rng_seq))
loss, params, state, sn_state, opt_state = update(params, state, sn_state, next(rng_seq), opt_state, batch)
losses.append(loss)
if step%100==0:
print(step, loss)
with open('params/{}/{}_{}/params-{}.pickle'.format(run_session, 'ardae_sn', dist_label, lipschitz_constant), 'wb') as handle:
pickle.dump(params, handle, protocol=pickle.HIGHEST_PROTOCOL)
model_sn = hk.transform_with_state(partial(forward, is_training=False))
score_sn = partial(model_sn.apply, params, state, next(rng_seq))
scores = [dae_score, score_sn]
labels = ['DAE', 'SN DAE']
print("Let's build a Neural Spline Flow")
"""Build a Normalizing follows
"""
"""
def forwardNF(x):
flow = NeuralSplineFlow()
return flow(x)
optimizer = optix.adam(1e-4)
rng_seq = hk.PRNGSequence(42)
batch_size = 512
def make_samples(rng_seq, n_samples, gm):
return gm.sample(n_samples, seed = next(rng_seq))
def get_batch():
x = make_samples(rng_seq, batch_size,distribution)
return {'x': x}
model_NF = hk.transform(forwardNF, apply_rng=True)
@jax.jit
def loss_fn(params, rng_key, batch):
log_prob = model_NF.apply(params, rng_key, batch['x'])
return -jnp.mean(log_prob)
@jax.jit
def update(params, rng_key, opt_state, batch):
loss, grads = jax.value_and_grad(loss_fn)(params, rng_key, batch)
updates, new_opt_state = optimizer.update(grads, opt_state)
new_params = optix.apply_updates(params, updates)
return loss, new_params, new_opt_state
params = model_NF.init(next(rng_seq), jnp.zeros((1, 2)))
opt_state = optimizer.init(params)
losses = []
for step in range(2000):
batch = get_batch()
loss, params, opt_state = update(params, next(rng_seq), opt_state, batch)
losses.append(loss)
if step%100==0:
print(loss)
os.mkdir('params/{}/{}_{}'.format(run_session, 'normalizing-flow', dist_label))
with open('params/{}/{}_{}/params.pickle'.format(run_session, 'normalizing-flow', dist_label), 'wb') as handle:
pickle.dump(params, handle, protocol=pickle.HIGHEST_PROTOCOL)
log_prob = partial(model_NF.apply, params, next(rng_seq))
log_prob(jnp.zeros(2).reshape(1,2)).shape
def log_prob_reshaped(x):
x = x.reshape([1,-1])
return jnp.reshape(log_prob(x), ())
score_NF = jax.vmap(jax.grad(log_prob_reshaped))
"""
if dist_label=='two_moons':
scale = 3
offset = jnp.array([0., 0.])
d_offset = jnp.array([.5, .25])
c1 = scale * (jnp.array([-.7, -0.5])) + d_offset + offset
c2 = scale * (jnp.array([.7, 0.5])) + d_offset + offset
elif dist_label=='two_gaussians':
scale = 1
offset = jnp.array([0., 0.])
c1 = scale * jnp.array([-7., -7]) + offset
c2 = scale * jnp.array([7., 7]) + offset
elif dist_label=='swiss_roll':
scale = 4
offset = jnp.array([0., 0.])
c1 = scale * jnp.array([-7., -7]) + offset
c2 = scale * jnp.array([7., 7]) + offset
#X = np.arange(c1[0], c2[0], 0.1)
#Y = np.arange(c1[1], c2[1], 0.1)
n = 100
X = jnp.linspace(c1[0], c2[0], int(n*7/5))
Y = jnp.linspace(c1[1], c2[1], n)
points = jnp.stack(jnp.meshgrid(X, Y), axis=-1).reshape((-1, 2))
estimated_sn, state = score_sn(points, 0.0*jnp.ones((len(points),1)))
estimated_sn = estimated_sn.reshape([len(Y), len(X),2])/jnp.linalg.norm(estimated_sn)
estimated_dae, state = dae_score(points, 0.0*jnp.ones((len(points),1)))
estimated_dae = estimated_dae.reshape([len(Y), len(X),2])/jnp.linalg.norm(estimated_dae)
"""
estimated_nf = score_NF(points)
estimated_nf = estimated_nf.reshape([len(Y), len(X),2])/jnp.linalg.norm(estimated_nf)
"""
true_score = jax.vmap(jax.grad(distribution.log_prob))
true_s = true_score(points)
true_s = true_s.reshape([len(Y), len(X),2])/jnp.linalg.norm(true_s)
errors_sn = jnp.linalg.norm(estimated_sn - true_s, axis=2)
errors_dae = jnp.linalg.norm(estimated_dae - true_s, axis=2)
"""
errors_nf = jnp.linalg.norm(estimated_nf - true_s, axis=2)
errors = [errors_sn, errors_dae, errors_nf]
"""
errors = [errors_sn, errors_dae]
v_min = jnp.min([jnp.min(e) for e in errors[:-1]])
v_max = jnp.max([jnp.max(e) for e in errors[:-1]])
#plt.figure(dpi=100)
#plt.subplot(131)
plt.subplot(221)
plt.title('DAE', fontsize=9)
plt.imshow(errors_dae, origin='lower', vmin=v_min, vmax=v_max)
plt.colorbar()
plt.subplot(222)
g = estimated_dae
plt.quiver(X[::4], Y[::4], g[::4,::4,0], g[::4,::4,1])
plt.subplot(223)
plt.title('DAE w/ SN', fontsize=9)
plt.imshow(errors_sn, origin='lower', vmin=v_min, vmax=v_max)
plt.colorbar()
plt.subplot(224)
g = estimated_sn
plt.quiver(X[::4], Y[::4], g[::4,::4,0], g[::4,::4,1])
#plt.subplot(133)
#plt.title('distribution')
#a = distribution.log_prob(points)
#lp = a.reshape([len(Y), len(X)])
#plt.contourf(X,Y,lp,256,vmin=-30)
"""
plt.subplot(133)
plt.title('NSF', fontsize=9)
plt.imshow(errors_nf, origin='lower', vmin=v_min, vmax=v_max)
plt.colorbar()
"""
plt.tight_layout()
"""
plt.savefig('images/generalization_score_error.png')
"""
plt.show()
#plt.imshow(errors[i], origin='lower', vmin=v_min, vmax=v_max)
#plt.subplot(122)
#quiver(X[::4], Y[::4], estimated_s[::4,::4,0], estimated_s[::4,::4,1]);
#curve_error = []
"""
estimated_sn, state = score_sn(points, 0.0*jnp.ones((len(points),1)))
estimated_sn /= jnp.linalg.norm(estimated_sn)
estimated_dae, state = dae_score(points, 0.0*jnp.ones((len(points),1)))
estimated_dae /= jnp.linalg.norm(estimated_dae)
estimated_nf = score_NF(points)
estimated_nf /= jnp.linalg.norm(estimated_nf)
true_s = true_score(points)
true_s /= onp.linalg.norm(true_s)
error_sn = onp.linalg.norm(estimated_sn - true_s, axis=1)
error_dae = onp.linalg.norm(estimated_dae - true_s, axis=1)
error_nf = onp.linalg.norm(estimated_nf - true_s, axis=1)
distance = distribution.log_prob(points)
argsort_distance = distance.argsort()
distance = distance[argsort_distance]
error_sn = error_sn[argsort_distance]
error_dae = error_dae[argsort_distance]
error_nf = error_nf[argsort_distance]
"""
"""
table_sn = jnp.stack([distance, error_sn])
table_sn = jnp.sort(table_sn, 1)
table_dae = jnp.stack([distance, error_dae])
table_dae = jnp.sort(table_dae, 1)
table_nf = jnp.stack([distance, error_nf])
table_nf = jnp.sort(table_nf, 1)
"""
"""
n_p = distance.shape[0]
r = 100
table_dae_bined = onp.zeros((2, n_p//r))
d_dae = onp.zeros(n_p//r)
table_sn_bined = onp.zeros((2, n_p//r))
d_sn = onp.zeros(n_p//r)
table_nf_bined = onp.zeros((2, n_p//r))
d_nf = onp.zeros(n_p//r)
for i in range(n_p//r):
a = int(i*r)
b = int((i+1)*r)
table_dae_bined[0, i] = onp.mean(distance[a:b])
table_dae_bined[1, i] = onp.mean(error_dae[a:b])
d_dae[i] = onp.std(error_dae[a:b])/2
table_sn_bined[0, i] = onp.mean(distance[a:b])
table_sn_bined[1, i] = onp.mean(error_sn[a:b])
d_sn[i] = jnp.std(error_sn[a:b])/2
table_nf_bined[0, i] = onp.mean(distance[a:b])
table_nf_bined[1, i] = onp.mean(error_nf[a:b])
d_nf[i] = onp.std(error_nf[a:b])/2
plt.figure(dpi=120)
plt.plot(table_nf_bined[0,:], table_nf_bined[1,:], alpha=1, label='NSF', color='green')
plt.fill_between(table_nf_bined[0,:], table_nf_bined[1,:] - d_nf, table_nf_bined[1,:] + d_nf,
color='green', alpha=0.2)
plt.plot(table_dae_bined[0,:], table_dae_bined[1,:], alpha=1, label='DAE', color='red')
plt.fill_between(table_dae_bined[0,:], table_dae_bined[1,:] - d_dae, table_dae_bined[1,:] + d_dae,
color='red', alpha=0.2)
plt.plot(table_sn_bined[0,:], table_sn_bined[1,:], alpha=1, label='DAE w/ SN', color='blue')
plt.fill_between(table_sn_bined[0,:], table_sn_bined[1,:] - d_sn, table_sn_bined[1,:] + d_sn,
color='blue', alpha=0.2)
plt.ylabel('average error')
plt.xlabel('$\log p(x)$')
#plt.xscale('symlog')
plt.ylim((-.0005, .04))
#plt.xscale('log')
plt.legend()
plt.savefig('images/generalization_error_distance.png')
plt.show()
"""
|
[
"matplotlib.pyplot.title",
"pickle.dump",
"matplotlib.pyplot.quiver",
"jax.random.PRNGKey",
"matplotlib.pyplot.tight_layout",
"nsec.models.dae.ardae.ARDAE",
"jax.experimental.optix.adam",
"numpy.random.randn",
"matplotlib.pyplot.imshow",
"jax.numpy.linspace",
"matplotlib.pyplot.colorbar",
"jax.numpy.linalg.norm",
"jax.numpy.min",
"jax.numpy.meshgrid",
"jax.experimental.optix.apply_updates",
"functools.partial",
"matplotlib.pyplot.show",
"nsec.normalization.SNParamsTree",
"haiku.PRNGSequence",
"jax.numpy.ones",
"jax.numpy.zeros",
"os.listdir",
"nsec.datasets.swiss_roll.get_swiss_roll",
"matplotlib.pyplot.subplot",
"jax.numpy.array",
"jax.numpy.max",
"jax.value_and_grad",
"jax.grad",
"jax.numpy.mean"
] |
[((1829, 1846), 'jax.experimental.optix.adam', 'optix.adam', (['(0.001)'], {}), '(0.001)\n', (1839, 1846), False, 'from jax.experimental import optix\n'), ((1856, 1875), 'haiku.PRNGSequence', 'hk.PRNGSequence', (['(42)'], {}), '(42)\n', (1871, 1875), True, 'import haiku as hk\n'), ((4205, 4222), 'jax.experimental.optix.adam', 'optix.adam', (['(0.001)'], {}), '(0.001)\n', (4215, 4222), False, 'from jax.experimental import optix\n'), ((4232, 4251), 'haiku.PRNGSequence', 'hk.PRNGSequence', (['(42)'], {}), '(42)\n', (4247, 4251), True, 'import haiku as hk\n'), ((8345, 8374), 'jax.numpy.linspace', 'jnp.linspace', (['c1[1]', 'c2[1]', 'n'], {}), '(c1[1], c2[1], n)\n', (8357, 8374), True, 'import jax.numpy as jnp\n'), ((9052, 9098), 'jax.numpy.linalg.norm', 'jnp.linalg.norm', (['(estimated_sn - true_s)'], {'axis': '(2)'}), '(estimated_sn - true_s, axis=2)\n', (9067, 9098), True, 'import jax.numpy as jnp\n'), ((9112, 9159), 'jax.numpy.linalg.norm', 'jnp.linalg.norm', (['(estimated_dae - true_s)'], {'axis': '(2)'}), '(estimated_dae - true_s, axis=2)\n', (9127, 9159), True, 'import jax.numpy as jnp\n'), ((9449, 9465), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(221)'], {}), '(221)\n', (9460, 9465), True, 'import matplotlib.pyplot as plt\n'), ((9466, 9494), 'matplotlib.pyplot.title', 'plt.title', (['"""DAE"""'], {'fontsize': '(9)'}), "('DAE', fontsize=9)\n", (9475, 9494), True, 'import matplotlib.pyplot as plt\n'), ((9495, 9557), 'matplotlib.pyplot.imshow', 'plt.imshow', (['errors_dae'], {'origin': '"""lower"""', 'vmin': 'v_min', 'vmax': 'v_max'}), "(errors_dae, origin='lower', vmin=v_min, vmax=v_max)\n", (9505, 9557), True, 'import matplotlib.pyplot as plt\n'), ((9558, 9572), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (9570, 9572), True, 'import matplotlib.pyplot as plt\n'), ((9574, 9590), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(222)'], {}), '(222)\n', (9585, 9590), True, 'import matplotlib.pyplot as plt\n'), ((9609, 9667), 'matplotlib.pyplot.quiver', 'plt.quiver', (['X[::4]', 'Y[::4]', 'g[::4, ::4, 0]', 'g[::4, ::4, 1]'], {}), '(X[::4], Y[::4], g[::4, ::4, 0], g[::4, ::4, 1])\n', (9619, 9667), True, 'import matplotlib.pyplot as plt\n'), ((9665, 9681), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(223)'], {}), '(223)\n', (9676, 9681), True, 'import matplotlib.pyplot as plt\n'), ((9682, 9716), 'matplotlib.pyplot.title', 'plt.title', (['"""DAE w/ SN"""'], {'fontsize': '(9)'}), "('DAE w/ SN', fontsize=9)\n", (9691, 9716), True, 'import matplotlib.pyplot as plt\n'), ((9717, 9778), 'matplotlib.pyplot.imshow', 'plt.imshow', (['errors_sn'], {'origin': '"""lower"""', 'vmin': 'v_min', 'vmax': 'v_max'}), "(errors_sn, origin='lower', vmin=v_min, vmax=v_max)\n", (9727, 9778), True, 'import matplotlib.pyplot as plt\n'), ((9779, 9793), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (9791, 9793), True, 'import matplotlib.pyplot as plt\n'), ((9795, 9811), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(224)'], {}), '(224)\n', (9806, 9811), True, 'import matplotlib.pyplot as plt\n'), ((9829, 9887), 'matplotlib.pyplot.quiver', 'plt.quiver', (['X[::4]', 'Y[::4]', 'g[::4, ::4, 0]', 'g[::4, ::4, 1]'], {}), '(X[::4], Y[::4], g[::4, ::4, 0], g[::4, ::4, 1])\n', (9839, 9887), True, 'import matplotlib.pyplot as plt\n'), ((10166, 10184), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (10182, 10184), True, 'import matplotlib.pyplot as plt\n'), ((10247, 10257), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (10255, 10257), True, 'import matplotlib.pyplot as plt\n'), ((1060, 1079), 'nsec.datasets.swiss_roll.get_swiss_roll', 'get_swiss_roll', (['(0.5)'], {}), '(0.5)\n', (1074, 1079), False, 'from nsec.datasets.swiss_roll import get_swiss_roll\n'), ((1184, 1215), 'jax.grad', 'jax.grad', (['distribution.log_prob'], {}), '(distribution.log_prob)\n', (1192, 1215), False, 'import jax\n'), ((1303, 1333), 'nsec.models.dae.ardae.ARDAE', 'ARDAE', ([], {'is_training': 'is_training'}), '(is_training=is_training)\n', (1308, 1333), False, 'from nsec.models.dae.ardae import ARDAE\n'), ((1402, 1436), 'functools.partial', 'partial', (['forward'], {'is_training': '(True)'}), '(forward, is_training=True)\n', (1409, 1436), False, 'from functools import partial\n'), ((1556, 1587), 'numpy.random.randn', 'onp.random.randn', (['batch_size', '(2)'], {}), '(batch_size, 2)\n', (1572, 1587), True, 'import numpy as onp\n'), ((2060, 2106), 'jax.numpy.mean', 'jnp.mean', (["((batch['u'] + batch['s'] * res) ** 2)"], {}), "((batch['u'] + batch['s'] * res) ** 2)\n", (2068, 2106), True, 'import jax.numpy as jnp\n'), ((2373, 2409), 'jax.experimental.optix.apply_updates', 'optix.apply_updates', (['params', 'updates'], {}), '(params, updates)\n', (2392, 2409), False, 'from jax.experimental import optix\n'), ((2542, 2559), 'jax.numpy.zeros', 'jnp.zeros', (['(1, 2)'], {}), '((1, 2))\n', (2551, 2559), True, 'import jax.numpy as jnp\n'), ((2594, 2610), 'jax.numpy.ones', 'jnp.ones', (['(1, 1)'], {}), '((1, 1))\n', (2602, 2610), True, 'import jax.numpy as jnp\n'), ((3107, 3168), 'pickle.dump', 'pickle.dump', (['params', 'handle'], {'protocol': 'pickle.HIGHEST_PROTOCOL'}), '(params, handle, protocol=pickle.HIGHEST_PROTOCOL)\n', (3118, 3168), False, 'import pickle\n'), ((3202, 3237), 'functools.partial', 'partial', (['forward'], {'is_training': '(False)'}), '(forward, is_training=False)\n', (3209, 3237), False, 'from functools import partial\n'), ((3551, 3581), 'nsec.models.dae.ardae.ARDAE', 'ARDAE', ([], {'is_training': 'is_training'}), '(is_training=is_training)\n', (3556, 3581), False, 'from nsec.models.dae.ardae import ARDAE\n'), ((3675, 3709), 'functools.partial', 'partial', (['forward'], {'is_training': '(True)'}), '(forward, is_training=True)\n', (3682, 3709), False, 'from functools import partial\n'), ((3944, 3975), 'numpy.random.randn', 'onp.random.randn', (['batch_size', '(2)'], {}), '(batch_size, 2)\n', (3960, 3975), True, 'import numpy as onp\n'), ((4436, 4482), 'jax.numpy.mean', 'jnp.mean', (["((batch['u'] + batch['s'] * res) ** 2)"], {}), "((batch['u'] + batch['s'] * res) ** 2)\n", (4444, 4482), True, 'import jax.numpy as jnp\n'), ((4759, 4795), 'jax.experimental.optix.apply_updates', 'optix.apply_updates', (['params', 'updates'], {}), '(params, updates)\n', (4778, 4795), False, 'from jax.experimental import optix\n'), ((5020, 5037), 'jax.numpy.zeros', 'jnp.zeros', (['(1, 2)'], {}), '((1, 2))\n', (5029, 5037), True, 'import jax.numpy as jnp\n'), ((5072, 5088), 'jax.numpy.ones', 'jnp.ones', (['(1, 1)'], {}), '((1, 1))\n', (5080, 5088), True, 'import jax.numpy as jnp\n'), ((5151, 5172), 'jax.random.PRNGKey', 'jax.random.PRNGKey', (['(1)'], {}), '(1)\n', (5169, 5172), False, 'import jax\n'), ((5683, 5744), 'pickle.dump', 'pickle.dump', (['params', 'handle'], {'protocol': 'pickle.HIGHEST_PROTOCOL'}), '(params, handle, protocol=pickle.HIGHEST_PROTOCOL)\n', (5694, 5744), False, 'import pickle\n'), ((5781, 5816), 'functools.partial', 'partial', (['forward'], {'is_training': '(False)'}), '(forward, is_training=False)\n', (5788, 5816), False, 'from functools import partial\n'), ((7698, 7719), 'jax.numpy.array', 'jnp.array', (['[0.0, 0.0]'], {}), '([0.0, 0.0])\n', (7707, 7719), True, 'import jax.numpy as jnp\n'), ((7733, 7755), 'jax.numpy.array', 'jnp.array', (['[0.5, 0.25]'], {}), '([0.5, 0.25])\n', (7742, 7755), True, 'import jax.numpy as jnp\n'), ((8568, 8597), 'jax.numpy.linalg.norm', 'jnp.linalg.norm', (['estimated_sn'], {}), '(estimated_sn)\n', (8583, 8597), True, 'import jax.numpy as jnp\n'), ((8729, 8759), 'jax.numpy.linalg.norm', 'jnp.linalg.norm', (['estimated_dae'], {}), '(estimated_dae)\n', (8744, 8759), True, 'import jax.numpy as jnp\n'), ((8910, 8941), 'jax.grad', 'jax.grad', (['distribution.log_prob'], {}), '(distribution.log_prob)\n', (8918, 8941), False, 'import jax\n'), ((9015, 9038), 'jax.numpy.linalg.norm', 'jnp.linalg.norm', (['true_s'], {}), '(true_s)\n', (9030, 9038), True, 'import jax.numpy as jnp\n'), ((1604, 1635), 'numpy.random.randn', 'onp.random.randn', (['batch_size', '(1)'], {}), '(batch_size, 1)\n', (1620, 1635), True, 'import numpy as onp\n'), ((2219, 2260), 'jax.value_and_grad', 'jax.value_and_grad', (['loss_fn'], {'has_aux': '(True)'}), '(loss_fn, has_aux=True)\n', (2237, 2260), False, 'import jax\n'), ((3992, 4023), 'numpy.random.randn', 'onp.random.randn', (['batch_size', '(1)'], {}), '(batch_size, 1)\n', (4008, 4023), True, 'import numpy as onp\n'), ((4605, 4646), 'jax.value_and_grad', 'jax.value_and_grad', (['loss_fn'], {'has_aux': '(True)'}), '(loss_fn, has_aux=True)\n', (4623, 4646), False, 'import jax\n'), ((7938, 7959), 'jax.numpy.array', 'jnp.array', (['[0.0, 0.0]'], {}), '([0.0, 0.0])\n', (7947, 7959), True, 'import jax.numpy as jnp\n'), ((9323, 9333), 'jax.numpy.min', 'jnp.min', (['e'], {}), '(e)\n', (9330, 9333), True, 'import jax.numpy as jnp\n'), ((9374, 9384), 'jax.numpy.max', 'jnp.max', (['e'], {}), '(e)\n', (9381, 9384), True, 'import jax.numpy as jnp\n'), ((710, 732), 'os.listdir', 'os.listdir', (['"""./params"""'], {}), "('./params')\n", (720, 732), False, 'import os, os.path\n'), ((3753, 3821), 'nsec.normalization.SNParamsTree', 'CustomSNParamsTree', ([], {'ignore_regex': '"""[^?!.]*b$"""', 'val': 'lipschitz_constant'}), "(ignore_regex='[^?!.]*b$', val=lipschitz_constant)\n", (3771, 3821), True, 'from nsec.normalization import SNParamsTree as CustomSNParamsTree\n'), ((8108, 8129), 'jax.numpy.array', 'jnp.array', (['[0.0, 0.0]'], {}), '([0.0, 0.0])\n', (8117, 8129), True, 'import jax.numpy as jnp\n'), ((8395, 8413), 'jax.numpy.meshgrid', 'jnp.meshgrid', (['X', 'Y'], {}), '(X, Y)\n', (8407, 8413), True, 'import jax.numpy as jnp\n'), ((7772, 7795), 'jax.numpy.array', 'jnp.array', (['[-0.7, -0.5]'], {}), '([-0.7, -0.5])\n', (7781, 7795), True, 'import jax.numpy as jnp\n'), ((7834, 7855), 'jax.numpy.array', 'jnp.array', (['[0.7, 0.5]'], {}), '([0.7, 0.5])\n', (7843, 7855), True, 'import jax.numpy as jnp\n'), ((7975, 7996), 'jax.numpy.array', 'jnp.array', (['[-7.0, -7]'], {}), '([-7.0, -7])\n', (7984, 7996), True, 'import jax.numpy as jnp\n'), ((8022, 8041), 'jax.numpy.array', 'jnp.array', (['[7.0, 7]'], {}), '([7.0, 7])\n', (8031, 8041), True, 'import jax.numpy as jnp\n'), ((8145, 8166), 'jax.numpy.array', 'jnp.array', (['[-7.0, -7]'], {}), '([-7.0, -7])\n', (8154, 8166), True, 'import jax.numpy as jnp\n'), ((8192, 8211), 'jax.numpy.array', 'jnp.array', (['[7.0, 7]'], {}), '([7.0, 7])\n', (8201, 8211), True, 'import jax.numpy as jnp\n')]
|
from sklearn.datasets import make_classification, make_blobs, load_iris
from sklearn.model_selection import train_test_split
import json
import numpy as np
def iris_dataset():
iris = load_iris()
X = iris.data[:, [0, 2]]
y = iris.target
X_train, X_test, y_train, y_test = train_test_split(X, y,
train_size=0.8,
random_state=42)
return X_train, X_test, y_train, y_test
def toy_data_binary():
data = make_classification(n_samples=500,
n_features=2,
n_informative=1,
n_redundant=0,
n_repeated=0,
n_classes=2,
n_clusters_per_class=1,
class_sep=1.,
random_state=42)
X_train, X_test, y_train, y_test = train_test_split(data[0], data[1],
train_size=0.7,
random_state=42)
return X_train, X_test, y_train, y_test
def toy_data_multiclass_3_classes_():
data = make_blobs(n_samples=500,
n_features=2,
random_state=42,
centers=[[0, 1], [2, 0], [0, -2]])
X_train, X_test, y_train, y_test = train_test_split(data[0], data[1],
train_size=0.7,
random_state=42)
return X_train, X_test, y_train, y_test
def toy_data_multiclass_3_classes_separable():
data = make_blobs(n_samples=500,
n_features=2,
random_state=42,
centers=[[0, 5], [10, 0], [0, -5]],
cluster_std=0.5)
X_train, X_test, y_train, y_test = train_test_split(data[0], data[1],
train_size=0.7,
random_state=42)
return X_train, X_test, y_train, y_test
def toy_data_multiclass_3_classes_non_separable():
data = make_blobs(n_samples=500,
n_features=2,
random_state=42,
centers=[[0, 5], [10, 0], [0, -5]],
cluster_std=3.5)
X_train, X_test, y_train, y_test = train_test_split(data[0], data[1],
train_size=0.7,
random_state=42)
return X_train, X_test, y_train, y_test
def toy_data_multiclass_5_classes():
data = make_blobs(n_samples=500,
n_features=2,
random_state=42,
centers=[[0, 5], [10, 0], [0, -5], [-5, 2], [4, 1]],
cluster_std=2.)
X_train, X_test, y_train, y_test = train_test_split(data[0], data[1],
train_size=0.7,
random_state=42)
return X_train, X_test, y_train, y_test
def data_loader_mnist(dataset='mnist_subset.json'):
# This function reads the MNIST data and separate it into train, val, and test set
with open(dataset, 'r') as f:
data_set = json.load(f)
train_set, valid_set, test_set = data_set['train'], data_set['valid'], data_set['test']
return np.asarray(train_set[0]), \
np.asarray(test_set[0]), \
np.asarray(train_set[1]), \
np.asarray(test_set[1])
# Xtrain = train_set[0]
# Ytrain = train_set[1]
# Xvalid = valid_set[0]
# Yvalid = valid_set[1]
# Xtest = test_set[0]
# Ytest = test_set[1]
# return np.array(Xtrain).reshape(-1, 1, 28, 28), np.array(Ytrain), np.array(Xvalid).reshape(-1, 1, 28, 28),\
# np.array(Yvalid), np.array(Xtest).reshape(-1, 1, 28, 28), np.array(Ytest)
|
[
"sklearn.datasets.load_iris",
"json.load",
"sklearn.model_selection.train_test_split",
"numpy.asarray",
"sklearn.datasets.make_classification",
"sklearn.datasets.make_blobs"
] |
[((190, 201), 'sklearn.datasets.load_iris', 'load_iris', ([], {}), '()\n', (199, 201), False, 'from sklearn.datasets import make_classification, make_blobs, load_iris\n'), ((291, 346), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'train_size': '(0.8)', 'random_state': '(42)'}), '(X, y, train_size=0.8, random_state=42)\n', (307, 346), False, 'from sklearn.model_selection import train_test_split\n'), ((541, 712), 'sklearn.datasets.make_classification', 'make_classification', ([], {'n_samples': '(500)', 'n_features': '(2)', 'n_informative': '(1)', 'n_redundant': '(0)', 'n_repeated': '(0)', 'n_classes': '(2)', 'n_clusters_per_class': '(1)', 'class_sep': '(1.0)', 'random_state': '(42)'}), '(n_samples=500, n_features=2, n_informative=1,\n n_redundant=0, n_repeated=0, n_classes=2, n_clusters_per_class=1,\n class_sep=1.0, random_state=42)\n', (560, 712), False, 'from sklearn.datasets import make_classification, make_blobs, load_iris\n'), ((1000, 1067), 'sklearn.model_selection.train_test_split', 'train_test_split', (['data[0]', 'data[1]'], {'train_size': '(0.7)', 'random_state': '(42)'}), '(data[0], data[1], train_size=0.7, random_state=42)\n', (1016, 1067), False, 'from sklearn.model_selection import train_test_split\n'), ((1278, 1374), 'sklearn.datasets.make_blobs', 'make_blobs', ([], {'n_samples': '(500)', 'n_features': '(2)', 'random_state': '(42)', 'centers': '[[0, 1], [2, 0], [0, -2]]'}), '(n_samples=500, n_features=2, random_state=42, centers=[[0, 1], [\n 2, 0], [0, -2]])\n', (1288, 1374), False, 'from sklearn.datasets import make_classification, make_blobs, load_iris\n'), ((1482, 1549), 'sklearn.model_selection.train_test_split', 'train_test_split', (['data[0]', 'data[1]'], {'train_size': '(0.7)', 'random_state': '(42)'}), '(data[0], data[1], train_size=0.7, random_state=42)\n', (1498, 1549), False, 'from sklearn.model_selection import train_test_split\n'), ((1769, 1883), 'sklearn.datasets.make_blobs', 'make_blobs', ([], {'n_samples': '(500)', 'n_features': '(2)', 'random_state': '(42)', 'centers': '[[0, 5], [10, 0], [0, -5]]', 'cluster_std': '(0.5)'}), '(n_samples=500, n_features=2, random_state=42, centers=[[0, 5], [\n 10, 0], [0, -5]], cluster_std=0.5)\n', (1779, 1883), False, 'from sklearn.datasets import make_classification, make_blobs, load_iris\n'), ((2014, 2081), 'sklearn.model_selection.train_test_split', 'train_test_split', (['data[0]', 'data[1]'], {'train_size': '(0.7)', 'random_state': '(42)'}), '(data[0], data[1], train_size=0.7, random_state=42)\n', (2030, 2081), False, 'from sklearn.model_selection import train_test_split\n'), ((2305, 2419), 'sklearn.datasets.make_blobs', 'make_blobs', ([], {'n_samples': '(500)', 'n_features': '(2)', 'random_state': '(42)', 'centers': '[[0, 5], [10, 0], [0, -5]]', 'cluster_std': '(3.5)'}), '(n_samples=500, n_features=2, random_state=42, centers=[[0, 5], [\n 10, 0], [0, -5]], cluster_std=3.5)\n', (2315, 2419), False, 'from sklearn.datasets import make_classification, make_blobs, load_iris\n'), ((2550, 2617), 'sklearn.model_selection.train_test_split', 'train_test_split', (['data[0]', 'data[1]'], {'train_size': '(0.7)', 'random_state': '(42)'}), '(data[0], data[1], train_size=0.7, random_state=42)\n', (2566, 2617), False, 'from sklearn.model_selection import train_test_split\n'), ((2827, 2958), 'sklearn.datasets.make_blobs', 'make_blobs', ([], {'n_samples': '(500)', 'n_features': '(2)', 'random_state': '(42)', 'centers': '[[0, 5], [10, 0], [0, -5], [-5, 2], [4, 1]]', 'cluster_std': '(2.0)'}), '(n_samples=500, n_features=2, random_state=42, centers=[[0, 5], [\n 10, 0], [0, -5], [-5, 2], [4, 1]], cluster_std=2.0)\n', (2837, 2958), False, 'from sklearn.datasets import make_classification, make_blobs, load_iris\n'), ((3088, 3155), 'sklearn.model_selection.train_test_split', 'train_test_split', (['data[0]', 'data[1]'], {'train_size': '(0.7)', 'random_state': '(42)'}), '(data[0], data[1], train_size=0.7, random_state=42)\n', (3104, 3155), False, 'from sklearn.model_selection import train_test_split\n'), ((3509, 3521), 'json.load', 'json.load', (['f'], {}), '(f)\n', (3518, 3521), False, 'import json\n'), ((3626, 3650), 'numpy.asarray', 'np.asarray', (['train_set[0]'], {}), '(train_set[0])\n', (3636, 3650), True, 'import numpy as np\n'), ((3665, 3688), 'numpy.asarray', 'np.asarray', (['test_set[0]'], {}), '(test_set[0])\n', (3675, 3688), True, 'import numpy as np\n'), ((3703, 3727), 'numpy.asarray', 'np.asarray', (['train_set[1]'], {}), '(train_set[1])\n', (3713, 3727), True, 'import numpy as np\n'), ((3742, 3765), 'numpy.asarray', 'np.asarray', (['test_set[1]'], {}), '(test_set[1])\n', (3752, 3765), True, 'import numpy as np\n')]
|
from gridworld import GridWorld
import random
from collections import defaultdict
import numpy as np
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
from plot_utils import heatmap, annotate_heatmap, plotArrow
import math
def get_random_start_pos(gridworld):
width, height = len(gridworld.grid), len(gridworld.grid[0])
while True:
x = random.randint(0, width-1)
y = random.randint(0, height-1)
if(gridworld.grid[x][y] == ' '):
return (x,y)
def eps_greedy(state, Q, eps):
rnd = random.random()
if(rnd < eps):
return random.randint(0, 3)
else:
qs = [Q[(state, 0)], Q[(state, 1)], Q[(state, 2)], Q[(state, 3)]]
return np.argmax(qs)
def qDictToMatrix(Q, gridworld):
width, height = len(gridworld.grid), len(gridworld.grid[0])
m = np.empty((width, height))
for x in range(width):
for y in range(height):
state = (x,y)
qs = [Q[((state), 0)], Q[(state, 1)], Q[(state, 2)], Q[(state, 3)]]
m[x][y] = np.max(qs)
r = gridworld.get_state_reward(state)
if(r != gridworld.move_value):
m[x][y] = r
if(gridworld.grid[x][y] == '#'):
m[x][y] = None
return m
def qDictToPolicy(Q, gridworld):
width, height = len(gridworld.grid), len(gridworld.grid[0])
m = np.empty((width, height))
for x in range(width):
for y in range(height):
state = (x,y)
qs = [Q[((state), 0)], Q[(state, 1)], Q[(state, 2)], Q[(state, 3)]]
m[x][y] = np.argmax(qs)
r = gridworld.get_state_reward(state)
if(r != gridworld.move_value):
m[x][y] = None
if(gridworld.grid[x][y] == '#'):
m[x][y] = None
return m
def plotQ(Q, gridworld, title=''):
m = qDictToMatrix(Q, gridworld)
plt.title(title)
im, _ = heatmap(m.transpose())
annotate_heatmap(im)
plt.show()
def plotPolicy(Q, gridworld, title = ""):
m = qDictToPolicy(Q, gridworld)
height, width = len(m), len(m[0])
for x in range(width):
for y in range(height):
if(not math.isnan(m[x][y])):
plotArrow(height - y, x, m[x][y])
if(gridworld.grid[x][y] == 'G' or gridworld.grid[x][y] == 'P'):
plt.text(x + 0.75, height - y - 0.25, gridworld.grid[x][y], fontsize = 25)
xTicks = np.arange(0, width + 2, 1)
subXTicks = np.arange(0.5, width + 1.5, 1)
yTicks = np.arange(0, height + 2, 1)
subYTicks = np.arange(0.5, height + 1.5, 1)
axes = plt.gca()
axes.set_xticks(xTicks)
axes.set_xticks(subXTicks, minor=True)
axes.set_yticks(yTicks)
axes.set_yticks(subYTicks, minor=True)
axes.set_xlim([0.5, width + 0.5])
axes.set_ylim([0.5, height + 0.5])
axes.grid(which='minor', alpha=0.5)
plt.title(title)
plt.show()
def SARSA(gridworld, episodes = 100, eps = 0.1, lr = 0.1, g = 1):
"""
Runs episodes with epislon-greedy policy and updates q-values with SARSA.
Arguments:
gridworld : The MPD to sample from of type GridWorld.
episodes : Number of episodes to simulate.
eps : Chance to sample random action from epsilon-greedy policy.
lr : Learning rate to control how fast SARSA converges.
g : Discount factor for future rewards
Returns:
Q : Dictionary of q-values after completing run.
"""
Q = defaultdict(float)
for _ in range(episodes):
start = get_random_start_pos(gridworld)
terminal = False
state = start
last_sar = (state, -1, 0)
while not terminal:
# sample next action from policy
action = eps_greedy(state, Q, eps)
# take step and get result
new_state, reward, terminal = gridworld.move_dir(state, action)
if last_sar[1] != -1:
s, a, r = last_sar
# SARSA update
Q[(s,a)] = Q[(s,a)] + lr * (r + g * Q[(state, action)] - Q[(s,a)])
last_sar = (state, action, reward)
state = new_state
# terminal state update
s, a, r = last_sar
Q[(s,a)] = Q[(s,a)] + lr * (r - Q[(s,a)])
return Q
def QLearning(gridworld, episodes = 100, eps = 0.2, lr = 0.1, g = 1):
"""
Runs episodes with epislon-greedy policy and updates q-values with Q-Learning.
Arguments:
gridworld : The MPD to sample from of type GridWorld.
episodes : Number of episodes to simulate.
eps : Chance to sample random action from epsilon-greedy policy.
lr : Learning rate to control how fast SARSA converges.
g : Discount factor for future rewards
Returns:
Q : Dictionary of q-values after completing run.
"""
Q = defaultdict(float)
for _ in range(episodes):
start = get_random_start_pos(gridworld)
terminal = False
state = start
while not terminal:
# sample next action from policy
action = eps_greedy(state, Q, eps)
# take step and get result
new_state, reward, terminal = gridworld.move_dir(state, action)
# Q-Learning update
s, a, r, s2 = (state, action, reward, new_state)
max_Qs2 = np.max([Q[((s2), 0)], Q[(s2, 1)], Q[(s2, 2)], Q[(s2, 3)]])
Q[(s,a)] = Q[(s,a)] + lr * (r + g * max_Qs2 - Q[(s,a)])
state = new_state
return Q
def main():
grid = ''
with open("grid.lay","r") as file:
grid = file.read()
eps = 0.2
episodes = 10000
random.seed(1)
gw = GridWorld(grid)
Q = SARSA(gw, episodes=episodes, eps=eps)
# plotQ(Q, gw, f'SARSA after {episodes} episodes')
plotPolicy(Q, gw, f'SARSA: greedy-policy after {episodes} episodes')
random.seed(1)
Q = QLearning(gw, episodes=episodes, eps=eps)
# plotQ(Q, gw, f'Q-Learning after {episodes} episodes')
plotPolicy(Q, gw, f'Q-Learning: greedy-policy after {episodes} episodes')
if __name__ == '__main__':
main()
|
[
"matplotlib.pyplot.title",
"math.isnan",
"matplotlib.pyplot.show",
"random.randint",
"plot_utils.plotArrow",
"numpy.argmax",
"numpy.empty",
"plot_utils.annotate_heatmap",
"collections.defaultdict",
"random.random",
"numpy.max",
"matplotlib.use",
"numpy.arange",
"random.seed",
"matplotlib.pyplot.text",
"matplotlib.pyplot.gca",
"gridworld.GridWorld"
] |
[((119, 142), 'matplotlib.use', 'matplotlib.use', (['"""TkAgg"""'], {}), "('TkAgg')\n", (133, 142), False, 'import matplotlib\n'), ((558, 573), 'random.random', 'random.random', ([], {}), '()\n', (571, 573), False, 'import random\n'), ((848, 873), 'numpy.empty', 'np.empty', (['(width, height)'], {}), '((width, height))\n', (856, 873), True, 'import numpy as np\n'), ((1392, 1417), 'numpy.empty', 'np.empty', (['(width, height)'], {}), '((width, height))\n', (1400, 1417), True, 'import numpy as np\n'), ((1913, 1929), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (1922, 1929), True, 'import matplotlib.pyplot as plt\n'), ((1969, 1989), 'plot_utils.annotate_heatmap', 'annotate_heatmap', (['im'], {}), '(im)\n', (1985, 1989), False, 'from plot_utils import heatmap, annotate_heatmap, plotArrow\n'), ((1994, 2004), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2002, 2004), True, 'import matplotlib.pyplot as plt\n'), ((2454, 2480), 'numpy.arange', 'np.arange', (['(0)', '(width + 2)', '(1)'], {}), '(0, width + 2, 1)\n', (2463, 2480), True, 'import numpy as np\n'), ((2497, 2527), 'numpy.arange', 'np.arange', (['(0.5)', '(width + 1.5)', '(1)'], {}), '(0.5, width + 1.5, 1)\n', (2506, 2527), True, 'import numpy as np\n'), ((2541, 2568), 'numpy.arange', 'np.arange', (['(0)', '(height + 2)', '(1)'], {}), '(0, height + 2, 1)\n', (2550, 2568), True, 'import numpy as np\n'), ((2585, 2616), 'numpy.arange', 'np.arange', (['(0.5)', '(height + 1.5)', '(1)'], {}), '(0.5, height + 1.5, 1)\n', (2594, 2616), True, 'import numpy as np\n'), ((2629, 2638), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (2636, 2638), True, 'import matplotlib.pyplot as plt\n'), ((2913, 2929), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (2922, 2929), True, 'import matplotlib.pyplot as plt\n'), ((2939, 2949), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2947, 2949), True, 'import matplotlib.pyplot as plt\n'), ((3545, 3563), 'collections.defaultdict', 'defaultdict', (['float'], {}), '(float)\n', (3556, 3563), False, 'from collections import defaultdict\n'), ((4962, 4980), 'collections.defaultdict', 'defaultdict', (['float'], {}), '(float)\n', (4973, 4980), False, 'from collections import defaultdict\n'), ((5765, 5779), 'random.seed', 'random.seed', (['(1)'], {}), '(1)\n', (5776, 5779), False, 'import random\n'), ((5789, 5804), 'gridworld.GridWorld', 'GridWorld', (['grid'], {}), '(grid)\n', (5798, 5804), False, 'from gridworld import GridWorld\n'), ((5984, 5998), 'random.seed', 'random.seed', (['(1)'], {}), '(1)\n', (5995, 5998), False, 'import random\n'), ((382, 410), 'random.randint', 'random.randint', (['(0)', '(width - 1)'], {}), '(0, width - 1)\n', (396, 410), False, 'import random\n'), ((421, 450), 'random.randint', 'random.randint', (['(0)', '(height - 1)'], {}), '(0, height - 1)\n', (435, 450), False, 'import random\n'), ((608, 628), 'random.randint', 'random.randint', (['(0)', '(3)'], {}), '(0, 3)\n', (622, 628), False, 'import random\n'), ((728, 741), 'numpy.argmax', 'np.argmax', (['qs'], {}), '(qs)\n', (737, 741), True, 'import numpy as np\n'), ((1062, 1072), 'numpy.max', 'np.max', (['qs'], {}), '(qs)\n', (1068, 1072), True, 'import numpy as np\n'), ((1606, 1619), 'numpy.argmax', 'np.argmax', (['qs'], {}), '(qs)\n', (1615, 1619), True, 'import numpy as np\n'), ((5459, 5507), 'numpy.max', 'np.max', (['[Q[s2, 0], Q[s2, 1], Q[s2, 2], Q[s2, 3]]'], {}), '([Q[s2, 0], Q[s2, 1], Q[s2, 2], Q[s2, 3]])\n', (5465, 5507), True, 'import numpy as np\n'), ((2201, 2220), 'math.isnan', 'math.isnan', (['m[x][y]'], {}), '(m[x][y])\n', (2211, 2220), False, 'import math\n'), ((2239, 2272), 'plot_utils.plotArrow', 'plotArrow', (['(height - y)', 'x', 'm[x][y]'], {}), '(height - y, x, m[x][y])\n', (2248, 2272), False, 'from plot_utils import heatmap, annotate_heatmap, plotArrow\n'), ((2365, 2437), 'matplotlib.pyplot.text', 'plt.text', (['(x + 0.75)', '(height - y - 0.25)', 'gridworld.grid[x][y]'], {'fontsize': '(25)'}), '(x + 0.75, height - y - 0.25, gridworld.grid[x][y], fontsize=25)\n', (2373, 2437), True, 'import matplotlib.pyplot as plt\n')]
|
#!/usr/bin/python
# create QuantLib models from Python models
try:
import QuantLib as ql
except ModuleNotFoundError as e:
print('Error: Module QuantLibPayoffs requires a (custom) QuantLib installation.')
raise e
try:
from QuantLib import QuasiGaussianModel as qlQuasiGaussianModel
except ImportError as e:
print('Error: Module QuantLibPayoffs requires a custom QuantLib installation.')
print('It seems you do have a QuantLib installed but maybe not the custom version')
print('with payoff scripting. Checkout https://github.com/sschlenkrich/QuantLib')
raise e
import numpy as np
import sys
sys.path.append('./')
from hybmc.termstructures.YieldCurve import YieldCurve
from hybmc.models.HullWhiteModel import HullWhiteModel
from hybmc.models.QuasiGaussianModel import QuasiGaussianModel
def QuantLibYieldCurve(curve):
if isinstance(curve,YieldCurve):
today = ql.Settings.instance().evaluationDate
return ql.YieldTermStructureHandle(
ql.FlatForward(today,curve.rate,ql.Actual365Fixed()))
else:
raise NotImplementedError('Implementation of JuliaYieldCurve for %s required.' % str(type(curve)))
return
def QuantLibModel(model):
#
if isinstance(model,QuasiGaussianModel):
ytsh = QuantLibYieldCurve(model.yieldCurve)
# we need to add trivial stoch vol parameters
eta = np.array([ 0.0 for t in model._times ])
theta = 0.1 # does not matter for zero vol of vol
Gamma = np.identity(model._d + 1)
for i in range(model._d):
for j in range(model._d):
Gamma[i,j] = model._Gamma[i,j]
return qlQuasiGaussianModel(ytsh,model._d,
model._times, model._sigma, model._slope, model._curve, eta,
model._delta, model._chi, model._Gamma, theta)
else:
raise NotImplementedError('Implementation of JuliaModel for %s required.' % str(type(model)))
return
|
[
"sys.path.append",
"QuantLib.Actual365Fixed",
"QuantLib.Settings.instance",
"numpy.identity",
"numpy.array",
"QuantLib.QuasiGaussianModel"
] |
[((627, 648), 'sys.path.append', 'sys.path.append', (['"""./"""'], {}), "('./')\n", (642, 648), False, 'import sys\n'), ((1384, 1423), 'numpy.array', 'np.array', (['[(0.0) for t in model._times]'], {}), '([(0.0) for t in model._times])\n', (1392, 1423), True, 'import numpy as np\n'), ((1498, 1523), 'numpy.identity', 'np.identity', (['(model._d + 1)'], {}), '(model._d + 1)\n', (1509, 1523), True, 'import numpy as np\n'), ((1658, 1807), 'QuantLib.QuasiGaussianModel', 'qlQuasiGaussianModel', (['ytsh', 'model._d', 'model._times', 'model._sigma', 'model._slope', 'model._curve', 'eta', 'model._delta', 'model._chi', 'model._Gamma', 'theta'], {}), '(ytsh, model._d, model._times, model._sigma, model.\n _slope, model._curve, eta, model._delta, model._chi, model._Gamma, theta)\n', (1678, 1807), True, 'from QuantLib import QuasiGaussianModel as qlQuasiGaussianModel\n'), ((909, 931), 'QuantLib.Settings.instance', 'ql.Settings.instance', ([], {}), '()\n', (929, 931), True, 'import QuantLib as ql\n'), ((1035, 1054), 'QuantLib.Actual365Fixed', 'ql.Actual365Fixed', ([], {}), '()\n', (1052, 1054), True, 'import QuantLib as ql\n')]
|
from util.Logger import Logger
from util.misc_util import *
import traceback
import sys
import numpy as np
import os
def _check_attr_is_None(attr):
def _check_attr_empty(f):
def wrapper(self, *args):
ret = f(self, *args)
if getattr(self, attr) is None:
raise ValueError("%s expect not None" % attr)
return ret
return wrapper
return _check_attr_empty
class MetaTask(type):
"""Metaclass for hook inherited class's function
metaclass ref from 'https://code.i-harness.com/ko/q/11fc307'
"""
def __init__(cls, name, bases, clsdict):
# add before, after task for AbstractDataset.load
new_load = None
if 'load' in clsdict:
def new_load(self, path, limit):
try:
if self.before_load_task is None:
self.if_need_download(path)
else:
self.before_load_task()
clsdict['load'](self, path, limit)
self.after_load(limit)
except Exception:
exc_type, exc_value, exc_traceback = sys.exc_info()
err_msg = traceback.format_exception(exc_type, exc_value, exc_traceback)
self.log(*err_msg)
setattr(cls, 'load', new_load)
class DownloadInfo:
"""download information for dataset
self.url : download url
self.is_zipped :
self.zip_file_name:
self.file_type :
"""
def __init__(self, url, is_zipped=False, download_file_name=None, extracted_file_names=None):
"""create dataset download info
:type url: str
:type is_zipped: bool
:type download_file_name: str
:type extracted_file_names: list
:param url: download url
:param is_zipped: if zip file set True, else False
:param download_file_name: file name of downloaded file
:param extracted_file_names: file names of unzipped file
"""
self.url = url
self.is_zipped = is_zipped
self.download_file_name = download_file_name
self.extracted_file_names = extracted_file_names
def attrs(self):
return self.url, self.is_zipped, self.download_file_name, self.extracted_file_names
# todo may be dataset path in env_setting will be better, if automatically assign path as class name
class AbstractDataset(metaclass=MetaTask):
"""
TODO
"""
def __init__(self, preprocess=None, batch_after_task=None, before_load_task=None):
"""create dataset handler class
***bellow attrs must initiate other value after calling super()***
self.download_infos: (list) dataset download info
self.batch_keys: (str) feature label of dataset,
managing batch keys in dict_keys.dataset_batch_keys recommend
:param preprocess: injected function for preprocess dataset
:param batch_after_task: function for inject into after iter mini_batch task
:param before_load_task: function for injecting into AbstractDataset.before_load
"""
self.download_infos = []
self.batch_keys = None
self.logger = Logger(self.__class__.__name__, stdout_only=True)
self.log = self.logger.get_log()
self.preprocess = preprocess
self.batch_after_task = batch_after_task
self.data = {}
self.cursor = {}
self.data_size = 0
self.before_load_task = before_load_task
def __del__(self):
del self.data
del self.cursor
del self.logger
del self.log
del self.batch_after_task
del self.batch_keys
def __repr__(self):
return self.__class__.__name__
def if_need_download(self, path):
"""check dataset is valid and if dataset is not valid download dataset
:type path: str
:param path: dataset path
"""
try:
os.makedirs(path)
except FileExistsError:
pass
for info in self.download_infos:
is_Invalid = False
files = glob(os.path.join(path, '*'))
names = list(map(lambda file: os.path.split(file)[1], files))
if info.is_zipped:
file_list = info.extracted_file_names
else:
file_list = info.download_file_name
for data_file in file_list:
if data_file not in names:
is_Invalid = True
if is_Invalid:
head, _ = os.path.split(path)
download_file = os.path.join(head, info.download_file_name)
self.log('download %s at %s ' % (info.download_file_name, download_file))
download_from_url(info.url, download_file)
if info.is_zipped:
self.log("extract %s at %s" % (info.download_file_name, head))
extract_file(download_file, head)
def after_load(self, limit=None):
"""after task for dataset and do execute preprocess for dataset
init cursor for each batch_key
limit dataset size
execute preprocess
:type limit: int
:param limit: limit size of dataset
"""
for key in self.batch_keys:
self.cursor[key] = 0
for key in self.batch_keys:
self.data[key] = self.data[key][:limit]
for key in self.batch_keys:
self.data_size = max(len(self.data[key]), self.data_size)
self.log("batch data '%s' %d item(s) loaded" % (key, len(self.data[key])))
self.log('%s fully loaded' % self.__str__())
if self.preprocess is not None:
self.preprocess(self)
self.log('%s preprocess end' % self.__str__())
# todo may be arg path default value is None and if None just feed default dataset path
def load(self, path, limit=None):
"""
TODO
:param path:
:param limit:
:return:
"""
pass
def save(self):
raise NotImplementedError
def _append_data(self, batch_key, data):
if batch_key not in self.data:
self.data[batch_key] = data
else:
self.data[batch_key] = np.concatenate((self.data[batch_key], data))
def __next_batch(self, batch_size, key, lookup=False):
data = self.data[key]
cursor = self.cursor[key]
data_size = len(data)
# if batch size exceeds the size of data set
over_data = batch_size // data_size
if over_data > 0:
whole_data = np.concatenate((data[cursor:], data[:cursor]))
batch_to_append = np.repeat(whole_data, over_data, axis=0)
batch_size -= data_size * over_data
else:
batch_to_append = None
begin, end = cursor, (cursor + batch_size) % data_size
if begin < end:
batch = data[begin:end]
else:
first, second = data[begin:], data[:end]
batch = np.concatenate((first, second))
if batch_to_append:
batch = np.concatenate((batch_to_append, batch))
if not lookup:
self.cursor[key] = end
return batch
def next_batch(self, batch_size, batch_keys=None, lookup=False):
"""return iter mini batch
ex)
dataset.next_batch(3, ["train_x", "train_label"]) =
[[train_x1, train_x2, train_x3], [train_label1, train_label2, train_label3]]
dataset.next_batch(3, ["train_x", "train_label"], lookup=True) =
[[train_x4, train_x5, train_x6], [train_label4, train_label5, train_label6]]
dataset.next_batch(3, ["train_x", "train_label"]) =
[[train_x4, train_x5, train_x6], [train_label4, train_label5, train_label6]]
:param batch_size: size of mini batch
:param batch_keys: (iterable type) select keys,
if batch_keys length is 1 than just return mini batch
else return list of mini batch
:param lookup: lookup == True cursor will not update
:return: (numpy array type) list of mini batch, order is same with batch_keys
"""
if batch_keys is None:
batch_keys = self.batch_keys
batches = []
for key in batch_keys:
batches += [self.__next_batch(batch_size, key, lookup)]
if self.batch_after_task is not None:
batches = self.batch_after_task(batches)
if len(batches) == 1:
batches = batches[0]
return batches
class AbstractDatasetHelper:
@staticmethod
def preprocess(dataset):
"""preprocess for loaded data
:param dataset: target dataset
"""
pass
@staticmethod
def next_batch_task(batch):
"""pre process for every iteration for mini batch
* must return some mini batch
:param batch: mini batch
:return: batch
"""
return batch
@staticmethod
def load_dataset(limit=None):
"""load dataset and return dataset and input_shapes of data
* return value of input_shapes must contain every input_shape of data
:type limit: int
:param limit: limit number of dataset_size
:return: dataset, input_shapes
"""
raise NotImplementedError
|
[
"traceback.format_exception",
"os.makedirs",
"util.Logger.Logger",
"sys.exc_info",
"os.path.split",
"os.path.join",
"numpy.concatenate",
"numpy.repeat"
] |
[((3317, 3366), 'util.Logger.Logger', 'Logger', (['self.__class__.__name__'], {'stdout_only': '(True)'}), '(self.__class__.__name__, stdout_only=True)\n', (3323, 3366), False, 'from util.Logger import Logger\n'), ((4100, 4117), 'os.makedirs', 'os.makedirs', (['path'], {}), '(path)\n', (4111, 4117), False, 'import os\n'), ((6482, 6526), 'numpy.concatenate', 'np.concatenate', (['(self.data[batch_key], data)'], {}), '((self.data[batch_key], data))\n', (6496, 6526), True, 'import numpy as np\n'), ((6840, 6886), 'numpy.concatenate', 'np.concatenate', (['(data[cursor:], data[:cursor])'], {}), '((data[cursor:], data[:cursor]))\n', (6854, 6886), True, 'import numpy as np\n'), ((6918, 6958), 'numpy.repeat', 'np.repeat', (['whole_data', 'over_data'], {'axis': '(0)'}), '(whole_data, over_data, axis=0)\n', (6927, 6958), True, 'import numpy as np\n'), ((7279, 7310), 'numpy.concatenate', 'np.concatenate', (['(first, second)'], {}), '((first, second))\n', (7293, 7310), True, 'import numpy as np\n'), ((7363, 7403), 'numpy.concatenate', 'np.concatenate', (['(batch_to_append, batch)'], {}), '((batch_to_append, batch))\n', (7377, 7403), True, 'import numpy as np\n'), ((4271, 4294), 'os.path.join', 'os.path.join', (['path', '"""*"""'], {}), "(path, '*')\n", (4283, 4294), False, 'import os\n'), ((4715, 4734), 'os.path.split', 'os.path.split', (['path'], {}), '(path)\n', (4728, 4734), False, 'import os\n'), ((4768, 4811), 'os.path.join', 'os.path.join', (['head', 'info.download_file_name'], {}), '(head, info.download_file_name)\n', (4780, 4811), False, 'import os\n'), ((1216, 1230), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (1228, 1230), False, 'import sys\n'), ((1262, 1324), 'traceback.format_exception', 'traceback.format_exception', (['exc_type', 'exc_value', 'exc_traceback'], {}), '(exc_type, exc_value, exc_traceback)\n', (1288, 1324), False, 'import traceback\n'), ((4339, 4358), 'os.path.split', 'os.path.split', (['file'], {}), '(file)\n', (4352, 4358), False, 'import os\n')]
|
# -*- coding: utf-8 -*-
"""Implements the RippleNet model."""
import logging
import math
import multiprocessing as mp
import time
from collections import defaultdict
from typing import Dict, Optional, Sequence, Tuple, Union
import numpy as np
import torch
from jsonargparse import Namespace
from jsonargparse.typing import NonNegativeInt, OpenUnitInterval, PositiveInt
from sklearn.metrics import f1_score, roc_auc_score
from sklearn.model_selection import train_test_split
from torch import nn
from torch.nn import functional as F
from torch.utils.data import DataLoader
from ..data import CTRPredictionDataset, create_dataloader
from ..data.utils import adj_list_from_triplets, read_data_lastfm
from .base import BaseModel
logger = logging.getLogger(__name__)
class RippleNet(BaseModel):
def __init__(
self,
optim_args: Namespace,
dataset: str,
data_dir: str,
max_hop: PositiveInt,
num_neighbors: PositiveInt,
embed_dim: PositiveInt,
weight_kg: float = 0.0,
val_ratio: OpenUnitInterval = 0.2,
test_ratio: OpenUnitInterval = 0.2,
batch_size_train: PositiveInt = 32,
batch_size_val: Optional[PositiveInt] = None,
batch_size_test: Optional[PositiveInt] = None,
num_workers: NonNegativeInt = 0,
pin_memory: bool = True,
):
"""Constructs a RippleNet model.
Args:
optim_args: Arguments for optimization.
dataset: Name of the dataset.
data_dir: Directory containing the dataset files.
max_hop: Stop expanding neighbors once this many hops is reached.
num_neighbors: Size of the neighborhood for each hop.
embed_dim: Dimension of the embedding space.
weight_kg: Weight of the loss on knowledge graph triplets. If set
to a negative number, the loss on knowledge graph triplets will be
ignored.
val_ratio: A value between 0.0 and 1.0 representing the proportion
of the dataset to include in the validation split.
test_ratio: A value between 0.0 and 1.0 representing the proportion
of the dataset to include in the test split.
batch_size_train: Batch size in the training stage.
batch_size_val: Batch size in the validation stage.
If not specified, `batch_size_train` will be used.
batch_size_test: Batch size in the test stage.
If not specified, 'batch_size_val' will be used.
batch_size_predict: Batch size in the prediction stage.
If not specified, 'batch_size_test' will be used.
num_workers: How many subprocesses to use for data loading.
pin_memory: If `True`, the data loader will copy Tensors
into CUDA pinned memory before returning them.
"""
super().__init__(optim_args)
self.save_hyperparameters()
self._weight_kg = weight_kg
# Arguments for dataloader
self._batch_size_train = batch_size_train
self._batch_size_val = batch_size_val or self._batch_size_train
self._batch_size_test = batch_size_test or self._batch_size_val
self._num_workers = num_workers
self._pin_memory = pin_memory
self._num_users = 0
self._num_entities = 0
self._num_relations = 0
self._dataset_train = None
self._dataset_val = None
self._dataset_test = None
self.register_buffer("ripple_sets", None)
self._build_dataset(
dataset, data_dir, max_hop, num_neighbors, val_ratio, test_ratio
)
# Model architecture
self.embeddings_entity = nn.Parameter(
torch.empty(self._num_entities, embed_dim)
)
self.embeddings_relation = nn.Parameter(
torch.empty(self._num_relations, embed_dim, embed_dim)
)
self.transform = nn.Linear(embed_dim, embed_dim, bias=False)
self.reset_parameters()
def _build_dataset(
self,
dataset: str,
data_dir: str,
max_hop: int,
num_neighbors: int,
val_ratio: float,
test_ratio: float,
):
dataset = dataset.lower()
if dataset == "lastfm":
ratings, triplets_kg = read_data_lastfm(data_dir)
else:
raise ValueError(f"Dataset '{dataset}' is not supported.")
self._num_users = ratings[:, 0].max() + 1
self._num_entities = triplets_kg[:, [0, 2]].max() + 1
self._num_relations = triplets_kg[:, 1].max() + 1
num_val = int(val_ratio * ratings.shape[0])
num_test = int(test_ratio * ratings.shape[0])
ratings, ratings_test = train_test_split(
ratings, test_size=num_test, shuffle=True, stratify=ratings[:, -1]
)
ratings_train, ratings_val = train_test_split(
ratings, test_size=num_val, shuffle=True, stratify=ratings[:, -1]
)
history = defaultdict(list) # `uid`` -> a list of `iids`
for uid, iid, label in ratings_train:
if label == 1:
history[uid].append(iid)
uids_valid = list(history.keys())
# `ripple_sets`: a `torch.Tensor` of shape
# `[num_users, max_hop, 3, num_neighbors]`.
adj_list_kg = adj_list_from_triplets(triplets_kg, reverse_triplet=True)
logger.info("===== Building ripple sets ... ======")
start = time.perf_counter()
self.ripple_sets = torch.empty(
self._num_users, max_hop, 3, num_neighbors, dtype=torch.long
)
queue_task = mp.JoinableQueue()
queue_res = mp.JoinableQueue()
workers = []
for _ in range(self._num_workers):
worker = _Worker(
queue_task, queue_res, max_hop, num_neighbors, adj_list_kg
)
worker.daemon = True
worker.start()
workers.append(worker)
num_tasks = 0
for uid in uids_valid:
num_tasks += 1
queue_task.put((uid, history[uid]))
for _ in range(self._num_workers):
queue_task.put(None)
queue_task.join()
for _ in range(len(uids_valid)):
uid, ripple_set = queue_res.get()
queue_res.task_done()
self.ripple_sets[uid] = torch.as_tensor(
ripple_set, dtype=torch.long
)
queue_res.join()
for worker in workers:
worker.join()
logger.info(
"===== Building ripple sets: Done. "
f"({time.perf_counter() - start:.3f}s) ======"
)
self._dataset_train = CTRPredictionDataset(
torch.as_tensor(
ratings_train[np.isin(ratings_train[:, 0], uids_valid)],
dtype=torch.long,
)
)
self._dataset_val = CTRPredictionDataset(
torch.as_tensor(
ratings_val[np.isin(ratings_val[:, 0], uids_valid)],
dtype=torch.long,
)
)
self._dataset_test = CTRPredictionDataset(
torch.as_tensor(
ratings_test[np.isin(ratings_test[:, 0], uids_valid)],
dtype=torch.long,
)
)
def reset_parameters(self):
a = math.sqrt(3 / self.embeddings_entity.size(1))
nn.init.uniform_(self.embeddings_entity, -a, a)
a = math.sqrt(3 / self.embeddings_relation.size(1))
nn.init.uniform_(self.embeddings_relation, -a, a)
nn.init.xavier_uniform_(self.transform.weight, gain=1.0)
def train_dataloader(self) -> DataLoader:
return create_dataloader(
self._dataset_train,
self._batch_size_train,
shuffle=True,
drop_last=True,
num_workers=self._num_workers,
pin_memory=self._pin_memory,
)
def val_dataloader(self) -> DataLoader:
return create_dataloader(
self._dataset_val,
self._batch_size_val,
shuffle=False,
drop_last=False,
num_workers=self._num_workers,
pin_memory=self._pin_memory,
)
def test_dataloader(self) -> DataLoader:
return create_dataloader(
self._dataset_test,
self._batch_size_test,
shuffle=False,
drop_last=False,
num_workers=self._num_workers,
pin_memory=self._pin_memory,
)
def _split_ripple_sets(
self, ripple_sets: torch.Tensor
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
embs_head = []
embs_relation = []
embs_tail = []
# `ripple_set`: A `torch.Tensor` object of shape
# `[batch_size, num_hops, 3, num_neighbors]`
num_hops = ripple_sets.size(1)
for hop in range(num_hops):
embs_head.append(self.embeddings_entity[ripple_sets[:, hop, 0, :]])
embs_relation.append(
self.embeddings_relation[ripple_sets[:, hop, 1, :]]
)
embs_tail.append(self.embeddings_entity[ripple_sets[:, hop, 2, :]])
return embs_head, embs_relation, embs_tail
def forward(
self,
inputs_item: torch.Tensor,
inputs_head: Sequence[torch.Tensor],
inputs_relation: Sequence[torch.Tensor],
inputs_tail: Sequence[torch.Tensor],
) -> torch.Tensor:
"""Computes logits of input data.
Args:
inputs_item: A `torch.Tensor` object of shape `[batch_size, dim]`
inputs_head: A list of `torch.Tensor` objects of shape
`[batch_size, num_memory, dim]`
inputs_relation: A list of `torch.Tensor` objects of shape
`[batch_size, num_memory, dim, dim]`
inputs_tail: A list of `torch.Tensor` objects of shape
`[batch_size, num_memory, dim]`
"""
query = inputs_item
num_hops = len(inputs_head)
values = []
for hop in range(num_hops):
r_h = (
torch.matmul(
inputs_relation[hop],
inputs_head[hop].unsqueeze(3).contiguous(),
)
.squeeze(3)
.contiguous()
)
logits = torch.sum(
r_h * query.unsqueeze(1).contiguous(), dim=2, keepdim=True
)
probs = F.softmax(logits, dim=1)
values.append(torch.sum(probs * inputs_tail[hop], dim=1))
query = self.transform(query + values[-1])
embeddings_user = sum(values)
logits = torch.sum(embeddings_user * query, dim=1)
return logits
def training_step(
self, batch: Dict[str, torch.Tensor], batch_idx: int
) -> Dict[str, Union[torch.Tensor, float]]:
embs_head, embs_relation, embs_tail = self._split_ripple_sets(
self.ripple_sets[batch["uids"]]
)
logits = self.forward(
self.embeddings_entity[batch["iids"]],
embs_head,
embs_relation,
embs_tail,
)
loss_cls = F.binary_cross_entropy_with_logits(
logits, target=batch["labels"].float()
)
wt_cls = float(logits.numel())
loss = 0 + loss_cls
outputs = {
"loss_cls": loss_cls.detach(),
"wt_cls": wt_cls,
}
if self._weight_kg > 0:
loss_kg = torch.zeros_like(loss)
wt_kg = 0.0
num_hops = len(embs_head)
for hop in range(num_hops):
r_t = (
torch.matmul(
embs_relation[hop],
embs_tail[hop].unsqueeze(3).contiguous(),
)
.squeeze(3)
.contiguous()
)
logits = torch.sum(embs_head[hop] * r_t, dim=2)
loss_kg += torch.sigmoid(logits).sum()
wt_kg += float(logits.numel())
loss_kg = -loss_kg / float(wt_kg)
loss += self._weight_kg * loss_kg
outputs["loss_kg"] = loss_kg.detach()
outputs["wt_kg"] = wt_kg
outputs["loss"] = loss
return outputs
def training_epoch_end(
self, outputs: Sequence[Dict[str, Union[torch.Tensor, float]]]
):
loss = 0.0
loss_cls = 0.0
wt_cls_cum = 0.0
loss_kg = 0.0
wt_kg_cum = 0.0
for out in outputs:
wt_cls = out["wt_cls"]
loss += out["loss"].item() * wt_cls
loss_cls += out["loss_cls"].item() * wt_cls
wt_cls_cum += wt_cls
if self._weight_kg > 0.0:
wt_kg = out["wt_kg"]
loss_kg += out["loss_kg"].item() * wt_kg
wt_kg_cum += wt_kg
self.log("loss", loss / wt_cls_cum)
self.log("loss_cls", loss_cls / wt_cls_cum)
self.log("wt_cls", wt_cls_cum)
if self._weight_kg > 0.0:
self.log("loss_kg", loss_kg / wt_kg_cum)
self.log("wt_kg", wt_kg_cum)
def validation_step(
self, batch: Dict[str, torch.Tensor], batch_idx: int
) -> Dict[str, torch.Tensor]:
embs_head, embs_relation, embs_tail = self._split_ripple_sets(
self.ripple_sets[batch["uids"]]
)
logits = self.forward(
self.embeddings_entity[batch["iids"]],
embs_head,
embs_relation,
embs_tail,
)
probs = torch.sigmoid(logits)
return {"probs": probs, "labels": batch["labels"]}
def validation_epoch_end(
self, outputs: Sequence[Dict[str, torch.Tensor]]
) -> Dict[str, Union[int, float]]:
metrics = self.evaluate(outputs)
for k, v in metrics.items():
self.log(f"{k}_val", float(v))
return metrics
def test_step(
self, batch: Dict[str, torch.Tensor], batch_idx: int
) -> Dict[str, torch.Tensor]:
return self.validation_step(batch, batch_idx)
def test_epoch_end(
self, outputs: Sequence[Dict[str, torch.Tensor]]
) -> Dict[str, Union[int, float]]:
metrics = self.evaluate(outputs)
for k, v in metrics.items():
self.log(f"{k}_test", float(v))
return metrics
def evaluate(
self, outputs: Sequence[Dict[str, torch.Tensor]]
) -> Dict[str, Union[int, float]]:
probs = []
labels = []
for out in outputs:
probs.append(out["probs"].detach().cpu().numpy())
labels.append(out["labels"].detach().cpu().numpy())
probs = np.hstack(probs)
preds = (probs >= 0.5).astype(np.int32)
labels = np.hstack(labels)
return {
"num_samples": probs.size,
"auc": roc_auc_score(y_true=labels, y_score=probs),
"f1": f1_score(y_true=labels, y_pred=preds),
}
class _Worker(mp.Process):
def __init__(
self,
queue_task: mp.JoinableQueue,
queue_res: mp.JoinableQueue,
max_hop: int,
num_neighbors: int,
adj_list_kg: Dict[int, Tuple[int, int]],
):
super().__init__()
self._queue_task = queue_task
self._queue_res = queue_res
self._max_hop = max_hop
self._num_neighbors = num_neighbors
self._adj_list_kg = adj_list_kg
def run(self):
while True:
task = self._queue_task.get()
if task is None:
self._queue_task.task_done()
break
uid, history = task
ripple_set = []
for hop in range(self._max_hop):
nbr_h, nbr_r, nbr_t = [], [], []
if hop == 0:
eids_h = history
else:
eids_h = ripple_set[-1][2]
for eid_h in eids_h:
for (rid, eid_t) in self._adj_list_kg[eid_h]:
nbr_h.append(eid_h)
nbr_r.append(rid)
nbr_t.append(eid_t)
if len(nbr_h) == 0:
ripple_set.append(ripple_set[-1])
else:
pop = len(nbr_h)
indices = np.random.choice(
pop,
size=self._num_neighbors,
replace=pop < self._num_neighbors,
)
nbr_h = [nbr_h[i] for i in indices]
nbr_r = [nbr_r[i] for i in indices]
nbr_t = [nbr_t[i] for i in indices]
ripple_set.append((nbr_h, nbr_r, nbr_t))
self._queue_res.put((uid, ripple_set))
self._queue_task.task_done()
|
[
"numpy.isin",
"sklearn.model_selection.train_test_split",
"torch.nn.init.uniform_",
"torch.empty",
"collections.defaultdict",
"sklearn.metrics.f1_score",
"numpy.random.choice",
"torch.nn.Linear",
"multiprocessing.JoinableQueue",
"torch.zeros_like",
"torch.nn.init.xavier_uniform_",
"time.perf_counter",
"numpy.hstack",
"sklearn.metrics.roc_auc_score",
"torch.sum",
"torch.nn.functional.softmax",
"torch.sigmoid",
"torch.as_tensor",
"logging.getLogger"
] |
[((739, 766), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (756, 766), False, 'import logging\n'), ((3972, 4015), 'torch.nn.Linear', 'nn.Linear', (['embed_dim', 'embed_dim'], {'bias': '(False)'}), '(embed_dim, embed_dim, bias=False)\n', (3981, 4015), False, 'from torch import nn\n'), ((4765, 4854), 'sklearn.model_selection.train_test_split', 'train_test_split', (['ratings'], {'test_size': 'num_test', 'shuffle': '(True)', 'stratify': 'ratings[:, -1]'}), '(ratings, test_size=num_test, shuffle=True, stratify=\n ratings[:, -1])\n', (4781, 4854), False, 'from sklearn.model_selection import train_test_split\n'), ((4909, 4997), 'sklearn.model_selection.train_test_split', 'train_test_split', (['ratings'], {'test_size': 'num_val', 'shuffle': '(True)', 'stratify': 'ratings[:, -1]'}), '(ratings, test_size=num_val, shuffle=True, stratify=ratings\n [:, -1])\n', (4925, 4997), False, 'from sklearn.model_selection import train_test_split\n'), ((5034, 5051), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (5045, 5051), False, 'from collections import defaultdict\n'), ((5499, 5518), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (5516, 5518), False, 'import time\n'), ((5546, 5619), 'torch.empty', 'torch.empty', (['self._num_users', 'max_hop', '(3)', 'num_neighbors'], {'dtype': 'torch.long'}), '(self._num_users, max_hop, 3, num_neighbors, dtype=torch.long)\n', (5557, 5619), False, 'import torch\n'), ((5664, 5682), 'multiprocessing.JoinableQueue', 'mp.JoinableQueue', ([], {}), '()\n', (5680, 5682), True, 'import multiprocessing as mp\n'), ((5703, 5721), 'multiprocessing.JoinableQueue', 'mp.JoinableQueue', ([], {}), '()\n', (5719, 5721), True, 'import multiprocessing as mp\n'), ((7415, 7462), 'torch.nn.init.uniform_', 'nn.init.uniform_', (['self.embeddings_entity', '(-a)', 'a'], {}), '(self.embeddings_entity, -a, a)\n', (7431, 7462), False, 'from torch import nn\n'), ((7532, 7581), 'torch.nn.init.uniform_', 'nn.init.uniform_', (['self.embeddings_relation', '(-a)', 'a'], {}), '(self.embeddings_relation, -a, a)\n', (7548, 7581), False, 'from torch import nn\n'), ((7591, 7647), 'torch.nn.init.xavier_uniform_', 'nn.init.xavier_uniform_', (['self.transform.weight'], {'gain': '(1.0)'}), '(self.transform.weight, gain=1.0)\n', (7614, 7647), False, 'from torch import nn\n'), ((10691, 10732), 'torch.sum', 'torch.sum', (['(embeddings_user * query)'], {'dim': '(1)'}), '(embeddings_user * query, dim=1)\n', (10700, 10732), False, 'import torch\n'), ((13593, 13614), 'torch.sigmoid', 'torch.sigmoid', (['logits'], {}), '(logits)\n', (13606, 13614), False, 'import torch\n'), ((14704, 14720), 'numpy.hstack', 'np.hstack', (['probs'], {}), '(probs)\n', (14713, 14720), True, 'import numpy as np\n'), ((14786, 14803), 'numpy.hstack', 'np.hstack', (['labels'], {}), '(labels)\n', (14795, 14803), True, 'import numpy as np\n'), ((3768, 3810), 'torch.empty', 'torch.empty', (['self._num_entities', 'embed_dim'], {}), '(self._num_entities, embed_dim)\n', (3779, 3810), False, 'import torch\n'), ((3882, 3936), 'torch.empty', 'torch.empty', (['self._num_relations', 'embed_dim', 'embed_dim'], {}), '(self._num_relations, embed_dim, embed_dim)\n', (3893, 3936), False, 'import torch\n'), ((6390, 6435), 'torch.as_tensor', 'torch.as_tensor', (['ripple_set'], {'dtype': 'torch.long'}), '(ripple_set, dtype=torch.long)\n', (6405, 6435), False, 'import torch\n'), ((10486, 10510), 'torch.nn.functional.softmax', 'F.softmax', (['logits'], {'dim': '(1)'}), '(logits, dim=1)\n', (10495, 10510), True, 'from torch.nn import functional as F\n'), ((11518, 11540), 'torch.zeros_like', 'torch.zeros_like', (['loss'], {}), '(loss)\n', (11534, 11540), False, 'import torch\n'), ((14879, 14922), 'sklearn.metrics.roc_auc_score', 'roc_auc_score', ([], {'y_true': 'labels', 'y_score': 'probs'}), '(y_true=labels, y_score=probs)\n', (14892, 14922), False, 'from sklearn.metrics import f1_score, roc_auc_score\n'), ((14942, 14979), 'sklearn.metrics.f1_score', 'f1_score', ([], {'y_true': 'labels', 'y_pred': 'preds'}), '(y_true=labels, y_pred=preds)\n', (14950, 14979), False, 'from sklearn.metrics import f1_score, roc_auc_score\n'), ((10537, 10579), 'torch.sum', 'torch.sum', (['(probs * inputs_tail[hop])'], {'dim': '(1)'}), '(probs * inputs_tail[hop], dim=1)\n', (10546, 10579), False, 'import torch\n'), ((11942, 11980), 'torch.sum', 'torch.sum', (['(embs_head[hop] * r_t)'], {'dim': '(2)'}), '(embs_head[hop] * r_t, dim=2)\n', (11951, 11980), False, 'import torch\n'), ((6800, 6840), 'numpy.isin', 'np.isin', (['ratings_train[:, 0]', 'uids_valid'], {}), '(ratings_train[:, 0], uids_valid)\n', (6807, 6840), True, 'import numpy as np\n'), ((7008, 7046), 'numpy.isin', 'np.isin', (['ratings_val[:, 0]', 'uids_valid'], {}), '(ratings_val[:, 0], uids_valid)\n', (7015, 7046), True, 'import numpy as np\n'), ((7216, 7255), 'numpy.isin', 'np.isin', (['ratings_test[:, 0]', 'uids_valid'], {}), '(ratings_test[:, 0], uids_valid)\n', (7223, 7255), True, 'import numpy as np\n'), ((16329, 16416), 'numpy.random.choice', 'np.random.choice', (['pop'], {'size': 'self._num_neighbors', 'replace': '(pop < self._num_neighbors)'}), '(pop, size=self._num_neighbors, replace=pop < self.\n _num_neighbors)\n', (16345, 16416), True, 'import numpy as np\n'), ((6635, 6654), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (6652, 6654), False, 'import time\n'), ((12008, 12029), 'torch.sigmoid', 'torch.sigmoid', (['logits'], {}), '(logits)\n', (12021, 12029), False, 'import torch\n')]
|
"""Microscoper is a wrapper around bioformats using a forked
python-bioformats to extract the raw images from Olympus IX83
CellSense .vsi format, into a more commonly used TIFF format.
Images are bundled together according to their channels.
This code is used internally in SCB Lab, TCIS, TIFR-H.
You're free to modify it and distribute it.
"""
from __future__ import unicode_literals, print_function
import os
import collections
import bioformats as bf
import javabridge as jb
import numpy as np
import tifffile as tf
import tqdm
from .args import arguments
import xml.dom.minidom
def get_files(directory, keyword):
""" Returns all the files in the given directory
and subdirectories, filtering with the keyword.
Usage:
>>> all_vsi_files = get_files(".", ".vsi")
This will have all the .vsi files in the current
directory and all other directories in the current
directory.
"""
file_list = []
for path, subdirs, files in os.walk(directory):
for name in files:
filename = os.path.join(path, name)
if keyword in filename:
file_list.append(filename)
return sorted(file_list)
def get_metadata(filename):
"""Read the meta data and return the metadata object.
"""
meta = bf.get_omexml_metadata(filename)
metadata = bf.omexml.OMEXML(meta)
return metadata
def get_channel(metadata, channel):
"""Return the channel name from the metadata object"""
try:
channel_name = metadata.image().Pixels.Channel(channel).Name
except:
return
if channel_name is None:
return
return channel_name.replace("/", "_")
def read_images(path, save_directory, big, save_separate):
"""Reads images from the .vsi and associated files.
Returns a dictionary with key as channel, and list
of images as values."""
with bf.ImageReader(path) as reader:
# Shape of the data
c_total = reader.rdr.getSizeC()
z_total = reader.rdr.getSizeZ()
t_total = reader.rdr.getSizeT()
# Since we don't support hyperstacks yet...
if 1 not in [z_total, t_total]:
raise TypeError("Only 4D images are currently supported.")
metadata = get_metadata(path)
# This is so we can manually set a description down below.
pbar_c = tqdm.tqdm(range(c_total))
for channel in pbar_c:
images = []
# Get the channel name, so we can name the file after this.
channel_name = get_channel(metadata, channel)
# Update the channel progress bar description with the
# channel name.
pbar_c.set_description(channel_name)
for time in tqdm.tqdm(range(t_total), "T"):
for z in tqdm.tqdm(range(z_total), "Z"):
image = reader.read(c=channel,
z=z,
t=time,
rescale=False)
# If there's no metadata on channel name, save channels
# with numbers,starting from 0.
if channel_name is None:
channel_name = str(channel)
images.append(image)
save_images(np.asarray(images), channel_name, save_directory, big,
save_separate)
return metadata
def save_images(images, channel, save_directory, big=False,
save_separate=False):
"""Saves the images as TIFs with channel name as the filename.
Channel names are saved as numbers when names are not available."""
# Make the output directory, if it doesn't alredy exist.
if not os.path.exists(save_directory):
os.makedirs(save_directory)
# Save a file for every image in a stack.
if save_separate:
filename = save_directory + str(channel) + "_{}.tif"
for num, image in enumerate(images):
with tf.TiffWriter(filename.format(num+1), bigtiff=big) as f:
f.save(image)
# Save a single .tif file for all the images in a channel.
else:
filename = save_directory + str(channel) + ".tif"
with tf.TiffWriter(filename, bigtiff=big) as f:
f.save(images)
def save_metadata(metadata, save_directory):
data = xml.dom.minidom.parseString(metadata.to_xml())
pretty_xml_as_string = data.toprettyxml()
with open(save_directory + "metadata.xml", "w") as xmlfile:
xmlfile.write(pretty_xml_as_string)
def _init_logger():
"""This is so that Javabridge doesn't spill out a lot of DEBUG messages
during runtime.
From CellProfiler/python-bioformats.
"""
rootLoggerName = jb.get_static_field("org/slf4j/Logger",
"ROOT_LOGGER_NAME",
"Ljava/lang/String;")
rootLogger = jb.static_call("org/slf4j/LoggerFactory",
"getLogger",
"(Ljava/lang/String;)Lorg/slf4j/Logger;",
rootLoggerName)
logLevel = jb.get_static_field("ch/qos/logback/classic/Level",
"WARN",
"Lch/qos/logback/classic/Level;")
jb.call(rootLogger,
"setLevel",
"(Lch/qos/logback/classic/Level;)V",
logLevel)
def run():
# Add file extensions to this to be able to read different file types.
extensions = [".vsi"]
arg = arguments()
files = get_files(arg.f, arg.k)
if 0 == len(files):
print("No file matching *{}* keyword.".format(arg.k))
exit()
if arg.list:
for f in files:
print(f)
print("======================")
print("Total files found:", len(files))
print("======================")
exit()
jb.start_vm(class_path=bf.JARS, max_heap_size="2G")
logger = _init_logger()
pbar_files = tqdm.tqdm(files)
for path in pbar_files:
if not any(_ in path for _ in extensions):
continue
file_location = os.path.dirname(os.path.realpath(path))
filename = os.path.splitext(os.path.basename(path))[0]
save_directory = file_location + "/_{}_/".format(filename)
pbar_files.set_description("..." + path[-15:])
# If the user wants to store meta data for existing data,
# the user may pass -om or --onlymetadata argument which
# will bypass read_images() and get metadata on its own.
if arg.onlymetadata:
metadata = get_metadata(path)
# The default behaviour is to store the files with the
# metadata.
else:
metadata = read_images(path, save_directory, big=arg.big,
save_separate=arg.separate)
save_metadata(metadata, save_directory)
jb.kill_vm()
|
[
"tqdm.tqdm",
"javabridge.static_call",
"javabridge.get_static_field",
"os.makedirs",
"javabridge.kill_vm",
"os.path.basename",
"bioformats.get_omexml_metadata",
"os.path.realpath",
"os.walk",
"os.path.exists",
"numpy.asarray",
"tifffile.TiffWriter",
"javabridge.start_vm",
"bioformats.ImageReader",
"bioformats.omexml.OMEXML",
"os.path.join",
"javabridge.call"
] |
[((984, 1002), 'os.walk', 'os.walk', (['directory'], {}), '(directory)\n', (991, 1002), False, 'import os\n'), ((1294, 1326), 'bioformats.get_omexml_metadata', 'bf.get_omexml_metadata', (['filename'], {}), '(filename)\n', (1316, 1326), True, 'import bioformats as bf\n'), ((1342, 1364), 'bioformats.omexml.OMEXML', 'bf.omexml.OMEXML', (['meta'], {}), '(meta)\n', (1358, 1364), True, 'import bioformats as bf\n'), ((4751, 4836), 'javabridge.get_static_field', 'jb.get_static_field', (['"""org/slf4j/Logger"""', '"""ROOT_LOGGER_NAME"""', '"""Ljava/lang/String;"""'], {}), "('org/slf4j/Logger', 'ROOT_LOGGER_NAME',\n 'Ljava/lang/String;')\n", (4770, 4836), True, 'import javabridge as jb\n'), ((4933, 5049), 'javabridge.static_call', 'jb.static_call', (['"""org/slf4j/LoggerFactory"""', '"""getLogger"""', '"""(Ljava/lang/String;)Lorg/slf4j/Logger;"""', 'rootLoggerName'], {}), "('org/slf4j/LoggerFactory', 'getLogger',\n '(Ljava/lang/String;)Lorg/slf4j/Logger;', rootLoggerName)\n", (4947, 5049), True, 'import javabridge as jb\n'), ((5158, 5255), 'javabridge.get_static_field', 'jb.get_static_field', (['"""ch/qos/logback/classic/Level"""', '"""WARN"""', '"""Lch/qos/logback/classic/Level;"""'], {}), "('ch/qos/logback/classic/Level', 'WARN',\n 'Lch/qos/logback/classic/Level;')\n", (5177, 5255), True, 'import javabridge as jb\n'), ((5327, 5405), 'javabridge.call', 'jb.call', (['rootLogger', '"""setLevel"""', '"""(Lch/qos/logback/classic/Level;)V"""', 'logLevel'], {}), "(rootLogger, 'setLevel', '(Lch/qos/logback/classic/Level;)V', logLevel)\n", (5334, 5405), True, 'import javabridge as jb\n'), ((5928, 5979), 'javabridge.start_vm', 'jb.start_vm', ([], {'class_path': 'bf.JARS', 'max_heap_size': '"""2G"""'}), "(class_path=bf.JARS, max_heap_size='2G')\n", (5939, 5979), True, 'import javabridge as jb\n'), ((6026, 6042), 'tqdm.tqdm', 'tqdm.tqdm', (['files'], {}), '(files)\n', (6035, 6042), False, 'import tqdm\n'), ((6949, 6961), 'javabridge.kill_vm', 'jb.kill_vm', ([], {}), '()\n', (6959, 6961), True, 'import javabridge as jb\n'), ((1883, 1903), 'bioformats.ImageReader', 'bf.ImageReader', (['path'], {}), '(path)\n', (1897, 1903), True, 'import bioformats as bf\n'), ((3741, 3771), 'os.path.exists', 'os.path.exists', (['save_directory'], {}), '(save_directory)\n', (3755, 3771), False, 'import os\n'), ((3781, 3808), 'os.makedirs', 'os.makedirs', (['save_directory'], {}), '(save_directory)\n', (3792, 3808), False, 'import os\n'), ((1054, 1078), 'os.path.join', 'os.path.join', (['path', 'name'], {}), '(path, name)\n', (1066, 1078), False, 'import os\n'), ((4233, 4269), 'tifffile.TiffWriter', 'tf.TiffWriter', (['filename'], {'bigtiff': 'big'}), '(filename, bigtiff=big)\n', (4246, 4269), True, 'import tifffile as tf\n'), ((6185, 6207), 'os.path.realpath', 'os.path.realpath', (['path'], {}), '(path)\n', (6201, 6207), False, 'import os\n'), ((3314, 3332), 'numpy.asarray', 'np.asarray', (['images'], {}), '(images)\n', (3324, 3332), True, 'import numpy as np\n'), ((6245, 6267), 'os.path.basename', 'os.path.basename', (['path'], {}), '(path)\n', (6261, 6267), False, 'import os\n')]
|
import argparse
import numpy as np
import glob
import torch
import torch.nn.functional as F
import os
from kaldi_io import read_mat_scp
import model as model_
import scipy.io as sio
from utils import *
def prep_feats(data_):
#data_ = ( data_ - data_.mean(0) ) / data_.std(0)
features = data_.T
if features.shape[1]<50:
mul = int(np.ceil(50/features.shape[1]))
features = np.tile(features, (1, mul))
features = features[:, :50]
return torch.from_numpy(features[np.newaxis, np.newaxis, :, :]).float()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Compute scores')
parser.add_argument('--path-to-data-la', type=str, default='./data_la/feats.scp', metavar='Path', help='Path to input data')
parser.add_argument('--path-to-data-pa', type=str, default='./data_pa/feats.scp', metavar='Path', help='Path to input data')
parser.add_argument('--path-to-data-mix', type=str, default='./data_mix/feats.scp', metavar='Path', help='Path to input data')
parser.add_argument('--model-la', choices=['lstm', 'resnet', 'resnet_pca', 'wideresnet', 'lcnn_9', 'lcnn_29', 'lcnn_9_pca', 'lcnn_29_pca', 'lcnn_9_prodspec', 'lcnn_9_icqspec', 'lcnn_9_CC', 'lcnn_29_CC', 'resnet_CC', 'Linear', 'TDNN', 'TDNN_multipool', 'TDNN_LSTM', 'FTDNN', 'mobilenet', 'densenet', 'VGG'], default='lcnn_29_CC', help='Model arch')
parser.add_argument('--model-pa', choices=['lstm', 'resnet', 'resnet_pca', 'wideresnet', 'lcnn_9', 'lcnn_29', 'lcnn_9_pca', 'lcnn_29_pca', 'lcnn_9_prodspec', 'lcnn_9_icqspec', 'lcnn_9_CC', 'lcnn_29_CC', 'resnet_CC', 'Linear', 'TDNN', 'TDNN_multipool', 'TDNN_LSTM', 'FTDNN', 'mobilenet', 'densenet', 'VGG'], default='lcnn_9_prodspec', help='Model arch')
parser.add_argument('--model-mix', choices=['lstm', 'resnet', 'resnet_pca', 'wideresnet', 'lcnn_9', 'lcnn_29', 'lcnn_9_pca', 'lcnn_29_pca', 'lcnn_9_prodspec', 'lcnn_9_icqspec', 'lcnn_9_CC', 'lcnn_29_CC', 'resnet_CC', 'Linear', 'TDNN', 'TDNN_multipool', 'FTDNN', 'TDNN_LSTM', 'mobilenet', 'densenet', 'VGG'], default='lcnn_29_CC', help='Model arch')
parser.add_argument('--vgg-type-la', choices=['VGG11', 'VGG13', 'VGG16', 'VGG19'], default='VGG16', help='VGG arch')
parser.add_argument('--vgg-type-pa', choices=['VGG11', 'VGG13', 'VGG16', 'VGG19'], default='VGG16', help='VGG arch')
parser.add_argument('--vgg-type-mix', choices=['VGG11', 'VGG13', 'VGG16', 'VGG19'], default='VGG16', help='VGG arch')
parser.add_argument('--resnet-type-la', choices=['18', '28', '34', '50', '101', 'se_18', 'se_28', 'se_34', 'se_50', 'se_101', '2net_18', '2net_se_18'], default='18', help='Resnet arch')
parser.add_argument('--resnet-type-pa', choices=['18', '28', '34', '50', '101', 'se_18', 'se_28', 'se_34', 'se_50', 'se_101', '2net_18', '2net_se_18'], default='18', help='Resnet arch')
parser.add_argument('--resnet-type-mix', choices=['18', '28', '34', '50', '101', 'se_18', 'se_28', 'se_34', 'se_50', 'se_101', '2net_18', '2net_se_18'], default='18', help='Resnet arch')
parser.add_argument('--train-mode', choices=['mix', 'lapa', 'independent'], default='mix', help='Train mode')
parser.add_argument('--trials-path', type=str, default=None, metavar='Path', help='Path to trials file')
parser.add_argument('--cp-path', type=str, default=None, metavar='Path', help='Path for file containing model')
parser.add_argument('--out-path', type=str, default='./', metavar='Path', help='Path to output hdf file')
parser.add_argument('--prefix', type=str, default='./scores', metavar='Path', help='prefix for score files names')
parser.add_argument('--no-cuda', action='store_true', default=False, help='Disables GPU use')
parser.add_argument('--no-output-file', action='store_true', default=False, help='Disables writing scores into out file')
parser.add_argument('--no-eer', action='store_true', default=False, help='Disables computation of EER')
parser.add_argument('--eval', action='store_true', default=False, help='Enables eval trials reading')
parser.add_argument('--ncoef-la', type=int, default=90, metavar='N', help='Number of cepstral coefs for the CC case (default: 90)')
parser.add_argument('--ncoef-pa', type=int, default=90, metavar='N', help='Number of cepstral coefs for the CC case (default: 90)')
parser.add_argument('--ncoef-mix', type=int, default=90, metavar='N', help='Number of cepstral coefs for the CC case (default: 90)')
args = parser.parse_args()
args.cuda = True if not args.no_cuda and torch.cuda.is_available() else False
print(args)
if args.cp_path is None:
raise ValueError('There is no checkpoint/model path. Use arg --cp-path to indicate the path!')
if os.path.isfile(args.out_path):
os.remove(args.out_path)
print(args.out_path + ' Removed')
if args.cuda:
device = get_freer_gpu()
if args.model_la == 'lstm':
model_la = model_.cnn_lstm()
elif args.model_la == 'VGG':
model_la = model_.VGG(vgg_name=args.vgg_type_la)
elif args.model_la == 'resnet':
model_la = model_.ResNet(resnet_type=args.resnet_type_la)
elif args.model_la == 'resnet_pca':
model_la = model_.ResNet_pca(resnet_type=args.resnet_type_la)
elif args.model_la == 'wideresnet':
model_la = model_.WideResNet()
elif args.model_la == 'lcnn_9':
model_la = model_.lcnn_9layers()
elif args.model_la == 'lcnn_29':
model_la = model_.lcnn_29layers_v2()
elif args.model_la == 'lcnn_9_pca':
model_la = model_.lcnn_9layers_pca()
elif args.model_la == 'lcnn_29_pca':
model_la = model_.lcnn_29layers_v2_pca()
elif args.model_la == 'lcnn_9_icqspec':
model_la = model_.lcnn_9layers_icqspec()
elif args.model_la == 'lcnn_9_prodspec':
model_la = model_.lcnn_9layers_prodspec()
elif args.model_la == 'lcnn_9_CC':
model_la = model_.lcnn_9layers_CC(ncoef=args.ncoef_la)
elif args.model_la == 'lcnn_29_CC':
model_la = model_.lcnn_29layers_CC(ncoef=args.ncoef_la)
elif args.model_la == 'resnet_CC':
model_la = model_.ResNet_CC(ncoef=args.ncoef_la, resnet_type=args.resnet_type_la)
elif args.model_la == 'TDNN':
model_la = model_.TDNN(ncoef=args.ncoef_la)
elif args.model_la == 'TDNN_multipool':
model_la = model_.TDNN_multipool(ncoef=args.ncoef_la)
elif args.model_la == 'TDNN_LSTM':
model_la = model_.TDNN_LSTM(ncoef=args.ncoef_la)
elif args.model_la == 'FTDNN':
model_la = model_.FTDNN(ncoef=args.ncoef_la)
elif args.model_la == 'Linear':
model_la = model_.Linear(ncoef=args.ncoef_la)
elif args.model_la == 'mobilenet':
model_la = model_.MobileNetV3_Small()
elif args.model_la == 'densenet':
model_la = model_.DenseNet()
if args.model_pa == 'lstm':
model_pa = model_.cnn_lstm()
elif args.model_pa == 'VGG':
model_pa = model_.VGG(vgg_name=args.vgg_type_pa)
elif args.model_pa == 'resnet':
model_pa = model_.ResNet(resnet_type=args.resnet_type_pa)
elif args.model_pa == 'resnet_pca':
model_pa = model_.ResNet_pca(resnet_type=args.resnet_type_pa)
elif args.model_pa == 'wideresnet':
model_pa = model_.WideResNet()
elif args.model_pa == 'lcnn_9':
model_pa = model_.lcnn_9layers()
elif args.model_pa == 'lcnn_29':
model_pa = model_.lcnn_29layers_v2()
elif args.model_pa == 'lcnn_9_pca':
model_pa = model_.lcnn_9layers_pca()
elif args.model_pa == 'lcnn_29_pca':
model_pa = model_.lcnn_29layers_v2_pca()
elif args.model_pa == 'lcnn_9_icqspec':
model_pa = model_.lcnn_9layers_icqspec()
elif args.model_pa == 'lcnn_9_prodspec':
model_pa = model_.lcnn_9layers_prodspec()
elif args.model_pa == 'lcnn_9_CC':
model_pa = model_.lcnn_9layers_CC(ncoef=args.ncoef_pa)
elif args.model_pa == 'lcnn_29_CC':
model_pa = model_.lcnn_29layers_CC(ncoef=args.ncoef_pa)
elif args.model_pa == 'resnet_CC':
model_pa = model_.ResNet_CC(ncoef=args.ncoef_pa, resnet_type=args.resnet_type_pa)
elif args.model_pa == 'TDNN':
model_pa = model_.TDNN(ncoef=args.ncoef_pa)
elif args.model_pa == 'TDNN_multipool':
model_pa = model_.TDNN_multipool(ncoef=args.ncoef_pa)
elif args.model_pa == 'TDNN_LSTM':
model_pa = model_.TDNN_LSTM(ncoef=args.ncoef_pa)
elif args.model_pa == 'FTDNN':
model_pa = model_.FTDNN(ncoef=args.ncoef_pa)
elif args.model_pa == 'Linear':
model_pa = model_.Linear(ncoef=args.ncoef_pa)
elif args.model_pa == 'mobilenet':
model_pa = model_.MobileNetV3_Small()
elif args.model_pa == 'densenet':
model_pa = model_.DenseNet()
if args.model_mix == 'lstm':
model_mix = model_.cnn_lstm()
elif args.model_mix == 'VGG':
model_mix = model_.VGG(vgg_name=args.vgg_type_mix)
elif args.model_mix == 'resnet':
model_mix = model_.ResNet(resnet_type=args.resnet_type_mix)
elif args.model_mix == 'resnet_pca':
model_mix = model_.ResNet_pca(resnet_type=args.resnet_type_mix)
elif args.model_mix == 'wideresnet':
model_mix = model_.WideResNet()
elif args.model_mix == 'lcnn_9':
model_mix = model_.lcnn_9layers()
elif args.model_mix == 'lcnn_29':
model_mix = model_.lcnn_29layers_v2()
elif args.model_mix == 'lcnn_9_pca':
model_mix = model_.lcnn_9layers_pca()
elif args.model_mix == 'lcnn_29_pca':
model_mix = model_.lcnn_29layers_v2_pca()
elif args.model_mix == 'lcnn_9_icqspec':
model_mix = model_.lcnn_9layers_icqspec()
elif args.model_mix == 'lcnn_9_prodspec':
model_mix = model_.lcnn_9layers_prodspec()
elif args.model_mix == 'lcnn_9_CC':
model_mix = model_.lcnn_9layers_CC(ncoef=args.ncoef_mix)
elif args.model_mix == 'lcnn_29_CC':
model_mix = model_.lcnn_29layers_CC(ncoef=args.ncoef_mix)
elif args.model_mix == 'resnet_CC':
model_mix = model_.ResNet_CC(ncoef=args.ncoef_mix, resnet_type=args.resnet_type_mix)
elif args.model_mix == 'TDNN':
model_mix = model_.FTDNN(ncoef=args.ncoef_mix)
elif args.model_mix == 'TDNN_multipool':
model_mix = model_.TDNN_multipool(ncoef=args.ncoef_mix)
elif args.model_mix == 'TDNN_LSTM':
model_mix = model_.TDNN_LSTM(ncoef=args.ncoef_mix)
elif args.model_mix == 'FTDNN':
model_mix = model_.TDNN(ncoef=args.ncoef_mix)
elif args.model_mix == 'Linear':
model_mix = model_.Linear(ncoef=args.ncoef_mix)
elif args.model_mix == 'mobilenet':
model_mix = model_.MobileNetV3_Small()
elif args.model_mix == 'densenet':
model_mix = model_.DenseNet()
print('Loading model')
ckpt = torch.load(args.cp_path, map_location = lambda storage, loc: storage)
model_la.load_state_dict(ckpt['model_la_state'])
model_pa.load_state_dict(ckpt['model_pa_state'])
model_mix.load_state_dict(ckpt['model_mix_state'])
model_la.eval()
model_pa.eval()
model_mix.eval()
print('Model loaded')
print('Loading data')
data_la = { k:m for k,m in read_mat_scp(args.path_to_data_la) }
data_pa = { k:m for k,m in read_mat_scp(args.path_to_data_pa) }
data_mix = { k:m for k,m in read_mat_scp(args.path_to_data_mix) }
if args.trials_path:
if args.eval:
test_utts = read_trials(args.trials_path, eval_=args.eval)
else:
test_utts, attack_type_list, label_list = read_trials(args.trials_path, eval_=args.eval)
else:
test_utts = list(data_la.keys())
print('Data loaded')
print('Start of scores computation')
scores = {}
scores['all'] = []
scores['la'] = []
scores['pa'] = []
scores['mix'] = []
scores['fusion'] = []
with torch.no_grad():
for i, utt in enumerate(test_utts):
feats_la = prep_feats(data_la[utt])
feats_pa = prep_feats(data_pa[utt])
feats_mix = prep_feats(data_mix[utt])
try:
if args.cuda:
feats_la = feats_la.to(device)
feats_pa = feats_pa.to(device)
feats_mix = feats_mix.to(device)
model_la = model_la.to(device)
model_pa = model_pa.to(device)
model_mix = model_mix.to(device)
pred_la = model_la.forward(feats_la).squeeze()
pred_pa = model_pa.forward(feats_pa).squeeze()
pred_mix = model_mix.forward(feats_mix).squeeze()
except:
feats_la = feats_la.cpu()
feats_pa = feats_pa.cpu()
feats_mix = feats_mix.cpu()
model_la = model_la.cpu()
model_pa = model_pa.cpu()
model_mix = model_mix.cpu()
pred_la = model_la.forward(feats_la).squeeze()
pred_pa = model_pa.forward(feats_pa).squeeze()
pred_mix = model_mix.forward(feats_mix).squeeze()
if args.train_mode == 'mix':
mixture_coef = 1.0-torch.sigmoid(pred_mix).squeeze()
score_all = 1.0-torch.sigmoid(mixture_coef*pred_la + (1.-mixture_coef)*pred_pa).squeeze().cpu().item()
score_la = 1.0-torch.sigmoid(pred_la).squeeze().cpu().item()
score_pa = 1.0-torch.sigmoid(pred_pa).squeeze().cpu().item()
score_mix = 1.0-2*abs(mixture_coef.cpu().item()-0.5)
score_fusion = (score_all+score_la+score_pa+score_mix)/4.
elif args.train_mode == 'lapa':
score_all = 0.0
score_la = 1.0-2*abs(torch.sigmoid(pred_la)-0.5).cpu().numpy().item()
score_pa = 1.0-2*abs(torch.sigmoid(pred_pa)-0.5).cpu().numpy().item()
score_mix = 1.0-2*abs(torch.sigmoid(pred_mix)-0.5).cpu().numpy().item()
score_fusion = (score_la+score_pa+score_mix)/3.
elif args.train_mode == 'independent':
score_all = 0.0
score_la = 1.0-torch.sigmoid(pred_la).cpu().numpy().item()
score_pa = 1.0-torch.sigmoid(pred_pa).cpu().numpy().item()
score_mix = 1.0-torch.sigmoid(pred_mix).cpu().numpy().item()
score_fusion = (score_la+score_pa+score_mix)/3.
scores['all'].append(score_all)
scores['la'].append(score_la)
scores['pa'].append(score_pa)
scores['mix'].append(score_mix)
scores['fusion'].append(score_fusion)
if not args.no_output_file:
print('Storing scores in output file:')
print(args.out_path)
for score_type, score_list in scores.items():
if (args.train_mode=='lapa' or args.train_mode=='independent') and score_type=='all':
continue
file_name = args.out_path+args.prefix+'_'+score_type+'.txt'
with open(file_name, 'w') as f:
if args.eval or args.trials_path is None:
for i, utt in enumerate(test_utts):
f.write("%s" % ' '.join([utt, str(score_list[i])+'\n']))
else:
for i, utt in enumerate(test_utts):
f.write("%s" % ' '.join([utt, attack_type_list[i], label_list[i], str(score_list[i])+'\n']))
if not args.no_eer and not args.eval and args.trials_path:
for score_type, score_list in scores.items():
print('\nEER {}: {}\n'.format(score_type, compute_eer_labels(label_list, score_list)))
print('All done!!')
|
[
"model.DenseNet",
"model.cnn_lstm",
"os.remove",
"model.TDNN",
"argparse.ArgumentParser",
"model.MobileNetV3_Small",
"os.path.isfile",
"numpy.tile",
"model.lcnn_9layers",
"torch.no_grad",
"model.lcnn_29layers_v2_pca",
"model.Linear",
"model.FTDNN",
"model.VGG",
"torch.load",
"model.TDNN_multipool",
"model.lcnn_29layers_CC",
"numpy.ceil",
"model.TDNN_LSTM",
"torch.cuda.is_available",
"kaldi_io.read_mat_scp",
"model.lcnn_9layers_icqspec",
"model.lcnn_9layers_pca",
"model.lcnn_29layers_v2",
"torch.from_numpy",
"model.lcnn_9layers_prodspec",
"model.WideResNet",
"model.ResNet_pca",
"model.ResNet",
"torch.sigmoid",
"model.lcnn_9layers_CC",
"model.ResNet_CC"
] |
[((554, 607), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Compute scores"""'}), "(description='Compute scores')\n", (577, 607), False, 'import argparse\n'), ((4587, 4616), 'os.path.isfile', 'os.path.isfile', (['args.out_path'], {}), '(args.out_path)\n', (4601, 4616), False, 'import os\n'), ((10047, 10114), 'torch.load', 'torch.load', (['args.cp_path'], {'map_location': '(lambda storage, loc: storage)'}), '(args.cp_path, map_location=lambda storage, loc: storage)\n', (10057, 10114), False, 'import torch\n'), ((383, 410), 'numpy.tile', 'np.tile', (['features', '(1, mul)'], {}), '(features, (1, mul))\n', (390, 410), True, 'import numpy as np\n'), ((4620, 4644), 'os.remove', 'os.remove', (['args.out_path'], {}), '(args.out_path)\n', (4629, 4644), False, 'import os\n'), ((4767, 4784), 'model.cnn_lstm', 'model_.cnn_lstm', ([], {}), '()\n', (4782, 4784), True, 'import model as model_\n'), ((6512, 6529), 'model.cnn_lstm', 'model_.cnn_lstm', ([], {}), '()\n', (6527, 6529), True, 'import model as model_\n'), ((8259, 8276), 'model.cnn_lstm', 'model_.cnn_lstm', ([], {}), '()\n', (8274, 8276), True, 'import model as model_\n'), ((10996, 11011), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (11009, 11011), False, 'import torch\n'), ((339, 370), 'numpy.ceil', 'np.ceil', (['(50 / features.shape[1])'], {}), '(50 / features.shape[1])\n', (346, 370), True, 'import numpy as np\n'), ((450, 506), 'torch.from_numpy', 'torch.from_numpy', (['features[np.newaxis, np.newaxis, :, :]'], {}), '(features[np.newaxis, np.newaxis, :, :])\n', (466, 506), False, 'import torch\n'), ((4407, 4432), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (4430, 4432), False, 'import torch\n'), ((4828, 4865), 'model.VGG', 'model_.VGG', ([], {'vgg_name': 'args.vgg_type_la'}), '(vgg_name=args.vgg_type_la)\n', (4838, 4865), True, 'import model as model_\n'), ((6573, 6610), 'model.VGG', 'model_.VGG', ([], {'vgg_name': 'args.vgg_type_pa'}), '(vgg_name=args.vgg_type_pa)\n', (6583, 6610), True, 'import model as model_\n'), ((8322, 8360), 'model.VGG', 'model_.VGG', ([], {'vgg_name': 'args.vgg_type_mix'}), '(vgg_name=args.vgg_type_mix)\n', (8332, 8360), True, 'import model as model_\n'), ((10398, 10432), 'kaldi_io.read_mat_scp', 'read_mat_scp', (['args.path_to_data_la'], {}), '(args.path_to_data_la)\n', (10410, 10432), False, 'from kaldi_io import read_mat_scp\n'), ((10463, 10497), 'kaldi_io.read_mat_scp', 'read_mat_scp', (['args.path_to_data_pa'], {}), '(args.path_to_data_pa)\n', (10475, 10497), False, 'from kaldi_io import read_mat_scp\n'), ((10529, 10564), 'kaldi_io.read_mat_scp', 'read_mat_scp', (['args.path_to_data_mix'], {}), '(args.path_to_data_mix)\n', (10541, 10564), False, 'from kaldi_io import read_mat_scp\n'), ((4912, 4958), 'model.ResNet', 'model_.ResNet', ([], {'resnet_type': 'args.resnet_type_la'}), '(resnet_type=args.resnet_type_la)\n', (4925, 4958), True, 'import model as model_\n'), ((6657, 6703), 'model.ResNet', 'model_.ResNet', ([], {'resnet_type': 'args.resnet_type_pa'}), '(resnet_type=args.resnet_type_pa)\n', (6670, 6703), True, 'import model as model_\n'), ((8409, 8456), 'model.ResNet', 'model_.ResNet', ([], {'resnet_type': 'args.resnet_type_mix'}), '(resnet_type=args.resnet_type_mix)\n', (8422, 8456), True, 'import model as model_\n'), ((5009, 5059), 'model.ResNet_pca', 'model_.ResNet_pca', ([], {'resnet_type': 'args.resnet_type_la'}), '(resnet_type=args.resnet_type_la)\n', (5026, 5059), True, 'import model as model_\n'), ((6754, 6804), 'model.ResNet_pca', 'model_.ResNet_pca', ([], {'resnet_type': 'args.resnet_type_pa'}), '(resnet_type=args.resnet_type_pa)\n', (6771, 6804), True, 'import model as model_\n'), ((8509, 8560), 'model.ResNet_pca', 'model_.ResNet_pca', ([], {'resnet_type': 'args.resnet_type_mix'}), '(resnet_type=args.resnet_type_mix)\n', (8526, 8560), True, 'import model as model_\n'), ((5110, 5129), 'model.WideResNet', 'model_.WideResNet', ([], {}), '()\n', (5127, 5129), True, 'import model as model_\n'), ((6855, 6874), 'model.WideResNet', 'model_.WideResNet', ([], {}), '()\n', (6872, 6874), True, 'import model as model_\n'), ((8613, 8632), 'model.WideResNet', 'model_.WideResNet', ([], {}), '()\n', (8630, 8632), True, 'import model as model_\n'), ((5176, 5197), 'model.lcnn_9layers', 'model_.lcnn_9layers', ([], {}), '()\n', (5195, 5197), True, 'import model as model_\n'), ((6921, 6942), 'model.lcnn_9layers', 'model_.lcnn_9layers', ([], {}), '()\n', (6940, 6942), True, 'import model as model_\n'), ((8681, 8702), 'model.lcnn_9layers', 'model_.lcnn_9layers', ([], {}), '()\n', (8700, 8702), True, 'import model as model_\n'), ((11985, 12008), 'torch.sigmoid', 'torch.sigmoid', (['pred_mix'], {}), '(pred_mix)\n', (11998, 12008), False, 'import torch\n'), ((5245, 5270), 'model.lcnn_29layers_v2', 'model_.lcnn_29layers_v2', ([], {}), '()\n', (5268, 5270), True, 'import model as model_\n'), ((6990, 7015), 'model.lcnn_29layers_v2', 'model_.lcnn_29layers_v2', ([], {}), '()\n', (7013, 7015), True, 'import model as model_\n'), ((8752, 8777), 'model.lcnn_29layers_v2', 'model_.lcnn_29layers_v2', ([], {}), '()\n', (8775, 8777), True, 'import model as model_\n'), ((5321, 5346), 'model.lcnn_9layers_pca', 'model_.lcnn_9layers_pca', ([], {}), '()\n', (5344, 5346), True, 'import model as model_\n'), ((7066, 7091), 'model.lcnn_9layers_pca', 'model_.lcnn_9layers_pca', ([], {}), '()\n', (7089, 7091), True, 'import model as model_\n'), ((8830, 8855), 'model.lcnn_9layers_pca', 'model_.lcnn_9layers_pca', ([], {}), '()\n', (8853, 8855), True, 'import model as model_\n'), ((5398, 5427), 'model.lcnn_29layers_v2_pca', 'model_.lcnn_29layers_v2_pca', ([], {}), '()\n', (5425, 5427), True, 'import model as model_\n'), ((7143, 7172), 'model.lcnn_29layers_v2_pca', 'model_.lcnn_29layers_v2_pca', ([], {}), '()\n', (7170, 7172), True, 'import model as model_\n'), ((8909, 8938), 'model.lcnn_29layers_v2_pca', 'model_.lcnn_29layers_v2_pca', ([], {}), '()\n', (8936, 8938), True, 'import model as model_\n'), ((5482, 5511), 'model.lcnn_9layers_icqspec', 'model_.lcnn_9layers_icqspec', ([], {}), '()\n', (5509, 5511), True, 'import model as model_\n'), ((7227, 7256), 'model.lcnn_9layers_icqspec', 'model_.lcnn_9layers_icqspec', ([], {}), '()\n', (7254, 7256), True, 'import model as model_\n'), ((8995, 9024), 'model.lcnn_9layers_icqspec', 'model_.lcnn_9layers_icqspec', ([], {}), '()\n', (9022, 9024), True, 'import model as model_\n'), ((12039, 12109), 'torch.sigmoid', 'torch.sigmoid', (['(mixture_coef * pred_la + (1.0 - mixture_coef) * pred_pa)'], {}), '(mixture_coef * pred_la + (1.0 - mixture_coef) * pred_pa)\n', (12052, 12109), False, 'import torch\n'), ((12145, 12167), 'torch.sigmoid', 'torch.sigmoid', (['pred_la'], {}), '(pred_la)\n', (12158, 12167), False, 'import torch\n'), ((12210, 12232), 'torch.sigmoid', 'torch.sigmoid', (['pred_pa'], {}), '(pred_pa)\n', (12223, 12232), False, 'import torch\n'), ((5567, 5597), 'model.lcnn_9layers_prodspec', 'model_.lcnn_9layers_prodspec', ([], {}), '()\n', (5595, 5597), True, 'import model as model_\n'), ((7312, 7342), 'model.lcnn_9layers_prodspec', 'model_.lcnn_9layers_prodspec', ([], {}), '()\n', (7340, 7342), True, 'import model as model_\n'), ((9082, 9112), 'model.lcnn_9layers_prodspec', 'model_.lcnn_9layers_prodspec', ([], {}), '()\n', (9110, 9112), True, 'import model as model_\n'), ((5647, 5690), 'model.lcnn_9layers_CC', 'model_.lcnn_9layers_CC', ([], {'ncoef': 'args.ncoef_la'}), '(ncoef=args.ncoef_la)\n', (5669, 5690), True, 'import model as model_\n'), ((7392, 7435), 'model.lcnn_9layers_CC', 'model_.lcnn_9layers_CC', ([], {'ncoef': 'args.ncoef_pa'}), '(ncoef=args.ncoef_pa)\n', (7414, 7435), True, 'import model as model_\n'), ((9164, 9208), 'model.lcnn_9layers_CC', 'model_.lcnn_9layers_CC', ([], {'ncoef': 'args.ncoef_mix'}), '(ncoef=args.ncoef_mix)\n', (9186, 9208), True, 'import model as model_\n'), ((12789, 12811), 'torch.sigmoid', 'torch.sigmoid', (['pred_la'], {}), '(pred_la)\n', (12802, 12811), False, 'import torch\n'), ((12852, 12874), 'torch.sigmoid', 'torch.sigmoid', (['pred_pa'], {}), '(pred_pa)\n', (12865, 12874), False, 'import torch\n'), ((12916, 12939), 'torch.sigmoid', 'torch.sigmoid', (['pred_mix'], {}), '(pred_mix)\n', (12929, 12939), False, 'import torch\n'), ((5741, 5785), 'model.lcnn_29layers_CC', 'model_.lcnn_29layers_CC', ([], {'ncoef': 'args.ncoef_la'}), '(ncoef=args.ncoef_la)\n', (5764, 5785), True, 'import model as model_\n'), ((7486, 7530), 'model.lcnn_29layers_CC', 'model_.lcnn_29layers_CC', ([], {'ncoef': 'args.ncoef_pa'}), '(ncoef=args.ncoef_pa)\n', (7509, 7530), True, 'import model as model_\n'), ((9261, 9306), 'model.lcnn_29layers_CC', 'model_.lcnn_29layers_CC', ([], {'ncoef': 'args.ncoef_mix'}), '(ncoef=args.ncoef_mix)\n', (9284, 9306), True, 'import model as model_\n'), ((5835, 5905), 'model.ResNet_CC', 'model_.ResNet_CC', ([], {'ncoef': 'args.ncoef_la', 'resnet_type': 'args.resnet_type_la'}), '(ncoef=args.ncoef_la, resnet_type=args.resnet_type_la)\n', (5851, 5905), True, 'import model as model_\n'), ((7580, 7650), 'model.ResNet_CC', 'model_.ResNet_CC', ([], {'ncoef': 'args.ncoef_pa', 'resnet_type': 'args.resnet_type_pa'}), '(ncoef=args.ncoef_pa, resnet_type=args.resnet_type_pa)\n', (7596, 7650), True, 'import model as model_\n'), ((9358, 9430), 'model.ResNet_CC', 'model_.ResNet_CC', ([], {'ncoef': 'args.ncoef_mix', 'resnet_type': 'args.resnet_type_mix'}), '(ncoef=args.ncoef_mix, resnet_type=args.resnet_type_mix)\n', (9374, 9430), True, 'import model as model_\n'), ((12456, 12478), 'torch.sigmoid', 'torch.sigmoid', (['pred_la'], {}), '(pred_la)\n', (12469, 12478), False, 'import torch\n'), ((12530, 12552), 'torch.sigmoid', 'torch.sigmoid', (['pred_pa'], {}), '(pred_pa)\n', (12543, 12552), False, 'import torch\n'), ((12605, 12628), 'torch.sigmoid', 'torch.sigmoid', (['pred_mix'], {}), '(pred_mix)\n', (12618, 12628), False, 'import torch\n'), ((5950, 5982), 'model.TDNN', 'model_.TDNN', ([], {'ncoef': 'args.ncoef_la'}), '(ncoef=args.ncoef_la)\n', (5961, 5982), True, 'import model as model_\n'), ((7695, 7727), 'model.TDNN', 'model_.TDNN', ([], {'ncoef': 'args.ncoef_pa'}), '(ncoef=args.ncoef_pa)\n', (7706, 7727), True, 'import model as model_\n'), ((9477, 9511), 'model.FTDNN', 'model_.FTDNN', ([], {'ncoef': 'args.ncoef_mix'}), '(ncoef=args.ncoef_mix)\n', (9489, 9511), True, 'import model as model_\n'), ((6037, 6079), 'model.TDNN_multipool', 'model_.TDNN_multipool', ([], {'ncoef': 'args.ncoef_la'}), '(ncoef=args.ncoef_la)\n', (6058, 6079), True, 'import model as model_\n'), ((7782, 7824), 'model.TDNN_multipool', 'model_.TDNN_multipool', ([], {'ncoef': 'args.ncoef_pa'}), '(ncoef=args.ncoef_pa)\n', (7803, 7824), True, 'import model as model_\n'), ((9568, 9611), 'model.TDNN_multipool', 'model_.TDNN_multipool', ([], {'ncoef': 'args.ncoef_mix'}), '(ncoef=args.ncoef_mix)\n', (9589, 9611), True, 'import model as model_\n'), ((6129, 6166), 'model.TDNN_LSTM', 'model_.TDNN_LSTM', ([], {'ncoef': 'args.ncoef_la'}), '(ncoef=args.ncoef_la)\n', (6145, 6166), True, 'import model as model_\n'), ((7874, 7911), 'model.TDNN_LSTM', 'model_.TDNN_LSTM', ([], {'ncoef': 'args.ncoef_pa'}), '(ncoef=args.ncoef_pa)\n', (7890, 7911), True, 'import model as model_\n'), ((9663, 9701), 'model.TDNN_LSTM', 'model_.TDNN_LSTM', ([], {'ncoef': 'args.ncoef_mix'}), '(ncoef=args.ncoef_mix)\n', (9679, 9701), True, 'import model as model_\n'), ((6212, 6245), 'model.FTDNN', 'model_.FTDNN', ([], {'ncoef': 'args.ncoef_la'}), '(ncoef=args.ncoef_la)\n', (6224, 6245), True, 'import model as model_\n'), ((7957, 7990), 'model.FTDNN', 'model_.FTDNN', ([], {'ncoef': 'args.ncoef_pa'}), '(ncoef=args.ncoef_pa)\n', (7969, 7990), True, 'import model as model_\n'), ((9749, 9782), 'model.TDNN', 'model_.TDNN', ([], {'ncoef': 'args.ncoef_mix'}), '(ncoef=args.ncoef_mix)\n', (9760, 9782), True, 'import model as model_\n'), ((6292, 6326), 'model.Linear', 'model_.Linear', ([], {'ncoef': 'args.ncoef_la'}), '(ncoef=args.ncoef_la)\n', (6305, 6326), True, 'import model as model_\n'), ((8037, 8071), 'model.Linear', 'model_.Linear', ([], {'ncoef': 'args.ncoef_pa'}), '(ncoef=args.ncoef_pa)\n', (8050, 8071), True, 'import model as model_\n'), ((9831, 9866), 'model.Linear', 'model_.Linear', ([], {'ncoef': 'args.ncoef_mix'}), '(ncoef=args.ncoef_mix)\n', (9844, 9866), True, 'import model as model_\n'), ((6376, 6402), 'model.MobileNetV3_Small', 'model_.MobileNetV3_Small', ([], {}), '()\n', (6400, 6402), True, 'import model as model_\n'), ((8121, 8147), 'model.MobileNetV3_Small', 'model_.MobileNetV3_Small', ([], {}), '()\n', (8145, 8147), True, 'import model as model_\n'), ((9918, 9944), 'model.MobileNetV3_Small', 'model_.MobileNetV3_Small', ([], {}), '()\n', (9942, 9944), True, 'import model as model_\n'), ((6451, 6468), 'model.DenseNet', 'model_.DenseNet', ([], {}), '()\n', (6466, 6468), True, 'import model as model_\n'), ((8196, 8213), 'model.DenseNet', 'model_.DenseNet', ([], {}), '()\n', (8211, 8213), True, 'import model as model_\n'), ((9995, 10012), 'model.DenseNet', 'model_.DenseNet', ([], {}), '()\n', (10010, 10012), True, 'import model as model_\n')]
|
""" If this operator needs to be run with the faster NMS implementation,
follow these steps:
1. Clone google/automl and tensorflow/models from Github.
2. Run the following commands in automl/efficientdet:
a. grep -lIR "from object_detection" ./* | xargs sed -i "s/from object_detection/from object_det/g"
b. mv object_detection object_det
c. grep -lIR "inference\." ./* | xargs sed -i 's/inference\./infer\./g'
d. grep -lIR "import inference" ./* | xargs sed -i 's/import inference/import infer/g'
e. mv inference.py infer.py
f. grep -lIR " utils" ./* | xargs sed -i 's/ utils/ util/g'
g. grep -lIR "utils.TpuBatchNormalization" ./* | xargs sed -i 's/utils\.TpuBatchNormalization/util\.TpuBatchNormalization/g'
h. mv utils.py util.py
3. Set the MODIFIED_AUTOML flag to on.
"""
import erdos
import time
import copy
import pylot.utils
from pylot.perception.detection.utils import BoundingBox2D, DetectedObstacle,\
load_coco_bbox_colors, load_coco_labels
from pylot.perception.messages import ObstaclesMessage
# Detection related imports.
import numpy as np
import tensorflow as tf
import hparams_config
try:
import infer
except ImportError:
import inference as infer
import anchors
NUM_CLASSES = 90
MODIFIED_AUTOML = False
class EfficientDetOperator(erdos.Operator):
""" Detects obstacles using the EfficientDet set of models.
The operator receives frames on camera stream, and runs a model for each
frame.
Args:
camera_stream (:py:class:`erdos.ReadStream`): The stream on which
camera frames are received.
obstacles_stream (:py:class:`erdos.WriteStream`): Stream on which the
operator sends
:py:class:`~pylot.perception.messages.ObstaclesMessage` messages.
model_path(:obj:`str`): Path to the model pb file.
flags (absl.flags): Object to be used to access absl flags.
"""
def __init__(self, camera_stream, time_to_decision_stream,
obstacles_stream, model_names, model_paths, flags):
camera_stream.add_callback(self.on_msg_camera_stream,
[obstacles_stream])
time_to_decision_stream.add_callback(self.on_time_to_decision_update)
self._flags = flags
self._logger = erdos.utils.setup_logging(self.config.name,
self.config.log_file_name)
self._csv_logger = erdos.utils.setup_csv_logging(
self.config.name + '-csv', self.config.csv_log_file_name)
# Load the COCO labels.
self._coco_labels = load_coco_labels(self._flags.path_coco_labels)
self._bbox_colors = load_coco_bbox_colors(self._coco_labels)
self._important_labels = {
'car', 'bicycle', 'motorcycle', 'bus', 'truck', 'vehicle',
'person', 'stop sign', 'parking meter', 'cat', 'dog',
'speed limit 30', 'speed limit 60', 'speed limit 90'
}
# Build inputs and preprocessing.
tf.compat.v1.disable_eager_execution()
assert len(model_names) == len(
model_paths), 'Model names and paths do not have same length'
self._models = {}
for index, model_path in enumerate(model_paths):
model_name = model_names[index]
self._models[model_name] = self.load_model(model_name, model_path,
flags)
if index == 0:
# Use the first model by default.
(self._model_name, self._tf_session, self._image_placeholder,
self._detections_batch) = self._models[model_name]
self._unique_id = 0
def load_model(self, model_name, model_path, flags):
graph = tf.Graph()
# Initialize the Config and Session.
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=flags.
obstacle_detection_gpu_memory_fraction,
allow_growth=True)
tf_session = tf.Session(graph=graph,
config=tf.ConfigProto(gpu_options=gpu_options))
with graph.as_default():
# Get the required arguments to initialize Inference.
image_size = hparams_config.get_detection_config(
model_name).image_size
driver = infer.InferenceDriver(model_name, model_path, image_size,
NUM_CLASSES)
image_placeholder = tf.placeholder("uint8", [None, None, 3],
name="image_tensor")
raw_images, images, scales = \
EfficientDetOperator.build_inputs_with_placeholder(
image_placeholder, image_size)
# Build model.
class_outputs, box_outputs = infer.build_model(model_name, images)
infer.restore_ckpt(tf_session,
model_path,
enable_ema=True,
export_ckpt=None)
# Build postprocessing.
params = copy.deepcopy(driver.params)
params.update(dict(batch_size=1))
detections_batch = None
if MODIFIED_AUTOML:
detections_batch = EfficientDetOperator.det_post_process(
params, class_outputs, box_outputs, scales)
else:
detections_batch = infer.det_post_process(
params,
class_outputs,
box_outputs,
scales,
min_score_thresh=self._flags.
obstacle_detection_min_score_threshold)
return model_name, tf_session, image_placeholder, detections_batch
@staticmethod
def connect(camera_stream, time_to_decision_stream):
"""Connects the operator to other streams.
Args:
camera_stream (:py:class:`erdos.ReadStream`): The stream on which
camera frames are received.
Returns:
:py:class:`erdos.WriteStream`: Stream on which the operator sends
:py:class:`~pylot.perception.messages.ObstaclesMessage` messages.
"""
obstacles_stream = erdos.WriteStream()
return [obstacles_stream]
def pick_model(self, ttd):
"""Decides which model to use based on time to decision."""
runtimes = [('efficientdet-d7', 262), ('efficientdet-d6', 190),
('efficientdet-d5', 141), ('efficientdet-d4', 74),
('efficientdet-d3', 42), ('efficientdet-d2', 24),
('efficientdet-d1', 20), ('efficientdet-d0', 16)]
fastest_loaded_model_name = None
for index, (model_name, runtime) in enumerate(runtimes):
# Pick the model if it is preloaded and if we have enough time to
# run it.
if ttd >= runtime and model_name in self._models:
self._logger.debug('Using detection model {}; ttd {}'.format(
model_name, ttd))
return self._models[model_name]
if model_name in self._models:
fastest_loaded_model_name = model_name
# Not enough time to run detection.
self._logger.error(
'Insufficient time to run detection. Using detection model {}'.
format(fastest_loaded_model_name))
return self._models[fastest_loaded_model_name]
def on_time_to_decision_update(self, msg):
self._logger.debug('@{}: {} received ttd update {}'.format(
msg.timestamp, self.config.name, msg))
if self._flags.deadline_enforcement == 'dynamic':
(self._model_name, self._tf_session, self._image_placeholder,
self._detections_batch) = self.pick_model(msg.data)
elif self._flags.deadline_enforcement == 'static':
(self._model_name, self._tf_session, self._image_placeholder,
self._detections_batch) = self.pick_model(
self._flags.detection_deadline)
else:
return
@erdos.profile_method()
def on_msg_camera_stream(self, msg, obstacles_stream):
"""Invoked whenever a frame message is received on the stream.
Args:
msg (:py:class:`~pylot.perception.messages.FrameMessage`): Message
received.
obstacles_stream (:py:class:`erdos.WriteStream`): Stream on which
the operator sends
:py:class:`~pylot.perception.messages.ObstaclesMessage`
messages.
"""
operator_time_total_start = time.time()
start_time = time.time()
self._logger.debug('@{}: {} received message'.format(
msg.timestamp, self.config.name))
inputs = msg.frame.as_rgb_numpy_array()
results = []
start_time = time.time()
if MODIFIED_AUTOML:
(boxes_np, scores_np, classes_np,
num_detections_np) = self._tf_session.run(
self._detections_batch,
feed_dict={self._image_placeholder: inputs})
num_detections = num_detections_np[0]
boxes = boxes_np[0][:num_detections]
scores = scores_np[0][:num_detections]
classes = classes_np[0][:num_detections]
results = zip(boxes, scores, classes)
else:
outputs_np = self._tf_session.run(
self._detections_batch,
feed_dict={self._image_placeholder: inputs})[0]
for _, x, y, width, height, score, _class in outputs_np:
results.append(((y, x, y + height, x + width), score, _class))
obstacles = []
for (ymin, xmin, ymax, xmax), score, _class in results:
if np.isclose(ymin, ymax) or np.isclose(xmin, xmax):
continue
if MODIFIED_AUTOML:
# The alternate NMS implementation screws up the class labels.
_class = int(_class) + 1
if _class in self._coco_labels:
if (score >= self._flags.obstacle_detection_min_score_threshold
and
self._coco_labels[_class] in self._important_labels):
camera_setup = msg.frame.camera_setup
width, height = camera_setup.width, camera_setup.height
xmin, xmax = max(0, int(xmin)), min(int(xmax), width)
ymin, ymax = max(0, int(ymin)), min(int(ymax), height)
if xmin < xmax and ymin < ymax:
obstacles.append(
DetectedObstacle(BoundingBox2D(
xmin, xmax, ymin, ymax),
score,
self._coco_labels[_class],
id=self._unique_id))
self._unique_id += 1
self._csv_logger.info(
"{},{},detection,{},{:4f}".format(
pylot.utils.time_epoch_ms(), msg.timestamp,
self._coco_labels[_class], score))
else:
self._logger.debug(
'Filtering unknown class: {}'.format(_class))
if (self._flags.visualize_detected_obstacles
or self._flags.log_detector_output):
msg.frame.annotate_with_bounding_boxes(msg.timestamp, obstacles,
None, self._bbox_colors)
if self._flags.visualize_detected_obstacles:
msg.frame.visualize(self.config.name,
pygame_display=pylot.utils.PYGAME_DISPLAY)
if self._flags.log_detector_output:
msg.frame.save(msg.timestamp.coordinates[0],
self._flags.data_path,
'detector-{}'.format(self.config.name))
end_time = time.time()
obstacles_stream.send(ObstaclesMessage(msg.timestamp, obstacles, 0))
obstacles_stream.send(erdos.WatermarkMessage(msg.timestamp))
operator_time_total_end = time.time()
self._logger.debug("@{}: runtime of the detector: {}".format(
msg.timestamp, (end_time - start_time) * 1000))
self._logger.debug("@{}: total time spent: {}".format(
msg.timestamp,
(operator_time_total_end - operator_time_total_start) * 1000))
@staticmethod
def build_inputs_with_placeholder(image, image_size):
""" Builds the input image using a placeholder.
Args:
image: A placeholder for the image.
image_size: a single integer for image width and height.
Returns
(raw_images, processed_image_placeholder, scales)
"""
raw_images, images, scales = [], [], []
raw_images.append(image)
image, scale = infer.image_preprocess(image, image_size)
images.append(image)
scales.append(scale)
return raw_images, tf.stack(images), tf.stack(scales)
@staticmethod
def det_post_process(params, class_outputs, box_outputs, scales):
from object_detection.core.post_processing import \
batch_multiclass_non_max_suppression
cls_outputs_all, box_outputs_all = [], []
for level in range(params['min_level'], params['max_level'] + 1):
cls_outputs_all.append(
tf.reshape(class_outputs[level],
[params['batch_size'], -1, params['num_classes']]))
box_outputs_all.append(
tf.reshape(box_outputs[level], [params['batch_size'], -1, 4]))
cls_outputs_all = tf.concat(cls_outputs_all, 1)
box_outputs_all = tf.concat(box_outputs_all, 1)
probs = tf.math.sigmoid(cls_outputs_all)
# Generate location of anchors.
eval_anchors = tf.transpose(
anchors.Anchors(params['min_level'], params['max_level'],
params['num_scales'], params['aspect_ratios'],
params['anchor_scale'],
params['image_size']).boxes)
ycenter_a = (eval_anchors[0] + eval_anchors[2]) / 2
xcenter_a = (eval_anchors[1] + eval_anchors[3]) / 2
ha = eval_anchors[2] - eval_anchors[0]
wa = eval_anchors[3] - eval_anchors[1]
# Generate absolute bboxes in the units of pixels of the image.
box_outputs_per_sample = tf.transpose(box_outputs_all[0])
ty, tx, th, tw = (box_outputs_per_sample[0], box_outputs_per_sample[1],
box_outputs_per_sample[2], box_outputs_per_sample[3])
w, h = tf.math.exp(tw) * wa, tf.math.exp(th) * ha
ycenter, xcenter = ty * ha + ycenter_a, tx * wa + xcenter_a
ymin, ymax = ycenter - h / 2.0, ycenter + h / 2.0
xmin, xmax = xcenter - w / 2.0, xcenter + w / 2.0
boxes = tf.transpose(tf.stack([ymin, xmin, ymax, xmax]))
# Generate the outputs
boxes_all = tf.reshape(boxes, [params['batch_size'], -1, 1, 4])
probs_all = tf.reshape(
probs, [params['batch_size'], -1, params['num_classes']])
(boxes_tf, scores_tf, classes_tf, _, _, num_detections_tf) = \
batch_multiclass_non_max_suppression(
boxes=boxes_all, scores=probs_all, score_thresh=0.5,
iou_thresh=0.5,
max_size_per_class=anchors.MAX_DETECTIONS_PER_IMAGE,
max_total_size=anchors.MAX_DETECTIONS_PER_IMAGE,
use_combined_nms=False, use_class_agnostic_nms=True)
boxes_tf *= scales
return [boxes_tf, scores_tf, classes_tf, num_detections_tf]
|
[
"pylot.perception.detection.utils.load_coco_labels",
"tensorflow.reshape",
"inference.image_preprocess",
"tensorflow.compat.v1.disable_eager_execution",
"tensorflow.ConfigProto",
"numpy.isclose",
"tensorflow.GPUOptions",
"erdos.profile_method",
"erdos.utils.setup_csv_logging",
"pylot.perception.messages.ObstaclesMessage",
"inference.InferenceDriver",
"pylot.perception.detection.utils.load_coco_bbox_colors",
"tensorflow.math.sigmoid",
"tensorflow.concat",
"hparams_config.get_detection_config",
"tensorflow.stack",
"tensorflow.placeholder",
"object_detection.core.post_processing.batch_multiclass_non_max_suppression",
"pylot.perception.detection.utils.BoundingBox2D",
"inference.det_post_process",
"erdos.WatermarkMessage",
"copy.deepcopy",
"inference.restore_ckpt",
"tensorflow.transpose",
"inference.build_model",
"tensorflow.Graph",
"tensorflow.math.exp",
"erdos.utils.setup_logging",
"anchors.Anchors",
"time.time",
"erdos.WriteStream"
] |
[((8167, 8189), 'erdos.profile_method', 'erdos.profile_method', ([], {}), '()\n', (8187, 8189), False, 'import erdos\n'), ((2318, 2388), 'erdos.utils.setup_logging', 'erdos.utils.setup_logging', (['self.config.name', 'self.config.log_file_name'], {}), '(self.config.name, self.config.log_file_name)\n', (2343, 2388), False, 'import erdos\n'), ((2465, 2557), 'erdos.utils.setup_csv_logging', 'erdos.utils.setup_csv_logging', (["(self.config.name + '-csv')", 'self.config.csv_log_file_name'], {}), "(self.config.name + '-csv', self.config.\n csv_log_file_name)\n", (2494, 2557), False, 'import erdos\n'), ((2627, 2673), 'pylot.perception.detection.utils.load_coco_labels', 'load_coco_labels', (['self._flags.path_coco_labels'], {}), '(self._flags.path_coco_labels)\n', (2643, 2673), False, 'from pylot.perception.detection.utils import BoundingBox2D, DetectedObstacle, load_coco_bbox_colors, load_coco_labels\n'), ((2702, 2742), 'pylot.perception.detection.utils.load_coco_bbox_colors', 'load_coco_bbox_colors', (['self._coco_labels'], {}), '(self._coco_labels)\n', (2723, 2742), False, 'from pylot.perception.detection.utils import BoundingBox2D, DetectedObstacle, load_coco_bbox_colors, load_coco_labels\n'), ((3041, 3079), 'tensorflow.compat.v1.disable_eager_execution', 'tf.compat.v1.disable_eager_execution', ([], {}), '()\n', (3077, 3079), True, 'import tensorflow as tf\n'), ((3788, 3798), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (3796, 3798), True, 'import tensorflow as tf\n'), ((3866, 3981), 'tensorflow.GPUOptions', 'tf.GPUOptions', ([], {'per_process_gpu_memory_fraction': 'flags.obstacle_detection_gpu_memory_fraction', 'allow_growth': '(True)'}), '(per_process_gpu_memory_fraction=flags.\n obstacle_detection_gpu_memory_fraction, allow_growth=True)\n', (3879, 3981), True, 'import tensorflow as tf\n'), ((6309, 6328), 'erdos.WriteStream', 'erdos.WriteStream', ([], {}), '()\n', (6326, 6328), False, 'import erdos\n'), ((8699, 8710), 'time.time', 'time.time', ([], {}), '()\n', (8708, 8710), False, 'import time\n'), ((8732, 8743), 'time.time', 'time.time', ([], {}), '()\n', (8741, 8743), False, 'import time\n'), ((8943, 8954), 'time.time', 'time.time', ([], {}), '()\n', (8952, 8954), False, 'import time\n'), ((12118, 12129), 'time.time', 'time.time', ([], {}), '()\n', (12127, 12129), False, 'import time\n'), ((12310, 12321), 'time.time', 'time.time', ([], {}), '()\n', (12319, 12321), False, 'import time\n'), ((13077, 13118), 'inference.image_preprocess', 'infer.image_preprocess', (['image', 'image_size'], {}), '(image, image_size)\n', (13099, 13118), True, 'import inference as infer\n'), ((13866, 13895), 'tensorflow.concat', 'tf.concat', (['cls_outputs_all', '(1)'], {}), '(cls_outputs_all, 1)\n', (13875, 13895), True, 'import tensorflow as tf\n'), ((13922, 13951), 'tensorflow.concat', 'tf.concat', (['box_outputs_all', '(1)'], {}), '(box_outputs_all, 1)\n', (13931, 13951), True, 'import tensorflow as tf\n'), ((13968, 14000), 'tensorflow.math.sigmoid', 'tf.math.sigmoid', (['cls_outputs_all'], {}), '(cls_outputs_all)\n', (13983, 14000), True, 'import tensorflow as tf\n'), ((14653, 14685), 'tensorflow.transpose', 'tf.transpose', (['box_outputs_all[0]'], {}), '(box_outputs_all[0])\n', (14665, 14685), True, 'import tensorflow as tf\n'), ((15205, 15256), 'tensorflow.reshape', 'tf.reshape', (['boxes', "[params['batch_size'], -1, 1, 4]"], {}), "(boxes, [params['batch_size'], -1, 1, 4])\n", (15215, 15256), True, 'import tensorflow as tf\n'), ((15277, 15345), 'tensorflow.reshape', 'tf.reshape', (['probs', "[params['batch_size'], -1, params['num_classes']]"], {}), "(probs, [params['batch_size'], -1, params['num_classes']])\n", (15287, 15345), True, 'import tensorflow as tf\n'), ((15442, 15720), 'object_detection.core.post_processing.batch_multiclass_non_max_suppression', 'batch_multiclass_non_max_suppression', ([], {'boxes': 'boxes_all', 'scores': 'probs_all', 'score_thresh': '(0.5)', 'iou_thresh': '(0.5)', 'max_size_per_class': 'anchors.MAX_DETECTIONS_PER_IMAGE', 'max_total_size': 'anchors.MAX_DETECTIONS_PER_IMAGE', 'use_combined_nms': '(False)', 'use_class_agnostic_nms': '(True)'}), '(boxes=boxes_all, scores=probs_all,\n score_thresh=0.5, iou_thresh=0.5, max_size_per_class=anchors.\n MAX_DETECTIONS_PER_IMAGE, max_total_size=anchors.\n MAX_DETECTIONS_PER_IMAGE, use_combined_nms=False,\n use_class_agnostic_nms=True)\n', (15478, 15720), False, 'from object_detection.core.post_processing import batch_multiclass_non_max_suppression\n'), ((4398, 4468), 'inference.InferenceDriver', 'infer.InferenceDriver', (['model_name', 'model_path', 'image_size', 'NUM_CLASSES'], {}), '(model_name, model_path, image_size, NUM_CLASSES)\n', (4419, 4468), True, 'import inference as infer\n'), ((4545, 4606), 'tensorflow.placeholder', 'tf.placeholder', (['"""uint8"""', '[None, None, 3]'], {'name': '"""image_tensor"""'}), "('uint8', [None, None, 3], name='image_tensor')\n", (4559, 4606), True, 'import tensorflow as tf\n'), ((4885, 4922), 'inference.build_model', 'infer.build_model', (['model_name', 'images'], {}), '(model_name, images)\n', (4902, 4922), True, 'import inference as infer\n'), ((4935, 5012), 'inference.restore_ckpt', 'infer.restore_ckpt', (['tf_session', 'model_path'], {'enable_ema': '(True)', 'export_ckpt': 'None'}), '(tf_session, model_path, enable_ema=True, export_ckpt=None)\n', (4953, 5012), True, 'import inference as infer\n'), ((5164, 5192), 'copy.deepcopy', 'copy.deepcopy', (['driver.params'], {}), '(driver.params)\n', (5177, 5192), False, 'import copy\n'), ((12160, 12205), 'pylot.perception.messages.ObstaclesMessage', 'ObstaclesMessage', (['msg.timestamp', 'obstacles', '(0)'], {}), '(msg.timestamp, obstacles, 0)\n', (12176, 12205), False, 'from pylot.perception.messages import ObstaclesMessage\n'), ((12237, 12274), 'erdos.WatermarkMessage', 'erdos.WatermarkMessage', (['msg.timestamp'], {}), '(msg.timestamp)\n', (12259, 12274), False, 'import erdos\n'), ((13204, 13220), 'tensorflow.stack', 'tf.stack', (['images'], {}), '(images)\n', (13212, 13220), True, 'import tensorflow as tf\n'), ((13222, 13238), 'tensorflow.stack', 'tf.stack', (['scales'], {}), '(scales)\n', (13230, 13238), True, 'import tensorflow as tf\n'), ((15117, 15151), 'tensorflow.stack', 'tf.stack', (['[ymin, xmin, ymax, xmax]'], {}), '([ymin, xmin, ymax, xmax])\n', (15125, 15151), True, 'import tensorflow as tf\n'), ((4135, 4174), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'gpu_options': 'gpu_options'}), '(gpu_options=gpu_options)\n', (4149, 4174), True, 'import tensorflow as tf\n'), ((4301, 4348), 'hparams_config.get_detection_config', 'hparams_config.get_detection_config', (['model_name'], {}), '(model_name)\n', (4336, 4348), False, 'import hparams_config\n'), ((5498, 5637), 'inference.det_post_process', 'infer.det_post_process', (['params', 'class_outputs', 'box_outputs', 'scales'], {'min_score_thresh': 'self._flags.obstacle_detection_min_score_threshold'}), '(params, class_outputs, box_outputs, scales,\n min_score_thresh=self._flags.obstacle_detection_min_score_threshold)\n', (5520, 5637), True, 'import inference as infer\n'), ((9856, 9878), 'numpy.isclose', 'np.isclose', (['ymin', 'ymax'], {}), '(ymin, ymax)\n', (9866, 9878), True, 'import numpy as np\n'), ((9882, 9904), 'numpy.isclose', 'np.isclose', (['xmin', 'xmax'], {}), '(xmin, xmax)\n', (9892, 9904), True, 'import numpy as np\n'), ((13613, 13701), 'tensorflow.reshape', 'tf.reshape', (['class_outputs[level]', "[params['batch_size'], -1, params['num_classes']]"], {}), "(class_outputs[level], [params['batch_size'], -1, params[\n 'num_classes']])\n", (13623, 13701), True, 'import tensorflow as tf\n'), ((13777, 13838), 'tensorflow.reshape', 'tf.reshape', (['box_outputs[level]', "[params['batch_size'], -1, 4]"], {}), "(box_outputs[level], [params['batch_size'], -1, 4])\n", (13787, 13838), True, 'import tensorflow as tf\n'), ((14091, 14251), 'anchors.Anchors', 'anchors.Anchors', (["params['min_level']", "params['max_level']", "params['num_scales']", "params['aspect_ratios']", "params['anchor_scale']", "params['image_size']"], {}), "(params['min_level'], params['max_level'], params[\n 'num_scales'], params['aspect_ratios'], params['anchor_scale'], params[\n 'image_size'])\n", (14106, 14251), False, 'import anchors\n'), ((14861, 14876), 'tensorflow.math.exp', 'tf.math.exp', (['tw'], {}), '(tw)\n', (14872, 14876), True, 'import tensorflow as tf\n'), ((14883, 14898), 'tensorflow.math.exp', 'tf.math.exp', (['th'], {}), '(th)\n', (14894, 14898), True, 'import tensorflow as tf\n'), ((10735, 10772), 'pylot.perception.detection.utils.BoundingBox2D', 'BoundingBox2D', (['xmin', 'xmax', 'ymin', 'ymax'], {}), '(xmin, xmax, ymin, ymax)\n', (10748, 10772), False, 'from pylot.perception.detection.utils import BoundingBox2D, DetectedObstacle, load_coco_bbox_colors, load_coco_labels\n')]
|
from entente.equality import have_same_topology
from lacecore import shapes
import numpy as np
def test_have_same_topology():
cube_1 = shapes.cube(np.zeros(3), 1.0)
cube_2 = shapes.cube(np.zeros(3), 1.0)
assert have_same_topology(cube_1, cube_2) is True
cube_1 = shapes.cube(np.zeros(3), 1.0)
cube_2 = shapes.cube(np.ones(3), 1.0)
assert have_same_topology(cube_1, cube_2) is True
cube_1 = shapes.cube(np.zeros(3), 1.0)
cube_2 = shapes.cube(np.zeros(3), 1.0)
cube_2.f = np.roll(cube_2.f, 1, axis=1)
assert have_same_topology(cube_1, cube_2) is False
cube_1 = shapes.cube(np.zeros(3), 1.0)
cube_2 = shapes.cube(np.zeros(3), 1.0)
cube_2.f = np.zeros((0, 3), dtype=np.uint64)
assert have_same_topology(cube_1, cube_2) is False
def test_have_same_topology_legacy():
# `lace.mesh.Mesh` uses None for empty vert or face arrays.
class LegacyMesh:
v = None
f = np.array((0, 3))
assert have_same_topology(LegacyMesh(), LegacyMesh()) is True
|
[
"numpy.roll",
"numpy.zeros",
"numpy.ones",
"numpy.array",
"entente.equality.have_same_topology"
] |
[((511, 539), 'numpy.roll', 'np.roll', (['cube_2.f', '(1)'], {'axis': '(1)'}), '(cube_2.f, 1, axis=1)\n', (518, 539), True, 'import numpy as np\n'), ((697, 730), 'numpy.zeros', 'np.zeros', (['(0, 3)'], {'dtype': 'np.uint64'}), '((0, 3), dtype=np.uint64)\n', (705, 730), True, 'import numpy as np\n'), ((154, 165), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (162, 165), True, 'import numpy as np\n'), ((197, 208), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (205, 208), True, 'import numpy as np\n'), ((226, 260), 'entente.equality.have_same_topology', 'have_same_topology', (['cube_1', 'cube_2'], {}), '(cube_1, cube_2)\n', (244, 260), False, 'from entente.equality import have_same_topology\n'), ((295, 306), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (303, 306), True, 'import numpy as np\n'), ((338, 348), 'numpy.ones', 'np.ones', (['(3)'], {}), '(3)\n', (345, 348), True, 'import numpy as np\n'), ((366, 400), 'entente.equality.have_same_topology', 'have_same_topology', (['cube_1', 'cube_2'], {}), '(cube_1, cube_2)\n', (384, 400), False, 'from entente.equality import have_same_topology\n'), ((435, 446), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (443, 446), True, 'import numpy as np\n'), ((478, 489), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (486, 489), True, 'import numpy as np\n'), ((551, 585), 'entente.equality.have_same_topology', 'have_same_topology', (['cube_1', 'cube_2'], {}), '(cube_1, cube_2)\n', (569, 585), False, 'from entente.equality import have_same_topology\n'), ((621, 632), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (629, 632), True, 'import numpy as np\n'), ((664, 675), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (672, 675), True, 'import numpy as np\n'), ((742, 776), 'entente.equality.have_same_topology', 'have_same_topology', (['cube_1', 'cube_2'], {}), '(cube_1, cube_2)\n', (760, 776), False, 'from entente.equality import have_same_topology\n'), ((941, 957), 'numpy.array', 'np.array', (['(0, 3)'], {}), '((0, 3))\n', (949, 957), True, 'import numpy as np\n')]
|
import numpy as np
from gym_collision_avoidance.envs.config import Config
from gym_collision_avoidance.envs.util import wrap, find_nearest
from gym_collision_avoidance.envs.utils import end_conditions as ec
import operator
import math
class Agent(object):
def __init__(self, start_x, start_y, goal_x, goal_y, radius,
pref_speed, initial_heading, policy, dynamics_model, sensors, id, cooperation_coef = 1.0):
if policy =="GA3CCADRLPolicy":
self.policy = "GA3CCADRLPolicy"
else:
self.policy = policy()
self.dynamics_model = dynamics_model(self)
self.sensors = [sensor() for sensor in sensors]
# Global Frame states
self.pos_global_frame = np.array([start_x, start_y], dtype='float64')
self.goal_global_frame = np.array([goal_x, goal_y], dtype='float64')
self.next_goal = np.array([goal_x, goal_y], dtype='float64')
self.rel_goal = self.goal_global_frame - self.pos_global_frame
self.vel_global_frame = np.array([0.0, 0.0], dtype='float64')
self.speed_global_frame = 0.0
self.angular_speed_global_frame = 0.0
if initial_heading is None:
vec_to_goal = self.goal_global_frame - self.pos_global_frame
self.heading_global_frame = np.arctan2(vec_to_goal[1], vec_to_goal[0])
else:
self.heading_global_frame = initial_heading
self.delta_heading_global_frame = 0.0
# Ego Frame states
self.speed_ego_frame = 0.0
self.heading_ego_frame = 0.0
self.vel_ego_frame = np.array([0.0, 0.0])
# Store past selected actions
self.chosen_action_dict = {}
self.num_actions_to_store = 2
self.action_dim = 2
self.past_actions = np.zeros((self.num_actions_to_store,
self.action_dim))
self.next_state = []
self.sensor_data_history = []
# Other parameters
self.radius = radius
self.pref_speed = pref_speed
self.id = id
self.dist_to_goal = 0.0
self.near_goal_threshold = Config.NEAR_GOAL_THRESHOLD
self.end_condition = ec._check_if_at_goal
self.straight_line_time_to_reach_goal = (np.linalg.norm(self.pos_global_frame - self.goal_global_frame) - self.near_goal_threshold)/self.pref_speed
if Config.EVALUATE_MODE or Config.PLAY_MODE:
self.time_remaining_to_reach_goal = Config.MAX_TIME_RATIO*self.straight_line_time_to_reach_goal
else:
self.time_remaining_to_reach_goal = Config.MAX_TIME_RATIO*self.straight_line_time_to_reach_goal
self.t = 0.0
self.t_offset = None
self.step_num = 0
self.is_at_goal = False
self.was_at_goal_already = False
self.was_in_collision_already = False
self.in_collision = False
self.ran_out_of_time = False
self.is_infeasible = False
self.min_x = -20.0
self.max_x = 20.0
self.min_y = -20.0
self.max_y = 20.0
self.num_states_in_history = 10000
self.global_state_dim = 13
self.global_state_history = np.zeros((self.num_states_in_history, self.global_state_dim))
self.ego_state_dim = 3
self.ego_state_history = np.empty((self.num_states_in_history, self.ego_state_dim))
# self.past_actions = np.zeros((self.num_actions_to_store,2))
self.past_global_velocities = np.zeros((self.num_actions_to_store,2))
self.past_global_velocities = self.vel_global_frame * np.ones((self.num_actions_to_store,2))
self.other_agent_states = np.zeros((10,))
self.dynamics_model.update_ego_frame()
# self._update_state_history()
# self._check_if_at_goal()
# self.take_action([0.0, 0.0])
self.dt_nominal = Config.DT
self.min_dist_to_other_agents = np.inf
self.turning_dir = 0.0
self.cooperation_coef = cooperation_coef
# self.latest_laserscan = LaserScan()
# self.latest_laserscan.ranges = 10*np.ones(Config.LASERSCAN_LENGTH)
self.is_done = False
self.warm_start = False
def __deepcopy__(self, memo):
# Copy every attribute about the agent except its policy
cls = self.__class__
obj = cls.__new__(cls)
for k, v in self.__dict__.items():
if k != 'policy':
setattr(obj, k, v)
return obj
def _check_if_at_goal(self):
#is_near_goal = (self.pos_global_frame[0] - self.goal_global_frame[0])**2 + (self.pos_global_frame[1] - self.goal_global_frame[1])**2 <= self.near_goal_threshold**2
#self.is_at_goal = is_near_goal
self.end_condition(self)
def set_state(self, px, py, vx=None, vy=None, heading=None):
if vx is None or vy is None:
if self.step_num == 0:
# On first timestep, just set to zero
self.vel_global_frame = np.array([0,0])
else:
# Interpolate velocity from last pos
self.vel_global_frame = (np.array([px, py]) - self.pos_global_frame) / self.dt_nominal
else:
self.vel_global_frame = np.array([vx, vy])
if heading is None:
# Estimate heading to be the direction of the velocity vector
heading = np.arctan2(self.vel_global_frame[1], self.vel_global_frame[0])
self.delta_heading_global_frame = wrap(heading - self.heading_global_frame)
else:
self.delta_heading_global_frame = wrap(heading - self.heading_global_frame)
self.pos_global_frame = np.array([px, py])
self.speed_global_frame = np.linalg.norm(self.vel_global_frame)
self.heading_global_frame = heading
def take_action(self, action, dt):
if self.is_at_goal or self.ran_out_of_time or self.in_collision:
if self.is_at_goal:
self.was_at_goal_already = True
if self.in_collision:
self.was_in_collision_already = True
self._update_state_history()
if not self.is_at_goal:
self.t += dt
#self.step_num += 1
self.vel_global_frame = np.array([0.0, 0.0])
self._store_past_velocities()
return
# Store past actions
self.past_actions = np.roll(self.past_actions, 1, axis=0)
self.past_actions[0, :] = action
# Store info about the TF btwn the ego frame and global frame before moving agent
goal_direction = self.goal_global_frame - self.pos_global_frame
theta = np.arctan2(goal_direction[1], goal_direction[0])
self.T_global_ego = np.array([[np.cos(theta), -np.sin(theta), self.pos_global_frame[0]], [np.sin(theta), np.cos(theta), self.pos_global_frame[1]], [0,0,1]])
self.ego_to_global_theta = theta
# In the case of ExternalDynamics, this call does nothing,
# but set_state was called instead
self.dynamics_model.step(action, dt)
self.dynamics_model.update_ego_frame()
self._update_state_history()
self._check_if_at_goal()
self._store_past_velocities()
# Update time left so agent does not run around forever
self.time_remaining_to_reach_goal -= dt
self.t += dt
self.step_num += 1
if self.time_remaining_to_reach_goal <= 0.0:
self.ran_out_of_time = True
return
def sense(self, agents, agent_index, top_down_map):
self.sensor_data = {}
for sensor in self.sensors:
sensor_data = sensor.sense(agents, agent_index, top_down_map)
self.sensor_data[sensor.name] = sensor_data
def _update_state_history(self):
global_state, ego_state = self.to_vector()
self.global_state_history[self.step_num, :] = global_state
self.ego_state_history[self.step_num, :] = ego_state
if ('local_grid' in self.sensor_data) :
self.sensor_data_history.append(self.sensor_data['local_grid'])
def print_agent_info(self):
print('----------')
print('Global Frame:')
print('(px,py):', self.pos_global_frame)
print('(vx,vy):', self.vel_global_frame)
print('speed:', self.speed_global_frame)
print('heading:', self.heading_global_frame)
print('Body Frame:')
print('(vx,vy):', self.vel_ego_frame)
print('heading:', self.heading_ego_frame)
print('----------')
def to_vector(self):
global_state = np.array([self.t,
self.pos_global_frame[0],
self.pos_global_frame[1],
self.goal_global_frame[0],
self.goal_global_frame[1],
self.radius,
self.pref_speed,
self.vel_global_frame[0],
self.vel_global_frame[1],
self.speed_global_frame,
self.heading_global_frame,
self.past_actions[0, 0],
self.past_actions[0, 1]])
ego_state = np.array([self.t, self.dist_to_goal, self.heading_ego_frame])
return global_state, ego_state
def get_sensor_data(self, sensor_name):
if sensor_name in self.sensor_data:
return self.sensor_data[sensor_name]
def get_agent_data(self, attribute):
return getattr(self, attribute)
def get_agent_data_equiv(self, attribute, value):
return eval("self."+attribute) == value
def get_observation_dict(self, agents):
observation = {}
for state in Config.STATES_IN_OBS:
observation[state] = np.array(eval("self." + Config.STATE_INFO_DICT[state]['attr']))
return observation
def get_ref(self):
#
# Using current and goal position of agent in global frame,
# compute coordinate axes of ego frame
#
# Returns:
# ref_prll: vector pointing from agent position -> goal
# ref_orthog: vector orthogonal to ref_prll
#
goal_direction = self.goal_global_frame - self.pos_global_frame
self.past_dist_to_goal = self.dist_to_goal
self.dist_to_goal = math.sqrt(goal_direction[0]**2 + goal_direction[1]**2)
if self.t == 0:
self.past_dist_to_goal = self.dist_to_goal
if self.dist_to_goal > 1e-8:
ref_prll = goal_direction / self.dist_to_goal
else:
ref_prll = goal_direction
ref_orth = np.array([-ref_prll[1], ref_prll[0]]) # rotate by 90 deg
return ref_prll, ref_orth
def _store_past_velocities(self):
self.past_global_velocities = np.roll(self.past_global_velocities,1,axis=0)
self.past_global_velocities[0,:] = self.vel_global_frame
def ego_pos_to_global_pos(self, ego_pos):
# goal_direction = self.goal_global_frame - self.pos_global_frame
# theta = np.arctan2(goal_direction[1], goal_direction[0])
# T_global_ego = np.array([[np.cos(theta), -np.sin(theta), self.pos_global_frame[0]], [np.sin(theta), np.cos(theta), self.pos_global_frame[1]], [0,0,1]])
if ego_pos.ndim == 1:
ego_pos_ = np.array([ego_pos[0], ego_pos[1], 1])
global_pos = np.dot(self.T_global_ego, ego_pos_)
return global_pos[:2]
else:
ego_pos_ = np.hstack([ego_pos, np.ones((ego_pos.shape[0],1))])
global_pos = np.dot(self.T_global_ego, ego_pos_.T).T
return global_pos[:,:2]
def global_pos_to_ego_pos(self, global_pos):
# goal_direction = self.goal_global_frame - self.pos_global_frame
# theta = np.arctan2(goal_direction[1], goal_direction[0])
# T_ego_global = np.linalg.inv(np.array([[np.cos(theta), -np.sin(theta), self.pos_global_frame[0]], [np.sin(theta), np.cos(theta), self.pos_global_frame[1]], [0,0,1]]))
ego_pos = np.dot(np.linalg.inv(self.T_global_ego), np.array([global_pos[0], global_pos[1], 1]))
return ego_pos[:2]
if __name__ == '__main__':
start_x = -3
start_y = 1
goal_x = 3
goal_y = 0
radius = 0.5
pref_speed = 1.2
initial_heading = 0.0
from gym_collision_avoidance.envs.policies.GA3CCADRLPolicy import GA3CCADRLPolicy
from gym_collision_avoidance.envs.dynamics.UnicycleDynamics import UnicycleDynamics
policy = GA3CCADRLPolicy
dynamics_model = UnicycleDynamics
sensors = []
id = 0
agent = Agent(start_x, start_y, goal_x, goal_y, radius,
pref_speed, initial_heading, policy, dynamics_model, sensors, id)
print(agent.ego_pos_to_global_pos(np.array([1,0.5])))
print(agent.global_pos_to_ego_pos(np.array([-1.93140658, 1.32879797])))
# agents = [Agent(start_x, start_y, goal_x, goal_y, radius,
# pref_speed, initial_heading, i) for i in range(4)]
# agents[0].observe(agents)
print("Created Agent.")
|
[
"numpy.arctan2",
"math.sqrt",
"numpy.roll",
"numpy.empty",
"numpy.zeros",
"numpy.ones",
"numpy.sin",
"numpy.array",
"numpy.linalg.norm",
"gym_collision_avoidance.envs.util.wrap",
"numpy.linalg.inv",
"numpy.cos",
"numpy.dot"
] |
[((734, 779), 'numpy.array', 'np.array', (['[start_x, start_y]'], {'dtype': '"""float64"""'}), "([start_x, start_y], dtype='float64')\n", (742, 779), True, 'import numpy as np\n'), ((813, 856), 'numpy.array', 'np.array', (['[goal_x, goal_y]'], {'dtype': '"""float64"""'}), "([goal_x, goal_y], dtype='float64')\n", (821, 856), True, 'import numpy as np\n'), ((882, 925), 'numpy.array', 'np.array', (['[goal_x, goal_y]'], {'dtype': '"""float64"""'}), "([goal_x, goal_y], dtype='float64')\n", (890, 925), True, 'import numpy as np\n'), ((1029, 1066), 'numpy.array', 'np.array', (['[0.0, 0.0]'], {'dtype': '"""float64"""'}), "([0.0, 0.0], dtype='float64')\n", (1037, 1066), True, 'import numpy as np\n'), ((1589, 1609), 'numpy.array', 'np.array', (['[0.0, 0.0]'], {}), '([0.0, 0.0])\n', (1597, 1609), True, 'import numpy as np\n'), ((1781, 1835), 'numpy.zeros', 'np.zeros', (['(self.num_actions_to_store, self.action_dim)'], {}), '((self.num_actions_to_store, self.action_dim))\n', (1789, 1835), True, 'import numpy as np\n'), ((3164, 3225), 'numpy.zeros', 'np.zeros', (['(self.num_states_in_history, self.global_state_dim)'], {}), '((self.num_states_in_history, self.global_state_dim))\n', (3172, 3225), True, 'import numpy as np\n'), ((3290, 3348), 'numpy.empty', 'np.empty', (['(self.num_states_in_history, self.ego_state_dim)'], {}), '((self.num_states_in_history, self.ego_state_dim))\n', (3298, 3348), True, 'import numpy as np\n'), ((3458, 3498), 'numpy.zeros', 'np.zeros', (['(self.num_actions_to_store, 2)'], {}), '((self.num_actions_to_store, 2))\n', (3466, 3498), True, 'import numpy as np\n'), ((3634, 3649), 'numpy.zeros', 'np.zeros', (['(10,)'], {}), '((10,))\n', (3642, 3649), True, 'import numpy as np\n'), ((5633, 5651), 'numpy.array', 'np.array', (['[px, py]'], {}), '([px, py])\n', (5641, 5651), True, 'import numpy as np\n'), ((5686, 5723), 'numpy.linalg.norm', 'np.linalg.norm', (['self.vel_global_frame'], {}), '(self.vel_global_frame)\n', (5700, 5723), True, 'import numpy as np\n'), ((6362, 6399), 'numpy.roll', 'np.roll', (['self.past_actions', '(1)'], {'axis': '(0)'}), '(self.past_actions, 1, axis=0)\n', (6369, 6399), True, 'import numpy as np\n'), ((6621, 6669), 'numpy.arctan2', 'np.arctan2', (['goal_direction[1]', 'goal_direction[0]'], {}), '(goal_direction[1], goal_direction[0])\n', (6631, 6669), True, 'import numpy as np\n'), ((8557, 8884), 'numpy.array', 'np.array', (['[self.t, self.pos_global_frame[0], self.pos_global_frame[1], self.\n goal_global_frame[0], self.goal_global_frame[1], self.radius, self.\n pref_speed, self.vel_global_frame[0], self.vel_global_frame[1], self.\n speed_global_frame, self.heading_global_frame, self.past_actions[0, 0],\n self.past_actions[0, 1]]'], {}), '([self.t, self.pos_global_frame[0], self.pos_global_frame[1], self.\n goal_global_frame[0], self.goal_global_frame[1], self.radius, self.\n pref_speed, self.vel_global_frame[0], self.vel_global_frame[1], self.\n speed_global_frame, self.heading_global_frame, self.past_actions[0, 0],\n self.past_actions[0, 1]])\n', (8565, 8884), True, 'import numpy as np\n'), ((9282, 9343), 'numpy.array', 'np.array', (['[self.t, self.dist_to_goal, self.heading_ego_frame]'], {}), '([self.t, self.dist_to_goal, self.heading_ego_frame])\n', (9290, 9343), True, 'import numpy as np\n'), ((10398, 10456), 'math.sqrt', 'math.sqrt', (['(goal_direction[0] ** 2 + goal_direction[1] ** 2)'], {}), '(goal_direction[0] ** 2 + goal_direction[1] ** 2)\n', (10407, 10456), False, 'import math\n'), ((10698, 10735), 'numpy.array', 'np.array', (['[-ref_prll[1], ref_prll[0]]'], {}), '([-ref_prll[1], ref_prll[0]])\n', (10706, 10735), True, 'import numpy as np\n'), ((10867, 10914), 'numpy.roll', 'np.roll', (['self.past_global_velocities', '(1)'], {'axis': '(0)'}), '(self.past_global_velocities, 1, axis=0)\n', (10874, 10914), True, 'import numpy as np\n'), ((1301, 1343), 'numpy.arctan2', 'np.arctan2', (['vec_to_goal[1]', 'vec_to_goal[0]'], {}), '(vec_to_goal[1], vec_to_goal[0])\n', (1311, 1343), True, 'import numpy as np\n'), ((3560, 3599), 'numpy.ones', 'np.ones', (['(self.num_actions_to_store, 2)'], {}), '((self.num_actions_to_store, 2))\n', (3567, 3599), True, 'import numpy as np\n'), ((5203, 5221), 'numpy.array', 'np.array', (['[vx, vy]'], {}), '([vx, vy])\n', (5211, 5221), True, 'import numpy as np\n'), ((5347, 5409), 'numpy.arctan2', 'np.arctan2', (['self.vel_global_frame[1]', 'self.vel_global_frame[0]'], {}), '(self.vel_global_frame[1], self.vel_global_frame[0])\n', (5357, 5409), True, 'import numpy as np\n'), ((5456, 5497), 'gym_collision_avoidance.envs.util.wrap', 'wrap', (['(heading - self.heading_global_frame)'], {}), '(heading - self.heading_global_frame)\n', (5460, 5497), False, 'from gym_collision_avoidance.envs.util import wrap, find_nearest\n'), ((5558, 5599), 'gym_collision_avoidance.envs.util.wrap', 'wrap', (['(heading - self.heading_global_frame)'], {}), '(heading - self.heading_global_frame)\n', (5562, 5599), False, 'from gym_collision_avoidance.envs.util import wrap, find_nearest\n'), ((6222, 6242), 'numpy.array', 'np.array', (['[0.0, 0.0]'], {}), '([0.0, 0.0])\n', (6230, 6242), True, 'import numpy as np\n'), ((11382, 11419), 'numpy.array', 'np.array', (['[ego_pos[0], ego_pos[1], 1]'], {}), '([ego_pos[0], ego_pos[1], 1])\n', (11390, 11419), True, 'import numpy as np\n'), ((11445, 11480), 'numpy.dot', 'np.dot', (['self.T_global_ego', 'ego_pos_'], {}), '(self.T_global_ego, ego_pos_)\n', (11451, 11480), True, 'import numpy as np\n'), ((12099, 12131), 'numpy.linalg.inv', 'np.linalg.inv', (['self.T_global_ego'], {}), '(self.T_global_ego)\n', (12112, 12131), True, 'import numpy as np\n'), ((12133, 12176), 'numpy.array', 'np.array', (['[global_pos[0], global_pos[1], 1]'], {}), '([global_pos[0], global_pos[1], 1])\n', (12141, 12176), True, 'import numpy as np\n'), ((12810, 12828), 'numpy.array', 'np.array', (['[1, 0.5]'], {}), '([1, 0.5])\n', (12818, 12828), True, 'import numpy as np\n'), ((12868, 12903), 'numpy.array', 'np.array', (['[-1.93140658, 1.32879797]'], {}), '([-1.93140658, 1.32879797])\n', (12876, 12903), True, 'import numpy as np\n'), ((2250, 2312), 'numpy.linalg.norm', 'np.linalg.norm', (['(self.pos_global_frame - self.goal_global_frame)'], {}), '(self.pos_global_frame - self.goal_global_frame)\n', (2264, 2312), True, 'import numpy as np\n'), ((4963, 4979), 'numpy.array', 'np.array', (['[0, 0]'], {}), '([0, 0])\n', (4971, 4979), True, 'import numpy as np\n'), ((11629, 11666), 'numpy.dot', 'np.dot', (['self.T_global_ego', 'ego_pos_.T'], {}), '(self.T_global_ego, ego_pos_.T)\n', (11635, 11666), True, 'import numpy as np\n'), ((6709, 6722), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (6715, 6722), True, 'import numpy as np\n'), ((6768, 6781), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (6774, 6781), True, 'import numpy as np\n'), ((6783, 6796), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (6789, 6796), True, 'import numpy as np\n'), ((11572, 11602), 'numpy.ones', 'np.ones', (['(ego_pos.shape[0], 1)'], {}), '((ego_pos.shape[0], 1))\n', (11579, 11602), True, 'import numpy as np\n'), ((5091, 5109), 'numpy.array', 'np.array', (['[px, py]'], {}), '([px, py])\n', (5099, 5109), True, 'import numpy as np\n'), ((6725, 6738), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (6731, 6738), True, 'import numpy as np\n')]
|
#Based on https://www.kaggle.com/tezdhar/wordbatch-with-memory-test
import gc
import time
import numpy as np
import pandas as pd
from scipy.sparse import csr_matrix, hstack
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.preprocessing import LabelBinarizer
from sklearn.model_selection import train_test_split
import psutil
import os
import wordbatch
from wordbatch.extractors import WordBag
from wordbatch.models import FTRL, FM_FTRL
from nltk.corpus import stopwords
import re
def rmsle(y, y0):
assert len(y) == len(y0)
return np.sqrt(np.mean(np.power(np.log1p(y) - np.log1p(y0), 2)))
def handle_missing_inplace(dataset):
dataset['description'].fillna(value='na', inplace=True)
dataset["image"].fillna("noinformation", inplace=True)
dataset["param_1"].fillna("nicapotato", inplace=True)
dataset["param_2"].fillna("nicapotato", inplace=True)
dataset["param_3"].fillna("nicapotato", inplace=True)
dataset['image_top_1'].fillna(value=-1, inplace=True)
dataset['price'].fillna(value=0, inplace=True)
def to_categorical(dataset):
dataset['param_1'] = dataset['param_1'].astype('category')
dataset['param_2'] = dataset['param_2'].astype('category')
dataset['param_3'] = dataset['param_3'].astype('category')
dataset['image_top_1'] = dataset['image_top_1'].astype('category')
dataset['image'] = dataset['image'].astype('category')
dataset['price'] = dataset['price'].astype('category')
#counting
dataset['num_desc_punct'] = dataset['num_desc_punct'].astype('category')
dataset['num_desc_capE'] = dataset['num_desc_capE'].astype('category')
dataset['num_desc_capP'] = dataset['num_desc_capP'].astype('category')
dataset['num_title_punct'] = dataset['num_title_punct'].astype('category')
dataset['num_title_capE'] = dataset['num_title_capE'].astype('category')
dataset['num_title_capP'] = dataset['num_title_capP'].astype('category')
dataset['is_in_desc_хорошо'] = dataset['is_in_desc_хорошо'].astype('category')
dataset['is_in_desc_Плохо'] = dataset['is_in_desc_Плохо'].astype('category')
dataset['is_in_desc_новый'] = dataset['is_in_desc_новый'].astype('category')
dataset['is_in_desc_старый'] = dataset['is_in_desc_старый'].astype('category')
dataset['is_in_desc_используемый'] = dataset['is_in_desc_используемый'].astype('category')
dataset['is_in_desc_есплатная_доставка'] = dataset['is_in_desc_есплатная_доставка'].astype('category')
dataset['is_in_desc_есплатный_возврат'] = dataset['is_in_desc_есплатный_возврат'].astype('category')
dataset['is_in_desc_идеально'] = dataset['is_in_desc_идеально'].astype('category')
dataset['is_in_desc_подержанный'] = dataset['is_in_desc_подержанный'].astype('category')
dataset['is_in_desc_пСниженные_цены'] = dataset['is_in_desc_пСниженные_цены'].astype('category')
#region
dataset['region'] = dataset['region'].astype('category')
dataset['city'] = dataset['city'].astype('category')
dataset['user_type'] = dataset['user_type'].astype('category')
dataset['category_name'] = dataset['category_name'].astype('category')
dataset['parent_category_name'] = dataset['parent_category_name'].astype('category')
# dataset['price+'] = dataset['price+'].astype('category')
# dataset['desc_len'] = dataset['desc_len'].astype('category')
# dataset['title_len'] = dataset['title_len'].astype('category')
# dataset['title_desc_len_ratio'] = dataset['title_desc_len_ratio'].astype('category')
# dataset['desc_word_count'] = dataset['desc_word_count'].astype('category')
# dataset['mean_des'] = dataset['mean_des'].astype('category')
# Define helpers for text normalization
stopwords = {x: 1 for x in stopwords.words('russian')}
non_alphanums = re.compile(u'[^A-Za-z0-9]+')
def normalize_text(text):
# if np.isnan(text): text='na'
return u" ".join(
[x for x in [y for y in non_alphanums.sub(' ', text).lower().strip().split(" ")] \
if len(x) > 1 and x not in stopwords])
develop = True
# develop= False
if __name__ == '__main__':
start_time = time.time()
from time import gmtime, strftime
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
import re
from scipy.sparse import hstack
from nltk.corpus import stopwords
from contextlib import contextmanager
@contextmanager
def timer(name):
t0 = time.time()
yield
print('[{}] done in {:.0f} s'.format(name, (time.time() - t0)))
import string
print(strftime("%Y-%m-%d %H:%M:%S", gmtime()))
print("\nData Load Stage")
# , nrows = nrows
nrows=10000*1
training = pd.read_csv('../input/train.csv', index_col="item_id", parse_dates=["activation_date"])
len_train = len(training)
traindex = training.index
testing = pd.read_csv('../input/test.csv', index_col="item_id", parse_dates=["activation_date"])
testdex = testing.index
# labels = training['deal_probability'].values
y = training.deal_probability.copy()
training.drop("deal_probability", axis=1, inplace=True)
# suppl
# used_cols = ["item_id", "user_id"]
# train_active = pd.read_csv("../input/train_active.csv", usecols=used_cols)
# test_active = pd.read_csv("../input/test_active.csv", usecols=used_cols)
# train_periods = pd.read_csv("../input/periods_train.csv", parse_dates=["date_from", "date_to"])
# test_periods = pd.read_csv("../input/periods_test.csv", parse_dates=["date_from", "date_to"])
# =============================================================================
# Add region-income
# =============================================================================
tmp = pd.read_csv("../input/region_income.csv", sep=";", names=["region", "income"])
training = training.merge(tmp, on="region", how="left")
testing = testing.merge(tmp, on="region", how="left")
del tmp;
gc.collect()
# =============================================================================
# Add region-income
# =============================================================================
tmp = pd.read_csv("../input/city_population_wiki_v3.csv",)
training = training.merge(tmp, on="city", how="left")
testing = testing.merge(tmp, on="city", how="left")
del tmp;
gc.collect()
import pickle
with open('../input/train_image_features.p', 'rb') as f:
x = pickle.load(f)
train_blurinesses = x['blurinesses']
train_ids = x['ids']
with open('../input/test_image_features.p', 'rb') as f:
x = pickle.load(f)
test_blurinesses = x['blurinesses']
test_ids = x['ids']
del x;
gc.collect()
incep_train_image_df = pd.DataFrame(train_blurinesses, columns=['blurinesses'])
incep_test_image_df = pd.DataFrame(test_blurinesses, columns=[f'blurinesses'])
incep_train_image_df['image'] = (train_ids)
incep_test_image_df['image'] = (test_ids)
training = training.join(incep_train_image_df.set_index('image'), on='image')
testing = testing.join(incep_test_image_df.set_index('image'), on='image')
print('adding whitenesses ...')
with open('../input/train_image_features.p', 'rb') as f:
x = pickle.load(f)
train_whitenesses = x['whitenesses']
train_ids = x['ids']
with open('../input/test_image_features.p', 'rb') as f:
x = pickle.load(f)
test_whitenesses = x['whitenesses']
test_ids = x['ids']
del x;
gc.collect()
incep_train_image_df = pd.DataFrame(train_whitenesses, columns=['whitenesses'])
incep_test_image_df = pd.DataFrame(test_whitenesses, columns=[f'whitenesses'])
incep_train_image_df['image'] = (train_ids)
incep_test_image_df['image'] = (test_ids)
training = training.join(incep_train_image_df.set_index('image'), on='image')
testing = testing.join(incep_test_image_df.set_index('image'), on='image')
print('adding dullnesses ...')
with open('../input/train_image_features.p', 'rb') as f:
x = pickle.load(f)
train_dullnesses = x['dullnesses']
train_ids = x['ids']
with open('../input/test_image_features.p', 'rb') as f:
x = pickle.load(f)
test_dullnesses = x['dullnesses']
test_ids = x['ids']
del x;
gc.collect()
incep_train_image_df = pd.DataFrame(train_dullnesses, columns=['dullnesses'])
incep_test_image_df = pd.DataFrame(test_dullnesses, columns=[f'dullnesses'])
incep_train_image_df['image'] = (train_ids)
incep_test_image_df['image'] = (test_ids)
training = training.join(incep_train_image_df.set_index('image'), on='image')
testing = testing.join(incep_test_image_df.set_index('image'), on='image')
print('adding average_pixel_width ...')
with open('../input/train_image_features_1.p', 'rb') as f:
x = pickle.load(f)
train_average_pixel_width = x['average_pixel_width']
train_ids = x['ids']
with open('../input/test_image_features_1.p', 'rb') as f:
x = pickle.load(f)
test_average_pixel_width = x['average_pixel_width']
test_ids = x['ids']
del x;
gc.collect()
incep_train_image_df = pd.DataFrame(train_average_pixel_width, columns=['average_pixel_width'])
incep_test_image_df = pd.DataFrame(test_average_pixel_width, columns=[f'average_pixel_width'])
incep_train_image_df['image'] = (train_ids)
incep_test_image_df['image'] = (test_ids)
training = training.join(incep_train_image_df.set_index('image'), on='image')
testing = testing.join(incep_test_image_df.set_index('image'), on='image')
print('adding average_reds ...')
with open('../input/train_image_features_1.p', 'rb') as f:
x = pickle.load(f)
train_average_reds = x['average_reds']
train_ids = x['ids']
with open('../input/test_image_features_1.p', 'rb') as f:
x = pickle.load(f)
test_average_reds = x['average_reds']
test_ids = x['ids']
del x;
gc.collect()
incep_train_image_df = pd.DataFrame(train_average_reds, columns=['average_reds'])
incep_test_image_df = pd.DataFrame(test_average_reds, columns=[f'average_reds'])
incep_train_image_df['image'] = (train_ids)
incep_test_image_df['image'] = (test_ids)
training = training.join(incep_train_image_df.set_index('image'), on='image')
testing = testing.join(incep_test_image_df.set_index('image'), on='image')
print('adding average_blues ...')
with open('../input/train_image_features_1.p', 'rb') as f:
x = pickle.load(f)
train_average_blues = x['average_blues']
train_ids = x['ids']
with open('../input/test_image_features_1.p', 'rb') as f:
x = pickle.load(f)
test_average_blues = x['average_blues']
test_ids = x['ids']
del x;
gc.collect()
incep_train_image_df = pd.DataFrame(train_average_blues, columns=['average_blues'])
incep_test_image_df = pd.DataFrame(test_average_blues, columns=[f'average_blues'])
incep_train_image_df['image'] = (train_ids)
incep_test_image_df['image'] = (test_ids)
training = training.join(incep_train_image_df.set_index('image'), on='image')
testing = testing.join(incep_test_image_df.set_index('image'), on='image')
print('adding average_greens ...')
with open('../input/train_image_features_1.p', 'rb') as f:
x = pickle.load(f)
train_average_greens = x['average_greens']
train_ids = x['ids']
with open('../input/test_image_features_1.p', 'rb') as f:
x = pickle.load(f)
test_average_greens = x['average_greens']
test_ids = x['ids']
del x;
gc.collect()
incep_train_image_df = pd.DataFrame(train_average_greens, columns=['average_greens'])
incep_test_image_df = pd.DataFrame(test_average_greens, columns=[f'average_greens'])
incep_train_image_df['image'] = (train_ids)
incep_test_image_df['image'] = (test_ids)
training = training.join(incep_train_image_df.set_index('image'), on='image')
testing = testing.join(incep_test_image_df.set_index('image'), on='image')
print('adding widths ...')
with open('../input/train_image_features_1.p', 'rb') as f:
x = pickle.load(f)
train_widths = x['widths']
train_ids = x['ids']
with open('../input/test_image_features_1.p', 'rb') as f:
x = pickle.load(f)
test_widths = x['widths']
test_ids = x['ids']
del x;
gc.collect()
incep_train_image_df = pd.DataFrame(train_widths, columns=['widths'])
incep_test_image_df = pd.DataFrame(test_widths, columns=[f'widths'])
incep_train_image_df['image'] = (train_ids)
incep_test_image_df['image'] = (test_ids)
training = training.join(incep_train_image_df.set_index('image'), on='image')
testing = testing.join(incep_test_image_df.set_index('image'), on='image')
print('adding heights ...')
with open('../input/train_image_features_1.p', 'rb') as f:
x = pickle.load(f)
train_heights = x['heights']
train_ids = x['ids']
with open('../input/test_image_features_1.p', 'rb') as f:
x = pickle.load(f)
test_heights = x['heights']
test_ids = x['ids']
del x;
gc.collect()
incep_train_image_df = pd.DataFrame(train_heights, columns=['heights'])
incep_test_image_df = pd.DataFrame(test_heights, columns=[f'heights'])
incep_train_image_df['image'] = (train_ids)
incep_test_image_df['image'] = (test_ids)
training = training.join(incep_train_image_df.set_index('image'), on='image')
testing = testing.join(incep_test_image_df.set_index('image'), on='image')
# ==============================================================================
# image features by Qifeng
# ==============================================================================
print('adding image features ...')
with open('../input/train_image_features_cspace.p', 'rb') as f:
x = pickle.load(f)
x_train = pd.DataFrame(x, columns=['average_HSV_Ss', \
'average_HSV_Vs', \
'average_LUV_Ls', \
'average_LUV_Us', \
'average_LUV_Vs', \
'average_HLS_Hs', \
'average_HLS_Ls', \
'average_HLS_Ss', \
'average_YUV_Ys', \
'average_YUV_Us', \
'average_YUV_Vs', \
'ids'
])
# x_train.rename(columns = {'$ids':'image'}, inplace = True)
with open('../input/test_image_features_cspace.p', 'rb') as f:
x = pickle.load(f)
x_test = pd.DataFrame(x, columns=['average_HSV_Ss', \
'average_HSV_Vs', \
'average_LUV_Ls', \
'average_LUV_Us', \
'average_LUV_Vs', \
'average_HLS_Hs', \
'average_HLS_Ls', \
'average_HLS_Ss', \
'average_YUV_Ys', \
'average_YUV_Us', \
'average_YUV_Vs', \
'ids'
])
# x_test.rename(columns = {'$ids':'image'}, inplace = True)
training = training.join(x_train.set_index('ids'), on='image')
testing = testing.join(x_test.set_index('ids'), on='image')
del x, x_train, x_test;
gc.collect()
print('Train shape: {} Rows, {} Columns'.format(*training.shape))
print('Test shape: {} Rows, {} Columns'.format(*testing.shape))
# Combine Train and Test
merge = pd.concat([training, testing], axis=0)
trnshape = training.shape[0]
gc.collect()
# handle_missing_inplace(test)
handle_missing_inplace(merge)
print('[{}] Handle missing completed.'.format(time.time() - start_time))
# some count
count = lambda l1, l2: sum([1 for x in l1 if x in l2])
merge["text_feature"] = merge.apply(lambda row: " ".join([str(row["param_1"]),
str(row["param_2"]), str(row["param_3"])]), axis=1)
merge["num_desc_punct"] = merge["description"].apply(lambda x: count(x, set(string.punctuation))).astype(np.int16)
merge["num_desc_capE"] = merge["description"].apply(lambda x: count(x, "[A-Z]")).astype(np.int16)
merge["num_desc_capP"] = merge["description"].apply(lambda x: count(x, "[А-Я]")).astype(np.int16)
merge["num_title_punct"] = merge["title"].apply(lambda x: count(x, set(string.punctuation))).astype(np.int16)
merge["num_title_capE"] = merge["title"].apply(lambda x: count(x, "[A-Z]")).astype(np.int16)
merge["num_title_capP"] = merge["title"].apply(lambda x: count(x, "[А-Я]")).astype(np.int16)
# good, used, bad ... count
merge["is_in_desc_хорошо"] = merge["description"].str.contains("хорошо").map({True: 1, False: 0}).astype(np.uint8)
merge["is_in_desc_Плохо"] = merge["description"].str.contains("Плохо").map({True: 1, False: 0}).astype(np.uint8)
merge["is_in_desc_новый"] = merge["description"].str.contains("новый").map({True: 1, False: 0}).astype(np.uint8)
merge["is_in_desc_старый"] = merge["description"].str.contains("старый").map({True: 1, False: 0}).astype(np.uint8)
merge["is_in_desc_используемый"] = merge["description"].str.contains("используемый").map(
{True: 1, False: 0}).astype(
np.uint8)
merge["is_in_desc_есплатная_доставка"] = merge["description"].str.contains("есплатная доставка").map(
{True: 1, False: 0}).astype(np.uint8)
merge["is_in_desc_есплатный_возврат"] = merge["description"].str.contains("есплатный возврат").map(
{True: 1, False: 0}).astype(np.uint8)
merge["is_in_desc_идеально"] = merge["description"].str.contains("идеально").map({True: 1, False: 0}).astype(
np.uint8)
merge["is_in_desc_подержанный"] = merge["description"].str.contains("подержанный").map({True: 1, False: 0}).astype(
np.uint8)
merge["is_in_desc_пСниженные_цены"] = merge["description"].str.contains("Сниженные цены").map(
{True: 1, False: 0}).astype(np.uint8)
#new features
# merge['desc_len'] = np.log1p(merge['description'].apply(lambda x: len(x)))
# merge['title_len'] = np.log1p(merge['title'].apply(lambda x: len(x)))
# merge['title_desc_len_ratio'] = np.log1p(merge['title_len'] / merge['desc_len'])
# #
# merge['desc_word_count'] = merge['description'].apply(lambda x: len(x.split()))
# merge['mean_des'] = merge['description'].apply(
# lambda x: 0 if len(x) == 0 else float(len(x.split())) / len(x)) * 10
# merge['title_word_count'] = merge['title'].apply(lambda x: len(x.split()))
# merge['mean_title'] = merge['title'].apply(lambda x: 0 if len(x) == 0 else float(len(x.split())) / len(x)) * 10
# merge.drop('category_name', axis=1, inplace=True)
# merge["price+"] = np.round(merge["price"] * 2.8).astype(np.int16) # 4.8
# merge["item_seq_number+"] = np.round(merge["item_seq_number"] / 100).astype(np.int16)
merge["item_seq_number"]=np.log1p(merge["item_seq_number"]).astype(np.float32)
merge["price"].fillna(-1, inplace=True)
# merge["wday"] = merge["activation_date"].dt.weekday
# merge["wday"] = merge["wday"].astype('category')
# merge["is_in_title_iphone"] = merge["title"].str.contains("iphone").map({True: 1, False: 0}).astype('category')
# merge["is_in_desc_ipod"] = merge["title"].str.contains("ipod").map({True: 1, False: 0}).astype('category')
#
# merge["is_in_desc_samsung"] = merge["title"].str.contains("samsung").map({True: 1, False: 0}).astype('category')
merge['blurinesses']=merge['blurinesses'].astype('category')
merge['whitenesses']=merge['whitenesses'].astype('category')
merge['dullnesses']=merge['dullnesses'].astype('category')
merge['average_pixel_width']=merge['average_pixel_width'].astype('category')
merge['average_reds'] = merge['average_reds'].astype('category')
merge['average_blues'] = merge['average_blues'].astype('category')
merge['average_greens'] = merge['average_greens'].astype('category')
merge['widths'] = merge['widths'].astype('category')
merge['heights'] = merge['heights'].astype('category')
merge['average_HSV_Ss'] = merge['average_HSV_Ss'].astype('category')
merge['average_HSV_Vs'] = merge['average_HSV_Vs'].astype('category')
merge['average_LUV_Ls'] = merge['average_LUV_Ls'].astype('category')
merge['average_LUV_Us'] = merge['average_LUV_Us'].astype('category')
merge['average_LUV_Vs'] = merge['average_LUV_Vs'].astype('category')
merge['average_HLS_Hs'] = merge['average_HLS_Hs'].astype('category')
merge['average_HLS_Ls'] = merge['average_HLS_Ls'].astype('category')
merge['average_HLS_Ss'] = merge['average_HLS_Ss'].astype('category')
merge['average_YUV_Ys'] = merge['average_YUV_Ys'].astype('category')
merge['average_YUV_Us'] = merge['average_YUV_Us'].astype('category')
merge['average_YUV_Vs'] = merge['average_YUV_Vs'].astype('category')
# merge["price+"] = np.round(merge["price"] * 2.8).astype(np.int16) # 4.8
print('[{}] Do some counting completed.'.format(time.time() - start_time))
with timer("Log features"):
for fea in ['price','image_top_1']:
merge[fea]= np.log2(1 + merge[fea].values).astype(int)
to_categorical(merge)
print('[{}] Convert categorical completed'.format(time.time() - start_time))
def text_preprocessing(text):
# text = str(text)
# text = text.lower()
# text = re.sub(r"(\\u[0-9A-Fa-f]+)", r"", text)
# text = re.sub(r"===", r" ", text)
# # https://www.kaggle.com/demery/lightgbm-with-ridge-feature/code
# text = " ".join(map(str.strip, re.split('(\d+)', text)))
# regex = re.compile(u'[^[:alpha:]]')
# text = regex.sub(" ", text)
# text = " ".join(text.split())
return text
merge['description']=merge['description'].apply(text_preprocessing)
merge['title'] = merge['title'].apply(text_preprocessing)
wb = wordbatch.WordBatch( extractor=(WordBag, {"hash_ngrams": 1, "hash_ngrams_weights": [1.5, 1.0],
"hash_size": 2 ** 29, "norm": None, "tf": 'binary',
"idf": None,
}), procs=16)
wb.dictionary_freeze = True
# wb.fit(train['name'])
min_df_name = 5#5,3
X_desc_merge = wb.fit_transform(merge['description'])
X_title_merge = wb.transform(merge['title'])
del (wb)
mask_name = np.where(X_desc_merge.getnnz(axis=0) > min_df_name)[0]
X_desc_merge = X_desc_merge[:, mask_name]
mask_name = np.where(X_title_merge.getnnz(axis=0) > min_df_name)[0]
X_title_merge = X_title_merge[:, mask_name]
print('[{}] Vectorize `desc,title` completed.'.format(time.time() - start_time))
wb = CountVectorizer()
X_param_1 = wb.fit_transform(merge['param_1'])
X_param_2 = wb.fit_transform(merge['param_2'])
X_param_3 = wb.fit_transform(merge['param_3'])
print('[{}] Count vectorize `categories` completed.'.format(time.time() - start_time))
# lb = LabelBinarizer(sparse_output=True)
# X_brand = lb.fit_transform(merge['brand_name'])
# X_brand_train = X_brand[:nrow_train]
# X_brand_test = X_brand[nrow_test:]
# del X_brand
# print('[{}] Label binarize `brand_name` completed.'.format(time.time() - start_time))
X_dummies = csr_matrix(pd.get_dummies(merge[['param_1', 'param_2', 'param_3',
'image_top_1',
# 'region'
'is_in_desc_хорошо', 'is_in_desc_Плохо',
'is_in_desc_новый', 'is_in_desc_старый', 'is_in_desc_используемый',
'is_in_desc_есплатная_доставка',
'is_in_desc_есплатный_возврат', 'is_in_desc_идеально',
'is_in_desc_подержанный', 'is_in_desc_пСниженные_цены',
# 'price+',
# 'city',
'user_type',
'category_name',
"parent_category_name",
# "wday"
# "is_in_title_iphone","is_in_desc_ipod","is_in_desc_samsung",
]],
sparse=True).values)
# X_dummies_test = X_dummies[nrow_test:]
# del X_dummies
print('[{}] Get dummies on `param_1` and `param_2,param_3` completed.'.format(time.time() - start_time))
#
X_counting = csr_matrix(pd.get_dummies(merge[
['num_desc_punct', 'num_desc_capE', 'num_desc_capP', 'num_title_punct',
'num_title_capP', 'num_title_capE',
# 'is_in_desc_хорошо', 'is_in_desc_Плохо',
# 'is_in_desc_новый', 'is_in_desc_старый', 'is_in_desc_используемый',
# 'is_in_desc_есплатная_доставка',
# 'is_in_desc_есплатный_возврат', 'is_in_desc_идеально',
# 'is_in_desc_подержанный', 'is_in_desc_пСниженные_цены',
'price',
# 'desc_len','title_len',
# 'title_desc_len_ratio',
# 'desc_word_count',
# 'mean_des',
# 'title_word_count',
# 'mean_title'
# 'price+',
"item_seq_number",
'blurinesses','whitenesses','dullnesses',
'average_pixel_width','average_reds',
'average_blues', 'average_greens', 'widths', 'heights',
'average_HSV_Ss', \
'average_HSV_Vs', \
'average_LUV_Ls', \
'average_LUV_Us', \
'average_LUV_Vs', \
'average_HLS_Hs', \
'average_HLS_Ls', \
'average_HLS_Ss', \
'average_YUV_Ys', \
'average_YUV_Us', \
'average_YUV_Vs', \
\
]
],
sparse=True).values)
# X_counting_train=X_counting[:nrow_train]
# X_counting_test = X_counting[nrow_test:]
# del X_counting
# if develop:
# print(u'memory:{}gb'.format(psutil.Process(os.getpid()).memory_info().rss / 1024 / 1024 / 1024))
#
# wb = CountVectorizer()
# merge['catship'] = merge['category_name'].astype(str) + merge['shipping'].astype(str)
# X_catship = wb.fit_transform(merge['catship'])
# X_catship_train = X_catship[:nrow_train]
# X_catship_test = X_catship[nrow_test:]
# del merge
# print('[{}] Count vectorize `catship` completed.'.format(time.time() - start_time))
# if develop:
# print(u'memory:{}gb'.format(psutil.Process(os.getpid()).memory_info().rss / 1024 / 1024 / 1024))
#
# print(X_dummies_train.shape, X_description_train.shape, X_brand_train.shape,
# X_category1_train.shape, X_category2_train.shape, X_category3_train.shape,
# X_name_train.shape, X_category_train.shape, X_catship_train.shape)
#
from nltk.corpus import stopwords
def char_analyzer(text):
"""
This is used to split strings in small lots
anttip saw this in an article
so <talk> and <talking> would have <Tal> <alk> in common
should be similar to russian I guess
"""
tokens = text.split()
return [token[i: i + 3] for token in tokens for i in range(len(token) - 2)]
stopWords = stopwords.words('russian')
with timer("Tfidf on description word"):
word_vectorizer = TfidfVectorizer(
sublinear_tf=True,
strip_accents='unicode',
tokenizer=lambda x: re.findall(r'[^{P}\W]+', x),
analyzer='word',
token_pattern=None,
stop_words=stopWords,
ngram_range=(1, 4),#1,2
max_features=200000)
X = word_vectorizer.fit_transform(merge['description'])
train_word_features = X[:len_train]
test_word_features = X[len_train:]
del (X)
with timer("Tfidf on title word"):
word_vectorizer = TfidfVectorizer(
sublinear_tf=True,
strip_accents='unicode',
tokenizer=lambda x: re.findall(r'[^{P}\W]+', x),
analyzer='word',
token_pattern=None,
stop_words=stopWords,
ngram_range=(3, 6),#1,2
max_features=50000)
X = word_vectorizer.fit_transform(merge['title'])
train_title_word_features = X[:trnshape]
test_title_word_features = X[trnshape:]
del (X)
with timer("Tfidf on char n_gram"):
char_vectorizer = TfidfVectorizer(
sublinear_tf=True,
strip_accents='unicode',
tokenizer=char_analyzer,
analyzer='word',
ngram_range=(1, 4),#
max_features=50000)
X = char_vectorizer.fit_transform(merge['title'])
train_char_features = X[:trnshape]
test_char_features = X[trnshape:]
del (X)
with timer("Tfidf on description word"):
word_vectorizer = TfidfVectorizer(
sublinear_tf=True,
strip_accents='unicode',
tokenizer=lambda x: re.findall(r'[^{P}\W]+', x),
analyzer='word',
token_pattern=None,
stop_words=stopWords,
ngram_range=(3, 6),#1,2
max_features=200000)#200000
X = word_vectorizer.fit_transform(merge['description'])
train_desc_word_features = X[:trnshape]
test_desc_word_features = X[trnshape:]
del (X)
# with timer("CountVectorizer on word"):
# word_vectorizer = CountVectorizer(
# ngram_range=(3, 5),)
# X = word_vectorizer.fit_transform(merge['text_feature'])
# train_text_feature_word_features = X[:trnshape]
# test_text_feature_word_features = X[trnshape:]
# del (X)
X = hstack((X_dummies[:len_train],X_counting[:len_train], X_param_1[:len_train],
X_param_2[: len_train],X_param_3[:len_train],X_desc_merge[:len_train],
X_title_merge[: len_train],
train_word_features,
# train_text_feature_word_features,
train_char_features,train_title_word_features,
train_desc_word_features
)).tocsr()
X_test = hstack((X_dummies[len_train:], X_counting[len_train:], X_param_1[len_train:],
X_param_2[len_train:], X_param_3[len_train:], X_desc_merge[len_train:],
X_title_merge[len_train:],
test_word_features,
# test_text_feature_word_features,
test_char_features,test_title_word_features,
test_desc_word_features
)).tocsr()
del X_title_merge,X_counting,X_desc_merge,X_dummies,X_param_1,X_param_2,X_param_3,merge, \
train_word_features,test_word_features,\
train_char_features, train_title_word_features,\
test_char_features, test_title_word_features,
train_desc_word_features,test_desc_word_features,
merge
gc.collect()
print('[{}] Create sparse merge completed'.format(time.time() - start_time))
from sklearn.model_selection import KFold
nfold = 5
kf = KFold(n_splits=nfold, random_state=42, shuffle=True)
fold_id = -1
val_predict = np.zeros(y.shape)
aver_rmse = 0.0
for train_index, val_index in kf.split(y):
fold_id += 1
print("Fold {} start...".format(fold_id))
train_X, valid_X = X[train_index], X[val_index]
train_y, valid_y = y[train_index], y[val_index]
# train_X, valid_X, train_y, valid_y = train_test_split(X_train, y, test_size=0.2, random_state=42)
# del X_train, y
d_shape = train_X.shape[1]
print('d_shape', d_shape)
model = FTRL(alpha=0.01, beta=0.1, L1=0.1, L2=10, D=d_shape, iters=5, inv_link="identity", threads=8)
model.fit(train_X, train_y)
def rmse(predictions, targets):
print("calculating RMSE ...")
return np.sqrt(((predictions - targets) ** 2).mean())
preds_valid_ftrl = model.predict(X=valid_X)
# print(" FTRL dev RMSLE:", rmsle(np.expm1(valid_y), np.expm1(preds_valid_ftrl)))
print(" FTRL dev RMSLE:", rmse(valid_y, preds_valid_ftrl))
# # model = FM_FTRL(alpha=0.01, beta=0.01, L1=0.00001, L2=0.1, D=X_train.shape[1], alpha_fm=0.01, L2_fm=0.0,
# # init_fm=0.01,
# # D_fm=200, e_noise=0.0001, iters=15, inv_link="identity", threads=4)
model = FM_FTRL(alpha=0.01, beta=0.01, L1=1, L2=8, D=d_shape, alpha_fm=0.01, L2_fm=0.0,
init_fm=0.01,
D_fm=200, iters=6, inv_link="identity", threads=8)
model.fit(train_X, train_y)
preds_valid_fm = model.predict(X=valid_X)
del valid_X,train_X, train_y
# print("FM dev RMSLE:", rmsle(np.expm1(valid_y), np.expm1(preds_valid_fm)))
print("FM dev RMSLE:", rmse(valid_y, preds_valid_fm))
def aggregate_predicts3(Y1, Y2, ratio1):
assert Y1.shape == Y2.shape
return Y1 * ratio1 + Y2 * (1-ratio1)
weight = 0.5#0.5
preds = weight * preds_valid_fm + (1 - weight) * preds_valid_ftrl
val_predict[val_index] = preds
# print("FM_FTRL dev RMSLE:", rmsle(np.expm1(valid_y), np.expm1(preds)))
print("FM_FTRL dev RMSLE:", rmse(valid_y, preds))
aver_rmse += rmse(valid_y, preds)
sub = pd.read_csv('../input/sample_submission.csv', ) # , nrows=10000*5
pred = model.predict(X_test)
sub['deal_probability'] = pred
sub['deal_probability'].clip(0.0, 1.0, inplace=True)
print("Output Prediction CSV")
sub.to_csv('subm/ftrl_fm_submissionV3_{}.csv'.format(fold_id), index=False)
print("average rmse:{}".format(aver_rmse / nfold))
train_data = pd.read_csv('../input/train.csv', )
label = ['deal_probability']
# train_user_ids = train_data.user_id.values
train_item_ids = train_data.item_id.values
train_item_ids = train_item_ids.reshape(len(train_item_ids), 1)
# train_user_ids = train_item_ids.reshape(len(train_user_ids), 1)
val_predicts = pd.DataFrame(data=val_predict, columns=label)
# val_predicts['user_id'] = train_user_ids
val_predicts['item_id'] = train_item_ids
val_predicts.to_csv('subm/ftrl_fmV3_train.csv', index=False)
# # ratio optimum finder for 3 models
# best1 = 0
# lowest = 0.99
# for i in range(100):
# r = i * 0.01
# if r < 1.0:
# Y_dev_preds = aggregate_predicts3(preds_valid_fm, preds_valid_ftrl, r)
# fpred = rmsle(np.expm1(valid_y), np.expm1(Y_dev_preds))
# if fpred < lowest:
# best1 = r
# lowest = fpred
# # print(str(r)+"-RMSL error for RNN + Ridge + RidgeCV on dev set:", fpred)
# Y_dev_preds = Y_dev_preds = aggregate_predicts3(preds_valid_fm, preds_valid_ftrl, best1)
# print(best1)
#
# print("(Best) RMSL error for RNN attention + FM + fasttext on dev set:", rmsle(np.expm1(valid_y), np.expm1(Y_dev_preds)))
#
# del train_X,train_y
# print('[{}] Train ridge v2 completed'.format(time.time() - start_time))
# if develop:
# print(u'memory:{}gb'.format(psutil.Process(os.getpid()).memory_info().rss / 1024 / 1024 / 1024))
#
# if develop:
# preds = model.predict(X=valid_X)
# print("FM_FTRL dev RMSLE:", rmsle(np.expm1(valid_y), np.expm1(preds)))
#
# predsFM = model.predict(X_test)
# print('[{}] Predict FM_FTRL completed'.format(time.time() - start_time))
# del X_test
# gc.collect()
# preds = predsFM
#
# submission['price'] = np.expm1(preds)
# submission.to_csv("submission_wordbatch_ftrl_fm.csv", index=False)
print(strftime("%Y-%m-%d %H:%M:%S", gmtime()))
print("Total time costs:{}".format(time.time()-start_time))
'''
1w oof
Output Prediction CSV
average rmse:0.244059242699125
average rmse:0.2436276297688677
average rmse:0.24356555599510213
average rmse:0.2435573104461158
average rmse:0.2433847234729977
average rmse:0.2430078486780956
average rmse:0.24299577528880514
average rmse:0.24297421901652375
average rmse:0.2429121752449718
average rmse:0.24265357451463557
average rmse:0.24252233100353485
average rmse:0.24247167824739174
average rmse:0.24219114762025212
average rmse:0.24154770841924011
2018-06-24 08:22:34
Total time costs:632.5025238990784
2018-06-24 04:37:31
5w oof
average rmse:0.23784727588111987
average rmse:0.2374566037691721
全数据oof
average rmse:0.22752099248003815
2018-06-24 01:34:11
1w
FTRL dev RMSLE: 0.236763228999
FM dev RMSLE: 0.236599859025
FTRL dev RMSLE: 0.236763228999
FM dev RMSLE: 0.236259762027
FM_FTRL dev RMSLE: 0.236307818481
加image_top_1
FTRL dev RMSLE: 0.2365524478
FM dev RMSLE: 0.236126474398
FM_FTRL dev RMSLE: 0.236139755285
加desc tfidf vec
d_shape 45372
FTRL dev RMSLE: 0.235671709213
FM dev RMSLE: 0.236226484101
FM_FTRL dev RMSLE: 0.236117518185
d_shape 45372
FTRL dev RMSLE: 0.235671709213
FM dev RMSLE: 0.236159988691
FM_FTRL dev RMSLE: 0.235875096042
2018-06-23 10:32:17
d_shape 221372
FTRL dev RMSLE: 0.235755131719
FM dev RMSLE: 0.236065858162
FM_FTRL dev RMSLE: 0.235762389065
2018-06-23 10:40:53
d_shape 264733
calculating RMSE ...
FTRL dev RMSLE: 0.236015070756
calculating RMSE ...
FM dev RMSLE: 0.235691015213
calculating RMSE ...
FM_FTRL dev RMSLE: 0.235624786658
2018-06-23 10:53:34
d_shape 264733
calculating RMSE ...
FTRL dev RMSLE: 0.243936175374
calculating RMSE ...
FM dev RMSLE: 0.242935442428
calculating RMSE ...
FM_FTRL dev RMSLE: 0.243110294203
2018-06-23 11:00:10
ftrl 选择0.01学习率,fm选择0.012学习率,终于两个结合在一起出现了提升的情况
d_shape 264733
calculating RMSE ...
FTRL dev RMSLE: 0.242810536001
calculating RMSE ...
FM dev RMSLE: 0.242935442428
calculating RMSE ...
FM_FTRL dev RMSLE: 0.242692624406
2018-06-23 11:03:27
5w
[55.92116975784302] Create sparse merge completed
d_shape 283708
calculating RMSE ...
FTRL dev RMSLE: 0.241283110197
calculating RMSE ...
FM dev RMSLE: 0.241620178685
calculating RMSE ...
FM_FTRL dev RMSLE: 0.241369959742
2018-06-23 11:09:12
去掉文本预处理
d_shape 283276
calculating RMSE ...
FTRL dev RMSLE: 0.240947392605
calculating RMSE ...
FM dev RMSLE: 0.24137407715
calculating RMSE ...
FM_FTRL dev RMSLE: 0.241087603203
2018-06-23 11:53:57
FTRL dev RMSLE: 0.24038598037733158
Total e: 6691.091679637143
Total e: 6197.443774721293
Total e: 5910.549085966008
Total e: 5678.391317973746
Total e: 5478.447318454014
Total e: 5299.388231258417
calculating RMSE ...
FM dev RMSLE: 0.24197215576549963
calculating RMSE ...
FM_FTRL dev RMSLE: 0.2408992078078851
calculating RMSE ...
FTRL dev RMSLE: 0.24041738076612498
Total e: 6694.977462749721
Total e: 6201.135074918874
Total e: 5913.840993519399
Total e: 5675.960904656893
Total e: 5468.428715351852
Total e: 5279.872363537804
calculating RMSE ...
FM dev RMSLE: 0.24162872695531198
calculating RMSE ...
FM_FTRL dev RMSLE: 0.2406825046482856
2018-06-23 13:44:26
全数据
calculating RMSE ...
FM dev RMSLE: 0.23003102622238622
calculating RMSE ...
FM_FTRL dev RMSLE: 0.22870936935371064
2018-06-23 13:11:24
'''
|
[
"sklearn.feature_extraction.text.CountVectorizer",
"wordbatch.WordBatch",
"pandas.read_csv",
"sklearn.feature_extraction.text.TfidfVectorizer",
"wordbatch.models.FM_FTRL",
"gc.collect",
"pickle.load",
"wordbatch.models.FTRL",
"pandas.DataFrame",
"re.findall",
"pandas.concat",
"numpy.log1p",
"pandas.get_dummies",
"numpy.log2",
"nltk.corpus.stopwords.words",
"re.compile",
"time.gmtime",
"numpy.zeros",
"sklearn.model_selection.KFold",
"time.time",
"scipy.sparse.hstack"
] |
[((3793, 3821), 're.compile', 're.compile', (['u"""[^A-Za-z0-9]+"""'], {}), "(u'[^A-Za-z0-9]+')\n", (3803, 3821), False, 'import re\n'), ((4125, 4136), 'time.time', 'time.time', ([], {}), '()\n', (4134, 4136), False, 'import time\n'), ((4695, 4787), 'pandas.read_csv', 'pd.read_csv', (['"""../input/train.csv"""'], {'index_col': '"""item_id"""', 'parse_dates': "['activation_date']"}), "('../input/train.csv', index_col='item_id', parse_dates=[\n 'activation_date'])\n", (4706, 4787), True, 'import pandas as pd\n'), ((4857, 4948), 'pandas.read_csv', 'pd.read_csv', (['"""../input/test.csv"""'], {'index_col': '"""item_id"""', 'parse_dates': "['activation_date']"}), "('../input/test.csv', index_col='item_id', parse_dates=[\n 'activation_date'])\n", (4868, 4948), True, 'import pandas as pd\n'), ((5743, 5821), 'pandas.read_csv', 'pd.read_csv', (['"""../input/region_income.csv"""'], {'sep': '""";"""', 'names': "['region', 'income']"}), "('../input/region_income.csv', sep=';', names=['region', 'income'])\n", (5754, 5821), True, 'import pandas as pd\n'), ((5958, 5970), 'gc.collect', 'gc.collect', ([], {}), '()\n', (5968, 5970), False, 'import gc\n'), ((6173, 6224), 'pandas.read_csv', 'pd.read_csv', (['"""../input/city_population_wiki_v3.csv"""'], {}), "('../input/city_population_wiki_v3.csv')\n", (6184, 6224), True, 'import pandas as pd\n'), ((6357, 6369), 'gc.collect', 'gc.collect', ([], {}), '()\n', (6367, 6369), False, 'import gc\n'), ((6711, 6723), 'gc.collect', 'gc.collect', ([], {}), '()\n', (6721, 6723), False, 'import gc\n'), ((6752, 6808), 'pandas.DataFrame', 'pd.DataFrame', (['train_blurinesses'], {'columns': "['blurinesses']"}), "(train_blurinesses, columns=['blurinesses'])\n", (6764, 6808), True, 'import pandas as pd\n'), ((6835, 6891), 'pandas.DataFrame', 'pd.DataFrame', (['test_blurinesses'], {'columns': "[f'blurinesses']"}), "(test_blurinesses, columns=[f'blurinesses'])\n", (6847, 6891), True, 'import pandas as pd\n'), ((7507, 7519), 'gc.collect', 'gc.collect', ([], {}), '()\n', (7517, 7519), False, 'import gc\n'), ((7548, 7604), 'pandas.DataFrame', 'pd.DataFrame', (['train_whitenesses'], {'columns': "['whitenesses']"}), "(train_whitenesses, columns=['whitenesses'])\n", (7560, 7604), True, 'import pandas as pd\n'), ((7631, 7687), 'pandas.DataFrame', 'pd.DataFrame', (['test_whitenesses'], {'columns': "[f'whitenesses']"}), "(test_whitenesses, columns=[f'whitenesses'])\n", (7643, 7687), True, 'import pandas as pd\n'), ((8298, 8310), 'gc.collect', 'gc.collect', ([], {}), '()\n', (8308, 8310), False, 'import gc\n'), ((8339, 8393), 'pandas.DataFrame', 'pd.DataFrame', (['train_dullnesses'], {'columns': "['dullnesses']"}), "(train_dullnesses, columns=['dullnesses'])\n", (8351, 8393), True, 'import pandas as pd\n'), ((8420, 8474), 'pandas.DataFrame', 'pd.DataFrame', (['test_dullnesses'], {'columns': "[f'dullnesses']"}), "(test_dullnesses, columns=[f'dullnesses'])\n", (8432, 8474), True, 'import pandas as pd\n'), ((9134, 9146), 'gc.collect', 'gc.collect', ([], {}), '()\n', (9144, 9146), False, 'import gc\n'), ((9175, 9247), 'pandas.DataFrame', 'pd.DataFrame', (['train_average_pixel_width'], {'columns': "['average_pixel_width']"}), "(train_average_pixel_width, columns=['average_pixel_width'])\n", (9187, 9247), True, 'import pandas as pd\n'), ((9274, 9346), 'pandas.DataFrame', 'pd.DataFrame', (['test_average_pixel_width'], {'columns': "[f'average_pixel_width']"}), "(test_average_pixel_width, columns=[f'average_pixel_width'])\n", (9286, 9346), True, 'import pandas as pd\n'), ((9971, 9983), 'gc.collect', 'gc.collect', ([], {}), '()\n', (9981, 9983), False, 'import gc\n'), ((10012, 10070), 'pandas.DataFrame', 'pd.DataFrame', (['train_average_reds'], {'columns': "['average_reds']"}), "(train_average_reds, columns=['average_reds'])\n", (10024, 10070), True, 'import pandas as pd\n'), ((10097, 10155), 'pandas.DataFrame', 'pd.DataFrame', (['test_average_reds'], {'columns': "[f'average_reds']"}), "(test_average_reds, columns=[f'average_reds'])\n", (10109, 10155), True, 'import pandas as pd\n'), ((10785, 10797), 'gc.collect', 'gc.collect', ([], {}), '()\n', (10795, 10797), False, 'import gc\n'), ((10826, 10886), 'pandas.DataFrame', 'pd.DataFrame', (['train_average_blues'], {'columns': "['average_blues']"}), "(train_average_blues, columns=['average_blues'])\n", (10838, 10886), True, 'import pandas as pd\n'), ((10913, 10973), 'pandas.DataFrame', 'pd.DataFrame', (['test_average_blues'], {'columns': "[f'average_blues']"}), "(test_average_blues, columns=[f'average_blues'])\n", (10925, 10973), True, 'import pandas as pd\n'), ((11608, 11620), 'gc.collect', 'gc.collect', ([], {}), '()\n', (11618, 11620), False, 'import gc\n'), ((11649, 11711), 'pandas.DataFrame', 'pd.DataFrame', (['train_average_greens'], {'columns': "['average_greens']"}), "(train_average_greens, columns=['average_greens'])\n", (11661, 11711), True, 'import pandas as pd\n'), ((11738, 11800), 'pandas.DataFrame', 'pd.DataFrame', (['test_average_greens'], {'columns': "[f'average_greens']"}), "(test_average_greens, columns=[f'average_greens'])\n", (11750, 11800), True, 'import pandas as pd\n'), ((12395, 12407), 'gc.collect', 'gc.collect', ([], {}), '()\n', (12405, 12407), False, 'import gc\n'), ((12436, 12482), 'pandas.DataFrame', 'pd.DataFrame', (['train_widths'], {'columns': "['widths']"}), "(train_widths, columns=['widths'])\n", (12448, 12482), True, 'import pandas as pd\n'), ((12509, 12555), 'pandas.DataFrame', 'pd.DataFrame', (['test_widths'], {'columns': "[f'widths']"}), "(test_widths, columns=[f'widths'])\n", (12521, 12555), True, 'import pandas as pd\n'), ((13155, 13167), 'gc.collect', 'gc.collect', ([], {}), '()\n', (13165, 13167), False, 'import gc\n'), ((13196, 13244), 'pandas.DataFrame', 'pd.DataFrame', (['train_heights'], {'columns': "['heights']"}), "(train_heights, columns=['heights'])\n", (13208, 13244), True, 'import pandas as pd\n'), ((13271, 13319), 'pandas.DataFrame', 'pd.DataFrame', (['test_heights'], {'columns': "[f'heights']"}), "(test_heights, columns=[f'heights'])\n", (13283, 13319), True, 'import pandas as pd\n'), ((13926, 14168), 'pandas.DataFrame', 'pd.DataFrame', (['x'], {'columns': "['average_HSV_Ss', 'average_HSV_Vs', 'average_LUV_Ls', 'average_LUV_Us',\n 'average_LUV_Vs', 'average_HLS_Hs', 'average_HLS_Ls', 'average_HLS_Ss',\n 'average_YUV_Ys', 'average_YUV_Us', 'average_YUV_Vs', 'ids']"}), "(x, columns=['average_HSV_Ss', 'average_HSV_Vs',\n 'average_LUV_Ls', 'average_LUV_Us', 'average_LUV_Vs', 'average_HLS_Hs',\n 'average_HLS_Ls', 'average_HLS_Ss', 'average_YUV_Ys', 'average_YUV_Us',\n 'average_YUV_Vs', 'ids'])\n", (13938, 14168), True, 'import pandas as pd\n'), ((14822, 15064), 'pandas.DataFrame', 'pd.DataFrame', (['x'], {'columns': "['average_HSV_Ss', 'average_HSV_Vs', 'average_LUV_Ls', 'average_LUV_Us',\n 'average_LUV_Vs', 'average_HLS_Hs', 'average_HLS_Ls', 'average_HLS_Ss',\n 'average_YUV_Ys', 'average_YUV_Us', 'average_YUV_Vs', 'ids']"}), "(x, columns=['average_HSV_Ss', 'average_HSV_Vs',\n 'average_LUV_Ls', 'average_LUV_Us', 'average_LUV_Vs', 'average_HLS_Hs',\n 'average_HLS_Ls', 'average_HLS_Ss', 'average_YUV_Ys', 'average_YUV_Us',\n 'average_YUV_Vs', 'ids'])\n", (14834, 15064), True, 'import pandas as pd\n'), ((15760, 15772), 'gc.collect', 'gc.collect', ([], {}), '()\n', (15770, 15772), False, 'import gc\n'), ((15953, 15991), 'pandas.concat', 'pd.concat', (['[training, testing]'], {'axis': '(0)'}), '([training, testing], axis=0)\n', (15962, 15991), True, 'import pandas as pd\n'), ((16030, 16042), 'gc.collect', 'gc.collect', ([], {}), '()\n', (16040, 16042), False, 'import gc\n'), ((22422, 22600), 'wordbatch.WordBatch', 'wordbatch.WordBatch', ([], {'extractor': "(WordBag, {'hash_ngrams': 1, 'hash_ngrams_weights': [1.5, 1.0], 'hash_size':\n 2 ** 29, 'norm': None, 'tf': 'binary', 'idf': None})", 'procs': '(16)'}), "(extractor=(WordBag, {'hash_ngrams': 1,\n 'hash_ngrams_weights': [1.5, 1.0], 'hash_size': 2 ** 29, 'norm': None,\n 'tf': 'binary', 'idf': None}), procs=16)\n", (22441, 22600), False, 'import wordbatch\n'), ((23334, 23351), 'sklearn.feature_extraction.text.CountVectorizer', 'CountVectorizer', ([], {}), '()\n', (23349, 23351), False, 'from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer\n'), ((29359, 29385), 'nltk.corpus.stopwords.words', 'stopwords.words', (['"""russian"""'], {}), "('russian')\n", (29374, 29385), False, 'from nltk.corpus import stopwords\n'), ((33079, 33091), 'gc.collect', 'gc.collect', ([], {}), '()\n', (33089, 33091), False, 'import gc\n'), ((33244, 33296), 'sklearn.model_selection.KFold', 'KFold', ([], {'n_splits': 'nfold', 'random_state': '(42)', 'shuffle': '(True)'}), '(n_splits=nfold, random_state=42, shuffle=True)\n', (33249, 33296), False, 'from sklearn.model_selection import KFold\n'), ((33335, 33352), 'numpy.zeros', 'np.zeros', (['y.shape'], {}), '(y.shape)\n', (33343, 33352), True, 'import numpy as np\n'), ((35915, 35948), 'pandas.read_csv', 'pd.read_csv', (['"""../input/train.csv"""'], {}), "('../input/train.csv')\n", (35926, 35948), True, 'import pandas as pd\n'), ((36238, 36283), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'val_predict', 'columns': 'label'}), '(data=val_predict, columns=label)\n', (36250, 36283), True, 'import pandas as pd\n'), ((3749, 3775), 'nltk.corpus.stopwords.words', 'stopwords.words', (['"""russian"""'], {}), "('russian')\n", (3764, 3775), False, 'from nltk.corpus import stopwords\n'), ((4441, 4452), 'time.time', 'time.time', ([], {}), '()\n', (4450, 4452), False, 'import time\n'), ((6461, 6475), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (6472, 6475), False, 'import pickle\n'), ((6616, 6630), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (6627, 6630), False, 'import pickle\n'), ((7257, 7271), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (7268, 7271), False, 'import pickle\n'), ((7412, 7426), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (7423, 7426), False, 'import pickle\n'), ((8052, 8066), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (8063, 8066), False, 'import pickle\n'), ((8205, 8219), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (8216, 8219), False, 'import pickle\n'), ((8850, 8864), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (8861, 8864), False, 'import pickle\n'), ((9023, 9037), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (9034, 9037), False, 'import pickle\n'), ((9715, 9729), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (9726, 9729), False, 'import pickle\n'), ((9874, 9888), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (9885, 9888), False, 'import pickle\n'), ((10525, 10539), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (10536, 10539), False, 'import pickle\n'), ((10686, 10700), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (10697, 10700), False, 'import pickle\n'), ((11344, 11358), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (11355, 11358), False, 'import pickle\n'), ((11507, 11521), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (11518, 11521), False, 'import pickle\n'), ((12163, 12177), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (12174, 12177), False, 'import pickle\n'), ((12310, 12324), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (12321, 12324), False, 'import pickle\n'), ((12919, 12933), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (12930, 12933), False, 'import pickle\n'), ((13068, 13082), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (13079, 13082), False, 'import pickle\n'), ((13896, 13910), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (13907, 13910), False, 'import pickle\n'), ((14793, 14807), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (14804, 14807), False, 'import pickle\n'), ((30545, 30691), 'sklearn.feature_extraction.text.TfidfVectorizer', 'TfidfVectorizer', ([], {'sublinear_tf': '(True)', 'strip_accents': '"""unicode"""', 'tokenizer': 'char_analyzer', 'analyzer': '"""word"""', 'ngram_range': '(1, 4)', 'max_features': '(50000)'}), "(sublinear_tf=True, strip_accents='unicode', tokenizer=\n char_analyzer, analyzer='word', ngram_range=(1, 4), max_features=50000)\n", (30560, 30691), False, 'from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer\n'), ((33815, 33913), 'wordbatch.models.FTRL', 'FTRL', ([], {'alpha': '(0.01)', 'beta': '(0.1)', 'L1': '(0.1)', 'L2': '(10)', 'D': 'd_shape', 'iters': '(5)', 'inv_link': '"""identity"""', 'threads': '(8)'}), "(alpha=0.01, beta=0.1, L1=0.1, L2=10, D=d_shape, iters=5, inv_link=\n 'identity', threads=8)\n", (33819, 33913), False, 'from wordbatch.models import FTRL, FM_FTRL\n'), ((34573, 34722), 'wordbatch.models.FM_FTRL', 'FM_FTRL', ([], {'alpha': '(0.01)', 'beta': '(0.01)', 'L1': '(1)', 'L2': '(8)', 'D': 'd_shape', 'alpha_fm': '(0.01)', 'L2_fm': '(0.0)', 'init_fm': '(0.01)', 'D_fm': '(200)', 'iters': '(6)', 'inv_link': '"""identity"""', 'threads': '(8)'}), "(alpha=0.01, beta=0.01, L1=1, L2=8, D=d_shape, alpha_fm=0.01, L2_fm=\n 0.0, init_fm=0.01, D_fm=200, iters=6, inv_link='identity', threads=8)\n", (34580, 34722), False, 'from wordbatch.models import FTRL, FM_FTRL\n'), ((35514, 35559), 'pandas.read_csv', 'pd.read_csv', (['"""../input/sample_submission.csv"""'], {}), "('../input/sample_submission.csv')\n", (35525, 35559), True, 'import pandas as pd\n'), ((4597, 4605), 'time.gmtime', 'gmtime', ([], {}), '()\n', (4603, 4605), False, 'from time import gmtime, strftime\n'), ((19407, 19441), 'numpy.log1p', 'np.log1p', (["merge['item_seq_number']"], {}), "(merge['item_seq_number'])\n", (19415, 19441), True, 'import numpy as np\n'), ((23923, 24338), 'pandas.get_dummies', 'pd.get_dummies', (["merge[['param_1', 'param_2', 'param_3', 'image_top_1', 'is_in_desc_хорошо',\n 'is_in_desc_Плохо', 'is_in_desc_новый', 'is_in_desc_старый',\n 'is_in_desc_используемый', 'is_in_desc_есплатная_доставка',\n 'is_in_desc_есплатный_возврат', 'is_in_desc_идеально',\n 'is_in_desc_подержанный', 'is_in_desc_пСниженные_цены', 'user_type',\n 'category_name', 'parent_category_name']]"], {'sparse': '(True)'}), "(merge[['param_1', 'param_2', 'param_3', 'image_top_1',\n 'is_in_desc_хорошо', 'is_in_desc_Плохо', 'is_in_desc_новый',\n 'is_in_desc_старый', 'is_in_desc_используемый',\n 'is_in_desc_есплатная_доставка', 'is_in_desc_есплатный_возврат',\n 'is_in_desc_идеально', 'is_in_desc_подержанный',\n 'is_in_desc_пСниженные_цены', 'user_type', 'category_name',\n 'parent_category_name']], sparse=True)\n", (23937, 24338), True, 'import pandas as pd\n'), ((25417, 25953), 'pandas.get_dummies', 'pd.get_dummies', (["merge[['num_desc_punct', 'num_desc_capE', 'num_desc_capP',\n 'num_title_punct', 'num_title_capP', 'num_title_capE', 'price',\n 'item_seq_number', 'blurinesses', 'whitenesses', 'dullnesses',\n 'average_pixel_width', 'average_reds', 'average_blues',\n 'average_greens', 'widths', 'heights', 'average_HSV_Ss',\n 'average_HSV_Vs', 'average_LUV_Ls', 'average_LUV_Us', 'average_LUV_Vs',\n 'average_HLS_Hs', 'average_HLS_Ls', 'average_HLS_Ss', 'average_YUV_Ys',\n 'average_YUV_Us', 'average_YUV_Vs']]"], {'sparse': '(True)'}), "(merge[['num_desc_punct', 'num_desc_capE', 'num_desc_capP',\n 'num_title_punct', 'num_title_capP', 'num_title_capE', 'price',\n 'item_seq_number', 'blurinesses', 'whitenesses', 'dullnesses',\n 'average_pixel_width', 'average_reds', 'average_blues',\n 'average_greens', 'widths', 'heights', 'average_HSV_Ss',\n 'average_HSV_Vs', 'average_LUV_Ls', 'average_LUV_Us', 'average_LUV_Vs',\n 'average_HLS_Hs', 'average_HLS_Ls', 'average_HLS_Ss', 'average_YUV_Ys',\n 'average_YUV_Us', 'average_YUV_Vs']], sparse=True)\n", (25431, 25953), True, 'import pandas as pd\n'), ((31817, 32103), 'scipy.sparse.hstack', 'hstack', (['(X_dummies[:len_train], X_counting[:len_train], X_param_1[:len_train],\n X_param_2[:len_train], X_param_3[:len_train], X_desc_merge[:len_train],\n X_title_merge[:len_train], train_word_features, train_char_features,\n train_title_word_features, train_desc_word_features)'], {}), '((X_dummies[:len_train], X_counting[:len_train], X_param_1[:len_train\n ], X_param_2[:len_train], X_param_3[:len_train], X_desc_merge[:\n len_train], X_title_merge[:len_train], train_word_features,\n train_char_features, train_title_word_features, train_desc_word_features))\n', (31823, 32103), False, 'from scipy.sparse import hstack\n'), ((32294, 32576), 'scipy.sparse.hstack', 'hstack', (['(X_dummies[len_train:], X_counting[len_train:], X_param_1[len_train:],\n X_param_2[len_train:], X_param_3[len_train:], X_desc_merge[len_train:],\n X_title_merge[len_train:], test_word_features, test_char_features,\n test_title_word_features, test_desc_word_features)'], {}), '((X_dummies[len_train:], X_counting[len_train:], X_param_1[len_train:\n ], X_param_2[len_train:], X_param_3[len_train:], X_desc_merge[len_train\n :], X_title_merge[len_train:], test_word_features, test_char_features,\n test_title_word_features, test_desc_word_features))\n', (32300, 32576), False, 'from scipy.sparse import hstack\n'), ((37899, 37907), 'time.gmtime', 'gmtime', ([], {}), '()\n', (37905, 37907), False, 'from time import gmtime, strftime\n'), ((16164, 16175), 'time.time', 'time.time', ([], {}), '()\n', (16173, 16175), False, 'import time\n'), ((21515, 21526), 'time.time', 'time.time', ([], {}), '()\n', (21524, 21526), False, 'import time\n'), ((21770, 21781), 'time.time', 'time.time', ([], {}), '()\n', (21779, 21781), False, 'import time\n'), ((23297, 23308), 'time.time', 'time.time', ([], {}), '()\n', (23306, 23308), False, 'import time\n'), ((23573, 23584), 'time.time', 'time.time', ([], {}), '()\n', (23582, 23584), False, 'import time\n'), ((25356, 25367), 'time.time', 'time.time', ([], {}), '()\n', (25365, 25367), False, 'import time\n'), ((33147, 33158), 'time.time', 'time.time', ([], {}), '()\n', (33156, 33158), False, 'import time\n'), ((37949, 37960), 'time.time', 'time.time', ([], {}), '()\n', (37958, 37960), False, 'import time\n'), ((593, 604), 'numpy.log1p', 'np.log1p', (['y'], {}), '(y)\n', (601, 604), True, 'import numpy as np\n'), ((607, 619), 'numpy.log1p', 'np.log1p', (['y0'], {}), '(y0)\n', (615, 619), True, 'import numpy as np\n'), ((4519, 4530), 'time.time', 'time.time', ([], {}), '()\n', (4528, 4530), False, 'import time\n'), ((21645, 21675), 'numpy.log2', 'np.log2', (['(1 + merge[fea].values)'], {}), '(1 + merge[fea].values)\n', (21652, 21675), True, 'import numpy as np\n'), ((29574, 29601), 're.findall', 're.findall', (['"""[^{P}\\\\W]+"""', 'x'], {}), "('[^{P}\\\\W]+', x)\n", (29584, 29601), False, 'import re\n'), ((30116, 30143), 're.findall', 're.findall', (['"""[^{P}\\\\W]+"""', 'x'], {}), "('[^{P}\\\\W]+', x)\n", (30126, 30143), False, 'import re\n'), ((31108, 31135), 're.findall', 're.findall', (['"""[^{P}\\\\W]+"""', 'x'], {}), "('[^{P}\\\\W]+', x)\n", (31118, 31135), False, 'import re\n')]
|
import numpy as np
import sklearn.dummy
import sklearn.linear_model
def eta_string(time_points, remaining_works):
return format_timedelta(eta(time_points, remaining_works))
def eta(time_points, remaining_works, regression_points_used=200):
"""Estimate the time remaining until completion of a task based on step history.
Args:
time_points: a sequence of points in time, represented as seconds elapsed since a common
reference, such as the Unix epoch or anything else.
remaining_works: a sequence of amounts of work that were remaining to be done at each
time in `time_points`. The values must be non-negative and 0 represents the
full completion of the task.
regression_points_used: This many of the last measurments are used in the linear regression.
Returns:
The estimated time remaining until completion of the task, relative to the last element
of `time_points`.
"""
time_points = np.asarray(time_points)
remaining_works = np.asarray(remaining_works)
return np.mean([
eta_linear_regression_shifted(
time_points[-regression_points_used:],
remaining_works[-regression_points_used:]),
eta_lookback(time_points, remaining_works)])
def eta_lookback(t, r):
"""Before half the work is done, make an estimate based on the first and last data points.
After that: given X amount of work remaining, assume that this X amount of
work will take the same time that the most recent X amount of work took.
In other words, the time remaining is equal to the time that elapsed between having 2*X
remaining work and X remaining work (i.e. now)."""
# Until half is done, estimate based on first and last:
if r[-1] * 2 >= r[0]:
time_per_unit_work = (t[-1] - t[0]) / (r[0] - r[-1])
return r[-1] * time_per_unit_work
# Find the time when twice the current remaining work was remaining, by linear interpolation.
# np.interp requires an increasing sequence, hence the negative signs.
t_twice_remaining = np.interp(-r[-1] * 2, -r, t)
return t[-1] - t_twice_remaining
def eta_linear_regression_shifted(t, r):
"""Estimate the time remaining by the following method:
Calculate the speed of progress by linear regression then make an estimate considering this
speed and the current work amount remaining (shifting the regression line
to go through the last point while keeping the slope)."""
model = sklearn.linear_model.LinearRegression()
model.fit(np.expand_dims(t, axis=1), r)
speed = -model.coef_[0]
return r[-1] / speed
def format_timedelta(seconds):
if seconds is None or np.isnan(seconds):
return 'unknown'
if seconds == np.inf:
return '∞'
if int(seconds) <= 0:
return '<= 0'
seconds = int(seconds)
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
years, days = divmod(days, 365)
values = [years, days, hours, minutes, seconds]
unit_names = ['year', 'day', 'hour', 'minute', 'second']
# Get first index where the value is larger than 0
i1 = next(i for (i, x) in enumerate(values) if x > 0)
return ', '.join(f'{value} {unit_name}{"" if value == 1 else "s"}'
for value, unit_name in zip(values[i1:i1 + 2], unit_names[i1:i1 + 2]))
|
[
"numpy.interp",
"numpy.asarray",
"numpy.expand_dims",
"numpy.isnan"
] |
[((991, 1014), 'numpy.asarray', 'np.asarray', (['time_points'], {}), '(time_points)\n', (1001, 1014), True, 'import numpy as np\n'), ((1037, 1064), 'numpy.asarray', 'np.asarray', (['remaining_works'], {}), '(remaining_works)\n', (1047, 1064), True, 'import numpy as np\n'), ((2097, 2125), 'numpy.interp', 'np.interp', (['(-r[-1] * 2)', '(-r)', 't'], {}), '(-r[-1] * 2, -r, t)\n', (2106, 2125), True, 'import numpy as np\n'), ((2569, 2594), 'numpy.expand_dims', 'np.expand_dims', (['t'], {'axis': '(1)'}), '(t, axis=1)\n', (2583, 2594), True, 'import numpy as np\n'), ((2711, 2728), 'numpy.isnan', 'np.isnan', (['seconds'], {}), '(seconds)\n', (2719, 2728), True, 'import numpy as np\n')]
|
import batoid
import numpy as np
from test_helpers import timer
@timer
def test_rSplit():
for i in range(100):
R = np.random.normal(0.7, 0.8)
conic = np.random.uniform(-2.0, 1.0)
ncoef = np.random.randint(0, 4)
coefs = [np.random.normal(0, 1e-10) for i in range(ncoef)]
asphere = batoid.Asphere(R, conic, coefs)
rays = batoid.rayGrid(10, 2*R, 0.0, 0.0, -1.0, 16, 500e-9, 1.0, batoid.Air())
coating = batoid.SimpleCoating(0.9, 0.1)
reflectedRays = asphere.reflect(rays, coating)
m1 = batoid.Air()
m2 = batoid.ConstMedium(1.1)
refractedRays = asphere.refract(rays, m1, m2, coating)
reflectedRays2, refractedRays2 = asphere.rSplit(rays, m1, m2, coating)
assert reflectedRays == reflectedRays2
assert refractedRays == refractedRays2
if __name__ == '__main__':
test_rSplit()
|
[
"numpy.random.uniform",
"batoid.SimpleCoating",
"batoid.Asphere",
"batoid.ConstMedium",
"batoid.Air",
"numpy.random.randint",
"numpy.random.normal"
] |
[((129, 155), 'numpy.random.normal', 'np.random.normal', (['(0.7)', '(0.8)'], {}), '(0.7, 0.8)\n', (145, 155), True, 'import numpy as np\n'), ((172, 200), 'numpy.random.uniform', 'np.random.uniform', (['(-2.0)', '(1.0)'], {}), '(-2.0, 1.0)\n', (189, 200), True, 'import numpy as np\n'), ((217, 240), 'numpy.random.randint', 'np.random.randint', (['(0)', '(4)'], {}), '(0, 4)\n', (234, 240), True, 'import numpy as np\n'), ((326, 357), 'batoid.Asphere', 'batoid.Asphere', (['R', 'conic', 'coefs'], {}), '(R, conic, coefs)\n', (340, 357), False, 'import batoid\n'), ((463, 493), 'batoid.SimpleCoating', 'batoid.SimpleCoating', (['(0.9)', '(0.1)'], {}), '(0.9, 0.1)\n', (483, 493), False, 'import batoid\n'), ((562, 574), 'batoid.Air', 'batoid.Air', ([], {}), '()\n', (572, 574), False, 'import batoid\n'), ((588, 611), 'batoid.ConstMedium', 'batoid.ConstMedium', (['(1.1)'], {}), '(1.1)\n', (606, 611), False, 'import batoid\n'), ((258, 284), 'numpy.random.normal', 'np.random.normal', (['(0)', '(1e-10)'], {}), '(0, 1e-10)\n', (274, 284), True, 'import numpy as np\n'), ((431, 443), 'batoid.Air', 'batoid.Air', ([], {}), '()\n', (441, 443), False, 'import batoid\n')]
|
from argparse import ArgumentParser
from copy import deepcopy
import json
import random
import spacy
from rouge import Rouge
from tqdm import tqdm
import numpy as np
from collections import defaultdict
import functools
import operator
from gensim.models import Word2Vec
import streamlit as st
import requests
import bs4
import re
nlp = spacy.load("en_core_web_lg", disable=["tagger", "ner", "parser"])
nlp.add_pipe(nlp.create_pipe('sentencizer'))
class BaselineSummarizer:
def __init__(self, n_sentences=5):
self._n_sentences = n_sentences
def __call__(self, text):
doc = nlp(text)
sentences = list(doc.sents)
idx = list(range(len(sentences)))
random.shuffle(idx)
return "\n".join([sentences[i].text for i in sorted(idx[:self._n_sentences])])
class Summarizer:
def __init__(self, n_sentences=5):
self._n_sentences = n_sentences
def __call__(self, text):
doc = nlp(text)
sentences = [sent for sent in doc.sents if sent.has_vector]
sentences_rank = sorted(
range(len(sentences)),
key=lambda i: doc.similarity(sentences[i]),
reverse=True
)
i2s = {}
for r in sentences_rank[:self._n_sentences]:
i2s[r] = sentences[r]
return "\n".join([sentences[i].text for i in sorted(i2s.keys())])
class TrainedSummarizer:
def __init__(self, n_sentences=5, dim=100):
self._n_sentences = n_sentences
self._model = None
self._dim = dim
def fit(self, train, train_size=None):
if train_size is not None:
train = deepcopy(train)
random.shuffle(train)
train = train[:train_size]
train_tokens = []
for train_item in tqdm(train, desc="tokenize"):
train_tokens.append([t.text for t in nlp(train_item)])
self._model = Word2Vec(sentences=train_tokens, size=self._dim, iter=10)
def average_vector(self, tokens):
vectors = [self._model.wv[t.text] for t in tokens if t.text in self._model.wv]
if vectors:
return functools.reduce(operator.add, vectors)
else:
return np.zeros(self._dim)
def __call__(self, text):
doc = nlp(text)
sentences = [sent for sent in doc.sents if sent.has_vector]
doc_vector = self.average_vector(doc)
sentences_rank = sorted(
range(len(sentences)),
key=lambda i: np.dot(doc_vector, self.average_vector(sentences[i])),
reverse=True
)
i2s = {}
for r in sentences_rank[:self._n_sentences]:
i2s[r] = sentences[r]
return "\n".join([sentences[i].text for i in sorted(i2s.keys())])
def compare_summarizers(data, summarizers):
# construct rouge metric function ROUGE-1 F
compute_rouge = Rouge(metrics=["rouge-1"], stats=["f"])
def get_score(reference, hypothesis):
"""
Compute ROUGE-1 F score
:param reference: true summary
:param hypothesis: predicted summary
:return: the value of ROUGE-1 F
"""
return compute_rouge.get_scores(hypothesis, reference)[0]["rouge-1"]["f"]
# Compare summarizers on the part of the validation dataset.
# Dataset is a list of dicts, each dict has two keys: "document" and "summary".
validation = deepcopy(data["validation"])
if args.validation_size is None:
validation_size = len(validation)
else:
validation_size = args.validation_size
# NB: always shuffle the data!
random.shuffle(validation)
# A document is a text of news articles separated by special token "|||||".
# For proper sentence segmentation we need to clean up the data.
def clean_document(text):
return "\n".join(text.split("|||||"))
print("Compute scores on the validation dataset")
scores = defaultdict(list)
for i in tqdm(range(validation_size)):
document = clean_document(validation[i]["document"])
true_summary = validation[i]["summary"]
for summarizer_name, summarizer in summarizers.items():
summary = summarizer(document)
scores[summarizer_name].append(get_score(true_summary, summary))
for summarizer_name in summarizers:
print("Score of '{}' is {}".format(summarizer_name, np.mean(scores[summarizer_name])))
if __name__ == '__main__':
p = ArgumentParser()
p.add_argument("solution", type=int, choices=(1, 2, 3))
p.add_argument("--multi-news-json", default="multi_news.json")
p.add_argument("-s", "--seed", type=int, default=0, help="random seed")
p.add_argument("-n", "--validation-size", type=int)
p.add_argument("-t", "--train-size", type=int)
args = p.parse_args()
random.seed(args.seed)
if args.solution == 3:
# show demo
summarizer = Summarizer(n_sentences=5)
st.title("TechCrunch sentence summarization demo")
url = st.text_input("TechCrunch URL", "")
@st.cache
def parse_techcrunch_url(url):
response = requests.get(url)
soup = bs4.BeautifulSoup(response.text, "html.parser")
items = soup.find("div", {"class": "article-content"}).findAll("p")
raw_html = "\n".join(map(str, items))
cleanr = re.compile('<.*?>')
clean_html = re.sub(cleanr, '', raw_html)
summary = summarizer(clean_html)
return summary, raw_html
if url:
summary, raw_html = parse_techcrunch_url(url)
st.subheader('Summary')
st.write(summary)
st.subheader('Article')
st.markdown(raw_html, unsafe_allow_html=True)
else:
# evaluate quality of summarizers
# read the data from multi_news.json
with open(args.multi_news_json) as f:
print("Read multi news data from", args.multi_news_json)
data = json.load(f)
summarizers = dict()
summarizers["baseline"] = BaselineSummarizer(n_sentences=5)
summarizers["spaCy vectors"] = Summarizer(n_sentences=5)
if args.solution == 2:
print("Train summarizer")
summarizers["trained vectors"] = TrainedSummarizer(n_sentences=5)
summarizers["trained vectors"].fit([e["document"] for e in data["train"]], train_size=args.train_size)
compare_summarizers(data, summarizers)
|
[
"streamlit.text_input",
"argparse.ArgumentParser",
"random.shuffle",
"streamlit.title",
"collections.defaultdict",
"numpy.mean",
"streamlit.subheader",
"rouge.Rouge",
"spacy.load",
"random.seed",
"requests.get",
"re.sub",
"copy.deepcopy",
"tqdm.tqdm",
"bs4.BeautifulSoup",
"re.compile",
"streamlit.markdown",
"json.load",
"numpy.zeros",
"gensim.models.Word2Vec",
"streamlit.write",
"functools.reduce"
] |
[((338, 403), 'spacy.load', 'spacy.load', (['"""en_core_web_lg"""'], {'disable': "['tagger', 'ner', 'parser']"}), "('en_core_web_lg', disable=['tagger', 'ner', 'parser'])\n", (348, 403), False, 'import spacy\n'), ((2851, 2890), 'rouge.Rouge', 'Rouge', ([], {'metrics': "['rouge-1']", 'stats': "['f']"}), "(metrics=['rouge-1'], stats=['f'])\n", (2856, 2890), False, 'from rouge import Rouge\n'), ((3363, 3391), 'copy.deepcopy', 'deepcopy', (["data['validation']"], {}), "(data['validation'])\n", (3371, 3391), False, 'from copy import deepcopy\n'), ((3896, 3913), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (3907, 3913), False, 'from collections import defaultdict\n'), ((4425, 4441), 'argparse.ArgumentParser', 'ArgumentParser', ([], {}), '()\n', (4439, 4441), False, 'from argparse import ArgumentParser\n'), ((4782, 4804), 'random.seed', 'random.seed', (['args.seed'], {}), '(args.seed)\n', (4793, 4804), False, 'import random\n'), ((697, 716), 'random.shuffle', 'random.shuffle', (['idx'], {}), '(idx)\n', (711, 716), False, 'import random\n'), ((1770, 1798), 'tqdm.tqdm', 'tqdm', (['train'], {'desc': '"""tokenize"""'}), "(train, desc='tokenize')\n", (1774, 1798), False, 'from tqdm import tqdm\n'), ((1890, 1947), 'gensim.models.Word2Vec', 'Word2Vec', ([], {'sentences': 'train_tokens', 'size': 'self._dim', 'iter': '(10)'}), '(sentences=train_tokens, size=self._dim, iter=10)\n', (1898, 1947), False, 'from gensim.models import Word2Vec\n'), ((3575, 3601), 'random.shuffle', 'random.shuffle', (['validation'], {}), '(validation)\n', (3589, 3601), False, 'import random\n'), ((4908, 4958), 'streamlit.title', 'st.title', (['"""TechCrunch sentence summarization demo"""'], {}), "('TechCrunch sentence summarization demo')\n", (4916, 4958), True, 'import streamlit as st\n'), ((4973, 5008), 'streamlit.text_input', 'st.text_input', (['"""TechCrunch URL"""', '""""""'], {}), "('TechCrunch URL', '')\n", (4986, 5008), True, 'import streamlit as st\n'), ((1628, 1643), 'copy.deepcopy', 'deepcopy', (['train'], {}), '(train)\n', (1636, 1643), False, 'from copy import deepcopy\n'), ((1656, 1677), 'random.shuffle', 'random.shuffle', (['train'], {}), '(train)\n', (1670, 1677), False, 'import random\n'), ((2113, 2152), 'functools.reduce', 'functools.reduce', (['operator.add', 'vectors'], {}), '(operator.add, vectors)\n', (2129, 2152), False, 'import functools\n'), ((2186, 2205), 'numpy.zeros', 'np.zeros', (['self._dim'], {}), '(self._dim)\n', (2194, 2205), True, 'import numpy as np\n'), ((5090, 5107), 'requests.get', 'requests.get', (['url'], {}), '(url)\n', (5102, 5107), False, 'import requests\n'), ((5127, 5174), 'bs4.BeautifulSoup', 'bs4.BeautifulSoup', (['response.text', '"""html.parser"""'], {}), "(response.text, 'html.parser')\n", (5144, 5174), False, 'import bs4\n'), ((5326, 5345), 're.compile', 're.compile', (['"""<.*?>"""'], {}), "('<.*?>')\n", (5336, 5345), False, 'import re\n'), ((5371, 5399), 're.sub', 're.sub', (['cleanr', '""""""', 'raw_html'], {}), "(cleanr, '', raw_html)\n", (5377, 5399), False, 'import re\n'), ((5569, 5592), 'streamlit.subheader', 'st.subheader', (['"""Summary"""'], {}), "('Summary')\n", (5581, 5592), True, 'import streamlit as st\n'), ((5605, 5622), 'streamlit.write', 'st.write', (['summary'], {}), '(summary)\n', (5613, 5622), True, 'import streamlit as st\n'), ((5635, 5658), 'streamlit.subheader', 'st.subheader', (['"""Article"""'], {}), "('Article')\n", (5647, 5658), True, 'import streamlit as st\n'), ((5671, 5716), 'streamlit.markdown', 'st.markdown', (['raw_html'], {'unsafe_allow_html': '(True)'}), '(raw_html, unsafe_allow_html=True)\n', (5682, 5716), True, 'import streamlit as st\n'), ((5950, 5962), 'json.load', 'json.load', (['f'], {}), '(f)\n', (5959, 5962), False, 'import json\n'), ((4353, 4385), 'numpy.mean', 'np.mean', (['scores[summarizer_name]'], {}), '(scores[summarizer_name])\n', (4360, 4385), True, 'import numpy as np\n')]
|
import argparse
import os
import torch
import itertools
from game.Player import RandomPlayer
from ai.HeuristicPlayer import HeuristicPlayer1, HeuristicPlayer2
from ai.RLPlayer import RLPlayer
from ai.EAPlayer import EAPlayer
from game.Game import Game
import numpy as np
from tqdm import tqdm
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('rounds_per_player', help="Total rounds per two players to play", type=int)
parser.add_argument('-c', '--config-path', default="./config.json")
return parser.parse_args()
if __name__ == '__main__':
args = parse_args()
rounds = args.rounds_per_player
output_dir_path = "output/" + "two_players"
device = 'cuda' if torch.cuda.is_available() else 'cpu'
print(f"Device used: {device}")
try:
os.mkdir(output_dir_path)
except OSError as error:
print(error)
rl_params = {"gamma": 0.99, "device": device}
action_space = ["left", "straight", "right"]
rl_weight_paths = [
"output/single_RL_g0.999/p1_final_"
]
ea_weight_paths = [
"output/EA_single_4/best_0.txt",
"output/EA_multi_pretrain_0/best_0.txt"
]
weights = [
np.genfromtxt(ea_weight_paths[0]),
np.genfromtxt(ea_weight_paths[1])
]
game = Game(2, 0, config_path=args.config_path)
game.init_round(2, 0)
game_state = game.get_game_state()
players = [
RandomPlayer("Random"),
HeuristicPlayer1("Creeper"),
HeuristicPlayer2("Bouncer"),
RLPlayer("RL_failure", game_state, action_space, parameters=rl_params),
EAPlayer("EA_single_trained", weights[0]),
EAPlayer("EA_full_trained", weights[1])
]
players[3].load_model_weights(rl_weight_paths[0])
stats = []
for players_in_round in itertools.combinations_with_replacement(players, r=2):
player1, player2 = players_in_round
print(f"{player1} vs {player2}")
stats.append([])
for i in tqdm(range(rounds), total=rounds):
if i % 2 == 0:
game.init_round([player1, player2], 0)
game_state = game.get_game_state().copy()
finish = False
while not finish:
actions = [player1.action(game_state, learning=False), player2.action(game_state, learning=False)]
finish = game.tick_ai(actions)
game_state = game.get_game_state().copy()
who_won = game_state["player_won"]
scores = [game.round.round_tick_counter, who_won]
stats[-1].append(scores)
else:
game.init_round([player2, player1], 0)
game_state = game.get_game_state().copy()
finish = False
while not finish:
actions = [player2.action(game_state, learning=False), player1.action(game_state, learning=False)]
finish = game.tick_ai(actions)
game_state = game.get_game_state().copy()
if game_state["player_won"] != -1:
who_won = (1, 0)[game_state["player_won"]]
else:
who_won = game_state["player_won"]
scores = [game.round.round_tick_counter, who_won]
stats[-1].append(scores)
temp_stats = np.array(stats[-1])
print(f"\n[0] {player1} stats: W/L/D {np.count_nonzero(temp_stats == 0)}/{np.count_nonzero(temp_stats == 1)}/{np.count_nonzero(temp_stats == -1)}",
f"\n[1] {player2} stats: W/L/D {np.count_nonzero(temp_stats == 1)}/{np.count_nonzero(temp_stats == 0)}/{np.count_nonzero(temp_stats == -1)}")
np.savetxt(f"{output_dir_path}/{player1.name}_vs_{player2.name}_stats.csv", temp_stats)
stats = np.array(stats)
|
[
"ai.EAPlayer.EAPlayer",
"os.mkdir",
"game.Player.RandomPlayer",
"ai.RLPlayer.RLPlayer",
"numpy.count_nonzero",
"argparse.ArgumentParser",
"game.Game.Game",
"numpy.savetxt",
"numpy.genfromtxt",
"itertools.combinations_with_replacement",
"ai.HeuristicPlayer.HeuristicPlayer2",
"torch.cuda.is_available",
"numpy.array",
"ai.HeuristicPlayer.HeuristicPlayer1"
] |
[((328, 353), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (351, 353), False, 'import argparse\n'), ((1301, 1341), 'game.Game.Game', 'Game', (['(2)', '(0)'], {'config_path': 'args.config_path'}), '(2, 0, config_path=args.config_path)\n', (1305, 1341), False, 'from game.Game import Game\n'), ((1814, 1867), 'itertools.combinations_with_replacement', 'itertools.combinations_with_replacement', (['players'], {'r': '(2)'}), '(players, r=2)\n', (1853, 1867), False, 'import itertools\n'), ((3817, 3832), 'numpy.array', 'np.array', (['stats'], {}), '(stats)\n', (3825, 3832), True, 'import numpy as np\n'), ((718, 743), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (741, 743), False, 'import torch\n'), ((809, 834), 'os.mkdir', 'os.mkdir', (['output_dir_path'], {}), '(output_dir_path)\n', (817, 834), False, 'import os\n'), ((1206, 1239), 'numpy.genfromtxt', 'np.genfromtxt', (['ea_weight_paths[0]'], {}), '(ea_weight_paths[0])\n', (1219, 1239), True, 'import numpy as np\n'), ((1249, 1282), 'numpy.genfromtxt', 'np.genfromtxt', (['ea_weight_paths[1]'], {}), '(ea_weight_paths[1])\n', (1262, 1282), True, 'import numpy as np\n'), ((1432, 1454), 'game.Player.RandomPlayer', 'RandomPlayer', (['"""Random"""'], {}), "('Random')\n", (1444, 1454), False, 'from game.Player import RandomPlayer\n'), ((1464, 1491), 'ai.HeuristicPlayer.HeuristicPlayer1', 'HeuristicPlayer1', (['"""Creeper"""'], {}), "('Creeper')\n", (1480, 1491), False, 'from ai.HeuristicPlayer import HeuristicPlayer1, HeuristicPlayer2\n'), ((1501, 1528), 'ai.HeuristicPlayer.HeuristicPlayer2', 'HeuristicPlayer2', (['"""Bouncer"""'], {}), "('Bouncer')\n", (1517, 1528), False, 'from ai.HeuristicPlayer import HeuristicPlayer1, HeuristicPlayer2\n'), ((1538, 1608), 'ai.RLPlayer.RLPlayer', 'RLPlayer', (['"""RL_failure"""', 'game_state', 'action_space'], {'parameters': 'rl_params'}), "('RL_failure', game_state, action_space, parameters=rl_params)\n", (1546, 1608), False, 'from ai.RLPlayer import RLPlayer\n'), ((1618, 1659), 'ai.EAPlayer.EAPlayer', 'EAPlayer', (['"""EA_single_trained"""', 'weights[0]'], {}), "('EA_single_trained', weights[0])\n", (1626, 1659), False, 'from ai.EAPlayer import EAPlayer\n'), ((1669, 1708), 'ai.EAPlayer.EAPlayer', 'EAPlayer', (['"""EA_full_trained"""', 'weights[1]'], {}), "('EA_full_trained', weights[1])\n", (1677, 1708), False, 'from ai.EAPlayer import EAPlayer\n'), ((3375, 3394), 'numpy.array', 'np.array', (['stats[-1]'], {}), '(stats[-1])\n', (3383, 3394), True, 'import numpy as np\n'), ((3716, 3807), 'numpy.savetxt', 'np.savetxt', (['f"""{output_dir_path}/{player1.name}_vs_{player2.name}_stats.csv"""', 'temp_stats'], {}), "(f'{output_dir_path}/{player1.name}_vs_{player2.name}_stats.csv',\n temp_stats)\n", (3726, 3807), True, 'import numpy as np\n'), ((3441, 3474), 'numpy.count_nonzero', 'np.count_nonzero', (['(temp_stats == 0)'], {}), '(temp_stats == 0)\n', (3457, 3474), True, 'import numpy as np\n'), ((3477, 3510), 'numpy.count_nonzero', 'np.count_nonzero', (['(temp_stats == 1)'], {}), '(temp_stats == 1)\n', (3493, 3510), True, 'import numpy as np\n'), ((3513, 3547), 'numpy.count_nonzero', 'np.count_nonzero', (['(temp_stats == -1)'], {}), '(temp_stats == -1)\n', (3529, 3547), True, 'import numpy as np\n'), ((3597, 3630), 'numpy.count_nonzero', 'np.count_nonzero', (['(temp_stats == 1)'], {}), '(temp_stats == 1)\n', (3613, 3630), True, 'import numpy as np\n'), ((3633, 3666), 'numpy.count_nonzero', 'np.count_nonzero', (['(temp_stats == 0)'], {}), '(temp_stats == 0)\n', (3649, 3666), True, 'import numpy as np\n'), ((3669, 3703), 'numpy.count_nonzero', 'np.count_nonzero', (['(temp_stats == -1)'], {}), '(temp_stats == -1)\n', (3685, 3703), True, 'import numpy as np\n')]
|
import numpy as np
from sgp4.api import Satrec
from astropy.io import ascii
def minmaxloc(num_list):
return np.argmin(num_list), np.argmax(num_list)
np.set_printoptions(precision=2)
with open('hipparcos-tle.txt', 'r') as f:
st = f.read().split('\n')
jds = np.genfromtxt("hipparcos_tle_jd.txt", dtype=None)
Njd = len(jds)
s = st[0:(Njd*2-1):2]
t = st[1:(Njd*2):2]
Nsim = 100000
jdsim = np.linspace(min(jds),max(jds),num=Nsim)
tmp = np.modf(jdsim)
jdi = tmp[1]
jdf = tmp[0]
es = np.zeros(Nsim)
rs = np.zeros((Nsim,3))
vs = np.zeros((Nsim,3))
for k in range(0,Nsim):
# index = np.minmaxloc(abs(jds-jdsim[k]))[0]
if k < (Nsim - 1):
index = np.where(jds - jdsim[k] > 0)[0][0] - 1
else:
index = Njd-1
satellite = Satrec.twoline2rv(s[index], t[index])
e, r, v = satellite.sgp4(jdi[k], jdf[k])
es[k] = e
rs[k][:] = r
vs[k][:] = v
out = np.concatenate((jdsim,rs,vs), axis=1)
np.savetxt('hipparcos_state.txt', out, delimiter=' ')
|
[
"numpy.set_printoptions",
"numpy.argmax",
"sgp4.api.Satrec.twoline2rv",
"numpy.savetxt",
"numpy.zeros",
"numpy.genfromtxt",
"numpy.argmin",
"numpy.where",
"numpy.modf",
"numpy.concatenate"
] |
[((156, 188), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'precision': '(2)'}), '(precision=2)\n', (175, 188), True, 'import numpy as np\n'), ((269, 318), 'numpy.genfromtxt', 'np.genfromtxt', (['"""hipparcos_tle_jd.txt"""'], {'dtype': 'None'}), "('hipparcos_tle_jd.txt', dtype=None)\n", (282, 318), True, 'import numpy as np\n'), ((444, 458), 'numpy.modf', 'np.modf', (['jdsim'], {}), '(jdsim)\n', (451, 458), True, 'import numpy as np\n'), ((492, 506), 'numpy.zeros', 'np.zeros', (['Nsim'], {}), '(Nsim)\n', (500, 506), True, 'import numpy as np\n'), ((512, 531), 'numpy.zeros', 'np.zeros', (['(Nsim, 3)'], {}), '((Nsim, 3))\n', (520, 531), True, 'import numpy as np\n'), ((536, 555), 'numpy.zeros', 'np.zeros', (['(Nsim, 3)'], {}), '((Nsim, 3))\n', (544, 555), True, 'import numpy as np\n'), ((892, 931), 'numpy.concatenate', 'np.concatenate', (['(jdsim, rs, vs)'], {'axis': '(1)'}), '((jdsim, rs, vs), axis=1)\n', (906, 931), True, 'import numpy as np\n'), ((930, 983), 'numpy.savetxt', 'np.savetxt', (['"""hipparcos_state.txt"""', 'out'], {'delimiter': '""" """'}), "('hipparcos_state.txt', out, delimiter=' ')\n", (940, 983), True, 'import numpy as np\n'), ((754, 791), 'sgp4.api.Satrec.twoline2rv', 'Satrec.twoline2rv', (['s[index]', 't[index]'], {}), '(s[index], t[index])\n', (771, 791), False, 'from sgp4.api import Satrec\n'), ((113, 132), 'numpy.argmin', 'np.argmin', (['num_list'], {}), '(num_list)\n', (122, 132), True, 'import numpy as np\n'), ((134, 153), 'numpy.argmax', 'np.argmax', (['num_list'], {}), '(num_list)\n', (143, 153), True, 'import numpy as np\n'), ((667, 695), 'numpy.where', 'np.where', (['(jds - jdsim[k] > 0)'], {}), '(jds - jdsim[k] > 0)\n', (675, 695), True, 'import numpy as np\n')]
|
'''
Theorem 1
this script is a brute-force verification that the scalar local Lipschitz
result is true
'''
import numpy as np
def relu(y):
return (y>0)*y
def lip(y0,y):
return np.abs(relu(y) - relu(y0))/np.abs(y-y0)
# setup
n_trials = 10**4
n_samps = 7
lip_anl = np.full(n_trials, np.nan)
lip_brute = np.full(n_trials, np.nan)
# loop over many trials
for i in range(n_trials):
# sample some points
y0 = np.random.uniform(-1,1,1)
Y = np.random.uniform(-1,1,n_samps)
# analytical
ybar = np.max(Y)
lip_anl[i] = lip(y0,ybar)
# brute-force
lip_frac = lip(y0,Y)
lip_brute[i] = np.max(lip_frac)
# compare analytical and brute-force results
lip_diff = lip_anl - lip_brute
lip_err = np.linalg.norm(lip_diff)
# print results
#print(lip_anl)
#print(lip_brute)
print('analytical v brute-force local Lipschitz error (should be zero):')
print(lip_err)
|
[
"numpy.full",
"numpy.random.uniform",
"numpy.abs",
"numpy.max",
"numpy.linalg.norm"
] |
[((275, 300), 'numpy.full', 'np.full', (['n_trials', 'np.nan'], {}), '(n_trials, np.nan)\n', (282, 300), True, 'import numpy as np\n'), ((313, 338), 'numpy.full', 'np.full', (['n_trials', 'np.nan'], {}), '(n_trials, np.nan)\n', (320, 338), True, 'import numpy as np\n'), ((726, 750), 'numpy.linalg.norm', 'np.linalg.norm', (['lip_diff'], {}), '(lip_diff)\n', (740, 750), True, 'import numpy as np\n'), ((424, 451), 'numpy.random.uniform', 'np.random.uniform', (['(-1)', '(1)', '(1)'], {}), '(-1, 1, 1)\n', (441, 451), True, 'import numpy as np\n'), ((458, 491), 'numpy.random.uniform', 'np.random.uniform', (['(-1)', '(1)', 'n_samps'], {}), '(-1, 1, n_samps)\n', (475, 491), True, 'import numpy as np\n'), ((519, 528), 'numpy.max', 'np.max', (['Y'], {}), '(Y)\n', (525, 528), True, 'import numpy as np\n'), ((622, 638), 'numpy.max', 'np.max', (['lip_frac'], {}), '(lip_frac)\n', (628, 638), True, 'import numpy as np\n'), ((214, 228), 'numpy.abs', 'np.abs', (['(y - y0)'], {}), '(y - y0)\n', (220, 228), True, 'import numpy as np\n')]
|
"""
2016 Day 8
https://adventofcode.com/2016/day/8
"""
from typing import Callable, Sequence, Tuple
import re
import numpy as np
import aocd # type: ignore
def blank_screen() -> np.ndarray:
"""
Create an empty 50x6 array.
"""
return np.array([[0 for col in range(50)] for row in range(6)], int)
def rotate_row(screen: np.ndarray, target_row: int, distance: int) -> np.ndarray:
"""
Rotate a specific row by a number of steps, with any items falling off the end being returned
to the opposite side.
"""
return np.array(
[
np.roll(row, distance) if r == target_row else row
for r, row in enumerate(screen)
]
)
def rotate_col(screen: np.ndarray, target_col: int, distance: int) -> np.ndarray:
"""
Rotate a specific column by a number of steps, with any items falling off the end being
returned to the oppoisite side.
"""
rotated = np.rot90(screen, axes=(1, 0))
rolled = rotate_row(rotated, target_col, -distance)
return np.rot90(rolled, axes=(0, 1))
def rect(screen: np.ndarray, width: int, height: int) -> np.ndarray:
"""
Return a modified version of the screen with the values in a 'width' x 'height' rectangle at
the top left being set to 1.
"""
return np.array(
[
[1 if c < width and r < height else val for (c, val) in enumerate(row)]
for (r, row) in enumerate(screen)
]
)
ScreenFunction = Callable[[np.ndarray, int, int], np.ndarray]
Operation = Tuple[re.Pattern, ScreenFunction]
OPERATIONS: Sequence[Operation] = [
(re.compile(regex), screen_function)
for (regex, screen_function) in (
(r"rect (\d+)x(\d+)", rect),
(r"rotate row y=(\d+) by (\d+)", rotate_row),
(r"rotate column x=(\d+) by (\d+)", rotate_col),
)
]
def run(text: str) -> np.ndarray:
"""
Create a blank screen, run all of the commands in the given text in sequence, and then return
the resulting 2d array.
"""
screen = blank_screen()
for instruction in text.split("\n"):
for (regex, func) in OPERATIONS:
search = regex.search(instruction)
if search:
screen = func(screen, *[int(arg) for arg in search.groups()])
return screen
def display(screen: np.ndarray) -> str:
"""
Create a string representation of the screen.
"""
return "\n".join(
"".join("■" if char == 1 else " " for char in line) for line in screen
)
def main() -> None:
"""
Calculate and output the solutions based on the real puzzle input.
"""
data = aocd.get_data(year=2016, day=8)
screen = run(data)
print(f"Part 1: {screen.sum()}")
print(f"Part 2:\n{display(screen)}")
if __name__ == "__main__":
main()
|
[
"numpy.roll",
"numpy.rot90",
"aocd.get_data",
"re.compile"
] |
[((935, 964), 'numpy.rot90', 'np.rot90', (['screen'], {'axes': '(1, 0)'}), '(screen, axes=(1, 0))\n', (943, 964), True, 'import numpy as np\n'), ((1032, 1061), 'numpy.rot90', 'np.rot90', (['rolled'], {'axes': '(0, 1)'}), '(rolled, axes=(0, 1))\n', (1040, 1061), True, 'import numpy as np\n'), ((2627, 2658), 'aocd.get_data', 'aocd.get_data', ([], {'year': '(2016)', 'day': '(8)'}), '(year=2016, day=8)\n', (2640, 2658), False, 'import aocd\n'), ((1608, 1625), 're.compile', 're.compile', (['regex'], {}), '(regex)\n', (1618, 1625), False, 'import re\n'), ((582, 604), 'numpy.roll', 'np.roll', (['row', 'distance'], {}), '(row, distance)\n', (589, 604), True, 'import numpy as np\n')]
|
import tensorflow as tf
from tensorflow import keras
import matplotlib.pyplot as plt
import numpy as np
import os
if __name__ == "__main__":
# Load trained model
model = keras.models.load_model("../paper_results/3d_optmock_6par/models/3D_21cmPIE_Net")
# Plot each of the 32 filters from the first convolutional layer with weights averaged over the first two dimensions
for y in range(32):
weights = model.layers[1].weights[0].numpy()
weights = weights.reshape(3,3,102,32)[:,:,:,y]
weights = np.mean(weights,axis=(0,1))
x = np.linspace(0,len(weights),len(weights))
fig, ax = plt.subplots()
ax.scatter(x,weights,s=4)
ax.set_xlabel("Pixel in redshift direction",fontsize=18)
ax.set_ylabel("Average Weight",fontsize=18)
plt.xticks(fontsize=15)
plt.yticks(fontsize=15)
plt.tight_layout()
fig.autolayout = True
os.makedirs("output/filter_plots/", exist_ok=True)
plt.savefig("output/filter_plots/filter"+str(y)+".png") # 0,1,2,4,5,26 are in Figure C1
plt.close()
|
[
"matplotlib.pyplot.tight_layout",
"tensorflow.keras.models.load_model",
"os.makedirs",
"matplotlib.pyplot.close",
"matplotlib.pyplot.yticks",
"numpy.mean",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.subplots"
] |
[((179, 265), 'tensorflow.keras.models.load_model', 'keras.models.load_model', (['"""../paper_results/3d_optmock_6par/models/3D_21cmPIE_Net"""'], {}), "(\n '../paper_results/3d_optmock_6par/models/3D_21cmPIE_Net')\n", (202, 265), False, 'from tensorflow import keras\n'), ((532, 561), 'numpy.mean', 'np.mean', (['weights'], {'axis': '(0, 1)'}), '(weights, axis=(0, 1))\n', (539, 561), True, 'import numpy as np\n'), ((631, 645), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (643, 645), True, 'import matplotlib.pyplot as plt\n'), ((805, 828), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'fontsize': '(15)'}), '(fontsize=15)\n', (815, 828), True, 'import matplotlib.pyplot as plt\n'), ((837, 860), 'matplotlib.pyplot.yticks', 'plt.yticks', ([], {'fontsize': '(15)'}), '(fontsize=15)\n', (847, 860), True, 'import matplotlib.pyplot as plt\n'), ((869, 887), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (885, 887), True, 'import matplotlib.pyplot as plt\n'), ((926, 976), 'os.makedirs', 'os.makedirs', (['"""output/filter_plots/"""'], {'exist_ok': '(True)'}), "('output/filter_plots/', exist_ok=True)\n", (937, 976), False, 'import os\n'), ((1081, 1092), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (1090, 1092), True, 'import matplotlib.pyplot as plt\n')]
|
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
from timeit import timeit
from fft import direct_ft, recursive_ft, bitrev_ft
a = -np.pi
b = np.pi
N = 512
x = np.linspace(a, b, N)
def func(x, **kwds):
# note peaks for each mode
# return np.sum([np.sin(i*x) for i in (1., 2., 5., 10., 50.)], axis=0)
# note mirrored peaks
# return np.sum(600*x)
# return np.piecewise(x, [np.abs(x)<.1], [1.])
s = kwds.get('s', .1)
return np.exp(-x**2/(2*s**2)) / np.sqrt(2*np.pi*s**2)
f = func(x)
np.fft.fft.__name__ = 'fft_numpy'
dfts = [direct_ft, recursive_ft, bitrev_ft, np.fft.fft]
for dft_func in dfts:
print(dft_func.__name__, ':\t',
timeit('ft(x)', globals={'ft' : dft_func, 'x' : f}, number=1000),
'ms')
fft = bitrev_ft(f)
fig, (ao, ar, ai) = plt.subplots(3)
fig.tight_layout()
fig.canvas.set_window_title('discrete fourier transform')
ao.set(title='original', xlabel='x', ylabel='A')
ao.plot(x, f)
ar.set(title='ft - real part', xlabel='k', ylabel='Â')
ar.plot(fft.real)
ai.set(title='ft - imaginary part', xlabel='k', ylabel='Â')
ai.plot(fft.imag)
|
[
"timeit.timeit",
"numpy.exp",
"fft.bitrev_ft",
"numpy.linspace",
"matplotlib.pyplot.subplots",
"numpy.sqrt"
] |
[((187, 207), 'numpy.linspace', 'np.linspace', (['a', 'b', 'N'], {}), '(a, b, N)\n', (198, 207), True, 'import numpy as np\n'), ((789, 801), 'fft.bitrev_ft', 'bitrev_ft', (['f'], {}), '(f)\n', (798, 801), False, 'from fft import direct_ft, recursive_ft, bitrev_ft\n'), ((823, 838), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(3)'], {}), '(3)\n', (835, 838), True, 'import matplotlib.pyplot as plt\n'), ((480, 510), 'numpy.exp', 'np.exp', (['(-x ** 2 / (2 * s ** 2))'], {}), '(-x ** 2 / (2 * s ** 2))\n', (486, 510), True, 'import numpy as np\n'), ((505, 532), 'numpy.sqrt', 'np.sqrt', (['(2 * np.pi * s ** 2)'], {}), '(2 * np.pi * s ** 2)\n', (512, 532), True, 'import numpy as np\n'), ((699, 761), 'timeit.timeit', 'timeit', (['"""ft(x)"""'], {'globals': "{'ft': dft_func, 'x': f}", 'number': '(1000)'}), "('ft(x)', globals={'ft': dft_func, 'x': f}, number=1000)\n", (705, 761), False, 'from timeit import timeit\n')]
|
import numpy as np
'''
# sort
# Syantax: numpy.sort(a, axis, kind, order)
a = np.array([[3,7],[9,1]])
print("sort default: ", np.sort(a))
print("sort axis = 0: ", np.sort(a, axis = 0))
# VIP sorting based on custom data type
dt = np.dtype([('name', 'S10'),('age', int)])
a = np.array([("raju",21),("anil",25),("ravi", 17), ("amar",27)], dtype = dt)
print("print with a given datatype \n", np.sort(a, order= 'age'))
# argsort
x = np.array([3, 1, 2])
y = np.argsort(x)
print("input array: ", x)
print("indices for sorting: ", y)
print("reconstruct the arry: ", x[y])
'''
# TODO: lexsort
'''
# argmx, argmin
a = np.array([[30,40,70],[80,20,10],[50,90,60]])
print("input array: ", a)
print ("argmax: ", np.argmax(a))
print ("argmax axis=0: ", np.argmax(a, axis =0))
minindex = np.argmin(a)
print ("with minindex ", a.flatten()[minindex])
'''
# where: returns indices where it mataches the condition
a = np.array([[30,40,0],[0,20,10],[50,0,60]])
y = np.where(a > 30)
print("indices are: ", y)
print("get the array with where: ", a[y])
# extract: The extract() function returns the elements satisfying any condition.
x = np.arange(9.).reshape(3, 3)
print ("return the values where condition is correct: ", np.extract(np.mod(x, 2) == 0, x))
|
[
"numpy.where",
"numpy.array",
"numpy.arange",
"numpy.mod"
] |
[((948, 997), 'numpy.array', 'np.array', (['[[30, 40, 0], [0, 20, 10], [50, 0, 60]]'], {}), '([[30, 40, 0], [0, 20, 10], [50, 0, 60]])\n', (956, 997), True, 'import numpy as np\n'), ((997, 1013), 'numpy.where', 'np.where', (['(a > 30)'], {}), '(a > 30)\n', (1005, 1013), True, 'import numpy as np\n'), ((1173, 1187), 'numpy.arange', 'np.arange', (['(9.0)'], {}), '(9.0)\n', (1182, 1187), True, 'import numpy as np\n'), ((1271, 1283), 'numpy.mod', 'np.mod', (['x', '(2)'], {}), '(x, 2)\n', (1277, 1283), True, 'import numpy as np\n')]
|
import numpy as np
import torch as th
def train_ppo(model, optimizer,
obs, acs, advs, vtargs, old_ac_logps,
n_epochs=3, n_mbatch=1, loss='clip',
vfcoef=0.5, entcoef=0.01, kl_threshold=np.inf, **update_kwargs):
batch_size = obs.shape[0]
mbatch_size = int(batch_size / n_mbatch)
for _ in range(n_epochs):
shuffle_idxs = np.random.permutation(batch_size)
obs, acs, advs, vtargs, old_ac_logps = map(
lambda x: x[shuffle_idxs],
[obs, acs, advs, vtargs, old_ac_logps])
for i in range(n_mbatch):
mb_obs, mb_acs, mb_advs, mb_vtargs, mb_old_ac_logps = map(
lambda x: x[i * mbatch_size : (i+1) * mbatch_size],
[obs, acs, advs, vtargs, old_ac_logps])
if loss == 'clip':
train_info = ppo_clip_update(model, optimizer,
mb_obs, mb_acs, mb_advs, mb_vtargs, mb_old_ac_logps,
vfcoef, entcoef, **update_kwargs)
elif loss == 'klpen':
raise NotImplementedError('PPO KL penalty loss not yet implemented')
else:
raise ValueError('loss must either be "clip" or "klpen"')
if train_info['kl_divergence'] > kl_threshold:
break
return train_info
def ppo_clip_update(model, optimizer, obs, acs, advs, vtargs, old_ac_logps,
vfcoef=0.5, entcoef=0.01, clip_eps=0.2):
pd, vpreds = model.forward(obs)
ac_logps = pd.log_prob(acs).unsqueeze(-1)
entropy = pd.entropy().unsqueeze(-1)
reduce_acd_dims = [i for i in range(1, ac_logps.ndim)]
ac_logps = ac_logps.sum(dim=reduce_acd_dims)
entropy = entropy.sum(dim=reduce_acd_dims).mean()
approx_kl = (old_ac_logps - ac_logps).mean()
ac_logp_frac = th.exp(ac_logps - old_ac_logps)
clipped_ac_logp_frac = th.clamp(ac_logp_frac, 1 - clip_eps, 1 + clip_eps)
policy_loss = th.max(ac_logp_frac * -advs, clipped_ac_logp_frac * -advs).mean()
value_loss = vfcoef * ((vpreds[:, 0] - vtargs) ** 2).mean()
entropy_loss = -entropy * entcoef
loss = policy_loss + value_loss + entropy_loss
optimizer.zero_grad()
loss.backward()
optimizer.step()
train_info_dict = dict(loss_policy=policy_loss,
loss_value=value_loss,
loss_entropy=entropy_loss,
entropy=entropy,
kl_divergence=approx_kl)
return train_info_dict
|
[
"numpy.random.permutation",
"torch.exp",
"torch.clamp",
"torch.max"
] |
[((1868, 1899), 'torch.exp', 'th.exp', (['(ac_logps - old_ac_logps)'], {}), '(ac_logps - old_ac_logps)\n', (1874, 1899), True, 'import torch as th\n'), ((1927, 1977), 'torch.clamp', 'th.clamp', (['ac_logp_frac', '(1 - clip_eps)', '(1 + clip_eps)'], {}), '(ac_logp_frac, 1 - clip_eps, 1 + clip_eps)\n', (1935, 1977), True, 'import torch as th\n'), ((387, 420), 'numpy.random.permutation', 'np.random.permutation', (['batch_size'], {}), '(batch_size)\n', (408, 420), True, 'import numpy as np\n'), ((1997, 2055), 'torch.max', 'th.max', (['(ac_logp_frac * -advs)', '(clipped_ac_logp_frac * -advs)'], {}), '(ac_logp_frac * -advs, clipped_ac_logp_frac * -advs)\n', (2003, 2055), True, 'import torch as th\n')]
|
import os
import time
from collections import Counter
import numpy as np
import tensorflow as tf
import tensorflow_hub as hub
from tensorflow import keras
from tensorflow.python.keras.callbacks import ModelCheckpoint, EarlyStopping, TensorBoard
from sklearn.metrics import f1_score, precision_score, recall_score, accuracy_score
from tqdm import tqdm
from utils_data_text import get_features_from_data, read_class_results
print(tf.__version__)
# sess=tf.Session()
# sess.run(tf.global_variables_initializer())
# sess.run(tf.tables_initializer())
# The provided .npy file thus has shape (1, num_frames, 224, 224, 3) for RGB, corresponding to a batch size of 1
# def load_video_feat():
# path_I3D_features = "../i3d_keras/data_old/results_overlapping/"
# #path_I3D_features = "test_rgb.npy"
# print("loading I3D")
# list_features = []
# for filename in tqdm(os.listdir(path_I3D_features)):
# print(path_I3D_features + filename)
# features = np.load(path_I3D_features + filename)
# list_features.append(features)
# print(features.shape)
# return list_features
def load_video_feat(clip):
filename = clip[:-4] + "_rgb.npy"
path_I3D_features = "../i3d_keras/data_old/results_overlapping/"
# print("loading I3D")
try:
features = np.load(path_I3D_features + filename)
except Exception as e:
print(clip)
print(e)
return np.zeros((1, 64, 224, 224, 3))
# features = np.load("test_rgb.npy")
return features
# def load_video_feat():
# path_I3D_features = "../i3d_keras/data_old/results_overlapping/"
# print("loading I3D")
# dict_clip_feat = {}
# for filename in tqdm(os.listdir(path_I3D_features)):
# if filename.split("_")[0] not in ["1p0", "1p1", "5p0", "5p1"]:
# continue
# try:
# features = np.load(path_I3D_features + filename)
# except Exception as e:
# print(filename)
# print(e)
#
# dict_clip_feat[filename[:-8] + ".mp4"] = features
# return features
def method_tf_actions(train_data, val_data, test_data):
[data_clips_feat_train, data_actions_emb_train, labels_train, data_actions_names_train,
data_clips_names_train], [data_clips_feat_val, data_actions_emb_val, labels_val, data_actions_names_val,
data_clips_names_val], [
data_clips_feat_test, data_actions_emb_test, labels_test, data_actions_names_test, data_clips_names_test] = \
get_features_from_data(train_data, val_data, test_data)
predicted = []
# dict_clip_feat = load_video_feat()
# inputs_frames must be normalized in [0, 1] and of the shape Batch x T x H x W x 3
input_frames = tf.placeholder(tf.float32, shape=(None, None, None, None, 3))
# inputs_words are just a list of sentences (i.e. ['the sky is blue', 'someone cutting an apple'])
input_words = tf.placeholder(tf.string, shape=(None,))
# module = hub.Module("https://tfhub.dev/deepmind/mil-nce/s3d/1")
module = hub.Module("https://tfhub.dev/deepmind/mil-nce/i3d/1")
# module = hub.Module("https://tfhub.dev/deepmind/mil-nce/i3d/1", trainable=True, tags={"train"})
vision_output = module(input_frames, signature='video', as_dict=True)
text_output = module(input_words, signature='text', as_dict=True)
video_embedding = vision_output['video_embedding']
text_embedding = text_output['text_embedding']
# We compute all the pairwise similarity scores between video and text.
similarity_matrix = tf.matmul(text_embedding, video_embedding, transpose_b=True)
sess = tf.InteractiveSession()
sess.run(tf.global_variables_initializer())
sess.run(tf.tables_initializer())
for [action, clip] in tqdm(list(zip(data_actions_names_test, data_clips_names_test))):#[:100]):
# clip_feat_rgb = dict_clip_feat[clip]
clip_feat_rgb = load_video_feat(clip)
result_sim = sess.run([similarity_matrix], feed_dict={input_words: [action],
input_frames: clip_feat_rgb})
predicted.append(result_sim)
# list_actions_per_clip = [action]
# clip_0 = clip
# np.save("data_old/tf_tes_predicted_train.npy", predicted)
np.save("data_old/tf_tes_predicted.npy", predicted)
# np.save("data_old/tf_train_predicted.npy", predicted)
# print("Predicted " + str(Counter(predicted)))
# f1_test = f1_score(labels_test, predicted)
# prec_test = precision_score(labels_test, predicted)
# rec_test = recall_score(labels_test, predicted)
# acc_test = accuracy_score(labels_test, predicted)
# print("precision {0}, recall: {1}, f1: {2}".format(prec_test, rec_test, f1_test))
# print("acc_test: {:0.2f}".format(acc_test))
#
# list_predictions = predicted
# return predicted, list_predictions
return [], []
#
# def run_tf(clip_feat_rgb, list_actions_per_clip):
#
#
# with tf.Session() as sess:
# sess.run(tf.global_variables_initializer())
# sess.run(tf.tables_initializer())
# similarity_matrix_res = sess.run([similarity_matrix], feed_dict={input_words: list_actions_per_clip, input_frames: clip_feat_rgb})
#
# return similarity_matrix_res
def read_test_predicted(train_data, val_data, test_data):
[data_clips_train, data_actions_train, labels_train, data_actions_names_train, data_clips_names_train], [
data_clips_val, data_actions_val,
labels_val,
data_actions_names_val, data_clips_names_val], \
[data_clips_test, data_actions_test, labels_test, data_actions_names_test,
data_clips_names_test] = get_features_from_data(train_data,
val_data,
test_data)
content = np.load("data_old/tf_tes_predicted.npy")
predicted = np.squeeze(content)
normalized_predicted = []
print(predicted)
print(predicted)
# learn the threshold
normalized_threshold = (min(predicted) + max(predicted)) /2
print(min(predicted))
print(max(predicted))
print(normalized_threshold)
for i in predicted:
if i >= normalized_threshold:
normalized_predicted.append(True)
else:
normalized_predicted.append(False)
predicted = normalized_predicted
# for action, clip, label_gt, label_pred in tqdm(
# list(zip(data_actions_names_test, data_clips_names_test, labels_test, predicted))[50:150]):
# print(action + " ; " + clip + " ; " + str(label_gt) + " ; " + str(label_pred))
print("Predicted " + str(Counter(predicted)))
f1_test = f1_score(labels_test, predicted)
prec_test = precision_score(labels_test, predicted)
rec_test = recall_score(labels_test, predicted)
acc_test = accuracy_score(labels_test, predicted)
print("precision {0}, recall: {1}, f1: {2}".format(prec_test, rec_test, f1_test))
print("acc_test: {:0.2f}".format(acc_test))
list_predictions = predicted
return predicted, list_predictions
def main():
read_test_predicted()
# video_rgb = load_video_feat()
# # inputs_frames must be normalized in [0, 1] and of the shape Batch x T x H x W x 3
# input_frames = tf.placeholder(tf.float32, shape=(None, None, None, None, 3))
# # inputs_words are just a list of sentences (i.e. ['the sky is blue', 'someone cutting an apple'])
# input_words = tf.placeholder(tf.string, shape=(None,))
#
# module = hub.Module("https://tfhub.dev/deepmind/mil-nce/s3d/1")
#
# vision_output = module(input_frames, signature='video', as_dict=True)
# text_output = module(input_words, signature='text', as_dict=True)
#
# video_embedding = vision_output['video_embedding']
# text_embedding = text_output['text_embedding']
# # We compute all the pairwise similarity scores between video and text.
# similarity_matrix = tf.matmul(text_embedding, video_embedding, transpose_b=True)
#
# with tf.Session() as sess:
# sess.run(tf.global_variables_initializer())
#
# sess.run(tf.tables_initializer())
#
# print(sess.run([similarity_matrix], feed_dict={input_words: ['the sky is blue'], input_frames: video_rgb}))
if __name__ == "__main__":
main()
|
[
"numpy.load",
"numpy.save",
"utils_data_text.get_features_from_data",
"tensorflow_hub.Module",
"tensorflow.global_variables_initializer",
"sklearn.metrics.accuracy_score",
"numpy.zeros",
"sklearn.metrics.recall_score",
"tensorflow.placeholder",
"tensorflow.matmul",
"sklearn.metrics.f1_score",
"sklearn.metrics.precision_score",
"tensorflow.tables_initializer",
"tensorflow.InteractiveSession",
"collections.Counter",
"numpy.squeeze"
] |
[((2516, 2571), 'utils_data_text.get_features_from_data', 'get_features_from_data', (['train_data', 'val_data', 'test_data'], {}), '(train_data, val_data, test_data)\n', (2538, 2571), False, 'from utils_data_text import get_features_from_data, read_class_results\n'), ((2742, 2803), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '(None, None, None, None, 3)'}), '(tf.float32, shape=(None, None, None, None, 3))\n', (2756, 2803), True, 'import tensorflow as tf\n'), ((2925, 2965), 'tensorflow.placeholder', 'tf.placeholder', (['tf.string'], {'shape': '(None,)'}), '(tf.string, shape=(None,))\n', (2939, 2965), True, 'import tensorflow as tf\n'), ((3050, 3104), 'tensorflow_hub.Module', 'hub.Module', (['"""https://tfhub.dev/deepmind/mil-nce/i3d/1"""'], {}), "('https://tfhub.dev/deepmind/mil-nce/i3d/1')\n", (3060, 3104), True, 'import tensorflow_hub as hub\n'), ((3560, 3620), 'tensorflow.matmul', 'tf.matmul', (['text_embedding', 'video_embedding'], {'transpose_b': '(True)'}), '(text_embedding, video_embedding, transpose_b=True)\n', (3569, 3620), True, 'import tensorflow as tf\n'), ((3633, 3656), 'tensorflow.InteractiveSession', 'tf.InteractiveSession', ([], {}), '()\n', (3654, 3656), True, 'import tensorflow as tf\n'), ((4291, 4342), 'numpy.save', 'np.save', (['"""data_old/tf_tes_predicted.npy"""', 'predicted'], {}), "('data_old/tf_tes_predicted.npy', predicted)\n", (4298, 4342), True, 'import numpy as np\n'), ((5677, 5732), 'utils_data_text.get_features_from_data', 'get_features_from_data', (['train_data', 'val_data', 'test_data'], {}), '(train_data, val_data, test_data)\n', (5699, 5732), False, 'from utils_data_text import get_features_from_data, read_class_results\n'), ((5854, 5894), 'numpy.load', 'np.load', (['"""data_old/tf_tes_predicted.npy"""'], {}), "('data_old/tf_tes_predicted.npy')\n", (5861, 5894), True, 'import numpy as np\n'), ((5911, 5930), 'numpy.squeeze', 'np.squeeze', (['content'], {}), '(content)\n', (5921, 5930), True, 'import numpy as np\n'), ((6699, 6731), 'sklearn.metrics.f1_score', 'f1_score', (['labels_test', 'predicted'], {}), '(labels_test, predicted)\n', (6707, 6731), False, 'from sklearn.metrics import f1_score, precision_score, recall_score, accuracy_score\n'), ((6748, 6787), 'sklearn.metrics.precision_score', 'precision_score', (['labels_test', 'predicted'], {}), '(labels_test, predicted)\n', (6763, 6787), False, 'from sklearn.metrics import f1_score, precision_score, recall_score, accuracy_score\n'), ((6803, 6839), 'sklearn.metrics.recall_score', 'recall_score', (['labels_test', 'predicted'], {}), '(labels_test, predicted)\n', (6815, 6839), False, 'from sklearn.metrics import f1_score, precision_score, recall_score, accuracy_score\n'), ((6855, 6893), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['labels_test', 'predicted'], {}), '(labels_test, predicted)\n', (6869, 6893), False, 'from sklearn.metrics import f1_score, precision_score, recall_score, accuracy_score\n'), ((1310, 1347), 'numpy.load', 'np.load', (['(path_I3D_features + filename)'], {}), '(path_I3D_features + filename)\n', (1317, 1347), True, 'import numpy as np\n'), ((3670, 3703), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (3701, 3703), True, 'import tensorflow as tf\n'), ((3718, 3741), 'tensorflow.tables_initializer', 'tf.tables_initializer', ([], {}), '()\n', (3739, 3741), True, 'import tensorflow as tf\n'), ((1427, 1457), 'numpy.zeros', 'np.zeros', (['(1, 64, 224, 224, 3)'], {}), '((1, 64, 224, 224, 3))\n', (1435, 1457), True, 'import numpy as np\n'), ((6664, 6682), 'collections.Counter', 'Counter', (['predicted'], {}), '(predicted)\n', (6671, 6682), False, 'from collections import Counter\n')]
|
import numpy
#numpy.genfromtxt('arr.txt', dtype=bool)
test_input = """00100
11110
10110
10111
10101
01111
00111
11100
10000
11001
00010
01010"""
with open('input') as f:
input = f.read().rstrip()
def parse_data(input):
return numpy.array([[int(char) for char in list(line)] for line in input.splitlines()])
def bits_to_int(bits):
return int("".join(str(i) for i in bits),2)
def gamma_rate(diagnostic_report):
return bits_to_int((numpy.count_nonzero(diagnostic_report, 0) > numpy.shape(diagnostic_report)[0] / 2).astype(int))
def epsilon_rate(diagnostic_report):
return bits_to_int((numpy.count_nonzero(diagnostic_report, 0) < numpy.shape(diagnostic_report)[0] / 2).astype(int))
def measure_rating(diagnostic_report, index = 0, direction = -1):
def get_digit(a, direction):
if direction == -1:
return 0 if (numpy.sum(a) >= len(a) / 2.0) else 1
else:
return 1 if (numpy.sum(a) >= len(a) / 2.0) else 0
def recursive(diagnostic_report, index):
if numpy.shape(diagnostic_report)[0] == 1:
result = [diagnostic_report[0, index:]]
else:
digit = get_digit(diagnostic_report[:,index], direction)
indices = numpy.argwhere(diagnostic_report[:,index] == digit).flatten()
if index < numpy.shape(diagnostic_report)[1] - 1:
result = numpy.insert(recursive(diagnostic_report[indices, :], index + 1), 0, digit).astype(int)
else:
result = [digit]
return result
result = recursive(diagnostic_report, index)
return bits_to_int(result)
## Part 1
# Test
test_data = parse_data(test_input)
assert bits_to_int([1,0,1,0,1,0]) == 42
assert gamma_rate(test_data) == 22, "Gamma rate should be 22"
assert epsilon_rate(test_data) == 9, "Epsilon rate should be 9"
print("Test Gamma rate is %d"%gamma_rate(test_data))
print("Test Epsilon rate is %d"%epsilon_rate(test_data))
print("Test Part 1 result is %d"%(gamma_rate(test_data) * epsilon_rate(test_data)))
print()
data = parse_data(input)
print("Gamma rate is %d"%gamma_rate(data))
print("Epsilon rate is %d"%epsilon_rate(data))
print("Part 1 result is %d"%(gamma_rate(data) * epsilon_rate(data)))
print()
print()
## Part 2
# test
oxygen = measure_rating(test_data, direction = 1)
assert oxygen == 23
print("Test part 2: oxygen rate is %d"%oxygen)
co2 = measure_rating(test_data, direction = -1)
assert co2 == 10
print("Test part 2: co2 rate is %d"%co2)
print()
oxygen = measure_rating(data, direction = 1)
print("Part 2: oxygen rate is %d"%oxygen)
co2 = measure_rating(data, direction = -1)
print("Part 2: co2 rate is %d"%co2)
print("Part 2 result is %d"%(oxygen * co2))
|
[
"numpy.shape",
"numpy.count_nonzero",
"numpy.sum",
"numpy.argwhere"
] |
[((1028, 1058), 'numpy.shape', 'numpy.shape', (['diagnostic_report'], {}), '(diagnostic_report)\n', (1039, 1058), False, 'import numpy\n'), ((451, 492), 'numpy.count_nonzero', 'numpy.count_nonzero', (['diagnostic_report', '(0)'], {}), '(diagnostic_report, 0)\n', (470, 492), False, 'import numpy\n'), ((609, 650), 'numpy.count_nonzero', 'numpy.count_nonzero', (['diagnostic_report', '(0)'], {}), '(diagnostic_report, 0)\n', (628, 650), False, 'import numpy\n'), ((858, 870), 'numpy.sum', 'numpy.sum', (['a'], {}), '(a)\n', (867, 870), False, 'import numpy\n'), ((934, 946), 'numpy.sum', 'numpy.sum', (['a'], {}), '(a)\n', (943, 946), False, 'import numpy\n'), ((1225, 1277), 'numpy.argwhere', 'numpy.argwhere', (['(diagnostic_report[:, index] == digit)'], {}), '(diagnostic_report[:, index] == digit)\n', (1239, 1277), False, 'import numpy\n'), ((1310, 1340), 'numpy.shape', 'numpy.shape', (['diagnostic_report'], {}), '(diagnostic_report)\n', (1321, 1340), False, 'import numpy\n'), ((495, 525), 'numpy.shape', 'numpy.shape', (['diagnostic_report'], {}), '(diagnostic_report)\n', (506, 525), False, 'import numpy\n'), ((653, 683), 'numpy.shape', 'numpy.shape', (['diagnostic_report'], {}), '(diagnostic_report)\n', (664, 683), False, 'import numpy\n')]
|
import music21 as m21
m21.humdrum.spineParser.flavors['JRP'] = True
import pandas as pd
import numpy as np
import json
import argparse
from fractions import Fraction
from collections import defaultdict
from pathlib import Path
from itertools import zip_longest
from MTCFeatures.MTCFeatureLoader import MTCFeatureLoader
epsilon = 0.0001
# These paths must exist:
# ${mtcroot}/MTC-FS-INST-2.0/metadata
# ${mtcroot}/MTC-LC-1.0/metadata
# ${mtcroot}/MTC-ANN-2.0.1/metadata
# ${mtckrnroot}/MTC-FS-INST-2.0/krn
# ${mtckrnroot}/MTC-LC-1.0/krn
# ${mtckrnroot}/MTC-ANN-2.0.1/krn
# ${mtcjsonroot}/MTC-FS-INST-2.0/json
# ${mtcjsonroot}/MTC-LC-1.0/json
# ${mtcjsonroot}/MTC-ANN-2.0.1/json
# The kernfiles should not contain grace notes
parser = argparse.ArgumentParser(description='Convert MTC .krn to feature sequences')
parser.add_argument(
'-mtcfsinst',
dest='gen_mtcfsinst',
help='Generate sequences for MTC-FS-INST.',
default=False,
action='store_true'
)
parser.add_argument(
'-mtcann',
dest='gen_mtcann',
help='Generate sequences for MTC-ANN.',
default=False,
action='store_true'
)
parser.add_argument(
'-essen',
dest='gen_essen',
help='Generate sequences for Essen collection.',
default=False,
action='store_true'
)
parser.add_argument(
'-mtcroot',
type=str,
help='path to MTC to find metadata',
default='/Users/pvk/data/MTC/'
)
parser.add_argument(
'-mtckrnroot',
type=str,
help='mtcroot for krn files',
default='/Users/pvk/data/MTC/'
)
parser.add_argument(
'-mtcjsonroot',
type=str,
help='mtcroot for json files as generated by krn2json',
default='/Users/pvk/data/MTCjson/'
)
parser.add_argument(
'-essenkrnroot',
type=str,
help='path to essen krn files',
default='/Users/pvk/data/essen/allkrn'
)
parser.add_argument(
'-essenjsonroot',
type=str,
help='path to essen json files as generated by krn2json',
default='/Users/pvk/data/essen/alljson'
)
parser.add_argument(
'-essenroot',
type=str,
help='path to essen data. ${essenroot}/allkrn, ${essenroot}/alljson and ${essenroot}/metadata.csv should exist',
default='/Users/pvk/data/essen'
)
parser.add_argument(
'-mtcanntextfeatspath',
type=str,
help='filename with text features for MTC-ANN',
default='/Users/pvk/git/MTCExtractFeatures/src/mtcann_textfeatures.jsonl'
)
parser.add_argument(
'-mtcfsinsttextfeatspath',
type=str,
help='filename with text features for MTC-FS-INST',
default='/Users/pvk/git/MTCExtractFeatures/src/mtcfsinst_textfeatures.jsonl'
)
parser.add_argument(
'-startat',
type=str,
help='NLBID of the melody to start with. Skips all preceeding ones.',
default=''
)
args = parser.parse_args()
mtcfsroot = Path(args.mtcroot, 'MTC-FS-INST-2.0')
mtcannroot = Path(args.mtcroot, 'MTC-ANN-2.0.1')
mtclcroot = Path(args.mtcroot, 'MTC-LC-1.0')
mtcfskrndir = Path(args.mtckrnroot, 'MTC-FS-INST-2.0','krn')
mtcannkrndir = Path(args.mtckrnroot, 'MTC-ANN-2.0.1','krn')
mtclckrndir = Path(args.mtckrnroot, 'MTC-LC-1.0','krn')
mtcfsjsondir = Path(args.mtcjsonroot, 'MTC-FS-INST-2.0','json')
mtcannjsondir = Path(args.mtcjsonroot, 'MTC-ANN-2.0.1','json')
mtclcjsondir = Path(args.mtcjsonroot, 'MTC-LC-1.0','json')
essenroot = Path(args.essenroot)
essenkrndir = Path(args.essenroot, 'allkrn')
essenjsondir = Path(args.essenroot, 'alljson')
essenmetadatapath = Path(args.essenroot, 'metadata.csv')
mtcfsinsttextfeatspath = Path(args.mtcfsinsttextfeatspath)
mtcanntextfeatspath = Path(args.mtcanntextfeatspath)
#these are indicated as 'vocal' in MTC-FS-INST-2.0 metadata, but are NOT
nlbids_notvocal = [
'NLB179932_01',
'NLB175861_01',
'NLB175902_01',
'NLB142256_01',
'NLB179920_01',
'NLB175873_01',
'NLB175938_01',
'NLB179916_01',
'NLB175945_01',
'NLB175826_01',
'NLB175926_01',
'NLB004881_01',
'NLB004794_01',
'NLB175934_01',
'NLB175834_01',
'NLB179867_01',
'NLB004786_01',
'NLB175849_01',
'NLB004844_01',
'NLB004839_01',
'NLB175795_01',
'NLB004827_01',
'NLB004856_01',
'NLB004848_01',
'NLB004835_01',
'NLB004860_01',
'NLB004872_01',
'NLB190125_01',
'NLB004779_01',
'NLB004911_01',
'NLB004811_01',
'NLB004837_01',
'NLB004854_01',
'NLB140072_02',
'NLB004829_01',
'NLB175797_01',
'NLB004858_01',
'NLB004825_01',
'NLB004846_01',
'NLB123127_01',
'NLB004913_01',
'NLB004813_01',
'NLB004870_01',
'NLB004901_01',
'NLB004862_01',
'NLB004777_01',
'NLB130097_01',
'NLB179922_01',
'NLB004854_02',
'NLB175871_01',
'NLB179930_01',
'NLB175863_01',
'NLB175936_01',
'NLB179918_01',
'NLB004784_01',
'NLB004891_01',
'NLB175928_01',
'NLB175924_01',
'NLB004796_01',
'NLB179914_01',
'NLB179869_01',
'NLB004788_01',
'NLB004805_01',
'NLB004905_01',
'NLB150179_02',
'NLB004878_01',
'NLB004866_01',
'NLB004917_01',
'NLB004817_01',
'NLB004909_01',
'NLB004809_01',
'NLB004874_01',
'NLB004821_01',
'NLB004842_01',
'NLB004833_01',
'NLB175894_01',
'NLB004850_01',
'NLB004887_01',
'NLB004899_01',
'NLB179910_01',
'NLB004780_01',
'NLB179861_01',
'NLB004895_01',
'NLB175932_01',
'NLB175832_01',
'NLB175804_01',
'NLB141973_02',
'NLB179934_01',
'NLB134872_02',
'NLB175875_01',
'NLB179926_01',
'NLB004850_02',
'NLB175853_01',
'NLB179863_01',
'NLB004897_01',
'NLB004782_01',
'NLB175930_01',
'NLB175830_01',
'NLB175941_01',
'NLB009297_01',
'NLB179912_01',
'NLB004885_01',
'NLB004790_01',
'NLB175922_01',
'NLB175877_01',
'NLB179924_01',
'NLB004852_02',
'NLB179936_01',
'NLB179928_01',
'NLB004876_01',
'NLB004915_01',
'NLB004815_01',
'NLB004819_01',
'NLB004864_01',
'NLB179890_01',
'NLB004907_01',
'NLB004852_01',
'NLB004831_01',
'NLB175896_01',
'NLB004840_01',
'NLB004902_01',
'NLB004861_01',
'NLB004810_01',
'NLB004910_01',
'NLB004873_01',
'NLB179887_01',
'NLB004826_01',
'NLB004838_01',
'NLB004834_01',
'NLB004849_01',
'NLB004857_01',
'NLB004880_01',
'NLB179909_01',
'NLB175944_01',
'NLB175939_01',
'NLB179917_01',
'NLB004892_01',
'NLB075947_02',
'NLB175848_01',
'NLB004787_01',
'NLB175935_01',
'NLB175856_01',
'NLB004799_01',
'NLB142453_01',
'NLB142633_02',
'NLB175803_01',
'NLB179933_01',
'NLB175872_01',
'NLB179921_01',
'NLB175854_01',
'NLB179907_01',
'NLB175829_01',
'NLB004785_01',
'NLB004890_01',
'NLB175937_01',
'NLB179919_01',
'NLB179868_01',
'NLB004789_01',
'NLB175846_01',
'NLB179915_01',
'NLB004797_01',
'NLB175858_01',
'NLB004882_01',
'NLB175925_01',
'NLB175825_01',
'NLB175870_01',
'NLB179923_01',
'NLB004871_01',
'NLB179885_01',
'NLB004812_01',
'NLB004912_01',
'NLB004863_01',
'NLB004776_01',
'NLB004900_01',
'NLB179889_01',
'NLB004828_01',
'NLB004855_01',
'NLB004836_01',
'NLB004847_01',
'NLB004824_01',
'NLB179935_01',
'NLB175866_01',
'NLB175905_01',
'NLB114131_01',
'NLB175878_01',
'NLB004851_02',
'NLB175874_01',
'NLB175942_01',
'NLB004793_01',
'NLB175933_01',
'NLB004781_01',
'NLB004894_01',
'NLB179860_01',
'NLB175899_01',
'NLB004843_01',
'NLB004820_01',
'NLB004851_01',
'NLB123757_01',
'NLB133670_01',
'NLB004832_01',
'NLB004879_01',
'NLB004904_01',
'NLB004804_01',
'NLB004875_01',
'NLB126963_02',
'NLB004816_01',
'NLB004916_01',
'NLB175897_01',
'NLB004830_01',
'NLB004853_01',
'NLB004822_01',
'NLB004841_01',
'NLB004869_01',
'NLB004814_01',
'NLB004914_01',
'NLB004877_01',
'NLB004906_01',
'NLB004806_01',
'NLB004865_01',
'NLB004818_01',
'NLB004853_02',
'NLB179925_01',
'NLB175876_01',
'NLB179929_01',
'NLB179937_01',
'NLB141970_02',
'NLB175931_01',
'NLB004783_01',
'NLB175852_01',
'NLB004888_01',
'NLB175923_01',
'NLB179870_01',
'NLB004884_01',
'NLB179913_01'
]
#song has no meter
class NoMeterError(Exception):
def __init__(self, arg):
self.args = arg
def __str__(self):
return repr(self.value)
#parsing failed
class ParseError(Exception):
def __init__(self, arg):
self.args = arg
def __str__(self):
return repr(self.value)
#nlbid not in cache
class CacheError(Exception):
def __init__(self, arg):
self.args = arg
def __str__(self):
return repr(self.value)
#feature vector not of same length
class FeatLenghtError(Exception):
def __init__(self, arg):
self.args = arg
def __str__(self):
return repr(self.value)
# add left padding to partial measure after repeat bar
def padSplittedBars(s):
partIds = [part.id for part in s.parts]
for partId in partIds:
measures = list(s.parts[partId].getElementsByClass('Measure'))
for m in zip(measures,measures[1:]):
if m[0].quarterLength + m[0].paddingLeft + m[1].quarterLength == m[0].barDuration.quarterLength:
m[1].paddingLeft = m[0].quarterLength
return s
def parseMelody(path):
try:
s = m21.converter.parse(path)
except m21.converter.ConverterException:
raise ParseError(path)
#add padding to partial measure caused by repeat bar in middle of measure
s = padSplittedBars(s)
s_noties = s.stripTies()
m = s_noties.flat
removeGrace(m)
return m
# s : flat music21 stream without ties and without grace notes
def removeGrace(s):
ixs = [s.index(n) for n in s.notes if n.quarterLength == 0.0]
for ix in reversed(ixs):
s.pop(ix)
return s
# n: Note
# t: Pitch (tonic)
def pitch2scaledegree(n, t):
tonicshift = t.diatonicNoteNum % 7
return ( n.pitch.diatonicNoteNum - tonicshift ) % 7 + 1
# expect tonic in zeroth (or other very low) octave
def pitch2scaledegreeSpecifer(n, t):
interval = m21.interval.Interval(noteStart=t, noteEnd=n)
return m21.interval.prefixSpecs[interval.specifier]
# Tonic in 0-octave has value 0
def pitch2diatonicPitch(n, t):
tonicshift = t.diatonicNoteNum % 7
if tonicshift == 0:
tonicshift = 7
return ( n.pitch.diatonicNoteNum - tonicshift )
# s : flat music21 stream without ties and without grace notes
def hasmeter(s):
#no time signature at all
if not s.getElementsByClass('TimeSignature'): return False
#maybe it is an Essen song with Mixed meter.
mixedmetercomments = [c.comment for c in s.getElementsByClass('GlobalComment') if c.comment.startswith('Mixed meters:')]
if len(mixedmetercomments) > 0:
return False
return True
def notes2metriccontour(n1, n2):
if n1.beatStrength > n2.beatStrength: return '-'
if n1.beatStrength < n2.beatStrength: return '+'
return '='
# s : flat music21 stream without ties and without grace notes
def m21TObeatstrength(s):
if not hasmeter(s):
raise NoMeterError("No Meter")
return [n.beatStrength for n in s.notes]
# s : flat music21 stream without ties and without grace notes
def m21TOmetriccontour(s):
if not hasmeter(s):
raise NoMeterError("No Meter")
metriccontour = [notes2metriccontour(x[0], x[1]) for x in zip(s.notes,s.notes[1:])]
metriccontour.insert(0,None)
return metriccontour
# s : flat music21 stream without ties and without grace notes
def m21TOscaledegrees(s):
tonic = s.flat.getElementsByClass('Key')[0].tonic
scaledegrees = [pitch2scaledegree(x, tonic) for x in s.notes]
return scaledegrees
# s : flat music21 stream without ties and without grace notes
# output: M: major, m: minor, P: perfect, A: augmented, d: diminished
def m21TOscaleSpecifiers(s):
tonic = s.flat.getElementsByClass('Key')[0].tonic
#put A COPY of the tonic in 0th octave
lowtonic = m21.note.Note(tonic.name)
lowtonic.octave = 0
return [pitch2scaledegreeSpecifer(x, lowtonic) for x in s.notes]
# s : flat music21 stream without ties and without grace notes
# Tonic in 0-octave has value 0
def m21TOdiatonicPitches(s):
tonic = s.flat.getElementsByClass('Key')[0].tonic
scaledegrees = [pitch2diatonicPitch(x, tonic) for x in s.notes]
return scaledegrees
# s : flat music21 stream without ties and without grace notes
def toDiatonicIntervals(s):
return [None] + [n[1].pitch.diatonicNoteNum - n[0].pitch.diatonicNoteNum for n in zip(s.notes, s.notes[1:]) ]
# s : flat music21 stream without ties and without grace notes
def toChromaticIntervals(s):
return [None] + [n[1].pitch.midi - n[0].pitch.midi for n in zip(s.notes, s.notes[1:]) ]
# compute expectancy of the note modelled with pitch proximity (Schellenberg, 1997)
def getPitchProximity(chromaticinterval):
return [None, None] + [abs(c) if abs(c) < 12 else None for c in chromaticinterval[2:] ]
# compute expectancy of the realized note modelled with pitch reversal (Schellenberg, 1997)
def getOnePitchReversal(implicative, realized):
if abs(implicative) == 6 or abs(implicative) > 11 or abs(realized) > 12:
return None
pitchrev_dir = None
if abs(implicative) < 6:
pitchrev_dir = 0
if abs(implicative) > 6 and abs(implicative) < 12:
if realized * implicative <= 0:
pitchrev_dir = 1
else:
pitchrev_dir = -1
pitchrev_ret = 1.5 if ( (abs(realized)>0) and (realized*implicative < 0) and (abs(implicative+realized) <= 2) ) else 0
return pitchrev_dir + pitchrev_ret
# compute expectancies of the note modelled with pitch reversal (Schellenberg, 1997)
def getPitchReversal(chromaticinterval):
return [None, None] + [getOnePitchReversal(i, r) for i,r in zip(chromaticinterval[1:], chromaticinterval[2:])]
#compute boundary strength for the potential boundary FOLLOWING the note. Take durations from input
#duration of the rest following the note (normalized; whole note is 1.0) and maximized (1.0).
def getFranklandGPR2a(restduration):
return [ min(1.0, float(Fraction(r) / 4.0)) if r is not None else None for r in restduration]
def getOneFranklandGPR2b(n1,n2,n3,n4):
return ( 1.0 - (float(n1+n3)/(2.0*n2)) ) if (n2>n3) and (n2>n1) else None
#compute boundary strength for the potential boundary FOLLOWING the note.
#For the rule to apply, n2 must be longer than both n1 and n3. In addition
#n1 through n4 must be notes (not rests)
def getFranklandGPR2b(lengths, restdurations):
quads = zip(lengths,lengths[1:],lengths[2:],lengths[3:])
res = [None] + [getOneFranklandGPR2b(n1, n2, n3, n4) for n1, n2, n3, n4 in quads] + [None, None]
#check conditions (Frankland 2004, p.505): no rests in between, n2>n1 and n2>n3 (in getOneFranklandGPR2b())
#rest_maks: positions with False result in None in res
rest_present = [Fraction(r)>Fraction(0) if r is not None else False for r in restdurations]
triple_rest_present = zip(rest_present,rest_present[1:],rest_present[2:])
rest_mask = [False] + [not (r1 or r2 or r3) for r1, r2, r3 in triple_rest_present] + [False]
#now set all values in res to None if False in mask
res = [res[ix] if rest_mask[ix] else None for ix in range(len(res))]
return res
def getOneFranklandGPR3a(n1, n2, n3, n4):
if n2 != n3 and abs(n2-n3) > abs(n1-n2) and abs(n2-n3) > abs(n3-n4):
return 1.0 - ( float(abs(n1-n2)+abs(n3-n4)) / float(2.0 * abs(n2-n3)) )
else:
return None
#The rule applies only if the transition from n2 to n3 is greater than from n1 to n2
#and from n3 to n4. In addition, the transition from n2 to n3 must be nonzero
def getFranklandGPR3a(midipitch):
quads = zip(midipitch,midipitch[1:],midipitch[2:],midipitch[3:])
return [None] + [getOneFranklandGPR3a(n1, n2, n3, n4) for n1, n2, n3, n4 in quads] + [None, None]
def getOneFranklandGPR3d(n1,n2,n3, n4):
if n1 != n2 or n3 != n4:
return None
if n3 > n1:
return 1.0 - (float(n1)/float(n3))
else:
return 1.0 - (float(n3)/float(n1))
#... to apply, the length of n1 must equal n2, and the length of n3 must euqal n4
def getFranklandGPR3d(lengths):
quads = zip(lengths,lengths[1:],lengths[2:],lengths[3:])
return [None] + [getOneFranklandGPR3d(n1, n2, n3, n4) for n1, n2, n3, n4 in quads] + [None, None]
#condition checking in getOneFranklandGRP3d()
#For LBDM parameters:
#Take interval AFTER note
#r1 is degree of change of interval AFTER the note
#compute boundary strength of interval FOLLOWING note
#note: n0 n1 n2 n3 n4 n5
# | \ | \ | \ | \ | \
#interval i0 i1 i2 i3 i4 i5
# | \ | \ | \ | \ | \ |
#change None r1 r2 r3 r4 r5
# | / | / | / | / | /
#strength None s1 s2 s3 s4 s5
#
# s1 is computed from r1 and r2
# s2 is computed from r2 and r3
# etc.
def getOneDegreeChange(x1, x2, const_add=0.0):
res = None
x1 += const_add
x2 += const_add
if x1 == x2: return 0.0
if (x1+x2) != 0 and x1 >= 0 and x2 >= 0:
res = float(abs(x1-x2)) / float (x1 + x2)
return res
#Cambouropoulos 2001
def getDegreeChangeLBDMpitch(chromaticinterval, threshold=12, const_add=1):
# we need absolute values
# and thr_int <= threshold
# and shift such that chormaticinterval is interval FOLLOWING note
thr_int = [min(threshold,abs(i)) for i in chromaticinterval[1:]] + [None]
pairs = zip(thr_int[:-1],thr_int[1:-1])
rpitch = [None] + [getOneDegreeChange(x1, x2, const_add=const_add) for x1, x2 in pairs] + [None]
return rpitch
#Cambouropoulos 2001
#default threshold: whole note (4.0 quarterLength)
def getDegreeChangeLBDMioi(ioi, threshold=4.0):
#We need IOI AFTER the note, and we need maximize the value
thr_ioi = [min(threshold,i) for i in ioi[:-1]] + [None]
pairs = zip(thr_ioi[:-1],thr_ioi[1:-1])
rioi = [None] + [getOneDegreeChange(x1, x2) for x1, x2 in pairs ] + [None]
return rioi
#Cambouropoulos 2001
def getDegreeChangeLBDMrest(restduration_frac, threshold=4.0):
#need rest AFTER note, and apply threshold
thr_rd = [min(threshold, float(Fraction(r))) if r is not None else 0.0 for r in restduration_frac[:-1]] + [None]
pairs = zip(thr_rd[:-1], thr_rd[1:-1])
rrest = [None] + [getOneDegreeChange(x1, x2) for x1, x2 in pairs] + [None]
return rrest
#Boundary strength AFTER the note
def getBoundaryStrength(rs, intervals):
#print(list(zip(rs, intervals)))
pairs = zip(rs[1:-1], rs[2:-1], intervals[1:])
strength = [ c * (r1 + r2) for r1, r2, c in pairs]
#very shor melodies:
if len(strength) == 0:
return [None, None, None]
#normalize
maxspitch = max(strength)
if maxspitch > 0:
strength = [s / maxspitch for s in strength]
#Add first and last
strength = [None] + strength + [None, None]
return strength
def getBoundaryStrengthPitch(rpitch, chromaticinterval, threshold=12):
# we need absolute values
# and thr_int <= threshold
# and shift such that chormaticinterval is interval FOLLOWING note
thr_int = [min(threshold,abs(i)) for i in chromaticinterval[1:]] + [None]
return getBoundaryStrength(rpitch, thr_int)
def getBoundaryStrengthIOI(rioi, ioi, threshold=4.0):
#We need IOI AFTER the note, and we need maximize the value
thr_ioi = [min(threshold,i) for i in ioi[:-1]] + [None]
return getBoundaryStrength(rioi, thr_ioi)
def getBoundaryStrengthRest(rrest, restduration_frac, threshold=4.0):
#need rest AFTER note, and apply threshold
thr_rd = [min(threshold, float(Fraction(r))) if r is not None else 0.0 for r in restduration_frac[:-1]] + [None]
return getBoundaryStrength(rrest, thr_rd)
#Cambouropoulos 2001
#Gives strength fot boundary AFTER the note
def getLocalBoundaryStrength(spitch, sioi, srest):
triplets = zip(spitch[1:-2], sioi[1:-2], srest[1:-2]) #remove None values at begin and end
strength = [0.25*p + 0.5*i + 0.25*r for p, i, r in triplets]
strength = [None] + strength + [None, None]
return strength
# s : flat music21 stream without ties and without grace notes
def m21TOPitches(s):
return [n.pitch.nameWithOctave for n in s.notes]
# s : flat music21 stream without ties and without grace notes
def m21TOMidiPitch(s):
return [n.pitch.midi for n in s.notes]
# s : flat music21 stream without ties and without grace notes
def m21TODuration(s):
return [float(n.duration.quarterLength) for n in s.notes]
# s : flat music21 stream without ties and without grace notes
def m21TODuration_fullname(s):
return [n.duration.fullName for n in s.notes]
# s : flat music21 stream without ties and without grace notes
def m21TODuration_frac(s):
return [str(Fraction(n.duration.quarterLength)) for n in s.notes]
def getDurationcontour(duration_frac):
return [None] + ['-' if Fraction(d2)<Fraction(d1) else '+' if Fraction(d2)>Fraction(d1) else '=' for d1, d2 in zip(duration_frac,duration_frac[1:])]
# s : flat music21 stream without ties and without grace notes
def m21TONextIsRest(s):
notesandrests = list(s.notesAndRests)
nextisrest = [ nextnote.isRest for note, nextnote in zip(notesandrests, notesandrests[1:]) if note.isNote]
if notesandrests[-1].isNote:
nextisrest.append(None) #final note
return nextisrest
#Duration of the rest(s) FOLLOWING the note
def m21TORestDuration_frac(s):
restdurations = []
notesandrests = list(s.notesAndRests)
rest_duration = Fraction(0)
#this computes length of rests PRECEEDING the note
for event in notesandrests:
if event.isRest:
rest_duration += Fraction(event.duration.quarterLength)
if event.isNote:
if rest_duration == 0:
restdurations.append(None)
else:
restdurations.append(str(rest_duration))
rest_duration = Fraction(0)
#shift list and add last
if notesandrests[-1].isNote:
restdurations = restdurations[1:] + [None]
else:
restdurations = restdurations[1:] + [str(rest_duration)]
return restdurations
# s : flat music21 stream without ties and without grace notes
def m21TOTimeSignature(s):
if not hasmeter(s):
raise NoMeterError("No Meter")
return [n.getContextByClass('TimeSignature').ratioString for n in s.notes]
def m21TOKey(s):
keys = [(k.tonic.name, k.mode) for k in [n.getContextByClass('Key') for n in s.notes]]
return list(zip(*keys))
# "4" -> ('4', '0')
# "3 1/3" -> ('3', '1/3')
def beatStrTOtuple(bstr):
bstr_splitted = bstr.split(' ')
if len(bstr_splitted) == 1:
bstr_splitted.append('0')
return bstr_splitted[0], bstr_splitted[1]
# s : flat music21 stream without ties and without grace notes
def m21TOBeat_str(s):
if not hasmeter(s):
raise NoMeterError("No Meter")
beats = []
beat_fractions = []
for n in s.notes:
try:
b, bfr = beatStrTOtuple(n.beatStr)
except m21.base.Music21ObjectException: #no time signature
b, bfr = '0', '0'
beats.append(b)
beat_fractions.append(bfr)
return beats, beat_fractions
# s : flat music21 stream without ties and without grace notes
def m21TOBeat_float(s):
if not hasmeter(s):
raise NoMeterError("No Meter")
beats = []
for n in s.notes:
try:
beat_float = float(n.beat)
except m21.base.Music21ObjectException: #no time signature
beat_float = 0.0
beats.append(beat_float)
return beats
# s : flat music21 stream without ties and without grace notes, and with left padding for partial measures
# caveat: upbeat before meter change is interpreted in context of old meter.
# origin is first downbeat in each phrase
def m21TOBeatInSongANDPhrase(s, phrasepos):
if not hasmeter(s):
raise NoMeterError("No Meter")
phrasestart_ixs = [ix+1 for ix, pp in enumerate(zip(phrasepos,phrasepos[1:])) if pp[1] < pp[0] ]
#print(phrasestart_ixs)
startbeat = Fraction(s.notesAndRests[0].beat)
if startbeat != Fraction(1): #upbeat
startbeat = Fraction(-1 * s.notesAndRests[0].getContextByClass('TimeSignature').beatCount) + startbeat
startbeat = startbeat - Fraction(1) #shift origin to first first (no typo) beat in measure
#print('startbeat', startbeat)
#beatfraction: length of the note with length of the beat as unit
beatinsong, beatinphrase, beatfraction = [], [], []
n_first = s.notesAndRests[0]
if n_first.isNote:
beatinsong.append(startbeat)
beatinphrase.append(startbeat)
duration_beatfraction = Fraction(n_first.duration.quarterLength) / Fraction(n_first.beatDuration.quarterLength)
beatfraction.append(duration_beatfraction) # add first note here, use nextnote in loop
cumsum_beat_song = startbeat
cumsum_beat_phrase = startbeat
note_ix = 0
notesandrests = list(s.notesAndRests)
for n, nextnote in zip(notesandrests, notesandrests[1:]):
#print("--------------")
#print(n)
duration_beatfraction = Fraction(n.duration.quarterLength) / Fraction(n.beatDuration.quarterLength)
cumsum_beat_song += duration_beatfraction
cumsum_beat_phrase += duration_beatfraction
#print(cumsum_beat_song)
if n.isNote:
if note_ix in phrasestart_ixs:
cumsum_beat_phrase = Fraction(n.beat)
#print('beat ', cumsum_beat_phrase)
if cumsum_beat_phrase != Fraction(1): #upbeat
cumsum_beat_phrase = Fraction(-1 * n.getContextByClass('TimeSignature').beatCount) + cumsum_beat_phrase
cumsum_beat_phrase = cumsum_beat_phrase - Fraction(1)
#print(note_ix, n, cumsum_beat_phrase)
beatinphrase[-1] = cumsum_beat_phrase
cumsum_beat_phrase += duration_beatfraction
#print(f'{n}, beat: {Fraction(n.beat)}, fraction: {duration_beatfraction}')
#print("note: ", cumsum_beat_song)
note_ix += 1
if nextnote.isNote:
beatinphrase.append(cumsum_beat_phrase)
beatinsong.append(cumsum_beat_song)
duration_beatfraction = Fraction(nextnote.duration.quarterLength) / Fraction(nextnote.beatDuration.quarterLength)
beatfraction.append(duration_beatfraction)
beatinsong = [str(f) for f in beatinsong] #string representation to make it JSON serializable
beatinphrase = [str(f) for f in beatinphrase] #string representation to make it JSON serializable
beatfraction = [str(f) for f in beatfraction] #string representation to make it JSON serializable
return beatinsong, beatinphrase, beatfraction
#origin is onset of last! beat in each phrase
#TODO: what if note on last beat is tied with previous? Syncope.
def getBeatinphrase_end(beatinphrase, phrase_ix, beat):
#find offset per phrase
beatinphrase_end = []
origin = defaultdict(lambda: 0.0)
for ix in range(len(beatinphrase)):
if abs(beat[ix] - 1.0) < epsilon:
origin[phrase_ix[ix]] = Fraction(beatinphrase[ix])
for ix in range(len(beatinphrase)):
beatinphrase_end.append( Fraction(beatinphrase[ix]) - Fraction(origin[phrase_ix[ix]]) )
return [str(f) for f in beatinphrase_end]
def value2contour(ima1, ima2):
if ima1 > ima2: return '-'
if ima1 < ima2: return '+'
return '='
def getFromJson(nlbid, path, feature, totype=int):
with open( path+'/'+nlbid+'.json', 'r') as f:
song = json.load(f)
featvals = [totype(x[feature]) for x in song[nlbid]['symbols']]
return featvals
def getIMA(nlbid, path):
return getFromJson(nlbid, path, 'ima', float)
def getPhrasePos(nlbid, path):
return getFromJson(nlbid, path, 'phrasepos', float)
def getSongPos(onsettick):
onsets = np.array(onsettick)
return list(onsets / onsets[-1])
def getPhraseIx(phrasepos):
current = 0
phr_ix = []
for pp in zip(phrasepos,phrasepos[1:]):
if pp[1] < pp[0]:
current += 1
phr_ix.append(current)
return [0]+phr_ix
def getPhraseEnd(phrasepos):
return [x[1]<x[0] for x in zip(phrasepos, phrasepos[1:])] + [True]
def getPitch40(nlbid, path):
return getFromJson(nlbid, path, 'pitch40', int)
def getContour3(midipitch1, midipitch2):
if midipitch1 > midipitch2 : return '-'
if midipitch1 < midipitch2 : return '+'
return '='
def getContour5(midipitch1, midipitch2, thresh):
diff = midipitch2 - midipitch1
if diff >= thresh : return '++'
elif diff > 0 : return '+'
elif diff == 0 : return '='
elif diff <= -thresh : return '--'
elif diff < 0 : return '-'
def midipitch2contour3(mp, undef=None):
return [undef] + [getContour3(p[0], p[1]) for p in zip(mp,mp[1:])]
def midipitch2contour5(mp, thresh=3, undef=None):
return [undef] + [getContour5(p[0], p[1], thresh) for p in zip(mp,mp[1:])]
def getIOR_frac(ioi_frac):
return [None] + [str(Fraction(ioi2)/Fraction(ioi1)) if ioi1 is not None and ioi2 is not None else None for ioi1, ioi2 in zip(ioi_frac,ioi_frac[1:])]
def getIOR(ior_frac):
return [float(Fraction(i)) if i is not None else None for i in ior_frac]
#IOI in quarterLength
#last note: take duration
def getIOI(ioi_frac):
return [float(Fraction(i)) if i is not None else None for i in ioi_frac]
#last should be none
def getIOI_frac(duration_frac, restduration_frac):
res = [str(Fraction(d)+Fraction(r)) if r is not None else str(Fraction(d)) for d, r, in zip(duration_frac[:-1], restduration_frac[:-1])]
#check last item. If no rest follows, we cannot compute IOI
if restduration_frac[-1] is not None:
res = res + [ str( Fraction(duration_frac[-1])+Fraction(restduration_frac[-1]) ) ]
else:
res = res + [None]
return res
def getOnsetTick(nlbid, path):
return getFromJson(nlbid, path, 'onset', int)
def getIMAcontour(ima):
imacontour = [value2contour(ima[0], ima[1]) for ima in zip(ima,ima[1:])]
imacontour.insert(0,None)
return imacontour
#returns:
#- lyrics
#- noncontentword
#- wordend
#- phoneme
#- rhymes
#- rhymescontentwords
#- wordstress
#- melismastate
class GetTextFeatures():
def __init__(self):
self.seqs = {}
def addSeqsFromFile(self, filename):
_seqs = MTCFeatureLoader(filename).sequences()
#convert to dict
_seqs = {seq['id']: seq for seq in _seqs}
#add to cache
self.seqs[filename] = _seqs
def __call__(self, nlbid, filename):
if not filename in self.seqs.keys():
self.addSeqsFromFile(filename)
if not nlbid in self.seqs[filename].keys():
raise CacheError(nlbid)
return (
self.seqs[filename][nlbid]['features']['lyrics'],
self.seqs[filename][nlbid]['features']['noncontentword'],
self.seqs[filename][nlbid]['features']['wordend'],
self.seqs[filename][nlbid]['features']['phoneme'],
self.seqs[filename][nlbid]['features']['rhymes'],
self.seqs[filename][nlbid]['features']['rhymescontentwords'],
self.seqs[filename][nlbid]['features']['wordstress'],
self.seqs[filename][nlbid]['features']['melismastate']
)
getTextFeatures = GetTextFeatures()
#iterator
def getSequences(
id_list,
krndir,
jsondir, #dir with .json file as generated by krn2json
song_metadata,
source_metadata,
textFeatureFile=None,
fieldmap={'TuneFamily':'TuneFamily', 'TuneFamily_full' : 'TuneFamily'},
startat=None,
):
seen=False
for nlbid in id_list:
if startat:
if nlbid==startat:
seen=True
if not seen:
continue
print(nlbid)
try:
s = parseMelody(str(Path(krndir,nlbid+'.krn')))
except ParseError:
print(nlbid, "does not exist")
continue
jsondir = str(jsondir)
sd = m21TOscaledegrees(s)
sdspec = m21TOscaleSpecifiers(s)
diatonicPitches = m21TOdiatonicPitches(s)
diatonicinterval = toDiatonicIntervals(s)
chromaticinterval = toChromaticIntervals(s)
ima = getIMA(nlbid, jsondir)
ic = getIMAcontour(ima)
pitch = m21TOPitches(s)
pitch40 = getPitch40(nlbid, jsondir)
midipitch = m21TOMidiPitch(s)
pitchproximity = getPitchProximity(chromaticinterval)
pitchreversal = getPitchReversal(chromaticinterval)
nextisrest = m21TONextIsRest(s)
restduration_frac = m21TORestDuration_frac(s)
tonic, mode = m21TOKey(s)
contour3 = midipitch2contour3(midipitch)
contour5 = midipitch2contour5(midipitch, thresh=3)
duration = m21TODuration(s)
duration_fullname = m21TODuration_fullname(s)
duration_frac = m21TODuration_frac(s)
durationcontour = getDurationcontour(duration_frac)
onsettick = getOnsetTick(nlbid, jsondir)
phrasepos = getPhrasePos(nlbid, jsondir)
phrase_end = getPhraseEnd(phrasepos)
phrase_ix = getPhraseIx(phrasepos)
ioi_frac = getIOI_frac(duration_frac, restduration_frac)
ioi = getIOI(ioi_frac)
ior_frac = getIOR_frac(ioi_frac)
ior = getIOR(ior_frac)
songpos = getSongPos(onsettick)
gpr2a_Frankland = getFranklandGPR2a(restduration_frac)
gpr2b_Frankland = getFranklandGPR2b(duration, restduration_frac) #or use IOI and no rest check!!!
gpr3a_Frankland = getFranklandGPR3a(midipitch)
gpr3d_Frankland = getFranklandGPR3d(ioi)
gpr_Frankland_sum = [sum(filter(None, x)) for x in zip(gpr2a_Frankland, gpr2b_Frankland, gpr3a_Frankland, gpr3d_Frankland)]
lbdm_rpitch = getDegreeChangeLBDMpitch(chromaticinterval)
lbdm_spitch = getBoundaryStrengthPitch(lbdm_rpitch, chromaticinterval)
lbdm_rioi = getDegreeChangeLBDMioi(ioi)
lbdm_sioi = getBoundaryStrengthIOI(lbdm_rioi, ioi)
lbdm_rrest = getDegreeChangeLBDMrest(restduration_frac)
lbdm_srest = getBoundaryStrengthRest(lbdm_rrest, restduration_frac)
lbdm_boundarystrength = getLocalBoundaryStrength(lbdm_spitch, lbdm_sioi, lbdm_srest)
if song_metadata.loc[nlbid,'source_id']:
sorting_year = source_metadata.loc[song_metadata.loc[nlbid,'source_id'],'sorting_year']
else:
sorting_year = ''
if sorting_year == '':
sorting_year = "-1" #UGLY
sorting_year = int(sorting_year)
if 'ann_bgcorpus' in song_metadata.columns:
ann_bgcorpus = bool(song_metadata.loc[nlbid,'ann_bgcorpus'])
else:
ann_bgcorpus = None
if 'origin' in song_metadata.columns:
origin = song_metadata.loc[nlbid,'origin']
else:
origin = ''
try:
#pass
timesignature = m21TOTimeSignature(s)
beat_str, beat_fraction_str = m21TOBeat_str(s)
beat_float = m21TOBeat_float(s)
mc = m21TOmetriccontour(s)
beatstrength = m21TObeatstrength(s)
beatinsong, beatinphrase, beatfraction = m21TOBeatInSongANDPhrase(s, phrasepos)
beatinphrase_end = getBeatinphrase_end(beatinphrase, phrase_ix, beat_float)
except NoMeterError:
print(nlbid, "has no time signature")
timesignature = [None]*len(sd)
beat_str, beat_fraction_str = [None]*len(sd) , [None]*len(sd)
beat_float = [None]*len(sd)
mc = [None]*len(sd)
beatstrength = [None]*len(sd)
beatinsong, beatinphrase, beatfraction = [None]*len(sd), [None]*len(sd), [None]*len(sd)
beatinphrase_end = [None]*len(sd)
seq = {'id':nlbid, 'tunefamily': str(song_metadata.loc[nlbid, fieldmap['tunefamily']]),
'year' : sorting_year,
'tunefamily_full': str(song_metadata.loc[nlbid, fieldmap['tunefamily_full']]),
'type' : str(song_metadata.loc[nlbid, 'type']),
'freemeter' : not hasmeter(s),
'origin' : origin,
'features': { 'scaledegree': sd,
'scaledegreespecifier' : sdspec,
'tonic': tonic,
'mode': mode,
'metriccontour':mc,
'imaweight':ima,
'pitch40': pitch40,
'midipitch': midipitch,
'diatonicpitch' : diatonicPitches,
'diatonicinterval': diatonicinterval,
'chromaticinterval': chromaticinterval,
'pitchproximity': pitchproximity,
'pitchreversal': pitchreversal,
'nextisrest': nextisrest,
'restduration_frac': restduration_frac,
'duration': duration,
'duration_frac': duration_frac,
'duration_fullname': duration_fullname,
'durationcontour': durationcontour,
'onsettick': onsettick,
'beatfraction': beatfraction,
'phrasepos': phrasepos,
'phrase_ix': phrase_ix,
'phrase_end': phrase_end,
'songpos': songpos,
'beatinsong': beatinsong,
'beatinphrase': beatinphrase,
'beatinphrase_end': beatinphrase_end,
'IOI_frac': ioi_frac,
'IOI': ioi,
'IOR_frac': ior_frac,
'IOR': ior,
'imacontour': ic,
'pitch': pitch,
'contour3' : contour3,
'contour5' : contour5,
'beatstrength': beatstrength,
'beat_str': beat_str,
'beat_fraction_str': beat_fraction_str,
'beat': beat_float,
'timesignature': timesignature,
'gpr2a_Frankland': gpr2a_Frankland,
'gpr2b_Frankland': gpr2b_Frankland,
'gpr3a_Frankland': gpr3a_Frankland,
'gpr3d_Frankland': gpr3d_Frankland,
'gpr_Frankland_sum': gpr_Frankland_sum,
'lbdm_spitch': lbdm_spitch,
'lbdm_sioi': lbdm_sioi,
'lbdm_srest': lbdm_srest,
'lbdm_rpitch': lbdm_rpitch,
'lbdm_rioi': lbdm_rioi,
'lbdm_rrest': lbdm_rrest,
'lbdm_boundarystrength': lbdm_boundarystrength
}}
if textFeatureFile and (nlbid not in nlbids_notvocal):
try:
lyrics, noncontentword, wordend, phoneme, rhymes, rhymescontentwords, wordstress, melismastate = \
getTextFeatures(nlbid, textFeatureFile)
seq['features']['lyrics'] = lyrics
seq['features']['noncontentword'] = noncontentword
seq['features']['wordend'] = wordend
seq['features']['phoneme'] = phoneme
seq['features']['rhymes'] = rhymes
seq['features']['rhymescontentwords'] = rhymescontentwords
seq['features']['wordstress'] = wordstress
seq['features']['melismastate'] = melismastate
except CacheError:
pass
#print(nlbid, 'has no lyrics.')
if ann_bgcorpus is not None:
seq['ann_bgcorpus'] = ann_bgcorpus
#check lengths
reflength = len(seq['features']['scaledegree'])
for feat in seq['features'].keys():
if len(seq['features'][feat]) != reflength:
print(f'Error: {nlbid}: length of {feat} differs.')
print(f'Difference: {len(seq["features"][feat])-reflength}')
raise FeatLenghtError(nlbid)
yield seq
def getANNBackgroundCorpusIndices(fsinst_song_metadata):
ann_song_metadata = pd.read_csv(
str(Path(mtcannroot,'metadata/MTC-ANN-songs.csv')),
na_filter=False,
index_col=0,
header=None,
encoding='utf8',
names=[
"songid",
"NLB_record_number",
"source_id",
"serial_number",
"page",
"singer_id_s",
"date_of_recording",
"place_of_recording",
"latitude",
"longitude",
"title",
"firstline",
"strophe_number"
]
)
#retrieve tf ids of mtc-ann tune families in mtc-fs-inst
tfids = set(fsinst_song_metadata.loc[ann_song_metadata.index,'tunefamily_id'])
tfids.remove('')
tfids = {tf.split('_')[0] for tf in tfids}
alltfids = set(fsinst_song_metadata['tunefamily_id'])
alltfids.remove('')
sel_tfids = {tfid for tfid in alltfids if tfid.split('_')[0] in tfids}
# now sel_tfids contains all tunefamily_ids of tune families related to the tune families in mtc-ann
#select songs not in tfs related to mtc-ann
bg_corpus_mask = ~fsinst_song_metadata['tunefamily_id'].isin(list(sel_tfids))
bg_corpus = fsinst_song_metadata[bg_corpus_mask]
#remove songs without tune family label
bg_corpus = bg_corpus.loc[bg_corpus.tunefamily_id != '']
# now bg_corpus contains all songs unrelated to mtc-ann's tune families
return bg_corpus.index
def ann2seqs(startat=None):
ann_tf_labels = pd.read_csv(
str(Path(mtcannroot,'metadata/MTC-ANN-tune-family-labels.csv')),
na_filter=False,
index_col=0,
header=None,
encoding='utf8',
names=['ID','TuneFamily']
)
ann_song_metadata = pd.read_csv(
str(Path(mtcannroot,'metadata/MTC-ANN-songs.csv')),
na_filter=False,
index_col=0,
header=None,
encoding='utf8',
names=[
"songid",
"NLB_record_number",
"source_id",
"serial_number",
"page",
"singer_id_s",
"date_of_recording",
"place_of_recording",
"latitude",
"longitude",
"title",
"firstline",
"strophe_number"
]
)
#add tune family labels to song_metadata
ann_full_metadata = pd.concat([ann_tf_labels, ann_song_metadata], axis=1, sort=False)
#add type ('vocal' for all songs)
ann_full_metadata['type'] = 'vocal'
ann_source_metadata = pd.read_csv(
str(Path(mtcannroot,'metadata/MTC-ANN-sources.csv')),
na_filter=False,
index_col=0,
header=None,
encoding='utf8',
names=[
"source_id",
"title",
"author",
"place_publisher",
"dating",
"sorting_year",
"type",
"copy_used",
"scan_url"]
)
print(mtcannkrndir)
for seq in getSequences(
ann_song_metadata.index,
krndir=mtcannkrndir,
jsondir=mtcannjsondir,
song_metadata=ann_full_metadata,
source_metadata=ann_source_metadata,
textFeatureFile=str(mtcanntextfeatspath),
fieldmap = {'tunefamily':'TuneFamily', 'tunefamily_full' : 'TuneFamily'},
startat=startat
):
yield(seq)
#def lc2seqs():
# tf_labels = pd.read_csv(mtclcroot+'metadata/MTC-LC-labels.txt', sep='\t', na_filter=False, index_col=0, header=None, encoding='utf8', names=['ID','TuneFamily'])
# for seq in getSequences(tf_labels.index, krndir=mtclckrndir, jsondir=mtclcjsondir, tf_labels=tf_labels):
# yield(seq)
#if noann, remove all songs related to MTC-ANN, and remove all songs without tune family label
def fsinst2seqs(startat=None):
fsinst_song_metadata = pd.read_csv(
str(Path(mtcfsroot,'metadata/MTC-FS-INST-2.0.csv')),
na_filter=False,
index_col=0,
header=None,
encoding='utf8',
names=[
"filename",
"songid",
"source_id",
"serial_number",
"page",
"singer_id_s",
"date_of_recording",
"place_of_recording",
"latitude",
"longitude",
"textfamily_id",
"title",
"firstline",
"tunefamily_id",
"tunefamily",
"type",
"voice_stanza_number",
"voice_stanza",
"image_filename_s",
"audio_filename",
"variation",
"confidence",
"comment",
"MTC_title",
"author"
]
)
fsinst_source_metadata = pd.read_csv(
str(Path(mtcfsroot,'metadata/MTC-FS-INST-2.0-sources.csv')),
na_filter=False,
index_col=0,
header=None,
encoding='utf8',
names=[
"source_id",
"title",
"author",
"place_publisher",
"dating",
"sorting_year",
"type",
"copy_used",
"scan_url"
]
)
#figure out which songs are not related to MTC-ANN
#and add to song metadata
ids_ann_bgcorpus = getANNBackgroundCorpusIndices(fsinst_song_metadata)
fsinst_song_metadata['ann_bgcorpus'] = False
fsinst_song_metadata.loc[ids_ann_bgcorpus,'ann_bgcorpus'] = True
for seq in getSequences(
fsinst_song_metadata.index,
krndir=mtcfskrndir,
jsondir=mtcfsjsondir,
song_metadata=fsinst_song_metadata,
source_metadata=fsinst_source_metadata,
textFeatureFile=str(mtcfsinsttextfeatspath),
fieldmap = {'tunefamily':'tunefamily_id', 'tunefamily_full' : 'tunefamily'},
startat=startat
):
yield(seq)
def essen2seqs(startat=None):
essen_song_metadata = pd.read_csv(
str(essenmetadatapath),
na_filter=False,
index_col=0,
header=0,
encoding='utf8'
)
essen_song_metadata['tunefamily'] = ''
essen_song_metadata['type'] = 'vocal'
essen_song_metadata['source_id'] = ''
for seq in getSequences(
essen_song_metadata.index,
krndir=essenkrndir,
jsondir=essenjsondir,
song_metadata=essen_song_metadata,
source_metadata=None,
fieldmap = {'tunefamily':'tunefamily', 'tunefamily_full' : 'tunefamily'},
startat = startat
):
yield(seq)
def main():
# MTC-LC-1.0 does not have a key tandem in the *kern files. Therefore not possible to compute scale degrees.
#lc_seqs = lc2seqs()
#with open('mtclc_sequences.json', 'w') as outfile:
# json.dump(lc_seqs, outfile)
if args.gen_mtcann:
with open(f'mtcann_sequences{"_from"+args.startat if args.startat else ""}.jsonl', 'w') as outfile:
for seq in ann2seqs(startat=args.startat):
outfile.write(json.dumps(seq)+'\n')
if args.gen_mtcfsinst:
with open(f'mtcfsinst_sequences{"_from"+args.startat if args.startat else ""}.jsonl', 'w') as outfile:
for seq in fsinst2seqs(startat=args.startat):
outfile.write(json.dumps(seq)+'\n')
if args.gen_essen:
with open(f'essen_sequences{"_from"+args.startat if args.startat else ""}.jsonl', 'w') as outfile:
for seq in essen2seqs(startat=args.startat):
outfile.write(json.dumps(seq)+'\n')
if __name__== "__main__":
main()
|
[
"json.load",
"argparse.ArgumentParser",
"pandas.concat",
"MTCFeatures.MTCFeatureLoader.MTCFeatureLoader",
"json.dumps",
"collections.defaultdict",
"music21.interval.Interval",
"pathlib.Path",
"numpy.array",
"music21.converter.parse",
"fractions.Fraction",
"music21.note.Note"
] |
[((739, 815), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Convert MTC .krn to feature sequences"""'}), "(description='Convert MTC .krn to feature sequences')\n", (762, 815), False, 'import argparse\n'), ((2781, 2818), 'pathlib.Path', 'Path', (['args.mtcroot', '"""MTC-FS-INST-2.0"""'], {}), "(args.mtcroot, 'MTC-FS-INST-2.0')\n", (2785, 2818), False, 'from pathlib import Path\n'), ((2832, 2867), 'pathlib.Path', 'Path', (['args.mtcroot', '"""MTC-ANN-2.0.1"""'], {}), "(args.mtcroot, 'MTC-ANN-2.0.1')\n", (2836, 2867), False, 'from pathlib import Path\n'), ((2880, 2912), 'pathlib.Path', 'Path', (['args.mtcroot', '"""MTC-LC-1.0"""'], {}), "(args.mtcroot, 'MTC-LC-1.0')\n", (2884, 2912), False, 'from pathlib import Path\n'), ((2928, 2975), 'pathlib.Path', 'Path', (['args.mtckrnroot', '"""MTC-FS-INST-2.0"""', '"""krn"""'], {}), "(args.mtckrnroot, 'MTC-FS-INST-2.0', 'krn')\n", (2932, 2975), False, 'from pathlib import Path\n'), ((2990, 3035), 'pathlib.Path', 'Path', (['args.mtckrnroot', '"""MTC-ANN-2.0.1"""', '"""krn"""'], {}), "(args.mtckrnroot, 'MTC-ANN-2.0.1', 'krn')\n", (2994, 3035), False, 'from pathlib import Path\n'), ((3049, 3091), 'pathlib.Path', 'Path', (['args.mtckrnroot', '"""MTC-LC-1.0"""', '"""krn"""'], {}), "(args.mtckrnroot, 'MTC-LC-1.0', 'krn')\n", (3053, 3091), False, 'from pathlib import Path\n'), ((3107, 3156), 'pathlib.Path', 'Path', (['args.mtcjsonroot', '"""MTC-FS-INST-2.0"""', '"""json"""'], {}), "(args.mtcjsonroot, 'MTC-FS-INST-2.0', 'json')\n", (3111, 3156), False, 'from pathlib import Path\n'), ((3172, 3219), 'pathlib.Path', 'Path', (['args.mtcjsonroot', '"""MTC-ANN-2.0.1"""', '"""json"""'], {}), "(args.mtcjsonroot, 'MTC-ANN-2.0.1', 'json')\n", (3176, 3219), False, 'from pathlib import Path\n'), ((3234, 3278), 'pathlib.Path', 'Path', (['args.mtcjsonroot', '"""MTC-LC-1.0"""', '"""json"""'], {}), "(args.mtcjsonroot, 'MTC-LC-1.0', 'json')\n", (3238, 3278), False, 'from pathlib import Path\n'), ((3291, 3311), 'pathlib.Path', 'Path', (['args.essenroot'], {}), '(args.essenroot)\n', (3295, 3311), False, 'from pathlib import Path\n'), ((3326, 3356), 'pathlib.Path', 'Path', (['args.essenroot', '"""allkrn"""'], {}), "(args.essenroot, 'allkrn')\n", (3330, 3356), False, 'from pathlib import Path\n'), ((3372, 3403), 'pathlib.Path', 'Path', (['args.essenroot', '"""alljson"""'], {}), "(args.essenroot, 'alljson')\n", (3376, 3403), False, 'from pathlib import Path\n'), ((3424, 3460), 'pathlib.Path', 'Path', (['args.essenroot', '"""metadata.csv"""'], {}), "(args.essenroot, 'metadata.csv')\n", (3428, 3460), False, 'from pathlib import Path\n'), ((3487, 3520), 'pathlib.Path', 'Path', (['args.mtcfsinsttextfeatspath'], {}), '(args.mtcfsinsttextfeatspath)\n', (3491, 3520), False, 'from pathlib import Path\n'), ((3543, 3573), 'pathlib.Path', 'Path', (['args.mtcanntextfeatspath'], {}), '(args.mtcanntextfeatspath)\n', (3547, 3573), False, 'from pathlib import Path\n'), ((10259, 10304), 'music21.interval.Interval', 'm21.interval.Interval', ([], {'noteStart': 't', 'noteEnd': 'n'}), '(noteStart=t, noteEnd=n)\n', (10280, 10304), True, 'import music21 as m21\n'), ((12147, 12172), 'music21.note.Note', 'm21.note.Note', (['tonic.name'], {}), '(tonic.name)\n', (12160, 12172), True, 'import music21 as m21\n'), ((21779, 21790), 'fractions.Fraction', 'Fraction', (['(0)'], {}), '(0)\n', (21787, 21790), False, 'from fractions import Fraction\n'), ((24318, 24351), 'fractions.Fraction', 'Fraction', (['s.notesAndRests[0].beat'], {}), '(s.notesAndRests[0].beat)\n', (24326, 24351), False, 'from fractions import Fraction\n'), ((27241, 27266), 'collections.defaultdict', 'defaultdict', (['(lambda : 0.0)'], {}), '(lambda : 0.0)\n', (27252, 27266), False, 'from collections import defaultdict\n'), ((28125, 28144), 'numpy.array', 'np.array', (['onsettick'], {}), '(onsettick)\n', (28133, 28144), True, 'import numpy as np\n'), ((43658, 43723), 'pandas.concat', 'pd.concat', (['[ann_tf_labels, ann_song_metadata]'], {'axis': '(1)', 'sort': '(False)'}), '([ann_tf_labels, ann_song_metadata], axis=1, sort=False)\n', (43667, 43723), True, 'import pandas as pd\n'), ((9496, 9521), 'music21.converter.parse', 'm21.converter.parse', (['path'], {}), '(path)\n', (9515, 9521), True, 'import music21 as m21\n'), ((24372, 24383), 'fractions.Fraction', 'Fraction', (['(1)'], {}), '(1)\n', (24380, 24383), False, 'from fractions import Fraction\n'), ((24533, 24544), 'fractions.Fraction', 'Fraction', (['(1)'], {}), '(1)\n', (24541, 24544), False, 'from fractions import Fraction\n'), ((27819, 27831), 'json.load', 'json.load', (['f'], {}), '(f)\n', (27828, 27831), False, 'import json\n'), ((21031, 21065), 'fractions.Fraction', 'Fraction', (['n.duration.quarterLength'], {}), '(n.duration.quarterLength)\n', (21039, 21065), False, 'from fractions import Fraction\n'), ((21932, 21970), 'fractions.Fraction', 'Fraction', (['event.duration.quarterLength'], {}), '(event.duration.quarterLength)\n', (21940, 21970), False, 'from fractions import Fraction\n'), ((22177, 22188), 'fractions.Fraction', 'Fraction', (['(0)'], {}), '(0)\n', (22185, 22188), False, 'from fractions import Fraction\n'), ((24925, 24965), 'fractions.Fraction', 'Fraction', (['n_first.duration.quarterLength'], {}), '(n_first.duration.quarterLength)\n', (24933, 24965), False, 'from fractions import Fraction\n'), ((24968, 25012), 'fractions.Fraction', 'Fraction', (['n_first.beatDuration.quarterLength'], {}), '(n_first.beatDuration.quarterLength)\n', (24976, 25012), False, 'from fractions import Fraction\n'), ((25379, 25413), 'fractions.Fraction', 'Fraction', (['n.duration.quarterLength'], {}), '(n.duration.quarterLength)\n', (25387, 25413), False, 'from fractions import Fraction\n'), ((25416, 25454), 'fractions.Fraction', 'Fraction', (['n.beatDuration.quarterLength'], {}), '(n.beatDuration.quarterLength)\n', (25424, 25454), False, 'from fractions import Fraction\n'), ((27384, 27410), 'fractions.Fraction', 'Fraction', (['beatinphrase[ix]'], {}), '(beatinphrase[ix])\n', (27392, 27410), False, 'from fractions import Fraction\n'), ((41370, 41416), 'pathlib.Path', 'Path', (['mtcannroot', '"""metadata/MTC-ANN-songs.csv"""'], {}), "(mtcannroot, 'metadata/MTC-ANN-songs.csv')\n", (41374, 41416), False, 'from pathlib import Path\n'), ((42828, 42887), 'pathlib.Path', 'Path', (['mtcannroot', '"""metadata/MTC-ANN-tune-family-labels.csv"""'], {}), "(mtcannroot, 'metadata/MTC-ANN-tune-family-labels.csv')\n", (42832, 42887), False, 'from pathlib import Path\n'), ((43070, 43116), 'pathlib.Path', 'Path', (['mtcannroot', '"""metadata/MTC-ANN-songs.csv"""'], {}), "(mtcannroot, 'metadata/MTC-ANN-songs.csv')\n", (43074, 43116), False, 'from pathlib import Path\n'), ((43853, 43901), 'pathlib.Path', 'Path', (['mtcannroot', '"""metadata/MTC-ANN-sources.csv"""'], {}), "(mtcannroot, 'metadata/MTC-ANN-sources.csv')\n", (43857, 43901), False, 'from pathlib import Path\n'), ((45145, 45192), 'pathlib.Path', 'Path', (['mtcfsroot', '"""metadata/MTC-FS-INST-2.0.csv"""'], {}), "(mtcfsroot, 'metadata/MTC-FS-INST-2.0.csv')\n", (45149, 45192), False, 'from pathlib import Path\n'), ((46030, 46085), 'pathlib.Path', 'Path', (['mtcfsroot', '"""metadata/MTC-FS-INST-2.0-sources.csv"""'], {}), "(mtcfsroot, 'metadata/MTC-FS-INST-2.0-sources.csv')\n", (46034, 46085), False, 'from pathlib import Path\n'), ((15093, 15104), 'fractions.Fraction', 'Fraction', (['r'], {}), '(r)\n', (15101, 15104), False, 'from fractions import Fraction\n'), ((15105, 15116), 'fractions.Fraction', 'Fraction', (['(0)'], {}), '(0)\n', (15113, 15116), False, 'from fractions import Fraction\n'), ((25691, 25707), 'fractions.Fraction', 'Fraction', (['n.beat'], {}), '(n.beat)\n', (25699, 25707), False, 'from fractions import Fraction\n'), ((26509, 26550), 'fractions.Fraction', 'Fraction', (['nextnote.duration.quarterLength'], {}), '(nextnote.duration.quarterLength)\n', (26517, 26550), False, 'from fractions import Fraction\n'), ((26553, 26598), 'fractions.Fraction', 'Fraction', (['nextnote.beatDuration.quarterLength'], {}), '(nextnote.beatDuration.quarterLength)\n', (26561, 26598), False, 'from fractions import Fraction\n'), ((27484, 27510), 'fractions.Fraction', 'Fraction', (['beatinphrase[ix]'], {}), '(beatinphrase[ix])\n', (27492, 27510), False, 'from fractions import Fraction\n'), ((27513, 27544), 'fractions.Fraction', 'Fraction', (['origin[phrase_ix[ix]]'], {}), '(origin[phrase_ix[ix]])\n', (27521, 27544), False, 'from fractions import Fraction\n'), ((29439, 29450), 'fractions.Fraction', 'Fraction', (['i'], {}), '(i)\n', (29447, 29450), False, 'from fractions import Fraction\n'), ((29587, 29598), 'fractions.Fraction', 'Fraction', (['i'], {}), '(i)\n', (29595, 29598), False, 'from fractions import Fraction\n'), ((29786, 29797), 'fractions.Fraction', 'Fraction', (['d'], {}), '(d)\n', (29794, 29797), False, 'from fractions import Fraction\n'), ((30598, 30624), 'MTCFeatures.MTCFeatureLoader.MTCFeatureLoader', 'MTCFeatureLoader', (['filename'], {}), '(filename)\n', (30614, 30624), False, 'from MTCFeatures.MTCFeatureLoader import MTCFeatureLoader\n'), ((21153, 21165), 'fractions.Fraction', 'Fraction', (['d2'], {}), '(d2)\n', (21161, 21165), False, 'from fractions import Fraction\n'), ((21166, 21178), 'fractions.Fraction', 'Fraction', (['d1'], {}), '(d1)\n', (21174, 21178), False, 'from fractions import Fraction\n'), ((25801, 25812), 'fractions.Fraction', 'Fraction', (['(1)'], {}), '(1)\n', (25809, 25812), False, 'from fractions import Fraction\n'), ((26004, 26015), 'fractions.Fraction', 'Fraction', (['(1)'], {}), '(1)\n', (26012, 26015), False, 'from fractions import Fraction\n'), ((29735, 29746), 'fractions.Fraction', 'Fraction', (['d'], {}), '(d)\n', (29743, 29746), False, 'from fractions import Fraction\n'), ((29747, 29758), 'fractions.Fraction', 'Fraction', (['r'], {}), '(r)\n', (29755, 29758), False, 'from fractions import Fraction\n'), ((32128, 32156), 'pathlib.Path', 'Path', (['krndir', "(nlbid + '.krn')"], {}), "(krndir, nlbid + '.krn')\n", (32132, 32156), False, 'from pathlib import Path\n'), ((14308, 14319), 'fractions.Fraction', 'Fraction', (['r'], {}), '(r)\n', (14316, 14319), False, 'from fractions import Fraction\n'), ((18440, 18451), 'fractions.Fraction', 'Fraction', (['r'], {}), '(r)\n', (18448, 18451), False, 'from fractions import Fraction\n'), ((19890, 19901), 'fractions.Fraction', 'Fraction', (['r'], {}), '(r)\n', (19898, 19901), False, 'from fractions import Fraction\n'), ((21191, 21203), 'fractions.Fraction', 'Fraction', (['d2'], {}), '(d2)\n', (21199, 21203), False, 'from fractions import Fraction\n'), ((21204, 21216), 'fractions.Fraction', 'Fraction', (['d1'], {}), '(d1)\n', (21212, 21216), False, 'from fractions import Fraction\n'), ((29270, 29284), 'fractions.Fraction', 'Fraction', (['ioi2'], {}), '(ioi2)\n', (29278, 29284), False, 'from fractions import Fraction\n'), ((29285, 29299), 'fractions.Fraction', 'Fraction', (['ioi1'], {}), '(ioi1)\n', (29293, 29299), False, 'from fractions import Fraction\n'), ((29994, 30021), 'fractions.Fraction', 'Fraction', (['duration_frac[-1]'], {}), '(duration_frac[-1])\n', (30002, 30021), False, 'from fractions import Fraction\n'), ((30022, 30053), 'fractions.Fraction', 'Fraction', (['restduration_frac[-1]'], {}), '(restduration_frac[-1])\n', (30030, 30053), False, 'from fractions import Fraction\n'), ((48236, 48251), 'json.dumps', 'json.dumps', (['seq'], {}), '(seq)\n', (48246, 48251), False, 'import json\n'), ((48485, 48500), 'json.dumps', 'json.dumps', (['seq'], {}), '(seq)\n', (48495, 48500), False, 'import json\n'), ((48737, 48752), 'json.dumps', 'json.dumps', (['seq'], {}), '(seq)\n', (48747, 48752), False, 'import json\n')]
|
"""parameter_search.py
Search for optimal parameters for RIDDLE and various ML classifiers.
Requires: Keras, NumPy, scikit-learn, RIDDLE (and their dependencies)
Author: <NAME>, Rzhetsky Lab
Copyright: 2018, all rights reserved
"""
from __future__ import print_function
import argparse
import os
import pickle
import time
import warnings
import numpy as np
from sklearn.metrics import log_loss
from sklearn.model_selection import RandomizedSearchCV
from riddle import emr
from riddle import tuning
from riddle.models import MLP
from utils import get_param_path
from utils import get_preprocessed_data
from utils import recursive_mkdir
from utils import select_features
from utils import subset_reencode_features
from utils import vectorize_features
SEED = 109971161161043253 % 8085
TUNING_K = 3 # number of partitions to use to evaluate a parameter config
parser = argparse.ArgumentParser(
description='Perform parameter search for various classification methods.')
parser.add_argument(
'--method', type=str, default='riddle',
help='Classification method to use.')
parser.add_argument(
'--data_fn', type=str, default='dummy.txt',
help='Filename of text data file.')
parser.add_argument(
'--prop_missing', type=float, default=0.0,
help='Proportion of feature observations to simulate as missing.')
parser.add_argument(
'--max_num_feature', type=int, default=-1,
help='Maximum number of features to use; with the default of -1, use all'
'available features')
parser.add_argument(
'--feature_selection', type=str, default='random',
help='Method to use for feature selection.')
parser.add_argument(
'--force_run', type=bool, default=False,
help='Whether to force parameter search to run even if it has been already'
'performed.')
parser.add_argument(
'--max_num_sample', type=int, default=10000,
help='Maximum number of samples to use during parameter tuning.')
parser.add_argument(
'--num_search', type=int, default=5,
help='Number of parameter settings (searches) to try.')
parser.add_argument(
'--data_dir', type=str, default='_data',
help='Directory of data files.')
parser.add_argument(
'--cache_dir', type=str, default='_cache',
help='Directory where to cache files and outputs.')
def loss_scorer(estimator, x, y):
"""Negative log loss scoring function for scikit-learn model selection."""
loss = log_loss(y, estimator.predict_proba(x))
assert loss >= 0
# we want to minimize loss; since scikit-learn model selection tries to
# maximize a given score, return the negative of the loss
return -1 * loss
def run(method, x_unvec, y, idx_feat_dict, num_feature, max_num_feature,
num_class, max_num_sample, feature_selection, k_idx, k, num_search,
perm_indices):
"""Run a parameter search for a single k-fold partitions
Arguments:
method: string
name of classification method; values = {'logit', 'random_forest',
'linear_svm', 'poly_svm', 'rbf_svm', 'gbdt', 'riddle'}
x_unvec: [[int]]
feature indices that have not been vectorized; each inner list
collects the indices of features that are present (binary on)
for a sample
y: [int]
list of class labels as integer indices
idx_feat_dict: {int: string}
dictionary mapping feature indices to features
num_feature: int
number of features present in the dataset
max_num_feature: int
maximum number of features to use
num_class: int
number of classes present
feature_selection: string
feature selection method; values = {'random', 'frequency', 'chi2'}
k_idx: int
index of the k-fold partition to use
k: int
number of partitions for k-fold cross-validation
num_search: int
number of searches (parameter configurations) to try
perm_indices: np.ndarray, int
array of indices representing a permutation of the samples with
shape (num_sample, )
Returns:
best_param: {string: ?}
dictionary mapping parameter names to the best values found
"""
print('-' * 72)
print('Partition k = {}'.format(k_idx))
x_train_unvec, y_train, x_val_unvec, y_val, _, _ = (
emr.get_k_fold_partition(x_unvec, y, k_idx=k_idx, k=k,
perm_indices=perm_indices))
if max_num_feature > 0: # select features and re-encode
feat_encoding_dict, _ = select_features(
x_train_unvec, y_train, idx_feat_dict,
method=feature_selection, num_feature=num_feature,
max_num_feature=max_num_feature)
x_val_unvec = subset_reencode_features(x_val_unvec, feat_encoding_dict)
num_feature = max_num_feature
# cap number of validation samples
if max_num_sample != None and len(x_val_unvec) > max_num_sample:
x_val_unvec = x_val_unvec[0:max_num_sample]
y_val = y_val[0:max_num_sample]
start = time.time()
if method == 'riddle':
model_class = MLP
init_args = {'num_feature': num_feature, 'num_class': num_class}
param_dist = {
'num_hidden_layer': 2, # [1, 2]
'num_hidden_node': 512, # [128, 256, 512]
'activation': ['prelu', 'relu'],
'dropout': tuning.Uniform(lo=0.2, hi=0.8),
'learning_rate': tuning.UniformLogSpace(10, lo=-6, hi=-1),
}
best_param = tuning.random_search(
model_class, init_args, param_dist, x_val_unvec, y_val,
num_class=num_class, k=TUNING_K, num_search=num_search)
else: # scikit-learn methods
x_val = vectorize_features(x_val_unvec, num_feature)
if method == 'logit': # logistic regression
from sklearn.linear_model import LogisticRegression
estimator = LogisticRegression(multi_class='multinomial',
solver='lbfgs')
param_dist = {'C': tuning.UniformLogSpace(base=10, lo=-3, hi=3)}
elif method == 'random_forest':
from sklearn.ensemble import RandomForestClassifier
estimator = RandomForestClassifier()
param_dist = {
'max_features': ['sqrt', 'log2', None],
'max_depth': tuning.UniformIntegerLogSpace(base=2, lo=0, hi=7),
'n_estimators': tuning.UniformIntegerLogSpace(base=2, lo=4, hi=8)
}
elif method == 'linear_svm':
from sklearn.svm import SVC
# remark: due to a bug in scikit-learn / libsvm, the sparse 'linear'
# kernel is much slower than the sparse 'poly' kernel, so we use
# the 'poly' kernel with degree=1 over the 'linear' kernel
estimator = SVC(kernel='poly', degree=1, coef0=0., gamma=1.,
probability=True, cache_size=1000)
param_dist = {
'C': tuning.UniformLogSpace(base=10, lo=-2, hi=1)
}
elif method == 'poly_svm':
from sklearn.svm import SVC
estimator = SVC(kernel='poly', probability=True, cache_size=1000)
param_dist = {
'C': tuning.UniformLogSpace(base=10, lo=-2, hi=1),
'degree': [2, 3, 4],
'gamma': tuning.UniformLogSpace(base=10, lo=-5, hi=1)
}
elif method == 'rbf_svm':
from sklearn.svm import SVC
estimator = SVC(kernel='rbf', probability=True, cache_size=1000)
param_dist = {
'C': tuning.UniformLogSpace(base=10, lo=-2, hi=1),
'gamma': tuning.UniformLogSpace(base=10, lo=-5, hi=1)
}
elif method == 'gbdt':
from xgboost import XGBClassifier
estimator = XGBClassifier(objective='multi:softprob')
param_dist = {
'max_depth': tuning.UniformIntegerLogSpace(base=2, lo=0, hi=5),
'n_estimators': tuning.UniformIntegerLogSpace(base=2, lo=4, hi=8),
'learning_rate': tuning.UniformLogSpace(base=10, lo=-3, hi=0)
}
else:
raise ValueError('unknown method: {}'.format(method))
param_search = RandomizedSearchCV(
estimator, param_dist, refit=False, n_iter=num_search,
scoring=loss_scorer)
param_search.fit(x_val, y_val)
best_param = param_search.best_params_
print('Best parameters for {} for k_idx={}: {} found in {:.3f} s'
.format(method, k_idx, best_param, time.time() - start))
return best_param
def run_kfold(data_fn, method='logit', prop_missing=0., max_num_feature=-1,
feature_selection='random', k=10, max_num_sample=10000,
num_search=30, data_dir='_data', cache_dir='_cache',
force_run=False):
"""Run several parameter searches a la k-fold cross-validation.
Arguments:
data_fn: string
data file filename
method: string
name of classification method; values = {'logit', 'random_forest',
'linear_svm', 'poly_svm', 'rbf_svm', 'gbdt', 'riddle'}
prop_missing: float
proportion of feature observations which should be randomly masked;
values in [0, 1)
max_num_feature: int
maximum number of features to use
feature_selection: string
feature selection method; values = {'random', 'frequency', 'chi2'}
k: int
number of partitions for k-fold cross-validation
max_num_sample: int
maximum number of samples to use
num_search: int
number of searches (parameter configurations) to try for each
partition
data_dir: string
directory where data files are located
cache_dir: string
directory where cached files (e.g., saved parameters) are located
out_dir: string
directory where outputs (e.g., results) should be saved
"""
if 'debug' in data_fn:
num_search = 3
# check if already did param search, if so, skip
param_path = get_param_path(cache_dir, method, data_fn, prop_missing,
max_num_feature, feature_selection)
if not force_run and os.path.isfile(param_path):
warnings.warn('Already did search for {}, skipping the search'
.format(method))
return
x_unvec, y, idx_feat_dict, idx_class_dict, _, perm_indices = (
get_preprocessed_data(data_dir, data_fn, prop_missing=prop_missing))
num_feature = len(idx_feat_dict)
num_class = len(idx_class_dict)
params = {}
for k_idx in range(0, k):
params[k_idx] = run(
method, x_unvec, y, idx_feat_dict, num_feature=num_feature,
max_num_feature=max_num_feature, num_class=num_class,
max_num_sample=max_num_sample, feature_selection=feature_selection,
k_idx=k_idx, k=k, num_search=num_search, perm_indices=perm_indices)
recursive_mkdir(FLAGS.cache_dir)
with open(param_path, 'wb') as f: # save
pickle.dump(params, f)
print('Finished parameter search for method: {}'.format(method))
def main():
"""Main method."""
np.random.seed(SEED) # for reproducibility, must be before Keras imports!
run_kfold(data_fn=FLAGS.data_fn,
method=FLAGS.method,
prop_missing=FLAGS.prop_missing,
max_num_feature=FLAGS.max_num_feature,
feature_selection=FLAGS.feature_selection,
max_num_sample=FLAGS.max_num_sample,
num_search=FLAGS.num_search,
data_dir=FLAGS.data_dir,
cache_dir=FLAGS.cache_dir,
force_run=FLAGS.force_run)
# if run as script, execute main
if __name__ == '__main__':
FLAGS, _ = parser.parse_known_args()
main()
|
[
"pickle.dump",
"numpy.random.seed",
"argparse.ArgumentParser",
"utils.subset_reencode_features",
"utils.get_param_path",
"utils.get_preprocessed_data",
"os.path.isfile",
"sklearn.svm.SVC",
"utils.vectorize_features",
"utils.recursive_mkdir",
"sklearn.model_selection.RandomizedSearchCV",
"riddle.tuning.Uniform",
"xgboost.XGBClassifier",
"sklearn.ensemble.RandomForestClassifier",
"riddle.tuning.UniformLogSpace",
"riddle.tuning.random_search",
"sklearn.linear_model.LogisticRegression",
"riddle.tuning.UniformIntegerLogSpace",
"riddle.emr.get_k_fold_partition",
"time.time",
"utils.select_features"
] |
[((883, 987), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Perform parameter search for various classification methods."""'}), "(description=\n 'Perform parameter search for various classification methods.')\n", (906, 987), False, 'import argparse\n'), ((4397, 4483), 'riddle.emr.get_k_fold_partition', 'emr.get_k_fold_partition', (['x_unvec', 'y'], {'k_idx': 'k_idx', 'k': 'k', 'perm_indices': 'perm_indices'}), '(x_unvec, y, k_idx=k_idx, k=k, perm_indices=\n perm_indices)\n', (4421, 4483), False, 'from riddle import emr\n'), ((5115, 5126), 'time.time', 'time.time', ([], {}), '()\n', (5124, 5126), False, 'import time\n'), ((10260, 10356), 'utils.get_param_path', 'get_param_path', (['cache_dir', 'method', 'data_fn', 'prop_missing', 'max_num_feature', 'feature_selection'], {}), '(cache_dir, method, data_fn, prop_missing, max_num_feature,\n feature_selection)\n', (10274, 10356), False, 'from utils import get_param_path\n'), ((10639, 10706), 'utils.get_preprocessed_data', 'get_preprocessed_data', (['data_dir', 'data_fn'], {'prop_missing': 'prop_missing'}), '(data_dir, data_fn, prop_missing=prop_missing)\n', (10660, 10706), False, 'from utils import get_preprocessed_data\n'), ((11159, 11191), 'utils.recursive_mkdir', 'recursive_mkdir', (['FLAGS.cache_dir'], {}), '(FLAGS.cache_dir)\n', (11174, 11191), False, 'from utils import recursive_mkdir\n'), ((11380, 11400), 'numpy.random.seed', 'np.random.seed', (['SEED'], {}), '(SEED)\n', (11394, 11400), True, 'import numpy as np\n'), ((4607, 4755), 'utils.select_features', 'select_features', (['x_train_unvec', 'y_train', 'idx_feat_dict'], {'method': 'feature_selection', 'num_feature': 'num_feature', 'max_num_feature': 'max_num_feature'}), '(x_train_unvec, y_train, idx_feat_dict, method=\n feature_selection, num_feature=num_feature, max_num_feature=max_num_feature\n )\n', (4622, 4755), False, 'from utils import select_features\n'), ((4805, 4862), 'utils.subset_reencode_features', 'subset_reencode_features', (['x_val_unvec', 'feat_encoding_dict'], {}), '(x_val_unvec, feat_encoding_dict)\n', (4829, 4862), False, 'from utils import subset_reencode_features\n'), ((5578, 5714), 'riddle.tuning.random_search', 'tuning.random_search', (['model_class', 'init_args', 'param_dist', 'x_val_unvec', 'y_val'], {'num_class': 'num_class', 'k': 'TUNING_K', 'num_search': 'num_search'}), '(model_class, init_args, param_dist, x_val_unvec, y_val,\n num_class=num_class, k=TUNING_K, num_search=num_search)\n', (5598, 5714), False, 'from riddle import tuning\n'), ((5786, 5830), 'utils.vectorize_features', 'vectorize_features', (['x_val_unvec', 'num_feature'], {}), '(x_val_unvec, num_feature)\n', (5804, 5830), False, 'from utils import vectorize_features\n'), ((8342, 8440), 'sklearn.model_selection.RandomizedSearchCV', 'RandomizedSearchCV', (['estimator', 'param_dist'], {'refit': '(False)', 'n_iter': 'num_search', 'scoring': 'loss_scorer'}), '(estimator, param_dist, refit=False, n_iter=num_search,\n scoring=loss_scorer)\n', (8360, 8440), False, 'from sklearn.model_selection import RandomizedSearchCV\n'), ((10410, 10436), 'os.path.isfile', 'os.path.isfile', (['param_path'], {}), '(param_path)\n', (10424, 10436), False, 'import os\n'), ((11246, 11268), 'pickle.dump', 'pickle.dump', (['params', 'f'], {}), '(params, f)\n', (11257, 11268), False, 'import pickle\n'), ((5444, 5474), 'riddle.tuning.Uniform', 'tuning.Uniform', ([], {'lo': '(0.2)', 'hi': '(0.8)'}), '(lo=0.2, hi=0.8)\n', (5458, 5474), False, 'from riddle import tuning\n'), ((5505, 5545), 'riddle.tuning.UniformLogSpace', 'tuning.UniformLogSpace', (['(10)'], {'lo': '(-6)', 'hi': '(-1)'}), '(10, lo=-6, hi=-1)\n', (5527, 5545), False, 'from riddle import tuning\n'), ((5973, 6034), 'sklearn.linear_model.LogisticRegression', 'LogisticRegression', ([], {'multi_class': '"""multinomial"""', 'solver': '"""lbfgs"""'}), "(multi_class='multinomial', solver='lbfgs')\n", (5991, 6034), False, 'from sklearn.linear_model import LogisticRegression\n'), ((6109, 6153), 'riddle.tuning.UniformLogSpace', 'tuning.UniformLogSpace', ([], {'base': '(10)', 'lo': '(-3)', 'hi': '(3)'}), '(base=10, lo=-3, hi=3)\n', (6131, 6153), False, 'from riddle import tuning\n'), ((6283, 6307), 'sklearn.ensemble.RandomForestClassifier', 'RandomForestClassifier', ([], {}), '()\n', (6305, 6307), False, 'from sklearn.ensemble import RandomForestClassifier\n'), ((8665, 8676), 'time.time', 'time.time', ([], {}), '()\n', (8674, 8676), False, 'import time\n'), ((6420, 6469), 'riddle.tuning.UniformIntegerLogSpace', 'tuning.UniformIntegerLogSpace', ([], {'base': '(2)', 'lo': '(0)', 'hi': '(7)'}), '(base=2, lo=0, hi=7)\n', (6449, 6469), False, 'from riddle import tuning\n'), ((6503, 6552), 'riddle.tuning.UniformIntegerLogSpace', 'tuning.UniformIntegerLogSpace', ([], {'base': '(2)', 'lo': '(4)', 'hi': '(8)'}), '(base=2, lo=4, hi=8)\n', (6532, 6552), False, 'from riddle import tuning\n'), ((6897, 6986), 'sklearn.svm.SVC', 'SVC', ([], {'kernel': '"""poly"""', 'degree': '(1)', 'coef0': '(0.0)', 'gamma': '(1.0)', 'probability': '(True)', 'cache_size': '(1000)'}), "(kernel='poly', degree=1, coef0=0.0, gamma=1.0, probability=True,\n cache_size=1000)\n", (6900, 6986), False, 'from sklearn.svm import SVC\n'), ((7057, 7101), 'riddle.tuning.UniformLogSpace', 'tuning.UniformLogSpace', ([], {'base': '(10)', 'lo': '(-2)', 'hi': '(1)'}), '(base=10, lo=-2, hi=1)\n', (7079, 7101), False, 'from riddle import tuning\n'), ((7215, 7268), 'sklearn.svm.SVC', 'SVC', ([], {'kernel': '"""poly"""', 'probability': '(True)', 'cache_size': '(1000)'}), "(kernel='poly', probability=True, cache_size=1000)\n", (7218, 7268), False, 'from sklearn.svm import SVC\n'), ((7317, 7361), 'riddle.tuning.UniformLogSpace', 'tuning.UniformLogSpace', ([], {'base': '(10)', 'lo': '(-2)', 'hi': '(1)'}), '(base=10, lo=-2, hi=1)\n', (7339, 7361), False, 'from riddle import tuning\n'), ((7425, 7469), 'riddle.tuning.UniformLogSpace', 'tuning.UniformLogSpace', ([], {'base': '(10)', 'lo': '(-5)', 'hi': '(1)'}), '(base=10, lo=-5, hi=1)\n', (7447, 7469), False, 'from riddle import tuning\n'), ((7582, 7634), 'sklearn.svm.SVC', 'SVC', ([], {'kernel': '"""rbf"""', 'probability': '(True)', 'cache_size': '(1000)'}), "(kernel='rbf', probability=True, cache_size=1000)\n", (7585, 7634), False, 'from sklearn.svm import SVC\n'), ((7683, 7727), 'riddle.tuning.UniformLogSpace', 'tuning.UniformLogSpace', ([], {'base': '(10)', 'lo': '(-2)', 'hi': '(1)'}), '(base=10, lo=-2, hi=1)\n', (7705, 7727), False, 'from riddle import tuning\n'), ((7754, 7798), 'riddle.tuning.UniformLogSpace', 'tuning.UniformLogSpace', ([], {'base': '(10)', 'lo': '(-5)', 'hi': '(1)'}), '(base=10, lo=-5, hi=1)\n', (7776, 7798), False, 'from riddle import tuning\n'), ((7914, 7955), 'xgboost.XGBClassifier', 'XGBClassifier', ([], {'objective': '"""multi:softprob"""'}), "(objective='multi:softprob')\n", (7927, 7955), False, 'from xgboost import XGBClassifier\n'), ((8012, 8061), 'riddle.tuning.UniformIntegerLogSpace', 'tuning.UniformIntegerLogSpace', ([], {'base': '(2)', 'lo': '(0)', 'hi': '(5)'}), '(base=2, lo=0, hi=5)\n', (8041, 8061), False, 'from riddle import tuning\n'), ((8095, 8144), 'riddle.tuning.UniformIntegerLogSpace', 'tuning.UniformIntegerLogSpace', ([], {'base': '(2)', 'lo': '(4)', 'hi': '(8)'}), '(base=2, lo=4, hi=8)\n', (8124, 8144), False, 'from riddle import tuning\n'), ((8179, 8223), 'riddle.tuning.UniformLogSpace', 'tuning.UniformLogSpace', ([], {'base': '(10)', 'lo': '(-3)', 'hi': '(0)'}), '(base=10, lo=-3, hi=0)\n', (8201, 8223), False, 'from riddle import tuning\n')]
|
import numpy as np
from dialRL.utils import distance, float_equality
origin = np.array([1. , 1.])
target = np.array([10., 10.])
print('origin position: ', origin)
print('Traget position: ', target)
a = distance(origin, target)
b = np.random.uniform(0, 9)
# , b = np.random.uniform(0, 9)
# a, b = np.max([a, b]), np.min([a, b])
lam = b / a
print('Distance to target(a): ', a)
print('Current time gap(b): ', b)
print('Current proportion of advance on the tragetory (lam):', lam)
new_pos = (1 - lam) * origin + (lam) * target
print('New position : ', new_pos)
to_go_now = distance(new_pos, origin)
to_go_later = distance(new_pos, target)
print('Distance from origin to new_position: ', to_go_now)
print('Distance from new_position to target: ', to_go_later)
print('Addition of distances: ', to_go_later + to_go_now)
eps = 0.0001
compare_gap_distance = float_equality(distance(new_pos, origin), b, eps=eps)
print('Comparaison float equality: ', compare_gap_distance, 'with eps=', eps)
|
[
"numpy.random.uniform",
"dialRL.utils.distance",
"numpy.array"
] |
[((79, 99), 'numpy.array', 'np.array', (['[1.0, 1.0]'], {}), '([1.0, 1.0])\n', (87, 99), True, 'import numpy as np\n'), ((108, 130), 'numpy.array', 'np.array', (['[10.0, 10.0]'], {}), '([10.0, 10.0])\n', (116, 130), True, 'import numpy as np\n'), ((205, 229), 'dialRL.utils.distance', 'distance', (['origin', 'target'], {}), '(origin, target)\n', (213, 229), False, 'from dialRL.utils import distance, float_equality\n'), ((234, 257), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(9)'], {}), '(0, 9)\n', (251, 257), True, 'import numpy as np\n'), ((580, 605), 'dialRL.utils.distance', 'distance', (['new_pos', 'origin'], {}), '(new_pos, origin)\n', (588, 605), False, 'from dialRL.utils import distance, float_equality\n'), ((620, 645), 'dialRL.utils.distance', 'distance', (['new_pos', 'target'], {}), '(new_pos, target)\n', (628, 645), False, 'from dialRL.utils import distance, float_equality\n'), ((877, 902), 'dialRL.utils.distance', 'distance', (['new_pos', 'origin'], {}), '(new_pos, origin)\n', (885, 902), False, 'from dialRL.utils import distance, float_equality\n')]
|
# -----------------------------------------------------------------------------
# From Pytnon to Numpy
# Copyright (2017) <NAME> - BSD license
# More information at https://github.com/rougier/numpy-book
# -----------------------------------------------------------------------------
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.path import Path
from matplotlib.animation import FuncAnimation
from matplotlib.collections import PathCollection
class MarkerCollection:
"""
Marker collection
"""
def __init__(self, n=100):
v = np.array([(-0.25, -0.25), (+0.0, +0.5), (+0.25, -0.25), (0, 0)])
c = np.array([Path.MOVETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY])
self._base_vertices = np.tile(v.reshape(-1), n).reshape(n, len(v), 2)
self._vertices = np.tile(v.reshape(-1), n).reshape(n, len(v), 2)
self._codes = np.tile(c.reshape(-1), n)
self._scale = np.ones(n)
self._translate = np.zeros((n, 2))
self._rotate = np.zeros(n)
self._path = Path(vertices=self._vertices.reshape(n*len(v), 2),
codes=self._codes)
self._collection = PathCollection([self._path], linewidth=0.5,
facecolor="k", edgecolor="w")
def update(self):
n = len(self._base_vertices)
self._vertices[...] = self._base_vertices * self._scale
cos_rotate, sin_rotate = np.cos(self._rotate), np.sin(self._rotate)
R = np.empty((n, 2, 2))
R[:, 0, 0] = cos_rotate
R[:, 1, 0] = sin_rotate
R[:, 0, 1] = -sin_rotate
R[:, 1, 1] = cos_rotate
self._vertices[...] = np.einsum('ijk,ilk->ijl', self._vertices, R)
self._vertices += self._translate.reshape(n, 1, 2)
class Flock:
def __init__(self, count=500, width=640, height=360):
self.width = width
self.height = height
self.min_velocity = 0.5
self.max_velocity = 2.0
self.max_acceleration = 0.03
self.velocity = np.zeros((count, 2), dtype=np.float32)
self.position = np.zeros((count, 2), dtype=np.float32)
angle = np.random.uniform(0, 2*np.pi, count)
self.velocity[:, 0] = np.cos(angle)
self.velocity[:, 1] = np.sin(angle)
angle = np.random.uniform(0, 2*np.pi, count)
radius = min(width, height)/2*np.random.uniform(0, 1, count)
self.position[:, 0] = width/2 + np.cos(angle)*radius
self.position[:, 1] = height/2 + np.sin(angle)*radius
def run(self):
position = self.position
velocity = self.velocity
min_velocity = self.min_velocity
max_velocity = self.max_velocity
max_acceleration = self.max_acceleration
n = len(position)
dx = np.subtract.outer(position[:, 0], position[:, 0])
dy = np.subtract.outer(position[:, 1], position[:, 1])
distance = np.hypot(dx, dy)
# Compute common distance masks
mask_0 = (distance > 0)
mask_1 = (distance < 25)
mask_2 = (distance < 50)
mask_1 *= mask_0
mask_2 *= mask_0
mask_3 = mask_2
mask_1_count = np.maximum(mask_1.sum(axis=1), 1)
mask_2_count = np.maximum(mask_2.sum(axis=1), 1)
mask_3_count = mask_2_count
# Separation
mask, count = mask_1, mask_1_count
target = np.dstack((dx, dy))
target = np.divide(target, distance.reshape(n, n, 1)**2, out=target,
where=distance.reshape(n, n, 1) != 0)
steer = (target*mask.reshape(n, n, 1)).sum(axis=1)/count.reshape(n, 1)
norm = np.sqrt((steer*steer).sum(axis=1)).reshape(n, 1)
steer = max_velocity*np.divide(steer, norm, out=steer,
where=norm != 0)
steer -= velocity
# Limit acceleration
norm = np.sqrt((steer*steer).sum(axis=1)).reshape(n, 1)
steer = np.multiply(steer, max_acceleration/norm, out=steer,
where=norm > max_acceleration)
separation = steer
# Alignment
# ---------------------------------------------------------------------
# Compute target
mask, count = mask_2, mask_2_count
target = np.dot(mask, velocity)/count.reshape(n, 1)
# Compute steering
norm = np.sqrt((target*target).sum(axis=1)).reshape(n, 1)
target = max_velocity * np.divide(target, norm, out=target,
where=norm != 0)
steer = target - velocity
# Limit acceleration
norm = np.sqrt((steer*steer).sum(axis=1)).reshape(n, 1)
steer = np.multiply(steer, max_acceleration/norm, out=steer,
where=norm > max_acceleration)
alignment = steer
# Cohesion
# ---------------------------------------------------------------------
# Compute target
mask, count = mask_3, mask_3_count
target = np.dot(mask, position)/count.reshape(n, 1)
# Compute steering
desired = target - position
norm = np.sqrt((desired*desired).sum(axis=1)).reshape(n, 1)
desired *= max_velocity / norm
steer = desired - velocity
# Limit acceleration
norm = np.sqrt((steer*steer).sum(axis=1)).reshape(n, 1)
steer = np.multiply(steer, max_acceleration/norm, out=steer,
where=norm > max_acceleration)
cohesion = steer
# ---------------------------------------------------------------------
acceleration = 1.5 * separation + alignment + cohesion
velocity += acceleration
norm = np.sqrt((velocity*velocity).sum(axis=1)).reshape(n, 1)
velocity = np.multiply(velocity, max_velocity/norm, out=velocity,
where=norm > max_velocity)
velocity = np.multiply(velocity, min_velocity/norm, out=velocity,
where=norm < min_velocity)
position += velocity
# Wraparound
position += (self.width, self.height)
position %= (self.width, self.height)
def update(*args):
global flock, collection, trace
# Flock updating
flock.run()
collection._scale = 10
collection._translate = flock.position
collection._rotate = -np.pi/2 + np.arctan2(flock.velocity[:, 1],
flock.velocity[:, 0])
collection.update()
# Trace updating
if trace is not None:
P = flock.position.astype(int)
trace[height-1-P[:, 1], P[:, 0]] = .75
trace *= .99
im.set_array(trace)
# -----------------------------------------------------------------------------
#if __name__ == '__main__':
n = 500
width, height = 640, 360
flock = Flock(n)
fig = plt.figure(figsize=(10, 10*height/width), facecolor="white")
ax = fig.add_axes([0.0, 0.0, 1.0, 1.0], aspect=1, frameon=False)
collection = MarkerCollection(n)
ax.add_collection(collection._collection)
ax.set_xlim(0, width)
ax.set_ylim(0, height)
ax.set_xticks([])
ax.set_yticks([])
# Trace
trace = None
if 0:
trace = np.zeros((height, width))
im = ax.imshow(trace, extent=[0, width, 0, height], vmin=0, vmax=1,
interpolation="nearest", cmap=plt.cm.gray_r)
animation = FuncAnimation(fig, update, interval=10, frames=1000)
animation.save('boid.mp4', fps=40, dpi=80, bitrate=-1, codec="libx264")
plt.show()
|
[
"numpy.arctan2",
"numpy.empty",
"numpy.einsum",
"numpy.ones",
"matplotlib.animation.FuncAnimation",
"matplotlib.pyplot.figure",
"numpy.sin",
"numpy.multiply",
"numpy.dstack",
"numpy.divide",
"matplotlib.pyplot.show",
"numpy.hypot",
"numpy.cos",
"numpy.dot",
"numpy.random.uniform",
"matplotlib.collections.PathCollection",
"numpy.zeros",
"numpy.subtract.outer",
"numpy.array"
] |
[((6821, 6885), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 10 * height / width)', 'facecolor': '"""white"""'}), "(figsize=(10, 10 * height / width), facecolor='white')\n", (6831, 6885), True, 'import matplotlib.pyplot as plt\n'), ((7318, 7370), 'matplotlib.animation.FuncAnimation', 'FuncAnimation', (['fig', 'update'], {'interval': '(10)', 'frames': '(1000)'}), '(fig, update, interval=10, frames=1000)\n', (7331, 7370), False, 'from matplotlib.animation import FuncAnimation\n'), ((7443, 7453), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (7451, 7453), True, 'import matplotlib.pyplot as plt\n'), ((7143, 7168), 'numpy.zeros', 'np.zeros', (['(height, width)'], {}), '((height, width))\n', (7151, 7168), True, 'import numpy as np\n'), ((572, 636), 'numpy.array', 'np.array', (['[(-0.25, -0.25), (+0.0, +0.5), (+0.25, -0.25), (0, 0)]'], {}), '([(-0.25, -0.25), (+0.0, +0.5), (+0.25, -0.25), (0, 0)])\n', (580, 636), True, 'import numpy as np\n'), ((649, 714), 'numpy.array', 'np.array', (['[Path.MOVETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY]'], {}), '([Path.MOVETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY])\n', (657, 714), True, 'import numpy as np\n'), ((937, 947), 'numpy.ones', 'np.ones', (['n'], {}), '(n)\n', (944, 947), True, 'import numpy as np\n'), ((974, 990), 'numpy.zeros', 'np.zeros', (['(n, 2)'], {}), '((n, 2))\n', (982, 990), True, 'import numpy as np\n'), ((1014, 1025), 'numpy.zeros', 'np.zeros', (['n'], {}), '(n)\n', (1022, 1025), True, 'import numpy as np\n'), ((1171, 1244), 'matplotlib.collections.PathCollection', 'PathCollection', (['[self._path]'], {'linewidth': '(0.5)', 'facecolor': '"""k"""', 'edgecolor': '"""w"""'}), "([self._path], linewidth=0.5, facecolor='k', edgecolor='w')\n", (1185, 1244), False, 'from matplotlib.collections import PathCollection\n'), ((1499, 1518), 'numpy.empty', 'np.empty', (['(n, 2, 2)'], {}), '((n, 2, 2))\n', (1507, 1518), True, 'import numpy as np\n'), ((1678, 1722), 'numpy.einsum', 'np.einsum', (['"""ijk,ilk->ijl"""', 'self._vertices', 'R'], {}), "('ijk,ilk->ijl', self._vertices, R)\n", (1687, 1722), True, 'import numpy as np\n'), ((2036, 2074), 'numpy.zeros', 'np.zeros', (['(count, 2)'], {'dtype': 'np.float32'}), '((count, 2), dtype=np.float32)\n', (2044, 2074), True, 'import numpy as np\n'), ((2099, 2137), 'numpy.zeros', 'np.zeros', (['(count, 2)'], {'dtype': 'np.float32'}), '((count, 2), dtype=np.float32)\n', (2107, 2137), True, 'import numpy as np\n'), ((2155, 2193), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(2 * np.pi)', 'count'], {}), '(0, 2 * np.pi, count)\n', (2172, 2193), True, 'import numpy as np\n'), ((2222, 2235), 'numpy.cos', 'np.cos', (['angle'], {}), '(angle)\n', (2228, 2235), True, 'import numpy as np\n'), ((2266, 2279), 'numpy.sin', 'np.sin', (['angle'], {}), '(angle)\n', (2272, 2279), True, 'import numpy as np\n'), ((2296, 2334), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(2 * np.pi)', 'count'], {}), '(0, 2 * np.pi, count)\n', (2313, 2334), True, 'import numpy as np\n'), ((2782, 2831), 'numpy.subtract.outer', 'np.subtract.outer', (['position[:, 0]', 'position[:, 0]'], {}), '(position[:, 0], position[:, 0])\n', (2799, 2831), True, 'import numpy as np\n'), ((2845, 2894), 'numpy.subtract.outer', 'np.subtract.outer', (['position[:, 1]', 'position[:, 1]'], {}), '(position[:, 1], position[:, 1])\n', (2862, 2894), True, 'import numpy as np\n'), ((2914, 2930), 'numpy.hypot', 'np.hypot', (['dx', 'dy'], {}), '(dx, dy)\n', (2922, 2930), True, 'import numpy as np\n'), ((3376, 3395), 'numpy.dstack', 'np.dstack', (['(dx, dy)'], {}), '((dx, dy))\n', (3385, 3395), True, 'import numpy as np\n'), ((3936, 4025), 'numpy.multiply', 'np.multiply', (['steer', '(max_acceleration / norm)'], {'out': 'steer', 'where': '(norm > max_acceleration)'}), '(steer, max_acceleration / norm, out=steer, where=norm >\n max_acceleration)\n', (3947, 4025), True, 'import numpy as np\n'), ((4670, 4759), 'numpy.multiply', 'np.multiply', (['steer', '(max_acceleration / norm)'], {'out': 'steer', 'where': '(norm > max_acceleration)'}), '(steer, max_acceleration / norm, out=steer, where=norm >\n max_acceleration)\n', (4681, 4759), True, 'import numpy as np\n'), ((5352, 5441), 'numpy.multiply', 'np.multiply', (['steer', '(max_acceleration / norm)'], {'out': 'steer', 'where': '(norm > max_acceleration)'}), '(steer, max_acceleration / norm, out=steer, where=norm >\n max_acceleration)\n', (5363, 5441), True, 'import numpy as np\n'), ((5756, 5843), 'numpy.multiply', 'np.multiply', (['velocity', '(max_velocity / norm)'], {'out': 'velocity', 'where': '(norm > max_velocity)'}), '(velocity, max_velocity / norm, out=velocity, where=norm >\n max_velocity)\n', (5767, 5843), True, 'import numpy as np\n'), ((5888, 5975), 'numpy.multiply', 'np.multiply', (['velocity', '(min_velocity / norm)'], {'out': 'velocity', 'where': '(norm < min_velocity)'}), '(velocity, min_velocity / norm, out=velocity, where=norm <\n min_velocity)\n', (5899, 5975), True, 'import numpy as np\n'), ((6345, 6399), 'numpy.arctan2', 'np.arctan2', (['flock.velocity[:, 1]', 'flock.velocity[:, 0]'], {}), '(flock.velocity[:, 1], flock.velocity[:, 0])\n', (6355, 6399), True, 'import numpy as np\n'), ((1444, 1464), 'numpy.cos', 'np.cos', (['self._rotate'], {}), '(self._rotate)\n', (1450, 1464), True, 'import numpy as np\n'), ((1466, 1486), 'numpy.sin', 'np.sin', (['self._rotate'], {}), '(self._rotate)\n', (1472, 1486), True, 'import numpy as np\n'), ((2371, 2401), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(1)', 'count'], {}), '(0, 1, count)\n', (2388, 2401), True, 'import numpy as np\n'), ((3710, 3760), 'numpy.divide', 'np.divide', (['steer', 'norm'], {'out': 'steer', 'where': '(norm != 0)'}), '(steer, norm, out=steer, where=norm != 0)\n', (3719, 3760), True, 'import numpy as np\n'), ((4262, 4284), 'numpy.dot', 'np.dot', (['mask', 'velocity'], {}), '(mask, velocity)\n', (4268, 4284), True, 'import numpy as np\n'), ((4431, 4483), 'numpy.divide', 'np.divide', (['target', 'norm'], {'out': 'target', 'where': '(norm != 0)'}), '(target, norm, out=target, where=norm != 0)\n', (4440, 4483), True, 'import numpy as np\n'), ((4993, 5015), 'numpy.dot', 'np.dot', (['mask', 'position'], {}), '(mask, position)\n', (4999, 5015), True, 'import numpy as np\n'), ((2442, 2455), 'numpy.cos', 'np.cos', (['angle'], {}), '(angle)\n', (2448, 2455), True, 'import numpy as np\n'), ((2504, 2517), 'numpy.sin', 'np.sin', (['angle'], {}), '(angle)\n', (2510, 2517), True, 'import numpy as np\n')]
|
from __future__ import absolute_import, division, print_function
from mmtbx.validation.ramalyze import draw_ramachandran_plot
import math
from scipy import interpolate
import numpy as np
def calculate_indexes(x, y, xmin, x_step, ymin, y_step):
i = math.floor((x-xmin) / x_step)
j = math.floor((y-ymin) / y_step)
return int(i), int(j)
class Grid2D(object):
def __init__(self, data, xmin, xmax, ymin, ymax):
# data - list of lists [[],[],...[]], data[x][y]
self.g = data
self.xmax = xmax
self.xmin = xmin
self.ymax = ymax
self.ymin = ymin
n_x = len(data)
n_y = len(data[0])
self.x_step = (xmax-xmin)/n_x
self.y_step = (ymax-ymin)/n_y
# print("x y steps:", self.x_step, self.y_step)
# assert 360 % self.phi_step == 0
# assert 360 // self.phi_step % 2 == 0
# assert 360 % self.psi_step == 0
# assert 360 // self.psi_step % 2 == 0
# self.n_phi_half = 360 // self.phi_step // 2
# self.n_psi_half = 360 // self.psi_step // 2
# for i in range(360 // self.phi_step):
# self.g.append([0]*(360 // self.psi_step))
# self.n_points = 0
# self.mean = None
# self.std = None
self.interpolation_f = self.set_interpolation_f()
@classmethod
def make_Grid2d(cls, points, x_nbins, y_nbins,
xmin=None, xmax=None, ymin=None, ymax=None):
# points - list of tuples [(x,y), (x,y)...]
if xmin is None:
print ("xmin = ", min([x[0] for x in points]) )
xmin = min([x[0] for x in points])
if xmax is None:
print ("xmax = ", max([x[0] for x in points]) )
xmax = max([x[0] for x in points])
if ymin is None:
print ("ymin = ", min([x[1] for x in points]) )
ymin = min([x[1] for x in points])
if ymax is None:
print ("ymax = ", max([x[1] for x in points]) )
ymax = max([x[1] for x in points])
x_step = (xmax-xmin)/x_nbins
y_step = (ymax-ymin)/y_nbins
data = []
for i in range(x_nbins):
data.append([0]*y_nbins)
for p in points:
i,j = calculate_indexes(p[0], p[1], xmin, x_step, ymin, y_step)
data[i][j] += 1
return cls(data, xmin, xmax, ymin, ymax)
def set_interpolation_f(self):
x = []
y = []
for target_list, vmin, vmax, vstep in [(x, self.xmin, self.xmax, self.x_step),
(y, self.ymin, self.ymax, self.y_step)]:
current_tick = vmin - vstep/2
while current_tick <= vmax + vstep/2 + 1e-6:
target_list.append(current_tick)
current_tick += vstep
z = []
# print "x,y", x, y
for i in range(len(self.g[0])+2):
z.append([0] * (len(self.g)+2) )
for i in range(len(z)):
for j in range(len(z)):
# figure out where to get value
ii = i-1
jj = j-1
if i == 0:
ii = len(self.g)-1
if i == len(z) - 1:
ii = 0
if j == 0:
jj = len(self.g[0])-1
if j == len(z) - 1:
jj = 0
z[i][j] = self.g[jj][ii]
# print ("len(x)", len(x))
# print ("len(y)", len(y))
# print ("len(z)", len(z), len(z[0]))
# print ("x", x)
# print ("y", y)
self.interpolation_f = interpolate.interp2d(x,y,z, kind='linear')
def get_interpolated_score(self, x, y):
# i, j = self._calc_ij(x,y)
# return [self.g[i][j]]
if self.interpolation_f is None:
self.set_interpolation_f()
# int_sc = self.interpolation_f([point[0]], [point[1]])
# print "Get interp score:", point, int_sc, self.g[i][j]
return self.interpolation_f([x],[y])[0]
# return [self.g[i][j], self.interpolation_f([point[0]], [point[1]])[0]]
def plot_distribution(self, fname, title="Default title"):
npz = np.array(self.g)
npz = np.swapaxes(npz, 0, 1)
# if you want ramachandran-like scaling
npz = npz ** 0.25
npz.astype(float)
p = draw_ramachandran_plot(
points=[],
rotarama_data=npz,
position_type=0, # RAMA_GENERAL
title=title,
show_labels=False,
markerfacecolor="white",
markeredgecolor="black",
show_filling=True,
show_contours=False,
markersize=10,
point_style='bo')
# fname = "4sc_%s_%s.png" % (k, r_type)
print ("saving", fname)
p.save_image(fname, dpi=300)
|
[
"math.floor",
"mmtbx.validation.ramalyze.draw_ramachandran_plot",
"scipy.interpolate.interp2d",
"numpy.array",
"numpy.swapaxes"
] |
[((253, 284), 'math.floor', 'math.floor', (['((x - xmin) / x_step)'], {}), '((x - xmin) / x_step)\n', (263, 284), False, 'import math\n'), ((289, 320), 'math.floor', 'math.floor', (['((y - ymin) / y_step)'], {}), '((y - ymin) / y_step)\n', (299, 320), False, 'import math\n'), ((3135, 3179), 'scipy.interpolate.interp2d', 'interpolate.interp2d', (['x', 'y', 'z'], {'kind': '"""linear"""'}), "(x, y, z, kind='linear')\n", (3155, 3179), False, 'from scipy import interpolate\n'), ((3665, 3681), 'numpy.array', 'np.array', (['self.g'], {}), '(self.g)\n', (3673, 3681), True, 'import numpy as np\n'), ((3692, 3714), 'numpy.swapaxes', 'np.swapaxes', (['npz', '(0)', '(1)'], {}), '(npz, 0, 1)\n', (3703, 3714), True, 'import numpy as np\n'), ((3811, 4049), 'mmtbx.validation.ramalyze.draw_ramachandran_plot', 'draw_ramachandran_plot', ([], {'points': '[]', 'rotarama_data': 'npz', 'position_type': '(0)', 'title': 'title', 'show_labels': '(False)', 'markerfacecolor': '"""white"""', 'markeredgecolor': '"""black"""', 'show_filling': '(True)', 'show_contours': '(False)', 'markersize': '(10)', 'point_style': '"""bo"""'}), "(points=[], rotarama_data=npz, position_type=0, title\n =title, show_labels=False, markerfacecolor='white', markeredgecolor=\n 'black', show_filling=True, show_contours=False, markersize=10,\n point_style='bo')\n", (3833, 4049), False, 'from mmtbx.validation.ramalyze import draw_ramachandran_plot\n')]
|
import numpy as np
from tictactoe import search
from tictactoe.search import Minimax, SearchAlgorithm
from tictactoe.board import Board, Winner
def app(algorithm: SearchAlgorithm, player: bool):
b = Board(np.full((3,3), None))
if not player:
print(str(b))
while b.winner == Winner.UNDETERMINED:
if b.next == player:
b = algorithm.search(b)
print("\n")
print(str(b))
else:
print("Your move:")
i = int(input("Enter X coordinate..."))
j = int(input("Enter Y coordinate..."))
b = b.apply_move(i, j)
s = "DRAW"
if b.winner == Winner.X:
s = "I WON" if player else "YOU WON"
elif b.winner == Winner.O:
s = "YOU WON" if player else "I WON"
print("**** " + s + " ****")
if __name__ == "__main__":
app(Minimax(False, 5), False)
|
[
"numpy.full",
"tictactoe.search.Minimax"
] |
[((211, 232), 'numpy.full', 'np.full', (['(3, 3)', 'None'], {}), '((3, 3), None)\n', (218, 232), True, 'import numpy as np\n'), ((864, 881), 'tictactoe.search.Minimax', 'Minimax', (['(False)', '(5)'], {}), '(False, 5)\n', (871, 881), False, 'from tictactoe.search import Minimax, SearchAlgorithm\n')]
|
from copy import deepcopy
import numpy as np
from bridge_sim.bridges.bridge_705 import bridge_705
from bridge_sim.configs import opensees_default
from bridge_sim.vehicles import truck1
from bridge_sim.model import PointLoad
from bridge_sim.util import flatten
c = opensees_default(bridge_705(0.5))
entering_time = truck1.time_entering_bridge(bridge=c.bridge)
entered_time = truck1.time_entered_bridge(bridge=c.bridge)
leaving_time = truck1.time_leaving_bridge(bridge=c.bridge)
left_time = truck1.time_left_bridge(bridge=c.bridge)
wagen1_top_lane = deepcopy(truck1)
wagen1_top_lane.lane = 1
assert truck1.lane != wagen1_top_lane.lane
assert truck1.init_x_frac == 0
def test_mv_vehicle_time_leaving_bridge():
# Bottom lane.
assert c.bridge.length / truck1.mps == truck1.time_leaving_bridge(c.bridge)
# Top lane.
assert c.bridge.length / wagen1_top_lane.mps == wagen1_top_lane.time_leaving_bridge(
c.bridge
)
def test_mv_vehicle_time_left_bridge():
# Bottom lane.
time_to_leave = truck1.time_left_bridge(c.bridge) - truck1.time_leaving_bridge(
c.bridge
)
assert np.isclose(truck1.length / truck1.mps, time_to_leave)
# Top lane.
time_to_leave = wagen1_top_lane.time_left_bridge(
c.bridge
) - wagen1_top_lane.time_leaving_bridge(c.bridge)
assert np.isclose(wagen1_top_lane.length / wagen1_top_lane.mps, time_to_leave)
def test_to_point_load_pw():
# As Truck 1 enters the bridge.
wagen1_times = np.linspace(entering_time, entered_time - 0.001, 100)
for time in wagen1_times:
loads = truck1.to_point_load_pw(time=time, bridge=c.bridge)
flat_loads = flatten(loads, PointLoad)
total_kn = sum(map(lambda l: l.load, flat_loads))
assert total_kn < truck1.total_kn()
# As Truck 1 is fully on the bridge.
wagen1_times = np.linspace(entered_time, leaving_time, 100)
for time in wagen1_times:
loads = truck1.to_point_load_pw(time=time, bridge=c.bridge)
flat_loads = flatten(loads, PointLoad)
total_kn = sum(map(lambda l: l.load, flat_loads))
assert total_kn == truck1.total_kn()
# As Truck 1 is leaving the bridge.
wagen1_times = np.linspace(leaving_time + 0.001, left_time, 100)
for time in wagen1_times:
loads = truck1.to_point_load_pw(time=time, bridge=c.bridge)
flat_loads = flatten(loads, PointLoad)
total_kn = sum(map(lambda l: l.load, flat_loads))
assert total_kn < truck1.total_kn()
def test_wheel_to_wheel_track_xs():
og_il_num_loads = c.il_num_loads
c.il_num_loads = 10
# Very beginning.
(x0, f0), (x1, f1) = truck1.to_wheel_track_xs(c=c, wheel_x=0)
assert x0 == c.bridge.x_min
assert f0 == 1
assert f1 == 0
# Very end.
(x0, f0), (x1, f1) = truck1.to_wheel_track_xs(c=c, wheel_x=c.bridge.x_max)
assert x0 == c.bridge.x_max
assert f0 == 1
assert f1 == 0
# In the middle.
(x0, f0), (x1, f1) = truck1.to_wheel_track_xs(c=c, wheel_x=c.bridge.length / 2)
assert f0 == 0.5
assert f1 == 0.5
bucket_width = c.bridge.length / (c.il_num_loads - 1)
assert x0 == np.around(bucket_width * 4, 6)
assert x1 == np.around(bucket_width * 5, 6)
# Near the beginning (exact match).
(x0, f0), (x1, f1) = truck1.to_wheel_track_xs(
c=c, wheel_x=c.bridge.length / (c.il_num_loads - 1),
)
# The fraction might not be exactly 1, because of rounding of the wheel
# track positions.
assert np.around(f0, 4) == 1
assert np.around(f1, 4) == 0
assert x0 == np.around(bucket_width, 6)
# Near the beginning (a little more).
(x0, f0), (x1, f1) = truck1.to_wheel_track_xs(
c=c, wheel_x=c.bridge.length / (c.il_num_loads - 1) + 0.001,
)
assert f0 != 0
assert f0 != 1
assert f0 + f1 == 1
assert f0 > f1
assert x0 == np.around(bucket_width, 6)
assert x1 == np.around(bucket_width * 2, 6)
c.il_num_loads = og_il_num_loads
def test_to_wheel_track_loads():
# As Truck 1 enters the bridge, total load is less than Truck 1.
enter_times = np.linspace(entering_time, entered_time - 0.001, 100)
for time in enter_times:
loads = truck1.to_wheel_track_loads(c=c, time=time)
flat_loads = flatten(loads, PointLoad)
total_kn = sum(map(lambda l: l.load, flat_loads))
assert total_kn < truck1.total_kn()
# As Truck 1 is fully on the bridge, total load equals that of Truck 1.
on_times = np.linspace(entered_time, leaving_time, 100)
truck_front_x = np.arange(8, 102)
more_times = np.array([truck1.time_at(x=x, bridge=c.bridge) for x in truck_front_x])
on_times = np.concatenate((on_times, more_times))
for time in on_times:
loads = truck1.to_wheel_track_loads(c=c, time=time)
flat_loads = flatten(loads, PointLoad)
total_kn = sum(map(lambda l: l.load, flat_loads))
assert np.isclose(total_kn, truck1.total_kn())
# As Truck 1 is leaving the bridge, total load is less than Truck 1.
leave_times = np.linspace(leaving_time + 0.001, left_time, 100)
for time in leave_times:
loads = truck1.to_wheel_track_loads(c=c, time=time)
flat_loads = flatten(loads, PointLoad)
total_kn = sum(map(lambda l: l.load, flat_loads))
assert total_kn < truck1.total_kn()
def test_wheel_track_loads_on_track():
wheel_track_xs = c.bridge.wheel_track_xs(c)
enter_times = np.linspace(entering_time, entered_time - 0.001, 100)
on_times = np.linspace(entered_time, leaving_time, 100)
leave_times = np.linspace(leaving_time + 0.001, left_time, 100)
for time in np.concatenate((enter_times, on_times, leave_times)):
loads = truck1.to_wheel_track_loads(c=c, time=time, flat=True)
for load in loads:
assert any(np.isclose(load.x, x) for x in wheel_track_xs)
def test_compare_to_wheel_track_and_to_point_load():
truck_front_x = np.arange(1, 116.1, 1)
times = [truck1.time_at(x=x, bridge=c.bridge) for x in truck_front_x]
loads_wt = [
[v.to_wheel_track_loads(c=c, time=time) for v in [truck1]] for time in times
]
# print_w(f"Not using fractions of wheel track bins in simulation")
loads_pw = [
[v.to_point_load_pw(time=time, bridge=c.bridge) for v in [truck1]]
for time in times
]
def sum_loads(loads):
"""Sum of the load intensity (kn) of all given loads."""
return sum(map(lambda l: l.load, flatten(loads, PointLoad)))
for i in range(len(times)):
# Assert that the total load intensity is equal for both functions.
wt, pw = np.array(loads_wt[i]), np.array(loads_pw[i])
sum_wt = np.around(sum_loads(wt), 5)
sum_pw = np.around(sum_loads(pw), 5)
assert sum_wt == sum_pw
# Assert the shape of fem is as expected.
assert wt.shape[0] == 1 # One vehicles.
assert pw.shape[0] == 1 # One vehicles.
# Assert that both loads have equal amount of axles.
assert wt.shape[1] == pw.shape[1]
# Assert that at each time, the shape of loads is as expected.
if wt.shape[1] >= 1:
assert len(wt.shape) >= 3
assert len(pw.shape) == 3
assert wt.shape[2] == 2
assert pw.shape[2] == 2
if len(wt.shape) == 4:
assert wt.shape[3] == 2
# Assert that x positions of loads match up.
for axle_i in range(wt.shape[1]):
for wt_load, pw_load in zip(wt[0][axle_i], pw[0][axle_i]):
# Total kn should be equal between both functions..
wt_kn = sum_loads(wt_load)
assert np.isclose(wt_kn, pw_load.load)
# ..x positions should match up too.
if len(wt_load) == 1:
assert np.isclose(wt_load[0].x, pw_load.x)
elif len(wt_load) == 2:
assert wt_load[0].x < pw_load.x < wt_load[1].x
else:
assert False
# def test_mv_vehicle_to_point_loads():
# wagen1 = get_wagen1()
# loads = wagen1.to_point_loads(time=2, bridge=c.bridge)
# assert len(loads) == 4
# assert loads[0][0].kn == 5050
# assert loads[0][1].kn == 5300
# assert loads[0][0].z_frac > loads[0][1].z_frac
# def test_mv_vehicle_time_at():
# wagen1 = get_wagen1()
# mps = wagen1.kmph / 3.6
# assert wagen1.time_at(x=20, bridge=c.bridge) == 20 / mps
# assert wagen1.time_at(x=102.75, bridge=c.bridge) == 102.75 / mps
|
[
"bridge_sim.vehicles.truck1.to_wheel_track_xs",
"copy.deepcopy",
"bridge_sim.util.flatten",
"bridge_sim.vehicles.truck1.time_left_bridge",
"bridge_sim.bridges.bridge_705.bridge_705",
"bridge_sim.vehicles.truck1.to_point_load_pw",
"bridge_sim.vehicles.truck1.total_kn",
"bridge_sim.vehicles.truck1.time_entering_bridge",
"numpy.isclose",
"numpy.around",
"numpy.arange",
"bridge_sim.vehicles.truck1.time_entered_bridge",
"numpy.linspace",
"bridge_sim.vehicles.truck1.time_at",
"bridge_sim.vehicles.truck1.to_wheel_track_loads",
"bridge_sim.vehicles.truck1.time_leaving_bridge",
"numpy.array",
"numpy.concatenate"
] |
[((316, 360), 'bridge_sim.vehicles.truck1.time_entering_bridge', 'truck1.time_entering_bridge', ([], {'bridge': 'c.bridge'}), '(bridge=c.bridge)\n', (343, 360), False, 'from bridge_sim.vehicles import truck1\n'), ((376, 419), 'bridge_sim.vehicles.truck1.time_entered_bridge', 'truck1.time_entered_bridge', ([], {'bridge': 'c.bridge'}), '(bridge=c.bridge)\n', (402, 419), False, 'from bridge_sim.vehicles import truck1\n'), ((435, 478), 'bridge_sim.vehicles.truck1.time_leaving_bridge', 'truck1.time_leaving_bridge', ([], {'bridge': 'c.bridge'}), '(bridge=c.bridge)\n', (461, 478), False, 'from bridge_sim.vehicles import truck1\n'), ((491, 531), 'bridge_sim.vehicles.truck1.time_left_bridge', 'truck1.time_left_bridge', ([], {'bridge': 'c.bridge'}), '(bridge=c.bridge)\n', (514, 531), False, 'from bridge_sim.vehicles import truck1\n'), ((550, 566), 'copy.deepcopy', 'deepcopy', (['truck1'], {}), '(truck1)\n', (558, 566), False, 'from copy import deepcopy\n'), ((283, 298), 'bridge_sim.bridges.bridge_705.bridge_705', 'bridge_705', (['(0.5)'], {}), '(0.5)\n', (293, 298), False, 'from bridge_sim.bridges.bridge_705 import bridge_705\n'), ((1117, 1170), 'numpy.isclose', 'np.isclose', (['(truck1.length / truck1.mps)', 'time_to_leave'], {}), '(truck1.length / truck1.mps, time_to_leave)\n', (1127, 1170), True, 'import numpy as np\n'), ((1323, 1394), 'numpy.isclose', 'np.isclose', (['(wagen1_top_lane.length / wagen1_top_lane.mps)', 'time_to_leave'], {}), '(wagen1_top_lane.length / wagen1_top_lane.mps, time_to_leave)\n', (1333, 1394), True, 'import numpy as np\n'), ((1481, 1534), 'numpy.linspace', 'np.linspace', (['entering_time', '(entered_time - 0.001)', '(100)'], {}), '(entering_time, entered_time - 0.001, 100)\n', (1492, 1534), True, 'import numpy as np\n'), ((1842, 1886), 'numpy.linspace', 'np.linspace', (['entered_time', 'leaving_time', '(100)'], {}), '(entered_time, leaving_time, 100)\n', (1853, 1886), True, 'import numpy as np\n'), ((2194, 2243), 'numpy.linspace', 'np.linspace', (['(leaving_time + 0.001)', 'left_time', '(100)'], {}), '(leaving_time + 0.001, left_time, 100)\n', (2205, 2243), True, 'import numpy as np\n'), ((2637, 2677), 'bridge_sim.vehicles.truck1.to_wheel_track_xs', 'truck1.to_wheel_track_xs', ([], {'c': 'c', 'wheel_x': '(0)'}), '(c=c, wheel_x=0)\n', (2661, 2677), False, 'from bridge_sim.vehicles import truck1\n'), ((2789, 2842), 'bridge_sim.vehicles.truck1.to_wheel_track_xs', 'truck1.to_wheel_track_xs', ([], {'c': 'c', 'wheel_x': 'c.bridge.x_max'}), '(c=c, wheel_x=c.bridge.x_max)\n', (2813, 2842), False, 'from bridge_sim.vehicles import truck1\n'), ((2959, 3017), 'bridge_sim.vehicles.truck1.to_wheel_track_xs', 'truck1.to_wheel_track_xs', ([], {'c': 'c', 'wheel_x': '(c.bridge.length / 2)'}), '(c=c, wheel_x=c.bridge.length / 2)\n', (2983, 3017), False, 'from bridge_sim.vehicles import truck1\n'), ((3279, 3356), 'bridge_sim.vehicles.truck1.to_wheel_track_xs', 'truck1.to_wheel_track_xs', ([], {'c': 'c', 'wheel_x': '(c.bridge.length / (c.il_num_loads - 1))'}), '(c=c, wheel_x=c.bridge.length / (c.il_num_loads - 1))\n', (3303, 3356), False, 'from bridge_sim.vehicles import truck1\n'), ((3648, 3738), 'bridge_sim.vehicles.truck1.to_wheel_track_xs', 'truck1.to_wheel_track_xs', ([], {'c': 'c', 'wheel_x': '(c.bridge.length / (c.il_num_loads - 1) + 0.001)'}), '(c=c, wheel_x=c.bridge.length / (c.il_num_loads - 1\n ) + 0.001)\n', (3672, 3738), False, 'from bridge_sim.vehicles import truck1\n'), ((4081, 4134), 'numpy.linspace', 'np.linspace', (['entering_time', '(entered_time - 0.001)', '(100)'], {}), '(entering_time, entered_time - 0.001, 100)\n', (4092, 4134), True, 'import numpy as np\n'), ((4464, 4508), 'numpy.linspace', 'np.linspace', (['entered_time', 'leaving_time', '(100)'], {}), '(entered_time, leaving_time, 100)\n', (4475, 4508), True, 'import numpy as np\n'), ((4529, 4546), 'numpy.arange', 'np.arange', (['(8)', '(102)'], {}), '(8, 102)\n', (4538, 4546), True, 'import numpy as np\n'), ((4651, 4689), 'numpy.concatenate', 'np.concatenate', (['(on_times, more_times)'], {}), '((on_times, more_times))\n', (4665, 4689), True, 'import numpy as np\n'), ((5027, 5076), 'numpy.linspace', 'np.linspace', (['(leaving_time + 0.001)', 'left_time', '(100)'], {}), '(leaving_time + 0.001, left_time, 100)\n', (5038, 5076), True, 'import numpy as np\n'), ((5422, 5475), 'numpy.linspace', 'np.linspace', (['entering_time', '(entered_time - 0.001)', '(100)'], {}), '(entering_time, entered_time - 0.001, 100)\n', (5433, 5475), True, 'import numpy as np\n'), ((5491, 5535), 'numpy.linspace', 'np.linspace', (['entered_time', 'leaving_time', '(100)'], {}), '(entered_time, leaving_time, 100)\n', (5502, 5535), True, 'import numpy as np\n'), ((5554, 5603), 'numpy.linspace', 'np.linspace', (['(leaving_time + 0.001)', 'left_time', '(100)'], {}), '(leaving_time + 0.001, left_time, 100)\n', (5565, 5603), True, 'import numpy as np\n'), ((5620, 5672), 'numpy.concatenate', 'np.concatenate', (['(enter_times, on_times, leave_times)'], {}), '((enter_times, on_times, leave_times))\n', (5634, 5672), True, 'import numpy as np\n'), ((5917, 5939), 'numpy.arange', 'np.arange', (['(1)', '(116.1)', '(1)'], {}), '(1, 116.1, 1)\n', (5926, 5939), True, 'import numpy as np\n'), ((773, 809), 'bridge_sim.vehicles.truck1.time_leaving_bridge', 'truck1.time_leaving_bridge', (['c.bridge'], {}), '(c.bridge)\n', (799, 809), False, 'from bridge_sim.vehicles import truck1\n'), ((1019, 1052), 'bridge_sim.vehicles.truck1.time_left_bridge', 'truck1.time_left_bridge', (['c.bridge'], {}), '(c.bridge)\n', (1042, 1052), False, 'from bridge_sim.vehicles import truck1\n'), ((1055, 1091), 'bridge_sim.vehicles.truck1.time_leaving_bridge', 'truck1.time_leaving_bridge', (['c.bridge'], {}), '(c.bridge)\n', (1081, 1091), False, 'from bridge_sim.vehicles import truck1\n'), ((1581, 1632), 'bridge_sim.vehicles.truck1.to_point_load_pw', 'truck1.to_point_load_pw', ([], {'time': 'time', 'bridge': 'c.bridge'}), '(time=time, bridge=c.bridge)\n', (1604, 1632), False, 'from bridge_sim.vehicles import truck1\n'), ((1654, 1679), 'bridge_sim.util.flatten', 'flatten', (['loads', 'PointLoad'], {}), '(loads, PointLoad)\n', (1661, 1679), False, 'from bridge_sim.util import flatten\n'), ((1933, 1984), 'bridge_sim.vehicles.truck1.to_point_load_pw', 'truck1.to_point_load_pw', ([], {'time': 'time', 'bridge': 'c.bridge'}), '(time=time, bridge=c.bridge)\n', (1956, 1984), False, 'from bridge_sim.vehicles import truck1\n'), ((2006, 2031), 'bridge_sim.util.flatten', 'flatten', (['loads', 'PointLoad'], {}), '(loads, PointLoad)\n', (2013, 2031), False, 'from bridge_sim.util import flatten\n'), ((2290, 2341), 'bridge_sim.vehicles.truck1.to_point_load_pw', 'truck1.to_point_load_pw', ([], {'time': 'time', 'bridge': 'c.bridge'}), '(time=time, bridge=c.bridge)\n', (2313, 2341), False, 'from bridge_sim.vehicles import truck1\n'), ((2363, 2388), 'bridge_sim.util.flatten', 'flatten', (['loads', 'PointLoad'], {}), '(loads, PointLoad)\n', (2370, 2388), False, 'from bridge_sim.util import flatten\n'), ((3135, 3165), 'numpy.around', 'np.around', (['(bucket_width * 4)', '(6)'], {}), '(bucket_width * 4, 6)\n', (3144, 3165), True, 'import numpy as np\n'), ((3183, 3213), 'numpy.around', 'np.around', (['(bucket_width * 5)', '(6)'], {}), '(bucket_width * 5, 6)\n', (3192, 3213), True, 'import numpy as np\n'), ((3482, 3498), 'numpy.around', 'np.around', (['f0', '(4)'], {}), '(f0, 4)\n', (3491, 3498), True, 'import numpy as np\n'), ((3515, 3531), 'numpy.around', 'np.around', (['f1', '(4)'], {}), '(f1, 4)\n', (3524, 3531), True, 'import numpy as np\n'), ((3554, 3580), 'numpy.around', 'np.around', (['bucket_width', '(6)'], {}), '(bucket_width, 6)\n', (3563, 3580), True, 'import numpy as np\n'), ((3847, 3873), 'numpy.around', 'np.around', (['bucket_width', '(6)'], {}), '(bucket_width, 6)\n', (3856, 3873), True, 'import numpy as np\n'), ((3891, 3921), 'numpy.around', 'np.around', (['(bucket_width * 2)', '(6)'], {}), '(bucket_width * 2, 6)\n', (3900, 3921), True, 'import numpy as np\n'), ((4180, 4223), 'bridge_sim.vehicles.truck1.to_wheel_track_loads', 'truck1.to_wheel_track_loads', ([], {'c': 'c', 'time': 'time'}), '(c=c, time=time)\n', (4207, 4223), False, 'from bridge_sim.vehicles import truck1\n'), ((4245, 4270), 'bridge_sim.util.flatten', 'flatten', (['loads', 'PointLoad'], {}), '(loads, PointLoad)\n', (4252, 4270), False, 'from bridge_sim.util import flatten\n'), ((4732, 4775), 'bridge_sim.vehicles.truck1.to_wheel_track_loads', 'truck1.to_wheel_track_loads', ([], {'c': 'c', 'time': 'time'}), '(c=c, time=time)\n', (4759, 4775), False, 'from bridge_sim.vehicles import truck1\n'), ((4797, 4822), 'bridge_sim.util.flatten', 'flatten', (['loads', 'PointLoad'], {}), '(loads, PointLoad)\n', (4804, 4822), False, 'from bridge_sim.util import flatten\n'), ((5122, 5165), 'bridge_sim.vehicles.truck1.to_wheel_track_loads', 'truck1.to_wheel_track_loads', ([], {'c': 'c', 'time': 'time'}), '(c=c, time=time)\n', (5149, 5165), False, 'from bridge_sim.vehicles import truck1\n'), ((5187, 5212), 'bridge_sim.util.flatten', 'flatten', (['loads', 'PointLoad'], {}), '(loads, PointLoad)\n', (5194, 5212), False, 'from bridge_sim.util import flatten\n'), ((5690, 5744), 'bridge_sim.vehicles.truck1.to_wheel_track_loads', 'truck1.to_wheel_track_loads', ([], {'c': 'c', 'time': 'time', 'flat': '(True)'}), '(c=c, time=time, flat=True)\n', (5717, 5744), False, 'from bridge_sim.vehicles import truck1\n'), ((5953, 5989), 'bridge_sim.vehicles.truck1.time_at', 'truck1.time_at', ([], {'x': 'x', 'bridge': 'c.bridge'}), '(x=x, bridge=c.bridge)\n', (5967, 5989), False, 'from bridge_sim.vehicles import truck1\n'), ((1764, 1781), 'bridge_sim.vehicles.truck1.total_kn', 'truck1.total_kn', ([], {}), '()\n', (1779, 1781), False, 'from bridge_sim.vehicles import truck1\n'), ((2117, 2134), 'bridge_sim.vehicles.truck1.total_kn', 'truck1.total_kn', ([], {}), '()\n', (2132, 2134), False, 'from bridge_sim.vehicles import truck1\n'), ((2473, 2490), 'bridge_sim.vehicles.truck1.total_kn', 'truck1.total_kn', ([], {}), '()\n', (2488, 2490), False, 'from bridge_sim.vehicles import truck1\n'), ((4355, 4372), 'bridge_sim.vehicles.truck1.total_kn', 'truck1.total_kn', ([], {}), '()\n', (4370, 4372), False, 'from bridge_sim.vehicles import truck1\n'), ((4574, 4610), 'bridge_sim.vehicles.truck1.time_at', 'truck1.time_at', ([], {'x': 'x', 'bridge': 'c.bridge'}), '(x=x, bridge=c.bridge)\n', (4588, 4610), False, 'from bridge_sim.vehicles import truck1\n'), ((4917, 4934), 'bridge_sim.vehicles.truck1.total_kn', 'truck1.total_kn', ([], {}), '()\n', (4932, 4934), False, 'from bridge_sim.vehicles import truck1\n'), ((5297, 5314), 'bridge_sim.vehicles.truck1.total_kn', 'truck1.total_kn', ([], {}), '()\n', (5312, 5314), False, 'from bridge_sim.vehicles import truck1\n'), ((6605, 6626), 'numpy.array', 'np.array', (['loads_wt[i]'], {}), '(loads_wt[i])\n', (6613, 6626), True, 'import numpy as np\n'), ((6628, 6649), 'numpy.array', 'np.array', (['loads_pw[i]'], {}), '(loads_pw[i])\n', (6636, 6649), True, 'import numpy as np\n'), ((6451, 6476), 'bridge_sim.util.flatten', 'flatten', (['loads', 'PointLoad'], {}), '(loads, PointLoad)\n', (6458, 6476), False, 'from bridge_sim.util import flatten\n'), ((5795, 5816), 'numpy.isclose', 'np.isclose', (['load.x', 'x'], {}), '(load.x, x)\n', (5805, 5816), True, 'import numpy as np\n'), ((7670, 7701), 'numpy.isclose', 'np.isclose', (['wt_kn', 'pw_load.load'], {}), '(wt_kn, pw_load.load)\n', (7680, 7701), True, 'import numpy as np\n'), ((7832, 7867), 'numpy.isclose', 'np.isclose', (['wt_load[0].x', 'pw_load.x'], {}), '(wt_load[0].x, pw_load.x)\n', (7842, 7867), True, 'import numpy as np\n')]
|
import rospy
import numpy as np
import pcl
from tools import *
#Import error, but we don't really used this file anymore
#from scipy.linalg import lstsq
from std_msgs.msg import Header, Int64
from geometry_msgs.msg import Point
from pointcloud_operations import filtering
from sensor_msgs.msg import PointCloud2
from sensor_msgs import point_cloud2
from gpd.msg import CloudIndexed
class GpdGrasps(object):
raw_cloud = []
filtered_cloud = pcl.PointCloud()
message_counter = 0
def __init__(self, max_messages=8):
self.max_messages = max_messages
pevent("Waiting for pointcloud")
rospy.Subscriber("/camera/depth_registered/points", PointCloud2, self.cloud_callback)
# rospy.Subscriber("/xtion/depth_registered/points", PointCloud2, self.cloud_callback)
rospy.sleep(3)
def cloud_callback(self, msg):
if self.message_counter < self.max_messages:
self.message_counter += 1
for p in point_cloud2.read_points(msg, skip_nans=True):
self.raw_cloud.append([p[0], p[1], p[2]])
def filter_cloud(self):
# Wait for point cloud to arrive.
while self.message_counter < self.max_messages:
rospy.sleep(0.01)
# Do filtering until filtering returns some points or user stops the script
while self.filtered_cloud.size == 0:
self.filtered_cloud = filtering(self.raw_cloud)
self.raw_cloud = None
if self.filtered_cloud.size == 0:
perror("PointCloud after filtering is empty. Are you sure that object is visible for the robot? \nTrying again")
def extract_indices(self):
# Extract the nonplanar indices. Uses a least squares fit AX = b. Plane equation: z = ax + by + c.
X = self.filtered_cloud.to_array()
A = np.c_[X[:, 0], X[:, 1], np.ones(X.shape[0])]
C, _, _, _ = lstsq(A, X[:, 2])
a, b, c, d = C[0], C[1], -1., C[2] # coefficients of the form: a*x + b*y + c*z + d = 0.
dist = ((a * X[:, 0] + b * X[:, 1] + d) - X[:, 2]) ** 2
# err = dist.sum()
idx = np.where(dist > 0.001)
return X, idx
def generate_cloud_indexed_msg(self):
np_cloud, idx = self.extract_indices()
msg = CloudIndexed()
header = Header()
# header.frame_id = "xtion_rgb_optical_frame"
header.frame_id = "camera_depth_optical_frame"
header.stamp = rospy.Time.now()
msg.cloud_sources.cloud = point_cloud2.create_cloud_xyz32(header, np_cloud.tolist())
msg.cloud_sources.view_points.append(Point(0, 0, 0))
for i in xrange(np_cloud.shape[0]):
msg.cloud_sources.camera_source.append(Int64(0))
for i in idx[0]:
msg.indices.append(Int64(i))
return msg
def publish_indexed_cloud(self):
msg = self.generate_cloud_indexed_msg()
pub = rospy.Publisher('cloud_indexed', CloudIndexed, queue_size=1, latch=True)
pub.publish(msg)
rospy.sleep(3.14)
pevent('Published cloud with ' + str(len(msg.indices)) + ' indices')
pub.unregister()
|
[
"std_msgs.msg.Int64",
"rospy.Subscriber",
"rospy.Time.now",
"gpd.msg.CloudIndexed",
"std_msgs.msg.Header",
"rospy.Publisher",
"rospy.sleep",
"numpy.ones",
"numpy.where",
"pointcloud_operations.filtering",
"geometry_msgs.msg.Point",
"sensor_msgs.point_cloud2.read_points",
"pcl.PointCloud"
] |
[((449, 465), 'pcl.PointCloud', 'pcl.PointCloud', ([], {}), '()\n', (463, 465), False, 'import pcl\n'), ((621, 711), 'rospy.Subscriber', 'rospy.Subscriber', (['"""/camera/depth_registered/points"""', 'PointCloud2', 'self.cloud_callback'], {}), "('/camera/depth_registered/points', PointCloud2, self.\n cloud_callback)\n", (637, 711), False, 'import rospy\n'), ((809, 823), 'rospy.sleep', 'rospy.sleep', (['(3)'], {}), '(3)\n', (820, 823), False, 'import rospy\n'), ((2116, 2138), 'numpy.where', 'np.where', (['(dist > 0.001)'], {}), '(dist > 0.001)\n', (2124, 2138), True, 'import numpy as np\n'), ((2267, 2281), 'gpd.msg.CloudIndexed', 'CloudIndexed', ([], {}), '()\n', (2279, 2281), False, 'from gpd.msg import CloudIndexed\n'), ((2299, 2307), 'std_msgs.msg.Header', 'Header', ([], {}), '()\n', (2305, 2307), False, 'from std_msgs.msg import Header, Int64\n'), ((2440, 2456), 'rospy.Time.now', 'rospy.Time.now', ([], {}), '()\n', (2454, 2456), False, 'import rospy\n'), ((2904, 2976), 'rospy.Publisher', 'rospy.Publisher', (['"""cloud_indexed"""', 'CloudIndexed'], {'queue_size': '(1)', 'latch': '(True)'}), "('cloud_indexed', CloudIndexed, queue_size=1, latch=True)\n", (2919, 2976), False, 'import rospy\n'), ((3010, 3027), 'rospy.sleep', 'rospy.sleep', (['(3.14)'], {}), '(3.14)\n', (3021, 3027), False, 'import rospy\n'), ((972, 1017), 'sensor_msgs.point_cloud2.read_points', 'point_cloud2.read_points', (['msg'], {'skip_nans': '(True)'}), '(msg, skip_nans=True)\n', (996, 1017), False, 'from sensor_msgs import point_cloud2\n'), ((1216, 1233), 'rospy.sleep', 'rospy.sleep', (['(0.01)'], {}), '(0.01)\n', (1227, 1233), False, 'import rospy\n'), ((1398, 1423), 'pointcloud_operations.filtering', 'filtering', (['self.raw_cloud'], {}), '(self.raw_cloud)\n', (1407, 1423), False, 'from pointcloud_operations import filtering\n'), ((2595, 2609), 'geometry_msgs.msg.Point', 'Point', (['(0)', '(0)', '(0)'], {}), '(0, 0, 0)\n', (2600, 2609), False, 'from geometry_msgs.msg import Point\n'), ((1854, 1873), 'numpy.ones', 'np.ones', (['X.shape[0]'], {}), '(X.shape[0])\n', (1861, 1873), True, 'import numpy as np\n'), ((2707, 2715), 'std_msgs.msg.Int64', 'Int64', (['(0)'], {}), '(0)\n', (2712, 2715), False, 'from std_msgs.msg import Header, Int64\n'), ((2773, 2781), 'std_msgs.msg.Int64', 'Int64', (['i'], {}), '(i)\n', (2778, 2781), False, 'from std_msgs.msg import Header, Int64\n')]
|
import os, pickle, glob
from pandas.core.reshape.concat import concat
from common.tflogs2pandas import tflog2pandas
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
from common.gym_interface import template
if False:
def read_df(body):
dfs = []
for seed in [0,1]:
folder = f"output_data/tensorboard_oracle_random_bodies/model-{body}-sd{seed}/PPO_1"
print(f"Loading {folder} ...")
df = tflog2pandas(folder)
if df.shape[0]!=1353:
return None # Fly-away bug causes the job to abort
df = df[df["metric"]==f"eval/{body}_mean_reward"]
max_value = df["value"].max()
final_value = df.iloc[-1, df.columns.get_loc("value")]
df = pd.DataFrame({
"body": template(body),
"body_id": body,
"max_value": max_value,
"final_value": final_value,
"seed": seed,
}, index=[body])
dfs.append(df)
return pd.concat(dfs)
dfs = []
for body in np.arange(start=100, stop=200):
df = read_df(body)
if df is not None:
dfs.append(df)
df = pd.concat(dfs)
print(df)
df.to_pickle("output_data/tmp/oracle_1xx_df")
df = pd.read_pickle("output_data/tmp/oracle_1xx_df")
for body_type in [100]:
df_one_type = df[df["body"]==template(body_type)]
df_one_type = df_one_type.groupby("body_id").mean()
df_one_type = df_one_type.sort_values(by="max_value", ascending=False)
print(df_one_type.head(20))
selected = df_one_type.head(20).index.tolist()
start_id = body_type
for s in selected:
print(f"cp output_data/bodies/{s}.xml ../input_data/bodies/{start_id}.xml")
print(f"cp output_data/tmp/model-{s}-sd0.zip output_data/models/model-{start_id}-sd0.zip")
print(f"cp output_data/tmp/model-{s}-sd1.zip output_data/models/model-{start_id}-sd1.zip")
start_id += 1
|
[
"common.tflogs2pandas.tflog2pandas",
"numpy.arange",
"common.gym_interface.template",
"pandas.read_pickle",
"pandas.concat"
] |
[((1324, 1371), 'pandas.read_pickle', 'pd.read_pickle', (['"""output_data/tmp/oracle_1xx_df"""'], {}), "('output_data/tmp/oracle_1xx_df')\n", (1338, 1371), True, 'import pandas as pd\n'), ((1115, 1145), 'numpy.arange', 'np.arange', ([], {'start': '(100)', 'stop': '(200)'}), '(start=100, stop=200)\n', (1124, 1145), True, 'import numpy as np\n'), ((1238, 1252), 'pandas.concat', 'pd.concat', (['dfs'], {}), '(dfs)\n', (1247, 1252), True, 'import pandas as pd\n'), ((1070, 1084), 'pandas.concat', 'pd.concat', (['dfs'], {}), '(dfs)\n', (1079, 1084), True, 'import pandas as pd\n'), ((487, 507), 'common.tflogs2pandas.tflog2pandas', 'tflog2pandas', (['folder'], {}), '(folder)\n', (499, 507), False, 'from common.tflogs2pandas import tflog2pandas\n'), ((1429, 1448), 'common.gym_interface.template', 'template', (['body_type'], {}), '(body_type)\n', (1437, 1448), False, 'from common.gym_interface import template\n'), ((836, 850), 'common.gym_interface.template', 'template', (['body'], {}), '(body)\n', (844, 850), False, 'from common.gym_interface import template\n')]
|
# -*- coding: utf-8 -*-
# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is
# holder of all proprietary rights on this computer program.
# You can only use this computer program if you have closed
# a license agreement with MPG or you get the right to use the computer
# program from someone who is authorized to grant you that right.
# Any use of the computer program without a valid license is prohibited and
# liable to prosecution.
#
# Copyright©2019 Max-Planck-Gesellschaft zur Förderung
# der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute
# for Intelligent Systems and the Max Planck Institute for Biological
# Cybernetics. All rights reserved.
#
# Contact: <EMAIL>
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import time
try:
import cPickle as pickle
except ImportError:
import pickle
import sys
import os
import os.path as osp
from tensorboardX import SummaryWriter
import numpy as np
import torch
import open3d as o3d
from tqdm import tqdm
from collections import defaultdict
import cv2
import PIL.Image as pil_img
from PIL import ImageDraw
import json
from temp_prox.optimizers import optim_factory
import temp_prox.fitting_temp_slide as fitting
from human_body_prior.tools.model_loader import load_vposer
import scipy.sparse as sparse
def fit_temp_loadprox_slide(img,
keypoints,
marker_mask,
scan,
scan_point_num,
scene_name,
body_model,
camera,
joint_weights,
body_pose_prior,
jaw_prior,
left_hand_prior,
right_hand_prior,
shape_prior,
expr_prior,
angle_prior,
result_fn_list,
mesh_fn_list,
out_img_fn_list,
log_folder,
loss_type='smplify',
use_face=True,
use_hands=True,
data_weights=None,
body_pose_prior_weights=None,
hand_pose_prior_weights=None,
jaw_pose_prior_weights=None,
shape_weights=None,
expr_weights=None,
hand_joints_weights=None,
face_joints_weights=None,
interpenetration=True,
coll_loss_weights=None,
df_cone_height=0.5,
penalize_outside=True,
max_collisions=8,
point2plane=False,
part_segm_fn='',
rho=100,
vposer_latent_dim=32,
vposer_ckpt='',
use_joints_conf=False,
interactive=True,
visualize=False,
save_meshes=True,
dtype=torch.float32,
ign_part_pairs=None,
####################
### PROX
render_results=True,
## Depth
s2m=False,
s2m_weights=None,
m2s=False,
m2s_weights=None,
rho_s2m=1,
rho_m2s=1,
#penetration
sdf_penetration=False,
sdf_penetration_weights=0.0,
sdf_dir=None,
cam2world_dir=None,
#contact
contact=False,
contact_loss_weights=None,
contact_body_parts=None,
body_segments_dir=None,
load_scene=False,
scene_dir=None,
prox_params_dict=None,
# smooth acceleration term
smooth_acc=False,
smooth_acc_weights=None,
# smooth velocity term
smooth_vel=False,
smooth_vel_weights=None,
# motion smoothness prior term
use_motion_smooth_prior=False,
motion_prior_smooth_weights=None,
motion_smooth_model=None,
# friction term
use_friction=None,
friction_normal_weights=None,
friction_tangent_weights=None,
# motion infilling prior term
use_motion_infill_prior=False,
motion_infill_rec_weights=None,
motion_infill_contact_weights=None,
motion_infill_model=None,
infill_pretrain_weights=None,
device=None,
first_batch_flag=None,
**kwargs):
batch_size = len(img)
body_model.reset_params() # set all params as 0
if data_weights is None:
data_weights = [1, ] * 5
############################## set loss weights if not predifined ############################
if body_pose_prior_weights is None:
body_pose_prior_weights = [4.04 * 1e2, 4.04 * 1e2, 57.4, 4.78]
msg = ('Number of Body pose prior weights does not match the number of data term weights')
assert (len(data_weights) == len(body_pose_prior_weights)), msg
if use_hands:
if hand_pose_prior_weights is None:
hand_pose_prior_weights = [1e2, 5 * 1e1, 1e1, .5 * 1e1]
msg = ('Number of Body pose prior weights does not match the' +
' number of hand pose prior weights')
assert (len(hand_pose_prior_weights) == len(body_pose_prior_weights)), msg
if hand_joints_weights is None:
hand_joints_weights = [0.0, 0.0, 0.0, 1.0]
msg = ('Number of Body pose prior weights does not match the' +
' number of hand joint distance weights')
assert (len(hand_joints_weights) == len(body_pose_prior_weights)), msg
if shape_weights is None:
shape_weights = [1e2, 5 * 1e1, 1e1, .5 * 1e1]
msg = ('Number of Body pose prior weights does not match the' +
' number of Shape prior weights')
assert (len(shape_weights) == len(body_pose_prior_weights)), msg
if use_face:
if jaw_pose_prior_weights is None:
jaw_pose_prior_weights = [[x] * 3 for x in shape_weights]
else:
jaw_pose_prior_weights = map(lambda x: map(float, x.split(',')),
jaw_pose_prior_weights)
jaw_pose_prior_weights = [list(w) for w in jaw_pose_prior_weights]
msg = ('Number of Body pose prior weights does not match the' +
' number of jaw pose prior weights')
assert (len(jaw_pose_prior_weights) == len(body_pose_prior_weights)), msg
if expr_weights is None:
expr_weights = [1e2, 5 * 1e1, 1e1, .5 * 1e1]
msg = ('Number of Body pose prior weights does not match the' +
' number of Expression prior weights')
assert (len(expr_weights) == len(body_pose_prior_weights)), msg
if face_joints_weights is None:
face_joints_weights = [0.0, 0.0, 0.0, 1.0]
msg = ('Number of Body pose prior weights does not match the' +
' number of face joint distance weights')
assert (len(face_joints_weights) == len(body_pose_prior_weights)), msg
if coll_loss_weights is None:
coll_loss_weights = [0.0] * len(body_pose_prior_weights)
msg = ('Number of Body pose prior weights does not match the' +
' number of collision loss weights')
assert (len(coll_loss_weights) == len(body_pose_prior_weights)), msg
if smooth_acc:
if smooth_acc_weights is None:
smooth_acc_weights = [0.0, 0.0, 0.0, 1.0]
msg = ('Number of Body pose prior weights does not match the' +
' number of smooth loss weights')
assert (len(smooth_acc_weights) == len(body_pose_prior_weights)), msg
if smooth_vel:
if smooth_vel_weights is None:
smooth_vel_weights = [0.0, 0.0, 0.0, 1.0]
msg = ('Number of Body pose prior weights does not match the' +
' number of smooth vel loss weights')
assert (len(smooth_vel_weights) == len(body_pose_prior_weights)), msg
if use_motion_smooth_prior:
if motion_prior_smooth_weights is None:
motion_prior_smooth_weights = [0.0, 0.0, 0.0, 1.0]
msg = ('Number of Body pose prior weights does not match the' +
' number of motion prior smooth loss weights')
assert (len(motion_prior_smooth_weights) == len(body_pose_prior_weights)), msg
if use_friction:
if friction_normal_weights is None:
friction_normal_weights = [0.0, 0.0, 0.0, 1.0]
msg = ('Number of Body pose prior weights does not match the' +
' number of friction normal loss weights')
assert (len(friction_normal_weights) == len(body_pose_prior_weights)), msg
if friction_tangent_weights is None:
friction_tangent_weights = [0.0, 0.0, 0.0, 1.0]
msg = ('Number of Body pose prior weights does not match the' +
' number of friction tangent loss weights')
assert (len(friction_tangent_weights) == len(body_pose_prior_weights)), msg
if use_motion_infill_prior:
if motion_infill_rec_weights is None:
motion_infill_rec_weights = [0.0, 0.0, 0.0, 1.0]
msg = ('Number of Body pose prior weights does not match the' +
' number of motion infill rec loss weights')
assert (len(motion_infill_rec_weights) == len(body_pose_prior_weights)), msg
if motion_infill_contact_weights is None:
motion_infill_contact_weights = [0.0, 0.0, 0.0, 1.0]
msg = ('Number of Body pose prior weights does not match the' +
' number of motion infill contact loss weights')
assert (len(motion_infill_contact_weights) == len(body_pose_prior_weights)), msg
######################## init vpose embedding from 0 / load vpose model ##########################
use_vposer = kwargs.get('use_vposer', True) # True
vposer, pose_embedding = [None, ] * 2
if use_vposer:
pose_embedding = torch.zeros([batch_size, 32],
dtype=dtype, device=device,
requires_grad=True) # all 0, [bs, 32]
vposer_ckpt = osp.expandvars(vposer_ckpt)
vposer, _ = load_vposer(vposer_ckpt, vp_model='snapshot')
vposer = vposer.to(device=device)
vposer.eval()
######################## keypoints/joint_conf/scan pointclouds to device ##########################
gt_joints = keypoints[:, :, :2] # [bs, 118, 2]
if use_joints_conf: # user 2D keypoint condifence score
joints_conf = keypoints[:, :, 2].reshape(keypoints.shape[0], -1) # [bs, 118]
scan_tensor = None
if scan is not None:
scan_tensor = scan.to(device) # [bs, 20000, 3]
scan_point_num = scan_point_num.to(device) # [bs]
######################## load sdf/normals/cam2world of the current scene ##########################
sdf = None
sdf_normals = None
grid_min = None
grid_max = None
voxel_size = None
if sdf_penetration or use_friction: # True
with open(osp.join(sdf_dir, scene_name + '.json'), 'r') as f:
sdf_data = json.load(f)
grid_min = torch.tensor(np.array(sdf_data['min']), dtype=dtype, device=device) # [3]
grid_max = torch.tensor(np.array(sdf_data['max']), dtype=dtype, device=device)
grid_dim = sdf_data['dim'] # 256
voxel_size = (grid_max - grid_min) / grid_dim # [3]
sdf = np.load(osp.join(sdf_dir, scene_name + '_sdf.npy')).reshape(grid_dim, grid_dim, grid_dim)
sdf = torch.tensor(sdf, dtype=dtype, device=device) # [256, 256, 256]
# for bs>1
grid_min = grid_min.repeat(gt_joints.shape[0], 1).unsqueeze(1) # [bs, 1, 3]
grid_max = grid_max.repeat(gt_joints.shape[0], 1).unsqueeze(1) # [bs, 1, 3]
sdf = sdf.repeat(gt_joints.shape[0], 1, 1, 1).unsqueeze(1) # [bs, 256, 256, 256]
if osp.exists(osp.join(sdf_dir, scene_name + '_normals.npy')):
sdf_normals = np.load(osp.join(sdf_dir, scene_name + '_normals.npy')).reshape(grid_dim, grid_dim, grid_dim, 3) # [256, 256, 256, 3]
sdf_normals = torch.tensor(sdf_normals, dtype=dtype, device=device)
else:
print("Normals not found...")
with open(os.path.join(cam2world_dir, scene_name + '.json'), 'r') as f:
cam2world = np.array(json.load(f)) # [4, 4] last row: [0,0,0,1]
R = torch.tensor(cam2world[:3, :3].reshape(3, 3), dtype=dtype, device=device)
t = torch.tensor(cam2world[:3, 3].reshape(1, 3), dtype=dtype, device=device)
######################## Create the search tree (for self interpenetration) ##########################
search_tree = None
pen_distance = None
filter_faces = None
if interpenetration: # True
from mesh_intersection.bvh_search_tree import BVH
import mesh_intersection.loss as collisions_loss
from mesh_intersection.filter_faces import FilterFaces
assert torch.cuda.is_available(), \
'No CUDA Device! Interpenetration term can only be used with CUDA'
search_tree = BVH(max_collisions=max_collisions) # max_collisions = 128
pen_distance = \
collisions_loss.DistanceFieldPenetrationLoss(
sigma=df_cone_height, point2plane=point2plane,
vectorized=True, penalize_outside=penalize_outside)
if part_segm_fn: # True
# Read the part segmentation
part_segm_fn = os.path.expandvars(part_segm_fn)
with open(part_segm_fn, 'rb') as faces_parents_file:
face_segm_data = pickle.load(faces_parents_file,
encoding='latin1')
faces_segm = face_segm_data['segm'] # [20908] each face belongs to which body part??
faces_parents = face_segm_data['parents'] # [20908]
# Create the module used to filter invalid collision pairs
filter_faces = FilterFaces(
faces_segm=faces_segm, faces_parents=faces_parents,
ign_part_pairs=ign_part_pairs).to(device=device)
#################################### load vertex ids of contact parts ##################################
contact_verts_ids = None
contact_fric_verts_ids = []
for part in ['L_Leg', 'R_Leg', 'gluteus']:
with open(os.path.join(body_segments_dir, part + '.json'), 'r') as f:
data = json.load(f)
contact_fric_verts_ids.append(list(set(data["verts_ind"])))
contact_fric_verts_ids = np.concatenate(contact_fric_verts_ids)
if contact:
contact_verts_ids = []
for part in contact_body_parts: # ['L_Leg', 'R_Leg', 'L_Hand', 'R_Hand', 'gluteus', 'back', 'thighs']
with open(os.path.join(body_segments_dir, part + '.json'), 'r') as f:
data = json.load(f)
contact_verts_ids.append(list(set(data["verts_ind"])))
contact_verts_ids = np.concatenate(contact_verts_ids) # [1121]
############################################ load scene mesh ##################################
scene_v = None
if contact:
if scene_name is not None:
if load_scene: # True
from psbody.mesh import Mesh
scene = Mesh(filename=os.path.join(scene_dir, scene_name + '.ply'))
scene.vn = scene.estimate_vertex_normals()
scene_v = torch.tensor(scene.v[np.newaxis, :], dtype=dtype, device=device).contiguous() # [1, num_scene_verts, 3]
######################################## loss weights ###################################
opt_weights_dict = {'data_weight': data_weights,
'body_pose_weight': body_pose_prior_weights,
'shape_weight': shape_weights}
if use_face:
opt_weights_dict['face_weight'] = face_joints_weights
opt_weights_dict['expr_prior_weight'] = expr_weights
opt_weights_dict['jaw_prior_weight'] = jaw_pose_prior_weights
if use_hands:
opt_weights_dict['hand_weight'] = hand_joints_weights
opt_weights_dict['hand_prior_weight'] = hand_pose_prior_weights
if interpenetration:
opt_weights_dict['coll_loss_weight'] = coll_loss_weights
if s2m:
opt_weights_dict['s2m_weight'] = s2m_weights
if m2s:
opt_weights_dict['m2s_weight'] = m2s_weights
if sdf_penetration:
opt_weights_dict['sdf_penetration_weight'] = sdf_penetration_weights
if contact:
opt_weights_dict['contact_loss_weight'] = contact_loss_weights
if smooth_acc:
opt_weights_dict['smooth_acc_weight'] = smooth_acc_weights
if smooth_vel:
opt_weights_dict['smooth_vel_weight'] = smooth_vel_weights
if use_motion_smooth_prior:
opt_weights_dict['motion_prior_smooth_weight'] = motion_prior_smooth_weights
if use_friction:
opt_weights_dict['friction_normal_weight'] = friction_normal_weights
opt_weights_dict['friction_tangent_weight'] = friction_tangent_weights
if use_motion_infill_prior:
opt_weights_dict['motion_infill_rec_weight'] = motion_infill_rec_weights
opt_weights_dict['motion_infill_contact_weight'] = motion_infill_contact_weights
keys = opt_weights_dict.keys()
opt_weights = [dict(zip(keys, vals)) for vals in
zip(*(opt_weights_dict[k] for k in keys
if opt_weights_dict[k] is not None))]
for weight_list in opt_weights:
for key in weight_list:
weight_list[key] = torch.tensor(weight_list[key], device=device, dtype=dtype)
########################### load indices of the head of smpl-x model ###########################
with open(osp.join(body_segments_dir, 'body_mask.json'), 'r') as fp:
head_indx = np.array(json.load(fp))
N = body_model.get_num_verts()
body_indx = np.setdiff1d(np.arange(N), head_indx) # 1D array of values in `ar1` that are not in `ar2`
head_mask = np.in1d(np.arange(N), head_indx) # [10475] True/False
body_mask = np.in1d(np.arange(N), body_indx)
################################## define loss #################################
loss = fitting.create_loss(loss_type=loss_type, # 'smplify'
joint_weights=joint_weights,
rho=rho,
use_joints_conf=use_joints_conf,
use_face=use_face, use_hands=use_hands,
vposer=vposer,
pose_embedding=pose_embedding,
body_pose_prior=body_pose_prior,
shape_prior=shape_prior,
angle_prior=angle_prior,
expr_prior=expr_prior,
left_hand_prior=left_hand_prior,
right_hand_prior=right_hand_prior,
jaw_prior=jaw_prior,
interpenetration=interpenetration,
pen_distance=pen_distance,
search_tree=search_tree,
tri_filtering_module=filter_faces,
s2m=s2m,
m2s=m2s,
rho_s2m=rho_s2m,
rho_m2s=rho_m2s,
head_mask=head_mask,
body_mask=body_mask,
sdf_penetration=sdf_penetration,
voxel_size=voxel_size,
grid_min=grid_min,
grid_max=grid_max,
sdf=sdf,
sdf_normals=sdf_normals,
R=R,
t=t,
contact=contact,
contact_verts_ids=contact_verts_ids,
dtype=dtype,
smooth_acc=smooth_acc,
smooth_vel=smooth_vel,
# motion prior
use_motion_smooth_prior=use_motion_smooth_prior,
motion_smooth_model=motion_smooth_model,
# friction term
use_friction=use_friction,
# batch_size=batch_size,
contact_fric_verts_ids=contact_fric_verts_ids,
# motion infill term
use_motion_infill_prior=use_motion_infill_prior,
motion_infill_model=motion_infill_model,
infill_pretrain_weights=infill_pretrain_weights,
device=device,
**kwargs)
loss = loss.to(device
=device)
############################ fitting ####################################
with fitting.FittingMonitor(**kwargs) as monitor:
results_list = []
#################################### optimize the whole body #######################################
final_loss_val = 0
opt_start = time.time()
writer = SummaryWriter(log_dir=log_folder)
########### init from optimized prox body params
for param_name in prox_params_dict:
prox_params_dict[param_name] = prox_params_dict[param_name].detach().cpu().numpy() # each param: array, [bs, xx]
mean_betas = np.mean(prox_params_dict['betas'], axis=0)
prox_params_dict['betas'] = np.repeat(np.expand_dims(mean_betas, axis=0), gt_joints.shape[0], axis=0)
body_model.reset_params(**prox_params_dict) # check requires_grad
if use_vposer:
with torch.no_grad():
pose_embedding = torch.from_numpy(prox_params_dict['pose_embedding']).float().to(device) # pose_embedding.requires_grad=True
pose_embedding.requires_grad = True
for opt_idx, curr_weights in enumerate(tqdm(opt_weights, desc='Stage')):
for opt_idx, curr_weights in enumerate(tqdm(opt_weights, desc='Stage')):
############################ define parameters to optimize ########################
body_model.betas.requires_grad = False # todo
# body_model.parameters(): betas(bs, 10), global_orient(bs, 3), transl(bs, 3), left/right_hand_pose(bs, 12/12), jaw/leye/reye_pose(bs, 3/3/3), expression(bs, 10)
body_params = list(body_model.parameters())
final_params = list(filter(lambda x: x.requires_grad, body_params))
if use_vposer:
final_params.append(pose_embedding) # [1, 32]
body_optimizer, body_create_graph = optim_factory.create_optimizer(final_params, **kwargs)
body_optimizer.zero_grad()
########################### update weights ############################
curr_weights['bending_prior_weight'] = (3.17 * curr_weights['body_pose_weight'])
if use_hands:
joint_weights[:, 25:76] = curr_weights['hand_weight']
if use_face:
joint_weights[:, 76:] = curr_weights['face_weight']
loss.reset_loss_weights(curr_weights)
############################ fitting ###################################
closure = monitor.create_fitting_closure(
body_optimizer, body_model,
camera=camera, gt_joints=gt_joints,
joints_conf=joints_conf,
marker_mask=marker_mask,
joint_weights=joint_weights,
loss=loss, create_graph=body_create_graph,
use_vposer=use_vposer, vposer=vposer,
pose_embedding=pose_embedding,
scan_tensor=scan_tensor,
scan_point_num=scan_point_num,
scene_v=scene_v,
return_verts=True, return_full_pose=True,
writer=writer,
first_batch_flag=first_batch_flag)
if interactive:
if torch.cuda.is_available():
torch.cuda.synchronize()
stage_start = time.time()
final_loss_val = monitor.run_fitting(
body_optimizer,
closure, final_params,
body_model,
pose_embedding=pose_embedding, vposer=vposer,
use_vposer=use_vposer)
if interactive:
if torch.cuda.is_available():
torch.cuda.synchronize()
elapsed = time.time() - stage_start
if interactive:
tqdm.write('Stage {:03d} done after {:.4f} seconds'.format(opt_idx, elapsed))
if interactive:
if torch.cuda.is_available():
torch.cuda.synchronize()
elapsed = time.time() - opt_start
tqdm.write('Body fitting done after {:.4f} seconds'.format(elapsed))
tqdm.write('Body final loss val = {:.5f}'.format(final_loss_val))
########################### set results pkl formation #############################
for i in range(batch_size):
result = {'camera_' + str(key): val[i].unsqueeze(0).detach().cpu().numpy()
for key, val in camera.named_parameters()}
result.update({key: val[i].unsqueeze(0).detach().cpu().numpy()
for key, val in body_model.named_parameters()})
if use_vposer:
result['pose_embedding'] = pose_embedding[i].unsqueeze(0).detach().cpu().numpy()
body_pose = vposer.decode(
pose_embedding,
output_type='aa').view(pose_embedding.shape[0], -1) if use_vposer else None
result['body_pose'] = body_pose[i].unsqueeze(0).detach().cpu().numpy()
results_list.append(result)
########################### save results pkl file #############################
for i in range(len(results_list)):
with open(result_fn_list[i], 'wb') as result_file:
pickle.dump(results_list[i], result_file, protocol=2)
#################################### save mesh #################################
if save_meshes or render_results:
body_pose = vposer.decode(
pose_embedding,
output_type='aa').view(pose_embedding.shape[0], -1) if use_vposer else None # [bs, 63]
model_type = kwargs.get('model_type', 'smpl')
append_wrists = model_type == 'smpl' and use_vposer
if append_wrists:
wrist_pose = torch.zeros([body_pose.shape[0], 6],
dtype=body_pose.dtype,
device=body_pose.device)
body_pose = torch.cat([body_pose, wrist_pose], dim=1)
model_output = body_model(return_verts=True, body_pose=body_pose) # all elements are in [bs, ...]
vertices = model_output.vertices.detach().cpu().numpy()
import trimesh
out_mesh_list = []
for i in range(len(vertices)):
out_mesh = trimesh.Trimesh(vertices[i], body_model.faces, process=False)
if save_meshes:
out_mesh.export(mesh_fn_list[i])
out_mesh_list.append(out_mesh)
#################################### rendering #################################
if render_results:
import pyrender
# common
camera_center = np.array([951.30, 536.77])
camera_pose = np.eye(4)
camera_pose = np.array([1.0, -1.0, -1.0, 1.0]).reshape(-1, 1) * camera_pose
camera_render = pyrender.camera.IntrinsicsCamera(
fx=1060.53, fy=1060.38,
cx=camera_center[0], cy=camera_center[1])
light = pyrender.DirectionalLight(color=np.ones(3), intensity=2.0)
material = pyrender.MetallicRoughnessMaterial(
metallicFactor=0.0,
alphaMode='OPAQUE',
baseColorFactor=(1.0, 1.0, 0.9, 1.0))
_, H, W, _ = img.shape # H,W: 1080, 1920
for i in range(len(img)):
############################# redering body in img #######################
scene = pyrender.Scene(bg_color=[0.0, 0.0, 0.0, 0.0],
ambient_light=(0.3, 0.3, 0.3))
scene.add(camera_render, pose=camera_pose)
scene.add(light, pose=camera_pose)
body_mesh = pyrender.Mesh.from_trimesh(out_mesh_list[i], material=material)
scene.add(body_mesh, 'mesh')
r = pyrender.OffscreenRenderer(viewport_width=W,
viewport_height=H,
point_size=1.0)
color, _ = r.render(scene, flags=pyrender.RenderFlags.RGBA)
color = color.astype(np.float32) / 255.0
valid_mask = (color[:, :, -1] > 0)[:, :, np.newaxis]
input_img = img[i].detach().cpu().numpy()
output_img = color[:, :, :-1] * valid_mask + (1 - valid_mask) * input_img
output_img = (output_img * 255).astype(np.uint8)
# visualize 2d joints
# openpose gt points
projected_joints = gt_joints # [bs, 118, 2]
projected_joints = projected_joints[i].detach().cpu().numpy() # [118, 2]
projected_joints = projected_joints.astype(int)
body_joints = projected_joints[0:25, :] # [25, 2]
draw = ImageDraw.Draw(output_img)
for k in range(len(body_joints)):
draw.ellipse((body_joints[k][0] - 2, body_joints[k][1] - 2,
body_joints[k][0] + 2, body_joints[k][1] + 2), fill=(255, 0, 0, 0))
# optimized body
projected_joints = camera(model_output.joints) # [bs, 118, 2]
projected_joints = projected_joints[i].detach().cpu().numpy() # [118, 2]
projected_joints = projected_joints.astype(int)
body_joints = projected_joints[0:25, :] # [25, 2]
draw = ImageDraw.Draw(output_img)
for k in range(len(body_joints)):
draw.ellipse((body_joints[k][0] - 2, body_joints[k][1] - 2,
body_joints[k][0] + 2, body_joints[k][1] + 2), fill=(255, 0, 0, 0))
cur_img = pil_img.fromarray(output_img)
cur_img.save(out_img_fn_list[i])
# ############################# redering body+scene #######################
# body_mesh = pyrender.Mesh.from_trimesh(out_mesh_list[i], material=material)
# static_scene = trimesh.load(osp.join(scene_dir, scene_name + '.ply'))
# trans = np.linalg.inv(cam2world)
# static_scene.apply_transform(trans)
# static_scene_mesh = pyrender.Mesh.from_trimesh(static_scene)
#
# scene = pyrender.Scene()
# scene.add(camera_render, pose=camera_pose)
# scene.add(light, pose=camera_pose)
#
# scene.add(static_scene_mesh, 'mesh')
# scene.add(body_mesh, 'mesh')
#
# r = pyrender.OffscreenRenderer(viewport_width=W,
# viewport_height=H)
# color, _ = r.render(scene)
# color = color.astype(np.float32) / 255.0
# cur_img = pil_img.fromarray((color * 255).astype(np.uint8))
# cur_img.save(rendering_fn_list[i])
|
[
"pyrender.camera.IntrinsicsCamera",
"torch.cuda.synchronize",
"pickle.dump",
"mesh_intersection.bvh_search_tree.BVH",
"torch.cat",
"numpy.ones",
"pyrender.Mesh.from_trimesh",
"numpy.mean",
"numpy.arange",
"pickle.load",
"pyrender.Scene",
"temp_prox.optimizers.optim_factory.create_optimizer",
"torch.no_grad",
"os.path.join",
"numpy.eye",
"human_body_prior.tools.model_loader.load_vposer",
"torch.zeros",
"PIL.ImageDraw.Draw",
"tqdm.tqdm",
"trimesh.Trimesh",
"os.path.expandvars",
"torch.cuda.is_available",
"temp_prox.fitting_temp_slide.FittingMonitor",
"numpy.concatenate",
"temp_prox.fitting_temp_slide.create_loss",
"torch.from_numpy",
"tensorboardX.SummaryWriter",
"json.load",
"numpy.expand_dims",
"time.time",
"numpy.array",
"pyrender.OffscreenRenderer",
"PIL.Image.fromarray",
"pyrender.MetallicRoughnessMaterial",
"mesh_intersection.loss.DistanceFieldPenetrationLoss",
"mesh_intersection.filter_faces.FilterFaces",
"torch.tensor"
] |
[((15875, 15913), 'numpy.concatenate', 'np.concatenate', (['contact_fric_verts_ids'], {}), '(contact_fric_verts_ids)\n', (15889, 15913), True, 'import numpy as np\n'), ((19531, 20794), 'temp_prox.fitting_temp_slide.create_loss', 'fitting.create_loss', ([], {'loss_type': 'loss_type', 'joint_weights': 'joint_weights', 'rho': 'rho', 'use_joints_conf': 'use_joints_conf', 'use_face': 'use_face', 'use_hands': 'use_hands', 'vposer': 'vposer', 'pose_embedding': 'pose_embedding', 'body_pose_prior': 'body_pose_prior', 'shape_prior': 'shape_prior', 'angle_prior': 'angle_prior', 'expr_prior': 'expr_prior', 'left_hand_prior': 'left_hand_prior', 'right_hand_prior': 'right_hand_prior', 'jaw_prior': 'jaw_prior', 'interpenetration': 'interpenetration', 'pen_distance': 'pen_distance', 'search_tree': 'search_tree', 'tri_filtering_module': 'filter_faces', 's2m': 's2m', 'm2s': 'm2s', 'rho_s2m': 'rho_s2m', 'rho_m2s': 'rho_m2s', 'head_mask': 'head_mask', 'body_mask': 'body_mask', 'sdf_penetration': 'sdf_penetration', 'voxel_size': 'voxel_size', 'grid_min': 'grid_min', 'grid_max': 'grid_max', 'sdf': 'sdf', 'sdf_normals': 'sdf_normals', 'R': 'R', 't': 't', 'contact': 'contact', 'contact_verts_ids': 'contact_verts_ids', 'dtype': 'dtype', 'smooth_acc': 'smooth_acc', 'smooth_vel': 'smooth_vel', 'use_motion_smooth_prior': 'use_motion_smooth_prior', 'motion_smooth_model': 'motion_smooth_model', 'use_friction': 'use_friction', 'contact_fric_verts_ids': 'contact_fric_verts_ids', 'use_motion_infill_prior': 'use_motion_infill_prior', 'motion_infill_model': 'motion_infill_model', 'infill_pretrain_weights': 'infill_pretrain_weights', 'device': 'device'}), '(loss_type=loss_type, joint_weights=joint_weights, rho=\n rho, use_joints_conf=use_joints_conf, use_face=use_face, use_hands=\n use_hands, vposer=vposer, pose_embedding=pose_embedding,\n body_pose_prior=body_pose_prior, shape_prior=shape_prior, angle_prior=\n angle_prior, expr_prior=expr_prior, left_hand_prior=left_hand_prior,\n right_hand_prior=right_hand_prior, jaw_prior=jaw_prior,\n interpenetration=interpenetration, pen_distance=pen_distance,\n search_tree=search_tree, tri_filtering_module=filter_faces, s2m=s2m,\n m2s=m2s, rho_s2m=rho_s2m, rho_m2s=rho_m2s, head_mask=head_mask,\n body_mask=body_mask, sdf_penetration=sdf_penetration, voxel_size=\n voxel_size, grid_min=grid_min, grid_max=grid_max, sdf=sdf, sdf_normals=\n sdf_normals, R=R, t=t, contact=contact, contact_verts_ids=\n contact_verts_ids, dtype=dtype, smooth_acc=smooth_acc, smooth_vel=\n smooth_vel, use_motion_smooth_prior=use_motion_smooth_prior,\n motion_smooth_model=motion_smooth_model, use_friction=use_friction,\n contact_fric_verts_ids=contact_fric_verts_ids, use_motion_infill_prior=\n use_motion_infill_prior, motion_infill_model=motion_infill_model,\n infill_pretrain_weights=infill_pretrain_weights, device=device, **kwargs)\n', (19550, 20794), True, 'import temp_prox.fitting_temp_slide as fitting\n'), ((11274, 11351), 'torch.zeros', 'torch.zeros', (['[batch_size, 32]'], {'dtype': 'dtype', 'device': 'device', 'requires_grad': '(True)'}), '([batch_size, 32], dtype=dtype, device=device, requires_grad=True)\n', (11285, 11351), False, 'import torch\n'), ((11469, 11496), 'os.path.expandvars', 'osp.expandvars', (['vposer_ckpt'], {}), '(vposer_ckpt)\n', (11483, 11496), True, 'import os.path as osp\n'), ((11517, 11562), 'human_body_prior.tools.model_loader.load_vposer', 'load_vposer', (['vposer_ckpt'], {'vp_model': '"""snapshot"""'}), "(vposer_ckpt, vp_model='snapshot')\n", (11528, 11562), False, 'from human_body_prior.tools.model_loader import load_vposer\n'), ((12876, 12921), 'torch.tensor', 'torch.tensor', (['sdf'], {'dtype': 'dtype', 'device': 'device'}), '(sdf, dtype=dtype, device=device)\n', (12888, 12921), False, 'import torch\n'), ((14304, 14329), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (14327, 14329), False, 'import torch\n'), ((14435, 14469), 'mesh_intersection.bvh_search_tree.BVH', 'BVH', ([], {'max_collisions': 'max_collisions'}), '(max_collisions=max_collisions)\n', (14438, 14469), False, 'from mesh_intersection.bvh_search_tree import BVH\n'), ((14532, 14684), 'mesh_intersection.loss.DistanceFieldPenetrationLoss', 'collisions_loss.DistanceFieldPenetrationLoss', ([], {'sigma': 'df_cone_height', 'point2plane': 'point2plane', 'vectorized': '(True)', 'penalize_outside': 'penalize_outside'}), '(sigma=df_cone_height,\n point2plane=point2plane, vectorized=True, penalize_outside=penalize_outside\n )\n', (14576, 14684), True, 'import mesh_intersection.loss as collisions_loss\n'), ((16290, 16323), 'numpy.concatenate', 'np.concatenate', (['contact_verts_ids'], {}), '(contact_verts_ids)\n', (16304, 16323), True, 'import numpy as np\n'), ((19232, 19244), 'numpy.arange', 'np.arange', (['N'], {}), '(N)\n', (19241, 19244), True, 'import numpy as np\n'), ((19334, 19346), 'numpy.arange', 'np.arange', (['N'], {}), '(N)\n', (19343, 19346), True, 'import numpy as np\n'), ((19405, 19417), 'numpy.arange', 'np.arange', (['N'], {}), '(N)\n', (19414, 19417), True, 'import numpy as np\n'), ((22472, 22504), 'temp_prox.fitting_temp_slide.FittingMonitor', 'fitting.FittingMonitor', ([], {}), '(**kwargs)\n', (22494, 22504), True, 'import temp_prox.fitting_temp_slide as fitting\n'), ((22700, 22711), 'time.time', 'time.time', ([], {}), '()\n', (22709, 22711), False, 'import time\n'), ((22729, 22762), 'tensorboardX.SummaryWriter', 'SummaryWriter', ([], {'log_dir': 'log_folder'}), '(log_dir=log_folder)\n', (22742, 22762), False, 'from tensorboardX import SummaryWriter\n'), ((23012, 23054), 'numpy.mean', 'np.mean', (["prox_params_dict['betas']"], {'axis': '(0)'}), "(prox_params_dict['betas'], axis=0)\n", (23019, 23054), True, 'import numpy as np\n'), ((29243, 29268), 'numpy.array', 'np.array', (['[951.3, 536.77]'], {}), '([951.3, 536.77])\n', (29251, 29268), True, 'import numpy as np\n'), ((29292, 29301), 'numpy.eye', 'np.eye', (['(4)'], {}), '(4)\n', (29298, 29301), True, 'import numpy as np\n'), ((29410, 29513), 'pyrender.camera.IntrinsicsCamera', 'pyrender.camera.IntrinsicsCamera', ([], {'fx': '(1060.53)', 'fy': '(1060.38)', 'cx': 'camera_center[0]', 'cy': 'camera_center[1]'}), '(fx=1060.53, fy=1060.38, cx=camera_center[0\n ], cy=camera_center[1])\n', (29442, 29513), False, 'import pyrender\n'), ((29629, 29745), 'pyrender.MetallicRoughnessMaterial', 'pyrender.MetallicRoughnessMaterial', ([], {'metallicFactor': '(0.0)', 'alphaMode': '"""OPAQUE"""', 'baseColorFactor': '(1.0, 1.0, 0.9, 1.0)'}), "(metallicFactor=0.0, alphaMode='OPAQUE',\n baseColorFactor=(1.0, 1.0, 0.9, 1.0))\n", (29663, 29745), False, 'import pyrender\n'), ((12447, 12459), 'json.load', 'json.load', (['f'], {}), '(f)\n', (12456, 12459), False, 'import json\n'), ((13245, 13291), 'os.path.join', 'osp.join', (['sdf_dir', "(scene_name + '_normals.npy')"], {}), "(sdf_dir, scene_name + '_normals.npy')\n", (13253, 13291), True, 'import os.path as osp\n'), ((13465, 13518), 'torch.tensor', 'torch.tensor', (['sdf_normals'], {'dtype': 'dtype', 'device': 'device'}), '(sdf_normals, dtype=dtype, device=device)\n', (13477, 13518), False, 'import torch\n'), ((13590, 13639), 'os.path.join', 'os.path.join', (['cam2world_dir', "(scene_name + '.json')"], {}), "(cam2world_dir, scene_name + '.json')\n", (13602, 13639), False, 'import os\n'), ((13681, 13693), 'json.load', 'json.load', (['f'], {}), '(f)\n', (13690, 13693), False, 'import json\n'), ((14811, 14843), 'os.path.expandvars', 'os.path.expandvars', (['part_segm_fn'], {}), '(part_segm_fn)\n', (14829, 14843), False, 'import os\n'), ((15761, 15773), 'json.load', 'json.load', (['f'], {}), '(f)\n', (15770, 15773), False, 'import json\n'), ((18889, 18947), 'torch.tensor', 'torch.tensor', (['weight_list[key]'], {'device': 'device', 'dtype': 'dtype'}), '(weight_list[key], device=device, dtype=dtype)\n', (18901, 18947), False, 'import torch\n'), ((19065, 19110), 'os.path.join', 'osp.join', (['body_segments_dir', '"""body_mask.json"""'], {}), "(body_segments_dir, 'body_mask.json')\n", (19073, 19110), True, 'import os.path as osp\n'), ((19153, 19166), 'json.load', 'json.load', (['fp'], {}), '(fp)\n', (19162, 19166), False, 'import json\n'), ((23101, 23135), 'numpy.expand_dims', 'np.expand_dims', (['mean_betas'], {'axis': '(0)'}), '(mean_betas, axis=0)\n', (23115, 23135), True, 'import numpy as np\n'), ((23541, 23572), 'tqdm.tqdm', 'tqdm', (['opt_weights'], {'desc': '"""Stage"""'}), "(opt_weights, desc='Stage')\n", (23545, 23572), False, 'from tqdm import tqdm\n'), ((26510, 26535), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (26533, 26535), False, 'import torch\n'), ((28365, 28454), 'torch.zeros', 'torch.zeros', (['[body_pose.shape[0], 6]'], {'dtype': 'body_pose.dtype', 'device': 'body_pose.device'}), '([body_pose.shape[0], 6], dtype=body_pose.dtype, device=\n body_pose.device)\n', (28376, 28454), False, 'import torch\n'), ((28560, 28601), 'torch.cat', 'torch.cat', (['[body_pose, wrist_pose]'], {'dim': '(1)'}), '([body_pose, wrist_pose], dim=1)\n', (28569, 28601), False, 'import torch\n'), ((28887, 28948), 'trimesh.Trimesh', 'trimesh.Trimesh', (['vertices[i]', 'body_model.faces'], {'process': '(False)'}), '(vertices[i], body_model.faces, process=False)\n', (28902, 28948), False, 'import trimesh\n'), ((29972, 30048), 'pyrender.Scene', 'pyrender.Scene', ([], {'bg_color': '[0.0, 0.0, 0.0, 0.0]', 'ambient_light': '(0.3, 0.3, 0.3)'}), '(bg_color=[0.0, 0.0, 0.0, 0.0], ambient_light=(0.3, 0.3, 0.3))\n', (29986, 30048), False, 'import pyrender\n'), ((30210, 30273), 'pyrender.Mesh.from_trimesh', 'pyrender.Mesh.from_trimesh', (['out_mesh_list[i]'], {'material': 'material'}), '(out_mesh_list[i], material=material)\n', (30236, 30273), False, 'import pyrender\n'), ((30331, 30410), 'pyrender.OffscreenRenderer', 'pyrender.OffscreenRenderer', ([], {'viewport_width': 'W', 'viewport_height': 'H', 'point_size': '(1.0)'}), '(viewport_width=W, viewport_height=H, point_size=1.0)\n', (30357, 30410), False, 'import pyrender\n'), ((31242, 31268), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['output_img'], {}), '(output_img)\n', (31256, 31268), False, 'from PIL import ImageDraw\n'), ((31822, 31848), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['output_img'], {}), '(output_img)\n', (31836, 31848), False, 'from PIL import ImageDraw\n'), ((32093, 32122), 'PIL.Image.fromarray', 'pil_img.fromarray', (['output_img'], {}), '(output_img)\n', (32110, 32122), True, 'import PIL.Image as pil_img\n'), ((12372, 12411), 'os.path.join', 'osp.join', (['sdf_dir', "(scene_name + '.json')"], {}), "(sdf_dir, scene_name + '.json')\n", (12380, 12411), True, 'import os.path as osp\n'), ((12496, 12521), 'numpy.array', 'np.array', (["sdf_data['min']"], {}), "(sdf_data['min'])\n", (12504, 12521), True, 'import numpy as np\n'), ((12594, 12619), 'numpy.array', 'np.array', (["sdf_data['max']"], {}), "(sdf_data['max'])\n", (12602, 12619), True, 'import numpy as np\n'), ((14942, 14992), 'pickle.load', 'pickle.load', (['faces_parents_file'], {'encoding': '"""latin1"""'}), "(faces_parents_file, encoding='latin1')\n", (14953, 14992), False, 'import pickle\n'), ((15682, 15729), 'os.path.join', 'os.path.join', (['body_segments_dir', "(part + '.json')"], {}), "(body_segments_dir, part + '.json')\n", (15694, 15729), False, 'import os\n'), ((16178, 16190), 'json.load', 'json.load', (['f'], {}), '(f)\n', (16187, 16190), False, 'import json\n'), ((23282, 23297), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (23295, 23297), False, 'import torch\n'), ((23626, 23657), 'tqdm.tqdm', 'tqdm', (['opt_weights'], {'desc': '"""Stage"""'}), "(opt_weights, desc='Stage')\n", (23630, 23657), False, 'from tqdm import tqdm\n'), ((24299, 24353), 'temp_prox.optimizers.optim_factory.create_optimizer', 'optim_factory.create_optimizer', (['final_params'], {}), '(final_params, **kwargs)\n', (24329, 24353), False, 'from temp_prox.optimizers import optim_factory\n'), ((26553, 26577), 'torch.cuda.synchronize', 'torch.cuda.synchronize', ([], {}), '()\n', (26575, 26577), False, 'import torch\n'), ((26600, 26611), 'time.time', 'time.time', ([], {}), '()\n', (26609, 26611), False, 'import time\n'), ((27853, 27906), 'pickle.dump', 'pickle.dump', (['results_list[i]', 'result_file'], {'protocol': '(2)'}), '(results_list[i], result_file, protocol=2)\n', (27864, 27906), False, 'import pickle\n'), ((29582, 29592), 'numpy.ones', 'np.ones', (['(3)'], {}), '(3)\n', (29589, 29592), True, 'import numpy as np\n'), ((12780, 12822), 'os.path.join', 'osp.join', (['sdf_dir', "(scene_name + '_sdf.npy')"], {}), "(sdf_dir, scene_name + '_sdf.npy')\n", (12788, 12822), True, 'import os.path as osp\n'), ((15299, 15397), 'mesh_intersection.filter_faces.FilterFaces', 'FilterFaces', ([], {'faces_segm': 'faces_segm', 'faces_parents': 'faces_parents', 'ign_part_pairs': 'ign_part_pairs'}), '(faces_segm=faces_segm, faces_parents=faces_parents,\n ign_part_pairs=ign_part_pairs)\n', (15310, 15397), False, 'from mesh_intersection.filter_faces import FilterFaces\n'), ((16095, 16142), 'os.path.join', 'os.path.join', (['body_segments_dir', "(part + '.json')"], {}), "(body_segments_dir, part + '.json')\n", (16107, 16142), False, 'import os\n'), ((25747, 25772), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (25770, 25772), False, 'import torch\n'), ((25857, 25868), 'time.time', 'time.time', ([], {}), '()\n', (25866, 25868), False, 'import time\n'), ((26200, 26225), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (26223, 26225), False, 'import torch\n'), ((29324, 29356), 'numpy.array', 'np.array', (['[1.0, -1.0, -1.0, 1.0]'], {}), '([1.0, -1.0, -1.0, 1.0])\n', (29332, 29356), True, 'import numpy as np\n'), ((13328, 13374), 'os.path.join', 'osp.join', (['sdf_dir', "(scene_name + '_normals.npy')"], {}), "(sdf_dir, scene_name + '_normals.npy')\n", (13336, 13374), True, 'import os.path as osp\n'), ((16628, 16672), 'os.path.join', 'os.path.join', (['scene_dir', "(scene_name + '.ply')"], {}), "(scene_dir, scene_name + '.ply')\n", (16640, 16672), False, 'import os\n'), ((16759, 16823), 'torch.tensor', 'torch.tensor', (['scene.v[np.newaxis, :]'], {'dtype': 'dtype', 'device': 'device'}), '(scene.v[np.newaxis, :], dtype=dtype, device=device)\n', (16771, 16823), False, 'import torch\n'), ((25798, 25822), 'torch.cuda.synchronize', 'torch.cuda.synchronize', ([], {}), '()\n', (25820, 25822), False, 'import torch\n'), ((26251, 26275), 'torch.cuda.synchronize', 'torch.cuda.synchronize', ([], {}), '()\n', (26273, 26275), False, 'import torch\n'), ((26306, 26317), 'time.time', 'time.time', ([], {}), '()\n', (26315, 26317), False, 'import time\n'), ((23332, 23384), 'torch.from_numpy', 'torch.from_numpy', (["prox_params_dict['pose_embedding']"], {}), "(prox_params_dict['pose_embedding'])\n", (23348, 23384), False, 'import torch\n')]
|
"""
Push Sum Gossip Gradient Descent class for parallel optimization using column stochastic mixing.
:author: <NAME>
:description: Distributed otpimization using column stochastic mixing and greedy gradient descent.
Based on the paper (nedich2015distributed)
"""
import time
import numpy as np
from .gossip_comm import GossipComm
from .push_sum_optimization import PushSumOptimizer
# Message passing and network variables
COMM = GossipComm.comm
SIZE = GossipComm.size
UID = GossipComm.uid
NAME = GossipComm.name
# Default constants
DEFAULT_LEARNING_RATE = 0.1 # Time in seconds
class PushSumSubgradientDescent(PushSumOptimizer):
""" Distributed optimization using column stochastic mixing and greedy gradient descent. """
# Inherit docstring
__doc__ += PushSumOptimizer.__doc__
def __init__(self, objective,
sub_gradient,
arg_start,
synch=True,
peers=None,
step_size=None,
terminate_by_time=False,
termination_condition=None,
log=False,
out_degree=None,
in_degree=SIZE,
num_averaging_itr=1,
constant_step_size=False,
learning_rate=None,
all_reduce=False):
""" Initialize the gossip optimization settings. """
self.constant_step_size = constant_step_size
if learning_rate is None:
learning_rate = DEFAULT_LEARNING_RATE
self.learning_rate = learning_rate
super(PushSumSubgradientDescent, self).__init__(objective=objective,
sub_gradient=sub_gradient,
arg_start=arg_start,
synch=synch,
peers=peers,
step_size=step_size,
terminate_by_time=terminate_by_time,
termination_condition=termination_condition,
log=log,
out_degree=out_degree,
in_degree=in_degree,
num_averaging_itr=num_averaging_itr,
all_reduce=all_reduce)
def _gradient_descent_step(self, ps_n, argmin_est, itr=None, start_time=None):
""" Take step in direction of negative gradient, and return the new domain point. """
# Diminshing step-size: 1 / sqrt(k)
if self.constant_step_size is False:
if self.synch is True:
if itr is None:
raise ValueError("'itr' is NONE for synch.alg. w/ diminishing stepsize")
effective_itr = itr
else:
if start_time is None:
raise ValueError("'start_time' is NONE for asynch.alg. w/ diminishing stepsize")
effective_itr = int((time.time() - start_time) / self.learning_rate) + 1
else:
effective_itr = 1
step_size = self.step_size / (effective_itr ** 0.5)
return ps_n - (step_size * self.sub_gradient(argmin_est))
def minimize(self):
"""
Minimize the objective specified in settings using the Subgradient-Push procedure
Procedure:
1) Gossip: push_sum_gossip([ps_n, ps_w])
2) Update: ps_result = push_sum_gossip([ps_n, ps_w])
2.a) ps_n = ps_result[ps_n]
2.b) ps_w = ps_result[ps_w]
2.c) argmin_est = ps_n / ps_w
2.d) ps_n = ps_n - step_size * sub_gradient(argmin_est)
3) Repeat until completed $(termination_condition) itr. or time (depending on settings)
:rtype:
log is True: dict("argmin_est": GossipLogger,
"ps_w": GossipLogger)
log is False: dict("argmin_est": float,
"objective": float,
"sub_gradient": float)
"""
super(PushSumSubgradientDescent, self).minimize()
# Initialize sub-gradient descent push sum gossip
ps_n = self.argmin_est
ps_w = 1.0
argmin_est = ps_n / ps_w
itr = 0
log = self.log
psga = self.ps_averager
objective = self.objective
gradient = self.sub_gradient
if log:
from .gossip_log import GossipLog
l_argmin_est = GossipLog() # Log the argmin estimate
l_ps_w = GossipLog() # Log the push sum weight
l_argmin_est.log(argmin_est, itr)
l_ps_w.log(ps_w, itr)
if self.terminate_by_time is False:
num_gossip_itr = self.termination_condition
condition = itr < num_gossip_itr
else:
gossip_time = self.termination_condition
end_time = time.time() + gossip_time # End time of optimization
condition = time.time() < end_time
# Goes high if a message was not received in the last gossip round
just_probe = False
# Start optimization at the same time
COMM.Barrier()
start_time = time.time()
# Optimization loop
while condition:
if self.synch is True:
COMM.Barrier()
itr += 1
# -- START Subgradient-Push update -- #
# Gossip
ps_result = psga.gossip(gossip_value=ps_n, ps_weight=ps_w)
ps_n = ps_result['ps_n']
ps_w = ps_result['ps_w']
# Update argmin estimate and take a step
argmin_est = ps_result['avg']
ps_n = self._gradient_descent_step(ps_n=ps_n,
argmin_est=argmin_est,
itr=itr,
start_time=start_time)
# -- END Subgradient-Push update -- #
# Log the varaibles
if log:
l_argmin_est.log(argmin_est, itr)
l_ps_w.log(ps_w, itr)
# Update the termination flag
if self.terminate_by_time is False:
condition = itr < num_gossip_itr
else:
condition = time.time() < end_time
self.argmin_est = argmin_est
if log is True:
return {"argmin_est": l_argmin_est,
"ps_w": l_ps_w}
else:
return {"argmin_est": argmin_est,
"objective": objective(argmin_est),
"sub_gradient": gradient(argmin_est)}
if __name__ == "__main__":
def demo(num_instances_per_node, num_features):
"""
Demo fo the use of the PushSumSubgradientDescent class.
To run the demo, run the following from the multi_agent_optimization directory CLI:
mpiexec -n $(num_nodes) python -m do4py.push_sum_gossip_gradient_descent
"""
# Create objective function and its gradient
np.random.seed(seed=UID)
x_start = np.random.randn(num_features, 1)
a_m = np.random.randn(num_instances_per_node, num_features)
b_v = np.random.randn(num_instances_per_node, 1)
objective = lambda x: 0.5 * (np.linalg.norm(a_m.dot(x) - b_v))**2
gradient = lambda x: a_m.T.dot(a_m.dot(x)-b_v)
pssgd = PushSumSubgradientDescent(objective=objective,
sub_gradient=gradient,
arg_start=x_start,
synch=True,
peers=[(UID + 1) % SIZE, (UID + 2) % SIZE],
step_size=1e-4,
terminate_by_time=False,
termination_condition=1000,
log=True,
in_degree=2,
num_averaging_itr=1,
constant_step_size=False,
learning_rate=1)
loggers = pssgd.minimize()
l_argmin_est = loggers['argmin_est']
l_argmin_est.print_gossip_value(UID, label='argmin_est', l2=True)
# Run a demo where nodes minimize a sum of squares function
demo(num_instances_per_node=5000, num_features=100)
|
[
"numpy.random.randn",
"numpy.random.seed",
"time.time"
] |
[((5484, 5495), 'time.time', 'time.time', ([], {}), '()\n', (5493, 5495), False, 'import time\n'), ((7341, 7365), 'numpy.random.seed', 'np.random.seed', ([], {'seed': 'UID'}), '(seed=UID)\n', (7355, 7365), True, 'import numpy as np\n'), ((7384, 7416), 'numpy.random.randn', 'np.random.randn', (['num_features', '(1)'], {}), '(num_features, 1)\n', (7399, 7416), True, 'import numpy as np\n'), ((7431, 7484), 'numpy.random.randn', 'np.random.randn', (['num_instances_per_node', 'num_features'], {}), '(num_instances_per_node, num_features)\n', (7446, 7484), True, 'import numpy as np\n'), ((7499, 7541), 'numpy.random.randn', 'np.random.randn', (['num_instances_per_node', '(1)'], {}), '(num_instances_per_node, 1)\n', (7514, 7541), True, 'import numpy as np\n'), ((5189, 5200), 'time.time', 'time.time', ([], {}), '()\n', (5198, 5200), False, 'import time\n'), ((5266, 5277), 'time.time', 'time.time', ([], {}), '()\n', (5275, 5277), False, 'import time\n'), ((6588, 6599), 'time.time', 'time.time', ([], {}), '()\n', (6597, 6599), False, 'import time\n'), ((3275, 3286), 'time.time', 'time.time', ([], {}), '()\n', (3284, 3286), False, 'import time\n')]
|
from copy import copy
from collections import ChainMap
from collections.abc import Collection, Iterable
from functools import lru_cache
import logging
import os
from pathlib import Path, PurePosixPath
import re
from types import SimpleNamespace
from warnings import warn
import jpype
from jpype import JClass
import numpy as np
import pandas as pd
from ixmp import config
from ixmp.core import Scenario
from ixmp.utils import as_str_list, filtered, islistable
from . import FIELDS
from .base import CachingBackend
log = logging.getLogger(__name__)
# Map of Python to Java log levels
LOG_LEVELS = {
'CRITICAL': 'ALL',
'ERROR': 'ERROR',
'WARNING': 'WARN',
'INFO': 'INFO',
'DEBUG': 'DEBUG',
'NOTSET': 'OFF',
}
# Java classes, loaded by start_jvm(). These become available as e.g.
# java.IxException or java.HashMap.
java = SimpleNamespace()
JAVA_CLASSES = [
'at.ac.iiasa.ixmp.exceptions.IxException',
'at.ac.iiasa.ixmp.objects.Scenario',
'at.ac.iiasa.ixmp.objects.TimeSeries.TimeSpan',
'at.ac.iiasa.ixmp.Platform',
'java.lang.Double',
'java.lang.Integer',
'java.lang.NoClassDefFoundError',
'java.math.BigDecimal',
'java.util.HashMap',
'java.util.LinkedHashMap',
'java.util.LinkedList',
'java.util.Properties',
]
DRIVER_CLASS = {
'oracle': 'oracle.jdbc.driver.OracleDriver',
'hsqldb': 'org.hsqldb.jdbcDriver',
}
def _create_properties(driver=None, path=None, url=None, user=None,
password=None):
"""Create a database Properties from arguments."""
properties = java.Properties()
# Handle arguments
try:
properties.setProperty('jdbc.driver', DRIVER_CLASS[driver])
except KeyError:
raise ValueError(f'unrecognized/unsupported JDBC driver {driver!r}')
if driver == 'oracle':
if url is None or path is not None:
raise ValueError("use JDBCBackend(driver='oracle', url=…)")
full_url = 'jdbc:oracle:thin:@{}'.format(url)
elif driver == 'hsqldb':
if path is None and url is None:
raise ValueError("use JDBCBackend(driver='hsqldb', path=…)")
if url is not None:
if url.startswith('jdbc:hsqldb:'):
full_url = url
else:
raise ValueError(url)
else:
# Convert Windows paths to use forward slashes per HyperSQL JDBC
# URL spec
url_path = (str(PurePosixPath(Path(path).resolve()))
.replace('\\', ''))
full_url = 'jdbc:hsqldb:file:{}'.format(url_path)
user = user or 'ixmp'
password = password or '<PASSWORD>'
properties.setProperty('jdbc.url', full_url)
properties.setProperty('jdbc.user', user)
properties.setProperty('jdbc.pwd', password)
return properties
def _read_properties(file):
"""Read database properties from *file*, returning :class:`dict`."""
properties = dict()
for line in file.read_text().split('\n'):
match = re.search(r'([^\s]+)\s*=\s*(.+)\s*', line)
if match is not None:
properties[match.group(1)] = match.group(2)
return properties
class JDBCBackend(CachingBackend):
"""Backend using JPype/JDBC to connect to Oracle and HyperSQLDB instances.
Parameters
----------
dbtype : 'HSQLDB', optional
Database type to use. If :obj:`None`, a remote database is accessed. If
'HSQLDB', a local database is created and used at the path given by
`dbprops`.
dbprops : path-like, optional
If `dbtype` is :obj:`None`, the name of a *database properties file*
(default: ``default.properties``) in the properties file directory
(see :class:`.Config`) or a path to a properties file.
If `dbtype` is 'HSQLDB'`, the path of a local database,
(default: ``$HOME/.local/ixmp/localdb/default``) or name of a
database file in the local database directory (default:
``$HOME/.local/ixmp/localdb/``).
jvmargs : str, optional
Java Virtual Machine arguments. See :func:`.start_jvm`.
"""
# NB Much of the code of this backend is in Java, in the iiasa/ixmp_source
# Github repository.
#
# Among other abstractions, this backend:
#
# - Handles any conversion between Java and Python types that is not
# done automatically by JPype.
# - Catches Java exceptions such as ixmp.exceptions.IxException, and
# re-raises them as appropriate Python exceptions.
#
# Limitations:
#
# - s_clone() is only supported when target_backend is JDBCBackend.
#: Reference to the at.ac.iiasa.ixmp.Platform Java object
jobj = None
#: Mapping from ixmp.TimeSeries object to the underlying
#: at.ac.iiasa.ixmp.Scenario object (or subclasses of either)
jindex = {}
def __init__(self, jvmargs=None, **kwargs):
properties = None
# Handle arguments
if 'dbtype' in kwargs:
warn("'dbtype' argument to JDBCBackend; use 'driver'",
DeprecationWarning)
if 'driver' in kwargs:
message = ('ambiguous: both driver={driver!r} and '
'dbtype={!r}').format(**kwargs)
raise ValueError(message)
elif len(kwargs) == 1 and kwargs['dbtype'].lower() == 'hsqldb':
log.info("using platform 'local' for dbtype='hsqldb'")
_, kwargs = config.get_platform_info('local')
assert kwargs.pop('class') == 'jdbc'
else:
kwargs['driver'] = kwargs.pop('dbtype').lower()
if 'dbprops' in kwargs:
# Use an existing file
dbprops = Path(kwargs.pop('dbprops'))
if dbprops.exists() and dbprops.is_file():
# Existing properties file
properties = _read_properties(dbprops)
if 'jdbc.url' not in properties:
raise ValueError('Config file contains no database URL')
elif (not dbprops.exists()
and dbprops.with_suffix('.lobs').exists()):
# Actually the basename for a HSQLDB
kwargs.setdefault('driver', 'hsqldb')
kwargs.setdefault('path', dbprops)
else:
raise FileNotFoundError(dbprops)
start_jvm(jvmargs)
# Create a database properties object
if properties:
# ...using file contents
new_props = java.Properties()
[new_props.setProperty(k, v) for k, v in properties.items()]
properties = new_props
else:
# ...from arguments
properties = _create_properties(**kwargs)
log.info('launching ixmp.Platform connected to {}'
.format(properties.getProperty('jdbc.url')))
try:
self.jobj = java.Platform('Python', properties)
except java.NoClassDefFoundError as e: # pragma: no cover
raise NameError(
'{}\nCheck that dependencies of ixmp.jar are included in {}'
.format(e, Path(__file__).parents[2] / 'lib'))
except jpype.JException as e: # pragma: no cover
# Handle Java exceptions
jclass = e.__class__.__name__
info = '\n{}\n(Java: {})'.format(e, jclass)
if jclass.endswith('HikariPool.PoolInitializationException'):
redacted = copy(kwargs)
redacted.update({'user': '(HIDDEN)', 'password': '(<PASSWORD>)'})
raise RuntimeError('unable to connect to database:\n{!r}{}'
.format(redacted, info)) from None
elif jclass.endswith('FlywayException'):
raise RuntimeError('when initializing database:' + info)
else:
raise RuntimeError('unhandled Java exception:' + info) from e
# Invoke the parent constructor to initialize the cache
super().__init__()
# Platform methods
def set_log_level(self, level):
self.jobj.setLogLevel(LOG_LEVELS[level])
def open_db(self):
"""(Re-)open the database connection."""
self.jobj.openDB()
def close_db(self):
"""Close the database connection.
A HSQL database can only be used by one :class:`Backend` instance at a
time. Any existing connection must be closed before a new one can be
opened.
"""
try:
self.jobj.closeDB()
except java.IxException as e:
if str(e) == 'Error closing the database connection!':
log.warning('Database connection could not be closed or was '
'already closed')
else:
log.warning(str(e))
def get_auth(self, user, models, kind):
return self.jobj.checkModelAccess(user, kind, to_jlist2(models))
def set_node(self, name, parent=None, hierarchy=None, synonym=None):
if parent and hierarchy and not synonym:
self.jobj.addNode(name, parent, hierarchy)
elif synonym and not (parent or hierarchy):
self.jobj.addNodeSynonym(synonym, name)
def get_nodes(self):
for r in self.jobj.listNodes('%'):
n, p, h = r.getName(), r.getParent(), r.getHierarchy()
yield (n, None, p, h)
yield from [(s, n, p, h) for s in (r.getSynonyms() or [])]
def get_scenarios(self, default, model, scenario):
# List<Map<String, Object>>
scenarios = self.jobj.getScenarioList(default, model, scenario)
for s in scenarios:
data = []
for field in FIELDS['get_scenarios']:
data.append(int(s[field]) if field == 'version' else s[field])
yield data
def set_unit(self, name, comment):
self.jobj.addUnitToDB(name, comment)
def get_units(self):
return to_pylist(self.jobj.getUnitList())
# Timeseries methods
def _common_init(self, ts, klass, *args):
"""Common code for ts_init and s_init."""
method = getattr(self.jobj, 'new' + klass)
# Create a new TimeSeries
jobj = method(ts.model, ts.scenario, *args)
# Add to index
self.jindex[ts] = jobj
# Retrieve initial version
ts.version = jobj.getVersion()
def init_ts(self, ts, annotation=None):
self._common_init(ts, 'TimeSeries', annotation)
def get(self, ts, version):
args = [ts.model, ts.scenario]
if version is not None:
# Load a TimeSeries of specific version
args.append(version)
# either getTimeSeries or getScenario
method = getattr(self.jobj, 'get' + ts.__class__.__name__)
try:
jobj = method(*args)
except java.IxException as e:
raise RuntimeError(*e.args)
# Add to index
self.jindex[ts] = jobj
# Retrieve or check the version
if version is None:
version = jobj.getVersion()
else:
assert version == jobj.getVersion()
# Update the version attribute
ts.version = version
if isinstance(ts, Scenario):
# Also retrieve the scheme
ts.scheme = jobj.getScheme()
def check_out(self, ts, timeseries_only):
self.jindex[ts].checkOut(timeseries_only)
def commit(self, ts, comment):
self.jindex[ts].commit(comment)
if ts.version == 0:
ts.version = self.jindex[ts].getVersion()
def discard_changes(self, ts):
self.jindex[ts].discardChanges()
def set_as_default(self, ts):
self.jindex[ts].setAsDefaultVersion()
def is_default(self, ts):
return bool(self.jindex[ts].isDefault())
def last_update(self, ts):
return self.jindex[ts].getLastUpdateTimestamp().toString()
def run_id(self, ts):
return self.jindex[ts].getRunId()
def preload(self, ts):
self.jindex[ts].preloadAllTimeseries()
def get_data(self, ts, region, variable, unit, year):
# Convert the selectors to Java lists
r = to_jlist2(region)
v = to_jlist2(variable)
u = to_jlist2(unit)
y = to_jlist2(year)
# Field types
ftype = {
'year': int,
'value': float,
}
# Iterate over returned rows
for row in self.jindex[ts].getTimeseries(r, v, u, None, y):
# Get the value of each field and maybe convert its type
yield tuple(ftype.get(f, str)
(getattr(row, 'get' + f.capitalize())())
for f in FIELDS['ts_get'])
def get_geo(self, ts):
# NB the return type of getGeoData() requires more processing than
# getTimeseries. It also accepts no selectors.
# Field types
ftype = {
'meta': int,
'time': lambda ord: timespans()[int(ord)], # Look up the name
'year': lambda obj: obj, # Pass through; handled later
}
# Returned names in Java data structure do not match API column names
jname = {
'meta': 'meta',
'region': 'nodeName',
'time': 'time',
'unit': 'unitName',
'variable': 'keyString',
'year': 'yearlyData'
}
# Iterate over rows from the Java backend
for row in self.jindex[ts].getGeoData():
data1 = {f: ftype.get(f, str)(row.get(jname.get(f, f)))
for f in FIELDS['ts_get_geo'] if f != 'value'}
# At this point, the 'year' key is a not a single value, but a
# year -> value mapping with multiple entries
yv_entries = data1.pop('year').entrySet()
# Construct a chain map: look up in data1, then data2
data2 = {'year': None, 'value': None}
cm = ChainMap(data1, data2)
for yv in yv_entries:
# Update data2
data2['year'] = yv.getKey()
data2['value'] = yv.getValue()
# Construct a row with a single value
yield tuple(cm[f] for f in FIELDS['ts_get_geo'])
def set_data(self, ts, region, variable, data, unit, meta):
# Convert *data* to a Java data structure
jdata = java.LinkedHashMap()
for k, v in data.items():
# Explicit cast is necessary; otherwise java.lang.Long
jdata.put(java.Integer(k), v)
self.jindex[ts].addTimeseries(region, variable, None, jdata, unit,
meta)
def set_geo(self, ts, region, variable, time, year, value, unit, meta):
self.jindex[ts].addGeoData(region, variable, time, java.Integer(year),
value, unit, meta)
def delete(self, ts, region, variable, years, unit):
years = to_jlist2(years, java.Integer)
self.jindex[ts].removeTimeseries(region, variable, None, years, unit)
def delete_geo(self, ts, region, variable, time, years, unit):
years = to_jlist2(years, java.Integer)
self.jindex[ts].removeGeoData(region, variable, time, years, unit)
# Scenario methods
def init_s(self, s, scheme, annotation):
self._common_init(s, 'Scenario', scheme, annotation)
def clone(self, s, platform_dest, model, scenario, annotation,
keep_solution, first_model_year=None):
# Raise exceptions for limitations of JDBCBackend
if not isinstance(platform_dest._backend, self.__class__):
raise NotImplementedError( # pragma: no cover
f'Clone between {self.__class__} and'
f'{platform_dest._backend.__class__}')
elif platform_dest._backend is not self:
msg = 'Cross-platform clone of {}.Scenario with'.format(
s.__class__.__module__.split('.')[0])
if keep_solution is False:
raise NotImplementedError(msg + ' `keep_solution=False`')
elif 'message_ix' in msg and first_model_year is not None:
raise NotImplementedError(msg + ' first_model_year != None')
# Prepare arguments
args = [platform_dest._backend.jobj, model, scenario, annotation,
keep_solution]
if first_model_year:
args.append(first_model_year)
# Reference to the cloned Java object
jclone = self.jindex[s].clone(*args)
# Instantiate same class as the original object
return s.__class__(platform_dest, model, scenario,
version=jclone.getVersion())
def has_solution(self, s):
return self.jindex[s].hasSolution()
def list_items(self, s, type):
return to_pylist(getattr(self.jindex[s], f'get{type.title()}List')())
def init_item(self, s, type, name, idx_sets, idx_names):
# generate index-set and index-name lists
if isinstance(idx_sets, set) or isinstance(idx_names, set):
raise ValueError('index dimension must be string or ordered lists')
idx_sets = to_jlist(idx_sets)
idx_names = to_jlist(idx_names if idx_names is not None else idx_sets)
# Initialize the Item
func = getattr(self.jindex[s], f'initialize{type.title()}')
# The constructor returns a reference to the Java Item, but these
# aren't exposed by Backend, so don't return here
try:
func(name, idx_sets, idx_names)
except jpype.JException as e:
e = str(e)
if e.startswith('This Scenario cannot be edited'):
raise RuntimeError(e)
elif 'already exists' in e:
raise ValueError('{!r} already exists'.format(name))
else:
raise
def delete_item(self, s, type, name):
getattr(self.jindex[s], f'remove{type.title()}')()
self.cache_invalidate(s, type, name)
def item_index(self, s, name, sets_or_names):
jitem = self._get_item(s, 'item', name, load=False)
return list(getattr(jitem, f'getIdx{sets_or_names.title()}')())
def item_get_elements(self, s, type, name, filters=None):
if filters:
# Convert filter elements to strings
filters = {dim: as_str_list(ele) for dim, ele in filters.items()}
try:
# Retrieve the cached value with this exact set of filters
return self.cache_get(s, type, name, filters)
except KeyError:
pass # Cache miss
try:
# Retrieve a cached, unfiltered value of the same item
unfiltered = self.cache_get(s, type, name, None)
except KeyError:
pass # Cache miss
else:
# Success; filter and return
return filtered(unfiltered, filters)
# Failed to load item from cache
# Retrieve the item
item = self._get_item(s, type, name, load=True)
idx_names = list(item.getIdxNames())
idx_sets = list(item.getIdxSets())
# Get list of elements, using filters if provided
if filters is not None:
jFilter = java.HashMap()
for idx_name, values in filters.items():
# Retrieve the elements of the index set as a list
idx_set = idx_sets[idx_names.index(idx_name)]
elements = self.item_get_elements(s, 'set', idx_set).tolist()
# Filter for only included values and store
filtered_elements = filter(lambda e: e in values, elements)
jFilter.put(idx_name, to_jlist2(filtered_elements))
jList = item.getElements(jFilter)
else:
jList = item.getElements()
if item.getDim() > 0:
# Mapping set or multi-dimensional equation, parameter, or variable
columns = copy(idx_names)
# Prepare dtypes for index columns
dtypes = {}
for idx_name, idx_set in zip(columns, idx_sets):
# NB using categoricals could be more memory-efficient, but
# requires adjustment of tests/documentation. See
# https://github.com/iiasa/ixmp/issues/228
# dtypes[idx_name] = CategoricalDtype(
# self.item_get_elements(s, 'set', idx_set))
dtypes[idx_name] = str
# Prepare dtypes for additional columns
if type == 'par':
columns.extend(['value', 'unit'])
dtypes['value'] = float
# Same as above
# dtypes['unit'] = CategoricalDtype(self.jobj.getUnitList())
dtypes['unit'] = str
elif type in ('equ', 'var'):
columns.extend(['lvl', 'mrg'])
dtypes.update({'lvl': float, 'mrg': float})
# Prepare empty DataFrame
result = pd.DataFrame(index=pd.RangeIndex(len(jList)),
columns=columns)
# Copy vectors from Java into DataFrame columns
# NB [:] causes JPype to use a faster code path
for i in range(len(idx_sets)):
result.iloc[:, i] = item.getCol(i, jList)[:]
if type == 'par':
result.loc[:, 'value'] = item.getValues(jList)[:]
result.loc[:, 'unit'] = item.getUnits(jList)[:]
elif type in ('equ', 'var'):
result.loc[:, 'lvl'] = item.getLevels(jList)[:]
result.loc[:, 'mrg'] = item.getMarginals(jList)[:]
# .loc assignment above modifies dtypes; set afterwards
result = result.astype(dtypes)
elif type == 'set':
# Index sets
result = pd.Series(item.getCol(0, jList))
elif type == 'par':
# Scalar parameters
result = dict(value=item.getScalarValue().floatValue(),
unit=str(item.getScalarUnit()))
elif type in ('equ', 'var'):
# Scalar equations and variables
result = dict(lvl=item.getScalarLevel().floatValue(),
mrg=item.getScalarMarginal().floatValue())
# Store cache
self.cache(s, type, name, filters, result)
return result
def item_set_elements(self, s, type, name, elements):
jobj = self._get_item(s, type, name)
try:
for key, value, unit, comment in elements:
# Prepare arguments
args = [to_jlist2(key)] if key else []
if type == 'par':
args.extend([java.Double(value), unit])
if comment:
args.append(comment)
# Activates one of 5 signatures for addElement:
# - set: (key)
# - set: (key, comment)
# - par: (key, value, unit, comment)
# - par: (key, value, unit)
# - par: (value, unit, comment)
jobj.addElement(*args)
except java.IxException as e:
msg = e.message()
if ('does not have an element' in msg) or ('The unit' in msg):
# Re-raise as Python ValueError
raise ValueError(msg) from e
else: # pragma: no cover
raise RuntimeError('unhandled Java exception') from e
self.cache_invalidate(s, type, name)
def item_delete_elements(self, s, type, name, keys):
jitem = self._get_item(s, type, name, load=False)
for key in keys:
jitem.removeElement(to_jlist2(key))
self.cache_invalidate(s, type, name)
def get_meta(self, s):
def unwrap(v):
"""Unwrap metadata numeric value (BigDecimal -> Double)"""
return v.doubleValue() if isinstance(v, java.BigDecimal) else v
return {entry.getKey(): unwrap(entry.getValue())
for entry in self.jindex[s].getMeta().entrySet()}
def set_meta(self, s, name, value):
self.jindex[s].setMeta(name, value)
def clear_solution(self, s, from_year=None):
from ixmp.core import Scenario
if from_year:
if type(s) is not Scenario:
raise TypeError('s_clear_solution(from_year=...) only valid '
'for ixmp.Scenario; not subclasses')
self.jindex[s].removeSolution(from_year)
else:
self.jindex[s].removeSolution()
self.cache_invalidate(s)
# MsgScenario methods
def cat_list(self, ms, name):
return to_pylist(self.jindex[ms].getTypeList(name))
def cat_get_elements(self, ms, name, cat):
return to_pylist(self.jindex[ms].getCatEle(name, cat))
def cat_set_elements(self, ms, name, cat, keys, is_unique):
self.jindex[ms].addCatEle(name, cat, to_jlist2(keys), is_unique)
# Helpers; not part of the Backend interface
def write_gdx(self, s, path):
"""Write the Scenario to a GDX file at *path*."""
# include_var_equ=False -> do not include variables/equations in GDX
self.jindex[s].toGDX(str(path.parent), path.name, False)
def read_gdx(self, s, path, check_solution, comment, equ_list, var_list):
"""Read the Scenario from a GDX file at *path*.
Parameters
----------
check_solution : bool
If True, raise an exception if the GAMS solver did not reach
optimality. (Only for MESSAGE-scheme Scenarios.)
comment : str
Comment added to Scenario when importing the solution.
equ_list : list of str
Equations to be imported.
var_list : list of str
Variables to be imported.
"""
self.jindex[s].readSolutionFromGDX(
str(path.parent), path.name, comment, to_jlist2(var_list),
to_jlist2(equ_list), check_solution)
self.cache_invalidate(s)
def _get_item(self, s, ix_type, name, load=True):
"""Return the Java object for item *name* of *ix_type*.
Parameters
----------
load : bool, optional
If *ix_type* is 'par', 'var', or 'equ', the elements of the item
are loaded from the database before :meth:`_item` returns. If
:const:`False`, the elements can be loaded later using
``item.loadItemElementsfromDB()``.
"""
# getItem is not overloaded to accept a second bool argument
args = [name] + ([load] if ix_type != 'item' else [])
try:
return getattr(self.jindex[s], f'get{ix_type.title()}')(*args)
except java.IxException as e:
if re.match('No item [^ ]* exists in this Scenario', e.args[0]):
# Re-raise as a Python KeyError
raise KeyError(f'No {ix_type.title()} {name!r} exists in this '
'Scenario!') from None
else: # pragma: no cover
raise RuntimeError('unhandled Java exception') from e
def start_jvm(jvmargs=None):
"""Start the Java Virtual Machine via :mod:`JPype`.
Parameters
----------
jvmargs : str or list of str, optional
Additional arguments for launching the JVM, passed to
:func:`jpype.startJVM`.
For instance, to set the maximum heap space to 4 GiB, give
``jvmargs=['-Xmx4G']``. See the `JVM documentation`_ for a list of
options.
.. _`JVM documentation`: https://docs.oracle.com/javase/7/docs
/technotes/tools/windows/java.html)
"""
# TODO change the jvmargs default to [] instead of None
if jpype.isJVMStarted():
return
jvmargs = jvmargs or []
# Arguments
args = [jpype.getDefaultJVMPath()]
# Add the ixmp root directory, ixmp.jar and bundled .jar and .dll files to
# the classpath
module_root = Path(__file__).parents[1]
jarfile = module_root / 'ixmp.jar'
module_jars = list(module_root.glob('lib/*'))
classpath = map(str, [module_root, jarfile] + list(module_jars))
sep = ';' if os.name == 'nt' else ':'
args.append('-Djava.class.path={}'.format(sep.join(classpath)))
# Add user args
args.extend(jvmargs if isinstance(jvmargs, list) else [jvmargs])
# For JPype 0.7 (raises a warning) and 0.8 (default is False).
# 'True' causes Java string objects to be converted automatically to Python
# str(), as expected by ixmp Python code.
kwargs = dict(convertStrings=True)
jpype.startJVM(*args, **kwargs)
# define auxiliary references to Java classes
global java
for class_name in JAVA_CLASSES:
setattr(java, class_name.split('.')[-1], JClass(class_name))
# Conversion methods
def to_pylist(jlist):
"""Transforms a Java.Array or Java.List to a :class:`numpy.array`."""
# handling string array
try:
return np.array(jlist[:])
# handling Java LinkedLists
except Exception:
return np.array(jlist.toArray()[:])
def to_jlist(pylist, idx_names=None):
"""Convert *pylist* to a jLinkedList."""
if pylist is None:
return None
jList = java.LinkedList()
if idx_names is None:
if islistable(pylist):
for key in pylist:
jList.add(str(key))
else:
jList.add(str(pylist))
else:
# pylist must be a dict
for idx in idx_names:
jList.add(str(pylist[idx]))
return jList
def to_jlist2(arg, convert=None):
"""Simple conversion of :class:`list` *arg* to java.LinkedList."""
jlist = java.LinkedList()
if convert:
arg = map(convert, arg)
if isinstance(arg, Collection):
# Sized collection can be used directly
jlist.addAll(arg)
elif isinstance(arg, Iterable):
# Transfer items from an iterable, generator, etc. to the LinkedList
[jlist.add(value) for value in arg]
else:
raise ValueError(arg)
return jlist
@lru_cache(1)
def timespans():
# Mapping for the enums of at.ac.iiasa.ixmp.objects.TimeSeries.TimeSpan
return {t.ordinal(): t.name() for t in java.TimeSpan.values()}
|
[
"ixmp.utils.as_str_list",
"jpype.isJVMStarted",
"ixmp.utils.islistable",
"jpype.JClass",
"copy.copy",
"re.match",
"ixmp.utils.filtered",
"pathlib.Path",
"numpy.array",
"jpype.getDefaultJVMPath",
"ixmp.config.get_platform_info",
"collections.ChainMap",
"warnings.warn",
"functools.lru_cache",
"jpype.startJVM",
"re.search",
"types.SimpleNamespace",
"logging.getLogger"
] |
[((524, 551), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (541, 551), False, 'import logging\n'), ((851, 868), 'types.SimpleNamespace', 'SimpleNamespace', ([], {}), '()\n', (866, 868), False, 'from types import SimpleNamespace\n'), ((30057, 30069), 'functools.lru_cache', 'lru_cache', (['(1)'], {}), '(1)\n', (30066, 30069), False, 'from functools import lru_cache\n'), ((27725, 27745), 'jpype.isJVMStarted', 'jpype.isJVMStarted', ([], {}), '()\n', (27743, 27745), False, 'import jpype\n'), ((28588, 28619), 'jpype.startJVM', 'jpype.startJVM', (['*args'], {}), '(*args, **kwargs)\n', (28602, 28619), False, 'import jpype\n'), ((3017, 3062), 're.search', 're.search', (['"""([^\\\\s]+)\\\\s*=\\\\s*(.+)\\\\s*"""', 'line'], {}), "('([^\\\\s]+)\\\\s*=\\\\s*(.+)\\\\s*', line)\n", (3026, 3062), False, 'import re\n'), ((27820, 27845), 'jpype.getDefaultJVMPath', 'jpype.getDefaultJVMPath', ([], {}), '()\n', (27843, 27845), False, 'import jpype\n'), ((28964, 28982), 'numpy.array', 'np.array', (['jlist[:]'], {}), '(jlist[:])\n', (28972, 28982), True, 'import numpy as np\n'), ((29277, 29295), 'ixmp.utils.islistable', 'islistable', (['pylist'], {}), '(pylist)\n', (29287, 29295), False, 'from ixmp.utils import as_str_list, filtered, islistable\n'), ((5011, 5085), 'warnings.warn', 'warn', (['"""\'dbtype\' argument to JDBCBackend; use \'driver\'"""', 'DeprecationWarning'], {}), '("\'dbtype\' argument to JDBCBackend; use \'driver\'", DeprecationWarning)\n', (5015, 5085), False, 'from warnings import warn\n'), ((13964, 13986), 'collections.ChainMap', 'ChainMap', (['data1', 'data2'], {}), '(data1, data2)\n', (13972, 13986), False, 'from collections import ChainMap\n'), ((18887, 18916), 'ixmp.utils.filtered', 'filtered', (['unfiltered', 'filters'], {}), '(unfiltered, filters)\n', (18895, 18916), False, 'from ixmp.utils import as_str_list, filtered, islistable\n'), ((19959, 19974), 'copy.copy', 'copy', (['idx_names'], {}), '(idx_names)\n', (19963, 19974), False, 'from copy import copy\n'), ((27965, 27979), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (27969, 27979), False, 'from pathlib import Path, PurePosixPath\n'), ((28772, 28790), 'jpype.JClass', 'JClass', (['class_name'], {}), '(class_name)\n', (28778, 28790), False, 'from jpype import JClass\n'), ((18366, 18382), 'ixmp.utils.as_str_list', 'as_str_list', (['ele'], {}), '(ele)\n', (18377, 18382), False, 'from ixmp.utils import as_str_list, filtered, islistable\n'), ((26764, 26824), 're.match', 're.match', (['"""No item [^ ]* exists in this Scenario"""', 'e.args[0]'], {}), "('No item [^ ]* exists in this Scenario', e.args[0])\n", (26772, 26824), False, 'import re\n'), ((5483, 5516), 'ixmp.config.get_platform_info', 'config.get_platform_info', (['"""local"""'], {}), "('local')\n", (5507, 5516), False, 'from ixmp import config\n'), ((7486, 7498), 'copy.copy', 'copy', (['kwargs'], {}), '(kwargs)\n', (7490, 7498), False, 'from copy import copy\n'), ((7156, 7170), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (7160, 7170), False, 'from pathlib import Path, PurePosixPath\n'), ((2457, 2467), 'pathlib.Path', 'Path', (['path'], {}), '(path)\n', (2461, 2467), False, 'from pathlib import Path, PurePosixPath\n')]
|
import logging
import os
from collections import defaultdict
from pathlib import Path
from multiprocessing import Pool, cpu_count
import librosa
import numpy as np
from python_speech_features import fbank
from tqdm import tqdm
from constants import SAMPLE_RATE, NUM_FBANKS
from utils import find_files, ensures_dir
logger = logging.getLogger(__name__)
def read_mfcc(input_filename, sample_rate):
audio = Audio.read(input_filename, sample_rate)
energy = np.abs(audio)
silence_threshold = np.percentile(energy, 95)
offsets = np.where(energy > silence_threshold)[0]
# left_blank_duration_ms = (1000.0 * offsets[0]) // self.sample_rate # frame_id to duration (ms)
# right_blank_duration_ms = (1000.0 * (len(audio) - offsets[-1])) // self.sample_rate
# TODO: could use trim_silence() here or a better VAD.
audio_voice_only = audio[offsets[0]:offsets[-1]]
mfcc = mfcc_fbank(audio_voice_only, sample_rate)
return mfcc
def extract_speaker_and_utterance_ids(filename: str): # LIBRI.
# 'audio/dev-other/116/288045/116-288045-0000.flac'
speaker, _, basename = Path(filename).parts[-3:]
filename.split('-')
utterance = os.path.splitext(basename.split('-', 1)[-1])[0]
assert basename.split('-')[0] == speaker
return speaker, utterance
class Audio:
def __init__(self, cache_dir: str, audio_dir: str = None, sample_rate: int = SAMPLE_RATE, ext='flac'):
self.ext = ext
self.cache_dir = os.path.join(cache_dir, 'audio-fbanks')
ensures_dir(self.cache_dir)
if audio_dir is not None:
self.build_cache(os.path.expanduser(audio_dir), sample_rate)
self.speakers_to_utterances = defaultdict(dict)
for cache_file in find_files(self.cache_dir, ext='npy'):
# /path/to/speaker_utterance.npy
speaker_id, utterance_id = Path(cache_file).stem.split('_')
self.speakers_to_utterances[speaker_id][utterance_id] = cache_file
@property
def speaker_ids(self):
return sorted(self.speakers_to_utterances)
@staticmethod
def trim_silence(audio, threshold):
"""Removes silence at the beginning and end of a sample."""
energy = librosa.feature.rms(audio)
frames = np.nonzero(np.array(energy > threshold))
indices = librosa.core.frames_to_samples(frames)[1]
# Note: indices can be an empty array, if the whole audio was silence.
audio_trim = audio[0:0]
left_blank = audio[0:0]
right_blank = audio[0:0]
if indices.size:
audio_trim = audio[indices[0]:indices[-1]]
left_blank = audio[:indices[0]] # slice before.
right_blank = audio[indices[-1]:] # slice after.
return audio_trim, left_blank, right_blank
@staticmethod
def read(filename, sample_rate=SAMPLE_RATE):
audio, sr = librosa.load(filename, sr=sample_rate, mono=True, dtype=np.float32)
assert sr == sample_rate
return audio
def subprocess(self, slibri, sample_rate):
print(slibri[0])
for i in range(len(slibri)):
filename = slibri[i]
self.cache_audio_file(filename, sample_rate)
def build_cache(self, audio_dir, sample_rate):
logger.info(f'audio_dir: {audio_dir}.')
logger.info(f'sample_rate: {sample_rate:,} hz.')
audio_files = find_files(audio_dir, ext=self.ext)
audio_files_count = len(audio_files)
assert audio_files_count != 0, f'Could not find any {self.ext} files in {audio_dir}.'
logger.info(f'Found {audio_files_count:,} files in {audio_dir}.')
thread = cpu_count()
p = Pool(thread)
patch = int(len(audio_files) / thread)
for i in range(thread):
if i < thread - 1:
slibri = audio_files[i * patch:(i + 1) * patch]
else:
slibri = audio_files[i * patch:]
print("task %s slibri length: %d" % (i, len(slibri)))
p.apply_async(self.subprocess, args=(slibri, sample_rate))
p.close()
p.join()
print("*^ˍ^* *^ˍ^* *^ˍ^* *^ˍ^* *^ˍ^* *^ˍ^* *^ˍ^* *^ˍ^* *^ˍ^* *^ˍ^* *^ˍ^*")
def cache_audio_file(self, input_filename, sample_rate):
sp, utt = extract_speaker_and_utterance_ids(input_filename)
cache_filename = os.path.join(self.cache_dir, f'{sp}_{utt}.npy')
if (os.path.exists(cache_filename)):
print('file exist:', cache_filename)
else:
if not os.path.isfile(cache_filename):
try:
mfcc = read_mfcc(input_filename, sample_rate)
np.save(cache_filename, mfcc)
except librosa.util.exceptions.ParameterError as e:
logger.error(e)
def pad_mfcc(mfcc, max_length): # num_frames, nfilt=64.
if len(mfcc) < max_length:
mfcc = np.vstack((mfcc, np.tile(np.zeros(mfcc.shape[1]), (max_length - len(mfcc), 1))))
return mfcc
def mfcc_fbank(signal: np.array, sample_rate: int): # 1D signal array.
# Returns MFCC with shape (num_frames, n_filters, 3).
filter_banks, energies = fbank(signal, samplerate=sample_rate, nfilt=NUM_FBANKS)
frames_features = normalize_frames(filter_banks)
# delta_1 = delta(filter_banks, N=1)
# delta_2 = delta(delta_1, N=1)
# frames_features = np.transpose(np.stack([filter_banks, delta_1, delta_2]), (1, 2, 0))
return np.array(frames_features, dtype=np.float32) # Float32 precision is enough here.
def normalize_frames(m, epsilon=1e-12):
return [(v - np.mean(v)) / max(np.std(v), epsilon) for v in m]
|
[
"numpy.abs",
"utils.find_files",
"collections.defaultdict",
"pathlib.Path",
"os.path.isfile",
"numpy.mean",
"utils.ensures_dir",
"os.path.join",
"multiprocessing.cpu_count",
"numpy.std",
"os.path.exists",
"librosa.core.frames_to_samples",
"librosa.feature.rms",
"numpy.save",
"numpy.percentile",
"python_speech_features.fbank",
"librosa.load",
"multiprocessing.Pool",
"numpy.zeros",
"numpy.where",
"numpy.array",
"os.path.expanduser",
"logging.getLogger"
] |
[((326, 353), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (343, 353), False, 'import logging\n'), ((465, 478), 'numpy.abs', 'np.abs', (['audio'], {}), '(audio)\n', (471, 478), True, 'import numpy as np\n'), ((503, 528), 'numpy.percentile', 'np.percentile', (['energy', '(95)'], {}), '(energy, 95)\n', (516, 528), True, 'import numpy as np\n'), ((5158, 5213), 'python_speech_features.fbank', 'fbank', (['signal'], {'samplerate': 'sample_rate', 'nfilt': 'NUM_FBANKS'}), '(signal, samplerate=sample_rate, nfilt=NUM_FBANKS)\n', (5163, 5213), False, 'from python_speech_features import fbank\n'), ((5447, 5490), 'numpy.array', 'np.array', (['frames_features'], {'dtype': 'np.float32'}), '(frames_features, dtype=np.float32)\n', (5455, 5490), True, 'import numpy as np\n'), ((543, 579), 'numpy.where', 'np.where', (['(energy > silence_threshold)'], {}), '(energy > silence_threshold)\n', (551, 579), True, 'import numpy as np\n'), ((1465, 1504), 'os.path.join', 'os.path.join', (['cache_dir', '"""audio-fbanks"""'], {}), "(cache_dir, 'audio-fbanks')\n", (1477, 1504), False, 'import os\n'), ((1513, 1540), 'utils.ensures_dir', 'ensures_dir', (['self.cache_dir'], {}), '(self.cache_dir)\n', (1524, 1540), False, 'from utils import find_files, ensures_dir\n'), ((1686, 1703), 'collections.defaultdict', 'defaultdict', (['dict'], {}), '(dict)\n', (1697, 1703), False, 'from collections import defaultdict\n'), ((1730, 1767), 'utils.find_files', 'find_files', (['self.cache_dir'], {'ext': '"""npy"""'}), "(self.cache_dir, ext='npy')\n", (1740, 1767), False, 'from utils import find_files, ensures_dir\n'), ((2202, 2228), 'librosa.feature.rms', 'librosa.feature.rms', (['audio'], {}), '(audio)\n', (2221, 2228), False, 'import librosa\n'), ((2866, 2933), 'librosa.load', 'librosa.load', (['filename'], {'sr': 'sample_rate', 'mono': '(True)', 'dtype': 'np.float32'}), '(filename, sr=sample_rate, mono=True, dtype=np.float32)\n', (2878, 2933), False, 'import librosa\n'), ((3383, 3418), 'utils.find_files', 'find_files', (['audio_dir'], {'ext': 'self.ext'}), '(audio_dir, ext=self.ext)\n', (3393, 3418), False, 'from utils import find_files, ensures_dir\n'), ((3649, 3660), 'multiprocessing.cpu_count', 'cpu_count', ([], {}), '()\n', (3658, 3660), False, 'from multiprocessing import Pool, cpu_count\n'), ((3673, 3685), 'multiprocessing.Pool', 'Pool', (['thread'], {}), '(thread)\n', (3677, 3685), False, 'from multiprocessing import Pool, cpu_count\n'), ((4347, 4394), 'os.path.join', 'os.path.join', (['self.cache_dir', 'f"""{sp}_{utt}.npy"""'], {}), "(self.cache_dir, f'{sp}_{utt}.npy')\n", (4359, 4394), False, 'import os\n'), ((4407, 4437), 'os.path.exists', 'os.path.exists', (['cache_filename'], {}), '(cache_filename)\n', (4421, 4437), False, 'import os\n'), ((1105, 1119), 'pathlib.Path', 'Path', (['filename'], {}), '(filename)\n', (1109, 1119), False, 'from pathlib import Path\n'), ((2257, 2285), 'numpy.array', 'np.array', (['(energy > threshold)'], {}), '(energy > threshold)\n', (2265, 2285), True, 'import numpy as np\n'), ((2305, 2343), 'librosa.core.frames_to_samples', 'librosa.core.frames_to_samples', (['frames'], {}), '(frames)\n', (2335, 2343), False, 'import librosa\n'), ((1604, 1633), 'os.path.expanduser', 'os.path.expanduser', (['audio_dir'], {}), '(audio_dir)\n', (1622, 1633), False, 'import os\n'), ((4522, 4552), 'os.path.isfile', 'os.path.isfile', (['cache_filename'], {}), '(cache_filename)\n', (4536, 4552), False, 'import os\n'), ((5587, 5597), 'numpy.mean', 'np.mean', (['v'], {}), '(v)\n', (5594, 5597), True, 'import numpy as np\n'), ((5605, 5614), 'numpy.std', 'np.std', (['v'], {}), '(v)\n', (5611, 5614), True, 'import numpy as np\n'), ((4661, 4690), 'numpy.save', 'np.save', (['cache_filename', 'mfcc'], {}), '(cache_filename, mfcc)\n', (4668, 4690), True, 'import numpy as np\n'), ((4925, 4948), 'numpy.zeros', 'np.zeros', (['mfcc.shape[1]'], {}), '(mfcc.shape[1])\n', (4933, 4948), True, 'import numpy as np\n'), ((1853, 1869), 'pathlib.Path', 'Path', (['cache_file'], {}), '(cache_file)\n', (1857, 1869), False, 'from pathlib import Path\n')]
|
import tkinter
import cv2
import PIL.Image, PIL.ImageTk
import time
import numpy as np
import RPi.GPIO as GPIO
import mpv
import sys
import os
import serial
from time import sleep
import picamera
import io
#Initialization
#webcam/blindspot
capleft = ""
capright = ""
all_Cam_Off = 1
left_Camera_On = 0
right_Camera_On = 2
disp_camera = all_Cam_Off
#mpv for soft horn
player=mpv.MPV(start_event_thread=False)
player.audio_channels=1
serial_com = serial.Serial('/dev/ttyAMA0', 9600, timeout=4, parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS) #9600 8N1
#Determines which GPIO to use for right and left detection
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
right_Camera_GPIO = 2
left_Camera_GPIO = 3
GPIO.setup(right_Camera_GPIO, GPIO.IN)
GPIO.setup(left_Camera_GPIO, GPIO.IN)
def LCamOn():
global disp_camera
disp_camera = left_Camera_On
def CamOff():
global disp_camera
disp_camera = all_Cam_Off
def RCamOn():
global disp_camera
disp_camera = right_Camera_On
def SoftHorn():
print("Horn Fired")
player.play('/home/pi/car_horn.ogg')
def readPins():
global disp_camera
if(GPIO.input(right_Camera_GPIO) == GPIO.LOW):
RCamOn()
elif(GPIO.input(left_Camera_GPIO) == GPIO.LOW):
LCamOn()
else:
CamOff()
def ser_read():
data = ""
buf = ""
while(buf != '\r'):
data += buf
try:
tmp = serial_com.read().decode('UTF-8')
if(tmp == '>' or tmp == ' ' or tmp == '\n'): #ignore '>' characters
buf = ""
else:
buf = tmp
except:
break
return data
def serialIn():
global serial_com
global cur_speed
while True:
if(serial_com.is_open == False):
print("Serial Thread Closed")
quit()
echo = ser_read()
print("\nEcho: ")
print(echo)
if(echo == "010D"): #double check that next data is for correct command
data = ser_read()
print("\nData: ")
print(data)
#try:
data = data[-2:] #get last two characters
data = int(data[-2], 16)*16 + int(data[-1], 16) #convert hex ascii to int
#except:
# data = 0 #default to 0 on failure
print(data)
cur_speed = round(int(data)/1.6)
file = open('/tmp/cur_speed.txt', 'w')
file.write(str(cur_speed) + " MPH")
file.close()
print(cur_speed)
else:
pass #just started or off by one
def speedlimit():
# samples and responses include training data for number recognition
samples = np.loadtxt(r'/home/pi/Desktop/Documents/Capstone-local/generalsamples.data',np.float32)
responses = np.loadtxt(r'/home/pi/Desktop/Documents/Capstone-local/generalresponses.data',np.float32)
responses = responses.reshape((responses.size,1))
# train the classifier for number recognition - K-nearest neighbors model
model = cv2.ml.KNearest_create()
model.train(samples,cv2.ml.ROW_SAMPLE,responses)
# load the pre-trained Haar Cascade classifier for speed limit detection
speedCascade = cv2.CascadeClassifier(r"/home/pi/Desktop/Documents/Capstone-local/Classifier/haar/speedLimitStage17.xml")
stream = io.BytesIO()
camera = picamera.PiCamera()
camera.framerate = 60
camera.resolution = (800,480)
camera.awb_mode = 'auto'
counter = 0
# scaleVal and neig are parameters for speed limit sign detection
scaleVal = 1.2
neig = 0
#main loop
while True:
# the following block of code is needed to convert the image format used by the PiCamera library to the format required by the OpenCV library
# get a picture and specify parameters
camera.capture(stream, format = 'jpeg')
# Convert the picture into a numpy array
buff = np.frombuffer(stream.getvalue(), dtype=np.uint8)
stream.seek(0)
# Create an OpenCV image
img = cv2.imdecode(buff,1)
# Convert to greyscale
imgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# run object detection algorithm
objects = speedCascade.detectMultiScale(img,scaleVal,neig)
for (x,y,w,h) in objects:
# crop the image to get rid of the backround and leave only the number portion of the speedlimit sign
speedSignCropped = img[int(np.floor((2*y+h)/2)):int(np.floor((2*y+h)/2+y+h-((2*y+h)/2))),int(np.floor(x+w*0.15)):int(np.floor(x+w*0.95))]
# adaptive thresholding to clean up the image
thresh = cv2.adaptiveThreshold(speedSignCropped,255,1,1,25,2)
#Find contours within the cropped image
temp_name,contours,hierarchy = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
# detected digits will be stored in this array
speedLimitArray = []
# For each detected contour, run the digit recognition algorithm to extract the number
for cnt in contours:
# ignore contours that are too small to be a digit, contours of area less then 10 is most likely to be just a noise
if cv2.contourArea(cnt)>10:
# dimwension of numbers on a speed limit sign have a certain ratio. If the detected contour is outside of this ratio, reject it.
if h>15 and not(h/w>1.5) and (h/w>1):
cv2.rectangle(speedSignCropped,(x,y),(x+w,y+h),(0,255,0),2)
# specify the region of interest to which the digit recognition algorithm will be applied
roi = thresh[y:y+h,x:x+w]
roismall = cv2.resize(roi,(10,10))
roismall = roismall.reshape((1,100))
roismall = np.float32(roismall)
# perform digit recognition
retval, results, neigh_resp, dists = model.findNearest(roismall, k = 1)
# store the number in the array
speedLimitArray = np.append(speedLimitArray,results[0][0])
# if more than two digits are detected, it must be an error.
if len(speedLimitArray) == 2:
counter = counter+1
# return the speed limit only if the same speed limit has been detected three consecutive times
if counter > 2:
detected = max(speedLimitArray)*10+min(speedLimitArray)
speedLimit = int(detected)
file = open('/tmp/speedLimit.txt', 'w')
file.write(str(speedLimit) + " MPH")
file.close()
counter = 0;
class App:
def __init__(self, window, window_title, video_source=0):
self.window = window
self.window.title(window_title)
self.window.configure(background="white")
self.window.attributes('-fullscreen',True)
self.video_source = video_source
# Create a canvas that can fit the above video source size
self.canvas = tkinter.Canvas(window, width = 800, height = 450)
self.canvas.pack()
softHorn = tkinter.Button(window, text="Soft Horn", width=27, command=SoftHorn, fg='white', bg='black')
softHorn.pack(side=tkinter.LEFT, expand=True)
# After it is called once, the update method will be automatically called every delay milliseconds
try:
self.update()
self.window.mainloop()
except KeyboardInterrupt: #don't get stuck on keyboard interrupt
pass
def update(self):
global cur_speed
#Read GPIO here and set disp_camera
readPins()
# Get a frame from the video source
if disp_camera==left_Camera_On:
ret, frame = capleft.read()
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frame = cv2.resize(frame,(800,480))
elif disp_camera==right_Camera_On:
ret, frame = capright.read()
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frame = cv2.resize(frame,(800,480))
elif disp_camera==all_Cam_Off:
file = open('/tmp/cur_speed.txt', 'r')
cur_speed = file.read()
file.close()
file = open('/tmp/speedLimit.txt', 'r')
speedLimit = file.read()
file.close()
frame = np.full((480,800),240)
frame = cv2.putText(frame,"Vehicle Speed",(150,180),cv2.FONT_HERSHEY_SIMPLEX,1,(0,0,0),4)
frame = cv2.putText(frame,"Speed Limit",(450,180),cv2.FONT_HERSHEY_SIMPLEX,1,(0,0,0),4)
frame = cv2.putText(frame,cur_speed,(150,300),cv2.FONT_HERSHEY_SIMPLEX,1,(0,0,0),4)
frame = cv2.putText(frame,speedLimit,(450,300),cv2.FONT_HERSHEY_SIMPLEX,1,(0,0,0),4)
self.photo = PIL.ImageTk.PhotoImage(image = PIL.Image.fromarray(frame))
self.canvas.create_image(0, 0, image = self.photo, anchor = tkinter.NW)
self.window.after(60, self.update)
# "main" function
def init():
global capleft
global capright
global serial_com
file = open('/tmp/cur_speed.txt', 'w')
file.write("0 MPH")
file.close()
file = open('/tmp/speedLimit.txt', 'w')
file.write("Undetected")
file.close()
pid = os.fork()
if pid: #parent
capleft = cv2.VideoCapture(1)
capleft.set(3,800)
capleft.set(4,800)
capleft.set(cv2.CAP_PROP_FPS, 60)
capright = cv2.VideoCapture(3)
capright.set(3,200)
capright.set(4,200)
capright.set(cv2.CAP_PROP_FPS, 60)
# Create a window and pass it to the Application object
def check():
root.after(50, check)
root = tkinter.Tk()
root.after(50, check) #prevent tk from getting stuck on a keyboard interrupt
App(root, "Main")
print(disp_camera)
root.destroy() #exit the application
capleft.release() #cleanly release the cameras
capright.release()
serial_com.close()
cur_speed.close()
print("Done")
else: #child
pid = os.fork() #fork again and run both threads
if pid:
serialIn()
else:
speedlimit()
init()
|
[
"numpy.floor",
"cv2.imdecode",
"cv2.adaptiveThreshold",
"mpv.MPV",
"cv2.rectangle",
"serial.Serial",
"numpy.full",
"cv2.contourArea",
"RPi.GPIO.setup",
"cv2.cvtColor",
"cv2.ml.KNearest_create",
"tkinter.Button",
"numpy.append",
"numpy.loadtxt",
"os.fork",
"tkinter.Tk",
"cv2.resize",
"picamera.PiCamera",
"RPi.GPIO.setmode",
"io.BytesIO",
"RPi.GPIO.input",
"RPi.GPIO.setwarnings",
"cv2.putText",
"tkinter.Canvas",
"numpy.float32",
"cv2.VideoCapture",
"cv2.CascadeClassifier",
"cv2.findContours"
] |
[((402, 435), 'mpv.MPV', 'mpv.MPV', ([], {'start_event_thread': '(False)'}), '(start_event_thread=False)\n', (409, 435), False, 'import mpv\n'), ((477, 611), 'serial.Serial', 'serial.Serial', (['"""/dev/ttyAMA0"""', '(9600)'], {'timeout': '(4)', 'parity': 'serial.PARITY_NONE', 'stopbits': 'serial.STOPBITS_ONE', 'bytesize': 'serial.EIGHTBITS'}), "('/dev/ttyAMA0', 9600, timeout=4, parity=serial.PARITY_NONE,\n stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS)\n", (490, 611), False, 'import serial\n'), ((709, 732), 'RPi.GPIO.setwarnings', 'GPIO.setwarnings', (['(False)'], {}), '(False)\n', (725, 732), True, 'import RPi.GPIO as GPIO\n'), ((734, 756), 'RPi.GPIO.setmode', 'GPIO.setmode', (['GPIO.BCM'], {}), '(GPIO.BCM)\n', (746, 756), True, 'import RPi.GPIO as GPIO\n'), ((803, 841), 'RPi.GPIO.setup', 'GPIO.setup', (['right_Camera_GPIO', 'GPIO.IN'], {}), '(right_Camera_GPIO, GPIO.IN)\n', (813, 841), True, 'import RPi.GPIO as GPIO\n'), ((843, 880), 'RPi.GPIO.setup', 'GPIO.setup', (['left_Camera_GPIO', 'GPIO.IN'], {}), '(left_Camera_GPIO, GPIO.IN)\n', (853, 880), True, 'import RPi.GPIO as GPIO\n'), ((2850, 2941), 'numpy.loadtxt', 'np.loadtxt', (['"""/home/pi/Desktop/Documents/Capstone-local/generalsamples.data"""', 'np.float32'], {}), "('/home/pi/Desktop/Documents/Capstone-local/generalsamples.data',\n np.float32)\n", (2860, 2941), True, 'import numpy as np\n'), ((2955, 3048), 'numpy.loadtxt', 'np.loadtxt', (['"""/home/pi/Desktop/Documents/Capstone-local/generalresponses.data"""', 'np.float32'], {}), "('/home/pi/Desktop/Documents/Capstone-local/generalresponses.data',\n np.float32)\n", (2965, 3048), True, 'import numpy as np\n'), ((3192, 3216), 'cv2.ml.KNearest_create', 'cv2.ml.KNearest_create', ([], {}), '()\n', (3214, 3216), False, 'import cv2\n'), ((3369, 3483), 'cv2.CascadeClassifier', 'cv2.CascadeClassifier', (['"""/home/pi/Desktop/Documents/Capstone-local/Classifier/haar/speedLimitStage17.xml"""'], {}), "(\n '/home/pi/Desktop/Documents/Capstone-local/Classifier/haar/speedLimitStage17.xml'\n )\n", (3390, 3483), False, 'import cv2\n'), ((3489, 3501), 'io.BytesIO', 'io.BytesIO', ([], {}), '()\n', (3499, 3501), False, 'import io\n'), ((3516, 3535), 'picamera.PiCamera', 'picamera.PiCamera', ([], {}), '()\n', (3533, 3535), False, 'import picamera\n'), ((9733, 9742), 'os.fork', 'os.fork', ([], {}), '()\n', (9740, 9742), False, 'import os\n'), ((1245, 1274), 'RPi.GPIO.input', 'GPIO.input', (['right_Camera_GPIO'], {}), '(right_Camera_GPIO)\n', (1255, 1274), True, 'import RPi.GPIO as GPIO\n'), ((4223, 4244), 'cv2.imdecode', 'cv2.imdecode', (['buff', '(1)'], {}), '(buff, 1)\n', (4235, 4244), False, 'import cv2\n'), ((4296, 4333), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2GRAY'], {}), '(img, cv2.COLOR_BGR2GRAY)\n', (4308, 4333), False, 'import cv2\n'), ((7409, 7454), 'tkinter.Canvas', 'tkinter.Canvas', (['window'], {'width': '(800)', 'height': '(450)'}), '(window, width=800, height=450)\n', (7423, 7454), False, 'import tkinter\n'), ((7509, 7606), 'tkinter.Button', 'tkinter.Button', (['window'], {'text': '"""Soft Horn"""', 'width': '(27)', 'command': 'SoftHorn', 'fg': '"""white"""', 'bg': '"""black"""'}), "(window, text='Soft Horn', width=27, command=SoftHorn, fg=\n 'white', bg='black')\n", (7523, 7606), False, 'import tkinter\n'), ((9793, 9812), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(1)'], {}), '(1)\n', (9809, 9812), False, 'import cv2\n'), ((9934, 9953), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(3)'], {}), '(3)\n', (9950, 9953), False, 'import cv2\n'), ((10218, 10230), 'tkinter.Tk', 'tkinter.Tk', ([], {}), '()\n', (10228, 10230), False, 'import tkinter\n'), ((10626, 10635), 'os.fork', 'os.fork', ([], {}), '()\n', (10633, 10635), False, 'import os\n'), ((1317, 1345), 'RPi.GPIO.input', 'GPIO.input', (['left_Camera_GPIO'], {}), '(left_Camera_GPIO)\n', (1327, 1345), True, 'import RPi.GPIO as GPIO\n'), ((4832, 4889), 'cv2.adaptiveThreshold', 'cv2.adaptiveThreshold', (['speedSignCropped', '(255)', '(1)', '(1)', '(25)', '(2)'], {}), '(speedSignCropped, 255, 1, 1, 25, 2)\n', (4853, 4889), False, 'import cv2\n'), ((4982, 5050), 'cv2.findContours', 'cv2.findContours', (['thresh', 'cv2.RETR_EXTERNAL', 'cv2.CHAIN_APPROX_SIMPLE'], {}), '(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n', (4998, 5050), False, 'import cv2\n'), ((8226, 8264), 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_BGR2RGB'], {}), '(frame, cv2.COLOR_BGR2RGB)\n', (8238, 8264), False, 'import cv2\n'), ((8286, 8315), 'cv2.resize', 'cv2.resize', (['frame', '(800, 480)'], {}), '(frame, (800, 480))\n', (8296, 8315), False, 'import cv2\n'), ((8421, 8459), 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_BGR2RGB'], {}), '(frame, cv2.COLOR_BGR2RGB)\n', (8433, 8459), False, 'import cv2\n'), ((8481, 8510), 'cv2.resize', 'cv2.resize', (['frame', '(800, 480)'], {}), '(frame, (800, 480))\n', (8491, 8510), False, 'import cv2\n'), ((5437, 5457), 'cv2.contourArea', 'cv2.contourArea', (['cnt'], {}), '(cnt)\n', (5452, 5457), False, 'import cv2\n'), ((8802, 8826), 'numpy.full', 'np.full', (['(480, 800)', '(240)'], {}), '((480, 800), 240)\n', (8809, 8826), True, 'import numpy as np\n'), ((8846, 8940), 'cv2.putText', 'cv2.putText', (['frame', '"""Vehicle Speed"""', '(150, 180)', 'cv2.FONT_HERSHEY_SIMPLEX', '(1)', '(0, 0, 0)', '(4)'], {}), "(frame, 'Vehicle Speed', (150, 180), cv2.FONT_HERSHEY_SIMPLEX, 1,\n (0, 0, 0), 4)\n", (8857, 8940), False, 'import cv2\n'), ((8949, 9041), 'cv2.putText', 'cv2.putText', (['frame', '"""Speed Limit"""', '(450, 180)', 'cv2.FONT_HERSHEY_SIMPLEX', '(1)', '(0, 0, 0)', '(4)'], {}), "(frame, 'Speed Limit', (450, 180), cv2.FONT_HERSHEY_SIMPLEX, 1,\n (0, 0, 0), 4)\n", (8960, 9041), False, 'import cv2\n'), ((9050, 9139), 'cv2.putText', 'cv2.putText', (['frame', 'cur_speed', '(150, 300)', 'cv2.FONT_HERSHEY_SIMPLEX', '(1)', '(0, 0, 0)', '(4)'], {}), '(frame, cur_speed, (150, 300), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, \n 0, 0), 4)\n', (9061, 9139), False, 'import cv2\n'), ((9147, 9236), 'cv2.putText', 'cv2.putText', (['frame', 'speedLimit', '(450, 300)', 'cv2.FONT_HERSHEY_SIMPLEX', '(1)', '(0, 0, 0)', '(4)'], {}), '(frame, speedLimit, (450, 300), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,\n 0, 0), 4)\n', (9158, 9236), False, 'import cv2\n'), ((5697, 5768), 'cv2.rectangle', 'cv2.rectangle', (['speedSignCropped', '(x, y)', '(x + w, y + h)', '(0, 255, 0)', '(2)'], {}), '(speedSignCropped, (x, y), (x + w, y + h), (0, 255, 0), 2)\n', (5710, 5768), False, 'import cv2\n'), ((5959, 5984), 'cv2.resize', 'cv2.resize', (['roi', '(10, 10)'], {}), '(roi, (10, 10))\n', (5969, 5984), False, 'import cv2\n'), ((6081, 6101), 'numpy.float32', 'np.float32', (['roismall'], {}), '(roismall)\n', (6091, 6101), True, 'import numpy as np\n'), ((6354, 6395), 'numpy.append', 'np.append', (['speedLimitArray', 'results[0][0]'], {}), '(speedLimitArray, results[0][0])\n', (6363, 6395), True, 'import numpy as np\n'), ((4640, 4665), 'numpy.floor', 'np.floor', (['((2 * y + h) / 2)'], {}), '((2 * y + h) / 2)\n', (4648, 4665), True, 'import numpy as np\n'), ((4665, 4716), 'numpy.floor', 'np.floor', (['((2 * y + h) / 2 + y + h - (2 * y + h) / 2)'], {}), '((2 * y + h) / 2 + y + h - (2 * y + h) / 2)\n', (4673, 4716), True, 'import numpy as np\n'), ((4706, 4728), 'numpy.floor', 'np.floor', (['(x + w * 0.15)'], {}), '(x + w * 0.15)\n', (4714, 4728), True, 'import numpy as np\n'), ((4730, 4752), 'numpy.floor', 'np.floor', (['(x + w * 0.95)'], {}), '(x + w * 0.95)\n', (4738, 4752), True, 'import numpy as np\n')]
|
import difflib
import os
import shutil
import subprocess
import sys
import time
import numpy as np
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import *
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from threading import Thread
# slash = '/' # linux
slash = '\\' # windows
#'b\'1\\r\\n\''
class Data:
def get_time(self, mask): return self.matrix_time[mask]
def get_time_sum(self, mask): return np.sum(self.matrix_time[mask], axis=0)
def get_tests_count(self): return len(self.matrix_time)
def get_params(self): return self.params
def get_results_tests(self, mask): return self.matrix_is_complete[mask]
def get_test_name(self, mask): return self.test_name[mask]
def clear_data(self):
self.matrix_time.clear()
self.matrix_is_complete.clear()
def download_data(self):
file = open(self.path_statistic, 'r')
b, g = file.readline()
# finish writing
def __init__(self, matrix_time, matrix_is_complete, path_statistic, test_name, params):
super().__init__()
self.matrix_time = matrix_time
self.matrix_is_complete = matrix_is_complete
self.path_statistic = path_statistic
self.test_name = test_name
self.params = params
class Kernel:
@staticmethod
def __is_equal_file_default(path1, path2):
if not os.path.isfile(path1) or not os.path.isfile(path1):
return False
file1 = open(path1, 'r') # result
file2 = open(path2, 'r') # reference
diff = difflib.ndiff(file1.readlines(), file2.readlines())
return ''.join(x for x in diff if x.startswith('- ')) == ""
@staticmethod
def __is_equal_file_true(path1, path2):
return True
@staticmethod
def __is_equal_file_user(path):
def func(path1, path2):
if not os.path.isfile(path1) or not os.path.isfile(path1):
return False
return subprocess.check_output([path, path1, path2]).__str__() == 'b\'1\''
return func
@staticmethod
def __is_equal_file_user_py(path):
def func(path1, path2):
if not os.path.isfile(path1) or not os.path.isfile(path1):
return False
return subprocess.check_output(['python', path, path1, path2]).__str__() == 'b\'1\\r\\n\''
return func
def __init__(self):
self.__program = ""
self.__output = ""
self.params = np.array([int(1), int(1)])
self.__matrix_time = np.array([])
self.__matrix_is_complete = np.array([])
self.__cmp = self.__is_equal_file_default
self.__template_call = ''
def __execute_test(self, string_call, test, res_i, reference, stat):
time_work = -1 * np.ones(int(self.params[1] + 1 - self.params[0]))
is_complete = np.array([False for i in range(self.params[1] + 1 - self.params[0])])
for i in range(int(self.params[1] + 1 - self.params[0])):
param = (i + self.params[0]).__str__()
res = res_i + slash + param + '.txt'
call = string_call.replace('$pathout', res).replace('$paramvalue', param).split()
timer = time.time()
subprocess.check_output(call).__str__()
time_work[i] = time.time() - timer
is_complete[i] = self.__cmp(res, reference)
stat.write(test + '; ' + param + '; ' + (time_work[i]).__str__() + '; ' + (is_complete[i]).__str__() + '\n')
return [time_work, is_complete]
def __execute_test_wo_ref(self, test, stat): # without output
time_work = -1 * np.ones(int(self.params[1] + 1 - self.params[0]))
for i in range(int(self.params[1] + 1 - self.params[0])):
param = (i + self.params[0]).__str__()
timer = time.time()
subprocess.check_output([self.__program, param, test]).__str__()
time_work[i] = time.time() - timer
stat.write(test + '; ' + param + '; ' + (time_work[i]).__str__() + '\n')
return time_work
def __start_tests(self, path_test, tests, path_reference, references):
self.__matrix_time = np.array([np.zeros(self.params[1] + 1 - self.params[0])])
self.__matrix_is_complete = np.array([[False for i in range(self.params[1] + 1 - self.params[0])]])
stat = open(self.__output + "statistic.csv", 'w')
stat.write("test_name; param; time; result\n")
for i in range(len(tests)):
test = path_test + tests[i]
reference = path_reference + references[i]
res = self.__output + i.__str__()
os.mkdir(res)
a, b = self.__execute_test(self.__template_call.replace('$pathin', test), test, res, reference, stat)
self.__matrix_time = np.append(self.__matrix_time, [a], axis=0)
self.__matrix_is_complete = np.append(self.__matrix_is_complete, [b], axis=0)
self.__matrix_time = np.delete(self.__matrix_time, 0, axis=0)
self.__matrix_is_complete = np.delete(self.__matrix_is_complete, 0, axis=0)
stat.close()
def __start_tests_wo_ref(self, path_test, tests):
self.__matrix_time = np.array([np.zeros(self.params[1] + 1 - self.params[0])])
stat = open(self.__output + "statistic.csv", 'w')
stat.write("test_name; param; time\n")
for i in range(len(tests)):
test = path_test + tests[i]
self.__matrix_time = np.append(self.__matrix_time, [self.__execute_test_wo_ref(test, stat)], axis=0)
self.__matrix_time = np.delete(self.__matrix_time, 0, axis=0)
stat.close()
def __validation(self, path_test, path_reference, path_cmp):
is_valid = True
message = ""
t = os.path.isfile(self.__program)
if not t:
message += "path program\n"
is_valid &= t
t = os.path.exists(path_test)
count_test = 0
if not t:
message += "path test\n"
else:
count_test = 1
if os.path.isdir(path_test):
listdir = os.listdir(path_test)
count_test = len(listdir)
for file_name in listdir:
if os.path.isdir(path_test + slash + file_name):
t = False
message += 'test include dir\n'
break
is_valid &= t
if not os.path.isdir(self.__output):
self.__output = os.getcwd()
message += "path result\n"
count_reference = 0
t = path_reference == "" or os.path.exists(path_reference)
if not t:
message += "path reference\n"
else:
count_reference = 1
if os.path.isdir(path_reference):
listdir = os.listdir(path_reference)
count_reference = len(listdir)
for file_name in listdir:
if os.path.isdir(path_reference + slash + file_name):
t = False
message += 'reference include dir\n'
break
is_valid &= t
t = count_reference == count_test
if is_valid and not t:
message += 'quantity mismatch reference, test\n'
is_valid &= t
if os.path.isfile(path_cmp):
if path_cmp.find('.py') != -1:
self.__cmp = self.__is_equal_file_user_py(path_cmp)
else:
self.__cmp = self.__is_equal_file_user(path_cmp)
else:
message += "path comparator\n"
return is_valid, message
def start_test_by_path(self, path_exe, path_test, params, path_res, path_reference, path_cmp, _template_call):
self.__program = path_exe
self.params = [min(params), max(params)]
self.__output = path_res
is_valid, message = self.__validation(path_test, path_reference, path_cmp)
if not is_valid:
return None, message
self.__template_call = path_exe + ' ' +_template_call
self.__output += slash + 'results'
if os.path.isdir(self.__output):
shutil.rmtree(self.__output)
tests = np.array([""])
if os.path.isdir(path_test): # check path_test is fold or file
tests = np.array(os.listdir(path_test))
path_test += slash
if path_reference == "":
os.mkdir(self.__output)
self.__output += slash
self.__start_tests_wo_ref(path_test, tests)
return Data(self.__matrix_time, self.__matrix_is_complete, path_test + "statistic.txt", tests,
self.params), message
reference = np.array([""])
if os.path.isdir(path_reference): # check path_reference is fold or file
reference = np.array(os.listdir(path_reference))
path_reference += slash
os.mkdir(self.__output)
self.__output += slash
self.__start_tests(path_test, tests, path_reference, reference)
return Data(self.__matrix_time, self.__matrix_is_complete, path_test + "statistic.txt", tests,
self.params), message
# Next code is UI
class ProgressWindow(QWidget):
def __init__(self):
super().__init__()
self.main_vertical_layout = QVBoxLayout()
self.progress_bar = QProgressBar(self)
self.progress_label = QLabel("Сделано столько то тестов")
self.main_vertical_layout.addWidget(self.progress_label)
self.main_vertical_layout.addWidget(self.progress_bar)
self.setLayout(self.main_vertical_layout)
self.setWindowTitle("Progress:")
self.setGeometry(400, 400, 300, 70)
def set_test_status(self, complete, number_of_test):
self.progress_bar.setValue(complete * 100 / number_of_test)
self.progress_label.setText(f"Complete {complete} tests of {number_of_test}")
def get_test_setter(self):
return self.set_test_status
class MainWindow(QWidget):
def __init__(self):
super().__init__()
self.error_window = ErrorWindow()
self.kernel = Kernel()
self.data = []
self.mask = []
self.progressive_window = ProgressWindow()
self.result = None
main_horizontal_layout = QHBoxLayout()
main_vertical_layout = QVBoxLayout()
test_scenario_label = QLabel("Path to executable scenario file")
self.test_scenario_path = QLineEdit()
path_tests_label = QLabel("Path to file(folder) with the test(tests)")
self.path_tests_path = QLineEdit()
test_params_layout = QHBoxLayout()
test_params_layout.addStretch(0)
self.test_params_label = QLabel("Current Param Range (min = 1, max = 1000)")
self.test_params_value_min = QLineEdit("1")
self.test_params_value_min.textChanged.connect(self.on_value_changed_min)
self.test_params_value_max = QLineEdit("1000")
self.test_params_value_max.textChanged.connect(self.on_value_changed_max)
test_params_layout.addWidget(self.test_params_label)
test_params_layout.addWidget(self.test_params_value_min)
test_params_layout.addStretch(0)
test_params_layout.addWidget(self.test_params_value_max)
test_params_layout.addStretch(20)
path_answers_label = QLabel("Path to folder with default test results")
self.path_answers_path = QLineEdit()
path_result_label = QLabel("Path to folder to save the results")
self.path_result_path = QLineEdit()
path_comp_label = QLabel("Path to answers comparator executable file")
self.path_comp_path = QLineEdit()
calc_button = QPushButton("Start Testing")
calc_button.clicked.connect(self.on_calc_click)
self.param_line_edit = QLineEdit()
self.param_line_edit_label = QLabel("Interpolation string")
main_vertical_layout.addStretch(1)
main_vertical_layout.addWidget(test_scenario_label)
main_vertical_layout.addStretch(0)
main_vertical_layout.addWidget(self.test_scenario_path)
main_vertical_layout.addStretch(1)
main_vertical_layout.addWidget(path_tests_label)
main_vertical_layout.addStretch(0)
main_vertical_layout.addWidget(self.path_tests_path)
main_vertical_layout.addStretch(1)
main_vertical_layout.addLayout(test_params_layout)
main_vertical_layout.addStretch(1)
main_vertical_layout.addWidget(path_answers_label)
main_vertical_layout.addStretch(0)
main_vertical_layout.addWidget(self.path_answers_path)
main_vertical_layout.addStretch(1)
main_vertical_layout.addWidget(path_result_label)
main_vertical_layout.addStretch(0)
main_vertical_layout.addWidget(self.path_result_path)
main_vertical_layout.addStretch(1)
main_vertical_layout.addWidget(path_comp_label)
main_vertical_layout.addStretch(0)
main_vertical_layout.addWidget(self.path_comp_path)
main_vertical_layout.addStretch(1)
main_vertical_layout.addWidget(self.param_line_edit_label)
main_vertical_layout.addStretch(0)
main_vertical_layout.addWidget(self.param_line_edit)
main_vertical_layout.addStretch(1)
main_vertical_layout.addWidget(calc_button)
main_horizontal_layout.addLayout(main_vertical_layout)
self.setLayout(main_horizontal_layout)
self.setGeometry(300, 200, 1280, 720)
self.showFullScreen()
self.setWindowTitle('QLineEdit')
def on_value_changed_min(self):
if len(self.test_params_value_min.text()) != 0:
try:
temp_value = int(self.test_params_value_min.text())
except ValueError:
temp_value = 1
if temp_value > 1000 or temp_value < 1:
temp_value = 0
self.test_params_value_min.setText(str(temp_value))
def on_value_changed_max(self):
if len(self.test_params_value_max.text()) != 0:
try:
temp_value = int(self.test_params_value_max.text())
except ValueError:
temp_value = 1000
if temp_value > 1000 or temp_value < 1:
temp_value = 1000
self.test_params_value_max.setText(str(temp_value))
def on_calc_click(self):
path_exe = self.test_scenario_path.text()
path_test = self.path_tests_path.text()
# params = [2, 4]
params = [int(self.test_params_value_min.text()), int(self.test_params_value_max.text())]
path_reference = self.path_answers_path.text()
path_res = self.path_result_path.text()
cmp = self.path_comp_path.text()
d = data_for_test()
interpolation_string = self.param_line_edit.text()
# result, message = self.kernel.start_test_by_path(path_exe, path_test, params, path_res, path_reference, cmp,
# self.progressive_window.get_test_setter())
result, message = self.kernel.start_test_by_path(d[0], d[1], d[2], d[3], d[4], d[5], interpolation_string)
if result is None:
self.error_window.set_title("Error!")
self.error_window.set_error(message)
self.error_window.show()
else:
print(result.get_time([True for i in range(result.get_tests_count())]))
self.mask = [True for i in range(result.get_tests_count())]
test_info = get_configuration_list(result, self.mask)
self.result = ResultWindow(test_info)
self.result.show()
if len(message) != 0:
self.error_window.set_title("Warning!")
self.error_window.set_error(f"{message}We used default")
self.error_window.show()
class ResultWindow(QWidget):
def template(self, number, func):
def f():
return self.on_curve_show_change(number, func())
return f
def __init__(self, result_data):
super().__init__()
self.setGeometry(300, 200, 1280, 720)
self.result_list = QVBoxLayout()
for i in range(len(result_data)):
self.result_list.addLayout(
self.get_result_item(result_data[i], i)
)
self.result_list.addSpacing(35)
self.result = result_data
group_box = QGroupBox()
group_box.setLayout(self.result_list)
self.scroll = QScrollArea()
self.scroll.setWidget(group_box)
self.scroll.setWidgetResizable(True)
self.left_vertical_layout = QVBoxLayout()
self.left_vertical_layout.addWidget(self.scroll)
self.sum_check_box = QCheckBox("Display result Sum")
self.sum_check_box.stateChanged.connect(self.on_sum_show_change)
self.left_vertical_layout.addWidget(self.sum_check_box)
self.curve_status_show = [True for i in range(len(result_data))]
self.test_names = [test[0].name for test in result_data]
self.result_graph = PlotCanvas(width=8, height=8, curve_status_show=self.curve_status_show, data=result_data,
test_names=self.test_names)
self.main_horizontal_layout = QHBoxLayout()
self.main_horizontal_layout.setAlignment(Qt.AlignRight)
self.main_horizontal_layout.addLayout(self.left_vertical_layout)
self.main_horizontal_layout.addWidget(self.result_graph)
self.main_horizontal_layout.setAlignment(Qt.AlignLeft)
self.setLayout(self.main_horizontal_layout)
def on_sum_show_change(self):
if not (not self.sum_check_box.checkState() == Qt.Checked):
self.main_horizontal_layout.removeWidget(self.result_graph)
self.result_graph.resize(0, 0)
self.result_graph = PlotCanvasSum(width=8, height=8, curve_status_show=self.curve_status_show,
data=self.result,
test_names=self.test_names)
self.main_horizontal_layout.addWidget(self.result_graph)
else:
self.main_horizontal_layout.removeWidget(self.result_graph)
self.result_graph.resize(0, 0)
self.result_graph = PlotCanvas(width=8, height=8, curve_status_show=self.curve_status_show, data=self.result,
test_names=self.test_names)
self.main_horizontal_layout.addWidget(self.result_graph)
def on_curve_show_change(self, number_of_curve, status):
self.sum_check_box.setChecked(False)
self.curve_status_show[number_of_curve] = status
self.main_horizontal_layout.removeWidget(self.result_graph)
self.result_graph.resize(0, 0)
self.result_graph = PlotCanvas(width=8, height=8, curve_status_show=self.curve_status_show, data=self.result,
test_names=self.test_names)
self.main_horizontal_layout.addWidget(self.result_graph)
def get_result_item(self, data_list, number_of_test):
item_layout = QHBoxLayout()
item_check_box = QCheckBox()
left_vertical_layout = QVBoxLayout()
item_check_box.setChecked(True)
item_check_box.stateChanged.connect(
self.template(number_of_test, item_check_box.isChecked))
left_vertical_layout.addWidget(item_check_box)
left_vertical_layout.addStretch(1)
item_layout.addLayout(left_vertical_layout)
item_layout.addStretch(0)
sub_items_layout = QVBoxLayout()
for data in data_list:
sub_record_layout = QHBoxLayout()
item_name = QLabel(f"Test name: {data.name}", )
item_time = QLabel(f"Execution time: {round(data.time, 6)} seconds,")
item_status = QLabel(f"Test status: {data.status},")
item_number = QLabel(str(data.number) + ",")
item_number_cores = QLabel(f"Param value: {data.param_value}")
sub_record_layout.addWidget(item_name)
sub_record_layout.addWidget(item_time)
sub_record_layout.addWidget(item_status)
sub_record_layout.addWidget(item_number)
sub_record_layout.addWidget(item_number_cores)
sub_items_layout.addLayout(sub_record_layout)
# sub_items_layout.addStretch(0.1) maybe do something with space between items
item_layout.addLayout(sub_items_layout)
item_layout.addStretch(0)
return item_layout
class PlotCanvasSum(FigureCanvas):
def __init__(self, width=7, height=7, dpi=80, data=None, curve_status_show=None, test_names=[]):
if curve_status_show is None:
curve_status_show = []
fig = Figure(figsize=(width, height), dpi=dpi)
FigureCanvas.__init__(self, fig)
self.plot(data, curve_status_show)
self.draw()
def plot(self, data_list, curve_status_show):
ax = self.figure.add_subplot(111)
sum_y = np.zeros_like(data_list[0])
x = np.array([current_test.param_value for current_test in data_list[-1]])
for test in range(len(data_list)):
if curve_status_show[test]:
y = np.array([current_test.time for current_test in data_list[test]])
sum_y += y
ax.plot(x, sum_y, label="Test: Result sum")
ax.scatter(x=x, y=sum_y, color="red")
ax.legend()
ax.set_ylabel("Execution time")
ax.set_xlabel("Param value")
ax.grid()
ax.set_title("Tasks Graph")
class PlotCanvas(FigureCanvas):
def __init__(self, width=7, height=7, dpi=80, data=None, curve_status_show=None, test_names=[]):
if curve_status_show is None:
curve_status_show = []
fig = Figure(figsize=(width, height), dpi=dpi)
FigureCanvas.__init__(self, fig)
self.plot(data, curve_status_show, test_names)
self.draw()
def plot(self, data_list, curve_status_show, test_names):
ax = self.figure.add_subplot(111)
for test in range(len(data_list)):
if curve_status_show[test]:
x = np.array([current_test.param_value for current_test in data_list[test]])
y = np.array([current_test.time for current_test in data_list[test]])
ax.plot(x, y, label=f"Test: {test_names[test]}")
for config in range(len(data_list[test])):
if data_list[test][config].status == "Complete":
ax.scatter(x=data_list[test][config].param_value, y=data_list[test][config].time, color="green")
else:
ax.scatter(x=data_list[test][config].param_value, y=data_list[test][config].time, color="red")
ax.legend()
ax.set_ylabel("Execution time")
ax.set_xlabel("Param value")
ax.grid()
ax.set_title("Tasks Graph")
class ErrorWindow(QWidget):
def __init__(self):
super().__init__()
layout = QVBoxLayout()
layout.addWidget(QLabel("Next data is not valid!"))
self.error_text = QLabel("")
layout.addWidget(self.error_text)
self.setLayout(layout)
self.setGeometry(600, 500, 300, 100)
self.setWindowTitle("Error!")
def set_error(self, error_text):
self.error_text.setText(error_text)
def set_title(self, title):
self.setWindowTitle(title)
class TestConfiguration:
def __init__(self, name, time_stat, status, number, count_of_cores):
self.name = name
self.time = time_stat
self.status = status
self.number = number
self.param_value = count_of_cores
def get_configuration_list(data_list, mask):
params = data_list.get_params()
delta = params[1] - params[0] + 1
configuration_time_list = data_list.get_time(mask)
configuration_status_list = data_list.get_results_tests(mask)
configuration_name_list = data_list.get_test_name(mask)
return np.array([[TestConfiguration(
configuration_name_list[j], # test_name should be here
configuration_time_list[j][i],
"Complete" if (configuration_status_list[j][i]) else "Failed",
delta * j + i,
params[0] + i)
for i in range(delta)] for j in range(len(configuration_time_list))])
import unittest
def data_for_test():
this_path = os.getcwd()
return [this_path + slash + 'test' + slash + 'main.exe', # 0
this_path + slash + 'test' + slash + 'test', # 1
[1, 4], # 2
this_path + slash + 'test', # 3
this_path + slash + 'test' + slash + 'reference', # 4
this_path + slash + 'test' + slash + 'cmp.py'] # 5
class TestKernel(unittest.TestCase):
kernel = Kernel()
d = data_for_test()
app = QApplication(sys.argv)
error_window = ErrorWindow()
error_window.set_title("Error!")
error_window.set_error("Some errors!")
# corrects
def test_error_window_title(self):
self.assertEqual("Error!", self.error_window.windowTitle())
def test_error_window_content(self):
self.assertEqual("Some errors!", self.error_window.error_text.text())
def test_correct_1(self):
res, message = self.kernel.start_test_by_path(self.d[0], self.d[1], self.d[2], self.d[3], self.d[4], self.d[5])
self.assertTrue(res is not None)
self.assertEqual(message, "")
def test_correct_2(self):
res, message = self.kernel.start_test_by_path(self.d[0], self.d[1] + slash + 'test1.txt', self.d[2],
self.d[3], self.d[4] + slash + 'res2.txt', self.d[5])
self.assertTrue(res is not None)
self.assertEqual(message, "")
def test_correct_3(self):
res, message = self.kernel.start_test_by_path(self.d[0], self.d[1] + '2', self.d[2],
self.d[3], self.d[4] + slash + 'res1.txt', self.d[5])
self.assertTrue(res is not None)
self.assertEqual(message, "")
# errors
def test_program_not_correct(self):
res, message = self.kernel.start_test_by_path('c:\\mIN.exe', self.d[1], self.d[2],
self.d[3], self.d[4], self.d[5])
self.assertTrue(res is None)
self.assertEqual(message, 'path program\n')
def test_not_correct(self):
res, message = self.kernel.start_test_by_path(self.d[0], 'c:\\main', self.d[2],
self.d[3], self.d[4], self.d[5])
self.assertTrue(res is None)
self.assertEqual(message, 'path test\n')
def test_include_dir(self):
os.mkdir(self.d[1] + '\\temp')
res, message = self.kernel.start_test_by_path(self.d[0], self.d[1], self.d[2],
self.d[3], self.d[4], self.d[5])
self.assertTrue(res is None)
self.assertEqual(message, "test include dir\n")
os.rmdir(self.d[1] + '\\temp')
def test_and_program_not_correct(self):
res, message = self.kernel.start_test_by_path('c:\\mIN.exe', 'c:\\main', self.d[2],
self.d[3], self.d[4], self.d[5])
self.assertTrue(res is None)
self.assertEqual(message, 'path program\npath test\n')
def test_reference_not_correct(self):
res, message = self.kernel.start_test_by_path(self.d[0], self.d[1], self.d[2],
self.d[3], 'file_name', self.d[5])
self.assertTrue(res is None)
self.assertEqual(message, 'path reference\n')
def test_reference_include_dir(self):
os.mkdir(self.d[4] + slash + 'temp')
res, message = self.kernel.start_test_by_path(self.d[0], self.d[1], self.d[2],
self.d[3], self.d[4], self.d[5])
self.assertTrue(res is None)
self.assertEqual(message, 'reference include dir\n')
os.rmdir(self.d[4] + slash + 'temp')
def test_mismatch_test_reference_1(self):
res, message = self.kernel.start_test_by_path(self.d[0], self.d[1], self.d[2],
self.d[3], self.d[4] + slash + 'res1.txt', self.d[5])
self.assertTrue(res is None)
self.assertEqual(message, 'quantity mismatch reference, test\n')
def test_mismatch_test_reference_2(self):
res, message = self.kernel.start_test_by_path(self.d[0], self.d[1] + slash + 'test1.txt', self.d[2],
self.d[3], self.d[4], self.d[5])
self.assertTrue(res is None)
self.assertEqual(message, 'quantity mismatch reference, test\n')
# warnings
def test_result_not_correct(self):
res, message = self.kernel.start_test_by_path(self.d[0], self.d[1], self.d[2],
'file_name', self.d[4], self.d[5])
self.assertTrue(res is not None)
self.assertEqual(message, 'path result\n')
def test_cmp_not_correct(self):
res, message = self.kernel.start_test_by_path(self.d[0], self.d[1], self.d[2],
self.d[3], self.d[4], self.d[4])
self.assertTrue(res is not None)
self.assertEqual(message, 'path comparator\n')
if __name__ == "__main__":
# unittest.main()
app = QApplication(sys.argv)
# time.sleep(10)
ex = MainWindow()
#ex.on_calc_click()
ex.show()
sys.exit(app.exec_())
|
[
"os.listdir",
"os.mkdir",
"numpy.zeros_like",
"numpy.sum",
"shutil.rmtree",
"os.getcwd",
"os.path.isdir",
"subprocess.check_output",
"os.path.exists",
"numpy.zeros",
"time.time",
"numpy.append",
"os.path.isfile",
"matplotlib.figure.Figure",
"numpy.array",
"matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg.__init__",
"os.rmdir",
"numpy.delete"
] |
[((24478, 24489), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (24487, 24489), False, 'import os\n'), ((483, 521), 'numpy.sum', 'np.sum', (['self.matrix_time[mask]'], {'axis': '(0)'}), '(self.matrix_time[mask], axis=0)\n', (489, 521), True, 'import numpy as np\n'), ((2571, 2583), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (2579, 2583), True, 'import numpy as np\n'), ((2620, 2632), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (2628, 2632), True, 'import numpy as np\n'), ((4992, 5032), 'numpy.delete', 'np.delete', (['self.__matrix_time', '(0)'], {'axis': '(0)'}), '(self.__matrix_time, 0, axis=0)\n', (5001, 5032), True, 'import numpy as np\n'), ((5069, 5116), 'numpy.delete', 'np.delete', (['self.__matrix_is_complete', '(0)'], {'axis': '(0)'}), '(self.__matrix_is_complete, 0, axis=0)\n', (5078, 5116), True, 'import numpy as np\n'), ((5603, 5643), 'numpy.delete', 'np.delete', (['self.__matrix_time', '(0)'], {'axis': '(0)'}), '(self.__matrix_time, 0, axis=0)\n', (5612, 5643), True, 'import numpy as np\n'), ((5789, 5819), 'os.path.isfile', 'os.path.isfile', (['self.__program'], {}), '(self.__program)\n', (5803, 5819), False, 'import os\n'), ((5913, 5938), 'os.path.exists', 'os.path.exists', (['path_test'], {}), '(path_test)\n', (5927, 5938), False, 'import os\n'), ((7347, 7371), 'os.path.isfile', 'os.path.isfile', (['path_cmp'], {}), '(path_cmp)\n', (7361, 7371), False, 'import os\n'), ((8150, 8178), 'os.path.isdir', 'os.path.isdir', (['self.__output'], {}), '(self.__output)\n', (8163, 8178), False, 'import os\n'), ((8238, 8252), 'numpy.array', 'np.array', (["['']"], {}), "([''])\n", (8246, 8252), True, 'import numpy as np\n'), ((8264, 8288), 'os.path.isdir', 'os.path.isdir', (['path_test'], {}), '(path_test)\n', (8277, 8288), False, 'import os\n'), ((8743, 8757), 'numpy.array', 'np.array', (["['']"], {}), "([''])\n", (8751, 8757), True, 'import numpy as np\n'), ((8769, 8798), 'os.path.isdir', 'os.path.isdir', (['path_reference'], {}), '(path_reference)\n', (8782, 8798), False, 'import os\n'), ((8949, 8972), 'os.mkdir', 'os.mkdir', (['self.__output'], {}), '(self.__output)\n', (8957, 8972), False, 'import os\n'), ((20837, 20877), 'matplotlib.figure.Figure', 'Figure', ([], {'figsize': '(width, height)', 'dpi': 'dpi'}), '(figsize=(width, height), dpi=dpi)\n', (20843, 20877), False, 'from matplotlib.figure import Figure\n'), ((20886, 20918), 'matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg.__init__', 'FigureCanvas.__init__', (['self', 'fig'], {}), '(self, fig)\n', (20907, 20918), True, 'from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\n'), ((21092, 21119), 'numpy.zeros_like', 'np.zeros_like', (['data_list[0]'], {}), '(data_list[0])\n', (21105, 21119), True, 'import numpy as np\n'), ((21132, 21202), 'numpy.array', 'np.array', (['[current_test.param_value for current_test in data_list[-1]]'], {}), '([current_test.param_value for current_test in data_list[-1]])\n', (21140, 21202), True, 'import numpy as np\n'), ((21872, 21912), 'matplotlib.figure.Figure', 'Figure', ([], {'figsize': '(width, height)', 'dpi': 'dpi'}), '(figsize=(width, height), dpi=dpi)\n', (21878, 21912), False, 'from matplotlib.figure import Figure\n'), ((21921, 21953), 'matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg.__init__', 'FigureCanvas.__init__', (['self', 'fig'], {}), '(self, fig)\n', (21942, 21953), True, 'from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\n'), ((26819, 26849), 'os.mkdir', 'os.mkdir', (["(self.d[1] + '\\\\temp')"], {}), "(self.d[1] + '\\\\temp')\n", (26827, 26849), False, 'import os\n'), ((27125, 27155), 'os.rmdir', 'os.rmdir', (["(self.d[1] + '\\\\temp')"], {}), "(self.d[1] + '\\\\temp')\n", (27133, 27155), False, 'import os\n'), ((27841, 27877), 'os.mkdir', 'os.mkdir', (["(self.d[4] + slash + 'temp')"], {}), "(self.d[4] + slash + 'temp')\n", (27849, 27877), False, 'import os\n'), ((28158, 28194), 'os.rmdir', 'os.rmdir', (["(self.d[4] + slash + 'temp')"], {}), "(self.d[4] + slash + 'temp')\n", (28166, 28194), False, 'import os\n'), ((3239, 3250), 'time.time', 'time.time', ([], {}), '()\n', (3248, 3250), False, 'import time\n'), ((3848, 3859), 'time.time', 'time.time', ([], {}), '()\n', (3857, 3859), False, 'import time\n'), ((4668, 4681), 'os.mkdir', 'os.mkdir', (['res'], {}), '(res)\n', (4676, 4681), False, 'import os\n'), ((4829, 4871), 'numpy.append', 'np.append', (['self.__matrix_time', '[a]'], {'axis': '(0)'}), '(self.__matrix_time, [a], axis=0)\n', (4838, 4871), True, 'import numpy as np\n'), ((4912, 4961), 'numpy.append', 'np.append', (['self.__matrix_is_complete', '[b]'], {'axis': '(0)'}), '(self.__matrix_is_complete, [b], axis=0)\n', (4921, 4961), True, 'import numpy as np\n'), ((6073, 6097), 'os.path.isdir', 'os.path.isdir', (['path_test'], {}), '(path_test)\n', (6086, 6097), False, 'import os\n'), ((6458, 6486), 'os.path.isdir', 'os.path.isdir', (['self.__output'], {}), '(self.__output)\n', (6471, 6486), False, 'import os\n'), ((6516, 6527), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (6525, 6527), False, 'import os\n'), ((6632, 6662), 'os.path.exists', 'os.path.exists', (['path_reference'], {}), '(path_reference)\n', (6646, 6662), False, 'import os\n'), ((6784, 6813), 'os.path.isdir', 'os.path.isdir', (['path_reference'], {}), '(path_reference)\n', (6797, 6813), False, 'import os\n'), ((8192, 8220), 'shutil.rmtree', 'shutil.rmtree', (['self.__output'], {}), '(self.__output)\n', (8205, 8220), False, 'import shutil\n'), ((8454, 8477), 'os.mkdir', 'os.mkdir', (['self.__output'], {}), '(self.__output)\n', (8462, 8477), False, 'import os\n'), ((1420, 1441), 'os.path.isfile', 'os.path.isfile', (['path1'], {}), '(path1)\n', (1434, 1441), False, 'import os\n'), ((1449, 1470), 'os.path.isfile', 'os.path.isfile', (['path1'], {}), '(path1)\n', (1463, 1470), False, 'import os\n'), ((3330, 3341), 'time.time', 'time.time', ([], {}), '()\n', (3339, 3341), False, 'import time\n'), ((3964, 3975), 'time.time', 'time.time', ([], {}), '()\n', (3973, 3975), False, 'import time\n'), ((4209, 4254), 'numpy.zeros', 'np.zeros', (['(self.params[1] + 1 - self.params[0])'], {}), '(self.params[1] + 1 - self.params[0])\n', (4217, 4254), True, 'import numpy as np\n'), ((5232, 5277), 'numpy.zeros', 'np.zeros', (['(self.params[1] + 1 - self.params[0])'], {}), '(self.params[1] + 1 - self.params[0])\n', (5240, 5277), True, 'import numpy as np\n'), ((6125, 6146), 'os.listdir', 'os.listdir', (['path_test'], {}), '(path_test)\n', (6135, 6146), False, 'import os\n'), ((6841, 6867), 'os.listdir', 'os.listdir', (['path_reference'], {}), '(path_reference)\n', (6851, 6867), False, 'import os\n'), ((8354, 8375), 'os.listdir', 'os.listdir', (['path_test'], {}), '(path_test)\n', (8364, 8375), False, 'import os\n'), ((8876, 8902), 'os.listdir', 'os.listdir', (['path_reference'], {}), '(path_reference)\n', (8886, 8902), False, 'import os\n'), ((21306, 21371), 'numpy.array', 'np.array', (['[current_test.time for current_test in data_list[test]]'], {}), '([current_test.time for current_test in data_list[test]])\n', (21314, 21371), True, 'import numpy as np\n'), ((22238, 22310), 'numpy.array', 'np.array', (['[current_test.param_value for current_test in data_list[test]]'], {}), '([current_test.param_value for current_test in data_list[test]])\n', (22246, 22310), True, 'import numpy as np\n'), ((22331, 22396), 'numpy.array', 'np.array', (['[current_test.time for current_test in data_list[test]]'], {}), '([current_test.time for current_test in data_list[test]])\n', (22339, 22396), True, 'import numpy as np\n'), ((1910, 1931), 'os.path.isfile', 'os.path.isfile', (['path1'], {}), '(path1)\n', (1924, 1931), False, 'import os\n'), ((1939, 1960), 'os.path.isfile', 'os.path.isfile', (['path1'], {}), '(path1)\n', (1953, 1960), False, 'import os\n'), ((2208, 2229), 'os.path.isfile', 'os.path.isfile', (['path1'], {}), '(path1)\n', (2222, 2229), False, 'import os\n'), ((2237, 2258), 'os.path.isfile', 'os.path.isfile', (['path1'], {}), '(path1)\n', (2251, 2258), False, 'import os\n'), ((3263, 3292), 'subprocess.check_output', 'subprocess.check_output', (['call'], {}), '(call)\n', (3286, 3292), False, 'import subprocess\n'), ((3872, 3926), 'subprocess.check_output', 'subprocess.check_output', (['[self.__program, param, test]'], {}), '([self.__program, param, test])\n', (3895, 3926), False, 'import subprocess\n'), ((6254, 6298), 'os.path.isdir', 'os.path.isdir', (['(path_test + slash + file_name)'], {}), '(path_test + slash + file_name)\n', (6267, 6298), False, 'import os\n'), ((6980, 7029), 'os.path.isdir', 'os.path.isdir', (['(path_reference + slash + file_name)'], {}), '(path_reference + slash + file_name)\n', (6993, 7029), False, 'import os\n'), ((2010, 2055), 'subprocess.check_output', 'subprocess.check_output', (['[path, path1, path2]'], {}), '([path, path1, path2])\n', (2033, 2055), False, 'import subprocess\n'), ((2308, 2363), 'subprocess.check_output', 'subprocess.check_output', (["['python', path, path1, path2]"], {}), "(['python', path, path1, path2])\n", (2331, 2363), False, 'import subprocess\n')]
|
"""
Preprocessing functions.
"""
import numpy as np
import scipy as sp
import nutsml.imageutil as ni
from nutsflow import *
from constants import C, H, W, H_TOP, H_BOTTOM
def flatten_layers(image, order=2, verbose=False):
"""
:param ndarray image: gray scale image.
:param int order: Order of polynom fitted [0..n].
:param bool verbose: True: return additional data,
False: return image with flattend layers
:return: Image with height h2 * 2 and flattened, centered layer
:rtype: ndarray of shape (h2*2, w)
"""
# build mask with bright pixels (layers)
threshold = np.mean(image) * 1.5
mask = (image > threshold).astype(int)
nrows, ncols = mask.shape
idxs = np.tile(np.array([range(nrows)]).transpose(), (1, ncols))
idxs = np.multiply(mask, idxs)
# get coordinates of vertical median of bright pixels
ys = np.apply_along_axis(lambda v: np.median(v[np.nonzero(v)]), 0, idxs)
ys[np.isnan(ys)] = 0
xs = np.array(range(ncols))
# fit polynom of degree order but ignore center (fovea, optic cup)
d = mask.shape[1] // 3 # ignore 1/3 image width center for polynom fit
rxs = np.hstack([xs[0:d], xs[ncols - d:ncols]])
rys = np.hstack([ys[0:d], ys[ncols - d:ncols]])
f = np.poly1d(np.polyfit(rxs, rys, order))
# copy image into vertically padded image
r,c = image.shape
padded = np.zeros((r*2,c))
offset = r//4
padded[offset:offset+r] = image
# extract flattened, vertically centered stripe from padded image
flat_img = []
ht, hb = int(r*H_TOP), int(r*H_BOTTOM)
for x in xs:
y = offset + int(f(x))
stripe = padded[y - ht:y + hb, x]
stripe = np.pad(stripe, (ht+hb-stripe.shape[0], 0), 'constant')
flat_img.append(stripe)
flat_img = np.transpose(np.vstack(flat_img))
flat_img = ni.resize(flat_img, c, r, order=1)
if verbose:
flat_img = ni.gray2rgb(flat_img)
fit_img = ni.gray2rgb(mask).astype('uint8') * 255
for x in range(fit_img.shape[1]):
y = int(f(x))
fit_img[y-2:y+2, x] = (255, 100, 0)
return (flat_img, fit_img) if verbose else flat_img
def flatten_cube(cube, order):
return np.stack(flatten_layers(bscan, order) for bscan in cube)
def resize_cube(cube, shape):
"""Return resized cube with the define shape"""
zoom = [float(x) / y for x, y in zip(shape, cube.shape)]
resized = sp.ndimage.zoom(cube, zoom)
assert resized.shape == shape
return resized
|
[
"numpy.pad",
"nutsml.imageutil.gray2rgb",
"numpy.multiply",
"numpy.polyfit",
"numpy.zeros",
"nutsml.imageutil.resize",
"scipy.ndimage.zoom",
"numpy.hstack",
"numpy.isnan",
"numpy.nonzero",
"numpy.mean",
"numpy.vstack"
] |
[((802, 825), 'numpy.multiply', 'np.multiply', (['mask', 'idxs'], {}), '(mask, idxs)\n', (813, 825), True, 'import numpy as np\n'), ((1177, 1218), 'numpy.hstack', 'np.hstack', (['[xs[0:d], xs[ncols - d:ncols]]'], {}), '([xs[0:d], xs[ncols - d:ncols]])\n', (1186, 1218), True, 'import numpy as np\n'), ((1229, 1270), 'numpy.hstack', 'np.hstack', (['[ys[0:d], ys[ncols - d:ncols]]'], {}), '([ys[0:d], ys[ncols - d:ncols]])\n', (1238, 1270), True, 'import numpy as np\n'), ((1400, 1420), 'numpy.zeros', 'np.zeros', (['(r * 2, c)'], {}), '((r * 2, c))\n', (1408, 1420), True, 'import numpy as np\n'), ((1862, 1896), 'nutsml.imageutil.resize', 'ni.resize', (['flat_img', 'c', 'r'], {'order': '(1)'}), '(flat_img, c, r, order=1)\n', (1871, 1896), True, 'import nutsml.imageutil as ni\n'), ((2450, 2477), 'scipy.ndimage.zoom', 'sp.ndimage.zoom', (['cube', 'zoom'], {}), '(cube, zoom)\n', (2465, 2477), True, 'import scipy as sp\n'), ((628, 642), 'numpy.mean', 'np.mean', (['image'], {}), '(image)\n', (635, 642), True, 'import numpy as np\n'), ((969, 981), 'numpy.isnan', 'np.isnan', (['ys'], {}), '(ys)\n', (977, 981), True, 'import numpy as np\n'), ((1289, 1316), 'numpy.polyfit', 'np.polyfit', (['rxs', 'rys', 'order'], {}), '(rxs, rys, order)\n', (1299, 1316), True, 'import numpy as np\n'), ((1711, 1769), 'numpy.pad', 'np.pad', (['stripe', '(ht + hb - stripe.shape[0], 0)', '"""constant"""'], {}), "(stripe, (ht + hb - stripe.shape[0], 0), 'constant')\n", (1717, 1769), True, 'import numpy as np\n'), ((1826, 1845), 'numpy.vstack', 'np.vstack', (['flat_img'], {}), '(flat_img)\n', (1835, 1845), True, 'import numpy as np\n'), ((1933, 1954), 'nutsml.imageutil.gray2rgb', 'ni.gray2rgb', (['flat_img'], {}), '(flat_img)\n', (1944, 1954), True, 'import nutsml.imageutil as ni\n'), ((936, 949), 'numpy.nonzero', 'np.nonzero', (['v'], {}), '(v)\n', (946, 949), True, 'import numpy as np\n'), ((1973, 1990), 'nutsml.imageutil.gray2rgb', 'ni.gray2rgb', (['mask'], {}), '(mask)\n', (1984, 1990), True, 'import nutsml.imageutil as ni\n')]
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import cv2
import numpy as np
# 找图 返回最近似的点
def search_img(img, template, threshold=0.9, debug=False, gray=0):
"""
在大图中找小图
:param img: 大图
:param template: 小图
:param threshold: 相似度 1为完美 -1为最差
:param debug: 是否显示图片匹配情况,True会框选出匹配项
:param gray: 是否灰度匹配
:return:
"""
if gray == 0:
color_mode = cv2.IMREAD_COLOR
else:
color_mode = cv2.COLOR_BGR2GRAY
img = cv2.cvtColor(img, color_mode)
template = cv2.cvtColor(template, color_mode)
result = cv2.matchTemplate(img, template, cv2.TM_CCOEFF_NORMED)
# res大于70%
loc = np.where(result >= threshold)
# 使用灰度图像中的坐标对原始RGB图像进行标记
point = ()
for pt in zip(*loc[::-1]):
template_size = template.shape[:2]
cv2.rectangle(img, pt, (pt[0] + template_size[1], pt[1] + + template_size[0]), (7, 249, 151), 2)
point = pt
if point == ():
return None
if debug:
cv2.circle(img, (int(point[0]), int(point[1])), 3, (0, 0, 255), 0)
cv2.imshow("image", img)
cv2.waitKey(0)
return point[0], point[1]
if __name__ == '__main__':
scale = 1
test_img = cv2.imread('../images/liaoyan/test.png') # 要找的大图
# img = cv2.resize(img, (0, 0), fx=scale, fy=scale)
test_template = cv2.imread('../images/liaoyan/num3.png') # 图中的小图
# template = cv2.resize(template, (0, 0), fx=scale, fy=scale)
point_color = (0, 0, 255)
x, y = search_img(test_img, test_template, threshold=0.9, debug=True)
cv2.circle(test_img, (int(x), int(y)), 3, point_color, 0)
# cv2.imshow("image", img)
# cv2.waitKey(0)
if test_img is None:
print("没找到图片")
else:
print("找到图片 位置:" + str(x) + " " + str(y))
|
[
"cv2.cvtColor",
"cv2.waitKey",
"cv2.imread",
"numpy.where",
"cv2.rectangle",
"cv2.imshow",
"cv2.matchTemplate"
] |
[((464, 493), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'color_mode'], {}), '(img, color_mode)\n', (476, 493), False, 'import cv2\n'), ((509, 543), 'cv2.cvtColor', 'cv2.cvtColor', (['template', 'color_mode'], {}), '(template, color_mode)\n', (521, 543), False, 'import cv2\n'), ((557, 611), 'cv2.matchTemplate', 'cv2.matchTemplate', (['img', 'template', 'cv2.TM_CCOEFF_NORMED'], {}), '(img, template, cv2.TM_CCOEFF_NORMED)\n', (574, 611), False, 'import cv2\n'), ((638, 667), 'numpy.where', 'np.where', (['(result >= threshold)'], {}), '(result >= threshold)\n', (646, 667), True, 'import numpy as np\n'), ((1184, 1224), 'cv2.imread', 'cv2.imread', (['"""../images/liaoyan/test.png"""'], {}), "('../images/liaoyan/test.png')\n", (1194, 1224), False, 'import cv2\n'), ((1311, 1351), 'cv2.imread', 'cv2.imread', (['"""../images/liaoyan/num3.png"""'], {}), "('../images/liaoyan/num3.png')\n", (1321, 1351), False, 'import cv2\n'), ((794, 894), 'cv2.rectangle', 'cv2.rectangle', (['img', 'pt', '(pt[0] + template_size[1], pt[1] + +template_size[0])', '(7, 249, 151)', '(2)'], {}), '(img, pt, (pt[0] + template_size[1], pt[1] + +template_size[0]\n ), (7, 249, 151), 2)\n', (807, 894), False, 'import cv2\n'), ((1047, 1071), 'cv2.imshow', 'cv2.imshow', (['"""image"""', 'img'], {}), "('image', img)\n", (1057, 1071), False, 'import cv2\n'), ((1080, 1094), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (1091, 1094), False, 'import cv2\n')]
|
import numpy as np
def get_sonic_specific_actions():
buttons = ["B", "A", "MODE", "START", "UP", "DOWN", "LEFT", "RIGHT", "C", "Y", "X", "Z"]
actions = [['LEFT'], ['RIGHT'], ['LEFT', 'DOWN'], ['RIGHT', 'DOWN'], ['DOWN'],
['DOWN', 'B'], ['B'], [], ['LEFT', 'B'], ['RIGHT', 'B']]
_actions = []
for action in actions:
arr = np.array([False] * 12)
for button in action:
arr[buttons.index(button)] = True
_actions.append(arr)
return _actions
|
[
"numpy.array"
] |
[((362, 384), 'numpy.array', 'np.array', (['([False] * 12)'], {}), '([False] * 12)\n', (370, 384), True, 'import numpy as np\n')]
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
showcase paths
==============
This example shows how OMAS supports dynamic path crection using different syntaxes.
.. figure:: ../images/dynamic_path_testimonial.png
:align: center
:width: 100%
:alt: What people say about OMAS dynamic path creation
:target: ../_images/dynamic_path_testimonial.png
"""
import numpy
from omas import *
ods = ODS()
# without dynamic path creation one must use Python approach to create nested dictionaries
# this can be extremely tedious!
with omas_environment(ods, dynamic_path_creation=False):
ods['equilibrium'] = ODS()
ods['equilibrium']['time_slice'] = ODS()
ods['equilibrium']['time_slice'][0] = ODS()
ods['equilibrium']['time_slice'][0]['time'] = 1000
assert ods['equilibrium']['time_slice'][0]['time'] == 1000.0
# Dynamic path creation (True by default) makes life easier.
# NOTE: OMAS supports different data access syntaxes
with omas_environment(ods, dynamic_path_creation=True):
# access data as dictionary
ods['equilibrium']['time_slice'][0]['time'] = 1000.0
assert ods['equilibrium']['time_slice'][0]['time'] == 1000.0
# access data as string
ods['equilibrium.time_slice.1.time'] = 2000.0
assert ods['equilibrium.time_slice.1.time'] == 2000.0
# access data as string (square brackets for arrays of structures)
ods['equilibrium.time_slice[2].time'] = 3000.0
assert ods['equilibrium.time_slice[2].time'] == 3000.0
# access data with path list
ods[['equilibrium', 'time_slice', 3, 'time']] = 4000.0
assert ods[['equilibrium', 'time_slice', 3, 'time']] == 4000.0
# access data with mix and match approach
ods['equilibrium']['time_slice.4.time'] = 5000.0
assert ods['equilibrium']['time_slice.4.time'] == 5000.0
# =============
# Data slicing
# =============
# classic ways to access data across an array of structures
data = []
for k in ods['equilibrium.time_slice'].keys():
data.append(ods['equilibrium.time_slice'][k]['time'])
data = numpy.array(data)
assert numpy.all(data == numpy.array([1000.0, 2000.0, 3000.0, 4000.0, 5000.0]))
# access data across an array of structures via data slicing
data = ods['equilibrium.time_slice.:.time']
assert numpy.all(data == numpy.array([1000.0, 2000.0, 3000.0, 4000.0, 5000.0]))
# =========================
# .setdefault() and .get()
# =========================
# like for Python dictionaries .setdefault() will set an entry with its
# default value (second argument) only if that entry does not exists already
ods = ODS()
ods['equilibrium.time_slice.0.global_quantities.ip'] = 6
ods.setdefault('equilibrium.time_slice.0.global_quantities.ip', 5)
assert ods['equilibrium.time_slice.0.global_quantities.ip'] == 6
ods = ODS()
ods.setdefault('equilibrium.time_slice.0.global_quantities.ip', 5)
assert ods['equilibrium.time_slice.0.global_quantities.ip'] == 5
# like for Python dictionaries .get() return the value of an entry or its
# default value (second argument) if that does not exists
ods = ODS()
ods.get('equilibrium.time_slice.0.global_quantities.ip', 5)
assert 'equilibrium.time_slice.0.global_quantities.ip' not in ods
# ========
# Cleanup
# ========
# Dynamic path creation can leave empty trees behind in case of bad IMAS location is entered.
# This is inevitable when splitting the path in individual pieces.
# These leftover are often innocuous, and occur only during the development stages.
# Use of .prune() to clean empty branches left behind from dynamic path creation
ods = ODS()
try:
ods['equilibrium']['time_slice'][0]['global_quantities']['not_valid'] = 6
except LookupError:
n = ods.prune()
assert n == 4
assert len(ods) == 0
# Note that single string access does not leave empty branches
ods = ODS()
try:
ods['equilibrium.time_slice.0.global_quantities.asdasd'] = 6
except LookupError:
assert len(ods) == 0
|
[
"numpy.array"
] |
[((2030, 2047), 'numpy.array', 'numpy.array', (['data'], {}), '(data)\n', (2041, 2047), False, 'import numpy\n'), ((2073, 2126), 'numpy.array', 'numpy.array', (['[1000.0, 2000.0, 3000.0, 4000.0, 5000.0]'], {}), '([1000.0, 2000.0, 3000.0, 4000.0, 5000.0])\n', (2084, 2126), False, 'import numpy\n'), ((2259, 2312), 'numpy.array', 'numpy.array', (['[1000.0, 2000.0, 3000.0, 4000.0, 5000.0]'], {}), '([1000.0, 2000.0, 3000.0, 4000.0, 5000.0])\n', (2270, 2312), False, 'import numpy\n')]
|
import random
import numpy as np
from PIL import Image
_plan_square = np.array([[0, 0], [1, 0], [0, 1], [1, 1]], dtype=np.float64)
_middle_point_coordinates = np.array([0.5, 0.5], dtype=np.float64)
def compute_perspective_params(plan_1, plan_2, width_, height_):
"""
Given the coordinates of the four corners of the first quadrilateral
and the coordinates of the four corners of the second quadrilateral,
compute the perspective transform that maps a new point in the first
quadrilateral onto the appropriate position on the second quadrilateral.
https://web.archive.org/web/20150222120106/xenia.media.mit.edu/~cwren/interpolator/
plan_1, plan_2:
list of 4 tuples, each tuple contains two float
plan_src is the first quadrilateral
plan_target is the second quadrilateral
p1, p2:
tuple of two float (corner coordinates normalized to [0, 1] range)
p1 corresponds to coordinates in the source plan (x, y)
p2 corresponds to coordinates in the target plan (X, Y)
"""
A = []
plan_1 = np.array(plan_1, copy=True)
plan_2 = np.array(plan_2, copy=True)
plan_1[:, 0] = plan_1[:, 0] * width_
plan_1[:, 1] = plan_1[:, 1] * height_
plan_2[:, 0] = plan_2[:, 0] * width_
plan_2[:, 1] = plan_2[:, 1] * height_
for p1, p2 in zip(plan_1, plan_2):
A.append([p1[0], p1[1], 1, 0, 0, 0, - p2[0] * p1[0], - p2[0] * p1[1]])
A.append([0, 0, 0, p1[0], p1[1], 1, - p2[1] * p1[0], - p2[1] * p1[1]])
A = np.array(A, dtype=np.float)
b = np.array(plan_2).reshape(8)
try:
res = np.linalg.inv(A.T.dot(A)).dot(A.T).dot(b)
except:
res = np.linalg.pinv(A.T.dot(A)).dot(A.T).dot(b)
return np.array(res).reshape(8)
def is_convex_quadrilateral(quadrilateral):
len_ = len(quadrilateral)
indices = [[1, 0, 2], [0, 2, 3], [2, 3, 1], [3, 1, 0]]
for idx_1, idx_2, idx_3 in indices:
edge_1 = quadrilateral[idx_2] - quadrilateral[idx_1]
edge_2 = quadrilateral[idx_3] - quadrilateral[idx_2]
# 2D cross product
if edge_1[0] * edge_2[1] - edge_2[0] * edge_1[1] >= 0:
return False
return True
def random_quadrilateral(gaussian_std=0.05, max_nb_trials=5):
for _ in range(max_nb_trials):
random_2d_points = []
for i in range(8):
random_2d_points.append(random.gauss(0, gaussian_std))
random_2d_points = np.array(random_2d_points).reshape((4, 2))
# top right corner
random_2d_points[1, 0] *= - 1
# bottom left corner
random_2d_points[2, 1] *= - 1
# bottom right corner
random_2d_points[3, 0] *= - 1
random_2d_points[3, 1] *= - 1
quadrilateral = random_2d_points + _plan_square
if is_convex_quadrilateral(quadrilateral):
return quadrilateral
return _plan_square
def transform(img, mask, quadrilateral=None, gaussian_std=0.05,
return_perspective_params=False):
"""
img.mode must be "RGB"
mask.mode must be "L"
quadrilateral and gaussian_std cannot be both None.
If both are provided, gaussian_std will be used,
which means that random quadrilateral will be generated.
"""
if quadrilateral is not None:
assert is_convex_quadrilateral(quadrilateral), \
"Corner points do not constitute a convex quadrilateral."
if gaussian_std is not None:
quadrilateral = random_quadrilateral(gaussian_std=gaussian_std)
perspective_params = compute_perspective_params(quadrilateral, _plan_square,
img.size[0], img.size[1])
img = img.transform(img.size, Image.PERSPECTIVE,
perspective_params, Image.BICUBIC, fillcolor=(255, 255, 255))
mask = mask.transform(mask.size, Image.PERSPECTIVE,
perspective_params, Image.BICUBIC, fillcolor=0)
if not return_perspective_params:
return img, mask
else:
return img, mask, perspective_params
|
[
"random.gauss",
"numpy.array"
] |
[((74, 134), 'numpy.array', 'np.array', (['[[0, 0], [1, 0], [0, 1], [1, 1]]'], {'dtype': 'np.float64'}), '([[0, 0], [1, 0], [0, 1], [1, 1]], dtype=np.float64)\n', (82, 134), True, 'import numpy as np\n'), ((163, 201), 'numpy.array', 'np.array', (['[0.5, 0.5]'], {'dtype': 'np.float64'}), '([0.5, 0.5], dtype=np.float64)\n', (171, 201), True, 'import numpy as np\n'), ((1092, 1119), 'numpy.array', 'np.array', (['plan_1'], {'copy': '(True)'}), '(plan_1, copy=True)\n', (1100, 1119), True, 'import numpy as np\n'), ((1133, 1160), 'numpy.array', 'np.array', (['plan_2'], {'copy': '(True)'}), '(plan_2, copy=True)\n', (1141, 1160), True, 'import numpy as np\n'), ((1537, 1564), 'numpy.array', 'np.array', (['A'], {'dtype': 'np.float'}), '(A, dtype=np.float)\n', (1545, 1564), True, 'import numpy as np\n'), ((1573, 1589), 'numpy.array', 'np.array', (['plan_2'], {}), '(plan_2)\n', (1581, 1589), True, 'import numpy as np\n'), ((1746, 1759), 'numpy.array', 'np.array', (['res'], {}), '(res)\n', (1754, 1759), True, 'import numpy as np\n'), ((2403, 2432), 'random.gauss', 'random.gauss', (['(0)', 'gaussian_std'], {}), '(0, gaussian_std)\n', (2415, 2432), False, 'import random\n'), ((2461, 2487), 'numpy.array', 'np.array', (['random_2d_points'], {}), '(random_2d_points)\n', (2469, 2487), True, 'import numpy as np\n')]
|
import numpy as np
import imageio
import argparse
import glob
import os
np.seterr(invalid='ignore')
def make_grayscale(depth: np.ndarray) -> np.ndarray:
"""Get depth for grayscale images."""
depth_not_nan = depth[np.logical_not(np.isnan(depth))]
min_v = np.min(depth_not_nan)
max_v = np.max(depth_not_nan)
r = (255 * (depth - min_v) / (max_v - min_v))
# normalize r
r[np.isnan(r)] = 255
return r.astype(np.uint8)
def gaussian(x, mu, sig):
"""Simple gaussian function."""
return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.))) / np.sqrt(2 * np.pi)
def normalize(in_mat: np.ndarray) -> np.ndarray:
"""Simple normalize function."""
in_mat = in_mat - np.min(in_mat[np.logical_not(np.isnan(in_mat))])
return in_mat / np.max(in_mat[np.logical_not(np.isnan(in_mat))])
def colorize(depth: np.ndarray) -> np.ndarray:
"""Colorize the picture."""
depth = normalize(depth)
r = gaussian(depth, 0, 0.2) * 255
g = gaussian(depth, 0.4, 0.2) * 255
b = gaussian(depth, 0.6, 0.2) * 255
rgb = np.stack([r, g, b], 2)
rgb[np.isnan(rgb)] = 255
return rgb.astype(np.uint8)
def compute_depth(cloud: np.ndarray, pose: np.ndarray) -> np.ndarray:
"""Compute Euclidean depth."""
xyz = pose[0:3]
depth = np.sqrt(np.sum(np.square(cloud - xyz), 2))
depth[cloud[:, :, 0] < 0] = np.nan
return depth
def compute_depth_images(pc_names: list, poses: np.ndarray, path: str, colorized=False):
"""Get depth images and save to disk."""
for j, pc_name in enumerate(pc_names):
cloud = np.load(os.path.join(path, pc_name))
depth = compute_depth(cloud, poses[j])
if colorized == 'c':
depth = colorize(depth)
imageio.imwrite(os.path.join(path, pc_name[:-4] + '_depth_color.png'), depth)
elif colorized == 'g':
depth = make_grayscale(depth)
imageio.imwrite(os.path.join(path, pc_name[:-4] + '_depth_grayscale.png'), depth)
else:
np.save(os.path.join(path, pc_name[:-4] + '_depth.npy'), depth)
def main():
parser = argparse.ArgumentParser()
parser.add_argument("path", type=str, help="Path of the dataset for which to generate depth images")
parser.add_argument("-min", type=int, help="Min index")
parser.add_argument("-max", type=int, help="Max index")
parser.add_argument("-i", type=int, nargs='+', help="List indexes (separated by ' ')")
parser.add_argument("-c", action="store_true", default=False,
help="Use this to get a colorized png depth visualisation instead of depth tif")
parser.add_argument("-g", action="store_true", default=False,
help="Use this to get a grayscale png depth visualisation instead of depth tif")
args = parser.parse_args()
color = 'c' if args.c else 'g' if args.g else False
path = os.path.abspath(args.path)
name = os.path.basename(os.path.abspath(path))
if '_saved' in name:
name = name[:name.find('_saved')]
poses = np.load(glob.glob(path + '/*poses.npy')[0])
min_ = args.min if args.min else 0
max_ = args.max if args.max else len(poses) - 1
indexes = np.array(args.i) if args.i else np.arange(min_, max_ + 1)
poses = poses[indexes, :]
pc = []
for j, ind in enumerate(indexes):
try:
pc.append(os.path.basename(glob.glob('{0}/{1}_{2:05d}_*pc.npy'.format(path, name, ind))[0]))
except Exception:
poses[j, 0] = np.nan
poses = poses[np.logical_not(np.isnan(poses[:, 0])), :]
compute_depth_images(pc, poses, path, color)
if __name__ == "__main__":
main()
|
[
"numpy.stack",
"os.path.abspath",
"argparse.ArgumentParser",
"numpy.seterr",
"numpy.power",
"numpy.square",
"numpy.isnan",
"numpy.min",
"numpy.max",
"numpy.array",
"numpy.arange",
"glob.glob",
"os.path.join",
"numpy.sqrt"
] |
[((73, 100), 'numpy.seterr', 'np.seterr', ([], {'invalid': '"""ignore"""'}), "(invalid='ignore')\n", (82, 100), True, 'import numpy as np\n'), ((269, 290), 'numpy.min', 'np.min', (['depth_not_nan'], {}), '(depth_not_nan)\n', (275, 290), True, 'import numpy as np\n'), ((303, 324), 'numpy.max', 'np.max', (['depth_not_nan'], {}), '(depth_not_nan)\n', (309, 324), True, 'import numpy as np\n'), ((1066, 1088), 'numpy.stack', 'np.stack', (['[r, g, b]', '(2)'], {}), '([r, g, b], 2)\n', (1074, 1088), True, 'import numpy as np\n'), ((2106, 2131), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (2129, 2131), False, 'import argparse\n'), ((2890, 2916), 'os.path.abspath', 'os.path.abspath', (['args.path'], {}), '(args.path)\n', (2905, 2916), False, 'import os\n'), ((399, 410), 'numpy.isnan', 'np.isnan', (['r'], {}), '(r)\n', (407, 410), True, 'import numpy as np\n'), ((581, 599), 'numpy.sqrt', 'np.sqrt', (['(2 * np.pi)'], {}), '(2 * np.pi)\n', (588, 599), True, 'import numpy as np\n'), ((1097, 1110), 'numpy.isnan', 'np.isnan', (['rgb'], {}), '(rgb)\n', (1105, 1110), True, 'import numpy as np\n'), ((2945, 2966), 'os.path.abspath', 'os.path.abspath', (['path'], {}), '(path)\n', (2960, 2966), False, 'import os\n'), ((3196, 3212), 'numpy.array', 'np.array', (['args.i'], {}), '(args.i)\n', (3204, 3212), True, 'import numpy as np\n'), ((3228, 3253), 'numpy.arange', 'np.arange', (['min_', '(max_ + 1)'], {}), '(min_, max_ + 1)\n', (3237, 3253), True, 'import numpy as np\n'), ((239, 254), 'numpy.isnan', 'np.isnan', (['depth'], {}), '(depth)\n', (247, 254), True, 'import numpy as np\n'), ((1304, 1326), 'numpy.square', 'np.square', (['(cloud - xyz)'], {}), '(cloud - xyz)\n', (1313, 1326), True, 'import numpy as np\n'), ((1591, 1618), 'os.path.join', 'os.path.join', (['path', 'pc_name'], {}), '(path, pc_name)\n', (1603, 1618), False, 'import os\n'), ((3055, 3086), 'glob.glob', 'glob.glob', (["(path + '/*poses.npy')"], {}), "(path + '/*poses.npy')\n", (3064, 3086), False, 'import glob\n'), ((1760, 1813), 'os.path.join', 'os.path.join', (['path', "(pc_name[:-4] + '_depth_color.png')"], {}), "(path, pc_name[:-4] + '_depth_color.png')\n", (1772, 1813), False, 'import os\n'), ((3544, 3565), 'numpy.isnan', 'np.isnan', (['poses[:, 0]'], {}), '(poses[:, 0])\n', (3552, 3565), True, 'import numpy as np\n'), ((531, 552), 'numpy.power', 'np.power', (['(x - mu)', '(2.0)'], {}), '(x - mu, 2.0)\n', (539, 552), True, 'import numpy as np\n'), ((559, 577), 'numpy.power', 'np.power', (['sig', '(2.0)'], {}), '(sig, 2.0)\n', (567, 577), True, 'import numpy as np\n'), ((739, 755), 'numpy.isnan', 'np.isnan', (['in_mat'], {}), '(in_mat)\n', (747, 755), True, 'import numpy as np\n'), ((808, 824), 'numpy.isnan', 'np.isnan', (['in_mat'], {}), '(in_mat)\n', (816, 824), True, 'import numpy as np\n'), ((1923, 1980), 'os.path.join', 'os.path.join', (['path', "(pc_name[:-4] + '_depth_grayscale.png')"], {}), "(path, pc_name[:-4] + '_depth_grayscale.png')\n", (1935, 1980), False, 'import os\n'), ((2023, 2070), 'os.path.join', 'os.path.join', (['path', "(pc_name[:-4] + '_depth.npy')"], {}), "(path, pc_name[:-4] + '_depth.npy')\n", (2035, 2070), False, 'import os\n')]
|
import re
import numpy as np
from kabuki import kabuki_mask
# We want to use the output
# of kabuki kidpix to initialize
# a Game of Life grid.
#
# Here is the format that Life expects:
#
# initialState : '[{"39":[60]},{"40":[62]},{"41":[59,60,63,64,65]}]',
#
# '[
# { "<row-id>" : [<col-id>, <col-id>, <col-id>],
# "<row-id>" : [<col-id>, <col-id>],
# "<row-id>" : [<col-id>, <col-id>, <col-id>, <col-id>]
# }
# ]'
#
# . * . . . . . .
# . . . * . . . .
# * * . . * * * .
# . . . . . . . .
def cocacola():
print("-"*40)
print("coca cola logo:")
kabuki_js("img/cocacola.png", padding_top=20, brightness_threshold=50, final_size=(100,100))
def github():
print("-"*40)
print("github logo:")
kabuki_js("img/ghlogo.jpg", padding_top=5, final_size=(80,80))
def obama():
print("-"*40)
print("obama signature:")
kabuki_js("img/obama.png", padding_top=10, padding_left=3, brightness_threshold=120, final_size=(110,110), invert=True)
def kabuki_js(img_filename, **kwargs):
if('final_size' not in kwargs.keys()):
kwargs['final_size'] = (100,100)
if('brightness_threshold' not in kwargs.keys()):
kwargs['brightness_threshold'] = 150
if('padding_left' not in kwargs.keys()):
kwargs['padding_left'] = 0
if('padding_top' not in kwargs.keys()):
kwargs['padding_top'] = 0
if('invert' not in kwargs.keys()):
kwargs['invert'] = False
mask = kabuki_mask(img_filename,kwargs['final_size'],kwargs['brightness_threshold'],kwargs['invert'])
arr = np.array(mask)
# We are constructing a list of dictionaries
# One key per dictionary, one row per dictionary
# Each row of the image is one key of the dictionary
initdicts = []
for row in range(np.shape(arr)[0]):
columns_in_this_row = []
# Check each column in this row
# to see if it is bright (switched on)
for col in range(np.shape(arr)[1]):
px = arr[row][col]
if(px>kwargs['brightness_threshold']):
columns_in_this_row.append(col + kwargs['padding_left'])
# Assemble the dictionary
if(len(columns_in_this_row)>0):
d = {}
d[str(row + kwargs['padding_top'])] = columns_in_this_row
initdicts.append(d)
result_badquotes = ",".join([str(d) for d in initdicts])
result_goodquotes = re.sub("'","\"",result_badquotes)
print()
print("Here is your final string:")
print()
print("GOL.initialState = '[%s]';"%(result_goodquotes) )
if __name__=="__main__":
cocacola()
github()
obama()
|
[
"numpy.shape",
"kabuki.kabuki_mask",
"numpy.array",
"re.sub"
] |
[((1463, 1565), 'kabuki.kabuki_mask', 'kabuki_mask', (['img_filename', "kwargs['final_size']", "kwargs['brightness_threshold']", "kwargs['invert']"], {}), "(img_filename, kwargs['final_size'], kwargs[\n 'brightness_threshold'], kwargs['invert'])\n", (1474, 1565), False, 'from kabuki import kabuki_mask\n'), ((1568, 1582), 'numpy.array', 'np.array', (['mask'], {}), '(mask)\n', (1576, 1582), True, 'import numpy as np\n'), ((2407, 2441), 're.sub', 're.sub', (['"""\'"""', '"""\\""""', 'result_badquotes'], {}), '("\'", \'"\', result_badquotes)\n', (2413, 2441), False, 'import re\n'), ((1783, 1796), 'numpy.shape', 'np.shape', (['arr'], {}), '(arr)\n', (1791, 1796), True, 'import numpy as np\n'), ((1950, 1963), 'numpy.shape', 'np.shape', (['arr'], {}), '(arr)\n', (1958, 1963), True, 'import numpy as np\n')]
|
#!/usr/bin/env python
r"""
The following parameters come from:
[1] <NAME>., <NAME>., <NAME>. & <NAME>.
Collisionless Isotropization of the Solar-Wind Protons By Compressive
Fluctuations and Plasma Instabilities. Astrophys. J. 831, 128 (2016).
for which the Bibtex entry is:
@article{Verscharen2016a,
author = {<NAME>. and <NAME>. and <NAME>.
and <NAME>},
doi = {10.3847/0004-637X/831/2/128},
issn = {1538-4357},
journal = {Astrophys. J.},
keywords = {accretion,accretion disks,accretion, accretion
disks,animation,instabilities,plasmas,solar wind,supporting
material,turbulence,waves},
number = {2},
pages = {128},
publisher = {IOP Publishing},
title = {{Collisionless Isotropization of the Solar-Wind Protons By
Compressive Fluctuations and Plasma Instabilities}},
url = {http://stacks.iop.org/0004-637X/831/i=2/a=128?key=crossref.765015074c72580bac87603b196556a0},
volume = {831},
year = {2016}
}
"""
import pdb # noqa: F401
import logging
import numpy as np
import pandas as pd
import matplotlib as mpl
from collections import namedtuple
from matplotlib import pyplot as plt
_inst_type_idx = pd.Index(["AIC", "FMW", "MM", "OFI"], name="Intability")
_param_idx = pd.Index(["a", "b", "c"], name="Fit Parameter")
_inst_type_idx = pd.Index(["AIC", "FMW", "MM", "OFI"], name="Intability")
_param_idx = pd.Index(["a", "b", "c"], name="Fit Parameter")
insta_params = pd.concat(
{
-4: pd.DataFrame(
[
[0.367, 0.364, 0.011],
[-0.408, 0.529, 0.41],
[0.702, 0.674, -0.009],
[-1.454, 1.023, -0.178],
],
index=_inst_type_idx,
columns=_param_idx,
),
-3: pd.DataFrame(
[
[0.437, 0.428, -0.003],
[-0.497, 0.566, 0.543],
[0.801, 0.763, -0.063],
[-1.39, 1.005, -0.111],
],
index=_inst_type_idx,
columns=_param_idx,
),
-2: pd.DataFrame(
[
[0.649, 0.4, 0.0],
[-0.647, 0.583, 0.713],
[1.04, 0.633, -0.012],
[-1.447, 1.0, -0.148],
],
index=_inst_type_idx,
columns=_param_idx,
),
},
axis=1,
names=["Growth Rate"],
).stack("Growth Rate")
_plot_contour_kwargs = pd.DataFrame(
[
["#ffcb05", "--", "X"],
["#00B2A9", "--", "d"],
["#00274c", "--", "o"],
["#D86018", "--", "P"],
["#ffcb05", ":", "X"],
["#00B2A9", ":", "d"],
["#00274c", ":", "o"],
["#D86018", ":", "P"],
["#ffcb05", "-.", "X"],
["#00B2A9", "-.", "d"],
["#00274c", "-.", "o"],
["#D86018", "-.", "P"],
],
index=pd.MultiIndex.from_tuples(
[
(-4, "AIC"),
(-4, "FMW"),
(-4, "MM"),
(-4, "OFI"),
(-3, "AIC"),
(-3, "FMW"),
(-3, "MM"),
(-3, "OFI"),
(-2, "AIC"),
(-2, "FMW"),
(-2, "MM"),
(-2, "OFI"),
],
names=["Growth Rate", "Instability"],
),
columns=["color", "linestyle", "marker"],
)
_instability_tests = namedtuple("InstabilityTests", "AIC,MM,FMW,OFI")(
np.greater, np.greater, np.less, np.less
)
def beta_ani_inst(beta, a=None, b=None, c=None):
r"""Constant growth rate isocontours from Eq. (5) in [1].
$R_p = 1 + \frac{a}{(\beta_{\parallel,p} - c)^b}$
where $p$ is defined assuming only a single proton population is fit.
`a`, `b`, and `c` are kwargs so that **kwarg expansion works.
"""
# Effectively, type checking.
a = float(a)
b = float(b)
c = float(c)
return 1 + (a / ((beta - c) ** b))
class StabilityCondition(object):
r"""
Determines the stability condition of a plasma based on it"s location in
the (beta, anisotropy) plane.
Call signature
--------------
StabilityCondition(growth_rate, beta, anisotropy, fill=-9999)
Methods
-------
set_instability_parameters:
Take the instability parameters corresponding to the passed growth rate.
set_beta_ani:
Set the be set_fill :
Set the fill value.ta and anistropy values.
_calc_instability_thresholds:
Calculate the instability thresholds. This is a private method that
should not be called. See `calculate_stability_criteria`.
_calc_is_unstable:
Determine if a measurement is unstable to each instability. This is a
private method that should not be called. See
`calculate_stability_criteria`.
_calc_stability_bin:
Identify which instability (if any) each measurement is unstale to.
This is a private method that should not be called. See
`calculate_stability_criteria`.
calculate_stability_criteria:
Run `_calc_instability_thresholds`, `_calc_is_unstable`, and
`_calc_stability_bin` in that order. Use this method over the others
individually.
Properties
----------
instability_parameters:
The Pandas DataFrame of instability parameters.
beta:
The beta values of the object.
anisotropy:
The anisotropy values of the object.
stability_map: dict
The map of ints to strings identifying the instabilities.
stability_map_inverse: dict
The inverse of `stability_map`.
instability_tests: dict
The tests used for each instability threshold. The keys are "AIC", "MM",
"FMW", and "OFI" for Alfven/Ion-Cyclotron, Mirror Mode, Fast
Magnetosonic / Whistler, and Oblique Firehose. The values are numpy
ufuncs.
instability_thresholds: pd.DataFrame
The value of the anisotropy for which the plasma goes unstable.
is_unstable: pd.DataFrame
Boolean DataFrame indicating if a measurement is unstable to a given
instability.
stability_bin: pd.Series
The integer corresponding to the (in)stability condition of the
measurement. The string identifying the instability is given by the
`stability_map`.
norm: mpl.colors.Normalize(min(stability_map), max(stability_map))
The normalization instance used for plotting the stability bin.
cmap: matplotlib colormap
A linearly segmented to have one level for each (in)stability condition.
"""
def __init__(self, growth_rate, beta, anisotropy):
r"""
growth_rate: int
Should correspond the the growth rate minor_axis index of the
`insta_params` Pandas.Panel in the containing module. Unless something
has changed, these where [-2, -3, -4] when the class was written.
beta, anisotropy: pd.Series
The 1D array-like objects containing the beta and anisotropy
measurements.
"""
self._init_logger()
self.set_instability_parameters(growth_rate)
self.set_beta_ani(beta, anisotropy)
self.calculate_stability_criteria()
def __str__(self):
return self.__class__.__name__
def _init_logger(self):
logger = logging.getLogger("{}.{}".format(__name__, self.__class__.__name__))
self._logger = logger
@property
def fill(self):
r"""Used for building data containers and checking that all entries are visited.
"""
return -9999.0
@property
def instability_parameters(self):
return self._instability_parameters
@property
def data(self):
return self._data
@property
def beta(self):
return self.data.loc[:, "beta"]
@property
def anisotropy(self):
return self.data.loc[:, "anisotropy"]
@property
def stability_map(self):
return {
4: "MM",
3: "Between\nAIC &\nMM",
2: "Stable",
1: "Between\nFMW &\nOFI",
0: "OFI",
}
@property
def stability_map_inverse(self):
return {v: k for k, v in self.stability_map.items()}
@property
def instability_thresholds(self):
return self._instability_thresholds
@property
def instability_tests(self):
return _instability_tests._asdict()
@property
def is_unstable(self):
return self._is_unstable
@property
def stability_bin(self):
return self._stability_bin
@property
def cmap(self):
return plt.cm.get_cmap("Paired", len(self.stability_map))
@property
# TODO: rename to `color_norm` for consistancy w/ plotting code.
def norm(self):
# Change the normalization slightly so that the tick marks are
# centered in their respective regions.
# TODO: What about using a BoundaryNorm instead and setting
# the boundaries at the mid points (avgs) between the stability_map
# keys? (20161112_1505)
min_norm = min(self.stability_map) - 0.5
max_norm = max(self.stability_map) + 0.5
return mpl.colors.Normalize(min_norm, max_norm)
@property
def cbar_kwargs(self):
cbar_formatter = mpl.pyplot.FuncFormatter(
lambda val, loc: self.stability_map[val]
)
ticks = sorted(self.stability_map.keys())
format_dict = dict(
format=cbar_formatter,
ticks=ticks,
extend="neither",
cmap=self.cmap,
norm=self.norm,
)
return format_dict
def set_instability_parameters(self, growth_rate):
growth_rate = int(growth_rate)
temp = insta_params.xs(growth_rate, axis=0, level="Growth Rate")
self._instability_parameters = temp
def set_beta_ani(self, beta, anisotropy):
assert beta.shape == anisotropy.shape
data = pd.concat({"beta": beta, "anisotropy": anisotropy}, axis=1)
self._data = data
def _calc_instability_thresholds(self):
r"""Calculate the beta for which a given anisotropy is unstable.
"""
instability_thresholds = {
k: beta_ani_inst(self.beta, **v)
for k, v in self.instability_parameters.iterrows()
}
instability_thresholds = pd.DataFrame.from_dict(instability_thresholds)
instability_thresholds = instability_thresholds.sort_index(axis=1)
self._instability_thresholds = instability_thresholds
def _calc_is_unstable(self):
r"""Calculate if the plasma is unstable to a given mode for the `growth_rate`.
"""
is_unstable = {
k: self.instability_tests[k](self.anisotropy, v)
for k, v in self.instability_thresholds.iteritems()
}
is_unstable = pd.concat(is_unstable, axis=1).sort_index(axis=1)
# If the value is NaN in `instability_thresholds`, the comparison
# returns False. We want to propagate it so that we can check the
# other instabilities.
is_unstable.mask(self.instability_thresholds.isnull(), inplace=True)
# When an instability is NaN, we have to check the other instabilities.
for key, column in is_unstable.iteritems():
# Temporarily replace the NaNs here with False because NaNs don"t
# qualify as unstable on their own. We make the replacement here
# and not earlier because we are relying on those NaNs to indicate
# the spectra we must actually check against the other
# instabilities.
others = is_unstable.drop(key, axis=1)
others = others.replace(np.nan, False).all(axis=1)
column = column.mask(column.isnull(), others).astype(bool)
is_unstable.loc[:, key] = column
if is_unstable.isnull().any().any():
msg = "Did you visit every data point? " "It looks like you missed %s."
msg = msg % (not is_unstable.isnull()).sum()
raise ValueError(msg)
self._is_unstable = is_unstable
def _calc_stability_bin(self):
r"""Using the results of `self._calc_instability_threshold` and `self._calc_is_unstable`,
determine the category each spectrum belongs in:
MM, between_AIC_MM, Stable, between_FMW_OFI, OFI
"""
unstable = self.is_unstable
between_AIC_MM = unstable.AIC & unstable.MM.pipe(np.logical_not)
between_FMW_OFI = unstable.FMW & unstable.OFI.pipe(np.logical_not)
stable = unstable.pipe(np.logical_not).all(axis=1)
# Here, we use integer identifiers b/c they are more
# computationally efficient to process.
stability_bin = pd.Series(self.fill, index=unstable.index, name="Stability")
map_inverse = self.stability_map_inverse
stability_bin.mask(stable, map_inverse["Stable"], inplace=True)
stability_bin.mask(
between_AIC_MM, map_inverse["Between\nAIC &\nMM"], inplace=True
)
stability_bin.mask(unstable.MM, map_inverse["MM"], inplace=True)
stability_bin.mask(
between_FMW_OFI, map_inverse["Between\nFMW &\nOFI"], inplace=True
)
stability_bin.mask(unstable.OFI, map_inverse["OFI"], inplace=True)
if (stability_bin == self.fill).any():
msg = "Did you visit every data point? " "It looks like you missed %s."
msg = msg % (stability_bin == self.fill).sum()
raise ValueError(msg)
self._stability_bin = stability_bin
def calculate_stability_criteria(self):
r"""
Run the full instability calculation.
N.B. This function was written to collect all steps. The steps are broken into:
1) `_calc_instability_thresholds` calculates each stability
threshold in anisotropy given beta.
2) `_calc_is_unstable` determines if the plasma is unstable to (1).
3) `_calc_stability_bin` categorize the instabilities according to
the `stability_map`.
so that we can refactor or expand functionality later should that be desired.
Also, while one could call the `.stability_bin` property to automatically calculate the different steps,
that function doesn"t force recalculation if we have, for example, changed the growth rate.
"""
self._calc_instability_thresholds()
self._calc_is_unstable()
self._calc_stability_bin()
class StabilityContours(object):
r"""
Calculate stability contours in the (beta, Rt) plane with a simple
API to add them to a matplotlib plot axis.
Parameters
----------
describe inputs
Methods
-------
describe methods
See Also
--------
what else should I look at?
Notes
-----
-last test :
-pass?
--condition:
-version :
-location :
--failure:
-Development history:
-Started class. (20170530 1630)
--major challenges:
Proposed updates
----------------
-Add beta limits for the range of parameters from the Verscharen2016a
fits. (20170530 1631)
Do not try
----------
"""
def __init__(self, beta):
self.set_beta(beta)
self._calc_instability_contours()
@property
def beta(self):
r"""
Proton core parallel beta.
"""
return self._beta
def set_beta(self, new):
assert isinstance(new, np.ndarray)
self._beta = new
def _calc_instability_contours(self):
r"""
Because we can call the contours many times, but only
need to calculate them once, move the calculation to
a separate method.
"""
contours = {
k: beta_ani_inst(self.beta, **v) for k, v in insta_params.iterrows()
}
contours = pd.Series(contours).unstack(level=0)
assert isinstance(contours, pd.DataFrame)
self._contours = contours
@property
def contours(self):
return self._contours
def plot_contours(
self, ax, fix_scale=True, plot_gamma=None, tk_kind=None, **kwargs
):
r"""
Add the instability contours to the plot.
Parameters
----------
ax: mpl.axis
fix_scale: bool
If True, make x- and y-axes log scaled.
plot_gamma: None, -2, -3, -4
If not None, the instability parameter to plot.
tk_kind: None, str, list-like of str
Contours to plot. Valid options are "MM", "AIC", "FMW", "OFI",
and any combination thereof.
"""
assert isinstance(ax, mpl.axes.Axes)
images_for_table_legend = pd.DataFrame(
index=self.contours.index, columns=self.contours.columns
)
kwargs = mpl.cbook.normalize_kwargs(kwargs, mpl.lines.Line2D._alias_map)
ms = kwargs.pop("markersize", 10)
mew = kwargs.pop("markeredgewidth", 0.5)
mec = kwargs.pop("markeredgecolor", "k")
markevery = kwargs.pop("markevery", 10)
if tk_kind is not None:
if isinstance(tk_kind, str):
tk_kind = [tk_kind]
if not np.all([isinstance(x, str) for x in tk_kind]):
raise TypeError(f"""Unexpected types for `tk_kind` ({tk_kind})""")
tk_kind = [x.upper() for x in tk_kind]
if not np.all([x in self.contours.columns for x in tk_kind]):
raise ValueError(f"""Unexpected values for `tk_kind` ({tk_kind})""")
target_contours = self.contours
if tk_kind is not None:
target_contours = target_contours.loc[:, tk_kind]
target_contours = target_contours.stack()
for k, v in target_contours.iteritems():
gamma, itype = k
if plot_gamma is not None:
plot_gamma = int(plot_gamma)
assert plot_gamma in [-2, -3, -4], "Unrecognized gamma: %s" % plot_gamma
if gamma != plot_gamma:
# Don't plot this gamma.
continue
plot_kwargs = _plot_contour_kwargs.loc[gamma, itype]
if gamma is not None:
plot_kwargs["label"] = itype
im = ax.plot(
self.beta,
v,
# label=k,
markevery=markevery,
ms=ms,
mew=mew,
mec=mec,
**plot_kwargs,
**kwargs,
)
# only want line object, not list of them. so im[0].
images_for_table_legend.loc[gamma, itype] = im[0]
if fix_scale:
ax.set_xscale("log")
ax.set_yscale("log")
if plot_gamma is None:
# Only need legend table if plotting all contours.
self._add_table_legend(ax, images_for_table_legend)
else:
ax.legend(
loc=1,
title=r"$\gamma/\Omega_{p} = 10^{%s}$" % plot_gamma,
framealpha=0,
ncol=2,
)
@staticmethod
def _add_table_legend(ax, images):
r"""
Create a legend in compact table format for identifying the
instability contours.
Modified from stackoverflow.
Source: https://stackoverflow.com/a/25995730/1200989
"""
assert isinstance(images, pd.DataFrame)
# assert images.shape == _plot_contour_kwargs.shape
# create blank rectangle
extra = mpl.patches.Rectangle(
(0, 0), 1, 1, fc="w", fill=False, edgecolor="none", linewidth=0
)
# Create organized list containing all handles for table.
# Extra represent empty space
legend_handles = [
extra,
extra,
extra,
extra,
extra,
extra,
images.loc[-2, "MM"],
images.loc[-2, "AIC"],
images.loc[-2, "FMW"],
images.loc[-2, "OFI"],
extra,
images.loc[-3, "MM"],
images.loc[-3, "AIC"],
images.loc[-3, "FMW"],
images.loc[-3, "OFI"],
extra,
images.loc[-4, "MM"],
images.loc[-4, "AIC"],
images.loc[-4, "FMW"],
images.loc[-4, "OFI"],
]
# Define the labels
label_rows = [
r"",
r"$\mathrm{AIC}$",
r"$\mathrm{FMW}$",
r"$\mathrm{MM}$",
r"$\mathrm{OFI}$",
]
label_col_0 = [r"$-2$"]
label_col_1 = [r"$-3$"]
label_col_2 = [r"$-4$"]
label_empty = [""]
# organize labels for table construction
legend_labels = (
label_rows
+ label_col_0
+ label_empty * 4
+ label_col_1
+ label_empty * 4
+ label_col_2
+ label_empty * 4
)
# Create legend
ax.legend(
legend_handles,
legend_labels,
loc=1,
ncol=4,
shadow=True,
handletextpad=-2,
framealpha=0.75,
)
# plt.show()
# if __name__ == "__main__":
# import unittest
# unittest.runner
|
[
"pandas.DataFrame",
"matplotlib.pyplot.FuncFormatter",
"pandas.MultiIndex.from_tuples",
"pandas.DataFrame.from_dict",
"matplotlib.colors.Normalize",
"matplotlib.patches.Rectangle",
"pandas.Index",
"collections.namedtuple",
"pandas.Series",
"matplotlib.cbook.normalize_kwargs",
"pandas.concat",
"numpy.all"
] |
[((1184, 1240), 'pandas.Index', 'pd.Index', (["['AIC', 'FMW', 'MM', 'OFI']"], {'name': '"""Intability"""'}), "(['AIC', 'FMW', 'MM', 'OFI'], name='Intability')\n", (1192, 1240), True, 'import pandas as pd\n'), ((1254, 1301), 'pandas.Index', 'pd.Index', (["['a', 'b', 'c']"], {'name': '"""Fit Parameter"""'}), "(['a', 'b', 'c'], name='Fit Parameter')\n", (1262, 1301), True, 'import pandas as pd\n'), ((1320, 1376), 'pandas.Index', 'pd.Index', (["['AIC', 'FMW', 'MM', 'OFI']"], {'name': '"""Intability"""'}), "(['AIC', 'FMW', 'MM', 'OFI'], name='Intability')\n", (1328, 1376), True, 'import pandas as pd\n'), ((1390, 1437), 'pandas.Index', 'pd.Index', (["['a', 'b', 'c']"], {'name': '"""Fit Parameter"""'}), "(['a', 'b', 'c'], name='Fit Parameter')\n", (1398, 1437), True, 'import pandas as pd\n'), ((3317, 3365), 'collections.namedtuple', 'namedtuple', (['"""InstabilityTests"""', '"""AIC,MM,FMW,OFI"""'], {}), "('InstabilityTests', 'AIC,MM,FMW,OFI')\n", (3327, 3365), False, 'from collections import namedtuple\n'), ((2849, 3076), 'pandas.MultiIndex.from_tuples', 'pd.MultiIndex.from_tuples', (["[(-4, 'AIC'), (-4, 'FMW'), (-4, 'MM'), (-4, 'OFI'), (-3, 'AIC'), (-3, 'FMW'\n ), (-3, 'MM'), (-3, 'OFI'), (-2, 'AIC'), (-2, 'FMW'), (-2, 'MM'), (-2,\n 'OFI')]"], {'names': "['Growth Rate', 'Instability']"}), "([(-4, 'AIC'), (-4, 'FMW'), (-4, 'MM'), (-4, 'OFI'\n ), (-3, 'AIC'), (-3, 'FMW'), (-3, 'MM'), (-3, 'OFI'), (-2, 'AIC'), (-2,\n 'FMW'), (-2, 'MM'), (-2, 'OFI')], names=['Growth Rate', 'Instability'])\n", (2874, 3076), True, 'import pandas as pd\n'), ((9125, 9165), 'matplotlib.colors.Normalize', 'mpl.colors.Normalize', (['min_norm', 'max_norm'], {}), '(min_norm, max_norm)\n', (9145, 9165), True, 'import matplotlib as mpl\n'), ((9233, 9299), 'matplotlib.pyplot.FuncFormatter', 'mpl.pyplot.FuncFormatter', (['(lambda val, loc: self.stability_map[val])'], {}), '(lambda val, loc: self.stability_map[val])\n', (9257, 9299), True, 'import matplotlib as mpl\n'), ((9905, 9964), 'pandas.concat', 'pd.concat', (["{'beta': beta, 'anisotropy': anisotropy}"], {'axis': '(1)'}), "({'beta': beta, 'anisotropy': anisotropy}, axis=1)\n", (9914, 9964), True, 'import pandas as pd\n'), ((10307, 10353), 'pandas.DataFrame.from_dict', 'pd.DataFrame.from_dict', (['instability_thresholds'], {}), '(instability_thresholds)\n', (10329, 10353), True, 'import pandas as pd\n'), ((12710, 12770), 'pandas.Series', 'pd.Series', (['self.fill'], {'index': 'unstable.index', 'name': '"""Stability"""'}), "(self.fill, index=unstable.index, name='Stability')\n", (12719, 12770), True, 'import pandas as pd\n'), ((16726, 16796), 'pandas.DataFrame', 'pd.DataFrame', ([], {'index': 'self.contours.index', 'columns': 'self.contours.columns'}), '(index=self.contours.index, columns=self.contours.columns)\n', (16738, 16796), True, 'import pandas as pd\n'), ((16837, 16900), 'matplotlib.cbook.normalize_kwargs', 'mpl.cbook.normalize_kwargs', (['kwargs', 'mpl.lines.Line2D._alias_map'], {}), '(kwargs, mpl.lines.Line2D._alias_map)\n', (16863, 16900), True, 'import matplotlib as mpl\n'), ((19554, 19644), 'matplotlib.patches.Rectangle', 'mpl.patches.Rectangle', (['(0, 0)', '(1)', '(1)'], {'fc': '"""w"""', 'fill': '(False)', 'edgecolor': '"""none"""', 'linewidth': '(0)'}), "((0, 0), 1, 1, fc='w', fill=False, edgecolor='none',\n linewidth=0)\n", (19575, 19644), True, 'import matplotlib as mpl\n'), ((1483, 1644), 'pandas.DataFrame', 'pd.DataFrame', (['[[0.367, 0.364, 0.011], [-0.408, 0.529, 0.41], [0.702, 0.674, -0.009], [-\n 1.454, 1.023, -0.178]]'], {'index': '_inst_type_idx', 'columns': '_param_idx'}), '([[0.367, 0.364, 0.011], [-0.408, 0.529, 0.41], [0.702, 0.674, \n -0.009], [-1.454, 1.023, -0.178]], index=_inst_type_idx, columns=_param_idx\n )\n', (1495, 1644), True, 'import pandas as pd\n'), ((1774, 1930), 'pandas.DataFrame', 'pd.DataFrame', (['[[0.437, 0.428, -0.003], [-0.497, 0.566, 0.543], [0.801, 0.763, -0.063], [-\n 1.39, 1.005, -0.111]]'], {'index': '_inst_type_idx', 'columns': '_param_idx'}), '([[0.437, 0.428, -0.003], [-0.497, 0.566, 0.543], [0.801, 0.763,\n -0.063], [-1.39, 1.005, -0.111]], index=_inst_type_idx, columns=_param_idx)\n', (1786, 1930), True, 'import pandas as pd\n'), ((2066, 2216), 'pandas.DataFrame', 'pd.DataFrame', (['[[0.649, 0.4, 0.0], [-0.647, 0.583, 0.713], [1.04, 0.633, -0.012], [-1.447,\n 1.0, -0.148]]'], {'index': '_inst_type_idx', 'columns': '_param_idx'}), '([[0.649, 0.4, 0.0], [-0.647, 0.583, 0.713], [1.04, 0.633, -\n 0.012], [-1.447, 1.0, -0.148]], index=_inst_type_idx, columns=_param_idx)\n', (2078, 2216), True, 'import pandas as pd\n'), ((10805, 10835), 'pandas.concat', 'pd.concat', (['is_unstable'], {'axis': '(1)'}), '(is_unstable, axis=1)\n', (10814, 10835), True, 'import pandas as pd\n'), ((15881, 15900), 'pandas.Series', 'pd.Series', (['contours'], {}), '(contours)\n', (15890, 15900), True, 'import pandas as pd\n'), ((17419, 17474), 'numpy.all', 'np.all', (['[(x in self.contours.columns) for x in tk_kind]'], {}), '([(x in self.contours.columns) for x in tk_kind])\n', (17425, 17474), True, 'import numpy as np\n')]
|
from abc import abstractmethod
import types
import numpy as np
import os
from multiprocessing import Pool
import schwimmbad
# from schwimmbad import SerialPool, MultiPool, MPIPool
from argparse import ArgumentParser
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
from corner import corner
import zeus
import emcee
import utils
import priors
import likelihood
from parameters import PARS_ORDER
from velocity import VelocityMap
from likelihood import log_posterior
import pudb
parser = ArgumentParser()
parser.add_argument('--show', action='store_true', default=False,
help='Set to show test plots')
parser.add_argument('--test', action='store_true', default=False,
help='Set to run tests')
class MCMCRunner(object):
'''
Class to run a MCMC chain with emcee or zeus
Currently a very light wrapper around emzee/zeus, but in principle
might want to do something fancier in the future
'''
def __init__(self, nwalkers, ndim, pfunc, args=None, kwargs=None):
'''
nwalkers: Number of MCMC walkers. Must be at least 2*ndim
ndim: Number of sampled dimensions
pfunc: Posterior function to sample from
args: List of additional args needed to evaluate posterior,
such as the data vector, covariance matrix, etc.
kwargs: List of additional kwargs needed to evaluate posterior,
such as the data vector, covariance matrix, etc.
'''
for name, val in {'nwalkers':nwalkers, 'ndim':ndim}.items():
if val <= 0:
raise ValueError(f'{name} must be positive!')
if not isinstance(val, int):
raise TypeError(f'{name} must be an int!')
if not callable(pfunc):
raise TypeError(f'{pfunc} is not callable!')
if args is not None:
if not isinstance(args, list):
raise TypeError('args must be a list!')
self.nwalkers = nwalkers
self.ndim = ndim
self.pfunc = pfunc
self.args = args
self.kwargs = kwargs
self.has_run = False
self.has_MAP = False
self.burn_in = None
# Are set after a run with `compute_MAP()`
self.MAP_means = None
self.MAP_medians = None
self.MAP_sigmas = None
return
@abstractmethod
def _initialize_sampler(self, pool=None):
pass
def _initialize_walkers(self, scale=0.1):
''''
TODO: Not obvious that this scale factor is reasonable
for our problem, should experiment & test further
Zeus reccommends to initialize in a small ball around the MAP
estimate, but that is of course difficult to know a priori
Might want to base this as some fractional scale for the width of
each prior, centered at the max of the prior
'''
if 'priors' in self.kwargs['pars']:
# use peak of priors for initialization
self.start = np.zeros((self.nwalkers, self.ndim))
for name, indx in PARS_ORDER.items():
prior = self.kwargs['pars']['priors'][name]
peak, cen = prior.peak, prior.cen
base = peak if peak is not None else cen
radius = base*scale if base !=0 else scale
# for (g1,g2), there seems to be some additional
# outlier problems. So reduce
if name in ['g1', 'g2']:
radius /= 2.
# random ball about base value
ball = radius * np.random.randn(self.nwalkers)
# rejcect 2+ sigma outliers or out of prior bounds
outliers, Noutliers = self._compute_start_outliers(
base, ball, radius, prior
)
# replace outliers
while Noutliers > 0:
ball[outliers] = radius * np.random.randn(Noutliers)
outliers, Noutliers = self._compute_start_outliers(
base, ball, radius, prior
)
self.start[:,indx] = base + ball
else:
# don't have much to go on
self.start = scale * np.random.rand(self.nwalkers, self.ndim)
return
def _compute_start_outliers(self, base, ball, radius, prior):
'''
base: The reference value
radius: The radius of the random ball
ball: A ball of random points centered at 0 with given radius
prior: prior being sampled with random points about ball
'''
outliers = np.abs(ball) > 2.*radius
if isinstance(prior, priors.UniformPrior):
left, right = prior.left, prior.right
outliers = outliers | \
((base + ball) < left) | \
((base + ball) > right)
elif isinstance(prior, priors.GaussPrior):
if prior.clip_sigmas is not None:
outliers = outliers | \
(abs(base + ball - prior.mu) > prior.clip_sigmas)
Noutliers = len(np.where(outliers == True)[0])
return outliers, Noutliers
def run(self, nsteps, pool, start=None, return_sampler=False,
vb=True):
'''
nsteps: int
Number of MCMC steps / iterations
pool: Pool
A pool object returned from schwimmbad. Can be SerialPool,
MultiPool, or MPIPool
start: list
Can provide starting walker positions if you don't
want to use the default initialization
return_sampler: bool
Set to True if you want the sampler returned
vb: bool
Will print out zeus summary if True
returns: zeus.EnsembleSampler object that contains the chains
'''
if start is None:
self._initialize_walkers()
start = self.start
if vb is True:
progress = True
else:
progress = False
if not isinstance(pool, schwimmbad.SerialPool):
omp = int(os.environ['OMP_NUM_THREADS'])
if omp != 1:
print('WARNING: ENV variable OMP_NUM_THREADS is ' +\
f'set to {omp}. If not set to 1, this will ' +\
'degrade perfomance for parallel processing.')
with pool:
pt = type(pool)
print(f'Pool: {pool}')
if isinstance(pool, schwimmbad.MPIPool):
if not pool.is_master():
pool.wait()
sys.exit(0)
sampler = self._initialize_sampler(pool=pool)
sampler.run_mcmc(
start, nsteps, progress=progress
)
self.sampler = sampler
self.has_run = True
if return_sampler is True:
return self.sampler
else:
return
def set_burn_in(burn_in):
self.burn_in = burn_in
return
def compute_MAP(self, discard=None, thin=1, recompute=False):
'''
TODO: For now, just computing the means & medians
Will fail for multi-modal distributions
discard: int
The number of samples to discard, from 0:discard
thin: int
The factor by which to thin out the samples by; i.e.
thin=2 will only use every-other sample
'''
if self.has_run is not True:
print('Warning: Cannot compute MAP until the mcmc has been run!')
return None
if self.has_MAP is True:
if recompute is False:
raise ValueError('MAP values aready computed for this ' +
'chain. To recompute with different ' +\
'choices, use recompute=True')
else:
return
if discard is None:
if self.burn_in is not None:
discard = self.burn_in
else:
raise ValueError('Must passs a value for discard if ' +\
'burn_in is not set!')
chain = self.sampler.get_chain(flat=True, discard=discard, thin=thin)
self.MAP_means = np.mean(chain, axis=0)
self.MAP_medians = np.median(chain, axis=0)
self.MAP_sigmas = []
for i in range(self.ndim):
self.MAP_sigmas.append(np.percentile(chain[:, i], [16, 84]))
self.has_MAP = True
return
def plot_chains(self, burn_in=0, reference=None, show=True, close=True,
outfile=None, size=None):
'''
burn_in: int
Set to discard the first 0:burn_in values of the chain
reference: list
Reference values to plot on chains, such as true values
'''
if self.has_run is not True:
print('Warning: Cannot plot chains until mcmc has been run!')
return
chain = self.sampler.get_chain()
ndim = self.ndim
if size is None:
size = (2*ndim, 1.25*ndim)
fig = plt.figure(figsize=size)
# for n in range(ndim):
for name, indx in PARS_ORDER.items():
plt.subplot2grid((ndim, 1), (indx, 0))
plt.plot(chain[burn_in:,:,indx], alpha=0.5)
plt.ylabel(name)
if reference is not None:
plt.axhline(reference[indx], lw=2, c='k', ls='--')
plt.tight_layout()
if outfile is not None:
plt.savefig(outfile, bbox_inches='tight', dpi=300)
if show is True:
plt.show()
if close is True:
plt.close()
return
def plot_corner(self, reference=None, discard=None, thin=1, crange=None,
show=True, close=True, outfile=None, size=(16,16),
show_titles=True, title=None, use_derived=True,
title_fmt='.3f'):
'''
reference: list
Reference values to plot on chains, such as true or MAP values
discard: int
Set to throw out first 0:discard samples. Will use self.burn_in
if already set
thin: int
Thins samples by the given factor
crange: list
A list of tuples or floats that define the parameter ranges or
percentile fraction that is shown. Same as corner range arg
use_derived: bool
Turn on to plot derived parameters as well
'''
if self.has_run is not True:
print('Warning: Cannot plot constraints until the mcmc has been run!')
return
if discard is None:
if self.burn_in is not None:
discard = self.burn_in
else:
raise ValueError('Must passs a value for discard if ' +\
'burn_in is not set!')
chain = self.sampler.get_chain(flat=True, discard=discard, thin=thin)
if use_derived is True:
# add derived quantity sini*vcirc
new_shape = (chain.shape[0], chain.shape[1]+1)
new_chain = np.zeros((new_shape))
new_chain[:,0:-1] = chain
i1, i2 = PARS_ORDER['sini'], PARS_ORDER['vcirc']
new_chain[:,-1] = chain[:,i1] * chain[:,i2]
chain = new_chain
if reference is not None:
if len(reference) != self.ndim:
raise ValueError('Length of reference list must be same as Ndim!')
if use_derived is True:
ref = reference[i1]*reference[i2]
if isinstance(reference, list):
reference.append(ref)
elif isinstance(reference, np.ndarray):
arr = np.zeros(len(reference)+1)
arr[0:-1] = reference
arr[-1] = ref
reference = arr
names = self.ndim*['']
for name, indx in PARS_ORDER.items():
names[indx] = name
if use_derived is True:
names.append('sini*vcirc')
else:
names = None
if crange is not None:
if use_derived is True:
crange.append(crange[-1])
if len(crange) != len(names):
raise ValueError('Length of crange list must be same as names!')
p = corner(
chain, labels=names, truths=reference, range=crange,
show_titles=show_titles, title_fmt=title_fmt
)
title_suffix = f'Burn in = {discard}'
if title is None:
title = title_suffix
else:
title += f'\n{title_suffix}'
plt.suptitle(title, fontsize=18)
if size is not None:
plt.gcf().set_size_inches(size)
plt.tight_layout()
if outfile is not None:
plt.savefig(outfile, bbox_inches='tight', dpi=300)
if show is True:
plt.show()
if close is True:
plt.close()
return
class ZeusRunner(MCMCRunner):
def _initialize_sampler(self, pool=None):
sampler = zeus.EnsembleSampler(
self.nwalkers, self.ndim, self.pfunc,
args=self.args, kwargs=self.kwargs, pool=pool
)
return sampler
class KLensZeusRunner(ZeusRunner):
'''
Main difference is that we assume args=[datacube] and
kwargs={pars:dict}
'''
def __init__(self, nwalkers, ndim, pfunc, datacube, pars):
'''
nwalkers: Number of MCMC walkers. Must be at least 2*ndim
ndim: Number of sampled dimensions
pfunc: Posterior function to sample from
datacube: Datacube object the fit a model to
pars: A dict of needed kwargs to evaluate posterior, such as
covariance matrix, SED definition, etc.
'''
super(KLensZeusRunner, self).__init__(
nwalkers, ndim, pfunc, args=[datacube], kwargs={'pars': pars}
)
self.datacube = datacube
self.pars = pars
self.MAP_vmap = None
return
def compute_MAP(self, discard=None, thin=1, recompute=False):
super(KLensZeusRunner, self).compute_MAP(
discard=discard, thin=thin, recompute=recompute
)
theta_pars = likelihood.theta2pars(self.MAP_medians)
# Now compute the corresonding (median) MAP velocity map
# vel_pars = theta_pars.copy()
# vel_pars['r_unit'] = self.pars['r_unit']
# vel_pars['v_unit'] = self.pars['v_unit']
# self.MAP_vmap = VelocityMap('default', vel_pars)
self.MAP_vmap = likelihood._setup_vmap(theta_pars, self.pars)
# Now do the same for the corresonding (median) MAP intensity map
# TODO: For now, doing same simple thing in likelihood
self.MAP_imap = likelihood._setup_imap(
theta_pars, self.datacube, self.pars
)
return
def compare_MAP_to_truth(self, true_vmap, show=True, close=True,
outfile=None, size=(8,8)):
'''
true_vmap: VelocityMap object
True velocity map
'''
Nx, Ny = self.datacube.Nx, self.datacube.Ny
X, Y = utils.build_map_grid(Nx, Ny)
Vtrue = true_vmap('obs', X, Y)
Vmap = self.MAP_vmap('obs', X, Y)
fig, axes = plt.subplots(2,2, figsize=size, sharey=True)
titles = ['Truth', 'MAP Model', 'Residual', '% Residual']
images = [Vtrue, Vmap, Vmap-Vtrue, 100.*(Vmap-Vtrue)/Vtrue]
for i in range(4):
ax = axes[i//2, i%2]
if '%' in titles[i]:
vmin = np.max([-100., np.min(images[i])])
vmax = np.min([ 100., np.max(images[i])])
else:
vmin, vmax = None, None
im = ax.imshow(
images[i], origin='lower', vmin=vmin, vmax=vmax
)
ax.set_title(titles[i])
divider = make_axes_locatable(ax)
cax = divider.append_axes('right', size='5%', pad=0.05)
plt.colorbar(im, cax=cax)
plt.tight_layout()
if outfile is not None:
plt.savefig(outfile, bbox_inches='tight', dpi=300)
if show is True:
plt.show()
if close is True:
plt.close()
return
def compare_MAP_to_data(self, show=True, close=True, outfile=None,
size=(16,5)):
'''
For this subclass, have guaranteed access to datacube
'''
if self.has_MAP is False:
print('MAP has not been computed yet; trying now ' +\
'with default parameters')
self.compute_MAP()
# gather needed components to evaluate model
datacube = self.datacube
lambdas = datacube.lambdas
sed = likelihood._setup_sed(self.pars)
sed_array = np.array([sed.x, sed.y])
vmap = self.MAP_vmap
imap = self.MAP_imap
# create grid of pixel centers in image coords
Nx = datacube.Nx
Ny = datacube.Ny
X, Y = utils.build_map_grid(Nx, Ny)
# Compute zfactor from MAP velocity map
V = vmap('obs', X, Y, normalized=True)
zfactor = 1. / (1. + V)
# compute intensity map from MAP
# TODO: Eventually this should be called like vmap
theta_pars = likelihood.theta2pars(self.MAP_medians)
intensity = imap.render(theta_pars, datacube, self.pars)
Nspec = datacube.Nspec
fig, axs = plt.subplots(4, Nspec, sharex=True, sharey=True,)
for i in range(Nspec):
# first, data
ax = axs[0,i]
data = datacube.slices[i]._data
im = ax.imshow(data, origin='lower')
if i == 0:
ax.set_ylabel('Data')
l, r = lambdas[i]
ax.set_title(f'({l:.1f}, {r:.1f}) nm')
divider = make_axes_locatable(ax)
cax = divider.append_axes('right', size='5%', pad=0.05)
plt.colorbar(im, cax=cax)
# second, model
ax = axs[1,i]
model = likelihood._compute_slice_model(
lambdas[i], sed_array, zfactor, intensity
)
im = ax.imshow(model, origin='lower')
if i == 0:
ax.set_ylabel('Model')
divider = make_axes_locatable(ax)
cax = divider.append_axes('right', size='5%', pad=0.05)
plt.colorbar(im, cax=cax)
# third, residual
ax = axs[2,i]
residual = data - model
im = ax.imshow(residual, origin='lower')
if i == 0:
ax.set_ylabel('Residual')
divider = make_axes_locatable(ax)
cax = divider.append_axes('right', size='5%', pad=0.05)
plt.colorbar(im, cax=cax)
# fourth, % residual
ax = axs[3,i]
residual = 100. * (data - model) / model
vmin = np.max([-100, np.min(residual)])
vmax = np.min([ 100, np.max(residual)])
im = ax.imshow(residual, origin='lower', vmin=vmin, vmax=vmax)
if i == 0:
ax.set_ylabel('% Residual')
divider = make_axes_locatable(ax)
cax = divider.append_axes('right', size='5%', pad=0.05)
plt.colorbar(im, cax=cax)
if size is not None:
plt.gcf().set_size_inches(size)
plt.tight_layout()
if outfile is not None:
plt.savefig(outfile, bbox_inches='tight', dpi=300)
if show is True:
plt.show()
if close is True:
plt.close()
return
class KLensEmceeRunner(KLensZeusRunner):
def _initialize_sampler(self, pool=None):
sampler = emcee.EnsembleSampler(
self.nwalkers, self.ndim, self.pfunc,
args=self.args, kwargs=self.kwargs, pool=pool
)
return sampler
def main(args):
show = args.show
outdir = os.path.join(utils.TEST_DIR, 'mcmc')
utils.make_dir(outdir)
print('Creating ZeusRunner object')
ndims = 10
nwalkers = 2*ndims
args = None
kwargs = None
runner = ZeusRunner(nwalkers, ndims, log_posterior, args=args, kwargs=kwargs)
return 0
if __name__ == '__main__':
args = parser.parse_args()
if args.test is True:
print('Starting tests')
rc = main(args)
if rc == 0:
print('All tests ran succesfully')
else:
print(f'Tests failed with return code of {rc}')
|
[
"utils.make_dir",
"argparse.ArgumentParser",
"numpy.abs",
"matplotlib.pyplot.suptitle",
"matplotlib.pyplot.subplot2grid",
"parameters.PARS_ORDER.items",
"matplotlib.pyplot.figure",
"numpy.mean",
"matplotlib.pyplot.tight_layout",
"os.path.join",
"zeus.EnsembleSampler",
"numpy.random.randn",
"matplotlib.pyplot.close",
"matplotlib.pyplot.colorbar",
"numpy.max",
"matplotlib.pyplot.subplots",
"likelihood.theta2pars",
"likelihood._setup_sed",
"utils.build_map_grid",
"matplotlib.pyplot.axhline",
"corner.corner",
"matplotlib.pyplot.show",
"numpy.median",
"numpy.percentile",
"numpy.min",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.gcf",
"likelihood._setup_vmap",
"mpl_toolkits.axes_grid1.make_axes_locatable",
"likelihood._compute_slice_model",
"matplotlib.pyplot.plot",
"emcee.EnsembleSampler",
"numpy.zeros",
"likelihood._setup_imap",
"numpy.where",
"numpy.array",
"numpy.random.rand",
"matplotlib.pyplot.savefig"
] |
[((528, 544), 'argparse.ArgumentParser', 'ArgumentParser', ([], {}), '()\n', (542, 544), False, 'from argparse import ArgumentParser\n'), ((20159, 20195), 'os.path.join', 'os.path.join', (['utils.TEST_DIR', '"""mcmc"""'], {}), "(utils.TEST_DIR, 'mcmc')\n", (20171, 20195), False, 'import os\n'), ((20200, 20222), 'utils.make_dir', 'utils.make_dir', (['outdir'], {}), '(outdir)\n', (20214, 20222), False, 'import utils\n'), ((8332, 8354), 'numpy.mean', 'np.mean', (['chain'], {'axis': '(0)'}), '(chain, axis=0)\n', (8339, 8354), True, 'import numpy as np\n'), ((8382, 8406), 'numpy.median', 'np.median', (['chain'], {'axis': '(0)'}), '(chain, axis=0)\n', (8391, 8406), True, 'import numpy as np\n'), ((9195, 9219), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': 'size'}), '(figsize=size)\n', (9205, 9219), True, 'import matplotlib.pyplot as plt\n'), ((9278, 9296), 'parameters.PARS_ORDER.items', 'PARS_ORDER.items', ([], {}), '()\n', (9294, 9296), False, 'from parameters import PARS_ORDER\n'), ((9549, 9567), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (9565, 9567), True, 'import matplotlib.pyplot as plt\n'), ((12487, 12597), 'corner.corner', 'corner', (['chain'], {'labels': 'names', 'truths': 'reference', 'range': 'crange', 'show_titles': 'show_titles', 'title_fmt': 'title_fmt'}), '(chain, labels=names, truths=reference, range=crange, show_titles=\n show_titles, title_fmt=title_fmt)\n', (12493, 12597), False, 'from corner import corner\n'), ((12796, 12828), 'matplotlib.pyplot.suptitle', 'plt.suptitle', (['title'], {'fontsize': '(18)'}), '(title, fontsize=18)\n', (12808, 12828), True, 'import matplotlib.pyplot as plt\n'), ((12912, 12930), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (12928, 12930), True, 'import matplotlib.pyplot as plt\n'), ((13239, 13348), 'zeus.EnsembleSampler', 'zeus.EnsembleSampler', (['self.nwalkers', 'self.ndim', 'self.pfunc'], {'args': 'self.args', 'kwargs': 'self.kwargs', 'pool': 'pool'}), '(self.nwalkers, self.ndim, self.pfunc, args=self.args,\n kwargs=self.kwargs, pool=pool)\n', (13259, 13348), False, 'import zeus\n'), ((14423, 14462), 'likelihood.theta2pars', 'likelihood.theta2pars', (['self.MAP_medians'], {}), '(self.MAP_medians)\n', (14444, 14462), False, 'import likelihood\n'), ((14754, 14799), 'likelihood._setup_vmap', 'likelihood._setup_vmap', (['theta_pars', 'self.pars'], {}), '(theta_pars, self.pars)\n', (14776, 14799), False, 'import likelihood\n'), ((14962, 15022), 'likelihood._setup_imap', 'likelihood._setup_imap', (['theta_pars', 'self.datacube', 'self.pars'], {}), '(theta_pars, self.datacube, self.pars)\n', (14984, 15022), False, 'import likelihood\n'), ((15351, 15379), 'utils.build_map_grid', 'utils.build_map_grid', (['Nx', 'Ny'], {}), '(Nx, Ny)\n', (15371, 15379), False, 'import utils\n'), ((15484, 15529), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(2)'], {'figsize': 'size', 'sharey': '(True)'}), '(2, 2, figsize=size, sharey=True)\n', (15496, 15529), True, 'import matplotlib.pyplot as plt\n'), ((16238, 16256), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (16254, 16256), True, 'import matplotlib.pyplot as plt\n'), ((16982, 17014), 'likelihood._setup_sed', 'likelihood._setup_sed', (['self.pars'], {}), '(self.pars)\n', (17003, 17014), False, 'import likelihood\n'), ((17035, 17059), 'numpy.array', 'np.array', (['[sed.x, sed.y]'], {}), '([sed.x, sed.y])\n', (17043, 17059), True, 'import numpy as np\n'), ((17239, 17267), 'utils.build_map_grid', 'utils.build_map_grid', (['Nx', 'Ny'], {}), '(Nx, Ny)\n', (17259, 17267), False, 'import utils\n'), ((17518, 17557), 'likelihood.theta2pars', 'likelihood.theta2pars', (['self.MAP_medians'], {}), '(self.MAP_medians)\n', (17539, 17557), False, 'import likelihood\n'), ((17675, 17723), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(4)', 'Nspec'], {'sharex': '(True)', 'sharey': '(True)'}), '(4, Nspec, sharex=True, sharey=True)\n', (17687, 17723), True, 'import matplotlib.pyplot as plt\n'), ((19599, 19617), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (19615, 19617), True, 'import matplotlib.pyplot as plt\n'), ((19937, 20047), 'emcee.EnsembleSampler', 'emcee.EnsembleSampler', (['self.nwalkers', 'self.ndim', 'self.pfunc'], {'args': 'self.args', 'kwargs': 'self.kwargs', 'pool': 'pool'}), '(self.nwalkers, self.ndim, self.pfunc, args=self.args,\n kwargs=self.kwargs, pool=pool)\n', (19958, 20047), False, 'import emcee\n'), ((3064, 3100), 'numpy.zeros', 'np.zeros', (['(self.nwalkers, self.ndim)'], {}), '((self.nwalkers, self.ndim))\n', (3072, 3100), True, 'import numpy as np\n'), ((3132, 3150), 'parameters.PARS_ORDER.items', 'PARS_ORDER.items', ([], {}), '()\n', (3148, 3150), False, 'from parameters import PARS_ORDER\n'), ((4694, 4706), 'numpy.abs', 'np.abs', (['ball'], {}), '(ball)\n', (4700, 4706), True, 'import numpy as np\n'), ((9310, 9348), 'matplotlib.pyplot.subplot2grid', 'plt.subplot2grid', (['(ndim, 1)', '(indx, 0)'], {}), '((ndim, 1), (indx, 0))\n', (9326, 9348), True, 'import matplotlib.pyplot as plt\n'), ((9361, 9406), 'matplotlib.pyplot.plot', 'plt.plot', (['chain[burn_in:, :, indx]'], {'alpha': '(0.5)'}), '(chain[burn_in:, :, indx], alpha=0.5)\n', (9369, 9406), True, 'import matplotlib.pyplot as plt\n'), ((9417, 9433), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['name'], {}), '(name)\n', (9427, 9433), True, 'import matplotlib.pyplot as plt\n'), ((9613, 9663), 'matplotlib.pyplot.savefig', 'plt.savefig', (['outfile'], {'bbox_inches': '"""tight"""', 'dpi': '(300)'}), "(outfile, bbox_inches='tight', dpi=300)\n", (9624, 9663), True, 'import matplotlib.pyplot as plt\n'), ((9702, 9712), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (9710, 9712), True, 'import matplotlib.pyplot as plt\n'), ((9752, 9763), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (9761, 9763), True, 'import matplotlib.pyplot as plt\n'), ((11233, 11252), 'numpy.zeros', 'np.zeros', (['new_shape'], {}), '(new_shape)\n', (11241, 11252), True, 'import numpy as np\n'), ((12066, 12084), 'parameters.PARS_ORDER.items', 'PARS_ORDER.items', ([], {}), '()\n', (12082, 12084), False, 'from parameters import PARS_ORDER\n'), ((12976, 13026), 'matplotlib.pyplot.savefig', 'plt.savefig', (['outfile'], {'bbox_inches': '"""tight"""', 'dpi': '(300)'}), "(outfile, bbox_inches='tight', dpi=300)\n", (12987, 13026), True, 'import matplotlib.pyplot as plt\n'), ((13065, 13075), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (13073, 13075), True, 'import matplotlib.pyplot as plt\n'), ((13115, 13126), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (13124, 13126), True, 'import matplotlib.pyplot as plt\n'), ((16099, 16122), 'mpl_toolkits.axes_grid1.make_axes_locatable', 'make_axes_locatable', (['ax'], {}), '(ax)\n', (16118, 16122), False, 'from mpl_toolkits.axes_grid1 import make_axes_locatable\n'), ((16203, 16228), 'matplotlib.pyplot.colorbar', 'plt.colorbar', (['im'], {'cax': 'cax'}), '(im, cax=cax)\n', (16215, 16228), True, 'import matplotlib.pyplot as plt\n'), ((16302, 16352), 'matplotlib.pyplot.savefig', 'plt.savefig', (['outfile'], {'bbox_inches': '"""tight"""', 'dpi': '(300)'}), "(outfile, bbox_inches='tight', dpi=300)\n", (16313, 16352), True, 'import matplotlib.pyplot as plt\n'), ((16391, 16401), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (16399, 16401), True, 'import matplotlib.pyplot as plt\n'), ((16441, 16452), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (16450, 16452), True, 'import matplotlib.pyplot as plt\n'), ((18065, 18088), 'mpl_toolkits.axes_grid1.make_axes_locatable', 'make_axes_locatable', (['ax'], {}), '(ax)\n', (18084, 18088), False, 'from mpl_toolkits.axes_grid1 import make_axes_locatable\n'), ((18169, 18194), 'matplotlib.pyplot.colorbar', 'plt.colorbar', (['im'], {'cax': 'cax'}), '(im, cax=cax)\n', (18181, 18194), True, 'import matplotlib.pyplot as plt\n'), ((18270, 18344), 'likelihood._compute_slice_model', 'likelihood._compute_slice_model', (['lambdas[i]', 'sed_array', 'zfactor', 'intensity'], {}), '(lambdas[i], sed_array, zfactor, intensity)\n', (18301, 18344), False, 'import likelihood\n'), ((18513, 18536), 'mpl_toolkits.axes_grid1.make_axes_locatable', 'make_axes_locatable', (['ax'], {}), '(ax)\n', (18532, 18536), False, 'from mpl_toolkits.axes_grid1 import make_axes_locatable\n'), ((18617, 18642), 'matplotlib.pyplot.colorbar', 'plt.colorbar', (['im'], {'cax': 'cax'}), '(im, cax=cax)\n', (18629, 18642), True, 'import matplotlib.pyplot as plt\n'), ((18876, 18899), 'mpl_toolkits.axes_grid1.make_axes_locatable', 'make_axes_locatable', (['ax'], {}), '(ax)\n', (18895, 18899), False, 'from mpl_toolkits.axes_grid1 import make_axes_locatable\n'), ((18980, 19005), 'matplotlib.pyplot.colorbar', 'plt.colorbar', (['im'], {'cax': 'cax'}), '(im, cax=cax)\n', (18992, 19005), True, 'import matplotlib.pyplot as plt\n'), ((19387, 19410), 'mpl_toolkits.axes_grid1.make_axes_locatable', 'make_axes_locatable', (['ax'], {}), '(ax)\n', (19406, 19410), False, 'from mpl_toolkits.axes_grid1 import make_axes_locatable\n'), ((19491, 19516), 'matplotlib.pyplot.colorbar', 'plt.colorbar', (['im'], {'cax': 'cax'}), '(im, cax=cax)\n', (19503, 19516), True, 'import matplotlib.pyplot as plt\n'), ((19663, 19713), 'matplotlib.pyplot.savefig', 'plt.savefig', (['outfile'], {'bbox_inches': '"""tight"""', 'dpi': '(300)'}), "(outfile, bbox_inches='tight', dpi=300)\n", (19674, 19713), True, 'import matplotlib.pyplot as plt\n'), ((19752, 19762), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (19760, 19762), True, 'import matplotlib.pyplot as plt\n'), ((19802, 19813), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (19811, 19813), True, 'import matplotlib.pyplot as plt\n'), ((4311, 4351), 'numpy.random.rand', 'np.random.rand', (['self.nwalkers', 'self.ndim'], {}), '(self.nwalkers, self.ndim)\n', (4325, 4351), True, 'import numpy as np\n'), ((5186, 5212), 'numpy.where', 'np.where', (['(outliers == True)'], {}), '(outliers == True)\n', (5194, 5212), True, 'import numpy as np\n'), ((8507, 8543), 'numpy.percentile', 'np.percentile', (['chain[:, i]', '[16, 84]'], {}), '(chain[:, i], [16, 84])\n', (8520, 8543), True, 'import numpy as np\n'), ((9489, 9539), 'matplotlib.pyplot.axhline', 'plt.axhline', (['reference[indx]'], {'lw': '(2)', 'c': '"""k"""', 'ls': '"""--"""'}), "(reference[indx], lw=2, c='k', ls='--')\n", (9500, 9539), True, 'import matplotlib.pyplot as plt\n'), ((3645, 3675), 'numpy.random.randn', 'np.random.randn', (['self.nwalkers'], {}), '(self.nwalkers)\n', (3660, 3675), True, 'import numpy as np\n'), ((12871, 12880), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '()\n', (12878, 12880), True, 'import matplotlib.pyplot as plt\n'), ((19152, 19168), 'numpy.min', 'np.min', (['residual'], {}), '(residual)\n', (19158, 19168), True, 'import numpy as np\n'), ((19204, 19220), 'numpy.max', 'np.max', (['residual'], {}), '(residual)\n', (19210, 19220), True, 'import numpy as np\n'), ((19559, 19568), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '()\n', (19566, 19568), True, 'import matplotlib.pyplot as plt\n'), ((3999, 4025), 'numpy.random.randn', 'np.random.randn', (['Noutliers'], {}), '(Noutliers)\n', (4014, 4025), True, 'import numpy as np\n'), ((15795, 15812), 'numpy.min', 'np.min', (['images[i]'], {}), '(images[i])\n', (15801, 15812), True, 'import numpy as np\n'), ((15853, 15870), 'numpy.max', 'np.max', (['images[i]'], {}), '(images[i])\n', (15859, 15870), True, 'import numpy as np\n')]
|
"""
Aurora is using axelrod_aurora_test1 to reproduce Table 2 from the Axelrod paper.
"""
import sys
import dworp
import igraph
import logging
import numpy as np
import axelrod_aurora_test1
import pdb
import pickle as pkl
import time
# --- Constant Parameters ---
xdim = 10
ydim = 10
n_tsteps = 8000 # because we cycle through the 100 sites each time, this represents n_tsteps*100 events
features_list = [5,10,15]
numtraits_list = [5,10,15]
N = 20 # Number of trials to average over
printby = 1000
checkby = 100
logging.basicConfig(level=logging.WARN)
outfilename = "table2_sim_mean_output_N%d.txt" % (N)
outfilename_med = "table2_sim_med_output_N%d.txt" % (N)
outfilename_pkl = "table2_simout_N%d.pkl" % (N)
# --- Setting the Random Seed ---
#toplevelseed = 348675
toplevelseed = 8675
np.random.seed(toplevelseed)
seedlist = [np.random.randint(1, 2**31) for _ in range(0, len(features_list) * len(numtraits_list) * N)]
# if you use np.random.randint(1, 2**32 -2), the script will send an error on some systems. I think 2**31 is the max
# --- Run the Simulations ---
print("begin simulation")
start_time = time.clock()
allresults = np.zeros([len(features_list),len(numtraits_list),N])
alltimings = np.zeros([len(features_list),len(numtraits_list),N])
place = 0
g = igraph.Graph.Lattice([xdim,ydim], nei=1, directed=False, circular=False)
env = axelrod_aurora_test1.AxelrodEnvironment(g)
observer = axelrod_aurora_test1.AxelrodObserver(printby)
term = axelrod_aurora_test1.AxelrodTerminator(checkby)
for i in range(0,len(features_list)):
num_features = features_list[i]
for j in range(0,len(numtraits_list)):
num_traits = numtraits_list[j]
for k in range(0,N):
this_s_time = time.clock()
# get this simulation's seed
curseed = seedlist[place]
place = place + 1
np.random.seed(curseed)
timeobj = dworp.BasicTime(n_tsteps)
# reset all the agent states
agents = [axelrod_aurora_test1.Site(v,num_features,num_traits) for v in g.vs]
# ensuring reproducibility by setting the seed
scheduler = dworp.RandomOrderScheduler(np.random.RandomState(curseed+1))
sim = dworp.TwoStageSimulation(agents, env, timeobj, scheduler, observer,terminator=term)
sim.run()
lastcount = observer.computenumregions(0,agents,env)
allresults[i,j,k] = lastcount
this_e_time = time.clock()
alltimings[i,j,k] = this_e_time - this_s_time
try:
end_time = time.clock()
sim_time_minutes = float(end_time-start_time)/60.0
print("simulation finished after %.2f minutes" % (sim_time_minutes))
except:
print("error here")
pdb.set_trace()
meanresults = np.zeros([len(features_list),len(numtraits_list)])
medianresults = np.zeros([len(features_list),len(numtraits_list)])
meantimingresults = np.zeros([len(features_list),len(numtraits_list)])
mediantimingresults = np.zeros([len(features_list),len(numtraits_list)])
for i in range(0,len(features_list)):
for j in range(0,len(numtraits_list)):
thislistresults = allresults[i,j,:]
meanresults[i,j] = np.mean(thislistresults)
medianresults[i,j] = np.median(thislistresults)
thislistresultstime = alltimings[i,j,:]
meantimingresults[i,j] = np.mean(thislistresultstime)
mediantimingresults[i,j] = np.median(thislistresultstime)
# --- Save results to a pickle file ---
resultstuple = (allresults,meanresults,medianresults,xdim,ydim,n_tsteps,features_list,numtraits_list,N,
toplevelseed,sim_time_minutes,alltimings,meantimingresults,mediantimingresults)
pkl.dump( resultstuple, open( outfilename_pkl, "wb" ) )
#partresultstuple = (allresults,xdim,ydim,n_tsteps,features_list,numtraits_list,N,toplevelseed,sim_time_minutes)
#pkl.dump( partresultstuple, open( "partial_"+outfilename_pkl, "wb" ) )
# --- Save results to text files ---
with open(outfilename,"w") as f:
f.write(" ")
for i in range(0,len(numtraits_list)):
f.write(",%d traits" % (numtraits_list[i]))
f.write("\n")
for i in range(0,len(features_list)):
f.write("%d" % (features_list[i]))
for j in range(0,len(numtraits_list)):
f.write(",%.2f" % (meanresults[i,j]))
f.write("\n")
f.close()
with open(outfilename_med,"w") as f:
f.write(" ")
for i in range(0,len(numtraits_list)):
f.write(",%d traits" % (numtraits_list[i]))
f.write("\n")
for i in range(0,len(features_list)):
f.write("%d" % (features_list[i]))
for j in range(0,len(numtraits_list)):
f.write(",%.2f" % (medianresults[i,j]))
f.write("\n")
f.close()
print("done saving files")
|
[
"numpy.random.seed",
"axelrod_aurora_test1.AxelrodTerminator",
"logging.basicConfig",
"dworp.TwoStageSimulation",
"numpy.median",
"time.clock",
"axelrod_aurora_test1.AxelrodEnvironment",
"numpy.random.RandomState",
"numpy.random.randint",
"numpy.mean",
"pdb.set_trace",
"axelrod_aurora_test1.AxelrodObserver",
"axelrod_aurora_test1.Site",
"igraph.Graph.Lattice",
"dworp.BasicTime"
] |
[((516, 555), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.WARN'}), '(level=logging.WARN)\n', (535, 555), False, 'import logging\n'), ((793, 821), 'numpy.random.seed', 'np.random.seed', (['toplevelseed'], {}), '(toplevelseed)\n', (807, 821), True, 'import numpy as np\n'), ((1114, 1126), 'time.clock', 'time.clock', ([], {}), '()\n', (1124, 1126), False, 'import time\n'), ((1273, 1346), 'igraph.Graph.Lattice', 'igraph.Graph.Lattice', (['[xdim, ydim]'], {'nei': '(1)', 'directed': '(False)', 'circular': '(False)'}), '([xdim, ydim], nei=1, directed=False, circular=False)\n', (1293, 1346), False, 'import igraph\n'), ((1352, 1394), 'axelrod_aurora_test1.AxelrodEnvironment', 'axelrod_aurora_test1.AxelrodEnvironment', (['g'], {}), '(g)\n', (1391, 1394), False, 'import axelrod_aurora_test1\n'), ((1406, 1451), 'axelrod_aurora_test1.AxelrodObserver', 'axelrod_aurora_test1.AxelrodObserver', (['printby'], {}), '(printby)\n', (1442, 1451), False, 'import axelrod_aurora_test1\n'), ((1459, 1506), 'axelrod_aurora_test1.AxelrodTerminator', 'axelrod_aurora_test1.AxelrodTerminator', (['checkby'], {}), '(checkby)\n', (1497, 1506), False, 'import axelrod_aurora_test1\n'), ((834, 863), 'numpy.random.randint', 'np.random.randint', (['(1)', '(2 ** 31)'], {}), '(1, 2 ** 31)\n', (851, 863), True, 'import numpy as np\n'), ((2547, 2559), 'time.clock', 'time.clock', ([], {}), '()\n', (2557, 2559), False, 'import time\n'), ((2724, 2739), 'pdb.set_trace', 'pdb.set_trace', ([], {}), '()\n', (2737, 2739), False, 'import pdb\n'), ((3169, 3193), 'numpy.mean', 'np.mean', (['thislistresults'], {}), '(thislistresults)\n', (3176, 3193), True, 'import numpy as np\n'), ((3223, 3249), 'numpy.median', 'np.median', (['thislistresults'], {}), '(thislistresults)\n', (3232, 3249), True, 'import numpy as np\n'), ((3331, 3359), 'numpy.mean', 'np.mean', (['thislistresultstime'], {}), '(thislistresultstime)\n', (3338, 3359), True, 'import numpy as np\n'), ((3395, 3425), 'numpy.median', 'np.median', (['thislistresultstime'], {}), '(thislistresultstime)\n', (3404, 3425), True, 'import numpy as np\n'), ((1718, 1730), 'time.clock', 'time.clock', ([], {}), '()\n', (1728, 1730), False, 'import time\n'), ((1852, 1875), 'numpy.random.seed', 'np.random.seed', (['curseed'], {}), '(curseed)\n', (1866, 1875), True, 'import numpy as np\n'), ((1898, 1923), 'dworp.BasicTime', 'dworp.BasicTime', (['n_tsteps'], {}), '(n_tsteps)\n', (1913, 1923), False, 'import dworp\n'), ((2217, 2305), 'dworp.TwoStageSimulation', 'dworp.TwoStageSimulation', (['agents', 'env', 'timeobj', 'scheduler', 'observer'], {'terminator': 'term'}), '(agents, env, timeobj, scheduler, observer,\n terminator=term)\n', (2241, 2305), False, 'import dworp\n'), ((2456, 2468), 'time.clock', 'time.clock', ([], {}), '()\n', (2466, 2468), False, 'import time\n'), ((1987, 2041), 'axelrod_aurora_test1.Site', 'axelrod_aurora_test1.Site', (['v', 'num_features', 'num_traits'], {}), '(v, num_features, num_traits)\n', (2012, 2041), False, 'import axelrod_aurora_test1\n'), ((2165, 2199), 'numpy.random.RandomState', 'np.random.RandomState', (['(curseed + 1)'], {}), '(curseed + 1)\n', (2186, 2199), True, 'import numpy as np\n')]
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
from scipy import integrate
import sympy as sp
sp.init_printing(use_unicode=True)
def stopFunCombined(t, s, lst, events, out=[]):
""" Universal event detection function that handles multiple events.
Intended for scipy.integrate.ode solout application. Provides
termination of integration process when first terminate event occur.
This happens when independent variable associated with this event
goes through defined stopval value in specified direction.
Uses almost the same ideas as in matlab event functions.
Can be used for gathering all intergation steps.
Shoudn't be called directly but through scipy.integrate.ode.
Parameters
----------
t : scalar
Dimensionless time (same as angle of system rotation)
s : array_like with 6 components
State vector of massless spacecraft (x,y,z,vx,vy,vz)
lst : list
Every call of this function put [*s,t,*cur_ivs] into lst, where
t - time (at current integration step),
s - spacecraft state vector at time t,
cur_ivs - list of independent variable values at time t.
events : list of dicts
Each dict consists of necessary information for event:
{
ivar : function(t, s, **kwargs)
Should return independent variable from spacecraft state vector.
stopval : double
stopFun return -1 if independent variable crosses stopval value in
right direction
direction : integer
1 : stops integration when independent variable crosses stopval value
from NEGATIVE to POSITIVE values
-1 : stops integration when independent variable crosses stopval value
from POSITIVE to NEGATIVE values
0 : in both cases (like 'direction' argument in matlab's event functions)
isterminal : integer, bool
Terminal event terminates integration process when event occurs.
corr : bool
Determines whether it is necessary to adjust last state vector or not
count : int
Number of event occasions.
If count == 0
Then event doesnt occur (turned off event).
If count == -1
Then (possibly) unlimited number of events can occur.
If isterminal == True
If count == 1
Then only one terminal event (possibly) occur.
If count > 1
Then non-terminal event (possibly) triggers count-1
times and one terminal event (possibly) occur.
If isterminal == False
Event (possibly) occurs count times.
kwargs : dict
Other parameters for ivar function
}
out : list
If non-terminal event(s) occur in [ti-1, ti] interval, 'out' will
be filled with [ei, ci, np.array([*s,te,*cur_ivs])], where:
ei - event index in events list,
ci - event triggered ci times,
te - time of event,
s - state vector at te,
cur_ivs - values of independent variables at te.
Returns
-------
-1 : scalar
When there are terminal event in event list and independent variable \
assiciated with this event goes through defined stopval value in \
specified direction. Will be treated by scipy.integrate.ode as it \
should stop integration process.
0 : scalar
Otherwise. Will be treated by scipy.integrate.ode as it\
should continue integration process.
"""
terminal = False
cur_ivs = []
sn = s.shape[0] + 1
for event in events:
if(type(event)!=str):
ivar = event.ivar
cur_iv = ivar(t, s)
cur_ivs.append(cur_iv)
if not lst: # fast way to check if lst is empty
cur_cnt = []
for event in events:
if(type(event)!=str):
cur_cnt.append(event.count)
if not out:
out.append(cur_cnt)
else:
out[0] = cur_cnt
lst.append([*s,t,*cur_ivs])
return 0
lst.append([*s,t,*cur_ivs])
cur_cnt = out[0]
for i, event in enumerate(events):
if(type(events[i])!=str):
stopval=event.stopval
direction=event.direction
corr=event.corr
isterminal=event.isterminal
init_cnt=event.count
cur_iv = cur_ivs[i]
prev_iv = lst[-2][sn+i]
f1 = (prev_iv < stopval) and (cur_iv > stopval) and ((direction == 1) or (direction == 0))
f2 = (prev_iv > stopval) and (cur_iv < stopval) and ((direction == -1) or (direction == 0))
if (f1 or f2) and ((cur_cnt[i] == -1) or (cur_cnt[i] > 0)):
if cur_cnt[i] > 0:
cur_cnt[i] -= 1
out.append([i, # event index
(-1 if cur_cnt[i]==-1 else init_cnt-cur_cnt[i]), # event trigger counter
lst[-2].copy(), # state before event
lst[-1].copy(), # state after event
corr, # if correction is needed
isterminal]) # if event is terminal
if isterminal and ((cur_cnt[i] == -1) or (cur_cnt[i] == 0)):
terminal = True
if terminal:
return -1
return 0
class base_integrator_tool:
"""A class for integrator"""
def __init__(self, rtol, nmax, method=None, stopf=None):
""" Set parameters for integrator int_param for scypy.integrate.
Parameters
----------
Rtol: double
tolerance
nmax: integer
maximum number of steps for integration
method:
integration method
"""
self.rtol = float(rtol)
self.nmax = float(nmax)
self.method = method
self.atol = float(rtol)
self.stopf = stopf
def integrate_ode(self, model, s0, tspan, events=[], out=[]):
return None
class integrator_tool(base_integrator_tool):
def integrate_ode(self, model, s0, tspan, events=[], out=[]):
"""
Integrate a state vector for preset time
Parameters
----------
Model: class model object
s0 : array_like with 6 components
Initial spacecraft state vector)
tspan: scalar
integration time
Returns
-------
lst: array
state vectors
"""
retarr=True
mu = model.mu1
prop = integrate.ode(model.equation)
if self.method != None:
method = self.method
prop.set_integrator(method, method=self.method, rtol=self.rtol)
else:
prop.set_integrator('dopri5')
prop.set_initial_value(s0, tspan[0])
prop.set_f_params(*[mu])
lst = []
if self.stopf!=None:
prop.set_solout(lambda t, s: self.int_param['stopf'](t, s, lst, events, out))
else:
prop.set_solout(lambda t, s: stopFunCombined(t, s, lst, events, out))
prop.integrate(tspan[1])
del prop
if len(out) > 0:
cor_out = self.correctEvents(model, events, out, None, sn=len(s0))
out.clear()
out.extend(cor_out)
if retarr:
return np.asarray(lst)
def correctEvents(self, model, events, evout, prop, sn):
"""Calculate corrected event states using newton method with
same tolerance as integrator used.
Parameters
----------
events : list of events
See stopFunCombined for description
evout : list (generated by stopFunCombined)
evout elements are lists where (by index):
0 - event index
1 - event trigger count
2 - state before event
3 - state after event
4 - correction flag
5 - terminal flag
sn : integer
State vector length
model : class model
"""
out = []
tol=1e-14
maxiter = 50
for ev in evout[1:]:
if ev[4] == False:
out.append([ev[0], ev[1], ev[3][:sn+1], ev[5]])
continue
t, s = self.brent(model, events[ev[0]], ev[2][sn], ev[3][sn], ev[2][:sn], tol=tol, maxiter=maxiter)
out.append([ev[0], ev[1], list(s)+[t], ev[5]])
return out
def brent(self, model, event, t0, t1, s0, tol=1e-12, maxiter=50, debug=False):
"""function for numerical Brent method"""
import scipy.optimize
import math
ivar = event.ivar
stopval = event.stopval
s_opt = [0]
def fopt(t, s0, t0):
if t == t0:
s = s0.copy()
else:
s = model.integrator.integrate_ode(model, s0, [t0, t])[-1, :6]
s_opt[0] = s
fval = ivar(t, s) - stopval
return math.fabs(fval)
t_opt = scipy.optimize.brent(fopt, args=(s0, t0), brack=(t0, t1), tol=tol)
return t_opt, s_opt[0]
|
[
"numpy.asarray",
"sympy.init_printing",
"math.fabs",
"scipy.integrate.ode"
] |
[((114, 148), 'sympy.init_printing', 'sp.init_printing', ([], {'use_unicode': '(True)'}), '(use_unicode=True)\n', (130, 148), True, 'import sympy as sp\n'), ((6746, 6775), 'scipy.integrate.ode', 'integrate.ode', (['model.equation'], {}), '(model.equation)\n', (6759, 6775), False, 'from scipy import integrate\n'), ((7472, 7487), 'numpy.asarray', 'np.asarray', (['lst'], {}), '(lst)\n', (7482, 7487), True, 'import numpy as np\n'), ((9049, 9064), 'math.fabs', 'math.fabs', (['fval'], {}), '(fval)\n', (9058, 9064), False, 'import math\n')]
|
from __future__ import division, print_function
import sys, os, glob, time, warnings, gc
import numpy as np
# import matplotlib
# matplotlib.use("Agg")
# import matplotlib.pyplot as plt
from astropy.table import Table, vstack, hstack, join
import fitsio
# from astropy.io import fits
columns = ['SGA_ID', 'REF_CAT', 'GALAXY', 'RA', 'DEC', 'DIAM']
ee = Table(fitsio.read('/global/cfs/cdirs/cosmo/data/legacysurvey/dr9/masking/SGA-ellipse-v3.0.kd.fits', columns=columns))
nn = Table(fitsio.read('/global/cfs/cdirs/cosmo/staging/largegalaxies/v3.0/SGA-ellipse-v3.0.fits', columns=columns))
old = ee[ee['SGA_ID'] > -1]
new = nn[nn['SGA_ID'] > -1]
old = old[np.argsort(old['SGA_ID'])]
new = new[np.argsort(new['SGA_ID'])]
ww = (old['REF_CAT'] == '') * (new['REF_CAT'] == 'L3')
cat = new[ww]['SGA_ID', 'GALAXY', 'RA', 'DEC', 'DIAM']
t = cat[['RA', 'DEC']]
t['radius'] = cat['DIAM']/2. * 60.
# t.write('/global/u2/r/rongpu/temp/missing_sga.fits', overwrite=True)
for index in range(len(t)):
print('{}, {}, {}'.format(t['RA'][index], t['DEC'][index], t['radius'][index]))
|
[
"fitsio.read",
"numpy.argsort"
] |
[((361, 481), 'fitsio.read', 'fitsio.read', (['"""/global/cfs/cdirs/cosmo/data/legacysurvey/dr9/masking/SGA-ellipse-v3.0.kd.fits"""'], {'columns': 'columns'}), "(\n '/global/cfs/cdirs/cosmo/data/legacysurvey/dr9/masking/SGA-ellipse-v3.0.kd.fits'\n , columns=columns)\n", (372, 481), False, 'import fitsio\n'), ((484, 597), 'fitsio.read', 'fitsio.read', (['"""/global/cfs/cdirs/cosmo/staging/largegalaxies/v3.0/SGA-ellipse-v3.0.fits"""'], {'columns': 'columns'}), "(\n '/global/cfs/cdirs/cosmo/staging/largegalaxies/v3.0/SGA-ellipse-v3.0.fits',\n columns=columns)\n", (495, 597), False, 'import fitsio\n'), ((656, 681), 'numpy.argsort', 'np.argsort', (["old['SGA_ID']"], {}), "(old['SGA_ID'])\n", (666, 681), True, 'import numpy as np\n'), ((693, 718), 'numpy.argsort', 'np.argsort', (["new['SGA_ID']"], {}), "(new['SGA_ID'])\n", (703, 718), True, 'import numpy as np\n')]
|
from sklearn.metrics import classification_report, accuracy_score
from collections import OrderedDict
from privacy.analysis.rdp_accountant import compute_rdp
from privacy.analysis.rdp_accountant import get_privacy_spent
from privacy.optimizers import dp_optimizer
import tensorflow as tf
import numpy as np
import os
import argparse
LOGGING = False # enables tf.train.ProfilerHook (see use below)
LOG_DIR = 'log'
# Compatibility with tf 1 and 2 APIs
try:
AdamOptimizer = tf.train.AdamOptimizer
except: # pylint: disable=bare-except
AdamOptimizer = tf.optimizers.Adam # pylint: disable=invalid-name
# optimal sigma values for RDP mechanism for the default batch size, training set size, delta and sampling ratio.
noise_multiplier = {0.01:525, 0.05:150, 0.1:70, 0.5:13.8, 1:7, 5:1.669, 10:1.056, 50:0.551, 100:0.445, 500:0.275, 1000:0.219}
def get_predictions(predictions):
pred_y, pred_scores = [], []
val = next(predictions, None)
while val is not None:
pred_y.append(val['classes'])
pred_scores.append(val['probabilities'])
val = next(predictions, None)
return np.array(pred_y), np.matrix(pred_scores)
def get_model(features, labels, mode, params):
n, n_in, n_hidden, n_out, non_linearity, model, privacy, dp, epsilon, delta, batch_size, learning_rate, l2_ratio, epochs = params
if model == 'nn':
#print('Using neural network...')
input_layer = tf.reshape(features['x'], [-1, n_in])
y = tf.keras.layers.Dense(n_hidden, activation=non_linearity, kernel_regularizer=tf.keras.regularizers.l2(l2_ratio)).apply(input_layer)
y = tf.keras.layers.Dense(n_hidden, activation=non_linearity, kernel_regularizer=tf.keras.regularizers.l2(l2_ratio)).apply(y)
logits = tf.keras.layers.Dense(n_out, activation=tf.nn.softmax, kernel_regularizer=tf.keras.regularizers.l2(l2_ratio)).apply(y)
else:
#print('Using softmax regression...')
input_layer = tf.reshape(features['x'], [-1, n_in])
logits = tf.keras.layers.Dense(n_out, activation=tf.nn.softmax, kernel_regularizer=tf.keras.regularizers.l2(l2_ratio)).apply(input_layer)
predictions = {
"classes": tf.argmax(input=logits, axis=1),
#"probabilities": tf.nn.softmax(logits, name="softmax_tensor")
"probabilities": logits
}
if mode == tf.estimator.ModeKeys.PREDICT:
return tf.estimator.EstimatorSpec(mode=mode,
predictions=predictions)
vector_loss = tf.keras.losses.sparse_categorical_crossentropy(labels, logits)
scalar_loss = tf.reduce_mean(vector_loss)
if mode == tf.estimator.ModeKeys.TRAIN:
if privacy == 'grad_pert':
C = 1 # Clipping Threshold
sigma = 0.
if dp == 'adv_cmp':
sigma = np.sqrt(epochs * np.log(2.5 * epochs / delta)) * (np.sqrt(np.log(2 / delta) + 2 * epsilon) + np.sqrt(np.log(2 / delta))) / epsilon # Adv Comp
elif dp == 'zcdp':
sigma = np.sqrt(epochs / 2) * (np.sqrt(np.log(1 / delta) + epsilon) + np.sqrt(np.log(1 / delta))) / epsilon # zCDP
elif dp == 'rdp':
sigma = noise_multiplier[epsilon]
elif dp == 'dp':
sigma = epochs * np.sqrt(2 * np.log(1.25 * epochs / delta)) / epsilon # DP
print(sigma)
optimizer = dp_optimizer.DPAdamGaussianOptimizer(
l2_norm_clip=C,
noise_multiplier=sigma,
num_microbatches=batch_size,
learning_rate=learning_rate,
ledger=None)
opt_loss = vector_loss
else:
optimizer = AdamOptimizer(learning_rate=learning_rate)
opt_loss = scalar_loss
global_step = tf.train.get_global_step()
train_op = optimizer.minimize(loss=opt_loss, global_step=global_step)
return tf.estimator.EstimatorSpec(mode=mode,
loss=scalar_loss,
train_op=train_op)
elif mode == tf.estimator.ModeKeys.EVAL:
eval_metric_ops = {
'accuracy':
tf.metrics.accuracy(
labels=labels,
predictions=predictions["classes"])
}
return tf.estimator.EstimatorSpec(mode=mode,
loss=scalar_loss,
eval_metric_ops=eval_metric_ops)
def train(dataset, n_hidden=50, batch_size=100, epochs=100, learning_rate=0.01, model='nn', l2_ratio=1e-7,
silent=True, non_linearity='relu', privacy='no_privacy', dp = 'dp', epsilon=0.5, delta=1e-5):
train_x, train_y, test_x, test_y = dataset
n_in = train_x.shape[1]
n_out = len(np.unique(train_y))
if batch_size > len(train_y):
batch_size = len(train_y)
classifier = tf.estimator.Estimator(
model_fn=get_model,
params = [
train_x.shape[0],
n_in,
n_hidden,
n_out,
non_linearity,
model,
privacy,
dp,
epsilon,
delta,
batch_size,
learning_rate,
l2_ratio,
epochs
])
train_input_fn = tf.estimator.inputs.numpy_input_fn(
x={'x': train_x},
y=train_y,
batch_size=batch_size,
num_epochs=epochs,
shuffle=True)
test_eval_input_fn = tf.estimator.inputs.numpy_input_fn(
x={'x': test_x},
y=test_y,
num_epochs=1,
shuffle=False)
train_eval_input_fn = tf.estimator.inputs.numpy_input_fn(
x={'x': train_x},
y=train_y,
num_epochs=1,
shuffle=False)
pred_input_fn = tf.estimator.inputs.numpy_input_fn(
x={'x': test_x},
num_epochs=1,
shuffle=False)
steps_per_epoch = train_x.shape[0] // batch_size
orders = [1 + x / 100.0 for x in range(1, 1000)] + list(range(12, 1200))
rdp = compute_rdp(batch_size / train_x.shape[0], noise_multiplier[epsilon], epochs * steps_per_epoch, orders)
eps, _, opt_order = get_privacy_spent(orders, rdp, target_delta=delta)
print('\nFor delta= %.5f' % delta, ',the epsilon is: %.2f\n' % eps)
if not os.path.exists(LOG_DIR):
os.makedirs(LOG_DIR)
for epoch in range(1, epochs + 1):
hooks = []
if LOGGING:
hooks.append(tf.train.ProfilerHook(
output_dir=LOG_DIR,
save_steps=30))
# This hook will save traces of what tensorflow is doing
# during the training of each model. View the combined trace
# by running `combine_traces.py`
classifier.train(input_fn=train_input_fn,
steps=steps_per_epoch,
hooks=hooks)
if not silent:
eval_results = classifier.evaluate(input_fn=train_eval_input_fn)
print('Train loss after %d epochs is: %.3f' % (epoch, eval_results['loss']))
eval_results = classifier.evaluate(input_fn=train_eval_input_fn)
train_acc = eval_results['accuracy']
train_loss = eval_results['loss']
if not silent:
print('Train accuracy is: %.3f' % (train_acc))
eval_results = classifier.evaluate(input_fn=test_eval_input_fn)
test_acc = eval_results['accuracy']
if not silent:
print('Test accuracy is: %.3f' % (test_acc))
predictions = classifier.predict(input_fn=pred_input_fn)
pred_y, pred_scores = get_predictions(predictions)
return classifier, pred_y, pred_scores, train_loss, train_acc, test_acc
def load_dataset(train_feat, train_label, test_feat=None, test_label=None):
train_x = np.genfromtxt(train_feat, delimiter=',', dtype='float32')
train_y = np.genfromtxt(train_label, dtype='int32')
min_y = np.min(train_y)
train_y -= min_y
if test_feat is not None and test_label is not None:
test_x = np.genfromtxt(train_feat, delimiter=',', dtype='float32')
test_y = np.genfromtxt(train_label, dtype='int32')
test_y -= min_y
else:
test_x = None
test_y = None
return train_x, train_y, test_x, test_y
def main():
parser = argparse.ArgumentParser()
parser.add_argument('train_feat', type=str)
parser.add_argument('train_label', type=str)
parser.add_argument('--test_feat', type=str, default=None)
parser.add_argument('--test_label', type=str, default=None)
parser.add_argument('--model', type=str, default='nn')
parser.add_argument('--learning_rate', type=float, default=0.01)
parser.add_argument('--batch_size', type=int, default=100)
parser.add_argument('--n_hidden', type=int, default=50)
parser.add_argument('--epochs', type=int, default=100)
args = parser.parse_args()
print(vars(args))
dataset = load_dataset(args.train_feat, args.train_label, args.test_feat, args.train_label)
train(dataset,
model=args.model,
learning_rate=args.learning_rate,
batch_size=args.batch_size,
n_hidden=args.n_hidden,
epochs=args.epochs)
if __name__ == '__main__':
main()
|
[
"argparse.ArgumentParser",
"tensorflow.reshape",
"privacy.optimizers.dp_optimizer.DPAdamGaussianOptimizer",
"tensorflow.estimator.Estimator",
"numpy.unique",
"tensorflow.keras.regularizers.l2",
"tensorflow.metrics.accuracy",
"privacy.analysis.rdp_accountant.get_privacy_spent",
"os.path.exists",
"numpy.genfromtxt",
"tensorflow.keras.losses.sparse_categorical_crossentropy",
"tensorflow.train.get_global_step",
"tensorflow.reduce_mean",
"numpy.min",
"tensorflow.train.ProfilerHook",
"tensorflow.estimator.EstimatorSpec",
"numpy.matrix",
"os.makedirs",
"numpy.log",
"tensorflow.argmax",
"privacy.analysis.rdp_accountant.compute_rdp",
"numpy.array",
"tensorflow.estimator.inputs.numpy_input_fn",
"numpy.sqrt"
] |
[((2559, 2622), 'tensorflow.keras.losses.sparse_categorical_crossentropy', 'tf.keras.losses.sparse_categorical_crossentropy', (['labels', 'logits'], {}), '(labels, logits)\n', (2606, 2622), True, 'import tensorflow as tf\n'), ((2642, 2669), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['vector_loss'], {}), '(vector_loss)\n', (2656, 2669), True, 'import tensorflow as tf\n'), ((5068, 5264), 'tensorflow.estimator.Estimator', 'tf.estimator.Estimator', ([], {'model_fn': 'get_model', 'params': '[train_x.shape[0], n_in, n_hidden, n_out, non_linearity, model, privacy, dp,\n epsilon, delta, batch_size, learning_rate, l2_ratio, epochs]'}), '(model_fn=get_model, params=[train_x.shape[0], n_in,\n n_hidden, n_out, non_linearity, model, privacy, dp, epsilon, delta,\n batch_size, learning_rate, l2_ratio, epochs])\n', (5090, 5264), True, 'import tensorflow as tf\n'), ((5563, 5687), 'tensorflow.estimator.inputs.numpy_input_fn', 'tf.estimator.inputs.numpy_input_fn', ([], {'x': "{'x': train_x}", 'y': 'train_y', 'batch_size': 'batch_size', 'num_epochs': 'epochs', 'shuffle': '(True)'}), "(x={'x': train_x}, y=train_y, batch_size=\n batch_size, num_epochs=epochs, shuffle=True)\n", (5597, 5687), True, 'import tensorflow as tf\n'), ((5755, 5849), 'tensorflow.estimator.inputs.numpy_input_fn', 'tf.estimator.inputs.numpy_input_fn', ([], {'x': "{'x': test_x}", 'y': 'test_y', 'num_epochs': '(1)', 'shuffle': '(False)'}), "(x={'x': test_x}, y=test_y, num_epochs=1,\n shuffle=False)\n", (5789, 5849), True, 'import tensorflow as tf\n'), ((5910, 6007), 'tensorflow.estimator.inputs.numpy_input_fn', 'tf.estimator.inputs.numpy_input_fn', ([], {'x': "{'x': train_x}", 'y': 'train_y', 'num_epochs': '(1)', 'shuffle': '(False)'}), "(x={'x': train_x}, y=train_y, num_epochs=\n 1, shuffle=False)\n", (5944, 6007), True, 'import tensorflow as tf\n'), ((6061, 6146), 'tensorflow.estimator.inputs.numpy_input_fn', 'tf.estimator.inputs.numpy_input_fn', ([], {'x': "{'x': test_x}", 'num_epochs': '(1)', 'shuffle': '(False)'}), "(x={'x': test_x}, num_epochs=1, shuffle=False\n )\n", (6095, 6146), True, 'import tensorflow as tf\n'), ((6315, 6423), 'privacy.analysis.rdp_accountant.compute_rdp', 'compute_rdp', (['(batch_size / train_x.shape[0])', 'noise_multiplier[epsilon]', '(epochs * steps_per_epoch)', 'orders'], {}), '(batch_size / train_x.shape[0], noise_multiplier[epsilon], \n epochs * steps_per_epoch, orders)\n', (6326, 6423), False, 'from privacy.analysis.rdp_accountant import compute_rdp\n'), ((6444, 6494), 'privacy.analysis.rdp_accountant.get_privacy_spent', 'get_privacy_spent', (['orders', 'rdp'], {'target_delta': 'delta'}), '(orders, rdp, target_delta=delta)\n', (6461, 6494), False, 'from privacy.analysis.rdp_accountant import get_privacy_spent\n'), ((8051, 8108), 'numpy.genfromtxt', 'np.genfromtxt', (['train_feat'], {'delimiter': '""","""', 'dtype': '"""float32"""'}), "(train_feat, delimiter=',', dtype='float32')\n", (8064, 8108), True, 'import numpy as np\n'), ((8124, 8165), 'numpy.genfromtxt', 'np.genfromtxt', (['train_label'], {'dtype': '"""int32"""'}), "(train_label, dtype='int32')\n", (8137, 8165), True, 'import numpy as np\n'), ((8179, 8194), 'numpy.min', 'np.min', (['train_y'], {}), '(train_y)\n', (8185, 8194), True, 'import numpy as np\n'), ((8569, 8594), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (8592, 8594), False, 'import argparse\n'), ((1143, 1159), 'numpy.array', 'np.array', (['pred_y'], {}), '(pred_y)\n', (1151, 1159), True, 'import numpy as np\n'), ((1161, 1183), 'numpy.matrix', 'np.matrix', (['pred_scores'], {}), '(pred_scores)\n', (1170, 1183), True, 'import numpy as np\n'), ((1460, 1497), 'tensorflow.reshape', 'tf.reshape', (["features['x']", '[-1, n_in]'], {}), "(features['x'], [-1, n_in])\n", (1470, 1497), True, 'import tensorflow as tf\n'), ((1996, 2033), 'tensorflow.reshape', 'tf.reshape', (["features['x']", '[-1, n_in]'], {}), "(features['x'], [-1, n_in])\n", (2006, 2033), True, 'import tensorflow as tf\n'), ((2226, 2257), 'tensorflow.argmax', 'tf.argmax', ([], {'input': 'logits', 'axis': '(1)'}), '(input=logits, axis=1)\n', (2235, 2257), True, 'import tensorflow as tf\n'), ((2432, 2494), 'tensorflow.estimator.EstimatorSpec', 'tf.estimator.EstimatorSpec', ([], {'mode': 'mode', 'predictions': 'predictions'}), '(mode=mode, predictions=predictions)\n', (2458, 2494), True, 'import tensorflow as tf\n'), ((3924, 3950), 'tensorflow.train.get_global_step', 'tf.train.get_global_step', ([], {}), '()\n', (3948, 3950), True, 'import tensorflow as tf\n'), ((4046, 4120), 'tensorflow.estimator.EstimatorSpec', 'tf.estimator.EstimatorSpec', ([], {'mode': 'mode', 'loss': 'scalar_loss', 'train_op': 'train_op'}), '(mode=mode, loss=scalar_loss, train_op=train_op)\n', (4072, 4120), True, 'import tensorflow as tf\n'), ((4956, 4974), 'numpy.unique', 'np.unique', (['train_y'], {}), '(train_y)\n', (4965, 4974), True, 'import numpy as np\n'), ((6582, 6605), 'os.path.exists', 'os.path.exists', (['LOG_DIR'], {}), '(LOG_DIR)\n', (6596, 6605), False, 'import os\n'), ((6615, 6635), 'os.makedirs', 'os.makedirs', (['LOG_DIR'], {}), '(LOG_DIR)\n', (6626, 6635), False, 'import os\n'), ((8293, 8350), 'numpy.genfromtxt', 'np.genfromtxt', (['train_feat'], {'delimiter': '""","""', 'dtype': '"""float32"""'}), "(train_feat, delimiter=',', dtype='float32')\n", (8306, 8350), True, 'import numpy as np\n'), ((8369, 8410), 'numpy.genfromtxt', 'np.genfromtxt', (['train_label'], {'dtype': '"""int32"""'}), "(train_label, dtype='int32')\n", (8382, 8410), True, 'import numpy as np\n'), ((3452, 3603), 'privacy.optimizers.dp_optimizer.DPAdamGaussianOptimizer', 'dp_optimizer.DPAdamGaussianOptimizer', ([], {'l2_norm_clip': 'C', 'noise_multiplier': 'sigma', 'num_microbatches': 'batch_size', 'learning_rate': 'learning_rate', 'ledger': 'None'}), '(l2_norm_clip=C, noise_multiplier=sigma,\n num_microbatches=batch_size, learning_rate=learning_rate, ledger=None)\n', (3488, 3603), False, 'from privacy.optimizers import dp_optimizer\n'), ((4470, 4563), 'tensorflow.estimator.EstimatorSpec', 'tf.estimator.EstimatorSpec', ([], {'mode': 'mode', 'loss': 'scalar_loss', 'eval_metric_ops': 'eval_metric_ops'}), '(mode=mode, loss=scalar_loss, eval_metric_ops=\n eval_metric_ops)\n', (4496, 4563), True, 'import tensorflow as tf\n'), ((4326, 4396), 'tensorflow.metrics.accuracy', 'tf.metrics.accuracy', ([], {'labels': 'labels', 'predictions': "predictions['classes']"}), "(labels=labels, predictions=predictions['classes'])\n", (4345, 4396), True, 'import tensorflow as tf\n'), ((6743, 6799), 'tensorflow.train.ProfilerHook', 'tf.train.ProfilerHook', ([], {'output_dir': 'LOG_DIR', 'save_steps': '(30)'}), '(output_dir=LOG_DIR, save_steps=30)\n', (6764, 6799), True, 'import tensorflow as tf\n'), ((1588, 1622), 'tensorflow.keras.regularizers.l2', 'tf.keras.regularizers.l2', (['l2_ratio'], {}), '(l2_ratio)\n', (1612, 1622), True, 'import tensorflow as tf\n'), ((1733, 1767), 'tensorflow.keras.regularizers.l2', 'tf.keras.regularizers.l2', (['l2_ratio'], {}), '(l2_ratio)\n', (1757, 1767), True, 'import tensorflow as tf\n'), ((1870, 1904), 'tensorflow.keras.regularizers.l2', 'tf.keras.regularizers.l2', (['l2_ratio'], {}), '(l2_ratio)\n', (1894, 1904), True, 'import tensorflow as tf\n'), ((2126, 2160), 'tensorflow.keras.regularizers.l2', 'tf.keras.regularizers.l2', (['l2_ratio'], {}), '(l2_ratio)\n', (2150, 2160), True, 'import tensorflow as tf\n'), ((3084, 3103), 'numpy.sqrt', 'np.sqrt', (['(epochs / 2)'], {}), '(epochs / 2)\n', (3091, 3103), True, 'import numpy as np\n'), ((2902, 2930), 'numpy.log', 'np.log', (['(2.5 * epochs / delta)'], {}), '(2.5 * epochs / delta)\n', (2908, 2930), True, 'import numpy as np\n'), ((2986, 3003), 'numpy.log', 'np.log', (['(2 / delta)'], {}), '(2 / delta)\n', (2992, 3003), True, 'import numpy as np\n'), ((2943, 2960), 'numpy.log', 'np.log', (['(2 / delta)'], {}), '(2 / delta)\n', (2949, 2960), True, 'import numpy as np\n'), ((3154, 3171), 'numpy.log', 'np.log', (['(1 / delta)'], {}), '(1 / delta)\n', (3160, 3171), True, 'import numpy as np\n'), ((3115, 3132), 'numpy.log', 'np.log', (['(1 / delta)'], {}), '(1 / delta)\n', (3121, 3132), True, 'import numpy as np\n'), ((3349, 3378), 'numpy.log', 'np.log', (['(1.25 * epochs / delta)'], {}), '(1.25 * epochs / delta)\n', (3355, 3378), True, 'import numpy as np\n')]
|
import re
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from pandas.core.algorithms import mode
import pandas_datareader as web
import datetime as dt
from six import unichr
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras import models
from tensorflow.keras.layers import Dense, Dropout, LSTM
from tensorflow.keras.models import Sequential
from tensorflow.python.keras.engine import sequential
crypto_currency = 'AAPL'
against_currency = 'USD'
start = dt.datetime(2016,1,1)
end = dt.datetime.now()
data = web.DataReader(f'{crypto_currency}', 'yahoo', start, end)
#Prepare Data
scaler = MinMaxScaler(feature_range=(0,1))
scaled_data = scaler.fit_transform(data['Close'].values.reshape(-1,1))
prediction_days = 60
future_day =30
x_train, y_train = [], []
for x in range(prediction_days, len(scaled_data)):
x_train.append(scaled_data[x-prediction_days:x, 0])
y_train.append(scaled_data[x, 0])
x_train, y_train = np.array(x_train), np.array(y_train)
x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))
#Create The Neural Network
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=(x_train.shape[1], 1)))
model.add(Dropout(0.2))
model.add(LSTM(units=50, return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(units=50))
model.add(Dropout(0.2))
model.add(Dense(units=1))
model.compile(optimizer='adam', loss='mean_squared_error')
model.fit(x_train, y_train, epochs=25, batch_size=32)
#Testing The Model
test_start = dt.datetime(2020,1,1)
test_end = dt.datetime.now()
test_data = web.DataReader(f'{crypto_currency}', 'yahoo', test_start, test_end)
actual_prices = test_data['Close'].values
total_dataset = pd.concat((data['Close'], test_data['Close']), axis=0)
model_inputs = total_dataset[len(total_dataset) - len(test_data) - prediction_days:].values
model_inputs = model_inputs.reshape(-1, 1)
model_inputs = scaler.fit_transform(model_inputs)
x_test = []
for x in range(prediction_days, len(model_inputs)):
x_test.append(model_inputs[x-prediction_days:x, 0])
x_test = np.array(x_test)
x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1))
prediction_prices = model.predict(x_test)
prediction_prices = scaler.inverse_transform(prediction_prices)
real_data = [model_inputs[len(model_inputs) + 1 - prediction_days:len(model_inputs) + 1, 0]]
real_data = np.array(real_data)
real_data = np.reshape(real_data, (real_data.shape[0], real_data.shape[1], 1))
prediction = model.predict(real_data)
prediction = scaler.inverse_transform(prediction)
print(prediction)
plt.plot(actual_prices, color='red', label='Actual Prices')
plt.plot(prediction_prices, color='green', label='Actual Prices')
plt.title(f'{crypto_currency} Price Prediction')
plt.xlabel('Time')
plt.ylabel('Price')
plt.legend(loc='upper left')
plt.show()
|
[
"pandas_datareader.DataReader",
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"tensorflow.keras.layers.Dropout",
"tensorflow.keras.layers.Dense",
"matplotlib.pyplot.legend",
"sklearn.preprocessing.MinMaxScaler",
"datetime.datetime",
"numpy.array",
"numpy.reshape",
"tensorflow.keras.models.Sequential",
"tensorflow.keras.layers.LSTM",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"datetime.datetime.now",
"pandas.concat"
] |
[((500, 523), 'datetime.datetime', 'dt.datetime', (['(2016)', '(1)', '(1)'], {}), '(2016, 1, 1)\n', (511, 523), True, 'import datetime as dt\n'), ((528, 545), 'datetime.datetime.now', 'dt.datetime.now', ([], {}), '()\n', (543, 545), True, 'import datetime as dt\n'), ((554, 611), 'pandas_datareader.DataReader', 'web.DataReader', (['f"""{crypto_currency}"""', '"""yahoo"""', 'start', 'end'], {}), "(f'{crypto_currency}', 'yahoo', start, end)\n", (568, 611), True, 'import pandas_datareader as web\n'), ((636, 670), 'sklearn.preprocessing.MinMaxScaler', 'MinMaxScaler', ([], {'feature_range': '(0, 1)'}), '(feature_range=(0, 1))\n', (648, 670), False, 'from sklearn.preprocessing import MinMaxScaler\n'), ((1018, 1078), 'numpy.reshape', 'np.reshape', (['x_train', '(x_train.shape[0], x_train.shape[1], 1)'], {}), '(x_train, (x_train.shape[0], x_train.shape[1], 1))\n', (1028, 1078), True, 'import numpy as np\n'), ((1116, 1128), 'tensorflow.keras.models.Sequential', 'Sequential', ([], {}), '()\n', (1126, 1128), False, 'from tensorflow.keras.models import Sequential\n'), ((1535, 1558), 'datetime.datetime', 'dt.datetime', (['(2020)', '(1)', '(1)'], {}), '(2020, 1, 1)\n', (1546, 1558), True, 'import datetime as dt\n'), ((1568, 1585), 'datetime.datetime.now', 'dt.datetime.now', ([], {}), '()\n', (1583, 1585), True, 'import datetime as dt\n'), ((1599, 1666), 'pandas_datareader.DataReader', 'web.DataReader', (['f"""{crypto_currency}"""', '"""yahoo"""', 'test_start', 'test_end'], {}), "(f'{crypto_currency}', 'yahoo', test_start, test_end)\n", (1613, 1666), True, 'import pandas_datareader as web\n'), ((1726, 1780), 'pandas.concat', 'pd.concat', (["(data['Close'], test_data['Close'])"], {'axis': '(0)'}), "((data['Close'], test_data['Close']), axis=0)\n", (1735, 1780), True, 'import pandas as pd\n'), ((2100, 2116), 'numpy.array', 'np.array', (['x_test'], {}), '(x_test)\n', (2108, 2116), True, 'import numpy as np\n'), ((2126, 2183), 'numpy.reshape', 'np.reshape', (['x_test', '(x_test.shape[0], x_test.shape[1], 1)'], {}), '(x_test, (x_test.shape[0], x_test.shape[1], 1))\n', (2136, 2183), True, 'import numpy as np\n'), ((2398, 2417), 'numpy.array', 'np.array', (['real_data'], {}), '(real_data)\n', (2406, 2417), True, 'import numpy as np\n'), ((2430, 2496), 'numpy.reshape', 'np.reshape', (['real_data', '(real_data.shape[0], real_data.shape[1], 1)'], {}), '(real_data, (real_data.shape[0], real_data.shape[1], 1))\n', (2440, 2496), True, 'import numpy as np\n'), ((2606, 2665), 'matplotlib.pyplot.plot', 'plt.plot', (['actual_prices'], {'color': '"""red"""', 'label': '"""Actual Prices"""'}), "(actual_prices, color='red', label='Actual Prices')\n", (2614, 2665), True, 'import matplotlib.pyplot as plt\n'), ((2666, 2731), 'matplotlib.pyplot.plot', 'plt.plot', (['prediction_prices'], {'color': '"""green"""', 'label': '"""Actual Prices"""'}), "(prediction_prices, color='green', label='Actual Prices')\n", (2674, 2731), True, 'import matplotlib.pyplot as plt\n'), ((2732, 2780), 'matplotlib.pyplot.title', 'plt.title', (['f"""{crypto_currency} Price Prediction"""'], {}), "(f'{crypto_currency} Price Prediction')\n", (2741, 2780), True, 'import matplotlib.pyplot as plt\n'), ((2781, 2799), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Time"""'], {}), "('Time')\n", (2791, 2799), True, 'import matplotlib.pyplot as plt\n'), ((2800, 2819), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Price"""'], {}), "('Price')\n", (2810, 2819), True, 'import matplotlib.pyplot as plt\n'), ((2820, 2848), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper left"""'}), "(loc='upper left')\n", (2830, 2848), True, 'import matplotlib.pyplot as plt\n'), ((2849, 2859), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2857, 2859), True, 'import matplotlib.pyplot as plt\n'), ((971, 988), 'numpy.array', 'np.array', (['x_train'], {}), '(x_train)\n', (979, 988), True, 'import numpy as np\n'), ((990, 1007), 'numpy.array', 'np.array', (['y_train'], {}), '(y_train)\n', (998, 1007), True, 'import numpy as np\n'), ((1140, 1212), 'tensorflow.keras.layers.LSTM', 'LSTM', ([], {'units': '(50)', 'return_sequences': '(True)', 'input_shape': '(x_train.shape[1], 1)'}), '(units=50, return_sequences=True, input_shape=(x_train.shape[1], 1))\n', (1144, 1212), False, 'from tensorflow.keras.layers import Dense, Dropout, LSTM\n'), ((1224, 1236), 'tensorflow.keras.layers.Dropout', 'Dropout', (['(0.2)'], {}), '(0.2)\n', (1231, 1236), False, 'from tensorflow.keras.layers import Dense, Dropout, LSTM\n'), ((1248, 1285), 'tensorflow.keras.layers.LSTM', 'LSTM', ([], {'units': '(50)', 'return_sequences': '(True)'}), '(units=50, return_sequences=True)\n', (1252, 1285), False, 'from tensorflow.keras.layers import Dense, Dropout, LSTM\n'), ((1297, 1309), 'tensorflow.keras.layers.Dropout', 'Dropout', (['(0.2)'], {}), '(0.2)\n', (1304, 1309), False, 'from tensorflow.keras.layers import Dense, Dropout, LSTM\n'), ((1321, 1335), 'tensorflow.keras.layers.LSTM', 'LSTM', ([], {'units': '(50)'}), '(units=50)\n', (1325, 1335), False, 'from tensorflow.keras.layers import Dense, Dropout, LSTM\n'), ((1347, 1359), 'tensorflow.keras.layers.Dropout', 'Dropout', (['(0.2)'], {}), '(0.2)\n', (1354, 1359), False, 'from tensorflow.keras.layers import Dense, Dropout, LSTM\n'), ((1371, 1385), 'tensorflow.keras.layers.Dense', 'Dense', ([], {'units': '(1)'}), '(units=1)\n', (1376, 1385), False, 'from tensorflow.keras.layers import Dense, Dropout, LSTM\n')]
|
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from pathlib import Path
from seabreeze.spectrometers import Spectrometer
class OceanMea():
def __init__(self,intgtime=1000,ave=10):
self.intgtime = intgtime
self.ave = ave
self.spec = Spectrometer.from_first_available()
# 0.1 seconds = 100000, 0.01s =10000, 0.001s = 1000
self.set_integtime()
def get_ref(self):
self.ref_wave, self.ref_ave_ints = self.get_ave_data()
def set_integtime(self):
self.spec.integration_time_micros(self.intgtime) # 0.1 seconds = 100000, 0.01
@classmethod
def calc_reflectance(cls,wave,ints,ref_ints):
reflec_ints = ints/ref_ints
plt.plot(wave,reflec_ints)
# plt.show(block=False)
plt.show()
return reflec_ints
def get_data(self):
self.wave = self.spec.wavelengths()
self.ints= self.spec.intensities()
return self.wave, self.ints
def get_ave_data(self):
self.wave = self.spec.wavelengths()
self.ave_ints = np.zeros_like(self.wave )
for i in range(self.ave):
self.ints= self.spec.intensities()
# print(self.ints[20])
self.ave_ints = (self.ave_ints + self.ints)/(i+1)
return self.wave, self.ave_ints
def df_return(self):
self.df_data =pd.DataFrame({'wave':self.wave,
'intensity':self.ave_ints})
return self.df_data
def save_csv(self,filename):
"""
filename:
example 'data/dst/to_csv_out.csv'
"""
self.df_ = self.df_return()
self.df_.to_csv(filename,index=False)
def get_ref_file(self,filename):
self.df_ref = pd.read_csv(filename)
self.ref_wave = self.df_ref['wave']
self.ref_ave_ints = self.df_ref['intensity']
return self.df_ref
def save_raw_to_csv(self, base_file_name, file_option, ref_file, SAVE_DATA_HOLDER=None):
"""
Spectra data save
metadata save
reflectance
:param SAVE_DATA_HOLDER:
:return:
"""
if SAVE_DATA_HOLDER == None:
SAVE_DATA_HOLDER = './data'
file_data_name = "{}_uvu_{}.csv".format(base_file_name, file_option)
save_data_path = Path(SAVE_DATA_HOLDER, file_data_name)
df_data = self.save_csv(save_data_path)
meta_device = {'device': {'modul_name': 'ocean optics usb2000+'}}
meta_condition = {'conditions': {'integration time': str(self.intgtime) + 'ms',
'average': str(self.ave),
'referanec': None}}
meta_csv = {'csv_data': {'column': ['wavelength', 'absolute_count'],
'unit': ['nm', 'uW/cm^2/nm']}}
meta_option = meta_device.copy()
meta_option.update(meta_condition)
meta_option.update(meta_csv)
# meta_file_name = "{}_uvu_meta.txt".format(base_file_name)
# meta_file_path = Path(SAVE_DATA_HOLDER + meta_file_name)
# with meta_file_path.open( 'w') as fmeta:
# fmeta.write(meta_condition)
return file_data_name, meta_option
def save_cal_to_csv(self, base_file_name, file_option, ref_file, SAVE_DATA_HOLDER=None):
"""
Spectra data save
metadata save
reflectance
:param SAVE_DATA_HOLDER:
:return:
"""
if SAVE_DATA_HOLDER == None:
SAVE_DATA_HOLDER = './data'
file_data_name = "{}_Ruvu_{}.csv".format(base_file_name, file_option)
save_data_path = Path(SAVE_DATA_HOLDER, file_data_name)
#
df_ref = self.get_ref_file(ref_file)
df_data = self.df_return()
reflectance = df_data[1] / df_ref[1]
df_out = pd.DataFrame({'wave': df_ref[0],'absolute_count': df_data[1],'reflectance': reflectance})
df_out.to_csv(save_data_path,index=False)
meta_device = {'device': {'modul_name': 'ocean optics usb2000+'}}
meta_condition = {'conditions': {'integration time': str(self.intgtime) + 'ms',
'average': str(self.ave),
'referanec': ref_file}}
meta_csv = {'csv_data': {'column': ['wavelength', 'absolute_count', 'reflectance'],
'unit': ['nm', 'uW/cm^2/nm', 'au']}}
meta_option = meta_device.copy()
meta_option.update(meta_condition)
meta_option.update(meta_csv)
# meta_file_name = "{}_uvu_meta.txt".format(base_file_name)
# meta_file_path = Path(SAVE_DATA_HOLDER + meta_file_name)
# with meta_file_path.open( 'w') as fmeta:
# fmeta.write(meta_condition)
return file_data_name, meta_option
if __name__ == '__main__':
import time
ref=OceanMea()
rwave,rints= ref.get_ave_data()
ref.save_csv('ref.csv')
print('-----')
time.sleep(5)
print('--remain 3--')
time.sleep(3)
_,ints =ref.get_ave_data()
ref.calc_reflectance(rwave,ints,rints)
|
[
"pandas.DataFrame",
"numpy.zeros_like",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"pandas.read_csv",
"time.sleep",
"pathlib.Path",
"seabreeze.spectrometers.Spectrometer.from_first_available"
] |
[((5316, 5329), 'time.sleep', 'time.sleep', (['(5)'], {}), '(5)\n', (5326, 5329), False, 'import time\n'), ((5362, 5375), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)\n', (5372, 5375), False, 'import time\n'), ((297, 332), 'seabreeze.spectrometers.Spectrometer.from_first_available', 'Spectrometer.from_first_available', ([], {}), '()\n', (330, 332), False, 'from seabreeze.spectrometers import Spectrometer\n'), ((775, 802), 'matplotlib.pyplot.plot', 'plt.plot', (['wave', 'reflec_ints'], {}), '(wave, reflec_ints)\n', (783, 802), True, 'import matplotlib.pyplot as plt\n'), ((844, 854), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (852, 854), True, 'import matplotlib.pyplot as plt\n'), ((1167, 1191), 'numpy.zeros_like', 'np.zeros_like', (['self.wave'], {}), '(self.wave)\n', (1180, 1191), True, 'import numpy as np\n'), ((1513, 1574), 'pandas.DataFrame', 'pd.DataFrame', (["{'wave': self.wave, 'intensity': self.ave_ints}"], {}), "({'wave': self.wave, 'intensity': self.ave_ints})\n", (1525, 1574), True, 'import pandas as pd\n'), ((1923, 1944), 'pandas.read_csv', 'pd.read_csv', (['filename'], {}), '(filename)\n', (1934, 1944), True, 'import pandas as pd\n'), ((2518, 2556), 'pathlib.Path', 'Path', (['SAVE_DATA_HOLDER', 'file_data_name'], {}), '(SAVE_DATA_HOLDER, file_data_name)\n', (2522, 2556), False, 'from pathlib import Path\n'), ((3919, 3957), 'pathlib.Path', 'Path', (['SAVE_DATA_HOLDER', 'file_data_name'], {}), '(SAVE_DATA_HOLDER, file_data_name)\n', (3923, 3957), False, 'from pathlib import Path\n'), ((4127, 4222), 'pandas.DataFrame', 'pd.DataFrame', (["{'wave': df_ref[0], 'absolute_count': df_data[1], 'reflectance': reflectance}"], {}), "({'wave': df_ref[0], 'absolute_count': df_data[1],\n 'reflectance': reflectance})\n", (4139, 4222), True, 'import pandas as pd\n')]
|
#-*-coding:utf-8-*-
import tensorflow as tf
import Data_helper
from utils.data_util import from_project_root
from tensorflow.contrib import learn
import numpy as np
from sklearn.metrics import f1_score
from sklearn.metrics import accuracy_score
from tqdm import tqdm
import pickle as pk
# ===================================================================================
# 参数设置
# 参数设置
tf.flags.DEFINE_boolean("allow_soft_placement", True, "Allow device soft device placement")
tf.flags.DEFINE_boolean("log_device_placement", False, "Log placement of ops on devices")
# 预测文件路径
tf.flags.DEFINE_string("predict_filename","lstm_model/processed_data/two_gram/filter_2-gram_phrase_level_data_dev.csv","predict_filename path")
# vocabulary path
tf.flags.DEFINE_string("vocabulary_path","./runs/1533471123/vocab","vocabulary_path")
tf.flags.DEFINE_string("vocab_file","lstm_model/processed_data/filter_phrase_level_vocab.pk","vocab file url")
tf.flags.DEFINE_integer("max_word_in_sent",1000,"max_word_in_sent")
# model checkpoint path
tf.flags.DEFINE_string("meta_path","./runs/1533471123/checkpoints/model-1300.meta","meta_path")
tf.flags.DEFINE_string("model_path","./runs/1533471123/checkpoints/model-1300","model_path")
tf.flags.DEFINE_string("result_path","./result/result_predict-1300.csv","result path")
FLAGS = tf.flags.FLAGS
# FLAGS._parse_flags()
# ===================================================================================
# 获取预测文本
predict_context,predict_labels = Data_helper.get_predict_data(from_project_root(FLAGS.predict_filename))
# 加载自己定义好的词典
# vocab_dict = pk.load(open(from_project_root(FLAGS.vocab_file),'rb'))
# x_vecs = []
# for x in predict_context:
# word_list = x.strip().split()
# x_vec = [0] * FLAGS.max_word_in_sent
# for i in range(min(FLAGS.max_word_in_sent,len(word_list))):
# x_vec[i] = vocab_dict[word_list[i]]
# x_vecs.append(x_vec)
vocab_processor = learn.preprocessing.VocabularyProcessor.restore(FLAGS.vocabulary_path)
x_vecs = np.array(list(vocab_processor.transform(predict_context)))
# predition
print("prediction.......")
# 预测
graph = tf.Graph()
with graph.as_default():
session_conf = tf.ConfigProto(
allow_soft_placement=FLAGS.allow_soft_placement,
log_device_placement=FLAGS.log_device_placement)
sess = tf.Session(config=session_conf)
with sess.as_default():
# 加载训练好的模型
saver = tf.train.import_meta_graph(FLAGS.meta_path)
saver.restore(sess,FLAGS.model_path)
# 获取模型输入
input_x = graph.get_operation_by_name("placeholder/input_x").outputs[0]
rnn_input_keep_prob = graph.get_operation_by_name("placeholder/rnn_input_keep_prob").outputs[0]
rnn_output_keep_prob = graph.get_operation_by_name("placeholder/rnn_output_keep_prob").outputs[0]
#
predictions = graph.get_operation_by_name("fully_connection_layer/prediction").outputs[0]
per_predict_limit = 100
sum_predict = len(x_vecs)
batch_size = int(sum_predict / per_predict_limit)
batch_prediction_all = []
# 一个一个进行预测
for index in tqdm(range(batch_size)):
start_index = index * per_predict_limit
if index == batch_size - 1 :
end_index = sum_predict
else:
end_index = start_index + per_predict_limit
predict_text = x_vecs[start_index:end_index]
predict_result = sess.run(predictions,{input_x:predict_text,rnn_input_keep_prob:1.0,
rnn_output_keep_prob:1.0})
batch_prediction_all.extend(predict_result)
# 预测结果输出
# print(batch_prediction_all)
reset_prediction_all = []
for predit in batch_prediction_all:
reset_prediction_all.append(int(predit)+1)
real_label = np.array(predict_labels).astype(int)
predict_labels = reset_prediction_all
macro_f1 = f1_score(real_label,reset_prediction_all,average='macro')
accuracy_score1 = accuracy_score(real_label,reset_prediction_all,normalize=True)
print("macro_f1:{}".format(macro_f1))
print("accuracy:{}".format(accuracy_score1))
ids = np.array(real_label).astype(int)
predict_labels = reset_prediction_all
# 写入文件
with open(FLAGS.result_path,'w',encoding='utf-8') as f:
f.write("id,class\n")
for i in range(len(ids)):
f.write("{},{}\n".format(ids[i],predict_labels[i]))
|
[
"tensorflow.contrib.learn.preprocessing.VocabularyProcessor.restore",
"tensorflow.train.import_meta_graph",
"sklearn.metrics.accuracy_score",
"tensorflow.Session",
"utils.data_util.from_project_root",
"tensorflow.ConfigProto",
"sklearn.metrics.f1_score",
"numpy.array",
"tensorflow.Graph",
"tensorflow.flags.DEFINE_integer",
"tensorflow.flags.DEFINE_boolean",
"tensorflow.flags.DEFINE_string"
] |
[((390, 485), 'tensorflow.flags.DEFINE_boolean', 'tf.flags.DEFINE_boolean', (['"""allow_soft_placement"""', '(True)', '"""Allow device soft device placement"""'], {}), "('allow_soft_placement', True,\n 'Allow device soft device placement')\n", (413, 485), True, 'import tensorflow as tf\n'), ((482, 575), 'tensorflow.flags.DEFINE_boolean', 'tf.flags.DEFINE_boolean', (['"""log_device_placement"""', '(False)', '"""Log placement of ops on devices"""'], {}), "('log_device_placement', False,\n 'Log placement of ops on devices')\n", (505, 575), True, 'import tensorflow as tf\n'), ((581, 735), 'tensorflow.flags.DEFINE_string', 'tf.flags.DEFINE_string', (['"""predict_filename"""', '"""lstm_model/processed_data/two_gram/filter_2-gram_phrase_level_data_dev.csv"""', '"""predict_filename path"""'], {}), "('predict_filename',\n 'lstm_model/processed_data/two_gram/filter_2-gram_phrase_level_data_dev.csv'\n , 'predict_filename path')\n", (603, 735), True, 'import tensorflow as tf\n'), ((744, 835), 'tensorflow.flags.DEFINE_string', 'tf.flags.DEFINE_string', (['"""vocabulary_path"""', '"""./runs/1533471123/vocab"""', '"""vocabulary_path"""'], {}), "('vocabulary_path', './runs/1533471123/vocab',\n 'vocabulary_path')\n", (766, 835), True, 'import tensorflow as tf\n'), ((830, 946), 'tensorflow.flags.DEFINE_string', 'tf.flags.DEFINE_string', (['"""vocab_file"""', '"""lstm_model/processed_data/filter_phrase_level_vocab.pk"""', '"""vocab file url"""'], {}), "('vocab_file',\n 'lstm_model/processed_data/filter_phrase_level_vocab.pk', 'vocab file url')\n", (852, 946), True, 'import tensorflow as tf\n'), ((941, 1010), 'tensorflow.flags.DEFINE_integer', 'tf.flags.DEFINE_integer', (['"""max_word_in_sent"""', '(1000)', '"""max_word_in_sent"""'], {}), "('max_word_in_sent', 1000, 'max_word_in_sent')\n", (964, 1010), True, 'import tensorflow as tf\n'), ((1033, 1134), 'tensorflow.flags.DEFINE_string', 'tf.flags.DEFINE_string', (['"""meta_path"""', '"""./runs/1533471123/checkpoints/model-1300.meta"""', '"""meta_path"""'], {}), "('meta_path',\n './runs/1533471123/checkpoints/model-1300.meta', 'meta_path')\n", (1055, 1134), True, 'import tensorflow as tf\n'), ((1129, 1227), 'tensorflow.flags.DEFINE_string', 'tf.flags.DEFINE_string', (['"""model_path"""', '"""./runs/1533471123/checkpoints/model-1300"""', '"""model_path"""'], {}), "('model_path',\n './runs/1533471123/checkpoints/model-1300', 'model_path')\n", (1151, 1227), True, 'import tensorflow as tf\n'), ((1222, 1314), 'tensorflow.flags.DEFINE_string', 'tf.flags.DEFINE_string', (['"""result_path"""', '"""./result/result_predict-1300.csv"""', '"""result path"""'], {}), "('result_path', './result/result_predict-1300.csv',\n 'result path')\n", (1244, 1314), True, 'import tensorflow as tf\n'), ((1921, 1991), 'tensorflow.contrib.learn.preprocessing.VocabularyProcessor.restore', 'learn.preprocessing.VocabularyProcessor.restore', (['FLAGS.vocabulary_path'], {}), '(FLAGS.vocabulary_path)\n', (1968, 1991), False, 'from tensorflow.contrib import learn\n'), ((2114, 2124), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (2122, 2124), True, 'import tensorflow as tf\n'), ((1514, 1555), 'utils.data_util.from_project_root', 'from_project_root', (['FLAGS.predict_filename'], {}), '(FLAGS.predict_filename)\n', (1531, 1555), False, 'from utils.data_util import from_project_root\n'), ((2171, 2287), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'allow_soft_placement': 'FLAGS.allow_soft_placement', 'log_device_placement': 'FLAGS.log_device_placement'}), '(allow_soft_placement=FLAGS.allow_soft_placement,\n log_device_placement=FLAGS.log_device_placement)\n', (2185, 2287), True, 'import tensorflow as tf\n'), ((2313, 2344), 'tensorflow.Session', 'tf.Session', ([], {'config': 'session_conf'}), '(config=session_conf)\n', (2323, 2344), True, 'import tensorflow as tf\n'), ((2410, 2453), 'tensorflow.train.import_meta_graph', 'tf.train.import_meta_graph', (['FLAGS.meta_path'], {}), '(FLAGS.meta_path)\n', (2436, 2453), True, 'import tensorflow as tf\n'), ((3956, 4015), 'sklearn.metrics.f1_score', 'f1_score', (['real_label', 'reset_prediction_all'], {'average': '"""macro"""'}), "(real_label, reset_prediction_all, average='macro')\n", (3964, 4015), False, 'from sklearn.metrics import f1_score\n'), ((4040, 4104), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['real_label', 'reset_prediction_all'], {'normalize': '(True)'}), '(real_label, reset_prediction_all, normalize=True)\n', (4054, 4104), False, 'from sklearn.metrics import accuracy_score\n'), ((3852, 3876), 'numpy.array', 'np.array', (['predict_labels'], {}), '(predict_labels)\n', (3860, 3876), True, 'import numpy as np\n'), ((4218, 4238), 'numpy.array', 'np.array', (['real_label'], {}), '(real_label)\n', (4226, 4238), True, 'import numpy as np\n')]
|
# Copyright (c) 2018-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import numpy as np
import pandas as pd
import copy
from common.quaternion import expmap_to_quaternion, qfix, qmul_np
from common.mocap_dataset import MocapDataset
from common.skeleton import Skeleton
from common.camera import *
h36m_skeleton = Skeleton(offsets=[
[ 0. , 0. , 0. ],
[-132.948591, 0. , 0. ],
[ 0. , -442.894612, 0. ],
[ 0. , -454.206447, 0. ],
[ 0. , 0. , 162.767078],
[ 0. , 0. , 74.999437],
[ 132.948826, 0. , 0. ],
[ 0. , -442.894413, 0. ],
[ 0. , -454.20659 , 0. ],
[ 0. , 0. , 162.767426],
[ 0. , 0. , 74.999948],
[ 0. , 0.1 , 0. ],
[ 0. , 233.383263, 0. ],
[ 0. , 257.077681, 0. ],
[ 0. , 121.134938, 0. ],
[ 0. , 115.002227, 0. ],
[ 0. , 257.077681, 0. ],
[ 0. , 151.034226, 0. ],
[ 0. , 278.882773, 0. ],
[ 0. , 251.733451, 0. ],
[ 0. , 0. , 0. ],
[ 0. , 0. , 99.999627],
[ 0. , 100.000188, 0. ],
[ 0. , 0. , 0. ],
[ 0. , 257.077681, 0. ],
[ 0. , 151.031437, 0. ],
[ 0. , 278.892924, 0. ],
[ 0. , 251.72868 , 0. ],
[ 0. , 0. , 0. ],
[ 0. , 0. , 99.999888],
[ 0. , 137.499922, 0. ],
[ 0. , 0. , 0. ]
],
parents=[-1, 0, 1, 2, 3, 4, 0, 6, 7, 8, 9, 0, 11, 12, 13, 14, 12,
16, 17, 18, 19, 20, 19, 22, 12, 24, 25, 26, 27, 28, 27, 30],
joints_right=[1, 2, 3, 4, 5, 24, 25, 26, 27, 28, 29, 30, 31],
joints_left=[6, 7, 8, 9, 10, 16, 17, 18, 19, 20, 21, 22, 23])
h36m_cameras_intrinsic_params = [
{
'id': '54138969',
'center': [512.54150390625, 515.4514770507812],
'focal_length': [1145.0494384765625, 1143.7811279296875],
'radial_distortion': [-0.20709891617298126, 0.24777518212795258, -0.0030751503072679043],
'tangential_distortion': [-0.0009756988729350269, -0.00142447161488235],
'res_w': 1000,
'res_h': 1002,
'azimuth': 70, # Only used for visualization
},
{
'id': '55011271',
'center': [508.8486328125, 508.0649108886719],
'focal_length': [1149.6756591796875, 1147.5916748046875],
'radial_distortion': [-0.1942136287689209, 0.2404085397720337, 0.006819975562393665],
'tangential_distortion': [-0.0016190266469493508, -0.0027408944442868233],
'res_w': 1000,
'res_h': 1000,
'azimuth': -70, # Only used for visualization
},
{
'id': '58860488',
'center': [519.8158569335938, 501.40264892578125],
'focal_length': [1149.1407470703125, 1148.7989501953125],
'radial_distortion': [-0.2083381861448288, 0.25548800826072693, -0.0024604974314570427],
'tangential_distortion': [0.0014843869721516967, -0.0007599993259645998],
'res_w': 1000,
'res_h': 1000,
'azimuth': 110, # Only used for visualization
},
{
'id': '60457274',
'center': [514.9682006835938, 501.88201904296875],
'focal_length': [1145.5113525390625, 1144.77392578125],
'radial_distortion': [-0.198384091258049, 0.21832367777824402, -0.008947807364165783],
'tangential_distortion': [-0.0005872055771760643, -0.0018133620033040643],
'res_w': 1000,
'res_h': 1002,
'azimuth': -110, # Only used for visualization
},
]
h36m_cameras_extrinsic_params = {
'S1': [
{
'orientation': [0.1407056450843811, -0.1500701755285263, -0.755240797996521, 0.6223280429840088],
'translation': [1841.1070556640625, 4955.28466796875, 1563.4454345703125],
},
{
'orientation': [0.6157187819480896, -0.764836311340332, -0.14833825826644897, 0.11794740706682205],
'translation': [1761.278564453125, -5078.0068359375, 1606.2650146484375],
},
{
'orientation': [0.14651472866535187, -0.14647851884365082, 0.7653023600578308, -0.6094175577163696],
'translation': [-1846.7777099609375, 5215.04638671875, 1491.972412109375],
},
{
'orientation': [0.5834008455276489, -0.7853162288665771, 0.14548823237419128, -0.14749594032764435],
'translation': [-1794.7896728515625, -3722.698974609375, 1574.8927001953125],
},
],
'S2': [
{},
{},
{},
{},
],
'S3': [
{},
{},
{},
{},
],
'S4': [
{},
{},
{},
{},
],
'S5': [
{
'orientation': [0.1467377245426178, -0.162370964884758, -0.7551892995834351, 0.6178938746452332],
'translation': [2097.3916015625, 4880.94482421875, 1605.732421875],
},
{
'orientation': [0.6159758567810059, -0.7626792192459106, -0.15728192031383514, 0.1189815029501915],
'translation': [2031.7008056640625, -5167.93310546875, 1612.923095703125],
},
{
'orientation': [0.14291371405124664, -0.12907841801643372, 0.7678384780883789, -0.6110143065452576],
'translation': [-1620.5948486328125, 5171.65869140625, 1496.43701171875],
},
{
'orientation': [0.5920479893684387, -0.7814217805862427, 0.1274748593568802, -0.15036417543888092],
'translation': [-1637.1737060546875, -3867.3173828125, 1547.033203125],
},
],
'S6': [
{
'orientation': [0.1337897777557373, -0.15692396461963654, -0.7571090459823608, 0.6198879480361938],
'translation': [1935.4517822265625, 4950.24560546875, 1618.0838623046875],
},
{
'orientation': [0.6147197484970093, -0.7628812789916992, -0.16174767911434174, 0.11819244921207428],
'translation': [1969.803955078125, -5128.73876953125, 1632.77880859375],
},
{
'orientation': [0.1529948115348816, -0.13529130816459656, 0.7646096348762512, -0.6112781167030334],
'translation': [-1769.596435546875, 5185.361328125, 1476.993408203125],
},
{
'orientation': [0.5916101336479187, -0.7804774045944214, 0.12832270562648773, -0.1561593860387802],
'translation': [-1721.668701171875, -3884.13134765625, 1540.4879150390625],
},
],
'S7': [
{
'orientation': [0.1435241848230362, -0.1631336808204651, -0.7548328638076782, 0.6188824772834778],
'translation': [1974.512939453125, 4926.3544921875, 1597.8326416015625],
},
{
'orientation': [0.6141672730445862, -0.7638262510299683, -0.1596645563840866, 0.1177929937839508],
'translation': [1937.0584716796875, -5119.7900390625, 1631.5665283203125],
},
{
'orientation': [0.14550060033798218, -0.12874816358089447, 0.7660516500473022, -0.6127139329910278],
'translation': [-1741.8111572265625, 5208.24951171875, 1464.8245849609375],
},
{
'orientation': [0.5912848114967346, -0.7821764349937439, 0.12445473670959473, -0.15196487307548523],
'translation': [-1734.7105712890625, -3832.42138671875, 1548.5830078125],
},
],
'S8': [
{
'orientation': [0.14110587537288666, -0.15589867532253265, -0.7561917304992676, 0.619644045829773],
'translation': [2150.65185546875, 4896.1611328125, 1611.9046630859375],
},
{
'orientation': [0.6169601678848267, -0.7647668123245239, -0.14846350252628326, 0.11158157885074615],
'translation': [2219.965576171875, -5148.453125, 1613.0440673828125],
},
{
'orientation': [0.1471444070339203, -0.13377119600772858, 0.7670128345489502, -0.6100369691848755],
'translation': [-1571.2215576171875, 5137.0185546875, 1498.1761474609375],
},
{
'orientation': [0.5927824378013611, -0.7825870513916016, 0.12147816270589828, -0.14631995558738708],
'translation': [-1476.913330078125, -3896.7412109375, 1547.97216796875],
},
],
'S9': [
{
'orientation': [0.15540587902069092, -0.15548215806484222, -0.7532095313072205, 0.6199594736099243],
'translation': [2044.45849609375, 4935.1171875, 1481.2275390625],
},
{
'orientation': [0.618784487247467, -0.7634735107421875, -0.14132238924503326, 0.11933968216180801],
'translation': [1990.959716796875, -5123.810546875, 1568.8048095703125],
},
{
'orientation': [0.13357827067375183, -0.1367100477218628, 0.7689454555511475, -0.6100738644599915],
'translation': [-1670.9921875, 5211.98583984375, 1528.387939453125],
},
{
'orientation': [0.5879399180412292, -0.7823407053947449, 0.1427614390850067, -0.14794869720935822],
'translation': [-1696.04345703125, -3827.099853515625, 1591.4127197265625],
},
],
'S11': [
{
'orientation': [0.15232472121715546, -0.15442320704460144, -0.7547563314437866, 0.6191070079803467],
'translation': [2098.440185546875, 4926.5546875, 1500.278564453125],
},
{
'orientation': [0.6189449429512024, -0.7600917220115662, -0.15300633013248444, 0.1255258321762085],
'translation': [2083.182373046875, -4912.1728515625, 1561.07861328125],
},
{
'orientation': [0.14943228662014008, -0.15650227665901184, 0.7681233882904053, -0.6026304364204407],
'translation': [-1609.8153076171875, 5177.3359375, 1537.896728515625],
},
{
'orientation': [0.5894251465797424, -0.7818877100944519, 0.13991211354732513, -0.14715361595153809],
'translation': [-1590.738037109375, -3854.1689453125, 1578.017578125],
},
],
}
class Human36mDataset(MocapDataset):
def __init__(self, path, keep_feet=False, keep_shoulders=False):
super().__init__(skeleton=copy.deepcopy(h36m_skeleton), fps=50, )
self.skeleton()._offsets /= 1000 # use m instead of mm
self._cameras = copy.deepcopy(h36m_cameras_extrinsic_params)
for cameras in self._cameras.values():
for i, cam in enumerate(cameras):
cam.update(h36m_cameras_intrinsic_params[i])
for k, v in cam.items():
if k not in ['id', 'res_w', 'res_h']:
cam[k] = np.array(v, dtype='float32')
# Normalize camera frame
cam['center'] = normalize_screen_coordinates(cam['center'], w=cam['res_w'], h=cam['res_h']).astype('float32')
cam['focal_length'] = cam['focal_length']/cam['res_w']*2
if 'translation' in cam:
cam['translation'] = cam['translation']/1000 # mm to meters
# Add intrinsic parameters vector
cam['intrinsic'] = np.concatenate((cam['focal_length'],
cam['center'],
cam['radial_distortion'],
cam['tangential_distortion']))
# Load serialized dataset
data = np.load(path, allow_pickle=True)
pos_3d = data['positions_3d'].item()
rot_3d = data['rotations_3d'].item()
traj = data['trajectory'].item()
self._data = {}
for subject, actions in pos_3d.items():
self._data[subject] = {}
for action_name, positions in actions.items():
self._data[subject][action_name] = {
'positions': positions,
'cameras': self._cameras[subject],
'rotations': rot_3d[subject][action_name],
'trajectory': traj[subject][action_name],
}
# Bring the skeleton to 21 joints instead of the original 32
self.remove_joints([5, 10, 11, 12, 20, 21, 22, 23, 28, 29, 30, 31])
if not keep_shoulders:
self._fix_shoulders(13, 17, 9)
if not keep_feet:
self.remove_joints([4, 8])
# removes the unnecessary double joints for the shoulder
# by removing the static ones, rewiring to the neck and fixing the offsets
# rotation won't get propagated!
def _fix_shoulders(self, lsho, rsho, neck):
skeleton = self._skeleton
lsho_parent, rsho_parent = skeleton._parents[[lsho, rsho]]
kept_joints = [j for j in range(skeleton.num_joints())
if j != lsho_parent and j != rsho_parent]
# remove from dataset
for subject in self._data.keys():
for action in self._data[subject]:
s = self._data[subject][action]
s['positions'] = np.ascontiguousarray(s['positions'][:, kept_joints])
rot = s['rotations']
for joint in [lsho_parent, rsho_parent]:
for child in self._skeleton.children()[joint]:
rot[:, child] = qmul_np(rot[:, joint], rot[:, child])
s['rotations'] = np.ascontiguousarray(rot[:, kept_joints])
# fix offsets
swap_idx = torch.tensor([1,0,2]) # swap first and second value
skeleton._offsets[lsho] = skeleton._offsets[lsho].index_select(0, swap_idx)
skeleton._offsets[rsho] = - skeleton._offsets[rsho].index_select(0, swap_idx)
skeleton._offsets = skeleton._offsets[kept_joints]
# remove static shoulders & rewire shoulders to the neck
skeleton._joints_left.remove(lsho_parent)
skeleton._joints_right.remove(rsho_parent)
skeleton._parents[lsho] = neck
skeleton._parents[rsho] = neck
skeleton._parents = skeleton._parents[kept_joints]
# recount indices for parent list
for i, p in enumerate(skeleton._parents):
index_offset = 2 if p >= rsho else 1 if p >= lsho else 0
skeleton._parents[i] -= index_offset
# recount indices for joints_left & joints_right
for i, j in enumerate(skeleton._joints_left):
index_offset = 2 if j >= rsho else 1 if j >= lsho else 0
skeleton._joints_left[i] -= index_offset
for i, j in enumerate(skeleton._joints_right):
index_offset = 2 if j >= rsho else 1 if j >= lsho else 0
skeleton._joints_right[i] -= index_offset
# fix children list
skeleton._compute_metadata()
def calc_2d_pos(self, normalized=False):
"""
compute 2D gt poses from all 4 cameras in pixel space
"""
for subject in self.subjects():
for action in self._data[subject].keys():
anim = self._data[subject][action]
positions_2d = []
for cam in anim['cameras']:
pos_3d = world_to_camera(anim['positions'], R=cam['orientation'], t=cam['translation'])
pos_2d = wrap(project_to_2d, pos_3d, cam['intrinsic'], unsqueeze=True)
if not normalized:
#convert to pixel_space
pos_2d = image_coordinates(pos_2d, w=cam['res_w'], h=cam['res_h'])
positions_2d.append(pos_2d.astype('float32'))
anim['positions_2d'] = positions_2d
|
[
"copy.deepcopy",
"numpy.load",
"common.skeleton.Skeleton",
"common.quaternion.qmul_np",
"numpy.array",
"numpy.ascontiguousarray",
"numpy.concatenate"
] |
[((439, 1497), 'common.skeleton.Skeleton', 'Skeleton', ([], {'offsets': '[[0.0, 0.0, 0.0], [-132.948591, 0.0, 0.0], [0.0, -442.894612, 0.0], [0.0, -\n 454.206447, 0.0], [0.0, 0.0, 162.767078], [0.0, 0.0, 74.999437], [\n 132.948826, 0.0, 0.0], [0.0, -442.894413, 0.0], [0.0, -454.20659, 0.0],\n [0.0, 0.0, 162.767426], [0.0, 0.0, 74.999948], [0.0, 0.1, 0.0], [0.0, \n 233.383263, 0.0], [0.0, 257.077681, 0.0], [0.0, 121.134938, 0.0], [0.0,\n 115.002227, 0.0], [0.0, 257.077681, 0.0], [0.0, 151.034226, 0.0], [0.0,\n 278.882773, 0.0], [0.0, 251.733451, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, \n 99.999627], [0.0, 100.000188, 0.0], [0.0, 0.0, 0.0], [0.0, 257.077681, \n 0.0], [0.0, 151.031437, 0.0], [0.0, 278.892924, 0.0], [0.0, 251.72868, \n 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 99.999888], [0.0, 137.499922, 0.0], [\n 0.0, 0.0, 0.0]]', 'parents': '[-1, 0, 1, 2, 3, 4, 0, 6, 7, 8, 9, 0, 11, 12, 13, 14, 12, 16, 17, 18, 19, \n 20, 19, 22, 12, 24, 25, 26, 27, 28, 27, 30]', 'joints_right': '[1, 2, 3, 4, 5, 24, 25, 26, 27, 28, 29, 30, 31]', 'joints_left': '[6, 7, 8, 9, 10, 16, 17, 18, 19, 20, 21, 22, 23]'}), '(offsets=[[0.0, 0.0, 0.0], [-132.948591, 0.0, 0.0], [0.0, -\n 442.894612, 0.0], [0.0, -454.206447, 0.0], [0.0, 0.0, 162.767078], [0.0,\n 0.0, 74.999437], [132.948826, 0.0, 0.0], [0.0, -442.894413, 0.0], [0.0,\n -454.20659, 0.0], [0.0, 0.0, 162.767426], [0.0, 0.0, 74.999948], [0.0, \n 0.1, 0.0], [0.0, 233.383263, 0.0], [0.0, 257.077681, 0.0], [0.0, \n 121.134938, 0.0], [0.0, 115.002227, 0.0], [0.0, 257.077681, 0.0], [0.0,\n 151.034226, 0.0], [0.0, 278.882773, 0.0], [0.0, 251.733451, 0.0], [0.0,\n 0.0, 0.0], [0.0, 0.0, 99.999627], [0.0, 100.000188, 0.0], [0.0, 0.0, \n 0.0], [0.0, 257.077681, 0.0], [0.0, 151.031437, 0.0], [0.0, 278.892924,\n 0.0], [0.0, 251.72868, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 99.999888], [\n 0.0, 137.499922, 0.0], [0.0, 0.0, 0.0]], parents=[-1, 0, 1, 2, 3, 4, 0,\n 6, 7, 8, 9, 0, 11, 12, 13, 14, 12, 16, 17, 18, 19, 20, 19, 22, 12, 24, \n 25, 26, 27, 28, 27, 30], joints_right=[1, 2, 3, 4, 5, 24, 25, 26, 27, \n 28, 29, 30, 31], joints_left=[6, 7, 8, 9, 10, 16, 17, 18, 19, 20, 21, \n 22, 23])\n', (447, 1497), False, 'from common.skeleton import Skeleton\n'), ((10835, 10879), 'copy.deepcopy', 'copy.deepcopy', (['h36m_cameras_extrinsic_params'], {}), '(h36m_cameras_extrinsic_params)\n', (10848, 10879), False, 'import copy\n'), ((11995, 12027), 'numpy.load', 'np.load', (['path'], {'allow_pickle': '(True)'}), '(path, allow_pickle=True)\n', (12002, 12027), True, 'import numpy as np\n'), ((10699, 10727), 'copy.deepcopy', 'copy.deepcopy', (['h36m_skeleton'], {}), '(h36m_skeleton)\n', (10712, 10727), False, 'import copy\n'), ((11675, 11788), 'numpy.concatenate', 'np.concatenate', (["(cam['focal_length'], cam['center'], cam['radial_distortion'], cam[\n 'tangential_distortion'])"], {}), "((cam['focal_length'], cam['center'], cam['radial_distortion'\n ], cam['tangential_distortion']))\n", (11689, 11788), True, 'import numpy as np\n'), ((13602, 13654), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (["s['positions'][:, kept_joints]"], {}), "(s['positions'][:, kept_joints])\n", (13622, 13654), True, 'import numpy as np\n'), ((13944, 13985), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['rot[:, kept_joints]'], {}), '(rot[:, kept_joints])\n', (13964, 13985), True, 'import numpy as np\n'), ((11166, 11194), 'numpy.array', 'np.array', (['v'], {'dtype': '"""float32"""'}), "(v, dtype='float32')\n", (11174, 11194), True, 'import numpy as np\n'), ((13873, 13910), 'common.quaternion.qmul_np', 'qmul_np', (['rot[:, joint]', 'rot[:, child]'], {}), '(rot[:, joint], rot[:, child])\n', (13880, 13910), False, 'from common.quaternion import expmap_to_quaternion, qfix, qmul_np\n')]
|
from typing import List
import numpy as np
import torch
from searl.neuroevolution.components.utils import Transition
from searl.rl_algorithms.components.wrappers import make_atari, wrap_deepmind, wrap_pytorch
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print("train CUDA", device == torch.device("cuda"), device)
class MPEvaluation():
def __init__(self, config, logger, replay_memory=None):
self.rng = np.random.RandomState(config.seed.evaluation)
self.cfg = config
self.log = logger
self.push_queue = replay_memory
self.eval_episodes = config.eval.eval_episodes
def test_individual(self, individual, epoch):
return_dict = self._evaluate_individual(individual, self.cfg, self.cfg.eval.test_episodes, epoch, False)
fitness = np.mean(return_dict[individual.index]["fitness_list"])
return fitness
@staticmethod
def _evaluate_individual(individual, config, num_episodes, seed, exploration_noise=False, start_phase=False):
actor_net = individual.actor
num_frames = 0
fitness_list = []
transistions_list = []
episodes = 0
env = make_atari(config.env.name)
env = wrap_deepmind(env)
env = wrap_pytorch(env)
env.seed(seed)
actor_net.eval()
actor_net.to(device)
actor_net.device = device
with torch.no_grad():
while episodes < num_episodes or num_frames < config.eval.min_eval_steps:
episode_fitness = 0.0
episode_transitions = []
state = env.reset()
done = False
while not done:
action = actor_net.act(state)
next_state, reward, done, info = env.step(action)
episode_fitness += reward
num_frames += 1
transition = Transition(torch.FloatTensor(state), torch.LongTensor([action]),
torch.FloatTensor(next_state), torch.FloatTensor(np.array([reward])),
torch.FloatTensor(np.array([done]).astype('uint8'))
)
episode_transitions.append(transition)
state = next_state
episodes += 1
fitness_list.append(episode_fitness)
transistions_list.append(episode_transitions)
actor_net.to(torch.device("cpu"))
return {individual.index: {"fitness_list": fitness_list, "num_episodes": num_episodes, "num_frames": num_frames,
"id": individual.index, "transitions": transistions_list}}
def evaluate_population(self, population: List, exploration_noise=False, total_frames=1):
population_id_lookup = [ind.index for ind in population]
new_population_mean_fitness = np.zeros(len(population))
new_population_var_fitness = np.zeros(len(population))
start_phase = total_frames <= self.cfg.rl.start_timesteps
if start_phase:
self.log("start phase", time_step=total_frames)
args_list = [(ind, self.cfg, self.eval_episodes, self.rng.randint(0, 100000), exploration_noise, start_phase)
for ind in population]
result_dict = []
for args in args_list:
result_dict.append(self._evaluate_individual(*args))
eval_frames = 0
for list_element in result_dict:
for ind_id, value_dict in list_element.items():
pop_idx = population_id_lookup.index(ind_id)
new_population_mean_fitness[pop_idx] = np.mean(value_dict['fitness_list'])
new_population_var_fitness[pop_idx] = np.var(value_dict['fitness_list'])
eval_frames += value_dict['num_frames']
population[pop_idx].train_log["eval_eps"] = self.eval_episodes
for transitions in value_dict['transitions']:
if self.cfg.nevo.ind_memory:
population[pop_idx].replay_memory.add(transitions)
else:
self.push_queue.put(transitions)
for idx in range(len(population)):
population[idx].train_log["post_fitness"] = new_population_mean_fitness[idx]
population[idx].train_log["index"] = population[idx].index
self.log.csv.log_csv(population[idx].train_log)
population[idx].train_log.update(
{"pre_fitness": new_population_mean_fitness[idx],
"eval_eps": 0}) # , "pre_rank": population_rank[idx], "eval_eps":0}
population[idx].fitness.append(new_population_mean_fitness[idx])
if len(population[idx].fitness) > 1:
population[idx].improvement = population[idx].fitness[-1] - population[idx].fitness[-2]
else:
population[idx].improvement = population[idx].fitness[-1]
return new_population_mean_fitness, new_population_var_fitness, eval_frames
|
[
"torch.LongTensor",
"torch.FloatTensor",
"searl.rl_algorithms.components.wrappers.wrap_pytorch",
"numpy.random.RandomState",
"numpy.var",
"searl.rl_algorithms.components.wrappers.wrap_deepmind",
"numpy.mean",
"torch.cuda.is_available",
"numpy.array",
"torch.device",
"searl.rl_algorithms.components.wrappers.make_atari",
"torch.no_grad"
] |
[((244, 269), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (267, 269), False, 'import torch\n'), ((312, 332), 'torch.device', 'torch.device', (['"""cuda"""'], {}), "('cuda')\n", (324, 332), False, 'import torch\n'), ((446, 491), 'numpy.random.RandomState', 'np.random.RandomState', (['config.seed.evaluation'], {}), '(config.seed.evaluation)\n', (467, 491), True, 'import numpy as np\n'), ((821, 875), 'numpy.mean', 'np.mean', (["return_dict[individual.index]['fitness_list']"], {}), "(return_dict[individual.index]['fitness_list'])\n", (828, 875), True, 'import numpy as np\n'), ((1187, 1214), 'searl.rl_algorithms.components.wrappers.make_atari', 'make_atari', (['config.env.name'], {}), '(config.env.name)\n', (1197, 1214), False, 'from searl.rl_algorithms.components.wrappers import make_atari, wrap_deepmind, wrap_pytorch\n'), ((1229, 1247), 'searl.rl_algorithms.components.wrappers.wrap_deepmind', 'wrap_deepmind', (['env'], {}), '(env)\n', (1242, 1247), False, 'from searl.rl_algorithms.components.wrappers import make_atari, wrap_deepmind, wrap_pytorch\n'), ((1262, 1279), 'searl.rl_algorithms.components.wrappers.wrap_pytorch', 'wrap_pytorch', (['env'], {}), '(env)\n', (1274, 1279), False, 'from searl.rl_algorithms.components.wrappers import make_atari, wrap_deepmind, wrap_pytorch\n'), ((1406, 1421), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (1419, 1421), False, 'import torch\n'), ((2510, 2529), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (2522, 2529), False, 'import torch\n'), ((3713, 3748), 'numpy.mean', 'np.mean', (["value_dict['fitness_list']"], {}), "(value_dict['fitness_list'])\n", (3720, 3748), True, 'import numpy as np\n'), ((3803, 3837), 'numpy.var', 'np.var', (["value_dict['fitness_list']"], {}), "(value_dict['fitness_list'])\n", (3809, 3837), True, 'import numpy as np\n'), ((1934, 1958), 'torch.FloatTensor', 'torch.FloatTensor', (['state'], {}), '(state)\n', (1951, 1958), False, 'import torch\n'), ((1960, 1986), 'torch.LongTensor', 'torch.LongTensor', (['[action]'], {}), '([action])\n', (1976, 1986), False, 'import torch\n'), ((2032, 2061), 'torch.FloatTensor', 'torch.FloatTensor', (['next_state'], {}), '(next_state)\n', (2049, 2061), False, 'import torch\n'), ((2081, 2099), 'numpy.array', 'np.array', (['[reward]'], {}), '([reward])\n', (2089, 2099), True, 'import numpy as np\n'), ((2164, 2180), 'numpy.array', 'np.array', (['[done]'], {}), '([done])\n', (2172, 2180), True, 'import numpy as np\n')]
|
# --------------------------------------------------------------------------------------------------
# Copyright (c) 2018 Microsoft Corporation
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
# associated documentation files (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge, publish, distribute,
# sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or
# substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
# NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# --------------------------------------------------------------------------------------------------
"""Module containing the shared, basic core functionality"""
from abc import ABC, abstractmethod
from enum import IntEnum
import logging
import os
import csv
import json
from collections import deque
import gym
import numpy as np
from .abc import FeedForwardModel, Visualizable, Explorable
from .utils import np_random, Graph, Node
class QType(IntEnum):
"""Different types of Q networks"""
DQN = 0
DoubleDQN = 1
class QFunctionApproximator(ABC):
"""Abstract base class for classes which approximate the Q function."""
def __init__(self, observation_space, action_space):
"""
Args:
observation_space -- The space of input observations
action_space -- The space of output actions
"""
assert isinstance(observation_space, gym.Space)
assert isinstance(action_space, gym.Space)
self._observation_space = observation_space
self._action_space = action_space
self.seed()
def seed(self, seed=None):
"""Seeds the pseudo-random number generator of the approximator.
Args:
seed -- the value used to seed the PRNG
Returns the seed
"""
self.np_random, seed = np_random(seed)
return seed
@property
def observation_space(self):
"""The space of observations upon which the agent can act."""
return self._observation_space
@property
def action_space(self):
"""The space to which actions returned by the agent will belong"""
return self._action_space
@abstractmethod
def present_batch(self, memory, minibatch_size):
"""Present a batch to the model.
Args:
memory -- a memory object
minibatch_size -- the size of minibatch to sample
"""
@abstractmethod
def train_model(self):
"""Train the model."""
@abstractmethod
def update_target(self):
"""Update the target."""
@abstractmethod
def compute(self, observations, is_training):
"""Compute the approximate q-values for all actions given the provided observations.
Args:
observations -- the observations
is_training -- whether the system is in training (as opposed to evaluation)
Returns the q values for each observation for every action in the action space
"""
@abstractmethod
def save(self, path):
"""Save the function to the specified path
Args:
path -- path to a location on the disk
"""
@abstractmethod
def load(self, path):
"""Load the function from the specified path
Args:
path -- path to a location on the disk
"""
class TrajectoryLearner(ABC):
"""Abstract base class for classes which learn a policy from trajectories."""
def __init__(self, observation_space, action_space):
"""
Args:
observation_space -- The space of input observations
action_space -- The space of output actions
"""
assert isinstance(observation_space, gym.Space)
assert isinstance(action_space, gym.Space)
self._observation_space = observation_space
self._action_space = action_space
self.seed()
def seed(self, seed=None):
"""Seeds the pseudo-random number generator of the approximator.
Args:
seed -- the value used to seed the PRNG
Returns the seed
"""
self.np_random, seed = np_random(seed)
return seed
@property
def observation_space(self):
"""The space of observations upon which the agent can act."""
return self._observation_space
@property
def action_space(self):
"""The space to which actions returned by the agent will belong"""
return self._action_space
@abstractmethod
def train_on_policy(self, batch, weights):
"""Trains the learner on-policy using the provided trajectories.
Args:
batch -- a TrajectoryBatch of trajectories from the current policy
weights -- per-trajectory weights
"""
@abstractmethod
def train_off_policy(self, batch, weights):
"""Trains the learner off-policy using the provided batch of trajectories.
Args:
batch -- a TrajectoryBatch of previous trajectories
weights -- per-trajectory weights
"""
@abstractmethod
def select_action(self, observation):
"""Selects an action for the given observation.
Args:
observation -- the current observation from the environment
Returns an action from the action space according to the current policy
"""
@abstractmethod
def save(self, path):
"""Save the learner to the specified path
Args:
path -- path to a location on the disk
"""
@abstractmethod
def load(self, path):
"""Load the learner from the specified path
Args:
path -- path to a location on the disk
"""
class FeedForwardModelQueue(object):
"""
Class which encapsulates a queue of models and manages processing data through all of them.
"""
def __init__(self, num_targets, reduce=None):
"""
Args:
num_targets -- the maximum number of targets to store
Keyword Args:
reduce -- the reduction function to use on model outputs [None]
"""
self._models = deque(maxlen=num_targets)
self._reduce = reduce
def enqueue(self, model):
"""Enqueue a new model.
Args:
model -- the model to enqueue.
"""
assert isinstance(model, FeedForwardModel)
self._models.append(model)
def compute(self, inputs):
"""Computes the output values for the inputs.
Args:
inputs -- the current inputs
Returns the result of compute the outputs from each model with an optional reduction
"""
if self._reduce:
outputs = self._reduce([model(inputs) for model in self._models])
else:
outputs = self._models[-1](inputs)
return outputs
def __call__(self, inputs):
return self.compute(inputs)
class FileRecorder(object):
"""Saves key-values pairs into a local file as a CSV."""
def __init__(self, output_path, keys=None):
"""
Args:
output_path -- the path to the output file
Keyword Args:
keys -- a dictionary of metadata keys written to the top of the file [{}]
"""
self._logger = logging.getLogger(__name__)
self._logger.info("Opening file %s", output_path)
if not os.path.isdir(os.path.dirname(output_path)):
os.makedirs(os.path.dirname(output_path))
self._file = open(output_path, 'w', newline='')
if not keys:
self._keys = {}
else:
self._keys = keys
self._count = 0
self._csv = None
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self._file.close()
def init(self, columns):
"""Indicate the labels for the values which the recorder will write to file.
Args:
columns -- a list of column names
"""
self._keys["columns"] = columns
self._file.write('key\n%s\n' % json.dumps(self._keys))
self._csv = csv.DictWriter(self._file, columns)
self._csv.writeheader()
def record(self, values):
"""Save values to the file and increment the counter.
Args:
values -- tuple of items that can be converted to string using str
these should be in the same order as the columns passed
to init()
"""
assert self._csv
content = dict(zip(self._keys["columns"], map(str, values)))
self._csv.writerow(content)
self._count += 1
class AgentMode(IntEnum):
"""Enumeration of different agent modes."""
Warmup = 0
Training = 1
Evaluation = 2
class Agent(ABC):
"""
Abstract base class for all agents.
"""
def __init__(self, observation_space, action_space):
"""
Args:
observation_space -- The space of observations upon which the agent can act
action_space -- The space to which actions returned by the agent will belong
"""
assert isinstance(observation_space, gym.Space)
assert isinstance(action_space, gym.Space)
self._observation_space = observation_space
self._action_space = action_space
self._mode = AgentMode.Warmup
self.seed()
def seed(self, seed=None):
"""Seed the pseudo-random number generator for the agent.
Keyword Args:
seed -- the seed to use. [None]
Returns the seed used (i.e. if None is passed one will be generated)
"""
self.np_random, seed = np_random(seed)
return seed
@property
def mode(self):
"""The current mode of the Agent (see `AgentMode`)."""
return self._mode
@mode.setter
def mode(self, value):
self._mode = value
@property
def observation_space(self):
"""The space of observations upon which the agent can act."""
return self._observation_space
@property
def action_space(self):
"""The space to which actions returned by the agent will belong"""
return self._action_space
@property
def unwrapped(self):
"""Completely unwrap this agent.
Returns the base non-wrapped Agent instance
"""
return self
def __str__(self):
return '<{} instance>'.format(type(self).__name__)
@abstractmethod
def act(self, observation):
"""Determine an action based upon the provided observation.
Args:
observation -- a sample from the supported observation space
Returns a sample from the action space
"""
@abstractmethod
def observe(self, pre_observation, action, reward, post_observation, done):
"""Lets the agent observe a sequence of observation => action => observation, reward.
Args:
pre_observation -- the observation before the action was taken
action -- the action which was taken
reward -- the reward which was given
post_observation -- the observation after the action was taken
done -- whether the environment was in a terminal state after the action was taken
"""
@abstractmethod
def save(self, path):
"""Save the agent to the specified path
Args:
path -- path to a location on the disk
"""
@abstractmethod
def load(self, path):
"""Load the agent from the specified path
Args:
path -- path to a location on the disk
"""
class AgentWrapper(Agent):
"""
Class which wraps an existing agent, allowing it to intercept the act and observe methods
as needed to add additional behavior.
"""
def __init__(self, agent):
assert isinstance(agent, Agent)
super(AgentWrapper, self).__init__(agent.observation_space, agent.action_space)
self._agent = agent
@property
def mode(self):
return self._agent.mode
@mode.setter
def mode(self, value):
self._agent.mode = value
@property
def agent(self):
"""The wrapped agent."""
return self._agent
@property
def unwrapped(self):
return self._agent.unwrapped
def __str__(self):
return '<{}{}>'.format(type(self).__name__, self._agent)
def __repr__(self):
return str(self)
@abstractmethod
def act(self, observation):
pass
@abstractmethod
def observe(self, pre_observation, action, reward, post_observation, done):
pass
def save(self, path):
self._agent.save(path)
def load(self, path):
self._agent.load(path)
class ActWrapper(AgentWrapper):
"""Agent wrapper which only wraps the act method."""
@abstractmethod
def act(self, observation):
pass
def observe(self, pre_observation, action, reward, post_observation, done):
self.agent.observe(pre_observation, action, reward, post_observation, done)
class ObserveWrapper(AgentWrapper):
"""Agent wrapper which only wraps the observe method."""
def act(self, observation):
return self.agent.act(observation)
@abstractmethod
def observe(self, pre_observation, action, reward, post_observation, done):
pass
class VisualizableWrapper(gym.Wrapper, Visualizable):
"""Class which exposes the metrics members of all wrapped environments."""
def __init__(self, env):
"""
Args:
env -- an environment which implements Visualizable at some level
of wrapping.
"""
super(VisualizableWrapper, self).__init__(env)
self._visualizable = []
# recursively unwrap the environment, gathering any metrics as we go
while isinstance(env, gym.Wrapper):
if isinstance(env, Visualizable):
self._visualizable.append(env)
env = env.env
if isinstance(env, Visualizable):
self._visualizable.append(env)
@property
def metrics(self):
result = []
for env in self._visualizable:
result.extend(env.metrics)
return result
def reset(self, **kwargs): #pylint: disable=E0202
return self.env.reset()
def step(self, action): #pylint: disable=E0202
return self.env.step(action)
class VisualizableAgentWrapper(AgentWrapper, Visualizable):
"""Class which exposes the metrics members of all wrapped agents"""
def __init__(self, agent):
super(VisualizableAgentWrapper, self).__init__(agent)
self._visualizable = []
# recursively unwrap the agent, gathering any metrics as we go
while isinstance(agent, AgentWrapper):
if isinstance(agent, Visualizable):
self._visualizable.append(agent)
agent = agent.agent
if isinstance(agent, Visualizable):
self._visualizable.append(agent)
@property
def metrics(self):
result = []
for agent in self._visualizable:
result.extend(agent.metrics)
return result
def act(self, observation):
return self.agent.act(observation)
def observe(self, pre_observation, action, reward, post_observation, done):
self.agent.observe(pre_observation, action, reward, post_observation, done)
class ExplorableGraph(Graph):
"""Graph wrapping for an Explorable environment."""
class Node(Node):
"""Node class for use by ExplorableGraph"""
def __init__(self, action, observation, key):
self.action = action
self.observation = observation
self._key = key
def matches(self, other):
return self.key == other.key
@property
def key(self):
return self._key
def __repr__(self):
return "{}=>{}".format(self.action, self.observation)
def __init__(self, env):
assert isinstance(env.unwrapped, Explorable)
self._env = env.unwrapped
def neighbors(self, node):
neighbors = []
pre_observation = node.observation
for action in self._env.available_actions(pre_observation):
post_observation, _, _ = self._env.try_step(pre_observation, action)
dist = self._env.distance(post_observation, pre_observation)
if not np.isclose(dist, 0.0):
neighbors.append(ExplorableGraph.Node(action,
post_observation,
self._env.hash(post_observation)))
return neighbors
def distance(self, node0, node1):
return self._env.distance(node0.observation, node1.observation)
@property
def nodes(self):
raise NotImplementedError
|
[
"os.path.dirname",
"collections.deque",
"json.dumps",
"numpy.isclose",
"logging.getLogger",
"csv.DictWriter"
] |
[((6846, 6871), 'collections.deque', 'deque', ([], {'maxlen': 'num_targets'}), '(maxlen=num_targets)\n', (6851, 6871), False, 'from collections import deque\n'), ((7992, 8019), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (8009, 8019), False, 'import logging\n'), ((8827, 8862), 'csv.DictWriter', 'csv.DictWriter', (['self._file', 'columns'], {}), '(self._file, columns)\n', (8841, 8862), False, 'import csv\n'), ((8107, 8135), 'os.path.dirname', 'os.path.dirname', (['output_path'], {}), '(output_path)\n', (8122, 8135), False, 'import os\n'), ((8162, 8190), 'os.path.dirname', 'os.path.dirname', (['output_path'], {}), '(output_path)\n', (8177, 8190), False, 'import os\n'), ((8783, 8805), 'json.dumps', 'json.dumps', (['self._keys'], {}), '(self._keys)\n', (8793, 8805), False, 'import json\n'), ((17170, 17191), 'numpy.isclose', 'np.isclose', (['dist', '(0.0)'], {}), '(dist, 0.0)\n', (17180, 17191), True, 'import numpy as np\n')]
|
import cv2
import numpy as np
class Color_Detection(object):
def __init__(self):
self.ColorStandard = np.array([[255, 0, 0], # red
[0, 0, 255], # blue
[0, 255, 0], # green
[0, 255, 255]]) # yellow
# Euclidean Distance, Red, Blue, Green, Yellow
self.ColorDistance_threshold = [150, 160, 200, 200]
# HSV space threshold
# H_min, H_max, S_min, S_max
self.hsv_threshold = np.array([[120, 130, 160, 180], # red
[15, 25, 85, 105], # blue
[30, 40, 200, 220], # green
[80, 90, 95, 115]]) # yellow
# according to the pixel point to get the color
def getPositionColor(self, color_image, depth_image, x, y, m=12):
hsv_color_image = cv2.cvtColor(color_image, cv2.COLOR_BGR2HSV)
# hsv_depth_image = cv2.cvtColor(depth_image, cv2.COLOR_BGR2HSV)
hsv_depth_image = depth_image
if x < m or x > 223-m or y < m or y > 223-m:
m = min(abs(x-0), abs(x-223), abs(y-0), abs(y-223))
obj_color = self.get_obj_color(hsv_color_image, hsv_depth_image, x, y, m)
else:
obj_color = self.get_obj_color(hsv_color_image, hsv_depth_image, x, y, m)
return obj_color
def get_obj_color(self, hsv_color_image, hsv_depth_image, x, y, m):
# store the color of the sample point
color = np.zeros((2 * m + 1, 2 * m + 1, 3), dtype=int)
each_point_H = []
each_point_S = []
vaild_depth_pixel = []
depth_threshold = 0.02 # the height of the blocks
red_count = 0
blue_count = 0
green_count = 0
yellow_count = 0
for row in range(-m, m + 1):
for col in range(-m, m + 1):
if hsv_depth_image[y+col][x+row] > depth_threshold:
vaild_depth_pixel.append([y+col, x+row])
if vaild_depth_pixel is not None:
for index in range(len(vaild_depth_pixel)):
each_point_H.append(hsv_color_image[vaild_depth_pixel[index][0], vaild_depth_pixel[index][1]][0])
each_point_S.append(hsv_color_image[vaild_depth_pixel[index][0], vaild_depth_pixel[index][1]][1])
for i in range(len(each_point_H)):
if self.hsv_threshold[0][0] <= each_point_H[i] <= self.hsv_threshold[0][1]:
red_count += 1
if self.hsv_threshold[1][0] <= each_point_H[i] <= self.hsv_threshold[1][1]:
blue_count += 1
if self.hsv_threshold[2][0] <= each_point_H[i] <= self.hsv_threshold[2][1]:
green_count += 1
if self.hsv_threshold[3][0] <= each_point_H[i] <= self.hsv_threshold[3][1]:
yellow_count += 1
count = [red_count, blue_count, green_count, yellow_count]
print('count:', count)
if count.count(0) == 4:
object_color = -1
else:
max_index = count.index(max(count))
object_color = max_index
else:
# -1 represent cannot recognize the color of the grasped object
object_color = -1
return object_color
|
[
"cv2.cvtColor",
"numpy.zeros",
"numpy.array"
] |
[((116, 180), 'numpy.array', 'np.array', (['[[255, 0, 0], [0, 0, 255], [0, 255, 0], [0, 255, 255]]'], {}), '([[255, 0, 0], [0, 0, 255], [0, 255, 0], [0, 255, 255]])\n', (124, 180), True, 'import numpy as np\n'), ((558, 652), 'numpy.array', 'np.array', (['[[120, 130, 160, 180], [15, 25, 85, 105], [30, 40, 200, 220], [80, 90, 95, 115]\n ]'], {}), '([[120, 130, 160, 180], [15, 25, 85, 105], [30, 40, 200, 220], [80,\n 90, 95, 115]])\n', (566, 652), True, 'import numpy as np\n'), ((961, 1005), 'cv2.cvtColor', 'cv2.cvtColor', (['color_image', 'cv2.COLOR_BGR2HSV'], {}), '(color_image, cv2.COLOR_BGR2HSV)\n', (973, 1005), False, 'import cv2\n'), ((1584, 1630), 'numpy.zeros', 'np.zeros', (['(2 * m + 1, 2 * m + 1, 3)'], {'dtype': 'int'}), '((2 * m + 1, 2 * m + 1, 3), dtype=int)\n', (1592, 1630), True, 'import numpy as np\n')]
|
import os
from scipy.io import loadmat, matlab
from scipy.signal import spectrogram, find_peaks, medfilt
import pandas as pd
import numpy as np
from joblib import Parallel, delayed
# remove these exercises from targets since there are no data samples
ignore_exercises = ['<Initial Activity>', 'Arm straight up', 'Invalid', 'Non-Exercise',
'Note', 'Tap IMU Device', 'Tap Right Device']
# load in the 75 different exercises available in the full data
exercises = pd.read_csv('codes/exercises.txt', header=None, names=['exercise']) # assumes the cwd is highest level
exercises = exercises.where(~exercises.exercise.isin(ignore_exercises)).dropna()
# 5 samples of exercise to classify for the simple model
targets_idx = {
'Crunch': 10,
'Jumping Jacks': 23,
'Running (treadmill)': 42,
'Squat': 50,
'Walk': 70
}
# Spectrogram Parameters for 'spec_gram'
spec_params = dict(fs=50, window='hamming',
nperseg=256, nfft=500,
noverlap=256 - 50, # half a second time difference
detrend='constant',
scaling='spectrum',
)
pad_size = ((spec_params['nperseg'] - spec_params['noverlap'],), (0,))
def load_mat(filename):
"""
This function should be called instead of direct scipy.io.loadmat
as it cures the problem of not properly recovering python dictionaries
from mat files. It calls the function check keys to cure all entries
which are still mat-objects
"""
def _check_vars(d):
"""
Checks if entries in dictionary are mat-objects. If yes
todict is called to change them to nested dictionaries
"""
for key in d:
if isinstance(d[key], matlab.mio5_params.mat_struct):
d[key] = _todict(d[key])
elif isinstance(d[key], np.ndarray):
d[key] = _toarray(d[key])
return d
def _todict(matobj):
"""
A recursive function which constructs from matobjects nested dictionaries
"""
d = {}
for strg in matobj._fieldnames:
elem = matobj.__dict__[strg]
if isinstance(elem, matlab.mio5_params.mat_struct):
d[strg] = _todict(elem)
elif isinstance(elem, np.ndarray):
d[strg] = _toarray(elem)
else:
d[strg] = elem
return d
def _toarray(ndarray):
"""
A recursive function which constructs ndarray from cellarrays
(which are loaded as numpy ndarrays), recursing into the elements
if they contain matobjects.
"""
if ndarray.dtype != 'float64':
elem_list = []
for sub_elem in ndarray:
if isinstance(sub_elem, matlab.mio5_params.mat_struct):
elem_list.append(_todict(sub_elem))
elif isinstance(sub_elem, np.ndarray):
elem_list.append(_toarray(sub_elem))
else:
elem_list.append(sub_elem)
return np.array(elem_list)
else:
return ndarray
data = loadmat(filename, struct_as_record=False, squeeze_me=True)
return _check_vars(data)
def spec_gram(subj, spec_params=spec_params, pad_size=pad_size):
"""
Args:
subj (numpy.ndarray): nd
spec_params:
pad_size:
Returns:
"""
spec3d = []
pad_sig = pd.DataFrame(np.pad(subj, pad_size, 'symmetric'), columns=['time', 'x', 'y', 'z'])
for d in ['x', 'y', 'z']:
f, t, Sxx = spectrogram(pad_sig[d], **spec_params)
spec3d.append(Sxx)
return f, t, spec3d
def log_freqs(nfft=None, fmin=1e-1, fs=50, bpo=10):
"""
Calculate a log-frequency spectrogram
% S is spectrogram to log-transform;
% nfft is parent FFT window; fs is the source samplerate.
% Optional FMIN is the lowest frequency to display (1mHz);
% BPO is the number of bins per octave (10).
% MX returns the nlogbin x nfftbin mapping matrix;
% sqrt(MX'*(Y.^2)) is an approximation to the original FFT
% spectrogram that Y is based on, suitably blurred by going
% through the log-F domain.
"""
# Ratio between adjacent frequencies in log-f axis
fratio = 2 ** (1 / bpo)
# How many bins in log-f axis
nbins = int(np.log2((fs / 2) / fmin) // np.log2(fratio)) + 1
# nfft is parent FFT window
if nfft is None:
nfft = 500
# Freqs corresponding to each bin in FFT
fftfrqs = np.arange(0, nfft / 2 + 1).reshape(1, -1) * (fs / nfft)
nfftbins = int(nfft / 2 + 1)
# Freqs corresponding to each bin in log F output
logffrqs = fmin * np.exp(np.log(2) * np.arange(0, nbins).reshape(1, -1) / bpo)
# Bandwidths of each bin in log F
logfbws = logffrqs * (fratio - 1)
# .. but bandwidth cannot be less than FFT binwidth
logfbws = np.maximum(logfbws, fs / nfft)
# Controls how much overlap there is between adjacent bands
ovfctr = 0.54 # Adjusted by hand to make sum(mx'*mx) close to 1.0
# Weighting matrix mapping energy in FFT bins to logF bins
# is a set of Gaussian profiles depending on the difference in
# frequencies, scaled by the bandwidth of that bin
freqdiff = ((np.tile(logffrqs.T, (1, nfftbins)) - np.tile(fftfrqs, (nbins, 1)))
/ np.tile(ovfctr * logfbws.T, (1, nfftbins)))
mx = np.exp(-0.5 * freqdiff ** 2)
# Normalize rows by sqrt(E), so multiplying by mx' gets approx orig spec back
mx = mx / np.tile(np.sqrt(2 * (mx ** 2).sum(1).reshape(-1, 1)), (1, nfftbins))
return logffrqs, mx
def log_specgram(S, mx=None):
if mx is None:
logffrqs, mx = log_freqs()
# Perform mapping in magnitude-squared (energy) domain
return np.sqrt(mx @ (np.abs(S) ** 2))
def signal_feats(s):
peaks, p_dict = find_peaks(medfilt(s, 5), prominence=0.1, width=5)
avg_peak_dist = np.diff(peaks).mean()
print('avg peak dist: ', round(avg_peak_dist, 2),
'\tavg prom: ', round(p_dict['prominences'].mean(), 2),
'\tavg width: ', round(p_dict['width_heights'].mean(), 2))
return peaks, p_dict
def segment_signal(data, targets=None, win=250, stride=50):
"""
Segment signal of an exercise recording into chunks of designated window size.
Args:
data (dict): signal data in dict of a recording of exercise from a subject with keys structure of
{'data':{accelDataMatrix':[...], 'gyroDataMatrix':[...]}}
targets (dict): exercises with their index in the 'exercises.txt' and in 'singleonly.mat' file
win: window of the signal to look at (default: 250 samples = 5 seconds)
stride: step-size of samples to skip for the next window (default: 50 samples = 1 seconds)
*** Assumes the sampling raate of the motion data is 50 Hz.
Returns:
A generator yielding windowed signal.
"""
if data['activityName'] not in targets: # only segment signal if there the activity is in the targets
return
signal = np.hstack((data['data']['accelDataMatrix'][:, 1:], data['data']['gyroDataMatrix'][:, 1:]))
# Data sanity check: only process the data for both accel & gyro that at least has the same samples as the window
# size
if signal.shape[0] > win:
if targets is None:
targets = targets_idx
ex = np.array(
[1 if k == data['activityName'] else 0 for k in targets]) # convert the exercise name to interger to
# pass into CNN model
steps = (signal.shape[0] - win) // stride if signal.shape[0] > 300 else 1
segments = np.vstack([[signal[s * stride:s * stride + win], ex] for s in range(steps)])
if isinstance(segments, np.ndarray):
return segments
|
[
"numpy.pad",
"numpy.maximum",
"numpy.abs",
"numpy.log",
"scipy.io.loadmat",
"pandas.read_csv",
"numpy.log2",
"scipy.signal.medfilt",
"numpy.hstack",
"numpy.diff",
"numpy.array",
"numpy.exp",
"scipy.signal.spectrogram",
"numpy.tile",
"numpy.arange"
] |
[((483, 550), 'pandas.read_csv', 'pd.read_csv', (['"""codes/exercises.txt"""'], {'header': 'None', 'names': "['exercise']"}), "('codes/exercises.txt', header=None, names=['exercise'])\n", (494, 550), True, 'import pandas as pd\n'), ((3151, 3209), 'scipy.io.loadmat', 'loadmat', (['filename'], {'struct_as_record': '(False)', 'squeeze_me': '(True)'}), '(filename, struct_as_record=False, squeeze_me=True)\n', (3158, 3209), False, 'from scipy.io import loadmat, matlab\n'), ((4926, 4956), 'numpy.maximum', 'np.maximum', (['logfbws', '(fs / nfft)'], {}), '(logfbws, fs / nfft)\n', (4936, 4956), True, 'import numpy as np\n'), ((5434, 5462), 'numpy.exp', 'np.exp', (['(-0.5 * freqdiff ** 2)'], {}), '(-0.5 * freqdiff ** 2)\n', (5440, 5462), True, 'import numpy as np\n'), ((7129, 7224), 'numpy.hstack', 'np.hstack', (["(data['data']['accelDataMatrix'][:, 1:], data['data']['gyroDataMatrix'][:, 1:])"], {}), "((data['data']['accelDataMatrix'][:, 1:], data['data'][\n 'gyroDataMatrix'][:, 1:]))\n", (7138, 7224), True, 'import numpy as np\n'), ((3464, 3499), 'numpy.pad', 'np.pad', (['subj', 'pad_size', '"""symmetric"""'], {}), "(subj, pad_size, 'symmetric')\n", (3470, 3499), True, 'import numpy as np\n'), ((3584, 3622), 'scipy.signal.spectrogram', 'spectrogram', (['pad_sig[d]'], {}), '(pad_sig[d], **spec_params)\n', (3595, 3622), False, 'from scipy.signal import spectrogram, find_peaks, medfilt\n'), ((5381, 5423), 'numpy.tile', 'np.tile', (['(ovfctr * logfbws.T)', '(1, nfftbins)'], {}), '(ovfctr * logfbws.T, (1, nfftbins))\n', (5388, 5423), True, 'import numpy as np\n'), ((5893, 5906), 'scipy.signal.medfilt', 'medfilt', (['s', '(5)'], {}), '(s, 5)\n', (5900, 5906), False, 'from scipy.signal import spectrogram, find_peaks, medfilt\n'), ((7454, 7522), 'numpy.array', 'np.array', (["[(1 if k == data['activityName'] else 0) for k in targets]"], {}), "([(1 if k == data['activityName'] else 0) for k in targets])\n", (7462, 7522), True, 'import numpy as np\n'), ((3078, 3097), 'numpy.array', 'np.array', (['elem_list'], {}), '(elem_list)\n', (3086, 3097), True, 'import numpy as np\n'), ((5296, 5330), 'numpy.tile', 'np.tile', (['logffrqs.T', '(1, nfftbins)'], {}), '(logffrqs.T, (1, nfftbins))\n', (5303, 5330), True, 'import numpy as np\n'), ((5333, 5361), 'numpy.tile', 'np.tile', (['fftfrqs', '(nbins, 1)'], {}), '(fftfrqs, (nbins, 1))\n', (5340, 5361), True, 'import numpy as np\n'), ((5954, 5968), 'numpy.diff', 'np.diff', (['peaks'], {}), '(peaks)\n', (5961, 5968), True, 'import numpy as np\n'), ((4371, 4393), 'numpy.log2', 'np.log2', (['(fs / 2 / fmin)'], {}), '(fs / 2 / fmin)\n', (4378, 4393), True, 'import numpy as np\n'), ((4399, 4414), 'numpy.log2', 'np.log2', (['fratio'], {}), '(fratio)\n', (4406, 4414), True, 'import numpy as np\n'), ((4552, 4578), 'numpy.arange', 'np.arange', (['(0)', '(nfft / 2 + 1)'], {}), '(0, nfft / 2 + 1)\n', (4561, 4578), True, 'import numpy as np\n'), ((5822, 5831), 'numpy.abs', 'np.abs', (['S'], {}), '(S)\n', (5828, 5831), True, 'import numpy as np\n'), ((4725, 4734), 'numpy.log', 'np.log', (['(2)'], {}), '(2)\n', (4731, 4734), True, 'import numpy as np\n'), ((4737, 4756), 'numpy.arange', 'np.arange', (['(0)', 'nbins'], {}), '(0, nbins)\n', (4746, 4756), True, 'import numpy as np\n')]
|
# Conversion of Washington DC Taxi Trips (2017): https://www.kaggle.com/bvc5283/dc-taxi-trips
import argparse
import pandas as pd
import numpy as np
def convertData(inFile, outFile, startDate, endDate):
df = pd.read_csv(inFile)
df_out = df[['StartDateTime',
'OriginLatitude', 'OriginLongitude',
'DestinationLatitude', 'DestinationLongitude']].rename(columns={
'StartDateTime': 'request time',
'OriginLatitude': 'src lat',
'OriginLongitude': 'src lng',
'DestinationLatitude': 'dst lat',
'DestinationLongitude': 'dst lng'
})
df_out['volume'] = 1
# Select a day of data
df_out['request time'] = pd.to_datetime(df_out['request time'], format="%Y-%m-%d %H:%M:%S", errors='coerce')
df_out.dropna(subset=['request time'], inplace=True) # Drop rows with invalid date format
df_out['request time'] = df_out['request time'].dt.tz_localize(None)
df_out['request time'] = df_out['request time'].dt.strftime("%Y-%m-%d %H:%M:%S")
mask = ((df_out['request time'] >= startDate) & (df_out['request time'] < endDate)).values
df_out = df_out.iloc[mask]
# Filter abnormal data: In Washington DC, any coordinate as 0 is abnormal
df_out.dropna(subset=['src lat', 'src lng', 'dst lat', 'dst lng'], inplace=True)
mask = ((df_out['src lat'] * df_out['src lng'] * df_out['dst lat'] * df_out['dst lng'] != 0) &
(df_out['src lat'] >= -90) & (df_out['src lat'] <= 90) &
(df_out['dst lat'] >= -90) & (df_out['dst lat'] <= 90) &
(df_out['src lng'] >= -180) & (df_out['src lng'] <= 180) &
(df_out['dst lng'] >= -180) & (df_out['dst lng'] <= 180)).values
df_out = df_out.iloc[mask]
# Sort by Date
df_out.sort_values(by=['request time'], inplace=True)
missingStat(df_out)
df_out.to_csv(outFile, index=False)
def missingStat(df):
nullSheet = df.isnull().sum()
nNull = np.sum(nullSheet)
total = np.prod(df.shape)
print('\nMissing Count:')
print(nullSheet)
print('Missing Percentage = %.2f / %.2f = %.2f%%\n' % (float(nNull), float(total), nNull / total * 100))
if __name__ == '__main__':
"""
Usage Example:
python dc2017.py -i taxi_final.csv -o dc2017.csv -sd 2017-06-18 -ed 2017-06-25
"""
# Command Line Arguments
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input', type=str, default='taxi_final.csv',
help='The input data file to be converted, default={}'.format('taxi_final.csv'))
parser.add_argument('-o', '--output', type=str, default='dc2017.csv',
help='The output converted data file, default={}'.format('ny2016.csv'))
parser.add_argument('-sd', '--startDate', type=str, default='2017-06-18',
help='The start date to filter (inclusive), default={}'.format('2017-06-18'))
parser.add_argument('-ed', '--endDate', type=str, default='2017-06-25',
help='The end date to filter (exclusive), default={}'.format('2017-06-25'))
FLAGS, unparsed = parser.parse_known_args()
convertData(FLAGS.input, FLAGS.output, FLAGS.startDate, FLAGS.endDate)
|
[
"numpy.sum",
"argparse.ArgumentParser",
"pandas.read_csv",
"pandas.to_datetime",
"numpy.prod"
] |
[((214, 233), 'pandas.read_csv', 'pd.read_csv', (['inFile'], {}), '(inFile)\n', (225, 233), True, 'import pandas as pd\n'), ((692, 780), 'pandas.to_datetime', 'pd.to_datetime', (["df_out['request time']"], {'format': '"""%Y-%m-%d %H:%M:%S"""', 'errors': '"""coerce"""'}), "(df_out['request time'], format='%Y-%m-%d %H:%M:%S', errors=\n 'coerce')\n", (706, 780), True, 'import pandas as pd\n'), ((1944, 1961), 'numpy.sum', 'np.sum', (['nullSheet'], {}), '(nullSheet)\n', (1950, 1961), True, 'import numpy as np\n'), ((1974, 1991), 'numpy.prod', 'np.prod', (['df.shape'], {}), '(df.shape)\n', (1981, 1991), True, 'import numpy as np\n'), ((2345, 2370), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (2368, 2370), False, 'import argparse\n')]
|
import numpy as np
from sklearn import linear_model
reg = linear_model.LinearRegression(fit_intercept=True)
def get_doubling_time_via_regression(in_array):
''' Use a linear regression to approximate the doubling rate'''
y = np.array(in_array)
X = np.arange(-1,2).reshape(-1, 1)
assert len(in_array)==3
reg.fit(X,y)
intercept=reg.intercept_
slope=reg.coef_
return intercept/slope
if __name__ == '__main__':
test_data = np.array([2, 4, 6])
result = get_doubling_time_via_regression(test_data)
print('The test slope is: ' + str(result))
|
[
"sklearn.linear_model.LinearRegression",
"numpy.array",
"numpy.arange"
] |
[((59, 108), 'sklearn.linear_model.LinearRegression', 'linear_model.LinearRegression', ([], {'fit_intercept': '(True)'}), '(fit_intercept=True)\n', (88, 108), False, 'from sklearn import linear_model\n'), ((239, 257), 'numpy.array', 'np.array', (['in_array'], {}), '(in_array)\n', (247, 257), True, 'import numpy as np\n'), ((472, 491), 'numpy.array', 'np.array', (['[2, 4, 6]'], {}), '([2, 4, 6])\n', (480, 491), True, 'import numpy as np\n'), ((266, 282), 'numpy.arange', 'np.arange', (['(-1)', '(2)'], {}), '(-1, 2)\n', (275, 282), True, 'import numpy as np\n')]
|
"""Script filename: example_optFrog.py
Exemplary calculation of an optFrog trace for data obtained from
the numerical propagation of a short and intense few-cycle optical
pulse in presence of the refractive index profile of an endlessly single
mode photonic crystal fiber.
"""
import sys
import numpy as np
import numpy.fft as nfft
from optfrog import optFrog
from figure import spectrogramFigure
def main():
tMin= -500.0
tMax= 5800.0
wMin= 0.75
wMax= 3.25
s0 = 36.0
a0 = 0.0
fName = './data/exampleData_pulsePropagation.npz'
oName="./FIGS/fig_optFrog_ESM_alpha%3.4lf.png"%(a0)
def fetchData(fileLoc):
data = np.load(fileLoc)
return data['t'], data['Et']
def windowFuncGauss(s0):
return lambda t: np.exp(-t**2/2/s0/s0)/np.sqrt(2.*np.pi)/s0
t,Et = fetchData(fName)
res = optFrog(t,Et,windowFuncGauss,alpha=a0,tLim=(tMin,tMax,10), wLim=(wMin,wMax,3))
spectrogramFigure((t,Et),res,oName=oName)
main()
# EOF: example_optFrog.py
|
[
"numpy.load",
"optfrog.optFrog",
"numpy.exp",
"figure.spectrogramFigure",
"numpy.sqrt"
] |
[((851, 941), 'optfrog.optFrog', 'optFrog', (['t', 'Et', 'windowFuncGauss'], {'alpha': 'a0', 'tLim': '(tMin, tMax, 10)', 'wLim': '(wMin, wMax, 3)'}), '(t, Et, windowFuncGauss, alpha=a0, tLim=(tMin, tMax, 10), wLim=(wMin,\n wMax, 3))\n', (858, 941), False, 'from optfrog import optFrog\n'), ((934, 978), 'figure.spectrogramFigure', 'spectrogramFigure', (['(t, Et)', 'res'], {'oName': 'oName'}), '((t, Et), res, oName=oName)\n', (951, 978), False, 'from figure import spectrogramFigure\n'), ((659, 675), 'numpy.load', 'np.load', (['fileLoc'], {}), '(fileLoc)\n', (666, 675), True, 'import numpy as np\n'), ((768, 797), 'numpy.exp', 'np.exp', (['(-t ** 2 / 2 / s0 / s0)'], {}), '(-t ** 2 / 2 / s0 / s0)\n', (774, 797), True, 'import numpy as np\n'), ((790, 810), 'numpy.sqrt', 'np.sqrt', (['(2.0 * np.pi)'], {}), '(2.0 * np.pi)\n', (797, 810), True, 'import numpy as np\n')]
|
import cv2
import numpy as np
import os
aaa = cv2.imread('seed0075.png')
aaa2 = cv2.imread('seed00752.png')
ddd = np.mean((aaa2 - aaa)**2)
print('ddd=%.6f' % ddd)
print()
|
[
"cv2.imread",
"numpy.mean"
] |
[((51, 77), 'cv2.imread', 'cv2.imread', (['"""seed0075.png"""'], {}), "('seed0075.png')\n", (61, 77), False, 'import cv2\n'), ((85, 112), 'cv2.imread', 'cv2.imread', (['"""seed00752.png"""'], {}), "('seed00752.png')\n", (95, 112), False, 'import cv2\n'), ((120, 146), 'numpy.mean', 'np.mean', (['((aaa2 - aaa) ** 2)'], {}), '((aaa2 - aaa) ** 2)\n', (127, 146), True, 'import numpy as np\n')]
|
import unittest
import numpy as np
from chainer0 import Variable, Chain
from chainer0.links import EmbedID, Linear
from chainer0.functions import sigmoid, tanh, mean_squared_error
from chainer0.optimizers import SGD
class TestEmbedModel(unittest.TestCase):
def test_train(self):
x = Variable(np.array([1, 2, 1, 2]))
target = Variable(np.array([[0], [1], [0], [1]]))
model = Chain(
embed=EmbedID(5, 3),
linear=Linear(3, 1),
)
def forward(x):
x = model.embed(x)
x = tanh(x)
x = model.linear(x)
x = sigmoid(x)
return x
optimizer = SGD(lr=0.5)
optimizer.setup(model)
np.random.seed(0)
model.embed.W.data = np.random.rand(5, 3)
model.linear.W.data = np.random.rand(3, 1)
log = []
for i in range(10):
pred = forward(x)
loss = mean_squared_error(pred, target)
model.cleargrads()
loss.backward()
optimizer.update()
log.append(loss.data)
expected = np.array([
0.25458621375800417,
0.24710456626288174,
0.24017425722643587,
0.23364699169761943,
0.22736806682064464,
0.2211879225084124,
0.2149697611450082,
0.20859448689275056,
0.2019642998089552,
0.195005940360243
])
res = np.allclose(np.array(log), expected)
self.assertTrue(res)
|
[
"chainer0.functions.mean_squared_error",
"numpy.random.seed",
"chainer0.functions.tanh",
"chainer0.functions.sigmoid",
"numpy.array",
"chainer0.optimizers.SGD",
"numpy.random.rand",
"chainer0.links.EmbedID",
"chainer0.links.Linear"
] |
[((670, 681), 'chainer0.optimizers.SGD', 'SGD', ([], {'lr': '(0.5)'}), '(lr=0.5)\n', (673, 681), False, 'from chainer0.optimizers import SGD\n'), ((722, 739), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (736, 739), True, 'import numpy as np\n'), ((769, 789), 'numpy.random.rand', 'np.random.rand', (['(5)', '(3)'], {}), '(5, 3)\n', (783, 789), True, 'import numpy as np\n'), ((820, 840), 'numpy.random.rand', 'np.random.rand', (['(3)', '(1)'], {}), '(3, 1)\n', (834, 840), True, 'import numpy as np\n'), ((1114, 1344), 'numpy.array', 'np.array', (['[0.25458621375800417, 0.24710456626288174, 0.24017425722643587, \n 0.23364699169761943, 0.22736806682064464, 0.2211879225084124, \n 0.2149697611450082, 0.20859448689275056, 0.2019642998089552, \n 0.195005940360243]'], {}), '([0.25458621375800417, 0.24710456626288174, 0.24017425722643587, \n 0.23364699169761943, 0.22736806682064464, 0.2211879225084124, \n 0.2149697611450082, 0.20859448689275056, 0.2019642998089552, \n 0.195005940360243])\n', (1122, 1344), True, 'import numpy as np\n'), ((307, 329), 'numpy.array', 'np.array', (['[1, 2, 1, 2]'], {}), '([1, 2, 1, 2])\n', (315, 329), True, 'import numpy as np\n'), ((357, 387), 'numpy.array', 'np.array', (['[[0], [1], [0], [1]]'], {}), '([[0], [1], [0], [1]])\n', (365, 387), True, 'import numpy as np\n'), ((561, 568), 'chainer0.functions.tanh', 'tanh', (['x'], {}), '(x)\n', (565, 568), False, 'from chainer0.functions import sigmoid, tanh, mean_squared_error\n'), ((617, 627), 'chainer0.functions.sigmoid', 'sigmoid', (['x'], {}), '(x)\n', (624, 627), False, 'from chainer0.functions import sigmoid, tanh, mean_squared_error\n'), ((936, 968), 'chainer0.functions.mean_squared_error', 'mean_squared_error', (['pred', 'target'], {}), '(pred, target)\n', (954, 968), False, 'from chainer0.functions import sigmoid, tanh, mean_squared_error\n'), ((1491, 1504), 'numpy.array', 'np.array', (['log'], {}), '(log)\n', (1499, 1504), True, 'import numpy as np\n'), ((431, 444), 'chainer0.links.EmbedID', 'EmbedID', (['(5)', '(3)'], {}), '(5, 3)\n', (438, 444), False, 'from chainer0.links import EmbedID, Linear\n'), ((465, 477), 'chainer0.links.Linear', 'Linear', (['(3)', '(1)'], {}), '(3, 1)\n', (471, 477), False, 'from chainer0.links import EmbedID, Linear\n')]
|
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class LICACritic(nn.Module):
def __init__(self, scheme, args):
super(LICACritic, self).__init__()
self.args = args
self.n_actions = args.n_actions
self.n_agents = args.n_agents
self.output_type = "q"
# Set up network layers
self.state_dim = int(np.prod(args.state_shape))
self.embed_dim = args.mixing_embed_dim * self.n_agents * self.n_actions
self.hid_dim = args.mixing_embed_dim
if getattr(args, "hypernet_layers", 1) == 1:
self.hyper_w_1 = nn.Linear(self.state_dim, self.embed_dim)
self.hyper_w_final = nn.Linear(self.state_dim, self.embed_dim)
elif getattr(args, "hypernet_layers", 1) == 2:
self.hyper_w_1 = nn.Sequential(nn.Linear(self.state_dim, self.embed_dim),
nn.ReLU(),
nn.Linear(self.embed_dim, self.embed_dim))
self.hyper_w_final = nn.Sequential(nn.Linear(self.state_dim, self.hid_dim),
nn.ReLU(),
nn.Linear(self.hid_dim, self.hid_dim))
elif getattr(args, "hypernet_layers", 1) > 2:
raise Exception("Sorry >2 hypernet layers is not implemented!")
else:
raise Exception("Error setting number of hypernet layers.")
# State dependent bias for hidden layer
self.hyper_b_1 = nn.Linear(self.state_dim, self.hid_dim)
self.hyper_b_2 = nn.Sequential(nn.Linear(self.state_dim, self.hid_dim),
nn.ReLU(),
nn.Linear(self.hid_dim, 1))
def forward(self, act, states):
bs = states.size(0)
states = states.reshape(-1, self.state_dim)
action_probs = act.reshape(-1, 1, self.n_agents * self.n_actions)
w1 = self.hyper_w_1(states)
b1 = self.hyper_b_1(states)
w1 = w1.view(-1, self.n_agents * self.n_actions, self.hid_dim)
b1 = b1.view(-1, 1, self.hid_dim)
h = torch.relu(torch.bmm(action_probs, w1) + b1)
w_final = self.hyper_w_final(states)
w_final = w_final.view(-1, self.hid_dim, 1)
h2 = torch.bmm(h, w_final)
b2 = self.hyper_b_2(states).view(-1, 1, 1)
q = h2 + b2
q = q.view(bs, -1, 1)
return q
|
[
"torch.nn.ReLU",
"torch.bmm",
"numpy.prod",
"torch.nn.Linear"
] |
[((1544, 1583), 'torch.nn.Linear', 'nn.Linear', (['self.state_dim', 'self.hid_dim'], {}), '(self.state_dim, self.hid_dim)\n', (1553, 1583), True, 'import torch.nn as nn\n'), ((2313, 2334), 'torch.bmm', 'torch.bmm', (['h', 'w_final'], {}), '(h, w_final)\n', (2322, 2334), False, 'import torch\n'), ((396, 421), 'numpy.prod', 'np.prod', (['args.state_shape'], {}), '(args.state_shape)\n', (403, 421), True, 'import numpy as np\n'), ((632, 673), 'torch.nn.Linear', 'nn.Linear', (['self.state_dim', 'self.embed_dim'], {}), '(self.state_dim, self.embed_dim)\n', (641, 673), True, 'import torch.nn as nn\n'), ((707, 748), 'torch.nn.Linear', 'nn.Linear', (['self.state_dim', 'self.embed_dim'], {}), '(self.state_dim, self.embed_dim)\n', (716, 748), True, 'import torch.nn as nn\n'), ((1624, 1663), 'torch.nn.Linear', 'nn.Linear', (['self.state_dim', 'self.hid_dim'], {}), '(self.state_dim, self.hid_dim)\n', (1633, 1663), True, 'import torch.nn as nn\n'), ((1696, 1705), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (1703, 1705), True, 'import torch.nn as nn\n'), ((1738, 1764), 'torch.nn.Linear', 'nn.Linear', (['self.hid_dim', '(1)'], {}), '(self.hid_dim, 1)\n', (1747, 1764), True, 'import torch.nn as nn\n'), ((2167, 2194), 'torch.bmm', 'torch.bmm', (['action_probs', 'w1'], {}), '(action_probs, w1)\n', (2176, 2194), False, 'import torch\n'), ((847, 888), 'torch.nn.Linear', 'nn.Linear', (['self.state_dim', 'self.embed_dim'], {}), '(self.state_dim, self.embed_dim)\n', (856, 888), True, 'import torch.nn as nn\n'), ((933, 942), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (940, 942), True, 'import torch.nn as nn\n'), ((987, 1028), 'torch.nn.Linear', 'nn.Linear', (['self.embed_dim', 'self.embed_dim'], {}), '(self.embed_dim, self.embed_dim)\n', (996, 1028), True, 'import torch.nn as nn\n'), ((1077, 1116), 'torch.nn.Linear', 'nn.Linear', (['self.state_dim', 'self.hid_dim'], {}), '(self.state_dim, self.hid_dim)\n', (1086, 1116), True, 'import torch.nn as nn\n'), ((1161, 1170), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (1168, 1170), True, 'import torch.nn as nn\n'), ((1215, 1252), 'torch.nn.Linear', 'nn.Linear', (['self.hid_dim', 'self.hid_dim'], {}), '(self.hid_dim, self.hid_dim)\n', (1224, 1252), True, 'import torch.nn as nn\n')]
|
'''
Created with love by Sigmoid
@Author - <NAME> - <EMAIL>
'''
# Importing all libraries
import numpy as np
import pandas as pd
from scipy.stats import norm
import sys
from .erorrs import NotBinaryData, NoSuchColumn
def warn(*args, **kwargs):
pass
import warnings
warnings.warn = warn
class MTDF:
def __init__(self, binary_columns : list = None, seed : 'int > 0' = 42) -> None:
'''
The constructor of the MTDF.
:param binary_columns: list, default = None
The list of columns that should have binary values after balancing.
:param seed: int > 0, default = 42
The seed used for random number generator.
'''
if binary_columns is None:
self.__binarize = False
else:
self.__binarize = True
self.__binary_columns = binary_columns
self.seed = seed
np.random.seed(self.seed)
def __infinity_check(self, matrix : 'np.array') -> 'np.array':
'''
This function replaces the infinity and -infinity values with the minimal and maximal float python values.
:param matrix: 'np.array'
The numpy array that was generated my the algorithm.
:return: 'np.array'
The numpy array with the infinity replaced values.
'''
matrix[matrix == -np.inf] = sys.float_info.min
matrix[matrix == np.inf] = sys.float_info.max
return matrix
def __to_binary(self) -> None:
'''
If the :param binary_columns: is set to True then the intermediate values in binary columns will be rounded.
'''
for column_name in self.__binary_columns:
serie = self.synthetic_df[column_name].values
threshold = (self.df[column_name].max() + self.df[column_name].min()) / 2
for i in range(len(serie)):
if serie[i] >= threshold:
serie[i] = self.df[column_name].max()
else:
serie[i] = self.df[column_name].min()
self.synthetic_df[column_name] = serie
def balance(self, df : pd.DataFrame, target : str):
'''
The balance function.
:param df: pd.DataFrame
The pandas Data Frame to apply the balancer.
:param target: str
The name of the target column.
:return: pd.DataFrame
A pandas Data Frame
'''
# Creating an internal copy of the data frame.
self.df = df.copy()
self.target = target
# Checking if the target string based t algorithm is present in the data frame.
if target not in self.df.columns:
raise NoSuchColumn(f"{target} isn't a column of passed data frame")
# Checking if the target column is a binary one.
if len(self.df[target].unique()) != 2:
raise NotBinaryData(f"{target} column isn't a binary column")
# Getting the column names that are not the target one.
self.X_columns = [column for column in self.df.columns if column != target]
# Calculating the variance vector.
variance = self.df[self.X_columns].var(axis=0).values
# Calculating the Uset.
uset = (self.df[self.X_columns].min(axis=0).values + self.df[self.X_columns].max(axis=0).values) / 2
# Getting the classes frequency.
classes_frequency = dict(self.df[target].value_counts())
# Searching for the class with the biggest frequency.
max_freq = 0
for cls in classes_frequency:
if classes_frequency[cls] > max_freq:
majority_class = cls
max_freq = classes_frequency[cls]
# Getting the name of the minority class.
minority_class = [cls for cls in classes_frequency if cls != majority_class][0]
# Computing the lower and upper skewness.
skewL = len(self.df[df[self.target] == minority_class]) / len(df)
skewU = len(self.df[df[self.target] == majority_class]) / len(df)
# Computing the lower and upper limits.
a = self.df[self.X_columns].min(axis=0).values / 10
b = self.df[self.X_columns].max(axis=0).values * 10
# Updating the lower and upper limits.
a = uset - skewL * np.sqrt(-2 * (variance / len(self.df[self.df[self.target] == minority_class])) * np.log(norm.cdf(a)))
b = uset - skewU * np.sqrt(-2 * (variance / len(self.df[self.df[self.target] == majority_class])) * np.log(norm.cdf(b)))
# Calculating the number of elements to generate.
number_of_elements_to_generate = len(self.df[self.df[self.target] == majority_class]) - len(self.df[self.df[self.target] == minority_class])
# Generating the synthetic data.
self.synthetic_data = []
# Eliminating possible -infinity and +infinity values.
a = self.__infinity_check(a)
b = self.__infinity_check(b)
for _ in range(number_of_elements_to_generate):
self.synthetic_data.append(
# Generating arrays with random values between a and b.
np.array([
np.random.uniform(a[i], b[i], 1)[0] for i in range(len(a))
])
)
# Replacing infinity values with minimal and maximal float python values.
self.synthetic_data = self.__infinity_check(np.array(self.synthetic_data).astype(float))
# Creating the synthetic data frame.
self.synthetic_df = pd.DataFrame(self.synthetic_data, columns=self.X_columns)
# Rounding binary columns if needed.
if self.__binarize:
self.__to_binary()
# Adding the target column to the synthetic data frame.
self.synthetic_df.loc[:, self.target] = minority_class
# Concatting the real data frame with the synthetic one.
new_df = pd.concat([self.df, self.synthetic_df], axis=0)
return new_df
|
[
"pandas.DataFrame",
"numpy.random.uniform",
"numpy.random.seed",
"scipy.stats.norm.cdf",
"numpy.array",
"pandas.concat"
] |
[((923, 948), 'numpy.random.seed', 'np.random.seed', (['self.seed'], {}), '(self.seed)\n', (937, 948), True, 'import numpy as np\n'), ((5630, 5687), 'pandas.DataFrame', 'pd.DataFrame', (['self.synthetic_data'], {'columns': 'self.X_columns'}), '(self.synthetic_data, columns=self.X_columns)\n', (5642, 5687), True, 'import pandas as pd\n'), ((6014, 6061), 'pandas.concat', 'pd.concat', (['[self.df, self.synthetic_df]'], {'axis': '(0)'}), '([self.df, self.synthetic_df], axis=0)\n', (6023, 6061), True, 'import pandas as pd\n'), ((5508, 5537), 'numpy.array', 'np.array', (['self.synthetic_data'], {}), '(self.synthetic_data)\n', (5516, 5537), True, 'import numpy as np\n'), ((4479, 4490), 'scipy.stats.norm.cdf', 'norm.cdf', (['a'], {}), '(a)\n', (4487, 4490), False, 'from scipy.stats import norm\n'), ((4609, 4620), 'scipy.stats.norm.cdf', 'norm.cdf', (['b'], {}), '(b)\n', (4617, 4620), False, 'from scipy.stats import norm\n'), ((5276, 5308), 'numpy.random.uniform', 'np.random.uniform', (['a[i]', 'b[i]', '(1)'], {}), '(a[i], b[i], 1)\n', (5293, 5308), True, 'import numpy as np\n')]
|
#!/usr/bin/env python2
#coding: utf-8
# Copyright (c) 2017-present, Facebook, Inc.
#
# 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.
##############################################################################
"""Perform inference on a single image or all images with a certain extension
(e.g., .jpg) in a folder.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# from __future__ import unicode_literals
#
import matplotlib.pyplot as plt
from PIL import Image, ImageDraw, ImageFont
from collections import defaultdict
import argparse
import cv2 # NOQA (Must import before importing caffe2 due to bug in cv2)
import glob
import logging
import os
import sys
import time
import numpy as np
import math
#
sys.path.append('/home/vpa/github/caffe2/build')
from caffe2.python import workspace
from core.config import assert_and_infer_cfg
from core.config import cfg
from core.config import merge_cfg_from_file
from utils.timer import Timer
import core.test_engine as infer_engine
import datasets.dummy_datasets as dummy_datasets
import utils.c2 as c2_utils
import utils.logging
import utils.vis as vis_utils
#
c2_utils.import_detectron_ops()
# OpenCL may be enabled by default in OpenCV3; disable it because it's not
# thread safe and causes unwanted GPU memory allocations.
cv2.ocl.setUseOpenCL(False)
_GRAY = (218, 227, 218)
_GREEN = (18, 127, 15)
_WHITE = (255, 255, 255)
# import sys
reload(sys)
sys.setdefaultencoding('utf8')
def parse_args():
parser = argparse.ArgumentParser(description='End-to-end inference')
parser.add_argument(
'--cfg',
dest='cfg',
help='cfg model file (/path/to/model_config.yaml)',
default='/home/vpa/github/Detectron/configs/12_2017_baselines/e2e_faster_rcnn_R-50-FPN_2x.yaml',
type=str
)
parser.add_argument(
'--wts',
dest='weights',
help='weights model file (/path/to/model_weights.pkl)',
default='/home/vpa/models/detectron/e2e_faster_rcnn_R-50-FPN_2x.pkl',
type=str
)
# parser.add_argument(
# '--output-dir',
# dest='output_dir',
# help='directory for visualization pdfs (default: /tmp/infer_simple)',
# default='/tmp/infer_simple',
# type=str
# )
# parser.add_argument(
# '--image-ext',
# dest='image_ext',
# help='image file name extension (default: jpg)',
# default='jpg',
# type=str
# )
# parser.add_argument(
# 'im_or_folder', help='image or folder of images',
# )
if len(sys.argv) == 1:
parser.print_help()
sys.exit(1)
return parser.parse_args()
def get_class_string(class_index, score, class_names):
class_text = class_names[class_index] if class_names is not None else \
'id{:d}'.format(class_index)
return class_text + ' {:0.2f}'.format(score).lstrip('0')
def vis_class(img, pos, class_str, font_scale=0.35):
"""Visualizes the class."""
x0, y0 = int(pos[0]), int(pos[1])
u,v = (pos[0]+pos[2])/2.0, 600-pos[3]
# 0.0230 * u - ((0.9996 * u - 550.3179) * (37.6942 * v - 2.2244e+06)) / (1.6394e+03 * v - 4.1343e+05) - 12.9168
#
# ((0.0070 * u - 1.6439e+03) * (37.6942 * v - 2.2244e+06)) / (1.6394e+03 * v - 4.1343e+05) - 1.6046e-04 * u + 0.0902
txt = class_str
# cv2 to pil
cv2_im = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # cv2和PIL中颜色的hex码的储存顺序不同
pil_im = Image.fromarray(cv2_im)
# draw pil
draw = ImageDraw.Draw(pil_im) # 括号中为需要打印的canvas,这里就是在图片上直接打印
font = ImageFont.truetype("/usr/share/fonts/truetype/simhei.ttf", 20, encoding="utf-8") # 第一个参数为字体文件路径,第二个为字体大小
draw.text((x0, y0-20), txt, (0, 0, 255), font=font) # 第一个参数为打印的坐标,第二个为打印的文本,第三个为字体颜色,第四个为字体
# pil to cv2
img = cv2.cvtColor(np.array(pil_im), cv2.COLOR_RGB2BGR)
cv2.imshow("detect", img)
# Compute text size.
# txt = class_str
# font = cv2.FONT_HERSHEY_SIMPLEX
# ((txt_w, txt_h), _) = cv2.getTextSize(txt, font, font_scale, 1)
# Place text background.
# back_tl = x0, y0 - int(1.3 * txt_h)
# back_br = x0 + txt_w, y0
# cv2.rectangle(img, back_tl, back_br, _GREEN, -1)
# Show text.
# txt_tl = x0, y0 - int(0.3 * txt_h)
# cv2.putText(img, txt, txt_tl, font, font_scale, _GRAY, lineType=cv2.LINE_AA)
return img
def vis_bbox(img, bbox, thick=1, color=_GREEN):
"""Visualizes a bounding box."""
(x0, y0, w, h) = bbox
x1, y1 = int(x0 + w), int(y0 + h)
x0, y0 = int(x0), int(y0)
cv2.rectangle(img, (x0, y0), (x1, y1), color, thickness=thick)
return img
def demo_vis_one_imageboxes_opencv(im, cls_boxes, thresh=[], show_box=False,dataset=None, show_class=False,
class_names=[], color_list=[], cls_sel=[]):
"""Constructs a numpy array with the detections visualized."""
box_list = [b for b in [cls_boxes[i] for i in cls_sel] if len(b) > 0]
if len(box_list) > 0:
boxes = np.concatenate(box_list)
else:
boxes = None
classes = []
# for j in range(len(cls_boxes)):
for j in cls_sel:
# print(len(cls_boxes[j]))
classes += [j] * len(cls_boxes[j])
if boxes is None or boxes.shape[0] == 0 or max(boxes[:, 4]) < min(thresh):
return im
# for i in sorted_inds:
for i, cls_id in enumerate(classes[0:]):
bbox = boxes[i, :4]
score = boxes[i, -1]
if score < thresh[cls_id]:
continue
# show box (off by default)
if show_box:
im = vis_bbox(
im, (bbox[0], bbox[1], bbox[2] - bbox[0], bbox[3] - bbox[1]), color=color_list[cls_id])
# show class (off by default)
if show_class:
class_str = get_class_string(classes[i], score, class_names)
im = vis_class(im, (bbox[0], bbox[1], bbox[2], bbox[3]), class_str)
return im
def detection(args):
logger = logging.getLogger(__name__)
merge_cfg_from_file(args.cfg)
cfg.TEST.WEIGHTS = args.weights
cfg.NUM_GPUS = 1
assert_and_infer_cfg()
model = infer_engine.initialize_model_from_cfg()
dummy_coco_dataset = dummy_datasets.get_coco_dataset()
start_time = time.time()
count = 0
# class_names =[
# '__background__', 'person', 'bicycle', 'car', 'motorcycle', 'airplane',
# 'bus', 'train', 'truck']
# color_list=[[0,0,0],[255,0,0],[0,255,0],[0,0,255],[255,255,0],[0,255,255],[255,255,0],[255,0,255],[255,255,255]]
class_names = [
'__background__', u'人'.encode('utf-8').decode('utf-8'), 'bicycle', u'车'.decode(), 'motorcycle', 'airplane',
'car', 'train', 'car']
color_list = [[0, 0, 0], [255, 0, 0], [0, 255, 0], [0, 0, 255], [255, 255, 0], [0, 0, 255], [255, 255, 0],
[255, 0, 255], [0, 0, 255]]
cls_sel = [1, 2, 3, 4, 6, 8]
cls_thresh = [1,0.6,0.5,0.8,0.5,0.9,0.7,0.9,0.5]
if count == 0:
logger.info(
' \ Note: inference on the first image will be slower than the '
'rest (caches and auto-tuning need to warm up)'
)
cap = cv2.VideoCapture(0)
cap.set(3, 800)
cap.set(4, 600)
size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
print(cv2.__version__)
fourcc = cv2.VideoWriter_fourcc(b'X', b'V', b'I', b'D')
videoWriter = cv2.VideoWriter('2.avi', fourcc, 10, size)
# fps = cap.get(cv2.CAP_PROP_FPS)
# print(fps)
while(1):
# get a frame
ret, im = cap.read()
count = count + 1
# im = cv2.resize(im, None, None, fx=im_scale, fy=im_scale, interpolation=cv2.INTER_LINEAR)
timers = defaultdict(Timer)
# detect one image
with c2_utils.NamedCudaScope(0):
cls_boxes, _, _ = infer_engine.im_detect_all(
model, im, None, timers=timers)
# logger.info('Inference time: {:.3f}s'.format(time.time() - t))
# for k, v in timers.items():1440
# logger.info(' | {}: {:.3f}s'.format(k, v.average_time))
# cls_boxes_sel=cls_boxes[[cls_id for cls_ind, cls_id in enumerate(cls_sel[0:])]]
demo_vis_one_imageboxes_opencv(im, cls_boxes, thresh=cls_thresh, show_box=True, dataset=dummy_coco_dataset,
show_class=True, class_names=class_names, color_list=color_list, cls_sel=cls_sel)
avg_fps = count / (time.time() - start_time)
cv2.putText(im, '{:s} {:.3f}/s'.format('fps', avg_fps), (40, 40), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 255),
lineType=cv2.LINE_AA)
# show a frame
return im
if __name__ == '__main__':
# workspace.GlobalInit(['caffe2', '--caffe2_log_level=0'])
# utils.logging.setup_logging(__name__)
args = parse_args()
main(args)
|
[
"argparse.ArgumentParser",
"core.config.merge_cfg_from_file",
"cv2.VideoWriter_fourcc",
"collections.defaultdict",
"datasets.dummy_datasets.get_coco_dataset",
"cv2.rectangle",
"cv2.VideoWriter",
"cv2.imshow",
"sys.path.append",
"cv2.cvtColor",
"core.config.assert_and_infer_cfg",
"sys.setdefaultencoding",
"core.test_engine.initialize_model_from_cfg",
"PIL.ImageDraw.Draw",
"utils.c2.NamedCudaScope",
"cv2.ocl.setUseOpenCL",
"utils.c2.import_detectron_ops",
"sys.exit",
"numpy.concatenate",
"time.time",
"PIL.ImageFont.truetype",
"cv2.VideoCapture",
"numpy.array",
"PIL.Image.fromarray",
"core.test_engine.im_detect_all",
"logging.getLogger"
] |
[((1268, 1316), 'sys.path.append', 'sys.path.append', (['"""/home/vpa/github/caffe2/build"""'], {}), "('/home/vpa/github/caffe2/build')\n", (1283, 1316), False, 'import sys\n'), ((1671, 1702), 'utils.c2.import_detectron_ops', 'c2_utils.import_detectron_ops', ([], {}), '()\n', (1700, 1702), True, 'import utils.c2 as c2_utils\n'), ((1836, 1863), 'cv2.ocl.setUseOpenCL', 'cv2.ocl.setUseOpenCL', (['(False)'], {}), '(False)\n', (1856, 1863), False, 'import cv2\n'), ((1962, 1992), 'sys.setdefaultencoding', 'sys.setdefaultencoding', (['"""utf8"""'], {}), "('utf8')\n", (1984, 1992), False, 'import sys\n'), ((2025, 2084), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""End-to-end inference"""'}), "(description='End-to-end inference')\n", (2048, 2084), False, 'import argparse\n'), ((3879, 3915), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2RGB'], {}), '(img, cv2.COLOR_BGR2RGB)\n', (3891, 3915), False, 'import cv2\n'), ((3955, 3978), 'PIL.Image.fromarray', 'Image.fromarray', (['cv2_im'], {}), '(cv2_im)\n', (3970, 3978), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((4005, 4027), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['pil_im'], {}), '(pil_im)\n', (4019, 4027), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((4071, 4156), 'PIL.ImageFont.truetype', 'ImageFont.truetype', (['"""/usr/share/fonts/truetype/simhei.ttf"""', '(20)'], {'encoding': '"""utf-8"""'}), "('/usr/share/fonts/truetype/simhei.ttf', 20, encoding='utf-8'\n )\n", (4089, 4156), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((4355, 4380), 'cv2.imshow', 'cv2.imshow', (['"""detect"""', 'img'], {}), "('detect', img)\n", (4365, 4380), False, 'import cv2\n'), ((5036, 5098), 'cv2.rectangle', 'cv2.rectangle', (['img', '(x0, y0)', '(x1, y1)', 'color'], {'thickness': 'thick'}), '(img, (x0, y0), (x1, y1), color, thickness=thick)\n', (5049, 5098), False, 'import cv2\n'), ((6437, 6464), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (6454, 6464), False, 'import logging\n'), ((6469, 6498), 'core.config.merge_cfg_from_file', 'merge_cfg_from_file', (['args.cfg'], {}), '(args.cfg)\n', (6488, 6498), False, 'from core.config import merge_cfg_from_file\n'), ((6560, 6582), 'core.config.assert_and_infer_cfg', 'assert_and_infer_cfg', ([], {}), '()\n', (6580, 6582), False, 'from core.config import assert_and_infer_cfg\n'), ((6595, 6635), 'core.test_engine.initialize_model_from_cfg', 'infer_engine.initialize_model_from_cfg', ([], {}), '()\n', (6633, 6635), True, 'import core.test_engine as infer_engine\n'), ((6661, 6694), 'datasets.dummy_datasets.get_coco_dataset', 'dummy_datasets.get_coco_dataset', ([], {}), '()\n', (6692, 6694), True, 'import datasets.dummy_datasets as dummy_datasets\n'), ((6713, 6724), 'time.time', 'time.time', ([], {}), '()\n', (6722, 6724), False, 'import time\n'), ((7605, 7624), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (7621, 7624), False, 'import cv2\n'), ((7798, 7844), 'cv2.VideoWriter_fourcc', 'cv2.VideoWriter_fourcc', (["b'X'", "b'V'", "b'I'", "b'D'"], {}), "(b'X', b'V', b'I', b'D')\n", (7820, 7844), False, 'import cv2\n'), ((7863, 7905), 'cv2.VideoWriter', 'cv2.VideoWriter', (['"""2.avi"""', 'fourcc', '(10)', 'size'], {}), "('2.avi', fourcc, 10, size)\n", (7878, 7905), False, 'import cv2\n'), ((3143, 3154), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (3151, 3154), False, 'import sys\n'), ((4314, 4330), 'numpy.array', 'np.array', (['pil_im'], {}), '(pil_im)\n', (4322, 4330), True, 'import numpy as np\n'), ((5486, 5510), 'numpy.concatenate', 'np.concatenate', (['box_list'], {}), '(box_list)\n', (5500, 5510), True, 'import numpy as np\n'), ((8169, 8187), 'collections.defaultdict', 'defaultdict', (['Timer'], {}), '(Timer)\n', (8180, 8187), False, 'from collections import defaultdict\n'), ((8228, 8254), 'utils.c2.NamedCudaScope', 'c2_utils.NamedCudaScope', (['(0)'], {}), '(0)\n', (8251, 8254), True, 'import utils.c2 as c2_utils\n'), ((8286, 8344), 'core.test_engine.im_detect_all', 'infer_engine.im_detect_all', (['model', 'im', 'None'], {'timers': 'timers'}), '(model, im, None, timers=timers)\n', (8312, 8344), True, 'import core.test_engine as infer_engine\n'), ((8903, 8914), 'time.time', 'time.time', ([], {}), '()\n', (8912, 8914), False, 'import time\n')]
|
"""Integration Test for local_implicit_grid + PDELayer."""
# pylint: disable=import-error, no-member, too-many-arguments, no-self-use
import unittest
import numpy as np
import torch
from parameterized import parameterized
from local_implicit_grid import query_local_implicit_grid
from implicit_net import ImNet
from pde import PDELayer
def setup_diffusion_equation():
# setup pde constraints
in_vars = 'x, y, t' # matches dim_in
out_vars = 'u, v' # matches dim_out
eqn_strs = ['dif(u, t) - (dif(dif(u, x), x) + dif(dif(u, y), y))',
'dif(v, t) - (dif(dif(v, x), x) + dif(dif(v, y), y))']
eqn_names = ['diffusion_u', 'diffusion_v']
pde_dict = {"in_vars": in_vars,
"out_vars": out_vars,
"eqn_strs": eqn_strs,
"eqn_names": eqn_names}
return pde_dict
def setup_rb2_equation():
# setup pde constraints
# constants
prandtl = 1.
rayleigh = 1e6
P = (rayleigh * prandtl)**(-1/2)
R = (rayleigh / prandtl)**(-1/2)
# set up variables and equations
in_vars = 't, x, z'
out_vars = 'p, b, u, w'
# eqn_strs = [
# f'dif(b,t)-{P}*(dif(dif(b,x),x)+dif(dif(b,z),z)) +(u*dif(b,x)+w*dif(b,z))',
# f'dif(u,t)-{R}*(dif(dif(u,x),x)+dif(dif(u,z),z))+dif(p,x) +(u*dif(u,x)+w*dif(u,z))',
# f'dif(w,t)-{R}*(dif(dif(w,x),x)+dif(dif(w,z),z))+dif(p,z)-b +(u*dif(w,x)+w*dif(w,z))',
# ]
# # a name/identifier for the equations
# eqn_names = ['transport_eqn_b', 'transport_eqn_u', 'transport_eqn_w']
eqn_strs = [
f'u*dif(b,x)',
]
# a name/identifier for the equations
eqn_names = ['transport_eqn_b']
pde_dict = {"in_vars": in_vars,
"out_vars": out_vars,
"eqn_strs": eqn_strs,
"eqn_names": eqn_names}
return pde_dict
class LocalImplicitGridIntegrationTest(unittest.TestCase):
"""Integration test for local_implicit_grid"""
@parameterized.expand((
[setup_diffusion_equation()],
[setup_rb2_equation()],
))
def test_local_implicit_grid_with_pde_layer_diff_eqn(self, pde_dict):
"""integration test for diffusion equation."""
# setup parameters
batch_size = 8 # batch size
grid_res = 16 # grid resolution
nc = 32 # number of latent channels
n_filter = 16 # number of filters in neural net
n_pts = 1024 # number of query points
in_vars = pde_dict['in_vars']
out_vars = pde_dict['out_vars']
eqn_strs = pde_dict['eqn_strs']
eqn_names = pde_dict['eqn_names']
dim_in = len(pde_dict['in_vars'].split(','))
dim_out = len(pde_dict['out_vars'].split(','))
# setup local implicit grid as forward function
latent_grid = torch.rand(batch_size, grid_res, grid_res, grid_res, nc)
query_pts = torch.rand(batch_size, n_pts, dim_in)
model = ImNet(dim=dim_in, in_features=nc, out_features=dim_out, nf=n_filter)
fwd_fn = lambda query_pts: query_local_implicit_grid(model, latent_grid, query_pts, 0., 1.)
# setup pde layer
pdel = PDELayer(in_vars=in_vars, out_vars=out_vars)
for eqn_str, eqn_name in zip(eqn_strs, eqn_names):
pdel.add_equation(eqn_str, eqn_name)
pdel.update_forward_method(fwd_fn)
val, res = pdel(query_pts)
# it's harder to check values due to the randomness of the neural net. so we test shape
# instead
np.testing.assert_allclose(val.shape, [batch_size, n_pts, dim_out])
for key in res.keys():
res_value = res[key]
np.testing.assert_allclose(res_value.shape, [batch_size, n_pts, 1])
if __name__ == '__main__':
unittest.main()
|
[
"unittest.main",
"pde.PDELayer",
"implicit_net.ImNet",
"local_implicit_grid.query_local_implicit_grid",
"torch.rand",
"numpy.testing.assert_allclose"
] |
[((3752, 3767), 'unittest.main', 'unittest.main', ([], {}), '()\n', (3765, 3767), False, 'import unittest\n'), ((2812, 2868), 'torch.rand', 'torch.rand', (['batch_size', 'grid_res', 'grid_res', 'grid_res', 'nc'], {}), '(batch_size, grid_res, grid_res, grid_res, nc)\n', (2822, 2868), False, 'import torch\n'), ((2889, 2926), 'torch.rand', 'torch.rand', (['batch_size', 'n_pts', 'dim_in'], {}), '(batch_size, n_pts, dim_in)\n', (2899, 2926), False, 'import torch\n'), ((2943, 3011), 'implicit_net.ImNet', 'ImNet', ([], {'dim': 'dim_in', 'in_features': 'nc', 'out_features': 'dim_out', 'nf': 'n_filter'}), '(dim=dim_in, in_features=nc, out_features=dim_out, nf=n_filter)\n', (2948, 3011), False, 'from implicit_net import ImNet\n'), ((3154, 3198), 'pde.PDELayer', 'PDELayer', ([], {'in_vars': 'in_vars', 'out_vars': 'out_vars'}), '(in_vars=in_vars, out_vars=out_vars)\n', (3162, 3198), False, 'from pde import PDELayer\n'), ((3508, 3575), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['val.shape', '[batch_size, n_pts, dim_out]'], {}), '(val.shape, [batch_size, n_pts, dim_out])\n', (3534, 3575), True, 'import numpy as np\n'), ((3047, 3113), 'local_implicit_grid.query_local_implicit_grid', 'query_local_implicit_grid', (['model', 'latent_grid', 'query_pts', '(0.0)', '(1.0)'], {}), '(model, latent_grid, query_pts, 0.0, 1.0)\n', (3072, 3113), False, 'from local_implicit_grid import query_local_implicit_grid\n'), ((3652, 3719), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['res_value.shape', '[batch_size, n_pts, 1]'], {}), '(res_value.shape, [batch_size, n_pts, 1])\n', (3678, 3719), True, 'import numpy as np\n')]
|
import os
import sys
import tensorflow as tf
import numpy as np
from model256 import LungSystem
from os.path import join as pjoin
import random
import logging
starting=False
logging.basicConfig(level=logging.INFO)
tf.app.flags.DEFINE_float("best_val_loss", float('inf'), "best val loss so far")
tf.app.flags.DEFINE_string("model", 'unet', "Type of model to use: linear or cnn or simplecnn")
tf.app.flags.DEFINE_integer("epochs", 999999, "number of epochs")
tf.app.flags.DEFINE_float("learning_rate", 0.0001, "Learning rate.")
tf.app.flags.DEFINE_float("leak", 0.01, "Leakiness")
tf.app.flags.DEFINE_float("dropout", 0.2, "dropout prob")
tf.app.flags.DEFINE_integer("image_height", 256, "height of each slice in pixels")
tf.app.flags.DEFINE_integer("image_width", 256, "width of each slice in pixels")
tf.app.flags.DEFINE_integer("batch_size", 32, "Batch size to use during training.")
tf.app.flags.DEFINE_float("train_size", 0.9, "Size of train set")
tf.app.flags.DEFINE_float("val_size", 0.1, "Size of val set")
tf.app.flags.DEFINE_float("weight_one", 2640.68737846, "ones label multiplier")
tf.app.flags.DEFINE_integer("skip", 1480, "ones label multiplier")
FLAGS = tf.app.flags.FLAGS
train_dir = './weights/%s256/' % (FLAGS.model)
def initialize_model(session, model, train_dir):
ckpt = tf.train.get_checkpoint_state(train_dir)
v2_path = ckpt.model_checkpoint_path + ".index" if ckpt else ""
if ckpt and (tf.gfile.Exists(ckpt.model_checkpoint_path) or tf.gfile.Exists(v2_path)):
logging.info("Reading model parameters from %s" % ckpt.model_checkpoint_path)
model.saver.restore(session, ckpt.model_checkpoint_path)
else:
logging.info("Unable to read parameters from %s" % train_dir)
sys.exit()
return model
def main(_):
DATA_FOLDER = 'kaggle-lung-masks/'
OUTPUT_FOLDER = 'kaggle-lung-unet-outputs/'
patient_data = os.listdir(DATA_FOLDER)
patient_data.sort()
lung_model = LungSystem(FLAGS)
with tf.Session() as sess:
initialize_model(sess, lung_model, train_dir)
for p in range(len(patient_data)):
if p < FLAGS.skip or p >= FLAGS.skip+50:
continue
print(p)
path = DATA_FOLDER + patient_data[p]
x = np.load(path)
pat_id = patient_data[p][:-4]
logging.info("Evaluating model on %s" % pat_id)
y = lung_model.predict(sess, x).astype(np.float16)
np.save(OUTPUT_FOLDER + pat_id, y)
if __name__ == "__main__":
tf.app.run()
|
[
"tensorflow.app.flags.DEFINE_float",
"tensorflow.gfile.Exists",
"numpy.load",
"numpy.save",
"logging.basicConfig",
"tensorflow.Session",
"logging.info",
"tensorflow.app.flags.DEFINE_string",
"sys.exit",
"tensorflow.app.flags.DEFINE_integer",
"tensorflow.app.run",
"os.listdir",
"tensorflow.train.get_checkpoint_state",
"model256.LungSystem"
] |
[((178, 217), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (197, 217), False, 'import logging\n'), ((301, 400), 'tensorflow.app.flags.DEFINE_string', 'tf.app.flags.DEFINE_string', (['"""model"""', '"""unet"""', '"""Type of model to use: linear or cnn or simplecnn"""'], {}), "('model', 'unet',\n 'Type of model to use: linear or cnn or simplecnn')\n", (327, 400), True, 'import tensorflow as tf\n'), ((397, 462), 'tensorflow.app.flags.DEFINE_integer', 'tf.app.flags.DEFINE_integer', (['"""epochs"""', '(999999)', '"""number of epochs"""'], {}), "('epochs', 999999, 'number of epochs')\n", (424, 462), True, 'import tensorflow as tf\n'), ((463, 531), 'tensorflow.app.flags.DEFINE_float', 'tf.app.flags.DEFINE_float', (['"""learning_rate"""', '(0.0001)', '"""Learning rate."""'], {}), "('learning_rate', 0.0001, 'Learning rate.')\n", (488, 531), True, 'import tensorflow as tf\n'), ((532, 584), 'tensorflow.app.flags.DEFINE_float', 'tf.app.flags.DEFINE_float', (['"""leak"""', '(0.01)', '"""Leakiness"""'], {}), "('leak', 0.01, 'Leakiness')\n", (557, 584), True, 'import tensorflow as tf\n'), ((585, 642), 'tensorflow.app.flags.DEFINE_float', 'tf.app.flags.DEFINE_float', (['"""dropout"""', '(0.2)', '"""dropout prob"""'], {}), "('dropout', 0.2, 'dropout prob')\n", (610, 642), True, 'import tensorflow as tf\n'), ((643, 729), 'tensorflow.app.flags.DEFINE_integer', 'tf.app.flags.DEFINE_integer', (['"""image_height"""', '(256)', '"""height of each slice in pixels"""'], {}), "('image_height', 256,\n 'height of each slice in pixels')\n", (670, 729), True, 'import tensorflow as tf\n'), ((726, 811), 'tensorflow.app.flags.DEFINE_integer', 'tf.app.flags.DEFINE_integer', (['"""image_width"""', '(256)', '"""width of each slice in pixels"""'], {}), "('image_width', 256, 'width of each slice in pixels'\n )\n", (753, 811), True, 'import tensorflow as tf\n'), ((807, 894), 'tensorflow.app.flags.DEFINE_integer', 'tf.app.flags.DEFINE_integer', (['"""batch_size"""', '(32)', '"""Batch size to use during training."""'], {}), "('batch_size', 32,\n 'Batch size to use during training.')\n", (834, 894), True, 'import tensorflow as tf\n'), ((891, 956), 'tensorflow.app.flags.DEFINE_float', 'tf.app.flags.DEFINE_float', (['"""train_size"""', '(0.9)', '"""Size of train set"""'], {}), "('train_size', 0.9, 'Size of train set')\n", (916, 956), True, 'import tensorflow as tf\n'), ((957, 1018), 'tensorflow.app.flags.DEFINE_float', 'tf.app.flags.DEFINE_float', (['"""val_size"""', '(0.1)', '"""Size of val set"""'], {}), "('val_size', 0.1, 'Size of val set')\n", (982, 1018), True, 'import tensorflow as tf\n'), ((1019, 1098), 'tensorflow.app.flags.DEFINE_float', 'tf.app.flags.DEFINE_float', (['"""weight_one"""', '(2640.68737846)', '"""ones label multiplier"""'], {}), "('weight_one', 2640.68737846, 'ones label multiplier')\n", (1044, 1098), True, 'import tensorflow as tf\n'), ((1099, 1165), 'tensorflow.app.flags.DEFINE_integer', 'tf.app.flags.DEFINE_integer', (['"""skip"""', '(1480)', '"""ones label multiplier"""'], {}), "('skip', 1480, 'ones label multiplier')\n", (1126, 1165), True, 'import tensorflow as tf\n'), ((1302, 1342), 'tensorflow.train.get_checkpoint_state', 'tf.train.get_checkpoint_state', (['train_dir'], {}), '(train_dir)\n', (1331, 1342), True, 'import tensorflow as tf\n'), ((1889, 1912), 'os.listdir', 'os.listdir', (['DATA_FOLDER'], {}), '(DATA_FOLDER)\n', (1899, 1912), False, 'import os\n'), ((1956, 1973), 'model256.LungSystem', 'LungSystem', (['FLAGS'], {}), '(FLAGS)\n', (1966, 1973), False, 'from model256 import LungSystem\n'), ((2556, 2568), 'tensorflow.app.run', 'tf.app.run', ([], {}), '()\n', (2566, 2568), True, 'import tensorflow as tf\n'), ((1510, 1587), 'logging.info', 'logging.info', (["('Reading model parameters from %s' % ckpt.model_checkpoint_path)"], {}), "('Reading model parameters from %s' % ckpt.model_checkpoint_path)\n", (1522, 1587), False, 'import logging\n'), ((1671, 1732), 'logging.info', 'logging.info', (["('Unable to read parameters from %s' % train_dir)"], {}), "('Unable to read parameters from %s' % train_dir)\n", (1683, 1732), False, 'import logging\n'), ((1741, 1751), 'sys.exit', 'sys.exit', ([], {}), '()\n', (1749, 1751), False, 'import sys\n'), ((1984, 1996), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (1994, 1996), True, 'import tensorflow as tf\n'), ((1428, 1471), 'tensorflow.gfile.Exists', 'tf.gfile.Exists', (['ckpt.model_checkpoint_path'], {}), '(ckpt.model_checkpoint_path)\n', (1443, 1471), True, 'import tensorflow as tf\n'), ((1475, 1499), 'tensorflow.gfile.Exists', 'tf.gfile.Exists', (['v2_path'], {}), '(v2_path)\n', (1490, 1499), True, 'import tensorflow as tf\n'), ((2280, 2293), 'numpy.load', 'np.load', (['path'], {}), '(path)\n', (2287, 2293), True, 'import numpy as np\n'), ((2352, 2399), 'logging.info', 'logging.info', (["('Evaluating model on %s' % pat_id)"], {}), "('Evaluating model on %s' % pat_id)\n", (2364, 2399), False, 'import logging\n'), ((2476, 2510), 'numpy.save', 'np.save', (['(OUTPUT_FOLDER + pat_id)', 'y'], {}), '(OUTPUT_FOLDER + pat_id, y)\n', (2483, 2510), True, 'import numpy as np\n')]
|
#!/usr/bin/env python
# encoding: utf-8
# Attention-Based Aspect-Based Sentiment Extraction 2 (ABABSE2).
#
# https://github.com/LucaZampierin/ABABSE
#
# Adapted from Trusca, Wassenberg, Frasincar and Dekker (2020). Changes have been made to adapt the methods
# to the current project and to adapt the scripts to TensorFlow 2.5.
# https://github.com/mtrusca/HAABSA_PLUS_PLUS
#
# <NAME>., <NAME>., <NAME>., <NAME>. (2020). A Hybrid Approach for aspect-based sentiment analysis using
# deep contextual word embeddings and hierarchical attention. 20th International Conference on Web Engineering (ICWE 2020)
# (Vol.12128, pp. 365–380). Springer
import os, sys
from sklearn.metrics import precision_score, recall_score, f1_score, accuracy_score
import tensorflow as tf
import numpy as np
from nn_layer import softmax_layer, reduce_mean_with_len, decoder_layer, bi_dynamic_rnn_abse
from att_layer import bilinear_attention_layer
from config import *
from utils import load_w2v, batch_index, load_inputs_twitter, load_word_id_mapping
sys.path.append(os.getcwd())
tf.compat.v1.disable_eager_execution()
def ababse2(input, sen_len, target, sen_len_tr, aspects, n_aspects, drop_rate1, drop_rate2, sub_vocab, l2, _id='all'):
"""
Structure of the Attention-Based Aspect-Based Sentiment Extraction 2 (ABABSE2) attentional neural network.
Adapts the strutures in Trusca et al. (2020) to the current project.
:param input:
:param sen_len:
:param target:
:param sen_len_tr:
:param aspects:
:param n_aspects:
:param drop_rate1:
:param drop_rate2:
:param sub_vocab:
:param l2:
:param _id:
:return:
"""
print('I am ABABSE2.')
cell = tf.compat.v1.nn.rnn_cell.LSTMCell
input = tf.nn.dropout(input, rate=drop_rate1)
hiddens = bi_dynamic_rnn_abse(cell, input, FLAGS.n_hidden, sen_len, FLAGS.max_sentence_len, 'l' + _id, 'all')
target = bi_dynamic_rnn_abse(cell, target, FLAGS.n_hidden, sen_len_tr, FLAGS.max_target_len, 'target' + _id, 'all')
pool_t = reduce_mean_with_len(target, sen_len_tr)
# Attention layer
att = bilinear_attention_layer(hiddens, pool_t, sen_len, FLAGS.n_hidden, l2, FLAGS.random_base, 'tl')
# Sentence representation
z_s = tf.matmul(att, input)
z_s = tf.squeeze(z_s, axis=1)
# Autoencoder-like dimensionalty reduction. Senitment classification
prob, soft_weight = softmax_layer(z_s, FLAGS.n_hidden, FLAGS.random_base, drop_rate2, l2, FLAGS.n_class)
# Sentence reconstruction
r_s, sent_embedding = decoder_layer(prob, aspects, FLAGS.n_hidden, FLAGS.n_class, n_aspects, FLAGS.random_base, l2,
sub_vocab, FLAGS, use_aspect=True)
return prob, r_s, z_s, att, sent_embedding
def main(train_path, test_path, test_size, sub_vocab, learning_rate=FLAGS.learning_rate, drop_rate=FLAGS.drop_rate1,
b1=0.99, b2=0.99, l2=FLAGS.l2_reg, seed_reg=FLAGS.seed_reg, ortho_reg=FLAGS.ortho_reg, batchsize=FLAGS.batch_size,
nsamples=FLAGS.negative_samples):
"""
Runs the ABABSE2 method. Method adapted from Trusca et al. (2020) to the current project.
:param train_path: path for train data
:param test_path: path for test data
:param test_size: size of test set
:param sub_vocab: seed vocabulary for seed regularization
:param learning_rate: learning rate used for backpropagation, defaults to 0.005
:param drop_rate: dropout rate, defaults to 0.05
:param b1: beta1 hyperparameter of Adam optimizer, defaults to 0.99
:param b2: beta2 hyperparameter of Adam optimizer, defaults to 0.99
:param l2: L2 regularization weight, defaults to 0.003
:param seed_reg: seed regularization weight, defaults to 5
:param ortho_reg: redundancy (orthogonal) regularization weight, defaults to 1
:param batchsize: number of training observations in each batch, defaults to 30
:param nsamples: number of negative samples for training, defaults to 10
:return:
"""
print_config()
with tf.device('/gpu:1'):
word_id_mapping, w2v = load_w2v(FLAGS.embedding_path, FLAGS.embedding_dim)
word_embedding = tf.constant(w2v, dtype=np.float32, name='word_embedding')
drop_rate1 = tf.placeholder(tf.float32)
drop_rate2 = tf.placeholder(tf.float32)
with tf.name_scope('inputs'):
x = tf.placeholder(tf.int32, [None, FLAGS.max_sentence_len])
y = tf.placeholder(tf.float32, [None, FLAGS.n_class])
aspect = tf.placeholder(tf.float32, [None, FLAGS.n_aspect])
sen_len = tf.placeholder(tf.int32, None)
ns_words = tf.placeholder(tf.int32, [None, FLAGS.max_sentence_len])
neg_sen_len = tf.placeholder(tf.int32, None)
target_words = tf.placeholder(tf.int32, [None, FLAGS.max_target_len])
tar_len = tf.placeholder(tf.int32, [None])
inputs = tf.nn.embedding_lookup(word_embedding, x)
target = tf.nn.embedding_lookup(word_embedding, target_words)
neg_samples = tf.nn.embedding_lookup(word_embedding, ns_words)
att= None
prob, r_s, z_s, att, sent_embedding = ababse2(inputs, sen_len, target, tar_len, aspect, FLAGS.n_aspect,
drop_rate1, drop_rate2, sub_vocab, l2, 'all')
loss = train_loss_func(z_s, r_s, sent_embedding, sub_vocab, neg_samples, seed_reg, ortho_reg, nsamples, neg_sen_len )
t_loss = test_loss_func(z_s, r_s)
acc_num, acc_prob = acc_func(y, prob) # acc_num is the total number of correct predictions, acc_prob is the percentage accuracy
global_step = tf.Variable(0, name='tr_global_step', trainable=False)
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate, beta1=b1, beta2=b2, epsilon=1e-08).minimize(loss,
global_step=global_step)
true_y = tf.argmax(y, 1)
pred_y = tf.argmax(prob, 1)
title = '-d1-{}d2-{}b-{}r-{}l2-{}sen-{}dim-{}h-{}c-{}'.format(
FLAGS.drop_rate1,
FLAGS.drop_rate2,
FLAGS.batch_size,
learning_rate,
FLAGS.l2_reg,
FLAGS.max_sentence_len,
FLAGS.embedding_dim,
FLAGS.n_hidden,
FLAGS.n_class
)
config = tf.ConfigProto(allow_soft_placement=True)
config.gpu_options.allow_growth = True
with tf.Session(config=config) as sess:
import time
timestamp = str(int(time.time()))
_dir = 'summary/' + str(timestamp) + '_' + title
test_loss = tf.placeholder(tf.float32)
test_acc = tf.placeholder(tf.float32)
train_summary_op, test_summary_op, validate_summary_op, train_summary_writer, test_summary_writer, \
validate_summary_writer = summary_func(loss, acc_prob, test_loss, test_acc, _dir, title, sess)
save_dir = 'temp_model/' + str(timestamp) + '_' + title + '/'
# saver = saver_func(save_dir)
sess.run(tf.global_variables_initializer())
# saver.restore(sess, '/-')
if FLAGS.is_r == '1':
is_r = True
else:
is_r = False
tr_x, tr_sen_len, tr_target_word, tr_tar_len, tr_y, tr_aspect, _, tr_x_neg, tr_neg_sen_len = load_inputs_twitter(
train_path,
word_id_mapping,
FLAGS.max_sentence_len,
'IAN',
is_r,
FLAGS.max_target_len,
)
te_x, te_sen_len, te_target_word, te_tar_len, te_y, te_aspect, all_y, te_x_neg, te_neg_sen_len = load_inputs_twitter(
test_path,
word_id_mapping,
FLAGS.max_sentence_len,
'IAN',
is_r,
FLAGS.max_target_len
)
def get_batch_data(x_f, sen_len_f, yi, target, tl, aspecti, train_x_neg, sen_len_neg, batch_size,
negative_samples, dr1, dr2, is_shuffle=True):
"""
Method adapted from Trusca et al. (2020). Obtain a batch of data.
:param x_f:
:param sen_len_f:
:param yi:
:param target:
:param tl:
:param aspecti:
:param train_x_neg:
:param sen_len_neg:
:param batch_size:
:param negative_samples:
:param dr1:
:param dr2:
:param is_shuffle:
:return:
"""
for index, neg_index in batch_index(len(yi), batch_size, negative_samples, 1, is_shuffle):
feed_dict = {
x: x_f[index],
sen_len: sen_len_f[index],
y: yi[index],
target_words: target[index],
tar_len: tl[index],
aspect: aspecti[index],
ns_words: train_x_neg[neg_index],
neg_sen_len: sen_len_neg[neg_index],
drop_rate1: dr1,
drop_rate2: dr2,
}
yield feed_dict, len(index)
max_acc, max_train_acc, min_cost = 0., 0., 1000000.
best_epoch = 0
max_ty, max_py = None, None
max_prob = None
best_sent_emb = None
step = None
for i in range(FLAGS.n_iter):
trainacc, traincnt, cost_train = 0., 0, 0.
for train, numtrain in get_batch_data(tr_x, tr_sen_len, tr_y, tr_target_word, tr_tar_len, tr_aspect, tr_x_neg,
tr_neg_sen_len, batchsize, nsamples, drop_rate, drop_rate):
loss_, _, step, summary, _trainacc = sess.run([loss, optimizer, global_step, train_summary_op, acc_num], feed_dict=train)
train_summary_writer.add_summary(summary, step)
trainacc += _trainacc
traincnt += numtrain
cost_train += loss_
acc, cost, cnt = 0., 0., 0
at, ty, py = [], [], []
p = []
# Test model
for test, num in get_batch_data(te_x, te_sen_len, te_y, te_target_word, te_tar_len, te_aspect, te_x_neg, te_neg_sen_len,
1000, 0, 0, 0, False):
_loss, _acc, _ty, _py, _p, _att, sent_emb = sess.run(
[t_loss, acc_num, true_y, pred_y, prob, att, sent_embedding], feed_dict=test)
ty = np.asarray(_ty)
py = np.asarray(_py)
p = np.asarray(_p)
at = np.asarray(_att)
sent_emb = np.asarray(sent_emb)
acc += _acc
cost += _loss * num
cnt += num
print('all samples={}, correct prediction={}'.format(cnt, acc))
trainacc = trainacc / traincnt
acc = acc / cnt
totalacc = acc
cost = cost / cnt
print('Iter {}: mini-batch loss={:.6f}, train acc={:.6f}, test acc={:.6f}, test_loss={:.6f}'.format(i, cost_train, trainacc, acc, cost))
summary = sess.run(test_summary_op, feed_dict={test_loss: cost, test_acc: acc})
test_summary_writer.add_summary(summary, step)
if cost < min_cost and i != 0:
min_cost = cost
max_acc = acc
max_train_acc = trainacc
max_att = at
max_ty = ty
max_py = py
max_prob = p
best_epoch = i
best_sent_emb = sent_emb
P = precision_score(max_ty, max_py, average=None)
R = recall_score(max_ty, max_py, average=None)
F1 = f1_score(max_ty, max_py, average=None)
print('P:', P, 'avg=', sum(P) / FLAGS.n_class)
print('R:', R, 'avg=', sum(R) / FLAGS.n_class)
print('F1:', F1, 'avg=', sum(F1) / FLAGS.n_class)
# Obtain the precision, recall, and F1 score for each class
per_class_scores = np.concatenate([P.reshape(-1,3), R.reshape(-1,3), F1.reshape(-1,3)], axis=0)
fp = open(FLAGS.prob_file, 'w')
for item in max_prob:
fp.write(' '.join([str(it) for it in item]) + '\n')
fp = open(FLAGS.prob_file + '_att', 'w')
for y1, y2, ws in zip(max_ty, max_py, max_att):
fp.write(str(y1) + ' ' + str(y2) + ' ' + ' '.join([str(w) for w in ws[0]]) + '\n')
print('Optimization Finished! Max acc={}'.format(max_acc))
print('Learning_rate={}, iter_num={}, batch_size={}, dropout_rate={}, l2={}, seed_reg={}, ortho_reg={}, negative_samples={}'.format(
learning_rate,
FLAGS.n_iter,
FLAGS.batch_size,
FLAGS.drop_rate1,
FLAGS.l2_reg,
FLAGS.seed_reg,
FLAGS.ortho_reg,
FLAGS.negative_samples
))
return min_cost, best_epoch, max_acc, np.where(np.subtract(max_py, max_ty) == 0, 0, 1), max_att.tolist(), \
all_y.tolist(), sum(P) / FLAGS.n_class, sum(R) / FLAGS.n_class, sum(F1) / FLAGS.n_class,\
max_train_acc, best_sent_emb, per_class_scores
if __name__ == '__main__':
tf.app.run()
|
[
"nn_layer.reduce_mean_with_len",
"nn_layer.softmax_layer",
"tensorflow.compat.v1.disable_eager_execution",
"tensorflow.matmul",
"tensorflow.ConfigProto",
"tensorflow.Variable",
"sklearn.metrics.f1_score",
"nn_layer.bi_dynamic_rnn_abse",
"utils.load_inputs_twitter",
"tensorflow.placeholder",
"tensorflow.squeeze",
"utils.load_w2v",
"tensorflow.name_scope",
"tensorflow.app.run",
"nn_layer.decoder_layer",
"att_layer.bilinear_attention_layer",
"tensorflow.nn.embedding_lookup",
"tensorflow.global_variables_initializer",
"numpy.asarray",
"tensorflow.Session",
"sklearn.metrics.recall_score",
"tensorflow.constant",
"numpy.subtract",
"os.getcwd",
"tensorflow.argmax",
"tensorflow.device",
"time.time",
"sklearn.metrics.precision_score",
"tensorflow.train.AdamOptimizer",
"tensorflow.nn.dropout"
] |
[((1088, 1126), 'tensorflow.compat.v1.disable_eager_execution', 'tf.compat.v1.disable_eager_execution', ([], {}), '()\n', (1124, 1126), True, 'import tensorflow as tf\n'), ((1074, 1085), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (1083, 1085), False, 'import os, sys\n'), ((1790, 1827), 'tensorflow.nn.dropout', 'tf.nn.dropout', (['input'], {'rate': 'drop_rate1'}), '(input, rate=drop_rate1)\n', (1803, 1827), True, 'import tensorflow as tf\n'), ((1843, 1947), 'nn_layer.bi_dynamic_rnn_abse', 'bi_dynamic_rnn_abse', (['cell', 'input', 'FLAGS.n_hidden', 'sen_len', 'FLAGS.max_sentence_len', "('l' + _id)", '"""all"""'], {}), "(cell, input, FLAGS.n_hidden, sen_len, FLAGS.\n max_sentence_len, 'l' + _id, 'all')\n", (1862, 1947), False, 'from nn_layer import softmax_layer, reduce_mean_with_len, decoder_layer, bi_dynamic_rnn_abse\n'), ((1957, 2068), 'nn_layer.bi_dynamic_rnn_abse', 'bi_dynamic_rnn_abse', (['cell', 'target', 'FLAGS.n_hidden', 'sen_len_tr', 'FLAGS.max_target_len', "('target' + _id)", '"""all"""'], {}), "(cell, target, FLAGS.n_hidden, sen_len_tr, FLAGS.\n max_target_len, 'target' + _id, 'all')\n", (1976, 2068), False, 'from nn_layer import softmax_layer, reduce_mean_with_len, decoder_layer, bi_dynamic_rnn_abse\n'), ((2078, 2118), 'nn_layer.reduce_mean_with_len', 'reduce_mean_with_len', (['target', 'sen_len_tr'], {}), '(target, sen_len_tr)\n', (2098, 2118), False, 'from nn_layer import softmax_layer, reduce_mean_with_len, decoder_layer, bi_dynamic_rnn_abse\n'), ((2155, 2254), 'att_layer.bilinear_attention_layer', 'bilinear_attention_layer', (['hiddens', 'pool_t', 'sen_len', 'FLAGS.n_hidden', 'l2', 'FLAGS.random_base', '"""tl"""'], {}), "(hiddens, pool_t, sen_len, FLAGS.n_hidden, l2,\n FLAGS.random_base, 'tl')\n", (2179, 2254), False, 'from att_layer import bilinear_attention_layer\n'), ((2295, 2316), 'tensorflow.matmul', 'tf.matmul', (['att', 'input'], {}), '(att, input)\n', (2304, 2316), True, 'import tensorflow as tf\n'), ((2328, 2351), 'tensorflow.squeeze', 'tf.squeeze', (['z_s'], {'axis': '(1)'}), '(z_s, axis=1)\n', (2338, 2351), True, 'import tensorflow as tf\n'), ((2453, 2542), 'nn_layer.softmax_layer', 'softmax_layer', (['z_s', 'FLAGS.n_hidden', 'FLAGS.random_base', 'drop_rate2', 'l2', 'FLAGS.n_class'], {}), '(z_s, FLAGS.n_hidden, FLAGS.random_base, drop_rate2, l2, FLAGS\n .n_class)\n', (2466, 2542), False, 'from nn_layer import softmax_layer, reduce_mean_with_len, decoder_layer, bi_dynamic_rnn_abse\n'), ((2598, 2730), 'nn_layer.decoder_layer', 'decoder_layer', (['prob', 'aspects', 'FLAGS.n_hidden', 'FLAGS.n_class', 'n_aspects', 'FLAGS.random_base', 'l2', 'sub_vocab', 'FLAGS'], {'use_aspect': '(True)'}), '(prob, aspects, FLAGS.n_hidden, FLAGS.n_class, n_aspects,\n FLAGS.random_base, l2, sub_vocab, FLAGS, use_aspect=True)\n', (2611, 2730), False, 'from nn_layer import softmax_layer, reduce_mean_with_len, decoder_layer, bi_dynamic_rnn_abse\n'), ((6520, 6561), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'allow_soft_placement': '(True)'}), '(allow_soft_placement=True)\n', (6534, 6561), True, 'import tensorflow as tf\n'), ((13474, 13486), 'tensorflow.app.run', 'tf.app.run', ([], {}), '()\n', (13484, 13486), True, 'import tensorflow as tf\n'), ((4111, 4130), 'tensorflow.device', 'tf.device', (['"""/gpu:1"""'], {}), "('/gpu:1')\n", (4120, 4130), True, 'import tensorflow as tf\n'), ((4164, 4215), 'utils.load_w2v', 'load_w2v', (['FLAGS.embedding_path', 'FLAGS.embedding_dim'], {}), '(FLAGS.embedding_path, FLAGS.embedding_dim)\n', (4172, 4215), False, 'from utils import load_w2v, batch_index, load_inputs_twitter, load_word_id_mapping\n'), ((4242, 4299), 'tensorflow.constant', 'tf.constant', (['w2v'], {'dtype': 'np.float32', 'name': '"""word_embedding"""'}), "(w2v, dtype=np.float32, name='word_embedding')\n", (4253, 4299), True, 'import tensorflow as tf\n'), ((4324, 4350), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {}), '(tf.float32)\n', (4338, 4350), True, 'import tensorflow as tf\n'), ((4373, 4399), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {}), '(tf.float32)\n', (4387, 4399), True, 'import tensorflow as tf\n'), ((5011, 5052), 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['word_embedding', 'x'], {}), '(word_embedding, x)\n', (5033, 5052), True, 'import tensorflow as tf\n'), ((5071, 5123), 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['word_embedding', 'target_words'], {}), '(word_embedding, target_words)\n', (5093, 5123), True, 'import tensorflow as tf\n'), ((5147, 5195), 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['word_embedding', 'ns_words'], {}), '(word_embedding, ns_words)\n', (5169, 5195), True, 'import tensorflow as tf\n'), ((5763, 5817), 'tensorflow.Variable', 'tf.Variable', (['(0)'], {'name': '"""tr_global_step"""', 'trainable': '(False)'}), "(0, name='tr_global_step', trainable=False)\n", (5774, 5817), True, 'import tensorflow as tf\n'), ((6091, 6106), 'tensorflow.argmax', 'tf.argmax', (['y', '(1)'], {}), '(y, 1)\n', (6100, 6106), True, 'import tensorflow as tf\n'), ((6125, 6143), 'tensorflow.argmax', 'tf.argmax', (['prob', '(1)'], {}), '(prob, 1)\n', (6134, 6143), True, 'import tensorflow as tf\n'), ((6616, 6641), 'tensorflow.Session', 'tf.Session', ([], {'config': 'config'}), '(config=config)\n', (6626, 6641), True, 'import tensorflow as tf\n'), ((6794, 6820), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {}), '(tf.float32)\n', (6808, 6820), True, 'import tensorflow as tf\n'), ((6841, 6867), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {}), '(tf.float32)\n', (6855, 6867), True, 'import tensorflow as tf\n'), ((7490, 7601), 'utils.load_inputs_twitter', 'load_inputs_twitter', (['train_path', 'word_id_mapping', 'FLAGS.max_sentence_len', '"""IAN"""', 'is_r', 'FLAGS.max_target_len'], {}), "(train_path, word_id_mapping, FLAGS.max_sentence_len,\n 'IAN', is_r, FLAGS.max_target_len)\n", (7509, 7601), False, 'from utils import load_w2v, batch_index, load_inputs_twitter, load_word_id_mapping\n'), ((7796, 7906), 'utils.load_inputs_twitter', 'load_inputs_twitter', (['test_path', 'word_id_mapping', 'FLAGS.max_sentence_len', '"""IAN"""', 'is_r', 'FLAGS.max_target_len'], {}), "(test_path, word_id_mapping, FLAGS.max_sentence_len,\n 'IAN', is_r, FLAGS.max_target_len)\n", (7815, 7906), False, 'from utils import load_w2v, batch_index, load_inputs_twitter, load_word_id_mapping\n'), ((11842, 11887), 'sklearn.metrics.precision_score', 'precision_score', (['max_ty', 'max_py'], {'average': 'None'}), '(max_ty, max_py, average=None)\n', (11857, 11887), False, 'from sklearn.metrics import precision_score, recall_score, f1_score, accuracy_score\n'), ((11901, 11943), 'sklearn.metrics.recall_score', 'recall_score', (['max_ty', 'max_py'], {'average': 'None'}), '(max_ty, max_py, average=None)\n', (11913, 11943), False, 'from sklearn.metrics import precision_score, recall_score, f1_score, accuracy_score\n'), ((11958, 11996), 'sklearn.metrics.f1_score', 'f1_score', (['max_ty', 'max_py'], {'average': 'None'}), '(max_ty, max_py, average=None)\n', (11966, 11996), False, 'from sklearn.metrics import precision_score, recall_score, f1_score, accuracy_score\n'), ((4416, 4439), 'tensorflow.name_scope', 'tf.name_scope', (['"""inputs"""'], {}), "('inputs')\n", (4429, 4439), True, 'import tensorflow as tf\n'), ((4458, 4514), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[None, FLAGS.max_sentence_len]'], {}), '(tf.int32, [None, FLAGS.max_sentence_len])\n', (4472, 4514), True, 'import tensorflow as tf\n'), ((4532, 4581), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, FLAGS.n_class]'], {}), '(tf.float32, [None, FLAGS.n_class])\n', (4546, 4581), True, 'import tensorflow as tf\n'), ((4604, 4654), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, FLAGS.n_aspect]'], {}), '(tf.float32, [None, FLAGS.n_aspect])\n', (4618, 4654), True, 'import tensorflow as tf\n'), ((4678, 4708), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', 'None'], {}), '(tf.int32, None)\n', (4692, 4708), True, 'import tensorflow as tf\n'), ((4735, 4791), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[None, FLAGS.max_sentence_len]'], {}), '(tf.int32, [None, FLAGS.max_sentence_len])\n', (4749, 4791), True, 'import tensorflow as tf\n'), ((4819, 4849), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', 'None'], {}), '(tf.int32, None)\n', (4833, 4849), True, 'import tensorflow as tf\n'), ((4880, 4934), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[None, FLAGS.max_target_len]'], {}), '(tf.int32, [None, FLAGS.max_target_len])\n', (4894, 4934), True, 'import tensorflow as tf\n'), ((4958, 4990), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[None]'], {}), '(tf.int32, [None])\n', (4972, 4990), True, 'import tensorflow as tf\n'), ((7215, 7248), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (7246, 7248), True, 'import tensorflow as tf\n'), ((5839, 5929), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {'learning_rate': 'learning_rate', 'beta1': 'b1', 'beta2': 'b2', 'epsilon': '(1e-08)'}), '(learning_rate=learning_rate, beta1=b1, beta2=b2,\n epsilon=1e-08)\n', (5861, 5929), True, 'import tensorflow as tf\n'), ((6701, 6712), 'time.time', 'time.time', ([], {}), '()\n', (6710, 6712), False, 'import time\n'), ((10699, 10714), 'numpy.asarray', 'np.asarray', (['_ty'], {}), '(_ty)\n', (10709, 10714), True, 'import numpy as np\n'), ((10737, 10752), 'numpy.asarray', 'np.asarray', (['_py'], {}), '(_py)\n', (10747, 10752), True, 'import numpy as np\n'), ((10774, 10788), 'numpy.asarray', 'np.asarray', (['_p'], {}), '(_p)\n', (10784, 10788), True, 'import numpy as np\n'), ((10811, 10827), 'numpy.asarray', 'np.asarray', (['_att'], {}), '(_att)\n', (10821, 10827), True, 'import numpy as np\n'), ((10856, 10876), 'numpy.asarray', 'np.asarray', (['sent_emb'], {}), '(sent_emb)\n', (10866, 10876), True, 'import numpy as np\n'), ((13207, 13234), 'numpy.subtract', 'np.subtract', (['max_py', 'max_ty'], {}), '(max_py, max_ty)\n', (13218, 13234), True, 'import numpy as np\n')]
|
import numpy as np
def function_for_pos(mass, mom):
return mom / mass
def function_for_mom(mass1, mass2, diff, dist):
return - mass1 * mass2 / dist ** 3 * diff
def compute_k(mass, pos, mom):
pos_k = [0] * len(pos)
mom_k = [0] * len(pos)
tmp_index = np.arange(len(pos))
index_j, index_i = np.meshgrid(tmp_index, tmp_index)
for i in range(len(pos)):
diff = pos[index_i] - pos[index_j]
dist = np.linalg.norm(pos[index_i]-pos[index_j], axis=2)
pos_k[i] = function_for_pos(mass[i], mom[i])
mom_k[i] = np.nansum([function_for_mom(mass[i], mass[j], diff[i][j], dist[i][j]) for j in range(len(pos))], axis=0)
return np.array(pos_k), np.array(mom_k)
def runge_kutta_4th(pos, mass, mom, dt):
pos_k1, mom_k1 = compute_k(mass, pos, mom)
tmp_pos = pos + 0.5 * dt * pos_k1
tmp_mom = mom + 0.5 * dt * mom_k1
pos_k2, mom_k2 = compute_k(mass, tmp_pos, tmp_mom)
tmp_pos = pos + 0.5 * dt * pos_k2
tmp_mom = mom + 0.5 * dt * mom_k2
pos_k3, mom_k3 = compute_k(mass, tmp_pos, tmp_mom)
tmp_pos = pos + dt * np.array(pos_k3)
tmp_mom = mom + dt * np.array(mom_k3)
pos_k4, mom_k4 = compute_k(mass, tmp_pos, tmp_mom)
delta_pos = dt / 6 * (pos_k1+2*pos_k2+2*pos_k3+pos_k4)
delta_mom = dt / 6 * (mom_k1+2*mom_k2+2*mom_k3+mom_k4)
pos = pos + delta_pos
mom = mom + delta_mom
return pos, mom
|
[
"numpy.array",
"numpy.meshgrid",
"numpy.linalg.norm"
] |
[((317, 350), 'numpy.meshgrid', 'np.meshgrid', (['tmp_index', 'tmp_index'], {}), '(tmp_index, tmp_index)\n', (328, 350), True, 'import numpy as np\n'), ((443, 494), 'numpy.linalg.norm', 'np.linalg.norm', (['(pos[index_i] - pos[index_j])'], {'axis': '(2)'}), '(pos[index_i] - pos[index_j], axis=2)\n', (457, 494), True, 'import numpy as np\n'), ((681, 696), 'numpy.array', 'np.array', (['pos_k'], {}), '(pos_k)\n', (689, 696), True, 'import numpy as np\n'), ((698, 713), 'numpy.array', 'np.array', (['mom_k'], {}), '(mom_k)\n', (706, 713), True, 'import numpy as np\n'), ((1094, 1110), 'numpy.array', 'np.array', (['pos_k3'], {}), '(pos_k3)\n', (1102, 1110), True, 'import numpy as np\n'), ((1136, 1152), 'numpy.array', 'np.array', (['mom_k3'], {}), '(mom_k3)\n', (1144, 1152), True, 'import numpy as np\n')]
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 18 20:55:39 2017
@author: <NAME>
"""
import NetBuilder as nb
import numpy as np
import sys
from sklearn.preprocessing import normalize as norm
def extract_data(filename):
with open(filename) as f:
data = np.loadtxt(f,delimiter=',',skiprows=1)
#The samples should be mixed more randomly to improve convergence
np.random.shuffle(data)
#normalize the data
#data = norm(data,axis=0) #with axis=0, each column in normalized independently of each other
#split inputs from target outputs (assume last column corresponds to labels or targets)
inputs = norm(data[:,:-1],axis=0)
targets = data[:,-1] #
targets = np.reshape(a=targets,newshape=(len(targets),1)) #targets should have the shape of [number of sumples x number of output features per sample]
#array_change_zeros = np.vectorize(change_zeros)
#targets = array_change_zeros(targets) #Here I am changing 0s to -1s because I intend to use the hyperbolic tangent function for the final layer of the network and it works better this way
return inputs, targets
def change_zeros(num):
if num==0:
return -1.
else:
return 1
def get_one_sample(data_inputs,data_targets,idx=None):
if idx==None:
idx = np.random.randint(0,len(data_inputs))
sample_in = data_inputs[idx:idx+1]
sample_tar = data_targets[idx:idx+1]
return sample_in,sample_tar
#First read the training data:
#data_file = sys.argv[1]
if __name__=='__main__':
array_change_zeros = np.vectorize(change_zeros)
data_file = sys.argv[1] #file containing the data
#data_file = 'curated_train_set.csv'
inputs,targets = extract_data(data_file)
#define the network structure:
input_features = len(inputs[0]) #the number of columns in the data matrix (this will be the number of input nodes to the network's first layer)
output_features = len(targets[0]) #this should be 1 (this will be the number of output nodes to the last layer)
#create the model
topology = [input_features,5,output_features]
try:
max_epochs = int(sys.argv[4]) #how many training epochs to run?
except:
max_epochs = 1000
batch_size = int(sys.argv[2]) #how many samples per iteration: number of iterations = number of epochs / batch size
print_rate = int(sys.argv[3]) #how often should training updates be printed? decreased for higher frequency
net = nb.Network(topology=topology,learningRate=0.01)
net.set_hiddenactivation_fun('sigmoid')
net.set_outActivation_fun('sigmoid')
net.train(input_set=inputs,
target_set=targets,
epochs=max_epochs,
batch_size=batch_size,
print_rate=print_rate)
#Saved the state of the network:
net.save('peptideNet.csv')
print('='*80,'\nTEST\n:')
test_in,test_tar = get_one_sample(inputs,targets)
test_out = net.feedforward(test_in)
print('Input:',test_in,'\nExpected:\tActual Output\n',test_tar,test_out)
|
[
"numpy.vectorize",
"NetBuilder.Network",
"sklearn.preprocessing.normalize",
"numpy.loadtxt",
"numpy.random.shuffle"
] |
[((1696, 1722), 'numpy.vectorize', 'np.vectorize', (['change_zeros'], {}), '(change_zeros)\n', (1708, 1722), True, 'import numpy as np\n'), ((2671, 2719), 'NetBuilder.Network', 'nb.Network', ([], {'topology': 'topology', 'learningRate': '(0.01)'}), '(topology=topology, learningRate=0.01)\n', (2681, 2719), True, 'import NetBuilder as nb\n'), ((288, 328), 'numpy.loadtxt', 'np.loadtxt', (['f'], {'delimiter': '""","""', 'skiprows': '(1)'}), "(f, delimiter=',', skiprows=1)\n", (298, 328), True, 'import numpy as np\n'), ((418, 441), 'numpy.random.shuffle', 'np.random.shuffle', (['data'], {}), '(data)\n', (435, 441), True, 'import numpy as np\n'), ((704, 730), 'sklearn.preprocessing.normalize', 'norm', (['data[:, :-1]'], {'axis': '(0)'}), '(data[:, :-1], axis=0)\n', (708, 730), True, 'from sklearn.preprocessing import normalize as norm\n')]
|
# coding=utf-8
# @Author : zhzhx2008
# @Date : 2019/12/29
# from:
# https://arxiv.org/abs/1611.01747,《A COMPARE-AGGREGATE MODEL FOR MATCHING TEXT SEQUENCES》
import warnings
import jieba
import numpy as np
from keras import Model, regularizers, constraints, initializers
from keras.callbacks import EarlyStopping, ModelCheckpoint
from keras.layers import *
from keras.preprocessing import sequence
from keras.preprocessing.text import Tokenizer
from sklearn.model_selection import train_test_split
from keras import backend as K
warnings.filterwarnings("ignore")
seed = 2019
np.random.seed(seed)
class Comapre_Aggregate(Layer):
def __init__(self, hidden_size, comparison='nn', bias = True,
initial = 'glorot_uniform',
W_regularizer=None, b_regularizer=None,
W_constraint=None, b_constraint=None,
**kwargs):
self.hidden_size = hidden_size
self.comparision = comparison
self.init = initializers.get(initial)
self.W_regularizer = regularizers.get(W_regularizer)
self.b_regularizer = regularizers.get(b_regularizer)
self.W_constraint = constraints.get(W_constraint)
self.b_constraint = constraints.get(b_constraint)
self.bias = bias
super(Comapre_Aggregate, self).__init__(**kwargs)
def build(self, input_shape):
self.Wi = self.add_weight(name='Wi',
shape=(input_shape[0][-1], self.hidden_size),
initializer=self.init,
regularizer = self.W_regularizer,
trainable=True,
constraint=self.W_constraint)
self.Wu = self.add_weight(name='Wu',
shape=(input_shape[0][-1], self.hidden_size),
initializer=self.init,
regularizer = self.W_regularizer,
trainable=True,
constraint=self.W_constraint)
self.Wg = self.add_weight(name='Wg',
shape=(self.hidden_size, self.hidden_size),
initializer=self.init,
regularizer = self.W_regularizer,
trainable=True,
constraint=self.W_constraint)
if self.comparision == 'nn':
self.Wt = self.add_weight(name='Wt',
shape=(self.hidden_size * 2, self.hidden_size),
initializer=self.init,
regularizer=self.W_regularizer,
trainable=True,
constraint=self.W_constraint)
elif self.comparision == 'ntn':
self.WT = self.add_weight(name='WT',
shape=(self.hidden_size, self.hidden_size, self.hidden_size),
initializer=self.init,
regularizer=self.W_regularizer,
trainable=True,
constraint=self.W_constraint)
if self.bias:
self.bi = self.add_weight(name='bi',
shape=(self.hidden_size,),
initializer='zero',
regularizer=self.b_regularizer,
trainable=True,
constraint=self.b_constraint)
self.bu = self.add_weight(name='bu',
shape=(self.hidden_size,),
initializer='zero',
regularizer=self.b_regularizer,
trainable=True,
constraint=self.b_constraint)
self.bg = self.add_weight(name='bg',
shape=(self.hidden_size,),
initializer='zero',
regularizer=self.b_regularizer,
trainable=True,
constraint=self.b_constraint)
if self.comparision == 'nn':
self.bt = self.add_weight(name='bt',
shape=(self.hidden_size,),
initializer='zero',
regularizer=self.b_regularizer,
trainable=True,
constraint=self.b_constraint)
elif self.comparision == 'ntn':
self.bT = self.add_weight(name='bT',
shape=(self.hidden_size,),
initializer='zero',
regularizer=self.b_regularizer,
trainable=True,
constraint=self.b_constraint)
super(Comapre_Aggregate, self).build(input_shape)
def call(self, x, **kwargs):
assert len(x) == 2
Q, A = x
Q = K.sigmoid(K.bias_add(K.dot(Q, self.Wi), self.bi)) * K.tanh(K.bias_add(K.dot(Q, self.Wu), self.bu))
A = K.sigmoid(K.bias_add(K.dot(A, self.Wi), self.bi)) * K.tanh(K.bias_add(K.dot(A, self.Wu), self.bu))
G = K.batch_dot(K.bias_add(K.dot(Q, self.Wg), self.bg), A, axes=[-1, -1])
G = K.softmax(G, axis=1)
H = K.batch_dot(G, Q, axes=[1, 1])
T = None
if self.comparision == 'nn':
T = concatenate([A, H])
T = K.dot(T, self.Wt)
T = K.bias_add(T, self.bt)
T = K.relu(T)
elif self.comparision == 'ntn':
T = K.dot(A, self.WT)
T = K.batch_dot(T, H, axes=[-1, -1])
T = K.bias_add(T, self.bT)
T = K.relu(T)
elif self.comparision == 'eu_cos':
T1 = K.sum(K.square(K.abs(A - H)))
T2 = K.sum(A, H) / K.sqrt(K.square(A)) * K.sqrt(K.square(H))
T = K.concatenate([T1, T2])
elif self.comparision == 'sub':
T = (A - H) * (A - H)
elif self.comparision == 'mult':
T = A * H
elif self.comparision == 'sub_mult_nn':
T = K.relu(K.bias_add(K.dot(K.concatenate([(A - H) * (A - H), A * H]), self.Wt), self.bt))
else:
pass
return T
def compute_output_shape(self, input_shape):
return (input_shape[1][0], input_shape[1][1], self.hidden_size)
def get_datas(input_file):
datas = []
with open(input_file, 'r') as fin:
for line in fin:
line = line.strip()
if '' == line:
continue
split = line.split('\t')
if 4 != len(split):
continue
q1 = split[1].strip()
q1_word = ' '.join(jieba.cut(q1))
q1_char = ' '.join(list(q1))
q2 = split[2].strip()
q2_word = ' '.join(jieba.cut(q2))
q2_char = ' '.join(list(q2))
label = int(split[3].strip())
datas.append((q1_word, q2_word, q1_char, q2_char, label))
return datas
input_file = './data/atec_nlp_sim_train.csv'
input_file_add = './data/atec_nlp_sim_train_add.csv'
datas = get_datas(input_file)
datas.extend(get_datas(input_file_add))
np.random.shuffle(datas)
datas = datas[:1000]
datas, datas_test = train_test_split(datas, test_size=0.3, shuffle=True)
datas_train, datas_dev = train_test_split(datas, test_size=0.3, shuffle=True)
q1_word_train = [x[0] for x in datas_train]
q1_word_dev = [x[0] for x in datas_dev]
q1_word_test = [x[0] for x in datas_test]
q2_word_train = [x[1] for x in datas_train]
q2_word_dev = [x[1] for x in datas_dev]
q2_word_test = [x[1] for x in datas_test]
q1_char_train = [x[2] for x in datas_train]
q1_char_dev = [x[2] for x in datas_dev]
q1_char_test = [x[2] for x in datas_test]
q2_char_train = [x[3] for x in datas_train]
q2_char_dev = [x[3] for x in datas_dev]
q2_char_test = [x[3] for x in datas_test]
label_train = [x[4] for x in datas_train]
label_dev = [x[4] for x in datas_dev]
label_test = [x[4] for x in datas_test]
# keras extract feature
tokenizer = Tokenizer()
tokenizer.fit_on_texts(q1_word_train + q2_word_train)
# feature5: word index for deep learning
q1_train_word_index = tokenizer.texts_to_sequences(q1_word_train)
q1_dev_word_index = tokenizer.texts_to_sequences(q1_word_dev)
q1_test_word_index = tokenizer.texts_to_sequences(q1_word_test)
q2_train_word_index = tokenizer.texts_to_sequences(q2_word_train)
q2_dev_word_index = tokenizer.texts_to_sequences(q2_word_dev)
q2_test_word_index = tokenizer.texts_to_sequences(q2_word_test)
max_word_length = max(
[max(len(q1_idx), len(q2_idx)) for q1_idx in q1_train_word_index for q2_idx in q2_train_word_index])
q1_train_word_index = sequence.pad_sequences(q1_train_word_index, maxlen=max_word_length)
q1_dev_word_index = sequence.pad_sequences(q1_dev_word_index, maxlen=max_word_length)
q1_test_word_index = sequence.pad_sequences(q1_test_word_index, maxlen=max_word_length)
q2_train_word_index = sequence.pad_sequences(q2_train_word_index, maxlen=max_word_length)
q2_dev_word_index = sequence.pad_sequences(q2_dev_word_index, maxlen=max_word_length)
q2_test_word_index = sequence.pad_sequences(q2_test_word_index, maxlen=max_word_length)
maxlen = max_word_length
voc_size = len(tokenizer.word_index)
embedding_dim = 300
drop_out = 0.2
hidden_size = 150
q_input = Input(name='q', shape=(maxlen,))
a_input = Input(name='a', shape=(maxlen,))
# 1. Input Encoding
embedding = Embedding(voc_size + 1, embedding_dim)
spatialdropout = SpatialDropout1D(drop_out)
q_embed = embedding(q_input)
a_embed = embedding(a_input)
q_embed = spatialdropout(q_embed)
a_embed = spatialdropout(a_embed)
com_agg = Comapre_Aggregate(hidden_size)([q_embed, a_embed])
cnn1 = Conv1D(hidden_size, 3, padding='same', strides=1, activation='relu')(com_agg)
cnn1 = GlobalMaxPool1D()(cnn1)
cnn2 = Conv1D(hidden_size, 4, padding='same', strides=1, activation='relu')(com_agg)
cnn2 = GlobalMaxPool1D()(cnn2)
cnn3 = Conv1D(hidden_size, 5, padding='same', strides=1, activation='relu')(com_agg)
cnn3 = GlobalMaxPool1D()(cnn3)
cnn = concatenate([cnn1, cnn2, cnn3], axis=-1)
out = Dense(1, activation='sigmoid')(cnn)
model = Model(inputs=[q_input, a_input], outputs=out)
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
print(model.summary())
model_weight_file = './model_compare_aggregate.h5'
model_file = './model_compare_aggregate.model'
early_stopping = EarlyStopping(monitor='val_loss', patience=5)
model_checkpoint = ModelCheckpoint(model_weight_file, save_best_only=True, save_weights_only=True)
model.fit([q1_train_word_index, q2_train_word_index],
label_train,
batch_size=32,
epochs=1000,
verbose=2,
callbacks=[early_stopping, model_checkpoint],
validation_data=([q1_dev_word_index, q2_dev_word_index], label_dev),
shuffle=True)
model.load_weights(model_weight_file)
model.save(model_file)
evaluate = model.evaluate([q1_test_word_index, q2_test_word_index], label_test, batch_size=32, verbose=2)
print('loss value=' + str(evaluate[0]))
print('metrics value=' + str(evaluate[1]))
|
[
"keras.backend.dot",
"numpy.random.seed",
"keras.preprocessing.sequence.pad_sequences",
"sklearn.model_selection.train_test_split",
"keras.regularizers.get",
"keras.backend.batch_dot",
"keras.backend.abs",
"keras.backend.relu",
"keras.backend.concatenate",
"keras.preprocessing.text.Tokenizer",
"keras.constraints.get",
"keras.initializers.get",
"numpy.random.shuffle",
"keras.Model",
"keras.callbacks.ModelCheckpoint",
"jieba.cut",
"keras.backend.bias_add",
"warnings.filterwarnings",
"keras.backend.sum",
"keras.callbacks.EarlyStopping",
"keras.backend.softmax",
"keras.backend.square"
] |
[((538, 571), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (561, 571), False, 'import warnings\n'), ((585, 605), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (599, 605), True, 'import numpy as np\n'), ((7694, 7718), 'numpy.random.shuffle', 'np.random.shuffle', (['datas'], {}), '(datas)\n', (7711, 7718), True, 'import numpy as np\n'), ((7761, 7813), 'sklearn.model_selection.train_test_split', 'train_test_split', (['datas'], {'test_size': '(0.3)', 'shuffle': '(True)'}), '(datas, test_size=0.3, shuffle=True)\n', (7777, 7813), False, 'from sklearn.model_selection import train_test_split\n'), ((7839, 7891), 'sklearn.model_selection.train_test_split', 'train_test_split', (['datas'], {'test_size': '(0.3)', 'shuffle': '(True)'}), '(datas, test_size=0.3, shuffle=True)\n', (7855, 7891), False, 'from sklearn.model_selection import train_test_split\n'), ((8554, 8565), 'keras.preprocessing.text.Tokenizer', 'Tokenizer', ([], {}), '()\n', (8563, 8565), False, 'from keras.preprocessing.text import Tokenizer\n'), ((9196, 9263), 'keras.preprocessing.sequence.pad_sequences', 'sequence.pad_sequences', (['q1_train_word_index'], {'maxlen': 'max_word_length'}), '(q1_train_word_index, maxlen=max_word_length)\n', (9218, 9263), False, 'from keras.preprocessing import sequence\n'), ((9284, 9349), 'keras.preprocessing.sequence.pad_sequences', 'sequence.pad_sequences', (['q1_dev_word_index'], {'maxlen': 'max_word_length'}), '(q1_dev_word_index, maxlen=max_word_length)\n', (9306, 9349), False, 'from keras.preprocessing import sequence\n'), ((9371, 9437), 'keras.preprocessing.sequence.pad_sequences', 'sequence.pad_sequences', (['q1_test_word_index'], {'maxlen': 'max_word_length'}), '(q1_test_word_index, maxlen=max_word_length)\n', (9393, 9437), False, 'from keras.preprocessing import sequence\n'), ((9460, 9527), 'keras.preprocessing.sequence.pad_sequences', 'sequence.pad_sequences', (['q2_train_word_index'], {'maxlen': 'max_word_length'}), '(q2_train_word_index, maxlen=max_word_length)\n', (9482, 9527), False, 'from keras.preprocessing import sequence\n'), ((9548, 9613), 'keras.preprocessing.sequence.pad_sequences', 'sequence.pad_sequences', (['q2_dev_word_index'], {'maxlen': 'max_word_length'}), '(q2_dev_word_index, maxlen=max_word_length)\n', (9570, 9613), False, 'from keras.preprocessing import sequence\n'), ((9635, 9701), 'keras.preprocessing.sequence.pad_sequences', 'sequence.pad_sequences', (['q2_test_word_index'], {'maxlen': 'max_word_length'}), '(q2_test_word_index, maxlen=max_word_length)\n', (9657, 9701), False, 'from keras.preprocessing import sequence\n'), ((10658, 10703), 'keras.Model', 'Model', ([], {'inputs': '[q_input, a_input]', 'outputs': 'out'}), '(inputs=[q_input, a_input], outputs=out)\n', (10663, 10703), False, 'from keras import Model, regularizers, constraints, initializers\n'), ((10925, 10970), 'keras.callbacks.EarlyStopping', 'EarlyStopping', ([], {'monitor': '"""val_loss"""', 'patience': '(5)'}), "(monitor='val_loss', patience=5)\n", (10938, 10970), False, 'from keras.callbacks import EarlyStopping, ModelCheckpoint\n'), ((10990, 11069), 'keras.callbacks.ModelCheckpoint', 'ModelCheckpoint', (['model_weight_file'], {'save_best_only': '(True)', 'save_weights_only': '(True)'}), '(model_weight_file, save_best_only=True, save_weights_only=True)\n', (11005, 11069), False, 'from keras.callbacks import EarlyStopping, ModelCheckpoint\n'), ((990, 1015), 'keras.initializers.get', 'initializers.get', (['initial'], {}), '(initial)\n', (1006, 1015), False, 'from keras import Model, regularizers, constraints, initializers\n'), ((1045, 1076), 'keras.regularizers.get', 'regularizers.get', (['W_regularizer'], {}), '(W_regularizer)\n', (1061, 1076), False, 'from keras import Model, regularizers, constraints, initializers\n'), ((1106, 1137), 'keras.regularizers.get', 'regularizers.get', (['b_regularizer'], {}), '(b_regularizer)\n', (1122, 1137), False, 'from keras import Model, regularizers, constraints, initializers\n'), ((1166, 1195), 'keras.constraints.get', 'constraints.get', (['W_constraint'], {}), '(W_constraint)\n', (1181, 1195), False, 'from keras import Model, regularizers, constraints, initializers\n'), ((1224, 1253), 'keras.constraints.get', 'constraints.get', (['b_constraint'], {}), '(b_constraint)\n', (1239, 1253), False, 'from keras import Model, regularizers, constraints, initializers\n'), ((5760, 5780), 'keras.backend.softmax', 'K.softmax', (['G'], {'axis': '(1)'}), '(G, axis=1)\n', (5769, 5780), True, 'from keras import backend as K\n'), ((5793, 5823), 'keras.backend.batch_dot', 'K.batch_dot', (['G', 'Q'], {'axes': '[1, 1]'}), '(G, Q, axes=[1, 1])\n', (5804, 5823), True, 'from keras import backend as K\n'), ((5931, 5948), 'keras.backend.dot', 'K.dot', (['T', 'self.Wt'], {}), '(T, self.Wt)\n', (5936, 5948), True, 'from keras import backend as K\n'), ((5965, 5987), 'keras.backend.bias_add', 'K.bias_add', (['T', 'self.bt'], {}), '(T, self.bt)\n', (5975, 5987), True, 'from keras import backend as K\n'), ((6004, 6013), 'keras.backend.relu', 'K.relu', (['T'], {}), '(T)\n', (6010, 6013), True, 'from keras import backend as K\n'), ((5701, 5718), 'keras.backend.dot', 'K.dot', (['Q', 'self.Wg'], {}), '(Q, self.Wg)\n', (5706, 5718), True, 'from keras import backend as K\n'), ((6070, 6087), 'keras.backend.dot', 'K.dot', (['A', 'self.WT'], {}), '(A, self.WT)\n', (6075, 6087), True, 'from keras import backend as K\n'), ((6104, 6136), 'keras.backend.batch_dot', 'K.batch_dot', (['T', 'H'], {'axes': '[-1, -1]'}), '(T, H, axes=[-1, -1])\n', (6115, 6136), True, 'from keras import backend as K\n'), ((6153, 6175), 'keras.backend.bias_add', 'K.bias_add', (['T', 'self.bT'], {}), '(T, self.bT)\n', (6163, 6175), True, 'from keras import backend as K\n'), ((6192, 6201), 'keras.backend.relu', 'K.relu', (['T'], {}), '(T)\n', (6198, 6201), True, 'from keras import backend as K\n'), ((7217, 7230), 'jieba.cut', 'jieba.cut', (['q1'], {}), '(q1)\n', (7226, 7230), False, 'import jieba\n'), ((7338, 7351), 'jieba.cut', 'jieba.cut', (['q2'], {}), '(q2)\n', (7347, 7351), False, 'import jieba\n'), ((5476, 5493), 'keras.backend.dot', 'K.dot', (['Q', 'self.Wi'], {}), '(Q, self.Wi)\n', (5481, 5493), True, 'from keras import backend as K\n'), ((5525, 5542), 'keras.backend.dot', 'K.dot', (['Q', 'self.Wu'], {}), '(Q, self.Wu)\n', (5530, 5542), True, 'from keras import backend as K\n'), ((5587, 5604), 'keras.backend.dot', 'K.dot', (['A', 'self.Wi'], {}), '(A, self.Wi)\n', (5592, 5604), True, 'from keras import backend as K\n'), ((5636, 5653), 'keras.backend.dot', 'K.dot', (['A', 'self.Wu'], {}), '(A, self.Wu)\n', (5641, 5653), True, 'from keras import backend as K\n'), ((6381, 6404), 'keras.backend.concatenate', 'K.concatenate', (['[T1, T2]'], {}), '([T1, T2])\n', (6394, 6404), True, 'from keras import backend as K\n'), ((6277, 6289), 'keras.backend.abs', 'K.abs', (['(A - H)'], {}), '(A - H)\n', (6282, 6289), True, 'from keras import backend as K\n'), ((6309, 6320), 'keras.backend.sum', 'K.sum', (['A', 'H'], {}), '(A, H)\n', (6314, 6320), True, 'from keras import backend as K\n'), ((6352, 6363), 'keras.backend.square', 'K.square', (['H'], {}), '(H)\n', (6360, 6363), True, 'from keras import backend as K\n'), ((6330, 6341), 'keras.backend.square', 'K.square', (['A'], {}), '(A)\n', (6338, 6341), True, 'from keras import backend as K\n'), ((6630, 6671), 'keras.backend.concatenate', 'K.concatenate', (['[(A - H) * (A - H), A * H]'], {}), '([(A - H) * (A - H), A * H])\n', (6643, 6671), True, 'from keras import backend as K\n')]
|
# %%
import rasterio
import pandas as pds
import numpy as np
import numpy.ma as ma
from sklearn.pipeline import Pipeline
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
import seaborn
# %%
HI_RES = '30s'
LOW_RES = '10m'
INCLUDE_VARS = [1,2,3,4,5,6,7,10,11]
vlab = ['meanT', 'diT', 'isoT', 'seaT', '+monT', '-monT', 'range', 'mean+Q', 'mean-Q']
def print_matrix(M, rlab=None, clab=None):
t = '\t'
if clab:
print('', end=t)
for cl in clab:
print(cl, end=t)
print('')
for ir, r in enumerate(M):
if rlab:
print(f'{rlab[ir]}', end=t)
for ic, c in enumerate(r):
print(f'{c:.2f}' if abs(c) > 0 else '', end=t)
print('')
def read_band(path):
with rasterio.open(path) as file:
return file.read(1, masked=True).ravel()
def build_matrix(res, varnums):
features = [read_band(f'./_data/wc2.1_{res}/bio_{num}.tif') for num in varnums]
return ma.mask_rows(ma.vstack(features).transpose())
# %%
raw_rows = build_matrix(LOW_RES, INCLUDE_VARS)
compressed = ma.compress_rows(raw_rows)
corr = np.corrcoef(compressed, rowvar=False)
cov = np.cov(compressed, rowvar=False)
# %%
scaler = StandardScaler()
scaled = scaler.fit_transform(compressed)
df = pds.DataFrame(scaled, columns=vlab)
# %%
pca = PCA(n_components=2)
df = pds.DataFrame(pca.fit_transform(scaled), columns=['pc1','pc2'])
# %%
kmeans = KMeans(n_clusters=8, random_state=3)
df['group'] = kmeans.fit_predict(df[['pc1', 'pc2']])
seaborn.jointplot(data=df, x='pc1', y='pc2', hue='group', kind='kde')
|
[
"pandas.DataFrame",
"rasterio.open",
"sklearn.preprocessing.StandardScaler",
"numpy.corrcoef",
"sklearn.cluster.KMeans",
"sklearn.decomposition.PCA",
"seaborn.jointplot",
"numpy.ma.vstack",
"numpy.cov",
"numpy.ma.compress_rows"
] |
[((1169, 1195), 'numpy.ma.compress_rows', 'ma.compress_rows', (['raw_rows'], {}), '(raw_rows)\n', (1185, 1195), True, 'import numpy.ma as ma\n'), ((1204, 1241), 'numpy.corrcoef', 'np.corrcoef', (['compressed'], {'rowvar': '(False)'}), '(compressed, rowvar=False)\n', (1215, 1241), True, 'import numpy as np\n'), ((1248, 1280), 'numpy.cov', 'np.cov', (['compressed'], {'rowvar': '(False)'}), '(compressed, rowvar=False)\n', (1254, 1280), True, 'import numpy as np\n'), ((1295, 1311), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (1309, 1311), False, 'from sklearn.preprocessing import StandardScaler\n'), ((1359, 1394), 'pandas.DataFrame', 'pds.DataFrame', (['scaled'], {'columns': 'vlab'}), '(scaled, columns=vlab)\n', (1372, 1394), True, 'import pandas as pds\n'), ((1407, 1426), 'sklearn.decomposition.PCA', 'PCA', ([], {'n_components': '(2)'}), '(n_components=2)\n', (1410, 1426), False, 'from sklearn.decomposition import PCA\n'), ((1511, 1547), 'sklearn.cluster.KMeans', 'KMeans', ([], {'n_clusters': '(8)', 'random_state': '(3)'}), '(n_clusters=8, random_state=3)\n', (1517, 1547), False, 'from sklearn.cluster import KMeans\n'), ((1601, 1670), 'seaborn.jointplot', 'seaborn.jointplot', ([], {'data': 'df', 'x': '"""pc1"""', 'y': '"""pc2"""', 'hue': '"""group"""', 'kind': '"""kde"""'}), "(data=df, x='pc1', y='pc2', hue='group', kind='kde')\n", (1618, 1670), False, 'import seaborn\n'), ((851, 870), 'rasterio.open', 'rasterio.open', (['path'], {}), '(path)\n', (864, 870), False, 'import rasterio\n'), ((1070, 1089), 'numpy.ma.vstack', 'ma.vstack', (['features'], {}), '(features)\n', (1079, 1089), True, 'import numpy.ma as ma\n')]
|
"""
.. module:: get_data_hlsp_everest
:synopsis: Returns EVEREST lightcurve data as a JSON string.
.. moduleauthor:: <NAME> <<EMAIL>>
"""
import collections
import numpy
from astropy.io import fits
from data_series import DataSeries
from parse_obsid_hlsp_everest import parse_obsid_hlsp_everest
#--------------------
def get_data_hlsp_everest(obsid):
"""
Given a EVEREST observation ID, returns the lightcurve data.
:param obsid: The EVEREST observation ID to retrieve the data from.
:type obsid: str
:returns: JSON -- The lightcurve data for this observation ID.
Error codes:
From parse_obsid_hlsp_everest:
0 = No error.
1 = Error parsing EVEREST observation ID.
2 = Cadence not recognized as long cadence.
3 = File is missing on disk.
From this module:
4 = FITS file does not have the expected number of FITS extensions.
5 = Could not open FITS file for reading.
6 = All values were non-finite in x and/or y.
"""
# This defines a data point for a DataSeries object as a namedtuple.
data_point = collections.namedtuple('DataPoint', ['x', 'y'])
# For EVEREST, this defines the x-axis and y-axis units as a string.
everest_xunit = "BJD"
everest_yunit = "electrons / second"
# Parse the obsID string to determine the paths+files to read. Note:
# this step will assign some of the error codes returned to the top level.
parsed_file_result = parse_obsid_hlsp_everest(obsid)
if parsed_file_result.errcode == 0:
# For each file, read in the contents and create a return JSON object.
all_plot_labels = ['']*2*len(parsed_file_result.files)
all_plot_series = ['']*2*len(parsed_file_result.files)
all_plot_xunits = ['']*2*len(parsed_file_result.files)
all_plot_yunits = ['']*2*len(parsed_file_result.files)
# This error code will be used unless there's a problem reading any of
# the FITS files in the list.
errcode = 0
for kfile in parsed_file_result.files:
try:
with fits.open(kfile) as hdulist:
# Extract time stamps and relevant fluxes.
if len(hdulist) == 6:
# Timestamps.
bjd = (hdulist[1].data["TIME"] +
hdulist[1].header["BJDREFF"] +
hdulist[1].header["BJDREFI"])
# Raw flux.
raw_flux = hdulist[1].data["FRAW"]
# Corrected flux.
cor_flux = hdulist[1].data["FCOR"]
# Only keep those points that don't have NaN's in them.
where_keep = numpy.where(
(numpy.isfinite(bjd)) &
(numpy.isfinite(raw_flux)) &
(numpy.isfinite(cor_flux)))[0]
if where_keep.size > 0:
bjd = bjd[where_keep]
raw_flux = raw_flux[where_keep]
cor_flux = cor_flux[where_keep]
else:
errcode = 6
# Create the plot label and plot series for the
# extracted and detrended fluxes.
this_plot_label = (
'EVEREST_' + parsed_file_result.everestid +
' ' + parsed_file_result.campaign.upper())
if errcode == 0:
# Get arrays into regular list with decimal limits.
bjd = [float("{0:.8f}".format(x)) for x in bjd]
raw_flux = [float("{0:.8f}".format(x))
for x in raw_flux]
cor_flux = [float("{0:.8f}".format(x))
for x in cor_flux]
all_plot_labels[0] = (this_plot_label +
' Raw')
all_plot_series[0] = [data_point(x=x, y=y) for
x, y in zip(bjd, raw_flux)]
all_plot_xunits[0] = everest_xunit
all_plot_yunits[0] = everest_yunit
all_plot_labels[1] = (this_plot_label +
' Corrected')
all_plot_series[1] = [data_point(x=x, y=y) for
x, y in zip(bjd,
cor_flux)]
all_plot_xunits[1] = everest_xunit
all_plot_yunits[1] = everest_yunit
else:
all_plot_labels[0] = ''
all_plot_series[0] = []
all_plot_xunits[0] = ''
all_plot_yunits[0] = ''
all_plot_labels[1] = ''
all_plot_series[1] = []
all_plot_xunits[1] = ''
all_plot_yunits[1] = ''
else:
# Then there aren't the expected number of extensions.
errcode = 4
except IOError:
errcode = 5
all_plot_labels[0] = ''
all_plot_series[0] = []
all_plot_xunits[0] = ''
all_plot_yunits[0] = ''
all_plot_labels[1] = ''
all_plot_series[1] = []
all_plot_xunits[1] = ''
all_plot_yunits[1] = ''
# Create the return DataSeries object.
return_dataseries = DataSeries('hlsp_everest', obsid, all_plot_series,
all_plot_labels,
all_plot_xunits, all_plot_yunits,
errcode)
else:
# This is where an error DataSeries object would be returned.
return_dataseries = DataSeries('hlsp_everest', obsid, [], [], [], [],
parsed_file_result.errcode)
# Return the DataSeries object back to the calling module.
return return_dataseries
#--------------------
|
[
"numpy.isfinite",
"astropy.io.fits.open",
"collections.namedtuple",
"parse_obsid_hlsp_everest.parse_obsid_hlsp_everest",
"data_series.DataSeries"
] |
[((1081, 1128), 'collections.namedtuple', 'collections.namedtuple', (['"""DataPoint"""', "['x', 'y']"], {}), "('DataPoint', ['x', 'y'])\n", (1103, 1128), False, 'import collections\n'), ((1449, 1480), 'parse_obsid_hlsp_everest.parse_obsid_hlsp_everest', 'parse_obsid_hlsp_everest', (['obsid'], {}), '(obsid)\n', (1473, 1480), False, 'from parse_obsid_hlsp_everest import parse_obsid_hlsp_everest\n'), ((5895, 6009), 'data_series.DataSeries', 'DataSeries', (['"""hlsp_everest"""', 'obsid', 'all_plot_series', 'all_plot_labels', 'all_plot_xunits', 'all_plot_yunits', 'errcode'], {}), "('hlsp_everest', obsid, all_plot_series, all_plot_labels,\n all_plot_xunits, all_plot_yunits, errcode)\n", (5905, 6009), False, 'from data_series import DataSeries\n'), ((6231, 6308), 'data_series.DataSeries', 'DataSeries', (['"""hlsp_everest"""', 'obsid', '[]', '[]', '[]', '[]', 'parsed_file_result.errcode'], {}), "('hlsp_everest', obsid, [], [], [], [], parsed_file_result.errcode)\n", (6241, 6308), False, 'from data_series import DataSeries\n'), ((2076, 2092), 'astropy.io.fits.open', 'fits.open', (['kfile'], {}), '(kfile)\n', (2085, 2092), False, 'from astropy.io import fits\n'), ((2892, 2916), 'numpy.isfinite', 'numpy.isfinite', (['cor_flux'], {}), '(cor_flux)\n', (2906, 2916), False, 'import numpy\n'), ((2783, 2802), 'numpy.isfinite', 'numpy.isfinite', (['bjd'], {}), '(bjd)\n', (2797, 2802), False, 'import numpy\n'), ((2835, 2859), 'numpy.isfinite', 'numpy.isfinite', (['raw_flux'], {}), '(raw_flux)\n', (2849, 2859), False, 'import numpy\n')]
|
import numpy as np
from qcodes import Parameter, ArrayParameter
from .RemoteProcessWrapper import RPGWrappedBase, ensure_ndarray, get_remote
from .ExtendedDataItem import ExtendedDataItem
from .ColorMap import ColorMap
class HistogramLUTItem(RPGWrappedBase):
_base = "HistogramLUTItem"
def __init__(self, *args, allowAdd=False, **kwargs):
super().__init__(*args, **kwargs)
self.allowAdd = allowAdd
self._remote_function_options['setLevels'] = {'callSync': 'off'}
self._remote_function_options['imageChanged'] = {'callSync': 'off'}
def __wrap__(self, *args, **kwargs):
super().__wrap__()
self._remote_function_options['setLevels'] = {'callSync': 'off'}
self._remote_function_options['imageChanged'] = {'callSync': 'off'}
@property
def axis(self):
return self.__getattr__("axis", _location="remote")
@property
def allowAdd(self):
return self.gradient.allowAdd
@allowAdd.setter
def allowAdd(self, val):
self.gradient.allowAdd = bool(val)
class ImageItem(ExtendedDataItem, RPGWrappedBase):
_base = "ImageItem"
def __init__(self, setpoint_x, setpoint_y, *args, colormap=None, **kwargs):
super().__init__(setpoint_x, setpoint_y, *args, colormap=colormap, **kwargs)
setpoint_x = ensure_ndarray(setpoint_x)
setpoint_y = ensure_ndarray(setpoint_y)
self._remote_function_options['setImage'] = {'callSync': 'off'}
# Set axis scales correctly
self._force_rescale(setpoint_x, setpoint_y)
if colormap is not None:
if not isinstance(colormap, ColorMap):
try:
colormap = get_remote().COLORMAPS['colormap']
except KeyError:
raise ValueError(f"Can't find colormap {colormap}.")
lut = colormap.getLookupTable(0, 1, alpha=False)
self.setLookupTable(lut)
def __wrap__(self, *args, **kwargs):
super().__wrap__(*args, **kwargs)
self._remote_function_options['setImage'] = {'callSync': 'off'}
def _force_rescale(self, setpoint_x, setpoint_y):
step_x = (setpoint_x[-1] - setpoint_x[0])/len(setpoint_x)
step_y = (setpoint_y[-1] - setpoint_y[0])/len(setpoint_y)
self.resetTransform()
self.translate(setpoint_x[0], setpoint_y[0])
self.scale(step_x, step_y)
def update(self, data, *args, **kwargs):
self.setImage(ensure_ndarray(data), autoDownsample=True)
@property
def image(self):
"""
Return the data underlying this trace
"""
return self.__getattr__("image", _returnType="value", _location="remote")
@property
def data(self):
"""
Return the data underlying this trace
"""
return self.image
class ExtendedImageItem(ImageItem):
"""
Extended image item keeps track of x and y setpoints remotely, as this is necessary
to do more enhanced image processing that makes use of the axis scale, like color-by-marquee.
"""
_base = "ExtendedImageItem"
def __init__(self, setpoint_x, setpoint_y, *args, colormap=None, **kwargs):
super().__init__(setpoint_x, setpoint_y, *args, colormap=colormap, **kwargs)
self.setpoint_x = setpoint_x
self.setpoint_y = setpoint_y
def _force_rescale(self, setpoint_x, setpoint_y):
"""
This is handled on the server side...
"""
@property
def setpoint_x(self):
return self.__getattr__("setpoint_x", _returnType="value", _location="remote")
@setpoint_x.setter
def setpoint_x(self, val):
self._base_inst.setpoint_x = val
@property
def setpoint_y(self):
return self.__getattr__("setpoint_y", _returnType="value", _location="remote")
@setpoint_y.setter
def setpoint_y(self, val):
self._base_inst.setpoint_y = val
class ImageItemWithHistogram(ExtendedImageItem):
_base = "ImageItemWithHistogram"
# Local Variables
_histogram = None
def __init__(self, setpoint_x, setpoint_y, *args, colormap=None, **kwargs):
super().__init__(setpoint_x, setpoint_y, *args, colormap=colormap, **kwargs)
self._histogram = None
def __wrap__(self, *args, **kwargs):
super().__wrap__(*args, **kwargs)
self._histogram = None
def pause_update(self):
"""
Pause histogram autoupdates while a sweep is running.
"""
try:
self._base_inst.sigImageChanged.disconnect()
except AttributeError:
pass
def resume_update(self):
"""
Resume histogram autoupdate
"""
self._base_inst.sigImageChanged.connect(self.histogram.imageChanged)
def update(self, data, *args, **kwargs):
super().update(data, *args, **kwargs)
# Only update the range if requested
if kwargs.get('update_range', True):
z_range = (np.min(data), np.max(data))
self.histogram.imageChanged()
self.histogram.setLevels(*z_range)
def update_histogram_axis(self, param_z):
"""
Update histogram axis labels
"""
if not isinstance(param_z, (Parameter, ArrayParameter)):
raise TypeError("param_z must be a qcodes parameter")
self.histogram.axis.label = param_z.label
self.histogram.axis.units = param_z.unit
@property
def histogram(self):
if self._histogram is None:
self._histogram = self.getHistogramLUTItem()
return self._histogram
@property
def colormap(self):
return self.cmap
@colormap.setter
def colormap(self, cmap):
self.changeColorScale(name=cmap)
|
[
"numpy.min",
"numpy.max"
] |
[((4953, 4965), 'numpy.min', 'np.min', (['data'], {}), '(data)\n', (4959, 4965), True, 'import numpy as np\n'), ((4967, 4979), 'numpy.max', 'np.max', (['data'], {}), '(data)\n', (4973, 4979), True, 'import numpy as np\n')]
|
import numpy as np
import time
import argparse
from rlkit.envs.wrappers import NormalizedBoxEnv
parser = argparse.ArgumentParser()
parser.add_argument('--exp_name', type=str, default='Ant')
parser.add_argument('--ml', type=int, default=1000)
args = parser.parse_args()
import gym
env = NormalizedBoxEnv(gym.make(args.exp_name+'-v2'))
o = env.reset()
# print(env.observation_space.high)
max_path_length = args.ml
path_length = 0
done = False
c_r = 0.0
while (path_length < max_path_length) and (not done):
path_length += 1
a = env.action_space.sample()
o, r, done, _ = env.step(a)
c_r += r
env.render()
print("step: ",path_length)
print("o_max: ",np.max(o),np.argmax(o))
print("o_mean: ",np.mean(o))
print("a: ",a)
print('r: ',r)
print(done)
time.sleep(0.1)
print('c_r: ',c_r)
|
[
"gym.make",
"argparse.ArgumentParser",
"numpy.argmax",
"time.sleep",
"numpy.max",
"numpy.mean"
] |
[((106, 131), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (129, 131), False, 'import argparse\n'), ((305, 336), 'gym.make', 'gym.make', (["(args.exp_name + '-v2')"], {}), "(args.exp_name + '-v2')\n", (313, 336), False, 'import gym\n'), ((756, 771), 'time.sleep', 'time.sleep', (['(0.1)'], {}), '(0.1)\n', (766, 771), False, 'import time\n'), ((656, 665), 'numpy.max', 'np.max', (['o'], {}), '(o)\n', (662, 665), True, 'import numpy as np\n'), ((666, 678), 'numpy.argmax', 'np.argmax', (['o'], {}), '(o)\n', (675, 678), True, 'import numpy as np\n'), ((698, 708), 'numpy.mean', 'np.mean', (['o'], {}), '(o)\n', (705, 708), True, 'import numpy as np\n')]
|
#!/usr/bin/env python
import rospy
import math
import numpy as np
import tf
import tf2_ros
import geometry_msgs.msg
from geometry_msgs.msg import Point
import geometry_msgs.msg
#import transformation_py.transformation as transformation
class FieldMapPublisher(object):
def __init__(self):
rospy.init_node('GPS_tf_node')
# rospy.sleep(0.5) # Wait for a while for init to complete before printing
rospy.loginfo(rospy.get_name() + " start")
self.rate = rospy.Rate(1.) # 10hz
# get static map information
self.map_file = rospy.get_param('map_file', default= '/home/pc/grapebot_simulation/gazebo_plugin_model_dir/map_file.json')
self.map_dict = eval(open(self.map_file, 'r').read())
self.map_heading = self.map_dict['heading']
self.map_origin = np.asarray(self.map_dict['origin'])
self.map_rows = np.asarray(self.map_dict['rows'])
print("map_file: ", self.map_file)
print("map_heading: ", self.map_heading)
print("map_origin: ", self.map_origin)
print("map_rows: ", self.map_rows.shape)
self.odom_T_gps = np.asarray(self.map_dict['odom_T_gps'])
self.tf_listener = tf.TransformListener()
self.publish_ned_to_field_static_tf()
self.map_rows_local = self.transform_map_points_to_local_frame()
def publish_ned_to_field_static_tf(self):
translation = self.odom_T_gps[:, 3]
static_transformStamped = geometry_msgs.msg.TransformStamped()
static_transformStamped.header.stamp = rospy.Time.now()
static_transformStamped.header.frame_id = "baseline_ned"
static_transformStamped.child_frame_id = "odom"
static_transformStamped.transform.translation.x = translation[0]
static_transformStamped.transform.translation.y = translation[1]
static_transformStamped.transform.translation.z = translation[2]
quat = tf.transformations.quaternion_from_matrix(self.odom_T_gps)
static_transformStamped.transform.rotation.x = quat[0]
static_transformStamped.transform.rotation.y = quat[1]
static_transformStamped.transform.rotation.z = quat[2]
static_transformStamped.transform.rotation.w = quat[3]
broadcaster = tf2_ros.StaticTransformBroadcaster()
broadcaster.sendTransform(static_transformStamped)
def transform_map_points_to_local_frame(self):
map_rows_transfered = self.map_rows.copy()[:, :, :2]
map_rows_transfered = map_rows_transfered.reshape([-1, 2])
map_rows_transfered_T = np.concatenate([map_rows_transfered, np.ones([len(map_rows_transfered), 2])], axis=1).T
map_rows_transfered_T = self.odom_T_gps.dot(map_rows_transfered_T)
map_rows_transfered = map_rows_transfered_T.T
map_rows_transfered = map_rows_transfered[:, :2]
map_rows_transfered = map_rows_transfered.reshape([-1, 2, 2])
return map_rows_transfered
def map_pub(self):
while not rospy.is_shutdown():
self.map_publisher.publish(self.field_row_lines)
self.rate.sleep()
if __name__ == '__main__':
field_map_publisher = FieldMapPublisher()
try:
field_map_publisher.map_pub()
except rospy.ROSInterruptException:
pass
|
[
"tf2_ros.StaticTransformBroadcaster",
"rospy.Time.now",
"numpy.asarray",
"rospy.Rate",
"rospy.get_param",
"rospy.is_shutdown",
"rospy.init_node",
"rospy.get_name",
"tf.transformations.quaternion_from_matrix",
"tf.TransformListener"
] |
[((303, 333), 'rospy.init_node', 'rospy.init_node', (['"""GPS_tf_node"""'], {}), "('GPS_tf_node')\n", (318, 333), False, 'import rospy\n'), ((489, 504), 'rospy.Rate', 'rospy.Rate', (['(1.0)'], {}), '(1.0)\n', (499, 504), False, 'import rospy\n'), ((573, 683), 'rospy.get_param', 'rospy.get_param', (['"""map_file"""'], {'default': '"""/home/pc/grapebot_simulation/gazebo_plugin_model_dir/map_file.json"""'}), "('map_file', default=\n '/home/pc/grapebot_simulation/gazebo_plugin_model_dir/map_file.json')\n", (588, 683), False, 'import rospy\n'), ((820, 855), 'numpy.asarray', 'np.asarray', (["self.map_dict['origin']"], {}), "(self.map_dict['origin'])\n", (830, 855), True, 'import numpy as np\n'), ((880, 913), 'numpy.asarray', 'np.asarray', (["self.map_dict['rows']"], {}), "(self.map_dict['rows'])\n", (890, 913), True, 'import numpy as np\n'), ((1130, 1169), 'numpy.asarray', 'np.asarray', (["self.map_dict['odom_T_gps']"], {}), "(self.map_dict['odom_T_gps'])\n", (1140, 1169), True, 'import numpy as np\n'), ((1197, 1219), 'tf.TransformListener', 'tf.TransformListener', ([], {}), '()\n', (1217, 1219), False, 'import tf\n'), ((1549, 1565), 'rospy.Time.now', 'rospy.Time.now', ([], {}), '()\n', (1563, 1565), False, 'import rospy\n'), ((1921, 1979), 'tf.transformations.quaternion_from_matrix', 'tf.transformations.quaternion_from_matrix', (['self.odom_T_gps'], {}), '(self.odom_T_gps)\n', (1962, 1979), False, 'import tf\n'), ((2254, 2290), 'tf2_ros.StaticTransformBroadcaster', 'tf2_ros.StaticTransformBroadcaster', ([], {}), '()\n', (2288, 2290), False, 'import tf2_ros\n'), ((2985, 3004), 'rospy.is_shutdown', 'rospy.is_shutdown', ([], {}), '()\n', (3002, 3004), False, 'import rospy\n'), ((440, 456), 'rospy.get_name', 'rospy.get_name', ([], {}), '()\n', (454, 456), False, 'import rospy\n')]
|
"""Configure common variables and data locations."""
from pathlib import Path
import numpy as np
# Path definitions
# -----------------------------------------------------------------------------
# if several external hard drives are used, pick the correct one by changing the index
external_name = {0: "LinuxDataAppelho", 1: "StefanBackupLinu"}[1]
# The directory in which sourcedata, BIDS rawdata, and derivatives are nested
# - DATA_DIR_REMOTE_LOCAL is the directory on the server, accessed via ssh from local pc
# - DATA_DIR_LOCAL is the directory on the local pc
# - DATA_DIR_EXTERNAL is the directory on an external harddrive
# - DATA_DIR_REMOTE is the directory on the server
DATA_DIR_LOCAL = Path("/home/stefanappelhoff/Desktop/eComp")
DATA_DIR_EXTERNAL = Path(
f"/media/stefanappelhoff/{external_name}/eeg_compression/ecomp_data/"
)
DATA_DIR_REMOTE = Path(
"/home/appelhoff/Projects/ARC-Studies/eeg_compression/ecomp_data/"
)
start = "/run/user/1000/gvfs/sftp:host=192.168.3.11,user=appelhoff"
DATA_DIR_REMOTE_LOCAL = Path(
start + "/home/appelhoff/Projects/ARC-Studies/eeg_compression/ecomp_data"
)
# The directory in which the analysis code is nested (this directory is tracked with git
# and is available on GitHub (private): https://github.com/sappelhoff/ecomp_analysis)
# same naming conventions as for DATA_DIR_* above
ANALYSIS_DIR_LOCAL = Path("/home/stefanappelhoff/Desktop/eComp/ecomp_analysis")
ANALYSIS_DIR_EXTERNAL = Path(
f"/media/stefanappelhoff/{external_name}/eeg_compression/ecomp_data/"
)
ANALYSIS_DIR_REMOTE = Path(
"/home/appelhoff/Projects/ARC-Studies/eeg_compression/ecomp_data/code/ecomp_analysis/" # noqa: E501
)
ANALYSIS_DIR_REMOTE_LOCAL = None
# Constants
# -----------------------------------------------------------------------------
BAD_SUBJS = {
15: "Consistently performed at chance level.",
23: "Misunderstood response cues in one of the tasks.",
}
SUBJS = np.array(list(set(range(1, 33)) - set(BAD_SUBJS)))
STREAMS = ["single", "dual"]
NUMBERS = np.arange(1, 10, dtype=int)
DEFAULT_RNG_SEED = 42
OVERWRITE_MSG = "\nfile exists and overwrite is False:\n\n>>> {}\n"
# Threshold for epochs rejection in FASTER pipeline, step 2
# 3.29 corresponds to p < 0.001, two-tailed
FASTER_THRESH = 3.29
# Electrode groups
P3_GROUP_CERCOR = [
"Cz",
"C1",
"C2",
"CPz",
"CP1",
"CP2",
"CP3",
"CP4",
"Pz",
"P1",
"P2",
]
P3_GROUP_NHB = ["CP1", "P1", "POz", "Pz", "CPz", "CP2", "P2"]
# Mapping choiced (lower/higher, red/blue) to 0 and 1
CHOICE_MAP = {
"lower": 0,
"higher": 1,
"red": 0,
"blue": 1,
}
|
[
"pathlib.Path",
"numpy.arange"
] |
[((705, 748), 'pathlib.Path', 'Path', (['"""/home/stefanappelhoff/Desktop/eComp"""'], {}), "('/home/stefanappelhoff/Desktop/eComp')\n", (709, 748), False, 'from pathlib import Path\n'), ((769, 844), 'pathlib.Path', 'Path', (['f"""/media/stefanappelhoff/{external_name}/eeg_compression/ecomp_data/"""'], {}), "(f'/media/stefanappelhoff/{external_name}/eeg_compression/ecomp_data/')\n", (773, 844), False, 'from pathlib import Path\n'), ((869, 941), 'pathlib.Path', 'Path', (['"""/home/appelhoff/Projects/ARC-Studies/eeg_compression/ecomp_data/"""'], {}), "('/home/appelhoff/Projects/ARC-Studies/eeg_compression/ecomp_data/')\n", (873, 941), False, 'from pathlib import Path\n'), ((1040, 1119), 'pathlib.Path', 'Path', (["(start + '/home/appelhoff/Projects/ARC-Studies/eeg_compression/ecomp_data')"], {}), "(start + '/home/appelhoff/Projects/ARC-Studies/eeg_compression/ecomp_data')\n", (1044, 1119), False, 'from pathlib import Path\n'), ((1373, 1431), 'pathlib.Path', 'Path', (['"""/home/stefanappelhoff/Desktop/eComp/ecomp_analysis"""'], {}), "('/home/stefanappelhoff/Desktop/eComp/ecomp_analysis')\n", (1377, 1431), False, 'from pathlib import Path\n'), ((1456, 1531), 'pathlib.Path', 'Path', (['f"""/media/stefanappelhoff/{external_name}/eeg_compression/ecomp_data/"""'], {}), "(f'/media/stefanappelhoff/{external_name}/eeg_compression/ecomp_data/')\n", (1460, 1531), False, 'from pathlib import Path\n'), ((1560, 1662), 'pathlib.Path', 'Path', (['"""/home/appelhoff/Projects/ARC-Studies/eeg_compression/ecomp_data/code/ecomp_analysis/"""'], {}), "(\n '/home/appelhoff/Projects/ARC-Studies/eeg_compression/ecomp_data/code/ecomp_analysis/'\n )\n", (1564, 1662), False, 'from pathlib import Path\n'), ((2027, 2054), 'numpy.arange', 'np.arange', (['(1)', '(10)'], {'dtype': 'int'}), '(1, 10, dtype=int)\n', (2036, 2054), True, 'import numpy as np\n')]
|
import numpy as np
from collections import Counter
from scipy.stats.stats import ttest_1samp, ttest_ind, pearsonr
from numpy.random.mtrand import permutation
from sklearn.metrics import mean_squared_error
from mvpa_itab.utils import progress
def cross_validate(ds, clf, partitioner, permuted_labels):
partitions = partitioner.generate(ds)
accuracies = []
true_labels = ds.targets.copy()
for p in partitions:
training_mask = p.sa.partitions == 1
ds.targets[training_mask] = permuted_labels[training_mask]
c = Counter(ds.targets[training_mask])
assert len(np.unique(np.array(c.values()))) == 1
assert (ds.targets[~training_mask] == true_labels[~training_mask]).any()
clf.train(ds[training_mask])
predictions = clf.predict(ds[~training_mask])
good_p = np.count_nonzero(np.array(predictions) == ds.targets[~training_mask])
acc = good_p/np.float(len(ds.targets[~training_mask]))
accuracies.append(acc)
ds.targets = true_labels
return np.array(accuracies)
def randomize_labels(ds):
'''
Procedure to randomize labels in each chunk.
------------------------
Parameters
ds: The dataset with chunks and targets to be shuffled
out: list of shuffled labels
'''
labels = ds.targets.copy()
for fold in np.unique(ds.chunks):
mask_chunk = ds.chunks == fold
labels[mask_chunk] = np.random.permutation(ds.targets[mask_chunk])
return labels
class PermutationTest(object):
def __init__(self,
analysis,
permutation_axis=0,
n_permutation=1000):
"""permutation dimension indicates the axis to permute on ds"""
self.analysis = analysis # check to be done
self.n_permutation = n_permutation
self._axis = permutation_axis
def shuffle(self, ds, labels):
# Temporary function
fp = np.memmap('/media/robbis/DATA/perm.dat',
dtype='float32',
mode='w+',
shape=(self.n_permutation,
ds.shape[1],
ds.shape[2])
)
#print fp.shape
for i in range(self.n_permutation):
p_labels = permutation(labels)
#print p_labels
fp[i,:] = self.analysis.transform(p_labels)
#fp[i,:] = self.analysis.transform(ds_p)
#null_dist.append(value_)
#fp = np.array(null_dist)
self.null_dist = fp
return fp
def transform(self, ds, labels):
# What the fuck is labels???
#null_dist = []
fp = np.memmap('/media/robbis/DATA/perm.dat',
dtype='float32',
mode='w+',
shape=(self.n_permutation,
len(labels),
len(labels))
)
for i in range(self.n_permutation):
ds_p = self.ds_simple_permutation(ds)
#fp[i,:] = self.analysis.transform(p_labels)
fp[i,:] = self.analysis.transform(ds_p)
#null_dist.append(value_)
#fp = np.array(null_dist)
self.null_dist = fp
return fp
def p_values(self, true_values, null_dist=None, tails=0):
"""tails = [0, two-tailed; 1, upper; -1, lower]"""
#check stuff
if null_dist == None:
null_dist = self._null_dist
if tails == 0:
count_ = np.abs(null_dist) > np.abs(true_values)
else:
count_ = (tails * null_dist) > (tails * true_values)
p_values = np.sum(count_, axis=0) / np.float(self.n_permutation)
self._p_values = p_values
return p_values
def ds_permutation(self, ds):
from datetime import datetime
start = datetime.now()
dim = self._axis
#check if dimension is coherent with ds shape
new_indexing = []
for i in range(len(ds.shape)):
ind = range(ds.shape[i])
if i == dim:
ind = list(permutation(ind))
new_indexing.append(ind)
ds_ = ds[np.ix_(*new_indexing)]
finish = datetime.now()
print (finish - start)
return ds_
def ds_simple_permutation(self, ds):
from datetime import datetime
start = datetime.now()
dim = self._axis
ind = range(ds.shape[dim])
if dim == 0:
ds_ = ds[ind]
elif dim == 1:
ds_ = ds[:,ind]
elif dim == 2:
ds_ = ds[:,:,ind]
finish = datetime.now()
print (finish - start)
return ds_
class TTest(object):
def __init__(self, ds, conditions=None, sample_value=None):
self.dataset = ds
self.conditions=conditions
self.sample_value=sample_value
def transform(self, labels):
ds = self.dataset
conditions = self.conditions
single_value = self.sample_value
if conditions == single_value == None:
raise ValueError()
elif len(conditions)>2:
raise ValueError()
if single_value != None:
t, p = ttest_1samp(ds, single_value, axis=0)
return t, p
t, p = ttest_ind(ds[labels == conditions[0]],
ds[labels == conditions[1]],
axis=0
)
#print ds.shape
#print t.shape
t[np.isnan(t)] = 1
return t
class Correlation(object):
def __init__(self, ds):
self._dataset = ds
def transform(self, ds, seed):
"""
"""
#ds = self._dataset.T
ds = ds.T
y = seed
corr = []
for x in ds:
r_, _ = pearsonr(x, y)
corr.append(r_)
corr = np.array(corr)
return corr, _
def __str__(self, *args, **kwargs):
self.__name__
class SKLRegressionWrapper(object):
def __init__(self, algorithm, error_fx=mean_squared_error):
self.is_trained = False
self.algorithm = algorithm
self.error_fx = error_fx
self._y_pred = None
def train(self, X, y):
self.algorithm.transform(X, y)
self.is_trained = True
return
def predict(self, X):
if self.is_trained == False:
raise ValueError()
self._y_pred = self.algorithm.predict(X)
return self._y_pred
def evaluate(self, y_true, y_pred=None):
if y_pred != None:
y_pred = self.y_pred
return self.error_fx(y_true, y_pred)
def transform(self, X, y, error_function=mean_squared_error, **kwargs):
return
class CrossValidation(object):
def __init__(self, method, algorithm, error_fx=[mean_squared_error]):
self.method = method
self.algorithm = algorithm
# List of error functions
self.errorfx = error_fx
def transform(self, X, y):
"""
The output is a vector r x n where r is the number
of repetitions of the splitting method
"""
cv = self.method
# Check if all elements could be selected
if cv.n != len(y):
cv.n = len(y)
mse_ = []
for train_index, test_index in cv:
X_train = X[train_index]
y_train = y[train_index]
# Feature selection
X_test = X[test_index]
# We suppose only scikit-learn transform algorithms are passed!
y_predict = self.algorithm.transform(X_train, y_train).predict(X_test)
errors = []
for error_ in self.errorfx:
err_ = error_(y[test_index], y_predict)
errors.append(err_)
mse_.append(errors)
self.result = np.array(mse_)
return self.result
class RegressionPermutation(object):
def __init__(self,
analysis,
n_permutation=1000,
print_progress=True):
"""permutation dimension indicates the axis to permute on ds"""
self.analysis = analysis # check to be done
self.n_permutation = n_permutation
self.print_progress = print_progress
def shuffle(self, y):
return permutation(y)
def transform(self, X, y):
null_dist = []
for i in range(self.n_permutation):
if self.print_progress:
progress(i, self.n_permutation)
y_perm = self.shuffle(y)
value = self.analysis.transform(X, y_perm)
null_dist.append(value)
null_dist = np.array(null_dist)
self.null_dist = null_dist
def p_values(self, true_values, null_dist=None, tails=0):
"""tails = [0, two-tailed; 1, upper; -1, lower]"""
#check stuff
if null_dist == None:
null_dist = np.mean(self.null_dist, axis=1)
if tails == 0:
count_ = np.abs(null_dist) > np.abs(true_values)
else:
count_ = (tails * null_dist) > (tails * true_values)
p_values = np.sum(count_, axis=0) / np.float(self.n_permutation)
self._p_values = p_values
return p_values
def ds_permutation(self, ds):
from datetime import datetime
start = datetime.now()
dim = self._axis
#check if dimension is coherent with ds shape
new_indexing = []
for i in range(len(ds.shape)):
ind = range(ds.shape[i])
if i == dim:
ind = list(permutation(ind))
new_indexing.append(ind)
ds_ = ds[np.ix_(*new_indexing)]
finish = datetime.now()
print (finish - start)
return ds_
def ds_simple_permutation(self, ds):
from datetime import datetime
start = datetime.now()
dim = self._axis
ind = range(ds.shape[dim])
if dim == 0:
ds_ = ds[ind]
elif dim == 1:
ds_ = ds[:,ind]
elif dim == 2:
ds_ = ds[:,:,ind]
finish = datetime.now()
print (finish - start)
return ds_
def permutation_test(ds, labels, analysis, n_permutation=1000):
null_dist = []
for _ in range(n_permutation):
p_labels = permutation(labels)
t_, _ = analysis.transform(ds, p_labels)
null_dist.append(t_)
return np.array(null_dist)
|
[
"mvpa_itab.utils.progress",
"numpy.sum",
"numpy.abs",
"scipy.stats.stats.ttest_ind",
"scipy.stats.stats.ttest_1samp",
"scipy.stats.stats.pearsonr",
"numpy.ix_",
"numpy.float",
"numpy.isnan",
"numpy.random.mtrand.permutation",
"numpy.mean",
"numpy.array",
"numpy.random.permutation",
"collections.Counter",
"numpy.memmap",
"datetime.datetime.now",
"numpy.unique"
] |
[((1132, 1152), 'numpy.array', 'np.array', (['accuracies'], {}), '(accuracies)\n', (1140, 1152), True, 'import numpy as np\n'), ((1467, 1487), 'numpy.unique', 'np.unique', (['ds.chunks'], {}), '(ds.chunks)\n', (1476, 1487), True, 'import numpy as np\n'), ((11742, 11761), 'numpy.array', 'np.array', (['null_dist'], {}), '(null_dist)\n', (11750, 11761), True, 'import numpy as np\n'), ((591, 625), 'collections.Counter', 'Counter', (['ds.targets[training_mask]'], {}), '(ds.targets[training_mask])\n', (598, 625), False, 'from collections import Counter\n'), ((1575, 1620), 'numpy.random.permutation', 'np.random.permutation', (['ds.targets[mask_chunk]'], {}), '(ds.targets[mask_chunk])\n', (1596, 1620), True, 'import numpy as np\n'), ((2138, 2265), 'numpy.memmap', 'np.memmap', (['"""/media/robbis/DATA/perm.dat"""'], {'dtype': '"""float32"""', 'mode': '"""w+"""', 'shape': '(self.n_permutation, ds.shape[1], ds.shape[2])'}), "('/media/robbis/DATA/perm.dat', dtype='float32', mode='w+', shape=\n (self.n_permutation, ds.shape[1], ds.shape[2]))\n", (2147, 2265), True, 'import numpy as np\n'), ((4283, 4297), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (4295, 4297), False, 'from datetime import datetime\n'), ((4684, 4698), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (4696, 4698), False, 'from datetime import datetime\n'), ((4877, 4891), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (4889, 4891), False, 'from datetime import datetime\n'), ((5152, 5166), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (5164, 5166), False, 'from datetime import datetime\n'), ((5875, 5950), 'scipy.stats.stats.ttest_ind', 'ttest_ind', (['ds[labels == conditions[0]]', 'ds[labels == conditions[1]]'], {'axis': '(0)'}), '(ds[labels == conditions[0]], ds[labels == conditions[1]], axis=0)\n', (5884, 5950), False, 'from scipy.stats.stats import ttest_1samp, ttest_ind, pearsonr\n'), ((6514, 6528), 'numpy.array', 'np.array', (['corr'], {}), '(corr)\n', (6522, 6528), True, 'import numpy as np\n'), ((8838, 8852), 'numpy.array', 'np.array', (['mse_'], {}), '(mse_)\n', (8846, 8852), True, 'import numpy as np\n'), ((9340, 9354), 'numpy.random.mtrand.permutation', 'permutation', (['y'], {}), '(y)\n', (9351, 9354), False, 'from numpy.random.mtrand import permutation\n'), ((9710, 9729), 'numpy.array', 'np.array', (['null_dist'], {}), '(null_dist)\n', (9718, 9729), True, 'import numpy as np\n'), ((10493, 10507), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (10505, 10507), False, 'from datetime import datetime\n'), ((10894, 10908), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (10906, 10908), False, 'from datetime import datetime\n'), ((11087, 11101), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (11099, 11101), False, 'from datetime import datetime\n'), ((11362, 11376), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (11374, 11376), False, 'from datetime import datetime\n'), ((11618, 11637), 'numpy.random.mtrand.permutation', 'permutation', (['labels'], {}), '(labels)\n', (11629, 11637), False, 'from numpy.random.mtrand import permutation\n'), ((2507, 2526), 'numpy.random.mtrand.permutation', 'permutation', (['labels'], {}), '(labels)\n', (2518, 2526), False, 'from numpy.random.mtrand import permutation\n'), ((4037, 4059), 'numpy.sum', 'np.sum', (['count_'], {'axis': '(0)'}), '(count_, axis=0)\n', (4043, 4059), True, 'import numpy as np\n'), ((4062, 4090), 'numpy.float', 'np.float', (['self.n_permutation'], {}), '(self.n_permutation)\n', (4070, 4090), True, 'import numpy as np\n'), ((4635, 4656), 'numpy.ix_', 'np.ix_', (['*new_indexing'], {}), '(*new_indexing)\n', (4641, 4656), True, 'import numpy as np\n'), ((5788, 5825), 'scipy.stats.stats.ttest_1samp', 'ttest_1samp', (['ds', 'single_value'], {'axis': '(0)'}), '(ds, single_value, axis=0)\n', (5799, 5825), False, 'from scipy.stats.stats import ttest_1samp, ttest_ind, pearsonr\n'), ((6072, 6083), 'numpy.isnan', 'np.isnan', (['t'], {}), '(t)\n', (6080, 6083), True, 'import numpy as np\n'), ((6430, 6444), 'scipy.stats.stats.pearsonr', 'pearsonr', (['x', 'y'], {}), '(x, y)\n', (6438, 6444), False, 'from scipy.stats.stats import ttest_1samp, ttest_ind, pearsonr\n'), ((10001, 10032), 'numpy.mean', 'np.mean', (['self.null_dist'], {'axis': '(1)'}), '(self.null_dist, axis=1)\n', (10008, 10032), True, 'import numpy as np\n'), ((10247, 10269), 'numpy.sum', 'np.sum', (['count_'], {'axis': '(0)'}), '(count_, axis=0)\n', (10253, 10269), True, 'import numpy as np\n'), ((10272, 10300), 'numpy.float', 'np.float', (['self.n_permutation'], {}), '(self.n_permutation)\n', (10280, 10300), True, 'import numpy as np\n'), ((10845, 10866), 'numpy.ix_', 'np.ix_', (['*new_indexing'], {}), '(*new_indexing)\n', (10851, 10866), True, 'import numpy as np\n'), ((917, 938), 'numpy.array', 'np.array', (['predictions'], {}), '(predictions)\n', (925, 938), True, 'import numpy as np\n'), ((3885, 3902), 'numpy.abs', 'np.abs', (['null_dist'], {}), '(null_dist)\n', (3891, 3902), True, 'import numpy as np\n'), ((3905, 3924), 'numpy.abs', 'np.abs', (['true_values'], {}), '(true_values)\n', (3911, 3924), True, 'import numpy as np\n'), ((9512, 9543), 'mvpa_itab.utils.progress', 'progress', (['i', 'self.n_permutation'], {}), '(i, self.n_permutation)\n', (9520, 9543), False, 'from mvpa_itab.utils import progress\n'), ((10095, 10112), 'numpy.abs', 'np.abs', (['null_dist'], {}), '(null_dist)\n', (10101, 10112), True, 'import numpy as np\n'), ((10115, 10134), 'numpy.abs', 'np.abs', (['true_values'], {}), '(true_values)\n', (10121, 10134), True, 'import numpy as np\n'), ((4541, 4557), 'numpy.random.mtrand.permutation', 'permutation', (['ind'], {}), '(ind)\n', (4552, 4557), False, 'from numpy.random.mtrand import permutation\n'), ((10751, 10767), 'numpy.random.mtrand.permutation', 'permutation', (['ind'], {}), '(ind)\n', (10762, 10767), False, 'from numpy.random.mtrand import permutation\n')]
|
from scipy.integrate import solve_ivp, quad
from sidmpy.Profiles.halo_density_profiles import TNFWprofile
from scipy.interpolate import interp1d
import numpy as np
from scipy.optimize import fsolve
def compute_r1(rhos, rs, vdispersion_halo, cross_section_class, halo_age):
"""
:param rhos: density normalization of NFW profile in M_sun / kpc^3
:param rs: scale radius in kpc
:param vdispersion_halo: the central velocity dispersion of the halo in km/sec
:param cross_section_class: an instance of a cross section class (currently the only option implemented is PowerLaw)
:param halo_age: units Gyr
:return: the solution to the equation for r_1 in kpc:
rho_nfw(r_1) * <sigma * v> * t_halo = 1
"""
# units cm^2 / gram * km/sec
cm2_per_gram_times_sigmav = cross_section_class.scattering_rate_cross_section(vdispersion_halo)
# cm^2 * solar masses * km / (kpc^3 * gram * sec) to 1/Gyr
const = 2.1358e-10
k = rhos * cm2_per_gram_times_sigmav * halo_age # cm^2 / g * km/sec * time * M_sun / kpc^3
k *= const # to a dimensionless number
roots = np.roots([1, 2, 1, -k])
lam = np.real(np.max(roots[np.where(np.isreal(roots))]))
return lam * rs
def compute_r1_nfw_velocity_dispersion(rhos, rs, cross_section_class, halo_age):
# cm^2 * solar masses * km / (kpc^3 * gram * sec) to 1/Gyr
const = 2.1358e-10
def _func_to_min(r):
r = r[0]
vdispersion_halo = nfw_velocity_dispersion_analytic(r, rhos, rs)
cm2_per_gram_times_sigmav = cross_section_class.scattering_rate_cross_section(vdispersion_halo)
func = const * TNFWprofile(r, rhos, rs, 100000 * rs) * cm2_per_gram_times_sigmav * halo_age - 1
return func
out = fsolve(_func_to_min, rs)
return out[0]
def ode_system(x, f):
"""
Decomposes the second order ODE into two first order ODEs
"""
z1 = f[1]
z2 = -2 * x ** -1 * f[1] - np.exp(f[0])
return [z1, z2]
def integrate_profile(rho0, s0, r_s, r_1, rmax_fac=1.2, rmin_fac=0.01,
r_min=None, r_max=None):
"""
Solves the ODE describing the to obtain the density profile
:returns: the integration domain in kpc and the solution to the density profile in M_sun / kpc^3
"""
G = 4.3e-6 # units kpc and solar mass
length_scale = np.sqrt(s0 ** 2 * (4 * np.pi * G * rho0) ** -1)
if r_max is None:
x_max = rmax_fac * r_1 / length_scale
else:
x_max = r_max/length_scale
if r_min is None:
x_min = r_1 * rmin_fac / length_scale
else:
x_min = r_min/length_scale
# solve the ODE with initial conditions
phi_0, phi_prime_0 = 0, 0
N = 600
xvalues = np.linspace(x_min, x_max, N)
res = solve_ivp(ode_system, (x_min, x_max),
[phi_0, phi_prime_0], t_eval=xvalues)
return res['t'] * length_scale, rho0 * np.exp(res.y[0])
def nfwprofile_mass(rhos, rs, rmax):
"""
Computes the mass of an NFW profile inside R = rmax
"""
x = rmax * rs ** -1
return 4*np.pi*rhos*rs**3 * (np.log(1+x) - x * (1+x) ** -1)
def isothermal_profile_mass(r_iso, rho_iso, rmax):
"""
Integrates the isothermal profile density out to a radius rmax
"""
mass = 0
dr_step = r_iso[1] - r_iso[0]
count = 0
assert r_iso[-1] > rmax
while True:
mass += 4 * np.pi * r_iso[count] ** 2 * rho_iso[count] * dr_step
count += 1
if r_iso[count] > rmax:
break
return mass
def isothermal_profile_density(r, r_iso, rho_iso):
"""
Evalutes the density of the isothermal mass profile at a radius r
"""
rho_iso_interp = interp1d(r_iso, rho_iso,
fill_value=(rho_iso[0], 0.), bounds_error=False)
return rho_iso_interp(r)
def nfw_velocity_dispersion_fromfit(m):
"""
The velocity dispersion of an NFW profile with mass m calibrated from a power law fit for halos
between 10^6 and 10^10 at z=0
:param m: halo mass in M_sun
:return: the velocity dispersion inside rs
"""
coeffs = [0.31575757, -1.74259129]
log_vrms = coeffs[0] * np.log10(m) + coeffs[1]
return 10 ** log_vrms
def nfw_mass_from_velocity_dispersion(vrms):
"""
The velocity dispersion of an NFW profile with mass m calibrated from a power law fit for halos
between 10^6 and 10^10 at z=0
:param m: halo mass in M_sun
:return: the velocity dispersion inside rs
"""
coeffs = [0.31575757, -1.74259129]
log_vmrs = np.log10(vrms)
logm = (log_vmrs - coeffs[1])/coeffs[0]
return 10 ** logm
def nfw_circular_velocity(r, rhos, rs):
G = 4.3e-6
x = r/rs
fx = np.log(1+x) -x/(1+x)
m = 4 * np.pi * rs ** 3 * rhos * fx
return np.sqrt(G * m / r)
def nfw_velocity_dispersion(r, rho_s, rs, tol=1e-4):
"""
:param r:
:param rho_s:
:param rs:
:return:
"""
def _integrand(rprime):
return TNFWprofile(rprime, rho_s, rs, 1000000000 * rs) * nfwprofile_mass(rho_s, rs, rprime) / rprime ** 2
rmax_init = 2 * rs
rmax_scale = 2.
rmax = rmax_init + rmax_scale * rs
integral = quad(_integrand, r, rmax)[0]
count_max = 5.
count = 0
while True:
rmax *= rmax_scale
integral_new = quad(_integrand, r, rmax)[0]
fit = abs(integral_new/integral - 1)
if fit < tol:
break
elif count > count_max:
print('warning: NFW velocity dispersion computtion did not converge to more than '+str(fit))
break
else:
count += 1
integral = integral_new
G = 4.3e-6 # units kpc/M_sun * (km/sec)^2
sigma_v_squared = G * integral_new / TNFWprofile(r, rho_s, rs, 1e+6 * rs)
return np.sqrt(sigma_v_squared)
def Li(x):
integrand = lambda u: np.log(1 - u) / u
return quad(integrand, x, 0)[0]
def nfw_velocity_dispersion_analytic(r, rhos, rs):
G = 4.3e-6
x = r / rs
factor = 0.5 * x * (1 + x) ** 2 * G * 4 * np.pi * rhos * rs ** 2
term = np.pi ** 2 - np.log(x) - 1 / x - 1 / (1 + x) ** 2 - 6 / (1 + x) + \
(1 + 1 / x ** 2 - 4 / x - 2 / (1 + x)) * np.log(1 + x) + 3 * np.log(1 + x) ** 2 + 6 * Li(-x)
return np.sqrt(factor * term)
def compute_rho_sigmav_grid(log_rho_values, vdis_values, rhos, rs, cross_section_class,
halo_age, rmin_profile, rmax_profile, use_nfw_velocity_dispersion):
fit_grid = np.ones_like(log_rho_values) * 1e+12
fit_grid = fit_grid.ravel()
# compute the fit quality for each point in the search space
for i, (log_rho_i, velocity_dispersion_i) in enumerate(zip(log_rho_values, vdis_values)):
if use_nfw_velocity_dispersion:
r1 = compute_r1_nfw_velocity_dispersion(rhos, rs, cross_section_class, halo_age)
else:
r1 = compute_r1(rhos, rs, velocity_dispersion_i, cross_section_class, halo_age)
r_iso, rho_iso = integrate_profile(10 ** log_rho_i,
velocity_dispersion_i, rs, r1, rmin_fac=rmin_profile,
rmax_fac=rmax_profile)
m_enclosed = isothermal_profile_mass(r_iso, rho_iso, r1)
rho_at_r1 = isothermal_profile_density(r1, r_iso, rho_iso)
m_nfw = nfwprofile_mass(rhos, rs, r1)
rho_nfw_at_r1 = TNFWprofile(r1, rhos, rs, 10000000 * rs)
mass_ratio = m_nfw / m_enclosed
density_ratio = rho_nfw_at_r1 / rho_at_r1
mass_penalty = np.absolute(mass_ratio - 1)
den_penalty = np.absolute(density_ratio - 1)
fit_qual = mass_penalty + den_penalty
fit_grid[i] = fit_qual
return fit_grid
|
[
"numpy.roots",
"numpy.absolute",
"numpy.isreal",
"numpy.ones_like",
"numpy.log",
"scipy.integrate.quad",
"sidmpy.Profiles.halo_density_profiles.TNFWprofile",
"scipy.integrate.solve_ivp",
"scipy.optimize.fsolve",
"numpy.exp",
"numpy.linspace",
"scipy.interpolate.interp1d",
"numpy.log10",
"numpy.sqrt"
] |
[((1106, 1129), 'numpy.roots', 'np.roots', (['[1, 2, 1, -k]'], {}), '([1, 2, 1, -k])\n', (1114, 1129), True, 'import numpy as np\n'), ((1736, 1760), 'scipy.optimize.fsolve', 'fsolve', (['_func_to_min', 'rs'], {}), '(_func_to_min, rs)\n', (1742, 1760), False, 'from scipy.optimize import fsolve\n'), ((2323, 2370), 'numpy.sqrt', 'np.sqrt', (['(s0 ** 2 * (4 * np.pi * G * rho0) ** -1)'], {}), '(s0 ** 2 * (4 * np.pi * G * rho0) ** -1)\n', (2330, 2370), True, 'import numpy as np\n'), ((2701, 2729), 'numpy.linspace', 'np.linspace', (['x_min', 'x_max', 'N'], {}), '(x_min, x_max, N)\n', (2712, 2729), True, 'import numpy as np\n'), ((2741, 2816), 'scipy.integrate.solve_ivp', 'solve_ivp', (['ode_system', '(x_min, x_max)', '[phi_0, phi_prime_0]'], {'t_eval': 'xvalues'}), '(ode_system, (x_min, x_max), [phi_0, phi_prime_0], t_eval=xvalues)\n', (2750, 2816), False, 'from scipy.integrate import solve_ivp, quad\n'), ((3655, 3729), 'scipy.interpolate.interp1d', 'interp1d', (['r_iso', 'rho_iso'], {'fill_value': '(rho_iso[0], 0.0)', 'bounds_error': '(False)'}), '(r_iso, rho_iso, fill_value=(rho_iso[0], 0.0), bounds_error=False)\n', (3663, 3729), False, 'from scipy.interpolate import interp1d\n'), ((4506, 4520), 'numpy.log10', 'np.log10', (['vrms'], {}), '(vrms)\n', (4514, 4520), True, 'import numpy as np\n'), ((4738, 4756), 'numpy.sqrt', 'np.sqrt', (['(G * m / r)'], {}), '(G * m / r)\n', (4745, 4756), True, 'import numpy as np\n'), ((5736, 5760), 'numpy.sqrt', 'np.sqrt', (['sigma_v_squared'], {}), '(sigma_v_squared)\n', (5743, 5760), True, 'import numpy as np\n'), ((6201, 6223), 'numpy.sqrt', 'np.sqrt', (['(factor * term)'], {}), '(factor * term)\n', (6208, 6223), True, 'import numpy as np\n'), ((1926, 1938), 'numpy.exp', 'np.exp', (['f[0]'], {}), '(f[0])\n', (1932, 1938), True, 'import numpy as np\n'), ((4666, 4679), 'numpy.log', 'np.log', (['(1 + x)'], {}), '(1 + x)\n', (4672, 4679), True, 'import numpy as np\n'), ((5128, 5153), 'scipy.integrate.quad', 'quad', (['_integrand', 'r', 'rmax'], {}), '(_integrand, r, rmax)\n', (5132, 5153), False, 'from scipy.integrate import solve_ivp, quad\n'), ((5688, 5729), 'sidmpy.Profiles.halo_density_profiles.TNFWprofile', 'TNFWprofile', (['r', 'rho_s', 'rs', '(1000000.0 * rs)'], {}), '(r, rho_s, rs, 1000000.0 * rs)\n', (5699, 5729), False, 'from sidmpy.Profiles.halo_density_profiles import TNFWprofile\n'), ((5828, 5849), 'scipy.integrate.quad', 'quad', (['integrand', 'x', '(0)'], {}), '(integrand, x, 0)\n', (5832, 5849), False, 'from scipy.integrate import solve_ivp, quad\n'), ((6425, 6453), 'numpy.ones_like', 'np.ones_like', (['log_rho_values'], {}), '(log_rho_values)\n', (6437, 6453), True, 'import numpy as np\n'), ((7321, 7361), 'sidmpy.Profiles.halo_density_profiles.TNFWprofile', 'TNFWprofile', (['r1', 'rhos', 'rs', '(10000000 * rs)'], {}), '(r1, rhos, rs, 10000000 * rs)\n', (7332, 7361), False, 'from sidmpy.Profiles.halo_density_profiles import TNFWprofile\n'), ((7477, 7504), 'numpy.absolute', 'np.absolute', (['(mass_ratio - 1)'], {}), '(mass_ratio - 1)\n', (7488, 7504), True, 'import numpy as np\n'), ((7527, 7557), 'numpy.absolute', 'np.absolute', (['(density_ratio - 1)'], {}), '(density_ratio - 1)\n', (7538, 7557), True, 'import numpy as np\n'), ((2881, 2897), 'numpy.exp', 'np.exp', (['res.y[0]'], {}), '(res.y[0])\n', (2887, 2897), True, 'import numpy as np\n'), ((3065, 3078), 'numpy.log', 'np.log', (['(1 + x)'], {}), '(1 + x)\n', (3071, 3078), True, 'import numpy as np\n'), ((4125, 4136), 'numpy.log10', 'np.log10', (['m'], {}), '(m)\n', (4133, 4136), True, 'import numpy as np\n'), ((5256, 5281), 'scipy.integrate.quad', 'quad', (['_integrand', 'r', 'rmax'], {}), '(_integrand, r, rmax)\n', (5260, 5281), False, 'from scipy.integrate import solve_ivp, quad\n'), ((5799, 5812), 'numpy.log', 'np.log', (['(1 - u)'], {}), '(1 - u)\n', (5805, 5812), True, 'import numpy as np\n'), ((4931, 4978), 'sidmpy.Profiles.halo_density_profiles.TNFWprofile', 'TNFWprofile', (['rprime', 'rho_s', 'rs', '(1000000000 * rs)'], {}), '(rprime, rho_s, rs, 1000000000 * rs)\n', (4942, 4978), False, 'from sidmpy.Profiles.halo_density_profiles import TNFWprofile\n'), ((1170, 1186), 'numpy.isreal', 'np.isreal', (['roots'], {}), '(roots)\n', (1179, 1186), True, 'import numpy as np\n'), ((6137, 6150), 'numpy.log', 'np.log', (['(1 + x)'], {}), '(1 + x)\n', (6143, 6150), True, 'import numpy as np\n'), ((6157, 6170), 'numpy.log', 'np.log', (['(1 + x)'], {}), '(1 + x)\n', (6163, 6170), True, 'import numpy as np\n'), ((1624, 1661), 'sidmpy.Profiles.halo_density_profiles.TNFWprofile', 'TNFWprofile', (['r', 'rhos', 'rs', '(100000 * rs)'], {}), '(r, rhos, rs, 100000 * rs)\n', (1635, 1661), False, 'from sidmpy.Profiles.halo_density_profiles import TNFWprofile\n'), ((6030, 6039), 'numpy.log', 'np.log', (['x'], {}), '(x)\n', (6036, 6039), True, 'import numpy as np\n')]
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 14 14:03:56 2019
@author: bmoseley
"""
# This code is my own python implementation of the SEISMIC_CPML library here: https://github.com/geodynamics/seismic_cpml/blob/master/seismic_CPML_2D_pressure_second_order.f90
import matplotlib.pyplot as plt
import numpy as np
## Code to get dampening profiles for seismic CPML, can cope with any number of dimensions
def get_dampening_profiles(velocity, NPOINTS_PML, Rcoef, K_MAX_PML, ALPHA_MAX_PML, NPOWER, DELTAT, DELTAS, dtype=np.float64, qc=False):
"Get dampening profiles for seismic CPML. Can cope with any number of dimensions defined by velocity array"
profiles = []
if qc: qc_profiles = []
assert len(DELTAS) == len(velocity.shape)
maxvel = np.max(velocity)
# for each dimension
for iN, N in enumerate(velocity.shape):
DELTA = DELTAS[iN]
thickness_PML = NPOINTS_PML * DELTA
d0 = - (NPOWER + 1) * maxvel * np.log(Rcoef) / (2 * thickness_PML)
d, d_half, K, K_half, alpha, alpha_half, b, b_half, a, a_half = np.zeros(N, dtype=dtype), np.zeros(N, dtype=dtype), np.zeros(N, dtype=dtype), np.zeros(N, dtype=dtype), np.zeros(N, dtype=dtype), np.zeros(N, dtype=dtype), np.zeros(N, dtype=dtype), np.zeros(N, dtype=dtype), np.zeros(N, dtype=dtype), np.zeros(N, dtype=dtype)
K[:], K_half[:] = 1,1
originleft = thickness_PML
originright = (N-1)*DELTA - thickness_PML
# calculate profile for each element
for i in range(N):
# abscissa of current grid point along the damping profile
val = DELTA * i
# define damping profile at the grid points, left and right edges
for abscissa_in_PML in [originleft - val, val - originright]:
if (abscissa_in_PML >= 0.):# if in PML
abscissa_normalized = abscissa_in_PML / thickness_PML
d[i] = d0 * (abscissa_normalized**NPOWER)
# from Stephen Gedney's unpublished class notes for class EE699, lecture 8, slide 8-2
K[i] = 1 + (K_MAX_PML - 1) * (abscissa_normalized**NPOWER)
alpha[i] = ALPHA_MAX_PML * (1 - abscissa_normalized)
# define damping profile at half the grid points, left and right edges
for abscissa_in_PML in [originleft - (val + DELTA/2.), (val + DELTA/2.) - originright]:
if (abscissa_in_PML >= 0.):
abscissa_normalized = abscissa_in_PML / thickness_PML
d_half[i] = d0 * (abscissa_normalized**NPOWER)
# from Stephen Gedney's unpublished class notes for class EE699, lecture 8, slide 8-2
K_half[i] = 1 + (K_MAX_PML - 1) * (abscissa_normalized**NPOWER)
alpha_half[i] = ALPHA_MAX_PML * (1 - abscissa_normalized)
b[i] = np.exp(-(d[i] / K[i] + alpha[i]) * DELTAT)
b_half[i] = np.exp(-(d_half[i] / K_half[i] + alpha_half[i]) * DELTAT)
# this to avoid division by zero outside the PML
if (np.abs(d[i]) > 1e-6):
a[i] = d[i] * (b[i] - 1) / (K[i] * (d[i] + K[i] * alpha[i]))
if (np.abs(d_half[i]) > 1e-6):
a_half[i] = d_half[i] * (b_half[i] - 1) / (K_half[i] * (d_half[i] + K_half[i] * alpha_half[i]))
# save all profiles if in qc mode
if qc:
qc_profiles.append([d.copy(), d_half.copy(), K.copy(), K_half.copy(), alpha.copy(), alpha_half.copy(), b.copy(), b_half.copy(), a.copy(), a_half.copy()])
# reshape profile so that it can be broadcasted onto the velocity array
shape = np.ones(len(velocity.shape), dtype=int)
shape[iN] = N
a, a_half = a.reshape(shape), a_half.reshape(shape)
b, b_half = b.reshape(shape), b_half.reshape(shape)
K, K_half = K.reshape(shape), K_half.reshape(shape)
profiles.append([a.copy(), a_half.copy(), b.copy(), b_half.copy(), K.copy(), K_half.copy()])
if qc:
return profiles, qc_profiles
return profiles
def _plot_cpml_qc_profiles(qc_profiles):
n_row = len(qc_profiles)
figsize = (7,2.3*n_row)
fa = plt.figure(figsize=figsize)
plt.suptitle("a")
fb = plt.figure(figsize=figsize)
plt.suptitle("b")
falpha = plt.figure(figsize=figsize)
plt.suptitle("alpha")
fd = plt.figure(figsize=figsize)
plt.suptitle("d")
fk = plt.figure(figsize=figsize)
plt.suptitle("K")
for i,qc_profile in enumerate(qc_profiles):
d, d_half, K, K_half, alpha, alpha_half, b, b_half, a, a_half = qc_profile
# plot dampening profiles
plt.figure(fa.number)
plt.subplot(n_row,1,i+1)
plt.plot(a)
plt.plot(a_half)
plt.figure(fb.number)
plt.subplot(n_row,1,i+1)
plt.plot(b)
plt.plot(b_half)
plt.figure(falpha.number)
plt.subplot(n_row,1,i+1)
plt.plot(alpha)
plt.plot(alpha_half)
plt.figure(fd.number)
plt.subplot(n_row,1,i+1)
plt.plot(d)
plt.plot(d_half)
plt.figure(fk.number)
plt.subplot(n_row,1,i+1)
plt.plot(K)
plt.plot(K_half)
if __name__ == "__main__":
##
NX = 51
NY = 61
NZ = 71
DELTAX = 5
DELTAY = 5
DELTAZ = 30
DELTAT = 0.0005
NPOINTS_PML = 10
dtype = np.float32
velocity = 2000.*np.ones((NX,NY,NZ), dtype=dtype)
##
f0 = 7.
K_MAX_PML = 1.
ALPHA_MAX_PML = 2.*np.pi*(f0/2.)# from Festa and Vilotte
NPOWER = 2.# power to compute d0 profile
Rcoef = 0.001
##
profiles, qc_profiles = get_dampening_profiles(velocity, NPOINTS_PML, Rcoef, K_MAX_PML, ALPHA_MAX_PML, NPOWER, DELTAT, DELTAS=(DELTAX, DELTAY, DELTAZ), dtype=np.float32, qc=True)
_plot_cpml_qc_profiles(qc_profiles)
plt.figure()
for profile in profiles:
for p in profile:
print(p.shape, p.dtype)
plt.plot(p.flatten())
plt.show()
|
[
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.show",
"numpy.log",
"matplotlib.pyplot.plot",
"numpy.abs",
"matplotlib.pyplot.suptitle",
"numpy.zeros",
"numpy.ones",
"numpy.max",
"matplotlib.pyplot.figure",
"numpy.exp"
] |
[((798, 814), 'numpy.max', 'np.max', (['velocity'], {}), '(velocity)\n', (804, 814), True, 'import numpy as np\n'), ((4386, 4413), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': 'figsize'}), '(figsize=figsize)\n', (4396, 4413), True, 'import matplotlib.pyplot as plt\n'), ((4418, 4435), 'matplotlib.pyplot.suptitle', 'plt.suptitle', (['"""a"""'], {}), "('a')\n", (4430, 4435), True, 'import matplotlib.pyplot as plt\n'), ((4445, 4472), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': 'figsize'}), '(figsize=figsize)\n', (4455, 4472), True, 'import matplotlib.pyplot as plt\n'), ((4477, 4494), 'matplotlib.pyplot.suptitle', 'plt.suptitle', (['"""b"""'], {}), "('b')\n", (4489, 4494), True, 'import matplotlib.pyplot as plt\n'), ((4508, 4535), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': 'figsize'}), '(figsize=figsize)\n', (4518, 4535), True, 'import matplotlib.pyplot as plt\n'), ((4540, 4561), 'matplotlib.pyplot.suptitle', 'plt.suptitle', (['"""alpha"""'], {}), "('alpha')\n", (4552, 4561), True, 'import matplotlib.pyplot as plt\n'), ((4571, 4598), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': 'figsize'}), '(figsize=figsize)\n', (4581, 4598), True, 'import matplotlib.pyplot as plt\n'), ((4603, 4620), 'matplotlib.pyplot.suptitle', 'plt.suptitle', (['"""d"""'], {}), "('d')\n", (4615, 4620), True, 'import matplotlib.pyplot as plt\n'), ((4630, 4657), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': 'figsize'}), '(figsize=figsize)\n', (4640, 4657), True, 'import matplotlib.pyplot as plt\n'), ((4662, 4679), 'matplotlib.pyplot.suptitle', 'plt.suptitle', (['"""K"""'], {}), "('K')\n", (4674, 4679), True, 'import matplotlib.pyplot as plt\n'), ((6112, 6124), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (6122, 6124), True, 'import matplotlib.pyplot as plt\n'), ((6260, 6270), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6268, 6270), True, 'import matplotlib.pyplot as plt\n'), ((4868, 4889), 'matplotlib.pyplot.figure', 'plt.figure', (['fa.number'], {}), '(fa.number)\n', (4878, 4889), True, 'import matplotlib.pyplot as plt\n'), ((4898, 4926), 'matplotlib.pyplot.subplot', 'plt.subplot', (['n_row', '(1)', '(i + 1)'], {}), '(n_row, 1, i + 1)\n', (4909, 4926), True, 'import matplotlib.pyplot as plt\n'), ((4931, 4942), 'matplotlib.pyplot.plot', 'plt.plot', (['a'], {}), '(a)\n', (4939, 4942), True, 'import matplotlib.pyplot as plt\n'), ((4951, 4967), 'matplotlib.pyplot.plot', 'plt.plot', (['a_half'], {}), '(a_half)\n', (4959, 4967), True, 'import matplotlib.pyplot as plt\n'), ((4985, 5006), 'matplotlib.pyplot.figure', 'plt.figure', (['fb.number'], {}), '(fb.number)\n', (4995, 5006), True, 'import matplotlib.pyplot as plt\n'), ((5015, 5043), 'matplotlib.pyplot.subplot', 'plt.subplot', (['n_row', '(1)', '(i + 1)'], {}), '(n_row, 1, i + 1)\n', (5026, 5043), True, 'import matplotlib.pyplot as plt\n'), ((5048, 5059), 'matplotlib.pyplot.plot', 'plt.plot', (['b'], {}), '(b)\n', (5056, 5059), True, 'import matplotlib.pyplot as plt\n'), ((5068, 5084), 'matplotlib.pyplot.plot', 'plt.plot', (['b_half'], {}), '(b_half)\n', (5076, 5084), True, 'import matplotlib.pyplot as plt\n'), ((5102, 5127), 'matplotlib.pyplot.figure', 'plt.figure', (['falpha.number'], {}), '(falpha.number)\n', (5112, 5127), True, 'import matplotlib.pyplot as plt\n'), ((5136, 5164), 'matplotlib.pyplot.subplot', 'plt.subplot', (['n_row', '(1)', '(i + 1)'], {}), '(n_row, 1, i + 1)\n', (5147, 5164), True, 'import matplotlib.pyplot as plt\n'), ((5169, 5184), 'matplotlib.pyplot.plot', 'plt.plot', (['alpha'], {}), '(alpha)\n', (5177, 5184), True, 'import matplotlib.pyplot as plt\n'), ((5193, 5213), 'matplotlib.pyplot.plot', 'plt.plot', (['alpha_half'], {}), '(alpha_half)\n', (5201, 5213), True, 'import matplotlib.pyplot as plt\n'), ((5231, 5252), 'matplotlib.pyplot.figure', 'plt.figure', (['fd.number'], {}), '(fd.number)\n', (5241, 5252), True, 'import matplotlib.pyplot as plt\n'), ((5261, 5289), 'matplotlib.pyplot.subplot', 'plt.subplot', (['n_row', '(1)', '(i + 1)'], {}), '(n_row, 1, i + 1)\n', (5272, 5289), True, 'import matplotlib.pyplot as plt\n'), ((5294, 5305), 'matplotlib.pyplot.plot', 'plt.plot', (['d'], {}), '(d)\n', (5302, 5305), True, 'import matplotlib.pyplot as plt\n'), ((5314, 5330), 'matplotlib.pyplot.plot', 'plt.plot', (['d_half'], {}), '(d_half)\n', (5322, 5330), True, 'import matplotlib.pyplot as plt\n'), ((5348, 5369), 'matplotlib.pyplot.figure', 'plt.figure', (['fk.number'], {}), '(fk.number)\n', (5358, 5369), True, 'import matplotlib.pyplot as plt\n'), ((5378, 5406), 'matplotlib.pyplot.subplot', 'plt.subplot', (['n_row', '(1)', '(i + 1)'], {}), '(n_row, 1, i + 1)\n', (5389, 5406), True, 'import matplotlib.pyplot as plt\n'), ((5411, 5422), 'matplotlib.pyplot.plot', 'plt.plot', (['K'], {}), '(K)\n', (5419, 5422), True, 'import matplotlib.pyplot as plt\n'), ((5431, 5447), 'matplotlib.pyplot.plot', 'plt.plot', (['K_half'], {}), '(K_half)\n', (5439, 5447), True, 'import matplotlib.pyplot as plt\n'), ((5663, 5697), 'numpy.ones', 'np.ones', (['(NX, NY, NZ)'], {'dtype': 'dtype'}), '((NX, NY, NZ), dtype=dtype)\n', (5670, 5697), True, 'import numpy as np\n'), ((1134, 1158), 'numpy.zeros', 'np.zeros', (['N'], {'dtype': 'dtype'}), '(N, dtype=dtype)\n', (1142, 1158), True, 'import numpy as np\n'), ((1160, 1184), 'numpy.zeros', 'np.zeros', (['N'], {'dtype': 'dtype'}), '(N, dtype=dtype)\n', (1168, 1184), True, 'import numpy as np\n'), ((1186, 1210), 'numpy.zeros', 'np.zeros', (['N'], {'dtype': 'dtype'}), '(N, dtype=dtype)\n', (1194, 1210), True, 'import numpy as np\n'), ((1212, 1236), 'numpy.zeros', 'np.zeros', (['N'], {'dtype': 'dtype'}), '(N, dtype=dtype)\n', (1220, 1236), True, 'import numpy as np\n'), ((1238, 1262), 'numpy.zeros', 'np.zeros', (['N'], {'dtype': 'dtype'}), '(N, dtype=dtype)\n', (1246, 1262), True, 'import numpy as np\n'), ((1264, 1288), 'numpy.zeros', 'np.zeros', (['N'], {'dtype': 'dtype'}), '(N, dtype=dtype)\n', (1272, 1288), True, 'import numpy as np\n'), ((1290, 1314), 'numpy.zeros', 'np.zeros', (['N'], {'dtype': 'dtype'}), '(N, dtype=dtype)\n', (1298, 1314), True, 'import numpy as np\n'), ((1316, 1340), 'numpy.zeros', 'np.zeros', (['N'], {'dtype': 'dtype'}), '(N, dtype=dtype)\n', (1324, 1340), True, 'import numpy as np\n'), ((1342, 1366), 'numpy.zeros', 'np.zeros', (['N'], {'dtype': 'dtype'}), '(N, dtype=dtype)\n', (1350, 1366), True, 'import numpy as np\n'), ((1368, 1392), 'numpy.zeros', 'np.zeros', (['N'], {'dtype': 'dtype'}), '(N, dtype=dtype)\n', (1376, 1392), True, 'import numpy as np\n'), ((3001, 3043), 'numpy.exp', 'np.exp', (['(-(d[i] / K[i] + alpha[i]) * DELTAT)'], {}), '(-(d[i] / K[i] + alpha[i]) * DELTAT)\n', (3007, 3043), True, 'import numpy as np\n'), ((3068, 3125), 'numpy.exp', 'np.exp', (['(-(d_half[i] / K_half[i] + alpha_half[i]) * DELTAT)'], {}), '(-(d_half[i] / K_half[i] + alpha_half[i]) * DELTAT)\n', (3074, 3125), True, 'import numpy as np\n'), ((1017, 1030), 'numpy.log', 'np.log', (['Rcoef'], {}), '(Rcoef)\n', (1023, 1030), True, 'import numpy as np\n'), ((3216, 3228), 'numpy.abs', 'np.abs', (['d[i]'], {}), '(d[i])\n', (3222, 3228), True, 'import numpy as np\n'), ((3331, 3348), 'numpy.abs', 'np.abs', (['d_half[i]'], {}), '(d_half[i])\n', (3337, 3348), True, 'import numpy as np\n')]
|
import numpy as np
import wave
from scipy.io.wavfile import read, write
import struct
from numpy.fft import fft, fftshift, ifft
def spectrum_shifting( x, shift, fs ):
X = fft( x )
N = fs
N_half = int( fs / 2 )
Y = np.zeros( N, dtype = 'complex' )
for i in range( N_half ):
if i + shift >= 0 and i + shift <= N_half:
Y[i + shift] = X[i]
for i in range( N_half + 1, fs ):
if i - shift >= N_half + 1 and i - shift < N:
Y[i - shift] = X[i]
y = ifft( Y )
y = y.real
return y
def main( ):
infile = input( "Input File: " )
outfile = input( "Output File: " )
# ----------------------------------------------------
# 輸入模組
# ----------------------------------------------------
wav = wave.open( infile, 'rb' )
num_channels = wav.getnchannels( ) # 通道數
sampwidth = wav.getsampwidth( ) # 樣本寬度
fs = wav.getframerate( ) # 取樣頻率(Hz)
num_frames = wav.getnframes( ) # 音框數 = 樣本數
comptype = wav.getcomptype( ) # 壓縮型態
compname = wav.getcompname( ) # 無壓縮
wav.close( )
sampling_rate, x = read( infile ) # 輸入訊號
# ----------------------------------------------------
# DSP 模組
# ----------------------------------------------------
y = np.zeros( x.size )
n = int( x.size / fs ) + 1
N = fs
for iter in range( n ):
xx = np.zeros( N )
yy = np.zeros( N )
for i in range( iter * N, ( iter + 1 ) * N ):
if i < x.size:
xx[i - iter * N] = x[i]
yy = spectrum_shifting( xx, 500, fs )
for i in range( iter * N, ( iter + 1 ) * N ):
if i < x.size:
y[i] = yy[i - iter * N]
# ----------------------------------------------------
# 輸出模組
# ----------------------------------------------------
wav_file = wave.open( outfile, 'w' )
wav_file.setparams(( num_channels, sampwidth, fs, num_frames, comptype, compname ))
for s in y:
wav_file.writeframes( struct.pack( 'h', int ( s ) ) )
wav_file.close( )
main( )
|
[
"numpy.fft.ifft",
"wave.open",
"numpy.fft.fft",
"numpy.zeros",
"scipy.io.wavfile.read"
] |
[((173, 179), 'numpy.fft.fft', 'fft', (['x'], {}), '(x)\n', (176, 179), False, 'from numpy.fft import fft, fftshift, ifft\n'), ((219, 247), 'numpy.zeros', 'np.zeros', (['N'], {'dtype': '"""complex"""'}), "(N, dtype='complex')\n", (227, 247), True, 'import numpy as np\n'), ((458, 465), 'numpy.fft.ifft', 'ifft', (['Y'], {}), '(Y)\n', (462, 465), False, 'from numpy.fft import fft, fftshift, ifft\n'), ((708, 731), 'wave.open', 'wave.open', (['infile', '"""rb"""'], {}), "(infile, 'rb')\n", (717, 731), False, 'import wave\n'), ((1014, 1026), 'scipy.io.wavfile.read', 'read', (['infile'], {}), '(infile)\n', (1018, 1026), False, 'from scipy.io.wavfile import read, write\n'), ((1166, 1182), 'numpy.zeros', 'np.zeros', (['x.size'], {}), '(x.size)\n', (1174, 1182), True, 'import numpy as np\n'), ((1663, 1686), 'wave.open', 'wave.open', (['outfile', '"""w"""'], {}), "(outfile, 'w')\n", (1672, 1686), False, 'import wave\n'), ((1253, 1264), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (1261, 1264), True, 'import numpy as np\n'), ((1274, 1285), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (1282, 1285), True, 'import numpy as np\n')]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.