code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
import numpy as np
import pylab as pl
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
global file_name
global extension,path
path='/Users/yves/fortran/GEOCLIM4/calibration/PD/' # / at the end of the line
opath='/Users/yves/fortran/GEOCLIM4/python/figs/'
extension=('out') #,'090_evol2','090_evol3']
xaxis='time (Myr)'
styling=list()
styling=['-','--',':','-.','.','o','^','-','-']
#runoff------------------------------
plt.figure(num=1)
file_label='run'
var=np.loadtxt(path+file_label+'.'+extension) #load files
pl.contourf(var)
#pl.subplot(2,2,3)
#i=0
#loop=True
#while (loop):
# i=i+1
# pl.plot(var[:,0]/1e6,var[:,5000+i])
# if i>5000:
# loop=False
#pl.legend(loc='upper right',fontsize=9)
#pl.xlabel(xaxis)
#pl.ylabel('atmospheric O2 (PAL)')
#plt.rcParams['xtick.labelsize'] = 7
#plt.rcParams['ytick.labelsize'] = 7
#pl.legend(loc='upper right',fontsize=7)
#pl.xlabel(xaxis)
#pl.ylabel('atmospheric CO2 (PAL)')
#runoff=var[:,[1:16384]] #extracting the ocean-atm fluxes
#print type(runoff)
# Atm_flux_total=list() #calculating the sum of the ocean-atm fluxes
# Atm_flux_total=np.sum(Atm_flux,axis=1) #sum of the columns
# pl.subplot(2,2,4)
# plt.rcParams['xtick.labelsize'] = 7
# plt.rcParams['ytick.labelsize'] = 7
# pl.plot(var[:,0]/1e6,Atm_flux_total/1e12,label=extension[i-1])
# pl.xlabel(xaxis)
# pl.ylabel('total ocean-atm CO2 flux (Tmol/yr)',fontsize=9)
# if i>nfile-1:
# loop=False
plt.show()
#plt.savefig(opath+'atmospheric.pdf',format='pdf')
plt.close(1)
| [
"matplotlib.pyplot.show",
"pylab.contourf",
"matplotlib.pyplot.close",
"matplotlib.pyplot.figure",
"numpy.loadtxt"
] | [((473, 490), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'num': '(1)'}), '(num=1)\n', (483, 490), True, 'import matplotlib.pyplot as plt\n'), ((512, 559), 'numpy.loadtxt', 'np.loadtxt', (["(path + file_label + '.' + extension)"], {}), "(path + file_label + '.' + extension)\n", (522, 559), True, 'import numpy as np\n'), ((579, 595), 'pylab.contourf', 'pl.contourf', (['var'], {}), '(var)\n', (590, 595), True, 'import pylab as pl\n'), ((1598, 1608), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1606, 1608), True, 'import matplotlib.pyplot as plt\n'), ((1660, 1672), 'matplotlib.pyplot.close', 'plt.close', (['(1)'], {}), '(1)\n', (1669, 1672), True, 'import matplotlib.pyplot as plt\n')] |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
#ensure dask and toolz are installed!
# https://github.com/pydata/xarray/issues/4164
import xarray as xr
import numpy as np
import pandas as pd
import pyresample
import pyproj
from pyproj import Transformer
import matplotlib.pyplot as plt
import glob
from natsort import natsorted
# In[ ]:
# For converting to a 10m height for use with WN
def logu(u, zin=40, zout=10):
z0=0.01
newu = u*np.log(zout/z0)/ np.log(zin/z0)
return newu
# In[ ]:
gem = xr.open_mfdataset("out.nc",combine='by_coords')
# In[ ]:
#The GEM winds were output at 40m, convert to a 10m windspeed
gem['u10'] = xr.apply_ufunc(logu,gem['u'],dask='allowed') # the GEM-CHM file has u @ 40m reference height
#zonal and meridonal components
gem['U10'] = -gem['u10']*np.sin(gem['vw_dir']*np.pi/180.)
gem['V10'] = -gem['u10']*np.cos(gem['vw_dir']*np.pi/180.)
# air temp needs to be in K
gem['t'] += 273.15
# In[ ]:
gem
# In[ ]:
#We are converting to a Lambert Conformal for Canada. Adjust as required.
#specified here and in the function below as proj_dict is needed later to build up the wrfout.nc meta data
proj_dict = {'proj':'lcc', 'lat_1':50, 'lat_2':70, 'lat_0':40, 'lon_0':-96, 'x_0':0, 'y_0':0, 'ellps':'GRS80', 'datum':'NAD83', 'units':'m'}
def resample(gem, variable, res,nx,ny, timestep):
if not isinstance(variable, list):
variable = [variable]
# Open with xarray
xref = gem
# Load 2D lat and lon
lat2d = xref.gridlat_0.values
lon2d = xref.gridlon_0.values
# Define the original swath required by pyresample
orig_def = pyresample.geometry.SwathDefinition(lons=lon2d, lats=lat2d)
####
# Definition of the target grid
###
# Definition of the Canadian LCC projection (https://spatialreference.org/ref/esri/canada-lambert-conformal-conic/)
proj_dict = {'proj':'lcc', 'lat_1':50, 'lat_2':70, 'lat_0':40, 'lon_0':-96, 'x_0':0, 'y_0':0, 'ellps':'GRS80', 'datum':'NAD83', 'units':'m'}
#Name of the grid
area_id = 'test_kan'
# Coordinate of the upper left corner of the grid
lat_upl = lat2d.max()
lon_upl = lon2d.min()
# Conversion from WGS84 lat/lon to coordinates in the Canadian LCC projection
transformer = Transformer.from_crs("EPSG:4326", "+proj=lcc +lat_1=50 +lat_2=70 +lat_0=40 +lon_0=-96 +x_0=0 +y_0=0 +ellps=GRS80 +datum=NAD83 +units=m +no_defs",always_xy=True)
xupl , yupl = transformer.transform(lon_upl,lat_upl)
# Definition of the targert grid according to pyresample
targ_def = pyresample.create_area_def(area_id, proj_dict,shape = (nx,ny),
upper_left_extent = (xupl,yupl),
resolution=(res, res),
description='Test LCC')
# Get the lat and lon corresponding to targ_def grid
# Maybe needed in the wrf_out.nc file??
lons, lats = targ_def.get_lonlats()
#different interp methods for the regrid
# # Nearest neighbor interpolation
# t_nearest = pyresample.kd_tree.resample_nearest(orig_def, tgem, \
# targ_def, radius_of_influence=500000, fill_value=None)
# # Bilinear interpolation
# t_bil = pyresample.bilinear.resample_bilinear(tgem, orig_def, targ_def)
resampled_gem = {}
for var in variable:
# Load variable to be interpolated (temperature here)
ingem = xref[var].values[timestep,:,:]
# IDW interpolation
wf = lambda r: 1/r**2
resampled_gem[var] = pyresample.kd_tree.resample_custom(orig_def, ingem,
targ_def, radius_of_influence=500000, neighbours=10,
weight_funcs=wf, fill_value=None)
resampled_gem[var] = np.flip(resampled_gem[var],axis=0)
return targ_def,resampled_gem
# In[ ]:
datetime = gem.datetime.to_pandas()
datetime = datetime.dt.strftime("%Y-%m-%d_%H:%M:%S")
datetime = datetime.values
#The strategy here is to regrid each timestep and output to a nc file that we later use the memory efficient Dask load to combine into one nc file
# this avoids having to hold it all in ram. I'm sure there is a way to do it with dask w/o the intermediatary step of the nc output, but I'm not sure how
for i, time in enumerate(datetime):
t = [time]
# convert the offset from epoch to datetime strings in the correct output
Time=xr.DataArray(np.array(t, dtype = np.dtype(('S', 16))), dims = ['Time']) # https://github.com/pydata/xarray/issues/3407
res_gem =2500.
# number of grids to output
nnx=151
nny=151
# these are the variables you want to resample
targ_def, resampled = resample(gem, ['t','U10','V10','HGT_P0_L1_GST'],res_gem,nnx,nny,timestep=i)
for k,d in resampled.items():
resampled[k] = xr.concat([xr.DataArray(d.data,dims=['south_north','west_east'])], 'Time')
lons, lats = targ_def.get_lonlats()
sn_dim = np.arange(0,nny)*res_gem
we_dim = np.arange(0,nnx)*res_gem
ds = xr.Dataset(
resampled,
{"Times":Time, 'south_north':sn_dim,'west_east':we_dim}
)
ds = ds.rename({'t':'T2'})
qcloud=xr.DataArray(np.zeros(lons.shape), dims = ['south_north','west_east']) # https://github.com/pydata/xarray/issues/3407
qcloud=xr.concat([qcloud], 'Time')
ds['QCLOUD'] = qcloud
# Add longitude/latitude
lon2d = xr.DataArray(np.flip(lons,axis=0), dims = ['south_north','west_east'])
ds['XLON'] =lon2d
lat2d = xr.DataArray(np.flip(lats,axis=0), dims = ['south_north','west_east'])
ds['XLAT'] =lat2d
ds.attrs['MAP_PROJ'] = 1 #LCC
ds.attrs['DX'] = res_gem
ds.attrs['DY'] = res_gem
clon,clat = targ_def.get_lonlat(int(targ_def.shape[0]/2),int(targ_def.shape[1]/2))
ds.attrs['CEN_LAT'] = clat
ds.attrs['CEN_LON'] = clon
ds.attrs['MOAD_CEN_LAT'] = proj_dict['lat_0']
ds.attrs['STAND_LON'] = proj_dict['lon_0']
ds.attrs['TRUELAT1'] = proj_dict['lat_1']
ds.attrs['TRUELAT2'] = proj_dict['lat_1']
ds.attrs['BOTTOM-TOP_GRID_DIMENSION'] = 1 # 1 (surface) z-layer,
ds.attrs['TITLE']='WRF proxy' #required for WindNinja
#output the temp files, esnure tmp dir exists
ds.to_netcdf(f'tmp/wrfout-{i}.nc',
format='NETCDF4',
encoding={
'Times': {
'zlib':True,
'complevel':5,
'char_dim_name':'DateStrLen'
}
},
unlimited_dims={'Time':True})
# In[ ]:
# In[ ]:
files = glob.glob('tmp/wrfout-*nc')
files=natsorted(files) #ensure the sorting is reasonable
# In[ ]:
# good for testing to try only a couple files
# files = files[:10]
# files
# In[ ]:
ds = xr.concat([xr.open_mfdataset(f,combine='by_coords') for f in files],dim='Time')
# In[ ]:
ds.to_netcdf(f'wrfout-gem.nc',
format='NETCDF4',
encoding={
'Times': {
'zlib':True,
'complevel':5,
'char_dim_name':'DateStrLen'
}
},
unlimited_dims={'Time':True})
# In[ ]:
# fig = plt.figure(figsize=(5,15))
# ax = fig.add_subplot(311)
# ax.imshow(t_nearest,interpolation='nearest')
# ax.set_title("Nearest neighbor")
# ax = fig.add_subplot(312)
# ax.imshow(t_idw,interpolation='nearest')
# plt.title("IDW of square distance \n using 10 neighbors");
# ax = fig.add_subplot(313)
# ax.imshow(t_bil,interpolation='nearest')
# plt.title("Bilinear Interpolation");
# plt.show()
| [
"pyresample.create_area_def",
"numpy.flip",
"numpy.log",
"xarray.apply_ufunc",
"pyresample.kd_tree.resample_custom",
"numpy.zeros",
"numpy.dtype",
"pyproj.Transformer.from_crs",
"xarray.Dataset",
"xarray.concat",
"numpy.sin",
"pyresample.geometry.SwathDefinition",
"numpy.arange",
"numpy.co... | [((515, 563), 'xarray.open_mfdataset', 'xr.open_mfdataset', (['"""out.nc"""'], {'combine': '"""by_coords"""'}), "('out.nc', combine='by_coords')\n", (532, 563), True, 'import xarray as xr\n'), ((651, 697), 'xarray.apply_ufunc', 'xr.apply_ufunc', (['logu', "gem['u']"], {'dask': '"""allowed"""'}), "(logu, gem['u'], dask='allowed')\n", (665, 697), True, 'import xarray as xr\n'), ((6687, 6714), 'glob.glob', 'glob.glob', (['"""tmp/wrfout-*nc"""'], {}), "('tmp/wrfout-*nc')\n", (6696, 6714), False, 'import glob\n'), ((6721, 6737), 'natsort.natsorted', 'natsorted', (['files'], {}), '(files)\n', (6730, 6737), False, 'from natsort import natsorted\n'), ((802, 839), 'numpy.sin', 'np.sin', (["(gem['vw_dir'] * np.pi / 180.0)"], {}), "(gem['vw_dir'] * np.pi / 180.0)\n", (808, 839), True, 'import numpy as np\n'), ((860, 897), 'numpy.cos', 'np.cos', (["(gem['vw_dir'] * np.pi / 180.0)"], {}), "(gem['vw_dir'] * np.pi / 180.0)\n", (866, 897), True, 'import numpy as np\n'), ((1641, 1700), 'pyresample.geometry.SwathDefinition', 'pyresample.geometry.SwathDefinition', ([], {'lons': 'lon2d', 'lats': 'lat2d'}), '(lons=lon2d, lats=lat2d)\n', (1676, 1700), False, 'import pyresample\n'), ((2280, 2450), 'pyproj.Transformer.from_crs', 'Transformer.from_crs', (['"""EPSG:4326"""', '"""+proj=lcc +lat_1=50 +lat_2=70 +lat_0=40 +lon_0=-96 +x_0=0 +y_0=0 +ellps=GRS80 +datum=NAD83 +units=m +no_defs"""'], {'always_xy': '(True)'}), "('EPSG:4326',\n '+proj=lcc +lat_1=50 +lat_2=70 +lat_0=40 +lon_0=-96 +x_0=0 +y_0=0 +ellps=GRS80 +datum=NAD83 +units=m +no_defs'\n , always_xy=True)\n", (2300, 2450), False, 'from pyproj import Transformer\n'), ((2575, 2725), 'pyresample.create_area_def', 'pyresample.create_area_def', (['area_id', 'proj_dict'], {'shape': '(nx, ny)', 'upper_left_extent': '(xupl, yupl)', 'resolution': '(res, res)', 'description': '"""Test LCC"""'}), "(area_id, proj_dict, shape=(nx, ny),\n upper_left_extent=(xupl, yupl), resolution=(res, res), description=\n 'Test LCC')\n", (2601, 2725), False, 'import pyresample\n'), ((5174, 5260), 'xarray.Dataset', 'xr.Dataset', (['resampled', "{'Times': Time, 'south_north': sn_dim, 'west_east': we_dim}"], {}), "(resampled, {'Times': Time, 'south_north': sn_dim, 'west_east':\n we_dim})\n", (5184, 5260), True, 'import xarray as xr\n'), ((5455, 5482), 'xarray.concat', 'xr.concat', (['[qcloud]', '"""Time"""'], {}), "([qcloud], 'Time')\n", (5464, 5482), True, 'import xarray as xr\n'), ((465, 481), 'numpy.log', 'np.log', (['(zin / z0)'], {}), '(zin / z0)\n', (471, 481), True, 'import numpy as np\n'), ((3546, 3693), 'pyresample.kd_tree.resample_custom', 'pyresample.kd_tree.resample_custom', (['orig_def', 'ingem', 'targ_def'], {'radius_of_influence': '(500000)', 'neighbours': '(10)', 'weight_funcs': 'wf', 'fill_value': 'None'}), '(orig_def, ingem, targ_def,\n radius_of_influence=500000, neighbours=10, weight_funcs=wf, fill_value=None\n )\n', (3580, 3693), False, 'import pyresample\n'), ((3913, 3948), 'numpy.flip', 'np.flip', (['resampled_gem[var]'], {'axis': '(0)'}), '(resampled_gem[var], axis=0)\n', (3920, 3948), True, 'import numpy as np\n'), ((5101, 5118), 'numpy.arange', 'np.arange', (['(0)', 'nny'], {}), '(0, nny)\n', (5110, 5118), True, 'import numpy as np\n'), ((5139, 5156), 'numpy.arange', 'np.arange', (['(0)', 'nnx'], {}), '(0, nnx)\n', (5148, 5156), True, 'import numpy as np\n'), ((5339, 5359), 'numpy.zeros', 'np.zeros', (['lons.shape'], {}), '(lons.shape)\n', (5347, 5359), True, 'import numpy as np\n'), ((5564, 5585), 'numpy.flip', 'np.flip', (['lons'], {'axis': '(0)'}), '(lons, axis=0)\n', (5571, 5585), True, 'import numpy as np\n'), ((5671, 5692), 'numpy.flip', 'np.flip', (['lats'], {'axis': '(0)'}), '(lats, axis=0)\n', (5678, 5692), True, 'import numpy as np\n'), ((6889, 6930), 'xarray.open_mfdataset', 'xr.open_mfdataset', (['f'], {'combine': '"""by_coords"""'}), "(f, combine='by_coords')\n", (6906, 6930), True, 'import xarray as xr\n'), ((448, 465), 'numpy.log', 'np.log', (['(zout / z0)'], {}), '(zout / z0)\n', (454, 465), True, 'import numpy as np\n'), ((4591, 4610), 'numpy.dtype', 'np.dtype', (["('S', 16)"], {}), "(('S', 16))\n", (4599, 4610), True, 'import numpy as np\n'), ((4982, 5037), 'xarray.DataArray', 'xr.DataArray', (['d.data'], {'dims': "['south_north', 'west_east']"}), "(d.data, dims=['south_north', 'west_east'])\n", (4994, 5037), True, 'import xarray as xr\n')] |
import numpy as np
import random
import matplotlib.pyplot as plt
from tqdm import tqdm
def read_data_set(path, add_intercept=False):
# read data set at given path
features = []
classes = []
with open(path, "r") as f:
for line in f.readlines():
sample = line.strip().split("\t")
feat, label = sample[:-1], sample[-1]
features.append([float(feature) for feature in feat])
if add_intercept:
features[-1].insert(0, 1)
classes.append(int(label))
return np.array(features), np.array(classes)
def split_data_set(x, y, train_percent):
# split data set between train/test data
assert 1 <= train_percent <= 100
num_train = int(train_percent/100 * len(x))
if num_train == 0:
num_train = 1
train_set = set(random.sample(range(len(x)), num_train))
test_set = set(range(len(x))) - train_set
train_x = []
train_y = []
test_x = []
test_y = []
for train_idx in train_set:
train_x.append(x[train_idx])
train_y.append(y[train_idx])
for test_idx in test_set:
test_x.append(x[test_idx])
test_y.append(y[test_idx])
return np.array(train_x), np.array(train_y), np.array(test_x), np.array(test_y)
# computes sigmoid for a np array of values z
def sig(z): return 1/(1 + np.exp(-z))
# applies sigmoid for dot product between a vector of features x and a vector of weights w
# x.shape[1] == w.shape[0]
def apply_sig(x, w):
return sig(np.dot(x, w))
def cost_function(x, y, w):
"""
computes the logistic regression cost of a vector of features x, with their corresponding labels y
and a vector of weights w
"""
z = np.dot(x, w)
return -sum(y*np.log(sig(z)) + (1 - y)*np.log(1 - sig(z)))/x.shape[0]
def log_reg_non_stoch(x, y, lr, max_iterations, print_iter_num, verbose=False):
# computes the weights a vector of features x and their corresponding labels y
# using the non stochastic logistic regression algorithm
if isinstance(x, list):
x = np.array(x)
if isinstance(y, list):
y = np.array(y)
n, m = x.shape
weights = np.random.rand(m)
best_weights = weights
best_cost = np.inf
loss = []
for iteration in tqdm(range(max_iterations)):
diff = apply_sig(x, weights) - y
weights = weights - lr/n * np.dot(x.T, diff)
current_loss = cost_function(x, y, weights)
if current_loss < best_cost:
best_cost = current_loss
best_weights = weights
loss.append(current_loss)
if iteration % print_iter_num == 0 and verbose is True:
print(f"Iteration: {iteration}, has cost: {current_loss}")
return best_weights, weights, loss
def log_reg_stoch(x, y, lr, max_iterations, print_iter_num, verbose=False):
# computes the weights a vector of features x and their corresponding labels y
# using the non stochastic logistic regression algorithm
if isinstance(x, list):
x = np.array(x)
if isinstance(y, list):
y = np.array(y)
n, m = x.shape
weights = np.random.rand(m)
best_weights = weights
best_cost = np.inf
loss = []
for iteration in tqdm(range(max_iterations)):
for i in range(len(x)):
diff = sig(np.dot(x[i], weights)) - y[i]
weights = weights - lr/n * diff * x[i]
current_loss = cost_function(x, y, weights)
if current_loss < best_cost:
best_cost = current_loss
best_weights = weights
loss.append(current_loss)
if iteration % print_iter_num == 0 and verbose is True:
print(f"Iteration: {iteration}, has cost: {current_loss}")
return best_weights, weights, loss
def predict(x, w):
# predicts the binary class of a vector of features x, using a vector of weights w
return np.array([1 if pred > 0.5 else 0 for pred in apply_sig(x, w)])
def error_rate(x, y, w):
# computes error rate for a vector of features x with the corresponding labels, using a vector of
# weights w
return sum(np.abs(predict(x, w) - y)) / len(y)
def normalize_data(x, n_type='linear'):
# normalizes the input vector x
# n_type can be 'z-score' or 'linear'
if isinstance(x, list):
x = np.arange(x)
if n_type == 'linear':
mins = np.min(x, axis=0)
maxs = np.max(x, axis=0)
for i in range(len(mins)):
if mins[i] == maxs[i]:
mins[i] = 0
return (x - mins)/(maxs - mins)
elif n_type == 'z-score':
return (x - np.mean(x, axis=0))/np.std(x, axis=0)
else:
return None
def plot_2d_data(x, y):
# plot 2d data
x_0 = [x[i][1] for i in range(len(x)) if y[i] == 0]
y_0 = [x[i][2] for i in range(len(x)) if y[i] == 0]
x_1 = [x[i][1] for i in range(len(x)) if y[i] == 1]
y_1 = [x[i][2] for i in range(len(x)) if y[i] == 1]
plt.plot(x_0, y_0, "o", label='0 class')
plt.plot(x_1, y_1, "s", label='1 class')
plt.legend()
plt.show()
def plot_loss(loss):
plt.plot(range(len(loss)), loss)
plt.show()
def plot_2d_decision_boundary(x, y, w):
x_0 = [x[i][1] for i in range(len(x)) if y[i] == 0]
y_0 = [x[i][2] for i in range(len(x)) if y[i] == 0]
x_1 = [x[i][1] for i in range(len(x)) if y[i] == 1]
y_1 = [x[i][2] for i in range(len(x)) if y[i] == 1]
x_line = np.arange(0, 1, 0.01)
y_line = (-w[0] - w[1]*x_line)/w[2]
plt.plot(x_0, y_0, "o", label='0 class')
plt.plot(x_1, y_1, "s", label='1 class')
plt.plot(x_line, y_line, label='Decision line')
plt.legend()
plt.show()
| [
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"numpy.std",
"matplotlib.pyplot.legend",
"numpy.min",
"numpy.max",
"numpy.arange",
"numpy.array",
"numpy.exp",
"numpy.mean",
"numpy.random.rand",
"numpy.dot"
] | [((1728, 1740), 'numpy.dot', 'np.dot', (['x', 'w'], {}), '(x, w)\n', (1734, 1740), True, 'import numpy as np\n'), ((2181, 2198), 'numpy.random.rand', 'np.random.rand', (['m'], {}), '(m)\n', (2195, 2198), True, 'import numpy as np\n'), ((3141, 3158), 'numpy.random.rand', 'np.random.rand', (['m'], {}), '(m)\n', (3155, 3158), True, 'import numpy as np\n'), ((4961, 5001), 'matplotlib.pyplot.plot', 'plt.plot', (['x_0', 'y_0', '"""o"""'], {'label': '"""0 class"""'}), "(x_0, y_0, 'o', label='0 class')\n", (4969, 5001), True, 'import matplotlib.pyplot as plt\n'), ((5006, 5046), 'matplotlib.pyplot.plot', 'plt.plot', (['x_1', 'y_1', '"""s"""'], {'label': '"""1 class"""'}), "(x_1, y_1, 's', label='1 class')\n", (5014, 5046), True, 'import matplotlib.pyplot as plt\n'), ((5051, 5063), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (5061, 5063), True, 'import matplotlib.pyplot as plt\n'), ((5068, 5078), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5076, 5078), True, 'import matplotlib.pyplot as plt\n'), ((5143, 5153), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5151, 5153), True, 'import matplotlib.pyplot as plt\n'), ((5435, 5456), 'numpy.arange', 'np.arange', (['(0)', '(1)', '(0.01)'], {}), '(0, 1, 0.01)\n', (5444, 5456), True, 'import numpy as np\n'), ((5502, 5542), 'matplotlib.pyplot.plot', 'plt.plot', (['x_0', 'y_0', '"""o"""'], {'label': '"""0 class"""'}), "(x_0, y_0, 'o', label='0 class')\n", (5510, 5542), True, 'import matplotlib.pyplot as plt\n'), ((5547, 5587), 'matplotlib.pyplot.plot', 'plt.plot', (['x_1', 'y_1', '"""s"""'], {'label': '"""1 class"""'}), "(x_1, y_1, 's', label='1 class')\n", (5555, 5587), True, 'import matplotlib.pyplot as plt\n'), ((5592, 5639), 'matplotlib.pyplot.plot', 'plt.plot', (['x_line', 'y_line'], {'label': '"""Decision line"""'}), "(x_line, y_line, label='Decision line')\n", (5600, 5639), True, 'import matplotlib.pyplot as plt\n'), ((5644, 5656), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (5654, 5656), True, 'import matplotlib.pyplot as plt\n'), ((5661, 5671), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5669, 5671), True, 'import matplotlib.pyplot as plt\n'), ((558, 576), 'numpy.array', 'np.array', (['features'], {}), '(features)\n', (566, 576), True, 'import numpy as np\n'), ((578, 595), 'numpy.array', 'np.array', (['classes'], {}), '(classes)\n', (586, 595), True, 'import numpy as np\n'), ((1211, 1228), 'numpy.array', 'np.array', (['train_x'], {}), '(train_x)\n', (1219, 1228), True, 'import numpy as np\n'), ((1230, 1247), 'numpy.array', 'np.array', (['train_y'], {}), '(train_y)\n', (1238, 1247), True, 'import numpy as np\n'), ((1249, 1265), 'numpy.array', 'np.array', (['test_x'], {}), '(test_x)\n', (1257, 1265), True, 'import numpy as np\n'), ((1267, 1283), 'numpy.array', 'np.array', (['test_y'], {}), '(test_y)\n', (1275, 1283), True, 'import numpy as np\n'), ((1527, 1539), 'numpy.dot', 'np.dot', (['x', 'w'], {}), '(x, w)\n', (1533, 1539), True, 'import numpy as np\n'), ((2083, 2094), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (2091, 2094), True, 'import numpy as np\n'), ((2135, 2146), 'numpy.array', 'np.array', (['y'], {}), '(y)\n', (2143, 2146), True, 'import numpy as np\n'), ((3043, 3054), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (3051, 3054), True, 'import numpy as np\n'), ((3095, 3106), 'numpy.array', 'np.array', (['y'], {}), '(y)\n', (3103, 3106), True, 'import numpy as np\n'), ((4322, 4334), 'numpy.arange', 'np.arange', (['x'], {}), '(x)\n', (4331, 4334), True, 'import numpy as np\n'), ((4378, 4395), 'numpy.min', 'np.min', (['x'], {'axis': '(0)'}), '(x, axis=0)\n', (4384, 4395), True, 'import numpy as np\n'), ((4411, 4428), 'numpy.max', 'np.max', (['x'], {'axis': '(0)'}), '(x, axis=0)\n', (4417, 4428), True, 'import numpy as np\n'), ((1359, 1369), 'numpy.exp', 'np.exp', (['(-z)'], {}), '(-z)\n', (1365, 1369), True, 'import numpy as np\n'), ((2390, 2407), 'numpy.dot', 'np.dot', (['x.T', 'diff'], {}), '(x.T, diff)\n', (2396, 2407), True, 'import numpy as np\n'), ((4637, 4654), 'numpy.std', 'np.std', (['x'], {'axis': '(0)'}), '(x, axis=0)\n', (4643, 4654), True, 'import numpy as np\n'), ((3329, 3350), 'numpy.dot', 'np.dot', (['x[i]', 'weights'], {}), '(x[i], weights)\n', (3335, 3350), True, 'import numpy as np\n'), ((4617, 4635), 'numpy.mean', 'np.mean', (['x'], {'axis': '(0)'}), '(x, axis=0)\n', (4624, 4635), True, 'import numpy as np\n')] |
import numpy as np
from scipy.interpolate import interp1d
x = np.array([5,10,20,40,60,80])
nx = len(x)
flist = ('exp_r_Z_05.dat', 'exp_r_Z_10.dat', 'exp_r_Z_20.dat', 'exp_r_Z_40.dat', 'exp_r_Z_60.dat', 'exp_r_Z_80.dat')
print(flist)
fwhm_y = np.zeros(nx)
for i,file in enumerate(flist):
data = np.loadtxt(file)
r = data[:,0]
y = data[:,1]
n = len(y)
ymid = 0.5*(np.max(y) + np.min(y))
f_interp = interp1d(y[int(n/2):],r[int(n/2):])
rmid = f_interp(ymid)
print(rmid, ymid)
fwhm_y[i] = 2*rmid
data = np.vstack((x,fwhm_y)).T
np.savetxt("fwhm_Z.dat",data)
#-----------------------------------------------------
x = np.array([0,5,10,20,40,60,80])
nx = len(x)
flist = ('exp_r_v_0.dat', 'exp_r_v_05.dat', 'exp_r_v_10.dat', 'exp_r_v_20.dat', 'exp_r_v_40.dat', 'exp_r_v_60.dat', 'exp_r_v_80.dat')
print(flist)
fwhm_y = np.zeros(nx)
for i,file in enumerate(flist):
data = np.loadtxt(file)
r = data[:,0]
y = data[:,1]
n = len(y)
ymid = 0.5*(np.max(y) + np.min(y))
f_interp = interp1d(y[int(n/2):],r[int(n/2):])
rmid = f_interp(ymid)
print(rmid, ymid)
fwhm_y[i] = 2*rmid/0.008
data = np.vstack((x,fwhm_y)).T
np.savetxt("fwhm_u.dat",data)
| [
"numpy.savetxt",
"numpy.zeros",
"numpy.max",
"numpy.min",
"numpy.array",
"numpy.loadtxt",
"numpy.vstack"
] | [((63, 96), 'numpy.array', 'np.array', (['[5, 10, 20, 40, 60, 80]'], {}), '([5, 10, 20, 40, 60, 80])\n', (71, 96), True, 'import numpy as np\n'), ((243, 255), 'numpy.zeros', 'np.zeros', (['nx'], {}), '(nx)\n', (251, 255), True, 'import numpy as np\n'), ((660, 696), 'numpy.array', 'np.array', (['[0, 5, 10, 20, 40, 60, 80]'], {}), '([0, 5, 10, 20, 40, 60, 80])\n', (668, 696), True, 'import numpy as np\n'), ((859, 871), 'numpy.zeros', 'np.zeros', (['nx'], {}), '(nx)\n', (867, 871), True, 'import numpy as np\n'), ((299, 315), 'numpy.loadtxt', 'np.loadtxt', (['file'], {}), '(file)\n', (309, 315), True, 'import numpy as np\n'), ((569, 599), 'numpy.savetxt', 'np.savetxt', (['"""fwhm_Z.dat"""', 'data'], {}), "('fwhm_Z.dat', data)\n", (579, 599), True, 'import numpy as np\n'), ((915, 931), 'numpy.loadtxt', 'np.loadtxt', (['file'], {}), '(file)\n', (925, 931), True, 'import numpy as np\n'), ((1191, 1221), 'numpy.savetxt', 'np.savetxt', (['"""fwhm_u.dat"""', 'data'], {}), "('fwhm_u.dat', data)\n", (1201, 1221), True, 'import numpy as np\n'), ((541, 563), 'numpy.vstack', 'np.vstack', (['(x, fwhm_y)'], {}), '((x, fwhm_y))\n', (550, 563), True, 'import numpy as np\n'), ((1163, 1185), 'numpy.vstack', 'np.vstack', (['(x, fwhm_y)'], {}), '((x, fwhm_y))\n', (1172, 1185), True, 'import numpy as np\n'), ((384, 393), 'numpy.max', 'np.max', (['y'], {}), '(y)\n', (390, 393), True, 'import numpy as np\n'), ((396, 405), 'numpy.min', 'np.min', (['y'], {}), '(y)\n', (402, 405), True, 'import numpy as np\n'), ((1000, 1009), 'numpy.max', 'np.max', (['y'], {}), '(y)\n', (1006, 1009), True, 'import numpy as np\n'), ((1012, 1021), 'numpy.min', 'np.min', (['y'], {}), '(y)\n', (1018, 1021), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
"""
Test the FlowModel object.
"""
import numpy as np
import pickle
import pytest
import torch
from unittest.mock import create_autospec, MagicMock, patch
from nessai.flowmodel import update_config, FlowModel
@pytest.fixture()
def data_dim():
return 2
@pytest.fixture()
def model():
return create_autospec(FlowModel)
@pytest.fixture(scope='function')
def flow_model(flow_config, data_dim, tmpdir):
flow_config['model_config']['n_inputs'] = data_dim
output = str(tmpdir.mkdir('flowmodel'))
return FlowModel(flow_config, output=output)
def test_update_config_none():
"""Test update config for no input"""
config = update_config(None)
assert 'model_config' in config
def test_update_config_invalid_type():
"""Test update config when an invalid argument is specified"""
with pytest.raises(TypeError) as excinfo:
update_config(False)
assert 'Must pass a dictionary' in str(excinfo.value)
@pytest.mark.parametrize('noise_scale', ['auto', 4])
def test_update_config_invalid_noise_scale(noise_scale):
"""Assert an error is raised if noise_scale is not a float or adapative."""
config = {'noise_scale': noise_scale}
with pytest.raises(ValueError) as excinfo:
update_config(config)
assert 'noise_scale must be a float or' in str(excinfo.value)
def test_update_config_n_neurons():
"""Assert the n_neurons is set to 2x n_inputs"""
config = dict(model_config=dict(n_inputs=10))
config = update_config(config)
assert config['model_config']['n_neurons'] == 20
def test_init_no_config(tmpdir):
"""Test the init method with no config specified"""
output = str(tmpdir.mkdir('no_config'))
default_config = update_config(None)
fm = FlowModel(output=output)
assert fm.model_config == default_config['model_config']
def test_init_config_class(tmpdir):
"""Test the init and save methods when specifying `flow` as a class"""
from nessai.flows import RealNVP
output = str(tmpdir.mkdir('no_config'))
config = dict(model_config=dict(flow=RealNVP))
fm = FlowModel(config=config, output=output)
assert fm.model_config['flow'].__name__ == 'RealNVP'
def test_initialise(model):
"""Test the initialise method"""
model.get_optimiser = MagicMock()
model.model_config = dict(n_neurons=2)
model.inference_device = None
model.optimiser = 'adam'
model.optimiser_kwargs = {'weights': 0.1}
with patch('nessai.flowmodel.configure_model',
return_value=('model', 'cpu')) as mock:
FlowModel.initialise(model)
mock.assert_called_once_with(model.model_config)
model.get_optimiser.assert_called_once_with('adam', weights=0.1)
assert model.inference_device == torch.device('cpu')
@pytest.mark.parametrize('optimiser', ['Adam', 'AdamW', 'SGD'])
def test_get_optimiser(model, optimiser):
"""Test to make sure the three supported optimisers work"""
model.lr = 0.1
model.model = MagicMock()
with patch(f'torch.optim.{optimiser}') as mock:
FlowModel.get_optimiser(model, optimiser)
mock.assert_called_once()
@pytest.mark.parametrize('val_size, batch_size', [(0.1, 100),
(0.5, 'all')])
def test_prep_data(flow_model, data_dim, val_size, batch_size):
"""
Test the data prep, make sure batch sizes and validation size
produce the correct result.
"""
n = 100
x = np.random.randn(n, data_dim)
train, val = flow_model.prep_data(x, val_size, batch_size)
if batch_size == 'all':
batch_size = int(n * (1 - val_size))
assert flow_model.batch_size == batch_size
assert len(train) + len(val) == n
@pytest.mark.parametrize('val_size, batch_size', [(0.1, 100),
(0.5, 'all')])
def test_prep_data_dataloader(flow_model, data_dim, val_size, batch_size):
"""
Test the data prep, make sure batch sizes and validation size
produce the correct result.
"""
n = 100
x = np.random.randn(n, data_dim)
train, val = flow_model.prep_data(
x, val_size, batch_size, use_dataloader=True)
train_batch = next(iter(train))[0]
val_batch = next(iter(val))[0]
if batch_size == 'all':
batch_size = int(n * (1 - val_size))
assert train.batch_size == batch_size
assert list(val_batch.shape) == [int(val_size * n), data_dim]
assert len(train) * train_batch.shape[0] + val_batch.shape[0] == n
@pytest.mark.parametrize('batch_size', [None, '10', True, False])
def test_incorrect_batch_size_type(flow_model, data_dim, batch_size):
"""Ensure the non-interger batch sizes do not work"""
n = 1000
x = np.random.randn(n, data_dim)
with pytest.raises(RuntimeError) as excinfo:
flow_model.prep_data(x, 0.1, batch_size)
assert 'Unknown batch size' in str(excinfo.value)
@pytest.mark.parametrize('dataloader', [False, True])
def test_training(flow_model, data_dim, dataloader):
"""Test class until training"""
x = np.random.randn(1000, data_dim)
flow_model.use_dataloader = dataloader
flow_model.train(x)
assert flow_model.weights_file is not None
@pytest.mark.parametrize('key, value', [('annealing', True),
('noise_scale', 0.1),
('noise_scale', 'adaptive'),
('max_epochs', 51)])
def test_training_additional_config_args(flow_config, data_dim, tmpdir,
key, value):
"""
Test training with different config args
"""
flow_config['model_config']['n_inputs'] = data_dim
flow_config[key] = value
output = str(tmpdir.mkdir('flowmodel'))
flow_model = FlowModel(flow_config, output=output)
assert getattr(flow_model, key) == value
x = np.random.randn(100, data_dim)
flow_model.train(x)
def test_early_optimiser_init(flow_model):
"""Ensure calling the opitmiser before the model raises an error"""
with pytest.raises(RuntimeError) as excinfo:
flow_model.get_optimiser()
assert 'Cannot initialise optimiser' in str(excinfo.value)
@pytest.mark.parametrize('weights', [False, True])
@pytest.mark.parametrize('perms', [False, True])
def test_reset_model(flow_model, weights, perms):
"""Test resetting the model"""
flow_model.initialise()
flow_model.reset_model(weights=weights, permutations=perms)
def test_sample_and_log_prob_not_initialised(flow_model, data_dim):
"""
Ensure user cannot call the method before the model initialise.
"""
with pytest.raises(RuntimeError) as excinfo:
flow_model.sample_and_log_prob()
assert 'Model is not initialised' in str(excinfo.value)
@pytest.mark.parametrize('N', [1, 100])
def test_sample_and_log_prob_no_latent(flow_model, data_dim, N):
"""
Test the basic use of sample and log prob and ensure correct output
shapes.
"""
flow_model.initialise()
x, log_prob = flow_model.sample_and_log_prob(N=N)
assert x.shape == (N, data_dim)
assert log_prob.size == N
@pytest.mark.parametrize('N', [1, 100])
def test_sample_and_log_prob_with_latent(flow_model, data_dim, N):
"""
Test the basic use of sample and log prob when samples from the
latent space are provided
"""
flow_model.initialise()
z = np.random.randn(N, data_dim)
x, log_prob = flow_model.sample_and_log_prob(z=z)
assert x.shape == (N, data_dim)
assert log_prob.size == N
@pytest.mark.parametrize('N', [1, 100])
def test_forward_and_log_prob(flow_model, data_dim, N):
"""Test the basic use of forward and log prob"""
flow_model.initialise()
x = np.random.randn(N, data_dim)
z, log_prob = flow_model.forward_and_log_prob(x)
assert z.shape == (N, data_dim)
assert log_prob.size == N
def test_move_to_update_default(model):
"""Ensure the stored device is updated"""
model.device = 'cuda'
model.model = MagicMock()
model.model.to = MagicMock()
FlowModel.move_to(model, 'cpu', update_default=True)
assert model.device == torch.device('cpu')
model.model.to.assert_called_once()
@patch('torch.save')
def test_save_weights(mock_save, model):
"""Test saving the weights"""
model.model = MagicMock()
FlowModel.save_weights(model, 'model.pt')
mock_save.assert_called_once()
assert model.weights_file == 'model.pt'
def test_get_state(flow_model):
"""Make the object can be pickled"""
pickle.dumps(flow_model)
| [
"unittest.mock.create_autospec",
"unittest.mock.MagicMock",
"nessai.flowmodel.FlowModel.get_optimiser",
"numpy.random.randn",
"nessai.flowmodel.FlowModel",
"pytest.fixture",
"nessai.flowmodel.FlowModel.initialise",
"unittest.mock.patch",
"nessai.flowmodel.FlowModel.save_weights",
"pytest.raises",
... | [((238, 254), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (252, 254), False, 'import pytest\n'), ((287, 303), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (301, 303), False, 'import pytest\n'), ((358, 390), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""function"""'}), "(scope='function')\n", (372, 390), False, 'import pytest\n'), ((974, 1025), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""noise_scale"""', "['auto', 4]"], {}), "('noise_scale', ['auto', 4])\n", (997, 1025), False, 'import pytest\n'), ((2782, 2844), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""optimiser"""', "['Adam', 'AdamW', 'SGD']"], {}), "('optimiser', ['Adam', 'AdamW', 'SGD'])\n", (2805, 2844), False, 'import pytest\n'), ((3135, 3210), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""val_size, batch_size"""', "[(0.1, 100), (0.5, 'all')]"], {}), "('val_size, batch_size', [(0.1, 100), (0.5, 'all')])\n", (3158, 3210), False, 'import pytest\n'), ((3714, 3789), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""val_size, batch_size"""', "[(0.1, 100), (0.5, 'all')]"], {}), "('val_size, batch_size', [(0.1, 100), (0.5, 'all')])\n", (3737, 3789), False, 'import pytest\n'), ((4502, 4566), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""batch_size"""', "[None, '10', True, False]"], {}), "('batch_size', [None, '10', True, False])\n", (4525, 4566), False, 'import pytest\n'), ((4900, 4952), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""dataloader"""', '[False, True]'], {}), "('dataloader', [False, True])\n", (4923, 4952), False, 'import pytest\n'), ((5199, 5334), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""key, value"""', "[('annealing', True), ('noise_scale', 0.1), ('noise_scale', 'adaptive'), (\n 'max_epochs', 51)]"], {}), "('key, value', [('annealing', True), ('noise_scale',\n 0.1), ('noise_scale', 'adaptive'), ('max_epochs', 51)])\n", (5222, 5334), False, 'import pytest\n'), ((6199, 6248), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""weights"""', '[False, True]'], {}), "('weights', [False, True])\n", (6222, 6248), False, 'import pytest\n'), ((6250, 6297), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""perms"""', '[False, True]'], {}), "('perms', [False, True])\n", (6273, 6297), False, 'import pytest\n'), ((6782, 6820), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""N"""', '[1, 100]'], {}), "('N', [1, 100])\n", (6805, 6820), False, 'import pytest\n'), ((7137, 7175), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""N"""', '[1, 100]'], {}), "('N', [1, 100])\n", (7160, 7175), False, 'import pytest\n'), ((7545, 7583), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""N"""', '[1, 100]'], {}), "('N', [1, 100])\n", (7568, 7583), False, 'import pytest\n'), ((8201, 8220), 'unittest.mock.patch', 'patch', (['"""torch.save"""'], {}), "('torch.save')\n", (8206, 8220), False, 'from unittest.mock import create_autospec, MagicMock, patch\n'), ((328, 354), 'unittest.mock.create_autospec', 'create_autospec', (['FlowModel'], {}), '(FlowModel)\n', (343, 354), False, 'from unittest.mock import create_autospec, MagicMock, patch\n'), ((548, 585), 'nessai.flowmodel.FlowModel', 'FlowModel', (['flow_config'], {'output': 'output'}), '(flow_config, output=output)\n', (557, 585), False, 'from nessai.flowmodel import update_config, FlowModel\n'), ((674, 693), 'nessai.flowmodel.update_config', 'update_config', (['None'], {}), '(None)\n', (687, 693), False, 'from nessai.flowmodel import update_config, FlowModel\n'), ((1502, 1523), 'nessai.flowmodel.update_config', 'update_config', (['config'], {}), '(config)\n', (1515, 1523), False, 'from nessai.flowmodel import update_config, FlowModel\n'), ((1733, 1752), 'nessai.flowmodel.update_config', 'update_config', (['None'], {}), '(None)\n', (1746, 1752), False, 'from nessai.flowmodel import update_config, FlowModel\n'), ((1762, 1786), 'nessai.flowmodel.FlowModel', 'FlowModel', ([], {'output': 'output'}), '(output=output)\n', (1771, 1786), False, 'from nessai.flowmodel import update_config, FlowModel\n'), ((2103, 2142), 'nessai.flowmodel.FlowModel', 'FlowModel', ([], {'config': 'config', 'output': 'output'}), '(config=config, output=output)\n', (2112, 2142), False, 'from nessai.flowmodel import update_config, FlowModel\n'), ((2294, 2305), 'unittest.mock.MagicMock', 'MagicMock', ([], {}), '()\n', (2303, 2305), False, 'from unittest.mock import create_autospec, MagicMock, patch\n'), ((2988, 2999), 'unittest.mock.MagicMock', 'MagicMock', ([], {}), '()\n', (2997, 2999), False, 'from unittest.mock import create_autospec, MagicMock, patch\n'), ((3459, 3487), 'numpy.random.randn', 'np.random.randn', (['n', 'data_dim'], {}), '(n, data_dim)\n', (3474, 3487), True, 'import numpy as np\n'), ((4049, 4077), 'numpy.random.randn', 'np.random.randn', (['n', 'data_dim'], {}), '(n, data_dim)\n', (4064, 4077), True, 'import numpy as np\n'), ((4716, 4744), 'numpy.random.randn', 'np.random.randn', (['n', 'data_dim'], {}), '(n, data_dim)\n', (4731, 4744), True, 'import numpy as np\n'), ((5050, 5081), 'numpy.random.randn', 'np.random.randn', (['(1000)', 'data_dim'], {}), '(1000, data_dim)\n', (5065, 5081), True, 'import numpy as np\n'), ((5784, 5821), 'nessai.flowmodel.FlowModel', 'FlowModel', (['flow_config'], {'output': 'output'}), '(flow_config, output=output)\n', (5793, 5821), False, 'from nessai.flowmodel import update_config, FlowModel\n'), ((5877, 5907), 'numpy.random.randn', 'np.random.randn', (['(100)', 'data_dim'], {}), '(100, data_dim)\n', (5892, 5907), True, 'import numpy as np\n'), ((7393, 7421), 'numpy.random.randn', 'np.random.randn', (['N', 'data_dim'], {}), '(N, data_dim)\n', (7408, 7421), True, 'import numpy as np\n'), ((7729, 7757), 'numpy.random.randn', 'np.random.randn', (['N', 'data_dim'], {}), '(N, data_dim)\n', (7744, 7757), True, 'import numpy as np\n'), ((8009, 8020), 'unittest.mock.MagicMock', 'MagicMock', ([], {}), '()\n', (8018, 8020), False, 'from unittest.mock import create_autospec, MagicMock, patch\n'), ((8042, 8053), 'unittest.mock.MagicMock', 'MagicMock', ([], {}), '()\n', (8051, 8053), False, 'from unittest.mock import create_autospec, MagicMock, patch\n'), ((8058, 8110), 'nessai.flowmodel.FlowModel.move_to', 'FlowModel.move_to', (['model', '"""cpu"""'], {'update_default': '(True)'}), "(model, 'cpu', update_default=True)\n", (8075, 8110), False, 'from nessai.flowmodel import update_config, FlowModel\n'), ((8314, 8325), 'unittest.mock.MagicMock', 'MagicMock', ([], {}), '()\n', (8323, 8325), False, 'from unittest.mock import create_autospec, MagicMock, patch\n'), ((8330, 8371), 'nessai.flowmodel.FlowModel.save_weights', 'FlowModel.save_weights', (['model', '"""model.pt"""'], {}), "(model, 'model.pt')\n", (8352, 8371), False, 'from nessai.flowmodel import update_config, FlowModel\n'), ((8530, 8554), 'pickle.dumps', 'pickle.dumps', (['flow_model'], {}), '(flow_model)\n', (8542, 8554), False, 'import pickle\n'), ((847, 871), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (860, 871), False, 'import pytest\n'), ((892, 912), 'nessai.flowmodel.update_config', 'update_config', (['(False)'], {}), '(False)\n', (905, 912), False, 'from nessai.flowmodel import update_config, FlowModel\n'), ((1214, 1239), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (1227, 1239), False, 'import pytest\n'), ((1260, 1281), 'nessai.flowmodel.update_config', 'update_config', (['config'], {}), '(config)\n', (1273, 1281), False, 'from nessai.flowmodel import update_config, FlowModel\n'), ((2467, 2539), 'unittest.mock.patch', 'patch', (['"""nessai.flowmodel.configure_model"""'], {'return_value': "('model', 'cpu')"}), "('nessai.flowmodel.configure_model', return_value=('model', 'cpu'))\n", (2472, 2539), False, 'from unittest.mock import create_autospec, MagicMock, patch\n'), ((2572, 2599), 'nessai.flowmodel.FlowModel.initialise', 'FlowModel.initialise', (['model'], {}), '(model)\n', (2592, 2599), False, 'from nessai.flowmodel import update_config, FlowModel\n'), ((2759, 2778), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (2771, 2778), False, 'import torch\n'), ((3009, 3042), 'unittest.mock.patch', 'patch', (['f"""torch.optim.{optimiser}"""'], {}), "(f'torch.optim.{optimiser}')\n", (3014, 3042), False, 'from unittest.mock import create_autospec, MagicMock, patch\n'), ((3060, 3101), 'nessai.flowmodel.FlowModel.get_optimiser', 'FlowModel.get_optimiser', (['model', 'optimiser'], {}), '(model, optimiser)\n', (3083, 3101), False, 'from nessai.flowmodel import update_config, FlowModel\n'), ((4754, 4781), 'pytest.raises', 'pytest.raises', (['RuntimeError'], {}), '(RuntimeError)\n', (4767, 4781), False, 'import pytest\n'), ((6058, 6085), 'pytest.raises', 'pytest.raises', (['RuntimeError'], {}), '(RuntimeError)\n', (6071, 6085), False, 'import pytest\n'), ((6638, 6665), 'pytest.raises', 'pytest.raises', (['RuntimeError'], {}), '(RuntimeError)\n', (6651, 6665), False, 'import pytest\n'), ((8138, 8157), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (8150, 8157), False, 'import torch\n')] |
"""
Copyright (c) 2019 Intel Corporation
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 numpy as np
from ..adapters import Adapter
from ..config import ConfigValidator, StringField, NumberField
from ..representation import DetectionPrediction, ContainerPrediction
class ActionDetectorConfig(ConfigValidator):
type = StringField()
priorbox_out = StringField()
loc_out = StringField()
main_conf_out = StringField()
add_conf_out_prefix = StringField()
add_conf_out_count = NumberField(optional=True, min_value=1)
num_action_classes = NumberField()
detection_threshold = NumberField(optional=True, floats=True, min_value=0, max_value=1)
class ActionDetection(Adapter):
__provider__ = 'action_detection'
def validate_config(self):
action_detector_adapter_config = ActionDetectorConfig('ActionDetector_Config')
action_detector_adapter_config.validate(self.launcher_config)
def configure(self):
self.priorbox_out = self.launcher_config['priorbox_out']
self.loc_out = self.launcher_config['loc_out']
self.main_conf_out = self.launcher_config['main_conf_out']
self.num_action_classes = self.launcher_config['num_action_classes']
self.detection_threshold = self.launcher_config.get('detection_threshold', 0)
add_conf_out_count = self.launcher_config.get('add_conf_out_count')
add_conf_out_prefix = self.launcher_config['add_conf_out_prefix']
if add_conf_out_count is None:
self.add_conf_outs = [add_conf_out_prefix]
else:
self.add_conf_outs = []
for num in np.arange(start=1, stop=add_conf_out_count + 1):
self.add_conf_outs.append('{}{}'.format(add_conf_out_prefix, num))
def process(self, raw, identifiers=None, frame_meta=None):
result = []
raw_outputs = self._extract_predictions(raw, frame_meta)
prior_boxes = raw_outputs[self.priorbox_out][0][0].reshape(-1, 4)
prior_variances = raw_outputs[self.priorbox_out][0][1].reshape(-1, 4)
for batch_id, identifier in enumerate(identifiers):
labels, class_scores, x_mins, y_mins, x_maxs, y_maxs, main_scores = self.prepare_detection_for_id(
batch_id, raw_outputs, prior_boxes, prior_variances
)
action_prediction = DetectionPrediction(identifier, labels, class_scores, x_mins, y_mins, x_maxs, y_maxs)
person_prediction = DetectionPrediction(
identifier, [1] * len(labels), main_scores, x_mins, y_mins, x_maxs, y_maxs
)
result.append(ContainerPrediction({
'action_prediction': action_prediction, 'class_agnostic_prediction': person_prediction
}))
return result
def prepare_detection_for_id(self, batch_id, raw_outputs, prior_boxes, prior_variances):
num_detections = raw_outputs[self.loc_out][batch_id].size // 4
locs = raw_outputs[self.loc_out][batch_id].reshape(-1, 4)
main_conf = raw_outputs[self.main_conf_out][batch_id].reshape(num_detections, -1)
add_confs = list(map(
lambda layer: raw_outputs[layer][batch_id].reshape(-1, self.num_action_classes), self.add_conf_outs
))
anchors_num = len(add_confs)
labels, class_scores, x_mins, y_mins, x_maxs, y_maxs, main_scores = [], [], [], [], [], [], []
for index in range(num_detections):
if main_conf[index, 1] < self.detection_threshold:
continue
x_min, y_min, x_max, y_max = self.decode_box(prior_boxes[index], prior_variances[index], locs[index])
action_confs = add_confs[index % anchors_num][index // anchors_num]
action_label = np.argmax(action_confs)
labels.append(action_label)
class_scores.append(action_confs[action_label])
x_mins.append(x_min)
y_mins.append(y_min)
x_maxs.append(x_max)
y_maxs.append(y_max)
main_scores.append(main_conf[index, 1])
return labels, class_scores, x_mins, y_mins, x_maxs, y_maxs, main_scores
@staticmethod
def decode_box(prior, var, deltas):
prior_width = prior[2] - prior[0]
prior_height = prior[3] - prior[1]
prior_center_x = (prior[0] + prior[2]) / 2
prior_center_y = (prior[1] + prior[3]) / 2
decoded_box_center_x = var[0] * deltas[0] * prior_width + prior_center_x
decoded_box_center_y = var[1] * deltas[1] * prior_height + prior_center_y
decoded_box_width = np.exp(var[2] * deltas[2]) * prior_width
decoded_box_height = np.exp(var[3] * deltas[3]) * prior_height
decoded_xmin = decoded_box_center_x - decoded_box_width / 2
decoded_ymin = decoded_box_center_y - decoded_box_height / 2
decoded_xmax = decoded_box_center_x + decoded_box_width / 2
decoded_ymax = decoded_box_center_y + decoded_box_height / 2
return decoded_xmin, decoded_ymin, decoded_xmax, decoded_ymax
| [
"numpy.arange",
"numpy.exp",
"numpy.argmax"
] | [((2114, 2161), 'numpy.arange', 'np.arange', ([], {'start': '(1)', 'stop': '(add_conf_out_count + 1)'}), '(start=1, stop=add_conf_out_count + 1)\n', (2123, 2161), True, 'import numpy as np\n'), ((4234, 4257), 'numpy.argmax', 'np.argmax', (['action_confs'], {}), '(action_confs)\n', (4243, 4257), True, 'import numpy as np\n'), ((5062, 5088), 'numpy.exp', 'np.exp', (['(var[2] * deltas[2])'], {}), '(var[2] * deltas[2])\n', (5068, 5088), True, 'import numpy as np\n'), ((5132, 5158), 'numpy.exp', 'np.exp', (['(var[3] * deltas[3])'], {}), '(var[3] * deltas[3])\n', (5138, 5158), True, 'import numpy as np\n')] |
from typing import Optional
import pandas as pd
import statsmodels.api as sm
import numpy as np
from statsmodels.regression.linear_model import RegressionResults
from finstmt.exc import ForecastNotFitException
from finstmt.forecast.models.base import ForecastModel
class LinearTrendModel(ForecastModel):
model: Optional[sm.OLS] = None
model_result: Optional[RegressionResults] = None
def fit(self, series: pd.Series):
X = sm.add_constant(np.arange(len(series)))
self.model = sm.OLS(series, X)
self.model_result = self.model.fit()
super().fit(series)
def predict(self) -> pd.Series:
if self.model is None or self.model_result is None or self.orig_series is None:
raise ForecastNotFitException('call .fit before .predict')
last_t = len(self.model.exog) - 1
step = self.desired_freq_t_multiplier
future_X = sm.add_constant(np.arange(last_t + step, last_t + (self.config.periods * step) + step * 0.9, step))
future_dates = self._future_date_range
all_X = np.concatenate((self.model.exog, future_X))
all_dates = np.concatenate((self.orig_series.index, future_dates))
predicted = self.model_result.get_prediction(all_X)
predict_df = predicted.summary_frame().set_index(all_dates)
self.result_df = predict_df[['mean', 'mean_ci_lower', 'mean_ci_upper']].rename(
columns={'mean_ci_lower': 'lower', 'mean_ci_upper': 'upper'}
)
self.result = self.result_df['mean'].loc[future_dates]
super().predict()
return self.result
| [
"finstmt.exc.ForecastNotFitException",
"numpy.arange",
"numpy.concatenate",
"statsmodels.api.OLS"
] | [((508, 525), 'statsmodels.api.OLS', 'sm.OLS', (['series', 'X'], {}), '(series, X)\n', (514, 525), True, 'import statsmodels.api as sm\n'), ((1065, 1108), 'numpy.concatenate', 'np.concatenate', (['(self.model.exog, future_X)'], {}), '((self.model.exog, future_X))\n', (1079, 1108), True, 'import numpy as np\n'), ((1129, 1183), 'numpy.concatenate', 'np.concatenate', (['(self.orig_series.index, future_dates)'], {}), '((self.orig_series.index, future_dates))\n', (1143, 1183), True, 'import numpy as np\n'), ((742, 794), 'finstmt.exc.ForecastNotFitException', 'ForecastNotFitException', (['"""call .fit before .predict"""'], {}), "('call .fit before .predict')\n", (765, 794), False, 'from finstmt.exc import ForecastNotFitException\n'), ((918, 1003), 'numpy.arange', 'np.arange', (['(last_t + step)', '(last_t + self.config.periods * step + step * 0.9)', 'step'], {}), '(last_t + step, last_t + self.config.periods * step + step * 0.9, step\n )\n', (927, 1003), True, 'import numpy as np\n')] |
import numpy as np
import pandas as pd
from datetime import datetime
import json
from src.models.model_def import get_callbacks, get_model
from src.features.prepare_data import prepare_data
from statistics import mean, stdev
from sklearn.model_selection import KFold
#TODO port loading + processing data to function
# Create file for model info and validation metrics
def train_model(X_train, X_valid, X_test,
X_angle_train, X_angle_valid, X_angle_test,
y_train, y_valid,
train_id, val_id, test_id,
nb_fold=10):
model_info = dict()
bs = 32
folds = KFold(n_splits=nb_fold)
model_name = datetime.now().strftime('%Y-%m-%d-%H-%M-%S')
model_path = str(MODEL_PATH + model_name + ".model_weights.hdf5")
model_info['model_name'] = model_name
model_info['nb_folds'] = nb_fold
model_info['model_weight_path'] = model_path
model_info['metrics_per_fold'] = []
model_info['metrics_cv'] = {}
model_info['metrics_val'] = {}
prob_train_ho = None
callbacks = get_callbacks(filepath=model_path, patience=3)
for trainset, valset in folds.split(train):
print(len(X_train[trainset]))
print(len(X_train[valset]))
model.fit([X_train[trainset], X_angle_train[trainset]], y_train[trainset], epochs=1000,
validation_data=([X_train[valset], X_angle_train[valset]], y_train[valset]),
batch_size=bs,
callbacks=callbacks)
preds = model.predict([X_train[trainset], X_angle_train[trainset]], verbose=1, batch_size=bs)
eval_model = model.evaluate([X_train[valset], X_angle_train[valset]], y_train[valset],
verbose=1, batch_size=bs)
eval_model_dict = dict()
eval_model_dict['loss'] = eval_model[0]
eval_model_dict['accuracy'] = eval_model[1]
model_info['metrics_per_fold'].append(eval_model_dict)
if prob_train_ho is None:
prob_train_ho = pd.DataFrame({'id': train_id[trainset],
'is_iceberg': preds.reshape((preds.shape[0]))})
else:
temp_df = pd.DataFrame({'id': train_id[trainset],
'is_iceberg': preds.reshape((preds.shape[0]))})
prob_train_ho.append(temp_df)
eval_model_dict = dict()
loss = []
accuracy = []
for fold_result in model_info['metrics_per_fold']:
loss.append(fold_result['accuracy'])
accuracy.append(fold_result['loss'])
eval_model_dict['loss_mean'] = mean(loss)
eval_model_dict['loss_std'] = stdev(loss)
eval_model_dict['accuracy_mean'] = mean(accuracy)
eval_model_dict['accuracy_std'] = stdev(accuracy)
model_info['metrics_cv'] = eval_model_dict
model.fit([X_train, X_angle_train], y_train, epochs=1000,
validation_data=([X_valid, X_angle_valid], y_valid),
batch_size=bs,
callbacks=callbacks)
model_info['optimizer'] = model.get_config()
eval_model = model.evaluate([X_valid, X_angle_valid], y_valid,
verbose=1, batch_size=bs)
eval_model_dict['loss'] = eval_model[0]
eval_model_dict['accuracy'] = eval_model[1]
model_info['metrics_val'] = eval_model_dict
preds_val = model.predict([X_valid, X_angle_valid], verbose=1, batch_size=bs)
preds_test = model.predict([X_test, X_angle_test], verbose=1, batch_size=bs)
preds_val_df = pd.DataFrame({'id': val_id,
'is_iceberg': preds_val.reshape((preds_val.shape[0]))})
preds_test_df = pd.DataFrame({'id': test_id,
'is_iceberg': preds_test.reshape((preds_test.shape[0]))})
preds_val_df.to_csv(MODEL_PATH + model_name + "_val_prob.csv", index=False)
preds_test_df.to_csv(MODEL_PATH + model_name + "_test_prob.csv", index=False)
with open(MODEL_PATH + model_name + "-config.json", 'w') as f:
json.dump(model_info, f)
np.random.seed(966)
DATA_PATH = "../../data/processed/"
MODEL_PATH = "../../reports/models/"
train = pd.read_json(DATA_PATH + 'train.json')
val = pd.read_json(DATA_PATH + 'val.json')
test = pd.read_json(DATA_PATH + 'test.json')
print("Data loaded")
model = get_model()
model.summary()
X_train, X_valid, X_test, X_angle_train, X_angle_valid, X_angle_test, y_train, y_valid = prepare_data(train, val, test)
train_model(X_train, X_valid, X_test,
X_angle_train, X_angle_valid, X_angle_test,
y_train, y_valid,
train['id'], val['id'], test['id'], nb_fold=10)
| [
"json.dump",
"numpy.random.seed",
"src.features.prepare_data.prepare_data",
"src.models.model_def.get_model",
"statistics.stdev",
"sklearn.model_selection.KFold",
"pandas.read_json",
"statistics.mean",
"src.models.model_def.get_callbacks",
"datetime.datetime.now"
] | [((4040, 4059), 'numpy.random.seed', 'np.random.seed', (['(966)'], {}), '(966)\n', (4054, 4059), True, 'import numpy as np\n'), ((4143, 4181), 'pandas.read_json', 'pd.read_json', (["(DATA_PATH + 'train.json')"], {}), "(DATA_PATH + 'train.json')\n", (4155, 4181), True, 'import pandas as pd\n'), ((4188, 4224), 'pandas.read_json', 'pd.read_json', (["(DATA_PATH + 'val.json')"], {}), "(DATA_PATH + 'val.json')\n", (4200, 4224), True, 'import pandas as pd\n'), ((4232, 4269), 'pandas.read_json', 'pd.read_json', (["(DATA_PATH + 'test.json')"], {}), "(DATA_PATH + 'test.json')\n", (4244, 4269), True, 'import pandas as pd\n'), ((4301, 4312), 'src.models.model_def.get_model', 'get_model', ([], {}), '()\n', (4310, 4312), False, 'from src.models.model_def import get_callbacks, get_model\n'), ((4419, 4449), 'src.features.prepare_data.prepare_data', 'prepare_data', (['train', 'val', 'test'], {}), '(train, val, test)\n', (4431, 4449), False, 'from src.features.prepare_data import prepare_data\n'), ((632, 655), 'sklearn.model_selection.KFold', 'KFold', ([], {'n_splits': 'nb_fold'}), '(n_splits=nb_fold)\n', (637, 655), False, 'from sklearn.model_selection import KFold\n'), ((1070, 1116), 'src.models.model_def.get_callbacks', 'get_callbacks', ([], {'filepath': 'model_path', 'patience': '(3)'}), '(filepath=model_path, patience=3)\n', (1083, 1116), False, 'from src.models.model_def import get_callbacks, get_model\n'), ((2606, 2616), 'statistics.mean', 'mean', (['loss'], {}), '(loss)\n', (2610, 2616), False, 'from statistics import mean, stdev\n'), ((2651, 2662), 'statistics.stdev', 'stdev', (['loss'], {}), '(loss)\n', (2656, 2662), False, 'from statistics import mean, stdev\n'), ((2703, 2717), 'statistics.mean', 'mean', (['accuracy'], {}), '(accuracy)\n', (2707, 2717), False, 'from statistics import mean, stdev\n'), ((2756, 2771), 'statistics.stdev', 'stdev', (['accuracy'], {}), '(accuracy)\n', (2761, 2771), False, 'from statistics import mean, stdev\n'), ((4013, 4037), 'json.dump', 'json.dump', (['model_info', 'f'], {}), '(model_info, f)\n', (4022, 4037), False, 'import json\n'), ((673, 687), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (685, 687), False, 'from datetime import datetime\n')] |
import torch
import numpy as np
from dataclasses import dataclass
from typing import List, Optional, Union, NamedTuple, Dict
@dataclass(frozen=True)
class InputExample:
"""
A single training/test example for multiple choice
Args:
example_id: Unique id for the example.
question: string. The untokenized text of the second sequence (question).
contexts: list of str. The untokenized text of the first sequence (context of corresponding question).
endings: list of str. multiple choice's options. Its length must be equal to contexts' length.
label: (Optional) string. The label of the example. This should be
specified for train and dev examples, but not for test examples.
"""
example_id: Union[str, int]
question: str
contexts: List[str]
endings: List[str]
label: Optional[str]
def todict(self):
return dict(
example_id=self.example_id,
question=self.question,
contexts=self.contexts,
endings=self.endings,
label=self.label,
)
@dataclass(frozen=True)
class InputFeatures:
"""
A single set of features of data.
Property names are the same names as the corresponding inputs to a model.
"""
example_id: Union[str, int]
input_ids: List[List[int]]
attention_mask: Optional[List[List[int]]]
token_type_ids: Optional[List[List[int]]]
label: Optional[int]
class WindowPrediction(NamedTuple):
predictions: np.ndarray
window_ids: List[int]
labels: List[int]
label: Optional[int]
example: Optional[InputExample]
def todict(self):
return dict(
predictions=self.predictions.tolist(),
window_ids=self.window_ids,
labels=self.labels,
label=self.label,
example=(
self.example.todict() if self.example is not None else None
)
)
class DataCollatorWithIds():
def __init__(self):
self.example_ids = None
def collate(self, features: List) -> Dict[str, torch.Tensor]:
"""
Very simple data collator that:
- simply collates batches of dict-like objects
- Performs special handling for potential keys named:
- ``label``: handles a single value (int or float) per object
- ``label_ids``: handles a list of values per object
- does not do any additional preprocessing
i.e., Property names of the input object will be used as corresponding inputs to the model.
See glue and ner for example of how it's useful.
"""
# In this function we'll make the assumption that all `features` in the batch
# have the same attributes.
# So we will look at the first element as a proxy for what attributes exist
# on the whole batch.
if not isinstance(features[0], dict):
features = [vars(f) for f in features]
first = features[0]
batch = {}
# Special handling for labels.
# Ensure that tensor is created with the correct type
# (it should be automatically the case, but let's make sure of it.)
if "label" in first and first["label"] is not None:
label = first["label"].item() if isinstance(first["label"], torch.Tensor) else first["label"]
dtype = torch.long if isinstance(label, int) else torch.float
batch["labels"] = torch.tensor([f["label"] for f in features], dtype=dtype)
elif "label_ids" in first and first["label_ids"] is not None:
if isinstance(first["label_ids"], torch.Tensor):
batch["labels"] = torch.stack([f["label_ids"] for f in features])
else:
dtype = torch.long if type(first["label_ids"][0]) is int else torch.float
batch["labels"] = torch.tensor([f["label_ids"] for f in features], dtype=dtype)
# Skip example_ids
# if "example_id" in first and first["example_id"] is not None:
# example_id = first["example_id"].item() if isinstance(first["example_id"], torch.Tensor) else first["example_id"]
# dtype = torch.long if isinstance(example_id, int) else torch.float
# batch["example_ids"] = torch.tensor([f["example_id"] for f in features], dtype=dtype)
example_ids = [f["example_id"] for f in features]
if self.example_ids is None:
self.example_ids = np.array(example_ids)
else:
self.example_ids = np.hstack([self.example_ids, example_ids])
# Handling of all other possible keys.
# Again, we will use the first element to figure out which key/values are not None for this model.
for k, v in first.items():
if k not in ("label", "label_ids", "example_id") and v is not None and not isinstance(v, str):
if isinstance(v, torch.Tensor):
batch[k] = torch.stack([f[k] for f in features])
else:
batch[k] = torch.tensor([f[k] for f in features], dtype=torch.long)
return batch
def drop_ids(self):
self.example_ids = None
class PredictionOutputWithIds(NamedTuple):
predictions: np.ndarray
label_ids: Optional[np.ndarray]
example_ids: Optional[np.ndarray]
metrics: Optional[Dict[str, float]]
| [
"torch.stack",
"numpy.hstack",
"numpy.array",
"dataclasses.dataclass",
"torch.tensor"
] | [((129, 151), 'dataclasses.dataclass', 'dataclass', ([], {'frozen': '(True)'}), '(frozen=True)\n', (138, 151), False, 'from dataclasses import dataclass\n'), ((1101, 1123), 'dataclasses.dataclass', 'dataclass', ([], {'frozen': '(True)'}), '(frozen=True)\n', (1110, 1123), False, 'from dataclasses import dataclass\n'), ((3465, 3522), 'torch.tensor', 'torch.tensor', (["[f['label'] for f in features]"], {'dtype': 'dtype'}), "([f['label'] for f in features], dtype=dtype)\n", (3477, 3522), False, 'import torch\n'), ((4491, 4512), 'numpy.array', 'np.array', (['example_ids'], {}), '(example_ids)\n', (4499, 4512), True, 'import numpy as np\n'), ((4558, 4600), 'numpy.hstack', 'np.hstack', (['[self.example_ids, example_ids]'], {}), '([self.example_ids, example_ids])\n', (4567, 4600), True, 'import numpy as np\n'), ((3688, 3735), 'torch.stack', 'torch.stack', (["[f['label_ids'] for f in features]"], {}), "([f['label_ids'] for f in features])\n", (3699, 3735), False, 'import torch\n'), ((3878, 3939), 'torch.tensor', 'torch.tensor', (["[f['label_ids'] for f in features]"], {'dtype': 'dtype'}), "([f['label_ids'] for f in features], dtype=dtype)\n", (3890, 3939), False, 'import torch\n'), ((4976, 5013), 'torch.stack', 'torch.stack', (['[f[k] for f in features]'], {}), '([f[k] for f in features])\n', (4987, 5013), False, 'import torch\n'), ((5067, 5123), 'torch.tensor', 'torch.tensor', (['[f[k] for f in features]'], {'dtype': 'torch.long'}), '([f[k] for f in features], dtype=torch.long)\n', (5079, 5123), False, 'import torch\n')] |
# -*- coding: utf-8 -*-
"""
Useful extra functions
"""
import numpy as np
import pandas as pd
import numpy.linalg as LA
from collections import OrderedDict
import pdb
def calculate_error(x, y, error_type):
"""Calculate the normalised error of x relative to y as a percentage"""
# remove NaNs
notnan = ~np.isnan(x + y)
abserror = LA.norm(x[notnan] - y[notnan])
if abserror < 1e-10:
return np.nan
if error_type == "absolute":
return abserror
if error_type == "relative":
return abserror / LA.norm(y[notnan])
def my_linear_interp(var):
"""Linearly interpolate/extrapolate data from cell centres to cell edges"""
shifted = np.zeros((var.shape[0], var.shape[1] + 1))
shifted[:, 0] = (3 * var[:, 0] - var[:, 1]) / 2
shifted[:, 1:-1] = (var[:, 1:] + var[:, :-1]) / 2
shifted[:, -1] = (3 * var[:, -1] - var[:, -2]) / 2
return shifted
def datetime_to_hours(datetime, ref_datetime):
"""Convert a Timestamp to a number of hours elapsed since reference Timestamp"""
return (datetime - ref_datetime).total_seconds() / 3600
def load_data(
data_name,
imei=None,
dates=None,
ignore_start=False,
ignore_end=False,
wt=1,
n_coarse_points=0,
):
"""Load data as a list of dicts of lists"""
datas = OrderedDict()
if data_name == "March17":
for name, value in dates.items():
# Decompose dates
(start, end) = value
# Read the file (parsing dates)
fname = "".join(
("inputs/telemetry_", imei, "_", start, "_", end, ".csv")
)
df = pd.read_csv(
fname,
header=1,
parse_dates=[0],
names=["time", "voltage", "current", "temperature"],
)
# Get rid of NaN values in current or voltage (equivalently voltage)
df.dropna(subset=["voltage", "current"], inplace=True)
# Drop initial values and/or end values (or neither)
if ignore_start:
df.drop(
df[(df.voltage > 12) & (df.current < 0.25)].index,
inplace=True,
)
if ignore_end:
df.drop(
df[(df.voltage < 12) & (df.current < 0.25)].index,
inplace=True,
)
# Convert datetime to seconds since start
df.time = df.time.apply(
datetime_to_hours, args=(df.time[df.index[0]],)
)
# Sort by time
df = df.sort_values(by=["time"])
# Convert to dictionary of lists
df_dict = df.to_dict("list")
# Convert to dictionary of numpy arrays
datas[name] = {k: np.asarray(v) for (k, v) in df_dict.items()}
# Coarsen data if required
if n_coarse_points: # If n_coarse_points=0 (deault), do nothing
# Define fine time and coarse time
fine_time = datas[name]["time"]
coarse_time = np.linspace(
fine_time[0], fine_time[-1], n_coarse_points
)
# Interpolate to coarse time
datas[name]["current"] = np.interp(
coarse_time, fine_time, datas[name]["current"]
)
datas[name]["voltage"] = np.interp(
coarse_time, fine_time, datas[name]["voltage"]
)
datas[name]["time"] = coarse_time
# Add weights - no weight for the initial relaxation then more weight at the end
weights = np.ones(datas[name]["voltage"].shape)
# weights[(datas[name]['voltage'] < 12) &
# (datas[name]['current'] < 0.25)] = 0
weights[-1] = wt
datas[name]["weights"] = weights
elif data_name == "Nov17":
fname = (
"inputs/lead_acid_GITT_C-20_rest_2h_GEIS_100mA_10mHz_10kHz_"
+ imei
+ ".csv"
)
# Get headers (maybe not the most efficient way ...)
with open(fname, "rb") as f:
headers = f.read().splitlines()[99]
headers = str(headers)[2:-4].split("\\t")
# Remove units from headers
headers = [s.split("/", 1)[0] for s in headers]
# Read file
df = pd.read_csv(fname, header=97, sep="\t", names=headers)
# Convert current from mA to A and switch sign
df.I = -df.I / 1e3
# Convert time from seconds to hours
df.time /= 3600
# Change column names
df = df.rename(columns={"Ewe": "voltage", "I": "current"})
# Discharge only, no GEIS
df_discharge_clean = df[(df["Ns"].isin([4, 5]))]
mintime = df_discharge_clean.time[df_discharge_clean.index[0]]
df_discharge_clean.time -= mintime
# Convert to dictionary of lists
df_dict = df_discharge_clean.to_dict("list")
# Convert to dictionary of numpy arrays
datas["all"] = {k: np.asarray(v) for (k, v) in df_dict.items()}
datas["all"]["weights"] = np.ones(datas["all"]["time"].shape)
return datas
def make_results_table(filename, times):
"""Print CPU times and speed-up to a text file, to be used as a LaTeX Table"""
# Add directories to filename
filename = "out/tables/" + filename + ".txt"
# Read keys
Crates = list(times.keys())
methods = [
k
for k in sorted(
times[Crates[0]], key=times[Crates[0]].get, reverse=True
)
]
with open(filename, "w") as text_file:
# Table set-up
text_file.write(
("\\begin{{tabular}}{{|c|{}}}\n").format("cc|" * len(Crates))
)
text_file.write("\hline\n")
# Current row
for Crate in Crates:
text_file.write("& \multicolumn{{2}}{{c|}}{{{}C}}".format(Crate))
text_file.write(r"\\" + "\n")
text_file.write("\cline{{2-{}}}\n".format(2 * len(Crates) + 1))
# Defining the columns
text_file.write(
("Solution Method {}" + r"\\" + "\n").format(
"& Time & Speed-up " * len(Crates)
)
)
text_file.write("\hline\n")
# Fill in values method-by-method
for i, method in enumerate(methods):
text_file.write(method)
# Current-by-current: v is a dict with key: method and value: time
for v in times.values():
if method == "Numerical":
text_file.write(" & {:.3g} & {} ".format(v[method], "-"))
else:
text_file.write(
" & {:.3f} & {:d} ".format(
v[method], round(v["Numerical"] / v[method])
)
)
text_file.write(r"\\" + "\n")
# End
text_file.write("\hline\n\end{tabular}")
#
# with open(filename, "r") as text_file:
# print(text_file.read())
def save_data(
datafile, x, y, callfile, linestyle="", extra_feature="", n_coarse_points=0
):
"""Save data in table form for plotting using pgfplots"""
datafile = "out/data/" + datafile + ".dat"
# Coarsen data if required
if n_coarse_points: # If n_coarse_points=0 (deault), do nothing
# Define target x values
xvals = np.linspace(x[0], x[-1], n_coarse_points)
# Make sure y is a 1D object
if len(y.shape) > 1:
y = y[:, 0]
# Interpolate to coarse time
y = np.interp(xvals, x, y)
x = xvals
# Save data to datafile
np.savetxt(datafile, np.column_stack((x, y)))
# Add line to pgfplots callfile
callfile.write(
("\\addplot{} table{{code/{}}}{};\n").format(
linestyle, datafile, extra_feature
)
)
| [
"pandas.read_csv",
"numpy.interp",
"numpy.asarray",
"numpy.zeros",
"numpy.ones",
"numpy.isnan",
"numpy.linalg.norm",
"numpy.linspace",
"numpy.column_stack",
"collections.OrderedDict"
] | [((347, 377), 'numpy.linalg.norm', 'LA.norm', (['(x[notnan] - y[notnan])'], {}), '(x[notnan] - y[notnan])\n', (354, 377), True, 'import numpy.linalg as LA\n'), ((683, 725), 'numpy.zeros', 'np.zeros', (['(var.shape[0], var.shape[1] + 1)'], {}), '((var.shape[0], var.shape[1] + 1))\n', (691, 725), True, 'import numpy as np\n'), ((1305, 1318), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (1316, 1318), False, 'from collections import OrderedDict\n'), ((316, 331), 'numpy.isnan', 'np.isnan', (['(x + y)'], {}), '(x + y)\n', (324, 331), True, 'import numpy as np\n'), ((7403, 7444), 'numpy.linspace', 'np.linspace', (['x[0]', 'x[-1]', 'n_coarse_points'], {}), '(x[0], x[-1], n_coarse_points)\n', (7414, 7444), True, 'import numpy as np\n'), ((7584, 7606), 'numpy.interp', 'np.interp', (['xvals', 'x', 'y'], {}), '(xvals, x, y)\n', (7593, 7606), True, 'import numpy as np\n'), ((7679, 7702), 'numpy.column_stack', 'np.column_stack', (['(x, y)'], {}), '((x, y))\n', (7694, 7702), True, 'import numpy as np\n'), ((541, 559), 'numpy.linalg.norm', 'LA.norm', (['y[notnan]'], {}), '(y[notnan])\n', (548, 559), True, 'import numpy.linalg as LA\n'), ((1633, 1735), 'pandas.read_csv', 'pd.read_csv', (['fname'], {'header': '(1)', 'parse_dates': '[0]', 'names': "['time', 'voltage', 'current', 'temperature']"}), "(fname, header=1, parse_dates=[0], names=['time', 'voltage',\n 'current', 'temperature'])\n", (1644, 1735), True, 'import pandas as pd\n'), ((3658, 3695), 'numpy.ones', 'np.ones', (["datas[name]['voltage'].shape"], {}), "(datas[name]['voltage'].shape)\n", (3665, 3695), True, 'import numpy as np\n'), ((4384, 4438), 'pandas.read_csv', 'pd.read_csv', (['fname'], {'header': '(97)', 'sep': '"""\t"""', 'names': 'headers'}), "(fname, header=97, sep='\\t', names=headers)\n", (4395, 4438), True, 'import pandas as pd\n'), ((5141, 5176), 'numpy.ones', 'np.ones', (["datas['all']['time'].shape"], {}), "(datas['all']['time'].shape)\n", (5148, 5176), True, 'import numpy as np\n'), ((2786, 2799), 'numpy.asarray', 'np.asarray', (['v'], {}), '(v)\n', (2796, 2799), True, 'import numpy as np\n'), ((3077, 3134), 'numpy.linspace', 'np.linspace', (['fine_time[0]', 'fine_time[-1]', 'n_coarse_points'], {}), '(fine_time[0], fine_time[-1], n_coarse_points)\n', (3088, 3134), True, 'import numpy as np\n'), ((3259, 3316), 'numpy.interp', 'np.interp', (['coarse_time', 'fine_time', "datas[name]['current']"], {}), "(coarse_time, fine_time, datas[name]['current'])\n", (3268, 3316), True, 'import numpy as np\n'), ((3396, 3453), 'numpy.interp', 'np.interp', (['coarse_time', 'fine_time', "datas[name]['voltage']"], {}), "(coarse_time, fine_time, datas[name]['voltage'])\n", (3405, 3453), True, 'import numpy as np\n'), ((5062, 5075), 'numpy.asarray', 'np.asarray', (['v'], {}), '(v)\n', (5072, 5075), True, 'import numpy as np\n')] |
# coding: UTF-8
import torch
import numpy as np
import torch.nn.functional as F
class ATModel:
"""
base train class, without adversarial training
"""
def __init__(self, model, emb_name="embedding"):
self.model = model
self.epsilon = 0.1 # 扰动的scale
self.emb_backup = {} # 备份原始embedding用
self.grad_backup = {} # 备份原始梯度用
self.emb_name = emb_name # 模型中定义的embedding参数的名字
self.use_sign_grad = True # 采用哪种方式计算delta
self.use_project = True # 是否采用投影
self.use_clamp = False # 限制delta的范围
def train(self, trains, labels, optimizer):
"""
对抗训练过程,如果没有对抗网络,就是普通的训练流程
Args:
trains: 2-D int tensor, 训练数据, shape=[batch_size, seq_size]
labels: 1-D int tensor, 训练标签, shape=[batch_size]
optimizer: Adam优化器
Returns
outputs : 2-D float tensor, 分类得分, shape=[batch_size, class_num]
loss : float tensor, 最后的损失, float32
"""
outputs = self.model(trains)
self.model.zero_grad()
loss = F.cross_entropy(outputs, labels)
loss.backward()
optimizer.step()
return outputs, loss
def sign_grad(self, param, param_name, scale):
"""
计算sign grad
Args:
param: 参数值
param_name: 参数名字
scale: 缩放参数
Return:
sign_grad: sign_grad
"""
d_at = scale * np.sign(param.grad)
if self.use_clamp:
d_at.clamp_(-self.epsilon, self.epsilon)
param.data.add_(d_at)
def norm_grad(self, param, param_name, scale):
"""
计算norm grad
Args:
param: 参数值
param_name: 参数名字
scale: 缩放参数
Return:
norm_grad: norm_grad
"""
norm = torch.norm(param.grad)
if norm != 0 and not torch.isnan(norm):
d_at = scale * param.grad / norm
else:
d_at = scale * torch.zeros_like(param.grad)
param.data.add_(d_at)
if self.use_project:
param.data = self.project(param_name, param.data)
def calc_delta(self, param, param_name, scale):
"""
计算扰动值
Args:
param: 参数值
param_name: 参数名字
scale: 缩放参数
Return:
delta: 扰动值
"""
raise NotImplementedError
def project(self, param_name, param_data):
"""
如果delta落在扰动半径为epsilon的球面外,就映射回球面上,以保证扰动不要过大
即:||delta|| <= epsilon
Args:
param_name: 参数名字
param_data: 参数值
Return:
delta: 扰动值
"""
d_at = param_data - self.emb_backup[param_name]
if torch.norm(d_at) > self.epsilon:
d_at = self.epsilon * d_at / torch.norm(d_at)
return self.emb_backup[param_name] + d_at
def attack_emb(self, is_backup=True):
"""
计算在embedding上的扰动值
Args:
is_backup: 是否备份,默认True
Return:
"""
for name, param in self.model.named_parameters():
if param.requires_grad and self.emb_name in name:
if is_backup:
self.emb_backup[name] = param.data.clone()
self.calc_delta(param, name)
def backup_emb(self):
"""
备份embedding
"""
for name, param in self.model.named_parameters():
if param.requires_grad and self.emb_name in name:
self.emb_backup[name] = param.data.clone()
def clear_emb_back(self):
"""
清除
"""
self.emb_backup = {}
def restore_emb(self):
"""
恢复embedding
"""
for name, param in self.model.named_parameters():
if param.requires_grad and self.emb_name in name:
assert name in self.emb_backup
param.data = self.emb_backup[name]
self.emb_backup = {}
def backup_grad(self):
"""
备份梯度
"""
for name, param in self.model.named_parameters():
if param.requires_grad:
self.grad_backup[name] = param.grad.clone()
def restore_grad(self):
"""
恢复梯度值
"""
for name, param in self.model.named_parameters():
if param.requires_grad:
param.grad = self.grad_backup[name]
self.grad_backup = {}
| [
"torch.zeros_like",
"torch.norm",
"torch.nn.functional.cross_entropy",
"numpy.sign",
"torch.isnan"
] | [((1122, 1154), 'torch.nn.functional.cross_entropy', 'F.cross_entropy', (['outputs', 'labels'], {}), '(outputs, labels)\n', (1137, 1154), True, 'import torch.nn.functional as F\n'), ((1873, 1895), 'torch.norm', 'torch.norm', (['param.grad'], {}), '(param.grad)\n', (1883, 1895), False, 'import torch\n'), ((1493, 1512), 'numpy.sign', 'np.sign', (['param.grad'], {}), '(param.grad)\n', (1500, 1512), True, 'import numpy as np\n'), ((2768, 2784), 'torch.norm', 'torch.norm', (['d_at'], {}), '(d_at)\n', (2778, 2784), False, 'import torch\n'), ((1925, 1942), 'torch.isnan', 'torch.isnan', (['norm'], {}), '(norm)\n', (1936, 1942), False, 'import torch\n'), ((2030, 2058), 'torch.zeros_like', 'torch.zeros_like', (['param.grad'], {}), '(param.grad)\n', (2046, 2058), False, 'import torch\n'), ((2842, 2858), 'torch.norm', 'torch.norm', (['d_at'], {}), '(d_at)\n', (2852, 2858), False, 'import torch\n')] |
# -*- coding: utf-8 -*-
# @Date : 2020/6/1
# @Author: Luokun
# @Email : <EMAIL>
import sys
from os.path import dirname, abspath
import numpy as np
sys.path.append(dirname(dirname(abspath(__file__))))
def test_em():
from models.em import SimpleEM
y = np.array([1, 1, 0, 1, 0, 0, 1, 0, 1, 1])
em = SimpleEM([.5, .5, .5], 100)
em.fit(y)
print(em.prob) # [0.5, 0.6, 0.6]
em = SimpleEM([.4, .6, .7], 100)
em.fit(y)
print(em.prob) # [0.4064, 0.5368, 0.6432]
if __name__ == '__main__':
test_em()
| [
"os.path.abspath",
"numpy.array",
"models.em.SimpleEM"
] | [((264, 304), 'numpy.array', 'np.array', (['[1, 1, 0, 1, 0, 0, 1, 0, 1, 1]'], {}), '([1, 1, 0, 1, 0, 0, 1, 0, 1, 1])\n', (272, 304), True, 'import numpy as np\n'), ((314, 344), 'models.em.SimpleEM', 'SimpleEM', (['[0.5, 0.5, 0.5]', '(100)'], {}), '([0.5, 0.5, 0.5], 100)\n', (322, 344), False, 'from models.em import SimpleEM\n'), ((404, 434), 'models.em.SimpleEM', 'SimpleEM', (['[0.4, 0.6, 0.7]', '(100)'], {}), '([0.4, 0.6, 0.7], 100)\n', (412, 434), False, 'from models.em import SimpleEM\n'), ((183, 200), 'os.path.abspath', 'abspath', (['__file__'], {}), '(__file__)\n', (190, 200), False, 'from os.path import dirname, abspath\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#
# Copyright (c) 2020 University of Dundee.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
# OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Version: 1.0
#
import numpy
import os
import omero.clients
from omero.gateway import BlitzGateway
from getpass import getpass
from collections import OrderedDict
from ilastik import app
from ilastik.applets.dataSelection.opDataSelection import PreloadedArrayDatasetInfo # noqa
# Connect to the server
def connect(hostname, username, password):
conn = BlitzGateway(username, password,
host=hostname, secure=True)
conn.connect()
return conn
# Load-images
def load_images(conn, dataset_id):
return conn.getObjects('Image', opts={'dataset': dataset_id})
# Create-dataset
def create_dataset(conn, dataset_id):
dataset = omero.model.DatasetI()
v = "ilastik_probabilities_from_dataset_%s" % dataset_id
dataset.setName(omero.rtypes.rstring(v))
v = "ilatisk results probabilities from Dataset:%s" % dataset_id
dataset.setDescription(omero.rtypes.rstring(v))
return conn.getUpdateService().saveAndReturnObject(dataset)
# Load-data
def load_numpy_array(image):
pixels = image.getPrimaryPixels()
size_z = image.getSizeZ()
size_c = image.getSizeC()
size_t = image.getSizeT()
size_y = image.getSizeY()
size_x = image.getSizeX()
z, t, c = 0, 0, 0 # first plane of the image
zct_list = []
for t in range(size_t):
for z in range(size_z): # get the Z-stack
for c in range(size_c): # all channels
zct_list.append((z, c, t))
values = []
# Load all the planes as YX numpy array
planes = pixels.getPlanes(zct_list)
j = 0
k = 0
tmp_c = []
tmp_z = []
s = "z:%s t:%s c:%s y:%s x:%s" % (size_z, size_t, size_c, size_y, size_x)
print(s)
# axis tzyxc
print("Downloading image %s" % image.getName())
for i, p in enumerate(planes):
if k < size_z:
if j < size_c:
tmp_c.append(p)
j = j + 1
if j == size_c:
# use dstack to have c at the end
tmp_z.append(numpy.dstack(tmp_c))
tmp_c = []
j = 0
k = k + 1
if k == size_z: # done with the stack
values.append(numpy.stack(tmp_z))
tmp_z = []
k = 0
return numpy.stack(values)
# Analyze-data
def analyze(conn, images, model, new_dataset):
# Prepare ilastik
os.environ["LAZYFLOW_THREADS"] = "2"
os.environ["LAZYFLOW_TOTAL_RAM_MB"] = "2000"
args = app.parse_args([])
args.headless = True
args.project = model
shell = app.main(args)
for image in images:
input_data = load_numpy_array(image)
# run ilastik headless
print('running ilastik using %s and %s' % (model, image.getName()))
data = [ {"Raw Data": PreloadedArrayDatasetInfo(preloaded_array=input_data, axistags=vigra.defaultAxistags("tzyxc"))}] # noqa
predictions = shell.workflow.batchProcessingApplet.run_export(data,
export_to_array=True) # noqa
for d in predictions:
save_results(conn, image, d, new_dataset)
# Save-results
def save_results(conn, image, data, dataset):
filename, file_extension = os.path.splitext(image.getName())
# Save the probabilities file as an image
print("Saving Probabilities as an Image in OMERO")
name = filename + "_Probabilities"
desc = "ilastik probabilities from Image:%s" % image.getId()
# Re-organise array from tzyxc to zctyx order expected by OMERO
data = data.swapaxes(0, 1).swapaxes(3, 4).swapaxes(2, 3).swapaxes(1, 2)
def plane_gen():
"""
Set up a generator of 2D numpy arrays.
The createImage method below expects planes in the order specified here
(for z.. for c.. for t..)
"""
size_z = data.shape[0]-1
for z in range(data.shape[0]): # all Z sections data.shape[0]
print('z: %s/%s' % (z, size_z))
for c in range(data.shape[1]): # all channels
for t in range(data.shape[2]): # all time-points
yield data[z][c][t]
conn.createImageFromNumpySeq(plane_gen(), name, data.shape[0],
data.shape[1], data.shape[2],
description=desc, dataset=dataset)
# Disconnect
def disconnect(conn):
conn.close()
# main
def main():
try:
# Collect user credentials
host = input("Host [wss://workshop.openmicroscopy.org/omero-ws]: ") or 'wss://workshop.openmicroscopy.org/omero-ws' # noqa
username = input("Username [trainer-1]: ") or 'trainer-1'
password = getpass("Password: ")
dataset_id = input("Dataset ID [6210]: ") or '6210'
# Connect to the server
conn = connect(host, username, password)
conn.c.enableKeepAlive(60)
# path to the ilastik project
ilastik_project = "../notebooks/pipelines/pixel-class-133.ilp"
# Load the images in the dataset
images = load_images(conn, dataset_id)
new_dataset = create_dataset(conn, dataset_id)
analyze(conn, images, ilastik_project, new_dataset)
finally:
disconnect(conn)
print("done")
if __name__ == "__main__":
main()
| [
"numpy.stack",
"ilastik.app.parse_args",
"numpy.dstack",
"getpass.getpass",
"ilastik.app.main",
"omero.gateway.BlitzGateway"
] | [((1755, 1815), 'omero.gateway.BlitzGateway', 'BlitzGateway', (['username', 'password'], {'host': 'hostname', 'secure': '(True)'}), '(username, password, host=hostname, secure=True)\n', (1767, 1815), False, 'from omero.gateway import BlitzGateway\n'), ((3675, 3694), 'numpy.stack', 'numpy.stack', (['values'], {}), '(values)\n', (3686, 3694), False, 'import numpy\n'), ((3882, 3900), 'ilastik.app.parse_args', 'app.parse_args', (['[]'], {}), '([])\n', (3896, 3900), False, 'from ilastik import app\n'), ((3963, 3977), 'ilastik.app.main', 'app.main', (['args'], {}), '(args)\n', (3971, 3977), False, 'from ilastik import app\n'), ((6082, 6103), 'getpass.getpass', 'getpass', (['"""Password: """'], {}), "('Password: ')\n", (6089, 6103), False, 'from getpass import getpass\n'), ((3603, 3621), 'numpy.stack', 'numpy.stack', (['tmp_z'], {}), '(tmp_z)\n', (3614, 3621), False, 'import numpy\n'), ((3422, 3441), 'numpy.dstack', 'numpy.dstack', (['tmp_c'], {}), '(tmp_c)\n', (3434, 3441), False, 'import numpy\n')] |
"""Module for common card entities and operations."""
import numpy as np
import tkinter as tk
import os
from functools import partial
from os.path import join
RESOURSES_DIR = os.path.join(os.path.dirname(__file__), "..", 'resources')
try:
from playsound import playsound
playsound(join(RESOURSES_DIR, 'sounds/shuffle.wav'))
except ImportError:
def playsound(filename):
"""Empty functions if import fails."""
pass
class Cards(tk.Frame):
"""Class for basic operation with cards.
:param parent: parameter to be passed to tkinter.Frame constructor,
defaults to None
"""
def __init__(self, parent=None):
"""Initialize all card`s images."""
super().__init__(parent)
# 0 - Hearts, 1 - Diamonds, 2 - Clubs, 3 - Spades
self.cards_images = np.zeros((4, 13), dtype=tk.PhotoImage)
self.card_height, self.card_width = 230, 145
for i in range(self.cards_images.shape[0]):
for j in range(self.cards_images.shape[1]):
name = join(RESOURSES_DIR, 'cards', '{}_{}.png'.format(i, j))
self.cards_images[i, j] = tk.PhotoImage(file=name)
self.empty_image = tk.PhotoImage(
file=join(RESOURSES_DIR, 'cards/empty.png'))
self.back_image = tk.PhotoImage(
file=join(RESOURSES_DIR, 'cards/back.png'))
def create_button(self, card_id, position, relief='groove'):
"""
Create specified card`s button in specified position.
:param card_id: id of card to create; could be either list
[card_suit, card_value] or -1 for blank space or
None for back of cards
:param position: desired y coordinate and x coordinate for button
:type position: list
:param relief: relief style for button, defaults to groove
:type relief: string
:return: created button
:rtype: tkinter.Button
"""
if card_id is None:
button = tk.Button(
self.master,
image=self.empty_image,
relief=relief
)
elif card_id == -1:
button = tk.Button(
self.master,
image=self.back_image,
relief=relief
)
else:
(i, j) = card_id
button = tk.Button(
self.master,
image=self.cards_images[i, j],
relief=relief
)
button.place(y=position[0], x=position[1])
return button
class Deck(Cards):
"""Base class for game handlers.
:param parent: parameter to be passed to tkinter.Frame constructor,
defaults to None
:param row: row to visualize deck on, defaults to 0
:type row: int
:param hands: card hands to handle, defaults to None
:param player_hand: index to player hand, defaults to 0
:type player_hand: int
:param expand: whether to expand card hand or to keep it to 6 cards,
defaults to False
:type expand: bool
"""
def __init__(
self, parent=None, row=0,
hands=None, player_hand=0, expand=False):
"""Create card deck and initialize common game parameters."""
super().__init__(parent)
self.row = row
self.hands = hands
self.player_hand = player_hand
self.expand = expand
self.deck_cards_ids = np.arange(52)
self.deck_cards = []
self.update()
def update(self):
"""Update and visualize deck cards."""
for deck_card in self.deck_cards:
deck_card.destroy()
self.deck_cards.clear()
self.deck_cards.append(
tk.Button(self.master, image=self.empty_image, state='disabled')
)
self.deck_cards[-1].place(
y=self.row * self.card_height,
x=0
)
self.deck_cards[-1].bind(
'<Button-3>',
partial(self.get, self.hands[self.player_hand])
)
for i in range(int(np.ceil(self.deck_cards_ids.size / 13))):
self.deck_cards.append(
tk.Button(self.master, image=self.back_image, state='disabled')
)
self.deck_cards[-1].place(
y=self.row * self.card_height - i*3,
x=-i*3
)
self.deck_cards[-1].bind(
'<Button-3>',
partial(self.get, self.hands[self.player_hand])
)
def draw(self, hand, amount=6, empty=0, drop=False, event=None):
"""
Draw desired amount of cards to specified hand and visualize them.
:param hands: card hands to handle
:param amount: total amount of cards to draw, defaults to 6
:type amount: int
:param empty: number of drawed card to be empty, defaults to 0
:type empty: int
:param drop: whether to return drawed cards to deck or not,
defaults to False
:type drop: bool
"""
if self.deck_cards_ids.size > 0:
playsound(join(RESOURSES_DIR, 'sounds/draw.wav'))
cards_ids = []
for i in range(amount - empty):
card_id = np.random.choice(self.deck_cards_ids, (1))
if drop:
self.deck_cards_ids = np.setdiff1d(
self.deck_cards_ids,
card_id
)
cards_ids.append([card_id[0] // 13, card_id[0] % 13])
for i in range(empty):
cards_ids.append(None)
hand.show(cards_ids)
self.update()
def get(self, hand, event=None, card_id=None):
"""
Draw one card to specified hand and visualize it.
:param hand: card hand to draw to
:param card_id: card_id to get, defaults to None
:type card_id: list
"""
if None in hand.cards_ids and self.deck_cards_ids.size > 0:
playsound(join(RESOURSES_DIR, 'sounds/draw.wav'))
index = hand.cards_ids.index(None)
if card_id is None:
card_id = np.random.choice(self.deck_cards_ids, (1))
self.deck_cards_ids = np.setdiff1d(self.deck_cards_ids, card_id)
i, j = card_id[0] // 13, card_id[0] % 13
hand.cards_ids[index] = [i, j]
hand.show(hand.cards_ids)
self.update()
elif self.expand and self.deck_cards_ids.size > 0:
playsound(join(RESOURSES_DIR, 'sounds/draw.wav'))
if card_id is None:
card_id = np.random.choice(self.deck_cards_ids, (1))
self.deck_cards_ids = np.setdiff1d(self.deck_cards_ids, card_id)
i, j = card_id[0] // 13, card_id[0] % 13
hand.cards_ids.append([i, j])
hand.show(hand.cards_ids)
self.update()
def shuffle(self, event=None):
"""Reset the deck and card hands."""
playsound(join(RESOURSES_DIR, 'sounds/shuffle.wav'))
self.deck_cards_ids = np.arange(52)
self.update()
for hand in self.hands:
hand.show([None, None, None, None, None, None])
class Hand(Cards):
"""Class that simulates actions of a card hand.
:param parent: parameter to be passed to tkinter.Frame constructor,
defaults to None
:param row: row to visualize hand on, defaults to 0
:type row: int
:param show_cards: whether to show cards or their backs, defaults to True
:type show_cards: bool
:param allow_movement: whether to allow to move cards within the hand,
defaults to True
:type allow_movement: bool
"""
def __init__(
self, parent=None, row=0,
show_cards=True, allow_movement=True):
"""Initialize card hand parameters."""
super().__init__(parent)
self.row = row
self.show_cards = show_cards
self.allow_movement = allow_movement
self.cards_ids = []
self.cards = []
self.change_index = -1
def position(self, column):
"""
Return card`s position based on its column.
:param column: desired place in card hand (0 .. len(cards_ids) - 1)
:type column: int
"""
if len(self.cards_ids) <= 6:
return [self.row * self.card_height, column * self.card_width]
else:
return [self.row * self.card_height, np.floor(
column * self.card_width * 5 / (len(self.cards_ids) - 1))
]
def choose_card(self, index, event=None):
"""
Highlight or swap specified card.
:param index: index to hand`s card to perform action on
:type index: int
"""
if self.change_index == -1:
self.cards[index].destroy()
self.cards[index] = self.create_button(
self.cards_ids[index],
self.position(index),
'sunken'
)
self.cards[index].bind(
'<Button-1>',
partial(self.choose_card, index)
)
self.change_index = index
else:
if self.change_index != index:
playsound(join(RESOURSES_DIR, 'sounds/playcard.wav'))
self.cards_ids[index], self.cards_ids[self.change_index] = \
self.cards_ids[self.change_index], self.cards_ids[index]
self.show(self.cards_ids)
else:
self.show(self.cards_ids)
self.change_index = -1
def show(self, cards_ids):
"""
Visualize specified cards.
:param cards_ids: card`s identifiers to visualize
:type cards_ids: list
"""
for card in self.cards:
card.destroy()
self.cards.clear()
self.cards_ids = cards_ids
if len(cards_ids) != 0:
for column, card_id in enumerate(cards_ids):
if not self.show_cards and card_id is not None:
self.cards.append(
self.create_button(-1, self.position(column))
)
else:
self.cards.append(
self.create_button(card_id, self.position(column))
)
if self.allow_movement:
self.cards[-1].bind(
'<Button-1>',
partial(self.choose_card, column)
)
| [
"functools.partial",
"tkinter.PhotoImage",
"numpy.ceil",
"tkinter.Button",
"os.path.dirname",
"numpy.zeros",
"numpy.setdiff1d",
"numpy.arange",
"numpy.random.choice",
"os.path.join"
] | [((192, 217), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (207, 217), False, 'import os\n'), ((294, 335), 'os.path.join', 'join', (['RESOURSES_DIR', '"""sounds/shuffle.wav"""'], {}), "(RESOURSES_DIR, 'sounds/shuffle.wav')\n", (298, 335), False, 'from os.path import join\n'), ((823, 861), 'numpy.zeros', 'np.zeros', (['(4, 13)'], {'dtype': 'tk.PhotoImage'}), '((4, 13), dtype=tk.PhotoImage)\n', (831, 861), True, 'import numpy as np\n'), ((3424, 3437), 'numpy.arange', 'np.arange', (['(52)'], {}), '(52)\n', (3433, 3437), True, 'import numpy as np\n'), ((7057, 7070), 'numpy.arange', 'np.arange', (['(52)'], {}), '(52)\n', (7066, 7070), True, 'import numpy as np\n'), ((1992, 2053), 'tkinter.Button', 'tk.Button', (['self.master'], {'image': 'self.empty_image', 'relief': 'relief'}), '(self.master, image=self.empty_image, relief=relief)\n', (2001, 2053), True, 'import tkinter as tk\n'), ((3710, 3774), 'tkinter.Button', 'tk.Button', (['self.master'], {'image': 'self.empty_image', 'state': '"""disabled"""'}), "(self.master, image=self.empty_image, state='disabled')\n", (3719, 3774), True, 'import tkinter as tk\n'), ((3961, 4008), 'functools.partial', 'partial', (['self.get', 'self.hands[self.player_hand]'], {}), '(self.get, self.hands[self.player_hand])\n', (3968, 4008), False, 'from functools import partial\n'), ((6221, 6263), 'numpy.setdiff1d', 'np.setdiff1d', (['self.deck_cards_ids', 'card_id'], {}), '(self.deck_cards_ids, card_id)\n', (6233, 6263), True, 'import numpy as np\n'), ((6984, 7025), 'os.path.join', 'join', (['RESOURSES_DIR', '"""sounds/shuffle.wav"""'], {}), "(RESOURSES_DIR, 'sounds/shuffle.wav')\n", (6988, 7025), False, 'from os.path import join\n'), ((1144, 1168), 'tkinter.PhotoImage', 'tk.PhotoImage', ([], {'file': 'name'}), '(file=name)\n', (1157, 1168), True, 'import tkinter as tk\n'), ((1228, 1266), 'os.path.join', 'join', (['RESOURSES_DIR', '"""cards/empty.png"""'], {}), "(RESOURSES_DIR, 'cards/empty.png')\n", (1232, 1266), False, 'from os.path import join\n'), ((1326, 1363), 'os.path.join', 'join', (['RESOURSES_DIR', '"""cards/back.png"""'], {}), "(RESOURSES_DIR, 'cards/back.png')\n", (1330, 1363), False, 'from os.path import join\n'), ((2165, 2225), 'tkinter.Button', 'tk.Button', (['self.master'], {'image': 'self.back_image', 'relief': 'relief'}), '(self.master, image=self.back_image, relief=relief)\n', (2174, 2225), True, 'import tkinter as tk\n'), ((2352, 2420), 'tkinter.Button', 'tk.Button', (['self.master'], {'image': 'self.cards_images[i, j]', 'relief': 'relief'}), '(self.master, image=self.cards_images[i, j], relief=relief)\n', (2361, 2420), True, 'import tkinter as tk\n'), ((4047, 4085), 'numpy.ceil', 'np.ceil', (['(self.deck_cards_ids.size / 13)'], {}), '(self.deck_cards_ids.size / 13)\n', (4054, 4085), True, 'import numpy as np\n'), ((4141, 4204), 'tkinter.Button', 'tk.Button', (['self.master'], {'image': 'self.back_image', 'state': '"""disabled"""'}), "(self.master, image=self.back_image, state='disabled')\n", (4150, 4204), True, 'import tkinter as tk\n'), ((4432, 4479), 'functools.partial', 'partial', (['self.get', 'self.hands[self.player_hand]'], {}), '(self.get, self.hands[self.player_hand])\n', (4439, 4479), False, 'from functools import partial\n'), ((5083, 5121), 'os.path.join', 'join', (['RESOURSES_DIR', '"""sounds/draw.wav"""'], {}), "(RESOURSES_DIR, 'sounds/draw.wav')\n", (5087, 5121), False, 'from os.path import join\n'), ((5220, 5260), 'numpy.random.choice', 'np.random.choice', (['self.deck_cards_ids', '(1)'], {}), '(self.deck_cards_ids, 1)\n', (5236, 5260), True, 'import numpy as np\n'), ((5999, 6037), 'os.path.join', 'join', (['RESOURSES_DIR', '"""sounds/draw.wav"""'], {}), "(RESOURSES_DIR, 'sounds/draw.wav')\n", (6003, 6037), False, 'from os.path import join\n'), ((6144, 6184), 'numpy.random.choice', 'np.random.choice', (['self.deck_cards_ids', '(1)'], {}), '(self.deck_cards_ids, 1)\n', (6160, 6184), True, 'import numpy as np\n'), ((6682, 6724), 'numpy.setdiff1d', 'np.setdiff1d', (['self.deck_cards_ids', 'card_id'], {}), '(self.deck_cards_ids, card_id)\n', (6694, 6724), True, 'import numpy as np\n'), ((9067, 9099), 'functools.partial', 'partial', (['self.choose_card', 'index'], {}), '(self.choose_card, index)\n', (9074, 9099), False, 'from functools import partial\n'), ((5330, 5372), 'numpy.setdiff1d', 'np.setdiff1d', (['self.deck_cards_ids', 'card_id'], {}), '(self.deck_cards_ids, card_id)\n', (5342, 5372), True, 'import numpy as np\n'), ((6507, 6545), 'os.path.join', 'join', (['RESOURSES_DIR', '"""sounds/draw.wav"""'], {}), "(RESOURSES_DIR, 'sounds/draw.wav')\n", (6511, 6545), False, 'from os.path import join\n'), ((6605, 6645), 'numpy.random.choice', 'np.random.choice', (['self.deck_cards_ids', '(1)'], {}), '(self.deck_cards_ids, 1)\n', (6621, 6645), True, 'import numpy as np\n'), ((9235, 9277), 'os.path.join', 'join', (['RESOURSES_DIR', '"""sounds/playcard.wav"""'], {}), "(RESOURSES_DIR, 'sounds/playcard.wav')\n", (9239, 9277), False, 'from os.path import join\n'), ((10459, 10492), 'functools.partial', 'partial', (['self.choose_card', 'column'], {}), '(self.choose_card, column)\n', (10466, 10492), False, 'from functools import partial\n')] |
# SPDX-FileCopyrightText: 2021 Division of Intelligent Medical Systems, DKFZ
# SPDX-FileCopyrightText: 2021 <NAME>
# SPDX-License-Identifier: MIT
import unittest
import numpy as np
from simpa.utils.libraries.tissue_library import TISSUE_LIBRARY
from simpa.utils import Tags
from simpa.utils.settings import Settings
from simpa.utils.libraries.structure_library import EllipticalTubularStructure
class TestEllipticalTubes(unittest.TestCase):
def setUp(self):
self.global_settings = Settings()
self.global_settings[Tags.SPACING_MM] = 1
self.global_settings[Tags.DIM_VOLUME_X_MM] = 5
self.global_settings[Tags.DIM_VOLUME_Y_MM] = 5
self.global_settings[Tags.DIM_VOLUME_Z_MM] = 5
self.elliptical_tube_settings = Settings()
self.elliptical_tube_settings[Tags.STRUCTURE_START_MM] = [0, 0, 0]
self.elliptical_tube_settings[Tags.STRUCTURE_RADIUS_MM] = 1
self.elliptical_tube_settings[Tags.STRUCTURE_END_MM] = [0, 5, 0]
self.elliptical_tube_settings[Tags.STRUCTURE_ECCENTRICITY] = 0
self.elliptical_tube_settings[Tags.MOLECULE_COMPOSITION] = TISSUE_LIBRARY.muscle()
self.elliptical_tube_settings[Tags.ADHERE_TO_DEFORMATION] = True
self.elliptical_tube_settings[Tags.CONSIDER_PARTIAL_VOLUME] = True
self.global_settings.set_volume_creation_settings(
{
Tags.STRUCTURES: self.elliptical_tube_settings
}
)
def assert_values(self, volume, values):
assert abs(volume[0][0][0] - values[0]) < 1e-5, "excpected " + str(values[0]) + " but was " + str(volume[0][0][0])
assert abs(volume[0][0][1] - values[1]) < 1e-5, "excpected " + str(values[1]) + " but was " + str(volume[0][0][1])
assert abs(volume[0][0][2] - values[2]) < 1e-5, "excpected " + str(values[2]) + " but was " + str(volume[0][0][2])
assert abs(volume[0][0][3] - values[3]) < 1e-5, "excpected " + str(values[3]) + " but was " + str(volume[0][0][3])
assert abs(volume[0][0][4] - values[4]) < 1e-5, "excpected " + str(values[4]) + " but was " + str(volume[0][0][4])
assert abs(volume[0][0][5] - values[5]) < 1e-5, "excpected " + str(values[5]) + " but was " + str(volume[0][0][5])
def test_elliptical_tube_structures_partial_volume_within_one_voxel(self):
self.elliptical_tube_settings[Tags.STRUCTURE_START_MM] = [0.5, 0, 0.5]
self.elliptical_tube_settings[Tags.STRUCTURE_END_MM] = [0.5, 5, 0.5]
self.elliptical_tube_settings[Tags.STRUCTURE_RADIUS_MM] = 0.4
ets = EllipticalTubularStructure(self.global_settings, self.elliptical_tube_settings)
assert 0 < ets.geometrical_volume[0, 0, 0] < 1
assert 0 < ets.geometrical_volume[0, 4, 0] < 1
def test_elliptical_tube_structure_partial_volume_within_two_voxels(self):
self.elliptical_tube_settings[Tags.STRUCTURE_START_MM] = [1, 0, 1]
self.elliptical_tube_settings[Tags.STRUCTURE_END_MM] = [1, 5, 1]
self.elliptical_tube_settings[Tags.STRUCTURE_RADIUS_MM] = 0.4
ets = EllipticalTubularStructure(self.global_settings, self.elliptical_tube_settings)
assert 0 < ets.geometrical_volume[0, 0, 0] < 1
assert 0 < ets.geometrical_volume[1, 0, 0] < 1
assert 0 < ets.geometrical_volume[0, 1, 0] < 1
assert 0 < ets.geometrical_volume[0, 0, 1] < 1
assert 0 < ets.geometrical_volume[1, 1, 0] < 1
assert 0 < ets.geometrical_volume[1, 0, 1] < 1
assert 0 < ets.geometrical_volume[0, 1, 1] < 1
assert 0 < ets.geometrical_volume[1, 1, 1] < 1
def test_elliptical_tube_structure_partial_volume_with_one_full_voxel(self):
self.elliptical_tube_settings[Tags.STRUCTURE_START_MM] = [1.5, 0, 1.5]
self.elliptical_tube_settings[Tags.STRUCTURE_END_MM] = [1.5, 5, 1.5]
self.elliptical_tube_settings[Tags.STRUCTURE_RADIUS_MM] = np.sqrt(3*0.25) # diagonal of exactly one voxel
ets = EllipticalTubularStructure(self.global_settings, self.elliptical_tube_settings)
assert ets.geometrical_volume[1, 1, 1] == 1
assert ets.geometrical_volume[0, 1, 0] == 0
assert ets.geometrical_volume[0, 1, 2] == 0
assert ets.geometrical_volume[2, 1, 0] == 0
assert ets.geometrical_volume[2, 2, 2] == 0
assert 0 < ets.geometrical_volume[0, 1, 1] < 1
assert 0 < ets.geometrical_volume[1, 1, 0] < 1
assert 0 < ets.geometrical_volume[1, 1, 2] < 1
assert 0 < ets.geometrical_volume[2, 1, 1] < 1
def test_elliptical_tube_structure_partial_volume_across_volume(self):
self.elliptical_tube_settings[Tags.STRUCTURE_START_MM] = [0, 0, 0]
self.elliptical_tube_settings[Tags.STRUCTURE_END_MM] = [5, 5, 5]
self.elliptical_tube_settings[Tags.STRUCTURE_RADIUS_MM] = 1
ets = EllipticalTubularStructure(self.global_settings, self.elliptical_tube_settings)
assert ets.geometrical_volume[0, 0, 0] == 1
assert 0 < ets.geometrical_volume[0, 0, 1] < 1
assert 0 < ets.geometrical_volume[1, 0, 0] < 1
assert 0 < ets.geometrical_volume[1, 0, 1] < 1
assert ets.geometrical_volume[2, 2, 2] == 1
assert 0 < ets.geometrical_volume[2, 2, 3] < 1
assert 0 < ets.geometrical_volume[3, 2, 2] < 1
assert 0 < ets.geometrical_volume[3, 2, 3] < 1
assert 0 < ets.geometrical_volume[2, 2, 1] < 1
assert 0 < ets.geometrical_volume[1, 2, 2] < 1
assert 0 < ets.geometrical_volume[1, 2, 3] < 1
assert ets.geometrical_volume[4, 4, 4] == 1
def test_elliptical_tube_structure_partial_volume_with_eccentricity(self):
self.global_settings[Tags.DIM_VOLUME_X_MM] = 100
self.global_settings[Tags.DIM_VOLUME_Y_MM] = 100
self.global_settings[Tags.DIM_VOLUME_Z_MM] = 100
self.elliptical_tube_settings[Tags.STRUCTURE_START_MM] = [50, 0, 50]
self.elliptical_tube_settings[Tags.STRUCTURE_END_MM] = [50, 50, 50]
self.elliptical_tube_settings[Tags.STRUCTURE_RADIUS_MM] = 15
self.elliptical_tube_settings[Tags.STRUCTURE_ECCENTRICITY] = 0.8
ets = EllipticalTubularStructure(self.global_settings, self.elliptical_tube_settings)
assert ets.geometrical_volume[50, 50, 50] == 1
assert ets.geometrical_volume[50, 50, 40] == 1
assert ets.geometrical_volume[50, 50, 60] == 1
assert ets.geometrical_volume[35, 50, 50] == 1
assert ets.geometrical_volume[65, 50, 50] == 1
assert 0 < ets.geometrical_volume[50, 50, 38] < 1
assert 0 < ets.geometrical_volume[50, 50, 61] < 1
assert 0 < ets.geometrical_volume[30, 50, 50] < 1
assert 0 < ets.geometrical_volume[69, 50, 50] < 1
| [
"simpa.utils.libraries.tissue_library.TISSUE_LIBRARY.muscle",
"simpa.utils.settings.Settings",
"numpy.sqrt",
"simpa.utils.libraries.structure_library.EllipticalTubularStructure"
] | [((497, 507), 'simpa.utils.settings.Settings', 'Settings', ([], {}), '()\n', (505, 507), False, 'from simpa.utils.settings import Settings\n'), ((765, 775), 'simpa.utils.settings.Settings', 'Settings', ([], {}), '()\n', (773, 775), False, 'from simpa.utils.settings import Settings\n'), ((1130, 1153), 'simpa.utils.libraries.tissue_library.TISSUE_LIBRARY.muscle', 'TISSUE_LIBRARY.muscle', ([], {}), '()\n', (1151, 1153), False, 'from simpa.utils.libraries.tissue_library import TISSUE_LIBRARY\n'), ((2567, 2646), 'simpa.utils.libraries.structure_library.EllipticalTubularStructure', 'EllipticalTubularStructure', (['self.global_settings', 'self.elliptical_tube_settings'], {}), '(self.global_settings, self.elliptical_tube_settings)\n', (2593, 2646), False, 'from simpa.utils.libraries.structure_library import EllipticalTubularStructure\n'), ((3069, 3148), 'simpa.utils.libraries.structure_library.EllipticalTubularStructure', 'EllipticalTubularStructure', (['self.global_settings', 'self.elliptical_tube_settings'], {}), '(self.global_settings, self.elliptical_tube_settings)\n', (3095, 3148), False, 'from simpa.utils.libraries.structure_library import EllipticalTubularStructure\n'), ((3893, 3910), 'numpy.sqrt', 'np.sqrt', (['(3 * 0.25)'], {}), '(3 * 0.25)\n', (3900, 3910), True, 'import numpy as np\n'), ((3959, 4038), 'simpa.utils.libraries.structure_library.EllipticalTubularStructure', 'EllipticalTubularStructure', (['self.global_settings', 'self.elliptical_tube_settings'], {}), '(self.global_settings, self.elliptical_tube_settings)\n', (3985, 4038), False, 'from simpa.utils.libraries.structure_library import EllipticalTubularStructure\n'), ((4825, 4904), 'simpa.utils.libraries.structure_library.EllipticalTubularStructure', 'EllipticalTubularStructure', (['self.global_settings', 'self.elliptical_tube_settings'], {}), '(self.global_settings, self.elliptical_tube_settings)\n', (4851, 4904), False, 'from simpa.utils.libraries.structure_library import EllipticalTubularStructure\n'), ((6116, 6195), 'simpa.utils.libraries.structure_library.EllipticalTubularStructure', 'EllipticalTubularStructure', (['self.global_settings', 'self.elliptical_tube_settings'], {}), '(self.global_settings, self.elliptical_tube_settings)\n', (6142, 6195), False, 'from simpa.utils.libraries.structure_library import EllipticalTubularStructure\n')] |
import numpy as np
class DataClass1(object):
"""docstring for A"""
def __init__(self):
self.data = np.zeros((60,3,32,32))
self.indexes = np.arange(self.data.shape[0])
print(self.data.shape, self.indexes)
def __len__(self):
return self.data.shape[0]
if __name__ == '__main__':
A = DataClass1()
print(len(A))
print(A[0]) | [
"numpy.zeros",
"numpy.arange"
] | [((116, 141), 'numpy.zeros', 'np.zeros', (['(60, 3, 32, 32)'], {}), '((60, 3, 32, 32))\n', (124, 141), True, 'import numpy as np\n'), ((163, 192), 'numpy.arange', 'np.arange', (['self.data.shape[0]'], {}), '(self.data.shape[0])\n', (172, 192), True, 'import numpy as np\n')] |
import torch
from torch import nn, optim
from torch.nn.modules.loss import TripletMarginLoss
import numpy as np
import matplotlib.pyplot as plt
class NeuralNet(nn.Module):
def __init__(self, descriptor_size, hidden_dim, embedding_dim):
super(NeuralNet, self).__init__()
self.descriptor_size = descriptor_size
self.hidden_dim = hidden_dim
self.embedding_dim = embedding_dim
self.n_thetas = 16
self.n_rhos = 5
self.mu_rho = self.init_mu_rho()
self.mu_rho = nn.Parameter(self.mu_rho)
self.sigma_rho = nn.Parameter(torch.empty([5, 1, 80]).float())
torch.nn.init.ones_(self.sigma_rho)
self.mu_theta = self.init_mu_theta()
self.mu_theta = nn.Parameter(self.mu_theta)
self.sigma_theta = nn.Parameter(torch.empty([5, 1, 80]).float())
torch.nn.init.ones_(self.sigma_theta)
self.feat1 = nn.Linear(descriptor_size, hidden_dim)
torch.nn.init.xavier_normal_(self.feat1.weight)
self.feat2 = nn.Linear(descriptor_size, hidden_dim)
torch.nn.init.xavier_normal_(self.feat2.weight)
self.feat3 = nn.Linear(descriptor_size, hidden_dim)
torch.nn.init.xavier_normal_(self.feat3.weight)
self.feat4 = nn.Linear(descriptor_size, hidden_dim)
torch.nn.init.xavier_normal_(self.feat4.weight)
self.feat5 = nn.Linear(descriptor_size, hidden_dim)
torch.nn.init.xavier_normal_(self.feat5.weight)
self.embedding = nn.Linear(hidden_dim * 5, embedding_dim)
torch.nn.init.xavier_normal_(self.embedding.weight)
# wrong name for now
self.elu = nn.LeakyReLU(.01)
def compute_initial_coordinates(self):
range_rho = [0.0, 12.4]
range_theta = [0, 2 * np.pi]
grid_rho = np.linspace(range_rho[0], range_rho[1], num=self.n_rhos + 1)
grid_rho = grid_rho[1:]
grid_theta = np.linspace(range_theta[0], range_theta[1], num=self.n_thetas + 1)
grid_theta = grid_theta[:-1]
grid_rho_, grid_theta_ = np.meshgrid(grid_rho, grid_theta, sparse=False)
grid_rho_ = (
grid_rho_.T
) # the traspose here is needed to have the same behaviour as Matlab code
grid_theta_ = (
grid_theta_.T
) # the traspose here is needed to have the same behaviour as Matlab code
grid_rho_ = grid_rho_.flatten()
grid_theta_ = grid_theta_.flatten()
coords = np.concatenate((grid_rho_[None, :], grid_theta_[None, :]), axis=0)
coords = coords.T # every row contains the coordinates of a grid intersection
return coords
def init_mu_rho(self):
mu_rho = torch.empty([5, 1, 80])
initial_coords = self.compute_initial_coordinates()
mu_rho_initial = np.expand_dims(initial_coords[:, 0], 0).astype(
"float32"
)
for i in range(5):
mu_rho[i] = torch.Tensor(mu_rho_initial)
return mu_rho
def init_mu_theta(self):
mu_theta = torch.empty([5, 1, 80])
initial_coords = self.compute_initial_coordinates()
mu_theta_initial = np.expand_dims(initial_coords[:, 1], 0).astype(
"float32"
)
for i in range(5):
mu_theta[i] = torch.Tensor(mu_theta_initial)
return mu_theta
def hist(self, x, bins, minimum, maximum, sigma, weights):
delta = (maximum - minimum) / float(bins)
centers = minimum + delta * (torch.arange(bins, device='cuda:0') + 0.5)
hist = torch.unsqueeze(x, 2) - torch.unsqueeze(centers, 3)
delta = torch.unsqueeze(delta, dim=3)
hist = torch.exp(-0.5*(hist/sigma)**2) / (sigma * np.sqrt(np.pi*2)) * delta
weights = torch.unsqueeze(weights, dim=2)
hist = hist * weights
hist = hist.sum(dim=3)
return hist
def inference(
self,
input_feat,
rho_coords,
theta_coords,
mask,
mu_rho,
sigma_rho,
mu_theta,
sigma_theta,
eps=1e-5,
mean_gauss_activation=True,
):
n_samples = rho_coords.shape[0]
n_vertices = rho_coords.shape[1]
# n_feat = input_feat.get_shape().as_list()[2]
rho_coords_ = torch.reshape(rho_coords, [-1, 1]) # batch_size*n_vertices
thetas_coords_ = torch.reshape(theta_coords, [-1, 1]) # batch_size*n_vertices
all_conv_feat = []
soft_grid = self.compute_soft_grid(
input_feat,
rho_coords_,
thetas_coords_,
mask,
n_samples,
n_vertices,
mu_rho,
sigma_rho,
mu_theta,
sigma_theta,
0,
eps=1e-5,
mean_gauss_activation=True
)
#return the soft grid only
return soft_grid
def compute_soft_grid(
self,
input_feat,
rho_coords_,
thetas_coords_,
mask,
n_samples,
n_vertices,
mu_rho,
sigma_rho,
mu_theta,
sigma_theta,
k,
eps=1e-5,
mean_gauss_activation=True
):
#Change back to gradient along rho and theta, but mulitply by the unit vectors
rho_coords_ = torch.exp(
-torch.square(rho_coords_ - mu_rho) / (torch.square(sigma_rho) + eps)
)
thetas_coords_ = torch.exp(
-torch.square(thetas_coords_ - mu_theta) / (torch.square(sigma_theta) + eps)
)
gauss_activations = torch.multiply(
rho_coords_, thetas_coords_
) # batch_size*n_vertices, n_gauss
gauss_activations = torch.reshape(
gauss_activations, [n_samples, n_vertices, -1]
) # batch_size, n_vertices, n_gauss
gauss_activations = torch.multiply(gauss_activations, mask)
if (
mean_gauss_activation
): # computes mean weights for the different gaussians
gauss_activations /= (
torch.sum(gauss_activations, 1, keepdims=True) + eps
) # batch_size, n_vertices, n_gauss
gauss_activations = torch.unsqueeze(
gauss_activations, 2
) # batch_size, n_vertices, 1, n_gauss,
input_feat_ = torch.unsqueeze(
input_feat, 3
) # batch_size, n_vertices, n_feat, 1
gauss_desc = torch.multiply(
gauss_activations, input_feat_
) # batch_size, n_vertices, n_feat, n_gauss,
gauss_desc = torch.sum(gauss_desc, 1) # batch_size, n_feat, n_gauss,
gauss_desc = torch.reshape(
gauss_desc, [n_samples, self.n_thetas * self.n_rhos]
) # batch_size, 80
return gauss_desc
def net(self, batch_histogram):
# pass each feature through a seperate neural network channel
output1 = self.feat1(batch_histogram[:, 0:self.descriptor_size])
output2 = self.feat2(batch_histogram[:, self.descriptor_size:2*self.descriptor_size])
output3 = self.feat3(batch_histogram[:, 2*self.descriptor_size:3*self.descriptor_size])
output4 = self.feat4(batch_histogram[:, 3*self.descriptor_size:4*self.descriptor_size])
output5 = self.feat5(batch_histogram[:, 4*self.descriptor_size:5*self.descriptor_size])
# concatenate all features along dimension 1, [8, 400]
full_desc = torch.cat((output1, output2, output3, output4, output5), dim=1)
full_desc = self.elu(full_desc)
# embedding layer for all features
out = self.embedding(full_desc)
return out
def forward(
self,
batch_rho_coords,
batch_theta_coords,
batch_input_feat,
batch_mask,
region_rows,
region_columns,
num_regions,
num_bins_gradient,
num_bins_grid,
batch_size,
device,
mean_gauss_activation=True
):
n_thetas = 16
n_rhos = 5
all_soft_grids = torch.empty([5, batch_size, 80], device=device)
#mag = torch.empty([5 * batch_size, 80], device=device)
#direction = torch.empty([5 * batch_size, 80], device=device)
#gradient_r = torch.empty([5 * batch_size, self.n_rhos, self.n_thetas], device=device)
#gradient_t = torch.empty([5 * batch_size, self.n_rhos, self.n_thetas], device=device)
#reference_angles = torch.empty([5 * batch_size], device=device)
#descs = torch.empty([5 * batch_size, (num_bins_gradient + num_bins_grid) * num_regions], device=device)
shape = all_soft_grids.shape
length_of_region = region_rows * region_columns
#bin_width = (2 * np.pi) / 36
for i in range(5):
my_input_feat = torch.unsqueeze(batch_input_feat[:, :, i], 2)
desc = self.inference(
my_input_feat,
batch_rho_coords,
batch_theta_coords,
batch_mask,
self.mu_rho[i],
self.sigma_rho[i],
self.mu_theta[i],
self.sigma_theta[i],
) # batch_size, n_gauss*1
all_soft_grids[i] = desc
'''
# soft grid and magnitudes
approx = torch.reshape(all_soft_grids, [shape[0] * shape[1], 80])
approx = torch.reshape(approx, [shape[0] * shape[1], n_rhos, n_thetas])
gradient_r = torch.gradient(approx, dim=1, edge_order=2)
gradient_t = torch.gradient(approx, dim=2, edge_order=2)
gradient_r = torch.cat(gradient_r)
gradient_t = torch.cat(gradient_t)
gradient_r = torch.reshape(gradient_r, [shape[0] * shape[1], n_rhos * n_thetas])
gradient_t = torch.reshape(gradient_t, [shape[0] * shape[1], n_rhos * n_thetas])
# Go through the input structure and compute the gradient for each row
for i, sample in enumerate(gradient_r):
# calculate magnitude and direction
# Gradient could divide by zero for these if input is zero
mag[i] = torch.sqrt(torch.square(gradient_t[i]) + torch.square(gradient_r[i]) + 1e-5)
direction[i] = torch.atan2(gradient_t[i], gradient_r[i] + 1e-5)
sample = torch.remainder(direction[i], 2 * np.pi)
histogram = self.hist(sample, bins=36, minimum=0, maximum=2*np.pi, sigma=.05, weights=mag[i])
max_bin = torch.argmax(histogram)
# For now
reference_angle = (max_bin * bin_width) - (bin_width / 2)
reference_angles[i] = reference_angle
output_all_grids = torch.reshape(all_soft_grids, (shape[0] * shape[1], num_regions, length_of_region))
output_all_mag = torch.reshape(mag, (shape[0] * shape[1], num_regions, length_of_region))
output_all_direction = torch.reshape(direction, (shape[0] * shape[1], num_regions, length_of_region))
'''
output_all_grids = torch.reshape(all_soft_grids, (shape[0] * shape[1], 5, 16))
# vectorize this
min_grid = torch.min(output_all_grids, dim=2)
max_grid = torch.max(output_all_grids, dim=2)
hist_grid = self.hist(output_all_grids, bins=num_bins_grid, minimum=torch.unsqueeze(min_grid[0], dim=2), maximum=torch.unsqueeze(max_grid[0], dim=2), sigma=.03, weights=output_all_grids)
'''
for i, features in enumerate(output_all_grids):
for j, region in enumerate(features):
# gradient histograms
output_all_direction[i][j] = torch.remainder(output_all_direction[i][j] - reference_angles[i], 2 * np.pi)
# Sometimes the grid is zero I dont know why
hist_gradient = self.hist(output_all_direction[i][j], bins=num_bins_gradient, minimum=0, maximum=2*np.pi, sigma=.2, weights=output_all_mag[i][j])
min_grid = torch.min(region)
max_grid = torch.max(region)
hist_grid = self.hist(region, bins=num_bins_grid, minimum=float(min_grid), maximum=float(max_grid), sigma=.2, weights=region)
hist_total = torch.cat((hist_gradient, hist_grid))
featvec.append(hist_total)
featvec = torch.cat(featvec)
descs[i] = featvec
featvec = []
'''
# Reshaping
feature_descs = torch.reshape(hist_grid, [shape[0], shape[1], (num_bins_gradient + num_bins_grid) * num_regions])
feat1, feat2, feat3, feat4, feat5 = feature_descs[0], feature_descs[1], feature_descs[2], feature_descs[3], feature_descs[4]
soft_grid_approx = torch.stack((feat1, feat2, feat3, feat4, feat5), dim=1)
soft_grid_approx = torch.reshape(
soft_grid_approx, [-1, num_regions * (num_bins_gradient + num_bins_grid) * 5]
)
batch_embedding = self.net(soft_grid_approx)
batch_embedding = nn.functional.normalize(batch_embedding, p=2, dim=1)
return batch_embedding
| [
"torch.empty",
"torch.cat",
"torch.arange",
"torch.nn.functional.normalize",
"torch.square",
"numpy.meshgrid",
"torch.multiply",
"torch.exp",
"torch.Tensor",
"numpy.linspace",
"torch.nn.Linear",
"torch.nn.Parameter",
"torch.max",
"torch.unsqueeze",
"torch.nn.init.ones_",
"torch.reshape... | [((534, 559), 'torch.nn.Parameter', 'nn.Parameter', (['self.mu_rho'], {}), '(self.mu_rho)\n', (546, 559), False, 'from torch import nn, optim\n'), ((642, 677), 'torch.nn.init.ones_', 'torch.nn.init.ones_', (['self.sigma_rho'], {}), '(self.sigma_rho)\n', (661, 677), False, 'import torch\n'), ((750, 777), 'torch.nn.Parameter', 'nn.Parameter', (['self.mu_theta'], {}), '(self.mu_theta)\n', (762, 777), False, 'from torch import nn, optim\n'), ((862, 899), 'torch.nn.init.ones_', 'torch.nn.init.ones_', (['self.sigma_theta'], {}), '(self.sigma_theta)\n', (881, 899), False, 'import torch\n'), ((923, 961), 'torch.nn.Linear', 'nn.Linear', (['descriptor_size', 'hidden_dim'], {}), '(descriptor_size, hidden_dim)\n', (932, 961), False, 'from torch import nn, optim\n'), ((971, 1018), 'torch.nn.init.xavier_normal_', 'torch.nn.init.xavier_normal_', (['self.feat1.weight'], {}), '(self.feat1.weight)\n', (999, 1018), False, 'import torch\n'), ((1042, 1080), 'torch.nn.Linear', 'nn.Linear', (['descriptor_size', 'hidden_dim'], {}), '(descriptor_size, hidden_dim)\n', (1051, 1080), False, 'from torch import nn, optim\n'), ((1090, 1137), 'torch.nn.init.xavier_normal_', 'torch.nn.init.xavier_normal_', (['self.feat2.weight'], {}), '(self.feat2.weight)\n', (1118, 1137), False, 'import torch\n'), ((1169, 1207), 'torch.nn.Linear', 'nn.Linear', (['descriptor_size', 'hidden_dim'], {}), '(descriptor_size, hidden_dim)\n', (1178, 1207), False, 'from torch import nn, optim\n'), ((1217, 1264), 'torch.nn.init.xavier_normal_', 'torch.nn.init.xavier_normal_', (['self.feat3.weight'], {}), '(self.feat3.weight)\n', (1245, 1264), False, 'import torch\n'), ((1296, 1334), 'torch.nn.Linear', 'nn.Linear', (['descriptor_size', 'hidden_dim'], {}), '(descriptor_size, hidden_dim)\n', (1305, 1334), False, 'from torch import nn, optim\n'), ((1345, 1392), 'torch.nn.init.xavier_normal_', 'torch.nn.init.xavier_normal_', (['self.feat4.weight'], {}), '(self.feat4.weight)\n', (1373, 1392), False, 'import torch\n'), ((1424, 1462), 'torch.nn.Linear', 'nn.Linear', (['descriptor_size', 'hidden_dim'], {}), '(descriptor_size, hidden_dim)\n', (1433, 1462), False, 'from torch import nn, optim\n'), ((1473, 1520), 'torch.nn.init.xavier_normal_', 'torch.nn.init.xavier_normal_', (['self.feat5.weight'], {}), '(self.feat5.weight)\n', (1501, 1520), False, 'import torch\n'), ((1548, 1588), 'torch.nn.Linear', 'nn.Linear', (['(hidden_dim * 5)', 'embedding_dim'], {}), '(hidden_dim * 5, embedding_dim)\n', (1557, 1588), False, 'from torch import nn, optim\n'), ((1598, 1649), 'torch.nn.init.xavier_normal_', 'torch.nn.init.xavier_normal_', (['self.embedding.weight'], {}), '(self.embedding.weight)\n', (1626, 1649), False, 'import torch\n'), ((1701, 1719), 'torch.nn.LeakyReLU', 'nn.LeakyReLU', (['(0.01)'], {}), '(0.01)\n', (1713, 1719), False, 'from torch import nn, optim\n'), ((1852, 1912), 'numpy.linspace', 'np.linspace', (['range_rho[0]', 'range_rho[1]'], {'num': '(self.n_rhos + 1)'}), '(range_rho[0], range_rho[1], num=self.n_rhos + 1)\n', (1863, 1912), True, 'import numpy as np\n'), ((1966, 2032), 'numpy.linspace', 'np.linspace', (['range_theta[0]', 'range_theta[1]'], {'num': '(self.n_thetas + 1)'}), '(range_theta[0], range_theta[1], num=self.n_thetas + 1)\n', (1977, 2032), True, 'import numpy as np\n'), ((2104, 2151), 'numpy.meshgrid', 'np.meshgrid', (['grid_rho', 'grid_theta'], {'sparse': '(False)'}), '(grid_rho, grid_theta, sparse=False)\n', (2115, 2151), True, 'import numpy as np\n'), ((2516, 2582), 'numpy.concatenate', 'np.concatenate', (['(grid_rho_[None, :], grid_theta_[None, :])'], {'axis': '(0)'}), '((grid_rho_[None, :], grid_theta_[None, :]), axis=0)\n', (2530, 2582), True, 'import numpy as np\n'), ((2742, 2765), 'torch.empty', 'torch.empty', (['[5, 1, 80]'], {}), '([5, 1, 80])\n', (2753, 2765), False, 'import torch\n'), ((3094, 3117), 'torch.empty', 'torch.empty', (['[5, 1, 80]'], {}), '([5, 1, 80])\n', (3105, 3117), False, 'import torch\n'), ((3679, 3708), 'torch.unsqueeze', 'torch.unsqueeze', (['delta'], {'dim': '(3)'}), '(delta, dim=3)\n', (3694, 3708), False, 'import torch\n'), ((3811, 3842), 'torch.unsqueeze', 'torch.unsqueeze', (['weights'], {'dim': '(2)'}), '(weights, dim=2)\n', (3826, 3842), False, 'import torch\n'), ((4337, 4371), 'torch.reshape', 'torch.reshape', (['rho_coords', '[-1, 1]'], {}), '(rho_coords, [-1, 1])\n', (4350, 4371), False, 'import torch\n'), ((4422, 4458), 'torch.reshape', 'torch.reshape', (['theta_coords', '[-1, 1]'], {}), '(theta_coords, [-1, 1])\n', (4435, 4458), False, 'import torch\n'), ((5838, 5881), 'torch.multiply', 'torch.multiply', (['rho_coords_', 'thetas_coords_'], {}), '(rho_coords_, thetas_coords_)\n', (5852, 5881), False, 'import torch\n'), ((5978, 6039), 'torch.reshape', 'torch.reshape', (['gauss_activations', '[n_samples, n_vertices, -1]'], {}), '(gauss_activations, [n_samples, n_vertices, -1])\n', (5991, 6039), False, 'import torch\n'), ((6137, 6176), 'torch.multiply', 'torch.multiply', (['gauss_activations', 'mask'], {}), '(gauss_activations, mask)\n', (6151, 6176), False, 'import torch\n'), ((6498, 6535), 'torch.unsqueeze', 'torch.unsqueeze', (['gauss_activations', '(2)'], {}), '(gauss_activations, 2)\n', (6513, 6535), False, 'import torch\n'), ((6631, 6661), 'torch.unsqueeze', 'torch.unsqueeze', (['input_feat', '(3)'], {}), '(input_feat, 3)\n', (6646, 6661), False, 'import torch\n'), ((6755, 6801), 'torch.multiply', 'torch.multiply', (['gauss_activations', 'input_feat_'], {}), '(gauss_activations, input_feat_)\n', (6769, 6801), False, 'import torch\n'), ((6901, 6925), 'torch.sum', 'torch.sum', (['gauss_desc', '(1)'], {}), '(gauss_desc, 1)\n', (6910, 6925), False, 'import torch\n'), ((6983, 7050), 'torch.reshape', 'torch.reshape', (['gauss_desc', '[n_samples, self.n_thetas * self.n_rhos]'], {}), '(gauss_desc, [n_samples, self.n_thetas * self.n_rhos])\n', (6996, 7050), False, 'import torch\n'), ((7813, 7876), 'torch.cat', 'torch.cat', (['(output1, output2, output3, output4, output5)'], {'dim': '(1)'}), '((output1, output2, output3, output4, output5), dim=1)\n', (7822, 7876), False, 'import torch\n'), ((8436, 8483), 'torch.empty', 'torch.empty', (['[5, batch_size, 80]'], {'device': 'device'}), '([5, batch_size, 80], device=device)\n', (8447, 8483), False, 'import torch\n'), ((11431, 11490), 'torch.reshape', 'torch.reshape', (['all_soft_grids', '(shape[0] * shape[1], 5, 16)'], {}), '(all_soft_grids, (shape[0] * shape[1], 5, 16))\n', (11444, 11490), False, 'import torch\n'), ((11536, 11570), 'torch.min', 'torch.min', (['output_all_grids'], {'dim': '(2)'}), '(output_all_grids, dim=2)\n', (11545, 11570), False, 'import torch\n'), ((11590, 11624), 'torch.max', 'torch.max', (['output_all_grids'], {'dim': '(2)'}), '(output_all_grids, dim=2)\n', (11599, 11624), False, 'import torch\n'), ((12858, 12959), 'torch.reshape', 'torch.reshape', (['hist_grid', '[shape[0], shape[1], (num_bins_gradient + num_bins_grid) * num_regions]'], {}), '(hist_grid, [shape[0], shape[1], (num_bins_gradient +\n num_bins_grid) * num_regions])\n', (12871, 12959), False, 'import torch\n'), ((13117, 13172), 'torch.stack', 'torch.stack', (['(feat1, feat2, feat3, feat4, feat5)'], {'dim': '(1)'}), '((feat1, feat2, feat3, feat4, feat5), dim=1)\n', (13128, 13172), False, 'import torch\n'), ((13200, 13296), 'torch.reshape', 'torch.reshape', (['soft_grid_approx', '[-1, num_regions * (num_bins_gradient + num_bins_grid) * 5]'], {}), '(soft_grid_approx, [-1, num_regions * (num_bins_gradient +\n num_bins_grid) * 5])\n', (13213, 13296), False, 'import torch\n'), ((13395, 13447), 'torch.nn.functional.normalize', 'nn.functional.normalize', (['batch_embedding'], {'p': '(2)', 'dim': '(1)'}), '(batch_embedding, p=2, dim=1)\n', (13418, 13447), False, 'from torch import nn, optim\n'), ((2984, 3012), 'torch.Tensor', 'torch.Tensor', (['mu_rho_initial'], {}), '(mu_rho_initial)\n', (2996, 3012), False, 'import torch\n'), ((3340, 3370), 'torch.Tensor', 'torch.Tensor', (['mu_theta_initial'], {}), '(mu_theta_initial)\n', (3352, 3370), False, 'import torch\n'), ((3611, 3632), 'torch.unsqueeze', 'torch.unsqueeze', (['x', '(2)'], {}), '(x, 2)\n', (3626, 3632), False, 'import torch\n'), ((3635, 3662), 'torch.unsqueeze', 'torch.unsqueeze', (['centers', '(3)'], {}), '(centers, 3)\n', (3650, 3662), False, 'import torch\n'), ((9195, 9240), 'torch.unsqueeze', 'torch.unsqueeze', (['batch_input_feat[:, :, i]', '(2)'], {}), '(batch_input_feat[:, :, i], 2)\n', (9210, 9240), False, 'import torch\n'), ((2852, 2891), 'numpy.expand_dims', 'np.expand_dims', (['initial_coords[:, 0]', '(0)'], {}), '(initial_coords[:, 0], 0)\n', (2866, 2891), True, 'import numpy as np\n'), ((3206, 3245), 'numpy.expand_dims', 'np.expand_dims', (['initial_coords[:, 1]', '(0)'], {}), '(initial_coords[:, 1], 0)\n', (3220, 3245), True, 'import numpy as np\n'), ((3724, 3761), 'torch.exp', 'torch.exp', (['(-0.5 * (hist / sigma) ** 2)'], {}), '(-0.5 * (hist / sigma) ** 2)\n', (3733, 3761), False, 'import torch\n'), ((6359, 6405), 'torch.sum', 'torch.sum', (['gauss_activations', '(1)'], {'keepdims': '(True)'}), '(gauss_activations, 1, keepdims=True)\n', (6368, 6405), False, 'import torch\n'), ((11701, 11736), 'torch.unsqueeze', 'torch.unsqueeze', (['min_grid[0]'], {'dim': '(2)'}), '(min_grid[0], dim=2)\n', (11716, 11736), False, 'import torch\n'), ((11746, 11781), 'torch.unsqueeze', 'torch.unsqueeze', (['max_grid[0]'], {'dim': '(2)'}), '(max_grid[0], dim=2)\n', (11761, 11781), False, 'import torch\n'), ((600, 623), 'torch.empty', 'torch.empty', (['[5, 1, 80]'], {}), '([5, 1, 80])\n', (611, 623), False, 'import torch\n'), ((820, 843), 'torch.empty', 'torch.empty', (['[5, 1, 80]'], {}), '([5, 1, 80])\n', (831, 843), False, 'import torch\n'), ((3552, 3587), 'torch.arange', 'torch.arange', (['bins'], {'device': '"""cuda:0"""'}), "(bins, device='cuda:0')\n", (3564, 3587), False, 'import torch\n'), ((3767, 3785), 'numpy.sqrt', 'np.sqrt', (['(np.pi * 2)'], {}), '(np.pi * 2)\n', (3774, 3785), True, 'import numpy as np\n'), ((5575, 5609), 'torch.square', 'torch.square', (['(rho_coords_ - mu_rho)'], {}), '(rho_coords_ - mu_rho)\n', (5587, 5609), False, 'import torch\n'), ((5613, 5636), 'torch.square', 'torch.square', (['sigma_rho'], {}), '(sigma_rho)\n', (5625, 5636), False, 'import torch\n'), ((5715, 5754), 'torch.square', 'torch.square', (['(thetas_coords_ - mu_theta)'], {}), '(thetas_coords_ - mu_theta)\n', (5727, 5754), False, 'import torch\n'), ((5758, 5783), 'torch.square', 'torch.square', (['sigma_theta'], {}), '(sigma_theta)\n', (5770, 5783), False, 'import torch\n')] |
# coding: utf-8
# /*##########################################################################
#
# Copyright (c) 2015-2017 European Synchrotron Radiation Facility
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# ###########################################################################*/
from __future__ import absolute_import
__authors__ = ["<NAME>"]
__license__ = "MIT"
__date__ = "15/09/2016"
import numpy as np
from silx.gui import qt as Qt
from xsocs.io.FitH5 import FitH5, FitH5QAxis
from ....process.fitresults import FitStatus
from ...widgets.XsocsPlot2D import XsocsPlot2D
class DropPlotWidget(XsocsPlot2D):
sigSelected = Qt.Signal(object)
def __init__(self, *args, **kwargs):
super(DropPlotWidget, self).__init__(*args, **kwargs)
self.__legend = None
self.setActiveCurveHandling(False)
self.setKeepDataAspectRatio(True)
self.setAcceptDrops(True)
self.setPointSelectionEnabled(True)
self.setShowMousePosition(True)
def dropEvent(self, event):
mimeData = event.mimeData()
if not mimeData.hasFormat('application/FitModel'):
return super(DropPlotWidget, self).dropEvent(event)
qByteArray = mimeData.data('application/FitModel')
stream = Qt.QDataStream(qByteArray, Qt.QIODevice.ReadOnly)
h5File = stream.readQString()
entry = stream.readQString()
q_axis = stream.readInt()
type = stream.readQString()
if type == 'result':
process = stream.readQString()
result = stream.readQString()
self.plotFitResult(h5File, entry, process, result, q_axis)
elif type == 'status':
self.plotFitStatus(h5File, entry, q_axis)
def dragEnterEvent(self, event):
# super(DropWidget, self).dragEnterEvent(event)
if event.mimeData().hasFormat('application/FitModel'):
event.acceptProposedAction()
def dragLeaveEvent(self, event):
super(DropPlotWidget, self).dragLeaveEvent(event)
def dragMoveEvent(self, event):
super(DropPlotWidget, self).dragMoveEvent(event)
def plotFitResult(self, fitH5Name, entry, process, result, q_axis):
with FitH5(fitH5Name) as h5f:
data = h5f.get_axis_result(entry, process, result, q_axis)
scan_x = h5f.scan_x(entry)
scan_y = h5f.scan_y(entry)
xBorder = np.array([scan_x.min(), scan_x.max()])
yBorder = np.array([scan_y.min(), scan_y.max()])
self.addCurve(xBorder,
yBorder,
linestyle=' ',
symbol='.',
color='white',
legend='__border',
z=-1)
self.__legend = self.setPlotData(scan_x, scan_y, data)
self.setGraphTitle(result + '[' + FitH5QAxis.axis_names[q_axis] + ']')
def plotFitStatus(self, fitH5Name, entry, q_axis):
with FitH5(fitH5Name) as h5f:
data = h5f.get_status(entry, q_axis)
errorPts = np.where(data != FitStatus.OK)[0]
if len(errorPts) == 0:
return
scan_x = h5f.scan_x(entry)[errorPts]
scan_y = h5f.scan_y(entry)[errorPts]
data = data[errorPts]
self.__legend = self.setPlotData(scan_x, scan_y,
data, dataIndices=errorPts)
self.setGraphTitle('Errors[qx]' + FitH5QAxis.axis_names[q_axis])
if __name__ == '__main__':
pass
| [
"silx.gui.qt.Signal",
"xsocs.io.FitH5.FitH5",
"numpy.where",
"silx.gui.qt.QDataStream"
] | [((1657, 1674), 'silx.gui.qt.Signal', 'Qt.Signal', (['object'], {}), '(object)\n', (1666, 1674), True, 'from silx.gui import qt as Qt\n'), ((2281, 2330), 'silx.gui.qt.QDataStream', 'Qt.QDataStream', (['qByteArray', 'Qt.QIODevice.ReadOnly'], {}), '(qByteArray, Qt.QIODevice.ReadOnly)\n', (2295, 2330), True, 'from silx.gui import qt as Qt\n'), ((3222, 3238), 'xsocs.io.FitH5.FitH5', 'FitH5', (['fitH5Name'], {}), '(fitH5Name)\n', (3227, 3238), False, 'from xsocs.io.FitH5 import FitH5, FitH5QAxis\n'), ((3962, 3978), 'xsocs.io.FitH5.FitH5', 'FitH5', (['fitH5Name'], {}), '(fitH5Name)\n', (3967, 3978), False, 'from xsocs.io.FitH5 import FitH5, FitH5QAxis\n'), ((4059, 4089), 'numpy.where', 'np.where', (['(data != FitStatus.OK)'], {}), '(data != FitStatus.OK)\n', (4067, 4089), True, 'import numpy as np\n')] |
import numpy as np
from scipy.special import erfinv
def std_from_equipment(tolerance=0.1, probability=0.95):
"""
Converts tolerance `tolerance` for precision of measurement
equipment to a standard deviation, scaling so that
(100`probability`) percent of measurements are within `tolerance`.
A mean of zero is assumed. `erfinv` is imported from `scipy.special`
"""
standard_deviation = tolerance / (erfinv(probability) * np.sqrt(2))
return standard_deviation
def transform_linear_map(operator, data, std):
"""
Takes a linear map `operator` of size (len(data), dim_input)
or (1, dim_input) for repeated observations, along with
a vector `data` representing observations. It is assumed
that `data` is formed with `M@truth + sigma` where `sigma ~ N(0, std)`
This then transforms it to the MWE form expected by the DCI framework.
It returns a matrix `A` of shape (1, dim_input) and np.float `b`
and transforms it to the MWE form expected by the DCI framework.
>>> X = np.ones((10, 2))
>>> x = np.array([0.5, 0.5]).reshape(-1, 1)
>>> std = 1
>>> d = X @ x
>>> A, b = transform_linear_map(X, d, std)
>>> np.linalg.norm(A @ x + b)
0.0
>>> A, b = transform_linear_map(X, d, [std]*10)
>>> np.linalg.norm(A @ x + b)
0.0
>>> A, b = transform_linear_map(np.array([[1, 1]]), d, std)
>>> np.linalg.norm(A @ x + b)
0.0
>>> A, b = transform_linear_map(np.array([[1, 1]]), d, [std]*10)
Traceback (most recent call last):
...
ValueError: For repeated measurements, pass a float for std
"""
if isinstance(data, np.ndarray):
data = data.ravel()
num_observations = len(data)
if operator.shape[0] > 1: # if not repeated observations
assert (
operator.shape[0] == num_observations
), f"Operator shape mismatch, op={operator.shape}, obs={num_observations}"
if isinstance(std, (float, int)):
std = np.array([std] * num_observations)
if isinstance(std, (list, tuple)):
std = np.array(std)
assert len(std) == num_observations, "Standard deviation shape mismatch"
assert 0 not in np.round(std, 14), "Std must be > 1E-14"
D = np.diag(1.0 / (std * np.sqrt(num_observations)))
A = np.sum(D @ operator, axis=0)
else:
if isinstance(std, (list, tuple, np.ndarray)):
raise ValueError("For repeated measurements, pass a float for std")
assert std > 1e-14, "Std must be > 1E-14"
A = np.sqrt(num_observations) / std * operator
b = -1.0 / np.sqrt(num_observations) * np.sum(np.divide(data, std))
return A, b
def transform_linear_setup(operator_list, data_list, std_list):
if isinstance(std_list, (float, int)):
std_list = [std_list] * len(data_list)
# repeat process for multiple quantities of interest
results = [
transform_linear_map(o, d, s)
for o, d, s in zip(operator_list, data_list, std_list)
]
operators = [r[0] for r in results]
datas = [r[1] for r in results]
return np.vstack(operators), np.vstack(datas)
def null_space(A, rcond=None):
"""
Construct an orthonormal basis for the null space of A using SVD
Method is slight modification of ``scipy.linalg``
Parameters
----------
A : (M, N) array_like
Input array
rcond : float, optional
Relative condition number. Singular values ``s`` smaller than
``rcond * max(s)`` are considered zero.
Default: floating point eps * max(M,N).
Returns
-------
Z : (N, K) ndarray
Orthonormal basis for the null space of A.
K = dimension of effective null space, as determined by rcond
Examples
--------
One-dimensional null space:
>>> import numpy as np
>>> from mud.util import null_space
>>> A = np.array([[1, 1], [1, 1]])
>>> ns = null_space(A)
>>> ns * np.sign(ns[0,0]) # Remove the sign ambiguity of the vector
array([[ 0.70710678],
[-0.70710678]])
Two-dimensional null space:
>>> B = np.random.rand(3, 5)
>>> Z = null_space(B)
>>> Z.shape
(5, 2)
>>> np.allclose(B.dot(Z), 0)
True
The basis vectors are orthonormal (up to rounding error):
>>> np.allclose(Z.T.dot(Z), np.eye(2))
True
"""
u, s, vh = np.linalg.svd(A, full_matrices=True)
M, N = u.shape[0], vh.shape[1]
if rcond is None:
rcond = np.finfo(s.dtype).eps * max(M, N)
tol = np.amax(s) * rcond
num = np.sum(s > tol, dtype=int)
Q = vh[num:, :].T.conj()
return Q
| [
"numpy.divide",
"numpy.sum",
"scipy.special.erfinv",
"numpy.amax",
"numpy.finfo",
"numpy.linalg.svd",
"numpy.array",
"numpy.round",
"numpy.vstack",
"numpy.sqrt"
] | [((4371, 4407), 'numpy.linalg.svd', 'np.linalg.svd', (['A'], {'full_matrices': '(True)'}), '(A, full_matrices=True)\n', (4384, 4407), True, 'import numpy as np\n'), ((4554, 4580), 'numpy.sum', 'np.sum', (['(s > tol)'], {'dtype': 'int'}), '(s > tol, dtype=int)\n', (4560, 4580), True, 'import numpy as np\n'), ((2314, 2342), 'numpy.sum', 'np.sum', (['(D @ operator)'], {'axis': '(0)'}), '(D @ operator, axis=0)\n', (2320, 2342), True, 'import numpy as np\n'), ((3105, 3125), 'numpy.vstack', 'np.vstack', (['operators'], {}), '(operators)\n', (3114, 3125), True, 'import numpy as np\n'), ((3127, 3143), 'numpy.vstack', 'np.vstack', (['datas'], {}), '(datas)\n', (3136, 3143), True, 'import numpy as np\n'), ((4525, 4535), 'numpy.amax', 'np.amax', (['s'], {}), '(s)\n', (4532, 4535), True, 'import numpy as np\n'), ((428, 447), 'scipy.special.erfinv', 'erfinv', (['probability'], {}), '(probability)\n', (434, 447), False, 'from scipy.special import erfinv\n'), ((450, 460), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (457, 460), True, 'import numpy as np\n'), ((1985, 2019), 'numpy.array', 'np.array', (['([std] * num_observations)'], {}), '([std] * num_observations)\n', (1993, 2019), True, 'import numpy as np\n'), ((2081, 2094), 'numpy.array', 'np.array', (['std'], {}), '(std)\n', (2089, 2094), True, 'import numpy as np\n'), ((2200, 2217), 'numpy.round', 'np.round', (['std', '(14)'], {}), '(std, 14)\n', (2208, 2217), True, 'import numpy as np\n'), ((2609, 2634), 'numpy.sqrt', 'np.sqrt', (['num_observations'], {}), '(num_observations)\n', (2616, 2634), True, 'import numpy as np\n'), ((2644, 2664), 'numpy.divide', 'np.divide', (['data', 'std'], {}), '(data, std)\n', (2653, 2664), True, 'import numpy as np\n'), ((2550, 2575), 'numpy.sqrt', 'np.sqrt', (['num_observations'], {}), '(num_observations)\n', (2557, 2575), True, 'import numpy as np\n'), ((4481, 4498), 'numpy.finfo', 'np.finfo', (['s.dtype'], {}), '(s.dtype)\n', (4489, 4498), True, 'import numpy as np\n'), ((2274, 2299), 'numpy.sqrt', 'np.sqrt', (['num_observations'], {}), '(num_observations)\n', (2281, 2299), True, 'import numpy as np\n')] |
import sys
from sysconfig import get_path
from setuptools import setup, find_namespace_packages, Extension
from setuptools.command.build_ext import build_ext
from frds import (
__version__,
__description__,
__author__,
__author_email__,
__github_url__,
)
try:
import numpy
except ImportError:
print("Numpy needs to be installed.")
sys.exit(1)
if sys.platform in ("linux", "linux2"):
# linux
extra_compile_args = ["-std=c++17", "-lstdc++"]
elif sys.platform == "darwin":
# OS X
extra_compile_args = ["-std=c++17", "-lstdc++"]
elif sys.platform == "win32":
# Windows
extra_compile_args = ["/O2", "/std:c++17"]
requires = [
"scipy",
"pandas",
"sqlalchemy",
"psycopg2-binary",
"fredapi",
]
mod_isolation_forest = Extension(
"frds.algorithms.isolation_forest.iforest_ext",
include_dirs=[get_path("platinclude"), numpy.get_include()],
sources=[
"frds/algorithms/isolation_forest/src/iforest_module.cpp",
],
extra_compile_args=extra_compile_args,
language="c++",
)
mod_trth_parser = Extension(
"frds.mktstructure.trth_parser",
include_dirs=[get_path("platinclude")],
sources=["frds/mktstructure/trth_parser.c"],
language="c",
)
with open("README.md", "r", encoding="utf-8") as f:
README = f.read()
setup(
name="frds",
version=__version__,
description=__description__,
long_description=README,
long_description_content_type="text/markdown",
author=__author__,
author_email=__author_email__,
url=__github_url__,
packages=find_namespace_packages(),
package_data={
"": ["LICENSE", "README.md", "*.cpp", "*.hpp", "*.c"],
},
entry_points={"console_scripts": ["frds-mktstructure=frds.mktstructure.main:main"]},
install_requires=requires,
classifiers=[
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.8",
"Intended Audience :: End Users/Desktop",
"Intended Audience :: Financial and Insurance Industry",
"Intended Audience :: Education",
"Intended Audience :: Science/Research",
"Topic :: Scientific/Engineering :: Information Analysis",
],
license="MIT",
ext_modules=[
mod_isolation_forest,
mod_trth_parser,
],
cmdclass={"build_ext": build_ext},
)
| [
"setuptools.find_namespace_packages",
"numpy.get_include",
"sys.exit",
"sysconfig.get_path"
] | [((366, 377), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (374, 377), False, 'import sys\n'), ((1586, 1611), 'setuptools.find_namespace_packages', 'find_namespace_packages', ([], {}), '()\n', (1609, 1611), False, 'from setuptools import setup, find_namespace_packages, Extension\n'), ((872, 895), 'sysconfig.get_path', 'get_path', (['"""platinclude"""'], {}), "('platinclude')\n", (880, 895), False, 'from sysconfig import get_path\n'), ((897, 916), 'numpy.get_include', 'numpy.get_include', ([], {}), '()\n', (914, 916), False, 'import numpy\n'), ((1157, 1180), 'sysconfig.get_path', 'get_path', (['"""platinclude"""'], {}), "('platinclude')\n", (1165, 1180), False, 'from sysconfig import get_path\n')] |
import numpy as np
import scipy
import scipy.optimize
from . import units, utils
def center(coordinates, masses):
"""
Given coordinates and masses, return coordinates with center of mass at 0.
Also works to remove COM translational motion.
Args:
coordinates ({nparticle, ndim} ndarray): xyz (to compute COM) or velocities (COM velocity)
masses ({nparticle,} array_like): masses
Returns:
centered_coordinates ({nparticle, ndim} ndarray): xyz with COM at origin or velocities with COM velocity removed
"""
com_coordinates = utils.compute_center_of_mass(coordinates, masses)
new_coordinates = np.array(coordinates) - com_coordinates
return new_coordinates
def angular_momentum_components(coordinates, velocities, masses):
"""
Computes the minimal change in 3D momentum vectors to remove the angular
momentum by solving
min. || \Delta p ||^2_2
s.t. x \cross (p + \Delta p) = 0
Args:
coordinates ({nparticle, 3} ndarray): xyz coordinates
velocities ({nparticle, 3} ndarray): particle velocities
masses ({nparticle,} array_like): masses
Returns:
dv ({nparticle, 3} ndarray): minimal perturbation to velocities that have no angular momentum, such that v + dv has no angular momentum
"""
mass_r = np.reshape(masses, (-1, 1))
linear_momentum = velocities * mass_r
angular_constraint_mat = np.reshape(np.transpose(utils.cross_product_matrix(coordinates), (1, 0, 2)), (3, -1)) # 3 x (N x 3)
constraint_vec = - np.dot(angular_constraint_mat, np.reshape(linear_momentum, (-1, 1))) # 3 x 1
dp = np.linalg.lstsq(angular_constraint_mat, constraint_vec, rcond=None)[0]
dv = np.reshape(dp, (-1, 3)) / mass_r
return dv
def initialize_centered(coordinates, velocities, masses):
"""
Initialize coordinates to have COM at the origin and velocities to have COM
translation and angular momentum removed by minimizing
min. || \Delta p ||^2_2
s.t. x \cross (p + \Delta p) = 0
\sum_i (p_i + \Delta p_i) = 0
\sum_i x_i m_i = 0
Args:
coordinates ({nparticle, 3} ndarray): particle coordinates
velocities ({nparticle, 3} ndarray): particle velocities
masses ({nparticle,} array_like): masses
Returns:
centered_coordinates ({nparticle, 3} ndarray): particle coordinates
centered_velocities ({nparticle, 3} ndarray): particle velocities
"""
center_coordinates = center(coordinates, masses)
center_velocities = center(velocities, masses)
mass_r = np.reshape(masses, (-1, 1))
linear_momentum = center_velocities * mass_r
linear_constraint_mat = np.hstack([np.eye(3) for i in range(np.shape(center_coordinates)[0])]) # 3 x (N x 3)
angular_constraint_mat = np.reshape(np.transpose(utils.cross_product_matrix(center_coordinates), (1, 0, 2)), (3, -1)) # 3 x (N x 3)
total_constraint_mat = np.vstack([linear_constraint_mat, angular_constraint_mat]) # 6 x (N x 3)
constraint_vec = - np.dot(total_constraint_mat, np.reshape(linear_momentum, (-1, 1))) # 6 x 1
dp = np.linalg.lstsq(total_constraint_mat, constraint_vec, rcond=None)[0]
dv = np.reshape(dp, (-1, 3)) / mass_r
center_velocities = center_velocities + dv
return center_coordinates, center_velocities
def rescale_velocity(velocities, masses, kT):
"""
Rescale velocities to correspond to a specific temperature.
Args:
velocities ({nparticle, ndim} ndarray): particle velocities
masses ({nparticle,} ndarray): particle masses
kT (float): Temperature in energy units
Returns:
rescaled_velocities ({nparticle, ndim} ndarray): particle velocities after scaling to target kT
"""
alpha = np.sqrt(kT / utils.compute_temperature(velocities, masses))
rescaled_velocities = velocities * alpha
return rescaled_velocities
def boltzmann(kT, masses, dim=3, recenter=True):
"""
Take sample in dim dimensions for each masses at each temperature.
Args:
kT (float): Temperature in energy units
masses ({nparticle,} ndarray): particle masses
dim (int): number of dimensions to sample
recenter (bool): True to remove center of mass motion
Returns:
velocities ({nparticle, ndim} ndarray): particle velocities sampled from boltzmann distribution at energy kT
"""
mass_r = np.reshape(masses, (-1, 1))
factor = np.sqrt(kT/mass_r)
velocities = np.random.normal(scale=factor, size=(mass_r.shape[0], dim))
if recenter:
velocities = center(velocities, mass_r)
return velocities
def sin_velocity(masses, Qs, kT):
"""
Samples velocities and auxiliary velocities from Boltzmann distribution and then rescales the joint velocity and auxiliary velocity to fit the isokinetic Nose Hoover constraint.
Args:
masses ({nparticle,} ndarray): masses of nonauxiliary dofs
Qs ({2, L, nparticle, ndim} ndarray): auxiliary masses
kT (float): temperature in energy units
Returns:
({nparticle, ndim} ndarray, {2, L, nparticle, ndim} ndarray): tuple of velocity and auxiliary velocity arrays
"""
_, Lint, natom, ndim = np.shape(Qs)
factor = np.sqrt(kT/Qs)
velocities = boltzmann(kT, masses, dim=ndim)
aux_v = np.random.normal(scale=factor)
L = float(Lint)
for i in range(natom):
for a in range(ndim):
v = np.concatenate((velocities[i, a], aux_v[0, :, i, a]), axis=None)
m = np.concatenate((masses[i] / L, 1.0/(L+1.0)*Qs[0, :, i, a]), axis=None)
curr_kT = np.sum(v**2 * m)
alpha = np.sqrt(kT / curr_kT)
velocities[i, a] *= alpha
aux_v[0, :, i, a] *= alpha
Lhalf = Lint//2
# The first aux velocity should not change sign during dynamics, so we
# initialize half of them to each sign (if there are an even number of them)
if Lhalf*2 == Lint:
aux_v[0, :Lhalf, :, :] = np.abs(aux_v[0, :Lhalf, :, :])
aux_v[0, Lhalf:, :, :] = -np.abs(aux_v[0, Lhalf:, :, :])
return velocities, aux_v
def boltzmann_range(kT, masses, ppf_range):
"""
Take single sample of the Boltzmann distribution within a probability range.
Args:
kT (float): Temperature in energy units
masses ({nparticle,} ndarray): particle masses
ppf_range ({2, nparticle} array_like): percent range to sample in probability distribution
Returns:
speeds ({nparticle,} ndarray): speeds sampled from boltzmann distribution in given probability range
"""
ppf = np.random.uniform(ppf_range[0], ppf_range[1])
factor = np.sqrt(kT/masses)
sample = scipy.stats.maxwell.ppf(ppf, scale=factor)
return sample
def bimol(
coordinates1,
coordinates2,
masses1,
masses2,
impact_kT=10000.0 * units.K_TO_AU,
vibration_kT=600.0 * units.K_TO_AU,
nosc=100,
freq=3000.0 * units.INV_CM_TO_AU,
impact_ppf_range=(0.4,0.6),
tolerance=4.0,
):
"""
Function to go from two molecular coordinates to a total configuration for bimolecular collision
Args:
coordinates1 ({nparticle1, 3} ndarray): coordinates of molecule 1
coordinates2 ({nparticle2, 3} ndarray): coordinates of molecule 2
masses1 ({nparticle1,} ndarray): masses of atoms in molecule 1
masses2 ({nparticle2,} ndarray): masses of atoms in molecule 2
impact_kT (float): temperature at which to sample the impact in energy units
vibration_kT (float): temperature at which to sample molecular vibrations in energy units
nosc (float): number of oscillations at given frequency, used to compute distance
freq (float): vibrational frequency to use in energy units
impact_ppf_range ({2,} array_like): percents to sample of Boltzmann cumulative distribution function for impact velocity
tolerance (float): minimum usable distance between two molecules
Returns:
coordinates_tot ({nparticle1+nparticle2, 3} ndarray): coordinates of two molecules randomly rotated, separated on x axis
velocities_tot ({nparticle1+nparticle2, 3} ndarray): velocities drawn from boltzmann distributions pointed at one another on x axis
"""
# Convert to atomic units
mass_tot = np.concatenate([masses1, masses2])
natom1 = len(masses1)
natom2 = len(masses2)
# Get randomly rotated molecules
coordinates1_rot = np.dot(center(coordinates1, masses1), utils.random_rotation_matrix())
coordinates2_rot = np.dot(center(coordinates2, masses2), utils.random_rotation_matrix())
# View each molecule as rigid body of their own mass at the given temperature,
# sample boltzmann distribution of velocities within given percentage bounds
sample_velocities1 = boltzmann_range(impact_kT, np.sum(masses1), impact_ppf_range)
sample_velocities2 = boltzmann_range(impact_kT, np.sum(masses2), impact_ppf_range)
speed_tot = sample_velocities1 + sample_velocities2
# Compute time to impact based on number of oscillations at the given frequency
impact_time = nosc / freq
# Use velocities and time to impact to compute minimal distance
impact_dist = speed_tot * impact_time
# Place first molecule with center of mass zero, second molecule on 1d line with minimal distance
min_dist = impact_dist + np.max(coordinates1_rot[:, 0]) - np.min(coordinates2_rot[:, 0])
coordinates2_rot[:, 0] = coordinates2_rot[:, 0] + min_dist
# Ensure molecules are beyond tolerance
while np.min(utils.pairwise_dist(coordinates1_rot, coordinates2_rot)) < tolerance:
coordinates2_rot[:, 0] += 0.2
# Construct total coordinate matrix, center total mass at zero
coordinates_tot = np.vstack([coordinates1_rot, coordinates2_rot])
coordinates_tot = center(coordinates_tot, mass_tot)
# Assign velocities
velocities_tot = np.zeros_like(coordinates_tot)
velocities_tot[:natom1, 0] = sample_velocities1
velocities_tot[natom1:, 0] = -sample_velocities2
# Add random boltzmann energy to each atom (may be different temperature)
velocities_tot[:natom1, :] += boltzmann(vibration_kT, masses1)
velocities_tot[natom1:, :] += boltzmann(vibration_kT, masses2)
# Remove COM motion and total angular momentum
coordinates_tot, velocities_tot = initialize_centered(coordinates_tot, velocities_tot, mass_tot)
return coordinates_tot, velocities_tot
#def gaussian_x(x, a=1.0, x0=0.0, k0=1.0):
# """
# Gaussian wave packet of width a, centered at x0, with momentum k0
# """
# return ((a * np.sqrt(np.pi)) ** (-0.5)
# * np.exp(-0.5 * ((x - x0) * 1. / a) ** 2 + 1j * x * k0))
#
#def gaussian_k(k, a=1.0, x0=0.0, k0=1.0):
# """
# Fourier transform of gaussian_x(x)
# """
# return ((a / np.sqrt(np.pi))**0.5
# * np.exp(-0.5 * (a * (k - k0)) ** 2 - 1j * (k - k0) * x0))
| [
"numpy.random.uniform",
"numpy.zeros_like",
"numpy.abs",
"numpy.concatenate",
"numpy.linalg.lstsq",
"numpy.sum",
"numpy.shape",
"numpy.min",
"numpy.max",
"numpy.array",
"numpy.reshape",
"numpy.random.normal",
"numpy.eye",
"scipy.stats.maxwell.ppf",
"numpy.vstack",
"numpy.sqrt"
] | [((1329, 1356), 'numpy.reshape', 'np.reshape', (['masses', '(-1, 1)'], {}), '(masses, (-1, 1))\n', (1339, 1356), True, 'import numpy as np\n'), ((2590, 2617), 'numpy.reshape', 'np.reshape', (['masses', '(-1, 1)'], {}), '(masses, (-1, 1))\n', (2600, 2617), True, 'import numpy as np\n'), ((2943, 3001), 'numpy.vstack', 'np.vstack', (['[linear_constraint_mat, angular_constraint_mat]'], {}), '([linear_constraint_mat, angular_constraint_mat])\n', (2952, 3001), True, 'import numpy as np\n'), ((4412, 4439), 'numpy.reshape', 'np.reshape', (['masses', '(-1, 1)'], {}), '(masses, (-1, 1))\n', (4422, 4439), True, 'import numpy as np\n'), ((4453, 4473), 'numpy.sqrt', 'np.sqrt', (['(kT / mass_r)'], {}), '(kT / mass_r)\n', (4460, 4473), True, 'import numpy as np\n'), ((4489, 4548), 'numpy.random.normal', 'np.random.normal', ([], {'scale': 'factor', 'size': '(mass_r.shape[0], dim)'}), '(scale=factor, size=(mass_r.shape[0], dim))\n', (4505, 4548), True, 'import numpy as np\n'), ((5217, 5229), 'numpy.shape', 'np.shape', (['Qs'], {}), '(Qs)\n', (5225, 5229), True, 'import numpy as np\n'), ((5243, 5259), 'numpy.sqrt', 'np.sqrt', (['(kT / Qs)'], {}), '(kT / Qs)\n', (5250, 5259), True, 'import numpy as np\n'), ((5319, 5349), 'numpy.random.normal', 'np.random.normal', ([], {'scale': 'factor'}), '(scale=factor)\n', (5335, 5349), True, 'import numpy as np\n'), ((6624, 6669), 'numpy.random.uniform', 'np.random.uniform', (['ppf_range[0]', 'ppf_range[1]'], {}), '(ppf_range[0], ppf_range[1])\n', (6641, 6669), True, 'import numpy as np\n'), ((6683, 6703), 'numpy.sqrt', 'np.sqrt', (['(kT / masses)'], {}), '(kT / masses)\n', (6690, 6703), True, 'import numpy as np\n'), ((6715, 6757), 'scipy.stats.maxwell.ppf', 'scipy.stats.maxwell.ppf', (['ppf'], {'scale': 'factor'}), '(ppf, scale=factor)\n', (6738, 6757), False, 'import scipy\n'), ((8375, 8409), 'numpy.concatenate', 'np.concatenate', (['[masses1, masses2]'], {}), '([masses1, masses2])\n', (8389, 8409), True, 'import numpy as np\n'), ((9827, 9874), 'numpy.vstack', 'np.vstack', (['[coordinates1_rot, coordinates2_rot]'], {}), '([coordinates1_rot, coordinates2_rot])\n', (9836, 9874), True, 'import numpy as np\n'), ((9977, 10007), 'numpy.zeros_like', 'np.zeros_like', (['coordinates_tot'], {}), '(coordinates_tot)\n', (9990, 10007), True, 'import numpy as np\n'), ((651, 672), 'numpy.array', 'np.array', (['coordinates'], {}), '(coordinates)\n', (659, 672), True, 'import numpy as np\n'), ((1637, 1704), 'numpy.linalg.lstsq', 'np.linalg.lstsq', (['angular_constraint_mat', 'constraint_vec'], {'rcond': 'None'}), '(angular_constraint_mat, constraint_vec, rcond=None)\n', (1652, 1704), True, 'import numpy as np\n'), ((1717, 1740), 'numpy.reshape', 'np.reshape', (['dp', '(-1, 3)'], {}), '(dp, (-1, 3))\n', (1727, 1740), True, 'import numpy as np\n'), ((3123, 3188), 'numpy.linalg.lstsq', 'np.linalg.lstsq', (['total_constraint_mat', 'constraint_vec'], {'rcond': 'None'}), '(total_constraint_mat, constraint_vec, rcond=None)\n', (3138, 3188), True, 'import numpy as np\n'), ((3201, 3224), 'numpy.reshape', 'np.reshape', (['dp', '(-1, 3)'], {}), '(dp, (-1, 3))\n', (3211, 3224), True, 'import numpy as np\n'), ((5988, 6018), 'numpy.abs', 'np.abs', (['aux_v[0, :Lhalf, :, :]'], {}), '(aux_v[0, :Lhalf, :, :])\n', (5994, 6018), True, 'import numpy as np\n'), ((8903, 8918), 'numpy.sum', 'np.sum', (['masses1'], {}), '(masses1)\n', (8909, 8918), True, 'import numpy as np\n'), ((8990, 9005), 'numpy.sum', 'np.sum', (['masses2'], {}), '(masses2)\n', (8996, 9005), True, 'import numpy as np\n'), ((9472, 9502), 'numpy.min', 'np.min', (['coordinates2_rot[:, 0]'], {}), '(coordinates2_rot[:, 0])\n', (9478, 9502), True, 'import numpy as np\n'), ((1582, 1618), 'numpy.reshape', 'np.reshape', (['linear_momentum', '(-1, 1)'], {}), '(linear_momentum, (-1, 1))\n', (1592, 1618), True, 'import numpy as np\n'), ((2706, 2715), 'numpy.eye', 'np.eye', (['(3)'], {}), '(3)\n', (2712, 2715), True, 'import numpy as np\n'), ((3068, 3104), 'numpy.reshape', 'np.reshape', (['linear_momentum', '(-1, 1)'], {}), '(linear_momentum, (-1, 1))\n', (3078, 3104), True, 'import numpy as np\n'), ((5443, 5507), 'numpy.concatenate', 'np.concatenate', (['(velocities[i, a], aux_v[0, :, i, a])'], {'axis': 'None'}), '((velocities[i, a], aux_v[0, :, i, a]), axis=None)\n', (5457, 5507), True, 'import numpy as np\n'), ((5524, 5600), 'numpy.concatenate', 'np.concatenate', (['(masses[i] / L, 1.0 / (L + 1.0) * Qs[0, :, i, a])'], {'axis': 'None'}), '((masses[i] / L, 1.0 / (L + 1.0) * Qs[0, :, i, a]), axis=None)\n', (5538, 5600), True, 'import numpy as np\n'), ((5617, 5635), 'numpy.sum', 'np.sum', (['(v ** 2 * m)'], {}), '(v ** 2 * m)\n', (5623, 5635), True, 'import numpy as np\n'), ((5654, 5675), 'numpy.sqrt', 'np.sqrt', (['(kT / curr_kT)'], {}), '(kT / curr_kT)\n', (5661, 5675), True, 'import numpy as np\n'), ((6053, 6083), 'numpy.abs', 'np.abs', (['aux_v[0, Lhalf:, :, :]'], {}), '(aux_v[0, Lhalf:, :, :])\n', (6059, 6083), True, 'import numpy as np\n'), ((9439, 9469), 'numpy.max', 'np.max', (['coordinates1_rot[:, 0]'], {}), '(coordinates1_rot[:, 0])\n', (9445, 9469), True, 'import numpy as np\n'), ((2731, 2759), 'numpy.shape', 'np.shape', (['center_coordinates'], {}), '(center_coordinates)\n', (2739, 2759), True, 'import numpy as np\n')] |
""" Basic script to mimic the behavior of Pyneal during an actual scan.
This is a quick and dirty server set up to mimic the behavior of Pyneal. It
will listen for incoming data over an assigned port using the same methods
that Pyneal would use during a real scan. This tool allows you to test
components of Pyneal Scanner without having to actually run a full Pyneal
setup.
Usage
-----
python pynealReceiver_sim.py [--port] [--nVols]
Defaults:
-p/--port: 5555
-n/--nVols: 60
After the scan is complete and all of the data has arrived, this will save the
received 4D volume as a nifti image in same directory as this script (output file named 'receivedImg.nii.gz')
"""
from __future__ import division
import os
import time
import json
import argparse
import zmq
import numpy as np
import nibabel as nib
def launchPynealReceiver(port, nVols, saveImage=True):
""" Launch Pyneal Receiver simulation.
This method will simulate the behavior of the scanReceiver thread of
Pyneal. That is, it will listen for incoming 3D volumes sent from Pyneal
Scanner, enabling you to test Pyneal Scanner without having to run the full
Pyneal Setup
Parameters
----------
port : int
port number that will be used to transfer data between Pyneal Scanner
and Pyneal
nVols : int
number of expected volumes in the dataset
saveImage : boolean, optional
flag for whether to save received image or not
"""
### Set up socket to listen for incoming data
# Note: since this is designed for testing, it assumes
# you are running locally and sets the host accordingly
host = '*'
context = zmq.Context.instance()
sock = context.socket(zmq.PAIR)
sock.bind('tcp://{}:{}'.format(host, port))
print('pynealReceiver_sim listening for connection at {}:{}'.format(host,
port))
# wait for initial contact
while True:
msg = sock.recv_string()
sock.send_string(msg)
break
firstVolHasArrived = False
print('Waiting for first volume data to appear...')
while True:
# receive header info as json
volInfo = sock.recv_json(flags=0)
# retrieve relevant values about this slice
volIdx = volInfo['volIdx']
volDtype = volInfo['dtype']
volShape = volInfo['shape']
# build the imageMatrix if this is the first volume
if not firstVolHasArrived:
imageMatrix = np.zeros(shape=(volShape[0],
volShape[1],
volShape[2],
nVols), dtype=volDtype)
volAffine = np.array(json.loads(volInfo['affine']))
# update first vol flag
firstVolHasArrived = True
# receive raw data stream, reshape to slice dimensions
data = sock.recv(flags=0, copy=False, track=False)
voxelArray = np.frombuffer(data, dtype=volDtype)
voxelArray = voxelArray.reshape(volShape)
# add the voxel data to the appropriate location
imageMatrix[:, :, :, volIdx] = voxelArray
# send slice over socket
if volIdx == (nVols-1):
response = 'Received vol {} - STOP'.format(volIdx)
else:
response = 'Received vol {}'.format(volIdx)
sock.send_string(response)
print(response)
# if all volumes have arrived, save the image
if volIdx == (nVols-1):
if saveImage:
receivedImg = nib.Nifti1Image(imageMatrix, volAffine)
outputName = 'receivedImg.nii.gz'
nib.save(receivedImg, outputName)
print('Image saved at: {}'.format(os.path.abspath(outputName)))
# close socket
time.sleep(.5)
context.destroy()
break
if __name__ == '__main__':
# parse arguments
parser = argparse.ArgumentParser(description='Simulate Receiving thread of Pyneal')
parser.add_argument('-p', '--port',
type=int,
default=5555,
help='port number to listen on for incoming data from pynealScanner ')
parser.add_argument('-n', '--nVols',
type=int,
default=60,
help='number of expected volumes')
# grab the input args
args = parser.parse_args()
# launch
launchPynealReceiver(args.port, args.nVols)
| [
"nibabel.Nifti1Image",
"os.path.abspath",
"argparse.ArgumentParser",
"json.loads",
"numpy.frombuffer",
"numpy.zeros",
"time.sleep",
"nibabel.save",
"zmq.Context.instance"
] | [((1675, 1697), 'zmq.Context.instance', 'zmq.Context.instance', ([], {}), '()\n', (1695, 1697), False, 'import zmq\n'), ((3939, 4013), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Simulate Receiving thread of Pyneal"""'}), "(description='Simulate Receiving thread of Pyneal')\n", (3962, 4013), False, 'import argparse\n'), ((2957, 2992), 'numpy.frombuffer', 'np.frombuffer', (['data'], {'dtype': 'volDtype'}), '(data, dtype=volDtype)\n', (2970, 2992), True, 'import numpy as np\n'), ((2469, 2547), 'numpy.zeros', 'np.zeros', ([], {'shape': '(volShape[0], volShape[1], volShape[2], nVols)', 'dtype': 'volDtype'}), '(shape=(volShape[0], volShape[1], volShape[2], nVols), dtype=volDtype)\n', (2477, 2547), True, 'import numpy as np\n'), ((3812, 3827), 'time.sleep', 'time.sleep', (['(0.5)'], {}), '(0.5)\n', (3822, 3827), False, 'import time\n'), ((2707, 2736), 'json.loads', 'json.loads', (["volInfo['affine']"], {}), "(volInfo['affine'])\n", (2717, 2736), False, 'import json\n'), ((3552, 3591), 'nibabel.Nifti1Image', 'nib.Nifti1Image', (['imageMatrix', 'volAffine'], {}), '(imageMatrix, volAffine)\n', (3567, 3591), True, 'import nibabel as nib\n'), ((3658, 3691), 'nibabel.save', 'nib.save', (['receivedImg', 'outputName'], {}), '(receivedImg, outputName)\n', (3666, 3691), True, 'import nibabel as nib\n'), ((3742, 3769), 'os.path.abspath', 'os.path.abspath', (['outputName'], {}), '(outputName)\n', (3757, 3769), False, 'import os\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 19 23:18:44 2021
@author: fa19
"""
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 27 14:16:37 2020
@author: fa19
"""
from scipy.interpolate import griddata
import os
import params
from params import gen_id
import sys
import numpy as np
from os.path import abspath, dirname
import torch
import torch.nn as nn
#sys.path.append(dirname(abspath(__file__)))
from utils import validate_graph, train_graph, pick_criterion, load_optimiser, import_from, load_testing_graph
from data_utils.MyDataLoader import My_dHCP_Data_Graph
from data_utils.utils import load_dataloader_graph,load_dataloader_graph_classification, load_dataset_graph,load_dataset_arrays, load_model, make_fig
import json
from json.decoder import JSONDecodeError
import copy
def make_logdir(args):
logdir = os.path.expanduser(args.logdir)
logdir = os.path.join(logdir, args.model, args.task)
os.makedirs(logdir, exist_ok=True)
logfile = os.path.join(logdir, 'used_args.json')
if not os.path.exists(logfile):
open(logfile, 'w')
return logfile
def make_resultsdir(args):
resdir = os.path.expanduser(args.resdir)
resdir = os.path.join(resdir,args.model,args.dataset_arr, args.run_id)
os.makedirs(resdir, exist_ok=True)
return resdir
def experiment_exists(args, logfile):
current_args = args.__dict__
with open(logfile, 'r') as x:
try:
data = json.load(x)
if current_args in data['dataset']:
exists = True
else:
exists = False
with open(logfile, 'w') as outfile:
previous_stuff = data['dataset']
previous_stuff.append(current_args)
json.dump({"dataset" : previous_stuff}, outfile, sort_keys = True, indent = 4)
except JSONDecodeError:
with open(logfile, 'w') as outfile:
json.dump({"dataset" : [current_args]}, outfile, sort_keys = True, indent = 4)
exists = False
return exists
# if current_args in old_data['dataset']:
# exists = True
# else:
# exists = False
# with open(logfile, 'w') as outfile:
#
# json.dump(old_data['dataset'].append(current_args),outfile)
#
#
# except JSONDecodeError:
# json.dump(json.dumps({"dataset" : [current_args]}, sort_keys = True,ensure_ascii=True, indent = 4), outfile)
#
# try:
# with open(logfile, 'r') as f:
# data = json.load(f)
# print('loaded data is', data)
#except JSON
# if current_args in data:
# print('its in here')
# else:
# data = data.append(list(copy.deepcopy(current_args)))
# print(data)
# with open(logfile, 'w') as f:
# json.dump(data, f)
# print('written')
def get_device(args):
device = torch.device('cuda:' + str(args.device) if torch.cuda.is_available() else 'cpu')
print('device is ', device)
torch.cuda.set_device(args.device)
return device
def main():
args = params.parse()
device = get_device(args)
logfile = make_logdir(args)
criterion = pick_criterion(args)
exists = experiment_exists(args, logfile)
print('exists is ', exists)
if exists == True and args.overwrite == False:
print('Params already located in logfile. Experiment has already been run. Overwrite not set to True. Attempt Terminated' )
#else:
resdir = make_resultsdir(args) # directory for results
train_arr, val_arr, test_arr = load_dataset_arrays(args)
train_ds, val_ds, test_ds, rot_test_ds = load_dataset_graph(train_arr, val_arr, test_arr, args)
train_weighted = args.weighted_sampling
train_shuffle = 1 - train_weighted
if args.task == 'classification':
train_loader = load_dataloader_graph_classification(train_ds,train_arr, batch_size = args.train_bsize, num_workers=2, shuffle = train_shuffle, weighted=train_weighted)
val_loader = load_dataloader_graph_classification(val_ds,val_arr, shuffle = True, num_workers=1)
test_loader = load_dataloader_graph_classification(test_ds, test_arr, shuffle = False, num_workers=1)
rot_test_loader = load_dataloader_graph_classification(rot_test_ds, test_arr, shuffle = False, num_workers=1)
else:
train_loader = load_dataloader_graph(train_ds,train_arr, batch_size = args.train_bsize, num_workers=2, shuffle = train_shuffle, weighted=train_weighted)
val_loader = load_dataloader_graph(val_ds,val_arr, shuffle = True, num_workers=1)
test_loader = load_dataloader_graph(test_ds, test_arr, shuffle = False, num_workers=1)
rot_test_loader = load_dataloader_graph(rot_test_ds, test_arr, shuffle = False, num_workers=1)
chosen_model = load_model(args)
features = [int(item) for item in args.features.split(',')]
model = chosen_model(in_channels = args.in_channels, num_features = features)
model.to(args.device)
optimiser_fun = load_optimiser(args)
optimiser = optimiser_fun(model.parameters(), lr = args.learning_rate,weight_decay = args.weight_decay)
test_function = load_testing_graph(args)
current_best = 1000000
current_patience = 0
converged = False
epoch_counter = 0
while converged == False:
train_graph(args, model, optimiser,criterion, train_loader, device, epoch_counter)
current_patience, current_best , converged = validate_graph(args, model, criterion, val_loader,
current_best,current_patience, device, resdir)
epoch_counter +=1
torch.save(model, resdir+'/end_model')
U_mae_finished, U_labels_finished, U_outputs_finished = test_function(args, model, criterion, test_loader,device)
R_mae_finished, R_labels_finished, R_outputs_finished = test_function(args, model, criterion, rot_test_loader,device)
model = torch.load(resdir+'/best_model')
U_mae_best, U_labels_best, U_outputs_best = test_function(args, model, criterion, test_loader,device)
R_mae_best, R_labels_best, R_outputs_best = test_function(args, model, criterion, rot_test_loader,device)
if U_mae_finished <= U_mae_best:
make_fig(U_labels_finished, U_outputs_finished, resdir, 'unrotated')
make_fig(R_labels_finished, R_outputs_finished, resdir, 'rotated')
with open(resdir+'/Output.txt', "w") as text_file:
text_file.write("Unrotated MAE: %f \n" % U_mae_finished)
text_file.write("Rotated MAE: %f \n" % R_mae_finished)
text_file.write("Winning model was finished")
np.save(resdir+'/U_preds_labels.npy', [U_outputs_finished, U_labels_finished])
np.save(resdir+'/R_preds_labels.npy', [R_outputs_finished, R_labels_finished])
else:
make_fig(U_labels_best, U_outputs_best, resdir, 'unrotated')
make_fig(R_labels_best, R_outputs_best, resdir, 'rotated')
with open(resdir+'/Output.txt', "w") as text_file:
text_file.write("Unrotated MAE: %f \n" % U_mae_best)
text_file.write("Rotated MAE: %f \n" % R_mae_best)
text_file.write("Winning model was best")
np.save(resdir+'/U_preds_labels.npy', [U_outputs_best, U_labels_best])
np.save(resdir+'/R_preds_labels.npy', [R_outputs_best, R_labels_best])
with open(resdir+'/ParamsUsed.json', "w") as text_file:
json.dump({"parameters" : [args.__dict__]}, text_file, sort_keys = True, indent = 4)
if __name__== '__main__':
main() | [
"os.path.join",
"data_utils.utils.load_dataset_graph",
"torch.load",
"os.path.exists",
"params.parse",
"utils.train_graph",
"torch.cuda.set_device",
"utils.validate_graph",
"utils.load_optimiser",
"data_utils.utils.load_dataset_arrays",
"json.dump",
"numpy.save",
"data_utils.utils.make_fig",... | [((872, 903), 'os.path.expanduser', 'os.path.expanduser', (['args.logdir'], {}), '(args.logdir)\n', (890, 903), False, 'import os\n'), ((917, 960), 'os.path.join', 'os.path.join', (['logdir', 'args.model', 'args.task'], {}), '(logdir, args.model, args.task)\n', (929, 960), False, 'import os\n'), ((965, 999), 'os.makedirs', 'os.makedirs', (['logdir'], {'exist_ok': '(True)'}), '(logdir, exist_ok=True)\n', (976, 999), False, 'import os\n'), ((1014, 1052), 'os.path.join', 'os.path.join', (['logdir', '"""used_args.json"""'], {}), "(logdir, 'used_args.json')\n", (1026, 1052), False, 'import os\n'), ((1178, 1209), 'os.path.expanduser', 'os.path.expanduser', (['args.resdir'], {}), '(args.resdir)\n', (1196, 1209), False, 'import os\n'), ((1223, 1286), 'os.path.join', 'os.path.join', (['resdir', 'args.model', 'args.dataset_arr', 'args.run_id'], {}), '(resdir, args.model, args.dataset_arr, args.run_id)\n', (1235, 1286), False, 'import os\n'), ((1289, 1323), 'os.makedirs', 'os.makedirs', (['resdir'], {'exist_ok': '(True)'}), '(resdir, exist_ok=True)\n', (1300, 1323), False, 'import os\n'), ((3203, 3237), 'torch.cuda.set_device', 'torch.cuda.set_device', (['args.device'], {}), '(args.device)\n', (3224, 3237), False, 'import torch\n'), ((3296, 3310), 'params.parse', 'params.parse', ([], {}), '()\n', (3308, 3310), False, 'import params\n'), ((3390, 3410), 'utils.pick_criterion', 'pick_criterion', (['args'], {}), '(args)\n', (3404, 3410), False, 'from utils import validate_graph, train_graph, pick_criterion, load_optimiser, import_from, load_testing_graph\n'), ((3780, 3805), 'data_utils.utils.load_dataset_arrays', 'load_dataset_arrays', (['args'], {}), '(args)\n', (3799, 3805), False, 'from data_utils.utils import load_dataloader_graph, load_dataloader_graph_classification, load_dataset_graph, load_dataset_arrays, load_model, make_fig\n'), ((3851, 3905), 'data_utils.utils.load_dataset_graph', 'load_dataset_graph', (['train_arr', 'val_arr', 'test_arr', 'args'], {}), '(train_arr, val_arr, test_arr, args)\n', (3869, 3905), False, 'from data_utils.utils import load_dataloader_graph, load_dataloader_graph_classification, load_dataset_graph, load_dataset_arrays, load_model, make_fig\n'), ((5051, 5067), 'data_utils.utils.load_model', 'load_model', (['args'], {}), '(args)\n', (5061, 5067), False, 'from data_utils.utils import load_dataloader_graph, load_dataloader_graph_classification, load_dataset_graph, load_dataset_arrays, load_model, make_fig\n'), ((5270, 5290), 'utils.load_optimiser', 'load_optimiser', (['args'], {}), '(args)\n', (5284, 5290), False, 'from utils import validate_graph, train_graph, pick_criterion, load_optimiser, import_from, load_testing_graph\n'), ((5429, 5453), 'utils.load_testing_graph', 'load_testing_graph', (['args'], {}), '(args)\n', (5447, 5453), False, 'from utils import validate_graph, train_graph, pick_criterion, load_optimiser, import_from, load_testing_graph\n'), ((5931, 5971), 'torch.save', 'torch.save', (['model', "(resdir + '/end_model')"], {}), "(model, resdir + '/end_model')\n", (5941, 5971), False, 'import torch\n'), ((6232, 6266), 'torch.load', 'torch.load', (["(resdir + '/best_model')"], {}), "(resdir + '/best_model')\n", (6242, 6266), False, 'import torch\n'), ((1064, 1087), 'os.path.exists', 'os.path.exists', (['logfile'], {}), '(logfile)\n', (1078, 1087), False, 'import os\n'), ((4051, 4205), 'data_utils.utils.load_dataloader_graph_classification', 'load_dataloader_graph_classification', (['train_ds', 'train_arr'], {'batch_size': 'args.train_bsize', 'num_workers': '(2)', 'shuffle': 'train_shuffle', 'weighted': 'train_weighted'}), '(train_ds, train_arr, batch_size=args.\n train_bsize, num_workers=2, shuffle=train_shuffle, weighted=train_weighted)\n', (4087, 4205), False, 'from data_utils.utils import load_dataloader_graph, load_dataloader_graph_classification, load_dataset_graph, load_dataset_arrays, load_model, make_fig\n'), ((4227, 4313), 'data_utils.utils.load_dataloader_graph_classification', 'load_dataloader_graph_classification', (['val_ds', 'val_arr'], {'shuffle': '(True)', 'num_workers': '(1)'}), '(val_ds, val_arr, shuffle=True,\n num_workers=1)\n', (4263, 4313), False, 'from data_utils.utils import load_dataloader_graph, load_dataloader_graph_classification, load_dataset_graph, load_dataset_arrays, load_model, make_fig\n'), ((4334, 4423), 'data_utils.utils.load_dataloader_graph_classification', 'load_dataloader_graph_classification', (['test_ds', 'test_arr'], {'shuffle': '(False)', 'num_workers': '(1)'}), '(test_ds, test_arr, shuffle=False,\n num_workers=1)\n', (4370, 4423), False, 'from data_utils.utils import load_dataloader_graph, load_dataloader_graph_classification, load_dataset_graph, load_dataset_arrays, load_model, make_fig\n'), ((4448, 4541), 'data_utils.utils.load_dataloader_graph_classification', 'load_dataloader_graph_classification', (['rot_test_ds', 'test_arr'], {'shuffle': '(False)', 'num_workers': '(1)'}), '(rot_test_ds, test_arr, shuffle=False,\n num_workers=1)\n', (4484, 4541), False, 'from data_utils.utils import load_dataloader_graph, load_dataloader_graph_classification, load_dataset_graph, load_dataset_arrays, load_model, make_fig\n'), ((4585, 4723), 'data_utils.utils.load_dataloader_graph', 'load_dataloader_graph', (['train_ds', 'train_arr'], {'batch_size': 'args.train_bsize', 'num_workers': '(2)', 'shuffle': 'train_shuffle', 'weighted': 'train_weighted'}), '(train_ds, train_arr, batch_size=args.train_bsize,\n num_workers=2, shuffle=train_shuffle, weighted=train_weighted)\n', (4606, 4723), False, 'from data_utils.utils import load_dataloader_graph, load_dataloader_graph_classification, load_dataset_graph, load_dataset_arrays, load_model, make_fig\n'), ((4746, 4813), 'data_utils.utils.load_dataloader_graph', 'load_dataloader_graph', (['val_ds', 'val_arr'], {'shuffle': '(True)', 'num_workers': '(1)'}), '(val_ds, val_arr, shuffle=True, num_workers=1)\n', (4767, 4813), False, 'from data_utils.utils import load_dataloader_graph, load_dataloader_graph_classification, load_dataset_graph, load_dataset_arrays, load_model, make_fig\n'), ((4838, 4908), 'data_utils.utils.load_dataloader_graph', 'load_dataloader_graph', (['test_ds', 'test_arr'], {'shuffle': '(False)', 'num_workers': '(1)'}), '(test_ds, test_arr, shuffle=False, num_workers=1)\n', (4859, 4908), False, 'from data_utils.utils import load_dataloader_graph, load_dataloader_graph_classification, load_dataset_graph, load_dataset_arrays, load_model, make_fig\n'), ((4937, 5011), 'data_utils.utils.load_dataloader_graph', 'load_dataloader_graph', (['rot_test_ds', 'test_arr'], {'shuffle': '(False)', 'num_workers': '(1)'}), '(rot_test_ds, test_arr, shuffle=False, num_workers=1)\n', (4958, 5011), False, 'from data_utils.utils import load_dataloader_graph, load_dataloader_graph_classification, load_dataset_graph, load_dataset_arrays, load_model, make_fig\n'), ((5595, 5682), 'utils.train_graph', 'train_graph', (['args', 'model', 'optimiser', 'criterion', 'train_loader', 'device', 'epoch_counter'], {}), '(args, model, optimiser, criterion, train_loader, device,\n epoch_counter)\n', (5606, 5682), False, 'from utils import validate_graph, train_graph, pick_criterion, load_optimiser, import_from, load_testing_graph\n'), ((5740, 5842), 'utils.validate_graph', 'validate_graph', (['args', 'model', 'criterion', 'val_loader', 'current_best', 'current_patience', 'device', 'resdir'], {}), '(args, model, criterion, val_loader, current_best,\n current_patience, device, resdir)\n', (5754, 5842), False, 'from utils import validate_graph, train_graph, pick_criterion, load_optimiser, import_from, load_testing_graph\n'), ((6545, 6613), 'data_utils.utils.make_fig', 'make_fig', (['U_labels_finished', 'U_outputs_finished', 'resdir', '"""unrotated"""'], {}), "(U_labels_finished, U_outputs_finished, resdir, 'unrotated')\n", (6553, 6613), False, 'from data_utils.utils import load_dataloader_graph, load_dataloader_graph_classification, load_dataset_graph, load_dataset_arrays, load_model, make_fig\n'), ((6622, 6688), 'data_utils.utils.make_fig', 'make_fig', (['R_labels_finished', 'R_outputs_finished', 'resdir', '"""rotated"""'], {}), "(R_labels_finished, R_outputs_finished, resdir, 'rotated')\n", (6630, 6688), False, 'from data_utils.utils import load_dataloader_graph, load_dataloader_graph_classification, load_dataset_graph, load_dataset_arrays, load_model, make_fig\n'), ((6972, 7057), 'numpy.save', 'np.save', (["(resdir + '/U_preds_labels.npy')", '[U_outputs_finished, U_labels_finished]'], {}), "(resdir + '/U_preds_labels.npy', [U_outputs_finished, U_labels_finished]\n )\n", (6979, 7057), True, 'import numpy as np\n'), ((7059, 7144), 'numpy.save', 'np.save', (["(resdir + '/R_preds_labels.npy')", '[R_outputs_finished, R_labels_finished]'], {}), "(resdir + '/R_preds_labels.npy', [R_outputs_finished, R_labels_finished]\n )\n", (7066, 7144), True, 'import numpy as np\n'), ((7165, 7225), 'data_utils.utils.make_fig', 'make_fig', (['U_labels_best', 'U_outputs_best', 'resdir', '"""unrotated"""'], {}), "(U_labels_best, U_outputs_best, resdir, 'unrotated')\n", (7173, 7225), False, 'from data_utils.utils import load_dataloader_graph, load_dataloader_graph_classification, load_dataset_graph, load_dataset_arrays, load_model, make_fig\n'), ((7234, 7292), 'data_utils.utils.make_fig', 'make_fig', (['R_labels_best', 'R_outputs_best', 'resdir', '"""rotated"""'], {}), "(R_labels_best, R_outputs_best, resdir, 'rotated')\n", (7242, 7292), False, 'from data_utils.utils import load_dataloader_graph, load_dataloader_graph_classification, load_dataset_graph, load_dataset_arrays, load_model, make_fig\n'), ((7560, 7632), 'numpy.save', 'np.save', (["(resdir + '/U_preds_labels.npy')", '[U_outputs_best, U_labels_best]'], {}), "(resdir + '/U_preds_labels.npy', [U_outputs_best, U_labels_best])\n", (7567, 7632), True, 'import numpy as np\n'), ((7639, 7711), 'numpy.save', 'np.save', (["(resdir + '/R_preds_labels.npy')", '[R_outputs_best, R_labels_best]'], {}), "(resdir + '/R_preds_labels.npy', [R_outputs_best, R_labels_best])\n", (7646, 7711), True, 'import numpy as np\n'), ((7791, 7870), 'json.dump', 'json.dump', (["{'parameters': [args.__dict__]}", 'text_file'], {'sort_keys': '(True)', 'indent': '(4)'}), "({'parameters': [args.__dict__]}, text_file, sort_keys=True, indent=4)\n", (7800, 7870), False, 'import json\n'), ((1493, 1505), 'json.load', 'json.load', (['x'], {}), '(x)\n', (1502, 1505), False, 'import json\n'), ((3129, 3154), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (3152, 3154), False, 'import torch\n'), ((1819, 1892), 'json.dump', 'json.dump', (["{'dataset': previous_stuff}", 'outfile'], {'sort_keys': '(True)', 'indent': '(4)'}), "({'dataset': previous_stuff}, outfile, sort_keys=True, indent=4)\n", (1828, 1892), False, 'import json\n'), ((2023, 2096), 'json.dump', 'json.dump', (["{'dataset': [current_args]}", 'outfile'], {'sort_keys': '(True)', 'indent': '(4)'}), "({'dataset': [current_args]}, outfile, sort_keys=True, indent=4)\n", (2032, 2096), False, 'import json\n')] |
from matplotlib.colors import hsv_to_rgb
from matplotlib import colors
from matplotlib import pyplot as plt
from scipy import ndimage
from sklearn.preprocessing import StandardScaler
from skimage.feature import greycomatrix, greycoprops
import numpy as np
import pandas as pd
import cv2
import glob
import math
images = []
ruta = ""
for file in glob.glob(ruta):
images.append(cv2.imread(file))
# Crear un banco de filtros
filters = []
ksize = 31
for theta in np.arange(0, np.pi, np.pi / 16):
kern = cv2.getGaborKernel((ksize, ksize), 4.0, theta, 10.0, 0.5, 0, ktype=cv2.CV_32F)
kern /= 1.5*kern.sum()
filters.append(kern)
# Función usada para calcular los valores de texturas
texturas_val = []
salida_cuen = 0
# Aeruginosa 0 y 2 Woronichinia
def gabor_values(im):
salida = [0,0,0,0,0,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2]
global salida_cuen
feature_vector = []
for index,f in enumerate(filters):
conv = cv2.filter2D(im, -1, f)
# Calcular estadísticas para el vector
mean = np.mean(conv)
var = np.var(conv)
feature_vector.append(mean)
feature_vector.append(var)
# Distribucion de colores de la imagen
histogram, _ = np.histogram(conv, 100)
# Probabilidades de ocurrencia de cada color
histogram = histogram.astype(float)/ (conv.shape[0]*conv.shape[1])
# Formula entropia
H = -np.sum(histogram*np.log2(histogram + np.finfo(float).eps))
feature_vector.append(H)
# Calculamos tambien las matrices de concurrencia
cm = greycomatrix(im, [1, 2], [0, np.pi/4, np.pi/2, 3*np.pi/4], normed=True, symmetric=True)
props = greycoprops(cm, 'contrast')
vector = np.reshape(props, (1, props.shape[0]*props.shape[1]))
props2 = greycoprops(cm, 'energy')
vector2 = np.reshape(props2, (1, props2.shape[0]*props2.shape[1]))
props3 = greycoprops(cm, 'homogeneity')
vector3 = np.reshape(props3, (1, props3.shape[0]*props3.shape[1]))
props4 = greycoprops(cm, 'correlation')
vector4 = np.reshape(props4, (1, props4.shape[0]*props4.shape[1]))
# Concatenación
feature_vector.extend(vector[0])
feature_vector.extend(vector2[0])
feature_vector.extend(vector3[0])
feature_vector.extend(vector4[0])
feature_vector.append(salida[salida_cuen])
salida_cuen = salida_cuen + 1
global textura
texturas_val.append(feature_vector)
contador = 0
for im in images:
# Progreso análisis
contador += 1
print(contador, "imágenes de", len(images))
im_gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
im_rgb = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
im_hsv = cv2.cvtColor(im, cv2.COLOR_RGB2HSV)
canal = im_rgb[:,:,2] # Canal en segundo procesado
satura = im_hsv[:,:,1] # Selección canal 1 procesado
# Preprocesado para correcta segmentación utilizando el canal s del hsv(por las características de las imágenes)
khat = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (159,159))
kclose = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (55,55))
kopen = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (35,35))
filtroga = cv2.GaussianBlur(satura, (21, 21), 0) #Filtro ruido general
# Remarcar los bordes(secciones desenfocadas tienen nivel de s más bajo)
filtrosa = cv2.medianBlur(filtroga, 5)
diff = filtroga - filtrosa
satura2 = filtroga + diff
# Top hat + un filtrado de medias para rebajar ruido del fondo espúreo
satura2 = cv2.morphologyEx(satura2, cv2.MORPH_TOPHAT, khat)
satura2 = cv2.blur(satura2, (15,15))
# Umbralización con treshold bajo
ret, thr1 = cv2.threshold(satura2, 20, 255, cv2.THRESH_BINARY)
thr1 = cv2.morphologyEx(thr1, cv2.MORPH_CLOSE, kclose) #Cierre para asegurarnos bien que cojemos toda la región
thr1 = cv2.morphologyEx(thr1, cv2.MORPH_OPEN, kopen)
# Detección de contornos
contours, hierarchy = cv2.findContours(thr1,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
contours = sorted(contours, key=cv2.contourArea, reverse=True)
# Selección contornos válidos
conta = 0
for con in contours:
small = cv2.contourArea(con) # < 25000 área eliminar
if small < 25000:
break
conta += 1
contours = contours[0:conta]
# Dibujar contornos
out = im_rgb * 1 # Copiamos la imagen original para no modificarla
cv2.drawContours(out, contours, -1, (0,0,255), 3)
# Tratamiento
for con in range(0,len(contours)):
# Máscara para la región a analizar
mask1 = np.zeros(satura.shape, np.uint8)
cv2.drawContours(mask1, contours, con, 1, thickness=-1)
# Cálculos para descartar especie
thr2 = thr1 == 255
thr2 = thr2.astype(int)
satura3 = thr2 * mask1 #eliminar burbujas, etc
satura4 = satura3 + mask1
vacio = len(satura4[satura4==1])
lleno = len(satura4[satura4==2])
porcen = vacio / (lleno + vacio)
if porcen > 0.25: #Descartar anbaena
continue
# Calcular circularidad y excentricidad para ver si tenemos muchos objetos o uno
((x,y),(w,h), angle) = cv2.minAreaRect(contours[con])
Are = cv2.contourArea(contours[con])
Per = cv2.arcLength(contours[con], True)
Cir = (4*math.pi*Are)/Per**2
Exc = h/w
if Cir < 0.51 and Exc > 0.65: #Comprobar si son varios juntos o uno (posibilidad de varios)
newimage = satura * mask1
fnew = cv2.medianBlur(newimage, 11)
ret, thr3 = cv2.threshold(fnew, 75, 255, cv2.THRESH_BINARY)
kclose2 = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (47,47))
thr3 = cv2.morphologyEx(thr3, cv2.MORPH_CLOSE, kclose2)
# Contornos finos
contours2, hierarchy = cv2.findContours(thr3,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
contours2 = sorted(contours2, key=cv2.contourArea, reverse=True)
# Selección contornos válidos
conta = 0
for con in contours2:
small = cv2.contourArea(con) # < 40000 área eliminar
if small < 40000:
break
conta += 1
contours2 = contours2[0:conta]
# Dibujar contornos
out2 = im_rgb * 1 # Copiamos la imagen original para no modificarla
cv2.drawContours(out2, contours2, -1, (0,0,255), 3)
for conto in range(0,len(contours2)):
# Máscara para la región a analizar apertura muy grande con kernel circular para relleno
mask2 = np.zeros(satura.shape, np.uint8)
cv2.drawContours(mask2, contours2, conto, 1, thickness=-1)
kclose3 = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (137,137))
mask2 = cv2.morphologyEx(mask2, cv2.MORPH_CLOSE, kclose3)
mask4 = canal * mask2
# Extraer imágen para usar texturas
x,y,w,h = cv2.boundingRect(contours2[conto])
imtextura = im_gray[y:y+h, x:x+w]
gabor_values(imtextura)
else:
# Extraer imágen para usar texturas
x,y,w,h = cv2.boundingRect(contours[con])
imtextura = im_gray[y:y+h, x:x+w]
gabor_values(imtextura)
salir = "salir"
if contador == 20:
break
df = pd.DataFrame(texturas_val)
df.to_csv('Fitoplancton_features.csv', index=False, header=False) | [
"cv2.GaussianBlur",
"cv2.medianBlur",
"cv2.arcLength",
"numpy.histogram",
"numpy.mean",
"numpy.arange",
"glob.glob",
"cv2.minAreaRect",
"pandas.DataFrame",
"cv2.contourArea",
"cv2.filter2D",
"cv2.cvtColor",
"skimage.feature.greycoprops",
"skimage.feature.greycomatrix",
"numpy.finfo",
"... | [((360, 375), 'glob.glob', 'glob.glob', (['ruta'], {}), '(ruta)\n', (369, 375), False, 'import glob\n'), ((6808, 6834), 'pandas.DataFrame', 'pd.DataFrame', (['texturas_val'], {}), '(texturas_val)\n', (6820, 6834), True, 'import pandas as pd\n'), ((485, 516), 'numpy.arange', 'np.arange', (['(0)', 'np.pi', '(np.pi / 16)'], {}), '(0, np.pi, np.pi / 16)\n', (494, 516), True, 'import numpy as np\n'), ((1567, 1667), 'skimage.feature.greycomatrix', 'greycomatrix', (['im', '[1, 2]', '[0, np.pi / 4, np.pi / 2, 3 * np.pi / 4]'], {'normed': '(True)', 'symmetric': '(True)'}), '(im, [1, 2], [0, np.pi / 4, np.pi / 2, 3 * np.pi / 4], normed=\n True, symmetric=True)\n', (1579, 1667), False, 'from skimage.feature import greycomatrix, greycoprops\n'), ((1665, 1692), 'skimage.feature.greycoprops', 'greycoprops', (['cm', '"""contrast"""'], {}), "(cm, 'contrast')\n", (1676, 1692), False, 'from skimage.feature import greycomatrix, greycoprops\n'), ((1704, 1759), 'numpy.reshape', 'np.reshape', (['props', '(1, props.shape[0] * props.shape[1])'], {}), '(props, (1, props.shape[0] * props.shape[1]))\n', (1714, 1759), True, 'import numpy as np\n'), ((1769, 1794), 'skimage.feature.greycoprops', 'greycoprops', (['cm', '"""energy"""'], {}), "(cm, 'energy')\n", (1780, 1794), False, 'from skimage.feature import greycomatrix, greycoprops\n'), ((1807, 1865), 'numpy.reshape', 'np.reshape', (['props2', '(1, props2.shape[0] * props2.shape[1])'], {}), '(props2, (1, props2.shape[0] * props2.shape[1]))\n', (1817, 1865), True, 'import numpy as np\n'), ((1875, 1905), 'skimage.feature.greycoprops', 'greycoprops', (['cm', '"""homogeneity"""'], {}), "(cm, 'homogeneity')\n", (1886, 1905), False, 'from skimage.feature import greycomatrix, greycoprops\n'), ((1918, 1976), 'numpy.reshape', 'np.reshape', (['props3', '(1, props3.shape[0] * props3.shape[1])'], {}), '(props3, (1, props3.shape[0] * props3.shape[1]))\n', (1928, 1976), True, 'import numpy as np\n'), ((1986, 2016), 'skimage.feature.greycoprops', 'greycoprops', (['cm', '"""correlation"""'], {}), "(cm, 'correlation')\n", (1997, 2016), False, 'from skimage.feature import greycomatrix, greycoprops\n'), ((2029, 2087), 'numpy.reshape', 'np.reshape', (['props4', '(1, props4.shape[0] * props4.shape[1])'], {}), '(props4, (1, props4.shape[0] * props4.shape[1]))\n', (2039, 2087), True, 'import numpy as np\n'), ((2517, 2553), 'cv2.cvtColor', 'cv2.cvtColor', (['im', 'cv2.COLOR_BGR2GRAY'], {}), '(im, cv2.COLOR_BGR2GRAY)\n', (2529, 2553), False, 'import cv2\n'), ((2565, 2600), 'cv2.cvtColor', 'cv2.cvtColor', (['im', 'cv2.COLOR_BGR2RGB'], {}), '(im, cv2.COLOR_BGR2RGB)\n', (2577, 2600), False, 'import cv2\n'), ((2612, 2647), 'cv2.cvtColor', 'cv2.cvtColor', (['im', 'cv2.COLOR_RGB2HSV'], {}), '(im, cv2.COLOR_RGB2HSV)\n', (2624, 2647), False, 'import cv2\n'), ((2884, 2940), 'cv2.getStructuringElement', 'cv2.getStructuringElement', (['cv2.MORPH_ELLIPSE', '(159, 159)'], {}), '(cv2.MORPH_ELLIPSE, (159, 159))\n', (2909, 2940), False, 'import cv2\n'), ((2951, 3005), 'cv2.getStructuringElement', 'cv2.getStructuringElement', (['cv2.MORPH_ELLIPSE', '(55, 55)'], {}), '(cv2.MORPH_ELLIPSE, (55, 55))\n', (2976, 3005), False, 'import cv2\n'), ((3015, 3069), 'cv2.getStructuringElement', 'cv2.getStructuringElement', (['cv2.MORPH_ELLIPSE', '(35, 35)'], {}), '(cv2.MORPH_ELLIPSE, (35, 35))\n', (3040, 3069), False, 'import cv2\n'), ((3082, 3119), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['satura', '(21, 21)', '(0)'], {}), '(satura, (21, 21), 0)\n', (3098, 3119), False, 'import cv2\n'), ((3233, 3260), 'cv2.medianBlur', 'cv2.medianBlur', (['filtroga', '(5)'], {}), '(filtroga, 5)\n', (3247, 3260), False, 'import cv2\n'), ((3405, 3454), 'cv2.morphologyEx', 'cv2.morphologyEx', (['satura2', 'cv2.MORPH_TOPHAT', 'khat'], {}), '(satura2, cv2.MORPH_TOPHAT, khat)\n', (3421, 3454), False, 'import cv2\n'), ((3467, 3494), 'cv2.blur', 'cv2.blur', (['satura2', '(15, 15)'], {}), '(satura2, (15, 15))\n', (3475, 3494), False, 'import cv2\n'), ((3546, 3596), 'cv2.threshold', 'cv2.threshold', (['satura2', '(20)', '(255)', 'cv2.THRESH_BINARY'], {}), '(satura2, 20, 255, cv2.THRESH_BINARY)\n', (3559, 3596), False, 'import cv2\n'), ((3606, 3653), 'cv2.morphologyEx', 'cv2.morphologyEx', (['thr1', 'cv2.MORPH_CLOSE', 'kclose'], {}), '(thr1, cv2.MORPH_CLOSE, kclose)\n', (3622, 3653), False, 'import cv2\n'), ((3720, 3765), 'cv2.morphologyEx', 'cv2.morphologyEx', (['thr1', 'cv2.MORPH_OPEN', 'kopen'], {}), '(thr1, cv2.MORPH_OPEN, kopen)\n', (3736, 3765), False, 'import cv2\n'), ((3820, 3880), 'cv2.findContours', 'cv2.findContours', (['thr1', 'cv2.RETR_TREE', 'cv2.CHAIN_APPROX_NONE'], {}), '(thr1, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)\n', (3836, 3880), False, 'import cv2\n'), ((4242, 4293), 'cv2.drawContours', 'cv2.drawContours', (['out', 'contours', '(-1)', '(0, 0, 255)', '(3)'], {}), '(out, contours, -1, (0, 0, 255), 3)\n', (4258, 4293), False, 'import cv2\n'), ((393, 409), 'cv2.imread', 'cv2.imread', (['file'], {}), '(file)\n', (403, 409), False, 'import cv2\n'), ((531, 609), 'cv2.getGaborKernel', 'cv2.getGaborKernel', (['(ksize, ksize)', '(4.0)', 'theta', '(10.0)', '(0.5)', '(0)'], {'ktype': 'cv2.CV_32F'}), '((ksize, ksize), 4.0, theta, 10.0, 0.5, 0, ktype=cv2.CV_32F)\n', (549, 609), False, 'import cv2\n'), ((967, 990), 'cv2.filter2D', 'cv2.filter2D', (['im', '(-1)', 'f'], {}), '(im, -1, f)\n', (979, 990), False, 'import cv2\n'), ((1049, 1062), 'numpy.mean', 'np.mean', (['conv'], {}), '(conv)\n', (1056, 1062), True, 'import numpy as np\n'), ((1075, 1087), 'numpy.var', 'np.var', (['conv'], {}), '(conv)\n', (1081, 1087), True, 'import numpy as np\n'), ((1232, 1255), 'numpy.histogram', 'np.histogram', (['conv', '(100)'], {}), '(conv, 100)\n', (1244, 1255), True, 'import numpy as np\n'), ((4024, 4044), 'cv2.contourArea', 'cv2.contourArea', (['con'], {}), '(con)\n', (4039, 4044), False, 'import cv2\n'), ((4400, 4432), 'numpy.zeros', 'np.zeros', (['satura.shape', 'np.uint8'], {}), '(satura.shape, np.uint8)\n', (4408, 4432), True, 'import numpy as np\n'), ((4436, 4491), 'cv2.drawContours', 'cv2.drawContours', (['mask1', 'contours', 'con', '(1)'], {'thickness': '(-1)'}), '(mask1, contours, con, 1, thickness=-1)\n', (4452, 4491), False, 'import cv2\n'), ((4934, 4964), 'cv2.minAreaRect', 'cv2.minAreaRect', (['contours[con]'], {}), '(contours[con])\n', (4949, 4964), False, 'import cv2\n'), ((4974, 5004), 'cv2.contourArea', 'cv2.contourArea', (['contours[con]'], {}), '(contours[con])\n', (4989, 5004), False, 'import cv2\n'), ((5014, 5048), 'cv2.arcLength', 'cv2.arcLength', (['contours[con]', '(True)'], {}), '(contours[con], True)\n', (5027, 5048), False, 'import cv2\n'), ((5232, 5260), 'cv2.medianBlur', 'cv2.medianBlur', (['newimage', '(11)'], {}), '(newimage, 11)\n', (5246, 5260), False, 'import cv2\n'), ((5277, 5324), 'cv2.threshold', 'cv2.threshold', (['fnew', '(75)', '(255)', 'cv2.THRESH_BINARY'], {}), '(fnew, 75, 255, cv2.THRESH_BINARY)\n', (5290, 5324), False, 'import cv2\n'), ((5339, 5393), 'cv2.getStructuringElement', 'cv2.getStructuringElement', (['cv2.MORPH_ELLIPSE', '(47, 47)'], {}), '(cv2.MORPH_ELLIPSE, (47, 47))\n', (5364, 5393), False, 'import cv2\n'), ((5404, 5452), 'cv2.morphologyEx', 'cv2.morphologyEx', (['thr3', 'cv2.MORPH_CLOSE', 'kclose2'], {}), '(thr3, cv2.MORPH_CLOSE, kclose2)\n', (5420, 5452), False, 'import cv2\n'), ((5504, 5564), 'cv2.findContours', 'cv2.findContours', (['thr3', 'cv2.RETR_TREE', 'cv2.CHAIN_APPROX_NONE'], {}), '(thr3, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)\n', (5520, 5564), False, 'import cv2\n'), ((5959, 6012), 'cv2.drawContours', 'cv2.drawContours', (['out2', 'contours2', '(-1)', '(0, 0, 255)', '(3)'], {}), '(out2, contours2, -1, (0, 0, 255), 3)\n', (5975, 6012), False, 'import cv2\n'), ((6650, 6681), 'cv2.boundingRect', 'cv2.boundingRect', (['contours[con]'], {}), '(contours[con])\n', (6666, 6681), False, 'import cv2\n'), ((5721, 5741), 'cv2.contourArea', 'cv2.contourArea', (['con'], {}), '(con)\n', (5736, 5741), False, 'import cv2\n'), ((6162, 6194), 'numpy.zeros', 'np.zeros', (['satura.shape', 'np.uint8'], {}), '(satura.shape, np.uint8)\n', (6170, 6194), True, 'import numpy as np\n'), ((6200, 6258), 'cv2.drawContours', 'cv2.drawContours', (['mask2', 'contours2', 'conto', '(1)'], {'thickness': '(-1)'}), '(mask2, contours2, conto, 1, thickness=-1)\n', (6216, 6258), False, 'import cv2\n'), ((6276, 6332), 'cv2.getStructuringElement', 'cv2.getStructuringElement', (['cv2.MORPH_ELLIPSE', '(137, 137)'], {}), '(cv2.MORPH_ELLIPSE, (137, 137))\n', (6301, 6332), False, 'import cv2\n'), ((6345, 6394), 'cv2.morphologyEx', 'cv2.morphologyEx', (['mask2', 'cv2.MORPH_CLOSE', 'kclose3'], {}), '(mask2, cv2.MORPH_CLOSE, kclose3)\n', (6361, 6394), False, 'import cv2\n'), ((6480, 6514), 'cv2.boundingRect', 'cv2.boundingRect', (['contours2[conto]'], {}), '(contours2[conto])\n', (6496, 6514), False, 'import cv2\n'), ((1453, 1468), 'numpy.finfo', 'np.finfo', (['float'], {}), '(float)\n', (1461, 1468), True, 'import numpy as np\n')] |
import numpy as np
import csv
from os import listdir
from scipy import interpolate
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from . import bases
class Dispersion3D(bases.Bzone2D):
"""Intersect 2D band structure with electron plane. Can be used for 3D data or 2D data, but 3D data must be confined to a 2D
plane which at the moment is constrained to just planes in k_rho,kz where k_rho = norm(kx,ky). Realistically in COMSOl this
means only kz,kx and kz,ky because of the way bands are found - choose a direction from |k|=0 and increase |k|. Always sorted
by band (band is the root key)"""
def __init__(self, datafile, symmetry, headers=['skip', 'band', 'skip', 'frequency',\
'kx', 'ky', 'kz', 'n', 'skip'], sort_by = 'band', ndim=3, interpolate=True):
plt.rcParams.update({'font.size': 14})
np.set_printoptions(precision=3) # will this affect data saved to text?
self.ndim = ndim
for header in headers:
if header not in \
['band', 'frequency', 'kx', 'ky', 'kz', 'n', 'skip']:
print(header, "not allowed.")
raise ValueError("Invalid header supplied, must be one of "
"['band', 'frequency', 'kx', 'ky', 'kz', 'n']")
super(Dispersion3D, self).__init__\
(datafile, headers=headers, ndim=ndim,\
symmetry=symmetry)
if interpolate:
self.reflect()
self.interpolate() # default resolution is 100 elements
def intersect(self, v=0.999):
"""course intersection, then fine by looking in neighbourhood. Do this by interpolating between lines?"""
# raise NotImplementedError
for band in self.data:
# e_plane = self.data[band]['mj']*3.e8*v
mf = self.data[band]['mf'] # is this by reference?
mj = self.data[band]['mj']
mi = self.data[band]['mi']
self.data[band]['crossings'] = {'kz': [], 'k_rho': [], 'f': []}
# we are working to intersect in z direction, so loop over mj
# transpose mj so we are row major (does this change actual data?)
# order = 'F' (fortran order)
# get array for z values and rho values
z_array = mj.T[0][:-1] # starts at maximum
rho_array = mi[0]
for rho_i, z_values in enumerate(rho_array):
#print(x, xi)
for z_i, z in enumerate(z_array[:-1]):
#print(y, yi)
z2 = z_array[z_i + 1]
f = mf[rho_i, z_i]
f2 = mf[rho_i, z_i + 1]
ve = v*3.e8 # speed of light
# print(z2)
# print(z)
m = (f2-f)/(z2-z) # gradient
rho = rho_array[rho_i]
#y_cross = y*ve # ve*k = f
# print(m)
if abs(m) < 1e-20:
#print('skipping')
z_cross = f/ve
else:
c = f - m*z
z_cross = c/(ve - m)
# check if crossing point is inside ROI (f2-f, z2-z, rho)
if abs(z_cross) <= np.max(z_array) and z_cross*ve >= f and z_cross*ve <= f2:
#print(y)
# print('crossing at y=', y_cross,'x=',x,'f=',y_cross*ve)
self.data[band]['crossings']['kz'].append(z) # replace with intialised lists for speed?
self.data[band]['crossings']['k_rho'].append(rho)
self.data[band]['crossings']['f'].append(f)
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.set_xlabel(r"$k_rho$")
ax.set_ylabel(r"Wavelength $\lambda$")
# zmax = np.max(z_array)
# rhomax = np.max(rho_array)
theta = np.arctan(rho_array/(z_array+1e-20)) # <-- better sol
wl = 2*np.pi/self.data[band]['crossings']['f']
ax.set_title("Wavelength against Cherenkov Angle Derived from 2D Dispersion")
ax.plot(theta, wl)
plt.show()
def plot3D(self, mode='surface'):
print("Reflecting")
self.reflect()
print("Interpolating")
self.interpolate(resolution=0.01)
print("Plotting")
fig = plt.figure(figsize=(12,9))
#ax = fig.gca(projection='3d')
for i, band in enumerate(self.data):
mf = self.data[band]['mf']
mi = self.data[band]['mi']
mj = self.data[band]['mj']
#ax = fig.add_subplot(2,3,i+1, projection='3d')
ax = fig.add_subplot(1,1,1, projection='3d')
mi_range = np.max(mi) - np.min(mi)
mj_range = np.max(mj) - np.min(mj)
global_max = np.max([np.max(mi), np.max(mj)])
global_min = np.min([np.min(mi), np.min(mj)])
ax.set_xlim([global_min, global_max])
ax.set_ylim([global_min, global_max])
ax.auto_scale_xyz([np.min(mi), np.max(mi)], [np.min(mj), np.max(mj)], [np.min(mf),np.max(mf)])
# print(mj_range/mi_range)
#ax.set_aspect(mj_range/mi_range)
ax.set_title(r"Band "+str(i+1)+r" 3D Model Dispersion")
ax.set_xlabel(r"Wavevector in $(k_x,k_y)$, $k_{\rho}$ $(m^{-1})$")
ax.set_ylabel(r"Wavevector $k_z$ $(m^{-1})$")
ax.set_zlabel(r"Frequency $(Hz)$")
if mode == 'surface':
surf = ax.plot_surface(mi, mj, mf, cmap=cm.bwr,
linewidth=0, antialiased=False)
elif mode == 'scatter':
ax.scatter(self.data['1']['k_rho'], self.data['1']['kz'], self.data['1']['frequency'])
# plane = ax.plot_surface(mi, mj, mj*0.9*3.e8*np.pi/a, cmap=cm.coolwarm,
# linewidth=0, antialiased=False)
#ax.set_zlim([np.min(mf),np.max(mf)])
fig.show()
| [
"numpy.set_printoptions",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.rcParams.update",
"numpy.max",
"numpy.min",
"numpy.arctan"
] | [((853, 891), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (["{'font.size': 14}"], {}), "({'font.size': 14})\n", (872, 891), True, 'from matplotlib import pyplot as plt\n'), ((900, 932), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'precision': '(3)'}), '(precision=3)\n', (919, 932), True, 'import numpy as np\n'), ((4453, 4480), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(12, 9)'}), '(figsize=(12, 9))\n', (4463, 4480), True, 'from matplotlib import pyplot as plt\n'), ((3747, 3759), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (3757, 3759), True, 'from matplotlib import pyplot as plt\n'), ((3987, 4027), 'numpy.arctan', 'np.arctan', (['(rho_array / (z_array + 1e-20))'], {}), '(rho_array / (z_array + 1e-20))\n', (3996, 4027), True, 'import numpy as np\n'), ((4235, 4245), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4243, 4245), True, 'from matplotlib import pyplot as plt\n'), ((4822, 4832), 'numpy.max', 'np.max', (['mi'], {}), '(mi)\n', (4828, 4832), True, 'import numpy as np\n'), ((4835, 4845), 'numpy.min', 'np.min', (['mi'], {}), '(mi)\n', (4841, 4845), True, 'import numpy as np\n'), ((4869, 4879), 'numpy.max', 'np.max', (['mj'], {}), '(mj)\n', (4875, 4879), True, 'import numpy as np\n'), ((4882, 4892), 'numpy.min', 'np.min', (['mj'], {}), '(mj)\n', (4888, 4892), True, 'import numpy as np\n'), ((4926, 4936), 'numpy.max', 'np.max', (['mi'], {}), '(mi)\n', (4932, 4936), True, 'import numpy as np\n'), ((4938, 4948), 'numpy.max', 'np.max', (['mj'], {}), '(mj)\n', (4944, 4948), True, 'import numpy as np\n'), ((4984, 4994), 'numpy.min', 'np.min', (['mi'], {}), '(mi)\n', (4990, 4994), True, 'import numpy as np\n'), ((4996, 5006), 'numpy.min', 'np.min', (['mj'], {}), '(mj)\n', (5002, 5006), True, 'import numpy as np\n'), ((5140, 5150), 'numpy.min', 'np.min', (['mi'], {}), '(mi)\n', (5146, 5150), True, 'import numpy as np\n'), ((5152, 5162), 'numpy.max', 'np.max', (['mi'], {}), '(mi)\n', (5158, 5162), True, 'import numpy as np\n'), ((5166, 5176), 'numpy.min', 'np.min', (['mj'], {}), '(mj)\n', (5172, 5176), True, 'import numpy as np\n'), ((5178, 5188), 'numpy.max', 'np.max', (['mj'], {}), '(mj)\n', (5184, 5188), True, 'import numpy as np\n'), ((5192, 5202), 'numpy.min', 'np.min', (['mf'], {}), '(mf)\n', (5198, 5202), True, 'import numpy as np\n'), ((5203, 5213), 'numpy.max', 'np.max', (['mf'], {}), '(mf)\n', (5209, 5213), True, 'import numpy as np\n'), ((3301, 3316), 'numpy.max', 'np.max', (['z_array'], {}), '(z_array)\n', (3307, 3316), True, 'import numpy as np\n')] |
import numpy as np
from core.Functions.cuda import *
from core.Layers import im2col
import time
from core.Initializer import xavieruniform
input = np.random.randn(3, 280, 280, 32).astype(np.float32)
input_gpu = cuda.to_device(input)
lbl = [0, 1, 0, 0, 0, 0, 0, 0, 0, 0]
kernel_shape = [3, 3, 32, 32]
col_gpu = cu_im2col(input_gpu, kernel_shape, from_host=False, to_host=False)
col = im2col(input, kernel_shape)
# ## efficiency
# start_t = time.time()
# for i in range(10000):
# col = cu_conv_im2col(input_gpu , kernel_shape, from_host=False, to_host=False)
#
# print("[ duration ]: ", time.time() - start_t)
#
# start_t = time.time()
# for i in range(10000):
# col = im2col(input, kernel_shape)
#
# print("[ duration ]: ", time.time() - start_t)
random_kernel = xavieruniform().init(shape=kernel_shape)
random_kernel_gpu = cuda.to_device(random_kernel)
random_kernel_reshaped = random_kernel.reshape(-1, random_kernel.shape[3])
random_kernel_reshaped_gpu = random_kernel_gpu.reshape(np.prod(random_kernel_gpu.shape[0:3]),
random_kernel_gpu.shape[3])
Z = np.matmul(col, random_kernel_reshaped)
Z_gpu = cu_matmul(col, random_kernel_reshaped, from_host=True, to_host=False)
Z_cpu = Z_gpu.copy_to_host()
## efficiency
start_t = time.time()
for i in range(1000):
Z_gpu = cu_matmul(col_gpu, random_kernel_reshaped_gpu, from_host=False, to_host=False)
print("[ duration ]: ", time.time() - start_t)
start_t = time.time()
for i in range(1000):
Z = np.matmul(col, random_kernel_reshaped)
print("[ duration ]: ", time.time() - start_t)
print("finish")
| [
"numpy.random.randn",
"core.Layers.im2col",
"time.time",
"numpy.matmul",
"core.Initializer.xavieruniform",
"numpy.prod"
] | [((384, 411), 'core.Layers.im2col', 'im2col', (['input', 'kernel_shape'], {}), '(input, kernel_shape)\n', (390, 411), False, 'from core.Layers import im2col\n'), ((1121, 1159), 'numpy.matmul', 'np.matmul', (['col', 'random_kernel_reshaped'], {}), '(col, random_kernel_reshaped)\n', (1130, 1159), True, 'import numpy as np\n'), ((1292, 1303), 'time.time', 'time.time', ([], {}), '()\n', (1301, 1303), False, 'import time\n'), ((1476, 1487), 'time.time', 'time.time', ([], {}), '()\n', (1485, 1487), False, 'import time\n'), ((994, 1031), 'numpy.prod', 'np.prod', (['random_kernel_gpu.shape[0:3]'], {}), '(random_kernel_gpu.shape[0:3])\n', (1001, 1031), True, 'import numpy as np\n'), ((1518, 1556), 'numpy.matmul', 'np.matmul', (['col', 'random_kernel_reshaped'], {}), '(col, random_kernel_reshaped)\n', (1527, 1556), True, 'import numpy as np\n'), ((148, 180), 'numpy.random.randn', 'np.random.randn', (['(3)', '(280)', '(280)', '(32)'], {}), '(3, 280, 280, 32)\n', (163, 180), True, 'import numpy as np\n'), ((773, 788), 'core.Initializer.xavieruniform', 'xavieruniform', ([], {}), '()\n', (786, 788), False, 'from core.Initializer import xavieruniform\n'), ((1442, 1453), 'time.time', 'time.time', ([], {}), '()\n', (1451, 1453), False, 'import time\n'), ((1582, 1593), 'time.time', 'time.time', ([], {}), '()\n', (1591, 1593), False, 'import time\n')] |
#===============================================================================
# Copyright 2021 Intel Corporation
#
# 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 numpy as np
import numbers
import warnings
def _column_or_1d(y):
y = np.asarray(y)
shape = np.shape(y)
if len(shape) == 1:
return np.ravel(y)
if len(shape) == 2 and shape[1] == 1:
return np.ravel(y)
raise ValueError(
"y should be a 1d array, "
"got an array of shape {} instead.".format(shape))
def _compute_class_weight(class_weight, classes, y):
if set(y) - set(classes):
raise ValueError("classes should include all valid labels that can "
"be in y")
if class_weight is None or len(class_weight) == 0:
weight = np.ones(classes.shape[0], dtype=np.float64, order='C')
else:
# user-defined dictionary
weight = np.ones(classes.shape[0], dtype=np.float64, order='C')
if not isinstance(class_weight, dict):
raise ValueError("class_weight must be dict, 'balanced', or None,"
" got: %r" % class_weight)
else:
for c in class_weight:
i = np.searchsorted(classes, c)
if i >= len(classes) or classes[i] != c:
raise ValueError("Class label {} not present.".format(c))
else:
weight[i] = class_weight[c]
return weight
def _validate_targets(y, class_weight, dtype):
y_ = _column_or_1d(y)
classes, y = np.unique(y_, return_inverse=True)
class_weight_res = _compute_class_weight(class_weight,
classes=classes, y=y_)
if len(classes) < 2:
raise ValueError(
"The number of classes has to be greater than one; got %d"
" class" % len(classes))
return np.asarray(y, dtype=dtype, order='C'), class_weight_res, classes
def _check_array(array, dtype="numeric", accept_sparse=False, order=None,
copy=False, force_all_finite=True, ensure_2d=True):
# TODO
from sklearn.utils.validation import check_array
array = check_array(array=array, dtype=dtype, accept_sparse=accept_sparse,
order=order, copy=copy, force_all_finite=force_all_finite,
ensure_2d=ensure_2d)
# TODO: If data is not contiguous copy to contiguous
# Need implemeted numpy table in oneDAL
if not array.flags.c_contiguous and not array.flags.f_contiguous:
array = np.ascontiguousarray(array, array.dtype)
return array
def _check_X_y(X, y, dtype="numeric", accept_sparse=False, order=None, copy=False,
force_all_finite=True, ensure_2d=True):
if y is None:
raise ValueError("y cannot be None")
X = _check_array(X, accept_sparse=accept_sparse,
dtype=dtype, order=order, copy=copy,
force_all_finite=force_all_finite,
ensure_2d=ensure_2d)
y = _column_or_1d(y)
if y.dtype.kind == 'O':
y = y.astype(np.float64)
# TODO: replace on daal4py
from sklearn.utils.validation import assert_all_finite
assert_all_finite(y)
lengths = [len(X), len(y)]
uniques = np.unique(lengths)
if len(uniques) > 1:
raise ValueError("Found input variables with inconsistent numbers of"
" samples: %r" % [int(length) for length in lengths])
return X, y
def _get_sample_weight(X, y, sample_weight, class_weight, classes):
n_samples = X.shape[0]
dtype = X.dtype
if n_samples == 1:
raise ValueError("n_samples=1")
sample_weight = np.asarray([]
if sample_weight is None
else sample_weight, dtype=np.float64)
sample_weight_count = sample_weight.shape[0]
if sample_weight_count != 0 and sample_weight_count != n_samples:
raise ValueError("sample_weight and X have incompatible shapes: "
"%r vs %r\n"
"Note: Sparse matrices cannot be indexed w/"
"boolean masks (use `indices=True` in CV)."
% (len(sample_weight), X.shape))
ww = None
if sample_weight_count == 0 and class_weight is None:
return ww
elif sample_weight_count == 0:
sample_weight = np.ones(n_samples, dtype=dtype)
elif isinstance(sample_weight, numbers.Number):
sample_weight = np.full(n_samples, sample_weight, dtype=dtype)
else:
sample_weight = _check_array(
sample_weight, accept_sparse=False, ensure_2d=False,
dtype=dtype, order="C"
)
if sample_weight.ndim != 1:
raise ValueError("Sample weights must be 1D array or scalar")
if sample_weight.shape != (n_samples,):
raise ValueError("sample_weight.shape == {}, expected {}!"
.format(sample_weight.shape, (n_samples,)))
if np.all(sample_weight <= 0):
raise ValueError(
'Invalid input - all samples have zero or negative weights.')
elif np.any(sample_weight <= 0):
if len(np.unique(y[sample_weight > 0])) != len(classes):
raise ValueError(
'Invalid input - all samples with positive weights '
'have the same label.')
ww = sample_weight
if class_weight is not None:
for i, v in enumerate(class_weight):
ww[y == i] *= v
if not ww.flags.c_contiguous and not ww.flags.f_contiguous:
ww = np.ascontiguousarray(ww, dtype)
return ww
def _check_is_fitted(estimator, attributes=None, *, msg=None):
if msg is None:
msg = ("This %(name)s instance is not fitted yet. Call 'fit' with "
"appropriate arguments before using this estimator.")
if not hasattr(estimator, 'fit'):
raise TypeError("%s is not an estimator instance." % (estimator))
if attributes is not None:
if not isinstance(attributes, (list, tuple)):
attributes = [attributes]
attrs = all([hasattr(estimator, attr) for attr in attributes])
else:
attrs = [v for v in vars(estimator)
if v.endswith("_") and not v.startswith("__")]
if not attrs:
raise AttributeError(msg % {'name': type(estimator).__name__})
| [
"numpy.full",
"numpy.ravel",
"numpy.asarray",
"numpy.all",
"numpy.ones",
"numpy.searchsorted",
"numpy.shape",
"numpy.any",
"sklearn.utils.validation.assert_all_finite",
"numpy.ascontiguousarray",
"numpy.unique",
"sklearn.utils.validation.check_array"
] | [((848, 861), 'numpy.asarray', 'np.asarray', (['y'], {}), '(y)\n', (858, 861), True, 'import numpy as np\n'), ((875, 886), 'numpy.shape', 'np.shape', (['y'], {}), '(y)\n', (883, 886), True, 'import numpy as np\n'), ((2196, 2230), 'numpy.unique', 'np.unique', (['y_'], {'return_inverse': '(True)'}), '(y_, return_inverse=True)\n', (2205, 2230), True, 'import numpy as np\n'), ((2832, 2983), 'sklearn.utils.validation.check_array', 'check_array', ([], {'array': 'array', 'dtype': 'dtype', 'accept_sparse': 'accept_sparse', 'order': 'order', 'copy': 'copy', 'force_all_finite': 'force_all_finite', 'ensure_2d': 'ensure_2d'}), '(array=array, dtype=dtype, accept_sparse=accept_sparse, order=\n order, copy=copy, force_all_finite=force_all_finite, ensure_2d=ensure_2d)\n', (2843, 2983), False, 'from sklearn.utils.validation import check_array\n'), ((3893, 3913), 'sklearn.utils.validation.assert_all_finite', 'assert_all_finite', (['y'], {}), '(y)\n', (3910, 3913), False, 'from sklearn.utils.validation import assert_all_finite\n'), ((3963, 3981), 'numpy.unique', 'np.unique', (['lengths'], {}), '(lengths)\n', (3972, 3981), True, 'import numpy as np\n'), ((4398, 4474), 'numpy.asarray', 'np.asarray', (['([] if sample_weight is None else sample_weight)'], {'dtype': 'np.float64'}), '([] if sample_weight is None else sample_weight, dtype=np.float64)\n', (4408, 4474), True, 'import numpy as np\n'), ((5769, 5795), 'numpy.all', 'np.all', (['(sample_weight <= 0)'], {}), '(sample_weight <= 0)\n', (5775, 5795), True, 'import numpy as np\n'), ((928, 939), 'numpy.ravel', 'np.ravel', (['y'], {}), '(y)\n', (936, 939), True, 'import numpy as np\n'), ((999, 1010), 'numpy.ravel', 'np.ravel', (['y'], {}), '(y)\n', (1007, 1010), True, 'import numpy as np\n'), ((1410, 1464), 'numpy.ones', 'np.ones', (['classes.shape[0]'], {'dtype': 'np.float64', 'order': '"""C"""'}), "(classes.shape[0], dtype=np.float64, order='C')\n", (1417, 1464), True, 'import numpy as np\n'), ((1529, 1583), 'numpy.ones', 'np.ones', (['classes.shape[0]'], {'dtype': 'np.float64', 'order': '"""C"""'}), "(classes.shape[0], dtype=np.float64, order='C')\n", (1536, 1583), True, 'import numpy as np\n'), ((2539, 2576), 'numpy.asarray', 'np.asarray', (['y'], {'dtype': 'dtype', 'order': '"""C"""'}), "(y, dtype=dtype, order='C')\n", (2549, 2576), True, 'import numpy as np\n'), ((3222, 3262), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['array', 'array.dtype'], {}), '(array, array.dtype)\n', (3242, 3262), True, 'import numpy as np\n'), ((5909, 5935), 'numpy.any', 'np.any', (['(sample_weight <= 0)'], {}), '(sample_weight <= 0)\n', (5915, 5935), True, 'import numpy as np\n'), ((6359, 6390), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['ww', 'dtype'], {}), '(ww, dtype)\n', (6379, 6390), True, 'import numpy as np\n'), ((5132, 5163), 'numpy.ones', 'np.ones', (['n_samples'], {'dtype': 'dtype'}), '(n_samples, dtype=dtype)\n', (5139, 5163), True, 'import numpy as np\n'), ((1841, 1868), 'numpy.searchsorted', 'np.searchsorted', (['classes', 'c'], {}), '(classes, c)\n', (1856, 1868), True, 'import numpy as np\n'), ((5242, 5288), 'numpy.full', 'np.full', (['n_samples', 'sample_weight'], {'dtype': 'dtype'}), '(n_samples, sample_weight, dtype=dtype)\n', (5249, 5288), True, 'import numpy as np\n'), ((5953, 5984), 'numpy.unique', 'np.unique', (['y[sample_weight > 0]'], {}), '(y[sample_weight > 0])\n', (5962, 5984), True, 'import numpy as np\n')] |
import numpy as np
import torch
from torch import nn
import sys
import re
import struct,logging
import itertools
import torchvision
import pandas as pd
import json
import numpy as np
import sys
import re
import struct
import subprocess
from subprocess import Popen
def open_or_fd(file, mode='rb'):
""" fd = open_or_fd(file)
Open file, gzipped file, pipe, or forward the file-descriptor.
Eventually seeks in the 'file' argument contains ':offset' suffix.
"""
offset = None
try:
# strip 'ark:' prefix from r{x,w}filename (optional),
if re.search('^(ark|scp)(,scp|,b|,t|,n?f|,n?p|,b?o|,n?s|,n?cs)*:', file):
(prefix,file) = file.split(':',1)
# separate offset from filename (optional),
if re.search(':[0-9]+$', file):
(file,offset) = file.rsplit(':',1)
# input pipe?
if file[-1] == '|':
fd = popen(file[:-1], 'rb') # custom,
# output pipe?
elif file[0] == '|':
fd = popen(file[1:], 'wb') # custom,
# is it gzipped?
elif file.split('.')[-1] == 'gz':
fd = gzip.open(file, mode)
# a normal file...
else:
fd = open(file, mode)
except TypeError:
# 'file' is opened file descriptor,
fd = file
# Eventually seek to offset,
if offset != None: fd.seek(int(offset))
return fd
def read_key(fd):
""" [key] = read_key(fd)
Read the utterance-key from the opened ark/stream descriptor 'fd'.
"""
assert('b' in fd.mode), "Error: 'fd' was opened in text mode (in python3 use sys.stdin.buffer)"
key = ''
while 1:
char = fd.read(1).decode("latin1")
if char == '' : break
if char == ' ' : break
key += char
key = key.strip()
if key == '': return None # end of file,
assert(re.match('^\S+$',key) != None) # check format (no whitespace!)
return key
def read_vec_flt_ark(file_or_fd):
""" generator(key,vec) = read_vec_flt_ark(file_or_fd)
Create generator of (key,vector<float>) tuples, reading from an ark file/stream.
file_or_fd : ark, gzipped ark, pipe or opened file descriptor.
Read ark to a 'dictionary':
d = { u:d for u,d in kaldi_io.read_vec_flt_ark(file) }
"""
fd = open_or_fd(file_or_fd)
try:
key = read_key(fd)
while key:
ali = read_vec_flt(fd)
yield key, ali
key = read_key(fd)
finally:
if fd is not file_or_fd : fd.close()
def read_vec_flt(file_or_fd):
""" [flt-vec] = read_vec_flt(file_or_fd)
Read kaldi float vector, ascii or binary input,
"""
fd = open_or_fd(file_or_fd)
binary = fd.read(2).decode()
if binary == '\0B': # binary flag
ans = _read_vec_flt_binary(fd)
else: # ascii,
arr = (binary + fd.readline().decode()).strip().split()
try:
arr.remove('['); arr.remove(']') # optionally
except ValueError:
pass
ans = np.array(arr, dtype=float)
if fd is not file_or_fd : fd.close() # cleanup
return ans
def _read_vec_flt_binary(fd):
header = fd.read(3).decode()
if header == 'FV ' : sample_size = 4 # floats
elif header == 'DV ' : sample_size = 8 # doubles
else : raise UnknownVectorHeader("The header contained '%s'" % header)
assert (sample_size > 0)
# Dimension,
assert (fd.read(1).decode() == '\4'); # int-size
vec_size = np.frombuffer(fd.read(4), dtype='int32', count=1)[0] # vector dim
if vec_size == 0:
return np.array([], dtype='float32')
# Read whole vector,
buf = fd.read(vec_size * sample_size)
if sample_size == 4 : ans = np.frombuffer(buf, dtype='float32')
elif sample_size == 8 : ans = np.frombuffer(buf, dtype='float64')
else : raise BadSampleSize
return ans
def load_json(filename='data.json'):
with open(filename, 'r') as outfile:
data = json.load(outfile)
return data
def write_to_json(data, filename='data.json'):
with open(filename, 'w') as outfile:
json.dump(data, outfile)
common_meta = pd.read_csv('vox2_meta.csv')
face_embed_data = load_json("../../../data/vggface2_voxceleb2_embeddings.json")
# List of face and voice IDs
# Contains the class names
dont_include = ['n003729 ' , 'n003754 ']
train_face_list, valid_face_list, test_face_list = [], [], []
train_voice_list, valid_voice_list, test_voice_list = [], [], []
for i in range(len(common_meta['Set '])):
if common_meta['Set '].iloc[i] == "dev " and common_meta['VGGFace2 ID '].iloc[i] not in dont_include:
train_face_list.append(common_meta['VGGFace2 ID '].iloc[i][:-1].strip())
train_voice_list.append(common_meta['VoxCeleb2 ID '].iloc[i][:-1].strip())
elif common_meta['Set '].iloc[i] == "test " and common_meta['VGGFace2 ID '].iloc[i][:-1] not in dont_include:
test_face_list.append(common_meta['VGGFace2 ID '].iloc[i][:-1].strip())
test_voice_list.append(common_meta['VoxCeleb2 ID '].iloc[i][:-1].strip())
train_xvec = { key.strip():vec.tolist() for key,vec in read_vec_flt_ark('../../../data/xvec_v2_train.ark')}
assert(len(list(train_xvec.keys()))==1092009)
trainval_spk2utt = {line.strip().split(' ')[0]:line.strip().split(' ')[1:] for line in open('../../../data/spk2utt_train','r').readlines()}
assert(len(list(trainval_spk2utt.keys()))==5994)
train_utt_ids = []
train_face_embeds=[]
train_labels =[]
valid_utt_ids =[]
valid_face_embeds=[]
valid_labels=[]
train_spk_list = train_voice_list
#print(len(train_voice_list),"SPK@UTT",len(list(trainval_spk2utt.keys())))
count=0
## Get voice utt iD's , labels to extract feats from train_xvec
for i in range(len(list(train_spk_list))):
## TRAIN
utt_ids = trainval_spk2utt[train_spk_list[i]][:20]
face_ids = face_embed_data[train_face_list[i]][:20]
labels = [i] *20
train_utt_ids.extend(utt_ids)
train_face_embeds.extend(face_ids)
train_labels.extend(labels)
## VALID
utt_ids = trainval_spk2utt[train_spk_list[i]][20:25]
if len(utt_ids) < 5:
#print('INIT LEN ',len(utt_ids),utt_ids)
diff = -(len(utt_ids)-5)
#print('DIFF is',diff,"Factor is ",diff//len(utt_ids)+1)
utt_ids = utt_ids * (diff//len(utt_ids)+1)
#print('LATER LEN ',len(utt_ids),utt_ids)
if len(utt_ids)-5 !=0:
diff = -(len(utt_ids)-5)
#print('SECOND DIFF is',diff)
utt_ids = utt_ids + utt_ids[:diff]
#print('FINAL LEN IS',len(utt_ids))
assert(len(utt_ids)==5)
#print(train_spk_list[i],len(trainval_spk2utt[train_spk_list[i]]))
face_ids = face_embed_data[train_face_list[i]][20:25]
labels = [i] *25
valid_utt_ids.extend(utt_ids)
valid_face_embeds.extend(face_ids)
valid_labels.extend(labels)
full_data =[]
for i in list(train_xvec.keys()):
full_data.append(train_xvec[i])
full_data = np.array(full_data)
test_xvec = { key.strip():vec.tolist() for key,vec in read_vec_flt_ark('../../../data/xvec_v2_test.ark')}
assert(len(list(test_xvec.keys()))==36237)
test_spk2utt = {line.strip().split(' ')[0]:line.strip().split(' ')[1:] for line in open('../../../data/spk2utt_test','r').readlines()}
assert(len(list(test_spk2utt.keys()))==118)
test_data = []
for i in list(test_xvec.keys()):
test_data.append(test_xvec[i])
test_data = np.array(test_data)
total_data = np.concatenate((full_data,test_data),axis=0)
mx = np.max(total_data,axis=0)
mn = np.min(total_data,axis=0)
data = -1 +(2*(full_data - mn)) / (mx-mn)
new_test = -1 +(2*(test_data - mn)) / (mx-mn)
norm_train={}
for e,i in enumerate(list(train_xvec.keys())):
norm_train[i]=data[e].tolist()
norm_test ={}
for e,i in enumerate(list(test_xvec.keys())):
norm_test[i]=new_test[e].tolist()
write_to_json(norm_train,'../../../data/norm_train_xvecs.json')
write_to_json(norm_test,'../../../data/norm_test_xvecs.json')
| [
"json.dump",
"json.load",
"pandas.read_csv",
"numpy.frombuffer",
"re.match",
"numpy.max",
"numpy.min",
"numpy.array",
"re.search",
"numpy.concatenate"
] | [((4105, 4133), 'pandas.read_csv', 'pd.read_csv', (['"""vox2_meta.csv"""'], {}), "('vox2_meta.csv')\n", (4116, 4133), True, 'import pandas as pd\n'), ((6904, 6923), 'numpy.array', 'np.array', (['full_data'], {}), '(full_data)\n', (6912, 6923), True, 'import numpy as np\n'), ((7349, 7368), 'numpy.array', 'np.array', (['test_data'], {}), '(test_data)\n', (7357, 7368), True, 'import numpy as np\n'), ((7383, 7429), 'numpy.concatenate', 'np.concatenate', (['(full_data, test_data)'], {'axis': '(0)'}), '((full_data, test_data), axis=0)\n', (7397, 7429), True, 'import numpy as np\n'), ((7433, 7459), 'numpy.max', 'np.max', (['total_data'], {'axis': '(0)'}), '(total_data, axis=0)\n', (7439, 7459), True, 'import numpy as np\n'), ((7464, 7490), 'numpy.min', 'np.min', (['total_data'], {'axis': '(0)'}), '(total_data, axis=0)\n', (7470, 7490), True, 'import numpy as np\n'), ((577, 646), 're.search', 're.search', (['"""^(ark|scp)(,scp|,b|,t|,n?f|,n?p|,b?o|,n?s|,n?cs)*:"""', 'file'], {}), "('^(ark|scp)(,scp|,b|,t|,n?f|,n?p|,b?o|,n?s|,n?cs)*:', file)\n", (586, 646), False, 'import re\n'), ((757, 784), 're.search', 're.search', (['""":[0-9]+$"""', 'file'], {}), "(':[0-9]+$', file)\n", (766, 784), False, 'import re\n'), ((1848, 1871), 're.match', 're.match', (['"""^\\\\S+$"""', 'key'], {}), "('^\\\\S+$', key)\n", (1856, 1871), False, 'import re\n'), ((3007, 3033), 'numpy.array', 'np.array', (['arr'], {'dtype': 'float'}), '(arr, dtype=float)\n', (3015, 3033), True, 'import numpy as np\n'), ((3559, 3588), 'numpy.array', 'np.array', (['[]'], {'dtype': '"""float32"""'}), "([], dtype='float32')\n", (3567, 3588), True, 'import numpy as np\n'), ((3688, 3723), 'numpy.frombuffer', 'np.frombuffer', (['buf'], {'dtype': '"""float32"""'}), "(buf, dtype='float32')\n", (3701, 3723), True, 'import numpy as np\n'), ((3933, 3951), 'json.load', 'json.load', (['outfile'], {}), '(outfile)\n', (3942, 3951), False, 'import json\n'), ((4066, 4090), 'json.dump', 'json.dump', (['data', 'outfile'], {}), '(data, outfile)\n', (4075, 4090), False, 'import json\n'), ((3758, 3793), 'numpy.frombuffer', 'np.frombuffer', (['buf'], {'dtype': '"""float64"""'}), "(buf, dtype='float64')\n", (3771, 3793), True, 'import numpy as np\n')] |
import numpy as np
from distfit import distfit
def test_distfit():
X = np.random.normal(0, 2, 1000)
y = [-14,-8,-6,0,1,2,3,4,5,6,7,8,9,10,11,15]
# Initialize
dist = distfit()
assert np.all(np.isin(['method', 'alpha', 'bins', 'distr', 'multtest', 'n_perm'], dir(dist)))
# Fit and transform data
dist.fit_transform(X, verbose=3)
# TEST 1: check output is unchanged
assert np.all(np.isin(['method', 'model', 'summary', 'histdata', 'size'], dir(dist)))
# TEST 2: Check model output is unchanged
assert [*dist.model.keys()]==['distr', 'stats', 'params', 'name', 'model', 'score', 'loc', 'scale', 'arg', 'CII_min_alpha', 'CII_max_alpha']
# TEST 3: Check specific distribution
dist = distfit(distr='t')
dist.fit_transform(X)
assert dist.model['name']=='t'
# TEST 4: Check specific distribution
dist = distfit(distr='t', alpha=None)
dist.fit_transform(X)
assert dist.model['CII_min_alpha'] is not None
assert dist.model['CII_max_alpha'] is not None
# TEST 4A: Check multiple distribution
dist = distfit(distr=['norm', 't', 'gamma'])
results = dist.fit_transform(X)
assert np.all(np.isin(results['summary']['distr'].values, ['gamma', 't', 'norm']))
# TEST 5: Bound check
dist = distfit(distr='t', bound='up', alpha=0.05)
dist.fit_transform(X, verbose=0)
assert dist.model['CII_min_alpha'] is None
assert dist.model['CII_max_alpha'] is not None
dist = distfit(distr='t', bound='down', alpha=0.05)
dist.fit_transform(X, verbose=0)
assert dist.model['CII_min_alpha'] is not None
assert dist.model['CII_max_alpha'] is None
dist = distfit(distr='t', bound='both', alpha=0.05)
dist.fit_transform(X, verbose=0)
assert dist.model['CII_min_alpha'] is not None
assert dist.model['CII_max_alpha'] is not None
# TEST 6: Distribution check: Make sure the right loc and scale paramters are detected
X = np.random.normal(0, 2, 10000)
dist = distfit(distr='norm', alpha=0.05)
dist.fit_transform(X, verbose=0)
dist.model['loc']
'%.1f' %dist.model['scale']=='2.0'
'%.1f' %np.abs(dist.model['loc'])=='0.0'
# TEST 7
X = np.random.normal(0, 2, 1000)
y = [-14,-8,-6,0,1,2,3,4,5,6,7,8,9,10,11,15]
# TEST 1: Check bounds
out1 = distfit(distr='norm', bound='up')
out1.fit_transform(X, verbose=0)
out1.predict(y, verbose=0)
assert np.all(np.isin(np.unique(out1.results['y_pred']), ['none','up']))
out2 = distfit(distr='norm', bound='down')
out2.fit_transform(X, verbose=0)
out2.predict(y, verbose=0)
assert np.all(np.isin(np.unique(out2.results['y_pred']), ['none','down']))
out3 = distfit(distr='norm', bound='down')
out3.fit_transform(X, verbose=0)
out3.predict(y, verbose=0)
assert np.all(np.isin(np.unique(out3.results['y_pred']), ['none','down','up']))
# TEST 8: Check different sizes array
X = np.random.normal(0, 2, [10,100])
dist = distfit(distr='norm', bound='up')
dist.fit_transform(X, verbose=0)
dist.predict(y, verbose=0)
assert np.all(np.isin(np.unique(dist.results['y_pred']), ['none','up']))
# TEST 9
data_random = np.random.normal(0, 2, 1000)
data = [-14,-8,-6,0,1,2,3,4,5,6,7,8,9,10,11,15]
dist = distfit()
dist.fit_transform(X, verbose=0)
# TEST 10 Check number of output probabilities
dist.fit_transform(X, verbose=0)
dist.predict(y)
assert dist.results['y_proba'].shape[0]==len(y)
# TEST 11: Check whether alpha responds on results
out1 = distfit(alpha=0.05)
out1.fit_transform(X, verbose=0)
out1.predict(y)
out2 = distfit(alpha=0.2)
out2.fit_transform(X, verbose=0)
out2.predict(y)
assert np.all(out1.y_proba==out2.y_proba)
assert not np.all(out1.results['y_pred']==out2.results['y_pred'])
assert np.all(out1.results['P']==out2.results['P'])
assert sum(out1.results['y_pred']=='none')>sum(out2.results['y_pred']=='none')
# TEST 12: Check different sizes array
X = np.random.normal(0, 2, [10,100])
y = [-14,-8,-6,0,1,2,3,4,5,6,7,8,9,10,11,15]
dist = distfit(bound='up')
dist.fit_transform(X, verbose=0)
dist.predict(y)
assert np.all(np.isin(np.unique(dist.results['y_pred']), ['none','up']))
# TEST 13: Precentile
X = np.random.normal(0, 2, [10,100])
y = [-14,-8,-6,0,1,2,3,4,5,6,7,8,9,10,11,15]
dist = distfit(method='percentile')
dist.fit_transform(X, verbose=0)
results=dist.predict(y)
assert np.all(np.isin([*results.keys()], ['y', 'y_proba', 'y_pred', 'P', 'teststat']))
# TEST 14: Quantile
dist = distfit(method='quantile')
dist.fit_transform(X, verbose=0)
results=dist.predict(y)
assert np.all(np.isin([*results.keys()], ['y', 'y_proba', 'y_pred', 'teststat']))
# TEST 15: Discrete
import random
random.seed(10)
from scipy.stats import binom
# Generate random numbers
X = binom(8, 0.5).rvs(10000)
dist = distfit(method='discrete', f=1.5, weighted=True)
dist.fit_transform(X, verbose=3)
assert dist.model['n']==8
assert np.round(dist.model['p'], decimals=1)==0.5
# check output is unchanged
assert np.all(np.isin(['method', 'model', 'summary', 'histdata', 'size'], dir(dist)))
# TEST 15A
assert [*dist.model.keys()]==['name', 'distr', 'model', 'params', 'score', 'chi2r', 'n', 'p', 'CII_min_alpha', 'CII_max_alpha']
# TEST 15B
results = dist.predict([0, 1, 10, 11, 12])
assert np.all(np.isin([*results.keys()], ['y', 'y_proba', 'y_pred', 'P']))
| [
"numpy.isin",
"numpy.abs",
"numpy.unique",
"scipy.stats.binom",
"random.seed",
"numpy.random.normal",
"distfit.distfit",
"numpy.round",
"numpy.all"
] | [((76, 104), 'numpy.random.normal', 'np.random.normal', (['(0)', '(2)', '(1000)'], {}), '(0, 2, 1000)\n', (92, 104), True, 'import numpy as np\n'), ((182, 191), 'distfit.distfit', 'distfit', ([], {}), '()\n', (189, 191), False, 'from distfit import distfit\n'), ((732, 750), 'distfit.distfit', 'distfit', ([], {'distr': '"""t"""'}), "(distr='t')\n", (739, 750), False, 'from distfit import distfit\n'), ((866, 896), 'distfit.distfit', 'distfit', ([], {'distr': '"""t"""', 'alpha': 'None'}), "(distr='t', alpha=None)\n", (873, 896), False, 'from distfit import distfit\n'), ((1080, 1117), 'distfit.distfit', 'distfit', ([], {'distr': "['norm', 't', 'gamma']"}), "(distr=['norm', 't', 'gamma'])\n", (1087, 1117), False, 'from distfit import distfit\n'), ((1279, 1321), 'distfit.distfit', 'distfit', ([], {'distr': '"""t"""', 'bound': '"""up"""', 'alpha': '(0.05)'}), "(distr='t', bound='up', alpha=0.05)\n", (1286, 1321), False, 'from distfit import distfit\n'), ((1468, 1512), 'distfit.distfit', 'distfit', ([], {'distr': '"""t"""', 'bound': '"""down"""', 'alpha': '(0.05)'}), "(distr='t', bound='down', alpha=0.05)\n", (1475, 1512), False, 'from distfit import distfit\n'), ((1659, 1703), 'distfit.distfit', 'distfit', ([], {'distr': '"""t"""', 'bound': '"""both"""', 'alpha': '(0.05)'}), "(distr='t', bound='both', alpha=0.05)\n", (1666, 1703), False, 'from distfit import distfit\n'), ((1943, 1972), 'numpy.random.normal', 'np.random.normal', (['(0)', '(2)', '(10000)'], {}), '(0, 2, 10000)\n', (1959, 1972), True, 'import numpy as np\n'), ((1984, 2017), 'distfit.distfit', 'distfit', ([], {'distr': '"""norm"""', 'alpha': '(0.05)'}), "(distr='norm', alpha=0.05)\n", (1991, 2017), False, 'from distfit import distfit\n'), ((2183, 2211), 'numpy.random.normal', 'np.random.normal', (['(0)', '(2)', '(1000)'], {}), '(0, 2, 1000)\n', (2199, 2211), True, 'import numpy as np\n'), ((2300, 2333), 'distfit.distfit', 'distfit', ([], {'distr': '"""norm"""', 'bound': '"""up"""'}), "(distr='norm', bound='up')\n", (2307, 2333), False, 'from distfit import distfit\n'), ((2492, 2527), 'distfit.distfit', 'distfit', ([], {'distr': '"""norm"""', 'bound': '"""down"""'}), "(distr='norm', bound='down')\n", (2499, 2527), False, 'from distfit import distfit\n'), ((2688, 2723), 'distfit.distfit', 'distfit', ([], {'distr': '"""norm"""', 'bound': '"""down"""'}), "(distr='norm', bound='down')\n", (2695, 2723), False, 'from distfit import distfit\n'), ((2928, 2961), 'numpy.random.normal', 'np.random.normal', (['(0)', '(2)', '[10, 100]'], {}), '(0, 2, [10, 100])\n', (2944, 2961), True, 'import numpy as np\n'), ((2972, 3005), 'distfit.distfit', 'distfit', ([], {'distr': '"""norm"""', 'bound': '"""up"""'}), "(distr='norm', bound='up')\n", (2979, 3005), False, 'from distfit import distfit\n'), ((3184, 3212), 'numpy.random.normal', 'np.random.normal', (['(0)', '(2)', '(1000)'], {}), '(0, 2, 1000)\n', (3200, 3212), True, 'import numpy as np\n'), ((3276, 3285), 'distfit.distfit', 'distfit', ([], {}), '()\n', (3283, 3285), False, 'from distfit import distfit\n'), ((3551, 3570), 'distfit.distfit', 'distfit', ([], {'alpha': '(0.05)'}), '(alpha=0.05)\n', (3558, 3570), False, 'from distfit import distfit\n'), ((3640, 3658), 'distfit.distfit', 'distfit', ([], {'alpha': '(0.2)'}), '(alpha=0.2)\n', (3647, 3658), False, 'from distfit import distfit\n'), ((3728, 3764), 'numpy.all', 'np.all', (['(out1.y_proba == out2.y_proba)'], {}), '(out1.y_proba == out2.y_proba)\n', (3734, 3764), True, 'import numpy as np\n'), ((3844, 3890), 'numpy.all', 'np.all', (["(out1.results['P'] == out2.results['P'])"], {}), "(out1.results['P'] == out2.results['P'])\n", (3850, 3890), True, 'import numpy as np\n'), ((4024, 4057), 'numpy.random.normal', 'np.random.normal', (['(0)', '(2)', '[10, 100]'], {}), '(0, 2, [10, 100])\n', (4040, 4057), True, 'import numpy as np\n'), ((4118, 4137), 'distfit.distfit', 'distfit', ([], {'bound': '"""up"""'}), "(bound='up')\n", (4125, 4137), False, 'from distfit import distfit\n'), ((4307, 4340), 'numpy.random.normal', 'np.random.normal', (['(0)', '(2)', '[10, 100]'], {}), '(0, 2, [10, 100])\n', (4323, 4340), True, 'import numpy as np\n'), ((4400, 4428), 'distfit.distfit', 'distfit', ([], {'method': '"""percentile"""'}), "(method='percentile')\n", (4407, 4428), False, 'from distfit import distfit\n'), ((4621, 4647), 'distfit.distfit', 'distfit', ([], {'method': '"""quantile"""'}), "(method='quantile')\n", (4628, 4647), False, 'from distfit import distfit\n'), ((4847, 4862), 'random.seed', 'random.seed', (['(10)'], {}), '(10)\n', (4858, 4862), False, 'import random\n'), ((4972, 5020), 'distfit.distfit', 'distfit', ([], {'method': '"""discrete"""', 'f': '(1.5)', 'weighted': '(True)'}), "(method='discrete', f=1.5, weighted=True)\n", (4979, 5020), False, 'from distfit import distfit\n'), ((1172, 1239), 'numpy.isin', 'np.isin', (["results['summary']['distr'].values", "['gamma', 't', 'norm']"], {}), "(results['summary']['distr'].values, ['gamma', 't', 'norm'])\n", (1179, 1239), True, 'import numpy as np\n'), ((3778, 3834), 'numpy.all', 'np.all', (["(out1.results['y_pred'] == out2.results['y_pred'])"], {}), "(out1.results['y_pred'] == out2.results['y_pred'])\n", (3784, 3834), True, 'import numpy as np\n'), ((5099, 5136), 'numpy.round', 'np.round', (["dist.model['p']"], {'decimals': '(1)'}), "(dist.model['p'], decimals=1)\n", (5107, 5136), True, 'import numpy as np\n'), ((2128, 2153), 'numpy.abs', 'np.abs', (["dist.model['loc']"], {}), "(dist.model['loc'])\n", (2134, 2153), True, 'import numpy as np\n'), ((2429, 2462), 'numpy.unique', 'np.unique', (["out1.results['y_pred']"], {}), "(out1.results['y_pred'])\n", (2438, 2462), True, 'import numpy as np\n'), ((2623, 2656), 'numpy.unique', 'np.unique', (["out2.results['y_pred']"], {}), "(out2.results['y_pred'])\n", (2632, 2656), True, 'import numpy as np\n'), ((2819, 2852), 'numpy.unique', 'np.unique', (["out3.results['y_pred']"], {}), "(out3.results['y_pred'])\n", (2828, 2852), True, 'import numpy as np\n'), ((3101, 3134), 'numpy.unique', 'np.unique', (["dist.results['y_pred']"], {}), "(dist.results['y_pred'])\n", (3110, 3134), True, 'import numpy as np\n'), ((4221, 4254), 'numpy.unique', 'np.unique', (["dist.results['y_pred']"], {}), "(dist.results['y_pred'])\n", (4230, 4254), True, 'import numpy as np\n'), ((4935, 4948), 'scipy.stats.binom', 'binom', (['(8)', '(0.5)'], {}), '(8, 0.5)\n', (4940, 4948), False, 'from scipy.stats import binom\n')] |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
#loading the data from data directory
anti_ferromagnetic = np.load('./data/anti-ferromagnetic.npy')
fig = plt.figure()
frames = [] #empty list to put snaps of lattice in#
for i in range(int(anti_ferromagnetic.shape[0])):
Snaps = anti_ferromagnetic[i]
img = plt.imshow(Snaps, interpolation='none', animated=True)
frames.append([img]) #puts the snaps in the list#
ani = animation.ArtistAnimation(fig, frames, interval=10, blit=True)
plt.show()
plt.close() | [
"numpy.load",
"matplotlib.pyplot.show",
"matplotlib.pyplot.close",
"matplotlib.pyplot.imshow",
"matplotlib.animation.ArtistAnimation",
"matplotlib.pyplot.figure"
] | [((156, 196), 'numpy.load', 'np.load', (['"""./data/anti-ferromagnetic.npy"""'], {}), "('./data/anti-ferromagnetic.npy')\n", (163, 196), True, 'import numpy as np\n'), ((204, 216), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (214, 216), True, 'import matplotlib.pyplot as plt\n'), ((609, 671), 'matplotlib.animation.ArtistAnimation', 'animation.ArtistAnimation', (['fig', 'frames'], {'interval': '(10)', 'blit': '(True)'}), '(fig, frames, interval=10, blit=True)\n', (634, 671), True, 'import matplotlib.animation as animation\n'), ((674, 684), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (682, 684), True, 'import matplotlib.pyplot as plt\n'), ((685, 696), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (694, 696), True, 'import matplotlib.pyplot as plt\n'), ((447, 501), 'matplotlib.pyplot.imshow', 'plt.imshow', (['Snaps'], {'interpolation': '"""none"""', 'animated': '(True)'}), "(Snaps, interpolation='none', animated=True)\n", (457, 501), True, 'import matplotlib.pyplot as plt\n')] |
import gc
import multiprocessing
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
def gen_params():
from math import ceil
from itertools import chain
for width in chain(
# range(2, 100, 1),
# range(70, 100, 1)
range(50, 100, 5),
# range(100, 650, 50)
):
_max = ceil((width - 1) ** 2 / width ** 2 * 100)
for params in ((width, width, float(f'0.{f:02d}'), b) for f in range(
1,
_max,
2
) for b in (
True,
# False
)):
yield params
def simu(params):
import time
from minesweeper.logic import Field
from alt_generate import Dummy
width, height, mines, shuffle = params
gc.disable()
s = time.time_ns()
f = (Field if shuffle else Dummy)(width, height, int(width * height * mines))
f.generate()
e = time.time_ns()
execution_time = (e - s) / 1E6
gc.collect()
for _ in range(0, 10):
s = time.time_ns()
f = (Field if shuffle else Dummy)(width, height, int(width * height * mines))
f.generate()
e = time.time_ns()
execution_time = execution_time / 2 + (e - s) / 2E6
gc.collect()
mt = width * height / ((width - 1) * (height - 1))
if (width % 10 == 0 and width < 100 or width % 100 == 0 and width < 1000 or width % 1000 == 0) and mines >= mt:
print(f'Done with w={width},h={width},s={shuffle}')
return *params, execution_time
def plot(data: np.ndarray, below: int):
fig, ax = plt.subplots(subplot_kw={"projection": "3d"})
ax: Axes3D
data_shuffle = data[np.logical_and(data[:, -2] == True, data[:, 1] < below)]
data_rand_2d = data[np.logical_and(np.logical_not(data[:, -2] == True), data[:, 1] < below)]
for _data, label, cm in zip(
[data_shuffle, data_rand_2d],
['shuffle', 'rand_2d (bright)'],
[plt.cm.coolwarm, plt.cm.bwr]
):
if len(_data) == 0:
continue
surf = ax.plot_trisurf(
_data[:, 0],
_data[:, 2],
_data[:, -1],
# cmap=cm,
linewidth=1,
# shade=False,
label=label,
alpha=0.5,
zorder=10
)
surf._facecolors2d = surf._facecolor3d
surf._edgecolors2d = surf._edgecolor3d
ax.set_xlabel('Width/Height (n)')
ax.set_ylabel('Mines (%)')
ax.set_zlabel('Execution Time (ms)')
plt.legend()
plt.show()
if __name__ == '__main__':
import os
plt.switch_backend('macosx')
path = os.path.join(__file__.replace('/main.py', ''), 'cachefile.npy')
print(path)
if not os.path.exists(path):
with multiprocessing.Pool() as p:
data = np.asarray(p.map(simu, gen_params()))
print('Saving...')
np.save(path, data)
print('Done')
gc.enable()
else:
print('Loading...')
data = np.load(path)
print('Done')
plot(data, 1000)
plot(data, 100)
| [
"matplotlib.pyplot.switch_backend",
"numpy.load",
"numpy.save",
"gc.disable",
"matplotlib.pyplot.show",
"numpy.logical_and",
"math.ceil",
"matplotlib.pyplot.legend",
"numpy.logical_not",
"os.path.exists",
"gc.enable",
"gc.collect",
"time.time_ns",
"multiprocessing.Pool",
"matplotlib.pypl... | [((866, 878), 'gc.disable', 'gc.disable', ([], {}), '()\n', (876, 878), False, 'import gc\n'), ((888, 902), 'time.time_ns', 'time.time_ns', ([], {}), '()\n', (900, 902), False, 'import time\n'), ((1010, 1024), 'time.time_ns', 'time.time_ns', ([], {}), '()\n', (1022, 1024), False, 'import time\n'), ((1064, 1076), 'gc.collect', 'gc.collect', ([], {}), '()\n', (1074, 1076), False, 'import gc\n'), ((1671, 1716), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'subplot_kw': "{'projection': '3d'}"}), "(subplot_kw={'projection': '3d'})\n", (1683, 1716), True, 'import matplotlib.pyplot as plt\n'), ((2603, 2615), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (2613, 2615), True, 'import matplotlib.pyplot as plt\n'), ((2620, 2630), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2628, 2630), True, 'import matplotlib.pyplot as plt\n'), ((2679, 2707), 'matplotlib.pyplot.switch_backend', 'plt.switch_backend', (['"""macosx"""'], {}), "('macosx')\n", (2697, 2707), True, 'import matplotlib.pyplot as plt\n'), ((378, 419), 'math.ceil', 'ceil', (['((width - 1) ** 2 / width ** 2 * 100)'], {}), '((width - 1) ** 2 / width ** 2 * 100)\n', (382, 419), False, 'from math import ceil\n'), ((1117, 1131), 'time.time_ns', 'time.time_ns', ([], {}), '()\n', (1129, 1131), False, 'import time\n'), ((1251, 1265), 'time.time_ns', 'time.time_ns', ([], {}), '()\n', (1263, 1265), False, 'import time\n'), ((1334, 1346), 'gc.collect', 'gc.collect', ([], {}), '()\n', (1344, 1346), False, 'import gc\n'), ((1757, 1812), 'numpy.logical_and', 'np.logical_and', (['(data[:, -2] == True)', '(data[:, 1] < below)'], {}), '(data[:, -2] == True, data[:, 1] < below)\n', (1771, 1812), True, 'import numpy as np\n'), ((2811, 2831), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (2825, 2831), False, 'import os\n'), ((2967, 2986), 'numpy.save', 'np.save', (['path', 'data'], {}), '(path, data)\n', (2974, 2986), True, 'import numpy as np\n'), ((3017, 3028), 'gc.enable', 'gc.enable', ([], {}), '()\n', (3026, 3028), False, 'import gc\n'), ((3082, 3095), 'numpy.load', 'np.load', (['path'], {}), '(path)\n', (3089, 3095), True, 'import numpy as np\n'), ((1853, 1888), 'numpy.logical_not', 'np.logical_not', (['(data[:, -2] == True)'], {}), '(data[:, -2] == True)\n', (1867, 1888), True, 'import numpy as np\n'), ((2846, 2868), 'multiprocessing.Pool', 'multiprocessing.Pool', ([], {}), '()\n', (2866, 2868), False, 'import multiprocessing\n')] |
from sklearn.externals import joblib
from skimage import feature as skft
from sklearn import svm
import re
import os
from tqdm import tqdm
import numpy as np
import cv2
from numpy import *
import json
import copy
import tensorflow as tf
train_label=np.zeros( (2700) )
train_data=np.zeros((2700,512,512))
array_img = []
#读取训练集数据
def read_train_image(path):
print("-" * 50)
print("训练集读取")
'''读取路径下所有子文件夹中的图片并存入list'''
train = []
dir_counter = 0
x=0
i=0
h=-1
for child_dir in os.listdir(path):
child_path = os.path.join(path, child_dir)
h += 1
for dir_image in tqdm(os.listdir(child_path)):
img = cv2.imread(child_path + "\\" + dir_image, cv2.IMREAD_COLOR)
img=cv2.resize(img,(512,512))
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
data=np.zeros((512,512))
data[0:img.shape[0],0:img.shape[1]] = img
train_data[i, :, :] = data[0:512, 0:512]
train_label[x] = h
i += 1
x += 1
dir_counter += 1
train.append(train_label)
train.append(train_data)
return train
#读取测试集数据
def read_test_img(path):
'''读取路径下所有子文件夹中的图片并存入list'''
dir_counter = 0
i=0
x=0
h = -1
test=[]
test_label = np.zeros((300))
test_data=np.zeros((300,512,512))
for child_dir in os.listdir(path):
child_path = os.path.join(path, child_dir)
h += 1
for dir_image in tqdm(os.listdir(child_path)):
array_img.append(dir_image)
img = cv2.imread(child_path + "\\" + dir_image, cv2.IMREAD_COLOR)
img=cv2.resize(img,(512,512))
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
data=np.zeros((512,512))
data[0:img.shape[0],0:img.shape[1]] = img
test_data[i, :, :] = data[0:512, 0:512]
test_label[x] = h
x +=1
i += 1
dir_counter += 1
test.append(test_label)
test.append(test_data)
print(test[1])
return test
def texture_detect():
radius = 1
n_point = radius * 8
train_hist = np.zeros( (2700,256) )
test_hist = np.zeros( (300,256) )
for i in np.arange(2700):
#使用LBP方法提取图像的纹理特征.
lbp=skft.local_binary_pattern(train_data[i],n_point,radius,'default')
#统计图像的直方图
max_bins = int(lbp.max() + 1)
#hist size:256
train_hist[i], _ = np.histogram(lbp, normed=True, bins=max_bins, range=(0, max_bins))
for i in np.arange(300):
lbp = skft.local_binary_pattern(test_data[i],n_point,radius,'default')
# print("图像识别")
# print(图像识别)
# print(图像识别.shape)
#统计图像的直方图
max_bins = int(lbp.max() + 1)
#hist size:256
test_hist[i], _ = np.histogram(lbp, normed=True, bins=max_bins, range=(0, max_bins))
return train_hist,test_hist
list=[]
def liy():
train_hist, test_hist = texture_detect()
classifier=svm.SVC(C=5000,kernel='rbf',gamma=20,decision_function_shape='ovr', probability=True)#C是惩罚系数,即对误差的宽容度;C越小,容易欠拟合。C过大或过小,泛化能力变差; gamma越大,支持向量越少,gamma值越小,支持向量越多。支持向量的个数影响训练与预测的速度。gamma值越大映射的维度越高,训练的结果越好,但是越容易引起过拟合,即泛化能力低。
# print("train_hist")
# print(train_hist)
# print("train_hist.shape")
# print(train_hist.shape)
classifier.fit(train_hist,train_label.ravel())
joblib.dump(classifier, "lbp_model.ckpt")
clf = joblib.load("lbp_model.ckpt")
predict_gailv = clf.predict_proba(test_hist)
predict_gailv =predict_gailv.tolist()
print(predict_gailv)
for index in range(len(predict_gailv)):
predict = max(predict_gailv[index])
label = predict_gailv[index].index(max(predict_gailv[index]))
list.append(label)
#保存结果
tlist =[]
#list1 = []
#dict = {}
# i=0
# while i< 300 :
# key=array_img[i]
# #ret = re.match("[a-zA-Z0-9_]*",key)
# value =int(test_label[i])
# #[ { "image_id": "prcv2019test05213.jpg", "disease_class":1 }, ...]
# try:
#
# dict = {}
# dict["image_id"] = key
# dict["disease_class"] = value
# dict["test_hist"]=test_hist
# print("字典输入%d",dict)
# tlist.append(dict)
# #print(list)
# # if i%1 == 0:
# # list.append('\n')
# except Exception as f:
# print("没有添加")
# i += 1
# print("~"*80)
# with open('图像识别.txt', 'w') as f:
# for i in list:
# json_str = json.dumps(i)
# f.writelines(json_str+"\n")
# print("~"*80)
# print(tlist)
# print("~" * 80)
# print('训练集:',classifier.score(train_hist,train_label))
def acc(acc1,acc2):
i = 0
j = 0
h = 0
while i<len(acc1) and j<len(acc2):
if acc1[i] == acc2[j]:
h += 1
i += 1
j += 1
else:
i += 1
j += 1
l = len(acc1)
acc = h / l
return acc
if __name__ == '__main__':
image_path='train2700'#训练集路径
train =read_train_image(image_path)
# print(train)
train_label = train[0]
# print(train_label)
train_data = train[1]
print(train_data)
print("-" * 50)
print("测试集读取")
image_path='test300'#测试集路径
test=read_test_img(image_path)
test_label=test[0]
test_data=test[1]
liy()
shibiejieguo= array(list)
test_label=np.array(test_label,dtype=np.int)
test_acc = acc(shibiejieguo, test_label)
print('test_acc:', test_acc)
print('test_label:',test_label)
# print('test_label type:',type(test_label))
print('list:',shibiejieguo)
#print('list type',type(shibiejieguo))
| [
"sklearn.externals.joblib.dump",
"skimage.feature.local_binary_pattern",
"cv2.cvtColor",
"numpy.zeros",
"cv2.imread",
"sklearn.externals.joblib.load",
"numpy.histogram",
"numpy.arange",
"numpy.array",
"sklearn.svm.SVC",
"os.path.join",
"os.listdir",
"cv2.resize"
] | [((264, 278), 'numpy.zeros', 'np.zeros', (['(2700)'], {}), '(2700)\n', (272, 278), True, 'import numpy as np\n'), ((295, 321), 'numpy.zeros', 'np.zeros', (['(2700, 512, 512)'], {}), '((2700, 512, 512))\n', (303, 321), True, 'import numpy as np\n'), ((550, 566), 'os.listdir', 'os.listdir', (['path'], {}), '(path)\n', (560, 566), False, 'import os\n'), ((1388, 1401), 'numpy.zeros', 'np.zeros', (['(300)'], {}), '(300)\n', (1396, 1401), True, 'import numpy as np\n'), ((1420, 1445), 'numpy.zeros', 'np.zeros', (['(300, 512, 512)'], {}), '((300, 512, 512))\n', (1428, 1445), True, 'import numpy as np\n'), ((1467, 1483), 'os.listdir', 'os.listdir', (['path'], {}), '(path)\n', (1477, 1483), False, 'import os\n'), ((2282, 2303), 'numpy.zeros', 'np.zeros', (['(2700, 256)'], {}), '((2700, 256))\n', (2290, 2303), True, 'import numpy as np\n'), ((2322, 2342), 'numpy.zeros', 'np.zeros', (['(300, 256)'], {}), '((300, 256))\n', (2330, 2342), True, 'import numpy as np\n'), ((2358, 2373), 'numpy.arange', 'np.arange', (['(2700)'], {}), '(2700)\n', (2367, 2373), True, 'import numpy as np\n'), ((2675, 2689), 'numpy.arange', 'np.arange', (['(300)'], {}), '(300)\n', (2684, 2689), True, 'import numpy as np\n'), ((3148, 3240), 'sklearn.svm.SVC', 'svm.SVC', ([], {'C': '(5000)', 'kernel': '"""rbf"""', 'gamma': '(20)', 'decision_function_shape': '"""ovr"""', 'probability': '(True)'}), "(C=5000, kernel='rbf', gamma=20, decision_function_shape='ovr',\n probability=True)\n", (3155, 3240), False, 'from sklearn import svm\n'), ((3542, 3583), 'sklearn.externals.joblib.dump', 'joblib.dump', (['classifier', '"""lbp_model.ckpt"""'], {}), "(classifier, 'lbp_model.ckpt')\n", (3553, 3583), False, 'from sklearn.externals import joblib\n'), ((3595, 3624), 'sklearn.externals.joblib.load', 'joblib.load', (['"""lbp_model.ckpt"""'], {}), "('lbp_model.ckpt')\n", (3606, 3624), False, 'from sklearn.externals import joblib\n'), ((5665, 5699), 'numpy.array', 'np.array', (['test_label'], {'dtype': 'np.int'}), '(test_label, dtype=np.int)\n', (5673, 5699), True, 'import numpy as np\n'), ((591, 620), 'os.path.join', 'os.path.join', (['path', 'child_dir'], {}), '(path, child_dir)\n', (603, 620), False, 'import os\n'), ((1508, 1537), 'os.path.join', 'os.path.join', (['path', 'child_dir'], {}), '(path, child_dir)\n', (1520, 1537), False, 'import os\n'), ((2416, 2484), 'skimage.feature.local_binary_pattern', 'skft.local_binary_pattern', (['train_data[i]', 'n_point', 'radius', '"""default"""'], {}), "(train_data[i], n_point, radius, 'default')\n", (2441, 2484), True, 'from skimage import feature as skft\n'), ((2594, 2660), 'numpy.histogram', 'np.histogram', (['lbp'], {'normed': '(True)', 'bins': 'max_bins', 'range': '(0, max_bins)'}), '(lbp, normed=True, bins=max_bins, range=(0, max_bins))\n', (2606, 2660), True, 'import numpy as np\n'), ((2706, 2773), 'skimage.feature.local_binary_pattern', 'skft.local_binary_pattern', (['test_data[i]', 'n_point', 'radius', '"""default"""'], {}), "(test_data[i], n_point, radius, 'default')\n", (2731, 2773), True, 'from skimage import feature as skft\n'), ((2957, 3023), 'numpy.histogram', 'np.histogram', (['lbp'], {'normed': '(True)', 'bins': 'max_bins', 'range': '(0, max_bins)'}), '(lbp, normed=True, bins=max_bins, range=(0, max_bins))\n', (2969, 3023), True, 'import numpy as np\n'), ((670, 692), 'os.listdir', 'os.listdir', (['child_path'], {}), '(child_path)\n', (680, 692), False, 'import os\n'), ((715, 774), 'cv2.imread', 'cv2.imread', (["(child_path + '\\\\' + dir_image)", 'cv2.IMREAD_COLOR'], {}), "(child_path + '\\\\' + dir_image, cv2.IMREAD_COLOR)\n", (725, 774), False, 'import cv2\n'), ((793, 820), 'cv2.resize', 'cv2.resize', (['img', '(512, 512)'], {}), '(img, (512, 512))\n', (803, 820), False, 'import cv2\n'), ((839, 876), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2GRAY'], {}), '(img, cv2.COLOR_BGR2GRAY)\n', (851, 876), False, 'import cv2\n'), ((896, 916), 'numpy.zeros', 'np.zeros', (['(512, 512)'], {}), '((512, 512))\n', (904, 916), True, 'import numpy as np\n'), ((1587, 1609), 'os.listdir', 'os.listdir', (['child_path'], {}), '(child_path)\n', (1597, 1609), False, 'import os\n'), ((1674, 1733), 'cv2.imread', 'cv2.imread', (["(child_path + '\\\\' + dir_image)", 'cv2.IMREAD_COLOR'], {}), "(child_path + '\\\\' + dir_image, cv2.IMREAD_COLOR)\n", (1684, 1733), False, 'import cv2\n'), ((1752, 1779), 'cv2.resize', 'cv2.resize', (['img', '(512, 512)'], {}), '(img, (512, 512))\n', (1762, 1779), False, 'import cv2\n'), ((1798, 1835), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2GRAY'], {}), '(img, cv2.COLOR_BGR2GRAY)\n', (1810, 1835), False, 'import cv2\n'), ((1855, 1875), 'numpy.zeros', 'np.zeros', (['(512, 512)'], {}), '((512, 512))\n', (1863, 1875), True, 'import numpy as np\n')] |
import struct
import os
import cv2
import re
import numpy as np
from polygon import Bbox
def send_data(socket, data):
data = struct.pack('>I', len(data)) + data
socket.sendall(data)
def recv_data(sock):
# Read message length and unpack it into an integer
raw_msglen = recvall(sock, 4)
if not raw_msglen:
return None
msglen = struct.unpack('>I', raw_msglen)[0]
# Read the message data
return recvall(sock, msglen)
def recvall(sock, n):
# Helper function to recv n bytes or return None if EOF is hit
data = b''
while len(data) < n:
packet = sock.recv(n - len(data))
if not packet:
return None
data += packet
return data
def natural_sort_key(s, _nsre=re.compile('([0-9]+)')):
return [int(text) if text.isdigit() else text.lower()
for text in _nsre.split(s)]
def keypoints_to_bbox(kps):
x, y, v = kps[0::3], kps[1::3], kps[2::3]
x, y = x[v > 0], y[v > 0]
x1, y1, x2, y2 = np.min(x), np.min(y), np.max(x), np.max(y)
return Bbox(x1, y1, x2 - x1, y2 - y1)
| [
"struct.unpack",
"numpy.max",
"numpy.min",
"polygon.Bbox",
"re.compile"
] | [((748, 770), 're.compile', 're.compile', (['"""([0-9]+)"""'], {}), "('([0-9]+)')\n", (758, 770), False, 'import re\n'), ((1053, 1083), 'polygon.Bbox', 'Bbox', (['x1', 'y1', '(x2 - x1)', '(y2 - y1)'], {}), '(x1, y1, x2 - x1, y2 - y1)\n', (1057, 1083), False, 'from polygon import Bbox\n'), ((361, 392), 'struct.unpack', 'struct.unpack', (['""">I"""', 'raw_msglen'], {}), "('>I', raw_msglen)\n", (374, 392), False, 'import struct\n'), ((999, 1008), 'numpy.min', 'np.min', (['x'], {}), '(x)\n', (1005, 1008), True, 'import numpy as np\n'), ((1010, 1019), 'numpy.min', 'np.min', (['y'], {}), '(y)\n', (1016, 1019), True, 'import numpy as np\n'), ((1021, 1030), 'numpy.max', 'np.max', (['x'], {}), '(x)\n', (1027, 1030), True, 'import numpy as np\n'), ((1032, 1041), 'numpy.max', 'np.max', (['y'], {}), '(y)\n', (1038, 1041), True, 'import numpy as np\n')] |
import random
import numpy as np
import torch
def set_seed(seed: int,
use_cuda: bool):
random.seed(seed)
np.random.seed(seed)
torch.random.manual_seed(seed)
if use_cuda:
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
def generate_y(x, roots=[0.0, 0.0]):
_x = 1
for root in roots:
_x *= (x - root)
return _x
| [
"numpy.random.seed",
"torch.random.manual_seed",
"torch.cuda.manual_seed",
"torch.cuda.manual_seed_all",
"random.seed"
] | [((107, 124), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (118, 124), False, 'import random\n'), ((129, 149), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (143, 149), True, 'import numpy as np\n'), ((154, 184), 'torch.random.manual_seed', 'torch.random.manual_seed', (['seed'], {}), '(seed)\n', (178, 184), False, 'import torch\n'), ((210, 238), 'torch.cuda.manual_seed', 'torch.cuda.manual_seed', (['seed'], {}), '(seed)\n', (232, 238), False, 'import torch\n'), ((247, 279), 'torch.cuda.manual_seed_all', 'torch.cuda.manual_seed_all', (['seed'], {}), '(seed)\n', (273, 279), False, 'import torch\n')] |
# Copyright 2020 The MuLT Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
from correlation import xfs
import pandas as pd
import numpy as np
class SelectMarker(object):
@staticmethod
def select_k_top_markers(entropies):
if isinstance(entropies, pd.Series):
entropies = entropies.values.reshape([-1])
elif isinstance(entropies, list):
entropies = np.array(entropies)
entropies = entropies.reshape([-1])
def q25(e):
return np.quantile(e, q=.25)
def q50(e):
return np.quantile(e, q=.50)
def q75(e):
return np.quantile(e, q=.75)
def std(e):
return np.std(e, ddof=1)
betas = np.array([
-0.8848630975791922, 4.600451633673629, 3.615872144716864, 1.1838667374310157,
-0.7000817701614678, -0.018821646628496263, -0.2313025930161946, 0.2103729053368249,
-4.060631004415739, 0.14208357407079072])
params = np.array([1.0] + [op(entropies) for op in [
np.mean, std, np.min, np.max, np.sum, q25, q50, q75, len]])
return int(round(len(entropies) * params.dot(betas), 0))
@staticmethod
def select_markers(markers, outcome, threshold=0.0025, random_state=None):
"""
"""
assert isinstance(markers, pd.DataFrame)
selected_markers = xfs(markers, outcome, acceptable_noise=threshold, random_state=random_state)
return selected_markers
| [
"numpy.std",
"numpy.quantile",
"numpy.array",
"correlation.xfs"
] | [((1336, 1566), 'numpy.array', 'np.array', (['[-0.8848630975791922, 4.600451633673629, 3.615872144716864, \n 1.1838667374310157, -0.7000817701614678, -0.018821646628496263, -\n 0.2313025930161946, 0.2103729053368249, -4.060631004415739, \n 0.14208357407079072]'], {}), '([-0.8848630975791922, 4.600451633673629, 3.615872144716864, \n 1.1838667374310157, -0.7000817701614678, -0.018821646628496263, -\n 0.2313025930161946, 0.2103729053368249, -4.060631004415739, \n 0.14208357407079072])\n', (1344, 1566), True, 'import numpy as np\n'), ((1989, 2065), 'correlation.xfs', 'xfs', (['markers', 'outcome'], {'acceptable_noise': 'threshold', 'random_state': 'random_state'}), '(markers, outcome, acceptable_noise=threshold, random_state=random_state)\n', (1992, 2065), False, 'from correlation import xfs\n'), ((1115, 1137), 'numpy.quantile', 'np.quantile', (['e'], {'q': '(0.25)'}), '(e, q=0.25)\n', (1126, 1137), True, 'import numpy as np\n'), ((1177, 1198), 'numpy.quantile', 'np.quantile', (['e'], {'q': '(0.5)'}), '(e, q=0.5)\n', (1188, 1198), True, 'import numpy as np\n'), ((1239, 1261), 'numpy.quantile', 'np.quantile', (['e'], {'q': '(0.75)'}), '(e, q=0.75)\n', (1250, 1261), True, 'import numpy as np\n'), ((1301, 1318), 'numpy.std', 'np.std', (['e'], {'ddof': '(1)'}), '(e, ddof=1)\n', (1307, 1318), True, 'import numpy as np\n'), ((1010, 1029), 'numpy.array', 'np.array', (['entropies'], {}), '(entropies)\n', (1018, 1029), True, 'import numpy as np\n')] |
import os
import time
import sys
import re
from subprocess import call
import numpy as np
from nltk import TweetTokenizer
from nltk.tokenize.stanford import StanfordTokenizer
FASTTEXT_EXEC_PATH = os.path.abspath("./fasttext")
BASE_SNLP_PATH = "stanford-postagger/"
SNLP_TAGGER_JAR = os.path.join(BASE_SNLP_PATH, "stanford-postagger.jar")
MODEL_PG_3KBOOKS_BIGRAMS = os.path.abspath("./pre-trained-models/project-gutenburg-books-model.bin")
#MODEL_WIKI_BIGRAMS = os.path.abspath("./pre-trained-models/wiki_bigrams.bin")
#MODEL_TORONTOBOOKS_UNIGRAMS = os.path.abspath("./pre-trained-models/toronto_unigrams.bin")
#MODEL_TORONTOBOOKS_BIGRAMS = os.path.abspath("./sent2vec_wiki_bigrams")
#MODEL_TWITTER_UNIGRAMS = os.path.abspath('./sent2vec_twitter_unigrams')
#MODEL_TWITTER_BIGRAMS = os.path.abspath('./sent2vec_twitter_bigrams')
def tokenize(tknzr, sentence, to_lower=True):
"""Arguments:
- tknzr: a tokenizer implementing the NLTK tokenizer interface
- sentence: a string to be tokenized
- to_lower: lowercasing or not
"""
sentence = sentence.strip()
sentence = ' '.join([format_token(x) for x in tknzr.tokenize(sentence)])
if to_lower:
sentence = sentence.lower()
sentence = re.sub('((www\.[^\s]+)|(https?://[^\s]+)|(http?://[^\s]+))','<url>',sentence) #replace urls by <url>
sentence = re.sub('(\@[^\s]+)','<user>',sentence) #replace @user268 by <user>
filter(lambda word: ' ' not in word, sentence)
return sentence
def format_token(token):
""""""
if token == '-LRB-':
token = '('
elif token == '-RRB-':
token = ')'
elif token == '-RSB-':
token = ']'
elif token == '-LSB-':
token = '['
elif token == '-LCB-':
token = '{'
elif token == '-RCB-':
token = '}'
return token
def tokenize_sentences(tknzr, sentences, to_lower=True):
"""Arguments:
- tknzr: a tokenizer implementing the NLTK tokenizer interface
- sentences: a list of sentences
- to_lower: lowercasing or not
"""
return [tokenize(tknzr, s, to_lower) for s in sentences]
def get_embeddings_for_preprocessed_sentences(sentences, model_path, fasttext_exec_path):
"""Arguments:
- sentences: a list of preprocessed sentences
- model_path: a path to the sent2vec .bin model
- fasttext_exec_path: a path to the fasttext executable
"""
timestamp = str(time.time())
test_path = os.path.abspath('./'+timestamp+'_fasttext.test.txt')
embeddings_path = os.path.abspath('./'+timestamp+'_fasttext.embeddings.txt')
dump_text_to_disk(test_path, sentences)
call(fasttext_exec_path+
' print-sentence-vectors '+
model_path + ' < '+
test_path + ' > ' +
embeddings_path, shell=True)
embeddings = read_embeddings(embeddings_path)
print(len(embeddings))
os.remove(test_path)
os.remove(embeddings_path)
assert(len(sentences) == len(embeddings))
return np.array(embeddings)
def read_embeddings(embeddings_path):
"""Arguments:
- embeddings_path: path to the embeddings
"""
with open(embeddings_path, 'r') as in_stream:
embeddings = []
for line in in_stream:
line = '['+line.replace(' ',',')+']'
embeddings.append(eval(line))
return embeddings
return []
def dump_text_to_disk(file_path, X, Y=None):
"""Arguments:
- file_path: where to dump the data
- X: list of sentences to dump
- Y: labels, if any
"""
with open(file_path, 'w') as out_stream:
if Y is not None:
for x, y in zip(X, Y):
out_stream.write('__label__'+str(y)+' '+x+' \n')
else:
for x in X:
out_stream.write(x + ' \n')
def get_sentence_embeddings(sentences, ngram='bigrams', model='concat_wiki_twitter'):
""" Returns a numpy matrix of embeddings for one of the published models. It
handles tokenization and can be given raw sentences.
Arguments:
- ngram: 'unigrams' or 'bigrams'
- model: 'wiki', 'twitter', or 'concat_wiki_twitter'
- sentences: a list of raw sentences ['Once upon a time', 'This is another sentence.', ...]
"""
wiki_embeddings = None
twitter_embbedings = None
tokenized_sentences_NLTK_tweets = None
tokenized_sentences_SNLP = None
if model == "wiki" or model == 'concat_wiki_twitter':
tknzr = StanfordTokenizer(SNLP_TAGGER_JAR, encoding='utf-8')
s = ' <delimiter> '.join(sentences) # just a trick to make things faster
tokenized_sentences_SNLP = tokenize_sentences(tknzr, [s])
tokenized_sentences_SNLP = tokenized_sentences_SNLP[0].split(' <delimiter> ')
assert (len(tokenized_sentences_SNLP) == len(sentences))
wiki_embeddings = get_embeddings_for_preprocessed_sentences(tokenized_sentences_SNLP, \
MODEL_PG_3KBOOKS_BIGRAMS, FASTTEXT_EXEC_PATH)
if model == "wiki":
return wiki_embeddings
elif model == "concat_wiki_twitter":
return np.concatenate((wiki_embeddings, twitter_embbedings), axis=1)
sys.exit(-1)
def main():
sentences = ['Once upon a time.', 'And now for something completely different.']
my_embeddings = get_sentence_embeddings(sentences, ngram='unigrams', model='wiki')
print(my_embeddings.shape)
if __name__ == "__main__":
main()
| [
"os.path.abspath",
"os.remove",
"numpy.concatenate",
"time.time",
"nltk.tokenize.stanford.StanfordTokenizer",
"subprocess.call",
"numpy.array",
"sys.exit",
"os.path.join",
"re.sub"
] | [((197, 226), 'os.path.abspath', 'os.path.abspath', (['"""./fasttext"""'], {}), "('./fasttext')\n", (212, 226), False, 'import os\n'), ((285, 339), 'os.path.join', 'os.path.join', (['BASE_SNLP_PATH', '"""stanford-postagger.jar"""'], {}), "(BASE_SNLP_PATH, 'stanford-postagger.jar')\n", (297, 339), False, 'import os\n'), ((368, 441), 'os.path.abspath', 'os.path.abspath', (['"""./pre-trained-models/project-gutenburg-books-model.bin"""'], {}), "('./pre-trained-models/project-gutenburg-books-model.bin')\n", (383, 441), False, 'import os\n'), ((1235, 1322), 're.sub', 're.sub', (['"""((www\\\\.[^\\\\s]+)|(https?://[^\\\\s]+)|(http?://[^\\\\s]+))"""', '"""<url>"""', 'sentence'], {}), "('((www\\\\.[^\\\\s]+)|(https?://[^\\\\s]+)|(http?://[^\\\\s]+))', '<url>',\n sentence)\n", (1241, 1322), False, 'import re\n'), ((1351, 1393), 're.sub', 're.sub', (['"""(\\\\@[^\\\\s]+)"""', '"""<user>"""', 'sentence'], {}), "('(\\\\@[^\\\\s]+)', '<user>', sentence)\n", (1357, 1393), False, 'import re\n'), ((2459, 2515), 'os.path.abspath', 'os.path.abspath', (["('./' + timestamp + '_fasttext.test.txt')"], {}), "('./' + timestamp + '_fasttext.test.txt')\n", (2474, 2515), False, 'import os\n'), ((2534, 2596), 'os.path.abspath', 'os.path.abspath', (["('./' + timestamp + '_fasttext.embeddings.txt')"], {}), "('./' + timestamp + '_fasttext.embeddings.txt')\n", (2549, 2596), False, 'import os\n'), ((2641, 2769), 'subprocess.call', 'call', (["(fasttext_exec_path + ' print-sentence-vectors ' + model_path + ' < ' +\n test_path + ' > ' + embeddings_path)"], {'shell': '(True)'}), "(fasttext_exec_path + ' print-sentence-vectors ' + model_path + ' < ' +\n test_path + ' > ' + embeddings_path, shell=True)\n", (2645, 2769), False, 'from subprocess import call\n'), ((2884, 2904), 'os.remove', 'os.remove', (['test_path'], {}), '(test_path)\n', (2893, 2904), False, 'import os\n'), ((2909, 2935), 'os.remove', 'os.remove', (['embeddings_path'], {}), '(embeddings_path)\n', (2918, 2935), False, 'import os\n'), ((2993, 3013), 'numpy.array', 'np.array', (['embeddings'], {}), '(embeddings)\n', (3001, 3013), True, 'import numpy as np\n'), ((5301, 5313), 'sys.exit', 'sys.exit', (['(-1)'], {}), '(-1)\n', (5309, 5313), False, 'import sys\n'), ((2430, 2441), 'time.time', 'time.time', ([], {}), '()\n', (2439, 2441), False, 'import time\n'), ((4513, 4565), 'nltk.tokenize.stanford.StanfordTokenizer', 'StanfordTokenizer', (['SNLP_TAGGER_JAR'], {'encoding': '"""utf-8"""'}), "(SNLP_TAGGER_JAR, encoding='utf-8')\n", (4530, 4565), False, 'from nltk.tokenize.stanford import StanfordTokenizer\n'), ((5231, 5292), 'numpy.concatenate', 'np.concatenate', (['(wiki_embeddings, twitter_embbedings)'], {'axis': '(1)'}), '((wiki_embeddings, twitter_embbedings), axis=1)\n', (5245, 5292), True, 'import numpy as np\n')] |
#!/usr/bin/python
import matplotlib.pyplot as plt
import numpy as np
# sample 2D array
x = np.random.random((100, 100))
plt.imshow(x, cmap="gray")
plt.show()
| [
"matplotlib.pyplot.imshow",
"numpy.random.random",
"matplotlib.pyplot.show"
] | [((97, 125), 'numpy.random.random', 'np.random.random', (['(100, 100)'], {}), '((100, 100))\n', (113, 125), True, 'import numpy as np\n'), ((128, 154), 'matplotlib.pyplot.imshow', 'plt.imshow', (['x'], {'cmap': '"""gray"""'}), "(x, cmap='gray')\n", (138, 154), True, 'import matplotlib.pyplot as plt\n'), ((155, 165), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (163, 165), True, 'import matplotlib.pyplot as plt\n')] |
import numpy as np
import open3d
from ..configs import config
# from open3d.open3d.geometry import voxel_down_sample, estimate_normals, orient_normals_towards_camera_location
class PointCloud:
def __init__(self, cloud: open3d.geometry.PointCloud, visualization=False):
self.cloud = cloud
self.visualization = visualization
self.normals = None if len(np.asarray(cloud.normals)) <= 0 else np.asarray(cloud.normals)
def remove_outliers(self):
num_points_threshold = config.NUM_POINTS_THRESHOLD
radius_threshold = config.RADIUS_THRESHOLD
self.cloud.remove_radius_outlier(nb_points=num_points_threshold,
radius=radius_threshold)
if self.visualization:
open3d.visualization.draw_geometries([self.cloud])
def voxelize(self, voxel_size=config.VOXEL_SIZE):
self.cloud.voxel_down_sample(voxel_size=voxel_size)
# self.cloud = voxel_down_sample(self.cloud, voxel_size=voxel_size)
if self.visualization:
open3d.visualization.draw_geometries([self.cloud])
def estimate_normals(self, camera_pos=np.zeros(3)):
normal_radius = config.NORMAL_RADIUS
normal_max_nn = config.NORMAL_MAX_NN
self.cloud.estimate_normals(
search_param=open3d.geometry.KDTreeSearchParamHybrid(radius=normal_radius, max_nn=normal_max_nn),
fast_normal_computation=False)
# estimate_normals(self.cloud,
# search_param=open3d.geometry.KDTreeSearchParamHybrid(radius=normal_radius, max_nn=normal_max_nn))#,
# # fast_normal_computation=False)
self.cloud.normalize_normals()
if True:
# orient_normals_towards_camera_location(self.cloud, camera_pos)
self.cloud.orient_normals_towards_camera_location(camera_pos)
if self.visualization:
open3d.visualization.draw_geometries([self.cloud])
self.normals = np.asarray(self.cloud.normals)
| [
"open3d.visualization.draw_geometries",
"numpy.asarray",
"open3d.geometry.KDTreeSearchParamHybrid",
"numpy.zeros"
] | [((1146, 1157), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (1154, 1157), True, 'import numpy as np\n'), ((1962, 1992), 'numpy.asarray', 'np.asarray', (['self.cloud.normals'], {}), '(self.cloud.normals)\n', (1972, 1992), True, 'import numpy as np\n'), ((417, 442), 'numpy.asarray', 'np.asarray', (['cloud.normals'], {}), '(cloud.normals)\n', (427, 442), True, 'import numpy as np\n'), ((767, 817), 'open3d.visualization.draw_geometries', 'open3d.visualization.draw_geometries', (['[self.cloud]'], {}), '([self.cloud])\n', (803, 817), False, 'import open3d\n'), ((1052, 1102), 'open3d.visualization.draw_geometries', 'open3d.visualization.draw_geometries', (['[self.cloud]'], {}), '([self.cloud])\n', (1088, 1102), False, 'import open3d\n'), ((1887, 1937), 'open3d.visualization.draw_geometries', 'open3d.visualization.draw_geometries', (['[self.cloud]'], {}), '([self.cloud])\n', (1923, 1937), False, 'import open3d\n'), ((1311, 1399), 'open3d.geometry.KDTreeSearchParamHybrid', 'open3d.geometry.KDTreeSearchParamHybrid', ([], {'radius': 'normal_radius', 'max_nn': 'normal_max_nn'}), '(radius=normal_radius, max_nn=\n normal_max_nn)\n', (1350, 1399), False, 'import open3d\n'), ((380, 405), 'numpy.asarray', 'np.asarray', (['cloud.normals'], {}), '(cloud.normals)\n', (390, 405), True, 'import numpy as np\n')] |
import numpy as np
import re
from datetime import datetime, timedelta
def setDimensions(OBS):
'''
Takes an observation structure, calculate unique survey_times
and number of observations within each survey.
Returns OBS
'''
OBS.toarray()
OBS.survey_time=np.unique(OBS.time)
OBS.Nsurvey=len(OBS.survey_time)
OBS.Ndatum=len(OBS.time)
Nobs=np.ones_like(OBS.survey_time)*float('nan')
for item in enumerate(OBS.survey_time):
Nobs[item[0]] = len(np.array(np.argwhere(OBS.time==item[1])))
OBS.Nobs=Nobs
return OBS
def accum_np(accmap, a, func=np.sum):
indices = np.where(np.ediff1d(accmap, to_begin=[1],to_end=[1]))[0]
vals = np.zeros(len(indices) - 1)
for i in xrange(len(indices) - 1):
vals[i] = func(a[indices[i]:indices[i+1]])
return vals
def roundTime(dt=None, roundTo=60):
"""Round a datetime object to any time lapse in seconds
dt : datetime.datetime object, default now.
roundTo : Closest number of seconds to round to, default 1 minute.
Author: <NAME> 2012 - Use it as you want but don't blame me.
"""
if dt == None : dt = datetime.now()
seconds = (dt.replace(tzinfo=None) - dt.min).seconds
rounding = (seconds+roundTo/2) // roundTo * roundTo
return dt + timedelta(0,rounding-seconds,-dt.microsecond)
def sort_ascending(OBS):
'''
Takes an observation structure and sorts the observations
according to ascending time'
'''
field_list=OBS.getfieldlist()
OBS.tolist()
# order according to ascending obs_time
tmplist = sorted(zip(*[getattr(OBS,names) for names in field_list]))
tmplist = list(zip(*tmplist))
for n in range(0,len(field_list)):
if (len(OBS.__dict__[field_list[n]])):
setattr(OBS,field_list[n],tmplist[n])
OBS.toarray()
OBS=setDimensions(OBS)
return OBS
def popEntries(popindex, OBS):
field_list=OBS.getfieldlist()
OBS.tolist()
popindex=np.array(popindex).squeeze()
if popindex.size>1:
indices=sorted(popindex.tolist(),reverse=True)
for index in indices:
for names in field_list:
if (len(OBS.__dict__[names])):
del OBS.__dict__[names][index]
elif (popindex.size<2) & (popindex.size>0):
index=popindex
for names in field_list:
if (len(OBS.__dict__[names])):
del OBS.__dict__[names][index]
return OBS
def atoi(text):
return int(text) if text.isdigit() else text
def natural_keys(text):
'''
alist.sort(key=natural_keys) sorts in human order
http://nedbatchelder.com/blog/200712/human_sorting.html
(See Toothy's implementation in the comments)
'''
return [ atoi(c) for c in re.split(r'(\d+)', text) ]
def extract_number(string):
'''
Function that can help sort filelist with datestring in filename
'''
r = re.compile(r'(\d+)')
return int(r.findall(string)[0])
| [
"numpy.ones_like",
"re.split",
"numpy.ediff1d",
"datetime.timedelta",
"numpy.array",
"numpy.argwhere",
"datetime.datetime.now",
"numpy.unique",
"re.compile"
] | [((281, 300), 'numpy.unique', 'np.unique', (['OBS.time'], {}), '(OBS.time)\n', (290, 300), True, 'import numpy as np\n'), ((2889, 2909), 're.compile', 're.compile', (['"""(\\\\d+)"""'], {}), "('(\\\\d+)')\n", (2899, 2909), False, 'import re\n'), ((377, 406), 'numpy.ones_like', 'np.ones_like', (['OBS.survey_time'], {}), '(OBS.survey_time)\n', (389, 406), True, 'import numpy as np\n'), ((1135, 1149), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (1147, 1149), False, 'from datetime import datetime, timedelta\n'), ((1279, 1328), 'datetime.timedelta', 'timedelta', (['(0)', '(rounding - seconds)', '(-dt.microsecond)'], {}), '(0, rounding - seconds, -dt.microsecond)\n', (1288, 1328), False, 'from datetime import datetime, timedelta\n'), ((629, 673), 'numpy.ediff1d', 'np.ediff1d', (['accmap'], {'to_begin': '[1]', 'to_end': '[1]'}), '(accmap, to_begin=[1], to_end=[1])\n', (639, 673), True, 'import numpy as np\n'), ((1960, 1978), 'numpy.array', 'np.array', (['popindex'], {}), '(popindex)\n', (1968, 1978), True, 'import numpy as np\n'), ((2740, 2764), 're.split', 're.split', (['"""(\\\\d+)"""', 'text'], {}), "('(\\\\d+)', text)\n", (2748, 2764), False, 'import re\n'), ((501, 533), 'numpy.argwhere', 'np.argwhere', (['(OBS.time == item[1])'], {}), '(OBS.time == item[1])\n', (512, 533), True, 'import numpy as np\n')] |
import numpy as np
def contaminate_signal(X, noise_rate=10, noise_type='AWGN', missing_ratio=0):
''' Contaminates data with AWGN and random missing elements.
Parameters:
X: np.array(), double
Original data tensor.
noise_rate: double.
For 'AWGN', target SNR in dB. For 'gross', the rate of
corrupted elements.
noise_type: string
Type of noise to be added to data. Default: 'AWGN'
Currently supports 'AWGN' and gross noise ('gross')
missing_ratio: double,
Ratio of missing elements to tensor size. Should be in [0,1].
Outputs:
Y: Masked Array. np.ma()
Noisy tensor with missing elements.
'''
# Generate noise
sizes = X.shape
Y = X.copy()
if noise_type == 'AWGN':
signal_power = np.linalg.norm(X)**2/X.size
signal_dB = 10 * np.log10(signal_power)
noise_db = signal_dB - noise_rate
noise_power = 10 ** (noise_db / 10)
noise = np.sqrt(noise_power)*np.random.standard_normal(sizes)
Y = Y + noise
elif noise_type == 'gross':
vec_ind = np.nonzero(np.random.binomial(1, noise_rate, size=X.size))[0]
(
Y[np.unravel_index(vec_ind, sizes, 'F')]
) = np.random.uniform(low=X.min(), high=X.max(), size=vec_ind.size)
# Create mask
vec_mask = np.random.uniform(size=X.size)-missing_ratio < 0
mask = vec_mask.reshape(sizes)
return np.ma.array(Y, mask=mask)
| [
"numpy.random.uniform",
"numpy.random.binomial",
"numpy.unravel_index",
"numpy.ma.array",
"numpy.random.standard_normal",
"numpy.linalg.norm",
"numpy.log10",
"numpy.sqrt"
] | [((1482, 1507), 'numpy.ma.array', 'np.ma.array', (['Y'], {'mask': 'mask'}), '(Y, mask=mask)\n', (1493, 1507), True, 'import numpy as np\n'), ((901, 923), 'numpy.log10', 'np.log10', (['signal_power'], {}), '(signal_power)\n', (909, 923), True, 'import numpy as np\n'), ((1026, 1046), 'numpy.sqrt', 'np.sqrt', (['noise_power'], {}), '(noise_power)\n', (1033, 1046), True, 'import numpy as np\n'), ((1047, 1079), 'numpy.random.standard_normal', 'np.random.standard_normal', (['sizes'], {}), '(sizes)\n', (1072, 1079), True, 'import numpy as np\n'), ((1387, 1417), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': 'X.size'}), '(size=X.size)\n', (1404, 1417), True, 'import numpy as np\n'), ((848, 865), 'numpy.linalg.norm', 'np.linalg.norm', (['X'], {}), '(X)\n', (862, 865), True, 'import numpy as np\n'), ((1238, 1275), 'numpy.unravel_index', 'np.unravel_index', (['vec_ind', 'sizes', '"""F"""'], {}), "(vec_ind, sizes, 'F')\n", (1254, 1275), True, 'import numpy as np\n'), ((1163, 1209), 'numpy.random.binomial', 'np.random.binomial', (['(1)', 'noise_rate'], {'size': 'X.size'}), '(1, noise_rate, size=X.size)\n', (1181, 1209), True, 'import numpy as np\n')] |
#!/usr/bin/env python
import os, sys, glob
sys.path.append('/Users/vincentvoelz/scripts/ratespec')
import scipy
from scipy.linalg import pinv
import numpy as np
import matplotlib
from pylab import *
from RateSpecClass import *
from RateSpecTools import *
from PlottingTools import *
# For nice plots :)
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def addAxes(pos):
"""Add axes according the pos list, and return the axes handle."""
rect = pos[0]+margins[0], pos[1]+margins[2], pos[2]-margins[0]-margins[1], pos[3]-margins[2]-margins[3]
return fig.add_axes(rect)
# Default plotting parameters
if (1):
plt.rc('figure', figsize=(4.0, 3.5)) # in inches
plt.rc('figure.subplot', left=0.125, right=0.9, bottom=0.1, top=0.90)
plt.rc('lines', linewidth=1.5, markersize=5)
plt.rc('font', size=8.0)
plt.rc('font',**{'family':'sans-serif','sans-serif':['Arial']})
plt.rc('xtick', labelsize='small')
plt.rc('ytick', labelsize='small')
plt.rc('legend', fontsize='medium')
# Define workspace for all panels
panelpos = []
# top two panels
panelpos.append( [0, 0.5, 0.5, 0.5] ) # bottom left corner x, y; width, height
panelpos.append( [0.5, 0.5, 0.5, 0.5] ) # bottom left corner x, y; width, height
# bottom two panels
panelpos.append( [0, 0, 0.5, 0.5] ) # bottom left corner x, y; width, height
panelpos.append( [0.5, 0, 0.5, 0.5] ) # bottom left corner x, y; width, height
# define margins within each panel
margins = [0.1, 0.05, 0.1, 0.02 ] # for each panel (left, right, bottom, top)
fig = plt.figure(1)
plt.clf()
#### Filenames ###
outpdffile = 'Figure2.pdf'
tags = ['Lridge', 'Llasso', 'Lenet']
ratespec_files = ['data/triexp.sigma0.050.nRates100.%s.ratespec.dat'%tag for tag in tags]
mctraj_files = ['data/triexp.sigma0.050.nRates100.%s.mctraj.dat'%tag for tag in tags]
dat_files = ['data/triexp.sigma0.050.dat' for tag in tags]
for i in range(len(ratespec_files)):
ratespec_filename = ratespec_files[i]
mctraj_filename = mctraj_files[i]
data = scipy.loadtxt(dat_files[i])
Times = data[:,0]*1.0e-6 # convert from us to seconds
Values = data[:,1]
mctraj_data = scipy.loadtxt(mctraj_filename) # step w sigma tau neglogP
ratespec_data = scipy.loadtxt(ratespec_filename)
Timescales = ratespec_data[:,0]
maxLikA = ratespec_data[:,1]
meanA = ratespec_data[:,2]
stdA = ratespec_data[:,3]
ci_5pc = ratespec_data[:,4]
ci_95pc = ratespec_data[:,5]
# plot mean +/- std spectrum
ax = addAxes(panelpos[i])
#matplotlib.pyplot.errorbar(Timescales, meanA, yerr=stdA)
PlotStd = False
plot(Timescales, meanA, 'k-', linewidth=2)
hold(True)
if PlotStd:
plot(Timescales, meanA+stdA, 'k-', linewidth=1)
hold(True)
plot(Timescales, meanA-stdA, 'k-', linewidth=1)
else:
plot(Timescales, ci_5pc, 'k-', linewidth=1)
hold(True)
plot(Timescales, ci_95pc, 'k-', linewidth=1)
ax.set_xscale('log')
xlabel('timescale (s)')
ax.set_xticks([1.0e-9, 1.0e-6, 1.0e-3, 1.])
if (1):
# plot distribution of sigma
ax = addAxes(panelpos[3])
nskip = 1000
rhocounts, rhobins = np.histogram(mctraj_data[nskip:,4], bins=np.arange(0, 1.025, 0.025))
rhocounts = rhocounts/float(rhocounts.max())
plt.plot(rhobins, [0]+rhocounts.tolist(), 'b-', linestyle='steps', linewidth=1)
hold(True)
plt.axis([0, 1, -0.01, 1.2])
xlabel('$\\rho$')
ylabel('$P(\\rho)$')
ax.set_yticks([])
plt.savefig(outpdffile, format='pdf')
#show()
| [
"sys.path.append",
"scipy.loadtxt",
"matplotlib.pyplot.clf",
"matplotlib.pyplot.axis",
"matplotlib.pyplot.figure",
"matplotlib.use",
"numpy.arange",
"matplotlib.pyplot.rc",
"matplotlib.pyplot.savefig"
] | [((44, 99), 'sys.path.append', 'sys.path.append', (['"""/Users/vincentvoelz/scripts/ratespec"""'], {}), "('/Users/vincentvoelz/scripts/ratespec')\n", (59, 99), False, 'import os, sys, glob\n'), ((309, 330), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (323, 330), False, 'import matplotlib\n'), ((1558, 1571), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {}), '(1)\n', (1568, 1571), True, 'import matplotlib.pyplot as plt\n'), ((1572, 1581), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (1579, 1581), True, 'import matplotlib.pyplot as plt\n'), ((3516, 3553), 'matplotlib.pyplot.savefig', 'plt.savefig', (['outpdffile'], {'format': '"""pdf"""'}), "(outpdffile, format='pdf')\n", (3527, 3553), True, 'import matplotlib.pyplot as plt\n'), ((639, 675), 'matplotlib.pyplot.rc', 'plt.rc', (['"""figure"""'], {'figsize': '(4.0, 3.5)'}), "('figure', figsize=(4.0, 3.5))\n", (645, 675), True, 'import matplotlib.pyplot as plt\n'), ((693, 761), 'matplotlib.pyplot.rc', 'plt.rc', (['"""figure.subplot"""'], {'left': '(0.125)', 'right': '(0.9)', 'bottom': '(0.1)', 'top': '(0.9)'}), "('figure.subplot', left=0.125, right=0.9, bottom=0.1, top=0.9)\n", (699, 761), True, 'import matplotlib.pyplot as plt\n'), ((767, 811), 'matplotlib.pyplot.rc', 'plt.rc', (['"""lines"""'], {'linewidth': '(1.5)', 'markersize': '(5)'}), "('lines', linewidth=1.5, markersize=5)\n", (773, 811), True, 'import matplotlib.pyplot as plt\n'), ((816, 840), 'matplotlib.pyplot.rc', 'plt.rc', (['"""font"""'], {'size': '(8.0)'}), "('font', size=8.0)\n", (822, 840), True, 'import matplotlib.pyplot as plt\n'), ((845, 912), 'matplotlib.pyplot.rc', 'plt.rc', (['"""font"""'], {}), "('font', **{'family': 'sans-serif', 'sans-serif': ['Arial']})\n", (851, 912), True, 'import matplotlib.pyplot as plt\n'), ((913, 947), 'matplotlib.pyplot.rc', 'plt.rc', (['"""xtick"""'], {'labelsize': '"""small"""'}), "('xtick', labelsize='small')\n", (919, 947), True, 'import matplotlib.pyplot as plt\n'), ((952, 986), 'matplotlib.pyplot.rc', 'plt.rc', (['"""ytick"""'], {'labelsize': '"""small"""'}), "('ytick', labelsize='small')\n", (958, 986), True, 'import matplotlib.pyplot as plt\n'), ((991, 1026), 'matplotlib.pyplot.rc', 'plt.rc', (['"""legend"""'], {'fontsize': '"""medium"""'}), "('legend', fontsize='medium')\n", (997, 1026), True, 'import matplotlib.pyplot as plt\n'), ((2034, 2061), 'scipy.loadtxt', 'scipy.loadtxt', (['dat_files[i]'], {}), '(dat_files[i])\n', (2047, 2061), False, 'import scipy\n'), ((2164, 2194), 'scipy.loadtxt', 'scipy.loadtxt', (['mctraj_filename'], {}), '(mctraj_filename)\n', (2177, 2194), False, 'import scipy\n'), ((2259, 2291), 'scipy.loadtxt', 'scipy.loadtxt', (['ratespec_filename'], {}), '(ratespec_filename)\n', (2272, 2291), False, 'import scipy\n'), ((3415, 3443), 'matplotlib.pyplot.axis', 'plt.axis', (['[0, 1, -0.01, 1.2]'], {}), '([0, 1, -0.01, 1.2])\n', (3423, 3443), True, 'import matplotlib.pyplot as plt\n'), ((3235, 3261), 'numpy.arange', 'np.arange', (['(0)', '(1.025)', '(0.025)'], {}), '(0, 1.025, 0.025)\n', (3244, 3261), True, 'import numpy as np\n')] |
import numpy as np
class CategoricalAccuracy:
def __init__(self):
self.accuracy_sums = 0
self.iter = 1e-12
def __call__(self, y_true, y_pred):
print(y_pred.shape)
y_pred = np.argmax(y_pred, axis=0)
y_true = np.argmax(y_true, axis=0)
accuracy = np.sum(y_pred == y_true) / y_true.size
print(y_pred)
self.accuracy_sums += accuracy
self.iter += 1
def result(self):
return self.accuracy_sums / self.iter
def reset_states(self):
self.accuracy_sums = 0
self.iter = 1e-12 | [
"numpy.sum",
"numpy.argmax"
] | [((213, 238), 'numpy.argmax', 'np.argmax', (['y_pred'], {'axis': '(0)'}), '(y_pred, axis=0)\n', (222, 238), True, 'import numpy as np\n'), ((256, 281), 'numpy.argmax', 'np.argmax', (['y_true'], {'axis': '(0)'}), '(y_true, axis=0)\n', (265, 281), True, 'import numpy as np\n'), ((301, 325), 'numpy.sum', 'np.sum', (['(y_pred == y_true)'], {}), '(y_pred == y_true)\n', (307, 325), True, 'import numpy as np\n')] |
"""
aberrations.py
mostly copied over from the original by Rupert in MEDIS
collection of functions that deal with making aberration maps in proper for a given optical element.
Two initialize functions set up the ques for creating, saving, and reading FITs files of aberration maps. In general,
for an optical element in the telescope optical train, a aberration map is generated in Proper using prop_psd_errormap.
The map is saved as a FITs file and used for every wavelength and timestep in the observation sequence. Ideally this
will be updated for quasi-static aberrations, where the aberrations evolve over some user-defined timescale.
"""
import numpy as np
import proper
import os
import pickle
from medis.params import iop
from medis.utils import *
################################################################################################################
# Aberrations
################################################################################################################
def generate_maps(aber_vals, lens_diam, lens_name='lens', quasi_static=False):
"""
generate PSD-defined aberration maps for a lens(mirror) using Proper
Use Proper to generate an 2D aberration pattern across an optical element. The amplitude of the error per spatial
frequency (cycles/m) across the surface is taken from a power spectral density (PSD) of statistical likelihoods
for 'real' aberrations of physical optics.
parameters defining the PSD function are specified in tp.aber_vals. These limit the range for the constants of the
governing equation given by PSD = a/ [1+(k/b)^c]. This formula assumes the Terrestrial Planet Finder PSD, which is
set to TRUE unless manually overridden line-by-line. As stated in the proper manual, this PSD function general
under-predicts lower order aberrations, and thus Zernike polynomials can be added to get even more realistic
surface maps.
more information on a PSD error map can be found in the Proper manual on pgs 55-60
Note: Functionality related to OOPP (out of pupil plane) optics has been removed. There is only one surface
simulated for each optical surface
:param aber_vals: dictionary? of values to use in the equation that generates the aberration map. The dictionary
should contain 3 entries that get sent to proper.prop_psd_errormap. More information can be found on Proper
Manual pg 56
:param lens_diam: diameter of the lens/mirror to generate an aberration map for
:param lens_name: name of the lens, for file naming
:return: will create a FITs file in the folder specified by iop.quasi for each optic (and timestep in the case
of quasi-static aberrations)
"""
# TODO add different timescale aberations
if sp.verbose: dprint(f'Generating optic aberration maps using Proper at directory {iop.aberdir}')
if not os.path.isdir(iop.aberdir):
# todo remove when all test scripts use the new format
raise NotImplementedError
print('aberration maps should be created at the beginng, not on the fly')
os.makedirs(iop.aberdir, exist_ok=True)
# create blank lens wavefront for proper to add phase to
wfo = proper.prop_begin(lens_diam, 1., sp.grid_size, sp.beam_ratio)
aber_cube = np.zeros((1, sp.grid_size, sp.grid_size))
# Randomly select a value from the range of values for each constant
# rms_error = np.random.normal(aber_vals['a'][0], aber_vals['a'][1])
# c_freq = np.random.normal(aber_vals['b'][0], aber_vals['b'][1]) # correlation frequency (cycles/meter)
# high_power = np.random.normal(aber_vals['c'][0], aber_vals['c'][1]) # high frequency falloff (r^-high_power)
rms_error, c_freq, high_power = aber_vals
# perms = np.random.rand(sp.numframes, sp.grid_size, sp.grid_size)-0.5
# perms *= 1e-7
phase = 2 * np.pi * np.random.uniform(size=(sp.grid_size, sp.grid_size)) - np.pi
aber_cube[0] = proper.prop_psd_errormap(wfo, rms_error, c_freq, high_power, TPF=True, PHASE_HISTORY=phase)
# PHASE_HISTORY stuff is a kwarg Rupert added to a proper.prop_pds_errormap in proper_mod that helps
# ennable the small perturbations to the phase aberrations over time (quasi-static aberration evolution)
# however, this may not be implemented here, and the functionality may not be robust. It has yet to be
# verified in a robust manner. However, I am not sure it is being used....? KD 10-15-19
# TODO verify this and add qusi-static functionality
filename = f"{iop.aberdir}/t{0}_{lens_name}.fits"
#dprint(f"filename = {filename}")
if not os.path.isfile(filename):
saveFITS(aber_cube[0], filename)
if quasi_static:
# todo implement monkey patch of proper.prop_psd_error that return phase too so it can be incremented with correlated gaussian noise
# See commit 48c77c0babd5c6fcbc681b4fdd0d2db9cf540695 for original implementation of this code
raise NotImplementedError
def add_aber(wf, aberdir=None, step=0, lens_name=None):
"""
loads a phase error map and adds aberrations using proper.prop_add_phase
if no aberration file exists, creates one for specific lens using generate_maps
:param wf: a single (2D) wfo.wf_collection[iw,io] at one wavelength and object
:param d_lens: diameter (in m) of lens (only used when generating new aberrations maps)
:param step: is the step number for quasistatic aberrations
:param lens_name: name of the lens, used to save/read in FITS file of aberration map
:return returns nothing but will act upon a given wavefront and apply new or loaded-in aberration map
"""
# TODO this does not currently loop over time, so it is not using quasi-static abberations.
if tp.use_aber is False:
pass # don't do anything. Putting this type of check here allows universal toggling on/off rather than
# commenting/uncommenting in the proper perscription
else:
# dprint("Adding Abberations")
# Load in or Generate Aberration Map
# iop.aberdata = f"gridsz{sp.grid_size}_bmratio{sp.beam_ratio}_tsteps{sp.numframes}"
# iop.aberdir = os.path.join(iop.testdir, iop.aberroot, iop.aberdata)
filename = f"{iop.aberdir}/t{0}_{lens_name}.fits"
# print(f'Adding Abberations from {filename}')
# if not os.path.isfile(filename):
# generate_maps(aber_vals, d_lens, lens_name)
phase_map = readFITS(filename)
proper.prop_add_phase(wf, phase_map) # Add Phase Map
def add_zern_ab(wf, zern_order=[2,3,4], zern_vals=np.array([175,-150,200])*1.0e-9):
"""
adds low-order aberrations from Zernike polynomials
see Proper Manual pg 192 for full details
see good example in Proper manual pg 51
quote: These [polynomials] form an orthogonal set of aberrations that include:
wavefront tilt, defocus, coma, astigmatism, spherical aberration, and others
Orders are:
1 Piston
2 X tilt
3 Y tilt
4 Focus
5 45º astigmatism
6 0º astigmatism
7 Y coma
8 X coma
9 Y clover (trefoil)
10 X clover (trefoil)
"""
if not tp.add_zern:
pass
else:
proper.prop_zernikes(wf, zern_order, zern_vals)
def randomize_zern_values(zern_orders):
"""
selects a value at random for the selected zernike orders
The ranges specified are all in units of m. From Proper manual pg 192-193
'The values must be in meters of RMS phase error or dimensionless RMS amplitude error.'
:param zern_orders: array containing integers of zernike orders to apply
:return: array with randomly selected values in a pre-determined range, per zernike order specified in zern_orders
"""
# Set Range
z_range = {
'r1': [30e-9, 60e-9], # m of RMS amplitude error
'r2': [30e-9, 40e-9], # X tilt
'r3': [30e-9, 40e-9], # Y tilt
'r4': [60e-9, 120e-9], # focus
'r5': [30e-9, 1200e-9],
'r6': [30e-9, 1200e-9],
'r7': [30e-9, 1200e-9],
'r8': [30e-9, 1200e-9],
'r9': [30e-9, 1200e-9],
'r10': [30e-9, 1200e-9],
}
zern_vals = np.zeros(len(zern_orders))
for iw, w in enumerate(zern_orders):
if w == 1:
zern_vals[iw] = np.random.normal(z_range['r1'][0], z_range['r1'][1])
elif w == 2:
zern_vals[iw] = np.random.normal(z_range['r2'][0], z_range['r2'][1])
elif w == 3:
zern_vals[iw] = np.random.normal(z_range['r3'][0], z_range['r3'][1])
elif w == 4:
zern_vals[iw] = np.random.normal(z_range['r4'][0], z_range['r4'][1])
elif w == 5:
zern_vals[iw] = np.random.normal(z_range['r5'][0], z_range['r5'][1])
elif w == 6:
zern_vals[iw] = np.random.normal(z_range['r6'][0], z_range['r6'][1])
elif w == 7:
zern_vals[iw] = np.random.normal(z_range['r7'][0], z_range['r7'][1])
elif w == 8:
zern_vals[iw] = np.random.normal(z_range['r8'][0], z_range['r8'][1])
return zern_vals
###############################################################################################
# Depricated--but potenetially useful for quasi-static aberration implementation later
###############################################################################################
# def initialize_CPA_meas():
# required_servo = int(tp.servo_error[0])
# required_band = int(tp.servo_error[1])
# required_nframes = required_servo + required_band + 1
# CPA_maps = np.zeros((required_nframes, ap.n_wvl_init, sp.grid_size, sp.grid_size))
#
# with open(iop.CPA_meas, 'wb') as handle:
# pickle.dump((CPA_maps, np.arange(0, -required_nframes, -1)), handle, protocol=pickle.HIGHEST_PROTOCOL)
#
#
# def initialize_NCPA_meas():
# Imaps = np.zeros((4, sp.grid_size, sp.grid_size))
# phase_map = np.zeros((tp.ao_act, tp.ao_act)) # np.zeros((sp.grid_size,sp.grid_size))
# with open(iop.NCPA_meas, 'wb') as handle:
# pickle.dump((Imaps, phase_map, 0), handle, protocol=pickle.HIGHEST_PROTOCOL)
| [
"proper.prop_begin",
"proper.prop_zernikes",
"numpy.random.uniform",
"os.makedirs",
"os.path.isdir",
"numpy.zeros",
"proper.prop_add_phase",
"os.path.isfile",
"numpy.array",
"proper.prop_psd_errormap",
"numpy.random.normal"
] | [((3214, 3276), 'proper.prop_begin', 'proper.prop_begin', (['lens_diam', '(1.0)', 'sp.grid_size', 'sp.beam_ratio'], {}), '(lens_diam, 1.0, sp.grid_size, sp.beam_ratio)\n', (3231, 3276), False, 'import proper\n'), ((3292, 3333), 'numpy.zeros', 'np.zeros', (['(1, sp.grid_size, sp.grid_size)'], {}), '((1, sp.grid_size, sp.grid_size))\n', (3300, 3333), True, 'import numpy as np\n'), ((3955, 4050), 'proper.prop_psd_errormap', 'proper.prop_psd_errormap', (['wfo', 'rms_error', 'c_freq', 'high_power'], {'TPF': '(True)', 'PHASE_HISTORY': 'phase'}), '(wfo, rms_error, c_freq, high_power, TPF=True,\n PHASE_HISTORY=phase)\n', (3979, 4050), False, 'import proper\n'), ((2887, 2913), 'os.path.isdir', 'os.path.isdir', (['iop.aberdir'], {}), '(iop.aberdir)\n', (2900, 2913), False, 'import os\n'), ((3102, 3141), 'os.makedirs', 'os.makedirs', (['iop.aberdir'], {'exist_ok': '(True)'}), '(iop.aberdir, exist_ok=True)\n', (3113, 3141), False, 'import os\n'), ((4640, 4664), 'os.path.isfile', 'os.path.isfile', (['filename'], {}), '(filename)\n', (4654, 4664), False, 'import os\n'), ((6506, 6542), 'proper.prop_add_phase', 'proper.prop_add_phase', (['wf', 'phase_map'], {}), '(wf, phase_map)\n', (6527, 6542), False, 'import proper\n'), ((6615, 6641), 'numpy.array', 'np.array', (['[175, -150, 200]'], {}), '([175, -150, 200])\n', (6623, 6641), True, 'import numpy as np\n'), ((7220, 7267), 'proper.prop_zernikes', 'proper.prop_zernikes', (['wf', 'zern_order', 'zern_vals'], {}), '(wf, zern_order, zern_vals)\n', (7240, 7267), False, 'import proper\n'), ((3875, 3927), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': '(sp.grid_size, sp.grid_size)'}), '(size=(sp.grid_size, sp.grid_size))\n', (3892, 3927), True, 'import numpy as np\n'), ((8297, 8349), 'numpy.random.normal', 'np.random.normal', (["z_range['r1'][0]", "z_range['r1'][1]"], {}), "(z_range['r1'][0], z_range['r1'][1])\n", (8313, 8349), True, 'import numpy as np\n'), ((8399, 8451), 'numpy.random.normal', 'np.random.normal', (["z_range['r2'][0]", "z_range['r2'][1]"], {}), "(z_range['r2'][0], z_range['r2'][1])\n", (8415, 8451), True, 'import numpy as np\n'), ((8501, 8553), 'numpy.random.normal', 'np.random.normal', (["z_range['r3'][0]", "z_range['r3'][1]"], {}), "(z_range['r3'][0], z_range['r3'][1])\n", (8517, 8553), True, 'import numpy as np\n'), ((8603, 8655), 'numpy.random.normal', 'np.random.normal', (["z_range['r4'][0]", "z_range['r4'][1]"], {}), "(z_range['r4'][0], z_range['r4'][1])\n", (8619, 8655), True, 'import numpy as np\n'), ((8705, 8757), 'numpy.random.normal', 'np.random.normal', (["z_range['r5'][0]", "z_range['r5'][1]"], {}), "(z_range['r5'][0], z_range['r5'][1])\n", (8721, 8757), True, 'import numpy as np\n'), ((8807, 8859), 'numpy.random.normal', 'np.random.normal', (["z_range['r6'][0]", "z_range['r6'][1]"], {}), "(z_range['r6'][0], z_range['r6'][1])\n", (8823, 8859), True, 'import numpy as np\n'), ((8909, 8961), 'numpy.random.normal', 'np.random.normal', (["z_range['r7'][0]", "z_range['r7'][1]"], {}), "(z_range['r7'][0], z_range['r7'][1])\n", (8925, 8961), True, 'import numpy as np\n'), ((9011, 9063), 'numpy.random.normal', 'np.random.normal', (["z_range['r8'][0]", "z_range['r8'][1]"], {}), "(z_range['r8'][0], z_range['r8'][1])\n", (9027, 9063), True, 'import numpy as np\n')] |
import matplotlib.pyplot as plt
from matplotlib import colors
from matplotlib import cm
import numpy as np
import pandas as pd
from sklearn import metrics
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
def logistic_model(data, cell_types, sparsity=0.2, fraction=0.5):
X = (data / data.std()).dropna(1)
X_train, X_test, y_train, y_test = \
train_test_split(X, cell_types, test_size=fraction)
lr = LogisticRegression(penalty='l1', C=sparsity)
lr.fit(X_train, y_train)
y_prob = lr.predict_proba(X_test)
print((lr.coef_ > 0).sum(1))
lr_res = pd.DataFrame.from_records(lr.coef_, columns=X.columns)
return y_prob, y_test, lr_res, lr
def create_colors(lr):
n_cts = lr.classes_.shape[0]
color_norm = colors.Normalize(vmin=-n_cts / 3, vmax=n_cts)
ct_arr = np.arange(n_cts)
ct_colors = cm.YlOrRd(color_norm(ct_arr))
return ct_colors
def plot_roc(y_prob, y_test, lr):
ct_colors = create_colors(lr)
for i, cell_type in enumerate(lr.classes_):
fpr, tpr, _ = metrics.roc_curve(y_test == cell_type, y_prob[:, i])
plt.plot(fpr, tpr, c=ct_colors[i], lw=2)
plt.plot([0, 1], [0, 1], color='k', ls=':')
plt.xlabel('FPR')
plt.ylabel('TPR')
def get_top_markers(lr_res, N):
top_markers = \
lr_res \
.assign(cluster=lr_res.index) \
.melt(id_vars=['cluster'], var_name='gene', value_name='weight') \
.sort_values('weight', ascending=False) \
.groupby('cluster') \
.head(N) \
.sort_values(['cluster', 'weight'], ascending=[True, False])
return top_markers
def plot_marker_map(data, cell_types, top_markers):
sizes = pd.Series(cell_types, index=data.index).value_counts()
c_idx = pd.Series(cell_types, index=data.index).map(sizes).sort_values(ascending=False).index
g_idx = top_markers \
.assign(sizes=top_markers.cluster.map(sizes)) \
.sort_values('sizes', ascending=False) \
.gene[::-1]
marker_map = data.reindex(index=c_idx, columns=g_idx)
plt.pcolormesh(marker_map.T, cmap=cm.gray_r)
plt.colorbar(label='Expression')
for vl in sizes.cumsum():
plt.axvline(vl, lw=0.66, c='r')
plt.ylabel('Marker genes')
plt.xlabel('Cells')
def plot_marker_table(top_markers, lr, n_columns=5, max_rows=10):
ct_colors = create_colors(lr)
for i, m in enumerate(top_markers['cluster'].unique()):
plt.subplot(max_rows, n_columns, i + 1)
g = top_markers.query('cluster == @m')
plt.title(m, size=12, weight='bold', ha='left')
for j, gn in enumerate(g.iterrows()):
_, gn = gn
plt.annotate(f'{gn.weight:.2f} - {gn.gene}', (0, 0.2 * j), )
plt.axis('off')
plt.ylim((n_columns + 1) * 0.2, -0.2)
ax = plt.gca()
ax.plot([0.5, 1], [1, 1], transform=ax.transAxes, lw=3, c=ct_colors[i])
plt.tight_layout()
def html_marker_table(top_markers, n_columns=5):
html_str = '<table>'
for i, m in enumerate(top_markers['cluster'].unique()):
if i % n_columns == 0:
html_str += '<tr>'
html_str += '<td style="text-align: left;"><pre>'
g = top_markers.query('cluster == @m')
html_str += f'{m}\n-----\n'
for j, gn in enumerate(g.iterrows()):
_, gn = gn
if gn.weight == 0:
html_str += '\n'
continue
html_str += f'{gn.weight:.2}\t{gn.gene}\n'
html_str += '</pre></td>'
if i % n_columns == n_columns - 1:
html_str += '</tr>'
html_str += '</table>'
return html_str
| [
"matplotlib.pyplot.title",
"sklearn.model_selection.train_test_split",
"numpy.arange",
"matplotlib.pyplot.gca",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.axvline",
"matplotlib.colors.Normalize",
"matplotlib.pyplot.colorbar",
"matplotlib.pyplot.ylim",
"sklearn.linear_model.LogisticRegres... | [((411, 462), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'cell_types'], {'test_size': 'fraction'}), '(X, cell_types, test_size=fraction)\n', (427, 462), False, 'from sklearn.model_selection import train_test_split\n'), ((473, 517), 'sklearn.linear_model.LogisticRegression', 'LogisticRegression', ([], {'penalty': '"""l1"""', 'C': 'sparsity'}), "(penalty='l1', C=sparsity)\n", (491, 517), False, 'from sklearn.linear_model import LogisticRegression\n'), ((633, 687), 'pandas.DataFrame.from_records', 'pd.DataFrame.from_records', (['lr.coef_'], {'columns': 'X.columns'}), '(lr.coef_, columns=X.columns)\n', (658, 687), True, 'import pandas as pd\n'), ((802, 847), 'matplotlib.colors.Normalize', 'colors.Normalize', ([], {'vmin': '(-n_cts / 3)', 'vmax': 'n_cts'}), '(vmin=-n_cts / 3, vmax=n_cts)\n', (818, 847), False, 'from matplotlib import colors\n'), ((861, 877), 'numpy.arange', 'np.arange', (['n_cts'], {}), '(n_cts)\n', (870, 877), True, 'import numpy as np\n'), ((1194, 1237), 'matplotlib.pyplot.plot', 'plt.plot', (['[0, 1]', '[0, 1]'], {'color': '"""k"""', 'ls': '""":"""'}), "([0, 1], [0, 1], color='k', ls=':')\n", (1202, 1237), True, 'import matplotlib.pyplot as plt\n'), ((1242, 1259), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""FPR"""'], {}), "('FPR')\n", (1252, 1259), True, 'import matplotlib.pyplot as plt\n'), ((1264, 1281), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""TPR"""'], {}), "('TPR')\n", (1274, 1281), True, 'import matplotlib.pyplot as plt\n'), ((2091, 2135), 'matplotlib.pyplot.pcolormesh', 'plt.pcolormesh', (['marker_map.T'], {'cmap': 'cm.gray_r'}), '(marker_map.T, cmap=cm.gray_r)\n', (2105, 2135), True, 'import matplotlib.pyplot as plt\n'), ((2140, 2172), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {'label': '"""Expression"""'}), "(label='Expression')\n", (2152, 2172), True, 'import matplotlib.pyplot as plt\n'), ((2249, 2275), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Marker genes"""'], {}), "('Marker genes')\n", (2259, 2275), True, 'import matplotlib.pyplot as plt\n'), ((2280, 2299), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Cells"""'], {}), "('Cells')\n", (2290, 2299), True, 'import matplotlib.pyplot as plt\n'), ((2935, 2953), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (2951, 2953), True, 'import matplotlib.pyplot as plt\n'), ((1087, 1139), 'sklearn.metrics.roc_curve', 'metrics.roc_curve', (['(y_test == cell_type)', 'y_prob[:, i]'], {}), '(y_test == cell_type, y_prob[:, i])\n', (1104, 1139), False, 'from sklearn import metrics\n'), ((1148, 1188), 'matplotlib.pyplot.plot', 'plt.plot', (['fpr', 'tpr'], {'c': 'ct_colors[i]', 'lw': '(2)'}), '(fpr, tpr, c=ct_colors[i], lw=2)\n', (1156, 1188), True, 'import matplotlib.pyplot as plt\n'), ((2212, 2243), 'matplotlib.pyplot.axvline', 'plt.axvline', (['vl'], {'lw': '(0.66)', 'c': '"""r"""'}), "(vl, lw=0.66, c='r')\n", (2223, 2243), True, 'import matplotlib.pyplot as plt\n'), ((2471, 2510), 'matplotlib.pyplot.subplot', 'plt.subplot', (['max_rows', 'n_columns', '(i + 1)'], {}), '(max_rows, n_columns, i + 1)\n', (2482, 2510), True, 'import matplotlib.pyplot as plt\n'), ((2566, 2613), 'matplotlib.pyplot.title', 'plt.title', (['m'], {'size': '(12)', 'weight': '"""bold"""', 'ha': '"""left"""'}), "(m, size=12, weight='bold', ha='left')\n", (2575, 2613), True, 'import matplotlib.pyplot as plt\n'), ((2765, 2780), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (2773, 2780), True, 'import matplotlib.pyplot as plt\n'), ((2789, 2826), 'matplotlib.pyplot.ylim', 'plt.ylim', (['((n_columns + 1) * 0.2)', '(-0.2)'], {}), '((n_columns + 1) * 0.2, -0.2)\n', (2797, 2826), True, 'import matplotlib.pyplot as plt\n'), ((2840, 2849), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (2847, 2849), True, 'import matplotlib.pyplot as plt\n'), ((1722, 1761), 'pandas.Series', 'pd.Series', (['cell_types'], {'index': 'data.index'}), '(cell_types, index=data.index)\n', (1731, 1761), True, 'import pandas as pd\n'), ((2695, 2753), 'matplotlib.pyplot.annotate', 'plt.annotate', (['f"""{gn.weight:.2f} - {gn.gene}"""', '(0, 0.2 * j)'], {}), "(f'{gn.weight:.2f} - {gn.gene}', (0, 0.2 * j))\n", (2707, 2753), True, 'import matplotlib.pyplot as plt\n'), ((1789, 1828), 'pandas.Series', 'pd.Series', (['cell_types'], {'index': 'data.index'}), '(cell_types, index=data.index)\n', (1798, 1828), True, 'import pandas as pd\n')] |
import cv2
import time
import math
import random
import argparse
import numpy as np
import numpy.matlib as npmatlib
import matplotlib.pyplot as plt
from PIL import Image, ImageFilter
import statistics as stat
from skimage import io
from skimage import data
from skimage import color
from skimage.color import rgb2gray
from skimage.filters import gaussian
from skimage.measure import regionprops
from skimage.segmentation import active_contour
from skimage.filters import meijering, sato, frangi, hessian
from scipy.ndimage.filters import uniform_filter
from scipy.ndimage.measurements import variance
def auto_canny(image, sigma = 0.7):
# compute the median of the single channel pixel intensities
v = np.median(image)
# apply automatic Canny edge detection using the computed median
lower = int(max(0, (1.0 - sigma) * v))
upper = int(min(255, (1.0 + sigma) * v)/2)
#print(lower)
#print(upper)
edged = cv2.Canny(image, lower, upper)
# return the edged image
return edged
def nothing(x):
pass
def crimmins(data):
new_image = data.copy()
nrow = len(data)
ncol = len(data[0])
# Dark pixel adjustment
# First Step
# N-S
for i in range(1, nrow):
for j in range(ncol):
if data[i-1,j] >= (data[i,j] + 2):
new_image[i,j] += 1
data = new_image
# E-W
for i in range(nrow):
for j in range(ncol-1):
if data[i,j+1] >= (data[i,j] + 2):
new_image[i,j] += 1
data = new_image
# NW-SE
for i in range(1, nrow):
for j in range(1, ncol):
if data[i-1,j-1] >= (data[i,j] + 2):
new_image[i,j] += 1
data = new_image
#NE-SW
for i in range(1, nrow):
for j in range(ncol-1):
if data[i-1,j+1] >= (data[i,j] + 2):
new_image[i,j] += 1
data = new_image
# Second Step
# N-S
for i in range(1, nrow-1):
for j in range(ncol):
if (data[i-1,j] > data[i,j]) and (data[i,j] <= data[i+1,j]):
new_image[i,j] += 1
data = new_image
# E-W
for i in range(nrow):
for j in range(1, ncol-1):
if (data[i,j+1] > data[i,j]) and (data[i,j] <= data[i,j-1]):
new_image[i,j] += 1
data = new_image
# NW-SE
for i in range(1, nrow-1):
for j in range(1, ncol-1):
if (data[i-1,j-1] > data[i,j]) and (data[i,j] <= data[i+1,j+1]):
new_image[i,j] += 1
data = new_image
# NE-SW
for i in range(1, nrow-1):
for j in range(1, ncol-1):
if (data[i-1,j+1] > data[i,j]) and (data[i,j] <= data[i+1,j-1]):
new_image[i,j] += 1
data = new_image
#Third Step
# N-S
for i in range(1, nrow-1):
for j in range(ncol):
if (data[i+1,j] > data[i,j]) and (data[i,j] <= data[i-1,j]):
new_image[i,j] += 1
data = new_image
# E-W
for i in range(nrow):
for j in range(1, ncol-1):
if (data[i,j-1] > data[i,j]) and (data[i,j] <= data[i,j+1]):
new_image[i,j] += 1
data = new_image
# NW-SE
for i in range(1, nrow-1):
for j in range(1, ncol-1):
if (data[i+1,j+1] > data[i,j]) and (data[i,j] <= data[i-1,j-1]):
new_image[i,j] += 1
data = new_image
# NE-SW
for i in range(1, nrow-1):
for j in range(1, ncol-1):
if (data[i+1,j-1] > data[i,j]) and (data[i,j] <= data[i-1,j+1]):
new_image[i,j] += 1
data = new_image
# Fourth Step
# N-S
for i in range(nrow-1):
for j in range(ncol):
if (data[i+1,j] >= (data[i,j]+2)):
new_image[i,j] += 1
data = new_image
# E-W
for i in range(nrow):
for j in range(1,ncol):
if (data[i,j-1] >= (data[i,j]+2)):
new_image[i,j] += 1
data = new_image
# NW-SE
for i in range(nrow-1):
for j in range(ncol-1):
if (data[i+1,j+1] >= (data[i,j]+2)):
new_image[i,j] += 1
data = new_image
# NE-SW
for i in range(nrow-1):
for j in range(1,ncol):
if (data[i+1,j-1] >= (data[i,j]+2)):
new_image[i,j] += 1
data = new_image
# Light pixel adjustment
# First Step
# N-S
for i in range(1,nrow):
for j in range(ncol):
if (data[i-1,j] <= (data[i,j]-2)):
new_image[i,j] -= 1
data = new_image
# E-W
for i in range(nrow):
for j in range(ncol-1):
if (data[i,j+1] <= (data[i,j]-2)):
new_image[i,j] -= 1
data = new_image
# NW-SE
for i in range(1,nrow):
for j in range(1,ncol):
if (data[i-1,j-1] <= (data[i,j]-2)):
new_image[i,j] -= 1
data = new_image
# NE-SW
for i in range(1,nrow):
for j in range(ncol-1):
if (data[i-1,j+1] <= (data[i,j]-2)):
new_image[i,j] -= 1
data = new_image
# Second Step
# N-S
for i in range(1,nrow-1):
for j in range(ncol):
if (data[i-1,j] < data[i,j]) and (data[i,j] >= data[i+1,j]):
new_image[i,j] -= 1
data = new_image
# E-W
for i in range(nrow):
for j in range(1, ncol-1):
if (data[i,j+1] < data[i,j]) and (data[i,j] >= data[i,j-1]):
new_image[i,j] -= 1
data = new_image
# NW-SE
for i in range(1,nrow-1):
for j in range(1,ncol-1):
if (data[i-1,j-1] < data[i,j]) and (data[i,j] >= data[i+1,j+1]):
new_image[i,j] -= 1
data = new_image
# NE-SW
for i in range(1,nrow-1):
for j in range(1,ncol-1):
if (data[i-1,j+1] < data[i,j]) and (data[i,j] >= data[i+1,j-1]):
new_image[i,j] -= 1
data = new_image
# Third Step
# N-S
for i in range(1,nrow-1):
for j in range(ncol):
if (data[i+1,j] < data[i,j]) and (data[i,j] >= data[i-1,j]):
new_image[i,j] -= 1
data = new_image
# E-W
for i in range(nrow):
for j in range(1,ncol-1):
if (data[i,j-1] < data[i,j]) and (data[i,j] >= data[i,j+1]):
new_image[i,j] -= 1
data = new_image
# NW-SE
for i in range(1,nrow-1):
for j in range(1,ncol-1):
if (data[i+1,j+1] < data[i,j]) and (data[i,j] >= data[i-1,j-1]):
new_image[i,j] -= 1
data = new_image
# NE-SW
for i in range(1,nrow-1):
for j in range(1,ncol-1):
if (data[i+1,j-1] < data[i,j]) and (data[i,j] >= data[i-1,j+1]):
new_image[i,j] -= 1
data = new_image
# Fourth Step
# N-S
for i in range(nrow-1):
for j in range(ncol):
if (data[i+1,j] <= (data[i,j]-2)):
new_image[i,j] -= 1
data = new_image
# E-W
for i in range(nrow):
for j in range(1,ncol):
if (data[i,j-1] <= (data[i,j]-2)):
new_image[i,j] -= 1
data = new_image
# NW-SE
for i in range(nrow-1):
for j in range(ncol-1):
if (data[i+1,j+1] <= (data[i,j]-2)):
new_image[i,j] -= 1
data = new_image
# NE-SW
for i in range(nrow-1):
for j in range(1,ncol):
if (data[i+1,j-1] <= (data[i,j]-2)):
new_image[i,j] -= 1
data = new_image
return new_image.copy()
def crop(img, i):
# Returns dimensions of image
height, width = img.shape[0:2]
# Top and Bottom range
startrow = int(height*.12)
endrow = int(height*.88)
startcol = int(width*.05)
endcol = int(width*0.95)
img = img[startrow:endrow, startcol:endcol]
height, width = img.shape[0:2]
# Finds the side of the Optic Disk
side = find_eyeside(img, i)
# Left and Right range
if side == 'r':
startcol = int(width*.40)
endcol = int(width-10)
elif side == 'l':
startcol = int(10)
endcol = int(width*.60)
image = img[0:height, startcol:endcol]
height, width = img.shape[0:2]
image = image[20:520, 20:520]
return image
def conservative_smoothing_gray(data, filter_size):
temp = []
indexer = filter_size // 2
new_image = data.copy()
nrow, ncol = data.shape[0:2]
for i in range(nrow):
for j in range(ncol):
for k in range(i-indexer, i+indexer+1):
for m in range(j-indexer, j+indexer+1):
if (k > -1) and (k < nrow):
if (m > -1) and (m < ncol):
temp.append(data[k,m])
temp.remove(data[i,j])
max_value = max(temp)
min_value = min(temp)
if data[i,j] > max_value:
new_image[i,j] = max_value
elif data[i,j] < min_value:
new_image[i,j] = min_value
temp =[]
return new_image.copy()
"""
def window_function(img):
min_avg_px = np.zeros(5)
sum_px = 0
avg_px = 0.0
cntr = 0
i_min = 0
i_max = 0
j_min = 0
j_max = 0
height,width = img.shape[0:2]
for k in range(3):
for l in range(3):
i_min = math.floor(0.125*width)*k
i_max = min((math.floor(0.5*width)+math.floor(0.125*width)*k),width)
j_min = math.floor(0.1*height)*l
j_max = min((math.floor(0.4*height)+math.floor(0.1*height)*l),height)
sum_px = 0
avg_px = 0.0
cntr = 0
for i in range(i_min,i_max):
for j in range(j_min,j_max):
sum_px = sum_px + img[j,i]
cntr = cntr + 1
if(k==0 and l==0):
min_avg_px[0] = float(sum_px/cntr)
avg_px = float(sum_px/cntr)
if(avg_px<min_avg_px[0]):
min_avg_px[0] = avg_px
min_avg_px[1] = i_min
min_avg_px[2] = i_max
min_avg_px[3] = j_min
min_avg_px[4] = j_max
w_img = np.zeros((int(min_avg_px[4]-min_avg_px[3]),int(min_avg_px[2] - min_avg_px[1])))
for i in range(int(min_avg_px[1]),int(min_avg_px[2])):
for j in range(int(min_avg_px[3]),int(min_avg_px[4])):
w_img[(j-int(min_avg_px[3])),(i-int(min_avg_px[1]))] = img[j,i]
cv2.imwrite('window6_open.jpeg',w_img)
cv2.waitKey(0)
"""
def write_image(path, img):
# img = img*(2**16-1)
# img = img.astype(np.uint16)
# img = img.astype(np.uint8)
cv2.imwrite(path,img)
# Convert the scale (values range) of the image
#img = cv2.convertScaleAbs(img, alpha=(255.0))
# Save file
#plt.savefig(path, bbox_inches='tight')#, img, format = 'png')
def find_eyeside(img, i):
#side = input('Enter the Optic-Disk Side (R or L): ')
#side = 'r'
kernel = kernel = np.ones((25,25),np.uint8)
opening = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)
m, n = img.shape[0:2]
min_intensity = 255
for a in range(m):
for b in range(n):
if opening[a,b] < min_intensity:
min_intensity = opening[a,b]
x = a
y = b
if y > n/2:
side = 'r'
elif y <= n/2:
side = 'l'
return side
def lee_filter(img, size):
img_mean = uniform_filter(img, (size, size))
img_sqr_mean = uniform_filter(img**2, (size, size))
img_variance = img_sqr_mean - img_mean**2
overall_variance = variance(img)
img_weights = img_variance / (img_variance + overall_variance)
img_output = img_mean + img_weights * (img - img_mean)
return img_output
def segment(img, blur=0.01, alpha=0.1, beta=0.1, gamma=0.001):
height, width = img.shape[0:2]
# Initial contour
s = np.linspace(0, 2*np.pi, 400)
#r = int(height/2*np.ones(len(s)) + height*np.sin(s)/2)
#c = int(width/2*np.ones(len(s)) + width*np.cos(s)/2)
row = int(height/2)
column = int(width/2)
r = row + (row-10)*np.sin(s)
c = column + (column-10)*np.cos(s)
init = np.array([r, c]).T
# Parameters for Active Contour
blur = 0.01
alpha = 0.1
beta = 0.1
gamma = 0.001
w_line = -5
w_edge = 0
# Active contour
snake = active_contour(gaussian(img, blur), init, alpha, beta, gamma, coordinates='rc')
#snake = active_contour(gaussian(img, 1), init, alpha, beta, w_line, w_edge, gamma, coordinates='rc')
# boundary_condition='fixed' blur = 1, alpha = 0.1, beta=1, w_line = -5, w_edge=0, gamma = 0.1
# Display the image with contour
fig, ax = plt.subplots(figsize=(7, 7))
ax.imshow(img, cmap=plt.cm.gray)
ax.plot(init[:, 1], init[:, 0], '--r', lw=3)
ax.plot(snake[:, 1], snake[:, 0], '-b', lw=3)
ax.set_xticks([]), ax.set_yticks([])
ax.axis([0, img.shape[1], img.shape[0], 0])
plt.show()
def filterimage(img):
#cv2.imshow('i',img)
#croppedImage = img[startRow:endRow, startCol:endCol]
kernel = np.ones((5,5),np.uint8)
dilation = cv2.dilate(img,kernel,iterations = 1)
blur = dilation
#blur = cv2.GaussianBlur(dilation,(5,5),0)
#blur = cv2.blur(dilation,(5,5))
#plt.imshow(blur,cmap = 'gray')
#plt.show()
#dilation = cv2.dilate(blur,kernel,iterations = 1)
#blur = cv2.GaussianBlur(dilation,(5,5),0)
#blur = cv2.GaussianBlur(im,(5,5),0)
erosion = cv2.erode(blur,kernel,iterations = 1)
#blur = cv2.blur(erosion,(10,10),0)
plt.imshow(blur,cmap = 'gray')
plt.show()
opening = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)
closing = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)
gradient = cv2.morphologyEx(blur, cv2.MORPH_GRADIENT, kernel)
dil = cv2.erode(gradient,kernel,iterations = 1)
plt.subplot(2,3,1),plt.imshow(img,cmap = 'gray')
plt.title('Original'), plt.xticks([]), plt.yticks([])
plt.subplot(2,3,2),plt.imshow(erosion,cmap = 'gray')
plt.title('Erosion'), plt.xticks([]), plt.yticks([])
plt.subplot(2,3,3),plt.imshow(dilation,cmap = 'gray')
plt.title('Dilation'), plt.xticks([]), plt.yticks([])
plt.subplot(2,3,4),plt.imshow(opening,cmap = 'gray')
plt.title('Opening'), plt.xticks([]), plt.yticks([])
plt.subplot(2,3,5),plt.imshow(dil,cmap = 'gray')
plt.title('Dil'), plt.xticks([]), plt.yticks([])
plt.subplot(2,3,6),plt.imshow(gradient,cmap = 'gray')
plt.title('Gradient'), plt.xticks([]), plt.yticks([])
plt.show()
laplacian = cv2.Laplacian(img,cv2.CV_64F)
sobelx = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=5)
sobely = cv2.Sobel(img,cv2.CV_64F,0,1,ksize=5)
sobel = cv2.addWeighted(np.absolute(sobelx), 0.5, np.absolute(sobely), 0.5, 0)
#sobel = cv2.Sobel(img,cv2.CV_64F,1,1,ksize=5)
sobel = cv2.erode(sobel,kernel,iterations = 1)
plt.subplot(2,2,1),plt.imshow(sobel,cmap = 'gray')
plt.title('Sobel'), plt.xticks([]), plt.yticks([])
plt.subplot(2,2,2),plt.imshow(laplacian,cmap = 'gray')
plt.title('Laplacian'), plt.xticks([]), plt.yticks([])
plt.subplot(2,2,3),plt.imshow(sobelx,cmap = 'gray')
plt.title('Sobel X'), plt.xticks([]), plt.yticks([])
plt.subplot(2,2,4),plt.imshow(sobely,cmap = 'gray')
plt.title('<NAME>'), plt.xticks([]), plt.yticks([])
plt.show()
def houghcircles(img):
#creating mask??
#median_blur_copy_img = cv2.medianBlur(copy_img, 5)
m, n = img.shape[0:2]
copy_img = np.zeros((m,n))
copy_img = img.copy()
median_blur_copy_img = cv2.medianBlur(img, 5)
circles = cv2.HoughCircles(median_blur_copy_img, cv2.HOUGH_GRADIENT, dp=1, minDist=200, param1=25, param2=50, minRadius=0, maxRadius=0)
circles = np.around(circles)
circles = np.uint16(circles)
#print(circles)
# draw mask
mask = np.full((img.shape[0], img.shape[1]), 0, dtype=np.uint8)
mask = np.full((img.shape[0], img.shape[1]), 0, dtype=np.uint8)
for i in circles[0, :]:
cv2.circle(mask, (i[0], i[1]), i[2], (255, 255, 255), -1)
# get first masked value (foreground)
#fg = cv2.bitwise_or(copy_img, copy_img, mask=mask)
fg = cv2.bitwise_or(img, img, mask=mask)
# get second masked value (background) mask must be inverted
mask = cv2.bitwise_not(mask)
# background = np.full(copy_img.shape, 255, dtype=np.uint8)
background = np.full(img.shape, 255, dtype=np.uint8)
bk = cv2.bitwise_or(background, background, mask=mask)
# combine foreground+background
final = cv2.bitwise_or(fg, bk)
plt.subplot(2,3,1),plt.imshow(img,cmap = 'gray')
plt.title('equ'), plt.xticks([]), plt.yticks([])
plt.subplot(2,3,2),plt.imshow(copy_img,cmap = 'gray')
plt.title('equ+bottomHat1'), plt.xticks([]), plt.yticks([])
plt.subplot(2,3,3),plt.imshow(bk,cmap = 'gray')
plt.title('bk(mask)'), plt.xticks([]), plt.yticks([])
plt.subplot(2,3,4),plt.imshow(fg,cmap = 'gray')
plt.title('fg'), plt.xticks([]), plt.yticks([])
plt.subplot(2,3,5),plt.imshow(final,cmap = 'gray')
plt.title('final'), plt.xticks([]), plt.yticks([])
plt.show()
return final
def removeBloodVessels(img,th_0,th_1):
globalMin = 0
globalMax = 255 # it is the maximum gray level of the image
img_flat = img.flatten()
localMin = np.min(img_flat[np.nonzero(img_flat)]) # minimum non-zero intensity value of the taken image
localMax = max(img_flat) # maximum intensity value of the taken image
m, n = img.shape[0:2]
kernel1 = np.ones((25,25),np.uint8)
kernel0 = np.zeros((25,25),np.uint8)
copy_img = np.zeros((m,n))
copy_img = img.copy()
for i in range(m):
for j in range(n):
copy_img[i,j] = ((copy_img[i,j]-localMin)* ((globalMax-globalMin))/((localMax-localMin))) + globalMin
closing1 = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel1)
closing0 = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel0)
bottomHat1 = closing1 - copy_img
bottomHat0 = closing0 - copy_img
for i in range(m):
for j in range(n):
if bottomHat0[i,j] < th_0:
bottomHat0[i,j] = 0
else:
bottomHat0[i,j] = 255
if bottomHat1[i,j] < th_1:
bottomHat1[i,j] = 0
'''
alpha = 2
beta = -125
bottomHat1 = cv2.convertScaleAbs(bottomHat1, alpha=alpha, beta=beta)
new_greyimage = np.zeros((m,n),np.uint8)
for i in range(m):
for j in range(n):
if (bottomHat0[i,j] == 255):
new_greyimage[i,j] = bottomHat1[i,j]
'''
for i in range(m):
for j in range(n):
copy_img[i,j] = img[i,j] + bottomHat1[i,j]
if(copy_img[i,j]>255):
copy_img[i,j] = 255
"""
plt.subplot(2,2,1),plt.imshow(img,cmap = 'gray')
plt.title('crim'), plt.xticks([]), plt.yticks([])
plt.subplot(2,2,2),plt.imshow(bottomHat1,cmap = 'gray')
plt.title('bottomHat1'), plt.xticks([]), plt.yticks([])
plt.subplot(2,2,3),plt.imshow(bottomHat0,cmap = 'gray')
plt.title('bottomHat0'), plt.xticks([]), plt.yticks([])
plt.subplot(2,2,4),plt.imshow(copy_img,cmap = 'gray')
plt.title('crim+bottomHat1'), plt.xticks([]), plt.yticks([])
plt.show()
"""
#cv2.waitKey(0)
#enhancedVessel1 = meijering(new_greyimage)
#enhancedVessel2 = frangi(new_greyimage)
#new_greyimage = cv2.addWeighted(enhancedVessel1,0.5,enhancedVessel2,0.5,0.0)
#cv2.imshow('fuse',new_greyimage)
#cv2.waitKey(0)
return bottomHat0, bottomHat1
def threshold_tb(image, threshold = 50, th_type = 3):
alpha = 180
beta = 125
s = 0
cv2.namedWindow('Contrast')
# create trackbars for color change
cv2.createTrackbar('alpha','Contrast', alpha, 255, nothing)
cv2.createTrackbar('beta','Contrast', beta, 255, nothing)
cv2.createTrackbar('Threshold','Contrast', threshold, 255, nothing)
cv2.createTrackbar('Type','Contrast', th_type, 4, nothing)
# create switch for ON/OFF functionality
cv2.createTrackbar('Switch', 'Contrast', s, 1, nothing)
# get current positions of four trackbars
while(s == 0):
alpha = cv2.getTrackbarPos('alpha','Contrast')
beta = cv2.getTrackbarPos('beta','Contrast')
threshold = cv2.getTrackbarPos('Threshold','Contrast')
th_type = cv2.getTrackbarPos('Type','Contrast')
s = cv2.getTrackbarPos('Switch','Contrast')
"""
#0: Binary
#1: Binary Inverted
#2: Threshold Truncated
#3: Threshold to Zero
#4: Threshold to Zero Inverted
"""
_, dst = cv2.threshold(image, threshold, 255, th_type)
cv2.imshow('Threshold', dst)
k = cv2.waitKey(1) & 0xFF
if k == 27:
break
cv2.destroyAllWindows()
return dst
def bottomhat_tb(image, th_0 = 200, th_1 = 10):
s = 0
cv2.namedWindow('Trackbar')
img = image
# create trackbars for color change
cv2.createTrackbar('Bottom Hat 0','Trackbar', th_0, 255, nothing)
cv2.createTrackbar('Bottom Hat 1','Trackbar', th_1, 255, nothing)
cv2.createTrackbar('Switch', 'Trackbar', 0, 1, nothing)
# get current positions of four trackbars
while(s==0):
th_0 = cv2.getTrackbarPos('Bottom Hat 0','Trackbar')
th_1 = cv2.getTrackbarPos('Bottom Hat 1','Trackbar')
s = cv2.getTrackbarPos('Switch','Trackbar')
bottomhat0, bottomhat1 = removeBloodVessels(image, th_0, th_1)
image = img
cv2.imshow('BottomHat0', bottomhat0)
#cv2.imshow('BottomHat1', bottomhat1)
k = cv2.waitKey(1) & 0xFF
if k == 27:
break
return bottomhat0, bottomhat1
def adaptive_tb(image, mth1=11, mth2=2, gth1=11, gth2=2):
s = 0
img = cv2.medianBlur(image,5)
cv2.namedWindow('Contrast')
# create trackbars for color change
cv2.createTrackbar('Mean Threshold 1', 'Contrast', mth1, 255, nothing)
cv2.createTrackbar('Mean Threshold 2', 'Contrast', mth2, 255, nothing)
cv2.createTrackbar('Gaussian Threshold 1', 'Contrast', gth1, 255, nothing)
cv2.createTrackbar('Gaussian Threshold 2', 'Contrast', gth2, 255, nothing)
# create switch for ON/OFF functionality
cv2.createTrackbar('Switch', 'Contrast', s, 1, nothing)
# get current positions of four trackbars
while(s == 0):
mth1 = cv2.getTrackbarPos('Mean Threshold 1','Contrast')
mth2 = cv2.getTrackbarPos('Mean Threshold 2','Contrast')
gth1 = cv2.getTrackbarPos('Gaussian Threshold 1','Contrast')
gth2 = cv2.getTrackbarPos('Gaussian Threshold 2','Contrast')
s = cv2.getTrackbarPos('Switch','Contrast')
#_, dst = cv2.threshold(image, threshold, 255, th_type)
im1 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2)
im2 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)
cv2.imshow('Image', image)
cv2.imshow('AdaptiveMean', im1)
cv2.imshow('AdaptiveGaussian', im2)
k = cv2.waitKey(1) & 0xFF
if k == 27:
break
im1 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2)
im2 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)
cv2.destroyAllWindows()
return im1, im2
if __name__=="__main__":
# Image files location
location1 = 'Documents\GitHub\Optic_Disk\Images\_OD'
location2 = 'Documents\GitHub\Optic_Disk\Images_Processed\_OD'
# Loop through all the images
for index in range(1, 15):
image1 = location1 + str(index) + '.jpeg' # Filename
image2 = location2 + str(index) + '.jpg' # Filename
img1 = cv2.imread(image1,0) # Read image
img2 = cv2.imread(image2,0) # Read image
img1 = crop(img1, index) # Crop the image
img = img1.copy()
image = img.copy()
final = image.copy()
height, width = img.shape[0:2]
_, bottomhat = removeBloodVessels(image,200,50)
bottomhat = threshold_tb(bottomhat)
alpha = 2
beta = -125
#image = cv2.convertScaleAbs(image, alpha=alpha, beta=beta)
final = image.copy()
prev = np.zeros(10)
for i in range(height):
for j in range(width):
if bottomhat[i,j] == 0:
for a in range(10):
prev[a] = final[i,j-a-1]
a = 1
elif bottomhat[i,j] == 255:
pass
else:
if a == 9:
a = 1
final[i,j] = prev[a]
a=a+1
#final = cv2.GaussianBlur(final,(5,5),0)
#final = cv2.medianBlur(final,3)
final = cv2.blur(final,(5,5))
cv2.imshow('original', image)
cv2.imshow('final', final)
path = 'Documents\GitHub\Optic_Disk\Images_Processed\_VR' + str(index) + '.jpeg'
cv2.imwrite(path, final)
"""
equ = cv2.equalizeHist(final)
clahe1 = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
clahe2 = cv2.createCLAHE(clipLimit=1.5, tileGridSize=(3,3))
cl1 = clahe1.apply(final)
cl2 = clahe2.apply(final)
cv2.imshow('CLAHE1', cl1)
cv2.imshow('CLAHE2', cl2)
"""
cv2.waitKey(0)
cv2.destroyAllWindows()
segment(final)
#_, bottomhat = bottomhat_tb(image)
#mask = threshold_tb(bottomhat, 70)
#path = 'Documents\GitHub\Optic_Disk\BottomHat.jpg'
#mask = cv2.imread(path,0)
#image1 = trackbar(equ,25)
#image = trackbar(clahe,140)
#path = 'Documents\GitHub\Optic_Disk\Images_Processed\_OD' + str(i) + '.jpg'
#image2 = crimmins(image)
#cv2.imwrite(path, image2)
#print('Image ' + str(i) + ' - done')
#image = img
#equ = cv2.equalizeHist(image)
#equ = image - image2
"""
for i in range(height):
for j in range(width):
if (mask[i,j] != 0 and mask[i,j] != 255):
#final[i,j] = mask[i,j]
final[i,j] = 255 - final [i,j]
plt.subplot(1,3,1),plt.imshow(img,cmap = 'gray')
plt.title('IMG'), plt.xticks([]), plt.yticks([])
#plt.subplot(1,3,2),plt.imshow(equ,cmap = 'gray')
#plt.title('EQU'), plt.xticks([]), plt.yticks([])
plt.subplot(1,3,3),plt.imshow(final,cmap = 'gray')
plt.title('Final'), plt.xticks([]), plt.yticks([])
plt.show()
"""
#clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
#cl1 = clahe.apply(image2)
#equ2 = crimmins(equ)
#cl2 = crimmins(cl1)
"""
crim = cl2
unsharp = Image.fromarray(crim.astype('uint8'))
unsharp_class = unsharp.filter(ImageFilter.UnsharpMask(radius=2, percent=150))
unsharp = np.array(unsharp_class)
lee = lee_filter(img,10)
conservative = conservative_smoothing_gray(unsharp,9)
contrast = cv2.convertScaleAbs(conservative,alpha=1.8,beta=-120)
#dst_col = cv2.fastNlMeansDenoisingColored(img,None,10,10,7,21)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray = np.float64(gray)
# Convert back to uint8
noisy = np.uint8(np.clip(img,0,255))
dst_bw = cv2.fastNlMeansDenoisingMulti(noisy, 2, 5, None, 4, 7, 35)
"""
#removeBloodVessels(equ2,110,10)
#removeBloodVessels(equ2,110,10)
#removeBloodVessels(cl2,110,10)
"""
image = crimmins(image)
#alpha = 1.8
#beta = -125
#new_image1 = cv2.convertScaleAbs(image, alpha=alpha, beta=beta)
#new_image1 = cv2.GaussianBlur(new_image1,(5,5),8)
kernel = np.ones((5,5),np.uint8)
dilation = cv2.dilate(image,kernel,iterations = 1)
blur = dilation
opening = cv2.morphologyEx(new_image, cv2.MORPH_OPEN, kernel)
closing = cv2.morphologyEx(new_image, cv2.MORPH_CLOSE, kernel)
gradient = cv2.morphologyEx(opening, cv2.MORPH_GRADIENT, kernel)
dil = cv2.dilate(gradient,kernel,iterations = 1)
edge1 = auto_canny(opening)
edge2 = auto_canny(closing)
sobelx = cv2.Sobel(new_image,cv2.CV_64F,1,0,ksize=5)
sobely = cv2.Sobel(new_image,cv2.CV_64F,0,1,ksize=5)
sobel = cv2.addWeighted(np.absolute(sobelx), 0.5, np.absolute(sobely), 0.5, 0)
image_filter = img
for a in range(height):
for b in range(width):
val = new_image2[a,b] - gradient[a,b]
#val = new_image2[a,b] - sobel[a,b]
if val < 0:
image_filter[a,b] = 0
elif val > 255:
image_filter[a,b] = 255
else:
image_filter[a,b] = val
segment(gradient)
img1 = new_image1
img2 = new_image2
img3 = new_image3
img4 = gradient
img5 = sobel
#removeBloodVessels(img,110,10)
#removeBloodVessels(img1,30,110)
#for a in range(10,250,10):
#for b in range(10,250,10):
#removeBloodVessels(img2,a,b,i)
#v = 'img_'+str(i)
#cv2.imshow(v,img)
#cv2.imshow('new',new_image)
#filterimage(img)
segment(img1)
"""
cv2.waitKey(0)
cv2.destroyAllWindows
| [
"matplotlib.pyplot.title",
"numpy.absolute",
"cv2.medianBlur",
"numpy.ones",
"cv2.adaptiveThreshold",
"skimage.data.copy",
"numpy.around",
"numpy.sin",
"cv2.erode",
"cv2.imshow",
"numpy.full",
"cv2.dilate",
"cv2.imwrite",
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.yticks",
"skimage... | [((734, 750), 'numpy.median', 'np.median', (['image'], {}), '(image)\n', (743, 750), True, 'import numpy as np\n'), ((964, 994), 'cv2.Canny', 'cv2.Canny', (['image', 'lower', 'upper'], {}), '(image, lower, upper)\n', (973, 994), False, 'import cv2\n'), ((1112, 1123), 'skimage.data.copy', 'data.copy', ([], {}), '()\n', (1121, 1123), False, 'from skimage import data\n'), ((8572, 8583), 'skimage.data.copy', 'data.copy', ([], {}), '()\n', (8581, 8583), False, 'from skimage import data\n'), ((10892, 10914), 'cv2.imwrite', 'cv2.imwrite', (['path', 'img'], {}), '(path, img)\n', (10903, 10914), False, 'import cv2\n'), ((11232, 11259), 'numpy.ones', 'np.ones', (['(25, 25)', 'np.uint8'], {}), '((25, 25), np.uint8)\n', (11239, 11259), True, 'import numpy as np\n'), ((11273, 11318), 'cv2.morphologyEx', 'cv2.morphologyEx', (['img', 'cv2.MORPH_OPEN', 'kernel'], {}), '(img, cv2.MORPH_OPEN, kernel)\n', (11289, 11318), False, 'import cv2\n'), ((11703, 11736), 'scipy.ndimage.filters.uniform_filter', 'uniform_filter', (['img', '(size, size)'], {}), '(img, (size, size))\n', (11717, 11736), False, 'from scipy.ndimage.filters import uniform_filter\n'), ((11757, 11795), 'scipy.ndimage.filters.uniform_filter', 'uniform_filter', (['(img ** 2)', '(size, size)'], {}), '(img ** 2, (size, size))\n', (11771, 11795), False, 'from scipy.ndimage.filters import uniform_filter\n'), ((11865, 11878), 'scipy.ndimage.measurements.variance', 'variance', (['img'], {}), '(img)\n', (11873, 11878), False, 'from scipy.ndimage.measurements import variance\n'), ((12164, 12194), 'numpy.linspace', 'np.linspace', (['(0)', '(2 * np.pi)', '(400)'], {}), '(0, 2 * np.pi, 400)\n', (12175, 12194), True, 'import numpy as np\n'), ((12988, 13016), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(7, 7)'}), '(figsize=(7, 7))\n', (13000, 13016), True, 'import matplotlib.pyplot as plt\n'), ((13252, 13262), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (13260, 13262), True, 'import matplotlib.pyplot as plt\n'), ((13394, 13419), 'numpy.ones', 'np.ones', (['(5, 5)', 'np.uint8'], {}), '((5, 5), np.uint8)\n', (13401, 13419), True, 'import numpy as np\n'), ((13436, 13473), 'cv2.dilate', 'cv2.dilate', (['img', 'kernel'], {'iterations': '(1)'}), '(img, kernel, iterations=1)\n', (13446, 13473), False, 'import cv2\n'), ((13798, 13835), 'cv2.erode', 'cv2.erode', (['blur', 'kernel'], {'iterations': '(1)'}), '(blur, kernel, iterations=1)\n', (13807, 13835), False, 'import cv2\n'), ((13884, 13913), 'matplotlib.pyplot.imshow', 'plt.imshow', (['blur'], {'cmap': '"""gray"""'}), "(blur, cmap='gray')\n", (13894, 13913), True, 'import matplotlib.pyplot as plt\n'), ((13920, 13930), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (13928, 13930), True, 'import matplotlib.pyplot as plt\n'), ((13948, 13993), 'cv2.morphologyEx', 'cv2.morphologyEx', (['img', 'cv2.MORPH_OPEN', 'kernel'], {}), '(img, cv2.MORPH_OPEN, kernel)\n', (13964, 13993), False, 'import cv2\n'), ((14009, 14055), 'cv2.morphologyEx', 'cv2.morphologyEx', (['img', 'cv2.MORPH_CLOSE', 'kernel'], {}), '(img, cv2.MORPH_CLOSE, kernel)\n', (14025, 14055), False, 'import cv2\n'), ((14072, 14122), 'cv2.morphologyEx', 'cv2.morphologyEx', (['blur', 'cv2.MORPH_GRADIENT', 'kernel'], {}), '(blur, cv2.MORPH_GRADIENT, kernel)\n', (14088, 14122), False, 'import cv2\n'), ((14134, 14175), 'cv2.erode', 'cv2.erode', (['gradient', 'kernel'], {'iterations': '(1)'}), '(gradient, kernel, iterations=1)\n', (14143, 14175), False, 'import cv2\n'), ((14873, 14883), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (14881, 14883), True, 'import matplotlib.pyplot as plt\n'), ((14903, 14933), 'cv2.Laplacian', 'cv2.Laplacian', (['img', 'cv2.CV_64F'], {}), '(img, cv2.CV_64F)\n', (14916, 14933), False, 'import cv2\n'), ((14947, 14988), 'cv2.Sobel', 'cv2.Sobel', (['img', 'cv2.CV_64F', '(1)', '(0)'], {'ksize': '(5)'}), '(img, cv2.CV_64F, 1, 0, ksize=5)\n', (14956, 14988), False, 'import cv2\n'), ((14999, 15040), 'cv2.Sobel', 'cv2.Sobel', (['img', 'cv2.CV_64F', '(0)', '(1)'], {'ksize': '(5)'}), '(img, cv2.CV_64F, 0, 1, ksize=5)\n', (15008, 15040), False, 'import cv2\n'), ((15186, 15224), 'cv2.erode', 'cv2.erode', (['sobel', 'kernel'], {'iterations': '(1)'}), '(sobel, kernel, iterations=1)\n', (15195, 15224), False, 'import cv2\n'), ((15695, 15705), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (15703, 15705), True, 'import matplotlib.pyplot as plt\n'), ((15854, 15870), 'numpy.zeros', 'np.zeros', (['(m, n)'], {}), '((m, n))\n', (15862, 15870), True, 'import numpy as np\n'), ((15927, 15949), 'cv2.medianBlur', 'cv2.medianBlur', (['img', '(5)'], {}), '(img, 5)\n', (15941, 15949), False, 'import cv2\n'), ((15965, 16095), 'cv2.HoughCircles', 'cv2.HoughCircles', (['median_blur_copy_img', 'cv2.HOUGH_GRADIENT'], {'dp': '(1)', 'minDist': '(200)', 'param1': '(25)', 'param2': '(50)', 'minRadius': '(0)', 'maxRadius': '(0)'}), '(median_blur_copy_img, cv2.HOUGH_GRADIENT, dp=1, minDist=\n 200, param1=25, param2=50, minRadius=0, maxRadius=0)\n', (15981, 16095), False, 'import cv2\n'), ((16106, 16124), 'numpy.around', 'np.around', (['circles'], {}), '(circles)\n', (16115, 16124), True, 'import numpy as np\n'), ((16140, 16158), 'numpy.uint16', 'np.uint16', (['circles'], {}), '(circles)\n', (16149, 16158), True, 'import numpy as np\n'), ((16215, 16271), 'numpy.full', 'np.full', (['(img.shape[0], img.shape[1])', '(0)'], {'dtype': 'np.uint8'}), '((img.shape[0], img.shape[1]), 0, dtype=np.uint8)\n', (16222, 16271), True, 'import numpy as np\n'), ((16285, 16341), 'numpy.full', 'np.full', (['(img.shape[0], img.shape[1])', '(0)'], {'dtype': 'np.uint8'}), '((img.shape[0], img.shape[1]), 0, dtype=np.uint8)\n', (16292, 16341), True, 'import numpy as np\n'), ((16550, 16585), 'cv2.bitwise_or', 'cv2.bitwise_or', (['img', 'img'], {'mask': 'mask'}), '(img, img, mask=mask)\n', (16564, 16585), False, 'import cv2\n'), ((16666, 16687), 'cv2.bitwise_not', 'cv2.bitwise_not', (['mask'], {}), '(mask)\n', (16681, 16687), False, 'import cv2\n'), ((16771, 16810), 'numpy.full', 'np.full', (['img.shape', '(255)'], {'dtype': 'np.uint8'}), '(img.shape, 255, dtype=np.uint8)\n', (16778, 16810), True, 'import numpy as np\n'), ((16821, 16870), 'cv2.bitwise_or', 'cv2.bitwise_or', (['background', 'background'], {'mask': 'mask'}), '(background, background, mask=mask)\n', (16835, 16870), False, 'import cv2\n'), ((16927, 16949), 'cv2.bitwise_or', 'cv2.bitwise_or', (['fg', 'bk'], {}), '(fg, bk)\n', (16941, 16949), False, 'import cv2\n'), ((17531, 17541), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (17539, 17541), True, 'import matplotlib.pyplot as plt\n'), ((17955, 17982), 'numpy.ones', 'np.ones', (['(25, 25)', 'np.uint8'], {}), '((25, 25), np.uint8)\n', (17962, 17982), True, 'import numpy as np\n'), ((17996, 18024), 'numpy.zeros', 'np.zeros', (['(25, 25)', 'np.uint8'], {}), '((25, 25), np.uint8)\n', (18004, 18024), True, 'import numpy as np\n'), ((18039, 18055), 'numpy.zeros', 'np.zeros', (['(m, n)'], {}), '((m, n))\n', (18047, 18055), True, 'import numpy as np\n'), ((18268, 18315), 'cv2.morphologyEx', 'cv2.morphologyEx', (['img', 'cv2.MORPH_CLOSE', 'kernel1'], {}), '(img, cv2.MORPH_CLOSE, kernel1)\n', (18284, 18315), False, 'import cv2\n'), ((18332, 18379), 'cv2.morphologyEx', 'cv2.morphologyEx', (['img', 'cv2.MORPH_CLOSE', 'kernel0'], {}), '(img, cv2.MORPH_CLOSE, kernel0)\n', (18348, 18379), False, 'import cv2\n'), ((20181, 20208), 'cv2.namedWindow', 'cv2.namedWindow', (['"""Contrast"""'], {}), "('Contrast')\n", (20196, 20208), False, 'import cv2\n'), ((20255, 20315), 'cv2.createTrackbar', 'cv2.createTrackbar', (['"""alpha"""', '"""Contrast"""', 'alpha', '(255)', 'nothing'], {}), "('alpha', 'Contrast', alpha, 255, nothing)\n", (20273, 20315), False, 'import cv2\n'), ((20320, 20378), 'cv2.createTrackbar', 'cv2.createTrackbar', (['"""beta"""', '"""Contrast"""', 'beta', '(255)', 'nothing'], {}), "('beta', 'Contrast', beta, 255, nothing)\n", (20338, 20378), False, 'import cv2\n'), ((20383, 20451), 'cv2.createTrackbar', 'cv2.createTrackbar', (['"""Threshold"""', '"""Contrast"""', 'threshold', '(255)', 'nothing'], {}), "('Threshold', 'Contrast', threshold, 255, nothing)\n", (20401, 20451), False, 'import cv2\n'), ((20456, 20515), 'cv2.createTrackbar', 'cv2.createTrackbar', (['"""Type"""', '"""Contrast"""', 'th_type', '(4)', 'nothing'], {}), "('Type', 'Contrast', th_type, 4, nothing)\n", (20474, 20515), False, 'import cv2\n'), ((20566, 20621), 'cv2.createTrackbar', 'cv2.createTrackbar', (['"""Switch"""', '"""Contrast"""', 's', '(1)', 'nothing'], {}), "('Switch', 'Contrast', s, 1, nothing)\n", (20584, 20621), False, 'import cv2\n'), ((21334, 21357), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (21355, 21357), False, 'import cv2\n'), ((21442, 21469), 'cv2.namedWindow', 'cv2.namedWindow', (['"""Trackbar"""'], {}), "('Trackbar')\n", (21457, 21469), False, 'import cv2\n'), ((21533, 21599), 'cv2.createTrackbar', 'cv2.createTrackbar', (['"""Bottom Hat 0"""', '"""Trackbar"""', 'th_0', '(255)', 'nothing'], {}), "('Bottom Hat 0', 'Trackbar', th_0, 255, nothing)\n", (21551, 21599), False, 'import cv2\n'), ((21604, 21670), 'cv2.createTrackbar', 'cv2.createTrackbar', (['"""Bottom Hat 1"""', '"""Trackbar"""', 'th_1', '(255)', 'nothing'], {}), "('Bottom Hat 1', 'Trackbar', th_1, 255, nothing)\n", (21622, 21670), False, 'import cv2\n'), ((21675, 21730), 'cv2.createTrackbar', 'cv2.createTrackbar', (['"""Switch"""', '"""Trackbar"""', '(0)', '(1)', 'nothing'], {}), "('Switch', 'Trackbar', 0, 1, nothing)\n", (21693, 21730), False, 'import cv2\n'), ((22352, 22376), 'cv2.medianBlur', 'cv2.medianBlur', (['image', '(5)'], {}), '(image, 5)\n', (22366, 22376), False, 'import cv2\n'), ((22381, 22408), 'cv2.namedWindow', 'cv2.namedWindow', (['"""Contrast"""'], {}), "('Contrast')\n", (22396, 22408), False, 'import cv2\n'), ((22455, 22525), 'cv2.createTrackbar', 'cv2.createTrackbar', (['"""Mean Threshold 1"""', '"""Contrast"""', 'mth1', '(255)', 'nothing'], {}), "('Mean Threshold 1', 'Contrast', mth1, 255, nothing)\n", (22473, 22525), False, 'import cv2\n'), ((22531, 22601), 'cv2.createTrackbar', 'cv2.createTrackbar', (['"""Mean Threshold 2"""', '"""Contrast"""', 'mth2', '(255)', 'nothing'], {}), "('Mean Threshold 2', 'Contrast', mth2, 255, nothing)\n", (22549, 22601), False, 'import cv2\n'), ((22607, 22681), 'cv2.createTrackbar', 'cv2.createTrackbar', (['"""Gaussian Threshold 1"""', '"""Contrast"""', 'gth1', '(255)', 'nothing'], {}), "('Gaussian Threshold 1', 'Contrast', gth1, 255, nothing)\n", (22625, 22681), False, 'import cv2\n'), ((22687, 22761), 'cv2.createTrackbar', 'cv2.createTrackbar', (['"""Gaussian Threshold 2"""', '"""Contrast"""', 'gth2', '(255)', 'nothing'], {}), "('Gaussian Threshold 2', 'Contrast', gth2, 255, nothing)\n", (22705, 22761), False, 'import cv2\n'), ((22813, 22868), 'cv2.createTrackbar', 'cv2.createTrackbar', (['"""Switch"""', '"""Contrast"""', 's', '(1)', 'nothing'], {}), "('Switch', 'Contrast', s, 1, nothing)\n", (22831, 22868), False, 'import cv2\n'), ((23740, 23830), 'cv2.adaptiveThreshold', 'cv2.adaptiveThreshold', (['img', '(255)', 'cv2.ADAPTIVE_THRESH_MEAN_C', 'cv2.THRESH_BINARY', '(11)', '(2)'], {}), '(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.\n THRESH_BINARY, 11, 2)\n', (23761, 23830), False, 'import cv2\n'), ((23837, 23931), 'cv2.adaptiveThreshold', 'cv2.adaptiveThreshold', (['img', '(255)', 'cv2.ADAPTIVE_THRESH_GAUSSIAN_C', 'cv2.THRESH_BINARY', '(11)', '(2)'], {}), '(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.\n THRESH_BINARY, 11, 2)\n', (23858, 23931), False, 'import cv2\n'), ((23932, 23955), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (23953, 23955), False, 'import cv2\n'), ((12451, 12467), 'numpy.array', 'np.array', (['[r, c]'], {}), '([r, c])\n', (12459, 12467), True, 'import numpy as np\n'), ((12663, 12682), 'skimage.filters.gaussian', 'gaussian', (['img', 'blur'], {}), '(img, blur)\n', (12671, 12682), False, 'from skimage.filters import gaussian\n'), ((14184, 14204), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(3)', '(1)'], {}), '(2, 3, 1)\n', (14195, 14204), True, 'import matplotlib.pyplot as plt\n'), ((14203, 14231), 'matplotlib.pyplot.imshow', 'plt.imshow', (['img'], {'cmap': '"""gray"""'}), "(img, cmap='gray')\n", (14213, 14231), True, 'import matplotlib.pyplot as plt\n'), ((14238, 14259), 'matplotlib.pyplot.title', 'plt.title', (['"""Original"""'], {}), "('Original')\n", (14247, 14259), True, 'import matplotlib.pyplot as plt\n'), ((14261, 14275), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (14271, 14275), True, 'import matplotlib.pyplot as plt\n'), ((14277, 14291), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (14287, 14291), True, 'import matplotlib.pyplot as plt\n'), ((14297, 14317), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(3)', '(2)'], {}), '(2, 3, 2)\n', (14308, 14317), True, 'import matplotlib.pyplot as plt\n'), ((14316, 14348), 'matplotlib.pyplot.imshow', 'plt.imshow', (['erosion'], {'cmap': '"""gray"""'}), "(erosion, cmap='gray')\n", (14326, 14348), True, 'import matplotlib.pyplot as plt\n'), ((14355, 14375), 'matplotlib.pyplot.title', 'plt.title', (['"""Erosion"""'], {}), "('Erosion')\n", (14364, 14375), True, 'import matplotlib.pyplot as plt\n'), ((14377, 14391), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (14387, 14391), True, 'import matplotlib.pyplot as plt\n'), ((14393, 14407), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (14403, 14407), True, 'import matplotlib.pyplot as plt\n'), ((14413, 14433), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(3)', '(3)'], {}), '(2, 3, 3)\n', (14424, 14433), True, 'import matplotlib.pyplot as plt\n'), ((14432, 14465), 'matplotlib.pyplot.imshow', 'plt.imshow', (['dilation'], {'cmap': '"""gray"""'}), "(dilation, cmap='gray')\n", (14442, 14465), True, 'import matplotlib.pyplot as plt\n'), ((14472, 14493), 'matplotlib.pyplot.title', 'plt.title', (['"""Dilation"""'], {}), "('Dilation')\n", (14481, 14493), True, 'import matplotlib.pyplot as plt\n'), ((14495, 14509), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (14505, 14509), True, 'import matplotlib.pyplot as plt\n'), ((14511, 14525), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (14521, 14525), True, 'import matplotlib.pyplot as plt\n'), ((14531, 14551), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(3)', '(4)'], {}), '(2, 3, 4)\n', (14542, 14551), True, 'import matplotlib.pyplot as plt\n'), ((14550, 14582), 'matplotlib.pyplot.imshow', 'plt.imshow', (['opening'], {'cmap': '"""gray"""'}), "(opening, cmap='gray')\n", (14560, 14582), True, 'import matplotlib.pyplot as plt\n'), ((14589, 14609), 'matplotlib.pyplot.title', 'plt.title', (['"""Opening"""'], {}), "('Opening')\n", (14598, 14609), True, 'import matplotlib.pyplot as plt\n'), ((14611, 14625), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (14621, 14625), True, 'import matplotlib.pyplot as plt\n'), ((14627, 14641), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (14637, 14641), True, 'import matplotlib.pyplot as plt\n'), ((14647, 14667), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(3)', '(5)'], {}), '(2, 3, 5)\n', (14658, 14667), True, 'import matplotlib.pyplot as plt\n'), ((14666, 14694), 'matplotlib.pyplot.imshow', 'plt.imshow', (['dil'], {'cmap': '"""gray"""'}), "(dil, cmap='gray')\n", (14676, 14694), True, 'import matplotlib.pyplot as plt\n'), ((14701, 14717), 'matplotlib.pyplot.title', 'plt.title', (['"""Dil"""'], {}), "('Dil')\n", (14710, 14717), True, 'import matplotlib.pyplot as plt\n'), ((14719, 14733), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (14729, 14733), True, 'import matplotlib.pyplot as plt\n'), ((14735, 14749), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (14745, 14749), True, 'import matplotlib.pyplot as plt\n'), ((14755, 14775), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(3)', '(6)'], {}), '(2, 3, 6)\n', (14766, 14775), True, 'import matplotlib.pyplot as plt\n'), ((14774, 14807), 'matplotlib.pyplot.imshow', 'plt.imshow', (['gradient'], {'cmap': '"""gray"""'}), "(gradient, cmap='gray')\n", (14784, 14807), True, 'import matplotlib.pyplot as plt\n'), ((14814, 14835), 'matplotlib.pyplot.title', 'plt.title', (['"""Gradient"""'], {}), "('Gradient')\n", (14823, 14835), True, 'import matplotlib.pyplot as plt\n'), ((14837, 14851), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (14847, 14851), True, 'import matplotlib.pyplot as plt\n'), ((14853, 14867), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (14863, 14867), True, 'import matplotlib.pyplot as plt\n'), ((15066, 15085), 'numpy.absolute', 'np.absolute', (['sobelx'], {}), '(sobelx)\n', (15077, 15085), True, 'import numpy as np\n'), ((15092, 15111), 'numpy.absolute', 'np.absolute', (['sobely'], {}), '(sobely)\n', (15103, 15111), True, 'import numpy as np\n'), ((15232, 15252), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(2)', '(1)'], {}), '(2, 2, 1)\n', (15243, 15252), True, 'import matplotlib.pyplot as plt\n'), ((15251, 15281), 'matplotlib.pyplot.imshow', 'plt.imshow', (['sobel'], {'cmap': '"""gray"""'}), "(sobel, cmap='gray')\n", (15261, 15281), True, 'import matplotlib.pyplot as plt\n'), ((15288, 15306), 'matplotlib.pyplot.title', 'plt.title', (['"""Sobel"""'], {}), "('Sobel')\n", (15297, 15306), True, 'import matplotlib.pyplot as plt\n'), ((15308, 15322), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (15318, 15322), True, 'import matplotlib.pyplot as plt\n'), ((15324, 15338), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (15334, 15338), True, 'import matplotlib.pyplot as plt\n'), ((15344, 15364), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(2)', '(2)'], {}), '(2, 2, 2)\n', (15355, 15364), True, 'import matplotlib.pyplot as plt\n'), ((15363, 15397), 'matplotlib.pyplot.imshow', 'plt.imshow', (['laplacian'], {'cmap': '"""gray"""'}), "(laplacian, cmap='gray')\n", (15373, 15397), True, 'import matplotlib.pyplot as plt\n'), ((15404, 15426), 'matplotlib.pyplot.title', 'plt.title', (['"""Laplacian"""'], {}), "('Laplacian')\n", (15413, 15426), True, 'import matplotlib.pyplot as plt\n'), ((15428, 15442), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (15438, 15442), True, 'import matplotlib.pyplot as plt\n'), ((15444, 15458), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (15454, 15458), True, 'import matplotlib.pyplot as plt\n'), ((15464, 15484), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(2)', '(3)'], {}), '(2, 2, 3)\n', (15475, 15484), True, 'import matplotlib.pyplot as plt\n'), ((15483, 15514), 'matplotlib.pyplot.imshow', 'plt.imshow', (['sobelx'], {'cmap': '"""gray"""'}), "(sobelx, cmap='gray')\n", (15493, 15514), True, 'import matplotlib.pyplot as plt\n'), ((15521, 15541), 'matplotlib.pyplot.title', 'plt.title', (['"""Sobel X"""'], {}), "('Sobel X')\n", (15530, 15541), True, 'import matplotlib.pyplot as plt\n'), ((15543, 15557), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (15553, 15557), True, 'import matplotlib.pyplot as plt\n'), ((15559, 15573), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (15569, 15573), True, 'import matplotlib.pyplot as plt\n'), ((15579, 15599), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(2)', '(4)'], {}), '(2, 2, 4)\n', (15590, 15599), True, 'import matplotlib.pyplot as plt\n'), ((15598, 15629), 'matplotlib.pyplot.imshow', 'plt.imshow', (['sobely'], {'cmap': '"""gray"""'}), "(sobely, cmap='gray')\n", (15608, 15629), True, 'import matplotlib.pyplot as plt\n'), ((15636, 15655), 'matplotlib.pyplot.title', 'plt.title', (['"""<NAME>"""'], {}), "('<NAME>')\n", (15645, 15655), True, 'import matplotlib.pyplot as plt\n'), ((15657, 15671), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (15667, 15671), True, 'import matplotlib.pyplot as plt\n'), ((15673, 15687), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (15683, 15687), True, 'import matplotlib.pyplot as plt\n'), ((16380, 16437), 'cv2.circle', 'cv2.circle', (['mask', '(i[0], i[1])', 'i[2]', '(255, 255, 255)', '(-1)'], {}), '(mask, (i[0], i[1]), i[2], (255, 255, 255), -1)\n', (16390, 16437), False, 'import cv2\n'), ((16957, 16977), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(3)', '(1)'], {}), '(2, 3, 1)\n', (16968, 16977), True, 'import matplotlib.pyplot as plt\n'), ((16976, 17004), 'matplotlib.pyplot.imshow', 'plt.imshow', (['img'], {'cmap': '"""gray"""'}), "(img, cmap='gray')\n", (16986, 17004), True, 'import matplotlib.pyplot as plt\n'), ((17011, 17027), 'matplotlib.pyplot.title', 'plt.title', (['"""equ"""'], {}), "('equ')\n", (17020, 17027), True, 'import matplotlib.pyplot as plt\n'), ((17029, 17043), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (17039, 17043), True, 'import matplotlib.pyplot as plt\n'), ((17045, 17059), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (17055, 17059), True, 'import matplotlib.pyplot as plt\n'), ((17065, 17085), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(3)', '(2)'], {}), '(2, 3, 2)\n', (17076, 17085), True, 'import matplotlib.pyplot as plt\n'), ((17084, 17117), 'matplotlib.pyplot.imshow', 'plt.imshow', (['copy_img'], {'cmap': '"""gray"""'}), "(copy_img, cmap='gray')\n", (17094, 17117), True, 'import matplotlib.pyplot as plt\n'), ((17124, 17151), 'matplotlib.pyplot.title', 'plt.title', (['"""equ+bottomHat1"""'], {}), "('equ+bottomHat1')\n", (17133, 17151), True, 'import matplotlib.pyplot as plt\n'), ((17153, 17167), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (17163, 17167), True, 'import matplotlib.pyplot as plt\n'), ((17169, 17183), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (17179, 17183), True, 'import matplotlib.pyplot as plt\n'), ((17201, 17221), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(3)', '(3)'], {}), '(2, 3, 3)\n', (17212, 17221), True, 'import matplotlib.pyplot as plt\n'), ((17220, 17247), 'matplotlib.pyplot.imshow', 'plt.imshow', (['bk'], {'cmap': '"""gray"""'}), "(bk, cmap='gray')\n", (17230, 17247), True, 'import matplotlib.pyplot as plt\n'), ((17254, 17275), 'matplotlib.pyplot.title', 'plt.title', (['"""bk(mask)"""'], {}), "('bk(mask)')\n", (17263, 17275), True, 'import matplotlib.pyplot as plt\n'), ((17277, 17291), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (17287, 17291), True, 'import matplotlib.pyplot as plt\n'), ((17293, 17307), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (17303, 17307), True, 'import matplotlib.pyplot as plt\n'), ((17313, 17333), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(3)', '(4)'], {}), '(2, 3, 4)\n', (17324, 17333), True, 'import matplotlib.pyplot as plt\n'), ((17332, 17359), 'matplotlib.pyplot.imshow', 'plt.imshow', (['fg'], {'cmap': '"""gray"""'}), "(fg, cmap='gray')\n", (17342, 17359), True, 'import matplotlib.pyplot as plt\n'), ((17366, 17381), 'matplotlib.pyplot.title', 'plt.title', (['"""fg"""'], {}), "('fg')\n", (17375, 17381), True, 'import matplotlib.pyplot as plt\n'), ((17383, 17397), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (17393, 17397), True, 'import matplotlib.pyplot as plt\n'), ((17399, 17413), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (17409, 17413), True, 'import matplotlib.pyplot as plt\n'), ((17419, 17439), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(3)', '(5)'], {}), '(2, 3, 5)\n', (17430, 17439), True, 'import matplotlib.pyplot as plt\n'), ((17438, 17468), 'matplotlib.pyplot.imshow', 'plt.imshow', (['final'], {'cmap': '"""gray"""'}), "(final, cmap='gray')\n", (17448, 17468), True, 'import matplotlib.pyplot as plt\n'), ((17475, 17493), 'matplotlib.pyplot.title', 'plt.title', (['"""final"""'], {}), "('final')\n", (17484, 17493), True, 'import matplotlib.pyplot as plt\n'), ((17495, 17509), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (17505, 17509), True, 'import matplotlib.pyplot as plt\n'), ((17511, 17525), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (17521, 17525), True, 'import matplotlib.pyplot as plt\n'), ((20706, 20745), 'cv2.getTrackbarPos', 'cv2.getTrackbarPos', (['"""alpha"""', '"""Contrast"""'], {}), "('alpha', 'Contrast')\n", (20724, 20745), False, 'import cv2\n'), ((20761, 20799), 'cv2.getTrackbarPos', 'cv2.getTrackbarPos', (['"""beta"""', '"""Contrast"""'], {}), "('beta', 'Contrast')\n", (20779, 20799), False, 'import cv2\n'), ((20820, 20863), 'cv2.getTrackbarPos', 'cv2.getTrackbarPos', (['"""Threshold"""', '"""Contrast"""'], {}), "('Threshold', 'Contrast')\n", (20838, 20863), False, 'import cv2\n'), ((20882, 20920), 'cv2.getTrackbarPos', 'cv2.getTrackbarPos', (['"""Type"""', '"""Contrast"""'], {}), "('Type', 'Contrast')\n", (20900, 20920), False, 'import cv2\n'), ((20933, 20973), 'cv2.getTrackbarPos', 'cv2.getTrackbarPos', (['"""Switch"""', '"""Contrast"""'], {}), "('Switch', 'Contrast')\n", (20951, 20973), False, 'import cv2\n'), ((21170, 21215), 'cv2.threshold', 'cv2.threshold', (['image', 'threshold', '(255)', 'th_type'], {}), '(image, threshold, 255, th_type)\n', (21183, 21215), False, 'import cv2\n'), ((21225, 21253), 'cv2.imshow', 'cv2.imshow', (['"""Threshold"""', 'dst'], {}), "('Threshold', dst)\n", (21235, 21253), False, 'import cv2\n'), ((21812, 21858), 'cv2.getTrackbarPos', 'cv2.getTrackbarPos', (['"""Bottom Hat 0"""', '"""Trackbar"""'], {}), "('Bottom Hat 0', 'Trackbar')\n", (21830, 21858), False, 'import cv2\n'), ((21874, 21920), 'cv2.getTrackbarPos', 'cv2.getTrackbarPos', (['"""Bottom Hat 1"""', '"""Trackbar"""'], {}), "('Bottom Hat 1', 'Trackbar')\n", (21892, 21920), False, 'import cv2\n'), ((21933, 21973), 'cv2.getTrackbarPos', 'cv2.getTrackbarPos', (['"""Switch"""', '"""Trackbar"""'], {}), "('Switch', 'Trackbar')\n", (21951, 21973), False, 'import cv2\n'), ((22075, 22111), 'cv2.imshow', 'cv2.imshow', (['"""BottomHat0"""', 'bottomhat0'], {}), "('BottomHat0', bottomhat0)\n", (22085, 22111), False, 'import cv2\n'), ((22952, 23002), 'cv2.getTrackbarPos', 'cv2.getTrackbarPos', (['"""Mean Threshold 1"""', '"""Contrast"""'], {}), "('Mean Threshold 1', 'Contrast')\n", (22970, 23002), False, 'import cv2\n'), ((23018, 23068), 'cv2.getTrackbarPos', 'cv2.getTrackbarPos', (['"""Mean Threshold 2"""', '"""Contrast"""'], {}), "('Mean Threshold 2', 'Contrast')\n", (23036, 23068), False, 'import cv2\n'), ((23084, 23138), 'cv2.getTrackbarPos', 'cv2.getTrackbarPos', (['"""Gaussian Threshold 1"""', '"""Contrast"""'], {}), "('Gaussian Threshold 1', 'Contrast')\n", (23102, 23138), False, 'import cv2\n'), ((23154, 23208), 'cv2.getTrackbarPos', 'cv2.getTrackbarPos', (['"""Gaussian Threshold 2"""', '"""Contrast"""'], {}), "('Gaussian Threshold 2', 'Contrast')\n", (23172, 23208), False, 'import cv2\n'), ((23221, 23261), 'cv2.getTrackbarPos', 'cv2.getTrackbarPos', (['"""Switch"""', '"""Contrast"""'], {}), "('Switch', 'Contrast')\n", (23239, 23261), False, 'import cv2\n'), ((23341, 23431), 'cv2.adaptiveThreshold', 'cv2.adaptiveThreshold', (['img', '(255)', 'cv2.ADAPTIVE_THRESH_MEAN_C', 'cv2.THRESH_BINARY', '(11)', '(2)'], {}), '(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.\n THRESH_BINARY, 11, 2)\n', (23362, 23431), False, 'import cv2\n'), ((23442, 23536), 'cv2.adaptiveThreshold', 'cv2.adaptiveThreshold', (['img', '(255)', 'cv2.ADAPTIVE_THRESH_GAUSSIAN_C', 'cv2.THRESH_BINARY', '(11)', '(2)'], {}), '(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.\n THRESH_BINARY, 11, 2)\n', (23463, 23536), False, 'import cv2\n'), ((23541, 23567), 'cv2.imshow', 'cv2.imshow', (['"""Image"""', 'image'], {}), "('Image', image)\n", (23551, 23567), False, 'import cv2\n'), ((23577, 23608), 'cv2.imshow', 'cv2.imshow', (['"""AdaptiveMean"""', 'im1'], {}), "('AdaptiveMean', im1)\n", (23587, 23608), False, 'import cv2\n'), ((23618, 23653), 'cv2.imshow', 'cv2.imshow', (['"""AdaptiveGaussian"""', 'im2'], {}), "('AdaptiveGaussian', im2)\n", (23628, 23653), False, 'import cv2\n'), ((24381, 24402), 'cv2.imread', 'cv2.imread', (['image1', '(0)'], {}), '(image1, 0)\n', (24391, 24402), False, 'import cv2\n'), ((24443, 24464), 'cv2.imread', 'cv2.imread', (['image2', '(0)'], {}), '(image2, 0)\n', (24453, 24464), False, 'import cv2\n'), ((24954, 24966), 'numpy.zeros', 'np.zeros', (['(10)'], {}), '(10)\n', (24962, 24966), True, 'import numpy as np\n'), ((25532, 25555), 'cv2.blur', 'cv2.blur', (['final', '(5, 5)'], {}), '(final, (5, 5))\n', (25540, 25555), False, 'import cv2\n'), ((25563, 25592), 'cv2.imshow', 'cv2.imshow', (['"""original"""', 'image'], {}), "('original', image)\n", (25573, 25592), False, 'import cv2\n'), ((25602, 25628), 'cv2.imshow', 'cv2.imshow', (['"""final"""', 'final'], {}), "('final', final)\n", (25612, 25628), False, 'import cv2\n'), ((25728, 25752), 'cv2.imwrite', 'cv2.imwrite', (['path', 'final'], {}), '(path, final)\n', (25739, 25752), False, 'import cv2\n'), ((26117, 26131), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (26128, 26131), False, 'import cv2\n'), ((26141, 26164), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (26162, 26164), False, 'import cv2\n'), ((30411, 30425), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (30422, 30425), False, 'import cv2\n'), ((12389, 12398), 'numpy.sin', 'np.sin', (['s'], {}), '(s)\n', (12395, 12398), True, 'import numpy as np\n'), ((12429, 12438), 'numpy.cos', 'np.cos', (['s'], {}), '(s)\n', (12435, 12438), True, 'import numpy as np\n'), ((17755, 17775), 'numpy.nonzero', 'np.nonzero', (['img_flat'], {}), '(img_flat)\n', (17765, 17775), True, 'import numpy as np\n'), ((21267, 21281), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (21278, 21281), False, 'import cv2\n'), ((22172, 22186), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (22183, 22186), False, 'import cv2\n'), ((23667, 23681), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (23678, 23681), False, 'import cv2\n')] |
# SPDX-FileCopyrightText: 2021 Division of Intelligent Medical Systems, DKFZ
# SPDX-FileCopyrightText: 2021 <NAME>
# SPDX-License-Identifier: MIT
from abc import abstractmethod, ABC
from simpa.log import Logger
from simpa.utils import Settings
import numpy as np
from numpy import ndarray
import hashlib
import uuid
from simpa.utils.serializer import SerializableSIMPAClass
class DigitalDeviceTwinBase(SerializableSIMPAClass):
"""
This class represents a device that can be used for illumination, detection or a combined photoacoustic device
which has representations of both.
"""
def __init__(self, device_position_mm=None, field_of_view_extent_mm=None):
"""
:param device_position_mm: Each device has an internal position which serves as origin for internal \
representations of e.g. detector element positions or illuminator positions.
:type device_position_mm: ndarray
:param field_of_view_extent_mm: Field of view which is defined as a numpy array of the shape \
[xs, xe, ys, ye, zs, ze], where x, y, and z denote the coordinate axes and s and e denote the start and end \
positions.
:type field_of_view_extent_mm: ndarray
"""
if device_position_mm is None:
self.device_position_mm = np.array([0, 0, 0])
else:
self.device_position_mm = device_position_mm
if field_of_view_extent_mm is None:
self.field_of_view_extent_mm = np.asarray([-10, 10, -10, 10, -10, 10])
else:
self.field_of_view_extent_mm = field_of_view_extent_mm
self.logger = Logger()
def __eq__(self, other):
"""
Checks each key, value pair in the devices.
"""
if isinstance(other, DigitalDeviceTwinBase):
if self.__dict__.keys() != other.__dict__.keys():
return False
for self_key, self_value in self.__dict__.items():
other_value = other.__dict__[self_key]
if isinstance(self_value, np.ndarray):
boolean = (other_value != self_value).all()
else:
boolean = other_value != self_value
if boolean:
return False
else:
continue
return True
return False
@abstractmethod
def check_settings_prerequisites(self, global_settings) -> bool:
"""
It might be that certain device geometries need a certain dimensionality of the simulated PAI volume, or that
it requires the existence of certain Tags in the global global_settings.
To this end, a PAI device should use this method to inform the user about a mismatch of the desired device and
throw a ValueError if that is the case.
:param global_settings: Settings for the entire simulation pipeline.
:type global_settings: Settings
:raises ValueError: raises a value error if the prerequisites are not matched.
:returns: True if the prerequisites are met, False if they are not met, but no exception has been raised.
:rtype: bool
"""
pass
@abstractmethod
def update_settings_for_use_of_model_based_volume_creator(self, global_settings):
"""
This method can be overwritten by a PA device if the device poses special constraints to the
volume that should be considered by the model-based volume creator.
:param global_settings: Settings for the entire simulation pipeline.
:type global_settings: Settings
"""
pass
def get_field_of_view_mm(self) -> np.ndarray:
"""
Returns the absolute field of view in mm where the probe position is already
accounted for.
It is defined as a numpy array of the shape [xs, xe, ys, ye, zs, ze],
where x, y, and z denote the coordinate axes and s and e denote the start and end
positions.
:return: Absolute field of view in mm where the probe position is already accounted for.
:rtype: ndarray
"""
position = self.device_position_mm
field_of_view_extent = self.field_of_view_extent_mm
field_of_view = np.asarray([position[0] + field_of_view_extent[0],
position[0] + field_of_view_extent[1],
position[1] + field_of_view_extent[2],
position[1] + field_of_view_extent[3],
position[2] + field_of_view_extent[4],
position[2] + field_of_view_extent[5]
])
if min(field_of_view) < 0:
self.logger.warning(f"The field of view of the chosen device is not fully within the simulated volume, "
f"field of view is: {field_of_view}")
field_of_view[field_of_view < 0] = 0
return field_of_view
def generate_uuid(self):
"""
Generates a universally unique identifier (uuid) for each device.
:return:
"""
class_dict = self.__dict__
m = hashlib.md5()
m.update(str(class_dict).encode('utf-8'))
return str(uuid.UUID(m.hexdigest()))
def serialize(self) -> dict:
serialized_device = self.__dict__
return {"DigitalDeviceTwinBase": serialized_device}
@staticmethod
def deserialize(dictionary_to_deserialize):
deserialized_device = DigitalDeviceTwinBase(
device_position_mm=dictionary_to_deserialize["device_position_mm"],
field_of_view_extent_mm=dictionary_to_deserialize["field_of_view_extent_mm"])
return deserialized_device
class PhotoacousticDevice(DigitalDeviceTwinBase, ABC):
"""Base class of a photoacoustic device. It consists of one detection geometry that describes the geometry of the
single detector elements and a list of illuminators.
A Photoacoustic Device can be initialized as follows::
import simpa as sp
import numpy as np
# Initialise a PhotoacousticDevice with its position and field of view
device = sp.PhotoacousticDevice(device_position_mm=np.array([10, 10, 0]),
field_of_view_extent_mm=np.array([-20, 20, 0, 0, 0, 20]))
# Option 1) Set the detection geometry position relative to the PhotoacousticDevice
device.set_detection_geometry(sp.DetectionGeometry(),
detector_position_relative_to_pa_device=np.array([0, 0, -10]))
# Option 2) Set the detection geometry position absolute
device.set_detection_geometry(
sp.DetectionGeometryBase(device_position_mm=np.array([10, 10, -10])))
# Option 1) Add the illumination geometry position relative to the PhotoacousticDevice
device.add_illumination_geometry(sp.IlluminationGeometry(),
illuminator_position_relative_to_pa_device=np.array([0, 0, 0]))
# Option 2) Add the illumination geometry position absolute
device.add_illumination_geometry(
sp.IlluminationGeometryBase(device_position_mm=np.array([10, 10, 0]))
Attributes:
detection_geometry (DetectionGeometryBase): Geometry of the detector elements.
illumination_geometries (list): List of illuminations defined by :py:class:`IlluminationGeometryBase`.
"""
def __init__(self, device_position_mm=None, field_of_view_extent_mm=None):
"""
:param device_position_mm: Each device has an internal position which serves as origin for internal \
representations of e.g. detector element positions or illuminator positions.
:type device_position_mm: ndarray
:param field_of_view_extent_mm: Field of view which is defined as a numpy array of the shape \
[xs, xe, ys, ye, zs, ze], where x, y, and z denote the coordinate axes and s and e denote the start and end \
positions.
:type field_of_view_extent_mm: ndarray
"""
super(PhotoacousticDevice, self).__init__(device_position_mm=device_position_mm,
field_of_view_extent_mm=field_of_view_extent_mm)
self.detection_geometry = None
self.illumination_geometries = []
def set_detection_geometry(self, detection_geometry,
detector_position_relative_to_pa_device=None):
"""Sets the detection geometry for the PA device. The detection geometry can be instantiated with an absolute
position or it can be instantiated without the device_position_mm argument but a position relative to the
position of the PhotoacousticDevice. If both absolute and relative positions are given, the absolute position
is chosen as position of the detection geometry.
:param detection_geometry: Detection geometry of the PA device.
:type detection_geometry: DetectionGeometryBase
:param detector_position_relative_to_pa_device: Position of the detection geometry relative to the PA device.
:type detector_position_relative_to_pa_device: ndarray
:raises ValueError: if the detection_geometry is None
"""
if detection_geometry is None:
msg = "The given detection_geometry must not be None!"
self.logger.critical(msg)
raise ValueError(msg)
if np.linalg.norm(detection_geometry.device_position_mm) == 0 and \
detector_position_relative_to_pa_device is not None:
detection_geometry.device_position_mm = np.add(self.device_position_mm,
detector_position_relative_to_pa_device)
self.detection_geometry = detection_geometry
def add_illumination_geometry(self, illumination_geometry, illuminator_position_relative_to_pa_device=None):
"""Adds an illuminator to the PA device. The illumination geometry can be instantiated with an absolute
position or it can be instantiated without the device_position_mm argument but a position relative to the
position of the PhotoacousticDevice. If both absolute and relative positions are given, the absolute position
is chosen as position of the illumination geometry.
:param illumination_geometry: Geometry of the illuminator.
:type illumination_geometry: IlluminationGeometryBase
:param illuminator_position_relative_to_pa_device: Position of the illuminator relative to the PA device.
:type illuminator_position_relative_to_pa_device: ndarray
:raises ValueError: if the illumination_geometry is None
"""
if illumination_geometry is None:
msg = "The given illumination_geometry must not be None!"
self.logger.critical(msg)
raise ValueError(msg)
if np.linalg.norm(illumination_geometry.device_position_mm) == 0:
if illuminator_position_relative_to_pa_device is not None:
illumination_geometry.device_position_mm = np.add(self.device_position_mm,
illuminator_position_relative_to_pa_device)
else:
illumination_geometry.device_position_mm = self.device_position_mm
self.illumination_geometries.append(illumination_geometry)
def get_detection_geometry(self):
"""
:return: None if no detection geometry was set or an instance of DetectionGeometryBase.
:rtype: None, DetectionGeometryBase
"""
return self.detection_geometry
def get_illumination_geometry(self):
"""
:return: None, if no illumination geometry was defined,
an instance of IlluminationGeometryBase if exactly one geometry was defined,
a list of IlluminationGeometryBase instances if more than one device was defined.
:rtype: None, IlluminationGeometryBase
"""
if len(self.illumination_geometries) == 0:
return None
if len(self.illumination_geometries) == 1:
return self.illumination_geometries[0]
return self.illumination_geometries
def check_settings_prerequisites(self, global_settings) -> bool:
_result = True
if self.detection_geometry is not None \
and not self.detection_geometry.check_settings_prerequisites(global_settings):
_result = False
for illumination_geometry in self.illumination_geometries:
if illumination_geometry is not None \
and not illumination_geometry.check_settings_prerequisites(global_settings):
_result = False
return _result
def update_settings_for_use_of_model_based_volume_creator(self, global_settings):
pass
def serialize(self) -> dict:
serialized_device = self.__dict__
device_dict = {"PhotoacousticDevice": serialized_device}
return device_dict
@staticmethod
def deserialize(dictionary_to_deserialize):
deserialized_device = PhotoacousticDevice(
device_position_mm=dictionary_to_deserialize["device_position_mm"],
field_of_view_extent_mm=dictionary_to_deserialize["field_of_view_extent_mm"])
det_geometry = dictionary_to_deserialize["detection_geometry"]
if det_geometry != "None":
deserialized_device.set_detection_geometry(dictionary_to_deserialize["detection_geometry"])
if "illumination_geometries" in dictionary_to_deserialize:
for illumination_geometry in dictionary_to_deserialize["illumination_geometries"]:
deserialized_device.illumination_geometries.append(illumination_geometry)
return deserialized_device
| [
"hashlib.md5",
"numpy.asarray",
"simpa.log.Logger",
"numpy.array",
"numpy.linalg.norm",
"numpy.add"
] | [((1628, 1636), 'simpa.log.Logger', 'Logger', ([], {}), '()\n', (1634, 1636), False, 'from simpa.log import Logger\n'), ((4254, 4513), 'numpy.asarray', 'np.asarray', (['[position[0] + field_of_view_extent[0], position[0] + field_of_view_extent[\n 1], position[1] + field_of_view_extent[2], position[1] +\n field_of_view_extent[3], position[2] + field_of_view_extent[4], \n position[2] + field_of_view_extent[5]]'], {}), '([position[0] + field_of_view_extent[0], position[0] +\n field_of_view_extent[1], position[1] + field_of_view_extent[2], \n position[1] + field_of_view_extent[3], position[2] +\n field_of_view_extent[4], position[2] + field_of_view_extent[5]])\n', (4264, 4513), True, 'import numpy as np\n'), ((5211, 5224), 'hashlib.md5', 'hashlib.md5', ([], {}), '()\n', (5222, 5224), False, 'import hashlib\n'), ((1305, 1324), 'numpy.array', 'np.array', (['[0, 0, 0]'], {}), '([0, 0, 0])\n', (1313, 1324), True, 'import numpy as np\n'), ((1484, 1523), 'numpy.asarray', 'np.asarray', (['[-10, 10, -10, 10, -10, 10]'], {}), '([-10, 10, -10, 10, -10, 10])\n', (1494, 1523), True, 'import numpy as np\n'), ((9633, 9705), 'numpy.add', 'np.add', (['self.device_position_mm', 'detector_position_relative_to_pa_device'], {}), '(self.device_position_mm, detector_position_relative_to_pa_device)\n', (9639, 9705), True, 'import numpy as np\n'), ((10919, 10975), 'numpy.linalg.norm', 'np.linalg.norm', (['illumination_geometry.device_position_mm'], {}), '(illumination_geometry.device_position_mm)\n', (10933, 10975), True, 'import numpy as np\n'), ((9447, 9500), 'numpy.linalg.norm', 'np.linalg.norm', (['detection_geometry.device_position_mm'], {}), '(detection_geometry.device_position_mm)\n', (9461, 9500), True, 'import numpy as np\n'), ((11112, 11187), 'numpy.add', 'np.add', (['self.device_position_mm', 'illuminator_position_relative_to_pa_device'], {}), '(self.device_position_mm, illuminator_position_relative_to_pa_device)\n', (11118, 11187), True, 'import numpy as np\n')] |
import numpy as np
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
imagenet_example_label = 'hammerhead, hammerhead shark'
imagenet_example_id = 4
imagenet_example = np.load(dir_path + '/imagenet_249.npy')
if __name__ == "__main__":
img = imagenet_example
print('img size: ', img.size)
print('img shape: ', img.shape)
print('img type and dtype: ', type(img), ',', img.dtype)
| [
"numpy.load",
"os.path.realpath"
] | [((185, 224), 'numpy.load', 'np.load', (["(dir_path + '/imagenet_249.npy')"], {}), "(dir_path + '/imagenet_249.npy')\n", (192, 224), True, 'import numpy as np\n'), ((56, 82), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (72, 82), False, 'import os\n')] |
"""Test patches.datasets.pilgrimm.simple_models.
"""
import unittest
import numpy as np
from .. import simple_models as models
class TestCGM(unittest.TestCase):
"""Test the compositional geometric model.
"""
def test_cgm(self):
"""Test the CGM."""
cgm = models.compositional_geometric_model(width=10, change_probs=[0, 1], samples=5, seed=100)
lat_array = cgm.latent_array()
self.assertEqual(len(np.unique(lat_array[:, 0])), 1)
self.assertEqual(len(np.unique(lat_array[:, 1])), 2)
def test_cbm(self):
"""Test the CBM."""
cbm = models.compositional_binary_model(width=1, change_probs=[0, 1], samples=5, seed=100)
self.assertTrue(np.all(cbm.flat_array()**2==1))
class TestOGM(unittest.TestCase):
"""Test the occluded geometric model.
"""
def test_ogm(self):
"""Test the OGM."""
ogm = models.occluded_geometric_model(width=10, change_probs=[0, 0], magic=[False, True],
samples=20, seed=100, occlusion_probs=1)
lat_array = ogm.latent_array()
self.assertEqual(len(np.unique(lat_array[:, 0])), 1)
self.assertEqual(len(np.unique(lat_array[:, 1])), 2)
def test_obm(self):
"""Test the OBM."""
obm = models.occluded_geometric_model(width=10, change_probs=[0, 0], magic=[False, True],
samples=20, seed=100, occlusion_probs=1)
self.assertTrue(np.all(obm.flat_array()==0))
class TestSGM(unittest.TestCase):
"""Test the sequential geometric model.
"""
def test_sgm(self):
"""Test the SGM."""
sgm = models.sequential_geometric_model(width=10, magic=[False, True], samples=20, seed=100,
occlusion_probs=[1, 1])
lat_array = sgm.latent_array()
self.assertTrue(np.all((lat_array[1:, 0]+lat_array[:-1, 0])==1))
self.assertFalse(np.all((lat_array[1:, 1]+lat_array[:-1, 1])==1))
class TestOSM(unittest.TestCase):
"""Test the object slots model.
"""
def test_osm(self):
"""Test the OSM."""
osm = models.object_slots_model(occlusion_probs=[0.2, 0.2], magic=[False, True], samples=20, seed=100,
appearance_probs=0.5)
lat_array = osm.latent_array()
print(lat_array)
diffs = (lat_array[1:] - lat_array[:-1])**2 != 0
self.assertEqual(sum(diffs[:, 0]), 1)
self.assertGreater(sum(diffs[:, 1]), 1)
| [
"numpy.unique",
"numpy.all"
] | [((1896, 1945), 'numpy.all', 'np.all', (['(lat_array[1:, 0] + lat_array[:-1, 0] == 1)'], {}), '(lat_array[1:, 0] + lat_array[:-1, 0] == 1)\n', (1902, 1945), True, 'import numpy as np\n'), ((1970, 2019), 'numpy.all', 'np.all', (['(lat_array[1:, 1] + lat_array[:-1, 1] == 1)'], {}), '(lat_array[1:, 1] + lat_array[:-1, 1] == 1)\n', (1976, 2019), True, 'import numpy as np\n'), ((444, 470), 'numpy.unique', 'np.unique', (['lat_array[:, 0]'], {}), '(lat_array[:, 0])\n', (453, 470), True, 'import numpy as np\n'), ((505, 531), 'numpy.unique', 'np.unique', (['lat_array[:, 1]'], {}), '(lat_array[:, 1])\n', (514, 531), True, 'import numpy as np\n'), ((1136, 1162), 'numpy.unique', 'np.unique', (['lat_array[:, 0]'], {}), '(lat_array[:, 0])\n', (1145, 1162), True, 'import numpy as np\n'), ((1197, 1223), 'numpy.unique', 'np.unique', (['lat_array[:, 1]'], {}), '(lat_array[:, 1])\n', (1206, 1223), True, 'import numpy as np\n')] |
# !/usr/bin/env python
# -*- coding:utf-8 -*-
"""
Copyright 2020 Tianshu AI Platform. 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 sched
import sys
import time
import json
import numpy as np
from abc import ABC
from program.abstract.algorithm import Algorithm
from skimage.morphology import disk, binary_erosion, binary_closing
from skimage.measure import label, regionprops, find_contours
from skimage.filters import roberts
from scipy import ndimage as ndi
from skimage.segmentation import clear_border
import pydicom as dicom
import os
import logging
schedule = sched.scheduler(time.time, time.sleep)
base_path = "/nfs/"
delayId = ""
class Lungsegmentation(Algorithm, ABC):
def __init__(self):
pass
def execute(task):
return Lungsegmentation.process(task)
def process(task_dict):
"""Lung segmentation based on dcm task method.
Args:
task_dict: imagenet task details.
key: imagenet task key.
"""
global delayId
base_path = task_dict["annotationPath"]
if not os.path.exists(base_path):
logging.info("make annotation path.")
os.makedirs(base_path)
for dcm in task_dict["dcms"]:
image, image_path = Lungsegmentation.preprocesss_dcm_image(dcm)
# segmentation and wirte coutours to result_path
result_path = os.path.join(base_path, image_path)
Lungsegmentation.contour(Lungsegmentation.segmentation(image), result_path)
logging.info("all dcms in one task are processed.")
finish_data = {"reTaskId": task_dict["reTaskId"]}
return finish_data, True
def preprocesss_dcm_image(path):
"""Load and preprocesss dcm image.
Args:
path: dcm file path.
"""
# result_path = os.path.basename(path).split(".", 1)[0] + ".json"
result_path = ".".join(os.path.basename(path).split(".")[0:-1]) + ".json"
dcm = dicom.dcmread(path)
image = dcm.pixel_array.astype(np.int16)
# Set outside-of-scan pixels to 0.
image[image == -2000] = 0
# Convert to Hounsfield units (HU)
intercept = dcm.RescaleIntercept
slope = dcm.RescaleSlope
if slope != 1:
image = slope * image.astype(np.float64)
image = image.astype(np.int16)
image += np.int16(intercept)
logging.info("preprocesss_dcm_image done.")
return np.array(image, dtype=np.int16), result_path
def segmentation(image):
"""Segments the lung from the given 2D slice.
Args:
image: single image in one dcm.
"""
# Step 1: Convert into a binary image.
binary = image < -350
# Step 2: Remove the blobs connected to the border of the image.
cleared = clear_border(binary)
# Step 3: Label the image.
label_image = label(cleared)
# Step 4: Keep the labels with 2 largest areas.
areas = [r.area for r in regionprops(label_image)]
areas.sort()
if len(areas) > 2:
for region in regionprops(label_image):
if region.area < areas[-2]:
for coordinates in region.coords:
label_image[coordinates[0], coordinates[1]] = 0
binary = label_image > 0
# Step 5: Erosion operation with a disk of radius 2. This operation is seperate the lung nodules attached to the blood vessels.
selem = disk(1)
binary = binary_erosion(binary, selem)
# Step 6: Closure operation with a disk of radius 10. This operation is to keep nodules attached to the lung wall.
selem = disk(16)
binary = binary_closing(binary, selem)
# Step 7: Fill in the small holes inside the binary mask of lungs.
for _ in range(3):
edges = roberts(binary)
binary = ndi.binary_fill_holes(edges)
logging.info("lung segmentation done.")
return binary
def contour(image, path):
"""Get contours of segmentation.
Args:
seg: segmentation of lung.
"""
result = []
contours = find_contours(image, 0.5)
if len(contours) > 2:
contours.sort(key=lambda x: int(x.shape[0]))
contours = contours[-2:]
for n, contour in enumerate(contours):
# result.append({"type":n, "annotation":contour.tolist()})
result.append({"type": n, "annotation": np.flip(contour, 1).tolist()})
# write json
with open(path, 'w') as f:
json.dump(result, f)
logging.info("write {} done.".format(path))
| [
"skimage.morphology.binary_closing",
"scipy.ndimage.binary_fill_holes",
"sched.scheduler",
"skimage.measure.label",
"skimage.measure.find_contours",
"os.path.join",
"skimage.measure.regionprops",
"os.path.exists",
"skimage.morphology.binary_erosion",
"skimage.segmentation.clear_border",
"json.du... | [((1143, 1181), 'sched.scheduler', 'sched.scheduler', (['time.time', 'time.sleep'], {}), '(time.time, time.sleep)\n', (1158, 1181), False, 'import sched\n'), ((2103, 2154), 'logging.info', 'logging.info', (['"""all dcms in one task are processed."""'], {}), "('all dcms in one task are processed.')\n", (2115, 2154), False, 'import logging\n'), ((2564, 2583), 'pydicom.dcmread', 'dicom.dcmread', (['path'], {}), '(path)\n', (2577, 2583), True, 'import pydicom as dicom\n'), ((2967, 2986), 'numpy.int16', 'np.int16', (['intercept'], {}), '(intercept)\n', (2975, 2986), True, 'import numpy as np\n'), ((2995, 3038), 'logging.info', 'logging.info', (['"""preprocesss_dcm_image done."""'], {}), "('preprocesss_dcm_image done.')\n", (3007, 3038), False, 'import logging\n'), ((3430, 3450), 'skimage.segmentation.clear_border', 'clear_border', (['binary'], {}), '(binary)\n', (3442, 3450), False, 'from skimage.segmentation import clear_border\n'), ((3509, 3523), 'skimage.measure.label', 'label', (['cleared'], {}), '(cleared)\n', (3514, 3523), False, 'from skimage.measure import label, regionprops, find_contours\n'), ((4096, 4103), 'skimage.morphology.disk', 'disk', (['(1)'], {}), '(1)\n', (4100, 4103), False, 'from skimage.morphology import disk, binary_erosion, binary_closing\n'), ((4121, 4150), 'skimage.morphology.binary_erosion', 'binary_erosion', (['binary', 'selem'], {}), '(binary, selem)\n', (4135, 4150), False, 'from skimage.morphology import disk, binary_erosion, binary_closing\n'), ((4291, 4299), 'skimage.morphology.disk', 'disk', (['(16)'], {}), '(16)\n', (4295, 4299), False, 'from skimage.morphology import disk, binary_erosion, binary_closing\n'), ((4317, 4346), 'skimage.morphology.binary_closing', 'binary_closing', (['binary', 'selem'], {}), '(binary, selem)\n', (4331, 4346), False, 'from skimage.morphology import disk, binary_erosion, binary_closing\n'), ((4544, 4583), 'logging.info', 'logging.info', (['"""lung segmentation done."""'], {}), "('lung segmentation done.')\n", (4556, 4583), False, 'import logging\n'), ((4790, 4815), 'skimage.measure.find_contours', 'find_contours', (['image', '(0.5)'], {}), '(image, 0.5)\n', (4803, 4815), False, 'from skimage.measure import label, regionprops, find_contours\n'), ((1656, 1681), 'os.path.exists', 'os.path.exists', (['base_path'], {}), '(base_path)\n', (1670, 1681), False, 'import os\n'), ((1695, 1732), 'logging.info', 'logging.info', (['"""make annotation path."""'], {}), "('make annotation path.')\n", (1707, 1732), False, 'import logging\n'), ((1745, 1767), 'os.makedirs', 'os.makedirs', (['base_path'], {}), '(base_path)\n', (1756, 1767), False, 'import os\n'), ((1970, 2005), 'os.path.join', 'os.path.join', (['base_path', 'image_path'], {}), '(base_path, image_path)\n', (1982, 2005), False, 'import os\n'), ((3054, 3085), 'numpy.array', 'np.array', (['image'], {'dtype': 'np.int16'}), '(image, dtype=np.int16)\n', (3062, 3085), True, 'import numpy as np\n'), ((3714, 3738), 'skimage.measure.regionprops', 'regionprops', (['label_image'], {}), '(label_image)\n', (3725, 3738), False, 'from skimage.measure import label, regionprops, find_contours\n'), ((4470, 4485), 'skimage.filters.roberts', 'roberts', (['binary'], {}), '(binary)\n', (4477, 4485), False, 'from skimage.filters import roberts\n'), ((4507, 4535), 'scipy.ndimage.binary_fill_holes', 'ndi.binary_fill_holes', (['edges'], {}), '(edges)\n', (4528, 4535), True, 'from scipy import ndimage as ndi\n'), ((5211, 5231), 'json.dump', 'json.dump', (['result', 'f'], {}), '(result, f)\n', (5220, 5231), False, 'import json\n'), ((3614, 3638), 'skimage.measure.regionprops', 'regionprops', (['label_image'], {}), '(label_image)\n', (3625, 3638), False, 'from skimage.measure import label, regionprops, find_contours\n'), ((2499, 2521), 'os.path.basename', 'os.path.basename', (['path'], {}), '(path)\n', (2515, 2521), False, 'import os\n'), ((5111, 5130), 'numpy.flip', 'np.flip', (['contour', '(1)'], {}), '(contour, 1)\n', (5118, 5130), True, 'import numpy as np\n')] |
from __future__ import print_function
import glob
import itertools
import math
import os
import sys
import time
import numpy as np
from ..apply.get_simulation_screenshot import get_simulation_screenshot, TEMP_PATH
from ..infer.inference_wrapper_single_line import InferenceWrapperSingleLine
from ..model.evolutionary_model import EvolutionaryModel
# A script for driving in the simulation using a neural network trained with evolutionary algorithms for steering
# Created by brendon-ai, January 2018
# Paths to the temporary and permanent steering angle files
STEERING_FILE_PATH = TEMP_PATH + '0sim.txt'
TEMP_STEERING_FILE_PATH = TEMP_PATH + 'temp.txt'
# Path to the temporary file whose existence instructs the simulation to reset the car to its starting position
RESET_FILE_PATH = TEMP_PATH + 'reset_sim'
# The number of models with added noise that should be tested on each iteration of the outer loop
# Use only one for a stochastic algorithm that will be less predictable but hopefully quicker to converge
NUM_NOISE_MODELS = 7
# The number of seconds to test each noise model for
TEST_SECONDS = 60
# An arbitrary large number that is higher than any standard deviation values that will be encountered during real use
LARGE_STANDARD_DEVIATION = 1000
# The standard deviation of the Gaussian noise added to proportional errors
PROPORTIONAL_ERROR_NOISE = 0
# Check that the number of command line arguments is correct
num_arguments = len(sys.argv)
if num_arguments != 2:
print('Usage:', sys.argv[0], '<right line trained model>')
sys.exit()
# Delete all old images and data files from the temp folder
for file_path in glob.iglob(TEMP_PATH + '*sim*'):
os.remove(file_path)
# Record initial output to the first steering angle file
os.system('echo 0.0 > %s-1sim.txt' % TEMP_PATH)
# Load the sliding window model using the path provided as a command line argument
sliding_window_model_path = os.path.expanduser(sys.argv[1])
# Create an inference wrapper using the model path
inference_wrapper = InferenceWrapperSingleLine(sliding_window_model_path)
# Create a copy of the steering engine for error analysis purposes that will calculate errors at the bottom of the image
analysis_steering_engine = inference_wrapper.steering_engine
analysis_steering_engine.center_y = 90
# Create an initial evolutionary model with the default learning rate
base_model = EvolutionaryModel()
# Initialize the variable that holds the proportional standard deviation of the base model, starting at a large number
base_model_proportional_standard_deviation = LARGE_STANDARD_DEVIATION
# Loop forever, counting up from 0
for i in itertools.count():
# Update the learning rate of the model
base_model.update_learning_rate()
# Print a summary of the model that is being used as a base line
print('Summary of base model for iteration {}:'.format(i))
base_model.print_summary()
# Create a predefined number of copies of the base model with noise added
noise_models = [base_model.with_noise() for _ in range(NUM_NOISE_MODELS)]
# Create a corresponding list of proportional standard deviations
proportional_standard_deviations = []
# For each of the modified models, and a corresponding increasing index number
for model, model_index in zip(noise_models, itertools.count()):
# Create an empty list to which the proportional errors for this test will be appended
proportional_errors = []
# Set the ending time for the repeating inner loop to a predefined number of seconds from now
end_time = time.time() + TEST_SECONDS
# Loop as quickly as possible until the end time
while time.time() < end_time:
# Get the greatest-numbered image in the temp folder
image = get_simulation_screenshot(True)
# If a valid image was not found, skip the rest of this iteration
if image is None:
continue
# Run inference using the inference wrapper and collect the center line positions
center_line_positions = inference_wrapper.infer(image)[1]
# Get the errors computed by the steering engine
errors = inference_wrapper.steering_engine.errors
# Add Gaussian noise to the proportional error to cripple performance in the simulator so that its
# performance is closer to that observed in the real world
errors[0] += np.random.normal(0, PROPORTIONAL_ERROR_NOISE)
# Compute a steering angle with the evolutionary model using the proportional and derivative errors
steering_angle = model(errors)
# Write the output to a temp file and rename it
with open(TEMP_STEERING_FILE_PATH, 'w') as temp_file:
print(steering_angle, file=temp_file)
os.rename(TEMP_STEERING_FILE_PATH, STEERING_FILE_PATH)
# Run inference with the analysis steering engine on the center line positions
analysis_steering_engine.compute_steering_angle(center_line_positions)
# Get the proportional error computed by the analysis engine and add it to the list
analysis_proportional_error = analysis_steering_engine.errors[0]
proportional_errors.append(analysis_proportional_error)
# If the error list is not empty
if proportional_errors:
# Compute the standard deviation (the square root of the mean squared proportional error)
squared_errors = [error ** 2 for error in proportional_errors]
variance = sum(squared_errors) / len(squared_errors)
standard_deviation = math.sqrt(variance)
proportional_standard_deviations.append(standard_deviation)
# Log the standard deviation for this model
print('Proportional standard deviation for model {}: {}'.format(model_index, standard_deviation))
# Otherwise, add a large number to the list and log an error message
else:
proportional_standard_deviations.append(LARGE_STANDARD_DEVIATION)
print('List of errors was empty for model {}'.format(model_index))
# Create the reset file so that the car will restart at the beginning
open(RESET_FILE_PATH, 'a').close()
# The best tested model is the one that has the lowest proportional standard deviation
# Check if this lowest error is less than the original error of the base model
min_standard_deviation = min(proportional_standard_deviations)
if min_standard_deviation < base_model_proportional_standard_deviation:
# Get the index of this model and make it the new base model
best_model_index = proportional_standard_deviations.index(min_standard_deviation)
base_model = noise_models[best_model_index]
# Print a log that says the base model has been updated
print(
'Base model updated; proportional standard deviation decreased from {} last iteration to {} this iteration'
.format(base_model_proportional_standard_deviation, min_standard_deviation)
)
# Set the proportional standard deviation for this model
base_model_proportional_standard_deviation = min_standard_deviation
# Otherwise, the best performance this iteration was worse than last iteration
else:
# Print a log stating that the model has not been updated
print(
'Base model not updated; lowest standard deviation so far was {},'
.format(base_model_proportional_standard_deviation),
'minimum for this iteration is {}'
.format(min_standard_deviation)
)
| [
"os.remove",
"math.sqrt",
"os.rename",
"os.system",
"itertools.count",
"time.time",
"numpy.random.normal",
"glob.iglob",
"os.path.expanduser",
"sys.exit"
] | [((1641, 1672), 'glob.iglob', 'glob.iglob', (["(TEMP_PATH + '*sim*')"], {}), "(TEMP_PATH + '*sim*')\n", (1651, 1672), False, 'import glob\n'), ((1757, 1804), 'os.system', 'os.system', (["('echo 0.0 > %s-1sim.txt' % TEMP_PATH)"], {}), "('echo 0.0 > %s-1sim.txt' % TEMP_PATH)\n", (1766, 1804), False, 'import os\n'), ((1917, 1948), 'os.path.expanduser', 'os.path.expanduser', (['sys.argv[1]'], {}), '(sys.argv[1])\n', (1935, 1948), False, 'import os\n'), ((2634, 2651), 'itertools.count', 'itertools.count', ([], {}), '()\n', (2649, 2651), False, 'import itertools\n'), ((1552, 1562), 'sys.exit', 'sys.exit', ([], {}), '()\n', (1560, 1562), False, 'import sys\n'), ((1678, 1698), 'os.remove', 'os.remove', (['file_path'], {}), '(file_path)\n', (1687, 1698), False, 'import os\n'), ((3300, 3317), 'itertools.count', 'itertools.count', ([], {}), '()\n', (3315, 3317), False, 'import itertools\n'), ((3569, 3580), 'time.time', 'time.time', ([], {}), '()\n', (3578, 3580), False, 'import time\n'), ((3667, 3678), 'time.time', 'time.time', ([], {}), '()\n', (3676, 3678), False, 'import time\n'), ((4436, 4481), 'numpy.random.normal', 'np.random.normal', (['(0)', 'PROPORTIONAL_ERROR_NOISE'], {}), '(0, PROPORTIONAL_ERROR_NOISE)\n', (4452, 4481), True, 'import numpy as np\n'), ((4830, 4884), 'os.rename', 'os.rename', (['TEMP_STEERING_FILE_PATH', 'STEERING_FILE_PATH'], {}), '(TEMP_STEERING_FILE_PATH, STEERING_FILE_PATH)\n', (4839, 4884), False, 'import os\n'), ((5650, 5669), 'math.sqrt', 'math.sqrt', (['variance'], {}), '(variance)\n', (5659, 5669), False, 'import math\n')] |
import numpy as np
import pandas as pd
import tensorflow as tf
from params import *
from network_utils import *
from training_utils import *
from data_utils import load_data, lift_drag
### load model
best_model = invariant_edge_model(edge_feature_dims, num_filters, initializer)
best_model.load_weights('./best_model/best_model')
#### load and normalize data
#nodes = pd.read_csv('../data/cylindre/nodes.csv')[['x', 'y', 'Object']].values.astype('float32')#, 'u_bc1', 'u_bc2', 'dist0']]
#flow = pd.read_csv('../data/cylindre/flow.csv').values.astype('float32')
#edges = pd.read_csv('../data/cylindre/edges.csv').values
nodes = pd.read_csv('../data/naca/nodes.csv')[['x', 'y', 'Object']].values.astype('float32')#, 'u_bc1', 'u_bc2', 'dist0']]
flow = pd.read_csv('../data/naca/flow.csv').values.astype('float32')
edges = pd.read_csv('../data/naca/edges.csv').values
print('non-used nodes', np.setdiff1d(np.arange(nodes.shape[0]), np.unique(edges)))
### delete useless nodes
nodes = nodes[np.unique(edges),:]
flow = flow[np.unique(edges),:]
## reset node index
_, edges = np.unique(edges, return_inverse=True)
edges = np.reshape(edges, (-1,2))
nodes = tf.convert_to_tensor(nodes, dtype=tf.dtypes.float32)
edges = tf.convert_to_tensor(edges, dtype=tf.dtypes.int32)
flow = tf.convert_to_tensor(flow, dtype=tf.dtypes.float32)
x = tf.math.divide(tf.math.subtract(nodes[:,0:1], -2.0), 4.0)
y = tf.math.divide(tf.math.subtract(nodes[:,1:2], -2.0), 4.0)
objet = tf.reshape(nodes[:,-1], (-1,1))
nodes = tf.concat([x,y,objet], axis=1)
min_values = tf.constant([-0.13420522212982178, -0.830278217792511, -1.9049606323242188], dtype=tf.dtypes.float32, shape=(3,))
max_values = tf.constant([1.4902634620666504, 0.799094557762146, 1.558414101600647], dtype=tf.dtypes.float32, shape=(3,))
flow2 = tf.math.divide(tf.math.subtract(flow, min_values), tf.math.subtract(max_values, min_values))
##### predict
count = count_neighb_elements(nodes, edges)
print('{} nodes, {} edges.'.format(nodes.numpy().shape[0], edges.numpy().shape[0]))
print(' ')
edge_features = tf.math.reduce_mean(tf.gather(nodes[:,:3], edges), 1)
pred = best_model(nodes[:,:3], edges, edge_features, count)
loss = loss_fn(pred, flow2)
print('The MAE on this shape is {}.'.format(float(loss)))
print(' ')
###### compute drag
elements= pd.read_csv('../data/naca/elements.csv').values
_, elements = np.unique(elements, return_inverse=True)
elements = np.reshape(elements, (-1,3))
D1, L1 = lift_drag(nodes.numpy(), edges.numpy(), elements, flow.numpy(), 0.1)
D2, L2 = lift_drag(nodes.numpy(), edges.numpy(), elements, pred.numpy(), 0.1)
print('drag', D1)
print('lift', D2)
##### save predicted velocity and pressure
pred = pred.numpy()
pred1 = pred[0:5,:]
pred2 = np.zeros((129,3))#59 for cylinder
pred3 = pred[5:,:]
pred = np.vstack([pred1, pred2, pred3])
np.savetxt('best_model/naca.csv', pred, delimiter=',', header='u,v,p', fmt='%1.16f', comments='')
| [
"pandas.read_csv",
"tensorflow.convert_to_tensor",
"tensorflow.math.subtract",
"tensorflow.reshape",
"numpy.zeros",
"tensorflow.concat",
"tensorflow.constant",
"numpy.savetxt",
"tensorflow.gather",
"numpy.arange",
"numpy.reshape",
"numpy.vstack",
"numpy.unique"
] | [((1082, 1119), 'numpy.unique', 'np.unique', (['edges'], {'return_inverse': '(True)'}), '(edges, return_inverse=True)\n', (1091, 1119), True, 'import numpy as np\n'), ((1128, 1154), 'numpy.reshape', 'np.reshape', (['edges', '(-1, 2)'], {}), '(edges, (-1, 2))\n', (1138, 1154), True, 'import numpy as np\n'), ((1163, 1215), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['nodes'], {'dtype': 'tf.dtypes.float32'}), '(nodes, dtype=tf.dtypes.float32)\n', (1183, 1215), True, 'import tensorflow as tf\n'), ((1224, 1274), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['edges'], {'dtype': 'tf.dtypes.int32'}), '(edges, dtype=tf.dtypes.int32)\n', (1244, 1274), True, 'import tensorflow as tf\n'), ((1283, 1334), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['flow'], {'dtype': 'tf.dtypes.float32'}), '(flow, dtype=tf.dtypes.float32)\n', (1303, 1334), True, 'import tensorflow as tf\n'), ((1471, 1504), 'tensorflow.reshape', 'tf.reshape', (['nodes[:, -1]', '(-1, 1)'], {}), '(nodes[:, -1], (-1, 1))\n', (1481, 1504), True, 'import tensorflow as tf\n'), ((1511, 1543), 'tensorflow.concat', 'tf.concat', (['[x, y, objet]'], {'axis': '(1)'}), '([x, y, objet], axis=1)\n', (1520, 1543), True, 'import tensorflow as tf\n'), ((1556, 1673), 'tensorflow.constant', 'tf.constant', (['[-0.13420522212982178, -0.830278217792511, -1.9049606323242188]'], {'dtype': 'tf.dtypes.float32', 'shape': '(3,)'}), '([-0.13420522212982178, -0.830278217792511, -1.9049606323242188],\n dtype=tf.dtypes.float32, shape=(3,))\n', (1567, 1673), True, 'import tensorflow as tf\n'), ((1683, 1795), 'tensorflow.constant', 'tf.constant', (['[1.4902634620666504, 0.799094557762146, 1.558414101600647]'], {'dtype': 'tf.dtypes.float32', 'shape': '(3,)'}), '([1.4902634620666504, 0.799094557762146, 1.558414101600647],\n dtype=tf.dtypes.float32, shape=(3,))\n', (1694, 1795), True, 'import tensorflow as tf\n'), ((2371, 2411), 'numpy.unique', 'np.unique', (['elements'], {'return_inverse': '(True)'}), '(elements, return_inverse=True)\n', (2380, 2411), True, 'import numpy as np\n'), ((2423, 2452), 'numpy.reshape', 'np.reshape', (['elements', '(-1, 3)'], {}), '(elements, (-1, 3))\n', (2433, 2452), True, 'import numpy as np\n'), ((2739, 2757), 'numpy.zeros', 'np.zeros', (['(129, 3)'], {}), '((129, 3))\n', (2747, 2757), True, 'import numpy as np\n'), ((2799, 2831), 'numpy.vstack', 'np.vstack', (['[pred1, pred2, pred3]'], {}), '([pred1, pred2, pred3])\n', (2808, 2831), True, 'import numpy as np\n'), ((2832, 2934), 'numpy.savetxt', 'np.savetxt', (['"""best_model/naca.csv"""', 'pred'], {'delimiter': '""","""', 'header': '"""u,v,p"""', 'fmt': '"""%1.16f"""', 'comments': '""""""'}), "('best_model/naca.csv', pred, delimiter=',', header='u,v,p', fmt=\n '%1.16f', comments='')\n", (2842, 2934), True, 'import numpy as np\n'), ((829, 866), 'pandas.read_csv', 'pd.read_csv', (['"""../data/naca/edges.csv"""'], {}), "('../data/naca/edges.csv')\n", (840, 866), True, 'import pandas as pd\n'), ((1355, 1392), 'tensorflow.math.subtract', 'tf.math.subtract', (['nodes[:, 0:1]', '(-2.0)'], {}), '(nodes[:, 0:1], -2.0)\n', (1371, 1392), True, 'import tensorflow as tf\n'), ((1417, 1454), 'tensorflow.math.subtract', 'tf.math.subtract', (['nodes[:, 1:2]', '(-2.0)'], {}), '(nodes[:, 1:2], -2.0)\n', (1433, 1454), True, 'import tensorflow as tf\n'), ((1815, 1849), 'tensorflow.math.subtract', 'tf.math.subtract', (['flow', 'min_values'], {}), '(flow, min_values)\n', (1831, 1849), True, 'import tensorflow as tf\n'), ((1851, 1891), 'tensorflow.math.subtract', 'tf.math.subtract', (['max_values', 'min_values'], {}), '(max_values, min_values)\n', (1867, 1891), True, 'import tensorflow as tf\n'), ((2085, 2115), 'tensorflow.gather', 'tf.gather', (['nodes[:, :3]', 'edges'], {}), '(nodes[:, :3], edges)\n', (2094, 2115), True, 'import tensorflow as tf\n'), ((2309, 2349), 'pandas.read_csv', 'pd.read_csv', (['"""../data/naca/elements.csv"""'], {}), "('../data/naca/elements.csv')\n", (2320, 2349), True, 'import pandas as pd\n'), ((912, 937), 'numpy.arange', 'np.arange', (['nodes.shape[0]'], {}), '(nodes.shape[0])\n', (921, 937), True, 'import numpy as np\n'), ((939, 955), 'numpy.unique', 'np.unique', (['edges'], {}), '(edges)\n', (948, 955), True, 'import numpy as np\n'), ((997, 1013), 'numpy.unique', 'np.unique', (['edges'], {}), '(edges)\n', (1006, 1013), True, 'import numpy as np\n'), ((1029, 1045), 'numpy.unique', 'np.unique', (['edges'], {}), '(edges)\n', (1038, 1045), True, 'import numpy as np\n'), ((759, 795), 'pandas.read_csv', 'pd.read_csv', (['"""../data/naca/flow.csv"""'], {}), "('../data/naca/flow.csv')\n", (770, 795), True, 'import pandas as pd\n'), ((636, 673), 'pandas.read_csv', 'pd.read_csv', (['"""../data/naca/nodes.csv"""'], {}), "('../data/naca/nodes.csv')\n", (647, 673), True, 'import pandas as pd\n')] |
"""
@author: <NAME>
@time: 2022/01/28
@description:
Holistic 3D Vision Challenge on General Room Layout Estimation Track Evaluation Package
https://github.com/bertjiazheng/indoor-layout-evaluation
"""
from scipy.optimize import linear_sum_assignment
import numpy as np
import scipy
HEIGHT, WIDTH = 512, 1024
MAX_DISTANCE = np.sqrt(HEIGHT**2 + WIDTH**2)
def f1_score_2d(gt_corners, dt_corners, thresholds):
distances = scipy.spatial.distance.cdist(gt_corners, dt_corners)
return eval_junctions(distances, thresholds=thresholds)
def eval_junctions(distances, thresholds=5):
thresholds = thresholds if isinstance(thresholds, tuple) or isinstance(
thresholds, list) else list([thresholds])
num_gts, num_preds = distances.shape
# filter the matches between ceiling-wall and floor-wall junctions
mask = np.zeros_like(distances, dtype=np.bool)
mask[:num_gts//2, :num_preds//2] = True
mask[num_gts//2:, num_preds//2:] = True
distances[~mask] = np.inf
# F-measure under different thresholds
Fs = []
Ps = []
Rs = []
for threshold in thresholds:
distances_temp = distances.copy()
# filter the mis-matched pairs
distances_temp[distances_temp > threshold] = np.inf
# remain the rows and columns that contain non-inf elements
distances_temp = distances_temp[:, np.any(np.isfinite(distances_temp), axis=0)]
if np.prod(distances_temp.shape) == 0:
Fs.append(0)
Ps.append(0)
Rs.append(0)
continue
distances_temp = distances_temp[np.any(np.isfinite(distances_temp), axis=1), :]
# solve the bipartite graph matching problem
row_ind, col_ind = linear_sum_assignment_with_inf(distances_temp)
true_positive = np.sum(np.isfinite(distances_temp[row_ind, col_ind]))
# compute precision and recall
precision = true_positive / num_preds
recall = true_positive / num_gts
# compute F measure
Fs.append(2 * precision * recall / (precision + recall))
Ps.append(precision)
Rs.append(recall)
return Fs, Ps, Rs
def linear_sum_assignment_with_inf(cost_matrix):
"""
Deal with linear_sum_assignment with inf according to
https://github.com/scipy/scipy/issues/6900#issuecomment-451735634
"""
cost_matrix = np.copy(cost_matrix)
cost_matrix[np.isinf(cost_matrix)] = MAX_DISTANCE
return linear_sum_assignment(cost_matrix) | [
"scipy.spatial.distance.cdist",
"numpy.zeros_like",
"numpy.copy",
"numpy.isinf",
"numpy.isfinite",
"numpy.sqrt",
"numpy.prod",
"scipy.optimize.linear_sum_assignment"
] | [((326, 359), 'numpy.sqrt', 'np.sqrt', (['(HEIGHT ** 2 + WIDTH ** 2)'], {}), '(HEIGHT ** 2 + WIDTH ** 2)\n', (333, 359), True, 'import numpy as np\n'), ((427, 479), 'scipy.spatial.distance.cdist', 'scipy.spatial.distance.cdist', (['gt_corners', 'dt_corners'], {}), '(gt_corners, dt_corners)\n', (455, 479), False, 'import scipy\n'), ((838, 877), 'numpy.zeros_like', 'np.zeros_like', (['distances'], {'dtype': 'np.bool'}), '(distances, dtype=np.bool)\n', (851, 877), True, 'import numpy as np\n'), ((2359, 2379), 'numpy.copy', 'np.copy', (['cost_matrix'], {}), '(cost_matrix)\n', (2366, 2379), True, 'import numpy as np\n'), ((2445, 2479), 'scipy.optimize.linear_sum_assignment', 'linear_sum_assignment', (['cost_matrix'], {}), '(cost_matrix)\n', (2466, 2479), False, 'from scipy.optimize import linear_sum_assignment\n'), ((2396, 2417), 'numpy.isinf', 'np.isinf', (['cost_matrix'], {}), '(cost_matrix)\n', (2404, 2417), True, 'import numpy as np\n'), ((1420, 1449), 'numpy.prod', 'np.prod', (['distances_temp.shape'], {}), '(distances_temp.shape)\n', (1427, 1449), True, 'import numpy as np\n'), ((1800, 1845), 'numpy.isfinite', 'np.isfinite', (['distances_temp[row_ind, col_ind]'], {}), '(distances_temp[row_ind, col_ind])\n', (1811, 1845), True, 'import numpy as np\n'), ((1370, 1397), 'numpy.isfinite', 'np.isfinite', (['distances_temp'], {}), '(distances_temp)\n', (1381, 1397), True, 'import numpy as np\n'), ((1600, 1627), 'numpy.isfinite', 'np.isfinite', (['distances_temp'], {}), '(distances_temp)\n', (1611, 1627), True, 'import numpy as np\n')] |
"""
Created: Thu Jul 25 12:29:27 2019
@author: <NAME> <<EMAIL>>
"""
# %% Import, compile and load
from numpy import array, linspace
from fffi import FortranLibrary, FortranModule
libfortmod = FortranLibrary('fortmod')
fortmod = FortranModule(libfortmod, 'fortmod')
# member variable and subroutine definition stub
# TODO: parse fortmod.f90 automatically and strip away implementation
with open('fortmod.f90', 'r') as f:
code = f.read()
fortmod.fdef(code)
libfortmod.compile() # only required when Fortran library has changed
fortmod.load()
# %% Try some stuff
print('Before init(): member = {}'.format(fortmod.member))
fortmod.init()
print('After init(): member = {}'.format(fortmod.member))
a = fortmod.member_array # this is a mutable reference
print('Before side_effects(): member_array = {}'.format(a))
fortmod.side_effects()
print('After side_effects(): member_array = {}'.format(a))
z = linspace(1, 10, 4)
print('Before modify_vector(z, 4): z = {}'.format(z))
fortmod.modify_vector(z, 4)
print('After modify_vector(z, 4): z = {}'.format(z))
A = array([[1, 2], [3, 4]], order='F')
print('Before modify_matrix(A, 1): z = {}'.format(A))
fortmod.modify_matrix(A, 1.0)
print('After modify_matrix(A, 1): z = {}'.format(A))
print('Before allocating array')
fortmod.alloc_member()
print('After allocating array')
print('Before accessing array')
print(fortmod.alloc_array)
print('After accessing array')
| [
"fffi.FortranModule",
"fffi.FortranLibrary",
"numpy.array",
"numpy.linspace"
] | [((194, 219), 'fffi.FortranLibrary', 'FortranLibrary', (['"""fortmod"""'], {}), "('fortmod')\n", (208, 219), False, 'from fffi import FortranLibrary, FortranModule\n'), ((230, 266), 'fffi.FortranModule', 'FortranModule', (['libfortmod', '"""fortmod"""'], {}), "(libfortmod, 'fortmod')\n", (243, 266), False, 'from fffi import FortranLibrary, FortranModule\n'), ((906, 924), 'numpy.linspace', 'linspace', (['(1)', '(10)', '(4)'], {}), '(1, 10, 4)\n', (914, 924), False, 'from numpy import array, linspace\n'), ((1065, 1099), 'numpy.array', 'array', (['[[1, 2], [3, 4]]'], {'order': '"""F"""'}), "([[1, 2], [3, 4]], order='F')\n", (1070, 1099), False, 'from numpy import array, linspace\n')] |
__author__ = 'nmearl'
from pynamic import photometry, optimizers
import numpy as np
class Optimizer(object):
def __init__(self, params, photo_data_file='', rv_data_file='', rv_body=0,
chain_file=''):
self.params = params
self.photo_data = np.loadtxt(photo_data_file,
unpack=True, usecols=(0, 1, 2))
self.rv_data = np.zeros((3, 0))
if rv_data_file:
self.rv_data = np.loadtxt(rv_data_file,
unpack=True, usecols=(0, 1, 2))
self.rv_body = rv_body
self.chain = np.zeros([1, 1 + len(self.params.get_all(True))])
self.maxlnp = -np.inf
if chain_file:
self.chain = np.load(chain_file)[975001:, :]
print(self.chain.shape)
def run(self, method=None, **kwargs):
if method == 'mcmc':
optimizers.hammer(self, **kwargs)
elif method == 'multinest':
optimizers.multinest(self, **kwargs)
else:
optimizers.minimizer(self, method=method, **kwargs)
def save(self, chain_out_file="chain.txt", photo_out_file="photo_model.txt",
rv_out_file="rv_model.txt"):
if False:
mod_flux, mod_rv = self.model()
mod_rv = self.filled_rv_model()
np.savetxt(photo_out_file, mod_flux)
np.savetxt(rv_out_file, mod_rv)
np.savetxt(chain_out_file, self.chain)
np.save("chain", self.chain)
def model(self, nprocs=1):
flux_x, rv_x = self.photo_data[0], self.rv_data[0]
x = np.append(flux_x, rv_x)
flux_inds = np.in1d(x, flux_x, assume_unique=True)
rv_inds = np.in1d(x, rv_x, assume_unique=True)
mod_flux, mod_rv = photometry.generate(self.params, x,
self.rv_body, nprocs)
return mod_flux[flux_inds], mod_rv[rv_inds]
def filled_rv_model(self, input_times, nprocs=1):
mod_flux, mod_rv = photometry.generate(self.params, input_times,
self.rv_body, nprocs)
return mod_rv
def update_chain(self, tlnl, theta):
nobj = np.append(tlnl, theta)
self.chain = np.vstack([self.chain, nobj])
def redchisq(self):
mod_flux, mod_rv = self.model()
chisq = np.sum(((self.photo_data[1] - mod_flux) /
self.photo_data[2]) ** 2)
# REMOVE LATER
trv_corr = self.params.get("gamma_t").value
mrv_corr = self.params.get("gamma_m").value
chisq += np.sum(((self.rv_data[1][:10] - (mod_rv[:10] + trv_corr)) /
self.rv_data[2][:10]) ** 2)
chisq += np.sum(((self.rv_data[1][10:] - (mod_rv[10:] + mrv_corr)) /
self.rv_data[2][10:]) ** 2)
deg = len(self.params.get_flat(True))
nu = self.photo_data[1].size + self.rv_data[1].size - 1.0 - deg
# nu = self.photo_data[1].size - 1.0 - deg
return chisq / nu
def iterout(self, tlnl=-np.inf, theta=None, max=True):
improved = tlnl > self.maxlnp if max else tlnl < self.maxlnp
if improved or not np.isfinite(tlnl):
if theta is not None:
self.params.update(theta)
self.params.save()
self.save()
self.maxlnp = tlnl | [
"pynamic.optimizers.minimizer",
"numpy.load",
"numpy.save",
"numpy.sum",
"pynamic.photometry.generate",
"pynamic.optimizers.hammer",
"pynamic.optimizers.multinest",
"numpy.savetxt",
"numpy.zeros",
"numpy.isfinite",
"numpy.append",
"numpy.loadtxt",
"numpy.vstack",
"numpy.in1d"
] | [((279, 338), 'numpy.loadtxt', 'np.loadtxt', (['photo_data_file'], {'unpack': '(True)', 'usecols': '(0, 1, 2)'}), '(photo_data_file, unpack=True, usecols=(0, 1, 2))\n', (289, 338), True, 'import numpy as np\n'), ((399, 415), 'numpy.zeros', 'np.zeros', (['(3, 0)'], {}), '((3, 0))\n', (407, 415), True, 'import numpy as np\n'), ((1478, 1506), 'numpy.save', 'np.save', (['"""chain"""', 'self.chain'], {}), "('chain', self.chain)\n", (1485, 1506), True, 'import numpy as np\n'), ((1610, 1633), 'numpy.append', 'np.append', (['flux_x', 'rv_x'], {}), '(flux_x, rv_x)\n', (1619, 1633), True, 'import numpy as np\n'), ((1655, 1693), 'numpy.in1d', 'np.in1d', (['x', 'flux_x'], {'assume_unique': '(True)'}), '(x, flux_x, assume_unique=True)\n', (1662, 1693), True, 'import numpy as np\n'), ((1712, 1748), 'numpy.in1d', 'np.in1d', (['x', 'rv_x'], {'assume_unique': '(True)'}), '(x, rv_x, assume_unique=True)\n', (1719, 1748), True, 'import numpy as np\n'), ((1777, 1834), 'pynamic.photometry.generate', 'photometry.generate', (['self.params', 'x', 'self.rv_body', 'nprocs'], {}), '(self.params, x, self.rv_body, nprocs)\n', (1796, 1834), False, 'from pynamic import photometry, optimizers\n'), ((2017, 2084), 'pynamic.photometry.generate', 'photometry.generate', (['self.params', 'input_times', 'self.rv_body', 'nprocs'], {}), '(self.params, input_times, self.rv_body, nprocs)\n', (2036, 2084), False, 'from pynamic import photometry, optimizers\n'), ((2212, 2234), 'numpy.append', 'np.append', (['tlnl', 'theta'], {}), '(tlnl, theta)\n', (2221, 2234), True, 'import numpy as np\n'), ((2256, 2285), 'numpy.vstack', 'np.vstack', (['[self.chain, nobj]'], {}), '([self.chain, nobj])\n', (2265, 2285), True, 'import numpy as np\n'), ((2367, 2434), 'numpy.sum', 'np.sum', (['(((self.photo_data[1] - mod_flux) / self.photo_data[2]) ** 2)'], {}), '(((self.photo_data[1] - mod_flux) / self.photo_data[2]) ** 2)\n', (2373, 2434), True, 'import numpy as np\n'), ((2605, 2697), 'numpy.sum', 'np.sum', (['(((self.rv_data[1][:10] - (mod_rv[:10] + trv_corr)) / self.rv_data[2][:10]) **\n 2)'], {}), '(((self.rv_data[1][:10] - (mod_rv[:10] + trv_corr)) / self.rv_data[2]\n [:10]) ** 2)\n', (2611, 2697), True, 'import numpy as np\n'), ((2736, 2828), 'numpy.sum', 'np.sum', (['(((self.rv_data[1][10:] - (mod_rv[10:] + mrv_corr)) / self.rv_data[2][10:]) **\n 2)'], {}), '(((self.rv_data[1][10:] - (mod_rv[10:] + mrv_corr)) / self.rv_data[2]\n [10:]) ** 2)\n', (2742, 2828), True, 'import numpy as np\n'), ((469, 525), 'numpy.loadtxt', 'np.loadtxt', (['rv_data_file'], {'unpack': '(True)', 'usecols': '(0, 1, 2)'}), '(rv_data_file, unpack=True, usecols=(0, 1, 2))\n', (479, 525), True, 'import numpy as np\n'), ((898, 931), 'pynamic.optimizers.hammer', 'optimizers.hammer', (['self'], {}), '(self, **kwargs)\n', (915, 931), False, 'from pynamic import photometry, optimizers\n'), ((1337, 1373), 'numpy.savetxt', 'np.savetxt', (['photo_out_file', 'mod_flux'], {}), '(photo_out_file, mod_flux)\n', (1347, 1373), True, 'import numpy as np\n'), ((1386, 1417), 'numpy.savetxt', 'np.savetxt', (['rv_out_file', 'mod_rv'], {}), '(rv_out_file, mod_rv)\n', (1396, 1417), True, 'import numpy as np\n'), ((1430, 1468), 'numpy.savetxt', 'np.savetxt', (['chain_out_file', 'self.chain'], {}), '(chain_out_file, self.chain)\n', (1440, 1468), True, 'import numpy as np\n'), ((746, 765), 'numpy.load', 'np.load', (['chain_file'], {}), '(chain_file)\n', (753, 765), True, 'import numpy as np\n'), ((980, 1016), 'pynamic.optimizers.multinest', 'optimizers.multinest', (['self'], {}), '(self, **kwargs)\n', (1000, 1016), False, 'from pynamic import photometry, optimizers\n'), ((1043, 1094), 'pynamic.optimizers.minimizer', 'optimizers.minimizer', (['self'], {'method': 'method'}), '(self, method=method, **kwargs)\n', (1063, 1094), False, 'from pynamic import photometry, optimizers\n'), ((3202, 3219), 'numpy.isfinite', 'np.isfinite', (['tlnl'], {}), '(tlnl)\n', (3213, 3219), True, 'import numpy as np\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Generate figure showing the distribution of memorization values for models
trained with two different learning rates.
Author: <NAME>
License: See LICENSE file.
Copyright: 2021, The Alan Turing Institute
"""
import argparse
import numpy as np
from fitter import Fitter
from analysis_utils import dict2tex
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
"--lr3-file",
help="NumPy compressed archive with results for learning rate 1e-3",
required=True,
)
parser.add_argument(
"--lr4-file",
help="NumPy compressed archive with results for learning rate 1e-4",
required=True,
)
parser.add_argument(
"-o", "--output", help="Output file to write to (.tex)", required=True
)
return parser.parse_args()
def make_tex(M3, M4):
m3 = M3[:, -1]
m4 = M4[:, -1]
assert len(m3) == len(m4) == 60_000
del M3, M4
tex = []
pgfplotsset = """
\\pgfplotsset{compat=newest,%
/pgf/declare function={
gauss(\\x) = 1/sqrt(2*pi) * exp(-0.5 * \\x * \\x);%
johnson(\\x,\\a,\\b) = \\b/sqrt(\\x * \\x + 1) * gauss(\\a+\\b*ln(\\x+sqrt(\\x*\\x+1)));%
johnsonsu(\\x,\\a,\\b,\\loc,\\scale) = johnson((\\x - \\loc)/\\scale,\\a,\\b)/\\scale;%
},
}
"""
tex.append("\\documentclass[10pt,preview=true]{standalone}")
# LuaLaTeX
tex.append(
"\\pdfvariable suppressoptionalinfo \\numexpr1+2+8+16+32+64+128+512\\relax"
)
tex.append("\\usepackage[utf8]{inputenc}")
tex.append("\\usepackage[T1]{fontenc}")
tex.append("\\usepackage{pgfplots}")
tex.append(pgfplotsset)
tex.append("\\definecolor{MyBlue}{HTML}{004488}")
tex.append("\\definecolor{MyYellow}{HTML}{DDAA33}")
tex.append("\\definecolor{MyRed}{HTML}{BB5566}")
tex.append("\\begin{document}")
tex.append("\\begin{tikzpicture}")
fontsize = "\\normalsize"
bins = 100
xmin = -15
xmax = 35
ymin = 0
ymax = 0.12
axis_opts = {
"xmin": xmin,
"xmax": xmax,
"ymin": ymin,
"ymax": ymax,
"scale only axis": None,
"xlabel": "Memorization score",
"ylabel": "Density",
"width": "6cm",
"height": "8cm",
"ytick": "{0, 0.05, 0.10}",
"yticklabels": "{0, 0.05, 0.10}",
"xlabel style": {"font": fontsize},
"ylabel style": {"font": fontsize},
"xticklabel style": {"font": fontsize},
"yticklabel style": {"font": fontsize},
"legend pos": "north east",
"legend style": {"font": fontsize},
"legend cell align": "left",
}
tex.append(f"\\begin{{axis}}[{dict2tex(axis_opts)}]")
thickness = "ultra thick"
hist_plot_opts = {
"forget plot": None,
"draw": "none",
"fill opacity": 0.3,
"hist": {
"bins": bins,
"density": "true",
"data min": xmin,
"data max": xmax,
},
}
line_plot_opts = {
"domain": f"{xmin}:{xmax}",
"samples": 201,
"mark": "none",
"solid": None,
thickness: None,
}
vert_plot_opts = {
"forget plot": None,
"densely dashed": None,
thickness: None,
}
ms = [m3, m4]
labels = ["$\\eta = 10^{-3}$", "$\\eta = 10^{-4}$"]
colors = ["MyBlue", "MyYellow"]
for m, label, color in zip(ms, labels, colors):
hist_plot_opts["fill"] = color
line_plot_opts["draw"] = color
vert_plot_opts["draw"] = color
tex.append(
f"\\addplot [{dict2tex(hist_plot_opts)}] table[y index=0] {{%"
)
tex.append("data")
for v in m:
tex.append(str(v.item()))
tex.append("};")
f = Fitter(
m, distributions=["johnsonsu"], xmin=xmin, xmax=xmax, bins=bins
)
f.fit()
params = f.get_best()
a, b, loc, scale = params["johnsonsu"]
tex.append(f"\\addplot [{dict2tex(line_plot_opts)}] {{%")
tex.append(f"johnsonsu(x, {a}, {b}, {loc}, {scale})")
tex.append("};")
tex.append(f"\\addlegendentry{{{label}}}")
tex.append(f"\\addplot [{dict2tex(vert_plot_opts)}] coordinates {{%")
tex.append(
f"({np.quantile(m, 0.95)}, {ymin}) ({np.quantile(m, 0.95)}, {ymax})"
)
tex.append("};")
tex.append("\\end{axis}")
tex.append("\\end{tikzpicture}")
tex.append("\\end{document}")
return tex
def main():
args = parse_args()
bmnist3 = np.load(args.lr3_file)
bmnist4 = np.load(args.lr4_file)
M3 = bmnist3["M"]
M4 = bmnist4["M"]
tex = make_tex(M3, M4)
with open(args.output, "w") as fp:
fp.write("\n".join(tex))
if __name__ == "__main__":
main()
| [
"numpy.load",
"numpy.quantile",
"argparse.ArgumentParser",
"analysis_utils.dict2tex",
"fitter.Fitter"
] | [((394, 419), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (417, 419), False, 'import argparse\n'), ((4602, 4624), 'numpy.load', 'np.load', (['args.lr3_file'], {}), '(args.lr3_file)\n', (4609, 4624), True, 'import numpy as np\n'), ((4639, 4661), 'numpy.load', 'np.load', (['args.lr4_file'], {}), '(args.lr4_file)\n', (4646, 4661), True, 'import numpy as np\n'), ((3825, 3896), 'fitter.Fitter', 'Fitter', (['m'], {'distributions': "['johnsonsu']", 'xmin': 'xmin', 'xmax': 'xmax', 'bins': 'bins'}), "(m, distributions=['johnsonsu'], xmin=xmin, xmax=xmax, bins=bins)\n", (3831, 3896), False, 'from fitter import Fitter\n'), ((2726, 2745), 'analysis_utils.dict2tex', 'dict2tex', (['axis_opts'], {}), '(axis_opts)\n', (2734, 2745), False, 'from analysis_utils import dict2tex\n'), ((3643, 3667), 'analysis_utils.dict2tex', 'dict2tex', (['hist_plot_opts'], {}), '(hist_plot_opts)\n', (3651, 3667), False, 'from analysis_utils import dict2tex\n'), ((4046, 4070), 'analysis_utils.dict2tex', 'dict2tex', (['line_plot_opts'], {}), '(line_plot_opts)\n', (4054, 4070), False, 'from analysis_utils import dict2tex\n'), ((4251, 4275), 'analysis_utils.dict2tex', 'dict2tex', (['vert_plot_opts'], {}), '(vert_plot_opts)\n', (4259, 4275), False, 'from analysis_utils import dict2tex\n'), ((4332, 4352), 'numpy.quantile', 'np.quantile', (['m', '(0.95)'], {}), '(m, 0.95)\n', (4343, 4352), True, 'import numpy as np\n'), ((4365, 4385), 'numpy.quantile', 'np.quantile', (['m', '(0.95)'], {}), '(m, 0.95)\n', (4376, 4385), True, 'import numpy as np\n')] |
import tensorflow as tf
import re
import os
import json
import numpy as np
import codecs
from configs.event_config import event_config
from data_processing.event_prepare_data import EventRolePrepareMRC, EventTypeClassificationPrepare
from tensorflow.contrib import predictor
from pathlib import Path
from argparse import ArgumentParser
import datetime
import ipdb
class fastPredictTypeClassification:
def __init__(self, model_path, config):
self.model_path = model_path
self.data_loader = self.init_data_loader(config)
self.predict_fn = None
self.config = config
def load_models(self):
subdirs = [x for x in Path(self.model_path).iterdir()
if x.is_dir() and 'temp' not in str(x)]
latest = str(sorted(subdirs)[-1])
predict_fn = predictor.from_saved_model(latest)
return predict_fn
def load_models_kfold(self, model_path):
subdirs = [x for x in Path(model_path).iterdir()
if x.is_dir() and 'temp' not in str(x)]
latest = str(sorted(subdirs)[-1])
predict_fn = predictor.from_saved_model(latest)
return predict_fn
def init_data_loader(self, config):
event_type_file = os.path.join(config.get("slot_list_root_path"), config.get("event_type_file"))
# event_type_file = "data/slot_pattern/vocab_all_role_label_noBI_map.txt"
vocab_file_path = os.path.join(config.get(
"bert_pretrained_model_path"), config.get("vocab_file"))
data_loader = EventTypeClassificationPrepare(vocab_file_path, 512, event_type_file)
# data_loader = EventRoleClassificationPrepare(
# vocab_file_path, 512, event_type_file)
return data_loader
def parse_test_json(self, test_file):
id_list = []
text_list = []
with codecs.open(test_file, 'r', 'utf-8') as fr:
for line in fr:
line = line.strip()
line = line.strip("\n")
d_json = json.loads(line)
id_list.append(d_json.get("id"))
text_list.append(d_json.get("text"))
return id_list, text_list
def predict_single_sample(self, text):
words_input, token_type_ids = self.data_loader.trans_single_data_for_test(
text)
predictions = self.predict_fn({'words': [words_input], 'text_length': [
len(words_input)], 'token_type_ids': [token_type_ids]})
label = predictions["output"][0]
return np.argwhere(label > 0.5)
def predict_single_sample_prob(self, predict_fn, text):
words_input, token_type_ids, type_index_in_token_ids = self.data_loader.trans_single_data_for_test(
text)
predictions = predict_fn({'words': [words_input], 'text_length': [
len(words_input)], 'token_type_ids': [token_type_ids], 'type_index_in_ids_list': [type_index_in_token_ids]})
label = predictions["output"][0]
return label
def predict_for_all_prob(self, predict_fn, text_list):
event_type_prob = []
for text in text_list:
prob_output = self.predict_single_sample_prob(predict_fn, text)
event_type_prob.append(prob_output)
return event_type_prob
def predict_for_all(self, text_list):
event_result_list = []
for text in text_list:
label_output = self.predict_single_sample(text)
event_cur_type_list = [self.data_loader.id2labels_map.get(
ele[0]) for ele in label_output]
event_result_list.append(event_cur_type_list)
return event_result_list
class fastPredictCls:
def __init__(self, model_path, config, query_map_file):
self.model_path = model_path
self.data_loader = self.init_data_loader(config, query_map_file)
self.predict_fn = None
self.config = config
def load_models_kfold(self, model_path):
subdirs = [x for x in Path(model_path).iterdir()
if x.is_dir() and 'temp' not in str(x)]
latest = str(sorted(subdirs)[-1])
predict_fn = predictor.from_saved_model(latest)
return predict_fn
def init_data_loader(self, config, query_map_file):
vocab_file_path = os.path.join(config.get(
"bert_pretrained_model_path"), config.get("vocab_file"))
slot_file = os.path.join(event_config.get("slot_list_root_path"),
event_config.get("bert_slot_complete_file_name_role"))
schema_file = os.path.join(event_config.get(
"data_dir"), event_config.get("event_schema"))
# query_map_file = os.path.join(event_config.get(
# "slot_list_root_path"), event_config.get("query_map_file"))
data_loader = EventRolePrepareMRC(
vocab_file_path, 512, slot_file, schema_file, query_map_file)
return data_loader
def parse_test_json(self, test_file):
id_list = []
text_list = []
with codecs.open(test_file, 'r', 'utf-8') as fr:
for line in fr:
line = line.strip()
line = line.strip("\n")
d_json = json.loads(line)
id_list.append(d_json.get("id"))
text_list.append(d_json.get("text"))
return id_list, text_list
def predict_single_sample_prob(self, predict_fn, text, query_len, token_type_ids):
# words_input, token_type_ids,type_index_in_token_ids = self.data_loader.trans_single_data_for_test(
# text)
text_length = len(text)
predictions = predict_fn({'words': [text], 'text_length': [text_length],
'token_type_ids': [token_type_ids]})
label_prob = predictions["output"][0]
return label_prob
def predict_single_sample_av_prob(self, predict_fn, text, query_len, token_type_ids):
text_length = len(text)
predictions = predict_fn({'words': [text], 'text_length': [text_length], 'query_length': [query_len],
'token_type_ids': [token_type_ids]})
start_ids, end_ids, start_probs, end_probs, has_answer_probs = predictions.get("start_ids"), predictions.get(
"end_ids"), predictions.get("start_probs"), predictions.get("end_probs"), predictions.get(
"has_answer_probs")
return start_ids[0], end_ids[0], start_probs[0], end_probs[0], has_answer_probs[0]
# def predict_for_all_prob(self,predict_fn,text_list):
# event_type_prob = []
# for text in text_list:
# prob_output = self.predict_single_sample_prob(predict_fn,text)
# event_type_prob.append(prob_output)
# return event_type_prob
def extract_entity_from_start_end_ids(self, text, start_ids, end_ids, token_mapping):
# 根据开始,结尾标识,找到对应的实体
entity_list = []
start_end_tuple_list = []
# text_cur_index = 0
for i, start_id in enumerate(start_ids):
if start_id == 0:
# text_cur_index += len(token_mapping[i])
continue
if end_ids[i] == 1:
# start and end is the same
entity_str = "".join([text[char_index]
for char_index in token_mapping[i]])
# entity_str = text[text_cur_index:text_cur_index+cur_entity_len]
entity_list.append(entity_str)
start_end_tuple_list.append((i, i))
# text_cur_index += len(token_mapping[i])
continue
j = i + 1
find_end_tag = False
while j < len(end_ids):
# 若在遇到end=1之前遇到了新的start=1,则停止该实体的搜索
if start_ids[j] == 1:
break
if end_ids[j] == 1:
entity_str_index_list = []
for index in range(i, j + 1):
entity_str_index_list.extend(token_mapping[index])
start_end_tuple_list.append((i, j))
entity_str = "".join([text[char_index]
for char_index in entity_str_index_list])
entity_list.append(entity_str)
find_end_tag = True
break
else:
j += 1
if not find_end_tag:
entity_str = "".join([text[char_index]
for char_index in token_mapping[i]])
start_end_tuple_list.append((i, i))
entity_list.append(entity_str)
return entity_list, start_end_tuple_list
class fastPredictMRC:
def __init__(self, model_path, config, model_type):
self.model_path = model_path
self.model_type = model_type
self.data_loader = self.init_data_loader(config, model_type)
# self.predict_fn = self.load_models()
self.config = config
def load_models(self, model_path):
subdirs = [x for x in Path(model_path).iterdir()
if x.is_dir() and 'tmp' not in str(x)]
latest = str(sorted(subdirs)[-1])
# print(latest)
predict_fn = predictor.from_saved_model(latest)
return predict_fn
def init_data_loader(self, config, model_type):
vocab_file_path = os.path.join(config.get(
"bert_pretrained_model_path"), config.get("vocab_file"))
slot_file = os.path.join(event_config.get("slot_list_root_path"),
event_config.get("bert_slot_complete_file_name_role"))
schema_file = os.path.join(event_config.get(
"data_dir"), event_config.get("event_schema"))
query_map_file = os.path.join(event_config.get(
"slot_list_root_path"), event_config.get("query_map_file"))
data_loader = EventRolePrepareMRC(
vocab_file_path, 512, slot_file, schema_file, query_map_file)
return data_loader
def parse_test_json(self, test_file):
id_list = []
text_list = []
with codecs.open(test_file, 'r', 'utf-8') as fr:
for line in fr:
line = line.strip()
line = line.strip("\n")
d_json = json.loads(line)
id_list.append(d_json.get("id"))
text_list.append(d_json.get("text"))
return id_list, text_list
def predict_single_sample(self, predict_fn, text, query_len, token_type_ids):
text_length = len(text)
# print(text)
predictions = predict_fn({'words': [text], 'text_length': [text_length], 'query_length': [query_len],
'token_type_ids': [token_type_ids]})
# print(predictions)
# start_ids, end_ids,start_probs,end_probs = predictions.get("start_ids"), predictions.get("end_ids"),predictions.get("start_probs"), predictions.get("end_probs")
pred_ids, pred_probs = predictions.get("pred_ids"), predictions.get("pred_probs")
# return start_ids[0], end_ids[0],start_probs[0], end_probs[0]
return pred_ids[0], pred_probs[0]
def extract_entity_from_start_end_ids(self, text, start_ids, end_ids, token_mapping):
# 根据开始,结尾标识,找到对应的实体
entity_list = []
# text_cur_index = 0
for i, start_id in enumerate(start_ids):
if start_id == 0:
# text_cur_index += len(token_mapping[i])
continue
if end_ids[i] == 1:
# start and end is the same
entity_str = "".join([text[char_index]
for char_index in token_mapping[i]])
# entity_str = text[text_cur_index:text_cur_index+cur_entity_len]
entity_list.append(entity_str)
# text_cur_index += len(token_mapping[i])
continue
j = i + 1
find_end_tag = False
while j < len(end_ids):
# 若在遇到end=1之前遇到了新的start=1,则停止该实体的搜索
if start_ids[j] == 1:
break
if end_ids[j] == 1:
entity_str_index_list = []
for index in range(i, j + 1):
entity_str_index_list.extend(token_mapping[index])
entity_str = "".join([text[char_index]
for char_index in entity_str_index_list])
entity_list.append(entity_str)
find_end_tag = True
break
else:
j += 1
if not find_end_tag:
entity_str = "".join([text[char_index]
for char_index in token_mapping[i]])
entity_list.append(entity_str)
return entity_list
def parse_event_schema(json_file):
event_type_role_dict = {}
with codecs.open(json_file, 'r', 'utf-8') as fr:
for line in fr:
line = line.strip()
line = line.strip("\n")
data_json = json.loads(line)
event_type = data_json.get("event_type")
role_list = data_json.get("role_list")
role_name_list = [ele.get("role") for ele in role_list]
event_type_role_dict.update({event_type: role_name_list})
return event_type_role_dict
def parse_schema_type(schema_file):
schema_event_dict = {}
with codecs.open(schema_file, 'r', 'utf-8') as fr:
for line in fr:
s_json = json.loads(line)
role_list = s_json.get("role_list")
schema_event_dict.update(
{s_json.get("event_type"): [ele.get("role") for ele in role_list]})
return schema_event_dict
def extract_entity_span_from_muliclass(text, pred_ids, token_mapping):
buffer_list = []
entity_list = []
for index, label in enumerate(pred_ids):
if label == 0:
if buffer_list:
entity_str_index_list = []
for i in buffer_list:
entity_str_index_list.extend(token_mapping[i])
entity_str = "".join([text[char_index]
for char_index in entity_str_index_list])
entity_list.append(entity_str)
buffer_list.clear()
continue
elif label == 1:
if buffer_list:
entity_str_index_list = []
for i in buffer_list:
entity_str_index_list.extend(token_mapping[i])
entity_str = "".join([text[char_index]
for char_index in entity_str_index_list])
entity_list.append(entity_str)
buffer_list.clear()
buffer_list.append(index)
else:
if buffer_list:
buffer_list.append(index)
if buffer_list:
entity_str_index_list = []
for i in buffer_list:
entity_str_index_list.extend(token_mapping[i])
entity_str = "".join([text[char_index]
for char_index in entity_str_index_list])
entity_list.append(entity_str)
return entity_list
def parse_kfold_verify(args):
if(args.gpus is not None):
os.environ["CUDA_VISIBLE_DEVICES"] = args.gpus
# test_file = "data/test1.json"
# Path of test dataset json file
test_file = os.path.join(event_config.get("data_dir"), event_config.get("event_data_file_test"))
# Path of text multi label classification saved model
class_type_model_path = event_config.get(args.event_type_model_path)
event_schema_file = os.path.join(event_config.get("data_dir"), event_config.get("event_schema"))
event_schema_dict = parse_event_schema(event_schema_file)
# multi label event type classifer
fp_type = fastPredictTypeClassification(class_type_model_path, event_config)
# parse json file to get id and text
id_list, text_list = fp_type.parse_test_json(test_file)
#
kfold_type_result_list = [] # for prediction in 65 probabilities
event_type_result_list = [] # for result event type name
for k in range(1):
predict_fn = fp_type.load_models_kfold(class_type_model_path.format(k))
cur_fold_event_type_probs = fp_type.predict_for_all_prob(predict_fn,text_list)
kfold_type_result_list.append(cur_fold_event_type_probs)
for i in range(len(text_list)):
cur_sample_event_type_buffer = [ele[i] for ele in kfold_type_result_list]
cur_sample_event_type_prob = np.array(cur_sample_event_type_buffer).reshape((-1,65))
avg_result = np.mean(cur_sample_event_type_prob,axis=0)
event_label_ids = np.argwhere(avg_result > 0.5)
event_cur_type_strs = [fp_type.data_loader.id2labels_map.get(
ele[0]) for ele in event_label_ids]
event_type_result_list.append(event_cur_type_strs)
# path of Answerable Verificaion model to predict whether a query is answerable,
# 第一阶段 粗读 的 answaerable verifier ,
# External Front Verifier
exterinal_av_model_path = "output/model/final_verify_cls_fold_{}_usingtype_roberta_large_traindev_event_role_bert_mrc_model_desmodified_lowercase/saved_model"
# verify_av_model_path_old = event_config.get(args.event_verfifyav_model_path)
verify_av_model_path_old = "output/model/verify_avmrc_fold_{}_usingtype_roberta_large_traindev_event_role_bert_mrc_model_desmodified_lowercase/saved_model"
# 第二阶段 精读 的 answaerable verifier ,
# Internal Front Verifier 。
interbal_av_model_path = "output/model/final_verify_avmrc_fold_{}_usingtype_roberta_large_traindev_event_role_bert_mrc_model_desmodified_lowercase/saved_model"
fp_cls_old = fastPredictCls(exterinal_av_model_path, event_config, "data/slot_pattern/slot_descrip_old")
# fp_cls_new = fastPredictCls(cls_model_path, event_config, "data/slot_pattern/slot_descrip")
fp_answerable_verifier = fastPredictCls(exterinal_av_model_path, event_config, "data/slot_pattern/slot_descrip")
kfold_eav_hasa_result = []
kfold_start_result = []
kfold_end_result = []
kfold_hasa_result = []
for k in range(1):
# predict_fn_cls_new = fp_answerable_verifier.load_models_kfold(external_av_model_path.format(k))
# 粗读fn
predict_fn_ex_av = fp_answerable_verifier.load_models_kfold(exterinal_av_model_path.format(k))
# predict_fn_av = fp_cls_new.load_models_kfold(verify_av_model_path_new.format(k))
# 精读fn
predict_fn_in_av = fp_answerable_verifier.load_models_kfold(interbal_av_model_path.format(k))
cur_fold_eav_probs_result = {}
cur_fold_av_start_probs_result = {}
cur_fold_av_end_probs_result = {}
cur_fold_av_has_answer_probs_result = {}
for sample_id, event_type_res, text in zip(id_list, event_type_result_list, text_list):
if event_type_res is None or len(event_type_res) == 0:
# submit_result.append({"id": sample_id, "event_list": []})
cur_fold_eav_probs_result.update({sample_id: []})
continue
for cur_event_type in event_type_res:
cur_event_type = cur_event_type.strip()
if cur_event_type is None or cur_event_type == "":
continue
corresponding_role_type_list = event_schema_dict.get(cur_event_type)
cur_event_type_answerable_probs_result = []
cur_event_av_start_probs_result = []
cur_event_av_end_probs_result = []
cur_event_av_hasanswer_probs_result = []
for cur_role_type in corresponding_role_type_list:
has_answer_probs = None
label_prob = None
start_probs = None
end_probs = None
cur_query_word = fp_answerable_verifier.data_loader.gen_query_for_each_sample(
cur_event_type, cur_role_type)
query_token_ids, query_token_len, token_type_ids_ , token_mapping_new = fp_answerable_verifier.data_loader.trans_single_data_for_test(
text, cur_query_word, 512)
#############################################################################
## Exterinal Answerable Verify, predict answerable probs
eav_probs = fp_answerable_verifier.predict_single_sample_prob(predict_fn_ex_av, query_token_ids,
query_token_len, token_type_ids_ )
#############################################################################
# Internal Answerable Verify ,predict start&end labe and answerable probs
role_start_ids, role_end_ids, role_start_probs, role_end_probs, iav_probs = fp_cls_old.predict_single_sample_av_prob(
predict_fn_in_av, query_token_ids, query_token_len, token_type_ids_ )
cur_event_type_answerable_probs_result.append(eav_probs)
cur_event_av_hasanswer_probs_result.append(iav_probs)
cur_event_av_start_probs_result.append(role_start_probs)
cur_event_av_end_probs_result.append(role_end_probs)
cur_fold_eav_probs_result.update({sample_id + "-" + cur_event_type: cur_event_type_answerable_probs_result})
cur_fold_av_start_probs_result.update(
{sample_id + "-" + cur_event_type: cur_event_av_start_probs_result})
cur_fold_av_end_probs_result.update({sample_id + "-" + cur_event_type: cur_event_av_end_probs_result})
cur_fold_av_has_answer_probs_result.update(
{sample_id + "-" + cur_event_type: cur_event_av_hasanswer_probs_result})
kfold_eav_hasa_result.append(cur_fold_eav_probs_result)
kfold_start_result.append(cur_fold_av_start_probs_result)
kfold_end_result.append(cur_fold_av_end_probs_result)
kfold_hasa_result.append(cur_fold_av_has_answer_probs_result)
submit_result = []
for sample_id, event_type_res, text in zip(id_list, event_type_result_list, text_list):
event_list = []
if event_type_res is None or len(event_type_res) == 0:
submit_result.append({"id": sample_id, "event_list": []})
continue
for cur_event_type in event_type_res:
cur_event_type = cur_event_type.strip()
if cur_event_type is None or cur_event_type == "":
continue
corresponding_role_type_list = event_schema_dict.get(cur_event_type)
find_key = sample_id + "-" + cur_event_type
fold_cls_probs_cur_sample = [ele.get(find_key) for ele in kfold_eav_hasa_result]
fold_start_probs_cur_sample = [ele.get(find_key) for ele in kfold_start_result]
fold_end_probs_cur_sample = [ele.get(find_key) for ele in kfold_end_result]
fold_has_probs_cur_sample = [ele.get(find_key) for ele in kfold_hasa_result]
for index, cur_role_type in enumerate(corresponding_role_type_list):
cur_eav_fold_probs = [probs[index] for probs in fold_cls_probs_cur_sample]
cur_iav_hasa_fold_probs = [probs[index] for probs in fold_has_probs_cur_sample]
cur_eav_fold_probs = np.array(cur_eav_fold_probs).reshape((-1, 1))
cls_avg_result = np.mean(cur_eav_fold_probs, axis=0)
cur_iav_hasa_fold_probs = np.array(cur_iav_hasa_fold_probs).reshape((-1, 1))
has_avg_result = np.mean(cur_iav_hasa_fold_probs, axis=0)
######
# EAV * 0.5 + IAV * 0.5
final_probs_hasa = 0.5 * (cls_avg_result) + 0.5 * (has_avg_result)
if final_probs_hasa > 0.4:
cur_query_word = fp_answerable_verifier.data_loader.gen_query_for_each_sample(
cur_event_type, cur_role_type)
token_ids, query_len, token_type_ids, token_mapping = fp_answerable_verifier.data_loader.trans_single_data_for_test(
text, cur_query_word, 512)
token_len = len(token_ids)
cur_start_fold_probs = [probs[index] for probs in fold_start_probs_cur_sample]
cur_end_fold_probs = [probs[index] for probs in fold_end_probs_cur_sample]
cur_start_fold_probs = np.array(cur_start_fold_probs).reshape((-1, token_len, 2))
cur_end_fold_probs = np.array(cur_end_fold_probs).reshape((-1, token_len, 2))
start_avg_result = np.mean(cur_start_fold_probs, axis=0)
end_avg_result = np.mean(cur_end_fold_probs, axis=0)
text_start_probs = start_avg_result[query_len:-1, 1]
text_end_probs = end_avg_result[query_len:-1, 1]
pos_start_probs = (text_start_probs)
pos_end_probs = (text_end_probs)
start_ids = (pos_start_probs > 0.4).astype(int)
end_ids = (pos_end_probs > 0.4).astype(int)
token_mapping = token_mapping[1:-1]
entity_list, span_start_end_tuple_list = fp_answerable_verifier.extract_entity_from_start_end_ids(
text=text, start_ids=start_ids, end_ids=end_ids, token_mapping=token_mapping)
for entity in entity_list:
if len(entity) > 1:
event_list.append({"event_type": cur_event_type, "arguments": [
{"role": cur_role_type, "argument": entity}]})
submit_result.append({"id": sample_id, "event_list": event_list})
with codecs.open(args.submit_result, 'w', 'utf-8') as fw:
for dict_result in submit_result:
write_str = json.dumps(dict_result, ensure_ascii=False)
fw.write(write_str)
fw.write("\n")
print("finish")
if __name__ == '__main__':
print(os.listdir("data/slot_pattern/"))
parser = ArgumentParser()
parser.add_argument("--model_trigger_pb_dir",
default='bert_model_pb', type=str)
parser.add_argument("--model_role_pb_dir",
default='role_bert_model_pb', type=str)
parser.add_argument("--trigger_predict_res",
default="trigger_result.json", type=str)
parser.add_argument("--submit_result",
default="./data/test2allmerge_modifeddes_prob4null_0404threold_8epoch_type05_verify_kfold_notav_modifyneg_dropout15moretype_roberta_large.json",
type=str)
parser.add_argument("--multi_task_model_pb_dir",
default="multi_task_bert_model_pb", type=str)
parser.add_argument("--event_type_model_path",
default="type_class_bert_model_pb", type=str)
parser.add_argument("--event_cls_model_path",
default="role_verify_cls_bert_model_pb", type=str)
parser.add_argument("--event_verfifyav_model_path",
default="role_verify_avmrc_bert_model_pb", type=str)
parser.add_argument("--gpus", type=str, help="cuda visible devices")
# parser.add_argument("--model_pb_dir", default='base_pb_model_dir', type=str)
args = parser.parse_args()
parse_kfold_verify(args)
| [
"argparse.ArgumentParser",
"codecs.open",
"json.loads",
"configs.event_config.event_config.get",
"data_processing.event_prepare_data.EventRolePrepareMRC",
"json.dumps",
"tensorflow.contrib.predictor.from_saved_model",
"pathlib.Path",
"numpy.mean",
"numpy.array",
"numpy.argwhere",
"os.listdir",... | [((15619, 15663), 'configs.event_config.event_config.get', 'event_config.get', (['args.event_type_model_path'], {}), '(args.event_type_model_path)\n', (15635, 15663), False, 'from configs.event_config import event_config\n'), ((26481, 26497), 'argparse.ArgumentParser', 'ArgumentParser', ([], {}), '()\n', (26495, 26497), False, 'from argparse import ArgumentParser\n'), ((814, 848), 'tensorflow.contrib.predictor.from_saved_model', 'predictor.from_saved_model', (['latest'], {}), '(latest)\n', (840, 848), False, 'from tensorflow.contrib import predictor\n'), ((1100, 1134), 'tensorflow.contrib.predictor.from_saved_model', 'predictor.from_saved_model', (['latest'], {}), '(latest)\n', (1126, 1134), False, 'from tensorflow.contrib import predictor\n'), ((1532, 1601), 'data_processing.event_prepare_data.EventTypeClassificationPrepare', 'EventTypeClassificationPrepare', (['vocab_file_path', '(512)', 'event_type_file'], {}), '(vocab_file_path, 512, event_type_file)\n', (1562, 1601), False, 'from data_processing.event_prepare_data import EventRolePrepareMRC, EventTypeClassificationPrepare\n'), ((2513, 2537), 'numpy.argwhere', 'np.argwhere', (['(label > 0.5)'], {}), '(label > 0.5)\n', (2524, 2537), True, 'import numpy as np\n'), ((4113, 4147), 'tensorflow.contrib.predictor.from_saved_model', 'predictor.from_saved_model', (['latest'], {}), '(latest)\n', (4139, 4147), False, 'from tensorflow.contrib import predictor\n'), ((4783, 4868), 'data_processing.event_prepare_data.EventRolePrepareMRC', 'EventRolePrepareMRC', (['vocab_file_path', '(512)', 'slot_file', 'schema_file', 'query_map_file'], {}), '(vocab_file_path, 512, slot_file, schema_file,\n query_map_file)\n', (4802, 4868), False, 'from data_processing.event_prepare_data import EventRolePrepareMRC, EventTypeClassificationPrepare\n'), ((9206, 9240), 'tensorflow.contrib.predictor.from_saved_model', 'predictor.from_saved_model', (['latest'], {}), '(latest)\n', (9232, 9240), False, 'from tensorflow.contrib import predictor\n'), ((9876, 9961), 'data_processing.event_prepare_data.EventRolePrepareMRC', 'EventRolePrepareMRC', (['vocab_file_path', '(512)', 'slot_file', 'schema_file', 'query_map_file'], {}), '(vocab_file_path, 512, slot_file, schema_file,\n query_map_file)\n', (9895, 9961), False, 'from data_processing.event_prepare_data import EventRolePrepareMRC, EventTypeClassificationPrepare\n'), ((12941, 12977), 'codecs.open', 'codecs.open', (['json_file', '"""r"""', '"""utf-8"""'], {}), "(json_file, 'r', 'utf-8')\n", (12952, 12977), False, 'import codecs\n'), ((13466, 13504), 'codecs.open', 'codecs.open', (['schema_file', '"""r"""', '"""utf-8"""'], {}), "(schema_file, 'r', 'utf-8')\n", (13477, 13504), False, 'import codecs\n'), ((15461, 15489), 'configs.event_config.event_config.get', 'event_config.get', (['"""data_dir"""'], {}), "('data_dir')\n", (15477, 15489), False, 'from configs.event_config import event_config\n'), ((15491, 15531), 'configs.event_config.event_config.get', 'event_config.get', (['"""event_data_file_test"""'], {}), "('event_data_file_test')\n", (15507, 15531), False, 'from configs.event_config import event_config\n'), ((15701, 15729), 'configs.event_config.event_config.get', 'event_config.get', (['"""data_dir"""'], {}), "('data_dir')\n", (15717, 15729), False, 'from configs.event_config import event_config\n'), ((15731, 15763), 'configs.event_config.event_config.get', 'event_config.get', (['"""event_schema"""'], {}), "('event_schema')\n", (15747, 15763), False, 'from configs.event_config import event_config\n'), ((16673, 16716), 'numpy.mean', 'np.mean', (['cur_sample_event_type_prob'], {'axis': '(0)'}), '(cur_sample_event_type_prob, axis=0)\n', (16680, 16716), True, 'import numpy as np\n'), ((16742, 16771), 'numpy.argwhere', 'np.argwhere', (['(avg_result > 0.5)'], {}), '(avg_result > 0.5)\n', (16753, 16771), True, 'import numpy as np\n'), ((26149, 26194), 'codecs.open', 'codecs.open', (['args.submit_result', '"""w"""', '"""utf-8"""'], {}), "(args.submit_result, 'w', 'utf-8')\n", (26160, 26194), False, 'import codecs\n'), ((26434, 26466), 'os.listdir', 'os.listdir', (['"""data/slot_pattern/"""'], {}), "('data/slot_pattern/')\n", (26444, 26466), False, 'import os\n'), ((1838, 1874), 'codecs.open', 'codecs.open', (['test_file', '"""r"""', '"""utf-8"""'], {}), "(test_file, 'r', 'utf-8')\n", (1849, 1874), False, 'import codecs\n'), ((4384, 4423), 'configs.event_config.event_config.get', 'event_config.get', (['"""slot_list_root_path"""'], {}), "('slot_list_root_path')\n", (4400, 4423), False, 'from configs.event_config import event_config\n'), ((4458, 4511), 'configs.event_config.event_config.get', 'event_config.get', (['"""bert_slot_complete_file_name_role"""'], {}), "('bert_slot_complete_file_name_role')\n", (4474, 4511), False, 'from configs.event_config import event_config\n'), ((4548, 4576), 'configs.event_config.event_config.get', 'event_config.get', (['"""data_dir"""'], {}), "('data_dir')\n", (4564, 4576), False, 'from configs.event_config import event_config\n'), ((4591, 4623), 'configs.event_config.event_config.get', 'event_config.get', (['"""event_schema"""'], {}), "('event_schema')\n", (4607, 4623), False, 'from configs.event_config import event_config\n'), ((5005, 5041), 'codecs.open', 'codecs.open', (['test_file', '"""r"""', '"""utf-8"""'], {}), "(test_file, 'r', 'utf-8')\n", (5016, 5041), False, 'import codecs\n'), ((9473, 9512), 'configs.event_config.event_config.get', 'event_config.get', (['"""slot_list_root_path"""'], {}), "('slot_list_root_path')\n", (9489, 9512), False, 'from configs.event_config import event_config\n'), ((9551, 9604), 'configs.event_config.event_config.get', 'event_config.get', (['"""bert_slot_complete_file_name_role"""'], {}), "('bert_slot_complete_file_name_role')\n", (9567, 9604), False, 'from configs.event_config import event_config\n'), ((9641, 9669), 'configs.event_config.event_config.get', 'event_config.get', (['"""data_dir"""'], {}), "('data_dir')\n", (9657, 9669), False, 'from configs.event_config import event_config\n'), ((9688, 9720), 'configs.event_config.event_config.get', 'event_config.get', (['"""event_schema"""'], {}), "('event_schema')\n", (9704, 9720), False, 'from configs.event_config import event_config\n'), ((9760, 9799), 'configs.event_config.event_config.get', 'event_config.get', (['"""slot_list_root_path"""'], {}), "('slot_list_root_path')\n", (9776, 9799), False, 'from configs.event_config import event_config\n'), ((9818, 9852), 'configs.event_config.event_config.get', 'event_config.get', (['"""query_map_file"""'], {}), "('query_map_file')\n", (9834, 9852), False, 'from configs.event_config import event_config\n'), ((10103, 10139), 'codecs.open', 'codecs.open', (['test_file', '"""r"""', '"""utf-8"""'], {}), "(test_file, 'r', 'utf-8')\n", (10114, 10139), False, 'import codecs\n'), ((13101, 13117), 'json.loads', 'json.loads', (['line'], {}), '(line)\n', (13111, 13117), False, 'import json\n'), ((13557, 13573), 'json.loads', 'json.loads', (['line'], {}), '(line)\n', (13567, 13573), False, 'import json\n'), ((26268, 26311), 'json.dumps', 'json.dumps', (['dict_result'], {'ensure_ascii': '(False)'}), '(dict_result, ensure_ascii=False)\n', (26278, 26311), False, 'import json\n'), ((2011, 2027), 'json.loads', 'json.loads', (['line'], {}), '(line)\n', (2021, 2027), False, 'import json\n'), ((5178, 5194), 'json.loads', 'json.loads', (['line'], {}), '(line)\n', (5188, 5194), False, 'import json\n'), ((10276, 10292), 'json.loads', 'json.loads', (['line'], {}), '(line)\n', (10286, 10292), False, 'import json\n'), ((16596, 16634), 'numpy.array', 'np.array', (['cur_sample_event_type_buffer'], {}), '(cur_sample_event_type_buffer)\n', (16604, 16634), True, 'import numpy as np\n'), ((23719, 23754), 'numpy.mean', 'np.mean', (['cur_eav_fold_probs'], {'axis': '(0)'}), '(cur_eav_fold_probs, axis=0)\n', (23726, 23754), True, 'import numpy as np\n'), ((23882, 23922), 'numpy.mean', 'np.mean', (['cur_iav_hasa_fold_probs'], {'axis': '(0)'}), '(cur_iav_hasa_fold_probs, axis=0)\n', (23889, 23922), True, 'import numpy as np\n'), ((24980, 25017), 'numpy.mean', 'np.mean', (['cur_start_fold_probs'], {'axis': '(0)'}), '(cur_start_fold_probs, axis=0)\n', (24987, 25017), True, 'import numpy as np\n'), ((25055, 25090), 'numpy.mean', 'np.mean', (['cur_end_fold_probs'], {'axis': '(0)'}), '(cur_end_fold_probs, axis=0)\n', (25062, 25090), True, 'import numpy as np\n'), ((660, 681), 'pathlib.Path', 'Path', (['self.model_path'], {}), '(self.model_path)\n', (664, 681), False, 'from pathlib import Path\n'), ((951, 967), 'pathlib.Path', 'Path', (['model_path'], {}), '(model_path)\n', (955, 967), False, 'from pathlib import Path\n'), ((3964, 3980), 'pathlib.Path', 'Path', (['model_path'], {}), '(model_path)\n', (3968, 3980), False, 'from pathlib import Path\n'), ((9034, 9050), 'pathlib.Path', 'Path', (['model_path'], {}), '(model_path)\n', (9038, 9050), False, 'from pathlib import Path\n'), ((23640, 23668), 'numpy.array', 'np.array', (['cur_eav_fold_probs'], {}), '(cur_eav_fold_probs)\n', (23648, 23668), True, 'import numpy as np\n'), ((23798, 23831), 'numpy.array', 'np.array', (['cur_iav_hasa_fold_probs'], {}), '(cur_iav_hasa_fold_probs)\n', (23806, 23831), True, 'import numpy as np\n'), ((24784, 24814), 'numpy.array', 'np.array', (['cur_start_fold_probs'], {}), '(cur_start_fold_probs)\n', (24792, 24814), True, 'import numpy as np\n'), ((24884, 24912), 'numpy.array', 'np.array', (['cur_end_fold_probs'], {}), '(cur_end_fold_probs)\n', (24892, 24912), True, 'import numpy as np\n')] |
import argparse
import time
import os
import logging.config
import sys
import math
import numpy as np
import torch
import torch.nn as nn
from jazz_rnn.utils.utils import WeightDrop
from jazz_rnn.utilspy.log import ResultsLog, setup_logging
from jazz_rnn.utilspy.meters import AverageMeter, accuracy
from jazz_rnn.C_reward_induction.RewardMusicCorpusReg import RewardMusicCorpus, create_music_corpus
torch.backends.cudnn.enabled = False
class TrainReward:
def __init__(self, args):
parser = argparse.ArgumentParser(description='PyTorch Jazz RNN/LSTM Model')
model_parser = parser.add_argument_group('Model Parameters')
model_parser.add_argument('--pretrained_path', type=str,
help='path to pre-trained model. used to extract embeddings')
model_parser.add_argument('--pitch_emsize', type=int, default=256,
help='size of pitch embeddings')
model_parser.add_argument('--dur_emsize', type=int, default=256,
help='size of duration embeddings')
model_parser.add_argument('--hidden_size', type=int, default=512,
help='number of hidden units per layer')
model_parser.add_argument('--n_classes', type=int, default=3,
help='size of network output (n_classes)')
model_parser.add_argument('--num_layers', type=int, default=3,
help='number of layers')
model_parser.add_argument('--lr', type=float, default=0.1,
help='initial learning rate')
model_parser.add_argument('--clip', type=float, default=0.25,
help='gradient clipping')
model_parser.add_argument('--wd', type=float, default=1e-6,
help='weight decay')
model_parser.add_argument('--wdrop', type=float, default=0.8,
help='weight drop applied to hidden-to-hidden weights (0 = no dropout)')
model_parser.add_argument('--dropouti', type=float, default=0.0,
help='dropout applied to embedding (0 = no dropout)')
model_parser.add_argument('--dropoute', type=float, default=0.0,
help='dropout applied to whole embeddings (0 = no dropout)')
model_parser.add_argument('--dropouth', type=float, default=0.8,
help='dropout applied to between rnn layers (0 = no dropout)')
model_parser.add_argument('--dropouta', type=float, default=0.8,
help='dropout applied to attention layers (0 = no dropout)')
model_parser.add_argument('--normalize', action='store_true',
help='normalize word_embedding and rnn output')
training_parser = parser.add_argument_group('Training Parameters')
training_parser.add_argument('--data-pkl', type=str,
help='location of the pickled data corpus', required=True)
training_parser.add_argument('--epochs', type=int, default=100,
help='upper epoch limit')
training_parser.add_argument('--batch-size', type=int, default=32, metavar='N',
help='batch size')
training_parser.add_argument('--bptt', type=int, default=16,
help='sequence length')
training_parser.add_argument('--seed', type=int, default=1111,
help='random seed')
training_parser.add_argument('--no-cuda', action='store_true', default=False,
help='don''t use CUDA')
training_parser.add_argument('--all', action='store_true', default=False,
help='train using train+test data')
training_parser.add_argument('--test', action='store_true', default=False,
help='perform test only')
training_parser.add_argument('--resume', type=str, default='',
help='pkl path to load')
training_parser.add_argument('--train-chord-root', action='store_true', default=False,
help='train model to play only chord root')
logging_parser = parser.add_argument_group('Logging Parameters')
logging_parser.add_argument('--log-interval', type=int, default=100, metavar='N',
help='report interval')
logging_parser.add_argument('--save', type=str,
default='model_user' + time.strftime("%y_%m_%d"),
help='model name')
logging_parser.add_argument('--save-dir', type=str, default='results/reward_training_results',
help='path to save the final model')
self.args = parser.parse_args(args)
self.args.cuda = not self.args.no_cuda
# Set the random seed manually for reproducibility.
torch.manual_seed(self.args.seed)
if torch.cuda.is_available():
if self.args.no_cuda:
logging.info("WARNING: You have a CUDA device, so you should probably run without --no-cuda")
else:
torch.cuda.manual_seed_all(self.args.seed)
np.random.seed(self.args.seed)
self.save_path = os.path.join(self.args.save_dir, self.args.save)
if not os.path.exists(self.save_path):
os.makedirs(self.save_path)
setup_logging(os.path.join(self.save_path, 'log.txt'))
results_file = os.path.join(self.save_path, 'results.%s')
self.results = ResultsLog(results_file % 'csv', results_file % 'html', epochs=self.args.epochs)
logging.debug("run arguments: %s", self.args)
per_class_accuracies = ['acc_{}'.format(i) for i in range(self.args.n_classes)]
self.meters_list = ['loss', 'acc', *per_class_accuracies
]
###############################################################################
# Load data
###############################################################################
self.all_data_list, self.idxs_kf, self.converter, _ = create_music_corpus(pkl_path=self.args.data_pkl,
all=self.args.all)
os.system('cp ' + os.path.join(self.args.data_pkl, '*.pkl') + ' ' + self.save_path)
def evaluate(self, val_set, epoch):
losses = AverageMeter()
meters_avg = {k: AverageMeter() for k in self.meters_list}
val_batch_size = self.args.batch_size
# Turn on evaluation mode which disables dropout
self.model.eval()
hidden = self.model.init_hidden(val_batch_size)
num_batches = val_set.get_num_batches()
y_true = []
y_pred = []
with torch.no_grad():
for i in range(num_batches):
input, target = val_set.get_batch(i)
target = target.view(val_batch_size, -1)
output_reward, hidden = self.model.forward_reward(input, hidden)
loss, meters = self.get_music_loss(output_reward, target)
losses.update(float(loss), self.args.bptt)
for k, v in meters.items():
meters_avg[k].update(float(meters[k]), self.args.bptt)
y_true.append(target.view(1, val_set.batch_size).mode(dim=0)[0].cpu().numpy())
y_pred.append(output_reward.argmax(dim=1).cpu().numpy())
for k in meters_avg:
meters_avg[k] = meters_avg[k].avg
return losses.avg, meters_avg
def train(self, train_set, epoch):
# Turn on training mode which enables dropout.
self.model.train()
losses = AverageMeter()
errors_avg = {k: AverageMeter() for k in self.meters_list}
errors_logging = {k: AverageMeter() for k in self.meters_list}
logging_loss = AverageMeter()
start_time = time.time()
train_set.balance_dataset()
num_batches = train_set.get_num_batches()
train_set.permute_order()
indices = np.random.permutation(np.arange(num_batches))
for i in range(len(indices)):
input, target = train_set.get_batch(i)
target = target.view(self.args.batch_size, -1)
hidden = self.model.init_hidden(self.args.batch_size)
self.model.zero_grad()
output_reward, hidden = self.model.forward_reward(input, hidden)
loss, errors = self.get_music_loss(output_reward, target)
loss.backward()
# `clip_grad_norm` helps prevent the exploding gradient problem in RNNs / LSTMs.
grad_norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(), self.args.clip)
self.optimizer.step()
losses.update(float(loss), target.size(0))
logging_loss.update(float(loss), target.size(0))
for k, v in errors.items():
errors_avg[k].update(float(errors[k]), self.args.bptt)
errors_logging[k].update(float(errors[k]), self.args.bptt)
if i % self.args.log_interval == 0 and i > 0:
cur_loss = logging_loss.avg
elapsed = time.time() - start_time
error_str = ' | '.join(['{}: {:5.2f}'.format(k, v.avg) for k, v in errors_logging.items()])
logging.info('| epoch {:3d} | {:5d}/{:5d} batches | ms/batch {:5.2f} | '
'loss {:5.2f} | ppl {:8.2f} | grad_norm {:5.2f} | {}'
.format(epoch, i, num_batches,
elapsed * 1000 / self.args.log_interval, cur_loss, math.exp(cur_loss), grad_norm,
error_str))
logging_loss.reset()
for k, v in errors.items():
errors_logging[k].reset()
start_time = time.time()
for k in errors_avg:
errors_avg[k] = errors_avg[k].avg
return losses.avg, errors_avg
TOTAL_NOTES_IN_MIDI = 128
N_NOTES_IN_OCTAVE = 12
RESIDUAL = TOTAL_NOTES_IN_MIDI % N_NOTES_IN_OCTAVE
def get_music_loss(self, out_logits, target_var):
loss = self.criterion(torch.tanh(out_logits), target_var)
loss = torch.mean(loss)
try:
if len(torch.unique(target_var)) < 3:
raise IndexError('can''t calculate per class acc')
except IndexError:
return loss, {}
acc = accuracy(torch.sign(out_logits), torch.sign(target_var.contiguous()))[0]
per_class_accuracies = {}
meters = {'loss': loss, 'acc': acc, **per_class_accuracies}
return loss, meters
def main(self):
for self.fold_idx, (train_index, val_index) in enumerate(self.idxs_kf):
train_data_fold = np.array(self.all_data_list)[train_index]
logging.info('Training set statistics: ')
logging.info(np.histogram(np.concatenate(train_data_fold, axis=0)[:, -1], bins=3)[0])
self.train_corpus = RewardMusicCorpus(train_data_fold, self.converter, cuda=self.args.cuda,
batch_size=self.args.batch_size, balance=True,
n_classes=self.args.n_classes, seq_len=self.args.bptt)
if not self.args.all:
val_data_fold = np.array(self.all_data_list)[val_index]
logging.info('Validation set statistics: ')
logging.info(np.histogram(np.concatenate(val_data_fold, axis=0)[:, -1], bins=3)[0])
self.val_corpus = RewardMusicCorpus(val_data_fold, self.converter, cuda=self.args.cuda,
batch_size=self.args.batch_size, balance=False,
n_classes=self.args.n_classes, seq_len=self.args.bptt)
self.checkpoint_path = os.path.join(self.save_path, self.args.save + '_f{}.pt'.format(self.fold_idx))
###############################################################################
# Build the model
###############################################################################
if self.args.resume:
with open(self.args.resume, 'rb') as f:
self.model = torch.load(f)
if self.args.pretrained_path:
with open(self.args.pretrained_path, 'rb') as f:
self.model = torch.load(f)
# added for backward compatibility
self.model.normalize = self.args.normalize
for p in [self.model.encode_pitch, self.model.encode_duration, self.model.encode_offset,
self.model.decode_pitch, self.model.decode_duration]:
p.requires_grad = False
if isinstance(self.model.rnns[0], nn.LSTM) and self.args.wdrop != 0:
self.model.rnns = nn.ModuleList(
[WeightDrop(rnn, ['weight_hh_l0'], dropout=self.args.wdrop) for rnn in self.model.rnns])
self.model.dropoute = self.args.dropoute
self.model.dropouth = self.args.dropouth
self.model.dropouti = self.args.dropouti
self.model.dropouta = nn.Dropout(self.args.dropouta)
self.model.wdrop = self.args.wdrop
self.model.reward_attention = nn.Linear(1552 + 512, 1)
self.model.reward_linear = nn.Linear(512, 1)
if not self.args.no_cuda:
self.model.cuda()
num_params = 0
for p in self.model.parameters():
num_params += p.numel()
logging.info('num_params: {}'.format(num_params))
self.optimizer = torch.optim.SGD(filter(lambda p: p.requires_grad, self.model.parameters()),
lr=self.args.lr,
momentum=0.9, weight_decay=self.args.wd, nesterov=True)
self.scheduler = torch.optim.lr_scheduler.MultiStepLR(self.optimizer, milestones=[100, 150, 300, 400],
gamma=0.5)
self.criterion = nn.MSELoss()
LINE_LENGTH = 160
epoch_start_time = time.time()
if not self.args.all:
val_loss, val_errors = self.evaluate(self.val_corpus, 0)
self.results.add(epoch=0,
**{'f{}_val_{}'.format(self.fold_idx, k): v for k, v in val_errors.items()})
logging.info('-' * LINE_LENGTH)
logging.info('| end of epoch {:3d} | time: {:5.2f}s | valid loss {:5.2f} | '
'valid ppl {:8.2f}'.format(0, (time.time() - epoch_start_time),
val_loss, math.exp(val_loss)))
logging.info('-' * LINE_LENGTH)
# Loop over epochs.
best_val_error = None
# At any point you can hit Ctrl + C to break out of training early.
if self.args.test:
val_loss, val_errors = self.evaluate(self.val_corpus, 0)
logging.info('-' * LINE_LENGTH)
error_str = ' | '.join(['valid_{}: {:5.2f}'.format(k, v) for k, v in val_errors.items()])
logging.info('| end of epoch {:3d} | time: {:5.2f}s | valid loss {:5.2f} | '
'valid ppl {:8.2f} | {}'
.format(0, (time.time() - epoch_start_time),
val_loss, math.exp(val_loss), 0, error_str))
logging.info('-' * LINE_LENGTH)
return val_errors['acc']
try:
for epoch in range(1, self.args.epochs + 1):
epoch_start_time = time.time()
train_loss, train_errors = self.train(self.train_corpus, epoch)
if not self.args.all:
val_loss, val_errors = self.evaluate(self.val_corpus, epoch)
logging.info('-' * LINE_LENGTH)
error_str = ' | '.join(['valid_{}: {:5.2f}'.format(k, v) for k, v in val_errors.items()])
logging.info('| end of epoch {:3d} | time: {:5.2f}s | valid loss {:5.2f} | '
'valid ppl {:8.2f} | {}'
.format(epoch, (time.time() - epoch_start_time),
val_loss, math.exp(val_loss), error_str))
logging.info('-' * LINE_LENGTH)
# Save the model if the validation loss is the best we've seen so far.
avg_val_error = val_errors['acc']
if not best_val_error or avg_val_error < best_val_error:
with open(self.checkpoint_path, 'wb') as f:
torch.save(self.model, f)
best_val_error = avg_val_error
self.results.add(epoch=epoch,
**{'f{}_train_{}'.format(self.fold_idx, k): v for k, v in
train_errors.items()},
**{'f{}_val_{}'.format(self.fold_idx, k): v for k, v in val_errors.items()})
for k in train_errors:
self.results.plot(x='epoch', y=['train_{}'.format(k), 'val_{}'.format(k)],
title=k, ylabel=k, avg=True)
self.results.save()
if (self.args.save != '' and (epoch % 10) == 0) or self.args.all:
with open(self.checkpoint_path, 'wb') as f:
torch.save(self.model, f)
self.scheduler.step()
logging.info('=' * LINE_LENGTH)
if self.args.save != '' or self.args.all:
with open(self.checkpoint_path, 'wb') as f:
torch.save(self.model, f)
except KeyboardInterrupt:
logging.info('-' * LINE_LENGTH)
logging.info('Exiting from training early')
logging.info('=' * LINE_LENGTH)
if self.args.save != '' or self.args.all:
self.checkpoint_path = os.path.join(self.save_path, self.args.save + '_early_stop' + '.pt')
with open(self.checkpoint_path, 'wb') as f:
torch.save(self.model, f)
if __name__ == '__main__':
TrainReward(sys.argv[1:]).main()
| [
"torch.nn.Dropout",
"numpy.random.seed",
"argparse.ArgumentParser",
"time.strftime",
"numpy.arange",
"torch.no_grad",
"os.path.join",
"torch.nn.MSELoss",
"jazz_rnn.utilspy.meters.AverageMeter",
"torch.load",
"os.path.exists",
"torch.sign",
"torch.nn.Linear",
"torch.mean",
"torch.unique",... | [((507, 573), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""PyTorch Jazz RNN/LSTM Model"""'}), "(description='PyTorch Jazz RNN/LSTM Model')\n", (530, 573), False, 'import argparse\n'), ((5180, 5213), 'torch.manual_seed', 'torch.manual_seed', (['self.args.seed'], {}), '(self.args.seed)\n', (5197, 5213), False, 'import torch\n'), ((5225, 5250), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (5248, 5250), False, 'import torch\n'), ((5481, 5511), 'numpy.random.seed', 'np.random.seed', (['self.args.seed'], {}), '(self.args.seed)\n', (5495, 5511), True, 'import numpy as np\n'), ((5538, 5586), 'os.path.join', 'os.path.join', (['self.args.save_dir', 'self.args.save'], {}), '(self.args.save_dir, self.args.save)\n', (5550, 5586), False, 'import os\n'), ((5760, 5802), 'os.path.join', 'os.path.join', (['self.save_path', '"""results.%s"""'], {}), "(self.save_path, 'results.%s')\n", (5772, 5802), False, 'import os\n'), ((5826, 5911), 'jazz_rnn.utilspy.log.ResultsLog', 'ResultsLog', (["(results_file % 'csv')", "(results_file % 'html')"], {'epochs': 'self.args.epochs'}), "(results_file % 'csv', results_file % 'html', epochs=self.args.epochs\n )\n", (5836, 5911), False, 'from jazz_rnn.utilspy.log import ResultsLog, setup_logging\n'), ((6405, 6472), 'jazz_rnn.C_reward_induction.RewardMusicCorpusReg.create_music_corpus', 'create_music_corpus', ([], {'pkl_path': 'self.args.data_pkl', 'all': 'self.args.all'}), '(pkl_path=self.args.data_pkl, all=self.args.all)\n', (6424, 6472), False, 'from jazz_rnn.C_reward_induction.RewardMusicCorpusReg import RewardMusicCorpus, create_music_corpus\n'), ((6706, 6720), 'jazz_rnn.utilspy.meters.AverageMeter', 'AverageMeter', ([], {}), '()\n', (6718, 6720), False, 'from jazz_rnn.utilspy.meters import AverageMeter, accuracy\n'), ((8003, 8017), 'jazz_rnn.utilspy.meters.AverageMeter', 'AverageMeter', ([], {}), '()\n', (8015, 8017), False, 'from jazz_rnn.utilspy.meters import AverageMeter, accuracy\n'), ((8179, 8193), 'jazz_rnn.utilspy.meters.AverageMeter', 'AverageMeter', ([], {}), '()\n', (8191, 8193), False, 'from jazz_rnn.utilspy.meters import AverageMeter, accuracy\n'), ((8215, 8226), 'time.time', 'time.time', ([], {}), '()\n', (8224, 8226), False, 'import time\n'), ((10559, 10575), 'torch.mean', 'torch.mean', (['loss'], {}), '(loss)\n', (10569, 10575), False, 'import torch\n'), ((5602, 5632), 'os.path.exists', 'os.path.exists', (['self.save_path'], {}), '(self.save_path)\n', (5616, 5632), False, 'import os\n'), ((5646, 5673), 'os.makedirs', 'os.makedirs', (['self.save_path'], {}), '(self.save_path)\n', (5657, 5673), False, 'import os\n'), ((5696, 5735), 'os.path.join', 'os.path.join', (['self.save_path', '"""log.txt"""'], {}), "(self.save_path, 'log.txt')\n", (5708, 5735), False, 'import os\n'), ((6746, 6760), 'jazz_rnn.utilspy.meters.AverageMeter', 'AverageMeter', ([], {}), '()\n', (6758, 6760), False, 'from jazz_rnn.utilspy.meters import AverageMeter, accuracy\n'), ((7076, 7091), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (7089, 7091), False, 'import torch\n'), ((8043, 8057), 'jazz_rnn.utilspy.meters.AverageMeter', 'AverageMeter', ([], {}), '()\n', (8055, 8057), False, 'from jazz_rnn.utilspy.meters import AverageMeter, accuracy\n'), ((8114, 8128), 'jazz_rnn.utilspy.meters.AverageMeter', 'AverageMeter', ([], {}), '()\n', (8126, 8128), False, 'from jazz_rnn.utilspy.meters import AverageMeter, accuracy\n'), ((8387, 8409), 'numpy.arange', 'np.arange', (['num_batches'], {}), '(num_batches)\n', (8396, 8409), True, 'import numpy as np\n'), ((10508, 10530), 'torch.tanh', 'torch.tanh', (['out_logits'], {}), '(out_logits)\n', (10518, 10530), False, 'import torch\n'), ((11340, 11522), 'jazz_rnn.C_reward_induction.RewardMusicCorpusReg.RewardMusicCorpus', 'RewardMusicCorpus', (['train_data_fold', 'self.converter'], {'cuda': 'self.args.cuda', 'batch_size': 'self.args.batch_size', 'balance': '(True)', 'n_classes': 'self.args.n_classes', 'seq_len': 'self.args.bptt'}), '(train_data_fold, self.converter, cuda=self.args.cuda,\n batch_size=self.args.batch_size, balance=True, n_classes=self.args.\n n_classes, seq_len=self.args.bptt)\n', (11357, 11522), False, 'from jazz_rnn.C_reward_induction.RewardMusicCorpusReg import RewardMusicCorpus, create_music_corpus\n'), ((13581, 13611), 'torch.nn.Dropout', 'nn.Dropout', (['self.args.dropouta'], {}), '(self.args.dropouta)\n', (13591, 13611), True, 'import torch.nn as nn\n'), ((13702, 13726), 'torch.nn.Linear', 'nn.Linear', (['(1552 + 512)', '(1)'], {}), '(1552 + 512, 1)\n', (13711, 13726), True, 'import torch.nn as nn\n'), ((13766, 13783), 'torch.nn.Linear', 'nn.Linear', (['(512)', '(1)'], {}), '(512, 1)\n', (13775, 13783), True, 'import torch.nn as nn\n'), ((14331, 14432), 'torch.optim.lr_scheduler.MultiStepLR', 'torch.optim.lr_scheduler.MultiStepLR', (['self.optimizer'], {'milestones': '[100, 150, 300, 400]', 'gamma': '(0.5)'}), '(self.optimizer, milestones=[100, 150, \n 300, 400], gamma=0.5)\n', (14367, 14432), False, 'import torch\n'), ((14524, 14536), 'torch.nn.MSELoss', 'nn.MSELoss', ([], {}), '()\n', (14534, 14536), True, 'import torch.nn as nn\n'), ((14600, 14611), 'time.time', 'time.time', ([], {}), '()\n', (14609, 14611), False, 'import time\n'), ((5430, 5472), 'torch.cuda.manual_seed_all', 'torch.cuda.manual_seed_all', (['self.args.seed'], {}), '(self.args.seed)\n', (5456, 5472), False, 'import torch\n'), ((10184, 10195), 'time.time', 'time.time', ([], {}), '()\n', (10193, 10195), False, 'import time\n'), ((10786, 10808), 'torch.sign', 'torch.sign', (['out_logits'], {}), '(out_logits)\n', (10796, 10808), False, 'import torch\n'), ((11113, 11141), 'numpy.array', 'np.array', (['self.all_data_list'], {}), '(self.all_data_list)\n', (11121, 11141), True, 'import numpy as np\n'), ((11916, 12097), 'jazz_rnn.C_reward_induction.RewardMusicCorpusReg.RewardMusicCorpus', 'RewardMusicCorpus', (['val_data_fold', 'self.converter'], {'cuda': 'self.args.cuda', 'batch_size': 'self.args.batch_size', 'balance': '(False)', 'n_classes': 'self.args.n_classes', 'seq_len': 'self.args.bptt'}), '(val_data_fold, self.converter, cuda=self.args.cuda,\n batch_size=self.args.batch_size, balance=False, n_classes=self.args.\n n_classes, seq_len=self.args.bptt)\n', (11933, 12097), False, 'from jazz_rnn.C_reward_induction.RewardMusicCorpusReg import RewardMusicCorpus, create_music_corpus\n'), ((4762, 4787), 'time.strftime', 'time.strftime', (['"""%y_%m_%d"""'], {}), "('%y_%m_%d')\n", (4775, 4787), False, 'import time\n'), ((9494, 9505), 'time.time', 'time.time', ([], {}), '()\n', (9503, 9505), False, 'import time\n'), ((10609, 10633), 'torch.unique', 'torch.unique', (['target_var'], {}), '(target_var)\n', (10621, 10633), False, 'import torch\n'), ((11681, 11709), 'numpy.array', 'np.array', (['self.all_data_list'], {}), '(self.all_data_list)\n', (11689, 11709), True, 'import numpy as np\n'), ((12645, 12658), 'torch.load', 'torch.load', (['f'], {}), '(f)\n', (12655, 12658), False, 'import torch\n'), ((12799, 12812), 'torch.load', 'torch.load', (['f'], {}), '(f)\n', (12809, 12812), False, 'import torch\n'), ((16154, 16165), 'time.time', 'time.time', ([], {}), '()\n', (16163, 16165), False, 'import time\n'), ((6582, 6623), 'os.path.join', 'os.path.join', (['self.args.data_pkl', '"""*.pkl"""'], {}), "(self.args.data_pkl, '*.pkl')\n", (6594, 6623), False, 'import os\n'), ((9948, 9966), 'math.exp', 'math.exp', (['cur_loss'], {}), '(cur_loss)\n', (9956, 9966), False, 'import math\n'), ((13300, 13358), 'jazz_rnn.utils.utils.WeightDrop', 'WeightDrop', (['rnn', "['weight_hh_l0']"], {'dropout': 'self.args.wdrop'}), "(rnn, ['weight_hh_l0'], dropout=self.args.wdrop)\n", (13310, 13358), False, 'from jazz_rnn.utils.utils import WeightDrop\n'), ((15171, 15189), 'math.exp', 'math.exp', (['val_loss'], {}), '(val_loss)\n', (15179, 15189), False, 'import math\n'), ((15913, 15931), 'math.exp', 'math.exp', (['val_loss'], {}), '(val_loss)\n', (15921, 15931), False, 'import math\n'), ((18435, 18460), 'torch.save', 'torch.save', (['self.model', 'f'], {}), '(self.model, f)\n', (18445, 18460), False, 'import torch\n'), ((18758, 18826), 'os.path.join', 'os.path.join', (['self.save_path', "(self.args.save + '_early_stop' + '.pt')"], {}), "(self.save_path, self.args.save + '_early_stop' + '.pt')\n", (18770, 18826), False, 'import os\n'), ((11247, 11286), 'numpy.concatenate', 'np.concatenate', (['train_data_fold'], {'axis': '(0)'}), '(train_data_fold, axis=0)\n', (11261, 11286), True, 'import numpy as np\n'), ((15072, 15083), 'time.time', 'time.time', ([], {}), '()\n', (15081, 15083), False, 'import time\n'), ((15833, 15844), 'time.time', 'time.time', ([], {}), '()\n', (15842, 15844), False, 'import time\n'), ((18915, 18940), 'torch.save', 'torch.save', (['self.model', 'f'], {}), '(self.model, f)\n', (18925, 18940), False, 'import torch\n'), ((11823, 11860), 'numpy.concatenate', 'np.concatenate', (['val_data_fold'], {'axis': '(0)'}), '(val_data_fold, axis=0)\n', (11837, 11860), True, 'import numpy as np\n'), ((16852, 16870), 'math.exp', 'math.exp', (['val_loss'], {}), '(val_loss)\n', (16860, 16870), False, 'import math\n'), ((17278, 17303), 'torch.save', 'torch.save', (['self.model', 'f'], {}), '(self.model, f)\n', (17288, 17303), False, 'import torch\n'), ((18171, 18196), 'torch.save', 'torch.save', (['self.model', 'f'], {}), '(self.model, f)\n', (18181, 18196), False, 'import torch\n'), ((16764, 16775), 'time.time', 'time.time', ([], {}), '()\n', (16773, 16775), False, 'import time\n')] |
import cv2
import numpy as np
from .grasp_learner import grasp_obj
from .grasp_predictor import Predictors
from .shake_learner import shake_obj
from .force_filter_learner import force_filter_obj
from .five_filter_learner import five_filter_obj
from .shake_predictor import Predictors as Adv_Predictors
from .grasp_learner_with_filter import grasp_obj2
import time
import os
import ipdb
import gc
from grasp.utils.mjcf_utils import xml_path_completion
from grasp.utils.mjcf_utils import image_path_completion
from grasp.utils.mjcf_utils import root_path_completion
from grasp.utils.mjcf_utils import root_path_completion2
from grasp.utils.mjcf_utils import predict_image_path_completion
from mujoco_py import MjSim, MjViewer, load_model_from_path, functions
from mujoco_py.generated import const
from termcolor import colored
def drawRectangle(I, h, w, t, gsize=300, pred=None):
I_temp = I
grasp_l = gsize/2.5
grasp_w = gsize/5.0
grasp_angle = t*(np.pi/18)-np.pi/2
points = np.array([[-grasp_l, -grasp_w],
[grasp_l, -grasp_w],
[grasp_l, grasp_w],
[-grasp_l, grasp_w]])
R = np.array([[np.cos(grasp_angle), -np.sin(grasp_angle)],
[np.sin(grasp_angle), np.cos(grasp_angle)]])
rot_points = np.dot(R, points.transpose()).transpose()
im_points = rot_points + np.array([w, h])
# print('rec points: ',im_points)
min_x = min(im_points[0][0], im_points[2][0], im_points[2][0], im_points[3][0])
max_x = max(im_points[0][0], im_points[1][0], im_points[2][0], im_points[3][0])
min_y = min(im_points[0][1], im_points[1][1], im_points[2][1], im_points[3][1])
max_y = max(im_points[0][1], im_points[1][1], im_points[2][1], im_points[3][1])
center_pt = (int((min_x + max_x) / 2), int((min_y + max_y) / 2))
#print('center points: ', center_pt)
cv2.circle(I_temp, center_pt, 2, (255, 0, 0), -1)
cv2.line(I_temp, tuple(im_points[0].astype(int)), tuple(im_points[1].astype(int)), color=(0, 255, 0), thickness=5)
cv2.line(I_temp, tuple(im_points[1].astype(int)), tuple(im_points[2].astype(int)), color=(0, 0, 255), thickness=5)
cv2.line(I_temp, tuple(im_points[2].astype(int)), tuple(im_points[3].astype(int)), color=(0, 255, 0), thickness=5)
cv2.line(I_temp, tuple(im_points[3].astype(int)), tuple(im_points[0].astype(int)), color=(0, 0, 255), thickness=5)
font = cv2.FONT_HERSHEY_SIMPLEX
bottomLeftCornerOfText = center_pt
fontScale = 0.5
fontColor = (255, 0, 0)
lineType = 2
cv2.putText(I_temp, str(pred),
bottomLeftCornerOfText,
font,
fontScale,
fontColor,
lineType)
return (I_temp, center_pt, R, grasp_angle)
def drawRectangle_spot(gripper_coords, I, h, w, t, gsize=300, pred=None):
I_temp = I
grasp_l = gsize/2.5
grasp_w = gsize/5.0
points = np.array([[-grasp_l, -grasp_w],
[grasp_l, -grasp_w],
[grasp_l, grasp_w],
[-grasp_l, grasp_w]])
grasp_angles = t*(np.pi/18)-np.pi/2
R = []
for e in grasp_angles:
R.append(np.array([[np.cos(e), -np.sin(e)], [np.sin(e), np.cos(e)]]))
rot_points = []
for e in R:
rot_points.append(np.dot(e, points.transpose()).transpose())
for i, e in enumerate(rot_points):
im_points = e + np.array([h[i],w[i]])
# print('rec points: ',im_points)
min_x = min(im_points[0][0], im_points[2][0], im_points[2][0], im_points[3][0])
max_x = max(im_points[0][0], im_points[1][0], im_points[2][0], im_points[3][0])
min_y = min(im_points[0][1], im_points[1][1], im_points[2][1], im_points[3][1])
max_y = max(im_points[0][1], im_points[1][1], im_points[2][1], im_points[3][1])
center_pt = (int((min_x + max_x) / 2), int((min_y + max_y) / 2))
# print('center points: ', center_pt)
cv2.circle(I_temp, center_pt, 3, (255, 0, 0), -1)
cv2.line(I_temp, tuple(gripper_coords[0]), tuple(gripper_coords[1]), color=(0, 0, 255),
thickness=4)
cv2.line(I_temp, tuple(gripper_coords[2]), tuple(gripper_coords[3]), color=(0, 0, 255),
thickness=4)
return I_temp
def drawRectangle_spot_on_centre(adv_action, gripper_coords, obj_name,
timestep, log_dir, I, C, pre_reward, post_reward, method_opt=0, gsize=300):
I_temp = I
is_adv = False
adv_count = 0
col_count = 0
differ = 0
grasp_l = gsize/2.5
grasp_w = gsize/5.0
points = np.array([[-grasp_l, -grasp_w],
[grasp_l, -grasp_w],
[grasp_l, grasp_w],
[-grasp_l, grasp_w]])
for i, e in enumerate(C):
center_pt = e
grasp_angles = pre_reward[i][1]
R = np.array([[np.cos(grasp_angles), -np.sin(grasp_angles)], [np.sin(grasp_angles), np.cos(grasp_angles)]])
rot_point = np.dot(R, points.transpose()).transpose()
im_points = rot_point + np.array([center_pt[1], center_pt[0]]) # center_pt
min_x = min(im_points[0][0], im_points[2][0], im_points[2][0], im_points[3][0])
max_x = max(im_points[0][0], im_points[1][0], im_points[2][0], im_points[3][0])
min_y = min(im_points[0][1], im_points[1][1], im_points[2][1], im_points[3][1])
max_y = max(im_points[0][1], im_points[1][1], im_points[2][1], im_points[3][1])
center_pt = (int((min_x + max_x) / 2), int((min_y + max_y) / 2))
differ_spot = post_reward[i][0] - pre_reward[i][0] # pre_reward - post_reward
color_tutple = None
print(colored("differ!:{}".format(differ_spot), "yellow"))
if differ_spot > 0:#0.0005:
col_count += 1
#print(colored("col_force", "yellow"))
color = int(9000 * differ_spot)
if color >= 255:
color = 255
color_tutple = (color, 0, 0)
else:
adv_count += 1
#print(colored("adv_force", "yellow"))
color = int(-9000 * differ_spot)
if color >= 255:
color = 255
color_tutple = (0, 0, color)
cv2.circle(I_temp, center_pt, 3, color_tutple, -1)
differ += post_reward[i][0] - pre_reward[i][0] # pre_reward - post_reward
if method_opt == 0:
if col_count <= adv_count:
is_adv = True
else:
if differ <= 0:
is_adv = True
cv2.line(I_temp, tuple(gripper_coords[0]), tuple(gripper_coords[1]), color=(0, 0, 255),
thickness=4)
cv2.line(I_temp, tuple(gripper_coords[2]), tuple(gripper_coords[3]), color=(0, 0, 255),
thickness=4)
font = cv2.FONT_HERSHEY_SIMPLEX
bottomLeftCornerOfText = (30, 30)
fontScale = 0.6
lineType = 2
force_direction = None
if adv_action == 1:
force_direction = " <-Left"
elif adv_action == 2:
force_direction = " V Down"
elif adv_action == 3:
force_direction = " Right->"
elif adv_action == 4:
force_direction = " ^ Up"
print(colored(force_direction, "yellow"))
if is_adv:
is_adv_string = "Adv "
fontColor = (0, 0, 255)
else:
is_adv_string = "Col "
fontColor = (255, 0, 0)
if method_opt == 0:
is_adv_string = is_adv_string + "adv_count: {}".format(adv_count) + " col_count: {}".format(col_count)
elif method_opt == 1:
is_adv_string = is_adv_string + "adv_count: {}".format(adv_count) + " col_count: {}".format(col_count) + \
"differ sum: {}".format(differ)
is_adv_string = is_adv_string + force_direction
cv2.putText(I_temp, is_adv_string,
bottomLeftCornerOfText,
font,
fontScale,
fontColor,
lineType)
trial_types = "2Perturbed"
save_name = predict_image_path_completion(obj_name + '_predict_{}_{}.jpg'.format(timestep, trial_types),
log_dir)
try:
cv2.imwrite(save_name, I_temp)
print('prediction image {} saved'.format(save_name))
except:
print('error saving image: {}'.format(save_name))
return is_adv
# if train: root_path_completion
# if inference: root_path_completion2
def init_detector(num_samples, use_pro_new='False', use_pro_name='', batch_size=1, gpu_id=0, lr_rate=0.01, test_user=False):
# init
use_pro_name = 'bonus-test6-350-base' #198'
if test_user:
if use_pro_new and os.path.exists(root_path_completion2('predict_module/models/pro_model{}.index'.format(use_pro_name))):
model_path = root_path_completion2('predict_module/models/pro_model{}'.format(use_pro_name))
else:
model_path = root_path_completion2('predict_module/models/Grasp_model')
else:
if use_pro_new and os.path.exists(root_path_completion('predict_module/models/pro_model{}.index'.format(use_pro_name))):
model_path = root_path_completion('predict_module/models/pro_model{}'.format(use_pro_name))
else:
model_path = root_path_completion('predict_module/models/Grasp_model')
#model_path = '/home/icaros/grasp/grasp/predict_module/models/pro_model' + use_pro_name
print('Loading grasp model')
print('model-path: ', model_path)
G = grasp_obj(model_path, gpu_id, num_samples)
G.BATCH_SIZE = batch_size
G.test_init(lr_rate)
return G
def init_detector_with_filter(num_samples,use_pro_new='False', use_pro_name='', batch_size=1, gpu_id=0, lr_rate=0.01, test_user= False):
# init
use_pro_name = 'bonus-test6-350-base' #198'
if test_user:
if use_pro_new and os.path.exists(root_path_completion2('predict_module/models/pro_model{}.index'.format(use_pro_name))):
model_path = root_path_completion2('predict_module/models/pro_model{}'.format(use_pro_name))
else:
model_path = root_path_completion2('predict_module/models/filter/Grasp_model')
else:
if use_pro_new and os.path.exists(root_path_completion('predict_module/models/pro_model{}.index'.format(use_pro_name))):
model_path = root_path_completion('predict_module/models/pro_model{}'.format(use_pro_name))
else:
model_path = root_path_completion('predict_module/models/filter/Grasp_model')
#model_path = '/home/icaros/grasp/grasp/predict_module/models/pro_model' + use_pro_name
print('Loading grasp model')
print('model-path: ', model_path)
G = grasp_obj2(model_path, gpu_id, num_samples)
G.BATCH_SIZE = batch_size
G.test_init(lr_rate)
return G
def init_detector_test(num_samples, use_pro_new='False', use_pro_name='', batch_size=1, gpu_id=0, lr_rate=0.01,
test_user=False, option=0):
# init
use_pro_name = 'bonus-test6-100-' + str(option) #343'
#'bonus-test6-198-force-filter'
if test_user:
if use_pro_new and os.path.exists(
root_path_completion2('predict_module/models/pro_model{}.index'.format(use_pro_name))):
model_path = root_path_completion2('predict_module/models/pro_model{}'.format(use_pro_name))
else:
model_path = root_path_completion2('predict_module/models/Grasp_model')
else:
if use_pro_new and os.path.exists(
root_path_completion('predict_module/models/pro_model{}.index'.format(use_pro_name))):
model_path = root_path_completion('predict_module/models/pro_model{}'.format(use_pro_name))
else:
model_path = root_path_completion('predict_module/models/Grasp_model')
model_path = '/home/icaros/grasp/grasp/predict_module/models/pro_model' + use_pro_name
print('Loading grasp model')
print('model-path: ', model_path)
G = grasp_obj(model_path, gpu_id, num_samples)
G.BATCH_SIZE = batch_size
G.test_init(lr_rate)
return G
def init_detector_test_use_filter(num_samples, use_pro_new='False', use_pro_name='', batch_size=1, gpu_id=0, lr_rate=0.01,
test_user=False, option = 0):
# init
use_pro_name = 'bonus-test6-100-force-filter-' + str(option) #198 #96 #95 #---
use_pro_new = False
#'bonus-test6-198-force-filter'
if test_user:
if use_pro_new and os.path.exists(
root_path_completion2('predict_module/models/pro_model{}.index'.format(use_pro_name))):
model_path = root_path_completion2('predict_module/models/pro_model{}'.format(use_pro_name))
else:
model_path = root_path_completion2('predict_module/models/Grasp_model')
else:
if use_pro_new and os.path.exists(
root_path_completion('predict_module/models/pro_model{}.index'.format(use_pro_name))):
model_path = root_path_completion('predict_module/models/pro_model{}'.format(use_pro_name))
else:
model_path = root_path_completion('predict_module/models/Grasp_model')
model_path = '/home/icaros/grasp/grasp/predict_module/models/pro_model' + use_pro_name
print('Loading grasp model')
print('model-path: ', model_path)
G = grasp_obj(model_path, gpu_id, num_samples)
G.BATCH_SIZE = batch_size
G.test_init(lr_rate)
return G
# debug
def init_adv(num_samples, use_new_model='False', use_new_name='', batch_size=1, gpu_id=0,adv_lr_rate=0.01):
if use_new_model and os.path.exists(root_path_completion('predict_module/models/adv_model{}.index'.format(use_new_name))):
model_path = root_path_completion('predict_module/models/adv_model{}'.format(use_new_name))
else:
model_path = root_path_completion('predict_module/models/Shake_model')
print('Loading shake model')
G= shake_obj(model_path, gpu_id, num_samples)
G.BATCH_SIZE = batch_size
G.test_init(adv_lr_rate)
return G
#added by Yoon
def init_force_filter(batch_size, gpu_id, lr_rate, Collective_dimension): #2324):
model_path = 'models/checkpoint' #.ckpt-2000'
G = force_filter_obj(heckpoint_path=model_path, gpu_id=gpu_id, batch_size=batch_size, Collective_dimension=Collective_dimension)
return G
def init_force_filter2(batch_size, gpu_id, lr_rate, Collective_dimension, opt, is_alt):
model_path = None
if is_alt:
if opt == 0:
model_path = 'models/bottle_alt/checkpoint' # .ckpt-2000'
elif opt == 1:
model_path = 'models/new_cube_alt/checkpoint' # .ckpt-2000'
elif opt == 2:
model_path = 'models/cube_alt/checkpoint' # .ckpt-2000'
elif opt == 3:
model_path = 'models/half-nut_alt/checkpoint' # .ckpt-2000'
elif opt == 4:
model_path = 'models/round-nut_alt/checkpoint' # .ckpt-2000'
else:
if opt == 0:
model_path = 'models/bottle/checkpoint' # .ckpt-2000'
elif opt == 1:
model_path = 'models/new_cube/checkpoint' # .ckpt-2000'
elif opt == 2:
model_path = 'models/cube/checkpoint' # .ckpt-2000'
elif opt == 3:
model_path = 'models/half-nut/checkpoint' # .ckpt-2000'
elif opt == 4:
model_path = 'models/round-nut/checkpoint' # .ckpt-2000'
G = five_filter_obj(is_alt=is_alt, opt=opt, lr=lr_rate, checkpoint_path=model_path, gpu_id=gpu_id, batch_size=batch_size, Collective_dimension=Collective_dimension)
return G
# nbatches is batch size
def predict_from_img(gripper_coords, post_reward, num_samples, training_gt, image, obj_name, G, timestep,
log_dir, is_train=True, opt=1, update_info=None, was_valid=True):
print(colored("was valid?: {}".format(was_valid), "yellow"))
gscale = 0.234
I = cv2.imread(image)
imsize = 896
gsize = int(gscale * imsize)
# detector needs to have been initialized
P = Predictors(I, G)
P.opt = opt
P.update_info = update_info
print('Predicting on samples')
st_time = time.time()
print(colored('is_train in predict_from_img: {}'.format(is_train), 'red'))
print("gsize: ", gsize)
P.graspNet_grasp(patch_size=gsize, num_samples=num_samples) #, is_train = is_train)
if not (opt == 2):
epsil = (post_reward + 1) / 2
if not epsil == 1:
epsil = (epsil + 0.4) / 2
#cointoss = np.random.choice(2, 1, p=[1-epsil, epsil])
cointoss = np.random.choice(2, 1, p=[epsil, 1-epsil])
# P.graspNet_grasp(patch_size=gsize, num_samples=1000)
print('Time taken: {}s'.format(time.time() - st_time))
np.random.seed(np.random.randint(50))
Reward_array = P.fc8_norm_vals
r_pindex = 0 # location
r_tindex = 0 # angle
trial_types = None
if opt == 0:
if is_train:
angle_num = Reward_array.shape[1]
#cointoss = 0 #rl
if cointoss == 0 or obj_name == 'round-nut.xml':# and was_valid:
# print('debug predict_from_img fc8_norm_vals shape: ', P.fc8_norm_vals.shape)
index = np.argmax(Reward_array)
r_pindex = index // angle_num
# print("P.fc8_norm_vals.shape[1]: ", P.fc8_norm_vals.shape[1])
print("pindex: ", r_pindex)
r_tindex = index % angle_num
if training_gt:
r_tindex = np.random.randint(angle_num)
print("tindex: ", r_tindex)
print(colored("choose maximum bat", "yellow"))
trial_types = "opt"
else:
epsil = np.random.randint(10)
if epsil > 3:
index = np.argmax(Reward_array)
r_pindex = index // angle_num
r_tindex = np.random.randint(angle_num) # P.t_indice[r_pindex]
print("pindex: ", r_pindex)
print("tindex: ", r_tindex)
print(colored("random angle", "yellow"))
trial_types = "ra"
elif epsil <= 3 and epsil >= 1:
r_pindex = np.random.randint(num_samples) # // angle_num
r_tindex = np.argmax(Reward_array[r_pindex]) # % angle_num
print("pindex: ", r_pindex)
print("tindex: ", r_tindex)
print(colored("random loc", "yellow"))
trial_types = "rl"
else:
r_pindex = np.random.randint(num_samples) # // angle_num
r_tindex = np.random.randint(angle_num) # P.t_indice[r_pindex]
print("pindex: ", r_pindex)
print("tindex: ", r_tindex)
print(colored("fully randomized trials", "yellow"))
trial_types = "fr"
else:
index = np.argmax(P.fc8_norm_vals)
r_pindex = index // P.fc8_norm_vals.shape[1]
print("pindex: ", r_pindex)
r_tindex = index % P.fc8_norm_vals.shape[1]
print("tindex: ", r_tindex)
fc8_values = P.fc8_norm_vals
print("P.patch_hs[r_pindex]: ", P.patch_hs[r_pindex])
print("P.patch_ws[r_pindex]: ", P.patch_ws[r_pindex])
print("P.patch_hs -shape: ", P.patch_hs.shape)
print("P.patch_ws -shape: ", P.patch_ws.shape)
# R : Rotational Info
pred = P.pred
R_table_update_info = []
R_table_spec = None
if opt == 1:
pred_spot = np.max(pred, axis=1) # [1]
r_tindice = np.argmax(pred, axis=1)
I = drawRectangle_spot(gripper_coords, I, P.patch_hs, P.patch_ws, r_tindice, gsize,
pred=pred_spot)
R_table_update_info.append(P.r_angle_table_patches)
R_table_update_info.append(P.patch_hs) # 1
R_table_update_info.append(P.patch_ws) # 2
R_table_update_info.append(r_pindex) # 3
R_table_update_info.append(r_tindice) # 4
R_table_spec = P.R_table_spec
trial_types = "1Lifted"
# Added by Yoon for test
R = None
angle = None
center_pt = None
pred = np.max(pred)
if opt == 0:
(I, center_pt, R, angle) = drawRectangle(I, P.patch_hs[r_pindex], P.patch_ws[r_pindex], r_tindex, gsize,
pred=pred)
print("center from img: ", center_pt)
# R : Rotational Info
patch_Is_resized = P.patch_Is_resized[r_pindex]
patch_Is_resized = patch_Is_resized[np.newaxis, :] # [1,224,224,3]
# save_name = image_path_completion(obj_name + '_predict.jpg')
save_name = predict_image_path_completion(obj_name + '_predict_{}_{}.jpg'.format(timestep, trial_types),
log_dir)
try:
cv2.imwrite(save_name, I)
print('prediction image {} saved'.format(save_name))
except:
print('error saving image: {}'.format(save_name))
R_table_spec = P.R_table_spec
del P
gc.collect()
if opt == 1:
return (patch_Is_resized, pred, R_table_spec, R_table_update_info)
else: # opt == 0
return (center_pt, R, angle, patch_Is_resized, pred, fc8_values, R_table_spec)
# modified by Yoon
else:
fc8_values = P.fc8_norm_vals
R_table_spec = P.R_table_spec
R_table_update_info = []
R_table_update_info.append(P.r_angle_table_patches)
R_table_update_info.append(P.patch_hs)
R_table_update_info.append(P.patch_ws)
del P
return R_table_spec, R_table_update_info
def predict_from_R_table(R_table):
W, H = R_table.shape
denom = .0
max_w = 0
max_h = 0
max_num = 0
for w in range(W):
for h in range(H):
e = R_table[w, h]
p = e[0]
denom += p
for w in range(W):
for h in range(H):
e = R_table[w, h]
p = e[0]/denom
p = [p, 1-p]
if p[0] >= 0.0:
sampled = np.random.choice(2, 10, p=p)
zero_counts = (sampled == 0).sum()
if max_num < zero_counts or (max_num == zero_counts and np.random.randint(2) == 0):
max_w = w
max_h = h
max_num = zero_counts
indice = (max_w, max_h)
print(colored("Reward!: {}".format(R_table[max_w, max_h][0]), "red"))
print(colored("indices!: {}".format(indice), "red"))
return (indice, R_table[max_w, max_h][1])
def adv_predict_from_img(I, G_adv):
A = Adv_Predictors(I, G_adv)
print('Adv Predicting on samples')
st_time = time.time()
probs, adv_action = A.shakeNet_shake(num_actions= 6, num_samples = 1)
print('Time take: {}s'.format(time.time()-st_time))
del A
return probs,adv_action
| [
"cv2.circle",
"cv2.putText",
"grasp.utils.mjcf_utils.root_path_completion2",
"numpy.argmax",
"cv2.imwrite",
"grasp.utils.mjcf_utils.root_path_completion",
"time.time",
"termcolor.colored",
"cv2.imread",
"numpy.max",
"gc.collect",
"numpy.array",
"numpy.random.randint",
"numpy.cos",
"numpy... | [((1000, 1099), 'numpy.array', 'np.array', (['[[-grasp_l, -grasp_w], [grasp_l, -grasp_w], [grasp_l, grasp_w], [-grasp_l,\n grasp_w]]'], {}), '([[-grasp_l, -grasp_w], [grasp_l, -grasp_w], [grasp_l, grasp_w], [-\n grasp_l, grasp_w]])\n', (1008, 1099), True, 'import numpy as np\n'), ((1884, 1933), 'cv2.circle', 'cv2.circle', (['I_temp', 'center_pt', '(2)', '(255, 0, 0)', '(-1)'], {}), '(I_temp, center_pt, 2, (255, 0, 0), -1)\n', (1894, 1933), False, 'import cv2\n'), ((2932, 3031), 'numpy.array', 'np.array', (['[[-grasp_l, -grasp_w], [grasp_l, -grasp_w], [grasp_l, grasp_w], [-grasp_l,\n grasp_w]]'], {}), '([[-grasp_l, -grasp_w], [grasp_l, -grasp_w], [grasp_l, grasp_w], [-\n grasp_l, grasp_w]])\n', (2940, 3031), True, 'import numpy as np\n'), ((4611, 4710), 'numpy.array', 'np.array', (['[[-grasp_l, -grasp_w], [grasp_l, -grasp_w], [grasp_l, grasp_w], [-grasp_l,\n grasp_w]]'], {}), '([[-grasp_l, -grasp_w], [grasp_l, -grasp_w], [grasp_l, grasp_w], [-\n grasp_l, grasp_w]])\n', (4619, 4710), True, 'import numpy as np\n'), ((7749, 7849), 'cv2.putText', 'cv2.putText', (['I_temp', 'is_adv_string', 'bottomLeftCornerOfText', 'font', 'fontScale', 'fontColor', 'lineType'], {}), '(I_temp, is_adv_string, bottomLeftCornerOfText, font, fontScale,\n fontColor, lineType)\n', (7760, 7849), False, 'import cv2\n'), ((15824, 15841), 'cv2.imread', 'cv2.imread', (['image'], {}), '(image)\n', (15834, 15841), False, 'import cv2\n'), ((16064, 16075), 'time.time', 'time.time', ([], {}), '()\n', (16073, 16075), False, 'import time\n'), ((23053, 23064), 'time.time', 'time.time', ([], {}), '()\n', (23062, 23064), False, 'import time\n'), ((1378, 1394), 'numpy.array', 'np.array', (['[w, h]'], {}), '([w, h])\n', (1386, 1394), True, 'import numpy as np\n'), ((3967, 4016), 'cv2.circle', 'cv2.circle', (['I_temp', 'center_pt', '(3)', '(255, 0, 0)', '(-1)'], {}), '(I_temp, center_pt, 3, (255, 0, 0), -1)\n', (3977, 4016), False, 'import cv2\n'), ((6240, 6290), 'cv2.circle', 'cv2.circle', (['I_temp', 'center_pt', '(3)', 'color_tutple', '(-1)'], {}), '(I_temp, center_pt, 3, color_tutple, -1)\n', (6250, 6290), False, 'import cv2\n'), ((7171, 7205), 'termcolor.colored', 'colored', (['force_direction', '"""yellow"""'], {}), "(force_direction, 'yellow')\n", (7178, 7205), False, 'from termcolor import colored\n'), ((8139, 8169), 'cv2.imwrite', 'cv2.imwrite', (['save_name', 'I_temp'], {}), '(save_name, I_temp)\n', (8150, 8169), False, 'import cv2\n'), ((13747, 13804), 'grasp.utils.mjcf_utils.root_path_completion', 'root_path_completion', (['"""predict_module/models/Shake_model"""'], {}), "('predict_module/models/Shake_model')\n", (13767, 13804), False, 'from grasp.utils.mjcf_utils import root_path_completion\n'), ((16486, 16530), 'numpy.random.choice', 'np.random.choice', (['(2)', '(1)'], {'p': '[epsil, 1 - epsil]'}), '(2, 1, p=[epsil, 1 - epsil])\n', (16502, 16530), True, 'import numpy as np\n'), ((20478, 20490), 'numpy.max', 'np.max', (['pred'], {}), '(pred)\n', (20484, 20490), True, 'import numpy as np\n'), ((21405, 21417), 'gc.collect', 'gc.collect', ([], {}), '()\n', (21415, 21417), False, 'import gc\n'), ((3423, 3445), 'numpy.array', 'np.array', (['[h[i], w[i]]'], {}), '([h[i], w[i]])\n', (3431, 3445), True, 'import numpy as np\n'), ((5080, 5118), 'numpy.array', 'np.array', (['[center_pt[1], center_pt[0]]'], {}), '([center_pt[1], center_pt[0]])\n', (5088, 5118), True, 'import numpy as np\n'), ((8874, 8932), 'grasp.utils.mjcf_utils.root_path_completion2', 'root_path_completion2', (['"""predict_module/models/Grasp_model"""'], {}), "('predict_module/models/Grasp_model')\n", (8895, 8932), False, 'from grasp.utils.mjcf_utils import root_path_completion2\n'), ((9215, 9272), 'grasp.utils.mjcf_utils.root_path_completion', 'root_path_completion', (['"""predict_module/models/Grasp_model"""'], {}), "('predict_module/models/Grasp_model')\n", (9235, 9272), False, 'from grasp.utils.mjcf_utils import root_path_completion\n'), ((10050, 10115), 'grasp.utils.mjcf_utils.root_path_completion2', 'root_path_completion2', (['"""predict_module/models/filter/Grasp_model"""'], {}), "('predict_module/models/filter/Grasp_model')\n", (10071, 10115), False, 'from grasp.utils.mjcf_utils import root_path_completion2\n'), ((10398, 10462), 'grasp.utils.mjcf_utils.root_path_completion', 'root_path_completion', (['"""predict_module/models/filter/Grasp_model"""'], {}), "('predict_module/models/filter/Grasp_model')\n", (10418, 10462), False, 'from grasp.utils.mjcf_utils import root_path_completion\n'), ((11328, 11386), 'grasp.utils.mjcf_utils.root_path_completion2', 'root_path_completion2', (['"""predict_module/models/Grasp_model"""'], {}), "('predict_module/models/Grasp_model')\n", (11349, 11386), False, 'from grasp.utils.mjcf_utils import root_path_completion2\n'), ((11686, 11743), 'grasp.utils.mjcf_utils.root_path_completion', 'root_path_completion', (['"""predict_module/models/Grasp_model"""'], {}), "('predict_module/models/Grasp_model')\n", (11706, 11743), False, 'from grasp.utils.mjcf_utils import root_path_completion\n'), ((12668, 12726), 'grasp.utils.mjcf_utils.root_path_completion2', 'root_path_completion2', (['"""predict_module/models/Grasp_model"""'], {}), "('predict_module/models/Grasp_model')\n", (12689, 12726), False, 'from grasp.utils.mjcf_utils import root_path_completion2\n'), ((13026, 13083), 'grasp.utils.mjcf_utils.root_path_completion', 'root_path_completion', (['"""predict_module/models/Grasp_model"""'], {}), "('predict_module/models/Grasp_model')\n", (13046, 13083), False, 'from grasp.utils.mjcf_utils import root_path_completion\n'), ((16680, 16701), 'numpy.random.randint', 'np.random.randint', (['(50)'], {}), '(50)\n', (16697, 16701), True, 'import numpy as np\n'), ((19760, 19780), 'numpy.max', 'np.max', (['pred'], {'axis': '(1)'}), '(pred, axis=1)\n', (19766, 19780), True, 'import numpy as np\n'), ((19812, 19835), 'numpy.argmax', 'np.argmax', (['pred'], {'axis': '(1)'}), '(pred, axis=1)\n', (19821, 19835), True, 'import numpy as np\n'), ((21175, 21200), 'cv2.imwrite', 'cv2.imwrite', (['save_name', 'I'], {}), '(save_name, I)\n', (21186, 21200), False, 'import cv2\n'), ((1183, 1202), 'numpy.cos', 'np.cos', (['grasp_angle'], {}), '(grasp_angle)\n', (1189, 1202), True, 'import numpy as np\n'), ((1246, 1265), 'numpy.sin', 'np.sin', (['grasp_angle'], {}), '(grasp_angle)\n', (1252, 1265), True, 'import numpy as np\n'), ((1267, 1286), 'numpy.cos', 'np.cos', (['grasp_angle'], {}), '(grasp_angle)\n', (1273, 1286), True, 'import numpy as np\n'), ((19090, 19116), 'numpy.argmax', 'np.argmax', (['P.fc8_norm_vals'], {}), '(P.fc8_norm_vals)\n', (19099, 19116), True, 'import numpy as np\n'), ((22438, 22466), 'numpy.random.choice', 'np.random.choice', (['(2)', '(10)'], {'p': 'p'}), '(2, 10, p=p)\n', (22454, 22466), True, 'import numpy as np\n'), ((23173, 23184), 'time.time', 'time.time', ([], {}), '()\n', (23182, 23184), False, 'import time\n'), ((1205, 1224), 'numpy.sin', 'np.sin', (['grasp_angle'], {}), '(grasp_angle)\n', (1211, 1224), True, 'import numpy as np\n'), ((4893, 4913), 'numpy.cos', 'np.cos', (['grasp_angles'], {}), '(grasp_angles)\n', (4899, 4913), True, 'import numpy as np\n'), ((4940, 4960), 'numpy.sin', 'np.sin', (['grasp_angles'], {}), '(grasp_angles)\n', (4946, 4960), True, 'import numpy as np\n'), ((4962, 4982), 'numpy.cos', 'np.cos', (['grasp_angles'], {}), '(grasp_angles)\n', (4968, 4982), True, 'import numpy as np\n'), ((16632, 16643), 'time.time', 'time.time', ([], {}), '()\n', (16641, 16643), False, 'import time\n'), ((17172, 17195), 'numpy.argmax', 'np.argmax', (['Reward_array'], {}), '(Reward_array)\n', (17181, 17195), True, 'import numpy as np\n'), ((17732, 17753), 'numpy.random.randint', 'np.random.randint', (['(10)'], {}), '(10)\n', (17749, 17753), True, 'import numpy as np\n'), ((3204, 3213), 'numpy.cos', 'np.cos', (['e'], {}), '(e)\n', (3210, 3213), True, 'import numpy as np\n'), ((3229, 3238), 'numpy.sin', 'np.sin', (['e'], {}), '(e)\n', (3235, 3238), True, 'import numpy as np\n'), ((3240, 3249), 'numpy.cos', 'np.cos', (['e'], {}), '(e)\n', (3246, 3249), True, 'import numpy as np\n'), ((4916, 4936), 'numpy.sin', 'np.sin', (['grasp_angles'], {}), '(grasp_angles)\n', (4922, 4936), True, 'import numpy as np\n'), ((17498, 17526), 'numpy.random.randint', 'np.random.randint', (['angle_num'], {}), '(angle_num)\n', (17515, 17526), True, 'import numpy as np\n'), ((17601, 17640), 'termcolor.colored', 'colored', (['"""choose maximum bat"""', '"""yellow"""'], {}), "('choose maximum bat', 'yellow')\n", (17608, 17640), False, 'from termcolor import colored\n'), ((17820, 17843), 'numpy.argmax', 'np.argmax', (['Reward_array'], {}), '(Reward_array)\n', (17829, 17843), True, 'import numpy as np\n'), ((17933, 17961), 'numpy.random.randint', 'np.random.randint', (['angle_num'], {}), '(angle_num)\n', (17950, 17961), True, 'import numpy as np\n'), ((3216, 3225), 'numpy.sin', 'np.sin', (['e'], {}), '(e)\n', (3222, 3225), True, 'import numpy as np\n'), ((18120, 18153), 'termcolor.colored', 'colored', (['"""random angle"""', '"""yellow"""'], {}), "('random angle', 'yellow')\n", (18127, 18153), False, 'from termcolor import colored\n'), ((18286, 18316), 'numpy.random.randint', 'np.random.randint', (['num_samples'], {}), '(num_samples)\n', (18303, 18316), True, 'import numpy as np\n'), ((18368, 18401), 'numpy.argmax', 'np.argmax', (['Reward_array[r_pindex]'], {}), '(Reward_array[r_pindex])\n', (18377, 18401), True, 'import numpy as np\n'), ((18689, 18719), 'numpy.random.randint', 'np.random.randint', (['num_samples'], {}), '(num_samples)\n', (18706, 18719), True, 'import numpy as np\n'), ((18771, 18799), 'numpy.random.randint', 'np.random.randint', (['angle_num'], {}), '(angle_num)\n', (18788, 18799), True, 'import numpy as np\n'), ((22590, 22610), 'numpy.random.randint', 'np.random.randint', (['(2)'], {}), '(2)\n', (22607, 22610), True, 'import numpy as np\n'), ((18551, 18582), 'termcolor.colored', 'colored', (['"""random loc"""', '"""yellow"""'], {}), "('random loc', 'yellow')\n", (18558, 18582), False, 'from termcolor import colored\n'), ((18958, 19002), 'termcolor.colored', 'colored', (['"""fully randomized trials"""', '"""yellow"""'], {}), "('fully randomized trials', 'yellow')\n", (18965, 19002), False, 'from termcolor import colored\n')] |
import numpy as np
import re
import os
import argparse
from sklearn.manifold import TSNE
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
import glob
from tqdm import tqdm
import time
import pdb
import random
from matplotlib import cm
from matplotlib.colors import ListedColormap, LinearSegmentedColormap
from multiprocessing import Pool
from scipy.interpolate import interp1d
from sklearn.metrics import roc_curve
from scipy.optimize import brentq
class Plot2D(object):
def __init__(self,emb_indir,tsne_outdir,plot_outdir):
if not os.path.exists(plot_outdir):
os.makedirs(plot_outdir)
if not os.path.exists(tsne_outdir):
os.makedirs(tsne_outdir)
self.emb_indir=emb_indir
self.tsne_outdir=tsne_outdir
self.plot_outdir=plot_outdir
return
def load_embs(self):
emb_npy_list = glob.glob(self.emb_indir+'/*.npy')
utt_label_list = [ i.split('.npy')[0] for i in emb_npy_list ]
# load all emb
emb_list=[]
valid_utt_label_list=[]
for emb_npy,lab in zip(emb_npy_list,utt_label_list):
try:
emb_list.append(np.load(emb_npy,allow_pickle=True))
valid_utt_label_list.append(lab)
except:
print(f"[skipping] could not open {emb_npy}")
print(f"read {len(emb_list)} embedding npys,{len(valid_utt_label_list)} labels")
np.save(os.path.join(tsne_outdir,'utt_label_list.npy'),valid_utt_label_list)
return emb_list,valid_utt_label_list
def run_tsne(self,emb_list):
#TSNE
emb_list=np.asarray(emb_list).reshape(-1,256)
print(emb_list.shape)
print("tsne running ...")
start_tsne=time.time()
tsne = TSNE(n_components=2, random_state=0)
emb_2d_tsne = tsne.fit_transform(np.asarray(emb_list))
print(f"tsne done: {time.time()-start_tsne} secs")
np.save(os.path.join(tsne_outdir,'emb_tsne_2d.npy'),emb_2d_tsne)
print("tsne dim reduction saved as {os.path.join(tsne_outdir,'emb_tsne_2d.npy')}")
return emb_2d_tsne
def run_pca(self,emb_list,utt_label_list):
#PCA
return
def plot_2d(self,array_2d,utt_label_list,num_spk_show,rescale=True,rescale_range=(-1,1)):
plt.rcParams["figure.figsize"] = (30,30)
if rescale==True:
array_2d=np.interp(array_2d, (array_2d.min(), array_2d.max()),rescale_range)
spk_label_list=[os.path.basename(i).split('_')[0] for i in utt_label_list]
print(f" unique speakers: {len(set(spk_label_list))}")
if num_spk_show == "all":
num_spk_show = len(set(spk_label_list))
display_spk_list=spk_label_list[:num_spk_show]
# colors
preset_color_list = ['r', 'g', 'b', 'c', 'm', 'y', 'k', 'w', 'orange','purple']
gencolor = cm.get_cmap('prism', 1000)
list_rgba = np.linspace(0, 1, num_spk_show)
rand_rgba = np.random.uniform(0, 1, num_spk_show)
# plot axes lim
if rescale==True:
plt.xlim(rescale_range)
plt.ylim(rescale_range)
i=0
for speaker,rgba in zip(display_spk_list, list_rgba):
if num_spk_show <= len(preset_color_list):
color = preset_color_list[i]
else:
color = gencolor(rgba)
plt.scatter(
x= array_2d[[speaker == x for x in spk_label_list], 0],
y= array_2d[[speaker == x for x in spk_label_list], 1],
c= color,#
s=5,
#edgecolors = 'k',
label= speaker)
plt.legend(loc=2,prop={'fontsize': "x-small"})
plt.title('showing {} speakers'.format(i+1),fontdict = {'fontsize' : 20})
plt.savefig(os.path.join(plot_outdir,'TSNE_{:03d}.png'.format(i+1)),bbox_inches='tight')
i+=1
plt.savefig(os.path.join(plot_outdir,'TSNE_ALL.png'),bbox_inches='tight')
plt.close()
return
if __name__ == "__main__":
emb_indir = '/mnt/data1/youngsunhere/data/VCTK/embs_0828_ckpt1'
tsne_outdir='/mnt/data1/youngsunhere/data/VCTK/embs_0828_tsneout'
plot_outdir = '/mnt/data1/youngsunhere/data/VCTK/embs_0828_plot'
num_spk_show = "all"
plot2d=Plot2D(emb_indir,tsne_outdir,plot_outdir)
emb_list,utt_label_list=plot2d.load_embs()
emb_2d_tsne=plot2d.run_tsne(emb_list)
plot2d.plot_2d(emb_2d_tsne,utt_label_list,num_spk_show=num_spk_show,rescale=True,rescale_range=(-1,1))
| [
"numpy.random.uniform",
"matplotlib.pyplot.xlim",
"numpy.load",
"os.makedirs",
"matplotlib.cm.get_cmap",
"sklearn.manifold.TSNE",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.close",
"numpy.asarray",
"matplotlib.pyplot.scatter",
"os.path.exists",
"matplotlib.pyplot.legend",
"os.path.basename... | [((107, 128), 'matplotlib.use', 'matplotlib.use', (['"""agg"""'], {}), "('agg')\n", (121, 128), False, 'import matplotlib\n'), ((873, 909), 'glob.glob', 'glob.glob', (["(self.emb_indir + '/*.npy')"], {}), "(self.emb_indir + '/*.npy')\n", (882, 909), False, 'import glob\n'), ((1701, 1712), 'time.time', 'time.time', ([], {}), '()\n', (1710, 1712), False, 'import time\n'), ((1726, 1762), 'sklearn.manifold.TSNE', 'TSNE', ([], {'n_components': '(2)', 'random_state': '(0)'}), '(n_components=2, random_state=0)\n', (1730, 1762), False, 'from sklearn.manifold import TSNE\n'), ((2788, 2814), 'matplotlib.cm.get_cmap', 'cm.get_cmap', (['"""prism"""', '(1000)'], {}), "('prism', 1000)\n", (2799, 2814), False, 'from matplotlib import cm\n'), ((2833, 2864), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', 'num_spk_show'], {}), '(0, 1, num_spk_show)\n', (2844, 2864), True, 'import numpy as np\n'), ((2883, 2920), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(1)', 'num_spk_show'], {}), '(0, 1, num_spk_show)\n', (2900, 2920), True, 'import numpy as np\n'), ((3843, 3854), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (3852, 3854), True, 'import matplotlib.pyplot as plt\n'), ((571, 598), 'os.path.exists', 'os.path.exists', (['plot_outdir'], {}), '(plot_outdir)\n', (585, 598), False, 'import os\n'), ((609, 633), 'os.makedirs', 'os.makedirs', (['plot_outdir'], {}), '(plot_outdir)\n', (620, 633), False, 'import os\n'), ((648, 675), 'os.path.exists', 'os.path.exists', (['tsne_outdir'], {}), '(tsne_outdir)\n', (662, 675), False, 'import os\n'), ((686, 710), 'os.makedirs', 'os.makedirs', (['tsne_outdir'], {}), '(tsne_outdir)\n', (697, 710), False, 'import os\n'), ((1405, 1452), 'os.path.join', 'os.path.join', (['tsne_outdir', '"""utt_label_list.npy"""'], {}), "(tsne_outdir, 'utt_label_list.npy')\n", (1417, 1452), False, 'import os\n'), ((1802, 1822), 'numpy.asarray', 'np.asarray', (['emb_list'], {}), '(emb_list)\n', (1812, 1822), True, 'import numpy as np\n'), ((1895, 1939), 'os.path.join', 'os.path.join', (['tsne_outdir', '"""emb_tsne_2d.npy"""'], {}), "(tsne_outdir, 'emb_tsne_2d.npy')\n", (1907, 1939), False, 'import os\n'), ((2977, 3000), 'matplotlib.pyplot.xlim', 'plt.xlim', (['rescale_range'], {}), '(rescale_range)\n', (2985, 3000), True, 'import matplotlib.pyplot as plt\n'), ((3010, 3033), 'matplotlib.pyplot.ylim', 'plt.ylim', (['rescale_range'], {}), '(rescale_range)\n', (3018, 3033), True, 'import matplotlib.pyplot as plt\n'), ((3258, 3421), 'matplotlib.pyplot.scatter', 'plt.scatter', ([], {'x': 'array_2d[[(speaker == x) for x in spk_label_list], 0]', 'y': 'array_2d[[(speaker == x) for x in spk_label_list], 1]', 'c': 'color', 's': '(5)', 'label': 'speaker'}), '(x=array_2d[[(speaker == x) for x in spk_label_list], 0], y=\n array_2d[[(speaker == x) for x in spk_label_list], 1], c=color, s=5,\n label=speaker)\n', (3269, 3421), True, 'import matplotlib.pyplot as plt\n'), ((3515, 3562), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '(2)', 'prop': "{'fontsize': 'x-small'}"}), "(loc=2, prop={'fontsize': 'x-small'})\n", (3525, 3562), True, 'import matplotlib.pyplot as plt\n'), ((3775, 3816), 'os.path.join', 'os.path.join', (['plot_outdir', '"""TSNE_ALL.png"""'], {}), "(plot_outdir, 'TSNE_ALL.png')\n", (3787, 3816), False, 'import os\n'), ((1586, 1606), 'numpy.asarray', 'np.asarray', (['emb_list'], {}), '(emb_list)\n', (1596, 1606), True, 'import numpy as np\n'), ((1147, 1182), 'numpy.load', 'np.load', (['emb_npy'], {'allow_pickle': '(True)'}), '(emb_npy, allow_pickle=True)\n', (1154, 1182), True, 'import numpy as np\n'), ((1850, 1861), 'time.time', 'time.time', ([], {}), '()\n', (1859, 1861), False, 'import time\n'), ((2414, 2433), 'os.path.basename', 'os.path.basename', (['i'], {}), '(i)\n', (2430, 2433), False, 'import os\n')] |
import numpy as np
import torch
import torch.nn.functional as F
from skimage.util import img_as_bool
def avg_iou(target, prediction):
with torch.no_grad():
run_iou = 0.0
batch_size = target.shape[0]
assert batch_size == prediction.shape[0]
true_mask = img_as_bool(target.cpu().numpy())
convt_pred = prediction.cpu().numpy()
#convt_mask = (convt_target > 0.5) * 255
#pred_mask = convt_mask.astype(np.uint8)
pred_mask = (convt_pred > 0.5)
for index in range(batch_size):
truth = true_mask[index, 0]
predicted = pred_mask[index, 0]
run_iou += iou(truth, predicted)
run_iou /= batch_size
return run_iou
def iou(im1, im2, empty_score=0.0):
"""Calculates the iou for 2 images"""
if im1.shape != im2.shape:
raise ValueError("Shape mismatch: im1 and im2 must have the same shape.")
intersection = np.logical_and(im1, im2)
union = np.logical_or(im1, im2)
union_sum = union.sum()
if union_sum == 0:
return empty_score
return intersection.sum() / union_sum
def avg_dice_coeff(target, prediction):
with torch.no_grad():
run_dice_coeff = 0.0
batch_size = target.shape[0]
assert batch_size == prediction.shape[0]
true_mask = img_as_bool(target.cpu().numpy())
convt_pred = prediction.cpu().numpy()
pred_mask = (convt_pred > 0.5)
for index in range(batch_size):
truth = true_mask[index, 0]
predicted = pred_mask[index, 0]
run_dice_coeff += dice_coeff(truth, predicted)
run_dice_coeff /= batch_size
return run_dice_coeff
def dice_coeff(im1, im2, empty_score=1.0):
"""Calculates the dice coefficient for the images"""
if im1.shape != im2.shape:
raise ValueError("Shape mismatch: im1 and im2 must have the same shape.")
im_sum = im1.sum() + im2.sum()
if im_sum == 0:
return empty_score
intersection = np.logical_and(im1, im2)
return 2. * intersection.sum() / im_sum | [
"torch.no_grad",
"numpy.logical_or",
"numpy.logical_and"
] | [((963, 987), 'numpy.logical_and', 'np.logical_and', (['im1', 'im2'], {}), '(im1, im2)\n', (977, 987), True, 'import numpy as np\n'), ((1000, 1023), 'numpy.logical_or', 'np.logical_or', (['im1', 'im2'], {}), '(im1, im2)\n', (1013, 1023), True, 'import numpy as np\n'), ((2035, 2059), 'numpy.logical_and', 'np.logical_and', (['im1', 'im2'], {}), '(im1, im2)\n', (2049, 2059), True, 'import numpy as np\n'), ((145, 160), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (158, 160), False, 'import torch\n'), ((1196, 1211), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (1209, 1211), False, 'import torch\n')] |
#!/usr/bin/env python3
"""
A file for creating a one-hot encoding of all characters, including madd and harakat, in Tarteel's Qur'an dataset.
The output pickle file will contain an object with the one-hot encoded Qur'an, an encoding function, and a decoding
function.
Author: <NAME>
Date: Jan. 12, 2019
"""
import copy
import dill as pickle
import json
import numpy as np
from argparse import ArgumentParser
parser = ArgumentParser(description='Tarteel Arabic One Hot Encoding Generator')
parser.add_argument('-i', '--input_json_path', type=str)
parser.add_argument('-o', '--output_pickle_path', type=str)
parser.add_argument('-v', '--verbose', type=bool, default=False)
args = parser.parse_args()
# Define constants.
QURAN_KEY = "quran"
SURAHS_KEY = "surahs"
AYAHS_KEY = "ayahs"
TEXT_KEY = "text"
NUM_KEY = "num"
NAME_KEY = "name"
BISMILLAH_KEY = "bismillah"
ENCODING_MAP_KEY = "encoding_map"
DECODING_MAP_KEY = "decoding_map"
CHAR_TO_INT_MAP_KEY = "char_to_int"
INT_TO_CHAR_MAP_KEY = "int_to_char"
def create_list_of_quranic_chars(quran_obj, surahs_key=SURAHS_KEY, ayahs_key=AYAHS_KEY, text_key=TEXT_KEY):
"""
Create a sorted list containing every character in the Qur'an text provided and return it.
:param quran_obj: An object containing surah objects.
:type quran_obj: object
:param surahs_key: The key in quran_obj to the list of surah objects.
:type surahs_key: string
:param ayahs_key: The key in each surah object to the list of ayah objects in that surah.
:type ayahs_key: string
:param text_key: The key to the actual Qur'anic text in each ayah object.
:type text_key: string
:returns: A sorted list containing every Arabic character in the Qur'an exactly once.
:rtype: list string
"""
quranic_char_set = set()
for surah_obj in quran_obj[surahs_key]:
for ayah_obj in surah_obj[ayahs_key]:
ayah_text = ayah_obj[text_key]
for char in ayah_text:
quranic_char_set.add(char)
return sorted(list(quranic_char_set))
def create_one_hot_encoding(quranic_char_list):
"""
Creates a one-hot encoding that associates each character in the argument list to a number and vice versa.
:param quranic_char_list: A list of characters.
:type quranic_char_list: list string
:returns: A tuple containing the encoding and decoding functions for the alphabet.
:rtype: tuple (function string => int, function int => string)
"""
# Define an encoding of characters to integers.
char_to_int = dict((c, i) for i, c in enumerate(quranic_char_list))
int_to_char = dict((i, c) for i, c in enumerate(quranic_char_list))
def encode_char_as_one_hot(string, char_to_int):
"""
Converts a string of characters from our alphabet into a one_hot encoded string.
"""
str_len = len(string)
int_list = np.array([char_to_int[char] for char in string])
one_hot_string = np.zeros((str_len, len(char_to_int)))
one_hot_string[np.arange(str_len), int_list] = 1
return one_hot_string
def decode_one_hot_as_string(one_hot_string, int_to_char):
"""
Converts a one_hot encoded numpy array back into a string of characters from our alphabet.
"""
int_list = list(np.argmax(one_hot_string, axis=1))
char_list = [int_to_char[integer] for integer in int_list]
return str(char_list)
return char_to_int, int_to_char, encode_char_as_one_hot, decode_one_hot_as_string
def generate_a_one_hot_encoded_script(quran_obj,
encoding_fn,
surahs_key=SURAHS_KEY,
ayahs_key=AYAHS_KEY,
text_key=TEXT_KEY,
num_key=NUM_KEY,
name_key=NAME_KEY,
bismillah_key=BISMILLAH_KEY):
"""
Translates each ayah in the given quran_obj into a vector of one-hot encoded characters using the given encoding.
Create a sorted list containing every character in the Qur'an text provided and return it.
:param quran_obj: An object containing surah objects.
:type quran_obj: object
:param quran_obj: A function that converts Arabic Qur'anic characters to a one-hot encoding.
:type quran_obj: function (Arabic string => numpy 2darray)
:param surahs_key: The key in quran_obj to the list of surah objects.
:type surahs_key: string
:param ayahs_key: The key in each surah object to the list of ayah objects in that surah.
:type ayahs_key: string
:param text_key: The key to the actual Qur'anic text in each ayah object.
:type text_key: string
:param num_key: The key in surah and ayah objects to the ordering of the surah or ayah.
:type num_key: string
:param name_key: The key in each surah object to the name of that surah.
:type name_key: string
:param bismillah_key: The key to the bismillah text in the first ayah object of each surah object.
:type bismillah_key: string
:returns: An object identical to the quran_obj but with one-hot encodings of all Arabic text (not names).
:rtype: object
"""
one_hot_quran_encoding = {}
one_hot_quran_encoding[SURAHS_KEY] = []
for surah_obj in quran_obj[surahs_key]:
# Copy new surah object for one-hot Json container.
one_hot_surah_obj = {}
one_hot_surah_obj[num_key] = surah_obj[num_key]
one_hot_surah_obj[name_key] = surah_obj[name_key]
one_hot_surah_obj[ayahs_key] = []
for ayah_obj in surah_obj[ayahs_key]:
ayah_text = ayah_obj[text_key]
# Make new ayah object for one-hot Json container.
one_hot_ayah_obj = {}
one_hot_ayah_obj[num_key] = ayah_obj[num_key]
one_hot_ayah_obj[text_key] = encoding_fn(ayah_text)
if bismillah_key in ayah_obj:
one_hot_ayah_obj[bismillah_key] = encoding_fn(ayah_obj[bismillah_key])
one_hot_surah_obj[ayahs_key].append(one_hot_ayah_obj)
one_hot_quran_encoding[surahs_key].append(one_hot_surah_obj)
return one_hot_quran_encoding
def run_script(args):
"""
Runs the script to find all characters, generate the encoding, and translate and store it in the output file.
"""
# try:
with open(args.input_json_path, 'rb') as quran_json_file:
# Import json file.
quran_obj = json.load(quran_json_file)[QURAN_KEY]
#
# except:
# print("Json file failed to open. Exiting script...")
# return
# Get the list of every character in the Qur'an.
quranic_char_list = create_list_of_quranic_chars(quran_obj)
if args.verbose:
print(quranic_char_list, ' has ', len(quranic_char_list), ' characters.')
# Create the one-hot encodings.
char_to_int_map, \
int_to_char_map, \
encode_char_as_one_hot, \
decode_one_hot_as_string = create_one_hot_encoding(quranic_char_list)
if args.verbose:
print("encode!")
x = encode_char_as_one_hot("".join(quranic_char_list))
print(x)
print("decode!")
print(decode_one_hot_as_string(x))
# Generate the Qur'anic text in one-hot encoding.
one_hot_quran_encoding = generate_a_one_hot_encoded_script(
quran_obj,
lambda string: encode_char_as_one_hot(string, char_to_int_map))
# Create an object with the encoding and the two functions.
full_object = {
QURAN_KEY: one_hot_quran_encoding,
ENCODING_MAP_KEY: encode_char_as_one_hot,
DECODING_MAP_KEY: decode_one_hot_as_string,
CHAR_TO_INT_MAP_KEY: char_to_int_map,
INT_TO_CHAR_MAP_KEY: int_to_char_map
}
with open(args.output_pickle_path, 'wb') as one_hot_quran_pickle_file:
pickle.dump(full_object, one_hot_quran_pickle_file)
def load_data(pickle_file):
"""
A sample function to demonstrate how to load the object.
"""
try:
with open(pickle_file, 'rb') as one_hot_pickle:
one_hot_obj = pickle.load(one_hot_pickle)
print('Now, we can do things with it! Keys: ', one_hot_obj.keys())
except:
print("Pickle file failed to open. Exiting...")
return
if __name__ == "__main__":
run_script(args)
| [
"json.load",
"argparse.ArgumentParser",
"numpy.argmax",
"dill.load",
"numpy.array",
"numpy.arange",
"dill.dump"
] | [((422, 493), 'argparse.ArgumentParser', 'ArgumentParser', ([], {'description': '"""Tarteel Arabic One Hot Encoding Generator"""'}), "(description='Tarteel Arabic One Hot Encoding Generator')\n", (436, 493), False, 'from argparse import ArgumentParser\n'), ((2894, 2942), 'numpy.array', 'np.array', (['[char_to_int[char] for char in string]'], {}), '([char_to_int[char] for char in string])\n', (2902, 2942), True, 'import numpy as np\n'), ((7918, 7969), 'dill.dump', 'pickle.dump', (['full_object', 'one_hot_quran_pickle_file'], {}), '(full_object, one_hot_quran_pickle_file)\n', (7929, 7969), True, 'import dill as pickle\n'), ((3306, 3339), 'numpy.argmax', 'np.argmax', (['one_hot_string'], {'axis': '(1)'}), '(one_hot_string, axis=1)\n', (3315, 3339), True, 'import numpy as np\n'), ((6555, 6581), 'json.load', 'json.load', (['quran_json_file'], {}), '(quran_json_file)\n', (6564, 6581), False, 'import json\n'), ((8167, 8194), 'dill.load', 'pickle.load', (['one_hot_pickle'], {}), '(one_hot_pickle)\n', (8178, 8194), True, 'import dill as pickle\n'), ((3030, 3048), 'numpy.arange', 'np.arange', (['str_len'], {}), '(str_len)\n', (3039, 3048), True, 'import numpy as np\n')] |
#!/usr/bin/env python3
# Copyright 2021 <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.
#
# @title :finite_width/ridgelet_prior.py
# @author :ch
# @contact :<EMAIL>
# @created :07/30/2021
# @version :1.0
# @python_version :3.8.10
r"""
The Ridgelet Prior
------------------
The module :mod:`finite_width.ridgelet_prior` provides an implementation of the
Ridgelet prior as introduced by
`Matsubara et al. <https://arxiv.org/abs/2010.08488>`__,
The Ridgelet Prior: A Covariance Function Approach to Prior Specification
for Bayesian Neural Networks, 2021.
The ridgelet prior allows to specify a weight prior of a BNN (with given
architecture) to approximately capture the function space prior as described by
a target Gaussian process (GP).
The paper focuses on MLP networks. Note, that only certain activation functions
are supported (e.g., compare Table 1 in the paper).
In practice, the computation of the prior is rather expensive and currently
only interesting for toy examples. In addition, the GP prior can only be
approximated on a compact domain :math:`\mathcal{X}`, and the prior behavior
outside this domain would need to be investigated.
In the following, we comment a bit on the construction of this prior to gain a
better intuition.
The prior construction is based on the Ridgelet transform, which has the
following property for a suitably chosen pair of :math:`\phi(\cdot)` and
:math:`\psi(\cdot)`:
.. math::
f(\mathbf{x}) = \int_{\mathbb{R}^{d+1}} \bigg( \int_{\mathbb{R}^d} \
\psi(\mathbf{w}^T \mathbf{x} + b) f(\mathbf{x}) d\mathbf{x} \bigg) \
\phi(\mathbf{w}^T \mathbf{x} + b) d\mathbf{w} db
where :math:`d` is the dimensionality of the inputs. As a next step, those
integrals are discretized, which makes the connection to a single hidden layer
neural network obvious:
.. math::
:label: ridgelet-discretization
I_{\sigma, D, N} [f](\mathbf{x}) = \sum_{i=1}^N v_i \bigg( \
\sum_{j=1}^D u_j f(\mathbf{x}_j) \psi(\mathbf{w}_i^T \mathbf{x}_j \
+ b_i) \bigg) \phi(\mathbf{w}_i^T \mathbf{x} + b_i)
where :math:`D` is the number of points :math:`\mathbf{x}_j` chosen to perform
numerical integration on the compact domain :math:`\mathcal{X}`, and
:math:`v_i`, :math:`u_j` are the cubature points corresponding to the two
integrals.
The discretisation of the inner-integral is described in *Assumption 2* in the
paper. In our case, the compact domain :math:`\mathcal{X}` is simply defined by
the hyper-cube :math:`[S, S]^d` on which :math:`\{\mathbf{x}_j\}_{j=1}^D` form
a regular grid with cubature weights :math:`u_j = (2S)^d/D`.
The discretisation of the outer integral is described in *Assumption 3* in the
paper and based on a change of measure such that a Monte-Carlo integration
is feasible. Therefore, a set :math:`\{(\mathbf{w}_i, b_i)\}_{i=1}^N` is drawn
from the first layer's weight prior :math:`\mathcal{N}(0, \sigma_w^2)` and
:math:`\mathcal{N}(0, \sigma_b^2)`, and the cubature weights are set to
:math:`v_i = Z/N` with :math:`Z = (2\pi)^\frac{1}{2} \sigma_w^d \sigma_b`.
In the limit :math:`\sigma, N, D \rightarrow \infty` the estimator
:math:`I_{\sigma, D, N} [f](x)` should converge to the target :math:`f(x)`.
Eq :eq:`ridgelet-discretization` is reminiscent of a single hidden layer MLP
with 1 output neuron
.. math::
\text{NN}(\mathbf{x}) = \sum_{i=1}^N w_i^1 \
\phi( (\mathbf{w}_i^0)^T \mathbf{x} + b_i^0)
with outputs weights
.. math::
w_i^1 = v_i \sum_{j=1}^D u_j f(\mathbf{x}_j) \
\psi((\mathbf{w}_i^0)^T \mathbf{x}_j + b_i^0)
Note, the dependence of the output weights on the input weights, which is an
important construction detail of this prior.
Assume a matrix :math:`\Psi^0` with entries
:math:`[\Psi^0]_{i,j} = v_i u_j \psi((\mathbf{w}_i^0)^T \mathbf{x}_j + b_i^0)`
and a GP :math:`f \sim \mathcal{GP}(\mathbf{m}, K)`. In this case, we
can express the output weights as :math:`\mathbf{w}^1 = \Psi^0 \mathbf{f}` with
:math:`\mathbf{f}_j = f(\mathbf{x}_j)`. Since :math:`\mathbf{f}_j` is a Gaussian
random variable, also :math:`\mathbf{w}^1` is a Gaussian random variable with
mean :math:`\mathbb{E}[\mathbf{w}^1] = \Psi^0 \mathbf{m}` and covariance matrix
.. math::
\mathbb{E}\big[(\mathbf{w}^1 - \mathbb{E}[\mathbf{w}^1]) \
(\mathbf{w}^1 - \mathbb{E}[\mathbf{w}^1])^T\big] = \
\Psi^0 \mathbb{E}\big[(\mathbf{f} - \mathbf{m}) \
(\mathbf{f} - \mathbf{m})^T\big] (\Psi^0)^T = \Psi^0 K (\Psi^0)^T
In definition 1, the authors propose the following prior construction for a
multi-layer MLP with :math:`L` layers: biases are drawn from
:math:`b_i^{l-1} \sim \mathcal{N}(0, \sigma_b^2)`, first layer weights are
drawn from :math:`\mathbf{w}_i^0 \sim \mathcal{N}(0, \sigma_w^2 I)` and the
weights of all remaining layers are drawn according to
.. math::
\mathbf{w}^l_i \mid \{(\mathbf{w}_r^{l-1}, b_r^{l-1}) : r = 1,\dots,N_l \} \
\sim \mathcal{N}(\Psi^{l-1} \mathbf{m}, \Psi^{l-1} K (\Psi^{l-1})^T)
where
.. math::
[\Psi^{l-1}]_{i,j} = v_i u_j \psi\big( (\mathbf{w}_i^{l-1})^T \
\phi\big(\mathbf{z}^{l-1} (\mathbf{x}_j)\big) + b_i^{l-1} \big)
Example:
.. code-block:: python
from hypnettorch.mnets import MLP
from sklearn.gaussian_process.kernels import RBF
d = 1
S = 5
X = rp.regular_grid(cube_size=S, res_per_dim=8, grid_dim=d)
rbf_kernel = RBF(length_scale=1.)
m = torch.zeros(X.shape[0])
K = torch.from_numpy(rbf_kernel(X)).type(torch.FloatTensor)
net = MLP(n_in=d, n_out=1, hidden_layers=(10,))
sample, dists = rp.ridgelet_prior_sample(net, phi_name='relu',
cube_size=S, grid_points=X, gp_mean=m, gp_cov=K, return_dist=True)
print('log-prob: ', rp.ridgelet_prior_logprob(sample, dists=dists))
inputs = torch.rand(4, d)
preds = net.forward(inputs, weights=sample)
"""
from hypnettorch.mnets import MLP
import numpy as np
import torch
from torch.distributions import MultivariateNormal, Normal
from warnings import warn
def ridgelet_prior_sample(net=None, hidden_widths=None, phi_name='relu',
cube_size=5, grid_points=None, gp_mean=None,
gp_cov=None, sigma2_w=1., sigma2_b=1.,
return_dist=False, sample=None):
"""Generate a sample from the Ridgelet prior.
This function will generate a sample from the Ridgelet prior according to
the construction outlined above (see :mod:`finite_width.ridgelet_prior`). It
thus only applies to plain MLP networks. Therefore, one may either specify
an instance of class :class:`hypnettorch.mnets.mlp.MLP` via option ``net``,
or specify a list of hidden layer weights via option ``hidden_widths``. The
basic construction assumes bias terms at every hidden layer, but not at the
output layer. For simplicity, this assumption is carried on in this
implementation. Therefore, if ``net`` has output bias weights, these are
set to zero in every sample. On the other hand, if ``net`` has no bias terms
in hidden layers, an error is raised.
Args:
net (hypnettorch.mnets.mlp.MLP): A plain MLP instance. The returned
weight sample will have shapes according to attribute
``param_shapes``. Note, that this function assumes that attribute
``has_bias`` evaluates to ``True``.
hidden_widths (list or tuple, optional): If ``net`` is not provided,
then a list of hidden widths :math:`N_l` has to be provided. The
output shape of the network is assumed to be 1.
phi_name (str): The activation function used in the network. The
following options are supported:
- ``'relu'``: :math:`\phi(z) = \max(0, z)`
cube_size (float): The discretisation of the inner-integral is performed
using a regular grid on the hyper-cube :math:`[S, S]^d`. Argument
``cube_size`` refers to :math:`S`, while argument ``grid_points``
contains the actual grid points.
grid_points (torch.Tensor): A tensor of shape ``[D, d]`` containing the
grid points :math:`\mathbf{x}_j`.
gp_mean (torch.Tensor): A tensor of shape ``[D]`` containing the target
GP mean :math:`\mathbf{m}` at all the ``grid_points``.
gp_cov (torch.Tensor): A tensor of shape ``[D, D]`` containing the
target GP covariance matrix :math:`K`, i.e., the kernel value at all
``grid_points`` :math:`k(\mathbf{x}_i, \mathbf{x}_j)`.
sigma2_w (float): The variance :math:`\sigma_w^2` of the first layer
weights.
sigma2_b (float): The variance :math:`\sigma_b^2` of all biases.
return_dist (bool): If ``True``, a list of distribution objects from
class :class:`torch.distributions.normal.Normal` or
:class:`torch.distributions.multivariate_normal.MultivariateNormal`
is returned in addition to the weight sample. This list can be used
to compute the log-probability of the sample by summing the
individual log-probabilities.
This list will have the same order as the returned list of weight
samples.
Note:
Those distribution instances are only valid to compute the
log-probability for the returned sample, not for samples in
general, as every new sample recursively defines a different
list of distributions!
sample (list or tuple): A list of torch tensors. If provided, no new
sample will be generated, instead the passed ``sample`` will be
returned by this function. Therefore, this option is only meaningful
in combination with option ``return_dist`` in case the
log-probability of a given sample should be computed.
Returns:
(list): A list of tensors.
"""
# TODO Ideally we add an argument like this:
# rand_state (torch.Generator, optional): A generator to make random
# sampling reproducible.
# But that would require us (potentially) to implement our own `rsample`
# using the build-in sampling functions of PyTorch/
assert net is not None or hidden_widths is not None
#assert grid_points is not None and gp_mean is not None and \
# gp_cov is not None
if net is not None and hidden_widths is not None:
raise ValueError('You may either specify "net" or "hidden_widths", ' +
'not both!')
# Determine the `hidden_widths` from the network.
d_out = 1
if net is not None:
assert isinstance(net, MLP)
# Sanity check. This might fail, if the user uses a custom ReLU
# implementation.
if hasattr(net, '_a_fun') and phi_name == 'relu':
assert isinstance(net._a_fun, torch.nn.ReLU)
elif hasattr(net, '_a_fun') and phi_name == 'tanh':
assert isinstance(net._a_fun, torch.nn.Tanh)
num_layers = 0
for meta in net.param_shapes_meta:
if meta['name'] not in ['bias', 'weight']:
raise RuntimeError('Provided network is not plain MLP!')
if meta['name'] == 'weight':
num_layers += 1
num_layers -= 1 # we are interested in num hidden layers.
hidden_widths = [-1] * num_layers
for i, meta in enumerate(net.param_shapes_meta):
if meta['name'] == 'weight':
s = net.param_shapes[i]
if meta['layer'] < num_layers:
hidden_widths[meta['layer']] = s[0]
else:
d_out = s[0]
if sample is not None:
assert len(sample) == len(net.param_shapes)
weights = [None] * (num_layers+1)
biases = [None] * (num_layers+1)
for i, meta in enumerate(net.param_shapes_meta):
if meta['name'] == 'weight':
weights[meta['layer']] = sample[i]
else:
biases[meta['layer']] = sample[i]
if len(grid_points.shape) == 1:
grid_points.reshape(-1, 1)
assert len(grid_points.shape) == 2
D = grid_points.shape[0]
d = grid_points.shape[1]
device = grid_points.device
sigma_w = np.sqrt(sigma2_w)
sigma_b = np.sqrt(sigma2_b)
weight_dists = []
bias_dists = []
if sample is None:
weights = []
biases = []
else:
if net is None:
# TODO Decompose `sample` into list of `weights` and `biases`.
raise NotImplementedError()
# Compute choesky of Kernel matrix.
# Compute: K = L L^T, such that C = (P^T L) (P^T L)^T
# Note, weights can be samples as w = m + (P^T L) eps,
# where `eps` is white noise. However, this scheme might due to numerical
# issues cause C = (P^T L) (P^T L)^T to be not invertable. Thus, if
# distribution objects need to be created, this simple scheme is not
# sufficient as invertibility of `C` needs to be ensured.
gp_cov_L = None
if not return_dist:
gp_cov_L = _cholesky_noise_adaptive(gp_cov)
# Sample first layer weights.
weight_dists.append(Normal(torch.zeros([hidden_widths[0], d]).to(device),
sigma_w))
bias_dists.append(Normal(torch.zeros([hidden_widths[0]]).to(device),
sigma_b))
if sample is None:
weights.append(weight_dists[-1].rsample())
biases.append(bias_dists[-1].rsample())
if len(hidden_widths) == 0:
raise ValueError('The Ridgelet prior construction requires at least ' +
'one hidden layer.')
if len(hidden_widths) > 1:
raise NotImplementedError('Ridgelet prior not implemented for more ' +
'than one hidden layer yet.')
# Cubature weights
# TODO Incorporate mollifier to compute `x_j` dependent weight.
u_j = (2 * cube_size)**d / D
# Note, those cubature weights ideally depend on the determinant of the
# previous layer's covariance matrix.
v_i_unnorm = (2*np.pi)**(1/2) * sigma_w**d * sigma_b
# Sample next layer weights conditioned on previous layer weights.
z = grid_points
for l in range(len(hidden_widths)):
last = l == len(hidden_widths) - 1
n_in = hidden_widths[l]
n_out = d_out if last else hidden_widths[l+1]
if last:# No bias weights in the output layer.
bias_dists.append(None)
if sample is None:
biases.append(torch.zeros([n_out]).to(device))
else:
bias_dists.append(Normal(torch.zeros([n_out]).to(device), sigma_b))
if sample is None:
biases.append(bias_dists[-1].rsample())
W_prev = weights[l]
b_prev = biases[l]
if l > 0:
if phi_name == 'relu':
z = torch.nn.functional.relu(z)
z = z @ W_prev.T + b_prev[None, :]
if phi_name == 'relu' and d in [1, 2]: # Much faster.
psi = _ass_func_relu_manual(z, d)
elif phi_name == 'tanh' and d == 1: # Much faster.
psi = _ass_func_tanh_manual(z, d)
else:
psi = _ass_func(z, d, phi_name=phi_name)
v_i = v_i_unnorm / n_in
psi *= (u_j * v_i)
# Mean of weight distribution.
gauss_m = psi.T @ gp_mean
# Covariance of weight distribution.
if return_dist: # Sample and create distribution object.
gauss_C = psi.T @ gp_cov @ psi
gauss_L = _cholesky_noise_adaptive(gauss_C)
weight_dists.append(MultivariateNormal(gauss_m, scale_tril=gauss_L))
else: # Only sample.
gauss_L = psi.T @ gp_cov_L
weight_dists.append(None)
if sample is None:
W = [] # We need to draw a weight vector for every output neuron.
for _ in range(n_out):
if return_dist:
W.append(weight_dists[-1].rsample())
else:
eps = torch.normal(torch.zeros((D)).to(device))
W.append(gauss_m + gauss_L @ eps)
weights.append(torch.stack(W))
# Merge weights and biases in single list.
if net is None:
dists = []
sample = []
for i, wdist in enumerate(weight_dists):
last = i == len(weight_dists) - 1
dists.append(wdist)
sample.append(weights[i])
if not last:
dists.append(bias_dists[i])
sample.append(biases[i])
else:
dists = [None] * len(net.param_shapes)
sample = [None] * len(net.param_shapes)
for i, meta in enumerate(net.param_shapes_meta):
l = meta['layer']
if meta['name'] == 'weight':
dists[i] = weight_dists[l]
sample[i] = weights[l]
else:
dists[i] = bias_dists[l]
sample[i] = biases[l]
if return_dist:
return sample, dists
return sample
def ridgelet_prior_logprob(sample, dists=None, net=None, hidden_widths=None,
phi_name='relu', cube_size=5, grid_points=None,
gp_mean=None, gp_cov=None, sigma2_w=1., sigma2_b=1.):
"""Compute the log-probability of a sample from the Ridgelet prior.
This function computes the logprob of a sample returned by function
:func:`ridgelet_prior_sample`.
Args:
(....): See docstring of function :func:`ridgelet_prior_sample`.
dists (list): If option ``return_dist`` was used to obtain the
``sample`` via function :func:`ridgelet_prior_sample`, then the
returned distributions corresponding to the given ``sample`` can be
passed here.
If ``dists`` is provided, then all other options (except ``sample``)
don't need to be specified.
Note:
Every sample has its own set of distributions generated by
function :func:`ridgelet_prior_sample`!
Returns:
(float): The log-probability :math:`\log p(W)` for the given sample
:math:`W`.
"""
if dists is None:
_, dists = ridgelet_prior_sample(net=net, hidden_widths=hidden_widths,
phi_name=phi_name, cube_size=cube_size, grid_points=grid_points,
gp_mean=gp_mean, gp_cov=gp_cov, sigma2_w=sigma2_w,
sigma2_b=sigma2_b, return_dist=True, sample=sample)
logprob = 0
for i, d in enumerate(dists):
if isinstance(d, Normal):
logprob += d.log_prob(sample[i]).sum()
elif isinstance(d, MultivariateNormal):
# One logprob per neuron (row in sample matrix) is computed.
logprob += d.log_prob(sample[i]).sum()
else:
assert d is None # Bias of output layer.
return logprob
def regular_grid(cube_size=5, res_per_dim=100, grid_dim=1, device=None):
"""Create a regular grid.
This function creates a grid containing points :math:`\mathbf{x}_j` used
for numerical integraion in function :func:`ridgelet_prior_sample`.
Specifically, the return value of this function can be passed as argument
``grid_points`` to :func:`ridgelet_prior_sample`.
Args:
(....): See docstring of function :func:`ridgelet_prior_sample`.
res_per_dim (int): Resolution per dimension. In total, the grid will
have ``res_per_dim**grid_dim`` points.
grid_dim (int): The dimensionality :math:`d` of the grid.
device (optional): The PyTorch device of the return value.
Returns:
(torch.Tensor): A tensor of shape ``[D, grid_dim]``, where ``D`` is the
number of grid points.
"""
x_grid = torch.linspace(-cube_size, cube_size, res_per_dim)
mg = torch.meshgrid([x_grid] * grid_dim)
X = torch.vstack(list(map(torch.ravel, mg))).T
if device is not None:
X = X.to(device)
return X
def _cholesky_noise_adaptive(A):
"""Compute cholesky decomposition of :math:`A`.
Diagonal elements of :math:`A` are perturbed until the matrix becomes
positive definite.
"""
try: # TODO move outside of loop.
L = torch.linalg.cholesky(A)
except:
evs = torch.linalg.eigvalsh(A, UPLO='L')
noise = 1e-5
fail = True
while fail:
try:
L = torch.linalg.cholesky(A + \
(-evs.min() + noise) * torch.eye(A.shape[0]).to(A.device))
fail = False
except:
if noise > 1:
raise RuntimeError('Failed to make kernel matrix ' +
'invertible.')
noise *= 2
warn('Kenel matrix inversion required diagonal noise adaptation ' +
'of scale %f.' % (-evs.min() + noise))
return L
def _ass_func(z, d, phi_name='relu'):
"""Compute the associated function :math:`\psi(z)`.
This function computes the function :math:`\psi(z)` associated to an
activation function :math:`\phi(z)`. See Table 1
`here <https://arxiv.org/abs/2010.08488>`__ for examples.
Args:
z (torch.Tensor): Input :math:`\psi(z)`. The tensor ``z`` nay have
arbitrary shape, but the function :math:`\psi(z)` is applied
elementwise.
d (int): Input dimensionality.
Returns:
(torch.Tensor): Returns the output of :math:`\psi(z)`.
"""
if phi_name not in ['relu', 'tanh']:
raise NotImplementedError()
r = d % 2
def _relu_base(z):
return torch.exp(-z**2 / 2)
def _relu_factor():
return torch.Tensor([-2**(-d/2) * np.pi**(-(d-2*r+1) / 2)])
def _tanh_base(z):
return torch.exp(-z**2 / 2) * torch.sin(np.pi * z / 2)
def _tanh_factor():
return torch.Tensor([2**(-(d+r)/2) * np.pi**(-(d-r+2) / 2) * \
np.exp(np.pi**2 / 8)])
if phi_name == 'relu':
grad_order = d + r + 2
base_func = _relu_base
factor = _relu_factor()
elif phi_name == 'tanh':
grad_order = d - r + 2
base_func = _tanh_base
factor = _tanh_factor()
### Compute n-th derivative.
# grad can only be applied to scalar inputs.
orig_shape = z.shape
z_flat = z.flatten()
z_flat.requires_grad = True
grads = torch.empty_like(z_flat)
for i in range(z_flat.numel()):
x = z_flat[i]
y = base_func(x)
for n in range(grad_order):
last = n == grad_order - 1
grad = torch.autograd.grad(y, x, grad_outputs=None,
retain_graph=not last, create_graph=not last, only_inputs=True,
allow_unused=False)
y = grad[0]
grads[i] = y
grads = grads.reshape(orig_shape)
return factor * grads
def _ass_func_relu_manual(z, d):
"""The associated function :math:`\psi` for a ReLU activation.
This function uses manually computed derivatives and is not generally
applicable.
Args:
(....): See docstring of function :func:`_ass_func`.
Returns:
(torch.Tensor): Returns the output of :math:`\psi(z)`.
"""
r = d % 2
def _base_func(z):
return torch.exp(-z**2 / 2)
def _factor():
return torch.Tensor([-2**(-d/2) * np.pi**(-(d-2*r+1) / 2)])
order = d + r + 2
def _grad_1st(z):
return -z * _base_func(z)
def _grad_2nd(z):
return (z**2 - 1) * _base_func(z)
def _grad_3rd(z):
return (3*z - z**2) * _base_func(z)
def _grad_4th(z):
return (3 - 6*z**2 + z**4) * _base_func(z)
#print(1, _grad_1st(z))
#print(2, _grad_2nd(z))
#print(3, _grad_3rd(z))
#print(4, _grad_4th(z))
if order == 4:
return _grad_4th(z) * _factor()
else:
raise NotImplementedError()
def _ass_func_tanh_manual(z, d):
"""The associated function :math:`\psi` for a Tanh activation.
This function uses manually computed derivatives and is not generally
applicable.
Args:
(....): See docstring of function :func:`_ass_func`.
Returns:
(torch.Tensor): Returns the output of :math:`\psi(z)`.
"""
r = d % 2
def _exp_func(z):
return torch.exp(-z**2 / 2)
def _sin_func(z):
return torch.sin(z * np.pi / 2)
def _cos_func(z):
return torch.cos(z * np.pi / 2)
def _factor():
return torch.Tensor([2**(-(d+r)/2) * np.pi**(-(d-r+2) / 2) * \
np.exp(np.pi**2 / 8)])
order = d - r + 2
def _grad_1st(z):
return _exp_func(z) * (-z * _sin_func(z) + (np.pi / 2) * _cos_func(z))
def _grad_2nd(z):
return _exp_func(z) * (_sin_func(z) * (z**2 - np.pi**2 / 4 - 1) - \
_cos_func(z) * (np.pi * z))
#print(1, _grad_1st(z))
#print(2, _grad_2nd(z))
if order == 2:
return _grad_2nd(z) * _factor()
else:
raise NotImplementedError()
if __name__ == '__main__':
pass
| [
"torch.linalg.cholesky",
"torch.eye",
"torch.stack",
"torch.autograd.grad",
"torch.meshgrid",
"torch.exp",
"torch.Tensor",
"torch.empty_like",
"torch.cos",
"torch.distributions.MultivariateNormal",
"torch.nn.functional.relu",
"torch.zeros",
"torch.linspace",
"torch.linalg.eigvalsh",
"num... | [((12890, 12907), 'numpy.sqrt', 'np.sqrt', (['sigma2_w'], {}), '(sigma2_w)\n', (12897, 12907), True, 'import numpy as np\n'), ((12922, 12939), 'numpy.sqrt', 'np.sqrt', (['sigma2_b'], {}), '(sigma2_b)\n', (12929, 12939), True, 'import numpy as np\n'), ((20397, 20447), 'torch.linspace', 'torch.linspace', (['(-cube_size)', 'cube_size', 'res_per_dim'], {}), '(-cube_size, cube_size, res_per_dim)\n', (20411, 20447), False, 'import torch\n'), ((20458, 20493), 'torch.meshgrid', 'torch.meshgrid', (['([x_grid] * grid_dim)'], {}), '([x_grid] * grid_dim)\n', (20472, 20493), False, 'import torch\n'), ((23016, 23040), 'torch.empty_like', 'torch.empty_like', (['z_flat'], {}), '(z_flat)\n', (23032, 23040), False, 'import torch\n'), ((20855, 20879), 'torch.linalg.cholesky', 'torch.linalg.cholesky', (['A'], {}), '(A)\n', (20876, 20879), False, 'import torch\n'), ((22244, 22266), 'torch.exp', 'torch.exp', (['(-z ** 2 / 2)'], {}), '(-z ** 2 / 2)\n', (22253, 22266), False, 'import torch\n'), ((22305, 22369), 'torch.Tensor', 'torch.Tensor', (['[-2 ** (-d / 2) * np.pi ** (-(d - 2 * r + 1) / 2)]'], {}), '([-2 ** (-d / 2) * np.pi ** (-(d - 2 * r + 1) / 2)])\n', (22317, 22369), False, 'import torch\n'), ((23893, 23915), 'torch.exp', 'torch.exp', (['(-z ** 2 / 2)'], {}), '(-z ** 2 / 2)\n', (23902, 23915), False, 'import torch\n'), ((23949, 24013), 'torch.Tensor', 'torch.Tensor', (['[-2 ** (-d / 2) * np.pi ** (-(d - 2 * r + 1) / 2)]'], {}), '([-2 ** (-d / 2) * np.pi ** (-(d - 2 * r + 1) / 2)])\n', (23961, 24013), False, 'import torch\n'), ((24908, 24930), 'torch.exp', 'torch.exp', (['(-z ** 2 / 2)'], {}), '(-z ** 2 / 2)\n', (24917, 24930), False, 'import torch\n'), ((24967, 24991), 'torch.sin', 'torch.sin', (['(z * np.pi / 2)'], {}), '(z * np.pi / 2)\n', (24976, 24991), False, 'import torch\n'), ((25030, 25054), 'torch.cos', 'torch.cos', (['(z * np.pi / 2)'], {}), '(z * np.pi / 2)\n', (25039, 25054), False, 'import torch\n'), ((20906, 20940), 'torch.linalg.eigvalsh', 'torch.linalg.eigvalsh', (['A'], {'UPLO': '"""L"""'}), "(A, UPLO='L')\n", (20927, 20940), False, 'import torch\n'), ((22397, 22419), 'torch.exp', 'torch.exp', (['(-z ** 2 / 2)'], {}), '(-z ** 2 / 2)\n', (22406, 22419), False, 'import torch\n'), ((22420, 22444), 'torch.sin', 'torch.sin', (['(np.pi * z / 2)'], {}), '(np.pi * z / 2)\n', (22429, 22444), False, 'import torch\n'), ((23218, 23350), 'torch.autograd.grad', 'torch.autograd.grad', (['y', 'x'], {'grad_outputs': 'None', 'retain_graph': '(not last)', 'create_graph': '(not last)', 'only_inputs': '(True)', 'allow_unused': '(False)'}), '(y, x, grad_outputs=None, retain_graph=not last,\n create_graph=not last, only_inputs=True, allow_unused=False)\n', (23237, 23350), False, 'import torch\n'), ((15515, 15542), 'torch.nn.functional.relu', 'torch.nn.functional.relu', (['z'], {}), '(z)\n', (15539, 15542), False, 'import torch\n'), ((16245, 16292), 'torch.distributions.MultivariateNormal', 'MultivariateNormal', (['gauss_m'], {'scale_tril': 'gauss_L'}), '(gauss_m, scale_tril=gauss_L)\n', (16263, 16292), False, 'from torch.distributions import MultivariateNormal, Normal\n'), ((16801, 16815), 'torch.stack', 'torch.stack', (['W'], {}), '(W)\n', (16812, 16815), False, 'import torch\n'), ((13801, 13835), 'torch.zeros', 'torch.zeros', (['[hidden_widths[0], d]'], {}), '([hidden_widths[0], d])\n', (13812, 13835), False, 'import torch\n'), ((13918, 13949), 'torch.zeros', 'torch.zeros', (['[hidden_widths[0]]'], {}), '([hidden_widths[0]])\n', (13929, 13949), False, 'import torch\n'), ((22570, 22592), 'numpy.exp', 'np.exp', (['(np.pi ** 2 / 8)'], {}), '(np.pi ** 2 / 8)\n', (22576, 22592), True, 'import numpy as np\n'), ((25175, 25197), 'numpy.exp', 'np.exp', (['(np.pi ** 2 / 8)'], {}), '(np.pi ** 2 / 8)\n', (25181, 25197), True, 'import numpy as np\n'), ((15171, 15191), 'torch.zeros', 'torch.zeros', (['[n_out]'], {}), '([n_out])\n', (15182, 15191), False, 'import torch\n'), ((15255, 15275), 'torch.zeros', 'torch.zeros', (['[n_out]'], {}), '([n_out])\n', (15266, 15275), False, 'import torch\n'), ((16691, 16705), 'torch.zeros', 'torch.zeros', (['D'], {}), '(D)\n', (16702, 16705), False, 'import torch\n'), ((21110, 21131), 'torch.eye', 'torch.eye', (['A.shape[0]'], {}), '(A.shape[0])\n', (21119, 21131), False, 'import torch\n')] |
"""Class definition for generic convnet labeler."""
import numpy as np
from kaishi.core.pipeline_component import PipelineComponent
from kaishi.image.model import Model
class LabelerGenericConvnet(PipelineComponent):
"""Use pre-trained ConvNet to predict image labels (e.g. stretched, rotated, etc.).
This labeler uses a default configured :class:`kaishi.image.model.Model` object where the output layer is assumed
to have 6 values ranging 0 to 1, where the labels are [DOCUMENT, RECTIFIED, ROTATED_RIGHT, ROTATED_LEFT,
UPSIDE_DOWN, STRETCHED].
"""
def __init__(self):
"""Initialize a new generic convnet labeler component."""
super().__init__()
def __call__(self, dataset):
"""Perform the labeling operation on an image dataset.
:param dataset: kaishi image dataset
:type dataset: :class:`kaishi.image.dataset.ImageDataset`
"""
if dataset.model is None:
dataset.model = Model()
for batch, fobjs in dataset.build_numpy_batches(
batch_size=dataset.model.batch_size
):
pred = dataset.model.predict(batch)
for i in range(len(fobjs)):
if pred[i, 0] > 0.5:
fobjs[i].add_label("DOCUMENT")
rot = np.argmax(pred[i, 1:5])
if rot == 0:
fobjs[i].add_label("RECTIFIED")
elif rot == 1:
fobjs[i].add_label("ROTATED_RIGHT")
elif rot == 2:
fobjs[i].add_label("ROTATED_LEFT")
else:
fobjs[i].add_label("UPSIDE_DOWN")
if pred[i, 5] > 0.5:
fobjs[i].add_label("STRETCHED")
dataset.labeled = True
| [
"kaishi.image.model.Model",
"numpy.argmax"
] | [((973, 980), 'kaishi.image.model.Model', 'Model', ([], {}), '()\n', (978, 980), False, 'from kaishi.image.model import Model\n'), ((1295, 1318), 'numpy.argmax', 'np.argmax', (['pred[i, 1:5]'], {}), '(pred[i, 1:5])\n', (1304, 1318), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
import os
import PIL
import time
from IPython import display
import imageio
import glob
import tensorflow as tf
import matplotlib
# import matplotlib.pyplot as plt
matplotlib.use('Agg')
"""DCGAN_CIFAR10.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/19WOPLPC1Np55ps3-UeT6vZIqq3dmg-HU
**Copyright 2018 The TensorFlow Authors**.
Licensed under the Apache License, Version 2.0 (the "License").
# Generating CIFAR Images with DCGANs
<table class="tfo-notebook-buttons" align="left"><td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/tensorflow/blob/master/tensorflow/contrib/eager/python/examples/generative_examples/dcgan.ipynb">
<img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a>
</td><td>
<a target="_blank" href="https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/eager/python/examples/generative_examples/dcgan.ipynb"><img width=32px src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a></td></table>
"""
# Install imgeio in order to generate an animated gif showing the image generating process
# !pip install imageio
"""### Import TensorFlow and enable eager execution"""
print(tf.__version__)
"""### Load the dataset
We are going to use the MNIST dataset to train the generator and the discriminator. The generator will generate handwritten digits resembling the MNIST data.
"""
# (train_images, train_labels), (_, _) = tf.keras.datasets.mnist.load_data()
(train_images, train_labels), (_, _) = tf.keras.datasets.cifar10.load_data()
print(train_images.shape, train_labels.shape)
train_images = train_images.reshape(
train_images.shape[0], 32, 32, 3).astype('float32')
# train_images = (train_images - 127.5) / 127.5 # Normalize the images to [-1, 1]
train_images = train_images * (2.0 / 255) - 1.0
# print(train_images[0])
BUFFER_SIZE = 50000
BATCH_SIZE = 256
"""### Use tf.data to create batches and shuffle the dataset"""
train_dataset = tf.data.Dataset.from_tensor_slices(
train_images).shuffle(BUFFER_SIZE).batch(BATCH_SIZE)
"""## Create the models
We will use tf.keras [Sequential API](https://www.tensorflow.org/guide/keras#sequential_model) to define the generator and discriminator models.
### The Generator Model
The generator is responsible for creating convincing images that are good enough to fool the discriminator. The network architecture for the generator consists of [Conv2DTranspose](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Conv2DTranspose) (Upsampling) layers. We start with a fully connected layer and upsample the image two times in order to reach the desired image size of 28x28x1. We increase the width and height, and reduce the depth as we move through the layers in the network. We use [Leaky ReLU](https://www.tensorflow.org/api_docs/python/tf/keras/layers/LeakyReLU) activation for each layer except for the last one where we use a tanh activation.
"""
def make_generator_model():
model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(4096, use_bias=False, input_shape=(100,)))
model.add(tf.keras.layers.BatchNormalization())
model.add(tf.keras.layers.LeakyReLU())
model.add(tf.keras.layers.Reshape((4, 4, 256)))
print("Model shape should be (None, 4, 4, 256) -", model.output_shape)
# Note: None is the batch size
assert model.output_shape == (None, 4, 4, 256)
model.add(tf.keras.layers.Conv2DTranspose(
128, (5, 5), strides=(2, 2), padding='same', use_bias=False))
print("Model shape should be (None, 8, 8, 128) -", model.output_shape)
assert model.output_shape == (None, 8, 8, 128)
model.add(tf.keras.layers.BatchNormalization())
model.add(tf.keras.layers.LeakyReLU())
model.add(tf.keras.layers.Conv2DTranspose(
64, (4, 4), strides=(2, 2), padding='same', use_bias=False))
print("Model shape should be (None, 8, 8, 64) -", model.output_shape)
assert model.output_shape == (None, 16, 16, 64)
model.add(tf.keras.layers.BatchNormalization())
model.add(tf.keras.layers.LeakyReLU())
model.add(tf.keras.layers.Conv2DTranspose(3, (4, 4), strides=(
2, 2), padding='same', use_bias=False, activation='tanh'))
assert model.output_shape == (None, 32, 32, 3)
return model
generator = make_generator_model()
"""### The Discriminator model
The discriminator is responsible for distinguishing fake images from real images. It's similar to a regular CNN-based image classifier.
"""
def make_discriminator_model():
model = tf.keras.Sequential()
model.add(tf.keras.layers.Conv2D(
64, (5, 5), strides=(2, 2), padding='same'))
model.add(tf.keras.layers.LeakyReLU())
model.add(tf.keras.layers.Dropout(0.3))
model.add(tf.keras.layers.Conv2D(
128, (5, 5), strides=(2, 2), padding='same'))
model.add(tf.keras.layers.LeakyReLU())
model.add(tf.keras.layers.Dropout(0.3))
model.add(tf.keras.layers.Conv2D(
256, (5, 5), strides=(2, 2), padding='same'))
model.add(tf.keras.layers.LeakyReLU())
model.add(tf.keras.layers.Dropout(0.3))
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(1))
return model
discriminator = make_discriminator_model()
"""## Define the loss functions and the optimizer
Let's define the loss functions and the optimizers for the generator and the discriminator.
### Generator loss
The generator loss is a sigmoid cross entropy loss of the generated images and an array of ones, since the generator is trying to generate fake images that resemble the real images.
"""
def generator_loss(generated_output):
return tf.compat.v1.losses.sigmoid_cross_entropy(tf.ones_like(generated_output), generated_output)
"""### Discriminator loss
The discriminator loss function takes two inputs: real images, and generated images. Here is how to calculate the discriminator loss:
1. Calculate real_loss which is a sigmoid cross entropy loss of the real images and an array of ones (since these are the real images).
2. Calculate generated_loss which is a sigmoid cross entropy loss of the generated images and an array of zeros (since these are the fake images).
3. Calculate the total_loss as the sum of real_loss and generated_loss.
"""
def discriminator_loss(real_output, generated_output):
# [1,1,...,1] with real output since it is true and we want our generated examples to look like it
real_loss = tf.compat.v1.losses.sigmoid_cross_entropy(
multi_class_labels=tf.ones_like(real_output), logits=real_output)
# [0,0,...,0] with generated images since they are fake
generated_loss = tf.compat.v1.losses.sigmoid_cross_entropy(
multi_class_labels=tf.zeros_like(generated_output), logits=generated_output)
total_loss = real_loss + generated_loss
return total_loss
"""The discriminator and the generator optimizers are different since we will train two networks separately."""
generator_optimizer = tf.compat.v1.train.AdamOptimizer(1e-4)
discriminator_optimizer = tf.compat.v1.train.AdamOptimizer(1e-4)
"""**Checkpoints (Object-based saving)**"""
checkpoint_dir = './training_checkpoints_cifar'
checkpoint_prefix = os.path.join(checkpoint_dir, "ckpt")
checkpoint = tf.train.Checkpoint(generator_optimizer=generator_optimizer,
discriminator_optimizer=discriminator_optimizer,
generator=generator,
discriminator=discriminator)
"""## Set up GANs for Training
Now it's time to put together the generator and discriminator to set up the Generative Adversarial Networks, as you see in the diagam at the beginning of the tutorial.
**Define training parameters**
"""
EPOCHS = 400
noise_dim = 100
num_examples_to_generate = 16
# We'll re-use this random vector used to seed the generator so
# it will be easier to see the improvement over time.
random_vector_for_generation = tf.random.normal([num_examples_to_generate,
noise_dim])
"""**Define training method**
We start by iterating over the dataset. The generator is given a random vector as an input which is processed to output an image looking like a handwritten digit. The discriminator is then shown the real MNIST images as well as the generated images.
Next, we calculate the generator and the discriminator loss. Then, we calculate the gradients of loss with respect to both the generator and the discriminator variables.
"""
def train_step(images):
# generating noise from a normal distribution
noise = tf.random.normal([BATCH_SIZE, noise_dim])
with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape:
generated_images = generator(noise, training=True)
real_output = discriminator(images, training=True)
generated_output = discriminator(generated_images, training=True)
gen_loss = generator_loss(generated_output)
disc_loss = discriminator_loss(real_output, generated_output)
gradients_of_generator = gen_tape.gradient(gen_loss, generator.variables)
gradients_of_discriminator = disc_tape.gradient(
disc_loss, discriminator.variables)
generator_optimizer.apply_gradients(
zip(gradients_of_generator, generator.variables))
discriminator_optimizer.apply_gradients(
zip(gradients_of_discriminator, discriminator.variables))
"""This model takes about ~30 seconds per epoch to train on a single Tesla K80 on Colab, as of October 2018.
Eager execution can be slower than executing the equivalent graph as it can't benefit from whole-program optimizations on the graph, and also incurs overheads of interpreting Python code. By using [tf.contrib.eager.defun](https://www.tensorflow.org/api_docs/python/tf/contrib/eager/defun) to create graph functions, we get a ~20 secs/epoch performance boost (from ~50 secs/epoch down to ~30 secs/epoch). This way we get the best of both eager execution (easier for debugging) and graph mode (better performance).
"""
# train_step = tf.contrib.eager.defun(train_step)
def train(dataset, epochs):
for epoch in range(epochs):
start = time.time()
for images in dataset:
train_step(images)
display.clear_output(wait=True)
generate_and_save_images(generator,
epoch + 1,
random_vector_for_generation)
# saving (checkpoint) the model every 15 epochs
if (epoch + 1) % 15 == 0:
checkpoint.save(file_prefix=checkpoint_prefix)
print('Time taken for epoch {} is {} sec'.format(epoch + 1,
time.time()-start))
# generating after the final epoch
display.clear_output(wait=True)
generate_and_save_images(generator,
epochs,
random_vector_for_generation)
"""**Generate and save images**"""
def generate_and_save_images(model, epoch, test_input):
#
# make sure the training parameter is set to False because we
# don't want to train the batchnorm layer when doing inference.
predictions = model(test_input, training=False)
fig = plt.figure(figsize=(8, 8))
for i in range(predictions.shape[0]):
plt.subplot(4, 4, i+1)
predi = convert_array_to_image(predictions[i])
plt.imshow(predi)
plt.axis('off')
plt.savefig("images/" + 'image_at_epoch_{:04d}.png'.format(epoch))
plt.show()
def convert_array_to_image(array):
"""Converts a numpy array to a PIL Image and undoes any rescaling."""
img = PIL.Image.fromarray(np.uint8((array + 1.0) / 2.0 * 255), mode='RGB')
return img
pred = generator(random_vector_for_generation, training=False)
generate_and_save_images(generator, 1, random_vector_for_generation)
# print(pred[0].shape)
# predi = convert_array_to_image(pred[0])
# plt.imshow(predi)
# plt.show()
"""## Train the GANs
We will call the train() method defined above to train the generator and discriminator simultaneously. Note, training GANs can be tricky. It's important that the generator and discriminator do not overpower each other (e.g., that they train at a similar rate).
At the beginning of the training, the generated images look like random noise. As training progresses, you can see the generated digits look increasingly real. After 50 epochs, they look very much like the MNIST digits.
**Restore the latest checkpoint**
"""
checkpoint.restore(tf.train.latest_checkpoint(checkpoint_dir))
print("Num epochs", EPOCHS)
train(train_dataset, EPOCHS)
# restoring the latest checkpoint in checkpoint_dir
"""## Generated images
After training, its time to generate some images!
The last step is to plot the generated images and voila!
"""
# Display a single image using the epoch number
def display_image(epoch_no):
return PIL.Image.open('image_at_epoch_{:04d}.png'.format(epoch_no))
# display_image(EPOCHS)
"""**Generate a GIF of all the saved images**
We will use imageio to create an animated gif using all the images saved during training.
"""
with imageio.get_writer('dcgan.gif', mode='I') as writer:
filenames = glob.glob('image*.png')
filenames = sorted(filenames)
last = -1
for i, filename in enumerate(filenames):
frame = 2*(i**0.5)
if round(frame) > round(last):
last = frame
else:
continue
image = imageio.imread(filename)
writer.append_data(image)
image = imageio.imread(filename)
writer.append_data(image)
# this is a hack to display the gif inside the notebook
os.system('cp dcgan.gif dcgan.gif.png')
"""Display the animated gif with all the mages generated during the training of GANs."""
# display.Image(filename="dcgan.gif.png")
"""**Download the animated gif**
Uncomment the code below to download an animated gif from Colab.
"""
#from google.colab import files
# files.download('dcgan.gif')
"""## Learn more about GANs
We hope this tutorial was helpful! As a next step, you might like to experiment with a different dataset, for example the Large-scale Celeb Faces Attributes (CelebA) dataset [available on Kaggle](https://www.kaggle.com/jessicali9530/celeba-dataset/home).
To learn more about GANs:
* Check out MIT's lecture (linked above), or [this](http://cs231n.stanford.edu/slides/2018/cs231n_2018_lecture12.pdf) lecture form Stanford's CS231n.
* We also recommend the [CVPR 2018 Tutorial on GANs](https://sites.google.com/view/cvpr2018tutorialongans/), and the [NIPS 2016 Tutorial: Generative Adversarial Networks](https://arxiv.org/abs/1701.00160).
"""
| [
"tensorflow.keras.layers.Reshape",
"tensorflow.keras.layers.Dense",
"tensorflow.zeros_like",
"tensorflow.keras.layers.LeakyReLU",
"matplotlib.pyplot.figure",
"tensorflow.train.latest_checkpoint",
"tensorflow.keras.Sequential",
"glob.glob",
"os.path.join",
"tensorflow.keras.layers.Flatten",
"tens... | [((241, 262), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (255, 262), False, 'import matplotlib\n'), ((1697, 1734), 'tensorflow.keras.datasets.cifar10.load_data', 'tf.keras.datasets.cifar10.load_data', ([], {}), '()\n', (1732, 1734), True, 'import tensorflow as tf\n'), ((7138, 7178), 'tensorflow.compat.v1.train.AdamOptimizer', 'tf.compat.v1.train.AdamOptimizer', (['(0.0001)'], {}), '(0.0001)\n', (7170, 7178), True, 'import tensorflow as tf\n'), ((7203, 7243), 'tensorflow.compat.v1.train.AdamOptimizer', 'tf.compat.v1.train.AdamOptimizer', (['(0.0001)'], {}), '(0.0001)\n', (7235, 7243), True, 'import tensorflow as tf\n'), ((7356, 7392), 'os.path.join', 'os.path.join', (['checkpoint_dir', '"""ckpt"""'], {}), "(checkpoint_dir, 'ckpt')\n", (7368, 7392), False, 'import os\n'), ((7406, 7573), 'tensorflow.train.Checkpoint', 'tf.train.Checkpoint', ([], {'generator_optimizer': 'generator_optimizer', 'discriminator_optimizer': 'discriminator_optimizer', 'generator': 'generator', 'discriminator': 'discriminator'}), '(generator_optimizer=generator_optimizer,\n discriminator_optimizer=discriminator_optimizer, generator=generator,\n discriminator=discriminator)\n', (7425, 7573), True, 'import tensorflow as tf\n'), ((8112, 8167), 'tensorflow.random.normal', 'tf.random.normal', (['[num_examples_to_generate, noise_dim]'], {}), '([num_examples_to_generate, noise_dim])\n', (8128, 8167), True, 'import tensorflow as tf\n'), ((13836, 13875), 'os.system', 'os.system', (['"""cp dcgan.gif dcgan.gif.png"""'], {}), "('cp dcgan.gif dcgan.gif.png')\n", (13845, 13875), False, 'import os\n'), ((3163, 3184), 'tensorflow.keras.Sequential', 'tf.keras.Sequential', ([], {}), '()\n', (3182, 3184), True, 'import tensorflow as tf\n'), ((4710, 4731), 'tensorflow.keras.Sequential', 'tf.keras.Sequential', ([], {}), '()\n', (4729, 4731), True, 'import tensorflow as tf\n'), ((8762, 8803), 'tensorflow.random.normal', 'tf.random.normal', (['[BATCH_SIZE, noise_dim]'], {}), '([BATCH_SIZE, noise_dim])\n', (8778, 8803), True, 'import tensorflow as tf\n'), ((10945, 10976), 'IPython.display.clear_output', 'display.clear_output', ([], {'wait': '(True)'}), '(wait=True)\n', (10965, 10976), False, 'from IPython import display\n'), ((11411, 11437), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 8)'}), '(figsize=(8, 8))\n', (11421, 11437), True, 'import matplotlib.pyplot as plt\n'), ((11693, 11703), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (11701, 11703), True, 'import matplotlib.pyplot as plt\n'), ((12706, 12748), 'tensorflow.train.latest_checkpoint', 'tf.train.latest_checkpoint', (['checkpoint_dir'], {}), '(checkpoint_dir)\n', (12732, 12748), True, 'import tensorflow as tf\n'), ((13325, 13366), 'imageio.get_writer', 'imageio.get_writer', (['"""dcgan.gif"""'], {'mode': '"""I"""'}), "('dcgan.gif', mode='I')\n", (13343, 13366), False, 'import imageio\n'), ((13394, 13417), 'glob.glob', 'glob.glob', (['"""image*.png"""'], {}), "('image*.png')\n", (13403, 13417), False, 'import glob\n'), ((13724, 13748), 'imageio.imread', 'imageio.imread', (['filename'], {}), '(filename)\n', (13738, 13748), False, 'import imageio\n'), ((3199, 3262), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['(4096)'], {'use_bias': '(False)', 'input_shape': '(100,)'}), '(4096, use_bias=False, input_shape=(100,))\n', (3220, 3262), True, 'import tensorflow as tf\n'), ((3278, 3314), 'tensorflow.keras.layers.BatchNormalization', 'tf.keras.layers.BatchNormalization', ([], {}), '()\n', (3312, 3314), True, 'import tensorflow as tf\n'), ((3330, 3357), 'tensorflow.keras.layers.LeakyReLU', 'tf.keras.layers.LeakyReLU', ([], {}), '()\n', (3355, 3357), True, 'import tensorflow as tf\n'), ((3374, 3410), 'tensorflow.keras.layers.Reshape', 'tf.keras.layers.Reshape', (['(4, 4, 256)'], {}), '((4, 4, 256))\n', (3397, 3410), True, 'import tensorflow as tf\n'), ((3588, 3684), 'tensorflow.keras.layers.Conv2DTranspose', 'tf.keras.layers.Conv2DTranspose', (['(128)', '(5, 5)'], {'strides': '(2, 2)', 'padding': '"""same"""', 'use_bias': '(False)'}), "(128, (5, 5), strides=(2, 2), padding='same',\n use_bias=False)\n", (3619, 3684), True, 'import tensorflow as tf\n'), ((3831, 3867), 'tensorflow.keras.layers.BatchNormalization', 'tf.keras.layers.BatchNormalization', ([], {}), '()\n', (3865, 3867), True, 'import tensorflow as tf\n'), ((3883, 3910), 'tensorflow.keras.layers.LeakyReLU', 'tf.keras.layers.LeakyReLU', ([], {}), '()\n', (3908, 3910), True, 'import tensorflow as tf\n'), ((3927, 4022), 'tensorflow.keras.layers.Conv2DTranspose', 'tf.keras.layers.Conv2DTranspose', (['(64)', '(4, 4)'], {'strides': '(2, 2)', 'padding': '"""same"""', 'use_bias': '(False)'}), "(64, (4, 4), strides=(2, 2), padding='same',\n use_bias=False)\n", (3958, 4022), True, 'import tensorflow as tf\n'), ((4169, 4205), 'tensorflow.keras.layers.BatchNormalization', 'tf.keras.layers.BatchNormalization', ([], {}), '()\n', (4203, 4205), True, 'import tensorflow as tf\n'), ((4221, 4248), 'tensorflow.keras.layers.LeakyReLU', 'tf.keras.layers.LeakyReLU', ([], {}), '()\n', (4246, 4248), True, 'import tensorflow as tf\n'), ((4265, 4378), 'tensorflow.keras.layers.Conv2DTranspose', 'tf.keras.layers.Conv2DTranspose', (['(3)', '(4, 4)'], {'strides': '(2, 2)', 'padding': '"""same"""', 'use_bias': '(False)', 'activation': '"""tanh"""'}), "(3, (4, 4), strides=(2, 2), padding='same',\n use_bias=False, activation='tanh')\n", (4296, 4378), True, 'import tensorflow as tf\n'), ((4746, 4812), 'tensorflow.keras.layers.Conv2D', 'tf.keras.layers.Conv2D', (['(64)', '(5, 5)'], {'strides': '(2, 2)', 'padding': '"""same"""'}), "(64, (5, 5), strides=(2, 2), padding='same')\n", (4768, 4812), True, 'import tensorflow as tf\n'), ((4837, 4864), 'tensorflow.keras.layers.LeakyReLU', 'tf.keras.layers.LeakyReLU', ([], {}), '()\n', (4862, 4864), True, 'import tensorflow as tf\n'), ((4880, 4908), 'tensorflow.keras.layers.Dropout', 'tf.keras.layers.Dropout', (['(0.3)'], {}), '(0.3)\n', (4903, 4908), True, 'import tensorflow as tf\n'), ((4925, 4992), 'tensorflow.keras.layers.Conv2D', 'tf.keras.layers.Conv2D', (['(128)', '(5, 5)'], {'strides': '(2, 2)', 'padding': '"""same"""'}), "(128, (5, 5), strides=(2, 2), padding='same')\n", (4947, 4992), True, 'import tensorflow as tf\n'), ((5017, 5044), 'tensorflow.keras.layers.LeakyReLU', 'tf.keras.layers.LeakyReLU', ([], {}), '()\n', (5042, 5044), True, 'import tensorflow as tf\n'), ((5060, 5088), 'tensorflow.keras.layers.Dropout', 'tf.keras.layers.Dropout', (['(0.3)'], {}), '(0.3)\n', (5083, 5088), True, 'import tensorflow as tf\n'), ((5105, 5172), 'tensorflow.keras.layers.Conv2D', 'tf.keras.layers.Conv2D', (['(256)', '(5, 5)'], {'strides': '(2, 2)', 'padding': '"""same"""'}), "(256, (5, 5), strides=(2, 2), padding='same')\n", (5127, 5172), True, 'import tensorflow as tf\n'), ((5197, 5224), 'tensorflow.keras.layers.LeakyReLU', 'tf.keras.layers.LeakyReLU', ([], {}), '()\n', (5222, 5224), True, 'import tensorflow as tf\n'), ((5240, 5268), 'tensorflow.keras.layers.Dropout', 'tf.keras.layers.Dropout', (['(0.3)'], {}), '(0.3)\n', (5263, 5268), True, 'import tensorflow as tf\n'), ((5285, 5310), 'tensorflow.keras.layers.Flatten', 'tf.keras.layers.Flatten', ([], {}), '()\n', (5308, 5310), True, 'import tensorflow as tf\n'), ((5326, 5350), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['(1)'], {}), '(1)\n', (5347, 5350), True, 'import tensorflow as tf\n'), ((5858, 5888), 'tensorflow.ones_like', 'tf.ones_like', (['generated_output'], {}), '(generated_output)\n', (5870, 5888), True, 'import tensorflow as tf\n'), ((8814, 8831), 'tensorflow.GradientTape', 'tf.GradientTape', ([], {}), '()\n', (8829, 8831), True, 'import tensorflow as tf\n'), ((8845, 8862), 'tensorflow.GradientTape', 'tf.GradientTape', ([], {}), '()\n', (8860, 8862), True, 'import tensorflow as tf\n'), ((10339, 10350), 'time.time', 'time.time', ([], {}), '()\n', (10348, 10350), False, 'import time\n'), ((10423, 10454), 'IPython.display.clear_output', 'display.clear_output', ([], {'wait': '(True)'}), '(wait=True)\n', (10443, 10454), False, 'from IPython import display\n'), ((11489, 11513), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(4)', '(4)', '(i + 1)'], {}), '(4, 4, i + 1)\n', (11500, 11513), True, 'import matplotlib.pyplot as plt\n'), ((11575, 11592), 'matplotlib.pyplot.imshow', 'plt.imshow', (['predi'], {}), '(predi)\n', (11585, 11592), True, 'import matplotlib.pyplot as plt\n'), ((11601, 11616), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (11609, 11616), True, 'import matplotlib.pyplot as plt\n'), ((11845, 11880), 'numpy.uint8', 'np.uint8', (['((array + 1.0) / 2.0 * 255)'], {}), '((array + 1.0) / 2.0 * 255)\n', (11853, 11880), True, 'import numpy as np\n'), ((13653, 13677), 'imageio.imread', 'imageio.imread', (['filename'], {}), '(filename)\n', (13667, 13677), False, 'import imageio\n'), ((6676, 6701), 'tensorflow.ones_like', 'tf.ones_like', (['real_output'], {}), '(real_output)\n', (6688, 6701), True, 'import tensorflow as tf\n'), ((6875, 6906), 'tensorflow.zeros_like', 'tf.zeros_like', (['generated_output'], {}), '(generated_output)\n', (6888, 6906), True, 'import tensorflow as tf\n'), ((2152, 2200), 'tensorflow.data.Dataset.from_tensor_slices', 'tf.data.Dataset.from_tensor_slices', (['train_images'], {}), '(train_images)\n', (2186, 2200), True, 'import tensorflow as tf\n'), ((10882, 10893), 'time.time', 'time.time', ([], {}), '()\n', (10891, 10893), False, 'import time\n')] |
import argparse
import csv
from PIL import Image
from tqdm import tqdm
from random import randint
import numpy as np
import os
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument("--file", help="The CSV file to read and extract GPS coordinates from", required=True, type=str)
parser.add_argument("--images", help="The path to the images folder, (defaults to: images/)", default='images/', type=str)
parser.add_argument("--output", help="The output folder", required=True, type=str)
return parser.parse_args()
args = get_args()
targets_train = []
targets_val = []
def multi_label(num, decimals=4):
num_original = str(abs(float(num)))
if decimals > 0:
num = str(round(float(num) * (10 ** decimals)))
else:
num = str(round(float(num)))
if num[0] == '-':
label = np.array([1])
num = num[1:]
else:
label = np.array([0])
num = num.ljust(len(num_original.split('.')[0]) + decimals, '0')
num = num.zfill(decimals + 3)
for digit in num:
label = np.concatenate((label, np.eye(10)[int(digit)]))
return label
def get_data(coord, coord_index):
lat, lon = coord[0], coord[1]
img_path = os.path.join(args.images, f'street_view_{coord_index}.jpg')
img = Image.open(img_path)
lat_multi_label = multi_label(lat)
lon_multi_label = multi_label(lon)
target = np.concatenate((lat_multi_label, lon_multi_label))
return [img, target]
def main():
with open(args.file, 'r') as f:
coords_reader = csv.reader(f)
coords = []
for row in coords_reader:
coords.append(row)
train_data_path = os.path.join(args.output, 'train')
os.makedirs(train_data_path, exist_ok=True)
val_data_path = os.path.join(args.output, 'val')
os.makedirs(val_data_path, exist_ok=True)
val_count = 0
train_count = 0
for coord_index, coord in enumerate(tqdm(coords)):
if randint(0, 9) == 0:
data = get_data(coord, coord_index)
val_data_path = os.path.join(args.output, f'val/street_view_{val_count}.jpg')
data[0].save(val_data_path)
targets_val.append(data[1])
val_count += 1
else:
data = get_data(coord, coord_index)
train_data_path = os.path.join(args.output, f'train/street_view_{train_count}.jpg')
data[0].save(train_data_path)
targets_train.append(data[1])
train_count += 1
np.save(os.path.join(args.output, f'train/targets.npy'), np.array(targets_train))
np.save(os.path.join(args.output, f'val/targets.npy'), np.array(targets_val))
print('Train Files:', train_count)
print('Val Files:', val_count)
if __name__ == '__main__':
main()
| [
"tqdm.tqdm",
"csv.reader",
"os.makedirs",
"argparse.ArgumentParser",
"random.randint",
"PIL.Image.open",
"numpy.array",
"numpy.eye",
"os.path.join",
"numpy.concatenate"
] | [((157, 182), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (180, 182), False, 'import argparse\n'), ((1234, 1293), 'os.path.join', 'os.path.join', (['args.images', 'f"""street_view_{coord_index}.jpg"""'], {}), "(args.images, f'street_view_{coord_index}.jpg')\n", (1246, 1293), False, 'import os\n'), ((1304, 1324), 'PIL.Image.open', 'Image.open', (['img_path'], {}), '(img_path)\n', (1314, 1324), False, 'from PIL import Image\n'), ((1426, 1476), 'numpy.concatenate', 'np.concatenate', (['(lat_multi_label, lon_multi_label)'], {}), '((lat_multi_label, lon_multi_label))\n', (1440, 1476), True, 'import numpy as np\n'), ((1707, 1741), 'os.path.join', 'os.path.join', (['args.output', '"""train"""'], {}), "(args.output, 'train')\n", (1719, 1741), False, 'import os\n'), ((1746, 1789), 'os.makedirs', 'os.makedirs', (['train_data_path'], {'exist_ok': '(True)'}), '(train_data_path, exist_ok=True)\n', (1757, 1789), False, 'import os\n'), ((1810, 1842), 'os.path.join', 'os.path.join', (['args.output', '"""val"""'], {}), "(args.output, 'val')\n", (1822, 1842), False, 'import os\n'), ((1847, 1888), 'os.makedirs', 'os.makedirs', (['val_data_path'], {'exist_ok': '(True)'}), '(val_data_path, exist_ok=True)\n', (1858, 1888), False, 'import os\n'), ((848, 861), 'numpy.array', 'np.array', (['[1]'], {}), '([1])\n', (856, 861), True, 'import numpy as np\n'), ((910, 923), 'numpy.array', 'np.array', (['[0]'], {}), '([0])\n', (918, 923), True, 'import numpy as np\n'), ((1580, 1593), 'csv.reader', 'csv.reader', (['f'], {}), '(f)\n', (1590, 1593), False, 'import csv\n'), ((1977, 1989), 'tqdm.tqdm', 'tqdm', (['coords'], {}), '(coords)\n', (1981, 1989), False, 'from tqdm import tqdm\n'), ((2556, 2603), 'os.path.join', 'os.path.join', (['args.output', 'f"""train/targets.npy"""'], {}), "(args.output, f'train/targets.npy')\n", (2568, 2603), False, 'import os\n'), ((2605, 2628), 'numpy.array', 'np.array', (['targets_train'], {}), '(targets_train)\n', (2613, 2628), True, 'import numpy as np\n'), ((2642, 2687), 'os.path.join', 'os.path.join', (['args.output', 'f"""val/targets.npy"""'], {}), "(args.output, f'val/targets.npy')\n", (2654, 2687), False, 'import os\n'), ((2689, 2710), 'numpy.array', 'np.array', (['targets_val'], {}), '(targets_val)\n', (2697, 2710), True, 'import numpy as np\n'), ((2003, 2016), 'random.randint', 'randint', (['(0)', '(9)'], {}), '(0, 9)\n', (2010, 2016), False, 'from random import randint\n'), ((2099, 2160), 'os.path.join', 'os.path.join', (['args.output', 'f"""val/street_view_{val_count}.jpg"""'], {}), "(args.output, f'val/street_view_{val_count}.jpg')\n", (2111, 2160), False, 'import os\n'), ((2360, 2425), 'os.path.join', 'os.path.join', (['args.output', 'f"""train/street_view_{train_count}.jpg"""'], {}), "(args.output, f'train/street_view_{train_count}.jpg')\n", (2372, 2425), False, 'import os\n'), ((1098, 1108), 'numpy.eye', 'np.eye', (['(10)'], {}), '(10)\n', (1104, 1108), True, 'import numpy as np\n')] |
import argparse
import random
import threading
import time
from yattag import Doc
import cv2
import mss
import numpy as np
import os
from util import autolog, drop
from util.core import client, keyboard, mouse
from util.core.ssd.ssd_inference import SSD
parser = argparse.ArgumentParser(description = 'Debug')
parser.add_argument('--r', type = bool, help='record', default=False)
args = parser.parse_args()
record_debug = args.r
osclient = client.Client()
box = osclient.box
# rock_labels = {
# 0: 'none',
# 1:'depleted',
# 2:'bankchest',
# 3:'depositbox',
# 4:'amethyst' ,
# 5:'mithril' ,
# 6:'adamantite' ,
# 8:'coal' ,
# 9:'iron' ,
# 15: 'spooky_ghost'
#
# }
astrals_labels = {
0: 'none',
1:'bank',
2:'banker',
3:'astral_altar',
4: 'amethyst',
5: 'mithril',
6: 'adamantite',
8: 'coal',
9: 'iron',
15: 'spooky_ghost'
}
sct = mss.mss()
ssd_inference= SSD(ckpt_filename= '/home/walter/Documents/others_git/SSD-Tensorflow/checkpoints/astrals/astrals_model.ckpt', n_classes=3)
def visualize_box(img, rclasses, rscores, rbboxes, labels=astrals_labels):
for ind, box in enumerate(rbboxes):
topleft = (int(box[1] * img.shape[1]), int(box[0] * img.shape[0]))
botright = (int(box[3] * img.shape[1]), int(box[2] * img.shape[0]))
area = (botright[0] - topleft[0]) * (botright[1] - topleft[1])
if area> 0: #area > 3000:
img = cv2.putText(img, str(labels[rclasses[ind]])+": "+ str(np.round(rscores[ind], decimals=2)),
topleft, cv2.FONT_HERSHEY_SIMPLEX, .4, (255, 255, 255), 1, cv2.LINE_AA)
img = cv2.rectangle(img, topleft, botright, (0, 255, 0), 1)
return img
def get_client_debug():
img = np.array(sct.grab(box))[:, :, :-1]
img = np.array(img)
rclasses, rscores, rbboxes = ssd_inference.process_image(img, select_threshold=.8)
client_img = visualize_box(img, rclasses, rscores, rbboxes, labels=astrals_labels)
return client_img
def generate_xml(filename, img_path, annotation_path=os.path.join(os.path.dirname(__file__), "training_data/astrals/Annotations/")):
img = np.array(sct.grab(osclient.box))[:, :, :-1]
img = np.array(img)
rcenter = []
rclasses, rscores, rbboxes = ssd_inference.process_image(img)
doc, tag, text = Doc().tagtext()
with tag('annotation'):
with tag('folder'):
text('JPEGImages')
with tag('filename'):
text(filename+'.png')
with tag('path'):
text(img_path)
with tag('source'):
with tag('database'):
text('Unknown')
with tag('size'):
with tag('width'):
text(img.shape[1])
with tag('height'):
text(img.shape[0])
with tag('depth'):
text('3')
with tag('segmented'):
text('0')
for ind, box in enumerate(rbboxes):
with tag('object'):
with tag('name'):
text(labels[rclasses[ind]])
with tag('pose'):
text('Unspecified')
with tag('truncated'):
text('0')
with tag('difficult'):
text('0')
with tag('bndbox'):
with tag('xmin'):
text(str(int(box[1] * img.shape[1])))
with tag('ymin'):
text(str(int(box[0] * img.shape[0])))
with tag('xmax'):
text(str(int(box[3] * img.shape[1])))
with tag('ymax'):
text(str(int(box[2] * img.shape[0])))
xml_path = os.path.join(annotation_path, filename + '.xml')
with open(xml_path, 'w') as f:
f.write(doc.getvalue())
return rclasses, rbboxes, rcenter
def debug_thread():
if record_debug:
fourcc = cv2.VideoWriter_fourcc(*'DIVX')
out = cv2.VideoWriter('rocks_debug.mp4', fourcc, 15.0, (osclient.box['width'], osclient.box['height']))
while 1:
frame = get_client_debug()
cv2.imshow('pybot', frame)
if record_debug:
out.write(frame)
if cv2.waitKey(25) & 0xFF == ord('q'):
cv2.destroyAllWindows()
break
if __name__ == '__main__':
debug_thread()
| [
"argparse.ArgumentParser",
"cv2.VideoWriter_fourcc",
"cv2.waitKey",
"cv2.destroyAllWindows",
"os.path.dirname",
"cv2.imshow",
"yattag.Doc",
"cv2.rectangle",
"mss.mss",
"numpy.array",
"cv2.VideoWriter",
"numpy.round",
"util.core.client.Client",
"os.path.join",
"util.core.ssd.ssd_inference... | [((265, 309), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Debug"""'}), "(description='Debug')\n", (288, 309), False, 'import argparse\n'), ((444, 459), 'util.core.client.Client', 'client.Client', ([], {}), '()\n', (457, 459), False, 'from util.core import client, keyboard, mouse\n'), ((916, 925), 'mss.mss', 'mss.mss', ([], {}), '()\n', (923, 925), False, 'import mss\n'), ((942, 1073), 'util.core.ssd.ssd_inference.SSD', 'SSD', ([], {'ckpt_filename': '"""/home/walter/Documents/others_git/SSD-Tensorflow/checkpoints/astrals/astrals_model.ckpt"""', 'n_classes': '(3)'}), "(ckpt_filename=\n '/home/walter/Documents/others_git/SSD-Tensorflow/checkpoints/astrals/astrals_model.ckpt'\n , n_classes=3)\n", (945, 1073), False, 'from util.core.ssd.ssd_inference import SSD\n'), ((1809, 1822), 'numpy.array', 'np.array', (['img'], {}), '(img)\n', (1817, 1822), True, 'import numpy as np\n'), ((2217, 2230), 'numpy.array', 'np.array', (['img'], {}), '(img)\n', (2225, 2230), True, 'import numpy as np\n'), ((3742, 3790), 'os.path.join', 'os.path.join', (['annotation_path', "(filename + '.xml')"], {}), "(annotation_path, filename + '.xml')\n", (3754, 3790), False, 'import os\n'), ((2086, 2111), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (2101, 2111), False, 'import os\n'), ((3955, 3986), 'cv2.VideoWriter_fourcc', 'cv2.VideoWriter_fourcc', (["*'DIVX'"], {}), "(*'DIVX')\n", (3977, 3986), False, 'import cv2\n'), ((4001, 4102), 'cv2.VideoWriter', 'cv2.VideoWriter', (['"""rocks_debug.mp4"""', 'fourcc', '(15.0)', "(osclient.box['width'], osclient.box['height'])"], {}), "('rocks_debug.mp4', fourcc, 15.0, (osclient.box['width'],\n osclient.box['height']))\n", (4016, 4102), False, 'import cv2\n'), ((4155, 4181), 'cv2.imshow', 'cv2.imshow', (['"""pybot"""', 'frame'], {}), "('pybot', frame)\n", (4165, 4181), False, 'import cv2\n'), ((1659, 1712), 'cv2.rectangle', 'cv2.rectangle', (['img', 'topleft', 'botright', '(0, 255, 0)', '(1)'], {}), '(img, topleft, botright, (0, 255, 0), 1)\n', (1672, 1712), False, 'import cv2\n'), ((2337, 2342), 'yattag.Doc', 'Doc', ([], {}), '()\n', (2340, 2342), False, 'from yattag import Doc\n'), ((4295, 4318), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (4316, 4318), False, 'import cv2\n'), ((4247, 4262), 'cv2.waitKey', 'cv2.waitKey', (['(25)'], {}), '(25)\n', (4258, 4262), False, 'import cv2\n'), ((1508, 1542), 'numpy.round', 'np.round', (['rscores[ind]'], {'decimals': '(2)'}), '(rscores[ind], decimals=2)\n', (1516, 1542), True, 'import numpy as np\n')] |
import numpy as np
import cv2
import os
# from tabulate import tabulate
import classifier
from PIL import Image
from kafka import KafkaConsumer
from json import loads
import pickle
import logging
import time
import pymongo
import sys
import yaml
time.sleep(10)
print('--------------------------------------')
path_of_script = os.path.dirname(os.path.realpath(__file__))
def car_rec(image,confidence=0.5,threshold=0.3):
car_color_classifier = classifier.Classifier()
labelsPath = (os.path.join(path_of_script,"coco.names"))
weightsPath = (os.path.join(path_of_script,"yolov3.weights"))
configPath = (os.path.join(path_of_script,"yolov3.cfg"))
LABELS = open(labelsPath).read().strip().split("\n")
# load our YOLO object detector trained on COCO dataset (80 classes)
net = cv2.dnn.readNetFromDarknet(configPath, weightsPath)
# load our input image and grab its spatial dimensions
(H, W) = image.shape[:2]
# determine only the output layer names that we need from YOLO
layer_names = net.getLayerNames()
output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
# construct a blob from the input image and then perform a forward
# pass of the YOLO object detector, giving us our bounding boxes and
# associated probabilities
blob = cv2.dnn.blobFromImage(image, 1 / 255.0, (416, 416), swapRB=True, crop=False)
net.setInput(blob)
outputs = net.forward(output_layers)
# initialize our lists of detected bounding boxes, confidences, and
# class IDs, results, respectively
boxes = []
confidences = []
classIDs = []
results = []
# loop over each of the layer outputs
for output in outputs:
# loop over each of the detections
for detection in output:
# extract the class ID and confidence (i.e., probability) of
# the current object detection
scores = detection[5:]
classID = np.argmax(scores)
confident = scores[classID]
# filter out weak predictions by ensuring the detected
# probability is greater than the minimum probability
if confident > confidence:
# scale the bounding box coordinates back relative to the
# size of the image, keeping in mind that YOLO actually
# returns the center (x, y)-coordinates of the bounding
# box followed by the boxes' width and height
box = detection[0:4] * np.array([W, H, W, H])
(centerX, centerY, width, height) = box.astype("int")
# use the center (x, y)-coordinates to derive the top and
# and left corner of the bounding box
x = int(centerX - (width / 2))
y = int(centerY - (height / 2))
# update our list of bounding box coordinates, confidences,
# and class IDs
boxes.append([x, y, int(width), int(height)])
confidences.append(float(confident))
classIDs.append(classID)
# apply non-maxima suppression to suppress weak, overlapping bounding boxes
idxs = cv2.dnn.NMSBoxes(boxes, confidences, confidence, threshold)
# ensure at least one detection exists
if len(idxs) > 0:
# loop over the indexes we are keeping
for i in idxs.flatten():
# extract the bounding box coordinates
(x, y) = (boxes[i][0], boxes[i][1])
(w, h) = (boxes[i][2], boxes[i][3])
if classIDs[i] == 2:
# x,y,w,h, auto, marka, model
result = car_color_classifier.predict(image[max(y,0):y + h, max(x,0):x + w])
results.append([x,y,w,h,LABELS[classIDs[i]],result[0]['make'],result[0]['model']])
else:
# x,y,w,h, rodzaj przedmiotu
results.append([x,y,w,h,LABELS[classIDs[i]]])
# save results in results.txt
#with open('results.txt', 'w') as f:
# f.write(tabulate(results))
#print(tabulate(results))
return(results)
if __name__ == '__main__':
consumer = KafkaConsumer(
'topictest',
bootstrap_servers=['kafka:9093'],
auto_offset_reset='earliest',
enable_auto_commit=True
)
with open("car_rec_config.yaml") as yaml_file:
config_dict = yaml.load(yaml_file)["config_dictionary"]
db = pymongo.MongoClient(
'mongo1:27017',
username=config_dict['mongo_user'],
password=config_dict['mongo_password'],
authSource=config_dict['mongo_database'],
authMechanism='SCRAM-SHA-256')[config_dict['mongo_database']]
try:
db.list_collections()
except Exception as e:
logging.error(f"Problem with connection to MongoDB\n{e.args}")
sys.exit(2)
collection_import = db[config_dict['collection_photos']]
collection_export = db[config_dict['collection_labels']]
for event in consumer:
data = event.value
id, timestamp, url = pickle.loads(data)
record = collection_import.find_one({'id':id})
image = pickle.loads(record['photo'])
labels = car_rec(image)
collection_export.insert({'id':id,'timestamp':timestamp,'url':url,"labels":labels,"comments":[]}) | [
"pymongo.MongoClient",
"pickle.loads",
"yaml.load",
"logging.error",
"cv2.dnn.NMSBoxes",
"numpy.argmax",
"os.path.realpath",
"cv2.dnn.blobFromImage",
"cv2.dnn.readNetFromDarknet",
"classifier.Classifier",
"time.sleep",
"numpy.array",
"sys.exit",
"os.path.join",
"kafka.KafkaConsumer"
] | [((247, 261), 'time.sleep', 'time.sleep', (['(10)'], {}), '(10)\n', (257, 261), False, 'import time\n'), ((344, 370), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (360, 370), False, 'import os\n'), ((449, 472), 'classifier.Classifier', 'classifier.Classifier', ([], {}), '()\n', (470, 472), False, 'import classifier\n'), ((491, 533), 'os.path.join', 'os.path.join', (['path_of_script', '"""coco.names"""'], {}), "(path_of_script, 'coco.names')\n", (503, 533), False, 'import os\n'), ((552, 598), 'os.path.join', 'os.path.join', (['path_of_script', '"""yolov3.weights"""'], {}), "(path_of_script, 'yolov3.weights')\n", (564, 598), False, 'import os\n'), ((616, 658), 'os.path.join', 'os.path.join', (['path_of_script', '"""yolov3.cfg"""'], {}), "(path_of_script, 'yolov3.cfg')\n", (628, 658), False, 'import os\n'), ((797, 848), 'cv2.dnn.readNetFromDarknet', 'cv2.dnn.readNetFromDarknet', (['configPath', 'weightsPath'], {}), '(configPath, weightsPath)\n', (823, 848), False, 'import cv2\n'), ((1308, 1384), 'cv2.dnn.blobFromImage', 'cv2.dnn.blobFromImage', (['image', '(1 / 255.0)', '(416, 416)'], {'swapRB': '(True)', 'crop': '(False)'}), '(image, 1 / 255.0, (416, 416), swapRB=True, crop=False)\n', (1329, 1384), False, 'import cv2\n'), ((3099, 3158), 'cv2.dnn.NMSBoxes', 'cv2.dnn.NMSBoxes', (['boxes', 'confidences', 'confidence', 'threshold'], {}), '(boxes, confidences, confidence, threshold)\n', (3115, 3158), False, 'import cv2\n'), ((3997, 4116), 'kafka.KafkaConsumer', 'KafkaConsumer', (['"""topictest"""'], {'bootstrap_servers': "['kafka:9093']", 'auto_offset_reset': '"""earliest"""', 'enable_auto_commit': '(True)'}), "('topictest', bootstrap_servers=['kafka:9093'],\n auto_offset_reset='earliest', enable_auto_commit=True)\n", (4010, 4116), False, 'from kafka import KafkaConsumer\n'), ((4264, 4457), 'pymongo.MongoClient', 'pymongo.MongoClient', (['"""mongo1:27017"""'], {'username': "config_dict['mongo_user']", 'password': "config_dict['mongo_password']", 'authSource': "config_dict['mongo_database']", 'authMechanism': '"""SCRAM-SHA-256"""'}), "('mongo1:27017', username=config_dict['mongo_user'],\n password=config_dict['mongo_password'], authSource=config_dict[\n 'mongo_database'], authMechanism='SCRAM-SHA-256')\n", (4283, 4457), False, 'import pymongo\n'), ((4905, 4923), 'pickle.loads', 'pickle.loads', (['data'], {}), '(data)\n', (4917, 4923), False, 'import pickle\n'), ((4991, 5020), 'pickle.loads', 'pickle.loads', (["record['photo']"], {}), "(record['photo'])\n", (5003, 5020), False, 'import pickle\n'), ((1930, 1947), 'numpy.argmax', 'np.argmax', (['scores'], {}), '(scores)\n', (1939, 1947), True, 'import numpy as np\n'), ((4213, 4233), 'yaml.load', 'yaml.load', (['yaml_file'], {}), '(yaml_file)\n', (4222, 4233), False, 'import yaml\n'), ((4625, 4690), 'logging.error', 'logging.error', (['f"""Problem with connection to MongoDB\n{e.args}"""'], {}), '(f"""Problem with connection to MongoDB\n{e.args}""")\n', (4638, 4690), False, 'import logging\n'), ((4694, 4705), 'sys.exit', 'sys.exit', (['(2)'], {}), '(2)\n', (4702, 4705), False, 'import sys\n'), ((2461, 2483), 'numpy.array', 'np.array', (['[W, H, W, H]'], {}), '([W, H, W, H])\n', (2469, 2483), True, 'import numpy as np\n')] |
# --- external ---
import numpy as np
# --- internal ---
from .constants import CONST as const
def compute_blackbody_q1(T):
"""
Computes flux of photons at HeI line for black body of
temperature T
"""
# convert to unitless energy
x = (const.E_HeI / const.eV_erg) / (const.k_boltz * T)
q1 = photon_radiance(x)
# normalization constants
A = 2.0 * const.k_boltz**3 * T**3 / (const.h**3 *const.c**2)
return A * q1
def compute_blackbody_q0(T):
"""
Computes H ionizing photon flux for a black body of temperature T
"""
# convert to a unitless energy to compute radiance
x = (const.E_HI / const.eV_erg) / (const.k_boltz * T)
q0 = photon_radiance(x)
# constants to convert back to total count
A= 2.0 * const.k_boltz**3 * T**3 / (const.h**3 *const.c**2)
return A * q0
def fuv_flux_blackbody(T):
"""
Computes black body flux over the FUV band for a
black body of temperature T
"""
# convert to unitless energies
x2 = (const.E_HI / const.eV_erg) / (const.k_boltz * T)
x1 = (6.0 / const.eV_erg) / (const.k_boltz * T)
# normalization const
A = 2.0 * const.k_boltz**4 * T**4 / (const.h**3 * const.c**2)
# flux and renorm
fuv_flux = A * black_body_flux(x1,x2)
return fuv_flux
def LW_flux_blackbody(T):
"""
Computes black body flux over the LW band for a
black body of temperature T
"""
# convert to unitless energies
x2 = (const.E_HI / const.eV_erg) / (const.k_boltz * T)
x1 = (11.2 / const.eV_erg) / (const.k_boltz * T)
# normalization const
A = 2.0 * const.k_boltz**4 * T**4 / (const.h**3 * const.c**2)
# flux and renorm
LW_flux = A * black_body_flux(x1,x2)
return LW_flux
# AE: To do rename this function to black_body_flux and
# have this be the main function to use. Rename the other
# one to something else, and rewrite everything to be
# called via this. (a little easier to use rather
# than having to precompute the unitless numbers)
def BB_flux(E1, E2, T):
"""
Wrapper to compute black body flux given minimum and
maximum energies (in eV) and a black body temperature.
"""
x1 = E1 / (const.k_boltz * T) / const.eV_erg
x2 = E2 / (const.k_boltz * T) / const.eV_erg
A = 2.0 * const.k_boltz**4 * T**4 / (const.h**3 * const.c**2)
return A * black_body_flux(x1, x2)
def black_body_flux(x1,x2):
"""
Compute the black body flux between given unitless energy range
x = (E_photon / kT) using the series approximation to compute
the two one-sided integrals. The returned value is unitless
and needs to be scaled by :
2 (kT)^4 / (h^3 c^2) to get units of energy / area / steradian
"""
return one_sided_black_body_flux(x1) - one_sided_black_body_flux(x2)
def one_sided_black_body_flux(x):
"""
Compute the one sided black body flux intergral between
x = (E_photon / kT) using the series approximation to compute
The returned value is unitless and needs to be scaled by :
2 (kT)^4 / (h^3 c^2) to get units of energy / area / steradian
"""
max_iter = 513
min_iter = 4
tolerance = 1.0E-10
difference = 1.0
sum = 0.0; old_sum = 0.0
i = 1
while((difference > tolerance and i < max_iter) or i < min_iter):
old_sum = sum
sum += (x*x*x/(1.0*i) + 3.0*x*x/(1.0*i*i) + 6.0*x/(1.0*i*i*i) + 6.0/(1.0*i*i*i*i))*np.exp(-i*x)
difference = sum - old_sum
i = i + 1
return sum
def photon_radiance(x):
"""
Integral over black body spectrum to compute the number of photons
with energies above the given unitless energy x, where x = Eh / kT.
Uses series approximation of integral
"""
max_iter = 513
min_iter = 4
tolerance = 1.0E-10
difference = 1.0E10
sum = 0.0; old_sum = 0.0
i = 1
while((difference > tolerance and i < max_iter) or i < min_iter):
old_sum = sum
sum += ( x*x/(1.0*i) + 2.0*x/(1.0*i*i) + 2.0/(1.0*i*i*i))*np.exp(-i*x)
difference = sum - old_sum
i = i + 1
return sum
def average_energy(E_i, T):
"""
Given an energy in erg, computes the average energy of photons
above E_i for a black body of temperature T using a series approx of
the integral over the black body spectrum
"""
max_iter = 513
min_iter = 4
tolerance = 1.0E-10
x = E_i / (const.k_boltz * T)
difference = 1.0E10;
sum = old_sum = 0.0;
i = 1;
while((difference > tolerance and i < max_iter) or i < min_iter):
old_sum = sum
sum += ( x*x*x/(1.0* i) + 3.0*x*x/(1.0* i*i)
+ 6.0*x/(1.0* i*i*i) + 6.0 / (1.0*i*i*i*i)) * np.exp(-i*x)
difference = sum - old_sum
i = i + 1
u_dens_sum = sum
sum = 0.0; old_sum = 0.0; i = 1; difference = 1.0E10
while( (difference > tolerance and i < max_iter) or i < min_iter):
old_sum = sum
sum += ( x*x/(1.0*i) + 2.0*x/(1.0*i*i) + 2.0/(1.0*i**3))*np.exp(-i*x)
difference = sum - old_sum
i = i + 1
return (const.k_boltz * T)*(u_dens_sum / sum)
| [
"numpy.exp"
] | [((3461, 3475), 'numpy.exp', 'np.exp', (['(-i * x)'], {}), '(-i * x)\n', (3467, 3475), True, 'import numpy as np\n'), ((4055, 4069), 'numpy.exp', 'np.exp', (['(-i * x)'], {}), '(-i * x)\n', (4061, 4069), True, 'import numpy as np\n'), ((4739, 4753), 'numpy.exp', 'np.exp', (['(-i * x)'], {}), '(-i * x)\n', (4745, 4753), True, 'import numpy as np\n'), ((5044, 5058), 'numpy.exp', 'np.exp', (['(-i * x)'], {}), '(-i * x)\n', (5050, 5058), True, 'import numpy as np\n')] |
# do not run this code
from keras.models import Model
from keras import layers
from keras import Input
# build network model with multi-input
text_vocabulary_size = 10000 # the first 10000 words used most frequently; 10000 as the input dim in Embedding layer.
question_vocabulary_size = 10000 # question text input. input one
answer_vocabulary_size = 500 # answer text input. input two
# input 1:
text_input = Input(shape=(None,), dtype='int32', name='text')
# shape(None,): None dimension specified, The length of array input is uncertain.
# name: the unique layer name in the model.
embedded_text = layers.Embedding(text_vocabulary_size, 64)(text_input) # out:a word embedded into a 64 dimension vector
encoded_text = layers.LSTM(32)(embedded_text)
# input 2:
question_input = Input(shape=(None,), dtype='int32', name='question') # the name should be unique!
embedded_question = layers.Embedding(question_vocabulary_size, 32)(question_input)
encoded_question = layers.LSTM(16)(embedded_question)
# connect two input tensors which could be different size. input 1 is 32 but input 2 is 16.
concatenated = layers.concatenate([encoded_text, encoded_question], axis=-1) # -1: the last axis
# concatenat: https://blog.csdn.net/leviopku/article/details/82380710
answer = layers.Dense(answer_vocabulary_size, activation='softmax')(concatenated) # multi-classification
# make model instance
model = Model([text_input, question_input], answer) # if multi-input, use list or tuple of tensors
model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['acc'])
print('build network model done')
print('---------------------------------------------------------------------------------------------------------------')
# prepare input data and model fit ways
import numpy as np
from keras.utils import to_categorical # one_hot code
num_samples = 1000
max_length = 100
text = np.random.randint(1, text_vocabulary_size, size=(num_samples, max_length)) # low:1; high:10000; size:array size
question = np.random.randint(1, question_vocabulary_size, size=(num_samples, max_length))
answers = np.random.randint(answer_vocabulary_size, size=(num_samples,)) # low: 500; no high limit
answers = to_categorical(answers, answer_vocabulary_size) # one hot:map answer array into a 500 dimension binary matrix
# two ways to fit this model. pick one of them. P202
# fit way 1:
model.fit([text, question], answers, epochs=10, batch_size=128)
# fit way 2: need to give a unique name to each input layer
model.fit({'text': text, 'question': question}, answers, epochs=10, batch_size=128) # dict (name: input tensor)
print('prepare input data done')
print('---------------------------------------------------------------------------------------------------------------') | [
"keras.Input",
"keras.layers.LSTM",
"keras.models.Model",
"numpy.random.randint",
"keras.layers.Dense",
"keras.layers.Embedding",
"keras.layers.concatenate",
"keras.utils.to_categorical"
] | [((421, 469), 'keras.Input', 'Input', ([], {'shape': '(None,)', 'dtype': '"""int32"""', 'name': '"""text"""'}), "(shape=(None,), dtype='int32', name='text')\n", (426, 469), False, 'from keras import Input\n'), ((793, 845), 'keras.Input', 'Input', ([], {'shape': '(None,)', 'dtype': '"""int32"""', 'name': '"""question"""'}), "(shape=(None,), dtype='int32', name='question')\n", (798, 845), False, 'from keras import Input\n'), ((1121, 1182), 'keras.layers.concatenate', 'layers.concatenate', (['[encoded_text, encoded_question]'], {'axis': '(-1)'}), '([encoded_text, encoded_question], axis=-1)\n', (1139, 1182), False, 'from keras import layers\n'), ((1411, 1454), 'keras.models.Model', 'Model', (['[text_input, question_input]', 'answer'], {}), '([text_input, question_input], answer)\n', (1416, 1454), False, 'from keras.models import Model\n'), ((1904, 1978), 'numpy.random.randint', 'np.random.randint', (['(1)', 'text_vocabulary_size'], {'size': '(num_samples, max_length)'}), '(1, text_vocabulary_size, size=(num_samples, max_length))\n', (1921, 1978), True, 'import numpy as np\n'), ((2028, 2106), 'numpy.random.randint', 'np.random.randint', (['(1)', 'question_vocabulary_size'], {'size': '(num_samples, max_length)'}), '(1, question_vocabulary_size, size=(num_samples, max_length))\n', (2045, 2106), True, 'import numpy as np\n'), ((2117, 2179), 'numpy.random.randint', 'np.random.randint', (['answer_vocabulary_size'], {'size': '(num_samples,)'}), '(answer_vocabulary_size, size=(num_samples,))\n', (2134, 2179), True, 'import numpy as np\n'), ((2217, 2264), 'keras.utils.to_categorical', 'to_categorical', (['answers', 'answer_vocabulary_size'], {}), '(answers, answer_vocabulary_size)\n', (2231, 2264), False, 'from keras.utils import to_categorical\n'), ((613, 655), 'keras.layers.Embedding', 'layers.Embedding', (['text_vocabulary_size', '(64)'], {}), '(text_vocabulary_size, 64)\n', (629, 655), False, 'from keras import layers\n'), ((733, 748), 'keras.layers.LSTM', 'layers.LSTM', (['(32)'], {}), '(32)\n', (744, 748), False, 'from keras import layers\n'), ((896, 942), 'keras.layers.Embedding', 'layers.Embedding', (['question_vocabulary_size', '(32)'], {}), '(question_vocabulary_size, 32)\n', (912, 942), False, 'from keras import layers\n'), ((978, 993), 'keras.layers.LSTM', 'layers.LSTM', (['(16)'], {}), '(16)\n', (989, 993), False, 'from keras import layers\n'), ((1283, 1341), 'keras.layers.Dense', 'layers.Dense', (['answer_vocabulary_size'], {'activation': '"""softmax"""'}), "(answer_vocabulary_size, activation='softmax')\n", (1295, 1341), False, 'from keras import layers\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 18 21:20:01 2020
@author: yehuawei
This file generates an testing case where all parameters are specified in the main function
The testing case is saved into a .pkl file where its prefix is 'input',
followed by 'mX' where X specifies the number of source nodes,
followed by 'nY' where Y specifies the number of sink nodes,
then followed by 'cvXXX' which specifies the coefficient of variation of the demand.
"""
import numpy as np
import pickle
if __name__ == "__main__":
m=50; n=100
#capacity vector
mean_c = 100*np.ones(m)
#average demand vector
mean_d = sum(mean_c)/n*np.ones(n)
#demand standard deviation vector
coef_var = 0.5
sd_d = mean_d*coef_var
#profit matrix
profit_mat = np.ones((m,n))
#First stage costs -- fixed cost of each arc
fixed_costs = np.zeros((m,n))
#Starting network
flex_0 = np.zeros((m,n))
with open("input_m{}n{}_cv{}.pkl".format(m,n,coef_var), 'wb') as f:
pickle.dump([m,n],f)
pickle.dump(mean_c ,f)
pickle.dump(mean_d,f)
pickle.dump(sd_d,f)
pickle.dump(profit_mat,f)
pickle.dump(fixed_costs,f)
pickle.dump(flex_0,f)
| [
"pickle.dump",
"numpy.zeros",
"numpy.ones"
] | [((815, 830), 'numpy.ones', 'np.ones', (['(m, n)'], {}), '((m, n))\n', (822, 830), True, 'import numpy as np\n'), ((902, 918), 'numpy.zeros', 'np.zeros', (['(m, n)'], {}), '((m, n))\n', (910, 918), True, 'import numpy as np\n'), ((958, 974), 'numpy.zeros', 'np.zeros', (['(m, n)'], {}), '((m, n))\n', (966, 974), True, 'import numpy as np\n'), ((613, 623), 'numpy.ones', 'np.ones', (['m'], {}), '(m)\n', (620, 623), True, 'import numpy as np\n'), ((679, 689), 'numpy.ones', 'np.ones', (['n'], {}), '(n)\n', (686, 689), True, 'import numpy as np\n'), ((1059, 1081), 'pickle.dump', 'pickle.dump', (['[m, n]', 'f'], {}), '([m, n], f)\n', (1070, 1081), False, 'import pickle\n'), ((1089, 1111), 'pickle.dump', 'pickle.dump', (['mean_c', 'f'], {}), '(mean_c, f)\n', (1100, 1111), False, 'import pickle\n'), ((1120, 1142), 'pickle.dump', 'pickle.dump', (['mean_d', 'f'], {}), '(mean_d, f)\n', (1131, 1142), False, 'import pickle\n'), ((1150, 1170), 'pickle.dump', 'pickle.dump', (['sd_d', 'f'], {}), '(sd_d, f)\n', (1161, 1170), False, 'import pickle\n'), ((1178, 1204), 'pickle.dump', 'pickle.dump', (['profit_mat', 'f'], {}), '(profit_mat, f)\n', (1189, 1204), False, 'import pickle\n'), ((1212, 1239), 'pickle.dump', 'pickle.dump', (['fixed_costs', 'f'], {}), '(fixed_costs, f)\n', (1223, 1239), False, 'import pickle\n'), ((1247, 1269), 'pickle.dump', 'pickle.dump', (['flex_0', 'f'], {}), '(flex_0, f)\n', (1258, 1269), False, 'import pickle\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 18 17:12:36 2021
@author: duttar
Edited from <NAME>
"""
from shutil import copyfile
from osgeo import gdal ## GDAL support for reading virtual files
import os ## To create and remove directories
import matplotlib.pyplot as plt ## For plotting
import numpy as np ## Matrix calculations
import glob ## Retrieving list of files
import argparse
parser = argparse.ArgumentParser(description='Utility to plot multiple simple complex arrays')
parser.add_argument('-f', '--GDALfilename_wildcard', type=str, metavar='', required=True, help='Input file name')
parser.add_argument('-o', '--outfilename', type=str, metavar='', required=True, help='Output file name')
#parser.add_argument('-b', '--band', type=int, metavar='', required=True, help='Band number')
parser.add_argument('-t', '--title', type=str, metavar='', required=False, help='Input title')
#parser.add_argument('-c', '--colormap', type=str, metavar='', required=True, help='Input colormap')
parser.add_argument('-a', '--aspect', type=str, metavar='', required=False, help='Input aspect')
parser.add_argument('-dmin', '--datamin', type=float, metavar='', required=False, help='Input minimum data value')
parser.add_argument('-dmax', '--datamax', type=float, metavar='', required=False, help='Input maximum data value')
parser.add_argument('-i', '--interpolation', type=str, metavar='', required=False, help='interpolation technique')
args = parser.parse_args()
# name of the file
GDALfile = args.GDALfilename_wildcard
outfile = args.outfilename
#band = args.band
titl = args.title
#colormap = args.colormap
apect = args.aspect
dmin = args.datamin
dmax = args.datamax
interp = args.interpolation
def plotstackcomplexdata(GDALfilename_wildcard, outfilename,
title=None, aspect=1,
datamin=None, datamax=None,
interpolation='nearest',
draw_colorbar=True, colorbar_orientation="horizontal"):
# get a list of all files matching the filename wildcard criteria
GDALfilenames = glob.glob(GDALfilename_wildcard)
print(GDALfilenames)
# initialize empty numpy array
data = None
for GDALfilename in GDALfilenames:
ds = gdal.Open(GDALfilename, gdal.GA_ReadOnly)
data_temp = ds.GetRasterBand(1).ReadAsArray()
ds = None
if data is None:
data = data_temp
else:
data = np.vstack((data,data_temp))
# put all zero values to nan and do not plot nan
try:
data[data==0]=np.nan
except:
pass
fig = plt.figure(figsize=(18, 16))
ax = fig.add_subplot(1,2,1)
cax1=ax.imshow(np.abs(data), vmin=datamin, vmax=datamax,
cmap='gray', interpolation='nearest')
ax.set_title(title + " (amplitude)")
if draw_colorbar is not None:
cbar1 = fig.colorbar(cax1,orientation=colorbar_orientation)
ax.set_aspect(aspect)
ax = fig.add_subplot(1,2,2)
cax2 =ax.imshow(np.angle(data), cmap='rainbow',
interpolation='nearest')
ax.set_title(title + " (phase [rad])")
if draw_colorbar is not None:
cbar2 = fig.colorbar(cax2,orientation=colorbar_orientation)
ax.set_aspect(aspect)
#plt.show()
plt.savefig(outfilename)
# clearing the data
data = None
if titl is None:
titl = None
if apect is None:
apect = 1
if dmin is None:
dmin = None
if dmax is None:
dmax = None
if interp is None:
interp = 'nearest'
plotstackcomplexdata(GDALfile, outfile,titl, apect,dmin, dmax, interp)
| [
"numpy.abs",
"argparse.ArgumentParser",
"numpy.angle",
"matplotlib.pyplot.figure",
"glob.glob",
"numpy.vstack",
"osgeo.gdal.Open",
"matplotlib.pyplot.savefig"
] | [((499, 589), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Utility to plot multiple simple complex arrays"""'}), "(description=\n 'Utility to plot multiple simple complex arrays')\n", (522, 589), False, 'import argparse\n'), ((2183, 2215), 'glob.glob', 'glob.glob', (['GDALfilename_wildcard'], {}), '(GDALfilename_wildcard)\n', (2192, 2215), False, 'import glob\n'), ((2736, 2764), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(18, 16)'}), '(figsize=(18, 16))\n', (2746, 2764), True, 'import matplotlib.pyplot as plt\n'), ((3414, 3438), 'matplotlib.pyplot.savefig', 'plt.savefig', (['outfilename'], {}), '(outfilename)\n', (3425, 3438), True, 'import matplotlib.pyplot as plt\n'), ((2344, 2385), 'osgeo.gdal.Open', 'gdal.Open', (['GDALfilename', 'gdal.GA_ReadOnly'], {}), '(GDALfilename, gdal.GA_ReadOnly)\n', (2353, 2385), False, 'from osgeo import gdal\n'), ((2816, 2828), 'numpy.abs', 'np.abs', (['data'], {}), '(data)\n', (2822, 2828), True, 'import numpy as np\n'), ((3137, 3151), 'numpy.angle', 'np.angle', (['data'], {}), '(data)\n', (3145, 3151), True, 'import numpy as np\n'), ((2554, 2582), 'numpy.vstack', 'np.vstack', (['(data, data_temp)'], {}), '((data, data_temp))\n', (2563, 2582), True, 'import numpy as np\n')] |
"""
"""
import numpy as np
from nltk import word_tokenize
from nltk.corpus import stopwords
from nltk.stem.snowball import FrenchStemmer
def avg_document(model, document):
""" computes the average vector of the words in document
in the word2vec model space
Parameters
----------
model : word2vec.KeyedVectors instance
document : list
tokenized document to fold into a vector
Returns
-------
avg : np.ndarray
the average of all the words in document
"""
vocab = model.vocab
n_features = model.vector_size # change to model.vector_sizes
count = 0
vectors = np.zeros((n_features,), dtype='float64')
for word in document:
if word in vocab:
new_vec = model[word]
# print(new_vec.shape, vectors.shape) #debug statement
vectors = np.vstack((vectors, new_vec))
count += 1
# print(vectors.shape)
if count > 0:
avg = np.mean(vectors[1:], axis=0)
else:
avg = vectors
return avg
def avg_corpus(model, corpus):
""" computes average vector for each document of the corpus
Parameters
----------
model : gensim.word2vec.Word2Vec instance
Trained word2vec model
corpus : iterable of iterables
Returns
-------
"""
# n, p = len(corpus), model.layer1_size
features = [avg_document(model, doc) for doc in corpus]
return np.array(features)
def text_normalize(text, stop_words, stem=False):
""" This functions performs the preprocessing steps
needed to optimize the vectorization, such as normalization
stop words removal, lemmatization etc...
stemming for french not accurate enough yet
@TODO lemmatization for french + adapt stemmer for other languages
Parameters
----------
text: string
text to normalize
stop_words : list
list of additionnal stopwords to remove from the text
stem : bool
if True, stems the words to fetch the meaning of the words
However, this functionality does not perform well with french
Returns
-------
string
same text as input but cleansed and normalized
"""
sw = stopwords.words('french') + stop_words
tokens = word_tokenize(text, 'french')
tokens_filter = [word for word in tokens if word not in sw]
if stem:
stemmer = FrenchStemmer()
tokens_filter = [stemmer.stem(word) for word in tokens_filter]
return tokens_filter # " ".join(tokens_filter) #
| [
"nltk.stem.snowball.FrenchStemmer",
"numpy.zeros",
"numpy.mean",
"numpy.array",
"nltk.corpus.stopwords.words",
"nltk.word_tokenize",
"numpy.vstack"
] | [((634, 674), 'numpy.zeros', 'np.zeros', (['(n_features,)'], {'dtype': '"""float64"""'}), "((n_features,), dtype='float64')\n", (642, 674), True, 'import numpy as np\n'), ((1432, 1450), 'numpy.array', 'np.array', (['features'], {}), '(features)\n', (1440, 1450), True, 'import numpy as np\n'), ((2270, 2299), 'nltk.word_tokenize', 'word_tokenize', (['text', '"""french"""'], {}), "(text, 'french')\n", (2283, 2299), False, 'from nltk import word_tokenize\n'), ((966, 994), 'numpy.mean', 'np.mean', (['vectors[1:]'], {'axis': '(0)'}), '(vectors[1:], axis=0)\n', (973, 994), True, 'import numpy as np\n'), ((2218, 2243), 'nltk.corpus.stopwords.words', 'stopwords.words', (['"""french"""'], {}), "('french')\n", (2233, 2243), False, 'from nltk.corpus import stopwords\n'), ((2397, 2412), 'nltk.stem.snowball.FrenchStemmer', 'FrenchStemmer', ([], {}), '()\n', (2410, 2412), False, 'from nltk.stem.snowball import FrenchStemmer\n'), ((854, 883), 'numpy.vstack', 'np.vstack', (['(vectors, new_vec)'], {}), '((vectors, new_vec))\n', (863, 883), True, 'import numpy as np\n')] |
"""
Power law grain size distribution with an exponential cut-off at the large end
"""
import numpy as np
from scipy.integrate import trapz
from newdust.graindist import shape
__all__ = ['ExpCutoff']
# Some default values
RHO = 3.0 # g cm^-3 (average grain material density)
NA = 100 # default number for grain size dist resolution
PDIST = 3.5 # default slope for power law distribution
# min and max grain radii for MRN distribution
AMIN = 0.005 # micron
ACUT = 0.3 # micron
NFOLD = 5 # Number of e-foldings (a/amax) to cover past the amax point
SHAPE = shape.Sphere()
#------------------------------------
class ExpCutoff(object):
"""
| amin : minimum grain size [microns]
| acut : maximum grain size [microns], after which exponential function will cause a turn over in grain size
| p : scalar for power law dn/da \propto a^-p
| NA : int : number of a values to use
| log : boolean : False (default), True = use log-spaced a values
| nfold : number of e-foldings to go beyond acut
|
| **ATTRIBUTES**
| acut, p, a, dtype
|
| *functions*
| ndens(md, rho=3.0, shape=shape.Sphere()) : returns number density (dn/da) [cm^-2 um^-1]
| mdens(md, rho=3.0, shape=shape.Sphere()) : returns mass density (dm/da) [g cm^-2 um^-1]
| md = total dust mass column [g cm^-2]
| rho = dust grain material density [g cm^-3]
| shape = dust grain shape (default spherical)
|
| plot(ax, md, rho=3.0, *kwargs*) : plots (dn/da) a^4 [cm^-2 um^3]
"""
def __init__(self, amin=AMIN, acut=ACUT, p=PDIST, na=NA, log=False, nfold=NFOLD):
self.dtype = 'ExpCutoff'
self.acut = acut
if log:
self.a = np.logspace(np.log10(amin), np.log10(acut * nfold), na)
else:
self.a = np.linspace(amin, acut * nfold, na)
self.p = p
def ndens(self, md, rho=RHO, shape=SHAPE):
adep = np.power(self.a, -self.p) * np.exp(-self.a/self.acut) # um^-p
mgra = shape.vol(self.a) * rho # g (mass of each grain)
dmda = adep * mgra
const = md / trapz(dmda, self.a) # cm^-? um^p-1
return const * adep # cm^-? um^-1
def mdens(self, md, rho=RHO, shape=SHAPE):
nd = self.ndens(md, rho, shape) # dn/da [cm^-2 um^-1]
mg = shape.vol(self.a) * rho # grain mass for each radius [g]
return nd * mg # g cm^-2 um^-1
| [
"scipy.integrate.trapz",
"numpy.power",
"newdust.graindist.shape.vol",
"numpy.exp",
"numpy.linspace",
"newdust.graindist.shape.Sphere",
"numpy.log10"
] | [((613, 627), 'newdust.graindist.shape.Sphere', 'shape.Sphere', ([], {}), '()\n', (625, 627), False, 'from newdust.graindist import shape\n'), ((1853, 1888), 'numpy.linspace', 'np.linspace', (['amin', '(acut * nfold)', 'na'], {}), '(amin, acut * nfold, na)\n', (1864, 1888), True, 'import numpy as np\n'), ((1975, 2000), 'numpy.power', 'np.power', (['self.a', '(-self.p)'], {}), '(self.a, -self.p)\n', (1983, 2000), True, 'import numpy as np\n'), ((2003, 2030), 'numpy.exp', 'np.exp', (['(-self.a / self.acut)'], {}), '(-self.a / self.acut)\n', (2009, 2030), True, 'import numpy as np\n'), ((2055, 2072), 'newdust.graindist.shape.vol', 'shape.vol', (['self.a'], {}), '(self.a)\n', (2064, 2072), False, 'from newdust.graindist import shape\n'), ((2154, 2173), 'scipy.integrate.trapz', 'trapz', (['dmda', 'self.a'], {}), '(dmda, self.a)\n', (2159, 2173), False, 'from scipy.integrate import trapz\n'), ((2357, 2374), 'newdust.graindist.shape.vol', 'shape.vol', (['self.a'], {}), '(self.a)\n', (2366, 2374), False, 'from newdust.graindist import shape\n'), ((1774, 1788), 'numpy.log10', 'np.log10', (['amin'], {}), '(amin)\n', (1782, 1788), True, 'import numpy as np\n'), ((1790, 1812), 'numpy.log10', 'np.log10', (['(acut * nfold)'], {}), '(acut * nfold)\n', (1798, 1812), True, 'import numpy as np\n')] |
"""
Example3 is demo of E2EPipeline with transformers nonstandard from the sklearn perspective.
"""
import logging
import numpy as np
from sklearn.base import BaseEstimator
from src.e2epipeline import E2EPipeline
class TransformerX(BaseEstimator):
def fit(self, X, y=None):
self.num = len(X)
return self
def transform(self, X, copy=None):
return X + self.num
def fit_transform(self, X, y=None, **fit_params):
return self.fit(X, y).transform(X)
class TransformerY(BaseEstimator):
def fit(self, y):
self.num = y[0]
return self
def transform(self, y, copy=None):
return y + (self.num * 10)
def fit_transform(self, y, copy=None):
return self.fit(y).transform(y)
class TransformerXY(BaseEstimator):
def fit(self, X, y):
self.min_x = X.min()
self.min_y = y.min()
return self
def transform(self, X, y):
return X + self.min_x, y + self.min_y
def fit_transform(self, X, y):
return self.fit(X, y).transform(X, y)
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(module)s.%(funcName)s - %(message)s',
handlers=[
logging.StreamHandler(),
]
)
logging.debug("start")
X = np.array([
[4, 2, 3],
[3, 5, 7],
[5, 8, 4]
])
y = np.array([8, 4, 7])
pipeline = E2EPipeline([
('only_x', TransformerX()),
('only_y', TransformerY()),
('both_xy', TransformerXY()),
])
pipeline.fit(X=X, y=y)
new_x, new_y = pipeline.predict(X=X, y=y)
logging.debug(new_x)
logging.debug(new_y)
logging.debug("completed")
| [
"numpy.array",
"logging.StreamHandler",
"logging.debug"
] | [((1246, 1268), 'logging.debug', 'logging.debug', (['"""start"""'], {}), "('start')\n", (1259, 1268), False, 'import logging\n'), ((1273, 1316), 'numpy.array', 'np.array', (['[[4, 2, 3], [3, 5, 7], [5, 8, 4]]'], {}), '([[4, 2, 3], [3, 5, 7], [5, 8, 4]])\n', (1281, 1316), True, 'import numpy as np\n'), ((1335, 1354), 'numpy.array', 'np.array', (['[8, 4, 7]'], {}), '([8, 4, 7])\n', (1343, 1354), True, 'import numpy as np\n'), ((1546, 1566), 'logging.debug', 'logging.debug', (['new_x'], {}), '(new_x)\n', (1559, 1566), False, 'import logging\n'), ((1567, 1587), 'logging.debug', 'logging.debug', (['new_y'], {}), '(new_y)\n', (1580, 1587), False, 'import logging\n'), ((1588, 1614), 'logging.debug', 'logging.debug', (['"""completed"""'], {}), "('completed')\n", (1601, 1614), False, 'import logging\n'), ((1213, 1236), 'logging.StreamHandler', 'logging.StreamHandler', ([], {}), '()\n', (1234, 1236), False, 'import logging\n')] |
import math
import datetime as dt
import numpy as np
from typing import Tuple, Dict
from dataclasses import dataclass
from scipy.optimize import least_squares
from voltoolbox import BusinessTimeMeasure, bs_implied_volatility, longest_increasing_subsequence
from voltoolbox.fit.option_quotes import OptionQuoteSlice, QuoteSlice, VolQuoteSlice, VolSlice
from voltoolbox.fit.fit_utils import act365_time, filter_quotes
from voltoolbox.fit.average_spline import AverageSpline
def _slice_implied_vol(quotes: QuoteSlice,
option_type: float,
forward: float,
time_to_maturity: float) -> VolSlice:
xs = []
vol_mids = []
vol_errs = []
for k, b, a in zip(quotes.strikes, quotes.bids, quotes.asks):
vol_bid = bs_implied_volatility(forward, k, b, time_to_maturity, option_type)
vol_ask = bs_implied_volatility(forward, k, a, time_to_maturity, option_type)
if vol_bid > 0.0 and vol_ask > vol_bid:
vol_mids.append(0.5 * (vol_ask + vol_bid))
vol_errs.append(0.5 * (vol_ask - vol_bid))
xs.append(math.log(k / forward))
return VolSlice(tuple(xs),
tuple(vol_mids),
tuple(vol_errs))
def filter_vol_slice(vol_slice: VolSlice, time_to_maturity: float,
power_payoff_existence: float,
std_dev_range: Tuple[float, float])-> VolSlice:
sqrt_t = math.sqrt(time_to_maturity)
xs = np.array(vol_slice.log_moneyness)
mids = np.array(vol_slice.mids)
errs = np.array(vol_slice.errs)
inc_d_plus = longest_increasing_subsequence(xs / (sqrt_t * mids) - (power_payoff_existence - 0.5) * sqrt_t * mids)
mids = mids[inc_d_plus]
errs = errs[inc_d_plus]
xs = xs[inc_d_plus]
z_min, z_max = std_dev_range
range_filter = (xs / (sqrt_t * mids) >= z_min) & (xs / (sqrt_t * mids) <= z_max)
mids = mids[range_filter]
errs = errs[range_filter]
xs = xs[range_filter]
return VolSlice(tuple(xs),
tuple(mids),
tuple(errs))
def prepare_vol_quotes(quote_slice: OptionQuoteSlice,
forward: float,
box_spread: float,
pricing_dt: dt.datetime,
time_measure: BusinessTimeMeasure) -> VolQuoteSlice:
assert(quote_slice.expiry > pricing_dt)
box_discount = quote_slice.discount * math.exp(-box_spread * act365_time(pricing_dt, quote_slice.expiry))
quote_slice = OptionQuoteSlice(quote_slice.symbol,
quote_slice.expiry,
box_discount,
quote_slice.call,
quote_slice.put)
quote_slice = filter_quotes(quote_slice,
(forward * (1 - 0.0e-6), forward * (1 + 0.0e-6)),
discounted_output_quotes=True)
time_to_maturity = time_measure.distance(pricing_dt, quote_slice.expiry)
put_vols = _slice_implied_vol(quote_slice.put, -1.0, forward, time_to_maturity)
put_vols = filter_vol_slice(put_vols, time_to_maturity, 2.0, (-5.0, 1.0))
call_vols = _slice_implied_vol(quote_slice.call, 1.0, forward, time_to_maturity)
call_vols = filter_vol_slice(call_vols, time_to_maturity, -1.0, (-1.0, 5.0))
return VolQuoteSlice(quote_slice.symbol, quote_slice.expiry, time_to_maturity, forward, call_vols, put_vols)
def prepare_target_vol(vol_slice: VolQuoteSlice )-> VolSlice:
put = vol_slice.put
vol_datas = list(zip(put.log_moneyness, put.mids, put.errs, ['p'] * len(put.mids)))
call = vol_slice.call
vol_datas += list(zip(call.log_moneyness, call.mids, call.errs, ['c'] * len(call.mids)))
vol_datas = sorted(vol_datas, key = lambda q: q[0])
merged_datas = [vol_datas[0]]
prev_q = vol_datas[0]
for q in vol_datas[1:]:
if abs(q[0] - prev_q[0]) > 1.0e-5:
merged_datas.append((q[0], q[1], q[2]))
else:
if q[3]=='c':
assert(prev_q[3]=='p')
if q[0] < 0.0:
q0 = prev_q
q1 = q
else:
q0 = q
q1 = prev_q
else :
assert(prev_q[3]=='c')
if q[0] < 0.0:
q0 = q
q1 = prev_q
else:
q0 = prev_q
q1 = q
diff = abs(q0[1] - q1[1])
w = (1.0 - min(1.0, diff / q0[2])) * (1.0 - min(1.0, diff / q1[2]))
w0 = 1.0 - 0.5 * w
w1 = 1.0 - w0
merged_datas.append((q0[0], w0 * q0[1] + w1 * q1[1], w0 * q0[2] + w1 * min(q0[2], q1[2])))
prev_q = q
xs = [q[0] for q in merged_datas]
mids = [q[1] for q in merged_datas]
errs = [q[2] for q in merged_datas]
target_vols = VolSlice(xs, mids, errs)
target_vols = filter_vol_slice(target_vols, vol_slice.time_to_maturity, 0.5, (-10.0, 10.0))
return target_vols
@dataclass(frozen=True)
class TargetSlice():
t: float
zs: np.array
mids: np.array
errs: np.array
@classmethod
def create(cls, vol_sl: VolQuoteSlice):
target_vols = prepare_target_vol(vol_sl)
mids = np.array(target_vols.mids)
zs = np.array(target_vols.log_moneyness) / (math.sqrt(vol_sl.time_to_maturity) * mids)
return cls(vol_sl.time_to_maturity, zs, mids, np.array(target_vols.errs))
def fit_atm_vol(target_sl: TargetSlice,
*, fit_width: float=0.6) -> Tuple[float, float]:
target_zs = target_sl.zs
target_mids = target_sl.mids
target_errs = target_sl.errs
for i in range(0, 3):
atm_mask = (target_zs > -fit_width) & (target_zs < fit_width)
target_zs = target_zs[atm_mask]
if len(target_zs) > 4: # Enough strike
target_mids = target_mids[atm_mask]
target_errs = target_errs[atm_mask]
weights = (np.maximum(0.0, 1.0 - (target_zs / fit_width))**2.0) * 3.0 / 4.0 # Epanechnikov kernel
break
else: # rescale with larger fit_width
fit_width *= 1.6
target_zs = target_sl.zs
avg_spline = AverageSpline()
coeffs = avg_spline.fit_coeffs(target_zs, target_mids, target_errs / np.sqrt(weights), smoothing = 2.0e-7)
atm_vol = avg_spline.compute_vals(np.array([0.0])).dot(coeffs)[0]
fitted_targets = avg_spline.compute_avg_vals(target_zs).dot(coeffs)
atm_vol_err = ((target_errs + np.abs(target_mids - fitted_targets)) * weights).sum() / weights.sum()
return (atm_vol, atm_vol_err)
class VolCurveFitFunction:
def __init__(self, ts, vols, errs, smoothing):
assert len(ts)==len(vols)==len(errs)
self.ts = np.array(ts)
self.vols = vols
self.errs = errs
self.smoothing = smoothing
ref_fwd_vars = []
prev_t = 0.0
prev_var = 0.0
for t, v in zip(ts, vols):
fwd_var = np.maximum(0.10 * v * (t - prev_t), (t * v**2 - prev_var))
prev_t = t
prev_var += fwd_var
ref_fwd_vars.append(fwd_var)
self.ref_fwd_vars = np.array(ref_fwd_vars)
def fwd_vars(self, xs):
return self.ref_fwd_vars * np.exp(xs)
def vol_curve(self, xs):
fwd_vars = self.fwd_vars(xs)
vars = []
current_var = 0.0
for fwd_var in fwd_vars:
current_var += fwd_var
vars.append(current_var)
return np.sqrt(np.array(vars) / self.ts)
def fwd_vol_curve(self, xs):
fwd_vars = self.fwd_vars(xs)
dts = np.ediff1d(np.append(np.array([0.0]), self.ts))
return np.sqrt(fwd_vars / dts)
def fit_residuals(self, xs):
fit_vols = self.vol_curve(xs)
scores = []
for v, target_v, err in zip(fit_vols, self.vols, self.errs):
scores.append((v - target_v) / err)
#Curve smoothing penality term
fwd_vols = self.fwd_vol_curve(xs)
fwd_vol_smoothing = np.sqrt(self.smoothing) * np.ediff1d(fwd_vols) / np.ediff1d(self.ts)
return np.append(np.array(scores), fwd_vol_smoothing)
def __call__(self, xs):
return self.fit_residuals(xs)
def fit_atm_vol_curve(target_slices :Dict[dt.datetime, TargetSlice],
*, smoothing :float=5.0e-3) -> Dict[dt.datetime, float]:
ts = []
atm_vol_mids = []
atm_vol_errs = []
for target_sl in target_slices.values():
v, err = fit_atm_vol(target_sl)
ts.append(target_sl.t)
atm_vol_mids.append(v)
atm_vol_errs.append(err)
fit_func = VolCurveFitFunction(np.array(ts),
np.array(atm_vol_mids),
np.array(atm_vol_errs),
smoothing)
x0 = np.array([0.0] * len(ts))
res = least_squares(fit_func, x0)
atm_vols = fit_func.vol_curve(res.x)
return dict(zip(target_sl, atm_vols))
| [
"voltoolbox.fit.fit_utils.act365_time",
"numpy.maximum",
"numpy.abs",
"math.sqrt",
"voltoolbox.longest_increasing_subsequence",
"voltoolbox.fit.fit_utils.filter_quotes",
"voltoolbox.fit.option_quotes.VolQuoteSlice",
"scipy.optimize.least_squares",
"voltoolbox.fit.option_quotes.VolSlice",
"numpy.ed... | [((5142, 5164), 'dataclasses.dataclass', 'dataclass', ([], {'frozen': '(True)'}), '(frozen=True)\n', (5151, 5164), False, 'from dataclasses import dataclass\n'), ((1458, 1485), 'math.sqrt', 'math.sqrt', (['time_to_maturity'], {}), '(time_to_maturity)\n', (1467, 1485), False, 'import math\n'), ((1496, 1529), 'numpy.array', 'np.array', (['vol_slice.log_moneyness'], {}), '(vol_slice.log_moneyness)\n', (1504, 1529), True, 'import numpy as np\n'), ((1541, 1565), 'numpy.array', 'np.array', (['vol_slice.mids'], {}), '(vol_slice.mids)\n', (1549, 1565), True, 'import numpy as np\n'), ((1577, 1601), 'numpy.array', 'np.array', (['vol_slice.errs'], {}), '(vol_slice.errs)\n', (1585, 1601), True, 'import numpy as np\n'), ((1620, 1726), 'voltoolbox.longest_increasing_subsequence', 'longest_increasing_subsequence', (['(xs / (sqrt_t * mids) - (power_payoff_existence - 0.5) * sqrt_t * mids)'], {}), '(xs / (sqrt_t * mids) - (\n power_payoff_existence - 0.5) * sqrt_t * mids)\n', (1650, 1726), False, 'from voltoolbox import BusinessTimeMeasure, bs_implied_volatility, longest_increasing_subsequence\n'), ((2540, 2649), 'voltoolbox.fit.option_quotes.OptionQuoteSlice', 'OptionQuoteSlice', (['quote_slice.symbol', 'quote_slice.expiry', 'box_discount', 'quote_slice.call', 'quote_slice.put'], {}), '(quote_slice.symbol, quote_slice.expiry, box_discount,\n quote_slice.call, quote_slice.put)\n', (2556, 2649), False, 'from voltoolbox.fit.option_quotes import OptionQuoteSlice, QuoteSlice, VolQuoteSlice, VolSlice\n'), ((2804, 2909), 'voltoolbox.fit.fit_utils.filter_quotes', 'filter_quotes', (['quote_slice', '(forward * (1 - 0.0), forward * (1 + 0.0))'], {'discounted_output_quotes': '(True)'}), '(quote_slice, (forward * (1 - 0.0), forward * (1 + 0.0)),\n discounted_output_quotes=True)\n', (2817, 2909), False, 'from voltoolbox.fit.fit_utils import act365_time, filter_quotes\n'), ((3395, 3500), 'voltoolbox.fit.option_quotes.VolQuoteSlice', 'VolQuoteSlice', (['quote_slice.symbol', 'quote_slice.expiry', 'time_to_maturity', 'forward', 'call_vols', 'put_vols'], {}), '(quote_slice.symbol, quote_slice.expiry, time_to_maturity,\n forward, call_vols, put_vols)\n', (3408, 3500), False, 'from voltoolbox.fit.option_quotes import OptionQuoteSlice, QuoteSlice, VolQuoteSlice, VolSlice\n'), ((4995, 5019), 'voltoolbox.fit.option_quotes.VolSlice', 'VolSlice', (['xs', 'mids', 'errs'], {}), '(xs, mids, errs)\n', (5003, 5019), False, 'from voltoolbox.fit.option_quotes import OptionQuoteSlice, QuoteSlice, VolQuoteSlice, VolSlice\n'), ((6336, 6351), 'voltoolbox.fit.average_spline.AverageSpline', 'AverageSpline', ([], {}), '()\n', (6349, 6351), False, 'from voltoolbox.fit.average_spline import AverageSpline\n'), ((9008, 9035), 'scipy.optimize.least_squares', 'least_squares', (['fit_func', 'x0'], {}), '(fit_func, x0)\n', (9021, 9035), False, 'from scipy.optimize import least_squares\n'), ((793, 860), 'voltoolbox.bs_implied_volatility', 'bs_implied_volatility', (['forward', 'k', 'b', 'time_to_maturity', 'option_type'], {}), '(forward, k, b, time_to_maturity, option_type)\n', (814, 860), False, 'from voltoolbox import BusinessTimeMeasure, bs_implied_volatility, longest_increasing_subsequence\n'), ((879, 946), 'voltoolbox.bs_implied_volatility', 'bs_implied_volatility', (['forward', 'k', 'a', 'time_to_maturity', 'option_type'], {}), '(forward, k, a, time_to_maturity, option_type)\n', (900, 946), False, 'from voltoolbox import BusinessTimeMeasure, bs_implied_volatility, longest_increasing_subsequence\n'), ((5380, 5406), 'numpy.array', 'np.array', (['target_vols.mids'], {}), '(target_vols.mids)\n', (5388, 5406), True, 'import numpy as np\n'), ((6895, 6907), 'numpy.array', 'np.array', (['ts'], {}), '(ts)\n', (6903, 6907), True, 'import numpy as np\n'), ((7305, 7327), 'numpy.array', 'np.array', (['ref_fwd_vars'], {}), '(ref_fwd_vars)\n', (7313, 7327), True, 'import numpy as np\n'), ((7817, 7840), 'numpy.sqrt', 'np.sqrt', (['(fwd_vars / dts)'], {}), '(fwd_vars / dts)\n', (7824, 7840), True, 'import numpy as np\n'), ((8781, 8793), 'numpy.array', 'np.array', (['ts'], {}), '(ts)\n', (8789, 8793), True, 'import numpy as np\n'), ((8830, 8852), 'numpy.array', 'np.array', (['atm_vol_mids'], {}), '(atm_vol_mids)\n', (8838, 8852), True, 'import numpy as np\n'), ((8889, 8911), 'numpy.array', 'np.array', (['atm_vol_errs'], {}), '(atm_vol_errs)\n', (8897, 8911), True, 'import numpy as np\n'), ((5420, 5455), 'numpy.array', 'np.array', (['target_vols.log_moneyness'], {}), '(target_vols.log_moneyness)\n', (5428, 5455), True, 'import numpy as np\n'), ((5556, 5582), 'numpy.array', 'np.array', (['target_vols.errs'], {}), '(target_vols.errs)\n', (5564, 5582), True, 'import numpy as np\n'), ((6425, 6441), 'numpy.sqrt', 'np.sqrt', (['weights'], {}), '(weights)\n', (6432, 6441), True, 'import numpy as np\n'), ((7122, 7179), 'numpy.maximum', 'np.maximum', (['(0.1 * v * (t - prev_t))', '(t * v ** 2 - prev_var)'], {}), '(0.1 * v * (t - prev_t), t * v ** 2 - prev_var)\n', (7132, 7179), True, 'import numpy as np\n'), ((7392, 7402), 'numpy.exp', 'np.exp', (['xs'], {}), '(xs)\n', (7398, 7402), True, 'import numpy as np\n'), ((8209, 8228), 'numpy.ediff1d', 'np.ediff1d', (['self.ts'], {}), '(self.ts)\n', (8219, 8228), True, 'import numpy as np\n'), ((8255, 8271), 'numpy.array', 'np.array', (['scores'], {}), '(scores)\n', (8263, 8271), True, 'import numpy as np\n'), ((1127, 1148), 'math.log', 'math.log', (['(k / forward)'], {}), '(k / forward)\n', (1135, 1148), False, 'import math\n'), ((2477, 2520), 'voltoolbox.fit.fit_utils.act365_time', 'act365_time', (['pricing_dt', 'quote_slice.expiry'], {}), '(pricing_dt, quote_slice.expiry)\n', (2488, 2520), False, 'from voltoolbox.fit.fit_utils import act365_time, filter_quotes\n'), ((5459, 5493), 'math.sqrt', 'math.sqrt', (['vol_sl.time_to_maturity'], {}), '(vol_sl.time_to_maturity)\n', (5468, 5493), False, 'import math\n'), ((7642, 7656), 'numpy.array', 'np.array', (['vars'], {}), '(vars)\n', (7650, 7656), True, 'import numpy as np\n'), ((7775, 7790), 'numpy.array', 'np.array', (['[0.0]'], {}), '([0.0])\n', (7783, 7790), True, 'import numpy as np\n'), ((8160, 8183), 'numpy.sqrt', 'np.sqrt', (['self.smoothing'], {}), '(self.smoothing)\n', (8167, 8183), True, 'import numpy as np\n'), ((8186, 8206), 'numpy.ediff1d', 'np.ediff1d', (['fwd_vols'], {}), '(fwd_vols)\n', (8196, 8206), True, 'import numpy as np\n'), ((6502, 6517), 'numpy.array', 'np.array', (['[0.0]'], {}), '([0.0])\n', (6510, 6517), True, 'import numpy as np\n'), ((6099, 6143), 'numpy.maximum', 'np.maximum', (['(0.0)', '(1.0 - target_zs / fit_width)'], {}), '(0.0, 1.0 - target_zs / fit_width)\n', (6109, 6143), True, 'import numpy as np\n'), ((6641, 6677), 'numpy.abs', 'np.abs', (['(target_mids - fitted_targets)'], {}), '(target_mids - fitted_targets)\n', (6647, 6677), True, 'import numpy as np\n')] |
#System
import numpy as np
import sys
import os
import random
from glob import glob
from skimage import io
from PIL import Image
import random
import SimpleITK as sitk
#Torch
from torch.autograd import Variable
from torch.utils.data import Dataset, DataLoader
import torch.optim as optim
import torch.nn.functional as F
from torch.autograd import Function
import torch
import torch.nn as nn
import torchvision.transforms as standard_transforms
#from torchvision.models import resnet18
import nibabel as nib
from sklearn.metrics import classification_report, confusion_matrix, accuracy_score
from sklearn.feature_selection import RFE
from sklearn.linear_model import LogisticRegression
from sklearn.datasets import make_friedman1
from sklearn.svm import LinearSVC
from sklearn.svm import SVR
from sklearn.svm import SVC
os.environ["CUDA_VISIBLE_DEVICES"] = "2"
ckpt_path = 'ckpt'
exp_name = 'lol'
if not os.path.exists(ckpt_path):
os.makedirs(ckpt_path)
if not os.path.exists(os.path.join(ckpt_path, exp_name)):
os.makedirs(os.path.join(ckpt_path, exp_name))
args = {
'num_class': 2,
'num_gpus': 1,
'start_epoch': 1,
'num_epoch': 100,
'batch_size': 1,
'lr': 0.01,
'lr_decay': 0.9,
'weight_decay': 1e-4,
'momentum': 0.9,
'snapshot': '',
'opt': 'adam',
'crop_size1': 138,
}
class HEMDataset(Dataset):
def __init__(self, text_dir):
file_pairs = open(text_dir,'r')
self.img_anno_pairs = file_pairs.readlines()
self.req_file, self.req_tar = [],[]
for i in range(len(self.img_anno_pairs)):
net = self.img_anno_pairs[i][:-1]
self.req_file.append(net[:3])
self.req_tar.append(net[4])
def __len__(self):
return len(self.req_tar)
def __getitem__(self, index):
_file_num = self.req_file[index]
_gt = float(self.req_tar[index])
req_npy = './Features_Train/'+ str(_file_num) + 'ct1_seg.npy'
_input_arr = np.load(req_npy, allow_pickle=True)
_input = np.array([])
for i in range(len(_input_arr)):
_input = np.concatenate((_input, _input_arr[i]), axis=None)
_input = torch.from_numpy(np.array(_input)).float()
_target = torch.from_numpy(np.array(_gt)).long()
return _input, _target
class HEMDataset_test(Dataset):
def __init__(self, text_dir):
file_pairs = open(text_dir,'r')
self.img_anno_pairs = file_pairs.readlines()
self.req_file, self.req_tar = [],[]
for i in range(len(self.img_anno_pairs)):
net = self.img_anno_pairs[i][:-1]
self.req_file.append(net[:3])
self.req_tar.append(net[4])
def __len__(self):
return len(self.req_tar)
def __getitem__(self, index):
_file_num = self.req_file[index]
_gt = float(self.req_tar[index])
req_npy = './Features_Val/'+ str(_file_num) + 'ct1_seg.npy'
_input_arr = np.load(req_npy, allow_pickle=True)
_input = np.array([])
for i in range(len(_input_arr)):
_input = np.concatenate((_input, _input_arr[i]), axis=None)
#print(_input)
_input = torch.from_numpy(np.array(_input)).float()
_target = torch.from_numpy(np.array(_gt)).long()
return _input, _target
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(10, 1024)
self.fc2 = nn.Linear(1024, 128)
self.fc3 = nn.Linear(128, 2)
def forward(self, x):
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
def important_features(fea, idx):
batch = []
for j in range(len(fea)):
req_inputs = []
for i in idx[0]:
req_inputs.append(fea[0][i])
batch.append(req_inputs)
return req_inputs
if __name__ == '__main__':
train_file = 'Train_dir.txt'
test_file = 'Val_dir.txt'
train_dataset = HEMDataset(text_dir=train_file)
test_dataset = HEMDataset_test(text_dir=test_file)
rfe_loader = DataLoader(dataset=train_dataset, batch_size=1, shuffle=True, num_workers=2, drop_last=True)
train_loader = DataLoader(dataset=train_dataset, batch_size=args['batch_size'], shuffle=True, num_workers=2,drop_last=True)
test_loader = DataLoader(dataset=test_dataset, batch_size=1, shuffle=False, num_workers=2,drop_last=False)
max_epoch = 1
X_rfe, Y_rfe = [], []
for epoch in range (max_epoch):
for batch_idx, data in enumerate(rfe_loader):
inputs, labels = data
inputs, labels = inputs.cpu().numpy(), labels.cpu().numpy()
X_rfe.append(inputs)
Y_rfe.append(labels)
X_rfe, Y_rfe = np.squeeze(X_rfe, axis=1), np.squeeze(Y_rfe, axis=1)
rfe_model = SVR(kernel="linear")
rfe = RFE(rfe_model, 5, step=1)
fit = rfe.fit(X_rfe, Y_rfe)
rank = fit.ranking_
req_idx = np.where(rank == 1)
print(fit.ranking_)
print('Finished RFE')
X_train, Y_train = [], []
for batch_idx, data in enumerate(train_loader):
inputs, labels = data
req_inputs = important_features(inputs.cpu().numpy(), req_idx)
X_train.append(req_inputs)
Y_train.append(labels.cpu().numpy())
X_train, Y_train = np.array(X_train), np.squeeze(np.array(Y_train), axis=1)
X_test, Y_test = [], []
for batch_idx, data in enumerate(test_loader):
inputs, labels = data
req_inputs = important_features(inputs.cpu().numpy(), req_idx)
X_test.append(req_inputs)
Y_test.append(labels.cpu().numpy())
X_test, Y_test = np.array(X_test), np.squeeze(np.array(Y_test), axis=1)
score, count = [], []
#model = LogisticRegression()
model = SVC(gamma='auto')
model.fit(X_train, Y_train)
score.append(sum(model.predict(X_test) == Y_test))
count.append(len(Y_test))
print(model.predict(X_test))
print(score)
#print(X_train.shape, Y_train.shape, X_test.shape,Y_test.shape) | [
"sklearn.svm.SVR",
"numpy.load",
"os.makedirs",
"torch.utils.data.DataLoader",
"sklearn.feature_selection.RFE",
"os.path.exists",
"torch.nn.Linear",
"numpy.where",
"numpy.array",
"sklearn.svm.SVC",
"numpy.squeeze",
"os.path.join",
"numpy.concatenate"
] | [((905, 930), 'os.path.exists', 'os.path.exists', (['ckpt_path'], {}), '(ckpt_path)\n', (919, 930), False, 'import os\n'), ((936, 958), 'os.makedirs', 'os.makedirs', (['ckpt_path'], {}), '(ckpt_path)\n', (947, 958), False, 'import os\n'), ((4072, 4168), 'torch.utils.data.DataLoader', 'DataLoader', ([], {'dataset': 'train_dataset', 'batch_size': '(1)', 'shuffle': '(True)', 'num_workers': '(2)', 'drop_last': '(True)'}), '(dataset=train_dataset, batch_size=1, shuffle=True, num_workers=2,\n drop_last=True)\n', (4082, 4168), False, 'from torch.utils.data import Dataset, DataLoader\n'), ((4184, 4298), 'torch.utils.data.DataLoader', 'DataLoader', ([], {'dataset': 'train_dataset', 'batch_size': "args['batch_size']", 'shuffle': '(True)', 'num_workers': '(2)', 'drop_last': '(True)'}), "(dataset=train_dataset, batch_size=args['batch_size'], shuffle=\n True, num_workers=2, drop_last=True)\n", (4194, 4298), False, 'from torch.utils.data import Dataset, DataLoader\n'), ((4311, 4408), 'torch.utils.data.DataLoader', 'DataLoader', ([], {'dataset': 'test_dataset', 'batch_size': '(1)', 'shuffle': '(False)', 'num_workers': '(2)', 'drop_last': '(False)'}), '(dataset=test_dataset, batch_size=1, shuffle=False, num_workers=2,\n drop_last=False)\n', (4321, 4408), False, 'from torch.utils.data import Dataset, DataLoader\n'), ((4800, 4820), 'sklearn.svm.SVR', 'SVR', ([], {'kernel': '"""linear"""'}), "(kernel='linear')\n", (4803, 4820), False, 'from sklearn.svm import SVR\n'), ((4831, 4856), 'sklearn.feature_selection.RFE', 'RFE', (['rfe_model', '(5)'], {'step': '(1)'}), '(rfe_model, 5, step=1)\n', (4834, 4856), False, 'from sklearn.feature_selection import RFE\n'), ((4928, 4947), 'numpy.where', 'np.where', (['(rank == 1)'], {}), '(rank == 1)\n', (4936, 4947), True, 'import numpy as np\n'), ((5750, 5767), 'sklearn.svm.SVC', 'SVC', ([], {'gamma': '"""auto"""'}), "(gamma='auto')\n", (5753, 5767), False, 'from sklearn.svm import SVC\n'), ((981, 1014), 'os.path.join', 'os.path.join', (['ckpt_path', 'exp_name'], {}), '(ckpt_path, exp_name)\n', (993, 1014), False, 'import os\n'), ((1033, 1066), 'os.path.join', 'os.path.join', (['ckpt_path', 'exp_name'], {}), '(ckpt_path, exp_name)\n', (1045, 1066), False, 'import os\n'), ((1974, 2009), 'numpy.load', 'np.load', (['req_npy'], {'allow_pickle': '(True)'}), '(req_npy, allow_pickle=True)\n', (1981, 2009), True, 'import numpy as np\n'), ((2027, 2039), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (2035, 2039), True, 'import numpy as np\n'), ((2949, 2984), 'numpy.load', 'np.load', (['req_npy'], {'allow_pickle': '(True)'}), '(req_npy, allow_pickle=True)\n', (2956, 2984), True, 'import numpy as np\n'), ((3002, 3014), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (3010, 3014), True, 'import numpy as np\n'), ((3402, 3421), 'torch.nn.Linear', 'nn.Linear', (['(10)', '(1024)'], {}), '(10, 1024)\n', (3411, 3421), True, 'import torch.nn as nn\n'), ((3441, 3461), 'torch.nn.Linear', 'nn.Linear', (['(1024)', '(128)'], {}), '(1024, 128)\n', (3450, 3461), True, 'import torch.nn as nn\n'), ((3481, 3498), 'torch.nn.Linear', 'nn.Linear', (['(128)', '(2)'], {}), '(128, 2)\n', (3490, 3498), True, 'import torch.nn as nn\n'), ((4731, 4756), 'numpy.squeeze', 'np.squeeze', (['X_rfe'], {'axis': '(1)'}), '(X_rfe, axis=1)\n', (4741, 4756), True, 'import numpy as np\n'), ((4758, 4783), 'numpy.squeeze', 'np.squeeze', (['Y_rfe'], {'axis': '(1)'}), '(Y_rfe, axis=1)\n', (4768, 4783), True, 'import numpy as np\n'), ((5285, 5302), 'numpy.array', 'np.array', (['X_train'], {}), '(X_train)\n', (5293, 5302), True, 'import numpy as np\n'), ((5622, 5638), 'numpy.array', 'np.array', (['X_test'], {}), '(X_test)\n', (5630, 5638), True, 'import numpy as np\n'), ((2102, 2152), 'numpy.concatenate', 'np.concatenate', (['(_input, _input_arr[i])'], {'axis': 'None'}), '((_input, _input_arr[i]), axis=None)\n', (2116, 2152), True, 'import numpy as np\n'), ((3077, 3127), 'numpy.concatenate', 'np.concatenate', (['(_input, _input_arr[i])'], {'axis': 'None'}), '((_input, _input_arr[i]), axis=None)\n', (3091, 3127), True, 'import numpy as np\n'), ((5315, 5332), 'numpy.array', 'np.array', (['Y_train'], {}), '(Y_train)\n', (5323, 5332), True, 'import numpy as np\n'), ((5651, 5667), 'numpy.array', 'np.array', (['Y_test'], {}), '(Y_test)\n', (5659, 5667), True, 'import numpy as np\n'), ((2187, 2203), 'numpy.array', 'np.array', (['_input'], {}), '(_input)\n', (2195, 2203), True, 'import numpy as np\n'), ((2248, 2261), 'numpy.array', 'np.array', (['_gt'], {}), '(_gt)\n', (2256, 2261), True, 'import numpy as np\n'), ((3185, 3201), 'numpy.array', 'np.array', (['_input'], {}), '(_input)\n', (3193, 3201), True, 'import numpy as np\n'), ((3246, 3259), 'numpy.array', 'np.array', (['_gt'], {}), '(_gt)\n', (3254, 3259), True, 'import numpy as np\n')] |
import cv2
import numpy as np
import matplotlib.pyplot as plt
img = cv2.imread('./picture/dog1.jpg')
mask = np.zeros(img.shape[:2], np.uint8)
bgdModel = np.zeros((1, 65), np.float64)
fgdModel = np.zeros((1, 65), np.float64)
rect = (80, 10, 260, 215)
# cv2.rectangle(img, (80,10),(260,215), (255,0,0), 1)
cv2.grabCut(img, mask, rect, bgdModel, fgdModel, 3, cv2.GC_INIT_WITH_RECT)
mask2 = np.where((mask == 2) | (mask == 0), 0, 1).astype('uint8')
img = img * mask2[:, :, np.newaxis]
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
plt.imshow(img)
plt.colorbar()
plt.show()
| [
"cv2.grabCut",
"matplotlib.pyplot.show",
"cv2.cvtColor",
"matplotlib.pyplot.imshow",
"numpy.zeros",
"matplotlib.pyplot.colorbar",
"cv2.imread",
"numpy.where"
] | [((69, 101), 'cv2.imread', 'cv2.imread', (['"""./picture/dog1.jpg"""'], {}), "('./picture/dog1.jpg')\n", (79, 101), False, 'import cv2\n'), ((109, 142), 'numpy.zeros', 'np.zeros', (['img.shape[:2]', 'np.uint8'], {}), '(img.shape[:2], np.uint8)\n', (117, 142), True, 'import numpy as np\n'), ((155, 184), 'numpy.zeros', 'np.zeros', (['(1, 65)', 'np.float64'], {}), '((1, 65), np.float64)\n', (163, 184), True, 'import numpy as np\n'), ((196, 225), 'numpy.zeros', 'np.zeros', (['(1, 65)', 'np.float64'], {}), '((1, 65), np.float64)\n', (204, 225), True, 'import numpy as np\n'), ((308, 382), 'cv2.grabCut', 'cv2.grabCut', (['img', 'mask', 'rect', 'bgdModel', 'fgdModel', '(3)', 'cv2.GC_INIT_WITH_RECT'], {}), '(img, mask, rect, bgdModel, fgdModel, 3, cv2.GC_INIT_WITH_RECT)\n', (319, 382), False, 'import cv2\n'), ((492, 528), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2RGB'], {}), '(img, cv2.COLOR_BGR2RGB)\n', (504, 528), False, 'import cv2\n'), ((529, 544), 'matplotlib.pyplot.imshow', 'plt.imshow', (['img'], {}), '(img)\n', (539, 544), True, 'import matplotlib.pyplot as plt\n'), ((545, 559), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (557, 559), True, 'import matplotlib.pyplot as plt\n'), ((560, 570), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (568, 570), True, 'import matplotlib.pyplot as plt\n'), ((391, 432), 'numpy.where', 'np.where', (['((mask == 2) | (mask == 0))', '(0)', '(1)'], {}), '((mask == 2) | (mask == 0), 0, 1)\n', (399, 432), True, 'import numpy as np\n')] |
import numpy as np
import pandas as pd
import pickle
import os
import seaborn as sns
import matplotlib.pyplot as plt
import pystan
# original model code
varying_intercept = """
data {
int<lower=0> J; # number of counties
int<lower=0> N; # number of observations
int<lower=1,upper=J> county[N]; # which county does each observation belong to?
vector[N] x;
vector[N] y;
}
parameters {
vector[J] a;
real b;
real mu_a;
real<lower=0,upper=100> sigma_a;
real<lower=0,upper=100> sigma_y;
}
transformed parameters {
vector[N] y_hat;
for (i in 1:N)
y_hat[i] <- a[county[i]] + x[i] * b;
}
model {
sigma_a ~ uniform(0, 100);
a ~ normal (mu_a, sigma_a);
b ~ normal (0, 1);
sigma_y ~ uniform(0, 100);
y ~ normal(y_hat, sigma_y);
}
"""
# weighted model code
# different prior over a than original code, so that overall
# prior is proper
weighted_varying_intercept = """
data {
int<lower=0> J;
int<lower=0> N;
int<lower=1,upper=J> county[N];
vector[N] x;
vector[N] y;
vector[N] w;
}
parameters {
vector[J] a;
real b;
real mu_a;
real<lower=0,upper=100> sigma_a;
real<lower=0,upper=100> sigma_y;
}
transformed parameters {
vector[N] y_hat;
for (i in 1:N)
y_hat[i] <- a[county[i]] + x[i] * b;
}
model {
mu_a ~ normal(0, 100);
sigma_a ~ uniform(0, 100);
b ~ normal (0, 1);
sigma_y ~ uniform(0, 100);
a ~ normal (mu_a, sigma_a);
for (i in 1:N)
// target += w[i]*(-square(y[i]-y_hat[i])/(2*square(sigma_y))-log(sqrt(2*pi()*square(sigma_y))));
target += w[i]*normal_lpdf(y[i] | y_hat[i], sigma_y);
}
generated quantities {
vector[N] ll;
for (i in 1:N)
ll[i] = normal_lpdf(y[i] | y_hat[i], sigma_y);
}
"""
## model code for prior
prior_code = """
data {
int<lower=0> J;
int<lower=0> N;
int<lower=1,upper=J> county[N];
vector[N] x;
vector[N] y;
vector[N] w;
}
parameters {
vector[J] a;
real b;
real mu_a;
real<lower=0,upper=100> sigma_a;
real<lower=0,upper=100> sigma_y;
}
transformed parameters {
vector[N] y_hat;
for (i in 1:N)
y_hat[i] <- a[county[i]] + x[i] * b;
}
model {
mu_a ~ normal(0, 100);
sigma_a ~ uniform(0, 100);
b ~ normal (0, 1);
sigma_y ~ uniform(0, 100);
a ~ normal (mu_a, sigma_a);
}
generated quantities {
vector[N] ll;
for (i in 1:N)
ll[i] = normal_lpdf(y[i] | y_hat[i], sigma_y);
}
"""
def load_data():
# load radon data
srrs2 = pd.read_csv('../data/srrs2.dat')
srrs2.columns = srrs2.columns.map(str.strip)
srrs_mn = srrs2.assign(fips=srrs2.stfips*1000 + srrs2.cntyfips)[srrs2.state=='MN']
cty = pd.read_csv('../data/cty.dat')
cty_mn = cty[cty.st=='MN'].copy()
cty_mn[ 'fips'] = 1000*cty_mn.stfips + cty_mn.ctfips
srrs_mn = srrs_mn.merge(cty_mn[['fips', 'Uppm']], on='fips')
srrs_mn = srrs_mn.drop_duplicates(subset='idnum')
u = np.log(srrs_mn.Uppm)
n = len(srrs_mn)
n_county = srrs_mn.groupby('county')['idnum'].count()
srrs_mn.county = srrs_mn.county.str.strip()
mn_counties = srrs_mn.county.unique()
counties = len(mn_counties)
county_lookup = dict(zip(mn_counties, range(len(mn_counties))))
county = srrs_mn['county_code'] = srrs_mn.county.replace(county_lookup).values
radon = srrs_mn.activity
srrs_mn['log_radon'] = log_radon = np.log(radon + 0.1).values
floor_measure = srrs_mn.floor.values
data = {'N': len(log_radon),
'J': len(n_county),
'county': county+1, # Stan % counts starting at 1
'x': floor_measure,
'w': np.ones(len(log_radon)),
'y': log_radon}
return data | [
"pandas.read_csv",
"numpy.log"
] | [((2570, 2602), 'pandas.read_csv', 'pd.read_csv', (['"""../data/srrs2.dat"""'], {}), "('../data/srrs2.dat')\n", (2581, 2602), True, 'import pandas as pd\n'), ((2750, 2780), 'pandas.read_csv', 'pd.read_csv', (['"""../data/cty.dat"""'], {}), "('../data/cty.dat')\n", (2761, 2780), True, 'import pandas as pd\n'), ((3004, 3024), 'numpy.log', 'np.log', (['srrs_mn.Uppm'], {}), '(srrs_mn.Uppm)\n', (3010, 3024), True, 'import numpy as np\n'), ((3448, 3467), 'numpy.log', 'np.log', (['(radon + 0.1)'], {}), '(radon + 0.1)\n', (3454, 3467), True, 'import numpy as np\n')] |
import numpy as np
from keras.layers import Input, LSTM, RepeatVector
from keras.models import Model
from sklearn.preprocessing import MinMaxScaler
def encode(X_list, epochs=50, latent_factor=2):
# start_time = time.time()
for i in range(1, len(X_list)):
X_list[i] -= X_list[i - 1]
scaler = MinMaxScaler(copy=False)
for X in X_list:
scaler.fit_transform(X)
X = np.stack(X_list, axis=1) # X.shape = (n_samples, timesteps, n_features)
n_samples, timesteps, input_dim = X.shape
latent_dim = int(latent_factor * input_dim)
# x_train, x_test = train_test_split(X, stratify=Y)
inputs = Input(shape=(timesteps, input_dim))
encoded = LSTM(latent_dim)(inputs)
decoded = RepeatVector(timesteps)(encoded)
decoded = LSTM(input_dim, return_sequences=True)(decoded)
sequence_autoencoder = Model(inputs, decoded)
encoder = Model(inputs, encoded)
sequence_autoencoder.compile(optimizer='adadelta', loss='mse')
history = sequence_autoencoder.fit(X, X[:, ::-1, :], epochs=epochs, batch_size=256, shuffle=True)
# sequence_autoencoder.save('autorencoder.model')
print('Autoencoder Training Loss: %.4f' % history.history['loss'][-1])
# print(time.time()-start_time)
return encoder.predict(X)
| [
"numpy.stack",
"keras.layers.LSTM",
"sklearn.preprocessing.MinMaxScaler",
"keras.models.Model",
"keras.layers.Input",
"keras.layers.RepeatVector"
] | [((317, 341), 'sklearn.preprocessing.MinMaxScaler', 'MinMaxScaler', ([], {'copy': '(False)'}), '(copy=False)\n', (329, 341), False, 'from sklearn.preprocessing import MinMaxScaler\n'), ((404, 428), 'numpy.stack', 'np.stack', (['X_list'], {'axis': '(1)'}), '(X_list, axis=1)\n', (412, 428), True, 'import numpy as np\n'), ((645, 680), 'keras.layers.Input', 'Input', ([], {'shape': '(timesteps, input_dim)'}), '(shape=(timesteps, input_dim))\n', (650, 680), False, 'from keras.layers import Input, LSTM, RepeatVector\n'), ((858, 880), 'keras.models.Model', 'Model', (['inputs', 'decoded'], {}), '(inputs, decoded)\n', (863, 880), False, 'from keras.models import Model\n'), ((895, 917), 'keras.models.Model', 'Model', (['inputs', 'encoded'], {}), '(inputs, encoded)\n', (900, 917), False, 'from keras.models import Model\n'), ((695, 711), 'keras.layers.LSTM', 'LSTM', (['latent_dim'], {}), '(latent_dim)\n', (699, 711), False, 'from keras.layers import Input, LSTM, RepeatVector\n'), ((735, 758), 'keras.layers.RepeatVector', 'RepeatVector', (['timesteps'], {}), '(timesteps)\n', (747, 758), False, 'from keras.layers import Input, LSTM, RepeatVector\n'), ((782, 820), 'keras.layers.LSTM', 'LSTM', (['input_dim'], {'return_sequences': '(True)'}), '(input_dim, return_sequences=True)\n', (786, 820), False, 'from keras.layers import Input, LSTM, RepeatVector\n')] |
import numpy as np
from tqdm.auto import tqdm
def reciprocal_rank(y_true,y_score,k=10):
'''
Reciprocal rank at k
Parameters
----------
y_true : array-like, shape = [n_samples]
Ground truth (true relevance labels).
y_score : array-like, shape = [n_samples]
Predicted scores.
k : int
up to k-th item
Returns
-------
reciprocal rank at k
'''
order_score = np.argsort(y_score)[::-1].reset_index(drop=True)
order_true = np.argsort(y_true)[::-1][:k].reset_index(drop=True)
for i in range(len(order_score)):
if order_score[i] in order_true:
return 1/(i+1)
#snippet adapted from @witchapong
#https://gist.github.com/witchapong/fdfdcaf39fee9bfa85311489c72923c1?fbclid=IwAR0Sd7HgLmpJhQnft28O1YKSYpawBLFRhED5RcvKayq5e-bCJJsOIonBmrU
def hit_at_k(y_true,y_score,k_true=10,k_score=10):
'''
Hit at rank k
Parameters
----------
y_true : array-like, shape = [n_samples]
Ground truth (true relevance labels).
y_score : array-like, shape = [n_samples]
Predicted scores.
k_true : int
up to k-th item for ground truth
k_score : int
up to k-th item for prediction
Returns
-------
1 if there is hit 0 if there is no hit
'''
order_score = np.argsort(y_score)[::-1][:k_score]
order_true = np.argsort(y_true)[::-1][:k_true]
return 1 if set(order_score).intersection(set(order_true)) else 0
#snippets for average_precision_score and ndcg_score
#from https://gist.github.com/mblondel/7337391
def average_precision_score(y_true, y_score, k=10):
'''
Average precision at rank k
Parameters
----------
y_true : array-like, shape = [n_samples]
Ground truth (true relevance labels).
y_score : array-like, shape = [n_samples]
Predicted scores.
k : int
up to k-th item
Returns
-------
average precision @k : float
'''
unique_y = np.unique(y_true)
if len(unique_y) > 2:
raise ValueError("Only supported for two relevance levels.")
pos_label = unique_y[1]
n_pos = np.sum(y_true == pos_label)
order = np.argsort(y_score)[::-1][:min(n_pos, k)]
y_true = np.asarray(y_true)[order]
score = 0
for i in range(len(y_true)):
if y_true[i] == pos_label:
# Compute precision up to document i
# i.e, percentage of relevant documents up to document i.
prec = 0
for j in range(0, i + 1):
if y_true[j] == pos_label:
prec += 1.0
prec /= (i + 1.0)
score += prec
if n_pos == 0:
return 0
return score / n_pos
def dcg_score(y_true:np.array, y_score:np.array, k:int=10, gains:str="exponential"):
'''
Discounted cumulative gain (DCG) at rank k
Parameters
----------
y_true : array-like, shape = [n_samples]
Ground truth (true relevance labels).
y_score : array-like, shape = [n_samples]
Predicted scores.
k : int
up to k-th item
gains : str
Whether gains should be "exponential" (default) or "linear".
Returns
-------
DCG @k : float
'''
order = np.argsort(y_score)[::-1]
y_true = np.take(y_true, order[:k])
if gains == "exponential":
gains = 2 ** y_true - 1
elif gains == "linear":
gains = y_true
else:
raise ValueError("Invalid gains option.")
# highest rank is 1 so +2 instead of +1
discounts = np.log2(np.arange(len(y_true)) + 2)
return np.sum(gains / discounts)
def ndcg_score(y_true, y_score, k=10, gains="exponential"):
'''
Normalized discounted cumulative gain (NDCG) at rank k
Parameters
----------
y_true : array-like, shape = [n_samples]
Ground truth (true relevance labels).
y_score : array-like, shape = [n_samples]
Predicted scores.
k : int
up to k-th item
gains : str
Whether gains should be "exponential" (default) or "linear".
Returns
-------
NDCG @k : float
'''
best = dcg_score(y_true, y_true, k, gains)
actual = dcg_score(y_true, y_score, k, gains)
return actual / best
def get_metrics(test_features, k_true=10):
test_features['value_1'] = test_features.value+1
test_features['value_bin'] = test_features.value.map(lambda x: 1 if x>0 else 0)
acc_k = []
mrr_k = []
map_k = []
ndcg_k = []
for k in tqdm(range(5,21,5)):
acc = []
mrr = []
map = []
ndcg = []
for user_id in list(test_features.user_id.unique()):
d = test_features[test_features.user_id==user_id]
acc.append(hit_at_k(d['value'],d['pred'],k_true,k))
mrr.append(reciprocal_rank(d['value'],d['pred'],k))
map.append(average_precision_score(d['value_bin'],d['pred'],k))
ndcg.append(ndcg_score(d['value_1'],d['pred'],k))
acc_k.append(np.mean(acc))
mrr_k.append(np.mean(mrr))
map_k.append(np.mean(map))
ndcg_k.append(np.mean(ndcg))
print(f'''
acc@k {[np.round(i,4) for i in acc_k]}
MRR@k {[np.round(i,4) for i in mrr_k]}
MAP@k {[np.round(i,4) for i in map_k]}
nDCG@k {[np.round(i,4) for i in ndcg_k]}
''') | [
"numpy.sum",
"numpy.asarray",
"numpy.argsort",
"numpy.mean",
"numpy.take",
"numpy.round",
"numpy.unique"
] | [((1961, 1978), 'numpy.unique', 'np.unique', (['y_true'], {}), '(y_true)\n', (1970, 1978), True, 'import numpy as np\n'), ((2116, 2143), 'numpy.sum', 'np.sum', (['(y_true == pos_label)'], {}), '(y_true == pos_label)\n', (2122, 2143), True, 'import numpy as np\n'), ((3250, 3276), 'numpy.take', 'np.take', (['y_true', 'order[:k]'], {}), '(y_true, order[:k])\n', (3257, 3276), True, 'import numpy as np\n'), ((3560, 3585), 'numpy.sum', 'np.sum', (['(gains / discounts)'], {}), '(gains / discounts)\n', (3566, 3585), True, 'import numpy as np\n'), ((2212, 2230), 'numpy.asarray', 'np.asarray', (['y_true'], {}), '(y_true)\n', (2222, 2230), True, 'import numpy as np\n'), ((3211, 3230), 'numpy.argsort', 'np.argsort', (['y_score'], {}), '(y_score)\n', (3221, 3230), True, 'import numpy as np\n'), ((1301, 1320), 'numpy.argsort', 'np.argsort', (['y_score'], {}), '(y_score)\n', (1311, 1320), True, 'import numpy as np\n'), ((1354, 1372), 'numpy.argsort', 'np.argsort', (['y_true'], {}), '(y_true)\n', (1364, 1372), True, 'import numpy as np\n'), ((2157, 2176), 'numpy.argsort', 'np.argsort', (['y_score'], {}), '(y_score)\n', (2167, 2176), True, 'import numpy as np\n'), ((4958, 4970), 'numpy.mean', 'np.mean', (['acc'], {}), '(acc)\n', (4965, 4970), True, 'import numpy as np\n'), ((4993, 5005), 'numpy.mean', 'np.mean', (['mrr'], {}), '(mrr)\n', (5000, 5005), True, 'import numpy as np\n'), ((5028, 5040), 'numpy.mean', 'np.mean', (['map'], {}), '(map)\n', (5035, 5040), True, 'import numpy as np\n'), ((5064, 5077), 'numpy.mean', 'np.mean', (['ndcg'], {}), '(ndcg)\n', (5071, 5077), True, 'import numpy as np\n'), ((426, 445), 'numpy.argsort', 'np.argsort', (['y_score'], {}), '(y_score)\n', (436, 445), True, 'import numpy as np\n'), ((492, 510), 'numpy.argsort', 'np.argsort', (['y_true'], {}), '(y_true)\n', (502, 510), True, 'import numpy as np\n'), ((5118, 5132), 'numpy.round', 'np.round', (['i', '(4)'], {}), '(i, 4)\n', (5126, 5132), True, 'import numpy as np\n'), ((5161, 5175), 'numpy.round', 'np.round', (['i', '(4)'], {}), '(i, 4)\n', (5169, 5175), True, 'import numpy as np\n'), ((5204, 5218), 'numpy.round', 'np.round', (['i', '(4)'], {}), '(i, 4)\n', (5212, 5218), True, 'import numpy as np\n'), ((5248, 5262), 'numpy.round', 'np.round', (['i', '(4)'], {}), '(i, 4)\n', (5256, 5262), True, 'import numpy as np\n')] |
# Copyright 2017-2021 Reveal Energy Services, Inc
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This file is part of Orchid and related technologies.
#
from behave import *
use_step_matcher("parse")
import toolz.curried as toolz
import numpy as np
from hamcrest import assert_that, has_length, close_to
from orchid import (reference_origins as origins)
@when('I query the trajectory for well "{well}"')
def step_impl(context, well):
"""
:param well: Name of the well of interest
:type context: behave.runner.Context
"""
# Remember the `well` to correctly calculate the delta for `close_to` in trajectory step
context.well = well
actual_wells = list(context.project.wells().find_by_name(well))
# noinspection PyTypeChecker
assert_that(actual_wells, has_length(1))
actual_well = actual_wells[0]
context.trajectory = actual_well.trajectory
@when('I query the easting and northing arrays in the project reference frame in project units')
def step_impl(context):
"""
:type context: behave.runner.Context
"""
context.easting_array = context.trajectory.get_easting_array(origins.WellReferenceFrameXy.PROJECT)
context.northing_array = context.trajectory.get_northing_array(origins.WellReferenceFrameXy.PROJECT)
@then('I see {count:d} values in each array')
def step_impl(context, count):
"""
:param count: The number of expected values in the easting and northing arrays
:type context: behave.runner.Context
"""
assert_that(context.easting_array, has_length(count))
assert_that(context.northing_array, has_length(count))
# noinspection PyBDDParameters
@then("I see correct {easting:g} and {northing:g} values at {index:d}")
def step_impl(context, easting, northing, index):
"""
:type context: behave.runner.Context
:param easting: The easting value from the trajectory at index.
:type easting: float
:param northing: The northing value for the trajectory at index.
:type northing: float
:param index: The index of the well trajectory being sampled.
:type index: int
"""
assert_that(context.easting_array[index], close_to(easting, close_to_delta(context.well)))
assert_that(context.northing_array[index], close_to(northing, close_to_delta(context.well)))
def close_to_delta(well_to_test):
"""
Calculate the delta value to be used in a `close_to` comparison of trajectory points.
:param well_to_test: The name of the well used to calculate the appropriate delta.
:return: The value to be used as the third argument to `close_to` based on the well name.
"""
def is_bakken_well(to_test):
return to_test in set(toolz.map(lambda d: f'Demo_{d}H', [1, 2, 3, 4]))
def is_permian_well(to_test):
return to_test in set(toolz.map(lambda d: f'C{d}', [1, 2, 3])).union(['P1'])
def is_montney_well(to_test):
return to_test in set(toolz.map(lambda d: f'Hori_0{d}', [1, 2, 3])).union(['Vert_01'])
result = 0.0
# Delta of magnitude 6 accounts for half-even rounding
if is_bakken_well(well_to_test):
result = 6e-1
elif is_permian_well(well_to_test):
result = 6e-3
elif is_montney_well(well_to_test):
result = 6e-4
return result
@then('I see correct <easting> and <northing> values for specific points')
def step_impl(context):
"""
:type context: behave.runner.Context
"""
expected_eastings = np.array([float(r['easting']) for r in context.table])
expected_northings = np.array([float(r['northing']) for r in context.table])
sample_indices = np.array([int(i['index']) for i in context.table])
# Relative tolerance of 0.001 determined empirically. Expected data was rounded to 6 significant figures
np.testing.assert_allclose(context.easting_array[sample_indices], expected_eastings, rtol=0.001)
np.testing.assert_allclose(context.northing_array[sample_indices], expected_northings, rtol=0.001)
| [
"hamcrest.has_length",
"numpy.testing.assert_allclose",
"toolz.curried.map"
] | [((4279, 4379), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['context.easting_array[sample_indices]', 'expected_eastings'], {'rtol': '(0.001)'}), '(context.easting_array[sample_indices],\n expected_eastings, rtol=0.001)\n', (4305, 4379), True, 'import numpy as np\n'), ((4380, 4482), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['context.northing_array[sample_indices]', 'expected_northings'], {'rtol': '(0.001)'}), '(context.northing_array[sample_indices],\n expected_northings, rtol=0.001)\n', (4406, 4482), True, 'import numpy as np\n'), ((1313, 1326), 'hamcrest.has_length', 'has_length', (['(1)'], {}), '(1)\n', (1323, 1326), False, 'from hamcrest import assert_that, has_length, close_to\n'), ((2056, 2073), 'hamcrest.has_length', 'has_length', (['count'], {}), '(count)\n', (2066, 2073), False, 'from hamcrest import assert_that, has_length, close_to\n'), ((2115, 2132), 'hamcrest.has_length', 'has_length', (['count'], {}), '(count)\n', (2125, 2132), False, 'from hamcrest import assert_that, has_length, close_to\n'), ((3199, 3246), 'toolz.curried.map', 'toolz.map', (["(lambda d: f'Demo_{d}H')", '[1, 2, 3, 4]'], {}), "(lambda d: f'Demo_{d}H', [1, 2, 3, 4])\n", (3208, 3246), True, 'import toolz.curried as toolz\n'), ((3313, 3352), 'toolz.curried.map', 'toolz.map', (["(lambda d: f'C{d}')", '[1, 2, 3]'], {}), "(lambda d: f'C{d}', [1, 2, 3])\n", (3322, 3352), True, 'import toolz.curried as toolz\n'), ((3433, 3477), 'toolz.curried.map', 'toolz.map', (["(lambda d: f'Hori_0{d}')", '[1, 2, 3]'], {}), "(lambda d: f'Hori_0{d}', [1, 2, 3])\n", (3442, 3477), True, 'import toolz.curried as toolz\n')] |
import numpy as np
from precise.skaters.location.empirical import emp_d0
def avg_factory(y, fs, s:dict, k=1, e=1, draw_probability=1.0, **f_kwargs):
""" Average the predictions of several cov skaters
fs list of cov skaters
p Probability of using any given data point for any given skater
"""
if not s:
s = {'s_fs':[{} for f in fs]}
avg_mean_s = {}
ravel_cov_s = {}
count = 0
for f_ndx,f in enumerate(fs):
if (np.random.rand()<draw_probability) or ((f_ndx==len(fs)-1) and (count==0)):
x_mean, x_cov, s['s_fs'][f_ndx] = f(y=y, s=s['s_fs'][f_ndx], k=k, e=e, **f_kwargs)
ravel_cov, _, ravel_cov_s = emp_d0(y=np.ravel(x_cov), s=ravel_cov_s)
avg_mean, _, avg_mean_s = emp_d0(y=x_mean, s=avg_mean_s)
avg_cov = np.reshape( ravel_cov, newshape=np.shape(x_cov) )
return avg_mean, avg_cov, s
| [
"numpy.shape",
"precise.skaters.location.empirical.emp_d0",
"numpy.random.rand",
"numpy.ravel"
] | [((766, 796), 'precise.skaters.location.empirical.emp_d0', 'emp_d0', ([], {'y': 'x_mean', 's': 'avg_mean_s'}), '(y=x_mean, s=avg_mean_s)\n', (772, 796), False, 'from precise.skaters.location.empirical import emp_d0\n'), ((843, 858), 'numpy.shape', 'np.shape', (['x_cov'], {}), '(x_cov)\n', (851, 858), True, 'import numpy as np\n'), ((480, 496), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (494, 496), True, 'import numpy as np\n'), ((697, 712), 'numpy.ravel', 'np.ravel', (['x_cov'], {}), '(x_cov)\n', (705, 712), True, 'import numpy as np\n')] |
import numpy as np
import pandas as pd
import math
import shap
import matplotlib
import matplotlib.pyplot as plt
from textwrap import wrap
from risk_calculator.languages.english import English
from risk_calculator.languages.german import German
from risk_calculator.languages.italian import Italian
from risk_calculator.languages.spanish import Spanish
langs = [English(), German(), Spanish(), Italian()]
lang_names = {
0: "English",
1: "Deutsch",
2: "Español",
3: "Italiano",
}
matplotlib.use('Agg')
oxygen = 'Oxygen Saturation'
def get_title_mapping():
"""Returns a dic that indexes language number with feature name translation. E.g. { 0: {'Age': 'Age'}, ... }"""
return {num: lan.get_feature_names() for (num, lan) in zip(range(len(langs)), langs)}
def cvt_temp_c2f(x):
return x*9/5+32
def labs_ques(exp, language):
"""Returns yes if exp evaluates to True"""
return langs[language].get_yes(exp)
def oxygen_vals(val, language):
"""Returns yes if val == 92, else no"""
return langs[language].get_yes(val == 92)
def get_oxygen_info(cols, feats):
oxygen_in = "SaO2" in cols or 'ABG: Oxygen Saturation (SaO2)' in cols
title_mapping = get_title_mapping()
for i, f in enumerate(feats):
if title_mapping[0][f["name"]] == oxygen:
return oxygen_in, i
return oxygen_in, None
# Validates the user input into calculator
def valid_input(numeric_features, user_features, language):
title_mapping = get_title_mapping()
missing = 0
for i, user_feature in enumerate(user_features):
f_name = user_feature["id"]["feature"]
# Only check for numeric values
if "numeric" in user_feature["id"]["index"]:
user_val = user_feature["value"] if "value" in user_feature else None
if user_val is None:
if f_name == "Age":
return False, langs[language].prompt_missing_feature(f_name)
# Change None to np.nan. +1 offset bec assume 1 catageorical at index 0
user_features[i]["value"] = np.nan
missing += 1
else:
# Find the json feature from numeric_features with the name of the current user feature
numeric_feature = [f for f in numeric_features if f["name"] == f_name][0]
# Lazy save the index for later (so we don't have to search the json again)
user_features[i]["x-index"] = numeric_feature["index"]
# Check if user provided input is within range
min_val = numeric_feature["min_val"]
max_val = numeric_feature["max_val"]
if title_mapping[0][f_name] == oxygen and (user_val == 1 or user_val == 0):
continue
if user_val < min_val or user_val > max_val:
return False, \
langs[language].outOfRangeValues.format(title_mapping[language][f_name], min_val, max_val),
# user should give at least 2/3 of features
threshold = math.floor(2 * len(numeric_features) / 3)
if missing > threshold:
return False, langs[language].notEnoughValues.format(threshold)
return True, ""
# Uses model and features to predict score
def predict_risk(m, model, features, imputer, explainer, user_features, columns, language):
x = [0] * len(model.feature_importances_)
all_features = features["numeric"] + features["categorical"] + features["multidrop"]
# Loop through all user provided features
for feat in user_features:
# Get name of current feature
f_name = feat["id"]["feature"]
# The index that this feature should be assigned to in the input vector, x
index = -1
# Check if cached index is there
if "x-index" in feat:
index = feat["x-index"]
else:
# If not, find the index
json_feature = [f for f in all_features if f["name"] == f_name][0]
if f_name != "Comorbidities":
index = json_feature["index"]
else:
# Handle special case
for comorb in feat["value"]:
c_idx = features["multidrop"][0]["vals"].index(comorb)
index = features["multidrop"][0]["index"][c_idx]
x[index] = 1
continue
# Assign value to right index in input vector
x[index] = feat["value"]
imputed = np.argwhere(np.isnan(x))
x_full = imputer.transform([x])
_X = pd.DataFrame(columns=columns, index=range(1), dtype=np.float)
_X.loc[0] = x_full[0]
score = model.predict_proba(_X)[:, 1]
score = int(100*round(score[0], 2))
impute_text = [''] * len(imputed)
title_mapping = get_title_mapping()
for i, ind in enumerate(imputed):
ind = int(ind)
temp = '°F' if columns[ind] == 'Body Temperature' else ''
impute_text[i] = langs[language].missingFeatureTxt.format(
title_mapping[language][columns[ind]],
str(round(x_full[0][ind], 2)) + temp)
impute_text = ' \n'.join(impute_text)
shap_new = explainer.shap_values(_X)
names = ['\n'.join(wrap(''.join(['{}'.format(title_mapping[language][c])]), width=12)) for c in columns]
plot = shap.force_plot(
np.around(explainer.expected_value, decimals=2),
np.around(shap_new, decimals=2),
np.around(_X, decimals=2),
link="logit",
matplotlib=True,
show=False,
feature_names=names
)
plt.axis('off') # this rows the rectangular frame
return score, impute_text, plot
def build_lab_ques_card(lang):
return langs[lang].hasLabValues
def switch_oxygen(vec, ind):
# assume there is only 1 categorical variable
ind = ind + 1
vec = list(vec)
vals = vec[0]
length = len(vals)
if length > 0 and length > ind:
oxy = vals[-1]
n = len(vals)-1
for i in range(n, ind, -1):
vals[i] = vals[i-1]
vals[ind] = oxy
vec[0] = vals
return tuple(vec)
vec[0] = vals
return tuple(vec)
| [
"risk_calculator.languages.english.English",
"matplotlib.pyplot.axis",
"numpy.isnan",
"numpy.around",
"matplotlib.use",
"risk_calculator.languages.spanish.Spanish",
"risk_calculator.languages.italian.Italian",
"risk_calculator.languages.german.German"
] | [((497, 518), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (511, 518), False, 'import matplotlib\n'), ((364, 373), 'risk_calculator.languages.english.English', 'English', ([], {}), '()\n', (371, 373), False, 'from risk_calculator.languages.english import English\n'), ((375, 383), 'risk_calculator.languages.german.German', 'German', ([], {}), '()\n', (381, 383), False, 'from risk_calculator.languages.german import German\n'), ((385, 394), 'risk_calculator.languages.spanish.Spanish', 'Spanish', ([], {}), '()\n', (392, 394), False, 'from risk_calculator.languages.spanish import Spanish\n'), ((396, 405), 'risk_calculator.languages.italian.Italian', 'Italian', ([], {}), '()\n', (403, 405), False, 'from risk_calculator.languages.italian import Italian\n'), ((5566, 5581), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (5574, 5581), True, 'import matplotlib.pyplot as plt\n'), ((4497, 4508), 'numpy.isnan', 'np.isnan', (['x'], {}), '(x)\n', (4505, 4508), True, 'import numpy as np\n'), ((5336, 5383), 'numpy.around', 'np.around', (['explainer.expected_value'], {'decimals': '(2)'}), '(explainer.expected_value, decimals=2)\n', (5345, 5383), True, 'import numpy as np\n'), ((5393, 5424), 'numpy.around', 'np.around', (['shap_new'], {'decimals': '(2)'}), '(shap_new, decimals=2)\n', (5402, 5424), True, 'import numpy as np\n'), ((5434, 5459), 'numpy.around', 'np.around', (['_X'], {'decimals': '(2)'}), '(_X, decimals=2)\n', (5443, 5459), True, 'import numpy as np\n')] |
import numpy as np
import pika
import pickle
import time
import random
from copy import deepcopy
from multiprocessing import Process, Manager
from pygamoo.utils import RpcClient, assigning_gens
from pygamoo.utils import evaluate_call, get_not_dominated, front_suppression
class AGAMOO:
def __init__(self, nobjs, nvars, max_eval, change_iter, next_iter, max_front, cmd_exchange, objs_queues, host,
port):
self.nobjs = nobjs
self.nvars = nvars
self.max_front = max_front
self.max_eval = max_eval
self.change_iter = change_iter
self.next_iter = next_iter
self._prefix = ''.join([random.choice('abcdefghijklmnoprstquwyxz') for _ in range(10)])
self.best_pull_queue = self._prefix + '_best_pull'
self.best_push_queue = self._prefix + '_best_push'
self.pop_queue = self._prefix + '_pop'
self.cmd_queue = self._prefix + '_cmd'
self.cmd_exchange = cmd_exchange
self.objs_queues = objs_queues
self.host = host
self.port = port
self._p1 = None
self._p2 = None
self._p3 = None
self._p4 = None
self._p5 = None
try:
manager = getattr(type(self), 'manager')
except AttributeError:
manager = type(self).manager = Manager()
self._shared_best = manager.dict({})
self._shared_best['solutions'] = [None] * self.nobjs
self._shared_best['iter_counters'] = [None] * self.nobjs
self._shared_front = manager.dict({})
self._shared_front['objs_rpc'] = self.objs_queues
self._shared_front['stop_flag'] = False
self._shared_front['front'] = []
self._shared_front['front_eval'] = []
self._shared_front['iterations'] = []
self._shared_front['evaluations'] = []
self._shared_front['evaluations_m'] = []
self._shared_front['nobjs'] = self.nobjs
self._shared_front['max_front'] = self.max_front
self._shared_front['change_iter'] = self.change_iter
self._shared_front['max_eval'] = self.max_eval
self._shared_front['min_iter_pop'] = 0
self._shared_front['change_flag'] = True
self._shared_values = manager.dict({})
self._shared_values['start_flag'] = False
self._lock = manager.RLock()
def get_results(self):
res = deepcopy(self._shared_front)
del res['objs_rpc']
del res['nobjs']
del res['max_front']
del res['change_iter']
del res['max_eval']
del res['min_iter_pop']
del res['change_flag']
return res
def start(self):
self._send_to(self.cmd_queue, 'Start')
def stop(self):
self._send_to(self.cmd_queue, 'Stop')
def close(self):
if self._p1 is not None:
self._p1.terminate()
del self._p1
if self._p2 is not None:
self._p2.terminate()
del self._p2
if self._p3 is not None:
self._p3.terminate()
del self._p3
if self._p4 is not None:
self._p4.terminate()
del self._p4
if self._p5 is not None:
self._p5.terminate()
del self._p5
connection = pika.BlockingConnection(pika.ConnectionParameters(host=self.host, port=self.port))
channel = connection.channel()
channel.exchange_delete(exchange=self.cmd_exchange)
channel.queue_delete(queue=self.best_pull_queue)
channel.queue_delete(queue=self.best_push_queue)
channel.queue_delete(queue=self.pop_queue)
channel.queue_delete(queue=self.cmd_queue)
def __del__(self):
self.close()
def run(self):
p1 = Process(target=self._best_pull_consumer, args=(self,))
p1.daemon = True
p1.start()
p2 = Process(target=self._best_push_consumer, args=(self,))
p2.daemon = True
p2.start()
p3 = Process(target=self._pop_consumer, args=(self,))
p3.daemon = True
p3.start()
p4 = Process(target=self._cmd_consumer, args=(self,))
p4.daemon = True
p4.start()
p5 = Process(target=self._main_process, args=(self,))
p5.daemon = True
p5.start()
self._p1 = p1
self._p2 = p2
self._p3 = p3
self._p4 = p4
self._p5 = p5
def is_alive(self, separate=False):
if separate:
return (False if self._p1 is None else self._p1.is_alive(),
False if self._p2 is None else self._p2.is_alive(),
False if self._p3 is None else self._p3.is_alive(),
False if self._p4 is None else self._p4.is_alive(),
False if self._p5 is None else self._p5.is_alive())
if (self._p1 is not None) and (self._p2 is not None) and (self._p3 is not None) and (self._p4 is not None) and\
(self._p5 is not None):
return all([self._p1.is_alive(), self._p2.is_alive(), self._p3.is_alive(), self._p4.is_alive(),
self._p5.is_alive()])
if separate:
return (False if self._p1 is None else self._p1.is_alive(),
False if self._p2 is None else self._p2.is_alive(),
False if self._p3 is None else self._p3.is_alive(),
False if self._p4 is None else self._p4.is_alive(),
False if self._p5 is None else self._p5.is_alive())
return False
def is_working(self):
return self._shared_values['start_flag']
@staticmethod
def _best_pull_consumer(self,):
connection = pika.BlockingConnection(pika.ConnectionParameters(host=self.host, port=self.port))
channel = connection.channel()
channel.queue_declare(queue=self.best_pull_queue)
def callback(cal_shared_best, ch, method, props):
best = [deepcopy(cal_shared_best['solutions']), deepcopy(cal_shared_best['iter_counters'])]
response = pickle.dumps(best)
ch.basic_publish(exchange='', routing_key=props.reply_to,
properties=pika.BasicProperties(correlation_id=props.correlation_id), body=response)
ch.basic_ack(delivery_tag=method.delivery_tag)
channel.basic_qos(prefetch_count=1)
channel.basic_consume(queue=self.best_pull_queue,
on_message_callback=lambda ch, met, prop, body: callback(self._shared_best, ch,
met, prop))
channel.start_consuming()
@staticmethod
def _best_push_consumer(self,):
connection = pika.BlockingConnection(pika.ConnectionParameters(host=self.host, port=self.port))
channel = connection.channel()
channel.queue_declare(queue=self.best_push_queue)
def callback(cal_shared_best, cal_lock, body):
player_data = pickle.loads(body, encoding='bytes')
nobj = player_data['nobj']
solution = player_data['solution']
iterr = player_data['iter_counter']
solutions = deepcopy(cal_shared_best['solutions'])
iterrs = deepcopy(cal_shared_best['iter_counters'])
solutions[nobj] = solution
iterrs[nobj] = iterr
with cal_lock:
cal_shared_best['solutions'] = solutions
cal_shared_best['iter_counters'] = iterrs
channel.basic_consume(queue=self.best_push_queue,
on_message_callback=lambda ch, met, prop, body: callback(self._shared_best, self._lock,
body),
auto_ack=True)
channel.start_consuming()
@staticmethod
def _pop_consumer(self,):
connection = pika.BlockingConnection(pika.ConnectionParameters(host=self.host, port=self.port))
channel = connection.channel()
channel.queue_declare(queue=self.pop_queue)
def callback(cal_shared_front, cal_lock, body):
front = cal_shared_front['front']
front_eval = cal_shared_front['front_eval']
evaluations = cal_shared_front['evaluations']
evaluations_m = cal_shared_front['evaluations_m']
iterations = cal_shared_front['iterations']
max_front = cal_shared_front['max_front']
change_flag = cal_shared_front['change_flag']
change_iter = cal_shared_front['change_iter']
min_iter_pop = cal_shared_front['min_iter_pop']
stop_flag = cal_shared_front['stop_flag']
max_eval = cal_shared_front['max_eval']
nobjs = cal_shared_front['nobjs']
if stop_flag:
return None
objs_rpc = []
for i in range(nobjs):
objs_rpc.append(RpcClient(cal_shared_front['objs_rpc'][i], self.host, self.port))
player_data = pickle.loads(body, encoding='bytes')
nobj = player_data['nobj']
pop = player_data['population']
pop_eval = player_data['population_eval']
evaluation_counter = player_data['evaluation_counter']
iteration = player_data['iteration']
if len(iterations) == 0:
iterations = np.zeros(nobjs)
iterations[nobj] = iteration
min_iter = np.min(iterations)
if min_iter - min_iter_pop >= change_iter:
change_flag = True
min_iter_pop = min_iter
if len(evaluations) == 0:
evaluations = np.zeros(nobjs)
evaluations[nobj] = evaluation_counter
pop_evals = []
if len(evaluations_m) == 0:
evaluations_m = np.zeros(nobjs)
if pop.shape[0] > 0:
for i in range(nobjs):
if i != nobj:
pop_evals.append(np.reshape(evaluate_call(pop, objs_rpc[i]), (-1, 1)))
evaluations_m[i] += pop.shape[0]
else:
pop_evals.append(np.reshape(pop_eval, (-1, 1)))
pop_evals = np.hstack(pop_evals)
if max_eval > 0:
if np.min(evaluations + evaluations_m) >= max_eval:
stop_flag = True
if pop.shape[0] > 0:
mask = get_not_dominated(pop_evals)
pop = pop[mask]
pop_evals = pop_evals[mask]
if len(front) == 0:
front = deepcopy(pop)
front_eval = deepcopy(pop_evals)
else:
front = np.vstack([front, pop])
front_eval = np.vstack([front_eval, pop_evals])
mask = get_not_dominated(front_eval)
front = front[mask]
front_eval = front_eval[mask]
# front suppression
if 0 < max_front < front.shape[0]:
mask = front_suppression(front_eval, max_front)
front = front[mask]
front_eval = front_eval[mask]
with cal_lock:
cal_shared_front['front'] = front
cal_shared_front['front_eval'] = front_eval
cal_shared_front['evaluations'] = evaluations
cal_shared_front['evaluations_m'] = evaluations_m
cal_shared_front['iterations'] = iterations
cal_shared_front['change_flag'] = change_flag
cal_shared_front['stop_flag'] = stop_flag
cal_shared_front['min_iter_pop'] = min_iter_pop
channel.basic_consume(queue=self.pop_queue,
on_message_callback=lambda ch, met, prop, body: callback(self._shared_front, self._lock,
body),
auto_ack=True)
channel.start_consuming()
def _send_to_players(self, message):
connection = pika.BlockingConnection(pika.ConnectionParameters(host=self.host, port=self.port))
channel = connection.channel()
channel.exchange_declare(exchange=self.cmd_exchange, exchange_type='fanout')
channel.basic_publish(exchange=self.cmd_exchange, routing_key='', body=message)
connection.close()
def _send_to(self, queue, msg):
message = pickle.dumps(msg)
connection = pika.BlockingConnection(pika.ConnectionParameters(host=self.host, port=self.port))
channel = connection.channel()
channel.queue_declare(queue=queue)
channel.basic_publish(exchange='', routing_key=queue, body=message)
connection.close()
@staticmethod
def _cmd_consumer(self):
connection = pika.BlockingConnection(pika.ConnectionParameters(host=self.host, port=self.port))
channel = connection.channel()
channel.queue_declare(queue=self.cmd_queue)
def callback(cal_shared_values, cal_shared_front, cal_lock, body):
cmd = pickle.loads(body, encoding='bytes')
with cal_lock:
if cmd == 'Start':
cal_shared_values['start_flag'] = True
cal_shared_front['stop_flag'] = False
if cmd == 'Stop':
cal_shared_values['start_flag'] = False
channel.basic_consume(queue=self.cmd_queue,
on_message_callback=lambda ch, met, prop, body: callback(self._shared_values,
self._shared_front, self._lock,
body),
auto_ack=True)
channel.start_consuming()
@staticmethod
def _main_process(self):
patterns = None
first = True
while True:
if self._shared_front['stop_flag']:
with self._lock:
self._shared_values['start_flag'] = not self._shared_front['stop_flag']
if self._shared_values['start_flag']:
if first:
with self._lock:
self._shared_front['objs_rpc'] = self.objs_queues
self._shared_front['front'] = []
self._shared_front['front_eval'] = []
self._shared_front['evaluations'] = []
self._shared_front['evaluations_m'] = []
self._shared_front['iterations'] = []
self._shared_front['min_iter_pop'] = 0
self._shared_front['change_flag'] = True
self._shared_front['stop_flag'] = False
# sending parms to players
msg = ['parm', 'Next Iter', self.next_iter]
self._send_to_players(pickle.dumps(msg))
msg = ['queue', 'Manager Best', [self.best_push_queue, self.best_pull_queue]]
self._send_to_players(pickle.dumps(msg))
msg = ['queue', 'Manager Pop', self.pop_queue]
self._send_to_players(pickle.dumps(msg))
first = False
# sending gens
if self._shared_front['change_flag']:
patterns = assigning_gens(self.nvars, self.nobjs)
msg = ['parm', 'Gens', patterns]
self._send_to_players(pickle.dumps(msg))
with self._lock:
self._shared_front['change_flag'] = False
# sending START to players
msg = ['cmd', 'Start']
self._send_to_players(pickle.dumps(msg))
continue
# sending gens
if self._shared_front['change_flag']:
patterns = assigning_gens(self.nvars, self.nobjs)
msg = ['parm', 'Gens', patterns]
self._send_to_players(pickle.dumps(msg))
with self._lock:
self._shared_front['change_flag'] = False
else:
if first:
continue
else:
# sending STOP to players
msg = ['cmd', 'Stop']
self._send_to_players(pickle.dumps(msg))
# cleaning queues
connection = pika.BlockingConnection(pika.ConnectionParameters(host=self.host, port=self.port))
channel = connection.channel()
channel.queue_purge(queue=self.best_pull_queue)
channel.queue_purge(queue=self.best_push_queue)
channel.queue_purge(queue=self.pop_queue)
connection.close()
first = True
time.sleep(2)
| [
"pygamoo.utils.RpcClient",
"pygamoo.utils.evaluate_call",
"numpy.reshape",
"pika.BasicProperties",
"pickle.dumps",
"pickle.loads",
"copy.deepcopy",
"pika.ConnectionParameters",
"numpy.hstack",
"time.sleep",
"numpy.min",
"pygamoo.utils.assigning_gens",
"numpy.vstack",
"pygamoo.utils.front_s... | [((2377, 2405), 'copy.deepcopy', 'deepcopy', (['self._shared_front'], {}), '(self._shared_front)\n', (2385, 2405), False, 'from copy import deepcopy\n'), ((3739, 3793), 'multiprocessing.Process', 'Process', ([], {'target': 'self._best_pull_consumer', 'args': '(self,)'}), '(target=self._best_pull_consumer, args=(self,))\n', (3746, 3793), False, 'from multiprocessing import Process, Manager\n'), ((3852, 3906), 'multiprocessing.Process', 'Process', ([], {'target': 'self._best_push_consumer', 'args': '(self,)'}), '(target=self._best_push_consumer, args=(self,))\n', (3859, 3906), False, 'from multiprocessing import Process, Manager\n'), ((3965, 4013), 'multiprocessing.Process', 'Process', ([], {'target': 'self._pop_consumer', 'args': '(self,)'}), '(target=self._pop_consumer, args=(self,))\n', (3972, 4013), False, 'from multiprocessing import Process, Manager\n'), ((4072, 4120), 'multiprocessing.Process', 'Process', ([], {'target': 'self._cmd_consumer', 'args': '(self,)'}), '(target=self._cmd_consumer, args=(self,))\n', (4079, 4120), False, 'from multiprocessing import Process, Manager\n'), ((4179, 4227), 'multiprocessing.Process', 'Process', ([], {'target': 'self._main_process', 'args': '(self,)'}), '(target=self._main_process, args=(self,))\n', (4186, 4227), False, 'from multiprocessing import Process, Manager\n'), ((12534, 12551), 'pickle.dumps', 'pickle.dumps', (['msg'], {}), '(msg)\n', (12546, 12551), False, 'import pickle\n'), ((3287, 3344), 'pika.ConnectionParameters', 'pika.ConnectionParameters', ([], {'host': 'self.host', 'port': 'self.port'}), '(host=self.host, port=self.port)\n', (3312, 3344), False, 'import pika\n'), ((5698, 5755), 'pika.ConnectionParameters', 'pika.ConnectionParameters', ([], {'host': 'self.host', 'port': 'self.port'}), '(host=self.host, port=self.port)\n', (5723, 5755), False, 'import pika\n'), ((6040, 6058), 'pickle.dumps', 'pickle.dumps', (['best'], {}), '(best)\n', (6052, 6058), False, 'import pickle\n'), ((6748, 6805), 'pika.ConnectionParameters', 'pika.ConnectionParameters', ([], {'host': 'self.host', 'port': 'self.port'}), '(host=self.host, port=self.port)\n', (6773, 6805), False, 'import pika\n'), ((6986, 7022), 'pickle.loads', 'pickle.loads', (['body'], {'encoding': '"""bytes"""'}), "(body, encoding='bytes')\n", (6998, 7022), False, 'import pickle\n'), ((7181, 7219), 'copy.deepcopy', 'deepcopy', (["cal_shared_best['solutions']"], {}), "(cal_shared_best['solutions'])\n", (7189, 7219), False, 'from copy import deepcopy\n'), ((7241, 7283), 'copy.deepcopy', 'deepcopy', (["cal_shared_best['iter_counters']"], {}), "(cal_shared_best['iter_counters'])\n", (7249, 7283), False, 'from copy import deepcopy\n'), ((7942, 7999), 'pika.ConnectionParameters', 'pika.ConnectionParameters', ([], {'host': 'self.host', 'port': 'self.port'}), '(host=self.host, port=self.port)\n', (7967, 7999), False, 'import pika\n'), ((9051, 9087), 'pickle.loads', 'pickle.loads', (['body'], {'encoding': '"""bytes"""'}), "(body, encoding='bytes')\n", (9063, 9087), False, 'import pickle\n'), ((9489, 9507), 'numpy.min', 'np.min', (['iterations'], {}), '(iterations)\n', (9495, 9507), True, 'import numpy as np\n'), ((12181, 12238), 'pika.ConnectionParameters', 'pika.ConnectionParameters', ([], {'host': 'self.host', 'port': 'self.port'}), '(host=self.host, port=self.port)\n', (12206, 12238), False, 'import pika\n'), ((12597, 12654), 'pika.ConnectionParameters', 'pika.ConnectionParameters', ([], {'host': 'self.host', 'port': 'self.port'}), '(host=self.host, port=self.port)\n', (12622, 12654), False, 'import pika\n'), ((12934, 12991), 'pika.ConnectionParameters', 'pika.ConnectionParameters', ([], {'host': 'self.host', 'port': 'self.port'}), '(host=self.host, port=self.port)\n', (12959, 12991), False, 'import pika\n'), ((13178, 13214), 'pickle.loads', 'pickle.loads', (['body'], {'encoding': '"""bytes"""'}), "(body, encoding='bytes')\n", (13190, 13214), False, 'import pickle\n'), ((655, 697), 'random.choice', 'random.choice', (['"""abcdefghijklmnoprstquwyxz"""'], {}), "('abcdefghijklmnoprstquwyxz')\n", (668, 697), False, 'import random\n'), ((1321, 1330), 'multiprocessing.Manager', 'Manager', ([], {}), '()\n', (1328, 1330), False, 'from multiprocessing import Process, Manager\n'), ((5933, 5971), 'copy.deepcopy', 'deepcopy', (["cal_shared_best['solutions']"], {}), "(cal_shared_best['solutions'])\n", (5941, 5971), False, 'from copy import deepcopy\n'), ((5973, 6015), 'copy.deepcopy', 'deepcopy', (["cal_shared_best['iter_counters']"], {}), "(cal_shared_best['iter_counters'])\n", (5981, 6015), False, 'from copy import deepcopy\n'), ((9408, 9423), 'numpy.zeros', 'np.zeros', (['nobjs'], {}), '(nobjs)\n', (9416, 9423), True, 'import numpy as np\n'), ((9707, 9722), 'numpy.zeros', 'np.zeros', (['nobjs'], {}), '(nobjs)\n', (9715, 9722), True, 'import numpy as np\n'), ((9874, 9889), 'numpy.zeros', 'np.zeros', (['nobjs'], {}), '(nobjs)\n', (9882, 9889), True, 'import numpy as np\n'), ((10275, 10295), 'numpy.hstack', 'np.hstack', (['pop_evals'], {}), '(pop_evals)\n', (10284, 10295), True, 'import numpy as np\n'), ((10487, 10515), 'pygamoo.utils.get_not_dominated', 'get_not_dominated', (['pop_evals'], {}), '(pop_evals)\n', (10504, 10515), False, 'from pygamoo.utils import evaluate_call, get_not_dominated, front_suppression\n'), ((11116, 11156), 'pygamoo.utils.front_suppression', 'front_suppression', (['front_eval', 'max_front'], {}), '(front_eval, max_front)\n', (11133, 11156), False, 'from pygamoo.utils import evaluate_call, get_not_dominated, front_suppression\n'), ((6169, 6226), 'pika.BasicProperties', 'pika.BasicProperties', ([], {'correlation_id': 'props.correlation_id'}), '(correlation_id=props.correlation_id)\n', (6189, 6226), False, 'import pika\n'), ((8958, 9022), 'pygamoo.utils.RpcClient', 'RpcClient', (["cal_shared_front['objs_rpc'][i]", 'self.host', 'self.port'], {}), "(cal_shared_front['objs_rpc'][i], self.host, self.port)\n", (8967, 9022), False, 'from pygamoo.utils import RpcClient, assigning_gens\n'), ((10345, 10380), 'numpy.min', 'np.min', (['(evaluations + evaluations_m)'], {}), '(evaluations + evaluations_m)\n', (10351, 10380), True, 'import numpy as np\n'), ((10657, 10670), 'copy.deepcopy', 'deepcopy', (['pop'], {}), '(pop)\n', (10665, 10670), False, 'from copy import deepcopy\n'), ((10704, 10723), 'copy.deepcopy', 'deepcopy', (['pop_evals'], {}), '(pop_evals)\n', (10712, 10723), False, 'from copy import deepcopy\n'), ((10774, 10797), 'numpy.vstack', 'np.vstack', (['[front, pop]'], {}), '([front, pop])\n', (10783, 10797), True, 'import numpy as np\n'), ((10831, 10865), 'numpy.vstack', 'np.vstack', (['[front_eval, pop_evals]'], {}), '([front_eval, pop_evals])\n', (10840, 10865), True, 'import numpy as np\n'), ((10893, 10922), 'pygamoo.utils.get_not_dominated', 'get_not_dominated', (['front_eval'], {}), '(front_eval)\n', (10910, 10922), False, 'from pygamoo.utils import evaluate_call, get_not_dominated, front_suppression\n'), ((16106, 16144), 'pygamoo.utils.assigning_gens', 'assigning_gens', (['self.nvars', 'self.nobjs'], {}), '(self.nvars, self.nobjs)\n', (16120, 16144), False, 'from pygamoo.utils import RpcClient, assigning_gens\n'), ((17101, 17114), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (17111, 17114), False, 'import time\n'), ((15069, 15086), 'pickle.dumps', 'pickle.dumps', (['msg'], {}), '(msg)\n', (15081, 15086), False, 'import pickle\n'), ((15228, 15245), 'pickle.dumps', 'pickle.dumps', (['msg'], {}), '(msg)\n', (15240, 15245), False, 'import pickle\n'), ((15356, 15373), 'pickle.dumps', 'pickle.dumps', (['msg'], {}), '(msg)\n', (15368, 15373), False, 'import pickle\n'), ((15537, 15575), 'pygamoo.utils.assigning_gens', 'assigning_gens', (['self.nvars', 'self.nobjs'], {}), '(self.nvars, self.nobjs)\n', (15551, 15575), False, 'from pygamoo.utils import RpcClient, assigning_gens\n'), ((15942, 15959), 'pickle.dumps', 'pickle.dumps', (['msg'], {}), '(msg)\n', (15954, 15959), False, 'import pickle\n'), ((16240, 16257), 'pickle.dumps', 'pickle.dumps', (['msg'], {}), '(msg)\n', (16252, 16257), False, 'import pickle\n'), ((16587, 16604), 'pickle.dumps', 'pickle.dumps', (['msg'], {}), '(msg)\n', (16599, 16604), False, 'import pickle\n'), ((16701, 16758), 'pika.ConnectionParameters', 'pika.ConnectionParameters', ([], {'host': 'self.host', 'port': 'self.port'}), '(host=self.host, port=self.port)\n', (16726, 16758), False, 'import pika\n'), ((10216, 10245), 'numpy.reshape', 'np.reshape', (['pop_eval', '(-1, 1)'], {}), '(pop_eval, (-1, 1))\n', (10226, 10245), True, 'import numpy as np\n'), ((15679, 15696), 'pickle.dumps', 'pickle.dumps', (['msg'], {}), '(msg)\n', (15691, 15696), False, 'import pickle\n'), ((10049, 10080), 'pygamoo.utils.evaluate_call', 'evaluate_call', (['pop', 'objs_rpc[i]'], {}), '(pop, objs_rpc[i])\n', (10062, 10080), False, 'from pygamoo.utils import evaluate_call, get_not_dominated, front_suppression\n')] |
import numpy as np
from afib import BaseRisk
POAF_PTS = [1,2,3,1,1,1,1,1,1]
def poaf(age, copd, egfr, emrgncy, pibp, lvef, vs):
arr = np.array([60 <= age <= 69,
70 <= age <= 79,
age >= 80,
copd,
egfr < 15,
emrgncy,
pibp,
lvef < (30/100),
vs], dtype=int)
return arr.dot(POAF_PTS)
class PoafC(BaseRisk):
#array = ["age","copd","egfr","emrgncy","pibp","lvef","vs"]
def score(self, row):
return poaf(row["age"],
row["copd"],
row["egfr"],
row["emrgncy"],
row["pibp"],
row["lvef"],
row["vs"]) | [
"numpy.array"
] | [((141, 264), 'numpy.array', 'np.array', (['[60 <= age <= 69, 70 <= age <= 79, age >= 80, copd, egfr < 15, emrgncy,\n pibp, lvef < 30 / 100, vs]'], {'dtype': 'int'}), '([60 <= age <= 69, 70 <= age <= 79, age >= 80, copd, egfr < 15,\n emrgncy, pibp, lvef < 30 / 100, vs], dtype=int)\n', (149, 264), True, 'import numpy as np\n')] |
from param import Param
from grid import Grid
from fluid2d import Fluid2d
import numpy as np
param = Param('default.xml')
param.modelname = 'euler'
param.expname = 'turb2d_forced_ss'
# domain and resolution
param.nx = 64*2
param.ny = param.nx
param.Ly = param.Lx
param.npx = 1
param.npy = 1
param.geometry = 'perio'
# time
param.tend = 500.
param.cfl = 1.2
param.adaptable_dt = True
param.dt = .05
param.dtmax = 10.
# discretization
param.order = 5
# output
param.var_to_save = ['vorticity', 'psi', 'tracer']
param.list_diag = 'all'
param.freq_plot = 5
param.freq_his = 20
param.freq_diag = 10
param.exacthistime = True
# plot
param.plot_interactive = True
param.plot_var = 'vorticity'
param.plot_psi = False
param.cmap = 'Spectral'
param.cax = np.array([-1, 1])*.3
param.colorscheme = 'imposed'
param.generate_mp4 = True
# physics
param.forcing = True
param.forcing_module = 'embedded'
param.tau = 1.
param.k0 = 0.5*param.nx
param.noslip = False
param.diffusion = False
param.decay = False
#
# add a passive tracer
param.additional_tracer = ['tracer']
class Forcing(Param):
""" define the forcing """
def __init__(self, param, grid):
self.list_param = ['sizevar', 'tau', 'k0']
param.copy(self, self.list_param)
self.list_param = ['nh', 'msk', 'fill_halo', 'nx', 'ny',
'domain_integration', 'area']
grid.copy(self, self.list_param)
def set_x_and_k(n, L):
k = ((n//2+np.arange(n)) % n) - n//2
return (np.arange(n)+0.5)*L/n, 2*np.pi*k/L
self.t0 = 0.
_, kx = set_x_and_k(param.nx, np.pi)
_, ky = set_x_and_k(param.ny, np.pi)
kkx, kky = np.meshgrid(kx, ky)
self.kk = np.sqrt(kkx**2 + kky**2)
k0 = self.k0
dk = .1
# the forcing has a gaussian spectrum
self.amplitude = 1e3*np.exp(-(self.kk-k0)**2/(2*dk**2))
self.forc = np.zeros(self.sizevar)
def add_forcing(self, x, t, dxdt):
""" add the forcing term on x[0]=the vorticity """
dt = t-self.t0
self.t0 = t
gamma = dt/self.tau
nh = self.nh
# white noise phase
phase = np.random.normal(size=(self.ny, self.nx))*2*np.pi
hnoise = self.amplitude*np.exp(1j*phase)
forc = np.real(np.fft.ifft2(hnoise))
# time filter to introduce some time correlation in the forcing
self.forc[nh:-nh, nh:-nh] = gamma*forc + \
self.forc[nh:-nh, nh:-nh]*(1-gamma)
self.fill_halo(self.forc)
# impose zero net vorticity (otherwise the solver does not converge)
self.forc -= self.domain_integration(self.forc) / self.area
# add the forcing to the vorticity tendency
dxdt[0] += self.forc
grid = Grid(param)
param.Kdiff = 5e-4*grid.dx
f2d = Fluid2d(param, grid)
model = f2d.model
model.forc = Forcing(param, grid)
xr, yr = grid.xr, grid.yr
vor = model.var.get('vorticity')
trac = model.var.get('tracer')
# set an initial small scale random vorticity field (white noise)
np.random.seed(42)
def set_x_and_k(n, L):
k = ((n//2+np.arange(n)) % n) - n//2
return (np.arange(n)+0.5)*L/n, 2*np.pi*k/L
_, kx = set_x_and_k(param.nx, np.pi)
_, ky = set_x_and_k(param.ny, np.pi)
kkx, kky = np.meshgrid(kx, ky)
kk = np.sqrt(kkx**2 + kky**2)
k0 = param.k0
dk = 1
phase = np.random.normal(size=(param.ny, param.nx))*2*np.pi
hnoise = np.exp(-(kk-k0)**2/(2*dk**2))*np.exp(1j*phase)
noise = np.zeros_like(vor)
nh = grid.nh
noise[nh:-nh, nh:-nh] = 1e3*np.real(np.fft.ifft2(hnoise))
grid.fill_halo(noise)
noise -= grid.domain_integration(noise)*grid.msk/grid.area
vor[:] = noise*grid.msk
# initialize the passive tracer with square tiles (better idea?)
trac[:] = np.round(xr*6) % 2 + np.round(yr*6) % 2
model.set_psi_from_vorticity()
model.diagnostics(model.var, 0)
energy = model.diags['ke']
print('energy=', energy)
vor = vor*param.Lx/np.sqrt(energy)
vor = vor/1e3
model.set_psi_from_vorticity()
f2d.loop()
| [
"numpy.meshgrid",
"numpy.random.seed",
"numpy.zeros_like",
"grid.Grid",
"numpy.zeros",
"numpy.round",
"numpy.array",
"numpy.exp",
"numpy.random.normal",
"numpy.arange",
"numpy.fft.ifft2",
"fluid2d.Fluid2d",
"numpy.sqrt",
"param.Param"
] | [((102, 122), 'param.Param', 'Param', (['"""default.xml"""'], {}), "('default.xml')\n", (107, 122), False, 'from param import Param\n'), ((2755, 2766), 'grid.Grid', 'Grid', (['param'], {}), '(param)\n', (2759, 2766), False, 'from grid import Grid\n'), ((2801, 2821), 'fluid2d.Fluid2d', 'Fluid2d', (['param', 'grid'], {}), '(param, grid)\n', (2808, 2821), False, 'from fluid2d import Fluid2d\n'), ((3032, 3050), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (3046, 3050), True, 'import numpy as np\n'), ((3251, 3270), 'numpy.meshgrid', 'np.meshgrid', (['kx', 'ky'], {}), '(kx, ky)\n', (3262, 3270), True, 'import numpy as np\n'), ((3276, 3304), 'numpy.sqrt', 'np.sqrt', (['(kkx ** 2 + kky ** 2)'], {}), '(kkx ** 2 + kky ** 2)\n', (3283, 3304), True, 'import numpy as np\n'), ((3450, 3468), 'numpy.zeros_like', 'np.zeros_like', (['vor'], {}), '(vor)\n', (3463, 3468), True, 'import numpy as np\n'), ((751, 768), 'numpy.array', 'np.array', (['[-1, 1]'], {}), '([-1, 1])\n', (759, 768), True, 'import numpy as np\n'), ((3394, 3433), 'numpy.exp', 'np.exp', (['(-(kk - k0) ** 2 / (2 * dk ** 2))'], {}), '(-(kk - k0) ** 2 / (2 * dk ** 2))\n', (3400, 3433), True, 'import numpy as np\n'), ((3424, 3444), 'numpy.exp', 'np.exp', (['(1.0j * phase)'], {}), '(1.0j * phase)\n', (3430, 3444), True, 'import numpy as np\n'), ((3898, 3913), 'numpy.sqrt', 'np.sqrt', (['energy'], {}), '(energy)\n', (3905, 3913), True, 'import numpy as np\n'), ((1678, 1697), 'numpy.meshgrid', 'np.meshgrid', (['kx', 'ky'], {}), '(kx, ky)\n', (1689, 1697), True, 'import numpy as np\n'), ((1716, 1744), 'numpy.sqrt', 'np.sqrt', (['(kkx ** 2 + kky ** 2)'], {}), '(kkx ** 2 + kky ** 2)\n', (1723, 1744), True, 'import numpy as np\n'), ((1910, 1932), 'numpy.zeros', 'np.zeros', (['self.sizevar'], {}), '(self.sizevar)\n', (1918, 1932), True, 'import numpy as np\n'), ((3332, 3375), 'numpy.random.normal', 'np.random.normal', ([], {'size': '(param.ny, param.nx)'}), '(size=(param.ny, param.nx))\n', (3348, 3375), True, 'import numpy as np\n'), ((3518, 3538), 'numpy.fft.ifft2', 'np.fft.ifft2', (['hnoise'], {}), '(hnoise)\n', (3530, 3538), True, 'import numpy as np\n'), ((3722, 3738), 'numpy.round', 'np.round', (['(xr * 6)'], {}), '(xr * 6)\n', (3730, 3738), True, 'import numpy as np\n'), ((3743, 3759), 'numpy.round', 'np.round', (['(yr * 6)'], {}), '(yr * 6)\n', (3751, 3759), True, 'import numpy as np\n'), ((1855, 1899), 'numpy.exp', 'np.exp', (['(-(self.kk - k0) ** 2 / (2 * dk ** 2))'], {}), '(-(self.kk - k0) ** 2 / (2 * dk ** 2))\n', (1861, 1899), True, 'import numpy as np\n'), ((2251, 2271), 'numpy.exp', 'np.exp', (['(1.0j * phase)'], {}), '(1.0j * phase)\n', (2257, 2271), True, 'import numpy as np\n'), ((2292, 2312), 'numpy.fft.ifft2', 'np.fft.ifft2', (['hnoise'], {}), '(hnoise)\n', (2304, 2312), True, 'import numpy as np\n'), ((2169, 2210), 'numpy.random.normal', 'np.random.normal', ([], {'size': '(self.ny, self.nx)'}), '(size=(self.ny, self.nx))\n', (2185, 2210), True, 'import numpy as np\n'), ((3091, 3103), 'numpy.arange', 'np.arange', (['n'], {}), '(n)\n', (3100, 3103), True, 'import numpy as np\n'), ((3129, 3141), 'numpy.arange', 'np.arange', (['n'], {}), '(n)\n', (3138, 3141), True, 'import numpy as np\n'), ((1465, 1477), 'numpy.arange', 'np.arange', (['n'], {}), '(n)\n', (1474, 1477), True, 'import numpy as np\n'), ((1511, 1523), 'numpy.arange', 'np.arange', (['n'], {}), '(n)\n', (1520, 1523), True, 'import numpy as np\n')] |
import numpy as np
from sklearn.base import check_array
from cvxopt import solvers, matrix
from adapt.base import BaseAdaptEstimator, make_insert_doc
from adapt.metrics import linear_discrepancy
from adapt.utils import set_random_seed
@make_insert_doc()
class LDM(BaseAdaptEstimator):
"""
LDM : Linear Discrepancy Minimization
LDM reweights the source instances in order to minimize
the linear discrepancy between the reweighted source and
the target data.
The objective function is the following:
.. math::
\min_{||w||_1 = 1, w>0} \max_{||u||=1} |u^T M(w) u|
Where:
- :math:`M(w) = (1/n) X_T^T X_T - X^T_S diag(w) X_S`
- :math:`X_S, X_T` are respectively the source dataset
and the target dataset of size :math:`m` and :math:`n`
Parameters
----------
Attributes
----------
weights_ : numpy array
Training instance weights.
estimator_ : object
Estimator.
See also
--------
KMM
KLIEP
References
----------
.. [1] `[1] <https://arxiv.org/pdf/0902.3430.pdf>`_ \
<NAME>, <NAME>, and <NAME>. "Domain \
adaptation: Learning bounds and algorithms". In COLT, 2009.
"""
def __init__(self,
estimator=None,
Xt=None,
copy=True,
verbose=1,
random_state=None,
**params):
names = self._get_param_names()
kwargs = {k: v for k, v in locals().items() if k in names}
kwargs.update(params)
super().__init__(**kwargs)
def fit_weights(self, Xs, Xt, **kwargs):
"""
Fit importance weighting.
Parameters
----------
Xs : array
Input source data.
Xt : array
Input target data.
kwargs : key, value argument
Not used, present here for adapt consistency.
Returns
-------
weights_ : sample weights
"""
Xs = check_array(Xs)
Xt = check_array(Xt)
set_random_seed(self.random_state)
if self.verbose:
disc = linear_discrepancy(Xs, Xt)
print("Initial Discrepancy : %f"%disc)
n = len(Xs)
m = len(Xt)
p = Xs.shape[1]
Mis = []
for i in range(n):
Mis.append(Xs[i].reshape(-1,1).dot(Xs[i].reshape(1,-1)).ravel())
M = np.stack(Mis, -1)
lambda_I = np.eye(p).ravel().reshape(-1, 1)
M0 = (1/m) * Xt.transpose().dot(Xt)
M0 = M0.ravel().reshape(-1, 1)
first_const_G = np.concatenate((-lambda_I, -M), axis=1)
sec_const_G = np.concatenate((-lambda_I, M), axis=1)
first_linear = np.ones((1, n+1))
first_linear[0, 0] = 0.
second_linear = -np.eye(n)
second_linear = np.concatenate((np.zeros((n, 1)), second_linear), axis=1)
G = matrix(np.concatenate((
first_linear,
-first_linear,
second_linear,
first_const_G,
sec_const_G),
axis=0)
)
h = matrix(np.concatenate((
np.ones((1, 1)),
-np.ones((1, 1)),
np.zeros((n, 1)),
-M0,
M0)
))
c = np.zeros((n+1, 1))
c[0] = 1.
c = matrix(c)
dims = {'l': 2+n, 'q': [], 's': [p, p]}
sol = solvers.conelp(c, G, h, dims)
if self.verbose:
print("Final Discrepancy : %f"%sol['primal objective'])
self.weights_ = np.array(sol["x"]).ravel()
return self.weights_
def predict_weights(self):
"""
Return fitted source weights
Returns
-------
weights_ : sample weights
"""
if hasattr(self, "weights_"):
return self.weights_
else:
raise NotFittedError("Weights are not fitted yet, please "
"call 'fit_weights' or 'fit' first.") | [
"numpy.stack",
"adapt.metrics.linear_discrepancy",
"cvxopt.matrix",
"adapt.utils.set_random_seed",
"numpy.zeros",
"numpy.ones",
"adapt.base.make_insert_doc",
"cvxopt.solvers.conelp",
"numpy.array",
"numpy.eye",
"sklearn.base.check_array",
"numpy.concatenate"
] | [((239, 256), 'adapt.base.make_insert_doc', 'make_insert_doc', ([], {}), '()\n', (254, 256), False, 'from adapt.base import BaseAdaptEstimator, make_insert_doc\n'), ((2118, 2133), 'sklearn.base.check_array', 'check_array', (['Xs'], {}), '(Xs)\n', (2129, 2133), False, 'from sklearn.base import check_array\n'), ((2147, 2162), 'sklearn.base.check_array', 'check_array', (['Xt'], {}), '(Xt)\n', (2158, 2162), False, 'from sklearn.base import check_array\n'), ((2171, 2205), 'adapt.utils.set_random_seed', 'set_random_seed', (['self.random_state'], {}), '(self.random_state)\n', (2186, 2205), False, 'from adapt.utils import set_random_seed\n'), ((2545, 2562), 'numpy.stack', 'np.stack', (['Mis', '(-1)'], {}), '(Mis, -1)\n', (2553, 2562), True, 'import numpy as np\n'), ((2723, 2762), 'numpy.concatenate', 'np.concatenate', (['(-lambda_I, -M)'], {'axis': '(1)'}), '((-lambda_I, -M), axis=1)\n', (2737, 2762), True, 'import numpy as np\n'), ((2785, 2823), 'numpy.concatenate', 'np.concatenate', (['(-lambda_I, M)'], {'axis': '(1)'}), '((-lambda_I, M), axis=1)\n', (2799, 2823), True, 'import numpy as np\n'), ((2848, 2867), 'numpy.ones', 'np.ones', (['(1, n + 1)'], {}), '((1, n + 1))\n', (2855, 2867), True, 'import numpy as np\n'), ((3398, 3418), 'numpy.zeros', 'np.zeros', (['(n + 1, 1)'], {}), '((n + 1, 1))\n', (3406, 3418), True, 'import numpy as np\n'), ((3447, 3456), 'cvxopt.matrix', 'matrix', (['c'], {}), '(c)\n', (3453, 3456), False, 'from cvxopt import solvers, matrix\n'), ((3522, 3551), 'cvxopt.solvers.conelp', 'solvers.conelp', (['c', 'G', 'h', 'dims'], {}), '(c, G, h, dims)\n', (3536, 3551), False, 'from cvxopt import solvers, matrix\n'), ((2259, 2285), 'adapt.metrics.linear_discrepancy', 'linear_discrepancy', (['Xs', 'Xt'], {}), '(Xs, Xt)\n', (2277, 2285), False, 'from adapt.metrics import linear_discrepancy\n'), ((2924, 2933), 'numpy.eye', 'np.eye', (['n'], {}), '(n)\n', (2930, 2933), True, 'import numpy as np\n'), ((3036, 3136), 'numpy.concatenate', 'np.concatenate', (['(first_linear, -first_linear, second_linear, first_const_G, sec_const_G)'], {'axis': '(0)'}), '((first_linear, -first_linear, second_linear, first_const_G,\n sec_const_G), axis=0)\n', (3050, 3136), True, 'import numpy as np\n'), ((2974, 2990), 'numpy.zeros', 'np.zeros', (['(n, 1)'], {}), '((n, 1))\n', (2982, 2990), True, 'import numpy as np\n'), ((3687, 3705), 'numpy.array', 'np.array', (["sol['x']"], {}), "(sol['x'])\n", (3695, 3705), True, 'import numpy as np\n'), ((3265, 3280), 'numpy.ones', 'np.ones', (['(1, 1)'], {}), '((1, 1))\n', (3272, 3280), True, 'import numpy as np\n'), ((3324, 3340), 'numpy.zeros', 'np.zeros', (['(n, 1)'], {}), '((n, 1))\n', (3332, 3340), True, 'import numpy as np\n'), ((2582, 2591), 'numpy.eye', 'np.eye', (['p'], {}), '(p)\n', (2588, 2591), True, 'import numpy as np\n'), ((3295, 3310), 'numpy.ones', 'np.ones', (['(1, 1)'], {}), '((1, 1))\n', (3302, 3310), True, 'import numpy as np\n')] |
import argparse
import numpy as np
import os
import copy
import spglib
from numpy.linalg import norm, solve
from pymatgen.io.vasp.inputs import Poscar
from ase.io import write, read
from ase.utils import gcd, basestring
from ase.build import bulk
from pymatgen.core.structure import Structure
from pymatgen.core.lattice import Lattice
from pymatgen.symmetry.analyzer import SpacegroupAnalyzer
def surface(lattice, indices, layers, vacuum=None, tol=1e-10):
"""Create surface from a given lattice and Miller indices.
lattice: Atoms object or str
Bulk lattice structure of alloy or pure metal. Note that the
unit-cell must be the conventional cell - not the primitive cell.
One can also give the chemical symbol as a string, in which case the
correct bulk lattice will be generated automatically.
indices: sequence of three int
Surface normal in Miller indices (h,k,l).
layers: int
Number of equivalent layers of the slab.
vacuum: float
Amount of vacuum added on both sides of the slab.
"""
indices = np.asarray(indices)
if indices.shape != (3,) or not indices.any() or indices.dtype != int:
raise ValueError('%s is an invalid surface type' % indices)
if isinstance(lattice, basestring):
lattice = bulk(lattice, cubic=True)
h, k, l = indices
h0, k0, l0 = (indices == 0)
if h0 and k0 or h0 and l0 or k0 and l0: # if two indices are zero
if not h0:
c1, c2, c3 = [(0, 1, 0), (0, 0, 1), (1, 0, 0)]
if not k0:
c1, c2, c3 = [(0, 0, 1), (1, 0, 0), (0, 1, 0)]
if not l0:
c1, c2, c3 = [(1, 0, 0), (0, 1, 0), (0, 0, 1)]
else:
p, q = ext_gcd(k, l)
a1, a2, a3 = lattice.cell
# constants describing the dot product of basis c1 and c2:
# dot(c1,c2) = k1+i*k2, i in Z
k1 = np.dot(p * (k * a1 - h * a2) + q * (l * a1 - h * a3),
l * a2 - k * a3)
k2 = np.dot(l * (k * a1 - h * a2) - k * (l * a1 - h * a3),
l * a2 - k * a3)
if abs(k2) > tol:
i = -int(round(k1 / k2)) # i corresponding to the optimal basis
p, q = p + i * l, q - i * k
a, b = ext_gcd(p * k + q * l, h)
c1 = (p * k + q * l, -p * h, -q * h)
c2 = np.array((0, l, -k)) // abs(gcd(l, k))
c3 = (b, a * p, a * q)
surf = build(lattice, np.array([c1, c2, c3]), layers, tol)
if vacuum is not None:
surf.center(vacuum=vacuum, axis=2)
return surf
def build(lattice, basis, layers, tol):
surf = lattice.copy()
scaled = solve(basis.T, surf.get_scaled_positions().T).T
scaled -= np.floor(scaled + tol)
surf.set_scaled_positions(scaled)
surf.set_cell(np.dot(basis, surf.cell), scale_atoms=True)
surf *= (1, 1, layers)
a1, a2, a3 = surf.cell
surf.set_cell([a1, a2,
np.cross(a1, a2) * np.dot(a3, np.cross(a1, a2)) /
norm(np.cross(a1, a2))**2])
surf.pbc = (True, True, False)
# Move atoms into the unit cell:
scaled = surf.get_scaled_positions()
scaled[:, :2] %= 1
surf.set_scaled_positions(scaled)
surf.cell[2] = 0.0
return surf
def ext_gcd(a, b):
if b == 0:
return 1, 0
elif a % b == 0:
return 0, 1
else:
x, y = ext_gcd(b, a % b)
return y, x - y * (a // b)
def convert(bulk, slab, index, output, generate=True, print_M=True):
if type(bulk) == str:
primitiveCell = Structure.from_file(bulk)
else:
primitiveCell = bulk
if type(slab) == str:
refSlab = Structure.from_file(slab)
else:
refSlab = slab
sa = SpacegroupAnalyzer(primitiveCell)
conventionalCell = sa.get_conventional_standard_structure()
conventionalCell.to(filename='POSCAR.conventional')
bulk = read('POSCAR.conventional')
os.remove('POSCAR.conventional')
slab = surface(bulk, index, layers=2, vacuum=10)
lattice, _, _ = spglib.standardize_cell(cell=(slab.get_cell(
), slab.get_scaled_positions(), slab.get_atomic_numbers()), no_idealize=True)
lattice_params = np.sort(np.linalg.norm(lattice, axis=1))[:2]
scales = np.round(np.array([refSlab.lattice.a, refSlab.lattice.b] / lattice_params), 2)
newLattice = []
oldLattice = refSlab.lattice
for length, scale in zip([oldLattice.a, oldLattice.b], scales):
for j in range(len(lattice)):
if abs((np.linalg.norm(lattice[j]) * scale) - length) < 1e-1:
newLattice.append(copy.copy(scale * lattice[j][:]))
lattice[j] = [0, 0, 0]
break
for i in range(len(lattice)):
norm = np.linalg.norm(lattice[i])
if norm > 1e-1:
newLattice.append(lattice[i] / norm * oldLattice.c)
break
newLattice = Lattice(np.array(newLattice))
for x, y in zip(oldLattice.angles, newLattice.angles):
assert abs(x-y) < 1e-2, "The converted lattice has incorrect angles: {} compared with reference slab: {}".format(
" ".join(str(x) for x in newLattice.angles), " ".join(str(x) for x in oldLattice.angles))
newSlab = Structure(newLattice, [], [])
for atom in refSlab:
newSlab.append(atom.specie, atom.frac_coords[:])
if generate:
Poscar(newSlab.get_sorted_structure()).write_file(output, direct=True)
transformMat = newSlab.lattice.matrix.dot(
np.linalg.inv(primitiveCell.lattice.matrix))
transformMat = transformMat.round().astype(int)
if print_M:
print('-------------------------------------------')
print('Your Transformtaion Matrix is:')
print(' ')
print(transformMat)
print('-------------------------------------------')
return transformMat
if __name__ == "__main__":
bulk = './POSCAR_bulk'
slab = './POSCAR_10_100_22'
index = [1,0,0]
# bulk = './POSCAR_HgTe_ept'
# slab = './POSCAR_18'
# index = [1,0,0]
output = 'POSCAR_conv2'
M = convert(bulk, slab, index, output)
| [
"os.remove",
"ase.build.bulk",
"numpy.asarray",
"numpy.floor",
"numpy.cross",
"copy.copy",
"pymatgen.core.structure.Structure",
"numpy.array",
"ase.io.read",
"pymatgen.symmetry.analyzer.SpacegroupAnalyzer",
"numpy.linalg.norm",
"numpy.linalg.inv",
"numpy.dot",
"ase.utils.gcd",
"pymatgen.... | [((1088, 1107), 'numpy.asarray', 'np.asarray', (['indices'], {}), '(indices)\n', (1098, 1107), True, 'import numpy as np\n'), ((2693, 2715), 'numpy.floor', 'np.floor', (['(scaled + tol)'], {}), '(scaled + tol)\n', (2701, 2715), True, 'import numpy as np\n'), ((3703, 3736), 'pymatgen.symmetry.analyzer.SpacegroupAnalyzer', 'SpacegroupAnalyzer', (['primitiveCell'], {}), '(primitiveCell)\n', (3721, 3736), False, 'from pymatgen.symmetry.analyzer import SpacegroupAnalyzer\n'), ((3868, 3895), 'ase.io.read', 'read', (['"""POSCAR.conventional"""'], {}), "('POSCAR.conventional')\n", (3872, 3895), False, 'from ase.io import write, read\n'), ((3900, 3932), 'os.remove', 'os.remove', (['"""POSCAR.conventional"""'], {}), "('POSCAR.conventional')\n", (3909, 3932), False, 'import os\n'), ((5179, 5208), 'pymatgen.core.structure.Structure', 'Structure', (['newLattice', '[]', '[]'], {}), '(newLattice, [], [])\n', (5188, 5208), False, 'from pymatgen.core.structure import Structure\n'), ((1311, 1336), 'ase.build.bulk', 'bulk', (['lattice'], {'cubic': '(True)'}), '(lattice, cubic=True)\n', (1315, 1336), False, 'from ase.build import bulk\n'), ((1891, 1961), 'numpy.dot', 'np.dot', (['(p * (k * a1 - h * a2) + q * (l * a1 - h * a3))', '(l * a2 - k * a3)'], {}), '(p * (k * a1 - h * a2) + q * (l * a1 - h * a3), l * a2 - k * a3)\n', (1897, 1961), True, 'import numpy as np\n'), ((1995, 2065), 'numpy.dot', 'np.dot', (['(l * (k * a1 - h * a2) - k * (l * a1 - h * a3))', '(l * a2 - k * a3)'], {}), '(l * (k * a1 - h * a2) - k * (l * a1 - h * a3), l * a2 - k * a3)\n', (2001, 2065), True, 'import numpy as np\n'), ((2427, 2449), 'numpy.array', 'np.array', (['[c1, c2, c3]'], {}), '([c1, c2, c3])\n', (2435, 2449), True, 'import numpy as np\n'), ((2772, 2796), 'numpy.dot', 'np.dot', (['basis', 'surf.cell'], {}), '(basis, surf.cell)\n', (2778, 2796), True, 'import numpy as np\n'), ((3525, 3550), 'pymatgen.core.structure.Structure.from_file', 'Structure.from_file', (['bulk'], {}), '(bulk)\n', (3544, 3550), False, 'from pymatgen.core.structure import Structure\n'), ((3634, 3659), 'pymatgen.core.structure.Structure.from_file', 'Structure.from_file', (['slab'], {}), '(slab)\n', (3653, 3659), False, 'from pymatgen.core.structure import Structure\n'), ((4221, 4286), 'numpy.array', 'np.array', (['([refSlab.lattice.a, refSlab.lattice.b] / lattice_params)'], {}), '([refSlab.lattice.a, refSlab.lattice.b] / lattice_params)\n', (4229, 4286), True, 'import numpy as np\n'), ((4702, 4728), 'numpy.linalg.norm', 'np.linalg.norm', (['lattice[i]'], {}), '(lattice[i])\n', (4716, 4728), True, 'import numpy as np\n'), ((4860, 4880), 'numpy.array', 'np.array', (['newLattice'], {}), '(newLattice)\n', (4868, 4880), True, 'import numpy as np\n'), ((5444, 5487), 'numpy.linalg.inv', 'np.linalg.inv', (['primitiveCell.lattice.matrix'], {}), '(primitiveCell.lattice.matrix)\n', (5457, 5487), True, 'import numpy as np\n'), ((2331, 2351), 'numpy.array', 'np.array', (['(0, l, -k)'], {}), '((0, l, -k))\n', (2339, 2351), True, 'import numpy as np\n'), ((4162, 4193), 'numpy.linalg.norm', 'np.linalg.norm', (['lattice'], {'axis': '(1)'}), '(lattice, axis=1)\n', (4176, 4193), True, 'import numpy as np\n'), ((2359, 2368), 'ase.utils.gcd', 'gcd', (['l', 'k'], {}), '(l, k)\n', (2362, 2368), False, 'from ase.utils import gcd, basestring\n'), ((2916, 2932), 'numpy.cross', 'np.cross', (['a1', 'a2'], {}), '(a1, a2)\n', (2924, 2932), True, 'import numpy as np\n'), ((4558, 4590), 'copy.copy', 'copy.copy', (['(scale * lattice[j][:])'], {}), '(scale * lattice[j][:])\n', (4567, 4590), False, 'import copy\n'), ((2946, 2962), 'numpy.cross', 'np.cross', (['a1', 'a2'], {}), '(a1, a2)\n', (2954, 2962), True, 'import numpy as np\n'), ((2990, 3006), 'numpy.cross', 'np.cross', (['a1', 'a2'], {}), '(a1, a2)\n', (2998, 3006), True, 'import numpy as np\n'), ((4470, 4496), 'numpy.linalg.norm', 'np.linalg.norm', (['lattice[j]'], {}), '(lattice[j])\n', (4484, 4496), True, 'import numpy as np\n')] |
#!/usr/bin/env python
import os
import argparse
import yaml
import sys
from collections import defaultdict
import logging
import numpy as np
import platform
from phantom_analysis import dicom_util, scalar_analysis, voi_analysis, phantom_definitions
WINDOWS = True if platform.system() == 'Windows' else False
CLAMP = (0, 4000)
def isclose(a, b, rel_tol=1e-06, abs_tol=1e-3):
return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
def fuzzy_compare_dict(a, b):
if len(a) != len(b):
return False
for k in a.keys():
if k not in b:
return False
if isinstance(a[k], dict):
if not (isinstance(b[k], dict) and fuzzy_compare_dict(a[k], b[k])):
return False
elif isinstance(a[k], float):
if not (isinstance(b[k], float) and isclose(a[k], b[k])):
return False
else:
if not a[k] == b[k]:
return False
return True
def rounded_float_representer(dumper, value):
text = '{0:.4f}'.format(value)
return dumper.represent_scalar(u'tag:yaml.org,2002:float', text)
def baseline_format(expected, dir_output, voi_output, phantom_definition):
baseline = defaultdict(lambda: defaultdict) # 2 keys deep
center_distances = []
volume_differences = []
scalar_median_differences = []
scalar_mean_differences = []
total_clamped_pixels = 0
# Calculate scalar maps and VOI stats
scalar_type = dir_output["scalar_type"]
label_map = voi_output["label_map"]
if scalar_type == "ADC":
scalar_map = scalar_analysis.calculate_adc(dir_output["dwi"], dir_output["bvalues"]) * 1e6
voi_stats = scalar_analysis.voi_stats(label_map, scalar_map, dir_output["image_coordinate_system"], phantom_definition)
elif scalar_type == "T1":
scalar_map = scalar_analysis.calculate_t1(dir_output["dwi"], dir_output["alphas"], dir_output["rep_time_seconds"], use_pool= not WINDOWS, clamp=CLAMP, threshold=5)
voi_stats = scalar_analysis.voi_stats(label_map, scalar_map, dir_output["image_coordinate_system"], phantom_definition, clamp=CLAMP)
else:
# Shouldn't ever get here
return baseline
# Analyze stats for each VOI
vois = voi_output["found_vois"]
for voi in vois:
expected_voi_dict = expected[voi]
baseline[voi] = {}
# Compare center coordinates and variation in center
if "center" in vois[voi]:
center_info = {
"center_left_cm": vois[voi]["center"][0],
"center_posterior_cm": vois[voi]["center"][1],
"center_superior_cm": vois[voi]["center"][2],
"std_dev_of_coronal_center": { "coronal x": vois[voi]["coronal_center_std_dev"][0], "coronal y": vois[voi]["coronal_center_std_dev"][1] }
}
baseline[voi].update(center_info)
# Compare found center to expected (if known)
if "center_left_cm" in expected_voi_dict:
center_distance_cm = np.linalg.norm(np.array([expected_voi_dict["center_left_cm"],
expected_voi_dict["center_posterior_cm"],
expected_voi_dict["center_superior_cm"]]) - vois[voi]["center"])
center_distances.append(center_distance_cm)
baseline[voi].update({ "center_distance_cm": center_distance_cm })
# Compare scalar stats to expected values for this dataset (ADC/T1)
scalar_type = scalar_type.lower()
if voi in voi_stats:
median_diff = expected_voi_dict["{}_median".format(scalar_type)] - voi_stats[voi]["median"]
mean_diff = expected_voi_dict["{}_mean".format(scalar_type)] - voi_stats[voi]["mean"]
scalar_median_differences.append(np.abs(median_diff))
scalar_mean_differences.append(np.abs(mean_diff))
total_clamped_pixels += voi_stats[voi]["clamped_pixels"]
volume_difference_percent = (voi_stats[voi]["volume"] - expected_voi_dict["volume_cm3"])/expected_voi_dict["volume_cm3"] * 100
volume_differences.append(volume_difference_percent)
baseline[voi].update({
"{}_median".format(scalar_type): voi_stats[voi]["median"],
"{}_median_difference".format(scalar_type): median_diff,
"{}_mean".format(scalar_type): voi_stats[voi]["mean"],
"{}_mean_difference".format(scalar_type): mean_diff,
"{}_max".format(scalar_type): voi_stats[voi]["max"],
"{}_min".format(scalar_type): voi_stats[voi]["min"],
"{}_std_dev".format(scalar_type): voi_stats[voi]["std_dev"],
"number_clamped_pixels": voi_stats[voi]["clamped_pixels"],
"volume_cm3": voi_stats[voi]["volume"],
"volume_difference_percent": volume_difference_percent
})
# Gather information about entire dataset
missing_voi_count = len(expected.keys()) - len(voi_stats.keys())
baseline.update({
"center_max_distance_cm": max(center_distances) if center_distances else 0.0,
"center_average_distance_cm": np.mean(center_distances) if center_distances else 0.0,
"volume_max_difference_percent": max(volume_differences) if volume_differences else 0.0,
"volume_average_difference_percent": np.mean(volume_differences) if volume_differences else 0.0,
"missing_voi_count": missing_voi_count,
"{}_median_max_difference".format(scalar_type): max(scalar_median_differences) if scalar_median_differences else 0.0,
"{}_median_average_difference".format(scalar_type): np.mean(scalar_median_differences) if scalar_median_differences else 0.0,
"{}_mean_max_difference".format(scalar_type): max(scalar_mean_differences) if scalar_mean_differences else 0.0,
"{}_mean_average_difference".format(scalar_type): np.mean(scalar_mean_differences) if scalar_mean_differences else 0.0,
"total_clamped_pixels": total_clamped_pixels,
"error_in_voi_finding_for_dataset": voi_output["total_error"]
})
return baseline
def test_voi(update_baseline=False):
"""
Compare volume of interest finding against previously saved baselines.
Args:
update_baseline: update baseline files if actual results don't match
Returns:
Number of test failures (returns zero if everything passes).
"""
# simplify yaml representation to be more human readable and to round floats for simpler comparison
yaml.add_representer(defaultdict, yaml.representer.Representer.represent_dict)
yaml.add_representer(np.float64, rounded_float_representer)
yaml.add_representer(np.float32, rounded_float_representer)
yaml.add_representer(float, rounded_float_representer)
# Get test cases
test_voi_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "test_data", "voi")
all_cases = os.listdir(os.path.join(test_voi_dir, "adc")) + os.listdir(os.path.join(test_voi_dir, "t1"))
# Initialize counters and arrays
test_cases = 0
fail_count = 0
missing_voi_per_test_case = []
average_center_distance_per_test_case = []
max_center_distance = 0
average_volume_difference_per_test_case = []
max_volume_difference = 0
average_t1_median_difference_per_test_case = []
max_t1_median_difference = 0
average_t1_mean_difference_per_test_case = []
max_t1_mean_difference = 0
average_adc_median_difference_per_test_case = []
max_adc_median_difference = 0
average_adc_mean_difference_per_test_case = []
max_adc_mean_difference = 0
# Process each test case
for test_case in sorted(all_cases):
logging.info("Test case %s" % test_case)
test_cases += 1
# Parse name of directory
# Naming scheme for test directories is model_num_t1shape_scalar_date_scan
dir_name_parts = test_case.upper().split("_")
if len(dir_name_parts) != 6:
logging.warn("test case {} incorrectly formatted".format(test_case))
continue
model_num = dir_name_parts[0] + "_" + dir_name_parts[1]
t1_vial_shape = dir_name_parts[2]
scalar_type = dir_name_parts[3]
# Read directory
test_case_dir = os.path.join(test_voi_dir, scalar_type.lower(), test_case)
try:
dir_output = dicom_util.read_dicomdir(test_case_dir)
except Exception:
logging.warn("Failed to read DICOM files.")
raise
# Get flag for debug in get_vois()
debug = float(os.environ.get("PHANTOM_ANALYSIS_SHOW_INTERMEDIATE_RESULTS", "0")) != 0.0
# Check scalar type and get phantom definition for this dataset
assert dir_output["scalar_type"] == scalar_type
phantom_def_name = model_num + "_" + t1_vial_shape + "_" + scalar_type
phantom_def = getattr(phantom_definitions, phantom_def_name)
# Get vois for this dataset and phantom definition
voi_output = voi_analysis.get_vois(dir_output["dwi"], dir_output["image_coordinate_system"], phantom_def, debug, name=test_case)
# Get baseline and expected files for this dataset
baseline_path = os.path.join(test_case_dir, "baseline.yaml")
expected_path = os.path.join(test_case_dir, "target.yaml")
with open(expected_path, 'r') as expected_file:
expected = yaml.safe_load(expected_file)
if os.path.exists(baseline_path):
with open(baseline_path, 'r') as baseline_file:
baseline = yaml.safe_load(baseline_file)
else:
baseline = None
# compare baseline to vois after formatting through yaml to ensure same floating point precision
actual = yaml.safe_load(yaml.dump(baseline_format(expected, dir_output, voi_output, phantom_def)))
if not fuzzy_compare_dict(actual, baseline):
logging.warn("\tFAIL")
fail_count += 1
if update_baseline:
logging.info("\tupdating baseline")
with open(baseline_path, 'w') as baseline_file:
yaml.dump(actual, baseline_file)
else:
actual_path = "actual_%s.yaml" % test_case
with open(actual_path, 'w') as actual_file:
yaml.dump(actual, actual_file)
logging.warn("\tactual results don't match baseline: compare %s %s" % (baseline_path, actual_path))
else:
logging.info("\tPASS")
# track summary info
missing_voi_per_test_case.append(actual["missing_voi_count"])
average_center_distance_per_test_case.append(actual["center_average_distance_cm"])
max_center_distance = max(max_center_distance, actual["center_max_distance_cm"])
average_volume_difference_per_test_case.append(actual["volume_average_difference_percent"])
max_volume_difference = max(max_volume_difference, actual["volume_max_difference_percent"])
if dir_output["scalar_type"] == "T1":
average_t1_median_difference_per_test_case.append(actual["t1_median_average_difference"])
max_t1_median_difference = max(max_t1_median_difference, actual["t1_median_max_difference"])
average_t1_mean_difference_per_test_case.append(actual["t1_mean_average_difference"])
max_t1_mean_difference = max(max_t1_mean_difference, actual["t1_mean_max_difference"])
elif dir_output["scalar_type"] == "ADC":
average_adc_median_difference_per_test_case.append(actual["adc_median_average_difference"])
max_adc_median_difference = max(max_adc_median_difference, actual["adc_median_max_difference"])
average_adc_mean_difference_per_test_case.append(actual["adc_mean_average_difference"])
max_adc_mean_difference = max(max_adc_mean_difference, actual["adc_mean_max_difference"])
summary = {
"test_cases": test_cases,
"voi_missing_max": max(missing_voi_per_test_case),
"voi_missing_average": np.mean(missing_voi_per_test_case),
"voi_center_max_distance_cm": max_center_distance,
"voi_center_average_distance_cm": np.mean(average_center_distance_per_test_case),
"voi_volume_max_difference_percent": max_volume_difference,
"voi_volume_average_difference_percent": np.mean(average_volume_difference_per_test_case),
"t1_median_max_difference": max_t1_median_difference,
"t1_median_average_difference": np.mean(average_t1_median_difference_per_test_case),
"t1_mean_max_difference": max_t1_mean_difference,
"t1_mean_average_difference": np.mean(average_t1_mean_difference_per_test_case),
"adc_median_max_difference": max_adc_median_difference,
"adc_median_average_difference": np.mean(average_adc_median_difference_per_test_case),
"adc_mean_max_difference": max_adc_mean_difference,
"adc_mean_average_difference": np.mean(average_adc_mean_difference_per_test_case)
}
with open(os.path.join(test_voi_dir, "summary.yaml"), 'w') as summary_file:
yaml.dump(summary, summary_file)
return fail_count
def main():
parser = argparse.ArgumentParser(description="Test if voi calculations match saved baseline")
parser.add_argument('-u', '--update-baseline', action='store_true',
help="Write new baseline if baseline missing or doesn't match")
args = parser.parse_args()
failures = test_voi(args.update_baseline)
sys.exit(1 if failures else 0)
if __name__ == "__main__":
logging.getLogger().setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
logging.getLogger().handlers[0].setFormatter(formatter)
main()
| [
"phantom_analysis.scalar_analysis.voi_stats",
"argparse.ArgumentParser",
"numpy.abs",
"yaml.dump",
"collections.defaultdict",
"logging.Formatter",
"phantom_analysis.scalar_analysis.calculate_adc",
"numpy.mean",
"yaml.safe_load",
"os.path.join",
"os.path.abspath",
"os.path.exists",
"yaml.add_... | [((1210, 1243), 'collections.defaultdict', 'defaultdict', (['(lambda : defaultdict)'], {}), '(lambda : defaultdict)\n', (1221, 1243), False, 'from collections import defaultdict\n'), ((6621, 6699), 'yaml.add_representer', 'yaml.add_representer', (['defaultdict', 'yaml.representer.Representer.represent_dict'], {}), '(defaultdict, yaml.representer.Representer.represent_dict)\n', (6641, 6699), False, 'import yaml\n'), ((6704, 6763), 'yaml.add_representer', 'yaml.add_representer', (['np.float64', 'rounded_float_representer'], {}), '(np.float64, rounded_float_representer)\n', (6724, 6763), False, 'import yaml\n'), ((6768, 6827), 'yaml.add_representer', 'yaml.add_representer', (['np.float32', 'rounded_float_representer'], {}), '(np.float32, rounded_float_representer)\n', (6788, 6827), False, 'import yaml\n'), ((6832, 6886), 'yaml.add_representer', 'yaml.add_representer', (['float', 'rounded_float_representer'], {}), '(float, rounded_float_representer)\n', (6852, 6886), False, 'import yaml\n'), ((13291, 13380), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Test if voi calculations match saved baseline"""'}), "(description=\n 'Test if voi calculations match saved baseline')\n", (13314, 13380), False, 'import argparse\n'), ((13619, 13649), 'sys.exit', 'sys.exit', (['(1 if failures else 0)'], {}), '(1 if failures else 0)\n', (13627, 13649), False, 'import sys\n'), ((13742, 13800), 'logging.Formatter', 'logging.Formatter', (['"""%(asctime)s %(levelname)s %(message)s"""'], {}), "('%(asctime)s %(levelname)s %(message)s')\n", (13759, 13800), False, 'import logging\n'), ((270, 287), 'platform.system', 'platform.system', ([], {}), '()\n', (285, 287), False, 'import platform\n'), ((1684, 1796), 'phantom_analysis.scalar_analysis.voi_stats', 'scalar_analysis.voi_stats', (['label_map', 'scalar_map', "dir_output['image_coordinate_system']", 'phantom_definition'], {}), "(label_map, scalar_map, dir_output[\n 'image_coordinate_system'], phantom_definition)\n", (1709, 1796), False, 'from phantom_analysis import dicom_util, scalar_analysis, voi_analysis, phantom_definitions\n'), ((7793, 7833), 'logging.info', 'logging.info', (["('Test case %s' % test_case)"], {}), "('Test case %s' % test_case)\n", (7805, 7833), False, 'import logging\n'), ((9110, 9230), 'phantom_analysis.voi_analysis.get_vois', 'voi_analysis.get_vois', (["dir_output['dwi']", "dir_output['image_coordinate_system']", 'phantom_def', 'debug'], {'name': 'test_case'}), "(dir_output['dwi'], dir_output[\n 'image_coordinate_system'], phantom_def, debug, name=test_case)\n", (9131, 9230), False, 'from phantom_analysis import dicom_util, scalar_analysis, voi_analysis, phantom_definitions\n'), ((9310, 9354), 'os.path.join', 'os.path.join', (['test_case_dir', '"""baseline.yaml"""'], {}), "(test_case_dir, 'baseline.yaml')\n", (9322, 9354), False, 'import os\n'), ((9379, 9421), 'os.path.join', 'os.path.join', (['test_case_dir', '"""target.yaml"""'], {}), "(test_case_dir, 'target.yaml')\n", (9391, 9421), False, 'import os\n'), ((9544, 9573), 'os.path.exists', 'os.path.exists', (['baseline_path'], {}), '(baseline_path)\n', (9558, 9573), False, 'import os\n'), ((12151, 12185), 'numpy.mean', 'np.mean', (['missing_voi_per_test_case'], {}), '(missing_voi_per_test_case)\n', (12158, 12185), True, 'import numpy as np\n'), ((12288, 12334), 'numpy.mean', 'np.mean', (['average_center_distance_per_test_case'], {}), '(average_center_distance_per_test_case)\n', (12295, 12334), True, 'import numpy as np\n'), ((12453, 12501), 'numpy.mean', 'np.mean', (['average_volume_difference_per_test_case'], {}), '(average_volume_difference_per_test_case)\n', (12460, 12501), True, 'import numpy as np\n'), ((12605, 12656), 'numpy.mean', 'np.mean', (['average_t1_median_difference_per_test_case'], {}), '(average_t1_median_difference_per_test_case)\n', (12612, 12656), True, 'import numpy as np\n'), ((12754, 12803), 'numpy.mean', 'np.mean', (['average_t1_mean_difference_per_test_case'], {}), '(average_t1_mean_difference_per_test_case)\n', (12761, 12803), True, 'import numpy as np\n'), ((12910, 12962), 'numpy.mean', 'np.mean', (['average_adc_median_difference_per_test_case'], {}), '(average_adc_median_difference_per_test_case)\n', (12917, 12962), True, 'import numpy as np\n'), ((13063, 13113), 'numpy.mean', 'np.mean', (['average_adc_mean_difference_per_test_case'], {}), '(average_adc_mean_difference_per_test_case)\n', (13070, 13113), True, 'import numpy as np\n'), ((13208, 13240), 'yaml.dump', 'yaml.dump', (['summary', 'summary_file'], {}), '(summary, summary_file)\n', (13217, 13240), False, 'import yaml\n'), ((1586, 1657), 'phantom_analysis.scalar_analysis.calculate_adc', 'scalar_analysis.calculate_adc', (["dir_output['dwi']", "dir_output['bvalues']"], {}), "(dir_output['dwi'], dir_output['bvalues'])\n", (1615, 1657), False, 'from phantom_analysis import dicom_util, scalar_analysis, voi_analysis, phantom_definitions\n'), ((1843, 2000), 'phantom_analysis.scalar_analysis.calculate_t1', 'scalar_analysis.calculate_t1', (["dir_output['dwi']", "dir_output['alphas']", "dir_output['rep_time_seconds']"], {'use_pool': '(not WINDOWS)', 'clamp': 'CLAMP', 'threshold': '(5)'}), "(dir_output['dwi'], dir_output['alphas'],\n dir_output['rep_time_seconds'], use_pool=not WINDOWS, clamp=CLAMP,\n threshold=5)\n", (1871, 2000), False, 'from phantom_analysis import dicom_util, scalar_analysis, voi_analysis, phantom_definitions\n'), ((2014, 2139), 'phantom_analysis.scalar_analysis.voi_stats', 'scalar_analysis.voi_stats', (['label_map', 'scalar_map', "dir_output['image_coordinate_system']", 'phantom_definition'], {'clamp': 'CLAMP'}), "(label_map, scalar_map, dir_output[\n 'image_coordinate_system'], phantom_definition, clamp=CLAMP)\n", (2039, 2139), False, 'from phantom_analysis import dicom_util, scalar_analysis, voi_analysis, phantom_definitions\n'), ((6957, 6982), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (6972, 6982), False, 'import os\n'), ((7032, 7065), 'os.path.join', 'os.path.join', (['test_voi_dir', '"""adc"""'], {}), "(test_voi_dir, 'adc')\n", (7044, 7065), False, 'import os\n'), ((7080, 7112), 'os.path.join', 'os.path.join', (['test_voi_dir', '"""t1"""'], {}), "(test_voi_dir, 't1')\n", (7092, 7112), False, 'import os\n'), ((8474, 8513), 'phantom_analysis.dicom_util.read_dicomdir', 'dicom_util.read_dicomdir', (['test_case_dir'], {}), '(test_case_dir)\n', (8498, 8513), False, 'from phantom_analysis import dicom_util, scalar_analysis, voi_analysis, phantom_definitions\n'), ((9502, 9531), 'yaml.safe_load', 'yaml.safe_load', (['expected_file'], {}), '(expected_file)\n', (9516, 9531), False, 'import yaml\n'), ((10012, 10034), 'logging.warn', 'logging.warn', (['"""\tFAIL"""'], {}), "('\\tFAIL')\n", (10024, 10034), False, 'import logging\n'), ((10594, 10616), 'logging.info', 'logging.info', (['"""\tPASS"""'], {}), "('\\tPASS')\n", (10606, 10616), False, 'import logging\n'), ((13134, 13176), 'os.path.join', 'os.path.join', (['test_voi_dir', '"""summary.yaml"""'], {}), "(test_voi_dir, 'summary.yaml')\n", (13146, 13176), False, 'import os\n'), ((13683, 13702), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (13700, 13702), False, 'import logging\n'), ((3869, 3888), 'numpy.abs', 'np.abs', (['median_diff'], {}), '(median_diff)\n', (3875, 3888), True, 'import numpy as np\n'), ((3933, 3950), 'numpy.abs', 'np.abs', (['mean_diff'], {}), '(mean_diff)\n', (3939, 3950), True, 'import numpy as np\n'), ((5247, 5272), 'numpy.mean', 'np.mean', (['center_distances'], {}), '(center_distances)\n', (5254, 5272), True, 'import numpy as np\n'), ((5445, 5472), 'numpy.mean', 'np.mean', (['volume_differences'], {}), '(volume_differences)\n', (5452, 5472), True, 'import numpy as np\n'), ((5739, 5773), 'numpy.mean', 'np.mean', (['scalar_median_differences'], {}), '(scalar_median_differences)\n', (5746, 5773), True, 'import numpy as np\n'), ((5991, 6023), 'numpy.mean', 'np.mean', (['scalar_mean_differences'], {}), '(scalar_mean_differences)\n', (5998, 6023), True, 'import numpy as np\n'), ((8552, 8595), 'logging.warn', 'logging.warn', (['"""Failed to read DICOM files."""'], {}), "('Failed to read DICOM files.')\n", (8564, 8595), False, 'import logging\n'), ((8680, 8745), 'os.environ.get', 'os.environ.get', (['"""PHANTOM_ANALYSIS_SHOW_INTERMEDIATE_RESULTS"""', '"""0"""'], {}), "('PHANTOM_ANALYSIS_SHOW_INTERMEDIATE_RESULTS', '0')\n", (8694, 8745), False, 'import os\n'), ((9662, 9691), 'yaml.safe_load', 'yaml.safe_load', (['baseline_file'], {}), '(baseline_file)\n', (9676, 9691), False, 'import yaml\n'), ((10111, 10146), 'logging.info', 'logging.info', (['"""\tupdating baseline"""'], {}), "('\\tupdating baseline')\n", (10123, 10146), False, 'import logging\n'), ((10468, 10572), 'logging.warn', 'logging.warn', (['("\\tactual results don\'t match baseline: compare %s %s" % (baseline_path,\n actual_path))'], {}), '("\\tactual results don\'t match baseline: compare %s %s" % (\n baseline_path, actual_path))\n', (10480, 10572), False, 'import logging\n'), ((10231, 10263), 'yaml.dump', 'yaml.dump', (['actual', 'baseline_file'], {}), '(actual, baseline_file)\n', (10240, 10263), False, 'import yaml\n'), ((10421, 10451), 'yaml.dump', 'yaml.dump', (['actual', 'actual_file'], {}), '(actual, actual_file)\n', (10430, 10451), False, 'import yaml\n'), ((13805, 13824), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (13822, 13824), False, 'import logging\n'), ((3053, 3188), 'numpy.array', 'np.array', (["[expected_voi_dict['center_left_cm'], expected_voi_dict[\n 'center_posterior_cm'], expected_voi_dict['center_superior_cm']]"], {}), "([expected_voi_dict['center_left_cm'], expected_voi_dict[\n 'center_posterior_cm'], expected_voi_dict['center_superior_cm']])\n", (3061, 3188), True, 'import numpy as np\n')] |
from util import extract_features, rgb, slide_window, draw_boxes, make_heatmap, get_hog_features, color_hist, bin_spatial
import cv2
import matplotlib.pyplot as plt
import numpy as np
from scipy.ndimage.measurements import label as label_image
from skimage.filters.rank import windowed_histogram
import time
class Detector(object):
def __init__(self, classifier, feature_parameters, shape, scaler, heat_threshold, alpha=1.0):
self._alpha = alpha
self._last_heatmap = None
self._classifier = classifier
self._feature_parameters = dict(feature_parameters)
self._shape = shape
self._scaler = scaler
self._threshold = heat_threshold
self._cspace = self._feature_parameters['cspace']
del self._feature_parameters['cspace']
def __call__(self, img, show_plots=False):
hits = self.get_hits(img)
heat = make_heatmap(img.shape[0:2], hits)
if self._last_heatmap is None:
self._last_heatmap = heat
filtered_heat = (1-self._alpha) * self._last_heatmap + self._alpha * heat
self._last_heatmap = filtered_heat
binary = filtered_heat >= self._threshold
labels = label_image(binary)
boxes = []
for i in range(labels[1]):
y_points, x_points = np.where(labels[0] == i+1)
box = ((np.min(x_points), np.min(y_points)),
(np.max(x_points), np.max(y_points)))
width = box[1][0] - box[0][0]
height = box[1][1] - box[0][1]
if width >= 32 and height >= 32:
boxes.append(box)
if show_plots:
f, ((a0, a1), (a2, a3)) = plt.subplots(2, 2)
a0.set_title('Raw Hits')
a0.imshow(draw_boxes(rgb(img, self._cspace), hits))
a1.set_title('Heatmap')
a1.imshow(heat.astype(np.float32)/np.max(heat), cmap='gray')
a2.set_title('Thresholded Heatmap')
a2.imshow(binary, cmap='gray')
a3.set_title('Label Image')
a3.imshow(labels[0], cmap='gray')
return boxes
def get_hits(self, img, print_debug=False):
pix_per_cell = self._feature_parameters['hog_pix_per_cell']
x_cells_per_window = self._shape[1] // pix_per_cell - 1
y_cells_per_window = self._shape[0] // pix_per_cell - 1
scales = [
(2.0, 0.0, [ 1/4, 3/4], [.55, .64]),
(64/48, 0.5, [0, 1], [.5, .75]),
(1.0, 0.5, [1/3, 2/3], [.55, .9]),
(4/7, 0.75, [0, 1], [.5, .875]),
(0.5, 0.75, [0, 1], [.5, .875])
]
hits = []
if self._feature_parameters['spatial_size']:
spatial_scale_x = self._feature_parameters['spatial_size'][0] / self._shape[0]
spatial_scale_y = self._feature_parameters['spatial_size'][1] / self._shape[1]
for scale, overlap, x_range, y_range in scales:
start_time = time.clock()
start_hits = len(hits)
# Calculate ROI to avoid processing more than we have to
roi_x = (int(x_range[0] * img.shape[1]), int(x_range[1] * img.shape[1]))
roi_y = (int(y_range[0] * img.shape[0]), int(y_range[1] * img.shape[0]))
roi = img[roi_y[0]:roi_y[1], roi_x[0]:roi_x[1], :]
# Scale the ROI
scaled_shape = (int(roi.shape[1] * scale), int(roi.shape[0] * scale))
scaled_roi = cv2.resize(roi, scaled_shape)
# Calculate HOG features for whole scaled ROI at once
if self._feature_parameters['hog_channel'] == 'ALL':
hog = [get_hog_features(scaled_roi[:,:,c],
orient = self._feature_parameters['hog_orient'],
pix_per_cell = self._feature_parameters['hog_pix_per_cell'],
cell_per_block = self._feature_parameters['hog_cell_per_block'],
feature_vec=False) for c in range(scaled_roi.shape[-1])]
else:
c = self._feature_parameters['hog_channel']
hog = [get_hog_features(scaled_roi[:,:,c],
orient = self._feature_parameters['hog_orient'],
pix_per_cell = self._feature_parameters['hog_pix_per_cell'],
cell_per_block = self._feature_parameters['hog_cell_per_block'],
feature_vec=False)]
hog_shape = hog[0].shape
# Calculate color features for whole scaled ROI at once
hist_bins = self._feature_parameters['hist_bins']
if hist_bins > 0:
histo = [windowed_histogram((scaled_roi[:,:,c]*255/256*hist_bins).astype(np.uint8),
selem=np.ones(self._shape),
shift_x = -self._shape[1]/2,
shift_y = -self._shape[0]/2,
n_bins=self._feature_parameters['hist_bins']) for c in range(scaled_roi.shape[-1])]
# Rescale whole ROI for spatial features
if self._feature_parameters['spatial_size']:
spatial_shape = (int(scaled_shape[0] * spatial_scale_y),
int(scaled_shape[1] * spatial_scale_x))
spatial = cv2.resize(scaled_roi, spatial_shape)
# Calculate bounds for iterating over the HOG feature image
x_start = 0
x_stop = hog_shape[1] - x_cells_per_window + 1
x_step = int((1 - overlap) * x_cells_per_window)
y_start = 0
y_stop = hog_shape[0] - y_cells_per_window + 1
y_step = int((1 - overlap) * y_cells_per_window)
for x in range(x_start, x_stop, x_step):
for y in range(y_start, y_stop, y_step):
# Extract color features
if self._feature_parameters['hist_bins'] > 0:
color_features = np.ravel([h[(y * pix_per_cell), (x * pix_per_cell), :].ravel() for h in histo])
else:
color_features = []
# Extract spatial features
if self._feature_parameters['spatial_size']:
spatial_start_x = int(x*pix_per_cell * spatial_scale_x)
spatial_end_x = spatial_start_x + self._feature_parameters['spatial_size'][0]
spatial_start_y = int(y*pix_per_cell * spatial_scale_y)
spatial_end_y = spatial_start_y + self._feature_parameters['spatial_size'][1]
spatial_patch = spatial[spatial_start_y:spatial_end_y, spatial_start_x:spatial_end_x,:]
spatial_features = np.ravel(spatial_patch)
else:
spatial_features = []
# Extract hog features
hog_features = np.ravel([h[y:y+y_cells_per_window, x:x+x_cells_per_window].ravel() for h in hog])
# Create window (in unscaled image dimensions)
window_start = (roi_x[0] + int(x/scale * pix_per_cell), roi_y[0] + int(y/scale * pix_per_cell))
window_end = (int(window_start[0] + self._shape[1]/scale), int(window_start[1] + self._shape[0]/scale))
# Vectorize features
features = np.concatenate((spatial_features, color_features, hog_features))
features = features.reshape(1, -1)
features = self._scaler.transform(features)
# Check if the window is a vehicle
carness = self._classifier.decision_function(features)
if carness > 0.3:
hits.append((window_start, window_end, scale**2))
end_time = time.clock()
if print_debug:
print("Scale {:.2f} found {} hits in {} seconds".format(scale, len(hits) - start_hits, end_time - start_time))
return hits
| [
"util.make_heatmap",
"numpy.concatenate",
"numpy.ravel",
"scipy.ndimage.measurements.label",
"numpy.ones",
"time.clock",
"numpy.min",
"numpy.where",
"numpy.max",
"util.get_hog_features",
"util.rgb",
"matplotlib.pyplot.subplots",
"cv2.resize"
] | [((892, 926), 'util.make_heatmap', 'make_heatmap', (['img.shape[0:2]', 'hits'], {}), '(img.shape[0:2], hits)\n', (904, 926), False, 'from util import extract_features, rgb, slide_window, draw_boxes, make_heatmap, get_hog_features, color_hist, bin_spatial\n'), ((1196, 1215), 'scipy.ndimage.measurements.label', 'label_image', (['binary'], {}), '(binary)\n', (1207, 1215), True, 'from scipy.ndimage.measurements import label as label_image\n'), ((1303, 1331), 'numpy.where', 'np.where', (['(labels[0] == i + 1)'], {}), '(labels[0] == i + 1)\n', (1311, 1331), True, 'import numpy as np\n'), ((1669, 1687), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(2)'], {}), '(2, 2)\n', (1681, 1687), True, 'import matplotlib.pyplot as plt\n'), ((2959, 2971), 'time.clock', 'time.clock', ([], {}), '()\n', (2969, 2971), False, 'import time\n'), ((3444, 3473), 'cv2.resize', 'cv2.resize', (['roi', 'scaled_shape'], {}), '(roi, scaled_shape)\n', (3454, 3473), False, 'import cv2\n'), ((7859, 7871), 'time.clock', 'time.clock', ([], {}), '()\n', (7869, 7871), False, 'import time\n'), ((5329, 5366), 'cv2.resize', 'cv2.resize', (['scaled_roi', 'spatial_shape'], {}), '(scaled_roi, spatial_shape)\n', (5339, 5366), False, 'import cv2\n'), ((1350, 1366), 'numpy.min', 'np.min', (['x_points'], {}), '(x_points)\n', (1356, 1366), True, 'import numpy as np\n'), ((1368, 1384), 'numpy.min', 'np.min', (['y_points'], {}), '(y_points)\n', (1374, 1384), True, 'import numpy as np\n'), ((1407, 1423), 'numpy.max', 'np.max', (['x_points'], {}), '(x_points)\n', (1413, 1423), True, 'import numpy as np\n'), ((1425, 1441), 'numpy.max', 'np.max', (['y_points'], {}), '(y_points)\n', (1431, 1441), True, 'import numpy as np\n'), ((1758, 1780), 'util.rgb', 'rgb', (['img', 'self._cspace'], {}), '(img, self._cspace)\n', (1761, 1780), False, 'from util import extract_features, rgb, slide_window, draw_boxes, make_heatmap, get_hog_features, color_hist, bin_spatial\n'), ((1871, 1883), 'numpy.max', 'np.max', (['heat'], {}), '(heat)\n', (1877, 1883), True, 'import numpy as np\n'), ((3628, 3867), 'util.get_hog_features', 'get_hog_features', (['scaled_roi[:, :, c]'], {'orient': "self._feature_parameters['hog_orient']", 'pix_per_cell': "self._feature_parameters['hog_pix_per_cell']", 'cell_per_block': "self._feature_parameters['hog_cell_per_block']", 'feature_vec': '(False)'}), "(scaled_roi[:, :, c], orient=self._feature_parameters[\n 'hog_orient'], pix_per_cell=self._feature_parameters['hog_pix_per_cell'\n ], cell_per_block=self._feature_parameters['hog_cell_per_block'],\n feature_vec=False)\n", (3644, 3867), False, 'from util import extract_features, rgb, slide_window, draw_boxes, make_heatmap, get_hog_features, color_hist, bin_spatial\n'), ((4125, 4364), 'util.get_hog_features', 'get_hog_features', (['scaled_roi[:, :, c]'], {'orient': "self._feature_parameters['hog_orient']", 'pix_per_cell': "self._feature_parameters['hog_pix_per_cell']", 'cell_per_block': "self._feature_parameters['hog_cell_per_block']", 'feature_vec': '(False)'}), "(scaled_roi[:, :, c], orient=self._feature_parameters[\n 'hog_orient'], pix_per_cell=self._feature_parameters['hog_pix_per_cell'\n ], cell_per_block=self._feature_parameters['hog_cell_per_block'],\n feature_vec=False)\n", (4141, 4364), False, 'from util import extract_features, rgb, slide_window, draw_boxes, make_heatmap, get_hog_features, color_hist, bin_spatial\n'), ((7409, 7473), 'numpy.concatenate', 'np.concatenate', (['(spatial_features, color_features, hog_features)'], {}), '((spatial_features, color_features, hog_features))\n', (7423, 7473), True, 'import numpy as np\n'), ((6771, 6794), 'numpy.ravel', 'np.ravel', (['spatial_patch'], {}), '(spatial_patch)\n', (6779, 6794), True, 'import numpy as np\n'), ((4811, 4831), 'numpy.ones', 'np.ones', (['self._shape'], {}), '(self._shape)\n', (4818, 4831), True, 'import numpy as np\n')] |
"""
Define the Chow_liu Tree class
"""
#
from __future__ import print_function
import sys
import os
import glob
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import depth_first_order
from scipy.sparse.csgraph import minimum_spanning_tree
import numpy as np
from Util import *
'''
Class Chow-Liu Tree.
Members:
nvariables: Number of variables
xycounts:
Sufficient statistics: counts of value assignments to all pairs of variables
Four dimensional array: first two dimensions are variable indexes
last two dimensions are value indexes 00,01,10,11
xcounts:
Sufficient statistics: counts of value assignments to each variable
First dimension is variable, second dimension is value index [0][1]
xyprob:
xycounts converted to probabilities by normalizing them
xprob:
xcounts converted to probabilities by normalizing them
topo_order:
Topological ordering over the variables
parents:
Parent of each node. Parent[i] gives index of parent of variable indexed by i
If Parent[i]=-9999 then i is the root node
'''
class CLT:
def __init__(self):
self.nvariables = 0
self.xycounts = np.ones((1, 1, 2, 2), dtype=int)
self.xcounts = np.ones((1, 2), dtype=int)
self.xyprob = np.zeros((1, 1, 2, 2))
self.xprob = np.zeros((1, 2))
self.topo_order = []
self.parents = []
self.rng = np.random.default_rng()
'''
Learn the structure of the Chow-Liu Tree using the given dataset
'''
def learn(self, dataset, r = 0):
self.nvariables = dataset.shape[1]
self.xycounts = Util.compute_xycounts(dataset) + 1 # laplace correction
self.xcounts = Util.compute_xcounts(dataset) + 2 # laplace correction
self.xyprob = Util.normalize2d(self.xycounts)
self.xprob = Util.normalize1d(self.xcounts)
# compute mutual information score for all pairs of variables
# weights are multiplied by -1.0 because we compute the minimum spanning tree
edgemat = Util.compute_MI_prob(self.xyprob, self.xprob) * (-1.0)
# randomly setting r mutual info to 0
if r > 0:
x_coor, y_coor = self.generate_random_coordinates(
low=0, high=dataset.shape[1], count=r
)
edgemat[x_coor, y_coor] = 0.
edgemat[y_coor, x_coor] = 0.
edgemat[
edgemat == 0.0] = 1e-20 # to avoid the case where the tree is not connected
# compute the minimum spanning tree
Tree = minimum_spanning_tree(csr_matrix(edgemat))
# Convert the spanning tree to a Bayesian network
self.topo_order, self.parents = depth_first_order(Tree, 0,
directed=False)
'''
Update the Chow-Liu Tree using weighted samples.
Note that we assume that weight of each sample >0.
Important function for performing updates when running EM
'''
def update(self, dataset, weights):
# Update the Chow-Liu Tree based on a weighted dataset
# assume that dataset_.shape[0] equals weights.shape[0] because we assume each example has a weight
if not np.all(weights):
print('Error: Weight of an example in the dataset is zero')
sys.exit(-1)
if weights.shape[0] == dataset.shape[0]:
# Weighted laplace correction, note that num-examples=dataset.shape[0]
# If 1-laplace smoothing is applied to num-examples,
# then laplace smoothing applied to "sum-weights" equals "sum-weights/num-examples"
smooth = np.sum(weights) / dataset.shape[0]
self.xycounts = Util.compute_weighted_xycounts(dataset,
weights) + smooth
self.xcounts = Util.compute_weighted_xcounts(dataset,
weights) + 2.0 * smooth
else:
print('Error: Each example must have a weight')
sys.exit(-1)
self.xyprob = Util.normalize2d(self.xycounts)
self.xprob = Util.normalize1d(self.xcounts)
edgemat = Util.compute_MI_prob(self.xycounts, self.xcounts) * (-1.0)
Tree = minimum_spanning_tree(csr_matrix(edgemat))
self.topo_order, self.parents = depth_first_order(Tree, 0,
directed=False)
return self
'''
Compute the Log-likelihood score of the dataset
'''
def computeLL(self, dataset):
ll = 0.0
for i in range(dataset.shape[0]):
for x in self.topo_order:
assignx = dataset[i, x]
# if root sample from marginal
if self.parents[x] == -9999:
ll += np.log(self.xprob[x][assignx])
else:
# sample from p(x|y)
y = self.parents[x]
assigny = dataset[i, y]
ll += np.log(
self.xyprob[x, y, assignx, assigny] / self.xprob[
y, assigny])
return ll
def getProb(self, sample):
prob = 1.0
for x in self.topo_order:
assignx = sample[x]
# if root sample from marginal
if self.parents[x] == -9999:
prob *= self.xprob[x][assignx]
else:
# sample from p(x|y)
y = self.parents[x]
assigny = sample[y]
prob *= self.xyprob[x, y, assignx, assigny] / self.xprob[
y, assigny]
return prob
def generate_random_coordinates(self, low, high, count):
x_coor = self.rng.choice(range(low, high), size=count, replace=True)
y_coor = self.rng.choice(range(low, high), size=count, replace=True)
return x_coor, y_coor
if __name__ == "__main__":
# To learn Chow-Liu trees, you can use
folder_path = sys.argv[1]
data_path_pattern = os.path.join(folder_path, "*.ts.data")
for data_path in glob.glob(data_path_pattern):
print("WORKING ON DATAFILE: ", data_path)
# You can read the dataset using
dataset = Util.load_dataset(data_path)
# To learn Chow-Liu trees, you can use
clt = CLT()
clt.learn(dataset, r=5)
# To compute average log likelihood of a dataset, you can use
ll = clt.computeLL(dataset) / dataset.shape[0]
print("Average log likelihood on train data:", ll)
test_dataset = Util.load_dataset(
data_path.replace(".ts.data", ".test.data"))
test_ll = clt.computeLL(test_dataset) / test_dataset.shape[0]
print("Average log likelihood on test data: ", test_ll) | [
"numpy.sum",
"numpy.log",
"numpy.zeros",
"numpy.ones",
"numpy.all",
"numpy.random.default_rng",
"scipy.sparse.csr_matrix",
"glob.glob",
"sys.exit",
"os.path.join",
"scipy.sparse.csgraph.depth_first_order"
] | [((6104, 6142), 'os.path.join', 'os.path.join', (['folder_path', '"""*.ts.data"""'], {}), "(folder_path, '*.ts.data')\n", (6116, 6142), False, 'import os\n'), ((6164, 6192), 'glob.glob', 'glob.glob', (['data_path_pattern'], {}), '(data_path_pattern)\n', (6173, 6192), False, 'import glob\n'), ((1222, 1254), 'numpy.ones', 'np.ones', (['(1, 1, 2, 2)'], {'dtype': 'int'}), '((1, 1, 2, 2), dtype=int)\n', (1229, 1254), True, 'import numpy as np\n'), ((1278, 1304), 'numpy.ones', 'np.ones', (['(1, 2)'], {'dtype': 'int'}), '((1, 2), dtype=int)\n', (1285, 1304), True, 'import numpy as np\n'), ((1327, 1349), 'numpy.zeros', 'np.zeros', (['(1, 1, 2, 2)'], {}), '((1, 1, 2, 2))\n', (1335, 1349), True, 'import numpy as np\n'), ((1371, 1387), 'numpy.zeros', 'np.zeros', (['(1, 2)'], {}), '((1, 2))\n', (1379, 1387), True, 'import numpy as np\n'), ((1462, 1485), 'numpy.random.default_rng', 'np.random.default_rng', ([], {}), '()\n', (1483, 1485), True, 'import numpy as np\n'), ((2738, 2780), 'scipy.sparse.csgraph.depth_first_order', 'depth_first_order', (['Tree', '(0)'], {'directed': '(False)'}), '(Tree, 0, directed=False)\n', (2755, 2780), False, 'from scipy.sparse.csgraph import depth_first_order\n'), ((4401, 4443), 'scipy.sparse.csgraph.depth_first_order', 'depth_first_order', (['Tree', '(0)'], {'directed': '(False)'}), '(Tree, 0, directed=False)\n', (4418, 4443), False, 'from scipy.sparse.csgraph import depth_first_order\n'), ((2619, 2638), 'scipy.sparse.csr_matrix', 'csr_matrix', (['edgemat'], {}), '(edgemat)\n', (2629, 2638), False, 'from scipy.sparse import csr_matrix\n'), ((3266, 3281), 'numpy.all', 'np.all', (['weights'], {}), '(weights)\n', (3272, 3281), True, 'import numpy as np\n'), ((3367, 3379), 'sys.exit', 'sys.exit', (['(-1)'], {}), '(-1)\n', (3375, 3379), False, 'import sys\n'), ((4107, 4119), 'sys.exit', 'sys.exit', (['(-1)'], {}), '(-1)\n', (4115, 4119), False, 'import sys\n'), ((4340, 4359), 'scipy.sparse.csr_matrix', 'csr_matrix', (['edgemat'], {}), '(edgemat)\n', (4350, 4359), False, 'from scipy.sparse import csr_matrix\n'), ((3694, 3709), 'numpy.sum', 'np.sum', (['weights'], {}), '(weights)\n', (3700, 3709), True, 'import numpy as np\n'), ((4886, 4916), 'numpy.log', 'np.log', (['self.xprob[x][assignx]'], {}), '(self.xprob[x][assignx])\n', (4892, 4916), True, 'import numpy as np\n'), ((5090, 5158), 'numpy.log', 'np.log', (['(self.xyprob[x, y, assignx, assigny] / self.xprob[y, assigny])'], {}), '(self.xyprob[x, y, assignx, assigny] / self.xprob[y, assigny])\n', (5096, 5158), True, 'import numpy as np\n')] |
import numpy
from numpy.testing import assert_raises
from fuel.datasets import CalTech101Silhouettes
from tests import skip_if_not_available
def test_caltech101_silhouettes16():
skip_if_not_available(datasets=['caltech101_silhouettes16.hdf5'])
for which_set, size, num_examples in (
('train', 16, 4082), ('valid', 16, 2257), ('test', 16, 2302)):
ds = CalTech101Silhouettes(which_sets=[which_set], size=size,
load_in_memory=False)
assert ds.num_examples == num_examples
handle = ds.open()
features, targets = ds.get_data(handle, slice(0, 10))
assert features.shape == (10, 1, size, size)
assert targets.shape == (10, 1)
assert features.dtype == numpy.uint8
assert targets.dtype == numpy.uint8
def test_caltech101_silhouettes_unkn_size():
assert_raises(ValueError, CalTech101Silhouettes,
which_sets=['test'], size=10)
def test_caltech101_silhouettes28():
skip_if_not_available(datasets=['caltech101_silhouettes28.hdf5'])
for which_set, size, num_examples in (
('train', 28, 4100), ('valid', 28, 2264), ('test', 28, 2307)):
ds = CalTech101Silhouettes(which_sets=[which_set], size=size,
load_in_memory=False)
assert ds.num_examples == num_examples
handle = ds.open()
features, targets = ds.get_data(handle, slice(0, 10))
assert features.shape == (10, 1, size, size)
assert targets.shape == (10, 1)
assert features.dtype == numpy.uint8
assert targets.dtype == numpy.uint8
| [
"numpy.testing.assert_raises",
"tests.skip_if_not_available",
"fuel.datasets.CalTech101Silhouettes"
] | [((185, 250), 'tests.skip_if_not_available', 'skip_if_not_available', ([], {'datasets': "['caltech101_silhouettes16.hdf5']"}), "(datasets=['caltech101_silhouettes16.hdf5'])\n", (206, 250), False, 'from tests import skip_if_not_available\n'), ((869, 947), 'numpy.testing.assert_raises', 'assert_raises', (['ValueError', 'CalTech101Silhouettes'], {'which_sets': "['test']", 'size': '(10)'}), "(ValueError, CalTech101Silhouettes, which_sets=['test'], size=10)\n", (882, 947), False, 'from numpy.testing import assert_raises\n'), ((1009, 1074), 'tests.skip_if_not_available', 'skip_if_not_available', ([], {'datasets': "['caltech101_silhouettes28.hdf5']"}), "(datasets=['caltech101_silhouettes28.hdf5'])\n", (1030, 1074), False, 'from tests import skip_if_not_available\n'), ((382, 460), 'fuel.datasets.CalTech101Silhouettes', 'CalTech101Silhouettes', ([], {'which_sets': '[which_set]', 'size': 'size', 'load_in_memory': '(False)'}), '(which_sets=[which_set], size=size, load_in_memory=False)\n', (403, 460), False, 'from fuel.datasets import CalTech101Silhouettes\n'), ((1206, 1284), 'fuel.datasets.CalTech101Silhouettes', 'CalTech101Silhouettes', ([], {'which_sets': '[which_set]', 'size': 'size', 'load_in_memory': '(False)'}), '(which_sets=[which_set], size=size, load_in_memory=False)\n', (1227, 1284), False, 'from fuel.datasets import CalTech101Silhouettes\n')] |
import math
import numpy as np
from random import randint, seed
class Agent:
"""
The Agent class represents the agent in the Predator-Prey task.
...
Attributes
----------
loc : [float]
Location of the agent [x, y]
feasted : bool
Says whether the agent has caught the prey or not
alive : bool
Says whether the agent is still alive (i.e. has not been caught)
loc_trace : [[float]]
Keeps track of all the locations the agent was in
attn_trace : [[float]]
Keeps track of all the attention allocations
dist_trace : [[float]]
Keeps track of all distances at each time step
perceived_agent_trace : [[float]]
Keeps track of the perceived agent locations
perceived_prey_trace : [[float]]
Keeps track of the perceived prey locations
perceived_predator_trace : [[float]]
Keeps track of the perceived predator locations
w : int
Width of the coordinate plane
h : int
Height of the coordinate plane
Methods
-------
perceive(target, attention)
Get the perceived location of the target given an attention level.
move(agent_perceived, prey_perceived, predator_perceived, prey_real, predator_real, speed, bias)
Move the agent using the perceived locations, speed of movement, and pursuit bias.
bounce_back()
If the agent's location is outside the coordinate plane, bounce back into it.
track_attn(attention)
Add the given set of attention levels to the attention trace.
track_dist(attention)
Add the given set of attention levels to the attention trace.
"""
def __init__(self, w, h):
"""
Parameters
----------
w : int
Width of the coordinate plane
h : int
Height of the coordinate plane
"""
seed(1)
self.loc = [randint(int(w/3), int(2*w/3)), randint(0, h)]
self.feasted = False
self.alive = True
self.loc_trace = [list(self.loc)]
self.attn_trace = []
self.dist_trace = []
self.perceived_agent_trace = []
self.perceived_prey_trace = []
self.perceived_predator_trace = []
self.w = w
self.h = h
return
def perceive(self, target, attention):
"""Get the target's location given the attention level
Parameters
----------
target : Agent, Prey, or Predator
The target of attention
attention : float
The attention level
Returns
-------
[float]
The perceived location
Raises
------
ValueError
If given arguments are invalid.
"""
if target is None or attention < 0:
raise ValueError("invalid perceived arguments")
blur = 100 - attention
x = target.loc[0] + blur
y = target.loc[1] + blur
return [x, y]
def move(self, agent_perceived, prey_perceived, predator_perceived,
prey_real, predator_real, speed, bias):
"""Move the agent using the perceived locations, speed of movement, and pursuit bias
Parameters
----------
agent_perceived : [float]
The agent's perceived location [x, y]
prey_perceived : [float]
The prey's perceived location [x, y]
predator_perceived : [float]
The predator's perceived location [x, y]
prey_real : [float]
The prey's real location [x, y]
predator_real : [float]
The predator's real location [x, y]
speed : float
The speed of movement
bias : float
The bias on pursuing over avoiding
Returns
-------
void
Raises
------
ValueError
If given arguments are invalid.
"""
if agent_perceived is None or prey_perceived is None or predator_perceived is None or prey_real is None or predator_real is None:
raise ValueError("locations must all be valid")
if speed <= 0:
raise ValueError("speed must be positive number")
if bias < 0 or bias > 1:
raise ValueError("bias must be a number between 0 and 1")
# Track perceived locations
self.perceived_agent_trace.append(list(agent_perceived))
self.perceived_prey_trace.append(list(prey_perceived))
self.perceived_predator_trace.append(list(predator_perceived))
# If the distance between prey and predator is less than 10 it counts as a contact
buffer = 10
# Vector for the agent's real location
agent_real_v = np.array(self.loc)
# Vector for the agent's perceived location
agent_perceived_v = np.array(agent_perceived)
# Vector for the prey's real location
prey_real_v = np.array(prey_real)
# Vector for the prey's perceived location
prey_perceived_v = np.array(prey_perceived)
# Vector for the predator's real location
pred_real_v = np.array(predator_real)
# Vector for the predator's perceived location
pred_perceived_v = np.array(predator_perceived)
# Real distance between the agent and the predator
real_dist2pred = np.linalg.norm(pred_real_v - agent_real_v)
# If the agent has been caught, set alive to False
if real_dist2pred < buffer:
self.alive = False
# Reflect the predator's location along the agent's coordinates
new_pred_perceived_v = agent_perceived_v - (pred_perceived_v - agent_perceived_v)
# Get point in between predator's and prey's (superposition of pursuit and avoidance)
super_v = new_pred_perceived_v + bias * (prey_perceived_v - new_pred_perceived_v)
# Vector for the direction of movement
move_v = super_v - agent_perceived_v
# Move agent alongside the superposition vector at a given speed
d = speed / np.linalg.norm(move_v)
if d > 1:
d = 1
new_loc = np.floor((agent_real_v + d * move_v))
# Update agent's location
self.loc = new_loc
# Real distance between the prey and the agent
real_dist2prey = np.linalg.norm(prey_real_v - np.array(self.loc))
# If the agent has reached its prey, set feasted to True
if real_dist2prey < buffer:
self.feasted = True
# If the new location is out of range, bounce back
self.bounce_back()
# Update location trace
self.loc_trace.append(list(self.loc))
# Keep track of distances
self.track_dist([math.dist(prey_real, self.loc), math.dist(predator_real, self.loc)])
def move_quantum(self, agent_perceived, prey_perceived, predator_perceived,
prey_real, predator_real, speed, target):
"""Move the agent using the perceived locations, speed of movement, and the target
direction. Used in the quantum model.
Parameters
----------
agent_perceived : [float]
The agent's perceived location [x, y]
prey_perceived : [float]
The prey's perceived location [x, y]
predator_perceived : [float]
The predator's perceived location [x, y]
prey_real : [float]
The prey's real location [x, y]
predator_real : [float]
The predator's real location [x, y]
speed : float
The speed of movement
target : [float]
The target position that guides the direction of movement
Returns
-------
void
Raises
------
ValueError
If given arguments are invalid.
"""
if agent_perceived is None or prey_perceived is None or predator_perceived is None or prey_real is None or predator_real is None or target is None:
raise ValueError("locations must all be valid")
if speed <= 0:
raise ValueError("speed must be positive number")
# Track perceived locations
self.perceived_agent_trace.append(list(agent_perceived))
self.perceived_prey_trace.append(list(prey_perceived))
self.perceived_predator_trace.append(list(predator_perceived))
# If the distance between prey and predator is less than 10 it counts as a contact
buffer = 10
# Vector for the agent's real location
agent_real_v = np.array(self.loc)
# Vector for the agent's perceived location
agent_perceived_v = np.array(agent_perceived)
# Vector for the prey's real location
prey_real_v = np.array(prey_real)
# Vector for the predator's real location
pred_real_v = np.array(predator_real)
# Vector for the movement's target location
target_v = np.array(target)
# Real distance between the agent and the predator
real_dist2pred = np.linalg.norm(pred_real_v - agent_real_v)
# If the agent has been caught, set alive to False
if real_dist2pred < buffer:
self.alive = False
# Vector for the direction of movement
move_v = target_v - agent_perceived_v
# Move agent alongside movement vector at a given speed
d = speed / np.linalg.norm(move_v)
if d > 1:
d = 1
new_loc = np.floor((agent_real_v + d * move_v))
# Update agent's location
self.loc = new_loc
# Real distance between the prey and the agent
real_dist2prey = np.linalg.norm(prey_real_v - np.array(self.loc))
# If the agent has reached its prey, set feasted to True
if real_dist2prey < buffer:
self.feasted = True
# If the new location is out of range, bounce back
self.bounce_back()
# Update location trace
self.loc_trace.append(list(self.loc))
# Keep track of distances
self.track_dist([math.dist(prey_real, self.loc), math.dist(predator_real, self.loc)])
def bounce_back(self):
"""If the location is out of range, bounces it back into range
Parameters
----------
void
Returns
-------
void
"""
# Fix x-coordinate, if needed
if self.loc[0] < 0:
self.loc[0] = 1
elif self.loc[0] > self.w:
self.loc[0] = self.w - 1
# Fix y-coordinate, if needed
if self.loc[1] < 0:
self.loc[1] = 1
elif self.loc[1] > self.h:
self.loc[1] = self.h - 1
def track_attn(self, attention):
"""Add attentions to the attention_trace
Parameters
----------
attention : [float]
Set of attention levels to be be added to the attention trace
Returns
-------
void
"""
self.attn_trace.append(attention)
def track_dist(self, dist):
""" Add distances to the dist_trace
Parameters
----------
dist : [float]
Set of distances to be be added to the distance trace
Returns
-------
void
"""
self.dist_trace.append(dist)
def __repr__(self):
"""Displays information about the agent
"""
display = ['\n===============================']
display.append('A G E N T')
display.append('Alive: ' + str(self.alive))
display.append('Feasted: ' + str(self.feasted))
display.append('Steps taken: ' + str(len(self.loc_trace)))
display.append('Location trace:')
loc_trace_str = ""
for loc in self.loc_trace:
loc[0] = "{:.2f}".format(loc[0])
loc[1] = "{:.2f}".format(loc[1])
loc_trace_str += ", " + str(loc)
display.append(loc_trace_str)
display.append('Agent perceived location trace:')
agent_str = ""
for loc in self.perceived_agent_trace:
loc[0] = "{:.2f}".format(loc[0])
loc[1] = "{:.2f}".format(loc[1])
agent_str += ", " + str(loc)
display.append(agent_str)
display.append('Prey perceived location trace:')
prey_str = ""
for loc in self.perceived_prey_trace:
loc[0] = "{:.2f}".format(loc[0])
loc[1] = "{:.2f}".format(loc[1])
prey_str += ", " + str(loc)
display.append(prey_str)
display.append('Predator perceived location trace:')
predator_str = ""
for loc in self.perceived_predator_trace:
loc[0] = "{:.2f}".format(loc[0])
loc[1] = "{:.2f}".format(loc[1])
predator_str += ", " + str(loc)
display.append(predator_str)
display.append('Attention trace (agent, prey, predator):')
attn_trace_str = ""
for attn in self.attn_trace:
attn[0] = "{:.2f}".format(attn[0])
attn[1] = "{:.2f}".format(attn[1])
attn[2] = "{:.2f}".format(attn[2])
attn_trace_str += ", " + str(attn)
display.append(attn_trace_str)
display.append('Distances trace (dist to prey, dist to predator):')
dist_trace_str = ""
for dist in self.dist_trace:
dist[0] = "{:.2f}".format(dist[0])
dist[1] = "{:.2f}".format(dist[1])
dist_trace_str += ", " + str(dist)
display.append(dist_trace_str)
display.append('===============================\n')
return "\n".join(display)
| [
"math.dist",
"random.randint",
"numpy.floor",
"numpy.array",
"numpy.linalg.norm",
"random.seed"
] | [((1886, 1893), 'random.seed', 'seed', (['(1)'], {}), '(1)\n', (1890, 1893), False, 'from random import randint, seed\n'), ((4749, 4767), 'numpy.array', 'np.array', (['self.loc'], {}), '(self.loc)\n', (4757, 4767), True, 'import numpy as np\n'), ((4848, 4873), 'numpy.array', 'np.array', (['agent_perceived'], {}), '(agent_perceived)\n', (4856, 4873), True, 'import numpy as np\n'), ((4942, 4961), 'numpy.array', 'np.array', (['prey_real'], {}), '(prey_real)\n', (4950, 4961), True, 'import numpy as np\n'), ((5040, 5064), 'numpy.array', 'np.array', (['prey_perceived'], {}), '(prey_perceived)\n', (5048, 5064), True, 'import numpy as np\n'), ((5137, 5160), 'numpy.array', 'np.array', (['predator_real'], {}), '(predator_real)\n', (5145, 5160), True, 'import numpy as np\n'), ((5243, 5271), 'numpy.array', 'np.array', (['predator_perceived'], {}), '(predator_perceived)\n', (5251, 5271), True, 'import numpy as np\n'), ((5357, 5399), 'numpy.linalg.norm', 'np.linalg.norm', (['(pred_real_v - agent_real_v)'], {}), '(pred_real_v - agent_real_v)\n', (5371, 5399), True, 'import numpy as np\n'), ((6147, 6182), 'numpy.floor', 'np.floor', (['(agent_real_v + d * move_v)'], {}), '(agent_real_v + d * move_v)\n', (6155, 6182), True, 'import numpy as np\n'), ((8560, 8578), 'numpy.array', 'np.array', (['self.loc'], {}), '(self.loc)\n', (8568, 8578), True, 'import numpy as np\n'), ((8659, 8684), 'numpy.array', 'np.array', (['agent_perceived'], {}), '(agent_perceived)\n', (8667, 8684), True, 'import numpy as np\n'), ((8753, 8772), 'numpy.array', 'np.array', (['prey_real'], {}), '(prey_real)\n', (8761, 8772), True, 'import numpy as np\n'), ((8845, 8868), 'numpy.array', 'np.array', (['predator_real'], {}), '(predator_real)\n', (8853, 8868), True, 'import numpy as np\n'), ((8940, 8956), 'numpy.array', 'np.array', (['target'], {}), '(target)\n', (8948, 8956), True, 'import numpy as np\n'), ((9042, 9084), 'numpy.linalg.norm', 'np.linalg.norm', (['(pred_real_v - agent_real_v)'], {}), '(pred_real_v - agent_real_v)\n', (9056, 9084), True, 'import numpy as np\n'), ((9468, 9503), 'numpy.floor', 'np.floor', (['(agent_real_v + d * move_v)'], {}), '(agent_real_v + d * move_v)\n', (9476, 9503), True, 'import numpy as np\n'), ((1945, 1958), 'random.randint', 'randint', (['(0)', 'h'], {}), '(0, h)\n', (1952, 1958), False, 'from random import randint, seed\n'), ((6070, 6092), 'numpy.linalg.norm', 'np.linalg.norm', (['move_v'], {}), '(move_v)\n', (6084, 6092), True, 'import numpy as np\n'), ((9391, 9413), 'numpy.linalg.norm', 'np.linalg.norm', (['move_v'], {}), '(move_v)\n', (9405, 9413), True, 'import numpy as np\n'), ((6357, 6375), 'numpy.array', 'np.array', (['self.loc'], {}), '(self.loc)\n', (6365, 6375), True, 'import numpy as np\n'), ((6744, 6774), 'math.dist', 'math.dist', (['prey_real', 'self.loc'], {}), '(prey_real, self.loc)\n', (6753, 6774), False, 'import math\n'), ((6776, 6810), 'math.dist', 'math.dist', (['predator_real', 'self.loc'], {}), '(predator_real, self.loc)\n', (6785, 6810), False, 'import math\n'), ((9678, 9696), 'numpy.array', 'np.array', (['self.loc'], {}), '(self.loc)\n', (9686, 9696), True, 'import numpy as np\n'), ((10065, 10095), 'math.dist', 'math.dist', (['prey_real', 'self.loc'], {}), '(prey_real, self.loc)\n', (10074, 10095), False, 'import math\n'), ((10097, 10131), 'math.dist', 'math.dist', (['predator_real', 'self.loc'], {}), '(predator_real, self.loc)\n', (10106, 10131), False, 'import math\n')] |
import lightkurve as lk
from astropy.table import Table
from lightkurve.correctors import download_tess_cbvs
from lightkurve.correctors import CBVCorrector
from lightkurve.correctors import DesignMatrix
import numpy as np
import glob
import matplotlib.pyplot as plt
def correccion_curva_de_luz(archivo):
tpf = lk.read(archivo)
mask = np.array([[False, False, False, False, False, False, False, False, False, False], # última fila
[False, False, False, False, False, False, False, False, False, False],
[False, False, False, False, False, False, False, True, False, False],
[False, False, False, True, True, True, True, True, False, False],
[False, True, True, True, True, True, True, True, False, False],
[False, True, True, True, True, True, True, True, False, False],
[False, False, True, True, True, True, True, True, False, False],
[False, False, True, True, True, True, True, True, False, False],
[False, False, True, True, True, True, True, True, False, False],
[False, False, False, False, True, True, True, False, False, False]]) # Primera fila
#tpf.plot(aperture_mask=mask);
lc = tpf.to_lightcurve(aperture_mask=mask)
lc_clean = lc.remove_outliers(sigma=4)
cbvs = download_tess_cbvs(sector=lc.sector, camera=lc.camera, ccd=lc.ccd, cbv_type='SingleScale')
dm = DesignMatrix(tpf.flux[:, ~mask], name='pixel regressors').pca(5).append_constant()
cbvcorrector = CBVCorrector(lc, interpolate_cbvs=True)
cbvcorrector.correct_gaussian_prior(cbv_type=None, cbv_indices=None, ext_dm=dm, alpha=1e-4)
#cbvcorrector.diagnose()
# Select which CBVs to use in the correction
cbv_type = ['SingleScale', 'Spike']
# Select which CBV indices to use
# Use the first 8 SingleScale and all Spike CBVS
cbv_indices = [np.arange(1,9), 'ALL']
cbvcorrector.correct(cbv_type=cbv_type, cbv_indices=cbv_indices, ext_dm=dm, alpha_bounds=[1e-6, 1e-2], target_over_score=0.8, target_under_score=-1)
#cbvcorrector.diagnose();
correcter_2 = cbvcorrector.corrected_lc
t = Table([correcter_2["time"],correcter_2["flux"],correcter_2["flux_err"]])
t.write(archivo + "_correccion.csv", format='csv', overwrite = True)
#plt.plot(correcter_2["time"].value,correcter_2["flux"])
#plt.show()
archivos = glob.glob('**/*.fits', recursive=True)
for archivo in archivos:
correccion_curva_de_luz(archivo)
print(archivo)
| [
"lightkurve.correctors.download_tess_cbvs",
"astropy.table.Table",
"lightkurve.read",
"lightkurve.correctors.CBVCorrector",
"numpy.array",
"numpy.arange",
"glob.glob",
"lightkurve.correctors.DesignMatrix"
] | [((2543, 2581), 'glob.glob', 'glob.glob', (['"""**/*.fits"""'], {'recursive': '(True)'}), "('**/*.fits', recursive=True)\n", (2552, 2581), False, 'import glob\n'), ((317, 333), 'lightkurve.read', 'lk.read', (['archivo'], {}), '(archivo)\n', (324, 333), True, 'import lightkurve as lk\n'), ((346, 1075), 'numpy.array', 'np.array', (['[[False, False, False, False, False, False, False, False, False, False], [\n False, False, False, False, False, False, False, False, False, False],\n [False, False, False, False, False, False, False, True, False, False],\n [False, False, False, True, True, True, True, True, False, False], [\n False, True, True, True, True, True, True, True, False, False], [False,\n True, True, True, True, True, True, True, False, False], [False, False,\n True, True, True, True, True, True, False, False], [False, False, True,\n True, True, True, True, True, False, False], [False, False, True, True,\n True, True, True, True, False, False], [False, False, False, False, \n True, True, True, False, False, False]]'], {}), '([[False, False, False, False, False, False, False, False, False, \n False], [False, False, False, False, False, False, False, False, False,\n False], [False, False, False, False, False, False, False, True, False, \n False], [False, False, False, True, True, True, True, True, False, \n False], [False, True, True, True, True, True, True, True, False, False],\n [False, True, True, True, True, True, True, True, False, False], [False,\n False, True, True, True, True, True, True, False, False], [False, False,\n True, True, True, True, True, True, False, False], [False, False, True,\n True, True, True, True, True, False, False], [False, False, False, \n False, True, True, True, False, False, False]])\n', (354, 1075), True, 'import numpy as np\n'), ((1457, 1552), 'lightkurve.correctors.download_tess_cbvs', 'download_tess_cbvs', ([], {'sector': 'lc.sector', 'camera': 'lc.camera', 'ccd': 'lc.ccd', 'cbv_type': '"""SingleScale"""'}), "(sector=lc.sector, camera=lc.camera, ccd=lc.ccd, cbv_type\n ='SingleScale')\n", (1475, 1552), False, 'from lightkurve.correctors import download_tess_cbvs\n'), ((1661, 1700), 'lightkurve.correctors.CBVCorrector', 'CBVCorrector', (['lc'], {'interpolate_cbvs': '(True)'}), '(lc, interpolate_cbvs=True)\n', (1673, 1700), False, 'from lightkurve.correctors import CBVCorrector\n'), ((2294, 2368), 'astropy.table.Table', 'Table', (["[correcter_2['time'], correcter_2['flux'], correcter_2['flux_err']]"], {}), "([correcter_2['time'], correcter_2['flux'], correcter_2['flux_err']])\n", (2299, 2368), False, 'from astropy.table import Table\n'), ((2028, 2043), 'numpy.arange', 'np.arange', (['(1)', '(9)'], {}), '(1, 9)\n', (2037, 2043), True, 'import numpy as np\n'), ((1558, 1615), 'lightkurve.correctors.DesignMatrix', 'DesignMatrix', (['tpf.flux[:, ~mask]'], {'name': '"""pixel regressors"""'}), "(tpf.flux[:, ~mask], name='pixel regressors')\n", (1570, 1615), False, 'from lightkurve.correctors import DesignMatrix\n')] |
from sklearn.base import BaseEstimator, ClassifierMixin
import numpy as np
from Node import Node
class CartDecisionTreeClassifier(BaseEstimator, ClassifierMixin):
"""
A decision tree model for classification
It currently only supports continuous features. It supports multi-class labels and assumes the labels appear
in the last column of the data. It consists of a top down hierarchy of nodes.
"""
def __init__(self, max_depth=None, min_samples_leaf=1):
"""
:param max_depth: The maximum depth of the tree
:param min_samples_leaf: The minimum number of samples required to be at a leaf node.
"""
self.max_depth = max_depth
self.min_samples_leaf = min_samples_leaf
self.tree = None
self.number_of_features = None
def fit(self, X, y):
"""
Build a decision tree from the training set
:param X:the training features of the dataset
:param y: the training labels of the dataset
"""
self.number_of_features = X.shape[1]
self.tree = self.build_tree(X, y)
return self
@staticmethod
def split_on_best_feature(X, y, split_column, split_value):
"""
Split the feature data and labels into two subsets, selecting the feature column to be used, using the
split value as a threshold.
:param X: the 2 D numpy array holding the features dataset
:param y: the 1 D numpy array holding the labels.
:param split_column: corresponds to all th values for a feature
:param split_value: the threshold value to split on
:return: two pairs of branches, left and right, holding feature and labels
>>> f = np.array([[5.1, 3.5, 1.4, 0.2],[4.9, 3.0, 1.4, 0.2],
... [6.5,2.8,4.6,1.5],[5.7,2.8,4.5,1.3]])
>>> l = np.array([0,0,1,1])
>>> sc = 3
>>> sv = 0.8
>>> CartDecisionTreeClassifier.split_on_best_feature(f,l,sc,sv)
(array([[5.1, 3.5, 1.4, 0.2],
[4.9, 3. , 1.4, 0.2]]), array([0, 0]), array([[6.5, 2.8, 4.6, 1.5],
[5.7, 2.8, 4.5, 1.3]]), array([1, 1]))
"""
indices_left = X[:, split_column] <= split_value
X_left, y_left = X[indices_left], y[indices_left]
X_right, y_right = X[~indices_left], y[~indices_left]
return X_left, y_left, X_right, y_right
@staticmethod
def find_feature_midpoint(column_values, split_value):
"""
Split on a value mid way between two feature values to increase the chances
of finding a good boundary
:param column_values: The values in a feature column
:param split_value: The feature value that returned the best gini index
:return: the mid point between the split value and the feature value
>>> y = np.array([1,2,3,4,5,6,7,8])
>>> sv = 4
>>> CartDecisionTreeClassifier.find_feature_midpoint(y, sv)
4.5
"""
index = column_values.tolist().index(split_value)
if index < len(column_values):
next_value = column_values[index + 1]
best_split_value = (split_value + next_value) / 2
else:
best_split_value = split_value
return best_split_value
@staticmethod
def calculate_gini_index(y):
"""
The gini index is used to measure the impurity of a set
:param y: the label values
:return: the gini index
>>> t = np.array([0,0,0,1,1,3,3,3,3,3])
>>> CartDecisionTreeClassifier.calculate_gini_index(t)
0.62
"""
_, counts = np.unique(y, return_counts=True)
probabilities = counts / counts.sum()
gini = 1 - sum(probabilities ** 2)
return gini
def calculate_gini_gain(self, y_left, y_right):
"""
The gini gain is a measure of the likelihood of an incorrect classification of a
new instance of a random variable, if that new instance were randomly classified
according to the distribution of class labels from the data set.
:param y_left: the set of labels below the threshold
:param y_right: the set of labels afove the threshold
:return: the measure of gini gain
>>> ll = np.array([0,0,0,0])
>>> lr = np.array([1,1,2,2,2,2])
>>> dtc = CartDecisionTreeClassifier()
>>> dtc.calculate_gini_gain(ll, lr)
0.4444444444444444
"""
return self.calculate_gini_index(y_left) + self.calculate_gini_index(y_right)
def find_best_split_value_for_feature(self, X, y, split_column):
"""
Find the best split value for a given feature
:param X: the features of the dataset
:param y: the labels in the dataset
:param split_column: the column number
:return: return a tuple contains the best split value and the gini gain
>>> f = np.array([[5.1,3.5,1.4,0.2],[4.9,3.0,1.4,0.2],[6.2,2.9,4.3,1.3],
... [5.0,2.3,3.3,1.0],[6.3,3.3,6.0,2.5], [4.7,3.2,1.3,0.2]])
>>> l = np.array([0,0,0,1,1,2])
>>> sc = 3
>>> dtc = CartDecisionTreeClassifier()
>>> dtc.find_best_split_value_for_feature(f, l, sc)
(1.9, 0.5599999999999999)
"""
gini_gain = 999
X_values = X[:, split_column]
unique_values = np.unique(X_values)
for i in range(0, len(unique_values)):
split_value = unique_values[i]
X_left, y_left, X_right, y_right = \
self.split_on_best_feature(X, y, split_column, split_value)
temp_gain = self.calculate_gini_gain(y_left, y_right)
if temp_gain <= gini_gain:
gini_gain = temp_gain
best_split_value = split_value
normalized_split_value = self.find_feature_midpoint(unique_values, best_split_value)
return normalized_split_value, gini_gain
def find_best_feature(self, features, labels):
"""
Find the feature by looping through the columns of the dataset and finding the one
that returns the best gini gain score
:param features: the features of the dataset
:param labels: the labels in the dataset
:return: return a tuple containing the best feature and the best split value for
that feature
>>> f = np.array([[5.1,3.5,1.4,0.2],[4.9,3.0,1.4,0.2],[6.2,2.9,4.3,1.3],
... [5.0,2.3,3.3,1.0],[6.3,3.3,6.0,2.5], [4.7,3.2,1.3,0.2]])
>>> l = np.array([0,0,0,1,1,2])
>>> dtc = CartDecisionTreeClassifier()
>>> dtc.find_best_feature(f, l)
(2, 1.35, 0.48)
"""
gini_index = 999
_, num_columns = features.shape
for column_index in range(0, num_columns):
split_value, temp_gi = self.find_best_split_value_for_feature(features, labels, column_index)
if temp_gi <= gini_index:
gini_index = temp_gi
best_split_value = split_value
best_column = column_index
return best_column, best_split_value, gini_index
@staticmethod
def predict_label(labels):
"""
Find the label with the highest number of values in a subset
:param labels: an array of labels
:return: the most frequently occuring label
>>> l = np.array([0,0,0,1,1,2])
>>> CartDecisionTreeClassifier.predict_label(l)
0
"""
unique_labels, counts_unique_labels = np.unique(labels, return_counts=True)
index = counts_unique_labels.argmax()
predicted_label = unique_labels[index]
return predicted_label
@staticmethod
def is_leaf(labels):
"""
If all the labels are of the same type this is a leaf node and no futher processing is
required
:param labels: labels: an array of labels
:return: a boolean
>>> l = np.array([0,0,0,0,0,0])
>>> CartDecisionTreeClassifier.is_leaf(l)
True
"""
unique_classes = np.unique(labels)
if len(unique_classes) == 1:
return True
else:
return False
def build_tree(self, X, y, counter=0):
"""
Recursively build tree, splitting on the feature and value that increases information purity each time.
Check for depth and the number of class labels in each node.
:param X:the training features of the dataset
:param y: the training labels of the dataset
:param counter: Records the current depth of the tree
:return: a node is returned for the current depth containing child branches if any
along with the predicted label, the feature column used for the prediction and the
spit value on the feature column
For the doctest dont print the left and right branches
>>> f = np.array([[5.1,3.5,1.4,0.2],[4.9,3.0,1.4,0.2],[6.2,2.9,4.3,1.3],
... [5.0,2.3,3.3,1.0],[6.3,3.3,6.0,2.5], [4.7,3.2,1.3,0.2]])
>>> l = np.array([0,0,0,1,1,2])
>>> dtc = CartDecisionTreeClassifier()
>>> test_node = dtc.build_tree(f, l)
>>> print(test_node.predicted_label, test_node.feature_column, test_node.split_value)
0 2 1.35
"""
if (self.is_leaf(y)) or (counter == self.max_depth) or \
(len(y) < self.min_samples_leaf):
predicted_label = self.predict_label(y)
node = Node(predicted_label=predicted_label, samples=len(y))
return node
else:
counter += 1
predicted_label = self.predict_label(y)
node = Node(predicted_label=predicted_label, samples=len(y))
node.current_depth = counter
split_column, split_value, gini_index = self.find_best_feature(X, y)
X_left, y_left, X_right, y_right = \
self.split_on_best_feature(X, y, split_column, split_value)
node.feature_column = split_column
node.split_value = split_value
node.gini_index = gini_index
# the recursive bit...
left_branch = self.build_tree(X_left, y_left, counter)
right_branch = self.build_tree(X_right, y_right, counter)
if left_branch == right_branch:
node = left_branch
else:
node.left = left_branch
node.right = right_branch
return node
def predict(self, y):
"""
The predict method runs on the test set. Iterate through the test feature set. For each row, traverse
the nodes of the tree with the test feature values and return the predicted class label as per
the created model
:param y: The testing features of the dataset
:return: return the predicted label
"""
predicted_label = []
for row in y:
node = self.tree
while node.left:
if row[node.feature_column] < node.split_value:
node = node.left
else:
node = node.right
predicted_label.append(node.predicted_label)
return np.array(predicted_label)
def feature_importance(self):
# todo: implement this class to use sklearn feature selection
pass
| [
"numpy.array",
"numpy.unique"
] | [((3620, 3652), 'numpy.unique', 'np.unique', (['y'], {'return_counts': '(True)'}), '(y, return_counts=True)\n', (3629, 3652), True, 'import numpy as np\n'), ((5341, 5360), 'numpy.unique', 'np.unique', (['X_values'], {}), '(X_values)\n', (5350, 5360), True, 'import numpy as np\n'), ((7470, 7507), 'numpy.unique', 'np.unique', (['labels'], {'return_counts': '(True)'}), '(labels, return_counts=True)\n', (7479, 7507), True, 'import numpy as np\n'), ((8017, 8034), 'numpy.unique', 'np.unique', (['labels'], {}), '(labels)\n', (8026, 8034), True, 'import numpy as np\n'), ((11152, 11177), 'numpy.array', 'np.array', (['predicted_label'], {}), '(predicted_label)\n', (11160, 11177), True, 'import numpy as np\n')] |
from Crypto.Cipher import AES
from Crypto import Random
import numpy as np
import math
def countByte(data):
countedData = [0] * 256
for k in data:
countedData[k] += 1
return countedData
def calculateSecrecy(key, cipher):
countedKey = countByte(key)
countedCipher = countByte(cipher)
entropy = 0
secrecy = 0
for j in range(0, 256):
p_k = 1.0 * countedKey[j] / len(key)
p_c = 1.0 * countedCipher[j] / len(cipher)
if (p_k > 0):
entropy += p_k * np.log2(p_k)
secrecy += -p_c * entropy
return secrecy
def encryptAES(key, plaintext):
cipher = AES.new(key)
ciphertxt = cipher.encrypt(plaintext)
return ciphertxt
def getResults(keysize, plaintextsize):
key = Random.new().read(keysize)
totalValue = 0
for i in range(0, 100):
plaintext = Random.new().read(plaintextsize)
ciphertxt = encryptAES(key, plaintext)
cipherbyte = np.fromstring(ciphertxt, dtype=np.uint8)
keybyte = np.fromstring(key, dtype=np.uint8)
totalValue += calculateSecrecy(keybyte, cipherbyte)
avgValue = totalValue / 100
return avgValue
| [
"numpy.log2",
"numpy.fromstring",
"Crypto.Random.new",
"Crypto.Cipher.AES.new"
] | [((642, 654), 'Crypto.Cipher.AES.new', 'AES.new', (['key'], {}), '(key)\n', (649, 654), False, 'from Crypto.Cipher import AES\n'), ((967, 1007), 'numpy.fromstring', 'np.fromstring', (['ciphertxt'], {'dtype': 'np.uint8'}), '(ciphertxt, dtype=np.uint8)\n', (980, 1007), True, 'import numpy as np\n'), ((1026, 1060), 'numpy.fromstring', 'np.fromstring', (['key'], {'dtype': 'np.uint8'}), '(key, dtype=np.uint8)\n', (1039, 1060), True, 'import numpy as np\n'), ((770, 782), 'Crypto.Random.new', 'Random.new', ([], {}), '()\n', (780, 782), False, 'from Crypto import Random\n'), ((524, 536), 'numpy.log2', 'np.log2', (['p_k'], {}), '(p_k)\n', (531, 536), True, 'import numpy as np\n'), ((865, 877), 'Crypto.Random.new', 'Random.new', ([], {}), '()\n', (875, 877), False, 'from Crypto import Random\n')] |
"""
Paper: Session-based Recommendations with Recurrent Neural Networks
Author: <NAME>, <NAME>, <NAME>, and <NAME>
Reference: https://github.com/hidasib/GRU4Rec
https://github.com/Songweiping/GRU4Rec_TensorFlow
@author: <NAME>
"""
import numpy as np
from model.AbstractRecommender import SeqAbstractRecommender
import tensorflow as tf
from util import log_loss, l2_loss
class GRU4Rec(SeqAbstractRecommender):
def __init__(self, sess, dataset, conf):
super(GRU4Rec, self).__init__(dataset, conf)
self.train_matrix = dataset.train_matrix
self.dataset = dataset
self.users_num, self.items_num = self.train_matrix.shape
self.lr = conf["lr"]
self.reg = conf["reg"]
self.layers = conf["layers"]
self.batch_size = conf["batch_size"]
self.epochs = conf["epochs"]
if conf["hidden_act"] == "relu":
self.hidden_act = tf.nn.relu
elif conf["hidden_act"] == "tanh":
self.hidden_act = tf.nn.tanh
else:
raise ValueError("There is not hidden_act named '%s'." % conf["hidden_act"])
# final_act = leaky-relu
if conf["final_act"] == "relu":
self.final_act = tf.nn.relu
elif conf["final_act"] == "linear":
self.final_act = tf.identity
elif conf["final_act"] == "leaky_relu":
self.final_act = tf.nn.leaky_relu
else:
raise ValueError("There is not final_act named '%s'." % conf["final_act"])
if conf["loss"] == "bpr":
self.loss_fun = self._bpr_loss
elif conf["loss"] == "top1":
self.loss_fun = self._top1_loss
else:
raise ValueError("There is not loss named '%s'." % conf["loss"])
self.data_uit, self.offset_idx = self._init_data()
# for sampling negative items
_, pop = np.unique(self.data_uit[:, 1], return_counts=True)
pop_cumsum = np.cumsum(pop)
self.pop_cumsum = pop_cumsum / pop_cumsum[-1]
self.sess = sess
def _init_data(self):
time_dok = self.dataset.time_matrix.todok()
data_uit = [[row, col, time] for (row, col), time in time_dok.items()]
data_uit.sort(key=lambda x: (x[0], x[-1]))
data_uit = np.array(data_uit, dtype=np.int32)
_, idx = np.unique(data_uit[:, 0], return_index=True)
offset_idx = np.zeros(len(idx)+1, dtype=np.int32)
offset_idx[:-1] = idx
offset_idx[-1] = len(data_uit)
return data_uit, offset_idx
def _create_variable(self):
self.X_ph = tf.placeholder(tf.int32, [self.batch_size], name='input')
self.Y_ph = tf.placeholder(tf.int32, [self.batch_size], name='output')
self.state_ph = [tf.placeholder(tf.float32, [self.batch_size, n_unit], name='layer_%d_state' % idx)
for idx, n_unit in enumerate(self.layers)]
init = tf.random.truncated_normal([self.items_num, self.layers[0]], mean=0.0, stddev=0.01)
self.input_embeddings = tf.Variable(init, dtype=tf.float32, name="input_embeddings")
init = tf.random.truncated_normal([self.items_num, self.layers[-1]], mean=0.0, stddev=0.01)
self.item_embeddings = tf.Variable(init, dtype=tf.float32, name="item_embeddings")
self.item_biases = tf.Variable(tf.zeros([self.items_num]), dtype=tf.float32, name="item_biases")
def _bpr_loss(self, logits):
# logits: (b, size_y)
pos_logits = tf.matrix_diag_part(logits) # (b,)
pos_logits = tf.reshape(pos_logits, shape=[-1, 1]) # (b, 1)
loss = tf.reduce_mean(log_loss(pos_logits-logits))
return loss
def _top1_loss(self, logits):
# logits: (b, size_y)
pos_logits = tf.matrix_diag_part(logits) # (b,)
pos_logits = tf.reshape(pos_logits, shape=[-1, 1]) # (b, 1)
loss1 = tf.reduce_mean(tf.sigmoid(-pos_logits + logits), axis=-1) # (b,)
loss2 = tf.reduce_mean(tf.sigmoid(tf.pow(logits, 2)), axis=-1) - \
tf.squeeze(tf.sigmoid(tf.pow(pos_logits, 2))/self.batch_size) # (b,)
return tf.reduce_mean(loss1+loss2)
def build_graph(self):
self._create_variable()
# get embedding and bias
# b: batch size
# l1: the dim of the first layer
# ln: the dim of the last layer
# size_y: the length of Y_ph, i.e., n_sample+batch_size
cells = [tf.nn.rnn_cell.GRUCell(size, activation=self.hidden_act) for size in self.layers]
drop_cell = [tf.nn.rnn_cell.DropoutWrapper(cell) for cell in cells]
stacked_cell = tf.nn.rnn_cell.MultiRNNCell(drop_cell)
inputs = tf.nn.embedding_lookup(self.input_embeddings, self.X_ph) # (b, l1)
outputs, state = stacked_cell(inputs, state=self.state_ph)
self.u_emb = outputs # outputs: (b, ln)
self.final_state = state # [(b, l1), (b, l2), ..., (b, ln)]
# for training
items_embed = tf.nn.embedding_lookup(self.item_embeddings, self.Y_ph) # (size_y, ln)
items_bias = tf.gather(self.item_biases, self.Y_ph) # (size_y,)
logits = tf.matmul(outputs, items_embed, transpose_b=True) + items_bias # (b, size_y)
logits = self.final_act(logits)
loss = self.loss_fun(logits)
# reg loss
reg_loss = l2_loss(inputs, items_embed, items_bias)
final_loss = loss + self.reg*reg_loss
self.update_opt = tf.train.AdamOptimizer(self.lr).minimize(final_loss)
def train_model(self):
self.logger.info(self.evaluator.metrics_info())
data_uit, offset_idx = self.data_uit, self.offset_idx
data_items = data_uit[:, 1]
for epoch in range(self.epochs):
state = [np.zeros([self.batch_size, n_unit], dtype=np.float32) for n_unit in self.layers]
user_idx = np.random.permutation(len(offset_idx) - 1)
iters = np.arange(self.batch_size, dtype=np.int32)
maxiter = iters.max()
start = offset_idx[user_idx[iters]]
end = offset_idx[user_idx[iters]+1]
finished = False
while not finished:
min_len = (end - start).min()
out_idx = data_items[start]
for i in range(min_len-1):
in_idx = out_idx
out_idx = data_items[start+i+1]
out_items = out_idx
feed = {self.X_ph: in_idx, self.Y_ph: out_items}
for l in range(len(self.layers)):
feed[self.state_ph[l]] = state[l]
_, state = self.sess.run([self.update_opt, self.final_state], feed_dict=feed)
start = start+min_len-1
mask = np.arange(len(iters))[(end - start) <= 1]
for idx in mask:
maxiter += 1
if maxiter >= len(offset_idx)-1:
finished = True
break
iters[idx] = maxiter
start[idx] = offset_idx[user_idx[maxiter]]
end[idx] = offset_idx[user_idx[maxiter]+1]
if len(mask):
for i in range(len(self.layers)):
state[i][mask] = 0
result = self.evaluate_model()
self.logger.info("epoch %d:\t%s" % (epoch, result))
def _get_user_embeddings(self):
users = np.arange(self.users_num, dtype=np.int32)
u_nnz = np.array([self.train_matrix[u].nnz for u in users], dtype=np.int32)
users = users[np.argsort(-u_nnz)]
user_embeddings = np.zeros([self.users_num, self.layers[-1]], dtype=np.float32) # saving user embedding
data_uit, offset_idx = self.data_uit, self.offset_idx
data_items = data_uit[:, 1]
state = [np.zeros([self.batch_size, n_unit], dtype=np.float32) for n_unit in self.layers]
batch_iter = np.arange(self.batch_size, dtype=np.int32)
next_iter = batch_iter.max() + 1
start = offset_idx[users[batch_iter]]
end = offset_idx[users[batch_iter] + 1] # the start index of next user
batch_mask = np.ones([self.batch_size], dtype=np.int32)
while np.sum(batch_mask) > 0:
min_len = (end - start).min()
for i in range(min_len):
cur_items = data_items[start + i]
feed = {self.X_ph: cur_items}
for l in range(len(self.layers)):
feed[self.state_ph[l]] = state[l]
u_emb, state = self.sess.run([self.u_emb, self.final_state], feed_dict=feed)
start = start + min_len
mask = np.arange(self.batch_size)[(end - start) == 0]
for idx in mask:
u = users[batch_iter[idx]]
user_embeddings[u] = u_emb[idx] # saving user embedding
if next_iter < self.users_num:
batch_iter[idx] = next_iter
start[idx] = offset_idx[users[next_iter]]
end[idx] = offset_idx[users[next_iter] + 1]
next_iter += 1
else:
batch_mask[idx] = 0
start[idx] = 0
end[idx] = offset_idx[-1]
for i, _ in enumerate(self.layers):
state[i][mask] = 0
return user_embeddings
def evaluate_model(self):
self.cur_user_embeddings = self._get_user_embeddings()
self.cur_item_embeddings, self.cur_item_biases = self.sess.run([self.item_embeddings, self.item_biases])
return self.evaluator.evaluate(self)
def predict(self, users, items=None):
user_embeddings = self.cur_user_embeddings[users]
all_ratings = np.matmul(user_embeddings, self.cur_item_embeddings.T) + self.cur_item_biases
# final_act = leaky-relu
if self.final_act == tf.nn.relu:
all_ratings = np.maximum(all_ratings, 0)
elif self.final_act == tf.identity:
all_ratings = all_ratings
elif self.final_act == tf.nn.leaky_relu:
all_ratings = np.maximum(all_ratings, all_ratings*0.2)
else:
pass
all_ratings = np.array(all_ratings, dtype=np.float32)
if items is not None:
all_ratings = [all_ratings[idx][item] for idx, item in enumerate(items)]
return all_ratings
| [
"numpy.sum",
"numpy.maximum",
"tensorflow.reshape",
"util.l2_loss",
"numpy.ones",
"tensorflow.nn.rnn_cell.DropoutWrapper",
"tensorflow.matmul",
"numpy.argsort",
"tensorflow.Variable",
"numpy.arange",
"numpy.unique",
"tensorflow.gather",
"tensorflow.matrix_diag_part",
"numpy.cumsum",
"ten... | [((1877, 1927), 'numpy.unique', 'np.unique', (['self.data_uit[:, 1]'], {'return_counts': '(True)'}), '(self.data_uit[:, 1], return_counts=True)\n', (1886, 1927), True, 'import numpy as np\n'), ((1949, 1963), 'numpy.cumsum', 'np.cumsum', (['pop'], {}), '(pop)\n', (1958, 1963), True, 'import numpy as np\n'), ((2272, 2306), 'numpy.array', 'np.array', (['data_uit'], {'dtype': 'np.int32'}), '(data_uit, dtype=np.int32)\n', (2280, 2306), True, 'import numpy as np\n'), ((2324, 2368), 'numpy.unique', 'np.unique', (['data_uit[:, 0]'], {'return_index': '(True)'}), '(data_uit[:, 0], return_index=True)\n', (2333, 2368), True, 'import numpy as np\n'), ((2586, 2643), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[self.batch_size]'], {'name': '"""input"""'}), "(tf.int32, [self.batch_size], name='input')\n", (2600, 2643), True, 'import tensorflow as tf\n'), ((2664, 2722), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '[self.batch_size]'], {'name': '"""output"""'}), "(tf.int32, [self.batch_size], name='output')\n", (2678, 2722), True, 'import tensorflow as tf\n'), ((2915, 3002), 'tensorflow.random.truncated_normal', 'tf.random.truncated_normal', (['[self.items_num, self.layers[0]]'], {'mean': '(0.0)', 'stddev': '(0.01)'}), '([self.items_num, self.layers[0]], mean=0.0,\n stddev=0.01)\n', (2941, 3002), True, 'import tensorflow as tf\n'), ((3031, 3091), 'tensorflow.Variable', 'tf.Variable', (['init'], {'dtype': 'tf.float32', 'name': '"""input_embeddings"""'}), "(init, dtype=tf.float32, name='input_embeddings')\n", (3042, 3091), True, 'import tensorflow as tf\n'), ((3108, 3196), 'tensorflow.random.truncated_normal', 'tf.random.truncated_normal', (['[self.items_num, self.layers[-1]]'], {'mean': '(0.0)', 'stddev': '(0.01)'}), '([self.items_num, self.layers[-1]], mean=0.0,\n stddev=0.01)\n', (3134, 3196), True, 'import tensorflow as tf\n'), ((3224, 3283), 'tensorflow.Variable', 'tf.Variable', (['init'], {'dtype': 'tf.float32', 'name': '"""item_embeddings"""'}), "(init, dtype=tf.float32, name='item_embeddings')\n", (3235, 3283), True, 'import tensorflow as tf\n'), ((3474, 3501), 'tensorflow.matrix_diag_part', 'tf.matrix_diag_part', (['logits'], {}), '(logits)\n', (3493, 3501), True, 'import tensorflow as tf\n'), ((3531, 3568), 'tensorflow.reshape', 'tf.reshape', (['pos_logits'], {'shape': '[-1, 1]'}), '(pos_logits, shape=[-1, 1])\n', (3541, 3568), True, 'import tensorflow as tf\n'), ((3744, 3771), 'tensorflow.matrix_diag_part', 'tf.matrix_diag_part', (['logits'], {}), '(logits)\n', (3763, 3771), True, 'import tensorflow as tf\n'), ((3801, 3838), 'tensorflow.reshape', 'tf.reshape', (['pos_logits'], {'shape': '[-1, 1]'}), '(pos_logits, shape=[-1, 1])\n', (3811, 3838), True, 'import tensorflow as tf\n'), ((4107, 4136), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['(loss1 + loss2)'], {}), '(loss1 + loss2)\n', (4121, 4136), True, 'import tensorflow as tf\n'), ((4596, 4634), 'tensorflow.nn.rnn_cell.MultiRNNCell', 'tf.nn.rnn_cell.MultiRNNCell', (['drop_cell'], {}), '(drop_cell)\n', (4623, 4634), True, 'import tensorflow as tf\n'), ((4652, 4708), 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['self.input_embeddings', 'self.X_ph'], {}), '(self.input_embeddings, self.X_ph)\n', (4674, 4708), True, 'import tensorflow as tf\n'), ((4951, 5006), 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (['self.item_embeddings', 'self.Y_ph'], {}), '(self.item_embeddings, self.Y_ph)\n', (4973, 5006), True, 'import tensorflow as tf\n'), ((5044, 5082), 'tensorflow.gather', 'tf.gather', (['self.item_biases', 'self.Y_ph'], {}), '(self.item_biases, self.Y_ph)\n', (5053, 5082), True, 'import tensorflow as tf\n'), ((5310, 5350), 'util.l2_loss', 'l2_loss', (['inputs', 'items_embed', 'items_bias'], {}), '(inputs, items_embed, items_bias)\n', (5317, 5350), False, 'from util import log_loss, l2_loss\n'), ((7416, 7457), 'numpy.arange', 'np.arange', (['self.users_num'], {'dtype': 'np.int32'}), '(self.users_num, dtype=np.int32)\n', (7425, 7457), True, 'import numpy as np\n'), ((7474, 7541), 'numpy.array', 'np.array', (['[self.train_matrix[u].nnz for u in users]'], {'dtype': 'np.int32'}), '([self.train_matrix[u].nnz for u in users], dtype=np.int32)\n', (7482, 7541), True, 'import numpy as np\n'), ((7610, 7671), 'numpy.zeros', 'np.zeros', (['[self.users_num, self.layers[-1]]'], {'dtype': 'np.float32'}), '([self.users_num, self.layers[-1]], dtype=np.float32)\n', (7618, 7671), True, 'import numpy as np\n'), ((7916, 7958), 'numpy.arange', 'np.arange', (['self.batch_size'], {'dtype': 'np.int32'}), '(self.batch_size, dtype=np.int32)\n', (7925, 7958), True, 'import numpy as np\n'), ((8149, 8191), 'numpy.ones', 'np.ones', (['[self.batch_size]'], {'dtype': 'np.int32'}), '([self.batch_size], dtype=np.int32)\n', (8156, 8191), True, 'import numpy as np\n'), ((10200, 10239), 'numpy.array', 'np.array', (['all_ratings'], {'dtype': 'np.float32'}), '(all_ratings, dtype=np.float32)\n', (10208, 10239), True, 'import numpy as np\n'), ((2748, 2834), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[self.batch_size, n_unit]'], {'name': "('layer_%d_state' % idx)"}), "(tf.float32, [self.batch_size, n_unit], name='layer_%d_state' %\n idx)\n", (2762, 2834), True, 'import tensorflow as tf\n'), ((3323, 3349), 'tensorflow.zeros', 'tf.zeros', (['[self.items_num]'], {}), '([self.items_num])\n', (3331, 3349), True, 'import tensorflow as tf\n'), ((3609, 3638), 'util.log_loss', 'log_loss', (['(pos_logits - logits)'], {}), '(pos_logits - logits)\n', (3617, 3638), False, 'from util import log_loss, l2_loss\n'), ((3880, 3912), 'tensorflow.sigmoid', 'tf.sigmoid', (['(-pos_logits + logits)'], {}), '(-pos_logits + logits)\n', (3890, 3912), True, 'import tensorflow as tf\n'), ((4415, 4471), 'tensorflow.nn.rnn_cell.GRUCell', 'tf.nn.rnn_cell.GRUCell', (['size'], {'activation': 'self.hidden_act'}), '(size, activation=self.hidden_act)\n', (4437, 4471), True, 'import tensorflow as tf\n'), ((4518, 4553), 'tensorflow.nn.rnn_cell.DropoutWrapper', 'tf.nn.rnn_cell.DropoutWrapper', (['cell'], {}), '(cell)\n', (4547, 4553), True, 'import tensorflow as tf\n'), ((5114, 5163), 'tensorflow.matmul', 'tf.matmul', (['outputs', 'items_embed'], {'transpose_b': '(True)'}), '(outputs, items_embed, transpose_b=True)\n', (5123, 5163), True, 'import tensorflow as tf\n'), ((5889, 5931), 'numpy.arange', 'np.arange', (['self.batch_size'], {'dtype': 'np.int32'}), '(self.batch_size, dtype=np.int32)\n', (5898, 5931), True, 'import numpy as np\n'), ((7564, 7582), 'numpy.argsort', 'np.argsort', (['(-u_nnz)'], {}), '(-u_nnz)\n', (7574, 7582), True, 'import numpy as np\n'), ((7814, 7867), 'numpy.zeros', 'np.zeros', (['[self.batch_size, n_unit]'], {'dtype': 'np.float32'}), '([self.batch_size, n_unit], dtype=np.float32)\n', (7822, 7867), True, 'import numpy as np\n'), ((8206, 8224), 'numpy.sum', 'np.sum', (['batch_mask'], {}), '(batch_mask)\n', (8212, 8224), True, 'import numpy as np\n'), ((9742, 9796), 'numpy.matmul', 'np.matmul', (['user_embeddings', 'self.cur_item_embeddings.T'], {}), '(user_embeddings, self.cur_item_embeddings.T)\n', (9751, 9796), True, 'import numpy as np\n'), ((9921, 9947), 'numpy.maximum', 'np.maximum', (['all_ratings', '(0)'], {}), '(all_ratings, 0)\n', (9931, 9947), True, 'import numpy as np\n'), ((5423, 5454), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', (['self.lr'], {}), '(self.lr)\n', (5445, 5454), True, 'import tensorflow as tf\n'), ((5722, 5775), 'numpy.zeros', 'np.zeros', (['[self.batch_size, n_unit]'], {'dtype': 'np.float32'}), '([self.batch_size, n_unit], dtype=np.float32)\n', (5730, 5775), True, 'import numpy as np\n'), ((8660, 8686), 'numpy.arange', 'np.arange', (['self.batch_size'], {}), '(self.batch_size)\n', (8669, 8686), True, 'import numpy as np\n'), ((3973, 3990), 'tensorflow.pow', 'tf.pow', (['logits', '(2)'], {}), '(logits, 2)\n', (3979, 3990), True, 'import tensorflow as tf\n'), ((10105, 10147), 'numpy.maximum', 'np.maximum', (['all_ratings', '(all_ratings * 0.2)'], {}), '(all_ratings, all_ratings * 0.2)\n', (10115, 10147), True, 'import numpy as np\n'), ((4044, 4065), 'tensorflow.pow', 'tf.pow', (['pos_logits', '(2)'], {}), '(pos_logits, 2)\n', (4050, 4065), True, 'import tensorflow as tf\n')] |
import numpy as np
import cv2
from pathlib import Path
class MappingPoints:
def __init__(self, settings_map):
if settings_map.get('interceptor'):
settings_map['frame_points'] = (np.array(settings_map['frame_points']) -
np.array(settings_map['interceptor'])).tolist()
self.frame_points = np.int32(settings_map['frame_points'])
self.map_points = np.int32(settings_map['map_points'])
self.coord_points = np.array(settings_map['coord_points'])
self.VIDEO_SOURCE = f"data/{settings_map['VIDEO_SOURCE']}"
self.MAP_SOURCE = f"data/{settings_map['MAP_SOURCE']}"
self.transform_frame_to_map = cv2.getPerspectiveTransform(np.float32(self.frame_points),
np.float32(self.map_points))
self.transform_frame_to_coord = cv2.getPerspectiveTransform(np.float32(self.frame_points),
np.float32(self.coord_points))
def render_image_with_points(self, frame, points, cars=None):
frame_layer = frame.copy()
for p in points:
cv2.circle(frame_layer, tuple(p.tolist()), radius=5, color=(255, 200, 200), thickness=3)
cv2.polylines(frame_layer, [points.reshape((-1, 1, 2))], 4, color=(255, 200, 200), thickness=3)
if not cars is None:
for c in cars:
cv2.circle(frame_layer, tuple(c.tolist()[:2]), radius=5, color=(100, 255, 100), thickness=3)
frame = cv2.addWeighted(frame_layer, 0.8, frame, 0.2, 0.0)
return frame
def render_frame(self, frame=None, frame_point_car=None):
if frame is None:
frame = cv2.VideoCapture(self.VIDEO_SOURCE)
success, frame = frame.read()
if not frame_point_car is None:
frame_point_car = np.int32(frame_point_car)
return self.render_image_with_points(frame, self.frame_points, frame_point_car)
def render_map(self, frame=None, frame_point_car=None):
map_point_car = None
if not frame_point_car is None:
map_point_car = np.int32(self.getRealPoints(self.transform_frame_to_map, frame_point_car))
if frame is None:
frame = cv2.imread(self.MAP_SOURCE)
return self.render_image_with_points(frame, self.map_points, map_point_car)
def getRealPoints(self, lambda_tr, cars):
real_points = np.dot(lambda_tr, np.c_[cars, np.ones(cars.shape[0])].T).T
return np.divide(real_points.T, real_points[:, 2]).T
def render(self, frame=None, map=None, cars=None):
cars = self.test_cars_type(cars)
frame = self.render_frame(frame, cars)
map = self.render_map(map, cars)
frame_with_map = np.concatenate((frame, map), axis=0)
return frame_with_map
def test_cars_type(self, cars):
if not cars is None:
if isinstance(cars, list):
cars = np.array(cars)
if cars.ndim == 1:
cars = cars.reshape(-1, 2)
return cars
if __name__ == '__main__':
settings = {
'frame_points': [[346, 633], [1500, 404], [2405, 474], [1072, 1050]],
'map_points': [[297, 11], [569, 332], [462, 619], [96, 212]],
'coord_points': [[55.857961, 37.350879], [55.857386, 37.351734], [55.856881, 37.351394],
[55.857599, 37.35025]],
'interceptor': [699, 417],
'VIDEO_SOURCE': "frame.mp4",
'MAP_SOURCE': "map.PNG"
}
frame_with_map = MappingPoints(settings).render()
cv2.imshow('Image', frame_with_map)
cv2.waitKey(0)
cv2.destroyAllWindows()
| [
"numpy.divide",
"cv2.waitKey",
"numpy.float32",
"cv2.imshow",
"numpy.ones",
"cv2.addWeighted",
"cv2.VideoCapture",
"cv2.imread",
"numpy.array",
"numpy.int32",
"cv2.destroyAllWindows",
"numpy.concatenate"
] | [((3612, 3647), 'cv2.imshow', 'cv2.imshow', (['"""Image"""', 'frame_with_map'], {}), "('Image', frame_with_map)\n", (3622, 3647), False, 'import cv2\n'), ((3652, 3666), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (3663, 3666), False, 'import cv2\n'), ((3671, 3694), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (3692, 3694), False, 'import cv2\n'), ((365, 403), 'numpy.int32', 'np.int32', (["settings_map['frame_points']"], {}), "(settings_map['frame_points'])\n", (373, 403), True, 'import numpy as np\n'), ((430, 466), 'numpy.int32', 'np.int32', (["settings_map['map_points']"], {}), "(settings_map['map_points'])\n", (438, 466), True, 'import numpy as np\n'), ((495, 533), 'numpy.array', 'np.array', (["settings_map['coord_points']"], {}), "(settings_map['coord_points'])\n", (503, 533), True, 'import numpy as np\n'), ((1567, 1617), 'cv2.addWeighted', 'cv2.addWeighted', (['frame_layer', '(0.8)', 'frame', '(0.2)', '(0.0)'], {}), '(frame_layer, 0.8, frame, 0.2, 0.0)\n', (1582, 1617), False, 'import cv2\n'), ((2800, 2836), 'numpy.concatenate', 'np.concatenate', (['(frame, map)'], {'axis': '(0)'}), '((frame, map), axis=0)\n', (2814, 2836), True, 'import numpy as np\n'), ((730, 759), 'numpy.float32', 'np.float32', (['self.frame_points'], {}), '(self.frame_points)\n', (740, 759), True, 'import numpy as np\n'), ((827, 854), 'numpy.float32', 'np.float32', (['self.map_points'], {}), '(self.map_points)\n', (837, 854), True, 'import numpy as np\n'), ((924, 953), 'numpy.float32', 'np.float32', (['self.frame_points'], {}), '(self.frame_points)\n', (934, 953), True, 'import numpy as np\n'), ((1023, 1052), 'numpy.float32', 'np.float32', (['self.coord_points'], {}), '(self.coord_points)\n', (1033, 1052), True, 'import numpy as np\n'), ((1748, 1783), 'cv2.VideoCapture', 'cv2.VideoCapture', (['self.VIDEO_SOURCE'], {}), '(self.VIDEO_SOURCE)\n', (1764, 1783), False, 'import cv2\n'), ((1896, 1921), 'numpy.int32', 'np.int32', (['frame_point_car'], {}), '(frame_point_car)\n', (1904, 1921), True, 'import numpy as np\n'), ((2289, 2316), 'cv2.imread', 'cv2.imread', (['self.MAP_SOURCE'], {}), '(self.MAP_SOURCE)\n', (2299, 2316), False, 'import cv2\n'), ((2544, 2587), 'numpy.divide', 'np.divide', (['real_points.T', 'real_points[:, 2]'], {}), '(real_points.T, real_points[:, 2])\n', (2553, 2587), True, 'import numpy as np\n'), ((2995, 3009), 'numpy.array', 'np.array', (['cars'], {}), '(cars)\n', (3003, 3009), True, 'import numpy as np\n'), ((204, 242), 'numpy.array', 'np.array', (["settings_map['frame_points']"], {}), "(settings_map['frame_points'])\n", (212, 242), True, 'import numpy as np\n'), ((289, 326), 'numpy.array', 'np.array', (["settings_map['interceptor']"], {}), "(settings_map['interceptor'])\n", (297, 326), True, 'import numpy as np\n'), ((2500, 2522), 'numpy.ones', 'np.ones', (['cars.shape[0]'], {}), '(cars.shape[0])\n', (2507, 2522), True, 'import numpy as np\n')] |
import os
from datetime import datetime
import numpy as np
import scipy.io as sio
import re
from decimal import Decimal
import pathlib
import datajoint as dj
from pipeline import (reference, subject, acquisition, stimulation, analysis, virus,
intracellular, behavior, utilities)
# ================== Dataset ==================
data_dir = pathlib.Path(dj.config['custom'].get('data_directory')).as_posix()
meta_data_dir = os.path.join(data_dir, 'metadata')
sess_data_dir = os.path.join(data_dir, 'datafiles')
# ===================== Part 1: meta_data ========
meta_data_files = os.listdir(meta_data_dir)
for meta_data_file in meta_data_files:
print(f'-- Read {meta_data_file} --')
meta_data = sio.loadmat(os.path.join(
meta_data_dir, meta_data_file), struct_as_record=False, squeeze_me=True)['meta_data']
# ==================== subject ====================
subject_info = dict(subject_id=meta_data.animal_ID.lower(),
sex=meta_data.sex[0].upper() if meta_data.sex.size != 0 else 'U',
species=meta_data.species.lower())
if meta_data.animal_background.size != 0:
subject_info['subject_description'] = meta_data.animal_background
# dob
if meta_data.data_of_birth.size != 0:
subject_info['date_of_birth'] = utilities.parse_date(meta_data.data_of_birth)
# allele
source_strain = meta_data.source_strain # subject.Allele
if len(source_strain) > 0: # if found, search found string to find matched strain in db
allele_dict = {alias.lower(): allele for alias, allele in subject.AlleleAlias.fetch()}
regex_str = '|'.join([re.escape(alias) for alias in allele_dict.keys()])
alleles = [allele_dict[s.lower()] for s in re.findall(regex_str, source_strain, re.I)]
else:
alleles = ['N/A']
# source
source_identifier = meta_data.source_identifier # reference.AnimalSource
if len(source_identifier) > 0: # if found, search found string to find matched strain in db
source_dict = {alias.lower(): source for alias, source in reference.AnimalSourceAlias.fetch()}
regex_str = '|'.join([re.escape(alias) for alias in source_dict.keys()])
subject_info['animal_source'] = (source_dict[
re.search(regex_str, source_identifier, re.I).group().lower()]
if re.search(regex_str, source_identifier, re.I) else 'N/A')
else:
subject_info['animal_source'] = 'N/A'
with subject.Subject.connection.transaction:
if subject_info not in subject.Subject.proj():
subject.Subject.insert1(subject_info, ignore_extra_fields=True)
subject.Subject.Allele.insert((dict(subject_info, allele = k)
for k in alleles), ignore_extra_fields = True)
# ==================== session ====================
# -- session_time
date_of_experiment = utilities.parse_date(str(meta_data.date_of_experiment)) # acquisition.Session
if date_of_experiment is not None:
session_info = {'session_id': re.search('Cell\d+', meta_data_file).group(),
'session_time': date_of_experiment}
# experimenter and experiment type (possible multiple experimenters or types)
experiment_types = meta_data.experiment_type
experimenters = meta_data.experimenters # reference.Experimenter
experimenters = [experimenters] if np.array(experimenters).size <= 1 else experimenters # in case there's only 1 experimenter
reference.Experimenter.insert(zip(experimenters), skip_duplicates=True)
acquisition.ExperimentType.insert(zip(experiment_types), skip_duplicates=True)
with acquisition.Session.connection.transaction:
if {**subject_info, **session_info} not in acquisition.Session.proj():
acquisition.Session.insert1({**subject_info, **session_info}, ignore_extra_fields=True)
acquisition.Session.Experimenter.insert((dict({**subject_info, **session_info}, experimenter=k) for k in experimenters), ignore_extra_fields=True)
acquisition.Session.ExperimentType.insert((dict({**subject_info, **session_info}, experiment_type=k) for k in experiment_types), ignore_extra_fields=True)
print(f'Creating Session - Subject: {subject_info["subject_id"]} - Date: {session_info["session_time"]}')
# ==================== Intracellular ====================
if isinstance(meta_data.extracellular, sio.matlab.mio5_params.mat_struct):
extracellular = meta_data.extracellular
brain_region = re.split(',\s?|\s', extracellular.atlas_location)[1]
recording_coord_depth = extracellular.recording_coord_location[1] # acquisition.RecordingLocation
cortical_layer, brain_subregion = re.split(',\s?|\s', extracellular.recording_coord_location[0])[1:3]
hemisphere = 'left' # hardcoded here, not found in data, not found in paper
brain_location = {'brain_region': brain_region,
'brain_subregion': brain_subregion,
'cortical_layer': cortical_layer,
'hemisphere': hemisphere,
'brain_location_full_name': extracellular.atlas_location}
# -- BrainLocation
if brain_location not in reference.BrainLocation.proj():
reference.BrainLocation.insert1(brain_location)
# -- Whole Cell Device
ie_device = extracellular.probe_type.split(', ')[0]
reference.WholeCellDevice.insert1({'device_name': ie_device, 'device_desc': extracellular.probe_type},
skip_duplicates=True)
# -- Cell
cell_id = meta_data.cell.upper()
cell_key = dict({**subject_info, **session_info, **brain_location},
cell_id=cell_id,
cell_type=extracellular.cell_type,
device_name=ie_device,
recording_depth=round(Decimal(re.match(
'\d+', extracellular.recording_coord_location[1]).group()), 2))
if cell_key not in intracellular.Cell.proj():
intracellular.Cell.insert1(cell_key, ignore_extra_fields = True)
print(f'\tInsert Cell: {cell_id}')
# ==================== Photo stimulation ====================
if isinstance(meta_data.photostim, sio.matlab.mio5_params.mat_struct):
photostimInfo = meta_data.photostim
brain_region = re.split(',\s?|\s', photostimInfo.photostim_atlas_location)[1]
coord_ap_ml_dv = re.findall('\d+.\d+', photostimInfo.photostim_coord_location)
brain_location = {'brain_region': brain_region,
'brain_subregion': 'N/A',
'cortical_layer': 'N/A',
'hemisphere': hemisphere,
'brain_location_full_name': photostimInfo.photostim_atlas_location}
# -- BrainLocation
reference.BrainLocation.insert1(brain_location, skip_duplicates=True)
# -- ActionLocation
action_location = dict(brain_location,
coordinate_ref = 'bregma',
coordinate_ap = round(Decimal(coord_ap_ml_dv[0]), 2),
coordinate_ml = round(Decimal(coord_ap_ml_dv[1]), 2),
coordinate_dv = round(Decimal('0'), 2)) # no depth information for photostim
reference.ActionLocation.insert1(action_location, ignore_extra_fields=True, skip_duplicates=True)
# -- Device
stim_device = 'laser' # hard-coded here, could not find a more specific name from metadata
stimulation.PhotoStimDevice.insert1({'device_name': stim_device}, skip_duplicates=True)
# -- PhotoStimulationInfo
stim_lambda = float(re.match('\d+', getattr(photostimInfo, 'lambda')).group())
photim_stim_protocol = dict(protocol='_'.join([photostimInfo.stimulation_method, str(stim_lambda)]),
device_name=stim_device,
photo_stim_excitation_lambda=stim_lambda,
photo_stim_method=photostimInfo.stimulation_method)
stimulation.PhotoStimulationProtocol.insert1(photim_stim_protocol,
ignore_extra_fields=True, skip_duplicates=True)
if dict(session_info, photostim_datetime = session_info['session_time']) not in stimulation.PhotoStimulation.proj():
stimulation.PhotoStimulation.insert1(dict({**subject_info, **session_info,
**action_location, **photim_stim_protocol},
photostim_datetime = session_info['session_time']),
ignore_extra_fields = True)
print(f'\tInsert Photo-Stimulation')
# ==================== Virus ====================
if isinstance(meta_data.virus, sio.matlab.mio5_params.mat_struct):
virus_info = dict(
virus_source=meta_data.virus.virus_source,
virus=meta_data.virus.virus_name,
virus_lot_number=meta_data.virus.virus_lot_number if meta_data.virus.virus_lot_number.size != 0 else '',
virus_titer=meta_data.virus.titer.replace('x10', '') if len(meta_data.virus.titer) > 0 else None)
virus.Virus.insert1(virus_info, skip_duplicates=True)
# -- BrainLocation
brain_location = {'brain_region': meta_data.virus.atlas_location.split(' ')[0],
'brain_subregion': meta_data.virus.virus_coord_location,
'cortical_layer': 'N/A',
'hemisphere': hemisphere}
reference.BrainLocation.insert1(brain_location, skip_duplicates=True)
virus_injection = dict(
{**virus_info, **subject_info, **brain_location},
coordinate_ref='bregma',
injection_date=utilities.parse_date(meta_data.virus.injection_date))
virus.VirusInjection.insert([dict(virus_injection,
injection_depth = round(Decimal(re.match('\d+', depth).group()), 2),
injection_volume = round(Decimal(re.match('\d+', vol).group()), 2))
for depth, vol in zip(meta_data.virus.depth, meta_data.virus.volume)],
ignore_extra_fields=True, skip_duplicates=True)
print(f'\tInsert Virus Injections - Count: {len(meta_data.virus.depth)}')
| [
"pipeline.stimulation.PhotoStimulation.proj",
"pipeline.subject.AlleleAlias.fetch",
"pipeline.stimulation.PhotoStimulationProtocol.insert1",
"pipeline.reference.WholeCellDevice.insert1",
"pipeline.utilities.parse_date",
"pipeline.acquisition.Session.insert1",
"pipeline.acquisition.Session.proj",
"pipe... | [((447, 481), 'os.path.join', 'os.path.join', (['data_dir', '"""metadata"""'], {}), "(data_dir, 'metadata')\n", (459, 481), False, 'import os\n'), ((498, 533), 'os.path.join', 'os.path.join', (['data_dir', '"""datafiles"""'], {}), "(data_dir, 'datafiles')\n", (510, 533), False, 'import os\n'), ((604, 629), 'os.listdir', 'os.listdir', (['meta_data_dir'], {}), '(meta_data_dir)\n', (614, 629), False, 'import os\n'), ((1329, 1374), 'pipeline.utilities.parse_date', 'utilities.parse_date', (['meta_data.data_of_birth'], {}), '(meta_data.data_of_birth)\n', (1349, 1374), False, 'from pipeline import reference, subject, acquisition, stimulation, analysis, virus, intracellular, behavior, utilities\n'), ((5567, 5695), 'pipeline.reference.WholeCellDevice.insert1', 'reference.WholeCellDevice.insert1', (["{'device_name': ie_device, 'device_desc': extracellular.probe_type}"], {'skip_duplicates': '(True)'}), "({'device_name': ie_device, 'device_desc':\n extracellular.probe_type}, skip_duplicates=True)\n", (5600, 5695), False, 'from pipeline import reference, subject, acquisition, stimulation, analysis, virus, intracellular, behavior, utilities\n'), ((6647, 6710), 're.findall', 're.findall', (['"""\\\\d+.\\\\d+"""', 'photostimInfo.photostim_coord_location'], {}), "('\\\\d+.\\\\d+', photostimInfo.photostim_coord_location)\n", (6657, 6710), False, 'import re\n'), ((7050, 7119), 'pipeline.reference.BrainLocation.insert1', 'reference.BrainLocation.insert1', (['brain_location'], {'skip_duplicates': '(True)'}), '(brain_location, skip_duplicates=True)\n', (7081, 7119), False, 'from pipeline import reference, subject, acquisition, stimulation, analysis, virus, intracellular, behavior, utilities\n'), ((7540, 7641), 'pipeline.reference.ActionLocation.insert1', 'reference.ActionLocation.insert1', (['action_location'], {'ignore_extra_fields': '(True)', 'skip_duplicates': '(True)'}), '(action_location, ignore_extra_fields=True,\n skip_duplicates=True)\n', (7572, 7641), False, 'from pipeline import reference, subject, acquisition, stimulation, analysis, virus, intracellular, behavior, utilities\n'), ((7767, 7858), 'pipeline.stimulation.PhotoStimDevice.insert1', 'stimulation.PhotoStimDevice.insert1', (["{'device_name': stim_device}"], {'skip_duplicates': '(True)'}), "({'device_name': stim_device},\n skip_duplicates=True)\n", (7802, 7858), False, 'from pipeline import reference, subject, acquisition, stimulation, analysis, virus, intracellular, behavior, utilities\n'), ((8321, 8439), 'pipeline.stimulation.PhotoStimulationProtocol.insert1', 'stimulation.PhotoStimulationProtocol.insert1', (['photim_stim_protocol'], {'ignore_extra_fields': '(True)', 'skip_duplicates': '(True)'}), '(photim_stim_protocol,\n ignore_extra_fields=True, skip_duplicates=True)\n', (8365, 8439), False, 'from pipeline import reference, subject, acquisition, stimulation, analysis, virus, intracellular, behavior, utilities\n'), ((9522, 9575), 'pipeline.virus.Virus.insert1', 'virus.Virus.insert1', (['virus_info'], {'skip_duplicates': '(True)'}), '(virus_info, skip_duplicates=True)\n', (9541, 9575), False, 'from pipeline import reference, subject, acquisition, stimulation, analysis, virus, intracellular, behavior, utilities\n'), ((9886, 9955), 'pipeline.reference.BrainLocation.insert1', 'reference.BrainLocation.insert1', (['brain_location'], {'skip_duplicates': '(True)'}), '(brain_location, skip_duplicates=True)\n', (9917, 9955), False, 'from pipeline import reference, subject, acquisition, stimulation, analysis, virus, intracellular, behavior, utilities\n'), ((739, 782), 'os.path.join', 'os.path.join', (['meta_data_dir', 'meta_data_file'], {}), '(meta_data_dir, meta_data_file)\n', (751, 782), False, 'import os\n'), ((2397, 2442), 're.search', 're.search', (['regex_str', 'source_identifier', 're.I'], {}), '(regex_str, source_identifier, re.I)\n', (2406, 2442), False, 'import re\n'), ((2592, 2614), 'pipeline.subject.Subject.proj', 'subject.Subject.proj', ([], {}), '()\n', (2612, 2614), False, 'from pipeline import reference, subject, acquisition, stimulation, analysis, virus, intracellular, behavior, utilities\n'), ((2628, 2691), 'pipeline.subject.Subject.insert1', 'subject.Subject.insert1', (['subject_info'], {'ignore_extra_fields': '(True)'}), '(subject_info, ignore_extra_fields=True)\n', (2651, 2691), False, 'from pipeline import reference, subject, acquisition, stimulation, analysis, virus, intracellular, behavior, utilities\n'), ((4647, 4698), 're.split', 're.split', (['""",\\\\s?|\\\\s"""', 'extracellular.atlas_location'], {}), "(',\\\\s?|\\\\s', extracellular.atlas_location)\n", (4655, 4698), False, 'import re\n'), ((4849, 4913), 're.split', 're.split', (['""",\\\\s?|\\\\s"""', 'extracellular.recording_coord_location[0]'], {}), "(',\\\\s?|\\\\s', extracellular.recording_coord_location[0])\n", (4857, 4913), False, 'import re\n'), ((5376, 5406), 'pipeline.reference.BrainLocation.proj', 'reference.BrainLocation.proj', ([], {}), '()\n', (5404, 5406), False, 'from pipeline import reference, subject, acquisition, stimulation, analysis, virus, intracellular, behavior, utilities\n'), ((5420, 5467), 'pipeline.reference.BrainLocation.insert1', 'reference.BrainLocation.insert1', (['brain_location'], {}), '(brain_location)\n', (5451, 5467), False, 'from pipeline import reference, subject, acquisition, stimulation, analysis, virus, intracellular, behavior, utilities\n'), ((6199, 6224), 'pipeline.intracellular.Cell.proj', 'intracellular.Cell.proj', ([], {}), '()\n', (6222, 6224), False, 'from pipeline import reference, subject, acquisition, stimulation, analysis, virus, intracellular, behavior, utilities\n'), ((6238, 6300), 'pipeline.intracellular.Cell.insert1', 'intracellular.Cell.insert1', (['cell_key'], {'ignore_extra_fields': '(True)'}), '(cell_key, ignore_extra_fields=True)\n', (6264, 6300), False, 'from pipeline import reference, subject, acquisition, stimulation, analysis, virus, intracellular, behavior, utilities\n'), ((6559, 6620), 're.split', 're.split', (['""",\\\\s?|\\\\s"""', 'photostimInfo.photostim_atlas_location'], {}), "(',\\\\s?|\\\\s', photostimInfo.photostim_atlas_location)\n", (6567, 6620), False, 'import re\n'), ((8578, 8613), 'pipeline.stimulation.PhotoStimulation.proj', 'stimulation.PhotoStimulation.proj', ([], {}), '()\n', (8611, 8613), False, 'from pipeline import reference, subject, acquisition, stimulation, analysis, virus, intracellular, behavior, utilities\n'), ((1610, 1637), 'pipeline.subject.AlleleAlias.fetch', 'subject.AlleleAlias.fetch', ([], {}), '()\n', (1635, 1637), False, 'from pipeline import reference, subject, acquisition, stimulation, analysis, virus, intracellular, behavior, utilities\n'), ((1669, 1685), 're.escape', 're.escape', (['alias'], {}), '(alias)\n', (1678, 1685), False, 'import re\n'), ((1771, 1813), 're.findall', 're.findall', (['regex_str', 'source_strain', 're.I'], {}), '(regex_str, source_strain, re.I)\n', (1781, 1813), False, 'import re\n'), ((2106, 2141), 'pipeline.reference.AnimalSourceAlias.fetch', 'reference.AnimalSourceAlias.fetch', ([], {}), '()\n', (2139, 2141), False, 'from pipeline import reference, subject, acquisition, stimulation, analysis, virus, intracellular, behavior, utilities\n'), ((2173, 2189), 're.escape', 're.escape', (['alias'], {}), '(alias)\n', (2182, 2189), False, 'import re\n'), ((3850, 3876), 'pipeline.acquisition.Session.proj', 'acquisition.Session.proj', ([], {}), '()\n', (3874, 3876), False, 'from pipeline import reference, subject, acquisition, stimulation, analysis, virus, intracellular, behavior, utilities\n'), ((3894, 3985), 'pipeline.acquisition.Session.insert1', 'acquisition.Session.insert1', (['{**subject_info, **session_info}'], {'ignore_extra_fields': '(True)'}), '({**subject_info, **session_info},\n ignore_extra_fields=True)\n', (3921, 3985), False, 'from pipeline import reference, subject, acquisition, stimulation, analysis, virus, intracellular, behavior, utilities\n'), ((10115, 10167), 'pipeline.utilities.parse_date', 'utilities.parse_date', (['meta_data.virus.injection_date'], {}), '(meta_data.virus.injection_date)\n', (10135, 10167), False, 'from pipeline import reference, subject, acquisition, stimulation, analysis, virus, intracellular, behavior, utilities\n'), ((3116, 3153), 're.search', 're.search', (['"""Cell\\\\d+"""', 'meta_data_file'], {}), "('Cell\\\\d+', meta_data_file)\n", (3125, 3153), False, 'import re\n'), ((3477, 3500), 'numpy.array', 'np.array', (['experimenters'], {}), '(experimenters)\n', (3485, 3500), True, 'import numpy as np\n'), ((7306, 7332), 'decimal.Decimal', 'Decimal', (['coord_ap_ml_dv[0]'], {}), '(coord_ap_ml_dv[0])\n', (7313, 7332), False, 'from decimal import Decimal\n'), ((7391, 7417), 'decimal.Decimal', 'Decimal', (['coord_ap_ml_dv[1]'], {}), '(coord_ap_ml_dv[1])\n', (7398, 7417), False, 'from decimal import Decimal\n'), ((7476, 7488), 'decimal.Decimal', 'Decimal', (['"""0"""'], {}), "('0')\n", (7483, 7488), False, 'from decimal import Decimal\n'), ((2290, 2335), 're.search', 're.search', (['regex_str', 'source_identifier', 're.I'], {}), '(regex_str, source_identifier, re.I)\n', (2299, 2335), False, 'import re\n'), ((6070, 6129), 're.match', 're.match', (['"""\\\\d+"""', 'extracellular.recording_coord_location[1]'], {}), "('\\\\d+', extracellular.recording_coord_location[1])\n", (6078, 6129), False, 'import re\n'), ((10303, 10326), 're.match', 're.match', (['"""\\\\d+"""', 'depth'], {}), "('\\\\d+', depth)\n", (10311, 10326), False, 'import re\n'), ((10415, 10436), 're.match', 're.match', (['"""\\\\d+"""', 'vol'], {}), "('\\\\d+', vol)\n", (10423, 10436), False, 'import re\n')] |
import numpy as np
import sys
import warnings
from timer import Timer
from scon import scon
from custom_parser import parse_argv
from tensors.ndarray_svd import svd, eig
from tensors.tensorcommon import TensorCommon
from tensors.tensor import Tensor
from tensors.symmetrytensors import TensorZ2, TensorU1, TensorZ3
""" A test suite for the tensors package. """
# We do not accept warnings in the test, so raise them as errors.
warnings.simplefilter("error", UserWarning)
pars = parse_argv(sys.argv,
# Format is: (name_of_argument, type, default)
("test_to_and_from_ndarray", "bool", True),
("test_arithmetic_and_comparison", "bool", True),
("test_transposing", "bool", True),
("test_splitting_and_joining", "bool", True),
("test_to_and_from_matrix", "bool", True),
("test_diag", "bool", True),
("test_trace", "bool", True),
("test_multiply_diag", "bool", True),
("test_product", "bool", True),
("test_svd", "bool", True),
("test_eig", "bool", True),
("test_split", "bool", True),
("test_miscellaneous", "bool", True),
("test_expand_dims_product", "bool", True),
("test_scon_svd_scon", "bool", True),
("n_iters", "int", 500),
("classes", "word_list", ["Tensor", "TensorZ2", "TensorU1",
"TensorZ3"]))
pars = vars(pars)
classes = []
for w in pars["classes"]:
if w.strip().lower() == "tensor":
classes.append(Tensor)
elif w.strip().lower() == "tensorz2":
classes.append(TensorZ2)
elif w.strip().lower() == "tensoru1":
classes.append(TensorU1)
elif w.strip().lower() == "tensorz3":
classes.append(TensorZ3)
timer = Timer()
timer.start()
def test_internal_consistency(T):
if not isinstance(T, (Tensor, np.generic, np.ndarray)):
T.check_consistency()
for cls in classes:
print("\nTesting class " + str(cls))
if cls == TensorZ2:
n_qnums = 2
elif cls == TensorZ3:
n_qnums = 3
else:
n_qnums = None
def rshape(n=None, chi=None, nlow=0, nhigh=5, chilow=0, chihigh=3):
if n is None:
n = np.random.randint(nlow, high=nhigh)
shape = []
for i in range(n):
if n_qnums is None:
dim_dim = np.random.randint(low=1, high=5)
else:
dim_dim = n_qnums
if chi is None:
dim = []
for _ in range(dim_dim):
dim.append(np.random.randint(0, high=chihigh))
else:
dim = [chi]*dim_dim
s = sum(dim)
if s < chilow:
j = np.random.randint(0, len(dim))
dim[j] += chilow - s
shape.append(dim)
return shape
def rqhape(shape, qlow=-3, qhigh=3):
if n_qnums is not None:
qlow = 0
qhigh = n_qnums-1
try:
assert(all(len(dim) <= qhigh-qlow+1 for dim in shape))
except TypeError:
pass
possible_qnums = range(qlow, qhigh+1)
try:
qhape = [list(np.random.choice(possible_qnums, len(dim),
replace=False))
for dim in shape]
except TypeError:
qhape = None
return qhape
def rdirs(shape=None, length=None):
if shape is not None:
length = len(shape)
dirs = np.random.randint(low=0, high=2, size=length)
dirs = list(2*dirs - 1)
return dirs
def rcharge():
return np.random.randint(low=0, high=4)
def rtensor(shape=None, qhape=None, n=None, chi=None,
nlow=0, nhigh=5, chilow=0, chihigh=6,
charge=None, dirs=None, cmplx=True, **kwargs):
if shape is None:
shape = rshape(n=n, chi=chi, nlow=nlow, nhigh=nhigh, chilow=chilow,
chihigh=chihigh)
if qhape is None:
qhape = rqhape(shape)
if dirs is None:
dirs = rdirs(shape=shape)
elif dirs == 1:
dirs = [1]*len(shape)
if charge is None:
charge = rcharge()
real = cls.random(shape, qhape=qhape, dirs=dirs, charge=charge,
**kwargs)
if cmplx:
imag = cls.random(shape, qhape=qhape, dirs=dirs, charge=charge,
**kwargs)
res = real + 1j*imag
else:
res = real
return res
def test_with_np(func, T, S, T_np, S_np):
tensor_res = func(S,T)
np_res = func(S_np, T_np)
np_res = type(tensor_res).from_ndarray(np_res, shape=tensor_res.shape,
qhape=tensor_res.qhape,
dirs=tensor_res.dirs,
charge=tensor_res.charge)
return (tensor_res == np_res).all()
if pars["test_to_and_from_ndarray"]:
for iter_num in range(pars["n_iters"]):
T = rtensor()
T_np = T.to_ndarray()
S = cls.from_ndarray(T_np, shape=T.shape, qhape=T.qhape,
dirs=T.dirs, charge=T.charge)
test_internal_consistency(T)
test_internal_consistency(S)
assert((T==S).all())
print('Done testing to and from ndarray.')
if pars["test_arithmetic_and_comparison"]:
for iter_num in range(pars["n_iters"]):
s = rshape()
q = rqhape(s)
d = rdirs(shape=s)
T = rtensor(shape=s, qhape=q, dirs=d, cmplx=False)
c = T.charge
T_np = T.to_ndarray()
S = rtensor(shape=s, qhape=q, dirs=d, charge=c, cmplx=False)
S_np = S.to_ndarray()
assert(((S+T) - T).allclose(S))
assert(((-S)+S).allclose(cls.zeros(s, qhape=q, dirs=d, charge=c)))
assert((0*S).allclose(cls.zeros(s, qhape=q, dirs=d, charge=c)))
assert((S*0).allclose(cls.zeros(s, qhape=q, dirs=d, charge=c)))
assert((S*cls.zeros(s, qhape=q, dirs=d, charge=c)).allclose(
cls.zeros(s, qhape=q, dirs=d, charge=c)))
assert((cls.zeros(s, qhape=q, dirs=d, charge=c)*S).allclose(
cls.zeros(s, qhape=q, dirs=d, charge=c)))
assert((S*cls.ones(s, qhape=q, dirs=d, charge=c)).allclose(S))
assert((cls.ones(s, qhape=q, dirs=d, charge=c)*S).allclose(S))
assert(((S*2)/2).allclose(S))
assert((2*(S/2)).allclose(S))
assert(((S+2) - 2).allclose(S))
assert((T==T).all())
assert(not (T>T).any())
assert(test_with_np(lambda a,b: a+b, T, S, T_np, S_np))
assert(test_with_np(lambda a,b: a-b, T, S, T_np, S_np))
assert(test_with_np(lambda a,b: a*b, T, S, T_np, S_np))
assert(test_with_np(lambda a,b: a>b, T, S, T_np, S_np))
assert(test_with_np(lambda a,b: a==b, T, S, T_np, S_np))
print('Done testing arithmetic and comparison.')
if pars["test_transposing"]:
for iter_num in range(pars["n_iters"]):
T = rtensor(nlow=1)
shp = T.shape
i = np.random.randint(low=0, high=len(shp))
j = np.random.randint(low=0, high=len(shp))
S = T.copy()
S = S.swapaxes(i,j)
T = T.swapaxes(j,i)
assert((S==T).all())
test_internal_consistency(T)
T = T.swapaxes(i,i)
assert((S==T).all())
test_internal_consistency(T)
T = T.transpose(range(len(shp)))
assert((S==T).all())
test_internal_consistency(T)
perm = list(range(len(shp)))
np.random.shuffle(perm)
T_copy = T.copy()
T = T.transpose(perm)
T_tr_np = T.to_ndarray()
T_np_tr = np.transpose(T_copy.to_ndarray(), perm)
assert(np.all(T_tr_np == T_np_tr))
print('Done testing transposing.')
if pars["test_splitting_and_joining"]:
# First join and then split two indices, compare with original.
for iter_num in range(pars["n_iters"]):
T = rtensor(nlow=2)
T_orig = T.copy()
shp = T.shape
qhp = T.qhape
i = np.random.randint(low=0, high=len(shp))
j = i
while j==i:
j = np.random.randint(low=0, high=len(shp))
i_dim = shp[i]
j_dim = shp[j]
try:
i_qim = qhp[i]
j_qim = qhp[j]
except TypeError:
i_qim = None
j_qim = None
if T.dirs is not None:
di, dj = T.dirs[i], T.dirs[j]
else:
di, dj = None, None
new_d = rdirs(length=1)[0]
T_joined = T.join_indices(i,j, dirs=new_d)
assert((T == T_orig).all())
T = T_joined
test_internal_consistency(T)
if j < i:
i_new = i-1
else:
i_new = i
j_new = i_new + 1
if T.dirs is not None:
assert(T.dirs[i_new] == new_d)
if i != j:
T_before_split = T.copy()
T_split = T.split_indices(i_new, (i_dim, j_dim),
qims=(i_qim, j_qim), dirs=(di, dj))
assert((T_before_split == T).all())
T = T_split
test_internal_consistency(T)
while j_new != j:
if j_new > j:
T = T.swapaxes(j_new, j_new-1)
j_new = j_new - 1
else:
T = T.swapaxes(j_new, j_new+1)
j_new = j_new + 1
test_internal_consistency(T)
assert((T_orig==T).all())
#TODO
# First split then join two indices, compare with original.
#for iter_num in range(pars["n_iters"]):
# shp = rshape(nlow=1)
# i = np.random.randint(low=0, high=len(shp))
# m_dim = rshape(n=1)[0]
# n_dim = rshape(n=1)[0]
# i_dim = cls.combined_dim(m_dim, n_dim)
# shp[i] = i_dim
# T = rtensor(shape=shp)
# T_orig = T.copy()
# T = T.split_indices(i, (m_dim, n_dim))
# test_internal_consistency(T)
# T = T.join_indices(i,i+1)
# test_internal_consistency(T)
# assert((T_orig==T).all())
# First join then split many indices, don't compare.
for iter_num in range(pars["n_iters"]):
T = rtensor(nlow=1)
T_orig = T.copy()
shp = T.shape
batch_sizes = []
while True:
new_size = np.random.randint(low=1, high=len(T.shape)+1)
if sum(batch_sizes) + new_size <= len(T.shape):
batch_sizes.append(new_size)
else:
break
index_batches = []
sum_inds = list(np.random.choice(range(len(T.shape)),
size=sum(batch_sizes),
replace=False))
cumulator = 0
for b_n in batch_sizes:
index_batches.append(sum_inds[cumulator:cumulator+b_n])
cumulator += b_n
not_joined = sorted(set(range(len(T.shape))) - set(sum_inds))
batch_firsts = [batch[0] for batch in index_batches]
remaining_indices = sorted(not_joined + batch_firsts)
batch_new_indices = [remaining_indices.index(i)
for i in batch_firsts]
dim_batches = [[T.shape[i] for i in batch]
for batch in index_batches]
if T.qhape is not None:
qim_batches = [[T.qhape[i] for i in batch]
for batch in index_batches]
else:
qim_batches = None
if T.dirs is not None:
dir_batches = [[T.dirs[i] for i in batch]
for batch in index_batches]
else:
dir_batches = None
new_dirs = rdirs(length=len(index_batches))
T = T.join_indices(*tuple(index_batches), dirs=new_dirs)
test_internal_consistency(T)
T = T.split_indices(batch_new_indices, dim_batches,
qims=qim_batches, dirs=dir_batches)
test_internal_consistency(T)
print('Done testing splitting and joining.')
if pars["test_to_and_from_matrix"]:
for iter_num in range(pars["n_iters"]):
T = rtensor()
T_orig = T.copy()
n = np.random.randint(low=0, high=len(T.shape)+1)
if n:
i_list = list(np.random.choice(len(T.shape), size=n,
replace=False))
else:
i_list = []
i_list_compl = sorted(set(range(len(T.shape))) - set(i_list))
T_matrix, T_transposed_shape, T_transposed_qhape, T_transposed_dirs =\
T.to_matrix(i_list, i_list_compl, return_transposed_shape_data=True)
assert((T == T_orig).all())
T = T_matrix
test_internal_consistency(T)
T_orig = T_orig.transpose(i_list + i_list_compl)
assert(T_transposed_shape == T_orig.shape)
l_dims = T_transposed_shape[:len(i_list)]
r_dims = T_transposed_shape[len(i_list):]
if T_transposed_qhape is not None:
l_qims = T_transposed_qhape[:len(i_list)]
r_qims = T_transposed_qhape[len(i_list):]
else:
l_qims = None
r_qims = None
if T_transposed_dirs is not None:
l_dirs = T_transposed_dirs[:len(i_list)]
r_dirs = T_transposed_dirs[len(i_list):]
else:
l_dirs = None
r_dirs = None
T_matrix = T.copy()
T_tensor = T.from_matrix(l_dims, r_dims,
left_qims=l_qims, right_qims=r_qims,
left_dirs=l_dirs, right_dirs=r_dirs,)
assert((T == T_matrix).all())
T = T_tensor
test_internal_consistency(T)
assert((T == T_orig).all())
print('Done testing to and from matrix.')
if pars["test_diag"]:
for iter_num in range(pars["n_iters"]):
# Vectors to matrices
T = rtensor(n=1, invar=False)
T_np = T.to_ndarray()
T_diag = T.diag()
T_np_diag = np.diag(T_np)
T_np_diag = type(T).from_ndarray(T_np_diag, shape=T_diag.shape,
qhape=T_diag.qhape,
dirs=T_diag.dirs,
charge=T_diag.charge)
assert(T_np_diag.allclose(T_diag))
# Matrices to vectors
shp = rshape(n=2)
shp[1] = shp[0]
qhp = rqhape(shape=shp)
qhp[1] = qhp[0]
dirs = rdirs(shape=shp)
dirs[1] = -dirs[0]
T = rtensor(shape=shp, qhape=qhp, dirs=dirs)
T_np = T.to_ndarray()
T_diag = T.diag()
T_np_diag = np.diag(T_np)
T_np_diag = type(T).from_ndarray(T_np_diag, shape=T_diag.shape,
qhape=T_diag.qhape,
dirs=T_diag.dirs,
charge=T_diag.charge,
invar=False)
assert(T_np_diag.allclose(T_diag))
print('Done testing diag.')
if pars["test_trace"]:
for iter_num in range(pars["n_iters"]):
shp = rshape(nlow=2)
qhp = rqhape(shape=shp)
dirs = rdirs(shape=shp)
charge = rcharge()
i = np.random.randint(low=0, high=len(shp))
j = np.random.randint(low=0, high=len(shp))
while i==j:
j = np.random.randint(low=0, high=len(shp))
shp[j] = shp[i]
dirs[j] = -dirs[i]
qhp[j] = qhp[i]
T = rtensor(shape=shp, qhape=qhp, dirs=dirs, charge=charge)
T_np = T.to_ndarray()
tr = T.trace(axis1=i, axis2=j)
np_tr = np.trace(T_np, axis1=i, axis2=j)
test_internal_consistency(tr)
np_tr_tensor = type(T).from_ndarray(np_tr, shape=tr.shape,
qhape=tr.qhape, dirs=tr.dirs,
charge=tr.charge)
assert(np_tr_tensor.allclose(tr))
print('Done testing traces.')
if pars["test_multiply_diag"]:
for iter_num in range(pars["n_iters"]):
right = np.random.randint(low=0, high=2)
T = rtensor(nlow=1, chilow=1)
T_orig = T.copy()
i = np.random.randint(low=0, high=len(T.shape))
D_shape = [T.shape[i]]
D_qhape = None if T.qhape is None else [T.qhape[i]]
D_dirs = None if T.dirs is None else [T.dirs[i] * (1 - 2*right)]
D = rtensor(shape=D_shape, qhape=D_qhape, dirs=D_dirs,
invar=False, charge=0)
T_np = T.to_ndarray()
D_np = D.to_ndarray()
prod_np = np.tensordot(T_np, np.diag(D_np), (i,1-right))
perm = list(range(len(prod_np.shape)))
d = perm.pop(-1)
perm.insert(i, d)
prod_np = np.transpose(prod_np, perm)
direction = "right" if right else "left"
TD = T.multiply_diag(D, i, direction=direction)
assert((T == T_orig).all())
T = TD
test_internal_consistency(T)
assert(np.allclose(T.to_ndarray(), prod_np))
print('Done testing multiply_diag.')
if pars["test_product"]:
for iter_num in range(pars["n_iters"]):
shp1 = rshape(nlow=1)
n = np.random.randint(low=1, high=len(shp1)+1)
if n:
i_list = list(np.random.choice(len(shp1), size=n, replace=False))
else:
i_list = []
shp2 = rshape(nlow=n, chilow=1)
if n:
j_list = list(np.random.choice(len(shp2), size=n, replace=False))
else:
j_list = []
for k in range(n):
# A summation index should not have dimension 0
dim1 = shp1[i_list[k]]
if np.sum(dim1) < 1:
dim1 = rshape(n=1, chilow=1)[0]
shp1[i_list[k]] = dim1
shp2[j_list[k]] = dim1
qhp1 = rqhape(shp1)
qhp2 = rqhape(shp2)
if qhp1 is not None:
for k in range(n):
qhp2[j_list[k]] = qhp1[i_list[k]]
T1 = rtensor(shape=shp1, qhape=qhp1)
T1_orig = T1.copy()
if T.dirs is not None:
dirs2 = rdirs(shape=shp2)
for i,j in zip(i_list, j_list):
dirs2[j] = -T1.dirs[i]
else:
dirs2 = None
T2 = rtensor(shape=shp2, qhape=qhp2, dirs=dirs2)
T2_orig = T2.copy()
T1_np = T1.to_ndarray()
T2_np = T2.to_ndarray()
T = T1.dot(T2, (i_list, j_list))
assert((T1 == T1_orig).all())
assert((T2 == T2_orig).all())
test_internal_consistency(T)
i_list_compl = sorted(set(range(len(shp1))) - set(i_list))
j_list_compl = sorted(set(range(len(shp2))) - set(j_list))
product_shp = [shp1[i] for i in i_list_compl]\
+ [shp2[j] for j in j_list_compl]
if type(T) == Tensor:
product_shp = Tensor.flatten_shape(product_shp)
assert(T.shape == product_shp)
T_np = np.tensordot(T1_np, T2_np, (i_list, j_list))
assert(np.allclose(T_np, T.to_ndarray()))
# Products of non-invariant vectors.
n1 = np.random.randint(1,3)
T1 = rtensor(n=n1, chilow=1, invar=(n1!=1))
n2 = np.random.randint(1,3)
shp2 = rshape(n=n2, chilow=1)
qhp2 = rqhape(shape=shp2)
dirs2 = rdirs(shape=shp2)
c2 = rcharge()
shp2[0] = T1.shape[-1]
if T1.qhape is not None:
qhp2[0] = T1.qhape[-1]
dirs2[0] = -T1.dirs[-1]
T2 = rtensor(shape=shp2, qhape=qhp2, dirs=dirs2, charge=c2,
invar=(n2!=1))
T1_orig = T1.copy()
T2_orig = T2.copy()
test_internal_consistency(T1)
test_internal_consistency(T2)
T1_np = T1.to_ndarray()
T2_np = T2.to_ndarray()
T = T1.dot(T2, (n1-1, 0))
assert((T1 == T1_orig).all())
assert((T2 == T2_orig).all())
test_internal_consistency(T)
T_np = np.tensordot(T1_np, T2_np, (n1-1, 0))
assert(np.allclose(T_np, T.to_ndarray()))
print('Done testing products.')
if pars["test_svd"]:
for iter_num in range(pars["n_iters"]):
T = rtensor(nlow=2, chilow=1)
T_orig = T.copy()
T_np = T.to_ndarray()
n = np.random.randint(low=1, high=len(T.shape))
if n:
i_list = list(np.random.choice(len(T.shape), size=n, replace=False))
else:
i_list = []
i_list_compl = sorted(set(range(len(T.shape))) - set(i_list))
np.random.shuffle(i_list_compl)
# (Almost) no truncation.
U, S, V = T.svd(i_list, i_list_compl, eps=1e-15)
assert((T == T_orig).all())
test_internal_consistency(U)
test_internal_consistency(S)
test_internal_consistency(V)
US = U.dot(S.diag(), (len(i_list), 0))
USV = US.dot(V, (len(i_list), 0))
T = T.transpose(i_list+i_list_compl)
assert(USV.allclose(T))
U_np_svd, S_np_svd, V_np_svd = svd(T_np, i_list, i_list_compl, eps=1e-15)
U_svd_np, S_svd_np, V_svd_np = U.to_ndarray(), S.to_ndarray(), V.to_ndarray()
order = np.argsort(-S_svd_np)
S_svd_np = S_svd_np[order]
U_svd_np = U_svd_np[...,order]
V_svd_np = V_svd_np[order,...]
# abs is needed because of gauge freedom in SVD. We assume here
# that there are no degenerate singular values.
assert(np.allclose(np.abs(U_np_svd), np.abs(U_svd_np)))
assert(np.allclose(np.abs(S_np_svd), np.abs(S_svd_np)))
assert(np.allclose(np.abs(V_np_svd), np.abs(V_svd_np)))
# Truncation.
chi = np.random.randint(low=1, high=6)
chis = list(range(chi+1))
eps = 1e-5
U, S, V, rel_err = T_orig.svd(i_list, i_list_compl, chis=chis,
eps=eps, return_rel_err=True)
test_internal_consistency(U)
test_internal_consistency(S)
test_internal_consistency(V)
assert(rel_err<eps or sum(type(S).flatten_shape(S.shape)) == chi)
US = U.dot(S.diag(), (len(i_list), 0))
USV = US.dot(V, (len(i_list), 0))
err = (USV - T).norm()
T_norm = T_orig.norm()
if T_norm != 0:
true_rel_err = err/T_norm
else:
true_rel_err = 0
if rel_err > 1e-7 or true_rel_err > 1e-7:
# If this doesnt' hold we run into machine epsilon
# because of a square root.
assert(np.abs(rel_err - true_rel_err)/(rel_err+true_rel_err) < 1e-7)
else:
assert(USV.allclose(T))
U_np_svd, S_np_svd, V_np_svd, np_rel_err = svd(T_np, i_list, i_list_compl, chis=chis,
eps=eps, return_rel_err=True)
assert(np.allclose(rel_err, np_rel_err, atol=1e-7))
assert(np.allclose(-np.sort(-S.to_ndarray()), S_np_svd))
print('Done testing SVD.')
if pars["test_eig"]:
for iter_num in range(pars["n_iters"]):
n = np.random.randint(low=1, high=3)
shp = rshape(n=n*2, chilow=1, chihigh=4)
qhp = rqhape(shape=shp)
dirs = [1]*len(shp)
i_list = list(np.random.choice(len(shp), size=n, replace=False))
i_list_compl = sorted(set(range(len(shp))) - set(i_list))
np.random.shuffle(i_list_compl)
for i,j in zip(i_list, i_list_compl):
shp[j] = shp[i].copy()
qhp[j] = qhp[i].copy()
dirs[j] = -1
T = rtensor(shape=shp, qhape=qhp, dirs=dirs, charge=0)
T_orig = T.copy()
T_np = T.to_ndarray()
# No truncation, non-hermitian
S, U = T.eig(i_list, i_list_compl)
assert((T == T_orig).all())
test_internal_consistency(S)
test_internal_consistency(U)
S_np_eig, U_np_eig = eig(T_np, i_list, i_list_compl)
S_eig_np, U_eig_np = S.to_ndarray(), U.to_ndarray()
order = np.argsort(-S_eig_np)
S_eig_np = S_eig_np[order]
U_eig_np = U_eig_np[...,order]
order = np.argsort(-S_np_eig)
S_np_eig = S_np_eig[order]
U_np_eig = U_np_eig[...,order]
assert(np.allclose(S_np_eig, S_eig_np))
assert(np.allclose(np.abs(U_np_eig), np.abs(U_eig_np)))
# Truncation, non-hermitian
chi = np.random.randint(low=1, high=6)
chis = list(range(chi+1))
eps = 1e-5
S, U, rel_err = T.eig(i_list, i_list_compl, chis=chis, eps=eps,
return_rel_err=True)
assert((T == T_orig).all())
test_internal_consistency(S)
test_internal_consistency(U)
S_np_eig, U_np_eig, rel_err_np = eig(T_np, i_list, i_list_compl,
chis=chis, eps=eps,
return_rel_err=True)
S_eig_np, U_eig_np = S.to_ndarray(), U.to_ndarray()
order = np.argsort(-S_eig_np)
S_eig_np = S_eig_np[order]
U_eig_np = U_eig_np[...,order]
order = np.argsort(-S_np_eig)
S_np_eig = S_np_eig[order]
U_np_eig = U_np_eig[...,order]
assert(np.allclose(S_np_eig, S_eig_np))
assert(np.allclose(np.abs(U_np_eig), np.abs(U_eig_np)))
assert(np.allclose(rel_err, rel_err_np))
assert(rel_err<eps or sum(type(S).flatten_shape(S.shape)) == chi)
# No truncation, hermitian
T_scon_list = list(range(-len(T.shape), 0))
T_conj_scon_list = [i - 100 for i in T_scon_list]
for counter, i in enumerate(i_list_compl):
T_scon_list[i] = counter+1
T_conj_scon_list[i] = counter+1
T = scon((T, T.conjugate()), (T_scon_list, T_conj_scon_list))
T_orig = T.copy()
T_np = T.to_ndarray()
i_list = list(range(len(i_list_compl)))
i_list_compl = [len(i_list) + i for i in i_list]
S, U = T.eig(i_list, i_list_compl, hermitian=True)
assert((T == T_orig).all())
test_internal_consistency(S)
test_internal_consistency(U)
S_np_eig, U_np_eig = eig(T_np, i_list, i_list_compl,
hermitian=True)
S_eig_np, U_eig_np = S.to_ndarray(), U.to_ndarray()
order = np.argsort(-S_eig_np)
S_eig_np = S_eig_np[order]
U_eig_np = U_eig_np[...,order]
order = np.argsort(-S_np_eig)
S_np_eig = S_np_eig[order]
U_np_eig = U_np_eig[...,order]
assert(np.allclose(S_np_eig, S_eig_np))
assert(np.allclose(np.abs(U_np_eig), np.abs(U_eig_np)))
# Truncation, hermitian
chi = np.random.randint(low=1, high=6)
chis = list(range(chi+1))
eps = 1e-5
S, U, rel_err = T.eig(i_list, i_list_compl, chis=chis, eps=eps,
hermitian=True, return_rel_err=True)
assert((T == T_orig).all())
test_internal_consistency(S)
test_internal_consistency(U)
S_np_eig, U_np_eig, rel_err_np = eig(T_np, i_list, i_list_compl,
chis=chis, eps=eps,
hermitian=True,
return_rel_err=True)
S_eig_np, U_eig_np = S.to_ndarray(), U.to_ndarray()
order = np.argsort(-S_eig_np)
S_eig_np = S_eig_np[order]
U_eig_np = U_eig_np[...,order]
order = np.argsort(-S_np_eig)
S_np_eig = S_np_eig[order]
U_np_eig = U_np_eig[...,order]
assert(np.allclose(S_np_eig, S_eig_np))
assert(np.allclose(np.abs(U_np_eig), np.abs(U_eig_np)))
assert(np.allclose(rel_err, rel_err_np))
assert(rel_err<eps or sum(type(S).flatten_shape(S.shape)) == chi)
l = len(U.shape)
V_permutation = (l-1,) + tuple(range(l-1))
V = U.conjugate().transpose(V_permutation)
US = U.dot(S.diag(), (len(i_list), 0))
USV = US.dot(V, (len(i_list), 0))
err = (USV - T).norm()
T_norm = T_orig.norm()
if T_norm != 0:
true_rel_err = err/T_norm
else:
true_rel_err = 0
if rel_err > 1e-7 or true_rel_err > 1e-7:
# If this doesnt' hold we run into machine epsilon
# because of a square root.
assert(np.abs(rel_err - true_rel_err)/(rel_err+true_rel_err) < 1e-7)
else:
assert(USV.allclose(T))
print('Done testing eig.')
if pars["test_split"]:
for iter_num in range(pars["n_iters"]):
T = rtensor(nlow=2, chilow=1)
T_orig = T.copy()
n = np.random.randint(low=1, high=len(T.shape))
i_list = []
while len(i_list) < n:
i_list.append(np.random.randint(low=0, high=len(T.shape)))
i_list = list(set(i_list))
i_list_compl = sorted(set(range(len(T.shape))) - set(i_list))
np.random.shuffle(i_list)
np.random.shuffle(i_list_compl)
chi = np.random.randint(low=1, high=10)
eps = 10**(-1*np.random.randint(low=2, high=10))
svd_res = T.svd(i_list, i_list_compl, chis=chi, eps=eps)
assert((T == T_orig).all())
U, S, V = svd_res[0:3]
test_internal_consistency(U)
test_internal_consistency(S)
test_internal_consistency(V)
US = U.dot(S.sqrt().diag(), (len(i_list), 0))
SV = V.dot(S.sqrt().diag(), (0, 1))
perm = list(range(len(SV.shape)))
d = perm.pop(-1)
perm.insert(0, d)
SV = SV.transpose(perm)
split_res = T.split(i_list, i_list_compl, chis=chi, eps=eps, return_sings=True)
assert(US.allclose(split_res[0]))
assert(S.allclose(split_res[1]))
assert(SV.allclose(split_res[2]))
print('Done testing splitting tensors.')
if pars["test_miscellaneous"]:
for iter_num in range(pars["n_iters"]):
# Test norm
shp = rshape()
for dim in shp:
if all([d == 0 for d in dim]):
dim[0] = 1
T = rtensor(shape=shp)
T_np = T.to_ndarray()
T_norm = T.norm()
n = len(T.shape)
all_inds = tuple(range(n))
T_np_norm = np.sqrt(np.tensordot(T_np, T_np.conj(), (all_inds, all_inds)))
assert(np.allclose(T_norm, T_np_norm))
# Test min, max and average
shp = rshape()
for dim in shp:
if all([d == 0 for d in dim]):
dim[0] = 1
T = rtensor(shape=shp, cmplx=False)
T_np = T.to_ndarray()
T_max = T.max()
T_np_max = np.max(T_np)
assert(T_max == T_np_max)
shp = rshape()
for dim in shp:
if all([d == 0 for d in dim]):
dim[0] = 1
T = rtensor(shape=shp, cmplx=False)
T_np = T.to_ndarray()
T_min = T.min()
T_np_min = np.min(T_np)
assert(T_min == T_np_min)
shp = rshape()
for dim in shp:
if all([d == 0 for d in dim]):
dim[0] = 1
T = rtensor(shape=shp)
T_np = T.to_ndarray()
T_average = T.average()
T_np_average = np.average(T_np)
assert(np.allclose(T_average, T_np_average))
# Test expand_dim
T = rtensor()
T_orig = T.copy()
axis = np.random.randint(0, high=len(T.shape)+1)
T_np = T.to_ndarray()
T_expanded = T.expand_dims(axis)
assert((T == T_orig).all())
T = T_expanded
test_internal_consistency(T)
T_np = np.expand_dims(T_np, axis)
T_np_T = type(T).from_ndarray(T_np, shape=T.shape, qhape=T.qhape,
dirs=T.dirs, charge=T.charge)
test_internal_consistency(T_np_T)
assert(T.allclose(T_np_T))
# Test eye
dim = rshape(n=1)[0]
qim = rqhape(shape=[dim])[0]
T = cls.eye(dim, qim=qim)
T_np = np.eye(T.flatten_dim(dim))
T_np = type(T).from_ndarray(T_np, shape=T.shape, qhape=T.qhape,
dirs=T.dirs, charge=T.charge)
assert((T == T_np).all())
# Test flip_dir
T = rtensor(nlow=1)
T_orig = T.copy()
i = np.random.randint(low=0, high=len(T.shape))
T_flipped = T.flip_dir(i)
assert((T == T_orig).all())
test_internal_consistency(T_flipped)
T_flipped = T_flipped.flip_dir(i)
assert((T == T_flipped).all())
print('Done testing miscellaneous.')
if pars["test_expand_dims_product"]:
for iter_num in range(pars["n_iters"]):
T1 = rtensor()
T2 = rtensor()
axis1 = np.random.randint(0, high=len(T1.shape)+1)
axis2 = np.random.randint(0, high=len(T2.shape)+1)
T1_np = T1.to_ndarray()
T2_np = T2.to_ndarray()
T1 = T1.expand_dims(axis1, direction=1)
T2 = T2.expand_dims(axis2, direction=-1)
T1_np = np.expand_dims(T1_np, axis1)
T2_np = np.expand_dims(T2_np, axis2)
T = T1.dot(T2, (axis1, axis2))
test_internal_consistency(T)
T_np = np.tensordot(T1_np, T2_np, (axis1, axis2))
T_np_T = type(T).from_ndarray(T_np, shape=T.shape, qhape=T.qhape,
dirs=T.dirs, charge=T.charge)
test_internal_consistency(T_np_T)
assert(T.allclose(T_np_T))
print('Done testing expand_dims products.')
if pars["test_scon_svd_scon"]:
for iter_num in range(pars["n_iters"]):
# Create a random scon contraction
n_tensors = np.random.randint(low=1, high=4)
shapes = []
qhapes = []
dirss = []
charges = []
indices = set()
for i in range(n_tensors):
shp = rshape(nhigh=4, chilow=1)
shapes.append(shp)
qhapes.append(rqhape(shape=shp))
dirss.append(rdirs(shape=shp))
charges.append(rcharge())
for j in range(len(shp)):
indices.add((i,j))
scon_lists = []
index_numbers = set(range(-len(indices), 0))
for shp in shapes:
scon_list = []
for index in shp:
scon_list.append(index_numbers.pop())
scon_lists.append(scon_list)
n_contractions = np.random.randint(low=0, high=int(len(indices)/2)+1)
for counter in range(1, n_contractions+1):
t1, i1 = indices.pop()
t2, i2 = indices.pop()
shapes[t2][i2] = shapes[t1][i1]
qhapes[t2][i2] = qhapes[t1][i1]
dirss[t2][i2] = -dirss[t1][i1]
scon_lists[t1][i1] = counter
scon_lists[t2][i2] = counter
tensors = []
np_tensors = []
for shape, qhape, dirs, charge in zip(shapes, qhapes, dirss, charges):
tensor = rtensor(shape, qhape=qhape, dirs=dirs, charge=charge)
np_tensor = tensor.to_ndarray()
tensors.append(tensor)
np_tensors.append(np_tensor)
T = scon(tensors, scon_lists)
test_internal_consistency(T)
np_T = scon(np_tensors, scon_lists)
np_T = type(T).from_ndarray(np_T, shape=T.shape, qhape=T.qhape,
dirs=T.dirs, charge=T.charge)
assert(T.allclose(np_T))
if len(T.shape) > 1:
# SVD the result of the contraction
n_svd_inds = np.random.randint(low=1, high=len(T.shape))
if n_svd_inds:
i_list = list(np.random.choice(len(T.shape), size=n_svd_inds,
replace=False))
else:
i_list = []
i_list_compl = sorted(set(range(len(T.shape))) - set(i_list))
np.random.shuffle(i_list_compl)
U, S, V = T.svd(i_list, i_list_compl, eps=1e-15)
# scon U, S and V with S to get the norm_sq of S.
S_diag = S.diag().conjugate()
U = U.conjugate()
V = V.conjugate()
U_left_inds = [i+1 for i in i_list]
V_right_inds = [j+1 for j in i_list_compl]
norm_sq_scon = scon((T, U, S_diag, V),
(list(range(1, len(T.shape)+1)),
U_left_inds + [100],
[100,101],
[101] + V_right_inds))
norm_sq = S.norm_sq()
assert(np.allclose(norm_sq, norm_sq_scon.value()))
print('Done testing scon_svd_scon.')
| [
"numpy.trace",
"numpy.abs",
"numpy.sum",
"numpy.allclose",
"numpy.argsort",
"numpy.random.randint",
"numpy.diag",
"timer.Timer",
"warnings.simplefilter",
"numpy.transpose",
"numpy.max",
"custom_parser.parse_argv",
"tensors.ndarray_svd.svd",
"numpy.random.shuffle",
"tensors.ndarray_svd.ei... | [((429, 472), 'warnings.simplefilter', 'warnings.simplefilter', (['"""error"""', 'UserWarning'], {}), "('error', UserWarning)\n", (450, 472), False, 'import warnings\n'), ((481, 1195), 'custom_parser.parse_argv', 'parse_argv', (['sys.argv', "('test_to_and_from_ndarray', 'bool', True)", "('test_arithmetic_and_comparison', 'bool', True)", "('test_transposing', 'bool', True)", "('test_splitting_and_joining', 'bool', True)", "('test_to_and_from_matrix', 'bool', True)", "('test_diag', 'bool', True)", "('test_trace', 'bool', True)", "('test_multiply_diag', 'bool', True)", "('test_product', 'bool', True)", "('test_svd', 'bool', True)", "('test_eig', 'bool', True)", "('test_split', 'bool', True)", "('test_miscellaneous', 'bool', True)", "('test_expand_dims_product', 'bool', True)", "('test_scon_svd_scon', 'bool', True)", "('n_iters', 'int', 500)", "('classes', 'word_list', ['Tensor', 'TensorZ2', 'TensorU1', 'TensorZ3'])"], {}), "(sys.argv, ('test_to_and_from_ndarray', 'bool', True), (\n 'test_arithmetic_and_comparison', 'bool', True), ('test_transposing',\n 'bool', True), ('test_splitting_and_joining', 'bool', True), (\n 'test_to_and_from_matrix', 'bool', True), ('test_diag', 'bool', True),\n ('test_trace', 'bool', True), ('test_multiply_diag', 'bool', True), (\n 'test_product', 'bool', True), ('test_svd', 'bool', True), ('test_eig',\n 'bool', True), ('test_split', 'bool', True), ('test_miscellaneous',\n 'bool', True), ('test_expand_dims_product', 'bool', True), (\n 'test_scon_svd_scon', 'bool', True), ('n_iters', 'int', 500), (\n 'classes', 'word_list', ['Tensor', 'TensorZ2', 'TensorU1', 'TensorZ3']))\n", (491, 1195), False, 'from custom_parser import parse_argv\n'), ((1931, 1938), 'timer.Timer', 'Timer', ([], {}), '()\n', (1936, 1938), False, 'from timer import Timer\n'), ((3674, 3719), 'numpy.random.randint', 'np.random.randint', ([], {'low': '(0)', 'high': '(2)', 'size': 'length'}), '(low=0, high=2, size=length)\n', (3691, 3719), True, 'import numpy as np\n'), ((3808, 3840), 'numpy.random.randint', 'np.random.randint', ([], {'low': '(0)', 'high': '(4)'}), '(low=0, high=4)\n', (3825, 3840), True, 'import numpy as np\n'), ((2377, 2412), 'numpy.random.randint', 'np.random.randint', (['nlow'], {'high': 'nhigh'}), '(nlow, high=nhigh)\n', (2394, 2412), True, 'import numpy as np\n'), ((8019, 8042), 'numpy.random.shuffle', 'np.random.shuffle', (['perm'], {}), '(perm)\n', (8036, 8042), True, 'import numpy as np\n'), ((8225, 8251), 'numpy.all', 'np.all', (['(T_tr_np == T_np_tr)'], {}), '(T_tr_np == T_np_tr)\n', (8231, 8251), True, 'import numpy as np\n'), ((15108, 15121), 'numpy.diag', 'np.diag', (['T_np'], {}), '(T_np)\n', (15115, 15121), True, 'import numpy as np\n'), ((15809, 15822), 'numpy.diag', 'np.diag', (['T_np'], {}), '(T_np)\n', (15816, 15822), True, 'import numpy as np\n'), ((16900, 16932), 'numpy.trace', 'np.trace', (['T_np'], {'axis1': 'i', 'axis2': 'j'}), '(T_np, axis1=i, axis2=j)\n', (16908, 16932), True, 'import numpy as np\n'), ((17379, 17411), 'numpy.random.randint', 'np.random.randint', ([], {'low': '(0)', 'high': '(2)'}), '(low=0, high=2)\n', (17396, 17411), True, 'import numpy as np\n'), ((18117, 18144), 'numpy.transpose', 'np.transpose', (['prod_np', 'perm'], {}), '(prod_np, perm)\n', (18129, 18144), True, 'import numpy as np\n'), ((20512, 20556), 'numpy.tensordot', 'np.tensordot', (['T1_np', 'T2_np', '(i_list, j_list)'], {}), '(T1_np, T2_np, (i_list, j_list))\n', (20524, 20556), True, 'import numpy as np\n'), ((20678, 20701), 'numpy.random.randint', 'np.random.randint', (['(1)', '(3)'], {}), '(1, 3)\n', (20695, 20701), True, 'import numpy as np\n'), ((20775, 20798), 'numpy.random.randint', 'np.random.randint', (['(1)', '(3)'], {}), '(1, 3)\n', (20792, 20798), True, 'import numpy as np\n'), ((21609, 21648), 'numpy.tensordot', 'np.tensordot', (['T1_np', 'T2_np', '(n1 - 1, 0)'], {}), '(T1_np, T2_np, (n1 - 1, 0))\n', (21621, 21648), True, 'import numpy as np\n'), ((22217, 22248), 'numpy.random.shuffle', 'np.random.shuffle', (['i_list_compl'], {}), '(i_list_compl)\n', (22234, 22248), True, 'import numpy as np\n'), ((22738, 22780), 'tensors.ndarray_svd.svd', 'svd', (['T_np', 'i_list', 'i_list_compl'], {'eps': '(1e-15)'}), '(T_np, i_list, i_list_compl, eps=1e-15)\n', (22741, 22780), False, 'from tensors.ndarray_svd import svd, eig\n'), ((22892, 22913), 'numpy.argsort', 'np.argsort', (['(-S_svd_np)'], {}), '(-S_svd_np)\n', (22902, 22913), True, 'import numpy as np\n'), ((23424, 23456), 'numpy.random.randint', 'np.random.randint', ([], {'low': '(1)', 'high': '(6)'}), '(low=1, high=6)\n', (23441, 23456), True, 'import numpy as np\n'), ((24518, 24590), 'tensors.ndarray_svd.svd', 'svd', (['T_np', 'i_list', 'i_list_compl'], {'chis': 'chis', 'eps': 'eps', 'return_rel_err': '(True)'}), '(T_np, i_list, i_list_compl, chis=chis, eps=eps, return_rel_err=True)\n', (24521, 24590), False, 'from tensors.ndarray_svd import svd, eig\n'), ((24669, 24713), 'numpy.allclose', 'np.allclose', (['rel_err', 'np_rel_err'], {'atol': '(1e-07)'}), '(rel_err, np_rel_err, atol=1e-07)\n', (24680, 24713), True, 'import numpy as np\n'), ((24921, 24953), 'numpy.random.randint', 'np.random.randint', ([], {'low': '(1)', 'high': '(3)'}), '(low=1, high=3)\n', (24938, 24953), True, 'import numpy as np\n'), ((25234, 25265), 'numpy.random.shuffle', 'np.random.shuffle', (['i_list_compl'], {}), '(i_list_compl)\n', (25251, 25265), True, 'import numpy as np\n'), ((25801, 25832), 'tensors.ndarray_svd.eig', 'eig', (['T_np', 'i_list', 'i_list_compl'], {}), '(T_np, i_list, i_list_compl)\n', (25804, 25832), False, 'from tensors.ndarray_svd import svd, eig\n'), ((25918, 25939), 'numpy.argsort', 'np.argsort', (['(-S_eig_np)'], {}), '(-S_eig_np)\n', (25928, 25939), True, 'import numpy as np\n'), ((26042, 26063), 'numpy.argsort', 'np.argsort', (['(-S_np_eig)'], {}), '(-S_np_eig)\n', (26052, 26063), True, 'import numpy as np\n'), ((26165, 26196), 'numpy.allclose', 'np.allclose', (['S_np_eig', 'S_eig_np'], {}), '(S_np_eig, S_eig_np)\n', (26176, 26196), True, 'import numpy as np\n'), ((26325, 26357), 'numpy.random.randint', 'np.random.randint', ([], {'low': '(1)', 'high': '(6)'}), '(low=1, high=6)\n', (26342, 26357), True, 'import numpy as np\n'), ((26718, 26790), 'tensors.ndarray_svd.eig', 'eig', (['T_np', 'i_list', 'i_list_compl'], {'chis': 'chis', 'eps': 'eps', 'return_rel_err': '(True)'}), '(T_np, i_list, i_list_compl, chis=chis, eps=eps, return_rel_err=True)\n', (26721, 26790), False, 'from tensors.ndarray_svd import svd, eig\n'), ((26974, 26995), 'numpy.argsort', 'np.argsort', (['(-S_eig_np)'], {}), '(-S_eig_np)\n', (26984, 26995), True, 'import numpy as np\n'), ((27098, 27119), 'numpy.argsort', 'np.argsort', (['(-S_np_eig)'], {}), '(-S_np_eig)\n', (27108, 27119), True, 'import numpy as np\n'), ((27221, 27252), 'numpy.allclose', 'np.allclose', (['S_np_eig', 'S_eig_np'], {}), '(S_np_eig, S_eig_np)\n', (27232, 27252), True, 'import numpy as np\n'), ((27341, 27373), 'numpy.allclose', 'np.allclose', (['rel_err', 'rel_err_np'], {}), '(rel_err, rel_err_np)\n', (27352, 27373), True, 'import numpy as np\n'), ((28229, 28276), 'tensors.ndarray_svd.eig', 'eig', (['T_np', 'i_list', 'i_list_compl'], {'hermitian': '(True)'}), '(T_np, i_list, i_list_compl, hermitian=True)\n', (28232, 28276), False, 'from tensors.ndarray_svd import svd, eig\n'), ((28399, 28420), 'numpy.argsort', 'np.argsort', (['(-S_eig_np)'], {}), '(-S_eig_np)\n', (28409, 28420), True, 'import numpy as np\n'), ((28523, 28544), 'numpy.argsort', 'np.argsort', (['(-S_np_eig)'], {}), '(-S_np_eig)\n', (28533, 28544), True, 'import numpy as np\n'), ((28646, 28677), 'numpy.allclose', 'np.allclose', (['S_np_eig', 'S_eig_np'], {}), '(S_np_eig, S_eig_np)\n', (28657, 28677), True, 'import numpy as np\n'), ((28802, 28834), 'numpy.random.randint', 'np.random.randint', ([], {'low': '(1)', 'high': '(6)'}), '(low=1, high=6)\n', (28819, 28834), True, 'import numpy as np\n'), ((29211, 29303), 'tensors.ndarray_svd.eig', 'eig', (['T_np', 'i_list', 'i_list_compl'], {'chis': 'chis', 'eps': 'eps', 'hermitian': '(True)', 'return_rel_err': '(True)'}), '(T_np, i_list, i_list_compl, chis=chis, eps=eps, hermitian=True,\n return_rel_err=True)\n', (29214, 29303), False, 'from tensors.ndarray_svd import svd, eig\n'), ((29532, 29553), 'numpy.argsort', 'np.argsort', (['(-S_eig_np)'], {}), '(-S_eig_np)\n', (29542, 29553), True, 'import numpy as np\n'), ((29656, 29677), 'numpy.argsort', 'np.argsort', (['(-S_np_eig)'], {}), '(-S_np_eig)\n', (29666, 29677), True, 'import numpy as np\n'), ((29779, 29810), 'numpy.allclose', 'np.allclose', (['S_np_eig', 'S_eig_np'], {}), '(S_np_eig, S_eig_np)\n', (29790, 29810), True, 'import numpy as np\n'), ((29899, 29931), 'numpy.allclose', 'np.allclose', (['rel_err', 'rel_err_np'], {}), '(rel_err, rel_err_np)\n', (29910, 29931), True, 'import numpy as np\n'), ((31266, 31291), 'numpy.random.shuffle', 'np.random.shuffle', (['i_list'], {}), '(i_list)\n', (31283, 31291), True, 'import numpy as np\n'), ((31304, 31335), 'numpy.random.shuffle', 'np.random.shuffle', (['i_list_compl'], {}), '(i_list_compl)\n', (31321, 31335), True, 'import numpy as np\n'), ((31355, 31388), 'numpy.random.randint', 'np.random.randint', ([], {'low': '(1)', 'high': '(10)'}), '(low=1, high=10)\n', (31372, 31388), True, 'import numpy as np\n'), ((32757, 32787), 'numpy.allclose', 'np.allclose', (['T_norm', 'T_np_norm'], {}), '(T_norm, T_np_norm)\n', (32768, 32787), True, 'import numpy as np\n'), ((33096, 33108), 'numpy.max', 'np.max', (['T_np'], {}), '(T_np)\n', (33102, 33108), True, 'import numpy as np\n'), ((33414, 33426), 'numpy.min', 'np.min', (['T_np'], {}), '(T_np)\n', (33420, 33426), True, 'import numpy as np\n'), ((33743, 33759), 'numpy.average', 'np.average', (['T_np'], {}), '(T_np)\n', (33753, 33759), True, 'import numpy as np\n'), ((33779, 33815), 'numpy.allclose', 'np.allclose', (['T_average', 'T_np_average'], {}), '(T_average, T_np_average)\n', (33790, 33815), True, 'import numpy as np\n'), ((34171, 34197), 'numpy.expand_dims', 'np.expand_dims', (['T_np', 'axis'], {}), '(T_np, axis)\n', (34185, 34197), True, 'import numpy as np\n'), ((35679, 35707), 'numpy.expand_dims', 'np.expand_dims', (['T1_np', 'axis1'], {}), '(T1_np, axis1)\n', (35693, 35707), True, 'import numpy as np\n'), ((35728, 35756), 'numpy.expand_dims', 'np.expand_dims', (['T2_np', 'axis2'], {}), '(T2_np, axis2)\n', (35742, 35756), True, 'import numpy as np\n'), ((35860, 35902), 'numpy.tensordot', 'np.tensordot', (['T1_np', 'T2_np', '(axis1, axis2)'], {}), '(T1_np, T2_np, (axis1, axis2))\n', (35872, 35902), True, 'import numpy as np\n'), ((36346, 36378), 'numpy.random.randint', 'np.random.randint', ([], {'low': '(1)', 'high': '(4)'}), '(low=1, high=4)\n', (36363, 36378), True, 'import numpy as np\n'), ((37955, 37980), 'scon.scon', 'scon', (['tensors', 'scon_lists'], {}), '(tensors, scon_lists)\n', (37959, 37980), False, 'from scon import scon\n'), ((38041, 38069), 'scon.scon', 'scon', (['np_tensors', 'scon_lists'], {}), '(np_tensors, scon_lists)\n', (38045, 38069), False, 'from scon import scon\n'), ((2517, 2549), 'numpy.random.randint', 'np.random.randint', ([], {'low': '(1)', 'high': '(5)'}), '(low=1, high=5)\n', (2534, 2549), True, 'import numpy as np\n'), ((17957, 17970), 'numpy.diag', 'np.diag', (['D_np'], {}), '(D_np)\n', (17964, 17970), True, 'import numpy as np\n'), ((20416, 20449), 'tensors.tensor.Tensor.flatten_shape', 'Tensor.flatten_shape', (['product_shp'], {}), '(product_shp)\n', (20436, 20449), False, 'from tensors.tensor import Tensor\n'), ((23206, 23222), 'numpy.abs', 'np.abs', (['U_np_svd'], {}), '(U_np_svd)\n', (23212, 23222), True, 'import numpy as np\n'), ((23224, 23240), 'numpy.abs', 'np.abs', (['U_svd_np'], {}), '(U_svd_np)\n', (23230, 23240), True, 'import numpy as np\n'), ((23274, 23290), 'numpy.abs', 'np.abs', (['S_np_svd'], {}), '(S_np_svd)\n', (23280, 23290), True, 'import numpy as np\n'), ((23292, 23308), 'numpy.abs', 'np.abs', (['S_svd_np'], {}), '(S_svd_np)\n', (23298, 23308), True, 'import numpy as np\n'), ((23342, 23358), 'numpy.abs', 'np.abs', (['V_np_svd'], {}), '(V_np_svd)\n', (23348, 23358), True, 'import numpy as np\n'), ((23360, 23376), 'numpy.abs', 'np.abs', (['V_svd_np'], {}), '(V_svd_np)\n', (23366, 23376), True, 'import numpy as np\n'), ((26229, 26245), 'numpy.abs', 'np.abs', (['U_np_eig'], {}), '(U_np_eig)\n', (26235, 26245), True, 'import numpy as np\n'), ((26247, 26263), 'numpy.abs', 'np.abs', (['U_eig_np'], {}), '(U_eig_np)\n', (26253, 26263), True, 'import numpy as np\n'), ((27285, 27301), 'numpy.abs', 'np.abs', (['U_np_eig'], {}), '(U_np_eig)\n', (27291, 27301), True, 'import numpy as np\n'), ((27303, 27319), 'numpy.abs', 'np.abs', (['U_eig_np'], {}), '(U_eig_np)\n', (27309, 27319), True, 'import numpy as np\n'), ((28710, 28726), 'numpy.abs', 'np.abs', (['U_np_eig'], {}), '(U_np_eig)\n', (28716, 28726), True, 'import numpy as np\n'), ((28728, 28744), 'numpy.abs', 'np.abs', (['U_eig_np'], {}), '(U_eig_np)\n', (28734, 28744), True, 'import numpy as np\n'), ((29843, 29859), 'numpy.abs', 'np.abs', (['U_np_eig'], {}), '(U_np_eig)\n', (29849, 29859), True, 'import numpy as np\n'), ((29861, 29877), 'numpy.abs', 'np.abs', (['U_eig_np'], {}), '(U_eig_np)\n', (29867, 29877), True, 'import numpy as np\n'), ((38740, 38771), 'numpy.random.shuffle', 'np.random.shuffle', (['i_list_compl'], {}), '(i_list_compl)\n', (38757, 38771), True, 'import numpy as np\n'), ((19122, 19134), 'numpy.sum', 'np.sum', (['dim1'], {}), '(dim1)\n', (19128, 19134), True, 'import numpy as np\n'), ((31415, 31448), 'numpy.random.randint', 'np.random.randint', ([], {'low': '(2)', 'high': '(10)'}), '(low=2, high=10)\n', (31432, 31448), True, 'import numpy as np\n'), ((2727, 2761), 'numpy.random.randint', 'np.random.randint', (['(0)'], {'high': 'chihigh'}), '(0, high=chihigh)\n', (2744, 2761), True, 'import numpy as np\n'), ((24342, 24372), 'numpy.abs', 'np.abs', (['(rel_err - true_rel_err)'], {}), '(rel_err - true_rel_err)\n', (24348, 24372), True, 'import numpy as np\n'), ((30627, 30657), 'numpy.abs', 'np.abs', (['(rel_err - true_rel_err)'], {}), '(rel_err - true_rel_err)\n', (30633, 30657), 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.