code
stringlengths 31
1.05M
| apis
list | extract_api
stringlengths 97
1.91M
|
---|---|---|
# -*- coding: UTF-8 -*-
import cv2
import matplotlib.pyplot as plt
import numpy as np
class PROIE():
def __init__(self):
#####
pass
# PRIVATE METHODS
def _threshold(self):
#####
self.blur_img = cv2.GaussianBlur(self.in_img_g, (5, 5), 0)
_, self.thresh_img = cv2.threshold(
self.blur_img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
def _contours(self):
#####
self.contours, _ = cv2.findContours(
self.thresh_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
self.contours = self.contours[0]
self.contour_img = self.in_img_c.copy()
self.contour_img = cv2.drawContours(
self.contour_img, [self.contours], 0, (255, 0, 0), 2)
def _landmarks(self):
#####
M = cv2.moments(self.thresh_img)
x_c = M['m10'] // M['m00']
y_c = M['m01'] // M['m00']
self.center_point = {"x": x_c, "y": y_c}
self.contours = self.contours.reshape(-1, 2)
left_id = np.argmin(self.contours.sum(-1))
self.contours = np.concatenate(
[self.contours[left_id:, :], self.contours[:left_id, :]])
dist_c = np.sqrt(np.square(
self.contours-[self.center_point["x"], self.center_point["y"]]).sum(-1))
f = np.fft.rfft(dist_c)
cutoff = 15
f_new = np.concatenate([f[:cutoff], 0*f[cutoff:]])
dist_c_1 = np.fft.irfft(f_new)
derivative = np.diff(dist_c_1)
sign_change = np.diff(np.sign(derivative))/2
self.landmarks = {"x": [], "y": []}
for landmark in self.contours[np.where(sign_change > 0)[0]]:
self.landmarks["x"].append(landmark[0])
self.landmarks["y"].append(landmark[1])
def _landmarks_select(self):
#####
y_rank = np.array(np.argsort(self.landmarks["y"]))
self.landmarks_selected = {"x": np.array(self.landmarks["x"])[
y_rank][:3], "y": np.array(self.landmarks["y"])[y_rank][:3]}
x_rank = np.array(np.argsort(self.landmarks_selected["x"]))
self.landmarks_selected = {
"x": self.landmarks_selected["x"][x_rank][[0, 2]], "y": self.landmarks_selected["y"][x_rank][[0, 2]]}
def _alignement(self):
#####
h, w = self.in_img_g.shape
theta = np.arctan2((self.landmarks_selected["y"][1] - self.landmarks_selected["y"][0]), (
self.landmarks_selected["x"][1] - self.landmarks_selected["x"][0]))*180/np.pi
R = cv2.getRotationMatrix2D(
(self.landmarks_selected["x"][1], self.landmarks_selected["y"][1]), theta, 1)
self.align_img = cv2.warpAffine(self.in_img_g, R, (w, h))
point_1 = [self.landmarks_selected["x"]
[0], self.landmarks_selected["y"][0]]
point_2 = [self.landmarks_selected["x"]
[1], self.landmarks_selected["y"][1]]
point_1 = (R[:, :2] @ point_1 + R[:, -1]).astype(np.int)
point_2 = (R[:, :2] @ point_2 + R[:, -1]).astype(np.int)
self.landmarks_selected_align = {
"x": [point_1[0], point_2[0]], "y": [point_1[1], point_2[1]]}
def _roi_extract(self):
#####
point_1 = np.array([self.landmarks_selected_align["x"]
[0], self.landmarks_selected_align["y"][0]])
point_2 = np.array([self.landmarks_selected_align["x"]
[1], self.landmarks_selected_align["y"][1]])
self.ux = point_1[0]
self.uy = point_1[1] + (point_2-point_1)[0]//3
self.lx = point_2[0]
self.ly = point_2[1] + 4*(point_2-point_1)[0]//3
self.roi_zone_img = cv2.cvtColor(self.align_img, cv2.COLOR_GRAY2BGR)
cv2.rectangle(self.roi_zone_img, (self.lx, self.ly),
(self.ux, self.uy), (0, 255, 0), 2)
self.roi_img = self.align_img[self.uy:self.ly, self.ux:self.lx]
# PUBLIC METHODS
def extract_roi(self, path_in_img, rotate=False):
#####
self.in_img_c = cv2.imread(path_in_img)
if(rotate):
self.in_img_c = cv2.rotate(self.in_img_c, cv2.ROTATE_90_CLOCKWISE)
if len(self.in_img_c.shape) == 3:
self.in_img_g = cv2.cvtColor(self.in_img_c, cv2.COLOR_BGR2GRAY)
else:
self.in_img_g = self.in_img_c
self._threshold()
self._contours()
self._landmarks()
self._landmarks_select()
self._alignement()
self._roi_extract()
def save(self, path_out_img):
#####
cv2.imwrite(path_out_img, self.roi_img)
def show_result(self):
#####
plt.figure()
plt.subplot(241)
plt.imshow(self.in_img_g, cmap="gray")
plt.title("original")
plt.subplot(242)
plt.imshow(self.thresh_img, cmap="gray")
plt.title("threshold")
plt.subplot(243)
plt.imshow(self.contour_img, cmap="gray")
plt.plot(self.center_point["x"], self.center_point["y"], 'bx')
plt.title("contours")
plt.subplot(244)
plt.imshow(self.in_img_c, cmap="gray")
for idx in range(len(self.landmarks["x"])):
plt.plot(self.landmarks["x"][idx], self.landmarks["y"][idx], 'rx')
plt.title("landmarks")
plt.subplot(245)
plt.imshow(self.in_img_c, cmap="gray")
plt.plot(self.landmarks_selected["x"][0],
self.landmarks_selected["y"][0], 'rx')
plt.plot(self.landmarks_selected["x"][1],
self.landmarks_selected["y"][1], 'rx')
plt.title("selected")
plt.subplot(246)
plt.imshow(self.align_img, cmap="gray")
plt.plot(self.landmarks_selected_align["x"][0],
self.landmarks_selected_align["y"][0], 'rx')
plt.plot(self.landmarks_selected_align["x"][1],
self.landmarks_selected_align["y"][1], 'rx')
plt.title("alignement")
plt.subplot(247)
plt.imshow(self.roi_zone_img, cmap="gray")
plt.title("roi zone")
plt.subplot(248)
plt.imshow(self.roi_img, cmap="gray")
plt.title("extraction")
plt.show()
|
[
"matplotlib.pyplot.title",
"cv2.GaussianBlur",
"numpy.fft.rfft",
"numpy.arctan2",
"numpy.argsort",
"cv2.warpAffine",
"matplotlib.pyplot.figure",
"cv2.rectangle",
"cv2.getRotationMatrix2D",
"numpy.fft.irfft",
"cv2.cvtColor",
"cv2.imwrite",
"matplotlib.pyplot.imshow",
"cv2.drawContours",
"matplotlib.pyplot.show",
"numpy.square",
"numpy.concatenate",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.plot",
"cv2.rotate",
"cv2.threshold",
"cv2.moments",
"cv2.imread",
"numpy.diff",
"numpy.array",
"numpy.where",
"numpy.sign",
"cv2.findContours"
] |
[((244, 286), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['self.in_img_g', '(5, 5)', '(0)'], {}), '(self.in_img_g, (5, 5), 0)\n', (260, 286), False, 'import cv2\n'), ((316, 389), 'cv2.threshold', 'cv2.threshold', (['self.blur_img', '(0)', '(255)', '(cv2.THRESH_BINARY + cv2.THRESH_OTSU)'], {}), '(self.blur_img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)\n', (329, 389), False, 'import cv2\n'), ((470, 541), 'cv2.findContours', 'cv2.findContours', (['self.thresh_img', 'cv2.RETR_TREE', 'cv2.CHAIN_APPROX_NONE'], {}), '(self.thresh_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)\n', (486, 541), False, 'import cv2\n'), ((671, 741), 'cv2.drawContours', 'cv2.drawContours', (['self.contour_img', '[self.contours]', '(0)', '(255, 0, 0)', '(2)'], {}), '(self.contour_img, [self.contours], 0, (255, 0, 0), 2)\n', (687, 741), False, 'import cv2\n'), ((808, 836), 'cv2.moments', 'cv2.moments', (['self.thresh_img'], {}), '(self.thresh_img)\n', (819, 836), False, 'import cv2\n'), ((1084, 1156), 'numpy.concatenate', 'np.concatenate', (['[self.contours[left_id:, :], self.contours[:left_id, :]]'], {}), '([self.contours[left_id:, :], self.contours[:left_id, :]])\n', (1098, 1156), True, 'import numpy as np\n'), ((1303, 1322), 'numpy.fft.rfft', 'np.fft.rfft', (['dist_c'], {}), '(dist_c)\n', (1314, 1322), True, 'import numpy as np\n'), ((1359, 1403), 'numpy.concatenate', 'np.concatenate', (['[f[:cutoff], 0 * f[cutoff:]]'], {}), '([f[:cutoff], 0 * f[cutoff:]])\n', (1373, 1403), True, 'import numpy as np\n'), ((1421, 1440), 'numpy.fft.irfft', 'np.fft.irfft', (['f_new'], {}), '(f_new)\n', (1433, 1440), True, 'import numpy as np\n'), ((1462, 1479), 'numpy.diff', 'np.diff', (['dist_c_1'], {}), '(dist_c_1)\n', (1469, 1479), True, 'import numpy as np\n'), ((2497, 2603), 'cv2.getRotationMatrix2D', 'cv2.getRotationMatrix2D', (["(self.landmarks_selected['x'][1], self.landmarks_selected['y'][1])", 'theta', '(1)'], {}), "((self.landmarks_selected['x'][1], self.\n landmarks_selected['y'][1]), theta, 1)\n", (2520, 2603), False, 'import cv2\n'), ((2637, 2677), 'cv2.warpAffine', 'cv2.warpAffine', (['self.in_img_g', 'R', '(w, h)'], {}), '(self.in_img_g, R, (w, h))\n', (2651, 2677), False, 'import cv2\n'), ((3198, 3291), 'numpy.array', 'np.array', (["[self.landmarks_selected_align['x'][0], self.landmarks_selected_align['y'][0]]"], {}), "([self.landmarks_selected_align['x'][0], self.\n landmarks_selected_align['y'][0]])\n", (3206, 3291), True, 'import numpy as np\n'), ((3334, 3427), 'numpy.array', 'np.array', (["[self.landmarks_selected_align['x'][1], self.landmarks_selected_align['y'][1]]"], {}), "([self.landmarks_selected_align['x'][1], self.\n landmarks_selected_align['y'][1]])\n", (3342, 3427), True, 'import numpy as np\n'), ((3652, 3700), 'cv2.cvtColor', 'cv2.cvtColor', (['self.align_img', 'cv2.COLOR_GRAY2BGR'], {}), '(self.align_img, cv2.COLOR_GRAY2BGR)\n', (3664, 3700), False, 'import cv2\n'), ((3709, 3801), 'cv2.rectangle', 'cv2.rectangle', (['self.roi_zone_img', '(self.lx, self.ly)', '(self.ux, self.uy)', '(0, 255, 0)', '(2)'], {}), '(self.roi_zone_img, (self.lx, self.ly), (self.ux, self.uy), (0,\n 255, 0), 2)\n', (3722, 3801), False, 'import cv2\n'), ((4008, 4031), 'cv2.imread', 'cv2.imread', (['path_in_img'], {}), '(path_in_img)\n', (4018, 4031), False, 'import cv2\n'), ((4530, 4569), 'cv2.imwrite', 'cv2.imwrite', (['path_out_img', 'self.roi_img'], {}), '(path_out_img, self.roi_img)\n', (4541, 4569), False, 'import cv2\n'), ((4620, 4632), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (4630, 4632), True, 'import matplotlib.pyplot as plt\n'), ((4642, 4658), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(241)'], {}), '(241)\n', (4653, 4658), True, 'import matplotlib.pyplot as plt\n'), ((4667, 4705), 'matplotlib.pyplot.imshow', 'plt.imshow', (['self.in_img_g'], {'cmap': '"""gray"""'}), "(self.in_img_g, cmap='gray')\n", (4677, 4705), True, 'import matplotlib.pyplot as plt\n'), ((4714, 4735), 'matplotlib.pyplot.title', 'plt.title', (['"""original"""'], {}), "('original')\n", (4723, 4735), True, 'import matplotlib.pyplot as plt\n'), ((4745, 4761), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(242)'], {}), '(242)\n', (4756, 4761), True, 'import matplotlib.pyplot as plt\n'), ((4770, 4810), 'matplotlib.pyplot.imshow', 'plt.imshow', (['self.thresh_img'], {'cmap': '"""gray"""'}), "(self.thresh_img, cmap='gray')\n", (4780, 4810), True, 'import matplotlib.pyplot as plt\n'), ((4819, 4841), 'matplotlib.pyplot.title', 'plt.title', (['"""threshold"""'], {}), "('threshold')\n", (4828, 4841), True, 'import matplotlib.pyplot as plt\n'), ((4851, 4867), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(243)'], {}), '(243)\n', (4862, 4867), True, 'import matplotlib.pyplot as plt\n'), ((4876, 4917), 'matplotlib.pyplot.imshow', 'plt.imshow', (['self.contour_img'], {'cmap': '"""gray"""'}), "(self.contour_img, cmap='gray')\n", (4886, 4917), True, 'import matplotlib.pyplot as plt\n'), ((4926, 4988), 'matplotlib.pyplot.plot', 'plt.plot', (["self.center_point['x']", "self.center_point['y']", '"""bx"""'], {}), "(self.center_point['x'], self.center_point['y'], 'bx')\n", (4934, 4988), True, 'import matplotlib.pyplot as plt\n'), ((4997, 5018), 'matplotlib.pyplot.title', 'plt.title', (['"""contours"""'], {}), "('contours')\n", (5006, 5018), True, 'import matplotlib.pyplot as plt\n'), ((5028, 5044), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(244)'], {}), '(244)\n', (5039, 5044), True, 'import matplotlib.pyplot as plt\n'), ((5053, 5091), 'matplotlib.pyplot.imshow', 'plt.imshow', (['self.in_img_c'], {'cmap': '"""gray"""'}), "(self.in_img_c, cmap='gray')\n", (5063, 5091), True, 'import matplotlib.pyplot as plt\n'), ((5231, 5253), 'matplotlib.pyplot.title', 'plt.title', (['"""landmarks"""'], {}), "('landmarks')\n", (5240, 5253), True, 'import matplotlib.pyplot as plt\n'), ((5263, 5279), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(245)'], {}), '(245)\n', (5274, 5279), True, 'import matplotlib.pyplot as plt\n'), ((5288, 5326), 'matplotlib.pyplot.imshow', 'plt.imshow', (['self.in_img_c'], {'cmap': '"""gray"""'}), "(self.in_img_c, cmap='gray')\n", (5298, 5326), True, 'import matplotlib.pyplot as plt\n'), ((5335, 5420), 'matplotlib.pyplot.plot', 'plt.plot', (["self.landmarks_selected['x'][0]", "self.landmarks_selected['y'][0]", '"""rx"""'], {}), "(self.landmarks_selected['x'][0], self.landmarks_selected['y'][0], 'rx'\n )\n", (5343, 5420), True, 'import matplotlib.pyplot as plt\n'), ((5441, 5526), 'matplotlib.pyplot.plot', 'plt.plot', (["self.landmarks_selected['x'][1]", "self.landmarks_selected['y'][1]", '"""rx"""'], {}), "(self.landmarks_selected['x'][1], self.landmarks_selected['y'][1], 'rx'\n )\n", (5449, 5526), True, 'import matplotlib.pyplot as plt\n'), ((5547, 5568), 'matplotlib.pyplot.title', 'plt.title', (['"""selected"""'], {}), "('selected')\n", (5556, 5568), True, 'import matplotlib.pyplot as plt\n'), ((5578, 5594), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(246)'], {}), '(246)\n', (5589, 5594), True, 'import matplotlib.pyplot as plt\n'), ((5603, 5642), 'matplotlib.pyplot.imshow', 'plt.imshow', (['self.align_img'], {'cmap': '"""gray"""'}), "(self.align_img, cmap='gray')\n", (5613, 5642), True, 'import matplotlib.pyplot as plt\n'), ((5651, 5748), 'matplotlib.pyplot.plot', 'plt.plot', (["self.landmarks_selected_align['x'][0]", "self.landmarks_selected_align['y'][0]", '"""rx"""'], {}), "(self.landmarks_selected_align['x'][0], self.\n landmarks_selected_align['y'][0], 'rx')\n", (5659, 5748), True, 'import matplotlib.pyplot as plt\n'), ((5769, 5866), 'matplotlib.pyplot.plot', 'plt.plot', (["self.landmarks_selected_align['x'][1]", "self.landmarks_selected_align['y'][1]", '"""rx"""'], {}), "(self.landmarks_selected_align['x'][1], self.\n landmarks_selected_align['y'][1], 'rx')\n", (5777, 5866), True, 'import matplotlib.pyplot as plt\n'), ((5887, 5910), 'matplotlib.pyplot.title', 'plt.title', (['"""alignement"""'], {}), "('alignement')\n", (5896, 5910), True, 'import matplotlib.pyplot as plt\n'), ((5920, 5936), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(247)'], {}), '(247)\n', (5931, 5936), True, 'import matplotlib.pyplot as plt\n'), ((5945, 5987), 'matplotlib.pyplot.imshow', 'plt.imshow', (['self.roi_zone_img'], {'cmap': '"""gray"""'}), "(self.roi_zone_img, cmap='gray')\n", (5955, 5987), True, 'import matplotlib.pyplot as plt\n'), ((5996, 6017), 'matplotlib.pyplot.title', 'plt.title', (['"""roi zone"""'], {}), "('roi zone')\n", (6005, 6017), True, 'import matplotlib.pyplot as plt\n'), ((6027, 6043), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(248)'], {}), '(248)\n', (6038, 6043), True, 'import matplotlib.pyplot as plt\n'), ((6052, 6089), 'matplotlib.pyplot.imshow', 'plt.imshow', (['self.roi_img'], {'cmap': '"""gray"""'}), "(self.roi_img, cmap='gray')\n", (6062, 6089), True, 'import matplotlib.pyplot as plt\n'), ((6098, 6121), 'matplotlib.pyplot.title', 'plt.title', (['"""extraction"""'], {}), "('extraction')\n", (6107, 6121), True, 'import matplotlib.pyplot as plt\n'), ((6131, 6141), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6139, 6141), True, 'import matplotlib.pyplot as plt\n'), ((1824, 1855), 'numpy.argsort', 'np.argsort', (["self.landmarks['y']"], {}), "(self.landmarks['y'])\n", (1834, 1855), True, 'import numpy as np\n'), ((2028, 2068), 'numpy.argsort', 'np.argsort', (["self.landmarks_selected['x']"], {}), "(self.landmarks_selected['x'])\n", (2038, 2068), True, 'import numpy as np\n'), ((4081, 4131), 'cv2.rotate', 'cv2.rotate', (['self.in_img_c', 'cv2.ROTATE_90_CLOCKWISE'], {}), '(self.in_img_c, cv2.ROTATE_90_CLOCKWISE)\n', (4091, 4131), False, 'import cv2\n'), ((4203, 4250), 'cv2.cvtColor', 'cv2.cvtColor', (['self.in_img_c', 'cv2.COLOR_BGR2GRAY'], {}), '(self.in_img_c, cv2.COLOR_BGR2GRAY)\n', (4215, 4250), False, 'import cv2\n'), ((5156, 5222), 'matplotlib.pyplot.plot', 'plt.plot', (["self.landmarks['x'][idx]", "self.landmarks['y'][idx]", '"""rx"""'], {}), "(self.landmarks['x'][idx], self.landmarks['y'][idx], 'rx')\n", (5164, 5222), True, 'import matplotlib.pyplot as plt\n'), ((1510, 1529), 'numpy.sign', 'np.sign', (['derivative'], {}), '(derivative)\n', (1517, 1529), True, 'import numpy as np\n'), ((1615, 1640), 'numpy.where', 'np.where', (['(sign_change > 0)'], {}), '(sign_change > 0)\n', (1623, 1640), True, 'import numpy as np\n'), ((2313, 2462), 'numpy.arctan2', 'np.arctan2', (["(self.landmarks_selected['y'][1] - self.landmarks_selected['y'][0])", "(self.landmarks_selected['x'][1] - self.landmarks_selected['x'][0])"], {}), "(self.landmarks_selected['y'][1] - self.landmarks_selected['y'][0\n ], self.landmarks_selected['x'][1] - self.landmarks_selected['x'][0])\n", (2323, 2462), True, 'import numpy as np\n'), ((1195, 1270), 'numpy.square', 'np.square', (["(self.contours - [self.center_point['x'], self.center_point['y']])"], {}), "(self.contours - [self.center_point['x'], self.center_point['y']])\n", (1204, 1270), True, 'import numpy as np\n'), ((1897, 1926), 'numpy.array', 'np.array', (["self.landmarks['x']"], {}), "(self.landmarks['x'])\n", (1905, 1926), True, 'import numpy as np\n'), ((1958, 1987), 'numpy.array', 'np.array', (["self.landmarks['y']"], {}), "(self.landmarks['y'])\n", (1966, 1987), True, 'import numpy as np\n')]
|
import numpy as np
from pandas.testing import assert_frame_equal
import warnings
from hdmf.backends.hdf5 import HDF5IO
from hdmf.common import DynamicTable, VectorData, get_manager, AlignedDynamicTable
from hdmf.testing import TestCase, remove_test_file
class TestAlignedDynamicTableContainer(TestCase):
"""
Test the AlignedDynamicTable Container class.
"""
def setUp(self):
warnings.simplefilter("always") # Trigger all warnings
self.path = 'test_icephys_meta_intracellularrecording.h5'
def tearDown(self):
remove_test_file(self.path)
def test_init(self):
"""Test that just checks that populating the tables with data works correctly"""
AlignedDynamicTable(
name='test_aligned_table',
description='Test aligned container')
def test_init_categories_without_category_tables_error(self):
# Test raise error if categories is given without category_tables
with self.assertRaisesWith(ValueError, "Categories provided but no category_tables given"):
AlignedDynamicTable(
name='test_aligned_table',
description='Test aligned container',
categories=['cat1', 'cat2'])
def test_init_length_mismatch_between_categories_and_category_tables(self):
# Test length mismatch between categories and category_tables
with self.assertRaisesWith(ValueError, "0 category_tables given but 2 categories specified"):
AlignedDynamicTable(
name='test_aligned_table',
description='Test aligned container',
categories=['cat1', 'cat2'],
category_tables=[])
def test_init_category_table_names_do_not_match_categories(self):
# Construct some categories for testing
category_names = ['test1', 'test2', 'test3']
num_rows = 10
categories = [DynamicTable(name=val,
description=val+" description",
columns=[VectorData(name=val+t,
description=val+t+' description',
data=np.arange(num_rows)) for t in ['c1', 'c2', 'c3']]
) for val in category_names]
# Test add category_table that is not listed in the categories list
with self.assertRaisesWith(ValueError,
"DynamicTable test3 does not appear in categories ['test1', 'test2', 't3']"):
AlignedDynamicTable(
name='test_aligned_table',
description='Test aligned container',
categories=['test1', 'test2', 't3'], # bad name for 'test3'
category_tables=categories)
def test_init_duplicate_category_table_name(self):
# Test duplicate table name
with self.assertRaisesWith(ValueError, "Duplicate table name test1 found in input dynamic_tables"):
categories = [DynamicTable(name=val,
description=val+" description",
columns=[VectorData(name=val+t,
description=val+t+' description',
data=np.arange(10)) for t in ['c1', 'c2', 'c3']]
) for val in ['test1', 'test1', 'test3']]
AlignedDynamicTable(
name='test_aligned_table',
description='Test aligned container',
categories=['test1', 'test2', 'test3'],
category_tables=categories)
def test_init_misaligned_category_tables(self):
"""Test misaligned category tables"""
categories = [DynamicTable(name=val,
description=val+" description",
columns=[VectorData(name=val+t,
description=val+t+' description',
data=np.arange(10)) for t in ['c1', 'c2', 'c3']]
) for val in ['test1', 'test2']]
categories.append(DynamicTable(name='test3',
description="test3 description",
columns=[VectorData(name='test3 '+t,
description='test3 '+t+' description',
data=np.arange(8)) for t in ['c1', 'c2', 'c3']]))
with self.assertRaisesWith(ValueError,
"Category DynamicTable test3 does not align, it has 8 rows expected 10"):
AlignedDynamicTable(
name='test_aligned_table',
description='Test aligned container',
categories=['test1', 'test2', 'test3'],
category_tables=categories)
def test_init_with_custom_empty_categories(self):
"""Test that we can create an empty table with custom categories"""
category_names = ['test1', 'test2', 'test3']
categories = [DynamicTable(name=val, description=val+" description") for val in category_names]
AlignedDynamicTable(
name='test_aligned_table',
description='Test aligned container',
category_tables=categories)
def test_init_with_custom_nonempty_categories(self):
"""Test that we can create an empty table with custom categories"""
category_names = ['test1', 'test2', 'test3']
num_rows = 10
categories = [DynamicTable(name=val,
description=val+" description",
columns=[VectorData(name=val+t,
description=val+t+' description',
data=np.arange(num_rows)) for t in ['c1', 'c2', 'c3']]
) for val in category_names]
temp = AlignedDynamicTable(
name='test_aligned_table',
description='Test aligned container',
category_tables=categories)
self.assertEqual(temp.categories, category_names)
def test_init_with_custom_nonempty_categories_and_main(self):
"""
Test that we can create a non-empty table with custom non-empty categories
"""
category_names = ['test1', 'test2', 'test3']
num_rows = 10
categories = [DynamicTable(name=val,
description=val+" description",
columns=[VectorData(name=t,
description=val+t+' description',
data=np.arange(num_rows)) for t in ['c1', 'c2', 'c3']]
) for val in category_names]
temp = AlignedDynamicTable(
name='test_aligned_table',
description='Test aligned container',
category_tables=categories,
columns=[VectorData(name='main_' + t,
description='main_'+t+'_description',
data=np.arange(num_rows)) for t in ['c1', 'c2', 'c3']])
self.assertEqual(temp.categories, category_names)
self.assertTrue('test1' in temp) # test that contains category works
self.assertTrue(('test1', 'c1') in temp) # test that contains a column works
# test the error case of a tuple with len !=2
with self.assertRaisesWith(ValueError, "Expected tuple of strings of length 2 got tuple of length 3"):
('test1', 'c1', 't3') in temp
self.assertTupleEqual(temp.colnames, ('main_c1', 'main_c2', 'main_c3')) # confirm column names
def test_init_with_custom_misaligned_categories(self):
"""Test that we cannot create an empty table with custom categories"""
num_rows = 10
val1 = 'test1'
val2 = 'test2'
categories = [DynamicTable(name=val1,
description=val1+" description",
columns=[VectorData(name=val1+t,
description=val1+t+' description',
data=np.arange(num_rows)) for t in ['c1', 'c2', 'c3']]),
DynamicTable(name=val2,
description=val2+" description",
columns=[VectorData(name=val2+t,
description=val2+t+' description',
data=np.arange(num_rows+1)) for t in ['c1', 'c2', 'c3']])
]
with self.assertRaisesWith(ValueError,
"Category DynamicTable test2 does not align, it has 11 rows expected 10"):
AlignedDynamicTable(
name='test_aligned_table',
description='Test aligned container',
category_tables=categories)
def test_init_with_duplicate_custom_categories(self):
"""Test that we can create an empty table with custom categories"""
category_names = ['test1', 'test1']
num_rows = 10
categories = [DynamicTable(name=val,
description=val+" description",
columns=[VectorData(name=val+t,
description=val+t+' description',
data=np.arange(num_rows)) for t in ['c1', 'c2', 'c3']]
) for val in category_names]
with self.assertRaisesWith(ValueError, "Duplicate table name test1 found in input dynamic_tables"):
AlignedDynamicTable(
name='test_aligned_table',
description='Test aligned container',
category_tables=categories)
def test_init_with_bad_custom_categories(self):
"""Test that we cannot provide a category that is not a DynamicTable"""
num_rows = 10
categories = [ # good category
DynamicTable(name='test1',
description="test1 description",
columns=[VectorData(name='test1'+t,
description='test1' + t + ' description',
data=np.arange(num_rows)) for t in ['c1', 'c2', 'c3']]
),
# use a list as a bad category example
[0, 1, 2]]
with self.assertRaisesWith(ValueError, "Category table with index 1 is not a DynamicTable"):
AlignedDynamicTable(
name='test_aligned_table',
description='Test aligned container',
category_tables=categories)
def test_round_trip_container(self):
"""Test read and write the container by itself"""
category_names = ['test1', 'test2', 'test3']
num_rows = 10
categories = [DynamicTable(name=val,
description=val+" description",
columns=[VectorData(name=t,
description=val+t+' description',
data=np.arange(num_rows)) for t in ['c1', 'c2', 'c3']]
) for val in category_names]
curr = AlignedDynamicTable(
name='test_aligned_table',
description='Test aligned container',
category_tables=categories)
with HDF5IO(self.path, manager=get_manager(), mode='w') as io:
io.write(curr)
with HDF5IO(self.path, manager=get_manager(), mode='r') as io:
incon = io.read()
self.assertListEqual(incon.categories, curr.categories)
for n in category_names:
assert_frame_equal(incon[n], curr[n])
def test_add_category(self):
"""Test that we can correct a non-empty category to an existing table"""
category_names = ['test1', 'test2', 'test3']
num_rows = 10
categories = [DynamicTable(name=val,
description=val+" description",
columns=[VectorData(name=val+t,
description=val+t+' description',
data=np.arange(num_rows)) for t in ['c1', 'c2', 'c3']]
) for val in category_names]
adt = AlignedDynamicTable(
name='test_aligned_table',
description='Test aligned container',
category_tables=categories[0:2])
self.assertListEqual(adt.categories, category_names[0:2])
adt.add_category(categories[-1])
self.assertListEqual(adt.categories, category_names)
def test_add_category_misaligned_rows(self):
"""Test that we can correct a non-empty category to an existing table"""
category_names = ['test1', 'test2']
num_rows = 10
categories = [DynamicTable(name=val,
description=val+" description",
columns=[VectorData(name=val+t,
description=val+t+' description',
data=np.arange(num_rows)) for t in ['c1', 'c2', 'c3']]
) for val in category_names]
adt = AlignedDynamicTable(
name='test_aligned_table',
description='Test aligned container',
category_tables=categories)
self.assertListEqual(adt.categories, category_names)
with self.assertRaisesWith(ValueError, "New category DynamicTable does not align, it has 8 rows expected 10"):
adt.add_category(DynamicTable(name='test3',
description='test3_description',
columns=[VectorData(name='test3_'+t,
description='test3 '+t+' description',
data=np.arange(num_rows - 2)) for t in ['c1', 'c2', 'c3']
]))
def test_add_category_already_in_table(self):
category_names = ['test1', 'test2', 'test2']
num_rows = 10
categories = [DynamicTable(name=val,
description=val+" description",
columns=[VectorData(name=val+t,
description=val+t+' description',
data=np.arange(num_rows)) for t in ['c1', 'c2', 'c3']]
) for val in category_names]
adt = AlignedDynamicTable(
name='test_aligned_table',
description='Test aligned container',
category_tables=categories[0:2])
self.assertListEqual(adt.categories, category_names[0:2])
with self.assertRaisesWith(ValueError, "Category test2 already in the table"):
adt.add_category(categories[-1])
def test_add_column(self):
adt = AlignedDynamicTable(
name='test_aligned_table',
description='Test aligned container',
columns=[VectorData(name='test_'+t,
description='test_'+t+' description',
data=np.arange(10)) for t in ['c1', 'c2', 'c3']])
# Test successful add
adt.add_column(name='testA', description='testA', data=np.arange(10))
self.assertTupleEqual(adt.colnames, ('test_c1', 'test_c2', 'test_c3', 'testA'))
def test_add_column_bad_category(self):
"""Test add column with bad category"""
adt = AlignedDynamicTable(
name='test_aligned_table',
description='Test aligned container',
columns=[VectorData(name='test_'+t,
description='test_'+t+' description',
data=np.arange(10)) for t in ['c1', 'c2', 'c3']])
with self.assertRaisesWith(KeyError, "'Category mycat not in table'"):
adt.add_column(category='mycat', name='testA', description='testA', data=np.arange(10))
def test_add_column_bad_length(self):
"""Test add column that is too short"""
adt = AlignedDynamicTable(
name='test_aligned_table',
description='Test aligned container',
columns=[VectorData(name='test_'+t,
description='test_'+t+' description',
data=np.arange(10)) for t in ['c1', 'c2', 'c3']])
# Test successful add
with self.assertRaisesWith(ValueError, "column must have the same number of rows as 'id'"):
adt.add_column(name='testA', description='testA', data=np.arange(8))
def test_add_column_to_subcategory(self):
"""Test adding a column to a subcategory"""
category_names = ['test1', 'test2', 'test3']
num_rows = 10
categories = [DynamicTable(name=val,
description=val+" description",
columns=[VectorData(name=val+t,
description=val+t+' description',
data=np.arange(num_rows)) for t in ['c1', 'c2', 'c3']]
) for val in category_names]
adt = AlignedDynamicTable(
name='test_aligned_table',
description='Test aligned container',
category_tables=categories)
self.assertListEqual(adt.categories, category_names)
# Test successful add
adt.add_column(category='test2', name='testA', description='testA', data=np.arange(10))
self.assertTupleEqual(adt.get_category('test2').colnames, ('test2c1', 'test2c2', 'test2c3', 'testA'))
def test_add_row(self):
"""Test adding a row to a non_empty table"""
category_names = ['test1', ]
num_rows = 10
categories = [DynamicTable(name=val,
description=val+" description",
columns=[VectorData(name=t,
description=val+t+' description',
data=np.arange(num_rows)) for t in ['c1', 'c2']]
) for val in category_names]
temp = AlignedDynamicTable(
name='test_aligned_table',
description='Test aligned container',
category_tables=categories,
columns=[VectorData(name='main_' + t,
description='main_'+t+'_description',
data=np.arange(num_rows)) for t in ['c1', 'c2']])
self.assertListEqual(temp.categories, category_names)
# Test successful add
temp.add_row(test1=dict(c1=1, c2=2), main_c1=3, main_c2=5)
self.assertListEqual(temp[10].iloc[0].tolist(), [3, 5, 10, 1, 2])
# Test successful add version 2
temp.add_row(data=dict(test1=dict(c1=1, c2=2), main_c1=4, main_c2=5))
self.assertListEqual(temp[11].iloc[0].tolist(), [4, 5, 11, 1, 2])
# Test missing categories data
with self.assertRaises(KeyError) as ke:
temp.add_row(main_c1=3, main_c2=5)
self.assertTrue("row data keys do not match" in str(ke.exception))
def test_get_item(self):
"""Test getting elements from the table"""
category_names = ['test1', ]
num_rows = 10
categories = [DynamicTable(name=val,
description=val+" description",
columns=[VectorData(name=t,
description=val+t+' description',
data=np.arange(num_rows) + i + 3)
for i, t in enumerate(['c1', 'c2'])]
) for val in category_names]
temp = AlignedDynamicTable(
name='test_aligned_table',
description='Test aligned container',
category_tables=categories,
columns=[VectorData(name='main_' + t,
description='main_'+t+'_description',
data=np.arange(num_rows)+2) for t in ['c1', 'c2']])
self.assertListEqual(temp.categories, category_names)
# Test slicing with a single index
self.assertListEqual(temp[5].iloc[0].tolist(), [7, 7, 5, 8, 9])
# Test slice with list
self.assertListEqual(temp[[5, 7]].iloc[0].tolist(), [7, 7, 5, 8, 9])
self.assertListEqual(temp[[5, 7]].iloc[1].tolist(), [9, 9, 7, 10, 11])
# Test slice with slice
self.assertListEqual(temp[5:7].iloc[0].tolist(), [7, 7, 5, 8, 9])
self.assertListEqual(temp[5:7].iloc[1].tolist(), [8, 8, 6, 9, 10])
# Test slice with numpy index arrya
self.assertListEqual(temp[np.asarray([5, 8])].iloc[0].tolist(), [7, 7, 5, 8, 9])
self.assertListEqual(temp[np.asarray([5, 8])].iloc[1].tolist(), [10, 10, 8, 11, 12])
# Test slicing for a single column
self.assertListEqual(temp['main_c1'][:].tolist(), (np.arange(num_rows)+2).tolist())
# Test slicing for a single category
assert_frame_equal(temp['test1'], categories[0].to_dataframe())
# Test getting the main table
assert_frame_equal(temp[None], temp.to_dataframe())
# Test getting a specific column
self.assertListEqual(temp['test1', 'c1'][:].tolist(), (np.arange(num_rows) + 3).tolist())
# Test getting a specific cell
self.assertEqual(temp[None, 'main_c1', 1], 3)
# Test bad selection tuple
with self.assertRaisesWith(ValueError,
"Expected tuple of length 2 or 3 with (category, column, row) as value."):
temp[('main_c1',)]
def test_to_dataframe(self):
"""Test that the to_dataframe method works"""
category_names = ['test1', 'test2', 'test3']
num_rows = 10
categories = [DynamicTable(name=val,
description=val+" description",
columns=[VectorData(name=t,
description=val+t+' description',
data=np.arange(num_rows)) for t in ['c1', 'c2', 'c3']]
) for val in category_names]
adt = AlignedDynamicTable(
name='test_aligned_table',
description='Test aligned container',
category_tables=categories,
columns=[VectorData(name='main_' + t,
description='main_'+t+'_description',
data=np.arange(num_rows)) for t in ['c1', 'c2', 'c3']])
# Test the to_dataframe method with default settings
tdf = adt.to_dataframe()
self.assertListEqual(tdf.index.tolist(), list(range(10)))
self.assertTupleEqual(tdf.index.name, ('test_aligned_table', 'id'))
expected_cols = [('test_aligned_table', 'main_c1'),
('test_aligned_table', 'main_c2'),
('test_aligned_table', 'main_c3'),
('test1', 'id'), ('test1', 'c1'), ('test1', 'c2'), ('test1', 'c3'),
('test2', 'id'), ('test2', 'c1'), ('test2', 'c2'), ('test2', 'c3'),
('test3', 'id'), ('test3', 'c1'), ('test3', 'c2'), ('test3', 'c3')]
tdf_cols = tdf.columns.tolist()
for v in zip(expected_cols, tdf_cols):
self.assertTupleEqual(v[0], v[1])
# test the to_dataframe method with ignore_category_ids set to True
tdf = adt.to_dataframe(ignore_category_ids=True)
self.assertListEqual(tdf.index.tolist(), list(range(10)))
self.assertTupleEqual(tdf.index.name, ('test_aligned_table', 'id'))
expected_cols = [('test_aligned_table', 'main_c1'),
('test_aligned_table', 'main_c2'),
('test_aligned_table', 'main_c3'),
('test1', 'c1'), ('test1', 'c2'), ('test1', 'c3'),
('test2', 'c1'), ('test2', 'c2'), ('test2', 'c3'),
('test3', 'c1'), ('test3', 'c2'), ('test3', 'c3')]
tdf_cols = tdf.columns.tolist()
for v in zip(expected_cols, tdf_cols):
self.assertTupleEqual(v[0], v[1])
def test_nested_aligned_dynamic_table_not_allowed(self):
"""
Test that using and AlignedDynamicTable as category for an AlignedDynamicTable is not allowed
"""
# create an AlignedDynamicTable as category
subsubcol1 = VectorData(name='sub_sub_column1', description='test sub sub column', data=['test11', 'test12'])
sub_category = DynamicTable(name='sub_category1', description='test subcategory table', columns=[subsubcol1, ])
subcol1 = VectorData(name='sub_column1', description='test-subcolumn', data=['test1', 'test2'])
adt_category = AlignedDynamicTable(
name='category1',
description='test using AlignedDynamicTable as a category',
columns=[subcol1, ],
category_tables=[sub_category, ])
# Create a regular column for our main AlignedDynamicTable
col1 = VectorData(name='column1', description='regular test column', data=['test1', 'test2'])
# test 1: Make sure we can't add the AlignedDynamicTable category on init
msg = ("Category table with index %i is an AlignedDynamicTable. "
"Nesting of AlignedDynamicTable is currently not supported." % 0)
with self.assertRaisesWith(ValueError, msg):
# create the nested AlignedDynamicTable with our adt_category as a sub-category
AlignedDynamicTable(
name='nested_adt',
description='test nesting AlignedDynamicTable',
columns=[col1, ],
category_tables=[adt_category, ])
# test 2: Make sure we can't add the AlignedDynamicTable category via add_category
adt = AlignedDynamicTable(
name='nested_adt',
description='test nesting AlignedDynamicTable',
columns=[col1, ])
msg = "Category is an AlignedDynamicTable. Nesting of AlignedDynamicTable is currently not supported."
with self.assertRaisesWith(ValueError, msg):
adt.add_category(adt_category)
|
[
"pandas.testing.assert_frame_equal",
"warnings.simplefilter",
"hdmf.common.VectorData",
"numpy.asarray",
"hdmf.common.DynamicTable",
"hdmf.common.AlignedDynamicTable",
"numpy.arange",
"hdmf.common.get_manager",
"hdmf.testing.remove_test_file"
] |
[((402, 433), 'warnings.simplefilter', 'warnings.simplefilter', (['"""always"""'], {}), "('always')\n", (423, 433), False, 'import warnings\n'), ((557, 584), 'hdmf.testing.remove_test_file', 'remove_test_file', (['self.path'], {}), '(self.path)\n', (573, 584), False, 'from hdmf.testing import TestCase, remove_test_file\n'), ((708, 797), 'hdmf.common.AlignedDynamicTable', 'AlignedDynamicTable', ([], {'name': '"""test_aligned_table"""', 'description': '"""Test aligned container"""'}), "(name='test_aligned_table', description=\n 'Test aligned container')\n", (727, 797), False, 'from hdmf.common import DynamicTable, VectorData, get_manager, AlignedDynamicTable\n'), ((5354, 5471), 'hdmf.common.AlignedDynamicTable', 'AlignedDynamicTable', ([], {'name': '"""test_aligned_table"""', 'description': '"""Test aligned container"""', 'category_tables': 'categories'}), "(name='test_aligned_table', description=\n 'Test aligned container', category_tables=categories)\n", (5373, 5471), False, 'from hdmf.common import DynamicTable, VectorData, get_manager, AlignedDynamicTable\n'), ((6170, 6287), 'hdmf.common.AlignedDynamicTable', 'AlignedDynamicTable', ([], {'name': '"""test_aligned_table"""', 'description': '"""Test aligned container"""', 'category_tables': 'categories'}), "(name='test_aligned_table', description=\n 'Test aligned container', category_tables=categories)\n", (6189, 6287), False, 'from hdmf.common import DynamicTable, VectorData, get_manager, AlignedDynamicTable\n'), ((11853, 11970), 'hdmf.common.AlignedDynamicTable', 'AlignedDynamicTable', ([], {'name': '"""test_aligned_table"""', 'description': '"""Test aligned container"""', 'category_tables': 'categories'}), "(name='test_aligned_table', description=\n 'Test aligned container', category_tables=categories)\n", (11872, 11970), False, 'from hdmf.common import DynamicTable, VectorData, get_manager, AlignedDynamicTable\n'), ((13009, 13131), 'hdmf.common.AlignedDynamicTable', 'AlignedDynamicTable', ([], {'name': '"""test_aligned_table"""', 'description': '"""Test aligned container"""', 'category_tables': 'categories[0:2]'}), "(name='test_aligned_table', description=\n 'Test aligned container', category_tables=categories[0:2])\n", (13028, 13131), False, 'from hdmf.common import DynamicTable, VectorData, get_manager, AlignedDynamicTable\n'), ((13985, 14102), 'hdmf.common.AlignedDynamicTable', 'AlignedDynamicTable', ([], {'name': '"""test_aligned_table"""', 'description': '"""Test aligned container"""', 'category_tables': 'categories'}), "(name='test_aligned_table', description=\n 'Test aligned container', category_tables=categories)\n", (14004, 14102), False, 'from hdmf.common import DynamicTable, VectorData, get_manager, AlignedDynamicTable\n'), ((15383, 15505), 'hdmf.common.AlignedDynamicTable', 'AlignedDynamicTable', ([], {'name': '"""test_aligned_table"""', 'description': '"""Test aligned container"""', 'category_tables': 'categories[0:2]'}), "(name='test_aligned_table', description=\n 'Test aligned container', category_tables=categories[0:2])\n", (15402, 15505), False, 'from hdmf.common import DynamicTable, VectorData, get_manager, AlignedDynamicTable\n'), ((18141, 18258), 'hdmf.common.AlignedDynamicTable', 'AlignedDynamicTable', ([], {'name': '"""test_aligned_table"""', 'description': '"""Test aligned container"""', 'category_tables': 'categories'}), "(name='test_aligned_table', description=\n 'Test aligned container', category_tables=categories)\n", (18160, 18258), False, 'from hdmf.common import DynamicTable, VectorData, get_manager, AlignedDynamicTable\n'), ((25625, 25726), 'hdmf.common.VectorData', 'VectorData', ([], {'name': '"""sub_sub_column1"""', 'description': '"""test sub sub column"""', 'data': "['test11', 'test12']"}), "(name='sub_sub_column1', description='test sub sub column', data=\n ['test11', 'test12'])\n", (25635, 25726), False, 'from hdmf.common import DynamicTable, VectorData, get_manager, AlignedDynamicTable\n'), ((25745, 25843), 'hdmf.common.DynamicTable', 'DynamicTable', ([], {'name': '"""sub_category1"""', 'description': '"""test subcategory table"""', 'columns': '[subsubcol1]'}), "(name='sub_category1', description='test subcategory table',\n columns=[subsubcol1])\n", (25757, 25843), False, 'from hdmf.common import DynamicTable, VectorData, get_manager, AlignedDynamicTable\n'), ((25860, 25949), 'hdmf.common.VectorData', 'VectorData', ([], {'name': '"""sub_column1"""', 'description': '"""test-subcolumn"""', 'data': "['test1', 'test2']"}), "(name='sub_column1', description='test-subcolumn', data=['test1',\n 'test2'])\n", (25870, 25949), False, 'from hdmf.common import DynamicTable, VectorData, get_manager, AlignedDynamicTable\n'), ((25969, 26126), 'hdmf.common.AlignedDynamicTable', 'AlignedDynamicTable', ([], {'name': '"""category1"""', 'description': '"""test using AlignedDynamicTable as a category"""', 'columns': '[subcol1]', 'category_tables': '[sub_category]'}), "(name='category1', description=\n 'test using AlignedDynamicTable as a category', columns=[subcol1],\n category_tables=[sub_category])\n", (25988, 26126), False, 'from hdmf.common import DynamicTable, VectorData, get_manager, AlignedDynamicTable\n'), ((26254, 26344), 'hdmf.common.VectorData', 'VectorData', ([], {'name': '"""column1"""', 'description': '"""regular test column"""', 'data': "['test1', 'test2']"}), "(name='column1', description='regular test column', data=['test1',\n 'test2'])\n", (26264, 26344), False, 'from hdmf.common import DynamicTable, VectorData, get_manager, AlignedDynamicTable\n'), ((27046, 27153), 'hdmf.common.AlignedDynamicTable', 'AlignedDynamicTable', ([], {'name': '"""nested_adt"""', 'description': '"""test nesting AlignedDynamicTable"""', 'columns': '[col1]'}), "(name='nested_adt', description=\n 'test nesting AlignedDynamicTable', columns=[col1])\n", (27065, 27153), False, 'from hdmf.common import DynamicTable, VectorData, get_manager, AlignedDynamicTable\n'), ((1071, 1189), 'hdmf.common.AlignedDynamicTable', 'AlignedDynamicTable', ([], {'name': '"""test_aligned_table"""', 'description': '"""Test aligned container"""', 'categories': "['cat1', 'cat2']"}), "(name='test_aligned_table', description=\n 'Test aligned container', categories=['cat1', 'cat2'])\n", (1090, 1189), False, 'from hdmf.common import DynamicTable, VectorData, get_manager, AlignedDynamicTable\n'), ((1500, 1638), 'hdmf.common.AlignedDynamicTable', 'AlignedDynamicTable', ([], {'name': '"""test_aligned_table"""', 'description': '"""Test aligned container"""', 'categories': "['cat1', 'cat2']", 'category_tables': '[]'}), "(name='test_aligned_table', description=\n 'Test aligned container', categories=['cat1', 'cat2'], category_tables=[])\n", (1519, 1638), False, 'from hdmf.common import DynamicTable, VectorData, get_manager, AlignedDynamicTable\n'), ((2583, 2741), 'hdmf.common.AlignedDynamicTable', 'AlignedDynamicTable', ([], {'name': '"""test_aligned_table"""', 'description': '"""Test aligned container"""', 'categories': "['test1', 'test2', 't3']", 'category_tables': 'categories'}), "(name='test_aligned_table', description=\n 'Test aligned container', categories=['test1', 'test2', 't3'],\n category_tables=categories)\n", (2602, 2741), False, 'from hdmf.common import DynamicTable, VectorData, get_manager, AlignedDynamicTable\n'), ((3507, 3668), 'hdmf.common.AlignedDynamicTable', 'AlignedDynamicTable', ([], {'name': '"""test_aligned_table"""', 'description': '"""Test aligned container"""', 'categories': "['test1', 'test2', 'test3']", 'category_tables': 'categories'}), "(name='test_aligned_table', description=\n 'Test aligned container', categories=['test1', 'test2', 'test3'],\n category_tables=categories)\n", (3526, 3668), False, 'from hdmf.common import DynamicTable, VectorData, get_manager, AlignedDynamicTable\n'), ((4840, 5001), 'hdmf.common.AlignedDynamicTable', 'AlignedDynamicTable', ([], {'name': '"""test_aligned_table"""', 'description': '"""Test aligned container"""', 'categories': "['test1', 'test2', 'test3']", 'category_tables': 'categories'}), "(name='test_aligned_table', description=\n 'Test aligned container', categories=['test1', 'test2', 'test3'],\n category_tables=categories)\n", (4859, 5001), False, 'from hdmf.common import DynamicTable, VectorData, get_manager, AlignedDynamicTable\n'), ((5264, 5320), 'hdmf.common.DynamicTable', 'DynamicTable', ([], {'name': 'val', 'description': "(val + ' description')"}), "(name=val, description=val + ' description')\n", (5276, 5320), False, 'from hdmf.common import DynamicTable, VectorData, get_manager, AlignedDynamicTable\n'), ((9141, 9258), 'hdmf.common.AlignedDynamicTable', 'AlignedDynamicTable', ([], {'name': '"""test_aligned_table"""', 'description': '"""Test aligned container"""', 'category_tables': 'categories'}), "(name='test_aligned_table', description=\n 'Test aligned container', category_tables=categories)\n", (9160, 9258), False, 'from hdmf.common import DynamicTable, VectorData, get_manager, AlignedDynamicTable\n'), ((10066, 10183), 'hdmf.common.AlignedDynamicTable', 'AlignedDynamicTable', ([], {'name': '"""test_aligned_table"""', 'description': '"""Test aligned container"""', 'category_tables': 'categories'}), "(name='test_aligned_table', description=\n 'Test aligned container', category_tables=categories)\n", (10085, 10183), False, 'from hdmf.common import DynamicTable, VectorData, get_manager, AlignedDynamicTable\n'), ((11063, 11180), 'hdmf.common.AlignedDynamicTable', 'AlignedDynamicTable', ([], {'name': '"""test_aligned_table"""', 'description': '"""Test aligned container"""', 'category_tables': 'categories'}), "(name='test_aligned_table', description=\n 'Test aligned container', category_tables=categories)\n", (11082, 11180), False, 'from hdmf.common import DynamicTable, VectorData, get_manager, AlignedDynamicTable\n'), ((26736, 26880), 'hdmf.common.AlignedDynamicTable', 'AlignedDynamicTable', ([], {'name': '"""nested_adt"""', 'description': '"""test nesting AlignedDynamicTable"""', 'columns': '[col1]', 'category_tables': '[adt_category]'}), "(name='nested_adt', description=\n 'test nesting AlignedDynamicTable', columns=[col1], category_tables=[\n adt_category])\n", (26755, 26880), False, 'from hdmf.common import DynamicTable, VectorData, get_manager, AlignedDynamicTable\n'), ((12325, 12362), 'pandas.testing.assert_frame_equal', 'assert_frame_equal', (['incon[n]', 'curr[n]'], {}), '(incon[n], curr[n])\n', (12343, 12362), False, 'from pandas.testing import assert_frame_equal\n'), ((16185, 16198), 'numpy.arange', 'np.arange', (['(10)'], {}), '(10)\n', (16194, 16198), True, 'import numpy as np\n'), ((18463, 18476), 'numpy.arange', 'np.arange', (['(10)'], {}), '(10)\n', (18472, 18476), True, 'import numpy as np\n'), ((12043, 12056), 'hdmf.common.get_manager', 'get_manager', ([], {}), '()\n', (12054, 12056), False, 'from hdmf.common import DynamicTable, VectorData, get_manager, AlignedDynamicTable\n'), ((12142, 12155), 'hdmf.common.get_manager', 'get_manager', ([], {}), '()\n', (12153, 12155), False, 'from hdmf.common import DynamicTable, VectorData, get_manager, AlignedDynamicTable\n'), ((16870, 16883), 'numpy.arange', 'np.arange', (['(10)'], {}), '(10)\n', (16879, 16883), True, 'import numpy as np\n'), ((17497, 17509), 'numpy.arange', 'np.arange', (['(8)'], {}), '(8)\n', (17506, 17509), True, 'import numpy as np\n'), ((22042, 22061), 'numpy.arange', 'np.arange', (['num_rows'], {}), '(num_rows)\n', (22051, 22061), True, 'import numpy as np\n'), ((22394, 22413), 'numpy.arange', 'np.arange', (['num_rows'], {}), '(num_rows)\n', (22403, 22413), True, 'import numpy as np\n'), ((7387, 7406), 'numpy.arange', 'np.arange', (['num_rows'], {}), '(num_rows)\n', (7396, 7406), True, 'import numpy as np\n'), ((16047, 16060), 'numpy.arange', 'np.arange', (['(10)'], {}), '(10)\n', (16056, 16060), True, 'import numpy as np\n'), ((16661, 16674), 'numpy.arange', 'np.arange', (['(10)'], {}), '(10)\n', (16670, 16674), True, 'import numpy as np\n'), ((17255, 17268), 'numpy.arange', 'np.arange', (['(10)'], {}), '(10)\n', (17264, 17268), True, 'import numpy as np\n'), ((19483, 19502), 'numpy.arange', 'np.arange', (['num_rows'], {}), '(num_rows)\n', (19492, 19502), True, 'import numpy as np\n'), ((23667, 23686), 'numpy.arange', 'np.arange', (['num_rows'], {}), '(num_rows)\n', (23676, 23686), True, 'import numpy as np\n'), ((2221, 2240), 'numpy.arange', 'np.arange', (['num_rows'], {}), '(num_rows)\n', (2230, 2240), True, 'import numpy as np\n'), ((4152, 4165), 'numpy.arange', 'np.arange', (['(10)'], {}), '(10)\n', (4161, 4165), True, 'import numpy as np\n'), ((4627, 4639), 'numpy.arange', 'np.arange', (['(8)'], {}), '(8)\n', (4636, 4639), True, 'import numpy as np\n'), ((6041, 6060), 'numpy.arange', 'np.arange', (['num_rows'], {}), '(num_rows)\n', (6050, 6060), True, 'import numpy as np\n'), ((6951, 6970), 'numpy.arange', 'np.arange', (['num_rows'], {}), '(num_rows)\n', (6960, 6970), True, 'import numpy as np\n'), ((8511, 8530), 'numpy.arange', 'np.arange', (['num_rows'], {}), '(num_rows)\n', (8520, 8530), True, 'import numpy as np\n'), ((8895, 8918), 'numpy.arange', 'np.arange', (['(num_rows + 1)'], {}), '(num_rows + 1)\n', (8904, 8918), True, 'import numpy as np\n'), ((9832, 9851), 'numpy.arange', 'np.arange', (['num_rows'], {}), '(num_rows)\n', (9841, 9851), True, 'import numpy as np\n'), ((10768, 10787), 'numpy.arange', 'np.arange', (['num_rows'], {}), '(num_rows)\n', (10777, 10787), True, 'import numpy as np\n'), ((11724, 11743), 'numpy.arange', 'np.arange', (['num_rows'], {}), '(num_rows)\n', (11733, 11743), True, 'import numpy as np\n'), ((12881, 12900), 'numpy.arange', 'np.arange', (['num_rows'], {}), '(num_rows)\n', (12890, 12900), True, 'import numpy as np\n'), ((13857, 13876), 'numpy.arange', 'np.arange', (['num_rows'], {}), '(num_rows)\n', (13866, 13876), True, 'import numpy as np\n'), ((15255, 15274), 'numpy.arange', 'np.arange', (['num_rows'], {}), '(num_rows)\n', (15264, 15274), True, 'import numpy as np\n'), ((18013, 18032), 'numpy.arange', 'np.arange', (['num_rows'], {}), '(num_rows)\n', (18022, 18032), True, 'import numpy as np\n'), ((19053, 19072), 'numpy.arange', 'np.arange', (['num_rows'], {}), '(num_rows)\n', (19062, 19072), True, 'import numpy as np\n'), ((21122, 21141), 'numpy.arange', 'np.arange', (['num_rows'], {}), '(num_rows)\n', (21131, 21141), True, 'import numpy as np\n'), ((21792, 21810), 'numpy.asarray', 'np.asarray', (['[5, 8]'], {}), '([5, 8])\n', (21802, 21810), True, 'import numpy as np\n'), ((21881, 21899), 'numpy.asarray', 'np.asarray', (['[5, 8]'], {}), '([5, 8])\n', (21891, 21899), True, 'import numpy as np\n'), ((23232, 23251), 'numpy.arange', 'np.arange', (['num_rows'], {}), '(num_rows)\n', (23241, 23251), True, 'import numpy as np\n'), ((3370, 3383), 'numpy.arange', 'np.arange', (['(10)'], {}), '(10)\n', (3379, 3383), True, 'import numpy as np\n'), ((14693, 14716), 'numpy.arange', 'np.arange', (['(num_rows - 2)'], {}), '(num_rows - 2)\n', (14702, 14716), True, 'import numpy as np\n'), ((20626, 20645), 'numpy.arange', 'np.arange', (['num_rows'], {}), '(num_rows)\n', (20635, 20645), True, 'import numpy as np\n')]
|
# importing necessary packages
import pandas as pd
import numpy as np
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix
from sklearn.externals import joblib
from sklearn.preprocessing import StandardScaler
import os
import argparse
# command line arguments
parser = argparse.ArgumentParser()
# argument for delta
parser.add_argument('--delta', type=int, default=0, help='Value of delta while computing mfcc features')
# argument for components
parser.add_argument('--components', type = int, default = 4, help = 'How much number of components')
# arguement for energy coefficient
parser.add_argument('--coefficient', type = str, default = 'Yes', help = 'Enter False to not take energy coefficients')
args = parser.parse_args()
# delta value
delta = args.delta
# Number of components
components = args.components
# Coefficient
if(args.coefficient == 'Yes'):
coefficient = True
else:
coefficient = False
print("Delta is: ", delta)
print("Number of components are: ", components)
print("Energy coefficients are included: ", coefficient)
# loading encoder and Scaler
if(coefficient == True):
file_scalar = ("./Scalar/delta_" + str(delta) + "_with_coefficients_" + ".pkl")
print(True)
else:
file_scalar = ("./Scalar/delta_" + str(delta) + "_without_coefficients_" + ".pkl")
file_encoder = ("./labelEncoder/delta_" + str(delta) + "" + ".pkl")
# Load scalar and label encoder objects
scaler = joblib.load(file_scalar)
lb = joblib.load(file_encoder)
# Load data file
timit_testdf = pd.read_hdf("./features_for_PER/timit_test_delta_" + str(delta) + ".hdf")
print("Test data loaded")
# encoding labels
timit_testdf['labels_lb'] = lb.transform(timit_testdf['labels'])
# Take features and label encoded labels
test = timit_testdf.copy()
test = test[['features', 'labels_lb', 'id']]
# Get unique phonemes
unique_labels = np.unique(test.labels_lb)
# print("unique labels are: ", unique_labels)
# Get test feature set
features_test = np.array(test['features'].tolist())
# Filter the co-efficients based on energy coefficients inclusion
if(coefficient == False):
if(delta == 0):
features_test = features_test[:,1:]
elif(delta == 1):
features_test = np.delete(features_test,[0, 13], axis = 1)
else:
features_test = np.delete(features_test, [0, 13, 26], axis = 1)
# print('features shape' + str(features_test.shape))
# Make predictions
for i in unique_labels:
if(coefficient == True):
directory = "./models_updated/delta_" + str(delta) + "_with_energy_coefficients" + "/" + str(components)
else:
directory = "./models_updated/delta_" + str(delta) + "_without_energy_coefficients" + "/" + str(components)
if not os.path.exists(directory):
os.makedirs(directory)
filename = directory + "/" + str(i) + ".pkl"
model = joblib.load(filename)
log_prob = model.score_samples(scaler.transform(features_test))
col_name = str(i)
test[col_name] = log_prob
# Get predictions by using argmax
result = test.copy()
result = result.drop(['features', 'labels_lb', 'id'], axis = 1)
# Make predictions
test['predict'] = (result.idxmax(axis = 1))
test['predict'] = test['predict'].astype(int)
# Make groundtruth and prediction files
final = test.copy()
final = final[['id', 'labels_lb', 'predict']]
# final.head()
final.id = final.id.astype(str)
final.id = "sent_" + (final.id)
# final.head()
uniqueid = np.unique(final.id)
# uniqueid
# File for storing ground truth labels
gt = open("./files_for_WER_computation/groundTruth/groundTruth.txt", "w")
# File for storing predicted labels
pred = open("./files_for_WER_computation/predicted/predict_delta_" + str(delta) + "_components_" + str(components) + "_coefficient_" + str(coefficient) + ".txt", "w")
for i in uniqueid:
# print("sentence id is: ", i)
df = final[final.id==i]
gt.write(str(i))
pred.write(str(i))
for j in df.index.values:
gt.write(" " + str(df.labels_lb[j]))
pred.write(" " + str(df.predict[j]))
gt.write("\n")
pred.write("\n")
gt.close()
pred.close()
|
[
"os.makedirs",
"argparse.ArgumentParser",
"os.path.exists",
"sklearn.externals.joblib.load",
"numpy.delete",
"numpy.unique"
] |
[((368, 393), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (391, 393), False, 'import argparse\n'), ((1522, 1546), 'sklearn.externals.joblib.load', 'joblib.load', (['file_scalar'], {}), '(file_scalar)\n', (1533, 1546), False, 'from sklearn.externals import joblib\n'), ((1552, 1577), 'sklearn.externals.joblib.load', 'joblib.load', (['file_encoder'], {}), '(file_encoder)\n', (1563, 1577), False, 'from sklearn.externals import joblib\n'), ((1949, 1974), 'numpy.unique', 'np.unique', (['test.labels_lb'], {}), '(test.labels_lb)\n', (1958, 1974), True, 'import numpy as np\n'), ((3509, 3528), 'numpy.unique', 'np.unique', (['final.id'], {}), '(final.id)\n', (3518, 3528), True, 'import numpy as np\n'), ((2922, 2943), 'sklearn.externals.joblib.load', 'joblib.load', (['filename'], {}), '(filename)\n', (2933, 2943), False, 'from sklearn.externals import joblib\n'), ((2802, 2827), 'os.path.exists', 'os.path.exists', (['directory'], {}), '(directory)\n', (2816, 2827), False, 'import os\n'), ((2837, 2859), 'os.makedirs', 'os.makedirs', (['directory'], {}), '(directory)\n', (2848, 2859), False, 'import os\n'), ((2301, 2342), 'numpy.delete', 'np.delete', (['features_test', '[0, 13]'], {'axis': '(1)'}), '(features_test, [0, 13], axis=1)\n', (2310, 2342), True, 'import numpy as np\n'), ((2378, 2423), 'numpy.delete', 'np.delete', (['features_test', '[0, 13, 26]'], {'axis': '(1)'}), '(features_test, [0, 13, 26], axis=1)\n', (2387, 2423), True, 'import numpy as np\n')]
|
import scipy as sp
import scipy.optimize
from . import legops
import tensorflow as tf
import numpy as np
import numpy.random as npr
from . import constructions
def fit_model_family(ts,xs,model_family,p_init,maxiter=100,use_tqdm_notebook=False):
'''
Fits a custom LEG model
Input:
- ts: list of timestamp-vectors: nsamp x [ragged]
- xs: list of observations: nsamp x [ragged] x n
- model_family: model family to fit
- p_init: -- initial conditions for the parameter vector of the model family
- [optional] maxiter -- max number of iters to use in BFGS
- [optional] use_tqdm_notebook -- whether to make an update bar with tqdm
Output: dictionary with lots of keys. See supplementary.pdf for details. Important keys are:
- message (result of optimization)
- params (a dictionary with keys for each parameter of a LEG model)
- nats (the negative log likelihood divided by the number of observations)
'''
# store initial values
N,R,B,Lambda=model_family.p2NRBL(p_init)
initial_params=dict(N=N.numpy(),R=R.numpy(),B=B.numpy(),Lambda=Lambda.numpy())
# process dedups
time_info=[constructions.dedup_ts(tf.convert_to_tensor(x,dtype=tf.float64)) for x in ts]
xs=[tf.convert_to_tensor(x,dtype=tf.float64) for x in xs]
n=xs[0].shape[1]
nobs = np.sum([np.prod(x.shape) for x in xs])
# functions for scipy.optimize
nats=[]
def func(p):
Ls=0
for x,(sub_ts,sub_idxs) in zip(xs,time_info):
Ls+= model_family.log_likelihood(sub_ts,x,sub_idxs,p)
loss=-Ls.numpy()/nobs
nats.append(loss)
return loss
def jac(p):
gs=0
for x,(sub_ts,sub_idxs) in zip(xs,time_info):
gs+= model_family.informant(sub_ts,x,sub_idxs,p)
return -gs/nobs
# get an initial loss
func(p_init)
# fit it
if use_tqdm_notebook:
import tqdm.notebook
with tqdm.notebook.tqdm() as t:
def callback(*args,**kwargs):
t.update(len(nats))
t.set_description(f"nats={nats[-1]:.2f}")
result=sp.optimize.minimize(func,p_init,jac=jac,options=dict(maxiter=maxiter),callback=callback)
else:
result=sp.optimize.minimize(func,p_init,jac=jac,options=dict(maxiter=maxiter))
# supplement loss dictionary with some stuff of interest
result['nats']=nats
# store initial params
result['initial_params']=initial_params
# store final params:
N,R,B,Lambda=model_family.p2NRBL(result['x'])
result['params']=dict(N=N.numpy(),R=R.numpy(),B=B.numpy(),Lambda=Lambda.numpy())
# we call the parameters "p" not "x"
result['p']=result['x']
del result['x']
# done
return result
def fit(ts,xs,ell=None,N=None,R=None,B=None,Lambda=None,maxiter=100,use_tqdm_notebook=False):
'''
fit the LEG model with rank ell
Input:
- ts: list of timestamp-vectors: nsamp x [ragged]
- xs: list of observations: nsamp x [ragged] x n
- ell: order of the LEG model to fit
- [optional] N,R,B,Lambda -- initial conditions
- [optional] maxiter -- max number of iters to use in BFGS
- [optional] use_tqdm_notebook -- whether to make an update bar with tqdm
Output: dictionary with lots of keys. See supplementary.pdf for details. Important keys are:
- message (result of optimization)
- params (a dictionary with keys for each parameter of a LEG model)
- nats (the negative log likelihood divided by the number of observations)
'''
mf =LEGFamily(ell,xs[0].shape[1])
p_init=mf.get_initial_guess(ts,xs,N=N,R=R,B=B,Lambda=Lambda)
return fit_model_family(ts,xs,mf,p_init,use_tqdm_notebook=use_tqdm_notebook)
r'''
_ _ __ _ _ _
_ __ ___ ___ __| | ___| | / _| __ _ _ __ ___ (_) (_) ___ ___
| '_ ` _ \ / _ \ / _` |/ _ \ | | |_ / _` | '_ ` _ \| | | |/ _ \/ __|
| | | | | | (_) | (_| | __/ | | _| (_| | | | | | | | | | __/\__ \
|_| |_| |_|\___/ \__,_|\___|_| |_| \__,_|_| |_| |_|_|_|_|\___||___/
'''
class LEGFamily:
def __init__(self,ell,n):
self.ell=ell
self.n=n
msk=np.tril(np.ones((self.ell,self.ell)))
self.N_idxs = tf.convert_to_tensor(np.c_[np.where(msk)])
msk=np.tril(np.ones((self.ell,self.ell)),k=-1)
self.R_idxs = tf.convert_to_tensor(np.c_[np.where(msk)])
msk=np.tril(np.ones((self.n,self.n)))
self.Lambda_idxs = tf.convert_to_tensor(np.c_[np.where(msk)])
self.psize = self.N_idxs.shape[0]+self.R_idxs.shape[0]+self.ell*self.n+self.Lambda_idxs.shape[0]
def p2NRBL(self,p):
i=0
# N!
sz=self.N_idxs.shape[0]
N=tf.scatter_nd(self.N_idxs,p[i:i+sz],(self.ell,self.ell))
i+=sz
# R!
sz=self.R_idxs.shape[0]
R=tf.scatter_nd(self.R_idxs,p[i:i+sz],(self.ell,self.ell))
i+=sz
# B!
sz=self.ell*self.n; B = tf.reshape(p[i:i+sz],(self.n,self.ell)); i+=sz
# Lambda!
sz=self.Lambda_idxs.shape[0]
Lambda=tf.scatter_nd(self.Lambda_idxs,p[i:i+sz],(self.n,self.n))
i+=sz
return N,R,B,Lambda
@tf.function(autograph=False)
def informant(self,ts,x,idxs,p):
'''
gradient of log likelihood w.r.t. p
'''
with tf.GradientTape() as g:
g.watch(p)
N,R,B,Lambda = self.p2NRBL(p)
nats = legops.leg_log_likelihood_tensorflow(ts,x,idxs,N,R,B,Lambda)
return g.gradient(nats,p)
@tf.function(autograph=False)
def log_likelihood(self,ts,x,idxs,p):
'''
log likelihood
'''
N,R,B,Lambda = self.p2NRBL(p)
return legops.leg_log_likelihood_tensorflow(ts,x,idxs,N,R,B,Lambda)
def get_initial_guess(self,ts,xs,N=None,R=None,B=None,Lambda=None):
# make up values when nothing is provided
if N is None:
N=np.eye(self.ell)
if R is None:
R=npr.randn(self.ell,self.ell)*.2
R=.5*(R-R.T)
if B is None:
B=np.ones((self.n,self.ell))
B=.5*B/np.sqrt(np.sum(B**2,axis=1,keepdims=True))
if Lambda is None:
Lambda = .1*np.eye(self.n)
# make 'em nice for us
N = tf.linalg.cholesky([email protected](N))
R = (R-tf.transpose(R))
Lambda = tf.linalg.cholesky([email protected](Lambda))
# put it all together
pN=tf.gather_nd(N,self.N_idxs)
pR=tf.gather_nd(R,self.R_idxs)
pB=tf.reshape(B,(self.n*self.ell,))
pL=tf.gather_nd(Lambda,self.Lambda_idxs)
return tf.concat([pN,pR,pB,pL],axis=0)
class CeleriteFamily(LEGFamily):
def __init__(self,nblocks,n):
self.nblocks=nblocks
self.ell=nblocks*2
self.n=n
msk=np.eye(self.ell,dtype=np.bool) + np.diag(np.tile([True,False],self.nblocks)[:-1],-1)
self.N_idxs = tf.convert_to_tensor(np.c_[np.where(msk)])
msk = np.diag(np.tile([True,False],self.nblocks)[:-1],-1)
self.R_idxs = tf.convert_to_tensor(np.c_[np.where(msk)])
msk=np.tril(np.ones((self.n,self.n)))
self.Lambda_idxs = tf.convert_to_tensor(np.c_[np.where(msk)])
self.psize = self.N_idxs.shape[0]+self.R_idxs.shape[0]+self.ell*self.n+self.Lambda_idxs.shape[0]
def get_initial_guess(self,ts,xs):
N=np.eye(self.ell)
R=npr.randn(self.ell,self.ell)*.2
B=np.ones((self.n,self.ell))
B=.5*B/np.sqrt(np.sum(B**2,axis=1,keepdims=True))
Lambda = .1*np.eye(self.n)
N = tf.linalg.cholesky([email protected](N))
R = (R-tf.transpose(R))
Lambda = tf.linalg.cholesky([email protected](Lambda))
# put it all together
pN=tf.gather_nd(N,self.N_idxs)
pR=tf.gather_nd(R,self.R_idxs)
pB=tf.reshape(B,(self.n*self.ell,))
pL=tf.gather_nd(Lambda,self.Lambda_idxs)
return tf.concat([pN,pR,pB,pL],axis=0)
|
[
"numpy.sum",
"numpy.random.randn",
"tensorflow.gather_nd",
"tensorflow.convert_to_tensor",
"tensorflow.reshape",
"tensorflow.concat",
"numpy.ones",
"tensorflow.transpose",
"numpy.where",
"tensorflow.GradientTape",
"numpy.tile",
"tensorflow.function",
"numpy.eye",
"tensorflow.scatter_nd",
"numpy.prod"
] |
[((5309, 5337), 'tensorflow.function', 'tf.function', ([], {'autograph': '(False)'}), '(autograph=False)\n', (5320, 5337), True, 'import tensorflow as tf\n'), ((5665, 5693), 'tensorflow.function', 'tf.function', ([], {'autograph': '(False)'}), '(autograph=False)\n', (5676, 5693), True, 'import tensorflow as tf\n'), ((1251, 1292), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['x'], {'dtype': 'tf.float64'}), '(x, dtype=tf.float64)\n', (1271, 1292), True, 'import tensorflow as tf\n'), ((4816, 4877), 'tensorflow.scatter_nd', 'tf.scatter_nd', (['self.N_idxs', 'p[i:i + sz]', '(self.ell, self.ell)'], {}), '(self.N_idxs, p[i:i + sz], (self.ell, self.ell))\n', (4829, 4877), True, 'import tensorflow as tf\n'), ((4951, 5012), 'tensorflow.scatter_nd', 'tf.scatter_nd', (['self.R_idxs', 'p[i:i + sz]', '(self.ell, self.ell)'], {}), '(self.R_idxs, p[i:i + sz], (self.ell, self.ell))\n', (4964, 5012), True, 'import tensorflow as tf\n'), ((5068, 5111), 'tensorflow.reshape', 'tf.reshape', (['p[i:i + sz]', '(self.n, self.ell)'], {}), '(p[i:i + sz], (self.n, self.ell))\n', (5078, 5111), True, 'import tensorflow as tf\n'), ((5194, 5256), 'tensorflow.scatter_nd', 'tf.scatter_nd', (['self.Lambda_idxs', 'p[i:i + sz]', '(self.n, self.n)'], {}), '(self.Lambda_idxs, p[i:i + sz], (self.n, self.n))\n', (5207, 5256), True, 'import tensorflow as tf\n'), ((6578, 6606), 'tensorflow.gather_nd', 'tf.gather_nd', (['N', 'self.N_idxs'], {}), '(N, self.N_idxs)\n', (6590, 6606), True, 'import tensorflow as tf\n'), ((6617, 6645), 'tensorflow.gather_nd', 'tf.gather_nd', (['R', 'self.R_idxs'], {}), '(R, self.R_idxs)\n', (6629, 6645), True, 'import tensorflow as tf\n'), ((6656, 6691), 'tensorflow.reshape', 'tf.reshape', (['B', '(self.n * self.ell,)'], {}), '(B, (self.n * self.ell,))\n', (6666, 6691), True, 'import tensorflow as tf\n'), ((6700, 6738), 'tensorflow.gather_nd', 'tf.gather_nd', (['Lambda', 'self.Lambda_idxs'], {}), '(Lambda, self.Lambda_idxs)\n', (6712, 6738), True, 'import tensorflow as tf\n'), ((6753, 6788), 'tensorflow.concat', 'tf.concat', (['[pN, pR, pB, pL]'], {'axis': '(0)'}), '([pN, pR, pB, pL], axis=0)\n', (6762, 6788), True, 'import tensorflow as tf\n'), ((7498, 7514), 'numpy.eye', 'np.eye', (['self.ell'], {}), '(self.ell)\n', (7504, 7514), True, 'import numpy as np\n'), ((7567, 7594), 'numpy.ones', 'np.ones', (['(self.n, self.ell)'], {}), '((self.n, self.ell))\n', (7574, 7594), True, 'import numpy as np\n'), ((7876, 7904), 'tensorflow.gather_nd', 'tf.gather_nd', (['N', 'self.N_idxs'], {}), '(N, self.N_idxs)\n', (7888, 7904), True, 'import tensorflow as tf\n'), ((7915, 7943), 'tensorflow.gather_nd', 'tf.gather_nd', (['R', 'self.R_idxs'], {}), '(R, self.R_idxs)\n', (7927, 7943), True, 'import tensorflow as tf\n'), ((7954, 7989), 'tensorflow.reshape', 'tf.reshape', (['B', '(self.n * self.ell,)'], {}), '(B, (self.n * self.ell,))\n', (7964, 7989), True, 'import tensorflow as tf\n'), ((7998, 8036), 'tensorflow.gather_nd', 'tf.gather_nd', (['Lambda', 'self.Lambda_idxs'], {}), '(Lambda, self.Lambda_idxs)\n', (8010, 8036), True, 'import tensorflow as tf\n'), ((8051, 8086), 'tensorflow.concat', 'tf.concat', (['[pN, pR, pB, pL]'], {'axis': '(0)'}), '([pN, pR, pB, pL], axis=0)\n', (8060, 8086), True, 'import tensorflow as tf\n'), ((1188, 1229), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['x'], {'dtype': 'tf.float64'}), '(x, dtype=tf.float64)\n', (1208, 1229), True, 'import tensorflow as tf\n'), ((1345, 1361), 'numpy.prod', 'np.prod', (['x.shape'], {}), '(x.shape)\n', (1352, 1361), True, 'import numpy as np\n'), ((4272, 4301), 'numpy.ones', 'np.ones', (['(self.ell, self.ell)'], {}), '((self.ell, self.ell))\n', (4279, 4301), True, 'import numpy as np\n'), ((4388, 4417), 'numpy.ones', 'np.ones', (['(self.ell, self.ell)'], {}), '((self.ell, self.ell))\n', (4395, 4417), True, 'import numpy as np\n'), ((4509, 4534), 'numpy.ones', 'np.ones', (['(self.n, self.n)'], {}), '((self.n, self.n))\n', (4516, 4534), True, 'import numpy as np\n'), ((5456, 5473), 'tensorflow.GradientTape', 'tf.GradientTape', ([], {}), '()\n', (5471, 5473), True, 'import tensorflow as tf\n'), ((6056, 6072), 'numpy.eye', 'np.eye', (['self.ell'], {}), '(self.ell)\n', (6062, 6072), True, 'import numpy as np\n'), ((6202, 6229), 'numpy.ones', 'np.ones', (['(self.n, self.ell)'], {}), '((self.n, self.ell))\n', (6209, 6229), True, 'import numpy as np\n'), ((6454, 6469), 'tensorflow.transpose', 'tf.transpose', (['R'], {}), '(R)\n', (6466, 6469), True, 'import tensorflow as tf\n'), ((6939, 6970), 'numpy.eye', 'np.eye', (['self.ell'], {'dtype': 'np.bool'}), '(self.ell, dtype=np.bool)\n', (6945, 6970), True, 'import numpy as np\n'), ((7242, 7267), 'numpy.ones', 'np.ones', (['(self.n, self.n)'], {}), '((self.n, self.n))\n', (7249, 7267), True, 'import numpy as np\n'), ((7525, 7554), 'numpy.random.randn', 'npr.randn', (['self.ell', 'self.ell'], {}), '(self.ell, self.ell)\n', (7534, 7554), True, 'import numpy.random as npr\n'), ((7672, 7686), 'numpy.eye', 'np.eye', (['self.n'], {}), '(self.n)\n', (7678, 7686), True, 'import numpy as np\n'), ((7752, 7767), 'tensorflow.transpose', 'tf.transpose', (['R'], {}), '(R)\n', (7764, 7767), True, 'import tensorflow as tf\n'), ((4351, 4364), 'numpy.where', 'np.where', (['msk'], {}), '(msk)\n', (4359, 4364), True, 'import numpy as np\n'), ((4472, 4485), 'numpy.where', 'np.where', (['msk'], {}), '(msk)\n', (4480, 4485), True, 'import numpy as np\n'), ((4589, 4602), 'numpy.where', 'np.where', (['msk'], {}), '(msk)\n', (4597, 4602), True, 'import numpy as np\n'), ((6109, 6138), 'numpy.random.randn', 'npr.randn', (['self.ell', 'self.ell'], {}), '(self.ell, self.ell)\n', (6118, 6138), True, 'import numpy.random as npr\n'), ((6342, 6356), 'numpy.eye', 'np.eye', (['self.n'], {}), '(self.n)\n', (6348, 6356), True, 'import numpy as np\n'), ((6422, 6437), 'tensorflow.transpose', 'tf.transpose', (['N'], {}), '(N)\n', (6434, 6437), True, 'import tensorflow as tf\n'), ((6514, 6534), 'tensorflow.transpose', 'tf.transpose', (['Lambda'], {}), '(Lambda)\n', (6526, 6534), True, 'import tensorflow as tf\n'), ((7073, 7086), 'numpy.where', 'np.where', (['msk'], {}), '(msk)\n', (7081, 7086), True, 'import numpy as np\n'), ((7112, 7148), 'numpy.tile', 'np.tile', (['[True, False]', 'self.nblocks'], {}), '([True, False], self.nblocks)\n', (7119, 7148), True, 'import numpy as np\n'), ((7205, 7218), 'numpy.where', 'np.where', (['msk'], {}), '(msk)\n', (7213, 7218), True, 'import numpy as np\n'), ((7322, 7335), 'numpy.where', 'np.where', (['msk'], {}), '(msk)\n', (7330, 7335), True, 'import numpy as np\n'), ((7617, 7654), 'numpy.sum', 'np.sum', (['(B ** 2)'], {'axis': '(1)', 'keepdims': '(True)'}), '(B ** 2, axis=1, keepdims=True)\n', (7623, 7654), True, 'import numpy as np\n'), ((7720, 7735), 'tensorflow.transpose', 'tf.transpose', (['N'], {}), '(N)\n', (7732, 7735), True, 'import tensorflow as tf\n'), ((7812, 7832), 'tensorflow.transpose', 'tf.transpose', (['Lambda'], {}), '(Lambda)\n', (7824, 7832), True, 'import tensorflow as tf\n'), ((6256, 6293), 'numpy.sum', 'np.sum', (['(B ** 2)'], {'axis': '(1)', 'keepdims': '(True)'}), '(B ** 2, axis=1, keepdims=True)\n', (6262, 6293), True, 'import numpy as np\n'), ((6980, 7016), 'numpy.tile', 'np.tile', (['[True, False]', 'self.nblocks'], {}), '([True, False], self.nblocks)\n', (6987, 7016), True, 'import numpy as np\n')]
|
# -*- coding:utf-8 -*-
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the MIT License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# MIT License for more details.
"""Encode and decode the model config. for JDD."""
from copy import deepcopy
import numpy as np
from vega.search_space.codec import Codec
from vega.core.common.class_factory import ClassType, ClassFactory
@ClassFactory.register(ClassType.CODEC)
class JDDCodec(Codec):
"""Codec of the JDD search space."""
def __init__(self, search_space=None, **kwargs):
"""Construct the SRCodec class.
:param codec_name: name of the codec
:type codec_name: str
:param search_space: Search space of the codec
:type search_space: dictionary
"S_" means that the shrink RDB blcock with 1x1 convolution .
"G_" means that the RDB block with channel shuffle and group convolution.
"C_" means that the contextual RDB block with recursive layer.
first number: the number of convolutional layers in a block
second number: the growth rate of dense connected in a block
third number: the number of output channel in a block
"""
super(JDDCodec, self).__init__(search_space, **kwargs)
self.func_type, self.func_prob = self.get_choices()
self.func_type_num = len(self.func_type)
def get_choices(self):
"""Get search space information.
:return: the configs of the blocks
:rtype: lists
"""
channel_types = ['16', '32', '48']
channel_prob = [1, 0.5, 0.2]
block_types = ['R']
block_prob = [1]
model_type = self.search_space['modules'][0]
channel_types = self.search_space[model_type]['channel_types']
channel_prob = self.search_space[model_type]['channel_prob']
block_types = self.search_space[model_type]['block_types']
block_prob = self.search_space[model_type]['block_prob']
func_type = []
func_prob = []
for b_id in range(len(block_types)):
for chin_id in range(len(channel_types)):
for chout_id in range(len(channel_types)):
func_type.append(block_types[b_id] + '_' + channel_types[chin_id] + '_' + channel_types[chout_id])
func_prob.append(block_prob[b_id] * channel_prob[chin_id] * channel_prob[chout_id])
func_prob = np.cumsum(np.asarray(func_prob) / sum(func_prob))
return func_type, func_prob
def decode(self, indiv):
"""Add the network structure to config.
:param indiv: an individual which contains network architecture code
:type indiv: individual class
:return: config of model structure
:rtype: dictionary
"""
indiv_cfg = deepcopy(self.search_space)
model = indiv_cfg['modules'][0]
indiv_cfg[model]['code'] = indiv.gene.tolist()
indiv_cfg[model]['architecture'] = indiv.active_net_list()
return indiv_cfg
|
[
"vega.core.common.class_factory.ClassFactory.register",
"copy.deepcopy",
"numpy.asarray"
] |
[((646, 684), 'vega.core.common.class_factory.ClassFactory.register', 'ClassFactory.register', (['ClassType.CODEC'], {}), '(ClassType.CODEC)\n', (667, 684), False, 'from vega.core.common.class_factory import ClassType, ClassFactory\n'), ((3053, 3080), 'copy.deepcopy', 'deepcopy', (['self.search_space'], {}), '(self.search_space)\n', (3061, 3080), False, 'from copy import deepcopy\n'), ((2681, 2702), 'numpy.asarray', 'np.asarray', (['func_prob'], {}), '(func_prob)\n', (2691, 2702), True, 'import numpy as np\n')]
|
from __future__ import absolute_import, division, print_function
import torch
import warnings
from tqdm import tqdm
import pathlib
from scipy import linalg
import tensorflow as tf
import numpy as np
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
def check_or_download_inception(inception_path):
''' Checks if the path to the inception file is valid, or downloads
the file if it is not present. '''
INCEPTION_URL = 'http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz'
if inception_path is None:
inception_path = '/tmp'
inception_path = pathlib.Path(inception_path)
model_file = inception_path / 'classify_image_graph_def.pb'
if not model_file.exists():
print("Downloading Inception model")
from urllib import request
import tarfile
fn, _ = request.urlretrieve(INCEPTION_URL)
with tarfile.open(fn, mode='r') as f:
f.extract('classify_image_graph_def.pb', str(model_file.parent))
return str(model_file)
def create_inception_graph(pth):
"""Creates a graph from saved GraphDef file."""
# Creates graph from saved graph_def.pb.
with tf.io.gfile.GFile(pth, 'rb') as f:
graph_def = tf.compat.v1.GraphDef()
graph_def.ParseFromString(f.read())
_ = tf.import_graph_def(graph_def, name='FID_Inception_Net')
def calculate_activation_statistics(images,
sess,
batch_size=50,
verbose=False):
"""Calculation of the statistics used by the FID.
Params:
-- images : Numpy array of dimension (n_images, hi, wi, 3). The values
must lie between 0 and 255.
-- sess : current session
-- batch_size : the images numpy array is split into batches with batch size
batch_size. A reasonable batch size depends on the available hardware.
-- verbose : If set to True and parameter out_step is given, the number of calculated
batches is reported.
Returns:
-- mu : The mean over samples of the activations of the pool_3 layer of
the incption model.
-- sigma : The covariance matrix of the activations of the pool_3 layer of
the incption model.
"""
act = get_activations(images, sess, batch_size, verbose)
mu = np.mean(act, axis=0)
sigma = np.cov(act, rowvar=False)
return mu, sigma
# code for handling inception net derived from
# https://github.com/openai/improved-gan/blob/master/inception_score/model.py
def _get_inception_layer(sess):
"""Prepares inception net for batched usage and returns pool_3 layer. """
layername = 'FID_Inception_Net/pool_3:0'
pool3 = sess.graph.get_tensor_by_name(layername)
ops = pool3.graph.get_operations()
for op_idx, op in enumerate(ops):
for o in op.outputs:
shape = o.get_shape()
if shape._dims != []:
shape = [s.value for s in shape]
new_shape = []
for j, s in enumerate(shape):
if s == 1 and j == 0:
new_shape.append(None)
else:
new_shape.append(s)
o.__dict__['_shape_val'] = tf.TensorShape(new_shape)
return pool3
# -------------------------------------------------------------------------------
def get_activations(images, sess, batch_size=200, verbose=False):
"""Calculates the activations of the pool_3 layer for all images.
Params:
-- images : Numpy array of dimension (n_images, hi, wi, 3). The values
must lie between 0 and 256.
-- sess : current session
-- batch_size : the images numpy array is split into batches with batch size
batch_size. A reasonable batch size depends on the disposable hardware.
-- verbose : If set to True and parameter out_step is given, the number of calculated
batches is reported.
Returns:
-- A numpy array of dimension (num images, 2048) that contains the
activations of the given tensor when feeding inception with the query tensor.
"""
inception_layer = _get_inception_layer(sess)
n_images = images.shape[0]
if batch_size > n_images:
print(
"warning: batch size is bigger than the data size. setting batch size to data size"
)
batch_size = n_images
n_batches = n_images // batch_size
pred_arr = np.empty((n_images, 2048))
for i in tqdm(range(n_batches)):
if verbose:
print("\rPropagating batch %d/%d" % (i + 1, n_batches),
end="",
flush=True)
start = i * batch_size
if start + batch_size < n_images:
end = start + batch_size
else:
end = n_images
batch = images[start:end]
pred = sess.run(inception_layer,
{'FID_Inception_Net/ExpandDims:0': batch})
pred_arr[start:end] = pred.reshape(batch_size, -1)
if verbose:
print(" done")
return pred_arr
# -------------------------------------------------------------------------------
def calculate_frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6):
"""Numpy implementation of the Frechet Distance.
The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1)
and X_2 ~ N(mu_2, C_2) is
d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)).
Stable version by <NAME>.
Params:
-- mu1 : Numpy array containing the activations of the pool_3 layer of the
inception net ( like returned by the function 'get_predictions')
for generated samples.
-- mu2 : The sample mean over activations of the pool_3 layer, precalcualted
on an representive data set.
-- sigma1: The covariance matrix over activations of the pool_3 layer for
generated samples.
-- sigma2: The covariance matrix over activations of the pool_3 layer,
precalcualted on an representive data set.
Returns:
-- : The Frechet Distance.
"""
mu1 = np.atleast_1d(mu1)
mu2 = np.atleast_1d(mu2)
sigma1 = np.atleast_2d(sigma1)
sigma2 = np.atleast_2d(sigma2)
assert mu1.shape == mu2.shape, "Training and test mean vectors have different lengths"
assert sigma1.shape == sigma2.shape, "Training and test covariances have different dimensions"
diff = mu1 - mu2
# product might be almost singular
covmean, _ = linalg.sqrtm(sigma1.dot(sigma2), disp=False)
if not np.isfinite(covmean).all():
msg = "fid calculation produces singular product; adding %s to diagonal of cov estimates" % eps
warnings.warn(msg)
offset = np.eye(sigma1.shape[0]) * eps
covmean = linalg.sqrtm((sigma1 + offset).dot(sigma2 + offset))
# numerical error might give slight imaginary component
if np.iscomplexobj(covmean):
if not np.allclose(np.diagonal(covmean).imag, 0, atol=1e-3):
m = np.max(np.abs(covmean.imag))
raise ValueError("Imaginary component {}".format(m))
covmean = covmean.real
tr_covmean = np.trace(covmean)
return diff.dot(diff) + np.trace(sigma1) + np.trace(
sigma2) - 2 * tr_covmean
def pt_to_np(imgs):
'''normalizes pytorch image in [-1, 1] to [0, 255]'''
normalized = [((img / 2 + 0.5) * 255).clamp(0, 255) for img in imgs]
return np.array([img.permute(1, 2, 0).numpy() for img in normalized])
def compute_fid_given_images(fake_images, real_images):
'''requires that the image batches are numpy format, normalized to 0, 255'''
inception_path = check_or_download_inception(None)
create_inception_graph(inception_path)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
if isinstance(fake_images, tuple):
m1, s1 = fake_images
else:
m1, s1 = calculate_activation_statistics(fake_images, sess)
if isinstance(real_images, tuple):
m2, s2 = real_images
else:
m2, s2 = calculate_activation_statistics(real_images, sess)
return calculate_frechet_distance(m1, s1, m2, s2)
def compute_fid_given_path(path):
with np.load(path) as data:
fake_imgs = data['fake']
real_imgs = data['real']
return compute_fid_given_images(fake_imgs, real_imgs)
def load_from_path(source):
root = '/data/vision/torralba/ganprojects/placesgan/tracer/utils/fid_stats/'
path = os.path.join(root, f'{source}_stats.npz')
if os.path.exists(path):
print('Loading statistics from ', path)
with np.load(path) as data:
return data['m'], data['s']
else:
print("Stats not found in path", path)
exit()
def compute_fid(source1, source2):
if isinstance(source1, str):
source1 = load_from_path(source1)
if isinstance(source1, torch.Tensor):
source1 = pt_to_np(source1)
if isinstance(source2, str):
source2 = load_from_path(source2)
if isinstance(source2, torch.Tensor):
source2 = pt_to_np(source2)
return compute_fid_given_images(source1, source2)
if __name__ == '__main__':
import argparse
from PIL import Image
from torchvision import transforms
parser = argparse.ArgumentParser()
parser.add_argument('--source')
parser.add_argument('--target')
args = parser.parse_args()
transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
])
images1 = []
for file_name in tqdm(os.listdir(args.source)):
if file_name.lower().endswith(('.png', 'jpeg', '.jpg')):
path = os.path.join(args.source, file_name)
images1.append(transform(Image.open(path).convert('RGB')))
images1 = torch.stack(images1)
images2 = []
for file_name in tqdm(os.listdir(args.source)):
if file_name.lower().endswith(('.png', 'jpeg', '.jpg')):
path = os.path.join(args.source, file_name)
images2.append(transform(Image.open(path).convert('RGB')))
images2 = torch.stack(images2)
result = compute_fid(images1, images2)
print(result)
with open('fid_results.txt', 'a+') as f:
f.write(args.source + args.target + ':\n')
f.write(str(result) + '\n')
|
[
"numpy.trace",
"numpy.load",
"numpy.abs",
"argparse.ArgumentParser",
"numpy.empty",
"pathlib.Path",
"numpy.mean",
"torchvision.transforms.Normalize",
"os.path.join",
"numpy.atleast_2d",
"numpy.eye",
"os.path.exists",
"tensorflow.TensorShape",
"numpy.isfinite",
"torchvision.transforms.ToTensor",
"tarfile.open",
"tensorflow.compat.v1.GraphDef",
"numpy.cov",
"numpy.diagonal",
"tensorflow.global_variables_initializer",
"tensorflow.Session",
"urllib.request.urlretrieve",
"tensorflow.import_graph_def",
"os.listdir",
"torchvision.transforms.Resize",
"numpy.iscomplexobj",
"torch.stack",
"PIL.Image.open",
"warnings.warn",
"numpy.atleast_1d",
"tensorflow.io.gfile.GFile"
] |
[((600, 628), 'pathlib.Path', 'pathlib.Path', (['inception_path'], {}), '(inception_path)\n', (612, 628), False, 'import pathlib\n'), ((2414, 2434), 'numpy.mean', 'np.mean', (['act'], {'axis': '(0)'}), '(act, axis=0)\n', (2421, 2434), True, 'import numpy as np\n'), ((2447, 2472), 'numpy.cov', 'np.cov', (['act'], {'rowvar': '(False)'}), '(act, rowvar=False)\n', (2453, 2472), True, 'import numpy as np\n'), ((4578, 4604), 'numpy.empty', 'np.empty', (['(n_images, 2048)'], {}), '((n_images, 2048))\n', (4586, 4604), True, 'import numpy as np\n'), ((6259, 6277), 'numpy.atleast_1d', 'np.atleast_1d', (['mu1'], {}), '(mu1)\n', (6272, 6277), True, 'import numpy as np\n'), ((6288, 6306), 'numpy.atleast_1d', 'np.atleast_1d', (['mu2'], {}), '(mu2)\n', (6301, 6306), True, 'import numpy as np\n'), ((6321, 6342), 'numpy.atleast_2d', 'np.atleast_2d', (['sigma1'], {}), '(sigma1)\n', (6334, 6342), True, 'import numpy as np\n'), ((6356, 6377), 'numpy.atleast_2d', 'np.atleast_2d', (['sigma2'], {}), '(sigma2)\n', (6369, 6377), True, 'import numpy as np\n'), ((7049, 7073), 'numpy.iscomplexobj', 'np.iscomplexobj', (['covmean'], {}), '(covmean)\n', (7064, 7073), True, 'import numpy as np\n'), ((7303, 7320), 'numpy.trace', 'np.trace', (['covmean'], {}), '(covmean)\n', (7311, 7320), True, 'import numpy as np\n'), ((8651, 8692), 'os.path.join', 'os.path.join', (['root', 'f"""{source}_stats.npz"""'], {}), "(root, f'{source}_stats.npz')\n", (8663, 8692), False, 'import os\n'), ((8700, 8720), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (8714, 8720), False, 'import os\n'), ((9447, 9472), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (9470, 9472), False, 'import argparse\n'), ((10031, 10051), 'torch.stack', 'torch.stack', (['images1'], {}), '(images1)\n', (10042, 10051), False, 'import torch\n'), ((10328, 10348), 'torch.stack', 'torch.stack', (['images2'], {}), '(images2)\n', (10339, 10348), False, 'import torch\n'), ((844, 878), 'urllib.request.urlretrieve', 'request.urlretrieve', (['INCEPTION_URL'], {}), '(INCEPTION_URL)\n', (863, 878), False, 'from urllib import request\n'), ((1170, 1198), 'tensorflow.io.gfile.GFile', 'tf.io.gfile.GFile', (['pth', '"""rb"""'], {}), "(pth, 'rb')\n", (1187, 1198), True, 'import tensorflow as tf\n'), ((1225, 1248), 'tensorflow.compat.v1.GraphDef', 'tf.compat.v1.GraphDef', ([], {}), '()\n', (1246, 1248), True, 'import tensorflow as tf\n'), ((1305, 1361), 'tensorflow.import_graph_def', 'tf.import_graph_def', (['graph_def'], {'name': '"""FID_Inception_Net"""'}), "(graph_def, name='FID_Inception_Net')\n", (1324, 1361), True, 'import tensorflow as tf\n'), ((6844, 6862), 'warnings.warn', 'warnings.warn', (['msg'], {}), '(msg)\n', (6857, 6862), False, 'import warnings\n'), ((7885, 7897), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (7895, 7897), True, 'import tensorflow as tf\n'), ((8382, 8395), 'numpy.load', 'np.load', (['path'], {}), '(path)\n', (8389, 8395), True, 'import numpy as np\n'), ((9799, 9822), 'os.listdir', 'os.listdir', (['args.source'], {}), '(args.source)\n', (9809, 9822), False, 'import os\n'), ((10096, 10119), 'os.listdir', 'os.listdir', (['args.source'], {}), '(args.source)\n', (10106, 10119), False, 'import os\n'), ((892, 918), 'tarfile.open', 'tarfile.open', (['fn'], {'mode': '"""r"""'}), "(fn, mode='r')\n", (904, 918), False, 'import tarfile\n'), ((6880, 6903), 'numpy.eye', 'np.eye', (['sigma1.shape[0]'], {}), '(sigma1.shape[0])\n', (6886, 6903), True, 'import numpy as np\n'), ((7369, 7385), 'numpy.trace', 'np.trace', (['sigma2'], {}), '(sigma2)\n', (7377, 7385), True, 'import numpy as np\n'), ((7924, 7957), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (7955, 7957), True, 'import tensorflow as tf\n'), ((8783, 8796), 'numpy.load', 'np.load', (['path'], {}), '(path)\n', (8790, 8796), True, 'import numpy as np\n'), ((9622, 9651), 'torchvision.transforms.Resize', 'transforms.Resize', (['(224, 224)'], {}), '((224, 224))\n', (9639, 9651), False, 'from torchvision import transforms\n'), ((9661, 9682), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (9680, 9682), False, 'from torchvision import transforms\n'), ((9692, 9746), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['(0.5, 0.5, 0.5)', '(0.5, 0.5, 0.5)'], {}), '((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n', (9712, 9746), False, 'from torchvision import transforms\n'), ((9909, 9945), 'os.path.join', 'os.path.join', (['args.source', 'file_name'], {}), '(args.source, file_name)\n', (9921, 9945), False, 'import os\n'), ((10206, 10242), 'os.path.join', 'os.path.join', (['args.source', 'file_name'], {}), '(args.source, file_name)\n', (10218, 10242), False, 'import os\n'), ((3333, 3358), 'tensorflow.TensorShape', 'tf.TensorShape', (['new_shape'], {}), '(new_shape)\n', (3347, 3358), True, 'import tensorflow as tf\n'), ((6704, 6724), 'numpy.isfinite', 'np.isfinite', (['covmean'], {}), '(covmean)\n', (6715, 6724), True, 'import numpy as np\n'), ((7167, 7187), 'numpy.abs', 'np.abs', (['covmean.imag'], {}), '(covmean.imag)\n', (7173, 7187), True, 'import numpy as np\n'), ((7350, 7366), 'numpy.trace', 'np.trace', (['sigma1'], {}), '(sigma1)\n', (7358, 7366), True, 'import numpy as np\n'), ((7102, 7122), 'numpy.diagonal', 'np.diagonal', (['covmean'], {}), '(covmean)\n', (7113, 7122), True, 'import numpy as np\n'), ((9983, 9999), 'PIL.Image.open', 'Image.open', (['path'], {}), '(path)\n', (9993, 9999), False, 'from PIL import Image\n'), ((10280, 10296), 'PIL.Image.open', 'Image.open', (['path'], {}), '(path)\n', (10290, 10296), False, 'from PIL import Image\n')]
|
import ast
import json
import pickle
import ujson
import collections
import numpy as np
from chord_labels import parse_chord
from progressbar import ProgressBar, Bar, Percentage, AdaptiveETA, Counter
print("Opening files")
with open('dataset_chords.json', 'r') as values:
formatted_chords = ujson.load(values)
with open('dataset_chroma.pickle', 'rb') as chroma:
formatted_chroma = pickle.load(chroma)
print("Files Opened\n")
blank = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
blank12 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
values = collections.OrderedDict()
cleaned_chroma = []
cleaned_chords = []
final_chroma = {}
final_chords = {}
key_binary_pairs = {}
def slice_vals(chroma_vals, chord_vals, slice_size):
num_slices = int(len(chroma_vals)/slice_size)
sliced_chroma = []
sliced_chords = []
for i in range(num_slices):
sliced_chroma.append(chroma_vals[i*slice_size:(i+1)*100])
sliced_chords.append(chord_vals[i*100:(i+1)*100])
remaining_chroma = chroma_vals[num_slices*100:]
remaining_chords = chord_vals[num_slices*100:]
for i in range(100-len(remaining_chroma)):
remaining_chroma.append(blank)
remaining_chords.append(blank12)
if len(remaining_chroma) > 0:
sliced_chroma.append(remaining_chroma)
sliced_chords.append(remaining_chords)
del remaining_chords
del remaining_chroma
return sliced_chroma, sliced_chords
with open('file_ids.txt', 'r') as idList:
print("--CLEANING FILES: 890 TODO--\n")
progress_bar = ProgressBar(widgets=['PROCESSED: ', Counter(), '/890 ', Bar('>'), Percentage(), ' --- ', AdaptiveETA()], maxval=891)
progress_bar.start()
for i, id in enumerate(idList):
progress_bar.update(value=i)
id = int(id.strip('\n'))
chord_iter = iter(formatted_chords[str(id)].keys())
curr_chord = next(chord_iter)
curr_chord_tuple = ast.literal_eval(curr_chord)
in_chord = False
cleaned_chroma = []
cleaned_chords = []
chord_nums = 0
for i, time in enumerate(formatted_chroma[id].keys()):
if curr_chord_tuple[0] <= time <= curr_chord_tuple[1] and formatted_chords[str(id)][curr_chord] != 'X':
curr_chord_binary = parse_chord(formatted_chords[str(id)][curr_chord]).tones_binary
print(curr_chord_binary)
cleaned_chords.append(curr_chord_binary)
cleaned_chroma.append(formatted_chroma[id][time])
key_binary_pairs[tuple(curr_chord_binary)] = formatted_chords[str(id)][curr_chord]
chord_nums += 1
in_chord = True
elif in_chord:
try:
in_chord = False
cleaned_chords.append(blank12)
cleaned_chroma.append(formatted_chroma[id][time])
curr_chord = next(chord_iter)
curr_chord_tuple = ast.literal_eval(curr_chord)
except StopIteration:
pass
else:
cleaned_chords.append(blank12)
cleaned_chroma.append(formatted_chroma[id][time])
if time > curr_chord_tuple[1]:
try:
in_chord = False
cleaned_chords.append(blank12)
cleaned_chroma.append(formatted_chroma[id][time])
curr_chord = next(chord_iter)
curr_chord_tuple = ast.literal_eval(curr_chord)
except StopIteration:
pass
sliced = slice_vals(cleaned_chroma, cleaned_chords, 100)
final_chroma[int(id)] = sliced[0]
final_chords[int(id)] = sliced[1]
del sliced
key_binary_pairs[tuple(blank12)] = 'None'
print('\n')
print("<------------------------------------------------------->")
print("<------------------COUNTING KEYS------------------------>")
print("<------------------------------------------------------->")
hold_x = []
hold_y = []
print(len(final_chroma[12]))
with open("file_ids_subset.txt", 'r') as idFile:
for id in idFile:
id = int(id.strip('\n'))
for thing1 in final_chroma[id]:
hold_x.append(thing1)
for thing2 in final_chords[id]:
hold_y.append(thing2)
# samples x 100 x 24
print(hold_x[0][99][23])
cleaned_x = np.array(hold_x)
cleaned_y = np.array(hold_y)
# format in [file id][chroma (0) or chord (1)][slice num to look at (per 100)][index within slice]
print(cleaned_x.shape)
print(cleaned_y.shape)
print("NUM OBJECTS: " + str(len(final_chords)))
# with open("cleaned_chroma.pickle", 'wb') as file:
# dill.dump(cleaned_chroma, file, protocol=pickle.HIGHEST_PROTOCOL)
# del cleaned_chroma
#
# with open("cleaned_chords.pickle", 'wb') as file:
# dill.dump(cleaned_chords, file, protocol=pickle.HIGHEST_PROTOCOL)
# del cleaned_chords
print("saving chroma")
with open("cleaned_x.json", 'w') as file:
ujson.dump(hold_x, file)
print("saving chords")
with open("cleaned_y.json", 'w') as file:
ujson.dump(hold_y, file)
print("saving pairs")
with open("key_binary_pairs.json", 'w') as file:
ujson.dump(key_binary_pairs, file)
print("DONE SAVING")
|
[
"ast.literal_eval",
"progressbar.Counter",
"ujson.dump",
"ujson.load",
"progressbar.Bar",
"progressbar.Percentage",
"progressbar.AdaptiveETA",
"pickle.load",
"numpy.array",
"collections.OrderedDict"
] |
[((576, 601), 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), '()\n', (599, 601), False, 'import collections\n'), ((4438, 4454), 'numpy.array', 'np.array', (['hold_x'], {}), '(hold_x)\n', (4446, 4454), True, 'import numpy as np\n'), ((4467, 4483), 'numpy.array', 'np.array', (['hold_y'], {}), '(hold_y)\n', (4475, 4483), True, 'import numpy as np\n'), ((297, 315), 'ujson.load', 'ujson.load', (['values'], {}), '(values)\n', (307, 315), False, 'import ujson\n'), ((392, 411), 'pickle.load', 'pickle.load', (['chroma'], {}), '(chroma)\n', (403, 411), False, 'import pickle\n'), ((5051, 5075), 'ujson.dump', 'ujson.dump', (['hold_x', 'file'], {}), '(hold_x, file)\n', (5061, 5075), False, 'import ujson\n'), ((5147, 5171), 'ujson.dump', 'ujson.dump', (['hold_y', 'file'], {}), '(hold_y, file)\n', (5157, 5171), False, 'import ujson\n'), ((5249, 5283), 'ujson.dump', 'ujson.dump', (['key_binary_pairs', 'file'], {}), '(key_binary_pairs, file)\n', (5259, 5283), False, 'import ujson\n'), ((1944, 1972), 'ast.literal_eval', 'ast.literal_eval', (['curr_chord'], {}), '(curr_chord)\n', (1960, 1972), False, 'import ast\n'), ((1604, 1613), 'progressbar.Counter', 'Counter', ([], {}), '()\n', (1611, 1613), False, 'from progressbar import ProgressBar, Bar, Percentage, AdaptiveETA, Counter\n'), ((1626, 1634), 'progressbar.Bar', 'Bar', (['""">"""'], {}), "('>')\n", (1629, 1634), False, 'from progressbar import ProgressBar, Bar, Percentage, AdaptiveETA, Counter\n'), ((1636, 1648), 'progressbar.Percentage', 'Percentage', ([], {}), '()\n', (1646, 1648), False, 'from progressbar import ProgressBar, Bar, Percentage, AdaptiveETA, Counter\n'), ((1659, 1672), 'progressbar.AdaptiveETA', 'AdaptiveETA', ([], {}), '()\n', (1670, 1672), False, 'from progressbar import ProgressBar, Bar, Percentage, AdaptiveETA, Counter\n'), ((2980, 3008), 'ast.literal_eval', 'ast.literal_eval', (['curr_chord'], {}), '(curr_chord)\n', (2996, 3008), False, 'import ast\n'), ((3542, 3570), 'ast.literal_eval', 'ast.literal_eval', (['curr_chord'], {}), '(curr_chord)\n', (3558, 3570), False, 'import ast\n')]
|
# -*- coding: utf-8 -*-
from layers.dynamic_rnn import DynamicLSTM
from layers.shap import Distribution_SHAP, Map_SHAP
import torch
import torch.nn as nn
import numpy as np
class SHAP_LSTM(nn.Module):
def __init__(self, embedding_matrix, opt):
super(SHAP_LSTM, self).__init__()
self.opt = opt
self.embed_dim = embedding_matrix.shape[-1]
self.embed = nn.Embedding.from_pretrained(torch.tensor(embedding_matrix, dtype=torch.float))
self.lstm = DynamicLSTM(opt.embed_dim, opt.hidden_dim, num_layers=1, batch_first=True)
self.shap = Distribution_SHAP(self.opt.max_seq_len, self.opt.polarities_dim, opt)
self.map_shap = Map_SHAP(opt.embed_dim, opt.max_seq_len, opt)
self.dense = nn.Linear(opt.hidden_dim, opt.polarities_dim)
def forward(self, inputs, label, weights, update=True):
text_raw_indices, aspect_indices = inputs[0], inputs[1]
x = self.embed(text_raw_indices)
x_len = torch.sum(text_raw_indices != 0, dim=-1)
aspect_idx = torch.tensor(torch.eq(text_raw_indices, aspect_indices[:, 0].reshape((-1, 1))),
dtype=torch.float)
aspect_pos_idx = [np.where(aspect_idx[i, :] == 1)[0] for i in range(len(aspect_idx))]
if update:
H_N, (h_n, _) = self.lstm(x, x_len)
weights = self.shap(text_raw_indices, aspect_indices, label, H_N, weights, self.dense)
out = self.dense(h_n[0])
return out, weights
else:
if len(weights) != 0:
x = self.map_shap(x, aspect_pos_idx, weights)
else:
pass
_, (h_n, _) = self.lstm(x.to(self.opt.device), x_len)
out = self.dense(h_n[0])
return out
|
[
"layers.shap.Distribution_SHAP",
"torch.sum",
"layers.dynamic_rnn.DynamicLSTM",
"numpy.where",
"torch.nn.Linear",
"layers.shap.Map_SHAP",
"torch.tensor"
] |
[((489, 563), 'layers.dynamic_rnn.DynamicLSTM', 'DynamicLSTM', (['opt.embed_dim', 'opt.hidden_dim'], {'num_layers': '(1)', 'batch_first': '(True)'}), '(opt.embed_dim, opt.hidden_dim, num_layers=1, batch_first=True)\n', (500, 563), False, 'from layers.dynamic_rnn import DynamicLSTM\n'), ((584, 653), 'layers.shap.Distribution_SHAP', 'Distribution_SHAP', (['self.opt.max_seq_len', 'self.opt.polarities_dim', 'opt'], {}), '(self.opt.max_seq_len, self.opt.polarities_dim, opt)\n', (601, 653), False, 'from layers.shap import Distribution_SHAP, Map_SHAP\n'), ((678, 723), 'layers.shap.Map_SHAP', 'Map_SHAP', (['opt.embed_dim', 'opt.max_seq_len', 'opt'], {}), '(opt.embed_dim, opt.max_seq_len, opt)\n', (686, 723), False, 'from layers.shap import Distribution_SHAP, Map_SHAP\n'), ((745, 790), 'torch.nn.Linear', 'nn.Linear', (['opt.hidden_dim', 'opt.polarities_dim'], {}), '(opt.hidden_dim, opt.polarities_dim)\n', (754, 790), True, 'import torch.nn as nn\n'), ((975, 1015), 'torch.sum', 'torch.sum', (['(text_raw_indices != 0)'], {'dim': '(-1)'}), '(text_raw_indices != 0, dim=-1)\n', (984, 1015), False, 'import torch\n'), ((418, 467), 'torch.tensor', 'torch.tensor', (['embedding_matrix'], {'dtype': 'torch.float'}), '(embedding_matrix, dtype=torch.float)\n', (430, 467), False, 'import torch\n'), ((1196, 1227), 'numpy.where', 'np.where', (['(aspect_idx[i, :] == 1)'], {}), '(aspect_idx[i, :] == 1)\n', (1204, 1227), True, 'import numpy as np\n')]
|
import cv2
import numpy as np
from scipy.ndimage.morphology import distance_transform_cdt
import torch
from skimage.io import imsave
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def get_edge_mask(poly, mask):
"""
Generate edge mask
"""
h = mask.shape[0]
w = mask.shape[1]
gt_poly = np.zeros((poly.shape[0],poly.shape[1]),np.int32)
gt_poly[:,0] = np.floor(poly[:,0]*w)
gt_poly[:,1] = np.floor(poly[:,1]*h)
# print(gt_poly[:,0], gt_poly[:,1])
cv2.polylines(mask, np.int32([gt_poly]),True,[1], thickness = 1)
# cv2.fillPoly(mask, np.int32([gt_poly]),[255])
# imsave("./test33/"+str(poly.shape[0])+"edge.jpg",mask[0])
# imsave("./test33/"+str(poly.shape[0])+"edgegt.jpg",mask[1])
return mask
def get_poly_mask(poly, mask):
"""
Generate edge mask
"""
h = mask.shape[0]
w = mask.shape[1]
gt_poly = np.zeros((poly.shape[0],poly.shape[1]),np.int32)
gt_poly[:,0] = np.floor(poly[:,0]*w)
gt_poly[:,1] = np.floor(poly[:,1]*h)
# print(gt_poly[:,0], gt_poly[:,1])
# cv2.polylines(mask, np.int32([gt_poly]),True,[1], thickness = 1)
cv2.fillPoly(mask, np.int32([gt_poly]),[1])
# imsave("./test33/"+str(poly.shape[0])+"edge.jpg",mask[0])
# imsave("./test33/"+str(poly.shape[0])+"edgegt.jpg",mask[1])
return mask
def get_original_mask(poly, mask):
"""
Generate edge mask
"""
h = mask.shape[0]
w = mask.shape[1]
gt_poly = np.zeros((poly.shape[0],poly.shape[1]),np.int32)
gt_poly[:,0] = np.floor(poly[:,0]*w)
gt_poly[:,1] = np.floor(poly[:,1]*h)
# print(gt_poly[:,0], gt_poly[:,1])
# cv2.polylines(mask, np.int32([gt_poly]),True,[1], thickness = 1)
cv2.fillPoly(mask, np.int32([gt_poly]),[1])
# imsave("./test33/"+str(poly.shape[0])+"edge.jpg",mask[0])
# imsave("./test33/"+str(poly.shape[0])+"edgegt.jpg",mask[1])
return mask
def get_fp_mask(poly,mask):
h = mask.shape[0]
w = mask.shape[1]
x = np.int32(np.floor(poly[0,0]*w))
y = np.int32(np.floor(poly[0,1]*h))
mask[y,x] = 1.0
# if(y<=14 and x<=190 and x>=1 and y>=1):
# mask[y,x+1] = 1.0
# mask[y,x-1] = 1.0
# mask[y+1,x] = 1.0
# mask[y-1,x] = 1.0
return mask
def get_vertices_mask(poly, mask):
"""
Generate a vertex mask
"""
h = mask.shape[0]
w = mask.shape[1]
gt_poly = np.zeros((poly.shape[0],poly.shape[1]),np.int32)
gt_poly[:,0] = np.floor(poly[:,0]*w)
gt_poly[:,1] = np.floor(poly[:,1]*h)
mask[gt_poly[:, 1], gt_poly[:, 0]] = 1.0
return mask
def get_previous_mask(poly,mask,t):
mask = torch.zeros(1, 1, 25, 60, device=device)
h = 25
w = 60
x = np.int32(np.floor(poly[0,t,0]*w))
y = np.int32(np.floor(poly[0,t,1]*h))
mask[0,0,y,x] = 1
# if(y<=14 and x<=190 and x>=1 and y>=1):
# mask[0,0,y,x+1] = 1.0
# mask[0,0,y,x-1] = 1.0
# mask[0,0,y+1,x] = 1.0
# mask[0,0,y-1,x] = 1.0
return mask
def get_instance_mask(poly,mask):
h = 25
w = 60
masks = []
for tr in range(poly.shape[0]):
# print(poly[tr,0],poly[tr,1])
x = np.int32(np.floor(poly[tr,0]*w))
y = np.int32(np.floor(poly[tr,1]*h))
# print(y,x)
mask[y,x] = 1.0
# if(y<=14 and x<=190 and x>=1 and y>=1):
# mask[y,x+1] = 1.0
# mask[y,x-1] = 1.0
# mask[y+1,x] = 1.0
# mask[y-1,x] = 1.0
mask1 = mask.flatten()
if(tr == poly.shape[0]-1):
mask1 = np.append(mask1,[1.0])
else:
mask1 = np.append(mask1,[0.0])
masks.append(mask1)
# print(y,x)
mask[y,x] = 0.0
# if(y<=14 and x<=190 and x>=1 and y>=1):
# mask[y+1,x] = 0.0
# mask[y-1,x] = 0.0
# mask[y,x+1] = 0.0
# mask[y,x-1] = 0.0
return np.asarray(masks, dtype=np.float32)
def class_to_grid(poly, out_tensor):
"""
NOTE: Torch function
accepts out_tensor to do it inplace
poly: [batch, ]
out_tensor: [batch, 1, grid_size, grid_size]
"""
out_tensor.zero_()
# Remove old state of out_tensor
b = 0
for i in poly:
if i < 16 * 192:
x = (i%192).long()
y = (i/16).long()
out_tensor[0,0,y,x] = 1
b += 1
return out_tensor
def dt_targets_from_class(poly):
"""
NOTE: numpy function!
poly: [bs, time_steps], each value in [0, grid*size**2+1)
grid_size: size of the grid the polygon is in
dt_threshold: threshold for smoothing in dt targets
returns:
full_targets: [bs, time_steps, grid_size**2+1] array containing
dt smoothed targets to be used for the polygon loss function
"""
full_targets = []
for b in range(poly.shape[0]):
targets = []
for p in poly[b]:
t = np.zeros(16*192+1, dtype=np.int32)
t[p] += 1
if p != 16*192:#EOS
spatial_part = t[:-1]
spatial_part = np.reshape(spatial_part, [16, 192, 1])
# Invert image
spatial_part = -1 * (spatial_part - 1)
# Compute distance transform
spatial_part = distance_transform_cdt(spatial_part, metric='taxicab').astype(np.float32)
# Threshold
spatial_part = np.clip(spatial_part, 0, dt_threshold)
# Normalize
spatial_part /= dt_threshold
# Invert back
spatial_part = -1. * (spatial_part - 1.)
spatial_part /= np.sum(spatial_part)
spatial_part = spatial_part.flatten()
t = np.concatenate([spatial_part, [0.]], axis=-1)
targets.append(t.astype(np.float32))
full_targets.append(targets)
return np.array(full_targets, dtype=np.float32)
# def class_to_grid(poly, out_tensor):
# """
# NOTE: Torch function
# accepts out_tensor to do it inplace
# poly: [batch, ]
# out_tensor: [batch, 1, grid_size, grid_size]
# """
# out_tensor.zero_()
# # Remove old state of out_tensor
# b = 0
# for i in poly:
# if i < 16 * 192:
# x = (i%192).long()
# y = (i/16).long()
# out_tensor[b,0,y,x] = 1
# b += 1
# return out_tensor
|
[
"scipy.ndimage.morphology.distance_transform_cdt",
"numpy.sum",
"numpy.asarray",
"numpy.floor",
"numpy.zeros",
"numpy.clip",
"numpy.append",
"numpy.array",
"torch.cuda.is_available",
"numpy.int32",
"numpy.reshape",
"torch.zeros",
"numpy.concatenate"
] |
[((333, 383), 'numpy.zeros', 'np.zeros', (['(poly.shape[0], poly.shape[1])', 'np.int32'], {}), '((poly.shape[0], poly.shape[1]), np.int32)\n', (341, 383), True, 'import numpy as np\n'), ((401, 425), 'numpy.floor', 'np.floor', (['(poly[:, 0] * w)'], {}), '(poly[:, 0] * w)\n', (409, 425), True, 'import numpy as np\n'), ((442, 466), 'numpy.floor', 'np.floor', (['(poly[:, 1] * h)'], {}), '(poly[:, 1] * h)\n', (450, 466), True, 'import numpy as np\n'), ((905, 955), 'numpy.zeros', 'np.zeros', (['(poly.shape[0], poly.shape[1])', 'np.int32'], {}), '((poly.shape[0], poly.shape[1]), np.int32)\n', (913, 955), True, 'import numpy as np\n'), ((973, 997), 'numpy.floor', 'np.floor', (['(poly[:, 0] * w)'], {}), '(poly[:, 0] * w)\n', (981, 997), True, 'import numpy as np\n'), ((1014, 1038), 'numpy.floor', 'np.floor', (['(poly[:, 1] * h)'], {}), '(poly[:, 1] * h)\n', (1022, 1038), True, 'import numpy as np\n'), ((1479, 1529), 'numpy.zeros', 'np.zeros', (['(poly.shape[0], poly.shape[1])', 'np.int32'], {}), '((poly.shape[0], poly.shape[1]), np.int32)\n', (1487, 1529), True, 'import numpy as np\n'), ((1547, 1571), 'numpy.floor', 'np.floor', (['(poly[:, 0] * w)'], {}), '(poly[:, 0] * w)\n', (1555, 1571), True, 'import numpy as np\n'), ((1588, 1612), 'numpy.floor', 'np.floor', (['(poly[:, 1] * h)'], {}), '(poly[:, 1] * h)\n', (1596, 1612), True, 'import numpy as np\n'), ((2404, 2454), 'numpy.zeros', 'np.zeros', (['(poly.shape[0], poly.shape[1])', 'np.int32'], {}), '((poly.shape[0], poly.shape[1]), np.int32)\n', (2412, 2454), True, 'import numpy as np\n'), ((2472, 2496), 'numpy.floor', 'np.floor', (['(poly[:, 0] * w)'], {}), '(poly[:, 0] * w)\n', (2480, 2496), True, 'import numpy as np\n'), ((2513, 2537), 'numpy.floor', 'np.floor', (['(poly[:, 1] * h)'], {}), '(poly[:, 1] * h)\n', (2521, 2537), True, 'import numpy as np\n'), ((2646, 2686), 'torch.zeros', 'torch.zeros', (['(1)', '(1)', '(25)', '(60)'], {'device': 'device'}), '(1, 1, 25, 60, device=device)\n', (2657, 2686), False, 'import torch\n'), ((3894, 3929), 'numpy.asarray', 'np.asarray', (['masks'], {'dtype': 'np.float32'}), '(masks, dtype=np.float32)\n', (3904, 3929), True, 'import numpy as np\n'), ((5853, 5893), 'numpy.array', 'np.array', (['full_targets'], {'dtype': 'np.float32'}), '(full_targets, dtype=np.float32)\n', (5861, 5893), True, 'import numpy as np\n'), ((166, 191), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (189, 191), False, 'import torch\n'), ((532, 551), 'numpy.int32', 'np.int32', (['[gt_poly]'], {}), '([gt_poly])\n', (540, 551), True, 'import numpy as np\n'), ((1174, 1193), 'numpy.int32', 'np.int32', (['[gt_poly]'], {}), '([gt_poly])\n', (1182, 1193), True, 'import numpy as np\n'), ((1748, 1767), 'numpy.int32', 'np.int32', (['[gt_poly]'], {}), '([gt_poly])\n', (1756, 1767), True, 'import numpy as np\n'), ((2010, 2034), 'numpy.floor', 'np.floor', (['(poly[0, 0] * w)'], {}), '(poly[0, 0] * w)\n', (2018, 2034), True, 'import numpy as np\n'), ((2050, 2074), 'numpy.floor', 'np.floor', (['(poly[0, 1] * h)'], {}), '(poly[0, 1] * h)\n', (2058, 2074), True, 'import numpy as np\n'), ((2726, 2753), 'numpy.floor', 'np.floor', (['(poly[0, t, 0] * w)'], {}), '(poly[0, t, 0] * w)\n', (2734, 2753), True, 'import numpy as np\n'), ((2768, 2795), 'numpy.floor', 'np.floor', (['(poly[0, t, 1] * h)'], {}), '(poly[0, t, 1] * h)\n', (2776, 2795), True, 'import numpy as np\n'), ((3174, 3199), 'numpy.floor', 'np.floor', (['(poly[tr, 0] * w)'], {}), '(poly[tr, 0] * w)\n', (3182, 3199), True, 'import numpy as np\n'), ((3219, 3244), 'numpy.floor', 'np.floor', (['(poly[tr, 1] * h)'], {}), '(poly[tr, 1] * h)\n', (3227, 3244), True, 'import numpy as np\n'), ((3552, 3575), 'numpy.append', 'np.append', (['mask1', '[1.0]'], {}), '(mask1, [1.0])\n', (3561, 3575), True, 'import numpy as np\n'), ((3609, 3632), 'numpy.append', 'np.append', (['mask1', '[0.0]'], {}), '(mask1, [0.0])\n', (3618, 3632), True, 'import numpy as np\n'), ((4886, 4924), 'numpy.zeros', 'np.zeros', (['(16 * 192 + 1)'], {'dtype': 'np.int32'}), '(16 * 192 + 1, dtype=np.int32)\n', (4894, 4924), True, 'import numpy as np\n'), ((5045, 5083), 'numpy.reshape', 'np.reshape', (['spatial_part', '[16, 192, 1]'], {}), '(spatial_part, [16, 192, 1])\n', (5055, 5083), True, 'import numpy as np\n'), ((5380, 5418), 'numpy.clip', 'np.clip', (['spatial_part', '(0)', 'dt_threshold'], {}), '(spatial_part, 0, dt_threshold)\n', (5387, 5418), True, 'import numpy as np\n'), ((5612, 5632), 'numpy.sum', 'np.sum', (['spatial_part'], {}), '(spatial_part)\n', (5618, 5632), True, 'import numpy as np\n'), ((5708, 5754), 'numpy.concatenate', 'np.concatenate', (['[spatial_part, [0.0]]'], {'axis': '(-1)'}), '([spatial_part, [0.0]], axis=-1)\n', (5722, 5754), True, 'import numpy as np\n'), ((5247, 5301), 'scipy.ndimage.morphology.distance_transform_cdt', 'distance_transform_cdt', (['spatial_part'], {'metric': '"""taxicab"""'}), "(spatial_part, metric='taxicab')\n", (5269, 5301), False, 'from scipy.ndimage.morphology import distance_transform_cdt\n')]
|
import numpy as np
import torch
from utils import plotsAnalysis
import os
from utils.helper_functions import load_flags
def auto_swipe(mother_dir=None):
"""
This function swipes the parameter space of a folder and extract the varying hyper-parameters and make 2d heatmap w.r.t. all combinations of them
"""
if mother_dir is None:
#mother_dir = '/scratch/sr365/ML_MM_Benchmark/Yang_temp/models/sweep8'
#mother_dir = '/scratch/sr365/ML_MM_Benchmark/Transformer/models/Yang_new_sweep/'
mother_dir = '/scratch/sr365/ML_MM_Benchmark/Transformer/models/new_norm_color/'
#mother_dir = '/scratch/sr365/ML_MM_Benchmark/Transformer/models/Color_new_sweep/'
#mother_dir = '/scratch/sr365/ML_MM_Benchmark/Transformer/models/encoder_pos_analysis/Color'
#mother_dir = '/scratch/sr365/ML_MM_Benchmark/Color_temp/models'
#mother_dir = '/scratch/sr365/ML_MM_Benchmark/Color_temp/prev_sweep/test_size'
#mother_dir = '/scratch/sr365/ML_MM_Benchmark/Transformer/models/sweep_encode_lr'
flags_list = []
# First step, get the list of object flags
for folder in os.listdir(mother_dir):
# Get the current sub_folder
cur_folder = os.path.join(mother_dir, folder)
if not os.path.isdir(cur_folder) or not os.path.isfile(os.path.join(cur_folder, 'flags.obj')):
print('Either this is not a folder or there is no flags object under this folder for ', cur_folder)
continue
# Read the pickle object
cur_flags = load_flags(cur_folder)
flags_list.append(cur_flags)
# From the list of flags, get the things that are different except for loss terms
att_list = [a for a in dir(cur_flags) if not a.startswith('_') and not 'loss' in a and not 'trainable_param' in a and not 'model_name' in a and not 'dir' in a]
print('In total {} attributes, they are {}'.format(len(att_list), att_list))
# Create a dictionary that have keys as attributes and unique values as that
attDict = {key: [] for key in att_list}
# Loop over all the flags and get the unique values inside
for flags in flags_list:
for keys in attDict.keys():
try:
att = getattr(flags,keys)
except:
print('There is not attribute {} in flags, continue'.format(keys))
continue
# Skip if this is already inside the list
if att in attDict[keys]:
continue
attDict[keys].append(att)
# Get the atts in the dictionary that has more than 1 att inside
varying_att_list = []
for keys in attDict.keys():
if len(attDict[keys]) > 1:
# For linear layers, apply special handlings
if 'linear' not in keys:
varying_att_list.append(keys)
continue
length_list = []
num_node_in_layer_list = []
# Loop over the lists of linear
for linear_list in attDict[keys]:
assert type(linear_list) == list, 'Your linear layer is not list, check again'
length_list.append(len(linear_list)) # Record the length instead
if 'head_linear' in keys:
if len(linear_list) > 2:
num_node_in_layer_list.append(linear_list[-2]) # Record the -2 of the list, which denotes the number of nodes
elif 'tail_linear' in keys:
if len(linear_list) > 1:
num_node_in_layer_list.append(linear_list[-2]) # Record the -2 of the list, which denotes the number of nodes
# Add these two attributes to the
if len(np.unique(length_list)) > 1:
varying_att_list.append(keys)
if len(np.unique(num_node_in_layer_list)) > 1:
varying_att_list.append('linear_unit')
print('varying attributes are', varying_att_list)
# Showing how they are changing
for keys in varying_att_list:
if keys == 'linear_unit':
continue
print('att is {}, they have values of {}'.format(keys, attDict[keys]))
if len(varying_att_list) == 1:
# There is only 1 attribute that is changing
att = varying_att_list[0]
key_a = att
key_b = 'lr'
for heatmap_value in ['best_validation_loss', 'best_training_loss','trainable_param']:
#try:
print('doing heatmap {}'.format(heatmap_value))
plotsAnalysis.HeatMapBVL(key_a, key_b, key_a + '_' + key_b + '_HeatMap',save_name=mother_dir + '_' + key_a + '_' + key_b + '_' + heatmap_value + '_heatmap.png',
HeatMap_dir=mother_dir,feature_1_name=key_a,feature_2_name=key_b, heat_value_name=heatmap_value)
#except Exception as e:
# print('the plotswipe does not work in {} and {} cross for {}'.format(key_a, key_b, heatmap_value))
# print('error message: {}'.format(e))
# Start calling the plotsAnalysis function for all the pairs
for a, key_a in enumerate(varying_att_list):
for b, key_b in enumerate(varying_att_list):
# Skip the same attribute
if a <= b:
continue
# Call the plotsAnalysis function
#for heatmap_value in ['best_validation_loss']:
for heatmap_value in ['best_validation_loss', 'best_training_loss','trainable_param']:
print('doing heatmap {}'.format(heatmap_value))
try:
plotsAnalysis.HeatMapBVL(key_a, key_b, key_a + '_' + key_b + '_HeatMap',save_name=mother_dir + '_' + key_a + '_' + key_b + '_' + heatmap_value + '_heatmap.png',
HeatMap_dir=mother_dir,feature_1_name=key_a,feature_2_name=key_b, heat_value_name=heatmap_value)
except:
print('the plotswipe does not work in {} and {} cross for {}'.format(key_a, key_b, heatmap_value))
if __name__ == '__main__':
#pathnamelist = ['/scratch/sr365/ML_MM_Benchmark/Yang_temp/models/sweep4',
# '/scratch/sr365/ML_MM_Benchmark/Transformer/models/sweep4']#,
#'/scratch/sr365/ML_MM_Benchmark/Color_temp/models/sweep2']
#'/scratch/sr365/ML_MM_Benchmark/Yang_temp/models/lr_sweep']
#big_mother_dir = '/scratch/sr365/ML_MM_Benchmark/Transformer/models/encoder'
#big_mother_dir = '/scratch/sr365/ML_MM_Benchmark/Transformer/models/sequence_len'
#big_mother_dir = '/scratch/sr365/ML_MM_Benchmark/Transformer/models/MLP_complexity/'
#for dirs in os.listdir(big_mother_dir):
# mother_dir = os.path.join(big_mother_dir, dirs)
# if os.path.isdir(mother_dir):
# auto_swipe(mother_dir)
auto_swipe()
|
[
"utils.helper_functions.load_flags",
"os.path.isdir",
"utils.plotsAnalysis.HeatMapBVL",
"os.path.join",
"os.listdir",
"numpy.unique"
] |
[((1134, 1156), 'os.listdir', 'os.listdir', (['mother_dir'], {}), '(mother_dir)\n', (1144, 1156), False, 'import os\n'), ((1216, 1248), 'os.path.join', 'os.path.join', (['mother_dir', 'folder'], {}), '(mother_dir, folder)\n', (1228, 1248), False, 'import os\n'), ((1538, 1560), 'utils.helper_functions.load_flags', 'load_flags', (['cur_folder'], {}), '(cur_folder)\n', (1548, 1560), False, 'from utils.helper_functions import load_flags\n'), ((4527, 4799), 'utils.plotsAnalysis.HeatMapBVL', 'plotsAnalysis.HeatMapBVL', (['key_a', 'key_b', "(key_a + '_' + key_b + '_HeatMap')"], {'save_name': "(mother_dir + '_' + key_a + '_' + key_b + '_' + heatmap_value + '_heatmap.png')", 'HeatMap_dir': 'mother_dir', 'feature_1_name': 'key_a', 'feature_2_name': 'key_b', 'heat_value_name': 'heatmap_value'}), "(key_a, key_b, key_a + '_' + key_b + '_HeatMap',\n save_name=mother_dir + '_' + key_a + '_' + key_b + '_' + heatmap_value +\n '_heatmap.png', HeatMap_dir=mother_dir, feature_1_name=key_a,\n feature_2_name=key_b, heat_value_name=heatmap_value)\n", (4551, 4799), False, 'from utils import plotsAnalysis\n'), ((1264, 1289), 'os.path.isdir', 'os.path.isdir', (['cur_folder'], {}), '(cur_folder)\n', (1277, 1289), False, 'import os\n'), ((1312, 1349), 'os.path.join', 'os.path.join', (['cur_folder', '"""flags.obj"""'], {}), "(cur_folder, 'flags.obj')\n", (1324, 1349), False, 'import os\n'), ((3729, 3751), 'numpy.unique', 'np.unique', (['length_list'], {}), '(length_list)\n', (3738, 3751), True, 'import numpy as np\n'), ((3823, 3856), 'numpy.unique', 'np.unique', (['num_node_in_layer_list'], {}), '(num_node_in_layer_list)\n', (3832, 3856), True, 'import numpy as np\n'), ((5602, 5874), 'utils.plotsAnalysis.HeatMapBVL', 'plotsAnalysis.HeatMapBVL', (['key_a', 'key_b', "(key_a + '_' + key_b + '_HeatMap')"], {'save_name': "(mother_dir + '_' + key_a + '_' + key_b + '_' + heatmap_value + '_heatmap.png')", 'HeatMap_dir': 'mother_dir', 'feature_1_name': 'key_a', 'feature_2_name': 'key_b', 'heat_value_name': 'heatmap_value'}), "(key_a, key_b, key_a + '_' + key_b + '_HeatMap',\n save_name=mother_dir + '_' + key_a + '_' + key_b + '_' + heatmap_value +\n '_heatmap.png', HeatMap_dir=mother_dir, feature_1_name=key_a,\n feature_2_name=key_b, heat_value_name=heatmap_value)\n", (5626, 5874), False, 'from utils import plotsAnalysis\n')]
|
#!/usr/bin/env python
# Copyright 2019 <NAME>
#
# This file is part of RfPy.
#
# 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.
# Import modules and functions
import numpy as np
import pickle
import stdb
from obspy.clients.fdsn import Client
from obspy.core import Stream, UTCDateTime
from rfpy import arguments, binning, plotting
from rfpy import CCPimage
from pathlib import Path
def main():
print()
print("############################################")
print("# __ #")
print("# _ __ / _|_ __ _ _ ___ ___ _ __ #")
print("# | '__| |_| '_ \| | | | / __/ __| '_ \ #")
print("# | | | _| |_) | |_| | | (_| (__| |_) | #")
print("# |_| |_| | .__/ \__, |___\___\___| .__/ #")
print("# |_| |___/_____| |_| #")
print("# #")
print("############################################")
print()
# Run Input Parser
args = arguments.get_ccp_arguments()
# Load Database
db = stdb.io.load_db(fname=args.indb)
# Construct station key loop
allkeys = db.keys()
# Extract key subset
if len(args.stkeys) > 0:
stkeys = []
for skey in args.stkeys:
stkeys.extend([s for s in allkeys if skey in s])
else:
stkeys = db.keys()
if args.load:
# Check if CCPimage object exists and whether overwrite has been set
load_file = Path('CCP_load.pkl')
if load_file.is_file() and not args.ovr:
ccpfile = open(load_file, "rb")
ccpimage = pickle.load(ccpfile)
ccpfile.close()
else:
print()
print("|-----------------------------------------------|")
print("| Loading data |")
print("|-----------------------------------------------|")
print("| Gridding: ")
print("| start = {0:5.1f},{1:6.1f}".format(
args.coord_start[0],args.coord_start[1]))
print("| end = {0:5.1f},{1:6.1f}".format(
args.coord_end[0],args.coord_end[1]))
print("| dz = {0} (km)".format(str(args.dz)))
print("| dx = {0} (km)".format(str(args.dx)))
print()
# Initialize CCPimage object
ccpimage = CCPimage(coord_start=args.coord_start,
coord_end=args.coord_end,
dz=args.dz, dx=args.dx)
# Loop over station keys
for stkey in list(stkeys):
# Extract station information from dictionary
sta = db[stkey]
# Define path to see if it exists
if args.phase in ['P', 'PP', 'allP']:
datapath = Path('P_DATA') / stkey
elif args.phase in ['S', 'SKS', 'allS']:
datapath = Path('S_DATA') / stkey
if not datapath.is_dir():
print('Path to ' + str(datapath) + ' doesn`t exist - continuing')
continue
# Temporary print locations
tlocs = sta.location
if len(tlocs) == 0:
tlocs = ['']
for il in range(0, len(tlocs)):
if len(tlocs[il]) == 0:
tlocs[il] = "--"
sta.location = tlocs
rfRstream = Stream()
datafiles = [x for x in datapath.iterdir() if x.is_dir()]
for folder in datafiles:
# Skip hidden folders
if folder.name.startswith('.'):
continue
# Load meta data
filename = folder / "Meta_Data.pkl"
if not filename.is_file():
continue
metafile = open(filename, 'rb')
meta = pickle.load(metafile)
metafile.close()
# Skip data not in list of phases
if meta.phase not in args.listphase:
continue
# QC Thresholding
if meta.snrh < args.snrh:
continue
if meta.snr < args.snr:
continue
if meta.cc < args.cc:
continue
# If everything passed, load the RF data
filename = folder / "RF_Data.pkl"
if filename.is_file():
file = open(filename, "rb")
rfdata = pickle.load(file)
rfRstream.append(rfdata[1])
file.close()
if len(rfRstream) == 0:
continue
if args.no_outl:
t1 = 0.
t2 = 30.
varR = []
for i in range(len(rfRstream)):
taxis = rfRstream[i].stats.taxis
tselect = (taxis > t1) & (taxis < t2)
varR.append(np.var(rfRstream[i].data[tselect]))
varR = np.array(varR)
# Remove outliers wrt variance within time range
medvarR = np.median(varR)
madvarR = 1.4826*np.median(np.abs(varR-medvarR))
robustR = np.abs((varR-medvarR)/madvarR)
outliersR = np.arange(len(rfRstream))[robustR > 2.5]
for i in outliersR[::-1]:
rfRstream.remove(rfRstream[i])
print("Station: {0:>2s}.{1:5s} - {2} traces loaded".format(
sta.network, sta.station, len(rfRstream)))
if len(rfRstream)==0:
continue
ccpimage.add_rfstream(rfRstream)
if len(ccpimage.radialRF) > 0:
ccpimage.save("CCP_load.pkl")
ccpimage.is_ready_for_prep = True
print()
print("CCPimage saved to 'CCP_load.pkl'")
else:
ccpimage.is_ready_for_prep = False
else:
pass
if args.prep:
prep_file = Path("CCP_prep.pkl")
if prep_file.is_file() and not args.ovr:
ccpfile = open(prep_file, 'rb')
ccpimage = pickle.load(ccpfile)
ccpfile.close()
else:
load_file = Path('CCP_load.pkl')
if not load_file.is_file():
raise(Exception("No CCP_load.pkl file available - aborting"))
else:
print()
print("|-----------------------------------------------|")
print("| Preparing data before stacking |")
print("|-----------------------------------------------|")
print("| Frequencies: ")
print("| f1 = {0:4.2f} (Hz)".format(args.f1))
print("| f2ps = {0:4.2f} (Hz)".format(args.f2ps))
print("| f2pps = {0:4.2f} (Hz)".format(args.f2pps))
print("| f2pss = {0:4.2f} (Hz)".format(args.f2pss))
print("| Binning: ")
print("| nbaz = {0}".format(str(args.nbaz)))
print("| nslow = {0}".format(str(args.nslow)))
print()
ccpfile = open(load_file,"rb")
ccpimage = pickle.load(ccpfile)
ccpfile.close()
ccpimage.prep_data(f1=args.f1, f2ps=args.f2ps,
f2pps=args.f2pps, f2pss=args.f2pss,
nbaz=args.nbaz, nslow=args.nslow)
ccpimage.is_ready_for_prestack = True
ccpimage.save(prep_file)
print()
print("CCPimage saved to {0}".format(str(prep_file)))
else:
pass
if args.prestack:
prestack_file = Path("CCP_prestack.pkl")
if prestack_file.is_file() and not args.ovr:
ccpfile = open(prestack_file, 'rb')
ccpimage = pickle.load(ccpfile)
ccpfile.close()
else:
prep_file = Path("CCP_prep.pkl")
if not prep_file.is_file():
raise(Exception("No CCP_prep.pkl file available - aborting"))
else:
print()
print("|-----------------------------------------------|")
print("| CCP pre-stacking each phase |")
print("|-----------------------------------------------|")
print()
ccpfile = open(prep_file, 'rb')
ccpimage = pickle.load(ccpfile)
ccpfile.close()
ccpimage.prestack()
ccpimage.save(prestack_file)
print()
print("CCPimage saved to {0}".format(str(prestack_file)))
else:
pass
if args.ccp:
ccp_file = Path("CCP_stack.pkl")
if ccp_file.is_file() and not args.ovr:
ccpfile = open(ccp_file, 'rb')
ccpimage = pickle.load(ccpfile)
ccpfile.close()
else:
prestack_file = Path("CCP_prestack.pkl")
if not prestack_file.is_file():
raise(Exception("No CCP_prestack.pkl file available - aborting"))
else:
if args.linear:
print()
print("|-----------------------------------------------|")
print("| Linear CCP stack - all phases |")
print("|-----------------------------------------------|")
print()
elif args.pws:
print()
print("|-----------------------------------------------|")
print("| Phase-weighted CCP stack - all phases |")
print("|-----------------------------------------------|")
print()
ccpfile = open(prestack_file, 'rb')
ccpimage = pickle.load(ccpfile)
ccpfile.close()
ccpimage.ccp()
if args.linear:
if args.weights:
ccpimage.weights = args.weights
ccpimage.linear_stack(typ='ccp')
elif args.pws:
if args.weights:
ccpimage.weights = args.weights
ccpimage.phase_weighted_stack(typ='ccp')
ccpimage.save(ccp_file)
print()
print("CCPimage saved to {0}".format(str(ccp_file)))
if args.ccp_figure:
ccpimage.plot_ccp(save=args.save_figure, fmt=args.fmt,
vmin=-1.*args.cbound, vmax=args.cbound, title=args.title)
else:
pass
if args.gccp:
gccp_file = Path("GCCP_stack.pkl")
if gccp_file.is_file() and not args.ovr:
ccpfile = open(gccp_file, 'rb')
ccpimage = pickle.load(ccpfile)
ccpfile.close()
else:
prestack_file = Path("CCP_prestack.pkl")
if not prestack_file.is_file():
raise(Exception("No CCP_prestack.pkl file available - aborting"))
else:
if args.linear:
print()
print("|-----------------------------------------------|")
print("| Linear GCCP stack - all phases |")
print("|-----------------------------------------------|")
print()
elif args.pws:
print()
print("|-----------------------------------------------|")
print("| Phase-weighted GCCP stack - all phases |")
print("|-----------------------------------------------|")
print()
ccpfile = open(prestack_file, 'rb')
ccpimage = pickle.load(ccpfile)
ccpfile.close()
ccpimage.gccp(wlen=args.wlen)
if args.linear:
if args.weights:
ccpimage.weights = args.weights
ccpimage.linear_stack(typ='gccp')
elif args.pws:
if args.weights:
ccpimage.weights = args.weights
ccpimage.phase_weighted_stack(typ='gccp')
ccpimage.save(gccp_file)
print()
print("CCPimage saved to {0}".format(str(gccp_file)))
if args.ccp_figure:
ccpimage.plot_gccp(save=args.save_figure, fmt=args.fmt,
vmin=-1.*args.cbound, vmax=args.cbound, title=args.title)
else:
pass
if __name__ == "__main__":
# Run main program
main()
|
[
"numpy.abs",
"rfpy.arguments.get_ccp_arguments",
"numpy.median",
"rfpy.CCPimage",
"pathlib.Path",
"pickle.load",
"obspy.core.Stream",
"numpy.array",
"numpy.var",
"stdb.io.load_db"
] |
[((1987, 2016), 'rfpy.arguments.get_ccp_arguments', 'arguments.get_ccp_arguments', ([], {}), '()\n', (2014, 2016), False, 'from rfpy import arguments, binning, plotting\n'), ((2047, 2079), 'stdb.io.load_db', 'stdb.io.load_db', ([], {'fname': 'args.indb'}), '(fname=args.indb)\n', (2062, 2079), False, 'import stdb\n'), ((2461, 2481), 'pathlib.Path', 'Path', (['"""CCP_load.pkl"""'], {}), "('CCP_load.pkl')\n", (2465, 2481), False, 'from pathlib import Path\n'), ((7325, 7345), 'pathlib.Path', 'Path', (['"""CCP_prep.pkl"""'], {}), "('CCP_prep.pkl')\n", (7329, 7345), False, 'from pathlib import Path\n'), ((9067, 9091), 'pathlib.Path', 'Path', (['"""CCP_prestack.pkl"""'], {}), "('CCP_prestack.pkl')\n", (9071, 9091), False, 'from pathlib import Path\n'), ((10103, 10124), 'pathlib.Path', 'Path', (['"""CCP_stack.pkl"""'], {}), "('CCP_stack.pkl')\n", (10107, 10124), False, 'from pathlib import Path\n'), ((12042, 12064), 'pathlib.Path', 'Path', (['"""GCCP_stack.pkl"""'], {}), "('GCCP_stack.pkl')\n", (12046, 12064), False, 'from pathlib import Path\n'), ((2598, 2618), 'pickle.load', 'pickle.load', (['ccpfile'], {}), '(ccpfile)\n', (2609, 2618), False, 'import pickle\n'), ((3383, 3475), 'rfpy.CCPimage', 'CCPimage', ([], {'coord_start': 'args.coord_start', 'coord_end': 'args.coord_end', 'dz': 'args.dz', 'dx': 'args.dx'}), '(coord_start=args.coord_start, coord_end=args.coord_end, dz=args.dz,\n dx=args.dx)\n', (3391, 3475), False, 'from rfpy import CCPimage\n'), ((7462, 7482), 'pickle.load', 'pickle.load', (['ccpfile'], {}), '(ccpfile)\n', (7473, 7482), False, 'import pickle\n'), ((7549, 7569), 'pathlib.Path', 'Path', (['"""CCP_load.pkl"""'], {}), "('CCP_load.pkl')\n", (7553, 7569), False, 'from pathlib import Path\n'), ((9216, 9236), 'pickle.load', 'pickle.load', (['ccpfile'], {}), '(ccpfile)\n', (9227, 9236), False, 'import pickle\n'), ((9303, 9323), 'pathlib.Path', 'Path', (['"""CCP_prep.pkl"""'], {}), "('CCP_prep.pkl')\n", (9307, 9323), False, 'from pathlib import Path\n'), ((10239, 10259), 'pickle.load', 'pickle.load', (['ccpfile'], {}), '(ccpfile)\n', (10250, 10259), False, 'import pickle\n'), ((10330, 10354), 'pathlib.Path', 'Path', (['"""CCP_prestack.pkl"""'], {}), "('CCP_prestack.pkl')\n", (10334, 10354), False, 'from pathlib import Path\n'), ((12181, 12201), 'pickle.load', 'pickle.load', (['ccpfile'], {}), '(ccpfile)\n', (12192, 12201), False, 'import pickle\n'), ((12272, 12296), 'pathlib.Path', 'Path', (['"""CCP_prestack.pkl"""'], {}), "('CCP_prestack.pkl')\n", (12276, 12296), False, 'from pathlib import Path\n'), ((4485, 4493), 'obspy.core.Stream', 'Stream', ([], {}), '()\n', (4491, 4493), False, 'from obspy.core import Stream, UTCDateTime\n'), ((8549, 8569), 'pickle.load', 'pickle.load', (['ccpfile'], {}), '(ccpfile)\n', (8560, 8569), False, 'import pickle\n'), ((9809, 9829), 'pickle.load', 'pickle.load', (['ccpfile'], {}), '(ccpfile)\n', (9820, 9829), False, 'import pickle\n'), ((11228, 11248), 'pickle.load', 'pickle.load', (['ccpfile'], {}), '(ccpfile)\n', (11239, 11248), False, 'import pickle\n'), ((13170, 13190), 'pickle.load', 'pickle.load', (['ccpfile'], {}), '(ccpfile)\n', (13181, 13190), False, 'import pickle\n'), ((4991, 5012), 'pickle.load', 'pickle.load', (['metafile'], {}), '(metafile)\n', (5002, 5012), False, 'import pickle\n'), ((6278, 6292), 'numpy.array', 'np.array', (['varR'], {}), '(varR)\n', (6286, 6292), True, 'import numpy as np\n'), ((6393, 6408), 'numpy.median', 'np.median', (['varR'], {}), '(varR)\n', (6402, 6408), True, 'import numpy as np\n'), ((6508, 6542), 'numpy.abs', 'np.abs', (['((varR - medvarR) / madvarR)'], {}), '((varR - medvarR) / madvarR)\n', (6514, 6542), True, 'import numpy as np\n'), ((3844, 3858), 'pathlib.Path', 'Path', (['"""P_DATA"""'], {}), "('P_DATA')\n", (3848, 3858), False, 'from pathlib import Path\n'), ((5709, 5726), 'pickle.load', 'pickle.load', (['file'], {}), '(file)\n', (5720, 5726), False, 'import pickle\n'), ((3955, 3969), 'pathlib.Path', 'Path', (['"""S_DATA"""'], {}), "('S_DATA')\n", (3959, 3969), False, 'from pathlib import Path\n'), ((6215, 6249), 'numpy.var', 'np.var', (['rfRstream[i].data[tselect]'], {}), '(rfRstream[i].data[tselect])\n', (6221, 6249), True, 'import numpy as np\n'), ((6456, 6478), 'numpy.abs', 'np.abs', (['(varR - medvarR)'], {}), '(varR - medvarR)\n', (6462, 6478), True, 'import numpy as np\n')]
|
import pandas as pd
import numpy as np
from sklearn.metrics.pairwise import euclidean_distances, cosine_similarity, manhattan_distances
def top_5(book, items, similarity_measure):
"""
This function extracts the top-five similar books for a given book and
similarity measure. This function takes the following arguments:
book: the book for which five recommendations need to be provided
items: data-frame that contains all the books with their corresponding
engineered features.
similarity_measure: possible values Euclidean, Cosine or Manhattan
"""
## Filter out books with same title but different publisher
temp = items[items['itemID'] == book]
temp_title = items.loc[items['itemID'] == book, 'title']
items = items[~np.isin(items['title'], temp_title)]
items = pd.concat([temp, items]).reset_index(drop = True)
## Selecting books based on the same language and topic
items = items[np.isin(items['language'], temp['language'])].reset_index(drop = True)
if (items[np.isin(items['general_topic'], temp['general_topic'])].shape[0] > 5):
if (sum(items['general_topic'] == 'Y') > 15000):
if (all(temp['general_topic_2'] == 'YF') == True):
items = items[np.isin(items['general_topic_3'], temp['general_topic_3'])].reset_index(drop = True)
else:
if (items[np.isin(items['general_topic_2'], temp['general_topic_2'])].shape[0] >= 6):
items = items[np.isin(items['general_topic_2'], temp['general_topic_2'])].reset_index(drop = True)
else:
items = items[np.isin(items['general_topic'], temp['general_topic'])].reset_index(drop = True)
## Selecting variables of interest
to_remove = ['itemID', 'title', 'author', 'publisher', 'subtopics', 'general_topic', 'general_topic_2', 'general_topic_3', 'language', 'main topic']
variables_of_interest = items.columns[~np.isin(items.columns, to_remove)]
items_temp = items[variables_of_interest]
## Selecting top 5 similar books
if (similarity_measure == 'Euclidean'):
D = euclidean_distances(items_temp)
to_select = np.argsort(D[:, 0])[1:6]
elif (similarity_measure == 'Cosine'):
D = cosine_similarity(items_temp)
to_select = np.argsort(-D[:, 0])[1:6]
elif (similarity_measure == 'Manhattan'):
D = manhattan_distances(items_temp)
to_select = np.argsort(D[:, 0])[1:6]
return [items.loc[to_select[0], 'itemID'], items.loc[to_select[1], 'itemID'], items.loc[to_select[2], 'itemID'], items.loc[to_select[3], 'itemID'], items.loc[to_select[4], 'itemID']]
def top_5_after_transaction(book, book_to_recommend, items, similarity_measure):
"""
This function extracts the top-five similar books for a given book, books from
transaction history, items and a similarity measure. This function takes the
following arguments:
book: the book for which five recommendations need to be provided.
book_to_recommend: list of book from historical transactions.
items: data-frame that contains all the books with their corresponding
engineered features.
similarity_measure: possible values Euclidean, Cosine or Manhattan
"""
## Selecting books based on transactions
items_temp = items.loc[np.isin(items['itemID'], book_to_recommend)]
## Selecting books based on the same language and topic
temp = items[items['itemID'] == book]
temp_title = items.loc[items['itemID'] == book, 'title']
items_temp = items_temp[~np.isin(items_temp['title'], temp_title)]
items_temp = pd.concat([temp, items_temp]).reset_index(drop = True)
## Selecting books based on language
items_temp = items_temp[np.isin(items_temp['language'], temp['language'])].reset_index(drop = True)
## Selecting variables of interest
to_remove = ['itemID', 'title', 'author', 'publisher', 'subtopics', 'general_topic', 'general_topic_2', 'general_topic_3', 'language', 'main topic']
variables_of_interest = items.columns[~np.isin(items.columns, to_remove)]
items_temp_1 = items_temp[variables_of_interest]
## Sanity check
if (items_temp.shape[0] >= 6):
## Selecting top 5 similar books
if (similarity_measure == 'Euclidean'):
D = euclidean_distances(items_temp_1)
to_select = np.argsort(D[:, 0])[1:6]
elif (similarity_measure == 'Cosine'):
D = cosine_similarity(items_temp_1)
to_select = np.argsort(-D[:, 0])[1:6]
elif (similarity_measure == 'Manhattan'):
D = manhattan_distances(items_temp_1)
to_select = np.argsort(D[:, 0])[1:6]
return [items_temp.loc[to_select[0], 'itemID'], items_temp.loc[to_select[1], 'itemID'], items_temp.loc[to_select[2], 'itemID'], items_temp.loc[to_select[3], 'itemID'], items_temp.loc[to_select[4], 'itemID']]
else:
knn_top_5 = top_5(book, items, similarity_measure)
return knn_top_5
|
[
"numpy.isin",
"sklearn.metrics.pairwise.cosine_similarity",
"sklearn.metrics.pairwise.manhattan_distances",
"sklearn.metrics.pairwise.euclidean_distances",
"numpy.argsort",
"pandas.concat"
] |
[((2284, 2315), 'sklearn.metrics.pairwise.euclidean_distances', 'euclidean_distances', (['items_temp'], {}), '(items_temp)\n', (2303, 2315), False, 'from sklearn.metrics.pairwise import euclidean_distances, cosine_similarity, manhattan_distances\n'), ((3588, 3631), 'numpy.isin', 'np.isin', (["items['itemID']", 'book_to_recommend'], {}), "(items['itemID'], book_to_recommend)\n", (3595, 3631), True, 'import numpy as np\n'), ((805, 840), 'numpy.isin', 'np.isin', (["items['title']", 'temp_title'], {}), "(items['title'], temp_title)\n", (812, 840), True, 'import numpy as np\n'), ((854, 878), 'pandas.concat', 'pd.concat', (['[temp, items]'], {}), '([temp, items])\n', (863, 878), True, 'import pandas as pd\n'), ((2100, 2133), 'numpy.isin', 'np.isin', (['items.columns', 'to_remove'], {}), '(items.columns, to_remove)\n', (2107, 2133), True, 'import numpy as np\n'), ((2336, 2355), 'numpy.argsort', 'np.argsort', (['D[:, 0]'], {}), '(D[:, 0])\n', (2346, 2355), True, 'import numpy as np\n'), ((2438, 2467), 'sklearn.metrics.pairwise.cosine_similarity', 'cosine_similarity', (['items_temp'], {}), '(items_temp)\n', (2455, 2467), False, 'from sklearn.metrics.pairwise import euclidean_distances, cosine_similarity, manhattan_distances\n'), ((3835, 3875), 'numpy.isin', 'np.isin', (["items_temp['title']", 'temp_title'], {}), "(items_temp['title'], temp_title)\n", (3842, 3875), True, 'import numpy as np\n'), ((3894, 3923), 'pandas.concat', 'pd.concat', (['[temp, items_temp]'], {}), '([temp, items_temp])\n', (3903, 3923), True, 'import pandas as pd\n'), ((4339, 4372), 'numpy.isin', 'np.isin', (['items.columns', 'to_remove'], {}), '(items.columns, to_remove)\n', (4346, 4372), True, 'import numpy as np\n'), ((4615, 4648), 'sklearn.metrics.pairwise.euclidean_distances', 'euclidean_distances', (['items_temp_1'], {}), '(items_temp_1)\n', (4634, 4648), False, 'from sklearn.metrics.pairwise import euclidean_distances, cosine_similarity, manhattan_distances\n'), ((991, 1035), 'numpy.isin', 'np.isin', (["items['language']", "temp['language']"], {}), "(items['language'], temp['language'])\n", (998, 1035), True, 'import numpy as np\n'), ((2488, 2508), 'numpy.argsort', 'np.argsort', (['(-D[:, 0])'], {}), '(-D[:, 0])\n', (2498, 2508), True, 'import numpy as np\n'), ((2590, 2621), 'sklearn.metrics.pairwise.manhattan_distances', 'manhattan_distances', (['items_temp'], {}), '(items_temp)\n', (2609, 2621), False, 'from sklearn.metrics.pairwise import euclidean_distances, cosine_similarity, manhattan_distances\n'), ((4023, 4072), 'numpy.isin', 'np.isin', (["items_temp['language']", "temp['language']"], {}), "(items_temp['language'], temp['language'])\n", (4030, 4072), True, 'import numpy as np\n'), ((4673, 4692), 'numpy.argsort', 'np.argsort', (['D[:, 0]'], {}), '(D[:, 0])\n', (4683, 4692), True, 'import numpy as np\n'), ((4783, 4814), 'sklearn.metrics.pairwise.cosine_similarity', 'cosine_similarity', (['items_temp_1'], {}), '(items_temp_1)\n', (4800, 4814), False, 'from sklearn.metrics.pairwise import euclidean_distances, cosine_similarity, manhattan_distances\n'), ((1081, 1135), 'numpy.isin', 'np.isin', (["items['general_topic']", "temp['general_topic']"], {}), "(items['general_topic'], temp['general_topic'])\n", (1088, 1135), True, 'import numpy as np\n'), ((2642, 2661), 'numpy.argsort', 'np.argsort', (['D[:, 0]'], {}), '(D[:, 0])\n', (2652, 2661), True, 'import numpy as np\n'), ((4839, 4859), 'numpy.argsort', 'np.argsort', (['(-D[:, 0])'], {}), '(-D[:, 0])\n', (4849, 4859), True, 'import numpy as np\n'), ((4957, 4990), 'sklearn.metrics.pairwise.manhattan_distances', 'manhattan_distances', (['items_temp_1'], {}), '(items_temp_1)\n', (4976, 4990), False, 'from sklearn.metrics.pairwise import euclidean_distances, cosine_similarity, manhattan_distances\n'), ((5015, 5034), 'numpy.argsort', 'np.argsort', (['D[:, 0]'], {}), '(D[:, 0])\n', (5025, 5034), True, 'import numpy as np\n'), ((1312, 1370), 'numpy.isin', 'np.isin', (["items['general_topic_3']", "temp['general_topic_3']"], {}), "(items['general_topic_3'], temp['general_topic_3'])\n", (1319, 1370), True, 'import numpy as np\n'), ((1459, 1517), 'numpy.isin', 'np.isin', (["items['general_topic_2']", "temp['general_topic_2']"], {}), "(items['general_topic_2'], temp['general_topic_2'])\n", (1466, 1517), True, 'import numpy as np\n'), ((1590, 1648), 'numpy.isin', 'np.isin', (["items['general_topic_2']", "temp['general_topic_2']"], {}), "(items['general_topic_2'], temp['general_topic_2'])\n", (1597, 1648), True, 'import numpy as np\n'), ((1770, 1824), 'numpy.isin', 'np.isin', (["items['general_topic']", "temp['general_topic']"], {}), "(items['general_topic'], temp['general_topic'])\n", (1777, 1824), True, 'import numpy as np\n')]
|
# coding: utf8
# Copyright (c) <NAME>, University of Antwerp
# Distributed under the terms of the MIT License
import os
import numpy as np
from fireworks import Firework, LaunchPad, PyTask, Workflow
from pymongo.errors import ServerSelectionTimeoutError
from ruamel.yaml import YAML
from pybat.cli.commands.define import define_dimer, define_migration
from pybat.cli.commands.setup import transition
from pybat.core import Cathode, LiRichCathode, Dimer
from pybat.workflow.firetasks import VaspTask, CustodianTask, ConfigurationTask, \
EnergyConfTask
from pybat.workflow.fireworks import ScfFirework, RelaxFirework, NebFirework
"""
Package that contains all the Workflows of the pybat package.
"""
__author__ = "<NAME>"
__copyright__ = "Copyright 2019, <NAME>, University of Antwerp"
__version__ = "alpha"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__date__ = "Mar 2019"
# Load the workflow configuration
CONFIG_FILE = os.path.join(os.path.expanduser("~"), ".pybat_wf_config.yaml")
if os.path.exists(CONFIG_FILE):
with open(CONFIG_FILE, 'r') as configfile:
yaml = YAML()
yaml.default_flow_style = False
CONFIG = yaml.load(configfile.read())
try:
LAUNCHPAD = LaunchPad(
host=CONFIG["SERVER"].get("host", ""),
port=int(CONFIG["SERVER"].get("port", 0)),
name=CONFIG["SERVER"].get("name", ""),
username=CONFIG["SERVER"].get("username", ""),
password=CONFIG["SERVER"].get("password", ""),
ssl=CONFIG["SERVER"].get("ssl", False),
authsource=CONFIG["SERVER"].get("authsource", None)
)
except ServerSelectionTimeoutError:
raise TimeoutError("Could not connect to server. Please make "
"sure the details of the server are correctly "
"set up.")
else:
raise FileNotFoundError("No configuration file found in user's home "
"directory. Please use pybat config "
"in order to set up the configuration for "
"the workflows.")
# TODO Extend configuration and make the whole configuration setup more user friendly
# Currently the user is not guided to the workflow setup when attempting to use
# pybat workflows, this should change and be tested. Moreover, careful additions should
# be made to make sure all user-specific configuration elements are easily configured
# and implemented in the code.
# TODO Fix the CustodianTask
# TODO Add UnitTests!
# It's really getting time to do this. Think about what unit tests you need and make a
# test suite.
def scf_workflow(structure_file, functional=("pbe", {}), directory="",
write_chgcar=False, in_custodian=False, number_nodes=None):
"""
Set up a self consistent field calculation (SCF) workflow and add it to the
launchpad of the mongoDB server defined in the config file.
Args:
structure_file (str): Path to the geometry file of the structure.
functional (tuple): Tuple with the functional choices. The first element
contains a string that indicates the functional used ("pbe", "hse", ...),
whereas the second element contains a dictionary that allows the user
to specify the various functional tags.
directory (str): Directory in which the SCF calculation should be performed.
write_chgcar (bool): Flag that indicates whether the CHGCAR file should
be written.
in_custodian (bool): Flag that indicates whether the calculation should be
run inside a Custodian.
number_nodes (int): Number of nodes that should be used for the calculations.
Is required to add the proper `_category` to the Firework generated, so
it is picked up by the right Fireworker.
Returns:
None
"""
# Set up the calculation directory
if directory == "":
directory = os.path.join(os.getcwd(), functional[0])
if functional[0] == "pbeu":
directory += "_" + "".join(k + str(functional[1]["LDAUU"][k]) for k
in functional[1]["LDAUU"].keys())
directory += "_scf"
# Set up the SCF Firework
scf_firework = ScfFirework(
structure_file=structure_file, functional=functional,
directory=directory, write_chgcar=write_chgcar,
in_custodian=in_custodian, number_nodes=number_nodes
)
# Set up a clear name for the workflow
cathode = LiRichCathode.from_file(structure_file)
workflow_name = str(cathode.composition.reduced_formula).replace(" ", "")
workflow_name += str(functional)
# Create the workflow
workflow = Workflow(fireworks=[scf_firework, ],
name=workflow_name)
LAUNCHPAD.add_wf(workflow)
def relax_workflow(structure_file, functional=("pbe", {}), directory="",
is_metal=False, in_custodian=False, number_nodes=None):
"""
Set up a geometry optimization workflow and add it to the launchpad of the
mongoDB server defined in the config file.
Args:
structure_file (str): Path to the geometry file of the structure.
functional (tuple): Tuple with the functional choices. The first element
contains a string that indicates the functional used ("pbe", "hse", ...),
whereas the second element contains a dictionary that allows the user
to specify the various functional tags.
directory (str): Directory in which the SCF calculation should be performed.
is_metal (bool): Flag that indicates whether the material for which the
geometry optimization should be performed is metallic. Determines the
smearing method used.
in_custodian (bool): Flag that indicates wheter the calculation should be
run inside a Custodian.
number_nodes (int): Number of nodes that should be used for the calculations.
Is required to add the proper `_category` to the Firework generated, so
it is picked up by the right Fireworker.
Returns:
None
"""
# Set up the calculation directory
if directory == "":
directory = os.path.join(os.getcwd(), functional[0])
if functional[0] == "pbeu":
directory += "_" + "".join(k + str(functional[1]["LDAUU"][k]) for k
in functional[1]["LDAUU"].keys())
directory += "_relax"
# Set up the geometry optimization Firework
relax_firework = RelaxFirework(structure_file=structure_file,
functional=functional,
directory=directory,
is_metal=is_metal,
in_custodian=in_custodian,
number_nodes=number_nodes)
# Set up a clear name for the workflow
cathode = LiRichCathode.from_file(structure_file)
workflow_name = str(cathode.composition.reduced_formula).replace(" ", "")
workflow_name += str(functional)
# Create the workflow
workflow = Workflow(fireworks=[relax_firework, ],
name=workflow_name)
LAUNCHPAD.add_wf(workflow)
def dimer_workflow(structure_file, dimer_indices=(0, 0), distance=0,
functional=("pbe", {}), is_metal=False, in_custodian=False,
number_nodes=None):
"""
Set up a workflow that calculates the thermodynamics for a dimer
formation in the current directory.
Can later be expanded to also include kinetic barrier calculation.
Args:
structure_file (str): Structure file of the cathode material. Note
that the structure file should be a json format file that is
derived from the Cathode class, i.e. it should contain the cation
configuration of the structure.
dimer_indices (tuple): Indices of the oxygen sites which are to form a
dimer. If no indices are provided, the user will be prompted.
distance (float): Final distance between the oxygen atoms. If no
distance is provided, the user will be prompted.
functional (tuple): Tuple with the functional choices. The first element
contains a string that indicates the functional used ("pbe", "hse", ...),
whereas the second element contains a dictionary that allows the user
to specify the various functional tags.
is_metal (bool): Flag that indicates the material being studied is a
metal, which changes the smearing from Gaussian to second order
Methfessel-Paxton of 0.2 eV. Defaults to False.
in_custodian (bool): Flag that indicates that the calculations
should be run within a Custodian. Defaults to False.
number_nodes (int): Number of nodes that should be used for the calculations.
Is required to add the proper `_category` to the Firework generated, so
it is picked up by the right Fireworker.
"""
# TODO Change naming scheme
# Let the user define a dimer, unless one is provided
dimer_dir = define_dimer(structure_file=structure_file,
dimer_indices=dimer_indices,
distance=distance,
write_cif=True)
# Set up the FireTask that sets up the transition calculation
setup_transition = PyTask(
func="pybat.cli.commands.setup.transition",
kwargs={"directory": dimer_dir,
"functional": functional,
"is_metal": is_metal,
"is_migration": False}
)
# Create the PyTask that runs the calculation
if in_custodian:
vasprun = CustodianTask(directory=os.path.join(dimer_dir, "final"))
else:
vasprun = VaspTask(directory=os.path.join(dimer_dir, "final"))
# Extract the final cathode from the geometry optimization
get_cathode = PyTask(
func="pybat.cli.commands.get.get_cathode",
kwargs={"directory": os.path.join(dimer_dir, "final"),
"write_cif": True}
)
# Add number of nodes to spec, or "none"
firework_spec = {"_launch_dir": os.getcwd()}
if number_nodes is None:
firework_spec.update({"_category": "none"})
else:
firework_spec.update({"_category": str(number_nodes) + "nodes"})
transition_firework = Firework(tasks=[setup_transition, vasprun, get_cathode],
name="Dimer Geometry optimization",
spec=firework_spec)
# Set up the SCF calculation directory
scf_dir = os.path.join(dimer_dir, "scf_final")
final_cathode = os.path.join(dimer_dir, "final", "final_cathode.json")
# Set up the SCF calculation
scf_firework = ScfFirework(
structure_file=final_cathode, functional=functional,
directory=scf_dir, write_chgcar=False, in_custodian=in_custodian,
number_nodes=number_nodes
)
workflow = Workflow(fireworks=[transition_firework, scf_firework],
name=structure_file + dimer_dir.split("/")[-1],
links_dict={transition_firework: [scf_firework]})
LAUNCHPAD.add_wf(workflow)
def migration_workflow(structure_file, migration_indices=(0, 0),
functional=("pbe", {}), is_metal=False,
in_custodian=False, number_nodes=None):
"""
Set up a workflow that calculates the thermodynamics for a migration in
the current directory.
Can later be expanded to also include kinetic barrier calculation.
Args:
structure_file (str): Structure file of the cathode material. Note
that the structure file should be a json format file that is
derived from the Cathode class, i.e. it should contain the cation
configuration of the structure.
migration_indices (tuple): Tuple of the indices which designate the
migrating site and the vacant site to which the cation will
migrate. If no indices are provided, the user will be prompted.
functional (tuple): Tuple with the functional choices. The first element
contains a string that indicates the functional used ("pbe", "hse", ...),
whereas the second element contains a dictionary that allows the user
to specify the various functional tags.
is_metal (bool): Flag that indicates the material being studied is a
metal, which changes the smearing from Gaussian to second order
Methfessel-Paxton of 0.2 eV. Defaults to False.
in_custodian (bool): Flag that indicates that the calculations
should be run within a Custodian. Defaults to False.
number_nodes (int): Number of nodes that should be used for the calculations.
Is required to add the proper `_category` to the Firework generated, so
it is picked up by the right Fireworker.
"""
# TODO Add setup steps to the workflow
# In case adjustments need to made to the setup of certain calculations,
# after which the calculation needs to be rerun, not adding the setup
# steps to the workflow means that these will have to be rerun manually,
# instead of simply relying on the fireworks commands.
# Let the user define a migration
migration_dir = define_migration(structure_file=structure_file,
migration_indices=migration_indices,
write_cif=True)
# Set up the transition calculation
transition(directory=migration_dir,
functional=functional,
is_metal=is_metal,
is_migration=False)
# Create the PyTask that runs the calculation
if in_custodian:
vasprun = CustodianTask(directory=os.path.join(migration_dir, "final"))
else:
vasprun = VaspTask(directory=os.path.join(migration_dir, "final"))
# Add number of nodes to spec, or "none"
firework_spec = {"_launch_dir": os.getcwd()}
if number_nodes is None:
firework_spec.update({"_category": "none"})
else:
firework_spec.update({"_category": str(number_nodes) + "nodes"})
transition_firework = Firework(tasks=[vasprun],
name="Migration Geometry optimization",
spec=firework_spec)
workflow = Workflow(fireworks=[transition_firework],
name=structure_file + migration_dir.split("/")[-1])
LAUNCHPAD.add_wf(workflow)
def neb_workflow(directory, nimages=7, functional=("pbe", {}), is_metal=False,
is_migration=False, in_custodian=False,
number_nodes=None):
"""
Set up a workflow that calculates the kinetic barrier between two geometries.
# TODO
TEMPORARY? Should NEB be integrated in other workflows? If so, should we still
have a separate NEB workflow?
Args:
directory (str): Directory in which the NEB calculation should be performed.
nimages (int): Number of images to use for the NEB calculation.
functional (tuple): Tuple with the functional choices. The first element
contains a string that indicates the functional used ("pbe", "hse", ...),
whereas the second element contains a dictionary that allows the user
to specify the various functional tags.
is_metal (bool): Flag that indicates the material being studied is a
metal, which changes the smearing from Gaussian to second order
Methfessel-Paxton of 0.2 eV. Defaults to False.
is_migration (bool): Flag that indicates that the transition is a migration
of an atom in the structure.
in_custodian (bool): Flag that indicates that the calculations
should be run within a Custodian. Defaults to False.
number_nodes (int): Number of nodes that should be used for the calculations.
Is required to add the proper `_category` to the Firework generated, so
it is picked up by the right Fireworker. Defaults to the number of images.
"""
# If no number of nodes is specified, take the number of images
if number_nodes is None:
number_nodes = nimages
# Create the Firework that sets up and runs the NEB
neb_firework = NebFirework(
directory=directory,
nimages=nimages,
functional=functional,
is_metal=is_metal,
is_migration=is_migration,
in_custodian=in_custodian,
number_nodes=number_nodes
)
# Add number of nodes to spec, or "none"
firework_spec = {"_launch_dir": os.getcwd()}
if number_nodes is None:
firework_spec.update({"_category": "none"})
else:
firework_spec.update({"_category": str(number_nodes) + "nodes"})
cathode = Cathode.from_file(
os.path.join(directory, "final", "initial_cathode.json")
)
dir_name = os.path.abspath(directory).split("/")[-1]
workflow_name = str(cathode.composition).replace(" ", "") + " " + dir_name
workflow = Workflow(fireworks=[neb_firework, ],
name=workflow_name)
LAUNCHPAD.add_wf(workflow)
def configuration_workflow(structure_file, substitution_sites=None, element_list=None,
sizes=None, concentration_restrictions=None,
max_configurations=None, functional=("pbe", {}),
directory=None, in_custodian=False, number_nodes=None):
"""
Set up a workflow for a set of atomic configurations, which includes a geometric
optimization as well as a SCF calculation based on the final geometry.
Args:
structure_file (str): Structure file of the cathode material. Note
that the structure file should be a json format file that is
derived from the Cathode class, i.e. it should contain the cation
configuration of the structure.
substitution_sites (list): List of site indices or pymatgen.Sites to be
substituted.
element_list (list): List of string representations of the cation elements
which have to be substituted on the substitution sites. Can also
include "Vac" to introduce vacancy sites.
E.g. ["Li", "Vac"]; ["Mn", "Co", "Ni"]; ...
sizes (list): List of unit supercell sizes to be considered for the
enumeration of the configurations.
E.g. [1, 2]; range(1, 4); ...
concentration_restrictions (dict): Dictionary of allowed concentration
ranges for each element. Note that the concentration is defined
versus the total amount of atoms in the unit cell.
E.g. {"Li": (0.2, 0.3)}; {"Ni": (0.1, 0.2, "Mn": (0.05, 0.1)}; ...
max_configurations (int): Maximum number of new configurations to generate.
Note that the function detects all the cathode.json files present
in the directory tree and ignores the corresponding configurations.
max_configurations is the maximum number of new configurations that need
to be generated, i.e. on top of the configurations already present in the
directory tree in the form of cathode.json files.
functional (tuple): Tuple with the functional choices. The first element
contains a string that indicates the functional used ("pbe", "hse", ...),
whereas the second element contains a dictionary that allows the user
to specify the various functional tags.
directory (str): Path to the directory in which the configurations and
calculations should be set up.
in_custodian (bool): Flag that indicates that the calculations
should be run within a Custodian. Defaults to False.
number_nodes (int): Number of nodes that should be used for the calculations.
Is required to add the proper `_category` to the Firework generated, so
it is picked up by the right Fireworker.
Returns:
None
"""
# Load the cathode from the structure file
cathode = Cathode.from_file(structure_file)
# Check for the required input, and request if necessary
if not substitution_sites or not element_list or not sizes:
print(cathode)
print()
if not substitution_sites:
substitution_sites = [int(i) for i in input(
"Please provide the substitution site indices, separated by a space: "
).split(" ")]
if not element_list:
element_list = [i for i in input(
"Please provide the substitution elements, separated by a space: "
).split(" ")]
if not sizes:
sizes = [int(i) for i in input(
"Please provide the possible unit cell sizes, separated by a space: "
).split(" ")]
# Set up the directory
if directory == "":
directory = os.getcwd()
directory = os.path.abspath(directory)
configuration_task = ConfigurationTask(
structure=cathode,
directory=directory,
substitution_sites=list(substitution_sites),
element_list=element_list,
sizes=list(sizes),
concentration_restrictions=concentration_restrictions,
max_configurations=max_configurations
)
energy_task = EnergyConfTask(
functional=functional,
in_custodian=in_custodian,
number_nodes=number_nodes
)
# Set up a (sort of) clear name for the workflow
workflow_name = str(cathode.composition.reduced_formula).replace(" ", "")
workflow_name += " " + str(element_list)
workflow_name += " " + str(functional)
configuration_fw = Firework(tasks=[configuration_task, energy_task],
name="Configuration Setup",
spec={"_category": "none"})
# Create the workflow
workflow = Workflow(
fireworks=[configuration_fw],
name=workflow_name
)
LAUNCHPAD.add_wf(workflow)
def noneq_dimers_workflow(structure_file, distance, functional=("pbe", {}),
is_metal=False, in_custodian=False, number_nodes=None):
"""
Run dimer calculations for all the nonequivalent dimers in a structure.
Args:
structure_file (str): Structure file of the cathode material. Note
that the structure file should be a json format file that is
derived from the Cathode class, i.e. it should contain the cation
configuration of the structure.
distance (float): Final distance between the oxygen atoms. If no
distance is provided, the user will be prompted.
functional (tuple): Tuple with the functional choices. The first element
contains a string that indicates the functional used ("pbe", "hse", ...),
whereas the second element contains a dictionary that allows the user
to specify the various functional tags.
is_metal (bool): Flag that indicates the material being studied is a
metal, which changes the smearing from Gaussian to second order
Methfessel-Paxton of 0.2 eV. Defaults to False.
in_custodian (bool): Flag that indicates that the calculations
should be run within a Custodian. Defaults to False.
number_nodes (int): Number of nodes that should be used for the calculations.
Is required to add the proper `_category` to the Firework generated, so
it is picked up by the right Fireworker.
Returns:
None
"""
lirich = LiRichCathode.from_file(structure_file)
dimer_lists = lirich.list_noneq_dimers()
for dimer_list in dimer_lists:
# Find the dimer closest to the center of the lattice. Just for
# visualization purposes.
central_dimer = [(), 1e10]
for dimer in dimer_list:
dimer_center = Dimer(lirich, dimer).center
lattice_center = np.sum(lirich.lattice.matrix, 0) / 3
dist_to_center = np.linalg.norm(dimer_center - lattice_center)
if dist_to_center < central_dimer[1]:
central_dimer = [dimer, dist_to_center]
dimer_workflow(structure_file=structure_file,
dimer_indices=central_dimer[0],
distance=distance,
functional=functional,
is_metal=is_metal,
in_custodian=in_custodian,
number_nodes=number_nodes)
def site_dimers_workflow(structure_file, site_index, distance,
functional=("pbe", {}), is_metal=False,
in_custodian=False, number_nodes=None):
"""
Run dimer calculations for all the dimers around a site.
Args:
structure_file (str): Structure file of the cathode material. Note
that the structure file should be a json format file that is
derived from the Cathode class, i.e. it should contain the cation
configuration of the structure.
site_index (int): Index of the site around which the dimers should
be investigated. Corresponds to the internal Python index.
distance (float): Final distance between the oxygen atoms. If no
distance is provided, the user will be prompted.
functional (tuple): Tuple with the functional choices. The first element
contains a string that indicates the functional used ("pbe", "hse", ...),
whereas the second element contains a dictionary that allows the user
to specify the various functional tags.
is_metal (bool): Flag that indicates the material being studied is a
metal, which changes the smearing from Gaussian to second order
Methfessel-Paxton of 0.2 eV. Defaults to False.
in_custodian (bool): Flag that indicates that the calculations
should be run within a Custodian. Defaults to False.
number_nodes (int): Number of nodes that should be used for the calculations.
Is required to add the proper `_category` to the Firework generated, so
it is picked up by the right Fireworker.
Returns:
None
"""
lirich = LiRichCathode.from_file(structure_file)
dimer_list = lirich.find_noneq_dimers(int(site_index))
for dimer in dimer_list:
dimer_workflow(structure_file=structure_file,
dimer_indices=dimer,
distance=distance,
functional=functional,
is_metal=is_metal,
in_custodian=in_custodian,
number_nodes=number_nodes)
# region * Utility scripts
def find_all(name, path):
result = []
for root, dirs, files in os.walk(path):
if name in files:
result.append(os.path.join(root, name))
return result
def find_all_cathode_hashes(path):
return [Cathode.from_file(file).__hash__() for file in find_all("cathode.json", path)]
def find_hash_dict(path):
path = os.path.abspath(path)
return {Cathode.from_file(file).__hash__(): file.replace(path, "").replace(
"cathode.json", "")
for file in find_all("cathode.json", path)}
def generate_conf_dir(directory, element_list, configuration, number):
if "Vac" in element_list:
# Set up Li configuration directory
conf_dir = os.path.join(
directory, "tm_conf_1",
str(round(configuration.concentration, 3)),
"workion_conf" + str(number), "prim"
)
else:
# Set up TM configuration directory
try:
conf_dir = os.path.join(
directory, "tm_conf_" + str(number),
str(round(configuration.concentration, 3)), "workion_conf1",
"prim"
)
except ZeroDivisionError:
conf_dir = os.path.join(
directory, "tm_conf_" + str(number), "prim"
)
return conf_dir
# endregion
# region * Token workflows for testing
# endregion
|
[
"numpy.sum",
"fireworks.Workflow",
"os.walk",
"numpy.linalg.norm",
"os.path.join",
"os.path.abspath",
"pybat.core.LiRichCathode.from_file",
"os.path.exists",
"ruamel.yaml.YAML",
"pybat.cli.commands.setup.transition",
"pybat.workflow.fireworks.RelaxFirework",
"pybat.workflow.fireworks.NebFirework",
"pybat.workflow.firetasks.EnergyConfTask",
"pybat.cli.commands.define.define_migration",
"pybat.workflow.fireworks.ScfFirework",
"fireworks.PyTask",
"pybat.core.Dimer",
"pybat.core.Cathode.from_file",
"os.getcwd",
"fireworks.Firework",
"pybat.cli.commands.define.define_dimer",
"os.path.expanduser"
] |
[((1002, 1029), 'os.path.exists', 'os.path.exists', (['CONFIG_FILE'], {}), '(CONFIG_FILE)\n', (1016, 1029), False, 'import os\n'), ((948, 971), 'os.path.expanduser', 'os.path.expanduser', (['"""~"""'], {}), "('~')\n", (966, 971), False, 'import os\n'), ((4347, 4523), 'pybat.workflow.fireworks.ScfFirework', 'ScfFirework', ([], {'structure_file': 'structure_file', 'functional': 'functional', 'directory': 'directory', 'write_chgcar': 'write_chgcar', 'in_custodian': 'in_custodian', 'number_nodes': 'number_nodes'}), '(structure_file=structure_file, functional=functional, directory\n =directory, write_chgcar=write_chgcar, in_custodian=in_custodian,\n number_nodes=number_nodes)\n', (4358, 4523), False, 'from pybat.workflow.fireworks import ScfFirework, RelaxFirework, NebFirework\n'), ((4603, 4642), 'pybat.core.LiRichCathode.from_file', 'LiRichCathode.from_file', (['structure_file'], {}), '(structure_file)\n', (4626, 4642), False, 'from pybat.core import Cathode, LiRichCathode, Dimer\n'), ((4800, 4854), 'fireworks.Workflow', 'Workflow', ([], {'fireworks': '[scf_firework]', 'name': 'workflow_name'}), '(fireworks=[scf_firework], name=workflow_name)\n', (4808, 4854), False, 'from fireworks import Firework, LaunchPad, PyTask, Workflow\n'), ((6655, 6824), 'pybat.workflow.fireworks.RelaxFirework', 'RelaxFirework', ([], {'structure_file': 'structure_file', 'functional': 'functional', 'directory': 'directory', 'is_metal': 'is_metal', 'in_custodian': 'in_custodian', 'number_nodes': 'number_nodes'}), '(structure_file=structure_file, functional=functional,\n directory=directory, is_metal=is_metal, in_custodian=in_custodian,\n number_nodes=number_nodes)\n', (6668, 6824), False, 'from pybat.workflow.fireworks import ScfFirework, RelaxFirework, NebFirework\n'), ((7050, 7089), 'pybat.core.LiRichCathode.from_file', 'LiRichCathode.from_file', (['structure_file'], {}), '(structure_file)\n', (7073, 7089), False, 'from pybat.core import Cathode, LiRichCathode, Dimer\n'), ((7247, 7303), 'fireworks.Workflow', 'Workflow', ([], {'fireworks': '[relax_firework]', 'name': 'workflow_name'}), '(fireworks=[relax_firework], name=workflow_name)\n', (7255, 7303), False, 'from fireworks import Firework, LaunchPad, PyTask, Workflow\n'), ((9297, 9408), 'pybat.cli.commands.define.define_dimer', 'define_dimer', ([], {'structure_file': 'structure_file', 'dimer_indices': 'dimer_indices', 'distance': 'distance', 'write_cif': '(True)'}), '(structure_file=structure_file, dimer_indices=dimer_indices,\n distance=distance, write_cif=True)\n', (9309, 9408), False, 'from pybat.cli.commands.define import define_dimer, define_migration\n'), ((9582, 9744), 'fireworks.PyTask', 'PyTask', ([], {'func': '"""pybat.cli.commands.setup.transition"""', 'kwargs': "{'directory': dimer_dir, 'functional': functional, 'is_metal': is_metal,\n 'is_migration': False}"}), "(func='pybat.cli.commands.setup.transition', kwargs={'directory':\n dimer_dir, 'functional': functional, 'is_metal': is_metal,\n 'is_migration': False})\n", (9588, 9744), False, 'from fireworks import Firework, LaunchPad, PyTask, Workflow\n'), ((10567, 10684), 'fireworks.Firework', 'Firework', ([], {'tasks': '[setup_transition, vasprun, get_cathode]', 'name': '"""Dimer Geometry optimization"""', 'spec': 'firework_spec'}), "(tasks=[setup_transition, vasprun, get_cathode], name=\n 'Dimer Geometry optimization', spec=firework_spec)\n", (10575, 10684), False, 'from fireworks import Firework, LaunchPad, PyTask, Workflow\n'), ((10808, 10844), 'os.path.join', 'os.path.join', (['dimer_dir', '"""scf_final"""'], {}), "(dimer_dir, 'scf_final')\n", (10820, 10844), False, 'import os\n'), ((10866, 10920), 'os.path.join', 'os.path.join', (['dimer_dir', '"""final"""', '"""final_cathode.json"""'], {}), "(dimer_dir, 'final', 'final_cathode.json')\n", (10878, 10920), False, 'import os\n'), ((10974, 11141), 'pybat.workflow.fireworks.ScfFirework', 'ScfFirework', ([], {'structure_file': 'final_cathode', 'functional': 'functional', 'directory': 'scf_dir', 'write_chgcar': '(False)', 'in_custodian': 'in_custodian', 'number_nodes': 'number_nodes'}), '(structure_file=final_cathode, functional=functional, directory=\n scf_dir, write_chgcar=False, in_custodian=in_custodian, number_nodes=\n number_nodes)\n', (10985, 11141), False, 'from pybat.workflow.fireworks import ScfFirework, RelaxFirework, NebFirework\n'), ((13567, 13672), 'pybat.cli.commands.define.define_migration', 'define_migration', ([], {'structure_file': 'structure_file', 'migration_indices': 'migration_indices', 'write_cif': '(True)'}), '(structure_file=structure_file, migration_indices=\n migration_indices, write_cif=True)\n', (13583, 13672), False, 'from pybat.cli.commands.define import define_dimer, define_migration\n'), ((13787, 13889), 'pybat.cli.commands.setup.transition', 'transition', ([], {'directory': 'migration_dir', 'functional': 'functional', 'is_metal': 'is_metal', 'is_migration': '(False)'}), '(directory=migration_dir, functional=functional, is_metal=\n is_metal, is_migration=False)\n', (13797, 13889), False, 'from pybat.cli.commands.setup import transition\n'), ((14453, 14543), 'fireworks.Firework', 'Firework', ([], {'tasks': '[vasprun]', 'name': '"""Migration Geometry optimization"""', 'spec': 'firework_spec'}), "(tasks=[vasprun], name='Migration Geometry optimization', spec=\n firework_spec)\n", (14461, 14543), False, 'from fireworks import Firework, LaunchPad, PyTask, Workflow\n'), ((16582, 16762), 'pybat.workflow.fireworks.NebFirework', 'NebFirework', ([], {'directory': 'directory', 'nimages': 'nimages', 'functional': 'functional', 'is_metal': 'is_metal', 'is_migration': 'is_migration', 'in_custodian': 'in_custodian', 'number_nodes': 'number_nodes'}), '(directory=directory, nimages=nimages, functional=functional,\n is_metal=is_metal, is_migration=is_migration, in_custodian=in_custodian,\n number_nodes=number_nodes)\n', (16593, 16762), False, 'from pybat.workflow.fireworks import ScfFirework, RelaxFirework, NebFirework\n'), ((17333, 17387), 'fireworks.Workflow', 'Workflow', ([], {'fireworks': '[neb_firework]', 'name': 'workflow_name'}), '(fireworks=[neb_firework], name=workflow_name)\n', (17341, 17387), False, 'from fireworks import Firework, LaunchPad, PyTask, Workflow\n'), ((20407, 20440), 'pybat.core.Cathode.from_file', 'Cathode.from_file', (['structure_file'], {}), '(structure_file)\n', (20424, 20440), False, 'from pybat.core import Cathode, LiRichCathode, Dimer\n'), ((21225, 21251), 'os.path.abspath', 'os.path.abspath', (['directory'], {}), '(directory)\n', (21240, 21251), False, 'import os\n'), ((21602, 21697), 'pybat.workflow.firetasks.EnergyConfTask', 'EnergyConfTask', ([], {'functional': 'functional', 'in_custodian': 'in_custodian', 'number_nodes': 'number_nodes'}), '(functional=functional, in_custodian=in_custodian,\n number_nodes=number_nodes)\n', (21616, 21697), False, 'from pybat.workflow.firetasks import VaspTask, CustodianTask, ConfigurationTask, EnergyConfTask\n'), ((21968, 22078), 'fireworks.Firework', 'Firework', ([], {'tasks': '[configuration_task, energy_task]', 'name': '"""Configuration Setup"""', 'spec': "{'_category': 'none'}"}), "(tasks=[configuration_task, energy_task], name=\n 'Configuration Setup', spec={'_category': 'none'})\n", (21976, 22078), False, 'from fireworks import Firework, LaunchPad, PyTask, Workflow\n'), ((22180, 22238), 'fireworks.Workflow', 'Workflow', ([], {'fireworks': '[configuration_fw]', 'name': 'workflow_name'}), '(fireworks=[configuration_fw], name=workflow_name)\n', (22188, 22238), False, 'from fireworks import Firework, LaunchPad, PyTask, Workflow\n'), ((23875, 23914), 'pybat.core.LiRichCathode.from_file', 'LiRichCathode.from_file', (['structure_file'], {}), '(structure_file)\n', (23898, 23914), False, 'from pybat.core import Cathode, LiRichCathode, Dimer\n'), ((26565, 26604), 'pybat.core.LiRichCathode.from_file', 'LiRichCathode.from_file', (['structure_file'], {}), '(structure_file)\n', (26588, 26604), False, 'from pybat.core import Cathode, LiRichCathode, Dimer\n'), ((27123, 27136), 'os.walk', 'os.walk', (['path'], {}), '(path)\n', (27130, 27136), False, 'import os\n'), ((27401, 27422), 'os.path.abspath', 'os.path.abspath', (['path'], {}), '(path)\n', (27416, 27422), False, 'import os\n'), ((1093, 1099), 'ruamel.yaml.YAML', 'YAML', ([], {}), '()\n', (1097, 1099), False, 'from ruamel.yaml import YAML\n'), ((10363, 10374), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (10372, 10374), False, 'import os\n'), ((14249, 14260), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (14258, 14260), False, 'import os\n'), ((16899, 16910), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (16908, 16910), False, 'import os\n'), ((17118, 17174), 'os.path.join', 'os.path.join', (['directory', '"""final"""', '"""initial_cathode.json"""'], {}), "(directory, 'final', 'initial_cathode.json')\n", (17130, 17174), False, 'import os\n'), ((21197, 21208), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (21206, 21208), False, 'import os\n'), ((4052, 4063), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (4061, 4063), False, 'import os\n'), ((6338, 6349), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (6347, 6349), False, 'import os\n'), ((24324, 24369), 'numpy.linalg.norm', 'np.linalg.norm', (['(dimer_center - lattice_center)'], {}), '(dimer_center - lattice_center)\n', (24338, 24369), True, 'import numpy as np\n'), ((9921, 9953), 'os.path.join', 'os.path.join', (['dimer_dir', '"""final"""'], {}), "(dimer_dir, 'final')\n", (9933, 9953), False, 'import os\n'), ((10002, 10034), 'os.path.join', 'os.path.join', (['dimer_dir', '"""final"""'], {}), "(dimer_dir, 'final')\n", (10014, 10034), False, 'import os\n'), ((10206, 10238), 'os.path.join', 'os.path.join', (['dimer_dir', '"""final"""'], {}), "(dimer_dir, 'final')\n", (10218, 10238), False, 'import os\n'), ((14044, 14080), 'os.path.join', 'os.path.join', (['migration_dir', '"""final"""'], {}), "(migration_dir, 'final')\n", (14056, 14080), False, 'import os\n'), ((14129, 14165), 'os.path.join', 'os.path.join', (['migration_dir', '"""final"""'], {}), "(migration_dir, 'final')\n", (14141, 14165), False, 'import os\n'), ((17196, 17222), 'os.path.abspath', 'os.path.abspath', (['directory'], {}), '(directory)\n', (17211, 17222), False, 'import os\n'), ((24200, 24220), 'pybat.core.Dimer', 'Dimer', (['lirich', 'dimer'], {}), '(lirich, dimer)\n', (24205, 24220), False, 'from pybat.core import Cathode, LiRichCathode, Dimer\n'), ((24257, 24289), 'numpy.sum', 'np.sum', (['lirich.lattice.matrix', '(0)'], {}), '(lirich.lattice.matrix, 0)\n', (24263, 24289), True, 'import numpy as np\n'), ((27190, 27214), 'os.path.join', 'os.path.join', (['root', 'name'], {}), '(root, name)\n', (27202, 27214), False, 'import os\n'), ((27283, 27306), 'pybat.core.Cathode.from_file', 'Cathode.from_file', (['file'], {}), '(file)\n', (27300, 27306), False, 'from pybat.core import Cathode, LiRichCathode, Dimer\n'), ((27435, 27458), 'pybat.core.Cathode.from_file', 'Cathode.from_file', (['file'], {}), '(file)\n', (27452, 27458), False, 'from pybat.core import Cathode, LiRichCathode, Dimer\n')]
|
# -*- coding: utf-8 -*-
"""
.. invisible:
_ _ _____ _ _____ _____
| | | | ___| | | ___/ ___|
| | | | |__ | | | |__ \ `--.
| | | | __|| | | __| `--. \
\ \_/ / |___| |___| |___/\__/ /
\___/\____/\_____|____/\____/
Created on Jan 25, 2015
Loaders which get data from pickles
███████████████████████████████████████████████████████████████████████████████
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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.
███████████████████████████████████████████████████████████████████████████████
"""
import pickle
import numpy
import six
from zope.interface import implementer
from veles import error
from veles.compat import from_none
from veles.external.progressbar import ProgressBar
from veles.memory import interleave
from veles.loader.base import CLASS_NAME, Loader
from veles.loader.image import IImageLoader, COLOR_CHANNELS_MAP
from veles.loader.fullbatch import FullBatchLoader, IFullBatchLoader
from veles.loader.fullbatch_image import FullBatchImageLoader
@implementer(IFullBatchLoader)
class PicklesLoader(FullBatchLoader):
"""
Loads samples from pickles for data set.
"""
def __init__(self, workflow, **kwargs):
super(PicklesLoader, self).__init__(workflow, **kwargs)
self._test_pickles = list(kwargs.get("test_pickles", []))
self._validation_pickles = list(kwargs.get("validation_pickles", []))
self._train_pickles = list(kwargs.get("train_pickles", []))
self._pickles = (self.test_pickles, self.validation_pickles,
self.train_pickles)
@property
def test_pickles(self):
return self._test_pickles
@property
def validation_pickles(self):
return self._validation_pickles
@property
def train_pickles(self):
return self._train_pickles
def reshape(self, shape):
return shape
def transform_data(self, data):
return data
def load_data(self):
pbar = ProgressBar(maxval=sum(len(p) for p in self._pickles),
term_width=40)
self.info("Loading %d pickles...", pbar.maxval)
pbar.start()
loaded = [self.load_pickles(i, self._pickles[i], pbar)
for i in range(3)]
pbar.finish()
self.info("Initializing the arrays...")
shape = loaded[2][1][0].shape[1:]
for i in range(2):
if loaded[i][0] > 0:
shi = loaded[i][1][0].shape[1:]
if shape != shi:
raise error.BadFormatError(
"TRAIN and %s sets have the different sample shape "
"(%s vs %s)" % (CLASS_NAME[i], shape, shi))
self.create_originals(self.reshape(shape))
offsets = [0, 0]
for ds in range(3):
if loaded[ds][0] == 0:
continue
for arr in loaded[ds][1]:
self.original_data[offsets[0]:(offsets[0] + arr.shape[0])] = \
self.transform_data(arr)
offsets[0] += arr.shape[0]
for arr in loaded[ds][2]:
self.original_labels[offsets[1]:(offsets[1] + arr.shape[0])] =\
arr
offsets[1] += arr.shape[0]
def load_pickles(self, index, pickles, pbar):
unpickled = []
for pick in pickles:
try:
with open(pick, "rb") as fin:
self.debug("Loading %s...", pick)
if six.PY3:
loaded = pickle.load(fin, encoding='charmap')
else:
loaded = pickle.load(fin)
unpickled.append(loaded)
pbar.inc()
except Exception as e:
self.warning(
"Failed to load %s (part of %s set)" %
(pick, CLASS_NAME[index]))
raise from_none(e)
data = []
labels = []
for obj, pick in zip(unpickled, pickles):
if not isinstance(obj, dict):
raise TypeError(
"%s has the wrong format (part of %s set)" %
(pick, CLASS_NAME[index]))
try:
data.append(obj["data"])
labels.append(
numpy.array(obj["labels"], dtype=Loader.LABEL_DTYPE))
except KeyError as e:
self.error("%s has the wrong format (part of %s set)",
pick, CLASS_NAME[index])
raise from_none(e)
lengths = [0, sum(len(l) for l in labels)]
for arr in data:
lengths[0] += arr.shape[0]
if arr.shape[1:] != data[0].shape[1:]:
raise error.BadFormatError(
"Array has a different shape: expected %s, got %s"
"(%s set)" % (data[0].shape[1:],
arr.shape[1:], CLASS_NAME[index]))
if lengths[0] != lengths[1]:
raise error.BadFormatError(
"Data and labels has the different number of samples (data %d,"
" labels %d)" % lengths)
length = lengths[0]
self.class_lengths[index] = length
return length, data, labels
@implementer(IImageLoader)
class PicklesImageFullBatchLoader(PicklesLoader, FullBatchImageLoader):
MAPPING = "full_batch_pickles_image"
def __init__(self, workflow, **kwargs):
super(PicklesImageFullBatchLoader, self).__init__(workflow, **kwargs)
# Since we can not extract the color space information from pickles
# set it explicitly without any default value
self.color_space = kwargs["color_space"]
def get_image_label(self, key):
return int(self.image_labels[key])
def get_image_info(self, key):
return self.image_data[key].shape[:2], self.color_space
def get_image_data(self, key):
return self.image_data[key]
def get_keys(self, index):
offsets = [0, self.class_lengths[0],
self.class_lengths[0] + self.class_lengths[1],
self.total_samples]
self.original_shape = self.image_data.shape[1:-1]
return range(offsets[index], offsets[index + 1])
def reshape(self, shape):
if shape[0] == COLOR_CHANNELS_MAP[self.color_space]:
return shape[1:] + (shape[0],)
return shape
def transform_data(self, data):
if data.shape[1] == COLOR_CHANNELS_MAP[self.color_space]:
return interleave(data)
return data
def load_data(self):
PicklesLoader.load_data(self)
self.original_class_lengths = self.class_lengths
self.image_data = self.original_data.mem
self.original_data.mem = None
self.image_labels = self.original_labels[:]
del self.original_labels[:]
FullBatchImageLoader.load_data(self)
assert self.original_class_lengths == self.class_lengths
del self.image_data
def initialize(self, device, **kwargs):
super(PicklesImageFullBatchLoader, self).initialize(
device=device, **kwargs)
del self.image_labels
|
[
"zope.interface.implementer",
"veles.compat.from_none",
"veles.error.BadFormatError",
"numpy.array",
"veles.loader.fullbatch_image.FullBatchImageLoader.load_data",
"pickle.load",
"veles.memory.interleave"
] |
[((1713, 1742), 'zope.interface.implementer', 'implementer', (['IFullBatchLoader'], {}), '(IFullBatchLoader)\n', (1724, 1742), False, 'from zope.interface import implementer\n'), ((5966, 5991), 'zope.interface.implementer', 'implementer', (['IImageLoader'], {}), '(IImageLoader)\n', (5977, 5991), False, 'from zope.interface import implementer\n'), ((7575, 7611), 'veles.loader.fullbatch_image.FullBatchImageLoader.load_data', 'FullBatchImageLoader.load_data', (['self'], {}), '(self)\n', (7605, 7611), False, 'from veles.loader.fullbatch_image import FullBatchImageLoader\n'), ((5713, 5829), 'veles.error.BadFormatError', 'error.BadFormatError', (["('Data and labels has the different number of samples (data %d, labels %d)' %\n lengths)"], {}), "(\n 'Data and labels has the different number of samples (data %d, labels %d)'\n % lengths)\n", (5733, 5829), False, 'from veles import error\n'), ((7234, 7250), 'veles.memory.interleave', 'interleave', (['data'], {}), '(data)\n', (7244, 7250), False, 'from veles.memory import interleave\n'), ((5443, 5589), 'veles.error.BadFormatError', 'error.BadFormatError', (["('Array has a different shape: expected %s, got %s(%s set)' % (data[0].\n shape[1:], arr.shape[1:], CLASS_NAME[index]))"], {}), "(\n 'Array has a different shape: expected %s, got %s(%s set)' % (data[0].\n shape[1:], arr.shape[1:], CLASS_NAME[index]))\n", (5463, 5589), False, 'from veles import error\n'), ((3224, 3348), 'veles.error.BadFormatError', 'error.BadFormatError', (["('TRAIN and %s sets have the different sample shape (%s vs %s)' % (\n CLASS_NAME[i], shape, shi))"], {}), "(\n 'TRAIN and %s sets have the different sample shape (%s vs %s)' % (\n CLASS_NAME[i], shape, shi))\n", (3244, 3348), False, 'from veles import error\n'), ((4612, 4624), 'veles.compat.from_none', 'from_none', (['e'], {}), '(e)\n', (4621, 4624), False, 'from veles.compat import from_none\n'), ((5009, 5061), 'numpy.array', 'numpy.array', (["obj['labels']"], {'dtype': 'Loader.LABEL_DTYPE'}), "(obj['labels'], dtype=Loader.LABEL_DTYPE)\n", (5020, 5061), False, 'import numpy\n'), ((5242, 5254), 'veles.compat.from_none', 'from_none', (['e'], {}), '(e)\n', (5251, 5254), False, 'from veles.compat import from_none\n'), ((4230, 4266), 'pickle.load', 'pickle.load', (['fin'], {'encoding': '"""charmap"""'}), "(fin, encoding='charmap')\n", (4241, 4266), False, 'import pickle\n'), ((4326, 4342), 'pickle.load', 'pickle.load', (['fin'], {}), '(fin)\n', (4337, 4342), False, 'import pickle\n')]
|
'''
Unittests for pysal.model.spreg.error_sp_hom module
'''
import unittest
import pysal.lib
from pysal.model.spreg import error_sp_hom as HOM
import numpy as np
from pysal.lib.common import RTOL
import pysal.model.spreg
class BaseGM_Error_Hom_Tester(unittest.TestCase):
def setUp(self):
db=pysal.lib.io.open(pysal.lib.examples.get_path("columbus.dbf"),"r")
y = np.array(db.by_col("HOVAL"))
self.y = np.reshape(y, (49,1))
X = []
X.append(db.by_col("INC"))
X.append(db.by_col("CRIME"))
self.X = np.array(X).T
self.X = np.hstack((np.ones(self.y.shape),self.X))
self.w = pysal.lib.weights.Rook.from_shapefile(pysal.lib.examples.get_path("columbus.shp"))
self.w.transform = 'r'
def test_model(self):
reg = HOM.BaseGM_Error_Hom(self.y, self.X, self.w.sparse, A1='hom_sc')
np.testing.assert_allclose(reg.y[0],np.array([80.467003]),RTOL)
x = np.array([ 1. , 19.531 , 15.72598])
np.testing.assert_allclose(reg.x[0],x,RTOL)
betas = np.array([[ 47.9478524 ], [ 0.70633223], [ -0.55595633], [ 0.41288558]])
np.testing.assert_allclose(reg.betas,betas,RTOL)
np.testing.assert_allclose(reg.u[0],np.array([27.466734]),RTOL)
np.testing.assert_allclose(reg.e_filtered[0],np.array([ 32.37298547]),RTOL)
i_s = 'Maximum number of iterations reached.'
np.testing.assert_string_equal(reg.iter_stop,i_s)
np.testing.assert_allclose(reg.predy[0],np.array([ 53.000269]),RTOL)
np.testing.assert_allclose(reg.n,49,RTOL)
np.testing.assert_allclose(reg.k,3,RTOL)
sig2 = 189.94459439729718
np.testing.assert_allclose(reg.sig2,sig2)
vm = np.array([[ 1.51340717e+02, -5.29057506e+00, -1.85654540e+00, -2.39139054e-03], [ -5.29057506e+00, 2.46669610e-01, 5.14259101e-02, 3.19241302e-04], [ -1.85654540e+00, 5.14259101e-02, 3.20510550e-02, -5.95640240e-05], [ -2.39139054e-03, 3.19241302e-04, -5.95640240e-05, 3.36690159e-02]])
np.testing.assert_allclose(reg.vm,vm,RTOL)
xtx = np.array([[ 4.90000000e+01, 7.04371999e+02, 1.72131237e+03], [ 7.04371999e+02, 1.16866734e+04, 2.15575320e+04], [ 1.72131237e+03, 2.15575320e+04, 7.39058986e+04]])
np.testing.assert_allclose(reg.xtx,xtx,RTOL)
class GM_Error_Hom_Tester(unittest.TestCase):
def setUp(self):
db=pysal.lib.io.open(pysal.lib.examples.get_path("columbus.dbf"),"r")
y = np.array(db.by_col("HOVAL"))
self.y = np.reshape(y, (49,1))
X = []
X.append(db.by_col("INC"))
X.append(db.by_col("CRIME"))
self.X = np.array(X).T
self.w = pysal.lib.weights.Rook.from_shapefile(pysal.lib.examples.get_path("columbus.shp"))
self.w.transform = 'r'
def test_model(self):
reg = HOM.GM_Error_Hom(self.y, self.X, self.w, A1='hom_sc')
np.testing.assert_allclose(reg.y[0],np.array([80.467003]),RTOL)
x = np.array([ 1. , 19.531 , 15.72598])
np.testing.assert_allclose(reg.x[0],x,RTOL)
betas = np.array([[ 47.9478524 ], [ 0.70633223], [ -0.55595633], [ 0.41288558]])
np.testing.assert_allclose(reg.betas,betas,RTOL)
np.testing.assert_allclose(reg.u[0],np.array([27.46673388]),RTOL)
np.testing.assert_allclose(reg.e_filtered[0],np.array([ 32.37298547]),RTOL)
np.testing.assert_allclose(reg.predy[0],np.array([ 53.00026912]),RTOL)
np.testing.assert_allclose(reg.n,49,RTOL)
np.testing.assert_allclose(reg.k,3,RTOL)
vm = np.array([[ 1.51340717e+02, -5.29057506e+00, -1.85654540e+00, -2.39139054e-03], [ -5.29057506e+00, 2.46669610e-01, 5.14259101e-02, 3.19241302e-04], [ -1.85654540e+00, 5.14259101e-02, 3.20510550e-02, -5.95640240e-05], [ -2.39139054e-03, 3.19241302e-04, -5.95640240e-05, 3.36690159e-02]])
np.testing.assert_allclose(reg.vm,vm,RTOL)
i_s = 'Maximum number of iterations reached.'
np.testing.assert_string_equal(reg.iter_stop,i_s)
np.testing.assert_allclose(reg.iteration,1,RTOL)
my = 38.436224469387746
np.testing.assert_allclose(reg.mean_y,my)
std_y = 18.466069465206047
np.testing.assert_allclose(reg.std_y,std_y)
pr2 = 0.34950977055969729
np.testing.assert_allclose(reg.pr2,pr2)
sig2 = 189.94459439729718
np.testing.assert_allclose(reg.sig2,sig2)
std_err = np.array([ 12.30206149, 0.49665844, 0.17902808, 0.18349119])
np.testing.assert_allclose(reg.std_err,std_err,RTOL)
z_stat = np.array([[ 3.89754616e+00, 9.71723059e-05], [ 1.42216900e+00, 1.54977196e-01], [ -3.10541409e+00, 1.90012806e-03], [ 2.25016500e+00, 2.44384731e-02]])
np.testing.assert_allclose(reg.z_stat,z_stat,RTOL)
xtx = np.array([[ 4.90000000e+01, 7.04371999e+02, 1.72131237e+03], [ 7.04371999e+02, 1.16866734e+04, 2.15575320e+04], [ 1.72131237e+03, 2.15575320e+04, 7.39058986e+04]])
np.testing.assert_allclose(reg.xtx,xtx,RTOL)
class BaseGM_Endog_Error_Hom_Tester(unittest.TestCase):
def setUp(self):
db=pysal.lib.io.open(pysal.lib.examples.get_path("columbus.dbf"),"r")
y = np.array(db.by_col("HOVAL"))
self.y = np.reshape(y, (49,1))
X = []
X.append(db.by_col("INC"))
self.X = np.array(X).T
self.X = np.hstack((np.ones(self.y.shape),self.X))
yd = []
yd.append(db.by_col("CRIME"))
self.yd = np.array(yd).T
q = []
q.append(db.by_col("DISCBD"))
self.q = np.array(q).T
self.w = pysal.lib.weights.Rook.from_shapefile(pysal.lib.examples.get_path("columbus.shp"))
self.w.transform = 'r'
def test_model(self):
reg = HOM.BaseGM_Endog_Error_Hom(self.y, self.X, self.yd, self.q, self.w.sparse, A1='hom_sc')
np.testing.assert_allclose(reg.y[0],np.array([ 80.467003]),RTOL)
x = np.array([ 1. , 19.531])
np.testing.assert_allclose(reg.x[0],x,RTOL)
z = np.array([ 1. , 19.531 , 15.72598])
np.testing.assert_allclose(reg.z[0],z,RTOL)
h = np.array([ 1. , 19.531, 5.03 ])
np.testing.assert_allclose(reg.h[0],h,RTOL)
yend = np.array([ 15.72598])
np.testing.assert_allclose(reg.yend[0],yend,RTOL)
q = np.array([ 5.03])
np.testing.assert_allclose(reg.q[0],q,RTOL)
betas = np.array([[ 55.36575166], [ 0.46432416], [ -0.66904404], [ 0.43205526]])
np.testing.assert_allclose(reg.betas,betas,RTOL)
u = np.array([ 26.55390939])
np.testing.assert_allclose(reg.u[0],u,RTOL)
np.testing.assert_allclose(reg.e_filtered[0],np.array([ 31.74114306]),RTOL)
predy = np.array([ 53.91309361])
np.testing.assert_allclose(reg.predy[0],predy,RTOL)
np.testing.assert_allclose(reg.n,49,RTOL)
np.testing.assert_allclose(reg.k,3,RTOL)
sig2 = 190.59435238060928
np.testing.assert_allclose(reg.sig2,sig2)
vm = np.array([[ 5.52064057e+02, -1.61264555e+01, -8.86360735e+00, 1.04251912e+00], [ -1.61264555e+01, 5.44898242e-01, 2.39518645e-01, -1.88092950e-02], [ -8.86360735e+00, 2.39518645e-01, 1.55501840e-01, -2.18638648e-02], [ 1.04251912e+00, -1.88092950e-02, -2.18638648e-02, 3.71222222e-02]])
np.testing.assert_allclose(reg.vm,vm,RTOL)
i_s = 'Maximum number of iterations reached.'
np.testing.assert_string_equal(reg.iter_stop,i_s)
its = 1
np.testing.assert_allclose(reg.iteration,its,RTOL)
my = 38.436224469387746
np.testing.assert_allclose(reg.mean_y,my)
std_y = 18.466069465206047
np.testing.assert_allclose(reg.std_y,std_y)
sig2 = 0
#np.testing.assert_allclose(reg.sig2,sig2)
hth = np.array([[ 49. , 704.371999 , 139.75 ], [ 704.371999 , 11686.67338121, 2246.12800625], [ 139.75 , 2246.12800625, 498.5851]])
np.testing.assert_allclose(reg.hth,hth,RTOL)
class GM_Endog_Error_Hom_Tester(unittest.TestCase):
def setUp(self):
db=pysal.lib.io.open(pysal.lib.examples.get_path("columbus.dbf"),"r")
y = np.array(db.by_col("HOVAL"))
self.y = np.reshape(y, (49,1))
X = []
X.append(db.by_col("INC"))
self.X = np.array(X).T
yd = []
yd.append(db.by_col("CRIME"))
self.yd = np.array(yd).T
q = []
q.append(db.by_col("DISCBD"))
self.q = np.array(q).T
self.w = pysal.lib.weights.Rook.from_shapefile(pysal.lib.examples.get_path("columbus.shp"))
self.w.transform = 'r'
def test_model(self):
reg = HOM.GM_Endog_Error_Hom(self.y, self.X, self.yd, self.q, self.w, A1='hom_sc')
np.testing.assert_allclose(reg.y[0],np.array([ 80.467003]),RTOL)
x = np.array([ 1. , 19.531])
np.testing.assert_allclose(reg.x[0],x,RTOL)
z = np.array([ 1. , 19.531 , 15.72598])
np.testing.assert_allclose(reg.z[0],z,RTOL)
h = np.array([ 1. , 19.531, 5.03 ])
np.testing.assert_allclose(reg.h[0],h,RTOL)
yend = np.array([ 15.72598])
np.testing.assert_allclose(reg.yend[0],yend,RTOL)
q = np.array([ 5.03])
np.testing.assert_allclose(reg.q[0],q,RTOL)
betas = np.array([[ 55.36575166], [ 0.46432416], [ -0.66904404], [ 0.43205526]])
np.testing.assert_allclose(reg.betas,betas,RTOL)
u = np.array([ 26.55390939])
np.testing.assert_allclose(reg.u[0],u,RTOL)
np.testing.assert_allclose(reg.e_filtered[0],np.array([ 31.74114306]),RTOL)
predy = np.array([ 53.91309361])
np.testing.assert_allclose(reg.predy[0],predy,RTOL)
np.testing.assert_allclose(reg.n,49,RTOL)
np.testing.assert_allclose(reg.k,3,RTOL)
vm = np.array([[ 5.52064057e+02, -1.61264555e+01, -8.86360735e+00, 1.04251912e+00], [ -1.61264555e+01, 5.44898242e-01, 2.39518645e-01, -1.88092950e-02], [ -8.86360735e+00, 2.39518645e-01, 1.55501840e-01, -2.18638648e-02], [ 1.04251912e+00, -1.88092950e-02, -2.18638648e-02, 3.71222222e-02]])
np.testing.assert_allclose(reg.vm,vm,RTOL)
i_s = 'Maximum number of iterations reached.'
np.testing.assert_string_equal(reg.iter_stop,i_s)
its = 1
np.testing.assert_allclose(reg.iteration,its,RTOL)
my = 38.436224469387746
np.testing.assert_allclose(reg.mean_y,my)
std_y = 18.466069465206047
np.testing.assert_allclose(reg.std_y,std_y)
pr2 = 0.34647366525657419
np.testing.assert_allclose(reg.pr2,pr2)
sig2 = 190.59435238060928
np.testing.assert_allclose(reg.sig2,sig2)
#std_err
std_err = np.array([ 23.49604343, 0.73817223, 0.39433722, 0.19267128])
np.testing.assert_allclose(reg.std_err,std_err,RTOL)
z_stat = np.array([[ 2.35638617, 0.01845372], [ 0.62901874, 0.52933679], [-1.69662923, 0.08976678], [ 2.24244556, 0.02493259]])
np.testing.assert_allclose(reg.z_stat,z_stat,RTOL)
class BaseGM_Combo_Hom_Tester(unittest.TestCase):
def setUp(self):
db=pysal.lib.io.open(pysal.lib.examples.get_path("columbus.dbf"),"r")
y = np.array(db.by_col("HOVAL"))
self.y = np.reshape(y, (49,1))
X = []
X.append(db.by_col("INC"))
self.X = np.array(X).T
self.w = pysal.lib.weights.Rook.from_shapefile(pysal.lib.examples.get_path("columbus.shp"))
self.w.transform = 'r'
def test_model(self):
yd2, q2 = pysal.model.spreg.utils.set_endog(self.y, self.X, self.w, None, None, 1, True)
self.X = np.hstack((np.ones(self.y.shape),self.X))
reg = HOM.BaseGM_Combo_Hom(self.y, self.X, yend=yd2, q=q2, w=self.w.sparse, A1='hom_sc')
np.testing.assert_allclose(reg.y[0],np.array([80.467003]),RTOL)
x = np.array([ 1. , 19.531])
np.testing.assert_allclose(reg.x[0],x,RTOL)
betas = np.array([[ 10.12541428], [ 1.56832263], [ 0.15132076], [ 0.21033397]])
np.testing.assert_allclose(reg.betas,betas,RTOL)
np.testing.assert_allclose(reg.u[0],np.array([34.3450723]),RTOL)
np.testing.assert_allclose(reg.e_filtered[0],np.array([ 36.6149682]),RTOL)
np.testing.assert_allclose(reg.predy[0],np.array([ 46.1219307]),RTOL)
np.testing.assert_allclose(reg.n,49,RTOL)
np.testing.assert_allclose(reg.k,3,RTOL)
vm = np.array([[ 2.33694742e+02, -6.66856869e-01, -5.58304254e+00, 4.85488380e+00], [ -6.66856869e-01, 1.94241504e-01, -5.42327138e-02, 5.37225570e-02], [ -5.58304254e+00, -5.42327138e-02, 1.63860721e-01, -1.44425498e-01], [ 4.85488380e+00, 5.37225570e-02, -1.44425498e-01, 1.78622255e-01]])
np.testing.assert_allclose(reg.vm,vm,RTOL)
z = np.array([ 1. , 19.531 , 35.4585005])
np.testing.assert_allclose(reg.z[0],z,RTOL)
h = np.array([ 1. , 19.531, 18.594])
np.testing.assert_allclose(reg.h[0],h,RTOL)
yend = np.array([ 35.4585005])
np.testing.assert_allclose(reg.yend[0],yend,RTOL)
q = np.array([ 18.594])
np.testing.assert_allclose(reg.q[0],q,RTOL)
i_s = 'Maximum number of iterations reached.'
np.testing.assert_string_equal(reg.iter_stop,i_s)
its = 1
np.testing.assert_allclose(reg.iteration,its,RTOL)
my = 38.436224469387746
np.testing.assert_allclose(reg.mean_y,my)
std_y = 18.466069465206047
np.testing.assert_allclose(reg.std_y,std_y)
sig2 = 232.22680651270042
#np.testing.assert_allclose(reg.sig2,sig2)
np.testing.assert_allclose(reg.sig2,sig2)
hth = np.array([[ 49. , 704.371999 , 724.7435916 ], [ 704.371999 , 11686.67338121, 11092.519988 ], [ 724.7435916 , 11092.519988 , 11614.62257048]])
np.testing.assert_allclose(reg.hth,hth,RTOL)
class GM_Combo_Hom_Tester(unittest.TestCase):
def setUp(self):
db=pysal.lib.io.open(pysal.lib.examples.get_path("columbus.dbf"),"r")
y = np.array(db.by_col("HOVAL"))
self.y = np.reshape(y, (49,1))
X = []
X.append(db.by_col("INC"))
self.X = np.array(X).T
self.w = pysal.lib.weights.Rook.from_shapefile(pysal.lib.examples.get_path("columbus.shp"))
self.w.transform = 'r'
def test_model(self):
reg = HOM.GM_Combo_Hom(self.y, self.X, w=self.w, A1='hom_sc')
np.testing.assert_allclose(reg.y[0],np.array([80.467003]),RTOL)
x = np.array([ 1. , 19.531])
np.testing.assert_allclose(reg.x[0],x,RTOL)
betas = np.array([[ 10.12541428], [ 1.56832263], [ 0.15132076], [ 0.21033397]])
np.testing.assert_allclose(reg.betas,betas,RTOL)
np.testing.assert_allclose(reg.u[0],np.array([34.3450723]),RTOL)
np.testing.assert_allclose(reg.e_filtered[0],np.array([ 36.6149682]),RTOL)
np.testing.assert_allclose(reg.e_pred[0],np.array([ 32.90372983]),RTOL)
np.testing.assert_allclose(reg.predy[0],np.array([ 46.1219307]),RTOL)
np.testing.assert_allclose(reg.predy_e[0],np.array([47.56327317]),RTOL)
np.testing.assert_allclose(reg.n,49,RTOL)
np.testing.assert_allclose(reg.k,3,RTOL)
z = np.array([ 1. , 19.531 , 35.4585005])
np.testing.assert_allclose(reg.z[0],z,RTOL)
h = np.array([ 1. , 19.531, 18.594])
np.testing.assert_allclose(reg.h[0],h,RTOL)
yend = np.array([ 35.4585005])
np.testing.assert_allclose(reg.yend[0],yend,RTOL)
q = np.array([ 18.594])
np.testing.assert_allclose(reg.q[0],q,RTOL)
i_s = 'Maximum number of iterations reached.'
np.testing.assert_string_equal(reg.iter_stop,i_s)
np.testing.assert_allclose(reg.iteration,1,RTOL)
my = 38.436224469387746
np.testing.assert_allclose(reg.mean_y,my)
std_y = 18.466069465206047
np.testing.assert_allclose(reg.std_y,std_y)
pr2 = 0.28379825632694394
np.testing.assert_allclose(reg.pr2,pr2)
pr2_e = 0.25082892555141506
np.testing.assert_allclose(reg.pr2_e,pr2_e)
sig2 = 232.22680651270042
#np.testing.assert_allclose(reg.sig2, sig2)
np.testing.assert_allclose(reg.sig2, sig2)
std_err = np.array([ 15.28707761, 0.44072838, 0.40479714, 0.42263726])
np.testing.assert_allclose(reg.std_err,std_err,RTOL)
z_stat = np.array([[ 6.62351206e-01, 5.07746167e-01], [ 3.55847888e+00, 3.73008780e-04], [ 3.73818749e-01, 7.08539170e-01], [ 4.97670189e-01, 6.18716523e-01]])
np.testing.assert_allclose(reg.z_stat,z_stat,RTOL)
vm = np.array([[ 2.33694742e+02, -6.66856869e-01, -5.58304254e+00, 4.85488380e+00], [ -6.66856869e-01, 1.94241504e-01, -5.42327138e-02, 5.37225570e-02], [ -5.58304254e+00, -5.42327138e-02, 1.63860721e-01, -1.44425498e-01], [ 4.85488380e+00, 5.37225570e-02, -1.44425498e-01, 1.78622255e-01]])
np.testing.assert_allclose(reg.vm,vm,RTOL)
suite = unittest.TestSuite()
test_classes = [BaseGM_Error_Hom_Tester, GM_Error_Hom_Tester,\
BaseGM_Endog_Error_Hom_Tester, GM_Endog_Error_Hom_Tester, \
BaseGM_Combo_Hom_Tester, GM_Combo_Hom_Tester]
for i in test_classes:
a = unittest.TestLoader().loadTestsFromTestCase(i)
suite.addTest(a)
if __name__ == '__main__':
runner = unittest.TextTestRunner()
runner.run(suite)
|
[
"unittest.TextTestRunner",
"unittest.TestSuite",
"pysal.model.spreg.error_sp_hom.GM_Combo_Hom",
"pysal.model.spreg.error_sp_hom.BaseGM_Error_Hom",
"pysal.model.spreg.error_sp_hom.GM_Endog_Error_Hom",
"pysal.model.spreg.error_sp_hom.BaseGM_Combo_Hom",
"numpy.ones",
"numpy.array",
"numpy.reshape",
"numpy.testing.assert_string_equal",
"unittest.TestLoader",
"numpy.testing.assert_allclose",
"pysal.model.spreg.error_sp_hom.GM_Error_Hom",
"pysal.model.spreg.error_sp_hom.BaseGM_Endog_Error_Hom"
] |
[((17068, 17088), 'unittest.TestSuite', 'unittest.TestSuite', ([], {}), '()\n', (17086, 17088), False, 'import unittest\n'), ((17414, 17439), 'unittest.TextTestRunner', 'unittest.TextTestRunner', ([], {}), '()\n', (17437, 17439), False, 'import unittest\n'), ((430, 452), 'numpy.reshape', 'np.reshape', (['y', '(49, 1)'], {}), '(y, (49, 1))\n', (440, 452), True, 'import numpy as np\n'), ((800, 864), 'pysal.model.spreg.error_sp_hom.BaseGM_Error_Hom', 'HOM.BaseGM_Error_Hom', (['self.y', 'self.X', 'self.w.sparse'], {'A1': '"""hom_sc"""'}), "(self.y, self.X, self.w.sparse, A1='hom_sc')\n", (820, 864), True, 'from pysal.model.spreg import error_sp_hom as HOM\n'), ((949, 982), 'numpy.array', 'np.array', (['[1.0, 19.531, 15.72598]'], {}), '([1.0, 19.531, 15.72598])\n', (957, 982), True, 'import numpy as np\n'), ((1001, 1046), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.x[0]', 'x', 'RTOL'], {}), '(reg.x[0], x, RTOL)\n', (1027, 1046), True, 'import numpy as np\n'), ((1061, 1128), 'numpy.array', 'np.array', (['[[47.9478524], [0.70633223], [-0.55595633], [0.41288558]]'], {}), '([[47.9478524], [0.70633223], [-0.55595633], [0.41288558]])\n', (1069, 1128), True, 'import numpy as np\n'), ((1144, 1194), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.betas', 'betas', 'RTOL'], {}), '(reg.betas, betas, RTOL)\n', (1170, 1194), True, 'import numpy as np\n'), ((1411, 1461), 'numpy.testing.assert_string_equal', 'np.testing.assert_string_equal', (['reg.iter_stop', 'i_s'], {}), '(reg.iter_stop, i_s)\n', (1441, 1461), True, 'import numpy as np\n'), ((1546, 1589), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.n', '(49)', 'RTOL'], {}), '(reg.n, 49, RTOL)\n', (1572, 1589), True, 'import numpy as np\n'), ((1596, 1638), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.k', '(3)', 'RTOL'], {}), '(reg.k, 3, RTOL)\n', (1622, 1638), True, 'import numpy as np\n'), ((1679, 1721), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.sig2', 'sig2'], {}), '(reg.sig2, sig2)\n', (1705, 1721), True, 'import numpy as np\n'), ((1734, 1992), 'numpy.array', 'np.array', (['[[151.340717, -5.29057506, -1.8565454, -0.00239139054], [-5.29057506, \n 0.24666961, 0.0514259101, 0.000319241302], [-1.8565454, 0.0514259101, \n 0.032051055, -5.9564024e-05], [-0.00239139054, 0.000319241302, -\n 5.9564024e-05, 0.0336690159]]'], {}), '([[151.340717, -5.29057506, -1.8565454, -0.00239139054], [-\n 5.29057506, 0.24666961, 0.0514259101, 0.000319241302], [-1.8565454, \n 0.0514259101, 0.032051055, -5.9564024e-05], [-0.00239139054, \n 0.000319241302, -5.9564024e-05, 0.0336690159]])\n', (1742, 1992), True, 'import numpy as np\n'), ((2040, 2084), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.vm', 'vm', 'RTOL'], {}), '(reg.vm, vm, RTOL)\n', (2066, 2084), True, 'import numpy as np\n'), ((2097, 2218), 'numpy.array', 'np.array', (['[[49.0, 704.371999, 1721.31237], [704.371999, 11686.6734, 21557.532], [\n 1721.31237, 21557.532, 73905.8986]]'], {}), '([[49.0, 704.371999, 1721.31237], [704.371999, 11686.6734, \n 21557.532], [1721.31237, 21557.532, 73905.8986]])\n', (2105, 2218), True, 'import numpy as np\n'), ((2280, 2326), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.xtx', 'xtx', 'RTOL'], {}), '(reg.xtx, xtx, RTOL)\n', (2306, 2326), True, 'import numpy as np\n'), ((2529, 2551), 'numpy.reshape', 'np.reshape', (['y', '(49, 1)'], {}), '(y, (49, 1))\n', (2539, 2551), True, 'import numpy as np\n'), ((2840, 2893), 'pysal.model.spreg.error_sp_hom.GM_Error_Hom', 'HOM.GM_Error_Hom', (['self.y', 'self.X', 'self.w'], {'A1': '"""hom_sc"""'}), "(self.y, self.X, self.w, A1='hom_sc')\n", (2856, 2893), True, 'from pysal.model.spreg import error_sp_hom as HOM\n'), ((2978, 3011), 'numpy.array', 'np.array', (['[1.0, 19.531, 15.72598]'], {}), '([1.0, 19.531, 15.72598])\n', (2986, 3011), True, 'import numpy as np\n'), ((3030, 3075), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.x[0]', 'x', 'RTOL'], {}), '(reg.x[0], x, RTOL)\n', (3056, 3075), True, 'import numpy as np\n'), ((3090, 3157), 'numpy.array', 'np.array', (['[[47.9478524], [0.70633223], [-0.55595633], [0.41288558]]'], {}), '([[47.9478524], [0.70633223], [-0.55595633], [0.41288558]])\n', (3098, 3157), True, 'import numpy as np\n'), ((3173, 3223), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.betas', 'betas', 'RTOL'], {}), '(reg.betas, betas, RTOL)\n', (3199, 3223), True, 'import numpy as np\n'), ((3467, 3510), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.n', '(49)', 'RTOL'], {}), '(reg.n, 49, RTOL)\n', (3493, 3510), True, 'import numpy as np\n'), ((3517, 3559), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.k', '(3)', 'RTOL'], {}), '(reg.k, 3, RTOL)\n', (3543, 3559), True, 'import numpy as np\n'), ((3571, 3829), 'numpy.array', 'np.array', (['[[151.340717, -5.29057506, -1.8565454, -0.00239139054], [-5.29057506, \n 0.24666961, 0.0514259101, 0.000319241302], [-1.8565454, 0.0514259101, \n 0.032051055, -5.9564024e-05], [-0.00239139054, 0.000319241302, -\n 5.9564024e-05, 0.0336690159]]'], {}), '([[151.340717, -5.29057506, -1.8565454, -0.00239139054], [-\n 5.29057506, 0.24666961, 0.0514259101, 0.000319241302], [-1.8565454, \n 0.0514259101, 0.032051055, -5.9564024e-05], [-0.00239139054, \n 0.000319241302, -5.9564024e-05, 0.0336690159]])\n', (3579, 3829), True, 'import numpy as np\n'), ((3877, 3921), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.vm', 'vm', 'RTOL'], {}), '(reg.vm, vm, RTOL)\n', (3903, 3921), True, 'import numpy as np\n'), ((3982, 4032), 'numpy.testing.assert_string_equal', 'np.testing.assert_string_equal', (['reg.iter_stop', 'i_s'], {}), '(reg.iter_stop, i_s)\n', (4012, 4032), True, 'import numpy as np\n'), ((4040, 4090), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.iteration', '(1)', 'RTOL'], {}), '(reg.iteration, 1, RTOL)\n', (4066, 4090), True, 'import numpy as np\n'), ((4129, 4171), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.mean_y', 'my'], {}), '(reg.mean_y, my)\n', (4155, 4171), True, 'import numpy as np\n'), ((4214, 4258), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.std_y', 'std_y'], {}), '(reg.std_y, std_y)\n', (4240, 4258), True, 'import numpy as np\n'), ((4300, 4340), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.pr2', 'pr2'], {}), '(reg.pr2, pr2)\n', (4326, 4340), True, 'import numpy as np\n'), ((4382, 4424), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.sig2', 'sig2'], {}), '(reg.sig2, sig2)\n', (4408, 4424), True, 'import numpy as np\n'), ((4442, 4501), 'numpy.array', 'np.array', (['[12.30206149, 0.49665844, 0.17902808, 0.18349119]'], {}), '([12.30206149, 0.49665844, 0.17902808, 0.18349119])\n', (4450, 4501), True, 'import numpy as np\n'), ((4515, 4569), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.std_err', 'std_err', 'RTOL'], {}), '(reg.std_err, std_err, RTOL)\n', (4541, 4569), True, 'import numpy as np\n'), ((4585, 4711), 'numpy.array', 'np.array', (['[[3.89754616, 9.71723059e-05], [1.422169, 0.154977196], [-3.10541409, \n 0.00190012806], [2.250165, 0.0244384731]]'], {}), '([[3.89754616, 9.71723059e-05], [1.422169, 0.154977196], [-\n 3.10541409, 0.00190012806], [2.250165, 0.0244384731]])\n', (4593, 4711), True, 'import numpy as np\n'), ((4756, 4808), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.z_stat', 'z_stat', 'RTOL'], {}), '(reg.z_stat, z_stat, RTOL)\n', (4782, 4808), True, 'import numpy as np\n'), ((4821, 4942), 'numpy.array', 'np.array', (['[[49.0, 704.371999, 1721.31237], [704.371999, 11686.6734, 21557.532], [\n 1721.31237, 21557.532, 73905.8986]]'], {}), '([[49.0, 704.371999, 1721.31237], [704.371999, 11686.6734, \n 21557.532], [1721.31237, 21557.532, 73905.8986]])\n', (4829, 4942), True, 'import numpy as np\n'), ((5004, 5050), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.xtx', 'xtx', 'RTOL'], {}), '(reg.xtx, xtx, RTOL)\n', (5030, 5050), True, 'import numpy as np\n'), ((5264, 5286), 'numpy.reshape', 'np.reshape', (['y', '(49, 1)'], {}), '(y, (49, 1))\n', (5274, 5286), True, 'import numpy as np\n'), ((5768, 5859), 'pysal.model.spreg.error_sp_hom.BaseGM_Endog_Error_Hom', 'HOM.BaseGM_Endog_Error_Hom', (['self.y', 'self.X', 'self.yd', 'self.q', 'self.w.sparse'], {'A1': '"""hom_sc"""'}), "(self.y, self.X, self.yd, self.q, self.w.sparse,\n A1='hom_sc')\n", (5794, 5859), True, 'from pysal.model.spreg import error_sp_hom as HOM\n'), ((5941, 5964), 'numpy.array', 'np.array', (['[1.0, 19.531]'], {}), '([1.0, 19.531])\n', (5949, 5964), True, 'import numpy as np\n'), ((5980, 6025), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.x[0]', 'x', 'RTOL'], {}), '(reg.x[0], x, RTOL)\n', (6006, 6025), True, 'import numpy as np\n'), ((6036, 6069), 'numpy.array', 'np.array', (['[1.0, 19.531, 15.72598]'], {}), '([1.0, 19.531, 15.72598])\n', (6044, 6069), True, 'import numpy as np\n'), ((6088, 6133), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.z[0]', 'z', 'RTOL'], {}), '(reg.z[0], z, RTOL)\n', (6114, 6133), True, 'import numpy as np\n'), ((6144, 6173), 'numpy.array', 'np.array', (['[1.0, 19.531, 5.03]'], {}), '([1.0, 19.531, 5.03])\n', (6152, 6173), True, 'import numpy as np\n'), ((6190, 6235), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.h[0]', 'h', 'RTOL'], {}), '(reg.h[0], h, RTOL)\n', (6216, 6235), True, 'import numpy as np\n'), ((6249, 6269), 'numpy.array', 'np.array', (['[15.72598]'], {}), '([15.72598])\n', (6257, 6269), True, 'import numpy as np\n'), ((6279, 6330), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.yend[0]', 'yend', 'RTOL'], {}), '(reg.yend[0], yend, RTOL)\n', (6305, 6330), True, 'import numpy as np\n'), ((6341, 6357), 'numpy.array', 'np.array', (['[5.03]'], {}), '([5.03])\n', (6349, 6357), True, 'import numpy as np\n'), ((6367, 6412), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.q[0]', 'q', 'RTOL'], {}), '(reg.q[0], q, RTOL)\n', (6393, 6412), True, 'import numpy as np\n'), ((6427, 6495), 'numpy.array', 'np.array', (['[[55.36575166], [0.46432416], [-0.66904404], [0.43205526]]'], {}), '([[55.36575166], [0.46432416], [-0.66904404], [0.43205526]])\n', (6435, 6495), True, 'import numpy as np\n'), ((6510, 6560), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.betas', 'betas', 'RTOL'], {}), '(reg.betas, betas, RTOL)\n', (6536, 6560), True, 'import numpy as np\n'), ((6571, 6594), 'numpy.array', 'np.array', (['[26.55390939]'], {}), '([26.55390939])\n', (6579, 6594), True, 'import numpy as np\n'), ((6604, 6649), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.u[0]', 'u', 'RTOL'], {}), '(reg.u[0], u, RTOL)\n', (6630, 6649), True, 'import numpy as np\n'), ((6748, 6771), 'numpy.array', 'np.array', (['[53.91309361]'], {}), '([53.91309361])\n', (6756, 6771), True, 'import numpy as np\n'), ((6781, 6834), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.predy[0]', 'predy', 'RTOL'], {}), '(reg.predy[0], predy, RTOL)\n', (6807, 6834), True, 'import numpy as np\n'), ((6841, 6884), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.n', '(49)', 'RTOL'], {}), '(reg.n, 49, RTOL)\n', (6867, 6884), True, 'import numpy as np\n'), ((6891, 6933), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.k', '(3)', 'RTOL'], {}), '(reg.k, 3, RTOL)\n', (6917, 6933), True, 'import numpy as np\n'), ((6974, 7016), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.sig2', 'sig2'], {}), '(reg.sig2, sig2)\n', (7000, 7016), True, 'import numpy as np\n'), ((7029, 7272), 'numpy.array', 'np.array', (['[[552.064057, -16.1264555, -8.86360735, 1.04251912], [-16.1264555, \n 0.544898242, 0.239518645, -0.018809295], [-8.86360735, 0.239518645, \n 0.15550184, -0.0218638648], [1.04251912, -0.018809295, -0.0218638648, \n 0.0371222222]]'], {}), '([[552.064057, -16.1264555, -8.86360735, 1.04251912], [-16.1264555,\n 0.544898242, 0.239518645, -0.018809295], [-8.86360735, 0.239518645, \n 0.15550184, -0.0218638648], [1.04251912, -0.018809295, -0.0218638648, \n 0.0371222222]])\n', (7037, 7272), True, 'import numpy as np\n'), ((7332, 7376), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.vm', 'vm', 'RTOL'], {}), '(reg.vm, vm, RTOL)\n', (7358, 7376), True, 'import numpy as np\n'), ((7437, 7487), 'numpy.testing.assert_string_equal', 'np.testing.assert_string_equal', (['reg.iter_stop', 'i_s'], {}), '(reg.iter_stop, i_s)\n', (7467, 7487), True, 'import numpy as np\n'), ((7511, 7563), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.iteration', 'its', 'RTOL'], {}), '(reg.iteration, its, RTOL)\n', (7537, 7563), True, 'import numpy as np\n'), ((7602, 7644), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.mean_y', 'my'], {}), '(reg.mean_y, my)\n', (7628, 7644), True, 'import numpy as np\n'), ((7687, 7731), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.std_y', 'std_y'], {}), '(reg.std_y, std_y)\n', (7713, 7731), True, 'import numpy as np\n'), ((7813, 7936), 'numpy.array', 'np.array', (['[[49.0, 704.371999, 139.75], [704.371999, 11686.67338121, 2246.12800625], [\n 139.75, 2246.12800625, 498.5851]]'], {}), '([[49.0, 704.371999, 139.75], [704.371999, 11686.67338121, \n 2246.12800625], [139.75, 2246.12800625, 498.5851]])\n', (7821, 7936), True, 'import numpy as np\n'), ((7987, 8033), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.hth', 'hth', 'RTOL'], {}), '(reg.hth, hth, RTOL)\n', (8013, 8033), True, 'import numpy as np\n'), ((8242, 8264), 'numpy.reshape', 'np.reshape', (['y', '(49, 1)'], {}), '(y, (49, 1))\n', (8252, 8264), True, 'import numpy as np\n'), ((8687, 8763), 'pysal.model.spreg.error_sp_hom.GM_Endog_Error_Hom', 'HOM.GM_Endog_Error_Hom', (['self.y', 'self.X', 'self.yd', 'self.q', 'self.w'], {'A1': '"""hom_sc"""'}), "(self.y, self.X, self.yd, self.q, self.w, A1='hom_sc')\n", (8709, 8763), True, 'from pysal.model.spreg import error_sp_hom as HOM\n'), ((8849, 8872), 'numpy.array', 'np.array', (['[1.0, 19.531]'], {}), '([1.0, 19.531])\n', (8857, 8872), True, 'import numpy as np\n'), ((8888, 8933), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.x[0]', 'x', 'RTOL'], {}), '(reg.x[0], x, RTOL)\n', (8914, 8933), True, 'import numpy as np\n'), ((8944, 8977), 'numpy.array', 'np.array', (['[1.0, 19.531, 15.72598]'], {}), '([1.0, 19.531, 15.72598])\n', (8952, 8977), True, 'import numpy as np\n'), ((8996, 9041), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.z[0]', 'z', 'RTOL'], {}), '(reg.z[0], z, RTOL)\n', (9022, 9041), True, 'import numpy as np\n'), ((9052, 9081), 'numpy.array', 'np.array', (['[1.0, 19.531, 5.03]'], {}), '([1.0, 19.531, 5.03])\n', (9060, 9081), True, 'import numpy as np\n'), ((9098, 9143), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.h[0]', 'h', 'RTOL'], {}), '(reg.h[0], h, RTOL)\n', (9124, 9143), True, 'import numpy as np\n'), ((9157, 9177), 'numpy.array', 'np.array', (['[15.72598]'], {}), '([15.72598])\n', (9165, 9177), True, 'import numpy as np\n'), ((9187, 9238), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.yend[0]', 'yend', 'RTOL'], {}), '(reg.yend[0], yend, RTOL)\n', (9213, 9238), True, 'import numpy as np\n'), ((9249, 9265), 'numpy.array', 'np.array', (['[5.03]'], {}), '([5.03])\n', (9257, 9265), True, 'import numpy as np\n'), ((9275, 9320), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.q[0]', 'q', 'RTOL'], {}), '(reg.q[0], q, RTOL)\n', (9301, 9320), True, 'import numpy as np\n'), ((9335, 9403), 'numpy.array', 'np.array', (['[[55.36575166], [0.46432416], [-0.66904404], [0.43205526]]'], {}), '([[55.36575166], [0.46432416], [-0.66904404], [0.43205526]])\n', (9343, 9403), True, 'import numpy as np\n'), ((9418, 9468), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.betas', 'betas', 'RTOL'], {}), '(reg.betas, betas, RTOL)\n', (9444, 9468), True, 'import numpy as np\n'), ((9479, 9502), 'numpy.array', 'np.array', (['[26.55390939]'], {}), '([26.55390939])\n', (9487, 9502), True, 'import numpy as np\n'), ((9512, 9557), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.u[0]', 'u', 'RTOL'], {}), '(reg.u[0], u, RTOL)\n', (9538, 9557), True, 'import numpy as np\n'), ((9656, 9679), 'numpy.array', 'np.array', (['[53.91309361]'], {}), '([53.91309361])\n', (9664, 9679), True, 'import numpy as np\n'), ((9689, 9742), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.predy[0]', 'predy', 'RTOL'], {}), '(reg.predy[0], predy, RTOL)\n', (9715, 9742), True, 'import numpy as np\n'), ((9749, 9792), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.n', '(49)', 'RTOL'], {}), '(reg.n, 49, RTOL)\n', (9775, 9792), True, 'import numpy as np\n'), ((9799, 9841), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.k', '(3)', 'RTOL'], {}), '(reg.k, 3, RTOL)\n', (9825, 9841), True, 'import numpy as np\n'), ((9853, 10096), 'numpy.array', 'np.array', (['[[552.064057, -16.1264555, -8.86360735, 1.04251912], [-16.1264555, \n 0.544898242, 0.239518645, -0.018809295], [-8.86360735, 0.239518645, \n 0.15550184, -0.0218638648], [1.04251912, -0.018809295, -0.0218638648, \n 0.0371222222]]'], {}), '([[552.064057, -16.1264555, -8.86360735, 1.04251912], [-16.1264555,\n 0.544898242, 0.239518645, -0.018809295], [-8.86360735, 0.239518645, \n 0.15550184, -0.0218638648], [1.04251912, -0.018809295, -0.0218638648, \n 0.0371222222]])\n', (9861, 10096), True, 'import numpy as np\n'), ((10156, 10200), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.vm', 'vm', 'RTOL'], {}), '(reg.vm, vm, RTOL)\n', (10182, 10200), True, 'import numpy as np\n'), ((10261, 10311), 'numpy.testing.assert_string_equal', 'np.testing.assert_string_equal', (['reg.iter_stop', 'i_s'], {}), '(reg.iter_stop, i_s)\n', (10291, 10311), True, 'import numpy as np\n'), ((10335, 10387), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.iteration', 'its', 'RTOL'], {}), '(reg.iteration, its, RTOL)\n', (10361, 10387), True, 'import numpy as np\n'), ((10426, 10468), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.mean_y', 'my'], {}), '(reg.mean_y, my)\n', (10452, 10468), True, 'import numpy as np\n'), ((10511, 10555), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.std_y', 'std_y'], {}), '(reg.std_y, std_y)\n', (10537, 10555), True, 'import numpy as np\n'), ((10597, 10637), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.pr2', 'pr2'], {}), '(reg.pr2, pr2)\n', (10623, 10637), True, 'import numpy as np\n'), ((10679, 10721), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.sig2', 'sig2'], {}), '(reg.sig2, sig2)\n', (10705, 10721), True, 'import numpy as np\n'), ((10756, 10815), 'numpy.array', 'np.array', (['[23.49604343, 0.73817223, 0.39433722, 0.19267128]'], {}), '([23.49604343, 0.73817223, 0.39433722, 0.19267128])\n', (10764, 10815), True, 'import numpy as np\n'), ((10829, 10883), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.std_err', 'std_err', 'RTOL'], {}), '(reg.std_err, std_err, RTOL)\n', (10855, 10883), True, 'import numpy as np\n'), ((10899, 11018), 'numpy.array', 'np.array', (['[[2.35638617, 0.01845372], [0.62901874, 0.52933679], [-1.69662923, \n 0.08976678], [2.24244556, 0.02493259]]'], {}), '([[2.35638617, 0.01845372], [0.62901874, 0.52933679], [-1.69662923,\n 0.08976678], [2.24244556, 0.02493259]])\n', (10907, 11018), True, 'import numpy as np\n'), ((11030, 11082), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.z_stat', 'z_stat', 'RTOL'], {}), '(reg.z_stat, z_stat, RTOL)\n', (11056, 11082), True, 'import numpy as np\n'), ((11290, 11312), 'numpy.reshape', 'np.reshape', (['y', '(49, 1)'], {}), '(y, (49, 1))\n', (11300, 11312), True, 'import numpy as np\n'), ((11720, 11807), 'pysal.model.spreg.error_sp_hom.BaseGM_Combo_Hom', 'HOM.BaseGM_Combo_Hom', (['self.y', 'self.X'], {'yend': 'yd2', 'q': 'q2', 'w': 'self.w.sparse', 'A1': '"""hom_sc"""'}), "(self.y, self.X, yend=yd2, q=q2, w=self.w.sparse, A1=\n 'hom_sc')\n", (11740, 11807), True, 'from pysal.model.spreg import error_sp_hom as HOM\n'), ((11887, 11910), 'numpy.array', 'np.array', (['[1.0, 19.531]'], {}), '([1.0, 19.531])\n', (11895, 11910), True, 'import numpy as np\n'), ((11926, 11971), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.x[0]', 'x', 'RTOL'], {}), '(reg.x[0], x, RTOL)\n', (11952, 11971), True, 'import numpy as np\n'), ((11986, 12053), 'numpy.array', 'np.array', (['[[10.12541428], [1.56832263], [0.15132076], [0.21033397]]'], {}), '([[10.12541428], [1.56832263], [0.15132076], [0.21033397]])\n', (11994, 12053), True, 'import numpy as np\n'), ((12069, 12119), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.betas', 'betas', 'RTOL'], {}), '(reg.betas, betas, RTOL)\n', (12095, 12119), True, 'import numpy as np\n'), ((12360, 12403), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.n', '(49)', 'RTOL'], {}), '(reg.n, 49, RTOL)\n', (12386, 12403), True, 'import numpy as np\n'), ((12410, 12452), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.k', '(3)', 'RTOL'], {}), '(reg.k, 3, RTOL)\n', (12436, 12452), True, 'import numpy as np\n'), ((12464, 12707), 'numpy.array', 'np.array', (['[[233.694742, -0.666856869, -5.58304254, 4.8548838], [-0.666856869, \n 0.194241504, -0.0542327138, 0.053722557], [-5.58304254, -0.0542327138, \n 0.163860721, -0.144425498], [4.8548838, 0.053722557, -0.144425498, \n 0.178622255]]'], {}), '([[233.694742, -0.666856869, -5.58304254, 4.8548838], [-0.666856869,\n 0.194241504, -0.0542327138, 0.053722557], [-5.58304254, -0.0542327138, \n 0.163860721, -0.144425498], [4.8548838, 0.053722557, -0.144425498, \n 0.178622255]])\n', (12472, 12707), True, 'import numpy as np\n'), ((12766, 12810), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.vm', 'vm', 'RTOL'], {}), '(reg.vm, vm, RTOL)\n', (12792, 12810), True, 'import numpy as np\n'), ((12821, 12856), 'numpy.array', 'np.array', (['[1.0, 19.531, 35.4585005]'], {}), '([1.0, 19.531, 35.4585005])\n', (12829, 12856), True, 'import numpy as np\n'), ((12879, 12924), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.z[0]', 'z', 'RTOL'], {}), '(reg.z[0], z, RTOL)\n', (12905, 12924), True, 'import numpy as np\n'), ((12935, 12966), 'numpy.array', 'np.array', (['[1.0, 19.531, 18.594]'], {}), '([1.0, 19.531, 18.594])\n', (12943, 12966), True, 'import numpy as np\n'), ((12981, 13026), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.h[0]', 'h', 'RTOL'], {}), '(reg.h[0], h, RTOL)\n', (13007, 13026), True, 'import numpy as np\n'), ((13040, 13062), 'numpy.array', 'np.array', (['[35.4585005]'], {}), '([35.4585005])\n', (13048, 13062), True, 'import numpy as np\n'), ((13072, 13123), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.yend[0]', 'yend', 'RTOL'], {}), '(reg.yend[0], yend, RTOL)\n', (13098, 13123), True, 'import numpy as np\n'), ((13134, 13152), 'numpy.array', 'np.array', (['[18.594]'], {}), '([18.594])\n', (13142, 13152), True, 'import numpy as np\n'), ((13162, 13207), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.q[0]', 'q', 'RTOL'], {}), '(reg.q[0], q, RTOL)\n', (13188, 13207), True, 'import numpy as np\n'), ((13268, 13318), 'numpy.testing.assert_string_equal', 'np.testing.assert_string_equal', (['reg.iter_stop', 'i_s'], {}), '(reg.iter_stop, i_s)\n', (13298, 13318), True, 'import numpy as np\n'), ((13342, 13394), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.iteration', 'its', 'RTOL'], {}), '(reg.iteration, its, RTOL)\n', (13368, 13394), True, 'import numpy as np\n'), ((13433, 13475), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.mean_y', 'my'], {}), '(reg.mean_y, my)\n', (13459, 13475), True, 'import numpy as np\n'), ((13518, 13562), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.std_y', 'std_y'], {}), '(reg.std_y, std_y)\n', (13544, 13562), True, 'import numpy as np\n'), ((13655, 13697), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.sig2', 'sig2'], {}), '(reg.sig2, sig2)\n', (13681, 13697), True, 'import numpy as np\n'), ((13711, 13848), 'numpy.array', 'np.array', (['[[49.0, 704.371999, 724.7435916], [704.371999, 11686.67338121, 11092.519988\n ], [724.7435916, 11092.519988, 11614.62257048]]'], {}), '([[49.0, 704.371999, 724.7435916], [704.371999, 11686.67338121, \n 11092.519988], [724.7435916, 11092.519988, 11614.62257048]])\n', (13719, 13848), True, 'import numpy as np\n'), ((13888, 13934), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.hth', 'hth', 'RTOL'], {}), '(reg.hth, hth, RTOL)\n', (13914, 13934), True, 'import numpy as np\n'), ((14138, 14160), 'numpy.reshape', 'np.reshape', (['y', '(49, 1)'], {}), '(y, (49, 1))\n', (14148, 14160), True, 'import numpy as np\n'), ((14412, 14467), 'pysal.model.spreg.error_sp_hom.GM_Combo_Hom', 'HOM.GM_Combo_Hom', (['self.y', 'self.X'], {'w': 'self.w', 'A1': '"""hom_sc"""'}), "(self.y, self.X, w=self.w, A1='hom_sc')\n", (14428, 14467), True, 'from pysal.model.spreg import error_sp_hom as HOM\n'), ((14552, 14575), 'numpy.array', 'np.array', (['[1.0, 19.531]'], {}), '([1.0, 19.531])\n', (14560, 14575), True, 'import numpy as np\n'), ((14591, 14636), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.x[0]', 'x', 'RTOL'], {}), '(reg.x[0], x, RTOL)\n', (14617, 14636), True, 'import numpy as np\n'), ((14651, 14718), 'numpy.array', 'np.array', (['[[10.12541428], [1.56832263], [0.15132076], [0.21033397]]'], {}), '([[10.12541428], [1.56832263], [0.15132076], [0.21033397]])\n', (14659, 14718), True, 'import numpy as np\n'), ((14734, 14784), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.betas', 'betas', 'RTOL'], {}), '(reg.betas, betas, RTOL)\n', (14760, 14784), True, 'import numpy as np\n'), ((15185, 15228), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.n', '(49)', 'RTOL'], {}), '(reg.n, 49, RTOL)\n', (15211, 15228), True, 'import numpy as np\n'), ((15235, 15277), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.k', '(3)', 'RTOL'], {}), '(reg.k, 3, RTOL)\n', (15261, 15277), True, 'import numpy as np\n'), ((15288, 15323), 'numpy.array', 'np.array', (['[1.0, 19.531, 35.4585005]'], {}), '([1.0, 19.531, 35.4585005])\n', (15296, 15323), True, 'import numpy as np\n'), ((15346, 15391), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.z[0]', 'z', 'RTOL'], {}), '(reg.z[0], z, RTOL)\n', (15372, 15391), True, 'import numpy as np\n'), ((15402, 15433), 'numpy.array', 'np.array', (['[1.0, 19.531, 18.594]'], {}), '([1.0, 19.531, 18.594])\n', (15410, 15433), True, 'import numpy as np\n'), ((15448, 15493), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.h[0]', 'h', 'RTOL'], {}), '(reg.h[0], h, RTOL)\n', (15474, 15493), True, 'import numpy as np\n'), ((15507, 15529), 'numpy.array', 'np.array', (['[35.4585005]'], {}), '([35.4585005])\n', (15515, 15529), True, 'import numpy as np\n'), ((15539, 15590), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.yend[0]', 'yend', 'RTOL'], {}), '(reg.yend[0], yend, RTOL)\n', (15565, 15590), True, 'import numpy as np\n'), ((15601, 15619), 'numpy.array', 'np.array', (['[18.594]'], {}), '([18.594])\n', (15609, 15619), True, 'import numpy as np\n'), ((15629, 15674), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.q[0]', 'q', 'RTOL'], {}), '(reg.q[0], q, RTOL)\n', (15655, 15674), True, 'import numpy as np\n'), ((15735, 15785), 'numpy.testing.assert_string_equal', 'np.testing.assert_string_equal', (['reg.iter_stop', 'i_s'], {}), '(reg.iter_stop, i_s)\n', (15765, 15785), True, 'import numpy as np\n'), ((15793, 15843), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.iteration', '(1)', 'RTOL'], {}), '(reg.iteration, 1, RTOL)\n', (15819, 15843), True, 'import numpy as np\n'), ((15882, 15924), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.mean_y', 'my'], {}), '(reg.mean_y, my)\n', (15908, 15924), True, 'import numpy as np\n'), ((15967, 16011), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.std_y', 'std_y'], {}), '(reg.std_y, std_y)\n', (15993, 16011), True, 'import numpy as np\n'), ((16053, 16093), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.pr2', 'pr2'], {}), '(reg.pr2, pr2)\n', (16079, 16093), True, 'import numpy as np\n'), ((16137, 16181), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.pr2_e', 'pr2_e'], {}), '(reg.pr2_e, pr2_e)\n', (16163, 16181), True, 'import numpy as np\n'), ((16275, 16317), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.sig2', 'sig2'], {}), '(reg.sig2, sig2)\n', (16301, 16317), True, 'import numpy as np\n'), ((16336, 16395), 'numpy.array', 'np.array', (['[15.28707761, 0.44072838, 0.40479714, 0.42263726]'], {}), '([15.28707761, 0.44072838, 0.40479714, 0.42263726])\n', (16344, 16395), True, 'import numpy as np\n'), ((16409, 16463), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.std_err', 'std_err', 'RTOL'], {}), '(reg.std_err, std_err, RTOL)\n', (16435, 16463), True, 'import numpy as np\n'), ((16479, 16606), 'numpy.array', 'np.array', (['[[0.662351206, 0.507746167], [3.55847888, 0.00037300878], [0.373818749, \n 0.70853917], [0.497670189, 0.618716523]]'], {}), '([[0.662351206, 0.507746167], [3.55847888, 0.00037300878], [\n 0.373818749, 0.70853917], [0.497670189, 0.618716523]])\n', (16487, 16606), True, 'import numpy as np\n'), ((16650, 16702), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.z_stat', 'z_stat', 'RTOL'], {}), '(reg.z_stat, z_stat, RTOL)\n', (16676, 16702), True, 'import numpy as np\n'), ((16714, 16957), 'numpy.array', 'np.array', (['[[233.694742, -0.666856869, -5.58304254, 4.8548838], [-0.666856869, \n 0.194241504, -0.0542327138, 0.053722557], [-5.58304254, -0.0542327138, \n 0.163860721, -0.144425498], [4.8548838, 0.053722557, -0.144425498, \n 0.178622255]]'], {}), '([[233.694742, -0.666856869, -5.58304254, 4.8548838], [-0.666856869,\n 0.194241504, -0.0542327138, 0.053722557], [-5.58304254, -0.0542327138, \n 0.163860721, -0.144425498], [4.8548838, 0.053722557, -0.144425498, \n 0.178622255]])\n', (16722, 16957), True, 'import numpy as np\n'), ((17016, 17060), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['reg.vm', 'vm', 'RTOL'], {}), '(reg.vm, vm, RTOL)\n', (17042, 17060), True, 'import numpy as np\n'), ((556, 567), 'numpy.array', 'np.array', (['X'], {}), '(X)\n', (564, 567), True, 'import numpy as np\n'), ((909, 930), 'numpy.array', 'np.array', (['[80.467003]'], {}), '([80.467003])\n', (917, 930), True, 'import numpy as np\n'), ((1237, 1258), 'numpy.array', 'np.array', (['[27.466734]'], {}), '([27.466734])\n', (1245, 1258), True, 'import numpy as np\n'), ((1318, 1341), 'numpy.array', 'np.array', (['[32.37298547]'], {}), '([32.37298547])\n', (1326, 1341), True, 'import numpy as np\n'), ((1509, 1530), 'numpy.array', 'np.array', (['[53.000269]'], {}), '([53.000269])\n', (1517, 1530), True, 'import numpy as np\n'), ((2655, 2666), 'numpy.array', 'np.array', (['X'], {}), '(X)\n', (2663, 2666), True, 'import numpy as np\n'), ((2938, 2959), 'numpy.array', 'np.array', (['[80.467003]'], {}), '([80.467003])\n', (2946, 2959), True, 'import numpy as np\n'), ((3266, 3289), 'numpy.array', 'np.array', (['[27.46673388]'], {}), '([27.46673388])\n', (3274, 3289), True, 'import numpy as np\n'), ((3349, 3372), 'numpy.array', 'np.array', (['[32.37298547]'], {}), '([32.37298547])\n', (3357, 3372), True, 'import numpy as np\n'), ((3428, 3451), 'numpy.array', 'np.array', (['[53.00026912]'], {}), '([53.00026912])\n', (3436, 3451), True, 'import numpy as np\n'), ((5353, 5364), 'numpy.array', 'np.array', (['X'], {}), '(X)\n', (5361, 5364), True, 'import numpy as np\n'), ((5498, 5510), 'numpy.array', 'np.array', (['yd'], {}), '(yd)\n', (5506, 5510), True, 'import numpy as np\n'), ((5583, 5594), 'numpy.array', 'np.array', (['q'], {}), '(q)\n', (5591, 5594), True, 'import numpy as np\n'), ((5900, 5921), 'numpy.array', 'np.array', (['[80.467003]'], {}), '([80.467003])\n', (5908, 5921), True, 'import numpy as np\n'), ((6701, 6724), 'numpy.array', 'np.array', (['[31.74114306]'], {}), '([31.74114306])\n', (6709, 6724), True, 'import numpy as np\n'), ((8331, 8342), 'numpy.array', 'np.array', (['X'], {}), '(X)\n', (8339, 8342), True, 'import numpy as np\n'), ((8417, 8429), 'numpy.array', 'np.array', (['yd'], {}), '(yd)\n', (8425, 8429), True, 'import numpy as np\n'), ((8502, 8513), 'numpy.array', 'np.array', (['q'], {}), '(q)\n', (8510, 8513), True, 'import numpy as np\n'), ((8808, 8829), 'numpy.array', 'np.array', (['[80.467003]'], {}), '([80.467003])\n', (8816, 8829), True, 'import numpy as np\n'), ((9609, 9632), 'numpy.array', 'np.array', (['[31.74114306]'], {}), '([31.74114306])\n', (9617, 9632), True, 'import numpy as np\n'), ((11379, 11390), 'numpy.array', 'np.array', (['X'], {}), '(X)\n', (11387, 11390), True, 'import numpy as np\n'), ((11847, 11868), 'numpy.array', 'np.array', (['[80.467003]'], {}), '([80.467003])\n', (11855, 11868), True, 'import numpy as np\n'), ((12162, 12184), 'numpy.array', 'np.array', (['[34.3450723]'], {}), '([34.3450723])\n', (12170, 12184), True, 'import numpy as np\n'), ((12244, 12266), 'numpy.array', 'np.array', (['[36.6149682]'], {}), '([36.6149682])\n', (12252, 12266), True, 'import numpy as np\n'), ((12322, 12344), 'numpy.array', 'np.array', (['[46.1219307]'], {}), '([46.1219307])\n', (12330, 12344), True, 'import numpy as np\n'), ((14227, 14238), 'numpy.array', 'np.array', (['X'], {}), '(X)\n', (14235, 14238), True, 'import numpy as np\n'), ((14512, 14533), 'numpy.array', 'np.array', (['[80.467003]'], {}), '([80.467003])\n', (14520, 14533), True, 'import numpy as np\n'), ((14827, 14849), 'numpy.array', 'np.array', (['[34.3450723]'], {}), '([34.3450723])\n', (14835, 14849), True, 'import numpy as np\n'), ((14909, 14931), 'numpy.array', 'np.array', (['[36.6149682]'], {}), '([36.6149682])\n', (14917, 14931), True, 'import numpy as np\n'), ((14988, 15011), 'numpy.array', 'np.array', (['[32.90372983]'], {}), '([32.90372983])\n', (14996, 15011), True, 'import numpy as np\n'), ((15067, 15089), 'numpy.array', 'np.array', (['[46.1219307]'], {}), '([46.1219307])\n', (15075, 15089), True, 'import numpy as np\n'), ((15147, 15170), 'numpy.array', 'np.array', (['[47.56327317]'], {}), '([47.56327317])\n', (15155, 15170), True, 'import numpy as np\n'), ((17305, 17326), 'unittest.TestLoader', 'unittest.TestLoader', ([], {}), '()\n', (17324, 17326), False, 'import unittest\n'), ((598, 619), 'numpy.ones', 'np.ones', (['self.y.shape'], {}), '(self.y.shape)\n', (605, 619), True, 'import numpy as np\n'), ((5395, 5416), 'numpy.ones', 'np.ones', (['self.y.shape'], {}), '(self.y.shape)\n', (5402, 5416), True, 'import numpy as np\n'), ((11675, 11696), 'numpy.ones', 'np.ones', (['self.y.shape'], {}), '(self.y.shape)\n', (11682, 11696), True, 'import numpy as np\n')]
|
'''
The code is partially borrowed from:
https://github.com/v-iashin/video_features/blob/861efaa4ed67/utils/utils.py
and
https://github.com/PeihaoChen/regnet/blob/199609/extract_audio_and_video.py
'''
import os
import shutil
import subprocess
from glob import glob
from pathlib import Path
from typing import Dict
import cv2
import matplotlib.pyplot as plt
import numpy as np
import torch
import torchvision.models as models
import torchvision.transforms as transforms
import torchvision.transforms.functional as F
from omegaconf.omegaconf import OmegaConf
from sample_visualization import (load_feature_extractor,
load_model_from_config, load_vocoder)
from specvqgan.data.vggsound import CropFeats
from specvqgan.util import download, md5_hash
from specvqgan.models.cond_transformer import disabled_train
from train import instantiate_from_config
from feature_extraction.extract_mel_spectrogram import get_spectrogram
plt.rcParams['savefig.bbox'] = 'tight'
def which_ffmpeg() -> str:
'''Determines the path to ffmpeg library
Returns:
str -- path to the library
'''
result = subprocess.run(['which', 'ffmpeg'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
ffmpeg_path = result.stdout.decode('utf-8').replace('\n', '')
return ffmpeg_path
def which_ffprobe() -> str:
'''Determines the path to ffprobe library
Returns:
str -- path to the library
'''
result = subprocess.run(['which', 'ffprobe'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
ffprobe_path = result.stdout.decode('utf-8').replace('\n', '')
return ffprobe_path
def check_video_for_audio(path):
assert which_ffprobe() != '', 'Is ffmpeg installed? Check if the conda environment is activated.'
cmd = f'{which_ffprobe()} -loglevel error -show_entries stream=codec_type -of default=nw=1 {path}'
result = subprocess.run(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
result = result.stdout.decode('utf-8')
print(result)
return 'codec_type=audio' in result
def get_duration(path):
assert which_ffprobe() != '', 'Is ffmpeg installed? Check if the conda environment is activated.'
cmd = f'{which_ffprobe()} -hide_banner -loglevel panic' \
f' -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 {path}'
result = subprocess.run(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
duration = float(result.stdout.decode('utf-8').replace('\n', ''))
return duration
def trim_video(video_path: str, start: int, trim_duration: int = 10, tmp_path: str = './tmp'):
assert which_ffmpeg() != '', 'Is ffmpeg installed? Check if the conda environment is activated.'
if Path(video_path).suffix != '.mp4':
print(f'File Extension is not `mp4` (it is {Path(video_path).suffix}). It will be re-encoded to mp4.')
video_duration = get_duration(video_path)
print('Video Duration:', video_duration)
assert video_duration > start, f'Video Duration < Trim Start: {video_duration} < {start}'
# create tmp dir if doesn't exist
os.makedirs(tmp_path, exist_ok=True)
trim_vid_path = os.path.join(tmp_path, f'{Path(video_path).stem}_trim_to_{trim_duration}s.mp4')
cmd = f'{which_ffmpeg()} -hide_banner -loglevel panic' \
f' -i {video_path} -ss {start} -t {trim_duration} -y {trim_vid_path}'
subprocess.call(cmd.split())
print('Trimmed the input video', video_path, 'and saved the output @', trim_vid_path)
return trim_vid_path
def reencode_video_with_diff_fps(video_path: str, tmp_path: str, extraction_fps: int) -> str:
'''Reencodes the video given the path and saves it to the tmp_path folder.
Args:
video_path (str): original video
tmp_path (str): the folder where tmp files are stored (will be appended with a proper filename).
extraction_fps (int): target fps value
Returns:
str: The path where the tmp file is stored. To be used to load the video from
'''
assert which_ffmpeg() != '', 'Is ffmpeg installed? Check if the conda environment is activated.'
# assert video_path.endswith('.mp4'), 'The file does not end with .mp4. Comment this if expected'
# create tmp dir if doesn't exist
os.makedirs(tmp_path, exist_ok=True)
# form the path to tmp directory
new_path = os.path.join(tmp_path, f'{Path(video_path).stem}_new_fps.mp4')
cmd = f'{which_ffmpeg()} -hide_banner -loglevel panic '
cmd += f'-y -i {video_path} -filter:v fps=fps={extraction_fps} {new_path}'
subprocess.call(cmd.split())
return new_path
def maybe_download_model(model_name: str, log_dir: str) -> str:
name2info = {
'2021-06-20T16-35-20_vggsound_transformer': {
'info': 'No Feats',
'hash': 'b1f9bb63d831611479249031a1203371',
'link': 'https://a3s.fi/swift/v1/AUTH_a235c0f452d648828f745589cde1219a'
'/specvqgan_public/models/2021-06-20T16-35-20_vggsound_transformer.tar.gz',
},
'2021-07-30T21-03-22_vggsound_transformer': {
'info': '1 ResNet50 Feature',
'hash': '27a61d4b74a72578d13579333ed056f6',
'link': 'https://a3s.fi/swift/v1/AUTH_a235c0f452d648828f745589cde1219a'
'/specvqgan_public/models/2021-07-30T21-03-22_vggsound_transformer.tar.gz',
},
'2021-07-30T21-34-25_vggsound_transformer': {
'info': '5 ResNet50 Features',
'hash': 'f4d7105811589d441b69f00d7d0b8dc8',
'link': 'https://a3s.fi/swift/v1/AUTH_a235c0f452d648828f745589cde1219a'
'/specvqgan_public/models/2021-07-30T21-34-25_vggsound_transformer.tar.gz',
},
'2021-07-30T21-34-41_vggsound_transformer': {
'info': '212 ResNet50 Features',
'hash': 'b222cc0e7aeb419f533d5806a08669fe',
'link': 'https://a3s.fi/swift/v1/AUTH_a235c0f452d648828f745589cde1219a'
'/specvqgan_public/models/2021-07-30T21-34-41_vggsound_transformer.tar.gz',
},
'2021-06-03T00-43-28_vggsound_transformer': {
'info': 'Class Label',
'hash': '98a3788ab973f1c3cc02e2e41ad253bc',
'link': 'https://a3s.fi/swift/v1/AUTH_a235c0f452d648828f745589cde1219a'
'/specvqgan_public/models/2021-06-03T00-43-28_vggsound_transformer.tar.gz',
},
'2021-05-19T22-16-54_vggsound_codebook': {
'info': 'VGGSound Codebook',
'hash': '7ea229427297b5d220fb1c80db32dbc5',
'link': 'https://a3s.fi/swift/v1/AUTH_a235c0f452d648828f745589cde1219a'
'/specvqgan_public/models/2021-05-19T22-16-54_vggsound_codebook.tar.gz',
}
}
print(f'Using: {model_name} ({name2info[model_name]["info"]})')
model_dir = os.path.join(log_dir, model_name)
if not os.path.exists(model_dir):
tar_local_path = os.path.join(log_dir, f'{model_name}.tar.gz')
# check if tar already exists and its md5sum
if not os.path.exists(tar_local_path) or md5_hash(tar_local_path) != name2info[model_name]['hash']:
down_link = name2info[model_name]['link']
download(down_link, tar_local_path)
print('Unpacking', tar_local_path, 'to', log_dir)
shutil.unpack_archive(tar_local_path, log_dir)
# clean-up space as we already have unpacked folder
os.remove(tar_local_path)
return model_dir
def load_config(model_dir: str):
# Load the config
config_main = sorted(glob(os.path.join(model_dir, 'configs/*-project.yaml')))[-1]
config_pylt = sorted(glob(os.path.join(model_dir, 'configs/*-lightning.yaml')))[-1]
config = OmegaConf.merge(
OmegaConf.load(config_main),
OmegaConf.load(config_pylt),
)
# patch config. E.g. if the model is trained on another machine with different paths
for a in ['spec_dir_path', 'rgb_feats_dir_path', 'flow_feats_dir_path']:
if config.data.params[a] is not None:
if 'vggsound.VGGSound' in config.data.params.train.target:
base_path = './data/vggsound/'
elif 'vas.VAS' in config.data.params.train.target:
base_path = './data/vas/features/*/'
else:
raise NotImplementedError
config.data.params[a] = os.path.join(base_path, Path(config.data.params[a]).name)
return config
def load_model(model_name, log_dir, device):
to_use_gpu = True if device.type == 'cuda' else False
model_dir = maybe_download_model(model_name, log_dir)
config = load_config(model_dir)
# Sampling model
ckpt = sorted(glob(os.path.join(model_dir, 'checkpoints/*.ckpt')))[-1]
pl_sd = torch.load(ckpt, map_location='cpu')
sampler = load_model_from_config(config.model, pl_sd['state_dict'], to_use_gpu)['model']
sampler.to(device)
# aux models (vocoder and melception)
ckpt_melgan = config.lightning.callbacks.image_logger.params.vocoder_cfg.params.ckpt_vocoder
melgan = load_vocoder(ckpt_melgan, eval_mode=True)['model'].to(device)
melception = load_feature_extractor(to_use_gpu, eval_mode=True)
return config, sampler, melgan, melception
def load_neural_audio_codec(model_name, log_dir, device):
model_dir = maybe_download_model(model_name, log_dir)
config = load_config(model_dir)
config.model.params.ckpt_path = f'./logs/{model_name}/checkpoints/last.ckpt'
print(config.model.params.ckpt_path)
model = instantiate_from_config(config.model)
model = model.to(device)
model = model.eval()
model.train = disabled_train
vocoder = load_vocoder(Path('./vocoder/logs/vggsound/'), eval_mode=True)['model'].to(device)
return config, model, vocoder
class LeftmostCropOrTile(object):
def __init__(self, crop_or_tile_to):
self.crop_or_tile_to = crop_or_tile_to
def __call__(self, item: Dict):
# tile or crop features to the `crop_or_tile_to`
T, D = item['feature'].shape
if T != self.crop_or_tile_to:
how_many_tiles_needed = 1 + (self.crop_or_tile_to // T)
item['feature'] = np.tile(item['feature'], (how_many_tiles_needed, 1))[:self.crop_or_tile_to, :]
return item
class ExtractResNet50(torch.nn.Module):
def __init__(self, extraction_fps, feat_cfg, device, batch_size=32, tmp_dir='./tmp'):
super(ExtractResNet50, self).__init__()
self.tmp_path = tmp_dir
self.extraction_fps = extraction_fps
self.batch_size = batch_size
self.feat_cfg = feat_cfg
self.means = [0.485, 0.456, 0.406]
self.stds = [0.229, 0.224, 0.225]
self.transforms = transforms.Compose([
transforms.ToPILImage(),
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=self.means, std=self.stds)
])
random_crop = False
self.post_transforms = transforms.Compose([
LeftmostCropOrTile(feat_cfg.feat_len),
CropFeats([feat_cfg.feat_crop_len, feat_cfg.feat_depth], random_crop),
(lambda x: x) if feat_cfg.feat_sampler_cfg is None else instantiate_from_config(feat_cfg.feat_sampler_cfg),
])
self.device = device
self.model = models.resnet50(pretrained=True).to(device)
self.model.eval()
# save the pre-trained classifier for show_preds and replace it in the net with identity
self.model_class = self.model.fc
self.model.fc = torch.nn.Identity()
@torch.no_grad()
def forward(self, video_path: str) -> Dict[str, np.ndarray]:
if self.feat_cfg.replace_feats_with_random:
T, D = self.feat_cfg.feat_sampler_cfg.params.feat_sample_size, self.feat_cfg.feat_depth
print(f'Since we are in "No Feats" setting, returning a random feature: [{T}, {D}]')
random_features = {'feature': torch.rand(T, D)}
return random_features, []
# take the video, change fps and save to the tmp folder
if self.extraction_fps is not None:
video_path = reencode_video_with_diff_fps(video_path, self.tmp_path, self.extraction_fps)
# read a video
cap = cv2.VideoCapture(video_path)
batch_list = []
vid_feats = []
cached_frames = []
transforms_for_show = transforms.Compose(self.transforms.transforms[:4])
# sometimes when the target fps is 1 or 2, the first frame of the reencoded video is missing
# and cap.read returns None but the rest of the frames are ok. timestep is 0.0 for the 2nd frame in
# this case
first_frame = True
# iterating through the opened video frame-by-frame and occationally run the model once a batch is
# formed
while cap.isOpened():
frame_exists, rgb = cap.read()
if first_frame and not frame_exists:
continue
first_frame = False
if frame_exists:
# prepare data and cache if needed
rgb = cv2.cvtColor(rgb, cv2.COLOR_BGR2RGB)
cached_frames.append(transforms_for_show(rgb))
rgb = self.transforms(rgb).unsqueeze(0).to(self.device)
batch_list.append(rgb)
# when batch is formed to inference
if len(batch_list) == self.batch_size:
batch_feats = self.model(torch.cat(batch_list))
vid_feats.extend(batch_feats.tolist())
# clean up the batch list
batch_list = []
else:
# if the last batch was smaller than the batch size, we still need to process those frames
if len(batch_list) != 0:
batch_feats = self.model(torch.cat(batch_list))
vid_feats.extend(batch_feats.tolist())
cap.release()
break
vid_feats = np.array(vid_feats)
features = {'feature': vid_feats}
print('Raw Extracted Representation:', features['feature'].shape)
if self.post_transforms is not None:
features = self.post_transforms(features)
# using 'feature' as the key to reuse the feature resampling transform
cached_frames = self.post_transforms.transforms[-1]({'feature': torch.stack(cached_frames)})['feature']
print('Post-processed Representation:', features['feature'].shape)
return features, cached_frames
def extract_melspectrogram(in_path: str, sr: int, duration: int = 10, tmp_path: str = './tmp') -> np.ndarray:
'''Extract Melspectrogram similar to RegNet.'''
assert which_ffmpeg() != '', 'Is ffmpeg installed? Check if the conda environment is activated.'
# assert in_path.endswith('.mp4'), 'The file does not end with .mp4. Comment this if expected'
# create tmp dir if doesn't exist
os.makedirs(tmp_path, exist_ok=True)
# Extract audio from a video if needed
if in_path.endswith('.wav'):
audio_raw = in_path
else:
audio_raw = os.path.join(tmp_path, f'{Path(in_path).stem}.wav')
cmd = f'{which_ffmpeg()} -i {in_path} -hide_banner -loglevel panic -f wav -vn -y {audio_raw}'
subprocess.call(cmd.split())
# Extract audio from a video
audio_new = os.path.join(tmp_path, f'{Path(in_path).stem}_{sr}hz.wav')
cmd = f'{which_ffmpeg()} -i {audio_raw} -hide_banner -loglevel panic -ac 1 -ab 16k -ar {sr} -y {audio_new}'
subprocess.call(cmd.split())
length = int(duration * sr)
audio_zero_pad, spec = get_spectrogram(audio_new, save_dir=None, length=length, save_results=False)
# specvqgan expects inputs to be in [-1, 1] but spectrograms are in [0, 1]
spec = 2 * spec - 1
return spec
def show_grid(imgs):
print('Rendering the Plot with Frames Used in Conditioning')
figsize = ((imgs.shape[1] // 228 + 1) * 5, (imgs.shape[2] // 228 + 1) * 5)
if not isinstance(imgs, list):
imgs = [imgs]
fig, axs = plt.subplots(ncols=len(imgs), squeeze=False, figsize=figsize)
for i, img in enumerate(imgs):
img = img.detach()
img = F.to_pil_image(img)
axs[0, i].imshow(np.asarray(img))
axs[0, i].set(xticklabels=[], yticklabels=[], xticks=[], yticks=[])
return fig
def calculate_codebook_bitrate(duration, quant_z, codebook_size):
# Calculating the Bitrate
bottle_neck_size = quant_z.shape[-2:]
bits_per_codebook_entry = (codebook_size-1).bit_length()
bitrate = bits_per_codebook_entry * bottle_neck_size.numel() / duration / 1024
print(f'The input audio is {duration:.2f} seconds long.')
print(f'Codebook size is {codebook_size} i.e. a codebook entry allocates {bits_per_codebook_entry} bits')
print(f'SpecVQGAN bottleneck size: {list(bottle_neck_size)}')
print(f'Thus, bitrate is {bitrate:.2f} kbps')
return bitrate
def get_audio_file_bitrate(file):
assert which_ffprobe() != '', 'Is ffmpeg installed? Check if the conda environment is activated.'
cmd = f'{which_ffprobe()} -v error -select_streams a:0'\
f' -show_entries stream=bit_rate -of default=noprint_wrappers=1:nokey=1 {file}'
result = subprocess.run(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
bitrate = int(result.stdout.decode('utf-8').replace('\n', ''))
bitrate /= 1024
return bitrate
if __name__ == '__main__':
# if empty, it wasn't found
print(which_ffmpeg())
|
[
"os.remove",
"train.instantiate_from_config",
"omegaconf.omegaconf.OmegaConf.load",
"torch.cat",
"pathlib.Path",
"numpy.tile",
"feature_extraction.extract_mel_spectrogram.get_spectrogram",
"torchvision.transforms.Normalize",
"torch.no_grad",
"os.path.join",
"sample_visualization.load_vocoder",
"cv2.cvtColor",
"torch.load",
"specvqgan.data.vggsound.CropFeats",
"os.path.exists",
"torchvision.transforms.ToPILImage",
"torchvision.transforms.functional.to_pil_image",
"torchvision.transforms.Compose",
"specvqgan.util.md5_hash",
"torchvision.transforms.CenterCrop",
"sample_visualization.load_feature_extractor",
"numpy.asarray",
"torchvision.models.resnet50",
"sample_visualization.load_model_from_config",
"torch.rand",
"torch.nn.Identity",
"torchvision.transforms.Resize",
"subprocess.run",
"shutil.unpack_archive",
"os.makedirs",
"torch.stack",
"cv2.VideoCapture",
"numpy.array",
"specvqgan.util.download",
"torchvision.transforms.ToTensor"
] |
[((1139, 1229), 'subprocess.run', 'subprocess.run', (["['which', 'ffmpeg']"], {'stdout': 'subprocess.PIPE', 'stderr': 'subprocess.STDOUT'}), "(['which', 'ffmpeg'], stdout=subprocess.PIPE, stderr=\n subprocess.STDOUT)\n", (1153, 1229), False, 'import subprocess\n'), ((1459, 1550), 'subprocess.run', 'subprocess.run', (["['which', 'ffprobe']"], {'stdout': 'subprocess.PIPE', 'stderr': 'subprocess.STDOUT'}), "(['which', 'ffprobe'], stdout=subprocess.PIPE, stderr=\n subprocess.STDOUT)\n", (1473, 1550), False, 'import subprocess\n'), ((3117, 3153), 'os.makedirs', 'os.makedirs', (['tmp_path'], {'exist_ok': '(True)'}), '(tmp_path, exist_ok=True)\n', (3128, 3153), False, 'import os\n'), ((4276, 4312), 'os.makedirs', 'os.makedirs', (['tmp_path'], {'exist_ok': '(True)'}), '(tmp_path, exist_ok=True)\n', (4287, 4312), False, 'import os\n'), ((6832, 6865), 'os.path.join', 'os.path.join', (['log_dir', 'model_name'], {}), '(log_dir, model_name)\n', (6844, 6865), False, 'import os\n'), ((8747, 8783), 'torch.load', 'torch.load', (['ckpt'], {'map_location': '"""cpu"""'}), "(ckpt, map_location='cpu')\n", (8757, 8783), False, 'import torch\n'), ((9132, 9182), 'sample_visualization.load_feature_extractor', 'load_feature_extractor', (['to_use_gpu'], {'eval_mode': '(True)'}), '(to_use_gpu, eval_mode=True)\n', (9154, 9182), False, 'from sample_visualization import load_feature_extractor, load_model_from_config, load_vocoder\n'), ((9518, 9555), 'train.instantiate_from_config', 'instantiate_from_config', (['config.model'], {}), '(config.model)\n', (9541, 9555), False, 'from train import instantiate_from_config\n'), ((11600, 11615), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (11613, 11615), False, 'import torch\n'), ((14976, 15012), 'os.makedirs', 'os.makedirs', (['tmp_path'], {'exist_ok': '(True)'}), '(tmp_path, exist_ok=True)\n', (14987, 15012), False, 'import os\n'), ((15653, 15729), 'feature_extraction.extract_mel_spectrogram.get_spectrogram', 'get_spectrogram', (['audio_new'], {'save_dir': 'None', 'length': 'length', 'save_results': '(False)'}), '(audio_new, save_dir=None, length=length, save_results=False)\n', (15668, 15729), False, 'from feature_extraction.extract_mel_spectrogram import get_spectrogram\n'), ((6877, 6902), 'os.path.exists', 'os.path.exists', (['model_dir'], {}), '(model_dir)\n', (6891, 6902), False, 'import os\n'), ((6929, 6974), 'os.path.join', 'os.path.join', (['log_dir', 'f"""{model_name}.tar.gz"""'], {}), "(log_dir, f'{model_name}.tar.gz')\n", (6941, 6974), False, 'import os\n'), ((7750, 7777), 'omegaconf.omegaconf.OmegaConf.load', 'OmegaConf.load', (['config_main'], {}), '(config_main)\n', (7764, 7777), False, 'from omegaconf.omegaconf import OmegaConf\n'), ((7787, 7814), 'omegaconf.omegaconf.OmegaConf.load', 'OmegaConf.load', (['config_pylt'], {}), '(config_pylt)\n', (7801, 7814), False, 'from omegaconf.omegaconf import OmegaConf\n'), ((8798, 8867), 'sample_visualization.load_model_from_config', 'load_model_from_config', (['config.model', "pl_sd['state_dict']", 'to_use_gpu'], {}), "(config.model, pl_sd['state_dict'], to_use_gpu)\n", (8820, 8867), False, 'from sample_visualization import load_feature_extractor, load_model_from_config, load_vocoder\n'), ((11574, 11593), 'torch.nn.Identity', 'torch.nn.Identity', ([], {}), '()\n', (11591, 11593), False, 'import torch\n'), ((12279, 12307), 'cv2.VideoCapture', 'cv2.VideoCapture', (['video_path'], {}), '(video_path)\n', (12295, 12307), False, 'import cv2\n'), ((12412, 12462), 'torchvision.transforms.Compose', 'transforms.Compose', (['self.transforms.transforms[:4]'], {}), '(self.transforms.transforms[:4])\n', (12430, 12462), True, 'import torchvision.transforms as transforms\n'), ((14020, 14039), 'numpy.array', 'np.array', (['vid_feats'], {}), '(vid_feats)\n', (14028, 14039), True, 'import numpy as np\n'), ((16228, 16247), 'torchvision.transforms.functional.to_pil_image', 'F.to_pil_image', (['img'], {}), '(img)\n', (16242, 16247), True, 'import torchvision.transforms.functional as F\n'), ((2742, 2758), 'pathlib.Path', 'Path', (['video_path'], {}), '(video_path)\n', (2746, 2758), False, 'from pathlib import Path\n'), ((7202, 7237), 'specvqgan.util.download', 'download', (['down_link', 'tar_local_path'], {}), '(down_link, tar_local_path)\n', (7210, 7237), False, 'from specvqgan.util import download, md5_hash\n'), ((7312, 7358), 'shutil.unpack_archive', 'shutil.unpack_archive', (['tar_local_path', 'log_dir'], {}), '(tar_local_path, log_dir)\n', (7333, 7358), False, 'import shutil\n'), ((7435, 7460), 'os.remove', 'os.remove', (['tar_local_path'], {}), '(tar_local_path)\n', (7444, 7460), False, 'import os\n'), ((16273, 16288), 'numpy.asarray', 'np.asarray', (['img'], {}), '(img)\n', (16283, 16288), True, 'import numpy as np\n'), ((7043, 7073), 'os.path.exists', 'os.path.exists', (['tar_local_path'], {}), '(tar_local_path)\n', (7057, 7073), False, 'import os\n'), ((7077, 7101), 'specvqgan.util.md5_hash', 'md5_hash', (['tar_local_path'], {}), '(tar_local_path)\n', (7085, 7101), False, 'from specvqgan.util import download, md5_hash\n'), ((7568, 7617), 'os.path.join', 'os.path.join', (['model_dir', '"""configs/*-project.yaml"""'], {}), "(model_dir, 'configs/*-project.yaml')\n", (7580, 7617), False, 'import os\n'), ((7654, 7705), 'os.path.join', 'os.path.join', (['model_dir', '"""configs/*-lightning.yaml"""'], {}), "(model_dir, 'configs/*-lightning.yaml')\n", (7666, 7705), False, 'import os\n'), ((8683, 8728), 'os.path.join', 'os.path.join', (['model_dir', '"""checkpoints/*.ckpt"""'], {}), "(model_dir, 'checkpoints/*.ckpt')\n", (8695, 8728), False, 'import os\n'), ((9053, 9094), 'sample_visualization.load_vocoder', 'load_vocoder', (['ckpt_melgan'], {'eval_mode': '(True)'}), '(ckpt_melgan, eval_mode=True)\n', (9065, 9094), False, 'from sample_visualization import load_feature_extractor, load_model_from_config, load_vocoder\n'), ((10164, 10216), 'numpy.tile', 'np.tile', (["item['feature']", '(how_many_tiles_needed, 1)'], {}), "(item['feature'], (how_many_tiles_needed, 1))\n", (10171, 10216), True, 'import numpy as np\n'), ((10735, 10758), 'torchvision.transforms.ToPILImage', 'transforms.ToPILImage', ([], {}), '()\n', (10756, 10758), True, 'import torchvision.transforms as transforms\n'), ((10772, 10794), 'torchvision.transforms.Resize', 'transforms.Resize', (['(256)'], {}), '(256)\n', (10789, 10794), True, 'import torchvision.transforms as transforms\n'), ((10808, 10834), 'torchvision.transforms.CenterCrop', 'transforms.CenterCrop', (['(224)'], {}), '(224)\n', (10829, 10834), True, 'import torchvision.transforms as transforms\n'), ((10848, 10869), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (10867, 10869), True, 'import torchvision.transforms as transforms\n'), ((10883, 10935), 'torchvision.transforms.Normalize', 'transforms.Normalize', ([], {'mean': 'self.means', 'std': 'self.stds'}), '(mean=self.means, std=self.stds)\n', (10903, 10935), True, 'import torchvision.transforms as transforms\n'), ((11090, 11159), 'specvqgan.data.vggsound.CropFeats', 'CropFeats', (['[feat_cfg.feat_crop_len, feat_cfg.feat_depth]', 'random_crop'], {}), '([feat_cfg.feat_crop_len, feat_cfg.feat_depth], random_crop)\n', (11099, 11159), False, 'from specvqgan.data.vggsound import CropFeats\n'), ((11342, 11374), 'torchvision.models.resnet50', 'models.resnet50', ([], {'pretrained': '(True)'}), '(pretrained=True)\n', (11357, 11374), True, 'import torchvision.models as models\n'), ((11973, 11989), 'torch.rand', 'torch.rand', (['T', 'D'], {}), '(T, D)\n', (11983, 11989), False, 'import torch\n'), ((13127, 13163), 'cv2.cvtColor', 'cv2.cvtColor', (['rgb', 'cv2.COLOR_BGR2RGB'], {}), '(rgb, cv2.COLOR_BGR2RGB)\n', (13139, 13163), False, 'import cv2\n'), ((3200, 3216), 'pathlib.Path', 'Path', (['video_path'], {}), '(video_path)\n', (3204, 3216), False, 'from pathlib import Path\n'), ((4392, 4408), 'pathlib.Path', 'Path', (['video_path'], {}), '(video_path)\n', (4396, 4408), False, 'from pathlib import Path\n'), ((8388, 8415), 'pathlib.Path', 'Path', (['config.data.params[a]'], {}), '(config.data.params[a])\n', (8392, 8415), False, 'from pathlib import Path\n'), ((9670, 9702), 'pathlib.Path', 'Path', (['"""./vocoder/logs/vggsound/"""'], {}), "('./vocoder/logs/vggsound/')\n", (9674, 9702), False, 'from pathlib import Path\n'), ((11229, 11279), 'train.instantiate_from_config', 'instantiate_from_config', (['feat_cfg.feat_sampler_cfg'], {}), '(feat_cfg.feat_sampler_cfg)\n', (11252, 11279), False, 'from train import instantiate_from_config\n'), ((15415, 15428), 'pathlib.Path', 'Path', (['in_path'], {}), '(in_path)\n', (15419, 15428), False, 'from pathlib import Path\n'), ((2829, 2845), 'pathlib.Path', 'Path', (['video_path'], {}), '(video_path)\n', (2833, 2845), False, 'from pathlib import Path\n'), ((13490, 13511), 'torch.cat', 'torch.cat', (['batch_list'], {}), '(batch_list)\n', (13499, 13511), False, 'import torch\n'), ((13865, 13886), 'torch.cat', 'torch.cat', (['batch_list'], {}), '(batch_list)\n', (13874, 13886), False, 'import torch\n'), ((14415, 14441), 'torch.stack', 'torch.stack', (['cached_frames'], {}), '(cached_frames)\n', (14426, 14441), False, 'import torch\n'), ((15174, 15187), 'pathlib.Path', 'Path', (['in_path'], {}), '(in_path)\n', (15178, 15187), False, 'from pathlib import Path\n')]
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Author: <NAME>
Description:
This PySPark scripts maps geolocated mobility data for valid users
to specific land use type where the activity occured and counts
number of unique users within each land use type aggregated to 250m x 250m
neighborhoods in New York City.
"""
# imports
from pyspark.sql.session import SparkSession
from pyspark.sql.functions import col, concat, lit, substring, countDistinct, date_format, to_date, upper
from pyspark.sql.types import * # import types
import numpy as np
from math import sin, cos, sqrt, atan2, radians
spark = SparkSession.builder.getOrCreate()
def distance_km(x1, y1, x2, y2):
# approximate radius of earth in km
R = 6373.0
lat1 = radians(y1)
lon1 = radians(x1)
lat2 = radians(y2)
lon2 = radians(x2)
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2
c = 2 * atan2(sqrt(a), sqrt(1 - a))
distance = R * c
return distance
# Load grid data
land_use = spark.read.parquet('/raster/grid_classification/parquet_grid_data/')
x_raster_step = 0.000009
y_raster_step = 0.000012
# Load venpath data activity
df = spark.read.parquet('<directory-to-mobility-data-on-HDFS>')
df = df.withColumn('ad_id_upper', upper(col('ad_id')))
# define boundaries extent
llc_lon = -74.2555954656
llc_lat = 40.4961100684
urc_lon = -73.7000071112
urc_lat = 40.9155259862
# subset data based on bounding box
nyc = df.filter((col('ad_id')!='00000000-0000-0000-0000-000000000000') \
& (col('lon')>=llc_lon) \
& (col('lon')<=urc_lon) \
& (col('lat')>=llc_lat) \
& (col('lat')<=urc_lat) )
# create date column
nyc = nyc.withColumn("date", to_date(col("timestamp")))
# find valid users based on number of days active
ad_id_count = nyc.groupby("ad_id_upper").agg(countDistinct("date").alias('day_count')).withColumnRenamed("ad_id_upper", "id")
ad_id_count_filtered = ad_id_count.filter((col("day_count")>14))
nyc = nyc.join(ad_id_count_filtered, nyc.ad_id_upper == ad_id_count_filtered.id, how='inner')
# cast raster cell indices
nyc = nyc.withColumn("x_raster_cell", ((nyc["lon"]-llc_lon) / x_raster_step).cast('integer'))
nyc = nyc.withColumn("y_raster_cell", ((nyc["lat"]-llc_lat) / y_raster_step).cast('integer'))
# join with land use raster
nyc = nyc.join(land_use, (nyc.x_raster_cell == land_use.x_cell) & (nyc.y_raster_cell == land_use.y_cell), how='left')
# calculate the extent of the bounding box in kilometers
xx = distance_km(llc_lon, np.mean([llc_lat, urc_lat]), urc_lon, np.mean([llc_lat, urc_lat]))
yy = distance_km(np.mean([llc_lon, urc_lon]), llc_lat, np.mean([llc_lon, urc_lon]), urc_lat)
# find number of 500 m cels in x and y dimension
x_grid = xx / 0.25
y_grid = yy / 0.25
# define the x and y step size in geographic coordinates
x_grid_step = (urc_lon - llc_lon)/x_grid
y_grid_step = (urc_lat - llc_lat)/y_grid
# assign cell x, y, coordiantes and index for each ping
nyc = nyc.withColumn("x_250m_cell", ((nyc["lon"]-llc_lon) / x_grid_step).cast('integer'))
nyc = nyc.withColumn("cell_250m_lon", llc_lon+nyc["x_250m_cell"]*x_grid_step+0.5*x_grid_step)
nyc = nyc.withColumn("y_250m_cell", ((nyc["lat"]-llc_lat) / y_grid_step).cast('integer'))
nyc = nyc.withColumn("cell_250m_lat", llc_lat+nyc["y_250m_cell"]*y_grid_step+0.5*y_grid_step)
nyc = nyc.withColumn('cell_index', concat(col("x_250m_cell"), lit(";"), col("y_250m_cell")))
# create hour column
nyc = nyc.withColumn("hour", date_format(col("timestamp").cast("timestamp"), "yyyy-MM-dd HH:00"))
# count cell aggregations and save to file
hourly_counts = nyc.groupby("hour", "cell_index", "class").agg(countDistinct("ad_id_upper"))
hourly_counts.write \
.format("com.databricks.spark.csv") \
.mode("overwrite") \
.save("/user/bjb417/covid/output/nyc/nyc_land_use/nyc_250mGrid_landUse_uniqueDev_hourlyCounts_active14days.csv")
# save 250m x 250m grid information
grid = nyc.select("cell_index", "x_250m_cell", "y_250m_cell", "cell_250m_lon", "cell_250m_lat") \
.drop_duplicates(subset=['cell_index'])
grid.write \
.format("com.databricks.spark.csv") \
.mode("overwrite") \
.save("/user/bjb417/covid/output/nyc/nyc_land_use/nyc_250mGrid_landUse_active14days.csv")
|
[
"math.sqrt",
"math.radians",
"pyspark.sql.functions.lit",
"math.sin",
"numpy.mean",
"pyspark.sql.functions.col",
"math.cos",
"pyspark.sql.session.SparkSession.builder.getOrCreate",
"pyspark.sql.functions.countDistinct"
] |
[((610, 644), 'pyspark.sql.session.SparkSession.builder.getOrCreate', 'SparkSession.builder.getOrCreate', ([], {}), '()\n', (642, 644), False, 'from pyspark.sql.session import SparkSession\n'), ((736, 747), 'math.radians', 'radians', (['y1'], {}), '(y1)\n', (743, 747), False, 'from math import sin, cos, sqrt, atan2, radians\n'), ((756, 767), 'math.radians', 'radians', (['x1'], {}), '(x1)\n', (763, 767), False, 'from math import sin, cos, sqrt, atan2, radians\n'), ((776, 787), 'math.radians', 'radians', (['y2'], {}), '(y2)\n', (783, 787), False, 'from math import sin, cos, sqrt, atan2, radians\n'), ((796, 807), 'math.radians', 'radians', (['x2'], {}), '(x2)\n', (803, 807), False, 'from math import sin, cos, sqrt, atan2, radians\n'), ((2490, 2517), 'numpy.mean', 'np.mean', (['[llc_lat, urc_lat]'], {}), '([llc_lat, urc_lat])\n', (2497, 2517), True, 'import numpy as np\n'), ((2528, 2555), 'numpy.mean', 'np.mean', (['[llc_lat, urc_lat]'], {}), '([llc_lat, urc_lat])\n', (2535, 2555), True, 'import numpy as np\n'), ((2574, 2601), 'numpy.mean', 'np.mean', (['[llc_lon, urc_lon]'], {}), '([llc_lon, urc_lon])\n', (2581, 2601), True, 'import numpy as np\n'), ((2612, 2639), 'numpy.mean', 'np.mean', (['[llc_lon, urc_lon]'], {}), '([llc_lon, urc_lon])\n', (2619, 2639), True, 'import numpy as np\n'), ((3625, 3653), 'pyspark.sql.functions.countDistinct', 'countDistinct', (['"""ad_id_upper"""'], {}), "('ad_id_upper')\n", (3638, 3653), False, 'from pyspark.sql.functions import col, concat, lit, substring, countDistinct, date_format, to_date, upper\n'), ((1268, 1280), 'pyspark.sql.functions.col', 'col', (['"""ad_id"""'], {}), "('ad_id')\n", (1271, 1280), False, 'from pyspark.sql.functions import col, concat, lit, substring, countDistinct, date_format, to_date, upper\n'), ((1687, 1703), 'pyspark.sql.functions.col', 'col', (['"""timestamp"""'], {}), "('timestamp')\n", (1690, 1703), False, 'from pyspark.sql.functions import col, concat, lit, substring, countDistinct, date_format, to_date, upper\n'), ((1926, 1942), 'pyspark.sql.functions.col', 'col', (['"""day_count"""'], {}), "('day_count')\n", (1929, 1942), False, 'from pyspark.sql.functions import col, concat, lit, substring, countDistinct, date_format, to_date, upper\n'), ((3347, 3365), 'pyspark.sql.functions.col', 'col', (['"""x_250m_cell"""'], {}), "('x_250m_cell')\n", (3350, 3365), False, 'from pyspark.sql.functions import col, concat, lit, substring, countDistinct, date_format, to_date, upper\n'), ((3367, 3375), 'pyspark.sql.functions.lit', 'lit', (['""";"""'], {}), "(';')\n", (3370, 3375), False, 'from pyspark.sql.functions import col, concat, lit, substring, countDistinct, date_format, to_date, upper\n'), ((3377, 3395), 'pyspark.sql.functions.col', 'col', (['"""y_250m_cell"""'], {}), "('y_250m_cell')\n", (3380, 3395), False, 'from pyspark.sql.functions import col, concat, lit, substring, countDistinct, date_format, to_date, upper\n'), ((853, 866), 'math.sin', 'sin', (['(dlat / 2)'], {}), '(dlat / 2)\n', (856, 866), False, 'from math import sin, cos, sqrt, atan2, radians\n'), ((928, 935), 'math.sqrt', 'sqrt', (['a'], {}), '(a)\n', (932, 935), False, 'from math import sin, cos, sqrt, atan2, radians\n'), ((937, 948), 'math.sqrt', 'sqrt', (['(1 - a)'], {}), '(1 - a)\n', (941, 948), False, 'from math import sin, cos, sqrt, atan2, radians\n'), ((1605, 1615), 'pyspark.sql.functions.col', 'col', (['"""lat"""'], {}), "('lat')\n", (1608, 1615), False, 'from pyspark.sql.functions import col, concat, lit, substring, countDistinct, date_format, to_date, upper\n'), ((872, 881), 'math.cos', 'cos', (['lat1'], {}), '(lat1)\n', (875, 881), False, 'from math import sin, cos, sqrt, atan2, radians\n'), ((884, 893), 'math.cos', 'cos', (['lat2'], {}), '(lat2)\n', (887, 893), False, 'from math import sin, cos, sqrt, atan2, radians\n'), ((896, 909), 'math.sin', 'sin', (['(dlon / 2)'], {}), '(dlon / 2)\n', (899, 909), False, 'from math import sin, cos, sqrt, atan2, radians\n'), ((1578, 1588), 'pyspark.sql.functions.col', 'col', (['"""lat"""'], {}), "('lat')\n", (1581, 1588), False, 'from pyspark.sql.functions import col, concat, lit, substring, countDistinct, date_format, to_date, upper\n'), ((3461, 3477), 'pyspark.sql.functions.col', 'col', (['"""timestamp"""'], {}), "('timestamp')\n", (3464, 3477), False, 'from pyspark.sql.functions import col, concat, lit, substring, countDistinct, date_format, to_date, upper\n'), ((1551, 1561), 'pyspark.sql.functions.col', 'col', (['"""lon"""'], {}), "('lon')\n", (1554, 1561), False, 'from pyspark.sql.functions import col, concat, lit, substring, countDistinct, date_format, to_date, upper\n'), ((1802, 1823), 'pyspark.sql.functions.countDistinct', 'countDistinct', (['"""date"""'], {}), "('date')\n", (1815, 1823), False, 'from pyspark.sql.functions import col, concat, lit, substring, countDistinct, date_format, to_date, upper\n'), ((1464, 1476), 'pyspark.sql.functions.col', 'col', (['"""ad_id"""'], {}), "('ad_id')\n", (1467, 1476), False, 'from pyspark.sql.functions import col, concat, lit, substring, countDistinct, date_format, to_date, upper\n'), ((1524, 1534), 'pyspark.sql.functions.col', 'col', (['"""lon"""'], {}), "('lon')\n", (1527, 1534), False, 'from pyspark.sql.functions import col, concat, lit, substring, countDistinct, date_format, to_date, upper\n')]
|
import os
import random
import argparse
import numpy as np
from PIL import Image, ImageDraw, ImageFont
def make_blank_placeholder(image_file, out_file):
#print(out_file)
image = np.asarray(Image.open(image_file))
blank = np.ones(image.shape)*255
blank = blank.astype(np.uint8)
#print(blank.shape)
im = Image.fromarray(blank)
draw = ImageDraw.Draw(im)
(x, y) = ((image.shape[0]//2)-50+random.randint(-10,10), (image.shape[1]//2)-50+random.randint(-10,10))
font = ImageFont.truetype('/Library/Fonts/Arial Bold.ttf', 45)
message = "No Data"
color = 'rgb(0, 0, 0)' # black color
draw.text((x, y), message, fill=color, font=font)
#im.convert('L')
im.save(out_file)
def reduce_quality(image_file):
im = Image.open(image_file)
im.save(image_file, quality=90)
def main():
parser = argparse.ArgumentParser(description='Process some images.')
parser.add_argument('--path', metavar='path', type=str,
help='path to images')
parser.add_argument('--volume_identifier', metavar='vol_id', type=str,
help='unique volume identifier e.g. 3R_ROI1')
args = parser.parse_args()
path = args.path
vol_id = args.volume_identifier
#old_dirpath=None
images = []
id_nums = []
'''
metadata = {'Raw Z resolution (nm)': 50,
'Raw XY resolution (nm)': 10,
'Volume ID': vol_id,
'default_frame': 3,
'#set': None}
'''
manifest = open(os.path.join(path+'manifest.csv'),'w')
manifest.write((',').join(['image1', 'image2', 'image3', 'image4', 'image5', 'Raw Z resolution (nm)', 'Raw XY resolution (nm)', 'Volume ID', 'default_frame', '#set\n']))
for (dirpath, dirnames, filenames) in os.walk(path):
#if dirpath != old_dirpath:
# images = []
# id_nums = []
for f in filenames:
'''
metadata = {'Raw Z resolution (nm)': 50,
'Raw XY resolution (nm)': 10,
'default_frame': 3}
'''
image_file = os.path.join(dirpath, f)
if '.DS_Store' in image_file:
continue
if '.csv' in image_file:
continue
#print(image_file)
#if 'ROI1' in image_file:
# reduce_quality(image_file)
file_stub = image_file.strip('.jpg')[:-3] + '%03d_blank.jpg'
id_num = image_file.strip('.jpg')[-3:]
if id_num == 'ank':
continue
if id_num == 'opy':
id_num = image_file.strip(' copy.jpg')[-3:]
file_stub = image_file.strip(' copy.jpg')[:-3] + '%03d_blank.jpg'
id_nums.append(int(id_num))
images.append(image_file)
if images == []:
continue
sorted_images = [x for _,x in sorted(zip(id_nums,images))]
id_nums.sort()
make_blank_placeholder(images[0], file_stub%(id_nums[0]-2))
make_blank_placeholder(images[0], file_stub%(id_nums[0]-1))
make_blank_placeholder(images[0], file_stub%(id_nums[-1]+1))
make_blank_placeholder(images[0], file_stub%(id_nums[-1]+2))
images = [file_stub%(id_nums[0]-2), file_stub%(id_nums[0]-1)] + \
sorted_images + \
[file_stub%(id_nums[-1]+1), file_stub%(id_nums[-1]+2)]
#print(len(images))
for i in range(2,len(images)-2, 1):
#print(len(images[i-2:i+3]))
print(images[i-2:i+3])
#print(','.join(images[i-2:i+2]))
manifest.write((',').join([im.split('/')[-1] for im in images[i-2:i+3]]+['50', '10', vol_id, '3', dirpath.split('/')[-1]])+'\n')
if __name__ == '__main__':
main()
|
[
"argparse.ArgumentParser",
"random.randint",
"os.walk",
"numpy.ones",
"PIL.Image.open",
"PIL.ImageFont.truetype",
"PIL.Image.fromarray",
"PIL.ImageDraw.Draw",
"os.path.join"
] |
[((317, 339), 'PIL.Image.fromarray', 'Image.fromarray', (['blank'], {}), '(blank)\n', (332, 339), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((349, 367), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['im'], {}), '(im)\n', (363, 367), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((483, 538), 'PIL.ImageFont.truetype', 'ImageFont.truetype', (['"""/Library/Fonts/Arial Bold.ttf"""', '(45)'], {}), "('/Library/Fonts/Arial Bold.ttf', 45)\n", (501, 538), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((731, 753), 'PIL.Image.open', 'Image.open', (['image_file'], {}), '(image_file)\n', (741, 753), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((812, 871), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Process some images."""'}), "(description='Process some images.')\n", (835, 871), False, 'import argparse\n'), ((1715, 1728), 'os.walk', 'os.walk', (['path'], {}), '(path)\n', (1722, 1728), False, 'import os\n'), ((196, 218), 'PIL.Image.open', 'Image.open', (['image_file'], {}), '(image_file)\n', (206, 218), False, 'from PIL import Image, ImageDraw, ImageFont\n'), ((230, 250), 'numpy.ones', 'np.ones', (['image.shape'], {}), '(image.shape)\n', (237, 250), True, 'import numpy as np\n'), ((1464, 1499), 'os.path.join', 'os.path.join', (["(path + 'manifest.csv')"], {}), "(path + 'manifest.csv')\n", (1476, 1499), False, 'import os\n'), ((403, 426), 'random.randint', 'random.randint', (['(-10)', '(10)'], {}), '(-10, 10)\n', (417, 426), False, 'import random\n'), ((450, 473), 'random.randint', 'random.randint', (['(-10)', '(10)'], {}), '(-10, 10)\n', (464, 473), False, 'import random\n'), ((1997, 2021), 'os.path.join', 'os.path.join', (['dirpath', 'f'], {}), '(dirpath, f)\n', (2009, 2021), False, 'import os\n')]
|
import pickle
import logging
import hashlib
import numpy as np
import os
from pathlib import Path
import spacy
import shutil
import sys
import tarfile
import tempfile
import torch
from typing import Dict, List
sys.path.append("nbsvm")
from nltk import word_tokenize
from nltk.stem import WordNetLemmatizer
from nltk.stem.snowball import SnowballStemmer
from nltk.corpus import stopwords
from lime.lime_text import LimeTextExplainer
from allennlp.models.archival import load_archive
from allennlp.data import Vocabulary
from allennlp.data.dataset_readers import DatasetReader
from flask import Flask, request, Response, jsonify, render_template, send_from_directory
logging.basicConfig(level=logging.INFO)
stemmer = SnowballStemmer('english')
stopWords = set(stopwords.words('english'))
class LemmaTokenizer(object):
def __init__(self):
self.wnl = WordNetLemmatizer()
def __call__(self, articles):
return [stemmer.stem(self.wnl.lemmatize(t)) for t in word_tokenize(articles) if t not in stopWords]
# this was done to make sure the model unpickles correctly (may not actually be necessary)
setattr(sys.modules["__main__"], LemmaTokenizer.__name__, LemmaTokenizer)
class LimePredictor(object):
def __init__(self, idx2label: Dict[int, str]):
self.idx2label = idx2label
self.label2idx = {v: k for k, v in idx2label.items()}
self.class_names = [idx2label[i] for i in range(len(self.idx2label))]
def predict(self, text: str) -> Dict[str, np.ndarray]:
raise NotImplementedError
def predict_batch(self, texts: List[str]) -> np.ndarray:
raise NotImplementedError
class NBSVMLimePredictor(LimePredictor):
def __init__(self, model_path: str):
model_path = Path(model_path)
with open(str(model_path), "rb") as f:
self.model = pickle.load(f)
nbsvm = self.model.steps[1][1]
nbsvm.predict_proba = nbsvm._predict_proba_lr
self.idx2label = {i: l for i, l in enumerate(nbsvm.classes_.tolist())}
super(NBSVMLimePredictor, self).__init__(self.idx2label)
def predict(self, text: str) -> Dict[str, np.ndarray]:
out = {}
out['label'] = self.model.predict([text])[0]
logits = self.model.predict_proba([text])[0]
out['logits'] = logits
out['probs'] = logits
return out
def predict_batch(self, texts: List[str]) -> np.ndarray:
return self.model.predict_proba(texts)
class AllenNLPLimePredictor(LimePredictor):
def __init__(self, archive_path: str, device: int = -1, batch_size: int = 32):
archive_path = Path(archive_path)
archive = load_archive(archive_path)
self.params = archive.config
self.model = archive.model.eval()
self.batch_size = batch_size
self.reader = DatasetReader.from_params(self.params.get("dataset_reader"))
self.vocab = self._load_vocab(archive_path)
self.idx2label = self.vocab.get_index_to_token_vocabulary('labels')
if device != -1:
self.model.to(f"cuda:{device}")
super(AllenNLPLimePredictor, self).__init__(self.idx2label)
@staticmethod
def _load_vocab(archive_path: Path) -> Vocabulary:
# an annoying hack to load the vocab file
tempdir = tempfile.mkdtemp()
with tarfile.open(archive_path, 'r:gz') as _archive:
_archive.extractall(tempdir)
vocab_path = Path(tempdir) / "vocabulary"
vocab = Vocabulary.from_files(vocab_path)
shutil.rmtree(tempdir)
return vocab
def predict(self, text: str) -> Dict[str, np.ndarray]:
return self.model.forward_on_instance(self.reader.text_to_instance(text))
def predict_batch(self, texts: List[str]) -> np.ndarray:
with torch.no_grad():
instances = [self.reader.text_to_instance(t) for t in texts]
instance_chunks = [instances[x: x + self.batch_size] for x in
range(0, len(instances), self.batch_size)]
preds = []
for batch in instance_chunks:
pred = self.model.forward_on_instances(batch)
preds.extend(pred)
probs = [p['probs'] for p in preds]
return np.stack(probs, axis=0)
class ServerError(Exception):
status_code = 400
def __init__(self, message, status_code=None, payload=None):
Exception.__init__(self)
self.message = message
if status_code is not None:
self.status_code = status_code
self.payload = payload
def to_dict(self):
error_dict = dict(self.payload or ())
error_dict['message'] = self.message
return error_dict
app = Flask(__name__) # pylint: disable=invalid-name
# We hash the javascript file and use it as a cache breaker
hasher = hashlib.md5()
app_js = open("static/app.js")
hasher.update(app_js.read().encode('utf-8'))
js_hash = hasher.hexdigest()
nlp = spacy.load('en_core_web_sm', disable=['vectors', 'textcat', 'tagger', 'ner'])
# nlp.add_pipe(nlp.create_pipe('sentencizer'))
split_expr = lambda text: [sent.string.strip() for sent in nlp(text).sents]
home_path = Path(os.environ.get("HOME", "."))
nbsvm_predictor = NBSVMLimePredictor(home_path / ".models/nbsvm_imdb_sent_500.pkl")
device = 0 if torch.cuda.is_available() else -1
bert_predictor = AllenNLPLimePredictor(home_path / ".models/bert_base_1000.tar.gz", device=device)
nbsvm_explainer = LimeTextExplainer(class_names=nbsvm_predictor.class_names,
bow=True, split_expression=split_expr)
bert_explainer = LimeTextExplainer(class_names=bert_predictor.class_names,
bow=False, split_expression=split_expr)
models = {
'bert': {'explainer': bert_explainer, 'predictor': bert_predictor},
'nbsvm': {'explainer': nbsvm_explainer, 'predictor': nbsvm_predictor}
}
@app.errorhandler(ServerError)
def handle_invalid_usage(error: ServerError) -> Response: # pylint: disable=unused-variable
response = jsonify(error.to_dict())
response.status_code = error.status_code
return response
@app.route('/')
def index() -> Response: # pylint: disable=unused-variable
return render_template(
'app.html',
google_analytics_ua="UA-120916510-5", # TODO:don't hardcode this!
js_hash=js_hash
)
@app.route('/static/<path:path>')
def static_proxy(path: str) -> Response: # pylint: disable=unused-variable
return send_from_directory('static', path)
@app.route('/predict', methods=['POST', 'OPTIONS'])
def predict() -> Response: # pylint: disable=unused-variable
if request.method == "OPTIONS":
return Response(response="", status=200)
data = request.get_json()
previous_str = data["previous"]
# Log the query
app.logger.info(f"<{previous_str}>")
lime_tokens = split_expr(previous_str)
model_name = data.get("model_name", "BERT").lower()
predictor = models[model_name]['predictor']
explainer = models[model_name]['explainer']
app.logger.info(f"Using model {model_name}")
out = predictor.predict(previous_str)
class_probabilities = out['probs'].tolist()
label = out['label']
explanation = explainer.explain_instance(previous_str, predictor.predict_batch,
num_features=10, labels=[1], num_samples=100)
score_dict = dict(explanation.as_list(1))
lime_scores = [score_dict.get(tok, 0.) for tok in lime_tokens]
if predictor.label2idx['neg'] != 0:
# we need to reverse the lime scores
lime_scores = [-1 * score for score in lime_scores]
# make sure class probabilities are always consistently ordered
class_probabilities = [class_probabilities[predictor.label2idx[lbl]] for lbl in ['neg', 'pos']]
app.logger.info(label)
app.logger.info(lime_scores)
app.logger.info(lime_tokens)
app.logger.info(class_probabilities)
return jsonify({
"lime_scores": lime_scores,
"lime_tokens": lime_tokens,
"label": label,
"class_probabilities": class_probabilities,
"words": lime_tokens,
"output": previous_str,
"sentiment": label
})
if __name__ == "__main__":
app.run(host='0.0.0.0', threaded=False)
|
[
"flask.jsonify",
"pathlib.Path",
"pickle.load",
"shutil.rmtree",
"torch.no_grad",
"allennlp.data.Vocabulary.from_files",
"flask.request.get_json",
"nltk.word_tokenize",
"sys.path.append",
"nltk.stem.WordNetLemmatizer",
"spacy.load",
"tempfile.mkdtemp",
"flask.render_template",
"tarfile.open",
"flask.send_from_directory",
"flask.Response",
"lime.lime_text.LimeTextExplainer",
"numpy.stack",
"hashlib.md5",
"torch.cuda.is_available",
"nltk.corpus.stopwords.words",
"nltk.stem.snowball.SnowballStemmer",
"logging.basicConfig",
"flask.Flask",
"os.environ.get",
"allennlp.models.archival.load_archive"
] |
[((210, 234), 'sys.path.append', 'sys.path.append', (['"""nbsvm"""'], {}), "('nbsvm')\n", (225, 234), False, 'import sys\n'), ((670, 709), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (689, 709), False, 'import logging\n'), ((721, 747), 'nltk.stem.snowball.SnowballStemmer', 'SnowballStemmer', (['"""english"""'], {}), "('english')\n", (736, 747), False, 'from nltk.stem.snowball import SnowballStemmer\n'), ((4703, 4718), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (4708, 4718), False, 'from flask import Flask, request, Response, jsonify, render_template, send_from_directory\n'), ((4820, 4833), 'hashlib.md5', 'hashlib.md5', ([], {}), '()\n', (4831, 4833), False, 'import hashlib\n'), ((4946, 5023), 'spacy.load', 'spacy.load', (['"""en_core_web_sm"""'], {'disable': "['vectors', 'textcat', 'tagger', 'ner']"}), "('en_core_web_sm', disable=['vectors', 'textcat', 'tagger', 'ner'])\n", (4956, 5023), False, 'import spacy\n'), ((5444, 5545), 'lime.lime_text.LimeTextExplainer', 'LimeTextExplainer', ([], {'class_names': 'nbsvm_predictor.class_names', 'bow': '(True)', 'split_expression': 'split_expr'}), '(class_names=nbsvm_predictor.class_names, bow=True,\n split_expression=split_expr)\n', (5461, 5545), False, 'from lime.lime_text import LimeTextExplainer\n'), ((5593, 5694), 'lime.lime_text.LimeTextExplainer', 'LimeTextExplainer', ([], {'class_names': 'bert_predictor.class_names', 'bow': '(False)', 'split_expression': 'split_expr'}), '(class_names=bert_predictor.class_names, bow=False,\n split_expression=split_expr)\n', (5610, 5694), False, 'from lime.lime_text import LimeTextExplainer\n'), ((764, 790), 'nltk.corpus.stopwords.words', 'stopwords.words', (['"""english"""'], {}), "('english')\n", (779, 790), False, 'from nltk.corpus import stopwords\n'), ((5165, 5192), 'os.environ.get', 'os.environ.get', (['"""HOME"""', '"""."""'], {}), "('HOME', '.')\n", (5179, 5192), False, 'import os\n'), ((5292, 5317), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (5315, 5317), False, 'import torch\n'), ((6204, 6291), 'flask.render_template', 'render_template', (['"""app.html"""'], {'google_analytics_ua': '"""UA-120916510-5"""', 'js_hash': 'js_hash'}), "('app.html', google_analytics_ua='UA-120916510-5', js_hash=\n js_hash)\n", (6219, 6291), False, 'from flask import Flask, request, Response, jsonify, render_template, send_from_directory\n'), ((6468, 6503), 'flask.send_from_directory', 'send_from_directory', (['"""static"""', 'path'], {}), "('static', path)\n", (6487, 6503), False, 'from flask import Flask, request, Response, jsonify, render_template, send_from_directory\n'), ((6717, 6735), 'flask.request.get_json', 'request.get_json', ([], {}), '()\n', (6733, 6735), False, 'from flask import Flask, request, Response, jsonify, render_template, send_from_directory\n'), ((7943, 8142), 'flask.jsonify', 'jsonify', (["{'lime_scores': lime_scores, 'lime_tokens': lime_tokens, 'label': label,\n 'class_probabilities': class_probabilities, 'words': lime_tokens,\n 'output': previous_str, 'sentiment': label}"], {}), "({'lime_scores': lime_scores, 'lime_tokens': lime_tokens, 'label':\n label, 'class_probabilities': class_probabilities, 'words': lime_tokens,\n 'output': previous_str, 'sentiment': label})\n", (7950, 8142), False, 'from flask import Flask, request, Response, jsonify, render_template, send_from_directory\n'), ((868, 887), 'nltk.stem.WordNetLemmatizer', 'WordNetLemmatizer', ([], {}), '()\n', (885, 887), False, 'from nltk.stem import WordNetLemmatizer\n'), ((1751, 1767), 'pathlib.Path', 'Path', (['model_path'], {}), '(model_path)\n', (1755, 1767), False, 'from pathlib import Path\n'), ((2617, 2635), 'pathlib.Path', 'Path', (['archive_path'], {}), '(archive_path)\n', (2621, 2635), False, 'from pathlib import Path\n'), ((2654, 2680), 'allennlp.models.archival.load_archive', 'load_archive', (['archive_path'], {}), '(archive_path)\n', (2666, 2680), False, 'from allennlp.models.archival import load_archive\n'), ((3287, 3305), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), '()\n', (3303, 3305), False, 'import tempfile\n'), ((3474, 3507), 'allennlp.data.Vocabulary.from_files', 'Vocabulary.from_files', (['vocab_path'], {}), '(vocab_path)\n', (3495, 3507), False, 'from allennlp.data import Vocabulary\n'), ((3516, 3538), 'shutil.rmtree', 'shutil.rmtree', (['tempdir'], {}), '(tempdir)\n', (3529, 3538), False, 'import shutil\n'), ((4236, 4259), 'numpy.stack', 'np.stack', (['probs'], {'axis': '(0)'}), '(probs, axis=0)\n', (4244, 4259), True, 'import numpy as np\n'), ((6671, 6704), 'flask.Response', 'Response', ([], {'response': '""""""', 'status': '(200)'}), "(response='', status=200)\n", (6679, 6704), False, 'from flask import Flask, request, Response, jsonify, render_template, send_from_directory\n'), ((1840, 1854), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (1851, 1854), False, 'import pickle\n'), ((3319, 3353), 'tarfile.open', 'tarfile.open', (['archive_path', '"""r:gz"""'], {}), "(archive_path, 'r:gz')\n", (3331, 3353), False, 'import tarfile\n'), ((3429, 3442), 'pathlib.Path', 'Path', (['tempdir'], {}), '(tempdir)\n', (3433, 3442), False, 'from pathlib import Path\n'), ((3777, 3792), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (3790, 3792), False, 'import torch\n'), ((984, 1007), 'nltk.word_tokenize', 'word_tokenize', (['articles'], {}), '(articles)\n', (997, 1007), False, 'from nltk import word_tokenize\n')]
|
import numpy as np
import matplotlib.pyplot as plt
# 计算delta
def calculate_delta(t, chosen_count, item):
if chosen_count[item] == 0:
return 1
else:
return np.sqrt(2 * np.log(t) / chosen_count[item])
def choose_arm(upper_bound_probs):
max = np.max(upper_bound_probs)
idx = np.where(upper_bound_probs == max) # 返回tuple,包含符合条件值的下标
idx = np.array(idx[0]) # 转为array
if np.size(idx) == 1:
return idx[0]
else:
return np.random.choice(idx, 1)[0]
def train():
# 时间
T = []
# 可选的臂(根据数据)
num_arms = 10
# 总回报
total_reward = 0
total_best_reward = 0
total_reward_with_T = []
total_regret_with_T = []
np.random.seed(23)
true_rewards_prop = np.random.uniform(low=0, high=1, size=num_arms) # 每个老虎机真实的吐钱概率
true_max_prop_arm = np.argmax(true_rewards_prop)
print("true reward prop: \n", true_rewards_prop)
print("\ntrue_max_prop_arm: ", true_max_prop_arm)
estimated_rewards = np.zeros(num_arms) # 每个老虎机吐钱的观测概率,初始都为0
chosen_count = np.zeros(num_arms) # 每个老虎机当前已经探索的次数,初始都为0
# for i in range(10):
# choosen_arm = i % 10
# reward = np.random.binomial(n=1, p=true_rewards_prop[choosen_arm])
# best_reward = np.random.binomial(n=1, p=true_rewards_prop[true_max_prop_arm])
#
# total_reward += reward
# total_best_reward += best_reward
# T.append(i)
# total_reward_with_T.append(total_reward)
# total_regret_with_T.append(total_best_reward - total_reward)
#
# if i < 10:
# estimated_rewards[choosen_arm] = reward
# else:
# # estimated_rewards[choosen_arm] = ((i - 1) * estimated_rewards[choosen_arm] + reward) / i
# estimated_rewards[choosen_arm] = (chosen_count[choosen_arm] * estimated_rewards[choosen_arm] + reward) / (
# chosen_count[choosen_arm] + 1)
# chosen_count[choosen_arm] += 1
print("\ninit estimated reward: ")
print(estimated_rewards)
# 初始化
for t in range(0, 20000):
upper_bound_probs = [estimated_rewards[item] + calculate_delta(t, chosen_count, item) for item in
range(num_arms)]
# 选择最大置信区间上界的arm
# choosen_arm = np.argmax(upper_bound_probs)
choosen_arm = choose_arm(upper_bound_probs)
reward = np.random.binomial(n=1, p=true_rewards_prop[choosen_arm])
best_reward = np.random.binomial(n=1, p=true_rewards_prop[true_max_prop_arm])
total_reward += reward
total_best_reward += best_reward
T.append(t)
total_reward_with_T.append(total_reward)
total_regret_with_T.append(total_best_reward - total_reward)
# 更新每个老虎机的吐钱概率
# estimated_rewards[choosen_arm] = ((t - 1) * estimated_rewards[choosen_arm] + reward) / t
estimated_rewards[choosen_arm] = (chosen_count[choosen_arm] * estimated_rewards[choosen_arm] + reward) / (
chosen_count[choosen_arm] + 1)
chosen_count[choosen_arm] += 1
# if t % 200 == 0:
# print("estimated reward: ")
# print(estimated_rewards)
print("\ntotal reward: ", total_reward)
print("\nbest reward: ", total_best_reward)
print("\nestimated reward: ")
print(estimated_rewards)
print("\nchoosen arm: ", chosen_count)
# CTR趋势画图
plt.xlabel("T")
plt.ylabel("Total regret")
plt.plot(T, total_regret_with_T)
# 存入路径
plt.savefig('./regret1.png')
if __name__ == "__main__":
# 训练
train()
|
[
"numpy.random.uniform",
"numpy.size",
"numpy.random.seed",
"numpy.random.binomial",
"matplotlib.pyplot.plot",
"numpy.argmax",
"numpy.log",
"numpy.zeros",
"numpy.max",
"numpy.where",
"numpy.array",
"numpy.random.choice",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.savefig"
] |
[((272, 297), 'numpy.max', 'np.max', (['upper_bound_probs'], {}), '(upper_bound_probs)\n', (278, 297), True, 'import numpy as np\n'), ((308, 342), 'numpy.where', 'np.where', (['(upper_bound_probs == max)'], {}), '(upper_bound_probs == max)\n', (316, 342), True, 'import numpy as np\n'), ((375, 391), 'numpy.array', 'np.array', (['idx[0]'], {}), '(idx[0])\n', (383, 391), True, 'import numpy as np\n'), ((699, 717), 'numpy.random.seed', 'np.random.seed', (['(23)'], {}), '(23)\n', (713, 717), True, 'import numpy as np\n'), ((743, 790), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(0)', 'high': '(1)', 'size': 'num_arms'}), '(low=0, high=1, size=num_arms)\n', (760, 790), True, 'import numpy as np\n'), ((831, 859), 'numpy.argmax', 'np.argmax', (['true_rewards_prop'], {}), '(true_rewards_prop)\n', (840, 859), True, 'import numpy as np\n'), ((994, 1012), 'numpy.zeros', 'np.zeros', (['num_arms'], {}), '(num_arms)\n', (1002, 1012), True, 'import numpy as np\n'), ((1055, 1073), 'numpy.zeros', 'np.zeros', (['num_arms'], {}), '(num_arms)\n', (1063, 1073), True, 'import numpy as np\n'), ((3387, 3402), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""T"""'], {}), "('T')\n", (3397, 3402), True, 'import matplotlib.pyplot as plt\n'), ((3407, 3433), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Total regret"""'], {}), "('Total regret')\n", (3417, 3433), True, 'import matplotlib.pyplot as plt\n'), ((3438, 3470), 'matplotlib.pyplot.plot', 'plt.plot', (['T', 'total_regret_with_T'], {}), '(T, total_regret_with_T)\n', (3446, 3470), True, 'import matplotlib.pyplot as plt\n'), ((3486, 3514), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""./regret1.png"""'], {}), "('./regret1.png')\n", (3497, 3514), True, 'import matplotlib.pyplot as plt\n'), ((410, 422), 'numpy.size', 'np.size', (['idx'], {}), '(idx)\n', (417, 422), True, 'import numpy as np\n'), ((2376, 2433), 'numpy.random.binomial', 'np.random.binomial', ([], {'n': '(1)', 'p': 'true_rewards_prop[choosen_arm]'}), '(n=1, p=true_rewards_prop[choosen_arm])\n', (2394, 2433), True, 'import numpy as np\n'), ((2456, 2519), 'numpy.random.binomial', 'np.random.binomial', ([], {'n': '(1)', 'p': 'true_rewards_prop[true_max_prop_arm]'}), '(n=1, p=true_rewards_prop[true_max_prop_arm])\n', (2474, 2519), True, 'import numpy as np\n'), ((476, 500), 'numpy.random.choice', 'np.random.choice', (['idx', '(1)'], {}), '(idx, 1)\n', (492, 500), True, 'import numpy as np\n'), ((193, 202), 'numpy.log', 'np.log', (['t'], {}), '(t)\n', (199, 202), True, 'import numpy as np\n')]
|
"""
===============================================
Repair EEG artefacts caused by ocular movements
===============================================
Identify "bad" components in ICA solution (e.g., components which are highly
correlated the time course of the electrooculogram).
Authors: <NAME> <<EMAIL>>
License: BSD (3-clause)
"""
import numpy as np
import matplotlib.pyplot as plt
from mne import open_report, events_from_annotations, Epochs
from mne.io import read_raw_fif
from mne.preprocessing import read_ica, corrmap
# All parameters are defined in config.py
from config import fname, parser, LoggingFormat
# Handle command line arguments
args = parser.parse_args()
subject = args.subject
print(LoggingFormat.PURPLE +
LoggingFormat.BOLD +
'Finding and removing bad components for subject %s' % subject +
LoggingFormat.END)
###############################################################################
# 1) Import the output from previous processing step
input_file = fname.output(subject=subject,
processing_step='repair_bads',
file_type='raw.fif')
raw = read_raw_fif(input_file, preload=True)
# activate average reference
raw.apply_proj()
###############################################################################
# 2) Import ICA weights from precious processing step
ica_file = fname.output(subject=subject,
processing_step='fit_ica',
file_type='ica.fif')
ica = read_ica(ica_file)
###############################################################################
# 3) Find bad components via correlation with template ICA
temp_subjs = [2, 10]
# temp_raws = []
temp_icas = []
# import template subjects
for subj in temp_subjs:
# temp_raws.append(read_raw_fif(fname.output(subject=subj,
# processing_step='repair_bads',
# file_type='raw.fif')))
temp_icas.append(read_ica(fname.output(subject=subj,
processing_step='fit_ica',
file_type='ica.fif')))
# set thresholds for correlation
if subject in {5, 28, 32, 39, 45}:
threshold = 0.90
else:
threshold = 0.85
# compute correlations with template ocular movements up/down and left/right
corrmap(icas=[temp_icas[1], ica],
template=(0, 0), threshold=threshold, label='blink_up', plot=False)
corrmap(icas=[temp_icas[1], ica],
template=(0, 1), threshold=threshold, label='blink_side', plot=False)
# compute correlations with template ocular movements that look slightly
# different
corrmap(icas=[temp_icas[0], ica],
template=(0, 0), threshold=threshold, label='blink_misc', plot=False)
corrmap(icas=[temp_icas[0], ica],
template=(0, 1), threshold=threshold, label='blink_misc', plot=False)
###############################################################################
# 4) Create summary plots to show signal correction on main experimental
# condition
# create a-cue epochs
a_evs = events_from_annotations(raw, regexp='^(70)')[0]
a_epo = Epochs(raw, a_evs,
tmin=-2.0,
tmax=2.0,
reject_by_annotation=True,
proj=False,
preload=True)
a_epo.apply_baseline(baseline=(-0.3, -0.05))
a_evo = a_epo.average()
# loop over identified "bad" components
bad_components = []
for label in ica.labels_:
bad_components.extend(ica.labels_[label])
for bad_comp in np.unique(bad_components):
# show component frequency spectrum
fig_comp = ica.plot_properties(a_epo,
picks=bad_comp,
psd_args={'fmax': 35.},
show=False)[0]
# show how the signal is affected by component rejection
fig_evoked = ica.plot_overlay(a_evo, exclude=[bad_comp], show=False)
plt.close(fig_evoked)
# create HTML report
with open_report(fname.report(subject=subject)[0]) as report:
report.add_figs_to_section(fig_comp, 'Component %s identified '
'by correlation with template'
% bad_comp,
section='ICA',
replace=True)
report.add_figs_to_section(fig_evoked, 'Component %s rejected'
% bad_comp,
section='ICA',
replace=True)
report.save(fname.report(subject=subject)[1], overwrite=True,
open_browser=False)
# add bad components to exclusion list
ica.exclude = np.unique(bad_components)
# apply ica weights to data
ica.apply(raw)
###############################################################################
# 5) Save repaired data set
# output path
output_path = fname.output(processing_step='repaired_with_ica',
subject=subject,
file_type='raw.fif')
# save file
raw.save(output_path, overwrite=True)
|
[
"mne.io.read_raw_fif",
"mne.events_from_annotations",
"config.parser.parse_args",
"mne.preprocessing.read_ica",
"matplotlib.pyplot.close",
"mne.preprocessing.corrmap",
"mne.Epochs",
"config.fname.report",
"config.fname.output",
"numpy.unique"
] |
[((659, 678), 'config.parser.parse_args', 'parser.parse_args', ([], {}), '()\n', (676, 678), False, 'from config import fname, parser, LoggingFormat\n'), ((1002, 1088), 'config.fname.output', 'fname.output', ([], {'subject': 'subject', 'processing_step': '"""repair_bads"""', 'file_type': '"""raw.fif"""'}), "(subject=subject, processing_step='repair_bads', file_type=\n 'raw.fif')\n", (1014, 1088), False, 'from config import fname, parser, LoggingFormat\n'), ((1142, 1180), 'mne.io.read_raw_fif', 'read_raw_fif', (['input_file'], {'preload': '(True)'}), '(input_file, preload=True)\n', (1154, 1180), False, 'from mne.io import read_raw_fif\n'), ((1373, 1450), 'config.fname.output', 'fname.output', ([], {'subject': 'subject', 'processing_step': '"""fit_ica"""', 'file_type': '"""ica.fif"""'}), "(subject=subject, processing_step='fit_ica', file_type='ica.fif')\n", (1385, 1450), False, 'from config import fname, parser, LoggingFormat\n'), ((1505, 1523), 'mne.preprocessing.read_ica', 'read_ica', (['ica_file'], {}), '(ica_file)\n', (1513, 1523), False, 'from mne.preprocessing import read_ica, corrmap\n'), ((2372, 2477), 'mne.preprocessing.corrmap', 'corrmap', ([], {'icas': '[temp_icas[1], ica]', 'template': '(0, 0)', 'threshold': 'threshold', 'label': '"""blink_up"""', 'plot': '(False)'}), "(icas=[temp_icas[1], ica], template=(0, 0), threshold=threshold,\n label='blink_up', plot=False)\n", (2379, 2477), False, 'from mne.preprocessing import read_ica, corrmap\n'), ((2482, 2589), 'mne.preprocessing.corrmap', 'corrmap', ([], {'icas': '[temp_icas[1], ica]', 'template': '(0, 1)', 'threshold': 'threshold', 'label': '"""blink_side"""', 'plot': '(False)'}), "(icas=[temp_icas[1], ica], template=(0, 1), threshold=threshold,\n label='blink_side', plot=False)\n", (2489, 2589), False, 'from mne.preprocessing import read_ica, corrmap\n'), ((2680, 2787), 'mne.preprocessing.corrmap', 'corrmap', ([], {'icas': '[temp_icas[0], ica]', 'template': '(0, 0)', 'threshold': 'threshold', 'label': '"""blink_misc"""', 'plot': '(False)'}), "(icas=[temp_icas[0], ica], template=(0, 0), threshold=threshold,\n label='blink_misc', plot=False)\n", (2687, 2787), False, 'from mne.preprocessing import read_ica, corrmap\n'), ((2792, 2899), 'mne.preprocessing.corrmap', 'corrmap', ([], {'icas': '[temp_icas[0], ica]', 'template': '(0, 1)', 'threshold': 'threshold', 'label': '"""blink_misc"""', 'plot': '(False)'}), "(icas=[temp_icas[0], ica], template=(0, 1), threshold=threshold,\n label='blink_misc', plot=False)\n", (2799, 2899), False, 'from mne.preprocessing import read_ica, corrmap\n'), ((3157, 3254), 'mne.Epochs', 'Epochs', (['raw', 'a_evs'], {'tmin': '(-2.0)', 'tmax': '(2.0)', 'reject_by_annotation': '(True)', 'proj': '(False)', 'preload': '(True)'}), '(raw, a_evs, tmin=-2.0, tmax=2.0, reject_by_annotation=True, proj=\n False, preload=True)\n', (3163, 3254), False, 'from mne import open_report, events_from_annotations, Epochs\n'), ((3544, 3569), 'numpy.unique', 'np.unique', (['bad_components'], {}), '(bad_components)\n', (3553, 3569), True, 'import numpy as np\n'), ((4743, 4768), 'numpy.unique', 'np.unique', (['bad_components'], {}), '(bad_components)\n', (4752, 4768), True, 'import numpy as np\n'), ((4950, 5041), 'config.fname.output', 'fname.output', ([], {'processing_step': '"""repaired_with_ica"""', 'subject': 'subject', 'file_type': '"""raw.fif"""'}), "(processing_step='repaired_with_ica', subject=subject,\n file_type='raw.fif')\n", (4962, 5041), False, 'from config import fname, parser, LoggingFormat\n'), ((3101, 3145), 'mne.events_from_annotations', 'events_from_annotations', (['raw'], {'regexp': '"""^(70)"""'}), "(raw, regexp='^(70)')\n", (3124, 3145), False, 'from mne import open_report, events_from_annotations, Epochs\n'), ((3952, 3973), 'matplotlib.pyplot.close', 'plt.close', (['fig_evoked'], {}), '(fig_evoked)\n', (3961, 3973), True, 'import matplotlib.pyplot as plt\n'), ((2014, 2088), 'config.fname.output', 'fname.output', ([], {'subject': 'subj', 'processing_step': '"""fit_ica"""', 'file_type': '"""ica.fif"""'}), "(subject=subj, processing_step='fit_ica', file_type='ica.fif')\n", (2026, 2088), False, 'from config import fname, parser, LoggingFormat\n'), ((4021, 4050), 'config.fname.report', 'fname.report', ([], {'subject': 'subject'}), '(subject=subject)\n', (4033, 4050), False, 'from config import fname, parser, LoggingFormat\n'), ((4598, 4627), 'config.fname.report', 'fname.report', ([], {'subject': 'subject'}), '(subject=subject)\n', (4610, 4627), False, 'from config import fname, parser, LoggingFormat\n')]
|
# Copyright 2021 the Ithaca Authors
#
# 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
#
# https://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.
"""Ithaca: Restoring and attributing ancient texts with deep neural networks."""
import bz2
import distutils
import functools
import glob
import os
import pickle
from absl import app
from absl import flags
from absl import logging
import dataloader
from ithaca.models.model import Model
from ithaca.util.alphabet import GreekAlphabet
from ithaca.util.loss import categorical_kl_divergence
from ithaca.util.loss import cross_entropy_label_smoothing_loss
from ithaca.util.loss import cross_entropy_loss
from ithaca.util.loss import cross_entropy_mask_loss
from ithaca.util.loss import date_loss_l1
from ithaca.util.optim import adaptive_grad_clip
from ithaca.util.optim import linear_warmup_and_sqrt_decay
from ithaca.util.optim import linear_weight
from ithaca.util.region_names import load_region_maps
import jax
import jax.numpy as jnp
from jaxline import experiment
from jaxline import platform
from jaxline import utils as jl_utils
import numpy as np
import optax
import tensorflow_datasets.public_api as tfds
FLAGS = flags.FLAGS
class Experiment(experiment.AbstractExperiment):
"""Ithaca experiment."""
# Holds a map from object properties that will be checkpointed to their name
# within a checkpoint. Currently it is assume that these are all sharded
# device arrays.
CHECKPOINT_ATTRS = {
'_params': 'params',
'_opt_state': 'opt_state',
}
def __init__(self, mode, init_rng, config):
"""Initializes experiment."""
super(Experiment, self).__init__(mode=mode)
self.mode = mode
self.init_rng = init_rng
self.config = config
# Same random key on each device.
self._rng_key = jl_utils.bcast_local_devices(self.init_rng)
# Checkpointed experiment state.
self._params = None
self._opt_state = None
# Input pipelines.
self._train_input = None
self._eval_input = None
# Forward and update functions.
self.forward = Model(**self.config.model)
self._update_func = jax.pmap(
self._update_func, axis_name='i', donate_argnums=(0, 1))
self._learning_rate_fn = functools.partial(
linear_warmup_and_sqrt_decay,
max_lr=self.config.optimizer.kwargs.learning_rate,
warmup_steps=self.config.optimizer.warmup)
self._opt_init, self._opt_update = self.optimizer()
if 'use_jit' in self.config.evaluation and self.config.evaluation.use_jit:
self._eval_batch = jax.jit(self._eval_batch)
# Create alphabet
alphabet_kwargs = dict(self.config.alphabet)
wordlist_path = alphabet_kwargs.pop('wordlist_path')
with open(wordlist_path, 'r') as f:
self._alphabet = GreekAlphabet(wordlist_file=f, **alphabet_kwargs)
# Create region mapping
self._region_map = {'main': None, 'sub': None}
if self.config.dataset.region_main_path:
with open(self.config.dataset.region_main_path, 'r') as f:
self._region_map['main'] = load_region_maps(f)
if self.config.dataset.region_sub_path:
with open(self.config.dataset.region_sub_path, 'r') as f:
self._region_map['sub'] = load_region_maps(f)
def optimizer(self):
config_opt = self.config.optimizer
kwargs = config_opt.kwargs.to_dict()
kwargs['learning_rate'] = self._learning_rate_fn
opt = getattr(optax, config_opt.name)(**kwargs)
if hasattr(config_opt, 'clip_adaptive') and config_opt.clip_adaptive:
if config_opt.clip_level > 0.:
opt = optax.chain(adaptive_grad_clip(config_opt.clip_level), opt)
elif config_opt.clip_level > 0.:
opt = optax.chain(optax.clip_by_global_norm(config_opt.clip_level), opt)
return opt
# _ _
# | |_ _ __ __ _(_)_ __
# | __| '__/ _` | | '_ \
# | |_| | | (_| | | | | |
# \__|_| \__,_|_|_| |_|
#
def step(self, global_step, rng, **unused_args):
"""See base class."""
if self._train_input is None:
self._initialize_train(rng)
batch = next(self._train_input)
(self._params, self._opt_state, scalars) = (
self._update_func(self._params, self._opt_state, global_step, batch,
rng))
scalars = jl_utils.get_first(scalars)
return scalars
def _initialize_train(self, rng):
# Check we haven't already restored params
if self._params is None:
logging.info(
'Initializing parameters rather than restoring from checkpoint.')
batch = next(self._build_train_input())
rng = jl_utils.get_first(rng)
params_rng, dropout_rng = jax.random.split(rng)
params_rng = jl_utils.bcast_local_devices(params_rng)
dropout_rng = jl_utils.bcast_local_devices(dropout_rng)
init_net = jax.pmap(
functools.partial(self.forward.init, is_training=True))
self._params = init_net({
'params': params_rng,
'dropout': dropout_rng
},
text_char=batch['text_char'],
text_word=batch['text_word'])
init_opt = jax.pmap(self._opt_init)
self._opt_state = init_opt(self._params)
self._train_input = jl_utils.py_prefetch(self._build_train_input)
self._train_input = jl_utils.double_buffer_on_gpu(self._train_input)
def _build_train_input(self):
"""See base class."""
num_devices = jax.device_count()
global_batch_size = self.config.training.batch_size
per_device_batch_size, ragged = divmod(global_batch_size, num_devices)
logging.info(
'num_devices: %d, per_device_batch_size: %d, global_batch_size: %d',
num_devices, per_device_batch_size, global_batch_size)
if ragged:
raise ValueError(
f'Global batch size {global_batch_size} must be divisible by '
f'num devices {num_devices}')
config_dataset = self.config.dataset
with open(config_dataset.dataset_path) as dataset_file:
ds = dataloader.loader_tf(
per_device_batch_size,
config_dataset,
self._region_map,
alphabet=self._alphabet,
dataset_file=dataset_file,
mode='train')
ds = ds.batch(jax.local_device_count())
return iter(tfds.as_numpy(ds))
def _loss_fn(self, params, batch, global_step, rng):
text_char = batch['text_char']
text_word = batch['text_word']
text_unmasked = batch['text_unmasked']
text_mask = batch['text_mask']
next_sentence_mask = batch['next_sentence_mask']
next_sentence_label = batch['next_sentence_label']
subregion = batch['region_sub_id']
date_min = batch['date_min']
date_max = batch['date_max']
date_dist = batch['date_dist']
date_available = batch['date_available']
eps = 1e-6
(date_pred, subregion_logits, mask_logits, nsp_logits) = self.forward.apply(
params,
text_char=text_char,
text_word=text_word,
text_char_onehot=None,
text_word_onehot=None,
is_training=True,
rngs={'dropout': rng})
date_loss = 0.
subregion_loss = 0.
subregion_accuracy = 0.
mask_loss = 0.
mask_accuracy = 0.
nsp_loss = 0.
nsp_accuracy = 0.
# Date loss
if self.config.loss.date.enabled:
if self.config.loss.date.label_smoothing > 0:
date_dist_prob = jnp.exp(date_dist) # logprob to prob
date_dist_prob_smooth = date_dist_prob * jax.random.uniform(
rng,
shape=date_dist_prob.shape,
dtype=date_dist_prob.dtype,
minval=1 - self.config.loss.date.label_smoothing,
maxval=1 + self.config.loss.date.label_smoothing)
date_dist_prob_smooth /= date_dist_prob_smooth.sum(axis=-1)[:,
jnp.newaxis]
date_dist_prob_smooth = jnp.clip(date_dist_prob_smooth, 1e-6, 1)
date_dist = jnp.log(date_dist_prob_smooth)
date_loss = 0.
if 'l1' in self.config.loss.date.type.split('+'):
date_pred_x = jnp.arange(
self.config.dataset.date_min +
self.config.dataset.date_interval / 2,
self.config.dataset.date_max +
self.config.dataset.date_interval / 2,
self.config.dataset.date_interval).reshape(-1, 1)
date_pred_val = jnp.dot(jax.nn.softmax(date_pred, axis=-1), date_pred_x)
date_loss_l1_ = jax.vmap(date_loss_l1)(date_pred_val, date_min,
date_max, date_available)
jnp.nan_to_num(date_loss_l1_, copy=False)
date_loss += (
jnp.mean(date_loss_l1_, axis=0) * self.config.loss.date.weight_l1)
if 'dist' in self.config.loss.date.type.split('+'):
date_loss_dist_ = categorical_kl_divergence(date_dist, date_pred)
date_loss_dist_ *= date_available
jnp.nan_to_num(date_loss_dist_, copy=False)
date_loss += (
jnp.mean(date_loss_dist_, axis=0) *
self.config.loss.date.weight_dist)
date_loss *= linear_weight(global_step, self.config.loss.date.step_start,
self.config.loss.date.step_end)
# Region and subregion loss
if self.config.loss.region.enabled:
subregion_loss = jnp.mean(
cross_entropy_label_smoothing_loss(
subregion_logits,
subregion,
label_smoothing=self.config.loss.region.label_smoothing), 0)
jnp.nan_to_num(subregion_loss, copy=False)
subregion_loss *= self.config.loss.region.weight
subregion_accuracy = jnp.mean(
jnp.argmax(subregion_logits, -1) == subregion)
w = linear_weight(global_step, self.config.loss.region.step_start,
self.config.loss.region.step_end)
subregion_loss *= w
# Mask loss
if self.config.loss.mask.enabled:
mask_loss = jnp.sum(
cross_entropy_label_smoothing_loss(
mask_logits,
text_unmasked,
text_mask,
label_smoothing=self.config.loss.mask.label_smoothing), 1) # [B]
assert mask_loss.ndim == 1
jnp.nan_to_num(mask_loss, copy=False)
mask_loss = jnp.mean(mask_loss, 0) * self.config.loss.mask.weight # []
mask_all_accuracy = (jnp.argmax(mask_logits, -1) == text_unmasked).astype(
mask_logits.dtype)
mask_accuracy = jnp.divide(
jnp.sum(
jnp.multiply(mask_all_accuracy,
text_mask.astype(mask_logits.dtype))),
jnp.sum(text_mask) + eps)
mask_loss *= linear_weight(global_step, self.config.loss.mask.step_start,
self.config.loss.mask.step_end)
# NSP loss
if self.config.loss.nsp.enabled:
nsp_loss = jnp.sum(
jax.vmap(jax.vmap(cross_entropy_mask_loss))(nsp_logits,
next_sentence_label,
next_sentence_mask),
1) # [B]
assert nsp_loss.ndim == 1
jnp.nan_to_num(nsp_loss, copy=False)
nsp_loss = jnp.mean(nsp_loss, 0) * self.config.loss.nsp.weight
nsp_all_accuracy = (jnp.argmax(
nsp_logits, -1) == next_sentence_label).astype(nsp_logits.dtype)
nsp_accuracy = jnp.divide(
jnp.sum(
jnp.multiply(nsp_all_accuracy,
next_sentence_mask.astype(nsp_logits.dtype))),
jnp.sum(next_sentence_mask) + eps)
nsp_loss *= linear_weight(global_step, self.config.loss.nsp.step_start,
self.config.loss.nsp.step_end)
loss = date_loss + subregion_loss + mask_loss + nsp_loss
scaled_loss = loss / jax.device_count()
# NOTE: We use scaled_loss for grads and unscaled for logging.
return scaled_loss, (loss, date_loss, subregion_loss, subregion_accuracy,
mask_loss, mask_accuracy, nsp_loss, nsp_accuracy)
def _update_func(self, params, opt_state, global_step, batch, rng):
"""Applies an update to parameters and returns new state."""
# This function computes the gradient of the first output of loss_fn and
# passes through the other arguments unchanged.
grad_loss_fn = jax.grad(self._loss_fn, has_aux=True)
scaled_grads, (loss, date_loss, subregion_loss, subregion_accuracy,
mask_loss, mask_accuracy, nsp_loss,
nsp_accuracy) = grad_loss_fn(params, batch, global_step, rng)
scaled_grads = jax.tree_map(jnp.nan_to_num, scaled_grads)
grads = jl_utils.tree_psum(scaled_grads, axis_name='i')
# Compute and apply updates via our optimizer.
learning_rate = self._learning_rate_fn(global_step)
updates, opt_state = self._opt_update(grads, opt_state, params=params)
params = optax.apply_updates(params, updates)
# Scalars to log (note: we log the mean across all hosts/devices).
scalars = {
'loss/train': loss,
'loss/date': date_loss,
'loss/subregion': subregion_loss,
'loss/mask': mask_loss,
'loss/nsp': nsp_loss,
'accuracy/subregion': subregion_accuracy,
'accuracy/mask': mask_accuracy,
'accuracy/nsp': nsp_accuracy,
'opt/learning_rate': learning_rate,
'opt/grad_norm': optax.global_norm(grads),
'opt/param_norm': optax.global_norm(params),
}
scalars = jax.lax.pmean(scalars, axis_name='i')
return params, opt_state, scalars
# _
# _____ ____ _| |
# / _ \ \ / / _` | |
# | __/\ V / (_| | |
# \___| \_/ \__,_|_|
#
def evaluate(self, global_step, rng, **unused_kwargs):
"""See base class."""
if self._eval_input is None:
self._initialize_eval()
global_step = np.array(jl_utils.get_first(global_step))
summary, outputs = self._eval_epoch(jl_utils.get_first(rng))
for k, v in summary.items():
summary[k] = np.array(v)
score = summary['score/eval']
logging.info('[Step %d] eval_score=%.2f', global_step, score)
# Log outputs
checkpoint_dir = jl_utils.get_checkpoint_dir(FLAGS.config,
jax.process_index())
outputs_path = os.path.join(checkpoint_dir, 'best_outputs.pkl.bz2')
score_path = os.path.join(checkpoint_dir, 'best_score.txt')
model_log_path = os.path.join(checkpoint_dir, 'model_log')
best_model_log_path = os.path.join(checkpoint_dir, 'best_model_log')
# Check for preexisting outputs
best_score = None
best_step = None
if os.path.exists(score_path):
with open(score_path, 'r') as f:
tok = f.read().strip().split(' ')
best_step = int(tok[0])
best_score = float(tok[1])
# Store outputs if score is better
if best_score is None or (score > best_score and global_step > best_step):
best_score = score
with open(score_path, 'w') as f:
f.write(f'{global_step} {best_score}')
with open(outputs_path, 'wb') as f:
outputs_pkl = pickle.dumps(outputs, protocol=2)
outputs_pkl_bz2 = bz2.compress(outputs_pkl)
f.write(outputs_pkl_bz2)
if self.config.evaluation.store_model_log:
if os.path.isdir(best_model_log_path):
map(os.remove, glob.glob(best_model_log_path + '/*'))
else:
os.makedirs(best_model_log_path)
distutils.dir_util.copy_tree(model_log_path, best_model_log_path)
logging.info('[Step %d] Writing eval outputs: %s.', global_step,
outputs_path)
# Log best score
summary['score/eval_best'] = best_score
return summary
def _initialize_eval(self):
self._eval_input = jl_utils.py_prefetch(self._build_eval_input)
def _build_eval_input(self):
"""Builds the evaluation input pipeline."""
config_dataset = self.config.dataset
with open(config_dataset.dataset_path) as dataset_file:
ds = dataloader.loader_tf(
self.config.evaluation.batch_size,
config_dataset,
self._region_map,
alphabet=self._alphabet,
dataset_file=dataset_file,
mode=self.config.evaluation.mode)
return iter(tfds.as_numpy(ds))
def _eval_batch(self, params, batch, rng):
"""Evaluates a batch."""
phi_id = batch['id']
text_char = batch['text_char']
text_word = batch['text_word']
text_unmasked = batch['text_unmasked']
text_mask = batch['text_mask']
next_sentence_mask = batch['next_sentence_mask']
next_sentence_label = batch['next_sentence_label']
subregion = batch['region_sub_id']
date_min = batch['date_min']
date_max = batch['date_max']
date_dist = batch['date_dist']
date_available = batch['date_available']
# with hlogging.context() as log:
(date_pred, subregion_logits, mask_logits, nsp_logits) = self.forward.apply(
params,
text_char=text_char,
text_word=text_word,
text_char_onehot=None,
text_word_onehot=None,
is_training=False,
rngs={'dropout': rng})
# Log model weights
model_log = {}
subregion_loss = 0.
subregion_accuracy = 0.
date_loss = 0.
date_l1_loss = 0.
nsp_loss = 0.
nsp_accuracy = 0.
# eps = 1e-6
date_count = 0
mask_count = 0
nsp_count = 0
# Date loss
if self.config.loss.date.enabled:
date_pred_x = jnp.arange(
self.config.dataset.date_min + self.config.dataset.date_interval / 2,
self.config.dataset.date_max + self.config.dataset.date_interval / 2,
self.config.dataset.date_interval).reshape(-1, 1)
date_pred_val = jnp.dot(jax.nn.softmax(date_pred, axis=-1), date_pred_x)
date_l1_loss = jnp.sum(
jax.vmap(date_loss_l1)(date_pred_val, date_min, date_max,
date_available),
axis=0)
if 'l1' in self.config.loss.date.type.split('+'):
date_loss += date_l1_loss * self.config.loss.date.weight_l1
if 'dist' in self.config.loss.date.type.split('+'):
date_loss_dist_ = categorical_kl_divergence(date_dist, date_pred)
date_loss_dist_ *= date_available
date_loss += (
jnp.sum(date_loss_dist_, axis=0) *
self.config.loss.date.weight_dist)
date_count = jnp.sum(date_available)
# Region and subregion loss
if self.config.loss.region.enabled:
subregion_loss = jnp.sum(
cross_entropy_loss(subregion_logits, subregion), 0)
subregion_loss *= self.config.loss.region.weight
subregion_accuracy = jnp.mean(
jnp.argmax(subregion_logits, -1) == subregion)
# Mask loss
if self.config.loss.mask.enabled:
mask_loss = jnp.sum(
cross_entropy_label_smoothing_loss(
mask_logits, text_unmasked, text_mask, label_smoothing=0),
1) # [B]
# mask_loss /= jnp.sum(text_mask, axis=1) + eps # [B]
assert mask_loss.ndim == 1
mask_loss = jnp.mean(mask_loss, 0) * self.config.loss.mask.weight # []
mask_all_accuracy = (jnp.argmax(mask_logits, -1) == text_unmasked).astype(
mask_logits.dtype)
mask_accuracy = jnp.sum(
jnp.multiply(mask_all_accuracy, text_mask.astype(mask_logits.dtype)))
mask_count = jnp.sum(text_mask)
# NSP loss
if self.config.loss.nsp.enabled:
nsp_loss = jnp.sum(
jax.vmap(jax.vmap(cross_entropy_mask_loss))(nsp_logits,
next_sentence_label,
next_sentence_mask),
1) # [B]
assert nsp_loss.ndim == 1
nsp_loss = jnp.sum(nsp_loss, 0) * self.config.loss.nsp.weight
nsp_all_accuracy = (jnp.argmax(
nsp_logits, -1) == next_sentence_label).astype(nsp_logits.dtype)
nsp_accuracy = jnp.sum(
jnp.multiply(nsp_all_accuracy,
next_sentence_mask.astype(nsp_logits.dtype)))
nsp_count = jnp.sum(next_sentence_mask)
# Outputs
scalars = {
'score/eval':
(mask_accuracy + subregion_accuracy - date_l1_loss * 0.01),
'loss/eval': mask_loss + date_loss + subregion_loss,
'loss/date': date_loss,
'loss/date_l1': date_l1_loss,
'loss/subregion': subregion_loss,
'loss/mask': mask_loss,
'loss/nsp': nsp_loss,
'count/date': date_count,
'count/nsp': nsp_count,
'count/mask': mask_count,
'accuracy/subregion': subregion_accuracy,
'accuracy/mask': mask_accuracy,
'accuracy/nsp': nsp_accuracy,
}
outputs = {
'outputs/id': phi_id,
'outputs/date_pred': date_pred.astype('float16'),
'outputs/date_min': date_min,
'outputs/date_max': date_max,
'outputs/date_dist': date_dist.astype('float16'),
'outputs/date_available': date_available,
'outputs/subregion_logits': subregion_logits.astype('float16'),
'outputs/subregion': subregion,
}
return scalars, outputs, model_log
def _eval_epoch(self, rng):
"""Evaluates an epoch."""
summary = {}
outputs = {}
total_num_sequences = 0
# Prepare directories for storing model log
checkpoint_dir = jl_utils.get_checkpoint_dir(FLAGS.config,
jax.process_index())
model_log_path = os.path.join(checkpoint_dir, 'model_log')
if self.config.evaluation.store_model_log:
if os.path.isdir(model_log_path):
map(os.remove, glob.glob(model_log_path + '/*'))
else:
os.makedirs(model_log_path)
# Checkpoints broadcast for each local device
params = jl_utils.get_first(self._params)
# Model log buffer initialisation
model_log_buffer = []
def _flush_model_log_buffer(model_log_buffer):
"""Writes model log to bz2 pickle files."""
while model_log_buffer:
model_log_batch_path, model_log_pkl_bz2 = model_log_buffer.pop(0)
with open(model_log_batch_path, 'wb') as f:
f.write(model_log_pkl_bz2)
# Converting to numpy here allows us to reset the generator
for batch in self._eval_input():
# Make sure that the input has batch_dim=1
assert batch['text_char'].shape[0] == 1
summary_batch, outputs_batch, model_log_batch = self._eval_batch(
params, batch, rng)
# Append batch values to dictionary
for k, v in summary_batch.items():
summary[k] = summary.get(k, 0) + v
for k, v in outputs_batch.items():
outputs.setdefault(k, []).append(v)
total_num_sequences += self.config.evaluation.batch_size
# Store model log per batch
if self.config.evaluation.store_model_log:
# Append to buffer
model_log_batch_path = os.path.join(
model_log_path,
str(outputs_batch['outputs/id'][0]) + '.pkl.bz2')
model_log_pkl = pickle.dumps(model_log_batch, protocol=2)
model_log_pkl_bz2 = bz2.compress(model_log_pkl)
model_log_buffer += [(model_log_batch_path, model_log_pkl_bz2)]
# Flush model log buffer
if (len(model_log_buffer) %
self.config.evaluation.store_model_log_steps == 0):
_flush_model_log_buffer(model_log_buffer)
# Flush remaining model log buffer
if self.config.evaluation.store_model_log:
_flush_model_log_buffer(model_log_buffer)
# Normalise and concatenate
summary['loss/date'] /= summary['count/date']
summary['loss/date_l1'] /= summary['count/date']
summary['loss/mask'] /= summary['count/mask']
summary['accuracy/mask'] /= summary['count/mask']
summary['loss/nsp'] /= summary['count/nsp']
summary['accuracy/nsp'] /= summary['count/nsp']
summary['loss/subregion'] /= total_num_sequences
summary['accuracy/subregion'] /= total_num_sequences
summary['score/eval'] = (
summary['accuracy/mask'] + summary['accuracy/subregion'] -
summary['loss/date_l1'] * 0.01)
summary['loss/eval'] = (
summary['loss/mask'] + summary['loss/date'] + summary['loss/subregion'])
for k, v in outputs.items():
outputs[k] = np.concatenate(v, axis=0)
return summary, outputs
if __name__ == '__main__':
flags.mark_flag_as_required('config')
app.run(functools.partial(platform.main, Experiment))
|
[
"absl.logging.info",
"jaxline.utils.double_buffer_on_gpu",
"glob.glob",
"os.path.join",
"ithaca.util.loss.cross_entropy_loss",
"jax.process_index",
"jax.random.uniform",
"jax.jit",
"jax.numpy.mean",
"jax.local_device_count",
"ithaca.models.model.Model",
"optax.apply_updates",
"absl.flags.mark_flag_as_required",
"os.path.exists",
"dataloader.loader_tf",
"ithaca.util.region_names.load_region_maps",
"jax.numpy.argmax",
"ithaca.util.alphabet.GreekAlphabet",
"ithaca.util.loss.cross_entropy_label_smoothing_loss",
"pickle.dumps",
"functools.partial",
"distutils.dir_util.copy_tree",
"jax.numpy.sum",
"jax.vmap",
"jax.pmap",
"jax.numpy.nan_to_num",
"jax.lax.pmean",
"jaxline.utils.get_first",
"ithaca.util.optim.adaptive_grad_clip",
"jaxline.utils.py_prefetch",
"ithaca.util.loss.categorical_kl_divergence",
"optax.clip_by_global_norm",
"numpy.concatenate",
"jaxline.utils.tree_psum",
"jax.numpy.log",
"jax.numpy.exp",
"os.makedirs",
"os.path.isdir",
"jax.numpy.arange",
"tensorflow_datasets.public_api.as_numpy",
"ithaca.util.optim.linear_weight",
"jaxline.utils.bcast_local_devices",
"jax.device_count",
"bz2.compress",
"numpy.array",
"jax.numpy.clip",
"jax.grad",
"jax.nn.softmax",
"optax.global_norm",
"jax.random.split",
"jax.tree_map"
] |
[((24646, 24683), 'absl.flags.mark_flag_as_required', 'flags.mark_flag_as_required', (['"""config"""'], {}), "('config')\n", (24673, 24683), False, 'from absl import flags\n'), ((2222, 2265), 'jaxline.utils.bcast_local_devices', 'jl_utils.bcast_local_devices', (['self.init_rng'], {}), '(self.init_rng)\n', (2250, 2265), True, 'from jaxline import utils as jl_utils\n'), ((2492, 2518), 'ithaca.models.model.Model', 'Model', ([], {}), '(**self.config.model)\n', (2497, 2518), False, 'from ithaca.models.model import Model\n'), ((2543, 2608), 'jax.pmap', 'jax.pmap', (['self._update_func'], {'axis_name': '"""i"""', 'donate_argnums': '(0, 1)'}), "(self._update_func, axis_name='i', donate_argnums=(0, 1))\n", (2551, 2608), False, 'import jax\n'), ((2648, 2794), 'functools.partial', 'functools.partial', (['linear_warmup_and_sqrt_decay'], {'max_lr': 'self.config.optimizer.kwargs.learning_rate', 'warmup_steps': 'self.config.optimizer.warmup'}), '(linear_warmup_and_sqrt_decay, max_lr=self.config.\n optimizer.kwargs.learning_rate, warmup_steps=self.config.optimizer.warmup)\n', (2665, 2794), False, 'import functools\n'), ((4671, 4698), 'jaxline.utils.get_first', 'jl_utils.get_first', (['scalars'], {}), '(scalars)\n', (4689, 4698), True, 'from jaxline import utils as jl_utils\n'), ((5820, 5838), 'jax.device_count', 'jax.device_count', ([], {}), '()\n', (5836, 5838), False, 'import jax\n'), ((5974, 6119), 'absl.logging.info', 'logging.info', (['"""num_devices: %d, per_device_batch_size: %d, global_batch_size: %d"""', 'num_devices', 'per_device_batch_size', 'global_batch_size'], {}), "(\n 'num_devices: %d, per_device_batch_size: %d, global_batch_size: %d',\n num_devices, per_device_batch_size, global_batch_size)\n", (5986, 6119), False, 'from absl import logging\n'), ((12668, 12705), 'jax.grad', 'jax.grad', (['self._loss_fn'], {'has_aux': '(True)'}), '(self._loss_fn, has_aux=True)\n', (12676, 12705), False, 'import jax\n'), ((12934, 12976), 'jax.tree_map', 'jax.tree_map', (['jnp.nan_to_num', 'scaled_grads'], {}), '(jnp.nan_to_num, scaled_grads)\n', (12946, 12976), False, 'import jax\n'), ((12989, 13036), 'jaxline.utils.tree_psum', 'jl_utils.tree_psum', (['scaled_grads'], {'axis_name': '"""i"""'}), "(scaled_grads, axis_name='i')\n", (13007, 13036), True, 'from jaxline import utils as jl_utils\n'), ((13233, 13269), 'optax.apply_updates', 'optax.apply_updates', (['params', 'updates'], {}), '(params, updates)\n', (13252, 13269), False, 'import optax\n'), ((13818, 13855), 'jax.lax.pmean', 'jax.lax.pmean', (['scalars'], {'axis_name': '"""i"""'}), "(scalars, axis_name='i')\n", (13831, 13855), False, 'import jax\n'), ((14397, 14458), 'absl.logging.info', 'logging.info', (['"""[Step %d] eval_score=%.2f"""', 'global_step', 'score'], {}), "('[Step %d] eval_score=%.2f', global_step, score)\n", (14409, 14458), False, 'from absl import logging\n'), ((14630, 14682), 'os.path.join', 'os.path.join', (['checkpoint_dir', '"""best_outputs.pkl.bz2"""'], {}), "(checkpoint_dir, 'best_outputs.pkl.bz2')\n", (14642, 14682), False, 'import os\n'), ((14700, 14746), 'os.path.join', 'os.path.join', (['checkpoint_dir', '"""best_score.txt"""'], {}), "(checkpoint_dir, 'best_score.txt')\n", (14712, 14746), False, 'import os\n'), ((14768, 14809), 'os.path.join', 'os.path.join', (['checkpoint_dir', '"""model_log"""'], {}), "(checkpoint_dir, 'model_log')\n", (14780, 14809), False, 'import os\n'), ((14836, 14882), 'os.path.join', 'os.path.join', (['checkpoint_dir', '"""best_model_log"""'], {}), "(checkpoint_dir, 'best_model_log')\n", (14848, 14882), False, 'import os\n'), ((14970, 14996), 'os.path.exists', 'os.path.exists', (['score_path'], {}), '(score_path)\n', (14984, 14996), False, 'import os\n'), ((16098, 16142), 'jaxline.utils.py_prefetch', 'jl_utils.py_prefetch', (['self._build_eval_input'], {}), '(self._build_eval_input)\n', (16118, 16142), True, 'from jaxline import utils as jl_utils\n'), ((21778, 21819), 'os.path.join', 'os.path.join', (['checkpoint_dir', '"""model_log"""'], {}), "(checkpoint_dir, 'model_log')\n", (21790, 21819), False, 'import os\n'), ((22076, 22108), 'jaxline.utils.get_first', 'jl_utils.get_first', (['self._params'], {}), '(self._params)\n', (22094, 22108), True, 'from jaxline import utils as jl_utils\n'), ((24694, 24738), 'functools.partial', 'functools.partial', (['platform.main', 'Experiment'], {}), '(platform.main, Experiment)\n', (24711, 24738), False, 'import functools\n'), ((2977, 3002), 'jax.jit', 'jax.jit', (['self._eval_batch'], {}), '(self._eval_batch)\n', (2984, 3002), False, 'import jax\n'), ((3195, 3244), 'ithaca.util.alphabet.GreekAlphabet', 'GreekAlphabet', ([], {'wordlist_file': 'f'}), '(wordlist_file=f, **alphabet_kwargs)\n', (3208, 3244), False, 'from ithaca.util.alphabet import GreekAlphabet\n'), ((4837, 4915), 'absl.logging.info', 'logging.info', (['"""Initializing parameters rather than restoring from checkpoint."""'], {}), "('Initializing parameters rather than restoring from checkpoint.')\n", (4849, 4915), False, 'from absl import logging\n'), ((4986, 5009), 'jaxline.utils.get_first', 'jl_utils.get_first', (['rng'], {}), '(rng)\n', (5004, 5009), True, 'from jaxline import utils as jl_utils\n'), ((5042, 5063), 'jax.random.split', 'jax.random.split', (['rng'], {}), '(rng)\n', (5058, 5063), False, 'import jax\n'), ((5083, 5123), 'jaxline.utils.bcast_local_devices', 'jl_utils.bcast_local_devices', (['params_rng'], {}), '(params_rng)\n', (5111, 5123), True, 'from jaxline import utils as jl_utils\n'), ((5144, 5185), 'jaxline.utils.bcast_local_devices', 'jl_utils.bcast_local_devices', (['dropout_rng'], {}), '(dropout_rng)\n', (5172, 5185), True, 'from jaxline import utils as jl_utils\n'), ((5523, 5547), 'jax.pmap', 'jax.pmap', (['self._opt_init'], {}), '(self._opt_init)\n', (5531, 5547), False, 'import jax\n'), ((5622, 5667), 'jaxline.utils.py_prefetch', 'jl_utils.py_prefetch', (['self._build_train_input'], {}), '(self._build_train_input)\n', (5642, 5667), True, 'from jaxline import utils as jl_utils\n'), ((5694, 5742), 'jaxline.utils.double_buffer_on_gpu', 'jl_utils.double_buffer_on_gpu', (['self._train_input'], {}), '(self._train_input)\n', (5723, 5742), True, 'from jaxline import utils as jl_utils\n'), ((6394, 6547), 'dataloader.loader_tf', 'dataloader.loader_tf', (['per_device_batch_size', 'config_dataset', 'self._region_map'], {'alphabet': 'self._alphabet', 'dataset_file': 'dataset_file', 'mode': '"""train"""'}), "(per_device_batch_size, config_dataset, self.\n _region_map, alphabet=self._alphabet, dataset_file=dataset_file, mode=\n 'train')\n", (6414, 6547), False, 'import dataloader\n'), ((6618, 6642), 'jax.local_device_count', 'jax.local_device_count', ([], {}), '()\n', (6640, 6642), False, 'import jax\n'), ((6660, 6677), 'tensorflow_datasets.public_api.as_numpy', 'tfds.as_numpy', (['ds'], {}), '(ds)\n', (6673, 6677), True, 'import tensorflow_datasets.public_api as tfds\n'), ((9462, 9559), 'ithaca.util.optim.linear_weight', 'linear_weight', (['global_step', 'self.config.loss.date.step_start', 'self.config.loss.date.step_end'], {}), '(global_step, self.config.loss.date.step_start, self.config.\n loss.date.step_end)\n', (9475, 9559), False, 'from ithaca.util.optim import linear_weight\n'), ((9878, 9920), 'jax.numpy.nan_to_num', 'jnp.nan_to_num', (['subregion_loss'], {'copy': '(False)'}), '(subregion_loss, copy=False)\n', (9892, 9920), True, 'import jax.numpy as jnp\n'), ((10081, 10182), 'ithaca.util.optim.linear_weight', 'linear_weight', (['global_step', 'self.config.loss.region.step_start', 'self.config.loss.region.step_end'], {}), '(global_step, self.config.loss.region.step_start, self.config.\n loss.region.step_end)\n', (10094, 10182), False, 'from ithaca.util.optim import linear_weight\n'), ((10556, 10593), 'jax.numpy.nan_to_num', 'jnp.nan_to_num', (['mask_loss'], {'copy': '(False)'}), '(mask_loss, copy=False)\n', (10570, 10593), True, 'import jax.numpy as jnp\n'), ((11003, 11100), 'ithaca.util.optim.linear_weight', 'linear_weight', (['global_step', 'self.config.loss.mask.step_start', 'self.config.loss.mask.step_end'], {}), '(global_step, self.config.loss.mask.step_start, self.config.\n loss.mask.step_end)\n', (11016, 11100), False, 'from ithaca.util.optim import linear_weight\n'), ((11482, 11518), 'jax.numpy.nan_to_num', 'jnp.nan_to_num', (['nsp_loss'], {'copy': '(False)'}), '(nsp_loss, copy=False)\n', (11496, 11518), True, 'import jax.numpy as jnp\n'), ((11935, 12030), 'ithaca.util.optim.linear_weight', 'linear_weight', (['global_step', 'self.config.loss.nsp.step_start', 'self.config.loss.nsp.step_end'], {}), '(global_step, self.config.loss.nsp.step_start, self.config.\n loss.nsp.step_end)\n', (11948, 12030), False, 'from ithaca.util.optim import linear_weight\n'), ((12145, 12163), 'jax.device_count', 'jax.device_count', ([], {}), '()\n', (12161, 12163), False, 'import jax\n'), ((13719, 13743), 'optax.global_norm', 'optax.global_norm', (['grads'], {}), '(grads)\n', (13736, 13743), False, 'import optax\n'), ((13771, 13796), 'optax.global_norm', 'optax.global_norm', (['params'], {}), '(params)\n', (13788, 13796), False, 'import optax\n'), ((14195, 14226), 'jaxline.utils.get_first', 'jl_utils.get_first', (['global_step'], {}), '(global_step)\n', (14213, 14226), True, 'from jaxline import utils as jl_utils\n'), ((14268, 14291), 'jaxline.utils.get_first', 'jl_utils.get_first', (['rng'], {}), '(rng)\n', (14286, 14291), True, 'from jaxline import utils as jl_utils\n'), ((14346, 14357), 'numpy.array', 'np.array', (['v'], {}), '(v)\n', (14354, 14357), True, 'import numpy as np\n'), ((14590, 14609), 'jax.process_index', 'jax.process_index', ([], {}), '()\n', (14607, 14609), False, 'import jax\n'), ((15860, 15938), 'absl.logging.info', 'logging.info', (['"""[Step %d] Writing eval outputs: %s."""', 'global_step', 'outputs_path'], {}), "('[Step %d] Writing eval outputs: %s.', global_step, outputs_path)\n", (15872, 15938), False, 'from absl import logging\n'), ((16335, 16518), 'dataloader.loader_tf', 'dataloader.loader_tf', (['self.config.evaluation.batch_size', 'config_dataset', 'self._region_map'], {'alphabet': 'self._alphabet', 'dataset_file': 'dataset_file', 'mode': 'self.config.evaluation.mode'}), '(self.config.evaluation.batch_size, config_dataset,\n self._region_map, alphabet=self._alphabet, dataset_file=dataset_file,\n mode=self.config.evaluation.mode)\n', (16355, 16518), False, 'import dataloader\n'), ((16589, 16606), 'tensorflow_datasets.public_api.as_numpy', 'tfds.as_numpy', (['ds'], {}), '(ds)\n', (16602, 16606), True, 'import tensorflow_datasets.public_api as tfds\n'), ((18704, 18727), 'jax.numpy.sum', 'jnp.sum', (['date_available'], {}), '(date_available)\n', (18711, 18727), True, 'import jax.numpy as jnp\n'), ((19678, 19696), 'jax.numpy.sum', 'jnp.sum', (['text_mask'], {}), '(text_mask)\n', (19685, 19696), True, 'import jax.numpy as jnp\n'), ((20383, 20410), 'jax.numpy.sum', 'jnp.sum', (['next_sentence_mask'], {}), '(next_sentence_mask)\n', (20390, 20410), True, 'import jax.numpy as jnp\n'), ((21736, 21755), 'jax.process_index', 'jax.process_index', ([], {}), '()\n', (21753, 21755), False, 'import jax\n'), ((21876, 21905), 'os.path.isdir', 'os.path.isdir', (['model_log_path'], {}), '(model_log_path)\n', (21889, 21905), False, 'import os\n'), ((24560, 24585), 'numpy.concatenate', 'np.concatenate', (['v'], {'axis': '(0)'}), '(v, axis=0)\n', (24574, 24585), True, 'import numpy as np\n'), ((3470, 3489), 'ithaca.util.region_names.load_region_maps', 'load_region_maps', (['f'], {}), '(f)\n', (3486, 3489), False, 'from ithaca.util.region_names import load_region_maps\n'), ((3632, 3651), 'ithaca.util.region_names.load_region_maps', 'load_region_maps', (['f'], {}), '(f)\n', (3648, 3651), False, 'from ithaca.util.region_names import load_region_maps\n'), ((5223, 5277), 'functools.partial', 'functools.partial', (['self.forward.init'], {'is_training': '(True)'}), '(self.forward.init, is_training=True)\n', (5240, 5277), False, 'import functools\n'), ((7752, 7770), 'jax.numpy.exp', 'jnp.exp', (['date_dist'], {}), '(date_dist)\n', (7759, 7770), True, 'import jax.numpy as jnp\n'), ((8265, 8306), 'jax.numpy.clip', 'jnp.clip', (['date_dist_prob_smooth', '(1e-06)', '(1)'], {}), '(date_dist_prob_smooth, 1e-06, 1)\n', (8273, 8306), True, 'import jax.numpy as jnp\n'), ((8326, 8356), 'jax.numpy.log', 'jnp.log', (['date_dist_prob_smooth'], {}), '(date_dist_prob_smooth)\n', (8333, 8356), True, 'import jax.numpy as jnp\n'), ((8953, 8994), 'jax.numpy.nan_to_num', 'jnp.nan_to_num', (['date_loss_l1_'], {'copy': '(False)'}), '(date_loss_l1_, copy=False)\n', (8967, 8994), True, 'import jax.numpy as jnp\n'), ((9182, 9229), 'ithaca.util.loss.categorical_kl_divergence', 'categorical_kl_divergence', (['date_dist', 'date_pred'], {}), '(date_dist, date_pred)\n', (9207, 9229), False, 'from ithaca.util.loss import categorical_kl_divergence\n'), ((9280, 9323), 'jax.numpy.nan_to_num', 'jnp.nan_to_num', (['date_loss_dist_'], {'copy': '(False)'}), '(date_loss_dist_, copy=False)\n', (9294, 9323), True, 'import jax.numpy as jnp\n'), ((9704, 9828), 'ithaca.util.loss.cross_entropy_label_smoothing_loss', 'cross_entropy_label_smoothing_loss', (['subregion_logits', 'subregion'], {'label_smoothing': 'self.config.loss.region.label_smoothing'}), '(subregion_logits, subregion,\n label_smoothing=self.config.loss.region.label_smoothing)\n', (9738, 9828), False, 'from ithaca.util.loss import cross_entropy_label_smoothing_loss\n'), ((10320, 10452), 'ithaca.util.loss.cross_entropy_label_smoothing_loss', 'cross_entropy_label_smoothing_loss', (['mask_logits', 'text_unmasked', 'text_mask'], {'label_smoothing': 'self.config.loss.mask.label_smoothing'}), '(mask_logits, text_unmasked, text_mask,\n label_smoothing=self.config.loss.mask.label_smoothing)\n', (10354, 10452), False, 'from ithaca.util.loss import cross_entropy_label_smoothing_loss\n'), ((10612, 10634), 'jax.numpy.mean', 'jnp.mean', (['mask_loss', '(0)'], {}), '(mask_loss, 0)\n', (10620, 10634), True, 'import jax.numpy as jnp\n'), ((11536, 11557), 'jax.numpy.mean', 'jnp.mean', (['nsp_loss', '(0)'], {}), '(nsp_loss, 0)\n', (11544, 11557), True, 'import jax.numpy as jnp\n'), ((15442, 15475), 'pickle.dumps', 'pickle.dumps', (['outputs'], {'protocol': '(2)'}), '(outputs, protocol=2)\n', (15454, 15475), False, 'import pickle\n'), ((15502, 15527), 'bz2.compress', 'bz2.compress', (['outputs_pkl'], {}), '(outputs_pkl)\n', (15514, 15527), False, 'import bz2\n'), ((15622, 15656), 'os.path.isdir', 'os.path.isdir', (['best_model_log_path'], {}), '(best_model_log_path)\n', (15635, 15656), False, 'import os\n'), ((15787, 15852), 'distutils.dir_util.copy_tree', 'distutils.dir_util.copy_tree', (['model_log_path', 'best_model_log_path'], {}), '(model_log_path, best_model_log_path)\n', (15815, 15852), False, 'import distutils\n'), ((18052, 18086), 'jax.nn.softmax', 'jax.nn.softmax', (['date_pred'], {'axis': '(-1)'}), '(date_pred, axis=-1)\n', (18066, 18086), False, 'import jax\n'), ((18477, 18524), 'ithaca.util.loss.categorical_kl_divergence', 'categorical_kl_divergence', (['date_dist', 'date_pred'], {}), '(date_dist, date_pred)\n', (18502, 18524), False, 'from ithaca.util.loss import categorical_kl_divergence\n'), ((18843, 18890), 'ithaca.util.loss.cross_entropy_loss', 'cross_entropy_loss', (['subregion_logits', 'subregion'], {}), '(subregion_logits, subregion)\n', (18861, 18890), False, 'from ithaca.util.loss import cross_entropy_loss\n'), ((19136, 19232), 'ithaca.util.loss.cross_entropy_label_smoothing_loss', 'cross_entropy_label_smoothing_loss', (['mask_logits', 'text_unmasked', 'text_mask'], {'label_smoothing': '(0)'}), '(mask_logits, text_unmasked, text_mask,\n label_smoothing=0)\n', (19170, 19232), False, 'from ithaca.util.loss import cross_entropy_label_smoothing_loss\n'), ((19377, 19399), 'jax.numpy.mean', 'jnp.mean', (['mask_loss', '(0)'], {}), '(mask_loss, 0)\n', (19385, 19399), True, 'import jax.numpy as jnp\n'), ((20061, 20081), 'jax.numpy.sum', 'jnp.sum', (['nsp_loss', '(0)'], {}), '(nsp_loss, 0)\n', (20068, 20081), True, 'import jax.numpy as jnp\n'), ((21984, 22011), 'os.makedirs', 'os.makedirs', (['model_log_path'], {}), '(model_log_path)\n', (21995, 22011), False, 'import os\n'), ((23315, 23356), 'pickle.dumps', 'pickle.dumps', (['model_log_batch'], {'protocol': '(2)'}), '(model_log_batch, protocol=2)\n', (23327, 23356), False, 'import pickle\n'), ((23385, 23412), 'bz2.compress', 'bz2.compress', (['model_log_pkl'], {}), '(model_log_pkl)\n', (23397, 23412), False, 'import bz2\n'), ((4000, 4041), 'ithaca.util.optim.adaptive_grad_clip', 'adaptive_grad_clip', (['config_opt.clip_level'], {}), '(config_opt.clip_level)\n', (4018, 4041), False, 'from ithaca.util.optim import adaptive_grad_clip\n'), ((4109, 4157), 'optax.clip_by_global_norm', 'optax.clip_by_global_norm', (['config_opt.clip_level'], {}), '(config_opt.clip_level)\n', (4134, 4157), False, 'import optax\n'), ((7839, 8027), 'jax.random.uniform', 'jax.random.uniform', (['rng'], {'shape': 'date_dist_prob.shape', 'dtype': 'date_dist_prob.dtype', 'minval': '(1 - self.config.loss.date.label_smoothing)', 'maxval': '(1 + self.config.loss.date.label_smoothing)'}), '(rng, shape=date_dist_prob.shape, dtype=date_dist_prob.\n dtype, minval=1 - self.config.loss.date.label_smoothing, maxval=1 +\n self.config.loss.date.label_smoothing)\n', (7857, 8027), False, 'import jax\n'), ((8751, 8785), 'jax.nn.softmax', 'jax.nn.softmax', (['date_pred'], {'axis': '(-1)'}), '(date_pred, axis=-1)\n', (8765, 8785), False, 'import jax\n'), ((8824, 8846), 'jax.vmap', 'jax.vmap', (['date_loss_l1'], {}), '(date_loss_l1)\n', (8832, 8846), False, 'import jax\n'), ((9030, 9061), 'jax.numpy.mean', 'jnp.mean', (['date_loss_l1_'], {'axis': '(0)'}), '(date_loss_l1_, axis=0)\n', (9038, 9061), True, 'import jax.numpy as jnp\n'), ((9359, 9392), 'jax.numpy.mean', 'jnp.mean', (['date_loss_dist_'], {'axis': '(0)'}), '(date_loss_dist_, axis=0)\n', (9367, 9392), True, 'import jax.numpy as jnp\n'), ((10023, 10055), 'jax.numpy.argmax', 'jnp.argmax', (['subregion_logits', '(-1)'], {}), '(subregion_logits, -1)\n', (10033, 10055), True, 'import jax.numpy as jnp\n'), ((10957, 10975), 'jax.numpy.sum', 'jnp.sum', (['text_mask'], {}), '(text_mask)\n', (10964, 10975), True, 'import jax.numpy as jnp\n'), ((11882, 11909), 'jax.numpy.sum', 'jnp.sum', (['next_sentence_mask'], {}), '(next_sentence_mask)\n', (11889, 11909), True, 'import jax.numpy as jnp\n'), ((15746, 15778), 'os.makedirs', 'os.makedirs', (['best_model_log_path'], {}), '(best_model_log_path)\n', (15757, 15778), False, 'import os\n'), ((17790, 17983), 'jax.numpy.arange', 'jnp.arange', (['(self.config.dataset.date_min + self.config.dataset.date_interval / 2)', '(self.config.dataset.date_max + self.config.dataset.date_interval / 2)', 'self.config.dataset.date_interval'], {}), '(self.config.dataset.date_min + self.config.dataset.date_interval /\n 2, self.config.dataset.date_max + self.config.dataset.date_interval / 2,\n self.config.dataset.date_interval)\n', (17800, 17983), True, 'import jax.numpy as jnp\n'), ((18141, 18163), 'jax.vmap', 'jax.vmap', (['date_loss_l1'], {}), '(date_loss_l1)\n', (18149, 18163), False, 'import jax\n'), ((18602, 18634), 'jax.numpy.sum', 'jnp.sum', (['date_loss_dist_'], {'axis': '(0)'}), '(date_loss_dist_, axis=0)\n', (18609, 18634), True, 'import jax.numpy as jnp\n'), ((18997, 19029), 'jax.numpy.argmax', 'jnp.argmax', (['subregion_logits', '(-1)'], {}), '(subregion_logits, -1)\n', (19007, 19029), True, 'import jax.numpy as jnp\n'), ((21930, 21962), 'glob.glob', 'glob.glob', (["(model_log_path + '/*')"], {}), "(model_log_path + '/*')\n", (21939, 21962), False, 'import glob\n'), ((8457, 8650), 'jax.numpy.arange', 'jnp.arange', (['(self.config.dataset.date_min + self.config.dataset.date_interval / 2)', '(self.config.dataset.date_max + self.config.dataset.date_interval / 2)', 'self.config.dataset.date_interval'], {}), '(self.config.dataset.date_min + self.config.dataset.date_interval /\n 2, self.config.dataset.date_max + self.config.dataset.date_interval / 2,\n self.config.dataset.date_interval)\n', (8467, 8650), True, 'import jax.numpy as jnp\n'), ((10699, 10726), 'jax.numpy.argmax', 'jnp.argmax', (['mask_logits', '(-1)'], {}), '(mask_logits, -1)\n', (10709, 10726), True, 'import jax.numpy as jnp\n'), ((11227, 11260), 'jax.vmap', 'jax.vmap', (['cross_entropy_mask_loss'], {}), '(cross_entropy_mask_loss)\n', (11235, 11260), False, 'import jax\n'), ((11614, 11640), 'jax.numpy.argmax', 'jnp.argmax', (['nsp_logits', '(-1)'], {}), '(nsp_logits, -1)\n', (11624, 11640), True, 'import jax.numpy as jnp\n'), ((15683, 15720), 'glob.glob', 'glob.glob', (["(best_model_log_path + '/*')"], {}), "(best_model_log_path + '/*')\n", (15692, 15720), False, 'import glob\n'), ((19465, 19492), 'jax.numpy.argmax', 'jnp.argmax', (['mask_logits', '(-1)'], {}), '(mask_logits, -1)\n', (19475, 19492), True, 'import jax.numpy as jnp\n'), ((19795, 19828), 'jax.vmap', 'jax.vmap', (['cross_entropy_mask_loss'], {}), '(cross_entropy_mask_loss)\n', (19803, 19828), False, 'import jax\n'), ((20138, 20164), 'jax.numpy.argmax', 'jnp.argmax', (['nsp_logits', '(-1)'], {}), '(nsp_logits, -1)\n', (20148, 20164), True, 'import jax.numpy as jnp\n')]
|
"""
Dataloaders for CUB200-2011, CARS196 and Stanford Online Products.
"""
"""==================================================================================================="""
################### LIBRARIES ###################
import warnings
warnings.filterwarnings("ignore")
import numpy as np, os, sys, pandas as pd, csv, copy
import torch, torch.nn as nn, matplotlib.pyplot as plt, random
from torch.utils.data import Dataset
from PIL import Image
from torchvision import transforms
from tqdm import tqdm
import pretrainedmodels.utils as utils
import auxiliaries as aux
"""==================================================================================================="""
################ FUNCTION TO RETURN ALL DATALOADERS NECESSARY ####################
def give_dataloaders(dataset, opt):
### ImageNet Properties
opt.mean, opt.std, opt.input_space, opt.input_range = [0.485, 0.456, 0.406], [0.229, 0.224, 0.225], 'RGB', [0,1]
if 'class_samples_per_class' in vars(opt).keys():
opt.samples_per_class = opt.class_samples_per_class
if opt.dataset=='cub200':
datasets = give_CUB200_datasets(opt)
elif opt.dataset=='cars196':
datasets = give_CARS196_datasets(opt)
elif opt.dataset=='online_products':
datasets = give_OnlineProducts_datasets(opt)
else:
raise Exception('No Dataset >{}< available!'.format(dataset))
dataloaders = {}
for key,dataset in datasets.items():
if dataset is not None:
is_val = dataset.is_validation
dataloaders[key] = torch.utils.data.DataLoader(dataset, batch_size=opt.bs, num_workers=opt.kernels, shuffle=not is_val, pin_memory=True, drop_last=not is_val)
return dataloaders
"""==================================================================================================="""
################# FUNCTIONS TO RETURN TRAIN/VAL PYTORCH DATASETS FOR CUB200, CARS196 AND STANFORD ONLINE PRODUCTS ####################################
def give_CUB200_datasets(opt):
"""
This function generates a training and testing dataloader for Metric Learning on the CUB-200-2011 dataset.
For Metric Learning, the dataset is sorted by name, and the first halt used for training while the last half is used for testing.
So no random shuffling of classes.
"""
image_sourcepath = opt.source_path+'/images'
image_classes = sorted([x for x in os.listdir(image_sourcepath) if '._' not in x], key=lambda x: int(x.split('.')[0]))
conversion = {int(x.split('.')[0]):x.split('.')[-1] for x in image_classes}
image_list = {int(key.split('.')[0]):sorted([image_sourcepath+'/'+key+'/'+x for x in os.listdir(image_sourcepath+'/'+key) if '._' not in x]) for key in image_classes}
image_list = [[(key,img_path) for img_path in image_list[key]] for key in image_list.keys()]
image_list = [x for y in image_list for x in y]
image_dict = {}
for key, img_path in image_list:
key = key-1
if not key in image_dict.keys():
image_dict[key] = []
image_dict[key].append(img_path)
keys = sorted(list(image_dict.keys()))
# random.shuffle(keys)
#Following "Deep Metric Learning via Lifted Structured Feature Embedding", we use the first half of classes for training.
train,test = keys[:len(keys)//2], keys[len(keys)//2:]
if opt.sampling=='learned':
if opt.train_val_split_by_class:
train_val_split = int(len(train)*opt.train_val_split)
train, val = train[:train_val_split], train[train_val_split:]
train_image_dict, val_image_dict, test_image_dict = {key:image_dict[key] for key in train}, {key:image_dict[key] for key in val}, {key:image_dict[key] for key in test}
else:
train_image_dict, val_image_dict = {},{}
for key in train:
# train_ixs = np.random.choice(len(image_dict[key]), int(len(image_dict[key])*opt.train_val_split), replace=False)
train_ixs = np.array(list(set(np.round(np.linspace(0,len(image_dict[key])-1,int(len(image_dict[key])*opt.train_val_split)))))).astype(int)
val_ixs = np.array([x for x in range(len(image_dict[key])) if x not in train_ixs])
train_image_dict[key] = np.array(image_dict[key])[train_ixs]
val_image_dict[key] = np.array(image_dict[key])[val_ixs]
else:
train_image_dict = {key:image_dict[key] for key in train}
test_image_dict = {key:image_dict[key] for key in test}
train_dataset = BaseTripletDataset(train_image_dict, opt, samples_per_class=opt.samples_per_class)
test_dataset = BaseTripletDataset(test_image_dict, opt, is_validation=True)
eval_dataset = BaseTripletDataset(train_image_dict, opt, is_validation=True)
train_dataset.conversion = conversion
test_dataset.conversion = conversion
eval_dataset.conversion = conversion
if opt.sampling!='learned':
return {'training':train_dataset, 'testing':test_dataset, 'evaluation':eval_dataset}
else:
val_dataset = BaseTripletDataset(val_image_dict, opt, is_validation=True)
val_dataset.conversion = conversion
return {'training':train_dataset, 'validation':val_dataset, 'testing':test_dataset, 'evaluation':eval_dataset}
def give_CARS196_datasets(opt):
"""
This function generates a training and testing dataloader for Metric Learning on the CARS-196 dataset.
For Metric Learning, the dataset is sorted by name, and the first halt used for training while the last half is used for testing.
So no random shuffling of classes.
"""
image_sourcepath = opt.source_path+'/images'
image_classes = sorted([x for x in os.listdir(image_sourcepath)])
conversion = {i:x for i,x in enumerate(image_classes)}
image_list = {i:sorted([image_sourcepath+'/'+key+'/'+x for x in os.listdir(image_sourcepath+'/'+key)]) for i,key in enumerate(image_classes)}
image_list = [[(key,img_path) for img_path in image_list[key]] for key in image_list.keys()]
image_list = [x for y in image_list for x in y]
image_dict = {}
for key, img_path in image_list:
if not key in image_dict.keys():
image_dict[key] = []
image_dict[key].append(img_path)
keys = sorted(list(image_dict.keys()))
# random.shuffle(keys)
#Following "Deep Metric Learning via Lifted Structured Feature Embedding", we use the first half of classes for training.
train,test = keys[:len(keys)//2], keys[len(keys)//2:]
if opt.sampling=='learned':
if opt.train_val_split_by_class:
train_val_split = int(len(train)*opt.train_val_split)
train, val = train[:train_val_split], train[train_val_split:]
train_image_dict, val_image_dict, test_image_dict = {key:image_dict[key] for key in train}, {key:image_dict[key] for key in val}, {key:image_dict[key] for key in test}
else:
train_image_dict, val_image_dict = {},{}
for key in train:
train_ixs = np.random.choice(len(image_dict[key]), int(len(image_dict[key])*opt.train_val_split), replace=False)
val_ixs = np.array([x for x in range(len(image_dict[key])) if x not in train_ixs])
train_image_dict[key] = np.array(image_dict[key])[train_ixs]
val_image_dict[key] = np.array(image_dict[key])[val_ixs]
test_image_dict = {key:image_dict[key] for key in test}
val_dataset = BaseTripletDataset(val_image_dict, opt, is_validation=True)
val_dataset.conversion = conversion
else:
train_image_dict, test_image_dict = {key:image_dict[key] for key in train}, {key:image_dict[key] for key in test}
val_dataset = None
train_dataset = BaseTripletDataset(train_image_dict, opt, samples_per_class=opt.samples_per_class)
test_dataset = BaseTripletDataset(test_image_dict, opt, is_validation=True)
eval_dataset = BaseTripletDataset(train_image_dict, opt, is_validation=True)
train_dataset.conversion = conversion
test_dataset.conversion = conversion
eval_dataset.conversion = conversion
return {'training':train_dataset, 'validation':val_dataset, 'testing':test_dataset, 'evaluation':eval_dataset}
def give_OnlineProducts_datasets(opt):
image_sourcepath = opt.source_path+'/images'
training_files = pd.read_table(opt.source_path+'/Info_Files/Ebay_train.txt', header=0, delimiter=' ')
test_files = pd.read_table(opt.source_path+'/Info_Files/Ebay_test.txt', header=0, delimiter=' ')
conversion, super_conversion = {},{}
for class_id, path in zip(training_files['class_id'],training_files['path']):
conversion[class_id] = path.split('/')[0]
for super_class_id, path in zip(training_files['super_class_id'],training_files['path']):
conversion[super_class_id] = path.split('/')[0]
for class_id, path in zip(test_files['class_id'],test_files['path']):
conversion[class_id] = path.split('/')[0]
train_image_dict, test_image_dict, super_train_image_dict = {},{},{}
for key, img_path in zip(training_files['class_id'],training_files['path']):
key = key-1
if not key in train_image_dict.keys():
train_image_dict[key] = []
train_image_dict[key].append(image_sourcepath+'/'+img_path)
for key, img_path in zip(test_files['class_id'],test_files['path']):
key = key-1
if not key in test_image_dict.keys():
test_image_dict[key] = []
test_image_dict[key].append(image_sourcepath+'/'+img_path)
for key, img_path in zip(training_files['super_class_id'],training_files['path']):
key = key-1
if not key in super_train_image_dict.keys():
super_train_image_dict[key] = []
super_train_image_dict[key].append(image_sourcepath+'/'+img_path)
train_keys = list(train_image_dict.keys())
# if opt.train_val_split_by_class:
if opt.sampling=='learned':
train_val_split = int(len(train_keys)*opt.train_val_split)
train, val = train_keys[:train_val_split], train_keys[train_val_split:]
train_image_dict, val_image_dict = {key:train_image_dict[key] for key in train}, {key:train_image_dict[key] for key in val}
val_dataset = BaseTripletDataset(val_image_dict, opt, is_validation=True)
val_dataset.conversion = conversion
else:
val_dataset = None
# else:
# train_image_dict_temp, val_image_dict_temp = {},{}
# for key in train_keys:
# print(len(train_image_dict[key]))
# train_ixs = np.random.choice(len(train_image_dict[key]), int(len(train_image_dict[key])*opt.train_val_split), replace=False)
# val_ixs = np.array([x for x in range(len(train_image_dict[key])) if x not in train_ixs])
# train_image_dict_temp[key] = np.array(image_dict[key])[train_ixs]
# val_image_dict_temp[key] = np.array(image_dict[key])[val_ixs]
super_train_dataset = BaseTripletDataset(super_train_image_dict, opt, is_validation=True)
train_dataset = BaseTripletDataset(train_image_dict, opt, samples_per_class=opt.samples_per_class)
test_dataset = BaseTripletDataset(test_image_dict, opt, is_validation=True)
eval_dataset = BaseTripletDataset(train_image_dict, opt, is_validation=True)
super_train_dataset.conversion = super_conversion
train_dataset.conversion = conversion
test_dataset.conversion = conversion
eval_dataset.conversion = conversion
return {'training':train_dataset, 'validation':val_dataset, 'testing':test_dataset, 'evaluation':eval_dataset, 'super_evaluation':super_train_dataset}
"""==================================================================================================="""
################## BASIC PYTORCH DATASET USED FOR ALL DATASETS ##################################
class BaseTripletDataset(Dataset):
def __init__(self, image_dict, opt, samples_per_class=8, is_validation=False):
self.is_validation = is_validation
self.pars = opt
self.image_dict = image_dict
self.samples_per_class = samples_per_class
#####
self.init_setup()
##### Option 2: Use Mean/Stds on which the networks were trained
if 'bninception' in opt.arch:
normalize = transforms.Normalize(mean=[0.502, 0.4588, 0.4078],std=[0.0039, 0.0039, 0.0039])
else:
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],std=[0.229, 0.224, 0.225])
transf_list = []
if not self.is_validation:
transf_list.extend([transforms.RandomResizedCrop(size=224), transforms.RandomHorizontalFlip(0.5)])
else:
transf_list.extend([transforms.Resize(256), transforms.CenterCrop(224)])
transf_list.extend([transforms.ToTensor(),
normalize])
self.transform = transforms.Compose(transf_list)
def init_setup(self):
self.n_files = np.sum([len(self.image_dict[key]) for key in self.image_dict.keys()])
self.avail_classes = sorted(list(self.image_dict.keys()))
self.image_dict = {i:self.image_dict[key] for i,key in enumerate(self.avail_classes)}
self.avail_classes = sorted(list(self.image_dict.keys()))
if not self.is_validation:
#Select current class to sample images from up to <samples_per_class>
self.current_class = np.random.randint(len(self.avail_classes))
self.classes_visited = [self.current_class, self.current_class]
self.n_samples_drawn = 0
# if self.is_validation or self.samples_per_class==1:
self.image_list = [[(x,key) for x in self.image_dict[key]] for key in self.image_dict.keys()]
self.image_list = [x for y in self.image_list for x in y]
# self.sample_probs = np.ones(len(self.image_list))/len(self.image_list)
self.is_init = True
def ensure_3dim(self, img):
if len(img.size)==2:
img = img.convert('RGB')
return img
def __getitem__(self, idx):
if self.is_init:
self.current_class = self.avail_classes[idx%len(self.avail_classes)]
self.is_init = False
if not self.is_validation:
if self.samples_per_class==1:
return (self.image_list[idx][-1], self.transform(self.ensure_3dim(Image.open(self.image_list[idx][0]))))
if self.n_samples_drawn==self.samples_per_class:
#Once enough samples per class have been drawn, we choose another class to draw samples from.
#Note that we ensure with self.classes_visited that no class is chosen if it had been chosen
#previously or one before that.
counter = copy.deepcopy(self.avail_classes)
for prev_class in self.classes_visited:
if prev_class in counter: counter.remove(prev_class)
self.current_class = counter[idx%len(counter)]
self.classes_visited = self.classes_visited[1:]+[self.current_class]
self.n_samples_drawn = 0
class_sample_idx = idx%len(self.image_dict[self.current_class])
self.n_samples_drawn += 1
out_img = self.transform(self.ensure_3dim(Image.open(self.image_dict[self.current_class][class_sample_idx])))
if 'bninception' in self.pars.arch:
out_img = out_img[range(3)[::-1],:]
return (self.current_class,out_img)
else:
out_img = self.transform(self.ensure_3dim(Image.open(self.image_list[idx][0])))
if 'bninception' in self.pars.arch:
out_img = out_img[range(3)[::-1],:]
return (self.image_list[idx][-1], out_img)
def __len__(self):
return self.n_files
|
[
"copy.deepcopy",
"torch.utils.data.DataLoader",
"warnings.filterwarnings",
"torchvision.transforms.RandomHorizontalFlip",
"torchvision.transforms.RandomResizedCrop",
"PIL.Image.open",
"torchvision.transforms.Compose",
"numpy.array",
"pandas.read_table",
"torchvision.transforms.CenterCrop",
"torchvision.transforms.Normalize",
"torchvision.transforms.Resize",
"os.listdir",
"torchvision.transforms.ToTensor"
] |
[((248, 281), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (271, 281), False, 'import warnings\n'), ((8460, 8550), 'pandas.read_table', 'pd.read_table', (["(opt.source_path + '/Info_Files/Ebay_train.txt')"], {'header': '(0)', 'delimiter': '""" """'}), "(opt.source_path + '/Info_Files/Ebay_train.txt', header=0,\n delimiter=' ')\n", (8473, 8550), True, 'import numpy as np, os, sys, pandas as pd, csv, copy\n'), ((8566, 8655), 'pandas.read_table', 'pd.read_table', (["(opt.source_path + '/Info_Files/Ebay_test.txt')"], {'header': '(0)', 'delimiter': '""" """'}), "(opt.source_path + '/Info_Files/Ebay_test.txt', header=0,\n delimiter=' ')\n", (8579, 8655), True, 'import numpy as np, os, sys, pandas as pd, csv, copy\n'), ((13075, 13106), 'torchvision.transforms.Compose', 'transforms.Compose', (['transf_list'], {}), '(transf_list)\n', (13093, 13106), False, 'from torchvision import transforms\n'), ((1568, 1712), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['dataset'], {'batch_size': 'opt.bs', 'num_workers': 'opt.kernels', 'shuffle': '(not is_val)', 'pin_memory': '(True)', 'drop_last': '(not is_val)'}), '(dataset, batch_size=opt.bs, num_workers=opt.\n kernels, shuffle=not is_val, pin_memory=True, drop_last=not is_val)\n', (1595, 1712), False, 'import torch, torch.nn as nn, matplotlib.pyplot as plt, random\n'), ((12495, 12580), 'torchvision.transforms.Normalize', 'transforms.Normalize', ([], {'mean': '[0.502, 0.4588, 0.4078]', 'std': '[0.0039, 0.0039, 0.0039]'}), '(mean=[0.502, 0.4588, 0.4078], std=[0.0039, 0.0039, 0.0039]\n )\n', (12515, 12580), False, 'from torchvision import transforms\n'), ((12613, 12688), 'torchvision.transforms.Normalize', 'transforms.Normalize', ([], {'mean': '[0.485, 0.456, 0.406]', 'std': '[0.229, 0.224, 0.225]'}), '(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n', (12633, 12688), False, 'from torchvision import transforms\n'), ((2417, 2445), 'os.listdir', 'os.listdir', (['image_sourcepath'], {}), '(image_sourcepath)\n', (2427, 2445), False, 'import numpy as np, os, sys, pandas as pd, csv, copy\n'), ((5765, 5793), 'os.listdir', 'os.listdir', (['image_sourcepath'], {}), '(image_sourcepath)\n', (5775, 5793), False, 'import numpy as np, os, sys, pandas as pd, csv, copy\n'), ((12987, 13008), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (13006, 13008), False, 'from torchvision import transforms\n'), ((14963, 14996), 'copy.deepcopy', 'copy.deepcopy', (['self.avail_classes'], {}), '(self.avail_classes)\n', (14976, 14996), False, 'import numpy as np, os, sys, pandas as pd, csv, copy\n'), ((2684, 2724), 'os.listdir', 'os.listdir', (["(image_sourcepath + '/' + key)"], {}), "(image_sourcepath + '/' + key)\n", (2694, 2724), False, 'import numpy as np, os, sys, pandas as pd, csv, copy\n'), ((4313, 4338), 'numpy.array', 'np.array', (['image_dict[key]'], {}), '(image_dict[key])\n', (4321, 4338), True, 'import numpy as np, os, sys, pandas as pd, csv, copy\n'), ((4390, 4415), 'numpy.array', 'np.array', (['image_dict[key]'], {}), '(image_dict[key])\n', (4398, 4415), True, 'import numpy as np, os, sys, pandas as pd, csv, copy\n'), ((5929, 5969), 'os.listdir', 'os.listdir', (["(image_sourcepath + '/' + key)"], {}), "(image_sourcepath + '/' + key)\n", (5939, 5969), False, 'import numpy as np, os, sys, pandas as pd, csv, copy\n'), ((7365, 7390), 'numpy.array', 'np.array', (['image_dict[key]'], {}), '(image_dict[key])\n', (7373, 7390), True, 'import numpy as np, os, sys, pandas as pd, csv, copy\n'), ((7442, 7467), 'numpy.array', 'np.array', (['image_dict[key]'], {}), '(image_dict[key])\n', (7450, 7467), True, 'import numpy as np, os, sys, pandas as pd, csv, copy\n'), ((12780, 12818), 'torchvision.transforms.RandomResizedCrop', 'transforms.RandomResizedCrop', ([], {'size': '(224)'}), '(size=224)\n', (12808, 12818), False, 'from torchvision import transforms\n'), ((12820, 12856), 'torchvision.transforms.RandomHorizontalFlip', 'transforms.RandomHorizontalFlip', (['(0.5)'], {}), '(0.5)\n', (12851, 12856), False, 'from torchvision import transforms\n'), ((12905, 12927), 'torchvision.transforms.Resize', 'transforms.Resize', (['(256)'], {}), '(256)\n', (12922, 12927), False, 'from torchvision import transforms\n'), ((12929, 12955), 'torchvision.transforms.CenterCrop', 'transforms.CenterCrop', (['(224)'], {}), '(224)\n', (12950, 12955), False, 'from torchvision import transforms\n'), ((15489, 15554), 'PIL.Image.open', 'Image.open', (['self.image_dict[self.current_class][class_sample_idx]'], {}), '(self.image_dict[self.current_class][class_sample_idx])\n', (15499, 15554), False, 'from PIL import Image\n'), ((15773, 15808), 'PIL.Image.open', 'Image.open', (['self.image_list[idx][0]'], {}), '(self.image_list[idx][0])\n', (15783, 15808), False, 'from PIL import Image\n'), ((14569, 14604), 'PIL.Image.open', 'Image.open', (['self.image_list[idx][0]'], {}), '(self.image_list[idx][0])\n', (14579, 14604), False, 'from PIL import Image\n')]
|
#!/usr/bin/env python
#------------------------------------------------------------
# Purpose: Program finds best-fit pararameters of a model
# a*sin(bx+c) with data with errors in both variables
# x and y. It uses the effective variance method for
# kmpfit and the results are compared with SciPy's
# ODR routine.
# It can be used to demonstrate the sensitivity of
# the fit process to initial estimates by varying
# values for beta0
# Vog, 09 Dec, 2011
#------------------------------------------------------------
import numpy
from matplotlib.pyplot import figure, show, rc
from numpy.random import normal
from kapteyn import kmpfit
def model(p, x):
# Model: Y = a*sin(b*x+c)
a,b,c = p
return a * numpy.sin(b*x+c)
def residuals(p, data):
# Effective variance method
a, b, c = p
x, y, ex, ey = data
e2 = ey*ey + (a*b*numpy.cos(b*x+c))**2*ex*ex
w = numpy.sqrt(numpy.where(e2==0.0, 0.0, 1.0/(e2)))
d = w*(y-model(p,x))
return d
def residuals2(p, data):
# Merit function for data with errors Y only
a, b, c = p
x, y, ey = data
w = numpy.where(ey==0.0, 0.0, 1.0/(ey))
d = w*(y-model(p,x))
return d
# Generate noisy data points
N = 30
a0 = 2; b0 = 1; c0 = 1
x = numpy.linspace(-3, 7.0, N)
y = model((a0,b0,c0),x) + normal(0.0, 0.3, N)
errx = normal(0.1, 0.2, N)
erry = normal(0.1, 0.3, N)
# It is important to start with realistic initial estimates
beta0 = [1.8,0.9,0.9]
print("\nODR:")
print("==========")
from scipy.odr import Data, Model, ODR, RealData, odr_stop
linear = Model(model)
mydata = RealData(x, y, sx=errx, sy=erry)
myodr = ODR(mydata, linear, beta0=beta0, maxit=5000)
myoutput = myodr.run()
print("Fitted parameters: ", myoutput.beta)
print("Covariance errors: ", numpy.sqrt(myoutput.cov_beta.diagonal()))
print("Standard errors: ", myoutput.sd_beta)
print("Minimum chi^2: ", myoutput.sum_square)
print("Minimum (reduced)chi^2: ", myoutput.res_var)
beta = myoutput.beta
# Prepare fit routine
fitobj = kmpfit.Fitter(residuals=residuals, data=(x, y, errx, erry))
fitobj.fit(params0=beta0)
print("\n\n======== Results kmpfit with effective variance =========")
print("Fitted parameters: ", fitobj.params)
print("Covariance errors: ", fitobj.xerror)
print("Standard errors: ", fitobj.stderr)
print("Chi^2 min: ", fitobj.chi2_min)
print("Reduced Chi^2: ", fitobj.rchi2_min)
print("Status Message:", fitobj.message)
# Compare to a fit with weights for y only
fitobj2 = kmpfit.Fitter(residuals=residuals2, data=(x, y, erry))
fitobj2.fit(params0=beta0)
print("\n\n======== Results kmpfit errors in Y only =========")
print("Fitted parameters: ", fitobj2.params)
print("Covariance errors: ", fitobj2.xerror)
print("Standard errors: ", fitobj2.stderr)
print("Chi^2 min: ", fitobj2.chi2_min)
print("Reduced Chi^2: ", fitobj2.rchi2_min)
print("Status Message:", fitobj2.message)
# Some plotting
rc('font', size=9)
rc('legend', fontsize=8)
fig = figure(1)
frame = fig.add_subplot(1,1,1, aspect=1, adjustable='datalim')
frame.errorbar(x, y, xerr=errx, yerr=erry, fmt='bo')
# Plot first fit
frame.plot(x, model(beta,x), '-y', lw=4, label="SciPy's ODR", alpha=0.6)
frame.plot(x, model(fitobj.params,x), 'c', ls='--', lw=2, label="kmpfit (errors in X & Y")
frame.plot(x, model(fitobj2.params,x), 'm', ls='--', lw=2, label="kmpfit (errors in Y only)")
frame.plot(x, model((a0,b0,c0),x), 'r', label="Model with true parameters")
frame.set_xlabel("X")
frame.set_ylabel("Y")
frame.set_title("ODR and kmpfit with weighted fit. Model: $y=a\,\sin(bx+c)$")
frame.grid(True)
leg = frame.legend(loc=2)
show()
|
[
"kapteyn.kmpfit.Fitter",
"scipy.odr.ODR",
"matplotlib.pyplot.show",
"scipy.odr.Model",
"scipy.odr.RealData",
"matplotlib.pyplot.figure",
"numpy.where",
"numpy.sin",
"matplotlib.pyplot.rc",
"numpy.random.normal",
"numpy.linspace",
"numpy.cos"
] |
[((1276, 1302), 'numpy.linspace', 'numpy.linspace', (['(-3)', '(7.0)', 'N'], {}), '(-3, 7.0, N)\n', (1290, 1302), False, 'import numpy\n'), ((1356, 1375), 'numpy.random.normal', 'normal', (['(0.1)', '(0.2)', 'N'], {}), '(0.1, 0.2, N)\n', (1362, 1375), False, 'from numpy.random import normal\n'), ((1384, 1403), 'numpy.random.normal', 'normal', (['(0.1)', '(0.3)', 'N'], {}), '(0.1, 0.3, N)\n', (1390, 1403), False, 'from numpy.random import normal\n'), ((1593, 1605), 'scipy.odr.Model', 'Model', (['model'], {}), '(model)\n', (1598, 1605), False, 'from scipy.odr import Data, Model, ODR, RealData, odr_stop\n'), ((1615, 1647), 'scipy.odr.RealData', 'RealData', (['x', 'y'], {'sx': 'errx', 'sy': 'erry'}), '(x, y, sx=errx, sy=erry)\n', (1623, 1647), False, 'from scipy.odr import Data, Model, ODR, RealData, odr_stop\n'), ((1656, 1700), 'scipy.odr.ODR', 'ODR', (['mydata', 'linear'], {'beta0': 'beta0', 'maxit': '(5000)'}), '(mydata, linear, beta0=beta0, maxit=5000)\n', (1659, 1700), False, 'from scipy.odr import Data, Model, ODR, RealData, odr_stop\n'), ((2062, 2121), 'kapteyn.kmpfit.Fitter', 'kmpfit.Fitter', ([], {'residuals': 'residuals', 'data': '(x, y, errx, erry)'}), '(residuals=residuals, data=(x, y, errx, erry))\n', (2075, 2121), False, 'from kapteyn import kmpfit\n'), ((2565, 2619), 'kapteyn.kmpfit.Fitter', 'kmpfit.Fitter', ([], {'residuals': 'residuals2', 'data': '(x, y, erry)'}), '(residuals=residuals2, data=(x, y, erry))\n', (2578, 2619), False, 'from kapteyn import kmpfit\n'), ((3026, 3044), 'matplotlib.pyplot.rc', 'rc', (['"""font"""'], {'size': '(9)'}), "('font', size=9)\n", (3028, 3044), False, 'from matplotlib.pyplot import figure, show, rc\n'), ((3045, 3069), 'matplotlib.pyplot.rc', 'rc', (['"""legend"""'], {'fontsize': '(8)'}), "('legend', fontsize=8)\n", (3047, 3069), False, 'from matplotlib.pyplot import figure, show, rc\n'), ((3076, 3085), 'matplotlib.pyplot.figure', 'figure', (['(1)'], {}), '(1)\n', (3082, 3085), False, 'from matplotlib.pyplot import figure, show, rc\n'), ((3719, 3725), 'matplotlib.pyplot.show', 'show', ([], {}), '()\n', (3723, 3725), False, 'from matplotlib.pyplot import figure, show, rc\n'), ((1139, 1176), 'numpy.where', 'numpy.where', (['(ey == 0.0)', '(0.0)', '(1.0 / ey)'], {}), '(ey == 0.0, 0.0, 1.0 / ey)\n', (1150, 1176), False, 'import numpy\n'), ((1329, 1348), 'numpy.random.normal', 'normal', (['(0.0)', '(0.3)', 'N'], {}), '(0.0, 0.3, N)\n', (1335, 1348), False, 'from numpy.random import normal\n'), ((774, 794), 'numpy.sin', 'numpy.sin', (['(b * x + c)'], {}), '(b * x + c)\n', (783, 794), False, 'import numpy\n'), ((951, 988), 'numpy.where', 'numpy.where', (['(e2 == 0.0)', '(0.0)', '(1.0 / e2)'], {}), '(e2 == 0.0, 0.0, 1.0 / e2)\n', (962, 988), False, 'import numpy\n'), ((906, 926), 'numpy.cos', 'numpy.cos', (['(b * x + c)'], {}), '(b * x + c)\n', (915, 926), False, 'import numpy\n')]
|
#-*- coding:utf-8 -*-
"""
Main class that provides SPC analysis. It detects SPC rules violations.
It can draw charts using matplotlib.
:arguments:
data
user data as flat array/list
"""
from utils import *
import numpy as np
import pandas as pd
RULE_1_BEYOND_3SIGMA = '1个点落在A区以外'
RULE_2_OF_3_BEYOND_2SIGMA_ONE_SIDE = '3个点中有2个点连续落在B区以外'
RULE_4_OF_5_BEYOND_1SIGMA = '5个点中有4个点连续落在中心线同一侧C区以外'
RULE_6_TRENDING = '6个点连续增长或下降'
RULE_8_ON_TWO_SIDE_NONE_C = '8个连续的点落在中心线两侧且无一点在C区'
RULE_9_ON_ONE_SIDE = '9个连续的点在中心线的同一侧'
RULE_14_up_down = '连续14个点交替上下'
RULE_15_below_1sigma = '15个连续点在在中心线两侧C区'
RULES_ALL = [RULE_1_BEYOND_3SIGMA,
RULE_2_OF_3_BEYOND_2SIGMA_ONE_SIDE,
RULE_4_OF_5_BEYOND_1SIGMA,
RULE_6_TRENDING,
RULE_8_ON_TWO_SIDE_NONE_C,
RULE_9_ON_ONE_SIDE,
RULE_14_up_down,
RULE_15_below_1sigma]
RULES_FUNCS = {
RULE_1_BEYOND_3SIGMA: (test_1_beyond_3sigma, 1),
RULE_2_OF_3_BEYOND_2SIGMA_ONE_SIDE: (test_2_OF_3_BEYOND_2SIGMA_ONE_SIDE, 3),
RULE_4_OF_5_BEYOND_1SIGMA: (test_4_OF_5_BEYOND_1SIGMA_ONE_SIDE, 5),
RULE_6_TRENDING: (test_6_thrund, 6),
RULE_8_ON_TWO_SIDE_NONE_C: (test_8_BEYOND_1SIGMA, 8),
RULE_9_ON_ONE_SIDE: (test_violating_runs, 9),
RULE_14_up_down: (test_14_up_down, 14),
RULE_15_below_1sigma: (test_15_below_sigma, 15)}
class SPC_rule(object):
"""
Main class that provides WECR analysis. It detects WECR rules violations.
It can draw charts using matplotlib.
:arguments:
data
user data as flat array/list
"""
def __init__(self, data, center=None, sigma=None, rule_keys=None):
'''
:param data: list/dataframe/np.ndarray
:param center: mean
:param sigma: sigma
:param rule_keys: list, key of rules, such:[1,2]
1:RULE_1_BEYOND_3SIGMA = '1个点落在A区以外'
2:RULE_2_OF_3_BEYOND_2SIGMA_ONE_SIDE = '3个点中有2个点连续落在B区以外'
3:RULE_4_OF_5_BEYOND_1SIGMA = '5个点中有4个点连续落在中心线同一侧C区以外'
4:RULE_6_TRENDING = '6个点连续增长或下降'
5:RULE_8_ON_TWO_SIDE_NONE_C = '8个连续的点落在中心线两侧且无一点在C区'
6:RULE_9_ON_ONE_SIDE = '9个连续的点在中心线的同一侧'
7:RULE_14_up_down = '连续14个点交替上下'
8:RULE_15_below_1sigma = '15个连续点在在中心线两侧C区'
'''
if isinstance(data, pd.DataFrame):
data = data.values
data = data.reshape((1, -1))
data = list(data)
if isinstance(data, np.ndarray):
data = data.reshape((1, -1))
elif not isinstance(data, list):
raise TypeError('please input data of list or pd.Dataframe or np.ndarray')
self.orig_data = data
if not center:
center = np.mean(data)
self.center = center
if not sigma:
sigma = np.std(data, ddof=1)
self.sigma = sigma
if not rule_keys:
rule_new = RULES_ALL
else:
rule_new = []
for key in rule_keys:
rule_new.append(RULES_ALL[key-1])
self.rules = rule_new
self.length = len(data)
self.violating_points = self._find_violating_points()
def __repr__(self):
print(self.get_violating_points())
return "<spc: (%d)>" % self.__hash__()
def _find_violating_points(self):
points_all = {}
for r in self.rules:
func, points_num = RULES_FUNCS[r]
list1 = []
for i in range(len(self.orig_data)):
if i < points_num-1:
continue
if func(self.orig_data[i - points_num+1:i+1], self.center, self.sigma):
list1.extend(range(i - points_num+1, i+1))
points_all.setdefault(r, []).extend(list1)
return points_all
def get_violating_points(self):
"""Return points that violates rules"""
points_all = self.violating_points
points_dict = {}
for key, values in points_all.items():
# if values != []:
points_dict[key] = sorted(set(values))
return points_dict
|
[
"numpy.std",
"numpy.mean"
] |
[((2792, 2805), 'numpy.mean', 'np.mean', (['data'], {}), '(data)\n', (2799, 2805), True, 'import numpy as np\n'), ((2882, 2902), 'numpy.std', 'np.std', (['data'], {'ddof': '(1)'}), '(data, ddof=1)\n', (2888, 2902), True, 'import numpy as np\n')]
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/12/21 2:30 PM
# @Author : zhangzhen
# @Site :
# @File : __init__.py
# @Software: PyCharm
import tensorflow as tf
from numpy.random import RandomState as rdm
import logging
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.DEBUG)
class MLP:
def __init__(self, in_size=10, out_size=2, hiddens=[10], act_function=None) -> object:
self.x_dimension = in_size
self.y_dimension = out_size
self.build(in_size, out_size, hiddens=hiddens, act_function=act_function)
def build(self, in_size, out_size, hiddens=[], act_function=tf.nn.relu):
def add_layer(inputs: object, in_size: object, out_size: object, act_function: object = None) -> object:
W = tf.Variable(tf.random_normal([in_size, out_size]))
b = tf.Variable(tf.constant(0.1, shape=[out_size]))
Wx_plus_b = tf.matmul(inputs, W) + b
if act_function:
outputs = act_function(Wx_plus_b)
else:
outputs = Wx_plus_b
logging.info("tmp hidden layer out: {}".format(outputs))
return outputs
self.x = tf.placeholder(dtype=tf.float32, shape=(None, in_size), name='X-input')
self.y_ = tf.placeholder(dtype=tf.float32, shape=(None, out_size), name='y-input')
tmp_in_size = in_size
tmp_inputs = self.x
for hidden in hiddens:
tmp_outputs = add_layer(tmp_inputs, tmp_in_size, hidden, act_function=act_function)
tmp_in_size = hidden
tmp_inputs = tmp_outputs
self.y = add_layer(tmp_inputs, tmp_in_size, out_size, act_function=None)
logging.info("last out: {}".format(self.y))
self.cross_entropy = -tf.reduce_mean(self.y_ * tf.log(tf.clip_by_value(self.y, 1e-10, 1.0)))
self.step = tf.train.AdamOptimizer(0.001).minimize(self.cross_entropy)
logging.info("loss: {}".format(self.cross_entropy))
def train(self, steps=5000, batch_size=8):
X, Y = self.generate_data(size=128)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
# logging.info()
for i in range(steps):
start = (i*batch_size) % self.dataset_size
end = min(start+batch_size, self.dataset_size)
sess.run(self.step, feed_dict={self.x: X[start: end], self.y_: Y[start: end]})
if i % 1000 == 0:
total_losses = sess.run(self.cross_entropy, feed_dict={self.x: X, self.y_: Y})
logging.info("After {} training steps, crosses entropy on all data is {}".format(i, total_losses))
def predict(self):
pass
def generate_data(self, size=128, rdm_seed=1):
r = rdm(rdm_seed)
self.dataset_size = size
X = r.rand(size, self.x_dimension)
Y = [[int(sum(xs) < self.x_dimension/2)] for xs in X]
return X, Y
if __name__ == '__main__':
mlp = MLP(in_size=2, out_size=1)
mlp.train()
|
[
"logging.basicConfig",
"tensorflow.clip_by_value",
"tensorflow.global_variables_initializer",
"tensorflow.Session",
"numpy.random.RandomState",
"tensorflow.constant",
"tensorflow.placeholder",
"tensorflow.matmul",
"tensorflow.random_normal",
"tensorflow.train.AdamOptimizer"
] |
[((244, 340), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)s : %(levelname)s : %(message)s"""', 'level': 'logging.DEBUG'}), "(format='%(asctime)s : %(levelname)s : %(message)s',\n level=logging.DEBUG)\n", (263, 340), False, 'import logging\n'), ((1214, 1285), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.float32', 'shape': '(None, in_size)', 'name': '"""X-input"""'}), "(dtype=tf.float32, shape=(None, in_size), name='X-input')\n", (1228, 1285), True, 'import tensorflow as tf\n'), ((1304, 1376), 'tensorflow.placeholder', 'tf.placeholder', ([], {'dtype': 'tf.float32', 'shape': '(None, out_size)', 'name': '"""y-input"""'}), "(dtype=tf.float32, shape=(None, out_size), name='y-input')\n", (1318, 1376), True, 'import tensorflow as tf\n'), ((2825, 2838), 'numpy.random.RandomState', 'rdm', (['rdm_seed'], {}), '(rdm_seed)\n', (2828, 2838), True, 'from numpy.random import RandomState as rdm\n'), ((2113, 2125), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (2123, 2125), True, 'import tensorflow as tf\n'), ((815, 852), 'tensorflow.random_normal', 'tf.random_normal', (['[in_size, out_size]'], {}), '([in_size, out_size])\n', (831, 852), True, 'import tensorflow as tf\n'), ((882, 916), 'tensorflow.constant', 'tf.constant', (['(0.1)'], {'shape': '[out_size]'}), '(0.1, shape=[out_size])\n', (893, 916), True, 'import tensorflow as tf\n'), ((942, 962), 'tensorflow.matmul', 'tf.matmul', (['inputs', 'W'], {}), '(inputs, W)\n', (951, 962), True, 'import tensorflow as tf\n'), ((1888, 1917), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', (['(0.001)'], {}), '(0.001)\n', (1910, 1917), True, 'import tensorflow as tf\n'), ((2156, 2189), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (2187, 2189), True, 'import tensorflow as tf\n'), ((1829, 1865), 'tensorflow.clip_by_value', 'tf.clip_by_value', (['self.y', '(1e-10)', '(1.0)'], {}), '(self.y, 1e-10, 1.0)\n', (1845, 1865), True, 'import tensorflow as tf\n')]
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 5 23:54:49 2018
@author: tyler
"""
import numpy as np
#%%
def postprocess_cut(supernodes_original,supernodes_f,supernode_nonempty_Q,not_loop_Q):
'''
returns : partition of original vertices of $G$ and size of coresponding cut
'''
sn = supernodes_f[supernode_nonempty_Q]
size_E = sum(not_loop_Q)
if len(sn[0])<len(sn[1]):
sn = sn[0]
else:
sn = sn[1]
for v in list(sn):
if v >= len(supernodes):
sn.remove(v)
for sn_o in supernodes_original:
if v in sn_o:
sn.add(min(sn_o))
break
return list(sn),size_E
#%%
def karger(E,G,supernodes,supernode_nonempty_Q,not_loop_Q):
# start = time.clock()
size_E = np.shape(E)[0]
size_V = sum(supernode_nonempty_Q)
f = 0
s = 0
sn0 = {}
for j in range(size_V-2):
if j%500==0:
print('===================')
print('iteration:', j)
'''
print('find endpoints: ',f)
print('find loops : ', s)
f = 0
s = 0
print('sn0 size: ', len(sn0))
sn_count = sum(map(len,supernodes[np.where(supernode_nonempty_Q)[0]]))
print('numer of vert :', sn_count)
print('numer of sns :', sum(supernode_nonempty_Q))
'''
# pick random edge
#probably can't be faster than this unless we can compile
cs = np.cumsum(not_loop_Q)
# rand_idx = np.where(cs > np.random.randint(cs[-1]))[0][0]
rand_idx = np.searchsorted(cs, np.random.randint(cs[-1]))
e0,e1 = E[rand_idx]
#find edge endopoint vertices
# start = time.clock()
supernode_nonempty_idx = np.where(supernode_nonempty_Q)[0]
for i0 in supernode_nonempty_idx:
if e0 in supernodes[i0]:
break
for i1 in supernode_nonempty_idx[::-1]:
if e1 in supernodes[i1]:
break
# f += (time.clock() - start)
# merge vertex equivalence classes
sn0 = supernodes[i0]
sn1 = supernodes[i1]
# find loops
# search for edges with one end in sn0 and one in sn1
# start = time.clock()
for i in sn0:
Gi = G[i]
for j in sn1:
Gij = Gi[j]
if Gij != -1:
if not_loop_Q[Gij]:
not_loop_Q[Gij] = False
# s += time.clock() - start
# put sn1 into sn0 and sn1 into sn0 and delete sn1
supernodes[i0] = supernodes[i0] | supernodes[i1]
supernode_nonempty_Q[i1] = False
return supernodes,supernode_nonempty_Q,not_loop_Q
#%% load data
d = np.load('b0_pre.npz')
E=d['E']
G=d['G']
supernodes_=d['supernodes_']
supernode_nonempty_Q_=d['supernode_nonempty_Q_']
del(d)
#%%
supernodes,supernode_nonempty_Q = np.copy(supernodes_),np.copy(supernode_nonempty_Q_)
not_loop_Q = np.ones(len(E),dtype='bool')
supernodes,supernode_nonempty_Q,not_loop_Q = karger(E,G,supernodes,supernode_nonempty_Q,not_loop_Q)
#%%
postprocess_cut(supernodes_,supernodes,supernode_nonempty_Q,not_loop_Q)
#%%
len(E[np.any(E==8,axis=1)])
|
[
"numpy.load",
"numpy.copy",
"numpy.shape",
"numpy.cumsum",
"numpy.any",
"numpy.random.randint",
"numpy.where"
] |
[((2949, 2970), 'numpy.load', 'np.load', (['"""b0_pre.npz"""'], {}), "('b0_pre.npz')\n", (2956, 2970), True, 'import numpy as np\n'), ((3117, 3137), 'numpy.copy', 'np.copy', (['supernodes_'], {}), '(supernodes_)\n', (3124, 3137), True, 'import numpy as np\n'), ((3138, 3168), 'numpy.copy', 'np.copy', (['supernode_nonempty_Q_'], {}), '(supernode_nonempty_Q_)\n', (3145, 3168), True, 'import numpy as np\n'), ((844, 855), 'numpy.shape', 'np.shape', (['E'], {}), '(E)\n', (852, 855), True, 'import numpy as np\n'), ((1584, 1605), 'numpy.cumsum', 'np.cumsum', (['not_loop_Q'], {}), '(not_loop_Q)\n', (1593, 1605), True, 'import numpy as np\n'), ((3402, 3424), 'numpy.any', 'np.any', (['(E == 8)'], {'axis': '(1)'}), '(E == 8, axis=1)\n', (3408, 3424), True, 'import numpy as np\n'), ((1713, 1738), 'numpy.random.randint', 'np.random.randint', (['cs[-1]'], {}), '(cs[-1])\n', (1730, 1738), True, 'import numpy as np\n'), ((1901, 1931), 'numpy.where', 'np.where', (['supernode_nonempty_Q'], {}), '(supernode_nonempty_Q)\n', (1909, 1931), True, 'import numpy as np\n')]
|
import time
from autocfr.worker import Worker, VecWorker, GroupVecWorker
import numpy as np
import ray
class DiverContainer(Worker):
@ray.remote
def run(task):
a = task["a"]
b = task["b"]
result = {
"worker_index": task["worker_index"],
"group_index": task["group_index"],
"a": a,
"b": b,
}
try:
time.sleep(a)
out = a / b
except Exception as e:
result["status"] = "fail"
result["error"] = e
result["info"] = str(e)
else:
result["status"] = "succ"
result["out"] = out
return result
class Diver(Worker):
def run(self, task):
try:
result = self.get_result_dict(task)
a = task["a"]
b = task["b"]
time.sleep(int(a))
out = a / 0
out = a / b
except Exception as e:
result["state"] = "fail"
result["error"] = e
result["info"] = str(e)
else:
result["state"] = "succ"
result["out"] = out
return result
def test_run():
diver = Diver(1)
result = diver.run(dict(a=1, b=0))
assert result["state"] == "fail"
def atest_parallel_run():
ray.init()
vec_worker = VecWorker(3, Diver)
for i in range(10):
a = np.random.randint(low=0, high=100)
b = np.random.randint(low=0, high=100)
vec_worker.add_task(dict(a=a, b=b))
for i in range(20):
time.sleep(0.01)
result = vec_worker.get_result()
print(vec_worker.get_info())
ray.shutdown()
def atest_parallel_run_sync():
ray.init()
vec_worker = VecWorker(2, Diver)
tasks = []
for i in range(10):
a = np.random.randint(low=0, high=100)
b = np.random.randint(low=0, high=100)
tasks.append(dict(a=a, b=b))
results = vec_worker.execute_tasks(tasks)
for task, result in zip(tasks, results):
print(task["a"], task["b"], task["a"] / task["b"], result["out"])
ray.shutdown()
def atest_group_run():
ray.init()
group_vec_worker = GroupVecWorker(10, DiverContainer)
group_vec_worker.add_tasks([dict(a=3, b=4), dict(a=3, b=7), dict(a=1, b=1)])
group_vec_worker.add_tasks([dict(a=3, b=4), dict(a=5, b=0)])
group_vec_worker.add_tasks([dict(a=1, b=0), dict(a=3, b=4), dict(a=3, b=0)])
group_vec_worker.add_tasks([dict(a=1, b=4), dict(a=3, b=0), dict(a=2, b=4), ])
for i in range(20):
time.sleep(1)
print(group_vec_worker.info())
while True:
result = group_vec_worker.get_result()
if result is not None:
print(result)
else:
break
ray.shutdown()
|
[
"ray.init",
"time.sleep",
"numpy.random.randint",
"ray.shutdown",
"autocfr.worker.VecWorker",
"autocfr.worker.GroupVecWorker"
] |
[((1315, 1325), 'ray.init', 'ray.init', ([], {}), '()\n', (1323, 1325), False, 'import ray\n'), ((1343, 1362), 'autocfr.worker.VecWorker', 'VecWorker', (['(3)', 'Diver'], {}), '(3, Diver)\n', (1352, 1362), False, 'from autocfr.worker import Worker, VecWorker, GroupVecWorker\n'), ((1656, 1670), 'ray.shutdown', 'ray.shutdown', ([], {}), '()\n', (1668, 1670), False, 'import ray\n'), ((1708, 1718), 'ray.init', 'ray.init', ([], {}), '()\n', (1716, 1718), False, 'import ray\n'), ((1736, 1755), 'autocfr.worker.VecWorker', 'VecWorker', (['(2)', 'Diver'], {}), '(2, Diver)\n', (1745, 1755), False, 'from autocfr.worker import Worker, VecWorker, GroupVecWorker\n'), ((2095, 2109), 'ray.shutdown', 'ray.shutdown', ([], {}), '()\n', (2107, 2109), False, 'import ray\n'), ((2139, 2149), 'ray.init', 'ray.init', ([], {}), '()\n', (2147, 2149), False, 'import ray\n'), ((2173, 2207), 'autocfr.worker.GroupVecWorker', 'GroupVecWorker', (['(10)', 'DiverContainer'], {}), '(10, DiverContainer)\n', (2187, 2207), False, 'from autocfr.worker import Worker, VecWorker, GroupVecWorker\n'), ((2784, 2798), 'ray.shutdown', 'ray.shutdown', ([], {}), '()\n', (2796, 2798), False, 'import ray\n'), ((1399, 1433), 'numpy.random.randint', 'np.random.randint', ([], {'low': '(0)', 'high': '(100)'}), '(low=0, high=100)\n', (1416, 1433), True, 'import numpy as np\n'), ((1446, 1480), 'numpy.random.randint', 'np.random.randint', ([], {'low': '(0)', 'high': '(100)'}), '(low=0, high=100)\n', (1463, 1480), True, 'import numpy as np\n'), ((1557, 1573), 'time.sleep', 'time.sleep', (['(0.01)'], {}), '(0.01)\n', (1567, 1573), False, 'import time\n'), ((1807, 1841), 'numpy.random.randint', 'np.random.randint', ([], {'low': '(0)', 'high': '(100)'}), '(low=0, high=100)\n', (1824, 1841), True, 'import numpy as np\n'), ((1854, 1888), 'numpy.random.randint', 'np.random.randint', ([], {'low': '(0)', 'high': '(100)'}), '(low=0, high=100)\n', (1871, 1888), True, 'import numpy as np\n'), ((2551, 2564), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (2561, 2564), False, 'import time\n'), ((406, 419), 'time.sleep', 'time.sleep', (['a'], {}), '(a)\n', (416, 419), False, 'import time\n')]
|
import pennylane as qml
import numpy as np
if __name__ != '__main__':
from . encoder.encoding_circuits import EncodingCircuitsPennylane
from . pqc.parametric_circuits import ParametricCircuitsPennylane
from . measurement.measurement_circuits import MeasurementCircuitsPennylane
class PennylaneQNNCircuit:
def __init__(self, enc = 1, pqc = 1, meas = 1, layers = 1, qubit = 1):
'''
initialize variables
'''
self.enc = enc
self.pqc = pqc
self.meas = meas
self.qubit = qubit
self.layers = layers
self.pqc_builder = ParametricCircuitsPennylane(pqc = self.pqc, qubit = self.qubit, layers = self.layers)
self.enc_builder = EncodingCircuitsPennylane(enc = self.enc, qubit = self.qubit)
self.meas_builder = MeasurementCircuitsPennylane(meas = self.meas, qubit = self.qubit)
def construct_qnn_circuit(self, inputs, weights0, weights1 = 0):
assert len(inputs) <= self.enc_builder.max_inputs_length()
pqc_weights_shape = self.pqc_builder.weigths_shape()
if isinstance(pqc_weights_shape[0], tuple):
assert weights0.shape == pqc_weights_shape[0]
assert weights1.shape == pqc_weights_shape[1]
else:
assert weights0.shape == pqc_weights_shape
self.enc_builder.get_encoder(inputs)
self.pqc_builder.get_pqc(weights0, weights1 = weights1)
return self.meas_builder.get_meas()
if __name__ == '__main__':
from encoder.encoding_circuits import EncodingCircuitsPennylane
from pqc.parametric_circuits import ParametricCircuitsPennylane
from measurement.measurement_circuits import MeasurementCircuitsPennylane
qnn = PennylaneQNNCircuit(enc = 5, qubit = 5, layers = 2, pqc = 19, meas = 3)
input_length = qnn.enc_builder.max_inputs_length()
weight_shape = qnn.pqc_builder.weigths_shape()
inputs = np.random.random(input_length)
dev = qml.device("default.qubit", wires = 10) #target pennylane device
qnode = qml.QNode(qnn.construct_qnn_circuit, dev) #circuit
if isinstance(weight_shape[0], tuple):
weights0 = np.random.random(weight_shape[0])
weights1 = np.random.random(weight_shape[1])
qnode(inputs, weights0, weights1)
else:
weights = np.random.random(weight_shape)
qnode(inputs, weights)
print(qnode.draw())
|
[
"measurement.measurement_circuits.MeasurementCircuitsPennylane",
"pqc.parametric_circuits.ParametricCircuitsPennylane",
"pennylane.device",
"numpy.random.random",
"pennylane.QNode",
"encoder.encoding_circuits.EncodingCircuitsPennylane"
] |
[((1949, 1979), 'numpy.random.random', 'np.random.random', (['input_length'], {}), '(input_length)\n', (1965, 1979), True, 'import numpy as np\n'), ((1991, 2028), 'pennylane.device', 'qml.device', (['"""default.qubit"""'], {'wires': '(10)'}), "('default.qubit', wires=10)\n", (2001, 2028), True, 'import pennylane as qml\n'), ((2069, 2110), 'pennylane.QNode', 'qml.QNode', (['qnn.construct_qnn_circuit', 'dev'], {}), '(qnn.construct_qnn_circuit, dev)\n', (2078, 2110), True, 'import pennylane as qml\n'), ((619, 698), 'pqc.parametric_circuits.ParametricCircuitsPennylane', 'ParametricCircuitsPennylane', ([], {'pqc': 'self.pqc', 'qubit': 'self.qubit', 'layers': 'self.layers'}), '(pqc=self.pqc, qubit=self.qubit, layers=self.layers)\n', (646, 698), False, 'from pqc.parametric_circuits import ParametricCircuitsPennylane\n'), ((733, 790), 'encoder.encoding_circuits.EncodingCircuitsPennylane', 'EncodingCircuitsPennylane', ([], {'enc': 'self.enc', 'qubit': 'self.qubit'}), '(enc=self.enc, qubit=self.qubit)\n', (758, 790), False, 'from encoder.encoding_circuits import EncodingCircuitsPennylane\n'), ((824, 886), 'measurement.measurement_circuits.MeasurementCircuitsPennylane', 'MeasurementCircuitsPennylane', ([], {'meas': 'self.meas', 'qubit': 'self.qubit'}), '(meas=self.meas, qubit=self.qubit)\n', (852, 886), False, 'from measurement.measurement_circuits import MeasurementCircuitsPennylane\n'), ((2184, 2217), 'numpy.random.random', 'np.random.random', (['weight_shape[0]'], {}), '(weight_shape[0])\n', (2200, 2217), True, 'import numpy as np\n'), ((2238, 2271), 'numpy.random.random', 'np.random.random', (['weight_shape[1]'], {}), '(weight_shape[1])\n', (2254, 2271), True, 'import numpy as np\n'), ((2345, 2375), 'numpy.random.random', 'np.random.random', (['weight_shape'], {}), '(weight_shape)\n', (2361, 2375), True, 'import numpy as np\n')]
|
"""
Train a speaker model on R2R
"""
import logging
from typing import List, Tuple, Dict
import copy
import os
import random
import shutil
import sys
from datetime import datetime
from tqdm import tqdm
import numpy as np
import torch
import torch.distributed as dist
import torch.nn.functional as F
from torch import nn
from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, Subset, Dataset
from torch.utils.data.distributed import DistributedSampler
from torch.utils.tensorboard import SummaryWriter
from apex.parallel import DistributedDataParallel as DDP
from transformers import AutoTokenizer, BertTokenizer
from vilbert.optimization import AdamW, WarmupLinearSchedule
from vilbert.vilbert import BertConfig
from airbert import Airbert
from utils.cli import get_parser
from utils.dataset import PanoFeaturesReader
from utils.dataset.speak_dataset import SpeakDataset
logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
datefmt="%m/%d/%Y %H:%M:%S",
level=logging.INFO,
stream=sys.stdout,
)
logger = logging.getLogger(__name__)
Batch = Dict[str, torch.Tensor]
def main():
# ----- #
# setup #
# ----- #
# command line parsing
parser = get_parser(training=True, speaker=True)
args = parser.parse_args()
# FIXME how to do it properly in bash?
args.perturbations = [p for pert in args.perturbations for p in pert.split(" ")]
# validate command line arguments
if not (args.masked_vision or args.masked_language) and args.no_ranking:
parser.error(
"No training objective selected, add --masked_vision, "
"--masked_language, or remove --no_ranking"
)
# set seed
if args.seed:
seed = args.seed
if args.local_rank != -1:
seed += args.local_rank
torch.manual_seed(seed)
np.random.seed(seed) # type: ignore
random.seed(seed)
# get device settings
if args.local_rank == -1:
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
n_gpu = torch.cuda.device_count()
else:
# Initializes the distributed backend which will take care of synchronizing
# nodes/GPUs
torch.cuda.set_device(args.local_rank)
device = torch.device("cuda", args.local_rank)
dist.init_process_group(backend="nccl")
n_gpu = 1
# check if this is the default gpu
default_gpu = True
if args.local_rank != -1 and dist.get_rank() != 0:
default_gpu = False
if default_gpu:
logger.info(f"Playing with {n_gpu} GPUs")
# create output directory
save_folder = os.path.join(args.output_dir, f"run-{args.save_name}")
if default_gpu and not os.path.exists(save_folder):
os.makedirs(save_folder)
# ------------ #
# data loaders #
# ------------ #
tokenizer = AutoTokenizer.from_pretrained(args.bert_tokenizer)
if not isinstance(tokenizer, BertTokenizer):
raise ValueError("fix mypy")
features_reader = PanoFeaturesReader(args.img_feature)
vln_path = f"data/task/{args.prefix}R2R_train.json"
if default_gpu:
logger.info("using provided training trajectories")
logger.info(f"VLN path: {vln_path}")
if default_gpu:
logger.info("Loading train dataset")
train_dataset: Dataset = SpeakDataset(
vln_path=vln_path,
skeleton_path="np_train.json" if args.np else "",
tokenizer=tokenizer,
features_reader=features_reader,
max_instruction_length=args.max_instruction_length,
max_path_length=args.max_path_length,
max_num_boxes=args.max_num_boxes,
default_gpu=default_gpu,
)
if default_gpu:
logger.info("Loading val datasets")
val_seen_dataset = SpeakDataset(
vln_path=f"data/task/{args.prefix}R2R_val_seen.json",
skeleton_path="np_val_seen.json" if args.np else "",
tokenizer=tokenizer,
features_reader=features_reader,
max_instruction_length=args.max_instruction_length,
max_path_length=args.max_path_length,
max_num_boxes=args.max_num_boxes,
default_gpu=default_gpu,
)
val_unseen_dataset = SpeakDataset(
vln_path=f"data/task/{args.prefix}R2R_val_unseen.json",
skeleton_path="np_val_unseen.json" if args.np else "",
tokenizer=tokenizer,
features_reader=features_reader,
max_instruction_length=args.max_instruction_length,
max_path_length=args.max_path_length,
max_num_boxes=args.max_num_boxes,
default_gpu=default_gpu,
)
if args.local_rank == -1:
train_sampler = RandomSampler(train_dataset)
val_seen_sampler = SequentialSampler(val_seen_dataset)
val_unseen_sampler = SequentialSampler(val_unseen_dataset)
else:
train_sampler = DistributedSampler(train_dataset)
val_seen_sampler = DistributedSampler(val_seen_dataset)
val_unseen_sampler = DistributedSampler(val_unseen_dataset)
# adjust the batch size for distributed training
batch_size = args.batch_size // args.gradient_accumulation_steps
if args.local_rank != -1:
batch_size = batch_size // dist.get_world_size()
if default_gpu:
logger.info(f"batch_size: {batch_size}")
if default_gpu:
logger.info(f"Creating dataloader")
# create data loaders
train_data_loader = DataLoader(
train_dataset,
sampler=train_sampler,
batch_size=batch_size,
num_workers=args.num_workers,
pin_memory=True,
)
val_seen_data_loader = DataLoader(
val_seen_dataset,
sampler=val_seen_sampler,
shuffle=False,
batch_size=batch_size,
num_workers=args.num_workers,
pin_memory=True,
)
val_unseen_data_loader = DataLoader(
val_unseen_dataset,
sampler=val_unseen_sampler,
shuffle=False,
batch_size=batch_size,
num_workers=args.num_workers,
pin_memory=True,
)
# ----- #
# model #
# ----- #
if default_gpu:
logger.info(f"Loading model")
config = BertConfig.from_json_file(args.config_file)
config.cat_highlight = args.cat_highlight # type: ignore
config.convert_mask = True # type: ignore
if len(args.from_pretrained) == 0: # hack for catching --from_pretrained ""
model = Airbert(config)
else:
model = Airbert.from_pretrained(
args.from_pretrained, config, default_gpu=default_gpu
)
if default_gpu:
logger.info(
f"number of parameters: {sum(p.numel() for p in model.parameters())}"
)
# move/distribute model to device
model.to(device)
if args.local_rank != -1:
model = DDP(model, delay_allreduce=True)
if default_gpu:
logger.info("using distributed data parallel")
# elif n_gpu > 1:
# model = torch.nn.DataParallel(model) # type: ignore
# if default_gpu:
# logger.info("using data parallel")
# ------------ #
# optimization #
# ------------ #
# set parameter specific weight decay
no_decay = ["bias", "LayerNorm.weight", "LayerNorm.bias"]
optimizer_grouped_parameters = [
{"params": [], "weight_decay": 0.0},
{"params": [], "weight_decay": args.weight_decay},
]
for name, param in model.named_parameters():
if any(nd in name for nd in no_decay):
optimizer_grouped_parameters[0]["params"].append(param)
else:
optimizer_grouped_parameters[1]["params"].append(param)
# optimizer
optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate,)
# calculate learning rate schedule
t_total = (
len(train_data_loader) // args.gradient_accumulation_steps
) * args.num_epochs
warmup_steps = args.warmup_proportion * t_total
adjusted_t_total = warmup_steps + args.cooldown_factor * (t_total - warmup_steps)
scheduler = (
WarmupLinearSchedule(
optimizer,
warmup_steps=warmup_steps,
t_total=adjusted_t_total,
last_epoch=-1,
)
if not args.no_scheduler
else MultiplicativeLR(optimizer, lr_lambda=lambda epoch: 1.0) # type: ignore
)
# --------------- #
# before training #
# --------------- #
# save the parameters
if default_gpu:
with open(os.path.join(save_folder, "config.txt"), "w") as fid:
print(f"{datetime.now()}", file=fid)
print("\n", file=fid)
print(vars(args), file=fid)
print("\n", file=fid)
print(config, file=fid)
# loggers
if default_gpu:
writer = SummaryWriter(
log_dir=os.path.join(save_folder, "logging"), flush_secs=30
)
else:
writer = None
# -------- #
# training #
# -------- #
# run training
if default_gpu:
logger.info("starting training...")
best_seen_success_rate, best_unseen_success_rate = 0, 0
for epoch in range(args.num_epochs):
if default_gpu and args.debug:
logger.info(f"epoch {epoch}")
if args.local_rank > -1:
train_data_loader.sampler.set_epoch(epoch) # type: ignore
# train for one epoch
train_epoch(
epoch,
model,
optimizer,
scheduler,
train_data_loader,
writer,
default_gpu,
args,
)
if default_gpu and args.debug:
logger.info(f"saving the model")
# save the model every epoch
model_path = os.path.join(save_folder, f"pytorch_model_{epoch + 1}.bin")
if default_gpu:
model_state = (
model.module.state_dict() # type: ignore
if hasattr(model, "module")
else model.state_dict()
)
torch.save(
{
"model_state_dict": model_state,
"optimizer_state_dict": optimizer.state_dict(),
"scheduler_state_dict": scheduler.state_dict(),
"epoch": epoch,
},
model_path
)
if default_gpu and args.debug:
logger.info(f"running validation")
# run validation
global_step = (epoch + 1) * len(train_data_loader)
# run validation on the "val seen" split
with torch.no_grad():
seen_success_rate = val_epoch(
epoch,
model,
"val_seen",
val_seen_data_loader,
writer,
default_gpu,
args,
global_step,
)
if default_gpu:
logger.info(
f"[val_seen] epoch: {epoch + 1} success_rate: {seen_success_rate.item():.3f}"
)
# save the model that performs the best on val seen
if seen_success_rate > best_seen_success_rate:
best_seen_success_rate = seen_success_rate
if default_gpu:
best_seen_path = os.path.join(
save_folder, "pytorch_model_best_seen.bin"
)
shutil.copyfile(model_path, best_seen_path) # type: ignore
# run validation on the "val unseen" split
with torch.no_grad():
unseen_success_rate = val_epoch(
epoch,
model,
"val_unseen",
val_unseen_data_loader,
writer,
default_gpu,
args,
global_step,
)
if default_gpu:
logger.info(
f"[val_unseen] epoch: {epoch + 1} success_rate: {unseen_success_rate.item():.3f}"
)
# save the model that performs the best on val unseen
if unseen_success_rate > best_unseen_success_rate:
best_unseen_success_rate = unseen_success_rate
if default_gpu:
best_unseen_path = os.path.join(
save_folder, "pytorch_model_best_unseen.bin"
)
shutil.copyfile(model_path, best_unseen_path)
# -------------- #
# after training #
# -------------- #
if default_gpu:
writer.close()
def rollout(batch: Batch, model: nn.Module, window: int
) :
"""
we split the batch over sequences of $window tokens.
This reduces the burden on memory usage.
"""
# get the model input and output
instruction_length = batch["target_tokens"].shape[1]
batch_size = get_batch_size(batch)
device = get_device(batch)
inputs = get_model_input(batch)
# import ipdb
# ipdb.set_trace()
# B, N
target = get_target(batch) # inputs["instr_tokens"][:, 0]
# B, N, N
pred_mask = get_mask_predictions(batch)
# B, N
pad_or_sep = (batch["target_tokens"] == 102) | (batch["target_tokens"] == 0)
pad_or_sep = pad_or_sep.squeeze(1)
map_loss = torch.tensor(0.).to(device)
map_correct = torch.tensor(0.).to(device)
map_batch_size = torch.tensor(0.).to(device)
for start in range(0, instruction_length, window):
small_inputs = {
key: tensor[:, start: start+ window].flatten(0, 1) for key, tensor in inputs.items()
}
small_target = target[:, start+1:start+window+1].flatten()
output = model(**small_inputs)
# N * W * B
small_mask = pred_mask[:, start : start + window].flatten()
# N * W * B x V
predictions = output[2].view(-1, output[2].shape[-1])
# W * B x V
predictions = predictions[small_mask]
# W x B
instr = predictions.argmax(1).view(batch_size, -1)
# calculate the final loss on non-padding tokens
loss = F.cross_entropy(predictions, small_target, ignore_index=0)
# backward pass
if model.training:
loss.backward()
# calculate accuracy
# remove pad tokens and sep tokens
small_pad = pad_or_sep[0,start+1: start+window+1 ].flatten()
correct = torch.sum(instr.flatten()[small_pad] == small_target[small_pad]).detach().float()
# calculate accumulated stats
map_batch_size += batch_size
map_loss += loss.detach().float()
map_correct += correct.detach().float()
map_loss = torch.true_divide(map_loss.sum(), map_batch_size) # type: ignore
map_correct = torch.true_divide(map_correct.sum(), map_batch_size) # type: ignore
return map_batch_size.float(), map_loss.float(), map_correct.float()
def train_epoch(
epoch, model, optimizer, scheduler, data_loader, writer, default_gpu, args
) -> None:
device = next(model.parameters()).device
model.train()
batch: Batch
for step, batch in enumerate(tqdm(data_loader, disable=False)): # not (default_gpu))):
if step < 78:
continue
# load batch on gpu
batch = {
k: t.cuda(device=device, non_blocking=True) if hasattr(t, "cuda") else t
for k, t in batch.items()
}
batch_size, loss, correct = rollout(batch, model, args.window)
if args.gradient_accumulation_steps > 1:
loss /= args.gradient_accumulation_steps
correct /= args.gradient_accumulation_steps
# write stats to tensorboard
if default_gpu:
global_step = step + epoch * len(data_loader)
writer.add_scalar("loss/train", loss.float(), global_step=global_step)
writer.add_scalar(
"accuracy/train",
correct.float(),
global_step=global_step,
)
writer.add_scalar(
"learning_rate/train", scheduler.get_lr()[0], global_step=global_step
)
if args.local_rank != -1:
world_size = float(dist.get_world_size())
loss /= world_size
dist.all_reduce(loss, op=dist.ReduceOp.SUM)
dist.all_reduce(correct, op=dist.ReduceOp.SUM)
dist.all_reduce(batch_size, op=dist.ReduceOp.SUM)
if default_gpu and args.debug:
logger.info(
f"[train] step: {step + 1} "
f"loss: {loss:0.2f} "
f"accuracy: {correct / batch_size:0.2f} "
f"lr: {scheduler.get_lr()[0]:0.1e}"
)
if (step + 1) % args.gradient_accumulation_steps == 0:
optimizer.step()
scheduler.step()
model.zero_grad()
def val_epoch(epoch: int, model, tag, data_loader, writer, default_gpu, args, global_step):
device = next(model.parameters()).device
# validation
model.eval()
stats = torch.zeros(3, device=device).float()
for step, batch in enumerate(data_loader):
# load batch on gpu
batch = {
k: t.cuda(device=device, non_blocking=True) if hasattr(t, "cuda") else t
for k, t in batch.items()
}
# get the model output
batch_size, loss, correct = rollout(batch, model, args.window)
# accumulate
stats[0] += loss
stats[1] += correct
stats[2] += batch_size
if default_gpu and args.debug:
logger.info(
f"[{tag}] step: {step + 1} "
f"running loss: {stats[0] / stats[2]:0.2f} "
f"running success rate: {stats[1] / stats[2]:0.2f}"
)
if args.local_rank != -1:
dist.all_reduce(stats, op=dist.ReduceOp.SUM)
# write stats to tensorboard
if default_gpu:
writer.add_scalar(
f"loss/vce_{tag}", stats[0] / stats[2], global_step=global_step
)
writer.add_scalar(
f"accuracy/sr_{tag}", stats[1] / stats[2], global_step=global_step
)
return stats[1] / stats[2]
# ------------- #
# batch parsing #
# ------------- #
# batch format:
# 1:image_features, 2:image_locations, 3:image_mask,
# 5:image_targets_mask, 6:instr_tokens, 7:instr_mask, 8:instr_targets, 9:instr_highlights, 10:segment_ids,
# 11:co_attention_mask, 12:item_id
def get_instr_length(batch: Batch):
return batch["instr_tokens"].shape[1]
def get_instr_mask(batch: Batch) -> torch.Tensor:
return batch["instr_mask"].squeeze(1)
def get_model_input(batch: Batch) -> Dict[str, torch.Tensor]:
batch_size = get_batch_size(batch)
num_tokens = get_instr_length(batch)
# duplicate for each word token
image_features = batch["image_features"].unsqueeze(1).repeat(1, num_tokens - 1, 1, 1)
image_locations = batch["image_boxes"].unsqueeze(1).repeat(1, num_tokens - 1, 1, 1)
image_mask = batch["image_masks"].unsqueeze(1).repeat(1, num_tokens - 1, 1)
instr_tokens = batch["instr_tokens"].unsqueeze(1).repeat(1, num_tokens - 1, 1)
segment_ids = batch["segment_ids"].unsqueeze(1).repeat(1, num_tokens - 1, 1)
instr_mask = batch["instr_mask"].unsqueeze(1).repeat(1, num_tokens - 1, 1)
# create triangular masks
tri = (
torch.ones((num_tokens - 1, num_tokens))
.tril(0)
.bool()
.repeat(batch_size, 1, 1)
. transpose(0, 1)
.reshape(-1, num_tokens)
.to(instr_mask.device)
)
instr_mask = torch.logical_and(instr_mask, tri) # type: ignore
# transform batch shape
co_attention_mask = batch["co_attention_mask"].view(
-1, batch["co_attention_mask"].size(2), batch["co_attention_mask"].size(3)
)
return {
"instr_tokens": instr_tokens,
"image_features": image_features,
"image_locations": image_locations,
"token_type_ids": segment_ids,
"attention_mask": instr_mask,
"image_attention_mask": image_mask,
"co_attention_mask": co_attention_mask,
}
def get_batch_size(batch: Batch):
return batch["instr_tokens"].shape[0]
def get_target(batch: Batch) -> torch.Tensor:
return batch["target_tokens"]
def get_device(batch: Batch):
return batch["instr_tokens"].device
def get_mask_predictions(batch: Batch) -> torch.Tensor:
target_length = batch["target_tokens"].shape[1]
instruction_length = get_instr_length(batch) - target_length
batch_size = get_batch_size(batch)
device = get_device(batch)
diag = torch.diag(torch.tensor([1] * instruction_length), diagonal=target_length).bool().to(device)
diag = diag[:-target_length]
diag[-1] = 0
diag = diag.repeat(batch_size, 1, 1)
return diag
if __name__ == "__main__":
main()
|
[
"numpy.random.seed",
"torch.utils.data.RandomSampler",
"torch.cuda.device_count",
"torch.distributed.get_world_size",
"torch.device",
"torch.no_grad",
"os.path.join",
"torch.ones",
"torch.utils.data.DataLoader",
"torch.distributed.get_rank",
"os.path.exists",
"vilbert.optimization.WarmupLinearSchedule",
"torch.utils.data.distributed.DistributedSampler",
"random.seed",
"torch.utils.data.SequentialSampler",
"vilbert.vilbert.BertConfig.from_json_file",
"torch.cuda.set_device",
"torch.zeros",
"shutil.copyfile",
"utils.dataset.PanoFeaturesReader",
"datetime.datetime.now",
"airbert.Airbert.from_pretrained",
"tqdm.tqdm",
"vilbert.optimization.AdamW",
"torch.manual_seed",
"torch.nn.functional.cross_entropy",
"transformers.AutoTokenizer.from_pretrained",
"torch.cuda.is_available",
"apex.parallel.DistributedDataParallel",
"airbert.Airbert",
"utils.cli.get_parser",
"torch.distributed.all_reduce",
"torch.distributed.init_process_group",
"utils.dataset.speak_dataset.SpeakDataset",
"logging.basicConfig",
"os.makedirs",
"torch.tensor",
"logging.getLogger",
"torch.logical_and"
] |
[((892, 1054), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)s - %(levelname)s - %(name)s - %(message)s"""', 'datefmt': '"""%m/%d/%Y %H:%M:%S"""', 'level': 'logging.INFO', 'stream': 'sys.stdout'}), "(format=\n '%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt=\n '%m/%d/%Y %H:%M:%S', level=logging.INFO, stream=sys.stdout)\n", (911, 1054), False, 'import logging\n'), ((1073, 1100), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1090, 1100), False, 'import logging\n'), ((1230, 1269), 'utils.cli.get_parser', 'get_parser', ([], {'training': '(True)', 'speaker': '(True)'}), '(training=True, speaker=True)\n', (1240, 1269), False, 'from utils.cli import get_parser\n'), ((2657, 2711), 'os.path.join', 'os.path.join', (['args.output_dir', 'f"""run-{args.save_name}"""'], {}), "(args.output_dir, f'run-{args.save_name}')\n", (2669, 2711), False, 'import os\n'), ((2882, 2932), 'transformers.AutoTokenizer.from_pretrained', 'AutoTokenizer.from_pretrained', (['args.bert_tokenizer'], {}), '(args.bert_tokenizer)\n', (2911, 2932), False, 'from transformers import AutoTokenizer, BertTokenizer\n'), ((3041, 3077), 'utils.dataset.PanoFeaturesReader', 'PanoFeaturesReader', (['args.img_feature'], {}), '(args.img_feature)\n', (3059, 3077), False, 'from utils.dataset import PanoFeaturesReader\n'), ((3356, 3658), 'utils.dataset.speak_dataset.SpeakDataset', 'SpeakDataset', ([], {'vln_path': 'vln_path', 'skeleton_path': "('np_train.json' if args.np else '')", 'tokenizer': 'tokenizer', 'features_reader': 'features_reader', 'max_instruction_length': 'args.max_instruction_length', 'max_path_length': 'args.max_path_length', 'max_num_boxes': 'args.max_num_boxes', 'default_gpu': 'default_gpu'}), "(vln_path=vln_path, skeleton_path='np_train.json' if args.np else\n '', tokenizer=tokenizer, features_reader=features_reader,\n max_instruction_length=args.max_instruction_length, max_path_length=\n args.max_path_length, max_num_boxes=args.max_num_boxes, default_gpu=\n default_gpu)\n", (3368, 3658), False, 'from utils.dataset.speak_dataset import SpeakDataset\n'), ((3801, 4141), 'utils.dataset.speak_dataset.SpeakDataset', 'SpeakDataset', ([], {'vln_path': 'f"""data/task/{args.prefix}R2R_val_seen.json"""', 'skeleton_path': "('np_val_seen.json' if args.np else '')", 'tokenizer': 'tokenizer', 'features_reader': 'features_reader', 'max_instruction_length': 'args.max_instruction_length', 'max_path_length': 'args.max_path_length', 'max_num_boxes': 'args.max_num_boxes', 'default_gpu': 'default_gpu'}), "(vln_path=f'data/task/{args.prefix}R2R_val_seen.json',\n skeleton_path='np_val_seen.json' if args.np else '', tokenizer=\n tokenizer, features_reader=features_reader, max_instruction_length=args\n .max_instruction_length, max_path_length=args.max_path_length,\n max_num_boxes=args.max_num_boxes, default_gpu=default_gpu)\n", (3813, 4141), False, 'from utils.dataset.speak_dataset import SpeakDataset\n'), ((4221, 4565), 'utils.dataset.speak_dataset.SpeakDataset', 'SpeakDataset', ([], {'vln_path': 'f"""data/task/{args.prefix}R2R_val_unseen.json"""', 'skeleton_path': "('np_val_unseen.json' if args.np else '')", 'tokenizer': 'tokenizer', 'features_reader': 'features_reader', 'max_instruction_length': 'args.max_instruction_length', 'max_path_length': 'args.max_path_length', 'max_num_boxes': 'args.max_num_boxes', 'default_gpu': 'default_gpu'}), "(vln_path=f'data/task/{args.prefix}R2R_val_unseen.json',\n skeleton_path='np_val_unseen.json' if args.np else '', tokenizer=\n tokenizer, features_reader=features_reader, max_instruction_length=args\n .max_instruction_length, max_path_length=args.max_path_length,\n max_num_boxes=args.max_num_boxes, default_gpu=default_gpu)\n", (4233, 4565), False, 'from utils.dataset.speak_dataset import SpeakDataset\n'), ((5428, 5550), 'torch.utils.data.DataLoader', 'DataLoader', (['train_dataset'], {'sampler': 'train_sampler', 'batch_size': 'batch_size', 'num_workers': 'args.num_workers', 'pin_memory': '(True)'}), '(train_dataset, sampler=train_sampler, batch_size=batch_size,\n num_workers=args.num_workers, pin_memory=True)\n', (5438, 5550), False, 'from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, Subset, Dataset\n'), ((5621, 5764), 'torch.utils.data.DataLoader', 'DataLoader', (['val_seen_dataset'], {'sampler': 'val_seen_sampler', 'shuffle': '(False)', 'batch_size': 'batch_size', 'num_workers': 'args.num_workers', 'pin_memory': '(True)'}), '(val_seen_dataset, sampler=val_seen_sampler, shuffle=False,\n batch_size=batch_size, num_workers=args.num_workers, pin_memory=True)\n', (5631, 5764), False, 'from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, Subset, Dataset\n'), ((5845, 5992), 'torch.utils.data.DataLoader', 'DataLoader', (['val_unseen_dataset'], {'sampler': 'val_unseen_sampler', 'shuffle': '(False)', 'batch_size': 'batch_size', 'num_workers': 'args.num_workers', 'pin_memory': '(True)'}), '(val_unseen_dataset, sampler=val_unseen_sampler, shuffle=False,\n batch_size=batch_size, num_workers=args.num_workers, pin_memory=True)\n', (5855, 5992), False, 'from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, Subset, Dataset\n'), ((6159, 6202), 'vilbert.vilbert.BertConfig.from_json_file', 'BertConfig.from_json_file', (['args.config_file'], {}), '(args.config_file)\n', (6184, 6202), False, 'from vilbert.vilbert import BertConfig\n'), ((7661, 7719), 'vilbert.optimization.AdamW', 'AdamW', (['optimizer_grouped_parameters'], {'lr': 'args.learning_rate'}), '(optimizer_grouped_parameters, lr=args.learning_rate)\n', (7666, 7719), False, 'from vilbert.optimization import AdamW, WarmupLinearSchedule\n'), ((19405, 19439), 'torch.logical_and', 'torch.logical_and', (['instr_mask', 'tri'], {}), '(instr_mask, tri)\n', (19422, 19439), False, 'import torch\n'), ((1838, 1861), 'torch.manual_seed', 'torch.manual_seed', (['seed'], {}), '(seed)\n', (1855, 1861), False, 'import torch\n'), ((1870, 1890), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (1884, 1890), True, 'import numpy as np\n'), ((1914, 1931), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (1925, 1931), False, 'import random\n'), ((2083, 2108), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\n', (2106, 2108), False, 'import torch\n'), ((2232, 2270), 'torch.cuda.set_device', 'torch.cuda.set_device', (['args.local_rank'], {}), '(args.local_rank)\n', (2253, 2270), False, 'import torch\n'), ((2288, 2325), 'torch.device', 'torch.device', (['"""cuda"""', 'args.local_rank'], {}), "('cuda', args.local_rank)\n", (2300, 2325), False, 'import torch\n'), ((2334, 2373), 'torch.distributed.init_process_group', 'dist.init_process_group', ([], {'backend': '"""nccl"""'}), "(backend='nccl')\n", (2357, 2373), True, 'import torch.distributed as dist\n'), ((2776, 2800), 'os.makedirs', 'os.makedirs', (['save_folder'], {}), '(save_folder)\n', (2787, 2800), False, 'import os\n'), ((4674, 4702), 'torch.utils.data.RandomSampler', 'RandomSampler', (['train_dataset'], {}), '(train_dataset)\n', (4687, 4702), False, 'from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, Subset, Dataset\n'), ((4730, 4765), 'torch.utils.data.SequentialSampler', 'SequentialSampler', (['val_seen_dataset'], {}), '(val_seen_dataset)\n', (4747, 4765), False, 'from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, Subset, Dataset\n'), ((4795, 4832), 'torch.utils.data.SequentialSampler', 'SequentialSampler', (['val_unseen_dataset'], {}), '(val_unseen_dataset)\n', (4812, 4832), False, 'from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, Subset, Dataset\n'), ((4867, 4900), 'torch.utils.data.distributed.DistributedSampler', 'DistributedSampler', (['train_dataset'], {}), '(train_dataset)\n', (4885, 4900), False, 'from torch.utils.data.distributed import DistributedSampler\n'), ((4928, 4964), 'torch.utils.data.distributed.DistributedSampler', 'DistributedSampler', (['val_seen_dataset'], {}), '(val_seen_dataset)\n', (4946, 4964), False, 'from torch.utils.data.distributed import DistributedSampler\n'), ((4994, 5032), 'torch.utils.data.distributed.DistributedSampler', 'DistributedSampler', (['val_unseen_dataset'], {}), '(val_unseen_dataset)\n', (5012, 5032), False, 'from torch.utils.data.distributed import DistributedSampler\n'), ((6408, 6423), 'airbert.Airbert', 'Airbert', (['config'], {}), '(config)\n', (6415, 6423), False, 'from airbert import Airbert\n'), ((6450, 6528), 'airbert.Airbert.from_pretrained', 'Airbert.from_pretrained', (['args.from_pretrained', 'config'], {'default_gpu': 'default_gpu'}), '(args.from_pretrained, config, default_gpu=default_gpu)\n', (6473, 6528), False, 'from airbert import Airbert\n'), ((6791, 6823), 'apex.parallel.DistributedDataParallel', 'DDP', (['model'], {'delay_allreduce': '(True)'}), '(model, delay_allreduce=True)\n', (6794, 6823), True, 'from apex.parallel import DistributedDataParallel as DDP\n'), ((8032, 8136), 'vilbert.optimization.WarmupLinearSchedule', 'WarmupLinearSchedule', (['optimizer'], {'warmup_steps': 'warmup_steps', 't_total': 'adjusted_t_total', 'last_epoch': '(-1)'}), '(optimizer, warmup_steps=warmup_steps, t_total=\n adjusted_t_total, last_epoch=-1)\n', (8052, 8136), False, 'from vilbert.optimization import AdamW, WarmupLinearSchedule\n'), ((9687, 9746), 'os.path.join', 'os.path.join', (['save_folder', 'f"""pytorch_model_{epoch + 1}.bin"""'], {}), "(save_folder, f'pytorch_model_{epoch + 1}.bin')\n", (9699, 9746), False, 'import os\n'), ((13960, 14018), 'torch.nn.functional.cross_entropy', 'F.cross_entropy', (['predictions', 'small_target'], {'ignore_index': '(0)'}), '(predictions, small_target, ignore_index=0)\n', (13975, 14018), True, 'import torch.nn.functional as F\n'), ((14970, 15002), 'tqdm.tqdm', 'tqdm', (['data_loader'], {'disable': '(False)'}), '(data_loader, disable=False)\n', (14974, 15002), False, 'from tqdm import tqdm\n'), ((17648, 17692), 'torch.distributed.all_reduce', 'dist.all_reduce', (['stats'], {'op': 'dist.ReduceOp.SUM'}), '(stats, op=dist.ReduceOp.SUM)\n', (17663, 17692), True, 'import torch.distributed as dist\n'), ((2488, 2503), 'torch.distributed.get_rank', 'dist.get_rank', ([], {}), '()\n', (2501, 2503), True, 'import torch.distributed as dist\n'), ((2739, 2766), 'os.path.exists', 'os.path.exists', (['save_folder'], {}), '(save_folder)\n', (2753, 2766), False, 'import os\n'), ((5221, 5242), 'torch.distributed.get_world_size', 'dist.get_world_size', ([], {}), '()\n', (5240, 5242), True, 'import torch.distributed as dist\n'), ((10520, 10535), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (10533, 10535), False, 'import torch\n'), ((11450, 11465), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (11463, 11465), False, 'import torch\n'), ((13147, 13164), 'torch.tensor', 'torch.tensor', (['(0.0)'], {}), '(0.0)\n', (13159, 13164), False, 'import torch\n'), ((13193, 13210), 'torch.tensor', 'torch.tensor', (['(0.0)'], {}), '(0.0)\n', (13205, 13210), False, 'import torch\n'), ((13243, 13260), 'torch.tensor', 'torch.tensor', (['(0.0)'], {}), '(0.0)\n', (13255, 13260), False, 'import torch\n'), ((16105, 16148), 'torch.distributed.all_reduce', 'dist.all_reduce', (['loss'], {'op': 'dist.ReduceOp.SUM'}), '(loss, op=dist.ReduceOp.SUM)\n', (16120, 16148), True, 'import torch.distributed as dist\n'), ((16161, 16207), 'torch.distributed.all_reduce', 'dist.all_reduce', (['correct'], {'op': 'dist.ReduceOp.SUM'}), '(correct, op=dist.ReduceOp.SUM)\n', (16176, 16207), True, 'import torch.distributed as dist\n'), ((16220, 16269), 'torch.distributed.all_reduce', 'dist.all_reduce', (['batch_size'], {'op': 'dist.ReduceOp.SUM'}), '(batch_size, op=dist.ReduceOp.SUM)\n', (16235, 16269), True, 'import torch.distributed as dist\n'), ((16879, 16908), 'torch.zeros', 'torch.zeros', (['(3)'], {'device': 'device'}), '(3, device=device)\n', (16890, 16908), False, 'import torch\n'), ((2029, 2054), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (2052, 2054), False, 'import torch\n'), ((8453, 8492), 'os.path.join', 'os.path.join', (['save_folder', '"""config.txt"""'], {}), "(save_folder, 'config.txt')\n", (8465, 8492), False, 'import os\n'), ((8787, 8823), 'os.path.join', 'os.path.join', (['save_folder', '"""logging"""'], {}), "(save_folder, 'logging')\n", (8799, 8823), False, 'import os\n'), ((11215, 11271), 'os.path.join', 'os.path.join', (['save_folder', '"""pytorch_model_best_seen.bin"""'], {}), "(save_folder, 'pytorch_model_best_seen.bin')\n", (11227, 11271), False, 'import os\n'), ((11326, 11369), 'shutil.copyfile', 'shutil.copyfile', (['model_path', 'best_seen_path'], {}), '(model_path, best_seen_path)\n', (11341, 11369), False, 'import shutil\n'), ((12167, 12225), 'os.path.join', 'os.path.join', (['save_folder', '"""pytorch_model_best_unseen.bin"""'], {}), "(save_folder, 'pytorch_model_best_unseen.bin')\n", (12179, 12225), False, 'import os\n'), ((12280, 12325), 'shutil.copyfile', 'shutil.copyfile', (['model_path', 'best_unseen_path'], {}), '(model_path, best_unseen_path)\n', (12295, 12325), False, 'import shutil\n'), ((16039, 16060), 'torch.distributed.get_world_size', 'dist.get_world_size', ([], {}), '()\n', (16058, 16060), True, 'import torch.distributed as dist\n'), ((8528, 8542), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (8540, 8542), False, 'from datetime import datetime\n'), ((20470, 20508), 'torch.tensor', 'torch.tensor', (['([1] * instruction_length)'], {}), '([1] * instruction_length)\n', (20482, 20508), False, 'import torch\n'), ((19183, 19223), 'torch.ones', 'torch.ones', (['(num_tokens - 1, num_tokens)'], {}), '((num_tokens - 1, num_tokens))\n', (19193, 19223), False, 'import torch\n')]
|
"""
5_costsTester.py
Created by <NAME> at 18/02/2021, University of Milano-Bicocca.
(<EMAIL>)
All rights reserved.
This file is part of the EcoFin-Library (https://github.com/LucaCamerani/EcoFin-Library),
and is released under the "BSD Open Source License".
"""
"""
4_portfolioTester.py
Created by <NAME> at 10/02/2021, University of Milano-Bicocca.
(<EMAIL>)
All rights reserved.
This file is part of the EcoFin-Library (https://github.com/LucaCamerani/EcoFin-Library),
and is released under the "BSD Open Source License".
"""
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from tqdm import tqdm
from EcoFin.assetAllocation.performance import Performance
from EcoFin.utils import utils
from EcoFin.assetAllocation.allocation import Allocation
# -------------------------[Set-up]-------------------------
ticker_list = [line.rstrip('\n') for line in open(r'../INDEXs/DJIA.txt')]
maturity_min = 15
base_path = r'../Export/BackTest_C'
start_date = 0
# Strategy set-up
direction = 'OPS_[OI]' # Direction driver
force = 'VIX_[CBOE]' # In None, don't use force driver
polarize = True # True or False: polarize direction component
# Portfolio set-up
buy_only = False # Set a buy only strategy that ignore negative signals
w_limit = None # Ranks best N ticker based on strategy
w_equally = False # Equally weighted mode
leverage = None # Strategy leverage (1 is no leverage, None is auto-compensation)
# Transaction costs
tc = 8 # unit in basis points
# ----------------------------------------------------------
base = ['SpotPrice']
data = {b: {} for b in base + [direction, force]}
if None in data.keys():
del data[None]
for tick in tqdm(ticker_list, desc='Importing data'):
try:
# Import data and clean-up
source = pd.read_excel(r'{}/{}/backTest_[{}].xlsx'.format(base_path, tick, maturity_min), engine='openpyxl')
source = source.loc[source['Date'] >= start_date, ~source.columns.str.contains('^Unnamed')]
source.set_index(pd.to_datetime(source['Date'], format='%Y%m%d'), drop=True, inplace=True)
for driver in data.keys():
data[driver][tick] = source[driver]
except:
pass
# Merge (concatenate) data and create dataframes
for driver in data.keys():
data[driver] = pd.concat(data[driver], axis=1)
# ❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌[Normalize direction data]❌❌❌❌❌❌❌❌❌❌❌
if driver == direction:
data[driver] = data[driver].sub(data[driver].mean(axis=1), axis=0)
# ❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌❌
# Generate strategy signals
# -----------------------------------[STRATEGY SET-UP]-----------------------------------
if polarize: #
data[direction] = utils.polarizeTable(data[direction]) #
#
if force is None: #
force_v = 1 #
else: #
force_v = data[force] #
#
data['signals'] = data[direction] * force_v #
# -----------------------------------[STRATEGY SET-UP]-----------------------------------
# =====================================================================================
# FROM HERE NO 'signals data' MANIPULATION
# =====================================================================================
# [1] Compute ln-returns of benchmark
data['lnReturns'] = np.log(data['SpotPrice'].shift(-1) / data['SpotPrice'])
# [2] Compute strategy weights
allocation = Allocation(data['signals'], buyOnly=buy_only, limit=w_limit)
if w_equally:
data['weights'] = allocation.getEquallyWeights()
else:
data['weights'] = allocation.getSignalWeights()
# [3] Compute strategy ln-returns
if leverage is None:
leverage = data['SpotPrice'].shape[1]
data['strategy'] = data['lnReturns'] * data['weights'] * leverage
# Compute turnover and transaction costs
turnover = allocation.getTurnover(data['weights'])
data['costs'] = np.log(turnover.byTime * 2 * (tc/1e4) + 1)
data['strategy_net'] = data['strategy'].mean(axis=1) - data['costs']
# =====================================================================================
# FROM HERE NO DATA MANIPULATION
# =====================================================================================
# Create plot framework
fig, axs = plt.subplots(2, figsize=(15, 8), sharex=True)
fig.suptitle('Strategy tester', fontsize=16)
# Plot strategy return vs. benchmark (data)
axs[0].set_title('data returns')
axs[0].plot(data['lnReturns'].mean(axis=1).cumsum(), linestyle='dotted', label='Benchmark')
axs[0].plot(data['strategy'].mean(axis=1).cumsum(), label='Strategy Gross')
axs[0].plot(data['strategy_net'].cumsum(), label='Strategy Net')
axs[0].set(ylabel='Cumulated ln-returns ($X_t$)')
axs[0].legend()
# Plot transaction costs
ax2 = axs[0].twinx()
color = 'tab:gray'
ax2.set_ylabel('Transaction Costs', color=color)
ax2.fill_between(data['costs'].index, 0, data['costs'], linewidth=.5, alpha=.2, color=color)
ax2.plot(data['costs'], linewidth=.5, alpha=.6, color=color)
ax2.set_ylim([0, data['costs'].max() * 4])
ax2.tick_params(axis='y', labelcolor=color)
# Plot evolution of weights
axs[1].set_title('Transition costs')
axs[1].plot(turnover.byTime, color='gold', label=r'Turnover ($\gamma$)')
axs[1].axhline(turnover.mean, alpha=.6, linestyle='--', label=r'mean')
axs[1].legend()
plt.show()
|
[
"EcoFin.utils.utils.polarizeTable",
"tqdm.tqdm",
"matplotlib.pyplot.show",
"numpy.log",
"EcoFin.assetAllocation.allocation.Allocation",
"pandas.to_datetime",
"matplotlib.pyplot.subplots",
"pandas.concat"
] |
[((1762, 1802), 'tqdm.tqdm', 'tqdm', (['ticker_list'], {'desc': '"""Importing data"""'}), "(ticker_list, desc='Importing data')\n", (1766, 1802), False, 'from tqdm import tqdm\n'), ((4040, 4100), 'EcoFin.assetAllocation.allocation.Allocation', 'Allocation', (["data['signals']"], {'buyOnly': 'buy_only', 'limit': 'w_limit'}), "(data['signals'], buyOnly=buy_only, limit=w_limit)\n", (4050, 4100), False, 'from EcoFin.assetAllocation.allocation import Allocation\n'), ((4499, 4547), 'numpy.log', 'np.log', (['(turnover.byTime * 2 * (tc / 10000.0) + 1)'], {}), '(turnover.byTime * 2 * (tc / 10000.0) + 1)\n', (4505, 4547), True, 'import numpy as np\n'), ((4879, 4924), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)'], {'figsize': '(15, 8)', 'sharex': '(True)'}), '(2, figsize=(15, 8), sharex=True)\n', (4891, 4924), True, 'import matplotlib.pyplot as plt\n'), ((5930, 5940), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5938, 5940), True, 'import matplotlib.pyplot as plt\n'), ((2369, 2400), 'pandas.concat', 'pd.concat', (['data[driver]'], {'axis': '(1)'}), '(data[driver], axis=1)\n', (2378, 2400), True, 'import pandas as pd\n'), ((2850, 2886), 'EcoFin.utils.utils.polarizeTable', 'utils.polarizeTable', (['data[direction]'], {}), '(data[direction])\n', (2869, 2886), False, 'from EcoFin.utils import utils\n'), ((2090, 2137), 'pandas.to_datetime', 'pd.to_datetime', (["source['Date']"], {'format': '"""%Y%m%d"""'}), "(source['Date'], format='%Y%m%d')\n", (2104, 2137), True, 'import pandas as pd\n')]
|
# -*- coding: utf-8 -*-
import numpy as np
import chainer
from chainer import cuda, Function, Variable
from chainer import Link, Chain, ChainList
import chainer.functions as F
import chainer.links as L
from src.lib.loss import softmax_dice_loss
class Model_L2(Chain):
def __init__(
self,
ndim=3,
n_class=2,
init_channel=2,
kernel_size=3,
pool_size=2,
ap_factor=2,
gpu=-1,
class_weight=np.array([1, 1]).astype(np.float32),
loss_func='F.softmax_cross_entropy'
):
self.gpu = gpu
self.pool_size = pool_size
if gpu >= 0:
self.class_weight = cuda.to_gpu(np.array(class_weight).astype(np.float32))
else:
self.class_weight = np.array(class_weight).astype(np.float32)
self.train = True
self.loss_func = loss_func
initializer = chainer.initializers.HeNormal()
super(Model_L2, self).__init__(
c0=L.ConvolutionND(ndim, 1, init_channel, kernel_size, 1, int(kernel_size/2), initialW=initializer, initial_bias=None),
c1=L.ConvolutionND(ndim, init_channel, int(init_channel * (ap_factor ** 1)), kernel_size, 1, int(kernel_size/2), initialW=initializer, initial_bias=None),
c2=L.ConvolutionND(ndim, int(init_channel * (ap_factor ** 1)), int(init_channel * (ap_factor ** 1)), kernel_size, 1, int(kernel_size/2), initialW=initializer, initial_bias=None),
c3=L.ConvolutionND(ndim, int(init_channel * (ap_factor ** 1)), int(init_channel * (ap_factor ** 2)), kernel_size, 1, int(kernel_size/2), initialW=initializer, initial_bias=None),
c4=L.ConvolutionND(ndim, int(init_channel * (ap_factor ** 2)), int(init_channel * (ap_factor ** 2)), kernel_size, 1, int(kernel_size/2), initialW=initializer, initial_bias=None),
c5=L.ConvolutionND(ndim, int(init_channel * (ap_factor ** 2)), int(init_channel * (ap_factor ** 3)), kernel_size, 1, int(kernel_size/2), initialW=initializer, initial_bias=None),
dc0=L.DeconvolutionND(ndim, int(init_channel * (ap_factor ** 3)), int(init_channel * (ap_factor ** 3)), self.pool_size, self.pool_size, 0, initialW=initializer, initial_bias=None),
dc1=L.ConvolutionND(ndim, int(init_channel * (ap_factor ** 2) + init_channel * (ap_factor ** 3)), int(init_channel * (ap_factor ** 2)), kernel_size, 1, int(kernel_size/2), initialW=initializer, initial_bias=None),
dc2=L.ConvolutionND(ndim, int(init_channel * (ap_factor ** 2)), int(init_channel * (ap_factor ** 2)), kernel_size, 1, int(kernel_size/2), initialW=initializer, initial_bias=None),
dc3=L.DeconvolutionND(ndim, int(init_channel * (ap_factor ** 2)), int(init_channel * (ap_factor ** 2)), self.pool_size, self.pool_size, 0, initialW=initializer, initial_bias=None),
dc4=L.ConvolutionND(ndim, int(init_channel * (ap_factor ** 1) + init_channel * (ap_factor ** 2)), int(init_channel * (ap_factor ** 1)), kernel_size, 1, int(kernel_size/2), initialW=initializer, initial_bias=None),
dc5=L.ConvolutionND(ndim, int(init_channel * (ap_factor ** 1)), int(init_channel * (ap_factor ** 1)), kernel_size, 1, int(kernel_size/2), initialW=initializer, initial_bias=None),
dc6=L.ConvolutionND(ndim, int(init_channel * (ap_factor ** 1)), n_class, 1, 1, initialW=initializer, initial_bias=None),
bnc0=L.BatchNormalization(init_channel),
bnc1=L.BatchNormalization(int(init_channel * (ap_factor ** 1))),
bnc2=L.BatchNormalization(int(init_channel * (ap_factor ** 1))),
bnc3=L.BatchNormalization(int(init_channel * (ap_factor ** 2))),
bnc4=L.BatchNormalization(int(init_channel * (ap_factor ** 2))),
bnc5=L.BatchNormalization(int(init_channel * (ap_factor ** 3))),
bndc1=L.BatchNormalization(int(init_channel * (ap_factor ** 2))),
bndc2=L.BatchNormalization(int(init_channel * (ap_factor ** 2))),
bndc4=L.BatchNormalization(int(init_channel * (ap_factor ** 1))),
bndc5=L.BatchNormalization(int(init_channel * (ap_factor ** 1)))
)
def _calc(self, x):
e0 = F.relu(self.bnc0(self.c0(x)))
syn0 = F.relu(self.bnc1(self.c1(e0)))
del e0
e1 = F.max_pooling_nd(syn0, self.pool_size, self.pool_size)
e2 = F.relu(self.bnc2(self.c2(e1)))
syn1 = F.relu(self.bnc3(self.c3(e2)))
del e1, e2
e3 = F.max_pooling_nd(syn1, self.pool_size, self.pool_size)
e4 = F.relu(self.bnc4(self.c4(e3)))
e5 = F.relu(self.bnc5(self.c5(e4)))
del e3, e4
d0 = F.concat([self.dc0(e5), syn1])
del e5, syn1
d1 = F.relu(self.bndc1(self.dc1(d0)))
d2 = F.relu(self.bndc2(self.dc2(d1)))
del d0, d1
d3 = F.concat([self.dc3(d2), syn0])
del d2, syn0
d4 = F.relu(self.bndc4(self.dc4(d3)))
d5 = F.relu(self.bndc5(self.dc5(d4)))
del d3, d4
d6 = self.dc6(d5)
del d5
return d6
def __call__(self, x, t=None, seg=True):
h = self._calc(x)
if seg:
pred = F.softmax(h)
del h
return pred.data
else:
#loss = eval(self.loss_func)(h, t, class_weight=self.class_weight)
loss = eval(self.loss_func)(h, t)
pred = F.softmax(h)
del h
return loss, pred.data
class Model_L3(Chain):
def __init__(
self,
ndim=3,
n_class=2,
init_channel=2,
kernel_size=3,
pool_size=2,
ap_factor=2,
gpu=-1,
class_weight=np.array([1, 1]).astype(np.float32),
loss_func='F.softmax_cross_entropy'
):
self.gpu = gpu
self.pool_size = pool_size
if gpu >= 0:
self.class_weight = cuda.to_gpu(np.array(class_weight).astype(np.float32))
else:
self.class_weight = np.array(class_weight).astype(np.float32)
self.train = True
self.loss_func = loss_func
initializer = chainer.initializers.HeNormal()
super(Model_L3, self).__init__(
c0=L.ConvolutionND(ndim, 1, init_channel, kernel_size, 1, int(kernel_size/2), initialW=initializer, initial_bias=None),
c1=L.ConvolutionND(ndim, init_channel, int(init_channel * (ap_factor ** 1)), kernel_size, 1, int(kernel_size/2), initialW=initializer, initial_bias=None),
c2=L.ConvolutionND(ndim, int(init_channel * (ap_factor ** 1)), int(init_channel * (ap_factor ** 1)), kernel_size, 1, int(kernel_size/2), initialW=initializer, initial_bias=None),
c3=L.ConvolutionND(ndim, int(init_channel * (ap_factor ** 1)), int(init_channel * (ap_factor ** 2)), kernel_size, 1, int(kernel_size/2), initialW=initializer, initial_bias=None),
c4=L.ConvolutionND(ndim, int(init_channel * (ap_factor ** 2)), int(init_channel * (ap_factor ** 2)), kernel_size, 1, int(kernel_size/2), initialW=initializer, initial_bias=None),
c5=L.ConvolutionND(ndim, int(init_channel * (ap_factor ** 2)), int(init_channel * (ap_factor ** 3)), kernel_size, 1, int(kernel_size/2), initialW=initializer, initial_bias=None),
c6=L.ConvolutionND(ndim, int(init_channel * (ap_factor ** 3)), int(init_channel * (ap_factor ** 3)), kernel_size, 1, int(kernel_size/2), initialW=initializer, initial_bias=None),
c7=L.ConvolutionND(ndim, int(init_channel * (ap_factor ** 3)), int(init_channel * (ap_factor ** 4)), kernel_size, 1, int(kernel_size/2), initialW=initializer, initial_bias=None),
dc0=L.DeconvolutionND(ndim, int(init_channel * (ap_factor ** 4)), int(init_channel * (ap_factor ** 4)), self.pool_size, self.pool_size, 0, initialW=initializer, initial_bias=None),
dc1=L.ConvolutionND(ndim, int(init_channel * (ap_factor ** 3) + init_channel * (ap_factor ** 4)), int(init_channel * (ap_factor ** 3)), kernel_size, 1, int(kernel_size/2), initialW=initializer, initial_bias=None),
dc2=L.ConvolutionND(ndim, int(init_channel * (ap_factor ** 3)), int(init_channel * (ap_factor ** 3)), kernel_size, 1, int(kernel_size/2), initialW=initializer, initial_bias=None),
dc3=L.DeconvolutionND(ndim, int(init_channel * (ap_factor ** 3)), int(init_channel * (ap_factor ** 3)), self.pool_size, self.pool_size, 0, initialW=initializer, initial_bias=None),
dc4=L.ConvolutionND(ndim, int(init_channel * (ap_factor ** 2) + init_channel * (ap_factor ** 3)), int(init_channel * (ap_factor ** 2)), kernel_size, 1, int(kernel_size/2), initialW=initializer, initial_bias=None),
dc5=L.ConvolutionND(ndim, int(init_channel * (ap_factor ** 2)), int(init_channel * (ap_factor ** 2)), kernel_size, 1, int(kernel_size/2), initialW=initializer, initial_bias=None),
dc6=L.DeconvolutionND(ndim, int(init_channel * (ap_factor ** 2)), int(init_channel * (ap_factor ** 2)), self.pool_size, self.pool_size, 0, initialW=initializer, initial_bias=None),
dc7=L.ConvolutionND(ndim, int(init_channel * (ap_factor ** 1) + init_channel * (ap_factor ** 2)), int(init_channel * (ap_factor ** 1)), kernel_size, 1, int(kernel_size/2), initialW=initializer, initial_bias=None),
dc8=L.ConvolutionND(ndim, int(init_channel * (ap_factor ** 1)), int(init_channel * (ap_factor ** 1)), kernel_size, 1, int(kernel_size/2), initialW=initializer, initial_bias=None),
dc9=L.ConvolutionND(ndim, int(init_channel * (ap_factor ** 1)), n_class, 1, 1, initialW=initializer, initial_bias=None),
bnc0=L.BatchNormalization(init_channel),
bnc1=L.BatchNormalization(int(init_channel * (ap_factor ** 1))),
bnc2=L.BatchNormalization(int(init_channel * (ap_factor ** 1))),
bnc3=L.BatchNormalization(int(init_channel * (ap_factor ** 2))),
bnc4=L.BatchNormalization(int(init_channel * (ap_factor ** 2))),
bnc5=L.BatchNormalization(int(init_channel * (ap_factor ** 3))),
bnc6=L.BatchNormalization(int(init_channel * (ap_factor ** 3))),
bnc7=L.BatchNormalization(int(init_channel * (ap_factor ** 4))),
bndc1=L.BatchNormalization(int(init_channel * (ap_factor ** 3))),
bndc2=L.BatchNormalization(int(init_channel * (ap_factor ** 3))),
bndc4=L.BatchNormalization(int(init_channel * (ap_factor ** 2))),
bndc5=L.BatchNormalization(int(init_channel * (ap_factor ** 2))),
bndc7=L.BatchNormalization(int(init_channel * (ap_factor ** 1))),
bndc8=L.BatchNormalization(int(init_channel * (ap_factor ** 1)))
)
def _calc(self, x):
e0 = F.relu(self.bnc0(self.c0(x)))
syn0 = F.relu(self.bnc1(self.c1(e0)))
del e0
e1 = F.max_pooling_nd(syn0, self.pool_size, self.pool_size)
e2 = F.relu(self.bnc2(self.c2(e1)))
syn1 = F.relu(self.bnc3(self.c3(e2)))
del e1, e2
e3 = F.max_pooling_nd(syn1, self.pool_size, self.pool_size)
e4 = F.relu(self.bnc4(self.c4(e3)))
syn2 = F.relu(self.bnc5(self.c5(e4)))
del e3, e4
e5 = F.max_pooling_nd(syn2, self.pool_size, self.pool_size)
e6 = F.relu(self.bnc6(self.c6(e5)))
e7 = F.relu(self.bnc7(self.c7(e6)))
del e5, e6
d0 = F.concat([self.dc0(e7), syn2])
del e7, syn2
d1 = F.relu(self.bndc1(self.dc1(d0)))
d2 = F.relu(self.bndc2(self.dc2(d1)))
del d0, d1
d3 = F.concat([self.dc3(d2), syn1])
del d2, syn1
d4 = F.relu(self.bndc4(self.dc4(d3)))
d5 = F.relu(self.bndc5(self.dc5(d4)))
del d3, d4
d6 = F.concat([self.dc6(d5), syn0])
del d5, syn0
d7 = F.relu(self.bndc7(self.dc7(d6)))
d8 = F.relu(self.bndc8(self.dc8(d7)))
del d6, d7
d9 = self.dc9(d8)
del d8
return d9
def __call__(self, x, t=None, seg=True):
h = self._calc(x)
if seg:
pred = F.softmax(h)
del h
return pred.data
else:
#loss = eval(self.loss_func)(h, t, class_weight=self.class_weight)
loss = eval(self.loss_func)(h, t)
pred = F.softmax(h)
del h
return loss, pred.data
class Model_L4(Chain):
def __init__(
self,
ndim=3,
n_class=2,
init_channel=2,
kernel_size=3,
pool_size=2,
ap_factor=2,
gpu=-1,
class_weight=np.array([1, 1]).astype(np.float32),
loss_func='F.softmax_cross_entropy'
):
self.gpu = gpu
self.pool_size = pool_size
if gpu >= 0:
self.class_weight = cuda.to_gpu(np.array(class_weight).astype(np.float32))
else:
self.class_weight = np.array(class_weight).astype(np.float32)
self.train = True
self.loss_func = loss_func
initializer = chainer.initializers.HeNormal()
super(Model_L4, self).__init__(
c0=L.ConvolutionND(ndim, 1, init_channel, kernel_size, 1, int(kernel_size/2), initialW=initializer, initial_bias=None),
c1=L.ConvolutionND(ndim, init_channel, int(init_channel * (ap_factor ** 1)), kernel_size, 1, int(kernel_size/2), initialW=initializer, initial_bias=None),
c2=L.ConvolutionND(ndim, int(init_channel * (ap_factor ** 1)), int(init_channel * (ap_factor ** 1)), kernel_size, 1, int(kernel_size/2), initialW=initializer, initial_bias=None),
c3=L.ConvolutionND(ndim, int(init_channel * (ap_factor ** 1)), int(init_channel * (ap_factor ** 2)), kernel_size, 1, int(kernel_size/2), initialW=initializer, initial_bias=None),
c4=L.ConvolutionND(ndim, int(init_channel * (ap_factor ** 2)), int(init_channel * (ap_factor ** 2)), kernel_size, 1, int(kernel_size/2), initialW=initializer, initial_bias=None),
c5=L.ConvolutionND(ndim, int(init_channel * (ap_factor ** 2)), int(init_channel * (ap_factor ** 3)), kernel_size, 1, int(kernel_size/2), initialW=initializer, initial_bias=None),
c6=L.ConvolutionND(ndim, int(init_channel * (ap_factor ** 3)), int(init_channel * (ap_factor ** 3)), kernel_size, 1, int(kernel_size/2), initialW=initializer, initial_bias=None),
c7=L.ConvolutionND(ndim, int(init_channel * (ap_factor ** 3)), int(init_channel * (ap_factor ** 4)), kernel_size, 1, int(kernel_size/2), initialW=initializer, initial_bias=None),
c8=L.ConvolutionND(ndim, int(init_channel * (ap_factor ** 4)), int(init_channel * (ap_factor ** 4)), kernel_size, 1, int(kernel_size/2), initialW=initializer, initial_bias=None),
c9=L.ConvolutionND(ndim, int(init_channel * (ap_factor ** 4)), int(init_channel * (ap_factor ** 5)), kernel_size, 1, int(kernel_size/2), initialW=initializer, initial_bias=None),
dc0=L.DeconvolutionND(ndim, int(init_channel * (ap_factor ** 5)), int(init_channel * (ap_factor ** 5)), self.pool_size, self.pool_size, 0, initialW=initializer, initial_bias=None),
dc1=L.ConvolutionND(ndim, int(init_channel * (ap_factor ** 4) + init_channel * (ap_factor ** 5)), int(init_channel * (ap_factor ** 4)), kernel_size, 1, int(kernel_size/2), initialW=initializer, initial_bias=None),
dc2=L.ConvolutionND(ndim, int(init_channel * (ap_factor ** 4)), int(init_channel * (ap_factor ** 4)), kernel_size, 1, int(kernel_size/2), initialW=initializer, initial_bias=None),
dc3=L.DeconvolutionND(ndim, int(init_channel * (ap_factor ** 4)), int(init_channel * (ap_factor ** 4)), self.pool_size, self.pool_size, 0, initialW=initializer, initial_bias=None),
dc4=L.ConvolutionND(ndim, int(init_channel * (ap_factor ** 3) + init_channel * (ap_factor ** 4)), int(init_channel * (ap_factor ** 3)), kernel_size, 1, int(kernel_size/2), initialW=initializer, initial_bias=None),
dc5=L.ConvolutionND(ndim, int(init_channel * (ap_factor ** 3)), int(init_channel * (ap_factor ** 3)), kernel_size, 1, int(kernel_size/2), initialW=initializer, initial_bias=None),
dc6=L.DeconvolutionND(ndim, int(init_channel * (ap_factor ** 3)), int(init_channel * (ap_factor ** 3)), self.pool_size, self.pool_size, 0, initialW=initializer, initial_bias=None),
dc7=L.ConvolutionND(ndim, int(init_channel * (ap_factor ** 2) + init_channel * (ap_factor ** 3)), int(init_channel * (ap_factor ** 2)), kernel_size, 1, int(kernel_size/2), initialW=initializer, initial_bias=None),
dc8=L.ConvolutionND(ndim, int(init_channel * (ap_factor ** 2)), int(init_channel * (ap_factor ** 2)), kernel_size, 1, int(kernel_size/2), initialW=initializer, initial_bias=None),
dc9=L.DeconvolutionND(ndim, int(init_channel * (ap_factor ** 2)), int(init_channel * (ap_factor ** 2)), self.pool_size, self.pool_size, 0, initialW=initializer, initial_bias=None),
dc10=L.ConvolutionND(ndim, int(init_channel * (ap_factor ** 1) + init_channel * (ap_factor ** 2)), int(init_channel * (ap_factor ** 1)), kernel_size, 1, int(kernel_size/2), initialW=initializer, initial_bias=None),
dc11=L.ConvolutionND(ndim, int(init_channel * (ap_factor ** 1)), int(init_channel * (ap_factor ** 1)), kernel_size, 1, int(kernel_size/2), initialW=initializer, initial_bias=None),
dc12=L.ConvolutionND(ndim, int(init_channel * (ap_factor ** 1)), n_class, 1, 1, initialW=initializer, initial_bias=None),
bnc0=L.BatchNormalization(init_channel),
bnc1=L.BatchNormalization(int(init_channel * (ap_factor ** 1))),
bnc2=L.BatchNormalization(int(init_channel * (ap_factor ** 1))),
bnc3=L.BatchNormalization(int(init_channel * (ap_factor ** 2))),
bnc4=L.BatchNormalization(int(init_channel * (ap_factor ** 2))),
bnc5=L.BatchNormalization(int(init_channel * (ap_factor ** 3))),
bnc6=L.BatchNormalization(int(init_channel * (ap_factor ** 3))),
bnc7=L.BatchNormalization(int(init_channel * (ap_factor ** 4))),
bnc8=L.BatchNormalization(int(init_channel * (ap_factor ** 4))),
bnc9=L.BatchNormalization(int(init_channel * (ap_factor ** 5))),
bndc1=L.BatchNormalization(int(init_channel * (ap_factor ** 4))),
bndc2=L.BatchNormalization(int(init_channel * (ap_factor ** 4))),
bndc4=L.BatchNormalization(int(init_channel * (ap_factor ** 3))),
bndc5=L.BatchNormalization(int(init_channel * (ap_factor ** 3))),
bndc7=L.BatchNormalization(int(init_channel * (ap_factor ** 2))),
bndc8=L.BatchNormalization(int(init_channel * (ap_factor ** 2))),
bndc10=L.BatchNormalization(int(init_channel * (ap_factor ** 1))),
bndc11=L.BatchNormalization(int(init_channel * (ap_factor ** 1)))
)
def _calc(self, x):
e0 = F.relu(self.bnc0(self.c0(x)))
syn0 = F.relu(self.bnc1(self.c1(e0)))
del e0
e1 = F.max_pooling_nd(syn0, self.pool_size, self.pool_size)
e2 = F.relu(self.bnc2(self.c2(e1)))
syn1 = F.relu(self.bnc3(self.c3(e2)))
del e1, e2
e3 = F.max_pooling_nd(syn1, self.pool_size, self.pool_size)
e4 = F.relu(self.bnc4(self.c4(e3)))
syn2 = F.relu(self.bnc5(self.c5(e4)))
del e3, e4
e5 = F.max_pooling_nd(syn2, self.pool_size, self.pool_size)
e6 = F.relu(self.bnc6(self.c6(e5)))
syn3 = F.relu(self.bnc7(self.c7(e6)))
del e5, e6
e7 = F.max_pooling_nd(syn3, self.pool_size, self.pool_size)
e8 = F.relu(self.bnc8(self.c8(e7)))
e9 = F.relu(self.bnc9(self.c9(e8)))
del e7, e8
d0 = F.concat([self.dc0(e9), syn3])
del e9, syn3
d1 = F.relu(self.bndc1(self.dc1(d0)))
d2 = F.relu(self.bndc2(self.dc2(d1)))
del d0, d1
d3 = F.concat([self.dc3(d2), syn2])
del d2, syn2
d4 = F.relu(self.bndc4(self.dc4(d3)))
d5 = F.relu(self.bndc5(self.dc5(d4)))
del d3, d4
d6 = F.concat([self.dc6(d5), syn1])
del d5, syn1
d7 = F.relu(self.bndc7(self.dc7(d6)))
d8 = F.relu(self.bndc8(self.dc8(d7)))
del d6, d7
d9 = F.concat([self.dc9(d8), syn0])
del d8, syn0
d10 = F.relu(self.bndc10(self.dc10(d9)))
d11 = F.relu(self.bndc11(self.dc11(d10)))
del d9, d10
d12 = self.dc12(d11)
del d11
return d12
def __call__(self, x, t=None, seg=True):
h = self._calc(x)
if seg:
pred = F.softmax(h)
del h
return pred.data
else:
#loss = eval(self.loss_func)(h, t, class_weight=self.class_weight)
loss = eval(self.loss_func)(h, t)
pred = F.softmax(h)
del h
return loss, pred.data
|
[
"chainer.initializers.HeNormal",
"chainer.functions.max_pooling_nd",
"numpy.array",
"chainer.functions.softmax",
"chainer.links.BatchNormalization"
] |
[((932, 963), 'chainer.initializers.HeNormal', 'chainer.initializers.HeNormal', ([], {}), '()\n', (961, 963), False, 'import chainer\n'), ((4333, 4387), 'chainer.functions.max_pooling_nd', 'F.max_pooling_nd', (['syn0', 'self.pool_size', 'self.pool_size'], {}), '(syn0, self.pool_size, self.pool_size)\n', (4349, 4387), True, 'import chainer.functions as F\n'), ((4510, 4564), 'chainer.functions.max_pooling_nd', 'F.max_pooling_nd', (['syn1', 'self.pool_size', 'self.pool_size'], {}), '(syn1, self.pool_size, self.pool_size)\n', (4526, 4564), True, 'import chainer.functions as F\n'), ((6161, 6192), 'chainer.initializers.HeNormal', 'chainer.initializers.HeNormal', ([], {}), '()\n', (6190, 6192), False, 'import chainer\n'), ((10868, 10922), 'chainer.functions.max_pooling_nd', 'F.max_pooling_nd', (['syn0', 'self.pool_size', 'self.pool_size'], {}), '(syn0, self.pool_size, self.pool_size)\n', (10884, 10922), True, 'import chainer.functions as F\n'), ((11045, 11099), 'chainer.functions.max_pooling_nd', 'F.max_pooling_nd', (['syn1', 'self.pool_size', 'self.pool_size'], {}), '(syn1, self.pool_size, self.pool_size)\n', (11061, 11099), True, 'import chainer.functions as F\n'), ((11222, 11276), 'chainer.functions.max_pooling_nd', 'F.max_pooling_nd', (['syn2', 'self.pool_size', 'self.pool_size'], {}), '(syn2, self.pool_size, self.pool_size)\n', (11238, 11276), True, 'import chainer.functions as F\n'), ((13049, 13080), 'chainer.initializers.HeNormal', 'chainer.initializers.HeNormal', ([], {}), '()\n', (13078, 13080), False, 'import chainer\n'), ((19065, 19119), 'chainer.functions.max_pooling_nd', 'F.max_pooling_nd', (['syn0', 'self.pool_size', 'self.pool_size'], {}), '(syn0, self.pool_size, self.pool_size)\n', (19081, 19119), True, 'import chainer.functions as F\n'), ((19242, 19296), 'chainer.functions.max_pooling_nd', 'F.max_pooling_nd', (['syn1', 'self.pool_size', 'self.pool_size'], {}), '(syn1, self.pool_size, self.pool_size)\n', (19258, 19296), True, 'import chainer.functions as F\n'), ((19419, 19473), 'chainer.functions.max_pooling_nd', 'F.max_pooling_nd', (['syn2', 'self.pool_size', 'self.pool_size'], {}), '(syn2, self.pool_size, self.pool_size)\n', (19435, 19473), True, 'import chainer.functions as F\n'), ((19596, 19650), 'chainer.functions.max_pooling_nd', 'F.max_pooling_nd', (['syn3', 'self.pool_size', 'self.pool_size'], {}), '(syn3, self.pool_size, self.pool_size)\n', (19612, 19650), True, 'import chainer.functions as F\n'), ((5190, 5202), 'chainer.functions.softmax', 'F.softmax', (['h'], {}), '(h)\n', (5199, 5202), True, 'import chainer.functions as F\n'), ((5408, 5420), 'chainer.functions.softmax', 'F.softmax', (['h'], {}), '(h)\n', (5417, 5420), True, 'import chainer.functions as F\n'), ((12078, 12090), 'chainer.functions.softmax', 'F.softmax', (['h'], {}), '(h)\n', (12087, 12090), True, 'import chainer.functions as F\n'), ((12296, 12308), 'chainer.functions.softmax', 'F.softmax', (['h'], {}), '(h)\n', (12305, 12308), True, 'import chainer.functions as F\n'), ((20642, 20654), 'chainer.functions.softmax', 'F.softmax', (['h'], {}), '(h)\n', (20651, 20654), True, 'import chainer.functions as F\n'), ((20860, 20872), 'chainer.functions.softmax', 'F.softmax', (['h'], {}), '(h)\n', (20869, 20872), True, 'import chainer.functions as F\n'), ((499, 515), 'numpy.array', 'np.array', (['[1, 1]'], {}), '([1, 1])\n', (507, 515), True, 'import numpy as np\n'), ((3446, 3480), 'chainer.links.BatchNormalization', 'L.BatchNormalization', (['init_channel'], {}), '(init_channel)\n', (3466, 3480), True, 'import chainer.links as L\n'), ((5728, 5744), 'numpy.array', 'np.array', (['[1, 1]'], {}), '([1, 1])\n', (5736, 5744), True, 'import numpy as np\n'), ((9670, 9704), 'chainer.links.BatchNormalization', 'L.BatchNormalization', (['init_channel'], {}), '(init_channel)\n', (9690, 9704), True, 'import chainer.links as L\n'), ((12616, 12632), 'numpy.array', 'np.array', (['[1, 1]'], {}), '([1, 1])\n', (12624, 12632), True, 'import numpy as np\n'), ((17555, 17589), 'chainer.links.BatchNormalization', 'L.BatchNormalization', (['init_channel'], {}), '(init_channel)\n', (17575, 17589), True, 'import chainer.links as L\n'), ((807, 829), 'numpy.array', 'np.array', (['class_weight'], {}), '(class_weight)\n', (815, 829), True, 'import numpy as np\n'), ((6036, 6058), 'numpy.array', 'np.array', (['class_weight'], {}), '(class_weight)\n', (6044, 6058), True, 'import numpy as np\n'), ((12924, 12946), 'numpy.array', 'np.array', (['class_weight'], {}), '(class_weight)\n', (12932, 12946), True, 'import numpy as np\n'), ((718, 740), 'numpy.array', 'np.array', (['class_weight'], {}), '(class_weight)\n', (726, 740), True, 'import numpy as np\n'), ((5947, 5969), 'numpy.array', 'np.array', (['class_weight'], {}), '(class_weight)\n', (5955, 5969), True, 'import numpy as np\n'), ((12835, 12857), 'numpy.array', 'np.array', (['class_weight'], {}), '(class_weight)\n', (12843, 12857), True, 'import numpy as np\n')]
|
# pylint: disable-msg=E1101
"""
Wrapper to lowess and stl routines.
LOWESS:
Initial Fortran code available at:
http://netlib.bell-labs.com/netlib/go/lowess.f.gz
initial author: <NAME>, 1979.
Simple to double precision conversion of the Fortran code by Pierre
Gerard-Marchant, 2007/03.
STL:
Initial Fortran code available at:
http://netlib.bell-labs.com/netlib/a/stl.gz
Initial Authors: <NAME>, <NAME>, <NAME>, and
<NAME>, 1990.
Simple-to-double precision conversion of the Fortran code by Pierre
Gerard-Marchant, 2007/03.
LOESS:
Initial C/Fortran package avialable at
http://netlib.bell-labs.com/netlib/a/dloess.gz
Initial authors: <NAME>, <NAME> and Shyu
Adaptation to Pyrex/Python by <NAME>, 2007/03
:author: <NAME>
:contact: pierregm_at_uga_edu
:date: $Date$
:version: $Id$
"""
__author__ = "<NAME> ($Author$)"
__version__ = '1.0'
__revision__ = "$Revision$"
__date__ = '$Date$'
import numpy
from numpy import bool_, complex_, float_, int_, str_, object_
from numpy import array, recarray, empty, fromiter, logical_not
from . import _lowess, _stl, _loess
#####---------------------------------------------------------------------------
#--- --- FLOWESS ---
#####---------------------------------------------------------------------------
def flowess(x,y,span=0.5,nsteps=2,delta=0):
"""Performs a robust locally weighted regression (lowess).
Outputs a *3xN* array of fitted values, residuals and fit weights.
:Parameters:
x : ndarray
Abscissas of the points on the scatterplot; the values in X must be
ordered from smallest to largest.
y : ndarray
Ordinates of the points on the scatterplot.
span : Float *[0.5]*
Fraction of the total number of points used to compute each fitted value.
As f increases the smoothed values become smoother. Choosing f in the range
.2 to .8 usually results in a good fit.
nsteps : Integer *[2]*
Number of iterations in the robust fit. If nsteps=0, the nonrobust fit
is returned; setting nsteps=2 should serve most purposes.
delta : Integer *[0]*
Nonnegative parameter which may be used to save computations.
If N (the number of elements in x) is less than 100, set delta=0.0;
if N is greater than 100 you should find out how delta works by reading
the additional instructions section.
:Returns:
A recarray of smoothed values ('smooth'), residuals ('residuals') and local
robust weights ('weights').
Additional instructions
-----------------------
Fro the original author:
DELTA can be used to save computations. Very roughly the
algorithm is this: on the initial fit and on each of the
NSTEPS iterations locally weighted regression fitted values
are computed at points in X which are spaced, roughly, DELTA
apart; then the fitted values at the remaining points are
computed using linear interpolation. The first locally
weighted regression (l.w.r.) computation is carried out at
X(1) and the last is carried out at X(N). Suppose the
l.w.r. computation is carried out at X(I). If X(I+1) is
greater than or equal to X(I)+DELTA, the next l.w.r.
computation is carried out at X(I+1). If X(I+1) is less
than X(I)+DELTA, the next l.w.r. computation is carried out
at the largest X(J) which is greater than or equal to X(I)
but is not greater than X(I)+DELTA. Then the fitted values
for X(K) between X(I) and X(J), if there are any, are
computed by linear interpolation of the fitted values at
X(I) and X(J). If N is less than 100 then DELTA can be set
to 0.0 since the computation time will not be too great.
For larger N it is typically not necessary to carry out the
l.w.r. computation for all points, so that much computation
time can be saved by taking DELTA to be greater than 0.0.
If DELTA = Range (X)/k then, if the values in X were
uniformly scattered over the range, the full l.w.r.
computation would be carried out at approximately k points.
Taking k to be 50 often works well.
Method
------
The fitted values are computed by using the nearest neighbor
routine and robust locally weighted regression of degree 1
with the tricube weight function. A few additional features
have been added. Suppose r is FN truncated to an integer.
Let h be the distance to the r-th nearest neighbor
from X[i]. All points within h of X[i] are used. Thus if
the r-th nearest neighbor is exactly the same distance as
other points, more than r points can possibly be used for
the smooth at X[i]. There are two cases where robust
locally weighted regression of degree 0 is actually used at
X[i]. One case occurs when h is 0.0. The second case
occurs when the weighted standard error of the X[i] with
respect to the weights w[j] is less than .001 times the
range of the X[i], where w[j] is the weight assigned to the
j-th point of X (the tricube weight times the robustness
weight) divided by the sum of all of the weights. Finally,
if the w[j] are all zero for the smooth at X[i], the fitted
value is taken to be Y[i].
References
----------
<NAME>. 1978. Visual and Computational Considerations in
Smoothing Scatterplots by Locally Weighted Regression. In
Computer Science and Statistics: Eleventh Annual Symposium on the
Interface, pages 96-100. Institute of Statistics, North Carolina
State University, Raleigh, North Carolina, 1978.
<NAME>, 1979. Robust Locally Weighted Regression and
Smoothing Scatterplots. Journal of the American Statistical
Association, 74:829-836, 1979.
<NAME>, 1981. LOWESS: A Program for Smoothing Scatterplots
by Robust Locally Weighted Regression. The American Statistician,
35:54.
"""
x = array(x, copy=False, subok=True, dtype=float_)
y = array(y, copy=False, subok=True, dtype=float_)
if x.size != y.size:
raise ValueError("Incompatible size between observations and response!")
out_dtype = [('smooth',float_), ('weigths', float_), ('residuals', float_)]
return numeric.fromiter(zip(*_lowess.lowess(x,y,span,nsteps,delta,)),
dtype=out_dtype).view(recarray)
class lowess:
"""An object for robust locally weighted regression.
:IVariables:
inputs : An object storing the inputs.
x : A (n,) ndarray of observations (sorted by increasing values).
y : A (n,) ndarray of responses (sorted by increasing x).
parameters : An object storing the control parameters.
span : Fraction of the total number of points used in the smooth.
nsteps : Number of iterations of the robust fit.
delta : Parameter used to save computation time
outputs : An object storing the outputs.
smooth : A (n,) ndarray of fitted values.
residuals : A (n,) ndarray of fitted residuals.
weights : A (n,) ndarray of robust weights.
Method
------
The fitted values are computed by using the nearest neighbor
routine and robust locally weighted regression of degree 1
with the tricube weight function. A few additional features
have been added. Suppose r is FN truncated to an integer.
Let h be the distance to the r-th nearest neighbor
from X[i]. All points within h of X[i] are used. Thus if
the r-th nearest neighbor is exactly the same distance as
other points, more than r points can possibly be used for
the smooth at X[i]. There are two cases where robust
locally weighted regression of degree 0 is actually used at
X[i]. One case occurs when h is 0.0. The second case
occurs when the weighted standard error of the X[i] with
respect to the weights w[j] is less than .001 times the
range of the X[i], where w[j] is the weight assigned to the
j-th point of X (the tricube weight times the robustness
weight) divided by the sum of all of the weights. Finally,
if the w[j] are all zero for the smooth at X[i], the fitted
value is taken to be Y[i].
References
----------
<NAME>. 1978. Visual and Computational Considerations in
Smoothing Scatterplots by Locally Weighted Regression. In
Computer Science and Statistics: Eleventh Annual Symposium on the
Interface, pages 96-100. Institute of Statistics, North Carolina
State University, Raleigh, North Carolina, 1978.
<NAME>, 1979. Robust Locally Weighted Regression and
Smoothing Scatterplots. Journal of the American Statistical
Association, 74:829-836, 1979.
<NAME>, 1981. LOWESS: A Program for Smoothing Scatterplots
by Robust Locally Weighted Regression. The American Statistician,
35:54.
"""
#............................................
class _inputs(object):
"""Inputs of the lowess fit.
:IVariables:
x : ndarray
A (n,) float ndarray of observations (sorted by increasing values).
y : ndarray
A (n,) float ndarray of responses (sorted by increasing x).
"""
def __init__(self, x, y):
x = array(x, copy=False, subok=True, dtype=float_).ravel()
y = array(y, copy=False, subok=True, dtype=float_).ravel()
if x.size != y.size:
msg = "Incompatible size between observations (%s) and response (%s)!"
raise ValueError(msg % (x.size, y.size))
idx = x.argsort()
self._x = x[idx]
self._y = y[idx]
#.....
x = property(fget=lambda self:self._x)
y = property(fget=lambda self:self._y)
#............................................
class _parameters(object):
"""Parameters of the lowess fit.
:IVariables:
span : float *[0.5]*
Fraction of the total number of points used to compute each fitted value.
As f increases the smoothed values become smoother. Choosing f in the range
.2 to .8 usually results in a good fit.
nsteps : integer *[2]*
Number of iterations in the robust fit. If nsteps=0, the nonrobust fit
is returned; setting nsteps=2 should serve most purposes.
delta : integer *[0]*
Nonnegative parameter which may be used to save computations.
If N (the number of observations) is less than 100, set delta=0.0;
if N is greater than 100 you should find out how delta works by reading
the additional instructions section.
"""
def __init__(self, span, nsteps, delta, caller):
self.activated = False
self._span = span
self._nsteps = nsteps
self._delta = delta
self._caller = caller
#.....
def _get_span(self):
"Gets the current span."
return self._span
def _set_span(self, span):
"Sets the current span, and refit if needed."
if span <= 0 or span > 1:
raise ValueError("span should be between zero and one!")
self._span = span
if self.activated:
self._caller.fit()
span = property(fget=_get_span, fset=_set_span)
#.....
def _get_nsteps(self):
"Gets the current number of iterations."
return self._nsteps
def _set_nsteps(self, nsteps):
"Sets the current number of iterations, and refit if needed."
if nsteps < 0:
raise ValueError("nsteps should be positive!")
self._nsteps = nsteps
if self.activated:
self._caller.fit()
nsteps = property(fget=_get_nsteps, fset=_set_nsteps)
#.....
def _get_delta(self):
"Gets the current delta."
return self._delta
def _set_delta(self, delta):
"Sets the current delta, and refit if needed."
if delta < 0:
raise ValueError("delta should be positive!")
self._delta = delta
if self.activated:
self._caller.fit()
delta = property(fget=_get_delta, fset=_set_delta)
#............................................
class _outputs(object):
"""Outputs of the lowess fit.
:IVariables:
fitted_values : ndarray
A (n,) ndarray of fitted values (readonly).
fitted_residuals : ndarray
A (n,) ndarray of residuals (readonly).
weights : ndarray
A (n,) ndarray of robust weights (readonly).
"""
def __init__(self, n):
self._fval = empty((n,), float_)
self._rw = empty((n,), float_)
self._fres = empty((n,), float_)
#.....
fitted_values = property(fget=lambda self:self._fval)
robust_weights = property(fget=lambda self:self._rw)
fitted_residuals = property(fget=lambda self:self._fres)
#............................................
def __init__(self, x, y, span=0.5, nsteps=2, delta=0):
"""
:Parameters:
x : ndarray
Abscissas of the points on the scatterplot; the values in X must be
ordered from smallest to largest.
y : ndarray
Ordinates of the points on the scatterplot.
span : Float *[0.5]*
Fraction of the total number of points used to compute each fitted value.
As span increases the smoothed values become smoother. Choosing span in
the range .2 to .8 usually results in a good fit.
nsteps : Integer *[2]*
Number of iterations in the robust fit. If nsteps=0, the nonrobust fit
is returned; setting nsteps=2 should serve most purposes.
delta : Integer *[0]*
Nonnegative parameter which may be used to save computations.
If N (the number of elements in x) is less than 100, set delta=0.0;
if N is greater than 100 you should find out how delta works by reading
the additional instructions section.
"""
# Chek the input data .........
# Initialize the attributes ...
self.inputs = lowess._inputs(x,y)
self.parameters = lowess._parameters(span, nsteps, delta, self)
self.outputs = lowess._outputs(self.inputs._x.size)
# Force a fit .................
self.fit()
#............................................
def fit(self):
"""Computes the lowess fit. Returns a lowess.outputs object."""
(x, y) = (self.inputs._x, self.inputs._y)
# Get the parameters .....
self.parameters.activated = True
f = self.parameters._span
nsteps = self.parameters._nsteps
delta = self.parameters._delta
(tmp_s, tmp_w, tmp_r) = _lowess.lowess(x, y, f, nsteps, delta)
# Process the outputs .....
#... set the values
self.outputs.fitted_values[:] = tmp_s.flat
self.outputs.robust_weights[:] = tmp_w.flat
self.outputs.fitted_residuals[:] = tmp_r.flat
# Clean up the mess .......
del(tmp_s, tmp_w, tmp_r)
return self.outputs
#####---------------------------------------------------------------------------
#--- --- STL ---
#####---------------------------------------------------------------------------
def stl(y, np=12, ns=7, nt=None, nl=None, isdeg=1, itdeg=1, ildeg=1,
nsjump=None, ntjump=None, nljump=None, robust=True, ni=None, no=None):
"""Decomposes a time series into seasonal and trend components.
:Parameters:
y : Numerical array
Time Series to be decomposed.
np : Integer *[12]*
Period of the seasonal component.
For example, if the time series is monthly with a yearly cycle, then
np=12.
ns : Integer *[7]*
Length of the seasonal smoother.
The value of ns should be an odd integer greater than or equal to 3.
A value ns>6 is recommended. As ns increases the values of the
seasonal component at a given point in the seasonal cycle (e.g., January
values of a monthly series with a yearly cycle) become smoother.
nt : Integer *[None]*
Length of the trend smoother.
The value of nt should be an odd integer greater than or equal to 3.
A value of nt between 1.5*np and 2*np is recommended. As nt increases,
the values of the trend component become smoother.
If nt is None, it is estimated as the smallest odd integer greater
or equal to (1.5*np)/[1-(1.5/ns)]
nl : Integer *[None]*
Length of the low-pass filter.
The value of nl should be an odd integer greater than or equal to 3.
The smallest odd integer greater than or equal to np is used by default.
isdeg : Integer *[1]*
Degree of locally-fitted polynomial in seasonal smoothing.
The value is 0 or 1.
itdeg : Integer *[1]*
Degree of locally-fitted polynomial in trend smoothing.
The value is 0 or 1.
ildeg : Integer *[1]*
Degree of locally-fitted polynomial in low-pass smoothing.
The value is 0 or 1.
nsjump : Integer *[None]*
Skipping value for seasonal smoothing.
The seasonal smoother skips ahead nsjump points and then linearly
interpolates in between. The value of nsjump should be a positive
integer; if nsjump=1, a seasonal smooth is calculated at all n points.
To make the procedure run faster, a reasonable choice for nsjump is
10%-20% of ns. By default, nsjump= 0.1*ns.
ntjump : Integer *[1]*
Skipping value for trend smoothing. If None, ntjump= 0.1*nt
nljump : Integer *[1]*
Skipping value for low-pass smoothing. If None, nljump= 0.1*nl
robust : Boolean *[True]*
Flag indicating whether robust fitting should be performed.
ni : Integer *[None]*
Number of loops for updating the seasonal and trend components.
The value of ni should be a positive integer.
See the next argument for advice on the choice of ni.
If ni is None, ni is set to 1 for robust fitting, to 5 otherwise.
no : Integer *[None]*
Number of iterations of robust fitting. The value of no should
be a nonnegative integer. If the data are well behaved without
outliers, then robustness iterations are not needed. In this case
set no=0, and set ni=2 to 5 depending on how much security
you want that the seasonal-trend looping converges.
If outliers are present then no=3 is a very secure value unless
the outliers are radical, in which case no=5 or even 10 might
be better. If no>0 then set ni to 1 or 2.
If None, then no is set to 15 for robust fitting, to 0 otherwise.
Returns:
A recarray of estimated trend values ('trend'), estimated seasonal
components ('seasonal'), local robust weights ('weights') and fit
residuals ('residuals').
The final local robust weights are all 1 if no=0.
Reference
---------
<NAME>, <NAME>, <NAME> and <NAME>.
1990. STL: A Seasonal-Trend Decomposition Procedure Based on LOESS
(with Discussion). Journal of Official Statistics, 6:3-73.
"""
ns = max(ns, 3)
if ns%2 == 0:
ns += 1
np = max(2, np)
if nt is None:
nt = max(int((1.5*np/(1.-1.5/ns))+0.5), 3)
if not nt%2:
nt += 1
if nl is None:
nl = max(3,np)
if not nl%2:
nl += 1
if nsjump is None:
nsjump = int(0.1*ns + 0.9)
if ntjump is None:
ntjump = int(0.1*nt + 0.9)
if nljump is None:
nljump = int(0.1*nl + 0.9)
if robust:
if ni is None:
ni = 1
if no is None:
no = 15
else:
if ni is None:
ni = 5
if no is None:
no = 0
if hasattr(y,'_mask') and numpy.any(y._mask):
raise ValueError("Missing values should first be filled !")
y = array(y, subok=True, copy=False).ravel()
(rw,szn,trn,work) = _stl.stl(y,np,ns,nt,nl,isdeg,itdeg,ildeg,
nsjump,ntjump,nljump,ni,no,)
dtyp = [('trend', float_), ('seasonal', float_),
('residuals', float_), ('weights', float_)]
result = fromiter(zip(trn,szn,y-trn-szn,rw), dtype=dtyp)
return result.view(recarray)
#####---------------------------------------------------------------------------
#--- --- Loess ---
#####---------------------------------------------------------------------------
loess = _loess.loess
"""
loess : locally weighted estimates. Multi-variate version
:Keywords:
x : ndarray
A (n,p) ndarray of independent variables, with n the number of observations
and p the number of variables.
y : ndarray
A (n,) ndarray of observations
weights : ndarray
A (n,) ndarray of weights to be given to individual observations in the
sum of squared residuals that forms the local fitting criterion. If not
None, the weights should be non negative. If the different observations
have non-equal variances, the weights should be inversely proportional
to the variances.
By default, an unweighted fit is carried out (all the weights are one).
surface : string ["interpolate"]
Determines whether the fitted surface is computed directly at all points
("direct") or whether an interpolation method is used ("interpolate").
The default ("interpolate") is what most users should use unless special
circumstances warrant.
statistics : string ["approximate"]
Determines whether the statistical quantities are computed exactly
("exact") or approximately ("approximate"). "exact" should only be used
for testing the approximation in statistical development and is not meant
for routine usage because computation time can be horrendous.
trace_hat : string ["wait.to.decide"]
Determines how the trace of the hat matrix should be computed. The hat
matrix is used in the computation of the statistical quantities.
If "exact", an exact computation is done; this could be slow when the
number of observations n becomes large. If "wait.to.decide" is selected,
then a default is "exact" for n < 500 and "approximate" otherwise.
This option is only useful when the fitted surface is interpolated. If
surface is "exact", an exact computation is always done for the trace.
Setting trace_hat to "approximate" for large dataset will substantially
reduce the computation time.
iterations : integer
Number of iterations of the robust fitting method. If the family is
"gaussian", the number of iterations is set to 0.
cell : integer
Maximum cell size of the kd-tree. Suppose k = floor(n*cell*span),
where n is the number of observations, and span the smoothing parameter.
Then, a cell is further divided if the number of observations within it
is greater than or equal to k. This option is only used if the surface
is interpolated.
span : float [0.75]
Smoothing factor, as a fraction of the number of points to take into
account.
degree : integer [2]
Overall degree of locally-fitted polynomial. 1 is locally-linear
fitting and 2 is locally-quadratic fitting. Degree should be 2 at most.
normalize : boolean [True]
Determines whether the independent variables should be normalized.
If True, the normalization is performed by setting the 10% trimmed
standard deviation to one. If False, no normalization is carried out.
This option is only useful for more than one variable. For spatial
coordinates predictors or variables with a common scale, it should be
set to False.
family : string ["gaussian"]
Determines the assumed distribution of the errors. The values are
"gaussian" or "symmetric". If "gaussian" is selected, the fit is
performed with least-squares. If "symmetric" is selected, the fit
is performed robustly by redescending M-estimators.
parametric_flags : sequence [ [False]*p ]
Indicates which independent variables should be conditionally-parametric
(if there are two or more independent variables). The argument should
be a sequence of booleans, with the same size as the number of independent
variables, specified in the order of the predictor group ordered in x.
drop_square : sequence [ [False]* p]
When there are two or more independent variables and when a 2nd order
polynomial is used, "drop_square_flags" specifies those numeric predictors
whose squares should be dropped from the set of fitting variables.
The method of specification is the same as for parametric.
:Outputs:
fitted_values : ndarray
The (n,) ndarray of fitted values.
fitted_residuals : ndarray
The (n,) ndarray of fitted residuals (observations - fitted values).
enp : float
Equivalent number of parameters.
s : float
Estimate of the scale of residuals.
one_delta: float
Statistical parameter used in the computation of standard errors.
two_delta : float
Statistical parameter used in the computation of standard errors.
pseudovalues : ndarray
The (n,) ndarray of adjusted values of the response when robust estimation
is used.
trace_hat : float
Trace of the operator hat matrix.
diagonal :
Diagonal of the operator hat matrix.
robust : ndarray
The (n,) ndarray of robustness weights for robust fitting.
divisor : ndarray
The (p,) array of normalization divisors for numeric predictors.
newdata : ndarray
The (m,p) array of independent variables where the surface must be estimated.
values : ndarray
The (m,) ndarray of loess values evaluated at newdata
stderr : ndarray
The (m,) ndarray of the estimates of the standard error on the estimated
values.
residual_scale : float
Estimate of the scale of the residuals
df : integer
Degrees of freedom of the t-distribution used to compute pointwise
confidence intervals for the evaluated surface.
nest : integer
Number of new observations.
"""
loess_anova = _loess.anova
|
[
"numpy.any",
"numpy.empty",
"numpy.array"
] |
[((6139, 6185), 'numpy.array', 'array', (['x'], {'copy': '(False)', 'subok': '(True)', 'dtype': 'float_'}), '(x, copy=False, subok=True, dtype=float_)\n', (6144, 6185), False, 'from numpy import array, recarray, empty, fromiter, logical_not\n'), ((6194, 6240), 'numpy.array', 'array', (['y'], {'copy': '(False)', 'subok': '(True)', 'dtype': 'float_'}), '(y, copy=False, subok=True, dtype=float_)\n', (6199, 6240), False, 'from numpy import array, recarray, empty, fromiter, logical_not\n'), ((20086, 20104), 'numpy.any', 'numpy.any', (['y._mask'], {}), '(y._mask)\n', (20095, 20104), False, 'import numpy\n'), ((12875, 12894), 'numpy.empty', 'empty', (['(n,)', 'float_'], {}), '((n,), float_)\n', (12880, 12894), False, 'from numpy import array, recarray, empty, fromiter, logical_not\n'), ((12918, 12937), 'numpy.empty', 'empty', (['(n,)', 'float_'], {}), '((n,), float_)\n', (12923, 12937), False, 'from numpy import array, recarray, empty, fromiter, logical_not\n'), ((12963, 12982), 'numpy.empty', 'empty', (['(n,)', 'float_'], {}), '((n,), float_)\n', (12968, 12982), False, 'from numpy import array, recarray, empty, fromiter, logical_not\n'), ((20182, 20214), 'numpy.array', 'array', (['y'], {'subok': '(True)', 'copy': '(False)'}), '(y, subok=True, copy=False)\n', (20187, 20214), False, 'from numpy import array, recarray, empty, fromiter, logical_not\n'), ((9448, 9494), 'numpy.array', 'array', (['x'], {'copy': '(False)', 'subok': '(True)', 'dtype': 'float_'}), '(x, copy=False, subok=True, dtype=float_)\n', (9453, 9494), False, 'from numpy import array, recarray, empty, fromiter, logical_not\n'), ((9519, 9565), 'numpy.array', 'array', (['y'], {'copy': '(False)', 'subok': '(True)', 'dtype': 'float_'}), '(y, copy=False, subok=True, dtype=float_)\n', (9524, 9565), False, 'from numpy import array, recarray, empty, fromiter, logical_not\n')]
|
"""
This code validates the performance of VGG16 after L-OBS prunning
"""
import torch
import torch.backends.cudnn as cudnn
import torchvision.datasets as datasets
import torchvision.transforms as transforms
from models.vgg import vgg16_bn
from utils import validate, adjust_mean_var
import numpy as np
import os
from datetime import datetime
use_cuda = torch.cuda.is_available()
# -------------------------------------------- User Config ------------------------------------
# Specify parameters path
traindir = '/home/shangyu/imagenet-train'
valdir = '/home/shangyu/imagenet-val'
pruned_weight_root = './VGG16/pruned_weight'
pruned_parameter_root = './VGG16/pruned_param'
if not os.path.exists(pruned_parameter_root):
os.makedirs(pruned_parameter_root)
pretrain_model_path = './VGG16/vgg16_bn-6c64b313.pth'
n_validate_batch = 100 # Number of batches used for validation
validate_batch_size = 50 # Batch size of validation
adjust_batch_size = 128
n_adjust_batch = 500
# Prune data is retrieved from
# Learning bothWeights and Connections for Efficient Neural Networks (Song Han NIPS2015)
layer_name_list = {
'features.0': 55,
'features.3': 20,
'features.7': 35,
'features.10': 35,
'features.14': 55,
'features.17': 25,
'features.20': 40,
'features.24': 30,
'features.27': 30,
'features.30': 35,
'features.34': 35,
'features.37': 30,
'features.40': 35,
'classifier.0': 5,
'classifier.3': 5,
'classifier.6': 25
}
# -------------------------------------------- User Config ------------------------------------
net = vgg16_bn()
# net.load_state_dict(torch.load(pretrain_model_path))
# param = net.state_dict()
param = torch.load(pretrain_model_path)
total_nnz = 0
total_nelements = 0
n_weight_used = 0
n_total_weight = len(os.listdir('%s/CR_5' %(pruned_weight_root))) # It should be 16 * 2 = 32
for layer_name, CR in layer_name_list.items():
# if not os.path.exists('%s/CR_%d/%s.npy' %(pruned_weight_root, CR, layer_name)):
# continue
pruned_weight = np.load('%s/CR_%d/%s.weight.npy' %(pruned_weight_root, CR, layer_name))
pruned_bias = np.load('%s/CR_%d/%s.bias.npy' %(pruned_weight_root, CR, layer_name))
# print pruned_weight
# raw_input()
# Calculate sparsity
this_sparsity = np.count_nonzero(pruned_weight) + np.count_nonzero(pruned_bias)
this_total = pruned_weight.size + pruned_bias.size
print ('%s CR: %f' %(layer_name, float(this_sparsity)/float(this_total)))
total_nnz += this_sparsity
total_nelements += this_total
param['%s.weight' %layer_name] = torch.FloatTensor(pruned_weight)
param['%s.bias' %layer_name] = torch.FloatTensor(pruned_bias)
n_weight_used += 2
# assert(n_weight_used == n_total_weight)
print ('Prune weights used: %d/%d' %(n_weight_used, n_total_weight))
overall_CR = float(total_nnz) / float(total_nelements)
print ('Overall compression rate (nnz/total): %f' %overall_CR)
net.load_state_dict(param)
torch.save(param, open('%s/CR-%.3f.pth' %(pruned_parameter_root, overall_CR), 'w'))
if use_cuda:
net.cuda()
net = torch.nn.DataParallel(net, device_ids=range(torch.cuda.device_count()))
cudnn.benchmark = True
# Load training dataset for mean/var adjust
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
trainDataset = datasets.ImageFolder(traindir, transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
normalize,
]))
train_loader = torch.utils.data.DataLoader(trainDataset, batch_size = adjust_batch_size, shuffle=True)
print ('[%s] Begin adjust.' %(datetime.now()))
adjust_mean_var(net, train_loader, None, n_adjust_batch, use_cuda)
print ('[%s] Adjust finish. Now saving parameters' %(datetime.now()))
# Load validation dataset
print('==> Preparing data..')
val_loader = torch.utils.data.DataLoader(
datasets.ImageFolder(valdir, transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
normalize,
])),
batch_size = validate_batch_size, shuffle=True)
validate(net, val_loader, None, None, n_validate_batch, use_cuda)
|
[
"numpy.load",
"torch.cuda.device_count",
"torchvision.transforms.Normalize",
"torch.utils.data.DataLoader",
"torch.load",
"os.path.exists",
"utils.adjust_mean_var",
"torch.FloatTensor",
"torchvision.transforms.CenterCrop",
"datetime.datetime.now",
"models.vgg.vgg16_bn",
"torchvision.transforms.RandomHorizontalFlip",
"torch.cuda.is_available",
"os.listdir",
"torchvision.transforms.Resize",
"numpy.count_nonzero",
"os.makedirs",
"utils.validate",
"torchvision.transforms.RandomResizedCrop",
"torchvision.transforms.ToTensor"
] |
[((361, 386), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (384, 386), False, 'import torch\n'), ((1590, 1600), 'models.vgg.vgg16_bn', 'vgg16_bn', ([], {}), '()\n', (1598, 1600), False, 'from models.vgg import vgg16_bn\n'), ((1691, 1722), 'torch.load', 'torch.load', (['pretrain_model_path'], {}), '(pretrain_model_path)\n', (1701, 1722), False, 'import torch\n'), ((3251, 3326), 'torchvision.transforms.Normalize', 'transforms.Normalize', ([], {'mean': '[0.485, 0.456, 0.406]', 'std': '[0.229, 0.224, 0.225]'}), '(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n', (3271, 3326), True, 'import torchvision.transforms as transforms\n'), ((3527, 3616), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['trainDataset'], {'batch_size': 'adjust_batch_size', 'shuffle': '(True)'}), '(trainDataset, batch_size=adjust_batch_size,\n shuffle=True)\n', (3554, 3616), False, 'import torch\n'), ((3662, 3728), 'utils.adjust_mean_var', 'adjust_mean_var', (['net', 'train_loader', 'None', 'n_adjust_batch', 'use_cuda'], {}), '(net, train_loader, None, n_adjust_batch, use_cuda)\n', (3677, 3728), False, 'from utils import validate, adjust_mean_var\n'), ((4099, 4164), 'utils.validate', 'validate', (['net', 'val_loader', 'None', 'None', 'n_validate_batch', 'use_cuda'], {}), '(net, val_loader, None, None, n_validate_batch, use_cuda)\n', (4107, 4164), False, 'from utils import validate, adjust_mean_var\n'), ((688, 725), 'os.path.exists', 'os.path.exists', (['pruned_parameter_root'], {}), '(pruned_parameter_root)\n', (702, 725), False, 'import os\n'), ((731, 765), 'os.makedirs', 'os.makedirs', (['pruned_parameter_root'], {}), '(pruned_parameter_root)\n', (742, 765), False, 'import os\n'), ((1796, 1838), 'os.listdir', 'os.listdir', (["('%s/CR_5' % pruned_weight_root)"], {}), "('%s/CR_5' % pruned_weight_root)\n", (1806, 1838), False, 'import os\n'), ((2043, 2115), 'numpy.load', 'np.load', (["('%s/CR_%d/%s.weight.npy' % (pruned_weight_root, CR, layer_name))"], {}), "('%s/CR_%d/%s.weight.npy' % (pruned_weight_root, CR, layer_name))\n", (2050, 2115), True, 'import numpy as np\n'), ((2133, 2203), 'numpy.load', 'np.load', (["('%s/CR_%d/%s.bias.npy' % (pruned_weight_root, CR, layer_name))"], {}), "('%s/CR_%d/%s.bias.npy' % (pruned_weight_root, CR, layer_name))\n", (2140, 2203), True, 'import numpy as np\n'), ((2593, 2625), 'torch.FloatTensor', 'torch.FloatTensor', (['pruned_weight'], {}), '(pruned_weight)\n', (2610, 2625), False, 'import torch\n'), ((2661, 2691), 'torch.FloatTensor', 'torch.FloatTensor', (['pruned_bias'], {}), '(pruned_bias)\n', (2678, 2691), False, 'import torch\n'), ((2292, 2323), 'numpy.count_nonzero', 'np.count_nonzero', (['pruned_weight'], {}), '(pruned_weight)\n', (2308, 2323), True, 'import numpy as np\n'), ((2326, 2355), 'numpy.count_nonzero', 'np.count_nonzero', (['pruned_bias'], {}), '(pruned_bias)\n', (2342, 2355), True, 'import numpy as np\n'), ((3645, 3659), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (3657, 3659), False, 'from datetime import datetime\n'), ((3782, 3796), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (3794, 3796), False, 'from datetime import datetime\n'), ((3396, 3429), 'torchvision.transforms.RandomResizedCrop', 'transforms.RandomResizedCrop', (['(224)'], {}), '(224)\n', (3424, 3429), True, 'import torchvision.transforms as transforms\n'), ((3433, 3466), 'torchvision.transforms.RandomHorizontalFlip', 'transforms.RandomHorizontalFlip', ([], {}), '()\n', (3464, 3466), True, 'import torchvision.transforms as transforms\n'), ((3470, 3491), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (3489, 3491), True, 'import torchvision.transforms as transforms\n'), ((3139, 3164), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\n', (3162, 3164), False, 'import torch\n'), ((3951, 3973), 'torchvision.transforms.Resize', 'transforms.Resize', (['(256)'], {}), '(256)\n', (3968, 3973), True, 'import torchvision.transforms as transforms\n'), ((3977, 4003), 'torchvision.transforms.CenterCrop', 'transforms.CenterCrop', (['(224)'], {}), '(224)\n', (3998, 4003), True, 'import torchvision.transforms as transforms\n'), ((4007, 4028), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (4026, 4028), True, 'import torchvision.transforms as transforms\n')]
|
from flask import Flask, render_template, jsonify, request, url_for
from shapely.geometry import Point as Shapely_point, mapping
from geojson import Point as Geoj_point, Polygon as Geoj_polygon, Feature, FeatureCollection
from datetime import datetime
from sqlalchemy import *
import pandas as pd
import geopandas as gpd
import numpy as np
import psycopg2 as pg
import json
import leaflet as L
from elastic_app_search import Client
from elasticsearch import Elasticsearch
from elasticapm.contrib.flask import ElasticAPM
import matplotlib.colors as cl
import h3
import h3.api.basic_int as h3int
import json
import h3pandas
import cmasher as cmr
import plotly
import plotly.express as px
from scipy.stats import percentileofscore
from scipy import stats
import plotly.graph_objects as go
import os
import datetime
from netCDF4 import Dataset
import shapely.wkt
import folium
import ftplib
from ftplib import FTP
from pathlib import Path
from os import path, walk
############ globals
outDir = '/home/sumer/my_project_dir/ncep/'
updated_data_available_file = '/home/sumer/weather/weather-forecast/updated_data_available.txt'
#outDir = '/root/ncep/data/'
#updated_data_available_file = '/root/ncep/scripts/updated_data_available.txt'
list_of_ncfiles = [x for x in os.listdir(outDir) if x.endswith('.nc')]
list_of_ncfiles.sort()
time_dim = len(list_of_ncfiles)
varDict = {'TMP_2maboveground': 'Air Temp [C] (2 m above surface)',
'TSOIL_0D1M0D4mbelowground':'Soil Temperature [C] - 0.1-0.4 m below ground',
'SOILW_0D1M0D4mbelowground':'Volumetric Soil Moisture Content [Fraction] - 0.1-0.4 m below ground',
'CRAIN_surface':'Rainfall Boolean [1/0]',
}
#varList = ['TMP_2maboveground','TSOIL_0D1M0D4mbelowground','SOILW_0D1M0D4mbelowground', 'CRAIN_surface']
varList = list(varDict.keys())
var_val3D = []
var_val4D = []
#NOTE: the variable are in opposite order var_val4D[lat, lon, forecast_time_index, 0/1/2/3, where 0=CRAIN, 1=SOILW... etc]
updatedDtStr = list_of_ncfiles[0].split('__')[0]
updatedDt = datetime.datetime.strptime(updatedDtStr,'%Y%m%d_%H%M%S')
updatedDtDisplay = datetime.datetime.strftime(updatedDt, '%Y-%m-%dT%H%M%S')
#get the forecast end dt
forecastEndDtStr = list_of_ncfiles[-1].split('__')[1].split('__')[0]
forecastEndDt = datetime.datetime.strptime(forecastEndDtStr,'%Y%m%d_%H%M%S')
forecastEndDtDisplay = datetime.datetime.strftime(forecastEndDt, '%Y-%m-%dT%H%M%S')
i=0
for varName in varList:
tm_arr = []
print('Reading data for :'+varName)
j=0
for f in list_of_ncfiles:
#f = '20211209_000000__20211212_210000__093___gfs.t00z.pgrb2.0p25.f093.grb2.nc'
ncin = Dataset(outDir+f, "r")
titleStr = varDict[varName]
var_mat = ncin.variables[varName][:]
if 'Temp' in titleStr:
var_val = var_mat.squeeze() - 273.15 #convert to DegC
else:
var_val = var_mat.squeeze()
lons = ncin.variables['longitude'][:]
lats = ncin.variables['latitude'][:]
tms = ncin.variables['time'][:]
#tmstmpStr = datetime.datetime.fromtimestamp(tm.data[0]).strftime('%Y%m%d%H%M%S')
if j>0:
var_val3D = np.dstack((var_val3D,var_val.data))
else:
var_val3D = var_val.data
tm_arr.append(tms.data[0])
ncin.close()
j=j+1
if i>0:
var_val3D_rshp = np.reshape(var_val3D , (720,1440,time_dim,1))
var_val4D = np.append( var_val3D_rshp , var_val4D , axis = 3)
else:
var_val4D = np.reshape(var_val3D , (720,1440,time_dim,1))
i=i+1
def getWeatherForecastVars():
weatherForecastVars = {}
weatherForecastVars['source'] = 'United States NOAA - NOMADS Global Forecast Model'
weatherForecastVars['variables'] = list(varDict.values())
weatherForecastVars['updated at time [UTC]'] = updatedDt
weatherForecastVars['forecast start time [UTC]'] = updatedDtDisplay
weatherForecastVars['forecast end time [UTC]'] = forecastEndDtDisplay
weatherForecastVars['forecast type'] = 'hourly'
weatherForecastVars['Number of time intervals'] = time_dim
return weatherForecastVars
def getWeatherForecast(lon, lat):
df = pd.DataFrame()
try:
lat = float(lat)
lon = float(lon)
varList = list(varDict.keys())
df = pd.DataFrame()
idx=0
updated_dtStr = list_of_ncfiles[0].split('__')[0]
updated_dt = datetime.datetime.strptime(updated_dtStr, '%Y%m%d_%H%M%S')
for f in list_of_ncfiles:
dtStr = f.split('__')[1]
forecast_dt = datetime.datetime.strptime(dtStr, '%Y%m%d_%H%M%S')
#print([f,updated_dt, forecast_dt])
ncin = Dataset(outDir+f, "r")
#valList = list(ncin.variables.keys())
#extract the variable of interest from the list
for varName in varList:
titleStr = varDict[varName]
var_mat = ncin.variables[varName][:]
if 'Temp' in titleStr:
var_val = var_mat.squeeze() - 273.15 #convert to DegC
else:
var_val = var_mat.squeeze()
lons = ncin.variables['longitude'][:]
lats = ncin.variables['latitude'][:]
lon_ind = [i for i,v in enumerate(lons.data) if v >= lon][0]
lat_ind = [i for i,v in enumerate(lats.data) if v >= lat][0]
vv = var_val[lat_ind, lon_ind]
df.loc[idx,'UPDATED_DATE_UTC']=updated_dt
df.loc[idx,'FORECAST_DATE_UTC']=forecast_dt
df.loc[idx,'MEASURE']=titleStr
df.loc[idx,'lon']=lon
df.loc[idx,'lat']=lat
df.loc[idx,'VALUE']=vv
idx=idx+1
ncin.close()
except Exception as e:
print(e)
return df
def get4DWeatherForecast(lon, lat):
df_all = pd.DataFrame()
try:
lat = float(lat)
lon = float(lon)
idx=3
updated_dtStr = list_of_ncfiles[0].split('__')[0]
updated_dt = datetime.datetime.strptime(updated_dtStr, '%Y%m%d_%H%M%S')
df_all = pd.DataFrame()
updated_dts = [updated_dt for x in range(0,len(tm_arr))]
forecast_dts = [datetime.datetime.utcfromtimestamp(int(x)) for x in tm_arr]
df_all['UPDATED_DATE_UTC']=updated_dts
df_all['FORECAST_DATE_UTC']=forecast_dts
for varName in varList:
df = pd.DataFrame()
print(varName)
#try:
titleStr = varDict[varName]
lon_ind = [i for i,v in enumerate(lons.data) if v >= lon][0]
lat_ind = [i for i,v in enumerate(lats.data) if v >= lat][0]
vv = var_val4D[lat_ind, lon_ind,:,idx]
df[titleStr]=vv
df_all = pd.concat([df_all, df],axis=1)
idx=idx-1
except Exception as e:
print(e)
return df_all
############
#create the app
app = Flask(__name__)
app.config['JSON_SORT_KEYS']=False
error_res = {}
#rendering the entry using any of these routes:
@app.route('/')
@app.route('/index')
@app.route('/home')
def index():
return render_template('index.html')
#global weather forecast implementation
@app.route('/weatherForecastVariables')
def weatherForecastVariables():
try:
weatherForcastVars = getWeatherForecastVars()
except ValueError:
error_res['db function call error'] = 'function call failed for getWeatherForecastVars'
error_msg = jsonify(error_res)
return jsonify(weatherForcastVars)
#global weather forecast implementation
@app.route('/weatherForecast')
def weatherForecast():
lat = request.args.get('lat')
lon = request.args.get('lon')
try:
weatherForcast_df = get4DWeatherForecast(lon, lat)
except ValueError:
error_res['db function call error'] = 'DB function call failed for getWeatherForecast'
error_res['value given'] = 'lat='+str(lat)+', lon='+(str(lon))
error_msg = jsonify(error_res)
if len(weatherForcast_df)>0:
res = jsonify(weatherForcast_df.to_dict(orient='records'))
else:
res = "{'Error': 'WeatherForecast function returned no data'}"
return res
#main to run the app
if __name__ == '__main__':
extra_files = [updated_data_available_file,]
"""
#For auto-reload if anyhing changes in the entire directory do the following:
extra_dirs = [outDir,]
extra_files = extra_dirs[:]
for extra_dir in extra_dirs:
for dirname, dirs, files in walk(extra_dir):
for filename in files:
filename = path.join(dirname, filename)
if path.isfile(filename):
extra_files.append(filename)
"""
app.run(host='0.0.0.0' , port=5000, debug=True, extra_files=extra_files)
|
[
"datetime.datetime.strftime",
"pandas.DataFrame",
"netCDF4.Dataset",
"numpy.dstack",
"flask.request.args.get",
"flask.Flask",
"numpy.append",
"datetime.datetime.strptime",
"flask.jsonify",
"numpy.reshape",
"flask.render_template",
"pandas.concat",
"os.listdir"
] |
[((2025, 2082), 'datetime.datetime.strptime', 'datetime.datetime.strptime', (['updatedDtStr', '"""%Y%m%d_%H%M%S"""'], {}), "(updatedDtStr, '%Y%m%d_%H%M%S')\n", (2051, 2082), False, 'import datetime\n'), ((2101, 2157), 'datetime.datetime.strftime', 'datetime.datetime.strftime', (['updatedDt', '"""%Y-%m-%dT%H%M%S"""'], {}), "(updatedDt, '%Y-%m-%dT%H%M%S')\n", (2127, 2157), False, 'import datetime\n'), ((2269, 2330), 'datetime.datetime.strptime', 'datetime.datetime.strptime', (['forecastEndDtStr', '"""%Y%m%d_%H%M%S"""'], {}), "(forecastEndDtStr, '%Y%m%d_%H%M%S')\n", (2295, 2330), False, 'import datetime\n'), ((2353, 2413), 'datetime.datetime.strftime', 'datetime.datetime.strftime', (['forecastEndDt', '"""%Y-%m-%dT%H%M%S"""'], {}), "(forecastEndDt, '%Y-%m-%dT%H%M%S')\n", (2379, 2413), False, 'import datetime\n'), ((6224, 6239), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (6229, 6239), False, 'from flask import Flask, render_template, jsonify, request, url_for\n'), ((3975, 3989), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (3987, 3989), True, 'import pandas as pd\n'), ((5338, 5352), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (5350, 5352), True, 'import pandas as pd\n'), ((6418, 6447), 'flask.render_template', 'render_template', (['"""index.html"""'], {}), "('index.html')\n", (6433, 6447), False, 'from flask import Flask, render_template, jsonify, request, url_for\n'), ((6769, 6796), 'flask.jsonify', 'jsonify', (['weatherForcastVars'], {}), '(weatherForcastVars)\n', (6776, 6796), False, 'from flask import Flask, render_template, jsonify, request, url_for\n'), ((6899, 6922), 'flask.request.args.get', 'request.args.get', (['"""lat"""'], {}), "('lat')\n", (6915, 6922), False, 'from flask import Flask, render_template, jsonify, request, url_for\n'), ((6930, 6953), 'flask.request.args.get', 'request.args.get', (['"""lon"""'], {}), "('lon')\n", (6946, 6953), False, 'from flask import Flask, render_template, jsonify, request, url_for\n'), ((1266, 1284), 'os.listdir', 'os.listdir', (['outDir'], {}), '(outDir)\n', (1276, 1284), False, 'import os\n'), ((2619, 2643), 'netCDF4.Dataset', 'Dataset', (['(outDir + f)', '"""r"""'], {}), "(outDir + f, 'r')\n", (2626, 2643), False, 'from netCDF4 import Dataset\n'), ((3210, 3257), 'numpy.reshape', 'np.reshape', (['var_val3D', '(720, 1440, time_dim, 1)'], {}), '(var_val3D, (720, 1440, time_dim, 1))\n', (3220, 3257), True, 'import numpy as np\n'), ((3270, 3314), 'numpy.append', 'np.append', (['var_val3D_rshp', 'var_val4D'], {'axis': '(3)'}), '(var_val3D_rshp, var_val4D, axis=3)\n', (3279, 3314), True, 'import numpy as np\n'), ((3341, 3388), 'numpy.reshape', 'np.reshape', (['var_val3D', '(720, 1440, time_dim, 1)'], {}), '(var_val3D, (720, 1440, time_dim, 1))\n', (3351, 3388), True, 'import numpy as np\n'), ((4078, 4092), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (4090, 4092), True, 'import pandas as pd\n'), ((4168, 4226), 'datetime.datetime.strptime', 'datetime.datetime.strptime', (['updated_dtStr', '"""%Y%m%d_%H%M%S"""'], {}), "(updated_dtStr, '%Y%m%d_%H%M%S')\n", (4194, 4226), False, 'import datetime\n'), ((5473, 5531), 'datetime.datetime.strptime', 'datetime.datetime.strptime', (['updated_dtStr', '"""%Y%m%d_%H%M%S"""'], {}), "(updated_dtStr, '%Y%m%d_%H%M%S')\n", (5499, 5531), False, 'import datetime\n'), ((5544, 5558), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (5556, 5558), True, 'import pandas as pd\n'), ((3057, 3093), 'numpy.dstack', 'np.dstack', (['(var_val3D, var_val.data)'], {}), '((var_val3D, var_val.data))\n', (3066, 3093), True, 'import numpy as np\n'), ((4300, 4350), 'datetime.datetime.strptime', 'datetime.datetime.strptime', (['dtStr', '"""%Y%m%d_%H%M%S"""'], {}), "(dtStr, '%Y%m%d_%H%M%S')\n", (4326, 4350), False, 'import datetime\n'), ((4405, 4429), 'netCDF4.Dataset', 'Dataset', (['(outDir + f)', '"""r"""'], {}), "(outDir + f, 'r')\n", (4412, 4429), False, 'from netCDF4 import Dataset\n'), ((5815, 5829), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (5827, 5829), True, 'import pandas as pd\n'), ((6091, 6122), 'pandas.concat', 'pd.concat', (['[df_all, df]'], {'axis': '(1)'}), '([df_all, df], axis=1)\n', (6100, 6122), True, 'import pandas as pd\n'), ((6741, 6759), 'flask.jsonify', 'jsonify', (['error_res'], {}), '(error_res)\n', (6748, 6759), False, 'from flask import Flask, render_template, jsonify, request, url_for\n'), ((7202, 7220), 'flask.jsonify', 'jsonify', (['error_res'], {}), '(error_res)\n', (7209, 7220), False, 'from flask import Flask, render_template, jsonify, request, url_for\n')]
|
# -*- coding: utf-8 -*-
# Copyright (c) 2016-2022 by University of Kassel and Fraunhofer Institute for Energy Economics
# and Energy System Technology (IEE), Kassel. All rights reserved.
import numpy as np
import pandas as pd
from pandapower.shortcircuit.idx_brch import IKSS_F, IKSS_T, IP_F, IP_T, ITH_F, ITH_T
from pandapower.shortcircuit.idx_bus import IKSS1, IP, ITH, IKSS2, R_EQUIV_OHM, X_EQUIV_OHM, SKSS
from pandapower.pypower.idx_bus import BUS_TYPE, BASE_KV
BRANCH_RESULTS_KEYS = ("branch_ikss_f", "branch_ikss_t",
"branch_ip_f", "branch_ip_t",
"branch_ith_f", "branch_ith_t")
def _copy_result_to_ppci_orig(ppci_orig, ppci, ppci_bus, calc_options):
if ppci_orig is ppci:
return
ppci_orig["bus"][ppci_bus, :] = ppci["bus"][ppci_bus, :]
if calc_options["branch_results"]:
if calc_options["return_all_currents"]:
ppci_orig["internal"]["br_res_ks_ppci_bus"] =\
ppci_bus if "br_res_ks_ppci_bus" not in ppci_orig["internal"]\
else np.r_[ppci_orig["internal"]["br_res_ks_ppci_bus"], ppci_bus]
for res_key in BRANCH_RESULTS_KEYS:
# Skip not required data points
if res_key not in ppci["internal"]:
continue
if res_key not in ppci_orig["internal"]:
ppci_orig["internal"][res_key] = ppci["internal"][res_key]
else:
ppci_orig["internal"][res_key] = np.c_[ppci_orig["internal"][res_key],
ppci["internal"][res_key]]
else:
case = calc_options["case"]
branch_results_cols = [IKSS_F, IKSS_T, IP_F, IP_T, ITH_F, ITH_T]
if case == "max":
ppci_orig["branch"][:, branch_results_cols] =\
np.maximum(np.nan_to_num(ppci["branch"][:, branch_results_cols]),
np.nan_to_num(ppci_orig["branch"][:, branch_results_cols]))
else:
ppci_orig["branch"][:, branch_results_cols] =\
np.minimum(np.nan_to_num(ppci["branch"][:, branch_results_cols], nan=1e10),
np.nan_to_num(ppci_orig["branch"][:, branch_results_cols], nan=1e10))
def _get_bus_ppc_idx_for_br_all_results(net, ppc, bus):
bus_lookup = net._pd2ppc_lookups["bus"]
if bus is None:
bus = net.bus.index
ppc_index = bus_lookup[bus]
ppc_index[ppc["bus"][ppc_index, BUS_TYPE] == 4] = -1
return bus, ppc_index
def _extract_results(net, ppc, ppc_0, bus):
_get_bus_results(net, ppc, ppc_0, bus)
if net._options["branch_results"]:
if net._options['return_all_currents']:
_get_line_all_results(net, ppc, bus)
_get_trafo_all_results(net, ppc, bus)
_get_trafo3w_all_results(net, ppc, bus)
else:
_get_line_results(net, ppc)
_get_trafo_results(net, ppc)
_get_trafo3w_results(net, ppc)
def _get_bus_results(net, ppc, ppc_0, bus):
bus_lookup = net._pd2ppc_lookups["bus"]
ppc_index = bus_lookup[net.bus.index]
if net["_options"]["fault"] == "1ph":
net.res_bus_sc["ikss_ka"] = ppc_0["bus"][ppc_index, IKSS1] + ppc["bus"][ppc_index, IKSS2]
net.res_bus_sc["rk0_ohm"] = ppc_0["bus"][ppc_index, R_EQUIV_OHM]
net.res_bus_sc["xk0_ohm"] = ppc_0["bus"][ppc_index, X_EQUIV_OHM]
# in trafo3w, we add very high numbers (1e10) as impedances to block current
# here, we need to replace such high values by np.inf
baseZ = ppc_0["bus"][ppc_index, BASE_KV] ** 2 / ppc_0["baseMVA"]
net.res_bus_sc["xk0_ohm"].loc[net.res_bus_sc["xk0_ohm"]/baseZ > 1e9] = np.inf
net.res_bus_sc["rk0_ohm"].loc[net.res_bus_sc["rk0_ohm"]/baseZ > 1e9] = np.inf
else:
net.res_bus_sc["ikss_ka"] = ppc["bus"][ppc_index, IKSS1] + ppc["bus"][ppc_index, IKSS2]
net.res_bus_sc["skss_mw"] = ppc["bus"][ppc_index, SKSS]
if net._options["ip"]:
net.res_bus_sc["ip_ka"] = ppc["bus"][ppc_index, IP]
if net._options["ith"]:
net.res_bus_sc["ith_ka"] = ppc["bus"][ppc_index, ITH]
# Export also equivalent rk, xk on the calculated bus
net.res_bus_sc["rk_ohm"] = ppc["bus"][ppc_index, R_EQUIV_OHM]
net.res_bus_sc["xk_ohm"] = ppc["bus"][ppc_index, X_EQUIV_OHM]
# if for some reason (e.g. contribution of ext_grid set close to 0) we used very high values for rk, xk, we replace them by np.inf
baseZ = ppc["bus"][ppc_index, BASE_KV] ** 2 / ppc["baseMVA"]
net.res_bus_sc["rk_ohm"].loc[net.res_bus_sc["rk_ohm"] / baseZ > 1e9] = np.inf
net.res_bus_sc["xk_ohm"].loc[net.res_bus_sc["xk_ohm"] / baseZ > 1e9] = np.inf
net.res_bus_sc = net.res_bus_sc.loc[bus, :]
def _get_line_results(net, ppc):
branch_lookup = net._pd2ppc_lookups["branch"]
case = net._options["case"]
if "line" in branch_lookup:
f, t = branch_lookup["line"]
minmax = np.max if case == "max" else np.min
net.res_line_sc["ikss_ka"] = minmax(ppc["branch"][f:t, [IKSS_F, IKSS_T]].real, axis=1)
if net._options["ip"]:
net.res_line_sc["ip_ka"] = minmax(ppc["branch"][f:t, [IP_F, IP_T]].real, axis=1)
if net._options["ith"]:
net.res_line_sc["ith_ka"] = minmax(ppc["branch"][f:t, [ITH_F, ITH_T]].real, axis=1)
def _get_line_all_results(net, ppc, bus):
case = net._options["case"]
bus, ppc_index = _get_bus_ppc_idx_for_br_all_results(net, ppc, bus)
branch_lookup = net._pd2ppc_lookups["branch"]
multindex = pd.MultiIndex.from_product([net.res_line_sc.index, bus], names=['line','bus'])
net.res_line_sc = net.res_line_sc.reindex(multindex)
if "line" in branch_lookup:
f, t = branch_lookup["line"]
minmax = np.maximum if case == "max" else np.minimum
net.res_line_sc["ikss_ka"] = minmax(ppc["internal"]["branch_ikss_f"].iloc[f:t,:].loc[:, ppc_index].values.real.reshape(-1, 1),
ppc["internal"]["branch_ikss_t"].iloc[f:t,:].loc[:, ppc_index].values.real.reshape(-1, 1))
if net._options["ip"]:
net.res_line_sc["ip_ka"] = minmax(ppc["internal"]["branch_ip_f"].iloc[f:t,:].loc[:, ppc_index].values.real.reshape(-1, 1),
ppc["internal"]["branch_ip_t"].iloc[f:t,:].loc[:, ppc_index].values.real.reshape(-1, 1))
if net._options["ith"]:
net.res_line_sc["ith_ka"] = minmax(ppc["internal"]["branch_ith_f"].iloc[f:t,:].loc[:, ppc_index].values.real.reshape(-1, 1),
ppc["internal"]["branch_ith_t"].iloc[f:t,:].loc[:, ppc_index].values.real.reshape(-1, 1))
def _get_trafo_results(net, ppc):
branch_lookup = net._pd2ppc_lookups["branch"]
if "trafo" in branch_lookup:
f, t = branch_lookup["trafo"]
net.res_trafo_sc["ikss_hv_ka"] = ppc["branch"][f:t, IKSS_F].real
net.res_trafo_sc["ikss_lv_ka"] = ppc["branch"][f:t, IKSS_T].real
def _get_trafo_all_results(net, ppc, bus):
bus, ppc_index = _get_bus_ppc_idx_for_br_all_results(net, ppc, bus)
branch_lookup = net._pd2ppc_lookups["branch"]
multindex = pd.MultiIndex.from_product([net.res_trafo_sc.index, bus], names=['trafo', 'bus'])
net.res_trafo_sc = net.res_trafo_sc.reindex(multindex)
if "trafo" in branch_lookup:
f, t = branch_lookup["trafo"]
net.res_trafo_sc["ikss_hv_ka"] = ppc["internal"]["branch_ikss_f"].iloc[f:t,:].loc[:, ppc_index].values.real.reshape(-1, 1)
net.res_trafo_sc["ikss_lv_ka"] = ppc["internal"]["branch_ikss_t"].iloc[f:t,:].loc[:, ppc_index].values.real.reshape(-1, 1)
def _get_trafo3w_results(net, ppc):
branch_lookup = net._pd2ppc_lookups["branch"]
if "trafo3w" in branch_lookup:
f, t = net._pd2ppc_lookups["branch"]["trafo3w"]
hv = int(f + (t - f) / 3)
mv = int(f + 2 * (t - f) / 3)
lv = t
net.res_trafo3w_sc["ikss_hv_ka"] = ppc["branch"][f:hv, IKSS_F].real
net.res_trafo3w_sc["ikss_mv_ka"] = ppc["branch"][hv:mv, IKSS_T].real
net.res_trafo3w_sc["ikss_lv_ka"] = ppc["branch"][mv:lv, IKSS_T].real
def _get_trafo3w_all_results(net, ppc, bus):
bus, ppc_index = _get_bus_ppc_idx_for_br_all_results(net, ppc, bus)
branch_lookup = net._pd2ppc_lookups["branch"]
multindex = pd.MultiIndex.from_product([net.res_trafo3w_sc.index, bus], names=['trafo3w', 'bus'])
net.res_trafo3w_sc = net.res_trafo3w_sc.reindex(multindex)
if "trafo3w" in branch_lookup:
f, t = branch_lookup["trafo3w"]
hv = int(f + (t - f) / 3)
mv = int(f + 2 * (t - f) / 3)
lv = t
net.res_trafo3w_sc["ikss_hv_ka"] = ppc["internal"]["branch_ikss_f"].iloc[f:hv,:].loc[:, ppc_index].values.real.reshape(-1, 1)
net.res_trafo3w_sc["ikss_mv_ka"] = ppc["internal"]["branch_ikss_t"].iloc[hv:mv, :].loc[:, ppc_index].values.real.reshape(-1, 1)
net.res_trafo3w_sc["ikss_lv_ka"] = ppc["internal"]["branch_ikss_t"].iloc[mv:lv, :].loc[:, ppc_index].values.real.reshape(-1, 1)
|
[
"pandas.MultiIndex.from_product",
"numpy.nan_to_num"
] |
[((5733, 5812), 'pandas.MultiIndex.from_product', 'pd.MultiIndex.from_product', (['[net.res_line_sc.index, bus]'], {'names': "['line', 'bus']"}), "([net.res_line_sc.index, bus], names=['line', 'bus'])\n", (5759, 5812), True, 'import pandas as pd\n'), ((7392, 7477), 'pandas.MultiIndex.from_product', 'pd.MultiIndex.from_product', (['[net.res_trafo_sc.index, bus]'], {'names': "['trafo', 'bus']"}), "([net.res_trafo_sc.index, bus], names=['trafo',\n 'bus'])\n", (7418, 7477), True, 'import pandas as pd\n'), ((8574, 8664), 'pandas.MultiIndex.from_product', 'pd.MultiIndex.from_product', (['[net.res_trafo3w_sc.index, bus]'], {'names': "['trafo3w', 'bus']"}), "([net.res_trafo3w_sc.index, bus], names=[\n 'trafo3w', 'bus'])\n", (8600, 8664), True, 'import pandas as pd\n'), ((1932, 1985), 'numpy.nan_to_num', 'np.nan_to_num', (["ppci['branch'][:, branch_results_cols]"], {}), "(ppci['branch'][:, branch_results_cols])\n", (1945, 1985), True, 'import numpy as np\n'), ((2019, 2077), 'numpy.nan_to_num', 'np.nan_to_num', (["ppci_orig['branch'][:, branch_results_cols]"], {}), "(ppci_orig['branch'][:, branch_results_cols])\n", (2032, 2077), True, 'import numpy as np\n'), ((2194, 2266), 'numpy.nan_to_num', 'np.nan_to_num', (["ppci['branch'][:, branch_results_cols]"], {'nan': '(10000000000.0)'}), "(ppci['branch'][:, branch_results_cols], nan=10000000000.0)\n", (2207, 2266), True, 'import numpy as np\n'), ((2291, 2368), 'numpy.nan_to_num', 'np.nan_to_num', (["ppci_orig['branch'][:, branch_results_cols]"], {'nan': '(10000000000.0)'}), "(ppci_orig['branch'][:, branch_results_cols], nan=10000000000.0)\n", (2304, 2368), True, 'import numpy as np\n')]
|
import numpy as np
import ipyvolume as ipv
import h5py
import os
import matplotlib.pyplot as plt
import sys
from tqdm import tqdm
kinect_dir = '../dataset/kinect/'
dir = '../dataset/data/'
kinect_files = os.listdir(kinect_dir)
missing_file_count = 0
def get_vibe_dir(x):
x1 = x[16,:] - x[0,:]
x2 = x[17,:] - x[0,:]
return np.cross(x1,x2)
def get_kinect_dir(x):
x1 = x[8,:] - x[0,:]
x2 = x[4,:] - x[0,:]
return np.cross(x1, x2)
def get_kinect_peron(i):
# this function returns Kinect skeleton given the index
f = i + '.skeleton.npy'
p = np.zeros((300,2,25,3))
if f not in kinect_files:
# print(f)
pass
else:
kp = np.load(os.path.join(kinect_dir, f))
if kp.shape[0] != 0:
if kp.shape[0] == 1:
p[:,0,:,:] = kp[0,:,:,:]
else:
p[:,0,:,:] = kp[0,:,:,:]
p[:,1,:,:] = kp[1,:,:,:]
return p[:256,:,:,:]
def order_root(kinect_person, vibe):
vibe = vibe.reshape((256, 2, 24, 3))
# kinect_person = kinect_person[::4,:,:,:]
person = vibe[:,:,:]
left = kinect_person[:,0,0,:].reshape((256,1,3))
right = kinect_person[:,1,0,:].reshape((256,1,3))
person1 = person[:,0,:,:] + left
person2 = person[:,1,:,:] + right
v1 = get_vibe_dir(person[0,0,:,:])
v2 = get_vibe_dir(person[0,1,:,:])
v_cross = np.cross(v1, v2)
k1 = get_kinect_dir(kinect_person[0,0,:,:])
k2 = get_kinect_dir(kinect_person[0,1,:,:])
k_cross = np.cross(k1,k2)
dot_prod = np.sum(v_cross*k_cross)
# print(dot_prod)
if dot_prod > 0:
# right direction
return left, right
elif dot_prod < 0:
# Wrong Direction
return right, left
else:
# one person missing
return left, right
def get_root(x, y, train_file_names):
count = 0
root_list = []
# person_2_cls = [50,51,52,53,54,55,56,57,58,59,60]
person_2_cls = [50,51,52,53,54,55,56,57,58,59,60,106, 107, 108, 109
,110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120]
for i in tqdm(range(train_file_names.shape[0])):
file_name = train_file_names[i]
if len(file_name) >= 2 and len(file_name) != 20:
file_name = file_name[0]
if str(file_name)[0] == '[':
file_name = file_name[0]
root = np.zeros((256, 2, 3))
if y[i] in person_2_cls:
p = get_kinect_peron(file_name)
left, right = order_root(p, x[i])
if y[i] == 60:
root[:,0:1,:] = right
root[:,1:,:] = left
else:
root[:,0:1,:] = left
root[:,1:,:] = right
root_list.append(root)
return np.array(root_list)
if __name__ == '__main__':
f = h5py.File(os.path.join(dir, 'NTU_VIBE_CSet_120.h5'), 'r')
# train data
x = f['x'][:]
y = f['y'][:]
train_file_names = np.load(os.path.join(dir, 'Train_File_order.npy'), allow_pickle=True)
# print(x.shape)
train_root = get_root(x, y, train_file_names)
print(train_root.shape)
np.save(dir + 'Train_root.npy', train_root)
# test data
# test_x = f['test_x'][:]
# test_y = f['test_y'][:]
# test_file_names = np.load(os.path.join(dir, 'Test_File_order.npy'), allow_pickle=True)
# test_root = get_root(test_x, test_y, test_file_names)
# print(test_root.shape)
# np.save(dir + 'Test_root.npy', test_root)
|
[
"numpy.save",
"numpy.sum",
"numpy.zeros",
"numpy.cross",
"numpy.array",
"os.path.join",
"os.listdir"
] |
[((206, 228), 'os.listdir', 'os.listdir', (['kinect_dir'], {}), '(kinect_dir)\n', (216, 228), False, 'import os\n'), ((337, 353), 'numpy.cross', 'np.cross', (['x1', 'x2'], {}), '(x1, x2)\n', (345, 353), True, 'import numpy as np\n'), ((439, 455), 'numpy.cross', 'np.cross', (['x1', 'x2'], {}), '(x1, x2)\n', (447, 455), True, 'import numpy as np\n'), ((578, 603), 'numpy.zeros', 'np.zeros', (['(300, 2, 25, 3)'], {}), '((300, 2, 25, 3))\n', (586, 603), True, 'import numpy as np\n'), ((1383, 1399), 'numpy.cross', 'np.cross', (['v1', 'v2'], {}), '(v1, v2)\n', (1391, 1399), True, 'import numpy as np\n'), ((1511, 1527), 'numpy.cross', 'np.cross', (['k1', 'k2'], {}), '(k1, k2)\n', (1519, 1527), True, 'import numpy as np\n'), ((1547, 1572), 'numpy.sum', 'np.sum', (['(v_cross * k_cross)'], {}), '(v_cross * k_cross)\n', (1553, 1572), True, 'import numpy as np\n'), ((2769, 2788), 'numpy.array', 'np.array', (['root_list'], {}), '(root_list)\n', (2777, 2788), True, 'import numpy as np\n'), ((3107, 3150), 'numpy.save', 'np.save', (["(dir + 'Train_root.npy')", 'train_root'], {}), "(dir + 'Train_root.npy', train_root)\n", (3114, 3150), True, 'import numpy as np\n'), ((2367, 2388), 'numpy.zeros', 'np.zeros', (['(256, 2, 3)'], {}), '((256, 2, 3))\n', (2375, 2388), True, 'import numpy as np\n'), ((2833, 2874), 'os.path.join', 'os.path.join', (['dir', '"""NTU_VIBE_CSet_120.h5"""'], {}), "(dir, 'NTU_VIBE_CSet_120.h5')\n", (2845, 2874), False, 'import os\n'), ((2954, 2995), 'os.path.join', 'os.path.join', (['dir', '"""Train_File_order.npy"""'], {}), "(dir, 'Train_File_order.npy')\n", (2966, 2995), False, 'import os\n'), ((694, 721), 'os.path.join', 'os.path.join', (['kinect_dir', 'f'], {}), '(kinect_dir, f)\n', (706, 721), False, 'import os\n')]
|
# %% [markdown]
# #
import os
import pickle
import warnings
from operator import itemgetter
from pathlib import Path
from timeit import default_timer as timer
import colorcet as cc
import community as cm
import matplotlib.colors as mplc
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import pandas as pd
import seaborn as sns
from joblib import Parallel, delayed
from matplotlib.cm import ScalarMappable
from sklearn.model_selection import ParameterGrid
from graspy.embed import AdjacencySpectralEmbed, LaplacianSpectralEmbed
from graspy.plot import gridplot, heatmap, pairplot
from graspy.utils import symmetrize
from src.data import load_everything, load_metagraph, load_networkx
from src.embed import lse, preprocess_graph
from src.graph import MetaGraph, preprocess
from src.hierarchy import signal_flow
from src.io import savefig, saveobj, saveskels, savecsv
from src.utils import get_blockmodel_df, get_sbm_prob
from src.visualization import (
CLASS_COLOR_DICT,
CLASS_IND_DICT,
barplot_text,
bartreeplot,
draw_networkx_nice,
get_color_dict,
get_colors,
palplot,
probplot,
sankey,
screeplot,
stacked_barplot,
random_names,
)
FNAME = os.path.basename(__file__)[:-3]
print(FNAME)
# %% [markdown]
# # Parameters
BRAIN_VERSION = "2020-03-02"
BLIND = True
SAVEFIGS = False
SAVESKELS = False
SAVEOBJS = True
np.random.seed(9812343)
sns.set_context("talk")
def stashfig(name, **kws):
savefig(name, foldername=FNAME, save_on=True, **kws)
plt.close()
def stashcsv(df, name, **kws):
savecsv(df, name, foldername=FNAME, save_on=True, **kws)
def stashskel(name, ids, labels, colors=None, palette=None, **kws):
saveskels(
name,
ids,
labels,
colors=colors,
palette=None,
foldername=FNAME,
save_on=SAVESKELS,
**kws,
)
def stashobj(obj, name, **kws):
saveobj(obj, name, foldername=FNAME, save_on=SAVEOBJS, **kws)
graph_type = "G"
threshold = 3
binarize = True
# load and preprocess the data
mg = load_metagraph(graph_type, version=BRAIN_VERSION)
mg = preprocess(
mg, threshold=threshold, sym_threshold=True, remove_pdiff=True, binarize=binarize
)
#%%
import leidenalg as la
import igraph as ig
def _process_metagraph(mg, temp_loc):
adj = mg.adj
adj = symmetrize(adj, method="avg")
mg = MetaGraph(adj, mg.meta)
nx.write_graphml(mg.g, temp_loc)
def run_leiden(
mg,
temp_loc=None,
implementation="igraph",
partition_type=la.CPMVertexPartition,
**kws,
):
if temp_loc is None:
temp_loc = f"maggot_models/data/interim/temp-{np.random.randint(1e8)}.graphml"
else:
temp_loc = f"maggot_models/data/interim/{temp_loc}.graphml"
_process_metagraph(mg, temp_loc)
g = ig.Graph.Read_GraphML(temp_loc)
os.remove(temp_loc)
nodes = [int(v["id"]) for v in g.vs]
if implementation == "igraph":
vert_part = g.community_leiden(**kws)
elif implementation == "leidenalg":
vert_part = la.find_partition(g, partition_type, **kws)
labels = vert_part.membership
partition = pd.Series(data=labels, index=nodes)
return partition, vert_part.modularity
# %% [markdown]
# #
temp_loc = f"maggot_models/data/interim/temp-{np.random.randint(1e8)}.graphml"
_process_metagraph(mg, temp_loc)
g = ig.Graph.Read_GraphML(temp_loc)
os.remove(temp_loc)
nodes = [int(v["id"]) for v in g.vs]
vert_part = g.community_multilevel()
labels = vert_part.membership
partition = pd.Series(data=labels, index=nodes)
# %% [markdown]
# #
partition, modularity = run_leiden(
mg,
implementation="igraph",
resolution_parameter=0.1,
beta=0.1,
partition_type=la.CPMVertexPartition,
weights="weight",
n_iterations=-1,
)
print(partition.nunique())
# %% [markdown]
# #
pred_labels = partition
pred_labels = pred_labels[pred_labels.index.isin(mg.meta.index)]
partition = pred_labels.astype(int)
class_labels = mg["Merge Class"]
lineage_labels = mg["lineage"]
basename = ""
title = ""
def augment_classes(class_labels, lineage_labels, fill_unk=True):
if fill_unk:
classlin_labels = class_labels.copy()
fill_inds = np.where(class_labels == "unk")[0]
classlin_labels[fill_inds] = lineage_labels[fill_inds]
used_inds = np.array(list(CLASS_IND_DICT.values()))
unused_inds = np.setdiff1d(range(len(cc.glasbey_light)), used_inds)
lineage_color_dict = dict(
zip(np.unique(lineage_labels), np.array(cc.glasbey_light)[unused_inds])
)
color_dict = {**CLASS_COLOR_DICT, **lineage_color_dict}
hatch_dict = {}
for key, val in color_dict.items():
if key[0] == "~":
hatch_dict[key] = "//"
else:
hatch_dict[key] = ""
else:
color_dict = "class"
hatch_dict = None
return classlin_labels, color_dict, hatch_dict
lineage_labels = np.vectorize(lambda x: "~" + x)(lineage_labels)
classlin_labels, color_dict, hatch_dict = augment_classes(class_labels, lineage_labels)
# TODO then sort all of them by proportion of sensory/motor
# barplot by merge class and lineage
_, _, order = barplot_text(
partition,
classlin_labels,
color_dict=color_dict,
plot_proportions=False,
norm_bar_width=True,
figsize=(24, 18),
title=title,
hatch_dict=hatch_dict,
return_order=True,
)
stashfig(basename + "barplot-mergeclasslin-props")
plt.close()
category_order = np.unique(partition)[order]
fig, axs = barplot_text(
partition,
class_labels,
color_dict=color_dict,
plot_proportions=False,
norm_bar_width=True,
figsize=(24, 18),
title=title,
hatch_dict=None,
category_order=category_order,
)
stashfig(basename + "barplot-mergeclass-props")
fig, axs = barplot_text(
partition,
class_labels,
color_dict=color_dict,
plot_proportions=False,
norm_bar_width=False,
figsize=(24, 18),
title=title,
hatch_dict=None,
category_order=category_order,
)
stashfig(basename + "barplot-mergeclass-counts")
plt.close()
# TODO add gridmap
counts = False
weights = False
prob_df = get_blockmodel_df(
mg.adj, partition, return_counts=counts, use_weights=weights
)
prob_df = prob_df.reindex(category_order, axis=0)
prob_df = prob_df.reindex(category_order, axis=1)
probplot(100 * prob_df, fmt="2.0f", figsize=(20, 20), title=title, font_scale=0.7)
stashfig(basename + f"probplot-counts{counts}-weights{weights}")
plt.close()
|
[
"os.remove",
"numpy.random.seed",
"src.io.savefig",
"src.io.saveskels",
"src.graph.MetaGraph",
"igraph.Graph.Read_GraphML",
"numpy.random.randint",
"numpy.unique",
"src.graph.preprocess",
"matplotlib.pyplot.close",
"seaborn.set_context",
"numpy.vectorize",
"os.path.basename",
"src.visualization.barplot_text",
"pandas.Series",
"src.visualization.probplot",
"graspy.utils.symmetrize",
"src.io.saveobj",
"src.utils.get_blockmodel_df",
"src.data.load_metagraph",
"leidenalg.find_partition",
"numpy.where",
"numpy.array",
"src.io.savecsv",
"src.visualization.CLASS_IND_DICT.values",
"networkx.write_graphml"
] |
[((1392, 1415), 'numpy.random.seed', 'np.random.seed', (['(9812343)'], {}), '(9812343)\n', (1406, 1415), True, 'import numpy as np\n'), ((1416, 1439), 'seaborn.set_context', 'sns.set_context', (['"""talk"""'], {}), "('talk')\n", (1431, 1439), True, 'import seaborn as sns\n'), ((2069, 2118), 'src.data.load_metagraph', 'load_metagraph', (['graph_type'], {'version': 'BRAIN_VERSION'}), '(graph_type, version=BRAIN_VERSION)\n', (2083, 2118), False, 'from src.data import load_everything, load_metagraph, load_networkx\n'), ((2124, 2221), 'src.graph.preprocess', 'preprocess', (['mg'], {'threshold': 'threshold', 'sym_threshold': '(True)', 'remove_pdiff': '(True)', 'binarize': 'binarize'}), '(mg, threshold=threshold, sym_threshold=True, remove_pdiff=True,\n binarize=binarize)\n', (2134, 2221), False, 'from src.graph import MetaGraph, preprocess\n'), ((3354, 3385), 'igraph.Graph.Read_GraphML', 'ig.Graph.Read_GraphML', (['temp_loc'], {}), '(temp_loc)\n', (3375, 3385), True, 'import igraph as ig\n'), ((3386, 3405), 'os.remove', 'os.remove', (['temp_loc'], {}), '(temp_loc)\n', (3395, 3405), False, 'import os\n'), ((3522, 3557), 'pandas.Series', 'pd.Series', ([], {'data': 'labels', 'index': 'nodes'}), '(data=labels, index=nodes)\n', (3531, 3557), True, 'import pandas as pd\n'), ((5202, 5392), 'src.visualization.barplot_text', 'barplot_text', (['partition', 'classlin_labels'], {'color_dict': 'color_dict', 'plot_proportions': '(False)', 'norm_bar_width': '(True)', 'figsize': '(24, 18)', 'title': 'title', 'hatch_dict': 'hatch_dict', 'return_order': '(True)'}), '(partition, classlin_labels, color_dict=color_dict,\n plot_proportions=False, norm_bar_width=True, figsize=(24, 18), title=\n title, hatch_dict=hatch_dict, return_order=True)\n', (5214, 5392), False, 'from src.visualization import CLASS_COLOR_DICT, CLASS_IND_DICT, barplot_text, bartreeplot, draw_networkx_nice, get_color_dict, get_colors, palplot, probplot, sankey, screeplot, stacked_barplot, random_names\n'), ((5474, 5485), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (5483, 5485), True, 'import matplotlib.pyplot as plt\n'), ((5543, 5736), 'src.visualization.barplot_text', 'barplot_text', (['partition', 'class_labels'], {'color_dict': 'color_dict', 'plot_proportions': '(False)', 'norm_bar_width': '(True)', 'figsize': '(24, 18)', 'title': 'title', 'hatch_dict': 'None', 'category_order': 'category_order'}), '(partition, class_labels, color_dict=color_dict,\n plot_proportions=False, norm_bar_width=True, figsize=(24, 18), title=\n title, hatch_dict=None, category_order=category_order)\n', (5555, 5736), False, 'from src.visualization import CLASS_COLOR_DICT, CLASS_IND_DICT, barplot_text, bartreeplot, draw_networkx_nice, get_color_dict, get_colors, palplot, probplot, sankey, screeplot, stacked_barplot, random_names\n'), ((5827, 6021), 'src.visualization.barplot_text', 'barplot_text', (['partition', 'class_labels'], {'color_dict': 'color_dict', 'plot_proportions': '(False)', 'norm_bar_width': '(False)', 'figsize': '(24, 18)', 'title': 'title', 'hatch_dict': 'None', 'category_order': 'category_order'}), '(partition, class_labels, color_dict=color_dict,\n plot_proportions=False, norm_bar_width=False, figsize=(24, 18), title=\n title, hatch_dict=None, category_order=category_order)\n', (5839, 6021), False, 'from src.visualization import CLASS_COLOR_DICT, CLASS_IND_DICT, barplot_text, bartreeplot, draw_networkx_nice, get_color_dict, get_colors, palplot, probplot, sankey, screeplot, stacked_barplot, random_names\n'), ((6101, 6112), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (6110, 6112), True, 'import matplotlib.pyplot as plt\n'), ((6175, 6254), 'src.utils.get_blockmodel_df', 'get_blockmodel_df', (['mg.adj', 'partition'], {'return_counts': 'counts', 'use_weights': 'weights'}), '(mg.adj, partition, return_counts=counts, use_weights=weights)\n', (6192, 6254), False, 'from src.utils import get_blockmodel_df, get_sbm_prob\n'), ((6361, 6447), 'src.visualization.probplot', 'probplot', (['(100 * prob_df)'], {'fmt': '"""2.0f"""', 'figsize': '(20, 20)', 'title': 'title', 'font_scale': '(0.7)'}), "(100 * prob_df, fmt='2.0f', figsize=(20, 20), title=title,\n font_scale=0.7)\n", (6369, 6447), False, 'from src.visualization import CLASS_COLOR_DICT, CLASS_IND_DICT, barplot_text, bartreeplot, draw_networkx_nice, get_color_dict, get_colors, palplot, probplot, sankey, screeplot, stacked_barplot, random_names\n'), ((6509, 6520), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (6518, 6520), True, 'import matplotlib.pyplot as plt\n'), ((1220, 1246), 'os.path.basename', 'os.path.basename', (['__file__'], {}), '(__file__)\n', (1236, 1246), False, 'import os\n'), ((1473, 1525), 'src.io.savefig', 'savefig', (['name'], {'foldername': 'FNAME', 'save_on': '(True)'}), '(name, foldername=FNAME, save_on=True, **kws)\n', (1480, 1525), False, 'from src.io import savefig, saveobj, saveskels, savecsv\n'), ((1530, 1541), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (1539, 1541), True, 'import matplotlib.pyplot as plt\n'), ((1579, 1635), 'src.io.savecsv', 'savecsv', (['df', 'name'], {'foldername': 'FNAME', 'save_on': '(True)'}), '(df, name, foldername=FNAME, save_on=True, **kws)\n', (1586, 1635), False, 'from src.io import savefig, saveobj, saveskels, savecsv\n'), ((1710, 1815), 'src.io.saveskels', 'saveskels', (['name', 'ids', 'labels'], {'colors': 'colors', 'palette': 'None', 'foldername': 'FNAME', 'save_on': 'SAVESKELS'}), '(name, ids, labels, colors=colors, palette=None, foldername=FNAME,\n save_on=SAVESKELS, **kws)\n', (1719, 1815), False, 'from src.io import savefig, saveobj, saveskels, savecsv\n'), ((1921, 1982), 'src.io.saveobj', 'saveobj', (['obj', 'name'], {'foldername': 'FNAME', 'save_on': 'SAVEOBJS'}), '(obj, name, foldername=FNAME, save_on=SAVEOBJS, **kws)\n', (1928, 1982), False, 'from src.io import savefig, saveobj, saveskels, savecsv\n'), ((2340, 2369), 'graspy.utils.symmetrize', 'symmetrize', (['adj'], {'method': '"""avg"""'}), "(adj, method='avg')\n", (2350, 2369), False, 'from graspy.utils import symmetrize\n'), ((2379, 2402), 'src.graph.MetaGraph', 'MetaGraph', (['adj', 'mg.meta'], {}), '(adj, mg.meta)\n', (2388, 2402), False, 'from src.graph import MetaGraph, preprocess\n'), ((2407, 2439), 'networkx.write_graphml', 'nx.write_graphml', (['mg.g', 'temp_loc'], {}), '(mg.g, temp_loc)\n', (2423, 2439), True, 'import networkx as nx\n'), ((2805, 2836), 'igraph.Graph.Read_GraphML', 'ig.Graph.Read_GraphML', (['temp_loc'], {}), '(temp_loc)\n', (2826, 2836), True, 'import igraph as ig\n'), ((2841, 2860), 'os.remove', 'os.remove', (['temp_loc'], {}), '(temp_loc)\n', (2850, 2860), False, 'import os\n'), ((3137, 3172), 'pandas.Series', 'pd.Series', ([], {'data': 'labels', 'index': 'nodes'}), '(data=labels, index=nodes)\n', (3146, 3172), True, 'import pandas as pd\n'), ((4954, 4985), 'numpy.vectorize', 'np.vectorize', (["(lambda x: '~' + x)"], {}), "(lambda x: '~' + x)\n", (4966, 4985), True, 'import numpy as np\n'), ((5503, 5523), 'numpy.unique', 'np.unique', (['partition'], {}), '(partition)\n', (5512, 5523), True, 'import numpy as np\n'), ((3284, 3314), 'numpy.random.randint', 'np.random.randint', (['(100000000.0)'], {}), '(100000000.0)\n', (3301, 3314), True, 'import numpy as np\n'), ((3043, 3086), 'leidenalg.find_partition', 'la.find_partition', (['g', 'partition_type'], {}), '(g, partition_type, **kws)\n', (3060, 3086), True, 'import leidenalg as la\n'), ((4200, 4231), 'numpy.where', 'np.where', (["(class_labels == 'unk')"], {}), "(class_labels == 'unk')\n", (4208, 4231), True, 'import numpy as np\n'), ((2649, 2679), 'numpy.random.randint', 'np.random.randint', (['(100000000.0)'], {}), '(100000000.0)\n', (2666, 2679), True, 'import numpy as np\n'), ((4332, 4355), 'src.visualization.CLASS_IND_DICT.values', 'CLASS_IND_DICT.values', ([], {}), '()\n', (4353, 4355), False, 'from src.visualization import CLASS_COLOR_DICT, CLASS_IND_DICT, barplot_text, bartreeplot, draw_networkx_nice, get_color_dict, get_colors, palplot, probplot, sankey, screeplot, stacked_barplot, random_names\n'), ((4485, 4510), 'numpy.unique', 'np.unique', (['lineage_labels'], {}), '(lineage_labels)\n', (4494, 4510), True, 'import numpy as np\n'), ((4512, 4538), 'numpy.array', 'np.array', (['cc.glasbey_light'], {}), '(cc.glasbey_light)\n', (4520, 4538), True, 'import numpy as np\n')]
|
import numpy as np
from Redbox_v2 import file_manager as fm
import pandas as pd
from scipy.fftpack import rfft, rfftfreq
import matplotlib.pyplot as plt
import os
import math
def rms_time_dom(signal):
N = len(signal)
return math.sqrt(np.sum(np.power(signal,2))/N)
def rms_freq_dom(amplitude):
return math.sqrt(2*np.sum(np.power(amplitude, 2)))/2
def n_minutes_max(signal, dt, n=5):
""""
:param signal (np.array or list)
:param n: n-minutes range to obtain maximum (int)
:param dt: sample space or time between samples
this functions does not return the real time of the occuring
return: numpy array with
"""
maximums = np.zeros(1)
samples = int((n*60)/dt)
start = 0
end = samples
while start < len(signal):
selection = signal[start:end]
maximums = np.append(maximums, [np.amax(selection),np.amin(selection)])
start = end
end = min(len(signal), start + samples)
maximums = np.delete(maximums,0)
return maximums
def n_seconds_min_max(data, dt, n):
"""
:param data = 2D array with t and velocity in one direction
:param dt = sample space or time between samples
:param n = in seconds for which interval maximum value is determined
collect minimum and maximum values of the data over an interval
"""
samples = int(1/dt * n)
start = 0
end = samples
min_max_array = np.zeros([1, 2]) # col 1 = time [s], col 2 = min and max of direction
while start < data.shape[0]:
index_max = start + np.argmax(data[start:end, 1])
index_min = start + np.argmin(data[start:end, 1])
x = np.array([[data[index_max,0], data[index_max,1]], [data[index_min,0], data[index_min,1]]])
min_max_array = np.concatenate((min_max_array, x), axis=0)
start = end
end += samples
min_max_array = np.delete(min_max_array,0,0)
min_max_array = min_max_array[min_max_array[:,0].argsort()]
return min_max_array
def FFT(signal,dT):
"""
:param signal: [array]
:param dT: sample space [float]
"""
ampl = np.abs(rfft(signal)) * 2.0 / len(signal)
freq = rfftfreq(len(ampl),d=dT)
return ampl, freq
def FFT_amplitude(signal):
"""
:param signal: [array]
"""
ampl = np.abs(rfft(signal)) * 2.0 / len(signal)
return ampl
def OneThird_octave(low, high):
""""
:param low: lowest required frequency band
:param high: highest required frequency band
this function starts at the highest band and
"""
one_third_octave = 2**(1/3)
last_band = high
first_band = last_band
N = 0
while first_band > low:
first_band = first_band/one_third_octave
N += 1
first_band = first_band * one_third_octave
return first_band * np.logspace(0, N, endpoint=False, num=N, base=one_third_octave)
def FFT_to_OneThird_Octave(amplitude, df, low, high):
"""
:param amplitude: amplitudes of the FFT [array]
:param frequency: frequencies of the FFT [array]
"""
one_third_octave = 2 ** (1 / 3)
spectrum = OneThird_octave(low, high)
rms_amplitude = np.empty(len(spectrum))
#check if the maximum available frequency exceeds the upper bound
if (df*len(amplitude))*one_third_octave**0.5 > high:
lower_bound = spectrum[0] / one_third_octave ** 0.5
upper_bound = spectrum[0] * one_third_octave ** 0.5
for n in range(rms_amplitude.size):
rms_amplitude[n] = rms_freq_dom(amplitude[int(lower_bound // df)*2:int(upper_bound // df)*2])
lower_bound = lower_bound * one_third_octave
upper_bound = upper_bound * one_third_octave
return rms_amplitude, spectrum
else:
print("ERROR frequency range is not large enough")
return
def FFT_to_OneThird_Octave2(amplitude, df, spectrum):
"""
:param amplitude: amplitudes of the FFT [array]
:param frequency: frequencies of the FFT [array]
"""
one_third_octave = 2 ** (1 / 3)
spectrum = spectrum
rms_amplitude = np.empty(len(spectrum))
high = spectrum[-1]
#check if the maximum available frequency exceeds the upper bound
if (df*len(amplitude))*one_third_octave**0.5 > high:
lower_bound = spectrum[0] / one_third_octave ** 0.5
upper_bound = spectrum[0] * one_third_octave ** 0.5
for n in range(rms_amplitude.size):
rms_amplitude[n] = rms_freq_dom(amplitude[int(lower_bound // df)*2:int(upper_bound // df)*2])
lower_bound = lower_bound * one_third_octave
upper_bound = upper_bound * one_third_octave
return rms_amplitude
else:
print("ERROR frequency range is not large enough")
return
"""
integration and differentiation
"""
def integ_to_disp(vel,dt):
"""
:param vel: velocity obtained from data (np.array)
:return: (np.array) (displacement)
"""
disp = np.zeros(len(vel))
disp = disp[:-1]
for i in range(1, len(disp)):
disp[i] = disp[i - 1] + (vel[i + 1] - vel[i]) * dt
return disp
def diff_to_acc(vel,dt):
"""
:param vel: velocity obtained from data(lst)
:return: (tpl) (acceleration)
"""
acc = np.zeros(len(vel))
acc = acc[:-1]
for i in range(0, len(acc)):
acc[i] = (vel[i + 1] - vel[i]) / dt
return acc
def select_part(start, stop, to_select):
"""
TODO nagaan of deze functie werkelijk nuttig is
:param start: start of selection(flt/int)
:param stop: end time of selection (flt/int)
:return: (tpl) (displacement u, velocity v)
"""
i = int(start / dt)
j = int(stop / dt)
lst = []
for k in range(i,j):
lst.append(to_select[k])
lst_t = np.linspace(start, dt, stop)
return lst_t, lst
""" SBR methods"""
def compute_veff_sbr(v,T,Ts=0.125, a=8):
"""
:param =df = vels (mm/s)
:param = T = sample space (s)
:param a = each a'th sample is used
"""
l = int(np.log2(v.size)+1) #nth-power
N_org = v.size
N = 2**l
t = np.linspace(0,N*T,N,endpoint=False)
v = np.pad(v,(0,N-v.size),'constant')
vibrations_fft = np.fft.fft(v)
f = np.linspace(0, 1 / T, N, endpoint=False)
f_mod=f
f_mod[f<1.0]=0.1
weight = 1 / np.sqrt(1 + (5.6 / f_mod) ** 2)
vibrations_fft_w = weight * vibrations_fft
vibrations_w = np.fft.ifft(vibrations_fft_w).real
t_sel = t[:N_org:a]
vibrations_w = vibrations_w[:N_org:a]
v_sqrd_w = vibrations_w ** 2
v_eff = np.zeros(t_sel.size)
dt = t_sel[1] - t_sel[0]
print('compute v_eff')
for i in range(t_sel.size - 1):
g_xi = np.exp(-t_sel[:i + 1][::-1] / Ts)
v_eff[i] = np.sqrt(1 / Ts * np.trapz(g_xi * v_sqrd_w[:i + 1], dx=dt))
fm.progress(i,t_sel.size-1,"processing %s of %s" % (i + 1, t_sel.size))
idx = np.argmax(v_eff)
return v_eff[idx], t_sel, vibrations_w, v_eff
def plot_SBR_B(save_to_path,vibrations, vibrations_w,v_eff,t_sel):
"""
vibrations, vibrations_w,v_eff are optional arguments
"""
plt.figure(figsize=(10, 6))
if vibrations:
plt.plot(t_sel, vibrations, label="signal")
if vibrations_w:
plt.plot(t_sel, vibrations_w, label="weighted_signal")
if v_eff:
plt.plot(t_sel, v_eff, label="v_eff")
plt.text(t[idx], v_eff[idx], "max v_eff: {}".format(round(v_eff[idx], 3)), color="r")
plt.xlabel("t [s]")
plt.ylabel("v [mm/s]")
plt.title("velocity")
plt.legend()
plt.savefig(save_to_path.format("png"))
plt.show()
def plot_SBR_B_xyz(save_to_path,vibrations, vibrations_w,v_eff,t_sel):
"""
TODO check use of pandas plotting wrapper
vibrations, vibrations_w,v_eff are optional arguments (tpl)
"""
fig = plt.figure(figsize=(10, 18))
ax1 = fig.add_subplot(3,1,1)
ax2 = fig.add_subplot(3,1,2)
ax3 = fig.add_subplot(3,1,3)
if vibrations:
ax1.plot(t_sel, vibrations[0], label="signal")
ax2.plot(t_sel, vibrations[1], label="signal")
ax3.plot(t_sel, vibrations[2], label="signal")
if vibrations_w:
ax1.plot(t_sel, vibrations_w[0], label="weighted_signal")
ax2.plot(t_sel, vibrations_w[1], label="weighted_signal")
ax3.plot(t_sel, vibrations_w[2], label="weighted_signal")
if v_eff:
idx = [np.argmax(v_eff[x]) for x in range(len(v_eff))]
ax1.plot(t_sel, v_eff, label="v_eff")
ax1.text(t[idx[0]], v_eff[0][idx[0]], "max v_eff: {}".format(round(v_eff[idx], 3)), color="r")
ax2.plot(t_sel, v_eff, label="v_eff")
ax2.text(t[idx[1]], v_eff[1][idx[1]], "max v_eff: {}".format(round(v_eff[idx], 3)), color="r")
ax3.plot(t_sel, v_eff, label="v_eff")
ax3.text(t[idx[1]], v_eff[2][idx[2]], "max v_eff: {}".format(round(v_eff[idx], 3)), color="r")
plt.xlabel("t [s]")
plt.ylabel("v [mm/s]")
plt.title("velocity")
plt.legend()
plt.savefig(save_to_path.format("png"))
plt.show()
|
[
"matplotlib.pyplot.title",
"scipy.fftpack.rfft",
"numpy.amin",
"numpy.argmax",
"numpy.logspace",
"numpy.argmin",
"matplotlib.pyplot.figure",
"numpy.exp",
"numpy.pad",
"numpy.fft.fft",
"numpy.power",
"numpy.linspace",
"numpy.fft.ifft",
"numpy.trapz",
"matplotlib.pyplot.show",
"numpy.log2",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.ylabel",
"numpy.delete",
"numpy.concatenate",
"matplotlib.pyplot.plot",
"Redbox_v2.file_manager.progress",
"numpy.zeros",
"numpy.amax",
"numpy.array",
"matplotlib.pyplot.xlabel",
"numpy.sqrt"
] |
[((701, 712), 'numpy.zeros', 'np.zeros', (['(1)'], {}), '(1)\n', (709, 712), True, 'import numpy as np\n'), ((1015, 1037), 'numpy.delete', 'np.delete', (['maximums', '(0)'], {}), '(maximums, 0)\n', (1024, 1037), True, 'import numpy as np\n'), ((1467, 1483), 'numpy.zeros', 'np.zeros', (['[1, 2]'], {}), '([1, 2])\n', (1475, 1483), True, 'import numpy as np\n'), ((1933, 1963), 'numpy.delete', 'np.delete', (['min_max_array', '(0)', '(0)'], {}), '(min_max_array, 0, 0)\n', (1942, 1963), True, 'import numpy as np\n'), ((5924, 5952), 'numpy.linspace', 'np.linspace', (['start', 'dt', 'stop'], {}), '(start, dt, stop)\n', (5935, 5952), True, 'import numpy as np\n'), ((6255, 6295), 'numpy.linspace', 'np.linspace', (['(0)', '(N * T)', 'N'], {'endpoint': '(False)'}), '(0, N * T, N, endpoint=False)\n', (6266, 6295), True, 'import numpy as np\n'), ((6302, 6340), 'numpy.pad', 'np.pad', (['v', '(0, N - v.size)', '"""constant"""'], {}), "(v, (0, N - v.size), 'constant')\n", (6308, 6340), True, 'import numpy as np\n'), ((6358, 6371), 'numpy.fft.fft', 'np.fft.fft', (['v'], {}), '(v)\n', (6368, 6371), True, 'import numpy as np\n'), ((6383, 6423), 'numpy.linspace', 'np.linspace', (['(0)', '(1 / T)', 'N'], {'endpoint': '(False)'}), '(0, 1 / T, N, endpoint=False)\n', (6394, 6423), True, 'import numpy as np\n'), ((6735, 6755), 'numpy.zeros', 'np.zeros', (['t_sel.size'], {}), '(t_sel.size)\n', (6743, 6755), True, 'import numpy as np\n'), ((7074, 7090), 'numpy.argmax', 'np.argmax', (['v_eff'], {}), '(v_eff)\n', (7083, 7090), True, 'import numpy as np\n'), ((7296, 7323), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 6)'}), '(figsize=(10, 6))\n', (7306, 7323), True, 'import matplotlib.pyplot as plt\n'), ((7645, 7664), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""t [s]"""'], {}), "('t [s]')\n", (7655, 7664), True, 'import matplotlib.pyplot as plt\n'), ((7670, 7692), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""v [mm/s]"""'], {}), "('v [mm/s]')\n", (7680, 7692), True, 'import matplotlib.pyplot as plt\n'), ((7698, 7719), 'matplotlib.pyplot.title', 'plt.title', (['"""velocity"""'], {}), "('velocity')\n", (7707, 7719), True, 'import matplotlib.pyplot as plt\n'), ((7725, 7737), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (7735, 7737), True, 'import matplotlib.pyplot as plt\n'), ((7788, 7798), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (7796, 7798), True, 'import matplotlib.pyplot as plt\n'), ((8016, 8044), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 18)'}), '(figsize=(10, 18))\n', (8026, 8044), True, 'import matplotlib.pyplot as plt\n'), ((9095, 9114), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""t [s]"""'], {}), "('t [s]')\n", (9105, 9114), True, 'import matplotlib.pyplot as plt\n'), ((9120, 9142), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""v [mm/s]"""'], {}), "('v [mm/s]')\n", (9130, 9142), True, 'import matplotlib.pyplot as plt\n'), ((9148, 9169), 'matplotlib.pyplot.title', 'plt.title', (['"""velocity"""'], {}), "('velocity')\n", (9157, 9169), True, 'import matplotlib.pyplot as plt\n'), ((9175, 9187), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (9185, 9187), True, 'import matplotlib.pyplot as plt\n'), ((9238, 9248), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (9246, 9248), True, 'import matplotlib.pyplot as plt\n'), ((1704, 1802), 'numpy.array', 'np.array', (['[[data[index_max, 0], data[index_max, 1]], [data[index_min, 0], data[\n index_min, 1]]]'], {}), '([[data[index_max, 0], data[index_max, 1]], [data[index_min, 0],\n data[index_min, 1]]])\n', (1712, 1802), True, 'import numpy as np\n'), ((1820, 1862), 'numpy.concatenate', 'np.concatenate', (['(min_max_array, x)'], {'axis': '(0)'}), '((min_max_array, x), axis=0)\n', (1834, 1862), True, 'import numpy as np\n'), ((2892, 2955), 'numpy.logspace', 'np.logspace', (['(0)', 'N'], {'endpoint': '(False)', 'num': 'N', 'base': 'one_third_octave'}), '(0, N, endpoint=False, num=N, base=one_third_octave)\n', (2903, 2955), True, 'import numpy as np\n'), ((6481, 6512), 'numpy.sqrt', 'np.sqrt', (['(1 + (5.6 / f_mod) ** 2)'], {}), '(1 + (5.6 / f_mod) ** 2)\n', (6488, 6512), True, 'import numpy as np\n'), ((6581, 6610), 'numpy.fft.ifft', 'np.fft.ifft', (['vibrations_fft_w'], {}), '(vibrations_fft_w)\n', (6592, 6610), True, 'import numpy as np\n'), ((6867, 6900), 'numpy.exp', 'np.exp', (['(-t_sel[:i + 1][::-1] / Ts)'], {}), '(-t_sel[:i + 1][::-1] / Ts)\n', (6873, 6900), True, 'import numpy as np\n'), ((6989, 7064), 'Redbox_v2.file_manager.progress', 'fm.progress', (['i', '(t_sel.size - 1)', "('processing %s of %s' % (i + 1, t_sel.size))"], {}), "(i, t_sel.size - 1, 'processing %s of %s' % (i + 1, t_sel.size))\n", (7000, 7064), True, 'from Redbox_v2 import file_manager as fm\n'), ((7353, 7396), 'matplotlib.pyplot.plot', 'plt.plot', (['t_sel', 'vibrations'], {'label': '"""signal"""'}), "(t_sel, vibrations, label='signal')\n", (7361, 7396), True, 'import matplotlib.pyplot as plt\n'), ((7428, 7482), 'matplotlib.pyplot.plot', 'plt.plot', (['t_sel', 'vibrations_w'], {'label': '"""weighted_signal"""'}), "(t_sel, vibrations_w, label='weighted_signal')\n", (7436, 7482), True, 'import matplotlib.pyplot as plt\n'), ((7507, 7544), 'matplotlib.pyplot.plot', 'plt.plot', (['t_sel', 'v_eff'], {'label': '"""v_eff"""'}), "(t_sel, v_eff, label='v_eff')\n", (7515, 7544), True, 'import matplotlib.pyplot as plt\n'), ((1602, 1631), 'numpy.argmax', 'np.argmax', (['data[start:end, 1]'], {}), '(data[start:end, 1])\n', (1611, 1631), True, 'import numpy as np\n'), ((1661, 1690), 'numpy.argmin', 'np.argmin', (['data[start:end, 1]'], {}), '(data[start:end, 1])\n', (1670, 1690), True, 'import numpy as np\n'), ((6182, 6197), 'numpy.log2', 'np.log2', (['v.size'], {}), '(v.size)\n', (6189, 6197), True, 'import numpy as np\n'), ((8589, 8608), 'numpy.argmax', 'np.argmax', (['v_eff[x]'], {}), '(v_eff[x])\n', (8598, 8608), True, 'import numpy as np\n'), ((264, 283), 'numpy.power', 'np.power', (['signal', '(2)'], {}), '(signal, 2)\n', (272, 283), True, 'import numpy as np\n'), ((889, 907), 'numpy.amax', 'np.amax', (['selection'], {}), '(selection)\n', (896, 907), True, 'import numpy as np\n'), ((908, 926), 'numpy.amin', 'np.amin', (['selection'], {}), '(selection)\n', (915, 926), True, 'import numpy as np\n'), ((2180, 2192), 'scipy.fftpack.rfft', 'rfft', (['signal'], {}), '(signal)\n', (2184, 2192), False, 'from scipy.fftpack import rfft, rfftfreq\n'), ((2371, 2383), 'scipy.fftpack.rfft', 'rfft', (['signal'], {}), '(signal)\n', (2375, 2383), False, 'from scipy.fftpack import rfft, rfftfreq\n'), ((6938, 6978), 'numpy.trapz', 'np.trapz', (['(g_xi * v_sqrd_w[:i + 1])'], {'dx': 'dt'}), '(g_xi * v_sqrd_w[:i + 1], dx=dt)\n', (6946, 6978), True, 'import numpy as np\n'), ((352, 374), 'numpy.power', 'np.power', (['amplitude', '(2)'], {}), '(amplitude, 2)\n', (360, 374), True, 'import numpy as np\n')]
|
import warnings
import numpy as np
import scipy.linalg as scplin
import scipy.optimize as scpop
import scipy.sparse as scpsp
dfail = {}
try:
import sksparse as sksp
except Exception as err:
sksp = False
dfail['sksparse'] = "For cholesk factorizations"
try:
import scikits.umfpack as skumf
except Exception as err:
skumf = False
dfail['umfpack'] = "For faster sparse matrices"
if len(dfail) > 0:
lstr = [f"\t- {k0}: {v0}" for k0, v0 in dfail.items()]
msg = (
"Consider installing the following for faster inversions:\n"
+ "\n".join(lstr)
)
warnings.warn(msg)
# #############################################################################
# #############################################################################
# Basic routines - augmented tikhonov
# #############################################################################
def inv_linear_augTikho_dense(
Tn=None,
TTn=None,
Tyn=None,
R=None,
yn=None,
sol0=None,
nchan=None,
nbs=None,
mu0=None,
conv_crit=None,
a0bis=None,
b0=None,
a1bis=None,
b1=None,
d=None,
conv_reg=True,
verb=None,
verb2head=None,
**kwdargs,
):
"""
Linear algorithm for Phillips-Tikhonov regularisation
Called "Augmented Tikhonov", dense matrix version
"""
conv = 0. # convergence variable
niter = 0 # number of iterations
mu1 = 0. # regularisation param
# verb
if verb >= 2:
chi2n = np.sum((Tn.dot(sol0) - yn)**2) / nchan
reg = sol0.dot(R.dot(sol0))
temp = f"{nchan} * {chi2n:.3e} + {mu0:.3e} * {reg:.3e}"
print(
f"{verb2head}\n\t\t\t {temp} = {nchan*chi2n + mu0*reg:.3e}",
end='\n',
)
# loop
# Continue until convergence criterion, and at least 2 iterations
while niter < 2 or conv > conv_crit:
# call solver
sol = scplin.solve(
TTn + mu0*R, Tyn,
assume_a='pos', # faster than 'sym'
overwrite_a=True, # no significant gain
overwrite_b=False, # True is faster, but a copy of Tyn is needed
check_finite=False, # small speed gain compared to True
transposed=False,
) # 3
# compute residu, regularity...
res2 = np.sum((Tn.dot(sol)-yn)**2) # residu**2
reg = sol.dot(R.dot(sol)) # regularity term
# update lamb, tau
lamb = a0bis/(0.5*reg + b0) # Update reg. param. estimate
tau = a1bis/(0.5*res2 + b1) # Update noise coef. estimate
mu1 = (lamb/tau) * (2*a1bis/res2)**d # rescale mu with noise estimate
# Compute convergence variable
if conv_reg:
conv = np.abs(mu1 - mu0) / mu1
else:
sol2 = sol**2
sol2max = np.max(sol2)
sol2[sol2 < 0.001*sol2max] = 0.001*sol2max
conv = np.sqrt(np.sum((sol - sol0)**2 / sol2) / nbs)
# verb
if verb >= 2:
temp1 = f"{nchan} * {res2/nchan:.3e} + {mu1:.3e} * {reg:.3e}"
temp2 = f"{res2 + mu1*reg:.3e}"
temp = f"{temp1} = {temp2}"
print(f"\t\t{niter} \t {temp} {tau:.3e} {conv:.3e}")
# update sol0, mu0 for next iteration
sol0[:] = sol[:]
mu0 = mu1
niter += 1
return sol, mu1, res2/nchan, reg, niter, [tau, lamb]
def inv_linear_augTikho_sparse(
Tn=None,
TTn=None,
Tyn=None,
R=None,
yn=None,
sol0=None,
nchan=None,
nbs=None,
mu0=None,
conv_crit=None,
a0bis=None,
b0=None,
a1bis=None,
b1=None,
d=None,
conv_reg=True,
verb=None,
verb2head=None,
maxiter=None,
tol=None,
precond=None, # test
**kwdargs,
):
"""
Linear algorithm for Phillips-Tikhonov regularisation
Called "Augmented Tikhonov", sparese matrix version
see InvLin_AugTikho_V1.__doc__ for details
"""
conv = 0. # convergence variable
niter = 0 # number of iterations
mu1 = 0. # regularisation param
# verb
if verb >= 2:
chi2n = np.sum((Tn.dot(sol0) - yn)**2) / nchan
reg = sol0.dot(R.dot(sol0))
temp = f"{nchan} * {chi2n:.3e} + {mu0:.3e} * {reg:.3e}"
print(
f"{verb2head}\n\t\t\t {temp} = {nchan*chi2n + mu0*reg:.3e}",
end='\n',
)
# loop
# Continue until convergence criterion, and at least 2 iterations
while niter < 2 or conv > conv_crit:
# sol = scpsp.linalg.spsolve(
# TTn + mu0*R, Tyn,
# permc_spec=None,
# use_umfpack=True,
# )
# seems faster
sol, itconv = scpsp.linalg.cg(
TTn + mu0*R, Tyn,
x0=sol0,
tol=tol,
maxiter=maxiter,
M=precond,
)
res2 = np.sum((Tn.dot(sol)-yn)**2) # residu**2
reg = sol.dot(R.dot(sol)) # regularity term
lamb = a0bis/(0.5*reg + b0) # Update reg. param. estimate
tau = a1bis/(0.5*res2 + b1) # Update noise coef. estimate
mu1 = (lamb/tau) * (2*a1bis/res2)**d # rescale mu with noise estimate
# Compute convergence variable
if conv_reg:
conv = np.abs(mu1 - mu0) / mu1
else:
sol2 = sol**2
sol2max = np.max(sol2)
sol2[sol2 < 0.001*sol2max] = 0.001*sol2max
conv = np.sqrt(np.sum((sol - sol0)**2 / sol2) / nbs)
# verb
if verb >= 2:
temp1 = f"{nchan} * {res2/nchan:.3e} + {mu1:.3e} * {reg:.3e}"
temp2 = f"{res2 + mu1*reg:.3e}"
temp = f"{temp1} = {temp2}"
print(
f"\t\t{niter} \t {temp} {tau:.3e} {conv:.3e}"
)
sol0[:] = sol[:] # Update reference solution
niter += 1 # Update number of iterations
mu0 = mu1
return sol, mu1, res2/nchan, reg, niter, [tau, lamb]
def inv_linear_augTikho_chol_dense(
Tn=None,
TTn=None,
Tyn=None,
R=None,
yn=None,
sol0=None,
nchan=None,
nbs=None,
mu0=None,
conv_crit=None,
a0bis=None,
b0=None,
a1bis=None,
b1=None,
d=None,
conv_reg=True,
verb=None,
verb2head=None,
**kwdargs,
):
"""
"""
conv = 0. # convergence variable
niter = 0 # number of iterations
mu1 = 0. # regularisation param
# verb
if verb >= 2:
chi2n = np.sum((Tn.dot(sol0) - yn)**2) / nchan
reg = sol0.dot(R.dot(sol0))
temp = f"{nchan} * {chi2n:.3e} + {mu0:.3e} * {reg:.3e}"
print(
f"{verb2head}\n\t\t\t {temp} = {nchan*chi2n + mu0*reg:.3e}",
end='\n',
)
# loop
# Continue until convergence criterion, and at least 2 iterations
while niter < 2 or conv > conv_crit:
try:
# choleski decomposition requires det(TT + mu0*LL) != 0
# (chol(A).T * chol(A) = A
chol = scplin.cholesky(
TTn + mu0*R,
lower=False,
check_finite=False,
overwrite_a=False,
)
# Use np.linalg.lstsq for double-solving the equation
sol = scplin.cho_solve(
(chol, False), Tyn,
overwrite_b=None,
check_finite=True,
)
except Exception as err:
# call solver
sol = scplin.solve(
TTn + mu0*R, Tyn,
assume_a='sym', # chol failed => not 'pos'
overwrite_a=True, # no significant gain
overwrite_b=False, # True faster, but a copy of Tyn needed
check_finite=False, # small speed gain compared to True
transposed=False,
) # 3
# compute residu, regularity...
res2 = np.sum((Tn.dot(sol)-yn)**2) # residu**2
reg = sol.dot(R.dot(sol)) # regularity term
# update lamb, tau
lamb = a0bis/(0.5*reg + b0) # Update reg. param. estimate
tau = a1bis/(0.5*res2 + b1) # Update noise coef. estimate
mu1 = (lamb/tau) * (2*a1bis/res2)**d # mu rescale with noise estimate
# Compute convergence variable
if conv_reg:
conv = np.abs(mu1 - mu0) / mu1
else:
sol2 = sol**2
sol2max = np.max(sol2)
sol2[sol2 < 0.001*sol2max] = 0.001*sol2max
conv = np.sqrt(np.sum((sol - sol0)**2 / sol2) / nbs)
# verb
if verb >= 2:
temp1 = f"{nchan} * {res2/nchan:.3e} + {mu1:.3e} * {reg:.3e}"
temp2 = f"{res2 + mu1*reg:.3e}"
temp = f"{temp1} = {temp2}"
print(f"\t\t{niter} \t {temp} {tau:.3e} {conv:.3e}")
# update sol0, mu0 for next iteration
sol0[:] = sol[:]
mu0 = mu1
niter += 1
return sol, mu1, res2/nchan, reg, niter, [tau, lamb]
def inv_linear_augTikho_chol_sparse(
Tn=None,
TTn=None,
Tyn=None,
R=None,
yn=None,
sol0=None,
nchan=None,
nbs=None,
mu0=None,
conv_crit=None,
a0bis=None,
b0=None,
a1bis=None,
b1=None,
d=None,
conv_reg=True,
verb=None,
verb2head=None,
**kwdargs,
):
"""
Linear algorithm for Phillips-Tikhonov regularisation
Called "Augmented Tikhonov"
Augmented in the sense that bayesian statistics are combined
with standard Tikhonov regularisation
Determines both noise (common multiplicative coefficient) and
regularisation parameter automatically
We assume here that all arrays are scaled (noise, conditioning...)
Sparse matrixes are also prefered to speed-up the computation
In this method:
tau is an approximation of the inverse of the noise coefficient
lamb is an approximation of the regularisation parameter
N.B.: The noise and reg. param. have probability densities of the form:
f(x) = x^(a-1) * exp(-bx)
This function's maximum is in x = (a-1)/b, so a = b+1 gives a maximum at 1.
(a0, b0) for the reg. param.
(a1, b1) for the noise estimate
Ref:
[1] <NAME>., <NAME>., Inverse Problems, vol.25, nb.2, 025001, 2009
[2] http://www.math.uni-bremen.de/zetem/cms/media.php/250/nov14talk_jin%20bangti.pdf
[3] <NAME>, <NAME>, <NAME>,
"A New Choice Rule for Regularization Parameters in Tikhonov
Regularization", Research report, University of Hong Kong, 2008
"""
conv = 0. # convergence variable
niter = 0 # number of iterations
mu1 = 0. # regularisation param
# verb
if verb >= 2:
chi2n = np.sum((Tn.dot(sol0) - yn)**2) / nchan
reg = sol0.dot(R.dot(sol0))
temp = f"{nchan} * {chi2n:.3e} + {mu0:.3e} * {reg:.3e}"
print(
f"{verb2head}\n\t\t\t {temp} = {nchan*chi2n + mu0*reg:.3e}",
end='\n',
)
# loop
# Continue until convergence criterion, and at least 2 iterations
factor = None
while niter < 2 or conv > conv_crit:
try:
# choleski decomposition requires det(TT + mu0*LL) != 0
# A = (chol(A).T * chol(A)
# optimal if matrix is csc
if sksp is False:
factor = scpsp.linalg.factorized(TTn + mu0*R)
sol = factor(Tyn)
else:
if factor is None:
factor = sksp.cholmod.cholesky(
TTn + mu0*R,
beta=0,
mode='auto',
ordering_method='default',
use_long=False,
)
else:
# re-use same factor
factor.cholesky_inplace(TTn + mu0*R, beta=0)
sol = factor.solve_A(Tyn)
except Exception as err:
# call solver
sol = scpsp.linalg.spsolve(
TTn + mu0*R, Tyn,
permc_spec=None,
use_umfpack=True,
)
# compute residu, regularity...
res2 = np.sum((Tn.dot(sol)-yn)**2) # residu**2
reg = sol.dot(R.dot(sol)) # regularity term
# update lamb, tau
lamb = a0bis/(0.5*reg + b0) # Update reg. param. estimate
tau = a1bis/(0.5*res2 + b1) # Update noise coef. estimate
mu1 = (lamb/tau) * (2*a1bis/res2)**d # Update reg. param. rescaling
# Compute convergence variable
if conv_reg:
conv = np.abs(mu1 - mu0) / mu1
else:
sol2 = sol**2
sol2max = np.max(sol2)
sol2[sol2 < 0.001*sol2max] = 0.001*sol2max
conv = np.sqrt(np.sum((sol - sol0)**2 / sol2) / nbs)
# verb
if verb >= 2:
temp1 = f"{nchan} * {res2/nchan:.3e} + {mu1:.3e} * {reg:.3e}"
temp2 = f"{res2 + mu1*reg:.3e}"
temp = f"{temp1} = {temp2}"
print(f"\t\t{niter} \t {temp} {tau:.3e} {conv:.3e}")
# update sol0, mu0 for next iteration
sol0[:] = sol[:]
mu0 = mu1
niter += 1
return sol, mu1, res2/nchan, reg, niter, [tau, lamb]
def inv_linear_augTikho_pos_dense(
Tn=None,
TTn=None,
Tyn=None,
R=None,
yn=None,
sol0=None,
nchan=None,
nbs=None,
mu0=None,
conv_crit=None,
a0bis=None,
b0=None,
a1bis=None,
b1=None,
d=None,
conv_reg=True,
verb=None,
verb2head=None,
# specific
method=None,
options=None,
bounds=None,
func_val=None,
func_jac=None,
func_hess=None,
**kwdargs,
):
"""
Quadratic algorithm for Phillips-Tikhonov regularisation
Alternative to the linear version with positivity constraint
see TFI.InvLin_AugTikho_V1.__doc__ for details
"""
conv = 0. # convergence variable
niter = 0 # number of iterations
mu1 = 0. # regularisation param
# verb
if verb >= 2:
chi2n = np.sum((Tn.dot(sol0) - yn)**2) / nchan
reg = sol0.dot(R.dot(sol0))
temp = f"{nchan} * {chi2n:.3e} + {mu0:.3e} * {reg:.3e}"
print(
f"{verb2head}\n\t\t\t {temp} = {nchan*chi2n + mu0*reg:.3e}",
end='\n',
)
while niter < 2 or conv > conv_crit:
# quadratic method for positivity constraint
sol = scpop.minimize(
func_val, sol0,
args=(mu0, Tn, yn, TTn, Tyn),
jac=func_jac,
hess=func_hess,
method=method,
bounds=bounds,
options=options,
).x
# compute residu, regularity...
res2 = np.sum((Tn.dot(sol)-yn)**2) # residu**2
reg = sol.dot(R.dot(sol)) # regularity term
# update lamb, tau
lamb = a0bis/(0.5*reg + b0) # Update reg. param. estimate
tau = a1bis/(0.5*res2 + b1) # Update noise coef. estimate
mu1 = (lamb/tau) * (2*a1bis/res2)**d # Update reg. param. rescaling
# Compute convergence variable
if conv_reg:
conv = np.abs(mu1 - mu0) / mu1
else:
sol2 = sol**2
sol2max = np.max(sol2)
sol2[sol2 < 0.001*sol2max] = 0.001*sol2max
conv = np.sqrt(np.sum((sol - sol0)**2 / sol2) / nbs)
# verb
if verb >= 2:
temp1 = f"{nchan} * {res2/nchan:.3e} + {mu1:.3e} * {reg:.3e}"
temp2 = f"{res2 + mu1*reg:.3e}"
temp = f"{temp1} = {temp2}"
print(f"\t\t{niter} \t {temp} {tau:.3e} {conv:.3e}")
# update sol0, mu0 for next iteration
sol0[:] = sol[:]
mu0 = mu1
niter += 1
return sol, mu1, res2/nchan, reg, niter, [tau, lamb]
# #############################################################################
# #############################################################################
# Basic routines - discrepancy principle
# #############################################################################
def inv_linear_DisPrinc_sparse(
Tn=None,
TTn=None,
Tyn=None,
R=None,
yn=None,
sol0=None,
nchan=None,
mu0=None,
precond=None,
verb=None,
verb2head=None,
# specific
chi2n_tol=None,
chi2n_obj=None,
maxiter=None,
tol=None,
**kwdargs,
):
"""
Discrepancy principle: find mu such that chi2n = 1 +/- tol
"""
niter = 0
lchi2n = np.array([np.sum((Tn.dot(sol0) - yn)**2) / nchan])
lmu = np.array([mu0])
chi2n_obj_log = np.log(chi2n_obj)
# verb
if verb >= 2:
reg = sol0.dot(R.dot(sol0))
temp = f"{nchan} * {lchi2n[0]:.3e} + {mu0:.3e} * {reg:.3e}"
print(
f"{verb2head}\n\t\t\t {temp} = {nchan*lchi2n[0] + mu0*reg:.3e}",
end='\n',
)
while niter == 0 or np.abs(lchi2n[-1] - chi2n_obj) > chi2n_tol:
sol, itconv = scpsp.linalg.cg(
TTn + lmu[-1]*R, Tyn,
x0=sol0,
tol=tol,
maxiter=maxiter,
M=precond,
)
lchi2n = np.append(lchi2n, np.sum((Tn.dot(sol) - yn)**2) / nchan)
if niter == 0:
if lchi2n[-1] >= chi2n_obj + chi2n_tol:
lmu = np.append(lmu, lmu[-1] / 50.)
elif lchi2n[-1] <= chi2n_obj - chi2n_tol:
lmu = np.append(lmu, lmu[-1] * 50.)
else:
lmu = np.append(lmu, lmu[-1])
elif niter == 1 or (
np.all(lchi2n >= chi2n_obj + chi2n_tol)
or np.all(lchi2n <= chi2n_obj - chi2n_tol)
):
if lchi2n[-1] >= chi2n_obj + chi2n_tol:
lmu = np.append(lmu, lmu[-1] / 50.)
else:
lmu = np.append(lmu, lmu[-1] * 50.)
else:
if lmu[-2] == lmu[-1]:
# if the algo is stuck => break to avoid infinite loop
ind = np.argmin(lchi2n[1:] - chi2n_obj)
lmu[-1] = lmu[ind]
lchi2n[-1] = lchi2n[ind]
sol, itconv = scpsp.linalg.cg(
TTn + lmu[-1]*R, Tyn,
x0=sol0,
tol=tol,
maxiter=maxiter,
M=precond,
)
break
else:
indsort = np.argsort(lchi2n[1:])
lmu = np.append(lmu, np.exp(np.interp(
chi2n_obj_log,
np.log(lchi2n[1:])[indsort],
np.log(lmu)[indsort]
)))
# verb
if verb >= 2:
reg = sol.dot(R.dot(sol))
res2 = np.sum((Tn.dot(sol)-yn)**2)
temp1 = f"{nchan} * {lchi2n[-1]:.3e} + {lmu[-1]:.3e} * {reg:.3e}"
temp2 = f"{res2 + lmu[-1]*reg:.3e}"
temp = f"{temp1} = {temp2}"
print(f"\t\t{niter} \t {temp}")
sol0[:] = sol
niter += 1
reg = sol.dot(R.dot(sol)) # regularity term
return sol, lmu[-1], lchi2n[-1], reg, niter, None
|
[
"scipy.linalg.solve",
"scipy.optimize.minimize",
"numpy.abs",
"numpy.log",
"numpy.sum",
"scipy.linalg.cholesky",
"scipy.sparse.linalg.cg",
"scipy.linalg.cho_solve",
"scipy.sparse.linalg.factorized",
"sksparse.cholmod.cholesky",
"numpy.argmin",
"numpy.argsort",
"numpy.append",
"numpy.max",
"numpy.array",
"scipy.sparse.linalg.spsolve",
"warnings.warn",
"numpy.all"
] |
[((603, 621), 'warnings.warn', 'warnings.warn', (['msg'], {}), '(msg)\n', (616, 621), False, 'import warnings\n'), ((16794, 16809), 'numpy.array', 'np.array', (['[mu0]'], {}), '([mu0])\n', (16802, 16809), True, 'import numpy as np\n'), ((16830, 16847), 'numpy.log', 'np.log', (['chi2n_obj'], {}), '(chi2n_obj)\n', (16836, 16847), True, 'import numpy as np\n'), ((1978, 2105), 'scipy.linalg.solve', 'scplin.solve', (['(TTn + mu0 * R)', 'Tyn'], {'assume_a': '"""pos"""', 'overwrite_a': '(True)', 'overwrite_b': '(False)', 'check_finite': '(False)', 'transposed': '(False)'}), "(TTn + mu0 * R, Tyn, assume_a='pos', overwrite_a=True,\n overwrite_b=False, check_finite=False, transposed=False)\n", (1990, 2105), True, 'import scipy.linalg as scplin\n'), ((4792, 4878), 'scipy.sparse.linalg.cg', 'scpsp.linalg.cg', (['(TTn + mu0 * R)', 'Tyn'], {'x0': 'sol0', 'tol': 'tol', 'maxiter': 'maxiter', 'M': 'precond'}), '(TTn + mu0 * R, Tyn, x0=sol0, tol=tol, maxiter=maxiter, M=\n precond)\n', (4807, 4878), True, 'import scipy.sparse as scpsp\n'), ((17197, 17286), 'scipy.sparse.linalg.cg', 'scpsp.linalg.cg', (['(TTn + lmu[-1] * R)', 'Tyn'], {'x0': 'sol0', 'tol': 'tol', 'maxiter': 'maxiter', 'M': 'precond'}), '(TTn + lmu[-1] * R, Tyn, x0=sol0, tol=tol, maxiter=maxiter,\n M=precond)\n', (17212, 17286), True, 'import scipy.sparse as scpsp\n'), ((2907, 2919), 'numpy.max', 'np.max', (['sol2'], {}), '(sol2)\n', (2913, 2919), True, 'import numpy as np\n'), ((5464, 5476), 'numpy.max', 'np.max', (['sol2'], {}), '(sol2)\n', (5470, 5476), True, 'import numpy as np\n'), ((7148, 7235), 'scipy.linalg.cholesky', 'scplin.cholesky', (['(TTn + mu0 * R)'], {'lower': '(False)', 'check_finite': '(False)', 'overwrite_a': '(False)'}), '(TTn + mu0 * R, lower=False, check_finite=False, overwrite_a\n =False)\n', (7163, 7235), True, 'import scipy.linalg as scplin\n'), ((7392, 7465), 'scipy.linalg.cho_solve', 'scplin.cho_solve', (['(chol, False)', 'Tyn'], {'overwrite_b': 'None', 'check_finite': '(True)'}), '((chol, False), Tyn, overwrite_b=None, check_finite=True)\n', (7408, 7465), True, 'import scipy.linalg as scplin\n'), ((8576, 8588), 'numpy.max', 'np.max', (['sol2'], {}), '(sol2)\n', (8582, 8588), True, 'import numpy as np\n'), ((12875, 12887), 'numpy.max', 'np.max', (['sol2'], {}), '(sol2)\n', (12881, 12887), True, 'import numpy as np\n'), ((14638, 14779), 'scipy.optimize.minimize', 'scpop.minimize', (['func_val', 'sol0'], {'args': '(mu0, Tn, yn, TTn, Tyn)', 'jac': 'func_jac', 'hess': 'func_hess', 'method': 'method', 'bounds': 'bounds', 'options': 'options'}), '(func_val, sol0, args=(mu0, Tn, yn, TTn, Tyn), jac=func_jac,\n hess=func_hess, method=method, bounds=bounds, options=options)\n', (14652, 14779), True, 'import scipy.optimize as scpop\n'), ((15461, 15473), 'numpy.max', 'np.max', (['sol2'], {}), '(sol2)\n', (15467, 15473), True, 'import numpy as np\n'), ((17131, 17161), 'numpy.abs', 'np.abs', (['(lchi2n[-1] - chi2n_obj)'], {}), '(lchi2n[-1] - chi2n_obj)\n', (17137, 17161), True, 'import numpy as np\n'), ((2821, 2838), 'numpy.abs', 'np.abs', (['(mu1 - mu0)'], {}), '(mu1 - mu0)\n', (2827, 2838), True, 'import numpy as np\n'), ((5378, 5395), 'numpy.abs', 'np.abs', (['(mu1 - mu0)'], {}), '(mu1 - mu0)\n', (5384, 5395), True, 'import numpy as np\n'), ((7606, 7733), 'scipy.linalg.solve', 'scplin.solve', (['(TTn + mu0 * R)', 'Tyn'], {'assume_a': '"""sym"""', 'overwrite_a': '(True)', 'overwrite_b': '(False)', 'check_finite': '(False)', 'transposed': '(False)'}), "(TTn + mu0 * R, Tyn, assume_a='sym', overwrite_a=True,\n overwrite_b=False, check_finite=False, transposed=False)\n", (7618, 7733), True, 'import scipy.linalg as scplin\n'), ((8490, 8507), 'numpy.abs', 'np.abs', (['(mu1 - mu0)'], {}), '(mu1 - mu0)\n', (8496, 8507), True, 'import numpy as np\n'), ((11508, 11546), 'scipy.sparse.linalg.factorized', 'scpsp.linalg.factorized', (['(TTn + mu0 * R)'], {}), '(TTn + mu0 * R)\n', (11531, 11546), True, 'import scipy.sparse as scpsp\n'), ((12150, 12225), 'scipy.sparse.linalg.spsolve', 'scpsp.linalg.spsolve', (['(TTn + mu0 * R)', 'Tyn'], {'permc_spec': 'None', 'use_umfpack': '(True)'}), '(TTn + mu0 * R, Tyn, permc_spec=None, use_umfpack=True)\n', (12170, 12225), True, 'import scipy.sparse as scpsp\n'), ((12789, 12806), 'numpy.abs', 'np.abs', (['(mu1 - mu0)'], {}), '(mu1 - mu0)\n', (12795, 12806), True, 'import numpy as np\n'), ((15375, 15392), 'numpy.abs', 'np.abs', (['(mu1 - mu0)'], {}), '(mu1 - mu0)\n', (15381, 15392), True, 'import numpy as np\n'), ((17525, 17555), 'numpy.append', 'np.append', (['lmu', '(lmu[-1] / 50.0)'], {}), '(lmu, lmu[-1] / 50.0)\n', (17534, 17555), True, 'import numpy as np\n'), ((3002, 3034), 'numpy.sum', 'np.sum', (['((sol - sol0) ** 2 / sol2)'], {}), '((sol - sol0) ** 2 / sol2)\n', (3008, 3034), True, 'import numpy as np\n'), ((5559, 5591), 'numpy.sum', 'np.sum', (['((sol - sol0) ** 2 / sol2)'], {}), '((sol - sol0) ** 2 / sol2)\n', (5565, 5591), True, 'import numpy as np\n'), ((8671, 8703), 'numpy.sum', 'np.sum', (['((sol - sol0) ** 2 / sol2)'], {}), '((sol - sol0) ** 2 / sol2)\n', (8677, 8703), True, 'import numpy as np\n'), ((11661, 11766), 'sksparse.cholmod.cholesky', 'sksp.cholmod.cholesky', (['(TTn + mu0 * R)'], {'beta': '(0)', 'mode': '"""auto"""', 'ordering_method': '"""default"""', 'use_long': '(False)'}), "(TTn + mu0 * R, beta=0, mode='auto', ordering_method=\n 'default', use_long=False)\n", (11682, 11766), True, 'import sksparse as sksp\n'), ((12970, 13002), 'numpy.sum', 'np.sum', (['((sol - sol0) ** 2 / sol2)'], {}), '((sol - sol0) ** 2 / sol2)\n', (12976, 13002), True, 'import numpy as np\n'), ((15556, 15588), 'numpy.sum', 'np.sum', (['((sol - sol0) ** 2 / sol2)'], {}), '((sol - sol0) ** 2 / sol2)\n', (15562, 15588), True, 'import numpy as np\n'), ((17631, 17661), 'numpy.append', 'np.append', (['lmu', '(lmu[-1] * 50.0)'], {}), '(lmu, lmu[-1] * 50.0)\n', (17640, 17661), True, 'import numpy as np\n'), ((17701, 17724), 'numpy.append', 'np.append', (['lmu', 'lmu[-1]'], {}), '(lmu, lmu[-1])\n', (17710, 17724), True, 'import numpy as np\n'), ((17766, 17805), 'numpy.all', 'np.all', (['(lchi2n >= chi2n_obj + chi2n_tol)'], {}), '(lchi2n >= chi2n_obj + chi2n_tol)\n', (17772, 17805), True, 'import numpy as np\n'), ((17821, 17860), 'numpy.all', 'np.all', (['(lchi2n <= chi2n_obj - chi2n_tol)'], {}), '(lchi2n <= chi2n_obj - chi2n_tol)\n', (17827, 17860), True, 'import numpy as np\n'), ((17946, 17976), 'numpy.append', 'np.append', (['lmu', '(lmu[-1] / 50.0)'], {}), '(lmu, lmu[-1] / 50.0)\n', (17955, 17976), True, 'import numpy as np\n'), ((18016, 18046), 'numpy.append', 'np.append', (['lmu', '(lmu[-1] * 50.0)'], {}), '(lmu, lmu[-1] * 50.0)\n', (18025, 18046), True, 'import numpy as np\n'), ((18188, 18221), 'numpy.argmin', 'np.argmin', (['(lchi2n[1:] - chi2n_obj)'], {}), '(lchi2n[1:] - chi2n_obj)\n', (18197, 18221), True, 'import numpy as np\n'), ((18328, 18417), 'scipy.sparse.linalg.cg', 'scpsp.linalg.cg', (['(TTn + lmu[-1] * R)', 'Tyn'], {'x0': 'sol0', 'tol': 'tol', 'maxiter': 'maxiter', 'M': 'precond'}), '(TTn + lmu[-1] * R, Tyn, x0=sol0, tol=tol, maxiter=maxiter,\n M=precond)\n', (18343, 18417), True, 'import scipy.sparse as scpsp\n'), ((18597, 18619), 'numpy.argsort', 'np.argsort', (['lchi2n[1:]'], {}), '(lchi2n[1:])\n', (18607, 18619), True, 'import numpy as np\n'), ((18730, 18748), 'numpy.log', 'np.log', (['lchi2n[1:]'], {}), '(lchi2n[1:])\n', (18736, 18748), True, 'import numpy as np\n'), ((18779, 18790), 'numpy.log', 'np.log', (['lmu'], {}), '(lmu)\n', (18785, 18790), True, 'import numpy as np\n')]
|
# 0702.py
import cv2
import numpy as np
src = cv2.imread('./data/rect.jpg')
gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 50, 100)
lines = cv2.HoughLines(edges, rho = 1, theta = np.pi/180.0, threshold = 100)
print('lines.shape = ', lines.shape)
for line in lines:
rho, theta = line[0]
c = np.cos(theta)
s = np.sin(theta)
x0 = c * rho
y0 = s * rho
x1 = int(x0 + 1000 * (-s))
y1 = int(y0 + 1000 * (c))
x2 = int(x0 - 1000 * (-s))
y2 = int(y0 - 1000 * (c))
cv2.line(src, (x1, y1), (x2, y2), (0, 0, 255), 2)
cv2.imshow('edges', edges)
cv2.imshow('src', src)
cv2.waitKey()
cv2.destroyAllWindows()
|
[
"cv2.line",
"cv2.Canny",
"cv2.cvtColor",
"cv2.waitKey",
"cv2.destroyAllWindows",
"cv2.imread",
"numpy.sin",
"cv2.HoughLines",
"numpy.cos",
"cv2.imshow"
] |
[((53, 82), 'cv2.imread', 'cv2.imread', (['"""./data/rect.jpg"""'], {}), "('./data/rect.jpg')\n", (63, 82), False, 'import cv2\n'), ((91, 128), 'cv2.cvtColor', 'cv2.cvtColor', (['src', 'cv2.COLOR_BGR2GRAY'], {}), '(src, cv2.COLOR_BGR2GRAY)\n', (103, 128), False, 'import cv2\n'), ((138, 162), 'cv2.Canny', 'cv2.Canny', (['gray', '(50)', '(100)'], {}), '(gray, 50, 100)\n', (147, 162), False, 'import cv2\n'), ((172, 236), 'cv2.HoughLines', 'cv2.HoughLines', (['edges'], {'rho': '(1)', 'theta': '(np.pi / 180.0)', 'threshold': '(100)'}), '(edges, rho=1, theta=np.pi / 180.0, threshold=100)\n', (186, 236), False, 'import cv2\n'), ((593, 619), 'cv2.imshow', 'cv2.imshow', (['"""edges"""', 'edges'], {}), "('edges', edges)\n", (603, 619), False, 'import cv2\n'), ((621, 643), 'cv2.imshow', 'cv2.imshow', (['"""src"""', 'src'], {}), "('src', src)\n", (631, 643), False, 'import cv2\n'), ((645, 658), 'cv2.waitKey', 'cv2.waitKey', ([], {}), '()\n', (656, 658), False, 'import cv2\n'), ((660, 683), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (681, 683), False, 'import cv2\n'), ((336, 349), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (342, 349), True, 'import numpy as np\n'), ((359, 372), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (365, 372), True, 'import numpy as np\n'), ((540, 589), 'cv2.line', 'cv2.line', (['src', '(x1, y1)', '(x2, y2)', '(0, 0, 255)', '(2)'], {}), '(src, (x1, y1), (x2, y2), (0, 0, 255), 2)\n', (548, 589), False, 'import cv2\n')]
|
import os
from typing import Dict, Union
import numpy as np
def lenient_makedirs(path: str) -> None:
"""Simple wrapper around makedirs that first checks for existence.
Args:
path (str): path to be created
"""
if not os.path.exists(path):
os.makedirs(path)
def tile_overlapped(image: np.ndarray,
tile_size: Union[tuple, int] = 256,
channels_first: bool = False,
tile_rows: int = None,
tile_cols: int = None) -> np.ndarray:
if len(image.shape) == 2:
axis = 0 if channels_first else -1
image = np.expand_dims(image, axis=axis)
if channels_first:
image = np.moveaxis(image, 0, -1)
# assume height, width, channels from now on
height, width, channels = image.shape
tile_h, tile_w = tile_size if isinstance(tile_size, tuple) else (tile_size, tile_size)
if height <= tile_h and width <= tile_w:
raise ValueError("Image is smaller than the required tile size")
# number of expected tiles, manually defined or inferred
exact = [height / float(tile_h), width / float(tile_w)]
outer = [int(np.ceil(v)) for v in exact]
# the required number of tiles is given by the ceiling
tile_count_h = tile_rows or outer[0]
tile_count_w = tile_cols or outer[1]
# compute total remainder for the expanded window
remainder_h = (tile_count_h * tile_h) - height
remainder_w = (tile_count_w * tile_w) - width
# divide remainders among tiles as overlap
overlap_h = int(np.floor(remainder_h / float(tile_count_h))) if tile_count_h > 1 else 0
overlap_w = int(np.floor(remainder_w / float(tile_count_w))) if tile_count_w > 1 else 0
# create the empty tensor to contain tiles
tiles = np.empty((tile_count_h, tile_count_w, tile_h, tile_w, channels), dtype=image.dtype)
stride_h = tile_h - overlap_h
stride_w = tile_w - overlap_w
# iterate over tiles and copy content from image windows
for row in range(tile_count_h):
for col in range(tile_count_w):
# get the starting indices, accounting for initial positions
# overlap is halved to distribute in left/right and top/bottom
x = max(row * stride_h - overlap_h // 2, 0)
y = max(col * stride_w - overlap_w // 2, 0)
# if it exceeds horizontally or vertically in the last rows or cols, increase overlap to fit
if (x + tile_h) >= height:
x -= abs(x + tile_h - height)
if (y + tile_w) >= width:
y -= abs(y + tile_w - width)
# assign tile to final tensor
tiles[row, col] = image[x:x + tile_h, y:y + tile_w, :]
return tiles
def convert_mask(image: np.ndarray, lut: Dict[tuple, int]) -> np.ndarray:
"""Converts a given RGB image containing labels in channels-last format (h, w, c)
into a greyscale mask where each index indicates a given class.
:param image: RGB input image with dimensions [height, width, channels]
:type image: np.ndarray
:param lut: look-up table containing the associations color -> index
:type lut: Dict[tuple, int]
:return: greyscale image with size [height, width] containing the mapped label indices
:rtype: np.ndarray
"""
result = np.zeros(image.shape[:2])
for color, index in lut.items():
result[np.all(image == color, axis=-1)] = index
return result.astype(np.uint8)
|
[
"numpy.moveaxis",
"os.makedirs",
"numpy.ceil",
"numpy.empty",
"numpy.zeros",
"numpy.expand_dims",
"os.path.exists",
"numpy.all"
] |
[((1779, 1867), 'numpy.empty', 'np.empty', (['(tile_count_h, tile_count_w, tile_h, tile_w, channels)'], {'dtype': 'image.dtype'}), '((tile_count_h, tile_count_w, tile_h, tile_w, channels), dtype=\n image.dtype)\n', (1787, 1867), True, 'import numpy as np\n'), ((3302, 3327), 'numpy.zeros', 'np.zeros', (['image.shape[:2]'], {}), '(image.shape[:2])\n', (3310, 3327), True, 'import numpy as np\n'), ((244, 264), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (258, 264), False, 'import os\n'), ((274, 291), 'os.makedirs', 'os.makedirs', (['path'], {}), '(path)\n', (285, 291), False, 'import os\n'), ((629, 661), 'numpy.expand_dims', 'np.expand_dims', (['image'], {'axis': 'axis'}), '(image, axis=axis)\n', (643, 661), True, 'import numpy as np\n'), ((701, 726), 'numpy.moveaxis', 'np.moveaxis', (['image', '(0)', '(-1)'], {}), '(image, 0, -1)\n', (712, 726), True, 'import numpy as np\n'), ((1165, 1175), 'numpy.ceil', 'np.ceil', (['v'], {}), '(v)\n', (1172, 1175), True, 'import numpy as np\n'), ((3380, 3411), 'numpy.all', 'np.all', (['(image == color)'], {'axis': '(-1)'}), '(image == color, axis=-1)\n', (3386, 3411), True, 'import numpy as np\n')]
|
import json
import torch
import numpy as np
import random
import torch.nn.functional as F
import functools
def cmp_time(a, b):
a_num = int(a.split('_')[1])
b_num = int(b.split('_')[1])
return a_num - b_num
def pad_tensor(vec, pad):
"""
pad tensor to fixed length
:parameter
vec: tensor to pad
pad: the size to pad to
:return
a new tensor padded to 'pad'
"""
padded = torch.cat([vec, torch.zeros((pad - len(vec),20), dtype=torch.float)], dim=0).data.numpy()
return padded
def padding_all(vec, max_len):
"""
vec: [n, len, feat]
"""
n = vec.shape[0]
vec_len = vec.shape[1]
padded = torch.cat([vec, torch.zeros((n,max_len-vec_len,20), dtype=torch.double)], dim=1).data
return padded
def load_info_data(path):
ori_data = np.load(path)
protein_tensor = torch.tensor(ori_data['pssm_arr'], dtype =torch.float) # [n_p ,220]
drug_tensor = torch.tensor(ori_data['drug_arr'], dtype =torch.float) # [n_d, 881]
protein_num = protein_tensor.shape[0]
drug_num = drug_tensor.shape[0]
node_num = protein_num + drug_num
return protein_tensor, drug_tensor, node_num, protein_num
def load_pre_process(preprocess_path):
with open(preprocess_path, 'r') as f:
a = json.load(f)
adj = torch.FloatTensor(a['adj'])
dti_inter_mat = torch.FloatTensor(a['dti_inter_mat'])
train_interact_pos = torch.tensor(a['train_interact_pos'])
val_interact_pos = torch.tensor(a['val_interact_pos'])
return adj, dti_inter_mat, train_interact_pos, val_interact_pos
|
[
"numpy.load",
"json.load",
"torch.FloatTensor",
"torch.zeros",
"torch.tensor"
] |
[((824, 837), 'numpy.load', 'np.load', (['path'], {}), '(path)\n', (831, 837), True, 'import numpy as np\n'), ((859, 912), 'torch.tensor', 'torch.tensor', (["ori_data['pssm_arr']"], {'dtype': 'torch.float'}), "(ori_data['pssm_arr'], dtype=torch.float)\n", (871, 912), False, 'import torch\n'), ((945, 998), 'torch.tensor', 'torch.tensor', (["ori_data['drug_arr']"], {'dtype': 'torch.float'}), "(ori_data['drug_arr'], dtype=torch.float)\n", (957, 998), False, 'import torch\n'), ((1285, 1297), 'json.load', 'json.load', (['f'], {}), '(f)\n', (1294, 1297), False, 'import json\n'), ((1312, 1339), 'torch.FloatTensor', 'torch.FloatTensor', (["a['adj']"], {}), "(a['adj'])\n", (1329, 1339), False, 'import torch\n'), ((1364, 1401), 'torch.FloatTensor', 'torch.FloatTensor', (["a['dti_inter_mat']"], {}), "(a['dti_inter_mat'])\n", (1381, 1401), False, 'import torch\n'), ((1431, 1468), 'torch.tensor', 'torch.tensor', (["a['train_interact_pos']"], {}), "(a['train_interact_pos'])\n", (1443, 1468), False, 'import torch\n'), ((1496, 1531), 'torch.tensor', 'torch.tensor', (["a['val_interact_pos']"], {}), "(a['val_interact_pos'])\n", (1508, 1531), False, 'import torch\n'), ((688, 747), 'torch.zeros', 'torch.zeros', (['(n, max_len - vec_len, 20)'], {'dtype': 'torch.double'}), '((n, max_len - vec_len, 20), dtype=torch.double)\n', (699, 747), False, 'import torch\n')]
|
import sys
import numpy as np
import math
from JMLUtils import dist2, eprint
from StructureXYZ import StructXYZ
from typing import Sequence
TRIANGLE_TOL = 1E-4
Y_DENOM = 1.0 / math.sqrt(3)
def water(infile: str = 'QM_REF.xyz', delta=4.0):
delta = float(delta)
xyzfi = StructXYZ(infile)
assert len(xyzfi.probe_indices) == 0
assert xyzfi.n_atoms == 3
assert xyzfi.atom_names[0].startswith("O")
place_triangle(xyzfi, delta)
def place_triangle(xyzfi: StructXYZ, delta: float = 4.0, outname: str = "WATER_PROBE.xyz", center: int = 0,
flank1: int = 1, flank2: int = 2):
if center >= xyzfi.n_atoms or center < 0:
raise ValueError(f"Central atom index {center} out-of-bounds 0-{xyzfi.n_atoms}")
if flank1 >= xyzfi.n_atoms or flank1 < 0:
raise ValueError(f"Flank1 atom index {flank1} out-of-bounds 0-{xyzfi.n_atoms}")
if flank2 >= xyzfi.n_atoms or flank2 < 0:
raise ValueError(f"Flank2 atom index {flank2} out-of-bounds 0-{xyzfi.n_atoms}")
if center == flank1 or center == flank2 or flank1 == flank2:
raise ValueError(f"All three atoms must have distinct indices: received {center},{flank1},{flank2}")
triangle_center = xyzfi.coords[center] + xyzfi.coords[flank1] + xyzfi.coords[flank2]
triangle_center *= 0.5
place_vec = triangle_center - xyzfi.coords[center]
mag_pv = math.sqrt(np.dot(place_vec, place_vec))
bisector_vector = 0.5 * (xyzfi.coords[flank2] - xyzfi.coords[flank1])
# Only used as square, so don't bother w/ square root
half_bisector = np.dot(bisector_vector, bisector_vector)
from_bisector = math.sqrt((delta * delta) - half_bisector)
out_xyz = (place_vec * (from_bisector / mag_pv)) + triangle_center
eprint(f"Placing probe at {out_xyz}")
xyzfi.append_atom(xyzfi.get_default_probetype()[0], out_xyz)
xyzfi.write_out(outname)
|
[
"numpy.dot",
"StructureXYZ.StructXYZ",
"JMLUtils.eprint",
"math.sqrt"
] |
[((179, 191), 'math.sqrt', 'math.sqrt', (['(3)'], {}), '(3)\n', (188, 191), False, 'import math\n'), ((282, 299), 'StructureXYZ.StructXYZ', 'StructXYZ', (['infile'], {}), '(infile)\n', (291, 299), False, 'from StructureXYZ import StructXYZ\n'), ((1575, 1615), 'numpy.dot', 'np.dot', (['bisector_vector', 'bisector_vector'], {}), '(bisector_vector, bisector_vector)\n', (1581, 1615), True, 'import numpy as np\n'), ((1637, 1677), 'math.sqrt', 'math.sqrt', (['(delta * delta - half_bisector)'], {}), '(delta * delta - half_bisector)\n', (1646, 1677), False, 'import math\n'), ((1755, 1792), 'JMLUtils.eprint', 'eprint', (['f"""Placing probe at {out_xyz}"""'], {}), "(f'Placing probe at {out_xyz}')\n", (1761, 1792), False, 'from JMLUtils import dist2, eprint\n'), ((1392, 1420), 'numpy.dot', 'np.dot', (['place_vec', 'place_vec'], {}), '(place_vec, place_vec)\n', (1398, 1420), True, 'import numpy as np\n')]
|
# Objective: learn a Doc2Vec model
import logging
import multiprocessing
import random
from time import time
import numpy as np
from gensim.models import doc2vec
from benchmark_utils import load_benchmarked_app_ids, print_ranking
from sentence_models import print_most_similar_sentences
from universal_sentence_encoder import perform_knn_search_with_vectors_as_input
from universal_sentence_encoder import prepare_knn_search, transform_matches_to_app_ids
from utils import load_tokens, load_game_names, get_doc_model_file_name
from word_model import compute_similarity_using_word2vec_model
def get_tag_prefix():
return 'appID_'
def read_corpus(steam_tokens, game_tags=None, include_app_ids=True):
for app_id, tokens in steam_tokens.items():
doc_tag = []
if include_app_ids:
doc_tag += [get_tag_prefix() + str(app_id)]
try:
# Reference: https://medium.com/scaleabout/a-gentle-introduction-to-doc2vec-db3e8c0cce5e
doc_tag += game_tags[app_id]
except KeyError:
print('AppID = {} cannot be found in tag dictionary.'.format(app_id))
except TypeError:
pass
yield doc2vec.TaggedDocument(tokens, doc_tag)
def reformat_similarity_scores_for_doc2vec(similarity_scores_as_tuples, game_names=None):
if game_names is None:
game_names, _ = load_game_names()
dummy_app_ids = []
similarity_scores = dict()
for app_id, similarity_value in similarity_scores_as_tuples:
if app_id.startswith(get_tag_prefix()):
app_id = app_id[len(get_tag_prefix()):]
similarity_scores[str(app_id)] = similarity_value
if str(app_id) not in game_names:
dummy_app_ids.append(app_id)
if len(dummy_app_ids) > 0:
print('Dummy appIDs: {}'.format(dummy_app_ids))
return similarity_scores
def train_doc_model_on_steam_tokens(model=None, steam_tokens=None, num_epochs=10):
# You do not want to perform training this way, because training already happened when initializating the model
# with Doc2Vec(documents). Moreover, calling train() several times messes with decay of learning rate alpha!
if steam_tokens is None:
steam_tokens = load_tokens()
documents = list(read_corpus(steam_tokens))
if model is None:
model = doc2vec.Doc2Vec(documents) # training happens with 5 epochs (default) here
start = time()
model.train(documents, total_examples=len(documents), epochs=num_epochs)
print('Elapsed time: {%.2f}' % (time() - start))
model.save(get_doc_model_file_name())
return model
def compute_similarity_using_doc2vec_model(query_app_id, steam_tokens=None, model=None,
verbose=False,
enforce_training=False, avoid_inference=False, num_items_displayed=10):
if steam_tokens is None:
steam_tokens = load_tokens()
if model is None:
try:
print('Loading Doc2Vec model.')
model = doc2vec.Doc2Vec.load(get_doc_model_file_name())
if enforce_training:
model = train_doc_model_on_steam_tokens(model=model, steam_tokens=steam_tokens)
except FileNotFoundError:
print('Training Doc2Vec model from scratch.')
model = train_doc_model_on_steam_tokens(model=None, steam_tokens=steam_tokens)
if avoid_inference:
if verbose:
print('Finding most similar documents based on the query appID.')
# For games which are part of the training corpus, we do not need to call model.infer_vector()
similarity_scores_as_tuples = model.docvecs.most_similar(positive=get_tag_prefix() + str(query_app_id),
topn=num_items_displayed)
else:
if verbose:
print('Finding most similar documents based on an inferred vector, which represents the query document.')
query = steam_tokens[query_app_id]
# Caveat: « Subsequent calls to this function may infer different representations for the same document. »
# Reference: https://radimrehurek.com/gensim/models/doc2vec.html#gensim.models.doc2vec.Doc2Vec.infer_vector
inferred_vector = model.infer_vector(query)
similarity_scores_as_tuples = model.docvecs.most_similar([inferred_vector])
similarity_scores = reformat_similarity_scores_for_doc2vec(similarity_scores_as_tuples)
print_most_similar_sentences(similarity_scores, num_items_displayed=num_items_displayed)
return similarity_scores
def check_analogy(model, pos, neg, num_items_displayed=10):
similarity_scores_as_tuples = model.docvecs.most_similar(positive=[get_tag_prefix() + p for p in pos],
negative=[get_tag_prefix() + n for n in neg],
topn=num_items_displayed)
similarity_scores = reformat_similarity_scores_for_doc2vec(similarity_scores_as_tuples)
print_most_similar_sentences(similarity_scores, num_items_displayed)
return
def apply_pipeline(train_from_scratch=True, avoid_inference=False, shuffle_corpus=True,
include_genres=False, include_categories=True, include_app_ids=True,
verbose=False):
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
game_names, game_tags = load_game_names(include_genres, include_categories)
steam_tokens = load_tokens()
documents = list(read_corpus(steam_tokens, game_tags, include_app_ids))
if shuffle_corpus:
# « Only if the training data has some existing clumping – like all the examples with certain words/topics are
# stuck together at the top or bottom of the ordering – is native ordering likely to cause training problems.
# And in that case, a single shuffle, before any training, should be enough to remove the clumping. »
# Reference: https://stackoverflow.com/a/48080869
random.shuffle(documents)
if train_from_scratch:
print('Creating a new Doc2Vec model from scratch.')
model = doc2vec.Doc2Vec(documents,
vector_size=100,
window=5,
min_count=5,
epochs=20,
workers=multiprocessing.cpu_count())
# NB: Do not follow the piece of advice given in https://rare-technologies.com/doc2vec-tutorial/
# « I have obtained better results by iterating over the data several times and either:
# 1. randomizing the order of input sentences, or
# 2. manually controlling the learning rate over the course of several iterations. »
# Indeed, in my experience, this leads to buggy results. Moreover, this approach is not recommended according to
# https://stackoverflow.com/a/48080869
model.save(get_doc_model_file_name())
else:
print('Loading previous Doc2Vec model.')
model = doc2vec.Doc2Vec.load(get_doc_model_file_name())
# Test doc2vec
if verbose:
try:
# Spelunky + (Slay the Spire) - (Dream Quest)
check_analogy(model, pos=['239350', '646570'], neg=['557410'])
except TypeError:
pass
try:
# Half-Life + (Witcher 2) - (Witcher)
check_analogy(model, pos=['70', '20920'], neg=['20900'])
except TypeError:
pass
query_app_ids = ['620', '364470', '504230', '583950', '646570', '863550', '794600']
for query_app_id in query_app_ids:
print('Query appID: {} ({})'.format(query_app_id, game_names[query_app_id]))
compute_similarity_using_doc2vec_model(query_app_id, steam_tokens, model,
avoid_inference=avoid_inference,
num_items_displayed=10)
# Check the relevance of the corresponding word2vec
for query_word in ['anime', 'fun', 'violent']:
compute_similarity_using_word2vec_model(query_word, steam_tokens, model)
entity = get_doc_model_entity(model)
tag_entity = set(tag for tag in entity if 'appID_' not in tag)
print(tag_entity)
query_tags = ['In-App Purchases', 'Free to Play', 'Violent', 'Early Access']
for query_tag in tag_entity.intersection(query_tags):
for query_app_id in query_app_ids:
try:
sim = model.docvecs.similarity(get_tag_prefix() + query_app_id, query_tag)
print('Similarity = {:.0%} for tag {} vs. appID {} ({})'.format(sim, query_tag, query_app_id,
game_names[query_app_id]))
except KeyError:
pass
num_items_displayed = 3
for query_tag in tag_entity:
print('\nTag: {}'.format(query_tag))
similarity_scores_as_tuples = model.docvecs.most_similar(positive=query_tag, topn=num_items_displayed)
similarity_scores = reformat_similarity_scores_for_doc2vec(similarity_scores_as_tuples)
print_most_similar_sentences(similarity_scores, num_items_displayed=num_items_displayed)
# Top 100
query_app_ids = load_benchmarked_app_ids(append_hard_coded_app_ids=True)
num_neighbors = 10
only_print_banners = True
use_cosine_similarity = True
label_database = np.array(model.docvecs.vectors_docs)
doc_tags = list(model.docvecs.doctags.keys())
init_indices = np.array(range(len(doc_tags)))
bool_indices_to_remove = list(map(lambda x: not x.startswith(get_tag_prefix()), doc_tags))
indices_to_remove = init_indices[bool_indices_to_remove]
label_database = np.delete(label_database, indices_to_remove, axis=0)
app_ids = [int(doc_tag[len(get_tag_prefix()):]) for doc_tag in doc_tags
if doc_tag.startswith(get_tag_prefix())]
knn = prepare_knn_search(label_database, use_cosine_similarity=use_cosine_similarity)
query_des = None
for query_app_id in query_app_ids:
if avoid_inference:
inferred_vector = label_database[app_ids.index(query_app_id)]
else:
# From query appID to query feature vector
query = steam_tokens[str(query_app_id)]
# Caveat: « Subsequent calls to this function may infer different representations for the same document. »
# Reference: https://radimrehurek.com/gensim/models/doc2vec.html#gensim.models.doc2vec.Doc2Vec.infer_vector
inferred_vector = model.infer_vector(query)
if query_des is None:
query_des = inferred_vector
else:
query_des = np.vstack((query_des, inferred_vector))
# Matching of feature vectors
matches = perform_knn_search_with_vectors_as_input(query_des, knn, num_neighbors)
# From feature matches to appID matches
matches_as_app_ids = transform_matches_to_app_ids(matches, app_ids)
print_ranking(query_app_ids,
matches_as_app_ids,
num_elements_displayed=num_neighbors,
only_print_banners=only_print_banners)
return
def get_doc_model_entity(model):
# The equivalent of a vocabulary for a word model
index2entity_set = set(model.docvecs.index2entity)
return index2entity_set
if __name__ == '__main__':
apply_pipeline(train_from_scratch=True, avoid_inference=False, shuffle_corpus=True,
include_genres=False, include_categories=False, include_app_ids=True)
|
[
"benchmark_utils.load_benchmarked_app_ids",
"random.shuffle",
"word_model.compute_similarity_using_word2vec_model",
"sentence_models.print_most_similar_sentences",
"multiprocessing.cpu_count",
"universal_sentence_encoder.prepare_knn_search",
"universal_sentence_encoder.perform_knn_search_with_vectors_as_input",
"utils.get_doc_model_file_name",
"utils.load_game_names",
"benchmark_utils.print_ranking",
"utils.load_tokens",
"numpy.delete",
"numpy.vstack",
"gensim.models.doc2vec.TaggedDocument",
"logging.basicConfig",
"universal_sentence_encoder.transform_matches_to_app_ids",
"time.time",
"numpy.array",
"gensim.models.doc2vec.Doc2Vec"
] |
[((2425, 2431), 'time.time', 'time', ([], {}), '()\n', (2429, 2431), False, 'from time import time\n'), ((4499, 4592), 'sentence_models.print_most_similar_sentences', 'print_most_similar_sentences', (['similarity_scores'], {'num_items_displayed': 'num_items_displayed'}), '(similarity_scores, num_items_displayed=\n num_items_displayed)\n', (4527, 4592), False, 'from sentence_models import print_most_similar_sentences\n'), ((5078, 5146), 'sentence_models.print_most_similar_sentences', 'print_most_similar_sentences', (['similarity_scores', 'num_items_displayed'], {}), '(similarity_scores, num_items_displayed)\n', (5106, 5146), False, 'from sentence_models import print_most_similar_sentences\n'), ((5376, 5471), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)s : %(levelname)s : %(message)s"""', 'level': 'logging.INFO'}), "(format='%(asctime)s : %(levelname)s : %(message)s',\n level=logging.INFO)\n", (5395, 5471), False, 'import logging\n'), ((5497, 5548), 'utils.load_game_names', 'load_game_names', (['include_genres', 'include_categories'], {}), '(include_genres, include_categories)\n', (5512, 5548), False, 'from utils import load_tokens, load_game_names, get_doc_model_file_name\n'), ((5569, 5582), 'utils.load_tokens', 'load_tokens', ([], {}), '()\n', (5580, 5582), False, 'from utils import load_tokens, load_game_names, get_doc_model_file_name\n'), ((9486, 9542), 'benchmark_utils.load_benchmarked_app_ids', 'load_benchmarked_app_ids', ([], {'append_hard_coded_app_ids': '(True)'}), '(append_hard_coded_app_ids=True)\n', (9510, 9542), False, 'from benchmark_utils import load_benchmarked_app_ids, print_ranking\n'), ((9652, 9688), 'numpy.array', 'np.array', (['model.docvecs.vectors_docs'], {}), '(model.docvecs.vectors_docs)\n', (9660, 9688), True, 'import numpy as np\n'), ((9967, 10019), 'numpy.delete', 'np.delete', (['label_database', 'indices_to_remove'], {'axis': '(0)'}), '(label_database, indices_to_remove, axis=0)\n', (9976, 10019), True, 'import numpy as np\n'), ((10164, 10243), 'universal_sentence_encoder.prepare_knn_search', 'prepare_knn_search', (['label_database'], {'use_cosine_similarity': 'use_cosine_similarity'}), '(label_database, use_cosine_similarity=use_cosine_similarity)\n', (10182, 10243), False, 'from universal_sentence_encoder import prepare_knn_search, transform_matches_to_app_ids\n'), ((11021, 11092), 'universal_sentence_encoder.perform_knn_search_with_vectors_as_input', 'perform_knn_search_with_vectors_as_input', (['query_des', 'knn', 'num_neighbors'], {}), '(query_des, knn, num_neighbors)\n', (11061, 11092), False, 'from universal_sentence_encoder import perform_knn_search_with_vectors_as_input\n'), ((11163, 11209), 'universal_sentence_encoder.transform_matches_to_app_ids', 'transform_matches_to_app_ids', (['matches', 'app_ids'], {}), '(matches, app_ids)\n', (11191, 11209), False, 'from universal_sentence_encoder import prepare_knn_search, transform_matches_to_app_ids\n'), ((11215, 11345), 'benchmark_utils.print_ranking', 'print_ranking', (['query_app_ids', 'matches_as_app_ids'], {'num_elements_displayed': 'num_neighbors', 'only_print_banners': 'only_print_banners'}), '(query_app_ids, matches_as_app_ids, num_elements_displayed=\n num_neighbors, only_print_banners=only_print_banners)\n', (11228, 11345), False, 'from benchmark_utils import load_benchmarked_app_ids, print_ranking\n'), ((1367, 1384), 'utils.load_game_names', 'load_game_names', ([], {}), '()\n', (1382, 1384), False, 'from utils import load_tokens, load_game_names, get_doc_model_file_name\n'), ((2234, 2247), 'utils.load_tokens', 'load_tokens', ([], {}), '()\n', (2245, 2247), False, 'from utils import load_tokens, load_game_names, get_doc_model_file_name\n'), ((2336, 2362), 'gensim.models.doc2vec.Doc2Vec', 'doc2vec.Doc2Vec', (['documents'], {}), '(documents)\n', (2351, 2362), False, 'from gensim.models import doc2vec\n'), ((2578, 2603), 'utils.get_doc_model_file_name', 'get_doc_model_file_name', ([], {}), '()\n', (2601, 2603), False, 'from utils import load_tokens, load_game_names, get_doc_model_file_name\n'), ((2938, 2951), 'utils.load_tokens', 'load_tokens', ([], {}), '()\n', (2949, 2951), False, 'from utils import load_tokens, load_game_names, get_doc_model_file_name\n'), ((6097, 6122), 'random.shuffle', 'random.shuffle', (['documents'], {}), '(documents)\n', (6111, 6122), False, 'import random\n'), ((1184, 1223), 'gensim.models.doc2vec.TaggedDocument', 'doc2vec.TaggedDocument', (['tokens', 'doc_tag'], {}), '(tokens, doc_tag)\n', (1206, 1223), False, 'from gensim.models import doc2vec\n'), ((7051, 7076), 'utils.get_doc_model_file_name', 'get_doc_model_file_name', ([], {}), '()\n', (7074, 7076), False, 'from utils import load_tokens, load_game_names, get_doc_model_file_name\n'), ((7174, 7199), 'utils.get_doc_model_file_name', 'get_doc_model_file_name', ([], {}), '()\n', (7197, 7199), False, 'from utils import load_tokens, load_game_names, get_doc_model_file_name\n'), ((8203, 8275), 'word_model.compute_similarity_using_word2vec_model', 'compute_similarity_using_word2vec_model', (['query_word', 'steam_tokens', 'model'], {}), '(query_word, steam_tokens, model)\n', (8242, 8275), False, 'from word_model import compute_similarity_using_word2vec_model\n'), ((9361, 9454), 'sentence_models.print_most_similar_sentences', 'print_most_similar_sentences', (['similarity_scores'], {'num_items_displayed': 'num_items_displayed'}), '(similarity_scores, num_items_displayed=\n num_items_displayed)\n', (9389, 9454), False, 'from sentence_models import print_most_similar_sentences\n'), ((10932, 10971), 'numpy.vstack', 'np.vstack', (['(query_des, inferred_vector)'], {}), '((query_des, inferred_vector))\n', (10941, 10971), True, 'import numpy as np\n'), ((2545, 2551), 'time.time', 'time', ([], {}), '()\n', (2549, 2551), False, 'from time import time\n'), ((3073, 3098), 'utils.get_doc_model_file_name', 'get_doc_model_file_name', ([], {}), '()\n', (3096, 3098), False, 'from utils import load_tokens, load_game_names, get_doc_model_file_name\n'), ((6473, 6500), 'multiprocessing.cpu_count', 'multiprocessing.cpu_count', ([], {}), '()\n', (6498, 6500), False, 'import multiprocessing\n')]
|
#!/usr/bin/env python
# coding: utf-8
# # Navigation
#
# ---
#
# You are welcome to use this coding environment to train your agent for the project. Follow the instructions below to get started!
#
# ### 1. Start the Environment
#
# Run the next code cell to install a few packages. This line will take a few minutes to run!
# In[ ]:
get_ipython().system('pip -q install ./python')
# The environment is already saved in the Workspace and can be accessed at the file path provided below. Please run the next code cell without making any changes.
# In[ ]:
from unityagents import UnityEnvironment
import numpy as np
# please do not modify the line below
env = UnityEnvironment(file_name="/data/Banana_Linux_NoVis/Banana.x86_64")
# Environments contain **_brains_** which are responsible for deciding the actions of their associated agents. Here we check for the first brain available, and set it as the default brain we will be controlling from Python.
# In[ ]:
# get the default brain
brain_name = env.brain_names[0]
brain = env.brains[brain_name]
# ### 2. Examine the State and Action Spaces
#
# Run the code cell below to print some information about the environment.
# In[ ]:
# reset the environment
env_info = env.reset(train_mode=True)[brain_name]
# number of agents in the environment
print('Number of agents:', len(env_info.agents))
# number of actions
action_size = brain.vector_action_space_size
print('Number of actions:', action_size)
# examine the state space
state = env_info.vector_observations[0]
print('States look like:', state)
state_size = len(state)
print('States have length:', state_size)
# ### 3. Take Random Actions in the Environment
#
# In the next code cell, you will learn how to use the Python API to control the agent and receive feedback from the environment.
#
# Note that **in this coding environment, you will not be able to watch the agent while it is training**, and you should set `train_mode=True` to restart the environment.
# In[ ]:
env_info = env.reset(train_mode=True)[brain_name] # reset the environment
state = env_info.vector_observations[0] # get the current state
score = 0 # initialize the score
while True:
action = np.random.randint(action_size) # select an action
env_info = env.step(action)[brain_name] # send the action to the environment
next_state = env_info.vector_observations[0] # get the next state
reward = env_info.rewards[0] # get the reward
done = env_info.local_done[0] # see if episode has finished
score += reward # update the score
state = next_state # roll over the state to next time step
if done: # exit loop if episode finished
break
print("Score: {}".format(score))
# When finished, you can close the environment.
# In[ ]:
env.close()
# ### 4. It's Your Turn!
#
# Now it's your turn to train your own agent to solve the environment! A few **important notes**:
# - When training the environment, set `train_mode=True`, so that the line for resetting the environment looks like the following:
# ```python
# env_info = env.reset(train_mode=True)[brain_name]
# ```
# - To structure your work, you're welcome to work directly in this Jupyter notebook, or you might like to start over with a new file! You can see the list of files in the workspace by clicking on **_Jupyter_** in the top left corner of the notebook.
# - In this coding environment, you will not be able to watch the agent while it is training. However, **_after training the agent_**, you can download the saved model weights to watch the agent on your own machine!
|
[
"numpy.random.randint",
"unityagents.UnityEnvironment"
] |
[((674, 742), 'unityagents.UnityEnvironment', 'UnityEnvironment', ([], {'file_name': '"""/data/Banana_Linux_NoVis/Banana.x86_64"""'}), "(file_name='/data/Banana_Linux_NoVis/Banana.x86_64')\n", (690, 742), False, 'from unityagents import UnityEnvironment\n'), ((2258, 2288), 'numpy.random.randint', 'np.random.randint', (['action_size'], {}), '(action_size)\n', (2275, 2288), True, 'import numpy as np\n')]
|
import numpy as np
import hierarchy as hrcy
def get_stationary_distribution(capacities, r, lmbda, mu):
assert capacities[-1] == 1
matrix = hrcy.transitions.get_transition_matrix(
capacities=capacities, r=r, lmbda=lmbda, mu=mu
)
dimension = matrix.shape[0]
M = np.vstack((matrix.transpose(), np.ones(dimension)))
b = np.vstack((np.zeros((dimension, 1)), [1]))
return np.linalg.lstsq(M, b)[0].transpose()[0]
|
[
"numpy.linalg.lstsq",
"hierarchy.transitions.get_transition_matrix",
"numpy.zeros",
"numpy.ones"
] |
[((150, 241), 'hierarchy.transitions.get_transition_matrix', 'hrcy.transitions.get_transition_matrix', ([], {'capacities': 'capacities', 'r': 'r', 'lmbda': 'lmbda', 'mu': 'mu'}), '(capacities=capacities, r=r, lmbda=\n lmbda, mu=mu)\n', (188, 241), True, 'import hierarchy as hrcy\n'), ((323, 341), 'numpy.ones', 'np.ones', (['dimension'], {}), '(dimension)\n', (330, 341), True, 'import numpy as np\n'), ((363, 387), 'numpy.zeros', 'np.zeros', (['(dimension, 1)'], {}), '((dimension, 1))\n', (371, 387), True, 'import numpy as np\n'), ((407, 428), 'numpy.linalg.lstsq', 'np.linalg.lstsq', (['M', 'b'], {}), '(M, b)\n', (422, 428), True, 'import numpy as np\n')]
|
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([1, 2, 3])
newarr = np.sum([arr1, arr2])
print(newarr)
|
[
"numpy.array",
"numpy.sum"
] |
[((27, 46), 'numpy.array', 'np.array', (['[1, 2, 3]'], {}), '([1, 2, 3])\n', (35, 46), True, 'import numpy as np\n'), ((54, 73), 'numpy.array', 'np.array', (['[1, 2, 3]'], {}), '([1, 2, 3])\n', (62, 73), True, 'import numpy as np\n'), ((84, 104), 'numpy.sum', 'np.sum', (['[arr1, arr2]'], {}), '([arr1, arr2])\n', (90, 104), True, 'import numpy as np\n')]
|
'''
for i in predictions/test/*; do python visualize_predictions.py $i\/doc.json $i/pred_weights.npy prediction_dir/$i ; done;
'''
import argparse
import numpy as np
import bipartite_utils
import json
import os
import subprocess
import matplotlib.pyplot as plt
from sklearn.metrics import roc_auc_score
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('document')
parser.add_argument('predictions')
parser.add_argument('output')
parser.add_argument('--n_to_show', default=5)
return parser.parse_args()
def call(x):
subprocess.call(x, shell=True)
def main():
args = parse_args()
pred_adj = np.load(args.predictions)
with open(args.document) as f:
data = json.loads(f.read())
images, text = data[0], data[1]
solve_fn = bipartite_utils.generate_fast_hungarian_solving_function()
sol = solve_fn(pred_adj, args.n_to_show)
scores = pred_adj[sol[:,0], sol[:,1]]
true_adj = np.zeros((len(text), len(images)))
for text_idx, t in enumerate(text):
if t[1] == -1: continue
true_adj[text_idx, t[1]] = 1
for image_idx, t in enumerate(images):
if t[1] == -1: continue
true_adj[t[1], image_idx] = 1
auc = 100 * roc_auc_score(true_adj.flatten(),
pred_adj.flatten())
print('AUC: {:.2f} {}'.format(auc,
data[-1]))
ordered_images, ordered_sentences = [], []
for img_idx, sent_idx, sc in sorted(
zip(sol[:,1], sol[:,0], scores), key=lambda x:-x[-1])[:args.n_to_show]:
ordered_images.append(img_idx)
ordered_sentences.append(sent_idx)
print(sc)
pred_adj_subgraph = pred_adj[np.array(ordered_sentences),:][:,np.array(ordered_images)]
true_adj_subgraph = true_adj[np.array(ordered_sentences),:][:,np.array(ordered_images)]
selected_images = [images[img_idx][0] for img_idx in ordered_images]
selected_sentences = [text[sent_idx][0] for sent_idx in ordered_sentences]
# normalize predicted sims to have max 1 and min 0
# first, clip out negative values
pred_adj_subgraph = np.clip(pred_adj_subgraph, 0, 1.0)
pred_adj_subgraph -= np.min(pred_adj_subgraph.flatten())
pred_adj_subgraph /= np.max(pred_adj_subgraph.flatten())
assert np.min(pred_adj_subgraph.flatten()) == 0.0
assert np.max(pred_adj_subgraph.flatten()) == 1.0
print(pred_adj_subgraph.shape)
print(ordered_images)
print(ordered_sentences)
print(selected_images)
print(selected_sentences)
# each line has ((x1, y1, x2, y2), strength, correctness)
# images go above text
lines_to_plot = []
image_text_gap = 2
same_mode_gap = 2
offdiag_alpha_mul = .5
def cosine_to_width(cos, exp=2.0, maxwidth=8.0):
return cos**exp * maxwidth
def cosine_to_alpha(cos, exp=1/2., maxalpha=1.0):
return cos**exp * maxalpha
correct_color, incorrect_color = '#1b7837', '#762a83'
lines_to_plot = []
for text_idx in range(args.n_to_show):
for image_idx in range(args.n_to_show):
coords = (text_idx*same_mode_gap, 0, image_idx*same_mode_gap, image_text_gap)
strength = max(pred_adj_subgraph[text_idx, image_idx], 0)
correctness = true_adj_subgraph[text_idx, image_idx] == 1
lines_to_plot.append((coords, strength, correctness))
plt.figure(figsize=(args.n_to_show*same_mode_gap, image_text_gap))
for (x1, y1, x2, y2), strength, correct in sorted(lines_to_plot,
key=lambda x: x[1]):
if x1 == x2: continue
plt.plot([x1, x2], [y1, y2],
linewidth=cosine_to_width(strength),
alpha=cosine_to_alpha(strength) * offdiag_alpha_mul,
color=correct_color if correct else incorrect_color)
for (x1, y1, x2, y2), strength, correct in sorted(lines_to_plot,
key=lambda x: x[1]):
if x1 != x2: continue
plt.plot([x1, x2], [y1, y2],
linewidth=cosine_to_width(strength),
color=correct_color if correct else incorrect_color)
plt.axis('off')
plt.tight_layout()
if not os.path.exists(args.output):
os.makedirs(args.output)
with open(args.output + '/sentences.txt', 'w') as f:
f.write('\n'.join([' '.join(s.split()) for s in selected_sentences]))
with open(args.output + '/images.txt', 'w') as f:
f.write('\n'.join(selected_images))
with open(args.output + '/all_sentences.txt', 'w') as f:
f.write('\n'.join([' '.join(s[0].split()) for s in text]))
with open(args.output + '/all_images.txt', 'w') as f:
f.write('\n'.join([x[0] for x in images]))
with open(args.output + '/auc.txt', 'w') as f:
f.write('{:.4f}'.format(auc))
plt.savefig(args.output + '/graph.png', dpi=300)
call('convert {} -trim {}'.format(args.output + '/graph.png',
args.output + '/graph_cropped.png'))
if __name__ == '__main__':
main()
|
[
"numpy.load",
"argparse.ArgumentParser",
"os.makedirs",
"os.path.exists",
"matplotlib.pyplot.axis",
"numpy.clip",
"matplotlib.pyplot.figure",
"subprocess.call",
"numpy.array",
"bipartite_utils.generate_fast_hungarian_solving_function",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.savefig"
] |
[((336, 361), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (359, 361), False, 'import argparse\n'), ((571, 601), 'subprocess.call', 'subprocess.call', (['x'], {'shell': '(True)'}), '(x, shell=True)\n', (586, 601), False, 'import subprocess\n'), ((655, 680), 'numpy.load', 'np.load', (['args.predictions'], {}), '(args.predictions)\n', (662, 680), True, 'import numpy as np\n'), ((805, 863), 'bipartite_utils.generate_fast_hungarian_solving_function', 'bipartite_utils.generate_fast_hungarian_solving_function', ([], {}), '()\n', (861, 863), False, 'import bipartite_utils\n'), ((2141, 2175), 'numpy.clip', 'np.clip', (['pred_adj_subgraph', '(0)', '(1.0)'], {}), '(pred_adj_subgraph, 0, 1.0)\n', (2148, 2175), True, 'import numpy as np\n'), ((3395, 3463), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(args.n_to_show * same_mode_gap, image_text_gap)'}), '(figsize=(args.n_to_show * same_mode_gap, image_text_gap))\n', (3405, 3463), True, 'import matplotlib.pyplot as plt\n'), ((4223, 4238), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (4231, 4238), True, 'import matplotlib.pyplot as plt\n'), ((4243, 4261), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (4259, 4261), True, 'import matplotlib.pyplot as plt\n'), ((4903, 4951), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(args.output + '/graph.png')"], {'dpi': '(300)'}), "(args.output + '/graph.png', dpi=300)\n", (4914, 4951), True, 'import matplotlib.pyplot as plt\n'), ((4278, 4305), 'os.path.exists', 'os.path.exists', (['args.output'], {}), '(args.output)\n', (4292, 4305), False, 'import os\n'), ((4315, 4339), 'os.makedirs', 'os.makedirs', (['args.output'], {}), '(args.output)\n', (4326, 4339), False, 'import os\n'), ((1753, 1777), 'numpy.array', 'np.array', (['ordered_images'], {}), '(ordered_images)\n', (1761, 1777), True, 'import numpy as np\n'), ((1845, 1869), 'numpy.array', 'np.array', (['ordered_images'], {}), '(ordered_images)\n', (1853, 1869), True, 'import numpy as np\n'), ((1720, 1747), 'numpy.array', 'np.array', (['ordered_sentences'], {}), '(ordered_sentences)\n', (1728, 1747), True, 'import numpy as np\n'), ((1812, 1839), 'numpy.array', 'np.array', (['ordered_sentences'], {}), '(ordered_sentences)\n', (1820, 1839), True, 'import numpy as np\n')]
|
"""Global settings and imports"""
import sys
sys.path.append("../../")
import os
import numpy as np
import zipfile
from tqdm import tqdm
import scrapbook as sb
from tempfile import TemporaryDirectory
import tensorflow as tf
tf.get_logger().setLevel('ERROR') # only show error messages
from reco_utils.recommender.deeprec.deeprec_utils import download_deeprec_resources
from reco_utils.recommender.newsrec.newsrec_utils import prepare_hparams
from reco_utils.recommender.newsrec.models.nrms import NRMSModel
from reco_utils.recommender.newsrec.io.mind_iterator import MINDIterator
from reco_utils.recommender.newsrec.newsrec_utils import get_mind_data_set
print("System version: {}".format(sys.version))
print("Tensorflow version: {}".format(tf.__version__))
"""Prepare parameters"""
epochs = 5
seed = 42
batch_size = 32
# Options: demo, small, large
MIND_type = 'demo'
"""Download and load data"""
tmpdir = TemporaryDirectory()
data_path = tmpdir.name
train_news_file = os.path.join(data_path, 'train', r'news.tsv')
train_behaviors_file = os.path.join(data_path, 'train', r'behaviors.tsv')
valid_news_file = os.path.join(data_path, 'valid', r'news.tsv')
valid_behaviors_file = os.path.join(data_path, 'valid', r'behaviors.tsv')
wordEmb_file = os.path.join(data_path, "utils", "embedding.npy")
userDict_file = os.path.join(data_path, "utils", "uid2index.pkl")
wordDict_file = os.path.join(data_path, "utils", "word_dict.pkl")
yaml_file = os.path.join(data_path, "utils", r'nrms.yaml')
mind_url, mind_train_dataset, mind_dev_dataset, mind_utils = get_mind_data_set(MIND_type)
if not os.path.exists(train_news_file):
download_deeprec_resources(mind_url, os.path.join(data_path, 'train'), mind_train_dataset)
if not os.path.exists(valid_news_file):
download_deeprec_resources(mind_url, \
os.path.join(data_path, 'valid'), mind_dev_dataset)
if not os.path.exists(yaml_file):
download_deeprec_resources(r'https://recodatasets.z20.web.core.windows.net/newsrec/', \
os.path.join(data_path, 'utils'), mind_utils)
"""Create hyper-parameters"""
hparams = prepare_hparams(yaml_file,
wordEmb_file=wordEmb_file,
wordDict_file=wordDict_file,
userDict_file=userDict_file,
batch_size=batch_size,
epochs=epochs,
show_step=10)
print(hparams)
"""Train the NRMS model"""
iterator = MINDIterator
model = NRMSModel(hparams, iterator, seed=seed)
print(model.run_eval(valid_news_file, valid_behaviors_file))
model.fit(train_news_file, train_behaviors_file, valid_news_file, valid_behaviors_file)
res_syn = model.run_eval(valid_news_file, valid_behaviors_file)
print(res_syn)
sb.glue("res_syn", res_syn)
"""Save the model"""
model_path = os.path.join(data_path, "model")
os.makedirs(model_path, exist_ok=True)
model.model.save_weights(os.path.join(model_path, "nrms_ckpt"))
"""Output Predcition File"""
group_impr_indexes, group_labels, group_preds = model.run_fast_eval(valid_news_file, valid_behaviors_file)
with open(os.path.join(data_path, 'prediction.txt'), 'w') as f:
for impr_index, preds in tqdm(zip(group_impr_indexes, group_preds)):
impr_index += 1
pred_rank = (np.argsort(np.argsort(preds)[::-1]) + 1).tolist()
pred_rank = '[' + ','.join([str(i) for i in pred_rank]) + ']'
f.write(' '.join([str(impr_index), pred_rank])+ '\n')
f = zipfile.ZipFile(os.path.join(data_path, 'prediction.zip'), 'w', zipfile.ZIP_DEFLATED)
f.write(os.path.join(data_path, 'prediction.txt'), arcname='prediction.txt')
f.close()
|
[
"sys.path.append",
"reco_utils.recommender.newsrec.newsrec_utils.get_mind_data_set",
"tempfile.TemporaryDirectory",
"os.makedirs",
"scrapbook.glue",
"os.path.exists",
"numpy.argsort",
"reco_utils.recommender.newsrec.models.nrms.NRMSModel",
"os.path.join",
"reco_utils.recommender.newsrec.newsrec_utils.prepare_hparams",
"tensorflow.get_logger"
] |
[((45, 70), 'sys.path.append', 'sys.path.append', (['"""../../"""'], {}), "('../../')\n", (60, 70), False, 'import sys\n'), ((912, 932), 'tempfile.TemporaryDirectory', 'TemporaryDirectory', ([], {}), '()\n', (930, 932), False, 'from tempfile import TemporaryDirectory\n'), ((976, 1020), 'os.path.join', 'os.path.join', (['data_path', '"""train"""', '"""news.tsv"""'], {}), "(data_path, 'train', 'news.tsv')\n", (988, 1020), False, 'import os\n'), ((1045, 1094), 'os.path.join', 'os.path.join', (['data_path', '"""train"""', '"""behaviors.tsv"""'], {}), "(data_path, 'train', 'behaviors.tsv')\n", (1057, 1094), False, 'import os\n'), ((1114, 1158), 'os.path.join', 'os.path.join', (['data_path', '"""valid"""', '"""news.tsv"""'], {}), "(data_path, 'valid', 'news.tsv')\n", (1126, 1158), False, 'import os\n'), ((1183, 1232), 'os.path.join', 'os.path.join', (['data_path', '"""valid"""', '"""behaviors.tsv"""'], {}), "(data_path, 'valid', 'behaviors.tsv')\n", (1195, 1232), False, 'import os\n'), ((1249, 1298), 'os.path.join', 'os.path.join', (['data_path', '"""utils"""', '"""embedding.npy"""'], {}), "(data_path, 'utils', 'embedding.npy')\n", (1261, 1298), False, 'import os\n'), ((1315, 1364), 'os.path.join', 'os.path.join', (['data_path', '"""utils"""', '"""uid2index.pkl"""'], {}), "(data_path, 'utils', 'uid2index.pkl')\n", (1327, 1364), False, 'import os\n'), ((1381, 1430), 'os.path.join', 'os.path.join', (['data_path', '"""utils"""', '"""word_dict.pkl"""'], {}), "(data_path, 'utils', 'word_dict.pkl')\n", (1393, 1430), False, 'import os\n'), ((1443, 1488), 'os.path.join', 'os.path.join', (['data_path', '"""utils"""', '"""nrms.yaml"""'], {}), "(data_path, 'utils', 'nrms.yaml')\n", (1455, 1488), False, 'import os\n'), ((1552, 1580), 'reco_utils.recommender.newsrec.newsrec_utils.get_mind_data_set', 'get_mind_data_set', (['MIND_type'], {}), '(MIND_type)\n', (1569, 1580), False, 'from reco_utils.recommender.newsrec.newsrec_utils import get_mind_data_set\n'), ((2128, 2300), 'reco_utils.recommender.newsrec.newsrec_utils.prepare_hparams', 'prepare_hparams', (['yaml_file'], {'wordEmb_file': 'wordEmb_file', 'wordDict_file': 'wordDict_file', 'userDict_file': 'userDict_file', 'batch_size': 'batch_size', 'epochs': 'epochs', 'show_step': '(10)'}), '(yaml_file, wordEmb_file=wordEmb_file, wordDict_file=\n wordDict_file, userDict_file=userDict_file, batch_size=batch_size,\n epochs=epochs, show_step=10)\n', (2143, 2300), False, 'from reco_utils.recommender.newsrec.newsrec_utils import prepare_hparams\n'), ((2524, 2563), 'reco_utils.recommender.newsrec.models.nrms.NRMSModel', 'NRMSModel', (['hparams', 'iterator'], {'seed': 'seed'}), '(hparams, iterator, seed=seed)\n', (2533, 2563), False, 'from reco_utils.recommender.newsrec.models.nrms import NRMSModel\n'), ((2792, 2819), 'scrapbook.glue', 'sb.glue', (['"""res_syn"""', 'res_syn'], {}), "('res_syn', res_syn)\n", (2799, 2819), True, 'import scrapbook as sb\n'), ((2855, 2887), 'os.path.join', 'os.path.join', (['data_path', '"""model"""'], {}), "(data_path, 'model')\n", (2867, 2887), False, 'import os\n'), ((2888, 2926), 'os.makedirs', 'os.makedirs', (['model_path'], {'exist_ok': '(True)'}), '(model_path, exist_ok=True)\n', (2899, 2926), False, 'import os\n'), ((1589, 1620), 'os.path.exists', 'os.path.exists', (['train_news_file'], {}), '(train_news_file)\n', (1603, 1620), False, 'import os\n'), ((1725, 1756), 'os.path.exists', 'os.path.exists', (['valid_news_file'], {}), '(valid_news_file)\n', (1739, 1756), False, 'import os\n'), ((1891, 1916), 'os.path.exists', 'os.path.exists', (['yaml_file'], {}), '(yaml_file)\n', (1905, 1916), False, 'import os\n'), ((2953, 2990), 'os.path.join', 'os.path.join', (['model_path', '"""nrms_ckpt"""'], {}), "(model_path, 'nrms_ckpt')\n", (2965, 2990), False, 'import os\n'), ((3513, 3554), 'os.path.join', 'os.path.join', (['data_path', '"""prediction.zip"""'], {}), "(data_path, 'prediction.zip')\n", (3525, 3554), False, 'import os\n'), ((3591, 3632), 'os.path.join', 'os.path.join', (['data_path', '"""prediction.txt"""'], {}), "(data_path, 'prediction.txt')\n", (3603, 3632), False, 'import os\n'), ((224, 239), 'tensorflow.get_logger', 'tf.get_logger', ([], {}), '()\n', (237, 239), True, 'import tensorflow as tf\n'), ((1663, 1695), 'os.path.join', 'os.path.join', (['data_path', '"""train"""'], {}), "(data_path, 'train')\n", (1675, 1695), False, 'import os\n'), ((1832, 1864), 'os.path.join', 'os.path.join', (['data_path', '"""valid"""'], {}), "(data_path, 'valid')\n", (1844, 1864), False, 'import os\n'), ((2041, 2073), 'os.path.join', 'os.path.join', (['data_path', '"""utils"""'], {}), "(data_path, 'utils')\n", (2053, 2073), False, 'import os\n'), ((3139, 3180), 'os.path.join', 'os.path.join', (['data_path', '"""prediction.txt"""'], {}), "(data_path, 'prediction.txt')\n", (3151, 3180), False, 'import os\n'), ((3322, 3339), 'numpy.argsort', 'np.argsort', (['preds'], {}), '(preds)\n', (3332, 3339), True, 'import numpy as np\n')]
|
import os
import os.path as osp
import gym
import time
import datetime
import joblib
import logging
import numpy as np
import tensorflow as tf
from baselines import logger
from baselines.common import set_global_seeds, explained_variance
from baselines.common.vec_env.subproc_vec_env import SubprocVecEnv
from baselines.common.atari_wrappers import wrap_deepmind
from baselines.common import tf_util
from baselines.a2c.utils import discount_with_dones
from baselines.a2c.utils import Scheduler, make_path, find_trainable_variables
from baselines.a2c.utils import cat_entropy, mse
class Model(object):
def __init__(self, policy, ob_space, ac_space, nenvs, nsteps,
ent_coef=0.01, vf_coef=0.5, max_grad_norm=0.5, lr=7e-4,
alpha=0.99, epsilon=1e-5, total_timesteps=int(80e6), lrschedule='linear'):
sess = tf_util.make_session()
nact = ac_space.n
nbatch = nenvs*nsteps
A = tf.placeholder(tf.int32, [nbatch])
ADV = tf.placeholder(tf.float32, [nbatch])
R = tf.placeholder(tf.float32, [nbatch])
LR = tf.placeholder(tf.float32, [])
# Defines step_model function and train_model functions
# Pass each model a copy of 'sess'
print("Constructing model... STEP_MODEL & TRAIN_MODEL: constructing step_model policy | " + str(policy))
step_model = policy(sess, ob_space, ac_space, nenvs, 1, reuse=False)
# train_model takes in the mini-batch produced by 5 step_models, NOTE: reuse = true
train_model = policy(sess, ob_space, ac_space, nenvs*nsteps, nsteps, reuse=True)
# var init: this neglogpac is still somewhat unknown,
# looks like it does softmax over policy layer of training model
neglogpac = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=train_model.pi, labels=A)
print("MAIN: neglocpac = sparse_softmax_cross_entropy_with_logits() inputs: ")
print("MAIN: train_model_pi: " + str(train_model.pi))
print("MAIN: labels: " + str(A))
# var init: policy gradient loss determined by average of all advantage * neglogpac
pg_loss = tf.reduce_mean(ADV * neglogpac)
# value function loss is mse(tf.squeeze(train_model.vf), R)
# ^ in english, mse(model value prediction, actual Reward)
# mse == means squared error, defined in a2c/utils.py
vf_loss = tf.reduce_mean(mse(tf.squeeze(train_model.vf), R))
# entropy of policy
entropy = tf.reduce_mean(cat_entropy(train_model.pi))
# total loss calculation?
# todo: is this the loss function definition??? check with a3c paper
loss = pg_loss - entropy*ent_coef + vf_loss * vf_coef
# params gets trainable variables from model (weights of network?)
params = find_trainable_variables("model")
# computes gradients (change of weights, or direction of weights) using 'loss' and 'params' above
# computes 'symbolic derivatives of sum 'loss' w.r.t 'params'
# from tflow docs: 'gradients() adds ops to the graph to output the derivs of 'params'
grads = tf.gradients(loss, params)
if max_grad_norm is not None:
grads, grad_norm = tf.clip_by_global_norm(grads, max_grad_norm)
# TODO: how many gradients are computed here, should be 16
grads = list(zip(grads, params))
# RMSProp optimizes learning rate , check thesis notes
trainer = tf.train.RMSPropOptimizer(learning_rate=LR, decay=alpha, epsilon=epsilon)
# RMSProp pushes back new gradients over trainable variables to change weights
_train = trainer.apply_gradients(grads)
lr = Scheduler(v=lr, nvalues=total_timesteps, schedule=lrschedule)
writer = tf.summary.FileWriter("/tmp/helloTensorBoard.txt")
writer.add_graph(sess.graph)
# Trains the model,
# TODO: What is 'masks' input param
# TODO: How often does train_model (steps thru train_model) get run vs. step_model
# A: I think it does a 'train_model' for each mini-batch, which is currently 5 steps
# Does a sess.run with train_model
def train(obs, states, rewards, masks, actions, values):
advs = rewards - values
for step in range(len(obs)):
cur_lr = lr.value()
# td_map hooks up all inputs for train model?
td_map = {train_model.X:obs, A:actions, ADV:advs, R:rewards, LR:cur_lr}
if states is not None:
td_map[train_model.S] = states
td_map[train_model.M] = masks
# Policy Loss, Value Loss, and Policy Entropy calculations
# Propagates losses backwards through the neural network?
policy_loss, value_loss, policy_entropy, _ = sess.run(
[pg_loss, vf_loss, entropy, _train],
td_map
)
return policy_loss, value_loss, policy_entropy
def save(save_path):
path = logger.get_dir() + "/model.pkl"
print("Logger dir: " + logger.get_dir())
print("MODEL SAVED TO : " + str(path))
ps = sess.run(params)
#make_path(osp.dirname(save_path))
joblib.dump(ps, path)
def load(load_path):
loaded_params = joblib.load(load_path)
restores = []
for p, loaded_p in zip(params, loaded_params):
restores.append(p.assign(loaded_p))
ps = sess.run(restores)
self.train = train
self.train_model = train_model
self.step_model = step_model
self.step = step_model.step
self.value = step_model.value
self.initial_state = step_model.initial_state
self.save = save
self.load = load
tf.global_variables_initializer().run(session=sess)
class Runner(object):
# Run is passed a model and nsteps default to 5, runs both models?
def __init__(self, env, model, nsteps=5, gamma=0.99):
self.env = env
self.model = model
nh, nw, nc = env.observation_space.shape
nenv = env.num_envs
self.batch_ob_shape = (nenv*nsteps, nh, nw, nc)
self.obs = np.zeros((nenv, nh, nw, nc), dtype=np.uint8)
self.nc = nc
obs = env.reset()
self.gamma = gamma
self.nsteps = nsteps
self.states = model.initial_state
self.dones = [False for _ in range(nenv)]
# run() steps through 'nsteps' of each 'nenvs' environment, adds actions values
# 'nsteps' is 5 actions set above
def run(self):
# initializes mini-batch arrays
mb_obs, mb_rewards, mb_actions, mb_values, mb_dones = [],[],[],[],[]
mb_states = self.states
# For each step n (5), the model steps through each environment without 'learning' anything, adds rewards
for n in range(self.nsteps):
actions, values, states, _ = self.model.step(self.obs, self.states, self.dones)
print("#######************###### a2c::::: run() iter: " + str(n))
print("action(s): " + str(actions))
print("values(s): " + str(values))
# Records actions and values predicted from the model.step() call above
mb_obs.append(np.copy(self.obs))
mb_actions.append(actions)
mb_values.append(values)
mb_dones.append(self.dones)
# Executes the actions predicted above
# print("RUNNER: self.env: " + str(self.env))
obs, rewards, dones, _ = self.env.step(actions)
print("a2c::::: run(): rewards: " + str(rewards))
# print("RUNNER: len(obs): " + str(len(obs)))
# print("RUNNER: len(rewards): " + str(len(rewards)))
self.states = states
self.dones = dones
for n, done in enumerate(dones):
if done:
self.obs[n] = self.obs[n]*0
self.obs = obs
mb_rewards.append(rewards)
mb_dones.append(self.dones)
#batch of steps to batch of rollouts, aggregates all observations, rewards, actions, values, dones, swaps axis?
mb_obs = np.asarray(mb_obs, dtype=np.uint8).swapaxes(1, 0).reshape(self.batch_ob_shape)
mb_rewards = np.asarray(mb_rewards, dtype=np.float32).swapaxes(1, 0)
mb_actions = np.asarray(mb_actions, dtype=np.int32).swapaxes(1, 0)
mb_values = np.asarray(mb_values, dtype=np.float32).swapaxes(1, 0)
mb_dones = np.asarray(mb_dones, dtype=np.bool).swapaxes(1, 0)
mb_masks = mb_dones[:, :-1]
mb_dones = mb_dones[:, 1:]
last_values = self.model.value(self.obs, self.states, self.dones).tolist()
#discount/bootstrap off value fn
# For each (reward, dones, value) tuple in enumerate(zip(..,..,..) : add rewards to list, add dones to list,
for n, (rewards, dones, value) in enumerate(zip(mb_rewards, mb_dones, last_values)):
rewards = rewards.tolist()
dones = dones.tolist()
if dones[-1] == 0:
rewards = discount_with_dones(rewards+[value], dones+[0], self.gamma)[:-1]
else:
rewards = discount_with_dones(rewards, dones, self.gamma)
mb_rewards[n] = rewards
# Todo: What are these values, print out, the original data is .flattened() to produce return vals
mb_rewards = mb_rewards.flatten()
mb_actions = mb_actions.flatten()
mb_values = mb_values.flatten()
mb_masks = mb_masks.flatten()
return mb_obs, mb_states, mb_rewards, mb_masks, mb_actions, mb_values
def learn(policy, env, seed, nsteps=5, total_timesteps=int(80e6), vf_coef=0.5, ent_coef=0.01, max_grad_norm=0.5, lr=7e-4, lrschedule='linear', epsilon=1e-5, alpha=0.99, gamma=0.99, log_interval=100):
tf.reset_default_graph()
set_global_seeds(seed)
nenvs = env.num_envs
print('rockin ' + str(nenvs))
ob_space = env.observation_space
ac_space = env.action_space
print('observation space: ' + str(ob_space))
print('action space: ' + str(ac_space))
# Initializes model with all arguments obtained from run_atari
# Model DOES NOT GET the env stack object
model = Model(policy=policy, ob_space=ob_space, ac_space=ac_space, nenvs=nenvs, nsteps=nsteps, ent_coef=ent_coef, vf_coef=vf_coef,
max_grad_norm=max_grad_norm, lr=lr, alpha=alpha, epsilon=epsilon, total_timesteps=total_timesteps, lrschedule=lrschedule)
# Intializes a runner using the above model, an environment, and nsteps to run '5'
# env is the VectorFrameStack object created in run_atari, holds 16 environments
# Runner DOES GET the env stack object
# Runner DOES get the model, which lacks the env stack object
runner = Runner(env, model, nsteps=nsteps, gamma=gamma)
file = open("testOutput.txt", "w")
file.write(str(datetime.datetime.now()))
nbatch = nenvs*nsteps
tstart = time.time()
maxAvgReward = 0
# Todo: Figure out how frequently this is: loop 1 to 137,501
for update in range(1, total_timesteps//nbatch+1):
# print("__________ LEARN control loop: " + str(update) + " ------> " + str(total_timesteps//nbatch+1))
# runner.run(), steps model, returns observations, states, rewards, masks, actions, values for all agents?
obs, states, rewards, masks, actions, values = runner.run()
# 80 observations, 16 envs * 5 steps
# print("LEARNING FROM: len(obs): " + str(len(obs)))
# Printing states: TypeError: object of type 'NoneType' has no len()
#print("len(states): " + str(len(states)))
# print("LEARNING FROM: len(rewards): " + str(len(rewards)))
# model.train(), trains model, takes all that above data, processes it through train_model
policy_loss, value_loss, policy_entropy = model.train(obs, states, rewards, masks, actions, values)
nseconds = time.time()-tstart
fps = int((update*nbatch)/nseconds)
if update % log_interval == 0 or update == 1:
avgReward = 0
rewardCount = 0
for reward in rewards:
# Prints 80 reward values? (5 training steps * 16 nenvs) = 80 reward values
print("a2c::::: learn() reward(s): " + str(reward))
avgReward += reward
rewardCount += 1
avgReward = avgReward / rewardCount
ev = explained_variance(values, rewards)
logger.record_tabular("nupdates", update)
logger.record_tabular("total_timesteps", update*nbatch)
logger.record_tabular("fps", fps)
logger.record_tabular("policy_entropy", float(policy_entropy))
logger.record_tabular("value_loss", float(value_loss))
logger.record_tabular("avgReward", float(avgReward))
logger.record_tabular("explained_variance", float(ev))
logger.dump_tabular()
# If avg reward of this batch is greater than previous avg reward, save model
if avgReward > maxAvgReward:
logger.log("Saving model due to mean reward increase: {} -> {}".format(
maxAvgReward, avgReward))
# Save model
model.save("modelName")
# Set prevAvgReward = avgReward
maxAvgReward = avgReward
file.close()
env.close()
|
[
"baselines.a2c.utils.Scheduler",
"tensorflow.reset_default_graph",
"tensorflow.train.RMSPropOptimizer",
"joblib.dump",
"baselines.a2c.utils.find_trainable_variables",
"tensorflow.clip_by_global_norm",
"numpy.copy",
"tensorflow.placeholder",
"tensorflow.summary.FileWriter",
"tensorflow.squeeze",
"tensorflow.gradients",
"baselines.a2c.utils.discount_with_dones",
"datetime.datetime.now",
"baselines.a2c.utils.cat_entropy",
"tensorflow.global_variables_initializer",
"numpy.asarray",
"tensorflow.reduce_mean",
"baselines.logger.dump_tabular",
"baselines.logger.record_tabular",
"baselines.common.tf_util.make_session",
"baselines.logger.get_dir",
"numpy.zeros",
"baselines.common.set_global_seeds",
"time.time",
"baselines.common.explained_variance",
"joblib.load",
"tensorflow.nn.sparse_softmax_cross_entropy_with_logits"
] |
[((9842, 9866), 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), '()\n', (9864, 9866), True, 'import tensorflow as tf\n'), ((9871, 9893), 'baselines.common.set_global_seeds', 'set_global_seeds', (['seed'], {}), '(seed)\n', (9887, 9893), False, 'from baselines.common import set_global_seeds, explained_variance\n'), ((10969, 10980), 'time.time', 'time.time', ([], {}), '()\n', (10978, 10980), False, 'import time\n'), ((842, 864), 'baselines.common.tf_util.make_session', 'tf_util.make_session', ([], {}), '()\n', (862, 864), False, 'from baselines.common import tf_util\n'), ((934, 968), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[nbatch]'], {}), '(tf.int32, [nbatch])\n', (948, 968), True, 'import tensorflow as tf\n'), ((983, 1019), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[nbatch]'], {}), '(tf.float32, [nbatch])\n', (997, 1019), True, 'import tensorflow as tf\n'), ((1032, 1068), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[nbatch]'], {}), '(tf.float32, [nbatch])\n', (1046, 1068), True, 'import tensorflow as tf\n'), ((1082, 1112), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[]'], {}), '(tf.float32, [])\n', (1096, 1112), True, 'import tensorflow as tf\n'), ((1749, 1828), 'tensorflow.nn.sparse_softmax_cross_entropy_with_logits', 'tf.nn.sparse_softmax_cross_entropy_with_logits', ([], {'logits': 'train_model.pi', 'labels': 'A'}), '(logits=train_model.pi, labels=A)\n', (1795, 1828), True, 'import tensorflow as tf\n'), ((2130, 2161), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['(ADV * neglogpac)'], {}), '(ADV * neglogpac)\n', (2144, 2161), True, 'import tensorflow as tf\n'), ((2788, 2821), 'baselines.a2c.utils.find_trainable_variables', 'find_trainable_variables', (['"""model"""'], {}), "('model')\n", (2812, 2821), False, 'from baselines.a2c.utils import Scheduler, make_path, find_trainable_variables\n'), ((3110, 3136), 'tensorflow.gradients', 'tf.gradients', (['loss', 'params'], {}), '(loss, params)\n', (3122, 3136), True, 'import tensorflow as tf\n'), ((3441, 3514), 'tensorflow.train.RMSPropOptimizer', 'tf.train.RMSPropOptimizer', ([], {'learning_rate': 'LR', 'decay': 'alpha', 'epsilon': 'epsilon'}), '(learning_rate=LR, decay=alpha, epsilon=epsilon)\n', (3466, 3514), True, 'import tensorflow as tf\n'), ((3664, 3725), 'baselines.a2c.utils.Scheduler', 'Scheduler', ([], {'v': 'lr', 'nvalues': 'total_timesteps', 'schedule': 'lrschedule'}), '(v=lr, nvalues=total_timesteps, schedule=lrschedule)\n', (3673, 3725), False, 'from baselines.a2c.utils import Scheduler, make_path, find_trainable_variables\n'), ((3745, 3795), 'tensorflow.summary.FileWriter', 'tf.summary.FileWriter', (['"""/tmp/helloTensorBoard.txt"""'], {}), "('/tmp/helloTensorBoard.txt')\n", (3766, 3795), True, 'import tensorflow as tf\n'), ((6198, 6242), 'numpy.zeros', 'np.zeros', (['(nenv, nh, nw, nc)'], {'dtype': 'np.uint8'}), '((nenv, nh, nw, nc), dtype=np.uint8)\n', (6206, 6242), True, 'import numpy as np\n'), ((2491, 2518), 'baselines.a2c.utils.cat_entropy', 'cat_entropy', (['train_model.pi'], {}), '(train_model.pi)\n', (2502, 2518), False, 'from baselines.a2c.utils import cat_entropy, mse\n'), ((3206, 3250), 'tensorflow.clip_by_global_norm', 'tf.clip_by_global_norm', (['grads', 'max_grad_norm'], {}), '(grads, max_grad_norm)\n', (3228, 3250), True, 'import tensorflow as tf\n'), ((5225, 5246), 'joblib.dump', 'joblib.dump', (['ps', 'path'], {}), '(ps, path)\n', (5236, 5246), False, 'import joblib\n'), ((5305, 5327), 'joblib.load', 'joblib.load', (['load_path'], {}), '(load_path)\n', (5316, 5327), False, 'import joblib\n'), ((10903, 10926), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (10924, 10926), False, 'import datetime\n'), ((11961, 11972), 'time.time', 'time.time', ([], {}), '()\n', (11970, 11972), False, 'import time\n'), ((12463, 12498), 'baselines.common.explained_variance', 'explained_variance', (['values', 'rewards'], {}), '(values, rewards)\n', (12481, 12498), False, 'from baselines.common import set_global_seeds, explained_variance\n'), ((12512, 12553), 'baselines.logger.record_tabular', 'logger.record_tabular', (['"""nupdates"""', 'update'], {}), "('nupdates', update)\n", (12533, 12553), False, 'from baselines import logger\n'), ((12566, 12623), 'baselines.logger.record_tabular', 'logger.record_tabular', (['"""total_timesteps"""', '(update * nbatch)'], {}), "('total_timesteps', update * nbatch)\n", (12587, 12623), False, 'from baselines import logger\n'), ((12634, 12667), 'baselines.logger.record_tabular', 'logger.record_tabular', (['"""fps"""', 'fps'], {}), "('fps', fps)\n", (12655, 12667), False, 'from baselines import logger\n'), ((12955, 12976), 'baselines.logger.dump_tabular', 'logger.dump_tabular', ([], {}), '()\n', (12974, 12976), False, 'from baselines import logger\n'), ((2397, 2423), 'tensorflow.squeeze', 'tf.squeeze', (['train_model.vf'], {}), '(train_model.vf)\n', (2407, 2423), True, 'import tensorflow as tf\n'), ((4994, 5010), 'baselines.logger.get_dir', 'logger.get_dir', ([], {}), '()\n', (5008, 5010), False, 'from baselines import logger\n'), ((5791, 5824), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (5822, 5824), True, 'import tensorflow as tf\n'), ((7258, 7275), 'numpy.copy', 'np.copy', (['self.obs'], {}), '(self.obs)\n', (7265, 7275), True, 'import numpy as np\n'), ((8281, 8321), 'numpy.asarray', 'np.asarray', (['mb_rewards'], {'dtype': 'np.float32'}), '(mb_rewards, dtype=np.float32)\n', (8291, 8321), True, 'import numpy as np\n'), ((8358, 8396), 'numpy.asarray', 'np.asarray', (['mb_actions'], {'dtype': 'np.int32'}), '(mb_actions, dtype=np.int32)\n', (8368, 8396), True, 'import numpy as np\n'), ((8432, 8471), 'numpy.asarray', 'np.asarray', (['mb_values'], {'dtype': 'np.float32'}), '(mb_values, dtype=np.float32)\n', (8442, 8471), True, 'import numpy as np\n'), ((8506, 8541), 'numpy.asarray', 'np.asarray', (['mb_dones'], {'dtype': 'np.bool'}), '(mb_dones, dtype=np.bool)\n', (8516, 8541), True, 'import numpy as np\n'), ((9205, 9252), 'baselines.a2c.utils.discount_with_dones', 'discount_with_dones', (['rewards', 'dones', 'self.gamma'], {}), '(rewards, dones, self.gamma)\n', (9224, 9252), False, 'from baselines.a2c.utils import discount_with_dones\n'), ((5062, 5078), 'baselines.logger.get_dir', 'logger.get_dir', ([], {}), '()\n', (5076, 5078), False, 'from baselines import logger\n'), ((9096, 9159), 'baselines.a2c.utils.discount_with_dones', 'discount_with_dones', (['(rewards + [value])', '(dones + [0])', 'self.gamma'], {}), '(rewards + [value], dones + [0], self.gamma)\n', (9115, 9159), False, 'from baselines.a2c.utils import discount_with_dones\n'), ((8181, 8215), 'numpy.asarray', 'np.asarray', (['mb_obs'], {'dtype': 'np.uint8'}), '(mb_obs, dtype=np.uint8)\n', (8191, 8215), True, 'import numpy as np\n')]
|
import cv2
import sys
import numpy as np
import pyperclip as ppc
from tkinter import filedialog
from tkinter import *
def record_click(event,x,y,flags,param):
global mouseX,mouseY
if event == cv2.EVENT_LBUTTONDBLCLK:
mouseX,mouseY = x,y
point = "[" + str(mouseX) + ", " + str(mouseY) + "]"
cv2.drawMarker(img, (x, y), (0, 0, 255), markerSize=10, thickness=1)
blank = np.zeros((64,172,3), np.uint8)
cv2.putText(blank, point, (2, 20), cv2.FONT_HERSHEY_TRIPLEX, 0.75, (0, 0, 255))
cv2.imshow("Point", blank)
k=cv2.waitKey(10) & 0XFF
failed = False
if len(sys.argv) == 2:
file = str(sys.argv[1])
img = cv2.imread(file)
if not img.any():
failed = True
if len(sys.argv) != 2 or failed:
root = Tk()
root.filename = filedialog.askopenfilename(initialdir = ".",title = "Select file",filetypes = (("png files","*.png"),("jpeg files","*.jpg"),("all files","*.*")))
file = root.filename
img = cv2.imread(file)
root.destroy()
height, width, layers = img.shape
cv2.namedWindow("Select Points")
cv2.namedWindow("Point")
cv2.moveWindow("Point", width+132, 38)
cv2.setMouseCallback("Select Points",record_click)
points = "["
coord = ""
while(1):
cv2.imshow("Select Points",img)
k = cv2.waitKey(20) & 0xFF
if k == ord('\r'):
break
elif k == ord('s'):
coord = "[" + str(mouseX) + ", " + str(mouseY) + "], "
points += coord
print(coord[:-2], " - saved")
elif k == ord('\b'):
points = points[:-len(coord)]
print(coord[:-2], " - removed")
if len(points) > 3:
points = points[:-2]
points += "]"
print(points)
ppc.copy(points)
|
[
"cv2.putText",
"cv2.waitKey",
"numpy.zeros",
"tkinter.filedialog.askopenfilename",
"cv2.drawMarker",
"cv2.imread",
"cv2.setMouseCallback",
"pyperclip.copy",
"cv2.moveWindow",
"cv2.imshow",
"cv2.namedWindow"
] |
[((1004, 1036), 'cv2.namedWindow', 'cv2.namedWindow', (['"""Select Points"""'], {}), "('Select Points')\n", (1019, 1036), False, 'import cv2\n'), ((1037, 1061), 'cv2.namedWindow', 'cv2.namedWindow', (['"""Point"""'], {}), "('Point')\n", (1052, 1061), False, 'import cv2\n'), ((1062, 1102), 'cv2.moveWindow', 'cv2.moveWindow', (['"""Point"""', '(width + 132)', '(38)'], {}), "('Point', width + 132, 38)\n", (1076, 1102), False, 'import cv2\n'), ((1101, 1152), 'cv2.setMouseCallback', 'cv2.setMouseCallback', (['"""Select Points"""', 'record_click'], {}), "('Select Points', record_click)\n", (1121, 1152), False, 'import cv2\n'), ((1601, 1617), 'pyperclip.copy', 'ppc.copy', (['points'], {}), '(points)\n', (1609, 1617), True, 'import pyperclip as ppc\n'), ((646, 662), 'cv2.imread', 'cv2.imread', (['file'], {}), '(file)\n', (656, 662), False, 'import cv2\n'), ((761, 912), 'tkinter.filedialog.askopenfilename', 'filedialog.askopenfilename', ([], {'initialdir': '"""."""', 'title': '"""Select file"""', 'filetypes': "(('png files', '*.png'), ('jpeg files', '*.jpg'), ('all files', '*.*'))"}), "(initialdir='.', title='Select file', filetypes=(\n ('png files', '*.png'), ('jpeg files', '*.jpg'), ('all files', '*.*')))\n", (787, 912), False, 'from tkinter import filedialog\n'), ((936, 952), 'cv2.imread', 'cv2.imread', (['file'], {}), '(file)\n', (946, 952), False, 'import cv2\n'), ((1191, 1223), 'cv2.imshow', 'cv2.imshow', (['"""Select Points"""', 'img'], {}), "('Select Points', img)\n", (1201, 1223), False, 'import cv2\n'), ((315, 383), 'cv2.drawMarker', 'cv2.drawMarker', (['img', '(x, y)', '(0, 0, 255)'], {'markerSize': '(10)', 'thickness': '(1)'}), '(img, (x, y), (0, 0, 255), markerSize=10, thickness=1)\n', (329, 383), False, 'import cv2\n'), ((397, 429), 'numpy.zeros', 'np.zeros', (['(64, 172, 3)', 'np.uint8'], {}), '((64, 172, 3), np.uint8)\n', (405, 429), True, 'import numpy as np\n'), ((433, 512), 'cv2.putText', 'cv2.putText', (['blank', 'point', '(2, 20)', 'cv2.FONT_HERSHEY_TRIPLEX', '(0.75)', '(0, 0, 255)'], {}), '(blank, point, (2, 20), cv2.FONT_HERSHEY_TRIPLEX, 0.75, (0, 0, 255))\n', (444, 512), False, 'import cv2\n'), ((518, 544), 'cv2.imshow', 'cv2.imshow', (['"""Point"""', 'blank'], {}), "('Point', blank)\n", (528, 544), False, 'import cv2\n'), ((1231, 1246), 'cv2.waitKey', 'cv2.waitKey', (['(20)'], {}), '(20)\n', (1242, 1246), False, 'import cv2\n'), ((552, 567), 'cv2.waitKey', 'cv2.waitKey', (['(10)'], {}), '(10)\n', (563, 567), False, 'import cv2\n')]
|
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
pW = 0.48
pL = 1-pW
b_max = 500 #max bet ($)
def total_losses(b0, f, num_losses):
sum=0
for i in range(0, num_losses):
sum += f**i
return b0*sum
def net_winnings(b0, f, num_games):
# assumes you won on the last game and lost on all games prior
return b0*f**(num_games-1)-total_losses(b0, f, num_games-1)
def expected_outcome(b0, f, printN=False):
# print(b0)
# print(f)
N = np.int(np.log(b_max/b0)/np.log(f))+1
if printN:
print("N is {}".format(N))
sum = 0
for i in range(1, N+1):
sum += pL**(i-1)*net_winnings(b0, f, i)
expectation = pW*sum - pL**N*total_losses(b0, f, N)
return expectation
# b0 = 481.00
# f = 1.01
# print(expected_outcome(b0, f, 0))
b0 = np.arange(1, 500, 1) # initial bets
f = np.arange(1.01, 5, 0.1) # bet increase factor (=2 in typical Martingale System)
b0, f = np.meshgrid(b0, f)
results=[]
for b0i, fi in zip(b0.flatten(), f.flatten()):
# print("Expected outcome for b0 = {0}, f ={1:.2f} is {2}".format(b0i, fi, expected_outcome(b0i, fi)))
results.append(expected_outcome(b0i, fi))
results = np.asarray(results)
i_opt = np.argmax(results)
b_opt = b0.flatten()[i_opt]
f_opt = f.flatten()[i_opt]
result_opt = results[i_opt]
results=np.reshape(results, b0.shape)
for var in ['b_opt', 'f_opt', 'result_opt']:
print("{0} = {1:.04f}".format(var, eval(var)))
#plot
fig = plt.figure()
ax = fig.gca(projection='3d')
# Plot the surface.
surf = ax.plot_surface(b0, f, results, cmap=cm.coolwarm,
linewidth=0, antialiased=False)
ax.set_xlabel('Initial Bet ($)')
ax.set_ylabel('Bet Increase Factor')
ax.set_zlabel('Expected Outcome ($)')
# ax.set_zlim(0, ax.get_zlim()[1])
fig.suptitle('Expected Outcome Surface using Martingale System on Roulette')
plt.title('Min/Max Bet: \$1/\$500', fontsize=10)
plt.show()
print('bye')
|
[
"matplotlib.pyplot.title",
"numpy.meshgrid",
"matplotlib.pyplot.show",
"numpy.log",
"numpy.argmax",
"numpy.asarray",
"matplotlib.pyplot.figure",
"numpy.arange",
"numpy.reshape"
] |
[((859, 879), 'numpy.arange', 'np.arange', (['(1)', '(500)', '(1)'], {}), '(1, 500, 1)\n', (868, 879), True, 'import numpy as np\n'), ((900, 923), 'numpy.arange', 'np.arange', (['(1.01)', '(5)', '(0.1)'], {}), '(1.01, 5, 0.1)\n', (909, 923), True, 'import numpy as np\n'), ((989, 1007), 'numpy.meshgrid', 'np.meshgrid', (['b0', 'f'], {}), '(b0, f)\n', (1000, 1007), True, 'import numpy as np\n'), ((1231, 1250), 'numpy.asarray', 'np.asarray', (['results'], {}), '(results)\n', (1241, 1250), True, 'import numpy as np\n'), ((1259, 1277), 'numpy.argmax', 'np.argmax', (['results'], {}), '(results)\n', (1268, 1277), True, 'import numpy as np\n'), ((1370, 1399), 'numpy.reshape', 'np.reshape', (['results', 'b0.shape'], {}), '(results, b0.shape)\n', (1380, 1399), True, 'import numpy as np\n'), ((1510, 1522), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1520, 1522), True, 'import matplotlib.pyplot as plt\n'), ((1906, 1956), 'matplotlib.pyplot.title', 'plt.title', (['"""Min/Max Bet: \\\\$1/\\\\$500"""'], {'fontsize': '(10)'}), "('Min/Max Bet: \\\\$1/\\\\$500', fontsize=10)\n", (1915, 1956), True, 'import matplotlib.pyplot as plt\n'), ((1956, 1966), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1964, 1966), True, 'import matplotlib.pyplot as plt\n'), ((543, 561), 'numpy.log', 'np.log', (['(b_max / b0)'], {}), '(b_max / b0)\n', (549, 561), True, 'import numpy as np\n'), ((560, 569), 'numpy.log', 'np.log', (['f'], {}), '(f)\n', (566, 569), True, 'import numpy as np\n')]
|
import cv2
import numpy as np
from skimage.segmentation import slic
from skimage import color
from skimage.measure import regionprops
from PIL import Image, ImageDraw
import moviepy.editor as mp
import random
import os
class GifMaker():
def to_mosaic_gif(self, img_path, n_segments = 150, segments_per_frame = 3):
img = cv2.imread(img_path)
# generate superpixels
segments = slic(img, n_segments = n_segments, sigma = 5)
# generate image with superpixels avg color
superpixels_image = color.label2rgb(segments, img, kind='avg')
superpixels_image = cv2.normalize(superpixels_image, None, alpha = 0,
beta = 255, norm_type = cv2.NORM_MINMAX, dtype = cv2.CV_8U)
mask = np.zeros(img.shape[:2], dtype = "uint8")
n_segments = len(np.unique(segments))
frames = []
for (i, segVal) in enumerate(np.unique(segments)):
# construct a mask for the segment
mask[segments == segVal] = 255
a = cv2.bitwise_and(superpixels_image, superpixels_image, mask = mask)
a = np.uint8(a)
a = cv2.cvtColor(a, cv2.COLOR_BGR2RGB)
if i % segments_per_frame == 0:
n_segments -= segments_per_frame
frames.append(Image.fromarray(a))
if n_segments > 0:
frames.append(Image.fromarray(a))
path_splitted = os.path.split(img_path)
filename_with_extension = path_splitted[1]
path = path_splitted[0]
filename = filename_with_extension.split('.')[0]
self.__save_gif(path, filename, frames)
self.__to_mp4(path, filename)
def __save_gif(self, path, filename, frames):
filename = filename + '.gif'
save_path = os.path.join(path, filename)
frames[0].save(save_path,
save_all=True, format='GIF', append_images=frames[1:],
optimize=True, quality=20, duration=1, loop=0)
def __to_mp4(self, path, filename):
read_path = os.path.join(path, filename + '.gif')
save_path = os.path.join(path, filename + '.mp4')
clip = mp.VideoFileClip(read_path)
clip.write_videofile(save_path)
if __name__ == "__main__":
img_path = './data/prova_gif.jpg'
g = GifMaker()
g.to_mosaic_gif(img_path)
|
[
"numpy.uint8",
"skimage.color.label2rgb",
"moviepy.editor.VideoFileClip",
"cv2.bitwise_and",
"cv2.cvtColor",
"numpy.zeros",
"PIL.Image.fromarray",
"cv2.imread",
"cv2.normalize",
"skimage.segmentation.slic",
"os.path.split",
"os.path.join",
"numpy.unique"
] |
[((326, 346), 'cv2.imread', 'cv2.imread', (['img_path'], {}), '(img_path)\n', (336, 346), False, 'import cv2\n'), ((385, 426), 'skimage.segmentation.slic', 'slic', (['img'], {'n_segments': 'n_segments', 'sigma': '(5)'}), '(img, n_segments=n_segments, sigma=5)\n', (389, 426), False, 'from skimage.segmentation import slic\n'), ((499, 541), 'skimage.color.label2rgb', 'color.label2rgb', (['segments', 'img'], {'kind': '"""avg"""'}), "(segments, img, kind='avg')\n", (514, 541), False, 'from skimage import color\n'), ((564, 670), 'cv2.normalize', 'cv2.normalize', (['superpixels_image', 'None'], {'alpha': '(0)', 'beta': '(255)', 'norm_type': 'cv2.NORM_MINMAX', 'dtype': 'cv2.CV_8U'}), '(superpixels_image, None, alpha=0, beta=255, norm_type=cv2.\n NORM_MINMAX, dtype=cv2.CV_8U)\n', (577, 670), False, 'import cv2\n'), ((696, 734), 'numpy.zeros', 'np.zeros', (['img.shape[:2]'], {'dtype': '"""uint8"""'}), "(img.shape[:2], dtype='uint8')\n", (704, 734), True, 'import numpy as np\n'), ((1247, 1270), 'os.path.split', 'os.path.split', (['img_path'], {}), '(img_path)\n', (1260, 1270), False, 'import os\n'), ((1567, 1595), 'os.path.join', 'os.path.join', (['path', 'filename'], {}), '(path, filename)\n', (1579, 1595), False, 'import os\n'), ((1800, 1837), 'os.path.join', 'os.path.join', (['path', "(filename + '.gif')"], {}), "(path, filename + '.gif')\n", (1812, 1837), False, 'import os\n'), ((1852, 1889), 'os.path.join', 'os.path.join', (['path', "(filename + '.mp4')"], {}), "(path, filename + '.mp4')\n", (1864, 1889), False, 'import os\n'), ((1899, 1926), 'moviepy.editor.VideoFileClip', 'mp.VideoFileClip', (['read_path'], {}), '(read_path)\n', (1915, 1926), True, 'import moviepy.editor as mp\n'), ((759, 778), 'numpy.unique', 'np.unique', (['segments'], {}), '(segments)\n', (768, 778), True, 'import numpy as np\n'), ((826, 845), 'numpy.unique', 'np.unique', (['segments'], {}), '(segments)\n', (835, 845), True, 'import numpy as np\n'), ((928, 992), 'cv2.bitwise_and', 'cv2.bitwise_and', (['superpixels_image', 'superpixels_image'], {'mask': 'mask'}), '(superpixels_image, superpixels_image, mask=mask)\n', (943, 992), False, 'import cv2\n'), ((1002, 1013), 'numpy.uint8', 'np.uint8', (['a'], {}), '(a)\n', (1010, 1013), True, 'import numpy as np\n'), ((1021, 1055), 'cv2.cvtColor', 'cv2.cvtColor', (['a', 'cv2.COLOR_BGR2RGB'], {}), '(a, cv2.COLOR_BGR2RGB)\n', (1033, 1055), False, 'import cv2\n'), ((1208, 1226), 'PIL.Image.fromarray', 'Image.fromarray', (['a'], {}), '(a)\n', (1223, 1226), False, 'from PIL import Image, ImageDraw\n'), ((1147, 1165), 'PIL.Image.fromarray', 'Image.fromarray', (['a'], {}), '(a)\n', (1162, 1165), False, 'from PIL import Image, ImageDraw\n')]
|
# conda activate pymesh
import math
import numpy as np
import trimesh
import cv2
import os
import configs.config_loader as cfg_loader
import NDF_combine as NDF
def str2bool(inp):
return inp.lower() in 'true'
class Renderer():
def __init__(self):
self.get_args()
self.create_plane_points_from_bounds()
self.define_screen_points()
self.define_unit_rays()
def get_args(self):
"""
:return:
"""
self.args = cfg_loader.get_config()
# print(self.args.cam_position)
# print(self.args.cam_orientation)
os.makedirs(self.args.folder, exist_ok=True)
def create_plane_points_from_bounds(self):
"""
Creates a plane of points which acts as the screen for rendering
"""
# create an xy plane
x = np.linspace(-self.args.screen_bound, self.args.screen_bound, self.args.size)
y = np.linspace(-self.args.screen_bound, self.args.screen_bound, self.args.size)
X, Y = np.meshgrid(x, y, indexing='ij')
X = X.reshape((np.prod(X.shape),))
Y = Y.reshape((np.prod(Y.shape),))
# append the third dimension coordinate to the xy plane
points_list = np.column_stack((X, Y))
points_list = np.insert(points_list, 2, self.args.screen_depth, axis=1)
self.points_list = points_list
def to_rotation_matrix(self):
"""
Creates rotation matrix from the input euler angles
"""
euler_angles = np.array(self.args.cam_orientation)
R_x = np.array([[1, 0, 0],
[0, math.cos(math.radians(euler_angles[0])), -math.sin(math.radians(euler_angles[0]))],
[0, math.sin(math.radians(euler_angles[0])), math.cos(math.radians(euler_angles[0]))]
])
R_y = np.array([[math.cos(math.radians(euler_angles[1])), 0, math.sin(math.radians(euler_angles[1]))],
[0, 1, 0],
[-math.sin(math.radians(euler_angles[1])), 0, math.cos(math.radians(euler_angles[1]))]
])
R_z = np.array([[math.cos(math.radians(euler_angles[2])), -math.sin(math.radians(euler_angles[2])), 0],
[math.sin(math.radians(euler_angles[2])), math.cos(math.radians(euler_angles[2])), 0],
[0, 0, 1]
])
R = np.dot(R_z, np.dot(R_y, R_x))
self.rot_matrix = R
def to_transf_matrix(self):
"""
Creates a transformation matrix from rotation matrix and translation vector
"""
self.to_rotation_matrix()
temp_trans = np.array([0, 0, 0])
temp_trans = np.reshape(temp_trans, (1, 3))
rot = np.concatenate((self.rot_matrix, temp_trans), axis=0)
rot = np.concatenate((rot, np.reshape(np.array([0, 0, 0, 1]), (4, 1))), axis=1)
inp_trans = np.reshape(self.args.cam_position, (3,))
inp_trans = np.concatenate((inp_trans, [1]), axis=0)
rot[:, 3] = inp_trans
self.trans_mat = rot
def append_one(self, arr):
"""
:param arr:
:return:
"""
append = np.ones(arr.shape[0])
append = np.reshape(append, (append.shape[0], 1))
new_arr = np.concatenate((arr, append), axis=1)
return new_arr
def define_screen_points(self):
"""
Transforms the screen points and camera position using the camera translation and orientation information provided by the user
"""
self.create_plane_points_from_bounds()
self.to_transf_matrix()
cam_loc = np.array([0, 0, 0])
screen_and_cam = np.vstack((cam_loc, self.points_list))
screen_and_cam_hom = self.append_one(screen_and_cam)
# 4 X SIZE^2
screen_and_cam_hom_T = np.transpose(screen_and_cam_hom, (1, 0))
screen_and_cam_hom_T_transformed = np.matmul(self.trans_mat, screen_and_cam_hom_T)
# SIZE^2 X 4
screen_and_cam_hom_transformed = np.transpose(screen_and_cam_hom_T_transformed, (1, 0))
# SIZE^2 X 3
self.screen_and_cam_transformed = screen_and_cam_hom_transformed[:, :3]
if self.args.debug_mode:
trimesh.Trimesh(vertices=self.screen_and_cam_transformed, faces=[]).export('setup_camera_rot.off')
def define_unit_rays(self):
"""
Defines rays from camera to the screen along which
"""
# Separate screen points and camera point
points = self.screen_and_cam_transformed[1:, :]
self.cam_trans = np.reshape(self.screen_and_cam_transformed[0, :], (1, 3))
# Define ray paths from camera
ray_vector = (points - self.cam_trans)
# Normalize ray vectors
norm_ray = np.linalg.norm(ray_vector, ord=2, axis=1)
norm_ray = np.reshape(norm_ray, (self.args.size * self.args.size, 1))
self.unit_rays = ray_vector / norm_ray
def get_lgth_rays(self):
"""
:return:
"""
src_batch = np.repeat([self.args.light_position], self.args.size * self.args.size, axis=0)
rays = src_batch - self.final_points
norm_ray = np.linalg.norm(rays, ord=2, axis=1)
norm_ray = np.reshape(norm_ray, (self.args.size * self.args.size, 1))
self.ray_to_src = rays / norm_ray
def run(self):
"""
Runs the ray marching algorithm
"""
print(self.args)
NDF.loadNDF(
mode = 'test', index = self.args.index,
pointcloud_samples = self.args.pc_samples,
exp_name = self.args.exp_name, data_dir = self.args.data_dir,
split_file = self.args.split_file, sample_distribution = self.args.sample_ratio,
sample_sigmas = self.args.sample_std_dev, res = self.args.input_res
)
depth = np.zeros((self.args.size * self.args.size, 1))
cam_batch = np.repeat(self.cam_trans, self.args.size * self.args.size, axis=0)
points = cam_batch.copy()
iter = 1
ray = self.unit_rays.copy()
indices_cont_all = list(range(self.args.size * self.args.size))
while len(indices_cont_all) > 0:
print('Iter:', iter)
dists_points = NDF.predictRotNDF(points)
dists_points = np.reshape(dists_points, (self.args.size * self.args.size, 1))
indices_stop = np.where(dists_points < self.args.epsilon)[0]
indices_stop2 = np.where(depth > self.args.max_depth)[0]
indices_stop_all = list(set(indices_stop).union(set(indices_stop2)))
# print(len(indices_stop_all))
ray[indices_stop_all] = 0
setA = set(range(self.args.size * self.args.size))
setB = set(indices_stop_all)
indices_cont_all = list(setA.difference(setB))
# print(len(indices_cont_all))
depth[indices_cont_all] = depth[indices_cont_all] + self.args.alpha * dists_points[indices_cont_all]
points = points + (ray * (self.args.alpha * dists_points))
iter = iter + 1
points = points - (self.unit_rays * self.args.step_back)
self.final_points = points.copy()
## NORMALS
self.depth_np = depth.copy()
self.depth_np[self.depth_np > self.args.max_depth] = self.args.max_depth
dists, gradients = NDF.predictRotGradientNDF(points)
self.final_gradients = gradients.copy()
self.normals = np.reshape(gradients, (self.args.size * self.args.size, 3))
def save(self, image, name, size, normalize):
"""
:param image: Input image as np array
:param name: Name of file to be stored
:param size: Size of the image
:param normalize: whether to normalize all values to 0-1
Saves individual images
"""
if normalize:
image = (image + 1)/2
image = np.reshape(image, (self.args.size, self.args.size, size))
image = cv2.transpose(image)
image = cv2.flip(image, 0)
image = image[90:610, :]
cv2.imwrite(os.path.join(self.args.folder, name), np.uint8(255 * image))
def save_images(self):
"""
Saves Images after completion of the rendering algorithm
"""
shade = np.sum(np.multiply(-self.unit_rays, self.normals), axis=1)
shade = np.reshape(shade, (shade.shape[0], 1))
shade[self.depth_np == self.args.max_depth] = 1
self.save(shade, 'shade.jpg', 1, True)
# SHADE WITH LIGhT SOURCE
if self.args.shade:
self.get_lgth_rays()
shd_lgth = np.sum(np.multiply(self.ray_to_src, self.normals), axis=1)
shd_lgth = np.reshape(shd_lgth, (shd_lgth.shape[0], 1))
shd_lgth[self.depth_np == self.args.max_depth ] = 1
self.save(shd_lgth, 'shade_src.jpg', 1, True)
if self.args.normal:
RGB_normals = self.final_gradients.copy()
inds = (self.depth_np == self.args.max_depth)
for j in range(3):
new_arr = np.reshape(RGB_normals[:, j], (self.args.size * self.args.size, 1))
new_arr[inds] = 1
black_pixels_mask = np.all(RGB_normals == [0, 0, 0], axis=-1)
RGB_normals[black_pixels_mask] = np.array([1, 1, 1])
self.save(RGB_normals, 'normals.jpg', 3, True)
if self.args.depth:
depth_normalized = np.copy(self.depth_np / self.args.max_depth)
self.save(depth_normalized, 'depth_final.jpg', 1, False)
if __name__ == "__main__":
renderer = Renderer()
renderer.run()
renderer.save_images()
|
[
"numpy.ones",
"cv2.transpose",
"numpy.linalg.norm",
"configs.config_loader.get_config",
"os.path.join",
"numpy.prod",
"numpy.meshgrid",
"numpy.multiply",
"numpy.copy",
"math.radians",
"numpy.transpose",
"numpy.insert",
"NDF_combine.predictRotGradientNDF",
"numpy.reshape",
"numpy.linspace",
"NDF_combine.predictRotNDF",
"numpy.repeat",
"trimesh.Trimesh",
"numpy.uint8",
"cv2.flip",
"numpy.dot",
"numpy.vstack",
"numpy.concatenate",
"numpy.all",
"os.makedirs",
"numpy.zeros",
"numpy.where",
"numpy.array",
"numpy.matmul",
"numpy.column_stack",
"NDF_combine.loadNDF"
] |
[((484, 507), 'configs.config_loader.get_config', 'cfg_loader.get_config', ([], {}), '()\n', (505, 507), True, 'import configs.config_loader as cfg_loader\n'), ((600, 644), 'os.makedirs', 'os.makedirs', (['self.args.folder'], {'exist_ok': '(True)'}), '(self.args.folder, exist_ok=True)\n', (611, 644), False, 'import os\n'), ((836, 912), 'numpy.linspace', 'np.linspace', (['(-self.args.screen_bound)', 'self.args.screen_bound', 'self.args.size'], {}), '(-self.args.screen_bound, self.args.screen_bound, self.args.size)\n', (847, 912), True, 'import numpy as np\n'), ((925, 1001), 'numpy.linspace', 'np.linspace', (['(-self.args.screen_bound)', 'self.args.screen_bound', 'self.args.size'], {}), '(-self.args.screen_bound, self.args.screen_bound, self.args.size)\n', (936, 1001), True, 'import numpy as np\n'), ((1017, 1049), 'numpy.meshgrid', 'np.meshgrid', (['x', 'y'], {'indexing': '"""ij"""'}), "(x, y, indexing='ij')\n", (1028, 1049), True, 'import numpy as np\n'), ((1223, 1246), 'numpy.column_stack', 'np.column_stack', (['(X, Y)'], {}), '((X, Y))\n', (1238, 1246), True, 'import numpy as np\n'), ((1269, 1326), 'numpy.insert', 'np.insert', (['points_list', '(2)', 'self.args.screen_depth'], {'axis': '(1)'}), '(points_list, 2, self.args.screen_depth, axis=1)\n', (1278, 1326), True, 'import numpy as np\n'), ((1512, 1547), 'numpy.array', 'np.array', (['self.args.cam_orientation'], {}), '(self.args.cam_orientation)\n', (1520, 1547), True, 'import numpy as np\n'), ((2675, 2694), 'numpy.array', 'np.array', (['[0, 0, 0]'], {}), '([0, 0, 0])\n', (2683, 2694), True, 'import numpy as np\n'), ((2716, 2746), 'numpy.reshape', 'np.reshape', (['temp_trans', '(1, 3)'], {}), '(temp_trans, (1, 3))\n', (2726, 2746), True, 'import numpy as np\n'), ((2761, 2814), 'numpy.concatenate', 'np.concatenate', (['(self.rot_matrix, temp_trans)'], {'axis': '(0)'}), '((self.rot_matrix, temp_trans), axis=0)\n', (2775, 2814), True, 'import numpy as np\n'), ((2924, 2964), 'numpy.reshape', 'np.reshape', (['self.args.cam_position', '(3,)'], {}), '(self.args.cam_position, (3,))\n', (2934, 2964), True, 'import numpy as np\n'), ((2985, 3025), 'numpy.concatenate', 'np.concatenate', (['(inp_trans, [1])'], {'axis': '(0)'}), '((inp_trans, [1]), axis=0)\n', (2999, 3025), True, 'import numpy as np\n'), ((3197, 3218), 'numpy.ones', 'np.ones', (['arr.shape[0]'], {}), '(arr.shape[0])\n', (3204, 3218), True, 'import numpy as np\n'), ((3236, 3276), 'numpy.reshape', 'np.reshape', (['append', '(append.shape[0], 1)'], {}), '(append, (append.shape[0], 1))\n', (3246, 3276), True, 'import numpy as np\n'), ((3295, 3332), 'numpy.concatenate', 'np.concatenate', (['(arr, append)'], {'axis': '(1)'}), '((arr, append), axis=1)\n', (3309, 3332), True, 'import numpy as np\n'), ((3654, 3673), 'numpy.array', 'np.array', (['[0, 0, 0]'], {}), '([0, 0, 0])\n', (3662, 3673), True, 'import numpy as np\n'), ((3699, 3737), 'numpy.vstack', 'np.vstack', (['(cam_loc, self.points_list)'], {}), '((cam_loc, self.points_list))\n', (3708, 3737), True, 'import numpy as np\n'), ((3852, 3892), 'numpy.transpose', 'np.transpose', (['screen_and_cam_hom', '(1, 0)'], {}), '(screen_and_cam_hom, (1, 0))\n', (3864, 3892), True, 'import numpy as np\n'), ((3936, 3983), 'numpy.matmul', 'np.matmul', (['self.trans_mat', 'screen_and_cam_hom_T'], {}), '(self.trans_mat, screen_and_cam_hom_T)\n', (3945, 3983), True, 'import numpy as np\n'), ((4047, 4101), 'numpy.transpose', 'np.transpose', (['screen_and_cam_hom_T_transformed', '(1, 0)'], {}), '(screen_and_cam_hom_T_transformed, (1, 0))\n', (4059, 4101), True, 'import numpy as np\n'), ((4596, 4653), 'numpy.reshape', 'np.reshape', (['self.screen_and_cam_transformed[0, :]', '(1, 3)'], {}), '(self.screen_and_cam_transformed[0, :], (1, 3))\n', (4606, 4653), True, 'import numpy as np\n'), ((4793, 4834), 'numpy.linalg.norm', 'np.linalg.norm', (['ray_vector'], {'ord': '(2)', 'axis': '(1)'}), '(ray_vector, ord=2, axis=1)\n', (4807, 4834), True, 'import numpy as np\n'), ((4854, 4912), 'numpy.reshape', 'np.reshape', (['norm_ray', '(self.args.size * self.args.size, 1)'], {}), '(norm_ray, (self.args.size * self.args.size, 1))\n', (4864, 4912), True, 'import numpy as np\n'), ((5052, 5130), 'numpy.repeat', 'np.repeat', (['[self.args.light_position]', '(self.args.size * self.args.size)'], {'axis': '(0)'}), '([self.args.light_position], self.args.size * self.args.size, axis=0)\n', (5061, 5130), True, 'import numpy as np\n'), ((5195, 5230), 'numpy.linalg.norm', 'np.linalg.norm', (['rays'], {'ord': '(2)', 'axis': '(1)'}), '(rays, ord=2, axis=1)\n', (5209, 5230), True, 'import numpy as np\n'), ((5250, 5308), 'numpy.reshape', 'np.reshape', (['norm_ray', '(self.args.size * self.args.size, 1)'], {}), '(norm_ray, (self.args.size * self.args.size, 1))\n', (5260, 5308), True, 'import numpy as np\n'), ((5469, 5777), 'NDF_combine.loadNDF', 'NDF.loadNDF', ([], {'mode': '"""test"""', 'index': 'self.args.index', 'pointcloud_samples': 'self.args.pc_samples', 'exp_name': 'self.args.exp_name', 'data_dir': 'self.args.data_dir', 'split_file': 'self.args.split_file', 'sample_distribution': 'self.args.sample_ratio', 'sample_sigmas': 'self.args.sample_std_dev', 'res': 'self.args.input_res'}), "(mode='test', index=self.args.index, pointcloud_samples=self.\n args.pc_samples, exp_name=self.args.exp_name, data_dir=self.args.\n data_dir, split_file=self.args.split_file, sample_distribution=self.\n args.sample_ratio, sample_sigmas=self.args.sample_std_dev, res=self.\n args.input_res)\n", (5480, 5777), True, 'import NDF_combine as NDF\n'), ((5915, 5961), 'numpy.zeros', 'np.zeros', (['(self.args.size * self.args.size, 1)'], {}), '((self.args.size * self.args.size, 1))\n', (5923, 5961), True, 'import numpy as np\n'), ((5983, 6049), 'numpy.repeat', 'np.repeat', (['self.cam_trans', '(self.args.size * self.args.size)'], {'axis': '(0)'}), '(self.cam_trans, self.args.size * self.args.size, axis=0)\n', (5992, 6049), True, 'import numpy as np\n'), ((7429, 7462), 'NDF_combine.predictRotGradientNDF', 'NDF.predictRotGradientNDF', (['points'], {}), '(points)\n', (7454, 7462), True, 'import NDF_combine as NDF\n'), ((7534, 7593), 'numpy.reshape', 'np.reshape', (['gradients', '(self.args.size * self.args.size, 3)'], {}), '(gradients, (self.args.size * self.args.size, 3))\n', (7544, 7593), True, 'import numpy as np\n'), ((7971, 8028), 'numpy.reshape', 'np.reshape', (['image', '(self.args.size, self.args.size, size)'], {}), '(image, (self.args.size, self.args.size, size))\n', (7981, 8028), True, 'import numpy as np\n'), ((8046, 8066), 'cv2.transpose', 'cv2.transpose', (['image'], {}), '(image)\n', (8059, 8066), False, 'import cv2\n'), ((8083, 8101), 'cv2.flip', 'cv2.flip', (['image', '(0)'], {}), '(image, 0)\n', (8091, 8101), False, 'import cv2\n'), ((8425, 8463), 'numpy.reshape', 'np.reshape', (['shade', '(shade.shape[0], 1)'], {}), '(shade, (shade.shape[0], 1))\n', (8435, 8463), True, 'import numpy as np\n'), ((2427, 2443), 'numpy.dot', 'np.dot', (['R_y', 'R_x'], {}), '(R_y, R_x)\n', (2433, 2443), True, 'import numpy as np\n'), ((6312, 6337), 'NDF_combine.predictRotNDF', 'NDF.predictRotNDF', (['points'], {}), '(points)\n', (6329, 6337), True, 'import NDF_combine as NDF\n'), ((6365, 6427), 'numpy.reshape', 'np.reshape', (['dists_points', '(self.args.size * self.args.size, 1)'], {}), '(dists_points, (self.args.size * self.args.size, 1))\n', (6375, 6427), True, 'import numpy as np\n'), ((8156, 8192), 'os.path.join', 'os.path.join', (['self.args.folder', 'name'], {}), '(self.args.folder, name)\n', (8168, 8192), False, 'import os\n'), ((8194, 8215), 'numpy.uint8', 'np.uint8', (['(255 * image)'], {}), '(255 * image)\n', (8202, 8215), True, 'import numpy as np\n'), ((8357, 8399), 'numpy.multiply', 'np.multiply', (['(-self.unit_rays)', 'self.normals'], {}), '(-self.unit_rays, self.normals)\n', (8368, 8399), True, 'import numpy as np\n'), ((8769, 8813), 'numpy.reshape', 'np.reshape', (['shd_lgth', '(shd_lgth.shape[0], 1)'], {}), '(shd_lgth, (shd_lgth.shape[0], 1))\n', (8779, 8813), True, 'import numpy as np\n'), ((9270, 9311), 'numpy.all', 'np.all', (['(RGB_normals == [0, 0, 0])'], {'axis': '(-1)'}), '(RGB_normals == [0, 0, 0], axis=-1)\n', (9276, 9311), True, 'import numpy as np\n'), ((9357, 9376), 'numpy.array', 'np.array', (['[1, 1, 1]'], {}), '([1, 1, 1])\n', (9365, 9376), True, 'import numpy as np\n'), ((9496, 9540), 'numpy.copy', 'np.copy', (['(self.depth_np / self.args.max_depth)'], {}), '(self.depth_np / self.args.max_depth)\n', (9503, 9540), True, 'import numpy as np\n'), ((1073, 1089), 'numpy.prod', 'np.prod', (['X.shape'], {}), '(X.shape)\n', (1080, 1089), True, 'import numpy as np\n'), ((1116, 1132), 'numpy.prod', 'np.prod', (['Y.shape'], {}), '(Y.shape)\n', (1123, 1132), True, 'import numpy as np\n'), ((6456, 6498), 'numpy.where', 'np.where', (['(dists_points < self.args.epsilon)'], {}), '(dists_points < self.args.epsilon)\n', (6464, 6498), True, 'import numpy as np\n'), ((6530, 6567), 'numpy.where', 'np.where', (['(depth > self.args.max_depth)'], {}), '(depth > self.args.max_depth)\n', (6538, 6567), True, 'import numpy as np\n'), ((8694, 8736), 'numpy.multiply', 'np.multiply', (['self.ray_to_src', 'self.normals'], {}), '(self.ray_to_src, self.normals)\n', (8705, 8736), True, 'import numpy as np\n'), ((9135, 9202), 'numpy.reshape', 'np.reshape', (['RGB_normals[:, j]', '(self.args.size * self.args.size, 1)'], {}), '(RGB_normals[:, j], (self.args.size * self.args.size, 1))\n', (9145, 9202), True, 'import numpy as np\n'), ((2861, 2883), 'numpy.array', 'np.array', (['[0, 0, 0, 1]'], {}), '([0, 0, 0, 1])\n', (2869, 2883), True, 'import numpy as np\n'), ((4250, 4317), 'trimesh.Trimesh', 'trimesh.Trimesh', ([], {'vertices': 'self.screen_and_cam_transformed', 'faces': '[]'}), '(vertices=self.screen_and_cam_transformed, faces=[])\n', (4265, 4317), False, 'import trimesh\n'), ((1620, 1649), 'math.radians', 'math.radians', (['euler_angles[0]'], {}), '(euler_angles[0])\n', (1632, 1649), False, 'import math\n'), ((1732, 1761), 'math.radians', 'math.radians', (['euler_angles[0]'], {}), '(euler_angles[0])\n', (1744, 1761), False, 'import math\n'), ((1773, 1802), 'math.radians', 'math.radians', (['euler_angles[0]'], {}), '(euler_angles[0])\n', (1785, 1802), False, 'import math\n'), ((1867, 1896), 'math.radians', 'math.radians', (['euler_angles[1]'], {}), '(euler_angles[1])\n', (1879, 1896), False, 'import math\n'), ((1911, 1940), 'math.radians', 'math.radians', (['euler_angles[1]'], {}), '(euler_angles[1])\n', (1923, 1940), False, 'import math\n'), ((2058, 2087), 'math.radians', 'math.radians', (['euler_angles[1]'], {}), '(euler_angles[1])\n', (2070, 2087), False, 'import math\n'), ((2152, 2181), 'math.radians', 'math.radians', (['euler_angles[2]'], {}), '(euler_angles[2])\n', (2164, 2181), False, 'import math\n'), ((2264, 2293), 'math.radians', 'math.radians', (['euler_angles[2]'], {}), '(euler_angles[2])\n', (2276, 2293), False, 'import math\n'), ((2305, 2334), 'math.radians', 'math.radians', (['euler_angles[2]'], {}), '(euler_angles[2])\n', (2317, 2334), False, 'import math\n'), ((1662, 1691), 'math.radians', 'math.radians', (['euler_angles[0]'], {}), '(euler_angles[0])\n', (1674, 1691), False, 'import math\n'), ((2014, 2043), 'math.radians', 'math.radians', (['euler_angles[1]'], {}), '(euler_angles[1])\n', (2026, 2043), False, 'import math\n'), ((2194, 2223), 'math.radians', 'math.radians', (['euler_angles[2]'], {}), '(euler_angles[2])\n', (2206, 2223), False, 'import math\n')]
|
import os, sys
import numpy as np
from copy import deepcopy
from warnings import warn
from .Mesh import Mesh
from .GeometricPath import *
from Florence.Tensor import totuple, unique2d
__all__ = ['HarvesterPatch', 'SubdivisionArc', 'SubdivisionCircle', 'QuadBall',
'QuadBallSphericalArc']
"""
A series of custom meshes
"""
def HarvesterPatch(ndisc=20, nradial=4, show_plot=False):
"""Creates a custom mesh for an energy harvester patch. [Not to be modified]
ndisc: [int] number of discretisation in c
ndradial: [int] number of discretisation in radial directions for different
components of harevester
"""
center = np.array([30.6979,20.5])
p1 = np.array([30.,20.])
p2 = np.array([30.,21.])
p1line = p1 - center
p2line = p2 - center
radius = np.linalg.norm(p1line)
pp = np.array([center[0],center[1]+radius])
y_line = pp - center
start_angle = -np.pi/2. - np.arccos(np.linalg.norm(y_line*p1line)/np.linalg.norm(y_line)/np.linalg.norm(p1line))
end_angle = np.pi/2. + np.arccos(np.linalg.norm(y_line*p1line)/np.linalg.norm(y_line)/np.linalg.norm(p1line))
points = np.array([p1,p2,center])
# nradial = 4
mesh = Mesh()
mesh.Arc(element_type="quad", radius=radius, start_angle=start_angle,
end_angle=end_angle, nrad=nradial, ncirc=ndisc, center=(center[0],center[1]), refinement=True)
mesh1 = Mesh()
mesh1.Triangle(element_type="quad",npoints=nradial, c1=totuple(center), c2=totuple(p1), c3=totuple(p2))
mesh += mesh1
mesh_patch = Mesh()
mesh_patch.HollowArc(ncirc=ndisc, nrad=nradial, center=(-7.818181,44.22727272),
start_angle=np.arctan(44.22727272/-7.818181), end_angle=np.arctan(-24.22727272/37.818181),
element_type="quad", inner_radius=43.9129782, outer_radius=44.9129782)
mesh3 = Mesh()
mesh3.Triangle(element_type="quad",npoints=nradial, c2=totuple(p1), c3=totuple(p2), c1=(mesh_patch.points[0,0], mesh_patch.points[0,1]))
mesh += mesh3
mesh += mesh_patch
mesh.Extrude(nlong=ndisc,length=40)
if show_plot:
mesh.SimplePlot()
return mesh
def CurvedPlate(ncirc=2, nlong=20, show_plot=False):
"""Creates custom mesh for plate with curved edges
ncirc discretisation around circular fillets
nlong discretisation along the length - X
"""
mesh_arc = Mesh()
mesh_arc.Arc(element_type="quad",nrad=ncirc,ncirc=ncirc, radius=5)
mesh_arc1 = deepcopy(mesh_arc)
mesh_arc1.points[:,1] += 15
mesh_arc1.points[:,0] += 95
mesh_arc2 = deepcopy(mesh_arc)
mesh_arc2.points[:,1] +=15
mesh_arc2.points[:,0] *= -1.
mesh_arc2.points[:,0] += 5.
mesh_plate1 = Mesh()
mesh_plate1.Rectangle(element_type="quad",lower_left_point=(5,15),upper_right_point=(95,20),ny=ncirc, nx=nlong)
mesh_plate2 = deepcopy(mesh_plate1)
mesh_plate2.points[:,1] -= 5.
mesh_square1 = Mesh()
mesh_square1.Square(element_type="quad",lower_left_point=(0,10), side_length=5,nx=ncirc,ny=ncirc)
mesh_square2 = deepcopy(mesh_square1)
mesh_square2.points[:,0] += 95
mesh = mesh_plate1 + mesh_plate2 + mesh_arc1 + mesh_arc2 + mesh_square1 + mesh_square2
mesh.Extrude(length=0.5,nlong=1)
mesh2 = deepcopy(mesh)
mesh2.points[:,2] += 0.5
mesh += mesh2
if show_plot:
mesh.SimplePlot()
return mesh
def SubdivisionArc(center=(0.,0.), radius=1., nrad=16, ncirc=40,
start_angle=0., end_angle=np.pi/2., element_type="tri", refinement=False, refinement_level=2):
"""Creates a mesh on circle using midpoint subdivision.
This function is internally called from Mesh.Circle if
'midpoint_subdivision' algorithm is selected
"""
if start_angle!=0. and end_angle!=np.pi/2.:
raise ValueError("Subdivision based arc only produces meshes for a quarter-circle arc for now")
r = float(radius)
h_r = float(radius)/2.
nx = int(ncirc/4.)
ny = int(nrad/2.)
if nx < 3:
warn("Number of division in circumferential direction too low")
mesh = Mesh()
mesh.Rectangle(element_type="quad", lower_left_point=(-1.,-1.),
upper_right_point=(1.,1.), nx=nx, ny=ny)
uv = np.array([
[-1.,-1],
[1.,-1],
[1.,1],
[-1.,1],
])
t = np.pi/4.
end_points = np.array([
[0.,h_r*np.sin(t)],
[h_r*np.cos(t),h_r*np.sin(t)],
[r*np.cos(t),r*np.sin(t)],
[0.,radius],
])
edge_points = mesh.points[np.unique(mesh.edges),:]
new_end_points = []
new_end_points.append(end_points[0,:])
new_end_points.append(end_points[1,:])
new_end_points.append(end_points[2,:])
tt = np.linspace(np.pi/4,np.pi/2,nx)
x = r*np.cos(tt)
y = r*np.sin(tt)
interp_p = np.vstack((x,y)).T
for i in range(1,len(x)-1):
new_end_points.append([x[i], y[i]])
new_end_points.append(end_points[3,:])
new_end_points = np.array(new_end_points)
new_uv = []
new_uv.append(uv[0,:])
new_uv.append(uv[1,:])
new_uv.append(uv[2,:])
L = 0.
for i in range(1,interp_p.shape[0]):
L += np.linalg.norm(interp_p[i,:] - interp_p[i-1,:])
interp_uv = []
last_uv = uv[2,:]
for i in range(1,interp_p.shape[0]-1):
val = (uv[3,:] - uv[2,:])*np.linalg.norm(interp_p[i,:] - interp_p[i-1,:])/L + last_uv
last_uv = np.copy(val)
interp_uv.append(val)
interp_uv = np.array(interp_uv)
new_uv = np.array(new_uv)
if interp_uv.shape[0] !=0:
new_uv = np.vstack((new_uv,interp_uv))
new_uv = np.vstack((new_uv,uv[3,:]))
from Florence.FunctionSpace import MeanValueCoordinateMapping
new_points = np.zeros_like(mesh.points)
# All nodes barring the ones lying on the arc
for i in range(mesh.nnode - nx - 1):
point = MeanValueCoordinateMapping(mesh.points[i,:], new_uv, new_end_points)
new_points[i,:] = point
# The nodes on the arc are not exactly on the arc
# so they need to be snapped/clipped
tt = np.linspace(np.pi/4,np.pi/2,nx+1)[::-1]
x = r*np.cos(tt)
y = r*np.sin(tt)
new_points[mesh.nnode-nx-1:,:] = np.vstack((x,y)).T
mesh.points = new_points
rmesh = deepcopy(mesh)
rmesh.points = mesh.Rotate(angle=-np.pi/2., copy=True)
rmesh.points[:,1] *= -1.
mesh += rmesh
mesh.LaplacianSmoothing(niter=10)
qmesh = Mesh()
qmesh.Rectangle(element_type="quad", lower_left_point=(0.0,0.0),
upper_right_point=(h_r*np.cos(t),h_r*np.sin(t)),
nx=nx,
ny=nx)
mesh += qmesh
# mesh.LaplacianSmoothing(niter=20)
NodeSliderSmootherArc(mesh, niter=20)
mesh.points[:,0] += center[0]
mesh.points[:,1] += center[1]
if refinement:
mesh.Refine(level=refinement_level)
if element_type == "tri":
sys.stdout = open(os.devnull, "w")
mesh.ConvertQuadsToTris()
sys.stdout = sys.__stdout__
return mesh
def SubdivisionCircle(center=(0.,0.), radius=1., nrad=16, ncirc=40,
element_type="tri", refinement=False, refinement_level=2):
"""Creates a mesh on circle using midpoint subdivision.
This function is internally called from Mesh.Circle if
'midpoint_subdivision' algorithm is selected
"""
r = float(radius)
h_r = float(radius)/2.
nx = int(ncirc/4.)
ny = int(nrad/2.)
if nx < 3:
warn("Number of division in circumferential direction too low")
mesh = Mesh()
mesh.Rectangle(element_type="quad", lower_left_point=(-1.,-1.),
upper_right_point=(1.,1.), nx=nx, ny=ny)
uv = np.array([
[-1.,-1],
[1.,-1],
[1.,1],
[-1.,1],
])
t = np.pi/4
end_points = np.array([
[-h_r*np.cos(t),h_r*np.sin(t)],
[h_r*np.cos(t),h_r*np.sin(t)],
[r*np.cos(t),r*np.sin(t)],
[-r*np.cos(t),r*np.sin(t)],
])
edge_points = mesh.points[np.unique(mesh.edges),:]
new_end_points = []
new_end_points.append(end_points[0,:])
new_end_points.append(end_points[1,:])
new_end_points.append(end_points[2,:])
tt = np.linspace(np.pi/4,3*np.pi/4,nx)
x = r*np.cos(tt)
y = r*np.sin(tt)
interp_p = np.vstack((x,y)).T
for i in range(1,len(x)-1):
new_end_points.append([x[i], y[i]])
new_end_points.append(end_points[3,:])
new_end_points = np.array(new_end_points)
new_uv = []
new_uv.append(uv[0,:])
new_uv.append(uv[1,:])
new_uv.append(uv[2,:])
L = 0.
for i in range(1,interp_p.shape[0]):
L += np.linalg.norm(interp_p[i,:] - interp_p[i-1,:])
interp_uv = []
last_uv = uv[2,:]
for i in range(1,interp_p.shape[0]-1):
val = (uv[3,:] - uv[2,:])*np.linalg.norm(interp_p[i,:] - interp_p[i-1,:])/L + last_uv
last_uv = np.copy(val)
interp_uv.append(val)
interp_uv = np.array(interp_uv)
new_uv = np.array(new_uv)
if interp_uv.shape[0] !=0:
new_uv = np.vstack((new_uv,interp_uv))
new_uv = np.vstack((new_uv,uv[3,:]))
from Florence.FunctionSpace import MeanValueCoordinateMapping
new_points = np.zeros_like(mesh.points)
for i in range(mesh.nnode):
point = MeanValueCoordinateMapping(mesh.points[i,:], new_uv, new_end_points)
new_points[i,:] = point
mesh.points = new_points
rmesh = deepcopy(mesh)
rmesh.points = mesh.Rotate(angle=np.pi/2., copy=True)
mesh += rmesh
rmesh.points = rmesh.Rotate(angle=np.pi/2., copy=True)
mesh += rmesh
rmesh.points = rmesh.Rotate(angle=np.pi/2., copy=True)
mesh += rmesh
mesh.LaplacianSmoothing(niter=10)
qmesh = Mesh()
qmesh.Rectangle(element_type="quad", lower_left_point=(-h_r*np.cos(t),-h_r*np.sin(t)),
upper_right_point=(h_r*np.cos(t),h_r*np.sin(t)),
nx=nx,
ny=nx)
mesh += qmesh
mesh.LaplacianSmoothing(niter=20)
mesh.points[:,0] += center[0]
mesh.points[:,1] += center[1]
if refinement:
mesh.Refine(level=refinement_level)
if element_type == "tri":
sys.stdout = open(os.devnull, "w")
mesh.ConvertQuadsToTris()
sys.stdout = sys.__stdout__
return mesh
def QuadBall(center=(0.,0.,0.), radius=1., n=10, element_type="hex"):
"""Creates a fully hexahedral mesh on sphere using midpoint subdivision algorithm
by creating a cube and spherifying it using PostMesh's projection schemes
inputs:
n: [int] number of divsion in every direction.
Given that this implementation is based on
high order bases different divisions in
different directions is not possible
"""
try:
from Florence import Mesh, BoundaryCondition, DisplacementFormulation, FEMSolver, LinearSolver
from Florence import LinearElastic, NeoHookean
from Florence.Tensor import prime_number_factorisation
except ImportError:
raise ImportError("This function needs Florence's core support")
n = int(n)
if n > 50:
# Values beyond this result in >1M DoFs due to internal prime factoristaion splitting
raise ValueError("The value of n={} (division in each direction) is too high".format(str(n)))
if not isinstance(center,tuple):
raise ValueError("The center of the circle should be given in a tuple with two elements (x,y,z)")
if len(center) != 3:
raise ValueError("The center of the circle should be given in a tuple with two elements (x,y,z)")
if n == 2 or n==3 or n==5 or n==7:
ps = [n]
else:
def factorise_all(n):
if n < 2:
n = 2
factors = prime_number_factorisation(n)
if len(factors) == 1 and n > 2:
n += 1
factors = prime_number_factorisation(n)
return factors
factors = factorise_all(n)
ps = []
for factor in factors:
ps +=factorise_all(factor)
# Do high ps first
ps = np.sort(ps)[::-1].tolist()
niter = len(ps)
# IGS file for sphere with radius 1000.
sphere_igs_file_content = SphereIGS()
with open("sphere_cad_file.igs", "w") as f:
f.write(sphere_igs_file_content)
sys.stdout = open(os.devnull, "w")
ndim = 3
scale = 1000.
condition = 1.e020
mesh = Mesh()
material = LinearElastic(ndim, mu=1., lamb=4.)
# Keep the solver iterative for low memory consumption. All boundary points are Dirichlet BCs
# so they will be exact anyway
solver = LinearSolver(linear_solver="iterative", linear_solver_type="cg2",
dont_switch_solver=True, iterative_solver_tolerance=1e-9)
for it in range(niter):
if it == 0:
mesh.Parallelepiped(element_type="hex", nx=1, ny=1, nz=1, lower_left_rear_point=(-0.5,-0.5,-0.5),
upper_right_front_point=(0.5,0.5,0.5))
mesh.GetHighOrderMesh(p=ps[it], equally_spaced=True)
boundary_condition = BoundaryCondition()
boundary_condition.SetCADProjectionParameters(
"sphere_cad_file.igs",
scale=scale,condition=condition, project_on_curves=True, solve_for_planar_faces=True,
modify_linear_mesh_on_projection=True, fix_dof_elsewhere=False
)
boundary_condition.GetProjectionCriteria(mesh)
formulation = DisplacementFormulation(mesh)
fem_solver = FEMSolver(
number_of_load_increments=1,
analysis_nature="linear",
force_not_computing_mesh_qualities=True,
report_log_level=0,
optimise=True)
solution = fem_solver.Solve(formulation=formulation, mesh=mesh,
material=material, boundary_condition=boundary_condition, solver=solver)
mesh.points += solution.sol[:,:,-1]
mesh = mesh.ConvertToLinearMesh()
os.remove("sphere_cad_file.igs")
if not np.isclose(radius,1):
mesh.points *= radius
mesh.points[:,0] += center[0]
mesh.points[:,1] += center[1]
mesh.points[:,2] += center[2]
if element_type == "tet":
mesh.ConvertHexesToTets()
sys.stdout = sys.__stdout__
return mesh
def QuadBallSurface(center=(0.,0.,0.), radius=1., n=10, element_type="quad"):
"""Creates a surface quad mesh on sphere using midpoint subdivision algorithm
by creating a cube and spherifying it using PostMesh's projection schemes.
Unlike the volume QuadBall method there is no restriction on number of divisions
here as no system of equations is solved
inputs:
n: [int] number of divsion in every direction.
Given that this implementation is based on
high order bases different divisions in
different directions is not possible
"""
try:
from Florence import Mesh, BoundaryCondition, DisplacementFormulation, FEMSolver, LinearSolver
from Florence import LinearElastic, NeoHookean
from Florence.Tensor import prime_number_factorisation
except ImportError:
raise ImportError("This function needs Florence's core support")
n = int(n)
if not isinstance(center,tuple):
raise ValueError("The center of the circle should be given in a tuple with two elements (x,y,z)")
if len(center) != 3:
raise ValueError("The center of the circle should be given in a tuple with two elements (x,y,z)")
if n == 2 or n==3 or n==5 or n==7:
ps = [n]
else:
def factorise_all(n):
if n < 2:
n = 2
factors = prime_number_factorisation(n)
if len(factors) == 1 and n > 2:
n += 1
factors = prime_number_factorisation(n)
return factors
factors = factorise_all(n)
ps = []
for factor in factors:
ps +=factorise_all(factor)
# Do high ps first
ps = np.sort(ps)[::-1].tolist()
niter = len(ps)
sphere_igs_file_content = SphereIGS()
with open("sphere_cad_file.igs", "w") as f:
f.write(sphere_igs_file_content)
sys.stdout = open(os.devnull, "w")
ndim = 3
scale = 1000.
condition = 1.e020
mesh = Mesh()
material = LinearElastic(ndim, mu=1., lamb=4.)
for it in range(niter):
if it == 0:
mesh.Parallelepiped(element_type="hex", nx=1, ny=1, nz=1, lower_left_rear_point=(-0.5,-0.5,-0.5),
upper_right_front_point=(0.5,0.5,0.5))
mesh = mesh.CreateSurface2DMeshfrom3DMesh()
mesh.GetHighOrderMesh(p=ps[it], equally_spaced=True)
mesh = mesh.CreateDummy3DMeshfrom2DMesh()
formulation = DisplacementFormulation(mesh)
else:
mesh.GetHighOrderMesh(p=ps[it], equally_spaced=True)
mesh = mesh.CreateDummy3DMeshfrom2DMesh()
boundary_condition = BoundaryCondition()
boundary_condition.SetCADProjectionParameters(
"sphere_cad_file.igs",
scale=scale,condition=condition,
project_on_curves=True,
solve_for_planar_faces=True,
modify_linear_mesh_on_projection=True,
fix_dof_elsewhere=False
)
boundary_condition.GetProjectionCriteria(mesh)
nodesDBC, Dirichlet = boundary_condition.PostMeshWrapper(formulation, mesh, None, None, FEMSolver())
mesh.points[nodesDBC.ravel(),:] += Dirichlet
mesh = mesh.CreateSurface2DMeshfrom3DMesh()
mesh = mesh.ConvertToLinearMesh()
os.remove("sphere_cad_file.igs")
if not np.isclose(radius,1):
mesh.points *= radius
mesh.points[:,0] += center[0]
mesh.points[:,1] += center[1]
mesh.points[:,2] += center[2]
if element_type == "tri":
mesh.ConvertQuadsToTris()
sys.stdout = sys.__stdout__
return mesh
def QuadBallSphericalArc(center=(0.,0.,0.), inner_radius=9., outer_radius=10., n=10, nthick=1,
element_type="hex", cut_threshold=None, portion=1./8.):
"""Similar to QuadBall but hollow and creates only 1/8th or 1/4th or 1/2th of the sphere.
Starting and ending angles are not supported. Radial division (nthick: to be consistent
with SphericalArc method of Mesh class) is supported
input:
cut_threshold [float] cutting threshold for element removal since this function is based
QuadBall. Ideal value is zero, so prescribe a value as close to zero
as possible, however that might not always be possible as the cut
might take remove some wanted elements [default = -0.01]
portion [float] portion of the sphere to take. Can only be 1/8., 1/4., 1/2.
"""
assert inner_radius < outer_radius
mm = QuadBallSurface(n=n, element_type=element_type)
offset = outer_radius*2.
if cut_threshold is None:
cut_threshold = -0.01
if portion == 1./8.:
mm.RemoveElements(np.array([ [ cut_threshold, cut_threshold, cut_threshold], [ offset, offset, offset]]))
elif portion == 1./4.:
mm.RemoveElements(np.array([ [ cut_threshold, cut_threshold, -offset], [ offset, offset, offset]]))
elif portion == 1./2.:
mm.RemoveElements(np.array([ [ cut_threshold, -offset, -offset], [ offset, offset, offset]]))
else:
raise ValueError("The value of portion can only be 1/8., 1/4. or 1/2.")
radii = np.linspace(inner_radius, outer_radius, nthick+1)
mesh = Mesh()
mesh.element_type = "hex"
mesh.nelem = 0
mesh.nnode = 0
for i in range(nthick):
mm1, mm2 = deepcopy(mm), deepcopy(mm)
if not np.isclose(radii[i],1):
mm1.points *= radii[i]
if not np.isclose(radii[i+1],1):
mm2.points *= radii[i+1]
if i == 0:
elements = np.hstack((mm1.elements, mm1.nnode + mm2.elements)).astype(np.int64)
mesh.elements = np.copy(elements)
mesh.points = np.vstack((mm1.points, mm2.points))
else:
elements = np.hstack((mesh.elements[(i-1)*mm2.nelem:i*mm2.nelem,4:],
mesh.nnode + mm2.elements)).astype(np.int64)
mesh.elements = np.vstack((mesh.elements, elements))
mesh.points = np.vstack((mesh.points, mm2.points))
mesh.nelem = mesh.elements.shape[0]
mesh.nnode = mesh.points.shape[0]
mesh.elements = np.ascontiguousarray(mesh.elements, dtype=np.int64)
mesh.nelem = mesh.elements.shape[0]
mesh.nnode = mesh.points.shape[0]
mesh.GetBoundaryFaces()
mesh.GetBoundaryEdges()
mesh.points[:,0] += center[0]
mesh.points[:,1] += center[1]
mesh.points[:,2] += center[2]
return mesh
def Torus(show_plot=False):
"""Custom mesh for torus
"""
raise NotImplementedError("Not fully implemented yet")
# MAKE TORUS WORK
from copy import deepcopy
from numpy.linalg import norm
mesh = Mesh()
mesh.Circle(element_type="quad", ncirc=2, nrad=2)
tmesh = deepcopy(mesh)
arc = GeometricArc(start=(10,10,8),end=(10,10,-8))
# arc.GeometricArc()
nlong = 10
points = mesh.Extrude(path=arc, nlong=nlong)
# mesh.SimplePlot()
# print points
# elem_nodes = tmesh.elements[0,:]
# p1 = tmesh.points[elem_nodes[0],:]
# p2 = tmesh.points[elem_nodes[1],:]
# p3 = tmesh.points[elem_nodes[2],:]
# p4 = tmesh.points[elem_nodes[3],:]
# E1 = np.append(p2 - p1, 0.0)
# E2 = np.append(p4 - p1, 0.0)
# E3 = np.array([0,0,1.])
# E1 /= norm(E1)
# E2 /= norm(E2)
# # print E1,E2,E3
# elem_nodes = mesh.elements[0,:]
# p1 = mesh.points[elem_nodes[0],:]
# p2 = mesh.points[elem_nodes[1],:]
# p3 = mesh.points[elem_nodes[2],:]
# p4 = mesh.points[elem_nodes[3],:]
# p5 = mesh.points[elem_nodes[4],:]
# e1 = p2 - p1
# e2 = p4 - p1
# e3 = p5 - p1
# e1 /= norm(e1)
# e2 /= norm(e2)
# e3 /= norm(e3)
# # print e1,e2,e3
# # TRANSFORMATION MATRIX
# Q = np.array([
# [np.einsum('i,i',e1,E1), np.einsum('i,i',e1,E2), np.einsum('i,i',e1,E3)],
# [np.einsum('i,i',e2,E1), np.einsum('i,i',e2,E2), np.einsum('i,i',e2,E3)],
# [np.einsum('i,i',e3,E1), np.einsum('i,i',e3,E2), np.einsum('i,i',e3,E3)]
# ])
# mesh.points = np.dot(mesh.points,Q.T)
# points = np.dot(points,Q)
# E1 = np.array([1,0,0.])
E3 = np.array([0.,0.,1.])
nnode_2D = tmesh.points.shape[0]
for i in range(nlong+1):
# e1 = points[i,:][None,:]/norm(points[i,:])
# Q = np.dot(E1[:,None],e1)
# vpoints = np.dot(points,Q)
e3 = points[i+1,:] - points[i,:]; e3 /= norm(e3)
Q = np.dot(e3[:,None],E3[None,:])
# print Q
# print np.dot(Q,points[i,:][:,None])
vpoints = np.dot(points,Q)
# print current_points
mesh.points[nnode_2D*i:nnode_2D*(i+1),:2] = tmesh.points + points[i,:2]
mesh.points[nnode_2D*i:nnode_2D*(i+1), 2] = vpoints[i,2]
# print Q
# print tmesh.points
# mesh = Mesh.HexahedralProjection()
if show_plot:
mesh.SimplePlot()
return mesh
def NodeSliderSmootherArc(mesh, niter=10):
"""This is less than half-baked node slider smoother that only works
for arc type meshes
"""
if mesh.element_type != "quad":
raise RuntimeError("Only implemented for quads")
un_edges = np.unique(mesh.edges)
points = mesh.points[un_edges,:]
radius = mesh.Bounds[1,1]
# For all x==0
idx = np.where(np.isclose(mesh.points[:,0], 0.0)==True)[0]
idx_sort = np.lexsort((mesh.points[idx,1],mesh.points[idx,0]))
mesh.points[idx[idx_sort],1] = np.linspace(0.,radius, idx_sort.shape[0])
# For all y==0
idx = np.where(np.isclose(mesh.points[:,1], 0.0)==True)[0]
idx_sort = np.lexsort((mesh.points[idx,0],mesh.points[idx,1]))
mesh.points[idx[idx_sort],0] = np.linspace(0.,radius, idx_sort.shape[0])
mesh.LaplacianSmoothing(niter)
# -----------------------------------------------------------------------------------------
def SphereIGS():
# IGS file for sphere with radius 1000.
sphere_igs_file_content ="""
S0000001
,,31HOpen CASCADE IGES processor 6.7,13HFilename.iges, G0000001
16HOpen CASCADE 6.7,31HOpen CASCADE IGES processor 6.7,32,308,15,308,15,G0000002
,1.,6,1HM,1,0.00001,15H20150628.043945,1E-07,1.007104,5Hroman,,11,0, G0000003
15H20150628.043945,; G0000004
186 1 0 0 0 0 0 000000000D0000001
186 0 0 1 0 0D0000002
514 2 0 0 0 0 0 000010000D0000003
514 0 0 1 1 0D0000004
510 3 0 0 0 0 0 000010000D0000005
510 0 0 1 1 0D0000006
196 4 0 0 0 0 0 000010000D0000007
196 0 0 1 1 0D0000008
116 5 0 0 0 0 0 000010400D0000009
116 0 0 1 0 0D0000010
123 6 0 0 0 0 0 000010200D0000011
123 0 0 1 0 0D0000012
123 7 0 0 0 0 0 000010200D0000013
123 0 0 1 0 0D0000014
508 8 0 0 0 0 0 000010000D0000015
508 0 0 2 1 0D0000016
502 10 0 0 0 0 0 000010000D0000017
502 0 0 2 1 0D0000018
110 12 0 0 0 0 0 000010000D0000019
110 0 0 1 0 0D0000020
504 13 0 0 0 0 0 000010001D0000021
504 0 0 1 1 0D0000022
100 14 0 0 0 0 25 000010000D0000023
100 0 0 1 0 0D0000024
124 15 0 0 0 0 0 000000000D0000025
124 0 0 2 0 0D0000026
110 17 0 0 0 0 0 000010000D0000027
110 0 0 1 0 0D0000028
110 18 0 0 0 0 0 000010000D0000029
110 0 0 1 0 0D0000030
110 19 0 0 0 0 0 000010000D0000031
110 0 0 1 0 0D0000032
186,3,1,0; 0000001P0000001
514,1,5,1; 0000003P0000002
510,7,1,1,15; 0000005P0000003
196,9,1.,11,13; 0000007P0000004
116,0.,0.,0.,0; 0000009P0000005
123,0.,0.,1.; 0000011P0000006
123,1.,0.,-0.; 0000013P0000007
508,4,1,17,1,0,1,0,19,0,21,1,0,1,0,27,1,17,2,1,1,0,29,0,21,1,1, 0000015P0000008
1,0,31; 0000015P0000009
502,2,6.123233996E-17,-1.499759783E-32,1.,6.123233996E-17, 0000017P0000010
-1.499759783E-32,-1.; 0000017P0000011
110,360.,90.,0.,0.,90.,0.; 0000019P0000012
504,1,23,17,2,17,1; 0000021P0000013
100,0.,0.,0.,-1.836970199E-16,-1.,3.061616998E-16,1.; 0000023P0000014
124,1.,0.,-2.449293598E-16,0.,-2.449293598E-16,0.,-1.,0.,0.,1., 0000025P0000015
0.,0.; 0000025P0000016
110,0.,90.,-0.,0.,-90.,-0.; 0000027P0000017
110,0.,-90.,0.,360.,-90.,0.; 0000029P0000018
110,360.,-90.,0.,360.,90.,0.; 0000031P0000019
S 1G 4D 32P 19 T0000001
"""
return sphere_igs_file_content
|
[
"os.remove",
"Florence.Tensor.totuple",
"numpy.isclose",
"numpy.sin",
"numpy.linalg.norm",
"Florence.LinearElastic",
"Florence.Mesh",
"numpy.unique",
"Florence.BoundaryCondition",
"Florence.Tensor.prime_number_factorisation",
"numpy.zeros_like",
"numpy.copy",
"numpy.linspace",
"copy.deepcopy",
"numpy.hstack",
"numpy.sort",
"numpy.cos",
"numpy.dot",
"numpy.arctan",
"Florence.DisplacementFormulation",
"numpy.vstack",
"Florence.LinearSolver",
"numpy.lexsort",
"Florence.FunctionSpace.MeanValueCoordinateMapping",
"numpy.array",
"Florence.FEMSolver",
"warnings.warn",
"numpy.ascontiguousarray"
] |
[((700, 725), 'numpy.array', 'np.array', (['[30.6979, 20.5]'], {}), '([30.6979, 20.5])\n', (708, 725), True, 'import numpy as np\n'), ((738, 760), 'numpy.array', 'np.array', (['[30.0, 20.0]'], {}), '([30.0, 20.0])\n', (746, 760), True, 'import numpy as np\n'), ((771, 793), 'numpy.array', 'np.array', (['[30.0, 21.0]'], {}), '([30.0, 21.0])\n', (779, 793), True, 'import numpy as np\n'), ((854, 876), 'numpy.linalg.norm', 'np.linalg.norm', (['p1line'], {}), '(p1line)\n', (868, 876), True, 'import numpy as np\n'), ((886, 927), 'numpy.array', 'np.array', (['[center[0], center[1] + radius]'], {}), '([center[0], center[1] + radius])\n', (894, 927), True, 'import numpy as np\n'), ((1196, 1222), 'numpy.array', 'np.array', (['[p1, p2, center]'], {}), '([p1, p2, center])\n', (1204, 1222), True, 'import numpy as np\n'), ((1251, 1257), 'Florence.Mesh', 'Mesh', ([], {}), '()\n', (1255, 1257), False, 'from Florence import Mesh, BoundaryCondition, DisplacementFormulation, FEMSolver, LinearSolver\n'), ((1448, 1454), 'Florence.Mesh', 'Mesh', ([], {}), '()\n', (1452, 1454), False, 'from Florence import Mesh, BoundaryCondition, DisplacementFormulation, FEMSolver, LinearSolver\n'), ((1600, 1606), 'Florence.Mesh', 'Mesh', ([], {}), '()\n', (1604, 1606), False, 'from Florence import Mesh, BoundaryCondition, DisplacementFormulation, FEMSolver, LinearSolver\n'), ((1882, 1888), 'Florence.Mesh', 'Mesh', ([], {}), '()\n', (1886, 1888), False, 'from Florence import Mesh, BoundaryCondition, DisplacementFormulation, FEMSolver, LinearSolver\n'), ((2433, 2439), 'Florence.Mesh', 'Mesh', ([], {}), '()\n', (2437, 2439), False, 'from Florence import Mesh, BoundaryCondition, DisplacementFormulation, FEMSolver, LinearSolver\n'), ((2528, 2546), 'copy.deepcopy', 'deepcopy', (['mesh_arc'], {}), '(mesh_arc)\n', (2536, 2546), False, 'from copy import deepcopy\n'), ((2627, 2645), 'copy.deepcopy', 'deepcopy', (['mesh_arc'], {}), '(mesh_arc)\n', (2635, 2645), False, 'from copy import deepcopy\n'), ((2761, 2767), 'Florence.Mesh', 'Mesh', ([], {}), '()\n', (2765, 2767), False, 'from Florence import Mesh, BoundaryCondition, DisplacementFormulation, FEMSolver, LinearSolver\n'), ((2903, 2924), 'copy.deepcopy', 'deepcopy', (['mesh_plate1'], {}), '(mesh_plate1)\n', (2911, 2924), False, 'from copy import deepcopy\n'), ((2979, 2985), 'Florence.Mesh', 'Mesh', ([], {}), '()\n', (2983, 2985), False, 'from Florence import Mesh, BoundaryCondition, DisplacementFormulation, FEMSolver, LinearSolver\n'), ((3108, 3130), 'copy.deepcopy', 'deepcopy', (['mesh_square1'], {}), '(mesh_square1)\n', (3116, 3130), False, 'from copy import deepcopy\n'), ((3309, 3323), 'copy.deepcopy', 'deepcopy', (['mesh'], {}), '(mesh)\n', (3317, 3323), False, 'from copy import deepcopy\n'), ((4136, 4142), 'Florence.Mesh', 'Mesh', ([], {}), '()\n', (4140, 4142), False, 'from Florence import Mesh, BoundaryCondition, DisplacementFormulation, FEMSolver, LinearSolver\n'), ((4270, 4324), 'numpy.array', 'np.array', (['[[-1.0, -1], [1.0, -1], [1.0, 1], [-1.0, 1]]'], {}), '([[-1.0, -1], [1.0, -1], [1.0, 1], [-1.0, 1]])\n', (4278, 4324), True, 'import numpy as np\n'), ((4760, 4797), 'numpy.linspace', 'np.linspace', (['(np.pi / 4)', '(np.pi / 2)', 'nx'], {}), '(np.pi / 4, np.pi / 2, nx)\n', (4771, 4797), True, 'import numpy as np\n'), ((5010, 5034), 'numpy.array', 'np.array', (['new_end_points'], {}), '(new_end_points)\n', (5018, 5034), True, 'import numpy as np\n'), ((5503, 5522), 'numpy.array', 'np.array', (['interp_uv'], {}), '(interp_uv)\n', (5511, 5522), True, 'import numpy as np\n'), ((5537, 5553), 'numpy.array', 'np.array', (['new_uv'], {}), '(new_uv)\n', (5545, 5553), True, 'import numpy as np\n'), ((5645, 5674), 'numpy.vstack', 'np.vstack', (['(new_uv, uv[3, :])'], {}), '((new_uv, uv[3, :]))\n', (5654, 5674), True, 'import numpy as np\n'), ((5757, 5783), 'numpy.zeros_like', 'np.zeros_like', (['mesh.points'], {}), '(mesh.points)\n', (5770, 5783), True, 'import numpy as np\n'), ((6276, 6290), 'copy.deepcopy', 'deepcopy', (['mesh'], {}), '(mesh)\n', (6284, 6290), False, 'from copy import deepcopy\n'), ((6448, 6454), 'Florence.Mesh', 'Mesh', ([], {}), '()\n', (6452, 6454), False, 'from Florence import Mesh, BoundaryCondition, DisplacementFormulation, FEMSolver, LinearSolver\n'), ((7524, 7530), 'Florence.Mesh', 'Mesh', ([], {}), '()\n', (7528, 7530), False, 'from Florence import Mesh, BoundaryCondition, DisplacementFormulation, FEMSolver, LinearSolver\n'), ((7658, 7712), 'numpy.array', 'np.array', (['[[-1.0, -1], [1.0, -1], [1.0, 1], [-1.0, 1]]'], {}), '([[-1.0, -1], [1.0, -1], [1.0, 1], [-1.0, 1]])\n', (7666, 7712), True, 'import numpy as np\n'), ((8174, 8215), 'numpy.linspace', 'np.linspace', (['(np.pi / 4)', '(3 * np.pi / 4)', 'nx'], {}), '(np.pi / 4, 3 * np.pi / 4, nx)\n', (8185, 8215), True, 'import numpy as np\n'), ((8426, 8450), 'numpy.array', 'np.array', (['new_end_points'], {}), '(new_end_points)\n', (8434, 8450), True, 'import numpy as np\n'), ((8919, 8938), 'numpy.array', 'np.array', (['interp_uv'], {}), '(interp_uv)\n', (8927, 8938), True, 'import numpy as np\n'), ((8953, 8969), 'numpy.array', 'np.array', (['new_uv'], {}), '(new_uv)\n', (8961, 8969), True, 'import numpy as np\n'), ((9061, 9090), 'numpy.vstack', 'np.vstack', (['(new_uv, uv[3, :])'], {}), '((new_uv, uv[3, :]))\n', (9070, 9090), True, 'import numpy as np\n'), ((9173, 9199), 'numpy.zeros_like', 'np.zeros_like', (['mesh.points'], {}), '(mesh.points)\n', (9186, 9199), True, 'import numpy as np\n'), ((9391, 9405), 'copy.deepcopy', 'deepcopy', (['mesh'], {}), '(mesh)\n', (9399, 9405), False, 'from copy import deepcopy\n'), ((9687, 9693), 'Florence.Mesh', 'Mesh', ([], {}), '()\n', (9691, 9693), False, 'from Florence import Mesh, BoundaryCondition, DisplacementFormulation, FEMSolver, LinearSolver\n'), ((12476, 12482), 'Florence.Mesh', 'Mesh', ([], {}), '()\n', (12480, 12482), False, 'from Florence import Mesh, BoundaryCondition, DisplacementFormulation, FEMSolver, LinearSolver\n'), ((12498, 12535), 'Florence.LinearElastic', 'LinearElastic', (['ndim'], {'mu': '(1.0)', 'lamb': '(4.0)'}), '(ndim, mu=1.0, lamb=4.0)\n', (12511, 12535), False, 'from Florence import LinearElastic, NeoHookean\n'), ((12680, 12808), 'Florence.LinearSolver', 'LinearSolver', ([], {'linear_solver': '"""iterative"""', 'linear_solver_type': '"""cg2"""', 'dont_switch_solver': '(True)', 'iterative_solver_tolerance': '(1e-09)'}), "(linear_solver='iterative', linear_solver_type='cg2',\n dont_switch_solver=True, iterative_solver_tolerance=1e-09)\n", (12692, 12808), False, 'from Florence import Mesh, BoundaryCondition, DisplacementFormulation, FEMSolver, LinearSolver\n'), ((14000, 14032), 'os.remove', 'os.remove', (['"""sphere_cad_file.igs"""'], {}), "('sphere_cad_file.igs')\n", (14009, 14032), False, 'import os, sys\n'), ((16452, 16458), 'Florence.Mesh', 'Mesh', ([], {}), '()\n', (16456, 16458), False, 'from Florence import Mesh, BoundaryCondition, DisplacementFormulation, FEMSolver, LinearSolver\n'), ((16474, 16511), 'Florence.LinearElastic', 'LinearElastic', (['ndim'], {'mu': '(1.0)', 'lamb': '(4.0)'}), '(ndim, mu=1.0, lamb=4.0)\n', (16487, 16511), False, 'from Florence import LinearElastic, NeoHookean\n'), ((17770, 17802), 'os.remove', 'os.remove', (['"""sphere_cad_file.igs"""'], {}), "('sphere_cad_file.igs')\n", (17779, 17802), False, 'import os, sys\n'), ((19751, 19802), 'numpy.linspace', 'np.linspace', (['inner_radius', 'outer_radius', '(nthick + 1)'], {}), '(inner_radius, outer_radius, nthick + 1)\n', (19762, 19802), True, 'import numpy as np\n'), ((19813, 19819), 'Florence.Mesh', 'Mesh', ([], {}), '()\n', (19817, 19819), False, 'from Florence import Mesh, BoundaryCondition, DisplacementFormulation, FEMSolver, LinearSolver\n'), ((20726, 20777), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['mesh.elements'], {'dtype': 'np.int64'}), '(mesh.elements, dtype=np.int64)\n', (20746, 20777), True, 'import numpy as np\n'), ((21258, 21264), 'Florence.Mesh', 'Mesh', ([], {}), '()\n', (21262, 21264), False, 'from Florence import Mesh, BoundaryCondition, DisplacementFormulation, FEMSolver, LinearSolver\n'), ((21331, 21345), 'copy.deepcopy', 'deepcopy', (['mesh'], {}), '(mesh)\n', (21339, 21345), False, 'from copy import deepcopy\n'), ((22720, 22745), 'numpy.array', 'np.array', (['[0.0, 0.0, 1.0]'], {}), '([0.0, 0.0, 1.0])\n', (22728, 22745), True, 'import numpy as np\n'), ((23724, 23745), 'numpy.unique', 'np.unique', (['mesh.edges'], {}), '(mesh.edges)\n', (23733, 23745), True, 'import numpy as np\n'), ((23912, 23966), 'numpy.lexsort', 'np.lexsort', (['(mesh.points[idx, 1], mesh.points[idx, 0])'], {}), '((mesh.points[idx, 1], mesh.points[idx, 0]))\n', (23922, 23966), True, 'import numpy as np\n'), ((23999, 24042), 'numpy.linspace', 'np.linspace', (['(0.0)', 'radius', 'idx_sort.shape[0]'], {}), '(0.0, radius, idx_sort.shape[0])\n', (24010, 24042), True, 'import numpy as np\n'), ((24139, 24193), 'numpy.lexsort', 'np.lexsort', (['(mesh.points[idx, 0], mesh.points[idx, 1])'], {}), '((mesh.points[idx, 0], mesh.points[idx, 1]))\n', (24149, 24193), True, 'import numpy as np\n'), ((24226, 24269), 'numpy.linspace', 'np.linspace', (['(0.0)', 'radius', 'idx_sort.shape[0]'], {}), '(0.0, radius, idx_sort.shape[0])\n', (24237, 24269), True, 'import numpy as np\n'), ((4060, 4123), 'warnings.warn', 'warn', (['"""Number of division in circumferential direction too low"""'], {}), "('Number of division in circumferential direction too low')\n", (4064, 4123), False, 'from warnings import warn\n'), ((4802, 4812), 'numpy.cos', 'np.cos', (['tt'], {}), '(tt)\n', (4808, 4812), True, 'import numpy as np\n'), ((4823, 4833), 'numpy.sin', 'np.sin', (['tt'], {}), '(tt)\n', (4829, 4833), True, 'import numpy as np\n'), ((4849, 4866), 'numpy.vstack', 'np.vstack', (['(x, y)'], {}), '((x, y))\n', (4858, 4866), True, 'import numpy as np\n'), ((5199, 5250), 'numpy.linalg.norm', 'np.linalg.norm', (['(interp_p[i, :] - interp_p[i - 1, :])'], {}), '(interp_p[i, :] - interp_p[i - 1, :])\n', (5213, 5250), True, 'import numpy as np\n'), ((5444, 5456), 'numpy.copy', 'np.copy', (['val'], {}), '(val)\n', (5451, 5456), True, 'import numpy as np\n'), ((5602, 5632), 'numpy.vstack', 'np.vstack', (['(new_uv, interp_uv)'], {}), '((new_uv, interp_uv))\n', (5611, 5632), True, 'import numpy as np\n'), ((5891, 5960), 'Florence.FunctionSpace.MeanValueCoordinateMapping', 'MeanValueCoordinateMapping', (['mesh.points[i, :]', 'new_uv', 'new_end_points'], {}), '(mesh.points[i, :], new_uv, new_end_points)\n', (5917, 5960), False, 'from Florence.FunctionSpace import MeanValueCoordinateMapping\n'), ((6096, 6137), 'numpy.linspace', 'np.linspace', (['(np.pi / 4)', '(np.pi / 2)', '(nx + 1)'], {}), '(np.pi / 4, np.pi / 2, nx + 1)\n', (6107, 6137), True, 'import numpy as np\n'), ((6146, 6156), 'numpy.cos', 'np.cos', (['tt'], {}), '(tt)\n', (6152, 6156), True, 'import numpy as np\n'), ((6167, 6177), 'numpy.sin', 'np.sin', (['tt'], {}), '(tt)\n', (6173, 6177), True, 'import numpy as np\n'), ((6215, 6232), 'numpy.vstack', 'np.vstack', (['(x, y)'], {}), '((x, y))\n', (6224, 6232), True, 'import numpy as np\n'), ((7448, 7511), 'warnings.warn', 'warn', (['"""Number of division in circumferential direction too low"""'], {}), "('Number of division in circumferential direction too low')\n", (7452, 7511), False, 'from warnings import warn\n'), ((8218, 8228), 'numpy.cos', 'np.cos', (['tt'], {}), '(tt)\n', (8224, 8228), True, 'import numpy as np\n'), ((8239, 8249), 'numpy.sin', 'np.sin', (['tt'], {}), '(tt)\n', (8245, 8249), True, 'import numpy as np\n'), ((8265, 8282), 'numpy.vstack', 'np.vstack', (['(x, y)'], {}), '((x, y))\n', (8274, 8282), True, 'import numpy as np\n'), ((8615, 8666), 'numpy.linalg.norm', 'np.linalg.norm', (['(interp_p[i, :] - interp_p[i - 1, :])'], {}), '(interp_p[i, :] - interp_p[i - 1, :])\n', (8629, 8666), True, 'import numpy as np\n'), ((8860, 8872), 'numpy.copy', 'np.copy', (['val'], {}), '(val)\n', (8867, 8872), True, 'import numpy as np\n'), ((9018, 9048), 'numpy.vstack', 'np.vstack', (['(new_uv, interp_uv)'], {}), '((new_uv, interp_uv))\n', (9027, 9048), True, 'import numpy as np\n'), ((9248, 9317), 'Florence.FunctionSpace.MeanValueCoordinateMapping', 'MeanValueCoordinateMapping', (['mesh.points[i, :]', 'new_uv', 'new_end_points'], {}), '(mesh.points[i, :], new_uv, new_end_points)\n', (9274, 9317), False, 'from Florence.FunctionSpace import MeanValueCoordinateMapping\n'), ((13118, 13137), 'Florence.BoundaryCondition', 'BoundaryCondition', ([], {}), '()\n', (13135, 13137), False, 'from Florence import Mesh, BoundaryCondition, DisplacementFormulation, FEMSolver, LinearSolver\n'), ((13493, 13522), 'Florence.DisplacementFormulation', 'DisplacementFormulation', (['mesh'], {}), '(mesh)\n', (13516, 13522), False, 'from Florence import Mesh, BoundaryCondition, DisplacementFormulation, FEMSolver, LinearSolver\n'), ((13544, 13688), 'Florence.FEMSolver', 'FEMSolver', ([], {'number_of_load_increments': '(1)', 'analysis_nature': '"""linear"""', 'force_not_computing_mesh_qualities': '(True)', 'report_log_level': '(0)', 'optimise': '(True)'}), "(number_of_load_increments=1, analysis_nature='linear',\n force_not_computing_mesh_qualities=True, report_log_level=0, optimise=True)\n", (13553, 13688), False, 'from Florence import Mesh, BoundaryCondition, DisplacementFormulation, FEMSolver, LinearSolver\n'), ((14046, 14067), 'numpy.isclose', 'np.isclose', (['radius', '(1)'], {}), '(radius, 1)\n', (14056, 14067), True, 'import numpy as np\n'), ((17119, 17138), 'Florence.BoundaryCondition', 'BoundaryCondition', ([], {}), '()\n', (17136, 17138), False, 'from Florence import Mesh, BoundaryCondition, DisplacementFormulation, FEMSolver, LinearSolver\n'), ((17816, 17837), 'numpy.isclose', 'np.isclose', (['radius', '(1)'], {}), '(radius, 1)\n', (17826, 17837), True, 'import numpy as np\n'), ((22982, 22990), 'numpy.linalg.norm', 'norm', (['e3'], {}), '(e3)\n', (22986, 22990), False, 'from numpy.linalg import norm\n'), ((23003, 23035), 'numpy.dot', 'np.dot', (['e3[:, None]', 'E3[None, :]'], {}), '(e3[:, None], E3[None, :])\n', (23009, 23035), True, 'import numpy as np\n'), ((23115, 23132), 'numpy.dot', 'np.dot', (['points', 'Q'], {}), '(points, Q)\n', (23121, 23132), True, 'import numpy as np\n'), ((1514, 1529), 'Florence.Tensor.totuple', 'totuple', (['center'], {}), '(center)\n', (1521, 1529), False, 'from Florence.Tensor import totuple, unique2d\n'), ((1534, 1545), 'Florence.Tensor.totuple', 'totuple', (['p1'], {}), '(p1)\n', (1541, 1545), False, 'from Florence.Tensor import totuple, unique2d\n'), ((1550, 1561), 'Florence.Tensor.totuple', 'totuple', (['p2'], {}), '(p2)\n', (1557, 1561), False, 'from Florence.Tensor import totuple, unique2d\n'), ((1711, 1745), 'numpy.arctan', 'np.arctan', (['(44.22727272 / -7.818181)'], {}), '(44.22727272 / -7.818181)\n', (1720, 1745), True, 'import numpy as np\n'), ((1755, 1790), 'numpy.arctan', 'np.arctan', (['(-24.22727272 / 37.818181)'], {}), '(-24.22727272 / 37.818181)\n', (1764, 1790), True, 'import numpy as np\n'), ((1948, 1959), 'Florence.Tensor.totuple', 'totuple', (['p1'], {}), '(p1)\n', (1955, 1959), False, 'from Florence.Tensor import totuple, unique2d\n'), ((1964, 1975), 'Florence.Tensor.totuple', 'totuple', (['p2'], {}), '(p2)\n', (1971, 1975), False, 'from Florence.Tensor import totuple, unique2d\n'), ((4571, 4592), 'numpy.unique', 'np.unique', (['mesh.edges'], {}), '(mesh.edges)\n', (4580, 4592), True, 'import numpy as np\n'), ((7985, 8006), 'numpy.unique', 'np.unique', (['mesh.edges'], {}), '(mesh.edges)\n', (7994, 8006), True, 'import numpy as np\n'), ((11810, 11839), 'Florence.Tensor.prime_number_factorisation', 'prime_number_factorisation', (['n'], {}), '(n)\n', (11836, 11839), False, 'from Florence.Tensor import prime_number_factorisation\n'), ((15831, 15860), 'Florence.Tensor.prime_number_factorisation', 'prime_number_factorisation', (['n'], {}), '(n)\n', (15857, 15860), False, 'from Florence.Tensor import prime_number_factorisation\n'), ((16926, 16955), 'Florence.DisplacementFormulation', 'DisplacementFormulation', (['mesh'], {}), '(mesh)\n', (16949, 16955), False, 'from Florence import Mesh, BoundaryCondition, DisplacementFormulation, FEMSolver, LinearSolver\n'), ((17603, 17614), 'Florence.FEMSolver', 'FEMSolver', ([], {}), '()\n', (17612, 17614), False, 'from Florence import Mesh, BoundaryCondition, DisplacementFormulation, FEMSolver, LinearSolver\n'), ((19293, 19380), 'numpy.array', 'np.array', (['[[cut_threshold, cut_threshold, cut_threshold], [offset, offset, offset]]'], {}), '([[cut_threshold, cut_threshold, cut_threshold], [offset, offset,\n offset]])\n', (19301, 19380), True, 'import numpy as np\n'), ((19936, 19948), 'copy.deepcopy', 'deepcopy', (['mm'], {}), '(mm)\n', (19944, 19948), False, 'from copy import deepcopy\n'), ((19950, 19962), 'copy.deepcopy', 'deepcopy', (['mm'], {}), '(mm)\n', (19958, 19962), False, 'from copy import deepcopy\n'), ((19978, 20001), 'numpy.isclose', 'np.isclose', (['radii[i]', '(1)'], {}), '(radii[i], 1)\n', (19988, 20001), True, 'import numpy as np\n'), ((20052, 20079), 'numpy.isclose', 'np.isclose', (['radii[i + 1]', '(1)'], {}), '(radii[i + 1], 1)\n', (20062, 20079), True, 'import numpy as np\n'), ((20255, 20272), 'numpy.copy', 'np.copy', (['elements'], {}), '(elements)\n', (20262, 20272), True, 'import numpy as np\n'), ((20299, 20334), 'numpy.vstack', 'np.vstack', (['(mm1.points, mm2.points)'], {}), '((mm1.points, mm2.points))\n', (20308, 20334), True, 'import numpy as np\n'), ((20519, 20555), 'numpy.vstack', 'np.vstack', (['(mesh.elements, elements)'], {}), '((mesh.elements, elements))\n', (20528, 20555), True, 'import numpy as np\n'), ((20582, 20618), 'numpy.vstack', 'np.vstack', (['(mesh.points, mm2.points)'], {}), '((mesh.points, mm2.points))\n', (20591, 20618), True, 'import numpy as np\n'), ((1043, 1065), 'numpy.linalg.norm', 'np.linalg.norm', (['p1line'], {}), '(p1line)\n', (1057, 1065), True, 'import numpy as np\n'), ((1159, 1181), 'numpy.linalg.norm', 'np.linalg.norm', (['p1line'], {}), '(p1line)\n', (1173, 1181), True, 'import numpy as np\n'), ((11933, 11962), 'Florence.Tensor.prime_number_factorisation', 'prime_number_factorisation', (['n'], {}), '(n)\n', (11959, 11962), False, 'from Florence.Tensor import prime_number_factorisation\n'), ((12145, 12156), 'numpy.sort', 'np.sort', (['ps'], {}), '(ps)\n', (12152, 12156), True, 'import numpy as np\n'), ((15954, 15983), 'Florence.Tensor.prime_number_factorisation', 'prime_number_factorisation', (['n'], {}), '(n)\n', (15980, 15983), False, 'from Florence.Tensor import prime_number_factorisation\n'), ((16166, 16177), 'numpy.sort', 'np.sort', (['ps'], {}), '(ps)\n', (16173, 16177), True, 'import numpy as np\n'), ((19435, 19512), 'numpy.array', 'np.array', (['[[cut_threshold, cut_threshold, -offset], [offset, offset, offset]]'], {}), '([[cut_threshold, cut_threshold, -offset], [offset, offset, offset]])\n', (19443, 19512), True, 'import numpy as np\n'), ((23853, 23887), 'numpy.isclose', 'np.isclose', (['mesh.points[:, 0]', '(0.0)'], {}), '(mesh.points[:, 0], 0.0)\n', (23863, 23887), True, 'import numpy as np\n'), ((24080, 24114), 'numpy.isclose', 'np.isclose', (['mesh.points[:, 1]', '(0.0)'], {}), '(mesh.points[:, 1], 0.0)\n', (24090, 24114), True, 'import numpy as np\n'), ((990, 1021), 'numpy.linalg.norm', 'np.linalg.norm', (['(y_line * p1line)'], {}), '(y_line * p1line)\n', (1004, 1021), True, 'import numpy as np\n'), ((1020, 1042), 'numpy.linalg.norm', 'np.linalg.norm', (['y_line'], {}), '(y_line)\n', (1034, 1042), True, 'import numpy as np\n'), ((1106, 1137), 'numpy.linalg.norm', 'np.linalg.norm', (['(y_line * p1line)'], {}), '(y_line * p1line)\n', (1120, 1137), True, 'import numpy as np\n'), ((1136, 1158), 'numpy.linalg.norm', 'np.linalg.norm', (['y_line'], {}), '(y_line)\n', (1150, 1158), True, 'import numpy as np\n'), ((4422, 4431), 'numpy.sin', 'np.sin', (['t'], {}), '(t)\n', (4428, 4431), True, 'import numpy as np\n'), ((4447, 4456), 'numpy.cos', 'np.cos', (['t'], {}), '(t)\n', (4453, 4456), True, 'import numpy as np\n'), ((4461, 4470), 'numpy.sin', 'np.sin', (['t'], {}), '(t)\n', (4467, 4470), True, 'import numpy as np\n'), ((4484, 4493), 'numpy.cos', 'np.cos', (['t'], {}), '(t)\n', (4490, 4493), True, 'import numpy as np\n'), ((4496, 4505), 'numpy.sin', 'np.sin', (['t'], {}), '(t)\n', (4502, 4505), True, 'import numpy as np\n'), ((5366, 5417), 'numpy.linalg.norm', 'np.linalg.norm', (['(interp_p[i, :] - interp_p[i - 1, :])'], {}), '(interp_p[i, :] - interp_p[i - 1, :])\n', (5380, 5417), True, 'import numpy as np\n'), ((6555, 6564), 'numpy.cos', 'np.cos', (['t'], {}), '(t)\n', (6561, 6564), True, 'import numpy as np\n'), ((6569, 6578), 'numpy.sin', 'np.sin', (['t'], {}), '(t)\n', (6575, 6578), True, 'import numpy as np\n'), ((7807, 7816), 'numpy.cos', 'np.cos', (['t'], {}), '(t)\n', (7813, 7816), True, 'import numpy as np\n'), ((7821, 7830), 'numpy.sin', 'np.sin', (['t'], {}), '(t)\n', (7827, 7830), True, 'import numpy as np\n'), ((7846, 7855), 'numpy.cos', 'np.cos', (['t'], {}), '(t)\n', (7852, 7855), True, 'import numpy as np\n'), ((7860, 7869), 'numpy.sin', 'np.sin', (['t'], {}), '(t)\n', (7866, 7869), True, 'import numpy as np\n'), ((7883, 7892), 'numpy.cos', 'np.cos', (['t'], {}), '(t)\n', (7889, 7892), True, 'import numpy as np\n'), ((7895, 7904), 'numpy.sin', 'np.sin', (['t'], {}), '(t)\n', (7901, 7904), True, 'import numpy as np\n'), ((7919, 7928), 'numpy.cos', 'np.cos', (['t'], {}), '(t)\n', (7925, 7928), True, 'import numpy as np\n'), ((7931, 7940), 'numpy.sin', 'np.sin', (['t'], {}), '(t)\n', (7937, 7940), True, 'import numpy as np\n'), ((8782, 8833), 'numpy.linalg.norm', 'np.linalg.norm', (['(interp_p[i, :] - interp_p[i - 1, :])'], {}), '(interp_p[i, :] - interp_p[i - 1, :])\n', (8796, 8833), True, 'import numpy as np\n'), ((9758, 9767), 'numpy.cos', 'np.cos', (['t'], {}), '(t)\n', (9764, 9767), True, 'import numpy as np\n'), ((9773, 9782), 'numpy.sin', 'np.sin', (['t'], {}), '(t)\n', (9779, 9782), True, 'import numpy as np\n'), ((9816, 9825), 'numpy.cos', 'np.cos', (['t'], {}), '(t)\n', (9822, 9825), True, 'import numpy as np\n'), ((9830, 9839), 'numpy.sin', 'np.sin', (['t'], {}), '(t)\n', (9836, 9839), True, 'import numpy as np\n'), ((19571, 19642), 'numpy.array', 'np.array', (['[[cut_threshold, -offset, -offset], [offset, offset, offset]]'], {}), '([[cut_threshold, -offset, -offset], [offset, offset, offset]])\n', (19579, 19642), True, 'import numpy as np\n'), ((20158, 20209), 'numpy.hstack', 'np.hstack', (['(mm1.elements, mm1.nnode + mm2.elements)'], {}), '((mm1.elements, mm1.nnode + mm2.elements))\n', (20167, 20209), True, 'import numpy as np\n'), ((20372, 20468), 'numpy.hstack', 'np.hstack', (['(mesh.elements[(i - 1) * mm2.nelem:i * mm2.nelem, 4:], mesh.nnode + mm2.\n elements)'], {}), '((mesh.elements[(i - 1) * mm2.nelem:i * mm2.nelem, 4:], mesh.nnode +\n mm2.elements))\n', (20381, 20468), True, 'import numpy as np\n')]
|
import tensorflow as tf
from PIL import Image
import numpy as np
import os
from util import check_or_makedirs
im = Image.open("1.jpg")
print(im.mode, im.size)
np_im = np.array(im)
tf_im = tf.constant(np_im)
print(tf_im.dtype)
img = tf.image.grayscale_to_rgb(tf_im[:, :, tf.newaxis])
# scale image to fixed size
fixed_size = tf.constant([640, 640], dtype=tf.float32) # 16的倍数
raw_shape = tf.cast(tf.shape(img)[:2], tf.float32)
scale_ratio = tf.reduce_min(fixed_size / raw_shape)
new_size = tf.cast(raw_shape * scale_ratio, dtype=tf.int32)
img = tf.image.resize(img, size=new_size)
delta = tf.cast(fixed_size, tf.int32) - new_size
dh, dw = delta[0], delta[1]
img = tf.pad(img, paddings=[[0, dh], [0, dw], [0, 0]], mode='CONSTANT', constant_values=255) # fixed_size, 白底黑字
# image = tf.image.random_brightness(img, max_delta=0.5)
# image = tf.image.random_contrast(image, lower=0.5, upper=2.)
# image = tf.image.random_hue(image, max_delta=0.4)
# image = tf.image.random_jpeg_quality(image, min_jpeg_quality=20, max_jpeg_quality=80)
# image = tf.image.random_saturation(image, lower=0.5, upper=5)
# check_or_makedirs(os.path.join("..", "summary"))
# summary_writer = tf.summary.create_file_writer(os.path.join("..", "summary"))
# with summary_writer.as_default():
# print(np_im.dtype)
# tf.summary.image("image", np_im.reshape((1, 897, 708, 1)).astype("float32")/255, step=0)
# summary_writer.flush()
noise = tf.random.normal(img.shape, mean=0.0, stddev=30.0)
img = img + noise
img = tf.where(img < 0, 0, img)
img = tf.where(img > 255, 255, img)
img = tf.cast(img, tf.uint8)
for i in range(100):
print(i, img.dtype)
# ****************************
delta = -1 + i * 2 / 100
im = tf.image.adjust_brightness(img, delta=delta)
print(im.dtype)
np_im = im.numpy().astype(np.uint8)
p_im = Image.fromarray(np_im)
check_or_makedirs(os.path.join("..", "tf_image", "brightness"))
im_path = os.path.join("..", "tf_image", "brightness", "delta_" + str(delta) + ".jpg")
p_im.save(im_path, format="jpeg")
# ****************************
contrast_factor = 0.3 + i * 1.5 / 100
im = tf.image.adjust_contrast(img, contrast_factor=contrast_factor)
print(im.dtype)
np_im = im.numpy().astype(np.uint8)
p_im = Image.fromarray(np_im)
check_or_makedirs(os.path.join("..", "tf_image", "contrast"))
im_path = os.path.join("..", "tf_image", "contrast", "contrast_factor_" + str(contrast_factor) + ".jpg")
p_im.save(im_path, format="jpeg")
# ****************************
delta = -1 + i * 2 / 100
im = tf.image.adjust_hue(img, delta=delta)
print(im.dtype)
np_im = im.numpy().astype(np.uint8)
p_im = Image.fromarray(np_im)
check_or_makedirs(os.path.join("..", "tf_image", "hue"))
im_path = os.path.join("..", "tf_image", "hue", "delta_" + str(delta) + ".jpg")
p_im.save(im_path, format="jpeg")
# ****************************
jpeg_quality = 0 + i
im = tf.image.adjust_jpeg_quality(img, jpeg_quality=jpeg_quality)
print(im.dtype)
np_im = (im.numpy() * 255).astype(np.uint8)
# print(np_im)
p_im = Image.fromarray(np_im)
check_or_makedirs(os.path.join("..", "tf_image", "jpeg_quality"))
im_path = os.path.join("..", "tf_image", "jpeg_quality", "quality_" + str(jpeg_quality) + ".jpg")
p_im.save(im_path, format="jpeg")
# ****************************
saturation_factor = 0 + i * 100 / 100
im = tf.image.adjust_saturation(img, saturation_factor=saturation_factor)
print(im.dtype)
np_im = im.numpy().astype(np.uint8)
p_im = Image.fromarray(np_im)
check_or_makedirs(os.path.join("..", "tf_image", "saturation"))
im_path = os.path.join("..", "tf_image", "saturation", "saturation_factor_" + str(saturation_factor) + ".jpg")
p_im.save(im_path, format="jpeg")
|
[
"tensorflow.image.grayscale_to_rgb",
"os.path.join",
"tensorflow.random.normal",
"tensorflow.image.adjust_jpeg_quality",
"tensorflow.image.adjust_hue",
"tensorflow.pad",
"tensorflow.constant",
"PIL.Image.open",
"tensorflow.cast",
"tensorflow.shape",
"numpy.array",
"tensorflow.image.adjust_contrast",
"tensorflow.where",
"PIL.Image.fromarray",
"tensorflow.image.resize",
"tensorflow.reduce_min",
"tensorflow.image.adjust_brightness",
"tensorflow.image.adjust_saturation"
] |
[((116, 135), 'PIL.Image.open', 'Image.open', (['"""1.jpg"""'], {}), "('1.jpg')\n", (126, 135), False, 'from PIL import Image\n'), ((169, 181), 'numpy.array', 'np.array', (['im'], {}), '(im)\n', (177, 181), True, 'import numpy as np\n'), ((190, 208), 'tensorflow.constant', 'tf.constant', (['np_im'], {}), '(np_im)\n', (201, 208), True, 'import tensorflow as tf\n'), ((235, 285), 'tensorflow.image.grayscale_to_rgb', 'tf.image.grayscale_to_rgb', (['tf_im[:, :, tf.newaxis]'], {}), '(tf_im[:, :, tf.newaxis])\n', (260, 285), True, 'import tensorflow as tf\n'), ((328, 369), 'tensorflow.constant', 'tf.constant', (['[640, 640]'], {'dtype': 'tf.float32'}), '([640, 640], dtype=tf.float32)\n', (339, 369), True, 'import tensorflow as tf\n'), ((444, 481), 'tensorflow.reduce_min', 'tf.reduce_min', (['(fixed_size / raw_shape)'], {}), '(fixed_size / raw_shape)\n', (457, 481), True, 'import tensorflow as tf\n'), ((493, 541), 'tensorflow.cast', 'tf.cast', (['(raw_shape * scale_ratio)'], {'dtype': 'tf.int32'}), '(raw_shape * scale_ratio, dtype=tf.int32)\n', (500, 541), True, 'import tensorflow as tf\n'), ((548, 583), 'tensorflow.image.resize', 'tf.image.resize', (['img'], {'size': 'new_size'}), '(img, size=new_size)\n', (563, 583), True, 'import tensorflow as tf\n'), ((667, 757), 'tensorflow.pad', 'tf.pad', (['img'], {'paddings': '[[0, dh], [0, dw], [0, 0]]', 'mode': '"""CONSTANT"""', 'constant_values': '(255)'}), "(img, paddings=[[0, dh], [0, dw], [0, 0]], mode='CONSTANT',\n constant_values=255)\n", (673, 757), True, 'import tensorflow as tf\n'), ((1421, 1471), 'tensorflow.random.normal', 'tf.random.normal', (['img.shape'], {'mean': '(0.0)', 'stddev': '(30.0)'}), '(img.shape, mean=0.0, stddev=30.0)\n', (1437, 1471), True, 'import tensorflow as tf\n'), ((1497, 1522), 'tensorflow.where', 'tf.where', (['(img < 0)', '(0)', 'img'], {}), '(img < 0, 0, img)\n', (1505, 1522), True, 'import tensorflow as tf\n'), ((1529, 1558), 'tensorflow.where', 'tf.where', (['(img > 255)', '(255)', 'img'], {}), '(img > 255, 255, img)\n', (1537, 1558), True, 'import tensorflow as tf\n'), ((1565, 1587), 'tensorflow.cast', 'tf.cast', (['img', 'tf.uint8'], {}), '(img, tf.uint8)\n', (1572, 1587), True, 'import tensorflow as tf\n'), ((592, 621), 'tensorflow.cast', 'tf.cast', (['fixed_size', 'tf.int32'], {}), '(fixed_size, tf.int32)\n', (599, 621), True, 'import tensorflow as tf\n'), ((1708, 1752), 'tensorflow.image.adjust_brightness', 'tf.image.adjust_brightness', (['img'], {'delta': 'delta'}), '(img, delta=delta)\n', (1734, 1752), True, 'import tensorflow as tf\n'), ((1824, 1846), 'PIL.Image.fromarray', 'Image.fromarray', (['np_im'], {}), '(np_im)\n', (1839, 1846), False, 'from PIL import Image\n'), ((2131, 2193), 'tensorflow.image.adjust_contrast', 'tf.image.adjust_contrast', (['img'], {'contrast_factor': 'contrast_factor'}), '(img, contrast_factor=contrast_factor)\n', (2155, 2193), True, 'import tensorflow as tf\n'), ((2265, 2287), 'PIL.Image.fromarray', 'Image.fromarray', (['np_im'], {}), '(np_im)\n', (2280, 2287), False, 'from PIL import Image\n'), ((2575, 2612), 'tensorflow.image.adjust_hue', 'tf.image.adjust_hue', (['img'], {'delta': 'delta'}), '(img, delta=delta)\n', (2594, 2612), True, 'import tensorflow as tf\n'), ((2684, 2706), 'PIL.Image.fromarray', 'Image.fromarray', (['np_im'], {}), '(np_im)\n', (2699, 2706), False, 'from PIL import Image\n'), ((2960, 3020), 'tensorflow.image.adjust_jpeg_quality', 'tf.image.adjust_jpeg_quality', (['img'], {'jpeg_quality': 'jpeg_quality'}), '(img, jpeg_quality=jpeg_quality)\n', (2988, 3020), True, 'import tensorflow as tf\n'), ((3119, 3141), 'PIL.Image.fromarray', 'Image.fromarray', (['np_im'], {}), '(np_im)\n', (3134, 3141), False, 'from PIL import Image\n'), ((3439, 3507), 'tensorflow.image.adjust_saturation', 'tf.image.adjust_saturation', (['img'], {'saturation_factor': 'saturation_factor'}), '(img, saturation_factor=saturation_factor)\n', (3465, 3507), True, 'import tensorflow as tf\n'), ((3579, 3601), 'PIL.Image.fromarray', 'Image.fromarray', (['np_im'], {}), '(np_im)\n', (3594, 3601), False, 'from PIL import Image\n'), ((399, 412), 'tensorflow.shape', 'tf.shape', (['img'], {}), '(img)\n', (407, 412), True, 'import tensorflow as tf\n'), ((1869, 1913), 'os.path.join', 'os.path.join', (['""".."""', '"""tf_image"""', '"""brightness"""'], {}), "('..', 'tf_image', 'brightness')\n", (1881, 1913), False, 'import os\n'), ((2310, 2352), 'os.path.join', 'os.path.join', (['""".."""', '"""tf_image"""', '"""contrast"""'], {}), "('..', 'tf_image', 'contrast')\n", (2322, 2352), False, 'import os\n'), ((2729, 2766), 'os.path.join', 'os.path.join', (['""".."""', '"""tf_image"""', '"""hue"""'], {}), "('..', 'tf_image', 'hue')\n", (2741, 2766), False, 'import os\n'), ((3164, 3210), 'os.path.join', 'os.path.join', (['""".."""', '"""tf_image"""', '"""jpeg_quality"""'], {}), "('..', 'tf_image', 'jpeg_quality')\n", (3176, 3210), False, 'import os\n'), ((3624, 3668), 'os.path.join', 'os.path.join', (['""".."""', '"""tf_image"""', '"""saturation"""'], {}), "('..', 'tf_image', 'saturation')\n", (3636, 3668), False, 'import os\n')]
|
import glob
import random
import os
import numpy as np
from torch.utils.data import Dataset
from PIL import Image
import torchvision.transforms as transforms
class ImageDataset(Dataset):
def __init__(self, root, transforms_=None, unaligned=False, mode='train', portion=None):
self.transform = transforms.Compose(transforms_)
self.unaligned = unaligned
self._portion = portion
self.files_A_total = sorted(glob.glob(os.path.join(root, '%s/A' % mode) + '/*.jpg'))
self.files_B_total = sorted(glob.glob(os.path.join(root, '%s/B' % mode) + '/*.jpg'))
if self._portion is not None:
num_files_A = len(self.files_A_total)
num_files_B = len(self.files_B_total)
if self._portion > 0:
split_A = int(np.floor(self._portion * num_files_A))
self.files_A = self.files_A_total[:split_A]
split_B = int(np.floor(self._portion * num_files_B))
self.files_B = self.files_B_total[:split_B]
elif self._portion < 0:
split_A = int(np.floor((1 + self._portion) * num_files_A))
self.files_A = self.files_A_total[split_A:]
split_B = int(np.floor((1 + self._portion) * num_files_B))
self.files_B = self.files_B_total[split_B:]
else:
self.files_A = self.files_A_total
self.files_B = self.files_B_total
def __getitem__(self, index):
item_A = self.transform(Image.open(self.files_A[index % len(self.files_A)]))
if self.unaligned:
item_B = self.transform(Image.open(self.files_B[random.randint(0, len(self.files_B) - 1)]).convert('RGB'))
else:
item_B = self.transform(Image.open(self.files_B[index % len(self.files_B)]).convert('RGB'))
return {'A': item_A, 'B': item_B}
def __len__(self):
# return max(len(self.files_A), len(self.files_B))
return len(self.files_A)
class PairedImageDataset(Dataset):
def __init__(self, dataset_dir, soft_data_dir, mode='train', portion=None, transforms_=None):
'''
Construct a dataset with all images from a dir.
dataset: str. dataset name
style: str. 'A2B' or 'B2A'
'''
self.transform = transforms.Compose(transforms_)
self._portion = portion
path_A = os.path.join(dataset_dir, '%s/A' % mode)
path_B = os.path.join(soft_data_dir)
self.files_A_total = sorted(glob.glob(path_A + '/*.jpg'))
self.files_B_total = sorted(glob.glob(path_B + '/*.png'))
assert len(self.files_A_total) == len(self.files_B_total)
if self._portion is not None:
num_files = len(self.files_A_total)
if self._portion > 0:
split = int(np.floor(self._portion * num_files))
self.files_A = self.files_A_total[:split]
self.files_B = self.files_B_total[:split]
elif self._portion < 0:
split = int(np.floor((1 + self._portion) * num_files))
self.files_A = self.files_A_total[split:]
self.files_B = self.files_B_total[split:]
else:
self.files_A = self.files_A_total
self.files_B = self.files_B_total
print('files_A:', len(self.files_A))
print('files_B:', len(self.files_B))
def __getitem__(self, index):
if np.random.rand() < 0.5:
flip = True
else:
flip = False
img_A = Image.open(self.files_A[index % len(self.files_A)])
img_A = img_A.convert("RGB")
if flip:
img_A= np.asarray(img_A) # PIL.Image to np.ndarray
img_A = np.flip(img_A, axis=1) # data augumentation: horrizental flip
img_A = Image.fromarray(np.uint8(img_A)) # np.ndarray to PIL.Image
item_A = self.transform(img_A)
img_B = Image.open(self.files_B[index % len(self.files_B)])
img_B = img_B.convert("RGB")
if flip:
img_B= np.asarray(img_B) # PIL.Image to np.ndarray
img_B = np.flip(img_B, axis=1) # data augumentation: horrizental flip
img_B = Image.fromarray(np.uint8(img_B)) # np.ndarray to PIL.Image
item_B = self.transform(img_B)
return {'A': item_A, 'B': item_B}
def __len__(self):
return len(self.files_A)
|
[
"numpy.uint8",
"numpy.flip",
"numpy.asarray",
"numpy.floor",
"torchvision.transforms.Compose",
"glob.glob",
"numpy.random.rand",
"os.path.join"
] |
[((316, 347), 'torchvision.transforms.Compose', 'transforms.Compose', (['transforms_'], {}), '(transforms_)\n', (334, 347), True, 'import torchvision.transforms as transforms\n'), ((2362, 2393), 'torchvision.transforms.Compose', 'transforms.Compose', (['transforms_'], {}), '(transforms_)\n', (2380, 2393), True, 'import torchvision.transforms as transforms\n'), ((2455, 2495), 'os.path.join', 'os.path.join', (['dataset_dir', "('%s/A' % mode)"], {}), "(dataset_dir, '%s/A' % mode)\n", (2467, 2495), False, 'import os\n'), ((2514, 2541), 'os.path.join', 'os.path.join', (['soft_data_dir'], {}), '(soft_data_dir)\n', (2526, 2541), False, 'import os\n'), ((2579, 2607), 'glob.glob', 'glob.glob', (["(path_A + '/*.jpg')"], {}), "(path_A + '/*.jpg')\n", (2588, 2607), False, 'import glob\n'), ((2646, 2674), 'glob.glob', 'glob.glob', (["(path_B + '/*.png')"], {}), "(path_B + '/*.png')\n", (2655, 2674), False, 'import glob\n'), ((3543, 3559), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (3557, 3559), True, 'import numpy as np\n'), ((3782, 3799), 'numpy.asarray', 'np.asarray', (['img_A'], {}), '(img_A)\n', (3792, 3799), True, 'import numpy as np\n'), ((3847, 3869), 'numpy.flip', 'np.flip', (['img_A'], {'axis': '(1)'}), '(img_A, axis=1)\n', (3854, 3869), True, 'import numpy as np\n'), ((4192, 4209), 'numpy.asarray', 'np.asarray', (['img_B'], {}), '(img_B)\n', (4202, 4209), True, 'import numpy as np\n'), ((4257, 4279), 'numpy.flip', 'np.flip', (['img_B'], {'axis': '(1)'}), '(img_B, axis=1)\n', (4264, 4279), True, 'import numpy as np\n'), ((3946, 3961), 'numpy.uint8', 'np.uint8', (['img_A'], {}), '(img_A)\n', (3954, 3961), True, 'import numpy as np\n'), ((4356, 4371), 'numpy.uint8', 'np.uint8', (['img_B'], {}), '(img_B)\n', (4364, 4371), True, 'import numpy as np\n'), ((466, 499), 'os.path.join', 'os.path.join', (['root', "('%s/A' % mode)"], {}), "(root, '%s/A' % mode)\n", (478, 499), False, 'import os\n'), ((560, 593), 'os.path.join', 'os.path.join', (['root', "('%s/B' % mode)"], {}), "(root, '%s/B' % mode)\n", (572, 593), False, 'import os\n'), ((818, 855), 'numpy.floor', 'np.floor', (['(self._portion * num_files_A)'], {}), '(self._portion * num_files_A)\n', (826, 855), True, 'import numpy as np\n'), ((951, 988), 'numpy.floor', 'np.floor', (['(self._portion * num_files_B)'], {}), '(self._portion * num_files_B)\n', (959, 988), True, 'import numpy as np\n'), ((2901, 2936), 'numpy.floor', 'np.floor', (['(self._portion * num_files)'], {}), '(self._portion * num_files)\n', (2909, 2936), True, 'import numpy as np\n'), ((1124, 1167), 'numpy.floor', 'np.floor', (['((1 + self._portion) * num_files_A)'], {}), '((1 + self._portion) * num_files_A)\n', (1132, 1167), True, 'import numpy as np\n'), ((1263, 1306), 'numpy.floor', 'np.floor', (['((1 + self._portion) * num_files_B)'], {}), '((1 + self._portion) * num_files_B)\n', (1271, 1306), True, 'import numpy as np\n'), ((3124, 3165), 'numpy.floor', 'np.floor', (['((1 + self._portion) * num_files)'], {}), '((1 + self._portion) * num_files)\n', (3132, 3165), True, 'import numpy as np\n')]
|
import numpy as np
from sas7bdat import SAS7BDAT
import glob
import pandas as pd
from sklearn import preprocessing
from sas7bdat import SAS7BDAT
import glob
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
from sklearn import utils, model_selection, metrics, linear_model, neighbors, ensemble
def convertAllCHSData(year = [], onlySubjectsWBiomarkers = 0):
if onlySubjectsWBiomarkers:
print('Only obtaining data for subjects/households with biomarker data.')
dataDirs = glob.glob('./data/Master*')
for dir in dataDirs:
SASfiles = glob.glob(dir + '/*.sas7bdat')
for SASfile in SASfiles:
convertSASfile(SASfile, year)
def convertSASfile(inputFullPath, year = [], onlySubjectsWBiomarkers = 0):
print('Converting ' + inputFullPath)
df = SAS2DataFrame(inputFullPath, year = year)
outputName = inputFullPath.split('/')[-1].split('.')[0]
outputDir = '/'.join(inputFullPath.split('/')[0:-2])
if year:
outputFullPath = outputDir + '/' + outputName
outputFullPath = outputFullPath + '_' + str(year) + 'only' + '.csv'
else:
outputFullPath = outputDir + '/' + outputName + '.csv'
if onlySubjectsWBiomarkers:
subjectsWithBiomarkers = pd.read_csv('./data/subjectsWithBiomarkers.csv')
tmp = set(df.columns)
identifyingFields = list(tmp.intersection(set(subjectsWithBiomarkers.columns)))
if not identifyingFields:
print('No identifying fields found.')
return
elif identifyingFields.count('idind'):
selFactor = 'idind'
selidinds = list(set(df[selFactor]).intersection(set(subjectsWithBiomarkers[selFactor])))
selIdxs = [a in selidinds for a in df[selFactor]]
df = df[selIdxs]
elif identifyingFields.count('hhid'):
selFactor = 'hhid'
selidinds = list(set(df[selFactor]).intersection(set(subjectsWithBiomarkers[selFactor])))
selIdxs = [a in selidinds for a in df[selFactor]]
df = df[selIdxs]
elif identifyingFields.count('commid'):
selFactor = 'commid'
selidinds = list(set(df[selFactor]).intersection(set(subjectsWithBiomarkers[selFactor])))
selIdxs = [a in selidinds for a in df[selFactor]]
df = df[selIdxs]
print(str(df.shape[0]) + ' valid rows')
df.to_csv(outputFullPath)
return
def SAS2DataFrame(inputFullPath, year = []):
with SAS7BDAT(inputFullPath, skip_header=False) as reader:
df = reader.to_data_frame()
df.columns = [col.lower() for col in df.columns]
if (not not year) & any(df.columns == 'wave'):
df = df[df['wave'] == year]
return df
def getSurveyData():
''' Gets relevant survey data for dHealth project
i.e. survey data for subjects that have biomarker data
'''
surveyPath = './data/Master_ID_201908/surveys_pub_12.sas7bdat'
surveyData = SAS2DataFrame(surveyPath)
surveyData = surveyData[(surveyData['biomaker'] == 1) & (surveyData['wave'] == 2009)]
return surveyData
def getBiomarkerData():
surveyData = getSurveyData()
biomarkerPath = './data/Master_Biomarker_2009/biomarker_09.sas7bdat'
biomarkerData = SAS2DataFrame(biomarkerPath)
ids1 = set(biomarkerData.idind)
ids2 = set(surveyData.idind)
excludeIds = list(ids1.difference(ids2))
for id in excludeIds:
tmp = list(biomarkerData.idind)
idx = tmp.index(id)
biomarkerData = biomarkerData.drop(idx)
return biomarkerData
def createSubjectsWithBiomarkersCSV():
surveyData = getSurveyData()
surveyData = surveyData.iloc[:,[0,1,5,3]]
surveyData.columns = ['idind', 'hhid', 'commid', 'Age']
surveyData.to_csv('./data/subjectsWithBiomarkers.csv')
# createSubjectsWithBiomarkersCSV()
featureMap = pd.read_csv('featureTableMap.csv')
subjects = pd.read_csv('./data/subjectsWithBiomarkers.csv',usecols = ['idind','Age']) # Could add others too'hhid','commid'
def createGenderCSV():
print('Extracting gender data...')
subjects = pd.read_csv('./data/subjectsWithBiomarkers.csv',usecols = ['idind','hhid','commid'])
subjects = subjects.astype({'idind': 'int',
'hhid': 'int',
'commid': 'int'})
def getGender(subjectIdx, idind_1, idind_2, sex_1, sex_2):
gender = np.nan
if subjects.idind[subjectIdx] in idind_1:
idx = idind_1.index(subjects.idind[subjectIdx])
gender = int(sex_1[idx])
elif subjects.idind[subjectIdx] in idind_2:
idx = idind_2.index(subjects.idind[subjectIdx])
gender = int(sex_2[idx])
else:
gender = np.nan
if gender == 1:
gender = int(1)
elif gender == 2:
gender = 0
if subjectIdx % 500 == 0:
print(str(100*subjectIdx/9548) + '% complete')
return gender
relations = pd.read_csv('./data/relationmast_pub_00_2009only.csv')
idind_1 = list(relations.idind_1)
idind_2 = list(relations.idind_2)
sex_1 = list(relations.sex_1)
sex_2 = list(relations.sex_2)
gender = [getGender(i, idind_1, idind_2, sex_1, sex_2) for i in range(len(subjects))]
d = {'idind': subjects.idind, 'Sex': gender}
df = pd.DataFrame(data=d)
df.to_csv('./data/gender.csv')
def createSleep_ScreenTimeCSV():
sleep_screenTime = pd.read_csv('./data/pact_12_2009only.csv',usecols = ['idind', 'u324', 'u339','u340_mn', 'u341_mn','u508', 'u509_mn','u510_mn','u345','u346_mn', 'u347_mn'])
sleep_screenTime.columns = ['idind', 'Hours_of_sleep', 'watchTV','TVhours_week','TVhours_weekend','goesOnline','online_week','online_weekend', 'play_videoGames', 'videoGames_week', 'videoGames_weekend']
sleep_screenTime = sleep_screenTime.replace({'watchTV':{9:1,np.nan:1}, 'goesOnline':{9:0,np.nan:0}, 'play_videoGames':{9:0,np.nan:0}, 'Hours_of_sleep':{-9: np.nan}})
sleep_screenTime = sleep_screenTime.fillna(sleep_screenTime.median())
sleep_screenTime_subjects= list(sleep_screenTime.idind)
def getDailyScreenTime(subjectIdx):
weeklyScreenTime = 0
if subjects.idind[subjectIdx] in sleep_screenTime_subjects:
idx = sleep_screenTime_subjects.index(subjects.idind[subjectIdx])
else:
return np.nan
if sleep_screenTime.watchTV[idx]:
weeklyScreenTime = weeklyScreenTime + sleep_screenTime.TVhours_week[idx] + sleep_screenTime.TVhours_weekend[idx]
else:
pass
if sleep_screenTime.goesOnline[idx]:
weeklyScreenTime = weeklyScreenTime + sleep_screenTime.online_week[idx] + sleep_screenTime.online_weekend[idx]
else:
pass
if sleep_screenTime.play_videoGames[idx]:
weeklyScreenTime = weeklyScreenTime + sleep_screenTime.videoGames_week[idx] + sleep_screenTime.videoGames_weekend[idx]
else:
pass
return np.round(weeklyScreenTime/7)
def getDailySleepTime(subjectIdx):
if subjects.idind[subjectIdx] in sleep_screenTime_subjects:
idx = sleep_screenTime_subjects.index(subjects.idind[subjectIdx])
else:
return np.nan
return sleep_screenTime.Hours_of_sleep[idx]
subjects = pd.read_csv('./data/subjectsWithBiomarkers.csv',usecols = ['idind'])
Daily_screen_time = [getDailyScreenTime(i) for i in range(len(subjects))]
Hours_of_sleep = [getDailySleepTime(i) for i in range(len(subjects))]
d = {'idind': subjects.idind, 'Daily_screen_time': Daily_screen_time, 'Hours_of_sleep': Hours_of_sleep}
df = pd.DataFrame(data=d)
df.to_csv('./data/sleep_screentime.csv')
return df
# Define these variables for default inputs for the functions below:
def preprocessRawChinaHealthStudyData():
createSubjectsWithBiomarkersCSV()
convertAllCHSData(year = 2009, onlySubjectsWBiomarkers = 1)
createGenderCSV()
createSleep_ScreenTimeCSV()
def getAndMergeTables(subjects = subjects, tableNum = 1):
newDF = pd.read_csv('./data/'+featureMap['tablename'][tableNum],usecols = eval(featureMap['varnames'][tableNum]))
newDF.columns = eval(featureMap['newnames'][tableNum])
try:
replaceDict = eval(featureMap['replacements'][tableNum])
print('This should not work for surveys')
newDF.replace(replaceDict, inplace = True)
except:
print('Could not replace values or none exists.')
subjects = pd.merge(subjects,newDF,how='left', on ='idind')
print(list(newDF.columns))
print(subjects.columns)
return subjects
def createDataTable():
subjects = pd.read_csv('./data/subjectsWithBiomarkers.csv',usecols = ['idind','Age'])
print('Adding demographic info')
for i in range(1,4):
print('Adding ' + featureMap['tablename'][i])
subjects = getAndMergeTables(subjects = subjects, tableNum = i)
print('One-hot-encoding medical conditions...')
# One-hot-encode medical conditions:
medicalConditions = subjects['Medical_condition'].fillna('noReport')
medicalConditions = medicalConditions.fillna('noReport')
medicalConditions = pd.DataFrame(medicalConditions)
enc = preprocessing.OneHotEncoder(categories = "auto")
enc.fit(medicalConditions)
data = enc.transform(medicalConditions).toarray()
columnNames = enc.categories_[0]
medicalConditions = pd.DataFrame(data,columns=columnNames)
# Replace old medical condition column to one-hot-encoded vars:
subjects.drop('Medical_condition', axis=1, inplace=True)
subjects=pd.concat([subjects,medicalConditions], axis=1, ignore_index=False)
# Add physical exam:
print('Adding lifestyle features...')
i = 4
print('Adding ' + featureMap['tablename'][i])
subjects = getAndMergeTables(subjects = subjects, tableNum = i)
# Add lifestyle features:
print('Adding lifestyle features...')
for i in range(5,featureMap.shape[0]-1):
print('Adding ' + featureMap['tablename'][i])
subjects = getAndMergeTables(subjects = subjects, tableNum = i)
print('Adding reponse variables...')
# Add the response variables (biomarker levels):
i = featureMap.shape[0]-1
print('Adding ' + featureMap['tablename'][i])
subjects = getAndMergeTables(subjects = subjects, tableNum = i)
# Median impute missing data:
subjects = subjects.fillna(subjects.median())
#Change data types:
subjects = subjects.astype({'idind': 'int',
'Sex': 'int',
'Urban': 'int',
'Activity_level': 'int'})
return subjects
def shuffleAndSplit(featureMatrix, targetMatrix, test_size=.2, n_splits=5):
# Shuffle datasets:
X,Y = utils.shuffle(featureMatrix,targetMatrix, random_state = 0)
# Split X and y into training and test sets (80% Train : 20% Test):
X_Train, X_Test, Y_Train, Y_Test = model_selection.train_test_split(
X, Y, random_state = 0, test_size = test_size)
cv=model_selection.KFold(n_splits = n_splits, shuffle = False)
return X_Train, X_Test, Y_Train, Y_Test, cv
def showDataSplits(Y_Train, Y_Test, cv):
''' Helper function to show how the data was split
'''
fig, ax = plt.subplots(figsize = (12,3))
plt.xlim(0,len(Y_Train)+len(Y_Test))
plt.ylim(0,cv.n_splits+1.5)
ax.set_title('Training and Validation splits \n (after shuffling)')
plt.xlabel('Dataset indicies')
yticklabels= [];
offset = -.4
i = 0
for train_idxs, cval_idxs in cv.split(Y_Train):
# training data:
i += 1
start = (min(train_idxs),i+offset)
width = max(train_idxs)-min(train_idxs)
if i == 1:
ax.add_patch(mpl.patches.Rectangle(start, width = width, height = .8, color = 'c', label = 'CV_train'))
ax.add_patch(mpl.patches.Rectangle(start, width = width, height = .8, color = 'c'))
# cross-validation data:
start = (min(cval_idxs),i+offset)
width = max(cval_idxs)-min(cval_idxs)
if i == 1:
ax.add_patch(mpl.patches.Rectangle(start, width = width, height = .8, color = 'orange', label = 'CV_validation'))
ax.add_patch(mpl.patches.Rectangle(start, width = width, height = .8, color = 'orange'))
yticklabels.append('Cross validation_' + str(i))
start = (0,cv.n_splits+1+offset)
width = len(Y_Train)
ax.add_patch(mpl.patches.Rectangle(start, width = width, height = .8, color = 'g', label = 'Train'))
start = (len(Y_Train),cv.n_splits+1+offset)
width = len(Y_Train)
ax.add_patch(mpl.patches.Rectangle(start, width = width, height = .8, color = 'r', label = 'Test'))
yticklabels.append('Final test')
#Format plot
plt.yticks(np.arange(1,cv.n_splits+2),yticklabels)
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles, labels)
plt.show()
def createHealthForecasterModels():
import pickle
## Aggregate relevant data for ML:
data = createDataTable()
fixedFactors = ['Age', 'Sex', 'Urban', 'ENT', 'OBGYN', 'Old_age_midLife_syndrome', 'alcohol_poisoning',
'dermatological', 'digestive', 'endocrine', 'heart', 'hematological', 'infectious_parasitic', 'injury',
'muscular_rheumatological', 'neurological', 'noDiagnosis', 'noReport', 'other', 'pyschiatric', 'respiratory',
'sexualDysfunction', 'tumor', 'unknown', 'urinary', 'High_BP', 'Diabetes', 'Heart_attack', 'Internal_bleeding',
'Pregnant','Height']
fixedFactorIdxs = [list(data.columns).index(varName) for varName in fixedFactors]
lifestyleFactors = ['Smoker', 'Cups_water_daily', 'Alcohol_frequency', 'Weight', 'Kcal', 'Carbs', 'Fat', 'Protein', 'Activity_level', 'Daily_screen_time', 'Hours_of_sleep']
lifestyleFactorIdxs = [list(data.columns).index(varName) for varName in lifestyleFactors]
responseVariables = ['Insulin','Triglycerides','HDL_C', 'LDL_C','Urea', 'Uric_acid', 'APO_A', 'Lipoprotein_A','High_sensitivity_CRP', 'Creatinine',
'APO_B', 'Mg', 'Ferritin', 'Hemoglobin', 'White_blood_cell',
'Red_blood_cell', 'Platelet', 'Glucose_field','HbA1c', 'Total_protein','Albumin', 'Glucose',
'Total_cholestorol', 'Alanine_AT', 'Transferrin', 'Transferrin_receptor','Systol', 'Diastol']
responseVariableIdxs = [list(data.columns).index(varName) for varName in responseVariables]
fatRelatedIdxs = [responseVariables.index('APO_A'),
responseVariables.index('Lipoprotein_A'),
responseVariables.index('HDL_C'),
responseVariables.index('LDL_C'),
responseVariables.index('APO_B'),
responseVariables.index('Triglycerides'),
responseVariables.index('Total_cholestorol')]
gluRelatedIdxs = [responseVariables.index('Insulin'),
responseVariables.index('HbA1c'),
responseVariables.index('Glucose')]
inputFeatures = fixedFactors + lifestyleFactors
X = data[inputFeatures].to_numpy()
Y = data[responseVariables].to_numpy()
# Y_zscore = (Y-np.mean(Y,axis=0))/np.std(Y,axis=0)
# X_Train, X_Test, Y_Train, Y_Test, cv = shuffleAndSplit(X, Y, test_size=.2, n_splits=5)
# X_Train, X_Test, Y_Train_zscore, Y_Test_zscore, cv = shuffleAndSplit(X, Y_zscore, test_size=.2, n_splits=5)
## Create a second model to predict weight:
# fixedFactors2 = ['age', 'sex', 'urban', 'ENT', 'OBGYN', 'Old_age_midLife_syndrome', 'alcohol_poisoning',
# 'dermatological', 'digestive', 'endocrine', 'heart', 'hematological', 'infectious_parasitic', 'injury',
# 'muscular_rheumatological', 'neurological', 'noDiagnosis', 'noReport', 'other', 'pyschiatric', 'respiratory',
# 'sexualDysfunction', 'tumor', 'unknown', 'urinary', 'highBP', 'diabetes', 'heart_attack', 'internal_bleeding',
# 'pregnant','height']
# fixedFactorIdxs2 = [list(data.columns).index(varName) for varName in fixedFactors]
# lifestyleFactors2 = ['smoker', 'cups_water_daily', 'Alcohol_frequency', 'kcal', 'carbo', 'fat', 'protn', 'Activity_level', 'Daily_screen_time', 'Hours_of_sleep']
# lifestyleFactorIdxs2 = [list(data.columns).index(varName) for varName in lifestyleFactors]
# responseVariables2 = ['weight']
# responseVariableIdxs2 = [list(data.columns).index(varName) for varName in responseVariables2]
# inputFeatures2 = fixedFactors2+lifestyleFactors2
# X2 = data[fixedFactors2 + lifestyleFactors2].to_numpy()
# Y2 = data[responseVariables2].to_numpy()
# X_Train2, X_Test2, Y_Train2, Y_Test2, cv = shuffleAndSplit(X2, Y2, test_size=.2, n_splits=5)
models = dict(ols=linear_model.LinearRegression(),
lasso=linear_model.Lasso(alpha=0.75),
ridge=linear_model.Ridge(alpha=0.75),
elastic=linear_model.ElasticNet(alpha=0.1, l1_ratio=0.75),
randomForest = ensemble.RandomForestRegressor(random_state=0,
max_features = 'auto',
min_samples_leaf = 50, #max_depth = 3,
n_estimators = 200)
)
# Also define models to predict z_score Target Matrix
# models_zscore = dict(ols=linear_model.LinearRegression(),
# lasso=linear_model.Lasso(alpha=.5),
# ridge=linear_model.Ridge(alpha=.5),
# elastic=linear_model.ElasticNet(alpha=.5, l1_ratio=0.5),
# randomForest = ensemble.RandomForestRegressor(random_state=0,
# max_features = 'auto',
# min_samples_leaf = 10,
# n_estimators = 200)
# weightModel = dict(ols=linear_model.LinearRegression(),
# lasso=linear_model.Lasso(alpha=.5),
# ridge=linear_model.Ridge(alpha=.5),
# elastic=linear_model.ElasticNet(alpha=.5, l1_ratio=0.5),
# randomForest = ensemble.RandomForestRegressor(random_state=0,
# max_features = 'auto',
# min_samples_leaf = 10,
# n_estimators = 200))
# print('Training trainedWeightBPModels')
# trainedWeightModels = {}
# for name, mdl in weightModel.items():
# print('Training ' + str(name) + '...')
# trainedWeightModels.update({name : mdl.fit(X2,Y2.ravel())})
# print('finished')
# Train models
print('Training trainedModels')
trainedModels = {}
for name, mdl in models.items():
print('Training ' + str(name) + '...')
trainedModels.update({name : mdl.fit(X,Y)})
print('finished')
# pickle.dump([trainedModels, trainedWeightModels, inputFeatures, responseVariables, inputFeatures2, responseVariables2], open("models.p", "wb"))
pickle.dump([trainedModels, inputFeatures, responseVariables, data], open("models.p", "wb"))
# return trainedModels, trainedWeightModels, inputFeatures, responseVariables, inputFeatures2, responseVariables2
return trainedModels, inputFeatures, responseVariables
def parseInputs(inputDict,inputFeatures):
# inputValues = np.zeros(len(inputFeatures))
currentValues = np.zeros(len(inputFeatures))
futureValues = np.zeros(len(inputFeatures))
# Age
currentValues[inputFeatures.index('Age')] = inputDict['Age']
futureValues[inputFeatures.index('Age')] = inputDict['Age']
# Sex
if inputDict['Sex'] == 'M':
currentValues[inputFeatures.index('Sex')] = 1
futureValues[inputFeatures.index('Sex')] = 1
else:
currentValues[inputFeatures.index('Sex')] = 0
futureValues[inputFeatures.index('Sex')] = 0
# Location:
if inputDict['Location'] == 'Urban':
currentValues[inputFeatures.index('Urban')] = 1
futureValues[inputFeatures.index('Urban')] = 1
else:
currentValues[inputFeatures.index('Urban')] = 0
futureValues[inputFeatures.index('Urban')] = 0
# Physical exam/Medical Conditions:
currentValues[inputFeatures.index('Height')] = inputDict['Height']*2.54
futureValues[inputFeatures.index('Height')] = inputDict['Height']*2.54
currentValues[inputFeatures.index(inputDict['Medical_condition'])] = 1
futureValues[inputFeatures.index(inputDict['Medical_condition'])] = 1
if inputDict['Pregnant']:
currentValues[inputFeatures.index('Pregnant')] = 1
futureValues[inputFeatures.index('Pregnant')] = 1
if inputDict['Diabetes']:
currentValues[inputFeatures.index('Diabetes')] = 1
futureValues[inputFeatures.index('Diabetes')] = 1
if inputDict['High_BP']:
currentValues[inputFeatures.index('High_BP')] = 1
futureValues[inputFeatures.index('High_BP')] = 1
if inputDict['Heart_attack']:
currentValues[inputFeatures.index('Heart_attack')] = 1
futureValues[inputFeatures.index('Heart_attack')] = 1
if inputDict['Internal_bleeding']:
currentValues[inputFeatures.index('Internal_bleeding')] = 1
futureValues[inputFeatures.index('Internal_bleeding')] = 1
# currentValues = futureValues = inputValues # This may have done some weird cloning thing?
### Current lifestyle
# Habits:
if inputDict['currAlcohol_frequency'] == 'daily':
currentValues[inputFeatures.index('Alcohol_frequency')] = 1
elif inputDict['currAlcohol_frequency'] == '3-4 times a week':
currentValues[inputFeatures.index('Alcohol_frequency')] = 2
elif inputDict['currAlcohol_frequency'] == 'Once or twice a week':
currentValues[inputFeatures.index('Alcohol_frequency')] = 3
elif inputDict['currAlcohol_frequency'] == 'Once or twice a month':
currentValues[inputFeatures.index('Alcohol_frequency')] = 4
elif inputDict['currAlcohol_frequency'] == 'No more than once a month':
currentValues[inputFeatures.index('Alcohol_frequency')] = 5
else:
currentValues[inputFeatures.index('Alcohol_frequency')] = 3
currentValues[inputFeatures.index('Cups_water_daily')] = inputDict['currCups_water_daily']
if inputDict['currSmoker']:
currentValues[inputFeatures.index('Smoker')] = 1
# Diet/Weight:
currentValues[inputFeatures.index('Kcal')] = inputDict['currCarbo']*4 + inputDict['currProtn']*4 + inputDict['currFat']*9 #currKcal
currentValues[inputFeatures.index('Carbs')] = inputDict['currCarbo']
currentValues[inputFeatures.index('Fat')] = inputDict['currFat']
currentValues[inputFeatures.index('Protein')] = inputDict['currProtn']
# Activity
currentValues[inputFeatures.index('Activity_level')] = inputDict['currActivityLevel']
currentValues[inputFeatures.index('Daily_screen_time')] = inputDict['currDailyScreenTime']
currentValues[inputFeatures.index('Hours_of_sleep')] = inputDict['currHours_of_sleep']
if 'Weight' in inputFeatures:
currentValues[inputFeatures.index('Weight')] = inputDict['currWeight']/2.205
### Lifestyle intervention
# Habits:
if inputDict['intAlcohol_frequency'] == 'daily':
futureValues[inputFeatures.index('Alcohol_frequency')] = 1
elif inputDict['intAlcohol_frequency'] == '3-4 times a week':
futureValues[inputFeatures.index('Alcohol_frequency')] = 2
elif inputDict['intAlcohol_frequency'] == 'Once or twice a week':
futureValues[inputFeatures.index('Alcohol_frequency')] = 3
elif inputDict['intAlcohol_frequency'] == 'Once or twice a month':
futureValues[inputFeatures.index('Alcohol_frequency')] = 4
elif inputDict['intAlcohol_frequency'] == 'No more than once a month':
futureValues[inputFeatures.index('Alcohol_frequency')] = 5
else:
futureValues[inputFeatures.index('Alcohol_frequency')] = 3
futureValues[inputFeatures.index('Cups_water_daily')] = inputDict['intCups_water_daily']
if inputDict['intSmoker']:
futureValues[inputFeatures.index('Smoker')] = 1
# Diet/Weight:
futureValues[inputFeatures.index('Kcal')] = inputDict['intCarbo']*4 + inputDict['intProtn']*4 + inputDict['intFat']*9 #currKcal
futureValues[inputFeatures.index('Carbs')] = inputDict['intCarbo']
futureValues[inputFeatures.index('Fat')] = inputDict['intFat']
futureValues[inputFeatures.index('Protein')] = inputDict['intProtn']
# Activity
futureValues[inputFeatures.index('Activity_level')] = inputDict['intActivityLevel']
futureValues[inputFeatures.index('Daily_screen_time')] = inputDict['intDailyScreenTime']
futureValues[inputFeatures.index('Hours_of_sleep')] = inputDict['intHours_of_sleep']
if 'Weight' in inputFeatures:
futureValues[inputFeatures.index('Weight')] = inputDict['intWeight']/2.205
return currentValues, futureValues
def plotSubjectModelPrediction(trainedModels, X, Y, responseVariables, modelName = 'randomForest', subjectIdx = 3):
import matplotlib.pyplot as plt
f, ax = plt.subplots(figsize=(11, 5))
y_predict = trainedModels[modelName].predict(X[subjectIdx,:].reshape(1, -1))
plt.scatter(range(0,26), Y[subjectIdx,:].T,color = 'b',label = 'actual')
plt.scatter(range(0,26), y_predict.T,color = 'r',label = 'prediction')
plt.xticks(range(0,26))
plt.xticks(rotation='vertical')
ax.set_xticklabels(responseVariables)
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles, labels)
plt.show()
## Helper functions
def update_progress(numerator, denominator=1, taskName = 'Progress'):
from IPython.display import clear_output
bar_length = 20
if isinstance(numerator, int):
numerator = float(numerator)
if not isinstance(numerator, float):
numerator = 0
if numerator/denominator < 0:
numerator = 0
if numerator/denominator >= 1:
numerator = denominator
block = int(round(bar_length * (numerator/denominator)))
clear_output(wait = True)
text = taskName + ": [{0}] {1:.1f}%".format( "#" * block + "-" * (bar_length - block), (numerator/denominator) * 100)
print(text)
|
[
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"numpy.arange",
"glob.glob",
"numpy.round",
"pandas.DataFrame",
"matplotlib.patches.Rectangle",
"sklearn.linear_model.ElasticNet",
"pandas.merge",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.subplots",
"pandas.concat",
"sklearn.linear_model.Lasso",
"sklearn.linear_model.Ridge",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylim",
"sklearn.preprocessing.OneHotEncoder",
"sklearn.ensemble.RandomForestRegressor",
"sklearn.linear_model.LinearRegression",
"sas7bdat.SAS7BDAT",
"IPython.display.clear_output",
"sklearn.model_selection.KFold",
"sklearn.utils.shuffle",
"matplotlib.pyplot.xlabel"
] |
[((3880, 3914), 'pandas.read_csv', 'pd.read_csv', (['"""featureTableMap.csv"""'], {}), "('featureTableMap.csv')\n", (3891, 3914), True, 'import pandas as pd\n'), ((3926, 4000), 'pandas.read_csv', 'pd.read_csv', (['"""./data/subjectsWithBiomarkers.csv"""'], {'usecols': "['idind', 'Age']"}), "('./data/subjectsWithBiomarkers.csv', usecols=['idind', 'Age'])\n", (3937, 4000), True, 'import pandas as pd\n'), ((515, 542), 'glob.glob', 'glob.glob', (['"""./data/Master*"""'], {}), "('./data/Master*')\n", (524, 542), False, 'import glob\n'), ((4117, 4206), 'pandas.read_csv', 'pd.read_csv', (['"""./data/subjectsWithBiomarkers.csv"""'], {'usecols': "['idind', 'hhid', 'commid']"}), "('./data/subjectsWithBiomarkers.csv', usecols=['idind', 'hhid',\n 'commid'])\n", (4128, 4206), True, 'import pandas as pd\n'), ((5024, 5078), 'pandas.read_csv', 'pd.read_csv', (['"""./data/relationmast_pub_00_2009only.csv"""'], {}), "('./data/relationmast_pub_00_2009only.csv')\n", (5035, 5078), True, 'import pandas as pd\n'), ((5376, 5396), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'd'}), '(data=d)\n', (5388, 5396), True, 'import pandas as pd\n'), ((5489, 5656), 'pandas.read_csv', 'pd.read_csv', (['"""./data/pact_12_2009only.csv"""'], {'usecols': "['idind', 'u324', 'u339', 'u340_mn', 'u341_mn', 'u508', 'u509_mn',\n 'u510_mn', 'u345', 'u346_mn', 'u347_mn']"}), "('./data/pact_12_2009only.csv', usecols=['idind', 'u324', 'u339',\n 'u340_mn', 'u341_mn', 'u508', 'u509_mn', 'u510_mn', 'u345', 'u346_mn',\n 'u347_mn'])\n", (5500, 5656), True, 'import pandas as pd\n'), ((7415, 7482), 'pandas.read_csv', 'pd.read_csv', (['"""./data/subjectsWithBiomarkers.csv"""'], {'usecols': "['idind']"}), "('./data/subjectsWithBiomarkers.csv', usecols=['idind'])\n", (7426, 7482), True, 'import pandas as pd\n'), ((7753, 7773), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'd'}), '(data=d)\n', (7765, 7773), True, 'import pandas as pd\n'), ((8611, 8660), 'pandas.merge', 'pd.merge', (['subjects', 'newDF'], {'how': '"""left"""', 'on': '"""idind"""'}), "(subjects, newDF, how='left', on='idind')\n", (8619, 8660), True, 'import pandas as pd\n'), ((8778, 8852), 'pandas.read_csv', 'pd.read_csv', (['"""./data/subjectsWithBiomarkers.csv"""'], {'usecols': "['idind', 'Age']"}), "('./data/subjectsWithBiomarkers.csv', usecols=['idind', 'Age'])\n", (8789, 8852), True, 'import pandas as pd\n'), ((9303, 9334), 'pandas.DataFrame', 'pd.DataFrame', (['medicalConditions'], {}), '(medicalConditions)\n', (9315, 9334), True, 'import pandas as pd\n'), ((9345, 9391), 'sklearn.preprocessing.OneHotEncoder', 'preprocessing.OneHotEncoder', ([], {'categories': '"""auto"""'}), "(categories='auto')\n", (9372, 9391), False, 'from sklearn import preprocessing\n'), ((9540, 9579), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {'columns': 'columnNames'}), '(data, columns=columnNames)\n', (9552, 9579), True, 'import pandas as pd\n'), ((9721, 9789), 'pandas.concat', 'pd.concat', (['[subjects, medicalConditions]'], {'axis': '(1)', 'ignore_index': '(False)'}), '([subjects, medicalConditions], axis=1, ignore_index=False)\n', (9730, 9789), True, 'import pandas as pd\n'), ((10897, 10955), 'sklearn.utils.shuffle', 'utils.shuffle', (['featureMatrix', 'targetMatrix'], {'random_state': '(0)'}), '(featureMatrix, targetMatrix, random_state=0)\n', (10910, 10955), False, 'from sklearn import utils, model_selection, metrics, linear_model, neighbors, ensemble\n'), ((11070, 11145), 'sklearn.model_selection.train_test_split', 'model_selection.train_test_split', (['X', 'Y'], {'random_state': '(0)', 'test_size': 'test_size'}), '(X, Y, random_state=0, test_size=test_size)\n', (11102, 11145), False, 'from sklearn import utils, model_selection, metrics, linear_model, neighbors, ensemble\n'), ((11167, 11222), 'sklearn.model_selection.KFold', 'model_selection.KFold', ([], {'n_splits': 'n_splits', 'shuffle': '(False)'}), '(n_splits=n_splits, shuffle=False)\n', (11188, 11222), False, 'from sklearn import utils, model_selection, metrics, linear_model, neighbors, ensemble\n'), ((11394, 11423), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(12, 3)'}), '(figsize=(12, 3))\n', (11406, 11423), True, 'import matplotlib.pyplot as plt\n'), ((11470, 11500), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0)', '(cv.n_splits + 1.5)'], {}), '(0, cv.n_splits + 1.5)\n', (11478, 11500), True, 'import matplotlib.pyplot as plt\n'), ((11574, 11604), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Dataset indicies"""'], {}), "('Dataset indicies')\n", (11584, 11604), True, 'import matplotlib.pyplot as plt\n'), ((13040, 13050), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (13048, 13050), True, 'import matplotlib.pyplot as plt\n'), ((25631, 25660), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(11, 5)'}), '(figsize=(11, 5))\n', (25643, 25660), True, 'import matplotlib.pyplot as plt\n'), ((25926, 25957), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'rotation': '"""vertical"""'}), "(rotation='vertical')\n", (25936, 25957), True, 'import matplotlib.pyplot as plt\n'), ((26088, 26098), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (26096, 26098), True, 'import matplotlib.pyplot as plt\n'), ((26580, 26603), 'IPython.display.clear_output', 'clear_output', ([], {'wait': '(True)'}), '(wait=True)\n', (26592, 26603), False, 'from IPython.display import clear_output\n'), ((587, 617), 'glob.glob', 'glob.glob', (["(dir + '/*.sas7bdat')"], {}), "(dir + '/*.sas7bdat')\n", (596, 617), False, 'import glob\n'), ((1270, 1318), 'pandas.read_csv', 'pd.read_csv', (['"""./data/subjectsWithBiomarkers.csv"""'], {}), "('./data/subjectsWithBiomarkers.csv')\n", (1281, 1318), True, 'import pandas as pd\n'), ((2509, 2551), 'sas7bdat.SAS7BDAT', 'SAS7BDAT', (['inputFullPath'], {'skip_header': '(False)'}), '(inputFullPath, skip_header=False)\n', (2517, 2551), False, 'from sas7bdat import SAS7BDAT\n'), ((7077, 7107), 'numpy.round', 'np.round', (['(weeklyScreenTime / 7)'], {}), '(weeklyScreenTime / 7)\n', (7085, 7107), True, 'import numpy as np\n'), ((12571, 12650), 'matplotlib.patches.Rectangle', 'mpl.patches.Rectangle', (['start'], {'width': 'width', 'height': '(0.8)', 'color': '"""g"""', 'label': '"""Train"""'}), "(start, width=width, height=0.8, color='g', label='Train')\n", (12592, 12650), True, 'import matplotlib as mpl\n'), ((12750, 12828), 'matplotlib.patches.Rectangle', 'mpl.patches.Rectangle', (['start'], {'width': 'width', 'height': '(0.8)', 'color': '"""r"""', 'label': '"""Test"""'}), "(start, width=width, height=0.8, color='r', label='Test')\n", (12771, 12828), True, 'import matplotlib as mpl\n'), ((12912, 12941), 'numpy.arange', 'np.arange', (['(1)', '(cv.n_splits + 2)'], {}), '(1, cv.n_splits + 2)\n', (12921, 12941), True, 'import numpy as np\n'), ((11994, 12058), 'matplotlib.patches.Rectangle', 'mpl.patches.Rectangle', (['start'], {'width': 'width', 'height': '(0.8)', 'color': '"""c"""'}), "(start, width=width, height=0.8, color='c')\n", (12015, 12058), True, 'import matplotlib as mpl\n'), ((12354, 12423), 'matplotlib.patches.Rectangle', 'mpl.patches.Rectangle', (['start'], {'width': 'width', 'height': '(0.8)', 'color': '"""orange"""'}), "(start, width=width, height=0.8, color='orange')\n", (12375, 12423), True, 'import matplotlib as mpl\n'), ((17009, 17040), 'sklearn.linear_model.LinearRegression', 'linear_model.LinearRegression', ([], {}), '()\n', (17038, 17040), False, 'from sklearn import utils, model_selection, metrics, linear_model, neighbors, ensemble\n'), ((17062, 17092), 'sklearn.linear_model.Lasso', 'linear_model.Lasso', ([], {'alpha': '(0.75)'}), '(alpha=0.75)\n', (17080, 17092), False, 'from sklearn import utils, model_selection, metrics, linear_model, neighbors, ensemble\n'), ((17114, 17144), 'sklearn.linear_model.Ridge', 'linear_model.Ridge', ([], {'alpha': '(0.75)'}), '(alpha=0.75)\n', (17132, 17144), False, 'from sklearn import utils, model_selection, metrics, linear_model, neighbors, ensemble\n'), ((17168, 17217), 'sklearn.linear_model.ElasticNet', 'linear_model.ElasticNet', ([], {'alpha': '(0.1)', 'l1_ratio': '(0.75)'}), '(alpha=0.1, l1_ratio=0.75)\n', (17191, 17217), False, 'from sklearn import utils, model_selection, metrics, linear_model, neighbors, ensemble\n'), ((17248, 17358), 'sklearn.ensemble.RandomForestRegressor', 'ensemble.RandomForestRegressor', ([], {'random_state': '(0)', 'max_features': '"""auto"""', 'min_samples_leaf': '(50)', 'n_estimators': '(200)'}), "(random_state=0, max_features='auto',\n min_samples_leaf=50, n_estimators=200)\n", (17278, 17358), False, 'from sklearn import utils, model_selection, metrics, linear_model, neighbors, ensemble\n'), ((11882, 11969), 'matplotlib.patches.Rectangle', 'mpl.patches.Rectangle', (['start'], {'width': 'width', 'height': '(0.8)', 'color': '"""c"""', 'label': '"""CV_train"""'}), "(start, width=width, height=0.8, color='c', label=\n 'CV_train')\n", (11903, 11969), True, 'import matplotlib as mpl\n'), ((12231, 12328), 'matplotlib.patches.Rectangle', 'mpl.patches.Rectangle', (['start'], {'width': 'width', 'height': '(0.8)', 'color': '"""orange"""', 'label': '"""CV_validation"""'}), "(start, width=width, height=0.8, color='orange', label\n ='CV_validation')\n", (12252, 12328), True, 'import matplotlib as mpl\n')]
|
# Public python modules
import numpy as np
import pandas as pd
import pickle
import feature
from os import path
# If categories of test data = categories of the training data
class load():
def __init__(self, data_path, batch_size):
self.pointer = 0
self.dataframe = pickle.load(open(data_path,"rb"))
self.batch_size = batch_size
self.n_batch = int(len(self.dataframe) / self.batch_size) # The number of batches
self.n_class = len(set(self.dataframe['category'].values)) # The number of classes
# Batch
def batch(self, dataframe):
x_data = []
y_data = []
# get patches from the saved data (in here, "/dataset/train.p" OR "/dataset/valid.p") and append
for i, row in dataframe.iterrows():
# Select dataframe[row, 'patch']
patch = row['patch']
# Append "patch" to "x_data"
x_data.append(np.float32(patch))
# One-hot encoding
cl = row['category']
y = np.zeros(self.n_class)
y[cl] = 1
y_data.append(y)
return x_data, y_data
#print("x:", x_data)
#print("y:", y_data)
# Mini-batch (via batch(self, dataframe) )
def next_batch(self):
start_pos = self.pointer * self.batch_size
batch_df = self.dataframe.iloc[start_pos:start_pos + self.batch_size]
self.pointer = (self.pointer + 1) % self.n_batch # Move pointer for the next mini-batch
return self.batch(batch_df)
# If categories of test data ~= categories of the training data
class load2():
def __init__(self, data_path, batch_size):
self.pointer = 0
self.dataframe = pickle.load(open(data_path,"rb"))
self.batch_size = batch_size
self.n_batch = int(len(self.dataframe) / self.batch_size)
self.n_class = len(set(self.dataframe['category'].values))
# Batch
def batch(self, dataframe):
x_data = []
y_data = []
# get patches from the saved data (in here, "/dataset/train.p" OR "/dataset/valid.p") and append
for i, row in dataframe.iterrows():
# Select dataframe[row, 'patch']
patch = row['patch']
# Append "patch" to "x_data"
x_data.append(np.float32(patch))
# Append category
cl = row['track_id']
y_data.append(cl)
return x_data, y_data
# Mini-batch (via batch(self, dataframe) )
def next_batch(self):
start_pos = self.pointer * self.batch_size
batch_df = self.dataframe.iloc[start_pos:start_pos + self.batch_size]
self.pointer = (self.pointer + 1) % self.n_batch # Move pointer for the next mini-batch
return self.batch(batch_df)
if __name__ == "__main__":
import gen_data
|
[
"numpy.float32",
"numpy.zeros"
] |
[((1029, 1051), 'numpy.zeros', 'np.zeros', (['self.n_class'], {}), '(self.n_class)\n', (1037, 1051), True, 'import numpy as np\n'), ((929, 946), 'numpy.float32', 'np.float32', (['patch'], {}), '(patch)\n', (939, 946), True, 'import numpy as np\n'), ((2291, 2308), 'numpy.float32', 'np.float32', (['patch'], {}), '(patch)\n', (2301, 2308), True, 'import numpy as np\n')]
|
"""Main module."""
import itertools as it
import numpy as np
def read_data(filepath, sep=" "):
"""This function reads file containing Points Coordinates
Arguments:
filepath (str) -- Path to the file to be read
Keyword Arguments:
sep (str) -- Separator for columns in file (default: " ")
Returns:
(list) -- List of points read from input file, in the format [x,y,z]
"""
with open(filepath, "r") as file:
raw_lines = file.readlines()
points = []
for raw_line in raw_lines:
coordinates = raw_line.split(sep)[1:4]
for i in range(3):
coordinates[i] = float(coordinates[i])
points.append(coordinates)
return points
def rototranslation(points):
"""This function generates a rototranslator starting from three
non-collinear points
Arguments:
points (numpy.array) -- Three non-collinear points in a 3x3
numpy array [x,y,z]
Returns:
[numpy.array] -- Rototranslation matrix (4x4 numpy array)
"""
origin = points[0, :]
x = points[1, :] - points[0, :]
x_versor = np.divide(x, np.linalg.norm(x))
y_1 = points[1, :] - points[0, :]
y_2 = points[2, :] - points[0, :]
y = np.cross(y_1, y_2)
y_versor = np.divide(y, np.linalg.norm(y))
z_versor = np.cross(x_versor, y_versor)
rototranslator = np.array(
[
np.append(x_versor, 0.0),
np.append(y_versor, 0.0),
np.append(z_versor, 0.0),
np.append(origin, 1.0),
]
).T
return rototranslator
def calibrate(points_G, points_R):
"""This function performs the actual Robot to World Calibration.
It computes every possibile combination between three non-collinear points,
computes the correspoding rototranslator and then average the mean
rototranslator. Everything is expressed in mm.
Arguments:
points_G (numpy.array) -- Points in World Coordinates
points_R (numpy.array) -- Points in Robot Coordinates
Raises:
Exception: Number of points in Robot and World Coordinates
file is not correspoding.
Returns:
[dict] -- Dictionary containing the computed rototranslator
and some informations about the error (mean and standard
deviation).
"""
# Remove offset from data
if len(points_G) != len(points_R):
raise Exception(
"""
Number of points must match in robot and world files!
Found {} points in World file and {} points in Robot file""".format(
len(points_G), len(points_R)
)
)
num_points = len(points_G)
offset_G_x = -80 # coherence
offset_G_y = 0 # No offset on y axis
offset_G_z = 250 # coherence
offset_G = [offset_G_x, offset_G_y, offset_G_z]
offset_R_x = 80 - 80 # from TCP to SMR + coherence
offset_R_y = 0 # No offset on y axis
offset_R_z = (
20 + 25 + 250
) # pointer basement along z + SMR along z + coherence
offset_R = [offset_R_x, offset_R_y, offset_R_z]
# Remove offset
points_G = np.array(points_G)
points_R = np.array(points_R)
points_G[:, :] = points_G[:, :] - offset_G
points_R[:, :] = points_R[:, :] - offset_R
# Generate creation dataset and control dataset
creation_perc = 0.3
num_creation_points = round(num_points * creation_perc)
num_star_points = round(num_points * (1 - creation_perc))
# At least three points are needed in creation set
if num_creation_points <= 2:
num_creation_points = 3
num_star_points = num_points - num_creation_points
if num_creation_points + num_star_points != num_points:
num_star_points = num_star_points - 1
index_creation = np.round(
np.linspace(0, num_points - 1, num_creation_points)
)
index_creation = [int(i) for i in index_creation]
index_star = [i for i in range(num_points) if i not in index_creation]
points_G_creation = points_G[index_creation, :]
points_R_creation = points_R[index_creation, :]
points_star_G_real = points_G[index_star, :]
points_star_R = points_R[index_star, :]
# Mean Rototranslation Method
index_perm = list(
it.permutations(range(num_creation_points), 3)
) # permutations without ripetitions
creation_perm_G = np.zeros([len(index_perm), 9])
creation_perm_R = np.zeros([len(index_perm), 9])
for i in range(len(index_perm)):
creation_perm_G[i, :3] = points_G_creation[index_perm[i][0], :3]
creation_perm_G[i, 3:6] = points_G_creation[index_perm[i][1], :3]
creation_perm_G[i, 6:] = points_G_creation[index_perm[i][2], :3]
creation_perm_R[i, :3] = points_R_creation[index_perm[i][0], :3]
creation_perm_R[i, 3:6] = points_R_creation[index_perm[i][1], :3]
creation_perm_R[i, 6:] = points_R_creation[index_perm[i][2], :3]
LG_T = np.zeros([4, 4, len(index_perm)])
LR_T = np.zeros([4, 4, len(index_perm)])
RL_T = np.zeros([4, 4, len(index_perm)])
RG_T_temp = np.zeros([4, 4, len(index_perm)])
# for each permutation, generate the rototranslator
for i in range(len(index_perm)):
points_G_current = np.array(
[
creation_perm_G[i, :3],
creation_perm_G[i, 3:6],
creation_perm_G[i, 6:],
]
)
points_R_current = np.array(
[
creation_perm_R[i, :3],
creation_perm_R[i, 3:6],
creation_perm_R[i, 6:],
]
)
LG_T[:, :, i] = rototranslation(points_G_current)
LR_T[:, :, i] = rototranslation(points_R_current)
RL_T[:, :, i] = np.linalg.inv(LR_T[:, :, i])
RG_T_temp[:, :, i] = np.matmul(LG_T[:, :, i], RL_T[:, :, i])
RG_T = np.mean(RG_T_temp, axis=2) # Mean rototranslator
# Comparison between the three methods
points_star_R = np.append(
points_star_R, np.ones([len(points_star_R), 1]), axis=1
) # homogeneous
points_star_G_real = np.append(
points_star_G_real, np.ones([len(points_star_G_real), 1]), axis=1
) # homogeneous
# estimation starting from T and robot data
points_star_G_estimated = np.matmul(RG_T, points_star_R.T).T
# comparison between real and estimated
error = abs(points_star_G_real - points_star_G_estimated)
error_mean = np.mean(error, axis=0)[:3]
error_std_dev = np.std(error, axis=0)[:3]
results = {
"Rototranslator": RG_T,
"Error Mean": error_mean,
"Error Std Dev": error_std_dev,
}
return results
|
[
"numpy.std",
"numpy.cross",
"numpy.append",
"numpy.mean",
"numpy.array",
"numpy.linalg.norm",
"numpy.linspace",
"numpy.linalg.inv",
"numpy.matmul"
] |
[((1264, 1282), 'numpy.cross', 'np.cross', (['y_1', 'y_2'], {}), '(y_1, y_2)\n', (1272, 1282), True, 'import numpy as np\n'), ((1345, 1373), 'numpy.cross', 'np.cross', (['x_versor', 'y_versor'], {}), '(x_versor, y_versor)\n', (1353, 1373), True, 'import numpy as np\n'), ((3134, 3152), 'numpy.array', 'np.array', (['points_G'], {}), '(points_G)\n', (3142, 3152), True, 'import numpy as np\n'), ((3168, 3186), 'numpy.array', 'np.array', (['points_R'], {}), '(points_R)\n', (3176, 3186), True, 'import numpy as np\n'), ((5857, 5883), 'numpy.mean', 'np.mean', (['RG_T_temp'], {'axis': '(2)'}), '(RG_T_temp, axis=2)\n', (5864, 5883), True, 'import numpy as np\n'), ((1161, 1178), 'numpy.linalg.norm', 'np.linalg.norm', (['x'], {}), '(x)\n', (1175, 1178), True, 'import numpy as np\n'), ((1311, 1328), 'numpy.linalg.norm', 'np.linalg.norm', (['y'], {}), '(y)\n', (1325, 1328), True, 'import numpy as np\n'), ((3807, 3858), 'numpy.linspace', 'np.linspace', (['(0)', '(num_points - 1)', 'num_creation_points'], {}), '(0, num_points - 1, num_creation_points)\n', (3818, 3858), True, 'import numpy as np\n'), ((5240, 5328), 'numpy.array', 'np.array', (['[creation_perm_G[i, :3], creation_perm_G[i, 3:6], creation_perm_G[i, 6:]]'], {}), '([creation_perm_G[i, :3], creation_perm_G[i, 3:6], creation_perm_G[\n i, 6:]])\n', (5248, 5328), True, 'import numpy as np\n'), ((5437, 5525), 'numpy.array', 'np.array', (['[creation_perm_R[i, :3], creation_perm_R[i, 3:6], creation_perm_R[i, 6:]]'], {}), '([creation_perm_R[i, :3], creation_perm_R[i, 3:6], creation_perm_R[\n i, 6:]])\n', (5445, 5525), True, 'import numpy as np\n'), ((5747, 5775), 'numpy.linalg.inv', 'np.linalg.inv', (['LR_T[:, :, i]'], {}), '(LR_T[:, :, i])\n', (5760, 5775), True, 'import numpy as np\n'), ((5805, 5844), 'numpy.matmul', 'np.matmul', (['LG_T[:, :, i]', 'RL_T[:, :, i]'], {}), '(LG_T[:, :, i], RL_T[:, :, i])\n', (5814, 5844), True, 'import numpy as np\n'), ((6278, 6310), 'numpy.matmul', 'np.matmul', (['RG_T', 'points_star_R.T'], {}), '(RG_T, points_star_R.T)\n', (6287, 6310), True, 'import numpy as np\n'), ((6436, 6458), 'numpy.mean', 'np.mean', (['error'], {'axis': '(0)'}), '(error, axis=0)\n', (6443, 6458), True, 'import numpy as np\n'), ((6484, 6505), 'numpy.std', 'np.std', (['error'], {'axis': '(0)'}), '(error, axis=0)\n', (6490, 6505), True, 'import numpy as np\n'), ((1428, 1452), 'numpy.append', 'np.append', (['x_versor', '(0.0)'], {}), '(x_versor, 0.0)\n', (1437, 1452), True, 'import numpy as np\n'), ((1466, 1490), 'numpy.append', 'np.append', (['y_versor', '(0.0)'], {}), '(y_versor, 0.0)\n', (1475, 1490), True, 'import numpy as np\n'), ((1504, 1528), 'numpy.append', 'np.append', (['z_versor', '(0.0)'], {}), '(z_versor, 0.0)\n', (1513, 1528), True, 'import numpy as np\n'), ((1542, 1564), 'numpy.append', 'np.append', (['origin', '(1.0)'], {}), '(origin, 1.0)\n', (1551, 1564), True, 'import numpy as np\n')]
|
import os
import numpy as np
import glob
from sklearn.model_selection import StratifiedShuffleSplit
import sys, os
sys.path.insert(0, os.path.join(
os.path.dirname(os.path.realpath(__file__)), "../../"))
from deep_audio_features.bin import config
import wave
import contextlib
def load(folders=None, test_val=[0.2, 0.2], test=True, validation=True):
"""Loads a dataset from some folders.
Arguments
----------
folders {list} : A list of folders containing all samples.
test_val {list} : A list containing the percentages for test and validation split.
test {boolean} : If False only train samples and labels are returned.
validation {boolean} : If False only train and test samples and
labels are returned.
Returns
--------
X_train {list} : All filenames for train.
y_train {list} : Labels for train.
X_test {list} : Filenames for test.
y_test {list} : Labels for train.
if `validation` is `True` also returns the following:
X_valid {list} : Filenames for validation.
y_valid {list} : Labels for validation.
"""
if folders is None:
raise AssertionError()
filenames = []
labels = []
# Match filenames with labels
for folder in folders:
for f in glob.iglob(os.path.join(folder, '*.wav')):
filenames.append(f)
labels.append(folder)
# Convert labels to int
folder2idx, idx2folder = folders_mapping(folders=folders)
labels = list(map(lambda x: folder2idx[x], labels))
# Split
if test is False and validation is False:
# Use this data only to train
return filenames, labels
# Get percentages
test_p, val_p = test_val
X_train_, y_train_ = [], []
X_test, y_test = [], []
X_train, y_train = [], []
X_val, y_val = [], []
# First split
sss = StratifiedShuffleSplit(n_splits=1, test_size=test_p, random_state=0)
train_idx, test_idx = next(
sss.split(filenames, labels))
# Train
for idx in train_idx:
X_train_.append(filenames[idx])
y_train_.append(labels[idx])
# Test
for idx in test_idx:
X_test.append(filenames[idx])
y_test.append(labels[idx])
# If validation split is not needed return
if validation is False:
return X_train_, y_train_, X_test, y_test
# If valuation is True split again
sss = StratifiedShuffleSplit(n_splits=1, test_size=val_p, random_state=0)
train_idx, val_idx = next(sss.split(X_train_, y_train_))
# Train after both splits
for idx in train_idx:
X_train.append(X_train_[idx])
y_train.append(y_train_[idx])
# validation
for idx in val_idx:
X_val.append(X_train_[idx])
y_val.append(y_train_[idx])
return X_train, y_train, X_test, y_test, X_val, y_val
def compute_max_seq_len(reload=False, X=None, folders=None):
"""Return max sequence length for all files."""
# TAKE THE WINDOW STEPS
if reload is True:
if folders is None:
raise AssertionError()
# Get all sample labels
X_train, _, X_test, _, X_val, _ = load(folders=folders)
X = X_train+X_test+X_val
# DEFAULT
else:
if X is None:
raise AssertionError()
# Calculate and print max sequence number
print(config.HOP_LENGTH, config.WINDOW_LENGTH)
lengths = []
for f in X:
with contextlib.closing(wave.open(f, 'r')) as fp:
frames = fp.getnframes()
fs = fp.getframerate()
duration = frames / float(fs)
length = int((duration -
(config.WINDOW_LENGTH - config.HOP_LENGTH)) / \
(config.HOP_LENGTH) + 1)
lengths.append(length)
max_seq = np.max(lengths)
print(f"Max sequence length in dataset: {max_seq}")
return max_seq
def folders_mapping(folders):
"""Return a mapping from folder to class and a mapping from class to folder."""
folder2idx = {}
idx2folder = {}
for idx, folder in enumerate(folders):
folder2idx[folder] = idx
idx2folder[idx] = folder
return folder2idx, idx2folder
def get_categories_population_dictionary(labels, n_classes=9):
"""Return a mapping (category) -> Population."""
mapping = {i: 0 for i in range(0, n_classes)}
# Iterate each file and map
for l in labels:
if l >= n_classes:
continue
mapping[l] += 1
return mapping
|
[
"wave.open",
"os.path.realpath",
"sklearn.model_selection.StratifiedShuffleSplit",
"numpy.max",
"os.path.join"
] |
[((1898, 1966), 'sklearn.model_selection.StratifiedShuffleSplit', 'StratifiedShuffleSplit', ([], {'n_splits': '(1)', 'test_size': 'test_p', 'random_state': '(0)'}), '(n_splits=1, test_size=test_p, random_state=0)\n', (1920, 1966), False, 'from sklearn.model_selection import StratifiedShuffleSplit\n'), ((2437, 2504), 'sklearn.model_selection.StratifiedShuffleSplit', 'StratifiedShuffleSplit', ([], {'n_splits': '(1)', 'test_size': 'val_p', 'random_state': '(0)'}), '(n_splits=1, test_size=val_p, random_state=0)\n', (2459, 2504), False, 'from sklearn.model_selection import StratifiedShuffleSplit\n'), ((3822, 3837), 'numpy.max', 'np.max', (['lengths'], {}), '(lengths)\n', (3828, 3837), True, 'import numpy as np\n'), ((168, 194), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (184, 194), False, 'import sys, os\n'), ((1326, 1355), 'os.path.join', 'os.path.join', (['folder', '"""*.wav"""'], {}), "(folder, '*.wav')\n", (1338, 1355), False, 'import sys, os\n'), ((3472, 3489), 'wave.open', 'wave.open', (['f', '"""r"""'], {}), "(f, 'r')\n", (3481, 3489), False, 'import wave\n')]
|
#-*- coding: utf-8 -*-
import numpy as np
class GPSConverter(object):
'''
GPS Converter class which is able to perform convertions between the
CH1903 and WGS84 system.
'''
# Convert CH y/x/h to WGS height
def CHtoWGSheight(self, y, x, h):
# Axiliary values (% Bern)
y_aux = (y - 600000) / 1000000
x_aux = (x - 200000) / 1000000
h = (h + 49.55) - (12.60 * y_aux) - (22.64 * x_aux)
return h
# Convert CH y/x to WGS lat
def CHtoWGSlat(self, y, x):
# Axiliary values (% Bern)
y_aux = (y - 600000) / 1000000
x_aux = (x - 200000) / 1000000
lat = (16.9023892 + (3.238272 * x_aux)) + \
- (0.270978 * pow(y_aux, 2)) + \
- (0.002528 * pow(x_aux, 2)) + \
- (0.0447 * pow(y_aux, 2) * x_aux) + \
- (0.0140 * pow(x_aux, 3))
# Unit 10000" to 1" and convert seconds to degrees (dec)
lat = (lat * 100) / 36
return lat
# Convert CH y/x to WGS long
def CHtoWGSlng(self, y, x):
# Axiliary values (% Bern)
y_aux = (y - 600000) / 1000000
x_aux = (x - 200000) / 1000000
lng = (2.6779094 + (4.728982 * y_aux) + \
+ (0.791484 * y_aux * x_aux) + \
+ (0.1306 * y_aux * pow(x_aux, 2))) + \
- (0.0436 * pow(y_aux, 3))
# Unit 10000" to 1" and convert seconds to degrees (dec)
lng = (lng * 100) / 36
return lng
# Convert decimal angle (° dec) to sexagesimal angle (dd.mmss,ss)
def DecToSexAngle(self, dec):
degree = dec.astype(int)
minute = (np.floor((dec - degree) * 60)).astype(int)
second = (((dec - degree) * 60) - minute) * 60
return degree + ((minute).astype(float) / 100) + (second / 10000)
# Convert sexagesimal angle (dd.mmss,ss) to seconds
def SexAngleToSeconds(self, dms):
degree = 0
minute = 0
second = 0
degree = dms.astype(float)
minute = ((dms - degree) * 100).astype(float)
second = (((dms - degree) * 100) - minute) * 100
return second + (minute * 60) + (degree * 3600)
# Convert sexagesimal angle (dd.mmss) to decimal angle (degrees)
def SexToDecAngle(self, dms):
degree = 0
minute = 0
second = 0
degree = dms.astype(float)
minute = ((dms - degree) * 100).astype(float)
second = (((dms - degree) * 100) - minute) * 100
return degree + (minute / 60) + (second / 3600)
# Convert WGS lat/long (° dec) and height to CH h
def WGStoCHh(self, lat, lng, h):
lat = self.DecToSexAngle(lat)
lng = self.DecToSexAngle(lng)
lat = self.SexAngleToSeconds(lat)
lng = self.SexAngleToSeconds(lng)
# Axiliary values (% Bern)
lat_aux = (lat - 169028.66) / 10000
lng_aux = (lng - 26782.5) / 10000
h = (h - 49.55) + (2.73 * lng_aux) + (6.94 * lat_aux)
return h
# Convert WGS lat/long (° dec) to CH x
def WGStoCHx(self, lat, lng):
lat = self.DecToSexAngle(lat)
lng = self.DecToSexAngle(lng)
lat = self.SexAngleToSeconds(lat)
lng = self.SexAngleToSeconds(lng)
# Axiliary values (% Bern)
lat_aux = (lat - 169028.66) / 10000
lng_aux = (lng - 26782.5) / 10000
x = ((200147.07 + (308807.95 * lat_aux) + \
+ (3745.25 * lng_aux**2)) + \
+ (76.63 * lat_aux**2)) + \
- (194.56 *lng_aux**2 * lat_aux) + \
+ (119.79 * lat_aux**3)
return x
# Convert WGS lat/long (° dec) to CH y
def WGStoCHy(self, lat, lng):
lat = self.DecToSexAngle(lat)
lng = self.DecToSexAngle(lng)
lat = self.SexAngleToSeconds(lat)
lng = self.SexAngleToSeconds(lng)
# Axiliary values (% Bern)
lat_aux = (lat - 169028.66) / 10000
lng_aux = (lng - 26782.5) / 10000
y = (600072.37 + (211455.93 * lng_aux)) + \
- (10938.51 * lng_aux * lat_aux) + \
- (0.36 * lng_aux * lat_aux**2) + \
- (44.54 * lat_aux**3)
return y
def LV03toWGS84(self, east, north, height):
'''
Convert LV03 to WGS84 Return a array of double that contain lat, long,
and height
'''
d = []
d.append(self.CHtoWGSlat(east, north))
d.append(self.CHtoWGSlng(east, north))
d.append(self.CHtoWGSheight(east, north, height))
return d
def WGS84toLV03(self, latitude, longitude, ellHeight):
'''
Convert WGS84 to LV03 Return an array of double that contaign east,
north, and height
'''
d = []
d.append(self.WGStoCHy(latitude, longitude))
d.append(self.WGStoCHx(latitude, longitude))
d.append(self.WGStoCHh(latitude, longitude, ellHeight))
return d
converter = GPSConverter()
|
[
"numpy.floor"
] |
[((1645, 1674), 'numpy.floor', 'np.floor', (['((dec - degree) * 60)'], {}), '((dec - degree) * 60)\n', (1653, 1674), True, 'import numpy as np\n')]
|
import copy
from typing import Tuple
import numpy as np
from odyssey.distribution import Distribution
from iliad.integrators.info import SoftAbsLeapfrogInfo
from iliad.integrators.states import SoftAbsLeapfrogState
from iliad.integrators.terminal import cond
from iliad.integrators.fields import riemannian, softabs
def momentum_step(
val: Tuple[np.ndarray, np.ndarray, int],
step_size: float,
state: SoftAbsLeapfrogState,
) -> Tuple[np.ndarray, np.ndarray, int]:
"""Computes the update to the momentum variable using the equations of motion
determined by the SoftAbs metric.
Args:
val: A tuple containing the current guess for the fixed point of the
momentum, the difference between the momentum at this fixed point
iteration and the last, and the number of fixed point iterations
considered so far.
step_size: The integration step-size.
state: The current state of the SoftAbs metric system.
Returns:
pm: The updated momentum variable.
delta: The difference between the updated momentum variable and the
guess.
num_iters: The number of fixed point iterations attempted so far.
"""
pmcand, _, num_iters = val
f = softabs.force(pmcand,
state.grad_log_posterior,
state.jac_hessian,
state.hessian_eigenvals,
state.softabs_eigenvals,
state.softabs_inv_eigenvals,
state.hessian_eigenvecs,
state.alpha)
pm = state.momentum + step_size * f
delta = pm - pmcand
num_iters += 1
return pm, delta, num_iters
def position_step(
val: Tuple[np.ndarray, np.ndarray, int],
step_size: float,
distr: Distribution,
state: SoftAbsLeapfrogState,
) -> Tuple[np.ndarray, np.ndarray, int]:
"""Computes the update to the position variable using the equations of motion
determined by the SoftAbs metric.
Args:
val: A tuple containing the current guess for the fixed point of the
position, the difference between the position at this fixed point
iteration and the last, and the number of fixed point iterations
considered so far.
step_size: The integration step-size.
distr: The distribution that guides the time evolution of the Euclidean
Hamiltonian trajectory.
state: The current state of the SoftAbs metric system.
Returns:
qn: The updated momentum variable.
delta; The difference between the updated position variable and the
guess.
num_iters: The number of fixed point iterations attempted so far.
"""
qncand, _, num_iters = val
H = distr.hessian(qncand)
l, U, lt, inv_lt, metric, inv_metric = softabs.decomposition(H, state.alpha)
newvel = [email protected]
qn = state.position + step_size * newvel
delta = qn - qncand
num_iters += 1
return qn, delta, num_iters
def euler_a_single_step(
distr: Distribution,
state: SoftAbsLeapfrogState,
info: SoftAbsLeapfrogInfo,
step_size: float,
thresh: float,
max_iters: int,
) -> Tuple[SoftAbsLeapfrogState, SoftAbsLeapfrogInfo]:
"""The Euler-A integrator is a symplectic map that integrates Hamilton's
equations of motion for a general non-separable
Hamiltonian. It updates the position implicitly and then computes an
explicit update to the momentum variable.
Args:
distr: The distribution that guides the time evolution of the Euclidean
Hamiltonian trajectory.
state: An object containing the position and momentum variables of the
state in phase space, and possibly previously computed log-posterior,
metrics, and gradients.
info: An object that keeps track of the number of fixed point iterations
and whether or not integration has been successful.
step_size: Integration step-size.
thresh: Convergence tolerance for fixed point iterations.
max_iters: Maximum number of fixed point iterations.
Returns:
state: An augmented state object with the updated position and momentum
and values for the log-posterior and metric and their gradients.
info: An augmented information object with the updated number of fixed
point iterations and boolean indicator for successful integration.
"""
# Unpack the position and momentum.
qo, po = state.position, state.momentum
num_dims = len(qo)
# Precompute the initial difference vector, which is set to be an array of
# infinite values.
delta = np.inf*np.ones(num_dims)
# Fixed point iteration to solve the implicit update to the position.
val = (qo + step_size*state.velocity, delta, 0)
while cond(val, thresh, max_iters):
val = position_step(val, step_size, distr, state)
qn, delta, num_iters = val
success = np.max(np.abs(delta)) < thresh
# Update the state with the new position and compute the updated momentum.
state.position = qn
state.update(distr)
state.momentum += step_size*state.force
info.num_iters_pos += num_iters
info.success &= success
return state, info
def euler_b_single_step(
distr: Distribution,
state: SoftAbsLeapfrogState,
info: SoftAbsLeapfrogInfo,
step_size: float,
thresh: float,
max_iters: int,
) -> Tuple[SoftAbsLeapfrogState, SoftAbsLeapfrogInfo]:
"""The Euler-B integrator is a symplectic map that integrates Hamilton's
equations of motion for a general non-separable Hamiltonian. It updates the
momentum implicitly and then computes an explicit update to the position
variable.
Args:
distr: The distribution that guides the time evolution of the Euclidean
Hamiltonian trajectory.
state: An object containing the position and momentum variables of the
state in phase space, and possibly previously computed log-posterior,
metrics, and gradients.
info: An object that keeps track of the number of fixed point iterations
and whether or not integration has been successful.
step_size: Integration step-size.
thresh: Convergence tolerance for fixed point iterations.
max_iters: Maximum number of fixed point iterations.
Returns:
state: An augmented state object with the updated position and momentum
and values for the log-posterior and metric and their gradients.
info: An augmented information object with the updated number of fixed
point iterations and boolean indicator for successful integration.
"""
# Unpack the position and momentum.
qo, po = state.position, state.momentum
num_dims = len(qo)
# Precompute the initial difference vector, which is set to be an array of
# infinite values.
delta = np.inf*np.ones(num_dims)
# Fixed point iteration to solve the implicit update to the momentum.
val = (po + step_size*state.force, delta, 0)
while cond(val, thresh, max_iters):
val = momentum_step(val, step_size, state)
pn, delta, num_iters = val
vn = state.inv_metric@pn
success = np.max(np.abs(delta)) < thresh
# Update the state's new position.
state.momentum = pn
state.velocity = vn
state.position += step_size*vn
state.update(distr)
info.num_iters_mom += num_iters
info.success &= success
return state, info
def softabs_euler_a(
state: SoftAbsLeapfrogState,
step_size: float,
num_steps: int,
distr: Distribution,
thresh: float,
max_iters: int,
) -> Tuple[SoftAbsLeapfrogState, SoftAbsLeapfrogInfo]:
state = copy.copy(state)
info = SoftAbsLeapfrogInfo()
for i in range(num_steps):
state, info = euler_a_single_step(
distr,
state,
info,
step_size,
thresh,
max_iters,
)
L = np.linalg.cholesky(state.metric)
state.velocity = state.inv_metric.dot(state.momentum)
state.sqrtm_metric = L
state.logdet_metric = 2.0*np.sum(np.log(np.diag(L)))
return state, info
def softabs_euler_b(
state: SoftAbsLeapfrogState,
step_size: float,
num_steps: int,
distr: Distribution,
thresh: float,
max_iters: int,
) -> Tuple[SoftAbsLeapfrogState, SoftAbsLeapfrogInfo]:
state = copy.copy(state)
info = SoftAbsLeapfrogInfo()
for i in range(num_steps):
state, info = euler_b_single_step(
distr,
state,
info,
step_size,
thresh,
max_iters,
)
L = np.linalg.cholesky(state.metric)
state.velocity = state.inv_metric.dot(state.momentum)
state.sqrtm_metric = L
state.logdet_metric = 2.0*np.sum(np.log(np.diag(L)))
return state, info
|
[
"numpy.abs",
"iliad.integrators.info.SoftAbsLeapfrogInfo",
"iliad.integrators.fields.softabs.decomposition",
"iliad.integrators.fields.softabs.force",
"copy.copy",
"numpy.ones",
"numpy.diag",
"iliad.integrators.terminal.cond",
"numpy.linalg.cholesky"
] |
[((1270, 1462), 'iliad.integrators.fields.softabs.force', 'softabs.force', (['pmcand', 'state.grad_log_posterior', 'state.jac_hessian', 'state.hessian_eigenvals', 'state.softabs_eigenvals', 'state.softabs_inv_eigenvals', 'state.hessian_eigenvecs', 'state.alpha'], {}), '(pmcand, state.grad_log_posterior, state.jac_hessian, state.\n hessian_eigenvals, state.softabs_eigenvals, state.softabs_inv_eigenvals,\n state.hessian_eigenvecs, state.alpha)\n', (1283, 1462), False, 'from iliad.integrators.fields import riemannian, softabs\n'), ((2883, 2920), 'iliad.integrators.fields.softabs.decomposition', 'softabs.decomposition', (['H', 'state.alpha'], {}), '(H, state.alpha)\n', (2904, 2920), False, 'from iliad.integrators.fields import riemannian, softabs\n'), ((4941, 4969), 'iliad.integrators.terminal.cond', 'cond', (['val', 'thresh', 'max_iters'], {}), '(val, thresh, max_iters)\n', (4945, 4969), False, 'from iliad.integrators.terminal import cond\n'), ((7222, 7250), 'iliad.integrators.terminal.cond', 'cond', (['val', 'thresh', 'max_iters'], {}), '(val, thresh, max_iters)\n', (7226, 7250), False, 'from iliad.integrators.terminal import cond\n'), ((7894, 7910), 'copy.copy', 'copy.copy', (['state'], {}), '(state)\n', (7903, 7910), False, 'import copy\n'), ((7922, 7943), 'iliad.integrators.info.SoftAbsLeapfrogInfo', 'SoftAbsLeapfrogInfo', ([], {}), '()\n', (7941, 7943), False, 'from iliad.integrators.info import SoftAbsLeapfrogInfo\n'), ((8159, 8191), 'numpy.linalg.cholesky', 'np.linalg.cholesky', (['state.metric'], {}), '(state.metric)\n', (8177, 8191), True, 'import numpy as np\n'), ((8609, 8625), 'copy.copy', 'copy.copy', (['state'], {}), '(state)\n', (8618, 8625), False, 'import copy\n'), ((8637, 8658), 'iliad.integrators.info.SoftAbsLeapfrogInfo', 'SoftAbsLeapfrogInfo', ([], {}), '()\n', (8656, 8658), False, 'from iliad.integrators.info import SoftAbsLeapfrogInfo\n'), ((8874, 8906), 'numpy.linalg.cholesky', 'np.linalg.cholesky', (['state.metric'], {}), '(state.metric)\n', (8892, 8906), True, 'import numpy as np\n'), ((4787, 4804), 'numpy.ones', 'np.ones', (['num_dims'], {}), '(num_dims)\n', (4794, 4804), True, 'import numpy as np\n'), ((7071, 7088), 'numpy.ones', 'np.ones', (['num_dims'], {}), '(num_dims)\n', (7078, 7088), True, 'import numpy as np\n'), ((5082, 5095), 'numpy.abs', 'np.abs', (['delta'], {}), '(delta)\n', (5088, 5095), True, 'import numpy as np\n'), ((7385, 7398), 'numpy.abs', 'np.abs', (['delta'], {}), '(delta)\n', (7391, 7398), True, 'import numpy as np\n'), ((8321, 8331), 'numpy.diag', 'np.diag', (['L'], {}), '(L)\n', (8328, 8331), True, 'import numpy as np\n'), ((9036, 9046), 'numpy.diag', 'np.diag', (['L'], {}), '(L)\n', (9043, 9046), True, 'import numpy as np\n')]
|
import numpy as np
def rank5_accuracy(predictions, labels):
# initialize the rank-1 and rank-5 accuracies
rank_1 = 0
rank_5 = 0
# new_predictions = []
# loop over the predictions and the ground-truth labels
for (prediction_, ground_truth) in zip(predictions, labels):
# sort the probabilities by their index in descending order
# so that the more confident guesses are at the front of the list
prediction_ = np.argsort(prediction_)[::-1]
# check if the ground-truth label is in the top-5 predictions
if ground_truth in prediction_[:5]:
rank_5 += 1
# check if the ground-truth is in #1 prediction
if ground_truth == prediction_[0]:
rank_1 += 1
# compute the final rank-1 and rank-5 accuracy
rank_1 /= float(len(labels))
rank_5 /= float(len(labels))
# return a tuple of the rank-1 and rank-5 accuracies
return rank_1, rank_5
|
[
"numpy.argsort"
] |
[((459, 482), 'numpy.argsort', 'np.argsort', (['prediction_'], {}), '(prediction_)\n', (469, 482), True, 'import numpy as np\n')]
|
import numpy as np
from astropy.io import fits
from astropy.table import Table
from scipy.interpolate import InterpolatedUnivariateSpline
import matplotlib.pyplot as plt
#from scipy.signal import medfilt
# Your input template
template = 'Template_s1d_Gl699_sc1d_v_file_AB.fits'
# template = 'Template_s1d_Gl15A_sc1d_v_file_AB.fits'
# template = 'Template_s1d_HD189733_sc1d_v_file_AB.fits'
c = 2.99792458e5 # speed of light
# read wavelength and flux. The wavelength is expressed in Ang, we convert to µm
wave_phoenix = fits.getdata('WAVE_PHOENIX-ACES-AGSS-COND-2011.fits') / 10
# bit of code to download goettigen models. Use only you don't have the models locally and change the False to True
if False:
import os as os
for temperature in np.arange(3000, 6100, 100):
temperature = str(np.int(np.round(temperature, -2)))
print(temperature)
os.system(
'wget ftp://phoenix.astro.physik.uni-goettingen.de/HiResFITS/PHOENIX-ACES-AGSS-COND-2011/Z-0.0/lte0' + temperature + '-4.50-0.0.PHOENIX-ACES-AGSS-COND-2011-HiRes.fits')
# read template and header
tbl, hdr = fits.getdata(template, ext=1, header=True)
# round temperature in header to nearest 100 and get the right model
if 'OBJTEMP' in hdr:
temperature = hdr['OBJTEMP']
if temperature < 3000:
temperature = 3000
if temperature > 6000:
temperature = 6000
temperature = str(np.int(np.round(temperature, -2)))
else:
# if the header does not have a temperature value, assume it is an early-M. This does not really change much
temperature = '3600'
# tell the user which model you are using
print('Temperature = ', temperature)
model_file = 'lte0' + temperature + '-4.50-0.0.PHOENIX-ACES-AGSS-COND-2011-HiRes.fits'
print('Model file = ', model_file)
flux_phoenix = fits.getdata(model_file)
# get wave and flux vectors for the template
w = np.array(tbl['wavelength'])
f = np.array(tbl['flux'])
# smooth the template with a 7 km/s boxcar. This avoids lines due to spurious noise excursions
f2 = np.array(f)
mask = np.isfinite(f)
f2[~mask] = 0
mask = mask*1.0
# smooth by a boxcar and divide by a weight vector to avoid discontinuities at the edge or regions with NaNs
f = np.convolve(f2,np.ones(7), mode = 'same')/np.convolve(mask,np.ones(7), mode = 'same')
# find the first and second derivative of the flux
df = np.gradient(f)
ddf = np.gradient(np.gradient(f))
# lines are regions there is a sign change in the derivative of the flux
# we also have some checks for NaNs
line = np.where((np.sign(df[1:]) != np.sign(df[:-1])) &
np.isfinite(ddf[1:])
& np.isfinite(df[1:])
& np.isfinite(df[:-1]))[0]
# create the output table
tbl = Table()
tbl['ll_mask_s'] = np.zeros_like(line, dtype=float)
tbl['ll_mask_e'] = np.zeros_like(line, dtype=float)
dv = 0# mask width in km/s. Set to zero, but could be changed
for i in range(len(line)):
# we perform a linear interpolation to find the exact wavelength
# where the derivatives goes to zero
wave_cen = (np.polyfit(df[line[i]:line[i] + 2], w[line[i]:line[i] + 2], 1))[1]
# historically, masks are defined over a box of a given width (hence the 's' "start" and the 'e' "end" here)
# here the two values are that same, but one could have a non-zero dv value
corrv = np.sqrt((1 + (-dv / 2) / c) / (1 - (-dv / 2) / c))
tbl['ll_mask_s'][i] = wave_cen * corrv
# same but for the upper bound to the line position
corrv = np.sqrt((1 + (dv / 2) / c) / (1 - (dv / 2) / c))
tbl['ll_mask_e'][i] = wave_cen * corrv
# wavelength of lines is the mean of start and end.
wavelines = (tbl['ll_mask_s'] + tbl['ll_mask_e']) / 2.0
# the weight is the second derivative of the flux. The sharper the line,
# the more weight we give it
g = np.isfinite(ddf)
weight = InterpolatedUnivariateSpline(w[g], ddf[g])(wavelines)
# weight will be the second derivative
tbl['w_mask'] = weight
# create a spline of the model
model = InterpolatedUnivariateSpline(wave_phoenix, flux_phoenix)
# assume a 0 velocity and search
dv0 = 0.0 #
scale = 1.0
for ite in range(2):
dvs = np.arange(400, dtype=float)
dvs -= np.mean(dvs)
dvs *= scale
dvs += dv0
# loop in velocity space and fill the CCF values for each velocity step
ccf = np.zeros_like(dvs)
# this is the line to change if you want to have positive or negative features
mask = weight>0
for i in range(len(dvs)):
corrv = np.sqrt((1 + dvs[i] / c) / (1 - dvs[i] / c))
# lines that will be used in the CCF mask
ccf[i] = np.sum(model(wavelines[mask] / corrv))
# just centering the cc around one and removing low-f trends.
mini = np.argmin(ccf)
dv0 = dvs[mini]
scale /= 10.0
plt.plot(dvs, ccf)
plt.show()
# find the lowest point in the CCF
minpos = np.argmin(ccf)
# fit a 2nd order polynomial to the bottom pixels (-1 to +1 from bottom) and find minimimum point
fit = np.polyfit(dvs[minpos - 1:minpos + 2], ccf[minpos - 1:minpos + 2], 2)
# minimum of a 2nd order polynomial
systemic_velocity = -.5 * fit[1] / fit[0]
# return systemic velocity measured
print('systemic velocity : ', systemic_velocity, 'km/s')
# generate a nice plot to show positive/negative features
wavelines =tbl['ll_mask_s']
# find flux at sub-pixel position of lines
g = np.isfinite(f)
flux_lines = InterpolatedUnivariateSpline(w[g], f[g])(wavelines)
plt.plot(w,f, 'g-',label = 'spectrum')
pos_lines = np.array(tbl['w_mask'] < 0)
plt.plot(np.array(wavelines[pos_lines]),flux_lines[pos_lines],'r.', label = 'positive features')
neg_lines = np.array(tbl['w_mask'] > 0)
plt.plot(np.array(wavelines[neg_lines]),flux_lines[neg_lines],'b.', label = 'negative features')
plt.legend()
plt.show()
# updating the table to account for systemic velocity of star
corrv = np.sqrt((1 + systemic_velocity / c) / (1 - systemic_velocity / c)) # relativistic Doppler
tbl['ll_mask_s'] = tbl['ll_mask_s'] / corrv
tbl['ll_mask_e'] = tbl['ll_mask_e'] / corrv
# write the output table
fits.writeto(hdr['OBJECT'] + '.fits', tbl, hdr, overwrite=True)
tbl[tbl['w_mask'] < 0].write(hdr['OBJECT'] + '_pos.mas', format='ascii', overwrite=True)
tbl[tbl['w_mask'] > 0].write(hdr['OBJECT'] + '_neg.mas', format='ascii', overwrite=True)
tbl.write(hdr['OBJECT'] + '_full.mas', format='ascii', overwrite=True)
|
[
"numpy.polyfit",
"numpy.ones",
"numpy.argmin",
"numpy.mean",
"numpy.arange",
"numpy.round",
"numpy.zeros_like",
"scipy.interpolate.InterpolatedUnivariateSpline",
"astropy.io.fits.getdata",
"numpy.isfinite",
"matplotlib.pyplot.show",
"matplotlib.pyplot.legend",
"os.system",
"astropy.table.Table",
"matplotlib.pyplot.plot",
"astropy.io.fits.writeto",
"numpy.array",
"numpy.sign",
"numpy.gradient",
"numpy.sqrt"
] |
[((1107, 1149), 'astropy.io.fits.getdata', 'fits.getdata', (['template'], {'ext': '(1)', 'header': '(True)'}), '(template, ext=1, header=True)\n', (1119, 1149), False, 'from astropy.io import fits\n'), ((1801, 1825), 'astropy.io.fits.getdata', 'fits.getdata', (['model_file'], {}), '(model_file)\n', (1813, 1825), False, 'from astropy.io import fits\n'), ((1876, 1903), 'numpy.array', 'np.array', (["tbl['wavelength']"], {}), "(tbl['wavelength'])\n", (1884, 1903), True, 'import numpy as np\n'), ((1908, 1929), 'numpy.array', 'np.array', (["tbl['flux']"], {}), "(tbl['flux'])\n", (1916, 1929), True, 'import numpy as np\n'), ((2031, 2042), 'numpy.array', 'np.array', (['f'], {}), '(f)\n', (2039, 2042), True, 'import numpy as np\n'), ((2050, 2064), 'numpy.isfinite', 'np.isfinite', (['f'], {}), '(f)\n', (2061, 2064), True, 'import numpy as np\n'), ((2351, 2365), 'numpy.gradient', 'np.gradient', (['f'], {}), '(f)\n', (2362, 2365), True, 'import numpy as np\n'), ((2717, 2724), 'astropy.table.Table', 'Table', ([], {}), '()\n', (2722, 2724), False, 'from astropy.table import Table\n'), ((2744, 2776), 'numpy.zeros_like', 'np.zeros_like', (['line'], {'dtype': 'float'}), '(line, dtype=float)\n', (2757, 2776), True, 'import numpy as np\n'), ((2796, 2828), 'numpy.zeros_like', 'np.zeros_like', (['line'], {'dtype': 'float'}), '(line, dtype=float)\n', (2809, 2828), True, 'import numpy as np\n'), ((3791, 3807), 'numpy.isfinite', 'np.isfinite', (['ddf'], {}), '(ddf)\n', (3802, 3807), True, 'import numpy as np\n'), ((3974, 4030), 'scipy.interpolate.InterpolatedUnivariateSpline', 'InterpolatedUnivariateSpline', (['wave_phoenix', 'flux_phoenix'], {}), '(wave_phoenix, flux_phoenix)\n', (4002, 4030), False, 'from scipy.interpolate import InterpolatedUnivariateSpline\n'), ((4769, 4779), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4777, 4779), True, 'import matplotlib.pyplot as plt\n'), ((4825, 4839), 'numpy.argmin', 'np.argmin', (['ccf'], {}), '(ccf)\n', (4834, 4839), True, 'import numpy as np\n'), ((4944, 5013), 'numpy.polyfit', 'np.polyfit', (['dvs[minpos - 1:minpos + 2]', 'ccf[minpos - 1:minpos + 2]', '(2)'], {}), '(dvs[minpos - 1:minpos + 2], ccf[minpos - 1:minpos + 2], 2)\n', (4954, 5013), True, 'import numpy as np\n'), ((5321, 5335), 'numpy.isfinite', 'np.isfinite', (['f'], {}), '(f)\n', (5332, 5335), True, 'import numpy as np\n'), ((5402, 5440), 'matplotlib.pyplot.plot', 'plt.plot', (['w', 'f', '"""g-"""'], {'label': '"""spectrum"""'}), "(w, f, 'g-', label='spectrum')\n", (5410, 5440), True, 'import matplotlib.pyplot as plt\n'), ((5453, 5480), 'numpy.array', 'np.array', (["(tbl['w_mask'] < 0)"], {}), "(tbl['w_mask'] < 0)\n", (5461, 5480), True, 'import numpy as np\n'), ((5590, 5617), 'numpy.array', 'np.array', (["(tbl['w_mask'] > 0)"], {}), "(tbl['w_mask'] > 0)\n", (5598, 5617), True, 'import numpy as np\n'), ((5715, 5727), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (5725, 5727), True, 'import matplotlib.pyplot as plt\n'), ((5728, 5738), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5736, 5738), True, 'import matplotlib.pyplot as plt\n'), ((5810, 5876), 'numpy.sqrt', 'np.sqrt', (['((1 + systemic_velocity / c) / (1 - systemic_velocity / c))'], {}), '((1 + systemic_velocity / c) / (1 - systemic_velocity / c))\n', (5817, 5876), True, 'import numpy as np\n'), ((6015, 6078), 'astropy.io.fits.writeto', 'fits.writeto', (["(hdr['OBJECT'] + '.fits')", 'tbl', 'hdr'], {'overwrite': '(True)'}), "(hdr['OBJECT'] + '.fits', tbl, hdr, overwrite=True)\n", (6027, 6078), False, 'from astropy.io import fits\n'), ((522, 575), 'astropy.io.fits.getdata', 'fits.getdata', (['"""WAVE_PHOENIX-ACES-AGSS-COND-2011.fits"""'], {}), "('WAVE_PHOENIX-ACES-AGSS-COND-2011.fits')\n", (534, 575), False, 'from astropy.io import fits\n'), ((752, 778), 'numpy.arange', 'np.arange', (['(3000)', '(6100)', '(100)'], {}), '(3000, 6100, 100)\n', (761, 778), True, 'import numpy as np\n'), ((2384, 2398), 'numpy.gradient', 'np.gradient', (['f'], {}), '(f)\n', (2395, 2398), True, 'import numpy as np\n'), ((3319, 3365), 'numpy.sqrt', 'np.sqrt', (['((1 + -dv / 2 / c) / (1 - -dv / 2 / c))'], {}), '((1 + -dv / 2 / c) / (1 - -dv / 2 / c))\n', (3326, 3365), True, 'import numpy as np\n'), ((3482, 3526), 'numpy.sqrt', 'np.sqrt', (['((1 + dv / 2 / c) / (1 - dv / 2 / c))'], {}), '((1 + dv / 2 / c) / (1 - dv / 2 / c))\n', (3489, 3526), True, 'import numpy as np\n'), ((3817, 3859), 'scipy.interpolate.InterpolatedUnivariateSpline', 'InterpolatedUnivariateSpline', (['w[g]', 'ddf[g]'], {}), '(w[g], ddf[g])\n', (3845, 3859), False, 'from scipy.interpolate import InterpolatedUnivariateSpline\n'), ((4120, 4147), 'numpy.arange', 'np.arange', (['(400)'], {'dtype': 'float'}), '(400, dtype=float)\n', (4129, 4147), True, 'import numpy as np\n'), ((4159, 4171), 'numpy.mean', 'np.mean', (['dvs'], {}), '(dvs)\n', (4166, 4171), True, 'import numpy as np\n'), ((4292, 4310), 'numpy.zeros_like', 'np.zeros_like', (['dvs'], {}), '(dvs)\n', (4305, 4310), True, 'import numpy as np\n'), ((4691, 4705), 'numpy.argmin', 'np.argmin', (['ccf'], {}), '(ccf)\n', (4700, 4705), True, 'import numpy as np\n'), ((4750, 4768), 'matplotlib.pyplot.plot', 'plt.plot', (['dvs', 'ccf'], {}), '(dvs, ccf)\n', (4758, 4768), True, 'import matplotlib.pyplot as plt\n'), ((5349, 5389), 'scipy.interpolate.InterpolatedUnivariateSpline', 'InterpolatedUnivariateSpline', (['w[g]', 'f[g]'], {}), '(w[g], f[g])\n', (5377, 5389), False, 'from scipy.interpolate import InterpolatedUnivariateSpline\n'), ((5490, 5520), 'numpy.array', 'np.array', (['wavelines[pos_lines]'], {}), '(wavelines[pos_lines])\n', (5498, 5520), True, 'import numpy as np\n'), ((5627, 5657), 'numpy.array', 'np.array', (['wavelines[neg_lines]'], {}), '(wavelines[neg_lines])\n', (5635, 5657), True, 'import numpy as np\n'), ((876, 1064), 'os.system', 'os.system', (["(\n 'wget ftp://phoenix.astro.physik.uni-goettingen.de/HiResFITS/PHOENIX-ACES-AGSS-COND-2011/Z-0.0/lte0'\n + temperature + '-4.50-0.0.PHOENIX-ACES-AGSS-COND-2011-HiRes.fits')"], {}), "(\n 'wget ftp://phoenix.astro.physik.uni-goettingen.de/HiResFITS/PHOENIX-ACES-AGSS-COND-2011/Z-0.0/lte0'\n + temperature + '-4.50-0.0.PHOENIX-ACES-AGSS-COND-2011-HiRes.fits')\n", (885, 1064), True, 'import os as os\n'), ((2223, 2233), 'numpy.ones', 'np.ones', (['(7)'], {}), '(7)\n', (2230, 2233), True, 'import numpy as np\n'), ((2267, 2277), 'numpy.ones', 'np.ones', (['(7)'], {}), '(7)\n', (2274, 2277), True, 'import numpy as np\n'), ((3046, 3108), 'numpy.polyfit', 'np.polyfit', (['df[line[i]:line[i] + 2]', 'w[line[i]:line[i] + 2]', '(1)'], {}), '(df[line[i]:line[i] + 2], w[line[i]:line[i] + 2], 1)\n', (3056, 3108), True, 'import numpy as np\n'), ((4461, 4505), 'numpy.sqrt', 'np.sqrt', (['((1 + dvs[i] / c) / (1 - dvs[i] / c))'], {}), '((1 + dvs[i] / c) / (1 - dvs[i] / c))\n', (4468, 4505), True, 'import numpy as np\n'), ((1412, 1437), 'numpy.round', 'np.round', (['temperature', '(-2)'], {}), '(temperature, -2)\n', (1420, 1437), True, 'import numpy as np\n'), ((2659, 2679), 'numpy.isfinite', 'np.isfinite', (['df[:-1]'], {}), '(df[:-1])\n', (2670, 2679), True, 'import numpy as np\n'), ((813, 838), 'numpy.round', 'np.round', (['temperature', '(-2)'], {}), '(temperature, -2)\n', (821, 838), True, 'import numpy as np\n'), ((2621, 2640), 'numpy.isfinite', 'np.isfinite', (['df[1:]'], {}), '(df[1:])\n', (2632, 2640), True, 'import numpy as np\n'), ((2582, 2602), 'numpy.isfinite', 'np.isfinite', (['ddf[1:]'], {}), '(ddf[1:])\n', (2593, 2602), True, 'import numpy as np\n'), ((2527, 2542), 'numpy.sign', 'np.sign', (['df[1:]'], {}), '(df[1:])\n', (2534, 2542), True, 'import numpy as np\n'), ((2546, 2562), 'numpy.sign', 'np.sign', (['df[:-1]'], {}), '(df[:-1])\n', (2553, 2562), True, 'import numpy as np\n')]
|
# This program displays a plot of the functions x, x2 and 2x in the range [0, 4]
# <NAME> 2019-03-24
# I formulated this solution using the week 9 lectures as a starting point followed by further reading and research which is detailed further in the references section in the Readme file
# Additional reading included the matplotlib pyplot tutorial as recommended in lectures: https://matplotlib.org/users/pyplot_tutorial.html
print("The Plot should appear on your screen momentarily") # I have returned this line to the user when the script is run
import numpy as np # numpy module is imported and given the short name np
import matplotlib.pyplot as pl # mathplotlib.pyplot module is imported and given a shorter name pl
x = np.arange(start = 0, stop = 4) #The range is defined as being between 0 and 4 using the numpy.arange function
# Using numpy.arange to set the range between 0 and 4 using start and stop parameters
pl.xlabel("x axis", fontsize=12, fontweight= 'bold') # Adding name to x and y axis (read in pyplot tutorial text section)
pl.ylabel("y axis", fontsize=12, fontweight= 'bold') # Added a font size and font weight to the x and y axis labels
pl.title("Plot Generated from Solution_10.py", fontsize= 14, fontweight='bold')
# Adding a title to the plot and formatting as read in the text section of the pyplot tutorial
a = x # I introduced a variable called a set it equal to the value of x
b = x*x # I introduced a variable called b and set it equal to the value of x squared
c = 2**x # I introduced a variable called C and set it equal to 2 to the power of x. ** the power operator is used
pl.plot(a, c='r', lw= 4.0, ls= '--', label= 'x') # I have asked for 'a' to be plotted with a red line
# c short for color, ls short for linestyle and lw short for linewidth
# I formatted the line that will be plotted using the attributes that I read about in the 'controlling line properties' section of the pyplot tutorial
pl.plot(b, c='g', lw= 4.0, ls= '--', label= 'x²') # I have asked for 'b' to be plotted with a green line
pl.plot(c, c='y', lw= 4.0, ls= '--', label= '2x') # I have asked for 'c' to be plotted with a yellow line
pl.legend(loc= 'upper left') # This command shows the legend on the plot, I have given the names in pl.plot above using label
# I have used loc and upper left ask for the legend to be placed in the top left corner of the plot
pl.grid(True) # I revisited the solution and asked for a grid to be shown on the plot after further reading
pl.show() # This is the command used to show the plot created above
|
[
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.legend",
"numpy.arange",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.grid"
] |
[((728, 754), 'numpy.arange', 'np.arange', ([], {'start': '(0)', 'stop': '(4)'}), '(start=0, stop=4)\n', (737, 754), True, 'import numpy as np\n'), ((924, 975), 'matplotlib.pyplot.xlabel', 'pl.xlabel', (['"""x axis"""'], {'fontsize': '(12)', 'fontweight': '"""bold"""'}), "('x axis', fontsize=12, fontweight='bold')\n", (933, 975), True, 'import matplotlib.pyplot as pl\n'), ((1046, 1097), 'matplotlib.pyplot.ylabel', 'pl.ylabel', (['"""y axis"""'], {'fontsize': '(12)', 'fontweight': '"""bold"""'}), "('y axis', fontsize=12, fontweight='bold')\n", (1055, 1097), True, 'import matplotlib.pyplot as pl\n'), ((1162, 1240), 'matplotlib.pyplot.title', 'pl.title', (['"""Plot Generated from Solution_10.py"""'], {'fontsize': '(14)', 'fontweight': '"""bold"""'}), "('Plot Generated from Solution_10.py', fontsize=14, fontweight='bold')\n", (1170, 1240), True, 'import matplotlib.pyplot as pl\n'), ((1614, 1659), 'matplotlib.pyplot.plot', 'pl.plot', (['a'], {'c': '"""r"""', 'lw': '(4.0)', 'ls': '"""--"""', 'label': '"""x"""'}), "(a, c='r', lw=4.0, ls='--', label='x')\n", (1621, 1659), True, 'import matplotlib.pyplot as pl\n'), ((1939, 1985), 'matplotlib.pyplot.plot', 'pl.plot', (['b'], {'c': '"""g"""', 'lw': '(4.0)', 'ls': '"""--"""', 'label': '"""x²"""'}), "(b, c='g', lw=4.0, ls='--', label='x²')\n", (1946, 1985), True, 'import matplotlib.pyplot as pl\n'), ((2044, 2090), 'matplotlib.pyplot.plot', 'pl.plot', (['c'], {'c': '"""y"""', 'lw': '(4.0)', 'ls': '"""--"""', 'label': '"""2x"""'}), "(c, c='y', lw=4.0, ls='--', label='2x')\n", (2051, 2090), True, 'import matplotlib.pyplot as pl\n'), ((2151, 2178), 'matplotlib.pyplot.legend', 'pl.legend', ([], {'loc': '"""upper left"""'}), "(loc='upper left')\n", (2160, 2178), True, 'import matplotlib.pyplot as pl\n'), ((2377, 2390), 'matplotlib.pyplot.grid', 'pl.grid', (['(True)'], {}), '(True)\n', (2384, 2390), True, 'import matplotlib.pyplot as pl\n'), ((2485, 2494), 'matplotlib.pyplot.show', 'pl.show', ([], {}), '()\n', (2492, 2494), True, 'import matplotlib.pyplot as pl\n')]
|
import numpy as np
from scipy.linalg import expm
class Env( object):
def __init__(self,
action_space=[0,1,2],
dt=0.1):
super(Env, self).__init__()
self.action_space = action_space
self.n_actions = len(self.action_space)
self.n_features = 4
self.state = np.array([1,0,0,0])
self.nstep=0
self.dt=dt
def reset(self):
self.state = np.array([1,0,0,0])
self.nstep = 0
return self.state
def step(self, action):
psi = np.array([self.state[0:int(len(self.state) / 2)] + self.state[int(len(self.state) / 2):int(len(self.state))] * 1j])
psi = psi.T
psi=np.mat(psi)
J = 4 # control field strength
sx = np.mat([[0, 1], [1, 0]], dtype=complex)
sz = np.mat([[1, 0], [0, -1]], dtype=complex)
U = np.matrix(np.identity(2, dtype=complex))
H = J *float(action)/(self.n_actions-1)* sz + 1 * sx
U = expm(-1j * H * self.dt)
psi = U * psi # final state
target = np.mat([[0], [1]], dtype=complex)
err = 1 - (np.abs(psi.H * target) ** 2).item(0).real
rwd = 10 * (err<0.5)+100 * (err<0.1)+5000*(err < 10e-3)
done =( (err < 10e-3) or self.nstep>=np.pi/self.dt )
self.nstep +=1
psi=np.array(psi)
psi_T = psi.T
self.state = np.array(psi_T.real.tolist()[0] + psi_T.imag.tolist()[0])
return self.state, rwd, done, 1 - err
|
[
"scipy.linalg.expm",
"numpy.abs",
"numpy.identity",
"numpy.array",
"numpy.mat"
] |
[((314, 336), 'numpy.array', 'np.array', (['[1, 0, 0, 0]'], {}), '([1, 0, 0, 0])\n', (322, 336), True, 'import numpy as np\n'), ((419, 441), 'numpy.array', 'np.array', (['[1, 0, 0, 0]'], {}), '([1, 0, 0, 0])\n', (427, 441), True, 'import numpy as np\n'), ((683, 694), 'numpy.mat', 'np.mat', (['psi'], {}), '(psi)\n', (689, 694), True, 'import numpy as np\n'), ((749, 788), 'numpy.mat', 'np.mat', (['[[0, 1], [1, 0]]'], {'dtype': 'complex'}), '([[0, 1], [1, 0]], dtype=complex)\n', (755, 788), True, 'import numpy as np\n'), ((802, 842), 'numpy.mat', 'np.mat', (['[[1, 0], [0, -1]]'], {'dtype': 'complex'}), '([[1, 0], [0, -1]], dtype=complex)\n', (808, 842), True, 'import numpy as np\n'), ((981, 1006), 'scipy.linalg.expm', 'expm', (['(-1.0j * H * self.dt)'], {}), '(-1.0j * H * self.dt)\n', (985, 1006), False, 'from scipy.linalg import expm\n'), ((1063, 1096), 'numpy.mat', 'np.mat', (['[[0], [1]]'], {'dtype': 'complex'}), '([[0], [1]], dtype=complex)\n', (1069, 1096), True, 'import numpy as np\n'), ((1330, 1343), 'numpy.array', 'np.array', (['psi'], {}), '(psi)\n', (1338, 1343), True, 'import numpy as np\n'), ((866, 895), 'numpy.identity', 'np.identity', (['(2)'], {'dtype': 'complex'}), '(2, dtype=complex)\n', (877, 895), True, 'import numpy as np\n'), ((1118, 1140), 'numpy.abs', 'np.abs', (['(psi.H * target)'], {}), '(psi.H * target)\n', (1124, 1140), True, 'import numpy as np\n')]
|
# CSC 321, Assignment 4
#
# This is the main training file for the vanilla GAN part of the assignment.
#
# Usage:
# ======
# To train with the default hyperparamters (saves results to checkpoints_vanilla/ and samples_vanilla/):
# python vanilla_gan.py
import os
import pdb
import pickle
import argparse
import warnings
warnings.filterwarnings("ignore")
# Numpy & Scipy imports
import numpy as np
import scipy
import scipy.misc
# Torch imports
import torch
import torch.nn as nn
import torch.optim as optim
# Local imports
import utils
from data_loader import get_emoji_loader
from models import DCGenerator, DCDiscriminator
from models import WGANDiscriminator, WGANGenerator
from models import WGANGPDiscriminator, WGANGPGenerator
SEED = 11
# Set the random seed manually for reproducibility.
np.random.seed(SEED)
torch.manual_seed(SEED)
if torch.cuda.is_available():
torch.cuda.manual_seed(SEED)
def print_models(G, D):
"""Prints model information for the generators and discriminators.
"""
print(" G ")
print("---------------------------------------")
print(G)
print("---------------------------------------")
print(" D ")
print("---------------------------------------")
print(D)
print("---------------------------------------")
def create_model(opts):
"""Builds the generators and discriminators.
"""
if opts.GAN_type == 'LSGAN':
G = DCGenerator(noise_size=opts.noise_size, conv_dim=opts.conv_dim)
D = DCDiscriminator(conv_dim=opts.conv_dim, batch_norm=not opts.disable_bn)
elif opts.GAN_type == 'WGAN':
G = WGANGenerator(noise_size=opts.noise_size, conv_dim=opts.conv_dim)
D = WGANDiscriminator(conv_dim=opts.conv_dim, batch_norm=not opts.disable_bn)
elif opts.GAN_type == 'WGANGP':
G = WGANGPGenerator(noise_size=opts.noise_size, conv_dim=opts.conv_dim)
D = WGANGPDiscriminator(conv_dim=opts.conv_dim)
#print_models(G, D)
#move to device
G.to(opts.device) # in-place
D.to(opts.device) # in-place
print_models(G, D)
print('Models are at:'+str(opts.device))
return G, D
def checkpoint(iteration, G, D, opts):
"""Saves the parameters of the generator G and discriminator D.
"""
G_path = os.path.join(opts.checkpoint_dir, 'G.pkl')
D_path = os.path.join(opts.checkpoint_dir, 'D.pkl')
torch.save(G.state_dict(), G_path)
torch.save(D.state_dict(), D_path)
def create_image_grid(array, ncols=None):
"""
"""
num_images, channels, cell_h, cell_w = array.shape
if not ncols:
ncols = int(np.sqrt(num_images))
nrows = int(np.math.floor(num_images / float(ncols)))
result = np.zeros((cell_h*nrows, cell_w*ncols, channels), dtype=array.dtype)
for i in range(0, nrows):
for j in range(0, ncols):
result[i*cell_h:(i+1)*cell_h, j*cell_w:(j+1)*cell_w, :] = array[i*ncols+j].transpose(1, 2, 0)
if channels == 1:
result = result.squeeze()
return result
def save_samples(G, fixed_noise, iteration, opts):
generated_images = G(fixed_noise)
generated_images = utils.to_data(generated_images)
grid = create_image_grid(generated_images)
# merged = merge_images(X, fake_Y, opts)
path = os.path.join(opts.sample_dir, 'sample-{:06d}.png'.format(iteration))
scipy.misc.imsave(path, grid)
print('Saved {}'.format(path))
def sample_noise(dim):
"""
Generate a PyTorch Variable of uniform random noise.
Input:
- batch_size: Integer giving the batch size of noise to generate.
- dim: Integer giving the dimension of noise to generate.
Output:
- A PyTorch Variable of shape (batch_size, dim, 1, 1) containing uniform
random noise in the range (-1, 1).
"""
return utils.to_var(torch.rand(batch_size, dim) * 2 - 1).unsqueeze(2).unsqueeze(3)
def training_loop_LSGAN(train_dataloader, opts):
"""Runs the training loop.
* Saves checkpoints every opts.checkpoint_every iterations
* Saves generated samples every opts.sample_every iterations
"""
# Create generators and discriminators
G, D = create_model(opts)
# Create optimizers for the generators and discriminators
if opts.optimizer == 'Adam':
d_optimizer = optim.Adam(D.parameters(), opts.lr, [opts.beta1, opts.beta2])
g_optimizer = optim.Adam(G.parameters(), opts.lr, [opts.beta1, opts.beta2])
elif opts.optimizer == 'RMSProp' or opts.GAN_type == 'WGAN':
d_optimizer = optim.RMSprop(D.parameters(), opts.lr)
g_optimizer = optim.RMSprop(G.parameters(), opts.lr)
print(d_optimizer)
print(g_optimizer)
# Generate fixed noise for sampling from the generator
fixed_noise = sample_noise(opts.noise_size) # batch_size x noise_size x 1 x 1
iteration = 1
total_train_iters = opts.num_epochs * len(train_dataloader)
device = opts.device
noise_dim = opts.noise_size
#batch_size = opts.batch_size
for epoch in range(opts.num_epochs):
for batch in train_dataloader:
real_images, _ = batch
#print(real_images.device)
real_images = real_images.to(device)
#print(real_images.device)
#real_images, labels = utils.to_var(real_images), utils.to_var(labels).long().squeeze()
#print(real_images.shape)
################################################
### TRAIN THE DISCRIMINATOR ####
################################################
d_optimizer.zero_grad()
# FILL THIS IN
# 1. Compute the discriminator loss on real images
D_real_loss = 0.5 * torch.sum((D(real_images) - 1)**2) / batch_size
#D_real_loss = 0.5 * torch.sum((D(real_images) - 0.9)**2) / batch_size
#print(D_real_loss)
# 2. Sample noise
noise = 2 * torch.rand(batch_size, noise_dim) - 1
noise = noise.view(batch_size, noise_dim, 1, 1).to(device)
#print(noise.shape)
# 3. Generate fake images from the noise
fake_images = G(noise)
# 4. Compute the discriminator loss on the fake images
D_fake_loss = 0.5 * torch.sum(D(fake_images)**2) / batch_size
# 5. Compute the total discriminator loss
D_total_loss = D_fake_loss + D_real_loss
D_total_loss.backward()
d_optimizer.step()
###########################################
### TRAIN THE GENERATOR ###
###########################################
g_optimizer.zero_grad()
# FILL THIS IN
# 1. Sample noise
noise = 2 * torch.rand(batch_size, noise_dim) - 1
noise = noise.view(batch_size, noise_dim, 1, 1).to(device)
# 2. Generate fake images from the noise
fake_images = G(noise)
# 3. Compute the generator loss
G_loss = torch.sum((D(fake_images) -1)**2)/ batch_size
#G_loss = torch.sum((D(fake_images) -0.9)**2)/ batch_size
G_loss.backward()
g_optimizer.step()
# Print the log info
if iteration % opts.log_step == 0:
print('Iteration [{:4d}/{:4d}] | D_real_loss: {:6.4f} | D_fake_loss: {:6.4f} | G_loss: {:6.4f}'.format(
iteration, total_train_iters, D_real_loss.data[0], D_fake_loss.data[0], G_loss.data[0]))
# Save the generated samples
if iteration % opts.sample_every == 0:
save_samples(G, fixed_noise, iteration, opts)
# Save the model parameters
if iteration % opts.checkpoint_every == 0:
checkpoint(iteration, G, D, opts)
iteration += 1
def training_loop_WGAN(train_dataloader, opts):
"""Runs the training loop.
* Saves checkpoints every opts.checkpoint_every iterations
* Saves generated samples every opts.sample_every iterations
"""
# Create generators and discriminators
G, D = create_model(opts)
# Create optimizers for the generators and discriminators
if opts.optimizer == 'Adam':
d_optimizer = optim.Adam(D.parameters(), opts.lr, [opts.beta1, opts.beta2])
g_optimizer = optim.Adam(G.parameters(), opts.lr, [opts.beta1, opts.beta2])
elif opts.optimizer == 'RMSProp' or opts.GAN_type == 'WGAN':
d_optimizer = optim.RMSprop(D.parameters(), opts.lr)
g_optimizer = optim.RMSprop(G.parameters(), opts.lr)
print(d_optimizer)
print(g_optimizer)
# Generate fixed noise for sampling from the generator
fixed_noise = sample_noise(opts.noise_size) # batch_size x noise_size x 1 x 1
iteration = 1
total_train_iters = opts.num_epochs * len(train_dataloader)
device = opts.device
noise_dim = opts.noise_size
clip_value = 0.01
for epoch in range(opts.num_epochs):
for batch in train_dataloader:
real_images, _ = batch
#print(real_images.device)
real_images = real_images.to(device)
#print(real_images.device)
#real_images, labels = utils.to_var(real_images), utils.to_var(labels).long().squeeze()
#print(real_images.shape)
################################################
### TRAIN THE DISCRIMINATOR ####
################################################
d_optimizer.zero_grad()
# 2. Sample noise
noise = 2 * torch.rand(batch_size, noise_dim) - 1
noise = noise.view(batch_size, noise_dim, 1, 1).to(device)
# 3. Generate fake images from the noise
fake_images = G(noise).detach()
# 5. Compute the total discriminator loss
D_total_loss = torch.mean(D(fake_images)) - torch.mean(D(real_images))
D_total_loss.backward()
d_optimizer.step()
# CLIP WEIGHTS!!!! of Dicriminator
for p in D.parameters():
p.data.clamp_(-clip_value, clip_value)
###########################################
### TRAIN THE GENERATOR ###
###########################################
g_optimizer.zero_grad()
# FILL THIS IN
# 1. Sample noise
noise = 2 * torch.rand(batch_size, noise_dim) - 1
noise = noise.view(batch_size, noise_dim, 1, 1).to(device)
# 2. Generate fake images from the noise
fake_images = G(noise)
# 3. Compute the generator loss
G_loss = -torch.mean(D(fake_images))
#G_loss = torch.sum((D(fake_images) -0.9)**2)/ batch_size
G_loss.backward()
g_optimizer.step()
# Print the log info
with torch.no_grad():
if iteration % opts.log_step == 0:
print('Iteration [{:4d}/{:4d}] | D_total_loss: {:6.4f} | G_loss: {:6.4f}'.format(
iteration, total_train_iters, D_total_loss.data[0], G_loss.data[0]))
# Save the generated samples
if iteration % opts.sample_every == 0:
save_samples(G, fixed_noise, iteration, opts)
# Save the model parameters
if iteration % opts.checkpoint_every == 0:
checkpoint(iteration, G, D, opts)
iteration += 1
def training_loop_WGANGP(train_dataloader, opts):
"""Runs the training loop.
* Saves checkpoints every opts.checkpoint_every iterations
* Saves generated samples every opts.sample_every iterations
"""
# Create generators and discriminators
G, D = create_model(opts)
# Create optimizers for the generators and discriminators
if opts.optimizer == 'Adam':
d_optimizer = optim.Adam(D.parameters(), opts.lr, [opts.beta1, opts.beta2])
g_optimizer = optim.Adam(G.parameters(), opts.lr, [opts.beta1, opts.beta2])
elif opts.optimizer == 'RMSProp':
d_optimizer = optim.RMSprop(D.parameters(), opts.lr)
g_optimizer = optim.RMSprop(G.parameters(), opts.lr)
print(d_optimizer)
print(g_optimizer)
# Generate fixed noise for sampling from the generator
fixed_noise = sample_noise(opts.noise_size) # batch_size x noise_size x 1 x 1
iteration = 1
total_train_iters = opts.num_epochs * len(train_dataloader)
device = opts.device
noise_dim = opts.noise_size
lambda_GP = 10
for epoch in range(opts.num_epochs):
for batch in train_dataloader:
real_images, _ = batch
batch_size = real_images.shape[0]
#print(real_images.device)
real_images = real_images.to(device)
#print(real_images.device)
#real_images, labels = utils.to_var(real_images), utils.to_var(labels).long().squeeze()
#print(real_images.shape)
################################################
### TRAIN THE DISCRIMINATOR ####
################################################
d_optimizer.zero_grad()
# 2. Sample noise
noise = 2 * torch.rand(batch_size, noise_dim) - 1
noise = noise.view(batch_size, noise_dim, 1, 1).to(device)
# 3. Generate fake images from the noise
fake_images = G(noise)
D_fake_loss = torch.mean(D(fake_images))
# 4. Calculate gradient penalty(GP)
random_eps = torch.rand(1, device=device)
#print(fake_images.shape)
#print(real_images.shape)
interpolates = (1 - random_eps) * fake_images + random_eps * real_images
D_interpolates = D(interpolates)
# 5. Compute the total discriminator loss
fake = torch.ones(D_interpolates.size(), device=device)
#print(fake_images.shape)
#print(D_fake_loss.shape)
gradients = torch.autograd.grad(
outputs=D_interpolates, inputs=interpolates, grad_outputs=fake, create_graph=True, retain_graph=True, only_inputs=True)[0]
#print(gradients[0].shape)
D_total_loss = D_fake_loss - \
torch.mean(D(real_images)) \
+ lambda_GP * \
(gradients.norm(2) - 1)**2
D_total_loss.backward()
d_optimizer.step()
###########################################
### TRAIN THE GENERATOR ###
###########################################
g_optimizer.zero_grad()
# FILL THIS IN
# 1. Sample noise
noise = 2 * torch.rand(batch_size, noise_dim) - 1
noise = noise.view(batch_size, noise_dim, 1, 1).to(device)
# 2. Generate fake images from the noise
fake_images = G(noise)
# 3. Compute the generator loss
G_loss = -torch.mean(D(fake_images))
#G_loss = torch.sum((D(fake_images) -0.9)**2)/ batch_size
G_loss.backward()
g_optimizer.step()
# Print the log info
with torch.no_grad():
if iteration % opts.log_step == 0:
print('Iteration [{:4d}/{:4d}] | D_total_loss: {:6.4f} | G_loss: {:6.4f}'.format(
iteration, total_train_iters, D_total_loss.data[0], G_loss.data[0]))
# Save the generated samples
if iteration % opts.sample_every == 0:
save_samples(G, fixed_noise, iteration, opts)
# Save the model parameters
if iteration % opts.checkpoint_every == 0:
checkpoint(iteration, G, D, opts)
iteration += 1
def main(opts):
"""Loads the data, creates checkpoint and sample directories, and starts the training loop.
"""
# Create a dataloader for the training images
train_dataloader, _ = get_emoji_loader(opts.emoji, opts)
# Create checkpoint and sample directories
utils.create_dir(opts.checkpoint_dir)
utils.create_dir(opts.sample_dir)
if opts.GAN_type == 'LSGAN':
training_loop_LSGAN(train_dataloader, opts)
elif opts.GAN_type == 'WGAN':
training_loop_WGAN(train_dataloader, opts)
elif opts.GAN_type == 'WGANGP':
training_loop_WGANGP(train_dataloader, opts)
def create_parser():
"""Creates a parser for command-line arguments.
"""
parser = argparse.ArgumentParser()
# Model hyper-parameters
parser.add_argument('--image_size', type=int, default=32, help='The side length N to convert images to NxN.')
parser.add_argument('--conv_dim', type=int, default=32)
parser.add_argument('--noise_size', type=int, default=100)
parser.add_argument('--disable_bn', action='store_true', help='Disable Batch Normalization(BN)')
# Training hyper-parameters
parser.add_argument('--num_epochs', type=int, default=40)
parser.add_argument('--batch_size', type=int, default=16, help='The number of images in a batch.')
parser.add_argument('--num_workers', type=int, default=0, help='The number of threads to use for the DataLoader.')
parser.add_argument('--lr', type=float, default=0.0003, help='The learning rate (default 0.0003)')
parser.add_argument('--beta1', type=float, default=0.5)
parser.add_argument('--beta2', type=float, default=0.999)
# Data sources
parser.add_argument('--emoji', type=str, default='Apple', choices=['Apple', 'Facebook', 'Windows'], help='Choose the type of emojis to generate.')
# Directories and checkpoint/sample iterations
parser.add_argument('--checkpoint_dir', type=str, default='./checkpoints_vanilla')
parser.add_argument('--sample_dir', type=str, default='./samples_vanilla')
parser.add_argument('--log_step', type=int , default=10)
parser.add_argument('--sample_every', type=int , default=200)
parser.add_argument('--checkpoint_every', type=int , default=400)
# GPU or CPU
parser.add_argument('--disable-cuda', action='store_true', help='Disable CUDA')
# GAN training object:
parser.add_argument('--GAN_type', type=str, default='WGANGP', choices=['LSGAN','WGAN','WGANGP'], help='Choose the type of GAN')
# optmizer
parser.add_argument('--optimizer', type=str, default='Adam', choices=['Adam','RMSProp'], help='Choose the type of Optimizer')
return parser
if __name__ == '__main__':
parser = create_parser()
opts = parser.parse_args()
opts.device = None
if not opts.disable_cuda and torch.cuda.is_available():
opts.device = torch.device('cuda')
else:
opts.device = torch.device('cpu')
batch_size = opts.batch_size
print(opts)
main(opts)
|
[
"models.WGANGenerator",
"numpy.random.seed",
"argparse.ArgumentParser",
"torch.autograd.grad",
"torch.device",
"scipy.misc.imsave",
"torch.no_grad",
"os.path.join",
"models.WGANDiscriminator",
"utils.create_dir",
"utils.to_data",
"torch.manual_seed",
"torch.cuda.manual_seed",
"models.WGANGPGenerator",
"torch.cuda.is_available",
"torch.rand",
"models.DCDiscriminator",
"models.DCGenerator",
"warnings.filterwarnings",
"numpy.zeros",
"data_loader.get_emoji_loader",
"models.WGANGPDiscriminator",
"numpy.sqrt"
] |
[((330, 363), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (353, 363), False, 'import warnings\n'), ((809, 829), 'numpy.random.seed', 'np.random.seed', (['SEED'], {}), '(SEED)\n', (823, 829), True, 'import numpy as np\n'), ((830, 853), 'torch.manual_seed', 'torch.manual_seed', (['SEED'], {}), '(SEED)\n', (847, 853), False, 'import torch\n'), ((857, 882), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (880, 882), False, 'import torch\n'), ((888, 916), 'torch.cuda.manual_seed', 'torch.cuda.manual_seed', (['SEED'], {}), '(SEED)\n', (910, 916), False, 'import torch\n'), ((2341, 2383), 'os.path.join', 'os.path.join', (['opts.checkpoint_dir', '"""G.pkl"""'], {}), "(opts.checkpoint_dir, 'G.pkl')\n", (2353, 2383), False, 'import os\n'), ((2397, 2439), 'os.path.join', 'os.path.join', (['opts.checkpoint_dir', '"""D.pkl"""'], {}), "(opts.checkpoint_dir, 'D.pkl')\n", (2409, 2439), False, 'import os\n'), ((2764, 2835), 'numpy.zeros', 'np.zeros', (['(cell_h * nrows, cell_w * ncols, channels)'], {'dtype': 'array.dtype'}), '((cell_h * nrows, cell_w * ncols, channels), dtype=array.dtype)\n', (2772, 2835), True, 'import numpy as np\n'), ((3191, 3222), 'utils.to_data', 'utils.to_data', (['generated_images'], {}), '(generated_images)\n', (3204, 3222), False, 'import utils\n'), ((3401, 3430), 'scipy.misc.imsave', 'scipy.misc.imsave', (['path', 'grid'], {}), '(path, grid)\n', (3418, 3430), False, 'import scipy\n'), ((16255, 16289), 'data_loader.get_emoji_loader', 'get_emoji_loader', (['opts.emoji', 'opts'], {}), '(opts.emoji, opts)\n', (16271, 16289), False, 'from data_loader import get_emoji_loader\n'), ((16342, 16379), 'utils.create_dir', 'utils.create_dir', (['opts.checkpoint_dir'], {}), '(opts.checkpoint_dir)\n', (16358, 16379), False, 'import utils\n'), ((16384, 16417), 'utils.create_dir', 'utils.create_dir', (['opts.sample_dir'], {}), '(opts.sample_dir)\n', (16400, 16417), False, 'import utils\n'), ((16774, 16799), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (16797, 16799), False, 'import argparse\n'), ((1495, 1558), 'models.DCGenerator', 'DCGenerator', ([], {'noise_size': 'opts.noise_size', 'conv_dim': 'opts.conv_dim'}), '(noise_size=opts.noise_size, conv_dim=opts.conv_dim)\n', (1506, 1558), False, 'from models import DCGenerator, DCDiscriminator\n'), ((1571, 1642), 'models.DCDiscriminator', 'DCDiscriminator', ([], {'conv_dim': 'opts.conv_dim', 'batch_norm': '(not opts.disable_bn)'}), '(conv_dim=opts.conv_dim, batch_norm=not opts.disable_bn)\n', (1586, 1642), False, 'from models import DCGenerator, DCDiscriminator\n'), ((18866, 18891), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (18889, 18891), False, 'import torch\n'), ((18915, 18935), 'torch.device', 'torch.device', (['"""cuda"""'], {}), "('cuda')\n", (18927, 18935), False, 'import torch\n'), ((18968, 18987), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (18980, 18987), False, 'import torch\n'), ((1689, 1754), 'models.WGANGenerator', 'WGANGenerator', ([], {'noise_size': 'opts.noise_size', 'conv_dim': 'opts.conv_dim'}), '(noise_size=opts.noise_size, conv_dim=opts.conv_dim)\n', (1702, 1754), False, 'from models import WGANDiscriminator, WGANGenerator\n'), ((1767, 1840), 'models.WGANDiscriminator', 'WGANDiscriminator', ([], {'conv_dim': 'opts.conv_dim', 'batch_norm': '(not opts.disable_bn)'}), '(conv_dim=opts.conv_dim, batch_norm=not opts.disable_bn)\n', (1784, 1840), False, 'from models import WGANDiscriminator, WGANGenerator\n'), ((2672, 2691), 'numpy.sqrt', 'np.sqrt', (['num_images'], {}), '(num_images)\n', (2679, 2691), True, 'import numpy as np\n'), ((13787, 13815), 'torch.rand', 'torch.rand', (['(1)'], {'device': 'device'}), '(1, device=device)\n', (13797, 13815), False, 'import torch\n'), ((1889, 1956), 'models.WGANGPGenerator', 'WGANGPGenerator', ([], {'noise_size': 'opts.noise_size', 'conv_dim': 'opts.conv_dim'}), '(noise_size=opts.noise_size, conv_dim=opts.conv_dim)\n', (1904, 1956), False, 'from models import WGANGPDiscriminator, WGANGPGenerator\n'), ((1969, 2012), 'models.WGANGPDiscriminator', 'WGANGPDiscriminator', ([], {'conv_dim': 'opts.conv_dim'}), '(conv_dim=opts.conv_dim)\n', (1988, 2012), False, 'from models import WGANGPDiscriminator, WGANGPGenerator\n'), ((11036, 11051), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (11049, 11051), False, 'import torch\n'), ((14244, 14387), 'torch.autograd.grad', 'torch.autograd.grad', ([], {'outputs': 'D_interpolates', 'inputs': 'interpolates', 'grad_outputs': 'fake', 'create_graph': '(True)', 'retain_graph': '(True)', 'only_inputs': '(True)'}), '(outputs=D_interpolates, inputs=interpolates,\n grad_outputs=fake, create_graph=True, retain_graph=True, only_inputs=True)\n', (14263, 14387), False, 'import torch\n'), ((15438, 15453), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (15451, 15453), False, 'import torch\n'), ((6013, 6046), 'torch.rand', 'torch.rand', (['batch_size', 'noise_dim'], {}), '(batch_size, noise_dim)\n', (6023, 6046), False, 'import torch\n'), ((6849, 6882), 'torch.rand', 'torch.rand', (['batch_size', 'noise_dim'], {}), '(batch_size, noise_dim)\n', (6859, 6882), False, 'import torch\n'), ((9720, 9753), 'torch.rand', 'torch.rand', (['batch_size', 'noise_dim'], {}), '(batch_size, noise_dim)\n', (9730, 9753), False, 'import torch\n'), ((10561, 10594), 'torch.rand', 'torch.rand', (['batch_size', 'noise_dim'], {}), '(batch_size, noise_dim)\n', (10571, 10594), False, 'import torch\n'), ((13463, 13496), 'torch.rand', 'torch.rand', (['batch_size', 'noise_dim'], {}), '(batch_size, noise_dim)\n', (13473, 13496), False, 'import torch\n'), ((14963, 14996), 'torch.rand', 'torch.rand', (['batch_size', 'noise_dim'], {}), '(batch_size, noise_dim)\n', (14973, 14996), False, 'import torch\n'), ((3863, 3890), 'torch.rand', 'torch.rand', (['batch_size', 'dim'], {}), '(batch_size, dim)\n', (3873, 3890), False, 'import torch\n')]
|
import tensorflow as tf
import os
import numpy as np
import time
def get_timestamp(name):
timestamp = time.asctime().replace(' ', '_').replace(':', '')
unique_name = f'{name}_at_{timestamp}'
return unique_name
def get_callbacks(config, X_train):
logs = config['logs']
unique_dir_name = get_timestamp('tb_logs')
TENSORBOARD_ROOT_LOG_DIR = os.path.join(logs['logs_dir'], logs[TENSORBOARD_ROOT_LOG_DIR], unique_dir_name)
os.makedirs(TENSORBOARD_ROOT_LOG_DIR, exist_ok=True)
tensorboard_cb = tf.keras.callbacks.TensorBoard(log_dir=TENSORBOARD_ROOT_LOG_DIR)
file_writer = tf.summary.create_file_writer(log_dir=TENSORBOARD_ROOT_LOG_DIR)
with file_writer.as_default():
images = np.reshape(X_train[10:30], (-1, 28, 28, 1))
tf.summary.image('20 handwritten digit samples', images, max_outputs=25, step=0)
params = config['params']
early_stopping_cb = tf.keras.callbacks.EarlyStopping(patience=params['patience'],
restore_best_weights=params['restore_best_weights'])
artifacts = config['artifacts']
CKPT_dir = os.path.join(artifacts['artifacts_dir'], artifacts['CHECKPOINT_DIR'])
os.makedirs(CKPT_dir, exist_ok=True)
CKPT_path = os.path.join(CKPT_dir, 'model_ckpt.h5')
checkpoint_cb = tf.keras.callbacks.ModelCheckpoint(CKPT_path, save_best_only=True)
return [tensorboard_cb, early_stopping_cb, checkpoint_cb]
|
[
"time.asctime",
"tensorflow.summary.image",
"os.makedirs",
"tensorflow.keras.callbacks.ModelCheckpoint",
"numpy.reshape",
"tensorflow.summary.create_file_writer",
"tensorflow.keras.callbacks.TensorBoard",
"os.path.join",
"tensorflow.keras.callbacks.EarlyStopping"
] |
[((366, 445), 'os.path.join', 'os.path.join', (["logs['logs_dir']", 'logs[TENSORBOARD_ROOT_LOG_DIR]', 'unique_dir_name'], {}), "(logs['logs_dir'], logs[TENSORBOARD_ROOT_LOG_DIR], unique_dir_name)\n", (378, 445), False, 'import os\n'), ((451, 503), 'os.makedirs', 'os.makedirs', (['TENSORBOARD_ROOT_LOG_DIR'], {'exist_ok': '(True)'}), '(TENSORBOARD_ROOT_LOG_DIR, exist_ok=True)\n', (462, 503), False, 'import os\n'), ((526, 590), 'tensorflow.keras.callbacks.TensorBoard', 'tf.keras.callbacks.TensorBoard', ([], {'log_dir': 'TENSORBOARD_ROOT_LOG_DIR'}), '(log_dir=TENSORBOARD_ROOT_LOG_DIR)\n', (556, 590), True, 'import tensorflow as tf\n'), ((609, 672), 'tensorflow.summary.create_file_writer', 'tf.summary.create_file_writer', ([], {'log_dir': 'TENSORBOARD_ROOT_LOG_DIR'}), '(log_dir=TENSORBOARD_ROOT_LOG_DIR)\n', (638, 672), True, 'import tensorflow as tf\n'), ((914, 1032), 'tensorflow.keras.callbacks.EarlyStopping', 'tf.keras.callbacks.EarlyStopping', ([], {'patience': "params['patience']", 'restore_best_weights': "params['restore_best_weights']"}), "(patience=params['patience'],\n restore_best_weights=params['restore_best_weights'])\n", (946, 1032), True, 'import tensorflow as tf\n'), ((1138, 1207), 'os.path.join', 'os.path.join', (["artifacts['artifacts_dir']", "artifacts['CHECKPOINT_DIR']"], {}), "(artifacts['artifacts_dir'], artifacts['CHECKPOINT_DIR'])\n", (1150, 1207), False, 'import os\n'), ((1212, 1248), 'os.makedirs', 'os.makedirs', (['CKPT_dir'], {'exist_ok': '(True)'}), '(CKPT_dir, exist_ok=True)\n', (1223, 1248), False, 'import os\n'), ((1265, 1304), 'os.path.join', 'os.path.join', (['CKPT_dir', '"""model_ckpt.h5"""'], {}), "(CKPT_dir, 'model_ckpt.h5')\n", (1277, 1304), False, 'import os\n'), ((1325, 1391), 'tensorflow.keras.callbacks.ModelCheckpoint', 'tf.keras.callbacks.ModelCheckpoint', (['CKPT_path'], {'save_best_only': '(True)'}), '(CKPT_path, save_best_only=True)\n', (1359, 1391), True, 'import tensorflow as tf\n'), ((726, 769), 'numpy.reshape', 'np.reshape', (['X_train[10:30]', '(-1, 28, 28, 1)'], {}), '(X_train[10:30], (-1, 28, 28, 1))\n', (736, 769), True, 'import numpy as np\n'), ((778, 863), 'tensorflow.summary.image', 'tf.summary.image', (['"""20 handwritten digit samples"""', 'images'], {'max_outputs': '(25)', 'step': '(0)'}), "('20 handwritten digit samples', images, max_outputs=25, step=0\n )\n", (794, 863), True, 'import tensorflow as tf\n'), ((108, 122), 'time.asctime', 'time.asctime', ([], {}), '()\n', (120, 122), False, 'import time\n')]
|
import pytest
import numpy as np
from spexxy.grid import GridAxis, ValuesGrid
@pytest.fixture()
def number_grid():
# define grid
grid = np.array([
[1, 2, 3, 4, 5],
[3, 4, 5, 6, 7],
[2, 3, 4, 5, 6],
[4, 5, 6, 7, 8]
])
# define axes
ax1 = GridAxis(name='x', values=list(range(grid.shape[1])))
ax2 = GridAxis(name='y', values=list(range(grid.shape[0])))
# combine values
values = {}
for x in ax1.values:
for y in ax2.values:
values[(x, y)] = grid[y, x]
# return new grid
return ValuesGrid([ax1, ax2], values)
|
[
"numpy.array",
"spexxy.grid.ValuesGrid",
"pytest.fixture"
] |
[((82, 98), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (96, 98), False, 'import pytest\n'), ((147, 225), 'numpy.array', 'np.array', (['[[1, 2, 3, 4, 5], [3, 4, 5, 6, 7], [2, 3, 4, 5, 6], [4, 5, 6, 7, 8]]'], {}), '([[1, 2, 3, 4, 5], [3, 4, 5, 6, 7], [2, 3, 4, 5, 6], [4, 5, 6, 7, 8]])\n', (155, 225), True, 'import numpy as np\n'), ((577, 607), 'spexxy.grid.ValuesGrid', 'ValuesGrid', (['[ax1, ax2]', 'values'], {}), '([ax1, ax2], values)\n', (587, 607), False, 'from spexxy.grid import GridAxis, ValuesGrid\n')]
|
###################################################
#
# Script to:
# - Load the images and extract the patches
# - Define the neural network
# - define the training
#
##################################################
import numpy as np
import configparser
from keras.utils import multi_gpu_model
from keras.models import Model
from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout,Add,Convolution2D,merge,Conv3D, MaxPooling3D,Multiply
from keras.optimizers import Adam
from keras.callbacks import ModelCheckpoint, LearningRateScheduler
from keras import backend as K
from keras.utils.vis_utils import plot_model as plot
from keras.optimizers import SGD
import h5py
import sys
sys.path.insert(0, './lib/')
#from help_functions import *
from keras.layers import BatchNormalization,SpatialDropout3D,Reshape,GlobalMaxPooling3D,GlobalAveragePooling2D
#function to obtain data for training/testing (validation)
#from extract_patches import get_data_training
from keras.layers.core import Dropout, Activation
from keras import backend as K
import tensorflow as tf
print(K.backend())
from data_feed import *
from keras import optimizers
#from pre_processing import my_PreProc
import math
import sys
sys.setrecursionlimit(4000)
#Define the neural network
def focal_loss(gamma=2,alpha=0.75):
def focal_loss_fixed(y_true,y_pred):
pt_1=tf.where(tf.equal(y_true,1),y_pred,tf.ones_like(y_pred))
pt_0=tf.where(tf.equal(y_true,0),y_pred,tf.zeros_like(y_pred))
return -K.sum(alpha*K.pow(1.-pt_1,gamma)*K.log(pt_1))-K.sum((1-alpha)*K.pow(pt_0,gamma)*K.log(1.-pt_0))
return focal_loss_fixed
def block_2_conv(input,num_filter):
conv1=Conv2D(num_filter,(3,3),strides=(1,1),padding='same',data_format='channels_first')(input)
conv1_bn=BatchNormalization(axis=1)(conv1)
conv1_relu=Activation('relu')(conv1_bn)
conv2=Conv2D(num_filter,(3,3),strides=(1,1),padding='same',data_format='channels_first')(conv1_relu)
conv2_bn=BatchNormalization(axis=1)(conv2)
conv2_add=Add()([input,conv2_bn])
conv2_relu=Activation('relu')(conv2_add)
return conv2_relu
def block_2_conv3D(input,num_filter):
conv1 = Conv3D(num_filter, (3, 3,3), strides=(1, 1,1), padding='same', data_format='channels_first')(input)
conv1_bn = BatchNormalization(axis=1)(conv1)
conv1_relu = Activation('relu')(conv1_bn)
conv2 = Conv3D(num_filter, (3, 3,3), strides=(1, 1,1), padding='same', data_format='channels_first')(conv1_relu)
conv2_bn = BatchNormalization(axis=1)(conv2)
conv2_add = Add()([input, conv2_bn])
conv2_relu = Activation('relu')(conv2_add)
return conv2_relu
def attention_block(input,iter,depth):
global_pool=GlobalMaxPooling3D(data_format='channels_first')(input)
global_pool1=Reshape((depth,1,1,1))(global_pool)
conv_1x1=Conv3D(depth,(1,1,1),padding='same',data_format='channels_first')(global_pool1)
relu_out=Activation('relu')(conv_1x1)
conv_2x1=Conv3D(depth,(1,1,1),strides=(1,1,1),padding='same',data_format='channels_first')(relu_out)
sigmoid_out=Activation('sigmoid')(conv_2x1)
concat1=sigmoid_out
#print("***********1")
#print(concat1.shape)
for i in range(4-1):
concat1=concatenate([concat1,sigmoid_out],axis=2)
concat2=concat1
for j in range(iter-1):
concat2=concatenate([concat2,concat1],axis=3)
concat3=concat2
for k in range(iter-1):
concat3=concatenate([concat3,concat2],axis=4)
#print("************2")
#print(concat3.shape)
out=Multiply()([input,concat3])
return out
def saliency_map_attention_block(input,depth):
conv_1x1=Conv3D(depth,(1,1,1),padding='same',data_format='channels_first')(input)
relu_out=Activation('relu')(conv_1x1)
conv_2x1=Conv3D(depth,(1,1,1),padding='same',data_format='channels_first')(relu_out)
sigmoid_out=Activation('sigmoid')(conv_2x1)
out1=Multiply()([input,sigmoid_out])
out=Add()([input,out1])
return out
def channel_attnetion_block(low_input,high_input,depth,size):
input=concatenate([low_input,high_input],axis=1)
global_pool=GlobalAveragePooling2D(data_format='channels_first')(input)
global_pool1 = Reshape((2*depth, 1, 1))(global_pool)
conv_1x1 = Conv2D(depth, (1, 1), padding='same', data_format='channels_first')(global_pool1)
relu_out = Activation('relu')(conv_1x1)
conv_2x1 = Conv2D(depth, (1, 1), strides=(1, 1), padding='same', data_format='channels_first')(relu_out)
sigmoid_out = Activation('sigmoid')(conv_2x1)
concat1 = sigmoid_out
for i in range(size-1):
concat1=concatenate([concat1,sigmoid_out],axis=2)
concat2=concat1
for j in range(size-1):
concat2=concatenate([concat2,concat1],axis=3)
out1 = Multiply()([low_input, concat2])
out2=Add()([out1,high_input])
return out2
# F1 score: harmonic mean of precision and sensitivity DICE = 2*TP/(2*TP + FN + FP)
def DiceCoef(y_true, y_pred):
y_true_f = K.flatten(y_true)
y_pred_f = K.flatten(y_pred)
intersection = K.sum(y_true_f*y_pred_f)
return (2.*intersection)/(K.sum(y_true_f) + K.sum(y_pred_f) + 0.00001)
def DiceCoefLoss(y_true, y_pred):
return -DiceCoef(y_true, y_pred)
def get_unet3D_new_4_fram_2(n_ch,frame,patch_height,patch_width):
inputs = Input(shape=(n_ch, frame,patch_height, patch_width))
conv0 = Conv3D(8, (1, 1,1), padding='same')(inputs)
conv1 = block_2_conv3D(conv0, 8)
## channel attention
#out1=attention_block(conv1,512,8)
###特征输出
conv1_3d_2d = Conv3D(8, (4, 1, 1), strides=(1, 1, 1), data_format='channels_first')(conv1)
#conv1_3d_2d = Conv3D(8, (4, 1, 1), strides=(1, 1, 1), data_format='channels_first')(out1)
conv1_trans_2d = Reshape((8, 512, 512))(conv1_3d_2d)
conv1_1 = Conv3D(16, (2, 2,2), strides=(1,2,2),padding='same', data_format='channels_first')(conv1)
conv1_1 = BatchNormalization(axis=1)(conv1_1)
conv1_1 = Activation('relu')(conv1_1)
conv2 = block_2_conv3D(conv1_1, 16)
## channel attention
#out2 = attention_block(conv2, 256, 16)
###特征输出
conv2_3d_2d = Conv3D(16, (4, 1, 1), strides=(1, 1, 1), data_format='channels_first')(conv2)
#conv2_3d_2d = Conv3D(16, (4, 1, 1), strides=(1, 1, 1), data_format='channels_first')(out2)
conv2_trans_2d = Reshape((16, 256, 256))(conv2_3d_2d)
conv2_1 = Conv3D(32, (2, 2,2), strides=(1,2,2), padding='same',data_format='channels_first')(conv2)
conv2_1 = BatchNormalization(axis=1)(conv2_1)
conv2_1 = Activation('relu')(conv2_1)
conv3 = block_2_conv3D(conv2_1, 32)
## channel attention
#out3 = attention_block(conv3, 128, 32)
###特征输出
conv3_3d_2d = Conv3D(32, (4, 1, 1), strides=(1, 1, 1), data_format='channels_first')(conv3)
#conv3_3d_2d = Conv3D(32, (4, 1, 1), strides=(1, 1, 1), data_format='channels_first')(out3)
conv3_trans_2d = Reshape((32, 128, 128))(conv3_3d_2d)
conv3_1 = Conv3D(64, (2, 2,2), strides=(1,2,2),padding='same', data_format='channels_first')(conv3)
conv3_1 = BatchNormalization(axis=1)(conv3_1)
conv3_1 = Activation('relu')(conv3_1)
conv4 = block_2_conv3D(conv3_1, 64)
##saliency_map
out4_1=saliency_map_attention_block(conv4,64)
## channel attention
#out4 = attention_block(conv4, 64, 64)
out4 = attention_block(out4_1, 64, 64)
###特征输出
#conv4_3d_2d = Conv3D(64, (4, 1, 1), strides=(1, 1, 1), data_format='channels_first')(conv4)
conv4_3d_2d = Conv3D(64, (4, 1, 1), strides=(1, 1, 1), data_format='channels_first')(out4)
conv4_trans_2d = Reshape((64, 64, 64))(conv4_3d_2d)
conv4_1 = Conv3D(128, (2, 2,2), strides=(1,2,2), padding='same',data_format='channels_first')(conv4)
conv4_1 = BatchNormalization(axis=1)(conv4_1)
conv4_1 = Activation('relu')(conv4_1)
conv5 = block_2_conv3D(conv4_1, 128)
## channel attention
out5 = attention_block(conv5, 32, 128)
###特征输出
#conv5_3d_2d = Conv3D(128, (4, 1, 1), strides=(1, 1, 1), data_format='channels_first')(conv5)
conv5_3d_2d = Conv3D(128, (4, 1, 1), strides=(1, 1, 1), data_format='channels_first')(out5)
conv5_trans_2d = Reshape((128, 32, 32))(conv5_3d_2d)
conv5_dropout = SpatialDropout3D(0.5,data_format='channels_first')(conv5)
conv5_1 = Conv3D(256, (2, 2,2), strides=(1,2,2), padding='same',data_format='channels_first')(conv5_dropout)
conv5_1 = BatchNormalization(axis=1)(conv5_1)
conv5_1 = Activation('relu')(conv5_1)
conv6 = block_2_conv3D(conv5_1, 256)
## channel attention
out6 = attention_block(conv6, 16, 256)
###特征输出
#conv6_3d_2d=Conv3D(256,(4,1,1),strides=(1,1,1),data_format='channels_first')(conv6)
conv6_3d_2d = Conv3D(256, (4, 1, 1), strides=(1, 1, 1), data_format='channels_first')(out6)
conv6_trans_2d=Reshape((256,16,16))(conv6_3d_2d)
conv6_dropout = SpatialDropout3D(0.5,data_format='channels_first')(conv6)
conv6_1 = Conv3D(512, (2, 2,2), strides=(1,2,2), padding='same',data_format='channels_first')(conv6_dropout)
conv6_1 = BatchNormalization(axis=1)(conv6_1)
conv6_1 = Activation('relu')(conv6_1)
conv3d_2d=Conv3D(512,(4,1,1),strides=(1,1,1),data_format='channels_first')(conv6_1)
#print(conv3d_2d.shape)
conv_trans_2d=Reshape((512,8,8))(conv3d_2d)
up1 = UpSampling2D(size=(2, 2))(conv_trans_2d)
up1_1 = Conv2D(256, (2, 2), strides=1, padding='same', data_format='channels_first')(up1)
up1_1 = BatchNormalization(axis=1)(up1_1)
up1_1 = Activation('relu')(up1_1)
up1_2 = concatenate([ conv6_trans_2d , up1_1], axis=1)
up1_3 = block_2_conv(up1_2, 512)
up2 = UpSampling2D(size=(2, 2))(up1_3)
up2_1 = Conv2D(128, (2, 2), strides=1, padding='same', data_format='channels_first')(up2)
up2_1 = BatchNormalization(axis=1)(up2_1)
up2_1 = Activation('relu')(up2_1)
up2_2 = concatenate([conv5_trans_2d, up2_1], axis=1)
up2_3 = block_2_conv(up2_2, 256)
up3 = UpSampling2D(size=(2, 2))(up2_3)
up3_1 = Conv2D(64, (2, 2), strides=1, padding='same', data_format='channels_first')(up3)
up3_1 = BatchNormalization(axis=1)(up3_1)
up3_1 = Activation('relu')(up3_1)
up3_2 = concatenate([conv4_trans_2d, up3_1], axis=1)
up3_3 = block_2_conv(up3_2, 128)
up4 = UpSampling2D(size=(2, 2))(up3_3)
up4_1 = Conv2D(32, (2, 2), strides=1, padding='same', data_format='channels_first')(up4)
up4_1 = BatchNormalization(axis=1)(up4_1)
up4_1 = Activation('relu')(up4_1)
up4_2 = concatenate([conv3_trans_2d, up4_1], axis=1)
up4_3 = block_2_conv(up4_2, 64)
up5 = UpSampling2D(size=(2, 2))(up4_3)
up5_1 = Conv2D(16, (2, 2), strides=1, padding='same', data_format='channels_first')(up5)
up5_1 = BatchNormalization(axis=1)(up5_1)
up5_1 = Activation('relu')(up5_1)
up5_2 = concatenate([conv2_trans_2d, up5_1], axis=1)
up5_3 = block_2_conv(up5_2, 32)
up6 = UpSampling2D(size=(2, 2))(up5_3)
up6_1 = Conv2D(8, (2, 2), strides=1, padding='same', data_format='channels_first')(up6)
up6_1 = BatchNormalization(axis=1)(up6_1)
up6_1 = Activation('relu')(up6_1)
up6_2 = concatenate([conv1_trans_2d, up6_1], axis=1)
up6_3 = block_2_conv(up6_2, 16)
outputs = Conv2D(1, (1, 1), activation='sigmoid')(up6_3)
model = Model(inputs=inputs, outputs=outputs)
#model.compile(optimizer='sgd', loss=DiceCoefLoss, metrics=[DiceCoef])
return model
def get_unet3D_new_4_fram_2_new(n_ch,frame,patch_height,patch_width):
inputs = Input(shape=(n_ch, frame,patch_height, patch_width))
conv0 = Conv3D(8, (1, 1,1), padding='same')(inputs)
conv1 = block_2_conv3D(conv0, 8)
## channel attention
#out1=attention_block(conv1,512,8)
###特征输出
conv1_3d_2d = Conv3D(8, (4, 1, 1), strides=(1, 1, 1), data_format='channels_first')(conv1)
#conv1_3d_2d = Conv3D(8, (4, 1, 1), strides=(1, 1, 1), data_format='channels_first')(out1)
conv1_trans_2d = Reshape((8, 512, 512))(conv1_3d_2d)
conv1_1 = Conv3D(16, (2, 2,2), strides=(1,2,2),padding='same', data_format='channels_first')(conv1)
conv1_1 = BatchNormalization(axis=1)(conv1_1)
conv1_1 = Activation('relu')(conv1_1)
conv2 = block_2_conv3D(conv1_1, 16)
## channel attention
#out2 = attention_block(conv2, 256, 16)
###特征输出
conv2_3d_2d = Conv3D(16, (4, 1, 1), strides=(1, 1, 1), data_format='channels_first')(conv2)
#conv2_3d_2d = Conv3D(16, (4, 1, 1), strides=(1, 1, 1), data_format='channels_first')(out2)
conv2_trans_2d = Reshape((16, 256, 256))(conv2_3d_2d)
conv2_1 = Conv3D(32, (2, 2,2), strides=(1,2,2), padding='same',data_format='channels_first')(conv2)
conv2_1 = BatchNormalization(axis=1)(conv2_1)
conv2_1 = Activation('relu')(conv2_1)
conv3 = block_2_conv3D(conv2_1, 32)
## channel attention
#out3 = attention_block(conv3, 128, 32)
###特征输出
conv3_3d_2d = Conv3D(32, (4, 1, 1), strides=(1, 1, 1), data_format='channels_first')(conv3)
#conv3_3d_2d = Conv3D(32, (4, 1, 1), strides=(1, 1, 1), data_format='channels_first')(out3)
conv3_trans_2d = Reshape((32, 128, 128))(conv3_3d_2d)
conv3_1 = Conv3D(64, (2, 2,2), strides=(1,2,2),padding='same', data_format='channels_first')(conv3)
conv3_1 = BatchNormalization(axis=1)(conv3_1)
conv3_1 = Activation('relu')(conv3_1)
conv4 = block_2_conv3D(conv3_1, 64)
##saliency_map
#out4_1=saliency_map_attention_block(conv4,64)
## channel attention
#out4 = attention_block(conv4, 64, 64)
#out4 = attention_block(out4_1, 64, 64)
###特征输出
#conv4_3d_2d = Conv3D(64, (4, 1, 1), strides=(1, 1, 1), data_format='channels_first')(conv4)
conv4_3d_2d = Conv3D(64, (4, 1, 1), strides=(1, 1, 1), data_format='channels_first')(conv4)
conv4_trans_2d = Reshape((64, 64, 64))(conv4_3d_2d)
conv4_1 = Conv3D(128, (2, 2,2), strides=(1,2,2), padding='same',data_format='channels_first')(conv4)
conv4_1 = BatchNormalization(axis=1)(conv4_1)
conv4_1 = Activation('relu')(conv4_1)
conv5 = block_2_conv3D(conv4_1, 128)
## channel attention
#out5 = attention_block(conv5, 32, 128)
###特征输出
#conv5_3d_2d = Conv3D(128, (4, 1, 1), strides=(1, 1, 1), data_format='channels_first')(conv5)
conv5_3d_2d = Conv3D(128, (4, 1, 1), strides=(1, 1, 1), data_format='channels_first')(conv5)
conv5_trans_2d = Reshape((128, 32, 32))(conv5_3d_2d)
conv5_dropout = SpatialDropout3D(0.5,data_format='channels_first')(conv5)
conv5_1 = Conv3D(256, (2, 2,2), strides=(1,2,2), padding='same',data_format='channels_first')(conv5_dropout)
conv5_1 = BatchNormalization(axis=1)(conv5_1)
conv5_1 = Activation('relu')(conv5_1)
conv6 = block_2_conv3D(conv5_1, 256)
## channel attention
out6 = attention_block(conv6, 16, 256)
###特征输出
#conv6_3d_2d=Conv3D(256,(4,1,1),strides=(1,1,1),data_format='channels_first')(conv6)
conv6_3d_2d = Conv3D(256, (4, 1, 1), strides=(1, 1, 1), data_format='channels_first')(out6)
conv6_trans_2d=Reshape((256,16,16))(conv6_3d_2d)
conv6_dropout = SpatialDropout3D(0.5,data_format='channels_first')(conv6)
conv6_1 = Conv3D(512, (2, 2,2), strides=(1,2,2), padding='same',data_format='channels_first')(conv6_dropout)
conv6_1 = BatchNormalization(axis=1)(conv6_1)
conv6_1 = Activation('relu')(conv6_1)
conv3d_2d=Conv3D(512,(4,1,1),strides=(1,1,1),data_format='channels_first')(conv6_1)
#print(conv3d_2d.shape)
conv_trans_2d=Reshape((512,8,8))(conv3d_2d)
up1 = UpSampling2D(size=(2, 2))(conv_trans_2d)
up1_1 = Conv2D(256, (2, 2), strides=1, padding='same', data_format='channels_first')(up1)
up1_1 = BatchNormalization(axis=1)(up1_1)
up1_1 = Activation('relu')(up1_1)
up1_2=channel_attnetion_block(conv6_trans_2d,up1_1,256,16)
#up1_2 = concatenate([ conv6_trans_2d , up1_1], axis=1)
up1_3 = block_2_conv(up1_2, 256)
up2 = UpSampling2D(size=(2, 2))(up1_3)
up2_1 = Conv2D(128, (2, 2), strides=1, padding='same', data_format='channels_first')(up2)
up2_1 = BatchNormalization(axis=1)(up2_1)
up2_1 = Activation('relu')(up2_1)
up2_2=channel_attnetion_block(conv5_trans_2d,up2_1,128,32)
#up2_2 = concatenate([conv5_trans_2d, up2_1], axis=1)
up2_3 = block_2_conv(up2_2, 128)
up3 = UpSampling2D(size=(2, 2))(up2_3)
up3_1 = Conv2D(64, (2, 2), strides=1, padding='same', data_format='channels_first')(up3)
up3_1 = BatchNormalization(axis=1)(up3_1)
up3_1 = Activation('relu')(up3_1)
up3_2=channel_attnetion_block(conv4_trans_2d,up3_1,64,64)
#up3_2 = concatenate([conv4_trans_2d, up3_1], axis=1)
up3_3 = block_2_conv(up3_2, 64)
up4 = UpSampling2D(size=(2, 2))(up3_3)
up4_1 = Conv2D(32, (2, 2), strides=1, padding='same', data_format='channels_first')(up4)
up4_1 = BatchNormalization(axis=1)(up4_1)
up4_1 = Activation('relu')(up4_1)
up4_2=channel_attnetion_block(conv3_trans_2d,up4_1,32,128)
#up4_2 = concatenate([conv3_trans_2d, up4_1], axis=1)
up4_3 = block_2_conv(up4_2, 32)
up5 = UpSampling2D(size=(2, 2))(up4_3)
up5_1 = Conv2D(16, (2, 2), strides=1, padding='same', data_format='channels_first')(up5)
up5_1 = BatchNormalization(axis=1)(up5_1)
up5_1 = Activation('relu')(up5_1)
up5_2=channel_attnetion_block(conv2_trans_2d,up5_1,16,256)
# up5_2 = concatenate([conv2_trans_2d, up5_1], axis=1)
up5_3 = block_2_conv(up5_2, 16)
up6 = UpSampling2D(size=(2, 2))(up5_3)
up6_1 = Conv2D(8, (2, 2), strides=1, padding='same', data_format='channels_first')(up6)
up6_1 = BatchNormalization(axis=1)(up6_1)
up6_1 = Activation('relu')(up6_1)
up6_2=channel_attnetion_block(conv1_trans_2d,up6_1,8,512)
#up6_2 = concatenate([conv1_trans_2d, up6_1], axis=1)
up6_3 = block_2_conv(up6_2, 8)
outputs = Conv2D(1, (1, 1), activation='sigmoid')(up6_3)
model = Model(inputs=inputs, outputs=outputs)
#model.compile(optimizer='sgd', loss=DiceCoefLoss, metrics=[DiceCoef])
return model
#========= Load settings from Config file
config = configparser.RawConfigParser()
config.read('configuration.txt')
#patch to the datasets
path_data = config.get('data paths', 'path_local')
#Experiment name
name_experiment = config.get('experiment name', 'name')
#training settings
N_epochs = int(config.get('training settings', 'N_epochs'))
_batchSize = int(config.get('training settings', 'batch_size'))
n_ch=1
frame=4
patch_height=512
patch_width=512
model = get_unet3D_new_4_fram_2_new(n_ch, frame,patch_height, patch_width) #the U-net model
## data parallel
#parallel_model=multi_gpu_model(model,gpus=2)
parallel_model=model
sgd= optimizers.SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
parallel_model.compile(optimizer=sgd, loss=DiceCoefLoss, metrics=[DiceCoef])
#parallel_model.compile(optimizer='sgd', loss=[focal_loss(gamma=2,alpha=0.25)], metrics=[DiceCoef])
print ("Check: final output of the network:")
print (parallel_model.output_shape)
#plot(model, to_file='./'+name_experiment+'/'+name_experiment + '_model.png') #check how the model looks like
json_string = model.to_json()
open('./'+name_experiment+'/'+name_experiment +'_architecture.json', 'w').write(json_string)
new_train_imgs_original = path_data + config.get('data paths', 'train_imgs_original')
new_train_imgs_groundTruth=path_data + config.get('data paths', 'train_groundTruth')
train_data_ori= h5py.File(new_train_imgs_original,'r')
train_data_gt=h5py.File(new_train_imgs_groundTruth,'r')
train_imgs_original= np.array(train_data_ori['image'])
train_groundTruth=np.array(train_data_gt['image'])
train_imgs = train_imgs_original/np.max(train_imgs_original)
train_masks = train_groundTruth/np.max(train_groundTruth)
#check masks are within 0-1
#assert(np.min(train_masks)==0 and np.max(train_masks)==1)
print("imgs max value:")
print(np.max(train_imgs))
print("imgs min value")
print(np.min(train_imgs))
print("label max value")
print(np.max(train_masks))
print("label min value")
print(np.min(train_masks))
print ("\ntrain images/masks shape:")
print (train_imgs.shape)
print ("train images range (min-max): " +str(np.min(train_imgs)) +' - '+str(np.max(train_imgs)))
print ("train masks are within 0-1\n")
#============ Training ==================================
checkpoint_test = ModelCheckpoint(filepath='./'+name_experiment+'/'+name_experiment +'_best_weights.h5', monitor='val_loss', save_best_only=True,save_weights_only=True) #save at each epoch if the validation decreased
checkpoint = ModelCheckpoint(filepath='./'+name_experiment+'/'+name_experiment + "bestTrainWeight" + ".h5", monitor='loss', save_best_only=True, save_weights_only=True)
def step_decay(epoch):
lrate = 0.01 #the initial learning rate (by default in keras)
if epoch%200==0:
lrate=lrate*0.1
return lrate
lrate_drop = LearningRateScheduler(step_decay)
keepPctOriginal = 0.5
hflip = True
vflip = True
iter_times=250
num=train_imgs_original.shape[0]
np.random.seed(0)
index=list(np.random.permutation(num))
_X_train=train_imgs[index][0:174]
_Y_train=train_masks[index][0:174]
print(_X_train.shape)
print(_Y_train.shape)
_X_vali=train_imgs[index][174:219]
_Y_vali=train_masks[index][174:219]
print(_X_vali.shape)
print(_Y_vali.shape)
def ImgGenerator():
for image in train_generator(_X_train, _Y_train,_batchSize, iter_times, _keepPctOriginal=0.5,
_intensity=INTENSITY_FACTOR, _hflip=True, _vflip=True):
yield image
def valiGenerator():
for image in validation_generator(_X_vali, _Y_vali,_batchSize):
yield image
stepsPerEpoch = math.ceil((num-40) / _batchSize)
validationSteps = math.ceil(40 / _batchSize)
history = parallel_model.fit_generator(ImgGenerator(), verbose=2, workers=1,
validation_data=valiGenerator(),
steps_per_epoch=stepsPerEpoch, epochs=N_epochs,
validation_steps=validationSteps,
callbacks=[lrate_drop,checkpoint,checkpoint_test])
model.summary()
#========== Save and test the last model ===================
model.save_weights('./'+name_experiment+'/'+name_experiment +'_last_weights.h5', overwrite=True)
|
[
"numpy.random.seed",
"tensorflow.zeros_like",
"keras.models.Model",
"keras.layers.Input",
"keras.callbacks.LearningRateScheduler",
"keras.layers.concatenate",
"sys.setrecursionlimit",
"keras.layers.Reshape",
"keras.backend.pow",
"keras.optimizers.SGD",
"keras.backend.flatten",
"configparser.RawConfigParser",
"keras.layers.core.Activation",
"keras.layers.GlobalAveragePooling2D",
"numpy.max",
"keras.layers.GlobalMaxPooling3D",
"keras.layers.Multiply",
"tensorflow.equal",
"h5py.File",
"math.ceil",
"keras.callbacks.ModelCheckpoint",
"keras.backend.backend",
"tensorflow.ones_like",
"numpy.min",
"keras.layers.Conv2D",
"keras.layers.UpSampling2D",
"numpy.random.permutation",
"keras.layers.SpatialDropout3D",
"keras.layers.BatchNormalization",
"keras.backend.sum",
"sys.path.insert",
"keras.layers.Add",
"keras.layers.Conv3D",
"keras.backend.log",
"numpy.array"
] |
[((759, 787), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""./lib/"""'], {}), "(0, './lib/')\n", (774, 787), False, 'import sys\n'), ((1289, 1316), 'sys.setrecursionlimit', 'sys.setrecursionlimit', (['(4000)'], {}), '(4000)\n', (1310, 1316), False, 'import sys\n'), ((18411, 18441), 'configparser.RawConfigParser', 'configparser.RawConfigParser', ([], {}), '()\n', (18439, 18441), False, 'import configparser\n'), ((19020, 19085), 'keras.optimizers.SGD', 'optimizers.SGD', ([], {'lr': '(0.01)', 'decay': '(1e-06)', 'momentum': '(0.9)', 'nesterov': '(True)'}), '(lr=0.01, decay=1e-06, momentum=0.9, nesterov=True)\n', (19034, 19085), False, 'from keras import optimizers\n'), ((19788, 19827), 'h5py.File', 'h5py.File', (['new_train_imgs_original', '"""r"""'], {}), "(new_train_imgs_original, 'r')\n", (19797, 19827), False, 'import h5py\n'), ((19842, 19884), 'h5py.File', 'h5py.File', (['new_train_imgs_groundTruth', '"""r"""'], {}), "(new_train_imgs_groundTruth, 'r')\n", (19851, 19884), False, 'import h5py\n'), ((19908, 19941), 'numpy.array', 'np.array', (["train_data_ori['image']"], {}), "(train_data_ori['image'])\n", (19916, 19941), True, 'import numpy as np\n'), ((19961, 19993), 'numpy.array', 'np.array', (["train_data_gt['image']"], {}), "(train_data_gt['image'])\n", (19969, 19993), True, 'import numpy as np\n'), ((20703, 20869), 'keras.callbacks.ModelCheckpoint', 'ModelCheckpoint', ([], {'filepath': "('./' + name_experiment + '/' + name_experiment + '_best_weights.h5')", 'monitor': '"""val_loss"""', 'save_best_only': '(True)', 'save_weights_only': '(True)'}), "(filepath='./' + name_experiment + '/' + name_experiment +\n '_best_weights.h5', monitor='val_loss', save_best_only=True,\n save_weights_only=True)\n", (20718, 20869), False, 'from keras.callbacks import ModelCheckpoint, LearningRateScheduler\n'), ((20916, 21085), 'keras.callbacks.ModelCheckpoint', 'ModelCheckpoint', ([], {'filepath': "('./' + name_experiment + '/' + name_experiment + 'bestTrainWeight' + '.h5')", 'monitor': '"""loss"""', 'save_best_only': '(True)', 'save_weights_only': '(True)'}), "(filepath='./' + name_experiment + '/' + name_experiment +\n 'bestTrainWeight' + '.h5', monitor='loss', save_best_only=True,\n save_weights_only=True)\n", (20931, 21085), False, 'from keras.callbacks import ModelCheckpoint, LearningRateScheduler\n'), ((21257, 21290), 'keras.callbacks.LearningRateScheduler', 'LearningRateScheduler', (['step_decay'], {}), '(step_decay)\n', (21278, 21290), False, 'from keras.callbacks import ModelCheckpoint, LearningRateScheduler\n'), ((21395, 21412), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (21409, 21412), True, 'import numpy as np\n'), ((22056, 22090), 'math.ceil', 'math.ceil', (['((num - 40) / _batchSize)'], {}), '((num - 40) / _batchSize)\n', (22065, 22090), False, 'import math\n'), ((22108, 22134), 'math.ceil', 'math.ceil', (['(40 / _batchSize)'], {}), '(40 / _batchSize)\n', (22117, 22134), False, 'import math\n'), ((1155, 1166), 'keras.backend.backend', 'K.backend', ([], {}), '()\n', (1164, 1166), True, 'from keras import backend as K\n'), ((4155, 4199), 'keras.layers.concatenate', 'concatenate', (['[low_input, high_input]'], {'axis': '(1)'}), '([low_input, high_input], axis=1)\n', (4166, 4199), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((5095, 5112), 'keras.backend.flatten', 'K.flatten', (['y_true'], {}), '(y_true)\n', (5104, 5112), True, 'from keras import backend as K\n'), ((5126, 5143), 'keras.backend.flatten', 'K.flatten', (['y_pred'], {}), '(y_pred)\n', (5135, 5143), True, 'from keras import backend as K\n'), ((5161, 5187), 'keras.backend.sum', 'K.sum', (['(y_true_f * y_pred_f)'], {}), '(y_true_f * y_pred_f)\n', (5166, 5187), True, 'from keras import backend as K\n'), ((5419, 5472), 'keras.layers.Input', 'Input', ([], {'shape': '(n_ch, frame, patch_height, patch_width)'}), '(shape=(n_ch, frame, patch_height, patch_width))\n', (5424, 5472), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((9733, 9777), 'keras.layers.concatenate', 'concatenate', (['[conv6_trans_2d, up1_1]'], {'axis': '(1)'}), '([conv6_trans_2d, up1_1], axis=1)\n', (9744, 9777), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((10058, 10102), 'keras.layers.concatenate', 'concatenate', (['[conv5_trans_2d, up2_1]'], {'axis': '(1)'}), '([conv5_trans_2d, up2_1], axis=1)\n', (10069, 10102), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((10380, 10424), 'keras.layers.concatenate', 'concatenate', (['[conv4_trans_2d, up3_1]'], {'axis': '(1)'}), '([conv4_trans_2d, up3_1], axis=1)\n', (10391, 10424), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((10702, 10746), 'keras.layers.concatenate', 'concatenate', (['[conv3_trans_2d, up4_1]'], {'axis': '(1)'}), '([conv3_trans_2d, up4_1], axis=1)\n', (10713, 10746), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((11023, 11067), 'keras.layers.concatenate', 'concatenate', (['[conv2_trans_2d, up5_1]'], {'axis': '(1)'}), '([conv2_trans_2d, up5_1], axis=1)\n', (11034, 11067), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((11343, 11387), 'keras.layers.concatenate', 'concatenate', (['[conv1_trans_2d, up6_1]'], {'axis': '(1)'}), '([conv1_trans_2d, up6_1], axis=1)\n', (11354, 11387), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((11504, 11541), 'keras.models.Model', 'Model', ([], {'inputs': 'inputs', 'outputs': 'outputs'}), '(inputs=inputs, outputs=outputs)\n', (11509, 11541), False, 'from keras.models import Model\n'), ((11728, 11781), 'keras.layers.Input', 'Input', ([], {'shape': '(n_ch, frame, patch_height, patch_width)'}), '(shape=(n_ch, frame, patch_height, patch_width))\n', (11733, 11781), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((18206, 18243), 'keras.models.Model', 'Model', ([], {'inputs': 'inputs', 'outputs': 'outputs'}), '(inputs=inputs, outputs=outputs)\n', (18211, 18243), False, 'from keras.models import Model\n'), ((20030, 20057), 'numpy.max', 'np.max', (['train_imgs_original'], {}), '(train_imgs_original)\n', (20036, 20057), True, 'import numpy as np\n'), ((20091, 20116), 'numpy.max', 'np.max', (['train_groundTruth'], {}), '(train_groundTruth)\n', (20097, 20116), True, 'import numpy as np\n'), ((20241, 20259), 'numpy.max', 'np.max', (['train_imgs'], {}), '(train_imgs)\n', (20247, 20259), True, 'import numpy as np\n'), ((20293, 20311), 'numpy.min', 'np.min', (['train_imgs'], {}), '(train_imgs)\n', (20299, 20311), True, 'import numpy as np\n'), ((20346, 20365), 'numpy.max', 'np.max', (['train_masks'], {}), '(train_masks)\n', (20352, 20365), True, 'import numpy as np\n'), ((20400, 20419), 'numpy.min', 'np.min', (['train_masks'], {}), '(train_masks)\n', (20406, 20419), True, 'import numpy as np\n'), ((21425, 21451), 'numpy.random.permutation', 'np.random.permutation', (['num'], {}), '(num)\n', (21446, 21451), True, 'import numpy as np\n'), ((1757, 1850), 'keras.layers.Conv2D', 'Conv2D', (['num_filter', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'data_format': '"""channels_first"""'}), "(num_filter, (3, 3), strides=(1, 1), padding='same', data_format=\n 'channels_first')\n", (1763, 1850), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((1861, 1887), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'axis': '(1)'}), '(axis=1)\n', (1879, 1887), False, 'from keras.layers import BatchNormalization, SpatialDropout3D, Reshape, GlobalMaxPooling3D, GlobalAveragePooling2D\n'), ((1911, 1929), 'keras.layers.core.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (1921, 1929), False, 'from keras.layers.core import Dropout, Activation\n'), ((1951, 2044), 'keras.layers.Conv2D', 'Conv2D', (['num_filter', '(3, 3)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'data_format': '"""channels_first"""'}), "(num_filter, (3, 3), strides=(1, 1), padding='same', data_format=\n 'channels_first')\n", (1957, 2044), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((2060, 2086), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'axis': '(1)'}), '(axis=1)\n', (2078, 2086), False, 'from keras.layers import BatchNormalization, SpatialDropout3D, Reshape, GlobalMaxPooling3D, GlobalAveragePooling2D\n'), ((2109, 2114), 'keras.layers.Add', 'Add', ([], {}), '()\n', (2112, 2114), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((2149, 2167), 'keras.layers.core.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (2159, 2167), False, 'from keras.layers.core import Dropout, Activation\n'), ((2256, 2354), 'keras.layers.Conv3D', 'Conv3D', (['num_filter', '(3, 3, 3)'], {'strides': '(1, 1, 1)', 'padding': '"""same"""', 'data_format': '"""channels_first"""'}), "(num_filter, (3, 3, 3), strides=(1, 1, 1), padding='same',\n data_format='channels_first')\n", (2262, 2354), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((2372, 2398), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'axis': '(1)'}), '(axis=1)\n', (2390, 2398), False, 'from keras.layers import BatchNormalization, SpatialDropout3D, Reshape, GlobalMaxPooling3D, GlobalAveragePooling2D\n'), ((2424, 2442), 'keras.layers.core.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (2434, 2442), False, 'from keras.layers.core import Dropout, Activation\n'), ((2466, 2564), 'keras.layers.Conv3D', 'Conv3D', (['num_filter', '(3, 3, 3)'], {'strides': '(1, 1, 1)', 'padding': '"""same"""', 'data_format': '"""channels_first"""'}), "(num_filter, (3, 3, 3), strides=(1, 1, 1), padding='same',\n data_format='channels_first')\n", (2472, 2564), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((2587, 2613), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'axis': '(1)'}), '(axis=1)\n', (2605, 2613), False, 'from keras.layers import BatchNormalization, SpatialDropout3D, Reshape, GlobalMaxPooling3D, GlobalAveragePooling2D\n'), ((2638, 2643), 'keras.layers.Add', 'Add', ([], {}), '()\n', (2641, 2643), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((2681, 2699), 'keras.layers.core.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (2691, 2699), False, 'from keras.layers.core import Dropout, Activation\n'), ((2791, 2839), 'keras.layers.GlobalMaxPooling3D', 'GlobalMaxPooling3D', ([], {'data_format': '"""channels_first"""'}), "(data_format='channels_first')\n", (2809, 2839), False, 'from keras.layers import BatchNormalization, SpatialDropout3D, Reshape, GlobalMaxPooling3D, GlobalAveragePooling2D\n'), ((2865, 2890), 'keras.layers.Reshape', 'Reshape', (['(depth, 1, 1, 1)'], {}), '((depth, 1, 1, 1))\n', (2872, 2890), False, 'from keras.layers import BatchNormalization, SpatialDropout3D, Reshape, GlobalMaxPooling3D, GlobalAveragePooling2D\n'), ((2915, 2985), 'keras.layers.Conv3D', 'Conv3D', (['depth', '(1, 1, 1)'], {'padding': '"""same"""', 'data_format': '"""channels_first"""'}), "(depth, (1, 1, 1), padding='same', data_format='channels_first')\n", (2921, 2985), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((3009, 3027), 'keras.layers.core.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (3019, 3027), False, 'from keras.layers.core import Dropout, Activation\n'), ((3052, 3146), 'keras.layers.Conv3D', 'Conv3D', (['depth', '(1, 1, 1)'], {'strides': '(1, 1, 1)', 'padding': '"""same"""', 'data_format': '"""channels_first"""'}), "(depth, (1, 1, 1), strides=(1, 1, 1), padding='same', data_format=\n 'channels_first')\n", (3058, 3146), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((3161, 3182), 'keras.layers.core.Activation', 'Activation', (['"""sigmoid"""'], {}), "('sigmoid')\n", (3171, 3182), False, 'from keras.layers.core import Dropout, Activation\n'), ((3316, 3359), 'keras.layers.concatenate', 'concatenate', (['[concat1, sigmoid_out]'], {'axis': '(2)'}), '([concat1, sigmoid_out], axis=2)\n', (3327, 3359), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((3425, 3464), 'keras.layers.concatenate', 'concatenate', (['[concat2, concat1]'], {'axis': '(3)'}), '([concat2, concat1], axis=3)\n', (3436, 3464), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((3530, 3569), 'keras.layers.concatenate', 'concatenate', (['[concat3, concat2]'], {'axis': '(4)'}), '([concat3, concat2], axis=4)\n', (3541, 3569), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((3633, 3643), 'keras.layers.Multiply', 'Multiply', ([], {}), '()\n', (3641, 3643), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((3739, 3809), 'keras.layers.Conv3D', 'Conv3D', (['depth', '(1, 1, 1)'], {'padding': '"""same"""', 'data_format': '"""channels_first"""'}), "(depth, (1, 1, 1), padding='same', data_format='channels_first')\n", (3745, 3809), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((3826, 3844), 'keras.layers.core.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (3836, 3844), False, 'from keras.layers.core import Dropout, Activation\n'), ((3869, 3939), 'keras.layers.Conv3D', 'Conv3D', (['depth', '(1, 1, 1)'], {'padding': '"""same"""', 'data_format': '"""channels_first"""'}), "(depth, (1, 1, 1), padding='same', data_format='channels_first')\n", (3875, 3939), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((3962, 3983), 'keras.layers.core.Activation', 'Activation', (['"""sigmoid"""'], {}), "('sigmoid')\n", (3972, 3983), False, 'from keras.layers.core import Dropout, Activation\n'), ((4004, 4014), 'keras.layers.Multiply', 'Multiply', ([], {}), '()\n', (4012, 4014), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((4045, 4050), 'keras.layers.Add', 'Add', ([], {}), '()\n', (4048, 4050), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((4215, 4267), 'keras.layers.GlobalAveragePooling2D', 'GlobalAveragePooling2D', ([], {'data_format': '"""channels_first"""'}), "(data_format='channels_first')\n", (4237, 4267), False, 'from keras.layers import BatchNormalization, SpatialDropout3D, Reshape, GlobalMaxPooling3D, GlobalAveragePooling2D\n'), ((4295, 4321), 'keras.layers.Reshape', 'Reshape', (['(2 * depth, 1, 1)'], {}), '((2 * depth, 1, 1))\n', (4302, 4321), False, 'from keras.layers import BatchNormalization, SpatialDropout3D, Reshape, GlobalMaxPooling3D, GlobalAveragePooling2D\n'), ((4349, 4416), 'keras.layers.Conv2D', 'Conv2D', (['depth', '(1, 1)'], {'padding': '"""same"""', 'data_format': '"""channels_first"""'}), "(depth, (1, 1), padding='same', data_format='channels_first')\n", (4355, 4416), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((4447, 4465), 'keras.layers.core.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (4457, 4465), False, 'from keras.layers.core import Dropout, Activation\n'), ((4492, 4580), 'keras.layers.Conv2D', 'Conv2D', (['depth', '(1, 1)'], {'strides': '(1, 1)', 'padding': '"""same"""', 'data_format': '"""channels_first"""'}), "(depth, (1, 1), strides=(1, 1), padding='same', data_format=\n 'channels_first')\n", (4498, 4580), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((4605, 4626), 'keras.layers.core.Activation', 'Activation', (['"""sigmoid"""'], {}), "('sigmoid')\n", (4615, 4626), False, 'from keras.layers.core import Dropout, Activation\n'), ((4710, 4753), 'keras.layers.concatenate', 'concatenate', (['[concat1, sigmoid_out]'], {'axis': '(2)'}), '([concat1, sigmoid_out], axis=2)\n', (4721, 4753), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((4819, 4858), 'keras.layers.concatenate', 'concatenate', (['[concat2, concat1]'], {'axis': '(3)'}), '([concat2, concat1], axis=3)\n', (4830, 4858), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((4869, 4879), 'keras.layers.Multiply', 'Multiply', ([], {}), '()\n', (4877, 4879), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((4912, 4917), 'keras.layers.Add', 'Add', ([], {}), '()\n', (4915, 4917), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((5485, 5521), 'keras.layers.Conv3D', 'Conv3D', (['(8)', '(1, 1, 1)'], {'padding': '"""same"""'}), "(8, (1, 1, 1), padding='same')\n", (5491, 5521), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((5669, 5738), 'keras.layers.Conv3D', 'Conv3D', (['(8)', '(4, 1, 1)'], {'strides': '(1, 1, 1)', 'data_format': '"""channels_first"""'}), "(8, (4, 1, 1), strides=(1, 1, 1), data_format='channels_first')\n", (5675, 5738), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((5864, 5886), 'keras.layers.Reshape', 'Reshape', (['(8, 512, 512)'], {}), '((8, 512, 512))\n', (5871, 5886), False, 'from keras.layers import BatchNormalization, SpatialDropout3D, Reshape, GlobalMaxPooling3D, GlobalAveragePooling2D\n'), ((5917, 6008), 'keras.layers.Conv3D', 'Conv3D', (['(16)', '(2, 2, 2)'], {'strides': '(1, 2, 2)', 'padding': '"""same"""', 'data_format': '"""channels_first"""'}), "(16, (2, 2, 2), strides=(1, 2, 2), padding='same', data_format=\n 'channels_first')\n", (5923, 6008), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((6022, 6048), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'axis': '(1)'}), '(axis=1)\n', (6040, 6048), False, 'from keras.layers import BatchNormalization, SpatialDropout3D, Reshape, GlobalMaxPooling3D, GlobalAveragePooling2D\n'), ((6073, 6091), 'keras.layers.core.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (6083, 6091), False, 'from keras.layers.core import Dropout, Activation\n'), ((6253, 6323), 'keras.layers.Conv3D', 'Conv3D', (['(16)', '(4, 1, 1)'], {'strides': '(1, 1, 1)', 'data_format': '"""channels_first"""'}), "(16, (4, 1, 1), strides=(1, 1, 1), data_format='channels_first')\n", (6259, 6323), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((6450, 6473), 'keras.layers.Reshape', 'Reshape', (['(16, 256, 256)'], {}), '((16, 256, 256))\n', (6457, 6473), False, 'from keras.layers import BatchNormalization, SpatialDropout3D, Reshape, GlobalMaxPooling3D, GlobalAveragePooling2D\n'), ((6504, 6595), 'keras.layers.Conv3D', 'Conv3D', (['(32)', '(2, 2, 2)'], {'strides': '(1, 2, 2)', 'padding': '"""same"""', 'data_format': '"""channels_first"""'}), "(32, (2, 2, 2), strides=(1, 2, 2), padding='same', data_format=\n 'channels_first')\n", (6510, 6595), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((6609, 6635), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'axis': '(1)'}), '(axis=1)\n', (6627, 6635), False, 'from keras.layers import BatchNormalization, SpatialDropout3D, Reshape, GlobalMaxPooling3D, GlobalAveragePooling2D\n'), ((6660, 6678), 'keras.layers.core.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (6670, 6678), False, 'from keras.layers.core import Dropout, Activation\n'), ((6840, 6910), 'keras.layers.Conv3D', 'Conv3D', (['(32)', '(4, 1, 1)'], {'strides': '(1, 1, 1)', 'data_format': '"""channels_first"""'}), "(32, (4, 1, 1), strides=(1, 1, 1), data_format='channels_first')\n", (6846, 6910), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((7037, 7060), 'keras.layers.Reshape', 'Reshape', (['(32, 128, 128)'], {}), '((32, 128, 128))\n', (7044, 7060), False, 'from keras.layers import BatchNormalization, SpatialDropout3D, Reshape, GlobalMaxPooling3D, GlobalAveragePooling2D\n'), ((7091, 7182), 'keras.layers.Conv3D', 'Conv3D', (['(64)', '(2, 2, 2)'], {'strides': '(1, 2, 2)', 'padding': '"""same"""', 'data_format': '"""channels_first"""'}), "(64, (2, 2, 2), strides=(1, 2, 2), padding='same', data_format=\n 'channels_first')\n", (7097, 7182), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((7196, 7222), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'axis': '(1)'}), '(axis=1)\n', (7214, 7222), False, 'from keras.layers import BatchNormalization, SpatialDropout3D, Reshape, GlobalMaxPooling3D, GlobalAveragePooling2D\n'), ((7247, 7265), 'keras.layers.core.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (7257, 7265), False, 'from keras.layers.core import Dropout, Activation\n'), ((7639, 7709), 'keras.layers.Conv3D', 'Conv3D', (['(64)', '(4, 1, 1)'], {'strides': '(1, 1, 1)', 'data_format': '"""channels_first"""'}), "(64, (4, 1, 1), strides=(1, 1, 1), data_format='channels_first')\n", (7645, 7709), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((7738, 7759), 'keras.layers.Reshape', 'Reshape', (['(64, 64, 64)'], {}), '((64, 64, 64))\n', (7745, 7759), False, 'from keras.layers import BatchNormalization, SpatialDropout3D, Reshape, GlobalMaxPooling3D, GlobalAveragePooling2D\n'), ((7790, 7882), 'keras.layers.Conv3D', 'Conv3D', (['(128)', '(2, 2, 2)'], {'strides': '(1, 2, 2)', 'padding': '"""same"""', 'data_format': '"""channels_first"""'}), "(128, (2, 2, 2), strides=(1, 2, 2), padding='same', data_format=\n 'channels_first')\n", (7796, 7882), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((7896, 7922), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'axis': '(1)'}), '(axis=1)\n', (7914, 7922), False, 'from keras.layers import BatchNormalization, SpatialDropout3D, Reshape, GlobalMaxPooling3D, GlobalAveragePooling2D\n'), ((7947, 7965), 'keras.layers.core.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (7957, 7965), False, 'from keras.layers.core import Dropout, Activation\n'), ((8226, 8297), 'keras.layers.Conv3D', 'Conv3D', (['(128)', '(4, 1, 1)'], {'strides': '(1, 1, 1)', 'data_format': '"""channels_first"""'}), "(128, (4, 1, 1), strides=(1, 1, 1), data_format='channels_first')\n", (8232, 8297), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((8326, 8348), 'keras.layers.Reshape', 'Reshape', (['(128, 32, 32)'], {}), '((128, 32, 32))\n', (8333, 8348), False, 'from keras.layers import BatchNormalization, SpatialDropout3D, Reshape, GlobalMaxPooling3D, GlobalAveragePooling2D\n'), ((8385, 8436), 'keras.layers.SpatialDropout3D', 'SpatialDropout3D', (['(0.5)'], {'data_format': '"""channels_first"""'}), "(0.5, data_format='channels_first')\n", (8401, 8436), False, 'from keras.layers import BatchNormalization, SpatialDropout3D, Reshape, GlobalMaxPooling3D, GlobalAveragePooling2D\n'), ((8458, 8550), 'keras.layers.Conv3D', 'Conv3D', (['(256)', '(2, 2, 2)'], {'strides': '(1, 2, 2)', 'padding': '"""same"""', 'data_format': '"""channels_first"""'}), "(256, (2, 2, 2), strides=(1, 2, 2), padding='same', data_format=\n 'channels_first')\n", (8464, 8550), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((8572, 8598), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'axis': '(1)'}), '(axis=1)\n', (8590, 8598), False, 'from keras.layers import BatchNormalization, SpatialDropout3D, Reshape, GlobalMaxPooling3D, GlobalAveragePooling2D\n'), ((8623, 8641), 'keras.layers.core.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (8633, 8641), False, 'from keras.layers.core import Dropout, Activation\n'), ((8893, 8964), 'keras.layers.Conv3D', 'Conv3D', (['(256)', '(4, 1, 1)'], {'strides': '(1, 1, 1)', 'data_format': '"""channels_first"""'}), "(256, (4, 1, 1), strides=(1, 1, 1), data_format='channels_first')\n", (8899, 8964), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((8991, 9013), 'keras.layers.Reshape', 'Reshape', (['(256, 16, 16)'], {}), '((256, 16, 16))\n', (8998, 9013), False, 'from keras.layers import BatchNormalization, SpatialDropout3D, Reshape, GlobalMaxPooling3D, GlobalAveragePooling2D\n'), ((9048, 9099), 'keras.layers.SpatialDropout3D', 'SpatialDropout3D', (['(0.5)'], {'data_format': '"""channels_first"""'}), "(0.5, data_format='channels_first')\n", (9064, 9099), False, 'from keras.layers import BatchNormalization, SpatialDropout3D, Reshape, GlobalMaxPooling3D, GlobalAveragePooling2D\n'), ((9121, 9213), 'keras.layers.Conv3D', 'Conv3D', (['(512)', '(2, 2, 2)'], {'strides': '(1, 2, 2)', 'padding': '"""same"""', 'data_format': '"""channels_first"""'}), "(512, (2, 2, 2), strides=(1, 2, 2), padding='same', data_format=\n 'channels_first')\n", (9127, 9213), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((9235, 9261), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'axis': '(1)'}), '(axis=1)\n', (9253, 9261), False, 'from keras.layers import BatchNormalization, SpatialDropout3D, Reshape, GlobalMaxPooling3D, GlobalAveragePooling2D\n'), ((9286, 9304), 'keras.layers.core.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (9296, 9304), False, 'from keras.layers.core import Dropout, Activation\n'), ((9331, 9402), 'keras.layers.Conv3D', 'Conv3D', (['(512)', '(4, 1, 1)'], {'strides': '(1, 1, 1)', 'data_format': '"""channels_first"""'}), "(512, (4, 1, 1), strides=(1, 1, 1), data_format='channels_first')\n", (9337, 9402), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((9453, 9473), 'keras.layers.Reshape', 'Reshape', (['(512, 8, 8)'], {}), '((512, 8, 8))\n', (9460, 9473), False, 'from keras.layers import BatchNormalization, SpatialDropout3D, Reshape, GlobalMaxPooling3D, GlobalAveragePooling2D\n'), ((9498, 9523), 'keras.layers.UpSampling2D', 'UpSampling2D', ([], {'size': '(2, 2)'}), '(size=(2, 2))\n', (9510, 9523), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((9552, 9628), 'keras.layers.Conv2D', 'Conv2D', (['(256)', '(2, 2)'], {'strides': '(1)', 'padding': '"""same"""', 'data_format': '"""channels_first"""'}), "(256, (2, 2), strides=1, padding='same', data_format='channels_first')\n", (9558, 9628), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((9647, 9673), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'axis': '(1)'}), '(axis=1)\n', (9665, 9673), False, 'from keras.layers import BatchNormalization, SpatialDropout3D, Reshape, GlobalMaxPooling3D, GlobalAveragePooling2D\n'), ((9694, 9712), 'keras.layers.core.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (9704, 9712), False, 'from keras.layers.core import Dropout, Activation\n'), ((9831, 9856), 'keras.layers.UpSampling2D', 'UpSampling2D', ([], {'size': '(2, 2)'}), '(size=(2, 2))\n', (9843, 9856), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((9877, 9953), 'keras.layers.Conv2D', 'Conv2D', (['(128)', '(2, 2)'], {'strides': '(1)', 'padding': '"""same"""', 'data_format': '"""channels_first"""'}), "(128, (2, 2), strides=1, padding='same', data_format='channels_first')\n", (9883, 9953), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((9972, 9998), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'axis': '(1)'}), '(axis=1)\n', (9990, 9998), False, 'from keras.layers import BatchNormalization, SpatialDropout3D, Reshape, GlobalMaxPooling3D, GlobalAveragePooling2D\n'), ((10019, 10037), 'keras.layers.core.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (10029, 10037), False, 'from keras.layers.core import Dropout, Activation\n'), ((10154, 10179), 'keras.layers.UpSampling2D', 'UpSampling2D', ([], {'size': '(2, 2)'}), '(size=(2, 2))\n', (10166, 10179), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((10200, 10275), 'keras.layers.Conv2D', 'Conv2D', (['(64)', '(2, 2)'], {'strides': '(1)', 'padding': '"""same"""', 'data_format': '"""channels_first"""'}), "(64, (2, 2), strides=1, padding='same', data_format='channels_first')\n", (10206, 10275), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((10294, 10320), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'axis': '(1)'}), '(axis=1)\n', (10312, 10320), False, 'from keras.layers import BatchNormalization, SpatialDropout3D, Reshape, GlobalMaxPooling3D, GlobalAveragePooling2D\n'), ((10341, 10359), 'keras.layers.core.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (10351, 10359), False, 'from keras.layers.core import Dropout, Activation\n'), ((10476, 10501), 'keras.layers.UpSampling2D', 'UpSampling2D', ([], {'size': '(2, 2)'}), '(size=(2, 2))\n', (10488, 10501), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((10522, 10597), 'keras.layers.Conv2D', 'Conv2D', (['(32)', '(2, 2)'], {'strides': '(1)', 'padding': '"""same"""', 'data_format': '"""channels_first"""'}), "(32, (2, 2), strides=1, padding='same', data_format='channels_first')\n", (10528, 10597), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((10616, 10642), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'axis': '(1)'}), '(axis=1)\n', (10634, 10642), False, 'from keras.layers import BatchNormalization, SpatialDropout3D, Reshape, GlobalMaxPooling3D, GlobalAveragePooling2D\n'), ((10663, 10681), 'keras.layers.core.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (10673, 10681), False, 'from keras.layers.core import Dropout, Activation\n'), ((10797, 10822), 'keras.layers.UpSampling2D', 'UpSampling2D', ([], {'size': '(2, 2)'}), '(size=(2, 2))\n', (10809, 10822), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((10843, 10918), 'keras.layers.Conv2D', 'Conv2D', (['(16)', '(2, 2)'], {'strides': '(1)', 'padding': '"""same"""', 'data_format': '"""channels_first"""'}), "(16, (2, 2), strides=1, padding='same', data_format='channels_first')\n", (10849, 10918), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((10937, 10963), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'axis': '(1)'}), '(axis=1)\n', (10955, 10963), False, 'from keras.layers import BatchNormalization, SpatialDropout3D, Reshape, GlobalMaxPooling3D, GlobalAveragePooling2D\n'), ((10984, 11002), 'keras.layers.core.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (10994, 11002), False, 'from keras.layers.core import Dropout, Activation\n'), ((11118, 11143), 'keras.layers.UpSampling2D', 'UpSampling2D', ([], {'size': '(2, 2)'}), '(size=(2, 2))\n', (11130, 11143), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((11164, 11238), 'keras.layers.Conv2D', 'Conv2D', (['(8)', '(2, 2)'], {'strides': '(1)', 'padding': '"""same"""', 'data_format': '"""channels_first"""'}), "(8, (2, 2), strides=1, padding='same', data_format='channels_first')\n", (11170, 11238), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((11257, 11283), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'axis': '(1)'}), '(axis=1)\n', (11275, 11283), False, 'from keras.layers import BatchNormalization, SpatialDropout3D, Reshape, GlobalMaxPooling3D, GlobalAveragePooling2D\n'), ((11304, 11322), 'keras.layers.core.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (11314, 11322), False, 'from keras.layers.core import Dropout, Activation\n'), ((11442, 11481), 'keras.layers.Conv2D', 'Conv2D', (['(1)', '(1, 1)'], {'activation': '"""sigmoid"""'}), "(1, (1, 1), activation='sigmoid')\n", (11448, 11481), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((11794, 11830), 'keras.layers.Conv3D', 'Conv3D', (['(8)', '(1, 1, 1)'], {'padding': '"""same"""'}), "(8, (1, 1, 1), padding='same')\n", (11800, 11830), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((11978, 12047), 'keras.layers.Conv3D', 'Conv3D', (['(8)', '(4, 1, 1)'], {'strides': '(1, 1, 1)', 'data_format': '"""channels_first"""'}), "(8, (4, 1, 1), strides=(1, 1, 1), data_format='channels_first')\n", (11984, 12047), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((12173, 12195), 'keras.layers.Reshape', 'Reshape', (['(8, 512, 512)'], {}), '((8, 512, 512))\n', (12180, 12195), False, 'from keras.layers import BatchNormalization, SpatialDropout3D, Reshape, GlobalMaxPooling3D, GlobalAveragePooling2D\n'), ((12226, 12317), 'keras.layers.Conv3D', 'Conv3D', (['(16)', '(2, 2, 2)'], {'strides': '(1, 2, 2)', 'padding': '"""same"""', 'data_format': '"""channels_first"""'}), "(16, (2, 2, 2), strides=(1, 2, 2), padding='same', data_format=\n 'channels_first')\n", (12232, 12317), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((12331, 12357), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'axis': '(1)'}), '(axis=1)\n', (12349, 12357), False, 'from keras.layers import BatchNormalization, SpatialDropout3D, Reshape, GlobalMaxPooling3D, GlobalAveragePooling2D\n'), ((12382, 12400), 'keras.layers.core.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (12392, 12400), False, 'from keras.layers.core import Dropout, Activation\n'), ((12562, 12632), 'keras.layers.Conv3D', 'Conv3D', (['(16)', '(4, 1, 1)'], {'strides': '(1, 1, 1)', 'data_format': '"""channels_first"""'}), "(16, (4, 1, 1), strides=(1, 1, 1), data_format='channels_first')\n", (12568, 12632), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((12759, 12782), 'keras.layers.Reshape', 'Reshape', (['(16, 256, 256)'], {}), '((16, 256, 256))\n', (12766, 12782), False, 'from keras.layers import BatchNormalization, SpatialDropout3D, Reshape, GlobalMaxPooling3D, GlobalAveragePooling2D\n'), ((12813, 12904), 'keras.layers.Conv3D', 'Conv3D', (['(32)', '(2, 2, 2)'], {'strides': '(1, 2, 2)', 'padding': '"""same"""', 'data_format': '"""channels_first"""'}), "(32, (2, 2, 2), strides=(1, 2, 2), padding='same', data_format=\n 'channels_first')\n", (12819, 12904), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((12918, 12944), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'axis': '(1)'}), '(axis=1)\n', (12936, 12944), False, 'from keras.layers import BatchNormalization, SpatialDropout3D, Reshape, GlobalMaxPooling3D, GlobalAveragePooling2D\n'), ((12969, 12987), 'keras.layers.core.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (12979, 12987), False, 'from keras.layers.core import Dropout, Activation\n'), ((13149, 13219), 'keras.layers.Conv3D', 'Conv3D', (['(32)', '(4, 1, 1)'], {'strides': '(1, 1, 1)', 'data_format': '"""channels_first"""'}), "(32, (4, 1, 1), strides=(1, 1, 1), data_format='channels_first')\n", (13155, 13219), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((13346, 13369), 'keras.layers.Reshape', 'Reshape', (['(32, 128, 128)'], {}), '((32, 128, 128))\n', (13353, 13369), False, 'from keras.layers import BatchNormalization, SpatialDropout3D, Reshape, GlobalMaxPooling3D, GlobalAveragePooling2D\n'), ((13400, 13491), 'keras.layers.Conv3D', 'Conv3D', (['(64)', '(2, 2, 2)'], {'strides': '(1, 2, 2)', 'padding': '"""same"""', 'data_format': '"""channels_first"""'}), "(64, (2, 2, 2), strides=(1, 2, 2), padding='same', data_format=\n 'channels_first')\n", (13406, 13491), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((13505, 13531), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'axis': '(1)'}), '(axis=1)\n', (13523, 13531), False, 'from keras.layers import BatchNormalization, SpatialDropout3D, Reshape, GlobalMaxPooling3D, GlobalAveragePooling2D\n'), ((13556, 13574), 'keras.layers.core.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (13566, 13574), False, 'from keras.layers.core import Dropout, Activation\n'), ((13950, 14020), 'keras.layers.Conv3D', 'Conv3D', (['(64)', '(4, 1, 1)'], {'strides': '(1, 1, 1)', 'data_format': '"""channels_first"""'}), "(64, (4, 1, 1), strides=(1, 1, 1), data_format='channels_first')\n", (13956, 14020), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((14050, 14071), 'keras.layers.Reshape', 'Reshape', (['(64, 64, 64)'], {}), '((64, 64, 64))\n', (14057, 14071), False, 'from keras.layers import BatchNormalization, SpatialDropout3D, Reshape, GlobalMaxPooling3D, GlobalAveragePooling2D\n'), ((14102, 14194), 'keras.layers.Conv3D', 'Conv3D', (['(128)', '(2, 2, 2)'], {'strides': '(1, 2, 2)', 'padding': '"""same"""', 'data_format': '"""channels_first"""'}), "(128, (2, 2, 2), strides=(1, 2, 2), padding='same', data_format=\n 'channels_first')\n", (14108, 14194), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((14208, 14234), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'axis': '(1)'}), '(axis=1)\n', (14226, 14234), False, 'from keras.layers import BatchNormalization, SpatialDropout3D, Reshape, GlobalMaxPooling3D, GlobalAveragePooling2D\n'), ((14259, 14277), 'keras.layers.core.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (14269, 14277), False, 'from keras.layers.core import Dropout, Activation\n'), ((14539, 14610), 'keras.layers.Conv3D', 'Conv3D', (['(128)', '(4, 1, 1)'], {'strides': '(1, 1, 1)', 'data_format': '"""channels_first"""'}), "(128, (4, 1, 1), strides=(1, 1, 1), data_format='channels_first')\n", (14545, 14610), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((14640, 14662), 'keras.layers.Reshape', 'Reshape', (['(128, 32, 32)'], {}), '((128, 32, 32))\n', (14647, 14662), False, 'from keras.layers import BatchNormalization, SpatialDropout3D, Reshape, GlobalMaxPooling3D, GlobalAveragePooling2D\n'), ((14699, 14750), 'keras.layers.SpatialDropout3D', 'SpatialDropout3D', (['(0.5)'], {'data_format': '"""channels_first"""'}), "(0.5, data_format='channels_first')\n", (14715, 14750), False, 'from keras.layers import BatchNormalization, SpatialDropout3D, Reshape, GlobalMaxPooling3D, GlobalAveragePooling2D\n'), ((14772, 14864), 'keras.layers.Conv3D', 'Conv3D', (['(256)', '(2, 2, 2)'], {'strides': '(1, 2, 2)', 'padding': '"""same"""', 'data_format': '"""channels_first"""'}), "(256, (2, 2, 2), strides=(1, 2, 2), padding='same', data_format=\n 'channels_first')\n", (14778, 14864), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((14886, 14912), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'axis': '(1)'}), '(axis=1)\n', (14904, 14912), False, 'from keras.layers import BatchNormalization, SpatialDropout3D, Reshape, GlobalMaxPooling3D, GlobalAveragePooling2D\n'), ((14937, 14955), 'keras.layers.core.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (14947, 14955), False, 'from keras.layers.core import Dropout, Activation\n'), ((15207, 15278), 'keras.layers.Conv3D', 'Conv3D', (['(256)', '(4, 1, 1)'], {'strides': '(1, 1, 1)', 'data_format': '"""channels_first"""'}), "(256, (4, 1, 1), strides=(1, 1, 1), data_format='channels_first')\n", (15213, 15278), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((15305, 15327), 'keras.layers.Reshape', 'Reshape', (['(256, 16, 16)'], {}), '((256, 16, 16))\n', (15312, 15327), False, 'from keras.layers import BatchNormalization, SpatialDropout3D, Reshape, GlobalMaxPooling3D, GlobalAveragePooling2D\n'), ((15362, 15413), 'keras.layers.SpatialDropout3D', 'SpatialDropout3D', (['(0.5)'], {'data_format': '"""channels_first"""'}), "(0.5, data_format='channels_first')\n", (15378, 15413), False, 'from keras.layers import BatchNormalization, SpatialDropout3D, Reshape, GlobalMaxPooling3D, GlobalAveragePooling2D\n'), ((15435, 15527), 'keras.layers.Conv3D', 'Conv3D', (['(512)', '(2, 2, 2)'], {'strides': '(1, 2, 2)', 'padding': '"""same"""', 'data_format': '"""channels_first"""'}), "(512, (2, 2, 2), strides=(1, 2, 2), padding='same', data_format=\n 'channels_first')\n", (15441, 15527), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((15549, 15575), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'axis': '(1)'}), '(axis=1)\n', (15567, 15575), False, 'from keras.layers import BatchNormalization, SpatialDropout3D, Reshape, GlobalMaxPooling3D, GlobalAveragePooling2D\n'), ((15600, 15618), 'keras.layers.core.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (15610, 15618), False, 'from keras.layers.core import Dropout, Activation\n'), ((15645, 15716), 'keras.layers.Conv3D', 'Conv3D', (['(512)', '(4, 1, 1)'], {'strides': '(1, 1, 1)', 'data_format': '"""channels_first"""'}), "(512, (4, 1, 1), strides=(1, 1, 1), data_format='channels_first')\n", (15651, 15716), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((15767, 15787), 'keras.layers.Reshape', 'Reshape', (['(512, 8, 8)'], {}), '((512, 8, 8))\n', (15774, 15787), False, 'from keras.layers import BatchNormalization, SpatialDropout3D, Reshape, GlobalMaxPooling3D, GlobalAveragePooling2D\n'), ((15812, 15837), 'keras.layers.UpSampling2D', 'UpSampling2D', ([], {'size': '(2, 2)'}), '(size=(2, 2))\n', (15824, 15837), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((15866, 15942), 'keras.layers.Conv2D', 'Conv2D', (['(256)', '(2, 2)'], {'strides': '(1)', 'padding': '"""same"""', 'data_format': '"""channels_first"""'}), "(256, (2, 2), strides=1, padding='same', data_format='channels_first')\n", (15872, 15942), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((15961, 15987), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'axis': '(1)'}), '(axis=1)\n', (15979, 15987), False, 'from keras.layers import BatchNormalization, SpatialDropout3D, Reshape, GlobalMaxPooling3D, GlobalAveragePooling2D\n'), ((16008, 16026), 'keras.layers.core.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (16018, 16026), False, 'from keras.layers.core import Dropout, Activation\n'), ((16212, 16237), 'keras.layers.UpSampling2D', 'UpSampling2D', ([], {'size': '(2, 2)'}), '(size=(2, 2))\n', (16224, 16237), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((16258, 16334), 'keras.layers.Conv2D', 'Conv2D', (['(128)', '(2, 2)'], {'strides': '(1)', 'padding': '"""same"""', 'data_format': '"""channels_first"""'}), "(128, (2, 2), strides=1, padding='same', data_format='channels_first')\n", (16264, 16334), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((16353, 16379), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'axis': '(1)'}), '(axis=1)\n', (16371, 16379), False, 'from keras.layers import BatchNormalization, SpatialDropout3D, Reshape, GlobalMaxPooling3D, GlobalAveragePooling2D\n'), ((16400, 16418), 'keras.layers.core.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (16410, 16418), False, 'from keras.layers.core import Dropout, Activation\n'), ((16600, 16625), 'keras.layers.UpSampling2D', 'UpSampling2D', ([], {'size': '(2, 2)'}), '(size=(2, 2))\n', (16612, 16625), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((16646, 16721), 'keras.layers.Conv2D', 'Conv2D', (['(64)', '(2, 2)'], {'strides': '(1)', 'padding': '"""same"""', 'data_format': '"""channels_first"""'}), "(64, (2, 2), strides=1, padding='same', data_format='channels_first')\n", (16652, 16721), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((16740, 16766), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'axis': '(1)'}), '(axis=1)\n', (16758, 16766), False, 'from keras.layers import BatchNormalization, SpatialDropout3D, Reshape, GlobalMaxPooling3D, GlobalAveragePooling2D\n'), ((16787, 16805), 'keras.layers.core.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (16797, 16805), False, 'from keras.layers.core import Dropout, Activation\n'), ((16985, 17010), 'keras.layers.UpSampling2D', 'UpSampling2D', ([], {'size': '(2, 2)'}), '(size=(2, 2))\n', (16997, 17010), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((17031, 17106), 'keras.layers.Conv2D', 'Conv2D', (['(32)', '(2, 2)'], {'strides': '(1)', 'padding': '"""same"""', 'data_format': '"""channels_first"""'}), "(32, (2, 2), strides=1, padding='same', data_format='channels_first')\n", (17037, 17106), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((17125, 17151), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'axis': '(1)'}), '(axis=1)\n', (17143, 17151), False, 'from keras.layers import BatchNormalization, SpatialDropout3D, Reshape, GlobalMaxPooling3D, GlobalAveragePooling2D\n'), ((17172, 17190), 'keras.layers.core.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (17182, 17190), False, 'from keras.layers.core import Dropout, Activation\n'), ((17371, 17396), 'keras.layers.UpSampling2D', 'UpSampling2D', ([], {'size': '(2, 2)'}), '(size=(2, 2))\n', (17383, 17396), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((17417, 17492), 'keras.layers.Conv2D', 'Conv2D', (['(16)', '(2, 2)'], {'strides': '(1)', 'padding': '"""same"""', 'data_format': '"""channels_first"""'}), "(16, (2, 2), strides=1, padding='same', data_format='channels_first')\n", (17423, 17492), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((17511, 17537), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'axis': '(1)'}), '(axis=1)\n', (17529, 17537), False, 'from keras.layers import BatchNormalization, SpatialDropout3D, Reshape, GlobalMaxPooling3D, GlobalAveragePooling2D\n'), ((17558, 17576), 'keras.layers.core.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (17568, 17576), False, 'from keras.layers.core import Dropout, Activation\n'), ((17757, 17782), 'keras.layers.UpSampling2D', 'UpSampling2D', ([], {'size': '(2, 2)'}), '(size=(2, 2))\n', (17769, 17782), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((17803, 17877), 'keras.layers.Conv2D', 'Conv2D', (['(8)', '(2, 2)'], {'strides': '(1)', 'padding': '"""same"""', 'data_format': '"""channels_first"""'}), "(8, (2, 2), strides=1, padding='same', data_format='channels_first')\n", (17809, 17877), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((17896, 17922), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'axis': '(1)'}), '(axis=1)\n', (17914, 17922), False, 'from keras.layers import BatchNormalization, SpatialDropout3D, Reshape, GlobalMaxPooling3D, GlobalAveragePooling2D\n'), ((17943, 17961), 'keras.layers.core.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (17953, 17961), False, 'from keras.layers.core import Dropout, Activation\n'), ((18144, 18183), 'keras.layers.Conv2D', 'Conv2D', (['(1)', '(1, 1)'], {'activation': '"""sigmoid"""'}), "(1, (1, 1), activation='sigmoid')\n", (18150, 18183), False, 'from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, UpSampling2D, Reshape, core, Dropout, Add, Convolution2D, merge, Conv3D, MaxPooling3D, Multiply\n'), ((1447, 1466), 'tensorflow.equal', 'tf.equal', (['y_true', '(1)'], {}), '(y_true, 1)\n', (1455, 1466), True, 'import tensorflow as tf\n'), ((1473, 1493), 'tensorflow.ones_like', 'tf.ones_like', (['y_pred'], {}), '(y_pred)\n', (1485, 1493), True, 'import tensorflow as tf\n'), ((1518, 1537), 'tensorflow.equal', 'tf.equal', (['y_true', '(0)'], {}), '(y_true, 0)\n', (1526, 1537), True, 'import tensorflow as tf\n'), ((1544, 1565), 'tensorflow.zeros_like', 'tf.zeros_like', (['y_pred'], {}), '(y_pred)\n', (1557, 1565), True, 'import tensorflow as tf\n'), ((20563, 20581), 'numpy.max', 'np.max', (['train_imgs'], {}), '(train_imgs)\n', (20569, 20581), True, 'import numpy as np\n'), ((5214, 5229), 'keras.backend.sum', 'K.sum', (['y_true_f'], {}), '(y_true_f)\n', (5219, 5229), True, 'from keras import backend as K\n'), ((5232, 5247), 'keras.backend.sum', 'K.sum', (['y_pred_f'], {}), '(y_pred_f)\n', (5237, 5247), True, 'from keras import backend as K\n'), ((1664, 1681), 'keras.backend.log', 'K.log', (['(1.0 - pt_0)'], {}), '(1.0 - pt_0)\n', (1669, 1681), True, 'from keras import backend as K\n'), ((20532, 20550), 'numpy.min', 'np.min', (['train_imgs'], {}), '(train_imgs)\n', (20538, 20550), True, 'import numpy as np\n'), ((1617, 1628), 'keras.backend.log', 'K.log', (['pt_1'], {}), '(pt_1)\n', (1622, 1628), True, 'from keras import backend as K\n'), ((1646, 1664), 'keras.backend.pow', 'K.pow', (['pt_0', 'gamma'], {}), '(pt_0, gamma)\n', (1651, 1664), True, 'from keras import backend as K\n'), ((1596, 1620), 'keras.backend.pow', 'K.pow', (['(1.0 - pt_1)', 'gamma'], {}), '(1.0 - pt_1, gamma)\n', (1601, 1620), True, 'from keras import backend as K\n')]
|
import numpy as np
from copy import copy
from .base import Simplifier
from ... import operations
from ...analyzers import SplitAnalysis
class ConvertBatchNorm(Simplifier):
ANALYSES = {"is_split": SplitAnalysis}
def visit_BatchNormalization(self, operation: operations.BatchNormalization):
input_op = operation.x
if (
isinstance(input_op, operations.Conv)
and not self.analysis["is_split"][input_op]
):
std = np.sqrt(operation.variance + operation.epsilon)
a = operation.scale / std
b = operation.bias - operation.scale * operation.mean / std
weights = input_op.w
a_w = a[:, None, None, None]
weights = a_w * weights
bias = input_op.b
if bias is None:
bias = np.zeros(weights.shape[0], dtype=weights.dtype)
bias = a * bias + b
new_operation = copy(input_op)
new_operation.w = weights
new_operation.b = bias
return new_operation
elif (
isinstance(input_op, operations.Gemm)
and not self.analysis["is_split"][input_op]
):
std = np.sqrt(operation.variance + operation.epsilon)
a = operation.scale / std
b = operation.bias - operation.mean * a
return operations.Gemm(input_op, np.diag(a), b)
elif isinstance(input_op, operations.Input):
input_shape = input_op.shape
input_dtype = input_op.dtype
if len(input_shape) == 2:
std = np.sqrt(operation.variance + operation.epsilon)
a = operation.scale / std
b = operation.bias - operation.mean * a
return operations.Gemm(input_op, np.diag(a), b)
elif len(input_shape) == 4:
c = operation.mean.shape[0]
std = np.sqrt(operation.variance + operation.epsilon)
k = np.zeros(
(c, c, 1, 1), dtype=input_dtype
) # identity kernel (H, W, inC, outC)
for i in range(c):
k[i, i, 0, 0] = 1
W = k * operation.scale / std
b = operation.bias - operation.scale * operation.mean / std
op = operations.Conv(input_op, W, b)
return op
# TODO : in what other scenarios can BatchNorm be converted?
return operation
|
[
"numpy.zeros",
"numpy.diag",
"copy.copy",
"numpy.sqrt"
] |
[((481, 528), 'numpy.sqrt', 'np.sqrt', (['(operation.variance + operation.epsilon)'], {}), '(operation.variance + operation.epsilon)\n', (488, 528), True, 'import numpy as np\n'), ((941, 955), 'copy.copy', 'copy', (['input_op'], {}), '(input_op)\n', (945, 955), False, 'from copy import copy\n'), ((832, 879), 'numpy.zeros', 'np.zeros', (['weights.shape[0]'], {'dtype': 'weights.dtype'}), '(weights.shape[0], dtype=weights.dtype)\n', (840, 879), True, 'import numpy as np\n'), ((1212, 1259), 'numpy.sqrt', 'np.sqrt', (['(operation.variance + operation.epsilon)'], {}), '(operation.variance + operation.epsilon)\n', (1219, 1259), True, 'import numpy as np\n'), ((1395, 1405), 'numpy.diag', 'np.diag', (['a'], {}), '(a)\n', (1402, 1405), True, 'import numpy as np\n'), ((1605, 1652), 'numpy.sqrt', 'np.sqrt', (['(operation.variance + operation.epsilon)'], {}), '(operation.variance + operation.epsilon)\n', (1612, 1652), True, 'import numpy as np\n'), ((1800, 1810), 'numpy.diag', 'np.diag', (['a'], {}), '(a)\n', (1807, 1810), True, 'import numpy as np\n'), ((1921, 1968), 'numpy.sqrt', 'np.sqrt', (['(operation.variance + operation.epsilon)'], {}), '(operation.variance + operation.epsilon)\n', (1928, 1968), True, 'import numpy as np\n'), ((1989, 2030), 'numpy.zeros', 'np.zeros', (['(c, c, 1, 1)'], {'dtype': 'input_dtype'}), '((c, c, 1, 1), dtype=input_dtype)\n', (1997, 2030), True, 'import numpy as np\n')]
|
import tensorflow as tf
import numpy as np
import chess
#load the saved model
model=tf.keras.models.load_model('openlock_model')
#rest explained in nntest.py
probmodel=tf.keras.Sequential([
model,
tf.keras.layers.Softmax()
])
PieceNum={'p':'0','n':'1','b':'2','r':'3','q':'4','k':'5','.':'6'}
def numreprgen(repres):
splted=[repres[0:8],repres[8:16],repres[16:24],repres[24:32],repres[32:40],repres[40:48],repres[48:56],repres[56:64]]
numsplted=[]
for j in splted:
toappend=[]
for k in j:
toappend.append(PieceNum[k.lower()])
numsplted.append(toappend)
for j in range(len(numsplted)):
for k in range(8):
numsplted[j][k]=int(numsplted[j][k])/6.0
return numsplted
def reprgener(fen):
brd=chess.Board()
brd.set_fen(fen)
bb=chess.BaseBoard()
bb.set_board_fen(brd.board_fen())
pcmap=bb.piece_map()
repres=[]
for i in range(64):
if i in pcmap:
repres.append(pcmap[i].symbol())
else:
repres.append('.')
strrepres=''.join([elem for elem in repres])
return strrepres
testfen='r4r1k/p5p1/1pRq2np/5p2/7P/P4BP1/1P2QP2/2K1R3 b - - 0 1'
probs=probmodel(np.array([numreprgen(reprgener(testfen))]))
print(np.argmax(probs))
print(probs)
|
[
"tensorflow.keras.models.load_model",
"numpy.argmax",
"tensorflow.keras.layers.Softmax",
"chess.Board",
"chess.BaseBoard"
] |
[((85, 129), 'tensorflow.keras.models.load_model', 'tf.keras.models.load_model', (['"""openlock_model"""'], {}), "('openlock_model')\n", (111, 129), True, 'import tensorflow as tf\n'), ((778, 791), 'chess.Board', 'chess.Board', ([], {}), '()\n', (789, 791), False, 'import chess\n'), ((820, 837), 'chess.BaseBoard', 'chess.BaseBoard', ([], {}), '()\n', (835, 837), False, 'import chess\n'), ((1259, 1275), 'numpy.argmax', 'np.argmax', (['probs'], {}), '(probs)\n', (1268, 1275), True, 'import numpy as np\n'), ((203, 228), 'tensorflow.keras.layers.Softmax', 'tf.keras.layers.Softmax', ([], {}), '()\n', (226, 228), True, 'import tensorflow as tf\n')]
|
import numpy as np
import matplotlib.pyplot as plt
import timeit
import random
import math
def insertionSort(a):
for i in range(1,len(a)):
value = a[i]
pos = i
while (pos > 0 and value < a[pos-1]):
a[pos] = a[pos-1]
pos = pos-1
a[pos] = value
def countingSort(a,max):
m = max+1
count = [0 for i in range(m)]
for i in a:
count[i] +=1
x = 0
for i in range(m):
for j in range(count[i]):
a[x]=a
x+=1
def quickSort(a, low, high):
if (low >= high):
return
i, j = low, high
pivot = a[random.randint(low, high)]
while i <= j:
while a[i] < pivot: i += 1
while a[j] > pivot: j -= 1
if i <= j:
a[i], a[j] = a[j], a[i]
i, j = i + 1, j - 1
quickSort(a, low, j)
quickSort(a, i, high)
def mergeSort(a):
if (len(a)< 2):
return a
pivot = len(a)//2
left = mergeSort(a[:pivot])
right = mergeSort(a[pivot:])
return merge(left,right)
def merge(left,right):
if not left or not right:
return left or right
aux = []
i = 0
j = 0
while (len(aux) < len(left) + len(right)):
if (left[i] < right[j]):
aux.append(left[i])
i += 1
else:
aux.append(right[j])
j += 1
if (i == len(left) or j == len(right)):
aux.extend(left[i:] or right[j:])
break
return aux
def radixSort(a):
length = len(a)
out = [0] * length
count = [0]*10
for i in a:
if (i>0):
x = (a[i]//10)
count[(x)%10]+=1
for i in range(1,10):
count[i] += count[i-1]
i = length - 1
while (1>=0):
x = (a[i]//10)
out[count[(x)%10]-1] = a[i]
count[(x)%10] -= 1
i -= 1
for i in range(len(a)):
a[i] = out[i]
############## Begin Here ###############
a = np.random.randint(101, size = 128)
a = a.tolist()
radixSort(a)
print('true')
############ insertion sort ###############
b = np.array([])
c = np.array([])
d = np.array([])
e = np.array([])
counts = 0
print('128')
while (counts < 100):
a = np.random.randint(101, size = 128)
t1 = timeit.default_timer()
insertionSort(a)
t2 = timeit.default_timer()
t_diff = t2-t1
b = np.append(b, t_diff)
counts = counts + 1
b_insertion_sort_mean = np.mean(b)
print('1024')
while (counts < 200):
a = np.random.randint(101, size = 1024)
t1 = timeit.default_timer()
insertionSort(a)
t2 = timeit.default_timer()
t_diff = t2-t1
c = np.append(c, t_diff)
counts = counts + 1
c_insertion_sort_mean = np.mean(c)
print('4096')
while (counts < 300):
a = np.random.randint(101, size = 4096)
t1 = timeit.default_timer()
insertionSort(a)
t2 = timeit.default_timer()
t_diff = t2-t1
d = np.append(d, t_diff)
counts = counts + 1
d_insertion_sort_mean = np.mean(d)
print('16384')
while (counts < 400):
a = np.random.randint(101, size = 16384)
t1 = timeit.default_timer()
insertionSort(a)
t2 = timeit.default_timer()
t_diff = t2-t1
e = np.append(e, t_diff)
counts = counts + 1
e_insertion_sort_mean = np.mean(e)
################ counting sort ##################
b = np.array([])
c = np.array([])
d = np.array([])
e = np.array([])
counts = 0
print('128')
while (counts < 100):
a = np.random.randint(101, size = 128)
t1 = timeit.default_timer()
countingSort(a,100)
t2 = timeit.default_timer()
t_diff = t2-t1
b = np.append(b, t_diff)
counts = counts + 1
b_countingsort_mean = np.mean(b)
print('1024')
while (counts < 200):
a = np.random.randint(101, size = 1024)
t1 = timeit.default_timer()
countingSort(a,100)
t2 = timeit.default_timer()
t_diff = t2-t1
c = np.append(c, t_diff)
counts = counts + 1
c_countingsort_mean = np.mean(c)
print('4096')
while (counts < 300):
a = np.random.randint(101, size = 4096)
t1 = timeit.default_timer()
countingSort(a,100)
t2 = timeit.default_timer()
t_diff = t2-t1
d = np.append(d, t_diff)
counts = counts + 1
d_countingsort_mean = np.mean(d)
print('16384')
while (counts < 400):
a = np.random.randint(101, size = 16384)
t1 = timeit.default_timer()
countingSort(a,100)
t2 = timeit.default_timer()
t_diff = t2-t1
e = np.append(e, t_diff)
counts = counts + 1
e_countingsort_mean = np.mean(e)
################ quick sort ##################
b = np.array([])
c = np.array([])
d = np.array([])
e = np.array([])
counts = 0
print('128')
while (counts < 100):
a = np.random.randint(101, size = 128)
t1 = timeit.default_timer()
quickSort(a)
t2 = timeit.default_timer()
t_diff = t2-t1
b = np.append(b, t_diff)
counts = counts + 1
b_quicksort_mean = np.mean(b)
print('1024')
while (counts < 200):
a = np.random.randint(101, size = 1024)
t1 = timeit.default_timer()
quickSort(a)
t2 = timeit.default_timer()
t_diff = t2-t1
c = np.append(c, t_diff)
counts = counts + 1
c_quicksort_mean = np.mean(c)
print('4096')
while (counts < 300):
a = np.random.randint(101, size = 4096)
t1 = timeit.default_timer()
quickSort(a)
t2 = timeit.default_timer()
t_diff = t2-t1
d = np.append(d, t_diff)
counts = counts + 1
d_quicksort_mean = np.mean(d)
print('16384')
while (counts < 400):
a = np.random.randint(101, size = 16384)
t1 = timeit.default_timer()
quickSort(a)
t2 = timeit.default_timer()
t_diff = t2-t1
e = np.append(e, t_diff)
counts = counts + 1
e_quicksort_mean = np.mean(e)
############### merge sort ###################
b = np.array([])
c = np.array([])
d = np.array([])
e = np.array([])
counts = 0
print('128')
while (counts < 100):
a = np.random.randint(101, size = 128)
t1 = timeit.default_timer()
mergeSort(a)
t2 = timeit.default_timer()
t_diff = t2-t1
b = np.append(b, t_diff)
counts = counts + 1
b_mergesort_mean = np.mean(b)
print('1024')
while (counts < 200):
a = np.random.randint(101, size = 1024)
t1 = timeit.default_timer()
mergeSort(a)
t2 = timeit.default_timer()
t_diff = t2-t1
c = np.append(c, t_diff)
counts = counts + 1
c_mergesort_mean = np.mean(c)
print('4096')
while (counts < 300):
a = np.random.randint(101, size = 4096)
t1 = timeit.default_timer()
mergeSort(a)
t2 = timeit.default_timer()
t_diff = t2-t1
d = np.append(d, t_diff)
counts = counts + 1
d_mergesort_mean = np.mean(d)
print('16384')
while (counts < 400):
a = np.random.randint(101, size = 16384)
t1 = timeit.default_timer()
mergeSort(a)
t2 = timeit.default_timer()
t_diff = t2-t1
e = np.append(e, t_diff)
counts = counts + 1
e_mergesort_mean = np.mean(e)
############### radix sort ##################
b = np.array([])
c = np.array([])
d = np.array([])
e = np.array([])
counts = 0
print('128')
while (counts < 100):
a = np.random.randint(101, size = 128)
t1 = timeit.default_timer()
radixSort(a,10,100)
t2 = timeit.default_timer()
t_diff = t2-t1
b = np.append(b, t_diff)
counts = counts + 1
b_radixsort_mean = np.mean(b)
print('1024')
while (counts < 200):
a = np.random.randint(101, size = 1024)
t1 = timeit.default_timer()
radixSort(a,10,100)
t2 = timeit.default_timer()
t_diff = t2-t1
c = np.append(c, t_diff)
counts = counts + 1
c_radixsort_mean = np.mean(c)
print('4096')
while (counts < 300):
a = np.random.randint(101, size = 4096)
t1 = timeit.default_timer()
radixSort(a,10,100)
t2 = timeit.default_timer()
t_diff = t2-t1
d = np.append(d, t_diff)
counts = counts + 1
d_radixsort_mean = np.mean(d)
print('16384')
while (counts < 400):
a = np.random.randint(101, size = 16384)
t1 = timeit.default_timer()
radixSort(a,10,100)
t2 = timeit.default_timer()
t_diff = t2-t1
e = np.append(e, t_diff)
counts = counts + 1
e_radixsort_mean = np.mean(e)
############## plotting ##############
plt.plot([128, 1024, 4096, 16384],
[b_insertion_sort_mean, c_insertion_sort_mean, d_insertion_sort_mean,e_insertion_sort_mean],
c = 'blue',
label = 'Insertion Sort',
linestyle = '--',
linewidth = 2)
plt.plot([128, 1024, 4096, 16384],
[b_countingsort_mean, c_countingsort_mean, d_countingsort_mean,e_countingsort_mean],
c = 'red',
label = 'Counting Sort',
linestyle = '--',
linewidth = 2)
plt.plot([128, 1024, 4096, 16384],
[b_quicksort_mean, c_quicksort_mean, d_quicksort_mean,e_quicksort_mean],
c = 'green',
label = 'Quick Sort',
linestyle = '--',
linewidth = 2)
plt.plot([128, 1024, 4096, 16384],
[b_mergesort_mean, c_mergesort_mean, d_mergesort_mean,e_mergesort_mean],
c = 'yellow',
label = 'Merge Sort',
linestyle = '--',
linewidth = 2)
plt.plot([128, 1024, 4096, 16384],
[b_radixsort_mean, c_radixsort_mean, d_radixsort_mean,e_radixsort_mean],
c = 'black',
label = 'Radix Sort',
linestyle = '--',
linewidth = 2)
plt.axis([0,18000,0,.0005])
plt.show()
|
[
"matplotlib.pyplot.show",
"random.randint",
"matplotlib.pyplot.plot",
"timeit.default_timer",
"matplotlib.pyplot.axis",
"numpy.append",
"numpy.mean",
"numpy.random.randint",
"numpy.array"
] |
[((1790, 1822), 'numpy.random.randint', 'np.random.randint', (['(101)'], {'size': '(128)'}), '(101, size=128)\n', (1807, 1822), True, 'import numpy as np\n'), ((1927, 1939), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (1935, 1939), True, 'import numpy as np\n'), ((1945, 1957), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (1953, 1957), True, 'import numpy as np\n'), ((1963, 1975), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (1971, 1975), True, 'import numpy as np\n'), ((1981, 1993), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (1989, 1993), True, 'import numpy as np\n'), ((2260, 2270), 'numpy.mean', 'np.mean', (['b'], {}), '(b)\n', (2267, 2270), True, 'import numpy as np\n'), ((2523, 2533), 'numpy.mean', 'np.mean', (['c'], {}), '(c)\n', (2530, 2533), True, 'import numpy as np\n'), ((2786, 2796), 'numpy.mean', 'np.mean', (['d'], {}), '(d)\n', (2793, 2796), True, 'import numpy as np\n'), ((3051, 3061), 'numpy.mean', 'np.mean', (['e'], {}), '(e)\n', (3058, 3061), True, 'import numpy as np\n'), ((3122, 3134), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (3130, 3134), True, 'import numpy as np\n'), ((3140, 3152), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (3148, 3152), True, 'import numpy as np\n'), ((3158, 3170), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (3166, 3170), True, 'import numpy as np\n'), ((3176, 3188), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (3184, 3188), True, 'import numpy as np\n'), ((3456, 3466), 'numpy.mean', 'np.mean', (['b'], {}), '(b)\n', (3463, 3466), True, 'import numpy as np\n'), ((3720, 3730), 'numpy.mean', 'np.mean', (['c'], {}), '(c)\n', (3727, 3730), True, 'import numpy as np\n'), ((3984, 3994), 'numpy.mean', 'np.mean', (['d'], {}), '(d)\n', (3991, 3994), True, 'import numpy as np\n'), ((4250, 4260), 'numpy.mean', 'np.mean', (['e'], {}), '(e)\n', (4257, 4260), True, 'import numpy as np\n'), ((4320, 4332), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (4328, 4332), True, 'import numpy as np\n'), ((4338, 4350), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (4346, 4350), True, 'import numpy as np\n'), ((4356, 4368), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (4364, 4368), True, 'import numpy as np\n'), ((4374, 4386), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (4382, 4386), True, 'import numpy as np\n'), ((4644, 4654), 'numpy.mean', 'np.mean', (['b'], {}), '(b)\n', (4651, 4654), True, 'import numpy as np\n'), ((4898, 4908), 'numpy.mean', 'np.mean', (['c'], {}), '(c)\n', (4905, 4908), True, 'import numpy as np\n'), ((5152, 5162), 'numpy.mean', 'np.mean', (['d'], {}), '(d)\n', (5159, 5162), True, 'import numpy as np\n'), ((5408, 5418), 'numpy.mean', 'np.mean', (['e'], {}), '(e)\n', (5415, 5418), True, 'import numpy as np\n'), ((5474, 5486), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (5482, 5486), True, 'import numpy as np\n'), ((5492, 5504), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (5500, 5504), True, 'import numpy as np\n'), ((5510, 5522), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (5518, 5522), True, 'import numpy as np\n'), ((5528, 5540), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (5536, 5540), True, 'import numpy as np\n'), ((5798, 5808), 'numpy.mean', 'np.mean', (['b'], {}), '(b)\n', (5805, 5808), True, 'import numpy as np\n'), ((6052, 6062), 'numpy.mean', 'np.mean', (['c'], {}), '(c)\n', (6059, 6062), True, 'import numpy as np\n'), ((6306, 6316), 'numpy.mean', 'np.mean', (['d'], {}), '(d)\n', (6313, 6316), True, 'import numpy as np\n'), ((6562, 6572), 'numpy.mean', 'np.mean', (['e'], {}), '(e)\n', (6569, 6572), True, 'import numpy as np\n'), ((6629, 6641), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (6637, 6641), True, 'import numpy as np\n'), ((6647, 6659), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (6655, 6659), True, 'import numpy as np\n'), ((6665, 6677), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (6673, 6677), True, 'import numpy as np\n'), ((6683, 6695), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (6691, 6695), True, 'import numpy as np\n'), ((6960, 6970), 'numpy.mean', 'np.mean', (['b'], {}), '(b)\n', (6967, 6970), True, 'import numpy as np\n'), ((7221, 7231), 'numpy.mean', 'np.mean', (['c'], {}), '(c)\n', (7228, 7231), True, 'import numpy as np\n'), ((7482, 7492), 'numpy.mean', 'np.mean', (['d'], {}), '(d)\n', (7489, 7492), True, 'import numpy as np\n'), ((7745, 7755), 'numpy.mean', 'np.mean', (['e'], {}), '(e)\n', (7752, 7755), True, 'import numpy as np\n'), ((7802, 8002), 'matplotlib.pyplot.plot', 'plt.plot', (['[128, 1024, 4096, 16384]', '[b_insertion_sort_mean, c_insertion_sort_mean, d_insertion_sort_mean,\n e_insertion_sort_mean]'], {'c': '"""blue"""', 'label': '"""Insertion Sort"""', 'linestyle': '"""--"""', 'linewidth': '(2)'}), "([128, 1024, 4096, 16384], [b_insertion_sort_mean,\n c_insertion_sort_mean, d_insertion_sort_mean, e_insertion_sort_mean], c\n ='blue', label='Insertion Sort', linestyle='--', linewidth=2)\n", (7810, 8002), True, 'import matplotlib.pyplot as plt\n'), ((8012, 8201), 'matplotlib.pyplot.plot', 'plt.plot', (['[128, 1024, 4096, 16384]', '[b_countingsort_mean, c_countingsort_mean, d_countingsort_mean,\n e_countingsort_mean]'], {'c': '"""red"""', 'label': '"""Counting Sort"""', 'linestyle': '"""--"""', 'linewidth': '(2)'}), "([128, 1024, 4096, 16384], [b_countingsort_mean,\n c_countingsort_mean, d_countingsort_mean, e_countingsort_mean], c='red',\n label='Counting Sort', linestyle='--', linewidth=2)\n", (8020, 8201), True, 'import matplotlib.pyplot as plt\n'), ((8212, 8388), 'matplotlib.pyplot.plot', 'plt.plot', (['[128, 1024, 4096, 16384]', '[b_quicksort_mean, c_quicksort_mean, d_quicksort_mean, e_quicksort_mean]'], {'c': '"""green"""', 'label': '"""Quick Sort"""', 'linestyle': '"""--"""', 'linewidth': '(2)'}), "([128, 1024, 4096, 16384], [b_quicksort_mean, c_quicksort_mean,\n d_quicksort_mean, e_quicksort_mean], c='green', label='Quick Sort',\n linestyle='--', linewidth=2)\n", (8220, 8388), True, 'import matplotlib.pyplot as plt\n'), ((8399, 8576), 'matplotlib.pyplot.plot', 'plt.plot', (['[128, 1024, 4096, 16384]', '[b_mergesort_mean, c_mergesort_mean, d_mergesort_mean, e_mergesort_mean]'], {'c': '"""yellow"""', 'label': '"""Merge Sort"""', 'linestyle': '"""--"""', 'linewidth': '(2)'}), "([128, 1024, 4096, 16384], [b_mergesort_mean, c_mergesort_mean,\n d_mergesort_mean, e_mergesort_mean], c='yellow', label='Merge Sort',\n linestyle='--', linewidth=2)\n", (8407, 8576), True, 'import matplotlib.pyplot as plt\n'), ((8587, 8763), 'matplotlib.pyplot.plot', 'plt.plot', (['[128, 1024, 4096, 16384]', '[b_radixsort_mean, c_radixsort_mean, d_radixsort_mean, e_radixsort_mean]'], {'c': '"""black"""', 'label': '"""Radix Sort"""', 'linestyle': '"""--"""', 'linewidth': '(2)'}), "([128, 1024, 4096, 16384], [b_radixsort_mean, c_radixsort_mean,\n d_radixsort_mean, e_radixsort_mean], c='black', label='Radix Sort',\n linestyle='--', linewidth=2)\n", (8595, 8763), True, 'import matplotlib.pyplot as plt\n'), ((8774, 8805), 'matplotlib.pyplot.axis', 'plt.axis', (['[0, 18000, 0, 0.0005]'], {}), '([0, 18000, 0, 0.0005])\n', (8782, 8805), True, 'import matplotlib.pyplot as plt\n'), ((8803, 8813), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (8811, 8813), True, 'import matplotlib.pyplot as plt\n'), ((2055, 2087), 'numpy.random.randint', 'np.random.randint', (['(101)'], {'size': '(128)'}), '(101, size=128)\n', (2072, 2087), True, 'import numpy as np\n'), ((2097, 2119), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (2117, 2119), False, 'import timeit\n'), ((2146, 2168), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (2166, 2168), False, 'import timeit\n'), ((2192, 2212), 'numpy.append', 'np.append', (['b', 't_diff'], {}), '(b, t_diff)\n', (2201, 2212), True, 'import numpy as np\n'), ((2317, 2350), 'numpy.random.randint', 'np.random.randint', (['(101)'], {'size': '(1024)'}), '(101, size=1024)\n', (2334, 2350), True, 'import numpy as np\n'), ((2360, 2382), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (2380, 2382), False, 'import timeit\n'), ((2409, 2431), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (2429, 2431), False, 'import timeit\n'), ((2455, 2475), 'numpy.append', 'np.append', (['c', 't_diff'], {}), '(c, t_diff)\n', (2464, 2475), True, 'import numpy as np\n'), ((2580, 2613), 'numpy.random.randint', 'np.random.randint', (['(101)'], {'size': '(4096)'}), '(101, size=4096)\n', (2597, 2613), True, 'import numpy as np\n'), ((2623, 2645), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (2643, 2645), False, 'import timeit\n'), ((2672, 2694), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (2692, 2694), False, 'import timeit\n'), ((2718, 2738), 'numpy.append', 'np.append', (['d', 't_diff'], {}), '(d, t_diff)\n', (2727, 2738), True, 'import numpy as np\n'), ((2844, 2878), 'numpy.random.randint', 'np.random.randint', (['(101)'], {'size': '(16384)'}), '(101, size=16384)\n', (2861, 2878), True, 'import numpy as np\n'), ((2888, 2910), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (2908, 2910), False, 'import timeit\n'), ((2937, 2959), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (2957, 2959), False, 'import timeit\n'), ((2983, 3003), 'numpy.append', 'np.append', (['e', 't_diff'], {}), '(e, t_diff)\n', (2992, 3003), True, 'import numpy as np\n'), ((3250, 3282), 'numpy.random.randint', 'np.random.randint', (['(101)'], {'size': '(128)'}), '(101, size=128)\n', (3267, 3282), True, 'import numpy as np\n'), ((3292, 3314), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (3312, 3314), False, 'import timeit\n'), ((3344, 3366), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (3364, 3366), False, 'import timeit\n'), ((3390, 3410), 'numpy.append', 'np.append', (['b', 't_diff'], {}), '(b, t_diff)\n', (3399, 3410), True, 'import numpy as np\n'), ((3513, 3546), 'numpy.random.randint', 'np.random.randint', (['(101)'], {'size': '(1024)'}), '(101, size=1024)\n', (3530, 3546), True, 'import numpy as np\n'), ((3556, 3578), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (3576, 3578), False, 'import timeit\n'), ((3608, 3630), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (3628, 3630), False, 'import timeit\n'), ((3654, 3674), 'numpy.append', 'np.append', (['c', 't_diff'], {}), '(c, t_diff)\n', (3663, 3674), True, 'import numpy as np\n'), ((3777, 3810), 'numpy.random.randint', 'np.random.randint', (['(101)'], {'size': '(4096)'}), '(101, size=4096)\n', (3794, 3810), True, 'import numpy as np\n'), ((3820, 3842), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (3840, 3842), False, 'import timeit\n'), ((3872, 3894), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (3892, 3894), False, 'import timeit\n'), ((3918, 3938), 'numpy.append', 'np.append', (['d', 't_diff'], {}), '(d, t_diff)\n', (3927, 3938), True, 'import numpy as np\n'), ((4042, 4076), 'numpy.random.randint', 'np.random.randint', (['(101)'], {'size': '(16384)'}), '(101, size=16384)\n', (4059, 4076), True, 'import numpy as np\n'), ((4086, 4108), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (4106, 4108), False, 'import timeit\n'), ((4138, 4160), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (4158, 4160), False, 'import timeit\n'), ((4184, 4204), 'numpy.append', 'np.append', (['e', 't_diff'], {}), '(e, t_diff)\n', (4193, 4204), True, 'import numpy as np\n'), ((4448, 4480), 'numpy.random.randint', 'np.random.randint', (['(101)'], {'size': '(128)'}), '(101, size=128)\n', (4465, 4480), True, 'import numpy as np\n'), ((4490, 4512), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (4510, 4512), False, 'import timeit\n'), ((4535, 4557), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (4555, 4557), False, 'import timeit\n'), ((4581, 4601), 'numpy.append', 'np.append', (['b', 't_diff'], {}), '(b, t_diff)\n', (4590, 4601), True, 'import numpy as np\n'), ((4701, 4734), 'numpy.random.randint', 'np.random.randint', (['(101)'], {'size': '(1024)'}), '(101, size=1024)\n', (4718, 4734), True, 'import numpy as np\n'), ((4744, 4766), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (4764, 4766), False, 'import timeit\n'), ((4789, 4811), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (4809, 4811), False, 'import timeit\n'), ((4835, 4855), 'numpy.append', 'np.append', (['c', 't_diff'], {}), '(c, t_diff)\n', (4844, 4855), True, 'import numpy as np\n'), ((4955, 4988), 'numpy.random.randint', 'np.random.randint', (['(101)'], {'size': '(4096)'}), '(101, size=4096)\n', (4972, 4988), True, 'import numpy as np\n'), ((4998, 5020), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (5018, 5020), False, 'import timeit\n'), ((5043, 5065), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (5063, 5065), False, 'import timeit\n'), ((5089, 5109), 'numpy.append', 'np.append', (['d', 't_diff'], {}), '(d, t_diff)\n', (5098, 5109), True, 'import numpy as np\n'), ((5210, 5244), 'numpy.random.randint', 'np.random.randint', (['(101)'], {'size': '(16384)'}), '(101, size=16384)\n', (5227, 5244), True, 'import numpy as np\n'), ((5254, 5276), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (5274, 5276), False, 'import timeit\n'), ((5299, 5321), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (5319, 5321), False, 'import timeit\n'), ((5345, 5365), 'numpy.append', 'np.append', (['e', 't_diff'], {}), '(e, t_diff)\n', (5354, 5365), True, 'import numpy as np\n'), ((5602, 5634), 'numpy.random.randint', 'np.random.randint', (['(101)'], {'size': '(128)'}), '(101, size=128)\n', (5619, 5634), True, 'import numpy as np\n'), ((5644, 5666), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (5664, 5666), False, 'import timeit\n'), ((5689, 5711), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (5709, 5711), False, 'import timeit\n'), ((5735, 5755), 'numpy.append', 'np.append', (['b', 't_diff'], {}), '(b, t_diff)\n', (5744, 5755), True, 'import numpy as np\n'), ((5855, 5888), 'numpy.random.randint', 'np.random.randint', (['(101)'], {'size': '(1024)'}), '(101, size=1024)\n', (5872, 5888), True, 'import numpy as np\n'), ((5898, 5920), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (5918, 5920), False, 'import timeit\n'), ((5943, 5965), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (5963, 5965), False, 'import timeit\n'), ((5989, 6009), 'numpy.append', 'np.append', (['c', 't_diff'], {}), '(c, t_diff)\n', (5998, 6009), True, 'import numpy as np\n'), ((6109, 6142), 'numpy.random.randint', 'np.random.randint', (['(101)'], {'size': '(4096)'}), '(101, size=4096)\n', (6126, 6142), True, 'import numpy as np\n'), ((6152, 6174), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (6172, 6174), False, 'import timeit\n'), ((6197, 6219), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (6217, 6219), False, 'import timeit\n'), ((6243, 6263), 'numpy.append', 'np.append', (['d', 't_diff'], {}), '(d, t_diff)\n', (6252, 6263), True, 'import numpy as np\n'), ((6364, 6398), 'numpy.random.randint', 'np.random.randint', (['(101)'], {'size': '(16384)'}), '(101, size=16384)\n', (6381, 6398), True, 'import numpy as np\n'), ((6408, 6430), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (6428, 6430), False, 'import timeit\n'), ((6453, 6475), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (6473, 6475), False, 'import timeit\n'), ((6499, 6519), 'numpy.append', 'np.append', (['e', 't_diff'], {}), '(e, t_diff)\n', (6508, 6519), True, 'import numpy as np\n'), ((6757, 6789), 'numpy.random.randint', 'np.random.randint', (['(101)'], {'size': '(128)'}), '(101, size=128)\n', (6774, 6789), True, 'import numpy as np\n'), ((6799, 6821), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (6819, 6821), False, 'import timeit\n'), ((6851, 6873), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (6871, 6873), False, 'import timeit\n'), ((6897, 6917), 'numpy.append', 'np.append', (['b', 't_diff'], {}), '(b, t_diff)\n', (6906, 6917), True, 'import numpy as np\n'), ((7017, 7050), 'numpy.random.randint', 'np.random.randint', (['(101)'], {'size': '(1024)'}), '(101, size=1024)\n', (7034, 7050), True, 'import numpy as np\n'), ((7060, 7082), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (7080, 7082), False, 'import timeit\n'), ((7112, 7134), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (7132, 7134), False, 'import timeit\n'), ((7158, 7178), 'numpy.append', 'np.append', (['c', 't_diff'], {}), '(c, t_diff)\n', (7167, 7178), True, 'import numpy as np\n'), ((7278, 7311), 'numpy.random.randint', 'np.random.randint', (['(101)'], {'size': '(4096)'}), '(101, size=4096)\n', (7295, 7311), True, 'import numpy as np\n'), ((7321, 7343), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (7341, 7343), False, 'import timeit\n'), ((7373, 7395), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (7393, 7395), False, 'import timeit\n'), ((7419, 7439), 'numpy.append', 'np.append', (['d', 't_diff'], {}), '(d, t_diff)\n', (7428, 7439), True, 'import numpy as np\n'), ((7540, 7574), 'numpy.random.randint', 'np.random.randint', (['(101)'], {'size': '(16384)'}), '(101, size=16384)\n', (7557, 7574), True, 'import numpy as np\n'), ((7584, 7606), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (7604, 7606), False, 'import timeit\n'), ((7636, 7658), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (7656, 7658), False, 'import timeit\n'), ((7682, 7702), 'numpy.append', 'np.append', (['e', 't_diff'], {}), '(e, t_diff)\n', (7691, 7702), True, 'import numpy as np\n'), ((568, 593), 'random.randint', 'random.randint', (['low', 'high'], {}), '(low, high)\n', (582, 593), False, 'import random\n')]
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import tensorflow as tf
import numpy as np
import PIL.Image as Image
import time
import cv2
from pyfirmata import Arduino
board = Arduino('/dev/ttyACM0')
little = board.get_pin('d:3:s')
ring = board.get_pin('d:5:s')
middle = board.get_pin('d:6:s')
thumb = board.get_pin('d:9:s')
index = board.get_pin('d:10:s')
def rock():
thumb.write(170)
index.write(170)
middle.write(170)
ring.write(170)
little.write(170)
def paper():
thumb.write(10)
index.write(10)
middle.write(10)
ring.write(10)
little.write(10)
def scissor():
thumb.write(170)
index.write(10)
middle.write(10)
ring.write(170)
little.write(170)
def rps(model_dir, classes):
clicked = False
def onMouse(event, x, y, flags, param):
global clicked
if event == cv2.EVENT_LBUTTONUP:
clicked = True
cameraCapture = cv2.VideoCapture(2)
cameraCapture.set(3, 100)
cameraCapture.set(4, 100)
cv2.namedWindow('MyWindow')
cv2.setMouseCallback('MyWindow', onMouse)
print('showing camera feed. Click window or press and key to stop.')
success, frame = cameraCapture.read()
print(success)
count = 0
flag = 0
saver = tf.train.import_meta_graph(model_dir+".meta")
with tf.Session() as sess:
saver.restore(sess, model_dir)
x = tf.get_default_graph().get_tensor_by_name("images:0")
keep_prob = tf.get_default_graph().get_tensor_by_name("keep_prob:0")
y = tf.get_default_graph().get_tensor_by_name("fc2/output:0")
count=0
while success and cv2.waitKey(1)==-1 and not clicked:
time1 = time.time()
cv2.imshow('MyWindow', frame)
success, frame = cameraCapture.read()
img = Image.fromarray(frame)
# 将图片转化成灰度并缩小尺寸
img = np.array(img.convert('L').resize((28, 28)),dtype=np.float32)
img = img.reshape((1,28*28))
img = img/255.0
prediction = sess.run(y, feed_dict={x:img,keep_prob: 1.0})
index = np.argmax(prediction)
probability = prediction[0][index]
if index==0 and flag!=0 and probability>0.8:
print('you paper, me scissor')
scissor()
flag=0
elif index==1 and flag!=1 and probability>0.8:
print('you rock, me paper')
paper()
flag = 1
elif index==2 and flag!=2 and probability>0.8:
print('you scissor, me rock')
rock()
flag = 2
elif index == 3 and flag != 3 and probability > 0.8:
# rotate(p, -30)
print('hey, show either rock, paper or scissor')
flag = 3
cv2.destroyWindow('MyWindow')
cameraCapture.release()
if __name__=="__main__":
classes = ['paper', 'rock', 'scissors', 'others']
model_dir="model/model.ckpt"
time.sleep(2)
rps(model_dir, classes)
|
[
"tensorflow.train.import_meta_graph",
"numpy.argmax",
"cv2.waitKey",
"tensorflow.Session",
"time.sleep",
"cv2.VideoCapture",
"time.time",
"pyfirmata.Arduino",
"cv2.setMouseCallback",
"cv2.destroyWindow",
"PIL.Image.fromarray",
"tensorflow.get_default_graph",
"cv2.imshow",
"cv2.namedWindow"
] |
[((334, 357), 'pyfirmata.Arduino', 'Arduino', (['"""/dev/ttyACM0"""'], {}), "('/dev/ttyACM0')\n", (341, 357), False, 'from pyfirmata import Arduino\n'), ((1122, 1141), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(2)'], {}), '(2)\n', (1138, 1141), False, 'import cv2\n'), ((1206, 1233), 'cv2.namedWindow', 'cv2.namedWindow', (['"""MyWindow"""'], {}), "('MyWindow')\n", (1221, 1233), False, 'import cv2\n'), ((1244, 1285), 'cv2.setMouseCallback', 'cv2.setMouseCallback', (['"""MyWindow"""', 'onMouse'], {}), "('MyWindow', onMouse)\n", (1264, 1285), False, 'import cv2\n'), ((1507, 1554), 'tensorflow.train.import_meta_graph', 'tf.train.import_meta_graph', (["(model_dir + '.meta')"], {}), "(model_dir + '.meta')\n", (1533, 1554), True, 'import tensorflow as tf\n'), ((3346, 3359), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (3356, 3359), False, 'import time\n'), ((1566, 1578), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (1576, 1578), True, 'import tensorflow as tf\n'), ((3162, 3191), 'cv2.destroyWindow', 'cv2.destroyWindow', (['"""MyWindow"""'], {}), "('MyWindow')\n", (3179, 3191), False, 'import cv2\n'), ((1966, 1977), 'time.time', 'time.time', ([], {}), '()\n', (1975, 1977), False, 'import time\n'), ((1994, 2023), 'cv2.imshow', 'cv2.imshow', (['"""MyWindow"""', 'frame'], {}), "('MyWindow', frame)\n", (2004, 2023), False, 'import cv2\n'), ((2102, 2124), 'PIL.Image.fromarray', 'Image.fromarray', (['frame'], {}), '(frame)\n', (2117, 2124), True, 'import PIL.Image as Image\n'), ((2417, 2438), 'numpy.argmax', 'np.argmax', (['prediction'], {}), '(prediction)\n', (2426, 2438), True, 'import numpy as np\n'), ((1647, 1669), 'tensorflow.get_default_graph', 'tf.get_default_graph', ([], {}), '()\n', (1667, 1669), True, 'import tensorflow as tf\n'), ((1725, 1747), 'tensorflow.get_default_graph', 'tf.get_default_graph', ([], {}), '()\n', (1745, 1747), True, 'import tensorflow as tf\n'), ((1798, 1820), 'tensorflow.get_default_graph', 'tf.get_default_graph', ([], {}), '()\n', (1818, 1820), True, 'import tensorflow as tf\n'), ((1906, 1920), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (1917, 1920), False, 'import cv2\n')]
|
from sg.StanfordGap import StanfordGap
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn import datasets
class StanfordGapDemo(object):
def run(self):
"""
Run the Stanford Gap Statistic Analysis on the iris data set presented in
http://scikit-learn.org/stable/auto_examples/cluster/plot_cluster_iris.html#sphx-glr-auto-examples-cluster-plot-cluster-iris-py
:return:
"""
np.random.seed(42)
iris = datasets.load_iris()
X = iris.data
gaps = np.zeros((20, 1))
s = np.zeros((20, 1))
for k in range(0, 20):
est = KMeans(n_clusters=(k + 1))
est.fit(X)
sg = StanfordGap(B=10)
sg.fit(X, est.labels_, est.cluster_centers_)
gaps[k] = sg.gap
s[k] = sg.s
# Plot Gap(k)
# Choose the smallest k such that Gap(k)>=Gap(k+1) - s_(k+1)
plt.plot(gaps[0:18])
plt.plot(gaps[1:19] - s[1:19])
plt.legend(['Gap(k)', 'Gap(k+1) - s_k+1'])
plt.xticks(np.arange(20), np.arange(1, 20))
plt.xlabel('K')
plt.show()
|
[
"sklearn.datasets.load_iris",
"numpy.random.seed",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"sklearn.cluster.KMeans",
"matplotlib.pyplot.legend",
"numpy.zeros",
"numpy.arange",
"matplotlib.pyplot.xlabel",
"sg.StanfordGap.StanfordGap"
] |
[((473, 491), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (487, 491), True, 'import numpy as np\n'), ((507, 527), 'sklearn.datasets.load_iris', 'datasets.load_iris', ([], {}), '()\n', (525, 527), False, 'from sklearn import datasets\n'), ((566, 583), 'numpy.zeros', 'np.zeros', (['(20, 1)'], {}), '((20, 1))\n', (574, 583), True, 'import numpy as np\n'), ((596, 613), 'numpy.zeros', 'np.zeros', (['(20, 1)'], {}), '((20, 1))\n', (604, 613), True, 'import numpy as np\n'), ((958, 978), 'matplotlib.pyplot.plot', 'plt.plot', (['gaps[0:18]'], {}), '(gaps[0:18])\n', (966, 978), True, 'import matplotlib.pyplot as plt\n'), ((987, 1017), 'matplotlib.pyplot.plot', 'plt.plot', (['(gaps[1:19] - s[1:19])'], {}), '(gaps[1:19] - s[1:19])\n', (995, 1017), True, 'import matplotlib.pyplot as plt\n'), ((1026, 1068), 'matplotlib.pyplot.legend', 'plt.legend', (["['Gap(k)', 'Gap(k+1) - s_k+1']"], {}), "(['Gap(k)', 'Gap(k+1) - s_k+1'])\n", (1036, 1068), True, 'import matplotlib.pyplot as plt\n'), ((1129, 1144), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""K"""'], {}), "('K')\n", (1139, 1144), True, 'import matplotlib.pyplot as plt\n'), ((1153, 1163), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1161, 1163), True, 'import matplotlib.pyplot as plt\n'), ((663, 687), 'sklearn.cluster.KMeans', 'KMeans', ([], {'n_clusters': '(k + 1)'}), '(n_clusters=k + 1)\n', (669, 687), False, 'from sklearn.cluster import KMeans\n'), ((730, 747), 'sg.StanfordGap.StanfordGap', 'StanfordGap', ([], {'B': '(10)'}), '(B=10)\n', (741, 747), False, 'from sg.StanfordGap import StanfordGap\n'), ((1088, 1101), 'numpy.arange', 'np.arange', (['(20)'], {}), '(20)\n', (1097, 1101), True, 'import numpy as np\n'), ((1103, 1119), 'numpy.arange', 'np.arange', (['(1)', '(20)'], {}), '(1, 20)\n', (1112, 1119), True, 'import numpy as np\n')]
|
#!/usr/bin/python
import numpy as np
import pylab as plt
import seaborn as sns
sns.set_context("poster")
#with open("traj.dat") as f:
# data = f.read()
#
# data = data.split('\n')
#
# x = [row.split(' ')[0] for row in data]
# y = [row.split(' ')[1] for row in data]
#
# fig = plt.figure()
#
# ax1 = fig.add_subplot(111)
#
# ax1.set_title("Plot title...")
# ax1.set_xlabel('your x label..')
# ax1.set_ylabel('your y label...')
#
# ax1.plot(x,y, c='r', label='the data')
#
# leg = ax1.legend()
#fig = plt.figure()
plt.subplot(121)
#plt.ylim(-8,8)
data = np.genfromtxt(fname='q.dat')
#data = np.loadtxt('traj.dat')
for x in range(1,data.shape[1]):
plt.plot(data[:,0],data[:,x])
#plt.figure(1)
#plt.plot(x,y1,'-')
#plt.plot(x,y2,'g-')
plt.xlabel('time')
#plt.ylabel('position')
#plt.title('traj')
ax2 = plt.subplot(122)
data = np.genfromtxt(fname='c.dat')
#data = np.loadtxt('traj.dat')
for x in range(1,data.shape[1]):
plt.plot(data[:,0],data[:,x])
plt.xlabel('time')
ax2.yaxis.tick_right()
ax2.yaxis.set_ticks_position('both')
plt.ylim(-0.2,5)
#plt.subplot(2,2,3)
#data = np.genfromtxt(fname='norm')
#plt.plot(data[:,0],data[:,1],'r-',linewidth=2)
#plt.ylabel('Norm')
#plt.ylim(0,2)
plt.legend()
plt.savefig('traj.pdf')
plt.show()
|
[
"pylab.show",
"numpy.genfromtxt",
"pylab.plot",
"pylab.subplot",
"pylab.savefig",
"pylab.ylim",
"pylab.xlabel",
"pylab.legend",
"seaborn.set_context"
] |
[((81, 106), 'seaborn.set_context', 'sns.set_context', (['"""poster"""'], {}), "('poster')\n", (96, 106), True, 'import seaborn as sns\n'), ((551, 567), 'pylab.subplot', 'plt.subplot', (['(121)'], {}), '(121)\n', (562, 567), True, 'import pylab as plt\n'), ((591, 619), 'numpy.genfromtxt', 'np.genfromtxt', ([], {'fname': '"""q.dat"""'}), "(fname='q.dat')\n", (604, 619), True, 'import numpy as np\n'), ((777, 795), 'pylab.xlabel', 'plt.xlabel', (['"""time"""'], {}), "('time')\n", (787, 795), True, 'import pylab as plt\n'), ((846, 862), 'pylab.subplot', 'plt.subplot', (['(122)'], {}), '(122)\n', (857, 862), True, 'import pylab as plt\n'), ((870, 898), 'numpy.genfromtxt', 'np.genfromtxt', ([], {'fname': '"""c.dat"""'}), "(fname='c.dat')\n", (883, 898), True, 'import numpy as np\n'), ((998, 1016), 'pylab.xlabel', 'plt.xlabel', (['"""time"""'], {}), "('time')\n", (1008, 1016), True, 'import pylab as plt\n'), ((1078, 1095), 'pylab.ylim', 'plt.ylim', (['(-0.2)', '(5)'], {}), '(-0.2, 5)\n', (1086, 1095), True, 'import pylab as plt\n'), ((1236, 1248), 'pylab.legend', 'plt.legend', ([], {}), '()\n', (1246, 1248), True, 'import pylab as plt\n'), ((1249, 1272), 'pylab.savefig', 'plt.savefig', (['"""traj.pdf"""'], {}), "('traj.pdf')\n", (1260, 1272), True, 'import pylab as plt\n'), ((1274, 1284), 'pylab.show', 'plt.show', ([], {}), '()\n', (1282, 1284), True, 'import pylab as plt\n'), ((689, 721), 'pylab.plot', 'plt.plot', (['data[:, 0]', 'data[:, x]'], {}), '(data[:, 0], data[:, x])\n', (697, 721), True, 'import pylab as plt\n'), ((968, 1000), 'pylab.plot', 'plt.plot', (['data[:, 0]', 'data[:, x]'], {}), '(data[:, 0], data[:, x])\n', (976, 1000), True, 'import pylab as plt\n')]
|
import os
import sys
import numpy as np
import pytest
from matchms import Spectrum
from spec2vec import Spec2Vec
from spec2vec import SpectrumDocument
path_root = os.path.dirname(os.getcwd())
sys.path.insert(0, os.path.join(path_root, "matchmsextras"))
from matchmsextras.library_search import library_matching
def test_library_matching():
spectrum_1 = Spectrum(mz=np.array([100, 150, 200.]),
intensities=np.array([0.7, 0.2, 0.1]),
metadata={'precursor_mz': 500.5})
spectrum_2 = Spectrum(mz=np.array([100, 140, 190.]),
intensities=np.array([0.4, 0.2, 0.1]),
metadata={'precursor_mz': 500.11})
spectrum_3 = Spectrum(mz=np.array([100, 140, 190.]),
intensities=np.array([0.3, 0.5, 0.2]),
metadata={'precursor_mz': 501.1})
spectrum_4 = Spectrum(mz=np.array([97.5, 137.5, 200.]),
intensities=np.array([0.8, 0.5, 0.4]),
metadata={'precursor_mz': 500.1})
documents_library = [SpectrumDocument(s) for s in [spectrum_1, spectrum_2, spectrum_3]]
documents_query = [SpectrumDocument(spectrum_4)]
found_matches = library_matching(documents_query, documents_library,
model=None,
presearch_based_on=["precursor_mz"],
include_scores=["cosine", "modcosine"],
ignore_non_annotated=False,
intensity_weighting_power=0.5,
allowed_missing_percentage=5.0,
cosine_tol=2.0,
mass_tolerance=2.0,
mass_tolerance_type="Dalton")
scores_cosine = found_matches[0].values[:,0]
expected_scores_cosine = np.array([0.05312127152597306, 0.0, 0.0])
scores_modcos = found_matches[0].values[:,2]
expected_scores_modcos = np.array([0.05312127152597306, 0.0, 0.7757282939050968])
assert list(scores_cosine) == [pytest.approx(x, 1e-6) for x in expected_scores_cosine], \
"Expected different scores."
assert list(scores_modcos) == [pytest.approx(x, 1e-6) for x in expected_scores_modcos], \
"Expected different mod. cosine scores."
assert np.all(found_matches[0].values[:,3] == np.array([1, 0, 2])), \
"Expected different number of matches"
assert np.all(found_matches[0].values[:,4]), "Expected all mass matches to be True"
|
[
"matchmsextras.library_search.library_matching",
"os.getcwd",
"spec2vec.SpectrumDocument",
"numpy.array",
"pytest.approx",
"os.path.join",
"numpy.all"
] |
[((180, 191), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (189, 191), False, 'import os\n'), ((212, 252), 'os.path.join', 'os.path.join', (['path_root', '"""matchmsextras"""'], {}), "(path_root, 'matchmsextras')\n", (224, 252), False, 'import os\n'), ((1240, 1554), 'matchmsextras.library_search.library_matching', 'library_matching', (['documents_query', 'documents_library'], {'model': 'None', 'presearch_based_on': "['precursor_mz']", 'include_scores': "['cosine', 'modcosine']", 'ignore_non_annotated': '(False)', 'intensity_weighting_power': '(0.5)', 'allowed_missing_percentage': '(5.0)', 'cosine_tol': '(2.0)', 'mass_tolerance': '(2.0)', 'mass_tolerance_type': '"""Dalton"""'}), "(documents_query, documents_library, model=None,\n presearch_based_on=['precursor_mz'], include_scores=['cosine',\n 'modcosine'], ignore_non_annotated=False, intensity_weighting_power=0.5,\n allowed_missing_percentage=5.0, cosine_tol=2.0, mass_tolerance=2.0,\n mass_tolerance_type='Dalton')\n", (1256, 1554), False, 'from matchmsextras.library_search import library_matching\n'), ((1951, 1992), 'numpy.array', 'np.array', (['[0.05312127152597306, 0.0, 0.0]'], {}), '([0.05312127152597306, 0.0, 0.0])\n', (1959, 1992), True, 'import numpy as np\n'), ((2071, 2127), 'numpy.array', 'np.array', (['[0.05312127152597306, 0.0, 0.7757282939050968]'], {}), '([0.05312127152597306, 0.0, 0.7757282939050968])\n', (2079, 2127), True, 'import numpy as np\n'), ((2534, 2571), 'numpy.all', 'np.all', (['found_matches[0].values[:, 4]'], {}), '(found_matches[0].values[:, 4])\n', (2540, 2571), True, 'import numpy as np\n'), ((1100, 1119), 'spec2vec.SpectrumDocument', 'SpectrumDocument', (['s'], {}), '(s)\n', (1116, 1119), False, 'from spec2vec import SpectrumDocument\n'), ((1190, 1218), 'spec2vec.SpectrumDocument', 'SpectrumDocument', (['spectrum_4'], {}), '(spectrum_4)\n', (1206, 1218), False, 'from spec2vec import SpectrumDocument\n'), ((372, 399), 'numpy.array', 'np.array', (['[100, 150, 200.0]'], {}), '([100, 150, 200.0])\n', (380, 399), True, 'import numpy as np\n'), ((438, 463), 'numpy.array', 'np.array', (['[0.7, 0.2, 0.1]'], {}), '([0.7, 0.2, 0.1])\n', (446, 463), True, 'import numpy as np\n'), ((554, 581), 'numpy.array', 'np.array', (['[100, 140, 190.0]'], {}), '([100, 140, 190.0])\n', (562, 581), True, 'import numpy as np\n'), ((620, 645), 'numpy.array', 'np.array', (['[0.4, 0.2, 0.1]'], {}), '([0.4, 0.2, 0.1])\n', (628, 645), True, 'import numpy as np\n'), ((737, 764), 'numpy.array', 'np.array', (['[100, 140, 190.0]'], {}), '([100, 140, 190.0])\n', (745, 764), True, 'import numpy as np\n'), ((803, 828), 'numpy.array', 'np.array', (['[0.3, 0.5, 0.2]'], {}), '([0.3, 0.5, 0.2])\n', (811, 828), True, 'import numpy as np\n'), ((919, 949), 'numpy.array', 'np.array', (['[97.5, 137.5, 200.0]'], {}), '([97.5, 137.5, 200.0])\n', (927, 949), True, 'import numpy as np\n'), ((988, 1013), 'numpy.array', 'np.array', (['[0.8, 0.5, 0.4]'], {}), '([0.8, 0.5, 0.4])\n', (996, 1013), True, 'import numpy as np\n'), ((2163, 2186), 'pytest.approx', 'pytest.approx', (['x', '(1e-06)'], {}), '(x, 1e-06)\n', (2176, 2186), False, 'import pytest\n'), ((2294, 2317), 'pytest.approx', 'pytest.approx', (['x', '(1e-06)'], {}), '(x, 1e-06)\n', (2307, 2317), False, 'import pytest\n'), ((2452, 2471), 'numpy.array', 'np.array', (['[1, 0, 2]'], {}), '([1, 0, 2])\n', (2460, 2471), True, 'import numpy as np\n')]
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Unit Tests
__author__: <NAME>, <NAME>, <NAME>
"""
import os
import sys
import unittest
import numpy as np
from scipy.io import loadmat
sys.path.append(".")
from inferactively.distributions import Categorical, Dirichlet # nopep8
class TestDirichlet(unittest.TestCase):
def test_init_empty(self):
d = Dirichlet()
self.assertEqual(d.ndim, 2)
def test_init_overload(self):
with self.assertRaises(ValueError):
values = np.random.rand(3, 2)
_ = Dirichlet(dims=2, values=values)
def test_float_conversion(self):
values = np.array([2, 3])
self.assertEqual(values.dtype, np.int)
d = Dirichlet(values=values)
self.assertEqual(d.values.dtype, np.float64)
def test_init_dims_expand(self):
d = Dirichlet(dims=[5])
self.assertEqual(d.shape, (5, 1))
def test_init_dims_int_expand(self):
d = Dirichlet(dims=5)
self.assertEqual(d.shape, (5, 1))
def test_multi_factor_init_dims(self):
d = Dirichlet(dims=[[5, 4], [4, 3]])
self.assertEqual(d.shape, (2,))
self.assertEqual(d[0].shape, (5, 4))
self.assertEqual(d[1].shape, (4, 3))
def test_multi_factor_init_values(self):
values_1 = np.random.rand(5, 4)
values_2 = np.random.rand(4, 3)
values = np.array([values_1, values_2])
d = Dirichlet(values=values)
self.assertEqual(d.shape, (2,))
self.assertEqual(d[0].shape, (5, 4))
self.assertEqual(d[1].shape, (4, 3))
def test_multi_factor_init_values_expand(self):
values_1 = np.random.rand(5)
values_2 = np.random.rand(4)
values = np.array([values_1, values_2])
d = Dirichlet(values=values)
self.assertEqual(d.shape, (2,))
self.assertEqual(d[0].shape, (5, 1))
self.assertEqual(d[1].shape, (4, 1))
def test_normalize_multi_factor(self):
values_1 = np.random.rand(5)
values_2 = np.random.rand(4, 3)
values = np.array([values_1, values_2])
d = Dirichlet(values=values)
normed = Categorical(values=d.mean(return_numpy=True))
self.assertTrue(normed.is_normalized())
def test_normalize_single_dim(self):
values = np.array([1.0, 1.0])
d = Dirichlet(values=values)
expected_values = np.array([[0.5], [0.5]])
self.assertTrue(np.array_equal(d.mean(return_numpy=True), expected_values))
def test_normalize_two_dim(self):
values = np.array([[1.0, 1.0], [1.0, 1.0]])
d = Dirichlet(values=values)
expected_values = np.array([[0.5, 0.5], [0.5, 0.5]])
self.assertTrue(np.array_equal(d.mean(return_numpy=True), expected_values))
def test_remove_zeros(self):
values = np.array([[1.0, 0.0], [1.0, 1.0]])
d = Dirichlet(values=values)
self.assertTrue((d.values == 0.0).any())
d.remove_zeros()
self.assertFalse((d.values == 0.0).any())
def test_contains_zeros(self):
values = np.array([[1.0, 0.0], [1.0, 1.0]])
d = Dirichlet(values=values)
self.assertTrue(d.contains_zeros())
values = np.array([[1.0, 1.0], [1.0, 1.0]])
d = Dirichlet(values=values)
self.assertFalse(d.contains_zeros())
"""
def test_entropy(self):
values = np.random.rand(3, 2)
entropy = -np.sum(values * np.log(values), 0)
d = Dirichlet(values=values)
self.assertTrue(np.array_equal(d.entropy(return_numpy=True), entropy))
"""
def test_log(self):
values = np.random.rand(3, 2)
log_values = np.log(values)
d = Dirichlet(values=values)
self.assertTrue(np.array_equal(d.log(return_numpy=True), log_values))
def test_copy(self):
values = np.random.rand(3, 2)
d = Dirichlet(values=values)
d_copy = d.copy()
self.assertTrue(np.array_equal(d_copy.values, d.values))
d_copy.values = d_copy.values * 2
self.assertFalse(np.array_equal(d_copy.values, d.values))
def test_ndim(self):
values = np.random.rand(3, 2)
d = Dirichlet(values=values)
self.assertEqual(d.ndim, d.values.ndim)
def test_shape(self):
values = np.random.rand(3, 2)
d = Dirichlet(values=values)
self.assertEqual(d.shape, (3, 2))
def test_expectation_single_factor(self):
""" tests implementation of expect_log method against matlab version (single factor)
"""
array_path = os.path.join(os.getcwd(), "tests/data/wnorm_a.mat")
mat_contents = loadmat(file_name=array_path)
result = mat_contents["result"]
d = Dirichlet(values=mat_contents["A"])
result_py = d.expectation_of_log(return_numpy=True)
self.assertTrue(np.isclose(result, result_py).all())
def test_expectation_multi_factor(self):
""" tests implementation of expect_log method against matlab version (multi factor)
"""
array_path = os.path.join(os.getcwd(), "tests/data/wnorm_b.mat")
mat_contents = loadmat(file_name=array_path)
result_1 = mat_contents["result_1"]
result_2 = mat_contents["result_2"]
d = Dirichlet(values=mat_contents["A"][0])
result_py = d.expectation_of_log(return_numpy=True)
self.assertTrue(
np.isclose(result_1, result_py[0]).all() and np.isclose(result_2, result_py[1]).all()
)
if __name__ == "__main__":
unittest.main()
|
[
"sys.path.append",
"unittest.main",
"numpy.array_equal",
"numpy.log",
"scipy.io.loadmat",
"inferactively.distributions.Dirichlet",
"os.getcwd",
"numpy.isclose",
"numpy.array",
"numpy.random.rand"
] |
[((189, 209), 'sys.path.append', 'sys.path.append', (['"""."""'], {}), "('.')\n", (204, 209), False, 'import sys\n'), ((5509, 5524), 'unittest.main', 'unittest.main', ([], {}), '()\n', (5522, 5524), False, 'import unittest\n'), ((368, 379), 'inferactively.distributions.Dirichlet', 'Dirichlet', ([], {}), '()\n', (377, 379), False, 'from inferactively.distributions import Categorical, Dirichlet\n'), ((641, 657), 'numpy.array', 'np.array', (['[2, 3]'], {}), '([2, 3])\n', (649, 657), True, 'import numpy as np\n'), ((717, 741), 'inferactively.distributions.Dirichlet', 'Dirichlet', ([], {'values': 'values'}), '(values=values)\n', (726, 741), False, 'from inferactively.distributions import Categorical, Dirichlet\n'), ((845, 864), 'inferactively.distributions.Dirichlet', 'Dirichlet', ([], {'dims': '[5]'}), '(dims=[5])\n', (854, 864), False, 'from inferactively.distributions import Categorical, Dirichlet\n'), ((961, 978), 'inferactively.distributions.Dirichlet', 'Dirichlet', ([], {'dims': '(5)'}), '(dims=5)\n', (970, 978), False, 'from inferactively.distributions import Categorical, Dirichlet\n'), ((1077, 1109), 'inferactively.distributions.Dirichlet', 'Dirichlet', ([], {'dims': '[[5, 4], [4, 3]]'}), '(dims=[[5, 4], [4, 3]])\n', (1086, 1109), False, 'from inferactively.distributions import Categorical, Dirichlet\n'), ((1305, 1325), 'numpy.random.rand', 'np.random.rand', (['(5)', '(4)'], {}), '(5, 4)\n', (1319, 1325), True, 'import numpy as np\n'), ((1345, 1365), 'numpy.random.rand', 'np.random.rand', (['(4)', '(3)'], {}), '(4, 3)\n', (1359, 1365), True, 'import numpy as np\n'), ((1383, 1413), 'numpy.array', 'np.array', (['[values_1, values_2]'], {}), '([values_1, values_2])\n', (1391, 1413), True, 'import numpy as np\n'), ((1426, 1450), 'inferactively.distributions.Dirichlet', 'Dirichlet', ([], {'values': 'values'}), '(values=values)\n', (1435, 1450), False, 'from inferactively.distributions import Categorical, Dirichlet\n'), ((1653, 1670), 'numpy.random.rand', 'np.random.rand', (['(5)'], {}), '(5)\n', (1667, 1670), True, 'import numpy as np\n'), ((1690, 1707), 'numpy.random.rand', 'np.random.rand', (['(4)'], {}), '(4)\n', (1704, 1707), True, 'import numpy as np\n'), ((1725, 1755), 'numpy.array', 'np.array', (['[values_1, values_2]'], {}), '([values_1, values_2])\n', (1733, 1755), True, 'import numpy as np\n'), ((1768, 1792), 'inferactively.distributions.Dirichlet', 'Dirichlet', ([], {'values': 'values'}), '(values=values)\n', (1777, 1792), False, 'from inferactively.distributions import Categorical, Dirichlet\n'), ((1986, 2003), 'numpy.random.rand', 'np.random.rand', (['(5)'], {}), '(5)\n', (2000, 2003), True, 'import numpy as np\n'), ((2023, 2043), 'numpy.random.rand', 'np.random.rand', (['(4)', '(3)'], {}), '(4, 3)\n', (2037, 2043), True, 'import numpy as np\n'), ((2061, 2091), 'numpy.array', 'np.array', (['[values_1, values_2]'], {}), '([values_1, values_2])\n', (2069, 2091), True, 'import numpy as np\n'), ((2104, 2128), 'inferactively.distributions.Dirichlet', 'Dirichlet', ([], {'values': 'values'}), '(values=values)\n', (2113, 2128), False, 'from inferactively.distributions import Categorical, Dirichlet\n'), ((2299, 2319), 'numpy.array', 'np.array', (['[1.0, 1.0]'], {}), '([1.0, 1.0])\n', (2307, 2319), True, 'import numpy as np\n'), ((2332, 2356), 'inferactively.distributions.Dirichlet', 'Dirichlet', ([], {'values': 'values'}), '(values=values)\n', (2341, 2356), False, 'from inferactively.distributions import Categorical, Dirichlet\n'), ((2383, 2407), 'numpy.array', 'np.array', (['[[0.5], [0.5]]'], {}), '([[0.5], [0.5]])\n', (2391, 2407), True, 'import numpy as np\n'), ((2548, 2582), 'numpy.array', 'np.array', (['[[1.0, 1.0], [1.0, 1.0]]'], {}), '([[1.0, 1.0], [1.0, 1.0]])\n', (2556, 2582), True, 'import numpy as np\n'), ((2595, 2619), 'inferactively.distributions.Dirichlet', 'Dirichlet', ([], {'values': 'values'}), '(values=values)\n', (2604, 2619), False, 'from inferactively.distributions import Categorical, Dirichlet\n'), ((2646, 2680), 'numpy.array', 'np.array', (['[[0.5, 0.5], [0.5, 0.5]]'], {}), '([[0.5, 0.5], [0.5, 0.5]])\n', (2654, 2680), True, 'import numpy as np\n'), ((2816, 2850), 'numpy.array', 'np.array', (['[[1.0, 0.0], [1.0, 1.0]]'], {}), '([[1.0, 0.0], [1.0, 1.0]])\n', (2824, 2850), True, 'import numpy as np\n'), ((2863, 2887), 'inferactively.distributions.Dirichlet', 'Dirichlet', ([], {'values': 'values'}), '(values=values)\n', (2872, 2887), False, 'from inferactively.distributions import Categorical, Dirichlet\n'), ((3065, 3099), 'numpy.array', 'np.array', (['[[1.0, 0.0], [1.0, 1.0]]'], {}), '([[1.0, 0.0], [1.0, 1.0]])\n', (3073, 3099), True, 'import numpy as np\n'), ((3112, 3136), 'inferactively.distributions.Dirichlet', 'Dirichlet', ([], {'values': 'values'}), '(values=values)\n', (3121, 3136), False, 'from inferactively.distributions import Categorical, Dirichlet\n'), ((3198, 3232), 'numpy.array', 'np.array', (['[[1.0, 1.0], [1.0, 1.0]]'], {}), '([[1.0, 1.0], [1.0, 1.0]])\n', (3206, 3232), True, 'import numpy as np\n'), ((3245, 3269), 'inferactively.distributions.Dirichlet', 'Dirichlet', ([], {'values': 'values'}), '(values=values)\n', (3254, 3269), False, 'from inferactively.distributions import Categorical, Dirichlet\n'), ((3611, 3631), 'numpy.random.rand', 'np.random.rand', (['(3)', '(2)'], {}), '(3, 2)\n', (3625, 3631), True, 'import numpy as np\n'), ((3653, 3667), 'numpy.log', 'np.log', (['values'], {}), '(values)\n', (3659, 3667), True, 'import numpy as np\n'), ((3680, 3704), 'inferactively.distributions.Dirichlet', 'Dirichlet', ([], {'values': 'values'}), '(values=values)\n', (3689, 3704), False, 'from inferactively.distributions import Categorical, Dirichlet\n'), ((3826, 3846), 'numpy.random.rand', 'np.random.rand', (['(3)', '(2)'], {}), '(3, 2)\n', (3840, 3846), True, 'import numpy as np\n'), ((3859, 3883), 'inferactively.distributions.Dirichlet', 'Dirichlet', ([], {'values': 'values'}), '(values=values)\n', (3868, 3883), False, 'from inferactively.distributions import Categorical, Dirichlet\n'), ((4126, 4146), 'numpy.random.rand', 'np.random.rand', (['(3)', '(2)'], {}), '(3, 2)\n', (4140, 4146), True, 'import numpy as np\n'), ((4159, 4183), 'inferactively.distributions.Dirichlet', 'Dirichlet', ([], {'values': 'values'}), '(values=values)\n', (4168, 4183), False, 'from inferactively.distributions import Categorical, Dirichlet\n'), ((4276, 4296), 'numpy.random.rand', 'np.random.rand', (['(3)', '(2)'], {}), '(3, 2)\n', (4290, 4296), True, 'import numpy as np\n'), ((4309, 4333), 'inferactively.distributions.Dirichlet', 'Dirichlet', ([], {'values': 'values'}), '(values=values)\n', (4318, 4333), False, 'from inferactively.distributions import Categorical, Dirichlet\n'), ((4625, 4654), 'scipy.io.loadmat', 'loadmat', ([], {'file_name': 'array_path'}), '(file_name=array_path)\n', (4632, 4654), False, 'from scipy.io import loadmat\n'), ((4708, 4743), 'inferactively.distributions.Dirichlet', 'Dirichlet', ([], {'values': "mat_contents['A']"}), "(values=mat_contents['A'])\n", (4717, 4743), False, 'from inferactively.distributions import Categorical, Dirichlet\n'), ((5112, 5141), 'scipy.io.loadmat', 'loadmat', ([], {'file_name': 'array_path'}), '(file_name=array_path)\n', (5119, 5141), False, 'from scipy.io import loadmat\n'), ((5243, 5281), 'inferactively.distributions.Dirichlet', 'Dirichlet', ([], {'values': "mat_contents['A'][0]"}), "(values=mat_contents['A'][0])\n", (5252, 5281), False, 'from inferactively.distributions import Categorical, Dirichlet\n'), ((516, 536), 'numpy.random.rand', 'np.random.rand', (['(3)', '(2)'], {}), '(3, 2)\n', (530, 536), True, 'import numpy as np\n'), ((553, 585), 'inferactively.distributions.Dirichlet', 'Dirichlet', ([], {'dims': '(2)', 'values': 'values'}), '(dims=2, values=values)\n', (562, 585), False, 'from inferactively.distributions import Categorical, Dirichlet\n'), ((3934, 3973), 'numpy.array_equal', 'np.array_equal', (['d_copy.values', 'd.values'], {}), '(d_copy.values, d.values)\n', (3948, 3973), True, 'import numpy as np\n'), ((4042, 4081), 'numpy.array_equal', 'np.array_equal', (['d_copy.values', 'd.values'], {}), '(d_copy.values, d.values)\n', (4056, 4081), True, 'import numpy as np\n'), ((4563, 4574), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (4572, 4574), False, 'import os\n'), ((5050, 5061), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (5059, 5061), False, 'import os\n'), ((4828, 4857), 'numpy.isclose', 'np.isclose', (['result', 'result_py'], {}), '(result, result_py)\n', (4838, 4857), True, 'import numpy as np\n'), ((5380, 5414), 'numpy.isclose', 'np.isclose', (['result_1', 'result_py[0]'], {}), '(result_1, result_py[0])\n', (5390, 5414), True, 'import numpy as np\n'), ((5425, 5459), 'numpy.isclose', 'np.isclose', (['result_2', 'result_py[1]'], {}), '(result_2, result_py[1])\n', (5435, 5459), True, 'import numpy as np\n')]
|
from glob import glob
import cv2
import os
import sys
import yaml
import matplotlib as mpl
import numpy as np
from skimage.io import imread
import matplotlib.pyplot as plt
from ellipses import LSqEllipse # The code is pulled from https://github.com/bdhammel/least-squares-ellipse-fitting
import time
# This annotation script is written by <NAME> and <NAME> inspired by DeepVog repo by <NAME>
def _get_annotation_path_from_image_path(image_file_name, path, eye_part):
# print('get txt file name: ', path + image_file_name + eye_part + '.txt')
return path + image_file_name + eye_part + '.txt'
def fit_pupil(image_path, saving_directory, curr_image_number, plot=False, write_annotation=False, eye_part='pupil'):
# Mouse enumeration for development use only
# Todo: Remove this after we're done with the design
'''
BACK = 8
FORWARD = 9
LEFT = 1
MIDDLE = 2
RIGHT = 3
'''
upper_color = 'purple'
lower_color = 'green'
if 'pupil' in eye_part:
point_color = 'yellow'
fill_color = 'orange'
elif 'iris' in eye_part:
point_color = 'blue'
fill_color = 'cyan'
elif 'upper' in eye_part:
point_color = 'purple'
fill_color = 'grey'
elif 'lower' in eye_part:
point_color = 'green'
fill_color = 'white'
base = os.path.basename(image_path)
image_file_name = os.path.splitext(base)[0]
result = 'success'
while True:
plt.ion()
fig, ax = plt.subplots(figsize=(15, 15))
img = imread(image_path)
ax.set_title('Annotating {} for ID:{}\n File Name:{}'.format(eye_part.replace('_',''),curr_image_number, os.path.basename(image_path)))
ax.imshow(img, cmap='gray')
ax.set_xlim(-20, 420)
ax.set_ylim(-20, 420)
if 'upper' in eye_part or 'lower' in eye_part:
if 'upper' in eye_part:
annotated_text_file_name = _get_annotation_path_from_image_path(image_file_name, saving_directory,
'_lower')
my_color = lower_color
elif 'lower' in eye_part:
annotated_text_file_name = _get_annotation_path_from_image_path(image_file_name, saving_directory,
'_upper')
my_color = upper_color
if os.path.exists(annotated_text_file_name):
with open(annotated_text_file_name.replace(".txt", "_points.txt")) as f:
w, h = [x for x in next(f).split()] # read first line
array = []
for line in f: # read rest of lines
array.append([np.float(x) for x in line.split(',')])
previous_x = [np.float(x[0]) for x in array]
previous_y = [np.float(x[1]) for x in array]
ax.plot(previous_x, previous_y, c=my_color, marker='x')
key_points = plt.ginput(-1, mouse_pop=2, mouse_stop=3,
timeout=-1) # If negative, accumulate clicks until the input is terminated manually.
points_x = [x[0] for x in key_points]
points_y = [x[1] for x in key_points]
if not key_points:
plt.close()
result = 'proceed'
break
if 'pupil' in eye_part or 'iris' in eye_part:
fitted = LSqEllipse()
fitted.fit([points_x, points_y])
center_coord, width, height, angle = fitted.parameters()
axes = np.array([width, height])
angle = np.rad2deg(angle)
elif 'upper' in eye_part or 'lower' in eye_part:
poly = np.poly1d(np.polyfit(points_x, points_y, 4))
print("\npoly calculated:", poly)
print('\n')
if write_annotation:
annotated_text_file_name = _get_annotation_path_from_image_path(image_file_name, saving_directory,
eye_part)
with open(annotated_text_file_name, 'w+') as f:
# if all([c <= 50 for c in center_coord]):
# points_str = '-1:-1'
# else:
if 'pupil' in eye_part or 'iris' in eye_part:
points_str = '{}, {}'.format(center_coord[0], center_coord[1])
f.write(points_str)
elif 'upper' in eye_part or 'lower' in eye_part:
f.write('{}, {}\n'.format(min(points_x), points_y[np.argmin(points_x)]))
print("The left most eyelid point: {:.2f} {:.2f}".format(min(points_x), points_y[np.argmin(points_x)]))
f.write('{}, {}\n'.format(max(points_x), points_y[np.argmax(points_x)]))
print("The right most eyelid point: {:.2f} {:.2f}".format(max(points_x), points_y[np.argmax(points_x)]))
with open(annotated_text_file_name.replace(".txt","_points.txt"), 'w+') as f: # For detecting selected
for point in key_points:
f.write('{}, {}\n'.format(point[0], point[1]))
if plot:
all_x = [x[0] for x in key_points]
all_y = [x[1] for x in key_points]
plt.scatter(x=all_x, y=all_y, c=point_color, marker='x')
if 'pupil' in eye_part or 'iris' in eye_part:
ell = mpl.patches.Ellipse(xy=center_coord, width=axes[0] * 2,
height=axes[1] * 2, angle=angle, fill=True, color=fill_color, alpha=0.4)
ax.add_artist(ell)
elif 'upper' in eye_part or 'lower' in eye_part:
for my_x in np.arange(min(points_x), max(points_x), 1):
my_y = poly(my_x)
plt.plot(my_x, my_y, c=point_color, marker='o')
output_image_file = saving_directory + image_file_name + eye_part + "_ellipse.png"
fig.savefig(output_image_file)
print("saved: ", os.path.basename(output_image_file))
print('\n')
plt.show()
confirmation_point = plt.ginput(1, timeout=-1, mouse_add=3, mouse_stop=3)
plt.close()
if len(confirmation_point) == 0:
break
# Hacky way to read the q press to quit the loop otherwise the QT doesn't let go of the thread
# TODO: gracefully stop the tool
time.sleep(.01)
answer = input("")
print('q pressed!!', answer)
if answer == 'q':
print("\n\nQuiting the Annotation tool!")
result = 'quit'
# plt.ioff()
# plt.close()
# sys.exit(0)
break
return result
def annotate(image_directory, saving_directory, eye_part='pupil'):
images_paths = sorted(glob(os.path.join(image_directory, '*png')))
# imag_paths = sorted(glob(os.path.join(base_dir, '*jpg')))
annotation_paths = glob(os.path.join(saving_directory, '*txt'))
i = 0
for image_path in images_paths:
print("Running Annotation for: {} ID: {}/{}".format(os.path.basename(image_path), i, len(images_paths)))
base = os.path.basename(image_path)
image_file_name = os.path.splitext(base)[0]
annotated_text_file_name = _get_annotation_path_from_image_path(image_file_name, saving_directory, eye_part)
if annotated_text_file_name in annotation_paths:
print("Found the existing txt file for: ", os.path.basename(annotated_text_file_name))
else:
result = fit_pupil(image_path=image_path, saving_directory=saving_directory, curr_image_number=i, plot=True, write_annotation=True, eye_part=eye_part)
if result == 'quit':
print("\n\nQuit!!\n\n")
break
i = i + 1
def parse_pipeline_parameters(parameters_fpath):
param_dict = dict()
with open(parameters_fpath, "r") as stream:
param_dict = yaml.safe_load(stream)
return param_dict
if __name__ == '__main__':
plt = mpl.pyplot
fig = plt.figure()
# mpl.rcParams["savefig.directory"] = os.chdir(
# os.path.dirname('/home/kamran/Downloads/eye_image_annotation_results/'))
# File Path for the yaml file
parameters_fpath = os.getcwd() + "/annotation_parameters.yaml"
param_dict = parse_pipeline_parameters(parameters_fpath)
image_directory = param_dict['directory']['image_directory']
saving_directory = param_dict['directory']['saving_directory']
eye_part = param_dict['annotation']['eye_part']
print(param_dict)
print(eye_part)
if 'pupil' in eye_part:
eye_part = 'pupil'
elif 'iris' in eye_part:
eye_part = 'iris'
elif 'upper' in eye_part:
eye_part = 'upper'
elif 'lower' in eye_part:
eye_part = 'lower'
else:
raise ValueError("Wrong Eye Part for Annotation!!!")
annotate(image_directory=image_directory, saving_directory=saving_directory, eye_part='_' + eye_part)
sys.exit(0)
|
[
"numpy.polyfit",
"numpy.argmax",
"numpy.argmin",
"matplotlib.pyplot.figure",
"yaml.safe_load",
"os.path.join",
"matplotlib.pyplot.close",
"os.path.exists",
"ellipses.LSqEllipse",
"matplotlib.pyplot.subplots",
"skimage.io.imread",
"matplotlib.pyplot.show",
"os.path.basename",
"numpy.float",
"time.sleep",
"matplotlib.pyplot.ion",
"matplotlib.pyplot.ginput",
"matplotlib.patches.Ellipse",
"sys.exit",
"matplotlib.pyplot.plot",
"os.getcwd",
"matplotlib.pyplot.scatter",
"numpy.rad2deg",
"numpy.array",
"os.path.splitext"
] |
[((1337, 1365), 'os.path.basename', 'os.path.basename', (['image_path'], {}), '(image_path)\n', (1353, 1365), False, 'import os\n'), ((8092, 8104), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (8102, 8104), True, 'import matplotlib.pyplot as plt\n'), ((9034, 9045), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (9042, 9045), False, 'import sys\n'), ((1388, 1410), 'os.path.splitext', 'os.path.splitext', (['base'], {}), '(base)\n', (1404, 1410), False, 'import os\n'), ((1461, 1470), 'matplotlib.pyplot.ion', 'plt.ion', ([], {}), '()\n', (1468, 1470), True, 'import matplotlib.pyplot as plt\n'), ((1489, 1519), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(15, 15)'}), '(figsize=(15, 15))\n', (1501, 1519), True, 'import matplotlib.pyplot as plt\n'), ((1534, 1552), 'skimage.io.imread', 'imread', (['image_path'], {}), '(image_path)\n', (1540, 1552), False, 'from skimage.io import imread\n'), ((3013, 3066), 'matplotlib.pyplot.ginput', 'plt.ginput', (['(-1)'], {'mouse_pop': '(2)', 'mouse_stop': '(3)', 'timeout': '(-1)'}), '(-1, mouse_pop=2, mouse_stop=3, timeout=-1)\n', (3023, 3066), True, 'import matplotlib.pyplot as plt\n'), ((6452, 6468), 'time.sleep', 'time.sleep', (['(0.01)'], {}), '(0.01)\n', (6462, 6468), False, 'import time\n'), ((6985, 7023), 'os.path.join', 'os.path.join', (['saving_directory', '"""*txt"""'], {}), "(saving_directory, '*txt')\n", (6997, 7023), False, 'import os\n'), ((7199, 7227), 'os.path.basename', 'os.path.basename', (['image_path'], {}), '(image_path)\n', (7215, 7227), False, 'import os\n'), ((7987, 8009), 'yaml.safe_load', 'yaml.safe_load', (['stream'], {}), '(stream)\n', (8001, 8009), False, 'import yaml\n'), ((8298, 8309), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (8307, 8309), False, 'import os\n'), ((2426, 2466), 'os.path.exists', 'os.path.exists', (['annotated_text_file_name'], {}), '(annotated_text_file_name)\n', (2440, 2466), False, 'import os\n'), ((3304, 3315), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (3313, 3315), True, 'import matplotlib.pyplot as plt\n'), ((3440, 3452), 'ellipses.LSqEllipse', 'LSqEllipse', ([], {}), '()\n', (3450, 3452), False, 'from ellipses import LSqEllipse\n'), ((3586, 3611), 'numpy.array', 'np.array', (['[width, height]'], {}), '([width, height])\n', (3594, 3611), True, 'import numpy as np\n'), ((3632, 3649), 'numpy.rad2deg', 'np.rad2deg', (['angle'], {}), '(angle)\n', (3642, 3649), True, 'import numpy as np\n'), ((5288, 5344), 'matplotlib.pyplot.scatter', 'plt.scatter', ([], {'x': 'all_x', 'y': 'all_y', 'c': 'point_color', 'marker': '"""x"""'}), "(x=all_x, y=all_y, c=point_color, marker='x')\n", (5299, 5344), True, 'import matplotlib.pyplot as plt\n'), ((6112, 6122), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6120, 6122), True, 'import matplotlib.pyplot as plt\n'), ((6156, 6208), 'matplotlib.pyplot.ginput', 'plt.ginput', (['(1)'], {'timeout': '(-1)', 'mouse_add': '(3)', 'mouse_stop': '(3)'}), '(1, timeout=-1, mouse_add=3, mouse_stop=3)\n', (6166, 6208), True, 'import matplotlib.pyplot as plt\n'), ((6221, 6232), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (6230, 6232), True, 'import matplotlib.pyplot as plt\n'), ((6853, 6890), 'os.path.join', 'os.path.join', (['image_directory', '"""*png"""'], {}), "(image_directory, '*png')\n", (6865, 6890), False, 'import os\n'), ((7254, 7276), 'os.path.splitext', 'os.path.splitext', (['base'], {}), '(base)\n', (7270, 7276), False, 'import os\n'), ((1666, 1694), 'os.path.basename', 'os.path.basename', (['image_path'], {}), '(image_path)\n', (1682, 1694), False, 'import os\n'), ((5426, 5558), 'matplotlib.patches.Ellipse', 'mpl.patches.Ellipse', ([], {'xy': 'center_coord', 'width': '(axes[0] * 2)', 'height': '(axes[1] * 2)', 'angle': 'angle', 'fill': '(True)', 'color': 'fill_color', 'alpha': '(0.4)'}), '(xy=center_coord, width=axes[0] * 2, height=axes[1] * 2,\n angle=angle, fill=True, color=fill_color, alpha=0.4)\n', (5445, 5558), True, 'import matplotlib as mpl\n'), ((6039, 6074), 'os.path.basename', 'os.path.basename', (['output_image_file'], {}), '(output_image_file)\n', (6055, 6074), False, 'import os\n'), ((7131, 7159), 'os.path.basename', 'os.path.basename', (['image_path'], {}), '(image_path)\n', (7147, 7159), False, 'import os\n'), ((7509, 7551), 'os.path.basename', 'os.path.basename', (['annotated_text_file_name'], {}), '(annotated_text_file_name)\n', (7525, 7551), False, 'import os\n'), ((2827, 2841), 'numpy.float', 'np.float', (['x[0]'], {}), '(x[0])\n', (2835, 2841), True, 'import numpy as np\n'), ((2888, 2902), 'numpy.float', 'np.float', (['x[1]'], {}), '(x[1])\n', (2896, 2902), True, 'import numpy as np\n'), ((3736, 3769), 'numpy.polyfit', 'np.polyfit', (['points_x', 'points_y', '(4)'], {}), '(points_x, points_y, 4)\n', (3746, 3769), True, 'import numpy as np\n'), ((5823, 5870), 'matplotlib.pyplot.plot', 'plt.plot', (['my_x', 'my_y'], {'c': 'point_color', 'marker': '"""o"""'}), "(my_x, my_y, c=point_color, marker='o')\n", (5831, 5870), True, 'import matplotlib.pyplot as plt\n'), ((2758, 2769), 'numpy.float', 'np.float', (['x'], {}), '(x)\n', (2766, 2769), True, 'import numpy as np\n'), ((4574, 4593), 'numpy.argmin', 'np.argmin', (['points_x'], {}), '(points_x)\n', (4583, 4593), True, 'import numpy as np\n'), ((4698, 4717), 'numpy.argmin', 'np.argmin', (['points_x'], {}), '(points_x)\n', (4707, 4717), True, 'import numpy as np\n'), ((4791, 4810), 'numpy.argmax', 'np.argmax', (['points_x'], {}), '(points_x)\n', (4800, 4810), True, 'import numpy as np\n'), ((4916, 4935), 'numpy.argmax', 'np.argmax', (['points_x'], {}), '(points_x)\n', (4925, 4935), True, 'import numpy as np\n')]
|
import numpy as np
from math import log10
from math import sqrt
import time
import networkx as nx
import matplotlib.pyplot as plt
import pydot
import csv
class Graph(object):
def __init__(self):
self.root = None #root/source node is the start of the graph/tree and multicast source
self.nodes = []
self.leaves = []
class Node(object):
def __init__(self):
self.father = None #node's parent
self.id = None #ID of node
self.data = [] # tcpdump of the multicast packets of the end-nodes (and only end-nodes, internal nodes do not have data)
self.children = []
#In Packet Loss, we only care about the packet ID
def GetLinkLossDumps():
#Tcpdumps of source node stored at root.data
tcpfile = [line.rstrip('\n') for line in open('dumps/n1.txt')] #opens the tcpdump as a list of strings, we suppose that source connects only to one router to the rest of tree
for line in range(len(tcpfile)):
if "tos 0x7" in tcpfile[line]: # tos 0x7 is the characteristic I chose to distinguish my UDP packets used for tomography
temp = tcpfile[line].split()
graph.root.data.append(int(temp[7].replace(",",""))) #We keep only the packet ID
#tcpdump of every leave/destination node stored at node.data
for i in range(len(graph.leaves)):
filename = "dumps/n%d.txt" % (graph.leaves[i].id) #example tcpdump file path "thesisdumps/1/n1" if node 1 is a leaf
tcpfile = [line.rstrip('\n') for line in open(filename)]
for line in range(len(tcpfile)):
if "tos 0x7" in tcpfile[line]: # tos 0x7 is the characteristic I chose to distinguish my UDP packets used for tomography
temp = tcpfile[line].split()
graph.leaves[i].data.append(int(temp[7].replace(",",""))) #We keep only the packet ID
#In Link Delay and Utilization, we need both the packet ID and the timestamp of the packet
def GetLinkDelayDumps():
#Tcpdumps of source node stored at root.data
tcpfile = [line.rstrip('\n') for line in open('dumps/n1.txt')] #opens the tcpdump as a list of strings, we suppose that source connects only to one router to the rest of tree
for line in range(len(tcpfile)):
if "tos 0x7" in tcpfile[line]: # tos 0x7 is the characteristic I chose to distinguish my UDP packets used for tomography
temp = tcpfile[line].split()
graph.root.data.append([temp[0], int(temp[7].replace(",",""))]) #We keep the timestamp and the packet ID
#tcpdump of every leave/destination node stored at node.data
for i in range(len(graph.leaves)):
filename = "dumps/n%d.txt" % (graph.leaves[i].id) #example tcpdump file path "thesisdumps/1/n1" if node 1 is a leaf
tcpfile = [line.rstrip('\n') for line in open(filename)]
for line in range(len(tcpfile)):
if "tos 0x7" in tcpfile[line]: # tos 0x7 is the characteristic I chose to distinguish my UDP packets used for tomography
temp = tcpfile[line].split()
graph.leaves[i].data.append([temp[0], int(temp[7].replace(",",""))]) #We keep the timestamp and the packet ID
for node in range(len(graph.leaves)):
TimestampsIntoDelay(graph.root.data,graph.leaves[node].data,node) #we need to turn each timestamp into path delay for each packet
#root's delay is 0 in all packets (starting point)
for k in range(len(graph.root.data)):
graph.root.data[k][0] = float(0)
#Function that measures path Delay from a timestamp, in our algorithm turns every initial leaf's timestamps into delays (difference between start and finish)
def TimestampsIntoDelay(dump1,dump2,node):
startingpackets=len(dump1) #tcpdump of start node
endingpackets = len(dump2) #tcpdump of end node
for packet in range(endingpackets):
i = 0 # if we are sure that the packets will arive in order, i = packet for faster runtime
#find packets with same ID
while (dump1[i][1] != dump2[packet][1]):
i += 1
#measure delay for each packet
#seconds difference
timestamp1 = dump1[i][0]
timestamp2 = dump2[packet][0]
secondsdiff = (int(timestamp2[0:2])*3600+int(timestamp2[3:5])*60+int(timestamp2[6:8]))-(int(timestamp1[0:2])*3600+int(timestamp1[3:5])*60+int(timestamp1[6:8]))
#fractions of second
fraction1 = float("0"+timestamp1[8:15])
fraction2 = float("0"+timestamp2[8:15])
#delay
packetdelay=float("{0:.10f}".format(float(secondsdiff)+fraction2-fraction1))
graph.leaves[node].data[packet][0] = packetdelay #change timestamp with delay
# Function that estimates the distances based on the link loss parameter
def EstimateDistancesLoss():
# At this point, graph.nodes = U (= source + destination nodes)
NumberOfNodes = len(graph.nodes)
# Matrix is symmetric -> We only need to traverse through upper triangular and then complete the symmetrical elements
# Also, diagonal of the Matrix will be zero (by definition d(i,i) == 0)
for i in range(NumberOfNodes):
Xi = len(graph.nodes[i].data)/TotalProbes
for j in range(i+1,NumberOfNodes):
# How the distance metric is calculated can be seen in the provided documentation
Xj = len(graph.nodes[j].data)/TotalProbes
XiXj = len(set(graph.nodes[i].data)&set(graph.nodes[j].data))/TotalProbes
distance = log10(Xi*Xj/XiXj**2)
#Symmetric matrix
EstDistMatrix[graph.nodes[i].id][graph.nodes[j].id] = distance
EstDistMatrix[graph.nodes[j].id][graph.nodes[i].id] = distance
# Function that estimates the distances based on the link delay variance parameter
def EstimateDistancesDelayVar():
# At this point, graph.nodes = U (= source + destination nodes)
NumberOfNodes = len(graph.nodes)
# Matrix is symmetric -> We only need to traverse through upper triangular and then complete the symmetrical elements
# Also, diagonal of the Matrix will be zero (by definition d(i,i) == 0)
for i in range(NumberOfNodes):
meanTi = sum([graph.nodes[i].data[k][0] for k in range(len(graph.nodes[i].data))])/len(graph.nodes[i].data)
for j in range(i+1,NumberOfNodes):
# How the distance metric is calculated can be seen in the provided documentation
meanTj = sum([graph.nodes[j].data[k][0] for k in range(len(graph.nodes[j].data))])/len(graph.nodes[j].data)
# Compute the variances
varTi = (sum([(graph.nodes[i].data[k][0]-meanTi)**2 for k in range(len(graph.nodes[i].data))]))/(len(graph.nodes[i].data)-1)
varTj = (sum([(graph.nodes[j].data[k][0]-meanTj)**2 for k in range(len(graph.nodes[j].data))]))/(len(graph.nodes[j].data)-1)
# Find Common ID between the 2 nodes' packets
CommonIDs = []
for k1 in range(len(graph.nodes[i].data)):
for k2 in range(len(graph.nodes[j].data)):
if (graph.nodes[i].data[k1][1] == graph.nodes[j].data[k2][1]):
CommonIDs.append(graph.nodes[i].data[k1][1])
# Compute the covariance
covTiTj = Covariance(i,j,CommonIDs,meanTi,meanTj)
distance = varTi + varTj - 2*covTiTj
# Symmetric matrix
EstDistMatrix[graph.nodes[i].id][graph.nodes[j].id] = distance
EstDistMatrix[graph.nodes[j].id][graph.nodes[i].id] = distance
"""
# Function that estimates the distances based on the link utilization parameter
def EstimateDistancesUtil():
# At this point, graph.nodes = U (= source + destination nodes)
NumberOfNodes = len(graph.nodes)
# Epsilon is a small value to acount for possible measurement noise, defined by user
epsilon = 0.00001
# Matrix is symmetric -> We only need to traverse through upper triangular and then complete the symmetrical elements
# Also, diagonal of the Matrix will be zero (by definition d(i,i) == 0)
for i in range(NumberOfNodes):
minTi = min([graph.nodes[i].data[k][0] for k in range(len(graph.nodes[i].data))])
YiPackets = [graph.nodes[i].data[k][1] for k in range(len(graph.nodes[i].data)) if (graph.nodes[i].data[k][0]-minTi <= epsilon)]
Yi = len(YiPackets)/TotalProbes
for j in range(i+1,NumberOfNodes):
# How the distance metric is calculated can be seen in the provided documentation
minTj = min([graph.nodes[j].data[k][0] for k in range(len(graph.nodes[j].data))])
YjPackets = [graph.nodes[j].data[k][1] for k in range(len(graph.nodes[j].data)) if (graph.nodes[j].data[k][0]-minTj <= epsilon)]
Yj = len(YjPackets)/TotalProbes
YiYj = len(set(YiPackets)&set(YjPackets))/TotalProbes
distance = log10(Yi*Yj/YiYj**2)
# Symmetric matrix
EstDistMatrix[graph.nodes[i].id][graph.nodes[j].id] = distance
EstDistMatrix[graph.nodes[j].id][graph.nodes[i].id] = distance
"""
# Function that computes the covariance of nodes i,j
def Covariance(i,j,CommonIDs,meanTi,meanTj):
#Initiliazations
covar = 0
pos1 = 0
pos2 = 0
length1 = len(graph.nodes[i].data)
length2 = len(graph.nodes[j].data)
for packetID in CommonIDs:
#find position of packetID in node i
for k1 in range(pos1,length1):
if (graph.nodes[i].data[k1][1] == packetID):
pos1=k1
break
#find position of packetID in node j
for k2 in range(pos2,length2):
if (graph.nodes[j].data[k2][1] == packetID):
pos2=k2
break
covar += (graph.nodes[i].data[pos1][0]-meanTi)*(graph.nodes[j].data[pos2][0]-meanTj)
covar = covar/(len(CommonIDs)-1)
return covar
def EstimateScoreFunction():
# At this point, graph.leaves = D (= destination nodes)
NumberOfLeaves = len(graph.leaves)
# Matrix is symmetric -> We only need to traverse through upper triangular and then complete the symmetrical elements
# Also, diagonal of the Matrix will be equal to zero (we need pair of nodes)
for i in range(NumberOfLeaves):
for j in range(i+1,NumberOfLeaves):
# Score Function is calulated like this:
# ρ(i,j) = (d(s,i)+d(s,j)-d(i,j))/2
score = (EstDistMatrix[0][graph.leaves[i].id] + EstDistMatrix[0][graph.leaves[j].id] - EstDistMatrix[graph.leaves[i].id][graph.leaves[j].id])/2
#Symmetric matrix
ScoreFunction[graph.leaves[i].id][graph.leaves[j].id] = score
ScoreFunction[graph.leaves[j].id][graph.leaves[i].id] = score
# Function that calculates Δ(delta) so that the General Tree algorithm can be properly implemented
def CalculateDelta():
if (param == 'loss'):
successrate = 0.9995 #should be equal to the minimum link length in terms of loss, changes based on each topology
delta = -log10(successrate)
elif (param == 'delayvar'):
delta = 0.000001 #should be equal to the minimum link length in terms of delay variance, changes based on each topology
else:
pass #Link Utilization not measured in our algorithm
return delta
# Function that visualizes the discovered topology/tree in a .png file
def DrawTopology(param):
#Create Graph
G = pydot.Dot(graph_type='graph') #G =nx.Graph()
for i in range(len(graph.nodes)-1,-1,-1):
for j in range(len(graph.nodes[i].children)):
edge = pydot.Edge(graph.nodes[i].id,graph.nodes[i].children[j].id)
G.add_edge(edge)
#Draw Graph with desired Parameters
G.write_png('Results/'+param+'.png')
# Function that writes the results for each inference parameter in a .csv file
def ExtractResults(param):
# Success/Loss Rate of each Link
if (param == 'loss'):
with open('Results/Loss.csv', 'w') as csvfile:
filewriter = csv.writer(csvfile, delimiter=',',quotechar='|', quoting=csv.QUOTE_MINIMAL)
filewriter.writerow(['Link', 'Success Rate'])
for i in range(1,len(graph.nodes)):
SuccessRate = EstDistMatrix[graph.nodes[i].father.id][graph.nodes[i].id]
SuccessRate = 10**(-SuccessRate)
filewriter.writerow([graph.nodes[i].id,SuccessRate])
# Delay Variance of each Link
elif (param == 'delayvar'):
with open('Results/DelayVariance.csv', 'w') as csvfile:
filewriter = csv.writer(csvfile, delimiter=',',quotechar='|', quoting=csv.QUOTE_MINIMAL)
filewriter.writerow(['Link', 'Delay Variance'])
for i in range(1,len(graph.nodes)):
#LinkDelayVar = sqrt(EstDistMatrix[graph.nodes[i].father.id][graph.nodes[i].id]) ###If I want the Standard Deviation instead of Variance
LinkDelayVar = EstDistMatrix[graph.nodes[i].father.id][graph.nodes[i].id]
filewriter.writerow([graph.nodes[i].id,LinkDelayVar])
# Utilization of each LinkUtil
else:
"""
with open('Results/Utilization.csv', 'w') as csvfile:
filewriter = csv.writer(csvfile, delimiter=',',quotechar='|', quoting=csv.QUOTE_MINIMAL)
filewriter.writerow(['Link', 'Utilization'])
for i in range(1,len(graph.nodes)):
LinkUtil = EstDistMatrix[graph.nodes[i].father.id][graph.nodes[i].id]
LinkUtil = 10**(-LinkUtil)
filewriter.writerow([graph.nodes[i].id,LinkUtil])
"""
pass
### Start of Script ###
# input: Destination Nodes' IDs (Leaves) are given in the DstNodes.txt file
# Create a list with all the Destination Nodes=
DstNodes = [line.rstrip('\n').split(' ') for line in open('DstNodes.txt')]
DstNodes = list(map(int,DstNodes[0]))
# All the inference parameters we want to measure
inferparams = ['loss','delayvar','utilization']
# Perform the algorithm for each inference parameter in the inferparams list
for param in inferparams:
# Initial Graph Creation
# V = {s} : only source node initially on graph
# E = { } : no edges created initially
graph = Graph()
#creation of source node
node = Node()
node.id = 0 #node ID of root is 0
graph.root = node
graph.nodes.append(graph.root)
# Destination Nodes and Graph leaves are the same
# So we create the graph leaves (without any edges yet) to be able to extract the tcpdumps correctly
for i in range(len(DstNodes)):
node = Node()
node.id = DstNodes[i]
graph.nodes.append(node)
graph.leaves.append(node)
######### Algorithm: Rooted Neighbor-Joining (RNJ) Algorithm for Binary Trees #########
#We don't know number of nodes, so we start giving ID numbers to new nodes, starting from max ID of the existing Destination nodes
FreeID = max(DstNodes) + 1
#Get the tcpdumps for the root node and the leaves
if (param == 'loss'):
GetLinkLossDumps()
elif (param == 'delayvar'):
GetLinkDelayDumps()
else:
break #delete if you want to measure link utilization too
pass #GetLinkDelayDumps() used also for utilization
#Total Probes are equal to the probes sent from the source
TotalProbes = len(graph.root.data)
# Estimated Distance Matrix, default size = up to 200 nodes topology
# Holds the distance metric values for each path,
# (i,j) element -> Distance metric of path from node i to node j, d(i,j)
EstDistMatrix = np.zeros((200,200),dtype='f')
#Create the Estimate Distances Matrix
if (param == 'loss'):
EstimateDistancesLoss()
elif(param == 'delayvar'):
EstimateDistancesDelayVar()
else:
pass #EstimateDistancesUtil() used
# Step 1
# Score Function matrix, default size = up to 200 nodes topology (keep same with Estimated Distance matrix)
# Hold the score function for each pair of nodes i,j
# (i,j) element -> distance metric for pair of nodes i,j, ρ(i,j)
ScoreFunction = np.zeros((200,200),dtype='f')
EstimateScoreFunction()
# necessary to start the algorithm correctly, normally we shouldn't append destination nodes upon creation but it helped the tcpdumps function
graph.nodes = []
graph.nodes.append(graph.root)
# Step 2.1
while (len(graph.leaves) != 1):
# Find i*,j* in D with the largest ScoreFunction (tie is broken arbitrarily as we only take the first occurence)
NumberOfLeaves = len(graph.leaves)
# max initialization
maxScore = 0
Istar=Jstar = 0
# find the max score
for i in range(NumberOfLeaves):
for j in range(i+1,NumberOfLeaves):
if (ScoreFunction[graph.leaves[i].id][graph.leaves[j].id] >= maxScore):
maxScore = ScoreFunction[graph.leaves[i].id][graph.leaves[j].id]
Istar = graph.leaves[i].id
Jstar = graph.leaves[j].id
#Create a node f as parent of i* and j*
FatherNode = Node()
FatherNode.id = FreeID
FreeID += 1
# D = D \ {i*,j*}
# V = V U {i*,j*} , E = E U {(f,i*),(f,j*)}
for i in range(len(graph.leaves)): # for i*
if (graph.leaves[i].id == Istar):
graph.nodes.append(graph.leaves[i]) # V = V U {i*}
graph.leaves[i].father = FatherNode # E U {(f,i*)}
FatherNode.children.append(graph.leaves[i]) # E U {(f,i*)}
del graph.leaves[i] # D = D \ {i*}
break
for i in range(len(graph.leaves)): # for j*
if (graph.leaves[i].id == Jstar):
graph.nodes.append(graph.leaves[i]) # V = V U {j*}
graph.leaves[i].father = FatherNode # E U {(f,j*)}
FatherNode.children.append(graph.leaves[i]) # E U {(f,i*)}
del graph.leaves[i] # D = D \ {j*}
break
# Step 2.2
# d(s,f) = ρ(i*,j*)
EstDistMatrix[0][FatherNode.id] = ScoreFunction[Istar][Jstar]
EstDistMatrix[FatherNode.id][0] = EstDistMatrix[0][FatherNode.id] # SYMMETRY
# d(f,i*) = d(s,i*) - ρ(i*,j*)
EstDistMatrix[FatherNode.id][Istar] = EstDistMatrix[0][Istar] - ScoreFunction[Istar][Jstar]
EstDistMatrix[Istar][FatherNode.id] = EstDistMatrix[FatherNode.id][Istar] # SYMMETRY
# d(f,j*) = d(s,j*) - ρ(i*,j*)
EstDistMatrix[FatherNode.id][Jstar] = EstDistMatrix[0][Jstar] - ScoreFunction[Istar][Jstar]
EstDistMatrix[Jstar][FatherNode.id] = EstDistMatrix[FatherNode.id][Jstar] # SYMMETRY
# Step 2.3
# In this step we find if there are more than 2 siblings (if Istar,Jstar nodes have another sibling)
#Calculate Δ based on the link parameter that is inferred
delta = CalculateDelta()
# For every k in D such that ρ(i*,j*) - ρ(i*,k) <= Δ/2:
LeavesToDel = []
for k in range (len(graph.leaves)):
SiblID = graph.leaves[k].id # SiblID = node k ID
if (ScoreFunction[Istar][Jstar] - ScoreFunction[Istar][SiblID] <= delta/2):
# d(f,k) = d(s,k) - ρ(i*,j*)
EstDistMatrix[FatherNode.id][SiblID] = EstDistMatrix[0][SiblID] - ScoreFunction[Istar][Jstar]
EstDistMatrix[SiblID][FatherNode.id] = EstDistMatrix[FatherNode.id][SiblID] #SYMMETRY
# D = D \ {k}
# V = V U {k} , E = E U {(f,k)}
graph.nodes.append(graph.leaves[k]) # V = V U {k}
graph.leaves[k].father = FatherNode # E U {(f,k)}
FatherNode.children.append(graph.leaves[k]) # E U {(f,k)}
LeavesToDel.append(k) # D = D \ {k}, store the values to del together
#create a temporary list that will have all the graph.leaves nodes besides those that we want to delete from step 2.3
temp = []
for i in range(len(graph.leaves)):
if i not in LeavesToDel:
temp.append(graph.leaves[i])
graph.leaves = temp
# Step 2.4
for k in range(len(graph.leaves)):
# d(k,f) = 1/2[d(k,i*)-d(f,i*)] + 1/2[d(k,j*)-d(f,j*)]
EstDistMatrix[graph.leaves[k].id][FatherNode.id] = 0.5*(EstDistMatrix[graph.leaves[k].id][Istar]-EstDistMatrix[FatherNode.id][Istar]) + 0.5*(EstDistMatrix[graph.leaves[k].id][Jstar]-EstDistMatrix[FatherNode.id][Jstar])
EstDistMatrix[FatherNode.id][graph.leaves[k].id] = EstDistMatrix[graph.leaves[k].id][FatherNode.id] #SYMMETRY
# ρ(k,f) = 1/2[ρ(k,i*)+ρ(k,j*)]
ScoreFunction[graph.leaves[k].id][FatherNode.id] = 0.5*(ScoreFunction[graph.leaves[k].id][Istar]+ScoreFunction[graph.leaves[k].id][Jstar])
ScoreFunction[FatherNode.id][graph.leaves[k].id] = ScoreFunction[graph.leaves[k].id][FatherNode.id] # SYMMETRY
# D = D U f
graph.leaves.append(FatherNode)
# If |D| = 1, for the i in D: V = V U {i} , E = E U (s,i)
graph.nodes.append(graph.leaves[0])
graph.leaves[0].father = graph.root
graph.root.children = [graph.leaves[0]]
# Draw the Topology produced by Tomography
# variable "param" is used to draw the topology based on the specific inference parameter each time
DrawTopology(param)
# Write the results for each inference parameter performed in a csv file
ExtractResults(param)
|
[
"csv.writer",
"numpy.zeros",
"pydot.Dot",
"math.log10",
"pydot.Edge"
] |
[((11302, 11331), 'pydot.Dot', 'pydot.Dot', ([], {'graph_type': '"""graph"""'}), "(graph_type='graph')\n", (11311, 11331), False, 'import pydot\n'), ((15441, 15472), 'numpy.zeros', 'np.zeros', (['(200, 200)'], {'dtype': '"""f"""'}), "((200, 200), dtype='f')\n", (15449, 15472), True, 'import numpy as np\n'), ((15965, 15996), 'numpy.zeros', 'np.zeros', (['(200, 200)'], {'dtype': '"""f"""'}), "((200, 200), dtype='f')\n", (15973, 15996), True, 'import numpy as np\n'), ((5425, 5451), 'math.log10', 'log10', (['(Xi * Xj / XiXj ** 2)'], {}), '(Xi * Xj / XiXj ** 2)\n', (5430, 5451), False, 'from math import log10\n'), ((10912, 10930), 'math.log10', 'log10', (['successrate'], {}), '(successrate)\n', (10917, 10930), False, 'from math import log10\n'), ((11466, 11526), 'pydot.Edge', 'pydot.Edge', (['graph.nodes[i].id', 'graph.nodes[i].children[j].id'], {}), '(graph.nodes[i].id, graph.nodes[i].children[j].id)\n', (11476, 11526), False, 'import pydot\n'), ((11887, 11963), 'csv.writer', 'csv.writer', (['csvfile'], {'delimiter': '""","""', 'quotechar': '"""|"""', 'quoting': 'csv.QUOTE_MINIMAL'}), "(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)\n", (11897, 11963), False, 'import csv\n'), ((12431, 12507), 'csv.writer', 'csv.writer', (['csvfile'], {'delimiter': '""","""', 'quotechar': '"""|"""', 'quoting': 'csv.QUOTE_MINIMAL'}), "(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)\n", (12441, 12507), False, 'import csv\n')]
|
import cv2
import matplotlib.pyplot as plt
import numpy as np
from functions_feat_extraction import image_to_features
from project_5_utils import stitch_together
def draw_labeled_bounding_boxes(img, labeled_frame, num_objects):
"""
Starting from labeled regions, draw enclosing rectangles in the original color frame.
"""
# Iterate through all detected cars
for car_number in range(1, num_objects + 1):
# Find pixels with each car_number label value
rows, cols = np.where(labeled_frame == car_number)
# Find minimum enclosing rectangle
x_min, y_min = np.min(cols), np.min(rows)
x_max, y_max = np.max(cols), np.max(rows)
cv2.rectangle(img, (x_min, y_min), (x_max, y_max), color=(255, 0, 0), thickness=6)
return img
def compute_heatmap_from_detections(frame, hot_windows, threshold=5, verbose=False):
"""
Compute heatmaps from windows classified as positive, in order to filter false positives.
"""
h, w, c = frame.shape
heatmap = np.zeros(shape=(h, w), dtype=np.uint8)
for bbox in hot_windows:
# for each bounding box, add heat to the corresponding rectangle in the image
x_min, y_min = bbox[0]
x_max, y_max = bbox[1]
heatmap[y_min:y_max, x_min:x_max] += 1 # add heat
# apply threshold + morphological closure to remove noise
_, heatmap_thresh = cv2.threshold(heatmap, threshold, 255, type=cv2.THRESH_BINARY)
heatmap_thresh = cv2.morphologyEx(heatmap_thresh, op=cv2.MORPH_CLOSE,
kernel=cv2.getStructuringElement(cv2.MORPH_ELLIPSE,
(13, 13)), iterations=1)
if verbose:
f, ax = plt.subplots(1, 3)
ax[0].imshow(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
ax[1].imshow(heatmap, cmap='hot')
ax[2].imshow(heatmap_thresh, cmap='hot')
plt.show()
return heatmap, heatmap_thresh
def compute_windows_multiscale(image, verbose=False):
"""
Naive implementation of multiscale window search.
"""
h, w, c = image.shape
windows_multiscale = []
windows_32 = slide_window(image, x_start_stop=[None, None],
y_start_stop=[4 * h // 8, 5 * h // 8],
xy_window=(32, 32), xy_overlap=(0.8, 0.8))
windows_multiscale.append(windows_32)
windows_64 = slide_window(image, x_start_stop=[None, None],
y_start_stop=[4 * h // 8, 6 * h // 8],
xy_window=(64, 64), xy_overlap=(0.8, 0.8))
windows_multiscale.append(windows_64)
windows_128 = slide_window(image, x_start_stop=[None, None], y_start_stop=[3 * h // 8, h],
xy_window=(128, 128), xy_overlap=(0.8, 0.8))
windows_multiscale.append(windows_128)
if verbose:
windows_img_32 = draw_boxes(image, windows_32, color=(0, 0, 255), thick=1)
windows_img_64 = draw_boxes(image, windows_64, color=(0, 255, 0), thick=1)
windows_img_128 = draw_boxes(image, windows_128, color=(255, 0, 0), thick=1)
stitching = stitch_together([windows_img_32, windows_img_64, windows_img_128], (1, 3),
resize_dim=(1300, 500))
cv2.imshow('', stitching)
cv2.waitKey()
return np.concatenate(windows_multiscale)
def slide_window(img, x_start_stop=[None, None], y_start_stop=[None, None],
xy_window=(64, 64), xy_overlap=(0.5, 0.5)):
"""
Implementation of a sliding window in a region of interest of the image.
"""
# If x and/or y start/stop positions not defined, set to image size
if x_start_stop[0] is None:
x_start_stop[0] = 0
if x_start_stop[1] is None:
x_start_stop[1] = img.shape[1]
if y_start_stop[0] is None:
y_start_stop[0] = 0
if y_start_stop[1] is None:
y_start_stop[1] = img.shape[0]
# Compute the span of the region to be searched
x_span = x_start_stop[1] - x_start_stop[0]
y_span = y_start_stop[1] - y_start_stop[0]
# Compute the number of pixels per step in x/y
n_x_pix_per_step = np.int(xy_window[0] * (1 - xy_overlap[0]))
n_y_pix_per_step = np.int(xy_window[1] * (1 - xy_overlap[1]))
# Compute the number of windows in x / y
n_x_windows = np.int(x_span / n_x_pix_per_step) - 1
n_y_windows = np.int(y_span / n_y_pix_per_step) - 1
# Initialize a list to append window positions to
window_list = []
# Loop through finding x and y window positions.
for i in range(n_y_windows):
for j in range(n_x_windows):
# Calculate window position
start_x = j * n_x_pix_per_step + x_start_stop[0]
end_x = start_x + xy_window[0]
start_y = i * n_y_pix_per_step + y_start_stop[0]
end_y = start_y + xy_window[1]
# Append window position to list
window_list.append(((start_x, start_y), (end_x, end_y)))
# Return the list of windows
return window_list
def draw_boxes(img, bbox_list, color=(0, 0, 255), thick=6):
"""
Draw all bounding boxes in `bbox_list` onto a given image.
:param img: input image
:param bbox_list: list of bounding boxes
:param color: color used for drawing boxes
:param thick: thickness of the box line
:return: a new image with the bounding boxes drawn
"""
# Make a copy of the image
img_copy = np.copy(img)
# Iterate through the bounding boxes
for bbox in bbox_list:
# Draw a rectangle given bbox coordinates
tl_corner = tuple(bbox[0])
br_corner = tuple(bbox[1])
cv2.rectangle(img_copy, tl_corner, br_corner, color, thick)
# Return the image copy with boxes drawn
return img_copy
# Define a function you will pass an image and the list of windows to be searched (output of slide_windows())
def search_windows(img, windows, clf, scaler, feat_extraction_params):
hot_windows = [] # list to receive positive detection windows
for window in windows:
# Extract the current window from original image
resize_h, resize_w = feat_extraction_params['resize_h'], feat_extraction_params['resize_w']
test_img = cv2.resize(img[window[0][1]:window[1][1], window[0][0]:window[1][0]],
(resize_w, resize_h))
# Extract features for that window using single_img_features()
features = image_to_features(test_img, feat_extraction_params)
# Scale extracted features to be fed to classifier
test_features = scaler.transform(np.array(features).reshape(1, -1))
# Predict on rescaled features
prediction = clf.predict(test_features)
# If positive (prediction == 1) then save the window
if prediction == 1:
hot_windows.append(window)
# Return windows for positive detections
return hot_windows
|
[
"cv2.rectangle",
"functions_feat_extraction.image_to_features",
"cv2.imshow",
"project_5_utils.stitch_together",
"numpy.copy",
"cv2.cvtColor",
"numpy.max",
"numpy.int",
"matplotlib.pyplot.subplots",
"cv2.resize",
"matplotlib.pyplot.show",
"cv2.waitKey",
"numpy.min",
"numpy.concatenate",
"cv2.getStructuringElement",
"cv2.threshold",
"numpy.zeros",
"numpy.where",
"numpy.array"
] |
[((1030, 1068), 'numpy.zeros', 'np.zeros', ([], {'shape': '(h, w)', 'dtype': 'np.uint8'}), '(shape=(h, w), dtype=np.uint8)\n', (1038, 1068), True, 'import numpy as np\n'), ((1393, 1455), 'cv2.threshold', 'cv2.threshold', (['heatmap', 'threshold', '(255)'], {'type': 'cv2.THRESH_BINARY'}), '(heatmap, threshold, 255, type=cv2.THRESH_BINARY)\n', (1406, 1455), False, 'import cv2\n'), ((3360, 3394), 'numpy.concatenate', 'np.concatenate', (['windows_multiscale'], {}), '(windows_multiscale)\n', (3374, 3394), True, 'import numpy as np\n'), ((4183, 4225), 'numpy.int', 'np.int', (['(xy_window[0] * (1 - xy_overlap[0]))'], {}), '(xy_window[0] * (1 - xy_overlap[0]))\n', (4189, 4225), True, 'import numpy as np\n'), ((4249, 4291), 'numpy.int', 'np.int', (['(xy_window[1] * (1 - xy_overlap[1]))'], {}), '(xy_window[1] * (1 - xy_overlap[1]))\n', (4255, 4291), True, 'import numpy as np\n'), ((5476, 5488), 'numpy.copy', 'np.copy', (['img'], {}), '(img)\n', (5483, 5488), True, 'import numpy as np\n'), ((502, 539), 'numpy.where', 'np.where', (['(labeled_frame == car_number)'], {}), '(labeled_frame == car_number)\n', (510, 539), True, 'import numpy as np\n'), ((693, 779), 'cv2.rectangle', 'cv2.rectangle', (['img', '(x_min, y_min)', '(x_max, y_max)'], {'color': '(255, 0, 0)', 'thickness': '(6)'}), '(img, (x_min, y_min), (x_max, y_max), color=(255, 0, 0),\n thickness=6)\n', (706, 779), False, 'import cv2\n'), ((1748, 1766), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(3)'], {}), '(1, 3)\n', (1760, 1766), True, 'import matplotlib.pyplot as plt\n'), ((1927, 1937), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1935, 1937), True, 'import matplotlib.pyplot as plt\n'), ((3157, 3259), 'project_5_utils.stitch_together', 'stitch_together', (['[windows_img_32, windows_img_64, windows_img_128]', '(1, 3)'], {'resize_dim': '(1300, 500)'}), '([windows_img_32, windows_img_64, windows_img_128], (1, 3),\n resize_dim=(1300, 500))\n', (3172, 3259), False, 'from project_5_utils import stitch_together\n'), ((3300, 3325), 'cv2.imshow', 'cv2.imshow', (['""""""', 'stitching'], {}), "('', stitching)\n", (3310, 3325), False, 'import cv2\n'), ((3334, 3347), 'cv2.waitKey', 'cv2.waitKey', ([], {}), '()\n', (3345, 3347), False, 'import cv2\n'), ((4356, 4389), 'numpy.int', 'np.int', (['(x_span / n_x_pix_per_step)'], {}), '(x_span / n_x_pix_per_step)\n', (4362, 4389), True, 'import numpy as np\n'), ((4412, 4445), 'numpy.int', 'np.int', (['(y_span / n_y_pix_per_step)'], {}), '(y_span / n_y_pix_per_step)\n', (4418, 4445), True, 'import numpy as np\n'), ((5686, 5745), 'cv2.rectangle', 'cv2.rectangle', (['img_copy', 'tl_corner', 'br_corner', 'color', 'thick'], {}), '(img_copy, tl_corner, br_corner, color, thick)\n', (5699, 5745), False, 'import cv2\n'), ((6266, 6362), 'cv2.resize', 'cv2.resize', (['img[window[0][1]:window[1][1], window[0][0]:window[1][0]]', '(resize_w, resize_h)'], {}), '(img[window[0][1]:window[1][1], window[0][0]:window[1][0]], (\n resize_w, resize_h))\n', (6276, 6362), False, 'import cv2\n'), ((6479, 6530), 'functions_feat_extraction.image_to_features', 'image_to_features', (['test_img', 'feat_extraction_params'], {}), '(test_img, feat_extraction_params)\n', (6496, 6530), False, 'from functions_feat_extraction import image_to_features\n'), ((607, 619), 'numpy.min', 'np.min', (['cols'], {}), '(cols)\n', (613, 619), True, 'import numpy as np\n'), ((621, 633), 'numpy.min', 'np.min', (['rows'], {}), '(rows)\n', (627, 633), True, 'import numpy as np\n'), ((657, 669), 'numpy.max', 'np.max', (['cols'], {}), '(cols)\n', (663, 669), True, 'import numpy as np\n'), ((671, 683), 'numpy.max', 'np.max', (['rows'], {}), '(rows)\n', (677, 683), True, 'import numpy as np\n'), ((1575, 1629), 'cv2.getStructuringElement', 'cv2.getStructuringElement', (['cv2.MORPH_ELLIPSE', '(13, 13)'], {}), '(cv2.MORPH_ELLIPSE, (13, 13))\n', (1600, 1629), False, 'import cv2\n'), ((1788, 1826), 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_BGR2RGB'], {}), '(frame, cv2.COLOR_BGR2RGB)\n', (1800, 1826), False, 'import cv2\n'), ((6632, 6650), 'numpy.array', 'np.array', (['features'], {}), '(features)\n', (6640, 6650), True, 'import numpy as np\n')]
|
from __future__ import annotations
import threading
import numpy as np
from astropy.coordinates import SkyCoord
import astropy.units as u
from typing import Tuple, List
import random
from pyobs.object import Object
from pyobs.utils.enums import MotionStatus
class SimTelescope(Object):
"""A simulated telescope on an equitorial mount."""
__module__ = 'pyobs.utils.simulation'
def __init__(self, world: 'SimWorld', position: Tuple[float, float] = None, offsets: Tuple[float, float] = None,
pointing_offset: Tuple[float, float] = None, move_accuracy: float = 2.,
speed: float = 20., focus: float = 50, filters: List[str] = None, filter: str = 'clear',
drift: Tuple[float, float] = None, focal_length: float = 5000., *args, **kwargs):
"""Initializes new telescope.
Args:
world: World object.
position: RA/Dec tuple with position of telescope in degrees.
offsets: RA/Dec offsets of telescope in arcsecs.
pointing_offset: Pointing offset in RA/Dec in arcsecs.
move_accuracy: Accuracy of movements in RA/Dec, i.e. random error after any movement [arcsec].
speed: Speed of telescope in deg/sec.
focus: Telescope focus.
filters: List of filters.
filter: Current filter.
drift: RA/Dec drift of telescope in arcsec/sec.
focal_length: Focal length of telescope in mm.
"""
Object.__init__(self, *args, **kwargs)
# store
self.world = world
self.status = MotionStatus.IDLE
self.status_callback = None
# init
self._position = SkyCoord(0. * u.deg, 0. * u.deg, frame='icrs') if position is None else \
SkyCoord(position[0] * u.deg, position[1] * u.deg, frame='icrs')
self._offsets = (0., 0.) if offsets is None else offsets
self.pointing_offset = (20., 2.) if pointing_offset is None else pointing_offset
self.move_accuracy = (1, 1) if move_accuracy is None else move_accuracy
self.speed = speed # telescope speed in deg/sec
self.focus = focus
self.filters = ['clear', 'B', 'V', 'R'] if filters is None else filters
self.filter = filter
self.drift = (0.01, 0.0001) if drift is None else drift # arcsec/sec in RA/Dec
self.focal_length = focal_length
# private stuff
self._drift = (0., 0.)
self._dest_coords = None
# locks
self._pos_lock = threading.RLock()
# threads
self.add_thread_func(self._move_thread)
@property
def position(self):
return self._position
@property
def offsets(self):
return self._offsets
def _change_motion_status(self, status: MotionStatus):
"""Change the current motion status.
Args:
status: New motion status
"""
# call callback
if self.status_callback is not None and status != self.status:
self.status_callback(status)
# set it
self.status = status
@property
def real_pos(self):
# calculate offsets
dra = (self._offsets[0] * u.deg + self._drift[0] * u.arcsec) / np.cos(np.radians(self._position.dec.degree))
ddec = self._offsets[1] * u.deg + self._drift[1] * u.arcsec
# return position
with self._pos_lock:
return SkyCoord(ra=self._position.ra + dra,
dec=self._position.dec + ddec,
frame='icrs')
def move_ra_dec(self, coords):
"""Move telescope to given RA/Dec position.
Args:
coords: Destination coordinates.
"""
# change status
self._change_motion_status(MotionStatus.SLEWING)
# calculate random RA/Dec offsets
acc = self.move_accuracy / 3600.
ra = random.gauss(coords.ra.degree, acc / np.cos(np.radians(coords.dec.degree))) * u.deg
dec = random.gauss(coords.dec.degree, acc) * u.deg
# set coordinates
self._dest_coords = SkyCoord(ra=ra, dec=dec, frame='icrs')
def set_offsets(self, dra, ddec):
"""Move RA/Dec offsets.
Args:
dra: RA offset [deg]
ddec: Dec offset [deg]
"""
# calculate random RA/Dec offsets
acc = self.move_accuracy / 3600.
ra, dec = random.gauss(dra, acc), random.gauss(ddec, acc)
# set offsets
self._offsets = (ra, dec)
def _move_thread(self):
"""Move the telescope over time."""
# run until closed
while not self.closing.is_set():
# do we have destination coordinates?
if self._dest_coords is not None:
# calculate moving vector
vra = (self._dest_coords.ra.degree - self._position.ra.degree) * \
np.cos(np.radians(self._position.dec.degree))
vdec = self._dest_coords.dec.degree - self._position.dec.degree
# get direction
length = np.sqrt(vra**2 + vdec**2)
# do we reach target?
if length < self.speed:
# set it
with self._pos_lock:
# set position and reset destination
self._change_motion_status(MotionStatus.TRACKING)
self._position = self._dest_coords
self._dest_coords = None
# set some random drift around the pointing error
self._drift = (random.gauss(self.pointing_offset[0], self.pointing_offset[0] / 10.),
random.gauss(self.pointing_offset[1], self.pointing_offset[1] / 10.))
else:
# norm vector and get movement
dra = vra / length * self.speed / np.cos(np.radians(self._position.dec.degree)) * u.deg
ddec = vdec / length * self.speed * u.deg
# apply it
with self._pos_lock:
self._change_motion_status(MotionStatus.SLEWING)
self._position = SkyCoord(ra=self._position.ra + dra,
dec=self._position.dec + ddec,
frame='icrs')
else:
# no movement, just drift
# calculate constant drift
drift_ra = random.gauss(self.drift[0], self.drift[0] / 10.)
drift_dec = random.gauss(self.drift[1], self.drift[1] / 10.)
# and apply it
with self._pos_lock:
self._drift = (self._drift[0] + drift_ra, self._drift[1] + drift_dec)
# sleep a second
self.closing.wait(1)
__all__ = ['SimTelescope']
|
[
"numpy.radians",
"threading.RLock",
"random.gauss",
"astropy.coordinates.SkyCoord",
"pyobs.object.Object.__init__",
"numpy.sqrt"
] |
[((1494, 1532), 'pyobs.object.Object.__init__', 'Object.__init__', (['self', '*args'], {}), '(self, *args, **kwargs)\n', (1509, 1532), False, 'from pyobs.object import Object\n'), ((2538, 2555), 'threading.RLock', 'threading.RLock', ([], {}), '()\n', (2553, 2555), False, 'import threading\n'), ((4115, 4153), 'astropy.coordinates.SkyCoord', 'SkyCoord', ([], {'ra': 'ra', 'dec': 'dec', 'frame': '"""icrs"""'}), "(ra=ra, dec=dec, frame='icrs')\n", (4123, 4153), False, 'from astropy.coordinates import SkyCoord\n'), ((1694, 1742), 'astropy.coordinates.SkyCoord', 'SkyCoord', (['(0.0 * u.deg)', '(0.0 * u.deg)'], {'frame': '"""icrs"""'}), "(0.0 * u.deg, 0.0 * u.deg, frame='icrs')\n", (1702, 1742), False, 'from astropy.coordinates import SkyCoord\n'), ((1780, 1844), 'astropy.coordinates.SkyCoord', 'SkyCoord', (['(position[0] * u.deg)', '(position[1] * u.deg)'], {'frame': '"""icrs"""'}), "(position[0] * u.deg, position[1] * u.deg, frame='icrs')\n", (1788, 1844), False, 'from astropy.coordinates import SkyCoord\n'), ((3440, 3526), 'astropy.coordinates.SkyCoord', 'SkyCoord', ([], {'ra': '(self._position.ra + dra)', 'dec': '(self._position.dec + ddec)', 'frame': '"""icrs"""'}), "(ra=self._position.ra + dra, dec=self._position.dec + ddec, frame=\n 'icrs')\n", (3448, 3526), False, 'from astropy.coordinates import SkyCoord\n'), ((4015, 4051), 'random.gauss', 'random.gauss', (['coords.dec.degree', 'acc'], {}), '(coords.dec.degree, acc)\n', (4027, 4051), False, 'import random\n'), ((4422, 4444), 'random.gauss', 'random.gauss', (['dra', 'acc'], {}), '(dra, acc)\n', (4434, 4444), False, 'import random\n'), ((4446, 4469), 'random.gauss', 'random.gauss', (['ddec', 'acc'], {}), '(ddec, acc)\n', (4458, 4469), False, 'import random\n'), ((3258, 3295), 'numpy.radians', 'np.radians', (['self._position.dec.degree'], {}), '(self._position.dec.degree)\n', (3268, 3295), True, 'import numpy as np\n'), ((5097, 5126), 'numpy.sqrt', 'np.sqrt', (['(vra ** 2 + vdec ** 2)'], {}), '(vra ** 2 + vdec ** 2)\n', (5104, 5126), True, 'import numpy as np\n'), ((6552, 6601), 'random.gauss', 'random.gauss', (['self.drift[0]', '(self.drift[0] / 10.0)'], {}), '(self.drift[0], self.drift[0] / 10.0)\n', (6564, 6601), False, 'import random\n'), ((6629, 6678), 'random.gauss', 'random.gauss', (['self.drift[1]', '(self.drift[1] / 10.0)'], {}), '(self.drift[1], self.drift[1] / 10.0)\n', (6641, 6678), False, 'import random\n'), ((3961, 3990), 'numpy.radians', 'np.radians', (['coords.dec.degree'], {}), '(coords.dec.degree)\n', (3971, 3990), True, 'import numpy as np\n'), ((4920, 4957), 'numpy.radians', 'np.radians', (['self._position.dec.degree'], {}), '(self._position.dec.degree)\n', (4930, 4957), True, 'import numpy as np\n'), ((6239, 6325), 'astropy.coordinates.SkyCoord', 'SkyCoord', ([], {'ra': '(self._position.ra + dra)', 'dec': '(self._position.dec + ddec)', 'frame': '"""icrs"""'}), "(ra=self._position.ra + dra, dec=self._position.dec + ddec, frame=\n 'icrs')\n", (6247, 6325), False, 'from astropy.coordinates import SkyCoord\n'), ((5629, 5698), 'random.gauss', 'random.gauss', (['self.pointing_offset[0]', '(self.pointing_offset[0] / 10.0)'], {}), '(self.pointing_offset[0], self.pointing_offset[0] / 10.0)\n', (5641, 5698), False, 'import random\n'), ((5738, 5807), 'random.gauss', 'random.gauss', (['self.pointing_offset[1]', '(self.pointing_offset[1] / 10.0)'], {}), '(self.pointing_offset[1], self.pointing_offset[1] / 10.0)\n', (5750, 5807), False, 'import random\n'), ((5943, 5980), 'numpy.radians', 'np.radians', (['self._position.dec.degree'], {}), '(self._position.dec.degree)\n', (5953, 5980), True, 'import numpy as np\n')]
|
r"""
Definition
----------
The scattering intensity $I(q)$ is calculated as
.. math::
I(q) = \begin{cases}
A q^{-m1} + \text{background} & q <= q_c \\
C q^{-m2} + \text{background} & q > q_c
\end{cases}
where $q_c$ = the location of the crossover from one slope to the other,
$A$ = the scaling coefficent that sets the overall intensity of the lower Q
power law region, $m1$ = power law exponent at low Q, and $m2$ = power law
exponent at high Q. The scaling of the second power law region (coefficent C)
is then automatically scaled to match the first by following formula:
.. math::
C = \frac{A q_c^{m2}}{q_c^{m1}}
.. note::
Be sure to enter the power law exponents as positive values!
For 2D data the scattering intensity is calculated in the same way as 1D,
where the $q$ vector is defined as
.. math::
q = \sqrt{q_x^2 + q_y^2}
References
----------
None.
**Author:** NIST IGOR/DANSE **on:** pre 2010
**Last Modified by:** <NAME> **on:** February 18, 2016
**Last Reviewed by:** <NAME> **on:** March 21, 2016
"""
from numpy import inf, power, empty, errstate
name = "two_power_law"
title = "This model calculates an empirical functional form for SAS data \
characterized by two power laws."
description = """
I(q) = coef_A*pow(qval,-1.0*power1) + background for q<=q_c
=C*pow(qval,-1.0*power2) + background for q>q_c
where C=coef_A*pow(q_c,-1.0*power1)/pow(q_c,-1.0*power2).
coef_A = scaling coefficent
q_c = crossover location [1/A]
power_1 (=m1) = power law exponent at low Q
power_2 (=m2) = power law exponent at high Q
background = Incoherent background [1/cm]
"""
category = "shape-independent"
# pylint: disable=bad-whitespace, line-too-long
# ["name", "units", default, [lower, upper], "type", "description"],
parameters = [
["coefficent_1", "", 1.0, [-inf, inf], "", "coefficent A in low Q region"],
["crossover", "1/Ang", 0.04,[0, inf], "", "crossover location"],
["power_1", "", 1.0, [0, inf], "", "power law exponent at low Q"],
["power_2", "", 4.0, [0, inf], "", "power law exponent at high Q"],
]
# pylint: enable=bad-whitespace, line-too-long
def Iq(q,
coefficent_1=1.0,
crossover=0.04,
power_1=1.0,
power_2=4.0,
):
"""
:param q: Input q-value (float or [float, float])
:param coefficent_1: Scaling coefficent at low Q
:param crossover: Crossover location
:param power_1: Exponent of power law function at low Q
:param power_2: Exponent of power law function at high Q
:return: Calculated intensity
"""
result= empty(q.shape, 'd')
index = (q <= crossover)
with errstate(divide='ignore'):
coefficent_2 = coefficent_1 * power(crossover, power_2 - power_1)
result[index] = coefficent_1 * power(q[index], -power_1)
result[~index] = coefficent_2 * power(q[~index], -power_2)
return result
Iq.vectorized = True # Iq accepts an array of q values
demo = dict(scale=1, background=0.0,
coefficent_1=1.0,
crossover=0.04,
power_1=1.0,
power_2=4.0)
tests = [
# Accuracy tests based on content in test/utest_extra_models.py
[{'coefficent_1': 1.0,
'crossover': 0.04,
'power_1': 1.0,
'power_2': 4.0,
'background': 0.0,
}, 0.001, 1000],
[{'coefficent_1': 1.0,
'crossover': 0.04,
'power_1': 1.0,
'power_2': 4.0,
'background': 0.0,
}, 0.150141, 0.125945],
[{'coefficent_1': 1.0,
'crossover': 0.04,
'power_1': 1.0,
'power_2': 4.0,
'background': 0.0,
}, 0.442528, 0.00166884],
[{'coefficent_1': 1.0,
'crossover': 0.04,
'power_1': 1.0,
'power_2': 4.0,
'background': 0.0,
}, (0.442528, 0.00166884), 0.00166884],
]
|
[
"numpy.empty",
"numpy.errstate",
"numpy.power"
] |
[((2794, 2813), 'numpy.empty', 'empty', (['q.shape', '"""d"""'], {}), "(q.shape, 'd')\n", (2799, 2813), False, 'from numpy import inf, power, empty, errstate\n'), ((2852, 2877), 'numpy.errstate', 'errstate', ([], {'divide': '"""ignore"""'}), "(divide='ignore')\n", (2860, 2877), False, 'from numpy import inf, power, empty, errstate\n'), ((2917, 2952), 'numpy.power', 'power', (['crossover', '(power_2 - power_1)'], {}), '(crossover, power_2 - power_1)\n', (2922, 2952), False, 'from numpy import inf, power, empty, errstate\n'), ((2992, 3017), 'numpy.power', 'power', (['q[index]', '(-power_1)'], {}), '(q[index], -power_1)\n', (2997, 3017), False, 'from numpy import inf, power, empty, errstate\n'), ((3058, 3084), 'numpy.power', 'power', (['q[~index]', '(-power_2)'], {}), '(q[~index], -power_2)\n', (3063, 3084), False, 'from numpy import inf, power, empty, errstate\n')]
|
import pytest
import reinas.queens as queens
import numpy as np
import models.consultas as consultas
def test_numero_reinas(numero):
n = int(numero)
lista_soluciones = []
session = consultas.loadSession()
tablero = np.zeros(shape=(n,n),dtype=int)
queens.n_reinas(tablero,0,lista_soluciones)
num_soluciones = consultas.num_soluciones(n, session)
assert len(lista_soluciones) == num_soluciones
|
[
"models.consultas.num_soluciones",
"models.consultas.loadSession",
"numpy.zeros",
"reinas.queens.n_reinas"
] |
[((194, 217), 'models.consultas.loadSession', 'consultas.loadSession', ([], {}), '()\n', (215, 217), True, 'import models.consultas as consultas\n'), ((232, 265), 'numpy.zeros', 'np.zeros', ([], {'shape': '(n, n)', 'dtype': 'int'}), '(shape=(n, n), dtype=int)\n', (240, 265), True, 'import numpy as np\n'), ((272, 317), 'reinas.queens.n_reinas', 'queens.n_reinas', (['tablero', '(0)', 'lista_soluciones'], {}), '(tablero, 0, lista_soluciones)\n', (287, 317), True, 'import reinas.queens as queens\n'), ((341, 377), 'models.consultas.num_soluciones', 'consultas.num_soluciones', (['n', 'session'], {}), '(n, session)\n', (365, 377), True, 'import models.consultas as consultas\n')]
|
"""Align face images given landmarks."""
# MIT License
#
# Copyright (c) 2017 <NAME>
#
# 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.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import sys
import os
import warnings
import argparse
import random
import cv2
from align.mtcnntf import detector
from align.matlab_cp2tform import get_similarity_transform_for_cv2
def align(src_img, src_pts, ref_pts, image_size, scale=1.0, transpose_input=False):
w, h = image_size = tuple(image_size)
# Actual offset = new center - old center (scaled)
scale_ = max(w,h) * scale
cx_ref = cy_ref = 0.
offset_x = 0.5 * w - cx_ref * scale_
offset_y = 0.5 * h - cy_ref * scale_
s = np.array(src_pts).astype(np.float32).reshape([-1,2])
r = np.array(ref_pts).astype(np.float32) * scale_ + np.array([[offset_x, offset_y]])
if transpose_input:
s = s.reshape([2,-1]).T
tfm = get_similarity_transform_for_cv2(s, r)
dst_img = cv2.warpAffine(src_img, tfm, image_size)
s_new = np.concatenate([s.reshape([2,-1]), np.ones((1, s.shape[0]))])
s_new = np.matmul(tfm, s_new)
s_new = s_new.reshape([-1]) if transpose_input else s_new.T.reshape([-1])
# tfm = tfm.reshape([-1])
return dst_img, s_new, tfm
def detect_align(image, image_size=(256,256), scale=0.7, transpose_input=False):
bboxes, landmarks = detector.detect(image)
if len(bboxes) == 0 : return None
elif len(bboxes) > 1:
img_size = image.shape[:2]
bbox_size = bboxes[:,2] * bboxes[:,3]
img_center = img_size / 2
offsets = np.vstack([ bboxes[:,0]+0.5*bboxes[:,2]-img_center[1], bboxes[:,1]+0.5*bboxes[:,3]-img_center[0] ])
offset_dist_squared = np.sum(np.power(offsets,2.0),0)
index = np.argmax(offset_dist_squared*2.0) # some extra weight on the centering
bboxes = bboxes[index][None]
landmarks = landmarks[index][None]
src_pts = landmarks[0]
ref_pts = np.array( [[ -1.58083929e-01, -3.84258929e-02],
[ 1.56533929e-01, -4.01660714e-02],
[ 2.25000000e-04, 1.40505357e-01],
[ -1.29024107e-01, 3.24691964e-01],
[ 1.31516964e-01, 3.23250893e-01]])
img_new, new_pts, tfm = align(image, src_pts, ref_pts, image_size, scale, transpose_input)
return img_new, tfm
|
[
"align.matlab_cp2tform.get_similarity_transform_for_cv2",
"numpy.argmax",
"numpy.power",
"numpy.ones",
"align.mtcnntf.detector.detect",
"cv2.warpAffine",
"numpy.array",
"numpy.matmul",
"numpy.vstack"
] |
[((1998, 2036), 'align.matlab_cp2tform.get_similarity_transform_for_cv2', 'get_similarity_transform_for_cv2', (['s', 'r'], {}), '(s, r)\n', (2030, 2036), False, 'from align.matlab_cp2tform import get_similarity_transform_for_cv2\n'), ((2051, 2091), 'cv2.warpAffine', 'cv2.warpAffine', (['src_img', 'tfm', 'image_size'], {}), '(src_img, tfm, image_size)\n', (2065, 2091), False, 'import cv2\n'), ((2179, 2200), 'numpy.matmul', 'np.matmul', (['tfm', 's_new'], {}), '(tfm, s_new)\n', (2188, 2200), True, 'import numpy as np\n'), ((2453, 2475), 'align.mtcnntf.detector.detect', 'detector.detect', (['image'], {}), '(image)\n', (2468, 2475), False, 'from align.mtcnntf import detector\n'), ((3048, 3211), 'numpy.array', 'np.array', (['[[-0.158083929, -0.0384258929], [0.156533929, -0.0401660714], [0.000225, \n 0.140505357], [-0.129024107, 0.324691964], [0.131516964, 0.323250893]]'], {}), '([[-0.158083929, -0.0384258929], [0.156533929, -0.0401660714], [\n 0.000225, 0.140505357], [-0.129024107, 0.324691964], [0.131516964, \n 0.323250893]])\n', (3056, 3211), True, 'import numpy as np\n'), ((1897, 1929), 'numpy.array', 'np.array', (['[[offset_x, offset_y]]'], {}), '([[offset_x, offset_y]])\n', (1905, 1929), True, 'import numpy as np\n'), ((2140, 2164), 'numpy.ones', 'np.ones', (['(1, s.shape[0])'], {}), '((1, s.shape[0]))\n', (2147, 2164), True, 'import numpy as np\n'), ((2673, 2790), 'numpy.vstack', 'np.vstack', (['[bboxes[:, 0] + 0.5 * bboxes[:, 2] - img_center[1], bboxes[:, 1] + 0.5 *\n bboxes[:, 3] - img_center[0]]'], {}), '([bboxes[:, 0] + 0.5 * bboxes[:, 2] - img_center[1], bboxes[:, 1] +\n 0.5 * bboxes[:, 3] - img_center[0]])\n', (2682, 2790), True, 'import numpy as np\n'), ((2851, 2887), 'numpy.argmax', 'np.argmax', (['(offset_dist_squared * 2.0)'], {}), '(offset_dist_squared * 2.0)\n', (2860, 2887), True, 'import numpy as np\n'), ((2810, 2832), 'numpy.power', 'np.power', (['offsets', '(2.0)'], {}), '(offsets, 2.0)\n', (2818, 2832), True, 'import numpy as np\n'), ((1788, 1805), 'numpy.array', 'np.array', (['src_pts'], {}), '(src_pts)\n', (1796, 1805), True, 'import numpy as np\n'), ((1849, 1866), 'numpy.array', 'np.array', (['ref_pts'], {}), '(ref_pts)\n', (1857, 1866), True, 'import numpy as np\n')]
|
import torch, numpy as np, glob, math, torch.utils.data, scipy.ndimage, multiprocessing as mp
import math
import MinkowskiEngine as ME
from torch.utils.data.sampler import Sampler
import os,sys
MAX_POINTS=3000000
SEM_COLOR_MAP = {
0: (0., 0., 0.),
1: (174., 199., 232.),
2: (152., 223., 138.),
3: (31., 119., 180.),
4: (255., 187., 120.),
5: (188., 189., 34.),
6: (140., 86., 75.),
7: (255., 152., 150.),
8: (214., 39., 40.),
9: (197., 176., 213.),
10: (148., 103., 189.),
11: (196., 156., 148.),
12: (23., 190., 207.),
14: (247., 182., 210.),
15: (66., 188., 102.),
16: (219., 219., 141.),
17: (140., 57., 197.),
18: (202., 185., 52.),
19: (51., 176., 203.),
20: (200., 54., 131.),
21: (92., 193., 61.),
22: (78., 71., 183.),
23: (172., 114., 82.),
24: (255., 127., 14.),
25: (91., 163., 138.),
26: (153., 98., 156.),
27: (140., 153., 101.),
28: (158., 218., 229.),
29: (100., 125., 154.),
30: (178., 127., 135.),
32: (146., 111., 194.),
33: (44., 160., 44.),
34: (112., 128., 144.),
35: (96., 207., 209.),
36: (227., 119., 194.),
37: (213., 92., 176.),
38: (94., 106., 211.),
39: (82., 84., 163.),
40: (100., 85., 144.),
}
# segmantic lable remapper
SEM_CLASS_LABELS = ('wall', 'floor', 'cabinet', 'bed', 'chair', 'sofa', 'table', 'door', 'window',
'bookshelf', 'picture', 'counter', 'desk', 'curtain', 'refrigerator',
'shower curtain', 'toilet', 'sink', 'bathtub', 'otherfurniture')
SEM_VALID_CLASS_IDS = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 16, 24, 28, 33, 34, 36, 39]
SEM_REMAPPER=np.ones(150)*(20)
for i,x in enumerate(SEM_VALID_CLASS_IDS):
SEM_REMAPPER[x]=i
# scene type remapper
TYPE_CLASS_LABELS=('aparment','bathroom','bedroom','conference room','copy','hallway','kitchen','laundry room','living room','office','storage','misc')
TYPE_VALID_CLASS_IDS=[1,2,3,4,8,9,13,14,15,16,18,20,21]
TYPE_REMAPPER=np.ones(22)*(12)
for i,x in enumerate(TYPE_VALID_CLASS_IDS):
TYPE_REMAPPER[x]=i
'''
ScanNet dataset
'''
class ScanNetDataset(torch.utils.data.Dataset):
def __init__(self,path,augment=False,voxel_size=0.02,leave_rate=None,
crop_rate=None,skip_rate=1,ind_remove=None):
torch.utils.data.Dataset.__init__(self)
self.voxel_size=voxel_size
self.augment=augment
self.leave_rate=leave_rate
self.crop_rate=crop_rate
self.skip_rate=skip_rate
self.ind_remove=ind_remove
# load data
self.data=[]
for x in torch.utils.data.DataLoader(
glob.glob(path), collate_fn=lambda x: torch.load(x[0]),num_workers=mp.cpu_count()):
self.data.append(x)
# preprocess data on train/val/test data
for i in range(len(self.data)):
# normalize colors
self.data[i]['feats']/=255
self.data[i]['feats']-=0.5
# scene type label
# self.data[i]['scene_label']=TYPE_REMAPPER[self.data[i]['scene_label']]
self.data[i]['scene_label']-=1
# semantic label
self.data[i]['sem_label']=SEM_REMAPPER[self.data[i]['sem_label'].astype('int')]
def __getitem__(self,n):
crn_sample=self.data[n]
xyz=crn_sample['coords']
feats=crn_sample['feats']
sem_labels=crn_sample['sem_label']
scene_type=crn_sample['scene_label']
scene_name=crn_sample['scene_name']
# filter by semantic index
ind_left=sem_labels!=self.ind_remove
xyz,feats,sem_labels=xyz[ind_left],feats[ind_left],sem_labels[ind_left]
# voxelization
sel = ME.utils.sparse_quantize(xyz / self.voxel_size, return_index=True)
down_xyz, down_feat,down_labels = xyz[sel],feats[sel],sem_labels[sel]
# Get coords, shift to center
coords = np.floor(down_xyz / self.voxel_size)
coords-=coords.min(0)
return (coords,down_feat,down_labels,scene_type,scene_name)
def __len__(self):
return len(self.data)
'''
collate data for each batch
'''
def collate_fn(list_data):
new_list_data = []
num_removed = 0
for data in list_data:
if data is not None:
new_list_data.append(data)
else:
num_removed += 1
list_data = new_list_data
if len(list_data) == 0:
raise ValueError('No data in the batch')
coords, feats, labels,scene_types,scene_names = list(zip(*list_data))
eff_num_batch = len(coords)
assert len(labels) == eff_num_batch
lens = [len(c) for c in coords]
# filter samples
cum_len=np.cumsum(lens)
n_samples=(cum_len<MAX_POINTS).sum()
feats=feats[:n_samples]
labels=labels[:n_samples]
coords=coords[:n_samples]
scene_types=scene_types[:n_samples]
scene_names=scene_names[:n_samples]
# Concatenate all lists
curr_ptr = 0
num_tot_pts = sum(lens[:n_samples])
coords_batch = torch.zeros(num_tot_pts, 4)
feats_batch = torch.from_numpy(np.vstack(feats)).float()
labels_batch=torch.from_numpy(np.hstack(labels)).long()
scene_types_batch=torch.from_numpy(np.hstack(scene_types)).long()
for batch_id in range(n_samples):
coords_batch[curr_ptr:curr_ptr + lens[batch_id], :3] = torch.from_numpy(
coords[batch_id])
coords_batch[curr_ptr:curr_ptr + lens[batch_id], 3] = batch_id
curr_ptr += len(coords[batch_id])
return {
'coords': coords_batch,
'feats': feats_batch,
'sem_labels': labels_batch,
'clf_labels':scene_types_batch,
'scene_names':scene_names
}
class InfSampler(Sampler):
"""Samples elements randomly, without replacement.
Arguments:
data_source (Dataset): dataset to sample from
"""
def __init__(self, data_source, shuffle=True):
self.data_source = data_source
self.shuffle = shuffle
self.reset_permutation()
def reset_permutation(self):
perm = len(self.data_source)
if self.shuffle:
perm = torch.randperm(perm)
self._perm = perm.tolist()
def __iter__(self):
return self
def __next__(self):
if len(self._perm) == 0:
self.reset_permutation()
return self._perm.pop()
def __len__(self):
return len(self.data_source)
def get_iterators(path_train,path_val,config):
# train loader
train_set=ScanNetDataset(path_train,augment=True,voxel_size=config['voxel_size'])
train_args = {
'batch_size': config['train_batch_size'],
'num_workers': config['num_workers'],
'collate_fn': collate_fn,
'sampler':InfSampler(train_set),
'pin_memory': False,
'drop_last': False
}
train_loader = torch.utils.data.DataLoader(train_set, **train_args)
# val loader
val_set=ScanNetDataset(path_val,augment=False,voxel_size=config['voxel_size'])
val_args = {
'batch_size': config['val_batch_size'],
'num_workers': config['num_workers'],
'collate_fn': collate_fn,
'pin_memory': False,
'drop_last': False
}
val_loader = torch.utils.data.DataLoader(val_set,**val_args)
return {
'train': train_loader,
'val': val_loader
}
def get_testdataset(path_test,config):
test_set=ScanNetDataset(path_test,augment=False,voxel_size=config['voxel_size'])
val_args = {
'batch_size': config['test_batch_size'],
'num_workers': config['num_workers'],
'collate_fn': collate_fn,
'pin_memory': False,
'drop_last': False
}
test_loader = torch.utils.data.DataLoader(test_set,**val_args)
return test_loader
def get_valdataset(path_val,config):
# val loader
val_set=ScanNetDataset(path_val,augment=False,voxel_size=config['voxel_size'],
leave_rate=config['leave_rate'],crop_rate=config['crop_rate'],
skip_rate=config['skip_rate'],ind_remove=config['ind_remove'])
val_args = {
'batch_size': config['val_batch_size'],
'num_workers': config['num_workers'],
'collate_fn': collate_fn,
'pin_memory': False,
'drop_last': False
}
val_loader = torch.utils.data.DataLoader(val_set,**val_args)
return val_loader
|
[
"torch.utils.data.DataLoader",
"MinkowskiEngine.utils.sparse_quantize",
"numpy.floor",
"torch.load",
"numpy.ones",
"numpy.hstack",
"multiprocessing.cpu_count",
"numpy.cumsum",
"torch.utils.data.Dataset.__init__",
"torch.randperm",
"glob.glob",
"torch.zeros",
"numpy.vstack",
"torch.from_numpy"
] |
[((1684, 1696), 'numpy.ones', 'np.ones', (['(150)'], {}), '(150)\n', (1691, 1696), True, 'import torch, numpy as np, glob, math, torch.utils.data, scipy.ndimage, multiprocessing as mp\n'), ((2012, 2023), 'numpy.ones', 'np.ones', (['(22)'], {}), '(22)\n', (2019, 2023), True, 'import torch, numpy as np, glob, math, torch.utils.data, scipy.ndimage, multiprocessing as mp\n'), ((4765, 4780), 'numpy.cumsum', 'np.cumsum', (['lens'], {}), '(lens)\n', (4774, 4780), True, 'import torch, numpy as np, glob, math, torch.utils.data, scipy.ndimage, multiprocessing as mp\n'), ((5104, 5131), 'torch.zeros', 'torch.zeros', (['num_tot_pts', '(4)'], {}), '(num_tot_pts, 4)\n', (5115, 5131), False, 'import torch, numpy as np, glob, math, torch.utils.data, scipy.ndimage, multiprocessing as mp\n'), ((6937, 6989), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['train_set'], {}), '(train_set, **train_args)\n', (6964, 6989), False, 'import torch, numpy as np, glob, math, torch.utils.data, scipy.ndimage, multiprocessing as mp\n'), ((7319, 7367), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['val_set'], {}), '(val_set, **val_args)\n', (7346, 7367), False, 'import torch, numpy as np, glob, math, torch.utils.data, scipy.ndimage, multiprocessing as mp\n'), ((7805, 7854), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['test_set'], {}), '(test_set, **val_args)\n', (7832, 7854), False, 'import torch, numpy as np, glob, math, torch.utils.data, scipy.ndimage, multiprocessing as mp\n'), ((8421, 8469), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['val_set'], {}), '(val_set, **val_args)\n', (8448, 8469), False, 'import torch, numpy as np, glob, math, torch.utils.data, scipy.ndimage, multiprocessing as mp\n'), ((2317, 2356), 'torch.utils.data.Dataset.__init__', 'torch.utils.data.Dataset.__init__', (['self'], {}), '(self)\n', (2350, 2356), False, 'import torch, numpy as np, glob, math, torch.utils.data, scipy.ndimage, multiprocessing as mp\n'), ((3784, 3850), 'MinkowskiEngine.utils.sparse_quantize', 'ME.utils.sparse_quantize', (['(xyz / self.voxel_size)'], {'return_index': '(True)'}), '(xyz / self.voxel_size, return_index=True)\n', (3808, 3850), True, 'import MinkowskiEngine as ME\n'), ((3985, 4021), 'numpy.floor', 'np.floor', (['(down_xyz / self.voxel_size)'], {}), '(down_xyz / self.voxel_size)\n', (3993, 4021), True, 'import torch, numpy as np, glob, math, torch.utils.data, scipy.ndimage, multiprocessing as mp\n'), ((5430, 5464), 'torch.from_numpy', 'torch.from_numpy', (['coords[batch_id]'], {}), '(coords[batch_id])\n', (5446, 5464), False, 'import torch, numpy as np, glob, math, torch.utils.data, scipy.ndimage, multiprocessing as mp\n'), ((2666, 2681), 'glob.glob', 'glob.glob', (['path'], {}), '(path)\n', (2675, 2681), False, 'import torch, numpy as np, glob, math, torch.utils.data, scipy.ndimage, multiprocessing as mp\n'), ((6223, 6243), 'torch.randperm', 'torch.randperm', (['perm'], {}), '(perm)\n', (6237, 6243), False, 'import torch, numpy as np, glob, math, torch.utils.data, scipy.ndimage, multiprocessing as mp\n'), ((2733, 2747), 'multiprocessing.cpu_count', 'mp.cpu_count', ([], {}), '()\n', (2745, 2747), True, 'import torch, numpy as np, glob, math, torch.utils.data, scipy.ndimage, multiprocessing as mp\n'), ((5167, 5183), 'numpy.vstack', 'np.vstack', (['feats'], {}), '(feats)\n', (5176, 5183), True, 'import torch, numpy as np, glob, math, torch.utils.data, scipy.ndimage, multiprocessing as mp\n'), ((5227, 5244), 'numpy.hstack', 'np.hstack', (['labels'], {}), '(labels)\n', (5236, 5244), True, 'import torch, numpy as np, glob, math, torch.utils.data, scipy.ndimage, multiprocessing as mp\n'), ((5292, 5314), 'numpy.hstack', 'np.hstack', (['scene_types'], {}), '(scene_types)\n', (5301, 5314), True, 'import torch, numpy as np, glob, math, torch.utils.data, scipy.ndimage, multiprocessing as mp\n'), ((2704, 2720), 'torch.load', 'torch.load', (['x[0]'], {}), '(x[0])\n', (2714, 2720), False, 'import torch, numpy as np, glob, math, torch.utils.data, scipy.ndimage, multiprocessing as mp\n')]
|
import time
from pathlib import Path
import scipy.io
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import nibabel as nib
from nilearn import datasets
from nilearn.input_data import MultiNiftiMasker
from nilearn.image import get_data
from nilearn.mass_univariate import permuted_ols
from sklearn.feature_selection import VarianceThreshold
n_subjects = 2136
var_threshold = 0.001
smoothness = 12
permutations = 5000
jobs = 15
t0 = time.perf_counter()
print('loading and preprocessing data ...')
dir = Path('/mnt/qdata/raheppt1/data/brainage/nako/interim/vbm/test4')
files = sorted(list(dir.glob('*nii')))
keys = [f.stem[:6] for f in files]
tiv = Path('/mnt/qdata/raheppt1/data/brainage/nako/interim/vbm/test4/report/TIV_test4.txt')
tiv = np.array([float(l.split('\t')[0]) for l in tiv.open('r').readlines()])
info = pd.read_csv('/mnt/qdata/raheppt1/data/brainage/nako/interim/nako_age_labels.csv').astype({'key': str, 'age': np.float64})
info = info.set_index('key')
metadata = pd.merge(info.loc[keys]['age'], pd.DataFrame.from_dict({'key': keys, 'tiv': tiv}), how='inner', on='key')
metadata.set_index('key')
dir = Path('/mnt/qdata/raheppt1/data/brainage/nako/interim/vbm/test4/mri')
proc_files = sorted(list(dir.glob('mwp1*nii')))
proc_keys = [f.stem[4:10] for f in proc_files]
proc_metadata = metadata.set_index('key').loc[proc_keys]
print(len(proc_metadata))
gray_matter_map_filenames = proc_files
gray_matter_map_filenames = sorted([str(f) for f in gray_matter_map_filenames])[:n_subjects]
age = np.array(proc_metadata['age'].tolist())[:n_subjects]
tiv = np.array(proc_metadata['tiv'].tolist())[:n_subjects]
tiv[np.isnan(tiv)] = 0
tiv = tiv[:, np.newaxis]
nifti_masker = MultiNiftiMasker(standardize=False, smoothing_fwhm=smoothness, memory=None, n_jobs=jobs, verbose=1) #, cache options
gm_maps_masked = nifti_masker.fit_transform(gray_matter_map_filenames)
gm_maps_masked = np.concatenate(gm_maps_masked, axis=0)
n_samples, n_features = gm_maps_masked.shape
print('%d samples, %d features' % (n_subjects, n_features))
print(f'{time.perf_counter() - t0} s')
### Inference with massively univariate model ###
print("Massively univariate model")
# Remove features with too low between-subject variance
variance_threshold = VarianceThreshold(threshold=var_threshold)
# Statistical inference
data = variance_threshold.fit_transform(gm_maps_masked)
#data = gm_maps_masked
neg_log_pvals, t_scores_original_data, _ = permuted_ols(
age, data, # + intercept as a covariate by default
confounding_vars=tiv,
n_perm=permutations, # 1,000 in the interest of time; 10000 would be better
n_jobs=jobs) # CPUs
signed_neg_log_pvals = neg_log_pvals * np.sign(t_scores_original_data)
signed_neg_log_pvals_unmasked = nifti_masker.inverse_transform(
variance_threshold.inverse_transform(signed_neg_log_pvals))
print(f'{time.perf_counter() - t0} s')
nib.save(signed_neg_log_pvals_unmasked, 'test.nii.gz')
|
[
"nilearn.input_data.MultiNiftiMasker",
"numpy.concatenate",
"pandas.DataFrame.from_dict",
"pandas.read_csv",
"nilearn.mass_univariate.permuted_ols",
"time.perf_counter",
"numpy.isnan",
"nibabel.save",
"pathlib.Path",
"numpy.sign",
"sklearn.feature_selection.VarianceThreshold"
] |
[((459, 478), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (476, 478), False, 'import time\n'), ((531, 595), 'pathlib.Path', 'Path', (['"""/mnt/qdata/raheppt1/data/brainage/nako/interim/vbm/test4"""'], {}), "('/mnt/qdata/raheppt1/data/brainage/nako/interim/vbm/test4')\n", (535, 595), False, 'from pathlib import Path\n'), ((676, 771), 'pathlib.Path', 'Path', (['"""/mnt/qdata/raheppt1/data/brainage/nako/interim/vbm/test4/report/TIV_test4.txt"""'], {}), "(\n '/mnt/qdata/raheppt1/data/brainage/nako/interim/vbm/test4/report/TIV_test4.txt'\n )\n", (680, 771), False, 'from pathlib import Path\n'), ((1147, 1215), 'pathlib.Path', 'Path', (['"""/mnt/qdata/raheppt1/data/brainage/nako/interim/vbm/test4/mri"""'], {}), "('/mnt/qdata/raheppt1/data/brainage/nako/interim/vbm/test4/mri')\n", (1151, 1215), False, 'from pathlib import Path\n'), ((1708, 1811), 'nilearn.input_data.MultiNiftiMasker', 'MultiNiftiMasker', ([], {'standardize': '(False)', 'smoothing_fwhm': 'smoothness', 'memory': 'None', 'n_jobs': 'jobs', 'verbose': '(1)'}), '(standardize=False, smoothing_fwhm=smoothness, memory=None,\n n_jobs=jobs, verbose=1)\n', (1724, 1811), False, 'from nilearn.input_data import MultiNiftiMasker\n'), ((1914, 1952), 'numpy.concatenate', 'np.concatenate', (['gm_maps_masked'], {'axis': '(0)'}), '(gm_maps_masked, axis=0)\n', (1928, 1952), True, 'import numpy as np\n'), ((2263, 2305), 'sklearn.feature_selection.VarianceThreshold', 'VarianceThreshold', ([], {'threshold': 'var_threshold'}), '(threshold=var_threshold)\n', (2280, 2305), False, 'from sklearn.feature_selection import VarianceThreshold\n'), ((2454, 2533), 'nilearn.mass_univariate.permuted_ols', 'permuted_ols', (['age', 'data'], {'confounding_vars': 'tiv', 'n_perm': 'permutations', 'n_jobs': 'jobs'}), '(age, data, confounding_vars=tiv, n_perm=permutations, n_jobs=jobs)\n', (2466, 2533), False, 'from nilearn.mass_univariate import permuted_ols\n'), ((2894, 2948), 'nibabel.save', 'nib.save', (['signed_neg_log_pvals_unmasked', '"""test.nii.gz"""'], {}), "(signed_neg_log_pvals_unmasked, 'test.nii.gz')\n", (2902, 2948), True, 'import nibabel as nib\n'), ((1041, 1090), 'pandas.DataFrame.from_dict', 'pd.DataFrame.from_dict', (["{'key': keys, 'tiv': tiv}"], {}), "({'key': keys, 'tiv': tiv})\n", (1063, 1090), True, 'import pandas as pd\n'), ((1649, 1662), 'numpy.isnan', 'np.isnan', (['tiv'], {}), '(tiv)\n', (1657, 1662), True, 'import numpy as np\n'), ((2695, 2726), 'numpy.sign', 'np.sign', (['t_scores_original_data'], {}), '(t_scores_original_data)\n', (2702, 2726), True, 'import numpy as np\n'), ((847, 933), 'pandas.read_csv', 'pd.read_csv', (['"""/mnt/qdata/raheppt1/data/brainage/nako/interim/nako_age_labels.csv"""'], {}), "(\n '/mnt/qdata/raheppt1/data/brainage/nako/interim/nako_age_labels.csv')\n", (858, 933), True, 'import pandas as pd\n'), ((2068, 2087), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (2085, 2087), False, 'import time\n'), ((2864, 2883), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (2881, 2883), False, 'import time\n')]
|
import shutil
from os import mkdir, remove
from os.path import dirname, isdir, isfile, join
import pytest
from geoalchemy2.shape import to_shape
from geoalchemy2.types import WKTElement
from numpy.testing import assert_almost_equal
from rasterio.crs import CRS
from snowexsql.projection import *
@pytest.mark.parametrize('info, expected', [
# Test we add UTM info when its not provided
({'latitude': 39.039, 'longitude': -108.003}, {'easting': 759397.644, 'northing': 4325379.675, 'utm_zone': 12}),
# Test we add lat long when its not provided
({'easting': 759397.644, 'northing': 4325379.675, 'utm_zone': 12}, {'latitude': 39.039, 'longitude': -108.003}),
# Test ignoring easting in another projection
({'latitude': 39.008078, 'longitude': -108.184794, 'utm_wgs84_easting': 743766.4795, 'utm_wgs84_northing': 4321444.155},
{'easting': 743766.480, 'northing': 4321444.155}),
# Confirm we force the zone to zone 12
({'latitude':39.097464, 'longitude':-107.862476}, {'northing':4332280.1658, 'easting':771338.607})
])
def test_reproject_point_in_dict(info, expected):
"""
Test adding point projection information
"""
result = reproject_point_in_dict(info)
for k, v in expected.items():
assert k in result
if type(v) == float:
assert_almost_equal(v, result[k], 3)
else:
assert v == result[k]
def test_add_geom():
"""
Test add_geom adds a WKB element to a dictionary containing easting/northing info
"""
info = {'easting': 759397.644, 'northing': 4325379.675, 'utm_zone': 12}
result = add_geom(info, 26912)
# Ensure we added a geom key and value that is WKTE
assert 'geom' in result.keys()
assert type(result['geom']) == WKTElement
# Convert it to pyshapely for testing/ data integrity
p = to_shape(result['geom'])
assert p.x == info['easting']
assert p.y == info['northing']
assert result['geom'].srid == 26912
class TestReprojectRasterByEPSG():
output_f = join(dirname(__file__), 'test.tif')
# def teardown_method(self):
# '''
# Remove our output file
# '''
# if isfile(self.output_f):
# remove(self.output_f)
@classmethod
def teardown_method(self):
remove(self.output_f)
@pytest.mark.parametrize("input_f, epsg, bounds", [
('uavsar_latlon.amp1.real.tif', 26912,
(748446.1945536422, 4325651.650770078, 751909.2857505103, 4328702.971977075)),
])
def test_reproject(self, input_f, epsg, bounds):
"""
test reprojecting a raster from EPSG to another
"""
d = dirname(__file__)
f = join(d, 'data', input_f)
reproject_raster_by_epsg(f, self.output_f, epsg)
with rasterio.open(self.output_f) as dataset:
dbounds = dataset.bounds
dcrs = dataset.crs
# Test our epsg was assigned
assert CRS.from_epsg(epsg) == dataset.crs
# Assert bounds
for i, v in enumerate(bounds):
assert_almost_equal(v, dataset.bounds[i], 3)
|
[
"os.remove",
"numpy.testing.assert_almost_equal",
"os.path.dirname",
"geoalchemy2.shape.to_shape",
"pytest.mark.parametrize",
"os.path.join",
"rasterio.crs.CRS.from_epsg"
] |
[((301, 876), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""info, expected"""', "[({'latitude': 39.039, 'longitude': -108.003}, {'easting': 759397.644,\n 'northing': 4325379.675, 'utm_zone': 12}), ({'easting': 759397.644,\n 'northing': 4325379.675, 'utm_zone': 12}, {'latitude': 39.039,\n 'longitude': -108.003}), ({'latitude': 39.008078, 'longitude': -\n 108.184794, 'utm_wgs84_easting': 743766.4795, 'utm_wgs84_northing': \n 4321444.155}, {'easting': 743766.48, 'northing': 4321444.155}), ({\n 'latitude': 39.097464, 'longitude': -107.862476}, {'northing': \n 4332280.1658, 'easting': 771338.607})]"], {}), "('info, expected', [({'latitude': 39.039,\n 'longitude': -108.003}, {'easting': 759397.644, 'northing': 4325379.675,\n 'utm_zone': 12}), ({'easting': 759397.644, 'northing': 4325379.675,\n 'utm_zone': 12}, {'latitude': 39.039, 'longitude': -108.003}), ({\n 'latitude': 39.008078, 'longitude': -108.184794, 'utm_wgs84_easting': \n 743766.4795, 'utm_wgs84_northing': 4321444.155}, {'easting': 743766.48,\n 'northing': 4321444.155}), ({'latitude': 39.097464, 'longitude': -\n 107.862476}, {'northing': 4332280.1658, 'easting': 771338.607})])\n", (324, 876), False, 'import pytest\n'), ((1840, 1864), 'geoalchemy2.shape.to_shape', 'to_shape', (["result['geom']"], {}), "(result['geom'])\n", (1848, 1864), False, 'from geoalchemy2.shape import to_shape\n'), ((2313, 2491), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""input_f, epsg, bounds"""', "[('uavsar_latlon.amp1.real.tif', 26912, (748446.1945536422, \n 4325651.650770078, 751909.2857505103, 4328702.971977075))]"], {}), "('input_f, epsg, bounds', [(\n 'uavsar_latlon.amp1.real.tif', 26912, (748446.1945536422, \n 4325651.650770078, 751909.2857505103, 4328702.971977075))])\n", (2336, 2491), False, 'import pytest\n'), ((2031, 2048), 'os.path.dirname', 'dirname', (['__file__'], {}), '(__file__)\n', (2038, 2048), False, 'from os.path import dirname, isdir, isfile, join\n'), ((2285, 2306), 'os.remove', 'remove', (['self.output_f'], {}), '(self.output_f)\n', (2291, 2306), False, 'from os import mkdir, remove\n'), ((2651, 2668), 'os.path.dirname', 'dirname', (['__file__'], {}), '(__file__)\n', (2658, 2668), False, 'from os.path import dirname, isdir, isfile, join\n'), ((2681, 2705), 'os.path.join', 'join', (['d', '"""data"""', 'input_f'], {}), "(d, 'data', input_f)\n", (2685, 2705), False, 'from os.path import dirname, isdir, isfile, join\n'), ((1314, 1350), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['v', 'result[k]', '(3)'], {}), '(v, result[k], 3)\n', (1333, 1350), False, 'from numpy.testing import assert_almost_equal\n'), ((2940, 2959), 'rasterio.crs.CRS.from_epsg', 'CRS.from_epsg', (['epsg'], {}), '(epsg)\n', (2953, 2959), False, 'from rasterio.crs import CRS\n'), ((3051, 3095), 'numpy.testing.assert_almost_equal', 'assert_almost_equal', (['v', 'dataset.bounds[i]', '(3)'], {}), '(v, dataset.bounds[i], 3)\n', (3070, 3095), False, 'from numpy.testing import assert_almost_equal\n')]
|
# USAGE
# python mixed_training.py --dataset Houses-dataset/Houses\ Dataset/
# import the necessary packages
from pyimagesearch import datasets
from pyimagesearch import models
from sklearn.model_selection import train_test_split
from keras.layers.core import Dense
from keras.models import Model
from keras.optimizers import Adam
from keras.layers import concatenate
import numpy as np
import argparse
import locale
import os
# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-d", "--dataset", type=str, required=True,
help="path to input dataset of house images")
args = vars(ap.parse_args())
# construct the path to the input .txt file that contains information
# on each house in the dataset and then load the dataset
print("[INFO] loading house attributes...")
inputPath = os.path.sep.join([args["dataset"], "HousesInfo.txt"])
df = datasets.load_house_attributes(inputPath)
# load the house images and then scale the pixel intensities to the
# range [0, 1]
print("[INFO] loading house images...")
images = datasets.load_house_images(df, args["dataset"])
images = images / 255.0
# partition the data into training and testing splits using 75% of
# the data for training and the remaining 25% for testing
print("[INFO] processing data...")
split = train_test_split(df, images, test_size=0.25, random_state=42)
(trainAttrX, testAttrX, trainImagesX, testImagesX) = split
# find the largest house price in the training set and use it to
# scale our house prices to the range [0, 1] (will lead to better
# training and convergence)
maxPrice = trainAttrX["price"].max()
trainY = trainAttrX["price"] / maxPrice
testY = testAttrX["price"] / maxPrice
# process the house attributes data by performing min-max scaling
# on continuous features, one-hot encoding on categorical features,
# and then finally concatenating them together
(trainAttrX, testAttrX) = datasets.process_house_attributes(df,
trainAttrX, testAttrX)
# create the MLP and CNN models
mlp = models.create_mlp(trainAttrX.shape[1], regress=False)
cnn = models.create_cnn(64, 64, 3, regress=False)
# create the input to our final set of layers as the *output* of both
# the MLP and CNN
combinedInput = concatenate([mlp.output, cnn.output])
# our final FC layer head will have two dense layers, the final one
# being our regression head
x = Dense(4, activation="relu")(combinedInput)
x = Dense(1, activation="linear")(x)
# our final model will accept categorical/numerical data on the MLP
# input and images on the CNN input, outputting a single value (the
# predicted price of the house)
model = Model(inputs=[mlp.input, cnn.input], outputs=x)
# compile the model using mean absolute percentage error as our loss,
# implying that we seek to minimize the absolute percentage difference
# between our price *predictions* and the *actual prices*
opt = Adam(lr=1e-3, decay=1e-3 / 200)
model.compile(loss="mean_absolute_percentage_error", optimizer=opt)
# train the model
print("[INFO] training model...")
model.fit(
[trainAttrX, trainImagesX], trainY,
validation_data=([testAttrX, testImagesX], testY),
epochs=200, batch_size=8)
# make predictions on the testing data
print("[INFO] predicting house prices...")
preds = model.predict([testAttrX, testImagesX])
# compute the difference between the *predicted* house prices and the
# *actual* house prices, then compute the percentage difference and
# the absolute percentage difference
diff = preds.flatten() - testY
percentDiff = (diff / testY) * 100
absPercentDiff = np.abs(percentDiff)
# compute the mean and standard deviation of the absolute percentage
# difference
mean = np.mean(absPercentDiff)
std = np.std(absPercentDiff)
# finally, show some statistics on our model
locale.setlocale(locale.LC_ALL, "en_US.UTF-8")
print("[INFO] avg. house price: {}, std house price: {}".format(
locale.currency(df["price"].mean(), grouping=True),
locale.currency(df["price"].std(), grouping=True)))
print("[INFO] mean: {:.2f}%, std: {:.2f}%".format(mean, std))
|
[
"keras.layers.core.Dense",
"pyimagesearch.models.create_mlp",
"numpy.abs",
"argparse.ArgumentParser",
"numpy.std",
"sklearn.model_selection.train_test_split",
"pyimagesearch.models.create_cnn",
"keras.optimizers.Adam",
"keras.models.Model",
"pyimagesearch.datasets.process_house_attributes",
"numpy.mean",
"locale.setlocale",
"pyimagesearch.datasets.load_house_attributes",
"os.path.sep.join",
"keras.layers.concatenate",
"pyimagesearch.datasets.load_house_images"
] |
[((490, 515), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (513, 515), False, 'import argparse\n'), ((836, 889), 'os.path.sep.join', 'os.path.sep.join', (["[args['dataset'], 'HousesInfo.txt']"], {}), "([args['dataset'], 'HousesInfo.txt'])\n", (852, 889), False, 'import os\n'), ((895, 936), 'pyimagesearch.datasets.load_house_attributes', 'datasets.load_house_attributes', (['inputPath'], {}), '(inputPath)\n', (925, 936), False, 'from pyimagesearch import datasets\n'), ((1070, 1117), 'pyimagesearch.datasets.load_house_images', 'datasets.load_house_images', (['df', "args['dataset']"], {}), "(df, args['dataset'])\n", (1096, 1117), False, 'from pyimagesearch import datasets\n'), ((1311, 1372), 'sklearn.model_selection.train_test_split', 'train_test_split', (['df', 'images'], {'test_size': '(0.25)', 'random_state': '(42)'}), '(df, images, test_size=0.25, random_state=42)\n', (1327, 1372), False, 'from sklearn.model_selection import train_test_split\n'), ((1915, 1975), 'pyimagesearch.datasets.process_house_attributes', 'datasets.process_house_attributes', (['df', 'trainAttrX', 'testAttrX'], {}), '(df, trainAttrX, testAttrX)\n', (1948, 1975), False, 'from pyimagesearch import datasets\n'), ((2016, 2069), 'pyimagesearch.models.create_mlp', 'models.create_mlp', (['trainAttrX.shape[1]'], {'regress': '(False)'}), '(trainAttrX.shape[1], regress=False)\n', (2033, 2069), False, 'from pyimagesearch import models\n'), ((2076, 2119), 'pyimagesearch.models.create_cnn', 'models.create_cnn', (['(64)', '(64)', '(3)'], {'regress': '(False)'}), '(64, 64, 3, regress=False)\n', (2093, 2119), False, 'from pyimagesearch import models\n'), ((2225, 2262), 'keras.layers.concatenate', 'concatenate', (['[mlp.output, cnn.output]'], {}), '([mlp.output, cnn.output])\n', (2236, 2262), False, 'from keras.layers import concatenate\n'), ((2621, 2668), 'keras.models.Model', 'Model', ([], {'inputs': '[mlp.input, cnn.input]', 'outputs': 'x'}), '(inputs=[mlp.input, cnn.input], outputs=x)\n', (2626, 2668), False, 'from keras.models import Model\n'), ((2875, 2908), 'keras.optimizers.Adam', 'Adam', ([], {'lr': '(0.001)', 'decay': '(0.001 / 200)'}), '(lr=0.001, decay=0.001 / 200)\n', (2879, 2908), False, 'from keras.optimizers import Adam\n'), ((3545, 3564), 'numpy.abs', 'np.abs', (['percentDiff'], {}), '(percentDiff)\n', (3551, 3564), True, 'import numpy as np\n'), ((3655, 3678), 'numpy.mean', 'np.mean', (['absPercentDiff'], {}), '(absPercentDiff)\n', (3662, 3678), True, 'import numpy as np\n'), ((3685, 3707), 'numpy.std', 'np.std', (['absPercentDiff'], {}), '(absPercentDiff)\n', (3691, 3707), True, 'import numpy as np\n'), ((3754, 3800), 'locale.setlocale', 'locale.setlocale', (['locale.LC_ALL', '"""en_US.UTF-8"""'], {}), "(locale.LC_ALL, 'en_US.UTF-8')\n", (3770, 3800), False, 'import locale\n'), ((2364, 2391), 'keras.layers.core.Dense', 'Dense', (['(4)'], {'activation': '"""relu"""'}), "(4, activation='relu')\n", (2369, 2391), False, 'from keras.layers.core import Dense\n'), ((2411, 2440), 'keras.layers.core.Dense', 'Dense', (['(1)'], {'activation': '"""linear"""'}), "(1, activation='linear')\n", (2416, 2440), False, 'from keras.layers.core import Dense\n')]
|
import numpy as np
import tensorflow as tf
from gym_ds3.schedulers.deepsocs.average_reward import AveragePerStepReward
from gym_ds3.schedulers.deepsocs.compute_baselines import get_piecewise_linear_fit_baseline
from gym_ds3.schedulers.deepsocs.deepsocs_scheduler import Deepsocs
from gym_ds3.schedulers.models.deepsocs_model import create_deepsocs_model, create_deepsocs_graph
from gym_ds3.envs.utils.helper_deepsocs import suppress_tf_warning, discount
class ParameterServer(object):
def __init__(self, args):
self.args = args
self.seed = args.seed
suppress_tf_warning() # suppress TF warnings
# AAD model
self.model, self.sess = create_deepsocs_model(args)
self.graph = create_deepsocs_graph(args=args, model=self.model)
# Deepsocs Scheduler
self.deepsocs = Deepsocs(args, self.model, self.sess)
self.avg_reward_calculator = AveragePerStepReward(size=100000)
# Initialize model
tf.set_random_seed(self.seed)
np.random.seed(self.seed)
self.sess.run(tf.global_variables_initializer())
# Flag to initialize assign operations for 'set_weights()'
self.FIRST_SET_FLAG = True
def get_weights(self):
weight_vals = self.sess.run(self.model['all_vars'])
return weight_vals
def set_weights(self, weight_vals):
"""
Set weights without memory leakage
"""
if self.FIRST_SET_FLAG:
self.FIRST_SET_FLAG = False
self.assign_placeholders = []
self.assign_ops = []
for w_idx, weight_tf_var in enumerate(self.model['all_vars']):
a = weight_tf_var
assign_placeholder = tf.placeholder(a.dtype, shape=a.get_shape())
assign_op = a.assign(assign_placeholder)
self.assign_placeholders.append(assign_placeholder)
self.assign_ops.append(assign_op)
for w_idx, weight_tf_var in enumerate(self.model['all_vars']):
self.sess.run(self.assign_ops[w_idx],
{self.assign_placeholders[w_idx]: weight_vals[w_idx]})
def apply_gradients(self, gradients):
self.sess.run(self.graph['apply_grads'], feed_dict={
i: d for i, d in zip(self.graph['gradients'], gradients)
})
def compute_advantages(self, ops_vals):
# calculate advantages (input-dependent baselines)
all_times, all_diff_times, all_rewards, last_returns = [], [], [], []
results = {}
for ops_val in ops_vals:
rollout_val = ops_val[0]
stat = ops_val[1]
diff_time = np.array(rollout_val['wall_time'][1:]) - np.array(rollout_val['wall_time'][:-1])
self.avg_reward_calculator.add_list_filter_zero(rollout_val['reward'], diff_time)
all_diff_times.append(diff_time)
all_times.append(rollout_val['wall_time'][1:])
all_rewards.append(rollout_val['reward'])
for k, v in stat.items():
try:
results[k].append(v)
except:
results.update({k: []})
results[k].append(v)
adv, all_cum_reward = compute_advantage(
self.args, self.avg_reward_calculator, all_rewards, all_diff_times, all_times)
for cum_reward in all_cum_reward:
last_returns.append(cum_reward[-1])
return results, adv
def compute_advantage(args, reward_calculator, all_rewards, all_diff_times, all_times):
# compute differential reward
all_cum_reward = []
avg_per_step_reward = reward_calculator.get_avg_per_step_reward()
for i in range(args.num_agents):
# differential reward mode on
rewards = np.array([r - avg_per_step_reward * t for \
(r, t) in zip(all_rewards[i], all_diff_times[i])])
cum_reward = discount(rewards, args.gamma)
all_cum_reward.append(cum_reward)
baselines = get_piecewise_linear_fit_baseline(all_cum_reward, all_times)
# give worker back the advantage
advs = []
for i in range(args.num_agents):
batch_adv = all_cum_reward[i] - baselines[i]
batch_adv = np.reshape(batch_adv, [len(batch_adv), 1])
advs.append(batch_adv)
return advs, all_cum_reward
|
[
"gym_ds3.schedulers.deepsocs.average_reward.AveragePerStepReward",
"gym_ds3.schedulers.deepsocs.compute_baselines.get_piecewise_linear_fit_baseline",
"gym_ds3.schedulers.models.deepsocs_model.create_deepsocs_graph",
"numpy.random.seed",
"gym_ds3.schedulers.models.deepsocs_model.create_deepsocs_model",
"tensorflow.global_variables_initializer",
"gym_ds3.schedulers.deepsocs.deepsocs_scheduler.Deepsocs",
"gym_ds3.envs.utils.helper_deepsocs.suppress_tf_warning",
"tensorflow.set_random_seed",
"numpy.array",
"gym_ds3.envs.utils.helper_deepsocs.discount"
] |
[((4083, 4143), 'gym_ds3.schedulers.deepsocs.compute_baselines.get_piecewise_linear_fit_baseline', 'get_piecewise_linear_fit_baseline', (['all_cum_reward', 'all_times'], {}), '(all_cum_reward, all_times)\n', (4116, 4143), False, 'from gym_ds3.schedulers.deepsocs.compute_baselines import get_piecewise_linear_fit_baseline\n'), ((583, 604), 'gym_ds3.envs.utils.helper_deepsocs.suppress_tf_warning', 'suppress_tf_warning', ([], {}), '()\n', (602, 604), False, 'from gym_ds3.envs.utils.helper_deepsocs import suppress_tf_warning, discount\n'), ((682, 709), 'gym_ds3.schedulers.models.deepsocs_model.create_deepsocs_model', 'create_deepsocs_model', (['args'], {}), '(args)\n', (703, 709), False, 'from gym_ds3.schedulers.models.deepsocs_model import create_deepsocs_model, create_deepsocs_graph\n'), ((731, 781), 'gym_ds3.schedulers.models.deepsocs_model.create_deepsocs_graph', 'create_deepsocs_graph', ([], {'args': 'args', 'model': 'self.model'}), '(args=args, model=self.model)\n', (752, 781), False, 'from gym_ds3.schedulers.models.deepsocs_model import create_deepsocs_model, create_deepsocs_graph\n'), ((836, 873), 'gym_ds3.schedulers.deepsocs.deepsocs_scheduler.Deepsocs', 'Deepsocs', (['args', 'self.model', 'self.sess'], {}), '(args, self.model, self.sess)\n', (844, 873), False, 'from gym_ds3.schedulers.deepsocs.deepsocs_scheduler import Deepsocs\n'), ((920, 953), 'gym_ds3.schedulers.deepsocs.average_reward.AveragePerStepReward', 'AveragePerStepReward', ([], {'size': '(100000)'}), '(size=100000)\n', (940, 953), False, 'from gym_ds3.schedulers.deepsocs.average_reward import AveragePerStepReward\n'), ((990, 1019), 'tensorflow.set_random_seed', 'tf.set_random_seed', (['self.seed'], {}), '(self.seed)\n', (1008, 1019), True, 'import tensorflow as tf\n'), ((1028, 1053), 'numpy.random.seed', 'np.random.seed', (['self.seed'], {}), '(self.seed)\n', (1042, 1053), True, 'import numpy as np\n'), ((3993, 4022), 'gym_ds3.envs.utils.helper_deepsocs.discount', 'discount', (['rewards', 'args.gamma'], {}), '(rewards, args.gamma)\n', (4001, 4022), False, 'from gym_ds3.envs.utils.helper_deepsocs import suppress_tf_warning, discount\n'), ((1076, 1109), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (1107, 1109), True, 'import tensorflow as tf\n'), ((2685, 2723), 'numpy.array', 'np.array', (["rollout_val['wall_time'][1:]"], {}), "(rollout_val['wall_time'][1:])\n", (2693, 2723), True, 'import numpy as np\n'), ((2726, 2765), 'numpy.array', 'np.array', (["rollout_val['wall_time'][:-1]"], {}), "(rollout_val['wall_time'][:-1])\n", (2734, 2765), True, 'import numpy as np\n')]
|
#! /usr/bin/env python
#################################################################################
# File Name : ./layer.py
# Created By : yang
# Creation Date : [2017-11-15 12:51]
# Last Modified : [2017-11-15 13:09]
# Description : some layers definition
#################################################################################
import lasagne, theano
import numpy as np
import theano.tensor as T
DTYPE = "float32"
class FeatureCombineLayer(lasagne.layers.MergeLayer):
def __init__(self, incomings, **kwargs):
super(FeatureCombineLayer, self).__init__(incomings, **kwargs)
max_size = self.output_shape[2]
self.one = T.ones((1, max_size), dtype=DTYPE)
def get_output_shape_for(self, input_shapes, **kwargs):
return (input_shapes[0][0], input_shapes[0][1] + input_shapes[1][1] * 2, input_shapes[0][2], input_shapes[0][3])
def get_output_for(self, input,**kwargs):
feature2d = input[0]
feature1d = input[1]
feature1d_h = feature1d.dimshuffle(0, 1, 2, 'x')
feature1d_h = T.tensordot(feature1d_h, self.one, [[3], [0]])
feature1d_v = feature1d_h.dimshuffle(0, 1, 3, 2)
return T.concatenate([feature2d, feature1d_h, feature1d_v], axis = 1)
class Feature2dBiasLayer(lasagne.layers.Layer):
def __init__(self, incoming = None, **kwargs):
super(Feature2dBiasLayer,self).__init__(incoming, **kwargs)
self.max_size = self.output_shape[2]
###generate zero
self.bias = np.zeros((7, self.max_size, self.max_size), dtype = DTYPE)
for i in xrange(self.max_size):
for j in xrange(self.max_size):
delta = abs(i - j)
if delta < 14:
t = 0
elif delta < 18:
t = 1
elif delta < 23:
t = 2
elif delta < 28:
t = 3
elif delta < 38:
t = 4
elif delta < 48:
t = 5
else:
t = 6
self.bias[t, i, j] = 1.0
self.bias = theano.shared(self.bias)
self.bias = self.bias.dimshuffle('x', 0, 1, 2)
def get_output_shape_for(self, input_shape, **kwargs):
return (input_shape[0], input_shape[1] + 7, input_shape[2], input_shape[3])
def get_output_for(self, input, **kwargs):
batch_size = input.shape[0]
one = T.ones((batch_size, 1), dtype=DTYPE)
tmp = T.tensordot(one, self.bias, [[1], [0]])
return T.concatenate([input, tmp], axis = 1)
class LinearLayer(lasagne.layers.Layer):
def __init__(self, incoming = None, max_size = 256, deepth = 25, W = lasagne.init.GlorotUniform(), b = lasagne.init.Constant(0.0),num_output = 1,**kwargs):
super(LinearLayer, self).__init__(incoming, **kwargs)
self.max_size = max_size
self.deepth = deepth
self.num_output = num_output
self.W = self.add_param(W,(self.deepth,num_output), name = "W")
self.b = self.add_param(b, (num_output,), name = 'b')
def get_output_shape_for(self, input_shape, **kwargs):
return (input_shape[0], self.num_output, input_shape[2], input_shape[3])
def get_output_for(self, input, **kwargs):
tmp = T.tensordot(input, self.W, [[1],[0]]).dimshuffle(0, 3, 1, 2)
return tmp + self.b[None,:,None,None]
|
[
"theano.tensor.concatenate",
"lasagne.init.GlorotUniform",
"lasagne.init.Constant",
"numpy.zeros",
"theano.tensor.tensordot",
"theano.shared",
"theano.tensor.ones"
] |
[((741, 775), 'theano.tensor.ones', 'T.ones', (['(1, max_size)'], {'dtype': 'DTYPE'}), '((1, max_size), dtype=DTYPE)\n', (747, 775), True, 'import theano.tensor as T\n'), ((1146, 1192), 'theano.tensor.tensordot', 'T.tensordot', (['feature1d_h', 'self.one', '[[3], [0]]'], {}), '(feature1d_h, self.one, [[3], [0]])\n', (1157, 1192), True, 'import theano.tensor as T\n'), ((1266, 1326), 'theano.tensor.concatenate', 'T.concatenate', (['[feature2d, feature1d_h, feature1d_v]'], {'axis': '(1)'}), '([feature2d, feature1d_h, feature1d_v], axis=1)\n', (1279, 1326), True, 'import theano.tensor as T\n'), ((1588, 1644), 'numpy.zeros', 'np.zeros', (['(7, self.max_size, self.max_size)'], {'dtype': 'DTYPE'}), '((7, self.max_size, self.max_size), dtype=DTYPE)\n', (1596, 1644), True, 'import numpy as np\n'), ((2228, 2252), 'theano.shared', 'theano.shared', (['self.bias'], {}), '(self.bias)\n', (2241, 2252), False, 'import lasagne, theano\n'), ((2554, 2590), 'theano.tensor.ones', 'T.ones', (['(batch_size, 1)'], {'dtype': 'DTYPE'}), '((batch_size, 1), dtype=DTYPE)\n', (2560, 2590), True, 'import theano.tensor as T\n'), ((2605, 2644), 'theano.tensor.tensordot', 'T.tensordot', (['one', 'self.bias', '[[1], [0]]'], {}), '(one, self.bias, [[1], [0]])\n', (2616, 2644), True, 'import theano.tensor as T\n'), ((2660, 2695), 'theano.tensor.concatenate', 'T.concatenate', (['[input, tmp]'], {'axis': '(1)'}), '([input, tmp], axis=1)\n', (2673, 2695), True, 'import theano.tensor as T\n'), ((2813, 2841), 'lasagne.init.GlorotUniform', 'lasagne.init.GlorotUniform', ([], {}), '()\n', (2839, 2841), False, 'import lasagne, theano\n'), ((2847, 2873), 'lasagne.init.Constant', 'lasagne.init.Constant', (['(0.0)'], {}), '(0.0)\n', (2868, 2873), False, 'import lasagne, theano\n'), ((3398, 3436), 'theano.tensor.tensordot', 'T.tensordot', (['input', 'self.W', '[[1], [0]]'], {}), '(input, self.W, [[1], [0]])\n', (3409, 3436), True, 'import theano.tensor as T\n')]
|
import os, cv2
import torch
from torch import nn
import numpy as np
def weights_path(_file_, _root_num, dirname):
basepath = os.path.dirname(_file_)
backs = [".."]*_root_num
model_dir = os.path.abspath(os.path.join(basepath, *backs, dirname))
return model_dir
def _check_ins(name, val, cls, allow_none=False, default=None):
if allow_none and val is None:
return default
if not isinstance(val, cls):
err = 'Argument \'{}\' must be {}, but got {}'
if isinstance(cls, (tuple, list)):
types = [c.__name__ for c in cls]
err = err.format(name, types, type(val).__name__)
raise ValueError(err)
else:
err = err.format(name, cls.__name__, type(val).__name__)
raise ValueError(err)
return val
def _check_retval(funcname, val, cls):
if not isinstance(val, cls):
err = '\'{}\' must return {}, but got {}'
if isinstance(cls, (tuple, list)):
types = [c.__name__ for c in cls]
err = err.format(funcname, types, type(val).__name__)
raise ValueError(err)
else:
err = err.format(funcname, cls.__name__, type(val).__name__)
raise ValueError(err)
return val
def _check_norm(name, val):
if isinstance(val, (float, int)):
val = torch.tensor([float(val)], requires_grad=False)
elif isinstance(val, (list, tuple)):
val = torch.tensor(val, requires_grad=False).float()
elif not isinstance(val, torch.Tensor):
raise ValueError('{} must be int, float, list, tuple, Tensor, but got {}'.format(name, type(val).__name__))
return val
def _initialize_xavier_uniform(layers):
from .models.layers import ConvRelu
for module in layers.modules():
if isinstance(module, nn.Conv2d):
nn.init.xavier_uniform_(module.weight)
if module.bias is not None:
nn.init.constant_(module.bias, 0)
elif isinstance(module, ConvRelu):
nn.init.xavier_uniform_(module.conv.weight)
if module.conv.bias is not None:
nn.init.constant_(module.conv.bias, 0)
def _get_model_url(name):
model_urls = {
'vgg11': 'https://download.pytorch.org/models/vgg11-bbd30ac9.pth',
'vgg13': 'https://download.pytorch.org/models/vgg13-c768596a.pth',
'vgg16': 'https://download.pytorch.org/models/vgg16-397923af.pth',
'vgg19': 'https://download.pytorch.org/models/vgg19-dcbb9e9d.pth',
'vgg11_bn': 'https://download.pytorch.org/models/vgg11_bn-6002323d.pth',
'vgg13_bn': 'https://download.pytorch.org/models/vgg13_bn-abd245e5.pth',
'vgg16_bn': 'https://download.pytorch.org/models/vgg16_bn-6c64b313.pth',
'vgg19_bn': 'https://download.pytorch.org/models/vgg19_bn-c79401a0.pth',
}
return model_urls[name]
def _check_image(image, device, size=None):
"""
:param image: ndarray or Tensor of list or tuple, or ndarray, or Tensor. Note that each type will be handled as;
ndarray of list or tuple, ndarray: (?, h, w, c). channel order will be handled as RGB
Tensor of list or tuple, Tensor: (?, c, h, w). channel order will be handled as RGB
:param device: torch.device
:param size: None or tuple, if None is passed, check will not be done
Note that size = (w, h)
:return:
img: Tensor, shape = (b, c, h, w)
orig_imgs: list of Tensor, shape = (c, h, w) these images may be used for visualization
"""
orig_imgs = []
def __check(_tim, _cim, cfirst):
"""
Note that 2d or 3d image is resizable
:param _tim: tensor, shape = (h, w, ?) or (?, h, w)
:param _cim: ndarray, shape = (h, w, ?) or (?, h, w)
:return:
tims: tensor, shape = (c, h, w)
cims: ndarray, shape = (h, w, c)
"""
#### check size of tensor ####
if size:
h, w = _tim.shape[-2:] if cfirst else _tim.shape[:2]
wcond = size[0] if size[0] is not None else w
hcond = size[1] if size[1] is not None else h
if not (h == hcond and w == wcond):
# do resize
if cfirst and _cim.ndim == 3:
# note that _cim's shape must be (c, h, w)
_cim = _cim.transpose((1, 2, 0))
# _cim's shape = (h, w, ?)
resized_cim = cv2.resize(_cim, (wcond, hcond))
return __check(torch.tensor(resized_cim, requires_grad=False), _cim, cfirst=False)
#### check tensor ####
assert isinstance(_tim, torch.Tensor)
if _tim.ndim == 2:
tim = _tim.unsqueeze(2)
elif _tim.ndim == 3:
tim = _tim
else:
raise ValueError('Invalid image found. image must be 2d or 3d, but got {}'.format(_tim.ndim))
if not cfirst:
# note that tim's shape must be (h, w, c)
tim = tim.permute((2, 0, 1))
#### check cvimg ####
assert isinstance(_cim, np.ndarray)
if _cim.ndim == 2:
cim = np.broadcast_to(np.expand_dims(_cim, 2), (_cim.shape[0], _cim.shape[1], 3)).copy()
elif _cim.ndim == 3:
cim = _cim
else:
raise ValueError('Invalid image found. image must be 2d or 3d, but got {}'.format(_cim.ndim))
if cfirst:
# note that cim's shape must be (c, h, w)
cim = cim.transpose((1, 2, 0))
return tim, cim
if isinstance(image, (list, tuple)):
img = []
for im in image:
if isinstance(im, np.ndarray):
tim = torch.tensor(im, requires_grad=False)
# im and tim's shape = (h, w, ?)
tim, cim = __check(tim, im, cfirst=False)
elif isinstance(im, torch.Tensor):
cim = im.cpu().numpy()
# im and tim's shape = (?, h, w)
tim, cim = __check(im, cim, cfirst=True)
else:
raise ValueError('Invalid image type. list or tuple\'s element must be ndarray, but got \'{}\''.format(type(im).__name__))
img += [tim]
orig_imgs += [cim]
# (b, c, h, w)
img = torch.stack(img)
elif isinstance(image, np.ndarray):
if image.ndim == 2:
tim, cim = __check(torch.tensor(image, requires_grad=False), image, cfirst=False)
img = tim.unsqueeze(0)
orig_imgs += [cim]
elif image.ndim == 3:
tim, cim = __check(torch.tensor(image, requires_grad=False), image, cfirst=False)
img = tim.unsqueeze(0)
orig_imgs += [cim]
elif image.ndim == 4:
img = []
for i in range(image.shape[0]):
tim, cim = __check(torch.tensor(image[i], requires_grad=False), image[i], cfirst=False)
img += [tim]
orig_imgs += [cim]
img = torch.stack(img)
else:
raise ValueError('Invalid image found. image must be from 2d to 4d, but got {}'.format(image.ndim))
elif isinstance(image, torch.Tensor):
if image.ndim == 2:
tim, cim = __check(image, image.cpu().numpy(), cfirst=True)
img = tim.unsqueeze(0)
orig_imgs += [cim]
elif image.ndim == 3:
tim, cim = __check(image, image.cpu().numpy(), cfirst=True)
img = tim.unsqueeze(0)
orig_imgs += [cim]
elif image.ndim == 4:
img = []
for i in range(image.shape[0]):
tim, cim = __check(image[i], image[i].cpu().numpy(), cfirst=True)
img += [tim]
orig_imgs += [cim]
img = torch.stack(img)
else:
raise ValueError('Invalid image found. image must be from 2d to 4d, but got {}'.format(image.ndim))
else:
raise ValueError('Invalid image type. list or tuple\'s element must be'
'\'list\', \'tuple\', \'ndarray\' or \'Tensor\', but got \'{}\''.format(type(image).__name__))
assert img.ndim == 4, "may forget checking..."
return img.to(device), orig_imgs
def _check_shape(desired_shape, input_shape):
"""
Note that desired_shape is allowed to have None, which means whatever input size is ok
:param desired_shape: array-like
:param input_shape: array-like
:return:
"""
if len(desired_shape) != len(input_shape):
raise ValueError("shape dim was not same, got {} and {}".format(len(desired_shape), len(input_shape)))
for i, (des_d, inp_d) in enumerate(zip(desired_shape, input_shape)):
if des_d is None:
continue
if des_d != inp_d:
raise ValueError('dim:{} is invalid size, desired one: {}, but got {}'.format(i, des_d, inp_d))
def _get_normed_and_origin_img(img, orig_imgs, rgb_means, rgb_stds, toNorm, device):
"""
:param img: Tensor, shape = (b, c, h, w)
:param orig_imgs: list of ndarray, shape = (h, w, c)
:param rgb_means: tuple or float
:param rgb_stds: tuple or float
:param toNorm: Bool
:param device: torch.device
:return:
normed_img: Tensor, shape = (b, c, h, w)
orig_img: Tensor, shape = (b, c, h, w). Order is rgb
"""
rgb_means = _check_norm('rgb_means', rgb_means)
rgb_stds = _check_norm('rgb_stds', rgb_stds)
img = img.to(device)
if toNorm:
# shape = (1, 3, 1, 1)
rgb_means = rgb_means.unsqueeze(0).unsqueeze(-1).unsqueeze(-1).to(device)
rgb_stds = rgb_stds.unsqueeze(0).unsqueeze(-1).unsqueeze(-1).to(device)
normed_img = (img / 255. - rgb_means) / rgb_stds
orig_imgs = orig_imgs
else:
normed_img = img
# shape = (1, 1, 3)
rgb_means = rgb_means.unsqueeze(0).unsqueeze(0).cpu().numpy()
rgb_stds = rgb_stds.unsqueeze(0).unsqueeze(0).cpu().numpy()
orig_imgs = [oim * rgb_stds + rgb_means for oim in orig_imgs]
return normed_img, orig_imgs
|
[
"torch.stack",
"torch.nn.init.xavier_uniform_",
"os.path.dirname",
"numpy.expand_dims",
"torch.nn.init.constant_",
"torch.tensor",
"os.path.join",
"cv2.resize"
] |
[((130, 153), 'os.path.dirname', 'os.path.dirname', (['_file_'], {}), '(_file_)\n', (145, 153), False, 'import os, cv2\n'), ((215, 254), 'os.path.join', 'os.path.join', (['basepath', '*backs', 'dirname'], {}), '(basepath, *backs, dirname)\n', (227, 254), False, 'import os, cv2\n'), ((6262, 6278), 'torch.stack', 'torch.stack', (['img'], {}), '(img)\n', (6273, 6278), False, 'import torch\n'), ((1835, 1873), 'torch.nn.init.xavier_uniform_', 'nn.init.xavier_uniform_', (['module.weight'], {}), '(module.weight)\n', (1858, 1873), False, 'from torch import nn\n'), ((1930, 1963), 'torch.nn.init.constant_', 'nn.init.constant_', (['module.bias', '(0)'], {}), '(module.bias, 0)\n', (1947, 1963), False, 'from torch import nn\n'), ((2019, 2062), 'torch.nn.init.xavier_uniform_', 'nn.init.xavier_uniform_', (['module.conv.weight'], {}), '(module.conv.weight)\n', (2042, 2062), False, 'from torch import nn\n'), ((4441, 4473), 'cv2.resize', 'cv2.resize', (['_cim', '(wcond, hcond)'], {}), '(_cim, (wcond, hcond))\n', (4451, 4473), False, 'import os, cv2\n'), ((5672, 5709), 'torch.tensor', 'torch.tensor', (['im'], {'requires_grad': '(False)'}), '(im, requires_grad=False)\n', (5684, 5709), False, 'import torch\n'), ((1440, 1478), 'torch.tensor', 'torch.tensor', (['val'], {'requires_grad': '(False)'}), '(val, requires_grad=False)\n', (1452, 1478), False, 'import torch\n'), ((2124, 2162), 'torch.nn.init.constant_', 'nn.init.constant_', (['module.conv.bias', '(0)'], {}), '(module.conv.bias, 0)\n', (2141, 2162), False, 'from torch import nn\n'), ((4505, 4551), 'torch.tensor', 'torch.tensor', (['resized_cim'], {'requires_grad': '(False)'}), '(resized_cim, requires_grad=False)\n', (4517, 4551), False, 'import torch\n'), ((6379, 6419), 'torch.tensor', 'torch.tensor', (['image'], {'requires_grad': '(False)'}), '(image, requires_grad=False)\n', (6391, 6419), False, 'import torch\n'), ((5141, 5164), 'numpy.expand_dims', 'np.expand_dims', (['_cim', '(2)'], {}), '(_cim, 2)\n', (5155, 5164), True, 'import numpy as np\n'), ((6569, 6609), 'torch.tensor', 'torch.tensor', (['image'], {'requires_grad': '(False)'}), '(image, requires_grad=False)\n', (6581, 6609), False, 'import torch\n'), ((6979, 6995), 'torch.stack', 'torch.stack', (['img'], {}), '(img)\n', (6990, 6995), False, 'import torch\n'), ((7758, 7774), 'torch.stack', 'torch.stack', (['img'], {}), '(img)\n', (7769, 7774), False, 'import torch\n'), ((6828, 6871), 'torch.tensor', 'torch.tensor', (['image[i]'], {'requires_grad': '(False)'}), '(image[i], requires_grad=False)\n', (6840, 6871), False, 'import torch\n')]
|
"""
Parser for cechmate format of simplicial complex
"""
from itertools import chain, combinations
from cechmate import Cech, Rips, Alpha
import numpy as np
from scipy.sparse import coo_matrix
from dmt.morse_complex import MorseComplex
from dmt.perseus import save_points_perseus_brips, load_points_perseus_brips
def parse_cechmate(cechmate_complex):
""" Parses the Cechmate format for simplicial complexes
:param cechmate_complex: [(simplex_as_index_tuple, filtration)]
:return dict 'cell_dimensions': np.ndarray, 'filtration': np.ndarray,
'boundary_matrix': scipy.sparse.coo_matrix, 'cechmate_complex': cechmate complex for testing
:Example:
>>> cechmate_cplx = [([0], 0), ([1], 0), ([2], 0), ((0, 1, 2), 1.760962625882297), ((1, 2), 1.760962625882297), ((0, 2), 0.30122587679897417), ((0, 1), 0.2489387964292784)]
>>> MorseComplex(**parse_cechmate(cechmate_cplx)
"""
simplices, filtration = zip(*cechmate_complex)
simplices = list(map(tuple, simplices)) # All should be tuples, so they can be in a dict
size = len(simplices)
index_map = {splx: ix for splx, ix in zip(simplices, range(size))}
columns_rows = chain.from_iterable([[(index_map[splx], index_map[bdry])
for bdry in combinations(splx, len(splx) - 1) if bdry]
for splx in simplices])
columns, rows = zip(*columns_rows)
columns, rows = list(columns), list(rows)
data = [True] * len(columns)
boundary = coo_matrix((data, (rows, columns)), shape=(size, size), dtype=bool)
filtration = list(filtration)
cell_dimensions = np.array(list(map(len, simplices))) - 1
return dict(boundary_matrix=boundary,
cell_dimensions=cell_dimensions,
filtration=filtration,
cechmate_complex=cechmate_complex)
class VietorisRips(MorseComplex):
default_max_dim = 3
def __init__(self, points, max_dimension=default_max_dim):
points = np.array(points)
self.max_dimension = max_dimension
super().__init__(points=points, **parse_cechmate(Rips(maxdim=self.max_dimension).build(points)))
def save_brips(self, filepath):
save_points_perseus_brips(filepath, self.points)
@classmethod
def load_brips(cls, filepath, max_dimension=default_max_dim):
return cls(load_points_perseus_brips(filepath), max_dimension)
class CechComplex(MorseComplex):
default_max_dim = 3
def __init__(self, points, max_dimension=default_max_dim):
points = np.array(points, dtype=float)
self.max_dimension = max_dimension
super().__init__(points=points, **parse_cechmate(Cech(maxdim=self.max_dimension).build(points)))
class AlphaComplex(MorseComplex):
def __init__(self, points):
points = np.array(points, dtype=float)
super().__init__(points=points, **parse_cechmate(Alpha().build(points)))
|
[
"cechmate.Rips",
"cechmate.Cech",
"dmt.perseus.load_points_perseus_brips",
"scipy.sparse.coo_matrix",
"numpy.array",
"cechmate.Alpha",
"dmt.perseus.save_points_perseus_brips"
] |
[((1520, 1587), 'scipy.sparse.coo_matrix', 'coo_matrix', (['(data, (rows, columns))'], {'shape': '(size, size)', 'dtype': 'bool'}), '((data, (rows, columns)), shape=(size, size), dtype=bool)\n', (1530, 1587), False, 'from scipy.sparse import coo_matrix\n'), ((2007, 2023), 'numpy.array', 'np.array', (['points'], {}), '(points)\n', (2015, 2023), True, 'import numpy as np\n'), ((2217, 2265), 'dmt.perseus.save_points_perseus_brips', 'save_points_perseus_brips', (['filepath', 'self.points'], {}), '(filepath, self.points)\n', (2242, 2265), False, 'from dmt.perseus import save_points_perseus_brips, load_points_perseus_brips\n'), ((2562, 2591), 'numpy.array', 'np.array', (['points'], {'dtype': 'float'}), '(points, dtype=float)\n', (2570, 2591), True, 'import numpy as np\n'), ((2826, 2855), 'numpy.array', 'np.array', (['points'], {'dtype': 'float'}), '(points, dtype=float)\n', (2834, 2855), True, 'import numpy as np\n'), ((2369, 2404), 'dmt.perseus.load_points_perseus_brips', 'load_points_perseus_brips', (['filepath'], {}), '(filepath)\n', (2394, 2404), False, 'from dmt.perseus import save_points_perseus_brips, load_points_perseus_brips\n'), ((2124, 2155), 'cechmate.Rips', 'Rips', ([], {'maxdim': 'self.max_dimension'}), '(maxdim=self.max_dimension)\n', (2128, 2155), False, 'from cechmate import Cech, Rips, Alpha\n'), ((2692, 2723), 'cechmate.Cech', 'Cech', ([], {'maxdim': 'self.max_dimension'}), '(maxdim=self.max_dimension)\n', (2696, 2723), False, 'from cechmate import Cech, Rips, Alpha\n'), ((2913, 2920), 'cechmate.Alpha', 'Alpha', ([], {}), '()\n', (2918, 2920), False, 'from cechmate import Cech, Rips, Alpha\n')]
|
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 12 11:39:56 2019
@author: autol
"""
#%%
import numpy as np
import time
from gfun import StepClass,ConvClass,JClass,Hessian
from gupdate import UpdateClass
#%% methodtion
#@accepts(w=np.ndarray)
def gradient_descent_f(var,
X=0,y=0,w=0,n_iters=1,n_b=10,
sgd=0,method='mm10',isStep=0,
trace=1,doplot=1,ŋ=0,ŋ_a=1,skipConv=1,
**kwargs):
records = []
# Shuffle X,y
# r_index = np.random.RandomState(seed=43).permutation(len(y))
# X1 = X[r_index,:]
# w = var.w
# y1 = y[r_index]
time1 = time.time()
He = Hessian(var)
var.set(dict(A=He.A_(),H=He.H_()))
Jc = JClass(var,method)
var.set(dict(gJ=Jc.gJ,J=Jc.Loss,e0=Jc.Loss(w)))
var.set(dict(θ=w.copy(),
m=np.zeros(len(w)),v=np.zeros(len(w)),
t=1,))
Uc = UpdateClass(var)
Cc = ConvClass(var)
Sc = StepClass(var)
if isStep : #and not method in ['mm52','mm26']
ŋ = Sc.armijo_i(w,ŋ_a)
e1 = var.J(w)
ratio = 0
n_w,n_y=len(w),len(y)
records.append([-1,w.copy(),e1,ratio])
for i in range(n_iters):
if sgd == 0:
#if isStep : #and not method in ['mm52','mm26']
# ŋ = Sc.armijo_i(w,ŋ_a)
w = Uc.update_w(w,ŋ=ŋ,i=i)
# w += -ŋ*2./len(y)*X.T.dot(X.dot(w)-y)
e1 = var.J(w)
# e1 = np.mean((X.dot(w)-y)**2)
isConv,ratio = Cc.Conv(w,e1,ŋ,skipConv)
elif sgd == 1:
bb = range(0,n_y,n_b)
ws = np.zeros(n_w)
e1s = 0
for k in bb:
X_b = X[k:k + n_b]
y_b = y[k:k + n_b]
# print('each batch:',len(y_b))
if len(y_b) ==0:break # 没数据就退出
w = Uc.update_w(w,ŋ=ŋ,i=i,X=X_b,y=y_b)
e1s += var.J(w)
ws += w
e1 = e1s/len(bb)
w = ws/len(bb)
isConv,ratio = Cc.Conv(w,e1,ŋ,skipConv)
else:
print('None...');return None
records.append([i,w.copy(),e1,ratio])
ret = dict(ik=i,w=w,e1=e1,ratio=ratio)
# print(ret)
if isConv>0:break
# if trace:pass
print('last: \n',ret)
if not doplot: print('There\'s no method:',method)
time2 = time.time()
print('All Running time: %s Seconds'%(time2-time1))
rets = dict(wh=np.stack(records),finals=ret,method=method)
return rets
#%%
|
[
"numpy.stack",
"gfun.JClass",
"gupdate.UpdateClass",
"gfun.ConvClass",
"numpy.zeros",
"time.time",
"gfun.Hessian",
"gfun.StepClass"
] |
[((651, 662), 'time.time', 'time.time', ([], {}), '()\n', (660, 662), False, 'import time\n'), ((673, 685), 'gfun.Hessian', 'Hessian', (['var'], {}), '(var)\n', (680, 685), False, 'from gfun import StepClass, ConvClass, JClass, Hessian\n'), ((735, 754), 'gfun.JClass', 'JClass', (['var', 'method'], {}), '(var, method)\n', (741, 754), False, 'from gfun import StepClass, ConvClass, JClass, Hessian\n'), ((924, 940), 'gupdate.UpdateClass', 'UpdateClass', (['var'], {}), '(var)\n', (935, 940), False, 'from gupdate import UpdateClass\n'), ((950, 964), 'gfun.ConvClass', 'ConvClass', (['var'], {}), '(var)\n', (959, 964), False, 'from gfun import StepClass, ConvClass, JClass, Hessian\n'), ((974, 988), 'gfun.StepClass', 'StepClass', (['var'], {}), '(var)\n', (983, 988), False, 'from gfun import StepClass, ConvClass, JClass, Hessian\n'), ((2361, 2372), 'time.time', 'time.time', ([], {}), '()\n', (2370, 2372), False, 'import time\n'), ((2448, 2465), 'numpy.stack', 'np.stack', (['records'], {}), '(records)\n', (2456, 2465), True, 'import numpy as np\n'), ((1608, 1621), 'numpy.zeros', 'np.zeros', (['n_w'], {}), '(n_w)\n', (1616, 1621), True, 'import numpy as np\n')]
|
'''
File: main.py
Project: sketchKeras
File Created: Sunday, 7th October 2018 5:51:22 pm
Author: xiaofeng (<EMAIL>)
-----
Last Modified: Sunday, 7th October 2018 7:09:45 pm
Modified By: xiaofeng (<EMAIL>>)
-----
Copyright 2018.06 - 2018 onion Math, onion Math
'''
from keras.models import load_model
import keras.backend.tensorflow_backend as K
import tensorflow as tf
from keras.utils import plot_model
import datetime
import cv2
import os
import numpy as np
import pickle
from helper_sketch import *
class Sketch:
def __init__(self, gpu=0):
print("start")
self.root = "./images/"
self.batchsize = 1
self.outdir = self.root + "sketch/"
self.gpu = gpu
self._dtype = np.float32
if not os.path.isfile("./sketchKeras/mod.h5"):
print("/sketchKeras/mod.h5 not found. Please download them from github")
print("load model")
if self.gpu >= 0:
self.gpu_option = tf.GPUOptions(per_process_gpu_memory_fraction=0.9)
self.model_config = tf.ConfigProto(device_count={"CPU": 7},
gpu_options=self.gpu_option,
intra_op_parallelism_threads=0,
inter_op_parallelism_threads=0)
else:
self.model_config = tf.ConfigProto(device_count={"CPU": 2, "GPU": 0},
intra_op_parallelism_threads=0,
inter_op_parallelism_threads=0)
self.model = load_model('./sketchKeras/mod.h5')
if not os.path.exists(self.outdir):
os.makedirs(self.outdir)
def tosketch(self, id_str):
path = os.path.join(self.root, 'line', id_str + '.png')
saved_path = os.path.join(self.outdir, id_str+'.jpg')
from_mat = cv2.imread(path)
width = float(from_mat.shape[1])
height = float(from_mat.shape[0])
new_width = 0
new_height = 0
if (width > height):
from_mat = cv2.resize(
from_mat, (512, int(512 / width * height)),
interpolation=cv2.INTER_AREA)
new_width = 512
new_height = int(512 / width * height)
else:
from_mat = cv2.resize(from_mat, (int(512 / height * width), 512),
interpolation=cv2.INTER_AREA)
new_width = int(512 / height * width)
new_height = 512
from_mat = from_mat.transpose((2, 0, 1))
light_map = np.zeros(from_mat.shape, dtype=np.float)
for channel in range(3):
light_map[channel] = get_light_map_single(from_mat[channel])
light_map = normalize_pic(light_map)
light_map = resize_img_512_3d(light_map)
line_mat = self.model.predict(light_map, batch_size=self.batchsize)
line_mat = line_mat.transpose((3, 1, 2, 0))[0]
line_mat = line_mat[0:int(new_height), 0:int(new_width), :]
# show_active_img_and_save('sketchKeras_colored', line_mat, saved_path)
line_mat = np.amax(line_mat, 2)
# show_active_img_and_save_denoise_filter2('sketchKeras_enhanced', line_mat, saved_path)
show_active_img_and_save_denoise_filter('sketchKeras_pured', line_mat, saved_path)
# show_active_img_and_save_denoise('sketchKeras', line_mat, saved_path)
# cv2.waitKey(0)
if __name__ == '__main__':
for n in range(1):
s = Sketch()
s.tosketch(n * s.batchsize)
|
[
"keras.models.load_model",
"os.makedirs",
"numpy.zeros",
"os.path.exists",
"numpy.amax",
"cv2.imread",
"os.path.isfile",
"tensorflow.ConfigProto",
"tensorflow.GPUOptions",
"os.path.join"
] |
[((1593, 1627), 'keras.models.load_model', 'load_model', (['"""./sketchKeras/mod.h5"""'], {}), "('./sketchKeras/mod.h5')\n", (1603, 1627), False, 'from keras.models import load_model\n'), ((1757, 1805), 'os.path.join', 'os.path.join', (['self.root', '"""line"""', "(id_str + '.png')"], {}), "(self.root, 'line', id_str + '.png')\n", (1769, 1805), False, 'import os\n'), ((1827, 1869), 'os.path.join', 'os.path.join', (['self.outdir', "(id_str + '.jpg')"], {}), "(self.outdir, id_str + '.jpg')\n", (1839, 1869), False, 'import os\n'), ((1887, 1903), 'cv2.imread', 'cv2.imread', (['path'], {}), '(path)\n', (1897, 1903), False, 'import cv2\n'), ((2585, 2625), 'numpy.zeros', 'np.zeros', (['from_mat.shape'], {'dtype': 'np.float'}), '(from_mat.shape, dtype=np.float)\n', (2593, 2625), True, 'import numpy as np\n'), ((3124, 3144), 'numpy.amax', 'np.amax', (['line_mat', '(2)'], {}), '(line_mat, 2)\n', (3131, 3144), True, 'import numpy as np\n'), ((749, 787), 'os.path.isfile', 'os.path.isfile', (['"""./sketchKeras/mod.h5"""'], {}), "('./sketchKeras/mod.h5')\n", (763, 787), False, 'import os\n'), ((959, 1009), 'tensorflow.GPUOptions', 'tf.GPUOptions', ([], {'per_process_gpu_memory_fraction': '(0.9)'}), '(per_process_gpu_memory_fraction=0.9)\n', (972, 1009), True, 'import tensorflow as tf\n'), ((1042, 1178), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'device_count': "{'CPU': 7}", 'gpu_options': 'self.gpu_option', 'intra_op_parallelism_threads': '(0)', 'inter_op_parallelism_threads': '(0)'}), "(device_count={'CPU': 7}, gpu_options=self.gpu_option,\n intra_op_parallelism_threads=0, inter_op_parallelism_threads=0)\n", (1056, 1178), True, 'import tensorflow as tf\n'), ((1363, 1480), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'device_count': "{'CPU': 2, 'GPU': 0}", 'intra_op_parallelism_threads': '(0)', 'inter_op_parallelism_threads': '(0)'}), "(device_count={'CPU': 2, 'GPU': 0},\n intra_op_parallelism_threads=0, inter_op_parallelism_threads=0)\n", (1377, 1480), True, 'import tensorflow as tf\n'), ((1643, 1670), 'os.path.exists', 'os.path.exists', (['self.outdir'], {}), '(self.outdir)\n', (1657, 1670), False, 'import os\n'), ((1684, 1708), 'os.makedirs', 'os.makedirs', (['self.outdir'], {}), '(self.outdir)\n', (1695, 1708), False, 'import os\n')]
|
import pandas as pd
import numpy as np
from collections import namedtuple
from xbbg import const
from xbbg.io import logs, param
Session = namedtuple('Session', ['start_time', 'end_time'])
SessNA = Session(None, None)
def get_interval(ticker, session) -> Session:
"""
Get interval from defined session
Args:
ticker: ticker
session: session
Returns:
Session of start_time and end_time
Examples:
>>> get_interval('005490 KS Equity', 'day_open_30')
Session(start_time='09:00', end_time='09:30')
>>> get_interval('005490 KS Equity', 'day_normal_30_20')
Session(start_time='09:31', end_time='15:00')
>>> get_interval('005490 KS Equity', 'day_close_20')
Session(start_time='15:01', end_time='15:20')
>>> get_interval('700 HK Equity', 'am_open_30')
Session(start_time='09:30', end_time='10:00')
>>> get_interval('700 HK Equity', 'am_normal_30_30')
Session(start_time='10:01', end_time='11:30')
>>> get_interval('700 HK Equity', 'am_close_30')
Session(start_time='11:31', end_time='12:00')
>>> get_interval('ES1 Index', 'day_exact_2130_2230')
Session(start_time=None, end_time=None)
>>> get_interval('ES1 Index', 'allday_exact_2130_2230')
Session(start_time='21:30', end_time='22:30')
>>> get_interval('ES1 Index', 'allday_exact_2130_0230')
Session(start_time='21:30', end_time='02:30')
>>> get_interval('AMLP US', 'day_open_30')
Session(start_time=None, end_time=None)
>>> get_interval('7974 JP Equity', 'day_normal_180_300') is SessNA
True
>>> get_interval('Z 1 Index', 'allday_normal_30_30')
Session(start_time='01:31', end_time='20:30')
>>> get_interval('GBP Curncy', 'day')
Session(start_time='17:02', end_time='17:00')
"""
if '_' not in session:
session = f'{session}_normal_0_0'
interval = Intervals(ticker=ticker)
ss_info = session.split('_')
return getattr(interval, f'market_{ss_info.pop(1)}')(*ss_info)
def shift_time(start_time, mins) -> str:
"""
Shift start time by mins
Args:
start_time: start time in terms of HH:MM string
mins: number of minutes (+ / -)
Returns:
end time in terms of HH:MM string
"""
s_time = pd.Timestamp(start_time)
e_time = s_time + np.sign(mins) * pd.Timedelta(f'00:{abs(mins)}:00')
return e_time.strftime('%H:%M')
class Intervals(object):
def __init__(self, ticker):
"""
Args:
ticker: ticker
"""
self.ticker = ticker
self.exch = const.exch_info(ticker=ticker)
def market_open(self, session, mins) -> Session:
"""
Time intervals for market open
Args:
session: [allday, day, am, pm, night]
mins: mintues after open
Returns:
Session of start_time and end_time
"""
if session not in self.exch: return SessNA
start_time = self.exch[session][0]
return Session(start_time, shift_time(start_time, int(mins)))
def market_close(self, session, mins) -> Session:
"""
Time intervals for market close
Args:
session: [allday, day, am, pm, night]
mins: mintues before close
Returns:
Session of start_time and end_time
"""
if session not in self.exch: return SessNA
end_time = self.exch[session][-1]
return Session(shift_time(end_time, -int(mins) + 1), end_time)
def market_normal(self, session, after_open, before_close) -> Session:
"""
Time intervals between market
Args:
session: [allday, day, am, pm, night]
after_open: mins after open
before_close: mins before close
Returns:
Session of start_time and end_time
"""
logger = logs.get_logger(self.market_normal)
if session not in self.exch: return SessNA
ss = self.exch[session]
s_time = shift_time(ss[0], int(after_open) + 1)
e_time = shift_time(ss[-1], -int(before_close))
request_cross = pd.Timestamp(s_time) >= pd.Timestamp(e_time)
session_cross = pd.Timestamp(ss[0]) >= pd.Timestamp(ss[1])
if request_cross and (not session_cross):
logger.warning(f'end time {e_time} is earlier than {s_time} ...')
return SessNA
return Session(s_time, e_time)
def market_exact(self, session, start_time: str, end_time: str) -> Session:
"""
Explicitly specify start time and end time
Args:
session: predefined session
start_time: start time in terms of HHMM string
end_time: end time in terms of HHMM string
Returns:
Session of start_time and end_time
"""
if session not in self.exch: return SessNA
ss = self.exch[session]
same_day = ss[0] < ss[-1]
if not start_time: s_time = ss[0]
else:
s_time = param.to_hour(start_time)
if same_day: s_time = max(s_time, ss[0])
if not end_time: e_time = ss[-1]
else:
e_time = param.to_hour(end_time)
if same_day: e_time = min(e_time, ss[-1])
if same_day and (s_time > e_time): return SessNA
return Session(start_time=s_time, end_time=e_time)
|
[
"xbbg.io.logs.get_logger",
"pandas.Timestamp",
"xbbg.io.param.to_hour",
"collections.namedtuple",
"numpy.sign",
"xbbg.const.exch_info"
] |
[((142, 191), 'collections.namedtuple', 'namedtuple', (['"""Session"""', "['start_time', 'end_time']"], {}), "('Session', ['start_time', 'end_time'])\n", (152, 191), False, 'from collections import namedtuple\n'), ((2358, 2382), 'pandas.Timestamp', 'pd.Timestamp', (['start_time'], {}), '(start_time)\n', (2370, 2382), True, 'import pandas as pd\n'), ((2666, 2696), 'xbbg.const.exch_info', 'const.exch_info', ([], {'ticker': 'ticker'}), '(ticker=ticker)\n', (2681, 2696), False, 'from xbbg import const\n'), ((3966, 4001), 'xbbg.io.logs.get_logger', 'logs.get_logger', (['self.market_normal'], {}), '(self.market_normal)\n', (3981, 4001), False, 'from xbbg.io import logs, param\n'), ((2405, 2418), 'numpy.sign', 'np.sign', (['mins'], {}), '(mins)\n', (2412, 2418), True, 'import numpy as np\n'), ((4224, 4244), 'pandas.Timestamp', 'pd.Timestamp', (['s_time'], {}), '(s_time)\n', (4236, 4244), True, 'import pandas as pd\n'), ((4248, 4268), 'pandas.Timestamp', 'pd.Timestamp', (['e_time'], {}), '(e_time)\n', (4260, 4268), True, 'import pandas as pd\n'), ((4293, 4312), 'pandas.Timestamp', 'pd.Timestamp', (['ss[0]'], {}), '(ss[0])\n', (4305, 4312), True, 'import pandas as pd\n'), ((4316, 4335), 'pandas.Timestamp', 'pd.Timestamp', (['ss[1]'], {}), '(ss[1])\n', (4328, 4335), True, 'import pandas as pd\n'), ((5116, 5141), 'xbbg.io.param.to_hour', 'param.to_hour', (['start_time'], {}), '(start_time)\n', (5129, 5141), False, 'from xbbg.io import logs, param\n'), ((5272, 5295), 'xbbg.io.param.to_hour', 'param.to_hour', (['end_time'], {}), '(end_time)\n', (5285, 5295), False, 'from xbbg.io import logs, param\n')]
|
# Copyright (c) 2020 wngfra
# Use of this source code is governed by the Apache-2.0 license, see LICENSE
import socket
from collections import deque
import numpy as np
import rclpy
from rclpy.node import Node
from tactile_interfaces.msg import TactileSignal
from tactile_interfaces.srv import ChangeState
STATE_LIST = {0: "calibration", 1: "recording",
50: "standby", 99: "termination"}
class TactileSignalPublisher(Node):
"""
A node class for tactile signal publisher.
The node receives tactile signals in bytes via UDP and converts the data to array and publish to ROS2 network.
Runtime node state switch is implemented.
"""
def __init__(self):
super().__init__("tactile_publisher")
# Parameters are set via ROS2 parameter server.
self.declare_parameters(
namespace="",
parameters=[
("ip", "0.0.0.0"), # for container host net
("port", 10240),
("buffer_size", 96),
],
)
ip = str(self.get_parameter("ip").value)
port = int(self.get_parameter("port").value)
buffer_size = int(self.get_parameter("buffer_size").value)
# Open UDP socket and bind the port
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.bind((ip, port))
self.node_state = 0
# Data buffer for calibration
self.buffer = deque(maxlen=buffer_size)
self.reference_value = np.zeros(16)
# Create the publisher and service host
self.publisher = self.create_publisher(
TactileSignal, "tactile_signals", 10)
self.service = self.create_service(
ChangeState,
"tactile_publisher/change_state",
self.change_node_state_callback,
)
# Publisher rate 0.03s
self.timer = self.create_timer(0.03, self.timer_callback)
# self.get_logger().info("Node started in state: calibration")
def timer_callback(self):
data, addr = self.sock.recvfrom(256)
values = np.array(
[int.from_bytes(data[i: i + 2], "big")
for i in range(0, len(data), 2)],
dtype=np.int32,
)
try:
if self.node_state == 0: # calibration state
self.buffer.append(values)
# Once the buffer is full, compute the average values as reference
if len(self.buffer) == self.buffer.maxlen:
self.reference_value = np.mean(
self.buffer, axis=0, dtype=np.int32)
self.node_state = 1 # Change to recording state
self.get_logger().info("Calibration finished!")
elif self.node_state == 1: # recording state
if len(self.buffer) < self.buffer.maxlen:
self.get_logger().warn("Calibration unfinished!")
values -= self.reference_value
# Prepare TactileSignal message
msg = TactileSignal()
msg.addr = addr[0] + ":" + str(addr[1])
msg.header.frame_id = "world"
msg.header.stamp = self.get_clock().now().to_msg()
msg.data = values
msg.mean = np.mean(values)
self.publisher.publish(msg)
elif self.node_state == 50: # standby state
pass
elif self.node_state == 99: # termination state
self.get_logger().warn("Tactile publisher terminated.")
self.destroy_node()
except Exception as error:
self.get_logger().error(str(error))
def change_node_state_callback(self, request, response):
if request.transition != self.node_state and request.transition in STATE_LIST.keys():
self.node_state = request.transition
response.success = True
response.info = "OK"
self.get_logger().info(
"Changed to state: {}".format(
STATE_LIST[self.node_state])
)
if self.node_state == 0:
self.buffer.clear()
else:
raise Exception("Node state cannot be changed!")
return response
def main(args=None):
rclpy.init(args=args)
pub = TactileSignalPublisher()
rclpy.spin(pub)
rclpy.shutdown()
if __name__ == "__main__":
main()
|
[
"rclpy.spin",
"rclpy.init",
"socket.socket",
"numpy.zeros",
"rclpy.shutdown",
"numpy.mean",
"tactile_interfaces.msg.TactileSignal",
"collections.deque"
] |
[((4306, 4327), 'rclpy.init', 'rclpy.init', ([], {'args': 'args'}), '(args=args)\n', (4316, 4327), False, 'import rclpy\n'), ((4367, 4382), 'rclpy.spin', 'rclpy.spin', (['pub'], {}), '(pub)\n', (4377, 4382), False, 'import rclpy\n'), ((4387, 4403), 'rclpy.shutdown', 'rclpy.shutdown', ([], {}), '()\n', (4401, 4403), False, 'import rclpy\n'), ((1270, 1318), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_DGRAM'], {}), '(socket.AF_INET, socket.SOCK_DGRAM)\n', (1283, 1318), False, 'import socket\n'), ((1443, 1468), 'collections.deque', 'deque', ([], {'maxlen': 'buffer_size'}), '(maxlen=buffer_size)\n', (1448, 1468), False, 'from collections import deque\n'), ((1500, 1512), 'numpy.zeros', 'np.zeros', (['(16)'], {}), '(16)\n', (1508, 1512), True, 'import numpy as np\n'), ((2539, 2583), 'numpy.mean', 'np.mean', (['self.buffer'], {'axis': '(0)', 'dtype': 'np.int32'}), '(self.buffer, axis=0, dtype=np.int32)\n', (2546, 2583), True, 'import numpy as np\n'), ((3050, 3065), 'tactile_interfaces.msg.TactileSignal', 'TactileSignal', ([], {}), '()\n', (3063, 3065), False, 'from tactile_interfaces.msg import TactileSignal\n'), ((3296, 3311), 'numpy.mean', 'np.mean', (['values'], {}), '(values)\n', (3303, 3311), True, 'import numpy as np\n')]
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Copyright (c) 2019 <NAME>
This software is released under the MIT License.
See the LICENSE file in the project root for more information.
"""
import numpy as np
import os
import six.moves.urllib as urllib
import sys
import tarfile
import tensorflow as tf
import zipfile
import collections
import random
import time
import cv2
from distutils.version import StrictVersion
from collections import defaultdict
from io import StringIO
from PIL import Image
from collections import defaultdict
from datetime import datetime as dt
# This is needed since the notebook is stored in the object_detection folder.
from object_detection.utils import ops as utils_ops
if StrictVersion(tf.__version__) < StrictVersion('1.9.0'):
raise ImportError('Please upgrade your TensorFlow installation to v1.9.* or later!')
sys.path.append("/home/pi/models/research/object_detection")
from utils import label_map_util
from utils import visualization_utils as vis_util
MODEL_NAME = '/home/pi/models/research/object_detection/ssdlite_mobilenet_v2_coco_2018_05_09'
# Path to frozen detection graph. This is the actual model that is used for the object detection.
PATH_TO_FROZEN_GRAPH = os.path.join(MODEL_NAME, 'frozen_inference_graph.pb')
# List of the strings that is used to add correct label for each box.
PATH_TO_LABELS = os.path.join('/home/pi/models/research/object_detection/data', 'mscoco_label_map.pbtxt')
def load_image_into_numpy_array2(image):
return np.asarray(image).astype(np.uint8)
def main():
WINDOW_NAME = 'Tensorflow object detection'
freq = cv2.getTickFrequency()
cv2.namedWindow(WINDOW_NAME)
cv2.moveWindow(WINDOW_NAME, 100, 200)
image = np.zeros((480, 640, 3), np.uint8)
cv2.putText(image, 'Loadg ...', (80, 200), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 1, cv2.LINE_AA)
cv2.imshow(WINDOW_NAME, image)
for i in range(20):
cv2.waitKey(10)
# Load a (frozen) Tensorflow model into memory.
print('Load a (frozen) Tensorflow model into memory.')
detection_graph = tf.Graph()
with detection_graph.as_default():
od_graph_def = tf.GraphDef()
with tf.gfile.GFile(PATH_TO_FROZEN_GRAPH, 'rb') as fid:
serialized_graph = fid.read()
od_graph_def.ParseFromString(serialized_graph)
tf.import_graph_def(od_graph_def, name='')
# Loading label map
print('Loading label map.')
category_index = label_map_util.create_category_index_from_labelmap(PATH_TO_LABELS, use_display_name=True)
with detection_graph.as_default():
with tf.Session() as sess:
# Get handles to input and output tensors
print('Get handles to input and output tensors.')
ops = tf.get_default_graph().get_operations()
all_tensor_names = {output.name for op in ops for output in op.outputs}
tensor_dict = {}
for key in ['num_detections', 'detection_boxes', 'detection_scores', 'detection_classes', 'detection_masks']:
tensor_name = key + ':0'
if tensor_name in all_tensor_names:
tensor_dict[key] = tf.get_default_graph().get_tensor_by_name(tensor_name)
if 'detection_masks' in tensor_dict:
# The following processing is only for single image
detection_boxes = tf.squeeze(tensor_dict['detection_boxes'], [0])
detection_masks = tf.squeeze(tensor_dict['detection_masks'], [0])
# Reframe is required to translate mask from box coordinates to image coordinates and fit the image size.
real_num_detection = tf.cast(tensor_dict['num_detections'][0], tf.int32)
detection_boxes = tf.slice(detection_boxes, [0, 0], [real_num_detection, -1])
detection_masks = tf.slice(detection_masks, [0, 0, 0], [real_num_detection, -1, -1])
detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(
detection_masks, detection_boxes, image.shape[0], image.shape[1])
detection_masks_reframed = tf.cast(
tf.greater(detection_masks_reframed, 0.5), tf.uint8)
# Follow the convention by adding back the batch dimension
tensor_dict['detection_masks'] = tf.expand_dims(detection_masks_reframed, 0)
image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0')
# Start VideoCapture.
print('Start VideoCapture.')
cap = cv2.VideoCapture(0)
cap.set(3, 640)
cap.set(4, 480)
# Run inference
while (True):
# Capture frame-by-frame
ret, frame = cap.read()
# the array based representation of the image will be used later in order to prepare the
# result image with boxes and labels on it.
# image_np = load_image_into_numpy_array2(image)
# bgr -> rgb
image_np = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# Expand dimensions since the model expects images to have shape: [1, None, None, 3]
image_np_expanded = np.expand_dims(image_np, axis=0)
start_time = cv2.getTickCount()
# inference
print('sess.run in.')
output_dict = sess.run(tensor_dict, feed_dict={image_tensor: np.expand_dims(image_np, 0)})
print('sess.run out.')
end_time = cv2.getTickCount()
# all outputs are float32 numpy arrays, so convert types as appropriate
output_dict['num_detections'] = int(output_dict['num_detections'][0])
output_dict['detection_classes'] = output_dict['detection_classes'][0].astype(np.uint8)
output_dict['detection_boxes'] = output_dict['detection_boxes'][0]
output_dict['detection_scores'] = output_dict['detection_scores'][0]
if 'detection_masks' in output_dict:
output_dict['detection_masks'] = output_dict['detection_masks'][0]
# Visualization of the results of a detection.
vis_util.visualize_boxes_and_labels_on_image_array(
frame,
output_dict['detection_boxes'],
output_dict['detection_classes'],
output_dict['detection_scores'],
category_index,
instance_masks=output_dict.get('detection_masks'),
use_normalized_coordinates=True,
line_thickness=4)
# Draw FPS
frame_rate = 1 / ((end_time - start_time) / freq)
cv2.putText(frame, "FPS: {0:.2f}".format(frame_rate),
(30, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 0), 2, cv2.LINE_AA)
# Display the resulting frame
cv2.imshow(WINDOW_NAME, frame)
# if cv2.waitKey(10) & 0xFF == ord('q') or video_getter.stopped:
if cv2.waitKey(10) & 0xFF == ord('q'):
break
for i in range(10):
ret, frame = cap.read()
# When everything done, release the windows
cap.release()
cv2.destroyAllWindows()
if __name__ == '__main__':
main()
|
[
"distutils.version.StrictVersion",
"cv2.getTickCount",
"tensorflow.get_default_graph",
"cv2.imshow",
"os.path.join",
"tensorflow.greater",
"sys.path.append",
"cv2.getTickFrequency",
"cv2.cvtColor",
"tensorflow.cast",
"tensorflow.squeeze",
"tensorflow.GraphDef",
"cv2.destroyAllWindows",
"cv2.waitKey",
"numpy.asarray",
"tensorflow.Session",
"tensorflow.gfile.GFile",
"tensorflow.Graph",
"tensorflow.import_graph_def",
"tensorflow.expand_dims",
"cv2.putText",
"numpy.zeros",
"numpy.expand_dims",
"utils.label_map_util.create_category_index_from_labelmap",
"cv2.VideoCapture",
"object_detection.utils.ops.reframe_box_masks_to_image_masks",
"tensorflow.slice",
"cv2.moveWindow",
"cv2.namedWindow"
] |
[((873, 933), 'sys.path.append', 'sys.path.append', (['"""/home/pi/models/research/object_detection"""'], {}), "('/home/pi/models/research/object_detection')\n", (888, 933), False, 'import sys\n'), ((1234, 1287), 'os.path.join', 'os.path.join', (['MODEL_NAME', '"""frozen_inference_graph.pb"""'], {}), "(MODEL_NAME, 'frozen_inference_graph.pb')\n", (1246, 1287), False, 'import os\n'), ((1376, 1468), 'os.path.join', 'os.path.join', (['"""/home/pi/models/research/object_detection/data"""', '"""mscoco_label_map.pbtxt"""'], {}), "('/home/pi/models/research/object_detection/data',\n 'mscoco_label_map.pbtxt')\n", (1388, 1468), False, 'import os\n'), ((727, 756), 'distutils.version.StrictVersion', 'StrictVersion', (['tf.__version__'], {}), '(tf.__version__)\n', (740, 756), False, 'from distutils.version import StrictVersion\n'), ((759, 781), 'distutils.version.StrictVersion', 'StrictVersion', (['"""1.9.0"""'], {}), "('1.9.0')\n", (772, 781), False, 'from distutils.version import StrictVersion\n'), ((1625, 1647), 'cv2.getTickFrequency', 'cv2.getTickFrequency', ([], {}), '()\n', (1645, 1647), False, 'import cv2\n'), ((1653, 1681), 'cv2.namedWindow', 'cv2.namedWindow', (['WINDOW_NAME'], {}), '(WINDOW_NAME)\n', (1668, 1681), False, 'import cv2\n'), ((1686, 1723), 'cv2.moveWindow', 'cv2.moveWindow', (['WINDOW_NAME', '(100)', '(200)'], {}), '(WINDOW_NAME, 100, 200)\n', (1700, 1723), False, 'import cv2\n'), ((1737, 1770), 'numpy.zeros', 'np.zeros', (['(480, 640, 3)', 'np.uint8'], {}), '((480, 640, 3), np.uint8)\n', (1745, 1770), True, 'import numpy as np\n'), ((1775, 1879), 'cv2.putText', 'cv2.putText', (['image', '"""Loadg ..."""', '(80, 200)', 'cv2.FONT_HERSHEY_SIMPLEX', '(1)', '(0, 0, 255)', '(1)', 'cv2.LINE_AA'], {}), "(image, 'Loadg ...', (80, 200), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,\n 0, 255), 1, cv2.LINE_AA)\n", (1786, 1879), False, 'import cv2\n'), ((1880, 1910), 'cv2.imshow', 'cv2.imshow', (['WINDOW_NAME', 'image'], {}), '(WINDOW_NAME, image)\n', (1890, 1910), False, 'import cv2\n'), ((2093, 2103), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (2101, 2103), True, 'import tensorflow as tf\n'), ((2478, 2571), 'utils.label_map_util.create_category_index_from_labelmap', 'label_map_util.create_category_index_from_labelmap', (['PATH_TO_LABELS'], {'use_display_name': '(True)'}), '(PATH_TO_LABELS,\n use_display_name=True)\n', (2528, 2571), False, 'from utils import label_map_util\n'), ((7394, 7417), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (7415, 7417), False, 'import cv2\n'), ((1943, 1958), 'cv2.waitKey', 'cv2.waitKey', (['(10)'], {}), '(10)\n', (1954, 1958), False, 'import cv2\n'), ((2166, 2179), 'tensorflow.GraphDef', 'tf.GraphDef', ([], {}), '()\n', (2177, 2179), True, 'import tensorflow as tf\n'), ((1518, 1535), 'numpy.asarray', 'np.asarray', (['image'], {}), '(image)\n', (1528, 1535), True, 'import numpy as np\n'), ((2193, 2235), 'tensorflow.gfile.GFile', 'tf.gfile.GFile', (['PATH_TO_FROZEN_GRAPH', '"""rb"""'], {}), "(PATH_TO_FROZEN_GRAPH, 'rb')\n", (2207, 2235), True, 'import tensorflow as tf\n'), ((2357, 2399), 'tensorflow.import_graph_def', 'tf.import_graph_def', (['od_graph_def'], {'name': '""""""'}), "(od_graph_def, name='')\n", (2376, 2399), True, 'import tensorflow as tf\n'), ((2622, 2634), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (2632, 2634), True, 'import tensorflow as tf\n'), ((4575, 4594), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (4591, 4594), False, 'import cv2\n'), ((3391, 3438), 'tensorflow.squeeze', 'tf.squeeze', (["tensor_dict['detection_boxes']", '[0]'], {}), "(tensor_dict['detection_boxes'], [0])\n", (3401, 3438), True, 'import tensorflow as tf\n'), ((3473, 3520), 'tensorflow.squeeze', 'tf.squeeze', (["tensor_dict['detection_masks']", '[0]'], {}), "(tensor_dict['detection_masks'], [0])\n", (3483, 3520), True, 'import tensorflow as tf\n'), ((3680, 3731), 'tensorflow.cast', 'tf.cast', (["tensor_dict['num_detections'][0]", 'tf.int32'], {}), "(tensor_dict['num_detections'][0], tf.int32)\n", (3687, 3731), True, 'import tensorflow as tf\n'), ((3766, 3825), 'tensorflow.slice', 'tf.slice', (['detection_boxes', '[0, 0]', '[real_num_detection, -1]'], {}), '(detection_boxes, [0, 0], [real_num_detection, -1])\n', (3774, 3825), True, 'import tensorflow as tf\n'), ((3860, 3926), 'tensorflow.slice', 'tf.slice', (['detection_masks', '[0, 0, 0]', '[real_num_detection, -1, -1]'], {}), '(detection_masks, [0, 0, 0], [real_num_detection, -1, -1])\n', (3868, 3926), True, 'import tensorflow as tf\n'), ((3970, 4082), 'object_detection.utils.ops.reframe_box_masks_to_image_masks', 'utils_ops.reframe_box_masks_to_image_masks', (['detection_masks', 'detection_boxes', 'image.shape[0]', 'image.shape[1]'], {}), '(detection_masks, detection_boxes,\n image.shape[0], image.shape[1])\n', (4012, 4082), True, 'from object_detection.utils import ops as utils_ops\n'), ((4349, 4392), 'tensorflow.expand_dims', 'tf.expand_dims', (['detection_masks_reframed', '(0)'], {}), '(detection_masks_reframed, 0)\n', (4363, 4392), True, 'import tensorflow as tf\n'), ((5075, 5113), 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_BGR2RGB'], {}), '(frame, cv2.COLOR_BGR2RGB)\n', (5087, 5113), False, 'import cv2\n'), ((5252, 5284), 'numpy.expand_dims', 'np.expand_dims', (['image_np'], {'axis': '(0)'}), '(image_np, axis=0)\n', (5266, 5284), True, 'import numpy as np\n'), ((5315, 5333), 'cv2.getTickCount', 'cv2.getTickCount', ([], {}), '()\n', (5331, 5333), False, 'import cv2\n'), ((5575, 5593), 'cv2.getTickCount', 'cv2.getTickCount', ([], {}), '()\n', (5591, 5593), False, 'import cv2\n'), ((7050, 7080), 'cv2.imshow', 'cv2.imshow', (['WINDOW_NAME', 'frame'], {}), '(WINDOW_NAME, frame)\n', (7060, 7080), False, 'import cv2\n'), ((2778, 2800), 'tensorflow.get_default_graph', 'tf.get_default_graph', ([], {}), '()\n', (2798, 2800), True, 'import tensorflow as tf\n'), ((4172, 4213), 'tensorflow.greater', 'tf.greater', (['detection_masks_reframed', '(0.5)'], {}), '(detection_masks_reframed, 0.5)\n', (4182, 4213), True, 'import tensorflow as tf\n'), ((4421, 4443), 'tensorflow.get_default_graph', 'tf.get_default_graph', ([], {}), '()\n', (4441, 4443), True, 'import tensorflow as tf\n'), ((7180, 7195), 'cv2.waitKey', 'cv2.waitKey', (['(10)'], {}), '(10)\n', (7191, 7195), False, 'import cv2\n'), ((3185, 3207), 'tensorflow.get_default_graph', 'tf.get_default_graph', ([], {}), '()\n', (3205, 3207), True, 'import tensorflow as tf\n'), ((5478, 5505), 'numpy.expand_dims', 'np.expand_dims', (['image_np', '(0)'], {}), '(image_np, 0)\n', (5492, 5505), 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.