code
stringlengths 31
1.05M
| apis
list | extract_api
stringlengths 97
1.91M
|
---|---|---|
from scope2screen.server.models import data_model
import numpy as np
import scipy.misc as sp
import time
import tifffile as tf
import re
import zarr
import sys
from skimage import data, transform
from skimage.util import img_as_ubyte
from skimage.morphology import disk
from skimage.filters import rank
from skimage.io import imread
from skimage.color import rgb2gray
from skimage.transform import rescale, resize, downscale_local_mean
from skimage import measure
import cv2
from scope2screen import data_path
def prepSlidingWindow():
print('hi')
def histogramComparison(x, y, datasource_name, r, channels, viewport, zoomlevel, sensibility):
tic = time.perf_counter()
print("histogram comparison..")
print("load image sections")
viewport = np.array(viewport.split(",")).astype(float).astype(int);
#get image and lens section
png =[]
roi = []
for channel in channels:
png.append(loadPngSection(datasource_name, channel, min(zoomlevel+1, len(data_model.channels)-1), viewport))
roi.append(loadPngSection(datasource_name, channel, min(zoomlevel+1, len(data_model.channels)-1), np.array([x-r,y-r,x+r,y+r]).astype(int)))
tac = time.perf_counter()
print("cropped sections loaded after " + str(tac-tic))
#write those sections to file for debugging purposes
# cv2.imwrite('scope2screen/server/analytics/img/testcut.png', png)
# cv2.imwrite('scope2screen/server/analytics/img/roi.png', roi)
# calc image similarity map
print("calculate image similarity maps for each channel...")
i = 0
sim_map = []
combined_png = []
combined_roi = []
for channel in channels:
print("sim map for " + str(channel))
if (i == 0):
combined_png = png[i]
combined_roi = roi[i]
if (i > 0):
combined_png = np.add(combined_png, png[i])
combined_roi = np.add(combined_roi, roi[i])
i += 1
# cv2.imwrite('scope2screen/server/analytics/img/sim_map.jpg', sim_map)
# normalize by num channels considered
print("combining whole channels, combine lens parts. Norm by num channels")
if (len(channels) > 1):
combined_png = np.floor_divide(combined_png, len(channels))
combined_roi = np.floor_divide(combined_roi, len(channels))
print("compute similarity maps")
combined_sim_map = calc_sim(combined_png, combined_roi)
# find contours
print("compute contours")
contours = find_contours(combined_sim_map, sensibility)
# labels = find_labels(png, sim_map, sensibility)
#get global contour positions
length = len(data_model.channels[0].shape);
layerviewport = getLayerViewport( data_model.channels[0].shape[length-2],
data_model.channels[0].shape[length-1],
data_model.channels[min(zoomlevel+1, len(data_model.channels)-1)].shape[length-2],
data_model.channels[min(zoomlevel+1, len(data_model.channels)-1)].shape[length-1],
viewport)
contours = toWorldCoordinates(contours, viewport, layerviewport)
toc = time.perf_counter()
print("histogram computation time is" + str(toc-tic))
return {'contours': contours}
def histogramComparisonSimMap(x, y, datasource_name, r, channels, viewport, zoomlevel, sensibility):
tic = time.perf_counter()
print("histogram comparison..")
print("load image sections")
viewport = np.array(viewport.split(",")).astype(float).astype(int);
# get image and lens section
png = []
roi = []
for channel in channels:
png.append(loadPngSection(datasource_name, channel, zoomlevel+1, viewport))
roi.append(
loadPngSection(datasource_name, channel, min(zoomlevel+1, len(data_model.channels)-1), np.array([x - r, y - r, x + r, y + r]).astype(int)))
tac = time.perf_counter()
print("cropped sections loaded after " + str(tac - tic))
# write those sections to file for debugging purposes
# cv2.imwrite('scope2screen/server/analytics/img/testcut.png', png)
# cv2.imwrite('scope2screen/server/analytics/img/roi.png', roi)
# calc image similarity map
print("calculate image similarity maps for each channel...")
i = 0
sim_map = []
combined_png = []
combined_roi = []
for channel in channels:
print("sim map for " + str(channel))
if (i == 0):
combined_png = png[i]
combined_roi = roi[i]
if (i > 0):
combined_png = np.add(combined_png, png[i])
combined_roi = np.add(combined_roi, roi[i])
i += 1
# cv2.imwrite('scope2screen/server/analytics/img/sim_map.jpg', sim_map)
# normalize by num channels considered
print("combining whole channels, combine lens parts. Norm by num channels")
if (len(channels) > 1):
combined_png = np.floor_divide(combined_png, len(channels))
combined_roi = np.floor_divide(combined_roi, len(channels))
print("compute similarity maps")
combined_sim_map = calc_sim(combined_png, combined_roi)
combined_sim_map = combined_sim_map / combined_sim_map.max()
combined_sim_map[combined_sim_map < sensibility] = 0
# combined_sim_map = combined_sim_map * 255
# mask_sim_map = combined_sim_map > 500 * combined_sim_map * 255
# get global contour positions
length = len(data_model.channels[0].shape);
layerviewport = getLayerViewport(data_model.channels[0].shape[length - 2],
data_model.channels[0].shape[length - 1],
data_model.channels[min(zoomlevel+1, len(data_model.channels)-1)].shape[length - 2],
data_model.channels[min(zoomlevel+1, len(data_model.channels)-1)].shape[length - 1],
viewport)
cv2.imwrite('scope2screen/server/analytics/img/sim_map_strange.jpg', combined_sim_map)
mask = imageToWorldCoordinates(combined_sim_map, viewport, layerviewport)
# cv2.imwrite('scope2screen/server/analytics/img/sim_map_strange_after.jpg', mask)
toc = time.perf_counter()
print("histogram computation time is" + str(toc - tic))
return {'mask': mask, 'shift_x' : viewport[0], 'shift_y': viewport[1]}
def scale(im, nR, nC):
nR0 = len(im) # source number of rows
nC0 = len(im[0]) # source number of columns
return [[ im[int(nR0 * r / nR)][int(nC0 * c / nC)]
for c in range(nC)] for r in range(nR)]
# tic = time.perf_counter()
# print("histogram comparison..")
# print("load image sections")
#
# viewport = np.array(viewport.split(",")).astype(float).astype(int);
# #get image and lens section
#
# png =[]
# roi = []
# for channel in channels:
# png.append(loadPngSection(datasource_name, channel, zoomlevel, viewport))
# roi.append(loadPngSection(datasource_name, channel, zoomlevel, np.array([x-r,y-r,x+r,y+r]).astype(int)))
#
# #write those sections to file for debugging purposes
# # cv2.imwrite('scope2screen/server/analytics/img/testcut.png', png)
# # cv2.imwrite('scope2screen/server/analytics/img/roi.png', roi)
#
# # calc image similarity map
# print("calculate image similarity maps for each channel...")
# i = 0
# sim_map = []
# combined_sim_map = []
# for channel in channels:
# print("sim map for " + str(channel))
# sim_map.append(calc_sim(png[i], roi[i]))
# if (i == 0):
# combined_sim_map = sim_map[i]
# if (i > 0):
# combined_sim_map = np.add(combined_sim_map, sim_map[i])
# i += 1
# # cv2.imwrite('scope2screen/server/analytics/img/sim_map.jpg', sim_map)
#
# # normalize by num channels considered
# print("combining sim maps")
# combined_sim_map = np.true_divide(combined_sim_map, len(channels))
#
# # find contours
# print("compute contours")
# contours = find_contours(combined_sim_map, sensibility)
# # labels = find_labels(png, sim_map, sensibility)
#
# #get global contour positions
# length = len(data_model.channels[0].shape);
# layerviewport = getLayerViewport( data_model.channels[0].shape[length-2],
# data_model.channels[0].shape[length-1],
# data_model.channels[zoomlevel].shape[length-2],
# data_model.channels[zoomlevel].shape[length-1],
# viewport)
# contours = toWorldCoordinates(contours, viewport, layerviewport)
# toc = time.perf_counter()
#
# print("histogram computation time is" + str(toc-tic))
# return {'contours': contours}
def imageToWorldCoordinates(image, originalviewport, viewport):
# calc ratio from local cut to image
# resize to viewport
heightRatio = (originalviewport[3] - originalviewport[1]) / (viewport[3] - viewport[1]);
widthRatio = (originalviewport[2] - originalviewport[0]) / (viewport[2] - viewport[0]);
image = scale(image, (viewport[3] - viewport[1]), (viewport[2] - viewport[0]))
return image;
def toWorldCoordinates(contours, originalviewport, viewport):
# calc ratio from local cut to image
heightRatio = (originalviewport[3] - originalviewport[1]) / (viewport[3] - viewport[1]);
widthRatio = (originalviewport[2] - originalviewport[0]) / (viewport[2] - viewport[0]);
# convert viewport by scaling to original ratio and adding offset
for contour in contours:
for point in contour:
point[1] = point[1] * widthRatio + originalviewport[0];
point[0] = point[0] * heightRatio + originalviewport[1];
return contours;
#convert from whole image viewport to layer viewport (also: zarr has y,x flipped)
def getLayerViewport(imageHeight, imageWidth, layerHeight, layerWidth, viewport):
#calc ratio
heightRatio = layerHeight/imageHeight
widthRatio = layerWidth/imageWidth
layerviewport = [0,0,0,0]
#convert viewport
layerviewport[0] = int(viewport[0] * widthRatio);
layerviewport[1] = int(viewport[1] * heightRatio);
layerviewport[2] = int(viewport[2] * widthRatio);
layerviewport[3] = int(viewport[3] * heightRatio);
return layerviewport
# load a channel as png using zarr in full width and height
def loadPngSection(datasource_name, channel, zoomlevel, viewport):
print("chosen zoom level:")
print(zoomlevel)
# convert viewport to image layer: image height, width, layer height width, viewport
length = len(data_model.channels[0].shape)
viewport = getLayerViewport( data_model.channels[0].shape[length-2],
data_model.channels[0].shape[length-1],
data_model.channels[min(zoomlevel, len(data_model.channels)-1)].shape[length-2],
data_model.channels[min(zoomlevel, len(data_model.channels)-1)].shape[length-1],
viewport)
# print(data_model.get_channel_names(datasource_name, shortnames=False))
channel = data_model.get_channel_names(datasource_name, shortnames=False).index(channel)
if isinstance(data_model.channels, zarr.Array):
tile = data_model.channels[channel, viewport[1]:viewport[3], viewport[0]:viewport[2]]
else:
tile = data_model.channels[min(zoomlevel, len(data_model.channels)-1)][channel, viewport[1]:viewport[3], viewport[0]:viewport[2]]
return tile
# load a channel as png using zarr in full width and height
def loadPngAtZoomLevel(datasource_name, channel, zoomlevel):
ix = 0
iy = 0
print(channel)
print(data_model.get_channel_names(datasource_name, shortnames=False))
channel = data_model.get_channel_names(datasource_name, shortnames=False).index(channel)
if isinstance(data_model.channels, zarr.Array):
tile = data_model.channels[channel, ix:data_model.config[datasource_name]["width"],
iy:data_model.config[datasource_name]["height"]]
else:
tile = data_model.channels[min(zoomlevel, len(data_model.channels)-1)][channel, ix:data_model.config[datasource_name]["width"],
iy:data_model.config[datasource_name]["height"]]
tile = np.ascontiguousarray(tile, dtype='uint32')
png = tile.view('uint8').reshape(tile.shape + (-1,))[..., [2, 1, 0]]
return png
def find_labels(img, sim_map, eta):
# Apply thresholding to the surface
threshold = 0.8
mask = sim_map > 1.7
# Make a labelled image based on the thresholding regions
blobs_labels = measure.label(mask, background=0)
props = measure.regionprops(blobs_labels, intensity_image=sim_map)
return blobs_labels
def find_contours(sim_map, eta):
sim_map = np.pad(sim_map, pad_width=5, mode='constant', constant_values=0)
sim_map = sim_map / sim_map.max()
contours = measure.find_contours(sim_map, eta, fully_connected='high')
# print(data_path)
# f = open('scope2screen/server/analytics/measures/centers.txt', 'w')
# f.write('x,y\n')
# for contour in contours:
# # calculate centers
# f.write('{},{}\n'.format(round(contour[:, 1].mean(), 3),
# round(contour[:, 1].mean(), 3)))
# f.close()
return contours
def plotting_thread(fig, axe):
while (True):
mat = np.random.randn(256, 256)
time.sleep(2) # ... or some busy computing
axe.clear()
axe.imshow(mat)
fig.canvas.draw_idle() # use draw_idle instead of draw
def windowed_histogram_similarity(image, selem, reference_hist, n_bins):
# Compute normalized windowed histogram feature vector for each pixel
px_histograms = rank.windowed_histogram(image, selem, n_bins=n_bins)
# Reshape coin histogram to (1,1,N) for broadcast when we want to use it in
# arithmetic operations with the windowed histograms from the image
reference_hist = reference_hist.reshape((1, 1) + reference_hist.shape)
# Compute Chi squared distance metric: sum((X-Y)^2 / (X+Y));
# a measure of distance between histograms
X = px_histograms
Y = reference_hist
num = (X - Y) ** 2
denom = X + Y
denom[denom == 0] = np.infty
frac = num / denom
chi_sqr = 0.5 * np.sum(frac, axis=2)
# Generate a similarity measure. It needs to be low when distance is high
# and high when distance is low; taking the reciprocal will do this.
# Chi squared will always be >= 0, add small value to prevent divide by 0.
similarity = 1 / (chi_sqr + 1.0e-4)
return similarity
def calc_sim(img, coin):
# cv2.imwrite('scope2screen/server/analytics/img/testcut.png', img)
# img = cv2.imread('scope2screen/server/analytics/img/testcut.png');
print('prepare image')
# img = np.stack((img,) * 3, axis=-1)
# if img.shape[-1] == 3:
# img = rgbTOgray(img)
# img = img.astype('uint8')
img = img_as_ubyte(img)
# cv2.imwrite('scope2screen/server/analytics/img/coin.png', coin)
# coin = cv2.imread('scope2screen/server/analytics/img/coin.png');
print('prepare coin')
# coin = np.stack((coin,) * 3, axis=-1)
# if coin.shape[-1]==3:
# coin= rgbTOgray(coin)
# coin = coin.astype('uint8')
coin= img_as_ubyte(coin)
#we detect 16 steps histograms, so we shrink the intensity span to 16
img = img // 16
coin = coin // 16
# Compute coin histogram and normalize
print('compute histogram and normalize')
coin_hist, _ = np.histogram(coin.flatten(), bins=16, range=(0, 16))
coin_hist = coin_hist.astype(float) / np.sum(coin_hist)
# Compute a disk shaped mask that will define the shape of our sliding window
# A disk with diameter equal to max(w,h) of the roi should be a big enough reference
selem = disk(max(coin.shape) // 2)
# Compute the similarity across the complete image
print('compute similarity across image')
similarity = windowed_histogram_similarity(img, selem, coin_hist, coin_hist.shape[0])
print("image shape is: " + str(img.shape[0]) + " " + str(img.shape[1]))
print('sim computation done')
return similarity
def rgbTOgray(img):
gray = img[..., 0] * 0.299 + img[..., 1] * 0.587 + img[..., 2] * 0.114
return gray
|
[
"numpy.pad",
"scope2screen.server.models.data_model.get_channel_names",
"numpy.sum",
"numpy.random.randn",
"skimage.util.img_as_ubyte",
"cv2.imwrite",
"skimage.filters.rank.windowed_histogram",
"time.perf_counter",
"time.sleep",
"skimage.measure.label",
"numpy.array",
"skimage.measure.find_contours",
"numpy.add",
"numpy.ascontiguousarray",
"skimage.measure.regionprops"
] |
[((662, 681), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (679, 681), False, 'import time\n'), ((1188, 1207), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (1205, 1207), False, 'import time\n'), ((3150, 3169), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (3167, 3169), False, 'import time\n'), ((3379, 3398), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (3396, 3398), False, 'import time\n'), ((3941, 3960), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (3958, 3960), False, 'import time\n'), ((6095, 6185), 'cv2.imwrite', 'cv2.imwrite', (['"""scope2screen/server/analytics/img/sim_map_strange.jpg"""', 'combined_sim_map'], {}), "('scope2screen/server/analytics/img/sim_map_strange.jpg',\n combined_sim_map)\n", (6106, 6185), False, 'import cv2\n'), ((6369, 6388), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (6386, 6388), False, 'import time\n'), ((12509, 12551), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['tile'], {'dtype': '"""uint32"""'}), "(tile, dtype='uint32')\n", (12529, 12551), True, 'import numpy as np\n'), ((12845, 12878), 'skimage.measure.label', 'measure.label', (['mask'], {'background': '(0)'}), '(mask, background=0)\n', (12858, 12878), False, 'from skimage import measure\n'), ((12891, 12949), 'skimage.measure.regionprops', 'measure.regionprops', (['blobs_labels'], {'intensity_image': 'sim_map'}), '(blobs_labels, intensity_image=sim_map)\n', (12910, 12949), False, 'from skimage import measure\n'), ((13023, 13087), 'numpy.pad', 'np.pad', (['sim_map'], {'pad_width': '(5)', 'mode': '"""constant"""', 'constant_values': '(0)'}), "(sim_map, pad_width=5, mode='constant', constant_values=0)\n", (13029, 13087), True, 'import numpy as np\n'), ((13141, 13200), 'skimage.measure.find_contours', 'measure.find_contours', (['sim_map', 'eta'], {'fully_connected': '"""high"""'}), "(sim_map, eta, fully_connected='high')\n", (13162, 13200), False, 'from skimage import measure\n'), ((13974, 14026), 'skimage.filters.rank.windowed_histogram', 'rank.windowed_histogram', (['image', 'selem'], {'n_bins': 'n_bins'}), '(image, selem, n_bins=n_bins)\n', (13997, 14026), False, 'from skimage.filters import rank\n'), ((15192, 15209), 'skimage.util.img_as_ubyte', 'img_as_ubyte', (['img'], {}), '(img)\n', (15204, 15209), False, 'from skimage.util import img_as_ubyte\n'), ((15526, 15544), 'skimage.util.img_as_ubyte', 'img_as_ubyte', (['coin'], {}), '(coin)\n', (15538, 15544), False, 'from skimage.util import img_as_ubyte\n'), ((11920, 11983), 'scope2screen.server.models.data_model.get_channel_names', 'data_model.get_channel_names', (['datasource_name'], {'shortnames': '(False)'}), '(datasource_name, shortnames=False)\n', (11948, 11983), False, 'from scope2screen.server.models import data_model\n'), ((13619, 13644), 'numpy.random.randn', 'np.random.randn', (['(256)', '(256)'], {}), '(256, 256)\n', (13634, 13644), True, 'import numpy as np\n'), ((13653, 13666), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (13663, 13666), False, 'import time\n'), ((14532, 14552), 'numpy.sum', 'np.sum', (['frac'], {'axis': '(2)'}), '(frac, axis=2)\n', (14538, 14552), True, 'import numpy as np\n'), ((15866, 15883), 'numpy.sum', 'np.sum', (['coin_hist'], {}), '(coin_hist)\n', (15872, 15883), True, 'import numpy as np\n'), ((1844, 1872), 'numpy.add', 'np.add', (['combined_png', 'png[i]'], {}), '(combined_png, png[i])\n', (1850, 1872), True, 'import numpy as np\n'), ((1900, 1928), 'numpy.add', 'np.add', (['combined_roi', 'roi[i]'], {}), '(combined_roi, roi[i])\n', (1906, 1928), True, 'import numpy as np\n'), ((4668, 4696), 'numpy.add', 'np.add', (['combined_png', 'png[i]'], {}), '(combined_png, png[i])\n', (4674, 4696), True, 'import numpy as np\n'), ((4728, 4756), 'numpy.add', 'np.add', (['combined_roi', 'roi[i]'], {}), '(combined_roi, roi[i])\n', (4734, 4756), True, 'import numpy as np\n'), ((11354, 11417), 'scope2screen.server.models.data_model.get_channel_names', 'data_model.get_channel_names', (['datasource_name'], {'shortnames': '(False)'}), '(datasource_name, shortnames=False)\n', (11382, 11417), False, 'from scope2screen.server.models import data_model\n'), ((11999, 12062), 'scope2screen.server.models.data_model.get_channel_names', 'data_model.get_channel_names', (['datasource_name'], {'shortnames': '(False)'}), '(datasource_name, shortnames=False)\n', (12027, 12062), False, 'from scope2screen.server.models import data_model\n'), ((1134, 1172), 'numpy.array', 'np.array', (['[x - r, y - r, x + r, y + r]'], {}), '([x - r, y - r, x + r, y + r])\n', (1142, 1172), True, 'import numpy as np\n'), ((3873, 3911), 'numpy.array', 'np.array', (['[x - r, y - r, x + r, y + r]'], {}), '([x - r, y - r, x + r, y + r])\n', (3881, 3911), True, 'import numpy as np\n')]
|
# ----------------------------------------------------------------------------
# Copyright (c) 2018--, empress development team.
#
# Distributed under the terms of the Modified BSD License.
#
# ----------------------------------------------------------------------------
import unittest
import numpy as np
import pandas as pd
from skbio import DistanceMatrix, TreeNode
from scipy.cluster.hierarchy import complete
from pandas.util.testing import assert_frame_equal
from empress.tree import Tree
from empress.tree import DEFAULT_COLOR
class TestDendrogram(unittest.TestCase):
def mock_random_tree(self):
np.random.seed(0)
x = np.random.rand(10)
dm = DistanceMatrix.from_iterable(x, lambda x, y: np.abs(x - y))
lm = complete(dm.condensed_form())
ids = np.arange(len(x)).astype(np.str)
tree = TreeNode.from_linkage_matrix(lm, ids)
# initialize tree with branch length and named internal nodes
for i, n in enumerate(tree.postorder(include_self=True)):
n.length = 1
if not n.is_tip():
n.name = "y%d" % i
return tree
def mock_tree_from_nwk(self):
return TreeNode.read(['(((a:1,e:2)f:1,b:2)g:1,(c:1,d:3)h:2)i:1;'])
def setUp(self):
self.tree2 = self.mock_tree_from_nwk()
self.tree1 = self.mock_random_tree()
def test_from_tree_random_tree(self):
t = Tree.from_tree(self.tree1)
self.assertEqual(t.__class__, Tree)
def test_coords_random_tree(self):
t = Tree.from_tree(self.tree1)
data = [['7', 'y2', DEFAULT_COLOR, True, True, DEFAULT_COLOR, True,
79.070722542332845, 129.00083943597397,
1, 1, 50.679561936771449, 55.039337408460526
],
['8', 'y2', DEFAULT_COLOR, True, True, DEFAULT_COLOR, True,
79.070722542332845, 129.00083943597397,
1, 1, 12.628310993232901, 85.85263286563449
],
['4', 'y6', DEFAULT_COLOR, True, True, DEFAULT_COLOR, True,
74.068217341096869, 368.43664502236788,
1, 1, 12.499999999999979, 418.29360437746811
],
['6', 'y6', DEFAULT_COLOR, True, True, DEFAULT_COLOR, True,
74.068217341096869, 368.43664502236788,
1, 1, 53.563668631852295, 444.9606625915394
],
['9', 'y7', DEFAULT_COLOR, True, True, DEFAULT_COLOR, True,
117.21642391143635, 301.99423347326797,
1, 1, 38.10150433604548, 306.1404707163706
],
['y6', 'y7', DEFAULT_COLOR, True, False, DEFAULT_COLOR, True,
117.21642391143635, 301.99423347326797,
1, 1, 74.068217341096869, 368.43664502236788
],
['0', 'y11', DEFAULT_COLOR, True, True, DEFAULT_COLOR, True,
408.3850804246091, 240.10442497874831, 1, 1,
474.82749197370902, 283.25263154908782
],
['3', 'y11', DEFAULT_COLOR, True, True, DEFAULT_COLOR, True,
408.3850804246091, 240.10442497874831,
1, 1, 487.5, 235.95818773564568
],
['2', 'y14', DEFAULT_COLOR, True, True, DEFAULT_COLOR, True,
375.00926942577706, 153.15746472040379,
1, 1, 436.57748676687396, 103.30050536530359
],
['5', 'y14', DEFAULT_COLOR, True, True, DEFAULT_COLOR, True,
375.00926942577706, 153.15746472040379,
1, 1, 395.51381813502167, 76.633447151232261
],
['y11', 'y15', DEFAULT_COLOR, True, False, DEFAULT_COLOR, True,
331.86106285543758, 219.59987626950374,
1, 1, 408.3850804246091, 240.10442497874831
],
['y14', 'y15', DEFAULT_COLOR, True, False, DEFAULT_COLOR, True,
331.86106285543758, 219.59987626950374,
1, 1, 375.00926942577706, 153.15746472040379
],
['1', 'y16', DEFAULT_COLOR, True, True, DEFAULT_COLOR, True,
257.89956082792412, 247.99103687506513, 1, 1,
286.29072143348549, 321.95253890257857
],
['y15', 'y16', DEFAULT_COLOR, True, False, DEFAULT_COLOR, True,
257.89956082792412, 247.99103687506513,
1, 1, 331.86106285543758, 219.59987626950374
],
['y7', 'y17', DEFAULT_COLOR, True, False, DEFAULT_COLOR, True,
178.78464125253325, 252.13727411816777,
1, 1, 117.21642391143635, 301.99423347326797
],
['y16', 'y17', DEFAULT_COLOR, True, False, DEFAULT_COLOR, True,
178.78464125253325, 252.13727411816777,
1, 1, 257.89956082792412, 247.99103687506513
],
['y2', 'y18', DEFAULT_COLOR, True, False, DEFAULT_COLOR, True,
128.92768189743305, 190.56905677707087,
1, 1, 79.070722542332845, 129.00083943597397
],
['y17', 'y18', DEFAULT_COLOR, True, False, DEFAULT_COLOR, True,
128.92768189743305, 190.56905677707087,
1, 1, 178.78464125253325, 252.13727411816777
]]
edge_exp = pd.DataFrame(data, columns=[your,list,of,columns])
edge_exp.set_index('Node_id', inplace=True)
edge_exp = edge_exp[['Node_id',
'unique_id',
'is_tip',
'x',
'y',
'Parent_id',
'px',
'py',
'node_color',
'branch_color',
'node_is_visible',
'branch_is_visible',
'width',
'size']]
(edge_res, _, _, _) = t.coords(500, 500)
assert_frame_equal(edge_exp, edge_res)
def test_rescale_random_tree(self):
t = Tree.from_tree(self.tree1)
self.assertAlmostEqual(
t.rescale(500, 500), 79.223492618646006, places=5)
def test_from_tree(self):
t = Tree.from_tree(self.tree2)
self.assertEqual(t.__class__, Tree)
def test_coords(self):
t = Tree.from_tree(self.tree2)
edge_exp = pd.DataFrame(
{
'a': [
'a',
'f',
DEFAULT_COLOR,
True,
True,
DEFAULT_COLOR,
True,
141.35398602846797,
339.46141862722482,
1,
1,
83.371774496551481,
292.50834951934343],
'e': [
'e',
'f',
DEFAULT_COLOR,
True,
True,
DEFAULT_COLOR,
True,
141.35398602846797,
339.46141862722482,
1,
1,
16.20896388864297,
420.73154625569776],
'f': [
'f',
'g',
DEFAULT_COLOR,
True,
False,
DEFAULT_COLOR,
True,
215.86090210071345,
343.36616063979909,
1,
1,
141.35398602846797,
339.46141862722482],
'b': [
'b',
'g',
DEFAULT_COLOR,
True,
True,
DEFAULT_COLOR,
True,
215.86090210071345,
343.36616063979909,
1,
1,
254.48144795927647,
487.5],
'c': [
'c',
'h',
DEFAULT_COLOR,
True,
True,
DEFAULT_COLOR,
True,
403.57843531045097,
221.46096919708964,
1,
1,
478.08535138269644,
225.36571120966394],
'd': [
'd',
'h',
DEFAULT_COLOR,
True,
True,
DEFAULT_COLOR,
True,
403.57843531045097,
221.46096919708964,
1,
1,
483.79103611135702,
12.500000000000028],
'g': [
'g',
'i',
DEFAULT_COLOR,
True,
False,
DEFAULT_COLOR,
True,
278.43341317062595,
302.73109682556259,
1,
1,
215.86090210071345,
343.36616063979909],
'h': [
'h',
'i',
DEFAULT_COLOR,
True,
False,
DEFAULT_COLOR,
True,
278.43341317062595,
302.73109682556259,
1,
1,
403.57843531045097,
221.46096919708964]},
index=[
'Node_id',
'Parent_id',
'branch_color',
'branch_is_visible',
'is_tip',
'node_color',
'node_is_visible',
'px',
'py',
'size',
'width',
'x',
'y']).T
edge_exp = edge_exp[['Node_id',
'is_tip',
'x',
'y',
'Parent_id',
'px',
'py',
'node_color',
'branch_color',
'node_is_visible',
'branch_is_visible',
'width',
'size']]
(edge_res, _, _, _) = t.coords(500, 500)
assert_frame_equal(edge_exp, edge_res)
def test_rescale(self):
t = Tree.from_tree(self.tree2)
self.assertAlmostEqual(
t.rescale(500, 500), 74.609165340334656, places=5)
def test_to_df(self):
t = TreeNode.read(['((a,b)c,d)r;'])
t = Tree.from_tree(t)
t.assign_ids()
i = 0
for node in t.postorder():
node.x2, node.y2 = i, i
data = [['d', 'r', DEFAULT_COLOR, True, True, DEFAULT_COLOR, True,
0, 0, 1, 1, 0, 0, t.find('d').id
],
['c', 'r', DEFAULT_COLOR, True, False, DEFAULT_COLOR, True,
0, 0, 1, 1, 0, 0, t.find('c').id
],
['b', 'c', DEFAULT_COLOR, True, True, DEFAULT_COLOR, True,
0, 0, 1, 1, 0, 0, t.find('b').id
],
['a', 'c', DEFAULT_COLOR, True, True, DEFAULT_COLOR, True,
0, 0, 1, 1, 0, 0, t.find('a').id
]]
df_exp = pd.DataFrame(data, columns=['Node_id',
'Parent_id',
'branch_color',
'branch_is_visible',
'is_tip',
'node_color',
'node_is_visible',
'px',
'py',
'size',
'width',
'x',
'y',
'unique_id'])
df_exp = df_exp[[
'Node_id',
'unique_id',
'is_tip',
'x',
'y',
'Parent_id',
'px',
'py',
'node_color',
'branch_color',
'node_is_visible',
'branch_is_visible',
'width',
'size']]
df_res = t.to_df().iloc[::-1,:]
df_exp.set_index('Node_id', inplace=True)
df_res.set_index('Node_id', inplace=True)
assert_frame_equal(df_exp, df_res)
if __name__ == "__main__":
unittest.main()
|
[
"unittest.main",
"skbio.TreeNode.read",
"pandas.DataFrame",
"numpy.random.seed",
"pandas.util.testing.assert_frame_equal",
"numpy.abs",
"empress.tree.Tree.from_tree",
"numpy.random.rand",
"skbio.TreeNode.from_linkage_matrix"
] |
[((13016, 13031), 'unittest.main', 'unittest.main', ([], {}), '()\n', (13029, 13031), False, 'import unittest\n'), ((619, 636), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (633, 636), True, 'import numpy as np\n'), ((649, 667), 'numpy.random.rand', 'np.random.rand', (['(10)'], {}), '(10)\n', (663, 667), True, 'import numpy as np\n'), ((846, 883), 'skbio.TreeNode.from_linkage_matrix', 'TreeNode.from_linkage_matrix', (['lm', 'ids'], {}), '(lm, ids)\n', (874, 883), False, 'from skbio import DistanceMatrix, TreeNode\n'), ((1183, 1242), 'skbio.TreeNode.read', 'TreeNode.read', (["['(((a:1,e:2)f:1,b:2)g:1,(c:1,d:3)h:2)i:1;']"], {}), "(['(((a:1,e:2)f:1,b:2)g:1,(c:1,d:3)h:2)i:1;'])\n", (1196, 1242), False, 'from skbio import DistanceMatrix, TreeNode\n'), ((1412, 1438), 'empress.tree.Tree.from_tree', 'Tree.from_tree', (['self.tree1'], {}), '(self.tree1)\n', (1426, 1438), False, 'from empress.tree import Tree\n'), ((1535, 1561), 'empress.tree.Tree.from_tree', 'Tree.from_tree', (['self.tree1'], {}), '(self.tree1)\n', (1549, 1561), False, 'from empress.tree import Tree\n'), ((5484, 5537), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {'columns': '[your, list, of, columns]'}), '(data, columns=[your, list, of, columns])\n', (5496, 5537), True, 'import pandas as pd\n'), ((6209, 6247), 'pandas.util.testing.assert_frame_equal', 'assert_frame_equal', (['edge_exp', 'edge_res'], {}), '(edge_exp, edge_res)\n', (6227, 6247), False, 'from pandas.util.testing import assert_frame_equal\n'), ((6301, 6327), 'empress.tree.Tree.from_tree', 'Tree.from_tree', (['self.tree1'], {}), '(self.tree1)\n', (6315, 6327), False, 'from empress.tree import Tree\n'), ((6466, 6492), 'empress.tree.Tree.from_tree', 'Tree.from_tree', (['self.tree2'], {}), '(self.tree2)\n', (6480, 6492), False, 'from empress.tree import Tree\n'), ((6577, 6603), 'empress.tree.Tree.from_tree', 'Tree.from_tree', (['self.tree2'], {}), '(self.tree2)\n', (6591, 6603), False, 'from empress.tree import Tree\n'), ((11019, 11057), 'pandas.util.testing.assert_frame_equal', 'assert_frame_equal', (['edge_exp', 'edge_res'], {}), '(edge_exp, edge_res)\n', (11037, 11057), False, 'from pandas.util.testing import assert_frame_equal\n'), ((11099, 11125), 'empress.tree.Tree.from_tree', 'Tree.from_tree', (['self.tree2'], {}), '(self.tree2)\n', (11113, 11125), False, 'from empress.tree import Tree\n'), ((11258, 11289), 'skbio.TreeNode.read', 'TreeNode.read', (["['((a,b)c,d)r;']"], {}), "(['((a,b)c,d)r;'])\n", (11271, 11289), False, 'from skbio import DistanceMatrix, TreeNode\n'), ((11300, 11317), 'empress.tree.Tree.from_tree', 'Tree.from_tree', (['t'], {}), '(t)\n', (11314, 11317), False, 'from empress.tree import Tree\n'), ((12010, 12202), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {'columns': "['Node_id', 'Parent_id', 'branch_color', 'branch_is_visible', 'is_tip',\n 'node_color', 'node_is_visible', 'px', 'py', 'size', 'width', 'x', 'y',\n 'unique_id']"}), "(data, columns=['Node_id', 'Parent_id', 'branch_color',\n 'branch_is_visible', 'is_tip', 'node_color', 'node_is_visible', 'px',\n 'py', 'size', 'width', 'x', 'y', 'unique_id'])\n", (12022, 12202), True, 'import pandas as pd\n'), ((12948, 12982), 'pandas.util.testing.assert_frame_equal', 'assert_frame_equal', (['df_exp', 'df_res'], {}), '(df_exp, df_res)\n', (12966, 12982), False, 'from pandas.util.testing import assert_frame_equal\n'), ((6624, 8060), 'pandas.DataFrame', 'pd.DataFrame', (["{'a': ['a', 'f', DEFAULT_COLOR, True, True, DEFAULT_COLOR, True, \n 141.35398602846797, 339.4614186272248, 1, 1, 83.37177449655148, \n 292.5083495193434], 'e': ['e', 'f', DEFAULT_COLOR, True, True,\n DEFAULT_COLOR, True, 141.35398602846797, 339.4614186272248, 1, 1, \n 16.20896388864297, 420.73154625569776], 'f': ['f', 'g', DEFAULT_COLOR, \n True, False, DEFAULT_COLOR, True, 215.86090210071345, 343.3661606397991,\n 1, 1, 141.35398602846797, 339.4614186272248], 'b': ['b', 'g',\n DEFAULT_COLOR, True, True, DEFAULT_COLOR, True, 215.86090210071345, \n 343.3661606397991, 1, 1, 254.48144795927647, 487.5], 'c': ['c', 'h',\n DEFAULT_COLOR, True, True, DEFAULT_COLOR, True, 403.57843531045097, \n 221.46096919708964, 1, 1, 478.08535138269644, 225.36571120966394], 'd':\n ['d', 'h', DEFAULT_COLOR, True, True, DEFAULT_COLOR, True, \n 403.57843531045097, 221.46096919708964, 1, 1, 483.791036111357, \n 12.500000000000028], 'g': ['g', 'i', DEFAULT_COLOR, True, False,\n DEFAULT_COLOR, True, 278.43341317062595, 302.7310968255626, 1, 1, \n 215.86090210071345, 343.3661606397991], 'h': ['h', 'i', DEFAULT_COLOR, \n True, False, DEFAULT_COLOR, True, 278.43341317062595, 302.7310968255626,\n 1, 1, 403.57843531045097, 221.46096919708964]}"], {'index': "['Node_id', 'Parent_id', 'branch_color', 'branch_is_visible', 'is_tip',\n 'node_color', 'node_is_visible', 'px', 'py', 'size', 'width', 'x', 'y']"}), "({'a': ['a', 'f', DEFAULT_COLOR, True, True, DEFAULT_COLOR, \n True, 141.35398602846797, 339.4614186272248, 1, 1, 83.37177449655148, \n 292.5083495193434], 'e': ['e', 'f', DEFAULT_COLOR, True, True,\n DEFAULT_COLOR, True, 141.35398602846797, 339.4614186272248, 1, 1, \n 16.20896388864297, 420.73154625569776], 'f': ['f', 'g', DEFAULT_COLOR, \n True, False, DEFAULT_COLOR, True, 215.86090210071345, 343.3661606397991,\n 1, 1, 141.35398602846797, 339.4614186272248], 'b': ['b', 'g',\n DEFAULT_COLOR, True, True, DEFAULT_COLOR, True, 215.86090210071345, \n 343.3661606397991, 1, 1, 254.48144795927647, 487.5], 'c': ['c', 'h',\n DEFAULT_COLOR, True, True, DEFAULT_COLOR, True, 403.57843531045097, \n 221.46096919708964, 1, 1, 478.08535138269644, 225.36571120966394], 'd':\n ['d', 'h', DEFAULT_COLOR, True, True, DEFAULT_COLOR, True, \n 403.57843531045097, 221.46096919708964, 1, 1, 483.791036111357, \n 12.500000000000028], 'g': ['g', 'i', DEFAULT_COLOR, True, False,\n DEFAULT_COLOR, True, 278.43341317062595, 302.7310968255626, 1, 1, \n 215.86090210071345, 343.3661606397991], 'h': ['h', 'i', DEFAULT_COLOR, \n True, False, DEFAULT_COLOR, True, 278.43341317062595, 302.7310968255626,\n 1, 1, 403.57843531045097, 221.46096919708964]}, index=['Node_id',\n 'Parent_id', 'branch_color', 'branch_is_visible', 'is_tip',\n 'node_color', 'node_is_visible', 'px', 'py', 'size', 'width', 'x', 'y'])\n", (6636, 8060), True, 'import pandas as pd\n'), ((726, 739), 'numpy.abs', 'np.abs', (['(x - y)'], {}), '(x - y)\n', (732, 739), True, 'import numpy as np\n')]
|
from dataloader.paths import PathsDataset
from dataloader import indoor_scenes
from active_selection.vote_entropy import VoteEntropySelector
from utils.misc import turn_on_dropout, visualize_entropy, visualize_spx_dataset
import constants
import torch
from torch.utils.data import DataLoader
from tqdm import tqdm
import numpy as np
from collections import OrderedDict, defaultdict
class RegionalVoteEntropySelector:
def __init__(self, dataset, lmdb_handle, superpixel_dir, base_size, batch_size, num_classes, region_size, overlap_handler, mode):
self.lmdb_handle = lmdb_handle
self.base_size = base_size
self.batch_size = batch_size
self.dataset = dataset
self.superpixel_dir = superpixel_dir
self.overlap_handler = overlap_handler
self.vote_entropy_selector = VoteEntropySelector(dataset, lmdb_handle, base_size, batch_size, num_classes)
self.region_size = region_size
if mode == 'window':
self.select_next_batch = self.select_next_batch_with_windows
elif mode == 'superpixel':
self.select_next_batch = self.select_next_batch_with_superpixels
else:
raise NotImplementedError
# superpixel based selection methods
def select_next_batch_with_superpixels(self, model, training_set, selection_count):
model.eval()
model.apply(turn_on_dropout)
loader = DataLoader(indoor_scenes.IndoorScenesWithAllInfo(self.dataset, self.lmdb_handle, self.superpixel_dir, self.base_size, training_set.all_train_paths), batch_size=self.batch_size, shuffle=False, num_workers=0)
scores = []
superpixel_masks = []
#visualize_entropy.max_weight = 96*96
for sample in tqdm(loader, desc='Entropy'):
image_batch = sample['image'].cuda()
label_batch = sample['label'].cuda()
superpixel_batch = sample['superpixel']
superpixel_masks.extend([superpixel_batch[i, :, :] for i in range(superpixel_batch.shape[0])])
scores.extend(self.vote_entropy_selector.batch_entropy_func(model, image_batch, label_batch, superpixel_batch.numpy()))
all_train_scenes = sorted(list(set([indoor_scenes.IndoorScenesWithAllInfo.get_scene_id_from_image_path(self.dataset, x) for x in training_set.all_train_paths])))
scene_indices = [all_train_scenes.index(indoor_scenes.IndoorScenesWithAllInfo.get_scene_id_from_image_path(self.dataset, im_path)) for im_path in training_set.all_train_paths]
superpixel_ids = []
superpixel_scores_expanded = []
for image_score_idx, superpixel_scores in enumerate(scores):
for superpixel_idx in superpixel_scores.keys():
superpixel_ids.append((scene_indices[image_score_idx], image_score_idx, superpixel_idx))
superpixel_scores_expanded.append(superpixel_scores[superpixel_idx])
_sorted_scores = np.array(list(list(zip(*sorted(zip(superpixel_ids, superpixel_scores_expanded), key=lambda x: x[1], reverse=True)))[0]))
sorted_scores = np.zeros((_sorted_scores.shape[0], _sorted_scores.shape[1] + 1), dtype=np.int32)
sorted_scores[:, 0:_sorted_scores.shape[1]] = _sorted_scores
total_pixels_selected = 0
selected_regions = OrderedDict()
image_superpixels = defaultdict(list)
ctr = 0
print('Selecting superpixels...')
pbar = tqdm(total=selection_count)
while total_pixels_selected < selection_count * self.base_size[0] * self.base_size[1] and ctr < sorted_scores.shape[0]:
if sorted_scores[ctr, 2] not in training_set.image_superpixels[training_set.all_train_paths[sorted_scores[ctr, 1]]] and not (sorted_scores[ctr, 3] == 1):
mask = (superpixel_masks[sorted_scores[ctr, 1]] == sorted_scores[ctr, 2]).numpy().astype(np.uint8)
if training_set.all_train_paths[sorted_scores[ctr, 1]] in selected_regions:
selected_regions[training_set.all_train_paths[sorted_scores[ctr, 1]]] = selected_regions[training_set.all_train_paths[sorted_scores[ctr, 1]]] | mask
else:
selected_regions[training_set.all_train_paths[sorted_scores[ctr, 1]]] = mask
image_superpixels[training_set.all_train_paths[sorted_scores[ctr, 1]]].append(sorted_scores[ctr, 2])
valid_pixels = mask.sum()
total_pixels_selected += valid_pixels
pbar.update(valid_pixels / (self.base_size[0] * self.base_size[1]))
if not self.overlap_handler is None:
overlapping_indices = []
tgt_scene_id = indoor_scenes.IndoorScenesWithAllInfo.get_scene_id_from_image_path(self.dataset, training_set.all_train_paths[sorted_scores[ctr, 1]])
overlap_dict = self.overlap_handler.get_overlap_dict_for_scene(tgt_scene_id)
tgt_scene_list_index = all_train_scenes.index(tgt_scene_id)
sorted_scores_view_mask = sorted_scores[:, 0] == tgt_scene_list_index
sorted_scores_view = sorted_scores[sorted_scores_view_mask]
for sc_idx in range(sorted_scores_view.shape[0]):
src_scene_id = indoor_scenes.IndoorScenesWithAllInfo.get_scene_id_from_image_path(self.dataset, training_set.all_train_paths[sorted_scores_view[sc_idx, 1]])
if sorted_scores[ctr, 1] in overlap_dict and (sorted_scores[ctr, 2], sorted_scores_view[sc_idx, 1], sorted_scores_view[sc_idx, 2]) in overlap_dict[sorted_scores[ctr, 1]]:
if overlap_dict[sorted_scores[ctr, 1]][(sorted_scores[ctr, 2], sorted_scores_view[sc_idx, 1], sorted_scores_view[sc_idx, 2])] > self.overlap_handler.superpixel_overlap:
sorted_scores_view[sc_idx, 3] = 1
sorted_scores[sorted_scores_view_mask] = sorted_scores_view
ctr += 1
pbar.close()
print('Selected ', total_pixels_selected / (self.base_size[0] * self.base_size[1]), 'images')
model.eval()
training_set.expand_training_set(selected_regions, image_superpixels)
# window based selection methods
def nms(self, img_idx, score_map):
selected_score_map_pts = []
for i in range((score_map.shape[0]*score_map.shape[1])//(self.region_size*self.region_size)):
argmax = score_map.view(-1).argmax()
r, c = argmax // score_map.shape[1], argmax % score_map.shape[1]
selected_score_map_pts.append((img_idx, r.cpu().item(), c.cpu().item(), score_map[r, c].cpu().item()))
score_map[max(0, r - self.region_size): min(score_map.shape[0], r + self.region_size), max(0, c - self.region_size): min(score_map.shape[1], c + self.region_size)] = 0
return selected_score_map_pts
def select_next_batch_with_windows(self, model, training_set, selection_count):
model.eval()
model.apply(turn_on_dropout)
weights = torch.cuda.FloatTensor(self.region_size, self.region_size).fill_(1.)
loader = DataLoader(PathsDataset(self.lmdb_handle, self.base_size, training_set.all_train_paths), batch_size=self.batch_size, shuffle=False, num_workers=0)
map_ctr = 0
scores = []
for sample in tqdm(loader, desc='Entropy'):
image_batch = sample['image'].cuda()
label_batch = sample['label'].cuda()
for batch_idx, entropy_map in enumerate(self.vote_entropy_selector.batch_entropy_func(model, image_batch, label_batch)):
if training_set.all_train_paths[map_ctr] in training_set.get_selections():
entropy_map[training_set.get_selections()[training_set.all_train_paths[map_ctr]] == 1] = 0
convolution_output = torch.nn.functional.conv2d(torch.cuda.FloatTensor(entropy_map).unsqueeze(0).unsqueeze(0), weights.unsqueeze(0).unsqueeze(0)).squeeze().squeeze()
scores.extend(self.nms(map_ctr, convolution_output))
map_ctr += 1
selected_samples = sorted(scores, key=lambda x: x[3], reverse=True)[:int(0.5 + selection_count * self.base_size[0] * self.base_size[1] / (self.region_size * self.region_size))]
print('Last selected sample: ', selected_samples[-1])
selected_regions = OrderedDict()
total_pixels_selected = 0
for ss in selected_samples:
mask = np.zeros(self.base_size, dtype=np.int) == 1
mask[ss[1] : ss[1] + self.region_size, ss[2] : ss[2] + self.region_size] = True
valid_pixels = mask.sum()
total_pixels_selected += valid_pixels
if training_set.all_train_paths[ss[0]] in selected_regions:
selected_regions[training_set.all_train_paths[ss[0]]] = selected_regions[training_set.all_train_paths[ss[0]]] | mask
else:
selected_regions[training_set.all_train_paths[ss[0]]] = mask
model.eval()
print('Selected ', total_pixels_selected / (self.base_size[0] * self.base_size[1]), 'images')
training_set.expand_training_set(selected_regions, [])
|
[
"tqdm.tqdm",
"dataloader.indoor_scenes.IndoorScenesWithAllInfo",
"numpy.zeros",
"active_selection.vote_entropy.VoteEntropySelector",
"torch.cuda.FloatTensor",
"dataloader.indoor_scenes.IndoorScenesWithAllInfo.get_scene_id_from_image_path",
"collections.defaultdict",
"collections.OrderedDict",
"dataloader.paths.PathsDataset"
] |
[((824, 901), 'active_selection.vote_entropy.VoteEntropySelector', 'VoteEntropySelector', (['dataset', 'lmdb_handle', 'base_size', 'batch_size', 'num_classes'], {}), '(dataset, lmdb_handle, base_size, batch_size, num_classes)\n', (843, 901), False, 'from active_selection.vote_entropy import VoteEntropySelector\n'), ((1757, 1785), 'tqdm.tqdm', 'tqdm', (['loader'], {'desc': '"""Entropy"""'}), "(loader, desc='Entropy')\n", (1761, 1785), False, 'from tqdm import tqdm\n'), ((3099, 3184), 'numpy.zeros', 'np.zeros', (['(_sorted_scores.shape[0], _sorted_scores.shape[1] + 1)'], {'dtype': 'np.int32'}), '((_sorted_scores.shape[0], _sorted_scores.shape[1] + 1), dtype=np.int32\n )\n', (3107, 3184), True, 'import numpy as np\n'), ((3311, 3324), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (3322, 3324), False, 'from collections import OrderedDict, defaultdict\n'), ((3353, 3370), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (3364, 3370), False, 'from collections import OrderedDict, defaultdict\n'), ((3445, 3472), 'tqdm.tqdm', 'tqdm', ([], {'total': 'selection_count'}), '(total=selection_count)\n', (3449, 3472), False, 'from tqdm import tqdm\n'), ((7367, 7395), 'tqdm.tqdm', 'tqdm', (['loader'], {'desc': '"""Entropy"""'}), "(loader, desc='Entropy')\n", (7371, 7395), False, 'from tqdm import tqdm\n'), ((8385, 8398), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (8396, 8398), False, 'from collections import OrderedDict, defaultdict\n'), ((1434, 1575), 'dataloader.indoor_scenes.IndoorScenesWithAllInfo', 'indoor_scenes.IndoorScenesWithAllInfo', (['self.dataset', 'self.lmdb_handle', 'self.superpixel_dir', 'self.base_size', 'training_set.all_train_paths'], {}), '(self.dataset, self.lmdb_handle, self.\n superpixel_dir, self.base_size, training_set.all_train_paths)\n', (1471, 1575), False, 'from dataloader import indoor_scenes\n'), ((7160, 7236), 'dataloader.paths.PathsDataset', 'PathsDataset', (['self.lmdb_handle', 'self.base_size', 'training_set.all_train_paths'], {}), '(self.lmdb_handle, self.base_size, training_set.all_train_paths)\n', (7172, 7236), False, 'from dataloader.paths import PathsDataset\n'), ((2395, 2489), 'dataloader.indoor_scenes.IndoorScenesWithAllInfo.get_scene_id_from_image_path', 'indoor_scenes.IndoorScenesWithAllInfo.get_scene_id_from_image_path', (['self.dataset', 'im_path'], {}), '(self.\n dataset, im_path)\n', (2461, 2489), False, 'from dataloader import indoor_scenes\n'), ((7063, 7121), 'torch.cuda.FloatTensor', 'torch.cuda.FloatTensor', (['self.region_size', 'self.region_size'], {}), '(self.region_size, self.region_size)\n', (7085, 7121), False, 'import torch\n'), ((8497, 8535), 'numpy.zeros', 'np.zeros', (['self.base_size'], {'dtype': 'np.int'}), '(self.base_size, dtype=np.int)\n', (8505, 8535), True, 'import numpy as np\n'), ((4695, 4833), 'dataloader.indoor_scenes.IndoorScenesWithAllInfo.get_scene_id_from_image_path', 'indoor_scenes.IndoorScenesWithAllInfo.get_scene_id_from_image_path', (['self.dataset', 'training_set.all_train_paths[sorted_scores[ctr, 1]]'], {}), '(self.\n dataset, training_set.all_train_paths[sorted_scores[ctr, 1]])\n', (4761, 4833), False, 'from dataloader import indoor_scenes\n'), ((2221, 2309), 'dataloader.indoor_scenes.IndoorScenesWithAllInfo.get_scene_id_from_image_path', 'indoor_scenes.IndoorScenesWithAllInfo.get_scene_id_from_image_path', (['self.dataset', 'x'], {}), '(self.\n dataset, x)\n', (2287, 2309), False, 'from dataloader import indoor_scenes\n'), ((5286, 5432), 'dataloader.indoor_scenes.IndoorScenesWithAllInfo.get_scene_id_from_image_path', 'indoor_scenes.IndoorScenesWithAllInfo.get_scene_id_from_image_path', (['self.dataset', 'training_set.all_train_paths[sorted_scores_view[sc_idx, 1]]'], {}), '(self.\n dataset, training_set.all_train_paths[sorted_scores_view[sc_idx, 1]])\n', (5352, 5432), False, 'from dataloader import indoor_scenes\n'), ((7894, 7929), 'torch.cuda.FloatTensor', 'torch.cuda.FloatTensor', (['entropy_map'], {}), '(entropy_map)\n', (7916, 7929), False, 'import torch\n')]
|
"""This file contains methods for creating and updating cluster graphs (NOT a class) using networkx library
"""
import networkx as nx
import numpy as np
import copy
from statistics import mean, stdev
def create_cg(edge_dist_array):
"""
Given an edge distance array, returns a new cluster graph
:param edge_dist_array: array of entries in the format [[node1, node2, dist],[...],...]
:return: None
"""
cg = nx.Graph()
if len(edge_dist_array.shape) < 2 and len(edge_dist_array) == 3:
node1 = edge_dist_array[0]
node2 = edge_dist_array[1]
weight = edge_dist_array[2]
cg.add_weighted_edges_from([(node1, node2, weight)])
else:
append_edges_to_cg(cg, edge_dist_array)
#print("Created cluster: ", cg.nodes())
return cg
def append_edges_to_cg(cg, edge_dist_array):
"""
Given an edge distance array and cluster graph, appends edges to the cluster graph
:param cg: cluster graph
:param edge_dist_array: array of entries in the format [[node1, node2, dist],[...],...]
:return: updated cg
"""
if len(edge_dist_array) <1:
print("Warning! attempting to add empty edge_dist_array. Cluster unmodified!")
return cg
#print("Adding ", edge_dist_array , " to cluster ", cg.nodes())
for entry in edge_dist_array:
node1 = entry[0]
node2 = entry[1]
weight = entry[2]
cg.add_weighted_edges_from([(node1, node2, weight)])
return cg
def get_cg_avg_dist(cg):
"""
Given a cluster graph, returns its average distance
:param cg: a cluster graph
:return: average distance of the cluster graph cg
"""
dist = convert_cg_to_edge_dist_array(cg)
return mean(dist[:,2])
def convert_cg_to_edge_dist_array(cg): # not sorted edge_dist_array
"""
Given a cluster graph, extract and convert its edges to a list
:param cg: a cluster graoh cg
:return: edge distance array in format [(node1, node2, dist),(...),...]
"""
edge_dist_array = []
for edge in cg.edges():
node1 = edge[0]
node2 = edge[1]
weight = cg.get_edge_data(node1, node2)['weight']
edge_dist_array.append((node1, node2, weight))
return np.asarray(edge_dist_array)
def check_node_adding_criteria(cg, edge_dist_array, add_node_threshold):
"""
Returns True if a new node can be added to the cluster. A new node is represented by a
corresponding list of edges which link the new node to the existing nodes in the cluster
:param cg: a cluster graph
:param edge_dist_array: a list of edges (representing a new node) to be added to the cluster
:param add_node_threshold: A new node can be added to a cluster if the average distance of the new cluster is below
the add_node_threshold of the cluster.
:return: boolean
"""
new_cg = copy.deepcopy(cg)
new_cg = append_edges_to_cg(new_cg, edge_dist_array)
new_cg_avg_dist = get_cg_avg_dist(new_cg)
cg1_avg_dist = get_cg_avg_dist(cg)
diff_dist = ((new_cg_avg_dist - cg1_avg_dist)*100)/cg1_avg_dist
#print("Avg dist new cg: ", new_cg_avg_dist, " prev cg: ", cg1_avg_dist, " diff dist ", diff_dist)
return diff_dist < add_node_threshold
def check_and_add_node(cg, node, edge_dist_array, add_node_threshold):
"""
Check and add new node to the cluster if conditions by check_node_adding_criteria() are met
:param cg: a cluster graph
:param node: a new node
:param edge_dist_array: a list of edges (representing a new node) to be added to the cluster
:param add_node_threshold: A new node can be added to a cluster if the average distance of the new cluster is below
the add_node_threshold of the cluster
:return: None as the cluster is simply updated
"""
avg_dist = get_cg_avg_dist(cg)
cluster_size = len(cg.nodes())
if cluster_size>0 and avg_dist>0:
add_node_threshold = add_node_threshold /(cluster_size * avg_dist)
#print("Attempting to add node", node, " to cluster ", cg.nodes())
#print("Add Node threshold: ", add_node_threshold)
if not cg_has_node(cg, node) and check_node_adding_criteria(cg, edge_dist_array, add_node_threshold):
append_edges_to_cg(cg, edge_dist_array)
#print("Node added, cluster becomes ", cg.nodes())
else:
pass
#print("Node not added")
def check_and_add_node2(cg, node, edge_dist_array, add_node_threshold):
"""
Check and add new node to the cluster if conditions by check_node_adding_criteria() are met
:param cg: a cluster graph
:param node: a new node
:param edge_dist_array: a list of edges (representing a new node) to be added to the cluster
:param add_node_threshold: A new node can be added to a cluster if the average distance of the new cluster is below
the add_node_threshold of the cluster
:return: None as the cluster is simply updated
"""
avg_dist = get_cg_avg_dist(cg)
cluster_size = len(cg.nodes())
if cluster_size>0 and avg_dist>0:
add_node_threshold = add_node_threshold /(cluster_size * avg_dist)
if not cg_has_node(cg, node) and check_node_adding_criteria(cg, edge_dist_array, add_node_threshold):
#print("Attempting to add node", node, " to cluster ", cg.nodes())
#print("Add Node threshold: ", add_node_threshold)
append_edges_to_cg(cg, edge_dist_array)
#print("Node added, cluster becomes ", cg.nodes())
else:
pass
else:
if mean(edge_dist_array[:,2])< 0.3: # why
append_edges_to_cg(cg, edge_dist_array)
#print("I am here!", cg.nodes(), edge_dist_array)
def merge_clusters(cg1, cg2, edge_dist_array):
"""
Merge two clusters cg1 and cg2
:param cg1: cluster graph 1
:param cg2: cluster graph 2
:param edge_dist_array: a list of edges (representing a the edges connecting the the two clusters)
:return: a new cluster cg3
"""
cg3 = create_cg(edge_dist_array)
cg1_edge_dist_array = convert_cg_to_edge_dist_array(cg1)
cg2_edge_dist_array = convert_cg_to_edge_dist_array(cg2)
append_edges_to_cg(cg3, cg1_edge_dist_array)
append_edges_to_cg(cg3, cg2_edge_dist_array)
append_edges_to_cg(cg3, edge_dist_array)
return cg3
def check_cg_merge_criteria(cg1, cg2, edge_dist_array, merge_cluster_threshold):
"""
Returns True if two clusters can be merged. The connections between the two clusters are represented by a list
of edges
:param cg1: cluster graph 1
:param cg2: cluster graph 2
:param edge_dist_array: a list of edges (representing a the edges connecting the the two clusters)
:param merge_cluster_threshold: Two clusters can be merged together if the average distance of the new cluster is
below the merge_thresholds for either contributing clusters
:return: boolean
"""
avg_dist_cg1 = get_cg_avg_dist(cg1)
avg_dist_cg2 = get_cg_avg_dist(cg2)
cluster_size_cg1 = len(cg1.nodes())
cluster_size_cg2 = len(cg2.nodes())
merge_cluster_threshold_cg1 = merge_cluster_threshold
merge_cluster_threshold_cg2 = merge_cluster_threshold
if cluster_size_cg1 > 0 and avg_dist_cg1>0:
merge_cluster_threshold_cg1 = merge_cluster_threshold / (cluster_size_cg1 * avg_dist_cg1)
if cluster_size_cg2 > 0 and avg_dist_cg2:
merge_cluster_threshold_cg2 = merge_cluster_threshold / (cluster_size_cg2 * avg_dist_cg2)
new_cg = merge_clusters(cg1, cg2, edge_dist_array)
new_cg_avg_dist = get_cg_avg_dist(new_cg)
cg1_avg_dist = get_cg_avg_dist(cg1)
cg2_avg_dist = get_cg_avg_dist(cg2)
if cg1_avg_dist>0 and cg2_avg_dist>0:
diff_dist_c1 = ((new_cg_avg_dist - cg1_avg_dist)*100)/cg1_avg_dist
diff_dist_c2 = ((new_cg_avg_dist - cg2_avg_dist)*100)/cg2_avg_dist
#print("Avg dist c1: ",cg1_avg_dist, " c2: ", cg2_avg_dist, " c3: ",new_cg_avg_dist)
#print("merge cluster threshold cg1: ", merge_cluster_threshold_cg1, " cg2: ",merge_cluster_threshold_cg2)
#print(diff_dist_c1, diff_dist_c2)
return diff_dist_c1 < merge_cluster_threshold_cg1 and diff_dist_c2 < merge_cluster_threshold_cg2
else:
pass
#print("Error!! Size of cluster cannot be zero! Division by zero is attenpted")
def check_cg_merge_criteria2(cg1, cg2, edge_dist_array, merge_cluster_threshold):
"""
Returns True if two clusters can be merged. The connections between the two clusters are represented by a list
of edges
:param cg1: cluster graph 1
:param cg2: cluster graph 2
:param edge_dist_array: a list of edges (representing a the edges connecting the the two clusters)
:param merge_cluster_threshold: Two clusters can be merged together if the average distance of the new cluster is
below the merge_thresholds for either contributing clusters
:return: boolean
"""
avg_dist_cg1 = get_cg_avg_dist(cg1)
avg_dist_cg2 = get_cg_avg_dist(cg2)
cluster_size_cg1 = len(cg1.nodes())
cluster_size_cg2 = len(cg2.nodes())
merge_cluster_threshold_cg1 = merge_cluster_threshold
merge_cluster_threshold_cg2 = merge_cluster_threshold
new_cg = merge_clusters(cg1, cg2, edge_dist_array)
new_cg_avg_dist = get_cg_avg_dist(new_cg)
if cluster_size_cg1 > 0 and cluster_size_cg2 > 0 and avg_dist_cg1>0 and avg_dist_cg2>0:
merge_cluster_threshold_cg1 = merge_cluster_threshold / (cluster_size_cg1 * avg_dist_cg1)
merge_cluster_threshold_cg2 = merge_cluster_threshold / (cluster_size_cg2 * avg_dist_cg2)
diff_dist_c1 = ((new_cg_avg_dist - avg_dist_cg1)*100)/avg_dist_cg1
diff_dist_c2 = ((new_cg_avg_dist - avg_dist_cg2)*100)/avg_dist_cg2
#print("merge cluster threshold cg1: ", merge_cluster_threshold_cg1, " cg2: ", merge_cluster_threshold_cg2)
#print(diff_dist_c1, diff_dist_c2)
return diff_dist_c1 < merge_cluster_threshold_cg1 and diff_dist_c2 < merge_cluster_threshold_cg2
elif cluster_size_cg1 > 0 and cluster_size_cg2 > 0 and avg_dist_cg1 == 0 and avg_dist_cg2 > 0:
merge_cluster_threshold_cg2 = merge_cluster_threshold / (cluster_size_cg2 * avg_dist_cg2)
diff_dist_c2 = ((new_cg_avg_dist - avg_dist_cg2) * 100) / avg_dist_cg2
#print(" cg2: ", merge_cluster_threshold_cg2)
#print(0.4, diff_dist_c2)
#print("new avg dist", new_cg_avg_dist )
return new_cg_avg_dist < 0.3 and diff_dist_c2 < merge_cluster_threshold_cg2
elif cluster_size_cg1 > 0 and cluster_size_cg2 > 0 and avg_dist_cg1 > 0 and avg_dist_cg2 == 0:
merge_cluster_threshold_cg1 = merge_cluster_threshold / (cluster_size_cg1 * avg_dist_cg1)
diff_dist_c1 = ((new_cg_avg_dist - avg_dist_cg1) * 100) / avg_dist_cg1
#print(" cg1: ", merge_cluster_threshold_cg1)
#print(0.4, diff_dist_c1)
#print("new avg dist", new_cg_avg_dist)
return new_cg_avg_dist < 0.3 and diff_dist_c1 < merge_cluster_threshold_cg1
else:
pass
#print("Error!! Size of cluster cannot be zero! Division by zero is attenpted")
def check_and_merge_cg(cg1, cg2, dist_array, merge_cluster_threshold):
"""Check and merge two clusters if conditions by check_cg_merge_criteria() are met
:param cg1: cluster graph 1
:param cg2: cluster graph 2
:param edge_dist_array: a list of edges (representing a new node) to be added to the cluster
:param merge_threshold: Two clusters can be merged together if the average distance of the new cluster is below
the merge_thresholds for either contributing clusters
"""
nodes = set(list(cg1.node.keys()) + list( cg2.node.keys()))
selected_dist_array = np.asarray([e for e in dist_array if e[0] in nodes and e[1] in nodes])
#print(selected_dist_array)
if check_cg_merge_criteria2(cg1, cg2, selected_dist_array, merge_cluster_threshold):
#print("Clusters ", cg1.nodes()," and ", cg2.nodes(), " are merged")
return merge_clusters(cg1, cg2, selected_dist_array)
else:
pass
#print("Clusters",cg1.nodes()," and ", cg2.nodes(), " are not merged")
def cg_has_node(cg, node):
"""
Return True if the cluster graph contains the corresponding node
:param cg:
:param node:
:return:
"""
return cg.nodes().__contains__(node)
def find_cg_having_node(cg_list, node):
"""
From a list of cluster graphs, find the one containing a given node.
:param cg_list:
:param node:
:return:
"""
for cg in cg_list:
if cg_has_node(cg, node):
return cg
def print_cg_list(cg_list):
""" Print the clusters and members in a cg list
Keyword arguments:
cg_list: list of cluster grpahs
"""
for cg in cg_list:
print("\n\n")
print("\tnodes: ",cg.nodes())
print("\tavg. dist: ", get_cg_avg_dist(cg))
def prevent_duplicated_windows(dist_array):
"""
Iterates over each entry in the dist_array and removes those windows which have extremely small distance,
to prevent duplicated windows.
:param dist_array: a flattened version of the dist_matrix in the format of entries (node0/ window0, node1/ window1, distance),
usually sorted
:return: a new dist_array without duplicates
"""
duplicated_entries = [(elem[0],elem[1]) for elem in dist_array if elem[2]<0.005]
duplicated_nodes = [item for sublist in duplicated_entries for item in sublist]
#print(duplicated_nodes)
selected_dist_array = []
for entry in dist_array:
node0, node1, weight = entry[0], entry[1], entry[2]
if node1 not in duplicated_nodes and node0 not in duplicated_nodes:
selected_dist_array.append(entry)
return np.asarray(selected_dist_array)
def get_sorted_dist_array(dist_matrix, node_labels):
"""
Given a distance matrix, create an array of entries (node0/ window0, node1/ window1, distance) sorted by distance
:param dist_matrix: a two dimensional matrix representing the distance between windows.
:param node_labels: labels of nodes
:return:
"""
edges = []
for i in range(0, len(dist_matrix)):
for j in range(0, len(dist_matrix)):
if i > j:
edges.append((node_labels[i], node_labels[j], dist_matrix[i][j]))
sorted_dist_array = np.asarray(edges)
sorted_dist_array = sorted_dist_array[sorted_dist_array[:, 2].argsort()]
return sorted_dist_array
def filter_entries_containing_nodes(dist_array, nodes_set):
"""
Filter and select entries from a dist_array containing only those nodes in the given list of nodes
:param dist_array: a flattened version of the dist_matrix in the format of entries (node0/ window0, node1/ window1, distance),
usually sorted
:param nodes_set: nodes to be used for filtering
:return: a new dist_array with entries having nodes in nodes_set
"""
if len(dist_array)<1:
print("Warning! dist array is empty! None is returned!")
return None
if len(nodes_set)<1:
print("Warning! nodes_list is empty! None is returned!")
return None
selected_dist_array = []
for entry in dist_array:
node0, node1, weight = entry[0], entry[1], entry[2]
if node1 in nodes_set and node0 in nodes_set:
selected_dist_array.append(entry)
return np.asarray(selected_dist_array)
def cluster_graph(node_labels, dist_matrix, merge_cluster_threshold = 50, add_node_threshold = 50):
"""
Given a dist_matrix, create a list of cluster-graphs according to preset conditions
:param node_labels: labels of nodes
:param dist_matrix: a two dimensional matrix representing the distance between windows.
:param merge_cluster_threshold: Two clusters can be merged together if the average distance of the new cluster is below
the merge_thresholds for either contributing clusters
:param add_node_threshold: A new node can be added to a cluster if the average distance of the new cluster is below
the add_node_threshold of the cluster
:return: a list of cluster graphs
"""
# comment out
#sorted_dist_array = prevent_duplicated_windows(get_sorted_dist_array(dist_matrix, node_labels))# flatten the distance matrix to a sorted distance array
sorted_dist_array = get_sorted_dist_array(dist_matrix, node_labels) # flatten the distance matrix to a sorted distance array
#print("Sorted dist array")
#print(sorted_dist_array)
cg_list = [] # placeholder list to contain cluster_graphs
entries_already_traversed = np.asarray([])
''' Placeholder list to contain the entries that have been used before they were traversed,
perhaps because an entry containing one of the nodes was being processed.
The idea is to prevent entries that were traversed from being traversed again.
Can be programmed differently to not require this complication
'''
for i in range(0, len(sorted_dist_array)): # for all entries in the sorted_dist_arr
entry = sorted_dist_array[i]
#print("Entries covered ", entries_already_traversed)
if entry not in entries_already_traversed:
#print("\n\n\n Evaluating edge ", entry)
exclude_indices = range(0, i) # indices covered in order
remaining_dist_array = remove_indices(sorted_dist_array, exclude_indices) #remaining dist_array after entry
if len(cg_list) == 0: # if cg_list is empty
cg_list.append(create_cg(entry)) # create a cluster-graph
else:
node0,node1,weight = entry[0],entry[1],entry[2]
cluster_containing_node0 = find_cg_having_node(cg_list, node0)
cluster_containing_node1 = find_cg_having_node(cg_list, node1)
if cluster_containing_node0 is None and cluster_containing_node1 is None: # neither node0 not node 1 belong to any cluster
#print("Neither node ", node0 , " nor node ", node1, " is contained by any cluster")
cg_list.append(create_cg(entry))
elif cluster_containing_node0 is None and cluster_containing_node1 is not None: # node0 does not belong to cluster, node1 does. Therefore add node 0 to cluster.
#print("node ", node1, " is contained by cluster", cluster_containing_node1.nodes(), "while node ",node0, " is not")
nodes_set = set(cluster_containing_node1.nodes())
nodes_set.add(node0)
selected_dist_array = filter_entries_containing_nodes(remaining_dist_array, nodes_set)
entries_already_traversed = update_entry_already_traversed_list(entries_already_traversed,
selected_dist_array)
check_and_add_node2(cluster_containing_node1, node0, selected_dist_array, add_node_threshold)
elif cluster_containing_node0 is not None and cluster_containing_node1 is None: # node0 belongs to a cluster, node1 does not. Therefore add node 1 to cluster.
#print("node ", node0, " is contained by cluster", cluster_containing_node0.nodes(), "while node ",node1, " is not")
nodes_set = set(cluster_containing_node0.nodes())
nodes_set.add(node1)
selected_dist_array = filter_entries_containing_nodes(remaining_dist_array, nodes_set)
entries_already_traversed = update_entry_already_traversed_list(entries_already_traversed,
selected_dist_array)
check_and_add_node2(cluster_containing_node0, node1, selected_dist_array, add_node_threshold)
else: # node 0 and node 1 belong to different clusters which could be merged.
#print("node ", node1, " is contained by cluster", cluster_containing_node1.nodes(), "while node ",node0, " is contained by cluster", cluster_containing_node0.nodes())
nodes_to_merge = set(list(cluster_containing_node0.nodes()) + list(cluster_containing_node1.nodes()))
selected_dist_array = filter_entries_containing_nodes(remaining_dist_array, nodes_to_merge)
entries_already_traversed = update_entry_already_traversed_list(entries_already_traversed,
selected_dist_array)
new_cluster = check_and_merge_cg(cluster_containing_node0, cluster_containing_node1,
selected_dist_array, merge_cluster_threshold)
if new_cluster is not None:
#print("merged cluster ", new_cluster.nodes(), " is created")
if cluster_containing_node0 in cg_list:
#print(cluster_containing_node0.nodes(), " is being removed!")
cg_list.remove(cluster_containing_node0)
#print("successfully removed!")
if cluster_containing_node1 in cg_list:
#print(cluster_containing_node1.nodes(), " is being removed!")
cg_list.remove(cluster_containing_node1)
#print("successfully removed!")
cg_list.append(new_cluster)
else:
pass
#print("Clusters not merged")
#print_cg_list(cg_list)
#print_cg_list(cg_list)
return cg_list
def update_entry_already_traversed_list(old_traversed_array, new_entry_array):
"""
Update dist_array by adding entries already traversed from new_entry_array while avoiding duplicates.
Could be avoided by using sets, have to figure out numpy arr vs set usage. The entries already traversed are
not traversed again.
:param old_traversed_array: an array containing entries already traversed
:param new_entry_array: entries to be appended to old_traversed_array (if not already present)
:return:
"""
"""
Keyword arguments:
cg_list: list of cluster grpahs
"""
#print(dist_array.shape, new_entry_array.shape)
entries_to_add = [entry for entry in new_entry_array if entry not in old_traversed_array]
if len(entries_to_add) > 0 :
if len(old_traversed_array) > 0:
return np.concatenate((old_traversed_array, entries_to_add), axis=0)
else:
return new_entry_array
else:
return old_traversed_array
def remove_indices(dist_array, indices):
"""
Remove given indices from dist_array
:param dist_array: a flattened version of the dist_matrix in the format of entries (node0/ window0, node1/ window1, distance),
usually sorted
:param indices: indices which should be removed
:return:
"""
selected_dist_array = [element for i, element in enumerate(dist_array) if i not in indices]
return np.asarray(selected_dist_array)
def prune_clusters(cg_list):
"""
ignore clusters which have high ( exceed mean + 3sd )average distance in comparison to other clusters
:param cg_list: a list of cluster graphs
:return: a list of clusters
"""
#print("Pruning clusters")
cg_avg_dist = {}
for cg in cg_list:
avg_dist = get_cg_avg_dist(cg)
#print("nodes: ", cg.nodes())
#print("avg. dist: ", avg_dist)
cg_avg_dist[cg] = avg_dist
sorted_avg_dist = list(cg_avg_dist.values())
sorted_avg_dist.sort()
#m = mean(cg_avg_dist)
#sd = stdev(cg_avg_dist)
remove_indexes = []
for i in range(0,len(sorted_avg_dist)):
if i>=3:
m = mean(sorted_avg_dist[0:i])
sd = stdev(sorted_avg_dist[0:i])
for j in range(i+1, len(sorted_avg_dist)):
j_dist = sorted_avg_dist[j]
if j_dist > (m + 3*sd) or j_dist< (m - 3*sd):
#print("cg avg dist ", j_dist, ", mean: ", m, ", sd:", sd)
remove_indexes.append(j)
selected_avg_dist = [item for i,item in enumerate(sorted_avg_dist) if i not in remove_indexes]
#print(remove_indexes)
#print(selected_avg_dist)
selected_clusters = [cg for cg in cg_avg_dist if cg_avg_dist[cg] in selected_avg_dist]
return selected_clusters
'''
def iterate(node_labels, dist_matrix, merge_thresholds, add_node_thresholds, prune = True): ## REDESIGN REQUIRED FOR PRUNING
"""
:param node_labels:
:param dist_matrix:
:param merge_thresholds:
:param add_node_thresholds:
:param prune:
:return:
"""
""" Iterate the cluster graph algorithm over a range of merge_thresholds and add_node_thresholds to show effect of the variation
Keyword arguments:
node_labels: numeric labels representing the windows
dist_matrix: a two dimensional matrix representing the distance between windows.
merge_thresholds: an array of merge_thresholds values
add_node_thresholds: an array of add_node_thresholds values
"""
cg_list_list = []
for m_threshold in merge_thresholds:
for a_threshold in add_node_thresholds:
cg_list = cluster_graph(node_labels, dist_matrix, merge_cluster_threshold=m_threshold,
add_node_threshold=a_threshold)
if prune:
prune_clusters(cg_list)
cg_list_list.append([m_threshold, a_threshold, cg_list])
#print([(entry[0], entry[1], len(entry[2])) for entry in cg_list_list])
return [entry[2] for entry in cg_list_list]
'''
'''
def add_node_to_cg(cg, entry, dist_array): # entry = [node1, node2, dist] dist_array = remaining dist_array not prev entries
cg.add_weighted_edges_from(entry[0],entry[1], entry[2])
append_edges_to_cg(dist_array, cg)
'''
|
[
"copy.deepcopy",
"numpy.asarray",
"statistics.stdev",
"networkx.Graph",
"statistics.mean",
"numpy.concatenate"
] |
[((432, 442), 'networkx.Graph', 'nx.Graph', ([], {}), '()\n', (440, 442), True, 'import networkx as nx\n'), ((1721, 1737), 'statistics.mean', 'mean', (['dist[:, 2]'], {}), '(dist[:, 2])\n', (1725, 1737), False, 'from statistics import mean, stdev\n'), ((2225, 2252), 'numpy.asarray', 'np.asarray', (['edge_dist_array'], {}), '(edge_dist_array)\n', (2235, 2252), True, 'import numpy as np\n'), ((2862, 2879), 'copy.deepcopy', 'copy.deepcopy', (['cg'], {}), '(cg)\n', (2875, 2879), False, 'import copy\n'), ((11688, 11758), 'numpy.asarray', 'np.asarray', (['[e for e in dist_array if e[0] in nodes and e[1] in nodes]'], {}), '([e for e in dist_array if e[0] in nodes and e[1] in nodes])\n', (11698, 11758), True, 'import numpy as np\n'), ((13747, 13778), 'numpy.asarray', 'np.asarray', (['selected_dist_array'], {}), '(selected_dist_array)\n', (13757, 13778), True, 'import numpy as np\n'), ((14342, 14359), 'numpy.asarray', 'np.asarray', (['edges'], {}), '(edges)\n', (14352, 14359), True, 'import numpy as np\n'), ((15378, 15409), 'numpy.asarray', 'np.asarray', (['selected_dist_array'], {}), '(selected_dist_array)\n', (15388, 15409), True, 'import numpy as np\n'), ((16600, 16614), 'numpy.asarray', 'np.asarray', (['[]'], {}), '([])\n', (16610, 16614), True, 'import numpy as np\n'), ((23221, 23252), 'numpy.asarray', 'np.asarray', (['selected_dist_array'], {}), '(selected_dist_array)\n', (23231, 23252), True, 'import numpy as np\n'), ((5542, 5569), 'statistics.mean', 'mean', (['edge_dist_array[:, 2]'], {}), '(edge_dist_array[:, 2])\n', (5546, 5569), False, 'from statistics import mean, stdev\n'), ((22634, 22695), 'numpy.concatenate', 'np.concatenate', (['(old_traversed_array, entries_to_add)'], {'axis': '(0)'}), '((old_traversed_array, entries_to_add), axis=0)\n', (22648, 22695), True, 'import numpy as np\n'), ((23943, 23969), 'statistics.mean', 'mean', (['sorted_avg_dist[0:i]'], {}), '(sorted_avg_dist[0:i])\n', (23947, 23969), False, 'from statistics import mean, stdev\n'), ((23987, 24014), 'statistics.stdev', 'stdev', (['sorted_avg_dist[0:i]'], {}), '(sorted_avg_dist[0:i])\n', (23992, 24014), False, 'from statistics import mean, stdev\n')]
|
# -*- coding: utf-8 -*-
"""
usage: change your own data dir and it works
"""
import numpy as np
import os
from collections import namedtuple
from PIL import Image
import cv2
import matplotlib.pylab as plt
import codecs
Img_dataset_dir = './intermediate_file/padding_images_to_detection/'
Label_dataset_dir = './intermediate_file/detect_result/txt/'
crop_dataset_dir_vert = './intermediate_file/images_to_recognition/'
Label_list = os.listdir(Label_dataset_dir)
for i in range(len(Label_list)):
count=1
image_name=Label_list[i].split('.txt')[0]
name=Label_list[i].split('_')[4]
with open(os.path.join(Label_dataset_dir,Label_list[i])) as f:
for line in f.readlines():
img=cv2.imdecode(np.fromfile(Img_dataset_dir+image_name,dtype=np.uint8),-1)
# img = cv2.imread(Img_dataset_dir+image_name)
coordinates = line.split(',')[0:8]
coord = namedtuple('coord', ['x1', 'y1', 'x2', 'y2', 'x3', 'y3', 'x4', 'y4'])
coordinate= coord(coordinates[0],coordinates[1],coordinates[2],coordinates[3],coordinates[4],coordinates[5],coordinates[6],coordinates[7])
X = list(map(float, [coordinate.x1, coordinate.x2, coordinate.x3, coordinate.x4]))
Y = list(map(float, [coordinate.y1, coordinate.y2, coordinate.y3, coordinate.y4]))
Xmin = min(X)
Xmax = max(X)
Ymin = min(Y)
Ymax = max(Y)
img_new = img[int(Ymin):int(Ymax), int(Xmin):int(Xmax)]
img_new = cv2.flip(img_new, 1)
img_new = cv2.transpose(img_new)
img_new = Image.fromarray(img_new)
names = str('img_calligraphy_'+str(name) + '_bg_'+str(count)+'.jpg')
count+=1
p = img_new.size[1] / 64
if p == 0:
continue
new_height = 64
new_width = int(img_new.size[0] / p)
if new_width>1300:
new_width=1300
new_1=img_new.resize((new_width, new_height))
try:
new_1.save(os.path.join(crop_dataset_dir_vert, names))
# f = codecs.open(os.path.join(crop_dataset_dir_vert, 'lable.txt'), 'a', encoding='utf-8')
# f.write(str(crop_dataset_dir_vert + names + ',' + line))
except:
continue
# f.close()
|
[
"numpy.fromfile",
"cv2.transpose",
"collections.namedtuple",
"PIL.Image.fromarray",
"cv2.flip",
"os.path.join",
"os.listdir"
] |
[((435, 464), 'os.listdir', 'os.listdir', (['Label_dataset_dir'], {}), '(Label_dataset_dir)\n', (445, 464), False, 'import os\n'), ((607, 653), 'os.path.join', 'os.path.join', (['Label_dataset_dir', 'Label_list[i]'], {}), '(Label_dataset_dir, Label_list[i])\n', (619, 653), False, 'import os\n'), ((910, 979), 'collections.namedtuple', 'namedtuple', (['"""coord"""', "['x1', 'y1', 'x2', 'y2', 'x3', 'y3', 'x4', 'y4']"], {}), "('coord', ['x1', 'y1', 'x2', 'y2', 'x3', 'y3', 'x4', 'y4'])\n", (920, 979), False, 'from collections import namedtuple\n'), ((1515, 1535), 'cv2.flip', 'cv2.flip', (['img_new', '(1)'], {}), '(img_new, 1)\n', (1523, 1535), False, 'import cv2\n'), ((1558, 1580), 'cv2.transpose', 'cv2.transpose', (['img_new'], {}), '(img_new)\n', (1571, 1580), False, 'import cv2\n'), ((1603, 1627), 'PIL.Image.fromarray', 'Image.fromarray', (['img_new'], {}), '(img_new)\n', (1618, 1627), False, 'from PIL import Image\n'), ((725, 782), 'numpy.fromfile', 'np.fromfile', (['(Img_dataset_dir + image_name)'], {'dtype': 'np.uint8'}), '(Img_dataset_dir + image_name, dtype=np.uint8)\n', (736, 782), True, 'import numpy as np\n'), ((2056, 2098), 'os.path.join', 'os.path.join', (['crop_dataset_dir_vert', 'names'], {}), '(crop_dataset_dir_vert, names)\n', (2068, 2098), False, 'import os\n')]
|
class Resampler:
def __init__(self, *args):
# Choose histogram size according to bin edges
# Take under/overflow into account for dependent variables only
edges = []
for arg in args[:-1]:
edges.append(np.append(np.append([-np.inf], arg), [np.inf]))
edges.append(args[-1])
self.edges = edges
self.histogram = np.zeros(map(lambda x: len(x) - 1, self.edges))
def learn(self, features, weights=None):
assert(len(features) == len(self.edges))
features = np.array(features)
h , _ = np.histogramdd(features.T, bins=self.edges, weights=weights)
self.histogram += h
def sample(self, features):
import numpy as np
assert(len(features) == len(self.edges) - 1)
args = np.array(features)
idx = [np.searchsorted(edges, vals) - 1 for edges, vals in zip(self.edges, args)]
tmp = self.histogram[idx]
# Fix negative bins (resulting from possible negative weights) to zero
tmp[tmp < 0] = 0
norm = np.sum(tmp, axis=1)
probs = tmp / norm[:,np.newaxis]
sampled_bin = []
for i in range(tmp.shape[0]):
sampled_bin.append(np.random.choice(tmp.shape[1], p=probs[i,:]))
sampled_bin = np.array(sampled_bin)
sampled_val = np.random.uniform(self.edges[-1][sampled_bin],
self.edges[-1][sampled_bin + 1],
size=len(sampled_bin))
# If the histogram is empty, we can't sample
sampled_val[norm == 0] = np.nan
return sampled_val
|
[
"numpy.sum",
"numpy.histogramdd",
"numpy.searchsorted",
"numpy.append",
"numpy.array",
"numpy.random.choice"
] |
[((545, 563), 'numpy.array', 'np.array', (['features'], {}), '(features)\n', (553, 563), True, 'import numpy as np\n'), ((581, 641), 'numpy.histogramdd', 'np.histogramdd', (['features.T'], {'bins': 'self.edges', 'weights': 'weights'}), '(features.T, bins=self.edges, weights=weights)\n', (595, 641), True, 'import numpy as np\n'), ((800, 818), 'numpy.array', 'np.array', (['features'], {}), '(features)\n', (808, 818), True, 'import numpy as np\n'), ((1065, 1084), 'numpy.sum', 'np.sum', (['tmp'], {'axis': '(1)'}), '(tmp, axis=1)\n', (1071, 1084), True, 'import numpy as np\n'), ((1289, 1310), 'numpy.array', 'np.array', (['sampled_bin'], {}), '(sampled_bin)\n', (1297, 1310), True, 'import numpy as np\n'), ((835, 863), 'numpy.searchsorted', 'np.searchsorted', (['edges', 'vals'], {}), '(edges, vals)\n', (850, 863), True, 'import numpy as np\n'), ((1221, 1266), 'numpy.random.choice', 'np.random.choice', (['tmp.shape[1]'], {'p': 'probs[i, :]'}), '(tmp.shape[1], p=probs[i, :])\n', (1237, 1266), True, 'import numpy as np\n'), ((260, 285), 'numpy.append', 'np.append', (['[-np.inf]', 'arg'], {}), '([-np.inf], arg)\n', (269, 285), True, 'import numpy as np\n')]
|
import numpy as np
EPSILON = 1E-10
def calc_contrast(brighter, darker, method='weber', mode='elementwise'):
"""
Contrast metric calculation. Now supports Weber and Michelson metric.
:param brighter: ndarray of the brighter RoI
:param darker: ndarray of the darker RoI
:param method: contrast metric: 'weber' | 'michelson'
:param mode: 'pairwise' | 'elementwise'. If pairwise, contrasts will
be calculated for all possible pixel-pairs from the brighter and
darker RoIs. If elementwise, contrasts will be calculated for
pairs from the sample pixel locations.
:return:
"""
if brighter.ndim > 1:
brighter = brighter.ravel()
if darker.ndim > 1:
darker = darker.ravel()
length_diff = brighter.size - darker.size
if length_diff < 0:
brighter = np.hstack([brighter, np.random.choice(brighter, size=length_diff)])
if length_diff > 0:
darker = np.hstack([darker, np.random.choice(darker, size=length_diff)])
# auto-broadcasting achieves better performance than for-loop
if mode == 'pairwise':
brighter = brighter[:, None]
darker = darker[None, :]
if method.lower() == 'weber':
contrast = brighter / (darker + EPSILON)
elif method.lower() == 'michelson':
contrast = (brighter - darker) / (brighter + darker + EPSILON)
else:
raise ValueError('{} is not a valid contrast metric.'.format(method))
return contrast.ravel() if mode == 'pairwise' else contrast
|
[
"numpy.random.choice"
] |
[((858, 902), 'numpy.random.choice', 'np.random.choice', (['brighter'], {'size': 'length_diff'}), '(brighter, size=length_diff)\n', (874, 902), True, 'import numpy as np\n'), ((965, 1007), 'numpy.random.choice', 'np.random.choice', (['darker'], {'size': 'length_diff'}), '(darker, size=length_diff)\n', (981, 1007), True, 'import numpy as np\n')]
|
# -*- coding: utf-8 -*-
"""
Created on Wed 01 Sept 2021
@author: <NAME>
CentraleSupelec
MICS laboratory
9 rue Juliot Curie, Gif-Sur-Yvette, 91190 France
Build the Multi-Layer Classifier netowrk.
"""
import torch
import torch.nn as nn
from collections import OrderedDict
from customics.tools import FullyConnectedLayer
from customics.loss import classification_loss
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn import metrics
from sklearn.metrics import roc_auc_score
from sklearn.preprocessing import OneHotEncoder
from torch.optim import Adam
class MultiClassifier(nn.Module):
"""
Defines a multi-layer fully-connected classifier
"""
def __init__(self, n_class=2, latent_dim=256, norm_layer=nn.BatchNorm1d, leaky_slope=0.2, dropout=0,
class_dim = [128, 64]):
"""
Construct a multi-layer fully-connected classifier
Parameters:
class_num (int) -- the number of class
latent_dim (int) -- the dimensionality of the latent space and the input layer of the classifier
norm_layer -- normalization layer
leaky_slope (float) -- the negative slope of the Leaky ReLU activation function
dropout_p (float) -- probability of an element to be zeroed in a dropout layer
layer_num (int) -- the layer number of the classifier, >=3
"""
super(MultiClassifier, self).__init__()
self.dt_layers = OrderedDict()
self.dt_layers['InputLayer'] = FullyConnectedLayer(latent_dim, class_dim[0], norm_layer=norm_layer, leaky_slope=leaky_slope, dropout=dropout,
activation=True)
block_layer_num = len(class_dim)
dropout_flag = True
for num in range(1, block_layer_num):
self.dt_layers['Layer{}'.format(num)] = FullyConnectedLayer(class_dim[num - 1], class_dim[num], norm_layer=norm_layer, leaky_slope=leaky_slope,
dropout=dropout_flag*dropout, activation=True)
# dropout for every other layer
dropout_flag = not dropout_flag
# the output fully-connected layer of the classifier
self.dt_layers['OutputLayer'] = FullyConnectedLayer(class_dim[-1], n_class, norm_layer=norm_layer, leaky_slope=leaky_slope, dropout=0,
activation=False, normalization=False)
self.net = nn.Sequential(self.dt_layers)
def forward(self, x):
y = self.net(x)
return y
def predict(self, x):
return torch.max(self.forward(x), dim=1).indices
def compile(self, lr):
self.optimizer = Adam(self.parameters(), lr=lr)
def fit(self, x_train, y_train, n_epochs, verbose=False):
self.train()
for epoch in range(n_epochs):
overall_loss = 0
loss = 0
self.optimizer.zero_grad()
y_pred = self.forward(x_train)
loss = classification_loss('CE', y_pred, y_train)
overall_loss += loss.item()
loss.backward()
self.optimizer.step()
if verbose:
print("\tEpoch", epoch + 1, "complete!", "\tAverage Loss: ", overall_loss)
def roc_auc_score_multiclass(y_true, y_pred, average = "macro"):
ohe = OneHotEncoder(sparse=False).fit(np.array(y_true).reshape(-1,1))
y_true, y_pred = ohe.transform(np.array(y_true).reshape(-1,1)), ohe.transform(np.array(y_pred).reshape(-1,1))
roc_auc = roc_auc_score(y_true, y_pred, average = average, multi_class='ovo')
return roc_auc
def multi_classification_evaluation(y_true, y_pred, average='weighted', save_confusion=False, filename=None, plot_roc=False):
accuracy = metrics.accuracy_score(y_true, y_pred)
precision = metrics.precision_score(y_true, y_pred, average=average)
recall = metrics.recall_score(y_true, y_pred, average = average)
f1_score = metrics.f1_score(y_true, y_pred, average = average)
auc = roc_auc_score_multiclass(y_true, y_pred, average = average)
dt_scores = {'Accuracy': accuracy,
'F1-score' : f1_score,
'Precision' : precision,
'Recall' : recall,
'AUC' : auc}
if save_confusion:
plt.figure(figsize = (18,8))
sns.heatmap(metrics.confusion_matrix(y_true, y_pred), annot = True, xticklabels = np.unique(y_true), yticklabels = np.unique(y_true), cmap = 'summer')
plt.xlabel('Predicted Labels')
plt.ylabel('True Labels')
plt.savefig(filename + '.png')
plt.clf()
return dt_scores
|
[
"sklearn.metrics.confusion_matrix",
"matplotlib.pyplot.savefig",
"customics.loss.classification_loss",
"torch.nn.Sequential",
"matplotlib.pyplot.clf",
"sklearn.metrics.accuracy_score",
"numpy.unique",
"sklearn.preprocessing.OneHotEncoder",
"sklearn.metrics.recall_score",
"sklearn.metrics.roc_auc_score",
"sklearn.metrics.f1_score",
"matplotlib.pyplot.figure",
"numpy.array",
"sklearn.metrics.precision_score",
"collections.OrderedDict",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"customics.tools.FullyConnectedLayer"
] |
[((3568, 3633), 'sklearn.metrics.roc_auc_score', 'roc_auc_score', (['y_true', 'y_pred'], {'average': 'average', 'multi_class': '"""ovo"""'}), "(y_true, y_pred, average=average, multi_class='ovo')\n", (3581, 3633), False, 'from sklearn.metrics import roc_auc_score\n'), ((3798, 3836), 'sklearn.metrics.accuracy_score', 'metrics.accuracy_score', (['y_true', 'y_pred'], {}), '(y_true, y_pred)\n', (3820, 3836), False, 'from sklearn import metrics\n'), ((3853, 3909), 'sklearn.metrics.precision_score', 'metrics.precision_score', (['y_true', 'y_pred'], {'average': 'average'}), '(y_true, y_pred, average=average)\n', (3876, 3909), False, 'from sklearn import metrics\n'), ((3923, 3976), 'sklearn.metrics.recall_score', 'metrics.recall_score', (['y_true', 'y_pred'], {'average': 'average'}), '(y_true, y_pred, average=average)\n', (3943, 3976), False, 'from sklearn import metrics\n'), ((3994, 4043), 'sklearn.metrics.f1_score', 'metrics.f1_score', (['y_true', 'y_pred'], {'average': 'average'}), '(y_true, y_pred, average=average)\n', (4010, 4043), False, 'from sklearn import metrics\n'), ((1536, 1549), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (1547, 1549), False, 'from collections import OrderedDict\n'), ((1590, 1721), 'customics.tools.FullyConnectedLayer', 'FullyConnectedLayer', (['latent_dim', 'class_dim[0]'], {'norm_layer': 'norm_layer', 'leaky_slope': 'leaky_slope', 'dropout': 'dropout', 'activation': '(True)'}), '(latent_dim, class_dim[0], norm_layer=norm_layer,\n leaky_slope=leaky_slope, dropout=dropout, activation=True)\n', (1609, 1721), False, 'from customics.tools import FullyConnectedLayer\n'), ((2295, 2440), 'customics.tools.FullyConnectedLayer', 'FullyConnectedLayer', (['class_dim[-1]', 'n_class'], {'norm_layer': 'norm_layer', 'leaky_slope': 'leaky_slope', 'dropout': '(0)', 'activation': '(False)', 'normalization': '(False)'}), '(class_dim[-1], n_class, norm_layer=norm_layer,\n leaky_slope=leaky_slope, dropout=0, activation=False, normalization=False)\n', (2314, 2440), False, 'from customics.tools import FullyConnectedLayer\n'), ((2490, 2519), 'torch.nn.Sequential', 'nn.Sequential', (['self.dt_layers'], {}), '(self.dt_layers)\n', (2503, 2519), True, 'import torch.nn as nn\n'), ((4332, 4359), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(18, 8)'}), '(figsize=(18, 8))\n', (4342, 4359), True, 'import matplotlib.pyplot as plt\n'), ((4528, 4558), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Predicted Labels"""'], {}), "('Predicted Labels')\n", (4538, 4558), True, 'import matplotlib.pyplot as plt\n'), ((4567, 4592), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""True Labels"""'], {}), "('True Labels')\n", (4577, 4592), True, 'import matplotlib.pyplot as plt\n'), ((4601, 4631), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(filename + '.png')"], {}), "(filename + '.png')\n", (4612, 4631), True, 'import matplotlib.pyplot as plt\n'), ((4640, 4649), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (4647, 4649), True, 'import matplotlib.pyplot as plt\n'), ((1918, 2079), 'customics.tools.FullyConnectedLayer', 'FullyConnectedLayer', (['class_dim[num - 1]', 'class_dim[num]'], {'norm_layer': 'norm_layer', 'leaky_slope': 'leaky_slope', 'dropout': '(dropout_flag * dropout)', 'activation': '(True)'}), '(class_dim[num - 1], class_dim[num], norm_layer=\n norm_layer, leaky_slope=leaky_slope, dropout=dropout_flag * dropout,\n activation=True)\n', (1937, 2079), False, 'from customics.tools import FullyConnectedLayer\n'), ((3029, 3071), 'customics.loss.classification_loss', 'classification_loss', (['"""CE"""', 'y_pred', 'y_train'], {}), "('CE', y_pred, y_train)\n", (3048, 3071), False, 'from customics.loss import classification_loss\n'), ((3375, 3402), 'sklearn.preprocessing.OneHotEncoder', 'OneHotEncoder', ([], {'sparse': '(False)'}), '(sparse=False)\n', (3388, 3402), False, 'from sklearn.preprocessing import OneHotEncoder\n'), ((4381, 4421), 'sklearn.metrics.confusion_matrix', 'metrics.confusion_matrix', (['y_true', 'y_pred'], {}), '(y_true, y_pred)\n', (4405, 4421), False, 'from sklearn import metrics\n'), ((3407, 3423), 'numpy.array', 'np.array', (['y_true'], {}), '(y_true)\n', (3415, 3423), True, 'import numpy as np\n'), ((4451, 4468), 'numpy.unique', 'np.unique', (['y_true'], {}), '(y_true)\n', (4460, 4468), True, 'import numpy as np\n'), ((4484, 4501), 'numpy.unique', 'np.unique', (['y_true'], {}), '(y_true)\n', (4493, 4501), True, 'import numpy as np\n'), ((3474, 3490), 'numpy.array', 'np.array', (['y_true'], {}), '(y_true)\n', (3482, 3490), True, 'import numpy as np\n'), ((3521, 3537), 'numpy.array', 'np.array', (['y_pred'], {}), '(y_pred)\n', (3529, 3537), True, 'import numpy as np\n')]
|
# a:截取72个算式
import sys,os
sys.path.append(os.path.dirname(__file__) + os.sep + '../')
import time
import numpy as np
import cv2
import config.config as config
from utils import get_perspective_transform
points = config.POS
# 600:900
# 4*18
# 150:50
def get_equation(img, num=0):
while num < 72: #18*4
pos_x = 150 * (num // 18)
pos_y = 50 * (num % 18)
img_equation = img[pos_y:pos_y+50, pos_x:pos_x+150, :]
num = num+1
yield img_equation
def main():
cap = cv2.VideoCapture(0)
ret,img = cap.read()
# 初始化
import json # 使用json存储摄像头矫正参数
file_name = '.\\config\\config.txt'
with open(file_name) as file_obj:
temp_d = json.load(file_obj) # 返回列表数据,也支持字典
mtx = np.array(temp_d['mtx'])
dist = np.array(temp_d['dist'])
# print("读取参数:", mtx, dist)
img = cv2.undistort(img, mtx, dist, None, mtx)
img = np.rot90(img)
img_perspective = get_perspective_transform(img, points)
while ret is True:
cv2.namedWindow('image')
cv2.imshow('image', img_perspective)
ret, img = cap.read()
img = cv2.undistort(img, mtx, dist, None, mtx)
img = np.rot90(img)
img_perspective = get_perspective_transform(img, points)
ch = cv2.waitKey(5)
if ch == ord('q') :
break
if ch == ord('s') :
print("save photo")
cv2.imwrite(r".\data" + '\\' + str(time.time())+'.jpg', img_perspective)
if ch == ord('a') :
print("get_equation")
for img_equation in get_equation(img_perspective):
cv2.imshow("eq", img_equation)
cv2.waitKey(0)
print("here")
cv2.imwrite(r".\data" + '\\' + str(time.time())+'.jpg', img_equation)
if __name__ == '__main__':
main()
|
[
"json.load",
"cv2.waitKey",
"os.path.dirname",
"utils.get_perspective_transform",
"time.time",
"cv2.VideoCapture",
"numpy.rot90",
"numpy.array",
"cv2.imshow",
"cv2.namedWindow",
"cv2.undistort"
] |
[((511, 530), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (527, 530), False, 'import cv2\n'), ((743, 766), 'numpy.array', 'np.array', (["temp_d['mtx']"], {}), "(temp_d['mtx'])\n", (751, 766), True, 'import numpy as np\n'), ((781, 805), 'numpy.array', 'np.array', (["temp_d['dist']"], {}), "(temp_d['dist'])\n", (789, 805), True, 'import numpy as np\n'), ((853, 893), 'cv2.undistort', 'cv2.undistort', (['img', 'mtx', 'dist', 'None', 'mtx'], {}), '(img, mtx, dist, None, mtx)\n', (866, 893), False, 'import cv2\n'), ((904, 917), 'numpy.rot90', 'np.rot90', (['img'], {}), '(img)\n', (912, 917), True, 'import numpy as np\n'), ((940, 978), 'utils.get_perspective_transform', 'get_perspective_transform', (['img', 'points'], {}), '(img, points)\n', (965, 978), False, 'from utils import get_perspective_transform\n'), ((697, 716), 'json.load', 'json.load', (['file_obj'], {}), '(file_obj)\n', (706, 716), False, 'import json\n'), ((1021, 1045), 'cv2.namedWindow', 'cv2.namedWindow', (['"""image"""'], {}), "('image')\n", (1036, 1045), False, 'import cv2\n'), ((1054, 1090), 'cv2.imshow', 'cv2.imshow', (['"""image"""', 'img_perspective'], {}), "('image', img_perspective)\n", (1064, 1090), False, 'import cv2\n'), ((1135, 1175), 'cv2.undistort', 'cv2.undistort', (['img', 'mtx', 'dist', 'None', 'mtx'], {}), '(img, mtx, dist, None, mtx)\n', (1148, 1175), False, 'import cv2\n'), ((1190, 1203), 'numpy.rot90', 'np.rot90', (['img'], {}), '(img)\n', (1198, 1203), True, 'import numpy as np\n'), ((1230, 1268), 'utils.get_perspective_transform', 'get_perspective_transform', (['img', 'points'], {}), '(img, points)\n', (1255, 1268), False, 'from utils import get_perspective_transform\n'), ((1291, 1305), 'cv2.waitKey', 'cv2.waitKey', (['(5)'], {}), '(5)\n', (1302, 1305), False, 'import cv2\n'), ((42, 67), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (57, 67), False, 'import sys, os\n'), ((1638, 1668), 'cv2.imshow', 'cv2.imshow', (['"""eq"""', 'img_equation'], {}), "('eq', img_equation)\n", (1648, 1668), False, 'import cv2\n'), ((1685, 1699), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (1696, 1699), False, 'import cv2\n'), ((1459, 1470), 'time.time', 'time.time', ([], {}), '()\n', (1468, 1470), False, 'import time\n'), ((1781, 1792), 'time.time', 'time.time', ([], {}), '()\n', (1790, 1792), False, 'import time\n')]
|
# An attempt to replicate http://www.nature.com/nature/journal/v518/n7540/full/nature14236.html
# (You can download it from Scihub)
from __future__ import print_function, division
import tensorflow as tf
import numpy as np
import gym
from collections import namedtuple
import random
import os
import h5py
from itertools import cycle
FRAMES_PER_STATE = 4
FRAME_WIDTH = 84
FRAME_HEIGHT = 110
RAW_FRAME_WIDTH = 160
RAW_FRAME_HEIGHT = 210
def reduce_stdev(t):
return tf.nn.moments(t, axes=[0])[1]
def explained_variance(t, p):
return 1 - reduce_stdev(t - p) / reduce_stdev(t)
def weight_variable(*shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
def bias_variable(*shape):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)
def ident_none(f):
return (lambda x: x) if f is None else f
def lrelu(t):
return tf.maximum(t, 0.01 * t)
def conv_layer(x, window, out_channels, stride, vlist, nonlin = lrelu):
nonlin = ident_none(nonlin)
in_channels = x.get_shape()[3].value
W_conv = weight_variable(window, window, in_channels, out_channels)
b_conv = bias_variable(out_channels)
vlist.append(W_conv)
vlist.append(b_conv)
return nonlin(
tf.nn.conv2d(x, W_conv, strides=[1, stride, stride, 1], padding='SAME') + b_conv)
def fcl(x, size, vlist, nonlin = lrelu):
nonlin = ident_none(nonlin)
W = weight_variable(x.get_shape()[1].value, size)
b = bias_variable(size)
vlist.append(W)
vlist.append(b)
return nonlin(tf.matmul(x, W) + b)
QNetwork = namedtuple('QNetwork', 'frames qvals vlist')
Transition = namedtuple('Transition', 'begin action reward terminal end')
def count_dead(name, t):
zero = tf.less_equal(t, 0)
all_zero = tf.reduce_all(zero, 0)
zero_as_ones = tf.cast(all_zero, tf.float32)
tf.scalar_summary('%s_dead' % name, tf.reduce_sum(zero_as_ones))
def make_Qnetwork(num_outputs, count_dead_summaries=False):
vlist = []
inputs = tf.placeholder(tf.float32, [None, FRAME_HEIGHT, FRAME_WIDTH, FRAMES_PER_STATE])
scaled_inputs = inputs / 256.0
h_conv1 = conv_layer(scaled_inputs, 8, 32, 4, vlist)
h_conv2 = conv_layer(h_conv1, 4, 64, 2, vlist)
h_conv3 = conv_layer(h_conv2, 3, 64, 1, vlist)
h_conv3_flat = tf.contrib.layers.flatten(h_conv3)
h_fc = fcl(h_conv3_flat, 512, vlist)
Q_vars = fcl(h_fc, num_outputs, vlist, nonlin=None)
Q_est = fcl(h_fc, 1, vlist, nonlin=None)
max_var = tf.reduce_max(Q_vars, reduction_indices=1)
Q_vals = Q_vars + Q_est - max_var
if count_dead_summaries:
count_dead('conv1', h_conv1)
count_dead('conv2', h_conv2)
count_dead('conv3', h_conv3)
count_dead('fc', h_fc)
return QNetwork(inputs, Q_vals, vlist)
class QNetworkPair(object):
def __init__(self, session, discount_rate, num_outputs, global_step):
self.session = session
self.global_step = global_step
target_network = make_Qnetwork(num_outputs)
training_network = make_Qnetwork(num_outputs, count_dead_summaries=True)
copy_ops = [target_var.assign(train_var) for target_var, train_var in
zip(target_network.vlist, training_network.vlist)]
self.copy_op = tf.group(*copy_ops)
self.start_frames = training_network.frames
# Used to choose actions during roll-outs
self.best_action = tf.argmax(training_network.qvals, dimension=1)
self.terminal = tf.placeholder(tf.bool, [None])
not_terminal = tf.logical_not(self.terminal)
reward_mask = tf.cast(not_terminal, tf.float32)
max_Q = tf.reduce_max(target_network.qvals, reduction_indices=1)
self.end_frames = target_network.frames
self.rewards = tf.placeholder(tf.float32, [None])
# Terminate expected value sequence if game ended.
estimated_Qs = max_Q * discount_rate * reward_mask + self.rewards
tf.scalar_summary('average_Q', tf.reduce_mean(estimated_Qs))
self.actions_chosen = tf.placeholder(tf.uint8, [None])
# This is ugly
actions_hot = tf.one_hot(self.actions_chosen, num_outputs)
Qs_taken = tf.reduce_sum(training_network.qvals * actions_hot,
reduction_indices=1)
# Do not train the target network!
Q_error = Qs_taken - tf.stop_gradient(estimated_Qs)
squared_error = tf.square(Q_error)
tf.scalar_summary('explained_variance', explained_variance(estimated_Qs, Qs_taken))
# Error clipping
loss = tf.reduce_sum(tf.sqrt(tf.square(Q_error) + 1))
tf.scalar_summary('loss', tf.reduce_mean(squared_error))
self.opt = tf.train.RMSPropOptimizer(0.00025, momentum=0.95, epsilon=0.01).minimize(
loss, global_step=global_step)
self.summaries = tf.merge_all_summaries()
def choose_actions(self, states):
return self.session.run(self.best_action, {self.start_frames: states})
def train(self, starts, actions, rewards, terminals, ends):
_, summaries, step = self.session.run(
[self.opt, self.summaries, self.global_step],
{self.start_frames: starts,
self.actions_chosen: actions,
self.rewards: rewards,
self.terminal: terminals,
self.end_frames: ends})
return summaries, step
def update_targets(self):
self.session.run(self.copy_op)
class TransitionTable(object):
def __init__(self, f, prefix, size):
self.logical_size = size
self.physical_size = size + 1
self.starts_var = f.require_dataset('%s_starts' % prefix, (self.physical_size, FRAME_HEIGHT, FRAME_WIDTH, 4), dtype=np.uint8)
self.starts = np.array(self.starts_var, dtype=np.uint8)
self.actions_var = f.require_dataset('%s_actions' % prefix, (self.physical_size,), dtype=np.uint8)
self.actions = np.array(self.actions_var, dtype=np.uint8)
self.rewards_var = f.require_dataset('%s_rewards' % prefix, (self.physical_size,), dtype=np.int8)
self.rewards = np.array(self.rewards_var, dtype=np.int8)
self.terminal_var = f.require_dataset('%s_terminal' % prefix,
(self.physical_size,), dtype=np.bool8)
self.terminal = np.array(self.terminal_var, dtype=np.bool8)
self.write_ind_var = f.require_dataset('%s_write_ind' % prefix, (1,),
dtype=np.uint32)
self.full_var = f.require_dataset('%s_full' % prefix, (1,),
dtype=np.bool)
self.write_ind = self.write_ind_var[0]
self.full = self.full_var[0]
def save(self):
self.starts_var[:,:,:,:] = self.starts
self.actions_var[:] = self.actions
self.rewards_var[:] = self.rewards
self.terminal_var[:] = self.terminal
self.write_ind_var[0] = self.write_ind
self.full_var[0] = self.full
def count(self):
if self.full:
return self.logical_size
else:
return max(self.write_ind - 1, 0)
def insert(self, start, action, reward, terminal):
self.starts[self.write_ind] = start
self.actions[self.write_ind] = action
self.rewards[self.write_ind] = reward
self.terminal[self.write_ind] = terminal
self.write_ind += 1
if self.write_ind == self.physical_size:
self.full = True
self.write_ind = 0
def ignored_index(self):
return (self.write_ind - 1) % self.physical_size
def sample(self, n):
selections = np.random.choice(self.count(), min(n, self.count()), replace=False)
shifted_selections = [((i+1) % self.physical_size) if i >= self.ignored_index() else i for i in selections]
end_selections = [(i+1) % self.physical_size for i in shifted_selections]
return Transition(
self.starts[shifted_selections],
self.actions[shifted_selections],
self.rewards[shifted_selections],
self.terminal[shifted_selections],
self.starts[end_selections])
blank_frames = [np.empty([RAW_FRAME_HEIGHT, RAW_FRAME_WIDTH, 3], dtype=np.uint8)
for i in range(FRAMES_PER_STATE - 1)]
for b in blank_frames:
b.fill(0)
def reset_env(env):
return blank_frames + [env.reset()]
class Stepper(object):
def __init__(self, game, frames_same, table=None):
self.env = gym.make(game)
# ARGH
self.env.frameskip = 1
self.frames = reset_env(self.env)
self.frames_same = frames_same
self.transition_table = table
def step(self, action=None, render=False):
if action is None:
action = self.env.action_space.sample()
old_state = self.last_state
total_reward = 0
done = False
for i in range(self.frames_same):
frame, reward, done, info = self.env.step(action)
if render:
self.env.render()
total_reward += np.sign(reward)
if done:
break
self.frames.append(frame)
if done:
self.frames = reset_env(self.env)
else:
self.frames[:-FRAMES_PER_STATE] = []
if self.transition_table is not None:
self.transition_table.insert(old_state, action, total_reward, done)
class TrainingEnvironment(object):
saves_dir = 'saves'
epsilon_floor = .1
epsilon_drop_over = 1024 * 1024
epsilon = 1
num_steppers = 16
study_repeats = 8
transitions_to_keep = 1024 * 1024
frames_same = 4
train_every = 32
frames_start = 50 * 1024
update_target_every = 10 * 1024
total_training_steps = 10 * 1024 * 1024
def __init__(self, game, save_name, swap_path, **kwargs):
# you can set arbitrary hyperparameters
for k, v in kwargs.items():
if getattr(self, k, None) is None:
raise ValueError('undefined param %s' % k)
setattr(self, k, v)
self.frames_per_training = self.train_every * self.num_steppers
self.swap_file = h5py.File('%s/%s' % (swap_path, save_name))
self.tables = [TransitionTable(
self.swap_file, '%d_' % i, self.transitions_to_keep // self.num_steppers)
for i in range(self.num_steppers)]
self.steppers = [Stepper(game, self.frames_same, t) for t in self.tables]
num_outputs = self.steppers[0].env.action_space.n
self.session = tf.Session()
with self.session:
global_step = tf.Variable(0, name='global_step', trainable=False)
discount_rate = tf.minimum(0.96, 1.0 -
tf.train.exponential_decay(1.0,
global_step, 2 * 1024 * 1024 // self.frames_per_training, 0.04))
tf.scalar_summary('discount_rate', discount_rate)
self.qnetwork = QNetworkPair(self.session, discount_rate, num_outputs,
global_step)
self.make_resize_graph()
self.resize_stepper_states()
self.summary_writer = tf.train.SummaryWriter(
'%s/%s_summaries' % (self.saves_dir, save_name))
self.saver = tf.train.Saver()
self.save_path = '%s/%s.ckpt' % (self.saves_dir, save_name)
self.stop_file = '%s/%s.stop' % (self.saves_dir, save_name)
self.save_file = '%s/%s.save' % (self.saves_dir, save_name)
if os.path.isfile(self.save_path):
self.saver.restore(self.session, self.save_path)
else:
self.session.run(tf.initialize_all_variables())
self.qnetwork.update_targets()
self.frames_seen = 0
def make_resize_graph(self):
self.images_raw = tf.placeholder(tf.uint8,
[self.num_steppers, FRAMES_PER_STATE,
RAW_FRAME_HEIGHT, RAW_FRAME_WIDTH, 3])
images_gray = tf.image.rgb_to_grayscale(self.images_raw)
images_flatter = tf.reshape(images_gray, [self.num_steppers * FRAMES_PER_STATE,
RAW_FRAME_HEIGHT, RAW_FRAME_WIDTH, 1])
images_small = tf.image.resize_images(images_flatter,
[FRAME_HEIGHT, FRAME_WIDTH])
images_cast = tf.cast(images_small, tf.uint8)
small_image_sets = tf.reshape(images_cast,
[self.num_steppers, FRAMES_PER_STATE, FRAME_HEIGHT, FRAME_WIDTH])
self.states_ret = tf.transpose(small_image_sets, [0, 2, 3, 1])
def resize_stepper_states(self):
big_images = [s.frames for s in self.steppers]
new_states = self.session.run(self.states_ret,
{self.images_raw: big_images})
for stepper, state in zip(self.steppers, new_states):
stepper.last_state = state
def sample_transitions(self):
samples = [table.sample(self.study_repeats * self.train_every) for table in self.tables if
table.count() > 0]
return Transition(*[np.concatenate(arrays) for arrays in zip(*samples)])
def train(self):
# begin, action, reward, end
transitions = self.sample_transitions()
summaries, step = self.qnetwork.train(*transitions)
frames_seen = step * self.frames_per_training
self.summary_writer.add_summary(summaries, frames_seen)
# Do some occasional stuff. Do it here because we know what step it is
epsilon_rate = (1 - self.epsilon_floor) / self.epsilon_drop_over
self.epsilon = max(1 - frames_seen * epsilon_rate, self.epsilon_floor)
if step % (self.update_target_every // self.frames_per_training) == 0:
self.qnetwork.update_targets()
if step % 10000 == 0:
self.save()
self.frames_seen = frames_seen
def save(self):
self.saver.save(self.session, self.save_path)
def save_tables(self):
for t in self.tables:
t.save()
def step(self):
paired_steppers = [(random.random(), s) for s in self.steppers]
rand_steppers = [s for r, s in paired_steppers if r < self.epsilon]
determ_steppers = [s for r, s in paired_steppers if r >= self.epsilon]
for s in rand_steppers:
s.step()
if determ_steppers:
states = [s.last_state for s in determ_steppers]
actions = self.qnetwork.choose_actions(states)
for s, a in zip(determ_steppers, actions):
s.step(a)
self.resize_stepper_states()
def run(self):
total_saved = sum(t.count() for t in self.tables)
saved_remaining = self.frames_start - total_saved
for i, s in zip(range(saved_remaining), cycle(self.steppers)):
s.step()
print('stores primed')
while self.frames_seen < self.total_training_steps:
for i in range(self.train_every):
self.step()
if os.path.exists(self.stop_file):
os.remove(self.stop_file)
break
self.train()
if os.path.exists(self.save_file):
os.remove(self.save_file)
self.saver.save(self.session, self.save_path)
|
[
"tensorflow.scalar_summary",
"os.remove",
"tensorflow.reduce_sum",
"tensorflow.image.rgb_to_grayscale",
"tensorflow.maximum",
"tensorflow.contrib.layers.flatten",
"numpy.empty",
"tensorflow.reduce_all",
"tensorflow.merge_all_summaries",
"tensorflow.reshape",
"tensorflow.train.RMSPropOptimizer",
"tensorflow.matmul",
"os.path.isfile",
"tensorflow.Variable",
"tensorflow.nn.conv2d",
"itertools.cycle",
"tensorflow.reduce_max",
"tensorflow.truncated_normal",
"tensorflow.one_hot",
"tensorflow.nn.moments",
"os.path.exists",
"tensorflow.less_equal",
"tensorflow.cast",
"tensorflow.placeholder",
"tensorflow.initialize_all_variables",
"tensorflow.image.resize_images",
"h5py.File",
"tensorflow.train.Saver",
"tensorflow.stop_gradient",
"tensorflow.Session",
"tensorflow.reduce_mean",
"tensorflow.constant",
"tensorflow.transpose",
"random.random",
"tensorflow.group",
"tensorflow.train.exponential_decay",
"numpy.concatenate",
"gym.make",
"tensorflow.argmax",
"tensorflow.train.SummaryWriter",
"numpy.sign",
"tensorflow.logical_not",
"numpy.array",
"collections.namedtuple",
"tensorflow.square"
] |
[((1587, 1631), 'collections.namedtuple', 'namedtuple', (['"""QNetwork"""', '"""frames qvals vlist"""'], {}), "('QNetwork', 'frames qvals vlist')\n", (1597, 1631), False, 'from collections import namedtuple\n'), ((1645, 1705), 'collections.namedtuple', 'namedtuple', (['"""Transition"""', '"""begin action reward terminal end"""'], {}), "('Transition', 'begin action reward terminal end')\n", (1655, 1705), False, 'from collections import namedtuple\n'), ((628, 666), 'tensorflow.truncated_normal', 'tf.truncated_normal', (['shape'], {'stddev': '(0.1)'}), '(shape, stddev=0.1)\n', (647, 666), True, 'import tensorflow as tf\n'), ((678, 698), 'tensorflow.Variable', 'tf.Variable', (['initial'], {}), '(initial)\n', (689, 698), True, 'import tensorflow as tf\n'), ((741, 770), 'tensorflow.constant', 'tf.constant', (['(0.1)'], {'shape': 'shape'}), '(0.1, shape=shape)\n', (752, 770), True, 'import tensorflow as tf\n'), ((782, 802), 'tensorflow.Variable', 'tf.Variable', (['initial'], {}), '(initial)\n', (793, 802), True, 'import tensorflow as tf\n'), ((894, 917), 'tensorflow.maximum', 'tf.maximum', (['t', '(0.01 * t)'], {}), '(t, 0.01 * t)\n', (904, 917), True, 'import tensorflow as tf\n'), ((1743, 1762), 'tensorflow.less_equal', 'tf.less_equal', (['t', '(0)'], {}), '(t, 0)\n', (1756, 1762), True, 'import tensorflow as tf\n'), ((1778, 1800), 'tensorflow.reduce_all', 'tf.reduce_all', (['zero', '(0)'], {}), '(zero, 0)\n', (1791, 1800), True, 'import tensorflow as tf\n'), ((1820, 1849), 'tensorflow.cast', 'tf.cast', (['all_zero', 'tf.float32'], {}), '(all_zero, tf.float32)\n', (1827, 1849), True, 'import tensorflow as tf\n'), ((2008, 2087), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, FRAME_HEIGHT, FRAME_WIDTH, FRAMES_PER_STATE]'], {}), '(tf.float32, [None, FRAME_HEIGHT, FRAME_WIDTH, FRAMES_PER_STATE])\n', (2022, 2087), True, 'import tensorflow as tf\n'), ((2301, 2335), 'tensorflow.contrib.layers.flatten', 'tf.contrib.layers.flatten', (['h_conv3'], {}), '(h_conv3)\n', (2326, 2335), True, 'import tensorflow as tf\n'), ((2493, 2535), 'tensorflow.reduce_max', 'tf.reduce_max', (['Q_vars'], {'reduction_indices': '(1)'}), '(Q_vars, reduction_indices=1)\n', (2506, 2535), True, 'import tensorflow as tf\n'), ((8128, 8192), 'numpy.empty', 'np.empty', (['[RAW_FRAME_HEIGHT, RAW_FRAME_WIDTH, 3]'], {'dtype': 'np.uint8'}), '([RAW_FRAME_HEIGHT, RAW_FRAME_WIDTH, 3], dtype=np.uint8)\n', (8136, 8192), True, 'import numpy as np\n'), ((470, 496), 'tensorflow.nn.moments', 'tf.nn.moments', (['t'], {'axes': '[0]'}), '(t, axes=[0])\n', (483, 496), True, 'import tensorflow as tf\n'), ((1890, 1917), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['zero_as_ones'], {}), '(zero_as_ones)\n', (1903, 1917), True, 'import tensorflow as tf\n'), ((3266, 3285), 'tensorflow.group', 'tf.group', (['*copy_ops'], {}), '(*copy_ops)\n', (3274, 3285), True, 'import tensorflow as tf\n'), ((3417, 3463), 'tensorflow.argmax', 'tf.argmax', (['training_network.qvals'], {'dimension': '(1)'}), '(training_network.qvals, dimension=1)\n', (3426, 3463), True, 'import tensorflow as tf\n'), ((3489, 3520), 'tensorflow.placeholder', 'tf.placeholder', (['tf.bool', '[None]'], {}), '(tf.bool, [None])\n', (3503, 3520), True, 'import tensorflow as tf\n'), ((3544, 3573), 'tensorflow.logical_not', 'tf.logical_not', (['self.terminal'], {}), '(self.terminal)\n', (3558, 3573), True, 'import tensorflow as tf\n'), ((3596, 3629), 'tensorflow.cast', 'tf.cast', (['not_terminal', 'tf.float32'], {}), '(not_terminal, tf.float32)\n', (3603, 3629), True, 'import tensorflow as tf\n'), ((3646, 3702), 'tensorflow.reduce_max', 'tf.reduce_max', (['target_network.qvals'], {'reduction_indices': '(1)'}), '(target_network.qvals, reduction_indices=1)\n', (3659, 3702), True, 'import tensorflow as tf\n'), ((3774, 3808), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None]'], {}), '(tf.float32, [None])\n', (3788, 3808), True, 'import tensorflow as tf\n'), ((4043, 4075), 'tensorflow.placeholder', 'tf.placeholder', (['tf.uint8', '[None]'], {}), '(tf.uint8, [None])\n', (4057, 4075), True, 'import tensorflow as tf\n'), ((4122, 4166), 'tensorflow.one_hot', 'tf.one_hot', (['self.actions_chosen', 'num_outputs'], {}), '(self.actions_chosen, num_outputs)\n', (4132, 4166), True, 'import tensorflow as tf\n'), ((4186, 4258), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(training_network.qvals * actions_hot)'], {'reduction_indices': '(1)'}), '(training_network.qvals * actions_hot, reduction_indices=1)\n', (4199, 4258), True, 'import tensorflow as tf\n'), ((4403, 4421), 'tensorflow.square', 'tf.square', (['Q_error'], {}), '(Q_error)\n', (4412, 4421), True, 'import tensorflow as tf\n'), ((4832, 4856), 'tensorflow.merge_all_summaries', 'tf.merge_all_summaries', ([], {}), '()\n', (4854, 4856), True, 'import tensorflow as tf\n'), ((5767, 5808), 'numpy.array', 'np.array', (['self.starts_var'], {'dtype': 'np.uint8'}), '(self.starts_var, dtype=np.uint8)\n', (5775, 5808), True, 'import numpy as np\n'), ((5939, 5981), 'numpy.array', 'np.array', (['self.actions_var'], {'dtype': 'np.uint8'}), '(self.actions_var, dtype=np.uint8)\n', (5947, 5981), True, 'import numpy as np\n'), ((6111, 6152), 'numpy.array', 'np.array', (['self.rewards_var'], {'dtype': 'np.int8'}), '(self.rewards_var, dtype=np.int8)\n', (6119, 6152), True, 'import numpy as np\n'), ((6298, 6341), 'numpy.array', 'np.array', (['self.terminal_var'], {'dtype': 'np.bool8'}), '(self.terminal_var, dtype=np.bool8)\n', (6306, 6341), True, 'import numpy as np\n'), ((8444, 8458), 'gym.make', 'gym.make', (['game'], {}), '(game)\n', (8452, 8458), False, 'import gym\n'), ((10122, 10165), 'h5py.File', 'h5py.File', (["('%s/%s' % (swap_path, save_name))"], {}), "('%s/%s' % (swap_path, save_name))\n", (10131, 10165), False, 'import h5py\n'), ((10502, 10514), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (10512, 10514), True, 'import tensorflow as tf\n'), ((11086, 11157), 'tensorflow.train.SummaryWriter', 'tf.train.SummaryWriter', (["('%s/%s_summaries' % (self.saves_dir, save_name))"], {}), "('%s/%s_summaries' % (self.saves_dir, save_name))\n", (11108, 11157), True, 'import tensorflow as tf\n'), ((11196, 11212), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (11210, 11212), True, 'import tensorflow as tf\n'), ((11428, 11458), 'os.path.isfile', 'os.path.isfile', (['self.save_path'], {}), '(self.save_path)\n', (11442, 11458), False, 'import os\n'), ((11727, 11832), 'tensorflow.placeholder', 'tf.placeholder', (['tf.uint8', '[self.num_steppers, FRAMES_PER_STATE, RAW_FRAME_HEIGHT, RAW_FRAME_WIDTH, 3]'], {}), '(tf.uint8, [self.num_steppers, FRAMES_PER_STATE,\n RAW_FRAME_HEIGHT, RAW_FRAME_WIDTH, 3])\n', (11741, 11832), True, 'import tensorflow as tf\n'), ((11884, 11926), 'tensorflow.image.rgb_to_grayscale', 'tf.image.rgb_to_grayscale', (['self.images_raw'], {}), '(self.images_raw)\n', (11909, 11926), True, 'import tensorflow as tf\n'), ((11952, 12057), 'tensorflow.reshape', 'tf.reshape', (['images_gray', '[self.num_steppers * FRAMES_PER_STATE, RAW_FRAME_HEIGHT, RAW_FRAME_WIDTH, 1]'], {}), '(images_gray, [self.num_steppers * FRAMES_PER_STATE,\n RAW_FRAME_HEIGHT, RAW_FRAME_WIDTH, 1])\n', (11962, 12057), True, 'import tensorflow as tf\n'), ((12089, 12156), 'tensorflow.image.resize_images', 'tf.image.resize_images', (['images_flatter', '[FRAME_HEIGHT, FRAME_WIDTH]'], {}), '(images_flatter, [FRAME_HEIGHT, FRAME_WIDTH])\n', (12111, 12156), True, 'import tensorflow as tf\n'), ((12195, 12226), 'tensorflow.cast', 'tf.cast', (['images_small', 'tf.uint8'], {}), '(images_small, tf.uint8)\n', (12202, 12226), True, 'import tensorflow as tf\n'), ((12254, 12347), 'tensorflow.reshape', 'tf.reshape', (['images_cast', '[self.num_steppers, FRAMES_PER_STATE, FRAME_HEIGHT, FRAME_WIDTH]'], {}), '(images_cast, [self.num_steppers, FRAMES_PER_STATE, FRAME_HEIGHT,\n FRAME_WIDTH])\n', (12264, 12347), True, 'import tensorflow as tf\n'), ((12386, 12430), 'tensorflow.transpose', 'tf.transpose', (['small_image_sets', '[0, 2, 3, 1]'], {}), '(small_image_sets, [0, 2, 3, 1])\n', (12398, 12430), True, 'import tensorflow as tf\n'), ((1258, 1329), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (['x', 'W_conv'], {'strides': '[1, stride, stride, 1]', 'padding': '"""SAME"""'}), "(x, W_conv, strides=[1, stride, stride, 1], padding='SAME')\n", (1270, 1329), True, 'import tensorflow as tf\n'), ((1554, 1569), 'tensorflow.matmul', 'tf.matmul', (['x', 'W'], {}), '(x, W)\n', (1563, 1569), True, 'import tensorflow as tf\n'), ((3982, 4010), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['estimated_Qs'], {}), '(estimated_Qs)\n', (3996, 4010), True, 'import tensorflow as tf\n'), ((4348, 4378), 'tensorflow.stop_gradient', 'tf.stop_gradient', (['estimated_Qs'], {}), '(estimated_Qs)\n', (4364, 4378), True, 'import tensorflow as tf\n'), ((4635, 4664), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['squared_error'], {}), '(squared_error)\n', (4649, 4664), True, 'import tensorflow as tf\n'), ((9022, 9037), 'numpy.sign', 'np.sign', (['reward'], {}), '(reward)\n', (9029, 9037), True, 'import numpy as np\n'), ((10568, 10619), 'tensorflow.Variable', 'tf.Variable', (['(0)'], {'name': '"""global_step"""', 'trainable': '(False)'}), "(0, name='global_step', trainable=False)\n", (10579, 10619), True, 'import tensorflow as tf\n'), ((10816, 10865), 'tensorflow.scalar_summary', 'tf.scalar_summary', (['"""discount_rate"""', 'discount_rate'], {}), "('discount_rate', discount_rate)\n", (10833, 10865), True, 'import tensorflow as tf\n'), ((14613, 14633), 'itertools.cycle', 'cycle', (['self.steppers'], {}), '(self.steppers)\n', (14618, 14633), False, 'from itertools import cycle\n'), ((14837, 14867), 'os.path.exists', 'os.path.exists', (['self.stop_file'], {}), '(self.stop_file)\n', (14851, 14867), False, 'import os\n'), ((14973, 15003), 'os.path.exists', 'os.path.exists', (['self.save_file'], {}), '(self.save_file)\n', (14987, 15003), False, 'import os\n'), ((4685, 4748), 'tensorflow.train.RMSPropOptimizer', 'tf.train.RMSPropOptimizer', (['(0.00025)'], {'momentum': '(0.95)', 'epsilon': '(0.01)'}), '(0.00025, momentum=0.95, epsilon=0.01)\n', (4710, 4748), True, 'import tensorflow as tf\n'), ((11564, 11593), 'tensorflow.initialize_all_variables', 'tf.initialize_all_variables', ([], {}), '()\n', (11591, 11593), True, 'import tensorflow as tf\n'), ((13911, 13926), 'random.random', 'random.random', ([], {}), '()\n', (13924, 13926), False, 'import random\n'), ((14885, 14910), 'os.remove', 'os.remove', (['self.stop_file'], {}), '(self.stop_file)\n', (14894, 14910), False, 'import os\n'), ((15021, 15046), 'os.remove', 'os.remove', (['self.save_file'], {}), '(self.save_file)\n', (15030, 15046), False, 'import os\n'), ((4576, 4594), 'tensorflow.square', 'tf.square', (['Q_error'], {}), '(Q_error)\n', (4585, 4594), True, 'import tensorflow as tf\n'), ((10691, 10791), 'tensorflow.train.exponential_decay', 'tf.train.exponential_decay', (['(1.0)', 'global_step', '(2 * 1024 * 1024 // self.frames_per_training)', '(0.04)'], {}), '(1.0, global_step, 2 * 1024 * 1024 // self.\n frames_per_training, 0.04)\n', (10717, 10791), True, 'import tensorflow as tf\n'), ((12924, 12946), 'numpy.concatenate', 'np.concatenate', (['arrays'], {}), '(arrays)\n', (12938, 12946), True, 'import numpy as np\n')]
|
import tensorflow as tf
import numpy as np
from tensorflow.python.eager.backprop import GradientTape
d = np.array([0.00002, 0.00001])
L = np.array([1.326, 1.316])
x500: np.array = np.array(
[[-4.2, 4.3],
[-8.4, 8.5],
[-12.1, 12.3]]
)
x1000: np.array = np.array(
[[-8.5, 8.5],
[-17.1, 17.0],
[-25.8, 25.8]]
)
x500 = x500 * (10 ** (-2))
x1000 = x1000 * (10 ** (-2))
print(x500.shape)
delta4 = 0
for i in range(3):
delta4 += x500[2-i][1] - x500[i][0]
#sum of 3 sections
delta4 = delta4 / 3
delta = delta4 / 4
print(delta)
x500 = np.mean(np.abs(x500), axis=1)
print(x1000)
x1000 = np.mean(np.abs(x1000), axis=1)
print(x1000)
sin = x1000 / np.sqrt(x1000*x1000 + L[1]*L[1])
print(sin)
def gradient(x500, x1000, d=d, L=L):
#tmp
#x1000 = x1000[0]
x500 = tf.convert_to_tensor(x500)
x1000 = tf.convert_to_tensor(x1000)
#d = tf.convert_to_tensor(d[1])
d = tf.convert_to_tensor(d[0])
#L = tf.convert_to_tensor(L[1])
#L = np.full(shape=(3,), fill_value=L[1])
L = np.full(shape=(3,), fill_value=L[0])
L = tf.convert_to_tensor(L)
print(f"L:{L}")
x1000 = x500
with tf.GradientTape() as tape1, tf.GradientTape() as tape2:
tape1.watch(x500)
tape1.watch(x1000)
tape1.watch(L)
tape1.watch(d)
print(f"x1000:{x1000}")
sin = x1000 / tf.sqrt(x1000*x1000 + L*L)
print(f"sin{sin}")
m = tf.constant(np.array([1, 2, 3], dtype=np.float64))
#tmp
#m = tf.constant(np.array([1], dtype=np.float64))
print(f"m:{m}, d;{d}")
lambdas = d * (sin / m)
#lambdas = lambdas * (10 ** 9)
print(f"lambdas{lambdas}")
#dsin_dx = tape.gradient(sin, x1000)
#print(dsin_dx)
#print(L*L / (tf.sqrt(x1000*x1000 + L*L) ** 3))
dlambdas_dL = tape1.gradient(lambdas, L)
print(f"dlamdas / dL \n{dlambdas_dL}")
return
dlambdas_dx = tape.gradient(lambdas, x1000)
print(f"dlamdas / dx \n{dlambdas_dx}")
return
dlambdas_dL = tape.gradient(lambdas, L)
print(f"dlamdas / dL \n{dlambdas_dL}")
def gradients(x500: np.ndarray, x1000: np.ndarray, d=d, L=L):
print("=======gradients========")
#tmp
#x1000 = x1000[0]
x500 = x500.reshape(1, 3)
x1000 = x1000.reshape(1, 3)
print(f"x500:{x500}")
print(f"x1000:{x1000}")
x = np.concatenate([x500, x1000])
print(f"x:{x}")
x = tf.convert_to_tensor(x)
d = d.reshape((2, 1))
d = tf.convert_to_tensor(d)
#L = tf.convert_to_tensor(L[1])
#L = np.full(shape=(3,), fill_value=L[1])
L: np.ndarray = np.full(shape=(3,2), fill_value=L)
L = L.transpose()
L = tf.convert_to_tensor(L)
print(f"L:{L}")
with tf.GradientTape() as tape1, tf.GradientTape() as tape2:
for val in (x, d, L):
tape1.watch(val)
tape2.watch(val)
print((x*x).shape)
print((L*L).shape)
sin = x / tf.sqrt(x*x + L*L)
print(f"sin{sin}")
m = tf.constant(np.array([1, 2, 3], dtype=np.float64))
#tmp
#m = tf.constant(np.array([1], dtype=np.float64))
print(f"m:{m}, d;{d}")
print((sin / m).shape)
print(d.shape)
lambdas = d * (sin / m)
#lambdas = lambdas * (10 ** 9)
print(f"lambdas{lambdas}")
#dsin_dx = tape.gradient(sin, x1000)
#print(dsin_dx)
#print(L*L / (tf.sqrt(x1000*x1000 + L*L) ** 3))
print("==========result===========")
dlambdas_dL = tape1.gradient(lambdas, L)
print(f"\ndlamdas / dL \n{dlambdas_dL}")
dlambdas_dx = tape2.gradient(lambdas, x)
print(f"\ndlamdas / dx \n{dlambdas_dx}")
delta_by_x = dlambdas_dx * (0.05 * 10**(-2))
delta_by_L = dlambdas_dL * 0.0005
print()
print(f"\nxの誤差:\n{delta_by_x}")
print(f"\nLの誤差:\n{delta_by_L}")
print(f"\nx_mean\n{tf.reduce_mean(delta_by_x, axis=1)}")
print(f"\nL_mean\n{tf.reduce_mean(delta_by_L, axis=1)}")
print()
delta = delta_by_x + tf.abs(delta_by_L)
print(f"\n誤差総和:\n{delta}")
print(f"\n誤差平均:\n{tf.reduce_mean(delta, axis=1)}")
def main():
gradients(x500, x1000)
return
def get_lambda(d, x, L):
sin = x / np.sqrt(x*x + L*L)
m = np.array([1, 2, 3])
lambdas = d * (sin / m)
return lambdas
def abs():
delta = 0.05
lam_plus = get_lambda(d[0], x500 + delta, L[0])
lam_minus = get_lambda(d[0], x500 - delta, L[0])
print(f"delta_lambda:{np.abs(lam_plus - lam_minus) / 2}")
def test(L=L):
print("=====test========")
print(f"x1000{x1000}")
print(f"square{x1000*x1000}")
L = L[1]
print(f"L:{L}")
print()
sin = x1000 / np.sqrt(x1000*x1000 + L*L)
print(np.sqrt(x1000*x1000 + L*L))
print(f"sin{sin}")
if __name__ == "__main__":
main()
#test()
#abs()
|
[
"numpy.full",
"tensorflow.abs",
"numpy.abs",
"tensorflow.convert_to_tensor",
"tensorflow.reduce_mean",
"numpy.array",
"tensorflow.sqrt",
"tensorflow.GradientTape",
"numpy.concatenate",
"numpy.sqrt"
] |
[((110, 134), 'numpy.array', 'np.array', (['[2e-05, 1e-05]'], {}), '([2e-05, 1e-05])\n', (118, 134), True, 'import numpy as np\n'), ((144, 168), 'numpy.array', 'np.array', (['[1.326, 1.316]'], {}), '([1.326, 1.316])\n', (152, 168), True, 'import numpy as np\n'), ((189, 240), 'numpy.array', 'np.array', (['[[-4.2, 4.3], [-8.4, 8.5], [-12.1, 12.3]]'], {}), '([[-4.2, 4.3], [-8.4, 8.5], [-12.1, 12.3]])\n', (197, 240), True, 'import numpy as np\n'), ((282, 335), 'numpy.array', 'np.array', (['[[-8.5, 8.5], [-17.1, 17.0], [-25.8, 25.8]]'], {}), '([[-8.5, 8.5], [-17.1, 17.0], [-25.8, 25.8]])\n', (290, 335), True, 'import numpy as np\n'), ((605, 617), 'numpy.abs', 'np.abs', (['x500'], {}), '(x500)\n', (611, 617), True, 'import numpy as np\n'), ((658, 671), 'numpy.abs', 'np.abs', (['x1000'], {}), '(x1000)\n', (664, 671), True, 'import numpy as np\n'), ((714, 750), 'numpy.sqrt', 'np.sqrt', (['(x1000 * x1000 + L[1] * L[1])'], {}), '(x1000 * x1000 + L[1] * L[1])\n', (721, 750), True, 'import numpy as np\n'), ((852, 878), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['x500'], {}), '(x500)\n', (872, 878), True, 'import tensorflow as tf\n'), ((892, 919), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['x1000'], {}), '(x1000)\n', (912, 919), True, 'import tensorflow as tf\n'), ((966, 992), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['d[0]'], {}), '(d[0])\n', (986, 992), True, 'import tensorflow as tf\n'), ((1088, 1124), 'numpy.full', 'np.full', ([], {'shape': '(3,)', 'fill_value': 'L[0]'}), '(shape=(3,), fill_value=L[0])\n', (1095, 1124), True, 'import numpy as np\n'), ((1134, 1157), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['L'], {}), '(L)\n', (1154, 1157), True, 'import tensorflow as tf\n'), ((2461, 2490), 'numpy.concatenate', 'np.concatenate', (['[x500, x1000]'], {}), '([x500, x1000])\n', (2475, 2490), True, 'import numpy as np\n'), ((2523, 2546), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['x'], {}), '(x)\n', (2543, 2546), True, 'import tensorflow as tf\n'), ((2585, 2608), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['d'], {}), '(d)\n', (2605, 2608), True, 'import tensorflow as tf\n'), ((2718, 2753), 'numpy.full', 'np.full', ([], {'shape': '(3, 2)', 'fill_value': 'L'}), '(shape=(3, 2), fill_value=L)\n', (2725, 2753), True, 'import numpy as np\n'), ((2785, 2808), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['L'], {}), '(L)\n', (2805, 2808), True, 'import tensorflow as tf\n'), ((4401, 4420), 'numpy.array', 'np.array', (['[1, 2, 3]'], {}), '([1, 2, 3])\n', (4409, 4420), True, 'import numpy as np\n'), ((1213, 1230), 'tensorflow.GradientTape', 'tf.GradientTape', ([], {}), '()\n', (1228, 1230), True, 'import tensorflow as tf\n'), ((1241, 1258), 'tensorflow.GradientTape', 'tf.GradientTape', ([], {}), '()\n', (1256, 1258), True, 'import tensorflow as tf\n'), ((2842, 2859), 'tensorflow.GradientTape', 'tf.GradientTape', ([], {}), '()\n', (2857, 2859), True, 'import tensorflow as tf\n'), ((2870, 2887), 'tensorflow.GradientTape', 'tf.GradientTape', ([], {}), '()\n', (2885, 2887), True, 'import tensorflow as tf\n'), ((4160, 4178), 'tensorflow.abs', 'tf.abs', (['delta_by_L'], {}), '(delta_by_L)\n', (4166, 4178), True, 'import tensorflow as tf\n'), ((4371, 4393), 'numpy.sqrt', 'np.sqrt', (['(x * x + L * L)'], {}), '(x * x + L * L)\n', (4378, 4393), True, 'import numpy as np\n'), ((4866, 4896), 'numpy.sqrt', 'np.sqrt', (['(x1000 * x1000 + L * L)'], {}), '(x1000 * x1000 + L * L)\n', (4873, 4896), True, 'import numpy as np\n'), ((4904, 4934), 'numpy.sqrt', 'np.sqrt', (['(x1000 * x1000 + L * L)'], {}), '(x1000 * x1000 + L * L)\n', (4911, 4934), True, 'import numpy as np\n'), ((1432, 1462), 'tensorflow.sqrt', 'tf.sqrt', (['(x1000 * x1000 + L * L)'], {}), '(x1000 * x1000 + L * L)\n', (1439, 1462), True, 'import tensorflow as tf\n'), ((1512, 1549), 'numpy.array', 'np.array', (['[1, 2, 3]'], {'dtype': 'np.float64'}), '([1, 2, 3], dtype=np.float64)\n', (1520, 1549), True, 'import numpy as np\n'), ((3068, 3090), 'tensorflow.sqrt', 'tf.sqrt', (['(x * x + L * L)'], {}), '(x * x + L * L)\n', (3075, 3090), True, 'import tensorflow as tf\n'), ((3144, 3181), 'numpy.array', 'np.array', (['[1, 2, 3]'], {'dtype': 'np.float64'}), '([1, 2, 3], dtype=np.float64)\n', (3152, 3181), True, 'import numpy as np\n'), ((4015, 4049), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['delta_by_x'], {'axis': '(1)'}), '(delta_by_x, axis=1)\n', (4029, 4049), True, 'import tensorflow as tf\n'), ((4077, 4111), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['delta_by_L'], {'axis': '(1)'}), '(delta_by_L, axis=1)\n', (4091, 4111), True, 'import tensorflow as tf\n'), ((4244, 4273), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['delta'], {'axis': '(1)'}), '(delta, axis=1)\n', (4258, 4273), True, 'import tensorflow as tf\n'), ((4644, 4672), 'numpy.abs', 'np.abs', (['(lam_plus - lam_minus)'], {}), '(lam_plus - lam_minus)\n', (4650, 4672), True, 'import numpy as np\n')]
|
from matplotlib import pyplot as plt
from numpy import array, zeros, amax, amin
from matplotlib.ticker import MultipleLocator, AutoMinorLocator
def cm_to_inch(val:float):
return val * 0.393700787
def plot_SP_data(model, overlay=False):
t = []
SP = []
A = []
with open("C:\\Users\\luukv\\Documents\\Studie\\Masters\\Jaar2\\MSc_thesis\\PAPER\\forcedata\\{}_SPdata.txt".format(model), 'r') as f:
# with open("C:\\Users\\luukv\\Documents\\ThesisData\\{}\\{}_SPdata.txt".format(model, model), 'r') as f:
for line in f.readlines():
if line.startswith('time'):
pass
else:
data = line.split()
if float(data[0]) / 1e6 < 0.01:
pass
else:
t.append(float(data[0]) / 1e6)
SP.append(float(data[1]))
A.append(float(data[2]))
if overlay:
return array(t), array(SP), array(A)
else:
fig, ax = plt.subplots(2, figsize=(8, 4.0))
#cm_to_inch(14.0), cm_to_inch(15.2))
ax[0].plot(t, SP, 'r*-', label=model)
ax[1].plot(t, A, 'r*-', label=model)
for axis in ax:
axis.xaxis.set_major_locator(MultipleLocator(10))
axis.xaxis.set_major_formatter('{x:.0f}')
axis.xaxis.set_minor_locator(MultipleLocator(5))
# ax[0].set_xlabel('Time [Myr]')
ax[1].set_xlabel('Time [Myr]')
ax[0].set_ylabel('Slab pull force [N/m]')
ax[1].set_ylabel(r'Slab area [$m^2$]')
ax[0].grid(b=True)
ax[1].grid(b=True)
return fig, ax
if __name__ =="__main__":
# dictionary to hold colours and labels for each model to prevent mistakes.
idclrs = {"ER": ['r', 'ref'], "FI": ['b', 'oc510'], "FI_shortpush": [(0, 0, 0.67), 'oc510sp'], "FJ": ['k', 'oc410'], "FK": ['g', 'oc310'],
"FP_rerun": [(1, 153 / 255, 153 / 255), 'peierls'], "FQ": ['c', 'LM25'], "FR": ['y', 'LM50'],
"FS": ['m', 'LM75'], "FT": [(139 / 255, 69 / 255, 19 / 255), 'LMoc510'], "FX": [(0.8, 0.8, 0.8),
'slowref']}
Models = ["ER", 'FI', 'FJ', 'FK', 'FP_rerun', 'FQ', 'FR', 'FS', 'FT', 'FX']
# Models = ["ER", "FQ", "FR", "FS", "FT"]
# Models = ["ER", "FI", "FJ", "FK"]
# Models = ["FP"]
# filename = "oceanlength_old"
filename = "selection"
# fig, ax = plot_SP_data("ER", overlay=False)
fig, ax = plt.subplots(2, figsize=(8, 3.5))
for axis in ax:
axis.xaxis.set_major_locator(MultipleLocator(10))
axis.xaxis.set_major_formatter('{x:.0f}')
axis.xaxis.set_minor_locator(MultipleLocator(5))
for i, model in enumerate(Models):
t, SP, A = plot_SP_data(model, overlay=True)
if model != "ER":
ax[0].plot(t, SP, '-', color=idclrs[model][0], label= idclrs[model][1])
ax[1].plot(t, A, '-', color=idclrs[model][0])
print("Peak slab pull of {:.3e} N/m reaced at t = {} for model {}".format(min(SP), t[SP.argmin()], model))
else:
ax[0].plot(t, SP, '-', color=idclrs[model][0], marker='*', label=idclrs[model][1])
ax[1].plot(t, A, '-', color=idclrs[model][0], marker='*')
print("Peak slab pull of {:.3e} N/m reaced at t = {} for model {}".format(min(SP), t[SP.argmin()], model))
# fig, ax = plot_SP_data("FI", overlay=False)
# t, SP, A = plot_SP_data("ER", overlay=True)
# ax[0].plot(t, SP,'g--')
# ax[1].plot(t, A, 'g--')
# for a in ax:
# a.set_xlim([0, 20])
# ax[0].set_xlabel('Time [Myr]')
ax[1].set_xlabel('Time [Myr]')
ax[0].set_ylabel('Slab pull force [N/m]')
ax[1].set_ylabel(r'Slab area [$m^2$]')
[_.set_xlim([0, 115]) for _ in ax] if "FX" in Models else [_.set_xlim([0, 60]) for _ in ax]
ax[0].set_ylim([-4.7e14, 0.8e14]) if "FX" in Models else ax[0].set_ylim([-1.7e14, 0.7e14])
ax[0].plot([0, 120], [0, 0], 'k:', linewidth=2)
ax[1].set_ylim([0, 8.1e11]) if "FX"in Models else ax[1].set_ylim([0, 5e11])
ax[0].legend(bbox_to_anchor=(0.5, 1.25), ncol=5, loc='upper center', borderaxespad=0.1, fancybox=True)
# plt.subplots_adjust(bottom=0.15) # place legend below figure
# plt.show()
# plt.gca().set_axis_off()
plt.subplots_adjust(top=1, bottom=0, right=1, left=0,
hspace=0.2, wspace=0)
plt.margins(0, 0)
plt.savefig('C:/Users/luukv/Documents/Studie/Masters/Jaar2/MSc_thesis/PAPER/modelfigs/forces/{}.png'.format(filename), bbox_inches='tight', pad_inches=0, dpi=300)
|
[
"matplotlib.pyplot.margins",
"numpy.array",
"matplotlib.pyplot.subplots_adjust",
"matplotlib.ticker.MultipleLocator",
"matplotlib.pyplot.subplots"
] |
[((2518, 2551), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)'], {'figsize': '(8, 3.5)'}), '(2, figsize=(8, 3.5))\n', (2530, 2551), True, 'from matplotlib import pyplot as plt\n'), ((4334, 4409), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'top': '(1)', 'bottom': '(0)', 'right': '(1)', 'left': '(0)', 'hspace': '(0.2)', 'wspace': '(0)'}), '(top=1, bottom=0, right=1, left=0, hspace=0.2, wspace=0)\n', (4353, 4409), True, 'from matplotlib import pyplot as plt\n'), ((4438, 4455), 'matplotlib.pyplot.margins', 'plt.margins', (['(0)', '(0)'], {}), '(0, 0)\n', (4449, 4455), True, 'from matplotlib import pyplot as plt\n'), ((1001, 1034), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)'], {'figsize': '(8, 4.0)'}), '(2, figsize=(8, 4.0))\n', (1013, 1034), True, 'from matplotlib import pyplot as plt\n'), ((943, 951), 'numpy.array', 'array', (['t'], {}), '(t)\n', (948, 951), False, 'from numpy import array, zeros, amax, amin\n'), ((953, 962), 'numpy.array', 'array', (['SP'], {}), '(SP)\n', (958, 962), False, 'from numpy import array, zeros, amax, amin\n'), ((964, 972), 'numpy.array', 'array', (['A'], {}), '(A)\n', (969, 972), False, 'from numpy import array, zeros, amax, amin\n'), ((2609, 2628), 'matplotlib.ticker.MultipleLocator', 'MultipleLocator', (['(10)'], {}), '(10)\n', (2624, 2628), False, 'from matplotlib.ticker import MultipleLocator, AutoMinorLocator\n'), ((2717, 2735), 'matplotlib.ticker.MultipleLocator', 'MultipleLocator', (['(5)'], {}), '(5)\n', (2732, 2735), False, 'from matplotlib.ticker import MultipleLocator, AutoMinorLocator\n'), ((1236, 1255), 'matplotlib.ticker.MultipleLocator', 'MultipleLocator', (['(10)'], {}), '(10)\n', (1251, 1255), False, 'from matplotlib.ticker import MultipleLocator, AutoMinorLocator\n'), ((1352, 1370), 'matplotlib.ticker.MultipleLocator', 'MultipleLocator', (['(5)'], {}), '(5)\n', (1367, 1370), False, 'from matplotlib.ticker import MultipleLocator, AutoMinorLocator\n')]
|
# Importing Package(s)
import cv2
import numpy as np
print('Package(s) Imported')
# Basic Functions
img = cv2.imread('Resources/me.jpg')
kernel = np.ones((5,5), np.uint8)
imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Gray Scaled Image
imgBlur = cv2.GaussianBlur(imgGray, (7,7), 0) # Blurred Image, (7,7) - Kernel Size (always Odd), 0 - SigmaX
imgCanny = cv2.Canny(img, 100, 100) # Edge Detector
imgDialation = cv2.dilate(imgCanny, kernel, iterations = 1) # Dialate the Image
imgEroded = cv2.erode(imgDialation, kernel, iterations = 1) # Erode the Image (opposite of dialation)
cv2.imshow("Gray Image", imgGray)
cv2.imshow("Blur Image", imgBlur)
cv2.imshow("Canny Image", imgCanny)
cv2.imshow("Dialation Image", imgDialation)
cv2.imshow("Eroded Image", imgEroded)
cv2.waitKey(0)
|
[
"cv2.GaussianBlur",
"cv2.Canny",
"cv2.dilate",
"cv2.cvtColor",
"cv2.waitKey",
"numpy.ones",
"cv2.imread",
"cv2.erode",
"cv2.imshow"
] |
[((107, 137), 'cv2.imread', 'cv2.imread', (['"""Resources/me.jpg"""'], {}), "('Resources/me.jpg')\n", (117, 137), False, 'import cv2\n'), ((147, 172), 'numpy.ones', 'np.ones', (['(5, 5)', 'np.uint8'], {}), '((5, 5), np.uint8)\n', (154, 172), True, 'import numpy as np\n'), ((183, 220), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2GRAY'], {}), '(img, cv2.COLOR_BGR2GRAY)\n', (195, 220), False, 'import cv2\n'), ((252, 288), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['imgGray', '(7, 7)', '(0)'], {}), '(imgGray, (7, 7), 0)\n', (268, 288), False, 'import cv2\n'), ((364, 388), 'cv2.Canny', 'cv2.Canny', (['img', '(100)', '(100)'], {}), '(img, 100, 100)\n', (373, 388), False, 'import cv2\n'), ((420, 462), 'cv2.dilate', 'cv2.dilate', (['imgCanny', 'kernel'], {'iterations': '(1)'}), '(imgCanny, kernel, iterations=1)\n', (430, 462), False, 'import cv2\n'), ((497, 542), 'cv2.erode', 'cv2.erode', (['imgDialation', 'kernel'], {'iterations': '(1)'}), '(imgDialation, kernel, iterations=1)\n', (506, 542), False, 'import cv2\n'), ((587, 620), 'cv2.imshow', 'cv2.imshow', (['"""Gray Image"""', 'imgGray'], {}), "('Gray Image', imgGray)\n", (597, 620), False, 'import cv2\n'), ((621, 654), 'cv2.imshow', 'cv2.imshow', (['"""Blur Image"""', 'imgBlur'], {}), "('Blur Image', imgBlur)\n", (631, 654), False, 'import cv2\n'), ((655, 690), 'cv2.imshow', 'cv2.imshow', (['"""Canny Image"""', 'imgCanny'], {}), "('Canny Image', imgCanny)\n", (665, 690), False, 'import cv2\n'), ((691, 734), 'cv2.imshow', 'cv2.imshow', (['"""Dialation Image"""', 'imgDialation'], {}), "('Dialation Image', imgDialation)\n", (701, 734), False, 'import cv2\n'), ((735, 772), 'cv2.imshow', 'cv2.imshow', (['"""Eroded Image"""', 'imgEroded'], {}), "('Eroded Image', imgEroded)\n", (745, 772), False, 'import cv2\n'), ((773, 787), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (784, 787), False, 'import cv2\n')]
|
import numpy as np
import pytest
from bayesian_mmm.spend_transformation.spend_transformation import (
add_lagged_values_along_z,
compute_adstock,
compute_geo_decay,
compute_hill,
compute_reach
)
SPENDS = np.array([[10, 20], [0, 8], [1, 30], [5, 40]])
MAX_LAG = 4
LAGGED_SPENDS = np.array([
[[10, 0, 0, 0], [20, 0, 0, 0]],
[[ 0, 10, 0, 0], [ 8, 20, 0, 0]],
[[ 1, 0, 10, 0], [30, 8, 20, 0]],
[[ 5, 1, 0, 10], [40, 30, 8, 20]]
])
DELAYS = [2.5, 2]
RETAIN_RATES = [0.2, 0.9]
ECS = [0.2, 1]
SLOPES = [1, 4]
HALF_SATURATIONS = [2, 3]
def test_add_lagged_values_along_z():
print(add_lagged_values_along_z(SPENDS, MAX_LAG), LAGGED_SPENDS)
assert (add_lagged_values_along_z(SPENDS, MAX_LAG) == LAGGED_SPENDS).all()
def test_compute_adstock():
ADSTOCK_SPENDS = np.array([
[0.00031371564813652915, 3.796765139897573],
[0.19607228008533067, 6.726888689563381],
[4.90183837369808, 13.565290356181823],
[4.921571087965868, 22.928734700963517]
])
assert (compute_adstock(LAGGED_SPENDS, DELAYS, RETAIN_RATES) == ADSTOCK_SPENDS).all()
def test_compute_geo_decay():
GEO_DECAY_SPENDS = np.array([
[ 8.012820512820513 , 5.815644082582146 ],
[ 1.6025641025641026, 7.560337307356789 ],
[ 1.1217948717948718, 15.527769700494332 ],
[ 4.230769230769231 , 25.60628089560919 ]
])
assert (compute_geo_decay(LAGGED_SPENDS, RETAIN_RATES) == GEO_DECAY_SPENDS).all()
def test_compute_hill():
HILL_SPENDS = np.array([
[0.9803921568627451, 0.9999937500390623],
[0. , 0.9997559189650964],
[0.8333333333333334, 0.9999987654336229],
[0.9615384615384615, 0.9999996093751526]
])
assert (compute_hill(SPENDS, ECS, SLOPES) == HILL_SPENDS).all()
def test_compute_reach():
REACH_SPENDS = np.array([
[0.9999999958776927, 1. ],
[0. , 0.9999999999244973],
[0.7615941559557649, 1. ],
[0.9999092042625951, 1. ]
])
assert (compute_reach(SPENDS, HALF_SATURATIONS) == REACH_SPENDS).all()
|
[
"bayesian_mmm.spend_transformation.spend_transformation.compute_hill",
"bayesian_mmm.spend_transformation.spend_transformation.compute_reach",
"bayesian_mmm.spend_transformation.spend_transformation.compute_adstock",
"bayesian_mmm.spend_transformation.spend_transformation.compute_geo_decay",
"numpy.array",
"bayesian_mmm.spend_transformation.spend_transformation.add_lagged_values_along_z"
] |
[((226, 272), 'numpy.array', 'np.array', (['[[10, 20], [0, 8], [1, 30], [5, 40]]'], {}), '([[10, 20], [0, 8], [1, 30], [5, 40]])\n', (234, 272), True, 'import numpy as np\n'), ((303, 449), 'numpy.array', 'np.array', (['[[[10, 0, 0, 0], [20, 0, 0, 0]], [[0, 10, 0, 0], [8, 20, 0, 0]], [[1, 0, 10,\n 0], [30, 8, 20, 0]], [[5, 1, 0, 10], [40, 30, 8, 20]]]'], {}), '([[[10, 0, 0, 0], [20, 0, 0, 0]], [[0, 10, 0, 0], [8, 20, 0, 0]], [\n [1, 0, 10, 0], [30, 8, 20, 0]], [[5, 1, 0, 10], [40, 30, 8, 20]]])\n', (311, 449), True, 'import numpy as np\n'), ((820, 1007), 'numpy.array', 'np.array', (['[[0.00031371564813652915, 3.796765139897573], [0.19607228008533067, \n 6.726888689563381], [4.90183837369808, 13.565290356181823], [\n 4.921571087965868, 22.928734700963517]]'], {}), '([[0.00031371564813652915, 3.796765139897573], [0.19607228008533067,\n 6.726888689563381], [4.90183837369808, 13.565290356181823], [\n 4.921571087965868, 22.928734700963517]])\n', (828, 1007), True, 'import numpy as np\n'), ((1192, 1375), 'numpy.array', 'np.array', (['[[8.012820512820513, 5.815644082582146], [1.6025641025641026, \n 7.560337307356789], [1.1217948717948718, 15.527769700494332], [\n 4.230769230769231, 25.60628089560919]]'], {}), '([[8.012820512820513, 5.815644082582146], [1.6025641025641026, \n 7.560337307356789], [1.1217948717948718, 15.527769700494332], [\n 4.230769230769231, 25.60628089560919]])\n', (1200, 1375), True, 'import numpy as np\n'), ((1558, 1731), 'numpy.array', 'np.array', (['[[0.9803921568627451, 0.9999937500390623], [0.0, 0.9997559189650964], [\n 0.8333333333333334, 0.9999987654336229], [0.9615384615384615, \n 0.9999996093751526]]'], {}), '([[0.9803921568627451, 0.9999937500390623], [0.0, \n 0.9997559189650964], [0.8333333333333334, 0.9999987654336229], [\n 0.9615384615384615, 0.9999996093751526]])\n', (1566, 1731), True, 'import numpy as np\n'), ((1901, 2024), 'numpy.array', 'np.array', (['[[0.9999999958776927, 1.0], [0.0, 0.9999999999244973], [0.7615941559557649,\n 1.0], [0.9999092042625951, 1.0]]'], {}), '([[0.9999999958776927, 1.0], [0.0, 0.9999999999244973], [\n 0.7615941559557649, 1.0], [0.9999092042625951, 1.0]])\n', (1909, 2024), True, 'import numpy as np\n'), ((625, 667), 'bayesian_mmm.spend_transformation.spend_transformation.add_lagged_values_along_z', 'add_lagged_values_along_z', (['SPENDS', 'MAX_LAG'], {}), '(SPENDS, MAX_LAG)\n', (650, 667), False, 'from bayesian_mmm.spend_transformation.spend_transformation import add_lagged_values_along_z, compute_adstock, compute_geo_decay, compute_hill, compute_reach\n'), ((701, 743), 'bayesian_mmm.spend_transformation.spend_transformation.add_lagged_values_along_z', 'add_lagged_values_along_z', (['SPENDS', 'MAX_LAG'], {}), '(SPENDS, MAX_LAG)\n', (726, 743), False, 'from bayesian_mmm.spend_transformation.spend_transformation import add_lagged_values_along_z, compute_adstock, compute_geo_decay, compute_hill, compute_reach\n'), ((1058, 1110), 'bayesian_mmm.spend_transformation.spend_transformation.compute_adstock', 'compute_adstock', (['LAGGED_SPENDS', 'DELAYS', 'RETAIN_RATES'], {}), '(LAGGED_SPENDS, DELAYS, RETAIN_RATES)\n', (1073, 1110), False, 'from bayesian_mmm.spend_transformation.spend_transformation import add_lagged_values_along_z, compute_adstock, compute_geo_decay, compute_hill, compute_reach\n'), ((1437, 1483), 'bayesian_mmm.spend_transformation.spend_transformation.compute_geo_decay', 'compute_geo_decay', (['LAGGED_SPENDS', 'RETAIN_RATES'], {}), '(LAGGED_SPENDS, RETAIN_RATES)\n', (1454, 1483), False, 'from bayesian_mmm.spend_transformation.spend_transformation import add_lagged_values_along_z, compute_adstock, compute_geo_decay, compute_hill, compute_reach\n'), ((1796, 1829), 'bayesian_mmm.spend_transformation.spend_transformation.compute_hill', 'compute_hill', (['SPENDS', 'ECS', 'SLOPES'], {}), '(SPENDS, ECS, SLOPES)\n', (1808, 1829), False, 'from bayesian_mmm.spend_transformation.spend_transformation import add_lagged_values_along_z, compute_adstock, compute_geo_decay, compute_hill, compute_reach\n'), ((2135, 2174), 'bayesian_mmm.spend_transformation.spend_transformation.compute_reach', 'compute_reach', (['SPENDS', 'HALF_SATURATIONS'], {}), '(SPENDS, HALF_SATURATIONS)\n', (2148, 2174), False, 'from bayesian_mmm.spend_transformation.spend_transformation import add_lagged_values_along_z, compute_adstock, compute_geo_decay, compute_hill, compute_reach\n')]
|
# -*- coding: utf-8 -*-
from universal.algo import Algo
import universal.tools as tools
import numpy as np
from cvxopt import solvers, matrix
solvers.options['show_progress'] = False
class ONS(Algo):
"""
Online newton step algorithm.
Reference:
A.Agarwal, E.Hazan, S.Kale, R.E.Schapire.
Algorithms for Portfolio Management based on the Newton Method, 2006.
http://machinelearning.wustl.edu/mlpapers/paper_files/icml2006_AgarwalHKS06.pdf
"""
REPLACE_MISSING = True
def __init__(self, delta=0.125, beta=1., eta=0.):
"""
:param delta, beta, eta: Model parameters. See paper.
"""
super(ONS, self).__init__()
self.delta = delta
self.beta = beta
self.eta = eta
def init_weights(self, m):
return np.ones(m) / m
def init_step(self, X):
m = X.shape[1]
self.A = np.mat(np.eye(m))
self.b = np.mat(np.zeros(m)).T
def step(self, r, p):
# calculate gradient
grad = np.mat(r / np.dot(p, r)).T
# update A
self.A += grad * grad.T
# update b
self.b += (1 + 1./self.beta) * grad
# projection of p induced by norm A
pp = self.projection_in_norm(self.delta * self.A.I * self.b, self.A)
return pp * (1 - self.eta) + np.ones(len(r)) / float(len(r)) * self.eta
def projection_in_norm(self, x, M):
""" Projection of x to simplex indiced by matrix M. Uses quadratic programming.
"""
m = M.shape[0]
P = matrix(2*M)
q = matrix(-2 * M * x)
G = matrix(-np.eye(m))
h = matrix(np.zeros((m,1)))
A = matrix(np.ones((1,m)))
b = matrix(1.)
sol = solvers.qp(P, q, G, h, A, b)
return np.squeeze(sol['x'])
if __name__ == '__main__':
tools.quickrun(ONS())
|
[
"cvxopt.matrix",
"numpy.dot",
"numpy.zeros",
"numpy.ones",
"cvxopt.solvers.qp",
"numpy.eye",
"numpy.squeeze"
] |
[((1586, 1599), 'cvxopt.matrix', 'matrix', (['(2 * M)'], {}), '(2 * M)\n', (1592, 1599), False, 'from cvxopt import solvers, matrix\n'), ((1610, 1628), 'cvxopt.matrix', 'matrix', (['(-2 * M * x)'], {}), '(-2 * M * x)\n', (1616, 1628), False, 'from cvxopt import solvers, matrix\n'), ((1743, 1754), 'cvxopt.matrix', 'matrix', (['(1.0)'], {}), '(1.0)\n', (1749, 1754), False, 'from cvxopt import solvers, matrix\n'), ((1777, 1805), 'cvxopt.solvers.qp', 'solvers.qp', (['P', 'q', 'G', 'h', 'A', 'b'], {}), '(P, q, G, h, A, b)\n', (1787, 1805), False, 'from cvxopt import solvers, matrix\n'), ((1821, 1841), 'numpy.squeeze', 'np.squeeze', (["sol['x']"], {}), "(sol['x'])\n", (1831, 1841), True, 'import numpy as np\n'), ((818, 828), 'numpy.ones', 'np.ones', (['m'], {}), '(m)\n', (825, 828), True, 'import numpy as np\n'), ((918, 927), 'numpy.eye', 'np.eye', (['m'], {}), '(m)\n', (924, 927), True, 'import numpy as np\n'), ((1679, 1695), 'numpy.zeros', 'np.zeros', (['(m, 1)'], {}), '((m, 1))\n', (1687, 1695), True, 'import numpy as np\n'), ((1715, 1730), 'numpy.ones', 'np.ones', (['(1, m)'], {}), '((1, m))\n', (1722, 1730), True, 'import numpy as np\n'), ((953, 964), 'numpy.zeros', 'np.zeros', (['m'], {}), '(m)\n', (961, 964), True, 'import numpy as np\n'), ((1649, 1658), 'numpy.eye', 'np.eye', (['m'], {}), '(m)\n', (1655, 1658), True, 'import numpy as np\n'), ((1051, 1063), 'numpy.dot', 'np.dot', (['p', 'r'], {}), '(p, r)\n', (1057, 1063), True, 'import numpy as np\n')]
|
import scipy.sparse as sp
import numpy as np
from sklearn import preprocessing
import networkx as nx
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
def encode_onehot(labels):
classes = sorted(list(set(labels)))
classes_dict = {c: np.identity(len(classes))[i, :] for i, c in enumerate(classes)}
labels_onehot = np.array(list(map(classes_dict.get, labels)), dtype=np.int32)
return labels_onehot
def load_data(dataset):
"""Load feature matrix and ground truth assignment matrix."""
print('Loading {} dataset...'.format(dataset))
idx_feature_labels = np.genfromtxt("data/{}.content".format(dataset), dtype=np.dtype(str))
features = sp.csr_matrix(idx_feature_labels[:, 1:-1], dtype=np.float32)
labels = encode_onehot(idx_feature_labels[:, -1])
idx = np.array(idx_feature_labels[:, 0], dtype=np.int32)
nodelist_mapping = dict(enumerate(idx))
print('Samples={},Features={},Labels={}'.format(features.shape[0],features.shape[1],labels.shape[1]))
return features.toarray(), labels, nodelist_mapping
def preprocess_features(features):
"""Row-normalize feature matrix"""
features = preprocessing.normalize(features, norm='l1', axis=1)
return features
def count_nodes(adj):
"""Compute number of nodes of a graph using its adjacency matrix"""
return adj.shape[0]
def count_edges(adj):
"""Compute number of edges of a graph using its adjacency matrix"""
return int(np.sum(np.count_nonzero(adj)) / 2)
def count_density(adj):
"""Compute density of a graph using its adjacency matrix"""
N = adj.shape[0]
return count_edges(adj) / (N * (N-1) / 2)
def show_info(adj):
"""Show basic information about a graph using its adjacency matrix"""
print("Nodes={},Edges={},Density={:.5f}".format(count_nodes(adj),count_edges(adj),count_density(adj)))
def save_graph(adj, nodelist_mapping, filename):
"""Save a graph in the form of an edgelist from its adjacency matrix and node mapping"""
G_adj = nx.relabel_nodes(nx.Graph(adj),nodelist_mapping)
edgelists = list(nx.to_edgelist(G_adj))
f = open(filename, "w")
for i in range(len(edgelists)):
f.write(str(edgelists[i][0]) + '\t' + str(edgelists[i][1]) + '\n')
f.close()
|
[
"numpy.count_nonzero",
"numpy.dtype",
"networkx.to_edgelist",
"scipy.sparse.csr_matrix",
"networkx.Graph",
"numpy.array",
"sklearn.preprocessing.normalize"
] |
[((696, 756), 'scipy.sparse.csr_matrix', 'sp.csr_matrix', (['idx_feature_labels[:, 1:-1]'], {'dtype': 'np.float32'}), '(idx_feature_labels[:, 1:-1], dtype=np.float32)\n', (709, 756), True, 'import scipy.sparse as sp\n'), ((822, 872), 'numpy.array', 'np.array', (['idx_feature_labels[:, 0]'], {'dtype': 'np.int32'}), '(idx_feature_labels[:, 0], dtype=np.int32)\n', (830, 872), True, 'import numpy as np\n'), ((1171, 1223), 'sklearn.preprocessing.normalize', 'preprocessing.normalize', (['features'], {'norm': '"""l1"""', 'axis': '(1)'}), "(features, norm='l1', axis=1)\n", (1194, 1223), False, 'from sklearn import preprocessing\n'), ((2038, 2051), 'networkx.Graph', 'nx.Graph', (['adj'], {}), '(adj)\n', (2046, 2051), True, 'import networkx as nx\n'), ((2091, 2112), 'networkx.to_edgelist', 'nx.to_edgelist', (['G_adj'], {}), '(G_adj)\n', (2105, 2112), True, 'import networkx as nx\n'), ((666, 679), 'numpy.dtype', 'np.dtype', (['str'], {}), '(str)\n', (674, 679), True, 'import numpy as np\n'), ((1480, 1501), 'numpy.count_nonzero', 'np.count_nonzero', (['adj'], {}), '(adj)\n', (1496, 1501), True, 'import numpy as np\n')]
|
# -*- coding: utf-8 -*-
import pandas as pd
import torch
from sklearn.metrics import log_loss, roc_auc_score
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder, MinMaxScaler
from deepctr_torch.inputs import SparseFeat, DenseFeat, get_feature_names
from deepctr_torch.models import *
from torch import nn
import numpy as np
import argparse
import yaml
import json
import pdb
import sys
import shutil
from torch.utils.tensorboard import SummaryWriter
def count_parameters(model):
total_para = 0
strr = "PARAMETERS:\n"
for name,parameters in model.named_parameters():
strr += name + ':' + str(parameters.size()) + "\n"
total_para += parameters.numel()
strr += "Total:" + str(total_para) + "\n"
return strr
def load_data_in_df(args, config):
sparse_features = ['C' + str(i) for i in range(1, 27)]
dense_features = ['I' + str(i) for i in range(1, 14)]
target = ['label']
if args.test_run:
print("SAMPLE RUN...")
df = pd.read_csv('/home/apd10/DeepCTR-Torch/examples/criteo_sample.txt')
#df = pd.read_csv('/home/apd10/dlrm/dlrm/input/small_data.csv')
df[sparse_features] = df[sparse_features].fillna('-1', )
df[dense_features] = df[dense_features].fillna(0, )
# 1.Label Encoding for sparse features,and do simple Transformation for dense features
for feat in sparse_features:
lbe = LabelEncoder()
df[feat] = lbe.fit_transform(df[feat])
mms = MinMaxScaler(feature_range=(0, 1))
df[dense_features] = mms.fit_transform(df[dense_features])
else:
handle = np.load("/home/apd10/dlrm/dlrm/input/data.npz")
if "data" in config:
if config["data"]["type"] == "le2":
print("Using le2 data")
handle = np.load("/home/apd10/dlrm/dlrm/input/data.le2.npz")
intdf = pd.DataFrame(handle['intF'], columns = dense_features)
catdf = pd.DataFrame(handle['catF'], columns = sparse_features)
labeldf = pd.DataFrame(handle['label'], columns = target)
df = pd.concat([labeldf, intdf, catdf], axis=1)
del intdf, catdf, labeldf
# all the above processing like label encoding, mms etc is already done in dumped data.npz
return df
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--config', action="store", dest="config", type=str, default=None, required=True,
help="config to setup the training")
parser.add_argument('--test_run', action="store_true", default=False)
parser.add_argument('--epochs', action="store", dest="epochs", default=25, type=int)
args = parser.parse_args()
config_file = args.config
with open(config_file, "r") as f:
config = yaml.load(f)
print("config", config)
summaryWriter = SummaryWriter()
commandlinefile = summaryWriter.log_dir + "/cmd_args.txt"
configfile = summaryWriter.log_dir + "/config.yml"
shutil.copyfile(config_file, configfile)
with open(commandlinefile, "w") as f:
f.write(json.dumps(vars(args)))
out_handle = open(summaryWriter.log_dir +"/res.log", "a")
if not args.test_run:
sys.stdout = out_handle
else:
out_handle = sys.stdout
data = load_data_in_df(args, config)
sparse_features = ['C' + str(i) for i in range(1, 27)]
dense_features = ['I' + str(i) for i in range(1, 14)]
target = ['label']
# 2.count #unique features for each sparse field,and record dense feature field name
embedding_params = config["embedding"]
embedding_dim = embedding_params["size"]
if embedding_params["etype"] == "full":
fixlen_feature_columns = [SparseFeat(feat, data[feat].nunique(), embedding_dim)
for feat in sparse_features] + [DenseFeat(feat, 1, )
for feat in dense_features]
elif embedding_params["etype"] == "rma":
print("FIGURE OUT THE INITIALIZATION")
hashed_weight = nn.Parameter(torch.from_numpy(np.random.uniform(
low=-np.sqrt(1 / embedding_dim), high=np.sqrt(1 / embedding_dim), size=((embedding_params["rma"]["memory"],))
).astype(np.float32)))
fixlen_feature_columns = [SparseFeat(feat, data[feat].nunique(), embedding_dim, use_rma=True, hashed_weight=hashed_weight)
for feat in sparse_features] + [DenseFeat(feat, 1, )
for feat in dense_features]
elif embedding_params["etype"] == "lma":
print("FIGURE OUT THE INITIALIZATION")
lma_params = embedding_params["lma"]
hashed_weight = nn.Parameter(torch.from_numpy(np.random.uniform(
low=-np.sqrt(1 / embedding_dim), high=np.sqrt(1 / embedding_dim), size=((lma_params["memory"],))
).astype(np.float32)))
signature = np.load(lma_params["signature"])["signature"]
signature = torch.from_numpy(signature).to("cuda:0")
fixlen_feature_columns = [SparseFeat(feat, data[feat].nunique(), embedding_dim, use_lma=True, hashed_weight=hashed_weight,
key_bits=lma_params["key_bits"], keys_to_use=lma_params["keys_to_use"], signature=signature)
for feat in sparse_features] + [DenseFeat(feat, 1, ) for feat in dense_features]
elif embedding_params["etype"] == "rma_bern":
rma_bern_params = embedding_params["rma_bern"]
ls = [ int(x) for x in rma_bern_params["mlp"].split('-')]
mlp_model = nn.ModuleList()
for i in range(0, len(ls) - 2):
mlp_model.append(nn.Linear(ls[i], ls[i+1]))
mlp_model.append(nn.ReLU())
mlp_model.append(nn.Linear(ls[len(ls)-2], ls[len(ls) - 1]))
bern_mlp_model = torch.nn.Sequential(*mlp_model).to("cuda:0")
fixlen_feature_columns = [SparseFeat(feat, data[feat].nunique(), int(ls[-1]), use_rma_bern=True, bern_embedding_dim=ls[0], bern_mlp_model=bern_mlp_model)
for feat in sparse_features] + [DenseFeat(feat, 1, ) for feat in dense_features]
else:
raise NotImplementedError
# Question(yanzhou): why dnn_feature_columns and linear_feature_columns are the same?
dnn_feature_columns = fixlen_feature_columns
linear_feature_columns = fixlen_feature_columns
feature_names = get_feature_names(
linear_feature_columns + dnn_feature_columns)
# 3.generate input data for model
train, test = train_test_split(data, test_size=0.1, random_state=2020)
train_model_input = {name: train[name] for name in feature_names}
test_model_input = {name: test[name] for name in feature_names}
# 4.Define Model,train,predict and evaluate
device = 'cpu'
use_cuda = True
if use_cuda and torch.cuda.is_available():
print('cuda ready...')
device = 'cuda:0'
if "seed" in config:
model_seed = config["seed"]
else:
model_seed = 1024 # default seed
#initialize model
if config["model"] == "deepfm":
params = config["deepfm"]
model = DeepFM(linear_feature_columns=linear_feature_columns, dnn_feature_columns=dnn_feature_columns,
dnn_hidden_units=(400,400,400),
dnn_dropout=0.5,
task='binary',
l2_reg_embedding=0, l2_reg_linear=0, device=device, seed=model_seed)
elif config["model"] == "dcn":
params = config["dcn"]
model = DCN(linear_feature_columns=linear_feature_columns,
dnn_feature_columns=dnn_feature_columns,
dnn_hidden_units=(1024,1024,1024,1024),
cross_num = 1,
l2_reg_linear = 0, l2_reg_embedding=0, l2_reg_cross =0, l2_reg_dnn=0,
device=device, seed=model_seed)
elif config["model"] == "onn":
params = config["onn"]
model = ONN(linear_feature_columns=linear_feature_columns,
dnn_feature_columns=dnn_feature_columns,
dnn_hidden_units=(400,400,400),
l2_reg_linear = 0, l2_reg_embedding=0, l2_reg_dnn=0,
device=device, seed=model_seed)
elif config["model"] =="fibinet":
params = config["fibinet"]
model = FiBiNET(linear_feature_columns=linear_feature_columns,
dnn_feature_columns=dnn_feature_columns,
dnn_hidden_units=(400,400,400),
dnn_dropout=0.5,
device=device, seed=model_seed)
elif config["model"] =="xdeepfm":
params = config["xdeepfm"]
model = xDeepFM(linear_feature_columns=linear_feature_columns,
dnn_feature_columns=dnn_feature_columns,
dnn_hidden_units=(400,400,400),
cin_layer_size=(200,200,200),
dnn_dropout=0.5,
l2_reg_linear = 0.0001, l2_reg_embedding=0.0001, l2_reg_dnn=0.0001,
device=device, seed=model_seed)
elif config["model"] =="autoint":
params = config["autoint"]
model = AutoInt(linear_feature_columns=linear_feature_columns,
dnn_feature_columns=dnn_feature_columns, att_embedding_size=32, dnn_hidden_units=(400,400,400), l2_reg_dnn=0, l2_reg_embedding=0,
device=device, seed=model_seed)
else:
raise NotImplementedError
print(model)
strr = count_parameters(model)
out_handle.write(strr)
out_handle.flush()
model.compile("adam", "binary_crossentropy",
metrics=["binary_crossentropy", "auc"], )
min_test_iteration = 15000 # end of 1 epoch
batch_size = config["train"]["batch_size"]
if args.test_run:
min_test_iteration = 1
batch_size = 1000
history = model.fit(train_model_input, train[target].values, batch_size=batch_size, epochs=args.epochs, verbose=2,
validation_split=0.2, summaryWriter=summaryWriter, test_x = test_model_input, test_y = test[target].values,
min_test_iteration = min_test_iteration)
pd.DataFrame(history.history).to_csv(summaryWriter.log_dir + "/results.csv", index=False)
#pred_ans = model.predict(test_model_input, 16348)
#out_handle.write("test LogLoss: "+str( round(log_loss(test[target].values, pred_ans), 4))+"\n")
#out_handle.write("test AUC"+str( round(roc_auc_score(test[target].values, pred_ans), 4))+"\n")
out_handle.close()
|
[
"numpy.load",
"yaml.load",
"argparse.ArgumentParser",
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"sklearn.preprocessing.MinMaxScaler",
"pandas.DataFrame",
"sklearn.preprocessing.LabelEncoder",
"torch.utils.tensorboard.SummaryWriter",
"torch.nn.Linear",
"shutil.copyfile",
"pandas.concat",
"deepctr_torch.inputs.DenseFeat",
"torch.nn.ModuleList",
"deepctr_torch.inputs.get_feature_names",
"torch.cuda.is_available",
"torch.from_numpy",
"torch.nn.ReLU",
"torch.nn.Sequential",
"numpy.sqrt"
] |
[((2372, 2397), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (2395, 2397), False, 'import argparse\n'), ((2903, 2918), 'torch.utils.tensorboard.SummaryWriter', 'SummaryWriter', ([], {}), '()\n', (2916, 2918), False, 'from torch.utils.tensorboard import SummaryWriter\n'), ((3042, 3082), 'shutil.copyfile', 'shutil.copyfile', (['config_file', 'configfile'], {}), '(config_file, configfile)\n', (3057, 3082), False, 'import shutil\n'), ((6560, 6623), 'deepctr_torch.inputs.get_feature_names', 'get_feature_names', (['(linear_feature_columns + dnn_feature_columns)'], {}), '(linear_feature_columns + dnn_feature_columns)\n', (6577, 6623), False, 'from deepctr_torch.inputs import SparseFeat, DenseFeat, get_feature_names\n'), ((6691, 6747), 'sklearn.model_selection.train_test_split', 'train_test_split', (['data'], {'test_size': '(0.1)', 'random_state': '(2020)'}), '(data, test_size=0.1, random_state=2020)\n', (6707, 6747), False, 'from sklearn.model_selection import train_test_split\n'), ((1035, 1102), 'pandas.read_csv', 'pd.read_csv', (['"""/home/apd10/DeepCTR-Torch/examples/criteo_sample.txt"""'], {}), "('/home/apd10/DeepCTR-Torch/examples/criteo_sample.txt')\n", (1046, 1102), True, 'import pandas as pd\n'), ((1533, 1567), 'sklearn.preprocessing.MinMaxScaler', 'MinMaxScaler', ([], {'feature_range': '(0, 1)'}), '(feature_range=(0, 1))\n', (1545, 1567), False, 'from sklearn.preprocessing import LabelEncoder, MinMaxScaler\n'), ((1662, 1709), 'numpy.load', 'np.load', (['"""/home/apd10/dlrm/dlrm/input/data.npz"""'], {}), "('/home/apd10/dlrm/dlrm/input/data.npz')\n", (1669, 1709), True, 'import numpy as np\n'), ((1934, 1986), 'pandas.DataFrame', 'pd.DataFrame', (["handle['intF']"], {'columns': 'dense_features'}), "(handle['intF'], columns=dense_features)\n", (1946, 1986), True, 'import pandas as pd\n'), ((2005, 2058), 'pandas.DataFrame', 'pd.DataFrame', (["handle['catF']"], {'columns': 'sparse_features'}), "(handle['catF'], columns=sparse_features)\n", (2017, 2058), True, 'import pandas as pd\n'), ((2079, 2124), 'pandas.DataFrame', 'pd.DataFrame', (["handle['label']"], {'columns': 'target'}), "(handle['label'], columns=target)\n", (2091, 2124), True, 'import pandas as pd\n'), ((2141, 2183), 'pandas.concat', 'pd.concat', (['[labeldf, intdf, catdf]'], {'axis': '(1)'}), '([labeldf, intdf, catdf], axis=1)\n', (2150, 2183), True, 'import pandas as pd\n'), ((2841, 2853), 'yaml.load', 'yaml.load', (['f'], {}), '(f)\n', (2850, 2853), False, 'import yaml\n'), ((6995, 7020), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (7018, 7020), False, 'import torch\n'), ((1453, 1467), 'sklearn.preprocessing.LabelEncoder', 'LabelEncoder', ([], {}), '()\n', (1465, 1467), False, 'from sklearn.preprocessing import LabelEncoder, MinMaxScaler\n'), ((10104, 10133), 'pandas.DataFrame', 'pd.DataFrame', (['history.history'], {}), '(history.history)\n', (10116, 10133), True, 'import pandas as pd\n'), ((1852, 1903), 'numpy.load', 'np.load', (['"""/home/apd10/dlrm/dlrm/input/data.le2.npz"""'], {}), "('/home/apd10/dlrm/dlrm/input/data.le2.npz')\n", (1859, 1903), True, 'import numpy as np\n'), ((3896, 3914), 'deepctr_torch.inputs.DenseFeat', 'DenseFeat', (['feat', '(1)'], {}), '(feat, 1)\n', (3905, 3914), False, 'from deepctr_torch.inputs import SparseFeat, DenseFeat, get_feature_names\n'), ((4542, 4560), 'deepctr_torch.inputs.DenseFeat', 'DenseFeat', (['feat', '(1)'], {}), '(feat, 1)\n', (4551, 4560), False, 'from deepctr_torch.inputs import SparseFeat, DenseFeat, get_feature_names\n'), ((5044, 5076), 'numpy.load', 'np.load', (["lma_params['signature']"], {}), "(lma_params['signature'])\n", (5051, 5076), True, 'import numpy as np\n'), ((5733, 5748), 'torch.nn.ModuleList', 'nn.ModuleList', ([], {}), '()\n', (5746, 5748), False, 'from torch import nn\n'), ((5110, 5137), 'torch.from_numpy', 'torch.from_numpy', (['signature'], {}), '(signature)\n', (5126, 5137), False, 'import torch\n'), ((5491, 5509), 'deepctr_torch.inputs.DenseFeat', 'DenseFeat', (['feat', '(1)'], {}), '(feat, 1)\n', (5500, 5509), False, 'from deepctr_torch.inputs import SparseFeat, DenseFeat, get_feature_names\n'), ((5818, 5845), 'torch.nn.Linear', 'nn.Linear', (['ls[i]', 'ls[i + 1]'], {}), '(ls[i], ls[i + 1])\n', (5827, 5845), False, 'from torch import nn\n'), ((5874, 5883), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (5881, 5883), False, 'from torch import nn\n'), ((5978, 6009), 'torch.nn.Sequential', 'torch.nn.Sequential', (['*mlp_model'], {}), '(*mlp_model)\n', (5997, 6009), False, 'import torch\n'), ((6255, 6273), 'deepctr_torch.inputs.DenseFeat', 'DenseFeat', (['feat', '(1)'], {}), '(feat, 1)\n', (6264, 6273), False, 'from deepctr_torch.inputs import SparseFeat, DenseFeat, get_feature_names\n'), ((4238, 4264), 'numpy.sqrt', 'np.sqrt', (['(1 / embedding_dim)'], {}), '(1 / embedding_dim)\n', (4245, 4264), True, 'import numpy as np\n'), ((4205, 4231), 'numpy.sqrt', 'np.sqrt', (['(1 / embedding_dim)'], {}), '(1 / embedding_dim)\n', (4212, 4231), True, 'import numpy as np\n'), ((4926, 4952), 'numpy.sqrt', 'np.sqrt', (['(1 / embedding_dim)'], {}), '(1 / embedding_dim)\n', (4933, 4952), True, 'import numpy as np\n'), ((4893, 4919), 'numpy.sqrt', 'np.sqrt', (['(1 / embedding_dim)'], {}), '(1 / embedding_dim)\n', (4900, 4919), True, 'import numpy as np\n')]
|
import json
from datetime import timedelta
from glob import glob
from os.path import join, exists
import numpy as np
import pandas as pd
from grib2io import Grib2Message
from netCDF4 import Dataset, num2date
from scipy.interpolate import interp1d
from scipy.ndimage import gaussian_filter
from scipy.signal import fftconvolve
from scipy.spatial import cKDTree
from scipy.stats import gamma
from skimage.morphology import disk
from hagelslag.data.ModelOutput import ModelOutput
from hagelslag.util.make_proj_grids import read_arps_map_file, read_ncar_map_file, make_proj_grids
class EnsembleMemberProduct(object):
"""
This class loads machine learning forecasts for a single ensemble member and run and converts them to a gridded
field.
Args:
ensemble_name (str): name of the ensemble (e.g., HREF, SSEF, NCAR, etc.)
model_name (str): name of the machine learning model
member (str): name of the ensemble member
run_date (`datetime.datetime`): date of the initial time step of the model run
variable (str): name of the variable used for object-extraction
start_date (`datetime.datetime`): Start of the model extraction period
end_date (`datetime.datetime`): End of the model extraction period
path (str): Path to model output
single_step (bool): Whether or not the model output is stored in single files or multiple files.
size_distribution_training_path (str): Path to size distribution percentiles
watershed_var (str): Name of variable used for object extraction.
map_file (str or None): Map projection file for given ensemble type.
condition_model_name (str): Name of the condition ML model being used if different from model_name
condition_threshold (float): Probability threshold for including or excluding storms.
"""
def __init__(self, ensemble_name, model_name, member, run_date, variable, start_date, end_date, path, single_step,
size_distribution_training_path, watershed_var, map_file=None,
condition_model_name=None, condition_threshold=0.5):
self.ensemble_name = ensemble_name
self.model_name = model_name
self.member = member
self.run_date = run_date
self.variable = variable
self.start_date = start_date
self.end_date = end_date
self.times = pd.date_range(start=self.start_date, end=self.end_date, freq="1H")
self.forecast_hours = (self.times - self.run_date).astype('timedelta64[h]').values
self.path = path
self.single_step = single_step
self.size_distribution_training_path = size_distribution_training_path
self.watershed_var = watershed_var
self.track_forecasts = None
self.data = None
self.map_file = map_file
self.proj_dict = None
self.grid_dict = None
self.mapping_data = None
if condition_model_name is None:
self.condition_model_name = model_name
else:
self.condition_model_name = condition_model_name
self.condition_threshold = condition_threshold
self.percentiles = None
self.num_samples = None
self.percentile_data = None
if self.map_file is not None:
if self.map_file[-3:] == "map":
self.proj_dict, self.grid_dict = read_arps_map_file(self.map_file)
else:
self.proj_dict, self.grid_dict = read_ncar_map_file(self.map_file)
self.mapping_data = make_proj_grids(self.proj_dict, self.grid_dict)
self.units = ""
self.nc_patches = None
self.hail_forecast_table = None
def load_data(self, num_samples=1000, percentiles=None):
"""
Load data from forecast json files and map forecasts to grid with percentile method.
Args:
num_samples: Number of random samples at each grid point
percentiles: Which percentiles to extract from the random samples
Returns:
"""
self.percentiles = percentiles
self.num_samples = num_samples
if self.model_name.lower() in ["wrf"]:
mo = ModelOutput(self.ensemble_name, self.member, self.run_date, self.variable,
self.start_date, self.end_date, self.path, self.map_file, self.single_step)
mo.load_data()
self.data = mo.data[:]
if mo.units == "m":
self.data *= 1000
self.units = "mm"
else:
self.units = mo.units
else:
if self.track_forecasts is None:
self.load_track_data()
self.units = "mm"
self.data = np.zeros((self.forecast_hours.size,
self.mapping_data["lon"].shape[0],
self.mapping_data["lon"].shape[1]), dtype=np.float32)
if self.percentiles is not None:
self.percentile_data = np.zeros([len(self.percentiles)] + list(self.data.shape))
full_condition_name = "condition_" + self.condition_model_name.replace(" ", "-")
dist_model_name = "dist" + "_" + self.model_name.replace(" ", "-")
for track_forecast in self.track_forecasts:
times = track_forecast["properties"]["times"]
for s, step in enumerate(track_forecast["features"]):
forecast_params = step["properties"][dist_model_name]
if self.condition_model_name is not None:
condition = step["properties"][full_condition_name]
else:
condition = None
forecast_time = self.run_date + timedelta(hours=times[s])
if forecast_time in self.times:
t = np.where(self.times == forecast_time)[0][0]
mask = np.array(step["properties"]["masks"], dtype=int).ravel()
rankings = np.argsort(np.array(step["properties"]["timesteps"]).ravel()[mask == 1])
i = np.array(step["properties"]["i"], dtype=int).ravel()[mask == 1][rankings]
j = np.array(step["properties"]["j"], dtype=int).ravel()[mask == 1][rankings]
if rankings.size > 0 and forecast_params[0] > 0.1 and 1 < forecast_params[2] < 100:
raw_samples = np.sort(gamma.rvs(forecast_params[0], loc=forecast_params[1],
scale=forecast_params[2],
size=(num_samples, rankings.size)),
axis=1)
if self.percentiles is None:
samples = raw_samples.mean(axis=0)
if condition >= self.condition_threshold:
self.data[t, i, j] = samples
else:
for p, percentile in enumerate(self.percentiles):
if percentile != "mean":
if condition >= self.condition_threshold:
self.percentile_data[p, t, i, j] = np.percentile(raw_samples, percentile,
axis=0)
else:
if condition >= self.condition_threshold:
self.percentile_data[p, t, i, j] = np.mean(raw_samples, axis=0)
samples = raw_samples.mean(axis=0)
if condition >= self.condition_threshold:
self.data[t, i, j] = samples
def load_track_data(self):
"""
Load track forecats from json files and input info to self.track_forecasts.
"""
run_date_str = self.run_date.strftime("%Y%m%d")
print("Load track forecasts {0} {1}".format(self.ensemble_name, run_date_str))
track_files = sorted(glob(self.path + "/".join([run_date_str, self.member]) + "/*.json"))
if len(track_files) > 0:
self.track_forecasts = []
for track_file in track_files:
tfo = open(track_file)
self.track_forecasts.append(json.load(tfo))
tfo.close()
else:
self.track_forecasts = []
def load_forecast_csv_data(self, csv_path):
"""
Load track forecast csv files with pandas.
Args:
csv_path: Path to csv files.
Returns:
"""
forecast_file = join(csv_path, "hail_forecasts_{0}_{1}_{2}.csv".format(self.ensemble_name,
self.member,
self.run_date.strftime("%Y%m%d-%H%M")))
if exists(forecast_file):
self.hail_forecast_table = pd.read_csv(forecast_file)
return
def load_forecast_netcdf_data(self, nc_path):
"""
Load netCDF patches for each storm.
Args:
nc_path: Path to forecast netCDF files.
"""
nc_file = join(nc_path, "{0}_{1}_{2}_model_patches.nc".format(self.ensemble_name,
self.run_date.strftime("%Y%m%d-%H%M"),
self.member))
if exists(nc_file):
nc_patches = Dataset(nc_file)
nc_times = pd.DatetimeIndex(num2date(nc_patches.variables["time"][:],
nc_patches.variables["time"].units))
time_indices = np.isin(nc_times, self.times)
self.nc_patches = dict()
self.nc_patches["time"] = nc_times[time_indices]
self.nc_patches["forecast_hour"] = nc_patches.variables["time"][time_indices]
self.nc_patches["obj_values"] = nc_patches.variables[nc_patches.object_variable + "_curr"][time_indices]
self.nc_patches["masks"] = nc_patches.variables["masks"][time_indices]
self.nc_patches["i"] = nc_patches.variables["i"][time_indices]
self.nc_patches["j"] = nc_patches.variables["j"][time_indices]
nc_patches.close()
print(nc_file)
else:
print('no {0} {1} netCDF4 file'.format(self.member, self.run_date.strftime("%Y%m%d")))
self.nc_patches = None
return
return
def quantile_match(self):
"""
For each storm object, get the percentiles of the enhanced watershed variable field relative to the training
climatology of that variable. Then, extract the hail sizes at those percentiles from the predicted hail size
distribution for each storm. If the probability of hail occurring exceeds the model's condition
threshold, then the storm is written to the data grid.
"""
if self.nc_patches is None:
self.data = None
return
mask_indices = np.where(self.nc_patches["masks"] == 1)
obj_values = self.nc_patches["obj_values"][mask_indices]
obj_values = np.array(obj_values)
percentiles = np.linspace(0.1, 99.9, 100)
try:
filename = join(self.size_distribution_training_path,
'{0}_{1}_{2}_Size_Distribution.csv'.format(self.ensemble_name,
self.watershed_var,
self.member))
if not exists(filename):
filename = join(self.size_distribution_training_path,
'{0}_{1}_Size_Distribution.csv'.format(self.ensemble_name,
self.watershed_var))
train_period_obj_per_vals = pd.read_csv(filename)
train_period_obj_per_vals = train_period_obj_per_vals.loc[:, "Obj_Values"].values
per_func = interp1d(train_period_obj_per_vals, percentiles / 100.0,
bounds_error=False, fill_value=(0.1, 99.9))
except FileNotFoundError:
obj_per_vals = np.percentile(obj_values, percentiles)
per_func = interp1d(obj_per_vals, percentiles / 100.0, bounds_error=False, fill_value=(0.1, 99.9))
obj_percentiles = np.zeros(self.nc_patches["masks"].shape)
obj_percentiles[mask_indices] = per_func(obj_values)
obj_hail_sizes = np.zeros(obj_percentiles.shape)
model_name = self.model_name.replace(" ", "-")
self.units = "mm"
self.data = np.zeros((self.forecast_hours.size,
self.mapping_data["lon"].shape[0],
self.mapping_data["lon"].shape[1]), dtype=np.float32)
sh = self.forecast_hours.min()
for p in range(obj_hail_sizes.shape[0]):
if self.hail_forecast_table.loc[p, self.condition_model_name.replace(" ", "-") + "_conditionthresh"] > 0.5:
patch_mask = np.where(self.nc_patches["masks"][p] == 1)
obj_hail_sizes[p,
patch_mask[0],
patch_mask[1]] = gamma.ppf(obj_percentiles[p,
patch_mask[0],
patch_mask[1]],
self.hail_forecast_table.loc[p,
model_name + "_shape"],
self.hail_forecast_table.loc[p,
model_name + "_location"],
self.hail_forecast_table.loc[p,
model_name + "_scale"])
self.data[self.nc_patches["forecast_hour"][p] - sh,
self.nc_patches["i"][p, patch_mask[0], patch_mask[1]],
self.nc_patches["j"][p, patch_mask[0], patch_mask[1]]] = obj_hail_sizes[p, patch_mask[0],
patch_mask[1]]
return
def neighborhood_probability(self, threshold, radius):
"""
Calculate a probability based on the number of grid points in an area that exceed a threshold.
Args:
threshold: intensity threshold
radius: radius of neighborhood
Returns:
"""
weights = disk(radius, dtype=np.uint8)
thresh_data = np.zeros(self.data.shape[1:], dtype=np.uint8)
neighbor_prob = np.zeros(self.data.shape, dtype=np.float32)
for t in np.arange(self.data.shape[0]):
thresh_data[self.data[t] >= threshold] = 1
maximized = fftconvolve(thresh_data, weights, mode="same")
maximized[maximized > 1] = 1
maximized[maximized < 1] = 0
neighbor_prob[t] = fftconvolve(maximized, weights, mode="same")
thresh_data[:] = 0
neighbor_prob[neighbor_prob < 1] = 0
neighbor_prob /= weights.sum()
return neighbor_prob
def period_max_neighborhood_probability(self, threshold, radius):
"""
Aggregates gridded hail sizes across time and generates neighborhood probability that maximizes threshold
Args:
threshold (float): intensity threshold
radius (int): radius of influence in grid points.
Returns:
"""
weights = disk(radius, dtype=np.uint8)
thresh_data = np.zeros(self.data.shape[1:], dtype=np.uint8)
thresh_data[self.data.max(axis=0) >= threshold] = 1
maximized = fftconvolve(thresh_data, weights, mode="same")
maximized[maximized > 1] = 1
maximized[maximized < 1] = 0
neighborhood_prob = fftconvolve(maximized, weights, mode="same")
neighborhood_prob[neighborhood_prob < 1] = 0
neighborhood_prob /= weights.sum()
return neighborhood_prob
def period_surrogate_severe_prob(self, threshold, radius, sigma, stagger):
"""
Calculate surrogate severe probability for a member using method from Sobash et al. (2011).
Args:
threshold: intensity threshold
radius: Radius in grid cells for neighborhood aggregation
sigma: standard deviation of Gaussian smoother
stagger: how many grid points to skip when reducing grid size.
Returns:
surrogate_grid: grid with single member storm surrogate probabilities.
"""
i_grid, j_grid = np.indices(self.data.shape[1:])
max_data = self.data.max(axis=0)
max_points = np.array(np.where(max_data >= threshold)).T
max_tree = cKDTree(max_points)
stagger_points = np.vstack((i_grid[::stagger, ::stagger].ravel(), j_grid[::stagger, ::stagger].ravel())).T
valid_stagger_points = np.zeros(stagger_points.shape[0])
stagger_tree = cKDTree(stagger_points)
hit_points = np.unique(np.concatenate(max_tree.query_ball_tree(stagger_tree, radius)))
valid_stagger_points[hit_points] += 1
surrogate_grid = valid_stagger_points.reshape(i_grid[::stagger, ::stagger].shape)
surrogate_grid = gaussian_filter(surrogate_grid, sigma)
return surrogate_grid
def encode_grib2_percentile(self):
"""
Encodes member percentile data to GRIB2 format.
Returns:
Series of GRIB2 messages
"""
if self.data is None:
return None
lscale = 1e6
grib_id_start = [7, 0, 14, 14, 2]
gdsinfo = np.array([0, np.product(self.data.shape[-2:]), 0, 0, 30], dtype=np.int32)
lon_0 = self.proj_dict["lon_0"]
sw_lon = self.grid_dict["sw_lon"]
if lon_0 < 0:
lon_0 += 360
if sw_lon < 0:
sw_lon += 360
gdtmp1 = [1, 0, self.proj_dict['a'], 0, float(self.proj_dict['a']), 0, float(self.proj_dict['b']),
self.data.shape[-1], self.data.shape[-2], self.grid_dict["sw_lat"] * lscale,
sw_lon * lscale, 0, self.proj_dict["lat_0"] * lscale,
lon_0 * lscale,
self.grid_dict["dx"] * 1e3, self.grid_dict["dy"] * 1e3, 0b00000000, 0b01000000,
self.proj_dict["lat_1"] * lscale,
self.proj_dict["lat_2"] * lscale, -90 * lscale, 0]
pdtmp1 = np.array([1, # parameter category Moisture
31, # parameter number Hail
4, # Type of generating process Ensemble Forecast
0, # Background generating process identifier
31, # Generating process or model from NCEP
0, # Hours after reference time data cutoff
0, # Minutes after reference time data cutoff
1, # Forecast time units Hours
0, # Forecast time
1, # Type of first fixed surface Ground
1, # Scale value of first fixed surface
0, # Value of first fixed surface
1, # Type of second fixed surface
1, # Scale value of 2nd fixed surface
0, # Value of 2nd fixed surface
0, # Derived forecast type
self.num_samples # Number of ensemble members
], dtype=np.int32)
grib_objects = pd.Series(index=self.times, data=[None] * self.times.size, dtype=object)
drtmp1 = np.array([0, 0, 4, 8, 0], dtype=np.int32)
for t, time in enumerate(self.times):
time_list = list(self.run_date.utctimetuple()[0:6])
if grib_objects[time] is None:
# grib_objects[time] = Grib2Encode(0, np.array(grib_id_start + time_list + [2, 1], dtype=np.int32))
grib_objects[time] = Grib2Message(discipline=0,
idsect=np.array(grib_id_start + time_list + [2, 1], dtype=np.int32))
grib_objects[time].addgrid(gdsinfo, gdtmp1)
pdtmp1[8] = (time.to_pydatetime() - self.run_date).total_seconds() / 3600.0
data = self.percentile_data[:, t] / 1000.0
masked_data = np.ma.array(data, mask=data <= 0)
for p, percentile in enumerate(self.percentiles):
print("GRIB {3} Percentile {0}. Max: {1} Min: {2}".format(percentile,
masked_data[p].max(),
masked_data[p].min(),
time))
if percentile in range(1, 100):
pdtmp1[-2] = percentile
grib_objects[time].addfield(6, pdtmp1[:-1], 0, drtmp1, masked_data[p])
else:
pdtmp1[-2] = 0
grib_objects[time].addfield(2, pdtmp1, 0, drtmp1, masked_data[p])
return grib_objects
def encode_grib2_data(self):
"""
Encodes deterministic member predictions to GRIB2 format.
Returns:
Series of GRIB2 messages
"""
if self.data is None:
return None
lscale = 1e6
grib_id_start = [7, 0, 14, 14, 2]
gdsinfo = np.array([0, np.product(self.data.shape[-2:]), 0, 0, 30], dtype=np.int32)
lon_0 = self.proj_dict["lon_0"]
sw_lon = self.grid_dict["sw_lon"]
if lon_0 < 0:
lon_0 += 360
if sw_lon < 0:
sw_lon += 360
gdtmp1 = [1, 0, self.proj_dict['a'], 0, float(self.proj_dict['a']), 0, float(self.proj_dict['b']),
self.data.shape[-1], self.data.shape[-2], self.grid_dict["sw_lat"] * lscale,
sw_lon * lscale, 0, self.proj_dict["lat_0"] * lscale,
lon_0 * lscale,
self.grid_dict["dx"] * 1e3, self.grid_dict["dy"] * 1e3, 0b00000000, 0b01000000,
self.proj_dict["lat_1"] * lscale,
self.proj_dict["lat_2"] * lscale, -90 * lscale, 0]
pdtmp1 = np.array([1, # parameter category Moisture
31, # parameter number Hail
4, # Type of generating process Ensemble Forecast
0, # Background generating process identifier
31, # Generating process or model from NCEP
0, # Hours after reference time data cutoff
0, # Minutes after reference time data cutoff
1, # Forecast time units Hours
0, # Forecast time
1, # Type of first fixed surface Ground
1, # Scale value of first fixed surface
0, # Value of first fixed surface
1, # Type of second fixed surface
1, # Scale value of 2nd fixed surface
0, # Value of 2nd fixed surface
0, # Derived forecast type
1 # Number of ensemble members
], dtype=np.int32)
grib_objects = pd.Series(index=self.times, data=[None] * self.times.size, dtype=object)
drtmp1 = np.array([0, 0, 4, 8, 0], dtype=np.int32)
for t, time in enumerate(self.times):
time_list = list(self.run_date.utctimetuple()[0:6])
if grib_objects[time] is None:
# grib_objects[time] = Grib2Encode(0, np.array(grib_id_start + time_list + [2, 1], dtype=np.int32))
grib_objects[time] = Grib2Message(discipline=0,
idsect=np.array(grib_id_start + time_list + [2, 1], dtype=np.int32))
grib_objects[time].addgrid(gdsinfo, gdtmp1)
pdtmp1[8] = (time.to_pydatetime() - self.run_date).total_seconds() / 3600.0
data = self.data[t] / 1000.0
data[np.isnan(data)] = 0
masked_data = np.ma.array(data, mask=data <= 0)
pdtmp1[-2] = 0
grib_objects[time].addfield(1, pdtmp1, 0, drtmp1, masked_data)
return grib_objects
def write_grib2_files(self, grib_objects, path):
"""
Write a grib2 object to disk.
Args:
grib_objects: A Series of grib objects indexed by forecast time
path: Path where grib files are written.
"""
for t, time in enumerate(self.times.to_pydatetime()):
grib_objects[time].end()
filename = join(path, "{0}_{1}_{2}_{3}_{4}.grib2".format(self.ensemble_name,
self.member,
self.model_name.replace(" ", "-"),
self.variable,
self.run_date.strftime("%Y%m%d%H") +
"f{0:02d}".format(self.forecast_hours[t])
))
with open(filename, "wb") as fo:
fo.write(grib_objects[time]._msg)
|
[
"numpy.isin",
"hagelslag.util.make_proj_grids.read_arps_map_file",
"scipy.stats.gamma.rvs",
"pandas.read_csv",
"numpy.isnan",
"numpy.product",
"numpy.mean",
"numpy.arange",
"scipy.spatial.cKDTree",
"scipy.signal.fftconvolve",
"scipy.interpolate.interp1d",
"netCDF4.Dataset",
"scipy.ndimage.gaussian_filter",
"os.path.exists",
"scipy.stats.gamma.ppf",
"hagelslag.data.ModelOutput.ModelOutput",
"datetime.timedelta",
"numpy.linspace",
"pandas.date_range",
"hagelslag.util.make_proj_grids.make_proj_grids",
"hagelslag.util.make_proj_grids.read_ncar_map_file",
"numpy.percentile",
"numpy.indices",
"pandas.Series",
"json.load",
"numpy.zeros",
"skimage.morphology.disk",
"numpy.ma.array",
"numpy.where",
"numpy.array",
"netCDF4.num2date"
] |
[((2395, 2461), 'pandas.date_range', 'pd.date_range', ([], {'start': 'self.start_date', 'end': 'self.end_date', 'freq': '"""1H"""'}), "(start=self.start_date, end=self.end_date, freq='1H')\n", (2408, 2461), True, 'import pandas as pd\n'), ((9143, 9164), 'os.path.exists', 'exists', (['forecast_file'], {}), '(forecast_file)\n', (9149, 9164), False, 'from os.path import join, exists\n'), ((9728, 9743), 'os.path.exists', 'exists', (['nc_file'], {}), '(nc_file)\n', (9734, 9743), False, 'from os.path import join, exists\n'), ((11355, 11394), 'numpy.where', 'np.where', (["(self.nc_patches['masks'] == 1)"], {}), "(self.nc_patches['masks'] == 1)\n", (11363, 11394), True, 'import numpy as np\n'), ((11481, 11501), 'numpy.array', 'np.array', (['obj_values'], {}), '(obj_values)\n', (11489, 11501), True, 'import numpy as np\n'), ((11524, 11551), 'numpy.linspace', 'np.linspace', (['(0.1)', '(99.9)', '(100)'], {}), '(0.1, 99.9, 100)\n', (11535, 11551), True, 'import numpy as np\n'), ((12739, 12779), 'numpy.zeros', 'np.zeros', (["self.nc_patches['masks'].shape"], {}), "(self.nc_patches['masks'].shape)\n", (12747, 12779), True, 'import numpy as np\n'), ((12866, 12897), 'numpy.zeros', 'np.zeros', (['obj_percentiles.shape'], {}), '(obj_percentiles.shape)\n', (12874, 12897), True, 'import numpy as np\n'), ((12999, 13128), 'numpy.zeros', 'np.zeros', (["(self.forecast_hours.size, self.mapping_data['lon'].shape[0], self.\n mapping_data['lon'].shape[1])"], {'dtype': 'np.float32'}), "((self.forecast_hours.size, self.mapping_data['lon'].shape[0], self\n .mapping_data['lon'].shape[1]), dtype=np.float32)\n", (13007, 13128), True, 'import numpy as np\n'), ((15124, 15152), 'skimage.morphology.disk', 'disk', (['radius'], {'dtype': 'np.uint8'}), '(radius, dtype=np.uint8)\n', (15128, 15152), False, 'from skimage.morphology import disk\n'), ((15175, 15220), 'numpy.zeros', 'np.zeros', (['self.data.shape[1:]'], {'dtype': 'np.uint8'}), '(self.data.shape[1:], dtype=np.uint8)\n', (15183, 15220), True, 'import numpy as np\n'), ((15245, 15288), 'numpy.zeros', 'np.zeros', (['self.data.shape'], {'dtype': 'np.float32'}), '(self.data.shape, dtype=np.float32)\n', (15253, 15288), True, 'import numpy as np\n'), ((15306, 15335), 'numpy.arange', 'np.arange', (['self.data.shape[0]'], {}), '(self.data.shape[0])\n', (15315, 15335), True, 'import numpy as np\n'), ((16139, 16167), 'skimage.morphology.disk', 'disk', (['radius'], {'dtype': 'np.uint8'}), '(radius, dtype=np.uint8)\n', (16143, 16167), False, 'from skimage.morphology import disk\n'), ((16190, 16235), 'numpy.zeros', 'np.zeros', (['self.data.shape[1:]'], {'dtype': 'np.uint8'}), '(self.data.shape[1:], dtype=np.uint8)\n', (16198, 16235), True, 'import numpy as np\n'), ((16316, 16362), 'scipy.signal.fftconvolve', 'fftconvolve', (['thresh_data', 'weights'], {'mode': '"""same"""'}), "(thresh_data, weights, mode='same')\n", (16327, 16362), False, 'from scipy.signal import fftconvolve\n'), ((16465, 16509), 'scipy.signal.fftconvolve', 'fftconvolve', (['maximized', 'weights'], {'mode': '"""same"""'}), "(maximized, weights, mode='same')\n", (16476, 16509), False, 'from scipy.signal import fftconvolve\n'), ((17231, 17262), 'numpy.indices', 'np.indices', (['self.data.shape[1:]'], {}), '(self.data.shape[1:])\n', (17241, 17262), True, 'import numpy as np\n'), ((17388, 17407), 'scipy.spatial.cKDTree', 'cKDTree', (['max_points'], {}), '(max_points)\n', (17395, 17407), False, 'from scipy.spatial import cKDTree\n'), ((17554, 17587), 'numpy.zeros', 'np.zeros', (['stagger_points.shape[0]'], {}), '(stagger_points.shape[0])\n', (17562, 17587), True, 'import numpy as np\n'), ((17611, 17634), 'scipy.spatial.cKDTree', 'cKDTree', (['stagger_points'], {}), '(stagger_points)\n', (17618, 17634), False, 'from scipy.spatial import cKDTree\n'), ((17891, 17929), 'scipy.ndimage.gaussian_filter', 'gaussian_filter', (['surrogate_grid', 'sigma'], {}), '(surrogate_grid, sigma)\n', (17906, 17929), False, 'from scipy.ndimage import gaussian_filter\n'), ((19066, 19165), 'numpy.array', 'np.array', (['[1, 31, 4, 0, 31, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, self.num_samples]'], {'dtype': 'np.int32'}), '([1, 31, 4, 0, 31, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, self.\n num_samples], dtype=np.int32)\n', (19074, 19165), True, 'import numpy as np\n'), ((20226, 20298), 'pandas.Series', 'pd.Series', ([], {'index': 'self.times', 'data': '([None] * self.times.size)', 'dtype': 'object'}), '(index=self.times, data=[None] * self.times.size, dtype=object)\n', (20235, 20298), True, 'import pandas as pd\n'), ((20316, 20357), 'numpy.array', 'np.array', (['[0, 0, 4, 8, 0]'], {'dtype': 'np.int32'}), '([0, 0, 4, 8, 0], dtype=np.int32)\n', (20324, 20357), True, 'import numpy as np\n'), ((22958, 23037), 'numpy.array', 'np.array', (['[1, 31, 4, 0, 31, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1]'], {'dtype': 'np.int32'}), '([1, 31, 4, 0, 31, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1], dtype=np.int32)\n', (22966, 23037), True, 'import numpy as np\n'), ((24103, 24175), 'pandas.Series', 'pd.Series', ([], {'index': 'self.times', 'data': '([None] * self.times.size)', 'dtype': 'object'}), '(index=self.times, data=[None] * self.times.size, dtype=object)\n', (24112, 24175), True, 'import pandas as pd\n'), ((24193, 24234), 'numpy.array', 'np.array', (['[0, 0, 4, 8, 0]'], {'dtype': 'np.int32'}), '([0, 0, 4, 8, 0], dtype=np.int32)\n', (24201, 24234), True, 'import numpy as np\n'), ((3546, 3593), 'hagelslag.util.make_proj_grids.make_proj_grids', 'make_proj_grids', (['self.proj_dict', 'self.grid_dict'], {}), '(self.proj_dict, self.grid_dict)\n', (3561, 3593), False, 'from hagelslag.util.make_proj_grids import read_arps_map_file, read_ncar_map_file, make_proj_grids\n'), ((4190, 4344), 'hagelslag.data.ModelOutput.ModelOutput', 'ModelOutput', (['self.ensemble_name', 'self.member', 'self.run_date', 'self.variable', 'self.start_date', 'self.end_date', 'self.path', 'self.map_file', 'self.single_step'], {}), '(self.ensemble_name, self.member, self.run_date, self.variable,\n self.start_date, self.end_date, self.path, self.map_file, self.single_step)\n', (4201, 4344), False, 'from hagelslag.data.ModelOutput import ModelOutput\n'), ((4740, 4869), 'numpy.zeros', 'np.zeros', (["(self.forecast_hours.size, self.mapping_data['lon'].shape[0], self.\n mapping_data['lon'].shape[1])"], {'dtype': 'np.float32'}), "((self.forecast_hours.size, self.mapping_data['lon'].shape[0], self\n .mapping_data['lon'].shape[1]), dtype=np.float32)\n", (4748, 4869), True, 'import numpy as np\n'), ((9205, 9231), 'pandas.read_csv', 'pd.read_csv', (['forecast_file'], {}), '(forecast_file)\n', (9216, 9231), True, 'import pandas as pd\n'), ((9770, 9786), 'netCDF4.Dataset', 'Dataset', (['nc_file'], {}), '(nc_file)\n', (9777, 9786), False, 'from netCDF4 import Dataset, num2date\n'), ((9982, 10011), 'numpy.isin', 'np.isin', (['nc_times', 'self.times'], {}), '(nc_times, self.times)\n', (9989, 10011), True, 'import numpy as np\n'), ((12229, 12250), 'pandas.read_csv', 'pd.read_csv', (['filename'], {}), '(filename)\n', (12240, 12250), True, 'import pandas as pd\n'), ((12368, 12472), 'scipy.interpolate.interp1d', 'interp1d', (['train_period_obj_per_vals', '(percentiles / 100.0)'], {'bounds_error': '(False)', 'fill_value': '(0.1, 99.9)'}), '(train_period_obj_per_vals, percentiles / 100.0, bounds_error=False,\n fill_value=(0.1, 99.9))\n', (12376, 12472), False, 'from scipy.interpolate import interp1d\n'), ((15416, 15462), 'scipy.signal.fftconvolve', 'fftconvolve', (['thresh_data', 'weights'], {'mode': '"""same"""'}), "(thresh_data, weights, mode='same')\n", (15427, 15462), False, 'from scipy.signal import fftconvolve\n'), ((15576, 15620), 'scipy.signal.fftconvolve', 'fftconvolve', (['maximized', 'weights'], {'mode': '"""same"""'}), "(maximized, weights, mode='same')\n", (15587, 15620), False, 'from scipy.signal import fftconvolve\n'), ((21039, 21072), 'numpy.ma.array', 'np.ma.array', (['data'], {'mask': '(data <= 0)'}), '(data, mask=data <= 0)\n', (21050, 21072), True, 'import numpy as np\n'), ((24939, 24972), 'numpy.ma.array', 'np.ma.array', (['data'], {'mask': '(data <= 0)'}), '(data, mask=data <= 0)\n', (24950, 24972), True, 'import numpy as np\n'), ((3379, 3412), 'hagelslag.util.make_proj_grids.read_arps_map_file', 'read_arps_map_file', (['self.map_file'], {}), '(self.map_file)\n', (3397, 3412), False, 'from hagelslag.util.make_proj_grids import read_arps_map_file, read_ncar_map_file, make_proj_grids\n'), ((3480, 3513), 'hagelslag.util.make_proj_grids.read_ncar_map_file', 'read_ncar_map_file', (['self.map_file'], {}), '(self.map_file)\n', (3498, 3513), False, 'from hagelslag.util.make_proj_grids import read_arps_map_file, read_ncar_map_file, make_proj_grids\n'), ((9827, 9904), 'netCDF4.num2date', 'num2date', (["nc_patches.variables['time'][:]", "nc_patches.variables['time'].units"], {}), "(nc_patches.variables['time'][:], nc_patches.variables['time'].units)\n", (9835, 9904), False, 'from netCDF4 import Dataset, num2date\n'), ((11918, 11934), 'os.path.exists', 'exists', (['filename'], {}), '(filename)\n', (11924, 11934), False, 'from os.path import join, exists\n'), ((12562, 12600), 'numpy.percentile', 'np.percentile', (['obj_values', 'percentiles'], {}), '(obj_values, percentiles)\n', (12575, 12600), True, 'import numpy as np\n'), ((12624, 12716), 'scipy.interpolate.interp1d', 'interp1d', (['obj_per_vals', '(percentiles / 100.0)'], {'bounds_error': '(False)', 'fill_value': '(0.1, 99.9)'}), '(obj_per_vals, percentiles / 100.0, bounds_error=False, fill_value=\n (0.1, 99.9))\n', (12632, 12716), False, 'from scipy.interpolate import interp1d\n'), ((13421, 13463), 'numpy.where', 'np.where', (["(self.nc_patches['masks'][p] == 1)"], {}), "(self.nc_patches['masks'][p] == 1)\n", (13429, 13463), True, 'import numpy as np\n'), ((13592, 13837), 'scipy.stats.gamma.ppf', 'gamma.ppf', (['obj_percentiles[p, patch_mask[0], patch_mask[1]]', "self.hail_forecast_table.loc[p, model_name + '_shape']", "self.hail_forecast_table.loc[p, model_name + '_location']", "self.hail_forecast_table.loc[p, model_name + '_scale']"], {}), "(obj_percentiles[p, patch_mask[0], patch_mask[1]], self.\n hail_forecast_table.loc[p, model_name + '_shape'], self.\n hail_forecast_table.loc[p, model_name + '_location'], self.\n hail_forecast_table.loc[p, model_name + '_scale'])\n", (13601, 13837), False, 'from scipy.stats import gamma\n'), ((17334, 17365), 'numpy.where', 'np.where', (['(max_data >= threshold)'], {}), '(max_data >= threshold)\n', (17342, 17365), True, 'import numpy as np\n'), ((18283, 18315), 'numpy.product', 'np.product', (['self.data.shape[-2:]'], {}), '(self.data.shape[-2:])\n', (18293, 18315), True, 'import numpy as np\n'), ((22175, 22207), 'numpy.product', 'np.product', (['self.data.shape[-2:]'], {}), '(self.data.shape[-2:])\n', (22185, 22207), True, 'import numpy as np\n'), ((24893, 24907), 'numpy.isnan', 'np.isnan', (['data'], {}), '(data)\n', (24901, 24907), True, 'import numpy as np\n'), ((8527, 8541), 'json.load', 'json.load', (['tfo'], {}), '(tfo)\n', (8536, 8541), False, 'import json\n'), ((5767, 5792), 'datetime.timedelta', 'timedelta', ([], {'hours': 'times[s]'}), '(hours=times[s])\n', (5776, 5792), False, 'from datetime import timedelta\n'), ((20748, 20808), 'numpy.array', 'np.array', (['(grib_id_start + time_list + [2, 1])'], {'dtype': 'np.int32'}), '(grib_id_start + time_list + [2, 1], dtype=np.int32)\n', (20756, 20808), True, 'import numpy as np\n'), ((24625, 24685), 'numpy.array', 'np.array', (['(grib_id_start + time_list + [2, 1])'], {'dtype': 'np.int32'}), '(grib_id_start + time_list + [2, 1], dtype=np.int32)\n', (24633, 24685), True, 'import numpy as np\n'), ((5873, 5910), 'numpy.where', 'np.where', (['(self.times == forecast_time)'], {}), '(self.times == forecast_time)\n', (5881, 5910), True, 'import numpy as np\n'), ((5948, 5996), 'numpy.array', 'np.array', (["step['properties']['masks']"], {'dtype': 'int'}), "(step['properties']['masks'], dtype=int)\n", (5956, 5996), True, 'import numpy as np\n'), ((6475, 6594), 'scipy.stats.gamma.rvs', 'gamma.rvs', (['forecast_params[0]'], {'loc': 'forecast_params[1]', 'scale': 'forecast_params[2]', 'size': '(num_samples, rankings.size)'}), '(forecast_params[0], loc=forecast_params[1], scale=forecast_params\n [2], size=(num_samples, rankings.size))\n', (6484, 6594), False, 'from scipy.stats import gamma\n'), ((6051, 6092), 'numpy.array', 'np.array', (["step['properties']['timesteps']"], {}), "(step['properties']['timesteps'])\n", (6059, 6092), True, 'import numpy as np\n'), ((6141, 6185), 'numpy.array', 'np.array', (["step['properties']['i']"], {'dtype': 'int'}), "(step['properties']['i'], dtype=int)\n", (6149, 6185), True, 'import numpy as np\n'), ((6243, 6287), 'numpy.array', 'np.array', (["step['properties']['j']"], {'dtype': 'int'}), "(step['properties']['j'], dtype=int)\n", (6251, 6287), True, 'import numpy as np\n'), ((7370, 7416), 'numpy.percentile', 'np.percentile', (['raw_samples', 'percentile'], {'axis': '(0)'}), '(raw_samples, percentile, axis=0)\n', (7383, 7416), True, 'import numpy as np\n'), ((7713, 7741), 'numpy.mean', 'np.mean', (['raw_samples'], {'axis': '(0)'}), '(raw_samples, axis=0)\n', (7720, 7741), True, 'import numpy as np\n')]
|
import os, argparse
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import f1_score
def softmax_curvepoints(result_file, thresh, ood_ncls, num_rand):
assert os.path.exists(result_file), "File not found! Run baseline_i3d_softmax.py first!"
# load the testing results
results = np.load(result_file, allow_pickle=True)
ind_softmax = results['ind_softmax'] # (N1, C)
ood_softmax = results['ood_softmax'] # (N2, C)
ind_labels = results['ind_label'] # (N1,)
ood_labels = results['ood_label'] # (N2,)
ind_ncls = ind_softmax.shape[1]
ind_results = np.argmax(ind_softmax, axis=1)
ood_results = np.argmax(ood_softmax, axis=1)
ind_conf = np.max(ind_softmax, axis=1)
ood_conf = np.max(ood_softmax, axis=1)
ind_results[ind_conf < thresh] = ind_ncls # incorrect rejection
# open set F1 score (multi-class)
macro_F1 = f1_score(ind_labels, ind_results, average='macro')
macro_F1_list = [macro_F1 * 100]
openness_list = [0]
for n in range(ood_ncls):
ncls_novel = n + 1
openness = (1 - np.sqrt((2 * ind_ncls) / (2 * ind_ncls + ncls_novel))) * 100
openness_list.append(openness)
# randoml select the subset of ood samples
macro_F1_multi = np.zeros((num_rand), dtype=np.float32)
for m in range(num_rand):
cls_select = np.random.choice(ood_ncls, ncls_novel, replace=False)
ood_sub_results = np.concatenate([ood_results[ood_labels == clsid] for clsid in cls_select])
ood_sub_labels = np.ones_like(ood_sub_results) * ind_ncls
ood_sub_confs = np.concatenate([ood_conf[ood_labels == clsid] for clsid in cls_select])
ood_sub_results[ood_sub_confs < thresh] = ind_ncls # correct rejection
# construct preds and labels
preds = np.concatenate((ind_results, ood_sub_results), axis=0)
labels = np.concatenate((ind_labels, ood_sub_labels), axis=0)
macro_F1_multi[m] = f1_score(labels, preds, average='macro')
macro_F1 = np.mean(macro_F1_multi) * 100
macro_F1_list.append(macro_F1)
return openness_list, macro_F1_list
def openmax_curvepoints(result_file, ood_ncls, num_rand):
assert os.path.exists(result_file), "File not found! Run baseline_i3d_openmax.py first!"
results = np.load(result_file, allow_pickle=True)
ind_openmax = results['ind_openmax'] # (N1, C+1)
ood_openmax = results['ood_openmax'] # (N2, C+1)
ind_labels = results['ind_label'] # (N1,)
ood_labels = results['ood_label'] # (N2,)
ind_results = np.argmax(ind_openmax, axis=1)
ood_results = np.argmax(ood_openmax, axis=1)
ind_ncls = ind_openmax.shape[1] - 1 # (C+1)-1
# open set F1 score (multi-class)
macro_F1 = f1_score(ind_labels, ind_results, average='macro')
macro_F1_list = [macro_F1 * 100]
openness_list = [0]
for n in range(ood_ncls):
ncls_novel = n + 1
openness = (1 - np.sqrt((2 * ind_ncls) / (2 * ind_ncls + ncls_novel))) * 100
openness_list.append(openness)
# randoml select the subset of ood samples
macro_F1_multi = np.zeros((num_rand), dtype=np.float32)
for m in range(num_rand):
cls_select = np.random.choice(ood_ncls, ncls_novel, replace=False)
ood_sub_results = np.concatenate([ood_results[ood_labels == clsid] for clsid in cls_select])
ood_sub_labels = np.ones_like(ood_sub_results) * ind_ncls
# construct preds and labels
preds = np.concatenate((ind_results, ood_sub_results), axis=0)
labels = np.concatenate((ind_labels, ood_sub_labels), axis=0)
macro_F1_multi[m] = f1_score(labels, preds, average='macro')
macro_F1 = np.mean(macro_F1_multi) * 100
macro_F1_list.append(macro_F1)
return openness_list, macro_F1_list
def uncertainty_curvepoints(result_file, thresh, ind_ncls, ood_ncls, num_rand):
assert os.path.exists(result_file), "File not found! Run ood_detection first!"
# load the testing results
results = np.load(result_file, allow_pickle=True)
ind_uncertainties = results['ind_unctt'] # (N1,)
ood_uncertainties = results['ood_unctt'] # (N2,)
ind_results = results['ind_pred'] # (N1,)
ood_results = results['ood_pred'] # (N2,)
ind_labels = results['ind_label']
ood_labels = results['ood_label']
# open set F1 score (multi-class)
ind_results[ind_uncertainties > thresh] = ind_ncls # falsely rejection
macro_F1 = f1_score(ind_labels, ind_results, average='macro')
macro_F1_list = [macro_F1 * 100]
openness_list = [0]
for n in range(ood_ncls):
ncls_novel = n + 1
openness = (1 - np.sqrt((2 * ind_ncls) / (2 * ind_ncls + ncls_novel))) * 100
openness_list.append(openness)
# randoml select the subset of ood samples
macro_F1_multi = np.zeros((num_rand), dtype=np.float32)
for m in range(num_rand):
cls_select = np.random.choice(ood_ncls, ncls_novel, replace=False)
ood_sub_results = np.concatenate([ood_results[ood_labels == clsid] for clsid in cls_select])
ood_sub_uncertainties = np.concatenate([ood_uncertainties[ood_labels == clsid] for clsid in cls_select])
ood_sub_results[ood_sub_uncertainties > thresh] = ind_ncls # correctly rejection
ood_sub_labels = np.ones_like(ood_sub_results) * ind_ncls
# construct preds and labels
preds = np.concatenate((ind_results, ood_sub_results), axis=0)
labels = np.concatenate((ind_labels, ood_sub_labels), axis=0)
macro_F1_multi[m] = f1_score(labels, preds, average='macro')
macro_F1 = np.mean(macro_F1_multi) * 100
macro_F1_list.append(macro_F1)
return openness_list, macro_F1_list
def plot_all_curves(openness, values, line_styles, result_prefix, ylim=[60, 80], fontsize=18):
fig = plt.figure(figsize=(8,6)) # (w, h)
plt.rcParams["font.family"] = "Arial"
for k, v in values.items():
plt.plot(openness, v, line_styles[k], linewidth=2, label=k)
plt.xlim(0, max(openness))
plt.ylim(ylim)
plt.xlabel('Openness (%)', fontsize=fontsize)
plt.ylabel('Open maF1 (%)', fontsize=fontsize)
plt.xticks(fontsize=fontsize)
plt.yticks(np.arange(ylim[0], ylim[1]+1, 5), fontsize=fontsize)
plt.grid('on')
plt.legend(fontsize=fontsize-10, loc='lower center', ncol=3, handletextpad=0.3, columnspacing=0.5)
plt.tight_layout()
result_path = os.path.dirname(result_prefix)
if not os.path.exists(result_path):
os.makedirs(result_path)
plt.savefig(result_prefix + '_%s.png'%(args.ood_data), bbox_inches='tight', dpi=fig.dpi, pad_inches=0.0)
plt.savefig(result_prefix + '_%s.pdf'%(args.ood_data), bbox_inches='tight', dpi=fig.dpi, pad_inches=0.0)
def main_i3d():
# SoftMax
print('Compute Open maF1 for SoftMax...')
result_file = 'i3d/results_baselines/openmax/I3D_OpenMax_%s_result.npz'%(args.ood_data)
openness_softmax, maF1_softmax = softmax_curvepoints(result_file, 0.996825, args.ood_ncls, args.num_rand)
# OpenMax
print('Compute Open maF1 for OpenMax...')
result_file = 'i3d/results_baselines/openmax/I3D_OpenMax_%s_result.npz'%(args.ood_data)
openness_openmax, maF1_openmax = openmax_curvepoints(result_file, args.ood_ncls, args.num_rand)
# RPL
print('Compute Open maF1 for RPL...')
result_file = 'i3d/results_baselines/rpl/I3D_RPL_%s_result.npz'%(args.ood_data)
openness_rpl, maF1_rpl = softmax_curvepoints(result_file, 0.995178, args.ood_ncls, args.num_rand)
# MCDropout BALD
print('Compute Open maF1 for MC Dropout BALD...')
result_file = 'i3d/results/I3D_DNN_BALD_%s_result.npz'%(args.ood_data)
openness_dnn, maF1_dnn = uncertainty_curvepoints(result_file, 0.000433, args.ind_ncls, args.ood_ncls, args.num_rand)
# BNN SVI BALD
print('Compute Open maF1 for BNN SVI BALD...')
result_file = 'i3d/results/I3D_BNN_BALD_%s_result.npz'%(args.ood_data)
openness_bnn, maF1_bnn = uncertainty_curvepoints(result_file, 0.000004, args.ind_ncls, args.ood_ncls, args.num_rand)
# DEAR (full)
print('Compute Open maF1 for DEAR (full)...')
result_file = 'i3d/results/I3D_EDLNoKLAvUCDebias_EDL_%s_result.npz'%(args.ood_data)
openness_dear, maF1_dear = uncertainty_curvepoints(result_file, 0.004550, args.ind_ncls, args.ood_ncls, args.num_rand)
# draw F1 curve
line_styles = {'DEAR (full)': 'r-', 'SoftMax': 'b-', 'RPL': 'm-', 'BNN SVI': 'c-', 'MC Dropout': 'y-', 'OpenMax': 'k-'}
values = {'DEAR (full)': maF1_dear, 'SoftMax': maF1_softmax, 'RPL': maF1_rpl, 'BNN SVI': maF1_bnn, 'MC Dropout': maF1_dnn, 'OpenMax': maF1_openmax}
result_prefix = args.result_prefix + '_I3D'
plot_all_curves(openness_dear, values, line_styles, result_prefix, ylim=[60,80], fontsize=30)
def main_tsm():
# SoftMax
print('Compute Open maF1 for SoftMax...')
result_file = 'tsm/results_baselines/openmax/TSM_OpenMax_%s_result.npz'%(args.ood_data)
openness_softmax, maF1_softmax = softmax_curvepoints(result_file, 0.999683, args.ood_ncls, args.num_rand)
# OpenMax
print('Compute Open maF1 for OpenMax...')
result_file = 'tsm/results_baselines/openmax/TSM_OpenMax_%s_result.npz'%(args.ood_data)
openness_openmax, maF1_openmax = openmax_curvepoints(result_file, args.ood_ncls, args.num_rand)
# RPL
print('Compute Open maF1 for RPL...')
result_file = 'tsm/results_baselines/rpl/TSM_RPL_%s_result.npz'%(args.ood_data)
openness_rpl, maF1_rpl = softmax_curvepoints(result_file, 0.999167, args.ood_ncls, args.num_rand)
# MCDropout BALD
print('Compute Open maF1 for MC Dropout BALD...')
result_file = 'tsm/results/TSM_DNN_BALD_%s_result.npz'%(args.ood_data)
openness_dnn, maF1_dnn = uncertainty_curvepoints(result_file, 0.000022, args.ind_ncls, args.ood_ncls, args.num_rand)
# BNN SVI BALD
print('Compute Open maF1 for BNN SVI BALD...')
result_file = 'tsm/results/TSM_BNN_BALD_%s_result.npz'%(args.ood_data)
openness_bnn, maF1_bnn = uncertainty_curvepoints(result_file, 0.000003, args.ind_ncls, args.ood_ncls, args.num_rand)
# DEAR (full)
print('Compute Open maF1 for DEAR (full)...')
result_file = 'tsm/results/TSM_EDLNoKLAvUCDebias_EDL_%s_result.npz'%(args.ood_data)
openness_dear, maF1_dear = uncertainty_curvepoints(result_file, 0.004549, args.ind_ncls, args.ood_ncls, args.num_rand)
# draw F1 curve
line_styles = {'DEAR (full)': 'r-', 'SoftMax': 'b-', 'RPL': 'm-', 'BNN SVI': 'c-', 'MC Dropout': 'y-', 'OpenMax': 'k-'}
values = {'DEAR (full)': maF1_dear, 'SoftMax': maF1_softmax, 'RPL': maF1_rpl, 'BNN SVI': maF1_bnn, 'MC Dropout': maF1_dnn, 'OpenMax': maF1_openmax}
result_prefix = args.result_prefix + '_TSM'
ylim = [60, 90] if args.ood_data == 'HMDB' else [55, 90]
plot_all_curves(openness_dear, values, line_styles, result_prefix, ylim=ylim, fontsize=30)
def main_slowfast():
# SoftMax
print('Compute Open maF1 for SoftMax...')
result_file = 'slowfast/results_baselines/openmax/SlowFast_OpenMax_%s_result.npz'%(args.ood_data)
openness_softmax, maF1_softmax = softmax_curvepoints(result_file, 0.997915, args.ood_ncls, args.num_rand)
# OpenMax
print('Compute Open maF1 for OpenMax...')
result_file = 'slowfast/results_baselines/openmax/SlowFast_OpenMax_%s_result.npz'%(args.ood_data)
openness_openmax, maF1_openmax = openmax_curvepoints(result_file, args.ood_ncls, args.num_rand)
# RPL
print('Compute Open maF1 for RPL...')
result_file = 'slowfast/results_baselines/rpl/SlowFast_RPL_%s_result.npz'%(args.ood_data)
openness_rpl, maF1_rpl = softmax_curvepoints(result_file, 0.997780, args.ood_ncls, args.num_rand)
# MCDropout BALD
print('Compute Open maF1 for MC Dropout BALD...')
result_file = 'slowfast/results/SlowFast_DNN_BALD_%s_result.npz'%(args.ood_data)
openness_dnn, maF1_dnn = uncertainty_curvepoints(result_file, 0.000065, args.ind_ncls, args.ood_ncls, args.num_rand)
# BNN SVI BALD
print('Compute Open maF1 for BNN SVI BALD...')
result_file = 'slowfast/results/SlowFast_BNN_BALD_%s_result.npz'%(args.ood_data)
openness_bnn, maF1_bnn = uncertainty_curvepoints(result_file, 0.000004, args.ind_ncls, args.ood_ncls, args.num_rand)
# DEAR (full)
print('Compute Open maF1 for DEAR (full)...')
result_file = 'slowfast/results/SlowFast_EDLNoKLAvUCDebias_EDL_%s_result.npz'%(args.ood_data)
openness_dear, maF1_dear = uncertainty_curvepoints(result_file, 0.004552, args.ind_ncls, args.ood_ncls, args.num_rand)
# draw F1 curve
line_styles = {'DEAR (full)': 'r-', 'SoftMax': 'b-', 'RPL': 'm-', 'BNN SVI': 'c-', 'MC Dropout': 'y-', 'OpenMax': 'k-'}
values = {'DEAR (full)': maF1_dear, 'SoftMax': maF1_softmax, 'RPL': maF1_rpl, 'BNN SVI': maF1_bnn, 'MC Dropout': maF1_dnn, 'OpenMax': maF1_openmax}
result_prefix = args.result_prefix + '_SlowFast'
plot_all_curves(openness_dear, values, line_styles, result_prefix, ylim=[60,90], fontsize=30)
def main_tpn():
# SoftMax
print('Compute Open maF1 for SoftMax...')
result_file = 'tpn_slowonly/results_baselines/openmax/TPN_OpenMax_%s_result.npz'%(args.ood_data)
openness_softmax, maF1_softmax = softmax_curvepoints(result_file, 0.997623, args.ood_ncls, args.num_rand)
# OpenMax
print('Compute Open maF1 for OpenMax...')
result_file = 'tpn_slowonly/results_baselines/openmax/TPN_OpenMax_%s_result.npz'%(args.ood_data)
openness_openmax, maF1_openmax = openmax_curvepoints(result_file, args.ood_ncls, args.num_rand)
# RPL
print('Compute Open maF1 for RPL...')
result_file = 'tpn_slowonly/results_baselines/rpl/TPN_RPL_%s_result.npz'%(args.ood_data)
openness_rpl, maF1_rpl = softmax_curvepoints(result_file, 0.996931, args.ood_ncls, args.num_rand)
# MCDropout BALD
print('Compute Open maF1 for MC Dropout BALD...')
result_file = 'tpn_slowonly/results/TPN_SlowOnly_Dropout_BALD_%s_result.npz'%(args.ood_data)
openness_dnn, maF1_dnn = uncertainty_curvepoints(result_file, 0.000096, args.ind_ncls, args.ood_ncls, args.num_rand)
# BNN SVI BALD
print('Compute Open maF1 for BNN SVI BALD...')
result_file = 'tpn_slowonly/results/TPN_SlowOnly_BNN_BALD_%s_result.npz'%(args.ood_data)
openness_bnn, maF1_bnn = uncertainty_curvepoints(result_file, 0.000007, args.ind_ncls, args.ood_ncls, args.num_rand)
# DEAR (full)
print('Compute Open maF1 for DEAR (full)...')
result_file = 'tpn_slowonly/results/TPN_SlowOnly_EDLlogNoKLAvUCDebias_EDL_%s_result.npz'%(args.ood_data)
openness_dear, maF1_dear = uncertainty_curvepoints(result_file, 0.004555, args.ind_ncls, args.ood_ncls, args.num_rand)
# draw F1 curve
line_styles = {'DEAR (full)': 'r-', 'SoftMax': 'b-', 'RPL': 'm-', 'BNN SVI': 'c-', 'MC Dropout': 'y-', 'OpenMax': 'k-'}
values = {'DEAR (full)': maF1_dear, 'SoftMax': maF1_softmax, 'RPL': maF1_rpl, 'BNN SVI': maF1_bnn, 'MC Dropout': maF1_dnn, 'OpenMax': maF1_openmax}
result_prefix = args.result_prefix + '_TPN'
ylim = [50, 85] if args.ood_data == 'HMDB' else [50, 85]
plot_all_curves(openness_dear, values, line_styles, result_prefix, ylim=ylim, fontsize=30)
def parse_args():
parser = argparse.ArgumentParser(description='Compare the performance of Open macroF1 against openness')
# model config
parser.add_argument('--ind_ncls', type=int, default=101, help='the number of classes in known dataset')
parser.add_argument('--ood_ncls', type=int, default=51, choices=[51, 305], help='the number of classes in unknwon dataset')
parser.add_argument('--ood_data', default='HMDB', choices=['HMDB', 'MiT'], help='the name of OOD dataset.')
parser.add_argument('--model', default='I3D', choices=['I3D', 'TSM', 'SlowFast', 'TPN'], help='the action recognition model.')
parser.add_argument('--num_rand', type=int, default=10, help='the number of random selection for ood classes')
parser.add_argument('--result_prefix', default='../temp/F1_openness')
args = parser.parse_args()
return args
if __name__ == '__main__':
""" Example script:
python draw_openness_curves.py --model I3D --ood_data MiT --ood_ncls 305
"""
np.random.seed(123)
args = parse_args()
if args.model == 'I3D':
# draw results on I3D
main_i3d()
elif args.model == 'TSM':
# draw results on TSM
main_tsm()
elif args.model == 'SlowFast':
# draw results on SlowFast
main_slowfast()
elif args.model == 'TPN':
# draw results on TPN
main_tpn()
else:
raise NotImplementedError
|
[
"numpy.load",
"numpy.random.seed",
"argparse.ArgumentParser",
"numpy.argmax",
"sklearn.metrics.f1_score",
"matplotlib.pyplot.figure",
"numpy.arange",
"numpy.mean",
"matplotlib.pyplot.tight_layout",
"os.path.dirname",
"os.path.exists",
"numpy.max",
"numpy.random.choice",
"matplotlib.pyplot.xticks",
"numpy.ones_like",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.grid",
"numpy.concatenate",
"os.makedirs",
"matplotlib.pyplot.plot",
"numpy.zeros",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.savefig",
"numpy.sqrt"
] |
[((187, 214), 'os.path.exists', 'os.path.exists', (['result_file'], {}), '(result_file)\n', (201, 214), False, 'import os, argparse\n'), ((314, 353), 'numpy.load', 'np.load', (['result_file'], {'allow_pickle': '(True)'}), '(result_file, allow_pickle=True)\n', (321, 353), True, 'import numpy as np\n'), ((607, 637), 'numpy.argmax', 'np.argmax', (['ind_softmax'], {'axis': '(1)'}), '(ind_softmax, axis=1)\n', (616, 637), True, 'import numpy as np\n'), ((656, 686), 'numpy.argmax', 'np.argmax', (['ood_softmax'], {'axis': '(1)'}), '(ood_softmax, axis=1)\n', (665, 686), True, 'import numpy as np\n'), ((702, 729), 'numpy.max', 'np.max', (['ind_softmax'], {'axis': '(1)'}), '(ind_softmax, axis=1)\n', (708, 729), True, 'import numpy as np\n'), ((745, 772), 'numpy.max', 'np.max', (['ood_softmax'], {'axis': '(1)'}), '(ood_softmax, axis=1)\n', (751, 772), True, 'import numpy as np\n'), ((896, 946), 'sklearn.metrics.f1_score', 'f1_score', (['ind_labels', 'ind_results'], {'average': '"""macro"""'}), "(ind_labels, ind_results, average='macro')\n", (904, 946), False, 'from sklearn.metrics import f1_score\n'), ((2238, 2265), 'os.path.exists', 'os.path.exists', (['result_file'], {}), '(result_file)\n', (2252, 2265), False, 'import os, argparse\n'), ((2334, 2373), 'numpy.load', 'np.load', (['result_file'], {'allow_pickle': '(True)'}), '(result_file, allow_pickle=True)\n', (2341, 2373), True, 'import numpy as np\n'), ((2594, 2624), 'numpy.argmax', 'np.argmax', (['ind_openmax'], {'axis': '(1)'}), '(ind_openmax, axis=1)\n', (2603, 2624), True, 'import numpy as np\n'), ((2643, 2673), 'numpy.argmax', 'np.argmax', (['ood_openmax'], {'axis': '(1)'}), '(ood_openmax, axis=1)\n', (2652, 2673), True, 'import numpy as np\n'), ((2779, 2829), 'sklearn.metrics.f1_score', 'f1_score', (['ind_labels', 'ind_results'], {'average': '"""macro"""'}), "(ind_labels, ind_results, average='macro')\n", (2787, 2829), False, 'from sklearn.metrics import f1_score\n'), ((3960, 3987), 'os.path.exists', 'os.path.exists', (['result_file'], {}), '(result_file)\n', (3974, 3987), False, 'import os, argparse\n'), ((4077, 4116), 'numpy.load', 'np.load', (['result_file'], {'allow_pickle': '(True)'}), '(result_file, allow_pickle=True)\n', (4084, 4116), True, 'import numpy as np\n'), ((4524, 4574), 'sklearn.metrics.f1_score', 'f1_score', (['ind_labels', 'ind_results'], {'average': '"""macro"""'}), "(ind_labels, ind_results, average='macro')\n", (4532, 4574), False, 'from sklearn.metrics import f1_score\n'), ((5930, 5956), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 6)'}), '(figsize=(8, 6))\n', (5940, 5956), True, 'import matplotlib.pyplot as plt\n'), ((6143, 6157), 'matplotlib.pyplot.ylim', 'plt.ylim', (['ylim'], {}), '(ylim)\n', (6151, 6157), True, 'import matplotlib.pyplot as plt\n'), ((6162, 6207), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Openness (%)"""'], {'fontsize': 'fontsize'}), "('Openness (%)', fontsize=fontsize)\n", (6172, 6207), True, 'import matplotlib.pyplot as plt\n'), ((6212, 6258), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Open maF1 (%)"""'], {'fontsize': 'fontsize'}), "('Open maF1 (%)', fontsize=fontsize)\n", (6222, 6258), True, 'import matplotlib.pyplot as plt\n'), ((6263, 6292), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'fontsize': 'fontsize'}), '(fontsize=fontsize)\n', (6273, 6292), True, 'import matplotlib.pyplot as plt\n'), ((6365, 6379), 'matplotlib.pyplot.grid', 'plt.grid', (['"""on"""'], {}), "('on')\n", (6373, 6379), True, 'import matplotlib.pyplot as plt\n'), ((6384, 6488), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'fontsize': '(fontsize - 10)', 'loc': '"""lower center"""', 'ncol': '(3)', 'handletextpad': '(0.3)', 'columnspacing': '(0.5)'}), "(fontsize=fontsize - 10, loc='lower center', ncol=3,\n handletextpad=0.3, columnspacing=0.5)\n", (6394, 6488), True, 'import matplotlib.pyplot as plt\n'), ((6487, 6505), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (6503, 6505), True, 'import matplotlib.pyplot as plt\n'), ((6524, 6554), 'os.path.dirname', 'os.path.dirname', (['result_prefix'], {}), '(result_prefix)\n', (6539, 6554), False, 'import os, argparse\n'), ((6632, 6740), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(result_prefix + '_%s.png' % args.ood_data)"], {'bbox_inches': '"""tight"""', 'dpi': 'fig.dpi', 'pad_inches': '(0.0)'}), "(result_prefix + '_%s.png' % args.ood_data, bbox_inches='tight',\n dpi=fig.dpi, pad_inches=0.0)\n", (6643, 6740), True, 'import matplotlib.pyplot as plt\n'), ((6741, 6849), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(result_prefix + '_%s.pdf' % args.ood_data)"], {'bbox_inches': '"""tight"""', 'dpi': 'fig.dpi', 'pad_inches': '(0.0)'}), "(result_prefix + '_%s.pdf' % args.ood_data, bbox_inches='tight',\n dpi=fig.dpi, pad_inches=0.0)\n", (6752, 6849), True, 'import matplotlib.pyplot as plt\n'), ((15288, 15388), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Compare the performance of Open macroF1 against openness"""'}), "(description=\n 'Compare the performance of Open macroF1 against openness')\n", (15311, 15388), False, 'import os, argparse\n'), ((16263, 16282), 'numpy.random.seed', 'np.random.seed', (['(123)'], {}), '(123)\n', (16277, 16282), True, 'import numpy as np\n'), ((1265, 1301), 'numpy.zeros', 'np.zeros', (['num_rand'], {'dtype': 'np.float32'}), '(num_rand, dtype=np.float32)\n', (1273, 1301), True, 'import numpy as np\n'), ((3148, 3184), 'numpy.zeros', 'np.zeros', (['num_rand'], {'dtype': 'np.float32'}), '(num_rand, dtype=np.float32)\n', (3156, 3184), True, 'import numpy as np\n'), ((4893, 4929), 'numpy.zeros', 'np.zeros', (['num_rand'], {'dtype': 'np.float32'}), '(num_rand, dtype=np.float32)\n', (4901, 4929), True, 'import numpy as np\n'), ((6048, 6107), 'matplotlib.pyplot.plot', 'plt.plot', (['openness', 'v', 'line_styles[k]'], {'linewidth': '(2)', 'label': 'k'}), '(openness, v, line_styles[k], linewidth=2, label=k)\n', (6056, 6107), True, 'import matplotlib.pyplot as plt\n'), ((6308, 6342), 'numpy.arange', 'np.arange', (['ylim[0]', '(ylim[1] + 1)', '(5)'], {}), '(ylim[0], ylim[1] + 1, 5)\n', (6317, 6342), True, 'import numpy as np\n'), ((6566, 6593), 'os.path.exists', 'os.path.exists', (['result_path'], {}), '(result_path)\n', (6580, 6593), False, 'import os, argparse\n'), ((6603, 6627), 'os.makedirs', 'os.makedirs', (['result_path'], {}), '(result_path)\n', (6614, 6627), False, 'import os, argparse\n'), ((1363, 1416), 'numpy.random.choice', 'np.random.choice', (['ood_ncls', 'ncls_novel'], {'replace': '(False)'}), '(ood_ncls, ncls_novel, replace=False)\n', (1379, 1416), True, 'import numpy as np\n'), ((1448, 1522), 'numpy.concatenate', 'np.concatenate', (['[ood_results[ood_labels == clsid] for clsid in cls_select]'], {}), '([ood_results[ood_labels == clsid] for clsid in cls_select])\n', (1462, 1522), True, 'import numpy as np\n'), ((1621, 1692), 'numpy.concatenate', 'np.concatenate', (['[ood_conf[ood_labels == clsid] for clsid in cls_select]'], {}), '([ood_conf[ood_labels == clsid] for clsid in cls_select])\n', (1635, 1692), True, 'import numpy as np\n'), ((1838, 1892), 'numpy.concatenate', 'np.concatenate', (['(ind_results, ood_sub_results)'], {'axis': '(0)'}), '((ind_results, ood_sub_results), axis=0)\n', (1852, 1892), True, 'import numpy as np\n'), ((1914, 1966), 'numpy.concatenate', 'np.concatenate', (['(ind_labels, ood_sub_labels)'], {'axis': '(0)'}), '((ind_labels, ood_sub_labels), axis=0)\n', (1928, 1966), True, 'import numpy as np\n'), ((1999, 2039), 'sklearn.metrics.f1_score', 'f1_score', (['labels', 'preds'], {'average': '"""macro"""'}), "(labels, preds, average='macro')\n", (2007, 2039), False, 'from sklearn.metrics import f1_score\n'), ((2059, 2082), 'numpy.mean', 'np.mean', (['macro_F1_multi'], {}), '(macro_F1_multi)\n', (2066, 2082), True, 'import numpy as np\n'), ((3246, 3299), 'numpy.random.choice', 'np.random.choice', (['ood_ncls', 'ncls_novel'], {'replace': '(False)'}), '(ood_ncls, ncls_novel, replace=False)\n', (3262, 3299), True, 'import numpy as np\n'), ((3331, 3405), 'numpy.concatenate', 'np.concatenate', (['[ood_results[ood_labels == clsid] for clsid in cls_select]'], {}), '([ood_results[ood_labels == clsid] for clsid in cls_select])\n', (3345, 3405), True, 'import numpy as np\n'), ((3537, 3591), 'numpy.concatenate', 'np.concatenate', (['(ind_results, ood_sub_results)'], {'axis': '(0)'}), '((ind_results, ood_sub_results), axis=0)\n', (3551, 3591), True, 'import numpy as np\n'), ((3613, 3665), 'numpy.concatenate', 'np.concatenate', (['(ind_labels, ood_sub_labels)'], {'axis': '(0)'}), '((ind_labels, ood_sub_labels), axis=0)\n', (3627, 3665), True, 'import numpy as np\n'), ((3698, 3738), 'sklearn.metrics.f1_score', 'f1_score', (['labels', 'preds'], {'average': '"""macro"""'}), "(labels, preds, average='macro')\n", (3706, 3738), False, 'from sklearn.metrics import f1_score\n'), ((3758, 3781), 'numpy.mean', 'np.mean', (['macro_F1_multi'], {}), '(macro_F1_multi)\n', (3765, 3781), True, 'import numpy as np\n'), ((4991, 5044), 'numpy.random.choice', 'np.random.choice', (['ood_ncls', 'ncls_novel'], {'replace': '(False)'}), '(ood_ncls, ncls_novel, replace=False)\n', (5007, 5044), True, 'import numpy as np\n'), ((5076, 5150), 'numpy.concatenate', 'np.concatenate', (['[ood_results[ood_labels == clsid] for clsid in cls_select]'], {}), '([ood_results[ood_labels == clsid] for clsid in cls_select])\n', (5090, 5150), True, 'import numpy as np\n'), ((5187, 5272), 'numpy.concatenate', 'np.concatenate', (['[ood_uncertainties[ood_labels == clsid] for clsid in cls_select]'], {}), '([ood_uncertainties[ood_labels == clsid] for clsid in cls_select]\n )\n', (5201, 5272), True, 'import numpy as np\n'), ((5493, 5547), 'numpy.concatenate', 'np.concatenate', (['(ind_results, ood_sub_results)'], {'axis': '(0)'}), '((ind_results, ood_sub_results), axis=0)\n', (5507, 5547), True, 'import numpy as np\n'), ((5569, 5621), 'numpy.concatenate', 'np.concatenate', (['(ind_labels, ood_sub_labels)'], {'axis': '(0)'}), '((ind_labels, ood_sub_labels), axis=0)\n', (5583, 5621), True, 'import numpy as np\n'), ((5654, 5694), 'sklearn.metrics.f1_score', 'f1_score', (['labels', 'preds'], {'average': '"""macro"""'}), "(labels, preds, average='macro')\n", (5662, 5694), False, 'from sklearn.metrics import f1_score\n'), ((5714, 5737), 'numpy.mean', 'np.mean', (['macro_F1_multi'], {}), '(macro_F1_multi)\n', (5721, 5737), True, 'import numpy as np\n'), ((1089, 1140), 'numpy.sqrt', 'np.sqrt', (['(2 * ind_ncls / (2 * ind_ncls + ncls_novel))'], {}), '(2 * ind_ncls / (2 * ind_ncls + ncls_novel))\n', (1096, 1140), True, 'import numpy as np\n'), ((1552, 1581), 'numpy.ones_like', 'np.ones_like', (['ood_sub_results'], {}), '(ood_sub_results)\n', (1564, 1581), True, 'import numpy as np\n'), ((2972, 3023), 'numpy.sqrt', 'np.sqrt', (['(2 * ind_ncls / (2 * ind_ncls + ncls_novel))'], {}), '(2 * ind_ncls / (2 * ind_ncls + ncls_novel))\n', (2979, 3023), True, 'import numpy as np\n'), ((3435, 3464), 'numpy.ones_like', 'np.ones_like', (['ood_sub_results'], {}), '(ood_sub_results)\n', (3447, 3464), True, 'import numpy as np\n'), ((4717, 4768), 'numpy.sqrt', 'np.sqrt', (['(2 * ind_ncls / (2 * ind_ncls + ncls_novel))'], {}), '(2 * ind_ncls / (2 * ind_ncls + ncls_novel))\n', (4724, 4768), True, 'import numpy as np\n'), ((5391, 5420), 'numpy.ones_like', 'np.ones_like', (['ood_sub_results'], {}), '(ood_sub_results)\n', (5403, 5420), True, 'import numpy as np\n')]
|
import numpy
def append_if_not_exists(arr, x):
if x not in arr:
arr.append(x)
def some_useless_slow_function():
arr = list()
for i in range(10000):
x = numpy.random.randint(0, 10000)
append_if_not_exists(arr, x)
|
[
"numpy.random.randint"
] |
[((190, 220), 'numpy.random.randint', 'numpy.random.randint', (['(0)', '(10000)'], {}), '(0, 10000)\n', (210, 220), False, 'import numpy\n')]
|
####
#### last update Nov. 29, 2021
####
"""
This is not efficient. I am doing the following two scenarios in a
sequential fashion.
a. three filters: irrigated fields, NASS out, survey date correct
b. one filter: irrigated fields
The least could be done is do it in parallel fashion!
"""
import csv
import numpy as np
import pandas as pd
import datetime
import time
import os, os.path
# from patsy import cr
import sys
start_time = time.time()
# search path for modules
# look @ https://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path
####################################################################################
###
### Aeolus Core path
###
####################################################################################
sys.path.append('/home/hnoorazar/NASA/')
import NASA_core as nc
import NASA_plot_core as ncp
####################################################################################
###
### Parameters
###
####################################################################################
county = sys.argv[1]
indeks = sys.argv[2]
SEOS_cut = sys.argv[3]
"""
White SOS and EOS params
SEOS_cut will be provided as integers. 3, 4, 5, 35.
Convert to 0.3, 0.4, 0.4, or 0.35
"""
if len(SEOS_cut) == 1:
onset_cut = int(SEOS_cut) / 10.0
elif len(SEOS_cut) == 2:
onset_cut = int(SEOS_cut) / 100.0
offset_cut = onset_cut
print("SEOS_cut is {}.".format(SEOS_cut))
print("onset_cut is {} and offset_cut is {}.".format(onset_cut, offset_cut))
####################################################################################
###
### Aeolus Directories
###
####################################################################################
SF_data_dir = "/data/hydro/users/Hossein/NASA/000_shapefile_data_part/"
data_dir = "/data/hydro/users/Hossein/NASA/05_SG_TS/"
SOS_table_dir = "/data/hydro/users/Hossein/NASA/06_SOS_tables/"
output_dir = SOS_table_dir # + str(int(onset_cut*10)) + "_EOS" + str(int(offset_cut*10)) + "/"
os.makedirs(output_dir, exist_ok=True)
print ("_________________________________________________________")
print ("data dir is: " + data_dir)
print ("_________________________________________________________")
print ("output_dir is: " + output_dir)
print ("_________________________________________________________")
####################################################################################
###
### Read data
###
####################################################################################
SG_df = pd.read_csv(data_dir + "SG_" + county + "_" + indeks + "_JFD.csv")
SG_df['human_system_start_time'] = pd.to_datetime(SG_df['human_system_start_time'])
SG_df["ID"] = SG_df["ID"].astype(str) # Monterays ID will be read as integer, convert to string
"""
train data should be correct. Therefore, we need to filter by
last survey year, toss out NASS, and we are sticking to irrigated
fields for now.
"""
SF_data = pd.read_csv(SF_data_dir + county + ".csv")
SF_data["ID"] = SF_data["ID"].astype(str)
if county == "Monterey2014":
SF_data['Crop2014'] = SF_data['Crop2014'].str.lower().str.replace(" ", "_").str.replace(",", "").str.replace("/", "_")
else:
SF_data['CropTyp'] = SF_data['CropTyp'].str.lower().str.replace(" ", "_").str.replace(",", "").str.replace("/", "_")
if county != "Monterey2014":
# filter by last survey date. Last 4 digits of county name!
print("No. of fields in SF_data is {}.".format(len(SF_data.ID.unique())))
SF_data = nc.filter_by_lastSurvey(SF_data, year = county[-4:])
print("No. of fields in SF_data after survey year is {}.".format(len(SF_data.ID.unique())))
SF_data = nc.filter_out_NASS(SF_data) # Toss NASS
print("No. of fields in SF_data after NASS is {}.".format(len(SF_data.ID.unique())))
SF_data = nc.filter_out_nonIrrigated(SF_data) # keep only irrigated lands
print("No. of fields in SF_data after Irrigation is {}.".format(len(SF_data.ID.unique())))
fuck = list(SF_data.ID)
SG_df = SG_df[SG_df.ID.isin(fuck)]
SG_df = pd.merge(SG_df, SF_data, on=['ID'], how='left')
print ("columns of SG_df right after merging is: ")
print (SG_df.head(2))
####################################################################################
###
### process data
###
####################################################################################
SG_df.reset_index(drop=True, inplace=True)
SG_df = nc.initial_clean(df=SG_df, column_to_be_cleaned = indeks)
### List of unique polygons
polygon_list = SG_df['ID'].unique()
print ("_________________________________________________________")
print("polygon_list is of length {}.".format(len(polygon_list)))
#
# 25 columns
#
ratio_name = indeks + "_ratio"
SEOS_output_columns = ['ID', 'human_system_start_time', indeks,
ratio_name, 'SOS', 'EOS', 'season_count']
#
# The reason I am multiplying len(SG_df) by 4 is that we can have at least two
# seasons which means 2 SOS and 2 EOS. So, at least 4 rows are needed in case of double-cropped.
#
min_year = SG_df.human_system_start_time.dt.year.min()
max_year = SG_df.human_system_start_time.dt.year.max()
no_years = max_year - min_year + 1
all_poly_and_SEOS = pd.DataFrame(data = None,
index = np.arange(4*no_years*len(SG_df)),
columns = SEOS_output_columns)
counter = 0
pointer_SEOS_tab = 0
###########
########### Re-order columns of the read data table to be consistent with the output columns
###########
SG_df = SG_df[SEOS_output_columns[0:3]]
print ("line 144")
for a_poly in polygon_list:
if (counter % 1000 == 0):
print ("_________________________________________________________")
print ("counter: " + str(counter))
print (a_poly)
curr_field = SG_df[SG_df['ID']==a_poly].copy()
curr_field.sort_values(by=['human_system_start_time'], inplace=True)
curr_field.reset_index(drop=True, inplace=True)
# extract unique years. Should be 2008 thru 2021.
# unique_years = list(pd.DatetimeIndex(curr_field['human_system_start_time']).year.unique())
unique_years = curr_field['human_system_start_time'].dt.year.unique()
"""
detect SOS and EOS in each year
"""
for yr in unique_years:
curr_field_yr = curr_field[curr_field['human_system_start_time'].dt.year == yr].copy()
# Orchards EVI was between more than 0.3
y_orchard = curr_field_yr[curr_field_yr['human_system_start_time'].dt.month >= 5]
y_orchard = y_orchard[y_orchard['human_system_start_time'].dt.month <= 10]
y_orchard_range = max(y_orchard[indeks]) - min(y_orchard[indeks])
if y_orchard_range > 0.3:
#######################################################################
###
### find SOS and EOS, and add them to the table
###
#######################################################################
curr_field_yr = nc.addToDF_SOS_EOS_White(pd_TS = curr_field_yr,
VegIdx = indeks,
onset_thresh = onset_cut,
offset_thresh = offset_cut)
##
## Kill false detected seasons
##
curr_field_yr = nc.Null_SOS_EOS_by_DoYDiff(pd_TS=curr_field_yr, min_season_length=40)
#
# extract the SOS and EOS rows
#
SEOS = curr_field_yr[(curr_field_yr['SOS'] != 0) | curr_field_yr['EOS'] != 0]
SEOS = SEOS.copy()
# SEOS = SEOS.reset_index() # not needed really
SOS_tb = curr_field_yr[curr_field_yr['SOS'] != 0]
if len(SOS_tb) >= 2:
SEOS["season_count"] = len(SOS_tb)
# re-order columns of SEOS so they match!!!
SEOS = SEOS[all_poly_and_SEOS.columns]
all_poly_and_SEOS[pointer_SEOS_tab:(pointer_SEOS_tab+len(SEOS))] = SEOS.values
pointer_SEOS_tab += len(SEOS)
else:
# re-order columns of fine_granular_table so they match!!!
curr_field_yr["season_count"] = 1
curr_field_yr = curr_field_yr[all_poly_and_SEOS.columns]
aaa = curr_field_yr.iloc[0].values.reshape(1, len(curr_field_yr.iloc[0]))
all_poly_and_SEOS.iloc[pointer_SEOS_tab:(pointer_SEOS_tab+1)] = aaa
pointer_SEOS_tab += 1
else:
"""
here are potentially apples, cherries, etc.
we did not add EVI_ratio, SOS, and EOS. So, we are missing these
columns in the data frame. So, use 666 as proxy
"""
aaa = np.append(curr_field_yr.iloc[0], [666, 666, 666, 1])
aaa = aaa.reshape(1, len(aaa))
all_poly_and_SEOS.iloc[pointer_SEOS_tab:(pointer_SEOS_tab+1)] = aaa
pointer_SEOS_tab += 1
counter += 1
####################################################################################
###
### Write the outputs
###
####################################################################################
# replace the following line with dropna.
# all_poly_and_SEOS = all_poly_and_SEOS[0:(pointer_SEOS_tab)]
all_poly_and_SEOS.dropna(inplace=True)
out_name = output_dir + "SC_train_" + county + "_" + indeks + str(SEOS_cut) + "_irr_NoNASS_SurvCorrect_JFD.csv"
all_poly_and_SEOS.to_csv(out_name, index = False)
####################################################################################
###
### Do it again with only one filter: Irrigated fields; i.e.
### Forget about NASS and last survey date filter
###
####################################################################################
####################################################################################
###
### Read data
###
####################################################################################
SG_df = pd.read_csv(data_dir + "SG_" + county + "_" + indeks + "_JFD.csv")
SG_df['human_system_start_time'] = pd.to_datetime(SG_df['human_system_start_time'])
SG_df["ID"] = SG_df["ID"].astype(str) # Monterays ID will be read as integer, convert to string
SF_data = pd.read_csv(SF_data_dir + county + ".csv")
SF_data["ID"] = SF_data["ID"].astype(str)
if county == "Monterey2014":
SF_data['Crop2014'] = SF_data['Crop2014'].str.lower().str.replace(" ", "_").str.replace(",", "").str.replace("/", "_")
else:
SF_data['CropTyp'] = SF_data['CropTyp'].str.lower().str.replace(" ", "_").str.replace(",", "").str.replace("/", "_")
if county != "Monterey2014":
SF_data = nc.filter_out_nonIrrigated(SF_data) # keep only irrigated lands
print("No. of fields in SF_data after Irrigation is {}.".format(len(SF_data.ID.unique())))
fuck = list(SF_data.ID)
SG_df = SG_df[SG_df.ID.isin(fuck)]
SG_df = pd.merge(SG_df, SF_data, on=['ID'], how='left')
print ("columns of SG_df right after merging is: ")
print (SG_df.head(2))
####################################################################################
###
### process data
###
####################################################################################
SG_df.reset_index(drop=True, inplace=True)
SG_df = nc.initial_clean(df=SG_df, column_to_be_cleaned = indeks)
### List of unique polygons
polygon_list = SG_df['ID'].unique()
print ("_________________________________________________________")
print("polygon_list is of length {}.".format(len(polygon_list)))
#
# 25 columns
#
ratio_name = indeks + "_ratio"
SEOS_output_columns = ['ID', 'human_system_start_time', indeks,
ratio_name, 'SOS', 'EOS', 'season_count']
#
# The reason I am multiplying len(SG_df) by 4 is that we can have at least two
# seasons which means 2 SOS and 2 EOS. So, at least 4 rows are needed in case of double-cropped.
#
min_year = SG_df.human_system_start_time.dt.year.min()
max_year = SG_df.human_system_start_time.dt.year.max()
no_years = max_year - min_year + 1
all_poly_and_SEOS = pd.DataFrame(data = None,
index = np.arange(4*no_years*len(SG_df)),
columns = SEOS_output_columns)
counter = 0
pointer_SEOS_tab = 0
###########
########### Re-order columns of the read data table to be consistent with the output columns
###########
SG_df = SG_df[SEOS_output_columns[0:3]]
print ("line 144")
for a_poly in polygon_list:
if (counter % 1000 == 0):
print ("_________________________________________________________")
print ("counter: " + str(counter))
print (a_poly)
curr_field = SG_df[SG_df['ID']==a_poly].copy()
curr_field.sort_values(by=['human_system_start_time'], inplace=True)
curr_field.reset_index(drop=True, inplace=True)
# extract unique years. Should be 2008 thru 2021.
# unique_years = list(pd.DatetimeIndex(curr_field['human_system_start_time']).year.unique())
unique_years = curr_field['human_system_start_time'].dt.year.unique()
"""
detect SOS and EOS in each year
"""
for yr in unique_years:
curr_field_yr = curr_field[curr_field['human_system_start_time'].dt.year == yr].copy()
# Orchards EVI was between more than 0.3
y_orchard = curr_field_yr[curr_field_yr['human_system_start_time'].dt.month >= 5]
y_orchard = y_orchard[y_orchard['human_system_start_time'].dt.month <= 10]
y_orchard_range = max(y_orchard[indeks]) - min(y_orchard[indeks])
if y_orchard_range > 0.3:
#######################################################################
###
### find SOS and EOS, and add them to the table
###
#######################################################################
curr_field_yr = nc.addToDF_SOS_EOS_White(pd_TS = curr_field_yr,
VegIdx = indeks,
onset_thresh = onset_cut,
offset_thresh = offset_cut)
##
## Kill false detected seasons
##
curr_field_yr = nc.Null_SOS_EOS_by_DoYDiff(pd_TS=curr_field_yr, min_season_length=40)
#
# extract the SOS and EOS rows
#
SEOS = curr_field_yr[(curr_field_yr['SOS'] != 0) | curr_field_yr['EOS'] != 0]
SEOS = SEOS.copy()
# SEOS = SEOS.reset_index() # not needed really
SOS_tb = curr_field_yr[curr_field_yr['SOS'] != 0]
if len(SOS_tb) >= 2:
SEOS["season_count"] = len(SOS_tb)
# re-order columns of SEOS so they match!!!
SEOS = SEOS[all_poly_and_SEOS.columns]
all_poly_and_SEOS[pointer_SEOS_tab:(pointer_SEOS_tab+len(SEOS))] = SEOS.values
pointer_SEOS_tab += len(SEOS)
else:
# re-order columns of fine_granular_table so they match!!!
curr_field_yr["season_count"] = 1
curr_field_yr = curr_field_yr[all_poly_and_SEOS.columns]
aaa = curr_field_yr.iloc[0].values.reshape(1, len(curr_field_yr.iloc[0]))
all_poly_and_SEOS.iloc[pointer_SEOS_tab:(pointer_SEOS_tab+1)] = aaa
pointer_SEOS_tab += 1
else:
"""
here are potentially apples, cherries, etc.
we did not add EVI_ratio, SOS, and EOS. So, we are missing these
columns in the data frame. So, use 666 as proxy
"""
aaa = np.append(curr_field_yr.iloc[0], [666, 666, 666, 1])
aaa = aaa.reshape(1, len(aaa))
all_poly_and_SEOS.iloc[pointer_SEOS_tab:(pointer_SEOS_tab+1)] = aaa
pointer_SEOS_tab += 1
counter += 1
####################################################################################
###
### Write the outputs
###
####################################################################################
# replace the following line with dropna.
# all_poly_and_SEOS = all_poly_and_SEOS[0:(pointer_SEOS_tab)]
all_poly_and_SEOS.dropna(inplace=True)
out_name = output_dir + "SC_train_" + county + "_" + indeks + str(SEOS_cut) + "_irrOneFilter_JFD.csv"
all_poly_and_SEOS.to_csv(out_name, index = False)
print ("done")
end_time = time.time()
print ("it took {:.0f} minutes to run this code.".format((end_time - start_time)/60))
|
[
"sys.path.append",
"NASA_core.addToDF_SOS_EOS_White",
"os.makedirs",
"pandas.read_csv",
"pandas.merge",
"NASA_core.Null_SOS_EOS_by_DoYDiff",
"time.time",
"NASA_core.filter_out_nonIrrigated",
"numpy.append",
"pandas.to_datetime",
"NASA_core.initial_clean",
"NASA_core.filter_by_lastSurvey",
"NASA_core.filter_out_NASS"
] |
[((449, 460), 'time.time', 'time.time', ([], {}), '()\n', (458, 460), False, 'import time\n'), ((802, 842), 'sys.path.append', 'sys.path.append', (['"""/home/hnoorazar/NASA/"""'], {}), "('/home/hnoorazar/NASA/')\n", (817, 842), False, 'import sys\n'), ((2079, 2117), 'os.makedirs', 'os.makedirs', (['output_dir'], {'exist_ok': '(True)'}), '(output_dir, exist_ok=True)\n', (2090, 2117), False, 'import os, os.path\n'), ((2616, 2682), 'pandas.read_csv', 'pd.read_csv', (["(data_dir + 'SG_' + county + '_' + indeks + '_JFD.csv')"], {}), "(data_dir + 'SG_' + county + '_' + indeks + '_JFD.csv')\n", (2627, 2682), True, 'import pandas as pd\n'), ((2718, 2766), 'pandas.to_datetime', 'pd.to_datetime', (["SG_df['human_system_start_time']"], {}), "(SG_df['human_system_start_time'])\n", (2732, 2766), True, 'import pandas as pd\n'), ((3032, 3074), 'pandas.read_csv', 'pd.read_csv', (["(SF_data_dir + county + '.csv')"], {}), "(SF_data_dir + county + '.csv')\n", (3043, 3074), True, 'import pandas as pd\n'), ((4133, 4180), 'pandas.merge', 'pd.merge', (['SG_df', 'SF_data'], {'on': "['ID']", 'how': '"""left"""'}), "(SG_df, SF_data, on=['ID'], how='left')\n", (4141, 4180), True, 'import pandas as pd\n'), ((4521, 4576), 'NASA_core.initial_clean', 'nc.initial_clean', ([], {'df': 'SG_df', 'column_to_be_cleaned': 'indeks'}), '(df=SG_df, column_to_be_cleaned=indeks)\n', (4537, 4576), True, 'import NASA_core as nc\n'), ((10220, 10286), 'pandas.read_csv', 'pd.read_csv', (["(data_dir + 'SG_' + county + '_' + indeks + '_JFD.csv')"], {}), "(data_dir + 'SG_' + county + '_' + indeks + '_JFD.csv')\n", (10231, 10286), True, 'import pandas as pd\n'), ((10322, 10370), 'pandas.to_datetime', 'pd.to_datetime', (["SG_df['human_system_start_time']"], {}), "(SG_df['human_system_start_time'])\n", (10336, 10370), True, 'import pandas as pd\n'), ((10478, 10520), 'pandas.read_csv', 'pd.read_csv', (["(SF_data_dir + county + '.csv')"], {}), "(SF_data_dir + county + '.csv')\n", (10489, 10520), True, 'import pandas as pd\n'), ((11123, 11170), 'pandas.merge', 'pd.merge', (['SG_df', 'SF_data'], {'on': "['ID']", 'how': '"""left"""'}), "(SG_df, SF_data, on=['ID'], how='left')\n", (11131, 11170), True, 'import pandas as pd\n'), ((11511, 11566), 'NASA_core.initial_clean', 'nc.initial_clean', ([], {'df': 'SG_df', 'column_to_be_cleaned': 'indeks'}), '(df=SG_df, column_to_be_cleaned=indeks)\n', (11527, 11566), True, 'import NASA_core as nc\n'), ((16662, 16673), 'time.time', 'time.time', ([], {}), '()\n', (16671, 16673), False, 'import time\n'), ((3583, 3633), 'NASA_core.filter_by_lastSurvey', 'nc.filter_by_lastSurvey', (['SF_data'], {'year': 'county[-4:]'}), '(SF_data, year=county[-4:])\n', (3606, 3633), True, 'import NASA_core as nc\n'), ((3746, 3773), 'NASA_core.filter_out_NASS', 'nc.filter_out_NASS', (['SF_data'], {}), '(SF_data)\n', (3764, 3773), True, 'import NASA_core as nc\n'), ((3897, 3932), 'NASA_core.filter_out_nonIrrigated', 'nc.filter_out_nonIrrigated', (['SF_data'], {}), '(SF_data)\n', (3923, 3932), True, 'import NASA_core as nc\n'), ((10887, 10922), 'NASA_core.filter_out_nonIrrigated', 'nc.filter_out_nonIrrigated', (['SF_data'], {}), '(SF_data)\n', (10913, 10922), True, 'import NASA_core as nc\n'), ((7096, 7211), 'NASA_core.addToDF_SOS_EOS_White', 'nc.addToDF_SOS_EOS_White', ([], {'pd_TS': 'curr_field_yr', 'VegIdx': 'indeks', 'onset_thresh': 'onset_cut', 'offset_thresh': 'offset_cut'}), '(pd_TS=curr_field_yr, VegIdx=indeks, onset_thresh=\n onset_cut, offset_thresh=offset_cut)\n', (7120, 7211), True, 'import NASA_core as nc\n'), ((7481, 7550), 'NASA_core.Null_SOS_EOS_by_DoYDiff', 'nc.Null_SOS_EOS_by_DoYDiff', ([], {'pd_TS': 'curr_field_yr', 'min_season_length': '(40)'}), '(pd_TS=curr_field_yr, min_season_length=40)\n', (7507, 7550), True, 'import NASA_core as nc\n'), ((8914, 8966), 'numpy.append', 'np.append', (['curr_field_yr.iloc[0]', '[666, 666, 666, 1]'], {}), '(curr_field_yr.iloc[0], [666, 666, 666, 1])\n', (8923, 8966), True, 'import numpy as np\n'), ((14086, 14201), 'NASA_core.addToDF_SOS_EOS_White', 'nc.addToDF_SOS_EOS_White', ([], {'pd_TS': 'curr_field_yr', 'VegIdx': 'indeks', 'onset_thresh': 'onset_cut', 'offset_thresh': 'offset_cut'}), '(pd_TS=curr_field_yr, VegIdx=indeks, onset_thresh=\n onset_cut, offset_thresh=offset_cut)\n', (14110, 14201), True, 'import NASA_core as nc\n'), ((14471, 14540), 'NASA_core.Null_SOS_EOS_by_DoYDiff', 'nc.Null_SOS_EOS_by_DoYDiff', ([], {'pd_TS': 'curr_field_yr', 'min_season_length': '(40)'}), '(pd_TS=curr_field_yr, min_season_length=40)\n', (14497, 14540), True, 'import NASA_core as nc\n'), ((15886, 15938), 'numpy.append', 'np.append', (['curr_field_yr.iloc[0]', '[666, 666, 666, 1]'], {}), '(curr_field_yr.iloc[0], [666, 666, 666, 1])\n', (15895, 15938), True, 'import numpy as np\n')]
|
#
# Copyright 2018 California Institute of Technology
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ISOFIT: Imaging Spectrometer Optimal FITting
# Author: <NAME>, <EMAIL>
#
import os
import logging
import numpy as np
from scipy.interpolate import interp1d
from ..core.common import resample_spectrum, VectorInterpolator
from .look_up_tables import TabularRT, FileExistsError
from isofit.configs.sections.radiative_transfer_config import RadiativeTransferEngineConfig
from isofit.configs import Config
### Variables ###
eps = 1e-5 # used for finite difference derivative calculations
### Classes ###
class LibRadTranRT(TabularRT):
"""A model of photon transport including the atmosphere."""
def __init__(self, engine_config: RadiativeTransferEngineConfig, full_config: Config):
self.angular_lut_keys_degrees = ['OBSZEN', 'TRUEAZ', 'viewzen', 'viewaz',
'solzen', 'solaz']
self.angular_lut_keys_radians = []
super().__init__(engine_config, full_config)
self.treat_as_emissive = False
self.libradtran_dir = self.find_basedir(engine_config)
self.libradtran_template_file = engine_config.template_file
self.libradtran_environment = engine_config.environment
self.lut_quantities = ['rhoatm', 'transm', 'sphalb', 'transup']
# Build the lookup table
self.build_lut()
def find_basedir(self, config: RadiativeTransferEngineConfig):
"""Seek out a libradtran base directory."""
if config.engine_base_dir is not None:
return config.engine_base_dir
try:
return os.getenv('LIBRADTRAN_DIR')
except KeyError:
pass
return None
def rebuild_cmd(self, point, fn):
"""."""
# start with defaults
vals = {'atmosphere': 'midlatitude_summer'}
for n, v in zip(self.lut_names, point):
vals[n] = v
# Translate a couple of special cases
if 'AOT550' in self.lut_names:
vals['aerosol_visibility'] = self.ext550_to_vis(vals['AOT550'])
if 'H2OSTR' in self.lut_names:
vals['h2o_mm'] = vals['H2OSTR']*10.0
with open(self.libradtran_template_file, 'r') as fin:
template = fin.read()
dict0, dict025, dict05 = [dict(vals).copy() for q in (1, 2, 3)]
dict0['albedo'] = '0.0'
dict025['albedo'] = '0.25'
dict05['albedo'] = '0.5'
libradtran_config_str0 = template.format(**dict0)
libradtran_config_str025 = template.format(**dict025)
libradtran_config_str05 = template.format(**dict05)
# Check rebuild conditions: LUT is missing or from a different config
infilename0 = 'LUT_'+fn+'_alb0.inp'
infilename05 = 'LUT_'+fn+'_alb05.inp'
infilename025 = 'LUT_'+fn+'_alb025.inp'
infilepath0 = os.path.join(self.lut_dir, infilename0)
infilepath05 = os.path.join(self.lut_dir, infilename05)
infilepath025 = os.path.join(self.lut_dir, infilename025)
outfilename0 = 'LUT_'+fn+'_alb0.out'
outfilename05 = 'LUT_'+fn+'_alb05.out'
outfilename025 = 'LUT_'+fn+'_alb025.out'
outfilenamezen = 'LUT_'+fn+'.zen'
outfilepath0 = os.path.join(self.lut_dir, outfilename0)
outfilepath05 = os.path.join(self.lut_dir, outfilename05)
outfilepath025 = os.path.join(self.lut_dir, outfilename025)
outfilepathzen = os.path.join(self.lut_dir, outfilenamezen)
scriptfilename = 'LUT_'+fn+'.sh'
scriptfilepath = os.path.join(self.lut_dir, scriptfilename)
# Are all files present?
rebuild = False
for path in [infilepath0, infilepath05, infilepath025,
outfilepath0, outfilepath05, outfilepath025,
outfilepathzen, scriptfilepath]:
if not os.path.exists(path):
rebuild = True
# Has configuration changed?
if not rebuild:
current0 = open(infilepath0, 'r').read()
current05 = open(infilepath05, 'r').read()
current025 = open(infilepath025, 'r').read()
rebuild = (rebuild or (libradtran_config_str0 != current0))
rebuild = (rebuild or (libradtran_config_str025 != current025))
rebuild = (rebuild or (libradtran_config_str05 != current05))
if not rebuild:
raise FileExistsError('Files exist')
if self.libradtran_dir is None:
logging.error('Specify a LibRadTran installation')
raise KeyError('Specify a LibRadTran installation')
# write config files
with open(infilepath0, 'w') as f:
f.write(libradtran_config_str0)
with open(infilepath025, 'w') as f:
f.write(libradtran_config_str025)
with open(infilepath05, 'w') as f:
f.write(libradtran_config_str05)
# Find the location and time for solar zenith caching
with open(infilepath0, 'r') as fin:
lat, lon, yr, mon, day, hour, mn = \
None, None, None, None, None, None, None
for line in fin.readlines():
# Skip comment lines
if line.strip().startswith("#"):
continue
if 'latitude N' in line:
lat = float(line.split()[-1])
elif 'latitude S' in line:
lat = -float(line.split()[-1])
elif 'longitude W' in line:
lon = float(line.split()[-1])
elif 'longitude E' in line:
lon = -float(line.split()[-1])
elif 'time' in line:
yr, mon, day, hour, mn, sec = [
float(q) for q in line.split()[1:]]
# Write runscript file
with open(scriptfilepath, 'w') as f:
f.write('#!/usr/bin/bash\n')
f.write('%s\n' % self.libradtran_environment)
f.write('(cd %s/bin && ./uvspec < %s > %s)\n' %
(self.libradtran_dir, infilepath0, outfilepath0))
f.write('(cd %s/bin && ./uvspec < %s > %s)\n' %
(self.libradtran_dir, infilepath05, outfilepath05))
f.write('(cd %s/bin && ./uvspec < %s > %s)\n' %
(self.libradtran_dir, infilepath025, outfilepath025))
f.write('(cd %s/bin && ./zenith %s -a %s -o %s -y %s %s %s %s %s > %s)\n' %
(self.libradtran_dir,
'-s 0 -q', lat, lon, yr, day, mon, hour, mn,
outfilepathzen))
return 'bash '+scriptfilepath
def load_rt(self, fn):
"""Load the results of a LibRadTran run."""
_, rdn0, _ = np.loadtxt(self.lut_dir+'/LUT_'+fn+'_alb0.out').T
_, rdn025, _ = np.loadtxt(self.lut_dir+'/LUT_'+fn+'_alb025.out').T
wl, rdn05, irr = np.loadtxt(self.lut_dir+'/LUT_'+fn+'_alb05.out').T
# Replace a few zeros in the irradiance spectrum via interpolation
good = irr > 1e-15
bad = np.logical_not(good)
irr[bad] = interp1d(wl[good], irr[good])(wl[bad])
# Translate to Top of Atmosphere (TOA) reflectance
rhoatm = rdn0 / 10.0 / irr * np.pi # Translate to uW nm-1 cm-2 sr-1
rho025 = rdn025 / 10.0 / irr * np.pi
rho05 = rdn05 / 10.0 / irr * np.pi
# Resample TOA reflectances to simulate the instrument observation
rhoatm = resample_spectrum(rhoatm, wl, self.wl, self.fwhm)
rho025 = resample_spectrum(rho025, wl, self.wl, self.fwhm)
rho05 = resample_spectrum(rho05, wl, self.wl, self.fwhm)
irr = resample_spectrum(irr, wl, self.wl, self.fwhm)
# Calculate some atmospheric optical constants NOTE: This calc is not
# numerically stable for cases where rho025 and rho05 are the same.
# Anecdotally, in all of these cases, they are also the same as rhoatm,
# so the equation reduces to 0 / 0. Therefore, we assume that spherical
# albedo here is zero. Any other non-finite results are (currently)
# unexpected, so we convert them to errors.
bad = np.logical_and(rho025 == rhoatm, rho05 == rhoatm)
sphalb = 2.8*(2.0*rho025-rhoatm-rho05)/(rho025-rho05)
if np.sum(bad) > 0:
logging.debug('Setting sphalb = 0 where rho025 == rho05 == rhoatm.')
sphalb[bad] = 0
if not np.all(np.isfinite(sphalb)):
raise AttributeError('Non-finite values in spherical albedo calculation')
transm = (rho05-rhoatm)*(2.0-sphalb)
# For now, don't estimate this term!!
# TODO: Have LibRadTran calculate it directly
transup = np.zeros(self.wl.shape)
# Get solar zenith, translate to irradiance at zenith = 0
# HACK: If a file called `prescribed_geom` exists in the LUT directory,
# use that instead of the LibRadtran calculated zenith angle. This is
# not the most elegant or efficient solution, but it seems to work.
zenfile = os.path.join(self.lut_dir, "prescribed_geom")
if not os.path.exists(zenfile):
zenfile = os.path.join(self.lut_dir, 'LUT_'+fn+'.zen')
with open(zenfile, 'r') as fin:
output = fin.read().split()
solzen, solaz = [float(q) for q in output[1:]]
self.coszen = np.cos(solzen/360.0*2.0*np.pi)
irr = irr / self.coszen
self.solar_irr = irr.copy()
results = {"wl": self.wl, 'solzen': solzen, 'irr': irr,
"solzen": solzen, "rhoatm": rhoatm, "transm": transm,
"sphalb": sphalb, "transup": transup}
return results
def ext550_to_vis(self, ext550):
return np.log(50.0) / (ext550 + 0.01159)
def build_lut(self, rebuild=False):
TabularRT.build_lut(self, rebuild)
librt_outputs = []
for point, fn in zip(self.points, self.files):
librt_outputs.append(self.load_rt(fn))
self.cache = {}
dims_aug = self.lut_dims + [self.n_chan]
for key in self.lut_quantities:
temp = np.zeros(dims_aug, dtype=float)
for librt_output, point in zip(librt_outputs, self.points):
ind = [np.where(g == p)[0] for g, p in
zip(self.lut_grids, point)]
ind = tuple(ind)
temp[ind] = librt_output[key]
self.luts[key] = VectorInterpolator(self.lut_grids, temp,
self.lut_interp_types)
def _lookup_lut(self, point):
ret = {}
for key, lut in self.luts.items():
ret[key] = np.array(lut(point)).ravel()
return ret
def get(self, x_RT, geom):
point = np.zeros((self.n_point,))
for point_ind, name in enumerate(self.lut_grid_config):
if name in self.statevector_names:
ix = self.statevector_names.index(name)
point[point_ind] = x_RT[ix]
elif name == "OBSZEN":
point[point_ind] = geom.OBSZEN
elif name == "GNDALT":
point[point_ind] = geom.GNDALT
elif name == "viewzen":
point[point_ind] = geom.observer_zenith
elif name == "viewaz":
point[point_ind] = geom.observer_azimuth
elif name == "solaz":
point[point_ind] = geom.solar_azimuth
elif name == "solzen":
point[point_ind] = geom.solar_zenith
elif name == "TRUEAZ":
point[point_ind] = geom.TRUEAZ
elif name == 'phi':
point[point_ind] = geom.phi
elif name == 'umu':
point[point_ind] = geom.umu
else:
# If a variable is defined in the lookup table but not
# specified elsewhere, we will default to the minimum
point[point_ind] = min(self.lut_grid_config[name])
return self._lookup_lut(point)
def get_L_atm(self, x_RT, geom):
r = self.get(x_RT, geom)
rho = r['rhoatm']
rdn = rho / np.pi*(self.solar_irr * self.coszen)
return rdn
def get_L_down_transmitted(self, x_RT, geom):
r = self.get(x_RT, geom)
rdn = (self.solar_irr * self.coszen) / np.pi * r['transm']
return rdn
|
[
"logging.error",
"numpy.sum",
"logging.debug",
"numpy.logical_and",
"numpy.log",
"numpy.logical_not",
"numpy.zeros",
"os.path.exists",
"numpy.isfinite",
"numpy.where",
"numpy.loadtxt",
"numpy.cos",
"scipy.interpolate.interp1d",
"os.path.join",
"os.getenv"
] |
[((3425, 3464), 'os.path.join', 'os.path.join', (['self.lut_dir', 'infilename0'], {}), '(self.lut_dir, infilename0)\n', (3437, 3464), False, 'import os\n'), ((3488, 3528), 'os.path.join', 'os.path.join', (['self.lut_dir', 'infilename05'], {}), '(self.lut_dir, infilename05)\n', (3500, 3528), False, 'import os\n'), ((3553, 3594), 'os.path.join', 'os.path.join', (['self.lut_dir', 'infilename025'], {}), '(self.lut_dir, infilename025)\n', (3565, 3594), False, 'import os\n'), ((3802, 3842), 'os.path.join', 'os.path.join', (['self.lut_dir', 'outfilename0'], {}), '(self.lut_dir, outfilename0)\n', (3814, 3842), False, 'import os\n'), ((3867, 3908), 'os.path.join', 'os.path.join', (['self.lut_dir', 'outfilename05'], {}), '(self.lut_dir, outfilename05)\n', (3879, 3908), False, 'import os\n'), ((3934, 3976), 'os.path.join', 'os.path.join', (['self.lut_dir', 'outfilename025'], {}), '(self.lut_dir, outfilename025)\n', (3946, 3976), False, 'import os\n'), ((4002, 4044), 'os.path.join', 'os.path.join', (['self.lut_dir', 'outfilenamezen'], {}), '(self.lut_dir, outfilenamezen)\n', (4014, 4044), False, 'import os\n'), ((4112, 4154), 'os.path.join', 'os.path.join', (['self.lut_dir', 'scriptfilename'], {}), '(self.lut_dir, scriptfilename)\n', (4124, 4154), False, 'import os\n'), ((7613, 7633), 'numpy.logical_not', 'np.logical_not', (['good'], {}), '(good)\n', (7627, 7633), True, 'import numpy as np\n'), ((8714, 8763), 'numpy.logical_and', 'np.logical_and', (['(rho025 == rhoatm)', '(rho05 == rhoatm)'], {}), '(rho025 == rhoatm, rho05 == rhoatm)\n', (8728, 8763), True, 'import numpy as np\n'), ((9259, 9282), 'numpy.zeros', 'np.zeros', (['self.wl.shape'], {}), '(self.wl.shape)\n', (9267, 9282), True, 'import numpy as np\n'), ((9602, 9647), 'os.path.join', 'os.path.join', (['self.lut_dir', '"""prescribed_geom"""'], {}), "(self.lut_dir, 'prescribed_geom')\n", (9614, 9647), False, 'import os\n'), ((9917, 9953), 'numpy.cos', 'np.cos', (['(solzen / 360.0 * 2.0 * np.pi)'], {}), '(solzen / 360.0 * 2.0 * np.pi)\n', (9923, 9953), True, 'import numpy as np\n'), ((11318, 11343), 'numpy.zeros', 'np.zeros', (['(self.n_point,)'], {}), '((self.n_point,))\n', (11326, 11343), True, 'import numpy as np\n'), ((2159, 2186), 'os.getenv', 'os.getenv', (['"""LIBRADTRAN_DIR"""'], {}), "('LIBRADTRAN_DIR')\n", (2168, 2186), False, 'import os\n'), ((5044, 5094), 'logging.error', 'logging.error', (['"""Specify a LibRadTran installation"""'], {}), "('Specify a LibRadTran installation')\n", (5057, 5094), False, 'import logging\n'), ((7294, 7347), 'numpy.loadtxt', 'np.loadtxt', (["(self.lut_dir + '/LUT_' + fn + '_alb0.out')"], {}), "(self.lut_dir + '/LUT_' + fn + '_alb0.out')\n", (7304, 7347), True, 'import numpy as np\n'), ((7367, 7422), 'numpy.loadtxt', 'np.loadtxt', (["(self.lut_dir + '/LUT_' + fn + '_alb025.out')"], {}), "(self.lut_dir + '/LUT_' + fn + '_alb025.out')\n", (7377, 7422), True, 'import numpy as np\n'), ((7445, 7499), 'numpy.loadtxt', 'np.loadtxt', (["(self.lut_dir + '/LUT_' + fn + '_alb05.out')"], {}), "(self.lut_dir + '/LUT_' + fn + '_alb05.out')\n", (7455, 7499), True, 'import numpy as np\n'), ((7653, 7682), 'scipy.interpolate.interp1d', 'interp1d', (['wl[good]', 'irr[good]'], {}), '(wl[good], irr[good])\n', (7661, 7682), False, 'from scipy.interpolate import interp1d\n'), ((8837, 8848), 'numpy.sum', 'np.sum', (['bad'], {}), '(bad)\n', (8843, 8848), True, 'import numpy as np\n'), ((8866, 8934), 'logging.debug', 'logging.debug', (['"""Setting sphalb = 0 where rho025 == rho05 == rhoatm."""'], {}), "('Setting sphalb = 0 where rho025 == rho05 == rhoatm.')\n", (8879, 8934), False, 'import logging\n'), ((9663, 9686), 'os.path.exists', 'os.path.exists', (['zenfile'], {}), '(zenfile)\n', (9677, 9686), False, 'import os\n'), ((9710, 9758), 'os.path.join', 'os.path.join', (['self.lut_dir', "('LUT_' + fn + '.zen')"], {}), "(self.lut_dir, 'LUT_' + fn + '.zen')\n", (9722, 9758), False, 'import os\n'), ((10287, 10299), 'numpy.log', 'np.log', (['(50.0)'], {}), '(50.0)\n', (10293, 10299), True, 'import numpy as np\n'), ((10673, 10704), 'numpy.zeros', 'np.zeros', (['dims_aug'], {'dtype': 'float'}), '(dims_aug, dtype=float)\n', (10681, 10704), True, 'import numpy as np\n'), ((4415, 4435), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (4429, 4435), False, 'import os\n'), ((8986, 9005), 'numpy.isfinite', 'np.isfinite', (['sphalb'], {}), '(sphalb)\n', (8997, 9005), True, 'import numpy as np\n'), ((10800, 10816), 'numpy.where', 'np.where', (['(g == p)'], {}), '(g == p)\n', (10808, 10816), True, 'import numpy as np\n')]
|
import numpy as np
import sys,os
from evaluation import nDCG5, save_result
import data
import json
if __name__ == '__main__':
score= []
num = len(sys.argv) -1
for i in range(num):
score_path = sys.argv[i+1]
score.append(np.load(score_path, allow_pickle=True).item())
score_enm = {}
for k in score[0].keys():
score_list = []
for i in range(len(score[0][k])):
score_list.append((0, score[0][k][i][1]))
score_enm[k] = score_list
for k in score_enm.keys():
for ind in range(num):
for i in range(len(score_enm[k])):
for j in range(len(score[ind][k])):
if score_enm[k][i][1] == score[ind][k][j][1]:
if ind ==0:
score_enm[k][i] = (score_enm[k][i][0] + (1./6.)*score[ind][k][j][0], score_enm[k][i][1])
elif ind >= 1 and ind <= 5:
score_enm[k][i] = (score_enm[k][i][0] +(1./6.)* score[ind][k][j][0], score_enm[k][i][1])
break
#score_enm[k].sort(key=lambda x: x[0], reverse=True)
score_enm[k].sort(key=lambda x: x[0], reverse=False)
f = open('../data/valid/valid_answer.json')
#answer = json.load(f)
answer = None
if answer is None:
save_result(score_enm)
else:
ndcg5 = nDCG5(score_enm, answer)
print('Text to image nDCG5: ', ndcg5)
|
[
"evaluation.nDCG5",
"numpy.load",
"evaluation.save_result"
] |
[((1330, 1352), 'evaluation.save_result', 'save_result', (['score_enm'], {}), '(score_enm)\n', (1341, 1352), False, 'from evaluation import nDCG5, save_result\n'), ((1379, 1403), 'evaluation.nDCG5', 'nDCG5', (['score_enm', 'answer'], {}), '(score_enm, answer)\n', (1384, 1403), False, 'from evaluation import nDCG5, save_result\n'), ((251, 289), 'numpy.load', 'np.load', (['score_path'], {'allow_pickle': '(True)'}), '(score_path, allow_pickle=True)\n', (258, 289), True, 'import numpy as np\n')]
|
import unittest
import Mariana.layers as ML
import Mariana.layers as ML
import Mariana.decorators as dec
import Mariana.costs as MC
import Mariana.regularizations as MR
import Mariana.scenari as MS
import Mariana.activations as MA
import Mariana.training.datasetmaps as MD
import theano.tensor as tt
import numpy
class DastasetMapsTests(unittest.TestCase):
def setUp(self) :
pass
def tearDown(self) :
pass
def test_classSets(self) :
def sample(cls) :
o = cls.getAll("onehot")
n = cls.getAll("classNumber")
p = cls.getAll("input")
return o, n, p
l1 = numpy.arange(100)
l2 = numpy.arange(10) + 10
cls = MD.ClassSets( sets = [ ("l1", l1), ("l2", l2) ], sampleSize = len(l1) )
o, n, p = sample(cls)
for i in xrange(len(o)) :
if n[i] == 0. :
self.assertEquals(o[i][1], 0.)
self.assertEquals(o[i][0], 1.)
else :
self.assertEquals(o[i][0], 0.)
self.assertEquals(o[i][1], 1.)
nbTrials = 10000
nb2 = 0.
for i in xrange(nbTrials) :
o, n, p = sample(cls)
for j in xrange(len(p)) :
if p[j] > 10 :
nb2 += 1
f = nb2/float(len(p)*nbTrials)
r = abs(f-0.5)
self.assertTrue(r < 2)
if __name__ == '__main__' :
import Mariana.settings as MSET
MSET.VERBOSE = False
unittest.main()
|
[
"unittest.main",
"numpy.arange"
] |
[((1245, 1260), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1258, 1260), False, 'import unittest\n'), ((582, 599), 'numpy.arange', 'numpy.arange', (['(100)'], {}), '(100)\n', (594, 599), False, 'import numpy\n'), ((607, 623), 'numpy.arange', 'numpy.arange', (['(10)'], {}), '(10)\n', (619, 623), False, 'import numpy\n')]
|
# -*- coding: utf-8 -*-
"""
Created on May 23 2014
@author: florian
"""
import sys
import threading
import atexit
import pyaudio
import numpy as np
import matplotlib.pyplot as plt
from PyQt4 import QtGui, QtCore
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
# class taken from the SciPy 2015 Vispy talk opening example
# see https://github.com/vispy/vispy/pull/928
class MicrophoneRecorder(object):
def __init__(self, rate=4000, chunksize=1024):
self.rate = rate
self.chunksize = chunksize
self.p = pyaudio.PyAudio()
self.stream = self.p.open(format=pyaudio.paInt16,
channels=1,
rate=self.rate,
input=True,
frames_per_buffer=self.chunksize,
stream_callback=self.new_frame)
self.lock = threading.Lock()
self.stop = False
self.frames = []
atexit.register(self.close)
def new_frame(self, data, frame_count, time_info, status):
data = np.fromstring(data, 'int16')
with self.lock:
self.frames.append(data)
if self.stop:
return None, pyaudio.paComplete
return None, pyaudio.paContinue
def get_frames(self):
with self.lock:
frames = self.frames
self.frames = []
return frames
def start(self):
self.stream.start_stream()
def close(self):
with self.lock:
self.stop = True
self.stream.close()
self.p.terminate()
class StringTuning(QtGui.QWidget):
"""a widget for storing the tuning of one string"""
def __init__(self, text_label):
QtGui.QWidget.__init__(self)
self.tuning = 0.0
box = QtGui.QVBoxLayout()
label = QtGui.QLabel(text_label)
lcd = QtGui.QLCDNumber()
box.addWidget(label)
box.addWidget(lcd)
self.setLayout(box)
# keep reference
self.label = label
self.lcd = lcd
# bottom part
button = QtGui.QPushButton('set', parent=self)
vbox = QtGui.QVBoxLayout()
vbox.addWidget(button)
box.addLayout(vbox)
self.button = button
def updateTuning(self, new_tuning):
"""updates the tuning of the widget with the new value provided"""
self.tuning = new_tuning
self.lcd.display(new_tuning)
def getTuning(self):
"""returns current tuning for widget"""
return self.tuning
class MplFigure(object):
def __init__(self, parent):
self.figure = plt.figure(facecolor='white')
self.canvas = FigureCanvas(self.figure)
self.toolbar = NavigationToolbar(self.canvas, parent)
class LiveFFTWidget(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
# customize the UI
self.initUI()
# init class data
self.initData()
# connect slots
self.connectSlots()
# init MPL widget
self.initMplWidget()
def initUI(self):
"""builds the layout of the app"""
# layout: first horizontal box
hbox_gain = QtGui.QHBoxLayout()
autoGain = QtGui.QLabel('Auto gain')
autoGainCheckBox = QtGui.QCheckBox(checked=True)
self.autoGainCheckBox = autoGainCheckBox
self.clipboard_button = QtGui.QPushButton('copy to clipboard')
hbox_gain.addWidget(autoGain)
hbox_gain.addWidget(autoGainCheckBox)
hbox_gain.addSpacing(20)
hbox_gain.addWidget(self.clipboard_button)
# layout: second horizontal box
hbox_fixedGain = QtGui.QHBoxLayout()
fixedGain = QtGui.QLabel('Fixed gain level')
fixedGainSlider = QtGui.QSlider(QtCore.Qt.Horizontal)
self.fixedGainSlider = fixedGainSlider
hbox_fixedGain.addWidget(fixedGain)
hbox_fixedGain.addWidget(fixedGainSlider)
# layout: individual strings
hbox_3 = QtGui.QHBoxLayout()
string_widgets = [StringTuning(string) for string in ['low E', 'A', 'D', 'G', 'B', 'high E']]
for sw in string_widgets:
hbox_3.addWidget(sw)
self.string_widgets = string_widgets
# layout: put everything together
vbox = QtGui.QVBoxLayout()
vbox.addLayout(hbox_gain)
vbox.addLayout(hbox_fixedGain)
vbox.addLayout(hbox_3)
# mpl figure
self.main_figure = MplFigure(self)
vbox.addWidget(self.main_figure.toolbar)
vbox.addWidget(self.main_figure.canvas)
self.setLayout(vbox)
self.setGeometry(300, 300, 550, 500)
self.setWindowTitle('LiveFFT')
self.show()
def initData(self):
""" inits the data needed by the app"""
mic = MicrophoneRecorder()
mic.start()
# keeps reference to mic
self.mic = mic
# computes the parameters that will be used during plotting
self.freq_vect = np.fft.rfftfreq(mic.chunksize,
1./mic.rate)
self.time_vect = np.arange(mic.chunksize,
dtype=np.float32) / mic.rate * 1000
def connectSlots(self):
"""
connects the slots needed by the app to their widgets
"""
# timer for calls, taken from:
# http://ralsina.me/weblog/posts/BB974.html
timer = QtCore.QTimer()
timer.timeout.connect(self.handleNewData)
timer.start(100)
# keep reference to timer
self.timer = timer
# connect the push buttons
for sw in self.string_widgets:
sw.button.clicked.connect(self.updateLcd)
# copy to clipboard
self.clipboard_button.clicked.connect(self.copyTuningToClipboard)
def initMplWidget(self):
"""creates initial matplotlib plots in the main window and keeps
references for further use"""
# top plot
self.ax_top = self.main_figure.figure.add_subplot(211)
self.ax_top.set_ylim(-32768, 32768)
self.ax_top.set_xlim(0, self.time_vect.max())
self.ax_top.set_xlabel(u'time (ms)', fontsize=6)
# bottom plot
self.ax_bottom = self.main_figure.figure.add_subplot(212)
self.ax_bottom.set_ylim(0, 1)
self.ax_bottom.set_xlim(0, self.freq_vect.max())
self.ax_bottom.set_xlabel(u'frequency (Hz)', fontsize=6)
# lines that are overlaid
self.line_top, = self.ax_top.plot(self.time_vect,
np.ones_like(self.time_vect))
self.line_bottom, = self.ax_bottom.plot(self.freq_vect,
np.ones_like(self.freq_vect))
self.pitch_line, = self.ax_bottom.plot((self.freq_vect[self.freq_vect.size / 2], self.freq_vect[self.freq_vect.size / 2]),
self.ax_bottom.get_ylim(), lw=2)
# tight layout
#plt.tight_layout()
def handleNewData(self):
""" handles the asynchroneously collected sound chunks """
# gets the latest frames
frames = self.mic.get_frames()
if len(frames) > 0:
# keeps only the last frame
current_frame = frames[-1]
# plots the time signal
self.line_top.set_data(self.time_vect, current_frame)
# computes and plots the fft signal
fft_frame = np.fft.rfft(current_frame)
if self.autoGainCheckBox.checkState() == QtCore.Qt.Checked:
fft_frame /= np.abs(fft_frame).max()
else:
fft_frame *= (1 + self.fixedGainSlider.value()) / 5000000.
#print(np.abs(fft_frame).max())
self.line_bottom.set_data(self.freq_vect, np.abs(fft_frame))
# pitch tracking algorithm
new_pitch = compute_pitch_hps(current_frame, self.mic.rate,
dF=1)
precise_pitch = compute_pitch_hps(current_frame, self.mic.rate,
dF=0.01, Fmin=new_pitch * 0.8, Fmax = new_pitch * 1.2)
self.precise_pitch = precise_pitch
self.ax_top.set_title("pitch = {:.2f} Hz".format(precise_pitch))
self.pitch_line.set_data((new_pitch, new_pitch),
self.ax_bottom.get_ylim())
# refreshes the plots
self.main_figure.canvas.draw()
def updateLcd(self):
"""method that gets called when someone clicks one of the buttons
to store a tuning"""
sender = self.sender()
sender.parent().updateTuning(self.precise_pitch)
def copyTuningToClipboard(self):
"""copies the stored pitch values to clipboard"""
copy_text = ",".join([str(sw.getTuning()) for sw in self.string_widgets])
clipboard = QtGui.QApplication.clipboard()
clipboard.setText(copy_text)
def compute_pitch_hps(x, Fs, dF=None, Fmin=30., Fmax=900., H=5):
# default value for dF frequency resolution
if dF == None:
dF = Fs / x.size
# Hamming window apodization
x = np.array(x, dtype=np.double, copy=True)
x *= np.hamming(x.size)
# number of points in FFT to reach the resolution wanted by the user
n_fft = np.ceil(Fs / dF)
# DFT computation
X = np.abs(np.fft.fft(x, n=int(n_fft)))
# limiting frequency R_max computation
R = np.floor(1 + n_fft / 2. / H)
# computing the indices for min and max frequency
N_min = np.ceil(Fmin / Fs * n_fft)
N_max = np.floor(Fmax / Fs * n_fft)
N_max = min(N_max, R)
# harmonic product spectrum computation
indices = (np.arange(N_max)[:, np.newaxis] * np.arange(1, H+1)).astype(int)
P = np.prod(X[indices.ravel()].reshape(N_max, H), axis=1)
ix = np.argmax(P * ((np.arange(P.size) >= N_min) & (np.arange(P.size) <= N_max)))
return dF * ix
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
window = LiveFFTWidget()
window.show()
sys.exit(app.exec_())
|
[
"atexit.register",
"PyQt4.QtCore.QTimer",
"matplotlib.backends.backend_qt4agg.NavigationToolbar2QT",
"numpy.fft.rfft",
"PyQt4.QtGui.QLabel",
"PyQt4.QtGui.QCheckBox",
"numpy.abs",
"numpy.floor",
"PyQt4.QtGui.QVBoxLayout",
"matplotlib.backends.backend_qt4agg.FigureCanvasQTAgg",
"matplotlib.pyplot.figure",
"numpy.arange",
"PyQt4.QtGui.QSlider",
"threading.Lock",
"numpy.fromstring",
"numpy.ones_like",
"numpy.ceil",
"numpy.hamming",
"PyQt4.QtGui.QApplication",
"PyQt4.QtGui.QPushButton",
"numpy.fft.rfftfreq",
"PyQt4.QtGui.QWidget.__init__",
"PyQt4.QtGui.QHBoxLayout",
"numpy.array",
"PyQt4.QtGui.QApplication.clipboard",
"pyaudio.PyAudio",
"PyQt4.QtGui.QLCDNumber"
] |
[((9295, 9334), 'numpy.array', 'np.array', (['x'], {'dtype': 'np.double', 'copy': '(True)'}), '(x, dtype=np.double, copy=True)\n', (9303, 9334), True, 'import numpy as np\n'), ((9344, 9362), 'numpy.hamming', 'np.hamming', (['x.size'], {}), '(x.size)\n', (9354, 9362), True, 'import numpy as np\n'), ((9449, 9465), 'numpy.ceil', 'np.ceil', (['(Fs / dF)'], {}), '(Fs / dF)\n', (9456, 9465), True, 'import numpy as np\n'), ((9585, 9614), 'numpy.floor', 'np.floor', (['(1 + n_fft / 2.0 / H)'], {}), '(1 + n_fft / 2.0 / H)\n', (9593, 9614), True, 'import numpy as np\n'), ((9681, 9707), 'numpy.ceil', 'np.ceil', (['(Fmin / Fs * n_fft)'], {}), '(Fmin / Fs * n_fft)\n', (9688, 9707), True, 'import numpy as np\n'), ((9720, 9747), 'numpy.floor', 'np.floor', (['(Fmax / Fs * n_fft)'], {}), '(Fmax / Fs * n_fft)\n', (9728, 9747), True, 'import numpy as np\n'), ((10104, 10132), 'PyQt4.QtGui.QApplication', 'QtGui.QApplication', (['sys.argv'], {}), '(sys.argv)\n', (10122, 10132), False, 'from PyQt4 import QtGui, QtCore\n'), ((653, 670), 'pyaudio.PyAudio', 'pyaudio.PyAudio', ([], {}), '()\n', (668, 670), False, 'import pyaudio\n'), ((1025, 1041), 'threading.Lock', 'threading.Lock', ([], {}), '()\n', (1039, 1041), False, 'import threading\n'), ((1101, 1128), 'atexit.register', 'atexit.register', (['self.close'], {}), '(self.close)\n', (1116, 1128), False, 'import atexit\n'), ((1208, 1236), 'numpy.fromstring', 'np.fromstring', (['data', '"""int16"""'], {}), "(data, 'int16')\n", (1221, 1236), True, 'import numpy as np\n'), ((1875, 1903), 'PyQt4.QtGui.QWidget.__init__', 'QtGui.QWidget.__init__', (['self'], {}), '(self)\n', (1897, 1903), False, 'from PyQt4 import QtGui, QtCore\n'), ((1944, 1963), 'PyQt4.QtGui.QVBoxLayout', 'QtGui.QVBoxLayout', ([], {}), '()\n', (1961, 1963), False, 'from PyQt4 import QtGui, QtCore\n'), ((1980, 2004), 'PyQt4.QtGui.QLabel', 'QtGui.QLabel', (['text_label'], {}), '(text_label)\n', (1992, 2004), False, 'from PyQt4 import QtGui, QtCore\n'), ((2019, 2037), 'PyQt4.QtGui.QLCDNumber', 'QtGui.QLCDNumber', ([], {}), '()\n', (2035, 2037), False, 'from PyQt4 import QtGui, QtCore\n'), ((2238, 2275), 'PyQt4.QtGui.QPushButton', 'QtGui.QPushButton', (['"""set"""'], {'parent': 'self'}), "('set', parent=self)\n", (2255, 2275), False, 'from PyQt4 import QtGui, QtCore\n'), ((2291, 2310), 'PyQt4.QtGui.QVBoxLayout', 'QtGui.QVBoxLayout', ([], {}), '()\n', (2308, 2310), False, 'from PyQt4 import QtGui, QtCore\n'), ((2766, 2795), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'facecolor': '"""white"""'}), "(facecolor='white')\n", (2776, 2795), True, 'import matplotlib.pyplot as plt\n'), ((2818, 2843), 'matplotlib.backends.backend_qt4agg.FigureCanvasQTAgg', 'FigureCanvas', (['self.figure'], {}), '(self.figure)\n', (2830, 2843), True, 'from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas\n'), ((2867, 2905), 'matplotlib.backends.backend_qt4agg.NavigationToolbar2QT', 'NavigationToolbar', (['self.canvas', 'parent'], {}), '(self.canvas, parent)\n', (2884, 2905), True, 'from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar\n'), ((2975, 3003), 'PyQt4.QtGui.QWidget.__init__', 'QtGui.QWidget.__init__', (['self'], {}), '(self)\n', (2997, 3003), False, 'from PyQt4 import QtGui, QtCore\n'), ((3339, 3358), 'PyQt4.QtGui.QHBoxLayout', 'QtGui.QHBoxLayout', ([], {}), '()\n', (3356, 3358), False, 'from PyQt4 import QtGui, QtCore\n'), ((3378, 3403), 'PyQt4.QtGui.QLabel', 'QtGui.QLabel', (['"""Auto gain"""'], {}), "('Auto gain')\n", (3390, 3403), False, 'from PyQt4 import QtGui, QtCore\n'), ((3431, 3460), 'PyQt4.QtGui.QCheckBox', 'QtGui.QCheckBox', ([], {'checked': '(True)'}), '(checked=True)\n', (3446, 3460), False, 'from PyQt4 import QtGui, QtCore\n'), ((3542, 3580), 'PyQt4.QtGui.QPushButton', 'QtGui.QPushButton', (['"""copy to clipboard"""'], {}), "('copy to clipboard')\n", (3559, 3580), False, 'from PyQt4 import QtGui, QtCore\n'), ((3816, 3835), 'PyQt4.QtGui.QHBoxLayout', 'QtGui.QHBoxLayout', ([], {}), '()\n', (3833, 3835), False, 'from PyQt4 import QtGui, QtCore\n'), ((3856, 3888), 'PyQt4.QtGui.QLabel', 'QtGui.QLabel', (['"""Fixed gain level"""'], {}), "('Fixed gain level')\n", (3868, 3888), False, 'from PyQt4 import QtGui, QtCore\n'), ((3915, 3950), 'PyQt4.QtGui.QSlider', 'QtGui.QSlider', (['QtCore.Qt.Horizontal'], {}), '(QtCore.Qt.Horizontal)\n', (3928, 3950), False, 'from PyQt4 import QtGui, QtCore\n'), ((4147, 4166), 'PyQt4.QtGui.QHBoxLayout', 'QtGui.QHBoxLayout', ([], {}), '()\n', (4164, 4166), False, 'from PyQt4 import QtGui, QtCore\n'), ((4440, 4459), 'PyQt4.QtGui.QVBoxLayout', 'QtGui.QVBoxLayout', ([], {}), '()\n', (4457, 4459), False, 'from PyQt4 import QtGui, QtCore\n'), ((5140, 5186), 'numpy.fft.rfftfreq', 'np.fft.rfftfreq', (['mic.chunksize', '(1.0 / mic.rate)'], {}), '(mic.chunksize, 1.0 / mic.rate)\n', (5155, 5186), True, 'import numpy as np\n'), ((5568, 5583), 'PyQt4.QtCore.QTimer', 'QtCore.QTimer', ([], {}), '()\n', (5581, 5583), False, 'from PyQt4 import QtGui, QtCore\n'), ((9026, 9056), 'PyQt4.QtGui.QApplication.clipboard', 'QtGui.QApplication.clipboard', ([], {}), '()\n', (9054, 9056), False, 'from PyQt4 import QtGui, QtCore\n'), ((6713, 6741), 'numpy.ones_like', 'np.ones_like', (['self.time_vect'], {}), '(self.time_vect)\n', (6725, 6741), True, 'import numpy as np\n'), ((6855, 6883), 'numpy.ones_like', 'np.ones_like', (['self.freq_vect'], {}), '(self.freq_vect)\n', (6867, 6883), True, 'import numpy as np\n'), ((7599, 7625), 'numpy.fft.rfft', 'np.fft.rfft', (['current_frame'], {}), '(current_frame)\n', (7610, 7625), True, 'import numpy as np\n'), ((5250, 5292), 'numpy.arange', 'np.arange', (['mic.chunksize'], {'dtype': 'np.float32'}), '(mic.chunksize, dtype=np.float32)\n', (5259, 5292), True, 'import numpy as np\n'), ((7946, 7963), 'numpy.abs', 'np.abs', (['fft_frame'], {}), '(fft_frame)\n', (7952, 7963), True, 'import numpy as np\n'), ((9868, 9887), 'numpy.arange', 'np.arange', (['(1)', '(H + 1)'], {}), '(1, H + 1)\n', (9877, 9887), True, 'import numpy as np\n'), ((9834, 9850), 'numpy.arange', 'np.arange', (['N_max'], {}), '(N_max)\n', (9843, 9850), True, 'import numpy as np\n'), ((9986, 10003), 'numpy.arange', 'np.arange', (['P.size'], {}), '(P.size)\n', (9995, 10003), True, 'import numpy as np\n'), ((10017, 10034), 'numpy.arange', 'np.arange', (['P.size'], {}), '(P.size)\n', (10026, 10034), True, 'import numpy as np\n'), ((7727, 7744), 'numpy.abs', 'np.abs', (['fft_frame'], {}), '(fft_frame)\n', (7733, 7744), True, 'import numpy as np\n')]
|
# ======================================================================
#
# This routine interfaces with IPOPT
# It sets the optimization problem for every training point
# during the VFI.
#
# <NAME>, 11/16 ; 07/17; 01/19
# edited by <NAME>, with <NAME> and <NAME>, 11/2021
# Main difference is the shift from pyipopt to cyipopt
# Involves a class to pass the optimisation problem to ipopt
# ======================================================================
from parameters import *
from ipopt_wrapper_A import ipopt_obj
import numpy as np
# import pyipopt
import cyipopt
def iterate(k_init, n_agt, gp_old=None, final=False, initial=False, verbose=False):
N = n_pol # number of vars
M = n_ctt # number of constraints
NELE_JAC = N * M
NELE_HESS = (N+1)*N/2 # number of non-zero entries of Hess matrix
# Vector of variables -> solution of non-linear equation system
X = np.empty(N)
LAM = np.empty(M) # multipliers
G = np.empty(M) # (in-)equality constraints
# Vector of lower and upper bounds
G_L = np.empty(M)
G_U = np.empty(M)
X_L = np.empty(N)
X_U = np.empty(N)
X_start = np.empty(N)
Z_L = np.empty(N)
Z_U = np.empty(N)
# get coords of an individual grid points
grid_pt_box = k_init
# set bounds for policy variables
for iter in pol_key:
X_L[I[iter]]=pol_L[iter]
X_U[I[iter]]=pol_U[iter]
# initial guesses for first iteration (aka a warm start)
if iter != "sav" and iter != "con": # no warm starts for these
X[I[iter]] = pol_S[iter]
else:
X[I[iter]] = pol_L[iter]
# Set bounds for the constraints
for iter in ctt_key:
G_L[I_ctt[iter]]=ctt_L[iter]
G_U[I_ctt[iter]]=ctt_U[iter]
HS07 = ipopt_obj(X, n_agents=n_agt, k_init=k_init, NELE_JAC=NELE_JAC, NELE_HESS=NELE_HESS, gp_old=gp_old, initial=initial, verbose=verbose)
nlp = cyipopt.Problem(
n=N,
m=M,
problem_obj=HS07,
lb=X_L,
ub=X_U,
cl=G_L,
cu=G_U,
)
nlp.add_option("obj_scaling_factor", -1.00) # max function
nlp.add_option("mu_strategy", "adaptive")
nlp.add_option("tol", alphaSK)
nlp.add_option("print_level", 0)
nlp.add_option("hessian_approximation", "limited-memory")
nlp.add_option("max_iter", 10)
optimal_soln, info = nlp.solve(X)
x = info["x"] # soln of the primal variables
ctt = info["g"] # constraints
obj = info["obj_val"] # objective value
if final != True:
nlp.close()
# x: Solution of the primal variables
# z_l, z_u: Solution of the bound multipliers
# constraint_multipliers: Solution of the constraint
# obj: Objective value
# status: Exit Status
to_print = np.hstack((obj, x))
# == debug ==
# f=open("results.txt", 'a')
# np.savetxt(f, np.transpose(to_print) #, fmt=len(x)*'%10.10f ')
# for num in to_print:
# f.write(str(num)+"\t")
# f.write("\n")
# f.close()
res = dict()
res['obj'] = obj
res['ctt'] = ctt
for iter in pol_key:
res[iter] = x[I[iter]]
return res
|
[
"ipopt_wrapper_A.ipopt_obj",
"numpy.empty",
"cyipopt.Problem",
"numpy.hstack"
] |
[((938, 949), 'numpy.empty', 'np.empty', (['N'], {}), '(N)\n', (946, 949), True, 'import numpy as np\n'), ((961, 972), 'numpy.empty', 'np.empty', (['M'], {}), '(M)\n', (969, 972), True, 'import numpy as np\n'), ((996, 1007), 'numpy.empty', 'np.empty', (['M'], {}), '(M)\n', (1004, 1007), True, 'import numpy as np\n'), ((1087, 1098), 'numpy.empty', 'np.empty', (['M'], {}), '(M)\n', (1095, 1098), True, 'import numpy as np\n'), ((1109, 1120), 'numpy.empty', 'np.empty', (['M'], {}), '(M)\n', (1117, 1120), True, 'import numpy as np\n'), ((1132, 1143), 'numpy.empty', 'np.empty', (['N'], {}), '(N)\n', (1140, 1143), True, 'import numpy as np\n'), ((1154, 1165), 'numpy.empty', 'np.empty', (['N'], {}), '(N)\n', (1162, 1165), True, 'import numpy as np\n'), ((1180, 1191), 'numpy.empty', 'np.empty', (['N'], {}), '(N)\n', (1188, 1191), True, 'import numpy as np\n'), ((1203, 1214), 'numpy.empty', 'np.empty', (['N'], {}), '(N)\n', (1211, 1214), True, 'import numpy as np\n'), ((1225, 1236), 'numpy.empty', 'np.empty', (['N'], {}), '(N)\n', (1233, 1236), True, 'import numpy as np\n'), ((1822, 1959), 'ipopt_wrapper_A.ipopt_obj', 'ipopt_obj', (['X'], {'n_agents': 'n_agt', 'k_init': 'k_init', 'NELE_JAC': 'NELE_JAC', 'NELE_HESS': 'NELE_HESS', 'gp_old': 'gp_old', 'initial': 'initial', 'verbose': 'verbose'}), '(X, n_agents=n_agt, k_init=k_init, NELE_JAC=NELE_JAC, NELE_HESS=\n NELE_HESS, gp_old=gp_old, initial=initial, verbose=verbose)\n', (1831, 1959), False, 'from ipopt_wrapper_A import ipopt_obj\n'), ((1967, 2042), 'cyipopt.Problem', 'cyipopt.Problem', ([], {'n': 'N', 'm': 'M', 'problem_obj': 'HS07', 'lb': 'X_L', 'ub': 'X_U', 'cl': 'G_L', 'cu': 'G_U'}), '(n=N, m=M, problem_obj=HS07, lb=X_L, ub=X_U, cl=G_L, cu=G_U)\n', (1982, 2042), False, 'import cyipopt\n'), ((2817, 2836), 'numpy.hstack', 'np.hstack', (['(obj, x)'], {}), '((obj, x))\n', (2826, 2836), True, 'import numpy as np\n')]
|
import numpy as np
from matplotlib import pyplot as plt
# args to create data from copy past logs:
# cat hb_timeout.txt | uniq -u | grep "timeout in" | cut -d " " -f 1,6 |
# cut -d ":" -f 3- >> hb_timeout.dat
data = np.loadtxt("hb_timeout.dat")
# print(
fig = plt.figure(figsize=(9, 4))
plt.scatter(data[:, 0], data[:, 1])
plt.plot(data[:, 0], data[:, 1], alpha=0.5)
plt.axhspan(0, 50, alpha=0.4, color="red")
idx = np.argmin(data[:, 1])
plt.annotate(f"lowest: {data[idx,1]}ms", xy=data[idx], xytext=(40, 100),
arrowprops=dict(arrowstyle='-', facecolor="black"),)
plt.xlabel("time in seconds")
plt.ylabel("milliseconds till heartbeat timeout")
plt.savefig("hb_timeout.png", dpi=300)
|
[
"matplotlib.pyplot.plot",
"matplotlib.pyplot.scatter",
"numpy.argmin",
"matplotlib.pyplot.figure",
"numpy.loadtxt",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.axhspan"
] |
[((218, 246), 'numpy.loadtxt', 'np.loadtxt', (['"""hb_timeout.dat"""'], {}), "('hb_timeout.dat')\n", (228, 246), True, 'import numpy as np\n'), ((263, 289), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(9, 4)'}), '(figsize=(9, 4))\n', (273, 289), True, 'from matplotlib import pyplot as plt\n'), ((290, 325), 'matplotlib.pyplot.scatter', 'plt.scatter', (['data[:, 0]', 'data[:, 1]'], {}), '(data[:, 0], data[:, 1])\n', (301, 325), True, 'from matplotlib import pyplot as plt\n'), ((326, 369), 'matplotlib.pyplot.plot', 'plt.plot', (['data[:, 0]', 'data[:, 1]'], {'alpha': '(0.5)'}), '(data[:, 0], data[:, 1], alpha=0.5)\n', (334, 369), True, 'from matplotlib import pyplot as plt\n'), ((370, 412), 'matplotlib.pyplot.axhspan', 'plt.axhspan', (['(0)', '(50)'], {'alpha': '(0.4)', 'color': '"""red"""'}), "(0, 50, alpha=0.4, color='red')\n", (381, 412), True, 'from matplotlib import pyplot as plt\n'), ((420, 441), 'numpy.argmin', 'np.argmin', (['data[:, 1]'], {}), '(data[:, 1])\n', (429, 441), True, 'import numpy as np\n'), ((582, 611), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""time in seconds"""'], {}), "('time in seconds')\n", (592, 611), True, 'from matplotlib import pyplot as plt\n'), ((612, 661), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""milliseconds till heartbeat timeout"""'], {}), "('milliseconds till heartbeat timeout')\n", (622, 661), True, 'from matplotlib import pyplot as plt\n'), ((662, 700), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""hb_timeout.png"""'], {'dpi': '(300)'}), "('hb_timeout.png', dpi=300)\n", (673, 700), True, 'from matplotlib import pyplot as plt\n')]
|
import numpy as np
rand_num = np.random.normal(0,1,1)
print("Random number between 0 and 1:")
print(rand_num)
|
[
"numpy.random.normal"
] |
[((30, 55), 'numpy.random.normal', 'np.random.normal', (['(0)', '(1)', '(1)'], {}), '(0, 1, 1)\n', (46, 55), True, 'import numpy as np\n')]
|
from rdkit import Chem
from .AtomProperty import GetRelativeAtomicProperty
import numpy
import numpy.linalg
def getBurdenMatrix(mol, propertylabel='m'):
"""
#################################################################
Calculate Burden matrix and their eigenvalues.
#################################################################
"""
mol=Chem.AddHs(mol)
Natom=mol.GetNumAtoms()
AdMatrix=Chem.GetAdjacencyMatrix(mol)
bondindex=numpy.argwhere(AdMatrix)
AdMatrix1=numpy.array(AdMatrix,dtype=numpy.float32)
#The diagonal elements of B, Bii, are either given by
#the carbon normalized atomic mass,
#van der Waals volume, Sanderson electronegativity,
#and polarizability of atom i.
for i in range(Natom):
atom=mol.GetAtomWithIdx(i)
temp=GetRelativeAtomicProperty(element=atom.GetSymbol(),propertyname=propertylabel)
AdMatrix1[i,i]=round(temp,3)
#The element of B connecting atoms i and j, Bij,
#is equal to the square root of the bond
#order between atoms i and j.
for i in bondindex:
bond=mol.GetBondBetweenAtoms(int(i[0]),int(i[1]))
if bond.GetBondType().name =='SINGLE':
AdMatrix1[i[0],i[1]]=round(numpy.sqrt(1),3)
if bond.GetBondType().name=="DOUBLE":
AdMatrix1[i[0],i[1]]=round(numpy.sqrt(2),3)
if bond.GetBondType().name=="TRIPLE":
AdMatrix1[i[0],i[1]]=round(numpy.sqrt(3),3)
if bond.GetBondType().name=="AROMATIC":
AdMatrix1[i[0],i[1]]=round(numpy.sqrt(1.5),3)
##All other elements of B (corresponding non bonded
#atom pairs) are set to 0.001
bondnonindex=numpy.argwhere(AdMatrix==0)
for i in bondnonindex:
if i[0]!=i[1]:
AdMatrix1[i[0],i[1]]=0.001
return numpy.real(numpy.linalg.eigvals(AdMatrix1))
########################
def getbcutm(mol):
"""
#################################################################
Calculate Burden descriptors based on atomic mass.
res--->dict type with 16 descriptors
#################################################################
"""
temp=getBurdenMatrix(mol,propertylabel='m')
temp1=numpy.sort(temp[temp>=0])
temp2=numpy.sort(numpy.abs(temp[temp<0]))
if len(temp1)<8:
temp1=numpy.concatenate((numpy.zeros(8),temp1))
if len(temp2)<8:
temp2=numpy.concatenate((numpy.zeros(8),temp2))
bcut=["bcutm16","bcutm15","bcutm14","bcutm13","bcutm12","bcutm11","bcutm10",
"bcutm9","bcutm8","bcutm7","bcutm6","bcutm5","bcutm4","bcutm3",
"bcutm2","bcutm1"]
bcutvalue=numpy.concatenate((temp2[-8:],temp1[-8:]))
bcutvalue=[round(i,6) for i in bcutvalue]
res=dict(zip(bcut,bcutvalue))
return res
def getbcutv(mol):
"""
#################################################################
Calculate Burden descriptors based on atomic vloumes
res-->dict type with 16 descriptors
#################################################################
"""
temp=getBurdenMatrix(mol,propertylabel='V')
temp1=numpy.sort(temp[temp>=0])
temp2=numpy.sort(numpy.abs(temp[temp<0]))
if len(temp1)<8:
temp1=numpy.concatenate((numpy.zeros(8),temp1))
if len(temp2)<8:
temp2=numpy.concatenate((numpy.zeros(8),temp2))
bcut=["bcutv16","bcutv15","bcutv14","bcutv13","bcutv12","bcutv11","bcutv10",
"bcutv9","bcutv8","bcutv7","bcutv6","bcutv5","bcutv4","bcutv3",
"bcutv2","bcutv1"]
bcutvalue=numpy.concatenate((temp2[-8:],temp1[-8:]))
bcutvalue=[round(i,3) for i in bcutvalue]
res=dict(zip(bcut,bcutvalue))
return res
def getbcute(mol):
"""
#################################################################
Calculate Burden descriptors based on atomic electronegativity.
res-->dict type with 16 descriptors
#################################################################
"""
temp=getBurdenMatrix(mol,propertylabel='En')
temp1=numpy.sort(temp[temp>=0])
temp2=numpy.sort(numpy.abs(temp[temp<0]))
if len(temp1)<8:
temp1=numpy.concatenate((numpy.zeros(8),temp1))
if len(temp2)<8:
temp2=numpy.concatenate((numpy.zeros(8),temp2))
bcut=["bcute16","bcute15","bcute14","bcute13","bcute12","bcute11","bcute10",
"bcute9","bcute8","bcute7","bcute6","bcute5","bcute4","bcute3",
"bcute2","bcute1"]
bcutvalue=numpy.concatenate((temp2[-8:],temp1[-8:]))
bcutvalue=[round(i,3) for i in bcutvalue]
res=dict(zip(bcut,bcutvalue))
return res
def getbcutp(mol):
"""
#################################################################
Calculate Burden descriptors based on polarizability.
res-->dict type with 16 descriptors
#################################################################
"""
temp=getBurdenMatrix(mol,propertylabel='alapha')
temp1=numpy.sort(temp[temp>=0])
temp2=numpy.sort(numpy.abs(temp[temp<0]))
if len(temp1)<8:
temp1=numpy.concatenate((numpy.zeros(8),temp1))
if len(temp2)<8:
temp2=numpy.concatenate((numpy.zeros(8),temp2))
bcut=["bcutp16","bcutp15","bcutp14","bcutp13","bcutp12","bcutp11","bcutp10",
"bcutp9","bcutp8","bcutp7","bcutp6","bcutp5","bcutp4","bcutp3",
"bcutp2","bcutp1"]
bcutvalue=numpy.concatenate((temp2[-8:],temp1[-8:]))
bcutvalue=[round(i,3) for i in bcutvalue]
res=dict(zip(bcut,bcutvalue))
return res
_bcut = {"bcutm1": getbcutm,
"bcutm2": getbcutm,
"bcutm3": getbcutm,
"bcutm4": getbcutm,
"bcutm5": getbcutm,
"bcutm6": getbcutm,
"bcutm7": getbcutm,
"bcutm8": getbcutm,
"bcutm9": getbcutm,
"bcutm10": getbcutm,
"bcutm11": getbcutm,
"bcutm12": getbcutm,
"bcutm13": getbcutm,
"bcutm14": getbcutm,
"bcutm15": getbcutm,
"bcutm16": getbcutm,
"bcutv1": getbcutv,
"bcutv2": getbcutv,
"bcutv3": getbcutv,
"bcutv4": getbcutv,
"bcutv5": getbcutv,
"bcutv6": getbcutv,
"bcutv7": getbcutv,
"bcutv8": getbcutv,
"bcutv9": getbcutv,
"bcutv10": getbcutv,
"bcutv11": getbcutv,
"bcutv12": getbcutv,
"bcutv13": getbcutv,
"bcutv14": getbcutv,
"bcutv15": getbcutv,
"bcutv16": getbcutv,
"bcute1": getbcute,
"bcute2": getbcute,
"bcute3": getbcute,
"bcute4": getbcute,
"bcute5": getbcute,
"bcute6": getbcute,
"bcute7": getbcute,
"bcute8": getbcute,
"bcute9": getbcute,
"bcute10": getbcute,
"bcute11": getbcute,
"bcute12": getbcute,
"bcute13": getbcute,
"bcute14": getbcute,
"bcute15": getbcute,
"bcute16": getbcute,
"bcutp1": getbcutp,
"bcutp2": getbcutp,
"bcutp3": getbcutp,
"bcutp4": getbcutp,
"bcutp5": getbcutp,
"bcutp6": getbcutp,
"bcutp7": getbcutp,
"bcutp8": getbcutp,
"bcutp9": getbcutp,
"bcutp10": getbcutp,
"bcutp11": getbcutp,
"bcutp12": getbcutp,
"bcutp13": getbcutp,
"bcutp14": getbcutp,
"bcutp15": getbcutp,
"bcutp16": getbcutp
}
def GetBcut(mol):
"""
#################################################################
Calculate all 64 Burden descriptors
res-->dict type
#################################################################
"""
dresult={}
dresult.update(getbcutm(mol))
dresult.update(getbcutv(mol))
dresult.update(getbcute(mol))
dresult.update(getbcutp(mol))
return dresult
|
[
"numpy.linalg.eigvals",
"numpy.abs",
"numpy.concatenate",
"numpy.zeros",
"numpy.sort",
"numpy.array",
"numpy.argwhere",
"rdkit.Chem.AddHs",
"rdkit.Chem.GetAdjacencyMatrix",
"numpy.sqrt"
] |
[((370, 385), 'rdkit.Chem.AddHs', 'Chem.AddHs', (['mol'], {}), '(mol)\n', (380, 385), False, 'from rdkit import Chem\n'), ((428, 456), 'rdkit.Chem.GetAdjacencyMatrix', 'Chem.GetAdjacencyMatrix', (['mol'], {}), '(mol)\n', (451, 456), False, 'from rdkit import Chem\n'), ((471, 495), 'numpy.argwhere', 'numpy.argwhere', (['AdMatrix'], {}), '(AdMatrix)\n', (485, 495), False, 'import numpy\n'), ((510, 552), 'numpy.array', 'numpy.array', (['AdMatrix'], {'dtype': 'numpy.float32'}), '(AdMatrix, dtype=numpy.float32)\n', (521, 552), False, 'import numpy\n'), ((1701, 1730), 'numpy.argwhere', 'numpy.argwhere', (['(AdMatrix == 0)'], {}), '(AdMatrix == 0)\n', (1715, 1730), False, 'import numpy\n'), ((2239, 2266), 'numpy.sort', 'numpy.sort', (['temp[temp >= 0]'], {}), '(temp[temp >= 0])\n', (2249, 2266), False, 'import numpy\n'), ((2673, 2716), 'numpy.concatenate', 'numpy.concatenate', (['(temp2[-8:], temp1[-8:])'], {}), '((temp2[-8:], temp1[-8:]))\n', (2690, 2716), False, 'import numpy\n'), ((3157, 3184), 'numpy.sort', 'numpy.sort', (['temp[temp >= 0]'], {}), '(temp[temp >= 0])\n', (3167, 3184), False, 'import numpy\n'), ((3591, 3634), 'numpy.concatenate', 'numpy.concatenate', (['(temp2[-8:], temp1[-8:])'], {}), '((temp2[-8:], temp1[-8:]))\n', (3608, 3634), False, 'import numpy\n'), ((4079, 4106), 'numpy.sort', 'numpy.sort', (['temp[temp >= 0]'], {}), '(temp[temp >= 0])\n', (4089, 4106), False, 'import numpy\n'), ((4513, 4556), 'numpy.concatenate', 'numpy.concatenate', (['(temp2[-8:], temp1[-8:])'], {}), '((temp2[-8:], temp1[-8:]))\n', (4530, 4556), False, 'import numpy\n'), ((4994, 5021), 'numpy.sort', 'numpy.sort', (['temp[temp >= 0]'], {}), '(temp[temp >= 0])\n', (5004, 5021), False, 'import numpy\n'), ((5428, 5471), 'numpy.concatenate', 'numpy.concatenate', (['(temp2[-8:], temp1[-8:])'], {}), '((temp2[-8:], temp1[-8:]))\n', (5445, 5471), False, 'import numpy\n'), ((1845, 1876), 'numpy.linalg.eigvals', 'numpy.linalg.eigvals', (['AdMatrix1'], {}), '(AdMatrix1)\n', (1865, 1876), False, 'import numpy\n'), ((2286, 2311), 'numpy.abs', 'numpy.abs', (['temp[temp < 0]'], {}), '(temp[temp < 0])\n', (2295, 2311), False, 'import numpy\n'), ((3204, 3229), 'numpy.abs', 'numpy.abs', (['temp[temp < 0]'], {}), '(temp[temp < 0])\n', (3213, 3229), False, 'import numpy\n'), ((4126, 4151), 'numpy.abs', 'numpy.abs', (['temp[temp < 0]'], {}), '(temp[temp < 0])\n', (4135, 4151), False, 'import numpy\n'), ((5041, 5066), 'numpy.abs', 'numpy.abs', (['temp[temp < 0]'], {}), '(temp[temp < 0])\n', (5050, 5066), False, 'import numpy\n'), ((1254, 1267), 'numpy.sqrt', 'numpy.sqrt', (['(1)'], {}), '(1)\n', (1264, 1267), False, 'import numpy\n'), ((1356, 1369), 'numpy.sqrt', 'numpy.sqrt', (['(2)'], {}), '(2)\n', (1366, 1369), False, 'import numpy\n'), ((1458, 1471), 'numpy.sqrt', 'numpy.sqrt', (['(3)'], {}), '(3)\n', (1468, 1471), False, 'import numpy\n'), ((1562, 1577), 'numpy.sqrt', 'numpy.sqrt', (['(1.5)'], {}), '(1.5)\n', (1572, 1577), False, 'import numpy\n'), ((2370, 2384), 'numpy.zeros', 'numpy.zeros', (['(8)'], {}), '(8)\n', (2381, 2384), False, 'import numpy\n'), ((2447, 2461), 'numpy.zeros', 'numpy.zeros', (['(8)'], {}), '(8)\n', (2458, 2461), False, 'import numpy\n'), ((3288, 3302), 'numpy.zeros', 'numpy.zeros', (['(8)'], {}), '(8)\n', (3299, 3302), False, 'import numpy\n'), ((3365, 3379), 'numpy.zeros', 'numpy.zeros', (['(8)'], {}), '(8)\n', (3376, 3379), False, 'import numpy\n'), ((4210, 4224), 'numpy.zeros', 'numpy.zeros', (['(8)'], {}), '(8)\n', (4221, 4224), False, 'import numpy\n'), ((4287, 4301), 'numpy.zeros', 'numpy.zeros', (['(8)'], {}), '(8)\n', (4298, 4301), False, 'import numpy\n'), ((5125, 5139), 'numpy.zeros', 'numpy.zeros', (['(8)'], {}), '(8)\n', (5136, 5139), False, 'import numpy\n'), ((5202, 5216), 'numpy.zeros', 'numpy.zeros', (['(8)'], {}), '(8)\n', (5213, 5216), False, 'import numpy\n')]
|
#!/usr/bin/env python
# coding: utf-8
# In[2]:
import numpy as np
import pandas as pd
import sklearn as skl
import random
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder
from sklearn.preprocessing import StandardScaler
import re
import sys
from math import floor
import matplotlib.pyplot as plt
from Bio import SeqIO
# In[2]:
def convert_seq_to_array(seq) :
seq = seq.lower()
seq = re.sub('[^acgt]','z',seq)
seq_array = np.array(list(seq))
return seq_array
def one_hot_encoder(seq_array) :
label_encoder = LabelEncoder()
onehot_encoder = OneHotEncoder(sparse = False, dtype=int,categories=[range(5)])
seq_convert_int = label_encoder.fit_transform(seq_array)
seq_convert_int = seq_convert_int.reshape(len(seq_convert_int),1)
seq_onehot = onehot_encoder.fit_transform(seq_convert_int)
seq_onehot = np.delete(seq_onehot, -1, 1)
return seq_onehot
# In[3]:
def saveDataSet(path,train_genenames, train_expressions, train_sequences, test_genenames, test_expressions, test_sequences) :
train_genenames = np.array(train_genenames)
train_sequences = np.array(train_sequences)
train_expressions = np.array(train_expressions)
#variance_y = np.var(train_expressions)
#moyenne_y = np.mean(train_expressions)
#train_expressionsnorm = (train_expressions-moyenne_y)/variance_y
print('before',train_expressions)
#train_expressions = train_expressions.reshape(-1,1)
#dataset_scaler = StandardScaler()
#train_expressions = dataset_scaler.fit_transform(train_expressions)
#train_expressions = train_expressions.reshape(-1)
#print('after',train_expressionsnorm)
np.save(path + "genenames_trainset.npy", train_genenames)
np.save(path + "seqs_trainset.npy", train_sequences)
np.save(path + "exps_trainset.npy", train_expressions)
print("Enregistrement du training set fini...\n")
test_genenames = np.array(test_genenames)
test_sequences = np.array(test_sequences)
test_expressions = np.array(test_expressions)
#variance_y = np.var(test_expressions)
#moyenne_y = np.mean(test_expressions)
#test_expressionsnorm = (test_expressions-moyenne_y)/variance_y
print("before",test_expressions)
#test_expressions = test_expressions.reshape(-1,1)
#test_expressions = dataset_scaler.transform(test_expressions)
#test_expressions = test_expressions.reshape(-1)
#print("after",test_expressionsnorm)
np.save(path + "genenames_testset.npy", test_genenames)
np.save(path + "seqs_testset.npy", test_sequences)
np.save(path + "exps_testset.npy", test_expressions)
print("Enregistrement du test set fini...\n")
# In[4]:
def saveClusterDataSet(path,ctrain_genenames, ctrain_sequences, ctrain_expressions ,ctest_genenames,ctest_sequences,ctest_expressions,cluster):
ctrain_genenames = np.array(ctrain_genenames)
ctrain_sequences = np.array(ctrain_sequences)
ctrain_expressions = np.array(ctrain_expressions)
#variance_y = np.var(ctrain_expressions)
#moyenne_y = np.mean(ctrain_expressions)
#ctrain_expressionsnorm = (ctrain_expressions-moyenne_y)/variance_y
print("before",ctrain_expressions)
#ctrain_expressions = ctrain_expressions.reshape(-1,1)
#cluster_scaler = StandardScaler()
#ctrain_expressions = cluster_scaler.fit_transform(ctrain_expressions)
#ctrain_expressions = ctrain_expressions.reshape(-1)
#print("after",ctrain_expressionsnorm)
np.save(path + "cluster"+ str(cluster)+"_genenames_trainset.npy", ctrain_genenames)
np.save(path + "cluster"+ str(cluster)+"_seqs_trainset.npy", ctrain_sequences)
np.save(path + "cluster"+ str(cluster)+"_exps_trainset.npy", ctrain_expressions)
print("Enregistrement du training set", cluster," fini...\n")
ctest_genenames = np.array(ctest_genenames)
ctest_sequences = np.array(ctest_sequences)
ctest_expressions = np.array(ctest_expressions)
#variance_y = np.var(ctest_expressions)
#moyenne_y = np.mean(ctest_expressions)
#ctest_expressionsnorm = (ctest_expressions-moyenne_y)/variance_y
print("before",ctest_expressions)
#ctest_expressions = ctest_expressions.reshape(-1,1)
#ctest_expressions = cluster_scaler.transform(ctest_expressions)
#ctest_expressions= ctest_expressions.reshape(-1)
#print("after",ctest_expressionsnorm)
np.save(path + "cluster"+ str(cluster)+"_genenames_testset.npy", ctest_genenames)
np.save(path + "cluster"+ str(cluster)+"_seqs_testset.npy", ctest_sequences)
np.save(path + "cluster"+ str(cluster)+"_exps_testset.npy", ctest_expressions)
print("Enregistrement du test set", cluster," fini...\n")
# In[5]:
def saveDataSetlog(path,train_genenames, train_expressions, train_sequences, test_genenames, test_expressions, test_sequences) :
train_genenames = np.array(train_genenames)
train_sequences = np.array(train_sequences)
train_expressions = np.array(train_expressions)
print('before',train_expressions)
train_expressionslog = np.log(train_expressions)
print('after',train_expressionslog)
np.save(path + "genenames_trainset.npy", train_genenames)
np.save(path + "seqs_trainset.npy", train_sequences)
np.save(path + "exps_trainset.npy", train_expressionslog)
print("Enregistrement du training set fini...\n")
test_genenames = np.array(test_genenames)
test_sequences = np.array(test_sequences)
test_expressions = np.array(test_expressions)
print("before",test_expressions)
test_expressionslog = np.log(test_expressions)
print("after",test_expressionslog)
np.save(path + "genenames_testset.npy", test_genenames)
np.save(path + "seqs_testset.npy", test_sequences)
np.save(path + "exps_testset.npy", test_expressionslog)
print("Enregistrement du test set fini...\n")
# In[6]:
def saveClusterDataSetlog(path,ctrain_genenames, ctrain_sequences, ctrain_expressions ,ctest_genenames,ctest_sequences,ctest_expressions,cluster):
ctrain_genenames = np.array(ctrain_genenames)
ctrain_sequences = np.array(ctrain_sequences)
ctrain_expressions = np.array(ctrain_expressions)
ctrain_expressionslog = np.log(ctrain_expressions)
print(ctrain_expressions)
print(ctrain_expressionslog)
np.save(path + "cluster"+ str(cluster)+"_genenames_trainset.npy", ctrain_genenames)
np.save(path + "cluster"+ str(cluster)+"_seqs_trainset.npy", ctrain_sequences)
np.save(path + "cluster"+ str(cluster)+"_exps_trainset.npy", ctrain_expressionslog)
print("Enregistrement du training set", cluster," fini...\n")
ctest_genenames = np.array(ctest_genenames)
ctest_sequences = np.array(ctest_sequences)
ctest_expressions = np.array(ctest_expressions)
print("before",ctest_expressions)
ctest_expressionslog = np.log(ctest_expressions)
print("after",ctest_expressionslog)
np.save(path + "cluster"+ str(cluster)+"_genenames_testset.npy", ctest_genenames)
np.save(path + "cluster"+ str(cluster)+"_seqs_testset.npy", ctest_sequences)
np.save(path + "cluster"+ str(cluster)+"_exps_testset.npy", ctest_expressionslog)
print("Enregistrement du test set", cluster," fini...\n")
# In[7]:
#%%time
clusters = []
with open('cluster_101bp_sumQ20.fa') as fasta_file:
for seq_record in SeqIO.parse(fasta_file, 'fasta'):
split_id = seq_record.id.split("|")
clusters.append(split_id[1])
print("Nbr exemples :",len(clusters))
# In[8]:
clusters = list(set(clusters)) #rendre la liste unique
print("Clusters :",clusters)
print("nombre Clusters :",len(clusters))
# In[9]:
#%%time
cluster_list = []
for i in range(len(clusters)+1) :
cluster_list.append([])
with open('cluster_101bp_sumQ20.fa') as fasta_file:
for seq_record in SeqIO.parse(fasta_file, 'fasta'):
split_id = seq_record.id.split("|")
cluster = int(split_id[1])
cluster_list[cluster].append(seq_record)
# In[10]:
#%%time
path = "./cluster_dataset/"
i=0
ratio = 0.20
data_train = []
data_test = []
for i in range(1,len(cluster_list)) :
cluster=[]
for seq_record in cluster_list[i] :
cluster.append(seq_record)
np.random.shuffle(cluster)
split = int(np.floor(ratio * len(cluster)))
print("Split indice c",i,":",split)
cluster_train, cluster_test = cluster[split:], cluster[:split]
print("cluster_train :",len(cluster_train), "/","cluster_test :", len(cluster_test))
data_train.extend(cluster_train)
data_test.extend(cluster_test)
ctrain_genenames = []
ctrain_sequences = []
ctrain_expressions = []
for seq_record in cluster_train :
#data_train.append(seq_record)
split_id = seq_record.id.split("|")
ctrain_genenames.append(split_id[0])
ctrain_expressions.append(float(split_id[2]))
sequence = str(seq_record.seq)
seqconvert = one_hot_encoder(convert_seq_to_array(sequence))
ctrain_sequences.append(seqconvert)
print("Len cluster trainset :",len(ctrain_sequences))
ctest_genenames = []
ctest_sequences = []
ctest_expressions = []
for seq_record in cluster_test :
#data_test.append(seq_record)
split_id = seq_record.id.split("|")
ctest_genenames.append(split_id[0])
ctest_expressions.append(float(split_id[2]))
sequence = str(seq_record.seq)
seqconvert = one_hot_encoder(convert_seq_to_array(sequence))
ctest_sequences.append(seqconvert)
print("Len cluster testset :",len(ctest_sequences))
saveClusterDataSetlog(path,ctrain_genenames, ctrain_sequences, ctrain_expressions ,ctest_genenames,ctest_sequences,ctest_expressions,i)
i+=1
# In[11]:
#%%time
path = "./dataset/"
print("data_train :",len(data_train), "/","data_test :", len(data_test))
train_genenames = []
train_expressions = []
train_sequences = []
test_genenames = []
test_expressions = []
test_sequences = []
for seq_record in data_train :
split_id = seq_record.id.split("|")
train_genenames.append(split_id[0])
train_expressions.append(float(split_id[2]))
seq = str(seq_record.seq)
seqconvert = one_hot_encoder(convert_seq_to_array(seq))
train_sequences.append(seqconvert)
for seq_record in data_test :
split_id = seq_record.id.split("|")
test_genenames.append(split_id[0])
test_expressions.append(float(split_id[2]))
seq = str(seq_record.seq)
seqconvert = one_hot_encoder(convert_seq_to_array(seq))
test_sequences.append(seqconvert)
print("train_sequences :",len(train_sequences), "/","test_sequences :", len(test_sequences))
saveDataSetlog(path,train_genenames, train_expressions, train_sequences, test_genenames, test_expressions, test_sequences)
|
[
"numpy.save",
"Bio.SeqIO.parse",
"numpy.log",
"sklearn.preprocessing.LabelEncoder",
"numpy.array",
"re.sub",
"numpy.delete",
"numpy.random.shuffle"
] |
[((444, 471), 're.sub', 're.sub', (['"""[^acgt]"""', '"""z"""', 'seq'], {}), "('[^acgt]', 'z', seq)\n", (450, 471), False, 'import re\n'), ((581, 595), 'sklearn.preprocessing.LabelEncoder', 'LabelEncoder', ([], {}), '()\n', (593, 595), False, 'from sklearn.preprocessing import LabelEncoder\n'), ((891, 919), 'numpy.delete', 'np.delete', (['seq_onehot', '(-1)', '(1)'], {}), '(seq_onehot, -1, 1)\n', (900, 919), True, 'import numpy as np\n'), ((1108, 1133), 'numpy.array', 'np.array', (['train_genenames'], {}), '(train_genenames)\n', (1116, 1133), True, 'import numpy as np\n'), ((1156, 1181), 'numpy.array', 'np.array', (['train_sequences'], {}), '(train_sequences)\n', (1164, 1181), True, 'import numpy as np\n'), ((1206, 1233), 'numpy.array', 'np.array', (['train_expressions'], {}), '(train_expressions)\n', (1214, 1233), True, 'import numpy as np\n'), ((1711, 1768), 'numpy.save', 'np.save', (["(path + 'genenames_trainset.npy')", 'train_genenames'], {}), "(path + 'genenames_trainset.npy', train_genenames)\n", (1718, 1768), True, 'import numpy as np\n'), ((1773, 1825), 'numpy.save', 'np.save', (["(path + 'seqs_trainset.npy')", 'train_sequences'], {}), "(path + 'seqs_trainset.npy', train_sequences)\n", (1780, 1825), True, 'import numpy as np\n'), ((1830, 1884), 'numpy.save', 'np.save', (["(path + 'exps_trainset.npy')", 'train_expressions'], {}), "(path + 'exps_trainset.npy', train_expressions)\n", (1837, 1884), True, 'import numpy as np\n'), ((1965, 1989), 'numpy.array', 'np.array', (['test_genenames'], {}), '(test_genenames)\n', (1973, 1989), True, 'import numpy as np\n'), ((2011, 2035), 'numpy.array', 'np.array', (['test_sequences'], {}), '(test_sequences)\n', (2019, 2035), True, 'import numpy as np\n'), ((2059, 2085), 'numpy.array', 'np.array', (['test_expressions'], {}), '(test_expressions)\n', (2067, 2085), True, 'import numpy as np\n'), ((2508, 2563), 'numpy.save', 'np.save', (["(path + 'genenames_testset.npy')", 'test_genenames'], {}), "(path + 'genenames_testset.npy', test_genenames)\n", (2515, 2563), True, 'import numpy as np\n'), ((2568, 2618), 'numpy.save', 'np.save', (["(path + 'seqs_testset.npy')", 'test_sequences'], {}), "(path + 'seqs_testset.npy', test_sequences)\n", (2575, 2618), True, 'import numpy as np\n'), ((2623, 2675), 'numpy.save', 'np.save', (["(path + 'exps_testset.npy')", 'test_expressions'], {}), "(path + 'exps_testset.npy', test_expressions)\n", (2630, 2675), True, 'import numpy as np\n'), ((2911, 2937), 'numpy.array', 'np.array', (['ctrain_genenames'], {}), '(ctrain_genenames)\n', (2919, 2937), True, 'import numpy as np\n'), ((2961, 2987), 'numpy.array', 'np.array', (['ctrain_sequences'], {}), '(ctrain_sequences)\n', (2969, 2987), True, 'import numpy as np\n'), ((3013, 3041), 'numpy.array', 'np.array', (['ctrain_expressions'], {}), '(ctrain_expressions)\n', (3021, 3041), True, 'import numpy as np\n'), ((3876, 3901), 'numpy.array', 'np.array', (['ctest_genenames'], {}), '(ctest_genenames)\n', (3884, 3901), True, 'import numpy as np\n'), ((3924, 3949), 'numpy.array', 'np.array', (['ctest_sequences'], {}), '(ctest_sequences)\n', (3932, 3949), True, 'import numpy as np\n'), ((3974, 4001), 'numpy.array', 'np.array', (['ctest_expressions'], {}), '(ctest_expressions)\n', (3982, 4001), True, 'import numpy as np\n'), ((4919, 4944), 'numpy.array', 'np.array', (['train_genenames'], {}), '(train_genenames)\n', (4927, 4944), True, 'import numpy as np\n'), ((4967, 4992), 'numpy.array', 'np.array', (['train_sequences'], {}), '(train_sequences)\n', (4975, 4992), True, 'import numpy as np\n'), ((5017, 5044), 'numpy.array', 'np.array', (['train_expressions'], {}), '(train_expressions)\n', (5025, 5044), True, 'import numpy as np\n'), ((5116, 5141), 'numpy.log', 'np.log', (['train_expressions'], {}), '(train_expressions)\n', (5122, 5141), True, 'import numpy as np\n'), ((5188, 5245), 'numpy.save', 'np.save', (["(path + 'genenames_trainset.npy')", 'train_genenames'], {}), "(path + 'genenames_trainset.npy', train_genenames)\n", (5195, 5245), True, 'import numpy as np\n'), ((5250, 5302), 'numpy.save', 'np.save', (["(path + 'seqs_trainset.npy')", 'train_sequences'], {}), "(path + 'seqs_trainset.npy', train_sequences)\n", (5257, 5302), True, 'import numpy as np\n'), ((5307, 5364), 'numpy.save', 'np.save', (["(path + 'exps_trainset.npy')", 'train_expressionslog'], {}), "(path + 'exps_trainset.npy', train_expressionslog)\n", (5314, 5364), True, 'import numpy as np\n'), ((5445, 5469), 'numpy.array', 'np.array', (['test_genenames'], {}), '(test_genenames)\n', (5453, 5469), True, 'import numpy as np\n'), ((5491, 5515), 'numpy.array', 'np.array', (['test_sequences'], {}), '(test_sequences)\n', (5499, 5515), True, 'import numpy as np\n'), ((5539, 5565), 'numpy.array', 'np.array', (['test_expressions'], {}), '(test_expressions)\n', (5547, 5565), True, 'import numpy as np\n'), ((5635, 5659), 'numpy.log', 'np.log', (['test_expressions'], {}), '(test_expressions)\n', (5641, 5659), True, 'import numpy as np\n'), ((5705, 5760), 'numpy.save', 'np.save', (["(path + 'genenames_testset.npy')", 'test_genenames'], {}), "(path + 'genenames_testset.npy', test_genenames)\n", (5712, 5760), True, 'import numpy as np\n'), ((5765, 5815), 'numpy.save', 'np.save', (["(path + 'seqs_testset.npy')", 'test_sequences'], {}), "(path + 'seqs_testset.npy', test_sequences)\n", (5772, 5815), True, 'import numpy as np\n'), ((5820, 5875), 'numpy.save', 'np.save', (["(path + 'exps_testset.npy')", 'test_expressionslog'], {}), "(path + 'exps_testset.npy', test_expressionslog)\n", (5827, 5875), True, 'import numpy as np\n'), ((6114, 6140), 'numpy.array', 'np.array', (['ctrain_genenames'], {}), '(ctrain_genenames)\n', (6122, 6140), True, 'import numpy as np\n'), ((6164, 6190), 'numpy.array', 'np.array', (['ctrain_sequences'], {}), '(ctrain_sequences)\n', (6172, 6190), True, 'import numpy as np\n'), ((6216, 6244), 'numpy.array', 'np.array', (['ctrain_expressions'], {}), '(ctrain_expressions)\n', (6224, 6244), True, 'import numpy as np\n'), ((6279, 6305), 'numpy.log', 'np.log', (['ctrain_expressions'], {}), '(ctrain_expressions)\n', (6285, 6305), True, 'import numpy as np\n'), ((6722, 6747), 'numpy.array', 'np.array', (['ctest_genenames'], {}), '(ctest_genenames)\n', (6730, 6747), True, 'import numpy as np\n'), ((6770, 6795), 'numpy.array', 'np.array', (['ctest_sequences'], {}), '(ctest_sequences)\n', (6778, 6795), True, 'import numpy as np\n'), ((6820, 6847), 'numpy.array', 'np.array', (['ctest_expressions'], {}), '(ctest_expressions)\n', (6828, 6847), True, 'import numpy as np\n'), ((6925, 6950), 'numpy.log', 'np.log', (['ctest_expressions'], {}), '(ctest_expressions)\n', (6931, 6950), True, 'import numpy as np\n'), ((7421, 7453), 'Bio.SeqIO.parse', 'SeqIO.parse', (['fasta_file', '"""fasta"""'], {}), "(fasta_file, 'fasta')\n", (7432, 7453), False, 'from Bio import SeqIO\n'), ((7892, 7924), 'Bio.SeqIO.parse', 'SeqIO.parse', (['fasta_file', '"""fasta"""'], {}), "(fasta_file, 'fasta')\n", (7903, 7924), False, 'from Bio import SeqIO\n'), ((8293, 8319), 'numpy.random.shuffle', 'np.random.shuffle', (['cluster'], {}), '(cluster)\n', (8310, 8319), True, 'import numpy as np\n')]
|
import numpy as np
import torch, sys, os, pdb
from .jindlib import JindLib
def main():
import pickle
with open('data/dendrites_annotated.pkl', 'rb') as f:
data = pickle.load(f)
cell_ids = np.arange(len(data))
np.random.seed(0)
# np.random.shuffle(cell_ids)
# l = int(0.5*len(cell_ids))
batches = list(set(data['batch']))
batches.sort()
l = int(0.5*len(batches))
train_data = data[data['batch'].isin(batches[0:1])].copy()
test_data = data[data['batch'].isin(batches[1:2])].copy()
train_labels = train_data['labels']
# train_gene_mat = train_data.drop(['labels', 'batch'], 1)
test_labels = test_data['labels']
# test_gene_mat = test_data.drop(['labels', 'batch'], 1)
common_labels = list(set(train_labels) & set(test_labels))
train_data = train_data[train_data['labels'].isin(common_labels)].copy()
test_data = data[data['batch'].isin(batches[1:2])].copy()
# test_data = test_data[test_data['labels'].isin(common_labels)].copy()
# test_data = test_data[test_data['labels'].isin(common_labels)].copy()
train_labels = train_data['labels']
train_gene_mat = train_data.drop(['labels', 'batch'], 1)
test_labels = test_data['labels']
test_gene_mat = test_data.drop(['labels', 'batch'], 1)
# assert (set(train_labels)) == (set(test_labels))
common_labels.sort()
testing_set = list(set(test_labels))
testing_set.sort()
print("Selected Common Labels", common_labels)
print("Test Labels", testing_set)
with open('dendrites_results/scRNALib_objbr.pkl', 'rb') as f:
obj = pickle.load(f)
torch.set_num_threads(25)
obj.evaluate(test_gene_mat, test_labels, frac=0.0, name="testcfmtbr.pdf", test=True)
# pdb.set_trace()
if __name__ == "__main__":
main()
|
[
"pickle.load",
"torch.set_num_threads",
"numpy.random.seed"
] |
[((217, 234), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (231, 234), True, 'import numpy as np\n'), ((1527, 1552), 'torch.set_num_threads', 'torch.set_num_threads', (['(25)'], {}), '(25)\n', (1548, 1552), False, 'import torch, sys, os, pdb\n'), ((168, 182), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (179, 182), False, 'import pickle\n'), ((1509, 1523), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (1520, 1523), False, 'import pickle\n')]
|
from sre_parse import fix_flags
from cv2 import FileStorage_UNDEFINED
import numpy as np
import pandas as pd
from pandas.io import sql
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
df= pd.read_csv('HINDALCO.csv', index_col=False, delimiter = ',')
df = df.set_index(pd.DatetimeIndex(df['datetime'].values))
# print(df.head())
plt.figure(figsize=(16,8))
plt.title('Close Price History', fontsize=18)
plt.plot(df['close'])
plt.xlabel('Date',fontsize=18)
plt.ylabel('Close Price', fontsize=18)
# plt.show()
# fn to calculate the simple moving average (SMA)
def SMA(data,timeperiod=30,column="close"):
return data[column].rolling(window=timeperiod).mean()
#create two colms to store 20 day and 50 day SMA
df['SMA20']=SMA(df,20)
df['SMA50']=SMA(df,50)
df['Signal'] = np.where(df['SMA20'] > df['SMA50'],1,0)
df['Position'] = df['Signal'].diff()
df["Buy"]=np.where(df['Position']==1,df['close'],0)
df["Sell"]=np.where(df['Position']==-1,df['close'],0)
plt.figure(figsize=(16,8))
plt.title('Close Price History with Buys/Sell signal', fontsize=18)
plt.plot(df['close'],alpha=0.5,label="Close")
plt.plot(df['SMA20'],alpha=0.5,label="SMA20")
plt.plot(df['SMA50'],alpha=0.5,label="SMA50")
plt.scatter(df.index, df['Buy'], alpha=1, label="Buy Signal", marker = '^' , color='green')
plt.scatter(df.index, df['Sell'], alpha=1, label="Sell Signal", marker = 'v' , color='red')
plt.xlabel('Date',fontsize=18)
plt.ylabel('Close Price', fontsize=18)
plt.show()
# preprocessing before stroing into database
df['SMA20'] = df['SMA20'].fillna(0)
df['SMA50'] = df['SMA50'].fillna(0)
df['Position'] = df['Position'].fillna(0)
print(df['Signal'].unique())
#storing into csvfile
# df.to_csv("finalhindalco.csv")
#Storing back into MYSQL into a new table
import mysql.connector as mysql
from mysql.connector import Error
try:
conn = mysql.connect(host='localhost', database='invsto', user='root', password='<PASSWORD>')
if conn.is_connected():
cursor = conn.cursor()
cursor.execute("select database();")
record = cursor.fetchone()
cursor.execute("CREATE TABLE hindSMA(datetime datetime,close decimal(10,4),high decimal(10,4),low decimal(10,4),open decimal(10,4),volume int,instrument varchar(255),SMA20 decimal(14,7),SMA50 decimal(14,7),signals int,position int, buy decimal(14,7), sell decimal(14,7))")
print("You're connected to database: ", record)
for i,row in df.iterrows():
# print("Record inserted",tuple(row))
sql = "INSERT INTO invsto.hindSMA VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
cursor.execute(sql, tuple(row))
conn.commit()
print("Query executed")
except Error as e:
print("Error while connecting to MySQL", e)
|
[
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"mysql.connector.connect",
"pandas.read_csv",
"matplotlib.pyplot.scatter",
"pandas.DatetimeIndex",
"matplotlib.pyplot.style.use",
"matplotlib.pyplot.figure",
"numpy.where",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel"
] |
[((177, 209), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""fivethirtyeight"""'], {}), "('fivethirtyeight')\n", (190, 209), True, 'import matplotlib.pyplot as plt\n'), ((217, 276), 'pandas.read_csv', 'pd.read_csv', (['"""HINDALCO.csv"""'], {'index_col': '(False)', 'delimiter': '""","""'}), "('HINDALCO.csv', index_col=False, delimiter=',')\n", (228, 276), True, 'import pandas as pd\n'), ((364, 391), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(16, 8)'}), '(figsize=(16, 8))\n', (374, 391), True, 'import matplotlib.pyplot as plt\n'), ((392, 437), 'matplotlib.pyplot.title', 'plt.title', (['"""Close Price History"""'], {'fontsize': '(18)'}), "('Close Price History', fontsize=18)\n", (401, 437), True, 'import matplotlib.pyplot as plt\n'), ((439, 460), 'matplotlib.pyplot.plot', 'plt.plot', (["df['close']"], {}), "(df['close'])\n", (447, 460), True, 'import matplotlib.pyplot as plt\n'), ((462, 493), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Date"""'], {'fontsize': '(18)'}), "('Date', fontsize=18)\n", (472, 493), True, 'import matplotlib.pyplot as plt\n'), ((494, 532), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Close Price"""'], {'fontsize': '(18)'}), "('Close Price', fontsize=18)\n", (504, 532), True, 'import matplotlib.pyplot as plt\n'), ((820, 861), 'numpy.where', 'np.where', (["(df['SMA20'] > df['SMA50'])", '(1)', '(0)'], {}), "(df['SMA20'] > df['SMA50'], 1, 0)\n", (828, 861), True, 'import numpy as np\n'), ((913, 958), 'numpy.where', 'np.where', (["(df['Position'] == 1)", "df['close']", '(0)'], {}), "(df['Position'] == 1, df['close'], 0)\n", (921, 958), True, 'import numpy as np\n'), ((969, 1015), 'numpy.where', 'np.where', (["(df['Position'] == -1)", "df['close']", '(0)'], {}), "(df['Position'] == -1, df['close'], 0)\n", (977, 1015), True, 'import numpy as np\n'), ((1017, 1044), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(16, 8)'}), '(figsize=(16, 8))\n', (1027, 1044), True, 'import matplotlib.pyplot as plt\n'), ((1045, 1112), 'matplotlib.pyplot.title', 'plt.title', (['"""Close Price History with Buys/Sell signal"""'], {'fontsize': '(18)'}), "('Close Price History with Buys/Sell signal', fontsize=18)\n", (1054, 1112), True, 'import matplotlib.pyplot as plt\n'), ((1114, 1161), 'matplotlib.pyplot.plot', 'plt.plot', (["df['close']"], {'alpha': '(0.5)', 'label': '"""Close"""'}), "(df['close'], alpha=0.5, label='Close')\n", (1122, 1161), True, 'import matplotlib.pyplot as plt\n'), ((1161, 1208), 'matplotlib.pyplot.plot', 'plt.plot', (["df['SMA20']"], {'alpha': '(0.5)', 'label': '"""SMA20"""'}), "(df['SMA20'], alpha=0.5, label='SMA20')\n", (1169, 1208), True, 'import matplotlib.pyplot as plt\n'), ((1208, 1255), 'matplotlib.pyplot.plot', 'plt.plot', (["df['SMA50']"], {'alpha': '(0.5)', 'label': '"""SMA50"""'}), "(df['SMA50'], alpha=0.5, label='SMA50')\n", (1216, 1255), True, 'import matplotlib.pyplot as plt\n'), ((1255, 1347), 'matplotlib.pyplot.scatter', 'plt.scatter', (['df.index', "df['Buy']"], {'alpha': '(1)', 'label': '"""Buy Signal"""', 'marker': '"""^"""', 'color': '"""green"""'}), "(df.index, df['Buy'], alpha=1, label='Buy Signal', marker='^',\n color='green')\n", (1266, 1347), True, 'import matplotlib.pyplot as plt\n'), ((1348, 1440), 'matplotlib.pyplot.scatter', 'plt.scatter', (['df.index', "df['Sell']"], {'alpha': '(1)', 'label': '"""Sell Signal"""', 'marker': '"""v"""', 'color': '"""red"""'}), "(df.index, df['Sell'], alpha=1, label='Sell Signal', marker='v',\n color='red')\n", (1359, 1440), True, 'import matplotlib.pyplot as plt\n'), ((1441, 1472), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Date"""'], {'fontsize': '(18)'}), "('Date', fontsize=18)\n", (1451, 1472), True, 'import matplotlib.pyplot as plt\n'), ((1473, 1511), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Close Price"""'], {'fontsize': '(18)'}), "('Close Price', fontsize=18)\n", (1483, 1511), True, 'import matplotlib.pyplot as plt\n'), ((1513, 1523), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1521, 1523), True, 'import matplotlib.pyplot as plt\n'), ((300, 339), 'pandas.DatetimeIndex', 'pd.DatetimeIndex', (["df['datetime'].values"], {}), "(df['datetime'].values)\n", (316, 339), True, 'import pandas as pd\n'), ((1913, 2004), 'mysql.connector.connect', 'mysql.connect', ([], {'host': '"""localhost"""', 'database': '"""invsto"""', 'user': '"""root"""', 'password': '"""<PASSWORD>"""'}), "(host='localhost', database='invsto', user='root', password=\n '<PASSWORD>')\n", (1926, 2004), True, 'import mysql.connector as mysql\n')]
|
import torch
from torch import nn
from torch import optim
from torch.nn import functional as F
from torch.utils.data import TensorDataset, DataLoader
from torch import optim
import numpy as np
from learner import Learner
from copy import deepcopy
import errors
def get_lr(optimizer):
for param_group in optimizer.param_groups:
return param_group['lr']
class Meta(nn.Module):
"""
Meta Learner
"""
def __init__(self, args, config):
"""
:param args:
"""
super(Meta, self).__init__()
self.update_lr = args.update_lr
self.meta_lr = args.meta_lr
# self.k_spt = args.k_spt # support: not used: when used k_spt + k_qry
# self.k_qry = args.k_qry # should be 50 if task_num is 5 (250 training
self.task_num = args.task_num # images)
self.update_step = args.update_step # task level update step.
self.update_step_test = args.update_step_test
# inner loop: the network, takes network structure and input size
self.net = Learner(config)
self.meta_optim = optim.Adam(self.net.parameters(), lr=self.meta_lr)
self.scheduler = optim.lr_scheduler.MultiStepLR(self.meta_optim,
milestones=[2000, 4000],
gamma=0.5)
self.log = []
print('init in Meta class running!')
# I dont think this function has been used here!
def clip_grad_by_norm_(self, grad, max_norm):
"""
in-place gradient clipping.
:param grad: list of gradients
:param max_norm: maximum norm allowable
:return:
"""
total_norm = 0
counter = 0
for g in grad:
param_norm = g.data.norm(2)
total_norm += param_norm.item() ** 2
counter += 1
total_norm = total_norm ** (1. / 2)
clip_coef = max_norm / (total_norm + 1e-6)
if clip_coef < 1:
for g in grad:
g.data.mul_(clip_coef)
return total_norm/counter
def forward(self, spt_ms, spt_rgb, qry_ms, qry_rgb, epoch):
"""
:b: number of tasks/batches.
:setsz: number of training pairs?
:querysz number of test pairs for few shot
:param spt_ms: [task_num, setsz, 16, h, w]
:param spt_rgb: [task_num, querysz, 3, h, w]
:param qry_ms: [task_num, setsz, 16, h, w]
:param qry_rgb: [task_num, querysz, 3, h, w]
:return:
"""
spt_ms = spt_ms.squeeze()
spt_rgb = spt_rgb.squeeze()
qry_ms = qry_ms.squeeze()
qry_rgb = qry_rgb.squeeze()
task_num, setsz, c, h, w = spt_ms.size()
_, querysz, c, _, _ = qry_ms.size()
# losses_q[k] is the loss on step k of gradient descent (inner loop)
losses_q = [0 for _ in range(self.update_step + 1)]
# accuracy on step i of gradient descent (inner loop)
corrects = [0 for _ in range(self.update_step + 1)]
if (epoch < 4001):
if (epoch%2000==0) and (epoch > 1):
decay = 2 #(epoch // 5) + 1
self.update_lr = self.update_lr / decay
print('outer loop lr is: ', self.update_lr)
for i in range(task_num):
# 1. run the i-th task and compute loss for k=0, k is update step
logits = self.net(spt_ms[i], vars=None, bn_training=True)
loss = F.smooth_l1_loss(logits, spt_rgb[i])
# create a log with task_num x k
#print(loss.item())
# the sum of graidents of outputs w.r.t the input
grad = torch.autograd.grad(loss, self.net.parameters())
fast_weights = list(map(
lambda p: p[1] - self.update_lr * p[0],
zip(grad, self.net.parameters())
))
# what are these two torch.no_grad()s about?????????????????????
# the first one calculates accuracy right after initialization
# which makes sense, the second one is doing an update...why?????
# this is the loss and accuracy before first update
with torch.no_grad():
# [setsz, nway]
logits_q = self.net(qry_ms[i], self.net.parameters(),
bn_training=True)
loss_q = F.smooth_l1_loss(logits_q, qry_rgb[i])
losses_q[0] += loss_q # adding loss?!
pred_q = logits_q # logits_q used to be cross_entropy loss, and
# go through softmax to become pred_q.
# calculate PSNR
correct = errors.find_psnr(pred_q, qry_rgb[i])
corrects[0] = corrects[0] + correct
# this is the loss and accuracy after the first update
with torch.no_grad():
# [setsz, nway]
logits_q = self.net(qry_ms[i], fast_weights, bn_training=True)
loss_q = F.smooth_l1_loss(logits_q, qry_rgb[i])
losses_q[1] += loss_q
# [setsz]
pred_q = logits_q
correct = errors.find_psnr(pred_q, qry_rgb[i])
corrects[1] = corrects[1] + correct
for k in range(1, self.update_step):
# 1. run the i-th task and compute loss for k=1~K-1
logits = self.net(spt_ms[i], fast_weights, bn_training=True)
loss = F.smooth_l1_loss(logits, spt_rgb[i])
# 2. compute grad on theta_pi
grad = torch.autograd.grad(loss, fast_weights)
# 3. theta_pi = theta_pi - train_lr * grad
fast_weights = list(map(lambda p: p[1] - self.update_lr * p[0],
zip(grad, fast_weights)))
logits_q = self.net(qry_ms[i], fast_weights, bn_training=True)
self.valid_img = logits_q
# loss_q will be overwritten and we just keep the loss_q on
# last update step ==> losses_q[-1]
loss_q = F.smooth_l1_loss(logits_q, qry_rgb[i])
losses_q[k + 1] += loss_q
with torch.no_grad():
pred_q = logits_q
# convert to numpy
correct = errors.find_psnr(pred_q, qry_rgb[i])
corrects[k + 1] = corrects[k + 1] + correct
# end of all tasks
# sum over all losses on query set across all tasks
loss_q = losses_q[-1] / task_num
# self.log[-1] += loss.item()
# optimize theta parameters
# In the Learner the update is with respect to accuracy of the training
# set, but for meta_learner the meta_update is with respect to the test
# set of each episode.
self.meta_optim.zero_grad()
loss_q.backward() # backwards through grad above ==> d(loss_q)/d(grad)
# print('meta update')
# for p in self.net.parameters()[:5]:
# print(torch.norm(p).item())
self.meta_optim.step()
accs = np.average(np.array(corrects[-1])) #/ (querysz * task_num)
print('inner loop lr is: ', self.get_lr(self.meta_optim))
return accs, loss_q
def get_lr(self, optimizer):
for param_group in optimizer.param_groups:
return param_group['lr']
# finetunning is for training the network in a new task (fine tuning it)
def finetunning(self, spt_ms, spt_rgb, qry_ms, qry_rgb):
"""
:param spt_ms: [task_num, setsz, 16, h, w]
:param spt_rgb: [task_num, setsz, 16, h, w]
:param qry_ms: [task_num, setsz, 16, h, w]
:param qry_rgb: [task_num, setsz, 16, h, w]
:return:
"""
assert len(spt_ms.shape) == 4
querysz = qry_ms.size(0)
corrects = [0 for _ in range(self.update_step_test + 1)]
# in order to not ruin the state of running_mean/variance and bn_weight/bias
# we finetunning on the copied model instead of self.net
net = deepcopy(self.net)
# 1. run the i-th task and compute loss for k=0
logits = net(spt_ms)
loss = F.cross_entropy(logits, spt_rgb)
grad = torch.autograd.grad(loss, net.parameters())
fast_weights = list(map(lambda p: p[1] - self.update_lr * p[0],
zip(grad, net.parameters())))
# this is the loss and accuracy before first update
with torch.no_grad():
# [setsz, nway]
pred_q = net(qry_ms, net.parameters(), bn_training=True)
# [setsz]
# pred_q = F.softmax(logits_q, dim=1).argmax(dim=1)
# scalar
correct = torch.eq(pred_q, qry_rgb).sum().item()
corrects[0] = corrects[0] + correct
# this is the loss and accuracy after the first update
with torch.no_grad():
# [setsz, nway]
pred_q = net(qry_ms, fast_weights, bn_training=True)
# [setsz]
# pred_q = F.softmax(logits_q, dim=1).argmax(dim=1)
# scalar
correct = torch.eq(pred_q, qry_rgb).sum().item()
corrects[1] = corrects[1] + correct
for k in range(1, self.update_step_test):
# 1. run the i-th task and compute loss for k=1~K-1
logits = net(spt_ms, fast_weights, bn_training=True)
loss = F.cross_entropy(logits, spt_rgb)
# 2. compute grad on theta_pi
grad = torch.autograd.grad(loss, fast_weights)
# 3. theta_pi = theta_pi - train_lr * grad
fast_weights = list(map(lambda p: p[1] - self.update_lr * p[0],
zip(grad, fast_weights)))
pred_q = net(qry_ms, fast_weights, bn_training=True)
# loss_q will be overwritten and just keep the loss_q on last update step.
loss_q = F.smooth_l1_loss(pred_q, qry_rgb)
with torch.no_grad():
# pred_q = F.softmax(logits_q, dim=1).argmax(dim=1)
correct = torch.eq(pred_q, qry_rgb).sum().item() # convert to numpy
corrects[k + 1] = corrects[k + 1] + correct
del net
accs = np.array(corrects) / querysz
return accs
def main():
pass
if __name__ == '__main__':
main()
|
[
"torch.eq",
"copy.deepcopy",
"learner.Learner",
"errors.find_psnr",
"torch.autograd.grad",
"torch.nn.functional.cross_entropy",
"numpy.array",
"torch.no_grad",
"torch.nn.functional.smooth_l1_loss",
"torch.optim.lr_scheduler.MultiStepLR"
] |
[((1074, 1089), 'learner.Learner', 'Learner', (['config'], {}), '(config)\n', (1081, 1089), False, 'from learner import Learner\n'), ((1192, 1279), 'torch.optim.lr_scheduler.MultiStepLR', 'optim.lr_scheduler.MultiStepLR', (['self.meta_optim'], {'milestones': '[2000, 4000]', 'gamma': '(0.5)'}), '(self.meta_optim, milestones=[2000, 4000],\n gamma=0.5)\n', (1222, 1279), False, 'from torch import optim\n'), ((8100, 8118), 'copy.deepcopy', 'deepcopy', (['self.net'], {}), '(self.net)\n', (8108, 8118), False, 'from copy import deepcopy\n'), ((8220, 8252), 'torch.nn.functional.cross_entropy', 'F.cross_entropy', (['logits', 'spt_rgb'], {}), '(logits, spt_rgb)\n', (8235, 8252), True, 'from torch.nn import functional as F\n'), ((3472, 3508), 'torch.nn.functional.smooth_l1_loss', 'F.smooth_l1_loss', (['logits', 'spt_rgb[i]'], {}), '(logits, spt_rgb[i])\n', (3488, 3508), True, 'from torch.nn import functional as F\n'), ((7113, 7135), 'numpy.array', 'np.array', (['corrects[-1]'], {}), '(corrects[-1])\n', (7121, 7135), True, 'import numpy as np\n'), ((8500, 8515), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (8513, 8515), False, 'import torch\n'), ((8907, 8922), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (8920, 8922), False, 'import torch\n'), ((9432, 9464), 'torch.nn.functional.cross_entropy', 'F.cross_entropy', (['logits', 'spt_rgb'], {}), '(logits, spt_rgb)\n', (9447, 9464), True, 'from torch.nn import functional as F\n'), ((9526, 9565), 'torch.autograd.grad', 'torch.autograd.grad', (['loss', 'fast_weights'], {}), '(loss, fast_weights)\n', (9545, 9565), False, 'import torch\n'), ((9913, 9946), 'torch.nn.functional.smooth_l1_loss', 'F.smooth_l1_loss', (['pred_q', 'qry_rgb'], {}), '(pred_q, qry_rgb)\n', (9929, 9946), True, 'from torch.nn import functional as F\n'), ((10237, 10255), 'numpy.array', 'np.array', (['corrects'], {}), '(corrects)\n', (10245, 10255), True, 'import numpy as np\n'), ((4224, 4239), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (4237, 4239), False, 'import torch\n'), ((4410, 4448), 'torch.nn.functional.smooth_l1_loss', 'F.smooth_l1_loss', (['logits_q', 'qry_rgb[i]'], {}), '(logits_q, qry_rgb[i])\n', (4426, 4448), True, 'from torch.nn import functional as F\n'), ((4698, 4734), 'errors.find_psnr', 'errors.find_psnr', (['pred_q', 'qry_rgb[i]'], {}), '(pred_q, qry_rgb[i])\n', (4714, 4734), False, 'import errors\n'), ((4872, 4887), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (4885, 4887), False, 'import torch\n'), ((5025, 5063), 'torch.nn.functional.smooth_l1_loss', 'F.smooth_l1_loss', (['logits_q', 'qry_rgb[i]'], {}), '(logits_q, qry_rgb[i])\n', (5041, 5063), True, 'from torch.nn import functional as F\n'), ((5188, 5224), 'errors.find_psnr', 'errors.find_psnr', (['pred_q', 'qry_rgb[i]'], {}), '(pred_q, qry_rgb[i])\n', (5204, 5224), False, 'import errors\n'), ((5495, 5531), 'torch.nn.functional.smooth_l1_loss', 'F.smooth_l1_loss', (['logits', 'spt_rgb[i]'], {}), '(logits, spt_rgb[i])\n', (5511, 5531), True, 'from torch.nn import functional as F\n'), ((5601, 5640), 'torch.autograd.grad', 'torch.autograd.grad', (['loss', 'fast_weights'], {}), '(loss, fast_weights)\n', (5620, 5640), False, 'import torch\n'), ((6101, 6139), 'torch.nn.functional.smooth_l1_loss', 'F.smooth_l1_loss', (['logits_q', 'qry_rgb[i]'], {}), '(logits_q, qry_rgb[i])\n', (6117, 6139), True, 'from torch.nn import functional as F\n'), ((9965, 9980), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (9978, 9980), False, 'import torch\n'), ((6204, 6219), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (6217, 6219), False, 'import torch\n'), ((6328, 6364), 'errors.find_psnr', 'errors.find_psnr', (['pred_q', 'qry_rgb[i]'], {}), '(pred_q, qry_rgb[i])\n', (6344, 6364), False, 'import errors\n'), ((8743, 8768), 'torch.eq', 'torch.eq', (['pred_q', 'qry_rgb'], {}), '(pred_q, qry_rgb)\n', (8751, 8768), False, 'import torch\n'), ((9146, 9171), 'torch.eq', 'torch.eq', (['pred_q', 'qry_rgb'], {}), '(pred_q, qry_rgb)\n', (9154, 9171), False, 'import torch\n'), ((10076, 10101), 'torch.eq', 'torch.eq', (['pred_q', 'qry_rgb'], {}), '(pred_q, qry_rgb)\n', (10084, 10101), False, 'import torch\n')]
|
import os
import numpy as np
print("-------------------------------------------------")
print("|\t\tPyCylon Test Framework\t\t|")
print("-------------------------------------------------")
responses = []
def test_pycylon_installation_test():
print("1. PyCylon Installation Test")
responses.append(os.system("pytest -q python/test/test_pycylon.py"))
assert responses[-1] == 0
def test_pyarrow_installation_test():
print("2. PyArrow Installation Test")
responses.append(os.system("pytest -q python/test/test_build_arrow.py"))
assert responses[-1] == 0
# def test_fake():
# # NOTE: To Test the Test Framework
# print("Fake Test")
# responses.append(os.system("pytest -q python/test/test_fake.py"))
# assert responses[-1] == 0
def test_cylon_context():
print("3. CylonContext Test")
responses.append(
os.system("mpirun --oversubscribe -n 2 python -m pytest --with-mpi -q python/test/test_cylon_context.py"))
assert responses[-1] == 0
def test_channel():
print("4. Channel Test")
responses.append(os.system("pytest -q python/test/test_channel.py"))
assert responses[-1] == 0
def test_commtype():
print("5. CommType Test")
responses.append(os.system("pytest -q python/test/test_comm_type.py"))
assert responses[-1] == 0
def test_csv_read_options():
print("6. CSV Read Options Test")
responses.append(os.system("pytest -q python/test/test_csv_read_options.py"))
assert responses[-1] == 0
def test_datatype():
print("7. Data Types Test")
responses.append(os.system("pytest -q python/test/test_data_types.py"))
assert responses[-1] == 0
def test_data_utils():
print("8. Data Utils Test")
responses.append(os.system("pytest -q python/test/test_data_utils.py"))
assert responses[-1] == 0
def test_status():
print("9. Cylon Status Test")
responses.append(os.system("pytest -q python/test/test_status.py"))
assert responses[-1] == 0
def test_request():
print("10. Request Test")
responses.append(os.system("pytest -q python/test/test_txrequest.py"))
assert responses[-1] == 0
def test_pycylon_pyarrow():
print("11. PyArrow/PyCylon Test")
responses.append(os.system("pytest -q python/test/test_pyarrow.py"))
def test_table_conversion():
print("12. Table Conversion Test")
responses.append(os.system(
"mpirun --oversubscribe -n 2 python -m pytest --with-mpi -q python/test/test_cylon_table_conversion.py"))
assert responses[-1] == 0
def test_table_operation():
print("13. Table Operation Test")
responses.append(os.system("pytest -q python/test/test_table.py"))
def test_table_properties():
print("14. Table Properties Test")
responses.append(os.system("pytest -q python/test/test_table_properties.py"))
assert responses[-1] == 0
def test_aggregate():
print("15. Aggregate Test")
responses.append(os.system("pytest -q python/test/test_aggregate.py"))
def test_join_config():
print("16. Join Config Test")
responses.append(os.system("pytest -q python/test/test_join_config.py"))
assert responses[-1] == 0
def test_simple_table_join():
print("17. Simple Table Join Test")
responses.append(os.system(
"mpirun --oversubscribe -n 4 python -m pytest --with-mpi -q python/test/test_cylon_simple_table_join.py"))
assert responses[-1] == 0
def test_dist_rl():
print("18. Distributed Relational Algebra Operator Test")
responses.append(
os.system(
"mpirun --oversubscribe -n 4 python -m pytest --with-mpi -q python/test/test_dist_rl.py"))
assert responses[-1] == 0
def test_rl():
print("19. Sequential Relational Algebra Operator Test")
responses.append(os.system("pytest -q python/test/test_rl.py"))
assert responses[-1] == 0
def test_rl_col():
print("20. Sequential Relational Algebra with Column Names Test")
responses.append(os.system("pytest -q python/test/test_ra_by_column_names.py"))
assert responses[-1] == 0
def test_dist_rl_col():
print("21. Distributed Relational Algebra with Column Names Test")
responses.append(
os.system("mpirun --oversubscribe -n 4 python -m pytest --with-mpi -q "
"python/test/test_dist_ra_by_column_names.py"))
assert responses[-1] == 0
def test_all():
ar = np.array(responses)
total = len(responses)
failed_count = sum(ar > 0)
if failed_count > 0:
print(f"{failed_count} of {total} Tests Failed !!!")
else:
print("All Tests Passed!")
|
[
"numpy.array",
"os.system"
] |
[((4346, 4365), 'numpy.array', 'np.array', (['responses'], {}), '(responses)\n', (4354, 4365), True, 'import numpy as np\n'), ((309, 359), 'os.system', 'os.system', (['"""pytest -q python/test/test_pycylon.py"""'], {}), "('pytest -q python/test/test_pycylon.py')\n", (318, 359), False, 'import os\n'), ((494, 548), 'os.system', 'os.system', (['"""pytest -q python/test/test_build_arrow.py"""'], {}), "('pytest -q python/test/test_build_arrow.py')\n", (503, 548), False, 'import os\n'), ((862, 977), 'os.system', 'os.system', (['"""mpirun --oversubscribe -n 2 python -m pytest --with-mpi -q python/test/test_cylon_context.py"""'], {}), "(\n 'mpirun --oversubscribe -n 2 python -m pytest --with-mpi -q python/test/test_cylon_context.py'\n )\n", (871, 977), False, 'import os\n'), ((1071, 1121), 'os.system', 'os.system', (['"""pytest -q python/test/test_channel.py"""'], {}), "('pytest -q python/test/test_channel.py')\n", (1080, 1121), False, 'import os\n'), ((1227, 1279), 'os.system', 'os.system', (['"""pytest -q python/test/test_comm_type.py"""'], {}), "('pytest -q python/test/test_comm_type.py')\n", (1236, 1279), False, 'import os\n'), ((1401, 1460), 'os.system', 'os.system', (['"""pytest -q python/test/test_csv_read_options.py"""'], {}), "('pytest -q python/test/test_csv_read_options.py')\n", (1410, 1460), False, 'import os\n'), ((1568, 1621), 'os.system', 'os.system', (['"""pytest -q python/test/test_data_types.py"""'], {}), "('pytest -q python/test/test_data_types.py')\n", (1577, 1621), False, 'import os\n'), ((1731, 1784), 'os.system', 'os.system', (['"""pytest -q python/test/test_data_utils.py"""'], {}), "('pytest -q python/test/test_data_utils.py')\n", (1740, 1784), False, 'import os\n'), ((1892, 1941), 'os.system', 'os.system', (['"""pytest -q python/test/test_status.py"""'], {}), "('pytest -q python/test/test_status.py')\n", (1901, 1941), False, 'import os\n'), ((2046, 2098), 'os.system', 'os.system', (['"""pytest -q python/test/test_txrequest.py"""'], {}), "('pytest -q python/test/test_txrequest.py')\n", (2055, 2098), False, 'import os\n'), ((2219, 2269), 'os.system', 'os.system', (['"""pytest -q python/test/test_pyarrow.py"""'], {}), "('pytest -q python/test/test_pyarrow.py')\n", (2228, 2269), False, 'import os\n'), ((2362, 2486), 'os.system', 'os.system', (['"""mpirun --oversubscribe -n 2 python -m pytest --with-mpi -q python/test/test_cylon_table_conversion.py"""'], {}), "(\n 'mpirun --oversubscribe -n 2 python -m pytest --with-mpi -q python/test/test_cylon_table_conversion.py'\n )\n", (2371, 2486), False, 'import os\n'), ((2606, 2654), 'os.system', 'os.system', (['"""pytest -q python/test/test_table.py"""'], {}), "('pytest -q python/test/test_table.py')\n", (2615, 2654), False, 'import os\n'), ((2747, 2806), 'os.system', 'os.system', (['"""pytest -q python/test/test_table_properties.py"""'], {}), "('pytest -q python/test/test_table_properties.py')\n", (2756, 2806), False, 'import os\n'), ((2915, 2967), 'os.system', 'os.system', (['"""pytest -q python/test/test_aggregate.py"""'], {}), "('pytest -q python/test/test_aggregate.py')\n", (2924, 2967), False, 'import os\n'), ((3050, 3104), 'os.system', 'os.system', (['"""pytest -q python/test/test_join_config.py"""'], {}), "('pytest -q python/test/test_join_config.py')\n", (3059, 3104), False, 'import os\n'), ((3229, 3354), 'os.system', 'os.system', (['"""mpirun --oversubscribe -n 4 python -m pytest --with-mpi -q python/test/test_cylon_simple_table_join.py"""'], {}), "(\n 'mpirun --oversubscribe -n 4 python -m pytest --with-mpi -q python/test/test_cylon_simple_table_join.py'\n )\n", (3238, 3354), False, 'import os\n'), ((3499, 3608), 'os.system', 'os.system', (['"""mpirun --oversubscribe -n 4 python -m pytest --with-mpi -q python/test/test_dist_rl.py"""'], {}), "(\n 'mpirun --oversubscribe -n 4 python -m pytest --with-mpi -q python/test/test_dist_rl.py'\n )\n", (3508, 3608), False, 'import os\n'), ((3742, 3787), 'os.system', 'os.system', (['"""pytest -q python/test/test_rl.py"""'], {}), "('pytest -q python/test/test_rl.py')\n", (3751, 3787), False, 'import os\n'), ((3931, 3992), 'os.system', 'os.system', (['"""pytest -q python/test/test_ra_by_column_names.py"""'], {}), "('pytest -q python/test/test_ra_by_column_names.py')\n", (3940, 3992), False, 'import os\n'), ((4151, 4276), 'os.system', 'os.system', (['"""mpirun --oversubscribe -n 4 python -m pytest --with-mpi -q python/test/test_dist_ra_by_column_names.py"""'], {}), "(\n 'mpirun --oversubscribe -n 4 python -m pytest --with-mpi -q python/test/test_dist_ra_by_column_names.py'\n )\n", (4160, 4276), False, 'import os\n')]
|
import tensorflow as tf
from numpy.random import seed
from tensorflow.keras import activations
from tensorflow.keras.layers import Dense
import tensorflow.keras.backend as K
from tensorflow import set_random_seed
seed(2020)
set_random_seed(2020)
class SPARSE_MPNN(tf.keras.layers.Layer):
r"""Message passing cell.
Args:
state_dim (int): number of output channels.
T (int): number of message passing repetition.
attn_heads (int): number of attention heads.
attn_method (str): type of attention methods.
aggr_method (str): type of aggregation methods.
activation (str): type of activation functions.
update_method (str): type of update functions.
"""
def __init__(self,
state_dim,
T,
aggr_method,
attn_method,
update_method,
attn_head,
activation):
super(SPARSE_MPNN, self).__init__(self)
self.state_dim = state_dim
self.T = T
self.activation = activations.get(activation)
self.aggr_method = aggr_method
self.attn_method = attn_method
self.attn_head = attn_head
self.update_method = update_method
def build(self, input_shape):
self.embed = tf.keras.layers.Dense(self.state_dim, activation=self.activation)
self.MP = MP_layer(self.state_dim, self.aggr_method, self.activation,
self.attn_method, self.attn_head, self.update_method)
self.built = True
def call(self, inputs, **kwargs):
"""
Args:
inputs (list):
X (tensor): node feature tensor
A (tensor): edge pair tensor
E (tensor): edge feature tensor
mask (tensor): node mask tensor to mask out non-existent nodes
degree (tensor): node degree tensor for GCN attention
Returns:
X (tensor): results after several repetitions of edge network, attention, aggregation and update function
"""
X, A, E, mask, degree = inputs
A = tf.cast(A, tf.int32)
X = self.embed(X)
for _ in range(self.T):
X = self.MP([X, A, E, mask, degree])
return X
class MP_layer(tf.keras.layers.Layer):
r"""Message passing layer.
Args:
state_dim (int): number of output channels.
attn_heads (int): number of attention heads.
attn_method (str): type of attention methods.
aggr_method (str): type of aggregation methods.
activation (str): type of activation functions.
update_method (str): type of update functions.
"""
def __init__(self, state_dim, aggr_method, activation, attn_method, attn_head, update_method):
super(MP_layer, self).__init__(self)
self.state_dim = state_dim
self.aggr_method = aggr_method
self.activation = activation
self.attn_method = attn_method
self.attn_head = attn_head
self.update_method = update_method
def build(self, input_shape):
self.message_passer = Message_Passer_NNM(self.state_dim, self.attn_head, self.attn_method,
self.aggr_method, self.activation)
if self.update_method == 'gru':
self.update_functions = Update_Func_GRU(self.state_dim)
elif self.update_method == 'mlp':
self.update_functions = Update_Func_MLP(self.state_dim, self.activation)
self.built = True
def call(self, inputs, **kwargs):
"""
Args:
inputs (list):
X (tensor): node feature tensor
A (tensor): edge pair tensor
E (tensor): edge feature tensor
mask (tensor): node mask tensor to mask out non-existent nodes
degree (tensor): node degree tensor for GCN attention
Returns:
updated_nodes (tensor): results after edge network, attention, aggregation and update function
"""
X, A, E, mask, degree = inputs
agg_m = self.message_passer([X, A, E, degree])
mask = tf.tile(mask[..., None], [1, 1, self.state_dim])
agg_m = tf.multiply(agg_m, mask)
updated_nodes = self.update_functions([X, agg_m])
updated_nodes = tf.multiply(updated_nodes, mask)
return updated_nodes
class Message_Passer_NNM(tf.keras.layers.Layer):
r"""Message passing kernel.
Args:
state_dim (int): number of output channels.
attn_heads (int): number of attention heads.
attn_method (str): type of attention methods.
aggr_method (str): type of aggregation methods.
activation (str): type of activation functions.
"""
def __init__(self, state_dim, attn_heads, attn_method, aggr_method, activation):
super(Message_Passer_NNM, self).__init__()
self.state_dim = state_dim
self.attn_heads = attn_heads
self.attn_method = attn_method
self.aggr_method = aggr_method
self.activation = activation
def build(self, input_shape):
self.nn = tf.keras.layers.Dense(units=self.state_dim * self.state_dim * self.attn_heads,
activation=self.activation)
if self.attn_method == 'gat':
self.attn_func = Attention_GAT(self.state_dim, self.attn_heads)
elif self.attn_method == 'sym-gat':
self.attn_func = Attention_SYM_GAT(self.state_dim, self.attn_heads)
elif self.attn_method == 'cos':
self.attn_func = Attention_COS(self.state_dim, self.attn_heads)
elif self.attn_method == 'linear':
self.attn_func = Attention_Linear(self.state_dim, self.attn_heads)
elif self.attn_method == 'gen-linear':
self.attn_func = Attention_Gen_Linear(self.state_dim, self.attn_heads)
elif self.attn_method == 'const':
self.attn_func = Attention_Const(self.state_dim, self.attn_heads)
elif self.attn_method == 'gcn':
self.attn_func = Attention_GCN(self.state_dim, self.attn_heads)
self.bias = self.add_weight(name='attn_bias', shape=[self.state_dim], initializer='zeros')
self.built = True
def call(self, inputs, **kwargs):
"""
Args:
inputs (list):
X (tensor): node feature tensor
A (tensor): edge pair tensor
E (tensor): edge feature tensor
degree (tensor): node degree tensor for GCN attention
Returns:
output (tensor): results after edge network, attention and aggregation
"""
# Edge network to transform edge information to message weight
X, A, E, degree = inputs
N = K.int_shape(X)[1]
targets, sources = A[..., -2], A[..., -1]
W = self.nn(E)
W = tf.reshape(W, [-1, tf.shape(E)[1], self.attn_heads, self.state_dim, self.state_dim])
X = tf.tile(X[..., None], [1, 1, 1, self.attn_heads])
X = tf.transpose(X, [0, 1, 3, 2])
# Attention added to the message weight
attn_coef = self.attn_func([X, N, targets, sources, degree])
messages = tf.gather(X, sources, batch_dims=1)
messages = messages[..., None]
messages = tf.matmul(W, messages)
messages = messages[..., 0]
output = attn_coef * messages
num_rows = tf.shape(targets)[0]
rows_idx = tf.range(num_rows)
segment_ids_per_row = targets + N * tf.expand_dims(rows_idx, axis=1)
# Aggregation to summarize neighboring node messages
if self.aggr_method == 'max':
output = tf.math.unsorted_segment_max(output, segment_ids_per_row, N * num_rows)
elif self.aggr_method == 'mean':
output = tf.math.unsorted_segment_mean(output, segment_ids_per_row, N * num_rows)
elif self.aggr_method == 'sum':
output = tf.math.unsorted_segment_sum(output, segment_ids_per_row, N * num_rows)
# Output the mean of all attention heads
output = tf.reshape(output, [-1, N, self.attn_heads, self.state_dim])
output = tf.reduce_mean(output, axis=-2)
output = K.bias_add(output, self.bias)
return output
class Update_Func_GRU(tf.keras.layers.Layer):
r"""Gated recurrent unit update function. Check details here https://arxiv.org/abs/1412.3555
Args:
state_dim (int): number of output channels.
"""
def __init__(self, state_dim):
super(Update_Func_GRU, self).__init__()
self.state_dim = state_dim
def build(self, input_shape):
self.concat_layer = tf.keras.layers.Concatenate(axis=1)
self.GRU = tf.keras.layers.GRU(self.state_dim)
self.built = True
def call(self, inputs, **kwargs):
"""
Args:
inputs (list):
old_state (tensor): node hidden feature tensor
agg_messages (tensor): node hidden feature tensor
Returns:
activation (tensor): activated tensor from update function
"""
# Remember node dim
old_state, agg_messages = inputs
B, N, F = K.int_shape(old_state)
B1, N1, F1 = K.int_shape(agg_messages)
# Reshape so GRU can be applied, concat so old_state and messages are in sequence
old_state = tf.reshape(old_state, [-1, 1, F])
agg_messages = tf.reshape(agg_messages, [-1, 1, F1])
concat = self.concat_layer([old_state, agg_messages])
# Apply GRU and then reshape so it can be returned
activation = self.GRU(concat)
activation = tf.reshape(activation, [-1, N, F])
return activation
class Update_Func_MLP(tf.keras.layers.Layer):
r"""Multi-layer perceptron update function.
Args:
state_dim (int): number of output channels.
activation (str): the type of activation functions.
"""
def __init__(self, state_dim, activation):
super(Update_Func_MLP, self).__init__()
self.state_dim = state_dim
self.activation = activation
def build(self, input_shape):
self.concat_layer = tf.keras.layers.Concatenate(axis=-1)
self.dense = tf.keras.layers.Dense(self.state_dim, activation=self.activation, kernel_initializer='zeros')
def call(self, inputs, **kwargs):
"""
Args:
inputs (list):
old_state (tensor): node hidden feature tensor
agg_messages (tensor): node hidden feature tensor
Returns:
activation (tensor): activated tensor from update function (
"""
old_state, agg_messages = inputs
concat = self.concat_layer([old_state, agg_messages])
activation = self.dense(concat)
return activation
class Attention_GAT(tf.keras.layers.Layer):
r"""GAT Attention. Check details here https://arxiv.org/abs/1710.10903
The attention coefficient between node $i$ and $j$ is calculated as:
$$
\text{LeakyReLU}(\textbf{a}(\textbf{Wh}_i||\textbf{Wh}_j))
$$
where \(\textbf{a}\) is a trainable vector, and \(||\) represents concatenation.
Args:
state_dim (int): number of output channels.
attn_heads (int): number of attention heads.
"""
def __init__(self, state_dim, attn_heads):
super(Attention_GAT, self).__init__()
self.state_dim = state_dim
self.attn_heads = attn_heads
def build(self, input_shape):
self.attn_kernel_self = self.add_weight(name='attn_kernel_self', shape=[self.state_dim, self.attn_heads, 1],
initializer='glorot_uniform')
self.attn_kernel_adjc = self.add_weight(name='attn_kernel_adjc', shape=[self.state_dim, self.attn_heads, 1],
initializer='glorot_uniform')
self.built = True
def call(self, inputs, **kwargs):
"""
Args:
inputs (list):
X (tensor): node feature tensor
N (int): number of nodes
targets (tensor): target node index tensor
sources (tensor): source node index tensor
degree (tensor): node degree sqrt tensor (for GCN attention)
Returns:
attn_coef (tensor): attention coefficient tensor
"""
X, N, targets, sources, _ = inputs
attn_kernel_self = tf.transpose(self.attn_kernel_self, (2, 1, 0))
attn_kernel_adjc = tf.transpose(self.attn_kernel_adjc, (2, 1, 0))
attn_for_self = tf.reduce_sum(X * attn_kernel_self[None, ...], -1)
attn_for_self = tf.gather(attn_for_self, targets, batch_dims=1)
attn_for_adjc = tf.reduce_sum(X * attn_kernel_adjc[None, ...], -1)
attn_for_adjc = tf.gather(attn_for_adjc, sources, batch_dims=1)
attn_coef = attn_for_self + attn_for_adjc
attn_coef = tf.nn.leaky_relu(attn_coef, alpha=0.2)
attn_coef = tf.exp(attn_coef - tf.gather(tf.math.unsorted_segment_max(attn_coef, targets, N), targets))
attn_coef /= tf.gather(tf.math.unsorted_segment_max(attn_coef, targets, N) + 1e-9, targets)
attn_coef = tf.nn.dropout(attn_coef, 0.5)
attn_coef = attn_coef[..., None]
return attn_coef
class Attention_SYM_GAT(tf.keras.layers.Layer):
r"""GAT Symmetry Attention.
The attention coefficient between node $i$ and $j$ is calculated as:
$$
\alpha_{ij} + \alpha_{ij}
$$
based on GAT.
Args:
state_dim (int): number of output channels.
attn_heads (int): number of attention heads.
"""
def __init__(self, state_dim, attn_heads):
super(Attention_SYM_GAT, self).__init__()
self.state_dim = state_dim
self.attn_heads = attn_heads
def build(self, input_shape):
self.attn_kernel_self = self.add_weight(name='attn_kernel_self', shape=[self.state_dim, self.attn_heads, 1],
initializer='glorot_uniform')
self.attn_kernel_adjc = self.add_weight(name='attn_kernel_adjc', shape=[self.state_dim, self.attn_heads, 1],
initializer='glorot_uniform')
self.built = True
def call(self, inputs, **kwargs):
"""
Args:
inputs (list):
X (tensor): node feature tensor
N (int): number of nodes
targets (tensor): target node index tensor
sources (tensor): source node index tensor
degree (tensor): node degree sqrt tensor (for GCN attention)
Returns:
attn_coef (tensor): attention coefficient tensor
"""
X, N, targets, sources, _ = inputs
attn_kernel_self = tf.transpose(self.attn_kernel_self, (2, 1, 0))
attn_kernel_adjc = tf.transpose(self.attn_kernel_adjc, (2, 1, 0))
attn_for_self = tf.reduce_sum(X * attn_kernel_self[None, ...], -1)
attn_for_self = tf.gather(attn_for_self, targets, batch_dims=1)
attn_for_adjc = tf.reduce_sum(X * attn_kernel_adjc[None, ...], -1)
attn_for_adjc = tf.gather(attn_for_adjc, sources, batch_dims=1)
attn_for_self_reverse = tf.gather(attn_for_self, sources, batch_dims=1)
attn_for_adjc_reverse = tf.gather(attn_for_self, targets, batch_dims=1)
attn_coef = attn_for_self + attn_for_adjc + attn_for_self_reverse + attn_for_adjc_reverse
attn_coef = tf.nn.leaky_relu(attn_coef, alpha=0.2)
attn_coef = tf.exp(attn_coef - tf.gather(tf.math.unsorted_segment_max(attn_coef, targets, N), targets))
attn_coef /= tf.gather(tf.math.unsorted_segment_max(attn_coef, targets, N) + 1e-9, targets)
attn_coef = tf.nn.dropout(attn_coef, 0.5)
attn_coef = attn_coef[..., None]
return attn_coef
class Attention_COS(tf.keras.layers.Layer):
r"""COS Attention. Check details here https://arxiv.org/abs/1803.07294
The attention coefficient between node $i$ and $j$ is calculated as:
$$
\textbf{a}(\textbf{Wh}_i || \textbf{Wh}_j)
$$
where \(\textbf{a}\) is a trainable vector.
Args:
state_dim (int): number of output channels.
attn_heads (int): number of attention heads.
"""
def __init__(self, state_dim, attn_heads):
super(Attention_COS, self).__init__()
self.state_dim = state_dim
self.attn_heads = attn_heads
def build(self, input_shape):
self.attn_kernel_self = self.add_weight(name='attn_kernel_self', shape=[self.state_dim, self.attn_heads, 1],
initializer='glorot_uniform')
self.attn_kernel_adjc = self.add_weight(name='attn_kernel_adjc', shape=[self.state_dim, self.attn_heads, 1],
initializer='glorot_uniform')
self.built = True
def call(self, inputs, **kwargs):
"""
Args:
inputs (list):
X (tensor): node feature tensor
N (int): number of nodes
targets (tensor): target node index tensor
sources (tensor): source node index tensor
degree (tensor): node degree sqrt tensor (for GCN attention)
Returns:
attn_coef (tensor): attention coefficient tensor (batch, E, H, 1)
"""
X, N, targets, sources, _ = inputs
attn_kernel_self = tf.transpose(self.attn_kernel_self, (2, 1, 0))
attn_kernel_adjc = tf.transpose(self.attn_kernel_adjc, (2, 1, 0))
attn_for_self = tf.reduce_sum(X * attn_kernel_self[None, ...], -1)
attn_for_self = tf.gather(attn_for_self, targets, batch_dims=1)
attn_for_adjc = tf.reduce_sum(X * attn_kernel_adjc[None, ...], -1)
attn_for_adjc = tf.gather(attn_for_adjc, sources, batch_dims=1)
attn_coef = tf.multiply(attn_for_self, attn_for_adjc)
attn_coef = tf.nn.leaky_relu(attn_coef, alpha=0.2)
attn_coef = tf.exp(attn_coef - tf.gather(tf.math.unsorted_segment_max(attn_coef, targets, N), targets))
attn_coef /= tf.gather(tf.math.unsorted_segment_max(attn_coef, targets, N) + 1e-9, targets)
attn_coef = tf.nn.dropout(attn_coef, 0.5)
attn_coef = attn_coef[..., None]
return attn_coef
class Attention_Linear(tf.keras.layers.Layer):
r"""Linear Attention.
The attention coefficient between node $i$ and $j$ is calculated as:
$$
\text{tanh} (\textbf{a}_l\textbf{Wh}_i + \textbf{a}_r\textbf{Wh}_j)
$$
where \(\textbf{a}_l\) and \(\textbf{a}_r\) are trainable vectors.
Args:
state_dim (int): number of output channels.
attn_heads (int): number of attention heads.
"""
def __init__(self, state_dim, attn_heads):
super(Attention_Linear, self).__init__()
self.state_dim = state_dim
self.attn_heads = attn_heads
def build(self, input_shape):
self.attn_kernel_adjc = self.add_weight(name='attn_kernel_adjc', shape=[self.state_dim, self.attn_heads, 1],
initializer='glorot_uniform')
self.built = True
def call(self, inputs, **kwargs):
"""
Args:
inputs (list):
X (tensor): node feature tensor
N (int): number of nodes
targets (tensor): target node index tensor
sources (tensor): source node index tensor
degree (tensor): node degree sqrt tensor (for GCN attention)
Returns:
attn_coef (tensor): attention coefficient tensor
"""
X, N, targets, sources, _ = inputs
attn_kernel_adjc = tf.transpose(self.attn_kernel_adjc, (2, 1, 0))
attn_for_adjc = tf.reduce_sum(X * attn_kernel_adjc[None, ...], -1)
attn_for_adjc = tf.gather(attn_for_adjc, sources, batch_dims=1)
attn_coef = attn_for_adjc
attn_coef = tf.nn.tanh(attn_coef)
attn_coef = tf.exp(attn_coef - tf.gather(tf.math.unsorted_segment_max(attn_coef, targets, N), targets))
attn_coef /= tf.gather(tf.math.unsorted_segment_max(attn_coef, targets, N) + 1e-9, targets)
attn_coef = tf.nn.dropout(attn_coef, 0.5)
attn_coef = attn_coef[..., None]
return attn_coef
class Attention_Gen_Linear(tf.keras.layers.Layer):
r"""Generalized Linear Attention. Check details here https://arxiv.org/abs/1802.00910
The attention coefficient between node $i$ and $j$ is calculated as:
$$
\textbf{W}_G \text{tanh} (\textbf{Wh}_i + \textbf{Wh}_j)
$$
where \(\textbf{W}_G\) is a trainable matrix.
Args:
state_dim (int): number of output channels.
attn_heads (int): number of attention heads.
"""
def __init__(self, state_dim, attn_heads):
super(Attention_Gen_Linear, self).__init__()
self.state_dim = state_dim
self.attn_heads = attn_heads
def build(self, input_shape):
self.attn_kernel_self = self.add_weight(name='attn_kernel_self', shape=[self.state_dim, self.attn_heads, 1],
initializer='glorot_uniform')
self.attn_kernel_adjc = self.add_weight(name='attn_kernel_adjc', shape=[self.state_dim, self.attn_heads, 1],
initializer='glorot_uniform')
self.gen_nn = tf.keras.layers.Dense(units=self.attn_heads,
kernel_initializer='glorot_uniform', use_bias=False)
self.built = True
def call(self, inputs, **kwargs):
"""
Args:
inputs (list):
X (tensor): node feature tensor
N (int): number of nodes
targets (tensor): target node index tensor
sources (tensor): source node index tensor
degree (tensor): node degree sqrt tensor (for GCN attention)
Returns:
attn_coef (tensor): attention coefficient tensor
"""
X, N, targets, sources, _ = inputs
attn_kernel_self = tf.transpose(self.attn_kernel_self, (2, 1, 0))
attn_kernel_adjc = tf.transpose(self.attn_kernel_adjc, (2, 1, 0))
attn_for_self = tf.reduce_sum(X * attn_kernel_self[None, ...], -1)
attn_for_self = tf.gather(attn_for_self, targets, batch_dims=1)
attn_for_adjc = tf.reduce_sum(X * attn_kernel_adjc[None, ...], -1)
attn_for_adjc = tf.gather(attn_for_adjc, sources, batch_dims=1)
attn_coef = attn_for_self + attn_for_adjc
attn_coef = tf.nn.tanh(attn_coef)
attn_coef = self.gen_nn(attn_coef)
attn_coef = tf.exp(attn_coef - tf.gather(tf.math.unsorted_segment_max(attn_coef, targets, N), targets))
attn_coef /= tf.gather(tf.math.unsorted_segment_max(attn_coef, targets, N) + 1e-9, targets)
attn_coef = tf.nn.dropout(attn_coef, 0.5)
attn_coef = attn_coef[..., None]
return attn_coef
class Attention_GCN(tf.keras.layers.Layer):
r"""GCN Attention.
The attention coefficient between node $i$ and $j$ is calculated as:
$$
\frac{1}{\sqrt{|\mathcal{N}(i)||\mathcal{N}(j)|}}
$$
where \(\mathcal{N}(i)\) is the number of neighboring nodes of node \(i\).
Args:
state_dim (int): number of output channels.
attn_heads (int): number of attention heads.
"""
def __init__(self, state_dim, attn_heads):
super(Attention_GCN, self).__init__()
self.state_dim = state_dim
self.attn_heads = attn_heads
def call(self, inputs, **kwargs):
"""
Args:
inputs (list):
X (tensor): node feature tensor
N (int): number of nodes
targets (tensor): target node index tensor
sources (tensor): source node index tensor
degree (tensor): node degree sqrt tensor (for GCN attention)
Returns:
attn_coef (tensor): attention coefficient tensor
"""
_, _, _, _, degree = inputs
attn_coef = degree[..., None, None]
attn_coef = tf.tile(attn_coef, [1, 1, self.attn_heads, 1])
return attn_coef
class Attention_Const(tf.keras.layers.Layer):
r"""Constant Attention.
The attention coefficient between node $i$ and $j$ is calculated as:
$$
\alpha_{ij} = 1.
$$
Args:
state_dim (int): number of output channels.
attn_heads (int): number of attention heads.
"""
def __init__(self, state_dim, attn_heads):
super(Attention_Const, self).__init__()
self.state_dim = state_dim
self.attn_heads = attn_heads
def call(self, inputs, **kwargs):
"""
Args:
inputs (list):
X (tensor): node feature tensor
N (int): number of nodes
targets (tensor): target node index tensor
sources (tensor): source node index tensor
degree (tensor): node degree sqrt tensor (for GCN attention)
Returns:
attn_coef (tensor): attention coefficient tensor
"""
_, _, targets, _, degree = inputs
attn_coef = tf.ones((tf.shape(targets)[0], tf.shape(targets)[1], self.attn_heads, 1))
return attn_coef
class GlobalAttentionPool(tf.keras.layers.Layer):
r"""Global Attention Pool.
A gated attention global pooling layer as presented by [Li et al. (2017)](https://arxiv.org/abs/1511.05493).
Details can be seen from https://github.com/danielegrattarola/spektral
Args:
state_dim (int): number of output channels.
"""
def __init__(self, state_dim, **kwargs):
super(GlobalAttentionPool, self).__init__()
self.state_dim = state_dim
self.kwargs = kwargs
def __str__(self):
return f"GlobalAttentionPool"
def build(self, input_shape):
self.features_layer = Dense(self.state_dim, name='features_layer')
self.attention_layer = Dense(self.state_dim, name='attention_layer', activation='sigmoid')
self.built = True
def call(self, inputs, **kwargs):
"""
Args:
inputs (tensor): the node feature tensor
Returns:
GlobalAttentionPool tensor (tensor)
"""
inputs_linear = self.features_layer(inputs)
attn = self.attention_layer(inputs)
masked_inputs = inputs_linear * attn
output = K.sum(masked_inputs, axis=-2, keepdims=False)
return output
class GlobalAttentionSumPool(tf.keras.layers.Layer):
r"""Global Attention Summation Pool.
Pools a graph by learning attention coefficients to sum node features.
Details can be seen from https://github.com/danielegrattarola/spektral
"""
def __init__(self, **kwargs):
super(GlobalAttentionSumPool, self).__init__()
self.kwargs = kwargs
def __str__(self):
return f"GlobalAttentionSumPool"
def build(self, input_shape):
F = int(input_shape[-1])
# Attention kernels
self.attn_kernel = self.add_weight(shape=(F, 1),
initializer='glorot_uniform',
name='attn_kernel')
self.built = True
def call(self, inputs, **kwargs):
"""
Args:
inputs (tensor): the node feature tensor
Returns:
GlobalAttentionSumPool tensor (tensor)
"""
X = inputs
attn_coeff = K.dot(X, self.attn_kernel)
attn_coeff = K.squeeze(attn_coeff, -1)
attn_coeff = K.softmax(attn_coeff)
output = K.batch_dot(attn_coeff, X)
return output
class GlobalAvgPool(tf.keras.layers.Layer):
r"""Global Average Pool.
Takes the average over all the nodes or features.
Details can be seen from https://github.com/danielegrattarola/spektral
Args:
axis (int): the axis to take average.
"""
def __init__(self, axis=-2, **kwargs):
super(GlobalAvgPool, self).__init__()
self.axis = axis
self.kwargs = kwargs
def __str__(self):
return f"GlobalAvgPool"
def call(self, inputs, **kwargs):
"""
Args:
inputs (tensor): the node feature tensor
Returns:
GlobalAvgPool tensor (tensor)
"""
return tf.reduce_mean(inputs, axis=self.axis)
class GlobalMaxPool(tf.keras.layers.Layer):
r"""Global Max Pool.
Takes the max value over all the nodes or features.
Details can be seen from https://github.com/danielegrattarola/spektral
Args:
axis (int): the axis to take the max value.
"""
def __init__(self, axis=-2, **kwargs):
super(GlobalMaxPool, self).__init__()
self.axis = axis
self.kwargs = kwargs
def __str__(self):
return f"GlobalMaxPool"
def call(self, inputs, **kwargs):
"""
Args:
inputs (tensor): the node feature tensor
Returns:
GlobalMaxPool tensor (tensor)
"""
return tf.reduce_max(inputs, axis=self.axis)
class GlobalSumPool(tf.keras.layers.Layer):
r"""Global Summation Pool.
Takes the summation over all the nodes or features.
Details can be seen from https://github.com/danielegrattarola/spektral
Args:
axis (int): the axis to take summation.
"""
def __init__(self, axis=-2, **kwargs):
super(GlobalSumPool, self).__init__()
self.axis = axis
self.kwargs = kwargs
def __str__(self):
return f"GlobalSumPool"
def call(self, inputs, **kwargs):
"""
Args:
inputs (tensor): the node feature tensor
Returns:
GlobalSumPool tensor (tensor)
"""
return tf.reduce_sum(inputs, axis=self.axis)
|
[
"tensorflow.reduce_sum",
"numpy.random.seed",
"tensorflow.keras.backend.softmax",
"tensorflow.keras.layers.Dense",
"tensorflow.nn.tanh",
"tensorflow.reshape",
"tensorflow.keras.backend.int_shape",
"tensorflow.multiply",
"tensorflow.matmul",
"tensorflow.math.unsorted_segment_sum",
"tensorflow.nn.leaky_relu",
"tensorflow.reduce_max",
"tensorflow.keras.activations.get",
"tensorflow.keras.layers.Concatenate",
"tensorflow.gather",
"tensorflow.set_random_seed",
"tensorflow.cast",
"tensorflow.range",
"tensorflow.keras.layers.GRU",
"tensorflow.reduce_mean",
"tensorflow.transpose",
"tensorflow.tile",
"tensorflow.keras.backend.batch_dot",
"tensorflow.expand_dims",
"tensorflow.math.unsorted_segment_mean",
"tensorflow.keras.backend.sum",
"tensorflow.keras.backend.squeeze",
"tensorflow.keras.backend.bias_add",
"tensorflow.shape",
"tensorflow.keras.backend.dot",
"tensorflow.nn.dropout",
"tensorflow.math.unsorted_segment_max"
] |
[((221, 231), 'numpy.random.seed', 'seed', (['(2020)'], {}), '(2020)\n', (225, 231), False, 'from numpy.random import seed\n'), ((233, 254), 'tensorflow.set_random_seed', 'set_random_seed', (['(2020)'], {}), '(2020)\n', (248, 254), False, 'from tensorflow import set_random_seed\n'), ((1102, 1129), 'tensorflow.keras.activations.get', 'activations.get', (['activation'], {}), '(activation)\n', (1117, 1129), False, 'from tensorflow.keras import activations\n'), ((1349, 1414), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['self.state_dim'], {'activation': 'self.activation'}), '(self.state_dim, activation=self.activation)\n', (1370, 1414), True, 'import tensorflow as tf\n'), ((2200, 2220), 'tensorflow.cast', 'tf.cast', (['A', 'tf.int32'], {}), '(A, tf.int32)\n', (2207, 2220), True, 'import tensorflow as tf\n'), ((4292, 4340), 'tensorflow.tile', 'tf.tile', (['mask[..., None]', '[1, 1, self.state_dim]'], {}), '(mask[..., None], [1, 1, self.state_dim])\n', (4299, 4340), True, 'import tensorflow as tf\n'), ((4358, 4382), 'tensorflow.multiply', 'tf.multiply', (['agg_m', 'mask'], {}), '(agg_m, mask)\n', (4369, 4382), True, 'import tensorflow as tf\n'), ((4467, 4499), 'tensorflow.multiply', 'tf.multiply', (['updated_nodes', 'mask'], {}), '(updated_nodes, mask)\n', (4478, 4499), True, 'import tensorflow as tf\n'), ((5299, 5410), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', ([], {'units': '(self.state_dim * self.state_dim * self.attn_heads)', 'activation': 'self.activation'}), '(units=self.state_dim * self.state_dim * self.\n attn_heads, activation=self.activation)\n', (5320, 5410), True, 'import tensorflow as tf\n'), ((7186, 7235), 'tensorflow.tile', 'tf.tile', (['X[..., None]', '[1, 1, 1, self.attn_heads]'], {}), '(X[..., None], [1, 1, 1, self.attn_heads])\n', (7193, 7235), True, 'import tensorflow as tf\n'), ((7249, 7278), 'tensorflow.transpose', 'tf.transpose', (['X', '[0, 1, 3, 2]'], {}), '(X, [0, 1, 3, 2])\n', (7261, 7278), True, 'import tensorflow as tf\n'), ((7420, 7455), 'tensorflow.gather', 'tf.gather', (['X', 'sources'], {'batch_dims': '(1)'}), '(X, sources, batch_dims=1)\n', (7429, 7455), True, 'import tensorflow as tf\n'), ((7516, 7538), 'tensorflow.matmul', 'tf.matmul', (['W', 'messages'], {}), '(W, messages)\n', (7525, 7538), True, 'import tensorflow as tf\n'), ((7676, 7694), 'tensorflow.range', 'tf.range', (['num_rows'], {}), '(num_rows)\n', (7684, 7694), True, 'import tensorflow as tf\n'), ((8312, 8372), 'tensorflow.reshape', 'tf.reshape', (['output', '[-1, N, self.attn_heads, self.state_dim]'], {}), '(output, [-1, N, self.attn_heads, self.state_dim])\n', (8322, 8372), True, 'import tensorflow as tf\n'), ((8391, 8422), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['output'], {'axis': '(-2)'}), '(output, axis=-2)\n', (8405, 8422), True, 'import tensorflow as tf\n'), ((8441, 8470), 'tensorflow.keras.backend.bias_add', 'K.bias_add', (['output', 'self.bias'], {}), '(output, self.bias)\n', (8451, 8470), True, 'import tensorflow.keras.backend as K\n'), ((8903, 8938), 'tensorflow.keras.layers.Concatenate', 'tf.keras.layers.Concatenate', ([], {'axis': '(1)'}), '(axis=1)\n', (8930, 8938), True, 'import tensorflow as tf\n'), ((8959, 8994), 'tensorflow.keras.layers.GRU', 'tf.keras.layers.GRU', (['self.state_dim'], {}), '(self.state_dim)\n', (8978, 8994), True, 'import tensorflow as tf\n'), ((9445, 9467), 'tensorflow.keras.backend.int_shape', 'K.int_shape', (['old_state'], {}), '(old_state)\n', (9456, 9467), True, 'import tensorflow.keras.backend as K\n'), ((9490, 9515), 'tensorflow.keras.backend.int_shape', 'K.int_shape', (['agg_messages'], {}), '(agg_messages)\n', (9501, 9515), True, 'import tensorflow.keras.backend as K\n'), ((9628, 9661), 'tensorflow.reshape', 'tf.reshape', (['old_state', '[-1, 1, F]'], {}), '(old_state, [-1, 1, F])\n', (9638, 9661), True, 'import tensorflow as tf\n'), ((9686, 9723), 'tensorflow.reshape', 'tf.reshape', (['agg_messages', '[-1, 1, F1]'], {}), '(agg_messages, [-1, 1, F1])\n', (9696, 9723), True, 'import tensorflow as tf\n'), ((9908, 9942), 'tensorflow.reshape', 'tf.reshape', (['activation', '[-1, N, F]'], {}), '(activation, [-1, N, F])\n', (9918, 9942), True, 'import tensorflow as tf\n'), ((10443, 10479), 'tensorflow.keras.layers.Concatenate', 'tf.keras.layers.Concatenate', ([], {'axis': '(-1)'}), '(axis=-1)\n', (10470, 10479), True, 'import tensorflow as tf\n'), ((10502, 10599), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['self.state_dim'], {'activation': 'self.activation', 'kernel_initializer': '"""zeros"""'}), "(self.state_dim, activation=self.activation,\n kernel_initializer='zeros')\n", (10523, 10599), True, 'import tensorflow as tf\n'), ((12802, 12848), 'tensorflow.transpose', 'tf.transpose', (['self.attn_kernel_self', '(2, 1, 0)'], {}), '(self.attn_kernel_self, (2, 1, 0))\n', (12814, 12848), True, 'import tensorflow as tf\n'), ((12877, 12923), 'tensorflow.transpose', 'tf.transpose', (['self.attn_kernel_adjc', '(2, 1, 0)'], {}), '(self.attn_kernel_adjc, (2, 1, 0))\n', (12889, 12923), True, 'import tensorflow as tf\n'), ((12949, 12999), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(X * attn_kernel_self[None, ...])', '(-1)'], {}), '(X * attn_kernel_self[None, ...], -1)\n', (12962, 12999), True, 'import tensorflow as tf\n'), ((13025, 13072), 'tensorflow.gather', 'tf.gather', (['attn_for_self', 'targets'], {'batch_dims': '(1)'}), '(attn_for_self, targets, batch_dims=1)\n', (13034, 13072), True, 'import tensorflow as tf\n'), ((13098, 13148), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(X * attn_kernel_adjc[None, ...])', '(-1)'], {}), '(X * attn_kernel_adjc[None, ...], -1)\n', (13111, 13148), True, 'import tensorflow as tf\n'), ((13174, 13221), 'tensorflow.gather', 'tf.gather', (['attn_for_adjc', 'sources'], {'batch_dims': '(1)'}), '(attn_for_adjc, sources, batch_dims=1)\n', (13183, 13221), True, 'import tensorflow as tf\n'), ((13294, 13332), 'tensorflow.nn.leaky_relu', 'tf.nn.leaky_relu', (['attn_coef'], {'alpha': '(0.2)'}), '(attn_coef, alpha=0.2)\n', (13310, 13332), True, 'import tensorflow as tf\n'), ((13568, 13597), 'tensorflow.nn.dropout', 'tf.nn.dropout', (['attn_coef', '(0.5)'], {}), '(attn_coef, 0.5)\n', (13581, 13597), True, 'import tensorflow as tf\n'), ((15229, 15275), 'tensorflow.transpose', 'tf.transpose', (['self.attn_kernel_self', '(2, 1, 0)'], {}), '(self.attn_kernel_self, (2, 1, 0))\n', (15241, 15275), True, 'import tensorflow as tf\n'), ((15304, 15350), 'tensorflow.transpose', 'tf.transpose', (['self.attn_kernel_adjc', '(2, 1, 0)'], {}), '(self.attn_kernel_adjc, (2, 1, 0))\n', (15316, 15350), True, 'import tensorflow as tf\n'), ((15376, 15426), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(X * attn_kernel_self[None, ...])', '(-1)'], {}), '(X * attn_kernel_self[None, ...], -1)\n', (15389, 15426), True, 'import tensorflow as tf\n'), ((15452, 15499), 'tensorflow.gather', 'tf.gather', (['attn_for_self', 'targets'], {'batch_dims': '(1)'}), '(attn_for_self, targets, batch_dims=1)\n', (15461, 15499), True, 'import tensorflow as tf\n'), ((15525, 15575), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(X * attn_kernel_adjc[None, ...])', '(-1)'], {}), '(X * attn_kernel_adjc[None, ...], -1)\n', (15538, 15575), True, 'import tensorflow as tf\n'), ((15601, 15648), 'tensorflow.gather', 'tf.gather', (['attn_for_adjc', 'sources'], {'batch_dims': '(1)'}), '(attn_for_adjc, sources, batch_dims=1)\n', (15610, 15648), True, 'import tensorflow as tf\n'), ((15684, 15731), 'tensorflow.gather', 'tf.gather', (['attn_for_self', 'sources'], {'batch_dims': '(1)'}), '(attn_for_self, sources, batch_dims=1)\n', (15693, 15731), True, 'import tensorflow as tf\n'), ((15765, 15812), 'tensorflow.gather', 'tf.gather', (['attn_for_self', 'targets'], {'batch_dims': '(1)'}), '(attn_for_self, targets, batch_dims=1)\n', (15774, 15812), True, 'import tensorflow as tf\n'), ((15933, 15971), 'tensorflow.nn.leaky_relu', 'tf.nn.leaky_relu', (['attn_coef'], {'alpha': '(0.2)'}), '(attn_coef, alpha=0.2)\n', (15949, 15971), True, 'import tensorflow as tf\n'), ((16207, 16236), 'tensorflow.nn.dropout', 'tf.nn.dropout', (['attn_coef', '(0.5)'], {}), '(attn_coef, 0.5)\n', (16220, 16236), True, 'import tensorflow as tf\n'), ((17967, 18013), 'tensorflow.transpose', 'tf.transpose', (['self.attn_kernel_self', '(2, 1, 0)'], {}), '(self.attn_kernel_self, (2, 1, 0))\n', (17979, 18013), True, 'import tensorflow as tf\n'), ((18042, 18088), 'tensorflow.transpose', 'tf.transpose', (['self.attn_kernel_adjc', '(2, 1, 0)'], {}), '(self.attn_kernel_adjc, (2, 1, 0))\n', (18054, 18088), True, 'import tensorflow as tf\n'), ((18114, 18164), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(X * attn_kernel_self[None, ...])', '(-1)'], {}), '(X * attn_kernel_self[None, ...], -1)\n', (18127, 18164), True, 'import tensorflow as tf\n'), ((18190, 18237), 'tensorflow.gather', 'tf.gather', (['attn_for_self', 'targets'], {'batch_dims': '(1)'}), '(attn_for_self, targets, batch_dims=1)\n', (18199, 18237), True, 'import tensorflow as tf\n'), ((18263, 18313), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(X * attn_kernel_adjc[None, ...])', '(-1)'], {}), '(X * attn_kernel_adjc[None, ...], -1)\n', (18276, 18313), True, 'import tensorflow as tf\n'), ((18339, 18386), 'tensorflow.gather', 'tf.gather', (['attn_for_adjc', 'sources'], {'batch_dims': '(1)'}), '(attn_for_adjc, sources, batch_dims=1)\n', (18348, 18386), True, 'import tensorflow as tf\n'), ((18408, 18449), 'tensorflow.multiply', 'tf.multiply', (['attn_for_self', 'attn_for_adjc'], {}), '(attn_for_self, attn_for_adjc)\n', (18419, 18449), True, 'import tensorflow as tf\n'), ((18471, 18509), 'tensorflow.nn.leaky_relu', 'tf.nn.leaky_relu', (['attn_coef'], {'alpha': '(0.2)'}), '(attn_coef, alpha=0.2)\n', (18487, 18509), True, 'import tensorflow as tf\n'), ((18745, 18774), 'tensorflow.nn.dropout', 'tf.nn.dropout', (['attn_coef', '(0.5)'], {}), '(attn_coef, 0.5)\n', (18758, 18774), True, 'import tensorflow as tf\n'), ((20296, 20342), 'tensorflow.transpose', 'tf.transpose', (['self.attn_kernel_adjc', '(2, 1, 0)'], {}), '(self.attn_kernel_adjc, (2, 1, 0))\n', (20308, 20342), True, 'import tensorflow as tf\n'), ((20368, 20418), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(X * attn_kernel_adjc[None, ...])', '(-1)'], {}), '(X * attn_kernel_adjc[None, ...], -1)\n', (20381, 20418), True, 'import tensorflow as tf\n'), ((20444, 20491), 'tensorflow.gather', 'tf.gather', (['attn_for_adjc', 'sources'], {'batch_dims': '(1)'}), '(attn_for_adjc, sources, batch_dims=1)\n', (20453, 20491), True, 'import tensorflow as tf\n'), ((20548, 20569), 'tensorflow.nn.tanh', 'tf.nn.tanh', (['attn_coef'], {}), '(attn_coef)\n', (20558, 20569), True, 'import tensorflow as tf\n'), ((20805, 20834), 'tensorflow.nn.dropout', 'tf.nn.dropout', (['attn_coef', '(0.5)'], {}), '(attn_coef, 0.5)\n', (20818, 20834), True, 'import tensorflow as tf\n'), ((22036, 22138), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', ([], {'units': 'self.attn_heads', 'kernel_initializer': '"""glorot_uniform"""', 'use_bias': '(False)'}), "(units=self.attn_heads, kernel_initializer=\n 'glorot_uniform', use_bias=False)\n", (22057, 22138), True, 'import tensorflow as tf\n'), ((22759, 22805), 'tensorflow.transpose', 'tf.transpose', (['self.attn_kernel_self', '(2, 1, 0)'], {}), '(self.attn_kernel_self, (2, 1, 0))\n', (22771, 22805), True, 'import tensorflow as tf\n'), ((22834, 22880), 'tensorflow.transpose', 'tf.transpose', (['self.attn_kernel_adjc', '(2, 1, 0)'], {}), '(self.attn_kernel_adjc, (2, 1, 0))\n', (22846, 22880), True, 'import tensorflow as tf\n'), ((22906, 22956), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(X * attn_kernel_self[None, ...])', '(-1)'], {}), '(X * attn_kernel_self[None, ...], -1)\n', (22919, 22956), True, 'import tensorflow as tf\n'), ((22982, 23029), 'tensorflow.gather', 'tf.gather', (['attn_for_self', 'targets'], {'batch_dims': '(1)'}), '(attn_for_self, targets, batch_dims=1)\n', (22991, 23029), True, 'import tensorflow as tf\n'), ((23055, 23105), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(X * attn_kernel_adjc[None, ...])', '(-1)'], {}), '(X * attn_kernel_adjc[None, ...], -1)\n', (23068, 23105), True, 'import tensorflow as tf\n'), ((23131, 23178), 'tensorflow.gather', 'tf.gather', (['attn_for_adjc', 'sources'], {'batch_dims': '(1)'}), '(attn_for_adjc, sources, batch_dims=1)\n', (23140, 23178), True, 'import tensorflow as tf\n'), ((23251, 23272), 'tensorflow.nn.tanh', 'tf.nn.tanh', (['attn_coef'], {}), '(attn_coef)\n', (23261, 23272), True, 'import tensorflow as tf\n'), ((23552, 23581), 'tensorflow.nn.dropout', 'tf.nn.dropout', (['attn_coef', '(0.5)'], {}), '(attn_coef, 0.5)\n', (23565, 23581), True, 'import tensorflow as tf\n'), ((24854, 24900), 'tensorflow.tile', 'tf.tile', (['attn_coef', '[1, 1, self.attn_heads, 1]'], {}), '(attn_coef, [1, 1, self.attn_heads, 1])\n', (24861, 24900), True, 'import tensorflow as tf\n'), ((26742, 26786), 'tensorflow.keras.layers.Dense', 'Dense', (['self.state_dim'], {'name': '"""features_layer"""'}), "(self.state_dim, name='features_layer')\n", (26747, 26786), False, 'from tensorflow.keras.layers import Dense\n'), ((26819, 26886), 'tensorflow.keras.layers.Dense', 'Dense', (['self.state_dim'], {'name': '"""attention_layer"""', 'activation': '"""sigmoid"""'}), "(self.state_dim, name='attention_layer', activation='sigmoid')\n", (26824, 26886), False, 'from tensorflow.keras.layers import Dense\n'), ((27281, 27326), 'tensorflow.keras.backend.sum', 'K.sum', (['masked_inputs'], {'axis': '(-2)', 'keepdims': '(False)'}), '(masked_inputs, axis=-2, keepdims=False)\n', (27286, 27326), True, 'import tensorflow.keras.backend as K\n'), ((28383, 28409), 'tensorflow.keras.backend.dot', 'K.dot', (['X', 'self.attn_kernel'], {}), '(X, self.attn_kernel)\n', (28388, 28409), True, 'import tensorflow.keras.backend as K\n'), ((28432, 28457), 'tensorflow.keras.backend.squeeze', 'K.squeeze', (['attn_coeff', '(-1)'], {}), '(attn_coeff, -1)\n', (28441, 28457), True, 'import tensorflow.keras.backend as K\n'), ((28480, 28501), 'tensorflow.keras.backend.softmax', 'K.softmax', (['attn_coeff'], {}), '(attn_coeff)\n', (28489, 28501), True, 'import tensorflow.keras.backend as K\n'), ((28520, 28546), 'tensorflow.keras.backend.batch_dot', 'K.batch_dot', (['attn_coeff', 'X'], {}), '(attn_coeff, X)\n', (28531, 28546), True, 'import tensorflow.keras.backend as K\n'), ((29278, 29316), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['inputs'], {'axis': 'self.axis'}), '(inputs, axis=self.axis)\n', (29292, 29316), True, 'import tensorflow as tf\n'), ((30029, 30066), 'tensorflow.reduce_max', 'tf.reduce_max', (['inputs'], {'axis': 'self.axis'}), '(inputs, axis=self.axis)\n', (30042, 30066), True, 'import tensorflow as tf\n'), ((30783, 30820), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['inputs'], {'axis': 'self.axis'}), '(inputs, axis=self.axis)\n', (30796, 30820), True, 'import tensorflow as tf\n'), ((6982, 6996), 'tensorflow.keras.backend.int_shape', 'K.int_shape', (['X'], {}), '(X)\n', (6993, 6996), True, 'import tensorflow.keras.backend as K\n'), ((7635, 7652), 'tensorflow.shape', 'tf.shape', (['targets'], {}), '(targets)\n', (7643, 7652), True, 'import tensorflow as tf\n'), ((7898, 7969), 'tensorflow.math.unsorted_segment_max', 'tf.math.unsorted_segment_max', (['output', 'segment_ids_per_row', '(N * num_rows)'], {}), '(output, segment_ids_per_row, N * num_rows)\n', (7926, 7969), True, 'import tensorflow as tf\n'), ((7740, 7772), 'tensorflow.expand_dims', 'tf.expand_dims', (['rows_idx'], {'axis': '(1)'}), '(rows_idx, axis=1)\n', (7754, 7772), True, 'import tensorflow as tf\n'), ((8034, 8106), 'tensorflow.math.unsorted_segment_mean', 'tf.math.unsorted_segment_mean', (['output', 'segment_ids_per_row', '(N * num_rows)'], {}), '(output, segment_ids_per_row, N * num_rows)\n', (8063, 8106), True, 'import tensorflow as tf\n'), ((13478, 13529), 'tensorflow.math.unsorted_segment_max', 'tf.math.unsorted_segment_max', (['attn_coef', 'targets', 'N'], {}), '(attn_coef, targets, N)\n', (13506, 13529), True, 'import tensorflow as tf\n'), ((16117, 16168), 'tensorflow.math.unsorted_segment_max', 'tf.math.unsorted_segment_max', (['attn_coef', 'targets', 'N'], {}), '(attn_coef, targets, N)\n', (16145, 16168), True, 'import tensorflow as tf\n'), ((18655, 18706), 'tensorflow.math.unsorted_segment_max', 'tf.math.unsorted_segment_max', (['attn_coef', 'targets', 'N'], {}), '(attn_coef, targets, N)\n', (18683, 18706), True, 'import tensorflow as tf\n'), ((20715, 20766), 'tensorflow.math.unsorted_segment_max', 'tf.math.unsorted_segment_max', (['attn_coef', 'targets', 'N'], {}), '(attn_coef, targets, N)\n', (20743, 20766), True, 'import tensorflow as tf\n'), ((23462, 23513), 'tensorflow.math.unsorted_segment_max', 'tf.math.unsorted_segment_max', (['attn_coef', 'targets', 'N'], {}), '(attn_coef, targets, N)\n', (23490, 23513), True, 'import tensorflow as tf\n'), ((7107, 7118), 'tensorflow.shape', 'tf.shape', (['E'], {}), '(E)\n', (7115, 7118), True, 'import tensorflow as tf\n'), ((8170, 8241), 'tensorflow.math.unsorted_segment_sum', 'tf.math.unsorted_segment_sum', (['output', 'segment_ids_per_row', '(N * num_rows)'], {}), '(output, segment_ids_per_row, N * num_rows)\n', (8198, 8241), True, 'import tensorflow as tf\n'), ((13383, 13434), 'tensorflow.math.unsorted_segment_max', 'tf.math.unsorted_segment_max', (['attn_coef', 'targets', 'N'], {}), '(attn_coef, targets, N)\n', (13411, 13434), True, 'import tensorflow as tf\n'), ((16022, 16073), 'tensorflow.math.unsorted_segment_max', 'tf.math.unsorted_segment_max', (['attn_coef', 'targets', 'N'], {}), '(attn_coef, targets, N)\n', (16050, 16073), True, 'import tensorflow as tf\n'), ((18560, 18611), 'tensorflow.math.unsorted_segment_max', 'tf.math.unsorted_segment_max', (['attn_coef', 'targets', 'N'], {}), '(attn_coef, targets, N)\n', (18588, 18611), True, 'import tensorflow as tf\n'), ((20620, 20671), 'tensorflow.math.unsorted_segment_max', 'tf.math.unsorted_segment_max', (['attn_coef', 'targets', 'N'], {}), '(attn_coef, targets, N)\n', (20648, 20671), True, 'import tensorflow as tf\n'), ((23367, 23418), 'tensorflow.math.unsorted_segment_max', 'tf.math.unsorted_segment_max', (['attn_coef', 'targets', 'N'], {}), '(attn_coef, targets, N)\n', (23395, 23418), True, 'import tensorflow as tf\n'), ((25993, 26010), 'tensorflow.shape', 'tf.shape', (['targets'], {}), '(targets)\n', (26001, 26010), True, 'import tensorflow as tf\n'), ((26015, 26032), 'tensorflow.shape', 'tf.shape', (['targets'], {}), '(targets)\n', (26023, 26032), True, 'import tensorflow as tf\n')]
|
"""Functions for control of LTI systems."""
# Author: <NAME>
import numpy as np
from .matrixmath import dlyap, mdot
def ctrb(A, B):
"""Controllabilty matrix
Parameters
----------
A, B: np.array
Dynamics and input matrix of the system
Returns
-------
C: matrix
Controllability matrix
Examples
--------
>>> C = ctrb(A, B)
"""
n, m = np.shape(B)
AiB = np.zeros([n,m,n])
AiB[:,:,0] = np.copy(B)
for i in range(n-1):
AiB[:,:,i+1] = np.dot(A, AiB[:,:,i])
ctrb_matrix = np.reshape(AiB, [n,n*m], order='F')
return ctrb_matrix
def obsv(A, C):
"""Observability matrix
Parameters
----------
A, C: np.array
Dynamics and output matrix of the system
Returns
-------
O: matrix
Observability matrix
Examples
--------
>>> O = obsv(A, C)
"""
return ctrb(A.T, C.T).T
def dgram_ctrb(A, B):
"""Discrete-time controllability Gramian."""
return dlyap(A, B.dot(B.T))
def dgram_obsv(A, C):
"""Discrete-time observability Gramian."""
# return dlyap(A.T,C.T.dot(C))
return dgram_ctrb(A.T, C.T)
def dctg(A, Q, t):
"""Discrete-time finite-horizon cost-to-go matrix"""
P = np.copy(Q)
Pt = np.copy(Q)
for _ in range(t):
Pt = mdot(A.T, Pt, A)
P += Pt
return P
|
[
"numpy.copy",
"numpy.zeros",
"numpy.shape",
"numpy.reshape",
"numpy.dot"
] |
[((421, 432), 'numpy.shape', 'np.shape', (['B'], {}), '(B)\n', (429, 432), True, 'import numpy as np\n'), ((444, 463), 'numpy.zeros', 'np.zeros', (['[n, m, n]'], {}), '([n, m, n])\n', (452, 463), True, 'import numpy as np\n'), ((480, 490), 'numpy.copy', 'np.copy', (['B'], {}), '(B)\n', (487, 490), True, 'import numpy as np\n'), ((582, 620), 'numpy.reshape', 'np.reshape', (['AiB', '[n, n * m]'], {'order': '"""F"""'}), "(AiB, [n, n * m], order='F')\n", (592, 620), True, 'import numpy as np\n'), ((1302, 1312), 'numpy.copy', 'np.copy', (['Q'], {}), '(Q)\n', (1309, 1312), True, 'import numpy as np\n'), ((1323, 1333), 'numpy.copy', 'np.copy', (['Q'], {}), '(Q)\n', (1330, 1333), True, 'import numpy as np\n'), ((541, 564), 'numpy.dot', 'np.dot', (['A', 'AiB[:, :, i]'], {}), '(A, AiB[:, :, i])\n', (547, 564), True, 'import numpy as np\n')]
|
import numpy as np
class RandomEstimator:
def estimate(self, X_pool, *args):
return np.ones(X_pool.shape[0])
|
[
"numpy.ones"
] |
[((98, 122), 'numpy.ones', 'np.ones', (['X_pool.shape[0]'], {}), '(X_pool.shape[0])\n', (105, 122), True, 'import numpy as np\n')]
|
# -------------------------------------------------
# IMPORTS
# -------------------------------------------------
import numpy as np
from math import ceil
from imblearn.under_sampling import NearMiss
from imblearn.over_sampling import SMOTE, ADASYN
from collections import Counter
from sklearn.ensemble import RandomForestClassifier
from art.attacks import BoundaryAttack, ZooAttack, HopSkipJump
from art.classifiers import SklearnClassifier
from sklearn import preprocessing
from sklearn.model_selection import train_test_split
# CONCEPT SHIFT
def any_other_label(label_to_change, labels):
if len(labels) == 1:
#print('Warning: no other possible value to select. Returning the one single allowed value.')
return label_to_change
allowed_indices = np.where(labels != label_to_change)[0]
new_label = labels[np.random.choice(allowed_indices)]
return new_label
# Random change class of a subset of data.
def random_class_subset_shift(x, y, perc_max_changes=0.3):
labels, counts = np.unique(y, return_counts=True)
subset_indices = np.random.choice(x.shape[0], ceil(x.shape[0] * perc_max_changes), replace=False)
n_max_changes = int(np.floor(perc_max_changes * y.shape[0]))
subset_indices = subset_indices[:n_max_changes]
rand_labeler = lambda y: any_other_label(y, labels)
vec_rand_labeler = np.vectorize(rand_labeler)
y[subset_indices] = vec_rand_labeler(y[subset_indices])
return x, y, subset_indices
# PRIOR SHIFT
# Resample instances of all classes by given priors.
def rebalance_shift(x, y, priors):
labels, counts = np.unique(y, return_counts=True)
n_labels = len(labels)
n_priors = len(priors)
assert (n_labels == n_priors)
assert (np.sum(priors) == 1.)
n_to_sample = y.shape[0]
for label_idx, prior in enumerate(priors):
if prior > 0:
n_samples_label = counts[label_idx]
max_n_to_sample = np.round(n_samples_label / prior)
if n_to_sample > max_n_to_sample:
n_to_sample = max_n_to_sample
resampled_counts = [int(np.round(prior * n_to_sample)) for prior in priors]
resampled_indices = []
for cl, res_count in zip(labels, resampled_counts):
if res_count:
cl_indices = np.where(y == cl)[0]
cl_res_indices = np.random.choice(cl_indices, res_count, replace=False)
resampled_indices.extend(cl_res_indices)
x = x[resampled_indices, :]
y = y[resampled_indices]
return x, y
# Remove instances of a single class.
def knockout_shift(x, y, cl, delta):
del_indices = np.where(y == cl)[0]
until_index = ceil(delta * len(del_indices))
if until_index % 2 != 0:
until_index = until_index + 1
del_indices = del_indices[:until_index]
x = np.delete(x, del_indices, axis=0)
y = np.delete(y, del_indices, axis=0)
return x, y
# Remove all classes except for one via multiple knock-out.
def only_one_shift(x, y, keep_cl):
labels = np.unique(y)
for cl in labels:
if cl != keep_cl:
x, y = knockout_shift(x, y, cl, 1.0)
return x, y
# COVARIATE SHIFT
# Keeps an observation with a probability which decreases as points are further away from the samples mean
# gamma is the fraction of samples close to the mean we want to keep
def subsample_joint_shift(x, y, gamma=0.8, shift_features=None):
if shift_features is None:
shift_features = list(range(x.shape[1]))
x_mean = np.mean(x[:, shift_features], axis=0)
distance = np.sqrt(np.sum((x[:, shift_features] - x_mean) ** 2, axis=1))
gamma_quantile = np.quantile(distance, gamma)
ln_prob_keep_far = np.log(0.5) # sample with probability 50% samples with distance after gamma quantile
probabilities = np.exp(ln_prob_keep_far / gamma_quantile * distance)
keep_decisions = np.array([np.random.choice(['keep', 'remove'], size=1, p=[p, 1 - p])[0] for p in probabilities])
keep_indices = np.where(keep_decisions == 'keep')[0]
x = x[keep_indices, :]
y = y[keep_indices]
return x, y, shift_features
def is_integer_feature(x, f):
values = np.unique(x[:, f])
if values.dtype.char in np.typecodes['AllInteger']:
return True
else:
return np.all([v.is_integer() for v in values])
def is_categorical_feature(x, f):
values = np.unique(x[:, f])
n_values = len(values)
is_categorical = is_integer_feature(x, f) & (n_values < 1000)
return is_categorical
def get_feature_split_value(x, f):
#values = np.unique(x[:, f])
values = x[:, f]
f_split = np.median(values)
return f_split
# Subsample feature f with probability p when f<=f_split and 1-p when f>f_split.
def subsample_one_feature_shift(x, y, f, f_split, p=0.5, one_side=True, min_size=5000):
smaller_than_split_indices = np.where(x[:, f] <= f_split)[0]
n_smaller = len(smaller_than_split_indices)
larger_than_split_indices = np.where(x[:, f] > f_split)[0]
n_larger = len(larger_than_split_indices)
keep_smaller_decisions = np.random.choice(['keep', 'remove'], size=n_smaller, p=[p, 1 - p])
keep_smaller_indices = smaller_than_split_indices[np.where(keep_smaller_decisions == 'keep')[0]]
if one_side:
keep_larger_indices = larger_than_split_indices
else:
keep_larger_decisions = np.random.choice(['keep', 'remove'], size=n_larger, p=[1 - p, p])
keep_larger_indices = larger_than_split_indices[np.where(keep_larger_decisions == 'keep')[0]]
keep_indices = np.hstack([keep_smaller_indices, keep_larger_indices])
if len(keep_indices) < min_size:
to_add = min_size - len(keep_indices)
remove_smaller_indices = smaller_than_split_indices[np.where(keep_smaller_decisions == 'remove')[0]]
keep_indices = np.hstack([keep_smaller_indices, remove_smaller_indices[:to_add], keep_larger_indices])
x = x[keep_indices, :]
y = y[keep_indices]
return x, y
# Subsample all features with probability p when f<=f_split and 1-p when f>f_split
def subsample_feature_shift(x, y, feat_delta=0.5, p=0.5, numerical_features=None, one_side=True, min_size=5000):
if numerical_features is not None:
n_numerical = len(numerical_features)
n_feat_subsample = max(1, ceil(n_numerical * feat_delta))
feat_indices = np.random.choice(n_numerical, n_feat_subsample, replace=False)
feat_indices = np.array(numerical_features)[feat_indices]
else:
n_feat_subsample = min(1, ceil(x.shape[1] * feat_delta))
feat_indices = np.random.choice(x.shape[1], n_feat_subsample, replace=False)
for f in feat_indices:
f_split = get_feature_split_value(x, f)
x, y = subsample_one_feature_shift(x, y, f, f_split, p=p, one_side=one_side, min_size=min_size)
return x, y, feat_indices
def split_categorical_feature(x, group_features):
unique_rows = np.unique(x[:, np.array(group_features)], axis=0)
n_half = ceil(0.5 * unique_rows.shape[0])
choice = np.random.choice(range(unique_rows.shape[0]), size=(n_half,), replace=False)
half_1 = np.zeros(unique_rows.shape[0], dtype=bool)
half_1[choice] = True
half_2 = ~half_1
return unique_rows[half_1], unique_rows[half_2]
# Subsample categorical feature with probability p when f is in a random selection of categories,
# 1-p when f is in the remaining categories.
def subsample_categorical_feature_shift(x, y, group_features, p=0.5, return_groups=False, one_side=True, min_size=5000):
group_1, group_2 = split_categorical_feature(x, group_features)
smaller_than_split_indices = np.where(
np.apply_along_axis(lambda val: (val == group_1).all(axis=1).any(), 1, x[:, group_features]))[0]
n_smaller = len(smaller_than_split_indices)
larger_than_split_indices = np.where(
np.apply_along_axis(lambda val: (val == group_2).all(axis=1).any(), 1, x[:, group_features]))[0]
n_larger = len(larger_than_split_indices)
keep_smaller_decisions = np.random.choice(['keep', 'remove'], size=n_smaller, p=[p, 1 - p])
keep_smaller_indices = smaller_than_split_indices[np.where(keep_smaller_decisions == 'keep')[0]]
if one_side:
keep_larger_indices = larger_than_split_indices
else:
keep_larger_decisions = np.random.choice(['keep', 'remove'], size=n_larger, p=[1 - p, p])
keep_larger_indices = larger_than_split_indices[np.where(keep_larger_decisions == 'keep')[0]]
keep_indices = np.hstack([keep_smaller_indices, keep_larger_indices])
if len(keep_indices) < min_size:
to_add = min_size - len(keep_indices)
remove_smaller_indices = smaller_than_split_indices[np.where(keep_smaller_decisions == 'remove')[0]]
keep_indices = np.hstack([keep_smaller_indices, remove_smaller_indices[:to_add], keep_larger_indices])
x = x[keep_indices, :]
y = y[keep_indices]
if not return_groups:
return x, y
else:
return x, y, group_1, group_2
def subsample_all_categorical_feature_shift(x, y, categorical_groups, p=0.5, min_size=5000):
for group_features in categorical_groups:
x, y = subsample_categorical_feature_shift(x, y, group_features, p=p, min_size=min_size)
return x, y
# Subsample all features with probability p when f<=f_split and 1-p when f>f_split
def subsample_all_feature_shift(x, y, p=0.5, numerical_features=None, categorical_groups=None, one_side=True, min_size=5000):
x, y, _ = subsample_feature_shift(x, y, feat_delta=1.0, p=p, numerical_features=numerical_features,
one_side=one_side, min_size=min_size)
if categorical_groups:
x, y = subsample_all_categorical_feature_shift(x, y, categorical_groups, p=p, min_size=min_size)
return x, y
# Gaussian Noise applied on delta portion of samples and feat_delta portion of features
def gaussian_noise_shift(x, y, noise_amt=10., delta=1.0, feat_delta=1.0,
numerical_features=None, clip=True, ceil_int=True):
x, indices, feat_indices = gaussian_noise_subset(
x, noise_amt, normalization=1.0, delta=delta, feat_delta=feat_delta,
numerical_features=numerical_features, clip=clip, ceil_int=ceil_int)
return x, y, indices, feat_indices
def gaussian_noise(x, noise_amt, normalization=1.0, clip=True):
noise = np.random.normal(0, noise_amt / normalization, (x.shape[0], x.shape[1]))
if clip:
x_mins = np.min(x, axis=0)
x_maxs = np.max(x, axis=0)
x_clipped = np.clip(x + noise, x_mins, x_maxs)
return x_clipped
else:
return x + noise
def gaussian_noise_subset(x, noise_amt, normalization=1.0, delta=1.0, feat_delta=1.0,
numerical_features=None, clip=True, ceil_int=True):
# precompute for clip and ceil
int_features = [f for f in range(x.shape[1]) if is_integer_feature(x, f)]
x_mins = np.min(x, axis=0)
x_maxs = np.max(x, axis=0)
indices = np.random.choice(x.shape[0], ceil(x.shape[0] * delta), replace=False)
indices = np.transpose(indices[np.newaxis])
if numerical_features is not None:
n_numerical = len(numerical_features)
feat_indices = np.random.choice(n_numerical, ceil(n_numerical * feat_delta), replace=False)
feat_indices = np.array(numerical_features)[feat_indices]
else:
feat_indices = np.random.choice(x.shape[1], ceil(x.shape[1] * feat_delta), replace=False)
feat_indices = feat_indices[np.newaxis]
x_mod = x[indices, feat_indices]
noise = np.random.normal(0, noise_amt / normalization, (x_mod.shape[0], x_mod.shape[1]))
x_mod = x_mod + noise
if bool(int_features) & ceil_int:
int_features = list(set(int_features) & set(feat_indices.flatten()))
int_features_mapped = [list(feat_indices.flatten()).index(f_idx) for f_idx in int_features]
x_mod[:, int_features_mapped] = np.ceil(x_mod[:, int_features_mapped])
if clip:
x_mod = np.clip(x_mod, x_mins[np.squeeze(feat_indices)], x_maxs[np.squeeze(feat_indices)])
x[indices, feat_indices] = x_mod
return x, indices, feat_indices.flatten()
# Gaussian Noise applied on delta portion of samples and feat_delta portion of features
def constant_value_shift(x, y, delta=1.0, feat_delta=1.0, numerical_features=None):
indices = np.random.choice(x.shape[0], ceil(x.shape[0] * delta), replace=False)
indices = np.transpose(indices[np.newaxis])
if numerical_features is not None:
n_numerical = len(numerical_features)
feat_indices = np.random.choice(n_numerical, ceil(n_numerical * feat_delta), replace=False)
feat_indices = np.array(numerical_features)[feat_indices]
else:
feat_indices = np.random.choice(x.shape[1], ceil(x.shape[1] * feat_delta), replace=False)
feat_indices = feat_indices[np.newaxis]
x_mod = x[indices, feat_indices]
med = np.median(x[:, feat_indices], axis=0)
constant_val = np.repeat(med, x_mod.shape[0], axis=0)
x[indices, feat_indices] = constant_val
return x, y, indices.flatten(), feat_indices.flatten()
# Set a fraction of samples and features to median constant values (numerical) or random constant category (categorical)
def constant_all_feature_shift(x, y, delta=1.0, feat_delta=1.0, numerical_features=None, categorical_groups=None):
x, y, indices, features = constant_value_shift(x, y, delta=delta, feat_delta=feat_delta,
numerical_features=numerical_features)
if categorical_groups:
x[indices, :], y[indices], _, cat_features = constant_categorical_shift(x[indices, :], y[indices],
delta=1.0, feat_delta=feat_delta,
categorical_groups=categorical_groups)
features = np.concatenate((features, cat_features))
return x, y, indices, features
def any_other_array(array_to_change, arrays):
if len(arrays) == 1:
# print('Warning: no other possible value to select. Returning the one single allowed value.')
return array_to_change
allowed_indices = np.where((arrays != array_to_change).any(axis=1))[0]
new_array = arrays[np.random.choice(allowed_indices)]
return new_array
def switch_categorical_features(x, categorical_groups, categories):
for group_features, group_categories in zip(categorical_groups, categories):
switch_val = lambda val: any_other_array(val, group_categories)
x[:, group_features] = np.apply_along_axis(switch_val, 1, x[:, group_features])
return x
def switch_categorical_features_shift(x, y, categorical_groups, delta=0.5, feat_delta=1.0):
indices = np.random.choice(x.shape[0], ceil(x.shape[0] * delta), replace=False)
# compute the categories on the whole sample, otherwise might miss some values
# consider to put as input
n_categorical = len(categorical_groups)
group_indices = np.random.choice(n_categorical, ceil(n_categorical * feat_delta), replace=False)
feat_indices = []
categories = []
selected_categorical_groups = [categorical_groups[i] for i in group_indices]
for group_features in selected_categorical_groups:
if feat_indices is not None:
feat_indices = feat_indices.extend(group_features)
else:
feat_indices = group_features.copy()
unique_rows = np.unique(x[:, np.array(group_features)], axis=0)
categories.append(unique_rows)
x_mod = x[indices, :]
x_mod = switch_categorical_features(x_mod, selected_categorical_groups, categories)
x[indices, :] = x_mod
return x, y, indices, feat_indices
def constant_categorical(x, categorical_groups, categories):
for group_features, group_categories in zip(categorical_groups, categories):
allowed_indices = list(range(len(group_categories)))
random_constant_val = group_categories[np.random.choice(allowed_indices)]
x[:, group_features] = random_constant_val
return x
def constant_categorical_shift(x, y, categorical_groups, delta=0.5, feat_delta=1.0):
indices = np.random.choice(x.shape[0], ceil(x.shape[0] * delta), replace=False)
x_mod = x[indices, :]
# compute the categories on the whole sample, otherwise might miss some values
# consider to put as input
n_categorical = len(categorical_groups)
group_indices = np.random.choice(n_categorical, ceil(n_categorical * feat_delta), replace=False)
feat_indices = None
categories = []
selected_categorical_groups = [categorical_groups[i] for i in group_indices]
for group_features in selected_categorical_groups:
if feat_indices is not None:
feat_indices.extend(group_features)
else:
feat_indices = group_features.copy()
unique_rows = np.unique(x[:, np.array(group_features)], axis=0)
categories.append(unique_rows)
x_mod = constant_categorical(x_mod, selected_categorical_groups, categories)
x[indices, :] = x_mod
return x, y, indices, feat_indices
# Undersample by fraction selecting samples close to the minority class (NearMiss3 heuristics)
def under_sampling_shift(x, y, delta=0.5):
labels = np.unique(y)
y_counts = Counter(np.squeeze(y))
sampling_strategy = dict()
for label in labels:
sampling_strategy[label] = int(delta * y_counts[label])
# version 3 subsamples respecting more the initial data structure,
# but it gives less control on the n of final samples (initial resampling phase)
# thus let use version 2 as the default
nm1 = NearMiss(version=2, sampling_strategy=sampling_strategy)
x_resampled, y_resampled = nm1.fit_resample(x, y)
return x_resampled, y_resampled
# Replace a fraction of samples with samples interpolated from the remaining part
def over_sampling_shift(x, y, delta=0.5, mode='smote', n_neighbors=5):
assert(mode in ['smote', 'adasyn'])
y_counts = Counter(np.squeeze(y))
x_resampled, y_resampled = under_sampling_shift(x, y, delta=delta)
n_min_samples = np.min(list(Counter(y_resampled).values()))
n_neighbors = min(n_neighbors, n_min_samples - 1)
if mode == 'smote':
x_resampled, y_resampled = SMOTE(
sampling_strategy=y_counts, k_neighbors=n_neighbors).fit_resample(x_resampled, y_resampled)
elif mode == 'adasyn':
x_resampled, y_resampled = ADASYN(
sampling_strategy=y_counts, n_neighbors=n_neighbors).fit_resample(x_resampled, y_resampled)
return x_resampled, y_resampled
# non targeted black box adversarial attacks
def adversarial_attack_shift(x, y, delta=1.0, model=RandomForestClassifier(), attack_type='zoo',
numerical_features=None, feat_delta=1.0):
# in this case delta is the portion of half the data on which to generate attacks
# because the first half as a minimum has to be used to train a model against which generate the attacks
assert (attack_type in ['zoo', 'boundary', 'hop-skip-jump'])
le = preprocessing.LabelEncoder()
le.fit(np.squeeze(y))
y = le.transform(y)
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=(0.5 * delta))
if numerical_features is not None:
n_numerical = len(numerical_features)
feat_indices = np.random.choice(n_numerical, ceil(n_numerical * feat_delta), replace=False)
feat_indices = np.array(numerical_features)[feat_indices]
else:
feat_indices = np.random.choice(x.shape[1], ceil(x.shape[1] * feat_delta), replace=False)
other_features = list(set(range(x.shape[1])) - set(feat_indices))
x_train_other = x_train[:, other_features]
x_train_numerical = x_train[:, feat_indices]
x_test_other = x_test[:, other_features]
x_test_numerical = x_test[:, feat_indices]
classifier = SklearnClassifier(model=model, clip_values=(0, np.max(x_train_numerical)))
# Train the ART classifier
classifier.fit(x_train_numerical, y_train)
# Evaluate the ART classifier on benign test examples
predictions = classifier.predict(x_test_numerical)
accuracy = np.sum(np.argmax(predictions, axis=1) == y_test) / len(y_test)
print("Accuracy on benign test examples: {}%".format(accuracy * 100))
# Generate adversarial test examples
if attack_type == 'zoo':
attack = ZooAttack(
classifier=classifier,
confidence=0.0,
targeted=False,
learning_rate=1e-1,
max_iter=10,
binary_search_steps=10,
initial_const=1e-3,
abort_early=True,
use_resize=False,
use_importance=False,
nb_parallel=x_test_numerical.shape[1],
batch_size=1,
variable_h=0.01,
)
elif attack_type == 'boundary':
attack = BoundaryAttack(classifier, targeted=False, epsilon=0.02, max_iter=20, num_trial=10)
elif attack_type == 'hop-skip-jump':
attack = HopSkipJump(classifier,
targeted=False,
norm=2,
max_iter=20,
max_eval=10,
init_eval=9,
init_size=10)
x_adv = attack.generate(x=x_test_numerical, y=y_test)
# Evaluate the ART classifier on adversarial test examples
predictions_adv = classifier.predict(x_adv)
accuracy = np.sum(np.argmax(predictions_adv, axis=1) == y_test) / len(y_test)
print("Accuracy on adversarial test examples: {}%".format(accuracy * 100))
print("Max difference: {}".format(np.max(np.abs(x_test_numerical - x_adv) / x_test_numerical)))
x_final = np.zeros_like(x)
x_final[:, feat_indices] = np.vstack([x_train_numerical, x_adv])
x_final[:, other_features] = np.vstack([x_train_other, x_test_other])
y_final = np.concatenate([y_train, y_test], axis=0)
y_final = le.inverse_transform(y_final)
adv_indices = list(range(len(y_train), len(y)))
return x_final, y_final, adv_indices, feat_indices
def swap_random_features(x, corruption_probability=0.2):
p = [corruption_probability, 1 - corruption_probability]
(n_samples, n_features) = x.shape
corrupt_decisions = np.random.choice(['to_corrupt', 'ok'], size=n_samples, p=p)
corrupt_indices = np.where(corrupt_decisions == 'to_corrupt')[0]
features_to_switch = np.random.choice(range(n_features), size=2, replace=False)
tmp = x[corrupt_indices, features_to_switch[0]]
x[corrupt_indices, features_to_switch[0]] = x[corrupt_indices, features_to_switch[1]]
x[corrupt_indices, features_to_switch[1]] = tmp
return x
|
[
"numpy.sum",
"numpy.abs",
"numpy.argmax",
"sklearn.model_selection.train_test_split",
"numpy.floor",
"numpy.clip",
"numpy.mean",
"numpy.exp",
"numpy.random.normal",
"numpy.round",
"numpy.unique",
"numpy.zeros_like",
"art.attacks.ZooAttack",
"numpy.transpose",
"sklearn.preprocessing.LabelEncoder",
"art.attacks.HopSkipJump",
"numpy.apply_along_axis",
"numpy.max",
"numpy.random.choice",
"collections.Counter",
"numpy.repeat",
"sklearn.ensemble.RandomForestClassifier",
"numpy.vectorize",
"numpy.ceil",
"math.ceil",
"numpy.median",
"numpy.hstack",
"numpy.min",
"imblearn.over_sampling.SMOTE",
"numpy.squeeze",
"art.attacks.BoundaryAttack",
"imblearn.over_sampling.ADASYN",
"numpy.delete",
"numpy.vstack",
"numpy.concatenate",
"numpy.quantile",
"numpy.log",
"imblearn.under_sampling.NearMiss",
"numpy.zeros",
"numpy.where",
"numpy.array"
] |
[((1021, 1053), 'numpy.unique', 'np.unique', (['y'], {'return_counts': '(True)'}), '(y, return_counts=True)\n', (1030, 1053), True, 'import numpy as np\n'), ((1355, 1381), 'numpy.vectorize', 'np.vectorize', (['rand_labeler'], {}), '(rand_labeler)\n', (1367, 1381), True, 'import numpy as np\n'), ((1602, 1634), 'numpy.unique', 'np.unique', (['y'], {'return_counts': '(True)'}), '(y, return_counts=True)\n', (1611, 1634), True, 'import numpy as np\n'), ((2790, 2823), 'numpy.delete', 'np.delete', (['x', 'del_indices'], {'axis': '(0)'}), '(x, del_indices, axis=0)\n', (2799, 2823), True, 'import numpy as np\n'), ((2832, 2865), 'numpy.delete', 'np.delete', (['y', 'del_indices'], {'axis': '(0)'}), '(y, del_indices, axis=0)\n', (2841, 2865), True, 'import numpy as np\n'), ((2992, 3004), 'numpy.unique', 'np.unique', (['y'], {}), '(y)\n', (3001, 3004), True, 'import numpy as np\n'), ((3475, 3512), 'numpy.mean', 'np.mean', (['x[:, shift_features]'], {'axis': '(0)'}), '(x[:, shift_features], axis=0)\n', (3482, 3512), True, 'import numpy as np\n'), ((3611, 3639), 'numpy.quantile', 'np.quantile', (['distance', 'gamma'], {}), '(distance, gamma)\n', (3622, 3639), True, 'import numpy as np\n'), ((3663, 3674), 'numpy.log', 'np.log', (['(0.5)'], {}), '(0.5)\n', (3669, 3674), True, 'import numpy as np\n'), ((3769, 3821), 'numpy.exp', 'np.exp', (['(ln_prob_keep_far / gamma_quantile * distance)'], {}), '(ln_prob_keep_far / gamma_quantile * distance)\n', (3775, 3821), True, 'import numpy as np\n'), ((4126, 4144), 'numpy.unique', 'np.unique', (['x[:, f]'], {}), '(x[:, f])\n', (4135, 4144), True, 'import numpy as np\n'), ((4336, 4354), 'numpy.unique', 'np.unique', (['x[:, f]'], {}), '(x[:, f])\n', (4345, 4354), True, 'import numpy as np\n'), ((4579, 4596), 'numpy.median', 'np.median', (['values'], {}), '(values)\n', (4588, 4596), True, 'import numpy as np\n'), ((5039, 5105), 'numpy.random.choice', 'np.random.choice', (["['keep', 'remove']"], {'size': 'n_smaller', 'p': '[p, 1 - p]'}), "(['keep', 'remove'], size=n_smaller, p=[p, 1 - p])\n", (5055, 5105), True, 'import numpy as np\n'), ((5511, 5565), 'numpy.hstack', 'np.hstack', (['[keep_smaller_indices, keep_larger_indices]'], {}), '([keep_smaller_indices, keep_larger_indices])\n', (5520, 5565), True, 'import numpy as np\n'), ((6942, 6974), 'math.ceil', 'ceil', (['(0.5 * unique_rows.shape[0])'], {}), '(0.5 * unique_rows.shape[0])\n', (6946, 6974), False, 'from math import ceil\n'), ((7078, 7120), 'numpy.zeros', 'np.zeros', (['unique_rows.shape[0]'], {'dtype': 'bool'}), '(unique_rows.shape[0], dtype=bool)\n', (7086, 7120), True, 'import numpy as np\n'), ((7973, 8039), 'numpy.random.choice', 'np.random.choice', (["['keep', 'remove']"], {'size': 'n_smaller', 'p': '[p, 1 - p]'}), "(['keep', 'remove'], size=n_smaller, p=[p, 1 - p])\n", (7989, 8039), True, 'import numpy as np\n'), ((8445, 8499), 'numpy.hstack', 'np.hstack', (['[keep_smaller_indices, keep_larger_indices]'], {}), '([keep_smaller_indices, keep_larger_indices])\n', (8454, 8499), True, 'import numpy as np\n'), ((10309, 10381), 'numpy.random.normal', 'np.random.normal', (['(0)', '(noise_amt / normalization)', '(x.shape[0], x.shape[1])'], {}), '(0, noise_amt / normalization, (x.shape[0], x.shape[1]))\n', (10325, 10381), True, 'import numpy as np\n'), ((10872, 10889), 'numpy.min', 'np.min', (['x'], {'axis': '(0)'}), '(x, axis=0)\n', (10878, 10889), True, 'import numpy as np\n'), ((10903, 10920), 'numpy.max', 'np.max', (['x'], {'axis': '(0)'}), '(x, axis=0)\n', (10909, 10920), True, 'import numpy as np\n'), ((11020, 11053), 'numpy.transpose', 'np.transpose', (['indices[np.newaxis]'], {}), '(indices[np.newaxis])\n', (11032, 11053), True, 'import numpy as np\n'), ((11508, 11593), 'numpy.random.normal', 'np.random.normal', (['(0)', '(noise_amt / normalization)', '(x_mod.shape[0], x_mod.shape[1])'], {}), '(0, noise_amt / normalization, (x_mod.shape[0], x_mod.shape[1])\n )\n', (11524, 11593), True, 'import numpy as np\n'), ((12379, 12412), 'numpy.transpose', 'np.transpose', (['indices[np.newaxis]'], {}), '(indices[np.newaxis])\n', (12391, 12412), True, 'import numpy as np\n'), ((12865, 12902), 'numpy.median', 'np.median', (['x[:, feat_indices]'], {'axis': '(0)'}), '(x[:, feat_indices], axis=0)\n', (12874, 12902), True, 'import numpy as np\n'), ((12922, 12960), 'numpy.repeat', 'np.repeat', (['med', 'x_mod.shape[0]'], {'axis': '(0)'}), '(med, x_mod.shape[0], axis=0)\n', (12931, 12960), True, 'import numpy as np\n'), ((17261, 17273), 'numpy.unique', 'np.unique', (['y'], {}), '(y)\n', (17270, 17273), True, 'import numpy as np\n'), ((17643, 17699), 'imblearn.under_sampling.NearMiss', 'NearMiss', ([], {'version': '(2)', 'sampling_strategy': 'sampling_strategy'}), '(version=2, sampling_strategy=sampling_strategy)\n', (17651, 17699), False, 'from imblearn.under_sampling import NearMiss\n'), ((18697, 18721), 'sklearn.ensemble.RandomForestClassifier', 'RandomForestClassifier', ([], {}), '()\n', (18719, 18721), False, 'from sklearn.ensemble import RandomForestClassifier\n'), ((19083, 19111), 'sklearn.preprocessing.LabelEncoder', 'preprocessing.LabelEncoder', ([], {}), '()\n', (19109, 19111), False, 'from sklearn import preprocessing\n'), ((19202, 19247), 'sklearn.model_selection.train_test_split', 'train_test_split', (['x', 'y'], {'test_size': '(0.5 * delta)'}), '(x, y, test_size=0.5 * delta)\n', (19218, 19247), False, 'from sklearn.model_selection import train_test_split\n'), ((21756, 21772), 'numpy.zeros_like', 'np.zeros_like', (['x'], {}), '(x)\n', (21769, 21772), True, 'import numpy as np\n'), ((21804, 21841), 'numpy.vstack', 'np.vstack', (['[x_train_numerical, x_adv]'], {}), '([x_train_numerical, x_adv])\n', (21813, 21841), True, 'import numpy as np\n'), ((21875, 21915), 'numpy.vstack', 'np.vstack', (['[x_train_other, x_test_other]'], {}), '([x_train_other, x_test_other])\n', (21884, 21915), True, 'import numpy as np\n'), ((21931, 21972), 'numpy.concatenate', 'np.concatenate', (['[y_train, y_test]'], {'axis': '(0)'}), '([y_train, y_test], axis=0)\n', (21945, 21972), True, 'import numpy as np\n'), ((22308, 22367), 'numpy.random.choice', 'np.random.choice', (["['to_corrupt', 'ok']"], {'size': 'n_samples', 'p': 'p'}), "(['to_corrupt', 'ok'], size=n_samples, p=p)\n", (22324, 22367), True, 'import numpy as np\n'), ((778, 813), 'numpy.where', 'np.where', (['(labels != label_to_change)'], {}), '(labels != label_to_change)\n', (786, 813), True, 'import numpy as np\n'), ((840, 873), 'numpy.random.choice', 'np.random.choice', (['allowed_indices'], {}), '(allowed_indices)\n', (856, 873), True, 'import numpy as np\n'), ((1105, 1140), 'math.ceil', 'ceil', (['(x.shape[0] * perc_max_changes)'], {}), '(x.shape[0] * perc_max_changes)\n', (1109, 1140), False, 'from math import ceil\n'), ((1182, 1221), 'numpy.floor', 'np.floor', (['(perc_max_changes * y.shape[0])'], {}), '(perc_max_changes * y.shape[0])\n', (1190, 1221), True, 'import numpy as np\n'), ((1735, 1749), 'numpy.sum', 'np.sum', (['priors'], {}), '(priors)\n', (1741, 1749), True, 'import numpy as np\n'), ((2601, 2618), 'numpy.where', 'np.where', (['(y == cl)'], {}), '(y == cl)\n', (2609, 2618), True, 'import numpy as np\n'), ((3536, 3588), 'numpy.sum', 'np.sum', (['((x[:, shift_features] - x_mean) ** 2)'], {'axis': '(1)'}), '((x[:, shift_features] - x_mean) ** 2, axis=1)\n', (3542, 3588), True, 'import numpy as np\n'), ((3959, 3993), 'numpy.where', 'np.where', (["(keep_decisions == 'keep')"], {}), "(keep_decisions == 'keep')\n", (3967, 3993), True, 'import numpy as np\n'), ((4820, 4848), 'numpy.where', 'np.where', (['(x[:, f] <= f_split)'], {}), '(x[:, f] <= f_split)\n', (4828, 4848), True, 'import numpy as np\n'), ((4932, 4959), 'numpy.where', 'np.where', (['(x[:, f] > f_split)'], {}), '(x[:, f] > f_split)\n', (4940, 4959), True, 'import numpy as np\n'), ((5323, 5388), 'numpy.random.choice', 'np.random.choice', (["['keep', 'remove']"], {'size': 'n_larger', 'p': '[1 - p, p]'}), "(['keep', 'remove'], size=n_larger, p=[1 - p, p])\n", (5339, 5388), True, 'import numpy as np\n'), ((5781, 5872), 'numpy.hstack', 'np.hstack', (['[keep_smaller_indices, remove_smaller_indices[:to_add], keep_larger_indices]'], {}), '([keep_smaller_indices, remove_smaller_indices[:to_add],\n keep_larger_indices])\n', (5790, 5872), True, 'import numpy as np\n'), ((6310, 6372), 'numpy.random.choice', 'np.random.choice', (['n_numerical', 'n_feat_subsample'], {'replace': '(False)'}), '(n_numerical, n_feat_subsample, replace=False)\n', (6326, 6372), True, 'import numpy as np\n'), ((6537, 6598), 'numpy.random.choice', 'np.random.choice', (['x.shape[1]', 'n_feat_subsample'], {'replace': '(False)'}), '(x.shape[1], n_feat_subsample, replace=False)\n', (6553, 6598), True, 'import numpy as np\n'), ((8257, 8322), 'numpy.random.choice', 'np.random.choice', (["['keep', 'remove']"], {'size': 'n_larger', 'p': '[1 - p, p]'}), "(['keep', 'remove'], size=n_larger, p=[1 - p, p])\n", (8273, 8322), True, 'import numpy as np\n'), ((8715, 8806), 'numpy.hstack', 'np.hstack', (['[keep_smaller_indices, remove_smaller_indices[:to_add], keep_larger_indices]'], {}), '([keep_smaller_indices, remove_smaller_indices[:to_add],\n keep_larger_indices])\n', (8724, 8806), True, 'import numpy as np\n'), ((10412, 10429), 'numpy.min', 'np.min', (['x'], {'axis': '(0)'}), '(x, axis=0)\n', (10418, 10429), True, 'import numpy as np\n'), ((10447, 10464), 'numpy.max', 'np.max', (['x'], {'axis': '(0)'}), '(x, axis=0)\n', (10453, 10464), True, 'import numpy as np\n'), ((10485, 10519), 'numpy.clip', 'np.clip', (['(x + noise)', 'x_mins', 'x_maxs'], {}), '(x + noise, x_mins, x_maxs)\n', (10492, 10519), True, 'import numpy as np\n'), ((10965, 10989), 'math.ceil', 'ceil', (['(x.shape[0] * delta)'], {}), '(x.shape[0] * delta)\n', (10969, 10989), False, 'from math import ceil\n'), ((11871, 11909), 'numpy.ceil', 'np.ceil', (['x_mod[:, int_features_mapped]'], {}), '(x_mod[:, int_features_mapped])\n', (11878, 11909), True, 'import numpy as np\n'), ((12324, 12348), 'math.ceil', 'ceil', (['(x.shape[0] * delta)'], {}), '(x.shape[0] * delta)\n', (12328, 12348), False, 'from math import ceil\n'), ((13879, 13919), 'numpy.concatenate', 'np.concatenate', (['(features, cat_features)'], {}), '((features, cat_features))\n', (13893, 13919), True, 'import numpy as np\n'), ((14261, 14294), 'numpy.random.choice', 'np.random.choice', (['allowed_indices'], {}), '(allowed_indices)\n', (14277, 14294), True, 'import numpy as np\n'), ((14571, 14627), 'numpy.apply_along_axis', 'np.apply_along_axis', (['switch_val', '(1)', 'x[:, group_features]'], {}), '(switch_val, 1, x[:, group_features])\n', (14590, 14627), True, 'import numpy as np\n'), ((14778, 14802), 'math.ceil', 'ceil', (['(x.shape[0] * delta)'], {}), '(x.shape[0] * delta)\n', (14782, 14802), False, 'from math import ceil\n'), ((15030, 15062), 'math.ceil', 'ceil', (['(n_categorical * feat_delta)'], {}), '(n_categorical * feat_delta)\n', (15034, 15062), False, 'from math import ceil\n'), ((16194, 16218), 'math.ceil', 'ceil', (['(x.shape[0] * delta)'], {}), '(x.shape[0] * delta)\n', (16198, 16218), False, 'from math import ceil\n'), ((16472, 16504), 'math.ceil', 'ceil', (['(n_categorical * feat_delta)'], {}), '(n_categorical * feat_delta)\n', (16476, 16504), False, 'from math import ceil\n'), ((17297, 17310), 'numpy.squeeze', 'np.squeeze', (['y'], {}), '(y)\n', (17307, 17310), True, 'import numpy as np\n'), ((18010, 18023), 'numpy.squeeze', 'np.squeeze', (['y'], {}), '(y)\n', (18020, 18023), True, 'import numpy as np\n'), ((19123, 19136), 'numpy.squeeze', 'np.squeeze', (['y'], {}), '(y)\n', (19133, 19136), True, 'import numpy as np\n'), ((20401, 20683), 'art.attacks.ZooAttack', 'ZooAttack', ([], {'classifier': 'classifier', 'confidence': '(0.0)', 'targeted': '(False)', 'learning_rate': '(0.1)', 'max_iter': '(10)', 'binary_search_steps': '(10)', 'initial_const': '(0.001)', 'abort_early': '(True)', 'use_resize': '(False)', 'use_importance': '(False)', 'nb_parallel': 'x_test_numerical.shape[1]', 'batch_size': '(1)', 'variable_h': '(0.01)'}), '(classifier=classifier, confidence=0.0, targeted=False,\n learning_rate=0.1, max_iter=10, binary_search_steps=10, initial_const=\n 0.001, abort_early=True, use_resize=False, use_importance=False,\n nb_parallel=x_test_numerical.shape[1], batch_size=1, variable_h=0.01)\n', (20410, 20683), False, 'from art.attacks import BoundaryAttack, ZooAttack, HopSkipJump\n'), ((22390, 22433), 'numpy.where', 'np.where', (["(corrupt_decisions == 'to_corrupt')"], {}), "(corrupt_decisions == 'to_corrupt')\n", (22398, 22433), True, 'import numpy as np\n'), ((1933, 1966), 'numpy.round', 'np.round', (['(n_samples_label / prior)'], {}), '(n_samples_label / prior)\n', (1941, 1966), True, 'import numpy as np\n'), ((2088, 2117), 'numpy.round', 'np.round', (['(prior * n_to_sample)'], {}), '(prior * n_to_sample)\n', (2096, 2117), True, 'import numpy as np\n'), ((2320, 2374), 'numpy.random.choice', 'np.random.choice', (['cl_indices', 'res_count'], {'replace': '(False)'}), '(cl_indices, res_count, replace=False)\n', (2336, 2374), True, 'import numpy as np\n'), ((5160, 5202), 'numpy.where', 'np.where', (["(keep_smaller_decisions == 'keep')"], {}), "(keep_smaller_decisions == 'keep')\n", (5168, 5202), True, 'import numpy as np\n'), ((6255, 6285), 'math.ceil', 'ceil', (['(n_numerical * feat_delta)'], {}), '(n_numerical * feat_delta)\n', (6259, 6285), False, 'from math import ceil\n'), ((6396, 6424), 'numpy.array', 'np.array', (['numerical_features'], {}), '(numerical_features)\n', (6404, 6424), True, 'import numpy as np\n'), ((6483, 6512), 'math.ceil', 'ceil', (['(x.shape[1] * feat_delta)'], {}), '(x.shape[1] * feat_delta)\n', (6487, 6512), False, 'from math import ceil\n'), ((8094, 8136), 'numpy.where', 'np.where', (["(keep_smaller_decisions == 'keep')"], {}), "(keep_smaller_decisions == 'keep')\n", (8102, 8136), True, 'import numpy as np\n'), ((11193, 11223), 'math.ceil', 'ceil', (['(n_numerical * feat_delta)'], {}), '(n_numerical * feat_delta)\n', (11197, 11223), False, 'from math import ceil\n'), ((11263, 11291), 'numpy.array', 'np.array', (['numerical_features'], {}), '(numerical_features)\n', (11271, 11291), True, 'import numpy as np\n'), ((11368, 11397), 'math.ceil', 'ceil', (['(x.shape[1] * feat_delta)'], {}), '(x.shape[1] * feat_delta)\n', (11372, 11397), False, 'from math import ceil\n'), ((12552, 12582), 'math.ceil', 'ceil', (['(n_numerical * feat_delta)'], {}), '(n_numerical * feat_delta)\n', (12556, 12582), False, 'from math import ceil\n'), ((12622, 12650), 'numpy.array', 'np.array', (['numerical_features'], {}), '(numerical_features)\n', (12630, 12650), True, 'import numpy as np\n'), ((12727, 12756), 'math.ceil', 'ceil', (['(x.shape[1] * feat_delta)'], {}), '(x.shape[1] * feat_delta)\n', (12731, 12756), False, 'from math import ceil\n'), ((15965, 15998), 'numpy.random.choice', 'np.random.choice', (['allowed_indices'], {}), '(allowed_indices)\n', (15981, 15998), True, 'import numpy as np\n'), ((19390, 19420), 'math.ceil', 'ceil', (['(n_numerical * feat_delta)'], {}), '(n_numerical * feat_delta)\n', (19394, 19420), False, 'from math import ceil\n'), ((19460, 19488), 'numpy.array', 'np.array', (['numerical_features'], {}), '(numerical_features)\n', (19468, 19488), True, 'import numpy as np\n'), ((19567, 19596), 'math.ceil', 'ceil', (['(x.shape[1] * feat_delta)'], {}), '(x.shape[1] * feat_delta)\n', (19571, 19596), False, 'from math import ceil\n'), ((20891, 20978), 'art.attacks.BoundaryAttack', 'BoundaryAttack', (['classifier'], {'targeted': '(False)', 'epsilon': '(0.02)', 'max_iter': '(20)', 'num_trial': '(10)'}), '(classifier, targeted=False, epsilon=0.02, max_iter=20,\n num_trial=10)\n', (20905, 20978), False, 'from art.attacks import BoundaryAttack, ZooAttack, HopSkipJump\n'), ((2270, 2287), 'numpy.where', 'np.where', (['(y == cl)'], {}), '(y == cl)\n', (2278, 2287), True, 'import numpy as np\n'), ((3853, 3911), 'numpy.random.choice', 'np.random.choice', (["['keep', 'remove']"], {'size': '(1)', 'p': '[p, 1 - p]'}), "(['keep', 'remove'], size=1, p=[p, 1 - p])\n", (3869, 3911), True, 'import numpy as np\n'), ((5445, 5486), 'numpy.where', 'np.where', (["(keep_larger_decisions == 'keep')"], {}), "(keep_larger_decisions == 'keep')\n", (5453, 5486), True, 'import numpy as np\n'), ((5709, 5753), 'numpy.where', 'np.where', (["(keep_smaller_decisions == 'remove')"], {}), "(keep_smaller_decisions == 'remove')\n", (5717, 5753), True, 'import numpy as np\n'), ((6894, 6918), 'numpy.array', 'np.array', (['group_features'], {}), '(group_features)\n', (6902, 6918), True, 'import numpy as np\n'), ((8379, 8420), 'numpy.where', 'np.where', (["(keep_larger_decisions == 'keep')"], {}), "(keep_larger_decisions == 'keep')\n", (8387, 8420), True, 'import numpy as np\n'), ((8643, 8687), 'numpy.where', 'np.where', (["(keep_smaller_decisions == 'remove')"], {}), "(keep_smaller_decisions == 'remove')\n", (8651, 8687), True, 'import numpy as np\n'), ((11962, 11986), 'numpy.squeeze', 'np.squeeze', (['feat_indices'], {}), '(feat_indices)\n', (11972, 11986), True, 'import numpy as np\n'), ((11996, 12020), 'numpy.squeeze', 'np.squeeze', (['feat_indices'], {}), '(feat_indices)\n', (12006, 12020), True, 'import numpy as np\n'), ((18276, 18334), 'imblearn.over_sampling.SMOTE', 'SMOTE', ([], {'sampling_strategy': 'y_counts', 'k_neighbors': 'n_neighbors'}), '(sampling_strategy=y_counts, k_neighbors=n_neighbors)\n', (18281, 18334), False, 'from imblearn.over_sampling import SMOTE, ADASYN\n'), ((19938, 19963), 'numpy.max', 'np.max', (['x_train_numerical'], {}), '(x_train_numerical)\n', (19944, 19963), True, 'import numpy as np\n'), ((20183, 20213), 'numpy.argmax', 'np.argmax', (['predictions'], {'axis': '(1)'}), '(predictions, axis=1)\n', (20192, 20213), True, 'import numpy as np\n'), ((21033, 21137), 'art.attacks.HopSkipJump', 'HopSkipJump', (['classifier'], {'targeted': '(False)', 'norm': '(2)', 'max_iter': '(20)', 'max_eval': '(10)', 'init_eval': '(9)', 'init_size': '(10)'}), '(classifier, targeted=False, norm=2, max_iter=20, max_eval=10,\n init_eval=9, init_size=10)\n', (21044, 21137), False, 'from art.attacks import BoundaryAttack, ZooAttack, HopSkipJump\n'), ((21502, 21536), 'numpy.argmax', 'np.argmax', (['predictions_adv'], {'axis': '(1)'}), '(predictions_adv, axis=1)\n', (21511, 21536), True, 'import numpy as np\n'), ((15457, 15481), 'numpy.array', 'np.array', (['group_features'], {}), '(group_features)\n', (15465, 15481), True, 'import numpy as np\n'), ((16886, 16910), 'numpy.array', 'np.array', (['group_features'], {}), '(group_features)\n', (16894, 16910), True, 'import numpy as np\n'), ((18130, 18150), 'collections.Counter', 'Counter', (['y_resampled'], {}), '(y_resampled)\n', (18137, 18150), False, 'from collections import Counter\n'), ((18449, 18508), 'imblearn.over_sampling.ADASYN', 'ADASYN', ([], {'sampling_strategy': 'y_counts', 'n_neighbors': 'n_neighbors'}), '(sampling_strategy=y_counts, n_neighbors=n_neighbors)\n', (18455, 18508), False, 'from imblearn.over_sampling import SMOTE, ADASYN\n'), ((21686, 21718), 'numpy.abs', 'np.abs', (['(x_test_numerical - x_adv)'], {}), '(x_test_numerical - x_adv)\n', (21692, 21718), True, 'import numpy as np\n')]
|
'''external_drift.py
Classes
-------
ExternalDrift - base class for all external drift objects
ConstantDrift - generic class to apply a constant drift
'''
from abc import ABC, abstractmethod
import numpy as np
__all__ = ['ExternalDrift', 'ConstantDrift']
class ExternalDrift:
'''Base class for all external drift classes
All external drift classes inherit from this class. When subclassing the following
abstract methods need to be implemented:
* `__call__`: calculates the external drift at the given positions
* `parameters`: property returning the drift parameters
'''
def __init__(self):
'''Initialize ExternalDrift
'''
pass
@abstractmethod
def __call__(self, x):
'''Calculate drift from the position and return'''
pass
@property
@abstractmethod
def parameters(self):
'''ExternalDrift parameters
A subclass needs to override this function and retrieve the ExternalDrift parameters from `ExternalDrift.parameters`.
'''
return {}
class ConstantDrift(ExternalDrift):
'''Constant external drift class
'''
def __init__(self, drift_vector):
'''Initialize ConstantDrift
Parameters
----------
drift_vector: ndarray of size Ndim
Constant drift vector
'''
super().__init__()
self.drift_vector = np.array(drift_vector)[np.newaxis]
def __call__(self, x):
'''Calculate drift at the given positions.'''
return self.drift_vector
@property
def parameters(self):
'''ConstantDrift parameters'''
ret = super().parameters
ret.update({
'name': 'ConstantDrift',
'drift_vector': self.drift_vector[0],
})
return ret
|
[
"numpy.array"
] |
[((1399, 1421), 'numpy.array', 'np.array', (['drift_vector'], {}), '(drift_vector)\n', (1407, 1421), True, 'import numpy as np\n')]
|
from pathlib import Path
import pytest
from ai_ct_scans import data_loading
import pydicom
import mock
import numpy as np
@pytest.fixture()
def patient_1_dicom_dir():
return Path(__file__).parent / "fixtures" / "dicom_data" / "1"
@pytest.fixture()
def patched_root_directory(monkeypatch):
patch = mock.MagicMock()
patch.return_value = Path(__file__).parent / "fixtures" / "dicom_data"
monkeypatch.setattr(data_loading, "data_root_directory", patch)
@pytest.fixture()
def dicom_paths(patient_1_dicom_dir, patched_root_directory):
return data_loading.dir_dicom_paths(patient_1_dicom_dir)
def test_paths_retrieved(dicom_paths):
assert len(dicom_paths) > 0
for path in dicom_paths:
assert "I" in path.stem
def test_dicom_can_be_read(dicom_paths):
for path in dicom_paths:
out = pydicom.dcmread(path)
assert out.pixel_array.shape == (384, 512)
def test_dicom_anonymisation(dicom_paths):
for path in dicom_paths:
out = pydicom.dcmread(path)
assert "NAME^NONE" in out.PatientName
def test_data_root_directory_returns_expected_if_local_dir_exists():
expected = Path(__file__).parents[1] / "extra_data" / "data"
out = data_loading.data_root_directory()
assert expected == out
@pytest.fixture()
def first_patient_dir(patched_root_directory):
return data_loading.data_root_directory() / "1"
@pytest.fixture()
def pat_1_abdo_1_scan_loader(first_patient_dir):
root_dir = first_patient_dir / "1" / "Abdo1"
return data_loading.ScanLoader(root_dir)
def test_scan_loader_gets_expected_dicom_paths(pat_1_abdo_1_scan_loader):
assert len(pat_1_abdo_1_scan_loader.dicom_paths) == 2
for i in range(2):
assert pat_1_abdo_1_scan_loader.dicom_paths[i].stem == f"I{i}"
def test_load_2d_array_gets_expected_ndarray_shape(pat_1_abdo_1_scan_loader):
assert pat_1_abdo_1_scan_loader.load_2d_array(1, ignore_rescale=True).shape == (
384,
512,
)
@pytest.fixture()
def loaded_abdo(pat_1_abdo_1_scan_loader):
pat_1_abdo_1_scan_loader.load_scan()
return pat_1_abdo_1_scan_loader
def test_load_scan_gets_expected_shape(loaded_abdo):
assert loaded_abdo.full_scan.shape == (2, 192, 384)
@pytest.fixture()
def patched_mean_axial_thickness(monkeypatch):
patch = mock.MagicMock()
patch.return_value = 1.4
monkeypatch.setattr(data_loading.ScanLoader, "mean_axial_thickness", patch)
def test_load_scan_gets_expected_shape_abnormal_axial_thickness(
pat_1_abdo_1_scan_loader, patched_mean_axial_thickness
):
pat_1_abdo_1_scan_loader.load_scan()
assert pat_1_abdo_1_scan_loader.full_scan.shape == (4, 192, 384)
def test_load_scan_no_rescale_gets_expected_shape(first_patient_dir):
root_dir = first_patient_dir / "1" / "Abdo1"
abdo_scan_loader = data_loading.ScanLoader(root_dir, rescale_on_load=False)
abdo_scan_loader.load_scan()
assert abdo_scan_loader.full_scan.shape == (2, 384, 512)
def test_exception_raised_if_directory_does_not_exist(patched_root_directory):
root_dir = (
Path(__file__).parent
/ "fixtures"
/ "dicom_data_no_scan_1"
/ "1"
/ "1"
/ "Abdo1"
)
with pytest.raises(FileNotFoundError):
data_loading.ScanLoader(root_dir=root_dir)
@pytest.fixture()
def abdo_loader(first_patient_dir):
return data_loading.BodyPartLoader(root_dir=first_patient_dir, body_part="Abdo")
def test_abdo_loader_gets_expected_dicom_paths(abdo_loader):
assert len(abdo_loader.scan_1.dicom_paths) == 2
assert len(abdo_loader.scan_2.dicom_paths) == 2
for i in range(2):
assert abdo_loader.scan_1.dicom_paths[i].stem == f"I{i}"
for i in range(2):
assert abdo_loader.scan_2.dicom_paths[i].stem == f"I{i}"
def test_exception_raised_if_scan_1_does_not_exist(patched_root_directory):
root_dir = Path(__file__).parent / "fixtures" / "dicom_data_no_scan_1" / "1"
with pytest.raises(FileNotFoundError):
data_loading.BodyPartLoader(root_dir=root_dir, body_part="Abdo")
@pytest.fixture()
def patient_loader(patched_root_directory):
root_dir = data_loading.data_root_directory() / "1"
return data_loading.PatientLoader(root_dir=root_dir)
# No need to test both scans as defaulted to one body type for simplicity
# def test_patientloader_gets_abdo_and_thorax_both_scans(patient_loader):
# assert patient_loader.abdo.scan_1.dicom_paths[0].stem == 'I0'
# assert patient_loader.thorax.scan_1.dicom_paths[0].stem == 'I0'
@pytest.fixture()
def multi_patient_loader(patched_root_directory):
return data_loading.MultiPatientLoader()
def test_multipatientloader_gets_expected_patient_paths(multi_patient_loader):
assert multi_patient_loader.patients[0].abdo.scan_1.dicom_paths[0].stem == "I0"
assert multi_patient_loader.patients[1].abdo.scan_1.dicom_paths[0].stem == "I0"
def test_multipatientloader_with_alt_path(tmpdir):
loader = data_loading.MultiPatientLoader(Path(tmpdir))
assert loader.root_dir == Path(tmpdir)
def test_scan_loader_has_float_ndarray_pixel_spacing_after_load_scan(loaded_abdo):
assert len(loaded_abdo.pixel_spacing) == 2
for pixel_space in loaded_abdo.pixel_spacing:
assert isinstance(pixel_space, float)
class TestMemmapping:
"""A class for testing the memory mapping of 3D arrays, and conversion to tensors for the DL pipeline"""
@pytest.fixture()
def abdo_written_memmap(self, loaded_abdo):
loaded_abdo.full_scan_to_memmap()
return loaded_abdo
@pytest.fixture()
def abdo_written_memmap_no_normalise(self, loaded_abdo):
loaded_abdo.full_scan_to_memmap(normalise=False)
return loaded_abdo
@pytest.fixture()
def abdo_loaded_memmap_no_normalise(self, loaded_abdo):
loaded_abdo.load_memmap_and_clear_scan(normalise=False)
return loaded_abdo
def test_scan_loader_can_write_loadable_memmap(
self, abdo_written_memmap_no_normalise
):
abdo_written_memmap_no_normalise.load_full_memmap()
np.testing.assert_array_equal(
abdo_written_memmap_no_normalise.full_scan,
abdo_written_memmap_no_normalise.full_memmap,
)
def test_scan_loader_can_find_memmap_if_not_explicitly_written(
self, abdo_written_memmap_no_normalise
):
abdo_written_memmap_no_normalise.memmap_save_path = None
abdo_written_memmap_no_normalise.full_memmap = None
abdo_written_memmap_no_normalise.load_full_memmap()
np.testing.assert_array_equal(
abdo_written_memmap_no_normalise.full_scan,
abdo_written_memmap_no_normalise.full_memmap,
)
def test_find_memmap_returns_none_if_no_memmaps(
self, abdo_written_memmap, monkeypatch
):
patch = mock.MagicMock()
patch.return_value = []
monkeypatch.setattr(abdo_written_memmap, "_npy_list", patch)
assert abdo_written_memmap._find_memmaps() == []
def test_load_full_memmap_writes_memmap_if_none_found(
self, abdo_written_memmap, monkeypatch
):
abdo_written_memmap.memmap_save_paths = None
patch_find_memmap = mock.MagicMock()
patch_get_memmap_shape = mock.MagicMock()
patch_get_memmap_shape.return_value = [1, 2, 3]
monkeypatch.setattr(
abdo_written_memmap, "_get_memmap_shape", patch_get_memmap_shape
)
monkeypatch.setattr(abdo_written_memmap, "_find_memmaps", patch_find_memmap)
monkeypatch.setattr(
abdo_written_memmap, "full_scan_to_memmap", mock.MagicMock()
)
monkeypatch.setattr(abdo_written_memmap, "load_scan", mock.MagicMock())
monkeypatch.setattr(data_loading.np, "memmap", mock.MagicMock())
abdo_written_memmap.load_full_memmap()
abdo_written_memmap.full_scan_to_memmap.assert_called_once()
abdo_written_memmap.load_scan.assert_called_once()
def test_clear_full_scan_removes_full_scan_from_memory(self, abdo_written_memmap):
abdo_written_memmap.clear_scan()
assert abdo_written_memmap.full_scan is None
@pytest.fixture()
def abdo_loaded_memmap(self, abdo_written_memmap):
abdo_written_memmap.load_memmap_and_clear_scan()
return abdo_written_memmap
def test_load_memmap_and_clear_scan_clears_full_scan(self, abdo_loaded_memmap):
assert abdo_loaded_memmap.full_scan is None
def test_memmap_normalised_by_default(self, abdo_loaded_memmap):
assert abdo_loaded_memmap.full_memmap.min() >= 0.0
assert abdo_loaded_memmap.full_memmap.max() <= 1.0
def test_delete_memmap_deletes_memmap(self, abdo_written_memmap, monkeypatch):
monkeypatch.setattr(data_loading.os, "remove", mock.MagicMock())
abdo_written_memmap.delete_memmap()
assert data_loading.os.remove.call_count > 0
class TestMultiPatientAxialStreamer:
@pytest.fixture()
def streamer(self, patched_root_directory):
return data_loading.MultiPatientAxialStreamer()
def test_stream_next_gets_expected_shape(self, streamer):
out = streamer.stream_next()
assert isinstance(out, np.ndarray)
assert out.shape == (192, 384)
def test_stream_next_twice_gets_different_outputs(self, streamer):
out = [streamer.stream_next() for _ in range(2)]
assert not (out[0] == out[1]).all()
def test_stream_next_thrice_goes_to_second_scan(self, streamer):
out = [streamer.stream_next() for _ in range(3)]
for im in out[1:]:
assert not (out[0] == im).all()
def test_threshold_ensures_a_minimum_maximum(self, streamer):
threshold = 309
out = [streamer.stream_next(threshold=threshold) for _ in range(2)]
for im in out:
assert im.max() >= threshold
@pytest.fixture()
def patch_randint(self, monkeypatch):
patch = mock.MagicMock()
patch.return_value = 1
monkeypatch.setattr(data_loading.np.random, "randint", patch)
# def test_rand_used_to_select_if_random_true(self, streamer, patch_randint):
# streamer.stream_next(random=True)
# assert data_loading.np.random.randint.call_count > 0
def test_reset_indices_sets_to_zero(self, streamer):
streamer.stream_next(random=True)
streamer.reset_indices()
assert streamer.curr_patient_index == 0
assert streamer.curr_body_part_index == 0
assert streamer.curr_scan_num_index == 0
assert streamer.curr_axial_index == 0
|
[
"ai_ct_scans.data_loading.MultiPatientAxialStreamer",
"ai_ct_scans.data_loading.BodyPartLoader",
"pydicom.dcmread",
"ai_ct_scans.data_loading.ScanLoader",
"numpy.testing.assert_array_equal",
"ai_ct_scans.data_loading.dir_dicom_paths",
"ai_ct_scans.data_loading.data_root_directory",
"pytest.fixture",
"pytest.raises",
"pathlib.Path",
"ai_ct_scans.data_loading.PatientLoader",
"ai_ct_scans.data_loading.MultiPatientLoader",
"mock.MagicMock"
] |
[((126, 142), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (140, 142), False, 'import pytest\n'), ((240, 256), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (254, 256), False, 'import pytest\n'), ((473, 489), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (487, 489), False, 'import pytest\n'), ((1273, 1289), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (1287, 1289), False, 'import pytest\n'), ((1392, 1408), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (1406, 1408), False, 'import pytest\n'), ((1980, 1996), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (1994, 1996), False, 'import pytest\n'), ((2231, 2247), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (2245, 2247), False, 'import pytest\n'), ((3298, 3314), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (3312, 3314), False, 'import pytest\n'), ((4057, 4073), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (4071, 4073), False, 'import pytest\n'), ((4522, 4538), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (4536, 4538), False, 'import pytest\n'), ((310, 326), 'mock.MagicMock', 'mock.MagicMock', ([], {}), '()\n', (324, 326), False, 'import mock\n'), ((563, 612), 'ai_ct_scans.data_loading.dir_dicom_paths', 'data_loading.dir_dicom_paths', (['patient_1_dicom_dir'], {}), '(patient_1_dicom_dir)\n', (591, 612), False, 'from ai_ct_scans import data_loading\n'), ((1208, 1242), 'ai_ct_scans.data_loading.data_root_directory', 'data_loading.data_root_directory', ([], {}), '()\n', (1240, 1242), False, 'from ai_ct_scans import data_loading\n'), ((1518, 1551), 'ai_ct_scans.data_loading.ScanLoader', 'data_loading.ScanLoader', (['root_dir'], {}), '(root_dir)\n', (1541, 1551), False, 'from ai_ct_scans import data_loading\n'), ((2307, 2323), 'mock.MagicMock', 'mock.MagicMock', ([], {}), '()\n', (2321, 2323), False, 'import mock\n'), ((2816, 2872), 'ai_ct_scans.data_loading.ScanLoader', 'data_loading.ScanLoader', (['root_dir'], {'rescale_on_load': '(False)'}), '(root_dir, rescale_on_load=False)\n', (2839, 2872), False, 'from ai_ct_scans import data_loading\n'), ((3362, 3435), 'ai_ct_scans.data_loading.BodyPartLoader', 'data_loading.BodyPartLoader', ([], {'root_dir': 'first_patient_dir', 'body_part': '"""Abdo"""'}), "(root_dir=first_patient_dir, body_part='Abdo')\n", (3389, 3435), False, 'from ai_ct_scans import data_loading\n'), ((4185, 4230), 'ai_ct_scans.data_loading.PatientLoader', 'data_loading.PatientLoader', ([], {'root_dir': 'root_dir'}), '(root_dir=root_dir)\n', (4211, 4230), False, 'from ai_ct_scans import data_loading\n'), ((4600, 4633), 'ai_ct_scans.data_loading.MultiPatientLoader', 'data_loading.MultiPatientLoader', ([], {}), '()\n', (4631, 4633), False, 'from ai_ct_scans import data_loading\n'), ((5405, 5421), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (5419, 5421), False, 'import pytest\n'), ((5545, 5561), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (5559, 5561), False, 'import pytest\n'), ((5713, 5729), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (5727, 5729), False, 'import pytest\n'), ((8128, 8144), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (8142, 8144), False, 'import pytest\n'), ((8915, 8931), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (8929, 8931), False, 'import pytest\n'), ((9826, 9842), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (9840, 9842), False, 'import pytest\n'), ((833, 854), 'pydicom.dcmread', 'pydicom.dcmread', (['path'], {}), '(path)\n', (848, 854), False, 'import pydicom\n'), ((994, 1015), 'pydicom.dcmread', 'pydicom.dcmread', (['path'], {}), '(path)\n', (1009, 1015), False, 'import pydicom\n'), ((1348, 1382), 'ai_ct_scans.data_loading.data_root_directory', 'data_loading.data_root_directory', ([], {}), '()\n', (1380, 1382), False, 'from ai_ct_scans import data_loading\n'), ((3210, 3242), 'pytest.raises', 'pytest.raises', (['FileNotFoundError'], {}), '(FileNotFoundError)\n', (3223, 3242), False, 'import pytest\n'), ((3252, 3294), 'ai_ct_scans.data_loading.ScanLoader', 'data_loading.ScanLoader', ([], {'root_dir': 'root_dir'}), '(root_dir=root_dir)\n', (3275, 3294), False, 'from ai_ct_scans import data_loading\n'), ((3947, 3979), 'pytest.raises', 'pytest.raises', (['FileNotFoundError'], {}), '(FileNotFoundError)\n', (3960, 3979), False, 'import pytest\n'), ((3989, 4053), 'ai_ct_scans.data_loading.BodyPartLoader', 'data_loading.BodyPartLoader', ([], {'root_dir': 'root_dir', 'body_part': '"""Abdo"""'}), "(root_dir=root_dir, body_part='Abdo')\n", (4016, 4053), False, 'from ai_ct_scans import data_loading\n'), ((4133, 4167), 'ai_ct_scans.data_loading.data_root_directory', 'data_loading.data_root_directory', ([], {}), '()\n', (4165, 4167), False, 'from ai_ct_scans import data_loading\n'), ((4981, 4993), 'pathlib.Path', 'Path', (['tmpdir'], {}), '(tmpdir)\n', (4985, 4993), False, 'from pathlib import Path\n'), ((5025, 5037), 'pathlib.Path', 'Path', (['tmpdir'], {}), '(tmpdir)\n', (5029, 5037), False, 'from pathlib import Path\n'), ((6056, 6179), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['abdo_written_memmap_no_normalise.full_scan', 'abdo_written_memmap_no_normalise.full_memmap'], {}), '(abdo_written_memmap_no_normalise.full_scan,\n abdo_written_memmap_no_normalise.full_memmap)\n', (6085, 6179), True, 'import numpy as np\n'), ((6527, 6650), 'numpy.testing.assert_array_equal', 'np.testing.assert_array_equal', (['abdo_written_memmap_no_normalise.full_scan', 'abdo_written_memmap_no_normalise.full_memmap'], {}), '(abdo_written_memmap_no_normalise.full_scan,\n abdo_written_memmap_no_normalise.full_memmap)\n', (6556, 6650), True, 'import numpy as np\n'), ((6806, 6822), 'mock.MagicMock', 'mock.MagicMock', ([], {}), '()\n', (6820, 6822), False, 'import mock\n'), ((7176, 7192), 'mock.MagicMock', 'mock.MagicMock', ([], {}), '()\n', (7190, 7192), False, 'import mock\n'), ((7226, 7242), 'mock.MagicMock', 'mock.MagicMock', ([], {}), '()\n', (7240, 7242), False, 'import mock\n'), ((8995, 9035), 'ai_ct_scans.data_loading.MultiPatientAxialStreamer', 'data_loading.MultiPatientAxialStreamer', ([], {}), '()\n', (9033, 9035), False, 'from ai_ct_scans import data_loading\n'), ((9901, 9917), 'mock.MagicMock', 'mock.MagicMock', ([], {}), '()\n', (9915, 9917), False, 'import mock\n'), ((7585, 7601), 'mock.MagicMock', 'mock.MagicMock', ([], {}), '()\n', (7599, 7601), False, 'import mock\n'), ((7674, 7690), 'mock.MagicMock', 'mock.MagicMock', ([], {}), '()\n', (7688, 7690), False, 'import mock\n'), ((7747, 7763), 'mock.MagicMock', 'mock.MagicMock', ([], {}), '()\n', (7761, 7763), False, 'import mock\n'), ((8756, 8772), 'mock.MagicMock', 'mock.MagicMock', ([], {}), '()\n', (8770, 8772), False, 'import mock\n'), ((352, 366), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (356, 366), False, 'from pathlib import Path\n'), ((181, 195), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (185, 195), False, 'from pathlib import Path\n'), ((1148, 1162), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (1152, 1162), False, 'from pathlib import Path\n'), ((3872, 3886), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (3876, 3886), False, 'from pathlib import Path\n'), ((3073, 3087), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (3077, 3087), False, 'from pathlib import Path\n')]
|
import cv2
import numpy as np
def nothing(x):
pass
# for video capture
cap =cv2.VideoCapture(0)
cv2.namedWindow("Tracking")
cv2.createTrackbar("LH","Tracking",0,255,nothing)
cv2.createTrackbar("LS","Tracking",0,255,nothing)
cv2.createTrackbar("LV","Tracking",0,255,nothing)
cv2.createTrackbar("UH","Tracking",255,255,nothing)
cv2.createTrackbar("US","Tracking",255,255,nothing)
cv2.createTrackbar("UV","Tracking",255,255,nothing)
while True:
#frame = cv2.imread('samples/data/smarties.png')
_, frame= cap.read()
hsv =cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)
# from the opencv doc .... if not known WE USE TRACKBARS
#l_b = np.array([110,50,50])
#u_b = np.array([130,255,255])
l_h=cv2.getTrackbarPos("LH","Tracking")
l_s=cv2.getTrackbarPos("LS","Tracking")
l_v=cv2.getTrackbarPos("LV","Tracking")
u_h=cv2.getTrackbarPos("UH","Tracking")
u_s=cv2.getTrackbarPos("US","Tracking")
u_v=cv2.getTrackbarPos("UV","Tracking")
l_b = np.array([l_h,l_s,l_v])
u_b = np.array([u_h,u_s,u_v])
mask = cv2.inRange(hsv,l_b,u_b)
res = cv2.bitwise_and(frame,frame,mask=mask)
cv2.imshow("frame",frame)
cv2.imshow("Mask",mask)
cv2.imshow("res",res)
key =cv2.waitKey(1)
if key ==27:
break
cap.release()
cv2.destroyAllWindows()
|
[
"cv2.createTrackbar",
"cv2.bitwise_and",
"cv2.cvtColor",
"cv2.waitKey",
"cv2.imshow",
"cv2.VideoCapture",
"numpy.array",
"cv2.getTrackbarPos",
"cv2.destroyAllWindows",
"cv2.inRange",
"cv2.namedWindow"
] |
[((83, 102), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (99, 102), False, 'import cv2\n'), ((104, 131), 'cv2.namedWindow', 'cv2.namedWindow', (['"""Tracking"""'], {}), "('Tracking')\n", (119, 131), False, 'import cv2\n'), ((132, 185), 'cv2.createTrackbar', 'cv2.createTrackbar', (['"""LH"""', '"""Tracking"""', '(0)', '(255)', 'nothing'], {}), "('LH', 'Tracking', 0, 255, nothing)\n", (150, 185), False, 'import cv2\n'), ((182, 235), 'cv2.createTrackbar', 'cv2.createTrackbar', (['"""LS"""', '"""Tracking"""', '(0)', '(255)', 'nothing'], {}), "('LS', 'Tracking', 0, 255, nothing)\n", (200, 235), False, 'import cv2\n'), ((232, 285), 'cv2.createTrackbar', 'cv2.createTrackbar', (['"""LV"""', '"""Tracking"""', '(0)', '(255)', 'nothing'], {}), "('LV', 'Tracking', 0, 255, nothing)\n", (250, 285), False, 'import cv2\n'), ((282, 337), 'cv2.createTrackbar', 'cv2.createTrackbar', (['"""UH"""', '"""Tracking"""', '(255)', '(255)', 'nothing'], {}), "('UH', 'Tracking', 255, 255, nothing)\n", (300, 337), False, 'import cv2\n'), ((334, 389), 'cv2.createTrackbar', 'cv2.createTrackbar', (['"""US"""', '"""Tracking"""', '(255)', '(255)', 'nothing'], {}), "('US', 'Tracking', 255, 255, nothing)\n", (352, 389), False, 'import cv2\n'), ((386, 441), 'cv2.createTrackbar', 'cv2.createTrackbar', (['"""UV"""', '"""Tracking"""', '(255)', '(255)', 'nothing'], {}), "('UV', 'Tracking', 255, 255, nothing)\n", (404, 441), False, 'import cv2\n'), ((1329, 1352), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (1350, 1352), False, 'import cv2\n'), ((543, 581), 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_BGR2HSV'], {}), '(frame, cv2.COLOR_BGR2HSV)\n', (555, 581), False, 'import cv2\n'), ((733, 769), 'cv2.getTrackbarPos', 'cv2.getTrackbarPos', (['"""LH"""', '"""Tracking"""'], {}), "('LH', 'Tracking')\n", (751, 769), False, 'import cv2\n'), ((777, 813), 'cv2.getTrackbarPos', 'cv2.getTrackbarPos', (['"""LS"""', '"""Tracking"""'], {}), "('LS', 'Tracking')\n", (795, 813), False, 'import cv2\n'), ((821, 857), 'cv2.getTrackbarPos', 'cv2.getTrackbarPos', (['"""LV"""', '"""Tracking"""'], {}), "('LV', 'Tracking')\n", (839, 857), False, 'import cv2\n'), ((870, 906), 'cv2.getTrackbarPos', 'cv2.getTrackbarPos', (['"""UH"""', '"""Tracking"""'], {}), "('UH', 'Tracking')\n", (888, 906), False, 'import cv2\n'), ((914, 950), 'cv2.getTrackbarPos', 'cv2.getTrackbarPos', (['"""US"""', '"""Tracking"""'], {}), "('US', 'Tracking')\n", (932, 950), False, 'import cv2\n'), ((958, 994), 'cv2.getTrackbarPos', 'cv2.getTrackbarPos', (['"""UV"""', '"""Tracking"""'], {}), "('UV', 'Tracking')\n", (976, 994), False, 'import cv2\n'), ((1009, 1034), 'numpy.array', 'np.array', (['[l_h, l_s, l_v]'], {}), '([l_h, l_s, l_v])\n', (1017, 1034), True, 'import numpy as np\n'), ((1043, 1068), 'numpy.array', 'np.array', (['[u_h, u_s, u_v]'], {}), '([u_h, u_s, u_v])\n', (1051, 1068), True, 'import numpy as np\n'), ((1083, 1109), 'cv2.inRange', 'cv2.inRange', (['hsv', 'l_b', 'u_b'], {}), '(hsv, l_b, u_b)\n', (1094, 1109), False, 'import cv2\n'), ((1118, 1158), 'cv2.bitwise_and', 'cv2.bitwise_and', (['frame', 'frame'], {'mask': 'mask'}), '(frame, frame, mask=mask)\n', (1133, 1158), False, 'import cv2\n'), ((1167, 1193), 'cv2.imshow', 'cv2.imshow', (['"""frame"""', 'frame'], {}), "('frame', frame)\n", (1177, 1193), False, 'import cv2\n'), ((1197, 1221), 'cv2.imshow', 'cv2.imshow', (['"""Mask"""', 'mask'], {}), "('Mask', mask)\n", (1207, 1221), False, 'import cv2\n'), ((1225, 1247), 'cv2.imshow', 'cv2.imshow', (['"""res"""', 'res'], {}), "('res', res)\n", (1235, 1247), False, 'import cv2\n'), ((1266, 1280), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (1277, 1280), False, 'import cv2\n')]
|
from __future__ import print_function
import os
from skimage.transform import resize
from skimage.io import imsave
import numpy as np
import pdb
from skimage.io import imsave, imread
import cv2
#import pylab
import imageio
#import matplotlib.pyplot as plt
import params
from get_resUnet import *
#from get_model import *
from natsort import natsorted
from os.path import splitext
#from keras.utils import plot_model
#import pylab as plt
from gen_data import load_image,random_batch,test_batch,load_images,plot_images,load_test_image
from params import *
from skimage.io import imsave, imread
from skimage.io import imsave
#set the source directory here
from skimage.draw import ellipse
from skimage.measure import label, regionprops
import csv
def findcenters2(img):
#img=(img>0.2).astype(np.float)
match_pxls = np.where(img > 0.9)
B = np.zeros_like(img).astype(np.float)
B[match_pxls] = 1
img=B
img=(img).astype(np.uint8)
#img=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
temp=img
label_img = label(img)
regions = regionprops(label_img)
coorinates=[]
detection =0
# fig, ax = plt.subplots()
# ax.imshow(img, cmap=plt.cm.gray)
temp_area=0
for props in regions:
y0, x0 = props.centroid
if props.area >=temp_area and temp_area==0:
coorinates.append((y0,x0))
temp_area=props.area
detection=1
elif props.area >=temp_area:
coorinates[0]=(y0,x0)
temp_area=props.area
return coorinates,detection
def predict_for_image(i,files,data_path,pred_dir,framestat,model,writer,save_result=True):
imtest=os.path.join(data_path,files[i])
imtest,infos=load_test_image([imtest])
pred = model.predict(imtest, batch_size=1,verbose=0)
imtest= (imtest*255.).astype(np.uint8)
imtest = np.array(np.squeeze(imtest),dtype= np.uint8)
pred =np.squeeze(pred)
base=os.path.splitext(files[i])[0]
# y_pred_f = (pred>0.5).flatten()
# if sum(y_pred_f)==0:
# detection=0
# else:
# detection=1
pred =cv2.resize(pred,( infos[0][1],infos[0][0]),interpolation=cv2.INTER_CUBIC)
temp_coord=[]
temp_coord,detection=findcenters2(pred)
imtest =cv2.resize(imtest,( infos[0][1],infos[0][0]),interpolation=cv2.INTER_CUBIC)
path=os.path.join(pred_dir,base+'_mask'+'.png')
pred=np.clip(pred, 0, 1).astype(np.float)
im_pred = np.array(255*pred,dtype=np.uint8)
rgb_mask_pred = cv2.cvtColor(im_pred,cv2.COLOR_GRAY2RGB)
rgb_mask_pred[:,:,1:2] = 0*rgb_mask_pred[:,:,1:2]
heatmap = im_pred
imtest= (np.squeeze(imtest)*255).astype(np.uint8)
#
draw_img = cv2.addWeighted(rgb_mask_pred,0.2,imtest,1,0)
for props in temp_coord:
cv2.circle(draw_img, (int(props[1]),int(props[0])), 7, (0, 0, 1), -1)
framestat.append(i+1)
framestat.append(detection)
framestat.append(props[0] )
framestat.append(props[1] )
pred_conf=pred[pred>0.2]
framestat.append(max(0,pred_conf[np.nonzero(pred_conf)].mean()))
if len(temp_coord)==0:
framestat.append(i+1)
framestat.append( 0 )
framestat.append(0)
framestat.append( 0 )
pred_conf=pred[pred>0.05]
framestat.append(1-max(0,pred_conf[np.nonzero(pred_conf)].mean()) )
#pdb.set_trace()
if save_result:
#pdb.set_trace()
image = cv2.cvtColor((imtest*255).astype('uint8'), cv2.COLOR_RGB2BGR);
output = np.zeros((infos[0][0],infos[0][1]*3, 3), dtype='uint8')
output[0:infos[0][0],0:infos[0][1],:]=cv2.cvtColor((imtest*255).astype('uint8'), cv2.COLOR_RGB2BGR);
output[0:infos[0][0],(infos[0][1]):(2*infos[0][1])]=cv2.cvtColor((imtest*np.dstack([pred]*3)*255).astype('uint8'), cv2.COLOR_RGB2BGR);
output[0:infos[0][0],2*(infos[0][1]):3*(infos[0][1])]=cv2.cvtColor((draw_img*255).astype('uint8'), cv2.COLOR_RGB2BGR);
#imsave(path,draw_img*255 )
# pdb.set_trace()
writer.write(output)
#framestat.append((base,detection,temp_coord))
return framestat
if __name__ == "__main__":
params.init()
params.settings['rotzoom']=0
params.settings['CLAHE']=0
params.settings['OnlyPost']=1
params.settings['crop']=0
params.settings['training']=0
params.settings['lighting']=0
params.settings['perspective']=0
# model =Y10_net()
# filename='Y10_net.hdf5'
#logdirs='%s%s'%(splitext(filename)[0],'logs')
model =YnetResNet(include_top=False, weights='imagenet')
filename='YnetResNetFinal.hdf5'
#model =YnetResNet(include_top=False, weights='imagenet')
#filename='YnetResNetFinal.hdf5'
model.load_weights(filename, by_name=True)
dete_sub ='./detection/'
local_sub='./localize/'
for folder in range(1,19):
folder_name=str(folder)
data_path = os.path.join( '/media/a252/540/ChallengeTest/TestPolyDet',folder_name)
pred_dir=os.path.join( '/media/a252/540/ChallengeTest/Pred',folder_name)
files = [f for f in os.listdir(data_path) if f[-3:] == 'png']
files=natsorted(files, key=lambda y: y.lower())
framestat=[]
# initialize the FourCC, video writer, dimensions of the frame, and
# zeros array
imtest=os.path.join(data_path,files[0])
imtest,infos=load_test_image([imtest])
fourcc = cv2.VideoWriter_fourcc(*"MJPG")
writer = cv2.VideoWriter('Video'+folder_name+'.avi', fourcc, 20.0,(infos[0][1]*3,infos[0][0]))
# cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))
#pdb.set_trace()
for ii in range(len(files)):
predict_for_image(ii,files=files,data_path=data_path,pred_dir=pred_dir,framestat=framestat,model=model,writer=writer,save_result=True)
if ii % 100==0:
print('Video: {0} Done: {1}/{2} images'.format(folder, ii, len(files)))
myFile = open(os.path.join(local_sub)+folder_name+'.csv', 'w')
mydet = open(os.path.join(dete_sub)+folder_name+'.csv', 'w')
#columnTitleRow = "num_frame, detection_output,x_position,y_position, confidence\n"
#myFile.write(columnTitleRow)
for row_min in range(0, int((np.shape(framestat)[0])), 5):
row_max=min(row_min + 5, int((np.shape(framestat)[0])))
row = framestat[row_min:row_max]
frame=str(row[0])
detection=str(row[1])
x_coord=str(row[2])
y_coord=str(row[3])
conf=str(row[4])
#print(row)
myFile.write(frame+';'+detection+';'+x_coord+';'+y_coord+';'+ conf+"\n")
mydet.write(frame+';'+detection+';'+ conf+"\n")
#csv.write(row)
myFile.close()
mydet.close()
writer.release()
|
[
"gen_data.load_test_image",
"cv2.VideoWriter_fourcc",
"numpy.clip",
"numpy.shape",
"skimage.measure.label",
"cv2.VideoWriter",
"os.path.join",
"skimage.measure.regionprops",
"numpy.zeros_like",
"cv2.cvtColor",
"cv2.resize",
"numpy.dstack",
"params.init",
"cv2.addWeighted",
"numpy.squeeze",
"os.listdir",
"numpy.zeros",
"numpy.nonzero",
"numpy.where",
"numpy.array",
"os.path.splitext"
] |
[((825, 844), 'numpy.where', 'np.where', (['(img > 0.9)'], {}), '(img > 0.9)\n', (833, 844), True, 'import numpy as np\n'), ((1042, 1052), 'skimage.measure.label', 'label', (['img'], {}), '(img)\n', (1047, 1052), False, 'from skimage.measure import label, regionprops\n'), ((1067, 1089), 'skimage.measure.regionprops', 'regionprops', (['label_img'], {}), '(label_img)\n', (1078, 1089), False, 'from skimage.measure import label, regionprops\n'), ((1655, 1688), 'os.path.join', 'os.path.join', (['data_path', 'files[i]'], {}), '(data_path, files[i])\n', (1667, 1688), False, 'import os\n'), ((1705, 1730), 'gen_data.load_test_image', 'load_test_image', (['[imtest]'], {}), '([imtest])\n', (1720, 1730), False, 'from gen_data import load_image, random_batch, test_batch, load_images, plot_images, load_test_image\n'), ((1905, 1921), 'numpy.squeeze', 'np.squeeze', (['pred'], {}), '(pred)\n', (1915, 1921), True, 'import numpy as np\n'), ((2090, 2165), 'cv2.resize', 'cv2.resize', (['pred', '(infos[0][1], infos[0][0])'], {'interpolation': 'cv2.INTER_CUBIC'}), '(pred, (infos[0][1], infos[0][0]), interpolation=cv2.INTER_CUBIC)\n', (2100, 2165), False, 'import cv2\n'), ((2239, 2316), 'cv2.resize', 'cv2.resize', (['imtest', '(infos[0][1], infos[0][0])'], {'interpolation': 'cv2.INTER_CUBIC'}), '(imtest, (infos[0][1], infos[0][0]), interpolation=cv2.INTER_CUBIC)\n', (2249, 2316), False, 'import cv2\n'), ((2324, 2371), 'os.path.join', 'os.path.join', (['pred_dir', "(base + '_mask' + '.png')"], {}), "(pred_dir, base + '_mask' + '.png')\n", (2336, 2371), False, 'import os\n'), ((2427, 2463), 'numpy.array', 'np.array', (['(255 * pred)'], {'dtype': 'np.uint8'}), '(255 * pred, dtype=np.uint8)\n', (2435, 2463), True, 'import numpy as np\n'), ((2481, 2522), 'cv2.cvtColor', 'cv2.cvtColor', (['im_pred', 'cv2.COLOR_GRAY2RGB'], {}), '(im_pred, cv2.COLOR_GRAY2RGB)\n', (2493, 2522), False, 'import cv2\n'), ((2674, 2723), 'cv2.addWeighted', 'cv2.addWeighted', (['rgb_mask_pred', '(0.2)', 'imtest', '(1)', '(0)'], {}), '(rgb_mask_pred, 0.2, imtest, 1, 0)\n', (2689, 2723), False, 'import cv2\n'), ((4143, 4156), 'params.init', 'params.init', ([], {}), '()\n', (4154, 4156), False, 'import params\n'), ((1859, 1877), 'numpy.squeeze', 'np.squeeze', (['imtest'], {}), '(imtest)\n', (1869, 1877), True, 'import numpy as np\n'), ((1931, 1957), 'os.path.splitext', 'os.path.splitext', (['files[i]'], {}), '(files[i])\n', (1947, 1957), False, 'import os\n'), ((3506, 3564), 'numpy.zeros', 'np.zeros', (['(infos[0][0], infos[0][1] * 3, 3)'], {'dtype': '"""uint8"""'}), "((infos[0][0], infos[0][1] * 3, 3), dtype='uint8')\n", (3514, 3564), True, 'import numpy as np\n'), ((4878, 4948), 'os.path.join', 'os.path.join', (['"""/media/a252/540/ChallengeTest/TestPolyDet"""', 'folder_name'], {}), "('/media/a252/540/ChallengeTest/TestPolyDet', folder_name)\n", (4890, 4948), False, 'import os\n'), ((4969, 5032), 'os.path.join', 'os.path.join', (['"""/media/a252/540/ChallengeTest/Pred"""', 'folder_name'], {}), "('/media/a252/540/ChallengeTest/Pred', folder_name)\n", (4981, 5032), False, 'import os\n'), ((5294, 5327), 'os.path.join', 'os.path.join', (['data_path', 'files[0]'], {}), '(data_path, files[0])\n', (5306, 5327), False, 'import os\n'), ((5348, 5373), 'gen_data.load_test_image', 'load_test_image', (['[imtest]'], {}), '([imtest])\n', (5363, 5373), False, 'from gen_data import load_image, random_batch, test_batch, load_images, plot_images, load_test_image\n'), ((5391, 5422), 'cv2.VideoWriter_fourcc', 'cv2.VideoWriter_fourcc', (["*'MJPG'"], {}), "(*'MJPG')\n", (5413, 5422), False, 'import cv2\n'), ((5449, 5546), 'cv2.VideoWriter', 'cv2.VideoWriter', (["('Video' + folder_name + '.avi')", 'fourcc', '(20.0)', '(infos[0][1] * 3, infos[0][0])'], {}), "('Video' + folder_name + '.avi', fourcc, 20.0, (infos[0][1] *\n 3, infos[0][0]))\n", (5464, 5546), False, 'import cv2\n'), ((866, 884), 'numpy.zeros_like', 'np.zeros_like', (['img'], {}), '(img)\n', (879, 884), True, 'import numpy as np\n'), ((2376, 2395), 'numpy.clip', 'np.clip', (['pred', '(0)', '(1)'], {}), '(pred, 0, 1)\n', (2383, 2395), True, 'import numpy as np\n'), ((2611, 2629), 'numpy.squeeze', 'np.squeeze', (['imtest'], {}), '(imtest)\n', (2621, 2629), True, 'import numpy as np\n'), ((5062, 5083), 'os.listdir', 'os.listdir', (['data_path'], {}), '(data_path)\n', (5072, 5083), False, 'import os\n'), ((5947, 5970), 'os.path.join', 'os.path.join', (['local_sub'], {}), '(local_sub)\n', (5959, 5970), False, 'import os\n'), ((6017, 6039), 'os.path.join', 'os.path.join', (['dete_sub'], {}), '(dete_sub)\n', (6029, 6039), False, 'import os\n'), ((6240, 6259), 'numpy.shape', 'np.shape', (['framestat'], {}), '(framestat)\n', (6248, 6259), True, 'import numpy as np\n'), ((6312, 6331), 'numpy.shape', 'np.shape', (['framestat'], {}), '(framestat)\n', (6320, 6331), True, 'import numpy as np\n'), ((3039, 3060), 'numpy.nonzero', 'np.nonzero', (['pred_conf'], {}), '(pred_conf)\n', (3049, 3060), True, 'import numpy as np\n'), ((3752, 3773), 'numpy.dstack', 'np.dstack', (['([pred] * 3)'], {}), '([pred] * 3)\n', (3761, 3773), True, 'import numpy as np\n'), ((3293, 3314), 'numpy.nonzero', 'np.nonzero', (['pred_conf'], {}), '(pred_conf)\n', (3303, 3314), True, 'import numpy as np\n')]
|
#
# Copyright 2020 The FLEX Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import math
from typing import Union
import numpy as np
from Crypto.Cipher import AES
from flex.constants import *
class FF1Radix2Encryptor(object):
"""
Implements a special case of FF1 mode specified in NIST Special Publication 800-38G,
where the radix(or base) is 2.
"""
# TODO: support sm4-ff1
def __init__(self, key: bytes, n: int, t: bytes = b'', encrypt_algo: str = CRYPTO_AES):
"""
Init a new FF1Radix2 encryptor.
Args:
key: bytes, secret key for encryption, support key length of 16, 24 or 32 bytes.
n: int, max bit length of input/output(in radix 2).
t: bytes, tweak, length of t should be >= 0 and <= maxTlen.
encrypt_algo: string, symmetric encryption algorithm deployed by encryptor, 'aes' is supported.
"""
if encrypt_algo not in [CRYPTO_AES]:
raise NotImplementedError(f"Encryption algorithm {encrypt_algo} is not supported.")
self.encrypt_algo = encrypt_algo
self.radix = 2
self.key = key
self.n = n
self.T = t
self.T_len = len(t)
self.minlen = math.ceil(math.log(100, self.radix))
self.maxlen = 64
self.iters = 10
self.max_allow_number = self.radix ** self.n - 1
if not self.minlen <= n <= self.maxlen:
raise ValueError(f"Parameter n {n} is out of range, accept value >= {self.minlen} and <= {self.maxlen}. ")
self.ciph = AES.new(self.key, AES.MODE_ECB)
# step 1
self.u = math.floor(self.n // 2)
self.v = self.n - self.u
self.mask_for_B = int(self.v * '1', 2)
# step 3
self.b = math.ceil(math.ceil(self.v * math.log(self.radix, 2)) / 8)
# step 4
self.d = 4 * math.ceil(self.b / 4) + 4
# step 5 + step 6-i(1)
self.len_P = 16
# self.len_Q = self.T_len + ((-self.T_len - self.b - 1) % 16) + 1 + self.b
self.len_Q = 16 * math.ceil((self.T_len + self.b + 1) / 16)
self.PQ = np.zeros((self.len_P + self.len_Q), dtype=np.uint8)
self.PQ[0] = 1
self.PQ[1] = 2
self.PQ[2] = 1
self.PQ[3] = (self.radix >> 16) & 0xff
self.PQ[4] = (self.radix >> 8) & 0xff
self.PQ[5] = self.radix & 0xff
self.PQ[6] = 10
self.PQ[7] = self.u & 0xff
self.PQ[8] = (n >> 24) & 0xff
self.PQ[9] = (n >> 16) & 0xff
self.PQ[10] = (n >> 8) & 0xff
self.PQ[11] = n & 0xff
self.PQ[12] = (self.T_len >> 24) & 0xff
self.PQ[13] = (self.T_len >> 16) & 0xff
self.PQ[14] = (self.T_len >> 8) & 0xff
self.PQ[15] = self.T_len & 0xff
self.PQ[self.len_P: self.len_P + self.T_len] = np.frombuffer(self.T, dtype=np.uint8)
self.PQ_var_index = self.len_P + self.T_len + (-self.T_len - self.b - 1) % 16
self.PQ_m = None
self.radix_vector = np.zeros((16, 2), dtype=np.uint32)
# i is even --> column 0
# i is odd --> column 1
for i in range(math.ceil(self.u / 8)):
self.radix_vector[-i - 1, 0] = (1 << (8 * i))
for i in range(math.ceil(self.v / 8)):
self.radix_vector[-i - 1, 1] = (1 << (8 * i))
self.m = [self.u, self.v]
self.mask_for_c = [int(self.u * '1', 2), int(self.v * '1', 2)]
self.power_for_res = (1 << self.v)
def _encrypt(self, X: np.ndarray) -> np.ndarray:
"""
Encryption on np.uint32 or np.uint64
Args:
X: np.uint32 or np.uint64. Supported shape is (s, 1)
Returns: np.uint32 or np.uint64, same type and shape as X.
"""
s = X.shape[0]
# step 2
A = np.right_shift(X, self.v)
B = np.bitwise_and(X, self.mask_for_B)
self.PQ_m = np.tile(self.PQ, (s, 1))
# step 6
for i in range(10):
# step 6-i-2
self.PQ_m[:, self.PQ_var_index] = i
temp1 = np.frombuffer(B.byteswap().tobytes(), dtype=np.uint8)
self.PQ_m[:, self.PQ_var_index + 1:] = temp1.reshape(s, -1)[:, -self.b:]
# step 6-ii
R = np.zeros((s, 16), dtype=np.uint8)
for j in range(self.PQ_m.shape[1] // 16):
R = self.ciph.encrypt((R ^ self.PQ_m[:, 16 * j:16 * (j + 1)]).tobytes())
R = np.frombuffer(R, dtype=np.uint8).reshape(s, -1)
# step 6-iii
# if n <= 128, len(S) <= R
S = R[:, :self.d]
index = i % 2
# step 6-iv
y = np.matmul(S, self.radix_vector[-self.d:, index])[:, np.newaxis]
# step 6-v
# m = self.m[i % 2]
# step 6-vi, 6-vii
C = np.bitwise_and(A + y, self.mask_for_c[index])
# step 6-viii
A = B
# step 6-ix
B = C
return A * self.power_for_res + B
def _decrypt(self, X):
"""
Decryption on np.uint32 or np.uint64
Args:
X: np.uint32 or np.uint64. Supported shape is (s, 1)
Returns: np.uint32 or np.uint64, same type and shape as X.
"""
s = X.shape[0]
# step 2
A = np.right_shift(X, self.v)
B = np.bitwise_and(X, self.mask_for_B)
self.PQ_m = np.tile(self.PQ, (s, 1))
# step 6
for i in range(9, -1, -1):
# step 6-i-2
self.PQ_m[:, self.PQ_var_index] = i
temp2 = np.frombuffer(A.byteswap().tobytes(), dtype=np.uint8)
self.PQ_m[:, self.PQ_var_index + 1:] = temp2.reshape(s, -1)[:, -self.b:]
# step 6-ii
R = np.zeros((s, 16), dtype=np.uint8)
for j in range(self.PQ_m.shape[1] // 16):
R = self.ciph.encrypt((R ^ self.PQ_m[:, 16 * j:16 * (j + 1)]).tobytes())
R = np.frombuffer(R, dtype=np.uint8).reshape(s, -1)
# step 6-iii
# if n <= 128, len(S) <= R
S = R[:, :self.d]
index = i % 2
# step 6-iv
y = np.matmul(S, self.radix_vector[-self.d:, index])[:, np.newaxis]
# step 6-v
# m = self.m[i % 2]
# step 6-vi, 6-vii
C = np.bitwise_and(B - y, self.mask_for_c[index])
# step 6-viii
B = A
# step 6-ix
A = C
return A * self.power_for_res + B
def encrypt(self, x: Union[int, np.ndarray]) -> Union[int, np.ndarray]:
"""
Args:
x:
Returns:
"""
if isinstance(x, int):
if 0 <= x < 2 ** 32:
x_ndarray = np.array([x], dtype=np.uint32)
elif x < 2 ** 64:
x_ndarray = np.array([x], dtype=np.uint64)
else:
raise ValueError(f"Value of input x: {x} not in [0, 2^64).")
elif isinstance(x, np.ndarray):
x_ndarray = x
else:
raise TypeError(f"Type of input x: {type(x)} not valid.")
if not np.all((x_ndarray >= 0) & (x_ndarray <= self.max_allow_number)):
raise ValueError(f"Value of input x: {x} not allowed.")
x_reshaped = x_ndarray.reshape((x_ndarray.size, 1))
x_en = self._encrypt(x_reshaped)
x_en = x_en.reshape(x_ndarray.size)
if isinstance(x, int):
return int(x_en[0])
return x_en
def decrypt(self, x: Union[int, np.ndarray]) -> Union[int, np.ndarray]:
if isinstance(x, int):
if 0 <= x < 2 ** 32:
x_ndarray = np.array([x], dtype=np.uint32)
elif x < 2 ** 64:
x_ndarray = np.array([x], dtype=np.uint64)
else:
raise ValueError(f"Value of input x: {x} not in [0, 2^64).")
elif isinstance(x, np.ndarray):
x_ndarray = x
else:
raise TypeError(f"Type of input x: {type(x)} not valid.")
if not np.all((x_ndarray >= 0) & (x_ndarray <= self.max_allow_number)):
raise ValueError(f"Value of input x: {x} not allowed.")
x_reshaped = x_ndarray.reshape((x_ndarray.size, 1))
x_de = self._decrypt(x_reshaped)
x_de = x_de.reshape(x_ndarray.size)
if isinstance(x, int):
return int(x_de[0])
return x_de
|
[
"numpy.right_shift",
"math.ceil",
"numpy.frombuffer",
"numpy.zeros",
"math.floor",
"numpy.array",
"Crypto.Cipher.AES.new",
"numpy.bitwise_and",
"numpy.tile",
"numpy.matmul",
"math.log",
"numpy.all"
] |
[((2096, 2127), 'Crypto.Cipher.AES.new', 'AES.new', (['self.key', 'AES.MODE_ECB'], {}), '(self.key, AES.MODE_ECB)\n', (2103, 2127), False, 'from Crypto.Cipher import AES\n'), ((2163, 2186), 'math.floor', 'math.floor', (['(self.n // 2)'], {}), '(self.n // 2)\n', (2173, 2186), False, 'import math\n'), ((2651, 2700), 'numpy.zeros', 'np.zeros', (['(self.len_P + self.len_Q)'], {'dtype': 'np.uint8'}), '(self.len_P + self.len_Q, dtype=np.uint8)\n', (2659, 2700), True, 'import numpy as np\n'), ((3349, 3386), 'numpy.frombuffer', 'np.frombuffer', (['self.T'], {'dtype': 'np.uint8'}), '(self.T, dtype=np.uint8)\n', (3362, 3386), True, 'import numpy as np\n'), ((3528, 3562), 'numpy.zeros', 'np.zeros', (['(16, 2)'], {'dtype': 'np.uint32'}), '((16, 2), dtype=np.uint32)\n', (3536, 3562), True, 'import numpy as np\n'), ((4310, 4335), 'numpy.right_shift', 'np.right_shift', (['X', 'self.v'], {}), '(X, self.v)\n', (4324, 4335), True, 'import numpy as np\n'), ((4348, 4382), 'numpy.bitwise_and', 'np.bitwise_and', (['X', 'self.mask_for_B'], {}), '(X, self.mask_for_B)\n', (4362, 4382), True, 'import numpy as np\n'), ((4404, 4428), 'numpy.tile', 'np.tile', (['self.PQ', '(s, 1)'], {}), '(self.PQ, (s, 1))\n', (4411, 4428), True, 'import numpy as np\n'), ((5798, 5823), 'numpy.right_shift', 'np.right_shift', (['X', 'self.v'], {}), '(X, self.v)\n', (5812, 5823), True, 'import numpy as np\n'), ((5836, 5870), 'numpy.bitwise_and', 'np.bitwise_and', (['X', 'self.mask_for_B'], {}), '(X, self.mask_for_B)\n', (5850, 5870), True, 'import numpy as np\n'), ((5892, 5916), 'numpy.tile', 'np.tile', (['self.PQ', '(s, 1)'], {}), '(self.PQ, (s, 1))\n', (5899, 5916), True, 'import numpy as np\n'), ((1774, 1799), 'math.log', 'math.log', (['(100)', 'self.radix'], {}), '(100, self.radix)\n', (1782, 1799), False, 'import math\n'), ((2591, 2632), 'math.ceil', 'math.ceil', (['((self.T_len + self.b + 1) / 16)'], {}), '((self.T_len + self.b + 1) / 16)\n', (2600, 2632), False, 'import math\n'), ((3651, 3672), 'math.ceil', 'math.ceil', (['(self.u / 8)'], {}), '(self.u / 8)\n', (3660, 3672), False, 'import math\n'), ((3756, 3777), 'math.ceil', 'math.ceil', (['(self.v / 8)'], {}), '(self.v / 8)\n', (3765, 3777), False, 'import math\n'), ((4748, 4781), 'numpy.zeros', 'np.zeros', (['(s, 16)'], {'dtype': 'np.uint8'}), '((s, 16), dtype=np.uint8)\n', (4756, 4781), True, 'import numpy as np\n'), ((5324, 5369), 'numpy.bitwise_and', 'np.bitwise_and', (['(A + y)', 'self.mask_for_c[index]'], {}), '(A + y, self.mask_for_c[index])\n', (5338, 5369), True, 'import numpy as np\n'), ((6243, 6276), 'numpy.zeros', 'np.zeros', (['(s, 16)'], {'dtype': 'np.uint8'}), '((s, 16), dtype=np.uint8)\n', (6251, 6276), True, 'import numpy as np\n'), ((6818, 6863), 'numpy.bitwise_and', 'np.bitwise_and', (['(B - y)', 'self.mask_for_c[index]'], {}), '(B - y, self.mask_for_c[index])\n', (6832, 6863), True, 'import numpy as np\n'), ((7618, 7681), 'numpy.all', 'np.all', (['((x_ndarray >= 0) & (x_ndarray <= self.max_allow_number))'], {}), '((x_ndarray >= 0) & (x_ndarray <= self.max_allow_number))\n', (7624, 7681), True, 'import numpy as np\n'), ((8531, 8594), 'numpy.all', 'np.all', (['((x_ndarray >= 0) & (x_ndarray <= self.max_allow_number))'], {}), '((x_ndarray >= 0) & (x_ndarray <= self.max_allow_number))\n', (8537, 8594), True, 'import numpy as np\n'), ((2400, 2421), 'math.ceil', 'math.ceil', (['(self.b / 4)'], {}), '(self.b / 4)\n', (2409, 2421), False, 'import math\n'), ((5156, 5204), 'numpy.matmul', 'np.matmul', (['S', 'self.radix_vector[-self.d:, index]'], {}), '(S, self.radix_vector[-self.d:, index])\n', (5165, 5204), True, 'import numpy as np\n'), ((6650, 6698), 'numpy.matmul', 'np.matmul', (['S', 'self.radix_vector[-self.d:, index]'], {}), '(S, self.radix_vector[-self.d:, index])\n', (6659, 6698), True, 'import numpy as np\n'), ((7237, 7267), 'numpy.array', 'np.array', (['[x]'], {'dtype': 'np.uint32'}), '([x], dtype=np.uint32)\n', (7245, 7267), True, 'import numpy as np\n'), ((8150, 8180), 'numpy.array', 'np.array', (['[x]'], {'dtype': 'np.uint32'}), '([x], dtype=np.uint32)\n', (8158, 8180), True, 'import numpy as np\n'), ((7326, 7356), 'numpy.array', 'np.array', (['[x]'], {'dtype': 'np.uint64'}), '([x], dtype=np.uint64)\n', (7334, 7356), True, 'import numpy as np\n'), ((8239, 8269), 'numpy.array', 'np.array', (['[x]'], {'dtype': 'np.uint64'}), '([x], dtype=np.uint64)\n', (8247, 8269), True, 'import numpy as np\n'), ((2331, 2354), 'math.log', 'math.log', (['self.radix', '(2)'], {}), '(self.radix, 2)\n', (2339, 2354), False, 'import math\n'), ((4945, 4977), 'numpy.frombuffer', 'np.frombuffer', (['R'], {'dtype': 'np.uint8'}), '(R, dtype=np.uint8)\n', (4958, 4977), True, 'import numpy as np\n'), ((6440, 6472), 'numpy.frombuffer', 'np.frombuffer', (['R'], {'dtype': 'np.uint8'}), '(R, dtype=np.uint8)\n', (6453, 6472), True, 'import numpy as np\n')]
|
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 13 10:40:43 2020
@author: Código desarrollado en clase de EDP (USA - Maestría en Matemáticas Aplicadas)
"""
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-np.pi,np.pi,500)
plt.grid()
k2 = (2/np.pi)-(4/np.pi)*((1/3)*np.cos(2*x))
k3 = (2/np.pi)-(4/np.pi)*(((1/3)*np.cos(2*x))+(1/15)*np.cos(4*x))
k4 = (2/np.pi)-(4/np.pi)*(((1/3)*np.cos(2*x))+(1/15)*np.cos(4*x))+(1/35)*np.cos(6*x)
k5 = (2/np.pi)-(4/np.pi)*(((1/3)*np.cos(2*x))+(1/15)*np.cos(4*x))+(1/35)*np.cos(6*x)+(1/63)*np.cos(8*x)
k6 = (2/np.pi)-(4/np.pi)*(((1/3)*np.cos(2*x))+(1/15)*np.cos(4*x))+(1/35)*np.cos(6*x)+(1/63)*np.cos(8*x)+(1/99)*np.cos(10*x)
plt.plot(x,k2,"-b",label="k=2")
plt.plot(x,k3,"-r",label="k=3")
plt.plot(x,k4,"r--",label="k=4")
plt.plot(x,k5,"b--",label="k=5")
plt.plot(x,k6,"g--",label="k=6")
plt.legend(loc="below left")
#-------------------------------
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-np.pi,np.pi,100)
a0 = (16*np.pi**5)/15
d = (np.pi**2)*(k**2)-3
e = 3*np.pi*k*np.cos(np.pi*k)
c = 16/np.pi
f = np.cos(k*x)
for k in range(1,100):
y = (a0/2)+c*(((d+e)*f)/k**5)
plt.plot(x,2*y)
|
[
"matplotlib.pyplot.plot",
"matplotlib.pyplot.legend",
"numpy.cos",
"numpy.linspace",
"matplotlib.pyplot.grid"
] |
[((211, 242), 'numpy.linspace', 'np.linspace', (['(-np.pi)', 'np.pi', '(500)'], {}), '(-np.pi, np.pi, 500)\n', (222, 242), True, 'import numpy as np\n'), ((241, 251), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (249, 251), True, 'import matplotlib.pyplot as plt\n'), ((676, 710), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'k2', '"""-b"""'], {'label': '"""k=2"""'}), "(x, k2, '-b', label='k=2')\n", (684, 710), True, 'import matplotlib.pyplot as plt\n'), ((708, 742), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'k3', '"""-r"""'], {'label': '"""k=3"""'}), "(x, k3, '-r', label='k=3')\n", (716, 742), True, 'import matplotlib.pyplot as plt\n'), ((740, 775), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'k4', '"""r--"""'], {'label': '"""k=4"""'}), "(x, k4, 'r--', label='k=4')\n", (748, 775), True, 'import matplotlib.pyplot as plt\n'), ((773, 808), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'k5', '"""b--"""'], {'label': '"""k=5"""'}), "(x, k5, 'b--', label='k=5')\n", (781, 808), True, 'import matplotlib.pyplot as plt\n'), ((806, 841), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'k6', '"""g--"""'], {'label': '"""k=6"""'}), "(x, k6, 'g--', label='k=6')\n", (814, 841), True, 'import matplotlib.pyplot as plt\n'), ((839, 867), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""below left"""'}), "(loc='below left')\n", (849, 867), True, 'import matplotlib.pyplot as plt\n'), ((956, 987), 'numpy.linspace', 'np.linspace', (['(-np.pi)', 'np.pi', '(100)'], {}), '(-np.pi, np.pi, 100)\n', (967, 987), True, 'import numpy as np\n'), ((1080, 1093), 'numpy.cos', 'np.cos', (['(k * x)'], {}), '(k * x)\n', (1086, 1093), True, 'import numpy as np\n'), ((1155, 1173), 'matplotlib.pyplot.plot', 'plt.plot', (['x', '(2 * y)'], {}), '(x, 2 * y)\n', (1163, 1173), True, 'import matplotlib.pyplot as plt\n'), ((1046, 1063), 'numpy.cos', 'np.cos', (['(np.pi * k)'], {}), '(np.pi * k)\n', (1052, 1063), True, 'import numpy as np\n'), ((436, 449), 'numpy.cos', 'np.cos', (['(6 * x)'], {}), '(6 * x)\n', (442, 449), True, 'import numpy as np\n'), ((540, 553), 'numpy.cos', 'np.cos', (['(8 * x)'], {}), '(8 * x)\n', (546, 553), True, 'import numpy as np\n'), ((663, 677), 'numpy.cos', 'np.cos', (['(10 * x)'], {}), '(10 * x)\n', (669, 677), True, 'import numpy as np\n'), ((284, 297), 'numpy.cos', 'np.cos', (['(2 * x)'], {}), '(2 * x)\n', (290, 297), True, 'import numpy as np\n'), ((521, 534), 'numpy.cos', 'np.cos', (['(6 * x)'], {}), '(6 * x)\n', (527, 534), True, 'import numpy as np\n'), ((644, 657), 'numpy.cos', 'np.cos', (['(8 * x)'], {}), '(8 * x)\n', (650, 657), True, 'import numpy as np\n'), ((330, 343), 'numpy.cos', 'np.cos', (['(2 * x)'], {}), '(2 * x)\n', (336, 343), True, 'import numpy as np\n'), ((350, 363), 'numpy.cos', 'np.cos', (['(4 * x)'], {}), '(4 * x)\n', (356, 363), True, 'import numpy as np\n'), ((625, 638), 'numpy.cos', 'np.cos', (['(6 * x)'], {}), '(6 * x)\n', (631, 638), True, 'import numpy as np\n'), ((396, 409), 'numpy.cos', 'np.cos', (['(2 * x)'], {}), '(2 * x)\n', (402, 409), True, 'import numpy as np\n'), ((416, 429), 'numpy.cos', 'np.cos', (['(4 * x)'], {}), '(4 * x)\n', (422, 429), True, 'import numpy as np\n'), ((481, 494), 'numpy.cos', 'np.cos', (['(2 * x)'], {}), '(2 * x)\n', (487, 494), True, 'import numpy as np\n'), ((501, 514), 'numpy.cos', 'np.cos', (['(4 * x)'], {}), '(4 * x)\n', (507, 514), True, 'import numpy as np\n'), ((585, 598), 'numpy.cos', 'np.cos', (['(2 * x)'], {}), '(2 * x)\n', (591, 598), True, 'import numpy as np\n'), ((605, 618), 'numpy.cos', 'np.cos', (['(4 * x)'], {}), '(4 * x)\n', (611, 618), True, 'import numpy as np\n')]
|
#!/usr/bin/env python3
import importlib
import math
from collections import defaultdict, deque
import numpy as np
import cereal.messaging as messaging
from cereal import car,log,tesla
from common.numpy_fast import interp
from common.params import Params
from common.realtime import Ratekeeper, set_realtime_priority
from selfdrive.config import RADAR_TO_CAMERA
from selfdrive.controls.lib.cluster.fastcluster_py import cluster_points_centroid
from selfdrive.controls.lib.radar_helpers import Cluster, Track
from selfdrive.swaglog import cloudlog
from selfdrive.car.tesla.readconfig import read_config_file,CarSettings
DEBUG = False
RDR_TO_LDR = 0
class KalmanParams():
def __init__(self, dt):
# Lead Kalman Filter params, calculating K from A, C, Q, R requires the control library.
# hardcoding a lookup table to compute K for values of radar_ts between 0.1s and 1.0s
assert dt > .01 and dt < .1, "Radar time step must be between .01s and 0.1s"
self.A = [[1.0, dt], [0.0, 1.0]]
self.C = [1.0, 0.0]
#Q = np.matrix([[10., 0.0], [0.0, 100.]])
#R = 1e3
#K = np.matrix([[ 0.05705578], [ 0.03073241]])
dts = [dt * 0.01 for dt in range(1, 11)]
K0 = [0.12288, 0.14557, 0.16523, 0.18282, 0.19887, 0.21372, 0.22761, 0.24069, 0.2531, 0.26491]
K1 = [0.29666, 0.29331, 0.29043, 0.28787, 0.28555, 0.28342, 0.28144, 0.27958, 0.27783, 0.27617]
self.K = [[interp(dt, dts, K0)], [interp(dt, dts, K1)]]
def laplacian_cdf(x, mu, b):
b = max(b, 1e-4)
return math.exp(-abs(x-mu)/b)
def match_vision_to_cluster(v_ego, lead, clusters):
# match vision point to best statistical cluster match
offset_vision_dist = lead.dist - RADAR_TO_CAMERA
def prob(c):
prob_d = laplacian_cdf(c.dRel, offset_vision_dist, lead.std)
prob_y = laplacian_cdf(c.yRel, lead.relY, lead.relYStd)
prob_v = laplacian_cdf(c.vRel, lead.relVel, lead.relVelStd)
# This is isn't exactly right, but good heuristic
return prob_d * prob_y * prob_v
cluster = max(clusters, key=prob)
# if no 'sane' match is found return -1
# stationary radar points can be false positives
dist_sane = abs(cluster.dRel - offset_vision_dist) < max([(offset_vision_dist)*.25, 5.0])
vel_sane = (abs(cluster.vRel - lead.relVel) < 10) or (v_ego + cluster.vRel > 2)
if dist_sane and vel_sane:
return cluster
else:
return None
def get_rrext_by_trackId(rrext,trackId):
if rrext is not None:
for p in rrext:
if p.trackId == trackId:
return p
return None
def get_lead(v_ego, ready, clusters, lead_msg, low_speed_override=True,use_tesla_radar=False):
# Determine leads, this is where the essential logic happens
if len(clusters) > 0 and ready and lead_msg.prob > .5:
cluster = match_vision_to_cluster(v_ego, lead_msg, clusters)
else:
cluster = None
lead_dict = {'status': False}
lead_dict_ext = {'trackId': 1, 'oClass': 1, 'length': 0.}
# temporary for development purposes: we set the default lead vehicle type to truck (=0) to distinguish between vision (truck) and radar leads (car) in IC
if use_tesla_radar:
lead_dict_ext['oClass'] = 0
if cluster is not None:
lead_dict,lead_dict_ext = cluster.get_RadarState(lead_msg.prob)
elif (cluster is None) and ready and (lead_msg.prob > .5):
lead_dict = Cluster(use_tesla_radar).get_RadarState_from_vision(lead_msg, v_ego)
if low_speed_override:
low_speed_clusters = [c for c in clusters if c.potential_low_speed_lead(v_ego)]
if len(low_speed_clusters) > 0:
closest_cluster = min(low_speed_clusters, key=lambda c: c.dRel)
# Only choose new cluster if it is actually closer than the previous one
if (not lead_dict['status']) or (closest_cluster.dRel < lead_dict['dRel']):
lead_dict,lead_dict_ext = closest_cluster.get_RadarState()
return lead_dict,lead_dict_ext
class RadarD():
def __init__(self, radar_ts, mocked, RI,use_tesla_radar, delay=0):
self.current_time = 0
self.mocked = mocked
self.RI = RI
self.tracks = defaultdict(dict)
self.kalman_params = KalmanParams(radar_ts)
self.last_md_ts = 0
self.last_controls_state_ts = 0
self.active = 0
# v_ego
self.v_ego = 0.
self.v_ego_hist = deque([0], maxlen=delay+1)
self.ready = False
self.icCarLR = None
self.use_tesla_radar = use_tesla_radar
if (RI.TRACK_RIGHT_LANE or RI.TRACK_LEFT_LANE) and self.use_tesla_radar:
self.icCarLR = messaging.pub_sock('uiIcCarLR')
self.lane_width = 3.0
#only used for left and right lanes
self.path_x = np.arange(0.0, 160.0, 0.1) # 160 meters is max
self.dPoly = [0.,0.,0.,0.]
def update(self, frame, sm, rr, has_radar,rrext):
self.current_time = 1e-9*max([sm.logMonoTime[key] for key in sm.logMonoTime.keys()])
if sm.updated['controlsState']:
self.active = sm['controlsState'].active
self.v_ego = sm['controlsState'].vEgo
self.v_ego_hist.append(self.v_ego)
if sm.updated['model']:
self.ready = True
if sm.updated['pathPlan']:
self.lane_width = sm['pathPlan'].laneWidth
self.dPoly = sm['pathPlan'].dPoly
path_y = np.polyval(self.dPoly, self.path_x)
ar_pts = {}
for pt in rr.points:
extpt = get_rrext_by_trackId(rrext,pt.trackId)
ar_pts[pt.trackId] = [pt.dRel + RDR_TO_LDR, pt.yRel, pt.vRel, pt.measured, pt.aRel, pt.yvRel, extpt.objectClass, extpt.length, pt.trackId+2, extpt.movingState]
# *** remove missing points from meta data ***
for ids in list(self.tracks.keys()):
if ids not in ar_pts:
self.tracks.pop(ids, None)
# *** compute the tracks ***
for ids in ar_pts:
rpt = ar_pts[ids]
# align v_ego by a fixed time to align it with the radar measurement
v_lead = rpt[2] + self.v_ego_hist[0]
# distance relative to path
d_path = np.sqrt(np.amin((self.path_x - rpt[0]) ** 2 + (path_y - rpt[1]) ** 2))
# add sign
d_path *= np.sign(rpt[1] - np.interp(rpt[0], self.path_x, path_y))
# create the track if it doesn't exist or it's a new track
if ids not in self.tracks:
self.tracks[ids] = Track(v_lead, self.kalman_params)
self.tracks[ids].update(rpt[0], rpt[1], rpt[2], rpt[3], rpt[4],rpt[5],rpt[6],rpt[7],rpt[8],rpt[9], d_path, self.v_ego,self.use_tesla_radar)
idens = list(sorted(self.tracks.keys()))
track_pts = list([self.tracks[iden].get_key_for_cluster() for iden in idens])
# If we have multiple points, cluster them
if len(track_pts) > 1:
cluster_idxs = cluster_points_centroid(track_pts, 2.5)
clusters = [None] * (max(cluster_idxs) + 1)
for idx in range(len(track_pts)):
cluster_i = cluster_idxs[idx]
if clusters[cluster_i] is None:
clusters[cluster_i] = Cluster(self.use_tesla_radar)
clusters[cluster_i].add(self.tracks[idens[idx]])
elif len(track_pts) == 1:
# FIXME: cluster_point_centroid hangs forever if len(track_pts) == 1
cluster_idxs = [0]
clusters = [Cluster(self.use_tesla_radar)]
clusters[0].add(self.tracks[idens[0]])
else:
clusters = []
# if a new point, reset accel to the rest of the cluster
for idx in range(len(track_pts)):
if self.tracks[idens[idx]].cnt <= 1:
aLeadK = clusters[cluster_idxs[idx]].aLeadK
aLeadTau = clusters[cluster_idxs[idx]].aLeadTau
self.tracks[idens[idx]].reset_a_lead(aLeadK, aLeadTau)
### START REVIEW SECTION
#################################################################
#BB For Tesla integration we will also track Left and Right lanes
#################################################################
if (self.RI.TRACK_RIGHT_LANE or self.RI.TRACK_LEFT_LANE) and self.use_tesla_radar:
datrl = tesla.ICCarsLR.new_message()
datrl.v1Type = int(0)
datrl.v1Dx = float(0.)
datrl.v1Vrel = float(0.)
datrl.v1Dy = float(0.)
datrl.v1Id = int(0)
datrl.v2Type = int(0)
datrl.v2Dx = float(0.)
datrl.v2Vrel = float(0.)
datrl.v2Dy = float(0.)
datrl.v2Id = int(0)
datrl.v3Type = int(0)
datrl.v3Dx = float(0.)
datrl.v3Vrel = float(0.)
datrl.v3Dy = float(0.)
datrl.v3Id = int(0)
datrl.v4Type = int(0)
datrl.v4Dx = float(0.)
datrl.v4Vrel = float(0.)
datrl.v4Dy = float(0.)
datrl.v4Id = int(0)
lane_offset = 0.
#LEFT LANE
if self.RI.TRACK_LEFT_LANE and self.use_tesla_radar:
ll_track_pts = np.array([self.tracks[iden].get_key_for_cluster_dy(-self.lane_width) for iden in idens])
# If we have multiple points, cluster them
if len(ll_track_pts) > 1:
ll_cluster_idxs = cluster_points_centroid(ll_track_pts, 2.5)
ll_clusters = [None] * (max(ll_cluster_idxs) + 1)
for idx in range(len(ll_track_pts)):
ll_cluster_i = ll_cluster_idxs[idx]
if ll_clusters[ll_cluster_i] == None:
ll_clusters[ll_cluster_i] = Cluster(self.use_tesla_radar)
ll_clusters[ll_cluster_i].add(self.tracks[idens[idx]])
elif len(ll_track_pts) == 1:
# TODO: why do we need this?
ll_clusters = [Cluster(self.use_tesla_radar)]
ll_clusters[0].add(self.tracks[idens[0]])
else:
ll_clusters = []
if DEBUG:
for i in ll_clusters:
print(i)
# *** extract the lead car ***
ll_lead_clusters = [c for c in ll_clusters
if c.is_potential_lead_dy(self.v_ego,-self.lane_width)]
ll_lead_clusters.sort(key=lambda x: x.dRel)
ll_lead_len = len(ll_lead_clusters)
ll_lead1_truck = (len([c for c in ll_lead_clusters
if c.is_truck(ll_lead_clusters)]) > 0)
# *** extract the second lead from the whole set of leads ***
ll_lead2_clusters = [c for c in ll_lead_clusters
if c.is_potential_lead2(ll_lead_clusters)]
ll_lead2_clusters.sort(key=lambda x: x.dRel)
ll_lead2_len = len(ll_lead2_clusters)
ll_lead2_truck = (len([c for c in ll_lead_clusters
if c.is_truck(ll_lead2_clusters)]) > 0)
# publish data
if ll_lead_len > 0:
datrl.v1Type = int(ll_lead_clusters[0].oClass)
if datrl.v1Type == 1 and ll_lead1_truck:
datrl.v1Type = 0
datrl.v1Dx = float(ll_lead_clusters[0].dRel)
datrl.v1Vrel = float(ll_lead_clusters[0].vRel)
datrl.v1Dy = float(-ll_lead_clusters[0].yRel - lane_offset)
datrl.v1Id = int(ll_lead_clusters[0].track_id % 32)
if ll_lead2_len > 0:
datrl.v2Type = int(ll_lead2_clusters[0].oClass)
if datrl.v2Type == 1 and ll_lead2_truck:
datrl.v2Type = 0
datrl.v2Dx = float(ll_lead2_clusters[0].dRel)
datrl.v2Vrel = float(ll_lead2_clusters[0].vRel)
datrl.v2Dy = float(-ll_lead2_clusters[0].yRel - lane_offset)
datrl.v2Id = int(ll_lead2_clusters[0].track_id % 32)
#RIGHT LANE
if self.RI.TRACK_RIGHT_LANE and self.use_tesla_radar:
rl_track_pts = np.array([self.tracks[iden].get_key_for_cluster_dy(self.lane_width) for iden in idens])
# If we have multiple points, cluster them
if len(rl_track_pts) > 1:
rl_cluster_idxs = cluster_points_centroid(rl_track_pts, 2.5)
rl_clusters = [None] * (max(rl_cluster_idxs) + 1)
for idx in range(len(rl_track_pts)):
rl_cluster_i = rl_cluster_idxs[idx]
if rl_clusters[rl_cluster_i] == None:
rl_clusters[rl_cluster_i] = Cluster(self.use_tesla_radar)
rl_clusters[rl_cluster_i].add(self.tracks[idens[idx]])
elif len(rl_track_pts) == 1:
# TODO: why do we need this?
rl_clusters = [Cluster(self.use_tesla_radar)]
rl_clusters[0].add(self.tracks[idens[0]])
else:
rl_clusters = []
if DEBUG:
for i in rl_clusters:
print(i)
# *** extract the lead car ***
rl_lead_clusters = [c for c in rl_clusters
if c.is_potential_lead_dy(self.v_ego,self.lane_width)]
rl_lead_clusters.sort(key=lambda x: x.dRel)
rl_lead_len = len(rl_lead_clusters)
rl_lead1_truck = (len([c for c in rl_lead_clusters
if c.is_truck(rl_lead_clusters)]) > 0)
# *** extract the second lead from the whole set of leads ***
rl_lead2_clusters = [c for c in rl_lead_clusters
if c.is_potential_lead2(rl_lead_clusters)]
rl_lead2_clusters.sort(key=lambda x: x.dRel)
rl_lead2_len = len(rl_lead2_clusters)
rl_lead2_truck = (len([c for c in rl_lead_clusters
if c.is_truck(rl_lead2_clusters)]) > 0)
# publish data
if rl_lead_len > 0:
datrl.v3Type = int(rl_lead_clusters[0].oClass)
if datrl.v3Type == 1 and rl_lead1_truck:
datrl.v3Type = 0
datrl.v3Dx = float(rl_lead_clusters[0].dRel)
datrl.v3Vrel = float(rl_lead_clusters[0].vRel)
datrl.v3Dy = float(-rl_lead_clusters[0].yRel+ lane_offset)
datrl.v3Id = int(rl_lead_clusters[0].track_id % 32)
if rl_lead2_len > 0:
datrl.v4Type = int(rl_lead2_clusters[0].oClass)
if datrl.v4Type == 1 and rl_lead2_truck:
datrl.v4Type = 0
datrl.v4Dx = float(rl_lead2_clusters[0].dRel)
datrl.v4Vrel = float(rl_lead2_clusters[0].vRel)
datrl.v4Dy = float(-rl_lead2_clusters[0].yRel + lane_offset)
datrl.v4Id = int(rl_lead2_clusters[0].track_id % 32)
if (self.RI.TRACK_RIGHT_LANE or self.RI.TRACK_LEFT_LANE) and self.use_tesla_radar:
self.icCarLR.send(datrl.to_bytes())
### END REVIEW SECTION
# *** publish radarState ***
dat = messaging.new_message('radarState')
dat.valid = sm.all_alive_and_valid(service_list=['controlsState', 'model'])
dat.radarState.mdMonoTime = self.last_md_ts
dat.radarState.canMonoTimes = list(rr.canMonoTimes)
dat.radarState.radarErrors = list(rr.errors)
dat.radarState.controlsStateMonoTime = self.last_controls_state_ts
datext = tesla.ICLeads.new_message()
l1x = tesla.TeslaLeadPoint.new_message()
l2x = tesla.TeslaLeadPoint.new_message()
if has_radar:
l1d,l1x = get_lead(self.v_ego, self.ready, clusters, sm['model'].lead, low_speed_override=True,use_tesla_radar=self.use_tesla_radar)
l2d,l2x = get_lead(self.v_ego, self.ready, clusters, sm['model'].leadFuture, low_speed_override=False, use_tesla_radar=self.use_tesla_radar)
dat.radarState.leadOne = l1d
dat.radarState.leadTwo = l2d
datext.lead1trackId = l1x['trackId']
datext.lead1oClass = l1x['oClass']
datext.lead1length = l1x['length']
datext.lead2trackId = l2x['trackId']
datext.lead2oClass = l2x['oClass']
datext.lead2length = l2x['length']
return dat, datext
# fuses camera and radar data for best lead detection
def radard_thread(sm=None, pm=None, can_sock=None):
set_realtime_priority(2)
# wait for stats about the car to come in from controls
cloudlog.info("radard is waiting for CarParams")
CP = car.CarParams.from_bytes(Params().get("CarParams", block=True))
use_tesla_radar = CarSettings().get_value("useTeslaRadar")
mocked = (CP.carName == "mock") or ((CP.carName == "tesla") and not use_tesla_radar)
cloudlog.info("radard got CarParams")
# import the radar from the fingerprint
cloudlog.info("radard is importing %s", CP.carName)
RadarInterface = importlib.import_module('selfdrive.car.%s.radar_interface' % CP.carName).RadarInterface
if can_sock is None:
can_sock = messaging.sub_sock('can')
if sm is None:
sm = messaging.SubMaster(['model', 'controlsState', 'liveParameters', 'pathPlan'])
# *** publish radarState and liveTracks
if pm is None:
pm = messaging.PubMaster(['radarState', 'liveTracks'])
icLeads = messaging.pub_sock('uiIcLeads')
ahbInfo = messaging.pub_sock('ahbInfo')
RI = RadarInterface(CP)
rk = Ratekeeper(1.0 / CP.radarTimeStep, print_delay_threshold=None)
RD = RadarD(CP.radarTimeStep, mocked, RI, use_tesla_radar,RI.delay)
has_radar = not CP.radarOffCan or mocked
last_md_ts = 0.
v_ego = 0.
while 1:
can_strings = messaging.drain_sock_raw(can_sock, wait_for_one=True)
sm.update(0)
if sm.updated['controlsState']:
v_ego = sm['controlsState'].vEgo
rr,rrext,ahbCarDetected = RI.update(can_strings,v_ego)
if rr is None:
continue
dat,datext = RD.update(rk.frame, sm, rr, has_radar, rrext)
dat.radarState.cumLagMs = -rk.remaining*1000.
pm.send('radarState', dat)
icLeads.send(datext.to_bytes())
ahbInfoMsg = tesla.AHBinfo.new_message()
ahbInfoMsg.source = 0
ahbInfoMsg.radarCarDetected = ahbCarDetected
ahbInfoMsg.cameraCarDetected = False
ahbInfo.send(ahbInfoMsg.to_bytes())
# *** publish tracks for UI debugging (keep last) ***
tracks = RD.tracks
dat = messaging.new_message('liveTracks', len(tracks))
for cnt, ids in enumerate(sorted(tracks.keys())):
dat.liveTracks[cnt] = {
"trackId": ids,
"dRel": float(tracks[ids].dRel),
"yRel": float(tracks[ids].yRel),
"vRel": float(tracks[ids].vRel),
}
pm.send('liveTracks', dat)
rk.monitor_time()
def main(sm=None, pm=None, can_sock=None):
radard_thread(sm,pm,can_sock)
if __name__ == "__main__":
main()
|
[
"selfdrive.car.tesla.readconfig.CarSettings",
"numpy.amin",
"selfdrive.controls.lib.radar_helpers.Track",
"cereal.messaging.drain_sock_raw",
"collections.defaultdict",
"numpy.arange",
"common.realtime.set_realtime_priority",
"numpy.interp",
"cereal.tesla.ICCarsLR.new_message",
"collections.deque",
"common.realtime.Ratekeeper",
"cereal.messaging.sub_sock",
"cereal.tesla.ICLeads.new_message",
"selfdrive.swaglog.cloudlog.info",
"numpy.polyval",
"cereal.messaging.SubMaster",
"cereal.messaging.pub_sock",
"cereal.messaging.new_message",
"importlib.import_module",
"common.numpy_fast.interp",
"selfdrive.controls.lib.radar_helpers.Cluster",
"cereal.tesla.TeslaLeadPoint.new_message",
"selfdrive.controls.lib.cluster.fastcluster_py.cluster_points_centroid",
"cereal.tesla.AHBinfo.new_message",
"common.params.Params",
"cereal.messaging.PubMaster"
] |
[((14931, 14955), 'common.realtime.set_realtime_priority', 'set_realtime_priority', (['(2)'], {}), '(2)\n', (14952, 14955), False, 'from common.realtime import Ratekeeper, set_realtime_priority\n'), ((15017, 15065), 'selfdrive.swaglog.cloudlog.info', 'cloudlog.info', (['"""radard is waiting for CarParams"""'], {}), "('radard is waiting for CarParams')\n", (15030, 15065), False, 'from selfdrive.swaglog import cloudlog\n'), ((15287, 15324), 'selfdrive.swaglog.cloudlog.info', 'cloudlog.info', (['"""radard got CarParams"""'], {}), "('radard got CarParams')\n", (15300, 15324), False, 'from selfdrive.swaglog import cloudlog\n'), ((15370, 15421), 'selfdrive.swaglog.cloudlog.info', 'cloudlog.info', (['"""radard is importing %s"""', 'CP.carName'], {}), "('radard is importing %s', CP.carName)\n", (15383, 15421), False, 'from selfdrive.swaglog import cloudlog\n'), ((15943, 16005), 'common.realtime.Ratekeeper', 'Ratekeeper', (['(1.0 / CP.radarTimeStep)'], {'print_delay_threshold': 'None'}), '(1.0 / CP.radarTimeStep, print_delay_threshold=None)\n', (15953, 16005), False, 'from common.realtime import Ratekeeper, set_realtime_priority\n'), ((4006, 4023), 'collections.defaultdict', 'defaultdict', (['dict'], {}), '(dict)\n', (4017, 4023), False, 'from collections import defaultdict, deque\n'), ((4209, 4237), 'collections.deque', 'deque', (['[0]'], {'maxlen': '(delay + 1)'}), '([0], maxlen=delay + 1)\n', (4214, 4237), False, 'from collections import defaultdict, deque\n'), ((4546, 4572), 'numpy.arange', 'np.arange', (['(0.0)', '(160.0)', '(0.1)'], {}), '(0.0, 160.0, 0.1)\n', (4555, 4572), True, 'import numpy as np\n'), ((5128, 5163), 'numpy.polyval', 'np.polyval', (['self.dPoly', 'self.path_x'], {}), '(self.dPoly, self.path_x)\n', (5138, 5163), True, 'import numpy as np\n'), ((13709, 13744), 'cereal.messaging.new_message', 'messaging.new_message', (['"""radarState"""'], {}), "('radarState')\n", (13730, 13744), True, 'import cereal.messaging as messaging\n'), ((14063, 14090), 'cereal.tesla.ICLeads.new_message', 'tesla.ICLeads.new_message', ([], {}), '()\n', (14088, 14090), False, 'from cereal import car, log, tesla\n'), ((14101, 14135), 'cereal.tesla.TeslaLeadPoint.new_message', 'tesla.TeslaLeadPoint.new_message', ([], {}), '()\n', (14133, 14135), False, 'from cereal import car, log, tesla\n'), ((14146, 14180), 'cereal.tesla.TeslaLeadPoint.new_message', 'tesla.TeslaLeadPoint.new_message', ([], {}), '()\n', (14178, 14180), False, 'from cereal import car, log, tesla\n'), ((15441, 15513), 'importlib.import_module', 'importlib.import_module', (["('selfdrive.car.%s.radar_interface' % CP.carName)"], {}), "('selfdrive.car.%s.radar_interface' % CP.carName)\n", (15464, 15513), False, 'import importlib\n'), ((15568, 15593), 'cereal.messaging.sub_sock', 'messaging.sub_sock', (['"""can"""'], {}), "('can')\n", (15586, 15593), True, 'import cereal.messaging as messaging\n'), ((15621, 15698), 'cereal.messaging.SubMaster', 'messaging.SubMaster', (["['model', 'controlsState', 'liveParameters', 'pathPlan']"], {}), "(['model', 'controlsState', 'liveParameters', 'pathPlan'])\n", (15640, 15698), True, 'import cereal.messaging as messaging\n'), ((15768, 15817), 'cereal.messaging.PubMaster', 'messaging.PubMaster', (["['radarState', 'liveTracks']"], {}), "(['radarState', 'liveTracks'])\n", (15787, 15817), True, 'import cereal.messaging as messaging\n'), ((15832, 15863), 'cereal.messaging.pub_sock', 'messaging.pub_sock', (['"""uiIcLeads"""'], {}), "('uiIcLeads')\n", (15850, 15863), True, 'import cereal.messaging as messaging\n'), ((15878, 15907), 'cereal.messaging.pub_sock', 'messaging.pub_sock', (['"""ahbInfo"""'], {}), "('ahbInfo')\n", (15896, 15907), True, 'import cereal.messaging as messaging\n'), ((16181, 16234), 'cereal.messaging.drain_sock_raw', 'messaging.drain_sock_raw', (['can_sock'], {'wait_for_one': '(True)'}), '(can_sock, wait_for_one=True)\n', (16205, 16234), True, 'import cereal.messaging as messaging\n'), ((16628, 16655), 'cereal.tesla.AHBinfo.new_message', 'tesla.AHBinfo.new_message', ([], {}), '()\n', (16653, 16655), False, 'from cereal import car, log, tesla\n'), ((4425, 4456), 'cereal.messaging.pub_sock', 'messaging.pub_sock', (['"""uiIcCarLR"""'], {}), "('uiIcCarLR')\n", (4443, 4456), True, 'import cereal.messaging as messaging\n'), ((6522, 6561), 'selfdrive.controls.lib.cluster.fastcluster_py.cluster_points_centroid', 'cluster_points_centroid', (['track_pts', '(2.5)'], {}), '(track_pts, 2.5)\n', (6545, 6561), False, 'from selfdrive.controls.lib.cluster.fastcluster_py import cluster_points_centroid\n'), ((7764, 7792), 'cereal.tesla.ICCarsLR.new_message', 'tesla.ICCarsLR.new_message', ([], {}), '()\n', (7790, 7792), False, 'from cereal import car, log, tesla\n'), ((15157, 15170), 'selfdrive.car.tesla.readconfig.CarSettings', 'CarSettings', ([], {}), '()\n', (15168, 15170), False, 'from selfdrive.car.tesla.readconfig import read_config_file, CarSettings\n'), ((1392, 1411), 'common.numpy_fast.interp', 'interp', (['dt', 'dts', 'K0'], {}), '(dt, dts, K0)\n', (1398, 1411), False, 'from common.numpy_fast import interp\n'), ((1415, 1434), 'common.numpy_fast.interp', 'interp', (['dt', 'dts', 'K1'], {}), '(dt, dts, K1)\n', (1421, 1434), False, 'from common.numpy_fast import interp\n'), ((5838, 5899), 'numpy.amin', 'np.amin', (['((self.path_x - rpt[0]) ** 2 + (path_y - rpt[1]) ** 2)'], {}), '((self.path_x - rpt[0]) ** 2 + (path_y - rpt[1]) ** 2)\n', (5845, 5899), True, 'import numpy as np\n'), ((6117, 6150), 'selfdrive.controls.lib.radar_helpers.Track', 'Track', (['v_lead', 'self.kalman_params'], {}), '(v_lead, self.kalman_params)\n', (6122, 6150), False, 'from selfdrive.controls.lib.radar_helpers import Cluster, Track\n'), ((8680, 8722), 'selfdrive.controls.lib.cluster.fastcluster_py.cluster_points_centroid', 'cluster_points_centroid', (['ll_track_pts', '(2.5)'], {}), '(ll_track_pts, 2.5)\n', (8703, 8722), False, 'from selfdrive.controls.lib.cluster.fastcluster_py import cluster_points_centroid\n'), ((11236, 11278), 'selfdrive.controls.lib.cluster.fastcluster_py.cluster_points_centroid', 'cluster_points_centroid', (['rl_track_pts', '(2.5)'], {}), '(rl_track_pts, 2.5)\n', (11259, 11278), False, 'from selfdrive.controls.lib.cluster.fastcluster_py import cluster_points_centroid\n'), ((15098, 15106), 'common.params.Params', 'Params', ([], {}), '()\n', (15104, 15106), False, 'from common.params import Params\n'), ((3285, 3309), 'selfdrive.controls.lib.radar_helpers.Cluster', 'Cluster', (['use_tesla_radar'], {}), '(use_tesla_radar)\n', (3292, 3309), False, 'from selfdrive.controls.lib.radar_helpers import Cluster, Track\n'), ((5951, 5989), 'numpy.interp', 'np.interp', (['rpt[0]', 'self.path_x', 'path_y'], {}), '(rpt[0], self.path_x, path_y)\n', (5960, 5989), True, 'import numpy as np\n'), ((6763, 6792), 'selfdrive.controls.lib.radar_helpers.Cluster', 'Cluster', (['self.use_tesla_radar'], {}), '(self.use_tesla_radar)\n', (6770, 6792), False, 'from selfdrive.controls.lib.radar_helpers import Cluster, Track\n'), ((6998, 7027), 'selfdrive.controls.lib.radar_helpers.Cluster', 'Cluster', (['self.use_tesla_radar'], {}), '(self.use_tesla_radar)\n', (7005, 7027), False, 'from selfdrive.controls.lib.radar_helpers import Cluster, Track\n'), ((8962, 8991), 'selfdrive.controls.lib.radar_helpers.Cluster', 'Cluster', (['self.use_tesla_radar'], {}), '(self.use_tesla_radar)\n', (8969, 8991), False, 'from selfdrive.controls.lib.radar_helpers import Cluster, Track\n'), ((9152, 9181), 'selfdrive.controls.lib.radar_helpers.Cluster', 'Cluster', (['self.use_tesla_radar'], {}), '(self.use_tesla_radar)\n', (9159, 9181), False, 'from selfdrive.controls.lib.radar_helpers import Cluster, Track\n'), ((11518, 11547), 'selfdrive.controls.lib.radar_helpers.Cluster', 'Cluster', (['self.use_tesla_radar'], {}), '(self.use_tesla_radar)\n', (11525, 11547), False, 'from selfdrive.controls.lib.radar_helpers import Cluster, Track\n'), ((11708, 11737), 'selfdrive.controls.lib.radar_helpers.Cluster', 'Cluster', (['self.use_tesla_radar'], {}), '(self.use_tesla_radar)\n', (11715, 11737), False, 'from selfdrive.controls.lib.radar_helpers import Cluster, Track\n')]
|
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for string statistics generator."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import absltest
import numpy as np
from tensorflow_data_validation.statistics.generators import string_stats_generator
from tensorflow_data_validation.utils import test_util
from google.protobuf import text_format
from tensorflow_metadata.proto.v0 import schema_pb2
from tensorflow_metadata.proto.v0 import statistics_pb2
class StringStatsGeneratorTest(test_util.CombinerStatsGeneratorTest):
def test_string_stats_generator_single_feature(self):
# input with two batches: first batch has two examples and second batch
# has a single example.
batches = [{'a': np.array([np.array(['xyz']), np.array(['qwe'])])},
{'a': np.array([np.array(['ab'])])}]
expected_result = {
'a': text_format.Parse(
"""
name: 'a'
type: STRING
string_stats {
avg_length: 2.66666666
}
""", statistics_pb2.FeatureNameStatistics())}
generator = string_stats_generator.StringStatsGenerator()
self.assertCombinerOutputEqual(batches, generator, expected_result)
def test_string_stats_generator_with_missing_values(self):
# input with two batches: first batch has three examples and second batch
# has two examples.
batches = [{'a': np.array([np.array(['xyz']), None,
np.array(['qwe'])], dtype=np.object)},
{'a': np.array([np.array(['ab']), None], dtype=np.object)}]
expected_result = {
'a': text_format.Parse(
"""
name: 'a'
type: STRING
string_stats {
avg_length: 2.66666666
}
""", statistics_pb2.FeatureNameStatistics())}
generator = string_stats_generator.StringStatsGenerator()
self.assertCombinerOutputEqual(batches, generator, expected_result)
def test_string_stats_generator_with_multiple_features(self):
# input with two batches: first batch has two examples and second batch
# has a single example.
batches = [{'a': np.array([np.array(['xyz']), np.array(['qwe'])]),
'b': np.array([np.array(['hello', 'world']),
np.array(['foo', 'bar'])])},
{'a': np.array([np.array(['ab'])]),
'b': np.array([np.array(['zzz', 'aaa', 'ddd'])])}]
expected_result = {
'a': text_format.Parse(
"""
name: 'a'
type: STRING
string_stats {
avg_length: 2.66666666
}
""", statistics_pb2.FeatureNameStatistics()),
'b': text_format.Parse(
"""
name: 'b'
type: STRING
string_stats {
avg_length: 3.57142857
}
""", statistics_pb2.FeatureNameStatistics())}
generator = string_stats_generator.StringStatsGenerator()
self.assertCombinerOutputEqual(batches, generator, expected_result)
def test_string_stats_generator_with_missing_feature(self):
# input with two batches: first batch has two examples and second batch
# has a single example.
batches = [{'b': np.array([np.array(['hello', 'world']),
np.array(['foo', 'bar'])])},
{'a': np.array([np.array(['ab', 'xyz', 'qwe'])]),
'b': np.array([np.array(['zzz', 'aaa', 'ddd'])])}]
expected_result = {
'a': text_format.Parse(
"""
name: 'a'
type: STRING
string_stats {
avg_length: 2.66666666
}
""", statistics_pb2.FeatureNameStatistics()),
'b': text_format.Parse(
"""
name: 'b'
type: STRING
string_stats {
avg_length: 3.57142857
}
""", statistics_pb2.FeatureNameStatistics())}
generator = string_stats_generator.StringStatsGenerator()
self.assertCombinerOutputEqual(batches, generator, expected_result)
def test_string_stats_generator_with_one_numeric_feature(self):
# input with two batches: first batch has two examples and second batch
# has a single example.
batches = [{'a': np.array([np.array(['xyz']), np.array(['qwe'])]),
'b': np.array([np.array([1.0, 2.0, 3.0]),
np.array([4.0, 5.0])])},
{'a': np.array([np.array(['ab'])]),
'b': np.array([np.array([5.0, 6.0])])}]
expected_result = {
'a': text_format.Parse(
"""
name: 'a'
type: STRING
string_stats {
avg_length: 2.66666666
}
""", statistics_pb2.FeatureNameStatistics())}
generator = string_stats_generator.StringStatsGenerator()
self.assertCombinerOutputEqual(batches, generator, expected_result)
def test_string_stats_generator_unicode_feature(self):
# input with two batches: first batch has two examples and second batch
# has a single example.
batches = [{'a': np.array([np.array(['xyz']), np.array(['qwe'])],
dtype=np.unicode_)},
{'a': np.array([np.array(['ab'])], dtype=np.unicode_)}]
expected_result = {
'a': text_format.Parse(
"""
name: 'a'
type: STRING
string_stats {
avg_length: 2.66666666
}
""", statistics_pb2.FeatureNameStatistics())}
generator = string_stats_generator.StringStatsGenerator()
self.assertCombinerOutputEqual(batches, generator, expected_result)
def test_string_stats_generator_categorical_feature(self):
# input with two batches: first batch has two examples and second batch
# has a single example.
batches = [{'a': np.array([np.array([123]),
np.array([45])])},
{'a': np.array([np.array([456])])}]
expected_result = {
'a': text_format.Parse(
"""
name: 'a'
type: INT
string_stats {
avg_length: 2.66666666
}
""", statistics_pb2.FeatureNameStatistics())}
schema = text_format.Parse(
"""
feature {
name: "a"
type: INT
int_domain {
is_categorical: true
}
}
""", schema_pb2.Schema())
generator = string_stats_generator.StringStatsGenerator(schema=schema)
self.assertCombinerOutputEqual(batches, generator, expected_result)
def test_string_stats_generator_empty_batch(self):
batches = [{'a': np.array([])}]
expected_result = {}
generator = string_stats_generator.StringStatsGenerator()
self.assertCombinerOutputEqual(batches, generator, expected_result)
def test_string_stats_generator_empty_dict(self):
batches = [{}]
expected_result = {}
generator = string_stats_generator.StringStatsGenerator()
self.assertCombinerOutputEqual(batches, generator, expected_result)
def test_string_stats_generator_empty_list(self):
batches = []
expected_result = {}
generator = string_stats_generator.StringStatsGenerator()
self.assertCombinerOutputEqual(batches, generator, expected_result)
if __name__ == '__main__':
absltest.main()
|
[
"tensorflow_data_validation.statistics.generators.string_stats_generator.StringStatsGenerator",
"absl.testing.absltest.main",
"tensorflow_metadata.proto.v0.statistics_pb2.FeatureNameStatistics",
"numpy.array",
"tensorflow_metadata.proto.v0.schema_pb2.Schema"
] |
[((7974, 7989), 'absl.testing.absltest.main', 'absltest.main', ([], {}), '()\n', (7987, 7989), False, 'from absl.testing import absltest\n'), ((1701, 1746), 'tensorflow_data_validation.statistics.generators.string_stats_generator.StringStatsGenerator', 'string_stats_generator.StringStatsGenerator', ([], {}), '()\n', (1744, 1746), False, 'from tensorflow_data_validation.statistics.generators import string_stats_generator\n'), ((2455, 2500), 'tensorflow_data_validation.statistics.generators.string_stats_generator.StringStatsGenerator', 'string_stats_generator.StringStatsGenerator', ([], {}), '()\n', (2498, 2500), False, 'from tensorflow_data_validation.statistics.generators import string_stats_generator\n'), ((3554, 3599), 'tensorflow_data_validation.statistics.generators.string_stats_generator.StringStatsGenerator', 'string_stats_generator.StringStatsGenerator', ([], {}), '()\n', (3597, 3599), False, 'from tensorflow_data_validation.statistics.generators import string_stats_generator\n'), ((4594, 4639), 'tensorflow_data_validation.statistics.generators.string_stats_generator.StringStatsGenerator', 'string_stats_generator.StringStatsGenerator', ([], {}), '()\n', (4637, 4639), False, 'from tensorflow_data_validation.statistics.generators import string_stats_generator\n'), ((5446, 5491), 'tensorflow_data_validation.statistics.generators.string_stats_generator.StringStatsGenerator', 'string_stats_generator.StringStatsGenerator', ([], {}), '()\n', (5489, 5491), False, 'from tensorflow_data_validation.statistics.generators import string_stats_generator\n'), ((6189, 6234), 'tensorflow_data_validation.statistics.generators.string_stats_generator.StringStatsGenerator', 'string_stats_generator.StringStatsGenerator', ([], {}), '()\n', (6232, 6234), False, 'from tensorflow_data_validation.statistics.generators import string_stats_generator\n'), ((7104, 7162), 'tensorflow_data_validation.statistics.generators.string_stats_generator.StringStatsGenerator', 'string_stats_generator.StringStatsGenerator', ([], {'schema': 'schema'}), '(schema=schema)\n', (7147, 7162), False, 'from tensorflow_data_validation.statistics.generators import string_stats_generator\n'), ((7366, 7411), 'tensorflow_data_validation.statistics.generators.string_stats_generator.StringStatsGenerator', 'string_stats_generator.StringStatsGenerator', ([], {}), '()\n', (7409, 7411), False, 'from tensorflow_data_validation.statistics.generators import string_stats_generator\n'), ((7597, 7642), 'tensorflow_data_validation.statistics.generators.string_stats_generator.StringStatsGenerator', 'string_stats_generator.StringStatsGenerator', ([], {}), '()\n', (7640, 7642), False, 'from tensorflow_data_validation.statistics.generators import string_stats_generator\n'), ((7826, 7871), 'tensorflow_data_validation.statistics.generators.string_stats_generator.StringStatsGenerator', 'string_stats_generator.StringStatsGenerator', ([], {}), '()\n', (7869, 7871), False, 'from tensorflow_data_validation.statistics.generators import string_stats_generator\n'), ((7067, 7086), 'tensorflow_metadata.proto.v0.schema_pb2.Schema', 'schema_pb2.Schema', ([], {}), '()\n', (7084, 7086), False, 'from tensorflow_metadata.proto.v0 import schema_pb2\n'), ((1644, 1682), 'tensorflow_metadata.proto.v0.statistics_pb2.FeatureNameStatistics', 'statistics_pb2.FeatureNameStatistics', ([], {}), '()\n', (1680, 1682), False, 'from tensorflow_metadata.proto.v0 import statistics_pb2\n'), ((2398, 2436), 'tensorflow_metadata.proto.v0.statistics_pb2.FeatureNameStatistics', 'statistics_pb2.FeatureNameStatistics', ([], {}), '()\n', (2434, 2436), False, 'from tensorflow_metadata.proto.v0 import statistics_pb2\n'), ((3266, 3304), 'tensorflow_metadata.proto.v0.statistics_pb2.FeatureNameStatistics', 'statistics_pb2.FeatureNameStatistics', ([], {}), '()\n', (3302, 3304), False, 'from tensorflow_metadata.proto.v0 import statistics_pb2\n'), ((3497, 3535), 'tensorflow_metadata.proto.v0.statistics_pb2.FeatureNameStatistics', 'statistics_pb2.FeatureNameStatistics', ([], {}), '()\n', (3533, 3535), False, 'from tensorflow_metadata.proto.v0 import statistics_pb2\n'), ((4306, 4344), 'tensorflow_metadata.proto.v0.statistics_pb2.FeatureNameStatistics', 'statistics_pb2.FeatureNameStatistics', ([], {}), '()\n', (4342, 4344), False, 'from tensorflow_metadata.proto.v0 import statistics_pb2\n'), ((4537, 4575), 'tensorflow_metadata.proto.v0.statistics_pb2.FeatureNameStatistics', 'statistics_pb2.FeatureNameStatistics', ([], {}), '()\n', (4573, 4575), False, 'from tensorflow_metadata.proto.v0 import statistics_pb2\n'), ((5389, 5427), 'tensorflow_metadata.proto.v0.statistics_pb2.FeatureNameStatistics', 'statistics_pb2.FeatureNameStatistics', ([], {}), '()\n', (5425, 5427), False, 'from tensorflow_metadata.proto.v0 import statistics_pb2\n'), ((6132, 6170), 'tensorflow_metadata.proto.v0.statistics_pb2.FeatureNameStatistics', 'statistics_pb2.FeatureNameStatistics', ([], {}), '()\n', (6168, 6170), False, 'from tensorflow_metadata.proto.v0 import statistics_pb2\n'), ((6833, 6871), 'tensorflow_metadata.proto.v0.statistics_pb2.FeatureNameStatistics', 'statistics_pb2.FeatureNameStatistics', ([], {}), '()\n', (6869, 6871), False, 'from tensorflow_metadata.proto.v0 import statistics_pb2\n'), ((7310, 7322), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (7318, 7322), True, 'import numpy as np\n'), ((1337, 1354), 'numpy.array', 'np.array', (["['xyz']"], {}), "(['xyz'])\n", (1345, 1354), True, 'import numpy as np\n'), ((1356, 1373), 'numpy.array', 'np.array', (["['qwe']"], {}), "(['qwe'])\n", (1364, 1373), True, 'import numpy as np\n'), ((1409, 1425), 'numpy.array', 'np.array', (["['ab']"], {}), "(['ab'])\n", (1417, 1425), True, 'import numpy as np\n'), ((2014, 2031), 'numpy.array', 'np.array', (["['xyz']"], {}), "(['xyz'])\n", (2022, 2031), True, 'import numpy as np\n'), ((2070, 2087), 'numpy.array', 'np.array', (["['qwe']"], {}), "(['qwe'])\n", (2078, 2087), True, 'import numpy as np\n'), ((2140, 2156), 'numpy.array', 'np.array', (["['ab']"], {}), "(['ab'])\n", (2148, 2156), True, 'import numpy as np\n'), ((2773, 2790), 'numpy.array', 'np.array', (["['xyz']"], {}), "(['xyz'])\n", (2781, 2790), True, 'import numpy as np\n'), ((2792, 2809), 'numpy.array', 'np.array', (["['qwe']"], {}), "(['qwe'])\n", (2800, 2809), True, 'import numpy as np\n'), ((2844, 2872), 'numpy.array', 'np.array', (["['hello', 'world']"], {}), "(['hello', 'world'])\n", (2852, 2872), True, 'import numpy as np\n'), ((2905, 2929), 'numpy.array', 'np.array', (["['foo', 'bar']"], {}), "(['foo', 'bar'])\n", (2913, 2929), True, 'import numpy as np\n'), ((2965, 2981), 'numpy.array', 'np.array', (["['ab']"], {}), "(['ab'])\n", (2973, 2981), True, 'import numpy as np\n'), ((3016, 3047), 'numpy.array', 'np.array', (["['zzz', 'aaa', 'ddd']"], {}), "(['zzz', 'aaa', 'ddd'])\n", (3024, 3047), True, 'import numpy as np\n'), ((3870, 3898), 'numpy.array', 'np.array', (["['hello', 'world']"], {}), "(['hello', 'world'])\n", (3878, 3898), True, 'import numpy as np\n'), ((3931, 3955), 'numpy.array', 'np.array', (["['foo', 'bar']"], {}), "(['foo', 'bar'])\n", (3939, 3955), True, 'import numpy as np\n'), ((3991, 4021), 'numpy.array', 'np.array', (["['ab', 'xyz', 'qwe']"], {}), "(['ab', 'xyz', 'qwe'])\n", (3999, 4021), True, 'import numpy as np\n'), ((4056, 4087), 'numpy.array', 'np.array', (["['zzz', 'aaa', 'ddd']"], {}), "(['zzz', 'aaa', 'ddd'])\n", (4064, 4087), True, 'import numpy as np\n'), ((4914, 4931), 'numpy.array', 'np.array', (["['xyz']"], {}), "(['xyz'])\n", (4922, 4931), True, 'import numpy as np\n'), ((4933, 4950), 'numpy.array', 'np.array', (["['qwe']"], {}), "(['qwe'])\n", (4941, 4950), True, 'import numpy as np\n'), ((4985, 5010), 'numpy.array', 'np.array', (['[1.0, 2.0, 3.0]'], {}), '([1.0, 2.0, 3.0])\n', (4993, 5010), True, 'import numpy as np\n'), ((5043, 5063), 'numpy.array', 'np.array', (['[4.0, 5.0]'], {}), '([4.0, 5.0])\n', (5051, 5063), True, 'import numpy as np\n'), ((5099, 5115), 'numpy.array', 'np.array', (["['ab']"], {}), "(['ab'])\n", (5107, 5115), True, 'import numpy as np\n'), ((5150, 5170), 'numpy.array', 'np.array', (['[5.0, 6.0]'], {}), '([5.0, 6.0])\n', (5158, 5170), True, 'import numpy as np\n'), ((5757, 5774), 'numpy.array', 'np.array', (["['xyz']"], {}), "(['xyz'])\n", (5765, 5774), True, 'import numpy as np\n'), ((5776, 5793), 'numpy.array', 'np.array', (["['qwe']"], {}), "(['qwe'])\n", (5784, 5793), True, 'import numpy as np\n'), ((5878, 5894), 'numpy.array', 'np.array', (["['ab']"], {}), "(['ab'])\n", (5886, 5894), True, 'import numpy as np\n'), ((6504, 6519), 'numpy.array', 'np.array', (['[123]'], {}), '([123])\n', (6512, 6519), True, 'import numpy as np\n'), ((6552, 6566), 'numpy.array', 'np.array', (['[45]'], {}), '([45])\n', (6560, 6566), True, 'import numpy as np\n'), ((6602, 6617), 'numpy.array', 'np.array', (['[456]'], {}), '([456])\n', (6610, 6617), True, 'import numpy as np\n')]
|
# ------------------------------------------------------------------------------
# Copyright (c) Microsoft
# Licensed under the MIT License.
# Written by <NAME> (<EMAIL>)
# ------------------------------------------------------------------------------
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import numpy as np
import torchvision
import cv2
from utils.inference import get_max_preds
RED = (0, 0, 255)
GREEN = (0, 255, 0)
DARK_GREEN = (115, 181, 34)
BLUE = (255, 0, 0)
CYAN = (255, 128, 0)
YELLOW = (0, 255, 255)
ORANGE = (0, 165, 255)
PURPLE = (255, 0, 255)
PINK = (180, 105, 255)
BLACK = (0, 0, 0)
# SBC_colors = [ORANGE, RED, CYAN, DARK_GREEN, GREEN, BLUE, YELLOW, PURPLE, PINK]
SBC_colors = [ORANGE, ORANGE, ORANGE, RED, RED, RED, CYAN, CYAN, CYAN]
KPS_colors = [DARK_GREEN, DARK_GREEN, YELLOW, YELLOW, PINK]
subclasses = [BLACK, ORANGE, CYAN, PINK, DARK_GREEN, RED]
def save_batch_image_with_joints(batch_image,
batch_joints,
batch_joints_vis,
file_name,
nrow=8,
padding=2):
'''
batch_image: [batch_size, channel, height, width]
batch_joints: [batch_size, num_joints, 3],
batch_joints_vis: [batch_size, num_joints, 1],
}
'''
# print(file_name)
grid = torchvision.utils.make_grid(batch_image, nrow, padding, True)
ndarr = grid.mul(255).clamp(0, 255).byte().permute(1, 2, 0).cpu().numpy()
ndarr = ndarr.copy()
nmaps = batch_image.size(0)
xmaps = min(nrow, nmaps)
ymaps = int(math.ceil(float(nmaps) / xmaps))
height = int(batch_image.size(2) + padding)
width = int(batch_image.size(3) + padding)
k = 0
for y in range(ymaps):
for x in range(xmaps):
if k >= nmaps:
break
joints = batch_joints[k]
joints_vis = batch_joints_vis[k]
i = 0
for joint, joint_vis in zip(joints, joints_vis):
joint[0] = x * width + padding + joint[0]
joint[1] = y * height + padding + joint[1]
if joint_vis[0]:
cv2.circle(ndarr, (int(joint[0]), int(joint[1])), 2, KPS_colors[i], 2)
i += 1
k = k + 1
cv2.imwrite(file_name, ndarr)
def save_batch_image_with_boxes(batch_image,
batch_boxes,
batch_labels,
file_name,
nrow=2,
padding=2):
'''
batch_image: [batch_size, channel, height, width]
batch_joints: [batch_size, num_joints, 3],
batch_joints_vis: [batch_size, num_joints, 1],
}
'''
# print(file_name)
B, C, H, W = batch_image.size()
grid = torchvision.utils.make_grid(batch_image, nrow, padding, True)
ndarr = grid.mul(255).clamp(0, 255).byte().permute(1, 2, 0).cpu().numpy()
ndarr = ndarr.copy()
nmaps = batch_image.size(0)
xmaps = min(nrow, nmaps)
ymaps = int(math.ceil(float(nmaps) / xmaps))
height = int(batch_image.size(2) + padding)
width = int(batch_image.size(3) + padding)
k = 0
for y in range(ymaps):
for x in range(xmaps):
if k >= nmaps:
break
boxes = batch_boxes[k]
labels = batch_labels[k]
num_box = boxes.shape[0]
i = 0
for n in range(num_box):
lane = boxes[:, 3:][n]
xs = lane[:len(lane) // 2]
ys = lane[len(lane) // 2:]
ys = ys[xs >= 0] * H
xs = xs[xs >= 0] * W
cls = labels[n]
# print(cls)
if (cls > 0 and cls < 10):
for jj, xcoord, ycoord in zip(range(xs.shape[0]), xs, ys):
j_x = x * width + padding + xcoord
j_y = y * height + padding + ycoord
cv2.circle(ndarr, (int(j_x), int(j_y)), 2, subclasses[cls], 10)
i += 1
# exit()
k = k + 1
cv2.imwrite(file_name, ndarr)
def save_batch_image_with_dbs(batch_image,
batch_boxes,
batch_labels,
file_name,
nrow=2,
padding=2):
'''
batch_image: [batch_size, channel, height, width]
batch_joints: [batch_size, num_joints, 3],
batch_joints_vis: [batch_size, num_joints, 1],
}
'''
# print(file_name)
B, C, H, W = batch_image.size()
grid = torchvision.utils.make_grid(batch_image, nrow, padding, True)
ndarr = grid.mul(255).clamp(0, 255).byte().permute(1, 2, 0).cpu().numpy()
ndarr = ndarr.copy()
nmaps = batch_image.size(0)
xmaps = min(nrow, nmaps)
ymaps = int(math.ceil(float(nmaps) / xmaps))
height = int(batch_image.size(2) + padding)
width = int(batch_image.size(3) + padding)
k = 0
for y in range(ymaps):
for x in range(xmaps):
if k >= nmaps:
break
pred = batch_boxes[k].cpu().numpy() # 10 7
labels = batch_labels[k].cpu().numpy() # 10
pred = pred[labels <= 4] # 4 for llamas
num_pred = pred.shape[0]
if num_pred > 0:
for n, lane in enumerate(pred):
# print('pred, lane: {}'.format(lane))
cls = labels[n]
lane = lane[1:]
# lower, upper = lane[0], lane[1]
lower = np.minimum(lane[0], lane[1])
upper = np.maximum(lane[0], lane[1])
upper = 1.
lane = lane[2:]
ys = np.linspace(lower, upper, num=100)
points = np.zeros((len(ys), 2), dtype=np.int32)
points[:, 1] = (ys * H).astype(int)
# Calculate the predicted xs
# points[:, 0] = (np.polyval(lane, ys) * W).astype(int)
# points[:, 0] = ((lane[0] / (ys - lane[1]) + lane[2] + lane[3] * ys - lane[4]) * W).astype(int)
points[:, 0] = ((lane[0] / (ys - lane[1]) ** 2 + lane[2] / (ys - lane[1]) + lane[3] + lane[4] * ys - lane[5])
* W).astype(int)
points = points[(points[:, 0] > 0) & (points[:, 0] < W)]
points[:, 0] += x * width + padding
points[:, 1] += y * height + padding
for current_point, next_point in zip(points[:-1], points[1:]):
cv2.line(ndarr, tuple(current_point), tuple(next_point), color=subclasses[cls], thickness=2)
k = k + 1
# exit()
cv2.imwrite(file_name, ndarr)
def save_batch_heatmaps(batch_image, batch_heatmaps, file_name,
normalize=True):
'''
batch_image: [batch_size, channel, height, width]
batch_heatmaps: ['batch_size, num_joints, height, width]
file_name: saved file name
'''
# print(file_name)
if normalize:
batch_image = batch_image.clone()
min = float(batch_image.min())
max = float(batch_image.max())
batch_image.add_(-min).div_(max - min + 1e-5)
batch_size = batch_heatmaps.size(0)
num_joints = batch_heatmaps.size(1)
heatmap_height = batch_heatmaps.size(2)
heatmap_width = batch_heatmaps.size(3)
grid_image = np.zeros((batch_size*heatmap_height,
(num_joints+1)*heatmap_width,
3),
dtype=np.uint8)
preds, maxvals = get_max_preds(batch_heatmaps.detach().cpu().numpy())
for i in range(batch_size):
image = batch_image[i].mul(255)\
.clamp(0, 255)\
.byte()\
.permute(1, 2, 0)\
.cpu().numpy()
heatmaps = batch_heatmaps[i].mul(255)\
.clamp(0, 255)\
.byte()\
.cpu().numpy()
resized_image = cv2.resize(image,
(int(heatmap_width), int(heatmap_height)))
height_begin = heatmap_height * i
height_end = heatmap_height * (i + 1)
for j in range(num_joints):
cv2.circle(resized_image,
(int(preds[i][j][0]), int(preds[i][j][1])),
1, [0, 0, 255], 1)
heatmap = heatmaps[j, :, :]
colored_heatmap = cv2.applyColorMap(heatmap, cv2.COLORMAP_JET)
masked_image = colored_heatmap*0.7 + resized_image*0.3
cv2.circle(masked_image,
(int(preds[i][j][0]), int(preds[i][j][1])),
1, [0, 0, 255], 1)
width_begin = heatmap_width * (j+1)
width_end = heatmap_width * (j+2)
grid_image[height_begin:height_end, width_begin:width_end, :] = \
masked_image
# grid_image[height_begin:height_end, width_begin:width_end, :] = \
# colored_heatmap*0.7 + resized_image*0.3
grid_image[height_begin:height_end, 0:heatmap_width, :] = resized_image
cv2.imwrite(file_name, grid_image)
def save_debug_images(input, target, output,
prefix):
# save_batch_image_with_joints(
# input, meta['joints'], meta['joints_vis'],
# '{}_gt.jpg'.format(prefix)
# )
#
# save_batch_image_with_joints(
# input, joints_pred, meta['joints_vis'],
# '{}_pred.jpg'.format(prefix)
# )
save_batch_heatmaps(
input, target, '{}_hm_gt.jpg'.format(prefix)
)
save_batch_heatmaps(
input, output, '{}_hm_pred.jpg'.format(prefix)
)
def save_debug_images_training(input, target, output, prefix):
# save_batch_image_with_joints(
# input, joints, joints_vis,
# '{}_gt.jpg'.format(prefix)
# )
# save_batch_image_with_joints(
# input, joints_pred, joints_vis,
# '{}_pred.jpg'.format(prefix)
# )
save_batch_heatmaps(
input, target, '{}_hm_gt.jpg'.format(prefix)
)
save_batch_heatmaps(
input, output, '{}_hm_pred.jpg'.format(prefix)
)
def save_debug_images_joints(input, gt_joints, gt_joints_vis,
joints_pred=None, joints_vis_pred=None, prefix=None):
save_batch_image_with_joints(
input, gt_joints, gt_joints_vis,
'{}_gt.jpg'.format(prefix)
)
save_batch_image_with_joints(
input, joints_pred, gt_joints_vis,
'{}_pred.jpg'.format(prefix)
)
def save_debug_images_boxes(input, tgt_boxes, tgt_labels,
pred_boxes, pred_labels, prefix=None):
save_batch_image_with_boxes(
input, tgt_boxes, tgt_labels,
'{}_gt.jpg'.format(prefix)
)
save_batch_image_with_dbs(
input, pred_boxes, pred_labels,
'{}_pred.jpg'.format(prefix)
)
|
[
"numpy.minimum",
"numpy.maximum",
"cv2.imwrite",
"numpy.zeros",
"torchvision.utils.make_grid",
"numpy.linspace",
"cv2.applyColorMap"
] |
[((1446, 1507), 'torchvision.utils.make_grid', 'torchvision.utils.make_grid', (['batch_image', 'nrow', 'padding', '(True)'], {}), '(batch_image, nrow, padding, True)\n', (1473, 1507), False, 'import torchvision\n'), ((2386, 2415), 'cv2.imwrite', 'cv2.imwrite', (['file_name', 'ndarr'], {}), '(file_name, ndarr)\n', (2397, 2415), False, 'import cv2\n'), ((2924, 2985), 'torchvision.utils.make_grid', 'torchvision.utils.make_grid', (['batch_image', 'nrow', 'padding', '(True)'], {}), '(batch_image, nrow, padding, True)\n', (2951, 2985), False, 'import torchvision\n'), ((4239, 4268), 'cv2.imwrite', 'cv2.imwrite', (['file_name', 'ndarr'], {}), '(file_name, ndarr)\n', (4250, 4268), False, 'import cv2\n'), ((4765, 4826), 'torchvision.utils.make_grid', 'torchvision.utils.make_grid', (['batch_image', 'nrow', 'padding', '(True)'], {}), '(batch_image, nrow, padding, True)\n', (4792, 4826), False, 'import torchvision\n'), ((6939, 6968), 'cv2.imwrite', 'cv2.imwrite', (['file_name', 'ndarr'], {}), '(file_name, ndarr)\n', (6950, 6968), False, 'import cv2\n'), ((7640, 7736), 'numpy.zeros', 'np.zeros', (['(batch_size * heatmap_height, (num_joints + 1) * heatmap_width, 3)'], {'dtype': 'np.uint8'}), '((batch_size * heatmap_height, (num_joints + 1) * heatmap_width, 3),\n dtype=np.uint8)\n', (7648, 7736), True, 'import numpy as np\n'), ((9477, 9511), 'cv2.imwrite', 'cv2.imwrite', (['file_name', 'grid_image'], {}), '(file_name, grid_image)\n', (9488, 9511), False, 'import cv2\n'), ((8793, 8837), 'cv2.applyColorMap', 'cv2.applyColorMap', (['heatmap', 'cv2.COLORMAP_JET'], {}), '(heatmap, cv2.COLORMAP_JET)\n', (8810, 8837), False, 'import cv2\n'), ((5747, 5775), 'numpy.minimum', 'np.minimum', (['lane[0]', 'lane[1]'], {}), '(lane[0], lane[1])\n', (5757, 5775), True, 'import numpy as np\n'), ((5804, 5832), 'numpy.maximum', 'np.maximum', (['lane[0]', 'lane[1]'], {}), '(lane[0], lane[1])\n', (5814, 5832), True, 'import numpy as np\n'), ((5925, 5959), 'numpy.linspace', 'np.linspace', (['lower', 'upper'], {'num': '(100)'}), '(lower, upper, num=100)\n', (5936, 5959), True, 'import numpy as np\n')]
|
# Copyright (c) 2018-2020 Simons Observatory.
# Full license can be found in the top level "LICENSE" file.
"""TOAST interface tools.
This module contains code for interfacing with TOAST data representations.
"""
import os
import sys
import re
import traceback
import numpy as np
# Import so3g first so that it can control the import and monkey-patching
# of spt3g. Then our import of spt3g_core will use whatever has been imported
# by so3g.
import so3g
from spt3g import core as core3g
from toast.dist import Data, distribute_discrete
import toast.qarray as qa
from toast.tod import TOD, Noise
from toast.tod import spt3g_utils as s3utils
from toast.utils import Logger, Environment, memreport
from toast.timing import Timer
from toast.mpi import MPI
from ..core import Hardware
from .toast_frame_utils import frame_to_tod
# FIXME: This CamelCase name is ridiculous in all caps...
class SOTOD(TOD):
"""This class contains the timestream data.
An instance of this class loads a directory of frame files into memory.
Filtering by detector properties is done at construction time.
Args:
path (str): The path to this observation directory.
file_names:
file_nframes:
file_sample_offs:
frame_sizes:
frame_sizes_by_offset:
frame_sample_offs:
detquats:
mpicomm (mpi4py.MPI.Comm): the MPI communicator over which this
observation data is distributed.
detranks (int): The dimension of the process grid in the detector
direction. The MPI communicator size must be evenly divisible
by this number.
all_flavors (bool): Return all signal flavors
"""
def __init__(self, path, file_names, file_nframes, file_sample_offs,
frame_sizes, frame_sizes_by_offset,
frame_sample_offs, detquats,
mpicomm, detranks=1, all_flavors=False):
self._path = path
self._units = None
self._detquats = detquats
self._frame_sizes = frame_sizes
self._frame_sample_offs = frame_sample_offs
self._file_names = file_names
self._file_nframes = file_nframes
self._file_sample_offs = file_sample_offs
self._all_flavors = all_flavors
sampsizes = []
nsamp = 0
for sz in frame_sizes_by_offset.values():
sampsizes.append(sz)
nsamp += sz
# We need to assign a unique integer index to each detector. This
# is used when seeding the streamed RNG in order to simulate
# timestreams. For simplicity, and assuming that detector names
# are not too long, we can convert the detector name to bytes and
# then to an integer.
# FIXME: these numbers will not agree with the ones synthesized
# FIXME: in toast_so_sim.py. Instead, they should be made
# FIXME: part of the hardware model.
self._detindx = {}
for det in detquats.keys():
bdet = det.encode("utf-8")
uid = None
try:
ind = int.from_bytes(bdet, byteorder="little")
uid = int(ind & 0xFFFFFFFF)
except:
raise RuntimeError(
"Cannot convert detector name {} to a unique integer-\
maybe it is too long?".format(det))
self._detindx[det] = uid
# call base class constructor to distribute data
super().__init__(
mpicomm, list(sorted(detquats.keys())), nsamp,
detindx=self._detindx, detranks=detranks,
sampsizes=sampsizes, meta=dict())
# Now that the data distribution is set, read frames into memory.
self.load_frames()
self.get_azel()
return
def get_azel(self):
""" Translate the boresight az/el quaternions into azimuth and
elevation
"""
quats = self.cache.reference("boresight_azel")
theta, phi = qa.to_position(quats)
self._az = (-phi % (2 * np.pi))
self._el = np.pi / 2 - theta
if len(self._az) > 0:
azmin = np.amin(self._az)
azmax = np.amax(self._az)
elmin = np.amin(self._el)
elmax = np.amax(self._el)
else:
azmin = 1000
azmax = -1000
elmin = 1000
elmax = -1000
if self.mpicomm is not None:
azmin = self.mpicomm.allreduce(azmin, MPI.MIN)
azmax = self.mpicomm.allreduce(azmax, MPI.MAX)
elmin = self.mpicomm.allreduce(elmin, MPI.MIN)
elmax = self.mpicomm.allreduce(elmax, MPI.MAX)
self.scan_range = (azmin, azmax, elmin, elmax)
return
def load_frames(self):
log = Logger.get()
rank = 0
if self.mpicomm is not None:
rank = self.mpicomm.rank
# Timestamps
self.cache.create(self.TIMESTAMP_NAME, np.float64,
(self.local_samples[1],))
# Boresight pointing
self.cache.create("boresight_radec", np.float64,
(self.local_samples[1], 4))
self.cache.create("boresight_azel", np.float64,
(self.local_samples[1], 4))
self.cache.create(self.HWP_ANGLE_NAME, np.float64,
(self.local_samples[1],))
# Common flags
self.cache.create(self.COMMON_FLAG_NAME, np.uint8,
(self.local_samples[1],))
# Telescope position and velocity
self.cache.create(self.POSITION_NAME, np.float64,
(self.local_samples[1], 3))
self.cache.create(self.VELOCITY_NAME, np.float64,
(self.local_samples[1], 3))
# Detector data and flags
for det in self.local_dets:
name = "{}_{}".format(self.SIGNAL_NAME, det)
self.cache.create(name, np.float64, (self.local_samples[1],))
name = "{}_{}".format(self.FLAG_NAME, det)
self.cache.create(name, np.uint8, (self.local_samples[1],))
timer = Timer()
for ffile in self._file_names:
fnf = self._file_nframes[ffile]
frame_offsets = self._frame_sample_offs[ffile]
frame_sizes = self._frame_sizes[ffile]
if rank == 0:
log.debug("Loading {} frames from {}".format(fnf, ffile))
# Loop over all frames- only the root process will actually
# read data from disk.
if rank == 0:
gfile = core3g.G3File(ffile)
else:
gfile = [None] * fnf
timer.clear()
timer.start()
for fdata, frame_offset, frame_size in zip(
gfile, frame_offsets, frame_sizes):
is_scan = True
if rank == 0:
if fdata.type != core3g.G3FrameType.Scan:
is_scan = False
if self.mpicomm is not None:
is_scan = self.mpicomm.bcast(is_scan, root=0)
if not is_scan:
continue
frame_to_tod(
self,
frame_offset,
frame_size,
frame_data=fdata,
all_flavors=self._all_flavors,
)
if self.mpicomm is not None:
self.mpicomm.barrier()
timer.stop()
if rank == 0:
log.debug("Translated frames in {}s".format(timer.seconds()))
del gfile
return
def detoffset(self):
return dict(self._detquats)
def _get_boresight(self, start, n):
ref = self.cache.reference("boresight_radec")[start:start+n, :]
return ref
def _put_boresight(self, start, data):
ref = self.cache.reference("boresight_radec")
ref[start:(start+data.shape[0]), :] = data
del ref
return
def _get_boresight_azel(self, start, n):
ref = self.cache.reference("boresight_azel")[start:start+n, :]
return ref
def _put_boresight_azel(self, start, data):
ref = self.cache.reference("boresight_azel")
ref[start:(start+data.shape[0]), :] = data
del ref
return
def _get(self, detector, start, n):
name = "{}_{}".format("signal", detector)
ref = self.cache.reference(name)[start:start+n]
return ref
def _put(self, detector, start, data):
name = "{}_{}".format("signal", detector)
ref = self.cache.reference(name)
ref[start:(start+data.shape[0])] = data
del ref
return
def _get_flags(self, detector, start, n):
name = "{}_{}".format("flags", detector)
ref = self.cache.reference(name)[start:start+n]
return ref
def _put_flags(self, detector, start, flags):
name = "{}_{}".format("flags", detector)
ref = self.cache.reference(name)
ref[start:(start+flags.shape[0])] = flags
del ref
return
def _get_common_flags(self, start, n):
ref = self.cache.reference("flags_common")[start:start+n]
return ref
def _put_common_flags(self, start, flags):
ref = self.cache.reference("flags_common")
ref[start:(start+flags.shape[0])] = flags
del ref
return
def _get_hwp_angle(self, start, n):
if self.cache.exists(self.HWP_ANGLE_NAME):
hwpang = self.cache.reference(self.HWP_ANGLE_NAME)[start:start+n]
else:
hwpang = None
return hwpang
def _put_hwp_angle(self, start, hwpang):
ref = self.cache.reference(self.HWP_ANGLE_NAME)
ref[start:(start + hwpang.shape[0])] = hwpang
del ref
return
def _get_times(self, start, n):
ref = self.cache.reference("timestamps")[start:start+n]
tm = 1.0e-9 * ref.astype(np.float64)
del ref
return tm
def _put_times(self, start, stamps):
ref = self.cache.reference("timestamps")
ref[start:(start+stamps.shape[0])] = np.array(1.0e9 * stamps,
dtype=np.int64)
del ref
return
def _get_pntg(self, detector, start, n):
# Get boresight pointing (from disk or cache)
bore = self._get_boresight(start, n)
# Apply detector quaternion and return
return qa.mult(bore, self._detquats[detector])
def _put_pntg(self, detector, start, data):
raise RuntimeError("SOTOD computes detector pointing on the fly."
" Use the write_boresight() method instead.")
return
def _get_position(self, start, n):
ref = self.cache.reference("site_position")[start:start+n, :]
return ref
def _put_position(self, start, pos):
ref = self.cache.reference("site_position")
ref[start:(start+pos.shape[0]), :] = pos
del ref
return
def _get_velocity(self, start, n):
ref = self.cache.reference("site_velocity")[start:start+n, :]
return ref
def _put_velocity(self, start, vel):
ref = self.cache.reference("site_velocity")
ref[start:(start+vel.shape[0]), :] = vel
del ref
return
def read_boresight_az(self, local_start=0, n=0):
if n == 0:
n = self.local_samples[1] - local_start
if self.local_samples[1] <= 0:
raise RuntimeError(
"cannot read boresight azimuth - process "
"has no assigned local samples"
)
if (local_start < 0) or (local_start + n > self.local_samples[1]):
raise ValueError(
"local sample range {} - {} is invalid".format(
local_start, local_start + n - 1
)
)
return self._az[local_start : local_start + n]
def parse_cal_frames(calframes, dets):
detlist = None
if isinstance(dets, Hardware):
detlist = list(sorted(dets.data["detectors"].keys()))
elif isinstance(dets, list):
detlist = dets
qname = "detector_offset"
detoffset = dict()
kfreq = "noise_stream_freq"
kpsd = "noise_stream_psd"
kindx = "noise_stream_index"
dstr = "noise_detector_streams"
dwt = "noise_detector_weights"
noise_freq = dict()
noise_index = dict()
noise_psds = dict()
mixing = dict()
detstrms = dict()
detwghts = dict()
detnames = []
for calframe in calframes:
if detlist is None:
for d, q in calframe[qname].iteritems():
detoffset[d] = np.array(q)
else:
for d, q in calframe[qname].iteritems():
if d in detlist:
detoffset[d] = np.array(q)
detnames += list(detoffset.keys())
for k, v in calframe[kfreq].iteritems():
noise_freq[k] = np.array(v)
for k, v in calframe[kpsd].iteritems():
noise_psds[k] = np.array(v)
for k, v in calframe[kindx].iteritems():
noise_index[k] = int(v)
for k, v in calframe[dstr].iteritems():
detstrms[k] = np.array(v)
for k, v in calframe[dwt].iteritems():
detwghts[k] = np.array(v)
detnames = sorted(detnames)
for det in detnames:
mixing[det] = dict()
for st, wt in zip(detstrms[det], detwghts[det]):
mixing[det][st] = wt
#print(detnames, noise_freq, noise_psds, noise_index, mixing, flush=True)
# FIXME: The original data dump should have specified the mixing matrix
# explicitly.
nse = Noise(detectors=detnames, freqs=noise_freq, psds=noise_psds)
# nse = Noise(detectors=detnames, freqs=noise_freq, psds=noise_psds,
# mixmatrix=mixing, indices=noise_index)
return detoffset, nse
def load_observation(path, dets=None, mpicomm=None, prefix=None, **kwargs):
"""Loads an observation into memory.
Given an observation directory, load frame files into memory. Observation
and Calibration frames are stored in corresponding toast objects and Scan
frames are loaded and distributed. Further selection of a subset of
detectors is done based on an explicit list or a Hardware object.
Additional keyword arguments are passed to the SOTOD constructor.
Args:
path (str): The path to the observation directory.
dets (list): Either a list of detectors, a Hardware object, or None.
mpicomm (mpi4py.MPI.Comm): The communicator.
prefix (str): Only consider frame files with this prefix.
Returns:
(dict): The observation dictionary.
"""
log = Logger.get()
rank = 0
if mpicomm is not None:
rank = mpicomm.rank
frame_sizes = {}
frame_sizes_by_offset = {}
frame_sample_offs = {}
file_names = list()
file_sample_offs = {}
nframes = {}
obs = dict()
latest_obs = None
latest_cal_frames = []
first_offset = None
if rank == 0:
pat = None
if prefix is None:
pat = re.compile(r".*_(\d{8}).g3")
else:
pat = re.compile(r"{}_(\d{{8}}).g3".format(prefix))
for root, dirs, files in os.walk(path, topdown=True):
for f in sorted(files):
fmat = pat.match(f)
if fmat is not None:
ffile = os.path.join(path, f)
fsampoff = int(fmat.group(1))
if first_offset is None:
first_offset = fsampoff
file_names.append(ffile)
allframes = 0
file_sample_offs[ffile] = fsampoff
frame_sizes[ffile] = []
frame_sample_offs[ffile] = []
for frame in core3g.G3File(ffile):
allframes += 1
if frame.type == core3g.G3FrameType.Scan:
# This is a scan frame, process it.
fsz = len(frame["boresight"]["az"])
if fsampoff not in frame_sizes_by_offset:
frame_sizes_by_offset[fsampoff] = fsz
else:
if frame_sizes_by_offset[fsampoff] != fsz:
raise RuntimeError(
"Frame size at {} changes. {} != {}"
"".format(
fsampoff,
frame_sizes_by_offset[fsampoff],
fsz))
frame_sample_offs[ffile].append(fsampoff)
frame_sizes[ffile].append(fsz)
fsampoff += fsz
else:
frame_sample_offs[ffile].append(0)
frame_sizes[ffile].append(0)
if frame.type == core3g.G3FrameType.Observation:
latest_obs = frame
elif frame.type == core3g.G3FrameType.Calibration:
if fsampoff == first_offset:
latest_cal_frames.append(frame)
else:
# Unknown frame type- skip it.
pass
frame_sample_offs[ffile] = np.array(frame_sample_offs[ffile], dtype=np.int64)
nframes[ffile] = allframes
log.debug("{} starts at {} and has {} frames".format(
ffile, file_sample_offs[ffile], nframes[ffile]))
break
if len(file_names) == 0:
raise RuntimeError(
"No frames found at '{}' with prefix '{}'"
.format(path, prefix))
if mpicomm is not None:
latest_obs = mpicomm.bcast(latest_obs, root=0)
latest_cal_frames = mpicomm.bcast(latest_cal_frames, root=0)
nframes = mpicomm.bcast(nframes, root=0)
file_names = mpicomm.bcast(file_names, root=0)
file_sample_offs = mpicomm.bcast(file_sample_offs, root=0)
frame_sizes = mpicomm.bcast(frame_sizes, root=0)
frame_sizes_by_offset = mpicomm.bcast(frame_sizes_by_offset, root=0)
frame_sample_offs = mpicomm.bcast(frame_sample_offs, root=0)
if latest_obs is None:
raise RuntimeError("No observation frame was found!")
for k, v in latest_obs.iteritems():
obs[k] = s3utils.from_g3_type(v)
if len(latest_cal_frames) == 0:
raise RuntimeError("No calibration frame with detector offsets!")
detoffset, noise = parse_cal_frames(latest_cal_frames, dets)
obs["noise"] = noise
obs["tod"] = SOTOD(path, file_names, nframes, file_sample_offs,
frame_sizes, frame_sizes_by_offset,
frame_sample_offs, detquats=detoffset,
mpicomm=mpicomm, **kwargs)
return obs
def obsweight(path, prefix=None):
"""Compute frame file sizes.
This uses the sizes of the frame files in an observation as a proxy for
the amount of data in that observation. This allows us to approximately
load balance the observations across process groups.
Args:
path (str): The directory of frame files.
Returns:
(float): Approximate total size in MB.
"""
pat = None
if prefix is None:
pat = re.compile(r".*_\d{8}.g3")
else:
pat = re.compile(r"{}_\d{{8}}.g3".format(prefix))
total = 0
for root, dirs, files in os.walk(path, topdown=True):
for f in files:
mat = pat.match(f)
if mat is not None:
statinfo = os.stat(os.path.join(root, f))
total += statinfo.st_size
break
return float(total) / 1.0e6
def load_data(dir, obs=None, comm=None, prefix=None, **kwargs):
"""Loads data into memory.
Given a directory tree of observations, load one or more observations.
The observations are distributed among groups in the toast communicator.
Additional keyword arguments are passed to the load_observation()
function.
Args:
dir (str): The top-level directory that contains subdirectories (one
per observation).
obs (list): The list of observations to load.
comm (toast.Comm): the toast Comm class for distributing the data.
prefix (str): Only consider frame files with this prefix.
Returns:
(toast.Data): The distributed data object.
"""
log = Logger.get()
# the global communicator
cworld = comm.comm_world
# the communicator within the group
cgroup = comm.comm_group
# One process gets the list of observation directories
obslist = list()
weight = dict()
worldrank = 0
if cworld is not None:
worldrank = cworld.rank
if worldrank == 0:
for root, dirs, files in os.walk(dir, topdown=True):
for d in dirs:
# FIXME: Add some check here to make sure that this is a
# directory of frame files.
obslist.append(d)
weight[d] = obsweight(os.path.join(root, dir), prefix=prefix)
break
obslist = sorted(obslist)
# Filter by the requested obs
fobs = list()
if obs is not None:
for ob in obslist:
if ob in obs:
fobs.append(ob)
obslist = fobs
if cworld is not None:
obslist = cworld.bcast(obslist, root=0)
weight = cworld.bcast(weight, root=0)
# Distribute observations based on approximate size
dweight = [weight[x] for x in obslist]
distobs = distribute_discrete(dweight, comm.ngroups)
# Distributed data
data = Data(comm)
# Now every group adds its observations to the list
firstobs = distobs[comm.group][0]
nobs = distobs[comm.group][1]
for ob in range(firstobs, firstobs+nobs):
opath = os.path.join(dir, obslist[ob])
log.debug("Loading {}".format(opath))
# In case something goes wrong on one process, make sure the job
# is killed.
try:
data.obs.append(
load_observation(opath, mpicomm=cgroup, prefix=prefix, **kwargs)
)
except:
exc_type, exc_value, exc_traceback = sys.exc_info()
lines = traceback.format_exception(exc_type, exc_value,
exc_traceback)
lines = ["Proc {}: {}".format(worldrank, x)
for x in lines]
print("".join(lines), flush=True)
if cworld is not None:
cworld.Abort()
return data
|
[
"toast.qarray.mult",
"traceback.format_exception",
"toast.dist.Data",
"os.path.join",
"numpy.amin",
"os.walk",
"toast.qarray.to_position",
"toast.timing.Timer",
"toast.dist.distribute_discrete",
"numpy.amax",
"numpy.array",
"sys.exc_info",
"toast.tod.Noise",
"toast.tod.spt3g_utils.from_g3_type",
"spt3g.core.G3File",
"toast.utils.Logger.get",
"re.compile"
] |
[((13703, 13763), 'toast.tod.Noise', 'Noise', ([], {'detectors': 'detnames', 'freqs': 'noise_freq', 'psds': 'noise_psds'}), '(detectors=detnames, freqs=noise_freq, psds=noise_psds)\n', (13708, 13763), False, 'from toast.tod import TOD, Noise\n'), ((14759, 14771), 'toast.utils.Logger.get', 'Logger.get', ([], {}), '()\n', (14769, 14771), False, 'from toast.utils import Logger, Environment, memreport\n'), ((19787, 19814), 'os.walk', 'os.walk', (['path'], {'topdown': '(True)'}), '(path, topdown=True)\n', (19794, 19814), False, 'import os\n'), ((20784, 20796), 'toast.utils.Logger.get', 'Logger.get', ([], {}), '()\n', (20794, 20796), False, 'from toast.utils import Logger, Environment, memreport\n'), ((21946, 21988), 'toast.dist.distribute_discrete', 'distribute_discrete', (['dweight', 'comm.ngroups'], {}), '(dweight, comm.ngroups)\n', (21965, 21988), False, 'from toast.dist import Data, distribute_discrete\n'), ((22024, 22034), 'toast.dist.Data', 'Data', (['comm'], {}), '(comm)\n', (22028, 22034), False, 'from toast.dist import Data, distribute_discrete\n'), ((4005, 4026), 'toast.qarray.to_position', 'qa.to_position', (['quats'], {}), '(quats)\n', (4019, 4026), True, 'import toast.qarray as qa\n'), ((4787, 4799), 'toast.utils.Logger.get', 'Logger.get', ([], {}), '()\n', (4797, 4799), False, 'from toast.utils import Logger, Environment, memreport\n'), ((6134, 6141), 'toast.timing.Timer', 'Timer', ([], {}), '()\n', (6139, 6141), False, 'from toast.timing import Timer\n'), ((10163, 10210), 'numpy.array', 'np.array', (['(1000000000.0 * stamps)'], {'dtype': 'np.int64'}), '(1000000000.0 * stamps, dtype=np.int64)\n', (10171, 10210), True, 'import numpy as np\n'), ((10496, 10535), 'toast.qarray.mult', 'qa.mult', (['bore', 'self._detquats[detector]'], {}), '(bore, self._detquats[detector])\n', (10503, 10535), True, 'import toast.qarray as qa\n'), ((15302, 15329), 'os.walk', 'os.walk', (['path'], {'topdown': '(True)'}), '(path, topdown=True)\n', (15309, 15329), False, 'import os\n'), ((18703, 18726), 'toast.tod.spt3g_utils.from_g3_type', 's3utils.from_g3_type', (['v'], {}), '(v)\n', (18723, 18726), True, 'from toast.tod import spt3g_utils as s3utils\n'), ((19649, 19675), 're.compile', 're.compile', (['""".*_\\\\d{8}.g3"""'], {}), "('.*_\\\\d{8}.g3')\n", (19659, 19675), False, 'import re\n'), ((21161, 21187), 'os.walk', 'os.walk', (['dir'], {'topdown': '(True)'}), '(dir, topdown=True)\n', (21168, 21187), False, 'import os\n'), ((22227, 22257), 'os.path.join', 'os.path.join', (['dir', 'obslist[ob]'], {}), '(dir, obslist[ob])\n', (22239, 22257), False, 'import os\n'), ((4154, 4171), 'numpy.amin', 'np.amin', (['self._az'], {}), '(self._az)\n', (4161, 4171), True, 'import numpy as np\n'), ((4192, 4209), 'numpy.amax', 'np.amax', (['self._az'], {}), '(self._az)\n', (4199, 4209), True, 'import numpy as np\n'), ((4230, 4247), 'numpy.amin', 'np.amin', (['self._el'], {}), '(self._el)\n', (4237, 4247), True, 'import numpy as np\n'), ((4268, 4285), 'numpy.amax', 'np.amax', (['self._el'], {}), '(self._el)\n', (4275, 4285), True, 'import numpy as np\n'), ((12988, 12999), 'numpy.array', 'np.array', (['v'], {}), '(v)\n', (12996, 12999), True, 'import numpy as np\n'), ((13076, 13087), 'numpy.array', 'np.array', (['v'], {}), '(v)\n', (13084, 13087), True, 'import numpy as np\n'), ((13247, 13258), 'numpy.array', 'np.array', (['v'], {}), '(v)\n', (13255, 13258), True, 'import numpy as np\n'), ((13332, 13343), 'numpy.array', 'np.array', (['v'], {}), '(v)\n', (13340, 13343), True, 'import numpy as np\n'), ((15162, 15190), 're.compile', 're.compile', (['""".*_(\\\\d{8}).g3"""'], {}), "('.*_(\\\\d{8}).g3')\n", (15172, 15190), False, 'import re\n'), ((6592, 6612), 'spt3g.core.G3File', 'core3g.G3File', (['ffile'], {}), '(ffile)\n', (6605, 6612), True, 'from spt3g import core as core3g\n'), ((12709, 12720), 'numpy.array', 'np.array', (['q'], {}), '(q)\n', (12717, 12720), True, 'import numpy as np\n'), ((22600, 22614), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (22612, 22614), False, 'import sys\n'), ((22635, 22697), 'traceback.format_exception', 'traceback.format_exception', (['exc_type', 'exc_value', 'exc_traceback'], {}), '(exc_type, exc_value, exc_traceback)\n', (22661, 22697), False, 'import traceback\n'), ((12856, 12867), 'numpy.array', 'np.array', (['q'], {}), '(q)\n', (12864, 12867), True, 'import numpy as np\n'), ((15468, 15489), 'os.path.join', 'os.path.join', (['path', 'f'], {}), '(path, f)\n', (15480, 15489), False, 'import os\n'), ((15894, 15914), 'spt3g.core.G3File', 'core3g.G3File', (['ffile'], {}), '(ffile)\n', (15907, 15914), True, 'from spt3g import core as core3g\n'), ((17603, 17653), 'numpy.array', 'np.array', (['frame_sample_offs[ffile]'], {'dtype': 'np.int64'}), '(frame_sample_offs[ffile], dtype=np.int64)\n', (17611, 17653), True, 'import numpy as np\n'), ((19938, 19959), 'os.path.join', 'os.path.join', (['root', 'f'], {}), '(root, f)\n', (19950, 19959), False, 'import os\n'), ((21406, 21429), 'os.path.join', 'os.path.join', (['root', 'dir'], {}), '(root, dir)\n', (21418, 21429), False, 'import os\n')]
|
import os
import time
import numpy as np
from ..population.fireworks import SSPFirework
from ..operator import operator as opt
from ..tools.distribution import MultiVariateNormalDistribution as MVND
EPS = 1e-6
class FWASSP(object):
def __init__(self):
# params
self.fw_size = None
self.sp_size = None
self.init_scale = None
self.max_not_improved = None
# problem related params
self.dim = None
self.lb = None
self.ub = None
# population
self.fireworks = None
# firework parameters
self.spk_size = None
self.init_scale = None
self.mu_ratio = None
self.weight_method = None
self.adapt_lr = None
self.coop_lr = None
# states
self.restart_status = None
self.feature_points = None
# load default params
self.set_params(self.default_params())
def default_params(self, benchmark=None):
params = {}
params['fw_size'] = 5
params['sp_size'] = 300
params['max_not_improved'] = 20
# fireworks parameters
params['spk_size'] = 60
params['init_scale'] = 5
params['mu_ratio'] = 0.5
params['weight_method'] = 'Recombination'
params['adapt_lr'] = 0.5
params['coop_lr'] = 0.5
return params
def set_params(self, params):
for param in params:
setattr(self, param, params[param])
def optimize(self, e):
self.init(e)
while not e.terminate():
# independent cma evolving
for fw in self.fireworks:
fw.explode()
fw.eval(e)
fw.select()
fw.adapt()
# restart
self.restart(e)
# cooperate
self.cooperate()
# update
self.update()
return e.best_y
def init(self, e):
# record problem related params
self.dim = opt.dim = e.obj.dim
self.lb = opt.lb = e.obj.lb
self.ub = opt.ub = e.obj.ub
# init random seed
self.seed = int(os.getpid()*time.time() % 1e8)
np.random.seed(self.seed)
# init states
self.restart_status = np.array([False] * self.fw_size)
self.feature_points = [list() for _ in range(self.fw_size)]
# init population
init_pop = np.random.uniform(self.lb, self.ub, [self.fw_size, self.dim])
init_fit = e(init_pop)
shifts = init_pop.copy()
scales = [self.init_scale] * self.fw_size
covs = [np.eye(self.dim) for _ in range(self.fw_size)]
mvnds = [MVND(shifts[_,:], scales[_], covs[_]) for _ in range(self.fw_size)]
for mvnd in mvnds:
mvnd.decompose()
self.fireworks = [SSPFirework(init_pop[i,:],
init_fit[i],
mvnds[i],
self.spk_size,
mu_ratio=self.mu_ratio,
weights=self.weight_method,
lr=self.adapt_lr,
lb=self.lb,
ub=self.ub) for i in range(self.fw_size)]
def restart(self, e):
""" Decide fireworks to restart """
# restart status
self.restart_status = np.array([False] * self.fw_size)
""" Independent Restart """
for idx, fw in enumerate(self.fireworks):
# 1. Low value variance
if np.std(fw.spk_fit) < 1e-6:
self.restart_status[idx] = True
# 2. Low position variance
if fw.new_mvnd.scale * (np.max(fw.new_mvnd.eigvals) ** 0.5) < 1e-6:
self.restart_status[idx] = True
# 3. Max not improved
if fw.not_improved_fit > self.max_not_improved:
self.restart_status[idx] = True
""" Collaborated Restart """
"""
# 4. Loser-out tournament
left_iter = int(e.max_eval / self.spk_size)
for i, fw in enumerate(self.fireworks):
# ignore fireworks at first explosion
if fw.val is None:
continue
# ignore fireworks not improved
improve = fw.val - fw.new_val
if improve < 0:
continue
# restart if not improved fast enough
if improve * left_iter < fw.new_val - e.cur_y:
self.restart_status[i] = True
#print("r4 ", self.restart_status)
"""
# 5. Covered by better firework
sort_idx = np.argsort([fw.val for fw in self.fireworks])
for i in range(len(sort_idx)):
for j in range(i+1, len(sort_idx)):
if self.restart_status[sort_idx[i]] or self.restart_status[sort_idx[j]]:
continue
# alias
fw1 = self.fireworks[sort_idx[i]]
fw2 = self.fireworks[sort_idx[j]]
mvnd1 = fw1.new_mvnd
mvnd2 = fw2.new_mvnd
dim = self.dim
lam = int(fw2.nspk * fw2.mu_ratio)
# check cover rate
ys = (fw2.spk_pop[:lam,:] - mvnd1.shift[np.newaxis]) / mvnd1.scale
zs = np.dot(ys, mvnd1.invsqrt_cov)
r2 = np.sum(zs ** 2, axis=1)
d2 = dim * (1 - 1/(4*dim) + 1/(21 * dim**2)) ** 2
cover = r2 < d2
cover_rate = np.sum(cover) / lam
# restart if cover by 85%
if cover_rate > 0.85:
self.restart_status[sort_idx[j]] = True
#print("r5 ", self.restart_status)
""" Restart Fireworks """
for idx in range(self.fw_size):
if not self.restart_status[idx]:
continue
# generate new individual
idv = np.random.uniform(self.lb, self.ub, [self.dim])
val = e(idv[np.newaxis,:])[0]
shift = idv.copy()
scale = self.init_scale
cov = np.eye(self.dim)
mvnd = MVND(shift, scale, cov)
mvnd.decompose()
self.fireworks[idx] = SSPFirework(idv, val, mvnd, self.spk_size,
mu_ratio=self.mu_ratio,
weights=self.weight_method,
lr=self.adapt_lr,
lb=self.lb,
ub=self.ub)
# prepare for next generation
fw = self.fireworks[idx]
fw.new_idv = fw.idv
fw.new_val = fw.val
fw.new_mvnd = fw.mvnd
fw.new_ps = fw.ps
fw.new_pc = fw.pc
def cooperate(self):
# alias
dim = self.dim
""" Preparing """
poss = np.array([fw.new_mvnd.shift for fw in self.fireworks])
# pair-wise distance
dist = np.zeros((self.fw_size, self.fw_size))
for i in range(self.fw_size):
for j in range(i+1, self.fw_size):
d = np.sqrt(np.sum((poss[i,:] - poss[j,:]) ** 2))
dist[i,j] = dist[j,i] = d
# Unit vector
unit_vec = np.zeros((self.fw_size, self.fw_size, self.dim))
for i in range(self.fw_size):
for j in range(self.fw_size):
if i == j: continue
unit_vec[i,j,:] = (poss[j,:] - poss[i,:]) / dist[i,j]
# expected radius on direction
expr = np.zeros((self.fw_size, self.fw_size))
p0 = dim * (1 - 1/(4*dim) + 1/(21 * dim**2)) ** 2
for i in range(self.fw_size):
for j in range(self.fw_size):
if i == j: continue
pj = self.fireworks[i].new_mvnd.dispersion(poss[j,:])
expr[i,j] = dist[i,j] * np.sqrt(p0 / pj)
# firework rank
rank = np.empty(self.fw_size)
rank[np.argsort([fw.val for fw in self.fireworks])] = np.arange(self.fw_size)
""" Get feature points """
feature_points = [list() for _ in range(self.fw_size)]
feature_direct_expr = [list() for _ in range(self.fw_size)]
# obtain feature points
for i in range(self.fw_size):
for j in range(i+1, self.fw_size):
comp = self.fuzzy_compare(self.fireworks[i], self.fireworks[j])
r1 = dist[i,j] - expr[j,i]
r2 = dist[j,i] - expr[i,j]
mr1 = (expr[i,j] + dist[i,j] - expr[j,i]) / 2
mr2 = (expr[j,i] + dist[j,i] - expr[i,j]) / 2
# clipping
abs_r1, abs_r2, abs_mr1, abs_mr2 = np.abs(r1), np.abs(r2), np.abs(mr1), np.abs(mr2)
r1 *= np.clip(abs_r1, 0.5*expr[i,j], 2*expr[i,j]) / abs_r1
r2 *= np.clip(abs_r2, 0.5*expr[j,i], 2*expr[j,i]) / abs_r2
mr1 *= np.clip(abs_mr1, 0.5*expr[i,j], 2*expr[i,j]) / abs_mr1
mr2 *= np.clip(abs_mr2, 0.5*expr[j,i], 2*expr[j,i]) / abs_mr2
fp1 = poss[i,:] + unit_vec[i,j,:] * r1
fp2 = poss[j,:] + unit_vec[j,i,:] * r2
fp3 = poss[i,:] + unit_vec[i,j,:] * mr1
fp4 = poss[j,:] + unit_vec[j,i,:] * mr2
if comp == 1:
feature_points[j].append(fp2)
feature_direct_expr[j].append(expr[j,i])
elif comp == -1:
feature_points[i].append(fp1)
feature_direct_expr[i].append(expr[i,j])
else:
feature_points[i].append(fp3)
feature_direct_expr[i].append(expr[i,j])
feature_points[j].append(fp4)
feature_direct_expr[j].append(expr[j,i])
""" Clip feature points in bound """
for idx, fw in enumerate(self.fireworks):
for j, fp in enumerate(feature_points[idx]):
shift = fw.new_mvnd.shift
vec = fp - shift
out_ub = fp > self.ub
out_lb = fp < self.lb
if np.any(out_ub):
ubr = min(((self.ub * np.ones(self.dim))[out_ub] - shift[out_ub]) / vec[out_ub])
else:
ubr = 1
if np.any(out_lb):
lbr = min(((self.lb * np.ones(self.dim))[out_lb] - shift[out_lb]) / vec[out_lb])
else:
lbr = 1
feature_points[idx][j] = fw.mvnd.shift + min(ubr, lbr) * vec
""" Select feature points """
max_fps = 2
for idx, fw in enumerate(self.fireworks):
lam = len(feature_points[idx])
if lam <= max_fps:
continue
else:
fps = np.array(feature_points[idx])
vec = fps - fw.new_mvnd.shift[np.newaxis,:]
vec_norm = np.sqrt(np.sum(vec**2, axis=1))
sort_idx = np.argsort(vec_norm/np.array(feature_direct_expr[idx]))
if idx == 0:
feature_points[idx] = [fps[_] for _ in sort_idx[lam-max_fps:]]
else:
feature_points[idx] = [fps[_] for _ in sort_idx[:max_fps]]
self.feature_points = feature_points
""" Cooperate fireworks """
for i in range(self.fw_size):
if len(feature_points[i]) == 0:
continue
# alias
fw = self.fireworks[i]
dim = self.dim
fps = np.array(feature_points[i]).reshape(-1, dim)
lam = fps.shape[0]
lr = self.coop_lr
# fit feature points
new_shift = fw.new_mvnd.shift
new_scale = fw.new_mvnd.scale
ys = (fps - new_shift[np.newaxis,:]) / new_scale
zs = np.matmul(ys, fw.new_mvnd.invsqrt_cov)
d2 = dim * (1 - 1/(4*dim) + 1/(21 * dim**2)) ** 2
r2 = np.sum(zs ** 2, axis=1)
a = 1
b = 1/d2 - (1/r2) * a
new_cov = EPS * np.eye(dim)
new_cov += (1 - lr + lr * np.mean(a) - EPS) * fw.new_mvnd.cov
covs = np.matmul(ys[:,:,np.newaxis], ys[:,np.newaxis,:])
for j in range(lam):
new_cov += (lr * b[j]) / lam * covs[j,:,:]
fw.new_mvnd = MVND(new_shift, new_scale, new_cov)
fw.new_mvnd.decompose()
def update(self):
for fw in self.fireworks:
fw.update()
def fuzzy_compare(self, fw1, fw2):
if fw1.spk_fit is None and fw2.spk_fit is None:
return 0
elif fw1.spk_fit is None:
return -1
elif fw2.spk_fit is None:
return 1
else:
if max(fw1.spk_fit) < min(fw2.spk_fit):
return 1
elif min(fw1.spk_fit) > max(fw2.spk_fit):
return -1
else:
return 0
|
[
"numpy.random.seed",
"numpy.sum",
"numpy.abs",
"numpy.empty",
"numpy.ones",
"numpy.clip",
"numpy.argsort",
"numpy.mean",
"numpy.arange",
"numpy.std",
"numpy.max",
"numpy.dot",
"numpy.random.uniform",
"os.getpid",
"numpy.zeros",
"time.time",
"numpy.any",
"numpy.array",
"numpy.matmul",
"numpy.eye",
"numpy.sqrt"
] |
[((2232, 2257), 'numpy.random.seed', 'np.random.seed', (['self.seed'], {}), '(self.seed)\n', (2246, 2257), True, 'import numpy as np\n'), ((2311, 2343), 'numpy.array', 'np.array', (['([False] * self.fw_size)'], {}), '([False] * self.fw_size)\n', (2319, 2343), True, 'import numpy as np\n'), ((2458, 2519), 'numpy.random.uniform', 'np.random.uniform', (['self.lb', 'self.ub', '[self.fw_size, self.dim]'], {}), '(self.lb, self.ub, [self.fw_size, self.dim])\n', (2475, 2519), True, 'import numpy as np\n'), ((3489, 3521), 'numpy.array', 'np.array', (['([False] * self.fw_size)'], {}), '([False] * self.fw_size)\n', (3497, 3521), True, 'import numpy as np\n'), ((4793, 4838), 'numpy.argsort', 'np.argsort', (['[fw.val for fw in self.fireworks]'], {}), '([fw.val for fw in self.fireworks])\n', (4803, 4838), True, 'import numpy as np\n'), ((7161, 7215), 'numpy.array', 'np.array', (['[fw.new_mvnd.shift for fw in self.fireworks]'], {}), '([fw.new_mvnd.shift for fw in self.fireworks])\n', (7169, 7215), True, 'import numpy as np\n'), ((7261, 7299), 'numpy.zeros', 'np.zeros', (['(self.fw_size, self.fw_size)'], {}), '((self.fw_size, self.fw_size))\n', (7269, 7299), True, 'import numpy as np\n'), ((7543, 7591), 'numpy.zeros', 'np.zeros', (['(self.fw_size, self.fw_size, self.dim)'], {}), '((self.fw_size, self.fw_size, self.dim))\n', (7551, 7591), True, 'import numpy as np\n'), ((7833, 7871), 'numpy.zeros', 'np.zeros', (['(self.fw_size, self.fw_size)'], {}), '((self.fw_size, self.fw_size))\n', (7841, 7871), True, 'import numpy as np\n'), ((8213, 8235), 'numpy.empty', 'np.empty', (['self.fw_size'], {}), '(self.fw_size)\n', (8221, 8235), True, 'import numpy as np\n'), ((8298, 8321), 'numpy.arange', 'np.arange', (['self.fw_size'], {}), '(self.fw_size)\n', (8307, 8321), True, 'import numpy as np\n'), ((2651, 2667), 'numpy.eye', 'np.eye', (['self.dim'], {}), '(self.dim)\n', (2657, 2667), True, 'import numpy as np\n'), ((6118, 6165), 'numpy.random.uniform', 'np.random.uniform', (['self.lb', 'self.ub', '[self.dim]'], {}), '(self.lb, self.ub, [self.dim])\n', (6135, 6165), True, 'import numpy as np\n'), ((6306, 6322), 'numpy.eye', 'np.eye', (['self.dim'], {}), '(self.dim)\n', (6312, 6322), True, 'import numpy as np\n'), ((8249, 8294), 'numpy.argsort', 'np.argsort', (['[fw.val for fw in self.fireworks]'], {}), '([fw.val for fw in self.fireworks])\n', (8259, 8294), True, 'import numpy as np\n'), ((12136, 12174), 'numpy.matmul', 'np.matmul', (['ys', 'fw.new_mvnd.invsqrt_cov'], {}), '(ys, fw.new_mvnd.invsqrt_cov)\n', (12145, 12174), True, 'import numpy as np\n'), ((12255, 12278), 'numpy.sum', 'np.sum', (['(zs ** 2)'], {'axis': '(1)'}), '(zs ** 2, axis=1)\n', (12261, 12278), True, 'import numpy as np\n'), ((12467, 12520), 'numpy.matmul', 'np.matmul', (['ys[:, :, np.newaxis]', 'ys[:, np.newaxis, :]'], {}), '(ys[:, :, np.newaxis], ys[:, np.newaxis, :])\n', (12476, 12520), True, 'import numpy as np\n'), ((3660, 3678), 'numpy.std', 'np.std', (['fw.spk_fit'], {}), '(fw.spk_fit)\n', (3666, 3678), True, 'import numpy as np\n'), ((5482, 5511), 'numpy.dot', 'np.dot', (['ys', 'mvnd1.invsqrt_cov'], {}), '(ys, mvnd1.invsqrt_cov)\n', (5488, 5511), True, 'import numpy as np\n'), ((5533, 5556), 'numpy.sum', 'np.sum', (['(zs ** 2)'], {'axis': '(1)'}), '(zs ** 2, axis=1)\n', (5539, 5556), True, 'import numpy as np\n'), ((10409, 10423), 'numpy.any', 'np.any', (['out_ub'], {}), '(out_ub)\n', (10415, 10423), True, 'import numpy as np\n'), ((10595, 10609), 'numpy.any', 'np.any', (['out_lb'], {}), '(out_lb)\n', (10601, 10609), True, 'import numpy as np\n'), ((11088, 11117), 'numpy.array', 'np.array', (['feature_points[idx]'], {}), '(feature_points[idx])\n', (11096, 11117), True, 'import numpy as np\n'), ((12361, 12372), 'numpy.eye', 'np.eye', (['dim'], {}), '(dim)\n', (12367, 12372), True, 'import numpy as np\n'), ((2193, 2204), 'os.getpid', 'os.getpid', ([], {}), '()\n', (2202, 2204), False, 'import os\n'), ((2205, 2216), 'time.time', 'time.time', ([], {}), '()\n', (2214, 2216), False, 'import time\n'), ((5701, 5714), 'numpy.sum', 'np.sum', (['cover'], {}), '(cover)\n', (5707, 5714), True, 'import numpy as np\n'), ((7413, 7451), 'numpy.sum', 'np.sum', (['((poss[i, :] - poss[j, :]) ** 2)'], {}), '((poss[i, :] - poss[j, :]) ** 2)\n', (7419, 7451), True, 'import numpy as np\n'), ((8156, 8172), 'numpy.sqrt', 'np.sqrt', (['(p0 / pj)'], {}), '(p0 / pj)\n', (8163, 8172), True, 'import numpy as np\n'), ((8977, 8987), 'numpy.abs', 'np.abs', (['r1'], {}), '(r1)\n', (8983, 8987), True, 'import numpy as np\n'), ((8989, 8999), 'numpy.abs', 'np.abs', (['r2'], {}), '(r2)\n', (8995, 8999), True, 'import numpy as np\n'), ((9001, 9012), 'numpy.abs', 'np.abs', (['mr1'], {}), '(mr1)\n', (9007, 9012), True, 'import numpy as np\n'), ((9014, 9025), 'numpy.abs', 'np.abs', (['mr2'], {}), '(mr2)\n', (9020, 9025), True, 'import numpy as np\n'), ((9048, 9097), 'numpy.clip', 'np.clip', (['abs_r1', '(0.5 * expr[i, j])', '(2 * expr[i, j])'], {}), '(abs_r1, 0.5 * expr[i, j], 2 * expr[i, j])\n', (9055, 9097), True, 'import numpy as np\n'), ((9123, 9172), 'numpy.clip', 'np.clip', (['abs_r2', '(0.5 * expr[j, i])', '(2 * expr[j, i])'], {}), '(abs_r2, 0.5 * expr[j, i], 2 * expr[j, i])\n', (9130, 9172), True, 'import numpy as np\n'), ((9199, 9249), 'numpy.clip', 'np.clip', (['abs_mr1', '(0.5 * expr[i, j])', '(2 * expr[i, j])'], {}), '(abs_mr1, 0.5 * expr[i, j], 2 * expr[i, j])\n', (9206, 9249), True, 'import numpy as np\n'), ((9277, 9327), 'numpy.clip', 'np.clip', (['abs_mr2', '(0.5 * expr[j, i])', '(2 * expr[j, i])'], {}), '(abs_mr2, 0.5 * expr[j, i], 2 * expr[j, i])\n', (9284, 9327), True, 'import numpy as np\n'), ((11213, 11237), 'numpy.sum', 'np.sum', (['(vec ** 2)'], {'axis': '(1)'}), '(vec ** 2, axis=1)\n', (11219, 11237), True, 'import numpy as np\n'), ((11833, 11860), 'numpy.array', 'np.array', (['feature_points[i]'], {}), '(feature_points[i])\n', (11841, 11860), True, 'import numpy as np\n'), ((3823, 3850), 'numpy.max', 'np.max', (['fw.new_mvnd.eigvals'], {}), '(fw.new_mvnd.eigvals)\n', (3829, 3850), True, 'import numpy as np\n'), ((11284, 11318), 'numpy.array', 'np.array', (['feature_direct_expr[idx]'], {}), '(feature_direct_expr[idx])\n', (11292, 11318), True, 'import numpy as np\n'), ((12411, 12421), 'numpy.mean', 'np.mean', (['a'], {}), '(a)\n', (12418, 12421), True, 'import numpy as np\n'), ((10467, 10484), 'numpy.ones', 'np.ones', (['self.dim'], {}), '(self.dim)\n', (10474, 10484), True, 'import numpy as np\n'), ((10653, 10670), 'numpy.ones', 'np.ones', (['self.dim'], {}), '(self.dim)\n', (10660, 10670), True, 'import numpy as np\n')]
|
import numpy as np
def to_binary(val, Nb):
return [int(i) for i in '{:0{w}b}'.format(val, w=Nb)][::-1][:Nb]
def operator_function(operator_name, Ni, No):
Nb = Ni // 2
d = 2**Nb
if operator_name == 'zero':
return lambda x: 0
elif operator_name == 'add':
return lambda x: to_binary(int(x // d) + int(x % d), No)
elif operator_name == 'sub':
return lambda x: to_binary((int(x // d) - int(x % d)) % d, No)
elif operator_name == 'mul':
return lambda x: to_binary(int(x // d) * int(x % d), No)
elif operator_name == 'and':
return lambda x: to_binary(int(x // d) & int(x % d), No)
elif operator_name == 'or':
return lambda x: to_binary(int(x // d) | int(x % d), No)
else:
raise ValueError('no such operator: {}')
def check_samples(samples):
# check each row has distinct elements
Ns, Ne = samples.shape
for s in range(Ns):
if len(set(samples[s])) < Ne:
raise RuntimeError('Error: sample with duplicate indices')
num_duplicates = 0
for s in range(Ns):
for s2 in range(s+1, Ns):
if np.array_equal(samples[s], samples[s2]):
num_duplicates += 1
if num_duplicates > 0:
print('Warning: {} samples are duplicated for Ns={}, Ne={}. This is '
'unavoidable for Ns >= |samples| choose Ne but can also happen '
'by chance otherwise. You may need to run this tool again.'.
format(num_duplicates, Ns, Ne))
def construct_nontrivial_sample_base(operator, Ni, No):
''' Generates between log2(No) and No + 1 examples such that there is at
least one example with each target value for each target (that is:
there is a function expressed by the examples for each target).'''
# generate one example randomly
r = np.uint64(np.random.randint(2**Ni))
so_far = set([r])
targets_so_far = [set() for i in range(No)]
for o in range(No):
# record the target value (for this target) of all existing examples
for example in so_far:
T = operator(example)
targets_so_far[o].add(T[o])
# only generate new samples if the existing are not dichotomous for
# this target note that there will always be at least one value present
# since we generate an initial random example
if len(targets_so_far[o]) < 2:
r = np.uint64(np.random.randint(2**Ni))
while operator(r)[o] in targets_so_far[o]:
r = np.uint64(np.random.randint(2**Ni))
so_far.add(r)
return so_far
def single_nontrivial_sample(operator, Ni, No, Ne, output_vector):
so_far = construct_nontrivial_sample_base(operator, Ni, No)
for i, example in enumerate(so_far):
output_vector[i] = example
for i in range(len(so_far), Ne):
r = np.uint64(np.random.randint(2**Ni))
while r in so_far:
r = np.uint64(np.random.randint(2**Ni))
output_vector[i] = r
so_far.add(r)
def nontrivial_sampling(Ns, Ne, operator_name, Ni, No):
# get operator function from name
operator = operator_function(operator_name, Ni, No)
if Ne > 2**Ni:
raise ValueError('Cannot draw {} unique patterns of {} bits.'
.format(Ne, Ni))
samples = np.zeros(shape=(Ns, Ne), dtype=np.uint64)
for i in range(Ns):
single_nontrivial_sample(operator, Ni, No, Ne, samples[i])
check_samples(samples) # for errors
return samples
def simple_sampling(Ns, Ne, N):
# choose (Ns x Ne) random integers without replacement
samples = np.zeros(shape=(Ns, Ne), dtype=np.uint64)
for i in range(Ns):
so_far = set()
for k in range(Ne):
r = np.uint64(np.random.randint(N))
while r in so_far:
r = np.uint64(np.random.randint(N))
samples[i][k] = r
so_far.add(r)
check_samples(samples) # for errors
return samples
|
[
"numpy.array_equal",
"numpy.random.randint",
"numpy.zeros"
] |
[((3345, 3386), 'numpy.zeros', 'np.zeros', ([], {'shape': '(Ns, Ne)', 'dtype': 'np.uint64'}), '(shape=(Ns, Ne), dtype=np.uint64)\n', (3353, 3386), True, 'import numpy as np\n'), ((3647, 3688), 'numpy.zeros', 'np.zeros', ([], {'shape': '(Ns, Ne)', 'dtype': 'np.uint64'}), '(shape=(Ns, Ne), dtype=np.uint64)\n', (3655, 3688), True, 'import numpy as np\n'), ((1859, 1885), 'numpy.random.randint', 'np.random.randint', (['(2 ** Ni)'], {}), '(2 ** Ni)\n', (1876, 1885), True, 'import numpy as np\n'), ((1137, 1176), 'numpy.array_equal', 'np.array_equal', (['samples[s]', 'samples[s2]'], {}), '(samples[s], samples[s2])\n', (1151, 1176), True, 'import numpy as np\n'), ((2890, 2916), 'numpy.random.randint', 'np.random.randint', (['(2 ** Ni)'], {}), '(2 ** Ni)\n', (2907, 2916), True, 'import numpy as np\n'), ((2439, 2465), 'numpy.random.randint', 'np.random.randint', (['(2 ** Ni)'], {}), '(2 ** Ni)\n', (2456, 2465), True, 'import numpy as np\n'), ((2969, 2995), 'numpy.random.randint', 'np.random.randint', (['(2 ** Ni)'], {}), '(2 ** Ni)\n', (2986, 2995), True, 'import numpy as np\n'), ((3790, 3810), 'numpy.random.randint', 'np.random.randint', (['N'], {}), '(N)\n', (3807, 3810), True, 'import numpy as np\n'), ((2550, 2576), 'numpy.random.randint', 'np.random.randint', (['(2 ** Ni)'], {}), '(2 ** Ni)\n', (2567, 2576), True, 'import numpy as np\n'), ((3873, 3893), 'numpy.random.randint', 'np.random.randint', (['N'], {}), '(N)\n', (3890, 3893), True, 'import numpy as np\n')]
|
from model import Model
from preprocessing import VidToFrame
from preprocessing import FrameCount
import numpy as np
import sys
import os
class run_classification(object):
def __init__(self, file):
self.file = file
def FileToFrame(self):
return VidToFrame(self.file)
if __name__ == "__main__":
## 파일 불러와야함
path = '../uploads'
label = os.listdir(path)
video = path + '/'+ label[0]
input_data = run_classification(video)
## 레이블 불러와야댐 좆밥드랑
if label[0] == '0':
label = [1,0,0,0,0]
elif label[0] == '1':
label = [0,1,0,0,0]
elif label[0] == '2':
label = [0,0,1,0,0]
elif label[0] == '3':
label = [0,0,0,1,0]
elif label[0] == '4':
label = [0,0,0,0,1]
c3dnet = Model()
ans = c3dnet.run(np.expand_dims(input_data.FileToFrame(), axis=0), np.expand_dims(label, axis=0))
os.remove(video)
ans = str(ans[0])
print(ans)
|
[
"os.remove",
"model.Model",
"numpy.expand_dims",
"preprocessing.VidToFrame",
"os.listdir"
] |
[((373, 389), 'os.listdir', 'os.listdir', (['path'], {}), '(path)\n', (383, 389), False, 'import os\n'), ((770, 777), 'model.Model', 'Model', ([], {}), '()\n', (775, 777), False, 'from model import Model\n'), ((884, 900), 'os.remove', 'os.remove', (['video'], {}), '(video)\n', (893, 900), False, 'import os\n'), ((271, 292), 'preprocessing.VidToFrame', 'VidToFrame', (['self.file'], {}), '(self.file)\n', (281, 292), False, 'from preprocessing import VidToFrame\n'), ((849, 878), 'numpy.expand_dims', 'np.expand_dims', (['label'], {'axis': '(0)'}), '(label, axis=0)\n', (863, 878), True, 'import numpy as np\n')]
|
from torch.utils.data import Dataset
import numpy as np
import os, cv2, time
from PIL import Image
from torchvision import transforms
from datasets.data_io import *
s_h, s_w = 0, 0
class MVSDataset(Dataset):
def __init__(self, datapath, split='intermediate', nviews=3, img_wh=(1920, 1056), ndepths=192):
super(MVSDataset, self).__init__()
self.datapath = datapath
self.img_wh = img_wh
self.split = split
self.nviews = nviews
self.ndepths = ndepths
self.build_metas()
self.define_transforms()
def build_metas(self):
self.metas = []
if self.split == 'intermediate':
self.scans = ['Family', 'Francis', 'Horse', 'Lighthouse',
'M60', 'Panther', 'Playground', 'Train']
self.image_sizes = {'Family': (1920, 1080),
'Francis': (1920, 1080),
'Horse': (1920, 1080),
'Lighthouse': (2048, 1080),
'M60': (2048, 1080),
'Panther': (2048, 1080),
'Playground': (1920, 1080),
'Train': (1920, 1080)}
elif self.split == 'advanced':
self.scans = ['Auditorium', 'Ballroom', 'Courtroom',
'Museum', 'Palace', 'Temple']
self.image_sizes = {'Auditorium': (1920, 1080),
'Ballroom': (1920, 1080),
'Courtroom': (1920, 1080),
'Museum': (1920, 1080),
'Palace': (1920, 1080),
'Temple': (1920, 1080)}
for scan in self.scans:
with open(os.path.join(self.datapath, self.split, scan, 'pair.txt')) as f:
num_viewpoint = int(f.readline())
for view_idx in range(num_viewpoint):
ref_view = int(f.readline().rstrip())
src_views = [int(x) for x in f.readline().rstrip().split()[1::2]]
if len(src_views) != 0:
# self.metas += [(scan, -1, ref_view, src_views)]
self.metas += [(scan, ref_view, src_views, scan)]
print("split: ", self.split, "metas:", len(self.metas))
def define_transforms(self):
self.transform_seg = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
def read_cam_file(self, filename):
with open(filename) as f:
lines = [line.rstrip() for line in f.readlines()]
# extrinsics: line [1,5), 4x4 matrix
extrinsics = np.fromstring(' '.join(lines[1:5]), dtype=np.float32, sep=' ')
extrinsics = extrinsics.reshape((4, 4))
# intrinsics: line [7-10), 3x3 matrix
intrinsics = np.fromstring(' '.join(lines[7:10]), dtype=np.float32, sep=' ')
intrinsics = intrinsics.reshape((3, 3))
intrinsics[:2, :] /= 4.0
depth_min = float(lines[11].split()[0])
depth_max = float(lines[11].split()[1])
return intrinsics, extrinsics, depth_min, depth_max
def read_img(self, filename):
img = Image.open(filename)
# scale 0~255 to 0~1
np_img = np.array(img, dtype=np.float32) / 255.
return np_img
def read_img_seg(self, filename):
img = Image.open(filename)
return self.transform_seg(img)
def read_img_aug(self, filename):
img = Image.open(filename)
img = self.transform_aug(img)
return img
def read_depth(self, filename):
# read pfm depth file
return np.array(read_pfm(filename)[0], dtype=np.float32)
def scale_mvs_input(self, img, intrinsics, max_w, max_h, base=32):
h, w = img.shape[:2]
# if h > max_h or w > max_w:
# scale = 1.0 * max_h / h
# if scale * w > max_w:
# scale = 1.0 * max_w / w
# new_w, new_h = scale * w // base * base, scale * h // base * base
# else:
# new_w, new_h = 1.0 * w // base * base, 1.0 * h // base * base
new_h, new_w = max_h, max_w
scale_w = 1.0 * new_w / w
scale_h = 1.0 * new_h / h
intrinsics[0, :] *= scale_w
intrinsics[1, :] *= scale_h
img = cv2.resize(img, (int(new_w), int(new_h)))
return img, intrinsics
def __len__(self):
return len(self.metas)
def __getitem__(self, idx):
global s_h, s_w
# scan, _, ref_view, src_views = self.metas[idx]
scan, ref_view, src_views, scene_name = self.metas[idx]
# use only the reference view and first nviews-1 source views
view_ids = [ref_view] + src_views[:self.nviews-1]
img_w, img_h = self.image_sizes[scan]
imgs = []
depth_values = None
proj_matrices = []
for i, vid in enumerate(view_ids):
img_filename = os.path.join(self.datapath, self.split, scan, f'images/{vid:08d}.jpg')
proj_mat_filename = os.path.join(self.datapath, self.split, scan, f'cams_1/{vid:08d}_cam.txt')
img = self.read_img(img_filename)
# img = self.read_img_seg(img_filename)
intrinsics, extrinsics, depth_min_, depth_max_ = self.read_cam_file(proj_mat_filename)
# scale input
# img, intrinsics = self.scale_mvs_input(img, intrinsics, self.max_w, self.max_h)
img, intrinsics = self.scale_mvs_input(img, intrinsics, self.img_wh[0], self.img_wh[1])
img = self.transform_seg(img)
imgs.append(img)
# extrinsics, intrinsics
proj_mat = np.zeros(shape=(2, 4, 4), dtype=np.float32) #
proj_mat[0, :4, :4] = extrinsics
proj_mat[1, :3, :3] = intrinsics
proj_matrices.append(proj_mat)
if i == 0: # reference view
depth_min = depth_min_
depth_max = depth_max_
depth_interval = (depth_max - depth_min) / (self.ndepths - 1)
depth_values = np.arange(depth_min, depth_interval * (self.ndepths - 0.5) + depth_min, depth_interval,
dtype=np.float32)
#all
# imgs = np.stack(imgs).transpose([0, 3, 1, 2])
imgs = np.stack(imgs)
proj_matrices = np.stack(proj_matrices)
stage2_pjmats = proj_matrices.copy()
stage2_pjmats[:, 1, :2, :] = proj_matrices[:, 1, :2, :] * 2
stage3_pjmats = proj_matrices.copy()
stage3_pjmats[:, 1, :2, :] = proj_matrices[:, 1, :2, :] * 4
proj_matrices_ms = {
"stage1": proj_matrices,
"stage2": stage2_pjmats,
"stage3": stage3_pjmats
}
return {"imgs": imgs,
"proj_matrices": proj_matrices_ms,
"depth_values": depth_values,
"filename": scan + '/{}/' + '{:0>8}'.format(view_ids[0]) + "{}"}
|
[
"numpy.stack",
"numpy.zeros",
"PIL.Image.open",
"numpy.array",
"numpy.arange",
"torchvision.transforms.Normalize",
"os.path.join",
"torchvision.transforms.ToTensor"
] |
[((3387, 3407), 'PIL.Image.open', 'Image.open', (['filename'], {}), '(filename)\n', (3397, 3407), False, 'from PIL import Image\n'), ((3570, 3590), 'PIL.Image.open', 'Image.open', (['filename'], {}), '(filename)\n', (3580, 3590), False, 'from PIL import Image\n'), ((3684, 3704), 'PIL.Image.open', 'Image.open', (['filename'], {}), '(filename)\n', (3694, 3704), False, 'from PIL import Image\n'), ((6510, 6524), 'numpy.stack', 'np.stack', (['imgs'], {}), '(imgs)\n', (6518, 6524), True, 'import numpy as np\n'), ((6549, 6572), 'numpy.stack', 'np.stack', (['proj_matrices'], {}), '(proj_matrices)\n', (6557, 6572), True, 'import numpy as np\n'), ((3454, 3485), 'numpy.array', 'np.array', (['img'], {'dtype': 'np.float32'}), '(img, dtype=np.float32)\n', (3462, 3485), True, 'import numpy as np\n'), ((5140, 5210), 'os.path.join', 'os.path.join', (['self.datapath', 'self.split', 'scan', 'f"""images/{vid:08d}.jpg"""'], {}), "(self.datapath, self.split, scan, f'images/{vid:08d}.jpg')\n", (5152, 5210), False, 'import os, cv2, time\n'), ((5243, 5317), 'os.path.join', 'os.path.join', (['self.datapath', 'self.split', 'scan', 'f"""cams_1/{vid:08d}_cam.txt"""'], {}), "(self.datapath, self.split, scan, f'cams_1/{vid:08d}_cam.txt')\n", (5255, 5317), False, 'import os, cv2, time\n'), ((5868, 5911), 'numpy.zeros', 'np.zeros', ([], {'shape': '(2, 4, 4)', 'dtype': 'np.float32'}), '(shape=(2, 4, 4), dtype=np.float32)\n', (5876, 5911), True, 'import numpy as np\n'), ((2531, 2552), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (2550, 2552), False, 'from torchvision import transforms\n'), ((2566, 2632), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['[0.485, 0.456, 0.406]', '[0.229, 0.224, 0.225]'], {}), '([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n', (2586, 2632), False, 'from torchvision import transforms\n'), ((6278, 6387), 'numpy.arange', 'np.arange', (['depth_min', '(depth_interval * (self.ndepths - 0.5) + depth_min)', 'depth_interval'], {'dtype': 'np.float32'}), '(depth_min, depth_interval * (self.ndepths - 0.5) + depth_min,\n depth_interval, dtype=np.float32)\n', (6287, 6387), True, 'import numpy as np\n'), ((1865, 1922), 'os.path.join', 'os.path.join', (['self.datapath', 'self.split', 'scan', '"""pair.txt"""'], {}), "(self.datapath, self.split, scan, 'pair.txt')\n", (1877, 1922), False, 'import os, cv2, time\n')]
|
import os
import json
import torch
import torch.nn as nn
import torch.optim as optim
import matplotlib.pyplot as plt
import argparse
import pandas as pd
import numpy as np
from blitz.modules import BayesianLSTM
from blitz.utils import variational_estimator
from load_data import DataLoader
from sklearn.metrics import accuracy_score, classification_report, hamming_loss, \
jaccard_score, roc_auc_score, zero_one_loss
from tqdm import tqdm
from random import seed, random
# load config file
with open(os.path.join(os.path.dirname(__file__), '../config.json')) as f:
config = json.load(f)
# load parameters
parser = argparse.ArgumentParser()
parser.add_argument("--name", type=str, default='BLSTM')
parser.add_argument("--train_model", type=bool, default=True)
parser.add_argument("--eval_model", type=bool, default=True)
parser.add_argument("--dropout", type=float, default=0.5)
parser.add_argument("--hidden_dim", type=int, default=128)
parser.add_argument("--num_layers", type=int, default=1)
parser.add_argument("--output_dim", type=int, default=1)
parser.add_argument("--class_weighting", type=bool, default=True)
parser.add_argument("--adaptive_sampling", type=bool, default=True)
parser.add_argument("--num_classes", type=int, default=8)
parser.add_argument("--sample_num", type=int, default=5)
parser.add_argument("--seed", type=int, default=1)
args = parser.parse_args()
seed(args.seed)
@variational_estimator
class BayesianLongShortTermMemory(nn.Module):
"""
Defines the architecture of a bayesian long short-term memory neural network.
"""
def __init__(self, input_dim):
"""
Initialises the bayesian LSTM model architecture. 5 stacked BLSTM layers and 8/18 binary output nodes
for each activity class.
Parameters:
input_dim: int
Number of input features that will be passed into the model.
"""
super(BayesianLongShortTermMemory, self).__init__()
# define number of layers and nodes in each layer
self.input_dim = input_dim
self.hidden_dim = args.hidden_dim
self.num_layers = args.num_layers
# Bayesian LSTM layer
self.blstm1 = BayesianLSTM(self.input_dim, self.hidden_dim)
self.blstm2 = BayesianLSTM(self.hidden_dim, self.hidden_dim)
self.blstm3 = BayesianLSTM(self.hidden_dim, self.hidden_dim)
self.blstm4 = BayesianLSTM(self.hidden_dim, self.hidden_dim)
self.blstm5 = BayesianLSTM(self.hidden_dim, self.hidden_dim)
# fully connected output layer for each activity class
self.out1 = nn.Linear(self.hidden_dim, args.output_dim)
self.out2 = nn.Linear(self.hidden_dim, args.output_dim)
self.out3 = nn.Linear(self.hidden_dim, args.output_dim)
self.out4 = nn.Linear(self.hidden_dim, args.output_dim)
self.out5 = nn.Linear(self.hidden_dim, args.output_dim)
self.out6 = nn.Linear(self.hidden_dim, args.output_dim)
self.out7 = nn.Linear(self.hidden_dim, args.output_dim)
self.out8 = nn.Linear(self.hidden_dim, args.output_dim)
def forward(self, x):
"""
Performs forward pass through the LSTM layers.
Parameters:
x: torch.tensor
Input features of the model.
Returns:
out1, out2, out3, out4, out5, out6, out7, out8: torch.tensor
Model output for each activity class.
"""
# initialise hidden state for first input with zeros
hidden_0 = torch.zeros(self.num_layers, x.size(0), self.hidden_dim).requires_grad_()
print('hidden_0 size: {}'.format(hidden_0.size()))
print('hidden_0 detach size: {}'.format(hidden_0.detach().size()))
# initialise cell state for first input with zeros
cell_0 = torch.zeros(self.num_layers, x.size(0), self.hidden_dim).requires_grad_()
print('cell_0 size: {}'.format(cell_0.size()))
print('cell_0 detach size: {}'.format(cell_0.detach().size()))
# forward propagation by passing input, hidden state and cell state into model
x, (hidden_1, cell_1) = self.blstm1(x, (hidden_0.detach(), cell_0.detach()))
print('hidden_1 size: {}'.format(hidden_1.size()))
print('hidden_1 detach size: {}'.format(hidden_1.detach().size()))
print('cell_1 size: {}'.format(cell_1.size()))
print('cell_1 detach size: {}'.format(cell_1.detach().size()))
x, (hidden_2, cell_2) = self.blstm2(x, (hidden_1, cell_1))
x, (hidden_3, cell_3) = self.blstm3(x, (hidden_2, cell_2))
x, (hidden_4, cell_4) = self.blstm4(x, (hidden_3, cell_3))
x, _ = self.blstm5(x, (hidden_4, cell_4))
# reshape output which has shape (batch_size, seq_length, hidden size) to fit into FC layer
x = x[:, -1, :]
# a binary classifier output node for each activity class
out1 = torch.sigmoid(self.out1(x))
out2 = torch.sigmoid(self.out2(x))
out3 = torch.sigmoid(self.out3(x))
out4 = torch.sigmoid(self.out4(x))
out5 = torch.sigmoid(self.out5(x))
out6 = torch.sigmoid(self.out6(x))
out7 = torch.sigmoid(self.out7(x))
out8 = torch.sigmoid(self.out8(x))
return out1.float(), out2.float(), out3.float(), out4.float(), out5.float(), \
out6.float(), out7.float(), out8.float()
def calculate_loss(self, output, target):
"""
Calculates the loss value for each activity class and sums them up.
Parameters:
output: torch.tensor
Predicted outputs of the model.
target: torch.tensor
Target outputs.
Returns:
sum_loss: float
Binary cross entropy loss of model output for all activity classes.
"""
out1, out2, out3, out4, out5, out6, out7, out8 = output
t1, t2, t3, t4, t5, t6, t7, t8 = target
loss1 = nn.BCELoss()(out1, torch.reshape(t1, (-1, 1))).float()
loss2 = nn.BCELoss()(out2, torch.reshape(t2, (-1, 1))).float()
loss3 = nn.BCELoss()(out3, torch.reshape(t3, (-1, 1))).float()
loss4 = nn.BCELoss()(out4, torch.reshape(t4, (-1, 1))).float()
loss5 = nn.BCELoss()(out5, torch.reshape(t5, (-1, 1))).float()
loss6 = nn.BCELoss()(out6, torch.reshape(t6, (-1, 1))).float()
loss7 = nn.BCELoss()(out7, torch.reshape(t7, (-1, 1))).float()
loss8 = nn.BCELoss()(out8, torch.reshape(t8, (-1, 1))).float()
if args.class_weighting:
sum_loss = loss1 * delivercargo_weight + loss2 * pickupcargo_weight + \
loss3 * other_weight + loss4 * shift_weight + \
loss5 * break_weight + loss6 * dropofftrailer_weight + \
loss7 * pickuptrailer_weight + loss8 * maintenance_weight
else:
sum_loss = loss1 + loss2 + loss3 + loss4 + loss5 + loss6 + loss7 + loss8
return sum_loss
def train(model, optimiser, train_features, train_target, device):
"""
Train the model in batches for one epoch.
Parameters:
model: LongShortTermMemory object
Contains the model architecture of the LSTM.
optimiser: optimiser.Adam
Contains the optimiser for the model.
train_features: pd.Dataframe
Contain the input features for the training dataset.
train_target: pd.Dataframe
Contain the true labels for the training dataset.
device: torch.device
Indicates whether the model will be trained using CPU or CUDA.
Returns:
train_loss: float
Contains the average training loss for this epoch.
"""
model.train()
train_loss = 0.0
for i in tqdm(range(len(train_features) // config['batch_size'])):
batch_features = torch.tensor(
train_features.iloc[i*config['batch_size']: (i+1)*config['batch_size']].values
).view([config['batch_size'], -1, model.input_dim]).to(device)
batch_target = train_target.iloc[i*config['batch_size']: (i+1)*config['batch_size']]
delivercargo_target = torch.tensor(batch_target['MappedActivity.DeliverCargo'].values).to(device)
pickupcargo_target = torch.tensor(batch_target['MappedActivity.PickupCargo'].values).to(device)
other_target = torch.tensor(batch_target['MappedActivity.Other'].values).to(device)
shift_target = torch.tensor(batch_target['MappedActivity.Shift'].values).to(device)
break_target = torch.tensor(batch_target['MappedActivity.Break'].values).to(device)
dropofftrailer_target = torch.tensor(batch_target['MappedActivity.DropoffTrailerContainer'].values).to(device)
pickuptrailer_target = torch.tensor(batch_target['MappedActivity.PickupTrailerContainer'].values).to(device)
maintenance_target = torch.tensor(batch_target['MappedActivity.Maintenance'].values).to(device)
# reset optimiser gradient to zero
optimiser.zero_grad()
# perform inference and compute loss
target = (delivercargo_target.float(), pickupcargo_target.float(), other_target.float(),
shift_target.float(), break_target.float(), dropofftrailer_target.float(),
pickuptrailer_target.float(), maintenance_target.float())
# calculate loss based on average of each sample
for _ in range(args.sample_num):
output = model(batch_features.float())
loss = model.calculate_loss(output, target)
train_loss += loss.item() / args.sample_num
# perform backpropagation
loss.backward()
# update model parameters
optimiser.step()
# find the average loss of all batches in this epoch
train_loss = train_loss / (len(train_features) // config['batch_size'])
return train_loss
def plot_train_loss(train_loss):
"""
Plot training loss and save the figure locally.
Parameters:
train_loss: list
Contains the training loss for each epoch.
"""
plt.figure(figsize=(10, 7))
plt.plot(train_loss, color='orange')
plt.xlabel('Epochs')
plt.ylabel('Cross-entropy Loss')
if not os.path.exists(os.path.join(os.path.dirname(__file__), config['figures_directory'])):
os.makedirs(os.path.join(os.path.dirname(__file__), config['figures_directory']))
plt.savefig(os.path.join(os.path.dirname(__file__),
config['figures_directory'] + 'train_loss_{}.png'.format(args.name)))
plt.show()
def inference(model, input_features):
"""
Performs inference on the input features.
Parameters:
model: BayesianLongShortTermMemory object
Contains the model architecture of the Bayesian LSTM model.
input_features:
Contains the input features to be passed into the model for inference.
Returns:
final_labels: np.array
Contains the activity labels inferred by the model based on the input features.
"""
final_outputs = None
for i in tqdm(range(len(input_features) // config['batch_size'])):
batch_features = torch.tensor(
input_features.iloc[i*config['batch_size']: (i+1)*config['batch_size']].values
).view([config['batch_size'], -1, model.input_dim]).float().to(device)
batch_outputs = np.zeros((batch_features.size()[0], args.num_classes))
for _ in range(args.sample_num):
outputs = model(batch_features)
for j in range(len(outputs)):
batch_outputs[:, j] += outputs[j].cpu().detach().numpy().reshape(-1) / args.sample_num
if final_outputs is None:
final_outputs = batch_outputs
else:
final_outputs = np.vstack((final_outputs, batch_outputs))
final_labels = np.where(final_outputs < 0.5, 0, 1)
return final_labels
def print_evaluation_results(true_labels, pred_labels):
"""
Evaluates the performance of the trained model based on different multi-label classification metrics.
Parameters:
true_labels: pd.Dataframe
Contains the target labels.
pred_labels: torch.tensor
Contains the model's predicted labels.
"""
# generate evaluation scores
print('Bayesian Long Short-Term Memory')
activity_labels = [col.replace('MappedActivity.', '') for col in true_labels.columns]
pred_labels = pd.DataFrame(pred_labels, columns=true_labels.columns)
print('Classes: {}'.format(activity_labels))
print('Accuracy: {}'.format(accuracy_score(true_labels, pred_labels)))
print('Hamming Loss: {}'.format(hamming_loss(true_labels, pred_labels)))
print('Jaccard Score')
print(jaccard_score(true_labels, pred_labels, average=None))
print(jaccard_score(true_labels, pred_labels, average=True))
print('ROC AUC Score')
print(roc_auc_score(true_labels, pred_labels))
print('Zero One Loss: {}'.format(zero_one_loss(true_labels, pred_labels)))
print('Classification Report:')
print(classification_report(true_labels, pred_labels, target_names=activity_labels, zero_division=0))
return None
if __name__ == '__main__':
# load training and test datasets
loader = DataLoader()
train_data, test_data = loader.train_test_split(test_ratio=0.25)
# define features of interest
features = ['DriverID', 'Duration', 'StartHour', 'DayOfWeek.', 'PlaceType.', 'Commodity.',
'SpecialCargo.', 'Company.Type.', 'Industry.', 'VehicleType.', 'NumPOIs', 'POI.',
'LandUse.', 'Other.MappedActivity.', 'Past.MappedActivity.']
feature_cols = [col for col in train_data.columns
for feature in features
if feature in col]
# original activity types
# activity_cols = ['Activity.PickupTrailer', 'Activity.Passenger', 'Activity.Fueling', 'Activity.OtherWork',
# 'Activity.DropoffTrailer', 'Activity.Resting', 'Activity.Personal', 'Activity.Shift',
# 'Activity.ProvideService', 'Activity.DropoffContainer', 'Activity.Queuing', 'Activity.Other',
# 'Activity.DeliverCargo', 'Activity.Maintenance', 'Activity.Fail', 'Activity.PickupCargo',
# 'Activity.Meal', 'Activity.PickupContainer']
# mapped activity types
activity_cols = ['MappedActivity.DeliverCargo', 'MappedActivity.PickupCargo', 'MappedActivity.Other',
'MappedActivity.Shift', 'MappedActivity.Break', 'MappedActivity.DropoffTrailerContainer',
'MappedActivity.PickupTrailerContainer', 'MappedActivity.Maintenance']
train_x = train_data[feature_cols]
train_y = train_data[activity_cols]
test_x = test_data[feature_cols]
test_y = test_data[activity_cols]
# introduce class weights based on inverse of class frequency
delivercargo_weight = len(train_x) / (len(activity_cols) * train_y['MappedActivity.DeliverCargo'].sum())
pickupcargo_weight = len(train_x) / (len(activity_cols) * train_y['MappedActivity.PickupCargo'].sum())
other_weight = len(train_x) / (len(activity_cols) * train_y['MappedActivity.Other'].sum())
shift_weight = len(train_x) / (len(activity_cols) * train_y['MappedActivity.Shift'].sum())
break_weight = len(train_x) / (len(activity_cols) * train_y['MappedActivity.Break'].sum())
dropofftrailer_weight = len(train_x) / (
len(activity_cols) * train_y['MappedActivity.DropoffTrailerContainer'].sum())
pickuptrailer_weight = len(train_x) / (len(activity_cols) * train_y['MappedActivity.PickupTrailerContainer'].sum())
maintenance_weight = len(train_x) / (len(activity_cols) * train_y['MappedActivity.Maintenance'].sum())
if args.train_model: # perform model training
# initialise model architecture
model = BayesianLongShortTermMemory(input_dim=len(feature_cols))
# initialise optimiser and learning parameters
optimiser = optim.Adam(params=model.parameters(), lr=config['lstm_learning_rate'])
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model.to(device)
# train model
epoch_train_loss = []
for epoch in range(config['epochs']):
print('Epoch {}/{}'.format(epoch+1, config['epochs']))
epoch_loss = train(model, optimiser, train_x, train_y, device)
epoch_train_loss.append(epoch_loss)
print('Epoch loss: {}'.format(epoch_loss))
# save trained model
torch.save(model.state_dict(),
os.path.join(os.path.dirname(__file__),
config['activity_models_directory'] + 'model_{}.pth'.format(args.name)))
# plot train loss graph
plot_train_loss(epoch_train_loss)
if args.eval_model: # perform inference on test dataset and evaluate model performance
model = BayesianLongShortTermMemory(input_dim=len(feature_cols))
model.load_state_dict(torch.load(os.path.join(os.path.dirname(__file__),
config['activity_models_directory'] +
'model_{}.pth'.format(args.name))))
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model.to(device)
model.eval()
train_pred = inference(model, train_x)
print('Training Result')
print_evaluation_results(train_y.iloc[:train_pred.shape[0]], train_pred)
test_pred = inference(model, test_x)
print('Test Result')
print_evaluation_results(test_y.iloc[:test_pred.shape[0]], test_pred)
|
[
"argparse.ArgumentParser",
"sklearn.metrics.accuracy_score",
"sklearn.metrics.classification_report",
"sklearn.metrics.jaccard_score",
"matplotlib.pyplot.figure",
"load_data.DataLoader",
"matplotlib.pyplot.xlabel",
"pandas.DataFrame",
"torch.nn.BCELoss",
"os.path.dirname",
"random.seed",
"torch.nn.Linear",
"matplotlib.pyplot.show",
"sklearn.metrics.roc_auc_score",
"torch.cuda.is_available",
"matplotlib.pyplot.ylabel",
"torch.reshape",
"sklearn.metrics.hamming_loss",
"numpy.vstack",
"json.load",
"matplotlib.pyplot.plot",
"sklearn.metrics.zero_one_loss",
"numpy.where",
"blitz.modules.BayesianLSTM",
"torch.tensor"
] |
[((625, 650), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (648, 650), False, 'import argparse\n'), ((1389, 1404), 'random.seed', 'seed', (['args.seed'], {}), '(args.seed)\n', (1393, 1404), False, 'from random import seed, random\n'), ((584, 596), 'json.load', 'json.load', (['f'], {}), '(f)\n', (593, 596), False, 'import json\n'), ((10054, 10081), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 7)'}), '(figsize=(10, 7))\n', (10064, 10081), True, 'import matplotlib.pyplot as plt\n'), ((10086, 10122), 'matplotlib.pyplot.plot', 'plt.plot', (['train_loss'], {'color': '"""orange"""'}), "(train_loss, color='orange')\n", (10094, 10122), True, 'import matplotlib.pyplot as plt\n'), ((10127, 10147), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Epochs"""'], {}), "('Epochs')\n", (10137, 10147), True, 'import matplotlib.pyplot as plt\n'), ((10152, 10184), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Cross-entropy Loss"""'], {}), "('Cross-entropy Loss')\n", (10162, 10184), True, 'import matplotlib.pyplot as plt\n'), ((10533, 10543), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (10541, 10543), True, 'import matplotlib.pyplot as plt\n'), ((11825, 11860), 'numpy.where', 'np.where', (['(final_outputs < 0.5)', '(0)', '(1)'], {}), '(final_outputs < 0.5, 0, 1)\n', (11833, 11860), True, 'import numpy as np\n'), ((12427, 12481), 'pandas.DataFrame', 'pd.DataFrame', (['pred_labels'], {'columns': 'true_labels.columns'}), '(pred_labels, columns=true_labels.columns)\n', (12439, 12481), True, 'import pandas as pd\n'), ((13235, 13247), 'load_data.DataLoader', 'DataLoader', ([], {}), '()\n', (13245, 13247), False, 'from load_data import DataLoader\n'), ((2191, 2236), 'blitz.modules.BayesianLSTM', 'BayesianLSTM', (['self.input_dim', 'self.hidden_dim'], {}), '(self.input_dim, self.hidden_dim)\n', (2203, 2236), False, 'from blitz.modules import BayesianLSTM\n'), ((2259, 2305), 'blitz.modules.BayesianLSTM', 'BayesianLSTM', (['self.hidden_dim', 'self.hidden_dim'], {}), '(self.hidden_dim, self.hidden_dim)\n', (2271, 2305), False, 'from blitz.modules import BayesianLSTM\n'), ((2328, 2374), 'blitz.modules.BayesianLSTM', 'BayesianLSTM', (['self.hidden_dim', 'self.hidden_dim'], {}), '(self.hidden_dim, self.hidden_dim)\n', (2340, 2374), False, 'from blitz.modules import BayesianLSTM\n'), ((2397, 2443), 'blitz.modules.BayesianLSTM', 'BayesianLSTM', (['self.hidden_dim', 'self.hidden_dim'], {}), '(self.hidden_dim, self.hidden_dim)\n', (2409, 2443), False, 'from blitz.modules import BayesianLSTM\n'), ((2466, 2512), 'blitz.modules.BayesianLSTM', 'BayesianLSTM', (['self.hidden_dim', 'self.hidden_dim'], {}), '(self.hidden_dim, self.hidden_dim)\n', (2478, 2512), False, 'from blitz.modules import BayesianLSTM\n'), ((2597, 2640), 'torch.nn.Linear', 'nn.Linear', (['self.hidden_dim', 'args.output_dim'], {}), '(self.hidden_dim, args.output_dim)\n', (2606, 2640), True, 'import torch.nn as nn\n'), ((2661, 2704), 'torch.nn.Linear', 'nn.Linear', (['self.hidden_dim', 'args.output_dim'], {}), '(self.hidden_dim, args.output_dim)\n', (2670, 2704), True, 'import torch.nn as nn\n'), ((2725, 2768), 'torch.nn.Linear', 'nn.Linear', (['self.hidden_dim', 'args.output_dim'], {}), '(self.hidden_dim, args.output_dim)\n', (2734, 2768), True, 'import torch.nn as nn\n'), ((2789, 2832), 'torch.nn.Linear', 'nn.Linear', (['self.hidden_dim', 'args.output_dim'], {}), '(self.hidden_dim, args.output_dim)\n', (2798, 2832), True, 'import torch.nn as nn\n'), ((2853, 2896), 'torch.nn.Linear', 'nn.Linear', (['self.hidden_dim', 'args.output_dim'], {}), '(self.hidden_dim, args.output_dim)\n', (2862, 2896), True, 'import torch.nn as nn\n'), ((2917, 2960), 'torch.nn.Linear', 'nn.Linear', (['self.hidden_dim', 'args.output_dim'], {}), '(self.hidden_dim, args.output_dim)\n', (2926, 2960), True, 'import torch.nn as nn\n'), ((2981, 3024), 'torch.nn.Linear', 'nn.Linear', (['self.hidden_dim', 'args.output_dim'], {}), '(self.hidden_dim, args.output_dim)\n', (2990, 3024), True, 'import torch.nn as nn\n'), ((3045, 3088), 'torch.nn.Linear', 'nn.Linear', (['self.hidden_dim', 'args.output_dim'], {}), '(self.hidden_dim, args.output_dim)\n', (3054, 3088), True, 'import torch.nn as nn\n'), ((12720, 12773), 'sklearn.metrics.jaccard_score', 'jaccard_score', (['true_labels', 'pred_labels'], {'average': 'None'}), '(true_labels, pred_labels, average=None)\n', (12733, 12773), False, 'from sklearn.metrics import accuracy_score, classification_report, hamming_loss, jaccard_score, roc_auc_score, zero_one_loss\n'), ((12785, 12838), 'sklearn.metrics.jaccard_score', 'jaccard_score', (['true_labels', 'pred_labels'], {'average': '(True)'}), '(true_labels, pred_labels, average=True)\n', (12798, 12838), False, 'from sklearn.metrics import accuracy_score, classification_report, hamming_loss, jaccard_score, roc_auc_score, zero_one_loss\n'), ((12877, 12916), 'sklearn.metrics.roc_auc_score', 'roc_auc_score', (['true_labels', 'pred_labels'], {}), '(true_labels, pred_labels)\n', (12890, 12916), False, 'from sklearn.metrics import accuracy_score, classification_report, hamming_loss, jaccard_score, roc_auc_score, zero_one_loss\n'), ((13043, 13142), 'sklearn.metrics.classification_report', 'classification_report', (['true_labels', 'pred_labels'], {'target_names': 'activity_labels', 'zero_division': '(0)'}), '(true_labels, pred_labels, target_names=\n activity_labels, zero_division=0)\n', (13064, 13142), False, 'from sklearn.metrics import accuracy_score, classification_report, hamming_loss, jaccard_score, roc_auc_score, zero_one_loss\n'), ((519, 544), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (534, 544), False, 'import os\n'), ((10403, 10428), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (10418, 10428), False, 'import os\n'), ((11763, 11804), 'numpy.vstack', 'np.vstack', (['(final_outputs, batch_outputs)'], {}), '((final_outputs, batch_outputs))\n', (11772, 11804), True, 'import numpy as np\n'), ((12563, 12603), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['true_labels', 'pred_labels'], {}), '(true_labels, pred_labels)\n', (12577, 12603), False, 'from sklearn.metrics import accuracy_score, classification_report, hamming_loss, jaccard_score, roc_auc_score, zero_one_loss\n'), ((12642, 12680), 'sklearn.metrics.hamming_loss', 'hamming_loss', (['true_labels', 'pred_labels'], {}), '(true_labels, pred_labels)\n', (12654, 12680), False, 'from sklearn.metrics import accuracy_score, classification_report, hamming_loss, jaccard_score, roc_auc_score, zero_one_loss\n'), ((12955, 12994), 'sklearn.metrics.zero_one_loss', 'zero_one_loss', (['true_labels', 'pred_labels'], {}), '(true_labels, pred_labels)\n', (12968, 12994), False, 'from sklearn.metrics import accuracy_score, classification_report, hamming_loss, jaccard_score, roc_auc_score, zero_one_loss\n'), ((8131, 8195), 'torch.tensor', 'torch.tensor', (["batch_target['MappedActivity.DeliverCargo'].values"], {}), "(batch_target['MappedActivity.DeliverCargo'].values)\n", (8143, 8195), False, 'import torch\n'), ((8236, 8299), 'torch.tensor', 'torch.tensor', (["batch_target['MappedActivity.PickupCargo'].values"], {}), "(batch_target['MappedActivity.PickupCargo'].values)\n", (8248, 8299), False, 'import torch\n'), ((8334, 8391), 'torch.tensor', 'torch.tensor', (["batch_target['MappedActivity.Other'].values"], {}), "(batch_target['MappedActivity.Other'].values)\n", (8346, 8391), False, 'import torch\n'), ((8426, 8483), 'torch.tensor', 'torch.tensor', (["batch_target['MappedActivity.Shift'].values"], {}), "(batch_target['MappedActivity.Shift'].values)\n", (8438, 8483), False, 'import torch\n'), ((8518, 8575), 'torch.tensor', 'torch.tensor', (["batch_target['MappedActivity.Break'].values"], {}), "(batch_target['MappedActivity.Break'].values)\n", (8530, 8575), False, 'import torch\n'), ((8619, 8694), 'torch.tensor', 'torch.tensor', (["batch_target['MappedActivity.DropoffTrailerContainer'].values"], {}), "(batch_target['MappedActivity.DropoffTrailerContainer'].values)\n", (8631, 8694), False, 'import torch\n'), ((8737, 8811), 'torch.tensor', 'torch.tensor', (["batch_target['MappedActivity.PickupTrailerContainer'].values"], {}), "(batch_target['MappedActivity.PickupTrailerContainer'].values)\n", (8749, 8811), False, 'import torch\n'), ((8852, 8915), 'torch.tensor', 'torch.tensor', (["batch_target['MappedActivity.Maintenance'].values"], {}), "(batch_target['MappedActivity.Maintenance'].values)\n", (8864, 8915), False, 'import torch\n'), ((10225, 10250), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (10240, 10250), False, 'import os\n'), ((10316, 10341), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (10331, 10341), False, 'import os\n'), ((16083, 16108), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (16106, 16108), False, 'import torch\n'), ((16591, 16616), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (16606, 16616), False, 'import os\n'), ((17267, 17292), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (17290, 17292), False, 'import torch\n'), ((5934, 5946), 'torch.nn.BCELoss', 'nn.BCELoss', ([], {}), '()\n', (5944, 5946), True, 'import torch.nn as nn\n'), ((5953, 5979), 'torch.reshape', 'torch.reshape', (['t1', '(-1, 1)'], {}), '(t1, (-1, 1))\n', (5966, 5979), False, 'import torch\n'), ((6005, 6017), 'torch.nn.BCELoss', 'nn.BCELoss', ([], {}), '()\n', (6015, 6017), True, 'import torch.nn as nn\n'), ((6024, 6050), 'torch.reshape', 'torch.reshape', (['t2', '(-1, 1)'], {}), '(t2, (-1, 1))\n', (6037, 6050), False, 'import torch\n'), ((6076, 6088), 'torch.nn.BCELoss', 'nn.BCELoss', ([], {}), '()\n', (6086, 6088), True, 'import torch.nn as nn\n'), ((6095, 6121), 'torch.reshape', 'torch.reshape', (['t3', '(-1, 1)'], {}), '(t3, (-1, 1))\n', (6108, 6121), False, 'import torch\n'), ((6147, 6159), 'torch.nn.BCELoss', 'nn.BCELoss', ([], {}), '()\n', (6157, 6159), True, 'import torch.nn as nn\n'), ((6166, 6192), 'torch.reshape', 'torch.reshape', (['t4', '(-1, 1)'], {}), '(t4, (-1, 1))\n', (6179, 6192), False, 'import torch\n'), ((6218, 6230), 'torch.nn.BCELoss', 'nn.BCELoss', ([], {}), '()\n', (6228, 6230), True, 'import torch.nn as nn\n'), ((6237, 6263), 'torch.reshape', 'torch.reshape', (['t5', '(-1, 1)'], {}), '(t5, (-1, 1))\n', (6250, 6263), False, 'import torch\n'), ((6289, 6301), 'torch.nn.BCELoss', 'nn.BCELoss', ([], {}), '()\n', (6299, 6301), True, 'import torch.nn as nn\n'), ((6308, 6334), 'torch.reshape', 'torch.reshape', (['t6', '(-1, 1)'], {}), '(t6, (-1, 1))\n', (6321, 6334), False, 'import torch\n'), ((6360, 6372), 'torch.nn.BCELoss', 'nn.BCELoss', ([], {}), '()\n', (6370, 6372), True, 'import torch.nn as nn\n'), ((6379, 6405), 'torch.reshape', 'torch.reshape', (['t7', '(-1, 1)'], {}), '(t7, (-1, 1))\n', (6392, 6405), False, 'import torch\n'), ((6431, 6443), 'torch.nn.BCELoss', 'nn.BCELoss', ([], {}), '()\n', (6441, 6443), True, 'import torch.nn as nn\n'), ((6450, 6476), 'torch.reshape', 'torch.reshape', (['t8', '(-1, 1)'], {}), '(t8, (-1, 1))\n', (6463, 6476), False, 'import torch\n'), ((17018, 17043), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (17033, 17043), False, 'import os\n'), ((7832, 7934), 'torch.tensor', 'torch.tensor', (["train_features.iloc[i * config['batch_size']:(i + 1) * config['batch_size']\n ].values"], {}), "(train_features.iloc[i * config['batch_size']:(i + 1) * config[\n 'batch_size']].values)\n", (7844, 7934), False, 'import torch\n'), ((11150, 11252), 'torch.tensor', 'torch.tensor', (["input_features.iloc[i * config['batch_size']:(i + 1) * config['batch_size']\n ].values"], {}), "(input_features.iloc[i * config['batch_size']:(i + 1) * config[\n 'batch_size']].values)\n", (11162, 11252), False, 'import torch\n')]
|
import numpy as np
from ..metrics import mse, mse_grad
from .mv_splines import mv_b_spline_vector, mv_spline_grad
from tqdm import trange
from scipy.sparse import coo_matrix
def fit_spline(x_train, y_train,
x_val, y_val,
regressor,
optimizer,
knot_init=None,
p=None,
k=None,
max_iters=100,
patience=25,
batch_size=None,
verbose=False
):
num_of_vars = 1 if np.ndim(x_train) == 1 else x_train.shape[-1]
if p is None and knot_init is None:
p = np.array([1 for _ in range(num_of_vars)], dtype=np.int)
if k is None:
k = np.array([2 for _ in range(num_of_vars)], dtype=np.int)
if knot_init is None:
u = [np.array([i / (p_ + 1) for i in range(1, p_ + 1)]) for p_ in p]
else:
if not(knot_init is None):
u = knot_init #if num_of_vars > 1 else [knot_init]
u_history = {d+1: [np.array(u[d], dtype='float')] for d in range(num_of_vars)}
b_splines_train = mv_b_spline_vector(x_train.reshape(-1, 1), u, k) if num_of_vars == 1 \
else mv_b_spline_vector(x_train, u, k)
regressor.fit(coo_matrix(b_splines_train), y_train)
c = regressor.coef_
c_history = [c]
y_train_hat = regressor.predict(b_splines_train)
b_splines_val = mv_b_spline_vector(x_val.reshape(-1, 1), u, k) if num_of_vars == 1\
else mv_b_spline_vector(x_val, u, k)
y_val_hat = regressor.predict(b_splines_val)
mse_train = mse(y_train, y_train_hat)
mse_val = mse(y_val, y_val_hat)
r2_train = regressor.score(b_splines_train, y_train)
r2_val = regressor.score(b_splines_val, y_val)
mse_train_history = [mse_train]
mse_val_history = [mse_val]
r2_train_history = [r2_train]
r2_val_history = [r2_val]
history = {'u': u_history, 'c': c_history, 'mse_train': mse_train_history, 'mse_val': mse_val_history,
'r2_train': r2_train_history, 'r2_val': r2_val_history}
best_index = 0
epochs_range = trange(max_iters) if verbose else range(max_iters)
for i in epochs_range:
if batch_size is None:
index_batches = [range(x_train.shape[0])]
else:
num_of_complete_batches = x_train.shape[0] // batch_size
shuffled_indices = np.random.permutation(x_train.shape[0])
index_batches = [shuffled_indices[batch_size * i:batch_size * (i + 1)] for i in
range(num_of_complete_batches)]
if batch_size * num_of_complete_batches < x_train.shape[0]:
index_batches.append(shuffled_indices[batch_size * num_of_complete_batches:])
for idx in index_batches:
x = x_train[idx]
y = y_train[idx]
basis_splines = mv_b_spline_vector(x.reshape(-1, 1), u, k) if num_of_vars == 1\
else mv_b_spline_vector(x, u, k)
regressor.fit(coo_matrix(basis_splines), y)
c = regressor.coef_
y_hat = regressor.predict(basis_splines)
dy = mv_spline_grad(x.reshape(-1, 1), u, k, c) if num_of_vars == 1\
else mv_spline_grad(x, u, k, c)
grad = mse_grad(y, y_hat, dy)
u = optimizer.step(u, grad)
b_splines_train = mv_b_spline_vector(x_train.reshape(-1, 1), u, k) if num_of_vars == 1\
else mv_b_spline_vector(x_train, u, k)
regressor.fit(coo_matrix(b_splines_train), y_train)
c = regressor.coef_
b_splines_val = mv_b_spline_vector(x_val.reshape(-1, 1), u, k) if num_of_vars == 1\
else mv_b_spline_vector(x_val, u, k)
y_val_hat = regressor.predict(b_splines_val)
y_train_hat = regressor.predict(b_splines_train)
mse_train = mse(y_train, y_train_hat)
mse_val = mse(y_val, y_val_hat)
r2_train = regressor.score(b_splines_train, y_train)
r2_val = regressor.score(b_splines_val, y_val)
for d in range(num_of_vars):
history['u'][d+1].append(np.array(u[d], dtype='float'))
history['c'].append(c)
history['mse_train'].append(mse_train)
history['mse_val'].append(mse_val)
history['r2_train'].append(r2_train)
history['r2_val'].append(r2_val)
best_index = int(np.argmin(np.array(history['mse_val'])))
# Early Stopping:
if not (patience is None) and i >= patience and best_index <= i - patience:
break
u_best = [history['u'][d+1][best_index] for d in range(num_of_vars)]
b_splines_train = mv_b_spline_vector(x_train.reshape(-1, 1), u_best, k) if num_of_vars == 1 \
else mv_b_spline_vector(x_train, u_best, k)
regressor.fit(coo_matrix(b_splines_train), y_train)
return best_index, regressor, history
|
[
"tqdm.trange",
"numpy.ndim",
"scipy.sparse.coo_matrix",
"numpy.array",
"numpy.random.permutation"
] |
[((1223, 1250), 'scipy.sparse.coo_matrix', 'coo_matrix', (['b_splines_train'], {}), '(b_splines_train)\n', (1233, 1250), False, 'from scipy.sparse import coo_matrix\n'), ((2075, 2092), 'tqdm.trange', 'trange', (['max_iters'], {}), '(max_iters)\n', (2081, 2092), False, 'from tqdm import trange\n'), ((528, 544), 'numpy.ndim', 'np.ndim', (['x_train'], {}), '(x_train)\n', (535, 544), True, 'import numpy as np\n'), ((1003, 1032), 'numpy.array', 'np.array', (['u[d]'], {'dtype': '"""float"""'}), "(u[d], dtype='float')\n", (1011, 1032), True, 'import numpy as np\n'), ((2353, 2392), 'numpy.random.permutation', 'np.random.permutation', (['x_train.shape[0]'], {}), '(x_train.shape[0])\n', (2374, 2392), True, 'import numpy as np\n'), ((3468, 3495), 'scipy.sparse.coo_matrix', 'coo_matrix', (['b_splines_train'], {}), '(b_splines_train)\n', (3478, 3495), False, 'from scipy.sparse import coo_matrix\n'), ((4754, 4781), 'scipy.sparse.coo_matrix', 'coo_matrix', (['b_splines_train'], {}), '(b_splines_train)\n', (4764, 4781), False, 'from scipy.sparse import coo_matrix\n'), ((2972, 2997), 'scipy.sparse.coo_matrix', 'coo_matrix', (['basis_splines'], {}), '(basis_splines)\n', (2982, 2997), False, 'from scipy.sparse import coo_matrix\n'), ((4062, 4091), 'numpy.array', 'np.array', (['u[d]'], {'dtype': '"""float"""'}), "(u[d], dtype='float')\n", (4070, 4091), True, 'import numpy as np\n'), ((4335, 4363), 'numpy.array', 'np.array', (["history['mse_val']"], {}), "(history['mse_val'])\n", (4343, 4363), True, 'import numpy as np\n')]
|
# MIT License
#
# Copyright (c) 2020-2021 CNRS
#
# 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 math
import random
from collections import Counter
from typing import Callable, Iterable
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn.functional as F
from torch.nn import Parameter
from torch.optim import Optimizer
from torch_audiomentations.core.transforms_interface import BaseWaveformTransform
from typing_extensions import Literal
from pyannote.audio.core.io import Audio
from pyannote.audio.core.task import Problem, Resolution, Specifications, Task
from pyannote.audio.tasks.segmentation.mixins import SegmentationTaskMixin
from pyannote.audio.utils.permutation import permutate
from pyannote.audio.utils.random import create_rng_for_worker
from pyannote.core import Segment, SlidingWindow
from pyannote.database import Protocol
class Segmentation(SegmentationTaskMixin, Task):
"""Segmentation
Note that data augmentation is used to increase the proportion of "overlap".
This is achieved by generating chunks made out of the (weighted) sum of two
random chunks.
Parameters
----------
protocol : Protocol
pyannote.database protocol
duration : float, optional
Chunks duration. Defaults to 2s.
augmentation_probability : float, optional
Probability of artificial overlapping chunks. A probability of 0.6 means that,
on average, 40% of training chunks are "real" chunks, while 60% are artifical
chunks made out of the (weighted) sum of two chunks. Defaults to 0.5.
snr_min, snr_max : float, optional
Minimum and maximum signal-to-noise ratio between summed chunks, in dB.
Defaults to 0.0 and 10.
domain : str, optional
Indicate that data augmentation will only overlap chunks from the same domain
(i.e. share the same file[domain] value). Default behavior is to not contrain
data augmentation with regards to domain.
batch_size : int, optional
Number of training samples per batch. Defaults to 32.
num_workers : int, optional
Number of workers used for generating training samples.
Defaults to multiprocessing.cpu_count() // 2.
pin_memory : bool, optional
If True, data loaders will copy tensors into CUDA pinned
memory before returning them. See pytorch documentation
for more details. Defaults to False.
optimizer : callable, optional
Callable that takes model parameters as input and returns
an Optimizer instance. Defaults to `torch.optim.Adam`.
learning_rate : float, optional
Learning rate. Defaults to 1e-3.
augmentation : BaseWaveformTransform, optional
torch_audiomentations waveform transform, used by dataloader
during training.
vad_loss : {"bce", "mse"}, optional
Add voice activity detection loss.
"""
ACRONYM = "seg"
def __init__(
self,
protocol: Protocol,
duration: float = 2.0,
augmentation_probability: float = 0.5,
snr_min: float = 0.0,
snr_max: float = 10.0,
domain: str = None,
batch_size: int = 32,
num_workers: int = None,
pin_memory: bool = False,
optimizer: Callable[[Iterable[Parameter]], Optimizer] = None,
learning_rate: float = 1e-3,
augmentation: BaseWaveformTransform = None,
loss: Literal["bce", "mse"] = "bce",
vad_loss: Literal["bce", "mse"] = None,
):
super().__init__(
protocol,
duration=duration,
batch_size=batch_size,
num_workers=num_workers,
pin_memory=pin_memory,
optimizer=optimizer,
learning_rate=learning_rate,
augmentation=augmentation,
)
self.augmentation_probability = augmentation_probability
self.snr_min = snr_min
self.snr_max = snr_max
self.domain = domain
if loss not in ["bce", "mse"]:
raise ValueError("'loss' must be one of {'bce', 'mse'}.")
self.loss = loss
self.vad_loss = vad_loss
def setup(self, stage=None):
super().setup(stage=stage)
if stage == "fit":
# TODO: handle this domain thing in SegmentationTaskMixin
# build the list of domains
if self.domain is not None:
for f in self._train:
f["domain"] = f[self.domain]
self.domains = list(set(f["domain"] for f in self._train))
# slide a window (with 1s step) over the whole training set
# and keep track of the number of speakers in each location
num_speakers = []
for file in self._train:
start = file["annotated"][0].start
end = file["annotated"][-1].end
window = SlidingWindow(
start=start,
end=end,
duration=self.duration,
step=1.0,
)
for chunk in window:
num_speakers.append(len(file["annotation"].crop(chunk).labels()))
# because there might a few outliers, estimate the upper bound for the
# number of speakers as the 99th percentile
num_speakers, counts = zip(*list(Counter(num_speakers).items()))
num_speakers, counts = np.array(num_speakers), np.array(counts)
sorting_indices = np.argsort(num_speakers)
num_speakers = num_speakers[sorting_indices]
counts = counts[sorting_indices]
self.num_speakers = num_speakers[
np.where(np.cumsum(counts) / np.sum(counts) > 0.99)[0][0]
]
# TODO: add a few more speakers to make sure we don't skip
# too many artificial chunks (which might result in less
# overlap that we think we have)
# now that we know about the number of speakers upper bound
# we can set task specifications
self.specifications = Specifications(
problem=Problem.MULTI_LABEL_CLASSIFICATION,
resolution=Resolution.FRAME,
duration=self.duration,
classes=[f"speaker#{i+1}" for i in range(self.num_speakers)],
permutation_invariant=True,
)
def prepare_y(self, one_hot_y: np.ndarray):
"""Zero-pad segmentation targets
Parameters
----------
one_hot_y : (num_frames, num_speakers) np.ndarray
One-hot-encoding of current chunk speaker activity:
* one_hot_y[t, k] = 1 if kth speaker is active at tth frame
* one_hot_y[t, k] = 0 otherwise.
Returns
-------
padded_one_hot_y : (num_frames, self.num_speakers) np.ndarray
One-hot-encoding of current chunk speaker activity:
* one_hot_y[t, k] = 1 if kth speaker is active at tth frame
* one_hot_y[t, k] = 0 otherwise.
"""
num_frames, num_speakers = one_hot_y.shape
if num_speakers < self.num_speakers:
one_hot_y = np.pad(
one_hot_y, ((0, 0), (0, self.num_speakers - num_speakers))
)
return one_hot_y
def train__iter__helper(self, rng: random.Random, domain: str = None):
train = self._train
if domain is not None:
train = [f for f in train if f["domain"] == domain]
while True:
# select one file at random (with probability proportional to its annotated duration)
file, *_ = rng.choices(
train,
weights=[f["duration"] for f in train],
k=1,
)
# select one annotated region at random (with probability proportional to its duration)
segment, *_ = rng.choices(
file["annotated"],
weights=[s.duration for s in file["annotated"]],
k=1,
)
# select one chunk at random (with uniform distribution)
start_time = rng.uniform(segment.start, segment.end - self.duration)
chunk = Segment(start_time, start_time + self.duration)
yield self.prepare_chunk(file, chunk, duration=self.duration)
def train__iter__(self):
"""Iterate over training samples
Yields
------
X: (time, channel)
Audio chunks.
y: (frame, )
Frame-level targets. Note that frame < time.
`frame` is infered automagically from the
example model output.
"""
# create worker-specific random number generator
rng = create_rng_for_worker(self.model.current_epoch)
if self.domain is None:
chunks = self.train__iter__helper(rng)
else:
chunks_by_domain = {
domain: self.train__iter__helper(rng, domain=domain)
for domain in self.domains
}
while True:
if self.domain is not None:
# draw domain at random
domain = rng.choice(self.domains)
chunks = chunks_by_domain[domain]
# generate random chunk
X, one_hot_y, labels = next(chunks)
if rng.random() > self.augmentation_probability:
if one_hot_y.shape[1] > self.num_speakers:
# skip chunks that happen to have too many speakers
pass
else:
# pad and yield good ones
yield {"X": X, "y": self.prepare_y(one_hot_y)}
continue
# generate second random chunk
other_X, other_one_hot_y, other_labels = next(chunks)
# sum both chunks with random SNR
random_snr = (self.snr_max - self.snr_min) * rng.random() + self.snr_min
alpha = np.exp(-np.log(10) * random_snr / 20)
X = Audio.power_normalize(X) + alpha * Audio.power_normalize(other_X)
# combine speaker-to-index mapping
y_mapping = {label: i for i, label in enumerate(labels)}
num_labels = len(y_mapping)
for label in other_labels:
if label not in y_mapping:
y_mapping[label] = num_labels
num_labels += 1
# combine one-hot-encoded speaker activities
combined_y = np.zeros_like(one_hot_y, shape=(len(one_hot_y), num_labels))
for i, label in enumerate(labels):
combined_y[:, y_mapping[label]] += one_hot_y[:, i]
for i, label in enumerate(other_labels):
combined_y[:, y_mapping[label]] += other_one_hot_y[:, i]
# handle corner case when the same label is active at the same time in both chunks
combined_y = np.minimum(combined_y, 1, out=combined_y)
if combined_y.shape[1] > self.num_speakers:
# skip artificial chunks that happen to have too many speakers
pass
else:
# pad and yield good ones
yield {"X": X, "y": self.prepare_y(combined_y)}
def val__getitem__(self, idx):
f, chunk = self._validation[idx]
X, one_hot_y, _ = self.prepare_chunk(f, chunk, duration=self.duration)
# since number of speakers is estimated from the training set,
# we might encounter validation chunks that have more speakers.
# in that case, we arbirarily remove last speakers
if one_hot_y.shape[1] > self.num_speakers:
one_hot_y = one_hot_y[:, : self.num_speakers]
y = self.prepare_y(one_hot_y)
return {"X": X, "y": y}
def segmentation_loss(self, y: torch.Tensor, y_pred: torch.Tensor) -> torch.Tensor:
"""Permutation-invariant segmentation loss
Parameters
----------
y : (batch_size, num_frames, num_speakers) torch.Tensor
Speaker activity.
y_pred : torch.Tensor
Speaker activations
Returns
-------
seg_loss : torch.Tensor
Permutation-invariant segmentation loss
"""
permutated_y_pred, _ = permutate(y, y_pred)
if self.loss == "bce":
seg_losses = F.binary_cross_entropy(
permutated_y_pred, y.float(), reduction="none"
)
elif self.loss == "mse":
seg_losses = F.mse_loss(permutated_y_pred, y.float(), reduction="none")
seg_loss = torch.mean(seg_losses)
return seg_loss
def voice_activity_detection_loss(
self, y: torch.Tensor, y_pred: torch.Tensor
) -> torch.Tensor:
vad_y_pred, _ = torch.max(y_pred, dim=2, keepdim=False)
vad_y, _ = torch.max(y.float(), dim=2, keepdim=False)
if self.vad_loss == "bce":
vad_losses = F.binary_cross_entropy(vad_y_pred, vad_y, reduction="none")
elif self.vad_loss == "mse":
vad_losses = F.mse_loss(vad_y_pred, vad_y, reduction="none")
vad_loss = torch.mean(vad_losses)
return vad_loss
def training_step(self, batch, batch_idx: int):
"""Compute permutation-invariant binary cross-entropy
Parameters
----------
batch : (usually) dict of torch.Tensor
Current batch.
batch_idx: int
Batch index.
Returns
-------
loss : {str: torch.tensor}
{"loss": loss} with additional "loss_{task_name}" keys for multi-task models.
"""
X, y = batch["X"], batch["y"]
y_pred = self.model(X)
# loss = self.segmentation_loss(model, y, y_pred)
seg_loss = self.segmentation_loss(y, y_pred)
self.model.log(
f"{self.ACRONYM}@train_seg_loss",
seg_loss,
on_step=True,
on_epoch=True,
prog_bar=False,
logger=True,
)
if self.vad_loss is None:
vad_loss = 0.0
else:
vad_loss = self.voice_activity_detection_loss(y, y_pred)
self.model.log(
f"{self.ACRONYM}@train_vad_loss",
vad_loss,
on_step=True,
on_epoch=True,
prog_bar=False,
logger=True,
)
loss = seg_loss + vad_loss
self.model.log(
f"{self.ACRONYM}@train_loss",
loss,
on_step=True,
on_epoch=True,
prog_bar=True,
logger=True,
)
return {"loss": loss}
def validation_step(self, batch, batch_idx: int):
"""Compute validation F-score
Parameters
----------
batch : dict of torch.Tensor
Current batch.
batch_idx: int
Batch index.
"""
# move metric to model device
self.val_fbeta.to(self.model.device)
X, y = batch["X"], batch["y"]
# X = (batch_size, num_channels, num_samples)
# y = (batch_size, num_frames, num_classes)
y_pred = self.model(X)
permutated_y_pred, _ = permutate(y, y_pred)
# y_pred = (batch_size, num_frames, num_classes)
val_fbeta = self.val_fbeta(
permutated_y_pred[:, ::10].squeeze(), y[:, ::10].squeeze()
)
self.model.log(
f"{self.ACRONYM}@val_fbeta",
val_fbeta,
on_step=False,
on_epoch=True,
prog_bar=True,
logger=True,
)
if batch_idx > 0:
return
# visualize first 9 validation samples of first batch in Tensorboard
X = X.cpu().numpy()
y = y.float().cpu().numpy()
y_pred = y_pred.cpu().numpy()
permutated_y_pred = permutated_y_pred.cpu().numpy()
# prepare 3 x 3 grid (or smaller if batch size is smaller)
num_samples = min(self.batch_size, 9)
nrows = math.ceil(math.sqrt(num_samples))
ncols = math.ceil(num_samples / nrows)
fig, axes = plt.subplots(
nrows=4 * nrows,
ncols=ncols,
figsize=(15, 10),
)
# reshape target so that there is one line per class when plottingit
y[y == 0] = np.NaN
y *= np.arange(y.shape[2])
# plot each sample
for sample_idx in range(num_samples):
# find where in the grid it should be plotted
row_idx = sample_idx // nrows
col_idx = sample_idx % ncols
# plot waveform
ax_wav = axes[row_idx * 4 + 0, col_idx]
sample_X = np.mean(X[sample_idx], axis=0)
ax_wav.plot(sample_X)
ax_wav.set_xlim(0, len(sample_X))
ax_wav.get_xaxis().set_visible(False)
ax_wav.get_yaxis().set_visible(False)
# plot target
ax_ref = axes[row_idx * 4 + 1, col_idx]
sample_y = y[sample_idx]
ax_ref.plot(sample_y)
ax_ref.set_xlim(0, len(sample_y))
ax_ref.set_ylim(-1, sample_y.shape[1])
ax_ref.get_xaxis().set_visible(False)
ax_ref.get_yaxis().set_visible(False)
# plot prediction
ax_hyp = axes[row_idx * 4 + 2, col_idx]
sample_y_pred = y_pred[sample_idx]
ax_hyp.plot(sample_y_pred)
ax_hyp.set_ylim(-0.1, 1.1)
ax_hyp.set_xlim(0, len(sample_y))
ax_hyp.get_xaxis().set_visible(False)
# plot permutated prediction
ax_map = axes[row_idx * 4 + 3, col_idx]
sample_y_pred_map = permutated_y_pred[sample_idx]
ax_map.plot(sample_y_pred_map)
ax_map.set_ylim(-0.1, 1.1)
ax_map.set_xlim(0, len(sample_y))
plt.tight_layout()
self.model.logger.experiment.add_figure(
f"{self.ACRONYM}@val_samples", fig, self.model.current_epoch
)
|
[
"torch.nn.functional.binary_cross_entropy",
"numpy.sum",
"numpy.argsort",
"numpy.mean",
"numpy.arange",
"matplotlib.pyplot.tight_layout",
"pyannote.audio.utils.random.create_rng_for_worker",
"numpy.pad",
"pyannote.audio.core.io.Audio.power_normalize",
"pyannote.audio.utils.permutation.permutate",
"pyannote.core.SlidingWindow",
"numpy.cumsum",
"collections.Counter",
"matplotlib.pyplot.subplots",
"torch.mean",
"numpy.minimum",
"math.sqrt",
"math.ceil",
"torch.nn.functional.mse_loss",
"torch.max",
"numpy.log",
"pyannote.core.Segment",
"numpy.array"
] |
[((9794, 9841), 'pyannote.audio.utils.random.create_rng_for_worker', 'create_rng_for_worker', (['self.model.current_epoch'], {}), '(self.model.current_epoch)\n', (9815, 9841), False, 'from pyannote.audio.utils.random import create_rng_for_worker\n'), ((13342, 13362), 'pyannote.audio.utils.permutation.permutate', 'permutate', (['y', 'y_pred'], {}), '(y, y_pred)\n', (13351, 13362), False, 'from pyannote.audio.utils.permutation import permutate\n'), ((13659, 13681), 'torch.mean', 'torch.mean', (['seg_losses'], {}), '(seg_losses)\n', (13669, 13681), False, 'import torch\n'), ((13847, 13886), 'torch.max', 'torch.max', (['y_pred'], {'dim': '(2)', 'keepdim': '(False)'}), '(y_pred, dim=2, keepdim=False)\n', (13856, 13886), False, 'import torch\n'), ((14201, 14223), 'torch.mean', 'torch.mean', (['vad_losses'], {}), '(vad_losses)\n', (14211, 14223), False, 'import torch\n'), ((16288, 16308), 'pyannote.audio.utils.permutation.permutate', 'permutate', (['y', 'y_pred'], {}), '(y, y_pred)\n', (16297, 16308), False, 'from pyannote.audio.utils.permutation import permutate\n'), ((17155, 17185), 'math.ceil', 'math.ceil', (['(num_samples / nrows)'], {}), '(num_samples / nrows)\n', (17164, 17185), False, 'import math\n'), ((17206, 17266), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(4 * nrows)', 'ncols': 'ncols', 'figsize': '(15, 10)'}), '(nrows=4 * nrows, ncols=ncols, figsize=(15, 10))\n', (17218, 17266), True, 'import matplotlib.pyplot as plt\n'), ((17432, 17453), 'numpy.arange', 'np.arange', (['y.shape[2]'], {}), '(y.shape[2])\n', (17441, 17453), True, 'import numpy as np\n'), ((18929, 18947), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (18945, 18947), True, 'import matplotlib.pyplot as plt\n'), ((6527, 6551), 'numpy.argsort', 'np.argsort', (['num_speakers'], {}), '(num_speakers)\n', (6537, 6551), True, 'import numpy as np\n'), ((8226, 8292), 'numpy.pad', 'np.pad', (['one_hot_y', '((0, 0), (0, self.num_speakers - num_speakers))'], {}), '(one_hot_y, ((0, 0), (0, self.num_speakers - num_speakers)))\n', (8232, 8292), True, 'import numpy as np\n'), ((9266, 9313), 'pyannote.core.Segment', 'Segment', (['start_time', '(start_time + self.duration)'], {}), '(start_time, start_time + self.duration)\n', (9273, 9313), False, 'from pyannote.core import Segment, SlidingWindow\n'), ((11982, 12023), 'numpy.minimum', 'np.minimum', (['combined_y', '(1)'], {'out': 'combined_y'}), '(combined_y, 1, out=combined_y)\n', (11992, 12023), True, 'import numpy as np\n'), ((14010, 14069), 'torch.nn.functional.binary_cross_entropy', 'F.binary_cross_entropy', (['vad_y_pred', 'vad_y'], {'reduction': '"""none"""'}), "(vad_y_pred, vad_y, reduction='none')\n", (14032, 14069), True, 'import torch.nn.functional as F\n'), ((17115, 17137), 'math.sqrt', 'math.sqrt', (['num_samples'], {}), '(num_samples)\n', (17124, 17137), False, 'import math\n'), ((17774, 17804), 'numpy.mean', 'np.mean', (['X[sample_idx]'], {'axis': '(0)'}), '(X[sample_idx], axis=0)\n', (17781, 17804), True, 'import numpy as np\n'), ((5910, 5979), 'pyannote.core.SlidingWindow', 'SlidingWindow', ([], {'start': 'start', 'end': 'end', 'duration': 'self.duration', 'step': '(1.0)'}), '(start=start, end=end, duration=self.duration, step=1.0)\n', (5923, 5979), False, 'from pyannote.core import Segment, SlidingWindow\n'), ((6455, 6477), 'numpy.array', 'np.array', (['num_speakers'], {}), '(num_speakers)\n', (6463, 6477), True, 'import numpy as np\n'), ((6479, 6495), 'numpy.array', 'np.array', (['counts'], {}), '(counts)\n', (6487, 6495), True, 'import numpy as np\n'), ((11085, 11109), 'pyannote.audio.core.io.Audio.power_normalize', 'Audio.power_normalize', (['X'], {}), '(X)\n', (11106, 11109), False, 'from pyannote.audio.core.io import Audio\n'), ((14133, 14180), 'torch.nn.functional.mse_loss', 'F.mse_loss', (['vad_y_pred', 'vad_y'], {'reduction': '"""none"""'}), "(vad_y_pred, vad_y, reduction='none')\n", (14143, 14180), True, 'import torch.nn.functional as F\n'), ((11120, 11150), 'pyannote.audio.core.io.Audio.power_normalize', 'Audio.power_normalize', (['other_X'], {}), '(other_X)\n', (11141, 11150), False, 'from pyannote.audio.core.io import Audio\n'), ((11039, 11049), 'numpy.log', 'np.log', (['(10)'], {}), '(10)\n', (11045, 11049), True, 'import numpy as np\n'), ((6388, 6409), 'collections.Counter', 'Counter', (['num_speakers'], {}), '(num_speakers)\n', (6395, 6409), False, 'from collections import Counter\n'), ((6726, 6743), 'numpy.cumsum', 'np.cumsum', (['counts'], {}), '(counts)\n', (6735, 6743), True, 'import numpy as np\n'), ((6746, 6760), 'numpy.sum', 'np.sum', (['counts'], {}), '(counts)\n', (6752, 6760), True, 'import numpy as np\n')]
|
#*----------------------------------------------------------------------------*
#* Copyright (C) 2021 Politecnico di Torino, Italy *
#* SPDX-License-Identifier: Apache-2.0 *
#* *
#* Licensed under the Apache License, Version 2.0 (the "License"); *
#* you may not use this file except in compliance with the License. *
#* You may obtain a copy of the License at *
#* *
#* http://www.apache.org/licenses/LICENSE-2.0 *
#* *
#* Unless required by applicable law or agreed to in writing, software *
#* distributed under the License is distributed on an "AS IS" BASIS, *
#* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
#* See the License for the specific language governing permissions and *
#* limitations under the License. *
#* *
#* Author: <NAME> <<EMAIL>> *
#*----------------------------------------------------------------------------*
import unittest
from parse_config import ConfigParser
import argparse
import collections
import torch
import numpy as np
from trainer.NinaProDB1Trainer import NinaProDB1Trainer
from data_loader.NinaProDB1DataLoader import NinaProDB1DataLoader
from model.TCCNet import TCCNet
import model.loss as module_loss
import model.metric as module_metric
from utils import prepare_device
import pdb
np.random.seed(1234)
class TestNinaProDB1Trainer(unittest.TestCase):
args_tuple = collections.namedtuple('args', 'config resume device')
def test_cross_val(self):
# Pars CLI argument and config file
args = TestNinaProDB1Trainer.args_tuple("config/config_NinaProDB1.json", None, None)
config = ConfigParser.from_args(args)
# Setup logger
logger = config.get_logger('train')
# Build model architecture and print to console
#model = TCCNet('NinaProDB1', config['arch']['args'], learned_dil=[1,1,1,1,1,1,1], learned_rf=[7, 11, 19, 35, 67, 131, 129])
#model = TCCNet('NinaProDB1', config['arch']['args'], learned_dil=[1,4,8,16,16,32,1])
model = TCCNet('NinaProDB1', config['arch']['args'])
logger.info(model)
# Prepare for (multi-device) GPU training
device, device_ids = prepare_device(config['n_gpu'])
model = model.to(device)
if len(device_ids) > 1:
model = torch.nn.DataParallel(model, device_ids=device_ids)
# Get function handles of loss and metrics
criterion = getattr(module_loss, config['loss'])
metrics = [getattr(module_metric, met) for met in config['metrics']]
# Build optimizer
trainable_params = filter(lambda p: p.requires_grad, model.parameters())
optimizer = config.init_obj('optimizer', torch.optim, trainable_params)
if config['trainer']['cross_validation']['do']:
print("Do cross-validation")
trainer = NinaProDB1Trainer(
model = model,
criterion = criterion,
metric_ftns = metrics,
optimizer = optimizer,
config = config,
device = device,
data_loader = NinaProDB1DataLoader,
data_dir = config['data_loader']['args']['data_dir'],
batch_size = config['data_loader']['args']['batch_size']
)
acc = trainer.cross_val(config['trainer']['cross_validation']['folds'])
avg = sum(acc.values()) / len(acc)
print("Average Accuracy : {}".format(avg))
if __name__ == '__main__':
unittest.main()
|
[
"unittest.main",
"numpy.random.seed",
"utils.prepare_device",
"trainer.NinaProDB1Trainer.NinaProDB1Trainer",
"collections.namedtuple",
"model.TCCNet.TCCNet",
"torch.nn.DataParallel",
"parse_config.ConfigParser.from_args"
] |
[((1810, 1830), 'numpy.random.seed', 'np.random.seed', (['(1234)'], {}), '(1234)\n', (1824, 1830), True, 'import numpy as np\n'), ((1902, 1956), 'collections.namedtuple', 'collections.namedtuple', (['"""args"""', '"""config resume device"""'], {}), "('args', 'config resume device')\n", (1924, 1956), False, 'import collections\n'), ((4148, 4163), 'unittest.main', 'unittest.main', ([], {}), '()\n', (4161, 4163), False, 'import unittest\n'), ((2146, 2174), 'parse_config.ConfigParser.from_args', 'ConfigParser.from_args', (['args'], {}), '(args)\n', (2168, 2174), False, 'from parse_config import ConfigParser\n'), ((2559, 2603), 'model.TCCNet.TCCNet', 'TCCNet', (['"""NinaProDB1"""', "config['arch']['args']"], {}), "('NinaProDB1', config['arch']['args'])\n", (2565, 2603), False, 'from model.TCCNet import TCCNet\n'), ((2711, 2742), 'utils.prepare_device', 'prepare_device', (["config['n_gpu']"], {}), "(config['n_gpu'])\n", (2725, 2742), False, 'from utils import prepare_device\n'), ((2828, 2879), 'torch.nn.DataParallel', 'torch.nn.DataParallel', (['model'], {'device_ids': 'device_ids'}), '(model, device_ids=device_ids)\n', (2849, 2879), False, 'import torch\n'), ((3403, 3682), 'trainer.NinaProDB1Trainer.NinaProDB1Trainer', 'NinaProDB1Trainer', ([], {'model': 'model', 'criterion': 'criterion', 'metric_ftns': 'metrics', 'optimizer': 'optimizer', 'config': 'config', 'device': 'device', 'data_loader': 'NinaProDB1DataLoader', 'data_dir': "config['data_loader']['args']['data_dir']", 'batch_size': "config['data_loader']['args']['batch_size']"}), "(model=model, criterion=criterion, metric_ftns=metrics,\n optimizer=optimizer, config=config, device=device, data_loader=\n NinaProDB1DataLoader, data_dir=config['data_loader']['args']['data_dir'\n ], batch_size=config['data_loader']['args']['batch_size'])\n", (3420, 3682), False, 'from trainer.NinaProDB1Trainer import NinaProDB1Trainer\n')]
|
import numpy as np
from rllab.envs.mujoco.hill.hill_env import HillEnv
from rllab.envs.mujoco.walker2d_env import Walker2DEnv
from rllab.misc.overrides import overrides
import rllab.envs.mujoco.hill.terrain as terrain
from rllab.spaces import Box
class Walker2DHillEnv(HillEnv):
MODEL_CLASS = Walker2DEnv
@overrides
def _mod_hfield(self, hfield):
# clear a flat patch for the robot to start off from
return terrain.clear_patch(hfield, Box(np.array([-2.0, -2.0]), np.array([-0.5, -0.5])))
|
[
"numpy.array"
] |
[((475, 497), 'numpy.array', 'np.array', (['[-2.0, -2.0]'], {}), '([-2.0, -2.0])\n', (483, 497), True, 'import numpy as np\n'), ((499, 521), 'numpy.array', 'np.array', (['[-0.5, -0.5]'], {}), '([-0.5, -0.5])\n', (507, 521), True, 'import numpy as np\n')]
|
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 18 10:11:59 2018
@author: zhangxiang
"""
#import sys
#reload(sys)
#sys.setdefaultencoding("utf-8")
import importlib,sys
#importlib.reload(sys)
sys.path.append("/opt/spark/spark-2.2.0-bin-hadoop2.6/python")
sys.path.append("/opt/spark/spark-2.2.0-bin-hadoop2.6/python/lib/py4j-0.10.4-src.zip")
import pandas as pd
import numpy as np
from sklearn.cluster import DBSCAN
from pandas.core.frame import DataFrame
import argparse
# 指定集群python路径(yarn模式需要)
import os
os.environ["PYSPARK_PYTHON"]="/data/anaconda3/anaconda3/bin/python"
from pyspark.context import SparkContext
from pyspark.sql.session import SparkSession
from pyspark.sql import SQLContext
from pyspark.conf import SparkConf
from pyspark.sql import HiveContext
# 计算每一个uid的地理位置聚类lables (采用dbscan算法)
def get_lables_partitions(x):
final_iterator = []
for xi in x:
ary = []
for _row in xi[1]:
#t = [v for k,v in items() if k in ['pid', 'lon', 'lat']]
t = _row.asDict()
#print(t)
#print(type(t))
pid = t['pid']
login = t['login']
logout = t['logout']
lon = t['lon']
lat = t['lat']
weekday_weekend = t['weekday_weekend']
ary.append([pid, login, logout, lon, lat, weekday_weekend])
df = pd.DataFrame(ary)
df.columns = ['pid', 'login', 'logout', 'lon', 'lat', 'weekday_weekend']
dftmp = df[['lon', 'lat']]
db = DBSCAN(eps=eps, min_samples=min_samples, algorithm="ball_tree", metric='haversine').fit(np.radians(dftmp))
df['labels'] = db.labels_
#final_iterator.append(v for v in df.as_matrix().tolist() ] )
final_iterator.append(df.as_matrix().tolist())
return iter(final_iterator)
def get_lables(x):
ary = []
for _row in x[1]:
#t = [v for k,v in items() if k in ['pid', 'lon', 'lat']]
t = _row.asDict()
#print(t)
#print(type(t))
pid = t['pid']
login = t['login']
logout = t['logout']
lon = t['lon']
lat = t['lat']
weekday_weekend = t['weekday_weekend']
ary.append([pid, login, logout, lon, lat, weekday_weekend])
df = pd.DataFrame(ary)
df.columns = ['pid', 'login', 'logout', 'lon', 'lat', 'weekday_weekend']
dftmp = df[['lon', 'lat']]
db = DBSCAN(eps=eps, min_samples=min_samples, algorithm="ball_tree", metric='haversine').fit(np.radians(dftmp))
df['labels'] = db.labels_
return df.as_matrix().tolist()
# 将[[[1,2],[2,3]],[[2,3],[4,5],[6,8]]] 转换成 [[1,2],[2,3],[2,3],[4,5],[6,8]]
def split_list(x):
return [v for v in x]
if __name__ == '__main__':
distance = 0.8
min_samples = 2
date_time = str(sys.argv[1])
warehouse_name = str(sys.argv[2])
table_name = warehouse_name + '.' + 'sctdwd_bill_deviceinfo_offline_dbscan_d'
kms_per_radian = 6371.0088
eps = distance / kms_per_radian
if isinstance(float(distance), float) and isinstance(int(min_samples), int):
spark = SparkSession.builder \
.master("yarn") \
.appName("poi") \
.config("spark.some.config.option", "some-value") \
.enableHiveSupport() \
.getOrCreate() \
res = spark.sql(" \
select \
pid \
,login \
,logout \
,gps_lon lon \
,gps_lat lat \
,if(pmod(datediff(pt_dt,'2012-01-01'),7) in (0,6) , 'weekend', 'weekday' ) weekday_weekend \
from security_dwd.sctdwd_bill_deviceinfo_offline_d \
where \
pt_dt > date_add( '%s' ,-30) and pt_dt <= '%s' \
and ( gps_lat != 0 and gps_lat is not null and gps_lat > -90 and gps_lat < 90 ) \
and ( gps_lon != 0 and gps_lon is not null and gps_lon > -180 and gps_lon < 180 ) \
and ( login is not null ) \
and ( logout is not null ) \
and ( logout > login ) \
" % (date_time,date_time))
res_t1 = res.rdd.map(lambda x: ((x[0],x[5]), x))
res_t2 = res_t1.groupByKey().mapValues(list)
res_t3 = res_t2.map(get_lables)
# res_t3 = res_t2.mapPartitions(get_lables_partitions)
res_t4 = res_t3.flatMap(split_list)
res_t5 = spark.createDataFrame(res_t4,["pid","login","logout","lon","lat","weekday_weekend","labels"]).repartition(50).createOrReplaceTempView("df")
spark.sql(""" drop table if exists %s """ % table_name)
spark.sql("create table if not exists %s \
(pid INT,\
login STRING,\
logout STRING,\
lon FLOAT,\
lat FLOAT,\
weekday_weekend STRING,\
labels INT) PARTITIONED BY (pt_dt STRING)" % table_name)
spark.sql("SET spark.sql.shuffle.partitions=300")
spark.sql("INSERT OVERWRITE TABLE %s PARTITION(pt_dt= '%s')\
select \
cast(pid as int) pid, \
cast(login as string) login,\
cast(logout as string) logout,\
cast(lon as float) lon,\
cast(lat as float) lat,\
cast(weekday_weekend as string) weekday_weekend,\
cast(labels as int) labels \
from df\
" % (table_name,date_time))
spark.stop()
|
[
"sys.path.append",
"numpy.radians",
"pandas.DataFrame",
"pyspark.sql.session.SparkSession.builder.master",
"sklearn.cluster.DBSCAN"
] |
[((195, 257), 'sys.path.append', 'sys.path.append', (['"""/opt/spark/spark-2.2.0-bin-hadoop2.6/python"""'], {}), "('/opt/spark/spark-2.2.0-bin-hadoop2.6/python')\n", (210, 257), False, 'import importlib, sys\n'), ((258, 349), 'sys.path.append', 'sys.path.append', (['"""/opt/spark/spark-2.2.0-bin-hadoop2.6/python/lib/py4j-0.10.4-src.zip"""'], {}), "(\n '/opt/spark/spark-2.2.0-bin-hadoop2.6/python/lib/py4j-0.10.4-src.zip')\n", (273, 349), False, 'import importlib, sys\n'), ((2246, 2263), 'pandas.DataFrame', 'pd.DataFrame', (['ary'], {}), '(ary)\n', (2258, 2263), True, 'import pandas as pd\n'), ((1360, 1377), 'pandas.DataFrame', 'pd.DataFrame', (['ary'], {}), '(ary)\n', (1372, 1377), True, 'import pandas as pd\n'), ((2470, 2487), 'numpy.radians', 'np.radians', (['dftmp'], {}), '(dftmp)\n', (2480, 2487), True, 'import numpy as np\n'), ((1595, 1612), 'numpy.radians', 'np.radians', (['dftmp'], {}), '(dftmp)\n', (1605, 1612), True, 'import numpy as np\n'), ((2382, 2470), 'sklearn.cluster.DBSCAN', 'DBSCAN', ([], {'eps': 'eps', 'min_samples': 'min_samples', 'algorithm': '"""ball_tree"""', 'metric': '"""haversine"""'}), "(eps=eps, min_samples=min_samples, algorithm='ball_tree', metric=\n 'haversine')\n", (2388, 2470), False, 'from sklearn.cluster import DBSCAN\n'), ((1507, 1595), 'sklearn.cluster.DBSCAN', 'DBSCAN', ([], {'eps': 'eps', 'min_samples': 'min_samples', 'algorithm': '"""ball_tree"""', 'metric': '"""haversine"""'}), "(eps=eps, min_samples=min_samples, algorithm='ball_tree', metric=\n 'haversine')\n", (1513, 1595), False, 'from sklearn.cluster import DBSCAN\n'), ((3070, 3105), 'pyspark.sql.session.SparkSession.builder.master', 'SparkSession.builder.master', (['"""yarn"""'], {}), "('yarn')\n", (3097, 3105), False, 'from pyspark.sql.session import SparkSession\n')]
|
"""
License
Copyright 2019 <NAME>, <NAME>, <NAME>, <NAME>
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed
on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License
for the specific language governing permissions and limitations under the License.
DISCLAIMER: This notebook is not legal compliance advice.
"""
import pandas as pd
import numpy as np
from notebooks.scripts.disparity_measurement import DisparityTesting
pd.set_option('display.max_columns', 30)
pd.set_option('display.width', 200)
def disparity_tables(file_name,
pg_names,
cg_names,
pgcg_names,
predicted,
label,
probability_for_classification,
higher_score_favorable,
model_name,
):
data = pd.read_csv(file_name)
data["classification_outcome"] = np.where(data[predicted] >= probability_for_classification, 1, 0)
data["classification_outcome"].value_counts(normalize=True)
disp_tests = DisparityTesting(pg_names=pg_names, cg_names=cg_names, pgcg_names=pgcg_names,
higher_score_favorable=higher_score_favorable)
cat_outcomes = disp_tests.categorical_disparity_measures(data=data, label=label, outcome="classification_outcome")
cont_outcomes = disp_tests.continuous_disparity_measures(data=data, predicted=predicted)
disparity_measures = DisparityTesting.create_combined_output(cat_outcomes=cat_outcomes, cont_outcomes=cont_outcomes,
cat_vars=list(cat_outcomes.columns))
disparity_measures["Model Name"] = model_name
disparity_measures = disparity_measures[["Model Name"] +
[x for x in disparity_measures.columns if x != "Model Name"]]
return disparity_measures
if __name__ == '__main__':
hmda_static_params = {"pg_names": ["black", "female"],
"cg_names": ["white", "male"],
"pgcg_names": ["black", "white", "female", "male"],
# "pg_names": ["black", "amind", "hispanic", "female"],
# "cg_names": ["white", "white", "non_hispanic", "male"],
# "pgcg_names": ["black", "amind", "white", "hispanic", "non_hispanic", "female", "male"],
"higher_score_favorable": False,
"probability_for_classification": 0.20,
}
hmda_mgbm = disparity_tables(**hmda_static_params,
model_name="Monotonic GBM - HMDA Data",
file_name='./data/output/test_hmda_with_preds.csv',
predicted="high_priced_mgbm_pred",
label="high_priced",
)
# hmda_gbm = disparity_tables(**hmda_static_params,
# model_name="Standard GBM - HMDA Data",
# file_name='./data/output/test_hmda_with_preds.csv',
# predicted="high_priced_gbm_pred",
# label="high_priced",
# )
simu_static_params = {"pg_names": ["prot_class1", "prot_class2"],
"cg_names": ["ctrl_class1", "ctrl_class2"],
"pgcg_names": ["prot_class1", "ctrl_class1", "prot_class2", "ctrl_class2"],
"higher_score_favorable": True,
"probability_for_classification": 0.60,
}
simu_mgbm = disparity_tables(**simu_static_params,
model_name="Monotonic GBM - Simulated Data",
file_name='./data/output/test_sim_with_preds.csv',
predicted="outcome_mgbm_pred",
label="outcome",
)
# simu_gbm = disparity_tables(**simu_static_params,
# model_name="Standard GBM - Simulated Data",
# file_name='./data/output/test_sim_with_preds.csv',
# predicted="outcome_gbm_pred",
# label="outcome",
# )
hmda_xnn = disparity_tables(**hmda_static_params,
model_name="XNN - HMDA Data",
file_name="./data/xnn_output/hmda_results/Results_hmda_test_set.csv",
predicted="probability",
label="high_priced",
)
simu_xnn = disparity_tables(**simu_static_params,
model_name="XNN - Simulated Data",
file_name="./data/xnn_output/simulation_results/Results_simulation_test_set.csv",
predicted="probability",
label="outcome",
)
disparity_results = pd.concat([simu_mgbm, simu_xnn,
hmda_mgbm, hmda_xnn], axis=0)
# pc_only = disparity_results.loc[disparity_results["Class"].isin(['Prot-Class1', 'Prot-Class2'])]
disparity_results_for_paper = disparity_results[["Model Name", "Class", "Control", "Total", "Accuracy",
"False Positive Rate", "Control False Positive Rate",
"Relative False Positive Rate", "False Negative Rate",
"Control False Negative Rate", "Relative False Negative Rate",
"Marginal Effects", "Adverse Impact Ratio",
"Fishers Exact P-Value", "Standardized Mean Difference",
"T-Statistic P-Value"]]
disparity_results.to_csv('./data/output/disparity_results_mgbm_xnn_hmda_simu.csv', index=False)
disparity_results_for_paper.to_csv('./data/output/disparity_results_for_paper_mgbm_xnn_hmda_simu.csv', index=False)
|
[
"pandas.read_csv",
"numpy.where",
"notebooks.scripts.disparity_measurement.DisparityTesting",
"pandas.set_option",
"pandas.concat"
] |
[((750, 790), 'pandas.set_option', 'pd.set_option', (['"""display.max_columns"""', '(30)'], {}), "('display.max_columns', 30)\n", (763, 790), True, 'import pandas as pd\n'), ((791, 826), 'pandas.set_option', 'pd.set_option', (['"""display.width"""', '(200)'], {}), "('display.width', 200)\n", (804, 826), True, 'import pandas as pd\n'), ((1182, 1204), 'pandas.read_csv', 'pd.read_csv', (['file_name'], {}), '(file_name)\n', (1193, 1204), True, 'import pandas as pd\n'), ((1242, 1307), 'numpy.where', 'np.where', (['(data[predicted] >= probability_for_classification)', '(1)', '(0)'], {}), '(data[predicted] >= probability_for_classification, 1, 0)\n', (1250, 1307), True, 'import numpy as np\n'), ((1390, 1519), 'notebooks.scripts.disparity_measurement.DisparityTesting', 'DisparityTesting', ([], {'pg_names': 'pg_names', 'cg_names': 'cg_names', 'pgcg_names': 'pgcg_names', 'higher_score_favorable': 'higher_score_favorable'}), '(pg_names=pg_names, cg_names=cg_names, pgcg_names=\n pgcg_names, higher_score_favorable=higher_score_favorable)\n', (1406, 1519), False, 'from notebooks.scripts.disparity_measurement import DisparityTesting\n'), ((5534, 5595), 'pandas.concat', 'pd.concat', (['[simu_mgbm, simu_xnn, hmda_mgbm, hmda_xnn]'], {'axis': '(0)'}), '([simu_mgbm, simu_xnn, hmda_mgbm, hmda_xnn], axis=0)\n', (5543, 5595), True, 'import pandas as pd\n')]
|
import os
import random
import numpy as np
from typing import List, Tuple, Dict, Union, Iterable
from geometry.TwoDimension import SE2Pose, Point2
from slam.Variables import SE2Variable, VariableType, R2Variable, Variable
import matplotlib.pyplot as plt
from utils.Statistics import mmd
from utils.Visualization import plot_2d_samples
def getVars(order_file:str, pose_space: str = "SE2"):
var_list = []
order = np.genfromtxt(order_file, dtype='str')
for var in order:
if var[0] == "X":
if pose_space == "SE2":
var_list.append(SE2Variable(name=var,variable_type=VariableType.Pose))
elif pose_space == "R2":
var_list.append(R2Variable(name=var,variable_type=VariableType.Pose))
elif var[0] == "L":
var_list.append(R2Variable(name=var, variable_type=VariableType.Landmark))
return var_list
def getMeans(vars:List[Variable], marg_file: str)->dict:
res = {}
with open(marg_file) as fp:
for cnt, line in enumerate(fp):
# print("Line {}: {}".format(cnt, line))
data = line.strip().split(' ')
data_len = len(data)
if data_len > 2:
if isinstance(vars[cnt], SE2Variable):
res[vars[cnt]] = SE2Pose.by_array([float(item) for item in data[:3]])
elif isinstance(vars[cnt], R2Variable):
res[vars[cnt]] = Point2.by_array([float(item) for item in data[:2]])
else:
raise TypeError("Unkonwn type.")
return res
def getSamples(vars:List[Variable], var2mean:dict, joint: np.ndarray, sample_num:int):
dim, _ = joint.shape
res = np.zeros((sample_num,dim))
for i in range(sample_num):
noise = np.random.multivariate_normal(mean=np.zeros(dim),
cov=joint)
cur_idx = 0
for var in vars:
mean = var2mean[var]
if isinstance(mean, Point2):
res[i,cur_idx:cur_idx+2] = mean.array + noise[cur_idx:cur_idx+2]
cur_idx += 2
elif isinstance(mean, SE2Pose):
noised_pose = mean * SE2Pose.by_exp_map(noise[cur_idx:cur_idx+3])
res[i,cur_idx:cur_idx+3] = noised_pose.array
cur_idx += 3
else:
raise TypeError("mean can only be SE2Pose or Point2 type.")
return res
def compute_marginal_mmd(comp_samples: np.ndarray, ref_samples: np.ndarray) -> float:
col = 0
sum_mmd = 0.0
num_vars = comp_samples.shape[1] // 2
while col < num_vars * 2:
print(f"Marginal {col // 2 + 1} of {num_vars}")
m = mmd(comp_samples[:, col:col+2], ref_samples[:, col:col+2])[0]
sum_mmd += m
col += 2
return sum_mmd / num_vars
def reorder_samples(ref_order: List[Variable],
sample_order: List[Variable],
samples: np.ndarray):
# res = np.zeros_like(samples)
# cur_dim = 0
# for var in ref_order:
# var_idx = sample_order.index(var)
# if var_idx == 0:
# sample_dim = 0
# else:
# sample_dim = np.sum([it.dim for it in sample_order[:var_idx]])
# res[:,cur_dim:cur_dim+var.dim] = samples[:,sample_dim:sample_dim+var.dim]
# cur_dim += var.dim
# return res
res = []
cur_dim = 0
for var in ref_order:
var_idx = sample_order.index(var)
if var_idx == 0:
sample_dim = 0
else:
sample_dim = np.sum([it.dim for it in sample_order[:var_idx]])
res.append(samples[:, sample_dim:sample_dim+2])
cur_dim += var.dim
return np.hstack(res)
if __name__ == '__main__':
setup_folder = "icra_paper"
case_folder = "case1"
gtsam_folder = "gtsam"
reference_folder = "reference"
joint_mmd = True
pose_space = "SE2"
sample_num = 500
ref_dir = f"{setup_folder}/{case_folder}/{reference_folder}"
dir = f"{setup_folder}/{case_folder}/{gtsam_folder}"
batch_num = 0
order_file = f"{dir}/batch_{batch_num}_ordering"
sample_file = f"{dir}/batch{batch_num}"
mmd_list = []
marginal_mmds = []
while(os.path.exists(order_file) and
os.path.exists(sample_file)):
print(f"batch {batch_num}")
nodes = getVars(order_file=order_file)
samples = np.genfromtxt(sample_file)
print("Computing MMD")
ref_step = batch_num
ref_order = getVars(order_file=f"{ref_dir}/step_{ref_step}_ordering")
comp_samples = reorder_samples(ref_order=ref_order,sample_order=nodes,samples=samples)
ref_samples = np.loadtxt(f"{ref_dir}/step_{ref_step}")
ref_samples = reorder_samples(ref_order=ref_order,sample_order=nodes,samples=ref_samples)
ref_sample_num = ref_samples.shape[0]
comp_sample_num = comp_samples.shape[0]
assert (ref_sample_num >= sample_num)
downsampling_indices = np.array(random.sample(list(range(ref_sample_num)), sample_num))
ref_samples = ref_samples[downsampling_indices, :]
assert (comp_sample_num >= sample_num)
downsampling_indices = np.array(random.sample(list(range(comp_sample_num)), sample_num))
comp_samples = comp_samples[downsampling_indices, :]
if joint_mmd:
m = mmd(comp_samples, ref_samples)
mmd_list.append(m[0])
marg_mmd = compute_marginal_mmd(comp_samples, ref_samples)
marginal_mmds.append(marg_mmd)
batch_num += 1
order_file = f"{dir}/batch_{batch_num}_ordering"
sample_file = f"{dir}/batch{batch_num}"
print(marginal_mmds)
if joint_mmd:
np.savetxt(fname=f"{dir}/mmd",X=np.array(mmd_list))
np.savetxt(fname=f"{dir}/marginal_mmd",X=np.array(marginal_mmds))
|
[
"numpy.sum",
"slam.Variables.SE2Variable",
"numpy.zeros",
"numpy.genfromtxt",
"os.path.exists",
"numpy.hstack",
"slam.Variables.R2Variable",
"geometry.TwoDimension.SE2Pose.by_exp_map",
"numpy.array",
"numpy.loadtxt",
"utils.Statistics.mmd"
] |
[((423, 461), 'numpy.genfromtxt', 'np.genfromtxt', (['order_file'], {'dtype': '"""str"""'}), "(order_file, dtype='str')\n", (436, 461), True, 'import numpy as np\n'), ((1695, 1722), 'numpy.zeros', 'np.zeros', (['(sample_num, dim)'], {}), '((sample_num, dim))\n', (1703, 1722), True, 'import numpy as np\n'), ((3694, 3708), 'numpy.hstack', 'np.hstack', (['res'], {}), '(res)\n', (3703, 3708), True, 'import numpy as np\n'), ((4214, 4240), 'os.path.exists', 'os.path.exists', (['order_file'], {}), '(order_file)\n', (4228, 4240), False, 'import os\n'), ((4255, 4282), 'os.path.exists', 'os.path.exists', (['sample_file'], {}), '(sample_file)\n', (4269, 4282), False, 'import os\n'), ((4386, 4412), 'numpy.genfromtxt', 'np.genfromtxt', (['sample_file'], {}), '(sample_file)\n', (4399, 4412), True, 'import numpy as np\n'), ((4668, 4708), 'numpy.loadtxt', 'np.loadtxt', (['f"""{ref_dir}/step_{ref_step}"""'], {}), "(f'{ref_dir}/step_{ref_step}')\n", (4678, 4708), True, 'import numpy as np\n'), ((2688, 2750), 'utils.Statistics.mmd', 'mmd', (['comp_samples[:, col:col + 2]', 'ref_samples[:, col:col + 2]'], {}), '(comp_samples[:, col:col + 2], ref_samples[:, col:col + 2])\n', (2691, 2750), False, 'from utils.Statistics import mmd\n'), ((3550, 3599), 'numpy.sum', 'np.sum', (['[it.dim for it in sample_order[:var_idx]]'], {}), '([it.dim for it in sample_order[:var_idx]])\n', (3556, 3599), True, 'import numpy as np\n'), ((5345, 5375), 'utils.Statistics.mmd', 'mmd', (['comp_samples', 'ref_samples'], {}), '(comp_samples, ref_samples)\n', (5348, 5375), False, 'from utils.Statistics import mmd\n'), ((5796, 5819), 'numpy.array', 'np.array', (['marginal_mmds'], {}), '(marginal_mmds)\n', (5804, 5819), True, 'import numpy as np\n'), ((1805, 1818), 'numpy.zeros', 'np.zeros', (['dim'], {}), '(dim)\n', (1813, 1818), True, 'import numpy as np\n'), ((5731, 5749), 'numpy.array', 'np.array', (['mmd_list'], {}), '(mmd_list)\n', (5739, 5749), True, 'import numpy as np\n'), ((578, 632), 'slam.Variables.SE2Variable', 'SE2Variable', ([], {'name': 'var', 'variable_type': 'VariableType.Pose'}), '(name=var, variable_type=VariableType.Pose)\n', (589, 632), False, 'from slam.Variables import SE2Variable, VariableType, R2Variable, Variable\n'), ((812, 869), 'slam.Variables.R2Variable', 'R2Variable', ([], {'name': 'var', 'variable_type': 'VariableType.Landmark'}), '(name=var, variable_type=VariableType.Landmark)\n', (822, 869), False, 'from slam.Variables import SE2Variable, VariableType, R2Variable, Variable\n'), ((702, 755), 'slam.Variables.R2Variable', 'R2Variable', ([], {'name': 'var', 'variable_type': 'VariableType.Pose'}), '(name=var, variable_type=VariableType.Pose)\n', (712, 755), False, 'from slam.Variables import SE2Variable, VariableType, R2Variable, Variable\n'), ((2187, 2233), 'geometry.TwoDimension.SE2Pose.by_exp_map', 'SE2Pose.by_exp_map', (['noise[cur_idx:cur_idx + 3]'], {}), '(noise[cur_idx:cur_idx + 3])\n', (2205, 2233), False, 'from geometry.TwoDimension import SE2Pose, Point2\n')]
|
from shutil import rmtree
import pytest
import numpy as np
from snek5000_cbox.solver import Simul
from snek5000 import load
@pytest.mark.slow
def test_simple_simul():
params = Simul.create_default_params()
aspect_ratio = 1.0
params.prandtl = 0.71
# for aspect ratio 1, Ra_c = 1.825E08
params.rayleigh = 1.83e08
params.output.sub_directory = "tests_snek_cbox"
params.oper.nproc_min = 2
params.oper.dim = 2
nb_elements = 8
params.oper.nx = nb_elements
params.oper.ny = nb_elements
params.oper.nz = nb_elements
Lx = params.oper.Lx = 1.0
Ly = params.oper.Ly = Lx * aspect_ratio
params.oper.mesh_stretch_factor = 0.1
params.oper.elem.order = 7
# creation of the coordinates of the points saved by history points
n1d = 4
small = Lx / 10
xs = np.linspace(0, Lx, n1d)
xs[0] = small
xs[-1] = Lx - small
ys = np.linspace(0, Ly, n1d)
ys[0] = small
ys[-1] = Ly - small
coords = [(x, y) for x in xs for y in ys]
params.output.history_points.coords = coords
params.oper.max.hist = len(coords) + 1
num_steps = params.nek.general.num_steps = 5000
params.nek.general.write_interval = 500
params.nek.general.variable_dt = False
params.nek.general.dt = 0.05
params.nek.general.time_stepper = "BDF3"
params.nek.general.extrapolation = "OIFS"
params.output.phys_fields.write_interval_pert_field = 500
params.output.history_points.write_interval = 10
sim = Simul(params)
sim.make.exec("run_fg", resources={"nproc": 2})
sim = load(sim.path_run)
coords, df = sim.output.history_points.load()
assert coords.ndim == 2 and coords.shape == (n1d ** 2, 2)
times = df[df.index_points == 0].time
t_max = times.max()
assert t_max == num_steps * params.nek.general.dt
assert (
len(times) == num_steps / params.output.history_points.write_interval + 1
)
# check a physical result: since there is no probe close to the center,
# the temperature values at the end are > 0.15 and < 0.4
temperature_last = df[df.time == t_max].temperature
assert temperature_last.abs().max() < 0.4
assert temperature_last.abs().min() > 0.15
# if everything is fine, we can cleanup the directory of the simulation
rmtree(sim.path_run, ignore_errors=True)
|
[
"snek5000.load",
"numpy.linspace",
"snek5000_cbox.solver.Simul.create_default_params",
"shutil.rmtree",
"snek5000_cbox.solver.Simul"
] |
[((186, 215), 'snek5000_cbox.solver.Simul.create_default_params', 'Simul.create_default_params', ([], {}), '()\n', (213, 215), False, 'from snek5000_cbox.solver import Simul\n'), ((836, 859), 'numpy.linspace', 'np.linspace', (['(0)', 'Lx', 'n1d'], {}), '(0, Lx, n1d)\n', (847, 859), True, 'import numpy as np\n'), ((912, 935), 'numpy.linspace', 'np.linspace', (['(0)', 'Ly', 'n1d'], {}), '(0, Ly, n1d)\n', (923, 935), True, 'import numpy as np\n'), ((1510, 1523), 'snek5000_cbox.solver.Simul', 'Simul', (['params'], {}), '(params)\n', (1515, 1523), False, 'from snek5000_cbox.solver import Simul\n'), ((1588, 1606), 'snek5000.load', 'load', (['sim.path_run'], {}), '(sim.path_run)\n', (1592, 1606), False, 'from snek5000 import load\n'), ((2311, 2351), 'shutil.rmtree', 'rmtree', (['sim.path_run'], {'ignore_errors': '(True)'}), '(sim.path_run, ignore_errors=True)\n', (2317, 2351), False, 'from shutil import rmtree\n')]
|
# Provides GUI to label duplicate images in dataset and saves labels to pickle files
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Button
import time
import pickle
import sys
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.fashion_mnist.load_data()
def identify_dups(filename):
inds = y_train.argsort()
sorted_x_train = x_train[inds]
sorted_y_train = np.sort(y_train)
inds = y_test.argsort()
sorted_x_test = x_test[inds]
sorted_y_test = np.sort(y_test)
# Assumed to be 1 class per file
#dup_file = input("Duplicates file name: ")
pickle_in = open(filename,"rb")
dups = pickle.load(pickle_in)
num_non_duplicates = 0
fin_dups = []
def limit_reached():
print("Writing to file...")
pickle_out = open("label_dups_output/labeled_" + filename,"wb")
pickle.dump(fin_dups, pickle_out)
plt.close('all')
print("Please press enter to continue.")
class Index(object):
ind = 0
num_non_duplicates = 0
def iden_duplicate(self, event):
dups[self.ind].append(1)
fin_dups.append(dups[self.ind])
self.ind += 1
val = dups[self.ind]
img_fig_1.set_data(sorted_x_train[val[0]])
img_fig_2.set_data(sorted_x_test[val[1]])
plt.draw()
def iden_non_duplicate(self, event):
dups[self.ind].append(0)
fin_dups.append(dups[self.ind])
self.ind += 1
val = dups[self.ind]
img_fig_1.set_data(sorted_x_train[val[0]])
img_fig_2.set_data(sorted_x_test[val[1]])
self.num_non_duplicates += 1
#print("Non dup.")
if self.num_non_duplicates >20:
limit_reached()
plt.draw()
img_1 = sorted_x_train[dups[0][0]]
img_2 = sorted_x_test[dups[0][1]]
f, axarr = plt.subplots(1,2,figsize=(15,10))
axarr[0].title.set_fontsize(24)
axarr[0].title.set_text("Image from Training Set")
axarr[0].grid(False)
img_fig_1 = axarr[0].imshow(img_1, cmap='gray_r')
axarr[1].title.set_fontsize(24)
axarr[1].title.set_text("Image from Testing Set")
axarr[1].grid(False)
img_fig_2 = axarr[1].imshow(img_2, cmap='gray_r')
callback = Index()
axprev = plt.axes([0.3, 0.05, 0.2, 0.075])
axnext = plt.axes([0.51, 0.05, 0.2, 0.075])
bnext = Button(axnext, 'Very Similar')
bnext.label.set_fontsize(24)
bnext.on_clicked(callback.iden_duplicate)
bprev = Button(axprev, 'Distinct')
bprev.label.set_fontsize(24)
bprev.on_clicked(callback.iden_non_duplicate)
#print("Showing plot")
plt.show(block=False)
plt.pause(.01)
input("")
#print("After Showing plot")
for i in range(0,10):
fn = "dups/dups" + str(i) + ".pickle"
print("Reading in ", fn, ". This could take a few seconds.")
identify_dups(fn)
|
[
"pickle.dump",
"matplotlib.pyplot.show",
"matplotlib.pyplot.axes",
"matplotlib.pyplot.close",
"matplotlib.widgets.Button",
"matplotlib.pyplot.draw",
"numpy.sort",
"pickle.load",
"matplotlib.pyplot.pause",
"matplotlib.pyplot.subplots",
"tensorflow.keras.datasets.fashion_mnist.load_data"
] |
[((275, 318), 'tensorflow.keras.datasets.fashion_mnist.load_data', 'tf.keras.datasets.fashion_mnist.load_data', ([], {}), '()\n', (316, 318), True, 'import tensorflow as tf\n'), ((434, 450), 'numpy.sort', 'np.sort', (['y_train'], {}), '(y_train)\n', (441, 450), True, 'import numpy as np\n'), ((533, 548), 'numpy.sort', 'np.sort', (['y_test'], {}), '(y_test)\n', (540, 548), True, 'import numpy as np\n'), ((683, 705), 'pickle.load', 'pickle.load', (['pickle_in'], {}), '(pickle_in)\n', (694, 705), False, 'import pickle\n'), ((1948, 1984), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(2)'], {'figsize': '(15, 10)'}), '(1, 2, figsize=(15, 10))\n', (1960, 1984), True, 'import matplotlib.pyplot as plt\n'), ((2358, 2391), 'matplotlib.pyplot.axes', 'plt.axes', (['[0.3, 0.05, 0.2, 0.075]'], {}), '([0.3, 0.05, 0.2, 0.075])\n', (2366, 2391), True, 'import matplotlib.pyplot as plt\n'), ((2405, 2439), 'matplotlib.pyplot.axes', 'plt.axes', (['[0.51, 0.05, 0.2, 0.075]'], {}), '([0.51, 0.05, 0.2, 0.075])\n', (2413, 2439), True, 'import matplotlib.pyplot as plt\n'), ((2452, 2482), 'matplotlib.widgets.Button', 'Button', (['axnext', '"""Very Similar"""'], {}), "(axnext, 'Very Similar')\n", (2458, 2482), False, 'from matplotlib.widgets import Button\n'), ((2574, 2600), 'matplotlib.widgets.Button', 'Button', (['axprev', '"""Distinct"""'], {}), "(axprev, 'Distinct')\n", (2580, 2600), False, 'from matplotlib.widgets import Button\n'), ((2715, 2736), 'matplotlib.pyplot.show', 'plt.show', ([], {'block': '(False)'}), '(block=False)\n', (2723, 2736), True, 'import matplotlib.pyplot as plt\n'), ((2741, 2756), 'matplotlib.pyplot.pause', 'plt.pause', (['(0.01)'], {}), '(0.01)\n', (2750, 2756), True, 'import matplotlib.pyplot as plt\n'), ((894, 927), 'pickle.dump', 'pickle.dump', (['fin_dups', 'pickle_out'], {}), '(fin_dups, pickle_out)\n', (905, 927), False, 'import pickle\n'), ((936, 952), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (945, 952), True, 'import matplotlib.pyplot as plt\n'), ((1378, 1388), 'matplotlib.pyplot.draw', 'plt.draw', ([], {}), '()\n', (1386, 1388), True, 'import matplotlib.pyplot as plt\n'), ((1844, 1854), 'matplotlib.pyplot.draw', 'plt.draw', ([], {}), '()\n', (1852, 1854), True, 'import matplotlib.pyplot as plt\n')]
|
#!/usr/bin/env python
import numpy as np
import csv
from matplotlib import pyplot as plt
def calculate_odometry_velocity(currentPos, velL, velR, deltaT):
""" Calculate odometry based on velocity readings
Args:
currentPos (np.mat): current position
velL (float): velocity of left wheel
velR (float): velocity of right wheel
deltaT (float): time difference between two preceeding positions
Returns:
(np.mat): updated position
"""
L = 330.0
A = np.mat([[np.cos(currentPos.item(2)) / 2.0, np.cos(currentPos.item(2)) / 2.0],
[np.sin(currentPos.item(2)) / 2.0, np.sin(currentPos.item(2)) / 2.0],
[1 / L, -1 / L]])
V = np.mat([[velR],
[velL]])
V = V * deltaT
deltaPos = A * V
currentPos = currentPos + deltaPos
return currentPos
def calculate_odometry_encoders(currentPos, deltaL, deltaR):
"""Calculate odometry based on encoder readings
Args:
currentPos (np.mat): current position
deltaL (int): shift readed on left encoder
deltaR (int): shift readed on right encoder
Returns:
(np.mat): updated position
"""
L = 330.0
ticksPerRev = 76600
d = 195
A = np.mat([[np.cos(currentPos.item(2)) / 2.0, np.cos(currentPos.item(2)) / 2.0],
[np.sin(currentPos.item(2)) / 2.0, np.sin(currentPos.item(2)) / 2.0],
[1 / L, -1 / L]])
V = np.mat([[(deltaR / ticksPerRev) * np.pi * d],
[(deltaL / ticksPerRev) * np.pi * d]])
deltaPos = A * V
currentPos = currentPos + deltaPos
return currentPos
def calcualte_encoder_shift(row, prev_enc_L, prev_enc_R):
"""Calculate shift for both encoders
Args:
row (dict): dictionary with new data
prev_enc_L (int): previous position of left encoder
prev_enc_R (int): previous position of right encoder
Returns:
[int, int]: encoders shift
"""
deltaL = 0
deltaR = 0
if prev_enc_L > 15000 and float(row['posL']) < -15000:
# forward from + to -
deltaL = float(row['posL']) - MIN_INT_16
deltaL = deltaL + (MAX_INT_16 - prev_enc_L)
elif prev_enc_L < -15000 and float(row['posL']) > 15000:
# backward from - to +
deltaL = float(row['posL']) - MAX_INT_16
deltaL = deltaL + (MIN_INT_16 - prev_enc_L)
else:
deltaL = float(row['posL']) - prev_enc_L
if prev_enc_R > 15000 and float(row['posR']) < -15000:
# forward from + to -
deltaR = float(row['posR']) - MIN_INT_16
deltaR = deltaR + (MAX_INT_16 - prev_enc_R)
elif prev_enc_R < -15000 and float(row['posR']) > 15000:
# backward from - to +
deltaR = float(row['posR']) - MAX_INT_16
deltaR = deltaR + (MIN_INT_16 - prev_enc_R)
else:
deltaR = float(row['posR']) - prev_enc_R
return deltaL, deltaR
def timestamp_to_sec(timeStamp):
x = timeStamp.split(':')
return float(x[2])
def print_possitions(vel, enc):
print("Current position: ")
print("VELOCITIES: x: {}, y: {}, T: {}".format(round(vel[0, 0], 3), round(vel[1, 0], 3), round(vel[2, 0], 3)))
print("ENCODERS: x: {}, y: {}, T: {}".format(round(enc[0, 0], 3), round(enc[1, 0], 3), round(enc[2, 0], 3)))
def plot_trajectory(title, x, y):
plt.figure()
plt.plot(x, y)
plt.title(title)
def plot_both_trajectories(title, x1, y1, x2, y2):
plt.figure()
plt.plot(x1, y1)
plt.plot(x2, y2)
plt.title(title)
plt.legend(["velocity odometry", 'encoders odometry'])
def showPlots():
plt.show()
if __name__ == "__main__":
_file = 'data/velocity/square_left.csv'
MIN_INT_16 = -32768
MAX_INT_16 = 32767
current_pos_vel = np.mat('0;0;0')
current_pos_enc = np.mat('0;0;0')
# lists to hold data for print
pos_vel_x = []
pos_vel_y = []
pos_enc_x = []
pos_enc_y = []
with open(_file) as csvfile:
reader = csv.DictReader(csvfile, delimiter=';', quotechar='|')
prev_time = 0
prev_enc_l = 0
prev_enc_r = 0
prev_enc_init = False
for row in reader:
timestamp = timestamp_to_sec(row['#time'])
current_pos_vel = calculate_odometry_velocity(current_pos_vel, float(row['velL']), float(row['velR']), timestamp - prev_time)
pos_vel_x.append(current_pos_vel[0, 0])
pos_vel_y.append(current_pos_vel[1, 0])
prev_time = timestamp
if prev_enc_init == False:
prev_enc_l = float(row['posL'])
prev_enc_r = float(row['posR'])
prev_enc_init = True
delta_l, delta__r = calcualte_encoder_shift(row, prev_enc_l, prev_enc_r)
current_pos_enc = calculate_odometry_encoders(current_pos_enc, delta_l, delta__r)
pos_enc_x.append(current_pos_enc[0, 0])
pos_enc_y.append(current_pos_enc[1, 0])
prev_enc_l = float(row['posL'])
prev_enc_r = float(row['posR'])
print_possitions(current_pos_vel, current_pos_enc)
plot_both_trajectories("encoders + velocity", pos_vel_x, pos_vel_y, pos_enc_x, pos_enc_y)
showPlots()
|
[
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"csv.DictReader",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.figure",
"numpy.mat"
] |
[((721, 745), 'numpy.mat', 'np.mat', (['[[velR], [velL]]'], {}), '([[velR], [velL]])\n', (727, 745), True, 'import numpy as np\n'), ((1466, 1551), 'numpy.mat', 'np.mat', (['[[deltaR / ticksPerRev * np.pi * d], [deltaL / ticksPerRev * np.pi * d]]'], {}), '([[deltaR / ticksPerRev * np.pi * d], [deltaL / ticksPerRev * np.pi * d]]\n )\n', (1472, 1551), True, 'import numpy as np\n'), ((3349, 3361), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (3359, 3361), True, 'from matplotlib import pyplot as plt\n'), ((3366, 3380), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y'], {}), '(x, y)\n', (3374, 3380), True, 'from matplotlib import pyplot as plt\n'), ((3385, 3401), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (3394, 3401), True, 'from matplotlib import pyplot as plt\n'), ((3459, 3471), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (3469, 3471), True, 'from matplotlib import pyplot as plt\n'), ((3476, 3492), 'matplotlib.pyplot.plot', 'plt.plot', (['x1', 'y1'], {}), '(x1, y1)\n', (3484, 3492), True, 'from matplotlib import pyplot as plt\n'), ((3497, 3513), 'matplotlib.pyplot.plot', 'plt.plot', (['x2', 'y2'], {}), '(x2, y2)\n', (3505, 3513), True, 'from matplotlib import pyplot as plt\n'), ((3518, 3534), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (3527, 3534), True, 'from matplotlib import pyplot as plt\n'), ((3539, 3593), 'matplotlib.pyplot.legend', 'plt.legend', (["['velocity odometry', 'encoders odometry']"], {}), "(['velocity odometry', 'encoders odometry'])\n", (3549, 3593), True, 'from matplotlib import pyplot as plt\n'), ((3617, 3627), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3625, 3627), True, 'from matplotlib import pyplot as plt\n'), ((3773, 3788), 'numpy.mat', 'np.mat', (['"""0;0;0"""'], {}), "('0;0;0')\n", (3779, 3788), True, 'import numpy as np\n'), ((3811, 3826), 'numpy.mat', 'np.mat', (['"""0;0;0"""'], {}), "('0;0;0')\n", (3817, 3826), True, 'import numpy as np\n'), ((3994, 4047), 'csv.DictReader', 'csv.DictReader', (['csvfile'], {'delimiter': '""";"""', 'quotechar': '"""|"""'}), "(csvfile, delimiter=';', quotechar='|')\n", (4008, 4047), False, 'import csv\n')]
|
# Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the CC-by-NC license found in the
# LICENSE file in the root directory of this source tree.
#
import argparse
import datetime
import numpy as np
import time
import torch
import torch.backends.cudnn as cudnn
import json
import os
import warnings
from pathlib import Path
from timm.data import Mixup
from timm.models import create_model
from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy
from timm.scheduler import create_scheduler
from timm.optim import create_optimizer
from timm.utils import NativeScaler, get_state_dict, ModelEma
#from datasets import build_dataset
from engine import train_one_epoch, evaluate
from samplers import RASampler
import models
import my_models
import torch.nn as nn
import simclr
import utils
from losses import DeepMutualLoss, ONELoss, MulMixturelLoss, SelfDistillationLoss
from video_dataset import VideoDataSet, VideoDataSetLMDB, VideoDataSetOnline
from video_dataset_aug import get_augmentor, build_dataflow
from video_dataset_config import get_dataset_config, DATASET_CONFIG
warnings.filterwarnings("ignore", category=UserWarning)
#torch.multiprocessing.set_start_method('spawn', force=True)
def get_args_parser():
parser = argparse.ArgumentParser('DeiT training and evaluation script', add_help=False)
parser.add_argument('--batch-size', default=64, type=int)
parser.add_argument('--epochs', default=300, type=int)
# Dataset parameters
parser.add_argument('--data_dir', type=str, metavar='DIR', help='path to dataset')
parser.add_argument('--dataset', default='st2stv2',
choices=list(DATASET_CONFIG.keys()), help='path to dataset file list')
parser.add_argument('--duration', default=8, type=int, help='number of frames')
parser.add_argument('--frame_cls_tokens', default=1, type=int, help='number of cls tokens per frame')
parser.add_argument('--frames_per_group', default=1, type=int,
help='[uniform sampling] number of frames per group; '
'[dense sampling]: sampling frequency')
parser.add_argument('--threed_data', action='store_true',
help='load data in the layout for 3D conv')
parser.add_argument('--input_size', default=224, type=int, metavar='N', help='input image size')
parser.add_argument('--disable_scaleup', action='store_true',
help='do not scale up and then crop a small region, directly crop the input_size')
parser.add_argument('--random_sampling', action='store_true',
help='perform determinstic sampling for data loader')
parser.add_argument('--dense_sampling', action='store_true',
help='perform dense sampling for data loader')
parser.add_argument('--augmentor_ver', default='v1', type=str, choices=['v1', 'v2'],
help='[v1] TSN data argmentation, [v2] resize the shorter side to `scale_range`')
parser.add_argument('--scale_range', default=[256, 320], type=int, nargs="+",
metavar='scale_range', help='scale range for augmentor v2')
parser.add_argument('--modality', default='rgb', type=str, help='rgb or flow',
choices=['rgb', 'flow'])
parser.add_argument('--use_lmdb', action='store_true', help='use lmdb instead of jpeg.')
parser.add_argument('--use_pyav', action='store_true', help='use video directly.')
# temporal module
parser.add_argument('--pretrained', action='store_true', default=False,
help='Start with pretrained version of specified network (if avail)')
parser.add_argument('--temporal_module_name', default=None, type=str, metavar='TEM', choices=['ResNet3d', 'TAM', 'TTAM', 'TSM', 'TTSM', 'MSA'],
help='temporal module applied. [TAM]')
parser.add_argument('--temporal_attention_only', action='store_true', default=False,
help='use attention only in temporal module]')
parser.add_argument('--no_token_mask', action='store_true', default=False, help='do not apply token mask')
parser.add_argument('--temporal_heads_scale', default=1.0, type=float, help='scale of the number of spatial heads')
parser.add_argument('--temporal_mlp_scale', default=1.0, type=float, help='scale of spatial mlp')
parser.add_argument('--rel_pos', action='store_true', default=False,
help='use relative positioning in temporal module]')
parser.add_argument('--temporal_pooling', type=str, default=None, choices=['avg', 'max', 'conv', 'depthconv'],
help='perform temporal pooling')
parser.add_argument('--bottleneck', default=None, choices=['regular', 'dw'],
help='use depth-wise bottleneck in temporal attention')
parser.add_argument('--temporal_roll', action='store_true', default=False,
help='use temporal rolling to enhance temporal interaction')
parser.add_argument('--window_size', default=7, type=int, help='number of frames')
parser.add_argument('--super_img_rows', default=1, type=int, help='number of frames per row')
parser.add_argument('--hpe_to_token', default=False, action='store_true',
help='add hub position embedding to image tokens')
parser.add_argument('--spatial_hub_size', type=int, nargs='+', default=[1,1],
help='grid size for spatial hubs')
parser.add_argument('--hub_attention', default='join',
choices=['join', 'divided'], help='ways to do hub attention')
parser.add_argument('--hub_aggregation', default='avg',
choices=['avg', 'max', 'diagonal', 'se', 'conv', 'weighted_diagonal'], help='ways to aggregate hub tokens')
# Model parameters
parser.add_argument('--model', default='deit_base_patch16_224', type=str, metavar='MODEL',
help='Name of model to train')
# parser.add_argument('--input-size', default=224, type=int, help='images input size')
parser.add_argument('--drop', type=float, default=0.0, metavar='PCT',
help='Dropout rate (default: 0.)')
parser.add_argument('--drop-path', type=float, default=0.0, metavar='PCT',
help='Drop path rate (default: 0.1)')
parser.add_argument('--drop-block', type=float, default=None, metavar='PCT',
help='Drop block rate (default: None)')
parser.add_argument('--model-ema', action='store_true')
parser.add_argument('--no-model-ema', action='store_false', dest='model_ema')
parser.set_defaults(model_ema=True)
parser.add_argument('--model-ema-decay', type=float, default=0.99996, help='')
parser.add_argument('--model-ema-force-cpu', action='store_true', default=False, help='')
# Optimizer parameters
parser.add_argument('--opt', default='adamw', type=str, metavar='OPTIMIZER',
help='Optimizer (default: "adamw"')
parser.add_argument('--opt-eps', default=1e-8, type=float, metavar='EPSILON',
help='Optimizer Epsilon (default: 1e-8)')
parser.add_argument('--opt-betas', default=None, type=float, nargs='+', metavar='BETA',
help='Optimizer Betas (default: None, use opt default)')
parser.add_argument('--clip-grad', type=float, default=None, metavar='NORM',
help='Clip gradient norm (default: None, no clipping)')
parser.add_argument('--momentum', type=float, default=0.9, metavar='M',
help='SGD momentum (default: 0.9)')
parser.add_argument('--weight-decay', type=float, default=0.05,
help='weight decay (default: 0.05)')
# Learning rate schedule parameters
parser.add_argument('--sched', default='cosine', type=str, metavar='SCHEDULER',
help='LR scheduler (default: "cosine"')
parser.add_argument('--lr', type=float, default=5e-4, metavar='LR',
help='learning rate (default: 5e-4)')
parser.add_argument('--p_lr', type=float, default=5e-4,
help='the learning rate for the policy model')
parser.add_argument('--lr-noise', type=float, nargs='+', default=None, metavar='pct, pct',
help='learning rate noise on/off epoch percentages')
parser.add_argument('--lr-noise-pct', type=float, default=0.67, metavar='PERCENT',
help='learning rate noise limit percent (default: 0.67)')
parser.add_argument('--lr-noise-std', type=float, default=1.0, metavar='STDDEV',
help='learning rate noise std-dev (default: 1.0)')
parser.add_argument('--warmup-lr', type=float, default=1e-6, metavar='LR',
help='warmup learning rate (default: 1e-6)')
parser.add_argument('--min-lr', type=float, default=1e-5, metavar='LR',
help='lower lr bound for cyclic schedulers that hit 0 (1e-5)')
parser.add_argument('--decay-epochs', type=float, default=30, metavar='N',
help='epoch interval to decay LR')
parser.add_argument('--warmup-epochs', type=int, default=5, metavar='N',
help='epochs to warmup LR, if scheduler supports')
parser.add_argument('--cooldown-epochs', type=int, default=10, metavar='N',
help='epochs to cooldown LR at min_lr, after cyclic schedule ends')
parser.add_argument('--patience-epochs', type=int, default=10, metavar='N',
help='patience epochs for Plateau LR scheduler (default: 10')
parser.add_argument('--decay-rate', '--dr', type=float, default=0.1, metavar='RATE',
help='LR decay rate (default: 0.1)')
# Augmentation parameters
parser.add_argument('--color-jitter', type=float, default=0.4, metavar='PCT',
help='Color jitter factor (default: 0.4)')
parser.add_argument('--aa', type=str, default='rand-m9-mstd0.5-inc1', metavar='NAME',
help='Use AutoAugment policy. "v0" or "original". " + \
"(default: rand-m9-mstd0.5-inc1)'),
parser.add_argument('--smoothing', type=float, default=0.1, help='Label smoothing (default: 0.1)')
parser.add_argument('--train-interpolation', type=str, default='bicubic',
help='Training interpolation (random, bilinear, bicubic default: "bicubic")')
parser.add_argument('--repeated-aug', action='store_true')
parser.add_argument('--no-repeated-aug', action='store_false', dest='repeated_aug')
parser.set_defaults(repeated_aug=False)
# * Random Erase params
parser.add_argument('--reprob', type=float, default=0.0, metavar='PCT',
help='Random erase prob (default: 0.25)')
parser.add_argument('--remode', type=str, default='pixel',
help='Random erase mode (default: "pixel")')
parser.add_argument('--recount', type=int, default=1,
help='Random erase count (default: 1)')
parser.add_argument('--resplit', action='store_true', default=False,
help='Do not random erase first (clean) augmentation split')
# * Mixup params
parser.add_argument('--mixup', type=float, default=0.0,
help='mixup alpha, mixup enabled if > 0. (default: 0.8)')
parser.add_argument('--cutmix', type=float, default=0.0,
help='cutmix alpha, cutmix enabled if > 0. (default: 1.0)')
parser.add_argument('--cutmix-minmax', type=float, nargs='+', default=None,
help='cutmix min/max ratio, overrides alpha and enables cutmix if set (default: None)')
parser.add_argument('--mixup-prob', type=float, default=1.0,
help='Probability of performing mixup or cutmix when either/both is enabled')
parser.add_argument('--mixup-switch-prob', type=float, default=0.5,
help='Probability of switching to cutmix when both mixup and cutmix enabled')
parser.add_argument('--mixup-mode', type=str, default='batch',
help='How to apply mixup/cutmix params. Per "batch", "pair", or "elem"')
# Dataset parameters
# parser.add_argument('--data-path', default=os.path.join(os.path.expanduser("~"), 'datasets/image_cls/imagenet1k/'), type=str,
# help='dataset path')
# parser.add_argument('--data-set', default='IMNET', choices=['CIFAR10', 'CIFAR100', 'IMNET', 'INAT', 'INAT19', 'IMNET21K', 'Flowers102', 'StanfordCars', 'iNaturalist2019', 'Caltech101'],
# type=str, help='Image Net dataset path')
# parser.add_argument('--inat-category', default='name',
# choices=['kingdom', 'phylum', 'class', 'order', 'supercategory', 'family', 'genus', 'name'],
# type=str, help='semantic granularity')
parser.add_argument('--output_dir', default='',
help='path where to save, empty for no saving')
parser.add_argument('--device', default='cuda',
help='device to use for training / testing')
parser.add_argument('--seed', default=0, type=int)
parser.add_argument('--resume', default='', help='resume from checkpoint')
parser.add_argument('--no-resume-loss-scaler', action='store_false', dest='resume_loss_scaler')
parser.add_argument('--no-amp', action='store_false', dest='amp', help='disable amp')
parser.add_argument('--use_checkpoint', default=False, action='store_true', help='use checkpoint to save memory')
parser.add_argument('--start_epoch', default=0, type=int, metavar='N',
help='start epoch')
parser.add_argument('--eval', action='store_true', help='Perform evaluation only')
parser.add_argument('--num_workers', default=10, type=int)
parser.add_argument('--pin-mem', action='store_true',
help='Pin CPU memory in DataLoader for more efficient (sometimes) transfer to GPU.')
parser.add_argument('--no-pin-mem', action='store_false', dest='pin_mem',
help='')
parser.set_defaults(pin_mem=True)
# for testing and validation
parser.add_argument('--num_crops', default=1, type=int, choices=[1, 3, 5, 10])
parser.add_argument('--num_clips', default=1, type=int)
# distributed training parameters
parser.add_argument('--world_size', default=1, type=int,
help='number of distributed processes')
parser.add_argument("--local_rank", type=int)
parser.add_argument('--dist_url', default='env://', help='url used to set up distributed training')
parser.add_argument('--auto-resume', action='store_true', help='auto resume')
# exp
parser.add_argument('--simclr_w', type=float, default=0., help='weights for simclr loss')
parser.add_argument('--contrastive_nomixup', action='store_true', help='do not involve mixup in contrastive learning')
parser.add_argument('--temperature', type=float, default=0.07, help='temperature of NCE')
parser.add_argument('--branch_div_w', type=float, default=0., help='add branch divergence in the loss')
parser.add_argument('--simsiam_w', type=float, default=0., help='weights for simsiam loss')
parser.add_argument('--moco_w', type=float, default=0., help='weights for moco loss')
parser.add_argument('--byol_w', type=float, default=0., help='weights for byol loss')
parser.add_argument('--finetune', action='store_true', help='finetune model')
parser.add_argument('--initial_checkpoint', type=str, default='', help='path to the pretrained model')
parser.add_argument('--dml_w', type=float, default=0., help='enable deep mutual learning')
parser.add_argument('--one_w', type=float, default=0., help='enable ONE')
parser.add_argument('--kd_temp', type=float, default=1.0, help='temperature for kd loss')
parser.add_argument('--mulmix_b', type=float, default=0., help='mulmix beta')
parser.add_argument('--hard_contrastive', action='store_true', help='use HEXA')
parser.add_argument('--selfdis_w', type=float, default=0., help='enable self distillation')
#iterative training
parser.add_argument('--curr_stage', type = str, default='warmup', help='the stage for training, can be set as warmup, alternative_training, and finetune')
parser.add_argument('--weight_decay', type = float, default= 0.0, help='the weight decay for creating optimizor')
parser.add_argument('--warmup_epochs', type = int, default= 1, help='the number epochs for warmup')
parser.add_argument('--finetune_epochs', type = int, default= 1, help='the number epochs for finetuning')
return parser
def main(args):
utils.init_distributed_mode(args)
print(args)
# Patch
if not hasattr(args, 'hard_contrastive'):
args.hard_contrastive = False
if not hasattr(args, 'selfdis_w'):
args.selfdis_w = 0.0
#is_imnet21k = args.data_set == 'IMNET21K'
device = torch.device(args.device)
# fix the seed for reproducibility
seed = args.seed + utils.get_rank()
torch.manual_seed(seed)
np.random.seed(seed)
# random.seed(seed)
cudnn.benchmark = True
num_classes, train_list_name, val_list_name, test_list_name, filename_seperator, image_tmpl, filter_video, label_file = get_dataset_config(
args.dataset, args.use_lmdb)
args.num_classes = num_classes
if args.modality == 'rgb':
args.input_channels = 3
elif args.modality == 'flow':
args.input_channels = 2 * 5
# mean = IMAGENET_DEFAULT_MEAN
# std = IMAGENET_DEFAULT_STD
mixup_fn = None
mixup_active = args.mixup > 0 or args.cutmix > 0. or args.cutmix_minmax is not None
if mixup_active:
mixup_fn = Mixup(
mixup_alpha=args.mixup, cutmix_alpha=args.cutmix, cutmix_minmax=args.cutmix_minmax,
prob=args.mixup_prob, switch_prob=args.mixup_switch_prob, mode=args.mixup_mode,
label_smoothing=args.smoothing, num_classes=args.num_classes)
print(f"Creating model: {args.model}")
model = create_model(
args.model,
pretrained=args.pretrained,
duration=args.duration,
frame_cls_tokens=args.frame_cls_tokens,
temporal_module_name=args.temporal_module_name,
temporal_attention_only=args.temporal_attention_only,
temporal_heads_scale=args.temporal_heads_scale,
temporal_mlp_scale = args.temporal_mlp_scale,
hpe_to_token = args.hpe_to_token,
spatial_hub_size = args.spatial_hub_size,
hub_attention=args.hub_attention,
hub_aggregation=args.hub_aggregation,
temporal_pooling = args.temporal_pooling,
bottleneck = args.bottleneck,
temporal_roll=args.temporal_roll,
rel_pos = args.rel_pos,
window_size=args.window_size,
super_img_rows = args.super_img_rows,
token_mask=not args.no_token_mask,
online_learning = args.one_w >0.0 or args.dml_w >0.0,
num_classes=args.num_classes,
drop_rate=args.drop,
drop_path_rate=args.drop_path,
drop_block_rate=args.drop_block,
use_checkpoint=args.use_checkpoint
)
# TODO: finetuning
model.to(device)
model_ema = None
if args.model_ema:
# Important to create EMA model after cuda(), DP wrapper, and AMP but before SyncBN and DDP wrapper
model_ema = ModelEma(
model,
decay=args.model_ema_decay,
device='cpu' if args.model_ema_force_cpu else '',
resume='')
model_without_ddp = model
if args.distributed:
#model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu], find_unused_parameters=True)
model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu])
model_without_ddp = model.module
n_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad)
print('number of params:', n_parameters)
#linear_scaled_lr = args.lr * args.batch_size * utils.get_world_size() / 512.0
#args.lr = linear_scaled_lr
##################
# use two separate optimizers
# policy_net_params = model.module.policy_net.parameters()
# main_net_params = model.module.main_net.parameters()
# optimizer = create_optimizer(args, model)
p_optimizer = torch.optim.Adam(model.parameters(), args.p_lr, weight_decay=args.weight_decay)
optimizer = torch.optim.Adam(model.parameters(), args.lr, weight_decay=args.weight_decay)
loss_scaler = NativeScaler()
#print(f"Scaled learning rate (batch size: {args.batch_size * utils.get_world_size()}): {linear_scaled_lr}")
lr_scheduler, _ = create_scheduler(args, optimizer)
p_scheduler, _ = create_scheduler(args, p_optimizer)
criterion = LabelSmoothingCrossEntropy()
if args.mixup > 0.:
# smoothing is handled with mixup label transform
criterion = SoftTargetCrossEntropy()
elif args.smoothing:
criterion = LabelSmoothingCrossEntropy(smoothing=args.smoothing)
else:
criterion = torch.nn.CrossEntropyLoss()
if args.dml_w > 0.:
criterion = DeepMutualLoss(criterion, args.dml_w, args.kd_temp)
elif args.one_w > 0.:
criterion = ONELoss(criterion, args.one_w, args.kd_temp)
elif args.mulmix_b > 0.:
criterion = MulMixturelLoss(criterion, args.mulmix_b)
elif args.selfdis_w > 0.:
criterion = SelfDistillationLoss(criterion, args.selfdis_w, args.kd_temp)
simclr_criterion = simclr.NTXent(temperature=args.temperature) if args.simclr_w > 0. else None
branch_div_criterion = torch.nn.CosineSimilarity() if args.branch_div_w > 0. else None
simsiam_criterion = simclr.SimSiamLoss() if args.simsiam_w > 0. else None
moco_criterion = torch.nn.CrossEntropyLoss() if args.moco_w > 0. else None
byol_criterion = simclr.BYOLLoss() if args.byol_w > 0. else None
max_accuracy = 0.0
output_dir = Path(args.output_dir)
curr_stage = args.curr_stage
if args.initial_checkpoint:
print("Loading pretrained model")
checkpoint = torch.load(args.initial_checkpoint, map_location='cpu')
utils.load_checkpoint(model, checkpoint['model'])
if args.auto_resume:
if args.resume == '':
args.resume = str(output_dir / "checkpoint.pth")
if not os.path.exists(args.resume):
args.resume = ''
if args.resume:
if args.resume.startswith('https'):
checkpoint = torch.hub.load_state_dict_from_url(
args.resume, map_location='cpu', check_hash=True)
else:
checkpoint = torch.load(args.resume, map_location='cpu')
utils.load_checkpoint(model, checkpoint['model'])
if not args.eval and 'optimizer' in checkpoint and 'lr_scheduler' in checkpoint and 'p_optimizer' in checkpoint and 'p_scheduler' in checkpoint and 'scheduler' in checkpoint and 'epoch' in checkpoint:
optimizer.load_state_dict(checkpoint['optimizer'])
lr_scheduler.load_state_dict(checkpoint['lr_scheduler'])
p_optimizer.load_state_dict(checkpoint['p_optimizer'])
try:
p_scheduler.load_state_dict(checkpoint['p_scheduler'])
# scheduler.load_state_dict(checkpoint['scheduler'])
except:
pass
args.start_epoch = checkpoint['epoch'] + 1
if 'scaler' in checkpoint and args.resume_loss_scaler:
print("Resume with previous loss scaler state")
loss_scaler.load_state_dict(checkpoint['scaler'])
if args.model_ema:
utils._load_checkpoint_for_ema(model_ema, checkpoint['model_ema'])
max_accuracy = checkpoint['max_accuracy']
curr_stage = checkpoint['stage']
mean = (0.5, 0.5, 0.5) if 'mean' not in model.module.default_cfg else model.module.default_cfg['mean']
std = (0.5, 0.5, 0.5) if 'std' not in model.module.default_cfg else model.module.default_cfg['std']
# dataset_train, args.nb_classes = build_dataset(is_train=True, args=args)
# create data loaders w/ augmentation pipeiine
if args.use_lmdb:
video_data_cls = VideoDataSetLMDB
elif args.use_pyav:
video_data_cls = VideoDataSetOnline
else:
video_data_cls = VideoDataSet
train_list = os.path.join(args.data_dir, train_list_name)
train_augmentor = get_augmentor(True, args.input_size, mean, std, threed_data=args.threed_data,
version=args.augmentor_ver, scale_range=args.scale_range, dataset=args.dataset)
dataset_train = video_data_cls(args.data_dir, train_list, args.duration, args.frames_per_group,
num_clips=args.num_clips,
modality=args.modality, image_tmpl=image_tmpl,
dense_sampling=args.dense_sampling,
transform=train_augmentor, is_train=True, test_mode=False,
seperator=filename_seperator, filter_video=filter_video)
num_tasks = utils.get_world_size()
data_loader_train = build_dataflow(dataset_train, is_train=True, batch_size=args.batch_size,
workers=args.num_workers, is_distributed=args.distributed)
val_list = os.path.join(args.data_dir, val_list_name)
val_augmentor = get_augmentor(False, args.input_size, mean, std, args.disable_scaleup,
threed_data=args.threed_data, version=args.augmentor_ver,
scale_range=args.scale_range, num_clips=args.num_clips, num_crops=args.num_crops, dataset=args.dataset)
dataset_val = video_data_cls(args.data_dir, val_list, args.duration, args.frames_per_group,
num_clips=args.num_clips,
modality=args.modality, image_tmpl=image_tmpl,
dense_sampling=args.dense_sampling,
transform=val_augmentor, is_train=False, test_mode=False,
seperator=filename_seperator, filter_video=filter_video)
data_loader_val = build_dataflow(dataset_val, is_train=False, batch_size=args.batch_size,
workers=args.num_workers, is_distributed=args.distributed)
if args.eval:
test_stats = evaluate(data_loader_val, model, device, num_tasks, distributed=True, amp=args.amp, num_crops=args.num_crops, num_clips=args.num_clips)
print(f"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%")
return
print(f"Start training, currnet max acc is {max_accuracy:.2f}")
start_time = time.time()
"""
Stage 2: Warmup the main network
Needed args: warmup epochs, lr, lr_scheduler,
- Freeze the policy net
"""
if curr_stage == 'warmup':
if args.warmup_epochs > 0:
print("Stage [Warming up]: Main network with {} epochs".format(args.warmup_epochs))
utils.unfreeze_model_weights(model)
utils.freeze_policy_net(model)
for epoch in range(args.start_epoch, args.warmup_epochs):
##train_one_epoch needs to be updated with p_optimizer
train_stats = train_one_epoch(
model, criterion, data_loader_train,
optimizer, device, epoch, loss_scaler,
args.clip_grad, model_ema, mixup_fn, num_tasks, True,
amp=args.amp,
simclr_criterion=simclr_criterion, simclr_w=args.simclr_w,
branch_div_criterion=branch_div_criterion, branch_div_w=args.branch_div_w,
simsiam_criterion=simsiam_criterion, simsiam_w=args.simsiam_w,
moco_criterion=moco_criterion, moco_w=args.moco_w,
byol_criterion=byol_criterion, byol_w=args.byol_w,
contrastive_nomixup=args.contrastive_nomixup,
hard_contrastive=args.hard_contrastive,
finetune=args.finetune)
lr_scheduler.step(epoch)
test_stats = evaluate(data_loader_val, model, device, num_tasks, distributed=True, amp=args.amp)
print(f"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%")
max_accuracy = max(max_accuracy, test_stats["acc1"])
print(f'Max accuracy: {max_accuracy:.2f}%')
if args.output_dir:
checkpoint_paths = [output_dir / 'checkpoint.pth']
if test_stats["acc1"] == max_accuracy:
checkpoint_paths.append(output_dir / 'model_best.pth')
for checkpoint_path in checkpoint_paths:
state_dict = {
'model': model_without_ddp.state_dict(),
'p_optimizer': p_optimizer.state_dict(),
'optimizer': optimizer.state_dict(),
'lr_scheduler': lr_scheduler.state_dict(),
'p_scheduler': p_scheduler.state_dict(),
'epoch': epoch,
'args': args,
'scaler': loss_scaler.state_dict(),
'max_accuracy': max_accuracy
}
log_stats = {**{f'train_{k}': v for k, v in train_stats.items()},
**{f'test_{k}': v for k, v in test_stats.items()},
'epoch': epoch,
'n_parameters': n_parameters}
if args.output_dir and utils.is_main_process():
with (output_dir / "log.txt").open("a") as f:
f.write(json.dumps(log_stats) + "\n")
# move to the next stage
curr_stage = 'alternative_training'
# policy_net_params = model.module.policy_net.parameters()
# main_net_params = model.module.main_net.parameters()
p_optimizer = torch.optim.Adam(model, args.p_lr,
weight_decay=args.weight_decay)
optimizer = torch.optim.Adam(model, args.lr,
weight_decay=args.weight_decay)
args.start_epoch = 0
"""
Stage 3: alternative training
Main net (k epochs) -> Policy net (k epochs) -> Main net (k epochs) ...
k is a configurable args, default = 1
- alternative_k:
- number of alternatives is determined by total_epochs // alternative_k
"""
if curr_stage == 'alternative_training':
print("Stage [Alternative training]: {} epochs".format(args.epochs))
for epoch in range(args.start_epoch, args.epochs):
print("Stage [Alternative training]: Training Main net")
# start with main net:
utils.unfreeze_model_weights(model)
utils.freeze_policy_net(model)
train_stats = train_one_epoch(
model, criterion, data_loader_train,
optimizer, device, epoch, loss_scaler,
args.clip_grad, model_ema, mixup_fn, num_tasks, True,
amp=args.amp,
simclr_criterion=simclr_criterion, simclr_w=args.simclr_w,
branch_div_criterion=branch_div_criterion, branch_div_w=args.branch_div_w,
simsiam_criterion=simsiam_criterion, simsiam_w=args.simsiam_w,
moco_criterion=moco_criterion, moco_w=args.moco_w,
byol_criterion=byol_criterion, byol_w=args.byol_w,
contrastive_nomixup=args.contrastive_nomixup,
hard_contrastive=args.hard_contrastive,
finetune=args.finetune)
lr_scheduler.step(epoch)
# change to policy net:
print("Stage [Alternative training]: Training Policy net")
utils.unfreeze_model_weights(model)
utils.freeze_main_net(model)
train_stats = train_one_epoch(
model, criterion, data_loader_train,
optimizer, device, epoch, loss_scaler,
args.clip_grad, model_ema, mixup_fn, num_tasks, True,
amp=args.amp,
simclr_criterion=simclr_criterion, simclr_w=args.simclr_w,
branch_div_criterion=branch_div_criterion, branch_div_w=args.branch_div_w,
simsiam_criterion=simsiam_criterion, simsiam_w=args.simsiam_w,
moco_criterion=moco_criterion, moco_w=args.moco_w,
byol_criterion=byol_criterion, byol_w=args.byol_w,
contrastive_nomixup=args.contrastive_nomixup,
hard_contrastive=args.hard_contrastive,
finetune=args.finetune)
test_stats = evaluate(data_loader_val, model, device, num_tasks, distributed=True, amp=args.amp)
print(f"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%")
max_accuracy = max(max_accuracy, test_stats["acc1"])
print(f'Max accuracy: {max_accuracy:.2f}%')
p_scheduler.step(epoch)
lr_scheduler.step(epoch)
if args.output_dir:
checkpoint_paths = [output_dir / 'checkpoint.pth']
if test_stats["acc1"] == max_accuracy:
checkpoint_paths.append(output_dir / 'model_best.pth')
for checkpoint_path in checkpoint_paths:
state_dict = {
'model': model_without_ddp.state_dict(),
'p_optimizer': p_optimizer.state_dict(),
'optimizer': optimizer.state_dict(),
'lr_scheduler': lr_scheduler.state_dict(),
'p_scheduler': p_scheduler.state_dict(),
'epoch': epoch,
'args': args,
'scaler': loss_scaler.state_dict(),
'max_accuracy': max_accuracy
}
log_stats = {**{f'train_{k}': v for k, v in train_stats.items()},
**{f'test_{k}': v for k, v in test_stats.items()},
'epoch': epoch,
'n_parameters': n_parameters}
if args.output_dir and utils.is_main_process():
with (output_dir / "log.txt").open("a") as f:
f.write(json.dumps(log_stats) + "\n")
# move to next stage
curr_stage = 'finetune'
# policy_net_params = model.module.policy_net.parameters()
# main_net_params = model.module.main_net.parameters()
p_optimizer = torch.optim.Adam(model, args.p_lr,
weight_decay=args.weight_decay)
optimizer = torch.optim.Adam(model, args.lr,
weight_decay=args.weight_decay)
args.start_epoch = 0
"""
Stage 4: fixed policy net and then finetune main network for few epochs
finetune epochs
"""
if curr_stage == 'finetune':
print("Stage [Post finetuning]: Finetune the main network {} epochs".format(args.finetune_epochs))
if args.finetune_epochs > 0:
# finetune on top of the best model when it moves from the previous stage
utils.unfreeze_model_weights(model)
utils.freeze_policy_net(model)
for epoch in range(args.start_epoch, args.finetune_epochs):
# NOTE: disable cost weight here
train_stats = train_one_epoch(
model, criterion, data_loader_train,
optimizer, device, epoch, loss_scaler,
args.clip_grad, model_ema, mixup_fn, num_tasks, True,
amp=args.amp,
simclr_criterion=simclr_criterion, simclr_w=args.simclr_w,
branch_div_criterion=branch_div_criterion, branch_div_w=args.branch_div_w,
simsiam_criterion=simsiam_criterion, simsiam_w=args.simsiam_w,
moco_criterion=moco_criterion, moco_w=args.moco_w,
byol_criterion=byol_criterion, byol_w=args.byol_w,
contrastive_nomixup=args.contrastive_nomixup,
hard_contrastive=args.hard_contrastive,
finetune=args.finetune)
test_stats = evaluate(data_loader_val, model, device, num_tasks, distributed=True, amp=args.amp)
print(f"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%")
max_accuracy = max(max_accuracy, test_stats["acc1"])
print(f'Max accuracy: {max_accuracy:.2f}%')
p_scheduler.step(epoch)
lr_scheduler.step(epoch)
if args.output_dir:
checkpoint_paths = [output_dir / 'checkpoint.pth']
if test_stats["acc1"] == max_accuracy:
checkpoint_paths.append(output_dir / 'model_best.pth')
for checkpoint_path in checkpoint_paths:
state_dict = {
'model': model_without_ddp.state_dict(),
'p_optimizer': p_optimizer.state_dict(),
'optimizer': optimizer.state_dict(),
'lr_scheduler': lr_scheduler.state_dict(),
'p_scheduler': p_scheduler.state_dict(),
'epoch': epoch,
'args': args,
'scaler': loss_scaler.state_dict(),
'max_accuracy': max_accuracy
}
log_stats = {**{f'train_{k}': v for k, v in train_stats.items()},
**{f'test_{k}': v for k, v in test_stats.items()},
'epoch': epoch,
'n_parameters': n_parameters}
if args.output_dir and utils.is_main_process():
with (output_dir / "log.txt").open("a") as f:
f.write(json.dumps(log_stats) + "\n")
# for epoch in range(args.start_epoch, args.epochs):
# if args.distributed:
# data_loader_train.sampler.set_epoch(epoch)
# train_stats = train_one_epoch(
# model, criterion, data_loader_train,
# optimizer, device, epoch, loss_scaler,
# args.clip_grad, model_ema, mixup_fn, num_tasks, True,
# amp=args.amp,
# simclr_criterion=simclr_criterion, simclr_w=args.simclr_w,
# branch_div_criterion=branch_div_criterion, branch_div_w=args.branch_div_w,
# simsiam_criterion=simsiam_criterion, simsiam_w=args.simsiam_w,
# moco_criterion=moco_criterion, moco_w=args.moco_w,
# byol_criterion=byol_criterion, byol_w=args.byol_w,
# contrastive_nomixup=args.contrastive_nomixup,
# hard_contrastive=args.hard_contrastive,
# finetune=args.finetune
# )
# lr_scheduler.step(epoch)
# test_stats = evaluate(data_loader_val, model, device, num_tasks, distributed=True, amp=args.amp)
# print(f"Accuracy of the network on the {len(dataset_val)} test images: {test_stats['acc1']:.1f}%")
# max_accuracy = max(max_accuracy, test_stats["acc1"])
# print(f'Max accuracy: {max_accuracy:.2f}%')
# if args.output_dir:
# checkpoint_paths = [output_dir / 'checkpoint.pth']
# if test_stats["acc1"] == max_accuracy:
# checkpoint_paths.append(output_dir / 'model_best.pth')
# for checkpoint_path in checkpoint_paths:
# state_dict = {
# 'model': model_without_ddp.state_dict(),
# 'optimizer': optimizer.state_dict(),
# 'lr_scheduler': lr_scheduler.state_dict(),
# 'epoch': epoch,
# 'args': args,
# 'scaler': loss_scaler.state_dict(),
# 'max_accuracy': max_accuracy
# }
# if args.model_ema:
# state_dict['model_ema'] = get_state_dict(model_ema)
# utils.save_on_master(state_dict, checkpoint_path)
# log_stats = {**{f'train_{k}': v for k, v in train_stats.items()},
# **{f'test_{k}': v for k, v in test_stats.items()},
# 'epoch': epoch,
# 'n_parameters': n_parameters}
# if args.output_dir and utils.is_main_process():
# with (output_dir / "log.txt").open("a") as f:
# f.write(json.dumps(log_stats) + "\n")
# total_time = time.time() - start_time
# total_time_str = str(datetime.timedelta(seconds=int(total_time)))
# print('Training time {}'.format(total_time_str))
if __name__ == '__main__':
parser = argparse.ArgumentParser('DeiT training and evaluation script', parents=[get_args_parser()])
args = parser.parse_args()
if args.output_dir:
Path(args.output_dir).mkdir(parents=True, exist_ok=True)
main(args)
|
[
"numpy.random.seed",
"argparse.ArgumentParser",
"utils.unfreeze_model_weights",
"utils.freeze_policy_net",
"video_dataset_config.get_dataset_config",
"json.dumps",
"pathlib.Path",
"torch.nn.CosineSimilarity",
"torch.device",
"losses.DeepMutualLoss",
"losses.ONELoss",
"os.path.join",
"timm.loss.SoftTargetCrossEntropy",
"timm.utils.NativeScaler",
"simclr.BYOLLoss",
"torch.nn.parallel.DistributedDataParallel",
"torch.load",
"os.path.exists",
"utils.load_checkpoint",
"utils.freeze_main_net",
"video_dataset_config.DATASET_CONFIG.keys",
"utils.is_main_process",
"losses.SelfDistillationLoss",
"utils.get_rank",
"utils.init_distributed_mode",
"torch.hub.load_state_dict_from_url",
"engine.train_one_epoch",
"timm.utils.ModelEma",
"torch.manual_seed",
"timm.models.create_model",
"timm.scheduler.create_scheduler",
"torch.optim.Adam",
"video_dataset_aug.build_dataflow",
"losses.MulMixturelLoss",
"utils.get_world_size",
"simclr.NTXent",
"timm.loss.LabelSmoothingCrossEntropy",
"warnings.filterwarnings",
"utils._load_checkpoint_for_ema",
"torch.nn.CrossEntropyLoss",
"time.time",
"engine.evaluate",
"timm.data.Mixup",
"video_dataset_aug.get_augmentor",
"simclr.SimSiamLoss"
] |
[((1145, 1200), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'category': 'UserWarning'}), "('ignore', category=UserWarning)\n", (1168, 1200), False, 'import warnings\n'), ((1299, 1377), 'argparse.ArgumentParser', 'argparse.ArgumentParser', (['"""DeiT training and evaluation script"""'], {'add_help': '(False)'}), "('DeiT training and evaluation script', add_help=False)\n", (1322, 1377), False, 'import argparse\n'), ((16912, 16945), 'utils.init_distributed_mode', 'utils.init_distributed_mode', (['args'], {}), '(args)\n', (16939, 16945), False, 'import utils\n'), ((17188, 17213), 'torch.device', 'torch.device', (['args.device'], {}), '(args.device)\n', (17200, 17213), False, 'import torch\n'), ((17298, 17321), 'torch.manual_seed', 'torch.manual_seed', (['seed'], {}), '(seed)\n', (17315, 17321), False, 'import torch\n'), ((17326, 17346), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (17340, 17346), True, 'import numpy as np\n'), ((17524, 17571), 'video_dataset_config.get_dataset_config', 'get_dataset_config', (['args.dataset', 'args.use_lmdb'], {}), '(args.dataset, args.use_lmdb)\n', (17542, 17571), False, 'from video_dataset_config import get_dataset_config, DATASET_CONFIG\n'), ((18291, 19235), 'timm.models.create_model', 'create_model', (['args.model'], {'pretrained': 'args.pretrained', 'duration': 'args.duration', 'frame_cls_tokens': 'args.frame_cls_tokens', 'temporal_module_name': 'args.temporal_module_name', 'temporal_attention_only': 'args.temporal_attention_only', 'temporal_heads_scale': 'args.temporal_heads_scale', 'temporal_mlp_scale': 'args.temporal_mlp_scale', 'hpe_to_token': 'args.hpe_to_token', 'spatial_hub_size': 'args.spatial_hub_size', 'hub_attention': 'args.hub_attention', 'hub_aggregation': 'args.hub_aggregation', 'temporal_pooling': 'args.temporal_pooling', 'bottleneck': 'args.bottleneck', 'temporal_roll': 'args.temporal_roll', 'rel_pos': 'args.rel_pos', 'window_size': 'args.window_size', 'super_img_rows': 'args.super_img_rows', 'token_mask': '(not args.no_token_mask)', 'online_learning': '(args.one_w > 0.0 or args.dml_w > 0.0)', 'num_classes': 'args.num_classes', 'drop_rate': 'args.drop', 'drop_path_rate': 'args.drop_path', 'drop_block_rate': 'args.drop_block', 'use_checkpoint': 'args.use_checkpoint'}), '(args.model, pretrained=args.pretrained, duration=args.duration,\n frame_cls_tokens=args.frame_cls_tokens, temporal_module_name=args.\n temporal_module_name, temporal_attention_only=args.\n temporal_attention_only, temporal_heads_scale=args.temporal_heads_scale,\n temporal_mlp_scale=args.temporal_mlp_scale, hpe_to_token=args.\n hpe_to_token, spatial_hub_size=args.spatial_hub_size, hub_attention=\n args.hub_attention, hub_aggregation=args.hub_aggregation,\n temporal_pooling=args.temporal_pooling, bottleneck=args.bottleneck,\n temporal_roll=args.temporal_roll, rel_pos=args.rel_pos, window_size=\n args.window_size, super_img_rows=args.super_img_rows, token_mask=not\n args.no_token_mask, online_learning=args.one_w > 0.0 or args.dml_w > \n 0.0, num_classes=args.num_classes, drop_rate=args.drop, drop_path_rate=\n args.drop_path, drop_block_rate=args.drop_block, use_checkpoint=args.\n use_checkpoint)\n', (18303, 19235), False, 'from timm.models import create_model\n'), ((20773, 20787), 'timm.utils.NativeScaler', 'NativeScaler', ([], {}), '()\n', (20785, 20787), False, 'from timm.utils import NativeScaler, get_state_dict, ModelEma\n'), ((20923, 20956), 'timm.scheduler.create_scheduler', 'create_scheduler', (['args', 'optimizer'], {}), '(args, optimizer)\n', (20939, 20956), False, 'from timm.scheduler import create_scheduler\n'), ((20978, 21013), 'timm.scheduler.create_scheduler', 'create_scheduler', (['args', 'p_optimizer'], {}), '(args, p_optimizer)\n', (20994, 21013), False, 'from timm.scheduler import create_scheduler\n'), ((21031, 21059), 'timm.loss.LabelSmoothingCrossEntropy', 'LabelSmoothingCrossEntropy', ([], {}), '()\n', (21057, 21059), False, 'from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy\n'), ((22194, 22215), 'pathlib.Path', 'Path', (['args.output_dir'], {}), '(args.output_dir)\n', (22198, 22215), False, 'from pathlib import Path\n'), ((24601, 24645), 'os.path.join', 'os.path.join', (['args.data_dir', 'train_list_name'], {}), '(args.data_dir, train_list_name)\n', (24613, 24645), False, 'import os\n'), ((24669, 24835), 'video_dataset_aug.get_augmentor', 'get_augmentor', (['(True)', 'args.input_size', 'mean', 'std'], {'threed_data': 'args.threed_data', 'version': 'args.augmentor_ver', 'scale_range': 'args.scale_range', 'dataset': 'args.dataset'}), '(True, args.input_size, mean, std, threed_data=args.\n threed_data, version=args.augmentor_ver, scale_range=args.scale_range,\n dataset=args.dataset)\n', (24682, 24835), False, 'from video_dataset_aug import get_augmentor, build_dataflow\n'), ((25380, 25402), 'utils.get_world_size', 'utils.get_world_size', ([], {}), '()\n', (25400, 25402), False, 'import utils\n'), ((25427, 25562), 'video_dataset_aug.build_dataflow', 'build_dataflow', (['dataset_train'], {'is_train': '(True)', 'batch_size': 'args.batch_size', 'workers': 'args.num_workers', 'is_distributed': 'args.distributed'}), '(dataset_train, is_train=True, batch_size=args.batch_size,\n workers=args.num_workers, is_distributed=args.distributed)\n', (25441, 25562), False, 'from video_dataset_aug import get_augmentor, build_dataflow\n'), ((25614, 25656), 'os.path.join', 'os.path.join', (['args.data_dir', 'val_list_name'], {}), '(args.data_dir, val_list_name)\n', (25626, 25656), False, 'import os\n'), ((25677, 25922), 'video_dataset_aug.get_augmentor', 'get_augmentor', (['(False)', 'args.input_size', 'mean', 'std', 'args.disable_scaleup'], {'threed_data': 'args.threed_data', 'version': 'args.augmentor_ver', 'scale_range': 'args.scale_range', 'num_clips': 'args.num_clips', 'num_crops': 'args.num_crops', 'dataset': 'args.dataset'}), '(False, args.input_size, mean, std, args.disable_scaleup,\n threed_data=args.threed_data, version=args.augmentor_ver, scale_range=\n args.scale_range, num_clips=args.num_clips, num_crops=args.num_crops,\n dataset=args.dataset)\n', (25690, 25922), False, 'from video_dataset_aug import get_augmentor, build_dataflow\n'), ((26486, 26620), 'video_dataset_aug.build_dataflow', 'build_dataflow', (['dataset_val'], {'is_train': '(False)', 'batch_size': 'args.batch_size', 'workers': 'args.num_workers', 'is_distributed': 'args.distributed'}), '(dataset_val, is_train=False, batch_size=args.batch_size,\n workers=args.num_workers, is_distributed=args.distributed)\n', (26500, 26620), False, 'from video_dataset_aug import get_augmentor, build_dataflow\n'), ((27039, 27050), 'time.time', 'time.time', ([], {}), '()\n', (27048, 27050), False, 'import time\n'), ((17277, 17293), 'utils.get_rank', 'utils.get_rank', ([], {}), '()\n', (17291, 17293), False, 'import utils\n'), ((17966, 18211), 'timm.data.Mixup', 'Mixup', ([], {'mixup_alpha': 'args.mixup', 'cutmix_alpha': 'args.cutmix', 'cutmix_minmax': 'args.cutmix_minmax', 'prob': 'args.mixup_prob', 'switch_prob': 'args.mixup_switch_prob', 'mode': 'args.mixup_mode', 'label_smoothing': 'args.smoothing', 'num_classes': 'args.num_classes'}), '(mixup_alpha=args.mixup, cutmix_alpha=args.cutmix, cutmix_minmax=args.\n cutmix_minmax, prob=args.mixup_prob, switch_prob=args.mixup_switch_prob,\n mode=args.mixup_mode, label_smoothing=args.smoothing, num_classes=args.\n num_classes)\n', (17971, 18211), False, 'from timm.data import Mixup\n'), ((19626, 19735), 'timm.utils.ModelEma', 'ModelEma', (['model'], {'decay': 'args.model_ema_decay', 'device': "('cpu' if args.model_ema_force_cpu else '')", 'resume': '""""""'}), "(model, decay=args.model_ema_decay, device='cpu' if args.\n model_ema_force_cpu else '', resume='')\n", (19634, 19735), False, 'from timm.utils import NativeScaler, get_state_dict, ModelEma\n'), ((19970, 20041), 'torch.nn.parallel.DistributedDataParallel', 'torch.nn.parallel.DistributedDataParallel', (['model'], {'device_ids': '[args.gpu]'}), '(model, device_ids=[args.gpu])\n', (20011, 20041), False, 'import torch\n'), ((21163, 21187), 'timm.loss.SoftTargetCrossEntropy', 'SoftTargetCrossEntropy', ([], {}), '()\n', (21185, 21187), False, 'from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy\n'), ((21390, 21441), 'losses.DeepMutualLoss', 'DeepMutualLoss', (['criterion', 'args.dml_w', 'args.kd_temp'], {}), '(criterion, args.dml_w, args.kd_temp)\n', (21404, 21441), False, 'from losses import DeepMutualLoss, ONELoss, MulMixturelLoss, SelfDistillationLoss\n'), ((21760, 21803), 'simclr.NTXent', 'simclr.NTXent', ([], {'temperature': 'args.temperature'}), '(temperature=args.temperature)\n', (21773, 21803), False, 'import simclr\n'), ((21863, 21890), 'torch.nn.CosineSimilarity', 'torch.nn.CosineSimilarity', ([], {}), '()\n', (21888, 21890), False, 'import torch\n'), ((21951, 21971), 'simclr.SimSiamLoss', 'simclr.SimSiamLoss', ([], {}), '()\n', (21969, 21971), False, 'import simclr\n'), ((22026, 22053), 'torch.nn.CrossEntropyLoss', 'torch.nn.CrossEntropyLoss', ([], {}), '()\n', (22051, 22053), False, 'import torch\n'), ((22105, 22122), 'simclr.BYOLLoss', 'simclr.BYOLLoss', ([], {}), '()\n', (22120, 22122), False, 'import simclr\n'), ((22345, 22400), 'torch.load', 'torch.load', (['args.initial_checkpoint'], {'map_location': '"""cpu"""'}), "(args.initial_checkpoint, map_location='cpu')\n", (22355, 22400), False, 'import torch\n'), ((22409, 22458), 'utils.load_checkpoint', 'utils.load_checkpoint', (['model', "checkpoint['model']"], {}), "(model, checkpoint['model'])\n", (22430, 22458), False, 'import utils\n'), ((22940, 22989), 'utils.load_checkpoint', 'utils.load_checkpoint', (['model', "checkpoint['model']"], {}), "(model, checkpoint['model'])\n", (22961, 22989), False, 'import utils\n'), ((26695, 26835), 'engine.evaluate', 'evaluate', (['data_loader_val', 'model', 'device', 'num_tasks'], {'distributed': '(True)', 'amp': 'args.amp', 'num_crops': 'args.num_crops', 'num_clips': 'args.num_clips'}), '(data_loader_val, model, device, num_tasks, distributed=True, amp=\n args.amp, num_crops=args.num_crops, num_clips=args.num_clips)\n', (26703, 26835), False, 'from engine import train_one_epoch, evaluate\n'), ((21233, 21285), 'timm.loss.LabelSmoothingCrossEntropy', 'LabelSmoothingCrossEntropy', ([], {'smoothing': 'args.smoothing'}), '(smoothing=args.smoothing)\n', (21259, 21285), False, 'from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy\n'), ((21316, 21343), 'torch.nn.CrossEntropyLoss', 'torch.nn.CrossEntropyLoss', ([], {}), '()\n', (21341, 21343), False, 'import torch\n'), ((21488, 21532), 'losses.ONELoss', 'ONELoss', (['criterion', 'args.one_w', 'args.kd_temp'], {}), '(criterion, args.one_w, args.kd_temp)\n', (21495, 21532), False, 'from losses import DeepMutualLoss, ONELoss, MulMixturelLoss, SelfDistillationLoss\n'), ((22747, 22835), 'torch.hub.load_state_dict_from_url', 'torch.hub.load_state_dict_from_url', (['args.resume'], {'map_location': '"""cpu"""', 'check_hash': '(True)'}), "(args.resume, map_location='cpu',\n check_hash=True)\n", (22781, 22835), False, 'import torch\n'), ((22888, 22931), 'torch.load', 'torch.load', (['args.resume'], {'map_location': '"""cpu"""'}), "(args.resume, map_location='cpu')\n", (22898, 22931), False, 'import torch\n'), ((27362, 27397), 'utils.unfreeze_model_weights', 'utils.unfreeze_model_weights', (['model'], {}), '(model)\n', (27390, 27397), False, 'import utils\n'), ((27410, 27440), 'utils.freeze_policy_net', 'utils.freeze_policy_net', (['model'], {}), '(model)\n', (27433, 27440), False, 'import utils\n'), ((30519, 30585), 'torch.optim.Adam', 'torch.optim.Adam', (['model', 'args.p_lr'], {'weight_decay': 'args.weight_decay'}), '(model, args.p_lr, weight_decay=args.weight_decay)\n', (30535, 30585), False, 'import torch\n'), ((30653, 30717), 'torch.optim.Adam', 'torch.optim.Adam', (['model', 'args.lr'], {'weight_decay': 'args.weight_decay'}), '(model, args.lr, weight_decay=args.weight_decay)\n', (30669, 30717), False, 'import torch\n'), ((35566, 35632), 'torch.optim.Adam', 'torch.optim.Adam', (['model', 'args.p_lr'], {'weight_decay': 'args.weight_decay'}), '(model, args.p_lr, weight_decay=args.weight_decay)\n', (35582, 35632), False, 'import torch\n'), ((35701, 35765), 'torch.optim.Adam', 'torch.optim.Adam', (['model', 'args.lr'], {'weight_decay': 'args.weight_decay'}), '(model, args.lr, weight_decay=args.weight_decay)\n', (35717, 35765), False, 'import torch\n'), ((1705, 1726), 'video_dataset_config.DATASET_CONFIG.keys', 'DATASET_CONFIG.keys', ([], {}), '()\n', (1724, 1726), False, 'from video_dataset_config import get_dataset_config, DATASET_CONFIG\n'), ((21582, 21623), 'losses.MulMixturelLoss', 'MulMixturelLoss', (['criterion', 'args.mulmix_b'], {}), '(criterion, args.mulmix_b)\n', (21597, 21623), False, 'from losses import DeepMutualLoss, ONELoss, MulMixturelLoss, SelfDistillationLoss\n'), ((22595, 22622), 'os.path.exists', 'os.path.exists', (['args.resume'], {}), '(args.resume)\n', (22609, 22622), False, 'import os\n'), ((23895, 23961), 'utils._load_checkpoint_for_ema', 'utils._load_checkpoint_for_ema', (['model_ema', "checkpoint['model_ema']"], {}), "(model_ema, checkpoint['model_ema'])\n", (23925, 23961), False, 'import utils\n'), ((27625, 28230), 'engine.train_one_epoch', 'train_one_epoch', (['model', 'criterion', 'data_loader_train', 'optimizer', 'device', 'epoch', 'loss_scaler', 'args.clip_grad', 'model_ema', 'mixup_fn', 'num_tasks', '(True)'], {'amp': 'args.amp', 'simclr_criterion': 'simclr_criterion', 'simclr_w': 'args.simclr_w', 'branch_div_criterion': 'branch_div_criterion', 'branch_div_w': 'args.branch_div_w', 'simsiam_criterion': 'simsiam_criterion', 'simsiam_w': 'args.simsiam_w', 'moco_criterion': 'moco_criterion', 'moco_w': 'args.moco_w', 'byol_criterion': 'byol_criterion', 'byol_w': 'args.byol_w', 'contrastive_nomixup': 'args.contrastive_nomixup', 'hard_contrastive': 'args.hard_contrastive', 'finetune': 'args.finetune'}), '(model, criterion, data_loader_train, optimizer, device,\n epoch, loss_scaler, args.clip_grad, model_ema, mixup_fn, num_tasks, \n True, amp=args.amp, simclr_criterion=simclr_criterion, simclr_w=args.\n simclr_w, branch_div_criterion=branch_div_criterion, branch_div_w=args.\n branch_div_w, simsiam_criterion=simsiam_criterion, simsiam_w=args.\n simsiam_w, moco_criterion=moco_criterion, moco_w=args.moco_w,\n byol_criterion=byol_criterion, byol_w=args.byol_w, contrastive_nomixup=\n args.contrastive_nomixup, hard_contrastive=args.hard_contrastive,\n finetune=args.finetune)\n', (27640, 28230), False, 'from engine import train_one_epoch, evaluate\n'), ((28491, 28579), 'engine.evaluate', 'evaluate', (['data_loader_val', 'model', 'device', 'num_tasks'], {'distributed': '(True)', 'amp': 'args.amp'}), '(data_loader_val, model, device, num_tasks, distributed=True, amp=\n args.amp)\n', (28499, 28579), False, 'from engine import train_one_epoch, evaluate\n'), ((31416, 31451), 'utils.unfreeze_model_weights', 'utils.unfreeze_model_weights', (['model'], {}), '(model)\n', (31444, 31451), False, 'import utils\n'), ((31468, 31498), 'utils.freeze_policy_net', 'utils.freeze_policy_net', (['model'], {}), '(model)\n', (31491, 31498), False, 'import utils\n'), ((31546, 32151), 'engine.train_one_epoch', 'train_one_epoch', (['model', 'criterion', 'data_loader_train', 'optimizer', 'device', 'epoch', 'loss_scaler', 'args.clip_grad', 'model_ema', 'mixup_fn', 'num_tasks', '(True)'], {'amp': 'args.amp', 'simclr_criterion': 'simclr_criterion', 'simclr_w': 'args.simclr_w', 'branch_div_criterion': 'branch_div_criterion', 'branch_div_w': 'args.branch_div_w', 'simsiam_criterion': 'simsiam_criterion', 'simsiam_w': 'args.simsiam_w', 'moco_criterion': 'moco_criterion', 'moco_w': 'args.moco_w', 'byol_criterion': 'byol_criterion', 'byol_w': 'args.byol_w', 'contrastive_nomixup': 'args.contrastive_nomixup', 'hard_contrastive': 'args.hard_contrastive', 'finetune': 'args.finetune'}), '(model, criterion, data_loader_train, optimizer, device,\n epoch, loss_scaler, args.clip_grad, model_ema, mixup_fn, num_tasks, \n True, amp=args.amp, simclr_criterion=simclr_criterion, simclr_w=args.\n simclr_w, branch_div_criterion=branch_div_criterion, branch_div_w=args.\n branch_div_w, simsiam_criterion=simsiam_criterion, simsiam_w=args.\n simsiam_w, moco_criterion=moco_criterion, moco_w=args.moco_w,\n byol_criterion=byol_criterion, byol_w=args.byol_w, contrastive_nomixup=\n args.contrastive_nomixup, hard_contrastive=args.hard_contrastive,\n finetune=args.finetune)\n', (31561, 32151), False, 'from engine import train_one_epoch, evaluate\n'), ((32515, 32550), 'utils.unfreeze_model_weights', 'utils.unfreeze_model_weights', (['model'], {}), '(model)\n', (32543, 32550), False, 'import utils\n'), ((32567, 32595), 'utils.freeze_main_net', 'utils.freeze_main_net', (['model'], {}), '(model)\n', (32588, 32595), False, 'import utils\n'), ((32626, 33231), 'engine.train_one_epoch', 'train_one_epoch', (['model', 'criterion', 'data_loader_train', 'optimizer', 'device', 'epoch', 'loss_scaler', 'args.clip_grad', 'model_ema', 'mixup_fn', 'num_tasks', '(True)'], {'amp': 'args.amp', 'simclr_criterion': 'simclr_criterion', 'simclr_w': 'args.simclr_w', 'branch_div_criterion': 'branch_div_criterion', 'branch_div_w': 'args.branch_div_w', 'simsiam_criterion': 'simsiam_criterion', 'simsiam_w': 'args.simsiam_w', 'moco_criterion': 'moco_criterion', 'moco_w': 'args.moco_w', 'byol_criterion': 'byol_criterion', 'byol_w': 'args.byol_w', 'contrastive_nomixup': 'args.contrastive_nomixup', 'hard_contrastive': 'args.hard_contrastive', 'finetune': 'args.finetune'}), '(model, criterion, data_loader_train, optimizer, device,\n epoch, loss_scaler, args.clip_grad, model_ema, mixup_fn, num_tasks, \n True, amp=args.amp, simclr_criterion=simclr_criterion, simclr_w=args.\n simclr_w, branch_div_criterion=branch_div_criterion, branch_div_w=args.\n branch_div_w, simsiam_criterion=simsiam_criterion, simsiam_w=args.\n simsiam_w, moco_criterion=moco_criterion, moco_w=args.moco_w,\n byol_criterion=byol_criterion, byol_w=args.byol_w, contrastive_nomixup=\n args.contrastive_nomixup, hard_contrastive=args.hard_contrastive,\n finetune=args.finetune)\n', (32641, 33231), False, 'from engine import train_one_epoch, evaluate\n'), ((33434, 33522), 'engine.evaluate', 'evaluate', (['data_loader_val', 'model', 'device', 'num_tasks'], {'distributed': '(True)', 'amp': 'args.amp'}), '(data_loader_val, model, device, num_tasks, distributed=True, amp=\n args.amp)\n', (33442, 33522), False, 'from engine import train_one_epoch, evaluate\n'), ((35163, 35186), 'utils.is_main_process', 'utils.is_main_process', ([], {}), '()\n', (35184, 35186), False, 'import utils\n'), ((36271, 36306), 'utils.unfreeze_model_weights', 'utils.unfreeze_model_weights', (['model'], {}), '(model)\n', (36299, 36306), False, 'import utils\n'), ((36323, 36353), 'utils.freeze_policy_net', 'utils.freeze_policy_net', (['model'], {}), '(model)\n', (36346, 36353), False, 'import utils\n'), ((39178, 39201), 'utils.is_main_process', 'utils.is_main_process', ([], {}), '()\n', (39199, 39201), False, 'import utils\n'), ((42324, 42345), 'pathlib.Path', 'Path', (['args.output_dir'], {}), '(args.output_dir)\n', (42328, 42345), False, 'from pathlib import Path\n'), ((21674, 21735), 'losses.SelfDistillationLoss', 'SelfDistillationLoss', (['criterion', 'args.selfdis_w', 'args.kd_temp'], {}), '(criterion, args.selfdis_w, args.kd_temp)\n', (21694, 21735), False, 'from losses import DeepMutualLoss, ONELoss, MulMixturelLoss, SelfDistillationLoss\n'), ((30117, 30140), 'utils.is_main_process', 'utils.is_main_process', ([], {}), '()\n', (30138, 30140), False, 'import utils\n'), ((36522, 37127), 'engine.train_one_epoch', 'train_one_epoch', (['model', 'criterion', 'data_loader_train', 'optimizer', 'device', 'epoch', 'loss_scaler', 'args.clip_grad', 'model_ema', 'mixup_fn', 'num_tasks', '(True)'], {'amp': 'args.amp', 'simclr_criterion': 'simclr_criterion', 'simclr_w': 'args.simclr_w', 'branch_div_criterion': 'branch_div_criterion', 'branch_div_w': 'args.branch_div_w', 'simsiam_criterion': 'simsiam_criterion', 'simsiam_w': 'args.simsiam_w', 'moco_criterion': 'moco_criterion', 'moco_w': 'args.moco_w', 'byol_criterion': 'byol_criterion', 'byol_w': 'args.byol_w', 'contrastive_nomixup': 'args.contrastive_nomixup', 'hard_contrastive': 'args.hard_contrastive', 'finetune': 'args.finetune'}), '(model, criterion, data_loader_train, optimizer, device,\n epoch, loss_scaler, args.clip_grad, model_ema, mixup_fn, num_tasks, \n True, amp=args.amp, simclr_criterion=simclr_criterion, simclr_w=args.\n simclr_w, branch_div_criterion=branch_div_criterion, branch_div_w=args.\n branch_div_w, simsiam_criterion=simsiam_criterion, simsiam_w=args.\n simsiam_w, moco_criterion=moco_criterion, moco_w=args.moco_w,\n byol_criterion=byol_criterion, byol_w=args.byol_w, contrastive_nomixup=\n args.contrastive_nomixup, hard_contrastive=args.hard_contrastive,\n finetune=args.finetune)\n', (36537, 37127), False, 'from engine import train_one_epoch, evaluate\n'), ((37386, 37474), 'engine.evaluate', 'evaluate', (['data_loader_val', 'model', 'device', 'num_tasks'], {'distributed': '(True)', 'amp': 'args.amp'}), '(data_loader_val, model, device, num_tasks, distributed=True, amp=\n args.amp)\n', (37394, 37474), False, 'from engine import train_one_epoch, evaluate\n'), ((35278, 35299), 'json.dumps', 'json.dumps', (['log_stats'], {}), '(log_stats)\n', (35288, 35299), False, 'import json\n'), ((39293, 39314), 'json.dumps', 'json.dumps', (['log_stats'], {}), '(log_stats)\n', (39303, 39314), False, 'import json\n'), ((30240, 30261), 'json.dumps', 'json.dumps', (['log_stats'], {}), '(log_stats)\n', (30250, 30261), False, 'import json\n')]
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Project: Azimuthal integration
# https://github.com/silx-kit/pyFAI
#
# Copyright (C) 2015-2018 European Synchrotron Radiation Facility, Grenoble, France
#
# Principal author: <NAME> (<EMAIL>)
#
# 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 division, with_statement, print_function
"""Benchmark for HDF5 writing"""
__author__ = "<NAME>"
__date__ = "24/09/2014"
import os
import time
import tempfile
import numpy
from pyFAI.third_party.argparse import ArgumentParser
from pyFAI import io
import logging
logger = logging.getLogger("Bench_hdf5")
logger.setLevel(logging.INFO)
def parse():
"""
Parse command line arguments
"""
parser = ArgumentParser(description=__doc__)
parser.add_argument('-d', '--dir', dest='directory', default=tempfile.gettempdir(),
help='Destination directory (/tmp)')
parser.add_argument('-n', '--number', dest='n', default=1024, type=int,
help='Number of frames to write')
parser.add_argument('-w', '--width', dest='width', default=1024, type=int,
help='width of a frame (1024)')
parser.add_argument('-H', '--height', dest='height', default=1024, type=int,
help='height of the image (1024)')
parser.add_argument('-t', '--type', dest='dtype', default="float32", type=str,
help='data type of item (float32)')
parser.add_argument('-b', '--bsize', dest='bsize', default=10, type=int,
help='size of the random buffer for frames (10)')
opt = parser.parse_args()
return opt
def bench_hdf5(n=1024, shape=(1024, 1024), dtype="float32", dirname=None, bsize=10):
"""
Actually performs the HDF5 writing benchmark
:param n: number of frames to be written
:param shape: 2-tuple of integer describing the shape of the image
:param bsize: number of frames in buffer
"""
tmp_dir = tempfile.mkdtemp(dir=dirname)
h5file = os.path.join(tmp_dir, "junk.h5")
logger.info("Writing large dataset %ix(%i,%i) of %s to %s.", n, shape[0], shape[1], dtype, h5file)
dtype = numpy.dtype(dtype)
if dtype.kind == "f":
data = numpy.random.random((bsize, shape[0], shape[1])).astype(dtype)
elif dtype.name.find("int") >= 0:
size = bsize * shape[0] * shape[1]
maxi = 2 ** (dtype.itemsize * 8 - 1) - 1
data = numpy.random.random_integers(0, maxi, size=size).astype(dtype)
data.shape = (bsize, shape[0], shape[1])
else:
raise RuntimeError("unhandled data type %s" % dtype)
size = n * shape[0] * shape[1]
nbytes = size * dtype.itemsize
nmbytes = nbytes / 1e6
t0 = time.time()
writer = io.HDF5Writer(filename=h5file, hpath="data")
writer.init({"nbpt_azim": shape[0], "nbpt_rad": shape[1], "dtype": dtype.name})
for i in range(n):
writer.write(data[i % bsize], i)
writer.close()
t = time.time() - t0
bps = nbytes / t
logger.info("Writing of %.3fMB in HDF5 took %.3fs (%.3f MByte/s)", nmbytes, t, nmbytes / t)
statinfo = os.stat(h5file)
assert statinfo.st_size > nbytes
# Clean up
os.unlink(h5file)
os.removedirs(tmp_dir)
return bps
if __name__ == "__main__":
opts = parse()
print(bench_hdf5(dirname=opts.directory,
n=opts.n,
shape=(opts.height, opts.width),
dtype=opts.dtype,
bsize=opts.bsize))
|
[
"os.unlink",
"os.stat",
"os.removedirs",
"numpy.dtype",
"tempfile.gettempdir",
"time.time",
"pyFAI.io.HDF5Writer",
"tempfile.mkdtemp",
"pyFAI.third_party.argparse.ArgumentParser",
"numpy.random.random",
"os.path.join",
"numpy.random.random_integers",
"logging.getLogger"
] |
[((1623, 1654), 'logging.getLogger', 'logging.getLogger', (['"""Bench_hdf5"""'], {}), "('Bench_hdf5')\n", (1640, 1654), False, 'import logging\n'), ((1761, 1796), 'pyFAI.third_party.argparse.ArgumentParser', 'ArgumentParser', ([], {'description': '__doc__'}), '(description=__doc__)\n', (1775, 1796), False, 'from pyFAI.third_party.argparse import ArgumentParser\n'), ((3021, 3050), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {'dir': 'dirname'}), '(dir=dirname)\n', (3037, 3050), False, 'import tempfile\n'), ((3064, 3096), 'os.path.join', 'os.path.join', (['tmp_dir', '"""junk.h5"""'], {}), "(tmp_dir, 'junk.h5')\n", (3076, 3096), False, 'import os\n'), ((3213, 3231), 'numpy.dtype', 'numpy.dtype', (['dtype'], {}), '(dtype)\n', (3224, 3231), False, 'import numpy\n'), ((3770, 3781), 'time.time', 'time.time', ([], {}), '()\n', (3779, 3781), False, 'import time\n'), ((3795, 3839), 'pyFAI.io.HDF5Writer', 'io.HDF5Writer', ([], {'filename': 'h5file', 'hpath': '"""data"""'}), "(filename=h5file, hpath='data')\n", (3808, 3839), False, 'from pyFAI import io\n'), ((4164, 4179), 'os.stat', 'os.stat', (['h5file'], {}), '(h5file)\n', (4171, 4179), False, 'import os\n'), ((4237, 4254), 'os.unlink', 'os.unlink', (['h5file'], {}), '(h5file)\n', (4246, 4254), False, 'import os\n'), ((4259, 4281), 'os.removedirs', 'os.removedirs', (['tmp_dir'], {}), '(tmp_dir)\n', (4272, 4281), False, 'import os\n'), ((4015, 4026), 'time.time', 'time.time', ([], {}), '()\n', (4024, 4026), False, 'import time\n'), ((1862, 1883), 'tempfile.gettempdir', 'tempfile.gettempdir', ([], {}), '()\n', (1881, 1883), False, 'import tempfile\n'), ((3273, 3321), 'numpy.random.random', 'numpy.random.random', (['(bsize, shape[0], shape[1])'], {}), '((bsize, shape[0], shape[1]))\n', (3292, 3321), False, 'import numpy\n'), ((3481, 3529), 'numpy.random.random_integers', 'numpy.random.random_integers', (['(0)', 'maxi'], {'size': 'size'}), '(0, maxi, size=size)\n', (3509, 3529), False, 'import numpy\n')]
|
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for gps_building_blocks.ml.statistical_inference.models."""
import numpy as np
import pandas as pd
from gps_building_blocks.ml.statistical_inference import data_preparation
from gps_building_blocks.ml.statistical_inference import models
from absl.testing import absltest
def _prepare_data_and_target(ready_for_modelling=True):
# Prepare data
data = np.array(
[[0.496714150, -0.13826430, 0.647688540, 1.523029860, -0.23415337],
[-0.23413696, 1.579212820, 0.767434730, -0.46947439, 0.542560040],
[-0.46341769, -0.46572975, 0.241962270, -1.91328024, -1.72491783],
[-0.56228753, -1.01283112, 0.314247330, -0.90802408, -1.41230370],
[1.465648770, -0.22577630, 0.067528200, -1.42474819, -0.54438272],
[0.110922590, -1.15099358, 0.375698020, -0.60063869, -0.29169375],
[-0.60170661, 1.852278180, -0.01349722, -1.05771093, 0.822544910],
[-1.22084365, 0.208863600, -1.95967012, -1.32818605, 0.196861240],
[0.738466580, 0.171368280, -0.11564828, -0.30110370, -1.47852199],
[-0.71984421, -0.46063877, 1.057122230, 0.343618290, -1.76304016],
[0.324083970, -0.38508228, -0.67692200, 0.611676290, 1.030999520],
[0.931280120, -0.83921752, -0.30921238, 0.331263430, 0.975545130],
[-0.47917424, -0.18565898, -1.10633497, -1.19620662, 0.812525820],
[1.356240030, -0.07201012, 1.003532900, 0.361636030, -0.64511975],
[0.361395610, 1.538036570, -0.03582604, 1.564643660, -2.61974510],
[0.821902500, 0.087047070, -0.29900735, 0.091760780, -1.98756891],
[-0.21967189, 0.357112570, 1.477894040, -0.51827022, -0.80849360],
[-0.50175704, 0.915402120, 0.328751110, -0.52976020, 0.513267430],
[0.097077550, 0.968644990, -0.70205309, -0.32766215, -0.39210815],
[-1.46351495, 0.296120280, 0.261055270, 0.005113460, -0.23458713]])
# Decreasing coefficients with alternated signs
idx = np.arange(data.shape[1])
coefficients = (-1) ** idx * np.exp(-idx / 10)
coefficients[10:] = 0 # sparsify
target = np.dot(data, coefficients)
# Add noise
noise = np.array(
[0.496714150, -0.13826430, 0.64768854, 1.523029860, -0.23415337,
-0.23413696, 1.579212820, 0.76743473, -0.46947439, 0.542560040,
-0.46341769, -0.46572975, 0.24196227, -1.91328024, -1.72491783,
-0.56228753, -1.01283112, 0.31424733, -0.90802408, -1.41230370])
target += 0.01 * noise
data = pd.DataFrame(data)
data['target'] = target
inference_data = data_preparation.InferenceData(data, 'target')
if ready_for_modelling:
inference_data._has_control_factors = True
inference_data._checked_low_variance = True
inference_data._checked_collinearity = True
return inference_data
class LinearModelTest(absltest.TestCase):
def test_fit(self):
data = _prepare_data_and_target()
model = models.InferenceElasticNet(random_state=18)
expected_result = pd.DataFrame(
data=[[-0.203832],
[-0.134636],
[0.0108217],
[0.0100611],
[0.0000000],
[0.0000000],],
columns=['effect'],
index=[1, 'Intercept', 0, 4, 3, 2])
model.fit(data)
result = model.get_results()
pd.testing.assert_frame_equal(
result[['effect']],
expected_result,
check_less_precise=2,
check_index_type=False)
def test_fit_bootstrap(self):
data = _prepare_data_and_target()
model = models.InferenceElasticNet(random_state=18)
expected_result = pd.DataFrame(
data=[[-0.173, 0.2715, 0.4477, False],
[-0.135, 0.0784, 0.1287, True],
[0.0445, 0.0893, 0.1473, False],
[0.0357, 0.0548, 0.0883, False],
[0.0123, 0.0384, 0.0643, False],
[-0.010, 0.0332, 0.0541, False]],
columns=['effect', 'bootstrap_std',
'confidence_interval', 'significant_bootstrap'],
index=['Intercept', 1, 0, 4, 2, 3])
model.fit(data)
model.fit_bootstrap(bootstraps=10, n_jobs=1, verbose=False)
result = model.get_results()
pd.testing.assert_frame_equal(
result[expected_result.columns],
expected_result,
check_less_precise=1,
check_index_type=False)
def test_predict(self):
data = _prepare_data_and_target()
model = models.InferenceElasticNet(random_state=18)
model.fit(data)
predictions = model.predict(data)
self.assertIsInstance(predictions, pd.Series)
self.assertEqual(len(predictions), len(data.data))
pd.testing.assert_index_equal(predictions.index, data.data.index)
def test_metrics_calculates_r2_and_mape(self):
data = _prepare_data_and_target()
model = models.InferenceElasticNet(random_state=18)
model.fit(data)
fit_metrics = ('rmse', 'r2')
metrics = model.calculate_fit_metrics(data, fit_metrics=fit_metrics)
self.assertTrue(0 < metrics['r2'] < 1)
self.assertLess(0, metrics['rmse'])
self.assertCountEqual(metrics.keys(), fit_metrics)
def test_permutation_test(self):
"""Ensures the permutation test computes the expected results."""
data = _prepare_data_and_target()
model = models.InferenceElasticNet(random_state=18)
model.fit(data)
expected_result = pd.DataFrame(
data=[[-0.20383230, np.nan, np.nan, np.nan, True],
[-0.13463647, np.nan, np.nan, np.nan, True],
[0.010821799, np.nan, np.nan, np.nan, True],
[0.010061159, np.nan, np.nan, np.nan, True],
[0.000000000, np.nan, np.nan, np.nan, False],
[0.000000000, np.nan, np.nan, np.nan, False]],
columns=[
'effect', 'bootstrap_std', 'confidence_interval',
'significant_bootstrap', 'significant_permutation'],
index=[1, 'Intercept', 0, 4, 3, 2])
model.permutation_test(n_permutations=5, verbose=False, n_jobs=1)
result = model.get_results()
pd.testing.assert_frame_equal(
result,
expected_result,
check_dtype=False,
check_index_type=False)
def test_permutation_test_not_fitted(self):
"""Ensures permutation test can't be run before fitting the model."""
model = models.InferenceElasticNet(random_state=18)
data = _prepare_data_and_target()
with self.assertRaises(RuntimeError):
model.permutation_test(data)
def test_fit_with_data_not_ready_throw_error(self):
data = _prepare_data_and_target(ready_for_modelling=False)
model = models.InferenceElasticNet(random_state=18)
with self.assertRaises(data_preparation.InferenceDataError):
model.fit(data)
def test_fit_with_data_not_ready_emit_warning(self):
data = _prepare_data_and_target(ready_for_modelling=False)
model = models.InferenceLinearRegression()
with self.assertWarns(data_preparation.InferenceDataWarning):
model.fit(data, raise_on_data_error=False)
if __name__ == '__main__':
absltest.main()
|
[
"pandas.DataFrame",
"absl.testing.absltest.main",
"pandas.testing.assert_frame_equal",
"gps_building_blocks.ml.statistical_inference.models.InferenceElasticNet",
"gps_building_blocks.ml.statistical_inference.data_preparation.InferenceData",
"gps_building_blocks.ml.statistical_inference.models.InferenceLinearRegression",
"numpy.array",
"numpy.arange",
"numpy.exp",
"numpy.dot",
"pandas.testing.assert_index_equal"
] |
[((942, 2328), 'numpy.array', 'np.array', (['[[0.49671415, -0.1382643, 0.64768854, 1.52302986, -0.23415337], [-\n 0.23413696, 1.57921282, 0.76743473, -0.46947439, 0.54256004], [-\n 0.46341769, -0.46572975, 0.24196227, -1.91328024, -1.72491783], [-\n 0.56228753, -1.01283112, 0.31424733, -0.90802408, -1.4123037], [\n 1.46564877, -0.2257763, 0.0675282, -1.42474819, -0.54438272], [\n 0.11092259, -1.15099358, 0.37569802, -0.60063869, -0.29169375], [-\n 0.60170661, 1.85227818, -0.01349722, -1.05771093, 0.82254491], [-\n 1.22084365, 0.2088636, -1.95967012, -1.32818605, 0.19686124], [\n 0.73846658, 0.17136828, -0.11564828, -0.3011037, -1.47852199], [-\n 0.71984421, -0.46063877, 1.05712223, 0.34361829, -1.76304016], [\n 0.32408397, -0.38508228, -0.676922, 0.61167629, 1.03099952], [\n 0.93128012, -0.83921752, -0.30921238, 0.33126343, 0.97554513], [-\n 0.47917424, -0.18565898, -1.10633497, -1.19620662, 0.81252582], [\n 1.35624003, -0.07201012, 1.0035329, 0.36163603, -0.64511975], [\n 0.36139561, 1.53803657, -0.03582604, 1.56464366, -2.6197451], [\n 0.8219025, 0.08704707, -0.29900735, 0.09176078, -1.98756891], [-\n 0.21967189, 0.35711257, 1.47789404, -0.51827022, -0.8084936], [-\n 0.50175704, 0.91540212, 0.32875111, -0.5297602, 0.51326743], [\n 0.09707755, 0.96864499, -0.70205309, -0.32766215, -0.39210815], [-\n 1.46351495, 0.29612028, 0.26105527, 0.00511346, -0.23458713]]'], {}), '([[0.49671415, -0.1382643, 0.64768854, 1.52302986, -0.23415337], [-\n 0.23413696, 1.57921282, 0.76743473, -0.46947439, 0.54256004], [-\n 0.46341769, -0.46572975, 0.24196227, -1.91328024, -1.72491783], [-\n 0.56228753, -1.01283112, 0.31424733, -0.90802408, -1.4123037], [\n 1.46564877, -0.2257763, 0.0675282, -1.42474819, -0.54438272], [\n 0.11092259, -1.15099358, 0.37569802, -0.60063869, -0.29169375], [-\n 0.60170661, 1.85227818, -0.01349722, -1.05771093, 0.82254491], [-\n 1.22084365, 0.2088636, -1.95967012, -1.32818605, 0.19686124], [\n 0.73846658, 0.17136828, -0.11564828, -0.3011037, -1.47852199], [-\n 0.71984421, -0.46063877, 1.05712223, 0.34361829, -1.76304016], [\n 0.32408397, -0.38508228, -0.676922, 0.61167629, 1.03099952], [\n 0.93128012, -0.83921752, -0.30921238, 0.33126343, 0.97554513], [-\n 0.47917424, -0.18565898, -1.10633497, -1.19620662, 0.81252582], [\n 1.35624003, -0.07201012, 1.0035329, 0.36163603, -0.64511975], [\n 0.36139561, 1.53803657, -0.03582604, 1.56464366, -2.6197451], [\n 0.8219025, 0.08704707, -0.29900735, 0.09176078, -1.98756891], [-\n 0.21967189, 0.35711257, 1.47789404, -0.51827022, -0.8084936], [-\n 0.50175704, 0.91540212, 0.32875111, -0.5297602, 0.51326743], [\n 0.09707755, 0.96864499, -0.70205309, -0.32766215, -0.39210815], [-\n 1.46351495, 0.29612028, 0.26105527, 0.00511346, -0.23458713]])\n', (950, 2328), True, 'import numpy as np\n'), ((2491, 2515), 'numpy.arange', 'np.arange', (['data.shape[1]'], {}), '(data.shape[1])\n', (2500, 2515), True, 'import numpy as np\n'), ((2612, 2638), 'numpy.dot', 'np.dot', (['data', 'coefficients'], {}), '(data, coefficients)\n', (2618, 2638), True, 'import numpy as np\n'), ((2663, 2938), 'numpy.array', 'np.array', (['[0.49671415, -0.1382643, 0.64768854, 1.52302986, -0.23415337, -0.23413696, \n 1.57921282, 0.76743473, -0.46947439, 0.54256004, -0.46341769, -\n 0.46572975, 0.24196227, -1.91328024, -1.72491783, -0.56228753, -\n 1.01283112, 0.31424733, -0.90802408, -1.4123037]'], {}), '([0.49671415, -0.1382643, 0.64768854, 1.52302986, -0.23415337, -\n 0.23413696, 1.57921282, 0.76743473, -0.46947439, 0.54256004, -\n 0.46341769, -0.46572975, 0.24196227, -1.91328024, -1.72491783, -\n 0.56228753, -1.01283112, 0.31424733, -0.90802408, -1.4123037])\n', (2671, 2938), True, 'import numpy as np\n'), ((2993, 3011), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {}), '(data)\n', (3005, 3011), True, 'import pandas as pd\n'), ((3057, 3103), 'gps_building_blocks.ml.statistical_inference.data_preparation.InferenceData', 'data_preparation.InferenceData', (['data', '"""target"""'], {}), "(data, 'target')\n", (3087, 3103), False, 'from gps_building_blocks.ml.statistical_inference import data_preparation\n'), ((7493, 7508), 'absl.testing.absltest.main', 'absltest.main', ([], {}), '()\n', (7506, 7508), False, 'from absl.testing import absltest\n'), ((2547, 2564), 'numpy.exp', 'np.exp', (['(-idx / 10)'], {}), '(-idx / 10)\n', (2553, 2564), True, 'import numpy as np\n'), ((3416, 3459), 'gps_building_blocks.ml.statistical_inference.models.InferenceElasticNet', 'models.InferenceElasticNet', ([], {'random_state': '(18)'}), '(random_state=18)\n', (3442, 3459), False, 'from gps_building_blocks.ml.statistical_inference import models\n'), ((3482, 3628), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': '[[-0.203832], [-0.134636], [0.0108217], [0.0100611], [0.0], [0.0]]', 'columns': "['effect']", 'index': "[1, 'Intercept', 0, 4, 3, 2]"}), "(data=[[-0.203832], [-0.134636], [0.0108217], [0.0100611], [0.0\n ], [0.0]], columns=['effect'], index=[1, 'Intercept', 0, 4, 3, 2])\n", (3494, 3628), True, 'import pandas as pd\n'), ((3791, 3907), 'pandas.testing.assert_frame_equal', 'pd.testing.assert_frame_equal', (["result[['effect']]", 'expected_result'], {'check_less_precise': '(2)', 'check_index_type': '(False)'}), "(result[['effect']], expected_result,\n check_less_precise=2, check_index_type=False)\n", (3820, 3907), True, 'import pandas as pd\n'), ((4020, 4063), 'gps_building_blocks.ml.statistical_inference.models.InferenceElasticNet', 'models.InferenceElasticNet', ([], {'random_state': '(18)'}), '(random_state=18)\n', (4046, 4063), False, 'from gps_building_blocks.ml.statistical_inference import models\n'), ((4086, 4438), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': '[[-0.173, 0.2715, 0.4477, False], [-0.135, 0.0784, 0.1287, True], [0.0445, \n 0.0893, 0.1473, False], [0.0357, 0.0548, 0.0883, False], [0.0123, \n 0.0384, 0.0643, False], [-0.01, 0.0332, 0.0541, False]]', 'columns': "['effect', 'bootstrap_std', 'confidence_interval', 'significant_bootstrap']", 'index': "['Intercept', 1, 0, 4, 2, 3]"}), "(data=[[-0.173, 0.2715, 0.4477, False], [-0.135, 0.0784, 0.1287,\n True], [0.0445, 0.0893, 0.1473, False], [0.0357, 0.0548, 0.0883, False],\n [0.0123, 0.0384, 0.0643, False], [-0.01, 0.0332, 0.0541, False]],\n columns=['effect', 'bootstrap_std', 'confidence_interval',\n 'significant_bootstrap'], index=['Intercept', 1, 0, 4, 2, 3])\n", (4098, 4438), True, 'import pandas as pd\n'), ((4659, 4788), 'pandas.testing.assert_frame_equal', 'pd.testing.assert_frame_equal', (['result[expected_result.columns]', 'expected_result'], {'check_less_precise': '(1)', 'check_index_type': '(False)'}), '(result[expected_result.columns],\n expected_result, check_less_precise=1, check_index_type=False)\n', (4688, 4788), True, 'import pandas as pd\n'), ((4895, 4938), 'gps_building_blocks.ml.statistical_inference.models.InferenceElasticNet', 'models.InferenceElasticNet', ([], {'random_state': '(18)'}), '(random_state=18)\n', (4921, 4938), False, 'from gps_building_blocks.ml.statistical_inference import models\n'), ((5108, 5173), 'pandas.testing.assert_index_equal', 'pd.testing.assert_index_equal', (['predictions.index', 'data.data.index'], {}), '(predictions.index, data.data.index)\n', (5137, 5173), True, 'import pandas as pd\n'), ((5274, 5317), 'gps_building_blocks.ml.statistical_inference.models.InferenceElasticNet', 'models.InferenceElasticNet', ([], {'random_state': '(18)'}), '(random_state=18)\n', (5300, 5317), False, 'from gps_building_blocks.ml.statistical_inference import models\n'), ((5740, 5783), 'gps_building_blocks.ml.statistical_inference.models.InferenceElasticNet', 'models.InferenceElasticNet', ([], {'random_state': '(18)'}), '(random_state=18)\n', (5766, 5783), False, 'from gps_building_blocks.ml.statistical_inference import models\n'), ((5826, 6275), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': '[[-0.2038323, np.nan, np.nan, np.nan, True], [-0.13463647, np.nan, np.nan,\n np.nan, True], [0.010821799, np.nan, np.nan, np.nan, True], [\n 0.010061159, np.nan, np.nan, np.nan, True], [0.0, np.nan, np.nan, np.\n nan, False], [0.0, np.nan, np.nan, np.nan, False]]', 'columns': "['effect', 'bootstrap_std', 'confidence_interval', 'significant_bootstrap',\n 'significant_permutation']", 'index': "[1, 'Intercept', 0, 4, 3, 2]"}), "(data=[[-0.2038323, np.nan, np.nan, np.nan, True], [-0.13463647,\n np.nan, np.nan, np.nan, True], [0.010821799, np.nan, np.nan, np.nan, \n True], [0.010061159, np.nan, np.nan, np.nan, True], [0.0, np.nan, np.\n nan, np.nan, False], [0.0, np.nan, np.nan, np.nan, False]], columns=[\n 'effect', 'bootstrap_std', 'confidence_interval',\n 'significant_bootstrap', 'significant_permutation'], index=[1,\n 'Intercept', 0, 4, 3, 2])\n", (5838, 6275), True, 'import pandas as pd\n'), ((6495, 6596), 'pandas.testing.assert_frame_equal', 'pd.testing.assert_frame_equal', (['result', 'expected_result'], {'check_dtype': '(False)', 'check_index_type': '(False)'}), '(result, expected_result, check_dtype=False,\n check_index_type=False)\n', (6524, 6596), True, 'import pandas as pd\n'), ((6759, 6802), 'gps_building_blocks.ml.statistical_inference.models.InferenceElasticNet', 'models.InferenceElasticNet', ([], {'random_state': '(18)'}), '(random_state=18)\n', (6785, 6802), False, 'from gps_building_blocks.ml.statistical_inference import models\n'), ((7049, 7092), 'gps_building_blocks.ml.statistical_inference.models.InferenceElasticNet', 'models.InferenceElasticNet', ([], {'random_state': '(18)'}), '(random_state=18)\n', (7075, 7092), False, 'from gps_building_blocks.ml.statistical_inference import models\n'), ((7312, 7346), 'gps_building_blocks.ml.statistical_inference.models.InferenceLinearRegression', 'models.InferenceLinearRegression', ([], {}), '()\n', (7344, 7346), False, 'from gps_building_blocks.ml.statistical_inference import models\n')]
|
# Copyright 2020 <NAME>, <NAME>, <NAME>, <NAME>
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import os
import torch
import numpy as np
import torch.backends.cudnn as cudnn
import torch.optim.lr_scheduler as lr_scheduler
from contextlib import nullcontext
from torch import optim
from torch.utils.data import DataLoader
from var_sep.networks.model import SeparableNetwork
from var_sep.networks.factory import get_encoder, get_decoder, get_resnet
from var_sep.networks.utils import ConstantS
from var_sep.options import parser
from var_sep.train import train
# Mixed-precision training packages
try:
from apex import amp as apex_amp
APX_ = True
except Exception:
APX_ = False
try:
from torch.cuda import amp as torch_amp
T_AMP_ = True
except ImportError:
T_AMP_ = False
if __name__ == "__main__":
# Arguments
args = parser.parse_args()
# CPU / GPU
os.environ['OMP_NUM_THREADS'] = str(args.num_workers)
if args.device is None:
device = torch.device('cpu')
else:
cudnn.benchmark = True
os.environ["CUDA_VISIBLE_DEVICES"] = str(args.device)
device = torch.device("cuda:0")
# Seed
seed = np.random.randint(0, 10000)
torch.manual_seed(seed)
# ########
# DATASETS
# ########
last_activation = None
if args.data == 'mnist':
from var_sep.data.moving_mnist import MovingMNIST
train_set = MovingMNIST.make_dataset(args.data_dir, 64, args.nt_cond, args.nt_cond + args.nt_pred, 4, True,
args.n_object, True)
last_activation = 'sigmoid'
shape = [1, 64, 64]
elif args.data == 'chairs':
from var_sep.data.chairs import Chairs
train_set = Chairs(True, args.data_dir, args.nt_cond, args.nt_cond + args.nt_pred)
last_activation = 'sigmoid'
shape = [3, 64, 64]
elif args.data == 'taxibj':
from var_sep.data.taxibj import TaxiBJ
train_set = TaxiBJ.make_datasets(args.data_dir, len_closeness=args.nt_cond + args.nt_pred,
nt_cond=args.nt_cond)[0]
shape = [2, 32, 32]
elif args.data == "sst":
from var_sep.data.sst import SST
train_set = SST(args.data_dir, args.nt_cond, args.nt_pred, True, zones=args.zones)
shape = [1, 64, 64]
elif args.data == "wave":
from var_sep.data.wave_eq import WaveEq
train_set = WaveEq(args.data_dir, args.nt_cond, args.nt_cond + args.nt_pred, True, args.downsample)
last_activation = 'sigmoid'
shape = [1, 64, 64]
elif args.data == "wave_partial":
from var_sep.data.wave_eq import WaveEqPartial
assert args.architecture not in ['dcgan', 'vgg']
train_set = WaveEqPartial(args.data_dir, args.nt_cond, args.nt_cond + args.nt_pred, True, args.downsample,
args.n_wave_points)
last_activation = 'sigmoid'
shape = [1, args.n_wave_points]
# Save params
with open(os.path.join(args.xp_dir, 'params.json'), 'w') as f:
json.dump(vars(args), f, indent=4, sort_keys=True)
# ###########
# DATA LOADER
# ###########
def worker_init_fn(worker_id):
np.random.seed((torch.randint(100000, []).item() + worker_id))
train_loader = DataLoader(train_set, batch_size=args.batch_size, pin_memory=True, shuffle=True,
num_workers=args.num_workers, worker_init_fn=worker_init_fn)
# ########
# NETWORKS
# ########
if not args.no_s:
Es = get_encoder(args.architecture, shape, args.code_size_s, args.enc_hidden_size, args.enc_n_layers,
args.nt_cond, args.init_encoder, args.gain_encoder).to(device)
else:
# Es is constant and equal to one
assert not args.skipco
args.code_size_s = args.code_size_t
args.mixing = 'mul'
Es = ConstantS(return_value=1, code_size=args.code_size_s).to(device)
Et = get_encoder(args.architecture, shape, args.code_size_t, args.enc_hidden_size, args.enc_n_layers,
args.nt_cond, args.init_encoder, args.gain_encoder).to(device)
decoder = get_decoder(args.architecture if args.decoder_architecture is None else args.decoder_architecture,
shape, args.code_size_t, args.code_size_s, last_activation, args.dec_hidden_size,
args.dec_n_layers, args.mixing, args.skipco, args.init_encoder,
args.gain_encoder).to(device)
t_resnet = get_resnet(args.code_size_t, args.n_blocks, args.res_hidden_size, args.init_resnet,
args.gain_resnet, args.architecture == 'encoderSST').to(device)
sep_net = SeparableNetwork(Es, Et, t_resnet, decoder, args.nt_cond, args.skipco)
# #########
# OPTIMIZER
# #########
optimizer = optim.Adam(sep_net.parameters(), lr=args.lr, betas=(args.beta1, args.beta2))
if args.scheduler:
scheduler = lr_scheduler.MultiStepLR(optimizer, args.scheduler_milestones, gamma=args.scheduler_decay)
else:
scheduler = None
# #########
# MIXED-PRECISION TRAINING
# #########
if args.apex_amp and not APX_:
raise ImportError('Apex not installed (https://github.com/NVIDIA/apex)')
if args.torch_amp and not T_AMP_:
raise ImportError('Mixed-precision not supported by this PyTorch version, upgrade PyTorch or use Apex')
with (torch_amp.autocast() if args.torch_amp else nullcontext()):
train(args.xp_dir, train_loader, device, sep_net, optimizer, scheduler, args.apex_amp, args.torch_amp,
args.epochs, args.lamb_ae, args.lamb_s, args.lamb_t, args.lamb_pred, args.offset, args.nt_cond,
args.nt_pred, args.no_s, args.skipco, args.chkpt_interval, args.architecture == 'encoderSST')
|
[
"var_sep.data.taxibj.TaxiBJ.make_datasets",
"var_sep.train.train",
"numpy.random.randint",
"torch.device",
"os.path.join",
"var_sep.data.chairs.Chairs",
"var_sep.networks.utils.ConstantS",
"var_sep.networks.factory.get_resnet",
"torch.cuda.amp.autocast",
"torch.utils.data.DataLoader",
"var_sep.options.parser.parse_args",
"var_sep.data.sst.SST",
"var_sep.data.wave_eq.WaveEq",
"contextlib.nullcontext",
"var_sep.networks.model.SeparableNetwork",
"torch.randint",
"var_sep.networks.factory.get_encoder",
"torch.manual_seed",
"var_sep.data.wave_eq.WaveEqPartial",
"var_sep.data.moving_mnist.MovingMNIST.make_dataset",
"var_sep.networks.factory.get_decoder",
"torch.optim.lr_scheduler.MultiStepLR"
] |
[((1367, 1386), 'var_sep.options.parser.parse_args', 'parser.parse_args', ([], {}), '()\n', (1384, 1386), False, 'from var_sep.options import parser\n'), ((1693, 1720), 'numpy.random.randint', 'np.random.randint', (['(0)', '(10000)'], {}), '(0, 10000)\n', (1710, 1720), True, 'import numpy as np\n'), ((1725, 1748), 'torch.manual_seed', 'torch.manual_seed', (['seed'], {}), '(seed)\n', (1742, 1748), False, 'import torch\n'), ((3820, 3966), 'torch.utils.data.DataLoader', 'DataLoader', (['train_set'], {'batch_size': 'args.batch_size', 'pin_memory': '(True)', 'shuffle': '(True)', 'num_workers': 'args.num_workers', 'worker_init_fn': 'worker_init_fn'}), '(train_set, batch_size=args.batch_size, pin_memory=True, shuffle=\n True, num_workers=args.num_workers, worker_init_fn=worker_init_fn)\n', (3830, 3966), False, 'from torch.utils.data import DataLoader\n'), ((5255, 5325), 'var_sep.networks.model.SeparableNetwork', 'SeparableNetwork', (['Es', 'Et', 't_resnet', 'decoder', 'args.nt_cond', 'args.skipco'], {}), '(Es, Et, t_resnet, decoder, args.nt_cond, args.skipco)\n', (5271, 5325), False, 'from var_sep.networks.model import SeparableNetwork\n'), ((1507, 1526), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (1519, 1526), False, 'import torch\n'), ((1647, 1669), 'torch.device', 'torch.device', (['"""cuda:0"""'], {}), "('cuda:0')\n", (1659, 1669), False, 'import torch\n'), ((1929, 2049), 'var_sep.data.moving_mnist.MovingMNIST.make_dataset', 'MovingMNIST.make_dataset', (['args.data_dir', '(64)', 'args.nt_cond', '(args.nt_cond + args.nt_pred)', '(4)', '(True)', 'args.n_object', '(True)'], {}), '(args.data_dir, 64, args.nt_cond, args.nt_cond +\n args.nt_pred, 4, True, args.n_object, True)\n', (1953, 2049), False, 'from var_sep.data.moving_mnist import MovingMNIST\n'), ((5511, 5606), 'torch.optim.lr_scheduler.MultiStepLR', 'lr_scheduler.MultiStepLR', (['optimizer', 'args.scheduler_milestones'], {'gamma': 'args.scheduler_decay'}), '(optimizer, args.scheduler_milestones, gamma=args.\n scheduler_decay)\n', (5535, 5606), True, 'import torch.optim.lr_scheduler as lr_scheduler\n'), ((6046, 6354), 'var_sep.train.train', 'train', (['args.xp_dir', 'train_loader', 'device', 'sep_net', 'optimizer', 'scheduler', 'args.apex_amp', 'args.torch_amp', 'args.epochs', 'args.lamb_ae', 'args.lamb_s', 'args.lamb_t', 'args.lamb_pred', 'args.offset', 'args.nt_cond', 'args.nt_pred', 'args.no_s', 'args.skipco', 'args.chkpt_interval', "(args.architecture == 'encoderSST')"], {}), "(args.xp_dir, train_loader, device, sep_net, optimizer, scheduler,\n args.apex_amp, args.torch_amp, args.epochs, args.lamb_ae, args.lamb_s,\n args.lamb_t, args.lamb_pred, args.offset, args.nt_cond, args.nt_pred,\n args.no_s, args.skipco, args.chkpt_interval, args.architecture ==\n 'encoderSST')\n", (6051, 6354), False, 'from var_sep.train import train\n'), ((2254, 2324), 'var_sep.data.chairs.Chairs', 'Chairs', (['(True)', 'args.data_dir', 'args.nt_cond', '(args.nt_cond + args.nt_pred)'], {}), '(True, args.data_dir, args.nt_cond, args.nt_cond + args.nt_pred)\n', (2260, 2324), False, 'from var_sep.data.chairs import Chairs\n'), ((3528, 3568), 'os.path.join', 'os.path.join', (['args.xp_dir', '"""params.json"""'], {}), "(args.xp_dir, 'params.json')\n", (3540, 3568), False, 'import os\n'), ((4501, 4658), 'var_sep.networks.factory.get_encoder', 'get_encoder', (['args.architecture', 'shape', 'args.code_size_t', 'args.enc_hidden_size', 'args.enc_n_layers', 'args.nt_cond', 'args.init_encoder', 'args.gain_encoder'], {}), '(args.architecture, shape, args.code_size_t, args.\n enc_hidden_size, args.enc_n_layers, args.nt_cond, args.init_encoder,\n args.gain_encoder)\n', (4512, 4658), False, 'from var_sep.networks.factory import get_encoder, get_decoder, get_resnet\n'), ((4697, 4972), 'var_sep.networks.factory.get_decoder', 'get_decoder', (['(args.architecture if args.decoder_architecture is None else args.\n decoder_architecture)', 'shape', 'args.code_size_t', 'args.code_size_s', 'last_activation', 'args.dec_hidden_size', 'args.dec_n_layers', 'args.mixing', 'args.skipco', 'args.init_encoder', 'args.gain_encoder'], {}), '(args.architecture if args.decoder_architecture is None else\n args.decoder_architecture, shape, args.code_size_t, args.code_size_s,\n last_activation, args.dec_hidden_size, args.dec_n_layers, args.mixing,\n args.skipco, args.init_encoder, args.gain_encoder)\n', (4708, 4972), False, 'from var_sep.networks.factory import get_encoder, get_decoder, get_resnet\n'), ((5066, 5207), 'var_sep.networks.factory.get_resnet', 'get_resnet', (['args.code_size_t', 'args.n_blocks', 'args.res_hidden_size', 'args.init_resnet', 'args.gain_resnet', "(args.architecture == 'encoderSST')"], {}), "(args.code_size_t, args.n_blocks, args.res_hidden_size, args.\n init_resnet, args.gain_resnet, args.architecture == 'encoderSST')\n", (5076, 5207), False, 'from var_sep.networks.factory import get_encoder, get_decoder, get_resnet\n'), ((5978, 5998), 'torch.cuda.amp.autocast', 'torch_amp.autocast', ([], {}), '()\n', (5996, 5998), True, 'from torch.cuda import amp as torch_amp\n'), ((6022, 6035), 'contextlib.nullcontext', 'nullcontext', ([], {}), '()\n', (6033, 6035), False, 'from contextlib import nullcontext\n'), ((4073, 4230), 'var_sep.networks.factory.get_encoder', 'get_encoder', (['args.architecture', 'shape', 'args.code_size_s', 'args.enc_hidden_size', 'args.enc_n_layers', 'args.nt_cond', 'args.init_encoder', 'args.gain_encoder'], {}), '(args.architecture, shape, args.code_size_s, args.\n enc_hidden_size, args.enc_n_layers, args.nt_cond, args.init_encoder,\n args.gain_encoder)\n', (4084, 4230), False, 'from var_sep.networks.factory import get_encoder, get_decoder, get_resnet\n'), ((4426, 4479), 'var_sep.networks.utils.ConstantS', 'ConstantS', ([], {'return_value': '(1)', 'code_size': 'args.code_size_s'}), '(return_value=1, code_size=args.code_size_s)\n', (4435, 4479), False, 'from var_sep.networks.utils import ConstantS\n'), ((2488, 2593), 'var_sep.data.taxibj.TaxiBJ.make_datasets', 'TaxiBJ.make_datasets', (['args.data_dir'], {'len_closeness': '(args.nt_cond + args.nt_pred)', 'nt_cond': 'args.nt_cond'}), '(args.data_dir, len_closeness=args.nt_cond + args.\n nt_pred, nt_cond=args.nt_cond)\n', (2508, 2593), False, 'from var_sep.data.taxibj import TaxiBJ\n'), ((2751, 2821), 'var_sep.data.sst.SST', 'SST', (['args.data_dir', 'args.nt_cond', 'args.nt_pred', '(True)'], {'zones': 'args.zones'}), '(args.data_dir, args.nt_cond, args.nt_pred, True, zones=args.zones)\n', (2754, 2821), False, 'from var_sep.data.sst import SST\n'), ((2948, 3040), 'var_sep.data.wave_eq.WaveEq', 'WaveEq', (['args.data_dir', 'args.nt_cond', '(args.nt_cond + args.nt_pred)', '(True)', 'args.downsample'], {}), '(args.data_dir, args.nt_cond, args.nt_cond + args.nt_pred, True, args\n .downsample)\n', (2954, 3040), False, 'from var_sep.data.wave_eq import WaveEq\n'), ((3754, 3779), 'torch.randint', 'torch.randint', (['(100000)', '[]'], {}), '(100000, [])\n', (3767, 3779), False, 'import torch\n'), ((3270, 3389), 'var_sep.data.wave_eq.WaveEqPartial', 'WaveEqPartial', (['args.data_dir', 'args.nt_cond', '(args.nt_cond + args.nt_pred)', '(True)', 'args.downsample', 'args.n_wave_points'], {}), '(args.data_dir, args.nt_cond, args.nt_cond + args.nt_pred, \n True, args.downsample, args.n_wave_points)\n', (3283, 3389), False, 'from var_sep.data.wave_eq import WaveEqPartial\n')]
|
# -*- coding: utf-8 -*-
"""
Created on Tue May 7 23:58:52 2019
@author: Sachin
"""
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
dataset = pd.read_csv('data.csv')
df = dataset.iloc[:,:-1].values
X = pd.DataFrame(df)
x = X.loc[:,X.columns != 1]
y = X.loc[:,1]
for i in range(len(y)) :
if y[i] == 'M' :
y[i] = 1
for i in range(len(y)) :
if y[i] == 'B' :
y[i] = 0
y
rows = 10
col = 10
t = rows*col
nd = 31
#network dimensions
n_d = np.array([10,10])
n_it = 200
n_lr = 0.5
#weigth
w = np.random.random((3,21,1))
|
[
"pandas.read_csv",
"numpy.random.random",
"numpy.array",
"pandas.DataFrame"
] |
[((181, 204), 'pandas.read_csv', 'pd.read_csv', (['"""data.csv"""'], {}), "('data.csv')\n", (192, 204), True, 'import pandas as pd\n'), ((244, 260), 'pandas.DataFrame', 'pd.DataFrame', (['df'], {}), '(df)\n', (256, 260), True, 'import pandas as pd\n'), ((559, 577), 'numpy.array', 'np.array', (['[10, 10]'], {}), '([10, 10])\n', (567, 577), True, 'import numpy as np\n'), ((617, 645), 'numpy.random.random', 'np.random.random', (['(3, 21, 1)'], {}), '((3, 21, 1))\n', (633, 645), True, 'import numpy as np\n')]
|
# Copyright (c) 2021, <NAME>, FUNLab, Xiamen University
# All rights reserved.
# Generate terrain (site specific) data
import os
import argparse
import random
import numpy as np
import scipy.io as sio
from pprint import pprint
def gen_BMs(world_len: int, mesh_len: int, N: int, save_dir: str, seed=123):
'''
Generate a world with building meshes.
'''
random.seed(seed)
np.random.seed(seed)
fname = f'terrain-{N}.mat'
assert world_len % mesh_len == 0, f'world_len={world_len}, mesh_len={mesh_len}'
M = world_len//mesh_len
assert M*M - N >= 0
raw_grids = np.ones(M*M, dtype=np.float32) * 90
zero_idcs = sorted(random.sample(range(0, M*M), M*M-N))
raw_grids[zero_idcs] = 0.
grids = raw_grids.reshape((M, M)).astype(np.float32)
mat = {
'world_len': world_len,
'mesh_len': mesh_len,
'N': N,
'grids': grids,
}
save_path = os.path.join(save_dir, fname)
sio.savemat(save_path, mat)
return mat, save_path
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--world-len', type=int, default=1000)
parser.add_argument('--mesh-len', type=int, default=50)
parser.add_argument('--N', type=int, default=60)
parser.add_argument('--save-dir', type=str, default='./')
parser.add_argument('--seed', type=int, default=123)
args = parser.parse_args()
mat, save_path = gen_BMs(args.world_len, args.mesh_len, args.N, args.save_dir, args.seed)
pprint(mat)
pprint(save_path)
|
[
"numpy.random.seed",
"argparse.ArgumentParser",
"scipy.io.savemat",
"numpy.ones",
"random.seed",
"pprint.pprint",
"os.path.join"
] |
[((370, 387), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (381, 387), False, 'import random\n'), ((392, 412), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (406, 412), True, 'import numpy as np\n'), ((919, 948), 'os.path.join', 'os.path.join', (['save_dir', 'fname'], {}), '(save_dir, fname)\n', (931, 948), False, 'import os\n'), ((953, 980), 'scipy.io.savemat', 'sio.savemat', (['save_path', 'mat'], {}), '(save_path, mat)\n', (964, 980), True, 'import scipy.io as sio\n'), ((1049, 1074), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1072, 1074), False, 'import argparse\n'), ((1500, 1511), 'pprint.pprint', 'pprint', (['mat'], {}), '(mat)\n', (1506, 1511), False, 'from pprint import pprint\n'), ((1516, 1533), 'pprint.pprint', 'pprint', (['save_path'], {}), '(save_path)\n', (1522, 1533), False, 'from pprint import pprint\n'), ((598, 630), 'numpy.ones', 'np.ones', (['(M * M)'], {'dtype': 'np.float32'}), '(M * M, dtype=np.float32)\n', (605, 630), True, 'import numpy as np\n')]
|
import unittest
import mindspore
import numpy as np
from mindspore import Tensor
from elmo.modules.highway import HighWay
from mindspore import context
class TestHighWay(unittest.TestCase):
def test_highway(self):
context.set_context(mode=context.PYNATIVE_MODE, device_target='Ascend')
inputs = Tensor(np.random.randn(3, 10), mindspore.float32)
highway = HighWay(10, 2)
outputs = highway(inputs)
assert outputs.shape == (3, 10)
def test_highway_graph_mode(self):
context.set_context(mode=context.GRAPH_MODE, device_target='Ascend')
inputs = Tensor(np.random.randn(3, 10), mindspore.float32)
highway = HighWay(10, 2)
outputs = highway(inputs)
assert outputs.shape == (3, 10)
|
[
"mindspore.context.set_context",
"elmo.modules.highway.HighWay",
"numpy.random.randn"
] |
[((227, 298), 'mindspore.context.set_context', 'context.set_context', ([], {'mode': 'context.PYNATIVE_MODE', 'device_target': '"""Ascend"""'}), "(mode=context.PYNATIVE_MODE, device_target='Ascend')\n", (246, 298), False, 'from mindspore import context\n'), ((384, 398), 'elmo.modules.highway.HighWay', 'HighWay', (['(10)', '(2)'], {}), '(10, 2)\n', (391, 398), False, 'from elmo.modules.highway import HighWay\n'), ((532, 600), 'mindspore.context.set_context', 'context.set_context', ([], {'mode': 'context.GRAPH_MODE', 'device_target': '"""Ascend"""'}), "(mode=context.GRAPH_MODE, device_target='Ascend')\n", (551, 600), False, 'from mindspore import context\n'), ((686, 700), 'elmo.modules.highway.HighWay', 'HighWay', (['(10)', '(2)'], {}), '(10, 2)\n', (693, 700), False, 'from elmo.modules.highway import HighWay\n'), ((323, 345), 'numpy.random.randn', 'np.random.randn', (['(3)', '(10)'], {}), '(3, 10)\n', (338, 345), True, 'import numpy as np\n'), ((625, 647), 'numpy.random.randn', 'np.random.randn', (['(3)', '(10)'], {}), '(3, 10)\n', (640, 647), True, 'import numpy as np\n')]
|
"""
PCA(SVD) analysis for glbase expression objects.
"""
from operator import itemgetter
import numpy
import numpy.linalg as LA
import matplotlib.pyplot as plot
import matplotlib.patches
from mpl_toolkits.mplot3d import Axes3D, art3d # not always available?
import scipy.cluster.vq
from . import config
from .draw import draw
from .genelist import genelist
class svd:
def __init__(self, parent=None, rowwise=False, label_key=None, whiten=False, mean_subtraction=False, **kargs):
"""
**Purpose**
A custom class for PCA(SVD) analysis of expression object data.
Not recommended to use directly, but if you must then:
expn = expression(...)
expn.svd = pca(expn)
expn.svd.loading(...)
...
**Arguments**
parent (Required)
The parent expression/genelist object.
whiten (Optional, default=False)
'Normalise' the data. Each feature is divided by its standard deviation
across all observations to give it unit variance
mean_subtraction (Optional, default=False)
subtract the mean from the matrix before PCA. Performed BEFORE Whitening
rowwise (Optional, default=False)
Perform PCA on the columns or the rows
label_key (Optional, Required if rowwise=True)
The key to use in the genelist to label. Required if rowwise=True
"""
if rowwise:
assert label_key, "You must specifiy 'label_key' if rowwise=True"
self.parent = parent
matrix = numpy.array(parent.serialisedArrayDataList)
self.__draw = draw()
self.cols = "black"
self.rowwise = rowwise
if rowwise:
if mean_subtraction:
config.log.info("pca(): mean subtract")
matrix -= numpy.mean(matrix, axis=0)
if whiten:
config.log.info("pca(): whiten")
matrix = scipy.cluster.vq.whiten(matrix)
#print matrix
self.__u, self.__d, self.__v = LA.svd(matrix, full_matrices=False)
self.labels = parent[label_key]
self.label_key = label_key
else:
matrix = matrix.T
if mean_subtraction:
config.log.info("pca(): mean subtract")
matrix -= numpy.mean(matrix, axis=0)
if whiten:
config.log.info("pca(): whiten")
matrix = scipy.cluster.vq.whiten(matrix)
#print matrix
self.__u, self.__d, self.__v = LA.svd(matrix, full_matrices=False)
self.labels = parent.getConditionNames() # It makes more sense to get a copy incase someone
# does something that reorders the list in between
self.label_key = label_key
self.__u = numpy.array(self.__u)
self.valid = True # Just check it's all calc'ed.
def __repr__(self):
return("<glbase.pca>")
def __str__(self):
ret = ["SVD object",
" Expression: %s" % self.parent.name,
" Dimensions: %s" % len(self.__d),
" u: %s" % str(self.__u.shape),
" v: %s" % str(self.__v.shape)
]
return("\n".join(ret))
def __len__(self):
"""
(Override)
return the number of dimensions.
"""
return(len(self.__d))
def project(self, new_expn):
"""
THIS IS CURRENTLY NOT WORKING
**Purpose**
Give me a new expression object containing a new set of conditions and
project those new conditions into the previously generated PCA.
**Arguments**
new_expn (Required)
a new expression object with at least one condition.
**returns**
True if successful, and all subsequent pca methods will use the new projected data.
"""
"""
data = numpy.array(self.parent.serialisedArrayDataList)
import sklearn
skpca = sklearn.decomposition.PCA()
X_r = skpca.fit(data).transform(data)
self.__v = X_r
"""
# old martrisx
matrix = numpy.array(self.parent.serialisedArrayDataList)
U, S, V = numpy.linalg.svd(matrix.T, full_matrices=False)
print("matrix", matrix.shape)
# set-ups
self.parent = new_expn
if self.rowwise:
self.labels = new_expn[self.label_key]
else:
self.labels = new_expn.getConditionNames()
matrix = numpy.array(self.parent.serialisedArrayDataList)
S = numpy.diag(S)
print("U", U.shape)
print("V", V.shape)
print("S", S.shape)
print("matrix", matrix.shape)
#data = np.dot(U, np.dot(S, V))
#X_transformed = np.dot(X_transformed, self.V.T)
print(numpy.dot(S, V).shape)
pr = numpy.dot(matrix, S)
print("pr", pr.shape)
#y = x*W;
#y0 = Y(1,:);
#sum(abs(y0 - y)) %
# I want a new v. U and D are the same.
self.__v = pr
print(U)
print()
print(pr)
print(numpy.allclose(U, pr))
print(numpy.allclose(matrix.T, numpy.dot(U, numpy.dot(S, V))))
return(True)
def get_uvd(self):
"""
**Purpose**
Get the u, v, d matrices.
**Arguments**
None
**Returns**
A dict, containing:
{"u": u,
"v": v,
"d": d}
"""
ret = {"u": self.__u,
"v": self.__v,
"d": self.__d}
return(ret)
def max(self):
"""
**Purpose**
Return the maximum number of PC for this experiment.
**Arguments**
None
**Returns**
The number of PCs. Strictly, len(d)
"""
return(len(self.__d))
def set_cols(self, sample_colours):
"""
**Purpose**
Set the colours for the individual samples.
**Arguments**
sample_colours (Required)
A list of sample colours (or None) for scatter plots and the like.
Must be the same length as the number of conditions.
**Returns**
None
"""
self.cols = sample_colours
def pcloading(self, filename=None, percent_variance=True, **kargs):
"""
**Purpose**
plot a graph of PC loading.
**Arguments**
filename (Required)
The filename to save the image to.
percent_variance (Optional, default=True)
Report as the percent variance explained
<common figure arguments are supported>
**Returns**
None.
"""
assert filename, "loading(): Must provide a filename"
if "aspect" not in kargs:
kargs["aspect"] = "wide"
newd = self.__d
if percent_variance:
newd2 = numpy.array(self.__d) **2
newd = (newd2 / sum(newd2)) * 100.0
fig = self.__draw.getfigure(**kargs)
ax = fig.add_subplot(111)
x = numpy.arange(len(newd))
ax.bar(x-0.4, newd, ec="black", color="grey")
ax.set_xlabel("Principal components")
if percent_variance:
ax.set_ylabel('Percent Variance')
else:
ax.set_ylabel("Loading")
ax.set_xticklabels(x+1)
ax.set_xticks(x)
ax.set_xlim([-0.5, len(newd)-0.5])
self.__draw.do_common_args(ax, **kargs)
real_filename = self.__draw.savefigure(fig, filename)
config.log.info("loading(): Saved PC loading '%s'" % real_filename)
def get_loading_percents(self, exclude_first_pc=False, **kargs):
"""
**Purpose**
Returns the percent of variance:
d^2 / sum(d^2)
**Arguments**
exclude_first_pc (Optional, default=False)
exclude the first PC.
In a lot of my data I use unnormalised data, this usually means the first
PC contains the 'shape' of the data and can dominate the overall
percent variance. Set this to True to ignore PC1.
**Returns**
Returns a dict in the form:
{
PC1: float(percent),
PC2: float(percent), ...
}
"""
res = {}
if exclude_first_pc:
newd2 = numpy.array(self.__d[1:]) **2
else:
newd2 = numpy.array(self.__d) **2
newd = (newd2 / sum(newd2)) * 100.0
for i, p in enumerate(newd):
if exclude_first_pc:
res[i+2] = p
else:
res[i+1] = p
return(res)
def scatter(self, x, y, filename=None, spot_cols=None, spots=True, label=False, alpha=0.8,
spot_size=40, label_font_size=7, cut=None, squish_scales=False, only_plot_if_x_in_label=None, **kargs):
"""
**Purpose**
plot a scatter plot of PCx against PCy.
**Arguments**
x, y (Required)
PC dimension to plot as scatter
Note that PC begin at 1 (and not at zero, as might be expected)
filename (Required)
spot_cols (Optional, default="black" or self.set_cols())
list of colours for the samples, should be the same length as
the number of conditions.
if labels == True and spots == False and spot_cols is not None then
spot_cols will be used to colour the labels.
label (Optional, default=False)
label each spot with the name of the condition
only_plot_if_x_in_label (Optional, default=None)
Only plot an individual scatter if X is in the label name.
Allows you to effectively remove points from the PCA plot.
spots (Optional, default=True)
Draw the spots
alpha (Optional, default=0.8)
alpha value to use to blend the individual points
spot_size (Optional, default=40)
Size of the spots on the scatter
label_font_size (Optional, default=7)
Size of the spot label text, only valid if label=True
cut (Optional, default=None)
Send a rectangle of the form [topleftx, toplefty, bottomrightx, bottomrighty], cut out all of the items within that
area and return their label and PC score
squish_scales (Optional, default=False)
set the limits very aggressively to [minmin(x), minmax(y)]
**Returns**
None
You can get PC data from pca.get_uvd()
"""
assert filename, "scatter(): Must provide a filename"
labels = self.labels
xdata = self.__v[x-1]
ydata = self.__v[y-1]
return_data = self.__unified_scatter(labels, xdata, ydata, x=x, y=y, filename=filename, spot_cols=spot_cols, spots=spots, label=label, alpha=alpha,
spot_size=spot_size, label_font_size=label_font_size, cut=cut, squish_scales=squish_scales, only_plot_if_x_in_label=only_plot_if_x_in_label, **kargs)
return(return_data)
def __unified_scatter(self, labels, xdata, ydata, x, y, filename=None, spot_cols=None, spots=True, label=False, alpha=0.8,
spot_size=40, label_font_size=7, cut=None, squish_scales=False, only_plot_if_x_in_label=None, **kargs):
'''
Unified for less bugs, more fun!
'''
perc_weights = self.get_loading_percents(exclude_first_pc=True)
ret_data = None
if not "aspect" in kargs:
kargs["aspect"] = "square"
fig = self.__draw.getfigure(**kargs)
ax = fig.add_subplot(111)
cols = self.cols
if spot_cols:
cols = spot_cols
if only_plot_if_x_in_label:
newx = []
newy = []
newlab = []
newcols = []
for i, lab in enumerate(labels):
if only_plot_if_x_in_label in lab:
newx.append(xdata[i])
newy.append(ydata[i])
newlab.append(labels[i])
newcols.append(spot_cols[i])
xdata = newx
ydata = newy
labels = newlab
cols = newcols
if spots:
ax.scatter(xdata, ydata, s=spot_size, alpha=alpha, edgecolors="none", c=cols)
else:
# if spots is false then the axis limits are set to 0..1. I will have to send my
# own semi-sensible limits:
ax.set_xlim([min(xdata), max(xdata)])
ax.set_ylim([min(ydata), max(ydata)])
if label:
for i, lab in enumerate(labels):
if not spots and isinstance(spot_cols, list):
ax.text(xdata[i], ydata[i], lab, size=label_font_size, ha="center", va="top", color=spot_cols[i])
else:
ax.text(xdata[i], ydata[i], lab, size=label_font_size, ha="center", va="top", color="black")
# Tighten the axis
if squish_scales:
if not "xlims" in kargs:
ax.set_xlim([min(xdata), max(xdata)])
if not "ylims" in kargs:
ax.set_ylim([min(ydata), max(ydata)])
ax.set_xlabel("PC%s (%.1f%%)" % (x, perc_weights[x+1])) # can be overridden via do_common_args()
ax.set_ylabel("PC%s (%.1f%%)" % (y, perc_weights[y+1]))
if "logx" in kargs and kargs["logx"]:
ax.set_xscale("log", basex=kargs["logx"])
if "logy" in kargs and kargs["logy"]:
ax.set_yscale("log", basey=kargs["logy"])
if cut:
rect = matplotlib.patches.Rectangle(cut[0:2], cut[2]-cut[0], cut[3]-cut[1], ec="none", alpha=0.2, fc="orange")
ax.add_patch(rect)
tdata = []
for i in range(0, len(xdata)):
if xdata[i] > cut[0] and xdata[i] < cut[2]:
if ydata[i] < cut[1] and ydata[i] > cut[3]:
if self.rowwise: # grab the full entry from the parent genelist
dat = {"pcx": xdata[i], "pcy": ydata[i]}
dat.update(self.parent.linearData[i])
tdata.append(dat)
else:
tdata.append({"name": lab[i], "pcx": xdata[i], "pcy": ydata[i]})
if tdata:
ret_data = genelist()
ret_data.load_list(tdata)
self.__draw.do_common_args(ax, **kargs)
real_filename = self.__draw.savefigure(fig, filename)
config.log.info("scatter: Saved 'PC%s' vs 'PC%s' scatter to '%s'" % (x, y, real_filename))
return(ret_data)
def loading_scatter(self, x, y, label_key, filename=None, spot_cols=None, spots=True, label=False, alpha=0.8,
topbots=False,
spot_size=40, label_font_size=7, cut=None, squish_scales=False, **kargs):
"""
**Purpose**
plot a scatter plot of the loading values for PCx and PCy
**Arguments**
x, y (Required)
PC dimension to plot as scatter
Note that PC begin at 1 (and not at zero, as might be expected)
label_key (Required)
a label key in the original genelist to use as a label for the spots
filename (Required)
topbots (Optional, default=False)
take on the top and bottom N on each PC axis
spot_cols (Optional, default="black" or self.set_cols())
list of colours for the samples, should be the same length as
the number of conditions.
if labels == True and spots == False and spot_cols is not None then
spot_cols will be used to colour the labels.
label (Optional, default=False)
label each spot with the name of the gene
spots (Optional, default=True)
Draw the spots
alpha (Optional, default=0.8)
alpha value to use to blend the individual points
spot_size (Optional, default=40)
Size of the spots on the scatter
label_font_size (Optional, default=7)
Size of the spot label text, only valid if label=True
cut (Optional, default=None)
Send a rectangle of the form [leftx, topy, rightx, bottomy], cut out all of the items within that
area and return their label and PC score
squish_scales (Optional, default=False)
set the limits very aggressively to [minmin(x), minmax(y)]
**Returns**
None
You can get PC data from pca.get_uvd()
"""
assert filename, "loading_scatter: Must provide a filename"
assert label_key, "loading_scatter: Must provide a label_key for the label names"
assert label_key in self.parent, "loading_scatter(): I can't find '%s' label_key in the original genelist" % label_key
ret_data = None
xdata = self.__u[:,x-1]
ydata = self.__u[:,y-1]
perc_weights = self.get_loading_percents(exclude_first_pc=True)
labs = self.parent[label_key]
if topbots:
# Get the top and bot from the X and Y sorted PCs:
sortable_data = list(zip(xdata, ydata, self.parent[label_key]))
sorted_by_x = sorted(sortable_data, key=lambda sortable_data: sortable_data[0])
x_tbs = list(sorted_by_x[0:topbots]) + list(sorted_by_x[-topbots:])
sorted_by_y = sorted(sortable_data, key=lambda sortable_data: sortable_data[1])
y_tbs = list(sorted_by_y[0:topbots]) + list(sorted_by_y[-topbots:])
# Merge duplicates:
all_items = list(set(x_tbs + y_tbs))
xdata = [i[0] for i in all_items]
ydata = [i[1] for i in all_items]
labs = [i[2] for i in all_items]
#print xdata, ydata
if not "aspect" in kargs:
kargs["aspect"] = "square"
fig = self.__draw.getfigure(**kargs)
ax = fig.add_subplot(111)
cols = self.cols
if spot_cols:
cols = spot_cols
if spots:
ax.scatter(xdata, ydata, s=spot_size, alpha=alpha, edgecolors="none", c=cols)
else:
# if spots is false then the axis limits are set to 0..1. I will have to send my
# own semi-sensible limits:
ax.set_xlim([min(xdata), max(xdata)])
ax.set_ylim([min(ydata), max(ydata)])
if label:
for i, lab in enumerate(labs):
if not spots and isinstance(spot_cols, list):
ax.text(xdata[i], ydata[i], lab, size=label_font_size, ha="center", va="top", color=spot_cols[i])
else:
ax.text(xdata[i], ydata[i], lab, size=label_font_size, ha="center", va="top", color="black")
# Tighten the axis
if squish_scales:
if not "xlims" in kargs:
ax.set_xlim([min(xdata), max(xdata)])
if not "ylims" in kargs:
ax.set_ylim([min(ydata), max(ydata)])
ax.set_xlabel("PC%s (%.1f%%)" % (x, perc_weights[x])) # can be overridden via do_common_args()
ax.set_ylabel("PC%s (%.1f%%)" % (y, perc_weights[y]))
if cut:
rect = matplotlib.patches.Rectangle(cut[0:2], cut[2]-cut[0], cut[3]-cut[1], ec="none", alpha=0.2, fc="orange")
ax.add_patch(rect)
tdata = []
labels = self.parent[label_key] # Just get once or big hit!
for i in range(0, len(xdata)):
if xdata[i] > cut[0] and xdata[i] < cut[2]:
if ydata[i] < cut[1] and ydata[i] > cut[3]:
tdata.append({"name": labels[i], "pcx": xdata[i], "pcy": ydata[i]})
if tdata:
ret_data = genelist()
ret_data.load_list(tdata)
self.__draw.do_common_args(ax, **kargs)
real_filename = self.__draw.savefigure(fig, filename)
config.log.info("loading_scatter: Saved 'PC%s' vs 'PC%s' scatter to '%s'" % (x, y, real_filename))
return(ret_data)
def scatter3d(self, x, y, z, filename=None, spot_cols=None, label=False, stem=False,
label_font_size=6, rotation=134, elevation=48, interactive=False, squish_scales=False,
spot_size=40, **kargs):
"""
**Purpose**
plot a scatter plot of PCx against PCy against PCz
This is the 3D variant
**Arguments**
x, y, z (Required)
PC dimension to plot as scatter
Note that PC begin at 1 (and not at zero, as might be expected)
spot_cols (Optional, default="black" or self.set_cols())
list of colours for the samples, should be the same length as
the number of conditions.
spot_size (Optional, default=40)
The relative spot size.
label (Optional, default=False)
label each spot with the name of the condition
label_font_size (Optional, default=6)
label font size.
stem (Optional, default=False)
Draw stems from the spot down to the base of the graph. (i.e. z=0)
rotation (Optional, default=134)
The rotation along the X, Y plane
elevation (Optional, default=48
The rotation along the Z plane.
interactive (Optional, default=False)
if True then spawn the matplotlib show() view. Note that this will pause
execution of your script.
Note that by default glbase uses a non-GUI matplotlib setting.
You will need to fiddle around with matplotlib.use() before importing glbase
squish_scales (Optional, default=False)
set the limits very aggressively to [minmax(x), minmax(y), minmax(z)]
**Returns**
None
You can get PC data from pca.get_uvd()
"""
assert filename, "scatter(): Must provide a filename"
xdata = self.__v[x-1]
ydata = self.__v[y-1]
zdata = self.__v[z-1]
fig = self.__draw.getfigure(**kargs)
ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=elevation, azim=rotation)
cols = self.cols
if spot_cols:
cols = spot_cols
ax.scatter(xdata, ydata, zdata, edgecolors="none", c=cols, s=spot_size)
if label:
for i, lab in enumerate(self.labels):
ax.text(xdata[i], ydata[i], zdata[i], lab, size=label_font_size, ha="center", va="bottom")
if stem: # stem must go after scatter for sorting. Actually, not true right? matplotlib uses zorder for that...
z_min = min(zdata)
for x_, y_, z_ in zip(xdata, ydata, zdata):
line = art3d.Line3D(*list(zip((x_, y_, z_min), (x_, y_, z_))), marker=None, c="grey", alpha=0.1)
ax.add_line(line)
ax.set_xlabel("PC%s" % (x,)) # can be overridden via do_common_args()
ax.set_ylabel("PC%s" % (y,))
ax.set_zlabel("PC%s" % (z,))
if "logx" in kargs and kargs["logx"]:
ax.set_xscale("log", basex=kargs["logx"])
if "logy" in kargs and kargs["logy"]:
ax.set_yscale("log", basey=kargs["logy"])
if squish_scales:
# Don't worry about kargs, do_common_args will overwrite.
ax.set_xlim([min(xdata), max(xdata)])
ax.set_ylim([min(ydata), max(ydata)])
ax.set_zlim([min(zdata), max(zdata)])
self.__draw.do_common_args(ax, **kargs)
if "zlims" in kargs:
ax.set_zlim([kargs["zlim"][0], kargs["zlim"][1]])
if interactive:
fig.show() # hope you are not on a cluster!
real_filename = self.__draw.savefigure(fig, filename)
config.log.info("scatter3d(): Saved 'PC%s' vs 'PC%s' vs 'PC%s' scatter to '%s'" % (x, y, z, real_filename))
def condition_loading(self, filename=None, PC=-1, top=50, bot=50, label_key='PC-score', all=False, **kargs):
'''
**Purpose**
Get the column loading
**Arguments**
Filename (Required)
PC (Required)
The PC to get the condition loading for
**Returns**
A list of conditions, sorted in the same orientation as the
'''
assert filename, 'condition_loading: You must specifiy a filename'
assert PC >= 0, "condition_loading: PC of <1 specified"
if "aspect" not in kargs:
kargs["aspect"] = "long"
data = self.__v[PC-1]
labs = self.parent._conditions
packed_data = [{label_key: i[0], "l": i[1]} for i in zip(labs, data)]
#print packed_data
sorted_data = sorted(packed_data, key=itemgetter("l"))
data = [i["l"] for i in sorted_data]
labs = [i[label_key] for i in sorted_data]
if all:
data = data
labs = labs
else:
if bot > 0 and top > 0: # data[-0:] returns the entire list and data[0:0] returns [] !
data = data[0:top] + data[-bot:]
labs = labs[0:top] + labs[-bot:]
elif top > 0:
data = data[0:top]
labs = labs[0:top]
elif bot > 0:
data = data[-bot:]
labs = labs[-bot:]
if filename:
fig = self.__draw.getfigure(**kargs)
ax = fig.add_subplot(111)
ax.set_position([0.3,0.03,0.6,0.96])
x = numpy.arange(len(data))
ax.barh(x-0.4, data, ec="black", color="grey")
ax.set_ylabel("Columns")
ax.set_xlabel("Loading")
ax.set_yticklabels(labs)
ax.set_yticks(x)
ax.set_ylim([-0.5, len(data)-0.5])
[t.set_fontsize(6) for t in ax.get_yticklabels()]
self.__draw.do_common_args(ax, **kargs)
real_filename = self.__draw.savefigure(fig, filename)
config.log.info("loading(): Saved PC loading '%s'" % real_filename)
# work out the list to return
newgl = genelist()
newgl.load_list([{"name": i[0], "pc_loading": i[1]} for i in zip(labs, data)]) # relist it so that top bot are used
newgl.sort("pc_loading")
return(newgl)
def gene_loading(self, filename=None, PC=-1, top=50, bot=50, label_key=None, **kargs):
"""
Deprecated.
NOTE: This is an alias of loading(), please use loading() and NOT gene_loading()
in future this method will be deleted.
"""
return(self.loading(filename=filename, PC=PC, top=top, bot=bot, label_key=label_key, **kargs))
def loading(self, filename=None, PC=-1, top=50, bot=50, label_key=None, all=None, **kargs):
"""
**Purpose**
Get the loading for the items for a particular PC
(technically, get u for a particular PC)
**Arguments**
filename(Optional)
filename to save the loading barchart to. This is optional, so you can use this function
just top return top and bot
PC (Required)
The Principal Component to use
label_key (Required)
The key in the expression object to use to label the bar chart
top & bot (Optional, default=50)
the number of top and bottom genes to plot on the bar graph and
also to return as a genelist. Set both to None to get all componenets
all (Optional, default=False)
if all is True, return all of the items.
**Returns**
topbot of the loading in a new genelist with an extra key "loadingPC<PC#>"
The object will be based on the original expression object, and will be sorted
based on the PC loading. This means you can do some neat stuff like:
new_expn = pca.gene_loading(..., top=50, bot=50)
new_expn.heatmap()
new_expn.boxplot()
"""
PC -= 1 # Pad the PC so that the expected PC is returned rather than the zero-based PC.
if not self.rowwise:
return(self.__row_loading(filename=filename, PC=PC, top=top, bot=bot, label_key=label_key, all=all, **kargs))
else:
return(self.__condition_loading(filename=filename, PC=PC, top=top, bot=bot, label_key=label_key, all=all, **kargs))
def __row_loading(self, filename=None, PC=-1, top=50, bot=50, label_key=None, all=False, **kargs):
"""
Internal handler for loading()
"""
assert not self.rowwise, "loading(): You probably don't mean to use this when rowwise=True"
assert PC >= 0, "loading(): PC of <1 specified"
if "aspect" not in kargs:
kargs["aspect"] = "long"
data = self.__u[:,PC]
labs = self.parent[label_key]
packed_data = [{label_key: i[0], "l": i[1]} for i in zip(labs, data)]
sorted_data = sorted(packed_data, key=itemgetter("l"))
data = [i["l"] for i in sorted_data]
labs = [i[label_key] for i in sorted_data]
if all:
data = data
labs = labs
else:
if bot > 0 and top > 0: # data[-0:] returns the entire list and data[0:0] returns [] !
data = data[0:top] + data[-bot:]
labs = labs[0:top] + labs[-bot:]
elif top > 0:
data = data[0:top]
labs = labs[0:top]
elif bot > 0:
data = data[-bot:]
labs = labs[-bot:]
if filename:
fig = self.__draw.getfigure(**kargs)
ax = fig.add_subplot(111)
ax.set_position([0.3,0.03,0.6,0.96])
x = numpy.arange(len(data))
ax.barh(x-0.4, data, ec="black", color="grey")
ax.set_ylabel("Rows")
ax.set_xlabel("Loading")
ax.set_yticklabels(labs)
ax.set_yticks(x)
ax.set_ylim([-0.5, len(data)-0.5])
[t.set_fontsize(6) for t in ax.get_yticklabels()]
self.__draw.do_common_args(ax, **kargs)
real_filename = self.__draw.savefigure(fig, filename)
config.log.info("loading(): Saved PC loading '%s'" % real_filename)
# work out the list to return
newgl = genelist()
newgl.load_list([{label_key: i[0], "pc_loading": i[1]} for i in zip(labs, data)]) # relist it so that top bot are used
newexpn = newgl.map(genelist=self.parent, key=label_key, greedy=False)
newexpn.sort("pc_loading")
return(newexpn)
def __condition_loading(self, filename=None, PC=-1, top=50, bot=50, label_key=None, all=False, **kargs):
"""
internal alias for loading()
"""
assert self.rowwise, "loading(): You probably don't mean to use this when rowwise=False"
assert PC >= 0, "loading(): PC of <1 specified"
if "aspect" not in kargs:
kargs["aspect"] = "long"
data = self.__u[:,PC]
labs = self.parent._conditions
packed_data = [{label_key: i[0], "l": i[1]} for i in zip(labs, data)]
sorted_data = sorted(packed_data, key=itemgetter("l"))
data = [i["l"] for i in sorted_data]
labs = [i[label_key] for i in sorted_data]
if all:
data = data
labs = labs
else:
if bot > 0 and top > 0: # data[-0:] returns the entire list and data[0:0] returns [] !
data = data[0:top] + data[-bot:]
labs = labs[0:top] + labs[-bot:]
elif top > 0:
data = data[0:top]
labs = labs[0:top]
elif bot > 0:
data = data[-bot:]
labs = labs[-bot:]
if filename:
fig = self.__draw.getfigure(**kargs)
ax = fig.add_subplot(111)
ax.set_position([0.3,0.03,0.6,0.96])
x = numpy.arange(len(data))
ax.barh(x-0.4, data, ec="black", color="grey")
ax.set_ylabel("Columns")
ax.set_xlabel("Loading")
ax.set_yticklabels(labs)
ax.set_yticks(x)
ax.set_ylim([-0.5, len(data)-0.5])
[t.set_fontsize(6) for t in ax.get_yticklabels()]
self.__draw.do_common_args(ax, **kargs)
real_filename = self.__draw.savefigure(fig, filename)
config.log.info("loading(): Saved PC loading '%s'" % real_filename)
# work out the list to return
newgl = genelist()
newgl.load_list([{"name": i[0], "pc_loading": i[1]} for i in zip(labs, data)]) # relist it so that top bot are used
newgl.sort("pc_loading")
return(newgl)
|
[
"mpl_toolkits.mplot3d.Axes3D",
"numpy.allclose",
"numpy.linalg.svd",
"numpy.array",
"numpy.mean",
"numpy.dot",
"operator.itemgetter",
"numpy.diag"
] |
[((1774, 1817), 'numpy.array', 'numpy.array', (['parent.serialisedArrayDataList'], {}), '(parent.serialisedArrayDataList)\n', (1785, 1817), False, 'import numpy\n'), ((3093, 3114), 'numpy.array', 'numpy.array', (['self.__u'], {}), '(self.__u)\n', (3104, 3114), False, 'import numpy\n'), ((4495, 4543), 'numpy.array', 'numpy.array', (['self.parent.serialisedArrayDataList'], {}), '(self.parent.serialisedArrayDataList)\n', (4506, 4543), False, 'import numpy\n'), ((4562, 4609), 'numpy.linalg.svd', 'numpy.linalg.svd', (['matrix.T'], {'full_matrices': '(False)'}), '(matrix.T, full_matrices=False)\n', (4578, 4609), False, 'import numpy\n'), ((4886, 4934), 'numpy.array', 'numpy.array', (['self.parent.serialisedArrayDataList'], {}), '(self.parent.serialisedArrayDataList)\n', (4897, 4934), False, 'import numpy\n'), ((4947, 4960), 'numpy.diag', 'numpy.diag', (['S'], {}), '(S)\n', (4957, 4960), False, 'import numpy\n'), ((5240, 5260), 'numpy.dot', 'numpy.dot', (['matrix', 'S'], {}), '(matrix, S)\n', (5249, 5260), False, 'import numpy\n'), ((24063, 24127), 'mpl_toolkits.mplot3d.Axes3D', 'Axes3D', (['fig'], {'rect': '[0, 0, 0.95, 1]', 'elev': 'elevation', 'azim': 'rotation'}), '(fig, rect=[0, 0, 0.95, 1], elev=elevation, azim=rotation)\n', (24069, 24127), False, 'from mpl_toolkits.mplot3d import Axes3D, art3d\n'), ((2314, 2349), 'numpy.linalg.svd', 'LA.svd', (['matrix'], {'full_matrices': '(False)'}), '(matrix, full_matrices=False)\n', (2320, 2349), True, 'import numpy.linalg as LA\n'), ((2817, 2852), 'numpy.linalg.svd', 'LA.svd', (['matrix'], {'full_matrices': '(False)'}), '(matrix, full_matrices=False)\n', (2823, 2852), True, 'import numpy.linalg as LA\n'), ((5530, 5551), 'numpy.allclose', 'numpy.allclose', (['U', 'pr'], {}), '(U, pr)\n', (5544, 5551), False, 'import numpy\n'), ((2089, 2115), 'numpy.mean', 'numpy.mean', (['matrix'], {'axis': '(0)'}), '(matrix, axis=0)\n', (2099, 2115), False, 'import numpy\n'), ((2592, 2618), 'numpy.mean', 'numpy.mean', (['matrix'], {'axis': '(0)'}), '(matrix, axis=0)\n', (2602, 2618), False, 'import numpy\n'), ((5203, 5218), 'numpy.dot', 'numpy.dot', (['S', 'V'], {}), '(S, V)\n', (5212, 5218), False, 'import numpy\n'), ((7554, 7575), 'numpy.array', 'numpy.array', (['self.__d'], {}), '(self.__d)\n', (7565, 7575), False, 'import numpy\n'), ((9095, 9120), 'numpy.array', 'numpy.array', (['self.__d[1:]'], {}), '(self.__d[1:])\n', (9106, 9120), False, 'import numpy\n'), ((9159, 9180), 'numpy.array', 'numpy.array', (['self.__d'], {}), '(self.__d)\n', (9170, 9180), False, 'import numpy\n'), ((26838, 26853), 'operator.itemgetter', 'itemgetter', (['"""l"""'], {}), "('l')\n", (26848, 26853), False, 'from operator import itemgetter\n'), ((31344, 31359), 'operator.itemgetter', 'itemgetter', (['"""l"""'], {}), "('l')\n", (31354, 31359), False, 'from operator import itemgetter\n'), ((33651, 33666), 'operator.itemgetter', 'itemgetter', (['"""l"""'], {}), "('l')\n", (33661, 33666), False, 'from operator import itemgetter\n'), ((5609, 5624), 'numpy.dot', 'numpy.dot', (['S', 'V'], {}), '(S, V)\n', (5618, 5624), False, 'import numpy\n')]
|
#!/usr/bin/env python
from distutils.util import strtobool
import numpy as np
import argparse
from generic.preprocess_data.extract_img_raw import extract_raw
from generic.data_provider.image_loader import RawImageBuilder
from clevr.data_provider.clevr_dataset import CLEVRDataset
from clevr.data_provider.clevr_batchifier import CLEVRBatchifier
parser = argparse.ArgumentParser('Feature extractor! ')
parser.add_argument("-img_dir", type=str, required=True, help="Input Image folder")
parser.add_argument("-data_dir", type=str, required=True,help="Dataset folder")
parser.add_argument("-out_dir", type=str, required=True, help="Output directory for h5 files")
parser.add_argument("-set_type", type=list, default=["val", "train", "test"], help='Select the dataset to dump')
parser.add_argument("-subtract_mean", type=lambda x:bool(strtobool(x)), default="True", help="Preprocess the image by substracting the mean")
parser.add_argument("-img_size", type=int, required=True, help="image size (pixels)")
parser.add_argument("-gpu_ratio", type=float, default=1., help="How many GPU ram is required? (ratio)")
parser.add_argument("-no_thread", type=int, default=2, help="No thread to load batch")
args = parser.parse_args()
# define image properties
if args.subtract_mean:
channel_mean = np.array([123.68, 116.779, 103.939])
else:
channel_mean = None
source_name = 'image'
image_builder = RawImageBuilder(args.img_dir,
height=args.img_size,
width=args.img_size,
channel=channel_mean)
image_shape=[args.img_size, args.img_size, 3]
extract_raw(
image_shape=image_shape,
dataset_cstor=CLEVRDataset,
dataset_args={"folder": args.data_dir, "year": args.year, "image_builder":image_builder},
batchifier_cstor=CLEVRBatchifier,
source_name=source_name,
out_dir=args.out_dir,
set_type=args.set_type,
no_threads=args.no_thread,
)
|
[
"generic.preprocess_data.extract_img_raw.extract_raw",
"argparse.ArgumentParser",
"distutils.util.strtobool",
"generic.data_provider.image_loader.RawImageBuilder",
"numpy.array"
] |
[((359, 405), 'argparse.ArgumentParser', 'argparse.ArgumentParser', (['"""Feature extractor! """'], {}), "('Feature extractor! ')\n", (382, 405), False, 'import argparse\n'), ((1405, 1503), 'generic.data_provider.image_loader.RawImageBuilder', 'RawImageBuilder', (['args.img_dir'], {'height': 'args.img_size', 'width': 'args.img_size', 'channel': 'channel_mean'}), '(args.img_dir, height=args.img_size, width=args.img_size,\n channel=channel_mean)\n', (1420, 1503), False, 'from generic.data_provider.image_loader import RawImageBuilder\n'), ((1643, 1946), 'generic.preprocess_data.extract_img_raw.extract_raw', 'extract_raw', ([], {'image_shape': 'image_shape', 'dataset_cstor': 'CLEVRDataset', 'dataset_args': "{'folder': args.data_dir, 'year': args.year, 'image_builder': image_builder}", 'batchifier_cstor': 'CLEVRBatchifier', 'source_name': 'source_name', 'out_dir': 'args.out_dir', 'set_type': 'args.set_type', 'no_threads': 'args.no_thread'}), "(image_shape=image_shape, dataset_cstor=CLEVRDataset,\n dataset_args={'folder': args.data_dir, 'year': args.year,\n 'image_builder': image_builder}, batchifier_cstor=CLEVRBatchifier,\n source_name=source_name, out_dir=args.out_dir, set_type=args.set_type,\n no_threads=args.no_thread)\n", (1654, 1946), False, 'from generic.preprocess_data.extract_img_raw import extract_raw\n'), ((1299, 1335), 'numpy.array', 'np.array', (['[123.68, 116.779, 103.939]'], {}), '([123.68, 116.779, 103.939])\n', (1307, 1335), True, 'import numpy as np\n'), ((837, 849), 'distutils.util.strtobool', 'strtobool', (['x'], {}), '(x)\n', (846, 849), False, 'from distutils.util import strtobool\n')]
|
"""基本的な VAE を提供するモジュール.
Notes:
- reference:
`https://github.com/bhpfelix/Variational-Autoencoder-PyTorch/blob/master/src/vanila_vae.py`
"""
# default packages
import logging
import typing as t
# third party packages
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
# logger
logger = logging.getLogger(__name__)
class CBA2d(nn.Module):
def __init__(
self,
in_channels: int,
out_channels: int,
kernel_size: t.Union[int, t.Tuple[int, int]],
stride: t.Union[int, t.Tuple[int, int]] = 1,
padding: t.Union[int, t.Tuple[int, int]] = 0,
dilation: t.Union[int, t.Tuple[int, int]] = 1,
groups: int = 1,
bias: bool = True,
padding_mode: str = "reflect",
use_activation: bool = True,
):
super(CBA2d, self).__init__()
self.conv = nn.Sequential(
nn.Conv2d(
in_channels,
out_channels,
kernel_size,
stride=stride,
padding=padding,
dilation=dilation,
groups=groups,
bias=bias,
padding_mode=padding_mode,
),
nn.BatchNorm2d(out_channels),
)
if use_activation:
self.conv.add_module("Act", nn.LeakyReLU(inplace=True))
def forward(self, x):
return self.conv(x)
class VAE(nn.Module):
def __init__(
self, in_channels: int, out_channels: int, image_size: t.Tuple[int, int]
) -> None:
super(VAE, self).__init__()
self.channels = np.array([32, 64, 128, 256, 512])
self.image_size = image_size
self.down_ratio = 2 ** 5
self.encoded_size = (
self.image_size[0] // self.down_ratio,
self.image_size[1] // self.down_ratio,
)
self.encoded_dim = (
self.encoded_size[0] * self.encoded_size[1] * self.channels[-1]
)
self.latent_dim = 512
self.encoder = nn.Sequential(
CBA2d(in_channels, self.channels[0], (3, 3), stride=2, padding=1),
CBA2d(self.channels[0], self.channels[1], (3, 3), stride=2, padding=1),
CBA2d(self.channels[1], self.channels[2], (3, 3), stride=2, padding=1),
CBA2d(self.channels[2], self.channels[3], (3, 3), stride=2, padding=1),
CBA2d(self.channels[3], self.channels[4], (3, 3), stride=2, padding=1),
)
self.fc_mean = nn.Linear(self.encoded_dim, self.latent_dim)
self.fc_logvar = nn.Linear(self.encoded_dim, self.latent_dim)
self.decode_input = nn.Linear(self.latent_dim, self.encoded_dim)
self.decoder = nn.Sequential(
nn.UpsamplingNearest2d(scale_factor=2),
CBA2d(self.channels[4], self.channels[3], (3, 3), padding=1),
nn.UpsamplingNearest2d(scale_factor=2),
CBA2d(self.channels[3], self.channels[2], (3, 3), padding=1),
nn.UpsamplingNearest2d(scale_factor=2),
CBA2d(self.channels[2], self.channels[1], (3, 3), padding=1),
nn.UpsamplingNearest2d(scale_factor=2),
CBA2d(self.channels[1], self.channels[0], (3, 3), padding=1),
)
self.decode_final = nn.Sequential(
nn.UpsamplingNearest2d(scale_factor=2),
CBA2d(self.channels[0], self.channels[0], (3, 3), padding=1),
CBA2d(self.channels[0], out_channels, (3, 3), padding=1),
nn.Tanh(),
)
def decode(self, z):
decoded = self.decode_input(z)
decoded = decoded.view(
-1, self.channels[-1], self.encoded_size[0], self.encoded_size[1]
)
decoded = self.decoder(decoded)
decoded = self.decode_final(decoded)
return decoded
def encode(self, x):
code = self.encoder(x)
code = code.view(-1, self.encoded_dim)
mean = self.fc_mean(code)
logvar = self.fc_logvar(code)
return mean, logvar
def forward(self, x):
mean, logvar = self.encode(x)
z = self.reparametrize(mean, logvar)
decoded = self.decode(z)
return decoded, mean, logvar
def reparametrize(self, mean, logvar):
std = torch.exp(0.5 * logvar)
eps = torch.randn_like(std)
z = mean + eps * std
return z
@classmethod
def loss_function(cls, x, decode, mean, logvar):
coef_kl_loss = 8e-4 # batch_size / (train or valid image_num)
reconstruct_loss = F.mse_loss(decode, x)
kl_loss = torch.mean(
-0.5 * torch.sum(1 + logvar - mean ** 2 - logvar.exp(), dim=1), dim=0
)
loss = reconstruct_loss + coef_kl_loss * kl_loss
return loss
|
[
"torch.nn.UpsamplingNearest2d",
"torch.randn_like",
"torch.nn.Tanh",
"torch.nn.functional.mse_loss",
"torch.nn.Conv2d",
"torch.exp",
"torch.nn.BatchNorm2d",
"numpy.array",
"torch.nn.Linear",
"torch.nn.LeakyReLU",
"logging.getLogger"
] |
[((335, 362), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (352, 362), False, 'import logging\n'), ((1624, 1657), 'numpy.array', 'np.array', (['[32, 64, 128, 256, 512]'], {}), '([32, 64, 128, 256, 512])\n', (1632, 1657), True, 'import numpy as np\n'), ((2502, 2546), 'torch.nn.Linear', 'nn.Linear', (['self.encoded_dim', 'self.latent_dim'], {}), '(self.encoded_dim, self.latent_dim)\n', (2511, 2546), True, 'import torch.nn as nn\n'), ((2572, 2616), 'torch.nn.Linear', 'nn.Linear', (['self.encoded_dim', 'self.latent_dim'], {}), '(self.encoded_dim, self.latent_dim)\n', (2581, 2616), True, 'import torch.nn as nn\n'), ((2646, 2690), 'torch.nn.Linear', 'nn.Linear', (['self.latent_dim', 'self.encoded_dim'], {}), '(self.latent_dim, self.encoded_dim)\n', (2655, 2690), True, 'import torch.nn as nn\n'), ((4253, 4276), 'torch.exp', 'torch.exp', (['(0.5 * logvar)'], {}), '(0.5 * logvar)\n', (4262, 4276), False, 'import torch\n'), ((4291, 4312), 'torch.randn_like', 'torch.randn_like', (['std'], {}), '(std)\n', (4307, 4312), False, 'import torch\n'), ((4530, 4551), 'torch.nn.functional.mse_loss', 'F.mse_loss', (['decode', 'x'], {}), '(decode, x)\n', (4540, 4551), True, 'import torch.nn.functional as F\n'), ((910, 1073), 'torch.nn.Conv2d', 'nn.Conv2d', (['in_channels', 'out_channels', 'kernel_size'], {'stride': 'stride', 'padding': 'padding', 'dilation': 'dilation', 'groups': 'groups', 'bias': 'bias', 'padding_mode': 'padding_mode'}), '(in_channels, out_channels, kernel_size, stride=stride, padding=\n padding, dilation=dilation, groups=groups, bias=bias, padding_mode=\n padding_mode)\n', (919, 1073), True, 'import torch.nn as nn\n'), ((1236, 1264), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['out_channels'], {}), '(out_channels)\n', (1250, 1264), True, 'import torch.nn as nn\n'), ((2741, 2779), 'torch.nn.UpsamplingNearest2d', 'nn.UpsamplingNearest2d', ([], {'scale_factor': '(2)'}), '(scale_factor=2)\n', (2763, 2779), True, 'import torch.nn as nn\n'), ((2867, 2905), 'torch.nn.UpsamplingNearest2d', 'nn.UpsamplingNearest2d', ([], {'scale_factor': '(2)'}), '(scale_factor=2)\n', (2889, 2905), True, 'import torch.nn as nn\n'), ((2993, 3031), 'torch.nn.UpsamplingNearest2d', 'nn.UpsamplingNearest2d', ([], {'scale_factor': '(2)'}), '(scale_factor=2)\n', (3015, 3031), True, 'import torch.nn as nn\n'), ((3119, 3157), 'torch.nn.UpsamplingNearest2d', 'nn.UpsamplingNearest2d', ([], {'scale_factor': '(2)'}), '(scale_factor=2)\n', (3141, 3157), True, 'import torch.nn as nn\n'), ((3298, 3336), 'torch.nn.UpsamplingNearest2d', 'nn.UpsamplingNearest2d', ([], {'scale_factor': '(2)'}), '(scale_factor=2)\n', (3320, 3336), True, 'import torch.nn as nn\n'), ((3494, 3503), 'torch.nn.Tanh', 'nn.Tanh', ([], {}), '()\n', (3501, 3503), True, 'import torch.nn as nn\n'), ((1343, 1369), 'torch.nn.LeakyReLU', 'nn.LeakyReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (1355, 1369), True, 'import torch.nn as nn\n')]
|
import torch
import copy
import scipy.stats
import numpy as np
from collections import OrderedDict
from tqdm import trange
from torch import nn
from utils import initiate_model
class ProtoTrainer:
"""Trainer module for MAML
"""
def __init__(self, args, model, device):
"""Initiate MAML trainer
Args:
model: model instance used for meta-learning
args: arguments entered by the user
"""
self.N = args.n_way
self.K = args.k_spt
self.Q = args.k_qry
self.Nt = args.n_way_test
self.Kt = args.k_spt_test
self.Qt = args.k_qry_test
self.num_train_points = args.num_train_points
self.num_test_points = args.num_test_points
self.dot = args.dot
self.device = device
self.model = initiate_model(model, self.device)
self.criterion = torch.nn.CrossEntropyLoss()
self.lr = args.lr
"""
def __dist__(self, x, y, dim):
if self.dot:
return -(x * y).sum(dim)
else:
return torch.pow(x - y, 2).sum(dim)
def __batch_dist__(self, P, Q):
return self.__dist__(P.unsqueeze(0), Q.unsqueeze(1), 2)
"""
def __batch_dist__(self, P, Q):
if self.dot:
P_norm = P / P.norm(dim=1)[:, None]
Q_norm = Q / Q.norm(dim=1)[:, None]
cos_sim = torch.mm(Q_norm, P_norm.transpose(0, 1))
return 1. - cos_sim
else:
return torch.cdist(Q.unsqueeze(0), P.unsqueeze(0), p=2).squeeze()
def __get_proto__(self, x, y, n_way):
proto = []
for label in range(n_way):
proto.append(torch.mean(x[y==label], 0))
proto = torch.stack(proto)
return proto
def train_step(self, dataloader, adjust_lr=False):
"""Method for meta-training
Args:
dataloader: torch.utils.data.DataLoader object to sample support & query sets from
adjust_lr: adjustr learning rate (True/False)
Returns:
te_losses_total: average losses on query set
te_losses_ci: 95% confidence interval lof losses on query set
te_accs_total: average accuracies on query set
te_accs_ci: 95% confidence interval lof accuracies on query set
"""
# adjust learning rate
if adjust_lr:
self.lr *= 0.5
# declare optimizer
optimizer = torch.optim.Adam(self.model.parameters(), lr=self.lr)
# iterative updates
for _ in trange(self.num_train_points, desc='[INFO] Meta-training', leave=False):
te_losses, te_accs = 0.0, 0.0
# get dataset
Sx, Sy, Qx, Qy = next(iter(dataloader))
Sx, Sy = Sx.to(self.device).view(self.N * self.K, *Sx.shape[2:]), Sy.to(self.device).view(-1, 1).squeeze()
Qx, Qy = Qx.to(self.device).view(self.N * self.Q, *Qx.shape[2:]), Qy.to(self.device).view(-1, 1).squeeze()
# make latent vectors
Sx = self.model(Sx)
Qx = self.model(Qx)
# get prototypes
S_proto = self.__get_proto__(Sx, Sy, self.N) # n_way x latent_dim
# get loss on adapted parameter to new tasks (with computational graph attached)
Qy_hat = (-self.__batch_dist__(S_proto, Qx))
te_loss = self.criterion(Qy_hat, Qy)
# update
optimizer.zero_grad()
te_loss.backward()
optimizer.step()
else:
# get metric and loss
te_losses += te_loss.item()
# get correct counts
predicted = Qy_hat.argmax(dim=1, keepdim=True)
te_accs += predicted.eq(Qy.view_as(predicted)).sum().item()
# update metrics for epoch
te_losses /= self.N * self.Q
te_accs /= self.N * self.Q
return te_losses, te_accs
def eval_step(self, dataloader, mode='val'):
"""Method for meta-testing
Args:
dataloader: torch.utils.data.DataLoader object to sample support & query sets from
mode: 'val'/'test'
Returns:
te_losses_total: average losses on query set
te_losses_ci: 95% confidence interval lof losses on query set
te_accs_total: average accuracies on query set
te_accs_ci: 95% confidence interval lof accuracies on query set
"""
# define new model for meta-test
meta_tester = copy.deepcopy(self.model)
# track losses and metrics
te_losses_total, te_accs_total = [], []
# iterative updates
for _ in trange(self.num_train_points if mode=='val' else self.num_test_points, desc='[INFO] Meta-validation' if mode=='val' else '[INFO] Meta-test', leave=False):
# track loss and metric per episode
te_losses, te_accs = 0.0, 0.0
# get dataset
Sx, Sy, Qx, Qy = next(iter(dataloader))
Sx, Sy = Sx.to(self.device).view(self.Nt * self.Kt, *Sx.shape[2:]), Sy.to(self.device).view(-1, 1).squeeze()
Qx, Qy = Qx.to(self.device).view(self.Nt * self.Qt, *Qx.shape[2:]), Qy.to(self.device).view(-1, 1).squeeze()
# make latent vectors
Sx = meta_tester(Sx)
Qx = meta_tester(Qx)
# get prototypes
S_proto = self.__get_proto__(Sx, Sy, self.Nt) # n_way x latent_dim
# get loss on adapted parameter to new tasks (with computational graph attached)
Qy_hat = (-self.__batch_dist__(S_proto, Qx))
te_loss = self.criterion(Qy_hat, Qy)
# get metric and loss
te_losses += te_loss.item()
# get correct counts
predicted = Qy_hat.argmax(dim=1, keepdim=True)
te_accs += predicted.eq(Qy.view_as(predicted)).sum().item()
# update metrics for epoch
te_losses /= self.Nt * self.Qt
te_accs /= self.Nt * self.Qt
te_losses_total.append(te_losses)
te_accs_total.append(te_accs)
else:
# update metrics for epoch
te_losses_mean = np.asarray(te_losses_total).mean()
te_accs_mean = np.asarray(te_accs_total).mean()
# calculate CI constant for collected losses
te_losses_ci = np.asarray(te_losses_total).std() * np.abs(scipy.stats.t.ppf((1. - 0.95) / 2, len(te_losses_total) - 1)) / np.sqrt(len(te_losses_total))
# calculate CI constant for accuracies
te_accs_ci = np.asarray(te_accs_total).std() * np.abs(scipy.stats.t.ppf((1. - 0.95) / 2, len(te_accs_total) - 1)) / np.sqrt(len(te_accs_total))
return te_losses_mean, te_losses_ci, te_accs_mean, te_accs_ci
|
[
"torch.mean",
"copy.deepcopy",
"torch.stack",
"tqdm.trange",
"numpy.asarray",
"torch.nn.CrossEntropyLoss",
"utils.initiate_model"
] |
[((847, 881), 'utils.initiate_model', 'initiate_model', (['model', 'self.device'], {}), '(model, self.device)\n', (861, 881), False, 'from utils import initiate_model\n'), ((907, 934), 'torch.nn.CrossEntropyLoss', 'torch.nn.CrossEntropyLoss', ([], {}), '()\n', (932, 934), False, 'import torch\n'), ((1761, 1779), 'torch.stack', 'torch.stack', (['proto'], {}), '(proto)\n', (1772, 1779), False, 'import torch\n'), ((2630, 2701), 'tqdm.trange', 'trange', (['self.num_train_points'], {'desc': '"""[INFO] Meta-training"""', 'leave': '(False)'}), "(self.num_train_points, desc='[INFO] Meta-training', leave=False)\n", (2636, 2701), False, 'from tqdm import trange\n'), ((4613, 4638), 'copy.deepcopy', 'copy.deepcopy', (['self.model'], {}), '(self.model)\n', (4626, 4638), False, 'import copy\n'), ((4785, 4950), 'tqdm.trange', 'trange', (["(self.num_train_points if mode == 'val' else self.num_test_points)"], {'desc': "('[INFO] Meta-validation' if mode == 'val' else '[INFO] Meta-test')", 'leave': '(False)'}), "(self.num_train_points if mode == 'val' else self.num_test_points,\n desc='[INFO] Meta-validation' if mode == 'val' else '[INFO] Meta-test',\n leave=False)\n", (4791, 4950), False, 'from tqdm import trange\n'), ((1717, 1745), 'torch.mean', 'torch.mean', (['x[y == label]', '(0)'], {}), '(x[y == label], 0)\n', (1727, 1745), False, 'import torch\n'), ((6334, 6361), 'numpy.asarray', 'np.asarray', (['te_losses_total'], {}), '(te_losses_total)\n', (6344, 6361), True, 'import numpy as np\n'), ((6396, 6421), 'numpy.asarray', 'np.asarray', (['te_accs_total'], {}), '(te_accs_total)\n', (6406, 6421), True, 'import numpy as np\n'), ((6514, 6541), 'numpy.asarray', 'np.asarray', (['te_losses_total'], {}), '(te_losses_total)\n', (6524, 6541), True, 'import numpy as np\n'), ((6728, 6753), 'numpy.asarray', 'np.asarray', (['te_accs_total'], {}), '(te_accs_total)\n', (6738, 6753), True, 'import numpy as np\n')]
|
# ***************************************************************
# Copyright (c) 2020 Jittor. Authors: <NAME> <<EMAIL>>. All Rights Reserved.
# This file is subject to the terms and conditions defined in
# file 'LICENSE.txt', which is part of this source code package.
# ***************************************************************
import unittest
import jittor as jt
import numpy as np
class TestWhereOp(unittest.TestCase):
def test(self):
assert (jt.where([0,1,0,1])[0].data == [1,3]).all()
a, = jt.where([0,1,0,1])
assert a.uncertain_shape==[-4]
a.data
assert a.uncertain_shape==[2]
a,b = jt.where([[0,0,1],[1,0,0]])
assert (a.data==[0,1]).all() and (b.data==[2,0]).all()
def test_reindex_dep(self):
a = jt.random([10])
b, = (a>1).where()
assert len(b.data)==0
b, = (a>0.5).where()
assert (b.data==np.where(a.data>0.5)).all()
b = a.reindex_var((a>0.5).where())
assert (b.data==a.data[a.data>0.5]).all()
def test_binary_dep(self):
a = jt.random([10])
b, = (a>0.5).where()
b = b+1
assert (b.data==np.where(a.data>0.5)[0]+1).all()
b, = (a>1).where()
b = b+1
assert (b.data==np.where(a.data>1)[0]+1).all()
def test_self_dep(self):
a = jt.random([100])
x = a.reindex_var((a>0.1).where())
x = x.reindex_var((x<0.9).where())
na = a.data
assert (na[np.logical_and(na>0.1, na<0.9)]==x.data).all()
def test_reduce_dep(self):
a = jt.random([100,100])
index = (a>0.5).where()
x = a.reindex_var(index)
xsum =x.sum()
na = a.data
assert np.allclose(np.sum(na[na>0.5]),xsum.data), (x.data, xsum.data, np.sum(na[na>0.5]))
def test_doc(self):
assert "Where Operator" in jt.where.__doc__
if __name__ == "__main__":
unittest.main()
|
[
"unittest.main",
"numpy.sum",
"numpy.logical_and",
"jittor.random",
"numpy.where",
"jittor.where"
] |
[((1910, 1925), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1923, 1925), False, 'import unittest\n'), ((523, 545), 'jittor.where', 'jt.where', (['[0, 1, 0, 1]'], {}), '([0, 1, 0, 1])\n', (531, 545), True, 'import jittor as jt\n'), ((649, 681), 'jittor.where', 'jt.where', (['[[0, 0, 1], [1, 0, 0]]'], {}), '([[0, 0, 1], [1, 0, 0]])\n', (657, 681), True, 'import jittor as jt\n'), ((785, 800), 'jittor.random', 'jt.random', (['[10]'], {}), '([10])\n', (794, 800), True, 'import jittor as jt\n'), ((1076, 1091), 'jittor.random', 'jt.random', (['[10]'], {}), '([10])\n', (1085, 1091), True, 'import jittor as jt\n'), ((1334, 1350), 'jittor.random', 'jt.random', (['[100]'], {}), '([100])\n', (1343, 1350), True, 'import jittor as jt\n'), ((1567, 1588), 'jittor.random', 'jt.random', (['[100, 100]'], {}), '([100, 100])\n', (1576, 1588), True, 'import jittor as jt\n'), ((1722, 1742), 'numpy.sum', 'np.sum', (['na[na > 0.5]'], {}), '(na[na > 0.5])\n', (1728, 1742), True, 'import numpy as np\n'), ((1773, 1793), 'numpy.sum', 'np.sum', (['na[na > 0.5]'], {}), '(na[na > 0.5])\n', (1779, 1793), True, 'import numpy as np\n'), ((911, 933), 'numpy.where', 'np.where', (['(a.data > 0.5)'], {}), '(a.data > 0.5)\n', (919, 933), True, 'import numpy as np\n'), ((1476, 1510), 'numpy.logical_and', 'np.logical_and', (['(na > 0.1)', '(na < 0.9)'], {}), '(na > 0.1, na < 0.9)\n', (1490, 1510), True, 'import numpy as np\n'), ((466, 488), 'jittor.where', 'jt.where', (['[0, 1, 0, 1]'], {}), '([0, 1, 0, 1])\n', (474, 488), True, 'import jittor as jt\n'), ((1161, 1183), 'numpy.where', 'np.where', (['(a.data > 0.5)'], {}), '(a.data > 0.5)\n', (1169, 1183), True, 'import numpy as np\n'), ((1261, 1281), 'numpy.where', 'np.where', (['(a.data > 1)'], {}), '(a.data > 1)\n', (1269, 1281), True, 'import numpy as np\n')]
|
# encoding=utf-8
import numpy as np
from sklearn import preprocessing
from src.config import feature_list
from src.feature.iku import spell_error, Mean_sentence_depth_level, essay_length
from src.feature.wangdq import word_vector_similarity_train, word_vector_similarity_test, \
mean_clause, pos_gram_train, pos_gram_test, good_pos_ngrams, vocab_size, pos_tagger, pos_tagger2
from src.feature.xiaoyl import word_length, get_sentence_length, word_bigram_train, word_bigram_test, \
word_trigram_train, word_trigram_test, bag_of_words_train, bag_of_words_test
from util.util import pos_tagging
class Feature:
def __init__(self):
self.wv_idf_diag = None
self.wv_tf_vocab = None
self.wv_tfidf = None
self.word_bigram_TF = None
self.word_bigram_tf_vocab = None
self.word_trigram_TF = None
self.word_trigram_tf_vocab = None
self.bag_of_words_tf_vocab = None
self.bag_of_words_TF = None
self.pos_3tf_vocab = None
self.pos_3TF = None
self.pos_2tf_vocab = None
self.pos_2TF = None
self.normalizer = None
self.tagged_data = None
def get_tagged_data(self, tokens_set):
""" 省时间啦 """
if self.tagged_data is None:
self.tagged_data = pos_tagging(tokens_set)
return self.tagged_data
@staticmethod
def get_instance(feature):
""" 从dataset中构建dataset
feature: {} """
feature_class = Feature()
feature_class.wv_idf_diag = feature.get('wv_idf_diag', None)
feature_class.wv_tf_vocab = feature.get('wv_tf_vocab', None)
feature_class.wv_tfidf = feature.get('wv_tfidf', None)
feature_class.pos_2tf_vocab = feature.get('pos_2tf_vocab', None)
feature_class.pos_2TF = feature.get('pos_2TF', None)
feature_class.pos_3tf_vocab = feature.get('pos_3tf_vocab', None)
feature_class.pos_3TF = feature.get('pos_3TF', None)
feature_class.word_bigram_tf_vocab = feature.get('word_bigram_tf_vocab', None)
feature_class.word_bigram_TF = feature.get('word_bigram_TF', None)
feature_class.word_trigram_tf_vocab = feature.get('word_trigram_tf_vocab', None)
feature_class.word_trigram_TF = feature.get('word_trigram_TF', None)
feature_class.bag_of_words_tf_vocab = feature.get('bag_of_words_tf_vocab', None)
feature_class.bag_of_words_TF = feature.get('bag_of_word_TF', None)
return feature_class
def concatenate_feature(self, feature, new_feature):
if new_feature is None:
return feature
if feature is None:
return new_feature
else:
return np.concatenate((feature, new_feature), axis=1)
def get_feature_by_name(self, feature_dict, feature_name, sentences_set, token_set, train_data, train_score,
name='train'):
if 'mean_word_length' == feature_name:
mean_word_length, var_word_length = word_length(token_set)
feature_dict.update({
"mean_word_length": mean_word_length,
"var_word_length": var_word_length
})
return mean_word_length
if 'var_word_length' == feature_name:
mean_word_length, var_word_length = word_length(token_set)
feature_dict.update({
"mean_word_length": mean_word_length,
"var_word_length": var_word_length
})
return var_word_length
if 'mean_clause_length' == feature_name:
mean_clause_length, mean_clause_number, mean_sentence_depth, mean_sentence_level = mean_clause(
sentences_set)
feature_dict.update({
"mean_clause_length": mean_clause_length,
"mean_clause_number": mean_clause_number,
"mean_sentence_depth": mean_sentence_depth,
"mean_sentence_level": mean_sentence_level
})
return mean_clause_length
if 'mean_clause_number' == feature_name:
mean_clause_length, mean_clause_number, mean_sentence_depth, mean_sentence_level = mean_clause(
sentences_set)
feature_dict.update({
"mean_clause_length": mean_clause_length,
"mean_clause_number": mean_clause_number,
"mean_sentence_depth": mean_sentence_depth,
"mean_sentence_level": mean_sentence_level
})
return mean_clause_number
if 'mean_sentence_length' == feature_name:
mean_sentence_length, var_sentence_length = get_sentence_length(sentences_set)
feature_dict.update({
"mean_sentence_length": mean_sentence_length,
"var_sentence_length": var_sentence_length
})
return mean_sentence_length
if 'var_sentence_length' == feature_name:
mean_sentence_length, var_sentence_length = get_sentence_length(sentences_set)
feature_dict.update({
"mean_sentence_length": mean_sentence_length,
"var_sentence_length": var_sentence_length
})
return var_sentence_length
if 'spell_error' == feature_name:
error = spell_error(train_data)
feature_dict.update({
"spell_error": error
})
return error
if 'mean_sentence_depth' == feature_name:
mean_clause_length, mean_clause_number, mean_sentence_depth, mean_sentence_level = mean_clause(
sentences_set)
feature_dict.update({
"mean_clause_length": mean_clause_length,
"mean_clause_number": mean_clause_number,
"mean_sentence_depth": mean_sentence_depth,
"mean_sentence_level": mean_sentence_level
})
return mean_sentence_depth
if 'mean_sentence_level' == feature_name:
mean_clause_length, mean_clause_number, mean_sentence_depth, mean_sentence_level = mean_clause(
sentences_set)
feature_dict.update({
"mean_clause_length": mean_clause_length,
"mean_clause_number": mean_clause_number,
"mean_sentence_depth": mean_sentence_depth,
"mean_sentence_level": mean_sentence_level
})
return mean_sentence_level
if 'essay_length' == feature_name:
length = essay_length(train_data)
feature_dict.update({
"essay_length": length,
})
return length
if 'current_pos' == feature_name:
current_pos, error_pos = good_pos_ngrams(self.get_tagged_data(token_set), gram=2)
feature_dict.update({
"current_pos": current_pos,
"error_pos": error_pos
})
return current_pos
if 'error_pos' == feature_name:
current_pos, error_pos = good_pos_ngrams(self.get_tagged_data(token_set), gram=2)
feature_dict.update({
"current_pos": current_pos,
"error_pos": error_pos
})
return error_pos
if 'current_pos3' == feature_name:
current_pos3, error_pos3 = good_pos_ngrams(self.get_tagged_data(token_set), gram=3)
feature_dict.update({
"current_pos3": current_pos3,
"error_pos3": error_pos3
})
return current_pos3
if 'error_pos3' == feature_name:
current_pos3, error_pos3 = good_pos_ngrams(self.get_tagged_data(token_set), gram=3)
feature_dict.update({
"current_pos3": current_pos3,
"error_pos3": error_pos3
})
return error_pos3
if 'vocab_size' == feature_name:
vocab_len, unique_size = vocab_size(token_set)
feature_dict.update({
"vocab_size": vocab_len,
"unique_size": unique_size
})
return vocab_len
if 'unique_size' == feature_name:
vocab_len, unique_size = vocab_size(token_set)
feature_dict.update({
"vocab_size": vocab_len,
"unique_size": unique_size
})
return unique_size
if feature_name in ["PRP_result", "MD_result", "NNP_result", "COMMA_result", "JJ_result", "JJS_result",
"JJR_result", "RB_result", "RBR_result", "RBS_result", "PDT_result", "NN_result"]:
label = feature_name[:-7]
feature_value = pos_tagger(self.get_tagged_data(token_set), label)
feature_dict.update({
feature_name: feature_value
})
return feature_value
if feature_name in ['RB_JJ', 'JJR_NN', 'JJS_NNPS', 'RB_VB', 'RB_RB']:
feature_value = pos_tagger2(self.get_tagged_data(token_set), feature_name)
feature_dict.update({
feature_name: feature_value
})
return feature_value
if 'wv_similarity' == feature_name:
if name == 'train':
wv_similarity, self.wv_tf_vocab, self.wv_idf_diag, self.wv_tfidf = word_vector_similarity_train(
token_set, train_score)
else:
wv_similarity = word_vector_similarity_test(token_set, train_score, self.wv_tf_vocab,
self.wv_idf_diag, self.wv_tfidf)
feature_dict.update({
"wv_similarity": wv_similarity
})
return wv_similarity
if 'pos_bigram' == feature_name:
if name == 'train':
pos_bigram, self.pos_2TF, self.pos_2tf_vocab = pos_gram_train(self.get_tagged_data(token_set), 2)
else:
pos_bigram = pos_gram_test(self.get_tagged_data(token_set), self.pos_2TF, self.pos_2tf_vocab, 2)
feature_dict.update({
"pos_bigram": pos_bigram
})
return pos_bigram
if 'pos_trigram' == feature_name:
if name == 'train':
pos_trigram, self.pos_3TF, self.pos_3tf_vocab = pos_gram_train(self.get_tagged_data(token_set), 3)
else:
pos_trigram = pos_gram_test(self.get_tagged_data(token_set), self.pos_3TF, self.pos_3tf_vocab, 3)
feature_dict.update({
"pos_trigram": pos_trigram
})
return pos_trigram
if 'word_bigram' == feature_name:
if name == 'train':
word_bigram, self.word_bigram_TF, self.word_bigram_tf_vocab = word_bigram_train(token_set)
else:
word_bigram = word_bigram_test(token_set, self.word_bigram_TF, self.word_bigram_tf_vocab)
feature_dict.update({
"word_bigram": word_bigram
})
return word_bigram
if 'word_trigram' == feature_name:
if name == 'train':
word_trigram, self.word_trigram_TF, self.word_trigram_tf_vocab = word_trigram_train(token_set)
else:
word_trigram = word_trigram_test(token_set, self.word_trigram_TF, self.word_trigram_tf_vocab)
feature_dict.update({
"word_trigram": word_trigram
})
return word_trigram
if 'semantic_vector_similarity' == feature_name:
assert False, u'这个特征没用呀,还没实现'
if 'bag_of_words' == feature_name:
if name == 'train':
bag_of_words, self.bag_of_words_TF, self.bag_of_words_tf_vocab = bag_of_words_train(token_set)
else:
bag_of_words = bag_of_words_test(token_set, self.bag_of_words_TF, self.bag_of_words_tf_vocab)
feature_dict.update({
"bag_of_words": bag_of_words
})
return bag_of_words
def get_saved_feature_all(self, feature_dict, sentences_list, tokens_list, train_data, train_score, name='train',
reset_list=[]):
feature = None
self.tagged_data = None
for feature_name in feature_list:
feature_value = feature_dict.get(feature_name, None)
if feature_value is None or feature_name in reset_list:
# 重新计算
feature_value = self.get_feature_by_name(feature_dict, feature_name, sentences_list,
tokens_list, train_data, train_score, name)
assert feature_value is not None, u"feature不能为none呀"
feature = self.concatenate_feature(feature, feature_value)
if name == 'train':
self.normalizer = preprocessing.StandardScaler().fit(feature)
feature = self.normalizer.transform(feature)
else:
feature = self.normalizer.transform(feature)
print("feature.shape = ", feature.shape)
return feature, feature_dict
|
[
"util.util.pos_tagging",
"src.feature.xiaoyl.bag_of_words_train",
"src.feature.wangdq.vocab_size",
"sklearn.preprocessing.StandardScaler",
"src.feature.xiaoyl.word_bigram_test",
"src.feature.xiaoyl.get_sentence_length",
"src.feature.wangdq.mean_clause",
"src.feature.xiaoyl.word_length",
"src.feature.xiaoyl.word_trigram_test",
"src.feature.wangdq.word_vector_similarity_train",
"src.feature.iku.essay_length",
"src.feature.xiaoyl.word_bigram_train",
"src.feature.iku.spell_error",
"src.feature.xiaoyl.word_trigram_train",
"src.feature.wangdq.word_vector_similarity_test",
"src.feature.xiaoyl.bag_of_words_test",
"numpy.concatenate"
] |
[((1294, 1317), 'util.util.pos_tagging', 'pos_tagging', (['tokens_set'], {}), '(tokens_set)\n', (1305, 1317), False, 'from util.util import pos_tagging\n'), ((2696, 2742), 'numpy.concatenate', 'np.concatenate', (['(feature, new_feature)'], {'axis': '(1)'}), '((feature, new_feature), axis=1)\n', (2710, 2742), True, 'import numpy as np\n'), ((2996, 3018), 'src.feature.xiaoyl.word_length', 'word_length', (['token_set'], {}), '(token_set)\n', (3007, 3018), False, 'from src.feature.xiaoyl import word_length, get_sentence_length, word_bigram_train, word_bigram_test, word_trigram_train, word_trigram_test, bag_of_words_train, bag_of_words_test\n'), ((3304, 3326), 'src.feature.xiaoyl.word_length', 'word_length', (['token_set'], {}), '(token_set)\n', (3315, 3326), False, 'from src.feature.xiaoyl import word_length, get_sentence_length, word_bigram_train, word_bigram_test, word_trigram_train, word_trigram_test, bag_of_words_train, bag_of_words_test\n'), ((3661, 3687), 'src.feature.wangdq.mean_clause', 'mean_clause', (['sentences_set'], {}), '(sentences_set)\n', (3672, 3687), False, 'from src.feature.wangdq import word_vector_similarity_train, word_vector_similarity_test, mean_clause, pos_gram_train, pos_gram_test, good_pos_ngrams, vocab_size, pos_tagger, pos_tagger2\n'), ((4172, 4198), 'src.feature.wangdq.mean_clause', 'mean_clause', (['sentences_set'], {}), '(sentences_set)\n', (4183, 4198), False, 'from src.feature.wangdq import word_vector_similarity_train, word_vector_similarity_test, mean_clause, pos_gram_train, pos_gram_test, good_pos_ngrams, vocab_size, pos_tagger, pos_tagger2\n'), ((4646, 4680), 'src.feature.xiaoyl.get_sentence_length', 'get_sentence_length', (['sentences_set'], {}), '(sentences_set)\n', (4665, 4680), False, 'from src.feature.xiaoyl import word_length, get_sentence_length, word_bigram_train, word_bigram_test, word_trigram_train, word_trigram_test, bag_of_words_train, bag_of_words_test\n'), ((4998, 5032), 'src.feature.xiaoyl.get_sentence_length', 'get_sentence_length', (['sentences_set'], {}), '(sentences_set)\n', (5017, 5032), False, 'from src.feature.xiaoyl import word_length, get_sentence_length, word_bigram_train, word_bigram_test, word_trigram_train, word_trigram_test, bag_of_words_train, bag_of_words_test\n'), ((5305, 5328), 'src.feature.iku.spell_error', 'spell_error', (['train_data'], {}), '(train_data)\n', (5316, 5328), False, 'from src.feature.iku import spell_error, Mean_sentence_depth_level, essay_length\n'), ((5586, 5612), 'src.feature.wangdq.mean_clause', 'mean_clause', (['sentences_set'], {}), '(sentences_set)\n', (5597, 5612), False, 'from src.feature.wangdq import word_vector_similarity_train, word_vector_similarity_test, mean_clause, pos_gram_train, pos_gram_test, good_pos_ngrams, vocab_size, pos_tagger, pos_tagger2\n'), ((6099, 6125), 'src.feature.wangdq.mean_clause', 'mean_clause', (['sentences_set'], {}), '(sentences_set)\n', (6110, 6125), False, 'from src.feature.wangdq import word_vector_similarity_train, word_vector_similarity_test, mean_clause, pos_gram_train, pos_gram_test, good_pos_ngrams, vocab_size, pos_tagger, pos_tagger2\n'), ((6531, 6555), 'src.feature.iku.essay_length', 'essay_length', (['train_data'], {}), '(train_data)\n', (6543, 6555), False, 'from src.feature.iku import spell_error, Mean_sentence_depth_level, essay_length\n'), ((7958, 7979), 'src.feature.wangdq.vocab_size', 'vocab_size', (['token_set'], {}), '(token_set)\n', (7968, 7979), False, 'from src.feature.wangdq import word_vector_similarity_train, word_vector_similarity_test, mean_clause, pos_gram_train, pos_gram_test, good_pos_ngrams, vocab_size, pos_tagger, pos_tagger2\n'), ((8222, 8243), 'src.feature.wangdq.vocab_size', 'vocab_size', (['token_set'], {}), '(token_set)\n', (8232, 8243), False, 'from src.feature.wangdq import word_vector_similarity_train, word_vector_similarity_test, mean_clause, pos_gram_train, pos_gram_test, good_pos_ngrams, vocab_size, pos_tagger, pos_tagger2\n'), ((9329, 9381), 'src.feature.wangdq.word_vector_similarity_train', 'word_vector_similarity_train', (['token_set', 'train_score'], {}), '(token_set, train_score)\n', (9357, 9381), False, 'from src.feature.wangdq import word_vector_similarity_train, word_vector_similarity_test, mean_clause, pos_gram_train, pos_gram_test, good_pos_ngrams, vocab_size, pos_tagger, pos_tagger2\n'), ((9454, 9561), 'src.feature.wangdq.word_vector_similarity_test', 'word_vector_similarity_test', (['token_set', 'train_score', 'self.wv_tf_vocab', 'self.wv_idf_diag', 'self.wv_tfidf'], {}), '(token_set, train_score, self.wv_tf_vocab, self.\n wv_idf_diag, self.wv_tfidf)\n', (9481, 9561), False, 'from src.feature.wangdq import word_vector_similarity_train, word_vector_similarity_test, mean_clause, pos_gram_train, pos_gram_test, good_pos_ngrams, vocab_size, pos_tagger, pos_tagger2\n'), ((10786, 10814), 'src.feature.xiaoyl.word_bigram_train', 'word_bigram_train', (['token_set'], {}), '(token_set)\n', (10803, 10814), False, 'from src.feature.xiaoyl import word_length, get_sentence_length, word_bigram_train, word_bigram_test, word_trigram_train, word_trigram_test, bag_of_words_train, bag_of_words_test\n'), ((10864, 10939), 'src.feature.xiaoyl.word_bigram_test', 'word_bigram_test', (['token_set', 'self.word_bigram_TF', 'self.word_bigram_tf_vocab'], {}), '(token_set, self.word_bigram_TF, self.word_bigram_tf_vocab)\n', (10880, 10939), False, 'from src.feature.xiaoyl import word_length, get_sentence_length, word_bigram_train, word_bigram_test, word_trigram_train, word_trigram_test, bag_of_words_train, bag_of_words_test\n'), ((11221, 11250), 'src.feature.xiaoyl.word_trigram_train', 'word_trigram_train', (['token_set'], {}), '(token_set)\n', (11239, 11250), False, 'from src.feature.xiaoyl import word_length, get_sentence_length, word_bigram_train, word_bigram_test, word_trigram_train, word_trigram_test, bag_of_words_train, bag_of_words_test\n'), ((11301, 11379), 'src.feature.xiaoyl.word_trigram_test', 'word_trigram_test', (['token_set', 'self.word_trigram_TF', 'self.word_trigram_tf_vocab'], {}), '(token_set, self.word_trigram_TF, self.word_trigram_tf_vocab)\n', (11318, 11379), False, 'from src.feature.xiaoyl import word_length, get_sentence_length, word_bigram_train, word_bigram_test, word_trigram_train, word_trigram_test, bag_of_words_train, bag_of_words_test\n'), ((11764, 11793), 'src.feature.xiaoyl.bag_of_words_train', 'bag_of_words_train', (['token_set'], {}), '(token_set)\n', (11782, 11793), False, 'from src.feature.xiaoyl import word_length, get_sentence_length, word_bigram_train, word_bigram_test, word_trigram_train, word_trigram_test, bag_of_words_train, bag_of_words_test\n'), ((11843, 11921), 'src.feature.xiaoyl.bag_of_words_test', 'bag_of_words_test', (['token_set', 'self.bag_of_words_TF', 'self.bag_of_words_tf_vocab'], {}), '(token_set, self.bag_of_words_TF, self.bag_of_words_tf_vocab)\n', (11860, 11921), False, 'from src.feature.xiaoyl import word_length, get_sentence_length, word_bigram_train, word_bigram_test, word_trigram_train, word_trigram_test, bag_of_words_train, bag_of_words_test\n'), ((12866, 12896), 'sklearn.preprocessing.StandardScaler', 'preprocessing.StandardScaler', ([], {}), '()\n', (12894, 12896), False, 'from sklearn import preprocessing\n')]
|
import deepdiff
import numpy as np
from scipy import spatial as spat
from pyfar import Coordinates
from copy import deepcopy
class SphericalVoronoi(spat.SphericalVoronoi):
"""
Voronoi diagrams on the surface of a sphere. Note that
:py:func:`calculate_sph_voronoi_weights` can be used directly, if only the
sampling weights are needed.
"""
def __init__(self, sampling, round_decimals=12, center=0.0):
"""
Calculate a Voronoi diagram on the sphere for the given samplings
points.
Parameters
----------
sampling : Coordinates
Spherical sampling.
round_decimals : int
Number of decimals to be rounded for checking for equal radius.
The default is ``12``.
center : double
Center point of the voronoi diagram. The default is ``0``.
Returns
-------
voronoi : SphericalVoronoi
Spherical voronoi diagram as implemented in ``scipy.spatial``.
See also
--------
:py:func:`calculate_sph_voronoi_weights`
"""
points = sampling.get_cart()
radius = sampling.get_sph()[:, -1]
radius_round = np.unique(np.round(radius, decimals=round_decimals))
if len(radius_round) > 1:
raise ValueError("All sampling points need to be on the \
same radius.")
super().__init__(points, radius_round, center)
def copy(self):
"""Return a copy of the Voronoi object."""
return deepcopy(self)
def _encode(self):
"""Return object in a proper encoding format."""
# Use public interface of the scipy super-class to prevent
# error in case of chaning super-class implementations
return {'points': self.points, 'center': self.center}
@classmethod
def _decode(cls, obj_dict):
"""Decode object based on its respective `_encode` counterpart."""
sampling = Coordinates(
obj_dict['points'][:, 0],
obj_dict['points'][:, 1],
obj_dict['points'][:, 2],
domain='cart')
return cls(sampling, center=obj_dict['center'])
def __eq__(self, other):
"""Check for equality of two objects."""
return not deepdiff.DeepDiff(self, other)
def calculate_sph_voronoi_weights(
sampling, normalize=True, center=[0, 0, 0], round_decimals=12):
"""
Calculate sampling weights for numeric integration.
Uses the class method ``calculate_areas`` from :py:class:`SphericalVoronoi`
to calculate the weights. It requires a spherical sampling grid with a
single radius and uses ``scipy.spatial.SphericalVoronoi`` in the
background.
Parameters
----------
sampling : Coordinates
Sampling points on a sphere, i.e., all points must have the same
radius.
normalize : boolean, optional
Normalize the samplings weights to ``sum(weights)=1``. Otherwise the
weights sum to :math:`4 \\pi r^2`. The default is ``True``.
center : list
Center of the spherical sampling grid. The default is ``[0, 0, 0]``.
round_decimals : int, optional
Round to `round_decimals` digits to check for equal radius. The
default is ``12``.
Returns
-------
weigths : ndarray, double
Sampling weights of size `samplings.csize`.
"""
# get Voronoi diagram
if sampling.csize <= 3:
raise ValueError(
'The number of points needs to be at least 4',
'to generate a valid SphericalVoronoi diagram.')
sv = SphericalVoronoi(sampling, round_decimals, center)
# get the area
weights = sv.calculate_areas()
if normalize:
weights /= np.sum(weights)
return weights
|
[
"copy.deepcopy",
"numpy.sum",
"deepdiff.DeepDiff",
"pyfar.Coordinates",
"numpy.round"
] |
[((1542, 1556), 'copy.deepcopy', 'deepcopy', (['self'], {}), '(self)\n', (1550, 1556), False, 'from copy import deepcopy\n'), ((1974, 2083), 'pyfar.Coordinates', 'Coordinates', (["obj_dict['points'][:, 0]", "obj_dict['points'][:, 1]", "obj_dict['points'][:, 2]"], {'domain': '"""cart"""'}), "(obj_dict['points'][:, 0], obj_dict['points'][:, 1], obj_dict[\n 'points'][:, 2], domain='cart')\n", (1985, 2083), False, 'from pyfar import Coordinates\n'), ((3751, 3766), 'numpy.sum', 'np.sum', (['weights'], {}), '(weights)\n', (3757, 3766), True, 'import numpy as np\n'), ((1218, 1259), 'numpy.round', 'np.round', (['radius'], {'decimals': 'round_decimals'}), '(radius, decimals=round_decimals)\n', (1226, 1259), True, 'import numpy as np\n'), ((2282, 2312), 'deepdiff.DeepDiff', 'deepdiff.DeepDiff', (['self', 'other'], {}), '(self, other)\n', (2299, 2312), False, 'import deepdiff\n')]
|
# Fix paths for imports to work in unit tests ----------------
if __name__ == "__main__":
from _fix_paths import fix_paths
fix_paths()
# ------------------------------------------------------------
# Load libraries ---------------------------------------------
import numpy as np
# ------------------------------------------------------------
def randargmax(a, rng=None, max_fn=np.max):
"""
Returns index of max element, with random tie breaking.
If random tie breaking is not needed, use np.argmax() instead.
:param Union[list, np.ndarray] a: A list or np.ndarray.
:param object rng: Random number generator. If None, np.random is used.
Must implement the choice method which chooses a random element of an array.
:param function max_fn: A function choosing the maximal element.
:return: Index of the max element.
:rtype: int
"""
temp = np.flatnonzero(a == max_fn(a))
try:
if rng is None:
return np.random.choice(temp)
else:
return rng.choice(temp)
except ValueError:
print('DEBUG: set breakpoint here in dhl.randargmax()')
return np.nan
def randargmax_ignoreNaN(a, rng=None):
"""
Returns index of max element, with random tie breaking.
If random tie breaking is not needed, use np.argmax() instead.
Will return the index even if there are NaNs in the array.
:param Union[list, np.ndarray] a: A list or np.ndarray.
:param object rng: Random number generator. If None, np.random is used.
Must implement the choice method which chooses a random element of an array.
:param function max_fn: A function choosing the maximal element.
:return: Index of the max element.
:rtype: int
"""
return randargmax(a, rng, max_fn=np.nanmax)
#
def find_nearest(val, arr):
"""
Returns element, index in arr that is nearest to val.
:param float val: Value to be approximated.
:param Union[list, np.ndarray] arr: List or array with values.
:return: Tuple of element and index in array nearest to val.
:rtype: tuple
"""
ix = np.argmin(np.abs(np.asarray(arr) - val))
return arr[ix], ix
def avg_running(old_est, n_th_sample, n):
"""
Calculates the running average.
:param old_est: Previous value of the average.
:param n_th_sample: New value to be included in the average.
:param n: Overall number of samples.
:return: Average including the new value.
:rtype: float
"""
assert(n > 0)
return 1/n * n_th_sample + (n-1)/n * old_est
|
[
"numpy.asarray",
"_fix_paths.fix_paths",
"numpy.random.choice"
] |
[((137, 148), '_fix_paths.fix_paths', 'fix_paths', ([], {}), '()\n', (146, 148), False, 'from _fix_paths import fix_paths\n'), ((991, 1013), 'numpy.random.choice', 'np.random.choice', (['temp'], {}), '(temp)\n', (1007, 1013), True, 'import numpy as np\n'), ((2146, 2161), 'numpy.asarray', 'np.asarray', (['arr'], {}), '(arr)\n', (2156, 2161), True, 'import numpy as np\n')]
|
from io import BytesIO
import matplotlib.pyplot as plt
import base64
import matplotlib
from astropy import utils, io
import numpy as np
from astropy.wcs import WCS
from astropy.visualization.wcsaxes import WCSAxes
import matplotlib.colors as mcolors
from astropy.visualization import (MinMaxInterval, SqrtStretch,ImageNormalize)
matplotlib.use('Agg')
class ImageUtils():
@staticmethod
def imgNpArrayToBase64(img_np_array,mark=""):
buffer= BytesIO()
plt.clf()
fig1 = plt.gcf()
w=img_np_array.shape[1]/96.
h=img_np_array.shape[0]/96. #3.125 # 300pixel = 3.125inches (1in == 2.54cm) 1 inch = 96 pixel
fig1.set_size_inches(w, h)
plt.imshow(img_np_array,origin='lower', interpolation='none', cmap=plt.get_cmap("Greys"),norm=matplotlib.colors.LogNorm(vmin=0.1, vmax=img_np_array.max()))
plt.axis("off")
radii=100
if mark != "":
plt.scatter(mark[0],mark[1],s=radii,facecolors='none', edgecolors='r')
#plt.show()
fig1.savefig(buffer,format='png')
str="data:image/png;base64,{0}"
base64str=base64.encodebytes(buffer.getvalue()).decode()
return str.format(base64str)
@staticmethod
def saveImageFromNPArray(img_np_array,output_path, mark=""):
plt.imshow(img_np_array, cmap='gray')
plt.colorbar()
plt.show()
NBINS = 1000
img_np_array=np.where(np.isnan(img_np_array),-99,img_np_array)
print(img_np_array.max(), img_np_array.min())
flatten=img_np_array.flatten()
histogram = plt.hist(flatten, NBINS)
plt.show()
# plt.clf()
# fig1 = plt.gcf()
#
# # Create an ImageNormalize object
# norm = ImageNormalize(img_np_array, interval=MinMaxInterval(),
# stretch=SqrtStretch())
#
# w = img_np_array.shape[1] / 96.
# h = img_np_array.shape[0] / 96. # 3.125 # 300pixel = 3.125inches (1in == 2.54cm) 1 inch = 96 pixel
# fig1.set_size_inches(w, h)
#
# plt.imshow(img_np_array, origin='lower', vmin=100, vmax=6000,interpolation='none', norm=mcolors.PowerNorm(0.3),cmap=plt.get_cmap("Greys"))#norm=matplotlib.colors.LogNorm(vmin=vmin, vmax=vmax),cmap=plt.get_cmap("Greys"))
#
# #plt.axis("off")
# radii = 100
# if mark != "":
# plt.scatter(mark[0], mark[1], s=radii, facecolors='none', edgecolors='r')
# plt.show()
# fig1.savefig(output_path, format='png')
# return output_path
@staticmethod
def saveImageFromFits(fits_path,mark=""):
data = ImageUtils.getImageFromFits(fits_path)
@staticmethod
def getImageFromFits(url):
try:
idx=url.index("html")
image = io.fits.getdata(utils.data.download_file(url, cache=True, show_progress=False, timeout=120))
except ValueError:
image = io.fits.getdata(url)
return image
@staticmethod
def getBase64FromFitsURL(url,mark=""):
base64 =ImageUtils.imgNpArrayToBase64(ImageUtils.getImageFromFits(url),mark=mark)
return base64
@staticmethod
def getImageFromUrl(url):
local_Path= utils.data.download_file(url, cache=True, show_progress=False, timeout=120)
image = io.fits.getdata(local_Path)
@staticmethod
def getPixelFromRADEC():
pass
|
[
"io.BytesIO",
"matplotlib.pyplot.show",
"matplotlib.pyplot.get_cmap",
"matplotlib.pyplot.hist",
"matplotlib.pyplot.clf",
"matplotlib.pyplot.imshow",
"astropy.io.fits.getdata",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.axis",
"numpy.isnan",
"matplotlib.pyplot.colorbar",
"matplotlib.use",
"astropy.utils.data.download_file",
"matplotlib.pyplot.gcf"
] |
[((331, 352), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (345, 352), False, 'import matplotlib\n'), ((457, 466), 'io.BytesIO', 'BytesIO', ([], {}), '()\n', (464, 466), False, 'from io import BytesIO\n'), ((475, 484), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (482, 484), True, 'import matplotlib.pyplot as plt\n'), ((500, 509), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '()\n', (507, 509), True, 'import matplotlib.pyplot as plt\n'), ((858, 873), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (866, 873), True, 'import matplotlib.pyplot as plt\n'), ((1295, 1332), 'matplotlib.pyplot.imshow', 'plt.imshow', (['img_np_array'], {'cmap': '"""gray"""'}), "(img_np_array, cmap='gray')\n", (1305, 1332), True, 'import matplotlib.pyplot as plt\n'), ((1341, 1355), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (1353, 1355), True, 'import matplotlib.pyplot as plt\n'), ((1364, 1374), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1372, 1374), True, 'import matplotlib.pyplot as plt\n'), ((1581, 1605), 'matplotlib.pyplot.hist', 'plt.hist', (['flatten', 'NBINS'], {}), '(flatten, NBINS)\n', (1589, 1605), True, 'import matplotlib.pyplot as plt\n'), ((1614, 1624), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1622, 1624), True, 'import matplotlib.pyplot as plt\n'), ((3228, 3303), 'astropy.utils.data.download_file', 'utils.data.download_file', (['url'], {'cache': '(True)', 'show_progress': '(False)', 'timeout': '(120)'}), '(url, cache=True, show_progress=False, timeout=120)\n', (3252, 3303), False, 'from astropy import utils, io\n'), ((3320, 3347), 'astropy.io.fits.getdata', 'io.fits.getdata', (['local_Path'], {}), '(local_Path)\n', (3335, 3347), False, 'from astropy import utils, io\n'), ((927, 1000), 'matplotlib.pyplot.scatter', 'plt.scatter', (['mark[0]', 'mark[1]'], {'s': 'radii', 'facecolors': '"""none"""', 'edgecolors': '"""r"""'}), "(mark[0], mark[1], s=radii, facecolors='none', edgecolors='r')\n", (938, 1000), True, 'import matplotlib.pyplot as plt\n'), ((1426, 1448), 'numpy.isnan', 'np.isnan', (['img_np_array'], {}), '(img_np_array)\n', (1434, 1448), True, 'import numpy as np\n'), ((760, 781), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""Greys"""'], {}), "('Greys')\n", (772, 781), True, 'import matplotlib.pyplot as plt\n'), ((2818, 2893), 'astropy.utils.data.download_file', 'utils.data.download_file', (['url'], {'cache': '(True)', 'show_progress': '(False)', 'timeout': '(120)'}), '(url, cache=True, show_progress=False, timeout=120)\n', (2842, 2893), False, 'from astropy import utils, io\n'), ((2942, 2962), 'astropy.io.fits.getdata', 'io.fits.getdata', (['url'], {}), '(url)\n', (2957, 2962), False, 'from astropy import utils, io\n')]
|
from copy import deepcopy
import numpy as np
import torch
import torchvision
from PIL import Image
from torch.utils.data import DataLoader
from src.dataset import factory as dataset_factory
from src.roar import roar_core
from src.utils.sysutils import get_cores_count
class CompoundImageFolderDataset(torch.utils.data.Dataset):
"""
To load Image Folder dataset along with images attribution files.
"""
def __init__(self, dataset_name,
image_files_train_path,
image_files_validation_path,
image_files_test_path,
attribution_files_train_path,
attribution_files_validation_path,
attribution_files_test_path,
percentile=0.1,
roar=True):
"""
Args:
dataset_name:
image_files_train_path:
image_files_validation_path:
image_files_test_path:
attribution_files_train_path:
attribution_files_validation_path:
attribution_files_test_path:
percentile: The % of pixels to remove from input image.
roar: Set to True for ROAR metric, False for KAR metric.
"""
if dataset_name not in dataset_factory.MAP_DATASET_TO_ENUM:
raise ValueError(f'Invalid dataset_name {dataset_name}')
self.dataset_name = dataset_name
self.attribution_files_train_path = attribution_files_train_path
self.attribution_files_validation_path = attribution_files_validation_path
self.attribution_files_test_path = attribution_files_test_path
self.percentile = percentile
self.roar = roar
self.dataset_class = dataset_factory.get_dataset_class(dataset_name=dataset_name)
self.mean = self.dataset_class.mean
self.std = self.dataset_class.std
self.demean = [-m / s for m, s in zip(self.mean, self.std)]
self.destd = [1 / s for s in self.std]
self.train_normalize_transform = self.dataset_class.get_train_transform(enable_augmentation=True)
self.evaluation_normalize_transform = self.dataset_class.get_validation_transform()
# Used for visualization of preprocessed images.
self.denormalize_transform = torchvision.transforms.Normalize(self.demean, self.destd)
# Note - For training, we do not apply augmentation transform.
# First, image is loaded, most/least important pixels are removed and then augmentations are applied.
self.training_images_dataset = torchvision.datasets.ImageFolder(root=image_files_train_path,
transform=torchvision.transforms.ToTensor())
self.validation_images_dataset = torchvision.datasets.ImageFolder(root=image_files_validation_path,
transform=self.evaluation_normalize_transform)
self.test_images_dataset = torchvision.datasets.ImageFolder(root=image_files_test_path,
transform=self.evaluation_normalize_transform)
self.training_attribution_map_dataset = torchvision.datasets.ImageFolder(
root=attribution_files_train_path,
transform=torchvision.transforms.ToTensor())
self.validation_attribution_map_dataset = torchvision.datasets.ImageFolder(
root=attribution_files_validation_path,
transform=torchvision.transforms.ToTensor())
self.test_attribution_map_dataset = torchvision.datasets.ImageFolder(
root=attribution_files_test_path,
transform=torchvision.transforms.ToTensor())
self.mode = 'training'
def __getitem__(self, index):
if self.mode == 'training':
image, label = self.training_images_dataset[index]
attribution_map, label = self.training_attribution_map_dataset[index]
mean = self.mean
elif self.mode == 'validation':
image, label = self.validation_images_dataset[index]
attribution_map, label = self.validation_attribution_map_dataset[index]
mean = [0, 0, 0]
else:
image, label = self.test_images_dataset[index]
attribution_map, label = self.test_attribution_map_dataset[index]
mean = [0, 0, 0] # validation and training images already are normalized.
# Below code is left intentionally for one to quickly check if input data to model is correct.
# import torchvision.transforms as T
# T.ToPILImage()(image).save('input.jpg') # only for training, for validation/test, denormalize first.
image = np.array(image)
attribution_map = np.max(attribution_map.numpy(), axis=0, keepdims=True)
image = roar_core.remove(image, attribution_map, mean, self.percentile, keep=not self.roar, gray=True)
if self.mode == 'training':
# Do augmentation(randomscale/randomcrop) transform only after removal of pixels is done.
image = image.transpose(1, 2, 0) # PIL needs HXWX3, converting from 3xHxW .
image = self.train_normalize_transform(Image.fromarray((image * 255).astype(np.uint8)))
# import torchvision.transforms as T
# T.ToPILImage()(self.denormalize_transform(image)).save('augmented.jpg')
return image, label
def __len__(self):
if self.mode == 'training':
return self.train_dataset_size
elif self.mode == 'validation':
return self.val_dataset_size
else:
return self.test_dataset_size
def get_train_dataloader(self, data_args) -> DataLoader:
self.mode = 'training'
# Deepcopy ensures any changes to mode variable will not influence this dataloader
return torch.utils.data.DataLoader(deepcopy(self),
batch_size=data_args['batch_size'],
shuffle=data_args['shuffle'],
num_workers=get_cores_count())
def get_validation_dataloader(self, data_args) -> DataLoader:
self.mode = 'validation'
return torch.utils.data.DataLoader(deepcopy(self),
batch_size=data_args['batch_size'],
shuffle=data_args['shuffle'],
num_workers=get_cores_count())
def get_test_dataloader(self, data_args):
self.mode = 'test'
return torch.utils.data.DataLoader(deepcopy(self),
batch_size=data_args['batch_size'],
shuffle=data_args['shuffle'],
num_workers=get_cores_count())
@property
def classes(self):
return self.training_attribution_map_dataset.classes
@property
def train_dataset_size(self):
return len(self.training_images_dataset)
@property
def val_dataset_size(self):
return len(self.validation_images_dataset)
@property
def test_dataset_size(self):
return len(self.test_images_dataset)
# ToDo Add debug method for Compound Image Folder Dataset.
|
[
"copy.deepcopy",
"src.roar.roar_core.remove",
"torchvision.datasets.ImageFolder",
"numpy.array",
"src.dataset.factory.get_dataset_class",
"torchvision.transforms.Normalize",
"src.utils.sysutils.get_cores_count",
"torchvision.transforms.ToTensor"
] |
[((1733, 1793), 'src.dataset.factory.get_dataset_class', 'dataset_factory.get_dataset_class', ([], {'dataset_name': 'dataset_name'}), '(dataset_name=dataset_name)\n', (1766, 1793), True, 'from src.dataset import factory as dataset_factory\n'), ((2288, 2345), 'torchvision.transforms.Normalize', 'torchvision.transforms.Normalize', (['self.demean', 'self.destd'], {}), '(self.demean, self.destd)\n', (2320, 2345), False, 'import torchvision\n'), ((2787, 2904), 'torchvision.datasets.ImageFolder', 'torchvision.datasets.ImageFolder', ([], {'root': 'image_files_validation_path', 'transform': 'self.evaluation_normalize_transform'}), '(root=image_files_validation_path,\n transform=self.evaluation_normalize_transform)\n', (2819, 2904), False, 'import torchvision\n'), ((3010, 3122), 'torchvision.datasets.ImageFolder', 'torchvision.datasets.ImageFolder', ([], {'root': 'image_files_test_path', 'transform': 'self.evaluation_normalize_transform'}), '(root=image_files_test_path, transform=self\n .evaluation_normalize_transform)\n', (3042, 3122), False, 'import torchvision\n'), ((4757, 4772), 'numpy.array', 'np.array', (['image'], {}), '(image)\n', (4765, 4772), True, 'import numpy as np\n'), ((4870, 4968), 'src.roar.roar_core.remove', 'roar_core.remove', (['image', 'attribution_map', 'mean', 'self.percentile'], {'keep': '(not self.roar)', 'gray': '(True)'}), '(image, attribution_map, mean, self.percentile, keep=not\n self.roar, gray=True)\n', (4886, 4968), False, 'from src.roar import roar_core\n'), ((5917, 5931), 'copy.deepcopy', 'deepcopy', (['self'], {}), '(self)\n', (5925, 5931), False, 'from copy import deepcopy\n'), ((6302, 6316), 'copy.deepcopy', 'deepcopy', (['self'], {}), '(self)\n', (6310, 6316), False, 'from copy import deepcopy\n'), ((6661, 6675), 'copy.deepcopy', 'deepcopy', (['self'], {}), '(self)\n', (6669, 6675), False, 'from copy import deepcopy\n'), ((2711, 2744), 'torchvision.transforms.ToTensor', 'torchvision.transforms.ToTensor', ([], {}), '()\n', (2742, 2744), False, 'import torchvision\n'), ((3338, 3371), 'torchvision.transforms.ToTensor', 'torchvision.transforms.ToTensor', ([], {}), '()\n', (3369, 3371), False, 'import torchvision\n'), ((3531, 3564), 'torchvision.transforms.ToTensor', 'torchvision.transforms.ToTensor', ([], {}), '()\n', (3562, 3564), False, 'import torchvision\n'), ((3712, 3745), 'torchvision.transforms.ToTensor', 'torchvision.transforms.ToTensor', ([], {}), '()\n', (3743, 3745), False, 'import torchvision\n'), ((6140, 6157), 'src.utils.sysutils.get_cores_count', 'get_cores_count', ([], {}), '()\n', (6155, 6157), False, 'from src.utils.sysutils import get_cores_count\n'), ((6525, 6542), 'src.utils.sysutils.get_cores_count', 'get_cores_count', ([], {}), '()\n', (6540, 6542), False, 'from src.utils.sysutils import get_cores_count\n'), ((6884, 6901), 'src.utils.sysutils.get_cores_count', 'get_cores_count', ([], {}), '()\n', (6899, 6901), False, 'from src.utils.sysutils import get_cores_count\n')]
|
import subprocess
import time
import numpy as np
def get_instances():
"""returns array of instance names, array of corresponding n"""
instance_data = np.genfromtxt('m2s_nqubits.csv', delimiter=',', skip_header=1, dtype=str) # can add _noGT_nondg on end
return instance_data[:, 0], instance_data[:, 1]
if __name__ == '__main__':
instance_names, instance_n_bits_str = get_instances()
n = 75
num_instances = 1000
runtimes = np.zeros(num_instances)
output_runtimes = np.zeros(num_instances)
num_repeats = 5
for repeat in range(num_repeats):
print("--------- repeat", repeat+1, "---------")
for i in range(num_instances):
instance_name = str(n) + "_" + str(i)
time_start_inst = time.process_time()
result = subprocess.run(['./../../mixsat/complete', "./../../instances_big_2/"+instance_name+".gz"], stdout=subprocess.PIPE) # can add _noGT_nondg on end
time_end_inst = time.process_time()
runtime = time_end_inst - time_start_inst
runtimes[i] = runtime
output = str(result.stdout)
string_slice_start = output.find('state_visited ')
output2 = output[string_slice_start:]
string_start_index = output2.find('time ') + 5
output3 = output2[string_start_index:]
string_end_index = output3.find('s')
output_time = float(output3[:string_end_index])
output_runtimes[i] = output_time
if i % 100 == 0:
print(i)
with open("big_runtimes_"+str(n)+".txt", "ab") as f: # saves runtimes using time.process_time() # can add _noGT_nondg in middle
f.write(b"\n")
np.savetxt(f, runtimes)
with open("big_output_runtimes_"+str(n)+".txt", "ab") as f: # saves counts # can add _noGT_nondg in middle
f.write(b"\n")
np.savetxt(f, output_runtimes)
|
[
"subprocess.run",
"time.process_time",
"numpy.savetxt",
"numpy.zeros",
"numpy.genfromtxt"
] |
[((160, 233), 'numpy.genfromtxt', 'np.genfromtxt', (['"""m2s_nqubits.csv"""'], {'delimiter': '""","""', 'skip_header': '(1)', 'dtype': 'str'}), "('m2s_nqubits.csv', delimiter=',', skip_header=1, dtype=str)\n", (173, 233), True, 'import numpy as np\n'), ((462, 485), 'numpy.zeros', 'np.zeros', (['num_instances'], {}), '(num_instances)\n', (470, 485), True, 'import numpy as np\n'), ((508, 531), 'numpy.zeros', 'np.zeros', (['num_instances'], {}), '(num_instances)\n', (516, 531), True, 'import numpy as np\n'), ((768, 787), 'time.process_time', 'time.process_time', ([], {}), '()\n', (785, 787), False, 'import time\n'), ((809, 932), 'subprocess.run', 'subprocess.run', (["['./../../mixsat/complete', './../../instances_big_2/' + instance_name + '.gz']"], {'stdout': 'subprocess.PIPE'}), "(['./../../mixsat/complete', './../../instances_big_2/' +\n instance_name + '.gz'], stdout=subprocess.PIPE)\n", (823, 932), False, 'import subprocess\n'), ((990, 1009), 'time.process_time', 'time.process_time', ([], {}), '()\n', (1007, 1009), False, 'import time\n'), ((1762, 1785), 'numpy.savetxt', 'np.savetxt', (['f', 'runtimes'], {}), '(f, runtimes)\n', (1772, 1785), True, 'import numpy as np\n'), ((1956, 1986), 'numpy.savetxt', 'np.savetxt', (['f', 'output_runtimes'], {}), '(f, output_runtimes)\n', (1966, 1986), True, 'import numpy as np\n')]
|
import numpy as np
import sys, os
import pprint
sys.path.append(os.path.dirname(sys.path[0]))
from lib.envs.gridworld import GridworldEnv
from ValueIteration import value_iteration
env = GridworldEnv()
pp = pprint.PrettyPrinter(indent=2)
random_policy = np.ones([env.nS, env.nA]) / env.nA
policy, v = value_iteration(env)
print("Policy Probability Distribution:")
print(policy)
print("")
print("Reshaped Grid Policy (0=up, 1=right, 2=down, 3=left):")
print(np.reshape(np.argmax(policy, axis=1), env.shape))
print("")
print("Value Function:")
print(v)
print("")
print("Reshaped Grid Value Function:")
print(v.reshape(env.shape))
print("")
# Test the value function
expected_v = np.array([ 0, -1, -2, -3, -1, -2, -3, -2, -2, -3, -2, -1, -3, -2, -1, 0])
np.testing.assert_array_almost_equal(v, expected_v, decimal=2)
|
[
"lib.envs.gridworld.GridworldEnv",
"numpy.argmax",
"os.path.dirname",
"numpy.ones",
"pprint.PrettyPrinter",
"numpy.array",
"ValueIteration.value_iteration",
"numpy.testing.assert_array_almost_equal"
] |
[((189, 203), 'lib.envs.gridworld.GridworldEnv', 'GridworldEnv', ([], {}), '()\n', (201, 203), False, 'from lib.envs.gridworld import GridworldEnv\n'), ((209, 239), 'pprint.PrettyPrinter', 'pprint.PrettyPrinter', ([], {'indent': '(2)'}), '(indent=2)\n', (229, 239), False, 'import pprint\n'), ((305, 325), 'ValueIteration.value_iteration', 'value_iteration', (['env'], {}), '(env)\n', (320, 325), False, 'from ValueIteration import value_iteration\n'), ((686, 758), 'numpy.array', 'np.array', (['[0, -1, -2, -3, -1, -2, -3, -2, -2, -3, -2, -1, -3, -2, -1, 0]'], {}), '([0, -1, -2, -3, -1, -2, -3, -2, -2, -3, -2, -1, -3, -2, -1, 0])\n', (694, 758), True, 'import numpy as np\n'), ((761, 823), 'numpy.testing.assert_array_almost_equal', 'np.testing.assert_array_almost_equal', (['v', 'expected_v'], {'decimal': '(2)'}), '(v, expected_v, decimal=2)\n', (797, 823), True, 'import numpy as np\n'), ((65, 93), 'os.path.dirname', 'os.path.dirname', (['sys.path[0]'], {}), '(sys.path[0])\n', (80, 93), False, 'import sys, os\n'), ((257, 282), 'numpy.ones', 'np.ones', (['[env.nS, env.nA]'], {}), '([env.nS, env.nA])\n', (264, 282), True, 'import numpy as np\n'), ((474, 499), 'numpy.argmax', 'np.argmax', (['policy'], {'axis': '(1)'}), '(policy, axis=1)\n', (483, 499), True, 'import numpy as np\n')]
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 16 13:12:53 2021
@author: emgordy
"""
# SST grids for the persistence model (basically making sure the time lines up, that's why we load in the OHC, it's a whole lotta checking)
import xarray as xr
import glob
import numpy as np
import matplotlib.pyplot as plt
writeout = False
run = 60 # set input run (12 or 24 or 60 months)
lf = 50
grid1 = 72
ohc700str = glob.glob('/Users/emgordy/Documents/Experiments/DecadalPrediction_ForReal/data/ohc_heat700-r*%d*detrended*spinup*%d*.nc' %(run,lf))[0]
ohc700_dataset = xr.open_dataset(ohc700str)
ohc700 = np.asarray(ohc700_dataset.ohc)
lon = ohc700_dataset.lon
lat = ohc700_dataset.lat
sststr = glob.glob('/Users/emgordy/Documents/Experiments/DecadalPrediction_ForReal/data/sst-r*detrended*spinup*lookback*%d*%d*.nc' %(lf,grid1))[0]
sst_dataset = xr.open_dataset(sststr)
lon2 = sst_dataset.lon
lat2 = sst_dataset.lat
sstforward = glob.glob('sst-r*detrended*spinup*lookforward*%d*%d*.nc' %(lf,grid1))[0]
sstf_dataset = xr.open_dataset(sststr)
sst = np.asarray(sst_dataset.sst)
sstf = np.asarray(sstf_dataset.sst)
#%% set lag for each persistence model, 12 for lead year 1-5, 36 for lead 3-7
lag = 12
ly1 = int(lag/12)
ly2 = ly1+4
arrdims = np.shape(ohc700)
ohc700flat = np.reshape(ohc700,(arrdims[0],arrdims[1]*arrdims[2]))
time = np.arange(arrdims[0])
ohc_input = np.asarray(ohc700flat)
#%%
sst_output = sstf[lag:]
if lag != 0:
timeohc = time[:-lag]
else:
timeohc = time
timesst = time[lag:]
#%%
# remove burnt ends
cut1 = np.shape(sst_output)[0]
ohc_input = ohc_input[:cut1]
sstp = sst[:cut1]
timeohc = timeohc[:cut1]
ohc_input[np.isnan(ohc_input)] = 0
#%%
# where lookback is nan
cut2 = run-1
ohc_input = ohc_input[cut2:]
sstp = sstp[cut2:]
sst_output = sst_output[cut2:]
timeohc = timeohc[cut2:]
timesst = timesst[cut2:]
#%%
# where lookforward is nan i.e. more burnt ends
sstpoint = sst_output[:,16,12]
ohc_input = ohc_input[~np.isnan(sstpoint)]
sst_output = sst_output[~np.isnan(sstpoint)]
sstp = sstp[~np.isnan(sstpoint)]
timeohc = timeohc[~np.isnan(sstpoint)]
timesst = timesst[~np.isnan(sstpoint)]
#%% make netCDF out
sst_datasetout = xr.Dataset(
{"sst": (("time","lat","lon"), sstp)},
coords={
"time": timesst,
"lat": lat2,
"lon": lon2
},
)
sststrout = "sst-persistence_detrended_spinup_runningmean%d_ly%d-%d_lf%d_r72x36_heatx3.nc" %(run,ly1,ly2,lf)
#%% and save
if writeout:
print("wrote some files")
sst_datasetout.to_netcdf(sststrout)
else:
print("did not write files")
|
[
"numpy.asarray",
"xarray.open_dataset",
"numpy.isnan",
"xarray.Dataset",
"numpy.shape",
"numpy.arange",
"numpy.reshape",
"glob.glob"
] |
[((585, 611), 'xarray.open_dataset', 'xr.open_dataset', (['ohc700str'], {}), '(ohc700str)\n', (600, 611), True, 'import xarray as xr\n'), ((622, 652), 'numpy.asarray', 'np.asarray', (['ohc700_dataset.ohc'], {}), '(ohc700_dataset.ohc)\n', (632, 652), True, 'import numpy as np\n'), ((865, 888), 'xarray.open_dataset', 'xr.open_dataset', (['sststr'], {}), '(sststr)\n', (880, 888), True, 'import xarray as xr\n'), ((1037, 1060), 'xarray.open_dataset', 'xr.open_dataset', (['sststr'], {}), '(sststr)\n', (1052, 1060), True, 'import xarray as xr\n'), ((1068, 1095), 'numpy.asarray', 'np.asarray', (['sst_dataset.sst'], {}), '(sst_dataset.sst)\n', (1078, 1095), True, 'import numpy as np\n'), ((1103, 1131), 'numpy.asarray', 'np.asarray', (['sstf_dataset.sst'], {}), '(sstf_dataset.sst)\n', (1113, 1131), True, 'import numpy as np\n'), ((1262, 1278), 'numpy.shape', 'np.shape', (['ohc700'], {}), '(ohc700)\n', (1270, 1278), True, 'import numpy as np\n'), ((1293, 1350), 'numpy.reshape', 'np.reshape', (['ohc700', '(arrdims[0], arrdims[1] * arrdims[2])'], {}), '(ohc700, (arrdims[0], arrdims[1] * arrdims[2]))\n', (1303, 1350), True, 'import numpy as np\n'), ((1354, 1375), 'numpy.arange', 'np.arange', (['arrdims[0]'], {}), '(arrdims[0])\n', (1363, 1375), True, 'import numpy as np\n'), ((1389, 1411), 'numpy.asarray', 'np.asarray', (['ohc700flat'], {}), '(ohc700flat)\n', (1399, 1411), True, 'import numpy as np\n'), ((2182, 2289), 'xarray.Dataset', 'xr.Dataset', (["{'sst': (('time', 'lat', 'lon'), sstp)}"], {'coords': "{'time': timesst, 'lat': lat2, 'lon': lon2}"}), "({'sst': (('time', 'lat', 'lon'), sstp)}, coords={'time': timesst,\n 'lat': lat2, 'lon': lon2})\n", (2192, 2289), True, 'import xarray as xr\n'), ((433, 576), 'glob.glob', 'glob.glob', (["('/Users/emgordy/Documents/Experiments/DecadalPrediction_ForReal/data/ohc_heat700-r*%d*detrended*spinup*%d*.nc'\n % (run, lf))"], {}), "(\n '/Users/emgordy/Documents/Experiments/DecadalPrediction_ForReal/data/ohc_heat700-r*%d*detrended*spinup*%d*.nc'\n % (run, lf))\n", (442, 576), False, 'import glob\n'), ((713, 859), 'glob.glob', 'glob.glob', (["('/Users/emgordy/Documents/Experiments/DecadalPrediction_ForReal/data/sst-r*detrended*spinup*lookback*%d*%d*.nc'\n % (lf, grid1))"], {}), "(\n '/Users/emgordy/Documents/Experiments/DecadalPrediction_ForReal/data/sst-r*detrended*spinup*lookback*%d*%d*.nc'\n % (lf, grid1))\n", (722, 859), False, 'import glob\n'), ((949, 1020), 'glob.glob', 'glob.glob', (["('sst-r*detrended*spinup*lookforward*%d*%d*.nc' % (lf, grid1))"], {}), "('sst-r*detrended*spinup*lookforward*%d*%d*.nc' % (lf, grid1))\n", (958, 1020), False, 'import glob\n'), ((1558, 1578), 'numpy.shape', 'np.shape', (['sst_output'], {}), '(sst_output)\n', (1566, 1578), True, 'import numpy as np\n'), ((1666, 1685), 'numpy.isnan', 'np.isnan', (['ohc_input'], {}), '(ohc_input)\n', (1674, 1685), True, 'import numpy as np\n'), ((1968, 1986), 'numpy.isnan', 'np.isnan', (['sstpoint'], {}), '(sstpoint)\n', (1976, 1986), True, 'import numpy as np\n'), ((2013, 2031), 'numpy.isnan', 'np.isnan', (['sstpoint'], {}), '(sstpoint)\n', (2021, 2031), True, 'import numpy as np\n'), ((2046, 2064), 'numpy.isnan', 'np.isnan', (['sstpoint'], {}), '(sstpoint)\n', (2054, 2064), True, 'import numpy as np\n'), ((2085, 2103), 'numpy.isnan', 'np.isnan', (['sstpoint'], {}), '(sstpoint)\n', (2093, 2103), True, 'import numpy as np\n'), ((2124, 2142), 'numpy.isnan', 'np.isnan', (['sstpoint'], {}), '(sstpoint)\n', (2132, 2142), True, 'import numpy as np\n')]
|
# -*- coding: utf-8 -*-
"""
对图片进行边缘检测;
添加滑动条,可自由调整阈值上下限。
"""
import cv2
import numpy as np
def nothing(x):
pass
cv2.namedWindow('Canny', 0)
# 创建滑动条
cv2.createTrackbar('min_val', 'Canny', 0, 255, nothing)
cv2.createTrackbar('max_val', 'Canny', 0, 255, nothing)
img = cv2.imread('Tree.jpg', 0)
# 高斯滤波去噪
img = cv2.GaussianBlur(img, (3, 3), 0)
edges = img
k = 0
while 1:
key = cv2.waitKey(50) & 0xFF
if key == ord('q'):
break
# 读取滑动条数值
min_val = cv2.getTrackbarPos('min_val', 'Canny')
max_val = cv2.getTrackbarPos('max_val', 'Canny')
edges = cv2.Canny(img, min_val, max_val)
# 拼接原图与边缘监测结果图
img_2 = np.hstack((img, edges))
cv2.imshow('Canny', img_2)
cv2.destroyAllWindows()
|
[
"cv2.createTrackbar",
"cv2.GaussianBlur",
"cv2.Canny",
"cv2.waitKey",
"cv2.imshow",
"numpy.hstack",
"cv2.imread",
"cv2.getTrackbarPos",
"cv2.destroyAllWindows",
"cv2.namedWindow"
] |
[((120, 147), 'cv2.namedWindow', 'cv2.namedWindow', (['"""Canny"""', '(0)'], {}), "('Canny', 0)\n", (135, 147), False, 'import cv2\n'), ((156, 211), 'cv2.createTrackbar', 'cv2.createTrackbar', (['"""min_val"""', '"""Canny"""', '(0)', '(255)', 'nothing'], {}), "('min_val', 'Canny', 0, 255, nothing)\n", (174, 211), False, 'import cv2\n'), ((212, 267), 'cv2.createTrackbar', 'cv2.createTrackbar', (['"""max_val"""', '"""Canny"""', '(0)', '(255)', 'nothing'], {}), "('max_val', 'Canny', 0, 255, nothing)\n", (230, 267), False, 'import cv2\n'), ((275, 300), 'cv2.imread', 'cv2.imread', (['"""Tree.jpg"""', '(0)'], {}), "('Tree.jpg', 0)\n", (285, 300), False, 'import cv2\n'), ((317, 349), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['img', '(3, 3)', '(0)'], {}), '(img, (3, 3), 0)\n', (333, 349), False, 'import cv2\n'), ((702, 725), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (723, 725), False, 'import cv2\n'), ((477, 515), 'cv2.getTrackbarPos', 'cv2.getTrackbarPos', (['"""min_val"""', '"""Canny"""'], {}), "('min_val', 'Canny')\n", (495, 515), False, 'import cv2\n'), ((530, 568), 'cv2.getTrackbarPos', 'cv2.getTrackbarPos', (['"""max_val"""', '"""Canny"""'], {}), "('max_val', 'Canny')\n", (548, 568), False, 'import cv2\n'), ((581, 613), 'cv2.Canny', 'cv2.Canny', (['img', 'min_val', 'max_val'], {}), '(img, min_val, max_val)\n', (590, 613), False, 'import cv2\n'), ((646, 669), 'numpy.hstack', 'np.hstack', (['(img, edges)'], {}), '((img, edges))\n', (655, 669), True, 'import numpy as np\n'), ((674, 700), 'cv2.imshow', 'cv2.imshow', (['"""Canny"""', 'img_2'], {}), "('Canny', img_2)\n", (684, 700), False, 'import cv2\n'), ((388, 403), 'cv2.waitKey', 'cv2.waitKey', (['(50)'], {}), '(50)\n', (399, 403), False, 'import cv2\n')]
|
import numpy as np
#import scipy.io as spio
# Utility functions to initialize the problem
from Grid.GridProcessing import Grid
from Shapes.ShapesFunctions import *
from hjComp6D import HJComp
# Specify the file that includes dynamic systems
from dynamics.DubinsCar6D_HRI import *
# Plot options
from plot_options import *
# Solver core
from solver import HJSolver
from Plots.plotting_utilities import *
import math
import os
""" USER INTERFACES
- Define grid
- Generate initial values for grid using shape functions
- Time length for computations
- Initialize plotting option
- Call HJSolver function
"""
'''
Defining parameters for the scenario
'''
# dictionary tracking parameters of the problem
params = {}
# avoid set specs
#idx = int(os.environ["SLURM_ARRAY_TASK_ID"])
# mode type: 'arc', 'rect','basic', None
modes = ['rect', 'rect', 'rect']
velRange = np.linspace(5, 20, 8, endpoint = True)
frontLeft = np.linspace(-2, 30, 17, endpoint = True)
frontRight = np.linspace(-2, 30, 17, endpoint = True)
behindRange = np.linspace(-15, -3, 7, endpoint = True)
print(velRange)
print(frontLeft)
print(behindRange)
state_idx = 0
states = []
for i in range(len(velRange)):
for j in range(len(frontLeft)):
for k in range(len(frontRight)):
for l in range(len(behindRange)):
states.append([[behindRange[l], 1.85, velRange[i]], [frontLeft[j], 1.85, velRange[i]], [frontRight[k], -1.85, velRange[i]]])
state_idx = state_idx + 1
print(state_idx)
# if mode = None, still fill out arbitrary state
print(np.shape(states))
print(len(states[0]))
idx = 0
params['avoid'] = {'lgt_lb': -5.5, 'lgt_ub': 5.5, 'lat_bd':2.0}
params['obst'] = {'state': states[idx] , 'a_max':0.1, 'theta_max':0.05, 'v_lat_max':0.1, 'mode':modes[idx]}
# Look-back length and time step
params['lookback_length'] = 5.0
params['tstep'] = 0.1
params['small_number'] = 1e-5
# num points in each dim
params['grid_points'] = [40, 12, 22, 8, 8, 8]
# road width
params['x1_ll'] = -30
params['x2_ll'] = -30
params['rd_bd_min'] = -3.7
params['x5_ll'] = 0
params['x6_ll'] = 0
params['x1_ul'] = 75
params['x2_ul'] = 75
params['rd_bd_max'] = 3.7
params['x5_ul'] = 35
params['x6_ul'] = 35
# target set specs
params['xr_tar_overtake'] = 10
params['xr_tar_lanekeep'] = -15
# input bounds and model parameters
params['accMax_R'] = 3
params['vLatMax_R'] = 3
params['accMax_H'] = 1
params['vLatMax_H'] = 1
params['accMax_R_sh'] = 3
params['vLatMax_R_sh'] = 3
params['accMax_H_sh'] = 1
params['vLatMax_H_sh'] = 1
params['talpha'] = 0.01
HJComp(params, idx)
|
[
"numpy.shape",
"numpy.linspace",
"hjComp6D.HJComp"
] |
[((866, 902), 'numpy.linspace', 'np.linspace', (['(5)', '(20)', '(8)'], {'endpoint': '(True)'}), '(5, 20, 8, endpoint=True)\n', (877, 902), True, 'import numpy as np\n'), ((917, 955), 'numpy.linspace', 'np.linspace', (['(-2)', '(30)', '(17)'], {'endpoint': '(True)'}), '(-2, 30, 17, endpoint=True)\n', (928, 955), True, 'import numpy as np\n'), ((971, 1009), 'numpy.linspace', 'np.linspace', (['(-2)', '(30)', '(17)'], {'endpoint': '(True)'}), '(-2, 30, 17, endpoint=True)\n', (982, 1009), True, 'import numpy as np\n'), ((1026, 1064), 'numpy.linspace', 'np.linspace', (['(-15)', '(-3)', '(7)'], {'endpoint': '(True)'}), '(-15, -3, 7, endpoint=True)\n', (1037, 1064), True, 'import numpy as np\n'), ((2540, 2559), 'hjComp6D.HJComp', 'HJComp', (['params', 'idx'], {}), '(params, idx)\n', (2546, 2559), False, 'from hjComp6D import HJComp\n'), ((1526, 1542), 'numpy.shape', 'np.shape', (['states'], {}), '(states)\n', (1534, 1542), True, 'import numpy as np\n')]
|
# Copyright 2021 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Code to run a pose estimation with a TFLite MoveNet model."""
import os
import cv2
import numpy as np
from utils import KEYPOINT_DICT
# pylint: disable=g-import-not-at-top
try:
# Import TFLite interpreter from tflite_runtime package if it's available.
from tflite_runtime.interpreter import Interpreter
except ImportError:
# If not, fallback to use the TFLite interpreter from the full TF package.
import tensorflow as tf
Interpreter = tf.lite.Interpreter
# pylint: enable=g-import-not-at-top
class Movenet(object):
"""A wrapper class for a Movenet TFLite pose estimation model."""
# Configure how confidence the model should be on the detected keypoints to
# proceed with using smart cropping logic.
_MIN_CROP_KEYPOINT_SCORE = 0.2
_TORSO_EXPANSION_RATIO = 1.9
_BODY_EXPANSION_RATIO = 1.2
def __init__(self, model_name):
"""Initialize a MoveNet pose estimation model.
Args:
model_name: Name of the TFLite MoveNet model.
"""
# Append TFLITE extension to model_name if there's no extension
_, ext = os.path.splitext(model_name)
if not ext:
model_name += '.tflite'
# Initialize model
interpreter = Interpreter(model_path=model_name, num_threads=4)
interpreter.allocate_tensors()
self._input_index = interpreter.get_input_details()[0]['index']
self._output_index = interpreter.get_output_details()[0]['index']
self._input_height = interpreter.get_input_details()[0]['shape'][1]
self._input_width = interpreter.get_input_details()[0]['shape'][2]
self._interpreter = interpreter
self._crop_region = None
def init_crop_region(self, image_height, image_width):
"""Defines the default crop region.
The function provides the initial crop region (pads the full image from
both sides to make it a square image) when the algorithm cannot reliably
determine the crop region from the previous frame.
Args:
image_height (int): The input image width
image_width (int): The input image height
Returns:
crop_region (dict): The default crop region.
"""
if image_width > image_height:
x_min = 0.0
box_width = 1.0
# Pad the vertical dimension to become a square image.
y_min = (image_height / 2 - image_width / 2) / image_height
box_height = image_width / image_height
else:
y_min = 0.0
box_height = 1.0
# Pad the horizontal dimension to become a square image.
x_min = (image_width / 2 - image_height / 2) / image_width
box_width = image_height / image_width
return {
'y_min': y_min,
'x_min': x_min,
'y_max': y_min + box_height,
'x_max': x_min + box_width,
'height': box_height,
'width': box_width
}
def _torso_visible(self, keypoints):
"""Checks whether there are enough torso keypoints.
This function checks whether the model is confident at predicting one of
the shoulders/hips which is required to determine a good crop region.
Args:
keypoints: Detection result of Movenet model.
Returns:
True/False
"""
left_hip_score = keypoints[KEYPOINT_DICT['left_hip'], 2]
right_hip_score = keypoints[KEYPOINT_DICT['right_hip'], 2]
left_shoulder_score = keypoints[KEYPOINT_DICT['left_shoulder'], 2]
right_shoulder_score = keypoints[KEYPOINT_DICT['right_shoulder'], 2]
left_hip_visible = left_hip_score > Movenet._MIN_CROP_KEYPOINT_SCORE
right_hip_visible = right_hip_score > Movenet._MIN_CROP_KEYPOINT_SCORE
left_shoulder_visible = left_shoulder_score > Movenet._MIN_CROP_KEYPOINT_SCORE
right_shoulder_visible = right_shoulder_score > Movenet._MIN_CROP_KEYPOINT_SCORE
return ((left_hip_visible or right_hip_visible) and
(left_shoulder_visible or right_shoulder_visible))
def _determine_torso_and_body_range(self, keypoints, target_keypoints,
center_y, center_x):
"""Calculates the maximum distance from each keypoints to the center.
The function returns the maximum distances from the two sets of keypoints:
full 17 keypoints and 4 torso keypoints. The returned information will
be used to determine the crop size. See determine_crop_region for more
details.
Args:
keypoints: Detection result of Movenet model.
target_keypoints: The 4 torso keypoints.
center_y (float): Vertical coordinate of the body center.
center_x (float): Horizontal coordinate of the body center.
Returns:
The maximum distance from each keypoints to the center location.
"""
torso_joints = ['left_shoulder', 'right_shoulder', 'left_hip', 'right_hip']
max_torso_yrange = 0.0
max_torso_xrange = 0.0
for joint in torso_joints:
dist_y = abs(center_y - target_keypoints[joint][0])
dist_x = abs(center_x - target_keypoints[joint][1])
if dist_y > max_torso_yrange:
max_torso_yrange = dist_y
if dist_x > max_torso_xrange:
max_torso_xrange = dist_x
max_body_yrange = 0.0
max_body_xrange = 0.0
for joint in KEYPOINT_DICT.keys():
if keypoints[KEYPOINT_DICT[joint], 2] < Movenet._MIN_CROP_KEYPOINT_SCORE:
continue
dist_y = abs(center_y - target_keypoints[joint][0])
dist_x = abs(center_x - target_keypoints[joint][1])
if dist_y > max_body_yrange:
max_body_yrange = dist_y
if dist_x > max_body_xrange:
max_body_xrange = dist_x
return [
max_torso_yrange, max_torso_xrange, max_body_yrange, max_body_xrange
]
def _determine_crop_region(self, keypoints, image_height, image_width):
"""Determines the region to crop the image for the model to run inference on.
The algorithm uses the detected joints from the previous frame to
estimate the square region that encloses the full body of the target
person and centers at the midpoint of two hip joints. The crop size is
determined by the distances between each joints and the center point.
When the model is not confident with the four torso joint predictions,
the function returns a default crop which is the full image padded to
square.
Args:
keypoints: Detection result of Movenet model.
image_height (int): The input image width
image_width (int): The input image height
Returns:
crop_region (dict): The crop region to run inference on.
"""
# Convert keypoint index to human-readable names.
target_keypoints = {}
for joint in KEYPOINT_DICT.keys():
target_keypoints[joint] = [
keypoints[KEYPOINT_DICT[joint], 0] * image_height,
keypoints[KEYPOINT_DICT[joint], 1] * image_width
]
# Calculate crop region if the torso is visible.
if self._torso_visible(keypoints):
center_y = (target_keypoints['left_hip'][0] +
target_keypoints['right_hip'][0]) / 2
center_x = (target_keypoints['left_hip'][1] +
target_keypoints['right_hip'][1]) / 2
(max_torso_yrange, max_torso_xrange, max_body_yrange,
max_body_xrange) = self._determine_torso_and_body_range(
keypoints, target_keypoints, center_y, center_x)
crop_length_half = np.amax([
max_torso_xrange * Movenet._TORSO_EXPANSION_RATIO,
max_torso_yrange * Movenet._TORSO_EXPANSION_RATIO,
max_body_yrange * Movenet._BODY_EXPANSION_RATIO,
max_body_xrange * Movenet._BODY_EXPANSION_RATIO
])
# Adjust crop length so that it is still within the image border
distances_to_border = np.array(
[center_x, image_width - center_x, center_y, image_height - center_y])
crop_length_half = np.amin(
[crop_length_half, np.amax(distances_to_border)])
# If the body is large enough, there's no need to apply cropping logic.
if crop_length_half > max(image_width, image_height) / 2:
return self.init_crop_region(image_height, image_width)
# Calculate the crop region that nicely covers the full body.
else:
crop_length = crop_length_half * 2
crop_corner = [center_y - crop_length_half, center_x - crop_length_half]
return {
'y_min':
crop_corner[0] / image_height,
'x_min':
crop_corner[1] / image_width,
'y_max': (crop_corner[0] + crop_length) / image_height,
'x_max': (crop_corner[1] + crop_length) / image_width,
'height': (crop_corner[0] + crop_length) / image_height -
crop_corner[0] / image_height,
'width': (crop_corner[1] + crop_length) / image_width -
crop_corner[1] / image_width
}
# Return the initial crop regsion if the torso isn't visible.
else:
return self.init_crop_region(image_height, image_width)
def _crop_and_resize(self, image, crop_region, crop_size):
"""Crops and resize the image to prepare for the model input."""
y_min, x_min, y_max, x_max = [
crop_region['y_min'], crop_region['x_min'], crop_region['y_max'],
crop_region['x_max']
]
crop_top = int(0 if y_min < 0 else y_min * image.shape[0])
crop_bottom = int(image.shape[0] if y_max >= 1 else y_max * image.shape[0])
crop_left = int(0 if x_min < 0 else x_min * image.shape[1])
crop_right = int(image.shape[1] if x_max >= 1 else x_max * image.shape[1])
padding_top = int(0 - y_min * image.shape[0] if y_min < 0 else 0)
padding_bottom = int((y_max - 1) * image.shape[0] if y_max >= 1 else 0)
padding_left = int(0 - x_min * image.shape[1] if x_min < 0 else 0)
padding_right = int((x_max - 1) * image.shape[1] if x_max >= 1 else 0)
# Crop and resize image
output_image = image[crop_top:crop_bottom, crop_left:crop_right]
output_image = cv2.copyMakeBorder(output_image, padding_top, padding_bottom,
padding_left, padding_right,
cv2.BORDER_CONSTANT)
output_image = cv2.resize(output_image, (crop_size[0], crop_size[1]))
return output_image
def _run_detector(self, image, crop_region, crop_size):
"""Runs model inference on the cropped region.
The function runs the model inference on the cropped region and updates
the model output to the original image coordinate system.
Args:
image: The input image.
crop_region: The region of interest to run inference on.
crop_size: The size of the crop region.
Returns:
An array of shape [17, 3] representing the keypoint absolute coordinates
and scores.
"""
input_image = self._crop_and_resize(image, crop_region, crop_size=crop_size)
input_image = input_image.astype(dtype=np.uint8)
self._interpreter.set_tensor(self._input_index,
np.expand_dims(input_image, axis=0))
self._interpreter.invoke()
keypoints_with_scores = self._interpreter.get_tensor(self._output_index)
keypoints_with_scores = np.squeeze(keypoints_with_scores)
# Update the coordinates.
for idx in KEYPOINT_DICT.values():
keypoints_with_scores[idx, 0] = crop_region[
'y_min'] + crop_region['height'] * keypoints_with_scores[idx, 0]
keypoints_with_scores[idx, 1] = crop_region[
'x_min'] + crop_region['width'] * keypoints_with_scores[idx, 1]
return keypoints_with_scores
def detect(self, input_image, reset_crop_region=False):
"""Run detection on an input image.
Args:
input_image: A [height, width, 3] RGB image. Note that height and width
can be anything since the image will be immediately resized according to
the needs of the model within this function.
reset_crop_region: Whether to use the crop region inferred from the
previous detection result to improve accuracy. Set to True if this is a
frame from a video. Set to False if this is a static image. Default
value is True.
Returns:
An array of shape [17, 3] representing the keypoint coordinates and
scores.
"""
image_height, image_width, _ = input_image.shape
if (self._crop_region is None) or reset_crop_region:
# Set crop region for the first frame.
self._crop_region = self.init_crop_region(image_height, image_width)
# Detect pose using the crop region inferred from the detection result in
# the previous frame
keypoint_with_scores = self._run_detector(
input_image,
self._crop_region,
crop_size=[self._input_height, self._input_width])
# Calculate the crop region for the next frame
self._crop_region = self._determine_crop_region(keypoint_with_scores,
image_height, image_width)
return keypoint_with_scores
|
[
"utils.KEYPOINT_DICT.keys",
"cv2.copyMakeBorder",
"numpy.expand_dims",
"numpy.amax",
"tflite_runtime.interpreter.Interpreter",
"os.path.splitext",
"numpy.array",
"utils.KEYPOINT_DICT.values",
"numpy.squeeze",
"cv2.resize"
] |
[((1666, 1694), 'os.path.splitext', 'os.path.splitext', (['model_name'], {}), '(model_name)\n', (1682, 1694), False, 'import os\n'), ((1783, 1832), 'tflite_runtime.interpreter.Interpreter', 'Interpreter', ([], {'model_path': 'model_name', 'num_threads': '(4)'}), '(model_path=model_name, num_threads=4)\n', (1794, 1832), False, 'from tflite_runtime.interpreter import Interpreter\n'), ((5703, 5723), 'utils.KEYPOINT_DICT.keys', 'KEYPOINT_DICT.keys', ([], {}), '()\n', (5721, 5723), False, 'from utils import KEYPOINT_DICT\n'), ((7124, 7144), 'utils.KEYPOINT_DICT.keys', 'KEYPOINT_DICT.keys', ([], {}), '()\n', (7142, 7144), False, 'from utils import KEYPOINT_DICT\n'), ((10404, 10519), 'cv2.copyMakeBorder', 'cv2.copyMakeBorder', (['output_image', 'padding_top', 'padding_bottom', 'padding_left', 'padding_right', 'cv2.BORDER_CONSTANT'], {}), '(output_image, padding_top, padding_bottom, padding_left,\n padding_right, cv2.BORDER_CONSTANT)\n', (10422, 10519), False, 'import cv2\n'), ((10611, 10665), 'cv2.resize', 'cv2.resize', (['output_image', '(crop_size[0], crop_size[1])'], {}), '(output_image, (crop_size[0], crop_size[1]))\n', (10621, 10665), False, 'import cv2\n'), ((11604, 11637), 'numpy.squeeze', 'np.squeeze', (['keypoints_with_scores'], {}), '(keypoints_with_scores)\n', (11614, 11637), True, 'import numpy as np\n'), ((11684, 11706), 'utils.KEYPOINT_DICT.values', 'KEYPOINT_DICT.values', ([], {}), '()\n', (11704, 11706), False, 'from utils import KEYPOINT_DICT\n'), ((7828, 8051), 'numpy.amax', 'np.amax', (['[max_torso_xrange * Movenet._TORSO_EXPANSION_RATIO, max_torso_yrange *\n Movenet._TORSO_EXPANSION_RATIO, max_body_yrange * Movenet.\n _BODY_EXPANSION_RATIO, max_body_xrange * Movenet._BODY_EXPANSION_RATIO]'], {}), '([max_torso_xrange * Movenet._TORSO_EXPANSION_RATIO, \n max_torso_yrange * Movenet._TORSO_EXPANSION_RATIO, max_body_yrange *\n Movenet._BODY_EXPANSION_RATIO, max_body_xrange * Movenet.\n _BODY_EXPANSION_RATIO])\n', (7835, 8051), True, 'import numpy as np\n'), ((8186, 8265), 'numpy.array', 'np.array', (['[center_x, image_width - center_x, center_y, image_height - center_y]'], {}), '([center_x, image_width - center_x, center_y, image_height - center_y])\n', (8194, 8265), True, 'import numpy as np\n'), ((11430, 11465), 'numpy.expand_dims', 'np.expand_dims', (['input_image'], {'axis': '(0)'}), '(input_image, axis=0)\n', (11444, 11465), True, 'import numpy as np\n'), ((8340, 8368), 'numpy.amax', 'np.amax', (['distances_to_border'], {}), '(distances_to_border)\n', (8347, 8368), True, 'import numpy as np\n')]
|
from turtle import st
import gym
import numpy as np
import matplotlib.pyplot as plt
import random
import pandas as pd
from tqdm import tqdm
import os
class BaiscStockEnv(gym.Env):
def __init__(self, dir:str, window_size:int, mode:str = 'csv', do_fast:bool = True):
self.files_name = os.listdir(dir)
self.dir_path = dir
self.window_size = window_size
self.mode = mode
self.do_fast = do_fast
if self.do_fast:
self.load_files()
def load_files(self):
self.file_list = []
print("\n\n\n########Loading Files########\n")
for f in tqdm(self.files_name):
if self.mode == 'csv':
file = pd.read_csv(os.path.join(self.dir_path, f))
elif self.mode == 'excel':
file = pd.read_excel(os.path.join(self.dir_path, f)) # open dataframe files
self.file_list.append(file)
def reset(self):
super().reset()
if not self.do_fast:
self.file_name = np.random.choice(self.files_name, 1, replace = False)[0] # 무작위로 파일 오픈 순서 배정
else:
self.file_index = np.random.randint(0, len(self.file_list))
self.current_time_index = 0 # 현재 열린 dataframe에서 self.start_index + self.current_time_index 위치를 나타냄. self.window_size 보다 클 수 없음.
self.model_money = 10000 # model로 매도 매수 했을 시 남은 예산
self.human_money = 10000 # holding 했을시의 남은 예산
self.model_history = [self.model_money]
self.human_history = [self.human_money]
self.file_open()
def file_open(self):
if self.do_fast:
self.current_file = self.file_list[self.file_index]
elif self.mode == 'csv':
self.current_file = pd.read_csv(os.path.join(self.dir_path, self.file_name)) # open dataframe files
elif self.mode =='excel':
self.current_file = pd.read_excel(os.path.join(self.dir_path, self.file_name)) # open dataframe files
self.start_index = random.randint(0, self.current_file.shape[0] - self.window_size) # randomly choose start index
def next(self): #return done
if self.current_time_index == self.start_index + self.window_size - 1:
return True
else:
self.current_time_index += 1
return False
def step(self, action:int):
# step => state, reward, done
# action이 policy net
done = self.next()
state = self.current_file.iloc[self.current_time_index].to_numpy()
y = state[-1]
reward = 1
return state, reward, done
def render(self):
plt.plot(self.model_history)
plt.plot(self.human_history)
plt.show()
if __name__ == '__main__':
print("starting environment test")
DIR_PATH = "/Users/seonseung-yeob/Downloads/20220308222144"
stock_env = BaiscStockEnv(dir = DIR_PATH, window_size = 10, mode = 'excel')
for i in range(1000):
stock_env.reset()
|
[
"tqdm.tqdm",
"matplotlib.pyplot.show",
"random.randint",
"matplotlib.pyplot.plot",
"numpy.random.choice",
"os.path.join",
"os.listdir"
] |
[((297, 312), 'os.listdir', 'os.listdir', (['dir'], {}), '(dir)\n', (307, 312), False, 'import os\n'), ((626, 647), 'tqdm.tqdm', 'tqdm', (['self.files_name'], {}), '(self.files_name)\n', (630, 647), False, 'from tqdm import tqdm\n'), ((2004, 2068), 'random.randint', 'random.randint', (['(0)', '(self.current_file.shape[0] - self.window_size)'], {}), '(0, self.current_file.shape[0] - self.window_size)\n', (2018, 2068), False, 'import random\n'), ((2636, 2664), 'matplotlib.pyplot.plot', 'plt.plot', (['self.model_history'], {}), '(self.model_history)\n', (2644, 2664), True, 'import matplotlib.pyplot as plt\n'), ((2673, 2701), 'matplotlib.pyplot.plot', 'plt.plot', (['self.human_history'], {}), '(self.human_history)\n', (2681, 2701), True, 'import matplotlib.pyplot as plt\n'), ((2710, 2720), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2718, 2720), True, 'import matplotlib.pyplot as plt\n'), ((1031, 1082), 'numpy.random.choice', 'np.random.choice', (['self.files_name', '(1)'], {'replace': '(False)'}), '(self.files_name, 1, replace=False)\n', (1047, 1082), True, 'import numpy as np\n'), ((719, 749), 'os.path.join', 'os.path.join', (['self.dir_path', 'f'], {}), '(self.dir_path, f)\n', (731, 749), False, 'import os\n'), ((1756, 1799), 'os.path.join', 'os.path.join', (['self.dir_path', 'self.file_name'], {}), '(self.dir_path, self.file_name)\n', (1768, 1799), False, 'import os\n'), ((827, 857), 'os.path.join', 'os.path.join', (['self.dir_path', 'f'], {}), '(self.dir_path, f)\n', (839, 857), False, 'import os\n'), ((1904, 1947), 'os.path.join', 'os.path.join', (['self.dir_path', 'self.file_name'], {}), '(self.dir_path, self.file_name)\n', (1916, 1947), False, 'import os\n')]
|
import unittest
import os
import numpy as np
from CGMFtk import histories as fh
class TestGammaProperties(unittest.TestCase):
# nubarg calculations
def test_nubarg_for_events(self):
"""
test the nubargtot function calculation (average gammas per event)
"""
nread = 10
#h = fh.Histories('92235_18MeV.cgmf',nevents=nread)
h = fh.Histories('../../utils/cgmf/tests/u235nf-18MeV-events/histories.cgmf.parallel.0.reference',nevents=nread)
nug = h.getNugtot()
self.assertEqual(np.mean(nug),h.nubargtot())
def test_nubarg_for_fragments(self):
"""
test the nubarg function calculation (average gammas per fragment)
"""
nread = 10
#h = fh.Histories('92235_18MeV.cgmf',nevents=nread)
h = fh.Histories('../../utils/cgmf/tests/u235nf-18MeV-events/histories.cgmf.parallel.0.reference',nevents=nread)
nug = h.getNug()
self.assertEqual(np.mean(nug),h.nubarg())
# we tested the mean list calculation in the neutron tests
# P(nug) tests
def test_gamma_multiplicity_distribution(self):
"""
test the gamma multiplicity distribution, P(N_gamma)
"""
nread = 10
#h = fh.Histories('92235_18MeV.cgmf',nevents=nread)
h = fh.Histories('../../utils/cgmf/tests/u235nf-18MeV-events/histories.cgmf.parallel.0.reference',nevents=nread)
nug,pnug = h.Pnug()
nugvals = h.getNugtot()
nugmax = np.max(nugvals)
self.assertEqual(nug[-1],nugmax)
for i in range(nugmax+1):
prob = (len(nugvals[nugvals==i]))/float(nread)
self.assertEqual(prob,pnug[i])
# energy thresholds
def test_gamma_spectrum_energy_threshold(self):
"""
test the implementation of the gamma-ray energy thresholds
specifically in the PFGS, but is constructed the same elsewhere
"""
nread = 10
#h = fh.Histories('92235_18MeV.cgmf',nevents=nread)
h = fh.Histories('../../utils/cgmf/tests/u235nf-18MeV-events/histories.cgmf.parallel.0.reference',nevents=nread)
Eth = 0.5
eng,pfgs = h.pfgs(Eth=Eth)
eng0,pfgs0 = h.pfgs()
emin = eng[pfgs>0]
emin0 = eng0[pfgs0>0]
if (Eth>0):
self.assertTrue(emin0[0]<emin[0])
else:
self.assertEqual(emin0[0],emin[0])
if __name__ == '__main__':
unittest.main()
|
[
"unittest.main",
"numpy.max",
"numpy.mean",
"CGMFtk.histories.Histories"
] |
[((2422, 2437), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2435, 2437), False, 'import unittest\n'), ((383, 502), 'CGMFtk.histories.Histories', 'fh.Histories', (['"""../../utils/cgmf/tests/u235nf-18MeV-events/histories.cgmf.parallel.0.reference"""'], {'nevents': 'nread'}), "(\n '../../utils/cgmf/tests/u235nf-18MeV-events/histories.cgmf.parallel.0.reference'\n , nevents=nread)\n", (395, 502), True, 'from CGMFtk import histories as fh\n'), ((805, 924), 'CGMFtk.histories.Histories', 'fh.Histories', (['"""../../utils/cgmf/tests/u235nf-18MeV-events/histories.cgmf.parallel.0.reference"""'], {'nevents': 'nread'}), "(\n '../../utils/cgmf/tests/u235nf-18MeV-events/histories.cgmf.parallel.0.reference'\n , nevents=nread)\n", (817, 924), True, 'from CGMFtk import histories as fh\n'), ((1302, 1421), 'CGMFtk.histories.Histories', 'fh.Histories', (['"""../../utils/cgmf/tests/u235nf-18MeV-events/histories.cgmf.parallel.0.reference"""'], {'nevents': 'nread'}), "(\n '../../utils/cgmf/tests/u235nf-18MeV-events/histories.cgmf.parallel.0.reference'\n , nevents=nread)\n", (1314, 1421), True, 'from CGMFtk import histories as fh\n'), ((1488, 1503), 'numpy.max', 'np.max', (['nugvals'], {}), '(nugvals)\n', (1494, 1503), True, 'import numpy as np\n'), ((2013, 2132), 'CGMFtk.histories.Histories', 'fh.Histories', (['"""../../utils/cgmf/tests/u235nf-18MeV-events/histories.cgmf.parallel.0.reference"""'], {'nevents': 'nread'}), "(\n '../../utils/cgmf/tests/u235nf-18MeV-events/histories.cgmf.parallel.0.reference'\n , nevents=nread)\n", (2025, 2132), True, 'from CGMFtk import histories as fh\n'), ((545, 557), 'numpy.mean', 'np.mean', (['nug'], {}), '(nug)\n', (552, 557), True, 'import numpy as np\n'), ((964, 976), 'numpy.mean', 'np.mean', (['nug'], {}), '(nug)\n', (971, 976), True, 'import numpy as np\n')]
|
import numpy as np
from ndindex import IntegerArray
class TimeIntegerArray:
def setup(self):
self.ia = IntegerArray([[1, 2], [2, -1]]*100)
def time_constructor_list(self):
IntegerArray([[1, 2], [2, -1]]*100)
def time_constructor_array(self):
IntegerArray(self.ia.array)
def time_constructor_invalid(self):
try:
IntegerArray(np.array([0.5]))
except TypeError:
pass
def time_reduce(self):
self.ia.reduce()
def time_reduce_shape(self):
self.ia.reduce(10)
def time_reduce_shape_error(self):
try:
self.ia.reduce(2)
except IndexError:
pass
def time_newshape(self):
self.ia.newshape((10, 5))
def time_isempty(self):
self.ia.isempty()
def time_isempty_shape(self):
self.ia.isempty((10, 5))
|
[
"numpy.array",
"ndindex.IntegerArray"
] |
[((116, 153), 'ndindex.IntegerArray', 'IntegerArray', (['([[1, 2], [2, -1]] * 100)'], {}), '([[1, 2], [2, -1]] * 100)\n', (128, 153), False, 'from ndindex import IntegerArray\n'), ((198, 235), 'ndindex.IntegerArray', 'IntegerArray', (['([[1, 2], [2, -1]] * 100)'], {}), '([[1, 2], [2, -1]] * 100)\n', (210, 235), False, 'from ndindex import IntegerArray\n'), ((281, 308), 'ndindex.IntegerArray', 'IntegerArray', (['self.ia.array'], {}), '(self.ia.array)\n', (293, 308), False, 'from ndindex import IntegerArray\n'), ((388, 403), 'numpy.array', 'np.array', (['[0.5]'], {}), '([0.5])\n', (396, 403), True, 'import numpy as np\n')]
|
import csv
from tempfile import NamedTemporaryFile
import shutil
import numpy as np
""" import csv
with open('/ws2122-lspm/upload_eventlog/data.csv', newline='') as f:
reader = csv.reader(f)
row1 = next(reader) # gets the first line
for row in reader:
print(row) # prints rows 2 and onward
"""
with open('/ws2122-lspm/upload_eventlog/data.csv') as csv_file:
# creating an object of csv reader
# with the delimiter as ,
csv_reader = csv.reader(csv_file, delimiter=',')
# list to store the names of columns
list_of_column_names = []
# loop to iterate through the rows of csv
for row in csv_reader:
# adding the first row
list_of_column_names.append(row)
# breaking the loop after the
# first iteration itself
break
# printing the result
# print("List of column names : ",
vars = []
array = np.array(list_of_column_names)
for column in array:
# hells[column]=list_of_column_names[0][column]
for j in column:
print(j)
vars.append(j)
print()
print(vars[3])
|
[
"csv.reader",
"numpy.array"
] |
[((898, 928), 'numpy.array', 'np.array', (['list_of_column_names'], {}), '(list_of_column_names)\n', (906, 928), True, 'import numpy as np\n'), ((476, 511), 'csv.reader', 'csv.reader', (['csv_file'], {'delimiter': '""","""'}), "(csv_file, delimiter=',')\n", (486, 511), False, 'import csv\n')]
|
import numpy as np
from .coordinates import RegularCoords, SeparatedCoords, UnstructuredCoords
from .field import Field
from .cartesian_grid import CartesianGrid
def make_uniform_grid(dims, extent, center=0, has_center=False):
'''Create a uniformly-spaced :class:`Grid` of a certain shape and size.
Parameters
----------
dims : scalar or ndarray
The number of points in each dimension. If this is a scalar, it will
be multiplexed over all dimensions.
extent : scalar or ndarray
The total extent of the grid in each dimension.
center : scalar or ndarray
The center point. The grid will by symmetric around this point.
has_center : boolean
Does the grid has to have the center as one of its points. If this is
False, this does not mean that the grid will not have the center.
Returns
-------
Grid
A :class:`Grid` with :class:`RegularCoords`.
'''
num_dims = max(np.array([dims]).shape[-1], np.array([extent]).shape[-1], np.array([center]).shape[-1])
dims = (np.ones(num_dims) * dims).astype('int')
extent = (np.ones(num_dims) * extent).astype('float')
center = (np.ones(num_dims) * center).astype('float')
delta = extent / dims
zero = -extent / 2 + center + delta / 2
if has_center:
zero -= delta / 2 * (1 - np.mod(dims, 2))
return CartesianGrid(RegularCoords(delta, dims, zero))
def make_pupil_grid(dims, diameter=1):
'''Makes a new :class:`Grid`, meant for descretisation of a pupil-plane wavefront.
This grid is symmetric around the origin, and therefore has no point exactly on
the origin for an even number of pixels.
Parameters
----------
dims : ndarray or integer
The number of pixels per dimension. If this is an integer, this number
of pixels is used for all dimensions.
diameter : ndarray or scalar
The diameter of the grid in each dimension. If this is a scalar, this diameter
is used for all dimensions.
Returns
-------
Grid
A :class:`CartesianGrid` with :class:`RegularCoords`.
'''
diameter = (np.ones(2) * diameter).astype('float')
dims = (np.ones(2) * dims).astype('int')
delta = diameter / (dims - 1)
zero = -diameter / 2
return CartesianGrid(RegularCoords(delta, dims, zero))
def make_focal_grid(pupil_grid, q=1, num_airy=None, focal_length=1, wavelength=1):
from ..fourier import make_fft_grid
f_lambda = focal_length * wavelength
if num_airy is None:
fov = 1
else:
fov = (num_airy * np.ones(pupil_grid.ndim, dtype='float')) / (pupil_grid.shape / 2)
if np.max(fov) > 1:
import warnings
warnings.warn('Focal grid is larger than the maximum allowed angle (fov=%.03f). You may see wrapping when doing propagations.' % np.max(fov), stacklevel=2)
uv = make_fft_grid(pupil_grid, q, fov)
focal_grid = uv.scaled(f_lambda / (2*np.pi))
return focal_grid
def make_hexagonal_grid(circum_diameter, n_rings, pointy_top=False, center=None):
'''Make a regular hexagonal grid.
Parameters
----------
circum_diameter : scalar
The circum diameter of the hexagons in the grid.
n_rings : integer
The number of rings in the grid.
pointy_top : boolean
If the hexagons contained in the grid.
center : ndarray
The center of the grid in cartesian coordinates.
Returns
-------
Grid
A :class:`CartesianGrid` with `UnstructuredCoords`, indicating the
center of the hexagons.
'''
if center is None:
center = np.zeros(2)
apothem = circum_diameter * np.sqrt(3) / 4
q = [0]
r = [0]
for n in range(1,n_rings+1):
#top
q += list(range(n,0,-1))
r += list(range(0,n))
# right top
q += list(range(0,-n,-1))
r += [n] * n
# right bottom
q += [-n] * n
r += list(range(n,0,-1))
# bottom
q += list(range(-n,0))
r += list(range(0,-n,-1))
# left bottom
q += list(range(0,n))
r += [-n] * n
# left top
q += [n] * n
r += list(range(-n,0))
x = (-np.array(q) + np.array(r)) * circum_diameter / 2 + center[0]
y = (np.array(q) + np.array(r)) * apothem * 2 + center[1]
weight = 2 * apothem**2 * np.sqrt(3)
if pointy_top:
return CartesianGrid(UnstructuredCoords((x, y)), weight)
else:
return CartesianGrid(UnstructuredCoords((y, x)), weight)
def make_chebyshev_grid(dims, minimum=None, maximum=None):
if minimum is None:
minimum = -1
if maximum is None:
maximum = 1
dims = np.array(dims)
minimum = np.ones(len(dims)) * minimum
maximum = np.ones(len(dims)) * maximum
middles = (minimum + maximum) / 2
intervals = (maximum - minimum) / 2
sep_coords = []
for dim, middle, interval in zip(dims, middles, intervals):
c = np.cos(np.pi * (2 * np.arange(dim) + 1) / (2.0 * dim))
c = middle + interval * c
sep_coords.append(c)
return CartesianGrid(SeparatedCoords(sep_coords))
def make_supersampled_grid(grid, oversampling):
'''Make a new grid that oversamples by a factor `oversampling`.
.. note ::
The Grid `grid` must be a grid with separable coordinates.
Parameters
----------
grid : Grid
The grid that we want to oversample.
oversampling : integer or scalar or ndarray
The factor by which to oversample. If this is a scalar, it will be rounded to
the nearest integer. If this is an array, a different oversampling factor will
be used for each dimension.
Returns
-------
Grid
The oversampled grid.
'''
oversampling = (np.round(oversampling)).astype('int')
if grid.is_regular:
delta_new = grid.delta / oversampling
zero_new = grid.zero - grid.delta / 2 + delta_new / 2
dims_new = grid.dims * oversampling
return grid.__class__(RegularCoords(delta_new, dims_new, zero_new))
elif grid.is_separated:
raise NotImplementedError()
raise ValueError('Cannot create a supersampled grid from a non-separated grid.')
def make_subsampled_grid(grid, undersampling):
'''Make a new grid that undersamples by a factor `undersampling`.
.. note ::
The dimensions of the `grid` must be divisible by `undersampling`.
Parameters
----------
grid : Grid
The grid that we want to oversample.
undersampling : integer or scalar or ndarray
The factor by which to undersample. If this is a scalar, it will be rounded to
the nearest integer. If this is an array, a different undersampling factor will
be used for each dimension.
Returns
-------
Grid
The undersampled grid.
'''
undersampling = (np.round(undersampling)).astype('int')
if grid.is_regular:
delta_new = grid.delta * undersampling
zero_new = grid.zero - grid.delta / 2 + delta_new / 2
dims_new = grid.dims // undersampling
return grid.__class__(RegularCoords(delta_new, dims_new, zero_new))
elif grid.is_separated:
raise NotImplementedError()
raise ValueError("Cannot create a subsampled grid from a non-separated grid.")
def subsample_field(field, subsampling, new_grid=None):
'''Average the field over subsampling pixels in each dimension.
.. note ::
The dimensions of the grid of `field` must be divisible by `subsampling`.
Parameters
----------
field : Field
The field to subsample. The grid of this field must have the right
dimensions to be able to be subsampled.
subsampling : integer or scalar or ndarray
The subsampling factor. If this is a scalar, it will be rounded to the
nearest integer. If this is an array, the subsampling factor will be
different for each dimension.
new_grid : Grid
If this grid is given, no new grid will be calculated and this grid will
be used instead. This saves on calculation time if your new grid is already
known beforehand.
Returns
-------
Field
The subsampled field.
'''
subsampling = (np.round(subsampling)).astype('int')
if new_grid is None:
new_grid = make_subsampled_grid(field.grid, subsampling)
reshape = []
axes = []
for i, s in enumerate(new_grid.shape):
reshape.extend([s, subsampling])
axes.append(2 * i + 1)
if field.tensor_order > 0:
reshape = list(field.tensor_shape) + reshape
axes = np.array(axes) + field.tensor_order
new_shape = list(field.tensor_shape) + [-1]
else:
new_shape = [-1]
if field.grid.is_regular:
# All weights will be the same, so a simple "mean" will do.
return Field(field.reshape(tuple(reshape)).mean(axis=tuple(axes)).reshape(tuple(new_shape)), new_grid)
else:
# Some weights will be different so calculate weighted mean instead.
weights = field.grid.weights
w = weights.reshape(tuple(reshape)).sum(axis=tuple(axes))
f = (field*weights).reshape(tuple(reshape)).sum(axis=tuple(axes))
return Field((f / w).reshape(tuple(new_shape)), new_grid)
def evaluate_supersampled(field_generator, grid, oversampling):
'''Evaluate a Field generator on `grid`, with an oversampling.
Parameters
----------
field_generator : Field generator
The field generator to evaluate.
grid : Grid
The grid on which to evaluate `field_generator`.
oversampling : integer or scalar or ndarray
The factor by which to oversample. If this is a scalar, it will be rounded to
the nearest integer. If this is an array, a different oversampling factor will
be used for each dimension.
Returns
-------
Field
The evaluated field.
'''
new_grid = make_supersampled_grid(grid, oversampling)
field = field_generator(new_grid)
return subsample_field(field, oversampling, grid)
|
[
"numpy.zeros",
"numpy.ones",
"numpy.mod",
"numpy.max",
"numpy.array",
"numpy.arange",
"numpy.round",
"numpy.sqrt"
] |
[((4234, 4248), 'numpy.array', 'np.array', (['dims'], {}), '(dims)\n', (4242, 4248), True, 'import numpy as np\n'), ((2457, 2468), 'numpy.max', 'np.max', (['fov'], {}), '(fov)\n', (2463, 2468), True, 'import numpy as np\n'), ((3324, 3335), 'numpy.zeros', 'np.zeros', (['(2)'], {}), '(2)\n', (3332, 3335), True, 'import numpy as np\n'), ((3938, 3948), 'numpy.sqrt', 'np.sqrt', (['(3)'], {}), '(3)\n', (3945, 3948), True, 'import numpy as np\n'), ((3367, 3377), 'numpy.sqrt', 'np.sqrt', (['(3)'], {}), '(3)\n', (3374, 3377), True, 'import numpy as np\n'), ((5219, 5241), 'numpy.round', 'np.round', (['oversampling'], {}), '(oversampling)\n', (5227, 5241), True, 'import numpy as np\n'), ((6210, 6233), 'numpy.round', 'np.round', (['undersampling'], {}), '(undersampling)\n', (6218, 6233), True, 'import numpy as np\n'), ((7461, 7482), 'numpy.round', 'np.round', (['subsampling'], {}), '(subsampling)\n', (7469, 7482), True, 'import numpy as np\n'), ((7793, 7807), 'numpy.array', 'np.array', (['axes'], {}), '(axes)\n', (7801, 7807), True, 'import numpy as np\n'), ((889, 905), 'numpy.array', 'np.array', (['[dims]'], {}), '([dims])\n', (897, 905), True, 'import numpy as np\n'), ((917, 935), 'numpy.array', 'np.array', (['[extent]'], {}), '([extent])\n', (925, 935), True, 'import numpy as np\n'), ((947, 965), 'numpy.array', 'np.array', (['[center]'], {}), '([center])\n', (955, 965), True, 'import numpy as np\n'), ((987, 1004), 'numpy.ones', 'np.ones', (['num_dims'], {}), '(num_dims)\n', (994, 1004), True, 'import numpy as np\n'), ((1038, 1055), 'numpy.ones', 'np.ones', (['num_dims'], {}), '(num_dims)\n', (1045, 1055), True, 'import numpy as np\n'), ((1093, 1110), 'numpy.ones', 'np.ones', (['num_dims'], {}), '(num_dims)\n', (1100, 1110), True, 'import numpy as np\n'), ((1246, 1261), 'numpy.mod', 'np.mod', (['dims', '(2)'], {}), '(dims, 2)\n', (1252, 1261), True, 'import numpy as np\n'), ((1974, 1984), 'numpy.ones', 'np.ones', (['(2)'], {}), '(2)\n', (1981, 1984), True, 'import numpy as np\n'), ((2022, 2032), 'numpy.ones', 'np.ones', (['(2)'], {}), '(2)\n', (2029, 2032), True, 'import numpy as np\n'), ((2385, 2424), 'numpy.ones', 'np.ones', (['pupil_grid.ndim'], {'dtype': '"""float"""'}), "(pupil_grid.ndim, dtype='float')\n", (2392, 2424), True, 'import numpy as np\n'), ((2623, 2634), 'numpy.max', 'np.max', (['fov'], {}), '(fov)\n', (2629, 2634), True, 'import numpy as np\n'), ((3804, 3815), 'numpy.array', 'np.array', (['r'], {}), '(r)\n', (3812, 3815), True, 'import numpy as np\n'), ((3857, 3868), 'numpy.array', 'np.array', (['q'], {}), '(q)\n', (3865, 3868), True, 'import numpy as np\n'), ((3871, 3882), 'numpy.array', 'np.array', (['r'], {}), '(r)\n', (3879, 3882), True, 'import numpy as np\n'), ((3790, 3801), 'numpy.array', 'np.array', (['q'], {}), '(q)\n', (3798, 3801), True, 'import numpy as np\n'), ((4507, 4521), 'numpy.arange', 'np.arange', (['dim'], {}), '(dim)\n', (4516, 4521), True, 'import numpy as np\n')]
|
'''
Class for all visualizations. Pass in Interact class, which contains all history variables
related to agent's actions, state and reward observations.
This file is currently designed to work with Binary_Maze.py
'''
import numpy as np
import matplotlib.pyplot as plt
import os, sys, glob
import math
import pickle
class Analysis:
'''
These are trial-level visualizations. They do not work for comparing experiment-level stats.
Cross session comparisons are implemented under Experiment.py
'''
def __init__(self, exp_path, sess_id, Maze, Interact, save_log = True):
self.exp_path = exp_path
self.sess_id = sess_id
self.Map = Maze
# History of [s_t, a_t, s_t+1] tupples
self.state_action_history = Interact.state_act_history_trials
# History of combined Interact output to Agent
self.state_obs_history = Interact.state_obs_history_trials
self.value_history = Interact.agent_qvalues_history_trials
self.maze_type = Interact.maze_type
self.novelty_history = Interact.agent_novelty_history_trials
self.init_sub_session_path()
if save_log:
pickle.dump(Interact.state_act_history_trials, open(f'{self.sess_output_path}/state_act_history.p', 'wb'))
self.cumulative_rewards = [] # for all trials
self.all_timesteps_trial = [] # for the entire trial
def init_sub_session_path(self):
# Make session folder
self.sess_output_path = self.exp_path + '/sess_' + str(self.sess_id) + '/'
if not os.path.exists(self.sess_output_path):
os.mkdir(self.sess_output_path)
def visualize(self, dpi = 300):
print('\nLogging experiment data..\n\n')
self.compare_total_steps_till_reward(dpi)
self.visualize_reward_all_episodes(dpi)
if self.maze_type == 'binary':
self.visualize_final_states(dpi)
self.log_reward(dpi = dpi)
self.visualize_state_values(dpi)
self.visualize_state_novelty(dpi)
self.visualize_timesteps_per_episode(dpi)
def visualize_reward_all_episodes(self, dpi, plot = False):
for trial_nb, trial_i in enumerate(self.state_obs_history):
nb_episodes = len(trial_i)
reward_record = []
for episode_nb, episode_j in enumerate(trial_i):
reward = episode_j[-1][-2]
reward_record.append(reward)
if plot:
plt.figure(figsize = (10,1))
x = np.arange(nb_episodes)
plt.scatter(x + 1, reward_record,
s = 20,
facecolor = (0,0,0,0),
linewidths = 0.6,
edgecolor = 'C3')
plt.xlabel('Episode')
plt.xlim(0, nb_episodes+1)
plt.ylim(-1, max(reward_record) + 1)
plt.ylabel('Reward')
plt.savefig(self.sess_output_path + self.Map.name + '_t' +
str(trial_nb) + '_reward_record.png',
dpi = dpi, bbox_inches = 'tight')
print('Reward log visualized.')
plt.close()
def visualize_final_states(self, dpi, plot = False):
list_of_final_states = self.Map.states_by_level[-1]
min_state = list_of_final_states[0]
nb_final_states = len(list_of_final_states)
nb_episodes = len(self.state_obs_history[0])
for trial_nb, trial_i in enumerate(self.state_obs_history):
visual_matrix = np.zeros((nb_final_states, nb_episodes))
# extract last states
for episode_nb, episode_j in enumerate(trial_i):
state = episode_j[-1][1]
visual_matrix[state - min_state, episode_nb] = 1
# plot
if plot:
plt.figure(figsize = (7,3))
plt.pcolor(visual_matrix, cmap=plt.cm.Blues,
edgecolors='white', linewidths=0.5)
# put the major ticks at the middle of each cell
plt.yticks(np.arange(visual_matrix.shape[0]) + 0.5, list_of_final_states)
plt.ylabel('Final State Reached')
plt.xlabel('Episode')
plt.savefig(self.sess_output_path + self.Map.name + '_t' + str(trial_nb) +
'_FinalState.png', dpi = dpi, bbox_inches = 'tight')
plt.close()
print('Final states visited visualized.')
def visualize_timesteps_per_episode(self, dpi, plot = False):
for trial_nb, trial_i in enumerate(self.state_obs_history):
episodes_length = []
for episode_nb, episode_j in enumerate(trial_i):
episode_length = len(episode_j)
episodes_length.append(episode_length)
nb_episodes = len(trial_i)
# plot
if plot:
plt.figure(figsize = (5,3.5))
x = np.arange(nb_episodes) + 1
plt.plot(x, episodes_length, color = 'C1', linewidth = 2)
ax = plt.axes()
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
plt.xlabel('Episode')
plt.xlim(1, nb_episodes)
plt.ylabel('Time Steps Until Termination)')
plt.savefig(self.sess_output_path + self.Map.name + '_t' +
str(trial_nb) + '_timesteps_per_episode.png',
dpi = dpi, bbox_inches = 'tight')
plt.close()
print('Timesteps per episode plotted.')
self.all_timesteps_trial.append(episodes_length)
def compare_total_steps_till_reward(self, dpi):
''' compute how many total steps it takes until first reward is encountered
state_obs_history: trials, episodes, timesteps within episode
'''
self.steps = []
for trial_nb, trial_i in enumerate(self.state_obs_history):
steps_trial_i = 0
for episode_nb, episode_j in enumerate(trial_i):
for obs_t in episode_j:
reward = obs_t[2]
if reward > 0:
break
else:
steps_trial_i += 1
if reward > 0: break
self.steps.append(steps_trial_i)
def log_reward(self, plot = False, dpi = 300):
for trial_nb, trial_i in enumerate(self.state_obs_history):
nb_episodes = len(trial_i)
reward_record = []
for episode_nb, episode_j in enumerate(trial_i):
reward = episode_j[-1][-2]
if episode_nb > 0:
reward_record.append(reward)
# changed
else:
reward_record.append(reward)
if plot:
self.plot_reward(dpi, nb_episodes, reward_record, trial_nb)
print('Trial-averaged rewards across episodes plotted.')
self.cumulative_rewards.append(reward_record)
def plot_reward(self, dpi, nb_episodes, reward_record, trial_nb):
plt.figure(figsize=(4, 3))
x = np.arange(nb_episodes)
plt.plot(x + 1, reward_record,
color='C2',
linewidth=1.5)
ax = plt.axes()
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
plt.xlabel('Episode')
plt.xlim(1, nb_episodes)
plt.ylim(0, )
plt.ylabel('Reward')
plt.savefig(self.sess_output_path + self.Map.name + '_t' +
str(trial_nb) + '_episode_reward.png',
dpi=dpi, bbox_inches='tight')
plt.close()
def visualize_state_values(self, dpi, plot = False):
'''
Visualize q value changes over episodes and trials.
NOTE: this dictionary object may contain incomplete state access history,
due to the nature of the exploration policy.
'''
for trial_nb, trial_i in enumerate(self.value_history):
visited_stateactions = list(trial_i[-1])
visited_stateactions.sort()
nb_episodes = len(trial_i)
value_matrix = np.zeros((len(visited_stateactions), nb_episodes))
for episode_nb, episode_j in enumerate(trial_i):
for row_nb, stateaction_k in enumerate(visited_stateactions):
if stateaction_k in episode_j:
value_matrix[row_nb, episode_nb] = episode_j[stateaction_k]
# plot
if plot:
plt.figure(figsize = (6,4))
plt.pcolor(value_matrix,
vmin=math.floor(np.min(value_matrix)),
vmax=math.ceil(np.max(value_matrix)))
plt.ylabel('Agent State-Action Value')
plt.xlabel('Episode')
plt.colorbar()
plt.savefig(self.sess_output_path + self.Map.name + '_t' + str(trial_nb) +
'_value_across_learning.png', dpi = dpi, bbox_inches = 'tight')
plt.close()
print('Value learning visualized.')
self.value_matrix = value_matrix
# USEFUL FOR DEBUGGING: print(np.max(value_matrix))
def visualize_state_novelty(self, dpi, plot = False):
'''
Visualize q value changes over episodes and trials.
NOTE: this dictionary object may contain incomplete state access history,
due to the nature of the exploration policy.
'''
for trial_nb, trial_i in enumerate(self.novelty_history):
visited_stateactions = list(trial_i[-1])
visited_stateactions.sort()
nb_episodes = len(trial_i)
novelty_matrix = np.zeros((len(visited_stateactions), nb_episodes))
for episode_nb, episode_j in enumerate(trial_i):
for row_nb, stateaction_k in enumerate(visited_stateactions):
if stateaction_k in episode_j:
novelty_matrix[row_nb, episode_nb] = episode_j[stateaction_k]
# plot
if plot:
plt.figure(figsize = (6,4))
plt.pcolor(novelty_matrix,
vmin=math.floor(np.min(novelty_matrix)),
vmax=math.ceil(np.max(novelty_matrix)))
plt.ylabel('Agent State-Action Novelty')
plt.xlabel('Episode')
plt.colorbar()
plt.savefig(self.sess_output_path + self.Map.name + '_t' + str(trial_nb) +
'_novelty_across_learning.png', dpi = dpi, bbox_inches = 'tight')
plt.close()
print('Novelty visualized.')
self.value_matrix = novelty_matrix
# USEFUL FOR DEBUGGING: print(np.max(value_matrix))
|
[
"matplotlib.pyplot.xlim",
"os.mkdir",
"matplotlib.pyplot.pcolor",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.axes",
"matplotlib.pyplot.close",
"matplotlib.pyplot.scatter",
"os.path.exists",
"numpy.zeros",
"matplotlib.pyplot.colorbar",
"matplotlib.pyplot.figure",
"numpy.min",
"numpy.arange",
"numpy.max",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel"
] |
[((7221, 7247), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(4, 3)'}), '(figsize=(4, 3))\n', (7231, 7247), True, 'import matplotlib.pyplot as plt\n'), ((7260, 7282), 'numpy.arange', 'np.arange', (['nb_episodes'], {}), '(nb_episodes)\n', (7269, 7282), True, 'import numpy as np\n'), ((7291, 7348), 'matplotlib.pyplot.plot', 'plt.plot', (['(x + 1)', 'reward_record'], {'color': '"""C2"""', 'linewidth': '(1.5)'}), "(x + 1, reward_record, color='C2', linewidth=1.5)\n", (7299, 7348), True, 'import matplotlib.pyplot as plt\n'), ((7396, 7406), 'matplotlib.pyplot.axes', 'plt.axes', ([], {}), '()\n', (7404, 7406), True, 'import matplotlib.pyplot as plt\n'), ((7505, 7526), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Episode"""'], {}), "('Episode')\n", (7515, 7526), True, 'import matplotlib.pyplot as plt\n'), ((7535, 7559), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(1)', 'nb_episodes'], {}), '(1, nb_episodes)\n', (7543, 7559), True, 'import matplotlib.pyplot as plt\n'), ((7568, 7579), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0)'], {}), '(0)\n', (7576, 7579), True, 'import matplotlib.pyplot as plt\n'), ((7590, 7610), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Reward"""'], {}), "('Reward')\n", (7600, 7610), True, 'import matplotlib.pyplot as plt\n'), ((7795, 7806), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (7804, 7806), True, 'import matplotlib.pyplot as plt\n'), ((1555, 1592), 'os.path.exists', 'os.path.exists', (['self.sess_output_path'], {}), '(self.sess_output_path)\n', (1569, 1592), False, 'import os, sys, glob\n'), ((1606, 1637), 'os.mkdir', 'os.mkdir', (['self.sess_output_path'], {}), '(self.sess_output_path)\n', (1614, 1637), False, 'import os, sys, glob\n'), ((3577, 3617), 'numpy.zeros', 'np.zeros', (['(nb_final_states, nb_episodes)'], {}), '((nb_final_states, nb_episodes))\n', (3585, 3617), True, 'import numpy as np\n'), ((2463, 2490), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 1)'}), '(figsize=(10, 1))\n', (2473, 2490), True, 'import matplotlib.pyplot as plt\n'), ((2512, 2534), 'numpy.arange', 'np.arange', (['nb_episodes'], {}), '(nb_episodes)\n', (2521, 2534), True, 'import numpy as np\n'), ((2551, 2651), 'matplotlib.pyplot.scatter', 'plt.scatter', (['(x + 1)', 'reward_record'], {'s': '(20)', 'facecolor': '(0, 0, 0, 0)', 'linewidths': '(0.6)', 'edgecolor': '"""C3"""'}), "(x + 1, reward_record, s=20, facecolor=(0, 0, 0, 0), linewidths=\n 0.6, edgecolor='C3')\n", (2562, 2651), True, 'import matplotlib.pyplot as plt\n'), ((2780, 2801), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Episode"""'], {}), "('Episode')\n", (2790, 2801), True, 'import matplotlib.pyplot as plt\n'), ((2818, 2846), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(0)', '(nb_episodes + 1)'], {}), '(0, nb_episodes + 1)\n', (2826, 2846), True, 'import matplotlib.pyplot as plt\n'), ((2914, 2934), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Reward"""'], {}), "('Reward')\n", (2924, 2934), True, 'import matplotlib.pyplot as plt\n'), ((3202, 3213), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (3211, 3213), True, 'import matplotlib.pyplot as plt\n'), ((3875, 3901), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(7, 3)'}), '(figsize=(7, 3))\n', (3885, 3901), True, 'import matplotlib.pyplot as plt\n'), ((3919, 4004), 'matplotlib.pyplot.pcolor', 'plt.pcolor', (['visual_matrix'], {'cmap': 'plt.cm.Blues', 'edgecolors': '"""white"""', 'linewidths': '(0.5)'}), "(visual_matrix, cmap=plt.cm.Blues, edgecolors='white', linewidths=0.5\n )\n", (3929, 4004), True, 'import matplotlib.pyplot as plt\n'), ((4198, 4231), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Final State Reached"""'], {}), "('Final State Reached')\n", (4208, 4231), True, 'import matplotlib.pyplot as plt\n'), ((4248, 4269), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Episode"""'], {}), "('Episode')\n", (4258, 4269), True, 'import matplotlib.pyplot as plt\n'), ((4458, 4469), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (4467, 4469), True, 'import matplotlib.pyplot as plt\n'), ((4955, 4983), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(5, 3.5)'}), '(figsize=(5, 3.5))\n', (4965, 4983), True, 'import matplotlib.pyplot as plt\n'), ((5048, 5101), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'episodes_length'], {'color': '"""C1"""', 'linewidth': '(2)'}), "(x, episodes_length, color='C1', linewidth=2)\n", (5056, 5101), True, 'import matplotlib.pyplot as plt\n'), ((5127, 5137), 'matplotlib.pyplot.axes', 'plt.axes', ([], {}), '()\n', (5135, 5137), True, 'import matplotlib.pyplot as plt\n'), ((5260, 5281), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Episode"""'], {}), "('Episode')\n", (5270, 5281), True, 'import matplotlib.pyplot as plt\n'), ((5298, 5322), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(1)', 'nb_episodes'], {}), '(1, nb_episodes)\n', (5306, 5322), True, 'import matplotlib.pyplot as plt\n'), ((5339, 5382), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Time Steps Until Termination)"""'], {}), "('Time Steps Until Termination)')\n", (5349, 5382), True, 'import matplotlib.pyplot as plt\n'), ((5610, 5621), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (5619, 5621), True, 'import matplotlib.pyplot as plt\n'), ((8688, 8714), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(6, 4)'}), '(figsize=(6, 4))\n', (8698, 8714), True, 'import matplotlib.pyplot as plt\n'), ((8904, 8942), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Agent State-Action Value"""'], {}), "('Agent State-Action Value')\n", (8914, 8942), True, 'import matplotlib.pyplot as plt\n'), ((8959, 8980), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Episode"""'], {}), "('Episode')\n", (8969, 8980), True, 'import matplotlib.pyplot as plt\n'), ((8997, 9011), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (9009, 9011), True, 'import matplotlib.pyplot as plt\n'), ((9211, 9222), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (9220, 9222), True, 'import matplotlib.pyplot as plt\n'), ((10272, 10298), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(6, 4)'}), '(figsize=(6, 4))\n', (10282, 10298), True, 'import matplotlib.pyplot as plt\n'), ((10494, 10534), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Agent State-Action Novelty"""'], {}), "('Agent State-Action Novelty')\n", (10504, 10534), True, 'import matplotlib.pyplot as plt\n'), ((10551, 10572), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Episode"""'], {}), "('Episode')\n", (10561, 10572), True, 'import matplotlib.pyplot as plt\n'), ((10589, 10603), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (10601, 10603), True, 'import matplotlib.pyplot as plt\n'), ((10805, 10816), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (10814, 10816), True, 'import matplotlib.pyplot as plt\n'), ((5005, 5027), 'numpy.arange', 'np.arange', (['nb_episodes'], {}), '(nb_episodes)\n', (5014, 5027), True, 'import numpy as np\n'), ((4119, 4152), 'numpy.arange', 'np.arange', (['visual_matrix.shape[0]'], {}), '(visual_matrix.shape[0])\n', (4128, 4152), True, 'import numpy as np\n'), ((8800, 8820), 'numpy.min', 'np.min', (['value_matrix'], {}), '(value_matrix)\n', (8806, 8820), True, 'import numpy as np\n'), ((8865, 8885), 'numpy.max', 'np.max', (['value_matrix'], {}), '(value_matrix)\n', (8871, 8885), True, 'import numpy as np\n'), ((10386, 10408), 'numpy.min', 'np.min', (['novelty_matrix'], {}), '(novelty_matrix)\n', (10392, 10408), True, 'import numpy as np\n'), ((10453, 10475), 'numpy.max', 'np.max', (['novelty_matrix'], {}), '(novelty_matrix)\n', (10459, 10475), True, 'import numpy as np\n')]
|
import numpy as np
from enum import Enum
from collections import defaultdict
import networking
# adapted from https://github.com/soong-construction/dirt-rally-time-recorder/blob/master/setup-dr2.sql
# max_rpm, idle_rpm, max_gears, car_name
car_data = [
# H1 FWD
[7330.3826904296875, 837.7580261230469, 4.0, 'Mini Cooper S'],
[6283.1854248046875, 1047.1975708007812, 4.0, 'Citroen DS 21'],
[6806.78466796875, 994.8377227783203, 4.0, 'Lancia Fulvia HF'],
# H2 FWD
[7853.98193359375, 942.4777984619141, 5.0, 'Volkswagen Golf GTI 16V'],
[7330.3826904296875, 1256.6371154785156, 5.0, 'Peugeot 205 GTI'],
# H2 RWD
[9948.377075195312, 1256.6371154785156, 5.0, 'Ford Escort Mk II'],
[8377.58056640625, 1675.5160522460938, 5.0, 'Renault Alpine A110 1600 S'],
[8377.58056640625, 1780.2359008789062, 5.0, 'Fiat 131 Abarth Rally'],
[9424.77783203125, 1570.7963562011719, 5.0, 'Opel Kadett C GT/E'],
# H3 RWD
[9320.05859375, 1151.9173431396484, 6.0, 'BMW E30 Evo Rally'],
[7853.98193359375, 1361.3568115234375, 5.0, 'Opel Ascona 400'],
[8901.179809570312, 1047.1975708007812, 5.0, 'Lancia Stratos'],
[8377.58056640625, 1518.4365844726562, 5.0, 'Renault 5 Turbo'],
[7797.432861328125, 804.2477416992188, 5.0, 'Datsun 240Z'],
[7853.98193359375, 1151.9173431396484, 5.0, 'Ford Sierra Cosworth RS500'],
# F2 Kit Car
[11519.173583984375, 1989.6754455566406, 6.0, 'Peugeot 306 Maxi'],
[9424.77783203125, 1361.3568115234375, 6.0, 'Seat Ibiza Kit Car'],
[9424.77783203125, 1256.6371154785156, 6.0, 'Volkswagen Golf Kitcar'],
# Group B RWD
[8901.179809570312, 1256.6371154785156, 5.0, 'Lancia 037 Evo 2'],
[8168.1414794921875, 1466.07666015625, 5.0, 'Opel Manta 400'],
[9686.577758789062, 1570.7963562011719, 5.0, 'BMW M1 Procar Rally'],
[8377.58056640625, 1361.3568115234375, 5.0, 'Porsche 911 SC RS'],
# Group B 4WD
[9424.77783203125, 1361.3568115234375, 5.0, 'Audi Sport quattro S1 E2'],
[8377.58056640625, 2094.3951416015625, 5.0, 'Peugeot 205 T16 Evo 2'],
[8901.179809570312, 1675.5160522460938, 5.0, 'Lancia Delta S4'], # same as Peugeot 208 R2
[9424.77783203125, 1256.6371154785156, 5.0, 'Ford RS200'],
[9948.377075195312, 1099.5574188232422, 5.0, 'MG Metro 6R4'],
# R2
[8168.1414794921875, 1570.7963562011719, 5.0, 'Ford Fiesta R2'],
[9058.25927734375, 1780.2359008789062, 5.0, '<NAME> R2'],
[8901.179809570312, 1675.5160522460938, 5.0, 'Peugeot 208 R2'], # same as Lancia Delta S4
# Group A
[7330.3826904296875, 1466.07666015625, 6.0, 'Mitsubishi Lancer Evo VI'], # same as BMW M2 Competition
[7330.3826904296875, 1151.9173431396484, 6.0, '<NAME> 1995'],
[7853.98193359375, 1047.1975708007812, 6.0, 'Lancia Delta HF Integrale'],
[7330.3826904296875, 1466.07666015625, 7.0, 'Ford Escort RS Cosworth'],
[7911.5777587890625, 2024.2329406738281, 6.0, 'Subaru Legacy RS'],
# NR4/R4
[8377.58056640625, 1780.2359008789062, 5.0, 'Subaru Impreza WRX STI NR4'],
[7853.98193359375, 1780.2359008789062, 5.0, 'Mitsubishi Lancer Evo X'], # same as Peugeot 208 T16
# 2000cc 4WD
[7749.2620849609375, 1884.9555969238281, 6.0, '<NAME>'],
[7749.2620849609375, 1780.2359008789062, 6.0, '<NAME>'], # same as Subaru WRX STI RX
[7696.9024658203125, 1869.2477416992188, 5.0, 'Ford Focus RS Rally 2007'],
[7853.98193359375, 2199.1148376464844, 6.0, 'Subaru Impreza 2008'],
[785.398193359375, 178.02359008789062, 6.0, 'Ford Focus RS Rally 2001'],
[8377.58056640625, 2042.035369873047, 6.0, 'Subaru Impreza 2001'],
[6806.78466796875, 1570.796356201172, 5.0, 'Peugeot 206 Rally'],
[8168.1414794921875, 2073.4512329101562, 6.0, '<NAME> S4 Rally'],
# R5
[7749.2620849609375, 1884.9555969238281, 5.0, '<NAME> R5'],
[7853.98193359375, 1780.2359008789062, 5.0, 'Peugeot 208 T16'], # same as Mitsubishi Lancer Evolution X
[8377.58056640625, 2199.1148376464844, 5.0, 'Mitsubishi Space Star R5'],
[7749.2620849609375, 1780.2359008789062, 5.0, 'Skoda Fabia R5'],
[7435.1031494140625, 1858.7757873535156, 5.0, 'Citroen C3 R5'],
[7749.2620849609375, 1780.2359008789062, 5.0, 'Volkswagen Polo GTI R5'],
# Rally GT
[7330.3826904296875, 1466.07666015625, 6.0, 'BMW M2 Competition'], # Mitsubishi Lancer Evo VI
[7592.1820068359375, 1780.2359008789062, 6.0, 'Chevrolet Camaro GT4.R'],
[9424.77783203125, 1884.9555969238281, 6.0, 'Porsche 911 RGT Rally Spec'],
[7330.3826904296875, 1047.1975708007812, 6.0, 'Aston Martin V8 Vantage GT4'],
[8639.380493164062, 1466.07666015625, 6.0, 'Ford Mustang GT4 Ford RS200'],
# RX Super 1600S
[9948.377075195312, 1884.9555969238281, 6.0, 'Volkswagen Polo S1600'],
[9686.577758789062, 1989.6754455566406, 6.0, 'Renault Clio RS S1600'],
[9948.377075195312, 1989.6754455566406, 6.0, 'Opel Corsa Super 1600'],
# Crosskarts
[15985.47119140625, 1612.6841735839844, 6.0, 'Speedcar Xtrem'],
# RX Group B
# [8901.179809570312, 1675.5160522460938, 5.0, 'Lancia Delta S4 RX'], # same as Peugeot 208 R2, non-rx
[9424.77783203125, 1675.5160522460938, 5.0, 'Ford RS200 Evolution'],
# [8377.58056640625, 2094.3951416015625, 5.0, 'Peugeot 205 T16 Evo 2 RX'], # same as non-rx
[9948.377075195312, 1151.9173431396484, 5.0, 'MG Metro 6R4 RX'],
# RX2
[8377.58056640625, 1675.5160522460938, 6.0, 'Ford Fiesta OMSE SuperCar Lites'],
# RX Supercars
[8744.099731445312, 2094.3951416015625, 6.0, 'Volkswagen Polo R Supercar'],
[8744.099731445312, 2094.3951416015625, 6.0, 'Audi S1 EKS RX quattro'],
[8377.58056640625, 1780.2359008789062, 6.0, 'Peugeot 208 WRX'],
[8168.1414794921875, 1727.8759765625, 5.0, 'Renault Megane RS'],
[8115.78125, 1884.9555969238281, 6.0, 'Ford Fiesta RX (MK8)'],
[7853.98193359375, 1727.8759765625, 6.0, 'Ford Fiesta RX (MK7)'],
[7749.2620849609375, 1780.2359008789062, 6.0, 'Subaru WRX STI RX'], # same as Sk<NAME>
# RX Supercars 2019
[8377.58056640625, 1780.2359008789062, 5.0, '<NAME>. RX'], # same as Subaru Impreza WRX STI NR4
[8377.58056640625, 1780.2359008789062, 6.0, 'Peugeot 208 WRX'], # same as Peugeot 208 WRX
[8744.099731445312, 2094.3951416015625, 6.0, 'Audi S1 EKS RX Quattro'], # same as Audi S1 EKS RX quattro
[8377.58056640625, 1780.2359008789062, 6.0, 'Ren<NAME> R.S. RX'], # same as Peugeot 208 WRX
[8377.58056640625, 1884.9555969238281, 6.0, 'Ford Fiesta RXS Evo 5'], # same as Ford Fiesta RX (Stard)
[8115.78125, 1884.9555969238281, 6.0, 'Ford Fiesta RX (MK8)'], # same as Ford Fiesta RX (MK8)
[7853.98193359375, 2617.9940795898438, 6.0, 'Mini Cooper SX1'],
[8377.58056640625, 1884.9555969238281, 6.0, 'Ford Fiesta RX (Stard)'], # same as Ford Fiesta RXS Evo 5
[7853.98193359375, 1780.2359008789062, 6.0, 'Seat Ibiza RX'],
]
# adapted from https://github.com/soong-construction/dirt-rally-time-recorder/blob/master/tracks.sql
# length, start_z, track_name
track_data = [
# Baumholder, Germany
[5361.90966796875, -2668.4755859375, 'Waldaufstieg'],
[5882.1796875, -948.372314453125, 'Waldabstieg'],
[6121.8701171875, -718.9346923828125, 'Kreuzungsring'],
[5666.25, 539.2579345703125, 'Kreuzungsring reverse'],
[10699.9599609375, 814.2764892578125, 'Ruschberg'],
[5855.6796875, 513.0728759765625, 'Verbundsring'],
[5550.85009765625, 657.1261596679688, 'Verbundsring reverse'],
[5129.0400390625, 814.3093872070312, 'Innerer Feld-Sprint'],
[4937.85009765625, 656.46044921875, 'Innerer Feld-Sprint reverse'],
[11487.189453125, -2668.59033203125, 'Oberstein'],
[10805.23046875, 513.07177734375, 'Hammerstein'],
[11551.16015625, 539.3564453125, 'Frauenberg'],
# Monte Carlo, Monaco
[10805.220703125, 1276.76611328125, '<NAME>'],
[10866.8603515625, -2344.705810546875, '<NAME>'],
[4730.02001953125, 283.7648620605469, '<NAME> – Sprint en descente'],
[4729.5400390625, -197.3816375732422, 'Col de Turini sprint en Montee'],
[5175.91015625, -131.84573364257812, 'Col de Turini – Descente'],
[5175.91015625, -467.3677062988281, 'Gordolon – Courte montee'],
[4015.35986328125, -991.9784545898438, 'Route de Turini (Descente)'],
[3952.150146484375, 1276.780517578125, 'Approche du Col de Turini – Montee'],
[9831.4501953125, -467.483154296875, 'Pra d´Alart'],
[9832.0205078125, 283.4727478027344, 'Col de Turini Depart'],
[6843.3203125, -991.945068359375, 'Route de Turini (Montee)'],
[6846.830078125, -2344.592529296875, 'Col de Turini – Depart en descente'],
# Powys, Wales
[4821.64990234375, 2047.56201171875, 'Pant Mawr Reverse'],
[4960.06005859375, 1924.06884765625, 'Bidno Moorland'],
[5165.96044921875, 2481.105224609375, 'Bidno Moorland Reverse'],
[11435.5107421875, -557.0780029296875, 'River Severn Valley'],
[11435.5400390625, 169.15403747558594, 'Bronfelen'],
[5717.39990234375, -557.11328125, '<NAME>'],
[5717.3896484375, -22.597640991210938, '<NAME> Reverse'],
[5718.099609375, -23.46375274658203, '<NAME>'],
[5718.10009765625, 169.0966033935547, '<NAME> Reverse'],
[9911.66015625, 2220.982177734375, '<NAME>'],
[10063.6005859375, 2481.169677734375, 'Geufron Forest'],
[4788.669921875, 2221.004150390625, '<NAME>'],
# Värmland, Sweden
[7055.9501953125, -1618.4476318359375, 'Älgsjön'],
[4911.68017578125, -1742.0498046875, '<NAME>'],
[6666.89013671875, -2143.403076171875, 'Stor-jangen Sprint'],
[6693.43994140625, 563.3468017578125, 'Stor-jangen Sprint Reverse'],
[4931.990234375, -5101.59619140625, 'Björklangen'],
[11922.6201171875, -4328.87158203125, 'Ransbysäter'],
[12123.740234375, 2697.36279296875, 'Hamra'],
[12123.5908203125, -5101.78369140625, 'Lysvik'],
[11503.490234375, 562.8009033203125, 'Norraskoga'],
[5248.35986328125, -4328.87158203125, 'Älgsjön Sprint'],
[7058.47998046875, 2696.98291015625, 'Elgsjön'],
[4804.0302734375, -2143.44384765625, 'Skogsrallyt'],
# New England, USA
[6575.8701171875, -408.4866027832031, 'Tolt Valley Sprint Forward'],
[6468.2998046875, 2768.171142578125, 'Unknown track'],
[6701.61962890625, 1521.6917724609375, 'Hancock Creek Burst'],
[6109.5400390625, -353.0966796875, 'Hancock Hill Sprint Reverse'],
[12228.830078125, 1521.5872802734375, 'North Fork Pass'],
[12276.1201171875, 27.728849411010742, 'North Fork Pass Reverse'],
[6488.330078125, 27.087112426757812, 'Fuller Mountain Descent'],
[6468.2998046875, 2768.10107421875, 'Fuller Mountain Ascent'],
[6681.60986328125, 2950.6044921875, 'Fury Lake Depart'],
[12856.66015625, 518.76123046875, 'Beaver Creek Trail Forward'],
[12765.919921875, -4617.37744140625, 'Beaver Creek Trail Reverse'],
[6229.10986328125, 518.7451171875, 'Hancock Hill Sprint Forward'],
[6604.0302734375, -4617.388671875, 'Tolt Valley Sprint Reverse'],
# Catamarca Province, Argentina
[7667.31982421875, 131.03880310058594, 'Valle de los puentes'],
[3494.010009765625, -1876.9149169921875, 'Huillaprima'],
[8265.9501953125, 205.80775451660156, '<NAME>'],
[8256.8603515625, 2581.345947265625, '<NAME>'],
[5303.7900390625, 2581.339599609375, 'Camino de acantilados y rocas'],
[4171.5, -3227.17626953125, 'San Isidro'],
[3353.0400390625, 130.6753692626953, 'Miraflores'],
[2845.6298828125, 206.18272399902344, 'El Rodeo'],
[7929.18994140625, -3227.17724609375, 'Valle de los puentes a la inversa'],
[5294.81982421875, 1379.72607421875, 'Camino de acantilados y rocas inverso'],
[4082.2998046875, -1864.662109375, '<NAME>'],
[2779.489990234375, 1344.307373046875, 'La Merced'],
# Hawkes Bay, New Zealand
[4799.84033203125, -4415.70703125, 'Te Awanga Sprint Forward'],
[11437.0703125, 1789.1517333984375, 'Ocean Beach'],
[6624.0302734375, 1789.0382080078125, 'Ocean Beach Sprint'],
[4688.52978515625, -2004.0015869140625, 'Te Awanga Sprint Reverse'],
[8807.490234375, 2074.951171875, 'Waimarama Sprint Forward'],
[6584.10009765625, -1950.1710205078125, 'Ocean Beach Sprint Reverse'],
[7137.81005859375, 2892.6181640625, 'Elsthorpe Sprint Forward'],
[15844.529296875, 2074.938720703125, 'Waimarama Point Reverse'],
[16057.8505859375, 2892.97216796875, 'Waimarama Point Forward'],
[11507.4404296875, -4415.119140625, 'Te Awanga Forward'],
[8733.98046875, 5268.0849609375, 'Waimarama Sprint Reverse'],
[6643.490234375, 5161.06396484375, 'Elsthorpe Sprint Reverse'],
# Poland, Leczna County:
[6622.080078125, 4644.4375, '<NAME>'],
[9254.900390625, 1972.7869873046875, 'Marynka'],
[6698.81005859375, -3314.843505859375, 'Lejno'],
[8159.81982421875, 7583.216796875, 'Józefin'],
[7840.1796875, 4674.87548828125, 'Kopina'],
[6655.5400390625, -402.56207275390625, 'Jagodno'],
[13180.3798828125, -3314.898193359375, 'Zienki'],
[16475.009765625, 4674.9150390625, 'Zaróbka'],
[16615.0, 1973.2518310546875, 'Zagorze'],
[13295.6796875, 4644.3798828125, '<NAME>'],
[9194.3203125, 7393.35107421875, 'Borysik'],
[6437.80029296875, -396.1388854980469, '<NAME>'],
# Australia, Monaro:
[13304.1201171875, 2242.524169921875, 'Mount Kaye Pass'],
[13301.109375, -2352.5615234375, 'Mount Kaye Pass Reverse'],
[6951.15966796875, 2242.5224609375, 'Rockton Plains'],
[7116.14990234375, 2457.100341796875, 'Rockton Plains Reverse'],
[6398.90966796875, 2519.408447265625, 'Yambulla Mountain Ascent'],
[6221.490234375, -2352.546630859375, 'Yambulla Mountain Descent'],
[12341.25, 2049.85888671875, 'Chandlers Creek'],
[12305.0400390625, -1280.10595703125, 'Chandlers Creek Reverse'],
[7052.2998046875, -603.9149169921875, 'Bondi Forest'],
[7007.02001953125, -1280.1004638671875, 'Taylor Farm Sprint'],
[5277.02978515625, 2049.85791015625, 'Noorinbee Ridge Ascent'],
[5236.91015625, -565.1859130859375, 'Noorinbee Ridge Descent'],
# Spain, Ribadelles:
[14348.3603515625, 190.28546142578125, 'Com<NAME> Bellriu'],
[10568.4296875, -2326.21142578125, 'Centenera'],
[7297.27001953125, 2593.36376953125, 'Ascenso bosque Montverd'],
[6194.7099609375, -2979.6650390625, '<NAME> inversa'],
[6547.39990234375, -2002.0657958984375, '<NAME>'],
[6815.4501953125, -2404.635009765625, 'Vinedos dentro del valle Parra'],
[10584.6796875, -2001.96337890625, 'Cam<NAME> Centenera'],
[4380.740234375, -3003.546630859375, 'Subida por carretera'],
[6143.5703125, 2607.470947265625, 'Salida desde Montverd'],
[7005.68994140625, 190.13796997070312, 'Ascenso por valle el Gualet'],
[4562.80029296875, -2326.251708984375, 'Descenso por carretera'],
[13164.330078125, -2404.1171875, 'Final de Bellriu'],
# Greece, Argolis
[4860.1904296875, 91.54808044433594, '<NAME>'],
[9666.5, -2033.0767822265625, '<NAME>'],
[9665.990234375, 457.1891784667969, '<NAME>'],
[5086.830078125, -2033.0767822265625, '<NAME>'],
[4582.009765625, 164.40521240234375, '<NAME>'],
[4515.39990234375, 457.18927001953125, '<NAME>'],
[10487.060546875, 504.3974609375, '<NAME>'],
[10357.8798828125, -3672.5810546875, '<NAME>'],
[5739.099609375, 504.3973693847656, '<NAME>'],
[5383.009765625, -2277.10986328125, '<NAME>'],
[6888.39990234375, -1584.236083984375, '<NAME>'],
[6595.31005859375, -3672.58154296875, '<NAME>'],
# Finland, Jämsä
[7515.40966796875, 39.52613830566406, 'Kailajärvi'],
[7461.65966796875, 881.0377197265625, 'Paskuri'],
[7310.5400390625, 846.68701171875, 'Naarajärvi'],
[7340.3798828125, -192.40794372558594, 'Jyrkysjärvi'],
[16205.1904296875, 3751.42236328125, 'Kakaristo'],
[16205.259765625, 833.2575073242188, 'Pitkäjärvi'],
[8042.5205078125, 3751.42236328125, 'Iso Oksjärvi'],
[8057.52978515625, -3270.775390625, 'Oksala'],
[8147.560546875, -3263.315185546875, 'Kotajärvi'],
[8147.419921875, 833.2575073242188, 'Järvenkylä'],
[14929.7998046875, 39.52613067626953, 'Kontinjärvi'],
[14866.08984375, -192.407958984375, 'Hämelahti'],
# Scotland, UK
[7144.69970703125, -1657.4295654296875, 'Rosebank Farm'],
[6967.89990234375, 3383.216796875, 'Rosebank Farm Reverse'],
[12857.0703125, 1386.7626953125, 'Newhouse Bridge'],
[12969.2109375, -403.3143310546875, 'Newhouse Bridge Reverse'],
[5822.77001953125, -1157.0889892578125, 'Old Butterstone Muir'],
[5659.8203125, 3339.01513671875, 'Old Butterstone Muir Reverse'],
[7703.72021484375, -403.3154602050781, 'Annbank Station'],
[7587.64013671875, -1839.5506591796875, 'Annbank Station Reverse'],
[5245.4501953125, 1387.3612060546875, 'Glencastle Farm'],
[5238.43994140625, -1860.2203369140625, 'Glencastle Farm Reverse'],
[12583.41015625, -1157.111083984375, 'South Morningside'],
[12670.58984375, -1656.8243408203125, 'South Morningside Reverse'],
# Rallycross locations:
[1075.0989990234375, 149.30722045898438, 'Mettet, Belgium'],
[1400.0770263671875, -230.09457397460938, 'Trois-Rivieres, Canada'],
[1348.85400390625, 101.5931396484375, 'Lydden Hill, England'],
[991.1160278320312, -185.40646362304688, 'Silverstone, England'],
[1064.97998046875, 195.76113891601562, 'Loheac, France'],
[951.51171875, -17.769332885742188, 'Estering, Germany'],
[1287.4329833984375, 134.0433807373047, 'Bikernieki, Latvia'],
[1036.0970458984375, 122.2354736328125, 'Hell, Norway'],
[1026.759033203125, -541.3275756835938, 'Montalegre, Portugal'],
[1064.623046875, -100.92737579345703, 'Killarney, South Africa'],
[1119.3590087890625, -341.3289794921875, 'Barcalona-Catalunya, Spain'],
[1207.18798828125, 180.26181030273438, 'Holjes, Sweden'],
[1194.22900390625, -133.4615936279297, '<NAME>, A<NAME>'],
# Test track locations:
[3601.22998046875, 121.67539978027344, 'DirtFish'],
]
car_dict = dict()
for d in car_data:
car_dict[(d[0], d[1], d[2])] = d[3]
# track length is not a unique key as some tracks are just reversed
# it's unique together with the starting position, which is not accurate to float precision
track_dict = defaultdict(list)
for t in track_data:
track_dict[t[0]].append((t[1], t[2]))
class GameState(Enum):
ignore_package = 0
race_not_running = 1
race_running = 2
def get_car_name_from_sample(sample):
max_rpm = sample[networking.Fields.max_rpm.value]
idle_rpm = sample[networking.Fields.idle_rpm.value]
max_gears = sample[networking.Fields.max_gears.value]
return get_car_name(max_rpm, idle_rpm, max_gears)
def get_car_name(max_rpm, idle_rpm, max_gears):
key = (max_rpm, idle_rpm, max_gears)
if key in car_dict.keys():
car_name = car_dict[key]
else:
car_name = 'Unknown car ' + str(key)
return car_name
def get_track_name_from_sample(sample):
length = sample[networking.Fields.track_length.value]
start_z = sample[networking.Fields.pos_z.value]
return get_track_name(length, start_z)
def get_track_name(length, start_z):
if start_z is not None and length in track_dict.keys():
track_candidates = track_dict[length]
track_candidates_start_z = np.array([t[0] for t in track_candidates])
track_candidates_start_z_dist = np.abs(track_candidates_start_z - start_z)
best_match_id = np.argmin(track_candidates_start_z_dist)
track_name = track_candidates[best_match_id][1]
else:
track_name = 'Unknown track ' + str((length, start_z))
return track_name
def get_game_state_str(state, last_sample, num_samples):
state_str = '{car} on {track}, samples: {samples:05d}, lap time: {time:.1f}, ' \
'speed: {speed:.1f} m/s, rpm: {rpm:5.1f}, ' \
'progress: {progress:.2f}, distance: {distance:.1f}, run_time: {run_time:.1f}, ' \
'{state}'
time = last_sample[networking.Fields.lap_time.value]
speed = last_sample[networking.Fields.speed_ms.value]
rpm = last_sample[networking.Fields.rpm.value]
progress = last_sample[networking.Fields.progress.value]
distance = last_sample[networking.Fields.distance.value]
run_time = last_sample[networking.Fields.run_time.value]
car_name = get_car_name_from_sample(last_sample)
track_name = get_track_name_from_sample(last_sample)
if state == GameState.race_not_running:
state = 'race not running'
elif state == GameState.race_running:
state = 'race running'
elif state == GameState.ignore_package:
state = 'ignore package'
else:
raise ValueError('Invalid game state: {}'.format(state))
state_str = state_str.format(
car=car_name, track=track_name,
samples=num_samples, time=time, speed=speed, rpm=rpm,
progress=progress, distance=distance, run_time=run_time,
state=state
)
return state_str
def get_game_state(receive_results, last_receive_results):
# no new data
if receive_results is None:
return GameState.ignore_package
# all equal except the run time -> new package, same game state in DR2 -> race is paused
if last_receive_results is not None and \
np.all(receive_results[1:] == last_receive_results[1:]):
return GameState.ignore_package
#if receive_results[networking.Fields.progress.value] > 0.0:
if receive_results[networking.Fields.lap_time.value] > 0.0:
return GameState.race_running
# race has not yet started
if receive_results[networking.Fields.lap_time.value] == 0.0:
return GameState.race_not_running
if receive_results[networking.Fields.distance.value] <= 0.0:
return GameState.race_not_running
# RPM will never be zero at the start (it will be the idle RPM)
# However, RPM can be zero for some reason in the service area. Ignore then.
if receive_results[networking.Fields.rpm.value] == 0.0 and receive_results[networking.Fields.run_time.value] <= 0.1:
return GameState.ignore_package
# strange packages with position at zero after race, speed check to be sure
if receive_results[networking.Fields.pos_y.value] == 0.0 and \
receive_results[networking.Fields.speed_ms.value] == 0.0:
return GameState.race_not_running
print('Unknown reason for "not running": progress={}'.format(receive_results[networking.Fields.progress.value]))
return GameState.race_not_running
def accept_new_data(state):
if state == GameState.race_not_running:
return False
elif state == GameState.race_running:
return True
elif state == GameState.ignore_package:
return False
else:
raise ValueError('Unknown state: {}'.format(state))
|
[
"numpy.abs",
"numpy.argmin",
"collections.defaultdict",
"numpy.array",
"numpy.all"
] |
[((18171, 18188), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (18182, 18188), False, 'from collections import defaultdict\n'), ((19213, 19255), 'numpy.array', 'np.array', (['[t[0] for t in track_candidates]'], {}), '([t[0] for t in track_candidates])\n', (19221, 19255), True, 'import numpy as np\n'), ((19296, 19338), 'numpy.abs', 'np.abs', (['(track_candidates_start_z - start_z)'], {}), '(track_candidates_start_z - start_z)\n', (19302, 19338), True, 'import numpy as np\n'), ((19363, 19403), 'numpy.argmin', 'np.argmin', (['track_candidates_start_z_dist'], {}), '(track_candidates_start_z_dist)\n', (19372, 19403), True, 'import numpy as np\n'), ((21206, 21261), 'numpy.all', 'np.all', (['(receive_results[1:] == last_receive_results[1:])'], {}), '(receive_results[1:] == last_receive_results[1:])\n', (21212, 21261), True, 'import numpy as np\n')]
|
import numpy as np
__all__ = ['NFWParam']
class NFWParam(object):
"""
class which contains a halo model parameters dependent on cosmology for NFW profile
all distances are given in comoving coordinates
"""
rhoc = 2.77536627e11 # critical density [h^2 M_sun Mpc^-3]
def rhoc_z(self, z):
"""
:param z: redshift
:return: scaled critical density as a function of redshift (attention, this is not rho_crit(z))
"""
return self.rhoc*(1+z)**3
def M200(self, Rs, rho0, c):
"""
M(R_200) calculation for NFW profile
:param Rs: scale radius
:type Rs: float
:param rho0: density normalization (characteristic density)
:type rho0: float
:param c: concentration
:type c: float [4,40]
:return: M(R_200) density
"""
return 4*np.pi*rho0*Rs**3*(np.log(1.+c)-c/(1.+c))
def r200_M(self, M):
"""
computes the radius R_200 of a halo of mass M in comoving distances M/h
:param M: halo mass in M_sun/h
:type M: float or numpy array
:return: radius R_200 in comoving Mpc/h
"""
return (3*M/(4*np.pi*self.rhoc*200))**(1./3.)
def M_r200(self, r200):
"""
:param r200: r200 in comoving Mpc/h
:return: M200 in M_sol/h
"""
return self.rhoc*200 * r200**3 * 4*np.pi/3.
def rho0_c(self, c):
"""
computes density normalization as a function of concentration parameter
:return: density normalization in h^2/Mpc^3 (comoving)
"""
return 200./3*self.rhoc*c**3/(np.log(1.+c)-c/(1.+c))
def c_rho0(self, rho0):
"""
computes the concentration given a comoving overdensity rho0 (inverse of function rho0_c)
:param rho0: density normalization in h^2/Mpc^3 (comoving)
:return: concentration parameter c
"""
if not hasattr(self, '_c_rho0_interp'):
c_array = np.linspace(0.1, 10, 100)
rho0_array = self.rho0_c(c_array)
from scipy import interpolate
self._c_rho0_interp = interpolate.InterpolatedUnivariateSpline(rho0_array, c_array, w=None, bbox=[None, None], k=3)
return self._c_rho0_interp(rho0)
def c_M_z(self, M, z):
"""
fitting function of http://moriond.in2p3.fr/J08/proceedings/duffy.pdf for the mass and redshift dependence of the concentration parameter
:param M: halo mass in M_sun/h
:type M: float or numpy array
:param z: redshift
:type z: float >0
:return: concentration parameter as float
"""
# fitted parameter values
A = 5.22
B = -0.072
C = -0.42
M_pivot = 2.*10**12
return A*(M/M_pivot)**B*(1+z)**C
def nfw_Mz(self, M, z):
"""
returns all needed parameter (in comoving units modulo h) to draw the profile of the main halo
r200 in co-moving Mpc/h
rho_s in h^2/Mpc^3 (co-moving)
Rs in Mpc/h co-moving
c unit less
"""
c = self.c_M_z(M, z)
r200 = self.r200_M(M)
rho0 = self.rho0_c(c)
Rs = r200/c
return r200, rho0, c, Rs
|
[
"numpy.log",
"scipy.interpolate.InterpolatedUnivariateSpline",
"numpy.linspace"
] |
[((1992, 2017), 'numpy.linspace', 'np.linspace', (['(0.1)', '(10)', '(100)'], {}), '(0.1, 10, 100)\n', (2003, 2017), True, 'import numpy as np\n'), ((2140, 2238), 'scipy.interpolate.InterpolatedUnivariateSpline', 'interpolate.InterpolatedUnivariateSpline', (['rho0_array', 'c_array'], {'w': 'None', 'bbox': '[None, None]', 'k': '(3)'}), '(rho0_array, c_array, w=None, bbox=\n [None, None], k=3)\n', (2180, 2238), False, 'from scipy import interpolate\n'), ((891, 906), 'numpy.log', 'np.log', (['(1.0 + c)'], {}), '(1.0 + c)\n', (897, 906), True, 'import numpy as np\n'), ((1638, 1653), 'numpy.log', 'np.log', (['(1.0 + c)'], {}), '(1.0 + c)\n', (1644, 1653), True, 'import numpy as np\n')]
|
import argparse
import os, h5py
import numpy as np
import context
#from context import EcalEnergyGan
from EcalEnergyGan import discriminator as build_discriminator
from EcalEnergyGan import generator as build_generator
def get_parser():
parser = argparse.ArgumentParser(
description='Generate 3D images',
formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
parser.add_argument('--nevents', '-n', action='store', type=int,
default='1000', help='Number of events to simulate')
parser.add_argument('--latent-size', action='store', type=int, default=200,
help='size of random N(0, 1) latent space to sample')
parser.add_argument('--nrun', action='store', type=int, default=1,
help='size of random N(0, 1) latent space to sample')
parser.add_argument('--gweights', '-g', action='store', type=str,
default='params_generator_epoch_029.hdf5', help='path to generator weights file')
parser.add_argument('--dweights', '-d', action='store', type=str,
default='params_discriminator_epoch_029.hdf5', help='path to discriminator weights file')
return parser
parser = get_parser()
results = parser.parse_args()
n_events = results.nevents
latent_space = results.latent_size
gen_weights = results.gweights
disc_weights = results.dweights
#gen_weights='/data/svalleco/GAN/weights_gk/params_generator_epoch_029.hdf5'
#disc_weights='/data/svalleco/GAN/weights_gk/params_discriminator_epoch_029.hdf5'
outfile_name = 'generation{0:03d}.hdf5'.format(results.nrun)
#if not ((os.path.isfile(gen_weights)) & (os.path.isfile(disc_weights))):
# download from somewhere
# but for now just load mine
# gen_weights='params_generator_epoch_048.hdf5'
# disc_weights='params_discriminator_epoch_048.hdf5'
np.random.seed()
g = build_generator(latent_space, return_intermediate=False)
g.load_weights(gen_weights)
noise = np.random.normal(0, 1, (n_events, latent_space))
sampled_energies = np.random.uniform(1, 5, (n_events, 1))
generator_ip = np.multiply(sampled_energies, noise)
generated_images = g.predict(generator_ip, verbose=False, batch_size=128)
print(generated_images.shape)
def safe_mkdir(path):
'''
Safe mkdir (i.e., don't create if already exists,
and no violation of race conditions)
'''
from os import makedirs
from errno import EEXIST
try:
makedirs(path)
except OSError as exception:
if exception.errno != EEXIST:
raise exception
outdir = 'plots'
safe_mkdir(outdir)
#f = plt.figure(figsize=(6, 6))
bins = np.linspace(0, 1, 30)
#_ = plt.hist(isreal, bins=bins, histtype='step', label='GAN', color='green')
#plt.legend(ncol=2, mode='expand')
#plt.xlabel('P(real)')
#plt.ylabel('Number of events')
#plt.ylim(ymax=4000)
#plt.tight_layout()
#plt.savefig(os.path.join('..', outdir, 'prob_real.pdf'))
generated_images = np.squeeze(generated_images)
with h5py.File(outfile_name,'w') as outfile:
outfile.create_dataset('ECAL',data=generated_images)
|
[
"numpy.random.uniform",
"EcalEnergyGan.generator",
"h5py.File",
"numpy.random.seed",
"numpy.multiply",
"argparse.ArgumentParser",
"os.makedirs",
"numpy.random.normal",
"numpy.linspace",
"numpy.squeeze"
] |
[((1867, 1883), 'numpy.random.seed', 'np.random.seed', ([], {}), '()\n', (1881, 1883), True, 'import numpy as np\n'), ((1888, 1944), 'EcalEnergyGan.generator', 'build_generator', (['latent_space'], {'return_intermediate': '(False)'}), '(latent_space, return_intermediate=False)\n', (1903, 1944), True, 'from EcalEnergyGan import generator as build_generator\n'), ((1982, 2030), 'numpy.random.normal', 'np.random.normal', (['(0)', '(1)', '(n_events, latent_space)'], {}), '(0, 1, (n_events, latent_space))\n', (1998, 2030), True, 'import numpy as np\n'), ((2050, 2088), 'numpy.random.uniform', 'np.random.uniform', (['(1)', '(5)', '(n_events, 1)'], {}), '(1, 5, (n_events, 1))\n', (2067, 2088), True, 'import numpy as np\n'), ((2104, 2140), 'numpy.multiply', 'np.multiply', (['sampled_energies', 'noise'], {}), '(sampled_energies, noise)\n', (2115, 2140), True, 'import numpy as np\n'), ((2644, 2665), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(30)'], {}), '(0, 1, 30)\n', (2655, 2665), True, 'import numpy as np\n'), ((2958, 2986), 'numpy.squeeze', 'np.squeeze', (['generated_images'], {}), '(generated_images)\n', (2968, 2986), True, 'import numpy as np\n'), ((252, 370), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Generate 3D images"""', 'formatter_class': 'argparse.ArgumentDefaultsHelpFormatter'}), "(description='Generate 3D images', formatter_class=\n argparse.ArgumentDefaultsHelpFormatter)\n", (275, 370), False, 'import argparse\n'), ((2993, 3021), 'h5py.File', 'h5py.File', (['outfile_name', '"""w"""'], {}), "(outfile_name, 'w')\n", (3002, 3021), False, 'import os, h5py\n'), ((2454, 2468), 'os.makedirs', 'makedirs', (['path'], {}), '(path)\n', (2462, 2468), False, 'from os import makedirs\n')]
|
'''
AUTHORS:
NORSTRÖM, ARVID 19940206-3193,
HISELIUS, LEO 19940221-4192
'''
from collections import namedtuple
import numpy as np
import gym
import torch
import matplotlib.pyplot as plt
from tqdm import trange
from DQN_agent import RandomAgent, Agent
from DQN_agent import ExperienceReplayBuffer
import torch.optim as optim
import torch.nn as nn
from PPO_problem import LunarLander
best_ll = LunarLander(0.99, 3000, 300, [8,64,64,4], [8,64,64,4])
best_ll.Actor = torch.load('models/best_actor.pt')
episodes = np.arange(50)
env = gym.make('LunarLanderContinuous-v2')
episode_reward_list = []
for i in episodes:
done = False
state = env.reset()
total_episode_reward = 0.
t = 0
while not done:
# Take epsilon greedy action
state_tensor = torch.tensor([state],
requires_grad=False,
dtype=torch.float32)
with torch.no_grad():
action = best_ll.Actor(torch.tensor([state],device = best_ll.dev, requires_grad = False, dtype = torch.float32)).detach().numpy().reshape(2,2)
mean,cov = action[0].reshape(2,1),np.diag(action[1])
action = np.random.multivariate_normal(mean.reshape(2,),cov).reshape(2,1)
#action = np.random.uniform(-1,1,2)
next_state, reward, done, _ = env.step(action.reshape(2,))
total_episode_reward += reward
# Update state for next iteration
state = next_state
t += 1
# Append episode reward and total number of steps
episode_reward_list.append(total_episode_reward)
# Close environment
env.close()
np.save("p3_best_agent", episode_reward_list)
|
[
"numpy.save",
"gym.make",
"torch.load",
"PPO_problem.LunarLander",
"numpy.arange",
"numpy.diag",
"torch.no_grad",
"torch.tensor"
] |
[((401, 461), 'PPO_problem.LunarLander', 'LunarLander', (['(0.99)', '(3000)', '(300)', '[8, 64, 64, 4]', '[8, 64, 64, 4]'], {}), '(0.99, 3000, 300, [8, 64, 64, 4], [8, 64, 64, 4])\n', (412, 461), False, 'from PPO_problem import LunarLander\n'), ((472, 506), 'torch.load', 'torch.load', (['"""models/best_actor.pt"""'], {}), "('models/best_actor.pt')\n", (482, 506), False, 'import torch\n'), ((519, 532), 'numpy.arange', 'np.arange', (['(50)'], {}), '(50)\n', (528, 532), True, 'import numpy as np\n'), ((539, 575), 'gym.make', 'gym.make', (['"""LunarLanderContinuous-v2"""'], {}), "('LunarLanderContinuous-v2')\n", (547, 575), False, 'import gym\n'), ((1682, 1727), 'numpy.save', 'np.save', (['"""p3_best_agent"""', 'episode_reward_list'], {}), "('p3_best_agent', episode_reward_list)\n", (1689, 1727), True, 'import numpy as np\n'), ((782, 845), 'torch.tensor', 'torch.tensor', (['[state]'], {'requires_grad': '(False)', 'dtype': 'torch.float32'}), '([state], requires_grad=False, dtype=torch.float32)\n', (794, 845), False, 'import torch\n'), ((941, 956), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (954, 956), False, 'import torch\n'), ((1177, 1195), 'numpy.diag', 'np.diag', (['action[1]'], {}), '(action[1])\n', (1184, 1195), True, 'import numpy as np\n'), ((1006, 1094), 'torch.tensor', 'torch.tensor', (['[state]'], {'device': 'best_ll.dev', 'requires_grad': '(False)', 'dtype': 'torch.float32'}), '([state], device=best_ll.dev, requires_grad=False, dtype=torch.\n float32)\n', (1018, 1094), False, 'import torch\n')]
|
import numpy as np
r1 = 4
r2 = 7
r3 = np.lcm(r1, r2) # finding lowest common multiple of 4 and 7
print(r3)
arr = np.array([3, 6, 12])
x = np.lcm.reduce(arr) # finding lcm for elements of array
print(x)
arr = np.arange(5, 16) # getting elements from 5 to 15 for finding lcm
x = np.lcm.reduce(arr)
print(x)
|
[
"numpy.arange",
"numpy.lcm.reduce",
"numpy.array",
"numpy.lcm"
] |
[((39, 53), 'numpy.lcm', 'np.lcm', (['r1', 'r2'], {}), '(r1, r2)\n', (45, 53), True, 'import numpy as np\n'), ((131, 151), 'numpy.array', 'np.array', (['[3, 6, 12]'], {}), '([3, 6, 12])\n', (139, 151), True, 'import numpy as np\n'), ((156, 174), 'numpy.lcm.reduce', 'np.lcm.reduce', (['arr'], {}), '(arr)\n', (169, 174), True, 'import numpy as np\n'), ((239, 255), 'numpy.arange', 'np.arange', (['(5)', '(16)'], {}), '(5, 16)\n', (248, 255), True, 'import numpy as np\n'), ((320, 338), 'numpy.lcm.reduce', 'np.lcm.reduce', (['arr'], {}), '(arr)\n', (333, 338), True, 'import numpy as np\n')]
|
import numpy as np
def prune_data(dataset,npoints):
'''
for a given dataset, selects a subset of npoints samples through feature distance mapping
'''
l_param = 1.5
comparison_distance = 10.0
# Select first point randomly
sample_point = np.random.randint(low=0,high=np.shape(dataset)[0])
sample_dataset = dataset[sample_point,:].reshape(1,np.shape(dataset)[1])
# Do sample proposal till npoints samples are reached
k = 0
stride = 0
while stride < np.shape(dataset)[0]:
# Choose a random point
sample_point = np.random.randint(low=0,high=np.shape(dataset)[0])
sample = dataset[sample_point,:].reshape(1,np.shape(dataset)[1])
# Find relative distance from each existing member of dataset
sample_distance = np.divide(np.subtract(sample_dataset[:,:-1],sample[:,:-1]),np.maximum(sample_dataset[:,:-1],sample[:,:-1])) # Distance of input features
sample_distance = np.sum(np.abs(sample_distance),axis=1)
if sample_distance[0]>comparison_distance:
sample_dataset = np.concatenate((sample_dataset,sample),axis=0)
k = k+1
if k == npoints-1:
break
stride = stride + 1
if stride == np.shape(dataset)[0] - 1:
stride = 0
comparison_distance = comparison_distance / l_param
return sample_dataset
if __name__ == '__main__':
print('This file has different data pruning techniques')
|
[
"numpy.abs",
"numpy.maximum",
"numpy.subtract",
"numpy.shape",
"numpy.concatenate"
] |
[((372, 389), 'numpy.shape', 'np.shape', (['dataset'], {}), '(dataset)\n', (380, 389), True, 'import numpy as np\n'), ((497, 514), 'numpy.shape', 'np.shape', (['dataset'], {}), '(dataset)\n', (505, 514), True, 'import numpy as np\n'), ((804, 855), 'numpy.subtract', 'np.subtract', (['sample_dataset[:, :-1]', 'sample[:, :-1]'], {}), '(sample_dataset[:, :-1], sample[:, :-1])\n', (815, 855), True, 'import numpy as np\n'), ((853, 903), 'numpy.maximum', 'np.maximum', (['sample_dataset[:, :-1]', 'sample[:, :-1]'], {}), '(sample_dataset[:, :-1], sample[:, :-1])\n', (863, 903), True, 'import numpy as np\n'), ((964, 987), 'numpy.abs', 'np.abs', (['sample_distance'], {}), '(sample_distance)\n', (970, 987), True, 'import numpy as np\n'), ((1077, 1125), 'numpy.concatenate', 'np.concatenate', (['(sample_dataset, sample)'], {'axis': '(0)'}), '((sample_dataset, sample), axis=0)\n', (1091, 1125), True, 'import numpy as np\n'), ((295, 312), 'numpy.shape', 'np.shape', (['dataset'], {}), '(dataset)\n', (303, 312), True, 'import numpy as np\n'), ((676, 693), 'numpy.shape', 'np.shape', (['dataset'], {}), '(dataset)\n', (684, 693), True, 'import numpy as np\n'), ((603, 620), 'numpy.shape', 'np.shape', (['dataset'], {}), '(dataset)\n', (611, 620), True, 'import numpy as np\n'), ((1241, 1258), 'numpy.shape', 'np.shape', (['dataset'], {}), '(dataset)\n', (1249, 1258), True, 'import numpy as np\n')]
|
import numpy as np
import numcalc_methods
def get_matrix(nmx):
init_augmx = np.zeros((nmx, nmx + 1))
init_solvec = np.zeros(nmx)
print("Enter augmented matrix coefficients: ")
for i in range(nmx):
for j in range(nmx + 1):
init_augmx[i][j] = float(input(f"a[{str(i)}][{str(j)}] = "))
return init_augmx, init_solvec
if __name__ == "__main__":
try:
nmx = int(input("Enter number of unknowns: "))
except Exception:
pass
init_augmx, init_solvec = get_matrix(nmx)
print("Applying gauss elimination")
solvec = numcalc_methods.gauss_elimination(init_augmx, init_solvec, nmx)
print("The solution vector is: ")
for i in range(nmx):
print(f"x{i} = {solvec[i]:.2f}")
|
[
"numpy.zeros",
"numcalc_methods.gauss_elimination"
] |
[((83, 107), 'numpy.zeros', 'np.zeros', (['(nmx, nmx + 1)'], {}), '((nmx, nmx + 1))\n', (91, 107), True, 'import numpy as np\n'), ((126, 139), 'numpy.zeros', 'np.zeros', (['nmx'], {}), '(nmx)\n', (134, 139), True, 'import numpy as np\n'), ((586, 649), 'numcalc_methods.gauss_elimination', 'numcalc_methods.gauss_elimination', (['init_augmx', 'init_solvec', 'nmx'], {}), '(init_augmx, init_solvec, nmx)\n', (619, 649), False, 'import numcalc_methods\n')]
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 10 15:32:08 2021
@author: twguest
"""
import numpy as np
from matplotlib import pyplot as plt
from felpy.utils.vis_utils import plot_fill_between
DATA_DIR = "/media/twguest/shared/data/nkb_sensing/beam_center_r0046.npy"
def load_data(DATA_DIR):
beam_area = np.load(DATA_DIR)
return beam_area
def beam_center_analysis(data, color = 'blue'):
### load beam area
plot_fill_between(data[:,:,0] - data[:,:,0].mean(),
title = "r0046 Horizontal Beam Center",
xlabel = "Pulse No.",
ylabel = "Horizontal Deviation from Mean ($\mu$m)",
plot_max = False,
color = color,
xlim = [0,data.shape[-3]])
plot_fill_between(data[:,:,1] - data[:,:,1].mean(),
title = "r0046 Vertical Beam Center",
xlabel = "Pulse No.",
ylabel = "Vertical Deviationfrom Mean ($\mu$m)",
plot_max = False,
color = color,
xlim = [0,data.shape[-3]])
plot_fill_between(np.moveaxis(data, 1,0)[:,:,0] - np.moveaxis(data, 1,0)[:,:,0].mean(),
title = "r0046 Horizontal Beam Center",
xlabel = "Pulse No.",
ylabel = "Horizontal Deviation from Mean ($\mu$m)",
plot_max = False,
color = color,
xlim = [0,np.moveaxis(data, 1,0).shape[-3]])
plt.plot(np.arange(data.std(0)[:,0].shape[0]),data.std(0)[:,0])
if __name__ == '__main__':
data = load_data(DATA_DIR)[3:103,]*1e6*28.9e-06
data = np.delete(data, 24, axis = -2)
beam_center_analysis(data, color = 'red')
|
[
"numpy.load",
"numpy.delete",
"numpy.moveaxis"
] |
[((342, 359), 'numpy.load', 'np.load', (['DATA_DIR'], {}), '(DATA_DIR)\n', (349, 359), True, 'import numpy as np\n'), ((1760, 1788), 'numpy.delete', 'np.delete', (['data', '(24)'], {'axis': '(-2)'}), '(data, 24, axis=-2)\n', (1769, 1788), True, 'import numpy as np\n'), ((1202, 1225), 'numpy.moveaxis', 'np.moveaxis', (['data', '(1)', '(0)'], {}), '(data, 1, 0)\n', (1213, 1225), True, 'import numpy as np\n'), ((1234, 1257), 'numpy.moveaxis', 'np.moveaxis', (['data', '(1)', '(0)'], {}), '(data, 1, 0)\n', (1245, 1257), True, 'import numpy as np\n'), ((1561, 1584), 'numpy.moveaxis', 'np.moveaxis', (['data', '(1)', '(0)'], {}), '(data, 1, 0)\n', (1572, 1584), 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.