code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 6 00:11:55 2020
@author: andreas
"""
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
from PlotScatter import hue_order
from Basefolder import basefolder
import pickle
import numpy as np
my_pal = {'FINDER_1D_loop':'#701ac0',\
'CAML_07VEJJ':'#eabe8e',\
'CAML_87B144':'#d67d1d',\
'FINDER_1D':'#af6eeb',\
'dbscan':'dimgrey',\
'OPTICS':'lightgrey'\
};
dict_algo_names_ = {"OPTICS":"OPTICS",
"dbscan":"DBSCAN",
"CAML_07VEJJ":"CAML (07VEJJ)",
"CAML_87B144":"CAML (87B144)",
"FINDER_1D_loop":"FINDER",
"FINDER_1D":"FINDER_1D (DBSCAN)"
};
base = basefolder+"/Results_Fig3/";
name_3mers = "Results_3mers";
name_4mers = "Results_4mers";
def PlotHistograms(axs,df,rightCol=False):
max_show = 10;
for i,algo in enumerate(['FINDER_1D_loop','CAML_07VEJJ','CAML_87B144']):
ax = axs[i];
mask2 = (df['algos'] == algo);
sns.histplot(data=df[mask2],x='subcl',palette=my_pal,ax=axs[i],discrete=True,shrink=0.8,color=my_pal[algo]);
ax.set_xlabel("")
ax.set_ylabel("")
ax.set_yticks([]);
ax.set_xticks([]);
ax.set_ylim(0,25);
ax.set_xlim(0,11);
# ax.axis('off');
ax.set_frame_on(False)
ax.plot([0,11],[0,0],'k')
#ax.axes.get_xaxis().set_visible(True)
if(rightCol):
ax.annotate(dict_algo_names_[algo],(10.5, 15),color=my_pal[algo],weight="bold",horizontalalignment='right');
if(rightCol):
axs[0].annotate("", xy=(4,25), xytext=(4,30),arrowprops=dict(arrowstyle="->"));
else:
axs[0].annotate("", xy=(3,15), xytext=(3,20),arrowprops=dict(arrowstyle="->"));
ax = axs[2];
ax.set_xticks(np.arange(max_show+1));
xlabs = [str(i) for i in np.arange(max_show+1)];
xlabs[-1] = ">= 10";
ax.set_xticklabels(xlabs)
ax.set_xlabel('Detected subclusters');
def PlotScatter(labels,XC,ax=[],filename=[]):
if(labels == []):
labels = -np.ones((len(XC),));
# Get correctly detected:
if(ax == []):
fig,ax = plt.subplots();
ax.scatter(x=XC[:,0],y=XC[:,1],marker='o',s=1,c='grey',alpha=0.1,edgecolor=None,linewidth=0);
ax.set_aspect('equal');
x_0 = 0;
y_0 = np.min(XC[:,1]) - 150;
ax.plot([x_0,x_0+500],[y_0,y_0],'k')
ax.annotate('$500nm$',(x_0+250,y_0+20),fontsize='large',ha='center');
ax.set_aspect(1);
ax.set_xticks([]);
ax.set_yticks([]);
ax.axis('off');
if(ax==[]):
plt.show();
if(not(filename == [])):
plt.savefig(filename)
gs_kw = dict(width_ratios=[1,1], height_ratios=[5,1,1,1],hspace=0.0,wspace=0.1);
fig,axs = plt.subplots(4,2,gridspec_kw=gs_kw,figsize=(12,12));
#****************************************************************
filename_pickle = base+name_3mers+".pickle";
all_data = []
infile = open(filename_pickle, "rb")
while 1:
try:
all_data.append(pickle.load(infile))
except (EOFError, pickle.UnpicklingError):
break
infile.close()
no_pts = all_data[0].Geometry.GetTypical_Number_of_points_templateClusters();
print("Typical number of points per 3mer: "+str(no_pts));
PlotScatter([],all_data[0].Geometry.XC,ax=axs[0,0]);
axs[0,0].set_title('3mers');
#****************************************************************
filename_pickle = base+name_4mers+".pickle";
all_data = []
infile = open(filename_pickle, "rb")
while 1:
try:
all_data.append(pickle.load(infile))
except (EOFError, pickle.UnpicklingError):
break
infile.close()
no_pts = all_data[0].Geometry.GetTypical_Number_of_points_templateClusters();
print("Typical number of points per 4mer: "+str(no_pts));
PlotScatter([],all_data[0].Geometry.XC,ax=axs[0,1]);
axs[0,1].set_title('4mers');
#****************************************************************
filename = name_3mers+"_subclusters0_0.txt";#"_corrected.txt";
df_3mers = pd.read_csv(base+filename);
ax = axs[1,0];
mask = df_3mers['subcl']>10;
df_3mers.loc[mask,'subcl'] = 10;
PlotHistograms(axs[1:,0],df_3mers);
#****************************************************************
#base = "/Users/andreas/Documents/NoiseRecognizer_Data/Results_2020_11_06_08_38_48_0/";
filename = name_4mers+"_subclusters0_0.txt";
df_4mers = pd.read_csv(base+filename);
mask = df_4mers['subcl']>10;
df_4mers.loc[mask,'subcl']= 10;
PlotHistograms(axs[1:,1],df_4mers,rightCol=True);
plt.savefig(base+"Fig3_Subclusters.pdf",bbox_inches="tight");
| [
"matplotlib.pyplot.savefig",
"pandas.read_csv",
"pickle.load",
"seaborn.histplot",
"numpy.min",
"matplotlib.pyplot.subplots",
"numpy.arange",
"matplotlib.pyplot.show"
] | [((2941, 2996), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(4)', '(2)'], {'gridspec_kw': 'gs_kw', 'figsize': '(12, 12)'}), '(4, 2, gridspec_kw=gs_kw, figsize=(12, 12))\n', (2953, 2996), True, 'import matplotlib.pyplot as plt\n'), ((4180, 4208), 'pandas.read_csv', 'pd.read_csv', (['(base + filename)'], {}), '(base + filename)\n', (4191, 4208), True, 'import pandas as pd\n'), ((4542, 4570), 'pandas.read_csv', 'pd.read_csv', (['(base + filename)'], {}), '(base + filename)\n', (4553, 4570), True, 'import pandas as pd\n'), ((4687, 4750), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(base + 'Fig3_Subclusters.pdf')"], {'bbox_inches': '"""tight"""'}), "(base + 'Fig3_Subclusters.pdf', bbox_inches='tight')\n", (4698, 4750), True, 'import matplotlib.pyplot as plt\n'), ((1130, 1248), 'seaborn.histplot', 'sns.histplot', ([], {'data': 'df[mask2]', 'x': '"""subcl"""', 'palette': 'my_pal', 'ax': 'axs[i]', 'discrete': '(True)', 'shrink': '(0.8)', 'color': 'my_pal[algo]'}), "(data=df[mask2], x='subcl', palette=my_pal, ax=axs[i], discrete\n =True, shrink=0.8, color=my_pal[algo])\n", (1142, 1248), True, 'import seaborn as sns\n'), ((1950, 1973), 'numpy.arange', 'np.arange', (['(max_show + 1)'], {}), '(max_show + 1)\n', (1959, 1973), True, 'import numpy as np\n'), ((2326, 2340), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (2338, 2340), True, 'import matplotlib.pyplot as plt\n'), ((2502, 2518), 'numpy.min', 'np.min', (['XC[:, 1]'], {}), '(XC[:, 1])\n', (2508, 2518), True, 'import numpy as np\n'), ((2767, 2777), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2775, 2777), True, 'import matplotlib.pyplot as plt\n'), ((2825, 2846), 'matplotlib.pyplot.savefig', 'plt.savefig', (['filename'], {}), '(filename)\n', (2836, 2846), True, 'import matplotlib.pyplot as plt\n'), ((2003, 2026), 'numpy.arange', 'np.arange', (['(max_show + 1)'], {}), '(max_show + 1)\n', (2012, 2026), True, 'import numpy as np\n'), ((3200, 3219), 'pickle.load', 'pickle.load', (['infile'], {}), '(infile)\n', (3211, 3219), False, 'import pickle\n'), ((3722, 3741), 'pickle.load', 'pickle.load', (['infile'], {}), '(infile)\n', (3733, 3741), False, 'import pickle\n')] |
# Code behind module for DCAL_Vegetation_Phenology.ipynb
################################
##
## Import Statments
##
################################
# Import standard Python modules
import sys
import datacube
import numpy as np
# Import DCAL utilities containing function definitions used generally across DCAL
sys.path.append('../DCAL_utils')
from dc_time import _n64_datetime_to_scalar, _scalar_to_n64_datetime
################################
##
## Function Definitions
##
################################
def TIMESAT_stats(dataarray, time_dim='time'):
"""
For a 1D array of values for a vegetation index - for which higher values tend to
indicate more vegetation - determine several statistics:
1. Beginning of Season (BOS): The time index of the beginning of the growing season.
(The downward inflection point before the maximum vegetation index value)
2. End of Season (EOS): The time index of the end of the growing season.
(The upward inflection point after the maximum vegetation index value)
3. Middle of Season (MOS): The time index of the maximum vegetation index value.
4. Length of Season (EOS-BOS): The time length of the season (index difference).
5. Base Value (BASE): The minimum vegetation index value.
6. Max Value (MAX): The maximum vegetation index value (the value at MOS).
7. Amplitude (AMP): The difference between BASE and MAX.
Parameters
----------
dataarray: xarray.DataArray
The 1D array of non-NaN values to determine the statistics for.
time_dim: string
The name of the time dimension in `dataarray`.
Returns
-------
stats: dict
A dictionary mapping statistic names to values.
"""
assert time_dim in dataarray.dims, "The parameter `time_dim` is \"{}\", " \
"but that dimension does not exist in the data.".format(time_dim)
stats = {}
data_np_arr = dataarray.values
time_np_arr = _n64_datetime_to_scalar(dataarray[time_dim].values)
data_inds = np.arange(len(data_np_arr))
# Obtain the first and second derivatives.
fst_deriv = np.gradient(data_np_arr, time_np_arr)
pos_fst_deriv = fst_deriv > 0
neg_fst_deriv = 0 > fst_deriv
snd_deriv = np.gradient(fst_deriv, time_np_arr)
pos_snd_deriv = snd_deriv > 0
neg_snd_deriv = 0 > snd_deriv
# Determine MOS.
# MOS is the index of the highest value.
idxmos = np.argmax(data_np_arr)
stats['Middle of Season'] = idxmos
data_inds_before_mos = data_inds[:idxmos]
data_inds_after_mos = data_inds[idxmos:]
# Determine BOS.
# BOS is the last negative inflection point before the MOS.
# If that point does not exist, choose the first positive
# first derivative point before the MOS. If that point does
# not exist, the BOS is the MOS (there is no point before the MOS in this case).
snd_deriv_neg_infl = np.concatenate((np.array([False]), neg_snd_deriv[1:] & ~neg_snd_deriv[:-1]))
if snd_deriv_neg_infl[data_inds_before_mos].sum() > 0:
idxbos = data_inds_before_mos[len(data_inds_before_mos) - 1 -
np.argmax(snd_deriv_neg_infl[data_inds_before_mos][::-1])]
elif pos_fst_deriv[data_inds_before_mos].sum() > 0:
idxbos = np.argmax(pos_fst_deriv[data_inds_before_mos])
else:
idxbos = idxmos
stats['Beginning of Season'] = idxbos
# Determine EOS.
# EOS is the first positive inflection point after the MOS.
# If that point does not exist, choose the last negative
# first derivative point after the MOS. If that point does
# not exist, the EOS is the MOS (there is no point after the MOS in this case).
snd_deriv_pos_infl = np.concatenate((np.array([False]), pos_snd_deriv[1:] & ~pos_snd_deriv[:-1]))
if snd_deriv_pos_infl[data_inds_after_mos].sum() > 0:
idxeos = data_inds_after_mos[np.argmax(snd_deriv_pos_infl[data_inds_after_mos])]
elif neg_fst_deriv[data_inds_after_mos].sum() > 0:
idxeos = np.argmax(neg_fst_deriv[data_inds_after_mos])
else:
idxeos = idxmos
stats['End of Season'] = idxeos
# Determine EOS-BOS.
stats['Length of Season'] = idxeos - idxbos
# Determine BASE.
stats['Base Value'] = data_np_arr.min()
# Determine MAX.
stats['Max Value'] = data_np_arr.max()
# Determine AMP.
stats['Amplitude'] = stats['Max Value'] - stats['Base Value']
return stats
| [
"dc_time._n64_datetime_to_scalar",
"numpy.argmax",
"numpy.array",
"numpy.gradient",
"sys.path.append"
] | [((316, 348), 'sys.path.append', 'sys.path.append', (['"""../DCAL_utils"""'], {}), "('../DCAL_utils')\n", (331, 348), False, 'import sys\n'), ((1961, 2012), 'dc_time._n64_datetime_to_scalar', '_n64_datetime_to_scalar', (['dataarray[time_dim].values'], {}), '(dataarray[time_dim].values)\n', (1984, 2012), False, 'from dc_time import _n64_datetime_to_scalar, _scalar_to_n64_datetime\n'), ((2125, 2162), 'numpy.gradient', 'np.gradient', (['data_np_arr', 'time_np_arr'], {}), '(data_np_arr, time_np_arr)\n', (2136, 2162), True, 'import numpy as np\n'), ((2247, 2282), 'numpy.gradient', 'np.gradient', (['fst_deriv', 'time_np_arr'], {}), '(fst_deriv, time_np_arr)\n', (2258, 2282), True, 'import numpy as np\n'), ((2435, 2457), 'numpy.argmax', 'np.argmax', (['data_np_arr'], {}), '(data_np_arr)\n', (2444, 2457), True, 'import numpy as np\n'), ((2935, 2952), 'numpy.array', 'np.array', (['[False]'], {}), '([False])\n', (2943, 2952), True, 'import numpy as np\n'), ((3296, 3342), 'numpy.argmax', 'np.argmax', (['pos_fst_deriv[data_inds_before_mos]'], {}), '(pos_fst_deriv[data_inds_before_mos])\n', (3305, 3342), True, 'import numpy as np\n'), ((3762, 3779), 'numpy.array', 'np.array', (['[False]'], {}), '([False])\n', (3770, 3779), True, 'import numpy as np\n'), ((3918, 3968), 'numpy.argmax', 'np.argmax', (['snd_deriv_pos_infl[data_inds_after_mos]'], {}), '(snd_deriv_pos_infl[data_inds_after_mos])\n', (3927, 3968), True, 'import numpy as np\n'), ((4042, 4087), 'numpy.argmax', 'np.argmax', (['neg_fst_deriv[data_inds_after_mos]'], {}), '(neg_fst_deriv[data_inds_after_mos])\n', (4051, 4087), True, 'import numpy as np\n'), ((3164, 3221), 'numpy.argmax', 'np.argmax', (['snd_deriv_neg_infl[data_inds_before_mos][::-1]'], {}), '(snd_deriv_neg_infl[data_inds_before_mos][::-1])\n', (3173, 3221), True, 'import numpy as np\n')] |
import numpy as np
import matplotlib.pyplot as plt
colors = ['gold', 'yellowgreen', 'c', 'royalblue', 'pink']
# randomly generate the number of occurrences of each color
occurrences = np.random.randint(10, size=len(colors)) + 1
# pmf of the distribution
sum = np.sum(occurrences)
pmf = occurrences / sum
print(pmf)
# plot pmf
bars = np.arange(len(colors))
fig, ax = plt.subplots(2)
ax[0].bar(bars, pmf, color=colors)
ax[0].set_xticks(bars)
ax[0].set_xticklabels(colors)
# plot cdf
cdf = np.cumsum(pmf)
ax[1].step(bars, cdf, where='mid')
ax[1].set_xticks(bars)
ax[1].set_xticklabels(colors)
print(cdf)
plt.show()
| [
"numpy.sum",
"numpy.cumsum",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.show"
] | [((262, 281), 'numpy.sum', 'np.sum', (['occurrences'], {}), '(occurrences)\n', (268, 281), True, 'import numpy as np\n'), ((370, 385), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)'], {}), '(2)\n', (382, 385), True, 'import matplotlib.pyplot as plt\n'), ((493, 507), 'numpy.cumsum', 'np.cumsum', (['pmf'], {}), '(pmf)\n', (502, 507), True, 'import numpy as np\n'), ((609, 619), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (617, 619), True, 'import matplotlib.pyplot as plt\n')] |
"""
Use the library to calculate stiffness matrices for Zysset-Curnier Model based orthotropic materials
and extract the engineering constants from the stiffness matrices.
"""
from collections import namedtuple
import numpy as np
import tenseng.tenseng.tenseng as t
cubic = namedtuple('CubicAnisotropic', ['E', 'nu', 'G'])
iso = namedtuple('Isotropic', ['E', 'nu'])
I = t.identity(2)
def C_iso(l_0, mu_0, k, rho=1):
"""Create an isotropic material and return the stiffness matrix"""
if not 0 <= rho <= 1:
raise ValueError("Invalid Density")
return np.asarray(t.to_matrix(l_0 * rho**k * t.dyad(I, I) + 2 * mu_0 * rho**k * t.double_tensor_product(I, I)))
def C_zysset(l_0, lp_0, mu_0, k, l, rho=1, M=np.eye(3)):
"""Create Zysset-Curnier model and return stiffness matrix"""
if np.trace(M) != 3:
raise ValueError("Invalid Fabric")
if not 0 <= rho <= 1:
raise ValueError("Invalid Density")
eval, evec = np.linalg.eig(M)
M = [t.dyad(t.Vector(*evec[i]), t.Vector(*evec[i])) for i in range(3)]
res = t.null(4)
for i in range(3):
res += (l_0 + 2 * mu_0) * rho ** k * eval[i] ** (2 * l) * t.dyad(M[i], M[i])
for i in range(3):
for j in range(3):
if i == j:
continue
res += lp_0 * rho**k * eval[i]**l * eval[j]**l * t.dyad(M[i], M[j])
for i in range(3):
for j in range(3):
if i == j:
continue
res += 2 * mu_0 * rho**k * eval[i]**l * eval[j]**l * t.double_tensor_product(M[i], M[j])
return np.asarray(t.to_matrix(res))
def cubic_to_constants(C):
"""Return Material constants E, nu and G for an cubic-anisotropic stiffness tensor"""
if C.shape != (6,6):
raise ValueError("Invalid Stiffness Matrix")
# Checks for isotropy / cubic-anisotropy
if not np.all(C * np.array(
[[0, 0, 0, 1, 1, 1], [0, 0, 0, 1, 1, 1], [0, 0, 0, 1, 1, 1], [1, 1, 1, 0, 1, 1], [1, 1, 1, 1, 0, 1],
[1, 1, 1, 1, 1, 0]]) == 0) or \
not np.isclose(C[0, 0], C[1, 1]) or \
not np.isclose(C[1, 1], C[2, 2]) or \
not np.isclose(C[3, 3], C[4, 4]) or \
not np.isclose(C[4, 4], C[5, 5]) or \
not np.isclose(C[0, 1], C[0, 2]) or \
not np.isclose(C[1, 2], C[0, 2]) or \
not np.isclose(C[1, 0], C[2, 0]) or \
not np.isclose(C[2, 1], C[2, 0]) or \
not np.isclose(C[0, 1], C[1, 0]):
raise ValueError("Matrix does not fulfill symmetry")
# Invert the stiffness tensor to elasticity tensor:
E = np.linalg.inv(C)
e = 1 / E[0,0] # The elastic modulus can directly be read
nu = -E[0,1] * e # the off-diagonal only contains the -nu/E terms
mu = 1 / E[3,3] # The shearmodulus can directly be read
return cubic(e, nu, mu)
def iso_to_constants(C):
"""Returns material constants E and nu for an isotropic material """
E, nu, G = cubic_to_constants(C)
if not np.isclose(E / (2*(1 + nu)), G):
raise ValueError("The Material is not isotropic!")
return iso(E, nu)
# Values are from Gross et al. (2013) Biomech Model Mechanobiol. DOI: 10.1007/s10237-012-0443-2
# Got them from Homogenization using KUBC and 12GPa nu=0.3 material
print("Isotropic Model for combined:")
C = C_iso(3429.0, 3536.0, 1.63)
print(C)
print(iso_to_constants(C))
print("Zysset-Curnier Model for combined (KUBC; 12GPa, 0.3):")
C = C_zysset(4982.4, 3518.5, 3470.7, 1.62, 1.10)
print(C)
print(cubic_to_constants(C))
print()
# Values from Panyasantisuk et al. (2015) J.Biomech.Eng. DOI: 10.1115/1.4028968
# Used PMUBC and 10GPa nu=0.3 material and compared with the paper above.
# NOTE: They scaled the material parameters from 12 to 10GPa for the comparison
# They compared to the femur set of Gross et al.
print("Zysset-Curnier for femur KUBC based scaled (10GPa, 0.3):")
print(cubic_to_constants(C_zysset(3841.04, 3076.34, 3115.17, 1.6, 0.99)))
print("Zysset-Curnier KUBC based (10GPa, 0.3):")
print(cubic_to_constants(C_zysset(3381.79, 2745.98, 2855.14, 1.55, 0.84)))
print("Zysset-Curnier KUBC based filtered:")
print(cubic_to_constants(C_zysset(3306.34, 2735.59, 2837.43, 1.55, 0.82)))
print()
print("Zysset-Curnier PMUBC based (10GPa, 0.3):")
print(cubic_to_constants(C_zysset(6250.22, 3768.00, 3446.81, 2.01, 1.20)))
print("Zysset-Curnier PMUBC based filtered:")
print(cubic_to_constants(C_zysset(5060.06, 3353.04, 3116.88, 1.91, 1.10)))
| [
"numpy.trace",
"numpy.eye",
"collections.namedtuple",
"numpy.isclose",
"numpy.linalg.eig",
"tenseng.tenseng.tenseng.to_matrix",
"tenseng.tenseng.tenseng.Vector",
"tenseng.tenseng.tenseng.double_tensor_product",
"tenseng.tenseng.tenseng.identity",
"tenseng.tenseng.tenseng.dyad",
"tenseng.tenseng.... | [((277, 325), 'collections.namedtuple', 'namedtuple', (['"""CubicAnisotropic"""', "['E', 'nu', 'G']"], {}), "('CubicAnisotropic', ['E', 'nu', 'G'])\n", (287, 325), False, 'from collections import namedtuple\n'), ((332, 368), 'collections.namedtuple', 'namedtuple', (['"""Isotropic"""', "['E', 'nu']"], {}), "('Isotropic', ['E', 'nu'])\n", (342, 368), False, 'from collections import namedtuple\n'), ((374, 387), 'tenseng.tenseng.tenseng.identity', 't.identity', (['(2)'], {}), '(2)\n', (384, 387), True, 'import tenseng.tenseng.tenseng as t\n'), ((726, 735), 'numpy.eye', 'np.eye', (['(3)'], {}), '(3)\n', (732, 735), True, 'import numpy as np\n'), ((959, 975), 'numpy.linalg.eig', 'np.linalg.eig', (['M'], {}), '(M)\n', (972, 975), True, 'import numpy as np\n'), ((1061, 1070), 'tenseng.tenseng.tenseng.null', 't.null', (['(4)'], {}), '(4)\n', (1067, 1070), True, 'import tenseng.tenseng.tenseng as t\n'), ((2602, 2618), 'numpy.linalg.inv', 'np.linalg.inv', (['C'], {}), '(C)\n', (2615, 2618), True, 'import numpy as np\n'), ((811, 822), 'numpy.trace', 'np.trace', (['M'], {}), '(M)\n', (819, 822), True, 'import numpy as np\n'), ((1579, 1595), 'tenseng.tenseng.tenseng.to_matrix', 't.to_matrix', (['res'], {}), '(res)\n', (1590, 1595), True, 'import tenseng.tenseng.tenseng as t\n'), ((2991, 3024), 'numpy.isclose', 'np.isclose', (['(E / (2 * (1 + nu)))', 'G'], {}), '(E / (2 * (1 + nu)), G)\n', (3001, 3024), True, 'import numpy as np\n'), ((992, 1010), 'tenseng.tenseng.tenseng.Vector', 't.Vector', (['*evec[i]'], {}), '(*evec[i])\n', (1000, 1010), True, 'import tenseng.tenseng.tenseng as t\n'), ((1012, 1030), 'tenseng.tenseng.tenseng.Vector', 't.Vector', (['*evec[i]'], {}), '(*evec[i])\n', (1020, 1030), True, 'import tenseng.tenseng.tenseng as t\n'), ((1160, 1178), 'tenseng.tenseng.tenseng.dyad', 't.dyad', (['M[i]', 'M[i]'], {}), '(M[i], M[i])\n', (1166, 1178), True, 'import tenseng.tenseng.tenseng as t\n'), ((2046, 2074), 'numpy.isclose', 'np.isclose', (['C[0, 0]', 'C[1, 1]'], {}), '(C[0, 0], C[1, 1])\n', (2056, 2074), True, 'import numpy as np\n'), ((2096, 2124), 'numpy.isclose', 'np.isclose', (['C[1, 1]', 'C[2, 2]'], {}), '(C[1, 1], C[2, 2])\n', (2106, 2124), True, 'import numpy as np\n'), ((2146, 2174), 'numpy.isclose', 'np.isclose', (['C[3, 3]', 'C[4, 4]'], {}), '(C[3, 3], C[4, 4])\n', (2156, 2174), True, 'import numpy as np\n'), ((2196, 2224), 'numpy.isclose', 'np.isclose', (['C[4, 4]', 'C[5, 5]'], {}), '(C[4, 4], C[5, 5])\n', (2206, 2224), True, 'import numpy as np\n'), ((2246, 2274), 'numpy.isclose', 'np.isclose', (['C[0, 1]', 'C[0, 2]'], {}), '(C[0, 1], C[0, 2])\n', (2256, 2274), True, 'import numpy as np\n'), ((2296, 2324), 'numpy.isclose', 'np.isclose', (['C[1, 2]', 'C[0, 2]'], {}), '(C[1, 2], C[0, 2])\n', (2306, 2324), True, 'import numpy as np\n'), ((2346, 2374), 'numpy.isclose', 'np.isclose', (['C[1, 0]', 'C[2, 0]'], {}), '(C[1, 0], C[2, 0])\n', (2356, 2374), True, 'import numpy as np\n'), ((2396, 2424), 'numpy.isclose', 'np.isclose', (['C[2, 1]', 'C[2, 0]'], {}), '(C[2, 1], C[2, 0])\n', (2406, 2424), True, 'import numpy as np\n'), ((2446, 2474), 'numpy.isclose', 'np.isclose', (['C[0, 1]', 'C[1, 0]'], {}), '(C[0, 1], C[1, 0])\n', (2456, 2474), True, 'import numpy as np\n'), ((1338, 1356), 'tenseng.tenseng.tenseng.dyad', 't.dyad', (['M[i]', 'M[j]'], {}), '(M[i], M[j])\n', (1344, 1356), True, 'import tenseng.tenseng.tenseng as t\n'), ((1520, 1555), 'tenseng.tenseng.tenseng.double_tensor_product', 't.double_tensor_product', (['M[i]', 'M[j]'], {}), '(M[i], M[j])\n', (1543, 1555), True, 'import tenseng.tenseng.tenseng as t\n'), ((612, 624), 'tenseng.tenseng.tenseng.dyad', 't.dyad', (['I', 'I'], {}), '(I, I)\n', (618, 624), True, 'import tenseng.tenseng.tenseng as t\n'), ((647, 676), 'tenseng.tenseng.tenseng.double_tensor_product', 't.double_tensor_product', (['I', 'I'], {}), '(I, I)\n', (670, 676), True, 'import tenseng.tenseng.tenseng as t\n'), ((1862, 1996), 'numpy.array', 'np.array', (['[[0, 0, 0, 1, 1, 1], [0, 0, 0, 1, 1, 1], [0, 0, 0, 1, 1, 1], [1, 1, 1, 0, 1,\n 1], [1, 1, 1, 1, 0, 1], [1, 1, 1, 1, 1, 0]]'], {}), '([[0, 0, 0, 1, 1, 1], [0, 0, 0, 1, 1, 1], [0, 0, 0, 1, 1, 1], [1, 1,\n 1, 0, 1, 1], [1, 1, 1, 1, 0, 1], [1, 1, 1, 1, 1, 0]])\n', (1870, 1996), True, 'import numpy as np\n')] |
from meas_exponential import mechanism_exponential_discrete
import numpy as np
def score_auction_price_discrete(x, candidates):
return candidates * (x[None] >= candidates[:, None]).sum(axis=1)
def release_dp_auction_price_via_de(x, candidate_prices, epsilon):
"""Release a price for a digital auction that maximizes revenue.
See Section 4.1, Theorem 9: http://kunaltalwar.org/papers/expmech.pdf
:param x: The maximum each buyer is willing to spend.
:param candidate_prices: potential price levels
:returns a price that nearly maximizes revenue"""
return mechanism_exponential_discrete(x, candidate_prices, epsilon,
scorer=score_auction_price_discrete,
sensitivity=max(candidate_prices))
def score_auction_constrained_price_discrete(x, candidate_pairs):
return np.array([
price * sum(x[product_id] >= price)
for price, product_id in candidate_pairs
])
def release_dp_auction_constrained_price_via_de(x, candidate_pairs, epsilon):
"""Release a price and product for a constrained pricing auction that maximizes revenue.
See Section 4.3, Theorem 12: http://kunaltalwar.org/papers/expmech.pdf
:param x: The maximum each buyer is willing to spend for each of k items.
:param candidate_prices: list of potential (price, product_id) pairs, where product id is a column index into `x`
:returns a (price, product_id) that nearly maximizes revenue"""
prices = map(lambda v: v[0], candidate_pairs)
return mechanism_exponential_discrete(x, candidate_pairs, epsilon,
scorer=score_auction_constrained_price_discrete,
sensitivity=max(prices))
def test_constrained_auction():
# amount that each of 100 individuals are willing to offer for each of 4 products
data = np.random.uniform(size=(1000, 4))
# each candidate is a price and offering pair
candidates = [(np.random.uniform(), np.random.randint(4)) for _ in range(100)]
ideal_price, ideal_product = release_dp_auction_constrained_price_via_de(data, candidates, epsilon=1.)
print(f"To maximize revenue, sell product {ideal_product} at {ideal_price}.")
def test_auction():
data = np.random.uniform(size=100)
candidates = np.random.uniform(size=5)
print(release_dp_auction_price_via_de(data, candidates, epsilon=1.))
# test_constrained_auction() | [
"numpy.random.randint",
"numpy.random.uniform"
] | [((1783, 1816), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': '(1000, 4)'}), '(size=(1000, 4))\n', (1800, 1816), True, 'import numpy as np\n'), ((2175, 2202), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': '(100)'}), '(size=100)\n', (2192, 2202), True, 'import numpy as np\n'), ((2220, 2245), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': '(5)'}), '(size=5)\n', (2237, 2245), True, 'import numpy as np\n'), ((1887, 1906), 'numpy.random.uniform', 'np.random.uniform', ([], {}), '()\n', (1904, 1906), True, 'import numpy as np\n'), ((1908, 1928), 'numpy.random.randint', 'np.random.randint', (['(4)'], {}), '(4)\n', (1925, 1928), True, 'import numpy as np\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2018 Brno University of Technology FIT
# Author: <NAME> <<EMAIL>>
# All Rights Reserved
import os
import re
import random
from os import listdir
from os.path import isfile, join
import fnmatch
import math
import numpy as np
import yaml
class Utils(object):
""" Class tools handles basic operations with files and directories.
"""
def __init__(self):
""" tools class constructor.
"""
return
@staticmethod
def list_directory_by_suffix(directory, suffix):
""" Return listed directory of files based on their suffix.
:param directory: directory to be listed
:type directory: str
:param suffix: suffix of files in directory
:type suffix: str
:returns: list of files specified byt suffix in directory
:rtype: list
>>> Utils.list_directory_by_suffix('../../tests/tools', '.test')
['empty1.test', 'empty2.test']
>>> Utils.list_directory_by_suffix('../../tests/tools_no_ex', '.test')
Traceback (most recent call last):
...
toolsException: [listDirectoryBySuffix] No directory found!
>>> Utils.list_directory_by_suffix('../../tests/tools', '.py')
[]
"""
abs_dir = os.path.abspath(directory)
try:
ofiles = [f for f in listdir(abs_dir) if isfile(join(abs_dir, f))]
except OSError:
raise ValueError('No directory named {} found!'.format(directory))
out = []
for file_in in ofiles:
if file_in.find(suffix) != -1:
out.append(file_in)
out.sort()
return out
@staticmethod
def list_directory(directory):
""" List directory.
:param directory: directory to be listed
:type directory: str
:returns: list with files in directory
:rtype: list
>>> Utils.list_directory('../../tests/tools')
['empty1.test', 'empty2.test', 'test', 'test.txt']
>>> Utils.list_directory('../../tests/tools_no_ex')
Traceback (most recent call last):
...
toolsException: [listDirectory] No directory found!
"""
directory = os.path.abspath(directory)
try:
out = [f for f in listdir(directory)]
except OSError:
raise ValueError('No directory found!')
out.sort()
return out
@staticmethod
def recursively_list_directory_by_suffix(directory, suffix):
""" Return recursively listed directory of files based on their suffix.
:param directory: directory to be listed
:type directory: str
:param suffix: suffix of files in directory
:type suffix: str
:returns: list of files specified by suffix in directory
:rtype: list
>>> Utils.recursively_list_directory_by_suffix( \
'../../tests/tools', '.test')
['empty1.test', 'empty2.test', 'test/empty.test']
>>> Utils.recursively_list_directory_by_suffix( \
'../../tests/tools_no_ex', '.test')
[]
"""
matches = []
for root, dirnames, filenames in os.walk(directory):
for filename in fnmatch.filter(filenames, '*' + suffix):
app = os.path.join(root, filename).replace(directory + '/', '')
matches.append(app)
matches.sort()
return matches
@staticmethod
def sed_in_file(input_file, regex1, regex2):
""" Replace in input file by regex.
:param input_file: input file
:type input_file: str
:param regex1: regular expression 1
:type regex1: str
:param regex2: regular expression 2
:type regex2: str
"""
with open(input_file, 'r') as sources:
lines = sources.readlines()
with open(input_file, 'w') as sources:
for line in lines:
sources.write(re.sub(regex1, regex2, line))
@staticmethod
def remove_lines_in_file_by_indexes(input_file, lines_indexes):
""" Remove specified lines in file.
:param input_file: input file name
:type input_file: str
:param lines_indexes: list with lines
:type lines_indexes: list
"""
with open(input_file, 'r') as sources:
lines = sources.readlines()
with open(input_file, 'w') as sources:
for i in range(len(lines)):
if i not in lines_indexes:
sources.write(lines[i])
@staticmethod
def get_method(instance, method):
""" Get method pointer.
:param instance: input object
:type instance: object
:param method: name of method
:type method: str
:returns: pointer to method
:rtype: method
"""
try:
attr = getattr(instance, method)
except AttributeError:
raise ValueError('Unknown class method!')
return attr
@staticmethod
def configure_instance(instance, input_list):
""" Configures instance base on methods list.
:param instance: reference to class instance
:type instance: object
:param input_list: input list with name of class members
:type input_list: list
:returns: configured instance
:rtype: object
"""
for line in input_list:
variable = line[:line.rfind('=')]
value = line[line.rfind('=') + 1:]
method_callback = Utils.get_method(instance, 'Set' + variable)
method_callback(value)
return instance
@staticmethod
def sort(scores, col=None):
""" Sort scores list where score is in n-th-1 column.
:param scores: scores list to be sorted
:type scores: list
:param col: index of column
:type col: int
:returns: sorted scores list
:rtype: list
>>> Utils.sort([['f1', 'f2', 10.0], \
['f3', 'f4', -10.0], \
['f5', 'f6', 9.58]], col=2)
[['f3', 'f4', -10.0], ['f5', 'f6', 9.58], ['f1', 'f2', 10.0]]
>>> Utils.sort([4.59, 8.8, 6.9, -10001.478])
[-10001.478, 4.59, 6.9, 8.8]
"""
if col is None:
return sorted(scores, key=float)
else:
return sorted(scores, key=lambda x: x[col])
@staticmethod
def reverse_sort(scores, col=None):
""" Reversively sort scores list where score is in n-th column.
:param scores: scores list to be sorted
:type scores: list
:param col: number of columns
:type col: int
:returns: reversively sorted scores list
:rtype: list
>>> Utils.reverse_sort([['f1', 'f2', 10.0], \
['f3', 'f4', -10.0], \
['f5', 'f6', 9.58]], col=2)
[['f1', 'f2', 10.0], ['f5', 'f6', 9.58], ['f3', 'f4', -10.0]]
>>> Utils.reverse_sort([4.59, 8.8, 6.9, -10001.478])
[8.8, 6.9, 4.59, -10001.478]
"""
if col is None:
return sorted(scores, key=float, reverse=True)
else:
return sorted(scores, key=lambda x: x[col], reverse=True)
@staticmethod
def get_nth_col(in_list, col):
""" Extract n-th-1 columns from list.
:param in_list: input list
:type in_list: list
:param col: column
:type col: int
:returns: list only with one column
:rtype: list
>>> Utils.get_nth_col([['1', '2'], ['3', '4'], ['5', '6']], col=1)
['2', '4', '6']
>>> Utils.get_nth_col([['1', '2'], ['3', '4'], ['5', '6']], col=42)
Traceback (most recent call last):
...
toolsException: [getNthCol] Column out of range!
"""
try:
out = [row[col] for row in in_list]
except IndexError:
raise ValueError('Column out of range!')
return out
@staticmethod
def find_in_dictionary(in_dict, value):
""" Find value in directory whose items are lists and return key.
:param in_dict: dictionary to search in
:type in_dict: dict
:param value: value to find
:type value: any
:returns: dictionary key
:rtype: any
>>> Utils.find_in_dictionary({ 0 : [42], 1 : [88], 2 : [69]}, 69)
2
>>> Utils.find_in_dictionary(dict(), 69)
Traceback (most recent call last):
...
toolsException: [findInDictionary] Value not found!
"""
for key in in_dict:
if value in in_dict[key]:
return key
raise ValueError('Value not found!')
@staticmethod
def get_scores(scores, key):
""" Get scores from scores list by key.
:param scores: input scores list
:type scores: list
:param key: key to find
:type key: list
:returns: score if key is present in score, None otherwise
:rtype: float
>>> Utils.get_scores([['f1', 'f2', 10.1], ['f3', 'f4', 20.1], \
['f5', 'f6', 30.1]], ['f6', 'f5'])
30.1
"""
if len(key) != 2:
raise ValueError('Unexpected key!')
if len(scores[0]) != 3:
raise ValueError('Invalid input list!')
for score in scores:
a = score[0]
b = score[1]
if (key[0] == a and key[1] == b) or (key[0] == b and key[1] == a):
return score[2]
return None
@staticmethod
def get_line_from_file(line_num, infile):
""" Get specified line from file.
:param line_num: number of line
:type line_num: int
:param infile: file name
:type infile: str
:returns: specified line, None otherwise
:rtype: str
>>> Utils.get_line_from_file(3, '../../tests/tools/test.txt')
'c\\n'
>>> Utils.get_line_from_file(10, '../../tests/tools/test.txt')
Traceback (most recent call last):
...
toolsException: [getLineFromFile] Line number not found!
"""
with open(infile) as fp:
for i, line in enumerate(fp):
if i == line_num - 1:
return line
raise ValueError('Line number {} not found in file.'.format(line_num, infile))
@staticmethod
def list2dict(input_list):
""" Create dictionary from list in format [key1, key2, score].
:param input_list: list to process
:type input_list: list
:returns: preprocessed dictionary
:rtype: dict
>>> Utils.list2dict([['f1', 'f2', 10.1], ['f3', 'f4', 20.1], \
['f5', 'f6', 30.1], ['f1', 'f3', 40.1]])
{'f1 f2': 10.1, 'f5 f6': 30.1, 'f3 f4': 20.1, 'f1 f3': 40.1}
>>> Utils.list2dict([['f1', 'f2', 10.1], ['f3', 'f4']])
Traceback (most recent call last):
...
toolsException: [list2Dict] Invalid format of input list!
"""
dictionary = dict()
for item in input_list:
if len(item) != 3:
raise ValueError('Invalid format of input list!')
tmp_list = [item[0], item[1]]
tmp_list.sort()
dictionary[tmp_list[0] + ' ' + tmp_list[1]] = item[2]
return dictionary
@staticmethod
def merge_dicts(*dict_args):
""" Merge dictionaries into single one.
:param dict_args: input dictionaries
:type dict_args: dict array
:returns: merged dictionaries into single one
:rtype: dict
>>> Utils.merge_dicts( \
{'f1 f2': 10.1, 'f5 f6': 30.1, 'f1 f3': 40.1}, {'f6 f2': 50.1})
{'f1 f2': 10.1, 'f5 f6': 30.1, 'f6 f2': 50.1, 'f1 f3': 40.1}
"""
result = {}
for dictionary in dict_args:
result.update(dictionary)
return result
@staticmethod
def save_object(obj, path):
""" Saves object to disk.
:param obj: reference to object
:type obj: any
:param path: path to file
:type path: str
"""
np.save(path, obj)
@staticmethod
def load_object(path):
""" Loads object from disk.
:param path: path to file
:type path: str
"""
np.load(path)
@staticmethod
def common_prefix(m):
""" Given a list of pathnames, returns the longest prefix."
:param m: input list
:type m: list
:returns: longest prefix in list
:rtype: str
"""
if not m:
return ''
s1 = min(m)
s2 = max(m)
for i, c in enumerate(s1):
if c != s2[i]:
return s1[:i]
return s1
@staticmethod
def root_name(d):
""" Return a root directory by name.
:param d: directory name
:type d: str
:returns: root directory name
:rtype d: str
"""
pass
@staticmethod
def read_config(config_path):
""" Read config in yaml format.
Args:
config_path (str): path to config file
Returns:
"""
with open(config_path, 'r') as ymlfile:
return yaml.load(ymlfile)
@staticmethod
def l2_norm(ivecs):
""" Perform L2 normalization.
Args:
ivecs (np.array): input i-vector
Returns:
np.array: normalized i-vectors
"""
ret_ivecs = ivecs.copy()
ret_ivecs /= np.sqrt((ret_ivecs ** 2).sum(axis=1)[:, np.newaxis])
return ret_ivecs
@staticmethod
def cos_sim(v1, v2):
"""
Args:
v1 (np.array): first vector
v2 (np.array): second vector
Returns:
"""
sumxx, sumxy, sumyy = 0, 0, 0
for i in range(len(v1)):
x = v1[i]
y = v2[i]
sumxx += x * x
sumyy += y * y
sumxy += x * y
return sumxy / math.sqrt(sumxx * sumyy)
@staticmethod
def partition(large_list, n_sublists, shuffle=False):
"""Partition a list ``l`` into ``n`` sublists."""
return np.array_split(large_list, n_sublists)
if __name__ == "__main__":
import doctest
doctest.testmod()
| [
"os.listdir",
"os.walk",
"math.sqrt",
"yaml.load",
"os.path.join",
"numpy.array_split",
"doctest.testmod",
"fnmatch.filter",
"os.path.abspath",
"re.sub",
"numpy.load",
"numpy.save"
] | [((14989, 15006), 'doctest.testmod', 'doctest.testmod', ([], {}), '()\n', (15004, 15006), False, 'import doctest\n'), ((1368, 1394), 'os.path.abspath', 'os.path.abspath', (['directory'], {}), '(directory)\n', (1383, 1394), False, 'import os\n'), ((2349, 2375), 'os.path.abspath', 'os.path.abspath', (['directory'], {}), '(directory)\n', (2364, 2375), False, 'import os\n'), ((3358, 3376), 'os.walk', 'os.walk', (['directory'], {}), '(directory)\n', (3365, 3376), False, 'import os\n'), ((12815, 12833), 'numpy.save', 'np.save', (['path', 'obj'], {}), '(path, obj)\n', (12822, 12833), True, 'import numpy as np\n'), ((13003, 13016), 'numpy.load', 'np.load', (['path'], {}), '(path)\n', (13010, 13016), True, 'import numpy as np\n'), ((14898, 14936), 'numpy.array_split', 'np.array_split', (['large_list', 'n_sublists'], {}), '(large_list, n_sublists)\n', (14912, 14936), True, 'import numpy as np\n'), ((3406, 3445), 'fnmatch.filter', 'fnmatch.filter', (['filenames', "('*' + suffix)"], {}), "(filenames, '*' + suffix)\n", (3420, 3445), False, 'import fnmatch\n'), ((13956, 13974), 'yaml.load', 'yaml.load', (['ymlfile'], {}), '(ymlfile)\n', (13965, 13974), False, 'import yaml\n'), ((14723, 14747), 'math.sqrt', 'math.sqrt', (['(sumxx * sumyy)'], {}), '(sumxx * sumyy)\n', (14732, 14747), False, 'import math\n'), ((1441, 1457), 'os.listdir', 'listdir', (['abs_dir'], {}), '(abs_dir)\n', (1448, 1457), False, 'from os import listdir\n'), ((2419, 2437), 'os.listdir', 'listdir', (['directory'], {}), '(directory)\n', (2426, 2437), False, 'from os import listdir\n'), ((4161, 4189), 're.sub', 're.sub', (['regex1', 'regex2', 'line'], {}), '(regex1, regex2, line)\n', (4167, 4189), False, 'import re\n'), ((1468, 1484), 'os.path.join', 'join', (['abs_dir', 'f'], {}), '(abs_dir, f)\n', (1472, 1484), False, 'from os.path import isfile, join\n'), ((3469, 3497), 'os.path.join', 'os.path.join', (['root', 'filename'], {}), '(root, filename)\n', (3481, 3497), False, 'import os\n')] |
import numpy as np
from mcfa import utils
np.random.seed(42)
def test_latent_factor_rotation(D=15, J=10, noise=0.05):
# Generate fake factors.
A = np.random.uniform(-1, 1, size=(D, J))
# Randomly flip them.
true_signs = np.sign(np.random.uniform(-1, 1, size=J)).astype(int)
# Add a little noise to the signs
m = np.random.normal(true_signs, noise, J)
# Add a little bias.
b = np.random.normal(0, noise, J)
A_prime = m * A + b
# Re-order them.
true_indices = np.random.choice(J, J, replace=False)
A_prime = A_prime[:, true_indices]
R = utils.rotation_matrix(A_prime, A)
# Check order.
nonzero = (R != 0)
_, inferred_indices = np.where(nonzero)
# Check flips.
assert np.alltrue(true_indices == inferred_indices)
inferred_signs = R.T[nonzero.T]
assert np.alltrue(true_signs == inferred_signs)
def test_latent_factor_rotation_many_times(N=10, D=15, J=10, noise=0.05):
for i in range(N):
test_latent_factor_rotation(D=D, J=J, noise=noise)
| [
"numpy.random.normal",
"mcfa.utils.rotation_matrix",
"numpy.alltrue",
"numpy.random.choice",
"numpy.where",
"numpy.random.seed",
"numpy.random.uniform"
] | [((47, 65), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (61, 65), True, 'import numpy as np\n'), ((163, 200), 'numpy.random.uniform', 'np.random.uniform', (['(-1)', '(1)'], {'size': '(D, J)'}), '(-1, 1, size=(D, J))\n', (180, 200), True, 'import numpy as np\n'), ((346, 384), 'numpy.random.normal', 'np.random.normal', (['true_signs', 'noise', 'J'], {}), '(true_signs, noise, J)\n', (362, 384), True, 'import numpy as np\n'), ((419, 448), 'numpy.random.normal', 'np.random.normal', (['(0)', 'noise', 'J'], {}), '(0, noise, J)\n', (435, 448), True, 'import numpy as np\n'), ((515, 552), 'numpy.random.choice', 'np.random.choice', (['J', 'J'], {'replace': '(False)'}), '(J, J, replace=False)\n', (531, 552), True, 'import numpy as np\n'), ((601, 634), 'mcfa.utils.rotation_matrix', 'utils.rotation_matrix', (['A_prime', 'A'], {}), '(A_prime, A)\n', (622, 634), False, 'from mcfa import utils\n'), ((704, 721), 'numpy.where', 'np.where', (['nonzero'], {}), '(nonzero)\n', (712, 721), True, 'import numpy as np\n'), ((753, 797), 'numpy.alltrue', 'np.alltrue', (['(true_indices == inferred_indices)'], {}), '(true_indices == inferred_indices)\n', (763, 797), True, 'import numpy as np\n'), ((846, 886), 'numpy.alltrue', 'np.alltrue', (['(true_signs == inferred_signs)'], {}), '(true_signs == inferred_signs)\n', (856, 886), True, 'import numpy as np\n'), ((253, 285), 'numpy.random.uniform', 'np.random.uniform', (['(-1)', '(1)'], {'size': 'J'}), '(-1, 1, size=J)\n', (270, 285), True, 'import numpy as np\n')] |
#!/usr/bin/env python3
import os
import numpy as np
import astropy.io.fits as fits
from stella.catalog.base import _str_to_float
inputfile = os.path.join(os.getenv('ASTRO_DATA'), 'catalog/I/239/hip_main.dat')
types = [
('HIP', np.int32),
('RAdeg', np.float64),
('DEdeg', np.float64),
('Vmag', np.float32),
('Plx', np.float32),
('e_Plx', np.float32),
('pmRA', np.float32),
('pmDE', np.float32),
('e_pmRA', np.float32),
('e_pmDE', np.float32),
('BTmag', np.float32),
('e_BTmag',np.float32),
('VTmag', np.float32),
('e_VTmag',np.float32),
('B-V', np.float32),
('e_B-V', np.float32),
('r_B-V', 'S1'),
('V-I', np.float32),
('e_V-I', np.float32),
('r_V-I', 'S1'),
('Hpmag', np.float32),
('e_Hpmag',np.float32),
('Hpscat', np.float32),
('o_Hpmag',np.int16),
#('CCDM', 'S10'),
#('HD', np.int32),
#('BD', 'S10'),
#('CoD', 'S10'),
('SpType', 'S12'),
('r_SpType','S1'),
]
tmp = list(zip(*types))
record = np.dtype({'names':tmp[0],'formats':tmp[1]})
fill_item = np.array((0, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN,
np.NaN, np.NaN, np.NaN, np.NaN, np.NaN,
np.NaN, np.NaN, np.NaN, np.NaN, np.NaN,
'', np.NaN, np.NaN, '', np.NaN, np.NaN, np.NaN,
-32768, '',''),dtype=record)
data = {}
infile = open(inputfile)
for row in infile:
hip = int(row[8:14])
rah = int(row[17:19])
ram = int(row[20:22])
ras = float(row[23:28])
radeg = (rah + ram/60. + ras/3600.)*15.
ded = abs(int(row[30:32]))
dem = int(row[33:35])
des = float(row[36:40])
dedeg = ded + dem/60. + des/3600.
if row[29]=='-':
dedeg = -dedeg
vmag = _str_to_float(row[41:46], np.NaN)
plx = _str_to_float(row[79:86], np.NaN)
e_plx = _str_to_float(row[119:125], np.NaN)
pmRA = _str_to_float(row[87:95], np.NaN)
pmDE = _str_to_float(row[96:104], np.NaN)
e_pmRA = _str_to_float(row[126:132], np.NaN)
e_pmDE = _str_to_float(row[133:139], np.NaN)
BTmag = _str_to_float(row[217:223], np.NaN)
VTmag = _str_to_float(row[230:236], np.NaN)
e_BTmag = _str_to_float(row[224:229], np.NaN)
e_VTmag = _str_to_float(row[237:242], np.NaN)
BV = _str_to_float(row[245:251], np.NaN)
e_BV = _str_to_float(row[252:257], np.NaN)
r_BV = row[258].strip()
VI = _str_to_float(row[260:264], np.NaN)
e_VI = _str_to_float(row[265:269], np.NaN)
r_VI = row[270].strip()
Hpmag = _str_to_float(row[274:281], np.NaN)
e_Hpmag = _str_to_float(row[282:288], np.NaN)
Hpscat = _str_to_float(row[289:294], np.NaN)
if row[295:298].strip()=='':
o_Hpmag = 0
else:
o_Hpmag = int(row[295:298])
if not np.isnan(pmRA):
pm_ra = pmRA*1e-3/3600. # convert pm_RA from mas/yr to degree/yr
#radeg += (2000.0-1991.25)*pm_ra/math.cos(dedeg/180.*math.pi)
if not np.isnan(pmDE):
pm_de = pmDE*1e-3/3600. # convert pm_Dec from mas/yr to degree/yr
#dedeg += (2000.0-1991.25)*pm_de
SpType = row[435:447].strip()
r_SpType = row[448].strip()
item = np.array((hip, radeg, dedeg, vmag, plx, e_plx,
pmRA, pmDE, e_pmRA, e_pmDE,
BTmag, e_BTmag, VTmag, e_VTmag,
BV, e_BV, r_BV, VI, e_VI, r_VI,
Hpmag, e_Hpmag, Hpscat, o_Hpmag,
#CCDM, HD, BD, CoD,
SpType, r_SpType,
),dtype=record)
if hip in data:
print('Error: Duplicate Records for HIP', hip)
data[hip] = item
infile.close()
newdata = []
for hip in range(1, max(data.keys())+1):
if hip in data:
newdata.append(data[hip])
else:
newdata.append(fill_item)
newdata = np.array(newdata, dtype=record)
pri_hdu = fits.PrimaryHDU()
tbl_hdu = fits.BinTableHDU(newdata)
hdu_lst = fits.HDUList([pri_hdu,tbl_hdu])
outputfile='HIP.fits'
if os.path.exists(outputfile):
os.remove(outputfile)
hdu_lst.writeto(outputfile)
| [
"os.path.exists",
"astropy.io.fits.HDUList",
"astropy.io.fits.PrimaryHDU",
"os.getenv",
"astropy.io.fits.BinTableHDU",
"numpy.array",
"stella.catalog.base._str_to_float",
"numpy.isnan",
"numpy.dtype",
"os.remove"
] | [((1185, 1231), 'numpy.dtype', 'np.dtype', (["{'names': tmp[0], 'formats': tmp[1]}"], {}), "({'names': tmp[0], 'formats': tmp[1]})\n", (1193, 1231), True, 'import numpy as np\n'), ((1242, 1462), 'numpy.array', 'np.array', (["(0, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN,\n np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, '', np.NaN, np.NaN, '',\n np.NaN, np.NaN, np.NaN, -32768, '', '')"], {'dtype': 'record'}), "((0, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN,\n np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, '', np.NaN, np.\n NaN, '', np.NaN, np.NaN, np.NaN, -32768, '', ''), dtype=record)\n", (1250, 1462), True, 'import numpy as np\n'), ((4044, 4075), 'numpy.array', 'np.array', (['newdata'], {'dtype': 'record'}), '(newdata, dtype=record)\n', (4052, 4075), True, 'import numpy as np\n'), ((4087, 4104), 'astropy.io.fits.PrimaryHDU', 'fits.PrimaryHDU', ([], {}), '()\n', (4102, 4104), True, 'import astropy.io.fits as fits\n'), ((4115, 4140), 'astropy.io.fits.BinTableHDU', 'fits.BinTableHDU', (['newdata'], {}), '(newdata)\n', (4131, 4140), True, 'import astropy.io.fits as fits\n'), ((4151, 4183), 'astropy.io.fits.HDUList', 'fits.HDUList', (['[pri_hdu, tbl_hdu]'], {}), '([pri_hdu, tbl_hdu])\n', (4163, 4183), True, 'import astropy.io.fits as fits\n'), ((4209, 4235), 'os.path.exists', 'os.path.exists', (['outputfile'], {}), '(outputfile)\n', (4223, 4235), False, 'import os\n'), ((155, 178), 'os.getenv', 'os.getenv', (['"""ASTRO_DATA"""'], {}), "('ASTRO_DATA')\n", (164, 178), False, 'import os\n'), ((1943, 1976), 'stella.catalog.base._str_to_float', '_str_to_float', (['row[41:46]', 'np.NaN'], {}), '(row[41:46], np.NaN)\n', (1956, 1976), False, 'from stella.catalog.base import _str_to_float\n'), ((1992, 2025), 'stella.catalog.base._str_to_float', '_str_to_float', (['row[79:86]', 'np.NaN'], {}), '(row[79:86], np.NaN)\n', (2005, 2025), False, 'from stella.catalog.base import _str_to_float\n'), ((2041, 2076), 'stella.catalog.base._str_to_float', '_str_to_float', (['row[119:125]', 'np.NaN'], {}), '(row[119:125], np.NaN)\n', (2054, 2076), False, 'from stella.catalog.base import _str_to_float\n'), ((2092, 2125), 'stella.catalog.base._str_to_float', '_str_to_float', (['row[87:95]', 'np.NaN'], {}), '(row[87:95], np.NaN)\n', (2105, 2125), False, 'from stella.catalog.base import _str_to_float\n'), ((2141, 2175), 'stella.catalog.base._str_to_float', '_str_to_float', (['row[96:104]', 'np.NaN'], {}), '(row[96:104], np.NaN)\n', (2154, 2175), False, 'from stella.catalog.base import _str_to_float\n'), ((2191, 2226), 'stella.catalog.base._str_to_float', '_str_to_float', (['row[126:132]', 'np.NaN'], {}), '(row[126:132], np.NaN)\n', (2204, 2226), False, 'from stella.catalog.base import _str_to_float\n'), ((2242, 2277), 'stella.catalog.base._str_to_float', '_str_to_float', (['row[133:139]', 'np.NaN'], {}), '(row[133:139], np.NaN)\n', (2255, 2277), False, 'from stella.catalog.base import _str_to_float\n'), ((2293, 2328), 'stella.catalog.base._str_to_float', '_str_to_float', (['row[217:223]', 'np.NaN'], {}), '(row[217:223], np.NaN)\n', (2306, 2328), False, 'from stella.catalog.base import _str_to_float\n'), ((2344, 2379), 'stella.catalog.base._str_to_float', '_str_to_float', (['row[230:236]', 'np.NaN'], {}), '(row[230:236], np.NaN)\n', (2357, 2379), False, 'from stella.catalog.base import _str_to_float\n'), ((2395, 2430), 'stella.catalog.base._str_to_float', '_str_to_float', (['row[224:229]', 'np.NaN'], {}), '(row[224:229], np.NaN)\n', (2408, 2430), False, 'from stella.catalog.base import _str_to_float\n'), ((2446, 2481), 'stella.catalog.base._str_to_float', '_str_to_float', (['row[237:242]', 'np.NaN'], {}), '(row[237:242], np.NaN)\n', (2459, 2481), False, 'from stella.catalog.base import _str_to_float\n'), ((2497, 2532), 'stella.catalog.base._str_to_float', '_str_to_float', (['row[245:251]', 'np.NaN'], {}), '(row[245:251], np.NaN)\n', (2510, 2532), False, 'from stella.catalog.base import _str_to_float\n'), ((2548, 2583), 'stella.catalog.base._str_to_float', '_str_to_float', (['row[252:257]', 'np.NaN'], {}), '(row[252:257], np.NaN)\n', (2561, 2583), False, 'from stella.catalog.base import _str_to_float\n'), ((2631, 2666), 'stella.catalog.base._str_to_float', '_str_to_float', (['row[260:264]', 'np.NaN'], {}), '(row[260:264], np.NaN)\n', (2644, 2666), False, 'from stella.catalog.base import _str_to_float\n'), ((2682, 2717), 'stella.catalog.base._str_to_float', '_str_to_float', (['row[265:269]', 'np.NaN'], {}), '(row[265:269], np.NaN)\n', (2695, 2717), False, 'from stella.catalog.base import _str_to_float\n'), ((2765, 2800), 'stella.catalog.base._str_to_float', '_str_to_float', (['row[274:281]', 'np.NaN'], {}), '(row[274:281], np.NaN)\n', (2778, 2800), False, 'from stella.catalog.base import _str_to_float\n'), ((2816, 2851), 'stella.catalog.base._str_to_float', '_str_to_float', (['row[282:288]', 'np.NaN'], {}), '(row[282:288], np.NaN)\n', (2829, 2851), False, 'from stella.catalog.base import _str_to_float\n'), ((2867, 2902), 'stella.catalog.base._str_to_float', '_str_to_float', (['row[289:294]', 'np.NaN'], {}), '(row[289:294], np.NaN)\n', (2880, 2902), False, 'from stella.catalog.base import _str_to_float\n'), ((3398, 3610), 'numpy.array', 'np.array', (['(hip, radeg, dedeg, vmag, plx, e_plx, pmRA, pmDE, e_pmRA, e_pmDE, BTmag,\n e_BTmag, VTmag, e_VTmag, BV, e_BV, r_BV, VI, e_VI, r_VI, Hpmag, e_Hpmag,\n Hpscat, o_Hpmag, SpType, r_SpType)'], {'dtype': 'record'}), '((hip, radeg, dedeg, vmag, plx, e_plx, pmRA, pmDE, e_pmRA, e_pmDE,\n BTmag, e_BTmag, VTmag, e_VTmag, BV, e_BV, r_BV, VI, e_VI, r_VI, Hpmag,\n e_Hpmag, Hpscat, o_Hpmag, SpType, r_SpType), dtype=record)\n', (3406, 3610), True, 'import numpy as np\n'), ((4241, 4262), 'os.remove', 'os.remove', (['outputfile'], {}), '(outputfile)\n', (4250, 4262), False, 'import os\n'), ((3014, 3028), 'numpy.isnan', 'np.isnan', (['pmRA'], {}), '(pmRA)\n', (3022, 3028), True, 'import numpy as np\n'), ((3186, 3200), 'numpy.isnan', 'np.isnan', (['pmDE'], {}), '(pmDE)\n', (3194, 3200), True, 'import numpy as np\n')] |
import astropy.units as u
from astropy.coordinates import EarthLocation,SkyCoord
from pytz import timezone
import numpy as np
from collections import Sequence
import matplotlib.pyplot as plt
from matplotlib import dates
from astroplan import Observer
from astroplan import FixedTarget
from datetime import datetime, timedelta
from bs4 import BeautifulSoup as bs
import re
class ATCA_sched:
'''
ATCA_sched(files)
Read ATCA schedules from html file(s) - compatible for v2.20 ATCA observing portal
params:
---------
files (str or list): file(s) to be read
example:
---------
sched = ATCA_sched(['./test/Week1.html', './test/Week2.html'])
attributes:
---------
timezone: timezone for the schedules
schedules: A dictionary to store all schedules information - the structure of the dictionary is organized as followed
keys: date;
values: a list consists of projects/blocks in that day, for a single block - [(time_start, time_end), project_name, available]
'''
def __init__(self, files):
### Attribute scheds - store all scheds information
self.schedules = {}
if isinstance(files, str):
self._read_single_file(files)
else:
for file in files:
self._read_single_file(file)
def _read_single_file(self, filename):
'''
Function to read a single html file to self.schedules
'''
with open(filename, "r", encoding='utf-8') as f:
text = f.read()
webcontent = bs(text, 'lxml')
portal_timezone = webcontent.find_all('button', attrs={'class':"fc-timeZone-button fc-button fc-button-primary"})[0].text
self.timezone = portal_timezone.split(':')[1].strip()
fc_head = webcontent.find_all('thead', attrs={'class':'fc-head'})[0]
fc_body = webcontent.find_all('div', attrs={'class':'fc-content-skeleton'})[0]
html_date = self._get_portal_dates(fc_head)
portal_scheds = self._get_portal_scheds(fc_body)
if len(html_date) != len(portal_scheds):
print(f'{filename} table head and body do not match!')
return None
for date, sched_day in zip(html_date, portal_scheds):
self.schedules[date] = self._get_portal_sched_day(sched_day)
def _get_portal_dates(self, fc_head):
'''
get dates from html files (table head)
'''
all_ths = fc_head.find_all('th') # all_ths[0] is about format
dates = [tag['data-date'] for tag in all_ths[1:]]
return dates
def _floathour_to_time(self, float_hour):
'''
covert a float number to hour:minute format (e.g.: 1.5 -> 01:30)
'''
return '{:0>2}:{:0>2.0f}'.format(int(float_hour), (float_hour - int(float_hour))*60)
def _get_time_from_style(self, fc_tag, hour_height=26.4):
'''
get block starting and ending time from html tag
Notes:
In the html file, each hour represents 26.4 pixels
'''
pattern = re.compile(r'top: (.*)px; bottom: (.*)px;')
px_start, px_end = pattern.findall(fc_tag['style'])[0]
block_start = self._floathour_to_time(float(px_start)/hour_height)
block_end = self._floathour_to_time(-float(px_end)/hour_height)
return block_start, block_end
def _get_portal_sched_day(self, fc_day):
'''
Get the schedule for one day
'''
formatted_sched = []
fc_scheds = fc_day.find_all('div')
for sched in fc_scheds:
block_time = self._get_time_from_style(sched)
block_disc = sched.text
block_avai = True if 'Green' in block_disc else False
formatted_sched.append([block_time, block_disc, block_avai])
return formatted_sched
def _get_portal_scheds(self, fc_body):
'''
get all raw html schedules from table body
'''
portal_raw_days = fc_body.find_all('td')[1:]
return [raw_day.find_all('div', attrs={'class':"fc-bgevent-container"})[0] for raw_day in portal_raw_days]
class ATCA_obs:
'''
ATCA_obs(targets, tzinfo='Australia/Sydney', portal_htmls=[])
Help with schedule the observation
params:
--------
targets (FixTarget or list): a single FixTarget or a list of FixTarget Objects
tzinfo (str): The timezone of the observer (check `pytz.all_timezones` for all acceptable timezones)
portal_htmls (list): If provided, load the ATCA schedule from the webpages. an empty list by default
example:
--------
import astropy.units as u
from astroplan import FixedTarget
from astropy.coordinates import SkyCoord
from datetime import datetime, timedelta
portal_htmls = ['./test/Week1.html', './test/Week2.html']
target = [FixedTarget(name='src1', coord=SkyCoord(233.3333,-66.6666,unit=u.deg)),
FixedTarget(name='src2', coord=SkyCoord(66.6666,-23.3333,unit=u.deg))]
t = datetime.fromisoformat('2020-10-28')
obs = ATCA_obs(target, tzinfo='Australia/Sydney', portal_htmls=portal_htmls)
fig, ax = obs.plot_target_altitude_with_schedule(t, duration=timedelta(days=10), dateformat='%D-%H:%M')
fig, ax = obs.plot_single_observability_heatmap(t, days=7, target_index=0)
attributes:
--------
targets: a list of FixedTarget objects need to be observed
calibrator: a list of FixedTarget objects
observer: an Observer object for ATCA
utcoffset: a timedelta object shows the offset between the timezone of the observer and UTC
tzinfo: timezone for the observer
portal_sched: the formatted schedule from portal_htmls - created from ATCA_sched.schedules
portal_utcoffset: a timedelta object shows the offset between the timezone of the ATCA schedule and UTC
portal_tz: ATCA portal timezone
functions:
--------
plot_target_altitude: plot targets altitude vs time
plot_target_altitude_with_schedule: plot targets altitude vs time, with green time shaded in green
plot_single_observability_heatmap: plot observability for a single source in a heatmap
'''
def __init__(self, targets, tzinfo='Australia/Sydney', portal_htmls=[]):
### target and calibrators
if not isinstance(targets, Sequence):
targets = [targets]
self.targets = targets
self.calibrator = [FixedTarget(name='1934-638', coord=SkyCoord('19h39m25.026s -63d42m45.63s')),
FixedTarget(name='0823-500', coord=SkyCoord('08h25m26.869s -50d10m38.49s'))]
### observer
ATCA_loc = (149.5501388*u.deg,-30.3128846*u.deg,237*u.m)
location = EarthLocation.from_geodetic(*ATCA_loc)
self.observer = Observer(name='ATCA',
location=location,
timezone=timezone('Australia/Sydney'))
time_now = datetime.now(timezone(tzinfo))
self.utcoffset = time_now.utcoffset()
self.tzinfo = tzinfo
if len(portal_htmls) == 0:
self.portal_tz = None
self.portal_sched = None
else:
atca_scheds = ATCA_sched(portal_htmls)
self.portal_tz = atca_scheds.timezone
self.portal_sched = atca_scheds.schedules
### portal utcoffset
portal_now = datetime.now(timezone(self.portal_tz))
self.portal_utcoffset = portal_now.utcoffset()
def plot_target_altitude(self, start_time, duration=timedelta(days=1), horizon=12, dateformat='%H:%M', **style_kwargs):
'''
plot_target_altitude(start_time, duration=timedelta(days=1), horizon=12, dateformat='%H:%M', **style_kwargs)
plot targets altitude vs time
params:
--------
start_time (datetime.datetime): the time to start the plot
duration (datetime.timedelta): the length of the plot, 1 day by default
horizon (int or float): telescope horizon in degree, 12 by default
dateformat (str): time label formatting, "%H:%M" by default
style_kwargs: arguments passed to matplotlib.pyplot.plot_date()
returns:
--------
fig, ax
'''
### plot style
if style_kwargs is None:
style_kwargs = {}
style_kwargs = dict(style_kwargs)
style_kwargs.setdefault('linestyle', '-')
style_kwargs.setdefault('linewidth', 2)
style_kwargs.setdefault('fmt', '-')
### convert time to series of time
time_num = (duration.days + 1)*1000 + 1
time_series = start_time + np.linspace(0,1,time_num)*duration
### covert times to UTC to calculate the alt/az
time_utcs = time_series - self.utcoffset
fig = plt.figure(figsize=(8*duration.total_seconds()/(24*3600), 6))
ax = fig.add_subplot(111)
for target in self.targets:
alts = self.observer.altaz(time_utcs, target).alt.value
if target.name:
ax.plot_date(time_series, alts, label=target.name, **style_kwargs)
else:
ax.plot_date(time_series, alts, **style_kwargs)
for calibrator in self.calibrator:
alts = self.observer.altaz(time_utcs, calibrator).alt.value
if calibrator.name == '1934-638':
ax.plot_date(time_series, alts, label=calibrator.name, fmt='black', lw=3, ls=':')
else:
ax.plot_date(time_series, alts, label=calibrator.name, fmt='black', lw=1, ls=':')
ax.axhline(y=horizon, color='red', ls=':', lw=2)
date_formatter = dates.DateFormatter(dateformat)
ax.xaxis.set_major_formatter(date_formatter)
plt.setp(ax.get_xticklabels(), rotation=30, ha='right')
ax.set_xlim(dates.date2num(time_series[0]), dates.date2num(time_series[-1]))
ax.set_ylim(0,90)
ax.legend()
ax.set_xlabel(f'TIME FROM {start_time.year}-{start_time.month}-{start_time.day} [{self.tzinfo}]')
return fig, ax
def plot_target_altitude_with_schedule(self, start_time, duration=timedelta(days=1), horizon=12, dateformat='%H:%M', **style_kwargs):
'''
plot_target_altitude_with_schedule(start_time, duration=timedelta(days=1), horizon=12, dateformat='%H:%M', **style_kwargs)
plot targets altitude vs time, with green time shaded in green
params:
--------
start_time (datetime.datetime): the time to start the plot
duration (datetime.timedelta): the length of the plot, 1 day by default
horizon (int or float): telescope horizon in degree, 12 by default
dateformat (str): time label formatting, "%H:%M" by default
style_kwargs: arguments passed to matplotlib.pyplot.plot_date()
returns:
--------
fig, ax
'''
if not self.portal_sched:
return self.plot_target_altitude(start_time, duration, horizon, dateformat, **style_kwargs)
fig, ax = self.plot_target_altitude(start_time, duration, horizon, dateformat, **style_kwargs)
### convert time to series of time
time_num = (duration.days + 1)*1000 + 1
time_series = start_time + np.linspace(0,1,time_num)*duration
### read schedules
for obs_day in self.portal_sched:
for project_row in self.portal_sched[obs_day]:
if project_row[-1]:
block_start = datetime.fromisoformat(obs_day) + timedelta(hours=float(project_row[0][0].split(':')[0]),
minutes=float(project_row[0][0].split(':')[1]))
block_start = block_start + self.utcoffset - self.portal_utcoffset
block_end = datetime.fromisoformat(obs_day) + timedelta(hours=float(project_row[0][1].split(':')[0]),
minutes=float(project_row[0][1].split(':')[1]))
block_end = block_end + self.utcoffset - self.portal_utcoffset
ax.axvspan(xmin=dates.date2num(block_start), xmax=dates.date2num(block_end),
color='green', alpha=0.1)
ax.set_xlim(dates.date2num(time_series[0]), dates.date2num(time_series[-1]))
return fig, ax
def _greentime_bool(self, time):
'''
_greentime_bool(time)
check if time is in during the green time slot
params:
--------
time (datetime.datetime): the time to be checked
returns:
--------
None if there is no schedule file for that day; True if it is in the green time slot; False if not
'''
if not self.portal_sched:
return None
### transfer time to portal timezone
time = time - self.utcoffset + self.portal_utcoffset
time_date = f'{time.year}-{time.month:0>2}-{time.day:0>2}'
if time_date not in self.portal_sched:
return None
for project in self.portal_sched[time_date]:
project_start = datetime.fromisoformat(time_date) + timedelta(hours=float(project[0][0].split(':')[0]),
minutes=float(project[0][0].split(':')[1]))
project_end = datetime.fromisoformat(time_date) + timedelta(hours=float(project[0][1].split(':')[0]),
minutes=float(project[0][1].split(':')[1]))
if time >= project_start and time < project_end:
if project[-1]:
return True
return False
return None
def plot_single_observability_heatmap(self, start_time, days=7, target_index=0, horizon=12):
'''
plot_single_observability_heatmap(start_time, days=7, target_index=0, horizon=12)
plot observability for a single source in a heatmap - we consider two factors: one is green time constrain, the other is altitude constrain
params:
--------
start_time (datetime.datetime): time to start the plot. MAKE SURE start at 00:00 or there will be a bug
days (int): number of days to plot, 7 by default
target_index (int): index of the target of interest - specify which target to plot
horizon (int or float): telescope horizon in degree, 12 by default
returns:
--------
fig, ax
'''
fig = plt.figure(figsize=(16,2*int(days)))
for day in range(days):
observability = np.zeros((2,48))
ax = fig.add_subplot(int(days),1,day+1)
day_time_start = start_time + timedelta(days=day)
for i in range(48):
block_time = day_time_start + timedelta(minutes=30) * i
block_time_utc = block_time - self.utcoffset
target_alt = self.observer.altaz(block_time_utc, self.targets[target_index]).alt.value
if target_alt < horizon:
observability[0][i] = 0
else:
observability[0][i] = 1
is_green_time = self._greentime_bool(block_time)
if is_green_time == None:
observability[1][i] = np.nan
else:
observability[1][i] = float(is_green_time)
extent = [-0.5, 47.5, -0.5, 1.5]
ax.imshow(observability, extent=extent, origin='lower')
ax.set_yticks(range(0, 2))
ax.set_xticks(range(0, 48,2))
ax.set_yticklabels(['Altitude Constrain','Greentime Constrain'])
ax.set_xticklabels([f"{i:0>2}:00" for i in range(24)])
ax.set_xticks(np.arange(extent[0], extent[1]), minor=True)
ax.set_yticks(np.arange(extent[2], extent[3]), minor=True)
ax.grid(which='minor', color='w', linestyle='-', linewidth=2)
ax.set_xlabel(f'Observability in {day_time_start.year}-{day_time_start.month}-{day_time_start.day} [{self.tzinfo}]')
# fig.suptitle(self.targets[target_index].name)
# plt.tight_layout()
return fig, ax
| [
"matplotlib.dates.date2num",
"pytz.timezone",
"re.compile",
"matplotlib.dates.DateFormatter",
"astropy.coordinates.EarthLocation.from_geodetic",
"astropy.coordinates.SkyCoord",
"bs4.BeautifulSoup",
"numpy.zeros",
"numpy.linspace",
"datetime.datetime.fromisoformat",
"datetime.timedelta",
"numpy... | [((1639, 1655), 'bs4.BeautifulSoup', 'bs', (['text', '"""lxml"""'], {}), "(text, 'lxml')\n", (1641, 1655), True, 'from bs4 import BeautifulSoup as bs\n'), ((3202, 3244), 're.compile', 're.compile', (['"""top: (.*)px; bottom: (.*)px;"""'], {}), "('top: (.*)px; bottom: (.*)px;')\n", (3212, 3244), False, 'import re\n'), ((6866, 6904), 'astropy.coordinates.EarthLocation.from_geodetic', 'EarthLocation.from_geodetic', (['*ATCA_loc'], {}), '(*ATCA_loc)\n', (6893, 6904), False, 'from astropy.coordinates import EarthLocation, SkyCoord\n'), ((7719, 7736), 'datetime.timedelta', 'timedelta', ([], {'days': '(1)'}), '(days=1)\n', (7728, 7736), False, 'from datetime import datetime, timedelta\n'), ((9907, 9938), 'matplotlib.dates.DateFormatter', 'dates.DateFormatter', (['dateformat'], {}), '(dateformat)\n', (9926, 9938), False, 'from matplotlib import dates\n'), ((10435, 10452), 'datetime.timedelta', 'timedelta', ([], {'days': '(1)'}), '(days=1)\n', (10444, 10452), False, 'from datetime import datetime, timedelta\n'), ((7108, 7124), 'pytz.timezone', 'timezone', (['tzinfo'], {}), '(tzinfo)\n', (7116, 7124), False, 'from pytz import timezone\n'), ((10085, 10115), 'matplotlib.dates.date2num', 'dates.date2num', (['time_series[0]'], {}), '(time_series[0])\n', (10099, 10115), False, 'from matplotlib import dates\n'), ((10117, 10148), 'matplotlib.dates.date2num', 'dates.date2num', (['time_series[-1]'], {}), '(time_series[-1])\n', (10131, 10148), False, 'from matplotlib import dates\n'), ((12697, 12727), 'matplotlib.dates.date2num', 'dates.date2num', (['time_series[0]'], {}), '(time_series[0])\n', (12711, 12727), False, 'from matplotlib import dates\n'), ((12729, 12760), 'matplotlib.dates.date2num', 'dates.date2num', (['time_series[-1]'], {}), '(time_series[-1])\n', (12743, 12760), False, 'from matplotlib import dates\n'), ((15187, 15204), 'numpy.zeros', 'np.zeros', (['(2, 48)'], {}), '((2, 48))\n', (15195, 15204), True, 'import numpy as np\n'), ((7046, 7074), 'pytz.timezone', 'timezone', (['"""Australia/Sydney"""'], {}), "('Australia/Sydney')\n", (7054, 7074), False, 'from pytz import timezone\n'), ((7569, 7593), 'pytz.timezone', 'timezone', (['self.portal_tz'], {}), '(self.portal_tz)\n', (7577, 7593), False, 'from pytz import timezone\n'), ((8834, 8861), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', 'time_num'], {}), '(0, 1, time_num)\n', (8845, 8861), True, 'import numpy as np\n'), ((11586, 11613), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', 'time_num'], {}), '(0, 1, time_num)\n', (11597, 11613), True, 'import numpy as np\n'), ((13625, 13658), 'datetime.datetime.fromisoformat', 'datetime.fromisoformat', (['time_date'], {}), '(time_date)\n', (13647, 13658), False, 'from datetime import datetime, timedelta\n'), ((13857, 13890), 'datetime.datetime.fromisoformat', 'datetime.fromisoformat', (['time_date'], {}), '(time_date)\n', (13879, 13890), False, 'from datetime import datetime, timedelta\n'), ((15311, 15330), 'datetime.timedelta', 'timedelta', ([], {'days': 'day'}), '(days=day)\n', (15320, 15330), False, 'from datetime import datetime, timedelta\n'), ((16427, 16458), 'numpy.arange', 'np.arange', (['extent[0]', 'extent[1]'], {}), '(extent[0], extent[1])\n', (16436, 16458), True, 'import numpy as np\n'), ((16498, 16529), 'numpy.arange', 'np.arange', (['extent[2]', 'extent[3]'], {}), '(extent[2], extent[3])\n', (16507, 16529), True, 'import numpy as np\n'), ((6615, 6654), 'astropy.coordinates.SkyCoord', 'SkyCoord', (['"""19h39m25.026s -63d42m45.63s"""'], {}), "('19h39m25.026s -63d42m45.63s')\n", (6623, 6654), False, 'from astropy.coordinates import EarthLocation, SkyCoord\n'), ((6719, 6758), 'astropy.coordinates.SkyCoord', 'SkyCoord', (['"""08h25m26.869s -50d10m38.49s"""'], {}), "('08h25m26.869s -50d10m38.49s')\n", (6727, 6758), False, 'from astropy.coordinates import EarthLocation, SkyCoord\n'), ((11828, 11859), 'datetime.datetime.fromisoformat', 'datetime.fromisoformat', (['obs_day'], {}), '(obs_day)\n', (11850, 11859), False, 'from datetime import datetime, timedelta\n'), ((12184, 12215), 'datetime.datetime.fromisoformat', 'datetime.fromisoformat', (['obs_day'], {}), '(obs_day)\n', (12206, 12215), False, 'from datetime import datetime, timedelta\n'), ((15409, 15430), 'datetime.timedelta', 'timedelta', ([], {'minutes': '(30)'}), '(minutes=30)\n', (15418, 15430), False, 'from datetime import datetime, timedelta\n'), ((12538, 12565), 'matplotlib.dates.date2num', 'dates.date2num', (['block_start'], {}), '(block_start)\n', (12552, 12565), False, 'from matplotlib import dates\n'), ((12572, 12597), 'matplotlib.dates.date2num', 'dates.date2num', (['block_end'], {}), '(block_end)\n', (12586, 12597), False, 'from matplotlib import dates\n')] |
# -*- coding: utf-8 -*-
"""
fix alpha blending of font_control
===================================
"""
# import standard libraries
from operator import sub
import os
from pathlib import Path
from colour.models.cie_lab import Lab_to_LCHab
# import third-party libraries
import numpy as np
from colour import LUT3D, RGB_to_XYZ, XYZ_to_Lab
from colour.models import BT709_COLOURSPACE
from colour.difference import delta_E_CIE2000
# import my libraries
import test_pattern_generator2 as tpg
import color_space as cs
# information
__author__ = '<NAME>'
__copyright__ = 'Copyright (C) 2021 - <NAME>'
__license__ = 'New BSD License - https://opensource.org/licenses/BSD-3-Clause'
__maintainer__ = '<NAME>'
__email__ = 'toru.ver.11 at-sign gmail.com'
__all__ = []
DE2000_8BIT_FILE = "./de2000_8bit.npy"
DE2000_RANK_INDEX = "./de2000_8bit_rank.npy"
def bt709_to_lab(rgb_gm24):
rgb_linear = rgb_gm24 ** 2.4
large_xyz = RGB_to_XYZ(
rgb_linear, cs.D65, cs.D65, BT709_COLOURSPACE.RGB_to_XYZ_matrix)
lab = XYZ_to_Lab(large_xyz)
return lab
def get_top_nth_index(data, inner_grid_num, direction_num, nth=10):
"""
get the top n-th index.
"""
r_base = (inner_grid_num ** 2) * direction_num
g_base = inner_grid_num * direction_num
b_base = direction_num
arg_idx = np.argsort(data.flatten())[::-1]
arg_idx = arg_idx[:nth]
rr_idx = arg_idx // r_base
gg_idx = (arg_idx % r_base) // g_base
bb_idx = (arg_idx % g_base) // b_base
dd_idx = (arg_idx % b_base)
return (rr_idx, gg_idx, bb_idx, dd_idx)
def calc_delta_e_for_next_grid(grid_num):
# calc lab
rgb_gm24 = LUT3D.linear_table(size=grid_num)
lab = bt709_to_lab(rgb_gm24)
# XY平面は同時計算して Z方向は forループで処理する
inner_grid_num = grid_num-1
inner_idx_list = np.arange(inner_grid_num)
inner_grid_num = len(inner_idx_list)
sum_diff_r_direction_buf = []
for r_idx in inner_idx_list:
base_lab = lab[r_idx, :inner_grid_num, :inner_grid_num]
lab_next1 = lab[r_idx+0, 0:inner_grid_num+0, 1:inner_grid_num+1]
lab_next2 = lab[r_idx+0, 1:inner_grid_num+1, 0:inner_grid_num+0]
lab_next3 = lab[r_idx+0, 1:inner_grid_num+1, 1:inner_grid_num+1]
lab_next4 = lab[r_idx+1, 0:inner_grid_num+0, 0:inner_grid_num+0]
lab_next5 = lab[r_idx+1, 0:inner_grid_num+0, 1:inner_grid_num+1]
lab_next6 = lab[r_idx+1, 1:inner_grid_num+1, 0:inner_grid_num+0]
lab_next7 = lab[r_idx+1, 1:inner_grid_num+1, 1:inner_grid_num+1]
lab_next_list = [
lab_next1, lab_next2, lab_next3, lab_next4,
lab_next5, lab_next6, lab_next7]
lab_next_diff_list = [
delta_E_CIE2000(base_lab, lab_next) for lab_next in lab_next_list]
# print(lab_next_diff_list)
# lab_nex_diff_array's shape is (g_idx, b_idx, direction)
lab_next_diff_array = np.dstack(lab_next_diff_list)
sum_diff_r_direction_buf.append(lab_next_diff_array)
# break
sum_diff_inner_rgb = np.stack((sum_diff_r_direction_buf))
return sum_diff_inner_rgb
def main_func(calc_de2k=False):
grid_num = 256
if (not Path(DE2000_8BIT_FILE).exists()) or calc_de2k:
print("re-calculation")
sum_diff_inner_rgb = calc_delta_e_for_next_grid(grid_num=grid_num)
np.save(DE2000_8BIT_FILE, sum_diff_inner_rgb)
rr, gg, bb, dd = get_top_nth_index(
data=sum_diff_inner_rgb, inner_grid_num=grid_num-1,
direction_num=7, nth=2**20)
np.save(DE2000_RANK_INDEX, np.array([rr, gg, bb, dd]))
else:
print("load save data")
sum_diff_inner_rgb = np.load(DE2000_8BIT_FILE)
rgbd_array = np.load(DE2000_RANK_INDEX)
rr = rgbd_array[0]
gg = rgbd_array[1]
bb = rgbd_array[2]
dd = rgbd_array[3]
# print(rr, gg, bb, dd)
# print(sum_diff_inner_rgb[rr, gg, bb, dd])
# for idx in range(400):
# print(rr[idx], gg[idx], bb[idx], dd[idx], sum_diff_inner_rgb[rr[idx], gg[idx], bb[idx], dd[idx]])
lh_cl = np.array([127, 127, 127]) # L=50, C=0
lh_cm = np.array([141, 126, 114]) # L=50, C=10
lh_ch = np.array([149, 122, 97]) # L=50, C=20
lm_cl = np.array([94, 94, 94]) # L=35, C=0
lm_cm = np.array([103, 90, 78]) # L=35, C=10
lm_ch = np.array([110, 88, 63]) # L=35, C=20
ll_cl = np.array([61, 61, 61]) # L=20, C=0
ll_cm = np.array([68, 58, 46]) # L=20, C=10
ll_ch = np.array([75, 56, 33]) # L=20, C=20
min_lightness = 20
min_chroma = 0
rgb = np.dstack((rr, gg, bb))
lch = Lab_to_LCHab(bt709_to_lab(rgb/255))
ll = lch[..., 0]
cc = lch[..., 1]
ok_idx = ((ll > min_lightness) & (cc > min_chroma))[0]
print(f"ok_idx's shape = {ok_idx}")
rr_new = rr[ok_idx]
gg_new = gg[ok_idx]
bb_new = bb[ok_idx]
dd_new = dd[ok_idx]
for idx in range(30):
print(
rr_new[idx],
gg_new[idx],
bb_new[idx],
dd_new[idx],
sum_diff_inner_rgb[rr_new[idx], gg_new[idx], bb_new[idx], dd_new[idx]])
if __name__ == '__main__':
os.chdir(os.path.dirname(os.path.abspath(__file__)))
main_func(calc_de2k=False)
| [
"numpy.dstack",
"pathlib.Path",
"colour.RGB_to_XYZ",
"colour.XYZ_to_Lab",
"numpy.stack",
"numpy.array",
"colour.LUT3D.linear_table",
"numpy.save",
"os.path.abspath",
"colour.difference.delta_E_CIE2000",
"numpy.arange",
"numpy.load"
] | [((926, 1001), 'colour.RGB_to_XYZ', 'RGB_to_XYZ', (['rgb_linear', 'cs.D65', 'cs.D65', 'BT709_COLOURSPACE.RGB_to_XYZ_matrix'], {}), '(rgb_linear, cs.D65, cs.D65, BT709_COLOURSPACE.RGB_to_XYZ_matrix)\n', (936, 1001), False, 'from colour import LUT3D, RGB_to_XYZ, XYZ_to_Lab\n'), ((1021, 1042), 'colour.XYZ_to_Lab', 'XYZ_to_Lab', (['large_xyz'], {}), '(large_xyz)\n', (1031, 1042), False, 'from colour import LUT3D, RGB_to_XYZ, XYZ_to_Lab\n'), ((1636, 1669), 'colour.LUT3D.linear_table', 'LUT3D.linear_table', ([], {'size': 'grid_num'}), '(size=grid_num)\n', (1654, 1669), False, 'from colour import LUT3D, RGB_to_XYZ, XYZ_to_Lab\n'), ((1792, 1817), 'numpy.arange', 'np.arange', (['inner_grid_num'], {}), '(inner_grid_num)\n', (1801, 1817), True, 'import numpy as np\n'), ((3003, 3037), 'numpy.stack', 'np.stack', (['sum_diff_r_direction_buf'], {}), '(sum_diff_r_direction_buf)\n', (3011, 3037), True, 'import numpy as np\n'), ((4036, 4061), 'numpy.array', 'np.array', (['[127, 127, 127]'], {}), '([127, 127, 127])\n', (4044, 4061), True, 'import numpy as np\n'), ((4087, 4112), 'numpy.array', 'np.array', (['[141, 126, 114]'], {}), '([141, 126, 114])\n', (4095, 4112), True, 'import numpy as np\n'), ((4139, 4163), 'numpy.array', 'np.array', (['[149, 122, 97]'], {}), '([149, 122, 97])\n', (4147, 4163), True, 'import numpy as np\n'), ((4192, 4214), 'numpy.array', 'np.array', (['[94, 94, 94]'], {}), '([94, 94, 94])\n', (4200, 4214), True, 'import numpy as np\n'), ((4241, 4264), 'numpy.array', 'np.array', (['[103, 90, 78]'], {}), '([103, 90, 78])\n', (4249, 4264), True, 'import numpy as np\n'), ((4291, 4314), 'numpy.array', 'np.array', (['[110, 88, 63]'], {}), '([110, 88, 63])\n', (4299, 4314), True, 'import numpy as np\n'), ((4342, 4364), 'numpy.array', 'np.array', (['[61, 61, 61]'], {}), '([61, 61, 61])\n', (4350, 4364), True, 'import numpy as np\n'), ((4390, 4412), 'numpy.array', 'np.array', (['[68, 58, 46]'], {}), '([68, 58, 46])\n', (4398, 4412), True, 'import numpy as np\n'), ((4439, 4461), 'numpy.array', 'np.array', (['[75, 56, 33]'], {}), '([75, 56, 33])\n', (4447, 4461), True, 'import numpy as np\n'), ((4530, 4553), 'numpy.dstack', 'np.dstack', (['(rr, gg, bb)'], {}), '((rr, gg, bb))\n', (4539, 4553), True, 'import numpy as np\n'), ((2871, 2900), 'numpy.dstack', 'np.dstack', (['lab_next_diff_list'], {}), '(lab_next_diff_list)\n', (2880, 2900), True, 'import numpy as np\n'), ((3299, 3344), 'numpy.save', 'np.save', (['DE2000_8BIT_FILE', 'sum_diff_inner_rgb'], {}), '(DE2000_8BIT_FILE, sum_diff_inner_rgb)\n', (3306, 3344), True, 'import numpy as np\n'), ((3627, 3652), 'numpy.load', 'np.load', (['DE2000_8BIT_FILE'], {}), '(DE2000_8BIT_FILE)\n', (3634, 3652), True, 'import numpy as np\n'), ((3674, 3700), 'numpy.load', 'np.load', (['DE2000_RANK_INDEX'], {}), '(DE2000_RANK_INDEX)\n', (3681, 3700), True, 'import numpy as np\n'), ((2672, 2707), 'colour.difference.delta_E_CIE2000', 'delta_E_CIE2000', (['base_lab', 'lab_next'], {}), '(base_lab, lab_next)\n', (2687, 2707), False, 'from colour.difference import delta_E_CIE2000\n'), ((3528, 3554), 'numpy.array', 'np.array', (['[rr, gg, bb, dd]'], {}), '([rr, gg, bb, dd])\n', (3536, 3554), True, 'import numpy as np\n'), ((5120, 5145), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (5135, 5145), False, 'import os\n'), ((3137, 3159), 'pathlib.Path', 'Path', (['DE2000_8BIT_FILE'], {}), '(DE2000_8BIT_FILE)\n', (3141, 3159), False, 'from pathlib import Path\n')] |
#!/usr/bin/env python
# coding: utf-8
import numpy as np
import random
import itertools
import mccd
## Extracting the EigenPSFs from the fitted models
vignets_noiseless = np.zeros((19665, 51, 51))
i=0
for j in list(range(2000000, 2000287)) + list(range(2100000, 2100150)):
path_fitted_model = '/n05data/ayed/outputs/mccd_runs/shapepipe_run_2021-07-13_11-19-06/mccd_fit_val_runner/output/fitted_model-'+str(j)+'.npy'
fitted_model = np.load(path_fitted_model, allow_pickle=True)
S = fitted_model[1]['S']
S_loc = S[-1]
vignets_noiseless[i*45:(i+1)*45, :, :] = mccd.utils.reg_format(S_loc)
i+=1
np.random.shuffle(vignets_noiseless)
## Saving the dataset
train_dic = {'VIGNETS_NOISELESS': vignets_noiseless}
mccd.mccd_utils.save_to_fits(train_dic, '/n05data/ayed/outputs/eigenpsfs/global_eigenpsfs.fits')
| [
"mccd.mccd_utils.save_to_fits",
"numpy.zeros",
"mccd.utils.reg_format",
"numpy.load",
"numpy.random.shuffle"
] | [((176, 201), 'numpy.zeros', 'np.zeros', (['(19665, 51, 51)'], {}), '((19665, 51, 51))\n', (184, 201), True, 'import numpy as np\n'), ((639, 675), 'numpy.random.shuffle', 'np.random.shuffle', (['vignets_noiseless'], {}), '(vignets_noiseless)\n', (656, 675), True, 'import numpy as np\n'), ((763, 863), 'mccd.mccd_utils.save_to_fits', 'mccd.mccd_utils.save_to_fits', (['train_dic', '"""/n05data/ayed/outputs/eigenpsfs/global_eigenpsfs.fits"""'], {}), "(train_dic,\n '/n05data/ayed/outputs/eigenpsfs/global_eigenpsfs.fits')\n", (791, 863), False, 'import mccd\n'), ((451, 496), 'numpy.load', 'np.load', (['path_fitted_model'], {'allow_pickle': '(True)'}), '(path_fitted_model, allow_pickle=True)\n', (458, 496), True, 'import numpy as np\n'), ((590, 618), 'mccd.utils.reg_format', 'mccd.utils.reg_format', (['S_loc'], {}), '(S_loc)\n', (611, 618), False, 'import mccd\n')] |
import numpy as np
from sklearn.base import BaseEstimator, clone
from sklearn.metrics import r2_score
from .utils import my_fit
class EraBoostXgbRegressor(BaseEstimator):
def __init__(self, base_estimator=None, num_iterations=3, proportion=0.5, n_estimators=None):
self.base_estimator = base_estimator
self.num_iterations = num_iterations
self.proportion = proportion
self.n_estimators = n_estimators
def fit(self, X, y, sample_weight=None, fit_context=None):
self.n_features_in_ = X.shape[1]
self.base_estimator_ = clone(self.base_estimator)
my_fit(
self.base_estimator_,
X,
y,
sample_weight=sample_weight,
fit_context=fit_context,
)
for iter in range(self.num_iterations - 1):
y_pred = self.base_estimator_.predict(X)
era_scores = []
indicies = []
n = y_pred.shape[0]
m = 10
for i in range(m):
idx = np.arange(i * n // m, (i + 1) * n // m)
indicies.append(idx)
y_pred2 = indexing(y_pred, idx)
y2 = indexing(y, idx)
era_scores.append(r2_score(y2, y_pred2))
score_threshold = np.quantile(era_scores, self.proportion)
idx = []
for i in range(m):
if era_scores[i] <= score_threshold:
idx.append(indicies[i])
idx = np.concatenate(idx)
self.base_estimator_.n_estimators += self.n_estimators
booster = self.base_estimator_.get_booster()
self.base_estimator_.fit(indexing(X, idx), indexing(y, idx), xgb_model=booster)
return self
def predict(self, X):
return self.base_estimator_.predict(X)
def indexing(x, idx):
if hasattr(x, 'iloc'):
return x.iloc[idx]
else:
return x[idx]
| [
"sklearn.base.clone",
"numpy.quantile",
"numpy.concatenate",
"sklearn.metrics.r2_score",
"numpy.arange"
] | [((575, 601), 'sklearn.base.clone', 'clone', (['self.base_estimator'], {}), '(self.base_estimator)\n', (580, 601), False, 'from sklearn.base import BaseEstimator, clone\n'), ((1287, 1327), 'numpy.quantile', 'np.quantile', (['era_scores', 'self.proportion'], {}), '(era_scores, self.proportion)\n', (1298, 1327), True, 'import numpy as np\n'), ((1495, 1514), 'numpy.concatenate', 'np.concatenate', (['idx'], {}), '(idx)\n', (1509, 1514), True, 'import numpy as np\n'), ((1036, 1075), 'numpy.arange', 'np.arange', (['(i * n // m)', '((i + 1) * n // m)'], {}), '(i * n // m, (i + 1) * n // m)\n', (1045, 1075), True, 'import numpy as np\n'), ((1233, 1254), 'sklearn.metrics.r2_score', 'r2_score', (['y2', 'y_pred2'], {}), '(y2, y_pred2)\n', (1241, 1254), False, 'from sklearn.metrics import r2_score\n')] |
import gc
import time
from typing import Optional
import numpy
from aydin.features.base import FeatureGeneratorBase
from aydin.features.standard_features import StandardFeatureGenerator
from aydin.it.balancing.data_histogram_balancer import DataHistogramBalancer
from aydin.it.base import ImageTranslatorBase
from aydin.regression.base import RegressorBase
from aydin.regression.cb import CBRegressor
from aydin.util.array.nd import nd_split_slices
from aydin.util.log.log import lprint, lsection
from aydin.util.offcore.offcore import offcore_array
class ImageTranslatorFGR(ImageTranslatorBase):
"""
Feature Generation & Regression (FGR) based Image TranslatorFGR Image Translator
"""
feature_generator: FeatureGeneratorBase
def __init__(
self,
feature_generator: FeatureGeneratorBase = None,
regressor: RegressorBase = None,
balance_training_data: bool = False,
voxel_keep_ratio: float = 1,
max_voxels_for_training: Optional[int] = None,
favour_bright_pixels: bool = False,
**kwargs,
):
"""Constructs a FGR image translator. FGR image translators use feature generation
and regression learning to acheive image translation.
Parameters
----------
feature_generator : FeatureGeneratorBase
Feature generator.
regressor : RegressorBase
Regressor.
balance_training_data : bool
Limits number training entries per target
value histogram bin.
voxel_keep_ratio : float
Ratio of the voxels to keep for training.
max_voxels_for_training : int, optional
Maximum number of the voxels that can be
used for training.
favour_bright_pixels : bool
Marks bright pixels more favourable for
the data histogram balancer.
kwargs : dict
Keyword arguments.
max_memory_usage_ratio : float
Maximum allowed memory load.
max_tiling_overhead : float
Maximum allowed margin overhead during tiling.
"""
super().__init__(**kwargs)
self.voxel_keep_ratio = voxel_keep_ratio
self.balance_training_data = balance_training_data
self.favour_bright_pixels = favour_bright_pixels
self.feature_generator = (
StandardFeatureGenerator()
if feature_generator is None
else feature_generator
)
self.regressor = CBRegressor() if regressor is None else regressor
self.max_voxels_for_training = (
self.regressor.recommended_max_num_datapoints()
if max_voxels_for_training is None
else max_voxels_for_training
)
# It seems empirically that excluding the central feature incurs no cost in quality,
# simply because for every scale the next scale already partly covers these pixels.
self.exclude_center_feature = True
# Option to exclude the center value during translation. Set to True by default.
self.exclude_center_value_when_translating = False
# Advanced private functionality:
# This field gives the opportunity to specify which channels must be 'passed-through'
# directly as features. This is not intended to be used directly by users.
self._passthrough_channels = None
with lsection("FGR image translator"):
lprint(f"balance training data: {self.balance_training_data}")
def save(self, path: str):
"""Saves a 'all-batteries-included' image translation model at a given path (folder).
Parameters
----------
path : str
path to save to
Returns
-------
frozen
"""
with lsection(f"Saving 'fgr' image translator to {path}"):
frozen = super().save(path)
frozen += self.feature_generator.save(path) + '\n'
frozen += self.regressor.save(path) + '\n'
return frozen
def _load_internals(self, path: str):
with lsection(f"Loading 'fgr' image translator from {path}"):
self.feature_generator = FeatureGeneratorBase.load(path)
self.regressor = RegressorBase.load(path)
# We exclude certain fields from saving:
def __getstate__(self):
state = self.__dict__.copy()
del state['feature_generator']
del state['regressor']
return state
def stop_training(self):
"""Stops currently running training within the instance by calling
the corresponding `stop_fit()` method on the regressor.
"""
self.regressor.stop_fit()
def _estimate_memory_needed_and_available(self, image):
with lsection(
"Estimating the amount of memory needed to store feature arrays:"
):
num_spatio_temp_dim = len(image.shape[2:])
dummy_image = numpy.zeros(
shape=(1, 1) + (4,) * num_spatio_temp_dim, dtype=numpy.float32
)
x = self._compute_features(
dummy_image,
exclude_center_feature=self.exclude_center_feature,
exclude_center_value=False,
)
num_features = x.shape[-1]
feature_dtype = x.dtype
(
memory_needed,
memory_available,
) = super()._estimate_memory_needed_and_available(image)
"""Here, 1.3 correction factor is chosen to have a bigger safety margin as we use
more memory while generating features(namely uniform features) than the amount
of memory we need after feature computations."""
memory_needed = max(
memory_needed, 1.3 * num_features * image.size * feature_dtype.itemsize
)
return memory_needed, memory_available
def _compute_features(
self,
image,
exclude_center_feature,
exclude_center_value,
features_last=True,
num_reserved_features=0,
image_slice=None,
whole_image_shape=None,
):
"""Internal function that computes features for a given image.
:param image: image
:param exclude_center_feature: exclude center feature
:param exclude_center_value: exclude center value
:return: returns flattened array of features
"""
with lsection(f"Computing features for image of shape {image.shape}:"):
excluded_voxels = (
None
if self.blind_spots is None
else list(
[
coordinate
for coordinate in self.blind_spots
if coordinate != (0,) * (image.ndim - 2)
]
)
)
lprint(f"exclude_center_feature = {exclude_center_feature}")
lprint(f"exclude_center_value = {exclude_center_value}")
lprint(f"excluded_voxels = {excluded_voxels}")
excluded_voxels = (
None
if self.blind_spots is None
else list(
[
coordinate
for coordinate in self.blind_spots
if coordinate != (0,) * (image.ndim - 2)
]
)
)
# If this is a part of a larger image, we can figure out what are the offsets and scales for the spatial features:
spatial_feature_scale = (
None
if whole_image_shape is None
else tuple(1.0 / s for s in whole_image_shape[2:])
)
spatial_feature_offset = (
None if image_slice is None else tuple(s.start for s in image_slice[2:])
)
lprint(f"spatial_feature_scale = {spatial_feature_scale}")
lprint(f"spatial_feature_offset = {spatial_feature_offset}")
features = self.feature_generator.compute(
image,
exclude_center_feature=exclude_center_feature,
exclude_center_value=exclude_center_value,
num_reserved_features=num_reserved_features,
passthrough_channels=self._passthrough_channels,
feature_last_dim=False,
excluded_voxels=excluded_voxels,
spatial_feature_offset=spatial_feature_offset,
spatial_feature_scale=spatial_feature_scale,
)
num_features = features.shape[0]
x = features.reshape(num_features, -1)
if features_last:
x = numpy.moveaxis(x, 0, -1)
return x
def _train(
self, input_image, target_image, train_valid_ratio, callback_period, jinv
):
with lsection(
f"Training image translator from image of shape {input_image.shape} to image of shape {target_image.shape}:"
):
self.prepare_monitoring_images()
num_input_channels = input_image.shape[1]
num_target_channels = target_image.shape[1]
normalised_input_shape = input_image.shape
# Deal with jinv parameter;
if jinv is None:
exclude_center_value = self.self_supervised
elif type(jinv) is tuple:
exclude_center_value = jinv
else:
exclude_center_value = jinv
# Prepare the splitting of train from valid data as well as balancing and decimation...
self._prepare_split_train_val(input_image, target_image)
# Tilling strategy is determined here:
tilling_strategy, margins = self._get_tilling_strategy_and_margins(
input_image,
max_voxels_per_tile=self.max_voxels_per_tile,
min_margin=self.tile_min_margin,
max_margin=self.tile_max_margin,
)
lprint(f"Tilling strategy (just batches): {tilling_strategy}")
lprint(f"Margins for tiles: {margins} .")
# tile slice objects with margins:
tile_slices_margins = list(
nd_split_slices(
normalised_input_shape, nb_slices=tilling_strategy, margins=margins
)
)
# Number of tiles:
number_of_tiles = len(tile_slices_margins)
lprint(f"Number of tiles (slices): {number_of_tiles}")
# We initialise the arrays:
x_train, x_valid, y_train, y_valid = (None,) * 4
for idx, slice_margin_tuple in enumerate(tile_slices_margins):
with lsection(
f"Current tile: {idx}/{number_of_tiles}, slice: {slice_margin_tuple} "
):
# We first extract the tile image:
input_image_tile = input_image[slice_margin_tuple]
target_image_tile = target_image[slice_margin_tuple]
x_tile = self._compute_features(
input_image_tile,
exclude_center_feature=self.exclude_center_feature,
exclude_center_value=exclude_center_value,
num_reserved_features=0,
features_last=False,
image_slice=slice_margin_tuple,
whole_image_shape=input_image.shape,
)
y_tile = target_image_tile.reshape(num_target_channels, -1)
num_features_tile = x_tile.shape[0]
num_entries_tile = y_tile.shape[1]
lprint(
f"Number of entries: {num_entries_tile}, features: {num_features_tile}, input channels: {num_input_channels}, target channels: {num_target_channels}"
)
# We split this tile's data into train and valid sets:
(
x_train_tile,
x_valid_tile,
y_train_tile,
y_valid_tile,
) = self._do_split_train_val(
num_target_channels, train_valid_ratio, x_tile, y_tile
)
# We get rid of x and y to free memory:
del x_tile, y_tile
gc.collect()
# We now put the feature dimension to the back:
x_train_tile = numpy.moveaxis(x_train_tile, 0, -1)
x_valid_tile = numpy.moveaxis(x_valid_tile, 0, -1)
if x_train is None or x_valid is None:
x_train, x_valid, y_train, y_valid = (
x_train_tile,
x_valid_tile,
y_train_tile,
y_valid_tile,
)
else:
x_train = numpy.append(x_train, x_train_tile, axis=0)
x_valid = numpy.append(x_valid, x_valid_tile, axis=0)
y_train = numpy.append(y_train, y_train_tile, axis=1)
y_valid = numpy.append(y_valid, y_valid_tile, axis=1)
lprint("Training now...")
self.regressor.fit(
x_train=x_train,
y_train=y_train,
x_valid=x_valid,
y_valid=y_valid,
regressor_callback=self.get_callback() if self.monitor else None,
)
self.loss_history = self.regressor.loss_history
def prepare_monitoring_images(self):
# Compute features for monitoring images:
if self.monitor is not None and self.monitor.monitoring_images is not None:
# Normalise monitoring images:
normalised_monitoring_images = [
self.shape_normaliser.normalise(
monitoring_image, batch_dims=None, channel_dims=None
)
for monitoring_image in self.monitor.monitoring_images
]
# compute features proper:
monitoring_images_features = [
self._compute_features(
monitoring_image,
exclude_center_feature=self.exclude_center_feature,
exclude_center_value=False,
features_last=True,
)
for monitoring_image in normalised_monitoring_images
]
else:
monitoring_images_features = None
# We keep these features handy...
self.monitoring_datasets = monitoring_images_features
def get_callback(self):
# Regressor callback:
def regressor_callback(iteration, val_loss, model):
if val_loss is None:
return
current_time_sec = time.time()
# Correct for dtype range:
if self.feature_generator.dtype == numpy.uint8:
val_loss /= 255
elif self.feature_generator.dtype == numpy.uint16:
val_loss /= 255 * 255
if current_time_sec > self.last_callback_time_sec + self.callback_period:
if self.monitoring_datasets and self.monitor:
predicted_monitoring_datasets = [
self.regressor.predict(x_m, models_to_use=[model])
for x_m in self.monitoring_datasets
]
inferred_images = [
y_m.reshape(image.shape)
for (image, y_m) in zip(
self.monitor.monitoring_images,
predicted_monitoring_datasets,
)
]
# for image in inferred_images:
for index in range(len(inferred_images)):
(
inferred_images[index],
_,
_,
) = self.shape_normaliser.shape_normalize(
inferred_images[index]
)
denormalised_inferred_images = [
self.target_shape_normaliser.denormalise(inferred_image)
for inferred_image in inferred_images
]
self.monitor.variables = (
iteration,
val_loss,
denormalised_inferred_images,
)
elif self.monitor:
self.monitor.variables = (iteration, val_loss, None)
self.last_callback_time_sec = current_time_sec
else:
pass
# print(f"Iteration={iteration} metric value: {eval_metric_value} ")
return regressor_callback
def _prepare_split_train_val(self, input_image, target_image):
# the number of voxels:
num_of_voxels = input_image.size
lprint(
f"Image has: {num_of_voxels} voxels, at most: {self.max_voxels_for_training} voxels will be used for training or validation."
)
# This is the ratio of pixels to keep:
max_voxels_keep_ratio = float(self.max_voxels_for_training) / num_of_voxels
effective_keep_ratio = min(self.voxel_keep_ratio, max_voxels_keep_ratio)
lprint(
f"Given train ratio is: {self.voxel_keep_ratio}, max_voxels induced keep-ratio is: {max_voxels_keep_ratio}"
)
# For small images it is not worth having any limit or balance anything:
num_voxels_in_small_image = 5 * 1e6
effective_keep_ratio = (
1.0 if num_of_voxels < num_voxels_in_small_image else effective_keep_ratio
)
balance_training_data = (
False
if num_of_voxels < num_voxels_in_small_image
else self.balance_training_data
)
lprint(
f"Data histogram balancer is: {'active' if balance_training_data else 'inactive'}"
)
lprint(f"Effective keep-ratio is: {effective_keep_ratio}")
lprint(
f"Favouring bright pixels: {'yes' if self.favour_bright_pixels else 'no'}"
)
# We decide on a 'batch' length that will be used to shuffle, select and then copy the training data...
num_of_voxels_per_stack = input_image[2:].size
batch_length = (
16
if num_of_voxels_per_stack < 1e5
else (
32
if num_of_voxels_per_stack < 1e6
else (
128
if num_of_voxels_per_stack < 1e7
else (512 if num_of_voxels_per_stack < 1e8 else 4096)
)
)
)
lprint(f"Using contiguous batches of length: {batch_length} ")
# We create a balancer common to all tiles:
balancer = DataHistogramBalancer(
balance=balance_training_data,
keep_ratio=effective_keep_ratio,
favour_bright_pixels=self.favour_bright_pixels,
)
# Calibration of the balancer is done on the entire image:
lprint("Calibrating balancer...")
balancer.calibrate(target_image.ravel(), batch_length)
# Keep both balancer and batch length
self.train_val_split_balancer = balancer
self.train_val_split_batch_length = batch_length
def _do_split_train_val(
self, num_target_channels: int, train_valid_ratio: float, x, y
):
with lsection(
f"Splitting train and test sets (train_test_ratio={train_valid_ratio}) "
):
balancer: DataHistogramBalancer = self.train_val_split_balancer
batch_length: int = self.train_val_split_batch_length
nb_features = x.shape[0]
nb_entries = y.shape[1]
nb_split_batches = max(nb_entries // batch_length, 64)
lprint(
f"Creating random indices for train/val split (nb_split_batches={nb_split_batches})"
)
nb_split_batches_valid = int(train_valid_ratio * nb_split_batches)
nb_split_batches_train = nb_split_batches - nb_split_batches_valid
is_train_array = numpy.full(nb_split_batches, False)
is_train_array[nb_split_batches_valid:] = True
lprint(f"train/valid bool array created (length={is_train_array.shape[0]})")
lprint("Shuffling train/valid bool array...")
numpy.random.shuffle(is_train_array)
lprint("Calculating number of entries for train and validation...")
nb_entries_per_split_batch = max(1, nb_entries // nb_split_batches)
nb_entries_train = nb_split_batches_train * nb_entries_per_split_batch
nb_entries_valid = nb_split_batches_valid * nb_entries_per_split_batch
lprint(
f"Number of entries for training: {nb_entries_train} = {nb_split_batches_train}*{nb_entries_per_split_batch}, validation: {nb_entries_valid} = {nb_split_batches_valid} * {nb_entries_per_split_batch}"
)
lprint("Allocating arrays...")
x_train = offcore_array(
shape=(nb_features, nb_entries_train),
dtype=x.dtype,
max_memory_usage_ratio=self.max_memory_usage_ratio,
)
y_train = offcore_array(
shape=(num_target_channels, nb_entries_train),
dtype=y.dtype,
max_memory_usage_ratio=self.max_memory_usage_ratio,
)
x_valid = offcore_array(
shape=(nb_features, nb_entries_valid),
dtype=x.dtype,
max_memory_usage_ratio=self.max_memory_usage_ratio,
)
y_valid = offcore_array(
shape=(num_target_channels, nb_entries_valid),
dtype=y.dtype,
max_memory_usage_ratio=self.max_memory_usage_ratio,
)
with lsection("Copying data for training and validation sets..."):
# We use a random permutation to avoid having the balancer drop only from the 'end' of the image
permutation = numpy.random.permutation(nb_split_batches)
i, jt, jv = 0, 0, 0
dst_stop_train = 0
dst_stop_valid = 0
balancer.initialise(nb_split_batches)
for is_train in numpy.nditer(is_train_array):
if i % (nb_split_batches // 64) == 0:
lprint(
f"Copying section [{i},{min(nb_split_batches, i + nb_split_batches // 64)}]"
)
permutated_i = permutation[i]
src_start = permutated_i * nb_entries_per_split_batch
src_stop = src_start + nb_entries_per_split_batch
i += 1
xsrc = x[:, src_start:src_stop]
ysrc = y[:, src_start:src_stop]
if balancer.add_entry(ysrc):
if is_train:
dst_start_train = jt * nb_entries_per_split_batch
dst_stop_train = (jt + 1) * nb_entries_per_split_batch
jt += 1
xdst = x_train[:, dst_start_train:dst_stop_train]
ydst = y_train[:, dst_start_train:dst_stop_train]
numpy.copyto(xdst, xsrc)
numpy.copyto(ydst, ysrc)
else:
dst_start_valid = jv * nb_entries_per_split_batch
dst_stop_valid = (jv + 1) * nb_entries_per_split_batch
jv += 1
xdst = x_valid[:, dst_start_valid:dst_stop_valid]
ydst = y_valid[:, dst_start_valid:dst_stop_valid]
numpy.copyto(xdst, xsrc)
numpy.copyto(ydst, ysrc)
# Now we actually truncate out all the zeros at the end of the arrays:
x_train = x_train[:, 0:dst_stop_train]
y_train = y_train[:, 0:dst_stop_train]
x_valid = x_valid[:, 0:dst_stop_valid]
y_valid = y_valid[:, 0:dst_stop_valid]
lprint(f"Histogram all : {balancer.get_histogram_all_as_string()}")
lprint(f"Histogram kept : {balancer.get_histogram_kept_as_string()}")
lprint(
f"Histogram dropped: {balancer.get_histogram_dropped_as_string()}"
)
lprint(
f"Number of entries kept: {balancer.total_kept()} out of {balancer.total_entries} total"
)
lprint(
f"Percentage of data kept: {100 * balancer.percentage_kept():.3f}% (train_data_ratio={balancer.keep_ratio}) "
)
if balancer.keep_ratio >= 1 and balancer.percentage_kept() < 1:
lprint(
"Note: balancer has dropped entries that fell on over-represented histogram bins"
)
return x_train, x_valid, y_train, y_valid
def _translate(self, input_image, image_slice=None, whole_image_shape=None):
"""Internal method that translates an input image on the basis of the trained model.
:param input_image: input image
:param batch_dims: batch dimensions
:return:
"""
shape = input_image.shape
num_batches = shape[0]
x = self._compute_features(
input_image,
exclude_center_feature=self.exclude_center_feature,
exclude_center_value=self.exclude_center_value_when_translating,
num_reserved_features=0,
features_last=True,
image_slice=image_slice,
whole_image_shape=whole_image_shape,
)
with lsection(
f"Predict from feature vector of dimension {x.shape} and dtype: {x.dtype}:"
):
lprint("Predicting... ")
# Predict using regressor:
yp = self.regressor.predict(x)
# We make sure that we have the result in float type, but make _sure_ to avoid copying data:
if yp.dtype != numpy.float32 and yp.dtype != numpy.float64:
yp = yp.astype(numpy.float32, copy=False)
# We reshape the array:
num_target_channels = yp.shape[0]
translated_image_shape = (num_batches, num_target_channels) + shape[2:]
lprint(f"Reshaping array to {translated_image_shape}... ")
inferred_image = yp.reshape(translated_image_shape)
return inferred_image
| [
"numpy.copyto",
"aydin.features.base.FeatureGeneratorBase.load",
"numpy.moveaxis",
"aydin.util.log.log.lsection",
"aydin.regression.cb.CBRegressor",
"aydin.regression.base.RegressorBase.load",
"numpy.random.permutation",
"aydin.util.array.nd.nd_split_slices",
"aydin.util.offcore.offcore.offcore_arra... | [((17235, 17378), 'aydin.util.log.log.lprint', 'lprint', (['f"""Image has: {num_of_voxels} voxels, at most: {self.max_voxels_for_training} voxels will be used for training or validation."""'], {}), "(\n f'Image has: {num_of_voxels} voxels, at most: {self.max_voxels_for_training} voxels will be used for training or validation.'\n )\n", (17241, 17378), False, 'from aydin.util.log.log import lprint, lsection\n'), ((17611, 17736), 'aydin.util.log.log.lprint', 'lprint', (['f"""Given train ratio is: {self.voxel_keep_ratio}, max_voxels induced keep-ratio is: {max_voxels_keep_ratio}"""'], {}), "(\n f'Given train ratio is: {self.voxel_keep_ratio}, max_voxels induced keep-ratio is: {max_voxels_keep_ratio}'\n )\n", (17617, 17736), False, 'from aydin.util.log.log import lprint, lsection\n'), ((18177, 18277), 'aydin.util.log.log.lprint', 'lprint', (['f"""Data histogram balancer is: {\'active\' if balance_training_data else \'inactive\'}"""'], {}), '(\n f"Data histogram balancer is: {\'active\' if balance_training_data else \'inactive\'}"\n )\n', (18183, 18277), False, 'from aydin.util.log.log import lprint, lsection\n'), ((18298, 18356), 'aydin.util.log.log.lprint', 'lprint', (['f"""Effective keep-ratio is: {effective_keep_ratio}"""'], {}), "(f'Effective keep-ratio is: {effective_keep_ratio}')\n", (18304, 18356), False, 'from aydin.util.log.log import lprint, lsection\n'), ((18365, 18452), 'aydin.util.log.log.lprint', 'lprint', (['f"""Favouring bright pixels: {\'yes\' if self.favour_bright_pixels else \'no\'}"""'], {}), '(\n f"Favouring bright pixels: {\'yes\' if self.favour_bright_pixels else \'no\'}")\n', (18371, 18452), False, 'from aydin.util.log.log import lprint, lsection\n'), ((19034, 19096), 'aydin.util.log.log.lprint', 'lprint', (['f"""Using contiguous batches of length: {batch_length} """'], {}), "(f'Using contiguous batches of length: {batch_length} ')\n", (19040, 19096), False, 'from aydin.util.log.log import lprint, lsection\n'), ((19168, 19306), 'aydin.it.balancing.data_histogram_balancer.DataHistogramBalancer', 'DataHistogramBalancer', ([], {'balance': 'balance_training_data', 'keep_ratio': 'effective_keep_ratio', 'favour_bright_pixels': 'self.favour_bright_pixels'}), '(balance=balance_training_data, keep_ratio=\n effective_keep_ratio, favour_bright_pixels=self.favour_bright_pixels)\n', (19189, 19306), False, 'from aydin.it.balancing.data_histogram_balancer import DataHistogramBalancer\n'), ((19424, 19457), 'aydin.util.log.log.lprint', 'lprint', (['"""Calibrating balancer..."""'], {}), "('Calibrating balancer...')\n", (19430, 19457), False, 'from aydin.util.log.log import lprint, lsection\n'), ((2371, 2397), 'aydin.features.standard_features.StandardFeatureGenerator', 'StandardFeatureGenerator', ([], {}), '()\n', (2395, 2397), False, 'from aydin.features.standard_features import StandardFeatureGenerator\n'), ((2509, 2522), 'aydin.regression.cb.CBRegressor', 'CBRegressor', ([], {}), '()\n', (2520, 2522), False, 'from aydin.regression.cb import CBRegressor\n'), ((3413, 3445), 'aydin.util.log.log.lsection', 'lsection', (['"""FGR image translator"""'], {}), "('FGR image translator')\n", (3421, 3445), False, 'from aydin.util.log.log import lprint, lsection\n'), ((3459, 3521), 'aydin.util.log.log.lprint', 'lprint', (['f"""balance training data: {self.balance_training_data}"""'], {}), "(f'balance training data: {self.balance_training_data}')\n", (3465, 3521), False, 'from aydin.util.log.log import lprint, lsection\n'), ((3808, 3860), 'aydin.util.log.log.lsection', 'lsection', (['f"""Saving \'fgr\' image translator to {path}"""'], {}), '(f"Saving \'fgr\' image translator to {path}")\n', (3816, 3860), False, 'from aydin.util.log.log import lprint, lsection\n'), ((4099, 4154), 'aydin.util.log.log.lsection', 'lsection', (['f"""Loading \'fgr\' image translator from {path}"""'], {}), '(f"Loading \'fgr\' image translator from {path}")\n', (4107, 4154), False, 'from aydin.util.log.log import lprint, lsection\n'), ((4193, 4224), 'aydin.features.base.FeatureGeneratorBase.load', 'FeatureGeneratorBase.load', (['path'], {}), '(path)\n', (4218, 4224), False, 'from aydin.features.base import FeatureGeneratorBase\n'), ((4254, 4278), 'aydin.regression.base.RegressorBase.load', 'RegressorBase.load', (['path'], {}), '(path)\n', (4272, 4278), False, 'from aydin.regression.base import RegressorBase\n'), ((4770, 4845), 'aydin.util.log.log.lsection', 'lsection', (['"""Estimating the amount of memory needed to store feature arrays:"""'], {}), "('Estimating the amount of memory needed to store feature arrays:')\n", (4778, 4845), False, 'from aydin.util.log.log import lprint, lsection\n'), ((4950, 5025), 'numpy.zeros', 'numpy.zeros', ([], {'shape': '((1, 1) + (4,) * num_spatio_temp_dim)', 'dtype': 'numpy.float32'}), '(shape=(1, 1) + (4,) * num_spatio_temp_dim, dtype=numpy.float32)\n', (4961, 5025), False, 'import numpy\n'), ((6454, 6519), 'aydin.util.log.log.lsection', 'lsection', (['f"""Computing features for image of shape {image.shape}:"""'], {}), "(f'Computing features for image of shape {image.shape}:')\n", (6462, 6519), False, 'from aydin.util.log.log import lprint, lsection\n'), ((6893, 6953), 'aydin.util.log.log.lprint', 'lprint', (['f"""exclude_center_feature = {exclude_center_feature}"""'], {}), "(f'exclude_center_feature = {exclude_center_feature}')\n", (6899, 6953), False, 'from aydin.util.log.log import lprint, lsection\n'), ((6966, 7024), 'aydin.util.log.log.lprint', 'lprint', (['f"""exclude_center_value = {exclude_center_value}"""'], {}), "(f'exclude_center_value = {exclude_center_value}')\n", (6972, 7024), False, 'from aydin.util.log.log import lprint, lsection\n'), ((7037, 7090), 'aydin.util.log.log.lprint', 'lprint', (['f"""excluded_voxels = {excluded_voxels}"""'], {}), "(f'excluded_voxels = {excluded_voxels}')\n", (7043, 7090), False, 'from aydin.util.log.log import lprint, lsection\n'), ((7918, 7980), 'aydin.util.log.log.lprint', 'lprint', (['f"""spatial_feature_scale = {spatial_feature_scale}"""'], {}), "(f'spatial_feature_scale = {spatial_feature_scale}')\n", (7924, 7980), False, 'from aydin.util.log.log import lprint, lsection\n'), ((7993, 8056), 'aydin.util.log.log.lprint', 'lprint', (['f"""spatial_feature_offset = {spatial_feature_offset}"""'], {}), "(f'spatial_feature_offset = {spatial_feature_offset}')\n", (7999, 8056), False, 'from aydin.util.log.log import lprint, lsection\n'), ((8925, 9053), 'aydin.util.log.log.lsection', 'lsection', (['f"""Training image translator from image of shape {input_image.shape} to image of shape {target_image.shape}:"""'], {}), "(\n f'Training image translator from image of shape {input_image.shape} to image of shape {target_image.shape}:'\n )\n", (8933, 9053), False, 'from aydin.util.log.log import lprint, lsection\n'), ((10070, 10132), 'aydin.util.log.log.lprint', 'lprint', (['f"""Tilling strategy (just batches): {tilling_strategy}"""'], {}), "(f'Tilling strategy (just batches): {tilling_strategy}')\n", (10076, 10132), False, 'from aydin.util.log.log import lprint, lsection\n'), ((10145, 10186), 'aydin.util.log.log.lprint', 'lprint', (['f"""Margins for tiles: {margins} ."""'], {}), "(f'Margins for tiles: {margins} .')\n", (10151, 10186), False, 'from aydin.util.log.log import lprint, lsection\n'), ((10527, 10581), 'aydin.util.log.log.lprint', 'lprint', (['f"""Number of tiles (slices): {number_of_tiles}"""'], {}), "(f'Number of tiles (slices): {number_of_tiles}')\n", (10533, 10581), False, 'from aydin.util.log.log import lprint, lsection\n'), ((13403, 13428), 'aydin.util.log.log.lprint', 'lprint', (['"""Training now..."""'], {}), "('Training now...')\n", (13409, 13428), False, 'from aydin.util.log.log import lprint, lsection\n'), ((15033, 15044), 'time.time', 'time.time', ([], {}), '()\n', (15042, 15044), False, 'import time\n'), ((19795, 19882), 'aydin.util.log.log.lsection', 'lsection', (['f"""Splitting train and test sets (train_test_ratio={train_valid_ratio}) """'], {}), "(\n f'Splitting train and test sets (train_test_ratio={train_valid_ratio}) ')\n", (19803, 19882), False, 'from aydin.util.log.log import lprint, lsection\n'), ((20197, 20299), 'aydin.util.log.log.lprint', 'lprint', (['f"""Creating random indices for train/val split (nb_split_batches={nb_split_batches})"""'], {}), "(\n f'Creating random indices for train/val split (nb_split_batches={nb_split_batches})'\n )\n", (20203, 20299), False, 'from aydin.util.log.log import lprint, lsection\n'), ((20508, 20543), 'numpy.full', 'numpy.full', (['nb_split_batches', '(False)'], {}), '(nb_split_batches, False)\n', (20518, 20543), False, 'import numpy\n'), ((20615, 20691), 'aydin.util.log.log.lprint', 'lprint', (['f"""train/valid bool array created (length={is_train_array.shape[0]})"""'], {}), "(f'train/valid bool array created (length={is_train_array.shape[0]})')\n", (20621, 20691), False, 'from aydin.util.log.log import lprint, lsection\n'), ((20705, 20750), 'aydin.util.log.log.lprint', 'lprint', (['"""Shuffling train/valid bool array..."""'], {}), "('Shuffling train/valid bool array...')\n", (20711, 20750), False, 'from aydin.util.log.log import lprint, lsection\n'), ((20763, 20799), 'numpy.random.shuffle', 'numpy.random.shuffle', (['is_train_array'], {}), '(is_train_array)\n', (20783, 20799), False, 'import numpy\n'), ((20813, 20880), 'aydin.util.log.log.lprint', 'lprint', (['"""Calculating number of entries for train and validation..."""'], {}), "('Calculating number of entries for train and validation...')\n", (20819, 20880), False, 'from aydin.util.log.log import lprint, lsection\n'), ((21140, 21357), 'aydin.util.log.log.lprint', 'lprint', (['f"""Number of entries for training: {nb_entries_train} = {nb_split_batches_train}*{nb_entries_per_split_batch}, validation: {nb_entries_valid} = {nb_split_batches_valid} * {nb_entries_per_split_batch}"""'], {}), "(\n f'Number of entries for training: {nb_entries_train} = {nb_split_batches_train}*{nb_entries_per_split_batch}, validation: {nb_entries_valid} = {nb_split_batches_valid} * {nb_entries_per_split_batch}'\n )\n", (21146, 21357), False, 'from aydin.util.log.log import lprint, lsection\n'), ((21391, 21421), 'aydin.util.log.log.lprint', 'lprint', (['"""Allocating arrays..."""'], {}), "('Allocating arrays...')\n", (21397, 21421), False, 'from aydin.util.log.log import lprint, lsection\n'), ((21444, 21567), 'aydin.util.offcore.offcore.offcore_array', 'offcore_array', ([], {'shape': '(nb_features, nb_entries_train)', 'dtype': 'x.dtype', 'max_memory_usage_ratio': 'self.max_memory_usage_ratio'}), '(shape=(nb_features, nb_entries_train), dtype=x.dtype,\n max_memory_usage_ratio=self.max_memory_usage_ratio)\n', (21457, 21567), False, 'from aydin.util.offcore.offcore import offcore_array\n'), ((21649, 21780), 'aydin.util.offcore.offcore.offcore_array', 'offcore_array', ([], {'shape': '(num_target_channels, nb_entries_train)', 'dtype': 'y.dtype', 'max_memory_usage_ratio': 'self.max_memory_usage_ratio'}), '(shape=(num_target_channels, nb_entries_train), dtype=y.dtype,\n max_memory_usage_ratio=self.max_memory_usage_ratio)\n', (21662, 21780), False, 'from aydin.util.offcore.offcore import offcore_array\n'), ((21862, 21985), 'aydin.util.offcore.offcore.offcore_array', 'offcore_array', ([], {'shape': '(nb_features, nb_entries_valid)', 'dtype': 'x.dtype', 'max_memory_usage_ratio': 'self.max_memory_usage_ratio'}), '(shape=(nb_features, nb_entries_valid), dtype=x.dtype,\n max_memory_usage_ratio=self.max_memory_usage_ratio)\n', (21875, 21985), False, 'from aydin.util.offcore.offcore import offcore_array\n'), ((22067, 22198), 'aydin.util.offcore.offcore.offcore_array', 'offcore_array', ([], {'shape': '(num_target_channels, nb_entries_valid)', 'dtype': 'y.dtype', 'max_memory_usage_ratio': 'self.max_memory_usage_ratio'}), '(shape=(num_target_channels, nb_entries_valid), dtype=y.dtype,\n max_memory_usage_ratio=self.max_memory_usage_ratio)\n', (22080, 22198), False, 'from aydin.util.offcore.offcore import offcore_array\n'), ((26298, 26393), 'aydin.util.log.log.lsection', 'lsection', (['f"""Predict from feature vector of dimension {x.shape} and dtype: {x.dtype}:"""'], {}), "(\n f'Predict from feature vector of dimension {x.shape} and dtype: {x.dtype}:'\n )\n", (26306, 26393), False, 'from aydin.util.log.log import lprint, lsection\n'), ((26419, 26443), 'aydin.util.log.log.lprint', 'lprint', (['"""Predicting... """'], {}), "('Predicting... ')\n", (26425, 26443), False, 'from aydin.util.log.log import lprint, lsection\n'), ((26941, 26999), 'aydin.util.log.log.lprint', 'lprint', (['f"""Reshaping array to {translated_image_shape}... """'], {}), "(f'Reshaping array to {translated_image_shape}... ')\n", (26947, 26999), False, 'from aydin.util.log.log import lprint, lsection\n'), ((8759, 8783), 'numpy.moveaxis', 'numpy.moveaxis', (['x', '(0)', '(-1)'], {}), '(x, 0, -1)\n', (8773, 8783), False, 'import numpy\n'), ((10291, 10380), 'aydin.util.array.nd.nd_split_slices', 'nd_split_slices', (['normalised_input_shape'], {'nb_slices': 'tilling_strategy', 'margins': 'margins'}), '(normalised_input_shape, nb_slices=tilling_strategy, margins\n =margins)\n', (10306, 10380), False, 'from aydin.util.array.nd import nd_split_slices\n'), ((22276, 22336), 'aydin.util.log.log.lsection', 'lsection', (['"""Copying data for training and validation sets..."""'], {}), "('Copying data for training and validation sets...')\n", (22284, 22336), False, 'from aydin.util.log.log import lprint, lsection\n'), ((22482, 22524), 'numpy.random.permutation', 'numpy.random.permutation', (['nb_split_batches'], {}), '(nb_split_batches)\n', (22506, 22524), False, 'import numpy\n'), ((22720, 22748), 'numpy.nditer', 'numpy.nditer', (['is_train_array'], {}), '(is_train_array)\n', (22732, 22748), False, 'import numpy\n'), ((10781, 10866), 'aydin.util.log.log.lsection', 'lsection', (['f"""Current tile: {idx}/{number_of_tiles}, slice: {slice_margin_tuple} """'], {}), "(f'Current tile: {idx}/{number_of_tiles}, slice: {slice_margin_tuple} '\n )\n", (10789, 10866), False, 'from aydin.util.log.log import lprint, lsection\n'), ((11786, 11953), 'aydin.util.log.log.lprint', 'lprint', (['f"""Number of entries: {num_entries_tile}, features: {num_features_tile}, input channels: {num_input_channels}, target channels: {num_target_channels}"""'], {}), "(\n f'Number of entries: {num_entries_tile}, features: {num_features_tile}, input channels: {num_input_channels}, target channels: {num_target_channels}'\n )\n", (11792, 11953), False, 'from aydin.util.log.log import lprint, lsection\n'), ((12511, 12523), 'gc.collect', 'gc.collect', ([], {}), '()\n', (12521, 12523), False, 'import gc\n'), ((12628, 12663), 'numpy.moveaxis', 'numpy.moveaxis', (['x_train_tile', '(0)', '(-1)'], {}), '(x_train_tile, 0, -1)\n', (12642, 12663), False, 'import numpy\n'), ((12699, 12734), 'numpy.moveaxis', 'numpy.moveaxis', (['x_valid_tile', '(0)', '(-1)'], {}), '(x_valid_tile, 0, -1)\n', (12713, 12734), False, 'import numpy\n'), ((25376, 25475), 'aydin.util.log.log.lprint', 'lprint', (['"""Note: balancer has dropped entries that fell on over-represented histogram bins"""'], {}), "(\n 'Note: balancer has dropped entries that fell on over-represented histogram bins'\n )\n", (25382, 25475), False, 'from aydin.util.log.log import lprint, lsection\n'), ((13112, 13155), 'numpy.append', 'numpy.append', (['x_train', 'x_train_tile'], {'axis': '(0)'}), '(x_train, x_train_tile, axis=0)\n', (13124, 13155), False, 'import numpy\n'), ((13190, 13233), 'numpy.append', 'numpy.append', (['x_valid', 'x_valid_tile'], {'axis': '(0)'}), '(x_valid, x_valid_tile, axis=0)\n', (13202, 13233), False, 'import numpy\n'), ((13268, 13311), 'numpy.append', 'numpy.append', (['y_train', 'y_train_tile'], {'axis': '(1)'}), '(y_train, y_train_tile, axis=1)\n', (13280, 13311), False, 'import numpy\n'), ((13346, 13389), 'numpy.append', 'numpy.append', (['y_valid', 'y_valid_tile'], {'axis': '(1)'}), '(y_valid, y_valid_tile, axis=1)\n', (13358, 13389), False, 'import numpy\n'), ((23769, 23793), 'numpy.copyto', 'numpy.copyto', (['xdst', 'xsrc'], {}), '(xdst, xsrc)\n', (23781, 23793), False, 'import numpy\n'), ((23822, 23846), 'numpy.copyto', 'numpy.copyto', (['ydst', 'ysrc'], {}), '(ydst, ysrc)\n', (23834, 23846), False, 'import numpy\n'), ((24262, 24286), 'numpy.copyto', 'numpy.copyto', (['xdst', 'xsrc'], {}), '(xdst, xsrc)\n', (24274, 24286), False, 'import numpy\n'), ((24315, 24339), 'numpy.copyto', 'numpy.copyto', (['ydst', 'ysrc'], {}), '(ydst, ysrc)\n', (24327, 24339), False, 'import numpy\n')] |
#!/usr/bin/env python
# from __future__ import division
import torch
import math
import random
from PIL import Image, ImageOps, ImageEnhance
import numbers
import torchvision.transforms.functional as F
import numpy as np
class RandomCrop(object):
"""Crop the given PIL Image at a random location.
Args:
size (sequence or int): Desired output size of the crop. If size is an
int instead of sequence like (h, w), a square crop (size, size) is
made.
padding (int or sequence, optional): Optional padding on each border
of the image. Default is 0, i.e no padding. If a sequence of length
4 is provided, it is used to pad left, top, right, bottom borders
respectively.
pad_if_needed (boolean): It will pad the image if smaller than the
desired size to avoid raising an exception.
"""
def __init__(self, size, padding=0, pad_if_needed=False):
if isinstance(size, numbers.Number):
self.size = (int(size), int(size))
else:
self.size = size
self.padding = padding
self.pad_if_needed = pad_if_needed
@staticmethod
def get_params(img, output_size):
"""Get parameters for ``crop`` for a random crop.
Args:
img (PIL Image): Image to be cropped.
output_size (tuple): Expected output size of the crop.
Returns:
tuple: params (i, j, h, w) to be passed to ``crop`` for random crop.
"""
h,w,_ = img.shape
th, tw = output_size
if w == tw and h == th:
return 0, 0, h, w
i = random.randint(0, h - th)
j = random.randint(0, w - tw)
return i, j, th, tw
def __call__(self, img,img_gt):
"""
Args:
img (PIL Image): Image to be cropped.
Returns:
PIL Image: Cropped image.
"""
if self.padding > 0:
img = F.pad(img, self.padding)
# pad the width if needed
if self.pad_if_needed and img.size[0] < self.size[1]:
img = F.pad(img, (int((1 + self.size[1] - img.size[0]) / 2), 0))
# pad the height if needed
if self.pad_if_needed and img.size[1] < self.size[0]:
img = F.pad(img, (0, int((1 + self.size[0] - img.size[1]) / 2)))
i, j, h, w = self.get_params(img, self.size)
return img[i:i+self.size[0],j:j+self.size[1],:],img_gt[i:i+self.size[0],j:j+self.size[1],:]
# return F.crop(img, i, j, h, w),F.crop(img_gt, i, j, h, w)
def __repr__(self):
return self.__class__.__name__ + '(size={0}, padding={1})'.format(self.size, self.padding)
class RandomResizedCrop(object):
"""Crop the given PIL Image to random size and aspect ratio.
A crop of random size (default: of 0.08 to 1.0) of the original size and a random
aspect ratio (default: of 3/4 to 4/3) of the original aspect ratio is made. This crop
is finally resized to given size.
This is popularly used to train the Inception networks.
Args:
size: expected output size of each edge
scale: range of size of the origin size cropped
ratio: range of aspect ratio of the origin aspect ratio cropped
interpolation: Default: PIL.Image.BILINEAR
"""
def __init__(self, size, scale=(0.8, 1), ratio=(3/4., 4/3), interpolation=Image.BICUBIC):
self.size = (size, size)
self.interpolation = interpolation
self.scale = scale
self.ratio = ratio
@staticmethod
def get_params(img, scale, ratio):
"""Get parameters for ``crop`` for a random sized crop.
Args:
img (PIL Image): Image to be cropped.
scale (tuple): range of size of the origin size cropped
ratio (tuple): range of aspect ratio of the origin aspect ratio cropped
Returns:
tuple: params (i, j, h, w) to be passed to ``crop`` for a random
sized crop.
"""
for attempt in range(10):
area = img.size[0] * img.size[1]
target_area = random.uniform(*scale) * area
aspect_ratio = random.uniform(*ratio)
w = int(round(math.sqrt(target_area * aspect_ratio)))
h = int(round(math.sqrt(target_area / aspect_ratio)))
if random.random() < 0.5:
w, h = h, w
if w <= img.size[0] and h <= img.size[1]:
i = random.randint(0, img.size[1] - h)
j = random.randint(0, img.size[0] - w)
return i, j, h, w
# Fallback
w = min(img.size[0], img.size[1])
i = (img.size[1] - w) // 2
j = (img.size[0] - w) // 2
return i, j, w, w
def __call__(self, img,img_gt):
"""
Args:
img (PIL Image): Image to be cropped and resized.
Returns:
PIL Image: Randomly cropped and resized image.
"""
i, j, h, w = self.get_params(img, self.scale, self.ratio)
return (F.resized_crop(img, i, j, h, w, self.size, self.interpolation),F.resized_crop(img_gt, i, j, h, w, self.size, self.interpolation))
def __repr__(self):
interpolate_str = _pil_interpolation_to_str[self.interpolation]
format_string = self.__class__.__name__ + '(size={0}'.format(self.size)
format_string += ', scale={0}'.format(tuple(round(s, 4) for s in self.scale))
format_string += ', ratio={0}'.format(tuple(round(r, 4) for r in self.ratio))
format_string += ', interpolation={0})'.format(interpolate_str)
return format_string
class RandomRotation(object):
"""Rotate the image by angle.
Args:
degrees (sequence or float or int): Range of degrees to select from.
If degrees is a number instead of sequence like (min, max), the range of degrees
will be (-degrees, +degrees).
resample ({PIL.Image.NEAREST, PIL.Image.BILINEAR, PIL.Image.BICUBIC}, optional):
An optional resampling filter.
See http://pillow.readthedocs.io/en/3.4.x/handbook/concepts.html#filters
If omitted, or if the image has mode "1" or "P", it is set to PIL.Image.NEAREST.
expand (bool, optional): Optional expansion flag.
If true, expands the output to make it large enough to hold the entire rotated image.
If false or omitted, make the output image the same size as the input image.
Note that the expand flag assumes rotation around the center and no translation.
center (2-tuple, optional): Optional center of rotation.
Origin is the upper left corner.
Default is the center of the image.
"""
def __init__(self, degrees, resample=Image.BICUBIC, expand=1, center=None):
if isinstance(degrees, numbers.Number):
if degrees < 0:
raise ValueError("If degrees is a single number, it must be positive.")
self.degrees = (-degrees, degrees)
else:
if len(degrees) != 2:
raise ValueError("If degrees is a sequence, it must be of len 2.")
self.degrees = degrees
self.resample = resample
self.expand = expand
self.center = center
@staticmethod
def get_params(degrees):
"""Get parameters for ``rotate`` for a random rotation.
Returns:
sequence: params to be passed to ``rotate`` for random rotation.
"""
angle = np.random.uniform(degrees[0], degrees[1])
return angle
def __call__(self, img,img_gt):
"""
img (PIL Image): Image to be rotated.
Returns:
PIL Image: Rotated image.
"""
angle = self.get_params(self.degrees)
return (F.rotate(img, angle, self.resample, self.expand, self.center),F.rotate(img_gt, angle, self.resample, self.expand, self.center))
def __repr__(self):
return self.__class__.__name__ + '(degrees={0})'.format(self.degrees)
class RandomHorizontallyFlip(object):
def __call__(self, img, mask):
if random.random() < 0.5:
return img.transpose(Image.FLIP_LEFT_RIGHT), mask.transpose(Image.FLIP_LEFT_RIGHT)
return img, mask
class RandomVerticallyFlip(object):
def __call__(self, img, mask):
if random.random() < 0.5:
return img.transpose(Image.FLIP_TOP_BOTTOM), mask.transpose(Image.FLIP_TOP_BOTTOM)
return img, mask | [
"random.uniform",
"math.sqrt",
"torchvision.transforms.functional.pad",
"torchvision.transforms.functional.rotate",
"torchvision.transforms.functional.resized_crop",
"numpy.random.uniform",
"random.random",
"random.randint"
] | [((1649, 1674), 'random.randint', 'random.randint', (['(0)', '(h - th)'], {}), '(0, h - th)\n', (1663, 1674), False, 'import random\n'), ((1687, 1712), 'random.randint', 'random.randint', (['(0)', '(w - tw)'], {}), '(0, w - tw)\n', (1701, 1712), False, 'import random\n'), ((7516, 7557), 'numpy.random.uniform', 'np.random.uniform', (['degrees[0]', 'degrees[1]'], {}), '(degrees[0], degrees[1])\n', (7533, 7557), True, 'import numpy as np\n'), ((1969, 1993), 'torchvision.transforms.functional.pad', 'F.pad', (['img', 'self.padding'], {}), '(img, self.padding)\n', (1974, 1993), True, 'import torchvision.transforms.functional as F\n'), ((4174, 4196), 'random.uniform', 'random.uniform', (['*ratio'], {}), '(*ratio)\n', (4188, 4196), False, 'import random\n'), ((5050, 5112), 'torchvision.transforms.functional.resized_crop', 'F.resized_crop', (['img', 'i', 'j', 'h', 'w', 'self.size', 'self.interpolation'], {}), '(img, i, j, h, w, self.size, self.interpolation)\n', (5064, 5112), True, 'import torchvision.transforms.functional as F\n'), ((5113, 5178), 'torchvision.transforms.functional.resized_crop', 'F.resized_crop', (['img_gt', 'i', 'j', 'h', 'w', 'self.size', 'self.interpolation'], {}), '(img_gt, i, j, h, w, self.size, self.interpolation)\n', (5127, 5178), True, 'import torchvision.transforms.functional as F\n'), ((7811, 7872), 'torchvision.transforms.functional.rotate', 'F.rotate', (['img', 'angle', 'self.resample', 'self.expand', 'self.center'], {}), '(img, angle, self.resample, self.expand, self.center)\n', (7819, 7872), True, 'import torchvision.transforms.functional as F\n'), ((7873, 7937), 'torchvision.transforms.functional.rotate', 'F.rotate', (['img_gt', 'angle', 'self.resample', 'self.expand', 'self.center'], {}), '(img_gt, angle, self.resample, self.expand, self.center)\n', (7881, 7937), True, 'import torchvision.transforms.functional as F\n'), ((8128, 8143), 'random.random', 'random.random', ([], {}), '()\n', (8141, 8143), False, 'import random\n'), ((8354, 8369), 'random.random', 'random.random', ([], {}), '()\n', (8367, 8369), False, 'import random\n'), ((4117, 4139), 'random.uniform', 'random.uniform', (['*scale'], {}), '(*scale)\n', (4131, 4139), False, 'import random\n'), ((4346, 4361), 'random.random', 'random.random', ([], {}), '()\n', (4359, 4361), False, 'import random\n'), ((4472, 4506), 'random.randint', 'random.randint', (['(0)', '(img.size[1] - h)'], {}), '(0, img.size[1] - h)\n', (4486, 4506), False, 'import random\n'), ((4527, 4561), 'random.randint', 'random.randint', (['(0)', '(img.size[0] - w)'], {}), '(0, img.size[0] - w)\n', (4541, 4561), False, 'import random\n'), ((4224, 4261), 'math.sqrt', 'math.sqrt', (['(target_area * aspect_ratio)'], {}), '(target_area * aspect_ratio)\n', (4233, 4261), False, 'import math\n'), ((4290, 4327), 'math.sqrt', 'math.sqrt', (['(target_area / aspect_ratio)'], {}), '(target_area / aspect_ratio)\n', (4299, 4327), False, 'import math\n')] |
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 24 16:57:31 2017
@author: Jean-Michel
"""
import AstarClass as AC
import sys
sys.path.append("../model")
from WeatherClass import Weather
import numpy as np
import SimulatorTLKT as SimC
from SimulatorTLKT import Simulator
import matplotlib.pyplot as plt
import mpl_toolkits
from mpl_toolkits.basemap import Basemap
import matplotlib
from matplotlib import animation
matplotlib.rcParams.update({'font.size': 16})
import copy
import pickle
import sys
sys.path.append("../solver")
from MyTree import Tree
# We load the forecast files
mydate = '20170519'
modelcycle = '00'
pathToSaveObj = '../data/' + mydate + '_' + modelcycle + '.obj'
Wavg = Weather.load(pathToSaveObj)
# We shift the times so that all times are in the correct bounds for interpolations
Tini = Wavg.time[0]
Wavg.time = Wavg.time - Tini
# We set up the parameters of the simulation
# times=np.arange(0,min([Wavg.time[-1],Wspr.time[-1]]),1*HOURS_TO_DAY)
# Tf=len(times)
Tf = 24 * 5
HOURS_TO_DAY = 1/24
times = np.arange(0, Tf * HOURS_TO_DAY, 1 * HOURS_TO_DAY)
lats = np.arange(Wavg.lat[0],Wavg.lat[-1], 0.05)
lons = np.arange(Wavg.lon[0], Wavg.lon[-1], 0.05)
stateInit = [0, 47.5, -3.5 + 360]
SimC.Boat.UNCERTAINTY_COEFF = 0
Sim = Simulator(times, lats, lons, Wavg, stateInit)
# We set up the parameters of the simulation : destination
heading = 230
tra = []
for t in Sim.times[0:5]:
tra.append(list(Sim.doStep(heading)))
destination = copy.copy(Sim.state[1:3])
#destination = [47.45, 356.40]
# %% test unitaires pour la class AstarClass
Sim.reset(stateInit)
solver_iso = AC.Pathfinder(Sim,stateInit[1:3],destination)
# %%
list_voisins = solver_iso.currentvoisin()
for noeud in list_voisins:
print(noeud)
# doit afficher 6 noeuds
solver_iso.openlist = list_voisins
print(solver_iso.petitfopen())
# doit afficher le noeud de plus petit f parmi la liste précédente
#solver_iso.openlist = [noeud]
#for noeud in list_voisins:
# solver_iso.ajout_openlist_trie_par_f_et_g(noeud)
#for noeud in solver_iso.openlist:
# print(noeud)
# doit afficher la liste précédente par ordre de f croissant et si égalité par g décroissant
# %%
noeud_faux = AC.Node(4,5,6)
noeud_vrai = AC.Node(8,list_voisins[3].lat,list_voisins[3].lon)
solver_iso.openlist = list_voisins
fait,noeud_id = solver_iso.testpresopen(noeud_faux)
print(fait)
print(noeud_id)
# doit afficher "false" et "None"
fait,noeud_id = solver_iso.testpresopen(noeud_vrai)
print(fait)
print(noeud_id,'\n',noeud_vrai)
# doit afficher "true" et 2 noeuds avec même lat. et lon. mais temps et val différents
# (le premier à la première liste affichée)
# testpresclose() étant identique à testpresopen(), je ne refais pas les tests
solver_iso.reset()
# %% We do the simulation of isochrone solving
Sim.reset(stateInit)
solver_iso.reset(stateInit[1:3],destination)
politique1 = solver_iso.solver()
print(politique1)
Sim.reset(stateInit)
solver_iso.reset(stateInit[1:3],destination)
#politique2 = solver_iso.solverplus()
#print(politique2)
#le résultat doit être le même pour les 2 politiques mais le temps de calcul peut être pas.
#vitesse max du bateau = 3 m/s ??? | [
"SimulatorTLKT.Simulator",
"matplotlib.rcParams.update",
"AstarClass.Node",
"copy.copy",
"AstarClass.Pathfinder",
"WeatherClass.Weather.load",
"sys.path.append",
"numpy.arange"
] | [((135, 162), 'sys.path.append', 'sys.path.append', (['"""../model"""'], {}), "('../model')\n", (150, 162), False, 'import sys\n'), ((434, 479), 'matplotlib.rcParams.update', 'matplotlib.rcParams.update', (["{'font.size': 16}"], {}), "({'font.size': 16})\n", (460, 479), False, 'import matplotlib\n'), ((523, 551), 'sys.path.append', 'sys.path.append', (['"""../solver"""'], {}), "('../solver')\n", (538, 551), False, 'import sys\n'), ((727, 754), 'WeatherClass.Weather.load', 'Weather.load', (['pathToSaveObj'], {}), '(pathToSaveObj)\n', (739, 754), False, 'from WeatherClass import Weather\n'), ((1077, 1126), 'numpy.arange', 'np.arange', (['(0)', '(Tf * HOURS_TO_DAY)', '(1 * HOURS_TO_DAY)'], {}), '(0, Tf * HOURS_TO_DAY, 1 * HOURS_TO_DAY)\n', (1086, 1126), True, 'import numpy as np\n'), ((1135, 1177), 'numpy.arange', 'np.arange', (['Wavg.lat[0]', 'Wavg.lat[-1]', '(0.05)'], {}), '(Wavg.lat[0], Wavg.lat[-1], 0.05)\n', (1144, 1177), True, 'import numpy as np\n'), ((1185, 1227), 'numpy.arange', 'np.arange', (['Wavg.lon[0]', 'Wavg.lon[-1]', '(0.05)'], {}), '(Wavg.lon[0], Wavg.lon[-1], 0.05)\n', (1194, 1227), True, 'import numpy as np\n'), ((1307, 1352), 'SimulatorTLKT.Simulator', 'Simulator', (['times', 'lats', 'lons', 'Wavg', 'stateInit'], {}), '(times, lats, lons, Wavg, stateInit)\n', (1316, 1352), False, 'from SimulatorTLKT import Simulator\n'), ((1528, 1553), 'copy.copy', 'copy.copy', (['Sim.state[1:3]'], {}), '(Sim.state[1:3])\n', (1537, 1553), False, 'import copy\n'), ((1668, 1715), 'AstarClass.Pathfinder', 'AC.Pathfinder', (['Sim', 'stateInit[1:3]', 'destination'], {}), '(Sim, stateInit[1:3], destination)\n', (1681, 1715), True, 'import AstarClass as AC\n'), ((2262, 2278), 'AstarClass.Node', 'AC.Node', (['(4)', '(5)', '(6)'], {}), '(4, 5, 6)\n', (2269, 2278), True, 'import AstarClass as AC\n'), ((2291, 2343), 'AstarClass.Node', 'AC.Node', (['(8)', 'list_voisins[3].lat', 'list_voisins[3].lon'], {}), '(8, list_voisins[3].lat, list_voisins[3].lon)\n', (2298, 2343), True, 'import AstarClass as AC\n')] |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import ConnectionPatch
from matplotlib.transforms import Bbox
import seaborn as sns
import utils
from utils import filters, maxima, segment, merge
import warnings
def pipeline(img, low, high, roi_percentile=85, focal_scope='global', maxima_areas='small', merge_type='blend',
merge_alpha=0.5, filter_type='percentage', filter_percentage=15, filter_threshold=0.6):
"""
Visualization of the whole workflow. Requires the original image and the high and low res CAMs to work. Performs
the following steps:
1. Applies a filter to blur the high-res map.
2. Extracts the ROI from the low-res map through a percentile.
3. Identifies the focal points of the low-res map by locating it's local maxima.
4. Computes the gradient of the high-res map through a sobel filter.
5. Draws a histogram of the gradient. Only considers areas corresponding to the ROI extracted from the low-res map.
6. Calculates a 'lower' and 'upper' bound on the 25th and 75th percentile, respectively.
7. Performs a region-growing segmentation algorithm on the gradient. The boundaries are the previous percentiles,
while the focal points are set as the initial seeds (from where to start growing).
8. Merges the result of the segmentation with the low-res map.
9. Segments the original image according to the result of the previous merger.
Note: it would be more efficient and elegant if I went for 'axes fraction' instead of 'data' for the coordinates
of the ConnectionPatches, but it's too much of a hassle to change.
:param img: Original RBG image, default shape=(224, 224, 3).
:param low: Low-resolution CAM, default shape=(14, 14).
:param high: High-resolution CAM, default shape=(224, 224).
:param roi_percentile: Percentile based on which the ROI will be extracted. The default percentile=85 means that
the ROI will include the 15% highest-intensity pixels from the low-res map.
:param focal_scope: The scope in which the focal points will be identified. 'global' looks for global maxima, while
'local' looks for local maxima. Accepted values: ['global', 'local']
:param maxima_areas: Specifies the size of the focal points. Two options available: 'small' and 'large'.
:param merge_type: Specifies the method of merging the high-res segment map with the low-res map.
Two methods available: 'blend' and 'multiply'. The first is a possibly weighted linear
combination of the two, while the second simply multiplies them.
:param merge_alpha: If merge_type='blend', alpha regulates the importance of each of the two images (i.e. the low
and the high-res maps). Should be a float in [0, 1]. High values result in more influence from
the high-res map.
:param filter_type: Specifies the method of segmenting the original image based on the combined CAM. Two methods are
available: 'percentage' and 'threshold'. The first keeps a percentage of the original image's
pixels while the second relies solely on the values of the combined CAM exceeding a threshold.
:param filter_percentage: Selects the percentage of pixels to be included in the final segment. Only relevant if
filter_type='percentage'. Should be a number between 0 and 100.
:param filter_threshold: Selects the threshold based on which the final segmentation will be performed. Only pixels
of the combined CAM that have an intensity greater than this threshold will be included.
Based on this mask, the original image will be segmented. Should be a float in [0, 1].
"""
# Value checks
# Categorical arguments
if maxima_areas not in ('small', 'large'):
raise ValueError("available options for maxima_areas are: 'small' and 'large'.")
if merge_type not in ('blend', 'multiply'):
raise ValueError("available options for merge_type are: 'blend' and 'multiply'.")
if filter_type not in ('percentage', 'threshold'):
raise ValueError("vailable options for filter_type are: 'percentage' and 'threshold'.")
# Percentage arguments
if roi_percentile <= 0 or roi_percentile >= 100:
raise ValueError('roi_percentile should be a percentage in (0, 100)')
elif roi_percentile < 1:
warnings.warn('roi_percentile value in [0, 1). Should be defined as a percentage in (0, 100), '
'e.g. If the desired percentage is 13%, pass 33 instead of 0.33!')
if filter_percentage <= 0 or filter_percentage >= 100:
raise ValueError('filter_percentage should be a percentage in (0, 100)')
elif filter_percentage < 1:
warnings.warn('filter_percentage value in [0, 1). Should be defined as a percentage in (0, 100), '
'e.g. If the desired percentage is 13%, pass 33 instead of 0.33!')
# Value arguments
if merge_alpha < 0 or merge_alpha > 1:
raise ValueError('merge_alpha should be a float in [0, 1]')
if filter_threshold < 0 or filter_threshold > 1:
raise ValueError('filter_threshold should be a float in [0, 1]')
# Coordinates of the top/bottom/left/right/middle of the input image
left = (0, img.shape[1] / 2)
right = (img.shape[1], img.shape[1] / 2)
bottom = (img.shape[1] / 2, img.shape[1])
top = (img.shape[1] / 2, 0)
midpoint = (img.shape[1] / 2, img.shape[1] / 2)
# Create two 'blank' images for filling empty positions
blank = np.ones(img[0].shape, dtype=np.uint8)
half_blank = blank[::2]
# Initialize 5x7 grid
fig, ax = plt.subplots(5, 7, figsize=(16, 16))
##############################
######## First column ########
##############################
# Fill first, second, fourth and fifth rows with blank images
ax[0, 0].imshow(blank, alpha=0)
ax[0, 0].axis('off')
ax[1, 0].imshow(blank, alpha=0)
ax[1, 0].axis('off')
ax[3, 0].imshow(blank, alpha=0)
ax[3, 0].axis('off')
ax[4, 0].imshow(half_blank, alpha=0)
ax[4, 0].axis('off')
# Add original image to the third row
ax[2, 0].imshow(img[0], zorder=3)
ax[2, 0].axis('off')
ax[2, 0].set_title('Original image', backgroundcolor='white', zorder=2)
# Three crooked lines starting from the first row, represented by thirteen (!) connection patches
# Connection of 'original image' to 'high-res map'
con1a = ConnectionPatch(xyA=top, xyB=midpoint, coordsA='data', coordsB='data',
axesA=ax[2, 0], axesB=ax[1, 0], color='black', lw=2, zorder=1)
con1b = ConnectionPatch(xyA=midpoint, xyB=left, coordsA='data', coordsB='data',
axesA=ax[1, 0], axesB=ax[1, 1], color='black', lw=2, arrowstyle='->')
# Connection of 'original image' to 'low-res map'
con2a = ConnectionPatch(xyA=bottom, xyB=midpoint, coordsA='data', coordsB='data',
axesA=ax[2, 0], axesB=ax[3, 0], color='black', lw=2)
con2b = ConnectionPatch(xyA=midpoint, xyB=left, coordsA='data', coordsB='data',
axesA=ax[3, 0], axesB=ax[3, 1], color='black', lw=2, arrowstyle='->')
# Connection of 'original image' to 'result'
con3b = ConnectionPatch(xyA=midpoint, xyB=bottom, coordsA='data', coordsB='data',
axesA=ax[1, 0], axesB=ax[0, 0], color='black', lw=2)
con3c = ConnectionPatch(xyA=bottom, xyB=bottom, coordsA='data', coordsB='data',
axesA=ax[0, 0], axesB=ax[0, 1], color='black', lw=2)
con3d = ConnectionPatch(xyA=bottom, xyB=bottom, coordsA='data', coordsB='data',
axesA=ax[0, 1], axesB=ax[0, 2], color='black', lw=2)
con3e = ConnectionPatch(xyA=bottom, xyB=bottom, coordsA='data', coordsB='data',
axesA=ax[0, 2], axesB=ax[0, 3], color='black', lw=2)
con3f = ConnectionPatch(xyA=bottom, xyB=bottom, coordsA='data', coordsB='data',
axesA=ax[0, 3], axesB=ax[0, 4], color='black', lw=2)
con3g = ConnectionPatch(xyA=bottom, xyB=bottom, coordsA='data', coordsB='data',
axesA=ax[0, 4], axesB=ax[0, 5], color='black', lw=2)
con3h = ConnectionPatch(xyA=bottom, xyB=bottom, coordsA='data', coordsB='data',
axesA=ax[0, 5], axesB=ax[0, 6], color='black', lw=2)
con3i = ConnectionPatch(xyA=bottom, xyB=midpoint, coordsA='data', coordsB='data',
axesA=ax[0, 6], axesB=ax[1, 6], color='black', lw=2)
con3k = ConnectionPatch(xyA=midpoint, xyB=midpoint, coordsA='data', coordsB='data',
axesA=ax[1, 6], axesB=ax[2, 6], color='black', lw=2)
con3l = ConnectionPatch(xyA=midpoint, xyB=top, coordsA='data', coordsB='data',
axesA=ax[2, 6], axesB=ax[3, 6], color='black', lw=2, arrowstyle='->', zorder=1)
# Add each patch to its respective axis
ax[2, 0].add_artist(con1a)
ax[1, 0].add_artist(con1b)
ax[2, 0].add_artist(con2a)
ax[3, 0].add_artist(con2b)
ax[1, 0].add_artist(con3b)
ax[0, 0].add_artist(con3c)
ax[0, 1].add_artist(con3d)
ax[0, 2].add_artist(con3e)
ax[0, 3].add_artist(con3f)
ax[0, 4].add_artist(con3g)
ax[0, 5].add_artist(con3h)
ax[0, 6].add_artist(con3i)
ax[1, 6].add_artist(con3k)
ax[2, 6].add_artist(con3l)
###############################
######## Second column ########
###############################
# High-res map on the second line
ax[1, 1].imshow(high)
ax[1, 1].axis('off')
ax[1, 1].set_title('High-res CAM')
# Low-res map on the fourth line
ax[3, 1].imshow(utils.resize(low), zorder=3)
ax[3, 1].axis('off')
ax[3, 1].set_title('Low-res CAM', backgroundcolor='white', zorder=2)
# Fill the first, third and fifth lines with blank images
ax[0, 1].imshow(blank, alpha=0)
ax[0, 1].axis('off')
ax[2, 1].imshow(blank, alpha=0)
ax[2, 1].axis('off')
ax[4, 1].imshow(half_blank, alpha=0)
ax[4, 1].axis('off')
# Four lines represented by eleven (!) connection patches
# Connection of 'high-res map' to 'gradient'
con4 = ConnectionPatch(xyA=right, xyB=left, coordsA='data', coordsB='data',
axesA=ax[1, 1], axesB=ax[1, 2], color='black', lw=2, arrowstyle='->')
# Connection of 'low-res map' to 'roi'
con5a = ConnectionPatch(xyA=top, xyB=midpoint, coordsA='data', coordsB='data',
axesA=ax[3, 1], axesB=ax[2, 1], color='black', lw=2, zorder=1)
con5b = ConnectionPatch(xyA=midpoint, xyB=left, coordsA='data', coordsB='data',
axesA=ax[2, 1], axesB=ax[2, 2], color='black', lw=2, arrowstyle='->')
# Connection of 'low-res map' to 'focal points'
con6 = ConnectionPatch(xyA=right, xyB=left, coordsA='data', coordsB='data',
axesA=ax[3, 1], axesB=ax[3, 2], color='black', lw=2, arrowstyle='->')
# Connection of 'low-res map' to 'merger'
con7a = ConnectionPatch(xyA=bottom, xyB=top, coordsA='data', coordsB='data',
axesA=ax[3, 1], axesB=ax[4, 1], color='black', lw=2, zorder=1)
con7b = ConnectionPatch(xyA=top, xyB=top, coordsA='data', coordsB='data',
axesA=ax[4, 1], axesB=ax[4, 2], color='black', lw=2, zorder=1)
con7c = ConnectionPatch(xyA=top, xyB=top, coordsA='data', coordsB='data',
axesA=ax[4, 2], axesB=ax[4, 3], color='black', lw=2, zorder=1)
con7d = ConnectionPatch(xyA=top, xyB=top, coordsA='data', coordsB='data',
axesA=ax[4, 3], axesB=ax[4, 4], color='black', lw=2, zorder=1)
con7e = ConnectionPatch(xyA=top, xyB=top, coordsA='data', coordsB='data',
axesA=ax[4, 4], axesB=ax[4, 5], color='black', lw=2, zorder=1)
con7f = ConnectionPatch(xyA=top, xyB=bottom, coordsA='data', coordsB='data',
axesA=ax[4, 5], axesB=ax[3, 5], color='black', lw=2, zorder=1, arrowstyle='->')
# Add the patches to their respective axes
ax[1, 1].add_artist(con4)
ax[3, 1].add_artist(con5a)
ax[2, 1].add_artist(con5b)
ax[3, 1].add_artist(con6)
ax[3, 1].add_artist(con7a)
ax[4, 1].add_artist(con7b)
ax[4, 2].add_artist(con7c)
ax[4, 3].add_artist(con7d)
ax[4, 4].add_artist(con7e)
ax[4, 5].add_artist(con7f)
##############################
######## Third column ########
##############################
# High-res blur
blurred = filters.blur(high)
ax[1, 2].imshow(blurred)
ax[1, 2].axis('off')
ax[1, 2].set_title('Blurred')
# Region of Interest
roi = utils.resize(low) > utils.percentile(utils.resize(low), roi_percentile)
a = ax[2, 2].imshow(roi)
ax[2, 2].axis('off')
ax[2, 2].set_title('Region of Interest')
# Focal Points
focal_points = maxima.find_focal_points(low, scope=focal_scope, maxima_areas=maxima_areas)
bg, dots = a.get_cmap().colors[0], a.get_cmap().colors[-1]
ax[3, 2].imshow((blank.reshape(-1, 3) * bg).reshape(img.shape[1], img.shape[1], 3))
ax[3, 2].scatter([x[0] for x in focal_points], [x[1] for x in focal_points], marker='x', s=30, c=dots)
ax[3, 2].axis('off')
ax[3, 2].set_title('Focal Points')
# Fill first and fifth rows with blank images
ax[0, 2].imshow(blank, alpha=0)
ax[0, 2].axis('off')
ax[4, 2].imshow(half_blank, alpha=0)
ax[4, 2].axis('off')
# Three lines represented by five connection patches
con8 = ConnectionPatch(xyA=right, xyB=left, coordsA='data', coordsB='data',
axesA=ax[1, 2], axesB=ax[1, 3], color='black', lw=2, arrowstyle='->')
con9 = ConnectionPatch(xyA=right, xyB=(0, 0.5), coordsA='data', coordsB='axes fraction',
axesA=ax[2, 2], axesB=ax[2, 3], color='black', lw=2, arrowstyle='->')
con10a = ConnectionPatch(xyA=right, xyB=midpoint, coordsA='data', coordsB='data',
axesA=ax[3, 2], axesB=ax[3, 3], color='black', lw=2)
con10b = ConnectionPatch(xyA=midpoint, xyB=midpoint, coordsA='data', coordsB='data',
axesA=ax[3, 3], axesB=ax[3, 4], color='black', lw=2)
con10c = ConnectionPatch(xyA=midpoint, xyB=left, coordsA='data', coordsB='data',
axesA=ax[3, 4], axesB=ax[3, 5], color='black', lw=2, arrowstyle='->')
# Add the patches to their respective axes
ax[1, 2].add_artist(con8)
ax[2, 2].add_artist(con9)
ax[3, 2].add_artist(con10a)
ax[3, 3].add_artist(con10b)
ax[3, 4].add_artist(con10c)
###############################
######## Fourth column ########
###############################
# High-res edge detection
grad = utils.normalize_image(filters.sobel(blurred))
ax[1, 3].imshow(grad)
ax[1, 3].axis('off')
ax[1, 3].set_title('Edge detection')
# Gradient percentiles
roi_grad = grad[roi]
lower = utils.percentile(roi_grad, 25)
upper = utils.percentile(roi_grad, 75)
ax[2, 3] = sns.distplot(roi_grad.ravel(), ax=ax[2, 3])
ax[2, 3].plot([lower, lower], [0, 4], c='C1')
ax[2, 3].plot([upper, upper], [0, 4], c='C1')
ax[2, 3].text(lower, -0.5, 'lower', color='C1', horizontalalignment='center')
ax[2, 3].text(upper, 4.5, 'upper', color='C1', horizontalalignment='center')
ax[2, 3].axis('off')
ttl = ax[2, 3].set_title('Edge Histogram')
ttl.set_bbox(dict(color='white', alpha=0.5, zorder=2))
square_axes(ax[2, 3]) # custom function that shrinks the axis object to a square box
# Fill first, fourth and fifth rows
ax[0, 3].imshow(blank, alpha=0)
ax[0, 3].axis('off')
ax[3, 3].imshow(blank, alpha=0)
ax[3, 3].axis('off')
ax[4, 3].imshow(half_blank, alpha=0)
ax[4, 3].axis('off')
# Three lines represented by four connection patches
con11 = ConnectionPatch(xyA=bottom, xyB=(0.5, 1), coordsA='data', coordsB='axes fraction',
axesA=ax[1, 3], axesB=ax[2, 3], color='black', lw=2, arrowstyle='->')
con12a = ConnectionPatch(xyA=right, xyB=midpoint, coordsA='data', coordsB='data',
axesA=ax[1, 3], axesB=ax[1, 4], color='black', lw=2)
con12b = ConnectionPatch(xyA=midpoint, xyB=top, coordsA='data', coordsB='data',
axesA=ax[1, 4], axesB=ax[2, 4], color='black', lw=2, arrowstyle='->', zorder=1)
con13 = ConnectionPatch(xyA=(1, 0.5), xyB=left, coordsA='axes fraction', coordsB='data',
axesA=ax[2, 3], axesB=ax[2, 4], color='black', lw=2, arrowstyle='->')
# Add the patches to their respective axes
ax[1, 3].add_artist(con11)
ax[1, 3].add_artist(con12a)
ax[1, 4].add_artist(con12b)
ax[2, 3].add_artist(con13)
##############################
######## Fifth column ########
##############################
# Region Growing Segmentation
segm = segment.region_growing(grad, seeds=focal_points, lower=lower, upper=upper)
ax[2, 4].imshow(segm, zorder=3)
ax[2, 4].axis('off')
ttl = ax[2, 4].set_title('Region Growing\nSegmentation')
ttl.set_bbox(dict(color='white', alpha=0.5, zorder=2))
# Fill first, second fourth and fifth rows
ax[0, 4].imshow(blank, alpha=0)
ax[0, 4].axis('off')
ax[1, 4].imshow(blank, alpha=0)
ax[1, 4].axis('off')
ax[3, 4].imshow(blank, alpha=0)
ax[3, 4].axis('off')
ax[4, 4].imshow(half_blank, alpha=0)
ax[4, 4].axis('off')
# Just one connection! :)
con14 = ConnectionPatch(xyA=right, xyB=left, coordsA='data', coordsB='data',
axesA=ax[2, 4], axesB=ax[2, 5], color='black', lw=2, arrowstyle='->')
ax[2, 4].add_artist(con14)
##############################
######## Sixth column ########
##############################
# Add edges and fill small holes
edges = (grad >= upper).astype(float)
roi_edges = edges * roi
segm_with_edges = segm + roi_edges
filled = maxima.remove_small_holes(segm_with_edges)
ax[2, 5].imshow(filled)
ax[2, 5].axis('off')
ax[2, 5].set_title('Remove small holes')
# High-Low merger
merged = merge.merge_images(filled, low, method=merge_type, alpha=merge_alpha)
ax[3, 5].imshow(merged)
ax[3, 5].axis('off')
ttl = ax[3, 5].set_title('High-Low Merger')
ttl.set_bbox(dict(color='white', alpha=0.5, zorder=2))
# Fill remaining rows
ax[0, 5].imshow(blank, alpha=0)
ax[0, 5].axis('off')
ax[1, 5].imshow(blank, alpha=0)
ax[1, 5].axis('off')
ax[3, 5].imshow(blank, alpha=0)
ax[3, 5].axis('off')
ax[4, 5].imshow(half_blank, alpha=0)
ax[4, 5].axis('off')
# Last connection patches...
con15 = ConnectionPatch(xyA=bottom, xyB=top, coordsA='data', coordsB='data',
axesA=ax[2, 5], axesB=ax[3, 5], color='black', lw=2, zorder=-1, arrowstyle='->')
con16 = ConnectionPatch(xyA=right, xyB=left, coordsA='data', coordsB='data',
axesA=ax[3, 5], axesB=ax[3, 6], color='black', lw=2, zorder=-1, arrowstyle='->')
ax[2, 5].add_artist(con15)
ax[3, 5].add_artist(con16)
################################
######## Seventh column ########
################################
# Result
if filter_type == 'percentage':
result = merge.keep_percentage(img, merged, percentage=filter_percentage/100)
else:
result = merge.filter_image(img, merged, threshold=filter_threshold)
ax[3, 6].imshow(result, zorder=3)
ax[3, 6].axis('off')
ttl = ax[3, 6].set_title('Result')
ttl.set_bbox(dict(color='white', alpha=0.5, zorder=2))
# Fill remaining rows
ax[0, 6].imshow(blank, alpha=0)
ax[0, 6].axis('off')
ax[1, 6].imshow(blank, alpha=0)
ax[1, 6].axis('off')
ax[2, 6].imshow(blank, alpha=0)
ax[2, 6].axis('off')
ax[4, 6].imshow(half_blank, alpha=0)
ax[4, 6].axis('off')
def plt_to_static(axes):
"""
Should convert an axis object to an image in a numpy.array. Doesn't work as intended!
:param axes: A matplotlib.axes.Axes object
:return: The same object as a numpy.array
"""
fig = plt.figure()
fig.axes.append(axes)
fig.canvas.draw()
buf = fig.canvas.tostring_rgb()
width, height = fig.canvas.get_width_height()
return np.frombuffer(buf, dtype=np.uint8).reshape(height, width, 3)
def square_axes(axes):
"""
Takes a matplotlib.axes.Axes object, finds its height and width and shrinks the largest dimension to match the
smallest one. Caution: it actually changes the object (in-place)!
:param axes: A matplotlib.axes.Axes object.
:return: The new Bbox coordinates.
"""
bbox = axes.get_position()._points.copy()
width = bbox[1, 0] - bbox[0, 0]
height = bbox[1, 1] - bbox[0, 1]
if width < height:
center = bbox[0, 1] + height / 2
bbox[0, 1] = center - width / 2
bbox[1, 1] = center + width / 2
else:
center = bbox[0, 0] + width / 2
bbox[0, 0] = center - height / 2
bbox[1, 0] = center + height / 2
axes.set_position(Bbox(bbox))
return bbox
| [
"utils.filters.blur",
"numpy.ones",
"utils.percentile",
"utils.resize",
"utils.maxima.remove_small_holes",
"utils.merge.merge_images",
"utils.merge.keep_percentage",
"matplotlib.transforms.Bbox",
"matplotlib.pyplot.figure",
"utils.segment.region_growing",
"matplotlib.patches.ConnectionPatch",
... | [((5729, 5766), 'numpy.ones', 'np.ones', (['img[0].shape'], {'dtype': 'np.uint8'}), '(img[0].shape, dtype=np.uint8)\n', (5736, 5766), True, 'import numpy as np\n'), ((5836, 5872), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(5)', '(7)'], {'figsize': '(16, 16)'}), '(5, 7, figsize=(16, 16))\n', (5848, 5872), True, 'import matplotlib.pyplot as plt\n'), ((6647, 6784), 'matplotlib.patches.ConnectionPatch', 'ConnectionPatch', ([], {'xyA': 'top', 'xyB': 'midpoint', 'coordsA': '"""data"""', 'coordsB': '"""data"""', 'axesA': 'ax[2, 0]', 'axesB': 'ax[1, 0]', 'color': '"""black"""', 'lw': '(2)', 'zorder': '(1)'}), "(xyA=top, xyB=midpoint, coordsA='data', coordsB='data',\n axesA=ax[2, 0], axesB=ax[1, 0], color='black', lw=2, zorder=1)\n", (6662, 6784), False, 'from matplotlib.patches import ConnectionPatch\n'), ((6821, 6966), 'matplotlib.patches.ConnectionPatch', 'ConnectionPatch', ([], {'xyA': 'midpoint', 'xyB': 'left', 'coordsA': '"""data"""', 'coordsB': '"""data"""', 'axesA': 'ax[1, 0]', 'axesB': 'ax[1, 1]', 'color': '"""black"""', 'lw': '(2)', 'arrowstyle': '"""->"""'}), "(xyA=midpoint, xyB=left, coordsA='data', coordsB='data',\n axesA=ax[1, 0], axesB=ax[1, 1], color='black', lw=2, arrowstyle='->')\n", (6836, 6966), False, 'from matplotlib.patches import ConnectionPatch\n'), ((7058, 7188), 'matplotlib.patches.ConnectionPatch', 'ConnectionPatch', ([], {'xyA': 'bottom', 'xyB': 'midpoint', 'coordsA': '"""data"""', 'coordsB': '"""data"""', 'axesA': 'ax[2, 0]', 'axesB': 'ax[3, 0]', 'color': '"""black"""', 'lw': '(2)'}), "(xyA=bottom, xyB=midpoint, coordsA='data', coordsB='data',\n axesA=ax[2, 0], axesB=ax[3, 0], color='black', lw=2)\n", (7073, 7188), False, 'from matplotlib.patches import ConnectionPatch\n'), ((7225, 7370), 'matplotlib.patches.ConnectionPatch', 'ConnectionPatch', ([], {'xyA': 'midpoint', 'xyB': 'left', 'coordsA': '"""data"""', 'coordsB': '"""data"""', 'axesA': 'ax[3, 0]', 'axesB': 'ax[3, 1]', 'color': '"""black"""', 'lw': '(2)', 'arrowstyle': '"""->"""'}), "(xyA=midpoint, xyB=left, coordsA='data', coordsB='data',\n axesA=ax[3, 0], axesB=ax[3, 1], color='black', lw=2, arrowstyle='->')\n", (7240, 7370), False, 'from matplotlib.patches import ConnectionPatch\n'), ((7457, 7587), 'matplotlib.patches.ConnectionPatch', 'ConnectionPatch', ([], {'xyA': 'midpoint', 'xyB': 'bottom', 'coordsA': '"""data"""', 'coordsB': '"""data"""', 'axesA': 'ax[1, 0]', 'axesB': 'ax[0, 0]', 'color': '"""black"""', 'lw': '(2)'}), "(xyA=midpoint, xyB=bottom, coordsA='data', coordsB='data',\n axesA=ax[1, 0], axesB=ax[0, 0], color='black', lw=2)\n", (7472, 7587), False, 'from matplotlib.patches import ConnectionPatch\n'), ((7624, 7752), 'matplotlib.patches.ConnectionPatch', 'ConnectionPatch', ([], {'xyA': 'bottom', 'xyB': 'bottom', 'coordsA': '"""data"""', 'coordsB': '"""data"""', 'axesA': 'ax[0, 0]', 'axesB': 'ax[0, 1]', 'color': '"""black"""', 'lw': '(2)'}), "(xyA=bottom, xyB=bottom, coordsA='data', coordsB='data',\n axesA=ax[0, 0], axesB=ax[0, 1], color='black', lw=2)\n", (7639, 7752), False, 'from matplotlib.patches import ConnectionPatch\n'), ((7789, 7917), 'matplotlib.patches.ConnectionPatch', 'ConnectionPatch', ([], {'xyA': 'bottom', 'xyB': 'bottom', 'coordsA': '"""data"""', 'coordsB': '"""data"""', 'axesA': 'ax[0, 1]', 'axesB': 'ax[0, 2]', 'color': '"""black"""', 'lw': '(2)'}), "(xyA=bottom, xyB=bottom, coordsA='data', coordsB='data',\n axesA=ax[0, 1], axesB=ax[0, 2], color='black', lw=2)\n", (7804, 7917), False, 'from matplotlib.patches import ConnectionPatch\n'), ((7954, 8082), 'matplotlib.patches.ConnectionPatch', 'ConnectionPatch', ([], {'xyA': 'bottom', 'xyB': 'bottom', 'coordsA': '"""data"""', 'coordsB': '"""data"""', 'axesA': 'ax[0, 2]', 'axesB': 'ax[0, 3]', 'color': '"""black"""', 'lw': '(2)'}), "(xyA=bottom, xyB=bottom, coordsA='data', coordsB='data',\n axesA=ax[0, 2], axesB=ax[0, 3], color='black', lw=2)\n", (7969, 8082), False, 'from matplotlib.patches import ConnectionPatch\n'), ((8119, 8247), 'matplotlib.patches.ConnectionPatch', 'ConnectionPatch', ([], {'xyA': 'bottom', 'xyB': 'bottom', 'coordsA': '"""data"""', 'coordsB': '"""data"""', 'axesA': 'ax[0, 3]', 'axesB': 'ax[0, 4]', 'color': '"""black"""', 'lw': '(2)'}), "(xyA=bottom, xyB=bottom, coordsA='data', coordsB='data',\n axesA=ax[0, 3], axesB=ax[0, 4], color='black', lw=2)\n", (8134, 8247), False, 'from matplotlib.patches import ConnectionPatch\n'), ((8284, 8412), 'matplotlib.patches.ConnectionPatch', 'ConnectionPatch', ([], {'xyA': 'bottom', 'xyB': 'bottom', 'coordsA': '"""data"""', 'coordsB': '"""data"""', 'axesA': 'ax[0, 4]', 'axesB': 'ax[0, 5]', 'color': '"""black"""', 'lw': '(2)'}), "(xyA=bottom, xyB=bottom, coordsA='data', coordsB='data',\n axesA=ax[0, 4], axesB=ax[0, 5], color='black', lw=2)\n", (8299, 8412), False, 'from matplotlib.patches import ConnectionPatch\n'), ((8449, 8577), 'matplotlib.patches.ConnectionPatch', 'ConnectionPatch', ([], {'xyA': 'bottom', 'xyB': 'bottom', 'coordsA': '"""data"""', 'coordsB': '"""data"""', 'axesA': 'ax[0, 5]', 'axesB': 'ax[0, 6]', 'color': '"""black"""', 'lw': '(2)'}), "(xyA=bottom, xyB=bottom, coordsA='data', coordsB='data',\n axesA=ax[0, 5], axesB=ax[0, 6], color='black', lw=2)\n", (8464, 8577), False, 'from matplotlib.patches import ConnectionPatch\n'), ((8614, 8744), 'matplotlib.patches.ConnectionPatch', 'ConnectionPatch', ([], {'xyA': 'bottom', 'xyB': 'midpoint', 'coordsA': '"""data"""', 'coordsB': '"""data"""', 'axesA': 'ax[0, 6]', 'axesB': 'ax[1, 6]', 'color': '"""black"""', 'lw': '(2)'}), "(xyA=bottom, xyB=midpoint, coordsA='data', coordsB='data',\n axesA=ax[0, 6], axesB=ax[1, 6], color='black', lw=2)\n", (8629, 8744), False, 'from matplotlib.patches import ConnectionPatch\n'), ((8781, 8913), 'matplotlib.patches.ConnectionPatch', 'ConnectionPatch', ([], {'xyA': 'midpoint', 'xyB': 'midpoint', 'coordsA': '"""data"""', 'coordsB': '"""data"""', 'axesA': 'ax[1, 6]', 'axesB': 'ax[2, 6]', 'color': '"""black"""', 'lw': '(2)'}), "(xyA=midpoint, xyB=midpoint, coordsA='data', coordsB='data',\n axesA=ax[1, 6], axesB=ax[2, 6], color='black', lw=2)\n", (8796, 8913), False, 'from matplotlib.patches import ConnectionPatch\n'), ((8950, 9108), 'matplotlib.patches.ConnectionPatch', 'ConnectionPatch', ([], {'xyA': 'midpoint', 'xyB': 'top', 'coordsA': '"""data"""', 'coordsB': '"""data"""', 'axesA': 'ax[2, 6]', 'axesB': 'ax[3, 6]', 'color': '"""black"""', 'lw': '(2)', 'arrowstyle': '"""->"""', 'zorder': '(1)'}), "(xyA=midpoint, xyB=top, coordsA='data', coordsB='data',\n axesA=ax[2, 6], axesB=ax[3, 6], color='black', lw=2, arrowstyle='->',\n zorder=1)\n", (8965, 9108), False, 'from matplotlib.patches import ConnectionPatch\n'), ((10407, 10550), 'matplotlib.patches.ConnectionPatch', 'ConnectionPatch', ([], {'xyA': 'right', 'xyB': 'left', 'coordsA': '"""data"""', 'coordsB': '"""data"""', 'axesA': 'ax[1, 1]', 'axesB': 'ax[1, 2]', 'color': '"""black"""', 'lw': '(2)', 'arrowstyle': '"""->"""'}), "(xyA=right, xyB=left, coordsA='data', coordsB='data', axesA=\n ax[1, 1], axesB=ax[1, 2], color='black', lw=2, arrowstyle='->')\n", (10422, 10550), False, 'from matplotlib.patches import ConnectionPatch\n'), ((10629, 10766), 'matplotlib.patches.ConnectionPatch', 'ConnectionPatch', ([], {'xyA': 'top', 'xyB': 'midpoint', 'coordsA': '"""data"""', 'coordsB': '"""data"""', 'axesA': 'ax[3, 1]', 'axesB': 'ax[2, 1]', 'color': '"""black"""', 'lw': '(2)', 'zorder': '(1)'}), "(xyA=top, xyB=midpoint, coordsA='data', coordsB='data',\n axesA=ax[3, 1], axesB=ax[2, 1], color='black', lw=2, zorder=1)\n", (10644, 10766), False, 'from matplotlib.patches import ConnectionPatch\n'), ((10803, 10948), 'matplotlib.patches.ConnectionPatch', 'ConnectionPatch', ([], {'xyA': 'midpoint', 'xyB': 'left', 'coordsA': '"""data"""', 'coordsB': '"""data"""', 'axesA': 'ax[2, 1]', 'axesB': 'ax[2, 2]', 'color': '"""black"""', 'lw': '(2)', 'arrowstyle': '"""->"""'}), "(xyA=midpoint, xyB=left, coordsA='data', coordsB='data',\n axesA=ax[2, 1], axesB=ax[2, 2], color='black', lw=2, arrowstyle='->')\n", (10818, 10948), False, 'from matplotlib.patches import ConnectionPatch\n'), ((11037, 11180), 'matplotlib.patches.ConnectionPatch', 'ConnectionPatch', ([], {'xyA': 'right', 'xyB': 'left', 'coordsA': '"""data"""', 'coordsB': '"""data"""', 'axesA': 'ax[3, 1]', 'axesB': 'ax[3, 2]', 'color': '"""black"""', 'lw': '(2)', 'arrowstyle': '"""->"""'}), "(xyA=right, xyB=left, coordsA='data', coordsB='data', axesA=\n ax[3, 1], axesB=ax[3, 2], color='black', lw=2, arrowstyle='->')\n", (11052, 11180), False, 'from matplotlib.patches import ConnectionPatch\n'), ((11262, 11398), 'matplotlib.patches.ConnectionPatch', 'ConnectionPatch', ([], {'xyA': 'bottom', 'xyB': 'top', 'coordsA': '"""data"""', 'coordsB': '"""data"""', 'axesA': 'ax[3, 1]', 'axesB': 'ax[4, 1]', 'color': '"""black"""', 'lw': '(2)', 'zorder': '(1)'}), "(xyA=bottom, xyB=top, coordsA='data', coordsB='data', axesA=\n ax[3, 1], axesB=ax[4, 1], color='black', lw=2, zorder=1)\n", (11277, 11398), False, 'from matplotlib.patches import ConnectionPatch\n'), ((11434, 11567), 'matplotlib.patches.ConnectionPatch', 'ConnectionPatch', ([], {'xyA': 'top', 'xyB': 'top', 'coordsA': '"""data"""', 'coordsB': '"""data"""', 'axesA': 'ax[4, 1]', 'axesB': 'ax[4, 2]', 'color': '"""black"""', 'lw': '(2)', 'zorder': '(1)'}), "(xyA=top, xyB=top, coordsA='data', coordsB='data', axesA=ax[\n 4, 1], axesB=ax[4, 2], color='black', lw=2, zorder=1)\n", (11449, 11567), False, 'from matplotlib.patches import ConnectionPatch\n'), ((11603, 11736), 'matplotlib.patches.ConnectionPatch', 'ConnectionPatch', ([], {'xyA': 'top', 'xyB': 'top', 'coordsA': '"""data"""', 'coordsB': '"""data"""', 'axesA': 'ax[4, 2]', 'axesB': 'ax[4, 3]', 'color': '"""black"""', 'lw': '(2)', 'zorder': '(1)'}), "(xyA=top, xyB=top, coordsA='data', coordsB='data', axesA=ax[\n 4, 2], axesB=ax[4, 3], color='black', lw=2, zorder=1)\n", (11618, 11736), False, 'from matplotlib.patches import ConnectionPatch\n'), ((11772, 11905), 'matplotlib.patches.ConnectionPatch', 'ConnectionPatch', ([], {'xyA': 'top', 'xyB': 'top', 'coordsA': '"""data"""', 'coordsB': '"""data"""', 'axesA': 'ax[4, 3]', 'axesB': 'ax[4, 4]', 'color': '"""black"""', 'lw': '(2)', 'zorder': '(1)'}), "(xyA=top, xyB=top, coordsA='data', coordsB='data', axesA=ax[\n 4, 3], axesB=ax[4, 4], color='black', lw=2, zorder=1)\n", (11787, 11905), False, 'from matplotlib.patches import ConnectionPatch\n'), ((11941, 12074), 'matplotlib.patches.ConnectionPatch', 'ConnectionPatch', ([], {'xyA': 'top', 'xyB': 'top', 'coordsA': '"""data"""', 'coordsB': '"""data"""', 'axesA': 'ax[4, 4]', 'axesB': 'ax[4, 5]', 'color': '"""black"""', 'lw': '(2)', 'zorder': '(1)'}), "(xyA=top, xyB=top, coordsA='data', coordsB='data', axesA=ax[\n 4, 4], axesB=ax[4, 5], color='black', lw=2, zorder=1)\n", (11956, 12074), False, 'from matplotlib.patches import ConnectionPatch\n'), ((12110, 12263), 'matplotlib.patches.ConnectionPatch', 'ConnectionPatch', ([], {'xyA': 'top', 'xyB': 'bottom', 'coordsA': '"""data"""', 'coordsB': '"""data"""', 'axesA': 'ax[4, 5]', 'axesB': 'ax[3, 5]', 'color': '"""black"""', 'lw': '(2)', 'zorder': '(1)', 'arrowstyle': '"""->"""'}), "(xyA=top, xyB=bottom, coordsA='data', coordsB='data', axesA=\n ax[4, 5], axesB=ax[3, 5], color='black', lw=2, zorder=1, arrowstyle='->')\n", (12125, 12263), False, 'from matplotlib.patches import ConnectionPatch\n'), ((12784, 12802), 'utils.filters.blur', 'filters.blur', (['high'], {}), '(high)\n', (12796, 12802), False, 'from utils import filters, maxima, segment, merge\n'), ((13137, 13212), 'utils.maxima.find_focal_points', 'maxima.find_focal_points', (['low'], {'scope': 'focal_scope', 'maxima_areas': 'maxima_areas'}), '(low, scope=focal_scope, maxima_areas=maxima_areas)\n', (13161, 13212), False, 'from utils import filters, maxima, segment, merge\n'), ((13782, 13925), 'matplotlib.patches.ConnectionPatch', 'ConnectionPatch', ([], {'xyA': 'right', 'xyB': 'left', 'coordsA': '"""data"""', 'coordsB': '"""data"""', 'axesA': 'ax[1, 2]', 'axesB': 'ax[1, 3]', 'color': '"""black"""', 'lw': '(2)', 'arrowstyle': '"""->"""'}), "(xyA=right, xyB=left, coordsA='data', coordsB='data', axesA=\n ax[1, 2], axesB=ax[1, 3], color='black', lw=2, arrowstyle='->')\n", (13797, 13925), False, 'from matplotlib.patches import ConnectionPatch\n'), ((13959, 14119), 'matplotlib.patches.ConnectionPatch', 'ConnectionPatch', ([], {'xyA': 'right', 'xyB': '(0, 0.5)', 'coordsA': '"""data"""', 'coordsB': '"""axes fraction"""', 'axesA': 'ax[2, 2]', 'axesB': 'ax[2, 3]', 'color': '"""black"""', 'lw': '(2)', 'arrowstyle': '"""->"""'}), "(xyA=right, xyB=(0, 0.5), coordsA='data', coordsB=\n 'axes fraction', axesA=ax[2, 2], axesB=ax[2, 3], color='black', lw=2,\n arrowstyle='->')\n", (13974, 14119), False, 'from matplotlib.patches import ConnectionPatch\n'), ((14151, 14280), 'matplotlib.patches.ConnectionPatch', 'ConnectionPatch', ([], {'xyA': 'right', 'xyB': 'midpoint', 'coordsA': '"""data"""', 'coordsB': '"""data"""', 'axesA': 'ax[3, 2]', 'axesB': 'ax[3, 3]', 'color': '"""black"""', 'lw': '(2)'}), "(xyA=right, xyB=midpoint, coordsA='data', coordsB='data',\n axesA=ax[3, 2], axesB=ax[3, 3], color='black', lw=2)\n", (14166, 14280), False, 'from matplotlib.patches import ConnectionPatch\n'), ((14319, 14451), 'matplotlib.patches.ConnectionPatch', 'ConnectionPatch', ([], {'xyA': 'midpoint', 'xyB': 'midpoint', 'coordsA': '"""data"""', 'coordsB': '"""data"""', 'axesA': 'ax[3, 3]', 'axesB': 'ax[3, 4]', 'color': '"""black"""', 'lw': '(2)'}), "(xyA=midpoint, xyB=midpoint, coordsA='data', coordsB='data',\n axesA=ax[3, 3], axesB=ax[3, 4], color='black', lw=2)\n", (14334, 14451), False, 'from matplotlib.patches import ConnectionPatch\n'), ((14490, 14635), 'matplotlib.patches.ConnectionPatch', 'ConnectionPatch', ([], {'xyA': 'midpoint', 'xyB': 'left', 'coordsA': '"""data"""', 'coordsB': '"""data"""', 'axesA': 'ax[3, 4]', 'axesB': 'ax[3, 5]', 'color': '"""black"""', 'lw': '(2)', 'arrowstyle': '"""->"""'}), "(xyA=midpoint, xyB=left, coordsA='data', coordsB='data',\n axesA=ax[3, 4], axesB=ax[3, 5], color='black', lw=2, arrowstyle='->')\n", (14505, 14635), False, 'from matplotlib.patches import ConnectionPatch\n'), ((15219, 15249), 'utils.percentile', 'utils.percentile', (['roi_grad', '(25)'], {}), '(roi_grad, 25)\n', (15235, 15249), False, 'import utils\n'), ((15262, 15292), 'utils.percentile', 'utils.percentile', (['roi_grad', '(75)'], {}), '(roi_grad, 75)\n', (15278, 15292), False, 'import utils\n'), ((16135, 16296), 'matplotlib.patches.ConnectionPatch', 'ConnectionPatch', ([], {'xyA': 'bottom', 'xyB': '(0.5, 1)', 'coordsA': '"""data"""', 'coordsB': '"""axes fraction"""', 'axesA': 'ax[1, 3]', 'axesB': 'ax[2, 3]', 'color': '"""black"""', 'lw': '(2)', 'arrowstyle': '"""->"""'}), "(xyA=bottom, xyB=(0.5, 1), coordsA='data', coordsB=\n 'axes fraction', axesA=ax[1, 3], axesB=ax[2, 3], color='black', lw=2,\n arrowstyle='->')\n", (16150, 16296), False, 'from matplotlib.patches import ConnectionPatch\n'), ((16329, 16458), 'matplotlib.patches.ConnectionPatch', 'ConnectionPatch', ([], {'xyA': 'right', 'xyB': 'midpoint', 'coordsA': '"""data"""', 'coordsB': '"""data"""', 'axesA': 'ax[1, 3]', 'axesB': 'ax[1, 4]', 'color': '"""black"""', 'lw': '(2)'}), "(xyA=right, xyB=midpoint, coordsA='data', coordsB='data',\n axesA=ax[1, 3], axesB=ax[1, 4], color='black', lw=2)\n", (16344, 16458), False, 'from matplotlib.patches import ConnectionPatch\n'), ((16497, 16655), 'matplotlib.patches.ConnectionPatch', 'ConnectionPatch', ([], {'xyA': 'midpoint', 'xyB': 'top', 'coordsA': '"""data"""', 'coordsB': '"""data"""', 'axesA': 'ax[1, 4]', 'axesB': 'ax[2, 4]', 'color': '"""black"""', 'lw': '(2)', 'arrowstyle': '"""->"""', 'zorder': '(1)'}), "(xyA=midpoint, xyB=top, coordsA='data', coordsB='data',\n axesA=ax[1, 4], axesB=ax[2, 4], color='black', lw=2, arrowstyle='->',\n zorder=1)\n", (16512, 16655), False, 'from matplotlib.patches import ConnectionPatch\n'), ((16690, 16850), 'matplotlib.patches.ConnectionPatch', 'ConnectionPatch', ([], {'xyA': '(1, 0.5)', 'xyB': 'left', 'coordsA': '"""axes fraction"""', 'coordsB': '"""data"""', 'axesA': 'ax[2, 3]', 'axesB': 'ax[2, 4]', 'color': '"""black"""', 'lw': '(2)', 'arrowstyle': '"""->"""'}), "(xyA=(1, 0.5), xyB=left, coordsA='axes fraction', coordsB=\n 'data', axesA=ax[2, 3], axesB=ax[2, 4], color='black', lw=2, arrowstyle\n ='->')\n", (16705, 16850), False, 'from matplotlib.patches import ConnectionPatch\n'), ((17195, 17269), 'utils.segment.region_growing', 'segment.region_growing', (['grad'], {'seeds': 'focal_points', 'lower': 'lower', 'upper': 'upper'}), '(grad, seeds=focal_points, lower=lower, upper=upper)\n', (17217, 17269), False, 'from utils import filters, maxima, segment, merge\n'), ((17791, 17934), 'matplotlib.patches.ConnectionPatch', 'ConnectionPatch', ([], {'xyA': 'right', 'xyB': 'left', 'coordsA': '"""data"""', 'coordsB': '"""data"""', 'axesA': 'ax[2, 4]', 'axesB': 'ax[2, 5]', 'color': '"""black"""', 'lw': '(2)', 'arrowstyle': '"""->"""'}), "(xyA=right, xyB=left, coordsA='data', coordsB='data', axesA=\n ax[2, 4], axesB=ax[2, 5], color='black', lw=2, arrowstyle='->')\n", (17806, 17934), False, 'from matplotlib.patches import ConnectionPatch\n'), ((18256, 18298), 'utils.maxima.remove_small_holes', 'maxima.remove_small_holes', (['segm_with_edges'], {}), '(segm_with_edges)\n', (18281, 18298), False, 'from utils import filters, maxima, segment, merge\n'), ((18433, 18502), 'utils.merge.merge_images', 'merge.merge_images', (['filled', 'low'], {'method': 'merge_type', 'alpha': 'merge_alpha'}), '(filled, low, method=merge_type, alpha=merge_alpha)\n', (18451, 18502), False, 'from utils import filters, maxima, segment, merge\n'), ((18985, 19139), 'matplotlib.patches.ConnectionPatch', 'ConnectionPatch', ([], {'xyA': 'bottom', 'xyB': 'top', 'coordsA': '"""data"""', 'coordsB': '"""data"""', 'axesA': 'ax[2, 5]', 'axesB': 'ax[3, 5]', 'color': '"""black"""', 'lw': '(2)', 'zorder': '(-1)', 'arrowstyle': '"""->"""'}), "(xyA=bottom, xyB=top, coordsA='data', coordsB='data', axesA=\n ax[2, 5], axesB=ax[3, 5], color='black', lw=2, zorder=-1, arrowstyle='->')\n", (19000, 19139), False, 'from matplotlib.patches import ConnectionPatch\n'), ((19175, 19329), 'matplotlib.patches.ConnectionPatch', 'ConnectionPatch', ([], {'xyA': 'right', 'xyB': 'left', 'coordsA': '"""data"""', 'coordsB': '"""data"""', 'axesA': 'ax[3, 5]', 'axesB': 'ax[3, 6]', 'color': '"""black"""', 'lw': '(2)', 'zorder': '(-1)', 'arrowstyle': '"""->"""'}), "(xyA=right, xyB=left, coordsA='data', coordsB='data', axesA=\n ax[3, 5], axesB=ax[3, 6], color='black', lw=2, zorder=-1, arrowstyle='->')\n", (19190, 19329), False, 'from matplotlib.patches import ConnectionPatch\n'), ((20424, 20436), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (20434, 20436), True, 'import matplotlib.pyplot as plt\n'), ((9906, 9923), 'utils.resize', 'utils.resize', (['low'], {}), '(low)\n', (9918, 9923), False, 'import utils\n'), ((12927, 12944), 'utils.resize', 'utils.resize', (['low'], {}), '(low)\n', (12939, 12944), False, 'import utils\n'), ((15038, 15060), 'utils.filters.sobel', 'filters.sobel', (['blurred'], {}), '(blurred)\n', (15051, 15060), False, 'from utils import filters, maxima, segment, merge\n'), ((19595, 19665), 'utils.merge.keep_percentage', 'merge.keep_percentage', (['img', 'merged'], {'percentage': '(filter_percentage / 100)'}), '(img, merged, percentage=filter_percentage / 100)\n', (19616, 19665), False, 'from utils import filters, maxima, segment, merge\n'), ((19691, 19750), 'utils.merge.filter_image', 'merge.filter_image', (['img', 'merged'], {'threshold': 'filter_threshold'}), '(img, merged, threshold=filter_threshold)\n', (19709, 19750), False, 'from utils import filters, maxima, segment, merge\n'), ((21376, 21386), 'matplotlib.transforms.Bbox', 'Bbox', (['bbox'], {}), '(bbox)\n', (21380, 21386), False, 'from matplotlib.transforms import Bbox\n'), ((4559, 4728), 'warnings.warn', 'warnings.warn', (['"""roi_percentile value in [0, 1). Should be defined as a percentage in (0, 100), e.g. If the desired percentage is 13%, pass 33 instead of 0.33!"""'], {}), "(\n 'roi_percentile value in [0, 1). Should be defined as a percentage in (0, 100), e.g. If the desired percentage is 13%, pass 33 instead of 0.33!'\n )\n", (4572, 4728), False, 'import warnings\n'), ((4925, 5097), 'warnings.warn', 'warnings.warn', (['"""filter_percentage value in [0, 1). Should be defined as a percentage in (0, 100), e.g. If the desired percentage is 13%, pass 33 instead of 0.33!"""'], {}), "(\n 'filter_percentage value in [0, 1). Should be defined as a percentage in (0, 100), e.g. If the desired percentage is 13%, pass 33 instead of 0.33!'\n )\n", (4938, 5097), False, 'import warnings\n'), ((12964, 12981), 'utils.resize', 'utils.resize', (['low'], {}), '(low)\n', (12976, 12981), False, 'import utils\n'), ((20582, 20616), 'numpy.frombuffer', 'np.frombuffer', (['buf'], {'dtype': 'np.uint8'}), '(buf, dtype=np.uint8)\n', (20595, 20616), True, 'import numpy as np\n')] |
import sys
import numpy
import six.moves
import cellprofiler_core.image
import cellprofiler.modules.measuregranularity
import cellprofiler_core.object
import cellprofiler_core.pipeline
import cellprofiler_core.workspace
import tests.modules
print((sys.path))
IMAGE_NAME = "myimage"
OBJECTS_NAME = "myobjects"
def test_load_v3():
file = tests.modules.get_test_resources_directory("measuregranularity/v3.pipeline")
with open(file, "r") as fd:
data = fd.read()
pipeline = cellprofiler_core.pipeline.Pipeline()
def callback(caller, event):
assert not isinstance(event, cellprofiler_core.pipeline.event.LoadException)
pipeline.add_listener(callback)
pipeline.load(six.moves.StringIO(data))
assert len(pipeline.modules()) == 1
module = pipeline.modules()[0]
assert isinstance(
module, cellprofiler.modules.measuregranularity.MeasureGranularity
)
assert len(module.images_list.value) == 2
for image_name, subsample_size, bsize, elsize, glen, objs in (
("DNA", 0.25, 0.25, 10, 16, ("Nuclei", "Cells")),
("Actin", 0.33, 0.50, 12, 20, ("Nuclei", "Cells", "Cytoplasm")),
):
assert image_name in module.images_list.value
assert module.subsample_size.value == 0.25
assert module.image_sample_size.value == 0.25
assert module.element_size.value == 10
assert module.granular_spectrum_length.value == 16
assert len(module.objects_list.value) == 3
assert all([obj in module.objects_list.value for obj in objs])
def make_pipeline(
image,
mask,
subsample_size,
image_sample_size,
element_size,
granular_spectrum_length,
labels=None,
):
"""Make a pipeline with a MeasureGranularity module
image - measure granularity on this image
mask - exclude / include pixels from measurement. None = no mask
subsample_size, etc. - values for corresponding settings in the module
returns tuple of module & workspace
"""
module = cellprofiler.modules.measuregranularity.MeasureGranularity()
module.set_module_num(1)
module.images_list.value = IMAGE_NAME
module.subsample_size.value = subsample_size
module.image_sample_size.value = image_sample_size
module.element_size.value = element_size
module.granular_spectrum_length.value = granular_spectrum_length
image_set_list = cellprofiler_core.image.ImageSetList()
image_set = image_set_list.get_image_set(0)
img = cellprofiler_core.image.Image(image, mask)
image_set.add(IMAGE_NAME, img)
pipeline = cellprofiler_core.pipeline.Pipeline()
def error_callback(event, caller):
assert not isinstance(event, cellprofiler_core.pipeline.event.RunException)
pipeline.add_listener(error_callback)
pipeline.add_module(module)
object_set = cellprofiler_core.object.ObjectSet()
if labels is not None:
objects = cellprofiler_core.object.Objects()
objects.segmented = labels
object_set.add_objects(objects, OBJECTS_NAME)
module.objects_list.value = OBJECTS_NAME
workspace = cellprofiler_core.workspace.Workspace(
pipeline,
module,
image_set,
object_set,
cellprofiler_core.measurement.Measurements(),
image_set_list,
)
return module, workspace
def test_all_masked():
"""Run on a totally masked image"""
module, workspace = make_pipeline(
numpy.zeros((40, 40)), numpy.zeros((40, 40), bool), 0.25, 0.25, 10, 16
)
assert isinstance(
module, cellprofiler.modules.measuregranularity.MeasureGranularity
)
module.run(workspace)
m = workspace.measurements
assert isinstance(m,cellprofiler_core.measurement.Measurements)
for i in range(1, 16):
feature = module.granularity_feature(i, IMAGE_NAME)
assert feature in m.get_feature_names("Image")
value = m.get_current_image_measurement(feature)
assert numpy.isnan(value)
def test_zeros():
"""Run on an image of all zeros"""
module, workspace = make_pipeline(numpy.zeros((40, 40)), None, 0.25, 0.25, 10, 16)
assert isinstance(
module, cellprofiler.modules.measuregranularity.MeasureGranularity
)
module.run(workspace)
m = workspace.measurements
assert isinstance(m,cellprofiler_core.measurement.Measurements)
for i in range(1, 16):
feature = module.granularity_feature(i, IMAGE_NAME)
assert feature in m.get_feature_names("Image")
value = m.get_current_image_measurement(feature)
assert round(abs(value - 0), 7) == 0
def test_no_scaling():
"""Run on an image without subsampling or background scaling"""
#
# Make an image with granularity at scale 1
#
i, j = numpy.mgrid[0:10, 0:10]
image = (i % 2 == j % 2).astype(float)
expected = [100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
module, workspace = make_pipeline(image, None, 1, 1, 10, 16)
assert isinstance(
module, cellprofiler.modules.measuregranularity.MeasureGranularity
)
module.run(workspace)
m = workspace.measurements
assert isinstance(m,cellprofiler_core.measurement.Measurements)
for i in range(1, 16):
feature = module.granularity_feature(i, IMAGE_NAME)
assert feature in m.get_feature_names("Image")
value = m.get_current_image_measurement(feature)
assert round(abs(value - expected[i - 1]), 7) == 0
def test_subsampling():
"""Run on an image with subsampling"""
#
# Make an image with granularity at scale 2
#
i, j = numpy.mgrid[0:80, 0:80]
image = ((i / 8).astype(int) % 2 == (j / 8).astype(int) % 2).astype(float)
#
# The 4x4 blocks need two erosions before disappearing. The corners
# need an additional two erosions before disappearing
#
expected = [0, 96, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
module, workspace = make_pipeline(image, None, 0.5, 1, 10, 16)
assert isinstance(
module, cellprofiler.modules.measuregranularity.MeasureGranularity
)
module.run(workspace)
m = workspace.measurements
assert isinstance(m,cellprofiler_core.measurement.Measurements)
for i in range(1, 16):
feature = module.granularity_feature(i, IMAGE_NAME)
assert feature in m.get_feature_names("Image")
value = m.get_current_image_measurement(feature)
assert round(abs(value - expected[i - 1]), 7) == 0
def test_background_sampling():
"""Run on an image with background subsampling"""
#
# Make an image with granularity at scale 2
#
i, j = numpy.mgrid[0:80, 0:80]
image = ((i / 4).astype(int) % 2 == (j / 4).astype(int) % 2).astype(float)
#
# Add in a background offset
#
image = image * 0.5 + 0.5
#
# The 4x4 blocks need two erosions before disappearing. The corners
# need an additional two erosions before disappearing
#
expected = [0, 99, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
module, workspace = make_pipeline(image, None, 1, 0.5, 10, 16)
assert isinstance(
module, cellprofiler.modules.measuregranularity.MeasureGranularity
)
module.run(workspace)
m = workspace.measurements
assert isinstance(m,cellprofiler_core.measurement.Measurements)
for i in range(1, 16):
feature = module.granularity_feature(i, IMAGE_NAME)
assert feature in m.get_feature_names("Image")
value = m.get_current_image_measurement(feature)
assert round(abs(value - expected[i - 1]), 7) == 0
def test_filter_background():
"""Run on an image, filtering out the background
This test makes sure that the grey_closing happens correctly
over the user-specified radius.
"""
#
# Make an image with granularity at scale 2
#
i, j = numpy.mgrid[0:80, 0:80]
image = ((i / 4).astype(int) % 2 == (j / 4).astype(int) % 2).astype(float)
#
# Scale the pixels down so we have some dynamic range and offset
# so the background is .2
#
image = image * 0.5 + 0.2
#
# Paint all background pixels on the edge and 1 in to be 0
#
image[:, :2][image[:, :2] < 0.5] = 0
#
# Paint all of the foreground pixels on the edge to be .5
#
image[:, 0][image[:, 0] > 0.5] = 0.5
#
# The pixel at 0,0 doesn't get a background of zero
#
image[0, 0] = 0.7
#
# The 4x4 blocks need two erosions before disappearing. The corners
# need an additional two erosions before disappearing
#
expected = [0, 99, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
module, workspace = make_pipeline(image, None, 1, 1, 5, 16)
assert isinstance(
module, cellprofiler.modules.measuregranularity.MeasureGranularity
)
module.run(workspace)
m = workspace.measurements
assert isinstance(m,cellprofiler_core.measurement.Measurements)
for i in range(1, 16):
feature = module.granularity_feature(i, IMAGE_NAME)
assert feature in m.get_feature_names("Image")
value = m.get_current_image_measurement(feature)
assert round(abs(value - expected[i - 1]), 7) == 0
def test_all_masked_alt():
"""Run on objects and a totally masked image"""
labels = numpy.ones((40, 40), int)
labels[20:, :] = 2
module, workspace = make_pipeline(
numpy.zeros((40, 40)), numpy.zeros((40, 40), bool), 0.25, 0.25, 10, 16, labels
)
assert isinstance(
module, cellprofiler.modules.measuregranularity.MeasureGranularity
)
module.run(workspace)
m = workspace.measurements
assert isinstance(m,cellprofiler_core.measurement.Measurements)
for i in range(1, 16):
feature = module.granularity_feature(i, IMAGE_NAME)
assert feature in m.get_feature_names("Image")
value = m.get_current_image_measurement(feature)
assert numpy.isnan(value)
values = m.get_current_measurement(OBJECTS_NAME, feature)
assert len(values) == 2
assert numpy.all(numpy.isnan(values)) or numpy.all(values == 0)
def test_no_objects():
"""Run on a labels matrix with no objects"""
module, workspace = make_pipeline(
numpy.zeros((40, 40)), None, 0.25, 0.25, 10, 16, numpy.zeros((40, 40), int)
)
assert isinstance(
module, cellprofiler.modules.measuregranularity.MeasureGranularity
)
module.run(workspace)
m = workspace.measurements
assert isinstance(m,cellprofiler_core.measurement.Measurements)
for i in range(1, 16):
feature = module.granularity_feature(i, IMAGE_NAME)
assert feature in m.get_feature_names("Image")
value = m.get_current_image_measurement(feature)
assert round(abs(value - 0), 7) == 0
values = m.get_current_measurement(OBJECTS_NAME, feature)
assert len(values) == 0
def test_zeros_alt():
"""Run on an image of all zeros"""
labels = numpy.ones((40, 40), int)
labels[20:, :] = 2
module, workspace = make_pipeline(
numpy.zeros((40, 40)), None, 0.25, 0.25, 10, 16, labels
)
assert isinstance(
module, cellprofiler.modules.measuregranularity.MeasureGranularity
)
module.run(workspace)
m = workspace.measurements
assert isinstance(m,cellprofiler_core.measurement.Measurements)
for i in range(1, 16):
feature = module.granularity_feature(i, IMAGE_NAME)
assert feature in m.get_feature_names("Image")
value = m.get_current_image_measurement(feature)
assert round(abs(value - 0), 7) == 0
values = m.get_current_measurement(OBJECTS_NAME, feature)
assert len(values) == 2
numpy.testing.assert_almost_equal(values, 0)
def test_no_scaling_alt():
"""Run on an image without subsampling or background scaling"""
#
# Make an image with granularity at scale 1
#
i, j = numpy.mgrid[0:40, 0:30]
image = (i % 2 == j % 2).astype(float)
expected = [100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
labels = numpy.ones((40, 30), int)
labels[20:, :] = 2
module, workspace = make_pipeline(image, None, 1, 1, 10, 16, labels)
assert isinstance(
module, cellprofiler.modules.measuregranularity.MeasureGranularity
)
module.run(workspace)
m = workspace.measurements
assert isinstance(m,cellprofiler_core.measurement.Measurements)
for i in range(1, 16):
feature = module.granularity_feature(i, IMAGE_NAME)
assert feature in m.get_feature_names("Image")
value = m.get_current_image_measurement(feature)
assert round(abs(value - expected[i - 1]), 7) == 0
values = m.get_current_measurement(OBJECTS_NAME, feature)
assert len(values) == 2
numpy.testing.assert_almost_equal(values, expected[i - 1])
def test_subsampling_alt():
"""Run on an image with subsampling"""
#
# Make an image with granularity at scale 2
#
i, j = numpy.mgrid[0:80, 0:80]
image = ((i / 8).astype(int) % 2 == (j / 8).astype(int) % 2).astype(float)
#
# The 4x4 blocks need two erosions before disappearing. The corners
# need an additional two erosions before disappearing
#
expected = [0, 96, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
labels = numpy.ones((80, 80), int)
labels[40:, :] = 2
module, workspace = make_pipeline(image, None, 0.5, 1, 10, 16, labels)
assert isinstance(
module, cellprofiler.modules.measuregranularity.MeasureGranularity
)
module.run(workspace)
m = workspace.measurements
assert isinstance(m,cellprofiler_core.measurement.Measurements)
for i in range(1, 16):
feature = module.granularity_feature(i, IMAGE_NAME)
assert feature in m.get_feature_names("Image")
value = m.get_current_image_measurement(feature)
assert round(abs(value - expected[i - 1]), 7) == 0
values = m.get_current_measurement(OBJECTS_NAME, feature)
assert len(values) == 2
#
# We rescale the downscaled image to the size of the labels
# and this throws the images off during interpolation
#
numpy.testing.assert_almost_equal(values, expected[i - 1], 0)
| [
"numpy.ones",
"numpy.testing.assert_almost_equal",
"numpy.zeros",
"numpy.isnan",
"numpy.all"
] | [((9229, 9254), 'numpy.ones', 'numpy.ones', (['(40, 40)', 'int'], {}), '((40, 40), int)\n', (9239, 9254), False, 'import numpy\n'), ((10892, 10917), 'numpy.ones', 'numpy.ones', (['(40, 40)', 'int'], {}), '((40, 40), int)\n', (10902, 10917), False, 'import numpy\n'), ((11988, 12013), 'numpy.ones', 'numpy.ones', (['(40, 30)', 'int'], {}), '((40, 30), int)\n', (11998, 12013), False, 'import numpy\n'), ((13229, 13254), 'numpy.ones', 'numpy.ones', (['(80, 80)', 'int'], {}), '((80, 80), int)\n', (13239, 13254), False, 'import numpy\n'), ((3437, 3458), 'numpy.zeros', 'numpy.zeros', (['(40, 40)'], {}), '((40, 40))\n', (3448, 3458), False, 'import numpy\n'), ((3460, 3487), 'numpy.zeros', 'numpy.zeros', (['(40, 40)', 'bool'], {}), '((40, 40), bool)\n', (3471, 3487), False, 'import numpy\n'), ((3957, 3975), 'numpy.isnan', 'numpy.isnan', (['value'], {}), '(value)\n', (3968, 3975), False, 'import numpy\n'), ((4073, 4094), 'numpy.zeros', 'numpy.zeros', (['(40, 40)'], {}), '((40, 40))\n', (4084, 4094), False, 'import numpy\n'), ((9325, 9346), 'numpy.zeros', 'numpy.zeros', (['(40, 40)'], {}), '((40, 40))\n', (9336, 9346), False, 'import numpy\n'), ((9348, 9375), 'numpy.zeros', 'numpy.zeros', (['(40, 40)', 'bool'], {}), '((40, 40), bool)\n', (9359, 9375), False, 'import numpy\n'), ((9853, 9871), 'numpy.isnan', 'numpy.isnan', (['value'], {}), '(value)\n', (9864, 9871), False, 'import numpy\n'), ((10163, 10184), 'numpy.zeros', 'numpy.zeros', (['(40, 40)'], {}), '((40, 40))\n', (10174, 10184), False, 'import numpy\n'), ((10212, 10238), 'numpy.zeros', 'numpy.zeros', (['(40, 40)', 'int'], {}), '((40, 40), int)\n', (10223, 10238), False, 'import numpy\n'), ((10988, 11009), 'numpy.zeros', 'numpy.zeros', (['(40, 40)'], {}), '((40, 40))\n', (10999, 11009), False, 'import numpy\n'), ((11629, 11673), 'numpy.testing.assert_almost_equal', 'numpy.testing.assert_almost_equal', (['values', '(0)'], {}), '(values, 0)\n', (11662, 11673), False, 'import numpy\n'), ((12703, 12761), 'numpy.testing.assert_almost_equal', 'numpy.testing.assert_almost_equal', (['values', 'expected[i - 1]'], {}), '(values, expected[i - 1])\n', (12736, 12761), False, 'import numpy\n'), ((14096, 14157), 'numpy.testing.assert_almost_equal', 'numpy.testing.assert_almost_equal', (['values', 'expected[i - 1]', '(0)'], {}), '(values, expected[i - 1], 0)\n', (14129, 14157), False, 'import numpy\n'), ((10019, 10041), 'numpy.all', 'numpy.all', (['(values == 0)'], {}), '(values == 0)\n', (10028, 10041), False, 'import numpy\n'), ((9995, 10014), 'numpy.isnan', 'numpy.isnan', (['values'], {}), '(values)\n', (10006, 10014), False, 'import numpy\n')] |
import os
import numpy as np
import imageio
import cv2
from backend import Config
def pre_proc(img, params):
"""
Description
Keyword arguments:
img --
params --
"""
interpolation = params['interpolation']
# img: read in by imageio.imread
# with shape (x,y,3), in the format of RGB
# convert to (3,112,96) with BGR
img_resize = cv2.resize(img, (112, 96), interpolation)
img_BGR = img_resize[...,::-1]
img_CHW = (img_BGR.transpose(2, 0, 1) - 127.5) / 128
return img_CHW
def crop_face(img, detector, outfilename, sess_id):
"""
Description
Keyword arguments:
"""
# interpolation = params['interpolation']
interpolation = cv2.INTER_LINEAR
minsize = 20 # minimum size of face
threshold = [ 0.6, 0.7, 0.7 ] # three steps's threshold
factor = 0.709 # scale factor
margin = 4
image_width = 96
image_height = 112
try:
bounding_boxes = detector.detect_faces(img)
nrof_faces = len(bounding_boxes)
except:
return None, None, 0
if nrof_faces < 1:
return None, None, 0
dets = []
faces = []
count = 0
for b in bounding_boxes:
det = b['box']
det[2] += det[0]
det[3] += det[1]
img_size = np.asarray(img.shape)[0:2]
bb = np.zeros(4, dtype=np.int32)
bb[0] = np.maximum(det[0]-margin/2, 0)
bb[1] = np.maximum(det[1]-margin/2, 0)
bb[2] = np.minimum(det[2]+margin/2, img_size[1])
bb[3] = np.minimum(det[3]+margin/2, img_size[0])
cropped = img[bb[1]:bb[3],bb[0]:bb[2],:]
scaled = cv2.resize(cropped, (image_height, image_width), interpolation)
scaled = scaled[...,::-1]
index = outfilename.index('.')
imageio.imwrite(os.path.join(Config.UPLOAD_FOLDER, '{}{}_{}.png'.format(sess_id, outfilename[:index], count)),scaled)
count += 1
face = np.around(np.transpose(scaled, (2,0,1))/255.0, decimals=12)
face = (face-0.5)*2
dets.append(det)
faces.append(face)
faces = np.array(faces)
return faces, dets, count
def apply_delta(delta, img, det, params):
"""
Description
Keyword arguments:
"""
margin = 4
img_size = np.asarray(img.shape)[0:2]
bb = np.zeros(4, dtype=np.int32)
bb[0] = np.maximum(det[0]-margin/2, 0)
bb[1] = np.maximum(det[1]-margin/2, 0)
bb[2] = np.minimum(det[2]+margin/2, img_size[1])
bb[3] = np.minimum(det[3]+margin/2, img_size[0])
orig_dim = [bb[3]-bb[1], bb[2]-bb[0]]
delta_up = cv2.resize(delta, (orig_dim[1], orig_dim[0]), params['interpolation'])
img[bb[1]:bb[3],bb[0]:bb[2],:3] += delta_up
img[bb[1]:bb[3],bb[0]:bb[2],:3] = np.maximum(img[bb[1]:bb[3],bb[0]:bb[2],:3], 0)
img[bb[1]:bb[3],bb[0]:bb[2],:3] = np.minimum(img[bb[1]:bb[3],bb[0]:bb[2],:3], 1)
return img
def read_face_from_aligned(file_list, params):
"""
Description
Keyword arguments:
"""
result = []
for file_name in file_list:
# print(file_name)
face = imageio.imread(file_name)
# print(face)
face = pre_proc(face, params)
# print(face)
result.append(face)
result = np.array(result)
return result
| [
"cv2.resize",
"numpy.minimum",
"numpy.asarray",
"numpy.array",
"numpy.zeros",
"imageio.imread",
"numpy.maximum",
"numpy.transpose"
] | [((384, 425), 'cv2.resize', 'cv2.resize', (['img', '(112, 96)', 'interpolation'], {}), '(img, (112, 96), interpolation)\n', (394, 425), False, 'import cv2\n'), ((2090, 2105), 'numpy.array', 'np.array', (['faces'], {}), '(faces)\n', (2098, 2105), True, 'import numpy as np\n'), ((2308, 2335), 'numpy.zeros', 'np.zeros', (['(4)'], {'dtype': 'np.int32'}), '(4, dtype=np.int32)\n', (2316, 2335), True, 'import numpy as np\n'), ((2348, 2382), 'numpy.maximum', 'np.maximum', (['(det[0] - margin / 2)', '(0)'], {}), '(det[0] - margin / 2, 0)\n', (2358, 2382), True, 'import numpy as np\n'), ((2391, 2425), 'numpy.maximum', 'np.maximum', (['(det[1] - margin / 2)', '(0)'], {}), '(det[1] - margin / 2, 0)\n', (2401, 2425), True, 'import numpy as np\n'), ((2434, 2478), 'numpy.minimum', 'np.minimum', (['(det[2] + margin / 2)', 'img_size[1]'], {}), '(det[2] + margin / 2, img_size[1])\n', (2444, 2478), True, 'import numpy as np\n'), ((2487, 2531), 'numpy.minimum', 'np.minimum', (['(det[3] + margin / 2)', 'img_size[0]'], {}), '(det[3] + margin / 2, img_size[0])\n', (2497, 2531), True, 'import numpy as np\n'), ((2587, 2657), 'cv2.resize', 'cv2.resize', (['delta', '(orig_dim[1], orig_dim[0])', "params['interpolation']"], {}), "(delta, (orig_dim[1], orig_dim[0]), params['interpolation'])\n", (2597, 2657), False, 'import cv2\n'), ((2744, 2792), 'numpy.maximum', 'np.maximum', (['img[bb[1]:bb[3], bb[0]:bb[2], :3]', '(0)'], {}), '(img[bb[1]:bb[3], bb[0]:bb[2], :3], 0)\n', (2754, 2792), True, 'import numpy as np\n'), ((2829, 2877), 'numpy.minimum', 'np.minimum', (['img[bb[1]:bb[3], bb[0]:bb[2], :3]', '(1)'], {}), '(img[bb[1]:bb[3], bb[0]:bb[2], :3], 1)\n', (2839, 2877), True, 'import numpy as np\n'), ((3236, 3252), 'numpy.array', 'np.array', (['result'], {}), '(result)\n', (3244, 3252), True, 'import numpy as np\n'), ((1325, 1352), 'numpy.zeros', 'np.zeros', (['(4)'], {'dtype': 'np.int32'}), '(4, dtype=np.int32)\n', (1333, 1352), True, 'import numpy as np\n'), ((1369, 1403), 'numpy.maximum', 'np.maximum', (['(det[0] - margin / 2)', '(0)'], {}), '(det[0] - margin / 2, 0)\n', (1379, 1403), True, 'import numpy as np\n'), ((1416, 1450), 'numpy.maximum', 'np.maximum', (['(det[1] - margin / 2)', '(0)'], {}), '(det[1] - margin / 2, 0)\n', (1426, 1450), True, 'import numpy as np\n'), ((1463, 1507), 'numpy.minimum', 'np.minimum', (['(det[2] + margin / 2)', 'img_size[1]'], {}), '(det[2] + margin / 2, img_size[1])\n', (1473, 1507), True, 'import numpy as np\n'), ((1520, 1564), 'numpy.minimum', 'np.minimum', (['(det[3] + margin / 2)', 'img_size[0]'], {}), '(det[3] + margin / 2, img_size[0])\n', (1530, 1564), True, 'import numpy as np\n'), ((1627, 1690), 'cv2.resize', 'cv2.resize', (['cropped', '(image_height, image_width)', 'interpolation'], {}), '(cropped, (image_height, image_width), interpolation)\n', (1637, 1690), False, 'import cv2\n'), ((2272, 2293), 'numpy.asarray', 'np.asarray', (['img.shape'], {}), '(img.shape)\n', (2282, 2293), True, 'import numpy as np\n'), ((3087, 3112), 'imageio.imread', 'imageio.imread', (['file_name'], {}), '(file_name)\n', (3101, 3112), False, 'import imageio\n'), ((1284, 1305), 'numpy.asarray', 'np.asarray', (['img.shape'], {}), '(img.shape)\n', (1294, 1305), True, 'import numpy as np\n'), ((1943, 1974), 'numpy.transpose', 'np.transpose', (['scaled', '(2, 0, 1)'], {}), '(scaled, (2, 0, 1))\n', (1955, 1974), True, 'import numpy as np\n')] |
r"""
Basic analysis of a MD simulation
=================================
In this example, we will analyze a trajectory of a *Gromacs* MD
simulation:
The trajectory contains simulation data of lysozyme over the course of
1 ns.
The data is the result of the famous *Gromacs*
'`Lysozyme in Water <http://www.mdtutorials.com/gmx/lysozyme/index.html>`_'
tutorial.
The trajectory file can be downloaded
:download:`here </examples/download/lysozyme_md.xtc>`
and the template PDB can be downloaded
:download:`here </examples/download/lysozyme_md.pdb>`.
We begin by loading the template PDB file as :class:`AtomArray`, sanitizing it
and using it to load the trajectory as :class:`AtomArrayStack`.
"""
# Code source: <NAME>
# License: BSD 3 clause
import biotite
import biotite.structure as struc
import biotite.structure.io as strucio
import biotite.structure.io.xtc as xtc
import numpy as np
import matplotlib.pyplot as plt
# Put here the path of the downloaded files
templ_file_path = "../../download/lysozyme_md.pdb"
traj_file_path = "../../download/lysozyme_md.xtc"
# Gromacs does not set the element symbol in its PDB files,
# but Biotite guesses the element names from the atom names,
# emitting a warning
template = strucio.load_structure(templ_file_path)
# The structure still has water and ions, that are not needed for our
# calculations, we are only interested in the protein itself
# These are removed for the sake of computational speed using a boolean
# mask
protein_mask = struc.filter_amino_acids(template)
template = template[protein_mask]
# We could have loaded the trajectory also with
# 'strucio.load_structure()', but in this case we only want to load
# those coordinates that belong to the already selected atoms of the
# template structure.
# Hence, we use the 'XTCFile' class directly to load the trajectory
# This gives us the additional option that allows us to select the
# coordinates belonging to the amino acids.
xtc_file = xtc.XTCFile.read(traj_file_path, atom_i=np.where(protein_mask)[0])
trajectory = xtc_file.get_structure(template)
# Get simulation time for plotting purposes
time = xtc_file.get_time()
########################################################################
# Since the MD simulation used periodic boundaries, the protein might be
# segmented over the box boundary.
# For further analysis we need to reassemble the protein chain into a
# whole molecule, without periodic boundaries.
# in *Gromacs* we could have used ``gmx trjconv`` for this, but this
# problem can be handled in *Biotite*, too.
trajectory = struc.remove_pbc(trajectory)
########################################################################
# Now our trajectory is ready for some analysis!
# At first we want to see if the simulation converged.
# For this purpose we take the RMSD of a frame compared to the initial
# model as measure. In order to calculate the RMSD we must
# superimpose all models onto a reference, in this case we also choose
# the initial structure.
trajectory, transform = struc.superimpose(trajectory[0], trajectory)
rmsd = struc.rmsd(trajectory[0], trajectory)
figure = plt.figure(figsize=(6,3))
ax = figure.add_subplot(111)
ax.plot(time, rmsd, color=biotite.colors["dimorange"])
ax.set_xlim(time[0], time[-1])
ax.set_ylim(0, 2)
ax.set_xlabel("Time (ps)")
ax.set_ylabel("RMSD (Å)")
figure.tight_layout()
########################################################################
# As we can see the simulation seems to converge already early in the
# simulation.
# After a about 200 ps the RMSD stays in a range of approx. 1 - 2 Å.
#
# In order to futher evaluate the unfolding of our enzyme in the
# course of simulation, we calculate and plot the radius of gyration
# (a measure for the protein radius).
radius = struc.gyration_radius(trajectory)
figure = plt.figure(figsize=(6,3))
ax = figure.add_subplot(111)
ax.plot(time, radius, color=biotite.colors["dimorange"])
ax.set_xlim(time[0], time[-1])
ax.set_ylim(14.0, 14.5)
ax.set_xlabel("Time (ps)")
ax.set_ylabel("Radius of gyration (Å)")
figure.tight_layout()
########################################################################
# From this perspective, the protein seems really stable.
# The radius does merely fluctuate in a range of approximately 0.3 Å
# during the entire simulation.
#
# Let's have a look at single amino acids:
# Which residues fluctuate most?
# For answering this question we calculate the RMSF
# (Root mean square fluctuation).
# It is similar to the RMSD, but instead of averaging over the atoms
# and looking at each time step, we average over the time and look at
# each residue.
# Usually the average model is taken as reference
# (compared to the starting model for RMSD).
#
# Since side chain atoms fluctuate quite a lot, they are not suitable
# for evaluation of the residue flexibility. Therefore, we consider only
# CA atoms.
# In all models, mask the CA atoms
ca_trajectory = trajectory[:, trajectory.atom_name == "CA"]
rmsf = struc.rmsf(struc.average(ca_trajectory), ca_trajectory)
figure = plt.figure(figsize=(6,3))
ax = figure.add_subplot(111)
res_count = struc.get_residue_count(trajectory)
ax.plot(np.arange(1, res_count+1), rmsf, color=biotite.colors["dimorange"])
ax.set_xlim(1, res_count)
ax.set_ylim(0, 1.5)
ax.set_xlabel("Residue")
ax.set_ylabel("RMSF (Å)")
figure.tight_layout()
plt.show() | [
"biotite.structure.io.load_structure",
"numpy.arange",
"numpy.where",
"biotite.structure.rmsd",
"biotite.structure.filter_amino_acids",
"matplotlib.pyplot.figure",
"biotite.structure.average",
"biotite.structure.get_residue_count",
"biotite.structure.remove_pbc",
"biotite.structure.gyration_radius... | [((1222, 1261), 'biotite.structure.io.load_structure', 'strucio.load_structure', (['templ_file_path'], {}), '(templ_file_path)\n', (1244, 1261), True, 'import biotite.structure.io as strucio\n'), ((1487, 1521), 'biotite.structure.filter_amino_acids', 'struc.filter_amino_acids', (['template'], {}), '(template)\n', (1511, 1521), True, 'import biotite.structure as struc\n'), ((2563, 2591), 'biotite.structure.remove_pbc', 'struc.remove_pbc', (['trajectory'], {}), '(trajectory)\n', (2579, 2591), True, 'import biotite.structure as struc\n'), ((3022, 3066), 'biotite.structure.superimpose', 'struc.superimpose', (['trajectory[0]', 'trajectory'], {}), '(trajectory[0], trajectory)\n', (3039, 3066), True, 'import biotite.structure as struc\n'), ((3074, 3111), 'biotite.structure.rmsd', 'struc.rmsd', (['trajectory[0]', 'trajectory'], {}), '(trajectory[0], trajectory)\n', (3084, 3111), True, 'import biotite.structure as struc\n'), ((3122, 3148), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(6, 3)'}), '(figsize=(6, 3))\n', (3132, 3148), True, 'import matplotlib.pyplot as plt\n'), ((3769, 3802), 'biotite.structure.gyration_radius', 'struc.gyration_radius', (['trajectory'], {}), '(trajectory)\n', (3790, 3802), True, 'import biotite.structure as struc\n'), ((3813, 3839), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(6, 3)'}), '(figsize=(6, 3))\n', (3823, 3839), True, 'import matplotlib.pyplot as plt\n'), ((5044, 5070), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(6, 3)'}), '(figsize=(6, 3))\n', (5054, 5070), True, 'import matplotlib.pyplot as plt\n'), ((5111, 5146), 'biotite.structure.get_residue_count', 'struc.get_residue_count', (['trajectory'], {}), '(trajectory)\n', (5134, 5146), True, 'import biotite.structure as struc\n'), ((5344, 5354), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5352, 5354), True, 'import matplotlib.pyplot as plt\n'), ((4989, 5017), 'biotite.structure.average', 'struc.average', (['ca_trajectory'], {}), '(ca_trajectory)\n', (5002, 5017), True, 'import biotite.structure as struc\n'), ((5155, 5182), 'numpy.arange', 'np.arange', (['(1)', '(res_count + 1)'], {}), '(1, res_count + 1)\n', (5164, 5182), True, 'import numpy as np\n'), ((1993, 2015), 'numpy.where', 'np.where', (['protein_mask'], {}), '(protein_mask)\n', (2001, 2015), True, 'import numpy as np\n')] |
"""
Split ramps into individual FLT exposures.
To use, download *just* the RAW files for a given visit/program.
>>> from wfc3dash import process_raw
>>> process_raw.run_all()
"""
def run_all(skip_first_read=True):
"""
Run splitting script on all RAW files in the working directory.
First generates IMA files from RAWs after setting CRCORR=OMIT.
"""
import os
import glob
import astropy.io.fits as pyfits
import wfc3tools
files = glob.glob("*raw.fits")
files.sort()
for file in files:
if os.path.exists(file.replace('_raw','_ima')):
print('IMA exists, skip', file)
continue
print('Process', file)
# Set CRCORR
raw_im = pyfits.open(file, mode='update')
raw_im[0].header['CRCORR'] = 'OMIT'
raw_im.flush()
# Remove FLT if it exists or calwf3 will die
if os.path.exists(file.replace('_raw','_flt')):
os.remove(file.replace('_raw','_flt'))
# Run calwf3
wfc3tools.calwf3(file)
# Split into individual FLTs
split_ima_flt(file=file.replace('_raw','_ima'), skip_first_read=skip_first_read)
def split_ima_flt(file='icxe15x0q_ima.fits', skip_first_read=True):
"""
Pull out reads of an IMA file into individual "FLT" files
"""
import os
import astropy.io.fits as pyfits
import numpy as np
# https://github.com/gbrammer/reprocess_wfc3
from reprocess_wfc3.reprocess_wfc3 import get_flat, split_multiaccum
ima = pyfits.open(file)
root = file.split("_ima")[0][:-1]
#### Pull out the data cube, order in the more natural sense
#### of first reads first
cube, dq, time, NSAMP = split_multiaccum(ima, scale_flat=False)
#### Readnoise in 4 amps
readnoise_2D = np.zeros((1024,1024))
readnoise_2D[512: ,0:512] += ima[0].header['READNSEA']
readnoise_2D[0:512,0:512] += ima[0].header['READNSEB']
readnoise_2D[0:512, 512:] += ima[0].header['READNSEC']
readnoise_2D[512: , 512:] += ima[0].header['READNSED']
readnoise_2D = readnoise_2D**2
#### Gain in 4 amps
gain_2D = np.zeros((1024,1024))
gain_2D[512: ,0:512] += ima[0].header['ATODGNA']
gain_2D[0:512,0:512] += ima[0].header['ATODGNB']
gain_2D[0:512, 512:] += ima[0].header['ATODGNC']
gain_2D[512: , 512:] += ima[0].header['ATODGND']
#### Need to put dark back in for Poisson
dark_file = ima[0].header['DARKFILE'].replace('iref$', os.getenv('iref')+'/')
dark = pyfits.open(dark_file)
dark_cube, dark_dq, dark_time, dark_NSAMP = split_multiaccum(dark, scale_flat=False)
#### Need flat for Poisson
if ima[0].header['FLATCORR'] == 'COMPLETE':
flat_im, flat = get_flat(ima)
else:
flat_im, flat = None, 1
#### Subtract diffs of flagged reads
diff = np.diff(cube, axis=0)
dark_diff = np.diff(dark_cube, axis=0)
dt = np.diff(time)
final_sci = diff
final_dark = dark_diff[:NSAMP-1]
final_exptime = dt
final_var = final_sci*0
final_err = final_sci*0
for i in range(NSAMP-1):
final_var[i,:,:] = readnoise_2D + (final_sci[i,:,:]*flat + final_dark[i,:,:]*gain_2D)*(gain_2D/2.368)
if ima[0].header['FLATCORR'] == 'COMPLETE':
final_var[i,:,:] += (final_sci[i,:,:]*flat*flat_im['ERR'].data)**2
final_err[i,:,:] = np.sqrt(final_var[i,:,:])/flat/(gain_2D/2.368)/1.003448/final_exptime[i]
final_sci[i,:,:] /= final_exptime[i]
h_0 = ima[0].header.copy()
h_sci = ima['SCI',1].header.copy()
h_err = ima['ERR',1].header.copy()
h_dq = ima['DQ',1].header.copy()
h_time = ima['TIME',1].header.copy()
final_dq = dq[1:,:,:]*1
final_dq -= (final_dq & 2048)
h_sci['CRPIX1'] = 507
h_sci['CRPIX2'] = 507
letters = 'abcdefghijklmno'
for i in range(1*skip_first_read,NSAMP-1):
h_0['EXPTIME'] = final_exptime[i]
h_0['IREAD'] = i
hdu = pyfits.HDUList(pyfits.PrimaryHDU(header=h_0))
hdu.append(pyfits.ImageHDU(data=final_sci[i,5:-5,5:-5], header=h_sci))
hdu.append(pyfits.ImageHDU(data=final_err[i,5:-5,5:-5], header=h_err))
hdu.append(pyfits.ImageHDU(data=final_dq[i,5:-5,5:-5], header=h_dq))
h_time['PIXVALUE'] = final_exptime[i]
h_time['NPIX1'] = 1014
h_time['NPIX2'] = 1014
hdu.append(pyfits.ImageHDU(header=h_time))
hdu.writeto('%s%s_flt.fits' %(root, letters[i-1]), clobber=True)
print('%s%s_flt.fits' %(root, letters[i-1]))
| [
"numpy.sqrt",
"os.getenv",
"astropy.io.fits.PrimaryHDU",
"reprocess_wfc3.reprocess_wfc3.get_flat",
"astropy.io.fits.ImageHDU",
"numpy.diff",
"numpy.zeros",
"glob.glob",
"astropy.io.fits.open",
"reprocess_wfc3.reprocess_wfc3.split_multiaccum",
"wfc3tools.calwf3"
] | [((505, 527), 'glob.glob', 'glob.glob', (['"""*raw.fits"""'], {}), "('*raw.fits')\n", (514, 527), False, 'import glob\n'), ((1610, 1627), 'astropy.io.fits.open', 'pyfits.open', (['file'], {}), '(file)\n', (1621, 1627), True, 'import astropy.io.fits as pyfits\n'), ((1794, 1833), 'reprocess_wfc3.reprocess_wfc3.split_multiaccum', 'split_multiaccum', (['ima'], {'scale_flat': '(False)'}), '(ima, scale_flat=False)\n', (1810, 1833), False, 'from reprocess_wfc3.reprocess_wfc3 import get_flat, split_multiaccum\n'), ((1887, 1909), 'numpy.zeros', 'np.zeros', (['(1024, 1024)'], {}), '((1024, 1024))\n', (1895, 1909), True, 'import numpy as np\n'), ((2219, 2241), 'numpy.zeros', 'np.zeros', (['(1024, 1024)'], {}), '((1024, 1024))\n', (2227, 2241), True, 'import numpy as np\n'), ((2597, 2619), 'astropy.io.fits.open', 'pyfits.open', (['dark_file'], {}), '(dark_file)\n', (2608, 2619), True, 'import astropy.io.fits as pyfits\n'), ((2668, 2708), 'reprocess_wfc3.reprocess_wfc3.split_multiaccum', 'split_multiaccum', (['dark'], {'scale_flat': '(False)'}), '(dark, scale_flat=False)\n', (2684, 2708), False, 'from reprocess_wfc3.reprocess_wfc3 import get_flat, split_multiaccum\n'), ((2934, 2955), 'numpy.diff', 'np.diff', (['cube'], {'axis': '(0)'}), '(cube, axis=0)\n', (2941, 2955), True, 'import numpy as np\n'), ((2972, 2998), 'numpy.diff', 'np.diff', (['dark_cube'], {'axis': '(0)'}), '(dark_cube, axis=0)\n', (2979, 2998), True, 'import numpy as np\n'), ((3008, 3021), 'numpy.diff', 'np.diff', (['time'], {}), '(time)\n', (3015, 3021), True, 'import numpy as np\n'), ((782, 814), 'astropy.io.fits.open', 'pyfits.open', (['file'], {'mode': '"""update"""'}), "(file, mode='update')\n", (793, 814), True, 'import astropy.io.fits as pyfits\n'), ((1081, 1103), 'wfc3tools.calwf3', 'wfc3tools.calwf3', (['file'], {}), '(file)\n', (1097, 1103), False, 'import wfc3tools\n'), ((2817, 2830), 'reprocess_wfc3.reprocess_wfc3.get_flat', 'get_flat', (['ima'], {}), '(ima)\n', (2825, 2830), False, 'from reprocess_wfc3.reprocess_wfc3 import get_flat, split_multiaccum\n'), ((2563, 2580), 'os.getenv', 'os.getenv', (['"""iref"""'], {}), "('iref')\n", (2572, 2580), False, 'import os\n'), ((4089, 4118), 'astropy.io.fits.PrimaryHDU', 'pyfits.PrimaryHDU', ([], {'header': 'h_0'}), '(header=h_0)\n', (4106, 4118), True, 'import astropy.io.fits as pyfits\n'), ((4148, 4208), 'astropy.io.fits.ImageHDU', 'pyfits.ImageHDU', ([], {'data': 'final_sci[i, 5:-5, 5:-5]', 'header': 'h_sci'}), '(data=final_sci[i, 5:-5, 5:-5], header=h_sci)\n', (4163, 4208), True, 'import astropy.io.fits as pyfits\n'), ((4227, 4287), 'astropy.io.fits.ImageHDU', 'pyfits.ImageHDU', ([], {'data': 'final_err[i, 5:-5, 5:-5]', 'header': 'h_err'}), '(data=final_err[i, 5:-5, 5:-5], header=h_err)\n', (4242, 4287), True, 'import astropy.io.fits as pyfits\n'), ((4306, 4364), 'astropy.io.fits.ImageHDU', 'pyfits.ImageHDU', ([], {'data': 'final_dq[i, 5:-5, 5:-5]', 'header': 'h_dq'}), '(data=final_dq[i, 5:-5, 5:-5], header=h_dq)\n', (4321, 4364), True, 'import astropy.io.fits as pyfits\n'), ((4500, 4530), 'astropy.io.fits.ImageHDU', 'pyfits.ImageHDU', ([], {'header': 'h_time'}), '(header=h_time)\n', (4515, 4530), True, 'import astropy.io.fits as pyfits\n'), ((3480, 3507), 'numpy.sqrt', 'np.sqrt', (['final_var[i, :, :]'], {}), '(final_var[i, :, :])\n', (3487, 3507), True, 'import numpy as np\n')] |
# -*- coding:utf-8 -*-
"""
Created on Wed Nov 20 12:40 2019
@author <NAME> - <EMAIL>
Agent - Recycler
"""
from mesa import Agent
import numpy as np
class Recyclers(Agent):
"""
A recycler which sells recycled materials and improve its processes.
Attributes:
unique_id: agent #, also relate to the node # in the network
model (see ABM_CE_PV_Model)
original_recycling_cost (a list for a triangular distribution) ($/fu) (
default=[0.106, 0.128, 0.117]). From EPRI 2018.
init_eol_rate (dictionary with initial end-of-life (EOL) ratios),
(default={"repair": 0.005, "sell": 0.02, "recycle": 0.1,
"landfill": 0.4375, "hoard": 0.4375}). From Monteiro Lunardi
et al 2018 and European Commission (2015).
recycling_learning_shape_factor, (default=-0.39). From Qiu & Suh 2019.
social_influencability_boundaries (from Ghali et al. 2017)
"""
def __init__(self, unique_id, model, original_recycling_cost,
init_eol_rate, recycling_learning_shape_factor,
social_influencability_boundaries):
"""
Creation of new recycler agent
"""
super().__init__(unique_id, model)
self.original_recycling_cost = np.random.triangular(
original_recycling_cost[0], original_recycling_cost[2],
original_recycling_cost[1])
self.original_fraction_recycled_waste = init_eol_rate["recycle"]
self.recycling_learning_shape_factor = recycling_learning_shape_factor
self.recycling_cost = self.original_recycling_cost
self.init_recycling_cost = self.original_recycling_cost
self.recycler_total_volume = 0
self.recycling_volume = 0
self.repairable_volume = 0
self.total_repairable_volume = 0
# Original recycling volume is based on previous years EoL volume
# (from 2000 to 2019)
original_recycled_volumes = [x / model.num_recyclers * 1E6 for x
in model.original_num_prod]
self.original_recycling_volume = \
(1 - self.model.repairability) * \
self.original_fraction_recycled_waste * \
sum(self.model.waste_generation(self.model.d_product_lifetimes,
self.model.avg_failure_rate[2],
original_recycled_volumes))
self.social_influencability = np.random.uniform(
social_influencability_boundaries[0],
social_influencability_boundaries[1])
self.knowledge = np.random.random()
self.social_interactions = np.random.random()
self.knowledge_learning = np.random.random()
self.knowledge_t = self.knowledge
self.symbiosis = False
self.agent_i = self.unique_id - self.model.num_consumers
self.recycler_costs = 0
def update_transport_recycling_costs(self):
"""
Update transportation costs according to the (evolving) mass of waste.
Here, an average distance between all origins and targets is assumed.
"""
self.recycling_cost = \
self.recycling_cost + \
(self.model.dynamic_product_average_wght -
self.model.product_average_wght) * \
self.model.transportation_cost / 1E3 * \
self.model.mn_mx_av_distance_to_recycler[2]
def update_recycled_waste(self):
"""
Update consumers' amount of recycled waste.
"""
if self.unique_id == self.model.num_consumers:
for agent in self.model.schedule.agents:
if agent.unique_id < self.model.num_consumers:
agent.update_yearly_recycled_waste(False)
def triage(self):
"""
Evaluate amount of products that can be refurbished
"""
self.recycler_total_volume = 0
self.recycling_volume = 0
self.repairable_volume = 0
self.total_repairable_volume = 0
tot_waste_sold = 0
new_installed_capacity = 0
for agent in self.model.schedule.agents:
if agent.unique_id < self.model.num_consumers and \
agent.EoL_pathway == "sell":
tot_waste_sold += agent.number_product_EoL
if agent.unique_id < self.model.num_consumers and \
agent.purchase_choice == "used":
new_installed_capacity += agent.number_product[-1]
used_vol_purchased = self.model.consumer_used_product \
/ self.model.num_consumers * new_installed_capacity
tot_waste_sold += self.model.yearly_repaired_waste
if tot_waste_sold < used_vol_purchased:
for agent in self.model.schedule.agents:
if agent.unique_id < self.model.num_consumers and \
agent.recycling_facility_id == self.unique_id:
self.recycler_total_volume += agent.yearly_recycled_waste
if self.model.yearly_repaired_waste < \
self.model.repairability * self.model.total_waste:
self.recycling_volume = \
(1 - self.model.repairability) * \
self.recycler_total_volume
self.repairable_volume = self.recycler_total_volume - \
self.recycling_volume
else:
self.recycling_volume = self.recycler_total_volume
self.repairable_volume = 0
else:
for agent in self.model.schedule.agents:
if agent.unique_id < self.model.num_consumers and \
agent.recycling_facility_id == self.unique_id:
self.recycler_total_volume += agent.yearly_recycled_waste
self.recycling_volume = self.recycler_total_volume
self.repairable_volume = 0
self.model.recycler_repairable_waste += self.repairable_volume
self.total_repairable_volume += self.repairable_volume
self.model.yearly_repaired_waste += self.repairable_volume
def learning_curve_function(self, original_volume, volume, original_cost,
shape_factor):
"""
Account for the learning effect: recyclers and refurbishers improve
their recycling and repairing processes respectively
"""
if volume > 0:
potential_recycling_cost = original_cost * \
(volume / original_volume) ** \
shape_factor
if potential_recycling_cost < original_cost:
return potential_recycling_cost
else:
return original_cost
return original_cost
def update_recyclers_knowledge(self):
"""
Update knowledge of agents about industrial symbiosis. Mathematical
model adapted from Ghali et al. 2017.
"""
self.knowledge_learning = np.random.random()
knowledge_neighbors = 0
neighbors_nodes = self.model.grid.get_neighbors(self.pos,
include_center=False)
for agent in self.model.grid.get_cell_list_contents(neighbors_nodes):
self.social_interactions = np.random.random()
agent_j = agent.unique_id - self.model.num_consumers
if self.model.trust_prod[self.agent_i, agent_j] >= \
self.model.trust_threshold:
knowledge_neighbors += self.social_interactions * (
agent.knowledge - self.knowledge)
self.knowledge_t = self.knowledge
self.knowledge += self.social_influencability * knowledge_neighbors + \
self.knowledge_learning
if self.knowledge < 0:
self.knowledge = 0
if self.knowledge > 1:
self.knowledge = 1
def compute_recycler_costs(self):
"""
Compute societal costs of recyclers. Only account for the material
recovered and the costs of recycling processes. Sales revenue of
repairable products are not included.
"""
revenue = 0
for agent in self.model.schedule.agents:
if self.model.num_consumers + self.model.num_recyclers <= \
agent.unique_id < self.model.num_consumers + \
self.model.num_prod_n_recyc:
if not np.isnan(agent.yearly_recycled_material_volume) and \
not np.isnan(agent.recycled_mat_price):
revenue += agent.yearly_recycled_material_volume * \
agent.recycled_mat_price
revenue /= self.model.num_recyclers
self.recycler_costs += \
((self.recycling_volume + self.model.installer_recycled_amount) *
self.recycling_cost - revenue)
def step(self):
"""
Evolution of agent at each step
"""
self.update_recycled_waste()
self.triage()
self.recycling_cost = self.learning_curve_function(
self.original_recycling_volume, self.recycling_volume,
self.original_recycling_cost,
self.recycling_learning_shape_factor)
self.update_transport_recycling_costs()
self.update_recyclers_knowledge()
| [
"numpy.random.triangular",
"numpy.random.random",
"numpy.isnan",
"numpy.random.uniform"
] | [((1276, 1384), 'numpy.random.triangular', 'np.random.triangular', (['original_recycling_cost[0]', 'original_recycling_cost[2]', 'original_recycling_cost[1]'], {}), '(original_recycling_cost[0], original_recycling_cost[2],\n original_recycling_cost[1])\n', (1296, 1384), True, 'import numpy as np\n'), ((2479, 2576), 'numpy.random.uniform', 'np.random.uniform', (['social_influencability_boundaries[0]', 'social_influencability_boundaries[1]'], {}), '(social_influencability_boundaries[0],\n social_influencability_boundaries[1])\n', (2496, 2576), True, 'import numpy as np\n'), ((2623, 2641), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (2639, 2641), True, 'import numpy as np\n'), ((2677, 2695), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (2693, 2695), True, 'import numpy as np\n'), ((2730, 2748), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (2746, 2748), True, 'import numpy as np\n'), ((7100, 7118), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (7116, 7118), True, 'import numpy as np\n'), ((7412, 7430), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (7428, 7430), True, 'import numpy as np\n'), ((8568, 8615), 'numpy.isnan', 'np.isnan', (['agent.yearly_recycled_material_volume'], {}), '(agent.yearly_recycled_material_volume)\n', (8576, 8615), True, 'import numpy as np\n'), ((8650, 8684), 'numpy.isnan', 'np.isnan', (['agent.recycled_mat_price'], {}), '(agent.recycled_mat_price)\n', (8658, 8684), True, 'import numpy as np\n')] |
import numpy as np
from torch.utils.data import DataLoader, SequentialSampler
HIDDEN_SIZE_BERT = 768
def flat_accuracy(preds, labels):
preds = preds.squeeze()
my_round = lambda x: 1 if x >= 0.5 else 0
pred_flat = np.fromiter(map(my_round, preds), dtype=np.int).flatten()
labels_flat = labels.flatten()
return np.sum(pred_flat == labels_flat) / len(labels_flat)
def get_max_len(sentences):
max_len = 0
# For every sentence...
for sent in sentences:
# Update the maximum sentence length.
max_len = max(max_len, len(sent))
#print('Max sentence length: ', max_len)
return max_len
def get_max_len_cap(sentences, cap: int = 128) -> (int, bool):
is_capped = False
max_len = 0
# For every sentence...
for sent in sentences:
# Update the maximum sentence length.
max_len = max(max_len, len(sent))
# check if the value is higher than the cap
if max_len >= cap:
is_capped = True
max_len = cap
break
#print('Max sentence length: ', max_len)
#print('Is capped: ', is_capped)
return max_len, is_capped
def create_data_loaders(train_dataset, val_dataset, batch_size=3):
# The DataLoader needs to know our batch size for training, so we specify it
# here. For fine-tuning BERT on a specific task, the authors recommend a batch
# size of 16 or 32.
# Create the DataLoaders for our training and validation sets.
# We'll take training samples in random order.
train_dataloader = DataLoader(
train_dataset, # The training samples.
sampler=SequentialSampler(train_dataset), # Select batches sequentially
batch_size=batch_size # Trains with this batch size.
)
# For validation the order doesn't matter, so we'll just read them sequentially.
validation_dataloader = DataLoader(
val_dataset, # The validation samples.
sampler=SequentialSampler(val_dataset), # Pull out batches sequentially.
batch_size=batch_size # Evaluate with this batch size.
)
return train_dataloader, validation_dataloader
def format_time(elapsed):
import datetime
'''
Takes a time in seconds and returns a string hh:mm:ss
'''
# Round to the nearest second.
elapsed_rounded = int(round((elapsed)))
# Format as hh:mm:ss
return str(datetime.timedelta(seconds=elapsed_rounded))
| [
"numpy.sum",
"datetime.timedelta",
"torch.utils.data.SequentialSampler"
] | [((331, 363), 'numpy.sum', 'np.sum', (['(pred_flat == labels_flat)'], {}), '(pred_flat == labels_flat)\n', (337, 363), True, 'import numpy as np\n'), ((2377, 2420), 'datetime.timedelta', 'datetime.timedelta', ([], {'seconds': 'elapsed_rounded'}), '(seconds=elapsed_rounded)\n', (2395, 2420), False, 'import datetime\n'), ((1624, 1656), 'torch.utils.data.SequentialSampler', 'SequentialSampler', (['train_dataset'], {}), '(train_dataset)\n', (1641, 1656), False, 'from torch.utils.data import DataLoader, SequentialSampler\n'), ((1947, 1977), 'torch.utils.data.SequentialSampler', 'SequentialSampler', (['val_dataset'], {}), '(val_dataset)\n', (1964, 1977), False, 'from torch.utils.data import DataLoader, SequentialSampler\n')] |
import numpy as np
import scipy.fftpack as fft
import sys
sys.path.append('../laplace_solver/')
import laplace_solver as lsolve
from scipy.integrate import cumtrapz
def fourier_inverse_curl(Bx, By, Bz, x, y, z, method='fourier', pad=True):
r"""
Invert curl with pseudo-spectral method described in MacKay 2006.
"""
shape = Bx.shape
Bx_copy = np.array(Bx)
By_copy = np.array(By)
Bz_copy = np.array(Bz)
if pad:
Bx = np.pad(Bx, pad_width=zip(shape, shape),
mode='reflect')
By = np.pad(By, pad_width=zip(shape, shape),
mode='reflect')
Bz = np.pad(Bz, pad_width=zip(shape, shape),
mode='reflect')
kx1 = np.zeros(Bx[0, :, 0].size)
ky1 = np.zeros(By[:, 0, 0].size)
kz1 = np.zeros(Bz[0, 0, :].size)
dx = x[0, 1, 0] - x[0, 0, 0]
dy = y[1, 0, 0] - y[0, 0, 0]
dz = z[0, 0, 1] - z[0, 0, 0]
nx = kx1.size
ny = ky1.size
nz = kz1.size
kx1 = fft.fftfreq(nx, dx)
ky1 = fft.fftfreq(ny, dy)
kz1 = fft.fftfreq(nz, dz)
kx, ky, kz = np.meshgrid(kx1, ky1, kz1)
if method == 'fourier':
Bx_k = np.fft.fftn(Bx)
By_k = np.fft.fftn(By)
Bz_k = np.fft.fftn(Bz)
if method == 'cosine':
Bx_k = lsolve.dct_3d(shape, Bx)
By_k = lsolve.dct_3d(shape, By)
Bz_k = lsolve.dct_3d(shape, Bz)
k_squared = kx**2. + ky**2. + kz**2.
if method == 'fourier':
Ax_k = 1j*(ky*Bz_k - kz*By_k)/k_squared
Ay_k = 1j*(kz*Bx_k - kx*Bz_k)/k_squared
Az_k = 1j*(kx*By_k - ky*Bx_k)/k_squared
if method == 'cosine':
Ax_k = (ky*Bz_k - kz*By_k)/k_squared
Ay_k = (kz*Bx_k - kx*Bz_k)/k_squared
Az_k = (kx*By_k - ky*Bx_k)/k_squared
Ax_k[0, 0, 0] = 0.
Ay_k[0, 0, 0] = 0.
Az_k[0, 0, 0] = 0.
if method == 'fourier':
Ax = np.real(np.fft.ifftn(Ax_k))
Ay = np.real(np.fft.ifftn(Ay_k))
Az = np.real(np.fft.ifftn(Az_k))
if method == 'cosine':
Ax = lsolve.idct_3d(shape, Ax_k)
Ay = lsolve.idct_3d(shape, Ay_k)
Az = lsolve.idct_3d(shape, Az_k)
if pad:
Ax = Ax[shape[0]:shape[0]*2,
shape[1]:shape[1]*2,
shape[2]:shape[2]*2]
Ay = Ay[shape[0]:shape[0]*2,
shape[1]:shape[1]*2,
shape[2]:shape[2]*2]
Az = Az[shape[0]:shape[0]*2,
shape[1]:shape[1]*2,
shape[2]:shape[2]*2]
B0_x = np.mean(Bx_copy)
B0_y = np.mean(By_copy)
B0_z = np.mean(Bz_copy)
A0_x = -(y*B0_z - z*B0_y)/2.
A0_y = -(z*B0_x - x*B0_z)/2.
A0_z = -(x*B0_y - y*B0_x)/2.
Ax = Ax + A0_x
Ay = Ay + A0_y
Az = Az + A0_z
return [Ax, Ay, Az]
def devore_invert_curl(mesh, b_field, with_z=True):
r"""
"""
b_field = np.asarray(b_field)
dz = mesh[2][0, 0, 1] - mesh[2][0, 0, 0]
z_length = mesh[0].shape[2]
A_0x, A_0y = devore_A_0(mesh, b_field)
A_x = np.expand_dims(A_0x, 2)
A_y = np.expand_dims(A_0y, 2)
A_x = np.repeat(A_x, z_length, axis=2)
A_y = np.repeat(A_y, z_length, axis=2)
A_x += cumtrapz(b_field[1], axis=2, dx=dz, initial=0)
A_y -= cumtrapz(b_field[0], axis=2, dx=dz, initial=0)
if with_z:
A_z = np.zeros(mesh[0].shape)
return A_x, A_y, A_z
else:
return A_x, A_y
def devore_A_0(mesh, b_field):
r"""
"""
dx = mesh[0][0, 1, 0] - mesh[0][0, 0, 0]
dy = mesh[1][1, 0, 0] - mesh[1][0, 0, 0]
A_0x = -0.5*cumtrapz(b_field[2, :, :, 0], axis=0, dx=dy, initial=0)
A_0y = 0.5*cumtrapz(b_field[2, :, :, 0], axis=1, dx=dx, initial=0)
return A_0x, A_0y
| [
"numpy.mean",
"numpy.repeat",
"scipy.fftpack.fftfreq",
"numpy.asarray",
"scipy.integrate.cumtrapz",
"numpy.fft.fftn",
"numpy.array",
"numpy.zeros",
"laplace_solver.dct_3d",
"laplace_solver.idct_3d",
"numpy.expand_dims",
"numpy.meshgrid",
"numpy.fft.ifftn",
"sys.path.append"
] | [((58, 95), 'sys.path.append', 'sys.path.append', (['"""../laplace_solver/"""'], {}), "('../laplace_solver/')\n", (73, 95), False, 'import sys\n'), ((363, 375), 'numpy.array', 'np.array', (['Bx'], {}), '(Bx)\n', (371, 375), True, 'import numpy as np\n'), ((390, 402), 'numpy.array', 'np.array', (['By'], {}), '(By)\n', (398, 402), True, 'import numpy as np\n'), ((417, 429), 'numpy.array', 'np.array', (['Bz'], {}), '(Bz)\n', (425, 429), True, 'import numpy as np\n'), ((721, 747), 'numpy.zeros', 'np.zeros', (['Bx[0, :, 0].size'], {}), '(Bx[0, :, 0].size)\n', (729, 747), True, 'import numpy as np\n'), ((758, 784), 'numpy.zeros', 'np.zeros', (['By[:, 0, 0].size'], {}), '(By[:, 0, 0].size)\n', (766, 784), True, 'import numpy as np\n'), ((795, 821), 'numpy.zeros', 'np.zeros', (['Bz[0, 0, :].size'], {}), '(Bz[0, 0, :].size)\n', (803, 821), True, 'import numpy as np\n'), ((988, 1007), 'scipy.fftpack.fftfreq', 'fft.fftfreq', (['nx', 'dx'], {}), '(nx, dx)\n', (999, 1007), True, 'import scipy.fftpack as fft\n'), ((1018, 1037), 'scipy.fftpack.fftfreq', 'fft.fftfreq', (['ny', 'dy'], {}), '(ny, dy)\n', (1029, 1037), True, 'import scipy.fftpack as fft\n'), ((1048, 1067), 'scipy.fftpack.fftfreq', 'fft.fftfreq', (['nz', 'dz'], {}), '(nz, dz)\n', (1059, 1067), True, 'import scipy.fftpack as fft\n'), ((1086, 1112), 'numpy.meshgrid', 'np.meshgrid', (['kx1', 'ky1', 'kz1'], {}), '(kx1, ky1, kz1)\n', (1097, 1112), True, 'import numpy as np\n'), ((2490, 2506), 'numpy.mean', 'np.mean', (['Bx_copy'], {}), '(Bx_copy)\n', (2497, 2506), True, 'import numpy as np\n'), ((2518, 2534), 'numpy.mean', 'np.mean', (['By_copy'], {}), '(By_copy)\n', (2525, 2534), True, 'import numpy as np\n'), ((2546, 2562), 'numpy.mean', 'np.mean', (['Bz_copy'], {}), '(Bz_copy)\n', (2553, 2562), True, 'import numpy as np\n'), ((2831, 2850), 'numpy.asarray', 'np.asarray', (['b_field'], {}), '(b_field)\n', (2841, 2850), True, 'import numpy as np\n'), ((2981, 3004), 'numpy.expand_dims', 'np.expand_dims', (['A_0x', '(2)'], {}), '(A_0x, 2)\n', (2995, 3004), True, 'import numpy as np\n'), ((3015, 3038), 'numpy.expand_dims', 'np.expand_dims', (['A_0y', '(2)'], {}), '(A_0y, 2)\n', (3029, 3038), True, 'import numpy as np\n'), ((3049, 3081), 'numpy.repeat', 'np.repeat', (['A_x', 'z_length'], {'axis': '(2)'}), '(A_x, z_length, axis=2)\n', (3058, 3081), True, 'import numpy as np\n'), ((3092, 3124), 'numpy.repeat', 'np.repeat', (['A_y', 'z_length'], {'axis': '(2)'}), '(A_y, z_length, axis=2)\n', (3101, 3124), True, 'import numpy as np\n'), ((3136, 3182), 'scipy.integrate.cumtrapz', 'cumtrapz', (['b_field[1]'], {'axis': '(2)', 'dx': 'dz', 'initial': '(0)'}), '(b_field[1], axis=2, dx=dz, initial=0)\n', (3144, 3182), False, 'from scipy.integrate import cumtrapz\n'), ((3194, 3240), 'scipy.integrate.cumtrapz', 'cumtrapz', (['b_field[0]'], {'axis': '(2)', 'dx': 'dz', 'initial': '(0)'}), '(b_field[0], axis=2, dx=dz, initial=0)\n', (3202, 3240), False, 'from scipy.integrate import cumtrapz\n'), ((1157, 1172), 'numpy.fft.fftn', 'np.fft.fftn', (['Bx'], {}), '(Bx)\n', (1168, 1172), True, 'import numpy as np\n'), ((1188, 1203), 'numpy.fft.fftn', 'np.fft.fftn', (['By'], {}), '(By)\n', (1199, 1203), True, 'import numpy as np\n'), ((1219, 1234), 'numpy.fft.fftn', 'np.fft.fftn', (['Bz'], {}), '(Bz)\n', (1230, 1234), True, 'import numpy as np\n'), ((1277, 1301), 'laplace_solver.dct_3d', 'lsolve.dct_3d', (['shape', 'Bx'], {}), '(shape, Bx)\n', (1290, 1301), True, 'import laplace_solver as lsolve\n'), ((1317, 1341), 'laplace_solver.dct_3d', 'lsolve.dct_3d', (['shape', 'By'], {}), '(shape, By)\n', (1330, 1341), True, 'import laplace_solver as lsolve\n'), ((1357, 1381), 'laplace_solver.dct_3d', 'lsolve.dct_3d', (['shape', 'Bz'], {}), '(shape, Bz)\n', (1370, 1381), True, 'import laplace_solver as lsolve\n'), ((2022, 2049), 'laplace_solver.idct_3d', 'lsolve.idct_3d', (['shape', 'Ax_k'], {}), '(shape, Ax_k)\n', (2036, 2049), True, 'import laplace_solver as lsolve\n'), ((2063, 2090), 'laplace_solver.idct_3d', 'lsolve.idct_3d', (['shape', 'Ay_k'], {}), '(shape, Ay_k)\n', (2077, 2090), True, 'import laplace_solver as lsolve\n'), ((2104, 2131), 'laplace_solver.idct_3d', 'lsolve.idct_3d', (['shape', 'Az_k'], {}), '(shape, Az_k)\n', (2118, 2131), True, 'import laplace_solver as lsolve\n'), ((3270, 3293), 'numpy.zeros', 'np.zeros', (['mesh[0].shape'], {}), '(mesh[0].shape)\n', (3278, 3293), True, 'import numpy as np\n'), ((3513, 3568), 'scipy.integrate.cumtrapz', 'cumtrapz', (['b_field[2, :, :, 0]'], {'axis': '(0)', 'dx': 'dy', 'initial': '(0)'}), '(b_field[2, :, :, 0], axis=0, dx=dy, initial=0)\n', (3521, 3568), False, 'from scipy.integrate import cumtrapz\n'), ((3584, 3639), 'scipy.integrate.cumtrapz', 'cumtrapz', (['b_field[2, :, :, 0]'], {'axis': '(1)', 'dx': 'dx', 'initial': '(0)'}), '(b_field[2, :, :, 0], axis=1, dx=dx, initial=0)\n', (3592, 3639), False, 'from scipy.integrate import cumtrapz\n'), ((1879, 1897), 'numpy.fft.ifftn', 'np.fft.ifftn', (['Ax_k'], {}), '(Ax_k)\n', (1891, 1897), True, 'import numpy as np\n'), ((1920, 1938), 'numpy.fft.ifftn', 'np.fft.ifftn', (['Ay_k'], {}), '(Ay_k)\n', (1932, 1938), True, 'import numpy as np\n'), ((1961, 1979), 'numpy.fft.ifftn', 'np.fft.ifftn', (['Az_k'], {}), '(Az_k)\n', (1973, 1979), True, 'import numpy as np\n')] |
import numpy as np
import sys
import tensorflow as tf
import cv2
import time
import sys
from .utils import cv2_letterbox_resize, download_from_url
import zipfile
import os
@tf.function
def transform_targets_for_output(y_true, grid_y, grid_x, anchor_idxs, classes):
# y_true: (N, boxes, (x1, y1, x2, y2, class, best_anchor))
N = tf.shape(y_true)[0]
# y_true_out: (N, grid, grid, anchors, [x, y, w, h, obj, class])
y_true_out = tf.zeros((N, grid_y, grid_x, tf.shape(anchor_idxs)[0], 6))
anchor_idxs = tf.cast(anchor_idxs, tf.int32)
indexes = tf.TensorArray(tf.int32, 1, dynamic_size=True)
updates = tf.TensorArray(tf.float32, 1, dynamic_size=True)
idx = 0
for i in tf.range(N):
for j in tf.range(tf.shape(y_true)[1]):
if tf.equal(y_true[i][j][2], 0):
continue
anchor_eq = tf.equal(anchor_idxs, tf.cast(y_true[i][j][5], tf.int32))
if tf.reduce_any(anchor_eq):
box = y_true[i][j][0:4]
box_xy = (y_true[i][j][0:2] + y_true[i][j][2:4]) / 2.
anchor_idx = tf.cast(tf.where(anchor_eq), tf.int32)
grid_size = tf.cast(tf.stack([grid_x, grid_y], axis=-1), tf.float32)
grid_xy = tf.cast(box_xy * grid_size, tf.int32)
# grid[y][x][anchor] = (tx, ty, bw, bh, obj, class)
indexes = indexes.write(idx, [i, grid_xy[1], grid_xy[0], anchor_idx[0][0]])
updates = updates.write(idx, [box[0], box[1], box[2], box[3], 1, y_true[i][j][4]])
idx += 1
y_ture_out = tf.tensor_scatter_nd_update(y_true_out, indexes.stack(), updates.stack())
return y_ture_out
def transform_targets(y_train, size, anchors, anchor_masks, classes, tiny=True):
y_outs = []
if tiny:
grid_y, grid_x = size[0] // 16, size[1] // 16
else:
grid_y, grid_x = size[0] // 32, size[1] // 32
# calculate anchor index for true boxes
anchors = tf.cast(anchors, tf.float32)
anchor_area = anchors[..., 0] * anchors[..., 1]
box_wh = y_train[..., 2:4] - y_train[..., 0:2]
box_wh = tf.tile(tf.expand_dims(box_wh, -2), (1, 1, tf.shape(anchors)[0], 1))
box_area = box_wh[..., 0] * box_wh[..., 1]
intersection = tf.minimum(box_wh[..., 0], anchors[..., 0]) * tf.minimum(box_wh[..., 1], anchors[..., 1])
iou = intersection / (box_area + anchor_area - intersection)
anchor_idx = tf.cast(tf.argmax(iou, axis=-1), tf.float32)
anchor_idx = tf.expand_dims(anchor_idx, axis=-1)
y_train = tf.concat([y_train, anchor_idx], axis=-1)
for anchor_idxs in anchor_masks:
y_out = transform_targets_for_output(y_train, grid_y, grid_x, anchor_idxs, classes)
y_outs.append(y_out)
grid_x *= 2
grid_y *= 2
return tuple(y_outs)
def decode_line(line, size):
# Decode the line to tensor
line = line.numpy().decode()
line_parts = line.strip().split()
imgname = line_parts[0]
x_train = cv2.imread(imgname)
#x_train = transform_images(x_train, size)
x_train, amat = cv2_letterbox_resize(x_train, (size, size))
x_train = x_train / 255.
xmins, ymins, xmaxs, ymaxs, labels = [], [], [], [], []
bbox_with_labels = line_parts[1:]
for bbox_with_label in bbox_with_labels:
bbox_with_label_parts = bbox_with_label.split(',')
xmin = float(bbox_with_label_parts[0])
ymin = float(bbox_with_label_parts[1])
xmax = float(bbox_with_label_parts[2])
ymax = float(bbox_with_label_parts[3])
tl = np.array([xmin, ymin, 1], np.float32)
br = np.array([xmax, ymax, 1], np.float32)
tl = np.dot(amat, tl)
br = np.dot(amat, br)
xmin, ymin = tl[0], tl[1]
xmax, ymax = br[0], br[1]
xmins.append(xmin / size)
ymins.append(ymin / size)
xmaxs.append(xmax / size)
ymaxs.append(ymax / size)
labels.append(float(bbox_with_label_parts[4]))
assert np.all(np.array(xmins) <= 1)
y_train = np.stack((xmins, ymins, xmaxs, ymaxs, labels), axis=1)
paddings = [[0, 100 - y_train.shape[0]], [0, 0]]
y_train = np.pad(y_train, paddings, mode='constant')
return x_train, y_train
def load_textline_dataset(file_pattern, size):
dataset = tf.data.TextLineDataset(file_pattern)
return dataset.map(lambda x: tf.py_function(func=decode_line, inp=[x, size], Tout=(tf.float32, tf.float32)))
def download_m2nist_if_not_exist():
data_rootdir = os.path.expanduser(os.path.join('~', '.m2nist'))
m2nist_zip_path = os.path.join(data_rootdir, 'm2nist.zip')
if os.path.exists(m2nist_zip_path):
return
os.makedirs(data_rootdir, exist_ok=True)
m2nist_zip_url = 'https://raw.githubusercontent.com/akkaze/datasets/master/m2nist.zip'
fail_counter = 0
while True:
try:
print('Trying to download m2nist...')
download_from_url(m2nist_zip_url, m2nist_zip_path)
break
except Exception as exc:
fail_counter += 1
print('Errors occured : {0}'.format(exc))
if fail_counter >= 6:
print(
'Please try to download dataset from {0} by yourself and put it under the directory {1}'.format(
m2nist_zip_path), data_rootdir)
time.sleep(5)
continue
zipf = zipfile.ZipFile(m2nist_zip_path)
zipf.extractall(data_rootdir)
zipf.close()
def load_m2nist_dataset(dst_size=(64, 64), val_ratio=0.2):
download_m2nist_if_not_exist()
data_rootdir = os.path.expanduser(os.path.join('~', '.m2nist'))
imgs = np.load(os.path.join(data_rootdir, 'combined.npy')).astype(np.uint8)
num_data = imgs.shape[0]
num_train = int(num_data * (1 - val_ratio))
def transform_target(img, line, expected_size):
img = img.numpy()
line = line.numpy().decode()
expected_size = tuple(expected_size.numpy())
img, amat = cv2_letterbox_resize(img, expected_size)
bbox_with_labels = line.strip().split()[1:]
xmins, xmaxs, ymins, ymaxs, labels = [], [], [], [], []
for bbox_with_label in bbox_with_labels:
bbox_with_label_parts = bbox_with_label.split(',')
xmin = float(bbox_with_label_parts[0])
ymin = float(bbox_with_label_parts[1])
xmax = float(bbox_with_label_parts[2])
ymax = float(bbox_with_label_parts[3])
label = float(bbox_with_label_parts[4])
tl = np.array([xmin, ymin, 1], np.float32)
br = np.array([xmax, ymax, 1], np.float32)
tl = np.dot(amat, tl)
br = np.dot(amat, br)
xmin, ymin = tl[0], tl[1]
xmax, ymax = br[0], br[1]
xmins.append(xmin / expected_size[0])
ymins.append(ymin / expected_size[1])
xmaxs.append(xmax / expected_size[0])
ymaxs.append(ymax / expected_size[1])
labels.append(label)
img = img.astype(np.float32) / 255.
bbox = np.stack((xmins, ymins, xmaxs, ymaxs, labels), axis=1)
paddings = [[0, 100 - bbox.shape[0]], [0, 0]]
bbox = np.pad(bbox, paddings, mode='constant')
return img, bbox
def tf_transform_target(img, line):
img, mask = tf.py_function(func=transform_target, inp=[img, line, dst_size], Tout=[tf.float32, tf.float32])
img.set_shape((*dst_size[::-1], 1))
mask.set_shape((100, 5))
return img, mask
img_dataset = tf.data.Dataset.from_tensor_slices(imgs)
bbox_dataset = tf.data.TextLineDataset(os.path.join(data_rootdir, 'bbox.txt'))
dataset = tf.data.Dataset.zip((img_dataset, bbox_dataset))
dataset = dataset.map(lambda x, y: tf_transform_target(x, y))
train_dataset = dataset.take(num_train)
val_dataset = dataset.skip(num_train)
return train_dataset, val_dataset | [
"tensorflow.equal",
"tensorflow.shape",
"zipfile.ZipFile",
"time.sleep",
"numpy.array",
"tensorflow.cast",
"os.path.exists",
"tensorflow.data.Dataset.from_tensor_slices",
"tensorflow.py_function",
"tensorflow.concat",
"numpy.stack",
"numpy.dot",
"tensorflow.reduce_any",
"tensorflow.stack",... | [((523, 553), 'tensorflow.cast', 'tf.cast', (['anchor_idxs', 'tf.int32'], {}), '(anchor_idxs, tf.int32)\n', (530, 553), True, 'import tensorflow as tf\n'), ((569, 615), 'tensorflow.TensorArray', 'tf.TensorArray', (['tf.int32', '(1)'], {'dynamic_size': '(True)'}), '(tf.int32, 1, dynamic_size=True)\n', (583, 615), True, 'import tensorflow as tf\n'), ((630, 678), 'tensorflow.TensorArray', 'tf.TensorArray', (['tf.float32', '(1)'], {'dynamic_size': '(True)'}), '(tf.float32, 1, dynamic_size=True)\n', (644, 678), True, 'import tensorflow as tf\n'), ((704, 715), 'tensorflow.range', 'tf.range', (['N'], {}), '(N)\n', (712, 715), True, 'import tensorflow as tf\n'), ((1973, 2001), 'tensorflow.cast', 'tf.cast', (['anchors', 'tf.float32'], {}), '(anchors, tf.float32)\n', (1980, 2001), True, 'import tensorflow as tf\n'), ((2487, 2522), 'tensorflow.expand_dims', 'tf.expand_dims', (['anchor_idx'], {'axis': '(-1)'}), '(anchor_idx, axis=-1)\n', (2501, 2522), True, 'import tensorflow as tf\n'), ((2538, 2579), 'tensorflow.concat', 'tf.concat', (['[y_train, anchor_idx]'], {'axis': '(-1)'}), '([y_train, anchor_idx], axis=-1)\n', (2547, 2579), True, 'import tensorflow as tf\n'), ((2981, 3000), 'cv2.imread', 'cv2.imread', (['imgname'], {}), '(imgname)\n', (2991, 3000), False, 'import cv2\n'), ((4006, 4060), 'numpy.stack', 'np.stack', (['(xmins, ymins, xmaxs, ymaxs, labels)'], {'axis': '(1)'}), '((xmins, ymins, xmaxs, ymaxs, labels), axis=1)\n', (4014, 4060), True, 'import numpy as np\n'), ((4128, 4170), 'numpy.pad', 'np.pad', (['y_train', 'paddings'], {'mode': '"""constant"""'}), "(y_train, paddings, mode='constant')\n", (4134, 4170), True, 'import numpy as np\n'), ((4262, 4299), 'tensorflow.data.TextLineDataset', 'tf.data.TextLineDataset', (['file_pattern'], {}), '(file_pattern)\n', (4285, 4299), True, 'import tensorflow as tf\n'), ((4541, 4581), 'os.path.join', 'os.path.join', (['data_rootdir', '"""m2nist.zip"""'], {}), "(data_rootdir, 'm2nist.zip')\n", (4553, 4581), False, 'import os\n'), ((4589, 4620), 'os.path.exists', 'os.path.exists', (['m2nist_zip_path'], {}), '(m2nist_zip_path)\n', (4603, 4620), False, 'import os\n'), ((4641, 4681), 'os.makedirs', 'os.makedirs', (['data_rootdir'], {'exist_ok': '(True)'}), '(data_rootdir, exist_ok=True)\n', (4652, 4681), False, 'import os\n'), ((5359, 5391), 'zipfile.ZipFile', 'zipfile.ZipFile', (['m2nist_zip_path'], {}), '(m2nist_zip_path)\n', (5374, 5391), False, 'import zipfile\n'), ((7494, 7534), 'tensorflow.data.Dataset.from_tensor_slices', 'tf.data.Dataset.from_tensor_slices', (['imgs'], {}), '(imgs)\n', (7528, 7534), True, 'import tensorflow as tf\n'), ((7632, 7680), 'tensorflow.data.Dataset.zip', 'tf.data.Dataset.zip', (['(img_dataset, bbox_dataset)'], {}), '((img_dataset, bbox_dataset))\n', (7651, 7680), True, 'import tensorflow as tf\n'), ((338, 354), 'tensorflow.shape', 'tf.shape', (['y_true'], {}), '(y_true)\n', (346, 354), True, 'import tensorflow as tf\n'), ((2126, 2152), 'tensorflow.expand_dims', 'tf.expand_dims', (['box_wh', '(-2)'], {}), '(box_wh, -2)\n', (2140, 2152), True, 'import tensorflow as tf\n'), ((2253, 2296), 'tensorflow.minimum', 'tf.minimum', (['box_wh[..., 0]', 'anchors[..., 0]'], {}), '(box_wh[..., 0], anchors[..., 0])\n', (2263, 2296), True, 'import tensorflow as tf\n'), ((2299, 2342), 'tensorflow.minimum', 'tf.minimum', (['box_wh[..., 1]', 'anchors[..., 1]'], {}), '(box_wh[..., 1], anchors[..., 1])\n', (2309, 2342), True, 'import tensorflow as tf\n'), ((2433, 2456), 'tensorflow.argmax', 'tf.argmax', (['iou'], {'axis': '(-1)'}), '(iou, axis=-1)\n', (2442, 2456), True, 'import tensorflow as tf\n'), ((3544, 3581), 'numpy.array', 'np.array', (['[xmin, ymin, 1]', 'np.float32'], {}), '([xmin, ymin, 1], np.float32)\n', (3552, 3581), True, 'import numpy as np\n'), ((3595, 3632), 'numpy.array', 'np.array', (['[xmax, ymax, 1]', 'np.float32'], {}), '([xmax, ymax, 1], np.float32)\n', (3603, 3632), True, 'import numpy as np\n'), ((3646, 3662), 'numpy.dot', 'np.dot', (['amat', 'tl'], {}), '(amat, tl)\n', (3652, 3662), True, 'import numpy as np\n'), ((3676, 3692), 'numpy.dot', 'np.dot', (['amat', 'br'], {}), '(amat, br)\n', (3682, 3692), True, 'import numpy as np\n'), ((4489, 4517), 'os.path.join', 'os.path.join', (['"""~"""', '""".m2nist"""'], {}), "('~', '.m2nist')\n", (4501, 4517), False, 'import os\n'), ((5577, 5605), 'os.path.join', 'os.path.join', (['"""~"""', '""".m2nist"""'], {}), "('~', '.m2nist')\n", (5589, 5605), False, 'import os\n'), ((7027, 7081), 'numpy.stack', 'np.stack', (['(xmins, ymins, xmaxs, ymaxs, labels)'], {'axis': '(1)'}), '((xmins, ymins, xmaxs, ymaxs, labels), axis=1)\n', (7035, 7081), True, 'import numpy as np\n'), ((7151, 7190), 'numpy.pad', 'np.pad', (['bbox', 'paddings'], {'mode': '"""constant"""'}), "(bbox, paddings, mode='constant')\n", (7157, 7190), True, 'import numpy as np\n'), ((7277, 7377), 'tensorflow.py_function', 'tf.py_function', ([], {'func': 'transform_target', 'inp': '[img, line, dst_size]', 'Tout': '[tf.float32, tf.float32]'}), '(func=transform_target, inp=[img, line, dst_size], Tout=[tf.\n float32, tf.float32])\n', (7291, 7377), True, 'import tensorflow as tf\n'), ((7578, 7616), 'os.path.join', 'os.path.join', (['data_rootdir', '"""bbox.txt"""'], {}), "(data_rootdir, 'bbox.txt')\n", (7590, 7616), False, 'import os\n'), ((780, 808), 'tensorflow.equal', 'tf.equal', (['y_true[i][j][2]', '(0)'], {}), '(y_true[i][j][2], 0)\n', (788, 808), True, 'import tensorflow as tf\n'), ((933, 957), 'tensorflow.reduce_any', 'tf.reduce_any', (['anchor_eq'], {}), '(anchor_eq)\n', (946, 957), True, 'import tensorflow as tf\n'), ((3970, 3985), 'numpy.array', 'np.array', (['xmins'], {}), '(xmins)\n', (3978, 3985), True, 'import numpy as np\n'), ((4333, 4411), 'tensorflow.py_function', 'tf.py_function', ([], {'func': 'decode_line', 'inp': '[x, size]', 'Tout': '(tf.float32, tf.float32)'}), '(func=decode_line, inp=[x, size], Tout=(tf.float32, tf.float32))\n', (4347, 4411), True, 'import tensorflow as tf\n'), ((6496, 6533), 'numpy.array', 'np.array', (['[xmin, ymin, 1]', 'np.float32'], {}), '([xmin, ymin, 1], np.float32)\n', (6504, 6533), True, 'import numpy as np\n'), ((6551, 6588), 'numpy.array', 'np.array', (['[xmax, ymax, 1]', 'np.float32'], {}), '([xmax, ymax, 1], np.float32)\n', (6559, 6588), True, 'import numpy as np\n'), ((6606, 6622), 'numpy.dot', 'np.dot', (['amat', 'tl'], {}), '(amat, tl)\n', (6612, 6622), True, 'import numpy as np\n'), ((6640, 6656), 'numpy.dot', 'np.dot', (['amat', 'br'], {}), '(amat, br)\n', (6646, 6656), True, 'import numpy as np\n'), ((474, 495), 'tensorflow.shape', 'tf.shape', (['anchor_idxs'], {}), '(anchor_idxs)\n', (482, 495), True, 'import tensorflow as tf\n'), ((743, 759), 'tensorflow.shape', 'tf.shape', (['y_true'], {}), '(y_true)\n', (751, 759), True, 'import tensorflow as tf\n'), ((881, 915), 'tensorflow.cast', 'tf.cast', (['y_true[i][j][5]', 'tf.int32'], {}), '(y_true[i][j][5], tf.int32)\n', (888, 915), True, 'import tensorflow as tf\n'), ((1249, 1286), 'tensorflow.cast', 'tf.cast', (['(box_xy * grid_size)', 'tf.int32'], {}), '(box_xy * grid_size, tf.int32)\n', (1256, 1286), True, 'import tensorflow as tf\n'), ((2161, 2178), 'tensorflow.shape', 'tf.shape', (['anchors'], {}), '(anchors)\n', (2169, 2178), True, 'import tensorflow as tf\n'), ((5313, 5326), 'time.sleep', 'time.sleep', (['(5)'], {}), '(5)\n', (5323, 5326), False, 'import time\n'), ((5626, 5668), 'os.path.join', 'os.path.join', (['data_rootdir', '"""combined.npy"""'], {}), "(data_rootdir, 'combined.npy')\n", (5638, 5668), False, 'import os\n'), ((1107, 1126), 'tensorflow.where', 'tf.where', (['anchor_eq'], {}), '(anchor_eq)\n', (1115, 1126), True, 'import tensorflow as tf\n'), ((1174, 1209), 'tensorflow.stack', 'tf.stack', (['[grid_x, grid_y]'], {'axis': '(-1)'}), '([grid_x, grid_y], axis=-1)\n', (1182, 1209), True, 'import tensorflow as tf\n')] |
"""
Bridging Composite and Real: Towards End-to-end Deep Image Matting [IJCV-2021]
Dataset processing.
Copyright (c) 2021, <NAME> (<EMAIL>)
Licensed under the MIT License (see LICENSE for details)
Github repo: https://github.com/JizhiziLi/GFM
Paper link (Arxiv): https://arxiv.org/abs/2010.16188
"""
from config import *
from util import *
import torch
import cv2
import os
import random
import numpy as np
from PIL import Image
from torch.utils.data import Dataset, DataLoader
from tqdm import tqdm
import json
import logging
import pickle
from torchvision import transforms
from torch.autograd import Variable
from skimage.transform import resize
#########################
## Data transformer
#########################
class MattingTransform(object):
def __init__(self):
super(MattingTransform, self).__init__()
def __call__(self, *argv):
ori = argv[0]
h, w, c = ori.shape
rand_ind = random.randint(0, len(CROP_SIZE) - 1)
crop_size = CROP_SIZE[rand_ind] if CROP_SIZE[rand_ind]<min(h, w) else 320
resize_size = RESIZE_SIZE
### generate crop centered in transition area randomly
trimap = argv[1]
trimap_crop = trimap[:h-crop_size, :w-crop_size]
target = np.where(trimap_crop == 128) if random.random() < 0.5 else np.where(trimap_crop > -100)
if len(target[0])==0:
target = np.where(trimap_crop > -100)
rand_ind = np.random.randint(len(target[0]), size = 1)[0]
cropx, cropy = target[1][rand_ind], target[0][rand_ind]
# # flip the samples randomly
flip_flag=True if random.random()<0.5 else False
# generate samples (crop, flip, resize)
argv_transform = []
for item in argv:
item = item[cropy:cropy+crop_size, cropx:cropx+crop_size]
if flip_flag:
item = cv2.flip(item, 1)
item = cv2.resize(item, (resize_size, resize_size), interpolation=cv2.INTER_LINEAR)
argv_transform.append(item)
return argv_transform
#########################
## Data Loader
#########################
class MattingDataset(torch.utils.data.Dataset):
def __init__(self, args, transform):
self.samples=[]
self.transform = transform
self.logging = args.logging
self.BG_CHOICE = args.bg_choice
self.backbone = args.backbone
self.FG_CF = True if args.fg_generate=='closed_form' else False
self.RSSN_DENOISE = args.rssn_denoise
self.logging.info('===> Loading training set')
self.samples += generate_paths_for_dataset(args)
self.logging.info(f"\t--crop_size: {CROP_SIZE} | resize: {RESIZE_SIZE}")
self.logging.info("\t--Valid Samples: {}".format(len(self.samples)))
def __getitem__(self,index):
# Prepare training sample paths
ori_path = self.samples[index][0]
mask_path = self.samples[index][1]
fg_path = self.samples[index][2] if self.FG_CF else None
bg_path = self.samples[index][3] if (self.FG_CF or self.BG_CHOICE!='original') else None
fg_path_denoise = self.samples[index][4] if (self.BG_CHOICE=='hd' and self.RSSN_DENOISE) else None
bg_path_denoise = self.samples[index][5] if (self.BG_CHOICE=='hd' and self.RSSN_DENOISE) else None
# Prepare ori/mask/fg/bg (mandatary)
ori = np.array(Image.open(ori_path))
mask = trim_img(np.array(Image.open(mask_path)))
fg = process_fgbg(ori, mask, True, fg_path)
bg = process_fgbg(ori, mask, False, bg_path)
# Prepare composite for hd/coco
if self.BG_CHOICE == 'hd':
fg_denoise = process_fgbg(ori, mask, True, fg_path_denoise) if self.RSSN_DENOISE else None
bg_denoise = process_fgbg(ori, mask, True, bg_path_denoise) if self.RSSN_DENOISE else None
ori, fg, bg = generate_composite_rssn(fg, bg, mask, fg_denoise, bg_denoise)
elif self.BG_CHOICE == 'coco':
ori, fg, bg = generate_composite_coco(fg, bg, mask)
# Generate trimap/dilation/erosion online
kernel_size = random.randint(25,35)
trimap = gen_trimap_with_dilate(mask, kernel_size)
dilation = gen_dilate(mask, kernel_size)
erosion = gen_erosion(mask, kernel_size)
# Data transformation to generate samples
# crop/flip/resize
argv = self.transform(ori, mask, fg, bg, trimap, dilation, erosion)
argv_transform = []
for item in argv:
if item.ndim<3:
item = torch.from_numpy(item.astype(np.float32)[np.newaxis, :, :])
else:
item = torch.from_numpy(item.astype(np.float32)).permute(2, 0, 1)
argv_transform.append(item)
[ori, mask, fg, bg, trimap, dilation, erosion] = argv_transform
return ori, mask, fg, bg, trimap, dilation, erosion
def __len__(self):
return len(self.samples)
| [
"PIL.Image.open",
"cv2.resize",
"cv2.flip",
"numpy.where",
"random.random",
"random.randint"
] | [((3715, 3737), 'random.randint', 'random.randint', (['(25)', '(35)'], {}), '(25, 35)\n', (3729, 3737), False, 'import random\n'), ((1181, 1209), 'numpy.where', 'np.where', (['(trimap_crop == 128)'], {}), '(trimap_crop == 128)\n', (1189, 1209), True, 'import numpy as np\n'), ((1240, 1268), 'numpy.where', 'np.where', (['(trimap_crop > -100)'], {}), '(trimap_crop > -100)\n', (1248, 1268), True, 'import numpy as np\n'), ((1305, 1333), 'numpy.where', 'np.where', (['(trimap_crop > -100)'], {}), '(trimap_crop > -100)\n', (1313, 1333), True, 'import numpy as np\n'), ((1737, 1813), 'cv2.resize', 'cv2.resize', (['item', '(resize_size, resize_size)'], {'interpolation': 'cv2.INTER_LINEAR'}), '(item, (resize_size, resize_size), interpolation=cv2.INTER_LINEAR)\n', (1747, 1813), False, 'import cv2\n'), ((3071, 3091), 'PIL.Image.open', 'Image.open', (['ori_path'], {}), '(ori_path)\n', (3081, 3091), False, 'from PIL import Image\n'), ((1213, 1228), 'random.random', 'random.random', ([], {}), '()\n', (1226, 1228), False, 'import random\n'), ((1505, 1520), 'random.random', 'random.random', ([], {}), '()\n', (1518, 1520), False, 'import random\n'), ((1709, 1726), 'cv2.flip', 'cv2.flip', (['item', '(1)'], {}), '(item, 1)\n', (1717, 1726), False, 'import cv2\n'), ((3120, 3141), 'PIL.Image.open', 'Image.open', (['mask_path'], {}), '(mask_path)\n', (3130, 3141), False, 'from PIL import Image\n')] |
import numpy as np
from astropy import units as u
from mpl_toolkits import mplot3d
import matplotlib.pyplot as plt
from json_to_dict import constants
from PS2.Ass1.ass1_utils import *
E = 80*u.keV
m = constants["m_e"]
q = constants["q_e"]
B =45000*u.nT
V = getV(E, m)
r_lam = getr_lam(m, V, q, B)
print("Larmor radius of a %s electron a magnetic field of %s (the average for the Earth): %s\n"
"The above assumes that the whole velocity of the electron is perpendicular to the magnetic field" %(E, B, r_lam))
print("Gives a velocity of %s" %V)
#######################################################################################################################
# Part B
# V = V.value
alpha = np.deg2rad(25)
Vperp = V * np.sin(alpha)
Vpar = V * np.cos(alpha)
r_lam = getr_lam(m, Vperp, q, B)
r_lam = r_lam.value
Vperp = Vperp.value
Vpar = Vpar.value
times = np.linspace(0,0.00001, 1001)
outArray = np.zeros((len(times), 4))
outArray[:, 0] = times
for i in range(len(times)):
t = times[i]
outArray[i, 1:] = getXYZ(t, Vperp, Vpar, r_lam)
print(outArray)
fig = plt.figure()
ax = plt.axes(projection='3d')
xline, yline, zline = outArray[:, 1], outArray[:, 2], outArray[:, 3]
ax.plot3D(xline, yline, zline)
plt.xlabel("x [m]")
plt.ylabel("y [m]")
ax.set_zlabel("z [m]")
ax.view_init(elev=40, azim=210)
plt.savefig("plots/electronPlot.pdf")
# for ii in range(0, 360, 10):
# ax.view_init(elev=40., azim=ii)
# plt.savefig("plots/movie%d.png" % ii)
plt.show()
| [
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"numpy.deg2rad",
"numpy.linspace",
"matplotlib.pyplot.axes",
"matplotlib.pyplot.figure",
"numpy.cos",
"numpy.sin",
"matplotlib.pyplot.show"
] | [((711, 725), 'numpy.deg2rad', 'np.deg2rad', (['(25)'], {}), '(25)\n', (721, 725), True, 'import numpy as np\n'), ((878, 905), 'numpy.linspace', 'np.linspace', (['(0)', '(1e-05)', '(1001)'], {}), '(0, 1e-05, 1001)\n', (889, 905), True, 'import numpy as np\n'), ((1091, 1103), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1101, 1103), True, 'import matplotlib.pyplot as plt\n'), ((1109, 1134), 'matplotlib.pyplot.axes', 'plt.axes', ([], {'projection': '"""3d"""'}), "(projection='3d')\n", (1117, 1134), True, 'import matplotlib.pyplot as plt\n'), ((1236, 1255), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""x [m]"""'], {}), "('x [m]')\n", (1246, 1255), True, 'import matplotlib.pyplot as plt\n'), ((1256, 1275), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""y [m]"""'], {}), "('y [m]')\n", (1266, 1275), True, 'import matplotlib.pyplot as plt\n'), ((1333, 1370), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""plots/electronPlot.pdf"""'], {}), "('plots/electronPlot.pdf')\n", (1344, 1370), True, 'import matplotlib.pyplot as plt\n'), ((1486, 1496), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1494, 1496), True, 'import matplotlib.pyplot as plt\n'), ((739, 752), 'numpy.sin', 'np.sin', (['alpha'], {}), '(alpha)\n', (745, 752), True, 'import numpy as np\n'), ((764, 777), 'numpy.cos', 'np.cos', (['alpha'], {}), '(alpha)\n', (770, 777), True, 'import numpy as np\n')] |
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
import numpy as np
import os
app = Flask(__name__)
# DB
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite3'
db = SQLAlchemy(app)
# MA
ma = Marshmallow(app)
# CONFIG
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
app.config['PUBLIC_FOLDER'] = os.path.join('app','static','public')
app.config['DATA_FOLDER'] = "data"
# ROUTES
from app.routes import index
from app.routes import students
from app.routes import subjects
from app.routes import train
from app.routes import attendance
# CREATE EMPTY MODEL
if not os.path.exists(app.config['DATA_FOLDER']):
os.mkdir(app.config['DATA_FOLDER'])
known_face_encodings = []
known_face_names = []
np.save(os.path.join(app.config['DATA_FOLDER'], "face_encodings.npy"), np.asarray(known_face_encodings))
np.save(os.path.join(app.config['DATA_FOLDER'], "face_ids.npy"), np.asarray(known_face_names))
print("Created empty models")
db.create_all()
| [
"os.path.exists",
"flask.Flask",
"flask_marshmallow.Marshmallow",
"os.path.join",
"numpy.asarray",
"os.mkdir",
"flask_sqlalchemy.SQLAlchemy"
] | [((142, 157), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (147, 157), False, 'from flask import Flask\n'), ((232, 247), 'flask_sqlalchemy.SQLAlchemy', 'SQLAlchemy', (['app'], {}), '(app)\n', (242, 247), False, 'from flask_sqlalchemy import SQLAlchemy\n'), ((259, 275), 'flask_marshmallow.Marshmallow', 'Marshmallow', (['app'], {}), '(app)\n', (270, 275), False, 'from flask_marshmallow import Marshmallow\n'), ((368, 407), 'os.path.join', 'os.path.join', (['"""app"""', '"""static"""', '"""public"""'], {}), "('app', 'static', 'public')\n", (380, 407), False, 'import os\n'), ((636, 677), 'os.path.exists', 'os.path.exists', (["app.config['DATA_FOLDER']"], {}), "(app.config['DATA_FOLDER'])\n", (650, 677), False, 'import os\n'), ((683, 718), 'os.mkdir', 'os.mkdir', (["app.config['DATA_FOLDER']"], {}), "(app.config['DATA_FOLDER'])\n", (691, 718), False, 'import os\n'), ((787, 848), 'os.path.join', 'os.path.join', (["app.config['DATA_FOLDER']", '"""face_encodings.npy"""'], {}), "(app.config['DATA_FOLDER'], 'face_encodings.npy')\n", (799, 848), False, 'import os\n'), ((850, 882), 'numpy.asarray', 'np.asarray', (['known_face_encodings'], {}), '(known_face_encodings)\n', (860, 882), True, 'import numpy as np\n'), ((896, 951), 'os.path.join', 'os.path.join', (["app.config['DATA_FOLDER']", '"""face_ids.npy"""'], {}), "(app.config['DATA_FOLDER'], 'face_ids.npy')\n", (908, 951), False, 'import os\n'), ((953, 981), 'numpy.asarray', 'np.asarray', (['known_face_names'], {}), '(known_face_names)\n', (963, 981), True, 'import numpy as np\n')] |
#!/usr/bin/python
#####
# applies model predictions to tiled CR predictor data
#####
import gdal
import scipy
import numpy as np
from sklearn import tree
from sklearn import ensemble
from sklearn import linear_model
from sklearn import svm
from sklearn import metrics
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
from scipy.stats import gaussian_kde
import pickle
# set base directory
base = '/home/cba/Downloads/tree-cover'
# list the tiles to compute over
tiles = [base + '/tiles/pred_001_despeckled.tif', base + '/tiles/pred_002_despeckled.tif', base + '/tiles/pred_003_despeckled.tif',
base + '/tiles/pred_004_despeckled.tif', base + '/tiles/pred_005_despeckled.tif', base + '/tiles/pred_006_despeckled.tif',
base + '/tiles/pred_008_despeckled.tif', base + '/tiles/pred_009_despeckled.tif']
# list the models to apply
#model_files = ["coto_brus_tree_cover_model_AdaBoost.sav",
# "coto_brus_tree_cover_model_Bagging.sav",
# "coto_brus_tree_cover_model_ExtraTrees.sav",
# "coto_brus_tree_cover_model_GradientBoosting.sav",
# "coto_brus_tree_cover_model_LinearModel.sav",
# "coto_brus_tree_cover_model_RandomForest.sav"]
model_files = ["coto_brus_tree_cover_model_GradientBoosting.sav"]
# "coto_brus_tree_cover_model_RandomForest.sav"]
# load the file for scaling the input data
scale = True
scaler = pickle.load(open("tree_cover_scaler.sav", 'r'))
# load the models to memory
models = []
for file in model_files:
models.append(pickle.load(open(file, 'r')))
# loop through each tile, apply the model, and save the output
for i in range(len(tiles)):
# report
print("-----")
print("Predicting file: {}".format(tiles[i]))
# read input reference
tref = gdal.Open(tiles[i])
tgeo = tref.GetGeoTransform()
tprj = tref.GetProjection()
nx = tref.RasterXSize
ny = tref.RasterYSize
# get nodata value and indices
bref = tref.GetRasterBand(1)
ndval = bref.GetNoDataValue()
band = bref.ReadAsArray()
gd = np.where(band != ndval)
band = None
bref = None
# read the predictor data into memory
print("Reading data into memory")
pred_arr = tref.ReadAsArray()
pred = pred_arr[:, gd[0], gd[1]].transpose()
pred_arr = None
# scale the data
if scale:
pred = scaler.transform(pred)
# predict each model
print("Predicting each model")
opred = np.zeros(len(gd[0]))
for model in models:
y_pred = model.predict(pred)
opred += y_pred
# take the average
opred /= float(len(models))
# create the square array to write as output
print("Creating output array")
outarr = np.zeros((ny, nx)) + 2.55
outarr[gd[0], gd[1]] = opred
# write to an output file
outfile = base + "/tiles/predicted_{:03d}.tif".format(i+1)
oref = gdal.GetDriverByName("GTiff").Create(outfile, nx, ny, 1, gdal.GDT_Float32)
oref.SetGeoTransform(tgeo)
oref.SetProjection(tprj)
oband = oref.GetRasterBand(1)
oband.WriteArray(outarr)
oband = None
outarr = None
oref = None | [
"numpy.where",
"numpy.zeros",
"gdal.Open",
"gdal.GetDriverByName"
] | [((1820, 1839), 'gdal.Open', 'gdal.Open', (['tiles[i]'], {}), '(tiles[i])\n', (1829, 1839), False, 'import gdal\n'), ((2104, 2127), 'numpy.where', 'np.where', (['(band != ndval)'], {}), '(band != ndval)\n', (2112, 2127), True, 'import numpy as np\n'), ((2776, 2794), 'numpy.zeros', 'np.zeros', (['(ny, nx)'], {}), '((ny, nx))\n', (2784, 2794), True, 'import numpy as np\n'), ((2944, 2973), 'gdal.GetDriverByName', 'gdal.GetDriverByName', (['"""GTiff"""'], {}), "('GTiff')\n", (2964, 2973), False, 'import gdal\n')] |
import torch.utils.data as data
import torch
import h5py
import numpy as np
def data_augment(im,num):
org_image = im.transpose(1,2,0)
if num ==0:
ud_image = np.flipud(org_image)
tranform = ud_image
elif num ==1:
lr_image = np.fliplr(org_image)
tranform = lr_image
elif num ==2:
lr_image = np.fliplr(org_image)
lrud_image = np.flipud(lr_image)
tranform = lrud_image
elif num ==3:
rotated_image1 = np.rot90(org_image)
tranform = rotated_image1
elif num ==4:
rotated_image2 = np.rot90(org_image, -1)
tranform = rotated_image2
elif num ==5:
rotated_image1 = np.rot90(org_image)
ud_image1 = np.flipud(rotated_image1)
tranform = ud_image1
elif num ==6:
rotated_image2 = np.rot90(org_image, -1)
ud_image2 = np.flipud(rotated_image2)
tranform = ud_image2
else:
tranform = org_image
tranform = tranform.transpose(2,0,1)
return tranform
class DatasetFromHdf5(data.Dataset):
def __init__(self, file_path):
super(DatasetFromHdf5, self).__init__()
hf = h5py.File(file_path)
self.data = hf.get('data')
print(self.data.shape)
self.target = hf.get('label_x4')
def __getitem__(self, index):
num = np.random.randint(0, 8)
im_data = self.data[index,:,:,:]
rim_data = data_augment(im_data,num)
data = torch.from_numpy(rim_data.copy()).float()
im_labelx4 = self.target[index,:,:,:]
rim_labelx4 = data_augment(im_labelx4,num)
label_x4 = torch.from_numpy(rim_labelx4.copy()).float()
# return torch.from_numpy(self.data[index,:,:,:]).float(), torch.from_numpy(self.target[index,:,:,:]).float()
return data, label_x4
def __len__(self):
return self.data.shape[0] | [
"numpy.flipud",
"numpy.fliplr",
"h5py.File",
"numpy.random.randint",
"numpy.rot90"
] | [((182, 202), 'numpy.flipud', 'np.flipud', (['org_image'], {}), '(org_image)\n', (191, 202), True, 'import numpy as np\n'), ((1191, 1211), 'h5py.File', 'h5py.File', (['file_path'], {}), '(file_path)\n', (1200, 1211), False, 'import h5py\n'), ((1374, 1397), 'numpy.random.randint', 'np.random.randint', (['(0)', '(8)'], {}), '(0, 8)\n', (1391, 1397), True, 'import numpy as np\n'), ((271, 291), 'numpy.fliplr', 'np.fliplr', (['org_image'], {}), '(org_image)\n', (280, 291), True, 'import numpy as np\n'), ((360, 380), 'numpy.fliplr', 'np.fliplr', (['org_image'], {}), '(org_image)\n', (369, 380), True, 'import numpy as np\n'), ((403, 422), 'numpy.flipud', 'np.flipud', (['lr_image'], {}), '(lr_image)\n', (412, 422), True, 'import numpy as np\n'), ((499, 518), 'numpy.rot90', 'np.rot90', (['org_image'], {}), '(org_image)\n', (507, 518), True, 'import numpy as np\n'), ((599, 622), 'numpy.rot90', 'np.rot90', (['org_image', '(-1)'], {}), '(org_image, -1)\n', (607, 622), True, 'import numpy as np\n'), ((703, 722), 'numpy.rot90', 'np.rot90', (['org_image'], {}), '(org_image)\n', (711, 722), True, 'import numpy as np\n'), ((744, 769), 'numpy.flipud', 'np.flipud', (['rotated_image1'], {}), '(rotated_image1)\n', (753, 769), True, 'import numpy as np\n'), ((845, 868), 'numpy.rot90', 'np.rot90', (['org_image', '(-1)'], {}), '(org_image, -1)\n', (853, 868), True, 'import numpy as np\n'), ((890, 915), 'numpy.flipud', 'np.flipud', (['rotated_image2'], {}), '(rotated_image2)\n', (899, 915), True, 'import numpy as np\n')] |
import numpy as np
from .. import inf
from ... import blm
from . import learning
from .prior import prior
class model:
def __init__(self, lik, mean, cov, inf='exact'):
self.lik = lik
self.prior = prior(mean=mean, cov=cov)
self.inf = inf
self.num_params = self.lik.num_params + self.prior.num_params
self.params = self.cat_params(self.lik.params, self.prior.params)
self.stats = ()
def cat_params(self, lik_params, prior_params):
''' concatinate the likelihood and prior parameters '''
params = np.append(lik_params, prior_params)
return params
def decomp_params(self, params=None):
if params is None:
params = np.copy(self.params)
lik_params = params[0:self.lik.num_params]
prior_params = params[self.lik.num_params:]
return lik_params, prior_params
def set_params(self, params):
self.params = params
lik_params, prior_params = self.decomp_params(params)
self.lik.set_params(lik_params)
self.prior.set_params(prior_params)
def sub_sampling(self, X, t, N):
num_data = X.shape[0]
if N is None or N < num_data:
index = np.random.permutation(num_data)
subX = X[index[0:N], :]
subt = t[index[0:N]]
else:
subX = X
subt = t
return subX, subt
def export_blm(self, num_basis):
if not hasattr(self.prior.cov, "rand_expans"):
raise ValueError('The kernel must be.')
basis_params = self.prior.cov.rand_expans(num_basis)
basis = blm.basis.fourier(basis_params)
prior = blm.prior.gauss(num_basis)
lik = blm.lik.gauss(blm.lik.linear(basis, bias=self.prior.get_mean(1)),
blm.lik.cov(self.lik.params))
blr = blm.model(lik, prior)
return blr
def eval_marlik(self, params, X, t, N=None):
subX, subt = self.sub_sampling(X, t, N)
if self.inf is 'exact':
marlik = inf.exact.eval_marlik(self, subX, subt, params=params)
else:
pass
return marlik
def get_grad_marlik(self, params, X, t, N=None):
subX, subt = self.sub_sampling(X, t, N)
if self.inf is 'exact':
grad_marlik = inf.exact.get_grad_marlik(self, subX, subt,
params=params)
return grad_marlik
def get_params_bound(self):
if self.lik.num_params != 0:
bound = self.lik.get_params_bound()
if self.prior.mean.num_params != 0:
bound.extend(self.prior.mean.get_params_bound())
if self.prior.cov.num_params != 0:
bound.extend(self.prior.cov.get_params_bound())
return bound
def prepare(self, X, t, params=None):
if params is None:
params = np.copy(self.params)
if self.inf is 'exact':
self.stats = inf.exact.prepare(self, X, t, params)
else:
pass
def get_post_fmean(self, X, Z, params=None):
if params is None:
params = np.copy(self.params)
if self.inf is 'exact':
post_fmu = inf.exact.get_post_fmean(self, X, Z, params)
return post_fmu
def get_post_fcov(self, X, Z, params=None, diag=True):
if params is None:
params = np.copy(self.params)
if self.inf is 'exact':
post_fcov = inf.exact.get_post_fcov(self, X, Z, params, diag)
return post_fcov
def post_sampling(self, X, Z, params=None, N=1, alpha=1):
if params is None:
params = np.copy(self.params)
fmean = self.get_post_fmean(X, Z, params=None)
fcov = self.get_post_fcov(X, Z, params=None, diag=False)
return np.random.multivariate_normal(fmean, fcov * alpha**2, N)
def predict_sampling(self, X, Z, params=None, N=1):
if params is None:
params = np.copy(self.params)
ndata = Z.shape[0]
fmean = self.get_post_fmean(X, Z, params=None)
fcov = self.get_post_fcov(X, Z, params=None, diag=False) \
+ self.lik.get_cov(ndata)
return np.random.multivariate_normal(fmean, fcov, N)
def print_params(self):
print('\n')
if self.lik.num_params != 0:
print('likelihood parameter = ', self.lik.params)
if self.prior.mean.num_params != 0:
print('mean parameter in GP prior: ', self.prior.mean.params)
print('covariance parameter in GP prior: ', self.prior.cov.params)
print('\n')
def get_cand_params(self, X, t):
''' candidate for parameters '''
params = np.zeros(self.num_params)
if self.lik.num_params != 0:
params[0:self.lik.num_params] = self.lik.get_cand_params(t)
temp = self.lik.num_params
if self.prior.mean.num_params != 0:
params[temp:temp + self.prior.mean.num_params] \
= self.prior.mean.get_cand_params(t)
temp += self.prior.mean.num_params
if self.prior.cov.num_params != 0:
params[temp:] = self.prior.cov.get_cand_params(X, t)
return params
def fit(self, X, t, config):
method = config.learning.method
if method == 'adam':
adam = learning.adam(self, config)
params = adam.run(X, t)
if method in ('bfgs', 'batch'):
bfgs = learning.batch(self, config)
params = bfgs.run(X, t)
self.set_params(params)
| [
"numpy.copy",
"numpy.random.multivariate_normal",
"numpy.append",
"numpy.zeros",
"numpy.random.permutation"
] | [((569, 604), 'numpy.append', 'np.append', (['lik_params', 'prior_params'], {}), '(lik_params, prior_params)\n', (578, 604), True, 'import numpy as np\n'), ((3818, 3876), 'numpy.random.multivariate_normal', 'np.random.multivariate_normal', (['fmean', '(fcov * alpha ** 2)', 'N'], {}), '(fmean, fcov * alpha ** 2, N)\n', (3847, 3876), True, 'import numpy as np\n'), ((4205, 4250), 'numpy.random.multivariate_normal', 'np.random.multivariate_normal', (['fmean', 'fcov', 'N'], {}), '(fmean, fcov, N)\n', (4234, 4250), True, 'import numpy as np\n'), ((4711, 4736), 'numpy.zeros', 'np.zeros', (['self.num_params'], {}), '(self.num_params)\n', (4719, 4736), True, 'import numpy as np\n'), ((718, 738), 'numpy.copy', 'np.copy', (['self.params'], {}), '(self.params)\n', (725, 738), True, 'import numpy as np\n'), ((1219, 1250), 'numpy.random.permutation', 'np.random.permutation', (['num_data'], {}), '(num_data)\n', (1240, 1250), True, 'import numpy as np\n'), ((2895, 2915), 'numpy.copy', 'np.copy', (['self.params'], {}), '(self.params)\n', (2902, 2915), True, 'import numpy as np\n'), ((3141, 3161), 'numpy.copy', 'np.copy', (['self.params'], {}), '(self.params)\n', (3148, 3161), True, 'import numpy as np\n'), ((3396, 3416), 'numpy.copy', 'np.copy', (['self.params'], {}), '(self.params)\n', (3403, 3416), True, 'import numpy as np\n'), ((3661, 3681), 'numpy.copy', 'np.copy', (['self.params'], {}), '(self.params)\n', (3668, 3681), True, 'import numpy as np\n'), ((3980, 4000), 'numpy.copy', 'np.copy', (['self.params'], {}), '(self.params)\n', (3987, 4000), True, 'import numpy as np\n')] |
import numpy as np
import labels as L
import sys
import tensorflow.contrib.keras as keras
import tensorflow as tf
from keras import backend as K
K.set_learning_phase(0)
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.utils import to_categorical
from keras.engine import Layer, InputSpec, InputLayer
from keras.models import Model, Sequential, load_model
from keras.layers import Dropout, Embedding, concatenate
from keras.layers import Conv1D, MaxPooling1D, GlobalAveragePooling1D, Conv2D, MaxPool2D, ZeroPadding1D
from keras.layers import Dense, Input, Flatten, BatchNormalization
from keras.layers import Concatenate, Dot, Merge, Multiply, RepeatVector
from keras.layers import Bidirectional, TimeDistributed
from keras.layers import SimpleRNN, LSTM, GRU, Lambda, Permute
from keras.layers.core import Reshape, Activation
from keras.optimizers import Adam
from keras.callbacks import ModelCheckpoint,EarlyStopping,TensorBoard
from keras.constraints import maxnorm
from keras.regularizers import l2
from keras.metrics import top_k_categorical_accuracy
import keras.metrics
def top_3_accuracy(y_true, y_pred):
return top_k_categorical_accuracy(y_true, y_pred, k=3)
keras.metrics.top_3_accuracy = top_3_accuracy
import pickle
EMBEDDING_DIM = 300
MAX_SEQUENCE_LENGTH = 100
MAX_NUMBER_WORDS = 136085
traces = []
with open('/app/dataset.txt', 'r') as tracesf:
traces = list(tracesf.readlines())
names = [ t.split('|')[0].strip() for t in traces ]
traces = [
(t.split('|')[1].strip(), t.split('|')[2].strip(), t.split('|')[3])
for t in traces
]
labels = [ L.LABELS[t[0]][0] for t in traces ]
texts = [ t[1] for t in traces ]
wrongs = [ t[2].strip() for t in traces ]
for t in traces:
assert len(t) <= MAX_SEQUENCE_LENGTH
tokenizer = None
with open('/app/assets/tokenizer.pkl', 'rb') as wordf:
tokenizer = pickle.load(wordf)
sequences = tokenizer.texts_to_sequences(texts)
word_index = tokenizer.word_index
print('Found %s unique tokens.' % len(word_index))
data = pad_sequences(sequences, maxlen=MAX_SEQUENCE_LENGTH)
labels = to_categorical(np.asarray(labels), num_classes=L.NUM_LABELS)
print('Shape of data tensor:', data.shape)
print('Shape of label tensor:', labels.shape)
model = load_model('/app/{}'.format(sys.argv[1]))
answers = model.predict(data, batch_size=32)
get = lambda i: [ l[0] for l in L.LABELS.items() if l[1][0] == i ][0]
top1 = 0
top3 = 0
top5 = 0
mistakes3 = 0
mistakes5 = 0
total = 0
for j,answer in enumerate(answers):
goal = get(np.argmax(labels[j]))
print('GOAL == {}:'.format(goal))
idx = 0
total += 1
for r in sorted([ (get(i), answer[i]) for i in range(0, len(answer)) ], key=lambda x: -x[1])[:5]:
idx += 1
print(' {} ({:.2%})'.format(*r))
if r[0] == goal and idx <= 1:
top1 += 1
if r[0] == goal and idx <= 3:
top3 += 1
if r[0] == goal and idx <= 5:
top5 += 1
if r[0] == wrongs[j] and idx <= 3:
mistakes3 += 1
if r[0] == wrongs[j] and idx <= 5:
mistakes5 += 1
print('Accuracy @3: {:.2%} ({}/{})'.format(float(top3)/float(total), top3, total))
print('Accuracy @5: {:.2%} ({}/{})'.format(float(top5)/float(total), top5, total))
print('----')
print('Mistakes @3: {:.2%} ({}/{})'.format(float(mistakes3)/float(total), mistakes3, total))
print('Mistakes @5: {:.2%} ({}/{})'.format(float(mistakes5)/float(total), mistakes5, total)) | [
"labels.LABELS.items",
"pickle.load",
"numpy.asarray",
"numpy.argmax",
"keras.metrics.top_k_categorical_accuracy",
"keras.preprocessing.sequence.pad_sequences",
"keras.backend.set_learning_phase"
] | [((149, 172), 'keras.backend.set_learning_phase', 'K.set_learning_phase', (['(0)'], {}), '(0)\n', (169, 172), True, 'from keras import backend as K\n'), ((2058, 2110), 'keras.preprocessing.sequence.pad_sequences', 'pad_sequences', (['sequences'], {'maxlen': 'MAX_SEQUENCE_LENGTH'}), '(sequences, maxlen=MAX_SEQUENCE_LENGTH)\n', (2071, 2110), False, 'from keras.preprocessing.sequence import pad_sequences\n'), ((1195, 1242), 'keras.metrics.top_k_categorical_accuracy', 'top_k_categorical_accuracy', (['y_true', 'y_pred'], {'k': '(3)'}), '(y_true, y_pred, k=3)\n', (1221, 1242), False, 'from keras.metrics import top_k_categorical_accuracy\n'), ((1897, 1915), 'pickle.load', 'pickle.load', (['wordf'], {}), '(wordf)\n', (1908, 1915), False, 'import pickle\n'), ((2136, 2154), 'numpy.asarray', 'np.asarray', (['labels'], {}), '(labels)\n', (2146, 2154), True, 'import numpy as np\n'), ((2554, 2574), 'numpy.argmax', 'np.argmax', (['labels[j]'], {}), '(labels[j])\n', (2563, 2574), True, 'import numpy as np\n'), ((2401, 2417), 'labels.LABELS.items', 'L.LABELS.items', ([], {}), '()\n', (2415, 2417), True, 'import labels as L\n')] |
# -*- coding: utf-8 -*-
"""
This is the module for normalizing the frequency of membrane potential.
You normalize the frequency of burst firings (1st~6th burst firing) and
plot normalized membrane potential, Ca, and so on.
"""
__author__ = '<NAME>'
__status__ = 'Prepared'
__version__ = '1.0.0'
__date__ = '24 Aug 2020'
import os
import sys
"""
LIMIT THE NUMBER OF THREADS!
change local env variables BEFORE importing numpy
"""
os.environ['OMP_NUM_THREADS'] = '1'
os.environ['NUMEXPR_NUM_THREADS'] = '1'
os.environ['MKL_NUM_THREADS'] = '1'
sys.path.append('../')
sys.path.append('../anmodel')
from copy import copy
import matplotlib.pyplot as plt
from multiprocessing import Pool
import numpy as np
import pandas as pd
from pathlib import Path
import pickle
import scipy.stats
import seaborn as sns
from tqdm import tqdm
from typing import Dict, List, Iterator, Optional
import anmodel
import analysistools
class Normalization:
def __init__(self, model: str='AN', wavepattern: str=None,
channel_bool: Optional[Dict]=None,
model_name: Optional[str]=None,
ion: bool=False, concentration: Dict=None)-> None:
""" Normalize the frequency of membrane potential.
Parameters
----------
model : str
the type of model a simulation is conducted (ex. AN, SAN, X)
wavepattern : str
the collected wavepattrn (ex. SWS, SPN)
channel_bool[Optional] : Dict
when X model is selected, you need to choose channels by this
model_name[Optional] : str
when X model is selected, you need to designate the model name (ex. RAN)
ion[Optional] : bool
whther you take extracellular ion concentration into account
concentration[Optional] : Dict
when ion=True, you need to designate initial ion concentrations
"""
self.model = model
self.wavepattern = wavepattern
if self.model == 'AN':
self.model_name = 'AN'
self.model = anmodel.models.ANmodel(ion, concentration)
elif self.model == 'SAN':
self.model_name = 'SAN'
self.model = anmodel.models.SANmodel(ion, concentration)
elif self.model == 'RAN':
self.model_name = 'RAN'
ran_bool = [1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1]
self.model = anmodel.models.Xmodel(channel_bool=ran_bool, ion=ion, concentration=concentration)
elif self.model == "X":
if channel_bool is None:
raise TypeError('Designate channel in argument of X model.')
self.model_name = model_name
self.model = anmodel.models.Xmodel(channel_bool, ion, concentration)
def norm_yoshida(self, param: pd.Series, samp_len: int=10) -> List[int]:
""" Normalize frequency of burst firing in SWS firing pattern.
Parameters
----------
param : pd.Series or Dict
single parameter set
samp_len : int
sampling time length (sec) (usually 10)
Returns
----------
List[int]
the index (time (ms)) of the 1st~6th ends of burst firing
Notes
----------
this algorithm is same as Yoshida et al., 2018
"""
self.model.set_params(param)
s, _ = self.model.run_odeint(samp_freq=1000, samp_len=samp_len)
v: np.ndarray = s[5000:, 0]
del(s)
vmax: np.float64 = v.max()
vmin: np.float64 = v.min()
vrange: np.float64 = vmax - vmin
ss: List[List] = []
for i in range(int(vrange)):
si: List[int] = []
for j in range(len(v)-1):
if (v[j]-(vmax-i))*(v[j+1]-(vmax-i))<0:
si.append(j)
ss.append(si)
d: List[int] = []
for i, si in enumerate(ss):
dd = []
for j in range(len(si)-1):
dd.append(si[j+1]-si[j])
if len(dd) == 0:
d.append(None)
else:
d.append(max(dd))
k: List[int] = []
maxlen = 0
for i, si in enumerate(ss):
if len(si) > maxlen:
k = [i]
maxlen = len(si)
elif len(si) == maxlen:
k.append(i)
else:
pass
dia: List[int] = []
for i in k:
dia.append(d[i])
h: List[int] = []
for k in k:
if d[k] is None:
pass
if d[k] == min(dia):
h.append(k)
dh = d[h[0]]
sh = ss[h[0]]
e = []
for j in range(len(sh)-1):
if sh[j+1]-sh[j] >= 0.5 * dh:
e.append(j)
if len(e) >= 7:
return [sh[i] for i in range(7)]
else:
if samp_len <=20:
self.norm_sws(param=param, channel=channel, samp_len=samp_len+10)
else:
return [None] * 7
def norm_sws(self, param: pd.Series, channel=None, channel2=None,
samp_len: int=10) -> List[int]:
""" Normalize frequency of burst firing in SWS firing pattern.
Parameters
----------
param : pd.Series or Dict
single parameter set
gl : float [Optional]
leak channel (na/k) conductance for bifurcation analysis
gl_name : str [Optional]
na / k
samp_len : int [Optional]
sampling time length (sec) (usually 10)
Returns
----------
List[int]
the index (time (ms)) of the 1st~6th ends of burst firing
"""
if channel is not None:
self.model.set_params(param.drop(['g_kl', 'g_nal']))
if channel != 'g_nal' and channel != 'g_kl' and channel2 != 'g_nal' and channel2 != 'g_kl':
self.model.leak.reset_div()
else:
self.model.leak.set_gk(param['g_kl'])
self.model.leak.set_gna(param['g_nal'])
else:
self.model.set_params(param)
s, _ = self.model.run_odeint(samp_freq=1000, samp_len=samp_len)
v: np.ndarray = s[5000:, 0]
del(s)
als = anmodel.analysis.FreqSpike()
_, burstidx, _, _ = als.get_burstinfo(v, spike='peak')
e = []
for lst in burstidx:
e.append(lst[-1])
if len(e) >= 7:
return e[:7]
else:
if samp_len <= 20:
self.norm_sws(param=param, channel=channel, samp_len=samp_len+10)
else:
return [None] * 7
def norm_spn(self, param: pd.Series, channel=None, channel2=None,
samp_len: int=10) -> List[int]:
""" Normalize frequency of burst firing in SPN firing pattern.
Parameters
----------
param : pd.Series or Dict
single parameter set
gl : float [Optional]
leak channel (na/k) conductance for bifurcation analysis
gl_name : str [Optional]
na / k
samp_len : int [Optional]
sampling time length (sec) (usually 10)
Returns
----------
List[int]
the index (time (ms)) of the 1st~6th ends of burst firing
"""
if 'g_nal' in param.index or 'g_kl' in param.index:
self.model.set_params(param.drop(['g_kl', 'g_nal']))
if channel != 'g_nal' and channel != 'g_kl' and channel2 != 'g_nal' and channel2 != 'g_kl':
self.model.leak.reset_div()
self.model.set_params(param)
else:
self.model.leak.set_div()
self.model.leak.set_gk(param['g_kl'])
self.model.leak.set_gna(param['g_nal'])
s, _ = self.model.run_odeint(samp_freq=1000, samp_len=samp_len)
v: np.ndarray = s[5000:, 0]
del(s)
als = anmodel.analysis.FreqSpike()
_, burstidx, _, _ = als.get_burstinfo(v, spike='bottom')
e = []
for lst in burstidx:
e.append(lst[-1])
if len(e) >= 7:
return e[:7]
else:
if samp_len <= 20:
self.norm_spn(param=param, channel=channel, channel2=channel2, samp_len=samp_len+10)
else:
return [None] * 7
def time(self, filename: str) -> None:
""" Calculate time points for 1st~6th burst firing for all parameter sets.
Parameters
----------
filename : str
the name of file in which parameter sets are contained
"""
p: Path = Path.cwd().parents[0]
data_p: Path = p / 'results' / f'{self.wavepattern}_params' / self.model_name
# res_p: Path = p / 'results' / 'normalization_mp_ca' / f'{self.wavepattern}_{self.model_name}_time.pickle'
res_p: Path = p / 'results' / 'normalization_mp_ca' / f'{filename}_time.pickle'
with open(data_p/filename, 'rb') as f:
df = pickle.load(f)
df.index = range(len(df))
res_df = pd.DataFrame([], columns=range(7), index=range(len(df)))
for i in tqdm(range(len(df))):
param = df.iloc[i, :]
if self.wavepattern == 'SWS':
res_df.iloc[i, :] = self.norm_sws(param)
elif self.wavepattern == 'SPN':
res_df.iloc[i, :] = self.norm_spn(param)
else:
raise NameError(f'Wavepattern {self.wavepattern} is unvalid.')
if i%10 == 0:
with open(res_p, 'wb') as f:
pickle.dump(res_df, f)
print(f'Now i={i}, and pickled')
with open(res_p, 'wb') as f:
pickle.dump(res_df, f)
def mp_ca(self, filename: str) -> None:
""" Calculate normalized mp and ca for plotting heatmap.
Parameters
----------
filename : str
the name of file in which parameter sets are contained
"""
p: Path = Path.cwd().parents[0]
data_p: Path = p / 'results' / f'{self.wavepattern}_params' / self.model_name
res_p: Path = p / 'results' / 'normalization_mp_ca'
with open(data_p/filename, 'rb') as f:
param_df = pickle.load(f)
param_df.index = range(len(param_df))
with open(res_p/f'{self.wavepattern}_{self.model_name}_time.pickle', 'rb') as f:
time_df = pickle.load(f).dropna(how='all')
time_df.index = range(len(time_df))
hm_df = pd.DataFrame([], columns=range(48), index=range(len(time_df)))
hm_ca_df = pd.DataFrame([], columns=range(48), index=range(len(time_df)))
for i in tqdm(range(len(time_df))):
param = param_df.iloc[i, :]
e = time_df.iloc[i, :]
if e[0] == None:
pass
else:
samp_len = 10 + ((5000+e[6])//10000) * 10
self.model.set_params(param)
s, _ = self.model.run_odeint(samp_freq=1000, samp_len=samp_len)
v: np.ndarray = scipy.stats.zscore(s[5000:, 0])
ca: np.ndarray = scipy.stats.zscore(s[5000:, -1])
v_norm = []
ca_norm = []
for j in range(len(e)-1):
tlst = np.linspace(e[j], e[j+1], 9, dtype=int)
for k in range(len(tlst)-1):
v_norm.append(v[tlst[k]:tlst[k+1]].var(ddof=0))
# v_norm.append(v[tlst[k]:tlst[k+1]].std(ddof=0))
ca_norm.append(ca[tlst[k]:tlst[k+1]].mean())
hm_df.iloc[i, :] = v_norm
hm_ca_df.iloc[i, :] = ca_norm
with open(res_p/f'{filename}_mp.pickle', 'wb') as f:
pickle.dump(hm_df, f)
with open(res_p/f'{filename}_ca.pickle', 'wb') as f:
pickle.dump(hm_ca_df, f)
plt.figure(figsize=(20, 20))
sns.heatmap(hm_df.values.tolist(), cmap='jet')
plt.savefig(res_p/f'{self.wavepattern}_{self.model_name}_mp_hm.png')
plt.figure(figsize=(20, 20))
sns.heatmap(hm_ca_df.values.tolist(), cmap='jet')
plt.savefig(res_p/f'{self.wavepattern}_{self.model_name}_ca_hm.png')
def time_bifurcation_rep(self, filename: str, channel: str, diff: int=100) -> None:
""" Calculate time points for 1st~6th burst firing for
the representative parameter set through bifurcation.
Parameters
----------
filename : str
the name of file in which parameter sets are contained
"""
p: Path = Path.cwd().parents[0]
data_p: Path = p / 'results' / f'{self.wavepattern}_params' / self.model_name
resname: str = f'{filename}_{channel}_{diff}_time.pickle'
res_p: Path = p / 'results' / 'normalization_mp_ca' / 'bifurcation_rep' / f'{self.model_name}'
res_p.mkdir(parents=True, exist_ok=True)
with open(data_p/filename, 'rb') as f:
param = pickle.load(f)
self.model.set_params(param)
if channel == 'g_nal' or channel == 'g_kl':
self.model.leak.set_div()
param.loc['g_nal'] = self.model.leak.gnal
param.loc['g_kl'] = self.model.leak.gkl
start = 1000 - diff
end = 1000 + diff + 1
res_df = pd.DataFrame([], columns=range(7), index=np.arange(start, end))
for i in tqdm(res_df.index):
param_c = copy(param)
param_c[channel] = param_c[channel] * i / 1000
if self.wavepattern == 'SWS':
res_df.loc[i, :] = self.norm_sws(param_c, channel)
elif self.wavepattern == 'SPN':
res_df.loc[i, :] = self.norm_spn(param_c, channel)
else:
raise NameError(f'Wavepattern {self.wavepattern} is unvalid.')
if i%10 == 0:
with open(res_p/resname, 'wb') as f:
pickle.dump(res_df, f)
print(f'Now i={i}, and pickled')
with open(res_p/resname, 'wb') as f:
pickle.dump(res_df, f)
def two_bifur_singleprocess(self, args) -> None:
core, param_lst, r_df, channel1, channel2, res_p, resname = args
for p_lst in param_lst:
m, param_c = p_lst
r_name = f'{resname}_{m}.pickle'
for i in tqdm(r_df.columns):
param_cc = copy(param_c)
# param_cc[f'g_{channel2}'] = param_cc[f'g_{channel2}'] * i/1000
param_cc[channel2] = param_cc[channel2] * i/1000
if self.wavepattern == 'SWS':
# try:
# r_df.loc[m, i] = 1000 / np.diff(self.norm_sws(param_cc, channel2, channel1)).mean()
# except:
# r_df.loc[m, i] = None
pass
elif self.wavepattern == 'SPN':
try:
r_df.loc[m, i] = 1000 / np.diff(self.norm_spn(param=param_cc, channel=channel1, channel2=channel2)).mean()
except:
r_df.loc[m, i] = None
else:
raise NameError(f'Wavepattern {self.wavepattern} is unvalid.')
with open(res_p/r_name, 'wb') as f:
pickle.dump(r_df, f)
def two_bifur_multi_singleprocess(self, ncore, filename, channel1, channel2, diff, interval):
p: Path = Path.cwd().parents[0]
data_p: Path = p / 'results' / f'{self.wavepattern}_params' / self.model_name
res_p: Path = p / 'results' / 'normalization_mp_ca' / 'two_bifurcation' / f'{self.model_name}' / f'{channel1}_{channel2}'
channel1 = 'g_' + channel1
channel2 = 'g_' + channel2
res_p.mkdir(parents=True, exist_ok=True)
with open(data_p/filename, 'rb') as f:
param = pickle.load(f)
self.model.set_params(param)
self.model.leak.set_div()
param.loc['g_nal'] = self.model.leak.gnal
param.loc['g_kl'] = self.model.leak.gkl
start = 1000 - diff
end = 1000 + diff + 1
# index: channel_1, columns: channel_2
magnif_lst = np.arange(start, end, interval)
res_df = pd.DataFrame(index=magnif_lst, columns=magnif_lst)
resname = f'{filename}_{diff}'
args: List = []
for core, m_lst in enumerate(np.array_split(magnif_lst, ncore)):
param_lst = []
for m in m_lst:
param_c = copy(param)
# param_c[f'g_{channel1}'] = param_c[f'g_{channel1}'] * m/1000
param_c[channel1] = param_c[channel1] * m/1000
param_lst.append([m, param_c])
r_df = res_df.loc[m_lst, :]
args.append((core, param_lst, r_df, channel1, channel2, res_p, resname))
with Pool(processes=ncore) as pool:
pool.map(self.two_bifur_singleprocess, args)
def load_two_bifur(self, filename, ch1, ch2, diff, interval):
p: Path = Path.cwd().parents[0]
res_p: Path = p / 'results' / 'normalization_mp_ca' / 'two_bifurcation' / f'{self.model_name}' / f'{ch1}_{ch2}'
start = 1000 - diff
end = 1000 + diff + 1
magnif_lst = np.arange(start, end, interval)
self.res_df = pd.DataFrame(index=magnif_lst, columns=magnif_lst)
for m in magnif_lst:
resname = f'{filename}_{diff}_{m}.pickle'
with open(res_p/resname, 'rb') as f:
self.res_df.loc[m, :] = pickle.load(f).iloc[0, :]
def time_bifurcation_all(self, filename: str,
channel: str, magnif: float) -> None:
""" Calculate time points for 1st~6th burst firing for
the representative parameter set through bifurcation.
Parameters
----------
filename : str
the name of file in which parameter sets are contained
"""
p: Path = Path.cwd().parents[0]
data_p: Path = p / 'results' / f'{self.wavepattern}_params' / self.model_name
resname: str = f'{filename}_{channel}_{magnif}_time.pickle'
res_p: Path = p / 'results' / 'normalization_mp_ca' / 'bifurcation_all' / f'{self.model_name}'
res_p.mkdir(parents=True, exist_ok=True)
with open(data_p/filename, 'rb') as f:
df = pickle.load(f)
res_df = pd.DataFrame([], columns=range(7), index=range(len(df)))
for i in tqdm(range(len(df))):
param = df.iloc[i, :]
self.model.set_params(param)
self.model.leak.set_div()
param.loc['g_nal'] = self.model.leak.gnal
param.loc['g_kl'] = self.model.leak.gkl
param_c = copy(param)
param_c[channel] = param_c[channel] * magnif
if self.wavepattern == 'SWS':
res_df.loc[i, :] = self.norm_sws(param_c, channel)
elif self.wavepattern == 'SPN':
res_df.loc[i, :] = self.norm_spn(param_c, channel)
else:
raise NameError(f'Wavepattern {self.wavepattern} is unvalid.')
if i%10 == 0:
with open(res_p/resname, 'wb') as f:
pickle.dump(res_df, f)
print(f'Now i={i}, and pickled')
with open(res_p/resname, 'wb') as f:
pickle.dump(res_df, f)
def load_time_bifurcation_all(self, dataname: str, diff: float=0.025):
p: Path = Path.cwd().parents[0]
res_p = p / 'results' / 'normalization_mp_ca' / 'bifurcation_all' / f'{self.model_name}'
magnif_u = 1 + diff
magnif_d = 1 - diff
if self.wavepattern == 'SWS':
with open(res_p/f'{dataname}_g_kvhh_1.0_time.pickle', 'rb') as f:
self.norm_t = pickle.load(f)
self.norm_fr = 1000 / self.norm_t.dropna().diff(axis=1).mean(axis=1)
elif self.wavepattern == 'SPN':
with open(res_p/f'{dataname}_g_kvsi_1.0_time.pickle', 'rb') as f:
self.norm_t = pickle.load(f)
self.norm_fr = 1000 / self.norm_t.dropna().diff(axis=1).mean(axis=1)
with open(res_p/f'{dataname}_g_kleak_{magnif_u}_time.pickle', 'rb') as f:
self.kl_t_u = pickle.load(f)
self.kl_fr_u = 1000 / self.kl_t_u.dropna().diff(axis=1).mean(axis=1) / self.norm_fr
with open(res_p/f'{dataname}_g_kleak_{magnif_d}_time.pickle', 'rb') as f:
self.kl_t_d = pickle.load(f)
self.kl_fr_d = 1000 / self.kl_t_d.dropna().diff(axis=1).mean(axis=1) / self.norm_fr
with open(res_p/f'{dataname}_g_kvsi_{magnif_u}_time.pickle', 'rb') as f:
self.kvsi_t_u = pickle.load(f)
self.kvsi_fr_u = 1000 / self.kvsi_t_u.dropna().diff(axis=1).mean(axis=1) / self.norm_fr
with open(res_p/f'{dataname}_g_kvsi_{magnif_d}_time.pickle', 'rb') as f:
self.kvsi_t_d = pickle.load(f)
self.kvsi_fr_d = 1000 / self.kvsi_t_d.dropna().diff(axis=1).mean(axis=1) / self.norm_fr
with open(res_p/f'{dataname}_g_kca_{magnif_u}_time.pickle', 'rb') as f:
self.kca_t_u = pickle.load(f)
self.kca_fr_u = 1000 / self.kca_t_u.dropna().diff(axis=1).mean(axis=1) / self.norm_fr
with open(res_p/f'{dataname}_g_kca_{magnif_d}_time.pickle', 'rb') as f:
self.kca_t_d = pickle.load(f)
self.kca_fr_d = 1000 / self.kca_t_d.dropna().diff(axis=1).mean(axis=1) / self.norm_fr
with open(res_p/f'{dataname}_g_naleak_{magnif_u}_time.pickle', 'rb') as f:
self.nal_t_u = pickle.load(f)
self.nal_fr_u = 1000 / self.nal_t_u.dropna().diff(axis=1).mean(axis=1) / self.norm_fr
with open(res_p/f'{dataname}_g_naleak_{magnif_d}_time.pickle', 'rb') as f:
self.nal_t_d = pickle.load(f)
self.nal_fr_d = 1000 / self.nal_t_d.dropna().diff(axis=1).mean(axis=1) / self.norm_fr
with open(res_p/f'{dataname}_g_nap_{magnif_u}_time.pickle', 'rb') as f:
self.nap_t_u = pickle.load(f)
self.nap_fr_u = 1000 / self.nap_t_u.dropna().diff(axis=1).mean(axis=1) / self.norm_fr
with open(res_p/f'{dataname}_g_nap_{magnif_d}_time.pickle', 'rb') as f:
self.nap_t_d = pickle.load(f)
self.nap_fr_d = 1000 / self.nap_t_d.dropna().diff(axis=1).mean(axis=1) / self.norm_fr
with open(res_p/f'{dataname}_g_cav_{magnif_u}_time.pickle', 'rb') as f:
self.cav_t_u = pickle.load(f)
self.cav_fr_u = 1000 / self.cav_t_u.dropna().diff(axis=1).mean(axis=1) / self.norm_fr
with open(res_p/f'{dataname}_g_cav_{magnif_d}_time.pickle', 'rb') as f:
self.cav_t_d = pickle.load(f)
self.cav_fr_d = 1000 / self.cav_t_d.dropna().diff(axis=1).mean(axis=1) / self.norm_fr
with open(res_p/f'{dataname}_t_ca_{magnif_u}_time.pickle', 'rb') as f:
self.tca_t_u = pickle.load(f)
self.tca_fr_u = 1000 / self.tca_t_u.dropna().diff(axis=1).mean(axis=1) / self.norm_fr
with open(res_p/f'{dataname}_t_ca_{magnif_d}_time.pickle', 'rb') as f:
self.tca_t_d = pickle.load(f)
self.tca_fr_d = 1000 / self.tca_t_d.dropna().diff(axis=1).mean(axis=1) / self.norm_fr
data_dic = {
'kleak': [self.kl_fr_u, self.kl_fr_d],
'kca': [self.kca_fr_u, self.kca_fr_d],
'naleak': [self.nal_fr_u, self.nal_fr_d],
'cav': [self.cav_fr_u, self.cav_fr_d],
'nap': [self.nap_fr_u, self.nap_fr_d],
'tca': [self.tca_fr_u, self.tca_fr_d],
}
if self.model_name == 'AN':
with open(res_p/f'{dataname}_g_nav_{magnif_u}_time.pickle', 'rb') as f:
self.nav_t_u = pickle.load(f)
self.nav_fr_u = 1000 / self.nav_t_u.dropna().diff(axis=1).mean(axis=1) / self.norm_fr
with open(res_p/f'{dataname}_g_nav_{magnif_d}_time.pickle', 'rb') as f:
self.nav_t_d = pickle.load(f)
self.nav_fr_d = 1000 / self.nav_t_d.dropna().diff(axis=1).mean(axis=1) / self.norm_fr
with open(res_p/f'{dataname}_g_kvhh_{magnif_u}_time.pickle', 'rb') as f:
self.kvhh_t_u = pickle.load(f)
self.kvhh_fr_u = 1000 / self.kvhh_t_u.dropna().diff(axis=1).mean(axis=1) / self.norm_fr
with open(res_p/f'{dataname}_g_kvhh_{magnif_d}_time.pickle', 'rb') as f:
self.kvhh_t_d = pickle.load(f)
self.kvhh_fr_d = 1000 / self.kvhh_t_d.dropna().diff(axis=1).mean(axis=1) / self.norm_fr
with open(res_p/f'{dataname}_g_kvsi_{magnif_u}_time.pickle', 'rb') as f:
self.kvsi_t_u = pickle.load(f)
self.kvsi_fr_u = 1000 / self.kvsi_t_u.dropna().diff(axis=1).mean(axis=1) / self.norm_fr
with open(res_p/f'{dataname}_g_kvsi_{magnif_d}_time.pickle', 'rb') as f:
self.kvsi_t_d = pickle.load(f)
self.kvsi_fr_d = 1000 / self.kvsi_t_d.dropna().diff(axis=1).mean(axis=1) / self.norm_fr
with open(res_p/f'{dataname}_g_kva_{magnif_u}_time.pickle', 'rb') as f:
self.kva_t_u = pickle.load(f)
self.kva_fr_u = 1000 / self.kva_t_u.dropna().diff(axis=1).mean(axis=1) / self.norm_fr
with open(res_p/f'{dataname}_g_kva_{magnif_d}_time.pickle', 'rb') as f:
self.kva_t_d = pickle.load(f)
self.kva_fr_d = 1000 / self.kva_t_d.dropna().diff(axis=1).mean(axis=1) / self.norm_fr
with open(res_p/f'{dataname}_g_kir_{magnif_u}_time.pickle', 'rb') as f:
self.kir_t_u = pickle.load(f)
self.kir_fr_u = 1000 / self.kir_t_u.dropna().diff(axis=1).mean(axis=1) / self.norm_fr
with open(res_p/f'{dataname}_g_kir_{magnif_d}_time.pickle', 'rb') as f:
self.kir_t_d = pickle.load(f)
self.kir_fr_d = 1000 / self.kir_t_d.dropna().diff(axis=1).mean(axis=1) / self.norm_fr
with open(res_p/f'{dataname}_g_ampar_{magnif_u}_time.pickle', 'rb') as f:
self.ampar_t_u = pickle.load(f)
self.ampar_fr_u = 1000 / self.ampar_t_u.dropna().diff(axis=1).mean(axis=1) / self.norm_fr
with open(res_p/f'{dataname}_g_ampar_{magnif_d}_time.pickle', 'rb') as f:
self.ampar_t_d = pickle.load(f)
self.ampar_fr_d = 1000 / self.ampar_t_d.dropna().diff(axis=1).mean(axis=1) / self.norm_fr
with open(res_p/f'{dataname}_g_nmdar_{magnif_u}_time.pickle', 'rb') as f:
self.nmdar_t_u = pickle.load(f)
self.nmdar_fr_u = 1000 / self.nmdar_t_u.dropna().diff(axis=1).mean(axis=1) / self.norm_fr
with open(res_p/f'{dataname}_g_nmdar_{magnif_d}_time.pickle', 'rb') as f:
self.nmdar_t_d = pickle.load(f)
self.nmdar_fr_d = 1000 / self.nmdar_t_d.dropna().diff(axis=1).mean(axis=1) / self.norm_fr
with open(res_p/f'{dataname}_g_gabar_{magnif_u}_time.pickle', 'rb') as f:
self.gabar_t_u = pickle.load(f)
self.gabar_fr_u = 1000 / self.gabar_t_u.dropna().diff(axis=1).mean(axis=1) / self.norm_fr
with open(res_p/f'{dataname}_g_gabar_{magnif_d}_time.pickle', 'rb') as f:
self.gabar_t_d = pickle.load(f)
self.gabar_fr_d = 1000 / self.gabar_t_d.dropna().diff(axis=1).mean(axis=1) / self.norm_fr
data_dic['nav'] = [self.nav_fr_u, self.nav_fr_d]
data_dic['kvhh'] = [self.kvhh_fr_u, self.kvhh_fr_d]
data_dic['kvsi'] = [self.kvsi_fr_u, self.kvsi_fr_d]
data_dic['kva'] = [self.kva_fr_u, self.kva_fr_d]
data_dic['kir'] = [self.kir_fr_u, self.kir_fr_d]
data_dic['ampar'] = [self.ampar_fr_u, self.ampar_fr_d]
data_dic['nmdar'] = [self.nmdar_fr_u, self.nmdar_fr_d]
data_dic['gabar'] = [self.gabar_fr_u, self.gabar_fr_d]
elif self.model_name == 'SAN':
with open(res_p/f'{dataname}_g_kvhh_{magnif_u}_time.pickle', 'rb') as f:
self.kvhh_t_u = pickle.load(f)
self.kvhh_fr_u = 1000 / self.kvhh_t_u.dropna().diff(axis=1).mean(axis=1) / self.norm_fr
with open(res_p/f'{dataname}_g_kvhh_{magnif_d}_time.pickle', 'rb') as f:
self.kvhh_t_d = pickle.load(f)
self.kvhh_fr_d = 1000 / self.kvhh_t_d.dropna().diff(axis=1).mean(axis=1) / self.norm_fr
data_dic['kvhh'] = [self.kvhh_fr_u, self.kvhh_fr_d]
elif self.model_name == 'RAN':
with open(res_p/f'{dataname}_g_kvsi_{magnif_u}_time.pickle', 'rb') as f:
self.kvsi_t_u = pickle.load(f)
self.kvsi_fr_u = 1000 / self.kvsi_t_u.dropna().diff(axis=1).mean(axis=1) / self.norm_fr
with open(res_p/f'{dataname}_g_kvsi_{magnif_d}_time.pickle', 'rb') as f:
self.kvsi_t_d = pickle.load(f)
self.kvsi_fr_d = 1000 / self.kvsi_t_d.dropna().diff(axis=1).mean(axis=1) / self.norm_fr
data_dic['kvsi'] = [self.kvsi_fr_u, self.kvsi_fr_d]
len_data = len(self.norm_fr)
self.n_df = pd.DataFrame(index=data_dic.keys(), columns=['inc', 'dec'])
self.diff_df = pd.DataFrame(index=data_dic.keys(), columns=['inc', 'dec'])
self.diff_sig = pd.DataFrame(index=data_dic.keys(), columns=['inc', 'dec'])
for ch in data_dic.keys():
n_inc = 0
n_dec = 0
avg_inc = 0
avg_dec = 0
var_inc = 0
var_dec = 0
fr_u, fr_d = data_dic[ch]
fr_u.index = range(len(fr_u))
fr_d.index = range(len(fr_d))
sh_idx = np.intersect1d(fr_u.dropna().index, fr_d.dropna().index)
sh_idx = sh_idx.astype(int)
for idx in sh_idx:
if fr_d[idx] < 0.1 or fr_u[idx] > 2.0:
pass
elif fr_d[idx] > 2.0 or fr_u[idx] < 0.1:
pass
elif fr_d[idx] < 0.975 and fr_u[idx] > 1.025:
n_inc += 1
diff = fr_u[idx] - fr_d[idx]
avg_inc_min1 = copy(avg_inc)
avg_inc += (diff - avg_inc) / n_inc
var_inc += (diff - avg_inc_min1) * (diff - avg_inc)
elif fr_d[idx] > 1.025 and fr_u[idx] < 0.975:
n_dec += 1
diff = fr_u[idx] - fr_d[idx]
avg_dec_min1 = copy(avg_dec)
avg_dec += (diff-avg_dec) / n_dec
var_dec += (diff - avg_dec_min1) * (diff - avg_dec_min1)
else:
pass
self.n_df.loc[ch] = [n_inc/len_data, n_dec/len_data]
self.diff_df.loc[ch] = [avg_inc, avg_dec]
self.diff_sig.loc[ch] = [np.sqrt(var_inc/(len_data-1)), np.sqrt(var_dec/(len_data-1))]
self.n_df = pd.DataFrame(self.n_df.stack().reset_index())
self.diff_df = pd.DataFrame(self.diff_df.stack().reset_index())
self.diff_sig = pd.DataFrame(self.diff_sig.stack().reset_index())
self.n_df.columns = ['channel', 'inc/dec', 'value']
self.diff_df.columns = ['channel', 'inc/dec', 'value']
self.diff_sig.columns = ['channel', 'inc/dec', 'value']
def calc_cal(self, filename: str, t_filename: str,
channel: str, tp: str):
""" Calculate calcium max/min/mean for 1st~6th burst firing for
the all parameter sets.
Parameters
----------
filename: str
the name of file in which parameter sets are contained
tp: str
type of the parameter sets (e.g., typical, atypical)
"""
p: Path = Path.cwd().parents[0]
data_p: Path = p / 'results' / 'normalization_mp_ca'
param_p: Path = p / 'results' / f'{self.wavepattern}_params' / self.model_name
with open(data_p/f'{t_filename}', 'rb') as f:
t_df = pickle.load(f).dropna(how='all')
with open(param_p/f'{filename}', 'rb') as f:
df = pickle.load(f)
t_df.index = range(len(t_df)) # reset index
df.index = range(len(df)) # reset index
if len(t_df) != len(df):
print('The number of parameter sets is different between time file and parameter file!!!')
return 0
with open(data_p/'incdec_analysis'/'index'/ f'{self.model_name}' / f'{channel}_{tp}.pickle', 'rb') as f:
idx = pickle.load(f)
# extract parameter sets in interest
t_df = t_df.loc[idx]
df = df.loc[idx]
resname: str = f'{filename}_{channel}_{tp}.pickle'
res_p: Path = p / 'results' / 'normalization_mp_ca' / 'incdec_analysis' / 'calcium' / self.model_name
res_p.mkdir(parents=True, exist_ok=True)
ca_max_lst = []
ca_min_lst = []
ca_mean_lst = []
for i in tqdm(range(len(t_df))):
param = df.iloc[i, :]
e = t_df.iloc[i, :]
if e[0] == None:
pass
else:
samp_len = 10 + ((5000+e[6])//10000) * 10
self.model.set_params(param)
s, _ = self.model.run_odeint(samp_freq=1000, samp_len=samp_len)
ca: np.ndarray = s[5000:, -1]
ca_max_loc = [] # local max
ca_min_loc = [] # local min
for i in range(6):
ca_max_loc.append(ca[e[i]:e[i+1]].max())
ca_min_loc.append(ca[e[i]:e[i+1]].min())
ca_max_lst.append(np.mean(ca_max_loc))
ca_min_lst.append(np.mean(ca_min_loc))
ca_mean_lst.append(np.mean(ca[e[0]:e[6]]))
tp_lst = [tp] * len(ca_max_lst)
res_df = pd.DataFrame([ca_max_lst, ca_min_lst, ca_mean_lst, tp_lst],
index=['max', 'min', 'mean', 'type']).T
with open(res_p/resname, 'wb') as f:
pickle.dump(res_df, f)
if __name__ == '__main__':
arg: List = sys.argv
model = arg[1]
wavepattern = arg[2]
filename = arg[3]
method = arg[4]
if model == 'RAN':
channel_bool = [1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1]
model_name = 'RAN'
norm = analysistools.norm_fre_mp.Normalization(
'X', wavepattern, channel_bool, model_name
)
elif model == 'Model2':
channel_bool = [1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1]
model_name = 'Model2'
norm = analysistools.norm_fre_mp.Normalization(
'X', wavepattern, channel_bool, model_name
)
else:
norm = analysistools.norm_fre_mp.Normalization(model, wavepattern)
if method == 'time':
norm.time(filename)
elif method == 'mp_ca':
norm.mp_ca(filename)
elif method == 'time_bifurcation_rep':
channel = arg[5]
diff = int(arg[6])
norm.time_bifurcation_rep(filename, channel, diff)
elif method == 'two_bifur':
channel1 = arg[5]
channel2 = arg[6]
diff = int(arg[7])
interval = int(arg[8])
ncore = int(arg[9])
norm.two_bifur_multi_singleprocess(ncore, filename, channel1, channel2, diff, interval)
elif method == 'time_bifurcation_all':
channel = arg[5]
magnif = float(arg[6])
norm.time_bifurcation_all(filename, channel, magnif)
elif method == 'calc_calcium':
t_filename = arg[5]
channel = arg[6]
tp = arg[7]
norm.calc_cal(filename, t_filename, channel, tp)
| [
"numpy.sqrt",
"anmodel.models.Xmodel",
"numpy.array_split",
"copy.copy",
"sys.path.append",
"numpy.arange",
"numpy.mean",
"numpy.linspace",
"pandas.DataFrame",
"anmodel.models.SANmodel",
"matplotlib.pyplot.savefig",
"pathlib.Path.cwd",
"analysistools.norm_fre_mp.Normalization",
"pickle.loa... | [((549, 571), 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), "('../')\n", (564, 571), False, 'import sys\n'), ((572, 601), 'sys.path.append', 'sys.path.append', (['"""../anmodel"""'], {}), "('../anmodel')\n", (587, 601), False, 'import sys\n'), ((6301, 6329), 'anmodel.analysis.FreqSpike', 'anmodel.analysis.FreqSpike', ([], {}), '()\n', (6327, 6329), False, 'import anmodel\n'), ((7974, 8002), 'anmodel.analysis.FreqSpike', 'anmodel.analysis.FreqSpike', ([], {}), '()\n', (8000, 8002), False, 'import anmodel\n'), ((11958, 11986), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(20, 20)'}), '(figsize=(20, 20))\n', (11968, 11986), True, 'import matplotlib.pyplot as plt\n'), ((12050, 12120), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(res_p / f'{self.wavepattern}_{self.model_name}_mp_hm.png')"], {}), "(res_p / f'{self.wavepattern}_{self.model_name}_mp_hm.png')\n", (12061, 12120), True, 'import matplotlib.pyplot as plt\n'), ((12128, 12156), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(20, 20)'}), '(figsize=(20, 20))\n', (12138, 12156), True, 'import matplotlib.pyplot as plt\n'), ((12223, 12293), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(res_p / f'{self.wavepattern}_{self.model_name}_ca_hm.png')"], {}), "(res_p / f'{self.wavepattern}_{self.model_name}_ca_hm.png')\n", (12234, 12293), True, 'import matplotlib.pyplot as plt\n'), ((13464, 13482), 'tqdm.tqdm', 'tqdm', (['res_df.index'], {}), '(res_df.index)\n', (13468, 13482), False, 'from tqdm import tqdm\n'), ((16221, 16252), 'numpy.arange', 'np.arange', (['start', 'end', 'interval'], {}), '(start, end, interval)\n', (16230, 16252), True, 'import numpy as np\n'), ((16270, 16320), 'pandas.DataFrame', 'pd.DataFrame', ([], {'index': 'magnif_lst', 'columns': 'magnif_lst'}), '(index=magnif_lst, columns=magnif_lst)\n', (16282, 16320), True, 'import pandas as pd\n'), ((17272, 17303), 'numpy.arange', 'np.arange', (['start', 'end', 'interval'], {}), '(start, end, interval)\n', (17281, 17303), True, 'import numpy as np\n'), ((17326, 17376), 'pandas.DataFrame', 'pd.DataFrame', ([], {'index': 'magnif_lst', 'columns': 'magnif_lst'}), '(index=magnif_lst, columns=magnif_lst)\n', (17338, 17376), True, 'import pandas as pd\n'), ((34203, 34290), 'analysistools.norm_fre_mp.Normalization', 'analysistools.norm_fre_mp.Normalization', (['"""X"""', 'wavepattern', 'channel_bool', 'model_name'], {}), "('X', wavepattern, channel_bool,\n model_name)\n", (34242, 34290), False, 'import analysistools\n'), ((2072, 2114), 'anmodel.models.ANmodel', 'anmodel.models.ANmodel', (['ion', 'concentration'], {}), '(ion, concentration)\n', (2094, 2114), False, 'import anmodel\n'), ((9060, 9074), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (9071, 9074), False, 'import pickle\n'), ((9771, 9793), 'pickle.dump', 'pickle.dump', (['res_df', 'f'], {}), '(res_df, f)\n', (9782, 9793), False, 'import pickle\n'), ((10301, 10315), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (10312, 10315), False, 'import pickle\n'), ((11821, 11842), 'pickle.dump', 'pickle.dump', (['hm_df', 'f'], {}), '(hm_df, f)\n', (11832, 11842), False, 'import pickle\n'), ((11916, 11940), 'pickle.dump', 'pickle.dump', (['hm_ca_df', 'f'], {}), '(hm_ca_df, f)\n', (11927, 11940), False, 'import pickle\n'), ((13059, 13073), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (13070, 13073), False, 'import pickle\n'), ((13506, 13517), 'copy.copy', 'copy', (['param'], {}), '(param)\n', (13510, 13517), False, 'from copy import copy\n'), ((14124, 14146), 'pickle.dump', 'pickle.dump', (['res_df', 'f'], {}), '(res_df, f)\n', (14135, 14146), False, 'import pickle\n'), ((14407, 14425), 'tqdm.tqdm', 'tqdm', (['r_df.columns'], {}), '(r_df.columns)\n', (14411, 14425), False, 'from tqdm import tqdm\n'), ((15910, 15924), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (15921, 15924), False, 'import pickle\n'), ((16422, 16455), 'numpy.array_split', 'np.array_split', (['magnif_lst', 'ncore'], {}), '(magnif_lst, ncore)\n', (16436, 16455), True, 'import numpy as np\n'), ((16878, 16899), 'multiprocessing.Pool', 'Pool', ([], {'processes': 'ncore'}), '(processes=ncore)\n', (16882, 16899), False, 'from multiprocessing import Pool\n'), ((18371, 18385), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (18382, 18385), False, 'import pickle\n'), ((18741, 18752), 'copy.copy', 'copy', (['param'], {}), '(param)\n', (18745, 18752), False, 'from copy import copy\n'), ((19356, 19378), 'pickle.dump', 'pickle.dump', (['res_df', 'f'], {}), '(res_df, f)\n', (19367, 19378), False, 'import pickle\n'), ((20252, 20266), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (20263, 20266), False, 'import pickle\n'), ((20471, 20485), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (20482, 20485), False, 'import pickle\n'), ((20691, 20705), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (20702, 20705), False, 'import pickle\n'), ((20915, 20929), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (20926, 20929), False, 'import pickle\n'), ((21137, 21151), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (21148, 21151), False, 'import pickle\n'), ((21357, 21371), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (21368, 21371), False, 'import pickle\n'), ((21580, 21594), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (21591, 21594), False, 'import pickle\n'), ((21803, 21817), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (21814, 21817), False, 'import pickle\n'), ((22023, 22037), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (22034, 22037), False, 'import pickle\n'), ((22243, 22257), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (22254, 22257), False, 'import pickle\n'), ((22463, 22477), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (22474, 22477), False, 'import pickle\n'), ((22683, 22697), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (22694, 22697), False, 'import pickle\n'), ((22902, 22916), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (22913, 22916), False, 'import pickle\n'), ((23121, 23135), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (23132, 23135), False, 'import pickle\n'), ((32041, 32055), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (32052, 32055), False, 'import pickle\n'), ((32444, 32458), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (32455, 32458), False, 'import pickle\n'), ((33724, 33825), 'pandas.DataFrame', 'pd.DataFrame', (['[ca_max_lst, ca_min_lst, ca_mean_lst, tp_lst]'], {'index': "['max', 'min', 'mean', 'type']"}), "([ca_max_lst, ca_min_lst, ca_mean_lst, tp_lst], index=['max',\n 'min', 'mean', 'type'])\n", (33736, 33825), True, 'import pandas as pd\n'), ((33912, 33934), 'pickle.dump', 'pickle.dump', (['res_df', 'f'], {}), '(res_df, f)\n', (33923, 33934), False, 'import pickle\n'), ((34449, 34536), 'analysistools.norm_fre_mp.Normalization', 'analysistools.norm_fre_mp.Normalization', (['"""X"""', 'wavepattern', 'channel_bool', 'model_name'], {}), "('X', wavepattern, channel_bool,\n model_name)\n", (34488, 34536), False, 'import analysistools\n'), ((34584, 34643), 'analysistools.norm_fre_mp.Normalization', 'analysistools.norm_fre_mp.Normalization', (['model', 'wavepattern'], {}), '(model, wavepattern)\n', (34623, 34643), False, 'import analysistools\n'), ((2210, 2253), 'anmodel.models.SANmodel', 'anmodel.models.SANmodel', (['ion', 'concentration'], {}), '(ion, concentration)\n', (2233, 2253), False, 'import anmodel\n'), ((8684, 8694), 'pathlib.Path.cwd', 'Path.cwd', ([], {}), '()\n', (8692, 8694), False, 'from pathlib import Path\n'), ((10063, 10073), 'pathlib.Path.cwd', 'Path.cwd', ([], {}), '()\n', (10071, 10073), False, 'from pathlib import Path\n'), ((12666, 12676), 'pathlib.Path.cwd', 'Path.cwd', ([], {}), '()\n', (12674, 12676), False, 'from pathlib import Path\n'), ((13424, 13445), 'numpy.arange', 'np.arange', (['start', 'end'], {}), '(start, end)\n', (13433, 13445), True, 'import numpy as np\n'), ((14454, 14467), 'copy.copy', 'copy', (['param_c'], {}), '(param_c)\n', (14458, 14467), False, 'from copy import copy\n'), ((15348, 15368), 'pickle.dump', 'pickle.dump', (['r_df', 'f'], {}), '(r_df, f)\n', (15359, 15368), False, 'import pickle\n'), ((15486, 15496), 'pathlib.Path.cwd', 'Path.cwd', ([], {}), '()\n', (15494, 15496), False, 'from pathlib import Path\n'), ((16539, 16550), 'copy.copy', 'copy', (['param'], {}), '(param)\n', (16543, 16550), False, 'from copy import copy\n'), ((17051, 17061), 'pathlib.Path.cwd', 'Path.cwd', ([], {}), '()\n', (17059, 17061), False, 'from pathlib import Path\n'), ((17979, 17989), 'pathlib.Path.cwd', 'Path.cwd', ([], {}), '()\n', (17987, 17989), False, 'from pathlib import Path\n'), ((19473, 19483), 'pathlib.Path.cwd', 'Path.cwd', ([], {}), '()\n', (19481, 19483), False, 'from pathlib import Path\n'), ((19795, 19809), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (19806, 19809), False, 'import pickle\n'), ((23732, 23746), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (23743, 23746), False, 'import pickle\n'), ((23964, 23978), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (23975, 23978), False, 'import pickle\n'), ((24198, 24212), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (24209, 24212), False, 'import pickle\n'), ((24434, 24448), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (24445, 24448), False, 'import pickle\n'), ((24670, 24684), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (24681, 24684), False, 'import pickle\n'), ((24906, 24920), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (24917, 24920), False, 'import pickle\n'), ((25140, 25154), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (25151, 25154), False, 'import pickle\n'), ((25372, 25386), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (25383, 25386), False, 'import pickle\n'), ((25604, 25618), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (25615, 25618), False, 'import pickle\n'), ((25836, 25850), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (25847, 25850), False, 'import pickle\n'), ((26072, 26086), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (26083, 26086), False, 'import pickle\n'), ((26312, 26326), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (26323, 26326), False, 'import pickle\n'), ((26552, 26566), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (26563, 26566), False, 'import pickle\n'), ((26792, 26806), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (26803, 26806), False, 'import pickle\n'), ((27032, 27046), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (27043, 27046), False, 'import pickle\n'), ((27272, 27286), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (27283, 27286), False, 'import pickle\n'), ((30792, 30825), 'numpy.sqrt', 'np.sqrt', (['(var_inc / (len_data - 1))'], {}), '(var_inc / (len_data - 1))\n', (30799, 30825), True, 'import numpy as np\n'), ((30823, 30856), 'numpy.sqrt', 'np.sqrt', (['(var_dec / (len_data - 1))'], {}), '(var_dec / (len_data - 1))\n', (30830, 30856), True, 'import numpy as np\n'), ((31695, 31705), 'pathlib.Path.cwd', 'Path.cwd', ([], {}), '()\n', (31703, 31705), False, 'from pathlib import Path\n'), ((2412, 2499), 'anmodel.models.Xmodel', 'anmodel.models.Xmodel', ([], {'channel_bool': 'ran_bool', 'ion': 'ion', 'concentration': 'concentration'}), '(channel_bool=ran_bool, ion=ion, concentration=\n concentration)\n', (2433, 2499), False, 'import anmodel\n'), ((9650, 9672), 'pickle.dump', 'pickle.dump', (['res_df', 'f'], {}), '(res_df, f)\n', (9661, 9672), False, 'import pickle\n'), ((10477, 10491), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (10488, 10491), False, 'import pickle\n'), ((11355, 11396), 'numpy.linspace', 'np.linspace', (['e[j]', 'e[j + 1]', '(9)'], {'dtype': 'int'}), '(e[j], e[j + 1], 9, dtype=int)\n', (11366, 11396), True, 'import numpy as np\n'), ((13994, 14016), 'pickle.dump', 'pickle.dump', (['res_df', 'f'], {}), '(res_df, f)\n', (14005, 14016), False, 'import pickle\n'), ((19227, 19249), 'pickle.dump', 'pickle.dump', (['res_df', 'f'], {}), '(res_df, f)\n', (19238, 19249), False, 'import pickle\n'), ((20043, 20057), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (20054, 20057), False, 'import pickle\n'), ((28061, 28075), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (28072, 28075), False, 'import pickle\n'), ((28297, 28311), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (28308, 28311), False, 'import pickle\n'), ((31938, 31952), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (31949, 31952), False, 'import pickle\n'), ((33532, 33551), 'numpy.mean', 'np.mean', (['ca_max_loc'], {}), '(ca_max_loc)\n', (33539, 33551), True, 'import numpy as np\n'), ((33587, 33606), 'numpy.mean', 'np.mean', (['ca_min_loc'], {}), '(ca_min_loc)\n', (33594, 33606), True, 'import numpy as np\n'), ((33643, 33665), 'numpy.mean', 'np.mean', (['ca[e[0]:e[6]]'], {}), '(ca[e[0]:e[6]])\n', (33650, 33665), True, 'import numpy as np\n'), ((2707, 2762), 'anmodel.models.Xmodel', 'anmodel.models.Xmodel', (['channel_bool', 'ion', 'concentration'], {}), '(channel_bool, ion, concentration)\n', (2728, 2762), False, 'import anmodel\n'), ((17549, 17563), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (17560, 17563), False, 'import pickle\n'), ((28636, 28650), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (28647, 28650), False, 'import pickle\n'), ((28872, 28886), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (28883, 28886), False, 'import pickle\n'), ((30125, 30138), 'copy.copy', 'copy', (['avg_inc'], {}), '(avg_inc)\n', (30129, 30138), False, 'from copy import copy\n'), ((30444, 30457), 'copy.copy', 'copy', (['avg_dec'], {}), '(avg_dec)\n', (30448, 30457), False, 'from copy import copy\n')] |
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
@AUTHOR:<NAME>
@CONTACT:<EMAIL>
@HOME_PAGE:joselynzhao.top
@SOFTWERE:PyCharm
@FILE:3.py
@TIME:2020/5/13 20:13
@DES:
'''
#
# num_book = int(input())
# num_reader = int(input())
# requeir_list = []
# for n in range(num_reader):
# info = list(map(int,input().strip().split()))
# requeir_list.append(info)
# print(requeir_list)
import numpy as np
num_book = 5
num_reader = 3
requeir_list = [[1, 2], [2], [3, 4]]
def get_max_index(l):
index = 0
max = l[0]
for i in range(1,len(l)):
if l[i]>max:
index = i
max = l[i]
return index
def updata_remain(num_book,requeir_list):
temp = []
for i in range(num_book):
temp.append(sum(requeir_list[:,i]))
return temp
# ag_requeir_list = []
for requeir in requeir_list:
for i in range(1,num_book+1):
if i not in requeir:
requeir.insert(i-1,0)
else:
requeir[i-1]=1
# print(requeir)
# print(requeir_list)
requeir_list = np.array(requeir_list)
remain_req = updata_remain(num_book,requeir_list)
satifi_list = np.ones(num_reader)
buy_book = []
while(sum(satifi_list)!=0):
# print('-----------------')
# print(requeir_list)
# print(remain_req)
# print(satifi_list)
# print(remain_req)
index = get_max_index(remain_req)
buy_book.append(index+1)
for i in range(num_reader):
if requeir_list[i][index]==1:
#需求已满足
satifi_list[i]=0
requeir_list[i]= 0
remain_req = updata_remain(num_book,requeir_list)
# print(requeir_list)
# print('-----------------')
print(len(buy_book))
| [
"numpy.array",
"numpy.ones"
] | [((1026, 1048), 'numpy.array', 'np.array', (['requeir_list'], {}), '(requeir_list)\n', (1034, 1048), True, 'import numpy as np\n'), ((1115, 1134), 'numpy.ones', 'np.ones', (['num_reader'], {}), '(num_reader)\n', (1122, 1134), True, 'import numpy as np\n')] |
from unittest import TestCase
import numpy as np
from source.analysis.performance.curve_performance import ROCPerformance, PrecisionRecallPerformance
class TestROCPerformance(TestCase):
def test_properties(self):
true_positive_rates = np.array([1, 2])
false_positive_rates = np.array([3, 4])
roc_performance = ROCPerformance(true_positive_rates=true_positive_rates,
false_positive_rates=false_positive_rates)
self.assertListEqual(true_positive_rates.tolist(), roc_performance.true_positive_rates.tolist())
self.assertListEqual(false_positive_rates.tolist(), roc_performance.false_positive_rates.tolist())
class TestPRPerformance(TestCase):
def test_properties(self):
precisions = np.array([1, 2])
recalls = np.array([3, 4])
precision_recall_performance = PrecisionRecallPerformance(precisions=precisions,
recalls=recalls)
self.assertListEqual(precisions.tolist(), precision_recall_performance.precisions.tolist())
self.assertListEqual(recalls.tolist(), precision_recall_performance.recalls.tolist())
| [
"numpy.array",
"source.analysis.performance.curve_performance.PrecisionRecallPerformance",
"source.analysis.performance.curve_performance.ROCPerformance"
] | [((252, 268), 'numpy.array', 'np.array', (['[1, 2]'], {}), '([1, 2])\n', (260, 268), True, 'import numpy as np\n'), ((300, 316), 'numpy.array', 'np.array', (['[3, 4]'], {}), '([3, 4])\n', (308, 316), True, 'import numpy as np\n'), ((343, 445), 'source.analysis.performance.curve_performance.ROCPerformance', 'ROCPerformance', ([], {'true_positive_rates': 'true_positive_rates', 'false_positive_rates': 'false_positive_rates'}), '(true_positive_rates=true_positive_rates,\n false_positive_rates=false_positive_rates)\n', (357, 445), False, 'from source.analysis.performance.curve_performance import ROCPerformance, PrecisionRecallPerformance\n'), ((786, 802), 'numpy.array', 'np.array', (['[1, 2]'], {}), '([1, 2])\n', (794, 802), True, 'import numpy as np\n'), ((821, 837), 'numpy.array', 'np.array', (['[3, 4]'], {}), '([3, 4])\n', (829, 837), True, 'import numpy as np\n'), ((877, 943), 'source.analysis.performance.curve_performance.PrecisionRecallPerformance', 'PrecisionRecallPerformance', ([], {'precisions': 'precisions', 'recalls': 'recalls'}), '(precisions=precisions, recalls=recalls)\n', (903, 943), False, 'from source.analysis.performance.curve_performance import ROCPerformance, PrecisionRecallPerformance\n')] |
# coding: utf-8
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Trains and Evaluates the Unlimited Hand - Finger condition network using a feed dictionary."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# pylint: disable=missing-docstring
import argparse
import csv
import glob
import math
import os.path
import random
import sys
import time
from six.moves import xrange # pylint: disable=redefined-builtin
import uh_sensor_values as uh_sensor_values
import tensorflow as tf
import numpy as np
from tensorflow.contrib.learn.python.learn.datasets import base
from tensorflow.contrib.learn.python.learn.datasets.mnist import DataSet
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors
from tensorflow.python.framework import errors_impl
from tensorflow.python.framework import graph_io
from tensorflow.python.tools import freeze_graph
# Basic model parameters as external flags.
FLAGS = None
DATA_INDEX_ACCEL = 0
DATA_INDEX_GYRO = 1
DATA_INDEX_PHOTO_REFLECTOR = 2
DATA_INDEX_ANGLE = 3
DATA_INDEX_TEMPERATURE = 4
DATA_INDEX_QUATERNION = 5
DATA_INDEX_AMBIENT_LIGHT = 6
DUMMY_FILE_NAME = "dummy_sensor_data.csv"
READ_SAVED_DATA_BUFFER = []
MAX_FINGER_COUNT = 5
ENABLE_FINGER_COUNT = MAX_FINGER_COUNT
VALIDATE_SENSOR_DATA_SETS = np.array([], dtype=np.float32)
VALIDATE_VALUE_DATA_SETS = np.array([], dtype=np.float32)
class SensorDataFile:
def __init__(self, sensor_data_file):
self.sensor_data_file = sensor_data_file
self.sensor_data_file_desc = None
self.reach_eof = False
self.sub_sensor_data_file_array = []
def __del__(self):
self.fileClose()
def __str__(self):
return self.sensor_data_file + ": " + str(self.reach_eof)
def readLine(self):
if self.sensor_data_file_desc == None:
# open file
self.sensor_data_file_desc = open(self.sensor_data_file, 'r')
line = self.sensor_data_file_desc.readline()
if line == None or len(line) == 0:
# 本当は正しくないけど、簡易的に判断するようにする
self.reach_eof = True
return line
def isEndOfFile(self):
return self.reach_eof
def fileClose(self):
if self.sensor_data_file_desc != None:
self.sensor_data_file_desc.close()
self.sensor_data_file_desc = None
self.reach_eof = False
if len(self.sub_sensor_data_file_array) > 0:
for sub_sensor_data_file in self.sub_sensor_data_file_array:
sub_sensor_data_file.fileClose()
def placeholder_inputs(batch_size):
"""Generate placeholder variables to represent the input tensors.
These placeholders are used as inputs by the rest of the model building
code and will be fed from the downloaded data in the .run() loop, below.
Args:
batch_size: The batch size will be baked into both placeholders.
Returns:
sensor_values_placeholder: Sensor values placeholder.
labels_placeholder: Labels placeholder.
"""
# Note that the shapes of the placeholders match the shapes of the full
# sensor values and label tensors, except the first dimension is now batch_size
# rather than the full size of the train or test data sets.
sensor_values_placeholder = tf.placeholder(tf.float32, shape=(batch_size,
get_parameter_data_count()),
name="sensor_values_placeholder")
labels_placeholder = tf.placeholder(tf.int32, shape=(batch_size), name="labels_placeholder")
return sensor_values_placeholder, labels_placeholder
def fill_feed_dict(data_set, sensor_values_pl, labels_pl):
"""Fills the feed_dict for training the given step.
A feed_dict takes the form of:
feed_dict = {
<placeholder>: <tensor of values to be passed for placeholder>,
....
}
Args:
data_set: The set of images and labels, from input_data.read_data_sets()
sensor_values_pl: The sensor values placeholder, from placeholder_inputs().
labels_pl: The labels placeholder, from placeholder_inputs().
Returns:
feed_dict: The feed dictionary mapping from placeholders to values.
"""
# Create the feed_dict for the placeholders filled with the next
# `batch size` examples.
sensor_values_feed, labels_feed = data_set.next_batch(FLAGS.batch_size,
FLAGS.fake_data)
feed_dict = {
sensor_values_pl: sensor_values_feed,
labels_pl: labels_feed,
}
return feed_dict
def do_eval(sess,
eval_correct,
sensor_values_placeholder,
labels_placeholder,
data_set):
"""Runs one evaluation against the full epoch of data.
Args:
sess: The session in which the model has been trained.
eval_correct: The Tensor that returns the number of correct predictions.
sensor_values_placeholder: The sensor values placeholder.
labels_placeholder: The labels placeholder.
data_set: The set of sensor values and labels to evaluate, from
input_data.read_data_sets().
"""
# And run one epoch of eval.
true_count = 0 # Counts the number of correct predictions.
steps_per_epoch = data_set.num_examples // FLAGS.batch_size
num_examples = steps_per_epoch * FLAGS.batch_size
for step in xrange(steps_per_epoch):
feed_dict = fill_feed_dict(data_set,
sensor_values_placeholder,
labels_placeholder)
true_count += sess.run(eval_correct, feed_dict=feed_dict)
if num_examples == 0:
precision = float(true_count) / data_set.num_examples
print(' Num examples: %d Num correct: %d Precision @ 1: %0.04f' %
(data_set.num_examples, true_count, precision))
else:
precision = float(true_count) / num_examples
print(' Num examples: %d Num correct: %d Precision @ 1: %0.04f' %
(num_examples, true_count, precision))
def run_training():
"""Train sensor data for a number of steps."""
# check enable finger count from FLAGS.enable_finger_flags
ENABLE_FINGER_COUNT = get_enable_finger_count()
# Get the sets of images and labels for training, validation, and test on uh_sensor_values.
read_step = FLAGS.batch_size
max_read_step = FLAGS.max_steps
with tf.Graph().as_default() as graph:
# Create a session for running Ops on the Graph.
sess = tf.Session()
# Generate placeholders for the images and labels.
sensor_values_placeholder, labels_placeholder = placeholder_inputs(FLAGS.batch_size)
# Build a Graph that computes predictions from the inference model.
layer_units_array = [get_parameter_data_count()]
hidden_layer_units_array = FLAGS.hidden_layrer_units.split(',')
for hidden_layer_units in hidden_layer_units_array:
layer_units_array.append(int(hidden_layer_units))
if FLAGS.use_rps_mode:
# 3layer for rock-paper-scissors mode
layer_units_array.append(3)
else:
layer_units_array.append(FLAGS.max_finger_condition ** ENABLE_FINGER_COUNT)
logits = uh_sensor_values.inference(sensor_values_placeholder, layer_units_array)
# Add to the Graph the Ops for loss calculation.
loss = uh_sensor_values.loss(logits, labels_placeholder)
# Add to the Graph the Ops that calculate and apply gradients.
train_op = uh_sensor_values.training(FLAGS.optimizer, loss, FLAGS.learning_rate)
# Add the Op to compare the logits to the labels during evaluation.
eval_correct = uh_sensor_values.evaluation(logits, labels_placeholder)
# Build the summary Tensor based on the TF collection of Summaries.
summary = tf.summary.merge_all()
# Add the variable initializer Op.
init = tf.global_variables_initializer()
# Instantiate a SummaryWriter to output summaries and the Graph.
summary_writer = tf.summary.FileWriter(FLAGS.log_dir, sess.graph)
# And then after everything is built:
# Run the Op to initialize the variables.
sess.run(init)
# Create a saver for writing training checkpoints.
saver = tf.train.Saver(max_to_keep=FLAGS.max_save_checkpoint)
checkpoint = ''
checkpoint_file = os.path.join(FLAGS.log_dir, 'model.ckpt')
eof_dict = {}
data_files = []
data_file_paths = []
if FLAGS.random_learning:
max_read_step, out_file_name = create_random_data_file()
data_file_paths = [out_file_name]
else:
data_file_paths = glob.glob(FLAGS.input_data_dir + "/sensor_data_*")
total_read_step = 0
# ファイルパスからSensorDataFileインスタンスへ変更
for data_file_path in data_file_paths:
data_files.append(SensorDataFile(data_file_path))
for data_file in data_files:
print('%s: ' % data_file)
offset_step = 0
while True:
# read data_sets from CVS
data_sets = read_sensor_data_sets(data_file, offset_step=offset_step, read_step=read_step)
if data_sets != None:
# Start the training loop.
start_time = time.time()
# Fill a feed dictionary with the actual set of images and labels
# for this particular training step.
feed_dict = fill_feed_dict(data_sets.train,
sensor_values_placeholder,
labels_placeholder)
# Run one step of the model. The return values are the activations
# from the `train_op` (which is discarded) and the `loss` Op. To
# inspect the values of your Ops or variables, you may include them
# in the list passed to sess.run() and the value tensors will be
# returned in the tuple from the call.
_, loss_value = sess.run([train_op, loss],
feed_dict=feed_dict)
duration = time.time() - start_time
# Write the summaries and print an overview fairly often.
if total_read_step % 100 == 0:
# Print status to stdout.
print('Step %d - %d: loss = %.2f (%.3f sec)' % (total_read_step, total_read_step + read_step, loss_value, duration))
# Update the events file.
summary_str = sess.run(summary, feed_dict=feed_dict)
summary_writer.add_summary(summary_str, total_read_step)
summary_writer.flush()
if (FLAGS.max_steps > 0) and ((total_read_step + read_step) % FLAGS.max_steps == 0):
# Save a checkpoint and evaluate the model periodically.
checkpoint = saver.save(sess, checkpoint_file, global_step=total_read_step)
offset_step += read_step
total_read_step += read_step
else:
break;
# Save a checkpoint and evaluate the model periodically.
checkpoint = saver.save(sess, checkpoint_file, global_step=total_read_step)
graph_io.write_graph(sess.graph, FLAGS.saved_data_dir, "saved_data.pb", as_text=False)
input_binary = True
input_graph_path = os.path.join(FLAGS.saved_data_dir, "saved_data.pb")
input_saver = ""
output_node_names = "eval_correct"
restore_op_name = "save/restore_all"
filename_tensor_name = "save/Const:0"
output_graph_path = os.path.join(FLAGS.saved_data_dir, "saved_data_out.pb")
clear_devices = False
freeze_graph.freeze_graph(input_graph_path, input_saver,
input_binary, checkpoint, output_node_names,
restore_op_name, filename_tensor_name,
output_graph_path, clear_devices, "", "")
# Evaluate against the training set.
print('Validation Data Eval:')
global VALIDATE_SENSOR_DATA_SETS
global VALIDATE_VALUE_DATA_SETS
new_shape = (int(len(VALIDATE_SENSOR_DATA_SETS) / get_parameter_data_count()), get_parameter_data_count())
VALIDATE_SENSOR_DATA_SETS = np.reshape(VALIDATE_SENSOR_DATA_SETS, new_shape)
VALIDATE_SENSOR_DATA_SETS.astype(np.float32)
train = DataSet(VALIDATE_SENSOR_DATA_SETS, VALIDATE_VALUE_DATA_SETS, dtype=dtypes.uint8, reshape=False)
data_sets = base.Datasets(train=train, validation=train, test=train)
if data_sets != None:
do_eval(sess,
eval_correct,
sensor_values_placeholder,
labels_placeholder,
data_sets.train)
def get_enable_finger_count():
enable_finger_count = 0
max_finger_count = MAX_FINGER_COUNT
enable_finger_flags = FLAGS.enable_finger_flags
for exponent in xrange(max_finger_count):
if enable_finger_flags % 10 != 0:
enable_finger_count += 1
# 桁を下げる
enable_finger_flags = enable_finger_flags // 10
return enable_finger_count
def create_random_data_file():
# ランダムデータを集めたファイルは作成に時間が掛かるので、それは作成せずに、ダミーファイルパスを返却し、コール元でパスにより判断できるようにする
data_files = glob.glob(FLAGS.input_data_dir + "/sensor_data_*")
return (FLAGS.max_steps * len(data_files), DUMMY_FILE_NAME)
def read_sensor_data_sets(
train_data_file,
dtype=dtypes.uint8,
reshape=False,
training=True,
offset_step=0,
read_step=500):
global VALIDATE_SENSOR_DATA_SETS
global VALIDATE_VALUE_DATA_SETS
global READ_SAVED_DATA_BUFFER
sensor_data_sets = np.array([], dtype=np.float32)
value_data_sets = np.array([], dtype=np.float32)
no_data = True
combine_data_line_array = []
if train_data_file.sensor_data_file == DUMMY_FILE_NAME:
if (FLAGS.max_steps == 0) or (offset_step < FLAGS.max_steps):
if len(train_data_file.sub_sensor_data_file_array) == 0:
data_files = glob.glob(FLAGS.input_data_dir + "/sensor_data_*")
for data_file in data_files:
data_file_flags = data_file[len(FLAGS.input_data_dir + "/sensor_data_"):]
enable_finger_flags = FLAGS.enable_finger_flags
enable_data_file = True
try:
data_file_flags_int = int(data_file_flags)
for finger_flag_count in xrange(MAX_FINGER_COUNT):
if enable_finger_flags % 10 == 0:
if data_file_flags_int % 10 != 0:
enable_data_file = False
break
data_file_flags_int = data_file_flags_int // 10
enable_finger_flags = enable_finger_flags // 10
except:
enable_data_file = False
pass
if enable_data_file:
train_data_file.sub_sensor_data_file_array.append(SensorDataFile(data_file))
data_files = train_data_file.sub_sensor_data_file_array
index_list = list(range(len(data_files)))
need_read_count = math.ceil((FLAGS.batch_size - len(READ_SAVED_DATA_BUFFER)) / len(data_files))
while len(READ_SAVED_DATA_BUFFER) < FLAGS.batch_size:
all_file_empty = False
for read_count in xrange(need_read_count):
empty_file_count = 0
random.shuffle(index_list)
for file_index in index_list:
if (data_files[file_index].isEndOfFile()) == False:
read_buffer = data_files[file_index].readLine()
if (read_buffer != None) and (len(read_buffer) > 0):
READ_SAVED_DATA_BUFFER.append(read_buffer.rstrip("\n").split(','))
else:
empty_file_count += 1
else:
empty_file_count += 1
if FLAGS.use_same_data_count and empty_file_count > 0:
# 全てのファイルからデータを取得できなくなったので、学習は終了させる
all_file_empty = True
break
elif empty_file_count == len(data_files):
# 全てのファイルから読み込めなくなったときはあきらめる
all_file_empty = True
break
if all_file_empty == True:
break
step_count = 0
read_step_count = 0
used_buffer_index = 0
if len(READ_SAVED_DATA_BUFFER) >= FLAGS.batch_size:
for line_index in xrange(FLAGS.batch_size):
used_buffer_index = line_index
if len(READ_SAVED_DATA_BUFFER) <= line_index:
break
else:
no_data = False
if read_step_count < read_step:
temp_data_array = []
temp_data_array.append(READ_SAVED_DATA_BUFFER[line_index])
sensor_data_sets, value_data_sets = insert_sensor_data(sensor_data_sets, value_data_sets, temp_data_array, training)
step_count+=1
read_step_count+=1
else:
break
# 使った分は削除する
READ_SAVED_DATA_BUFFER = READ_SAVED_DATA_BUFFER[read_step_count:]
else:
data_file_flags = train_data_file.sensor_data_file[len(FLAGS.input_data_dir + "/sensor_data_"):]
enable_finger_flags = FLAGS.enable_finger_flags
enable_data_file = True
try:
data_file_flags_int = int(data_file_flags)
for finger_flag_count in xrange(MAX_FINGER_COUNT):
if enable_finger_flags % 10 == 0:
if data_file_flags_int % 10 != 0:
enable_data_file = False
break
data_file_flags_int = data_file_flags_int // 10
enable_finger_flags = enable_finger_flags // 10
except:
enable_data_file = False
pass
if enable_data_file:
while len(READ_SAVED_DATA_BUFFER) < FLAGS.batch_size:
if (train_data_file.isEndOfFile()) == False:
read_buffer = train_data_file.readLine()
if (read_buffer != None) and (len(read_buffer) > 0):
READ_SAVED_DATA_BUFFER.append(read_buffer.rstrip("\n").split(','))
else:
break
else:
break
step_count = 0
read_step_count = 0
used_buffer_index = 0
if len(READ_SAVED_DATA_BUFFER) >= FLAGS.batch_size:
for line_index in xrange(FLAGS.batch_size):
used_buffer_index = line_index
if len(READ_SAVED_DATA_BUFFER) <= line_index:
break
else:
no_data = False
if read_step_count < read_step:
temp_data_array = []
temp_data_array.append(READ_SAVED_DATA_BUFFER[line_index])
sensor_data_sets, value_data_sets = insert_sensor_data(sensor_data_sets, value_data_sets, temp_data_array, training)
step_count+=1
read_step_count+=1
else:
break
# 使った分は削除する
READ_SAVED_DATA_BUFFER = []
if not no_data:
new_shape = (read_step_count, get_parameter_data_count())
sensor_data_sets = np.reshape(sensor_data_sets, new_shape)
sensor_data_sets.astype(np.float32)
if len(np.atleast_1d(VALIDATE_SENSOR_DATA_SETS)) < (FLAGS.validation_count * get_parameter_data_count()):
use_data_index = random.randint(0, len(sensor_data_sets) - 1)
VALIDATE_SENSOR_DATA_SETS = np.append(VALIDATE_SENSOR_DATA_SETS, sensor_data_sets[use_data_index])
VALIDATE_VALUE_DATA_SETS = np.append(VALIDATE_VALUE_DATA_SETS, value_data_sets[use_data_index])
train = DataSet(sensor_data_sets, value_data_sets, dtype=dtype, reshape=reshape)
return base.Datasets(train=train, validation=train, test=train)
else:
return None
def insert_sensor_data(sensor_data_sets, value_data_sets, combine_data_line_array, training):
for data_index in xrange(len(combine_data_line_array)):
sensor_data_set_array = combine_data_line_array[data_index][0].split('+')
for sensor_data_set_index in xrange(len(sensor_data_set_array)):
data_array = None
if sensor_data_set_index == DATA_INDEX_ACCEL and FLAGS.use_accel:
data_array = sensor_data_set_array[sensor_data_set_index].split('_')
elif sensor_data_set_index == DATA_INDEX_GYRO and FLAGS.use_gyro:
data_array = sensor_data_set_array[sensor_data_set_index].split('_')
elif sensor_data_set_index == DATA_INDEX_PHOTO_REFLECTOR and FLAGS.use_photo:
data_array = sensor_data_set_array[sensor_data_set_index].split('_')
elif sensor_data_set_index == DATA_INDEX_ANGLE and FLAGS.use_angle:
data_array = sensor_data_set_array[sensor_data_set_index].split('_')
elif sensor_data_set_index == DATA_INDEX_TEMPERATURE and FLAGS.use_temperature:
data_array = sensor_data_set_array[sensor_data_set_index].split('_')
elif sensor_data_set_index == DATA_INDEX_QUATERNION and FLAGS.use_quaternion:
data_array = sensor_data_set_array[sensor_data_set_index].split('_')
elif sensor_data_set_index == DATA_INDEX_AMBIENT_LIGHT and FLAGS.use_ambient_light:
data_array = sensor_data_set_array[sensor_data_set_index].split('_')
if data_array != None:
for data in data_array:
if data != "null":
if FLAGS.expand_data_size > 0:
# dataをFLAGS.expand_data_size分まで0詰め
data = data.zfill(FLAGS.expand_data_size)
data_byte_array = data.encode()
for data_byte in data_byte_array:
sensor_data_sets = np.append(sensor_data_sets, float(data_byte))
else:
# dataをそのまま使用
sensor_data_sets = np.append(sensor_data_sets, data)
if data_index == (len(combine_data_line_array) - 1):
if training == True:
# use value
try:
value_data_sets = np.append(value_data_sets, combine_data_line_array[data_index][1])
except IndexError:
print("combine_data_line_array: %s" % combine_data_line_array)
# remove first data, because it is not of range for combination
del combine_data_line_array[0]
return (sensor_data_sets, value_data_sets)
def get_parameter_data_count():
ret_unit = 0
if FLAGS.use_accel:
ret_unit += 3
if FLAGS.use_gyro:
ret_unit += 3
if FLAGS.use_photo:
ret_unit += 8
if FLAGS.use_angle:
ret_unit += 3
if FLAGS.use_temperature:
ret_unit += 1
if FLAGS.use_quaternion:
ret_unit += 4
if FLAGS.use_ambient_light:
ret_unit += 1
if FLAGS.expand_data_size > 0:
return (ret_unit * FLAGS.expand_data_size * FLAGS.combine_data_line_count)
else:
return (ret_unit * FLAGS.combine_data_line_count)
def main(_):
# if tf.gfile.Exists(FLAGS.log_dir):
# tf.gfile.DeleteRecursively(FLAGS.log_dir)
# tf.gfile.MakeDirs(FLAGS.log_dir)
run_training()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
'--debug_log',
default=False,
help='enable debug log'
)
parser.add_argument(
'--learning_rate',
type=float,
default=0.01,
help='Initial learning rate.'
)
parser.add_argument(
'--max_steps',
type=int,
default=0,
help='0: unlimited'
)
parser.add_argument(
'--validation_count',
type=int,
default=1000,
help=''
)
parser.add_argument(
'--hidden_layrer_units',
type=str,
default='8,4',
help='Number of units in hidden layers.'
)
parser.add_argument(
'--batch_size',
type=int,
default=100,
help='Batch size. Must divide evenly into the dataset sizes.'
)
parser.add_argument(
'--input_data_dir',
type=str,
default='data',
help='Directory to put the input data.'
)
parser.add_argument(
'--log_dir',
type=str,
default='./checkpoint',
help='Directory to put the log data.'
)
parser.add_argument(
'--max_save_checkpoint',
type=int,
default=1000,
help=''
)
parser.add_argument(
'--fake_data',
default=False,
help='If true, uses fake data for unit testing.',
action='store_true'
)
parser.add_argument(
'--saved_data_dir',
type=str,
default='./saved_train_data',
help='Directory to restore the saved data.'
)
parser.add_argument(
'--combine_data_line_count',
type=int,
default=1,
help=''
)
parser.add_argument(
'--max_finger_condition',
type=int,
default=2,
help='0: straight, 1: curve'
)
parser.add_argument(
'--random_learning',
type=int,
default=1,
help='0: no random learning, none 0: random learning'
)
parser.add_argument(
'--use_accel',
default=False,
action='store_true',
help='use accel for learning'
)
parser.add_argument(
'--use_gyro',
default=False,
action='store_true',
help='use gyro for learning'
)
parser.add_argument(
'--use_photo',
default=False,
action='store_true',
help='use photo reflector for learning'
)
parser.add_argument(
'--use_angle',
default=False,
action='store_true',
help='use angle for learning'
)
parser.add_argument(
'--use_temperature',
default=False,
action='store_true',
help='use temperature for learning'
)
parser.add_argument(
'--use_quaternion',
default=False,
action='store_true',
help='use quaternion for learning'
)
parser.add_argument(
'--use_ambient_light',
default=False,
action='store_true',
help='use ambient light for learning'
)
parser.add_argument(
'--expand_data_size',
type=int,
default=0,
help='0: As is'
)
parser.add_argument(
'--use_same_data_count',
default=False,
action='store_true',
help='use same data from each data files'
)
parser.add_argument(
'--use_rps_mode',
default=False,
action='store_true',
help='use rock-paper-scissors mode'
)
parser.add_argument(
'--enable_finger_flags',
type=int,
default=11111,
help='0: disable, none 0: enable, PRMIT order'
)
parser.add_argument(
'--optimizer',
type=str,
default='tf.train.AdamOptimizer',
help=''
)
FLAGS, unparsed = parser.parse_known_args()
tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
| [
"numpy.array",
"six.moves.xrange",
"uh_sensor_values.loss",
"tensorflow.app.run",
"tensorflow.Graph",
"numpy.reshape",
"argparse.ArgumentParser",
"tensorflow.placeholder",
"tensorflow.Session",
"glob.glob",
"tensorflow.summary.merge_all",
"uh_sensor_values.inference",
"random.shuffle",
"te... | [((1981, 2011), 'numpy.array', 'np.array', (['[]'], {'dtype': 'np.float32'}), '([], dtype=np.float32)\n', (1989, 2011), True, 'import numpy as np\n'), ((2039, 2069), 'numpy.array', 'np.array', (['[]'], {'dtype': 'np.float32'}), '([], dtype=np.float32)\n', (2047, 2069), True, 'import numpy as np\n'), ((4184, 4253), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {'shape': 'batch_size', 'name': '"""labels_placeholder"""'}), "(tf.int32, shape=batch_size, name='labels_placeholder')\n", (4198, 4253), True, 'import tensorflow as tf\n'), ((6012, 6035), 'six.moves.xrange', 'xrange', (['steps_per_epoch'], {}), '(steps_per_epoch)\n', (6018, 6035), False, 'from six.moves import xrange\n'), ((13824, 13848), 'six.moves.xrange', 'xrange', (['max_finger_count'], {}), '(max_finger_count)\n', (13830, 13848), False, 'from six.moves import xrange\n'), ((14161, 14211), 'glob.glob', 'glob.glob', (["(FLAGS.input_data_dir + '/sensor_data_*')"], {}), "(FLAGS.input_data_dir + '/sensor_data_*')\n", (14170, 14211), False, 'import glob\n'), ((14630, 14660), 'numpy.array', 'np.array', (['[]'], {'dtype': 'np.float32'}), '([], dtype=np.float32)\n', (14638, 14660), True, 'import numpy as np\n'), ((14683, 14713), 'numpy.array', 'np.array', (['[]'], {'dtype': 'np.float32'}), '([], dtype=np.float32)\n', (14691, 14713), True, 'import numpy as np\n'), ((25155, 25180), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (25178, 25180), False, 'import argparse\n'), ((28987, 29039), 'tensorflow.app.run', 'tf.app.run', ([], {'main': 'main', 'argv': '([sys.argv[0]] + unparsed)'}), '(main=main, argv=[sys.argv[0]] + unparsed)\n', (28997, 29039), True, 'import tensorflow as tf\n'), ((7124, 7136), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (7134, 7136), True, 'import tensorflow as tf\n'), ((7858, 7930), 'uh_sensor_values.inference', 'uh_sensor_values.inference', (['sensor_values_placeholder', 'layer_units_array'], {}), '(sensor_values_placeholder, layer_units_array)\n', (7884, 7930), True, 'import uh_sensor_values as uh_sensor_values\n'), ((8004, 8053), 'uh_sensor_values.loss', 'uh_sensor_values.loss', (['logits', 'labels_placeholder'], {}), '(logits, labels_placeholder)\n', (8025, 8053), True, 'import uh_sensor_values as uh_sensor_values\n'), ((8145, 8214), 'uh_sensor_values.training', 'uh_sensor_values.training', (['FLAGS.optimizer', 'loss', 'FLAGS.learning_rate'], {}), '(FLAGS.optimizer, loss, FLAGS.learning_rate)\n', (8170, 8214), True, 'import uh_sensor_values as uh_sensor_values\n'), ((8315, 8370), 'uh_sensor_values.evaluation', 'uh_sensor_values.evaluation', (['logits', 'labels_placeholder'], {}), '(logits, labels_placeholder)\n', (8342, 8370), True, 'import uh_sensor_values as uh_sensor_values\n'), ((8466, 8488), 'tensorflow.summary.merge_all', 'tf.summary.merge_all', ([], {}), '()\n', (8486, 8488), True, 'import tensorflow as tf\n'), ((8548, 8581), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (8579, 8581), True, 'import tensorflow as tf\n'), ((8681, 8729), 'tensorflow.summary.FileWriter', 'tf.summary.FileWriter', (['FLAGS.log_dir', 'sess.graph'], {}), '(FLAGS.log_dir, sess.graph)\n', (8702, 8729), True, 'import tensorflow as tf\n'), ((8927, 8980), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {'max_to_keep': 'FLAGS.max_save_checkpoint'}), '(max_to_keep=FLAGS.max_save_checkpoint)\n', (8941, 8980), True, 'import tensorflow as tf\n'), ((12073, 12163), 'tensorflow.python.framework.graph_io.write_graph', 'graph_io.write_graph', (['sess.graph', 'FLAGS.saved_data_dir', '"""saved_data.pb"""'], {'as_text': '(False)'}), "(sess.graph, FLAGS.saved_data_dir, 'saved_data.pb',\n as_text=False)\n", (12093, 12163), False, 'from tensorflow.python.framework import graph_io\n'), ((12550, 12740), 'tensorflow.python.tools.freeze_graph.freeze_graph', 'freeze_graph.freeze_graph', (['input_graph_path', 'input_saver', 'input_binary', 'checkpoint', 'output_node_names', 'restore_op_name', 'filename_tensor_name', 'output_graph_path', 'clear_devices', '""""""', '""""""'], {}), "(input_graph_path, input_saver, input_binary,\n checkpoint, output_node_names, restore_op_name, filename_tensor_name,\n output_graph_path, clear_devices, '', '')\n", (12575, 12740), False, 'from tensorflow.python.tools import freeze_graph\n'), ((13152, 13200), 'numpy.reshape', 'np.reshape', (['VALIDATE_SENSOR_DATA_SETS', 'new_shape'], {}), '(VALIDATE_SENSOR_DATA_SETS, new_shape)\n', (13162, 13200), True, 'import numpy as np\n'), ((13271, 13371), 'tensorflow.contrib.learn.python.learn.datasets.mnist.DataSet', 'DataSet', (['VALIDATE_SENSOR_DATA_SETS', 'VALIDATE_VALUE_DATA_SETS'], {'dtype': 'dtypes.uint8', 'reshape': '(False)'}), '(VALIDATE_SENSOR_DATA_SETS, VALIDATE_VALUE_DATA_SETS, dtype=dtypes.\n uint8, reshape=False)\n', (13278, 13371), False, 'from tensorflow.contrib.learn.python.learn.datasets.mnist import DataSet\n'), ((13387, 13443), 'tensorflow.contrib.learn.python.learn.datasets.base.Datasets', 'base.Datasets', ([], {'train': 'train', 'validation': 'train', 'test': 'train'}), '(train=train, validation=train, test=train)\n', (13400, 13443), False, 'from tensorflow.contrib.learn.python.learn.datasets import base\n'), ((20950, 20989), 'numpy.reshape', 'np.reshape', (['sensor_data_sets', 'new_shape'], {}), '(sensor_data_sets, new_shape)\n', (20960, 20989), True, 'import numpy as np\n'), ((21458, 21530), 'tensorflow.contrib.learn.python.learn.datasets.mnist.DataSet', 'DataSet', (['sensor_data_sets', 'value_data_sets'], {'dtype': 'dtype', 'reshape': 'reshape'}), '(sensor_data_sets, value_data_sets, dtype=dtype, reshape=reshape)\n', (21465, 21530), False, 'from tensorflow.contrib.learn.python.learn.datasets.mnist import DataSet\n'), ((21547, 21603), 'tensorflow.contrib.learn.python.learn.datasets.base.Datasets', 'base.Datasets', ([], {'train': 'train', 'validation': 'train', 'test': 'train'}), '(train=train, validation=train, test=train)\n', (21560, 21603), False, 'from tensorflow.contrib.learn.python.learn.datasets import base\n'), ((9342, 9392), 'glob.glob', 'glob.glob', (["(FLAGS.input_data_dir + '/sensor_data_*')"], {}), "(FLAGS.input_data_dir + '/sensor_data_*')\n", (9351, 9392), False, 'import glob\n'), ((18948, 18972), 'six.moves.xrange', 'xrange', (['MAX_FINGER_COUNT'], {}), '(MAX_FINGER_COUNT)\n', (18954, 18972), False, 'from six.moves import xrange\n'), ((21262, 21332), 'numpy.append', 'np.append', (['VALIDATE_SENSOR_DATA_SETS', 'sensor_data_sets[use_data_index]'], {}), '(VALIDATE_SENSOR_DATA_SETS, sensor_data_sets[use_data_index])\n', (21271, 21332), True, 'import numpy as np\n'), ((21372, 21440), 'numpy.append', 'np.append', (['VALIDATE_VALUE_DATA_SETS', 'value_data_sets[use_data_index]'], {}), '(VALIDATE_VALUE_DATA_SETS, value_data_sets[use_data_index])\n', (21381, 21440), True, 'import numpy as np\n'), ((7018, 7028), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (7026, 7028), True, 'import tensorflow as tf\n'), ((14995, 15045), 'glob.glob', 'glob.glob', (["(FLAGS.input_data_dir + '/sensor_data_*')"], {}), "(FLAGS.input_data_dir + '/sensor_data_*')\n", (15004, 15045), False, 'import glob\n'), ((16469, 16492), 'six.moves.xrange', 'xrange', (['need_read_count'], {}), '(need_read_count)\n', (16475, 16492), False, 'from six.moves import xrange\n'), ((17797, 17821), 'six.moves.xrange', 'xrange', (['FLAGS.batch_size'], {}), '(FLAGS.batch_size)\n', (17803, 17821), False, 'from six.moves import xrange\n'), ((20033, 20057), 'six.moves.xrange', 'xrange', (['FLAGS.batch_size'], {}), '(FLAGS.batch_size)\n', (20039, 20057), False, 'from six.moves import xrange\n'), ((21049, 21089), 'numpy.atleast_1d', 'np.atleast_1d', (['VALIDATE_SENSOR_DATA_SETS'], {}), '(VALIDATE_SENSOR_DATA_SETS)\n', (21062, 21089), True, 'import numpy as np\n'), ((9971, 9982), 'time.time', 'time.time', ([], {}), '()\n', (9980, 9982), False, 'import time\n'), ((16555, 16581), 'random.shuffle', 'random.shuffle', (['index_list'], {}), '(index_list)\n', (16569, 16581), False, 'import random\n'), ((24033, 24099), 'numpy.append', 'np.append', (['value_data_sets', 'combine_data_line_array[data_index][1]'], {}), '(value_data_sets, combine_data_line_array[data_index][1])\n', (24042, 24099), True, 'import numpy as np\n'), ((10882, 10893), 'time.time', 'time.time', ([], {}), '()\n', (10891, 10893), False, 'import time\n'), ((15439, 15463), 'six.moves.xrange', 'xrange', (['MAX_FINGER_COUNT'], {}), '(MAX_FINGER_COUNT)\n', (15445, 15463), False, 'from six.moves import xrange\n'), ((23817, 23850), 'numpy.append', 'np.append', (['sensor_data_sets', 'data'], {}), '(sensor_data_sets, data)\n', (23826, 23850), True, 'import numpy as np\n')] |
from __future__ import print_function
import numpy as np
import pandas as pd
import inspect
import os
import time
from . import Model
from . import Utils as U
#------------------------------
#FINDING NEAREST NEIGHBOR
#------------------------------
def mindistance(x,xma,Nx):
distx = 0
mindist = 1000000 * U.PC * U.AU
j = None
for i in range(Nx):
distx = abs(x-xma[i])
if (distx<mindist):
mindist=distx
j=i
return j
#------------------------------
#OVERLAPING SUBMODELS INTO GRID
#------------------------------
def overlap(GRID, submodels = [''], folder = './Subgrids/',
T_min = 30., rho_min = 1.e9,
all = False, radmc3d = False):
func_name = inspect.stack()[0][3]
if folder[-1] != '/': folder = folder + '/'
t0 = time.time()
num=int(np.loadtxt(os.popen("ls -1 %s*.dat| wc -l"%folder)))
data=os.popen("ls -1 %s*.dat"%folder).read().split('\n',num)[:-1]
if all:
names = [name for name in data] # if '_S.' in name or '_MSW' in name]
files = [np.loadtxt(name) for name in names]
else:
submodels = [folder + sub for sub in submodels]
names = [name for name in submodels]
files = [np.loadtxt(name) for name in names]
detected = [tmp.split(folder)[1] for tmp in data]
read = [tmp.split(folder)[1] for tmp in names]
print ("Running function '%s'..."%func_name)
print ('Files detected (%d):'%num, detected,
'\nFiles to merge in grid (%d):'%len(files), read)
NTotal = GRID.NPoints
Nx, Ny, Nz = GRID.Nodes
cm3_to_m3 = 1e6
gamma = 7./5 #Gamma for diatomic molecules
DENS = -1*np.ones(NTotal) #, dtype='float64') * 0.5 # * dens_back
TEMP = np.zeros(NTotal) # * temp_back * dens_back
ab0 = 5e-8
ABUND = np.zeros(NTotal) #np.ones(NTotal) * ab0
gtd0 = 100.
GTD = np.zeros(NTotal) #np.ones(NTotal) * gtd0
VEL = [np.zeros(NTotal),np.zeros(NTotal),np.ones(NTotal)*7e8]
#----------------------
#----------------------
#-------------------
#SUBGRIDS DEFINITION
#-------------------
NFiles = len(files); CountFiles = np.arange(NFiles)
lenFiles = [len(file) for file in files]
dens_tmp = [[{},{}] for i in CountFiles]
temp_tmp = [{} for i in CountFiles]
vel_tmp = [[{} for i in CountFiles] for i in range(3)]
abund_tmp = [{} for i in CountFiles]
gtd_tmp = [{} for i in CountFiles]
hg=0
IDList = [[] for i in CountFiles]
Xgrid, Ygrid, Zgrid = GRID.XYZgrid
for m in range(NFiles):
for n in files[m]:
x,y,z = n[1], n[2], n[3]
i = mindistance(x,Xgrid,Nx)
j = mindistance(y,Ygrid,Ny)
k = mindistance(z,Zgrid,Nz)
Num = i*(Ny)*(Nz)+j*(Nz)+k; #ID for the Global Grid
#if Num in IDList[m]: #Really slow as the size of IDList increases
try:
dens_tmp[m][0][Num] += n[4]
dens_tmp[m][1][Num] += 1
temp_tmp[m][Num] += n[4] * n[5]
vel_tmp[0][m][Num] += n[4] * n[6]
vel_tmp[1][m][Num] += n[4] * n[7]
vel_tmp[2][m][Num] += n[4] * n[8]
abund_tmp[m][Num] += n[4] * n[9]
gtd_tmp[m][Num] += n[4] * n[10]
except KeyError:
#else:
dens_tmp[m][0][Num] = n[4]
dens_tmp[m][1][Num] = 1
temp_tmp[m][Num] = n[4] * n[5]
vel_tmp[0][m][Num] = n[4] * n[6]
vel_tmp[1][m][Num] = n[4] * n[7]
vel_tmp[2][m][Num] = n[4] * n[8]
abund_tmp[m][Num] = n[4] * n[9]
gtd_tmp[m][Num] = n[4] * n[10]
IDList[m].append(Num)
#hg+=1
#if hg%50000 == 0: print (hg)
print ('Finished merging for: %s'%names[m])
print ('Computing combined densities, temperatures, etc....')
for m in range(NFiles):
for ind in IDList[m]:
dens_tot = dens_tmp[m][0][ind]
temp_tmp[m][ind] = temp_tmp[m][ind] / dens_tot
abund_tmp[m][ind] = abund_tmp[m][ind] / dens_tot
gtd_tmp[m][ind]= gtd_tmp[m][ind] / dens_tot
vel_tmp[0][m][ind] = vel_tmp[0][m][ind] / dens_tot
vel_tmp[1][m][ind] = vel_tmp[1][m][ind] / dens_tot
vel_tmp[2][m][ind] = vel_tmp[2][m][ind] / dens_tot
dens_tmp[m][0][ind] = dens_tot / dens_tmp[m][1][ind]
#-------------------
#FOR THE GLOBAL GRID
#-------------------
dens_dum = dens_tmp[m][0][ind]
temp_dum = temp_tmp[m][ind]
vel0_dum = vel_tmp[0][m][ind]
vel1_dum = vel_tmp[1][m][ind]
vel2_dum = vel_tmp[2][m][ind]
abund_dum = abund_tmp[m][ind]
gtd_dum = gtd_tmp[m][ind]
DENS[ind] += dens_dum
TEMP[ind] += dens_dum * temp_dum
VEL[0][ind] += dens_dum * vel0_dum
VEL[1][ind] += dens_dum * vel1_dum
VEL[2][ind] += dens_dum * vel2_dum
ABUND[ind] += dens_dum * abund_dum
GTD[ind] += dens_dum * gtd_dum
TEMP = TEMP / DENS
ABUND = ABUND / DENS
GTD = GTD / DENS
VEL[0] = VEL[0] / DENS
VEL[1] = VEL[1] / DENS
VEL[2] = VEL[2] / DENS
VEL = Model.Struct( **{'x': VEL[0], 'y': VEL[1], 'z': VEL[2]})
ind = np.where(DENS == -1.0)
DENS[ind] = rho_min
ABUND[ind] = ab0 #?
GTD[ind] = gtd0 #?
DENS = np.where(DENS < rho_min, rho_min, DENS)
TEMP = np.where(TEMP == 0., T_min, TEMP)
if radmc3d: Model.Datatab_RADMC3D_FreeFree(DENS,TEMP,GRID)
else: Model.DataTab_LIME(DENS,TEMP,VEL,ABUND,GTD,GRID)
AllProp = Model.Struct( **{'GRID': GRID, 'density': DENS, 'temperature': TEMP, 'vel': VEL, 'abundance': ABUND, 'gtd': GTD})
print ('%s is done!'%func_name)
print ('Ellapsed time: %.3fs' % (time.time() - t0))
print ('-------------------------------------------------\n-------------------------------------------------')
return AllProp
| [
"numpy.ones",
"inspect.stack",
"numpy.where",
"numpy.zeros",
"os.popen",
"numpy.loadtxt",
"time.time",
"numpy.arange"
] | [((834, 845), 'time.time', 'time.time', ([], {}), '()\n', (843, 845), False, 'import time\n'), ((1781, 1797), 'numpy.zeros', 'np.zeros', (['NTotal'], {}), '(NTotal)\n', (1789, 1797), True, 'import numpy as np\n'), ((1853, 1869), 'numpy.zeros', 'np.zeros', (['NTotal'], {}), '(NTotal)\n', (1861, 1869), True, 'import numpy as np\n'), ((1920, 1936), 'numpy.zeros', 'np.zeros', (['NTotal'], {}), '(NTotal)\n', (1928, 1936), True, 'import numpy as np\n'), ((2181, 2198), 'numpy.arange', 'np.arange', (['NFiles'], {}), '(NFiles)\n', (2190, 2198), True, 'import numpy as np\n'), ((5470, 5492), 'numpy.where', 'np.where', (['(DENS == -1.0)'], {}), '(DENS == -1.0)\n', (5478, 5492), True, 'import numpy as np\n'), ((5575, 5614), 'numpy.where', 'np.where', (['(DENS < rho_min)', 'rho_min', 'DENS'], {}), '(DENS < rho_min, rho_min, DENS)\n', (5583, 5614), True, 'import numpy as np\n'), ((5631, 5665), 'numpy.where', 'np.where', (['(TEMP == 0.0)', 'T_min', 'TEMP'], {}), '(TEMP == 0.0, T_min, TEMP)\n', (5639, 5665), True, 'import numpy as np\n'), ((1714, 1729), 'numpy.ones', 'np.ones', (['NTotal'], {}), '(NTotal)\n', (1721, 1729), True, 'import numpy as np\n'), ((1973, 1989), 'numpy.zeros', 'np.zeros', (['NTotal'], {}), '(NTotal)\n', (1981, 1989), True, 'import numpy as np\n'), ((1990, 2006), 'numpy.zeros', 'np.zeros', (['NTotal'], {}), '(NTotal)\n', (1998, 2006), True, 'import numpy as np\n'), ((754, 769), 'inspect.stack', 'inspect.stack', ([], {}), '()\n', (767, 769), False, 'import inspect\n'), ((869, 910), 'os.popen', 'os.popen', (["('ls -1 %s*.dat| wc -l' % folder)"], {}), "('ls -1 %s*.dat| wc -l' % folder)\n", (877, 910), False, 'import os\n'), ((1094, 1110), 'numpy.loadtxt', 'np.loadtxt', (['name'], {}), '(name)\n', (1104, 1110), True, 'import numpy as np\n'), ((1264, 1280), 'numpy.loadtxt', 'np.loadtxt', (['name'], {}), '(name)\n', (1274, 1280), True, 'import numpy as np\n'), ((2007, 2022), 'numpy.ones', 'np.ones', (['NTotal'], {}), '(NTotal)\n', (2014, 2022), True, 'import numpy as np\n'), ((5991, 6002), 'time.time', 'time.time', ([], {}), '()\n', (6000, 6002), False, 'import time\n'), ((920, 954), 'os.popen', 'os.popen', (["('ls -1 %s*.dat' % folder)"], {}), "('ls -1 %s*.dat' % folder)\n", (928, 954), False, 'import os\n')] |
"""
Tests of Tax-Calculator using puf.csv input.
Note that the puf.csv file that is required to run this program has
been constructed by the Tax-Calculator development team by merging
information from the most recent publicly available IRS SOI PUF file
and from the Census CPS file for the corresponding year. If you have
acquired from IRS the most recent SOI PUF file and want to execute
this program, contact the Tax-Calculator development team to discuss
your options.
Read Tax-Calculator/TESTING.md for details.
"""
# CODING-STYLE CHECKS:
# pycodestyle test_pufcsv.py
# pylint --disable=locally-disabled test_pufcsv.py
import os
import json
import pytest
import numpy as np
import pandas as pd
# pylint: disable=import-error
from taxcalc import Policy, Records, Calculator
START_YEAR = 2017
@pytest.mark.requires_pufcsv
def test_agg(tests_path, puf_fullsample):
"""
Test Tax-Calculator aggregate taxes with no policy reform using
the full-sample puf.csv and a small sub-sample of puf.csv
"""
# pylint: disable=too-many-locals,too-many-statements
nyrs = 10
# create a baseline Policy object with current-law policy parameters
baseline_policy = Policy()
# create a Records object (rec) containing all puf.csv input records
recs = Records(data=puf_fullsample)
# create a Calculator object using baseline policy and puf records
calc = Calculator(policy=baseline_policy, records=recs)
calc.advance_to_year(START_YEAR)
calc_start_year = calc.current_year
# create aggregate diagnostic table (adt) as a Pandas DataFrame object
adt = calc.diagnostic_table(nyrs).round(1) # column labels are int
taxes_fullsample = adt.loc["Combined Liability ($b)"]
# compare actual DataFrame, adt, with the expected DataFrame, edt
aggres_path = os.path.join(tests_path, 'pufcsv_agg_expect.csv')
edt = pd.read_csv(aggres_path, index_col=False) # column labels are str
edt.drop('Unnamed: 0', axis='columns', inplace=True)
assert len(adt.columns.values) == len(edt.columns.values)
diffs = False
for icol in adt.columns.values:
if not np.allclose(adt[icol], edt[str(icol)]):
diffs = True
if diffs:
new_filename = '{}{}'.format(aggres_path[:-10], 'actual.csv')
adt.to_csv(new_filename, float_format='%.1f')
msg = 'PUFCSV AGG RESULTS DIFFER FOR FULL-SAMPLE\n'
msg += '-------------------------------------------------\n'
msg += '--- NEW RESULTS IN pufcsv_agg_actual.csv FILE ---\n'
msg += '--- if new OK, copy pufcsv_agg_actual.csv to ---\n'
msg += '--- pufcsv_agg_expect.csv ---\n'
msg += '--- and rerun test. ---\n'
msg += '--- (both are in taxcalc/tests) ---\n'
msg += '-------------------------------------------------\n'
raise ValueError(msg)
# create aggregate diagnostic table using unweighted sub-sample of records
fullsample = puf_fullsample
rn_seed = 2222 # to ensure sub-sample is always the same
subfrac = 0.05 # sub-sample fraction
subsample = fullsample.sample(frac=subfrac, random_state=rn_seed)
recs_subsample = Records(data=subsample)
calc_subsample = Calculator(policy=baseline_policy, records=recs_subsample)
calc_subsample.advance_to_year(START_YEAR)
adt_subsample = calc_subsample.diagnostic_table(nyrs)
# compare combined tax liability from full and sub samples for each year
taxes_subsample = adt_subsample.loc["Combined Liability ($b)"]
msg = ''
for cyr in range(calc_start_year, calc_start_year + nyrs):
reltol = 0.01 # maximum allowed relative difference in tax liability
if not np.allclose(taxes_subsample[cyr], taxes_fullsample[cyr],
atol=0.0, rtol=reltol):
reldiff = (taxes_subsample[cyr] / taxes_fullsample[cyr]) - 1.
line1 = '\nPUFCSV AGG SUB-vs-FULL RESULTS DIFFER IN {}'
line2 = '\n when subfrac={:.3f}, rtol={:.4f}, seed={}'
line3 = '\n with sub={:.3f}, full={:.3f}, rdiff={:.4f}'
msg += line1.format(cyr)
msg += line2.format(subfrac, reltol, rn_seed)
msg += line3.format(taxes_subsample[cyr],
taxes_fullsample[cyr],
reldiff)
if msg:
raise ValueError(msg)
MTR_TAX_YEAR = 2013
MTR_NEG_DIFF = False # set True to subtract (rather than add) small amount
# specify payrolltax mtr histogram bin boundaries (or edges):
PTAX_MTR_BIN_EDGES = [0.0, 0.02, 0.04, 0.06, 0.08,
0.10, 0.12, 0.14, 0.16, 0.18, 1.0]
# the bin boundaries above are arbitrary, so users
# may want to experiment with alternative boundaries
# specify incometax mtr histogram bin boundaries (or edges):
ITAX_MTR_BIN_EDGES = [-1.0, -0.30, -0.20, -0.10, 0.0,
0.10, 0.20, 0.30, 0.40, 0.50, 1.0]
# the bin boundaries above are arbitrary, so users
# may want to experiment with alternative boundaries
def mtr_bin_counts(mtr_data, bin_edges, recid):
"""
Compute mtr histogram bin counts and return results as a string.
"""
res = ''
(bincount, _) = np.histogram(mtr_data.round(decimals=4), bins=bin_edges)
sum_bincount = np.sum(bincount)
res += '{} :'.format(sum_bincount)
for idx in range(len(bin_edges) - 1):
res += ' {:6d}'.format(bincount[idx])
res += '\n'
if sum_bincount < mtr_data.size:
res += 'WARNING: sum of bin counts is too low\n'
recinfo = ' mtr={:.2f} for recid={}\n'
mtr_min = mtr_data.min()
mtr_max = mtr_data.max()
bin_min = min(bin_edges)
bin_max = max(bin_edges)
if mtr_min < bin_min:
res += ' min(mtr)={:.2f}\n'.format(mtr_min)
for idx in range(mtr_data.size):
if mtr_data[idx] < bin_min:
res += recinfo.format(mtr_data[idx], recid[idx])
if mtr_max > bin_max:
res += ' max(mtr)={:.2f}\n'.format(mtr_max)
for idx in range(mtr_data.size):
if mtr_data[idx] > bin_max:
res += recinfo.format(mtr_data[idx], recid[idx])
return res
def nonsmall_diffs(linelist1, linelist2, small=0.0):
"""
Return True if line lists differ significantly; otherwise return False.
Significant numerical difference means one or more numbers differ (between
linelist1 and linelist2) by more than the specified small amount.
"""
# embedded function used only in nonsmall_diffs function
def isfloat(value):
"""
Return True if value can be cast to float; otherwise return False.
"""
try:
float(value)
return True
except ValueError:
return False
# begin nonsmall_diffs logic
assert isinstance(linelist1, list)
assert isinstance(linelist2, list)
if len(linelist1) != len(linelist2):
return True
assert 0.0 <= small <= 1.0
epsilon = 1e-6
smallamt = small + epsilon
for line1, line2 in zip(linelist1, linelist2):
if line1 == line2:
continue
else:
tokens1 = line1.replace(',', '').split()
tokens2 = line2.replace(',', '').split()
for tok1, tok2 in zip(tokens1, tokens2):
tok1_isfloat = isfloat(tok1)
tok2_isfloat = isfloat(tok2)
if tok1_isfloat and tok2_isfloat:
if abs(float(tok1) - float(tok2)) <= smallamt:
continue
else:
return True
elif not tok1_isfloat and not tok2_isfloat:
if tok1 == tok2:
continue
else:
return True
else:
return True
return False
@pytest.mark.requires_pufcsv
def test_mtr(tests_path, puf_path):
"""
Test Tax-Calculator marginal tax rates with no policy reform using puf.csv
Compute histograms for each marginal tax rate income type using
sample input from the puf.csv file and writing output to a string,
which is then compared for differences with EXPECTED_MTR_RESULTS.
"""
# pylint: disable=too-many-locals,too-many-statements
assert len(PTAX_MTR_BIN_EDGES) == len(ITAX_MTR_BIN_EDGES)
# construct actual results string, res
res = ''
if MTR_NEG_DIFF:
res += 'MTR computed using NEGATIVE finite_diff '
else:
res += 'MTR computed using POSITIVE finite_diff '
res += 'for tax year {}\n'.format(MTR_TAX_YEAR)
# create a Policy object (clp) containing current-law policy parameters
clp = Policy()
clp.set_year(MTR_TAX_YEAR)
# create a Records object (puf) containing puf.csv input records
puf = Records(data=puf_path)
recid = puf.RECID # pylint: disable=no-member
# create a Calculator object using clp policy and puf records
calc = Calculator(policy=clp, records=puf)
res += '{} = {}\n'.format('Total number of data records', puf.array_length)
res += 'PTAX mtr histogram bin edges:\n'
res += ' {}\n'.format(PTAX_MTR_BIN_EDGES)
res += 'ITAX mtr histogram bin edges:\n'
res += ' {}\n'.format(ITAX_MTR_BIN_EDGES)
variable_header = 'PTAX and ITAX mtr histogram bin counts for'
# compute marginal tax rate (mtr) histograms for each mtr variable
for var_str in Calculator.MTR_VALID_VARIABLES:
zero_out = (var_str == 'e01400')
(mtr_ptax, mtr_itax, _) = calc.mtr(variable_str=var_str,
negative_finite_diff=MTR_NEG_DIFF,
zero_out_calculated_vars=zero_out,
wrt_full_compensation=False)
if zero_out:
# check that calculated variables are consistent
assert np.allclose((calc.array('iitax') +
calc.array('payrolltax')),
calc.array('combined'))
assert np.allclose((calc.array('ptax_was') +
calc.array('setax') +
calc.array('ptax_amc')),
calc.array('payrolltax'))
assert np.allclose(calc.array('c21060') - calc.array('c21040'),
calc.array('c04470'))
assert np.allclose(calc.array('taxbc') + calc.array('c09600'),
calc.array('c05800'))
assert np.allclose((calc.array('c05800') +
calc.array('othertaxes') -
calc.array('c07100')),
calc.array('c09200'))
assert np.allclose(calc.array('c09200') - calc.array('refund'),
calc.array('iitax'))
if var_str == 'e00200s':
# only MARS==2 filing units have valid MTR values
mtr_ptax = mtr_ptax[calc.array('MARS') == 2]
mtr_itax = mtr_itax[calc.array('MARS') == 2]
res += '{} {}:\n'.format(variable_header, var_str)
res += mtr_bin_counts(mtr_ptax, PTAX_MTR_BIN_EDGES, recid)
res += mtr_bin_counts(mtr_itax, ITAX_MTR_BIN_EDGES, recid)
# check for differences between actual and expected results
mtrres_path = os.path.join(tests_path, 'pufcsv_mtr_expect.txt')
with open(mtrres_path, 'r') as expected_file:
txt = expected_file.read()
expected_results = txt.rstrip('\n\t ') + '\n' # cleanup end of file txt
if nonsmall_diffs(res.splitlines(True), expected_results.splitlines(True)):
new_filename = '{}{}'.format(mtrres_path[:-10], 'actual.txt')
with open(new_filename, 'w') as new_file:
new_file.write(res)
msg = 'PUFCSV MTR RESULTS DIFFER\n'
msg += '-------------------------------------------------\n'
msg += '--- NEW RESULTS IN pufcsv_mtr_actual.txt FILE ---\n'
msg += '--- if new OK, copy pufcsv_mtr_actual.txt to ---\n'
msg += '--- pufcsv_mtr_expect.txt ---\n'
msg += '--- and rerun test. ---\n'
msg += '-------------------------------------------------\n'
raise ValueError(msg)
@pytest.mark.requires_pufcsv
def test_mtr_pt_active(puf_subsample):
"""
Test whether including wages in active income causes
MTRs on e00900p and e26270 to be less than -1 (i.e., -100%)
"""
# pylint: disable=too-many-locals
rec = Records(data=puf_subsample)
reform_year = 2018
# create current-law Calculator object, calc1
pol1 = Policy()
calc1 = Calculator(policy=pol1, records=rec)
calc1.advance_to_year(reform_year)
calc1.calc_all()
mtr1_e00900p = calc1.mtr('e00900p')[2]
mtr1_e26270 = calc1.mtr('e26270')[2]
assert min(mtr1_e00900p) > -1
assert min(mtr1_e26270) > -1
# change PT rates, calc2
reform2 = {'PT_rt7': {reform_year: 0.35}}
pol2 = Policy()
pol2.implement_reform(reform2)
calc2 = Calculator(policy=pol2, records=rec)
calc2.advance_to_year(reform_year)
calc2.calc_all()
mtr2_e00900p = calc2.mtr('e00900p')[2]
mtr2_e26270 = calc2.mtr('e26270')[2]
assert min(mtr2_e00900p) > -1
assert min(mtr2_e26270) > -1
# change PT_wages_active_income
reform3 = {'PT_wages_active_income': {reform_year: True}}
pol3 = Policy()
pol3.implement_reform(reform3)
calc3 = Calculator(policy=pol3, records=rec)
calc3.advance_to_year(reform_year)
calc3.calc_all()
mtr3_e00900p = calc3.mtr('e00900p')[2]
mtr3_e26270 = calc3.mtr('e26270')[2]
assert min(mtr3_e00900p) > -1
assert min(mtr3_e26270) > -1
# change PT rates and PT_wages_active_income
reform4 = {
'PT_wages_active_income': {reform_year: True},
'PT_rt7': {reform_year: 0.35}
}
pol4 = Policy()
pol4.implement_reform(reform4)
calc4 = Calculator(policy=pol4, records=rec)
calc4.advance_to_year(reform_year)
calc4.calc_all()
mtr4_e00900p = calc4.mtr('e00900p')[2]
mtr4_e26270 = calc4.mtr('e26270')[2]
assert min(mtr4_e00900p) > -1
assert min(mtr4_e26270) > -1
@pytest.mark.requires_pufcsv
def test_credit_reforms(puf_subsample):
"""
Test personal credit reforms using puf.csv subsample
"""
rec = Records(data=puf_subsample)
reform_year = 2017
# create current-law Calculator object, calc1
pol = Policy()
calc1 = Calculator(policy=pol, records=rec)
calc1.advance_to_year(reform_year)
calc1.calc_all()
itax1 = calc1.weighted_total('iitax')
# create personal-refundable-credit-reform Calculator object, calc2
reform = {'II_credit': {reform_year: [1000, 1000, 1000, 1000, 1000]}}
pol.implement_reform(reform)
calc2 = Calculator(policy=pol, records=rec)
calc2.advance_to_year(reform_year)
calc2.calc_all()
itax2 = calc2.weighted_total('iitax')
# create personal-nonrefundable-credit-reform Calculator object, calc3
reform = {'II_credit_nr': {reform_year: [1000, 1000, 1000, 1000, 1000]}}
pol = Policy()
pol.implement_reform(reform)
calc3 = Calculator(policy=pol, records=rec)
calc3.advance_to_year(reform_year)
calc3.calc_all()
itax3 = calc3.weighted_total('iitax')
# check income tax revenues generated by the three Calculator objects
assert itax2 < itax1 # because refundable credits lower revenues
assert itax3 > itax2 # because nonrefundable credits lower revenues less
assert itax3 < itax1 # because nonrefundable credits lower revenues some
@pytest.mark.requires_pufcsv
def test_puf_availability(tests_path, puf_path):
"""
Cross-check records_variables.json data with variables in puf.csv file
"""
# make set of variable names in puf.csv file
pufdf = pd.read_csv(puf_path)
pufvars = set(list(pufdf))
# make set of variable names that are marked as puf.csv available
rvpath = os.path.join(tests_path, '..', 'records_variables.json')
with open(rvpath, 'r') as rvfile:
rvdict = json.load(rvfile)
recvars = set()
for vname, vdict in rvdict['read'].items():
if 'taxdata_puf' in vdict.get('availability', ''):
recvars.add(vname)
# check that pufvars and recvars sets are the same
assert (pufvars - recvars) == set()
assert (recvars - pufvars) == set()
| [
"taxcalc.Records",
"taxcalc.Calculator",
"numpy.allclose",
"pandas.read_csv",
"os.path.join",
"numpy.sum",
"json.load",
"taxcalc.Policy"
] | [((1187, 1195), 'taxcalc.Policy', 'Policy', ([], {}), '()\n', (1193, 1195), False, 'from taxcalc import Policy, Records, Calculator\n'), ((1280, 1308), 'taxcalc.Records', 'Records', ([], {'data': 'puf_fullsample'}), '(data=puf_fullsample)\n', (1287, 1308), False, 'from taxcalc import Policy, Records, Calculator\n'), ((1391, 1439), 'taxcalc.Calculator', 'Calculator', ([], {'policy': 'baseline_policy', 'records': 'recs'}), '(policy=baseline_policy, records=recs)\n', (1401, 1439), False, 'from taxcalc import Policy, Records, Calculator\n'), ((1810, 1859), 'os.path.join', 'os.path.join', (['tests_path', '"""pufcsv_agg_expect.csv"""'], {}), "(tests_path, 'pufcsv_agg_expect.csv')\n", (1822, 1859), False, 'import os\n'), ((1870, 1911), 'pandas.read_csv', 'pd.read_csv', (['aggres_path'], {'index_col': '(False)'}), '(aggres_path, index_col=False)\n', (1881, 1911), True, 'import pandas as pd\n'), ((3207, 3230), 'taxcalc.Records', 'Records', ([], {'data': 'subsample'}), '(data=subsample)\n', (3214, 3230), False, 'from taxcalc import Policy, Records, Calculator\n'), ((3252, 3310), 'taxcalc.Calculator', 'Calculator', ([], {'policy': 'baseline_policy', 'records': 'recs_subsample'}), '(policy=baseline_policy, records=recs_subsample)\n', (3262, 3310), False, 'from taxcalc import Policy, Records, Calculator\n'), ((5323, 5339), 'numpy.sum', 'np.sum', (['bincount'], {}), '(bincount)\n', (5329, 5339), True, 'import numpy as np\n'), ((8804, 8812), 'taxcalc.Policy', 'Policy', ([], {}), '()\n', (8810, 8812), False, 'from taxcalc import Policy, Records, Calculator\n'), ((8923, 8945), 'taxcalc.Records', 'Records', ([], {'data': 'puf_path'}), '(data=puf_path)\n', (8930, 8945), False, 'from taxcalc import Policy, Records, Calculator\n'), ((9074, 9109), 'taxcalc.Calculator', 'Calculator', ([], {'policy': 'clp', 'records': 'puf'}), '(policy=clp, records=puf)\n', (9084, 9109), False, 'from taxcalc import Policy, Records, Calculator\n'), ((11469, 11518), 'os.path.join', 'os.path.join', (['tests_path', '"""pufcsv_mtr_expect.txt"""'], {}), "(tests_path, 'pufcsv_mtr_expect.txt')\n", (11481, 11518), False, 'import os\n'), ((12656, 12683), 'taxcalc.Records', 'Records', ([], {'data': 'puf_subsample'}), '(data=puf_subsample)\n', (12663, 12683), False, 'from taxcalc import Policy, Records, Calculator\n'), ((12768, 12776), 'taxcalc.Policy', 'Policy', ([], {}), '()\n', (12774, 12776), False, 'from taxcalc import Policy, Records, Calculator\n'), ((12789, 12825), 'taxcalc.Calculator', 'Calculator', ([], {'policy': 'pol1', 'records': 'rec'}), '(policy=pol1, records=rec)\n', (12799, 12825), False, 'from taxcalc import Policy, Records, Calculator\n'), ((13123, 13131), 'taxcalc.Policy', 'Policy', ([], {}), '()\n', (13129, 13131), False, 'from taxcalc import Policy, Records, Calculator\n'), ((13179, 13215), 'taxcalc.Calculator', 'Calculator', ([], {'policy': 'pol2', 'records': 'rec'}), '(policy=pol2, records=rec)\n', (13189, 13215), False, 'from taxcalc import Policy, Records, Calculator\n'), ((13536, 13544), 'taxcalc.Policy', 'Policy', ([], {}), '()\n', (13542, 13544), False, 'from taxcalc import Policy, Records, Calculator\n'), ((13592, 13628), 'taxcalc.Calculator', 'Calculator', ([], {'policy': 'pol3', 'records': 'rec'}), '(policy=pol3, records=rec)\n', (13602, 13628), False, 'from taxcalc import Policy, Records, Calculator\n'), ((14015, 14023), 'taxcalc.Policy', 'Policy', ([], {}), '()\n', (14021, 14023), False, 'from taxcalc import Policy, Records, Calculator\n'), ((14071, 14107), 'taxcalc.Calculator', 'Calculator', ([], {'policy': 'pol4', 'records': 'rec'}), '(policy=pol4, records=rec)\n', (14081, 14107), False, 'from taxcalc import Policy, Records, Calculator\n'), ((14473, 14500), 'taxcalc.Records', 'Records', ([], {'data': 'puf_subsample'}), '(data=puf_subsample)\n', (14480, 14500), False, 'from taxcalc import Policy, Records, Calculator\n'), ((14584, 14592), 'taxcalc.Policy', 'Policy', ([], {}), '()\n', (14590, 14592), False, 'from taxcalc import Policy, Records, Calculator\n'), ((14605, 14640), 'taxcalc.Calculator', 'Calculator', ([], {'policy': 'pol', 'records': 'rec'}), '(policy=pol, records=rec)\n', (14615, 14640), False, 'from taxcalc import Policy, Records, Calculator\n'), ((14934, 14969), 'taxcalc.Calculator', 'Calculator', ([], {'policy': 'pol', 'records': 'rec'}), '(policy=pol, records=rec)\n', (14944, 14969), False, 'from taxcalc import Policy, Records, Calculator\n'), ((15234, 15242), 'taxcalc.Policy', 'Policy', ([], {}), '()\n', (15240, 15242), False, 'from taxcalc import Policy, Records, Calculator\n'), ((15288, 15323), 'taxcalc.Calculator', 'Calculator', ([], {'policy': 'pol', 'records': 'rec'}), '(policy=pol, records=rec)\n', (15298, 15323), False, 'from taxcalc import Policy, Records, Calculator\n'), ((15958, 15979), 'pandas.read_csv', 'pd.read_csv', (['puf_path'], {}), '(puf_path)\n', (15969, 15979), True, 'import pandas as pd\n'), ((16094, 16150), 'os.path.join', 'os.path.join', (['tests_path', '""".."""', '"""records_variables.json"""'], {}), "(tests_path, '..', 'records_variables.json')\n", (16106, 16150), False, 'import os\n'), ((16206, 16223), 'json.load', 'json.load', (['rvfile'], {}), '(rvfile)\n', (16215, 16223), False, 'import json\n'), ((3729, 3808), 'numpy.allclose', 'np.allclose', (['taxes_subsample[cyr]', 'taxes_fullsample[cyr]'], {'atol': '(0.0)', 'rtol': 'reltol'}), '(taxes_subsample[cyr], taxes_fullsample[cyr], atol=0.0, rtol=reltol)\n', (3740, 3808), True, 'import numpy as np\n')] |
import sys
import traceback
import numpy as np
from shapely import geometry as g
import multiprocessing as mp
from . import abCellSize
from . import abUtils
class abLongBreakWaterLocAlphaAdjust:
def __init__(self, cell, neighbors, coastPolygons, directions, alphas, betas):
self.cell = cell
self.neighbors = [c for c in neighbors if c != cell]
totPoly = cell
for cl in self.neighbors:
totPoly = totPoly.union(cl)
if totPoly.__class__ != g.Polygon:
# totPoly = totPoly.convex_hull
totPoly = None
self.totPoly = totPoly
self.isBoundaryCell = totPoly.boundary.intersects(cell.boundary) if (totPoly != None) else True
self.coastPolygons = [g.Polygon(p) for p in coastPolygons]
self.directions = directions
self.alphas = np.array(alphas)
self.betas = np.array(betas)
self.thresholdNInts = 3
clSz = abCellSize.abCellSize(cell)
self.minObstSizeKm = clSz.computeSizesKm([clSz.majorAxisDir])[0]*2.
def _countIntersectNeighbors(self, coastPoly):
cnt = 0
for nc in self.neighbors:
if coastPoly.intersects(nc):
cnt += 1
return cnt
def reviewLocalAlpha(self):
alphas = self.alphas
betas = self.betas
if (not self.isBoundaryCell) and (self.totPoly != None):
dirs = self.directions
newalphas = np.ones(alphas.shape)
newbetas = np.ones(betas.shape)
for cstPoly in self.coastPolygons:
# breakwater must intersect the cell
cints = cstPoly.intersection(self.cell)
if abUtils.greater(cints.area, 0):
# the breakwater must cross at least two sides of the cell
boundaryIntersect = cints.boundary.intersection(self.cell.boundary)
if boundaryIntersect.__class__ is g.MultiLineString:
# the number of intersected cells of the neighborhood must be >= 3
nints = self._countIntersectNeighbors(cstPoly) + 1
plSz = abCellSize.abCellSize(cstPoly)
cstPolySizeKm = plSz.computeSizesKm([plSz.majorAxisDir])[0]
if nints >= self.thresholdNInts and cstPolySizeKm > self.minObstSizeKm:
cstSection = cstPoly.intersection(self.totPoly)
if not cstSection.__class__ is g.Polygon:
# skipping strange case
return alphas, betas
clSz = abCellSize.abCellSize(cstSection)
avgCoastDir = clSz.majorAxisDir
for idr in range(len(dirs)):
dr, alpha, beta = dirs[idr], alphas[:, idr], betas[:, idr]
drDelta = np.abs(abUtils.angleDiff(avgCoastDir, dr))
if drDelta > np.pi/2.:
drDelta = np.pi - drDelta
coeff = 1. - drDelta/(np.pi/2.)
assert 0. <= coeff <= 1.
nalpha = alpha*coeff
nbeta = beta*coeff
newalphas[:, idr] = nalpha
newbetas[:, idr] = nbeta
# assuming a maximum one breakwater per cell
return newalphas, newbetas
return alphas, betas
class abLongBreakWaterLocAlphaAdjustAllCells:
def __init__(self, obstrCells, grid, coastPolygons, directions, alphas, betas, parallel = True, nParallelWorker = 4, verbose = True):
self.obstrCells = obstrCells
self.grid = grid
self.coastPolygons = coastPolygons
self.directions = directions
self.alphas = alphas
self.betas = betas
self.parallel = parallel
self.nParallelWorker = nParallelWorker
if parallel and (nParallelWorker > 1):
self.reviewLocalAlpha = self._reviewLocalAlphaParallel
else:
self.reviewLocalAlpha = self._reviewLocalAlphaSerial
self.verbose = verbose
def _progress(self, progPercentage):
if self.verbose:
sys.stdout.write('\r progress: {p:2.0f} %'.format(p = progPercentage))
sys.stdout.flush()
def _reviewLocalAlphaSerial(self):
#loop on all the cells, istantiate abLongBreakWaterAdjust and invoke reviewAlpha
global grid, coastPolygons, directions
grid = self.grid
coastPolygons = self.coastPolygons
directions = self.directions
obstrCells = self.obstrCells
newAlphas, newBetas = [], []
ncell = len(obstrCells)
adjAlphaGenerator = map(_elabOneCell, zip(obstrCells, self.alphas, self.betas, range(len(obstrCells))))
for cell, adjAlpha, adjBeta, icell in adjAlphaGenerator:
newAlphas.append(adjAlpha)
newBetas.append(adjBeta)
if icell % 10 == 0:
progPerc = (float(icell)/ncell)*100
self._progress(progPerc)
return newAlphas, newBetas
def _reviewLocalAlphaParallel(self):
#loop on all the cells, istantiate abLongBreakWaterAdjust and invoke reviewAlpha
global grid, coastPolygons, directions
grid = self.grid
coastPolygons = self.coastPolygons
directions = self.directions
obstrCells = self.obstrCells
newAlphas, newBetas = [], []
ncell = len(obstrCells)
p = mp.Pool(self.nParallelWorker)
adjAlphaGenerator = p.imap(_elabOneCell, zip(obstrCells, self.alphas, self.betas, range(len(obstrCells))))
for cell, adjAlpha, adjBeta, icell in adjAlphaGenerator:
newAlphas.append(adjAlpha)
newBetas.append(adjBeta)
if icell % 10 == 0:
progPerc = (float(icell)/ncell)*100
self._progress(progPerc)
p.close()
return newAlphas, newBetas
def _elabOneCell(cellAlphaObj):
try:
cell, alphas, betas, icell = cellAlphaObj
neighbors = grid.getNeighbors(cell)
bwadj = abLongBreakWaterLocAlphaAdjust(cell, neighbors, coastPolygons, directions, alphas, betas)
adjAlphas, adjBetas = bwadj.reviewLocalAlpha()
return cell, adjAlphas, adjBetas, icell
except:
raise abUtils.abException("".join(traceback.format_exception(*sys.exc_info())))
| [
"numpy.ones",
"numpy.array",
"shapely.geometry.Polygon",
"sys.exc_info",
"multiprocessing.Pool",
"sys.stdout.flush"
] | [((783, 799), 'numpy.array', 'np.array', (['alphas'], {}), '(alphas)\n', (791, 799), True, 'import numpy as np\n'), ((817, 832), 'numpy.array', 'np.array', (['betas'], {}), '(betas)\n', (825, 832), True, 'import numpy as np\n'), ((4959, 4988), 'multiprocessing.Pool', 'mp.Pool', (['self.nParallelWorker'], {}), '(self.nParallelWorker)\n', (4966, 4988), True, 'import multiprocessing as mp\n'), ((695, 707), 'shapely.geometry.Polygon', 'g.Polygon', (['p'], {}), '(p)\n', (704, 707), True, 'from shapely import geometry as g\n'), ((1320, 1341), 'numpy.ones', 'np.ones', (['alphas.shape'], {}), '(alphas.shape)\n', (1327, 1341), True, 'import numpy as np\n'), ((1359, 1379), 'numpy.ones', 'np.ones', (['betas.shape'], {}), '(betas.shape)\n', (1366, 1379), True, 'import numpy as np\n'), ((3852, 3870), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (3868, 3870), False, 'import sys\n'), ((5775, 5789), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (5787, 5789), False, 'import sys\n')] |
import gym
import numpy as np
import tensorflow as tf
import time
from actor_critic import RandomActorCritic
from common.multiprocessing_env import SubprocVecEnv
from common.model import NetworkBase, model_play_games
from environment_model.network import EMBuilder
from tqdm import tqdm
class EnvironmentModel(NetworkBase):
def __init__(self, sess, em_arch, ob_space, ac_space, loss_fn='mse', lr=7e-4,
obs_coeff=1.0, rew_coeff=1.0, summarize=False):
self.sess = sess
self.nact = ac_space.n
nw, nh, nc = ob_space
# Setup targets
self.target_obs = tf.placeholder(tf.float32, [None, nw, nh, nc], name='target_observations')
self.target_rew = tf.placeholder(tf.float32, [None], name='target_rewards')
# Setup the Graph for the Environment Model
self.model = EMBuilder(sess, em_arch, ob_space, ac_space)
# Compute the losses (defaults to MSE)
if loss_fn is 'ent':
self.obs_loss = tf.losses.softmax_cross_entropy(self.target_obs, self.model.pred_obs)
self.rew_loss = tf.losses.softmax_cross_entropy(self.target_rew, self.model.pred_rew)
else:
self.obs_loss = tf.reduce_mean(tf.square(self.target_obs - self.model.pred_obs) / 2.0)
self.rew_loss = tf.reduce_mean(tf.square(self.target_rew - self.model.pred_rew) / 2.0)
self.loss = (obs_coeff*self.obs_loss) + (rew_coeff*self.rew_loss)
# Find the model parameters
with tf.variable_scope('env_model'):
self.params = tf.trainable_variables()
grads = tf.gradients(self.loss, self.params)
grads = list(zip(grads, self.params))
# Setup the optimizer
# trainer = tf.train.AdamOptimizer(learning_rate=lr)
trainer = tf.train.RMSPropOptimizer(learning_rate=lr, decay=0.99, epsilon=1e-5)
self.opt = trainer.apply_gradients(grads)
if summarize:
tf.summary.scalar('Loss', self.loss)
tf.summary.scalar('Observation Loss', self.obs_loss)
tf.summary.scalar('Reward Loss', self.rew_loss)
self.saver = tf.train.Saver(self.params, max_to_keep=5000000)
# Single training step
def train(self, obs, actions, tar_obs, tar_rew, summary_op=None):
feed_dict = {
self.model.obs: obs,
self.model.a: actions,
self.target_obs: tar_obs,
self.target_rew: tar_rew,
}
ret_vals = [
self.loss,
self.obs_loss,
self.rew_loss,
self.opt,
]
if summary_op is not None:
ret_vals.append(summary_op)
return self.sess.run(ret_vals, feed_dict=feed_dict)
# Given an observation and an action, return the predicted next observation and reward
def predict(self, obs, a):
return self.model.predict(obs, a)
def train(env_fn = None,
spectrum = False,
em_arch = None,
a2c_arch = None,
nenvs = 16,
nsteps = 100,
max_iters = 1e6,
obs_coeff = 0.5,
rew_coeff = 0.5,
lr = 7e-4,
loss = 'mse',
log_interval = 100,
summarize = True,
em_load_path = None,
a2c_load_path = None,
log_path = None,
cpu_cores = 1):
# Construct the vectorized parallel environments
envs = [ env_fn for _ in range(nenvs) ]
envs = SubprocVecEnv(envs)
# Set some random seeds for the environment
envs.seed(0)
if spectrum:
envs.spectrum()
ob_space = envs.observation_space.shape
nw, nh, nc = ob_space
ac_space = envs.action_space
obs = envs.reset()
tf_config = tf.ConfigProto(
inter_op_parallelism_threads=cpu_cores,
intra_op_parallelism_threads=cpu_cores )
tf_config.gpu_options.allow_growth = True
with tf.Session(config=tf_config) as sess:
# Setup the Actor Critic
actor_critic = RandomActorCritic(sess, a2c_arch, ob_space, ac_space)
if a2c_load_path is not None:
actor_critic.load(a2c_load_path)
with open(logpath+'/a2c_load_path', 'w') as outfile:
outfile.write(a2c_load_path)
print('Loaded Actor Critic Weights')
else:
actor_critic.epsilon = -1
print('WARNING: No Actor Critic Model loaded. Using Random Agent')
# Setup the Environment Model
env_model = EnvironmentModel(sess, em_arch, ob_space, ac_space, loss,
lr, obs_coeff, rew_coeff, summarize)
load_count = 0
if em_load_path is not None:
env_model.load(em_load_path)
summary_op = tf.summary.merge_all()
writer = tf.summary.FileWriter(log_path, graph=sess.graph)
sess.run(tf.global_variables_initializer())
print('Env Model Training Start!')
print('Model will be saved on intervals of %i' % (log_interval))
for i in tqdm(range(load_count + 1, int(max_iters)+1), ascii=True, desc='EnvironmentModel'):
mb_s, mb_a, mb_r, mb_ns, mb_d = [], [], [], [], []
for s, a, r, ns, d in model_play_games(actor_critic, envs, nsteps):
mb_s.append(s)
mb_a.append(a)
mb_r.append(r)
mb_ns.append(ns)
mb_d.append(d)
mb_s = np.concatenate(mb_s)
mb_a = np.concatenate(mb_a)
mb_r = np.concatenate(mb_r)
mb_ns= np.concatenate(mb_ns)
mb_d = np.concatenate(mb_d)
if summarize:
loss, obs_loss, rew_loss, _, smy = env_model.train(mb_s, mb_a, mb_ns, mb_r, summary_op)
writer.add_summary(smy, i)
else:
loss, obs_loss, rew_loss, _ = env_model.train(mb_s, mb_a, mb_ns, mb_r)
if i % log_interval == 0:
env_model.save(log_path, i)
env_model.save(log_path, 'final')
print('Environment Model is finished training')
| [
"environment_model.network.EMBuilder",
"tensorflow.gradients",
"common.model.model_play_games",
"tensorflow.placeholder",
"common.multiprocessing_env.SubprocVecEnv",
"tensorflow.Session",
"numpy.concatenate",
"tensorflow.square",
"tensorflow.ConfigProto",
"tensorflow.summary.scalar",
"tensorflow... | [((3561, 3580), 'common.multiprocessing_env.SubprocVecEnv', 'SubprocVecEnv', (['envs'], {}), '(envs)\n', (3574, 3580), False, 'from common.multiprocessing_env import SubprocVecEnv\n'), ((3837, 3935), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'inter_op_parallelism_threads': 'cpu_cores', 'intra_op_parallelism_threads': 'cpu_cores'}), '(inter_op_parallelism_threads=cpu_cores,\n intra_op_parallelism_threads=cpu_cores)\n', (3851, 3935), True, 'import tensorflow as tf\n'), ((622, 696), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None, nw, nh, nc]'], {'name': '"""target_observations"""'}), "(tf.float32, [None, nw, nh, nc], name='target_observations')\n", (636, 696), True, 'import tensorflow as tf\n'), ((723, 780), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '[None]'], {'name': '"""target_rewards"""'}), "(tf.float32, [None], name='target_rewards')\n", (737, 780), True, 'import tensorflow as tf\n'), ((855, 899), 'environment_model.network.EMBuilder', 'EMBuilder', (['sess', 'em_arch', 'ob_space', 'ac_space'], {}), '(sess, em_arch, ob_space, ac_space)\n', (864, 899), False, 'from environment_model.network import EMBuilder\n'), ((1617, 1653), 'tensorflow.gradients', 'tf.gradients', (['self.loss', 'self.params'], {}), '(self.loss, self.params)\n', (1629, 1653), True, 'import tensorflow as tf\n'), ((1810, 1880), 'tensorflow.train.RMSPropOptimizer', 'tf.train.RMSPropOptimizer', ([], {'learning_rate': 'lr', 'decay': '(0.99)', 'epsilon': '(1e-05)'}), '(learning_rate=lr, decay=0.99, epsilon=1e-05)\n', (1835, 1880), True, 'import tensorflow as tf\n'), ((2149, 2197), 'tensorflow.train.Saver', 'tf.train.Saver', (['self.params'], {'max_to_keep': '(5000000)'}), '(self.params, max_to_keep=5000000)\n', (2163, 2197), True, 'import tensorflow as tf\n'), ((4006, 4034), 'tensorflow.Session', 'tf.Session', ([], {'config': 'tf_config'}), '(config=tf_config)\n', (4016, 4034), True, 'import tensorflow as tf\n'), ((4102, 4155), 'actor_critic.RandomActorCritic', 'RandomActorCritic', (['sess', 'a2c_arch', 'ob_space', 'ac_space'], {}), '(sess, a2c_arch, ob_space, ac_space)\n', (4119, 4155), False, 'from actor_critic import RandomActorCritic\n'), ((4845, 4867), 'tensorflow.summary.merge_all', 'tf.summary.merge_all', ([], {}), '()\n', (4865, 4867), True, 'import tensorflow as tf\n'), ((4885, 4934), 'tensorflow.summary.FileWriter', 'tf.summary.FileWriter', (['log_path'], {'graph': 'sess.graph'}), '(log_path, graph=sess.graph)\n', (4906, 4934), True, 'import tensorflow as tf\n'), ((1014, 1083), 'tensorflow.losses.softmax_cross_entropy', 'tf.losses.softmax_cross_entropy', (['self.target_obs', 'self.model.pred_obs'], {}), '(self.target_obs, self.model.pred_obs)\n', (1045, 1083), True, 'import tensorflow as tf\n'), ((1112, 1181), 'tensorflow.losses.softmax_cross_entropy', 'tf.losses.softmax_cross_entropy', (['self.target_rew', 'self.model.pred_rew'], {}), '(self.target_rew, self.model.pred_rew)\n', (1143, 1181), True, 'import tensorflow as tf\n'), ((1518, 1548), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""env_model"""'], {}), "('env_model')\n", (1535, 1548), True, 'import tensorflow as tf\n'), ((1576, 1600), 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), '()\n', (1598, 1600), True, 'import tensorflow as tf\n'), ((1965, 2001), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""Loss"""', 'self.loss'], {}), "('Loss', self.loss)\n", (1982, 2001), True, 'import tensorflow as tf\n'), ((2014, 2066), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""Observation Loss"""', 'self.obs_loss'], {}), "('Observation Loss', self.obs_loss)\n", (2031, 2066), True, 'import tensorflow as tf\n'), ((2079, 2126), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""Reward Loss"""', 'self.rew_loss'], {}), "('Reward Loss', self.rew_loss)\n", (2096, 2126), True, 'import tensorflow as tf\n'), ((4953, 4986), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (4984, 4986), True, 'import tensorflow as tf\n'), ((5317, 5361), 'common.model.model_play_games', 'model_play_games', (['actor_critic', 'envs', 'nsteps'], {}), '(actor_critic, envs, nsteps)\n', (5333, 5361), False, 'from common.model import NetworkBase, model_play_games\n'), ((5540, 5560), 'numpy.concatenate', 'np.concatenate', (['mb_s'], {}), '(mb_s)\n', (5554, 5560), True, 'import numpy as np\n'), ((5580, 5600), 'numpy.concatenate', 'np.concatenate', (['mb_a'], {}), '(mb_a)\n', (5594, 5600), True, 'import numpy as np\n'), ((5620, 5640), 'numpy.concatenate', 'np.concatenate', (['mb_r'], {}), '(mb_r)\n', (5634, 5640), True, 'import numpy as np\n'), ((5660, 5681), 'numpy.concatenate', 'np.concatenate', (['mb_ns'], {}), '(mb_ns)\n', (5674, 5681), True, 'import numpy as np\n'), ((5701, 5721), 'numpy.concatenate', 'np.concatenate', (['mb_d'], {}), '(mb_d)\n', (5715, 5721), True, 'import numpy as np\n'), ((1239, 1287), 'tensorflow.square', 'tf.square', (['(self.target_obs - self.model.pred_obs)'], {}), '(self.target_obs - self.model.pred_obs)\n', (1248, 1287), True, 'import tensorflow as tf\n'), ((1338, 1386), 'tensorflow.square', 'tf.square', (['(self.target_rew - self.model.pred_rew)'], {}), '(self.target_rew - self.model.pred_rew)\n', (1347, 1386), True, 'import tensorflow as tf\n')] |
import sys, csv
import numpy as np
from keras import models
from keras import layers
from keras.utils.np_utils import to_categorical
# import matplotlib.pyplot as plt
# from keras.datasets import boston_housing
Train_Data_List = []
Train_Target_List = []
with open('train.txt', 'r') as f:
reader = csv.DictReader(f, delimiter=',')
for row in reader:
Battery_power = float(row["battery_power"])
Blue = float(row["blue"])
Clock_speed = float(row["clock_speed"])
Dual_sim = float(row["dual_sim"])
Fc = float(row["fc"])
Four_g = float(row["four_g"])
Int_memory = float(row["int_memory"])
M_dep = float(row["m_dep"])
Mobile_wt = float(row["mobile_wt"])
N_cores = float(row["n_cores"])
Pc = float(row["pc"])
Px_height = float(row["px_height"])
Px_width = float(row["px_width"])
Ram = float(row["ram"])
Sc_h = float(row["sc_h"])
Sc_w = float(row["sc_w"])
Talk_time = float(row["talk_time"])
Three_g = float(row["three_g"])
Touch_screen = float(row["touch_screen"])
Wifi = float(row["wifi"])
PriceRange = int(row["price_range"])
Train_Data_List.append([Battery_power, Blue, Clock_speed,Dual_sim,Fc,Four_g,Int_memory,M_dep,Mobile_wt,N_cores
,Pc,Px_height,Px_width,Ram,Sc_h,Sc_w,Talk_time,Three_g,Touch_screen,Wifi ])
Train_Target_List.append(PriceRange)
train_data = np.array(Train_Data_List);
tensort_train_targets = np.array(Train_Target_List);
train_targets = to_categorical(tensort_train_targets)
#print(train_data.shape)
#print(train_targets.shape)
mean = train_data.mean(axis=0)
train_data -= mean
std = train_data.std(axis=0)
train_data /= std
# test_data -= mean
# test_data /= std
# print(train_data)
# print(train_targets)
def build_model():
model = models.Sequential()
model.add(layers.Dense(64, activation='relu',input_shape=(train_data.shape[1],)))
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(4, activation='softmax'))
model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])
return model
print(build_model())
num_epochs = 90
model = build_model()
model.fit(train_data, train_targets,epochs=num_epochs, batch_size=4, verbose=0)
val_categorical_crossentropy, val_accuracy = model.evaluate(train_data, train_targets, verbose=0)
print(val_accuracy)
# k = 4
# num_val_samples = len(train_data) // k
# all_accuracy_histories = []
# for i in range(k):
# print('processing fold #', i)
# val_data = train_data[i * num_val_samples: (i + 1) * num_val_samples]
# val_targets = train_targets[i * num_val_samples: (i + 1) * num_val_samples]
# partial_train_data = np.concatenate([train_data[:i * num_val_samples],train_data[(i + 1) * num_val_samples:]],axis=0)
# partial_train_targets = np.concatenate([train_targets[:i * num_val_samples],train_targets[(i + 1) * num_val_samples:]],axis=0)
# model = build_model()
# model.fit(partial_train_data, partial_train_targets,epochs=num_epochs, batch_size=4, verbose=0)
# val_categorical_crossentropy, val_accuracy = model.evaluate(val_data, val_targets, verbose=0)
# all_accuracy_histories.append(val_accuracy)
#
# def mean(numbers):
# return float(sum(numbers)) / max(len(numbers), 1)
#
# print(mean(all_accuracy_histories))
# average_accuracy_history = [np.mean([x[i] for x in all_accuracy_histories]) for i in range(num_epochs)]
#
# def smooth_curve(points, factor=0.9):
# smoothed_points = []
# for point in points:
# if smoothed_points:
# previous = smoothed_points[-1]
# smoothed_points.append(previous * factor + point * (1 - factor))
# else:
# smoothed_points.append(point)
# return smoothed_points
#
# smooth_accuracy_history = smooth_curve(average_accuracy_history[10:])
#
# print(smooth_accuracy_history)
# plt.plot(range(1, len(smooth_mae_history) + 1), smooth_mae_history)
# plt.xlabel('Epochs')
# plt.ylabel('Accuracy')
# plt.show()
#print(all_scores);
| [
"csv.DictReader",
"keras.models.Sequential",
"numpy.array",
"keras.utils.np_utils.to_categorical",
"keras.layers.Dense"
] | [((1463, 1488), 'numpy.array', 'np.array', (['Train_Data_List'], {}), '(Train_Data_List)\n', (1471, 1488), True, 'import numpy as np\n'), ((1514, 1541), 'numpy.array', 'np.array', (['Train_Target_List'], {}), '(Train_Target_List)\n', (1522, 1541), True, 'import numpy as np\n'), ((1559, 1596), 'keras.utils.np_utils.to_categorical', 'to_categorical', (['tensort_train_targets'], {}), '(tensort_train_targets)\n', (1573, 1596), False, 'from keras.utils.np_utils import to_categorical\n'), ((304, 336), 'csv.DictReader', 'csv.DictReader', (['f'], {'delimiter': '""","""'}), "(f, delimiter=',')\n", (318, 336), False, 'import sys, csv\n'), ((1864, 1883), 'keras.models.Sequential', 'models.Sequential', ([], {}), '()\n', (1881, 1883), False, 'from keras import models\n'), ((1898, 1969), 'keras.layers.Dense', 'layers.Dense', (['(64)'], {'activation': '"""relu"""', 'input_shape': '(train_data.shape[1],)'}), "(64, activation='relu', input_shape=(train_data.shape[1],))\n", (1910, 1969), False, 'from keras import layers\n'), ((1984, 2019), 'keras.layers.Dense', 'layers.Dense', (['(64)'], {'activation': '"""relu"""'}), "(64, activation='relu')\n", (1996, 2019), False, 'from keras import layers\n'), ((2035, 2072), 'keras.layers.Dense', 'layers.Dense', (['(4)'], {'activation': '"""softmax"""'}), "(4, activation='softmax')\n", (2047, 2072), False, 'from keras import layers\n')] |
import numpy as np
import pandas as pd
import math
import math
import matplotlib.pyplot as plt
import networkx as nx
from sklearn.cluster import KMeans as KMeans
from scipy import sparse
from numpy import linalg
# picture has been attached in the mail
df1 = pd.read_csv("./../data/11_twoCirclesData.csv") # reading the data
total_data= df1.values # taking out imp columns
# x=total_data['x'].values
# y=total_data['y'].values
m=len(total_data)
A=np.zeros((m,m))
var=0.0004900000000000002
cluster_0=[]
cluster_1=[]
for i in range(m):
for j in range (m):
a=np.square(np.linalg.norm(total_data[i]-total_data[j]))
A[i][j] = np.exp(- a/(var))
G=nx.from_numpy_matrix(A)
node_list=list(G.nodes())
l=nx.normalized_laplacian_matrix(G)
eigenValues, eigenVectors = linalg.eigh(l.todense())
temp=eigenVectors.T
idx = np.argsort(eigenValues)
a=temp[idx[1]]
b=temp[idx[2]]
#c=temp[idx[3]]
d=np.vstack((a,b))
#e=np.vstack((d,c))
import matplotlib.pyplot as plt
kmeans = KMeans(n_clusters=2, random_state=0).fit(d.T)
cluster_0=[]
cluster_1=[]
for i in range(len(kmeans.labels_)):
if (kmeans.labels_[i] == 0):
cluster_0.append(node_list[i])
x, y = total_data[i]
plt.scatter(x, y,c='red')
elif (kmeans.labels_[i] == 1):
cluster_1.append(node_list[i])
x, y = total_data[i]
plt.scatter(x, y,c='blue')
#var=var+0.00003
plt.show()
#plt.savefig('/content/gdrive/My Drive/Colab Notebooks/data/community_fiedler.jpg')
| [
"sklearn.cluster.KMeans",
"pandas.read_csv",
"numpy.linalg.norm",
"numpy.argsort",
"numpy.exp",
"numpy.zeros",
"networkx.normalized_laplacian_matrix",
"numpy.vstack",
"matplotlib.pyplot.scatter",
"networkx.from_numpy_matrix",
"matplotlib.pyplot.show"
] | [((263, 309), 'pandas.read_csv', 'pd.read_csv', (['"""./../data/11_twoCirclesData.csv"""'], {}), "('./../data/11_twoCirclesData.csv')\n", (274, 309), True, 'import pandas as pd\n'), ((468, 484), 'numpy.zeros', 'np.zeros', (['(m, m)'], {}), '((m, m))\n', (476, 484), True, 'import numpy as np\n'), ((681, 704), 'networkx.from_numpy_matrix', 'nx.from_numpy_matrix', (['A'], {}), '(A)\n', (701, 704), True, 'import networkx as nx\n'), ((733, 766), 'networkx.normalized_laplacian_matrix', 'nx.normalized_laplacian_matrix', (['G'], {}), '(G)\n', (763, 766), True, 'import networkx as nx\n'), ((846, 869), 'numpy.argsort', 'np.argsort', (['eigenValues'], {}), '(eigenValues)\n', (856, 869), True, 'import numpy as np\n'), ((919, 936), 'numpy.vstack', 'np.vstack', (['(a, b)'], {}), '((a, b))\n', (928, 936), True, 'import numpy as np\n'), ((1369, 1379), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1377, 1379), True, 'import matplotlib.pyplot as plt\n'), ((657, 673), 'numpy.exp', 'np.exp', (['(-a / var)'], {}), '(-a / var)\n', (663, 673), True, 'import numpy as np\n'), ((998, 1034), 'sklearn.cluster.KMeans', 'KMeans', ([], {'n_clusters': '(2)', 'random_state': '(0)'}), '(n_clusters=2, random_state=0)\n', (1004, 1034), True, 'from sklearn.cluster import KMeans as KMeans\n'), ((1202, 1228), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x', 'y'], {'c': '"""red"""'}), "(x, y, c='red')\n", (1213, 1228), True, 'import matplotlib.pyplot as plt\n'), ((598, 643), 'numpy.linalg.norm', 'np.linalg.norm', (['(total_data[i] - total_data[j])'], {}), '(total_data[i] - total_data[j])\n', (612, 643), True, 'import numpy as np\n'), ((1325, 1352), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x', 'y'], {'c': '"""blue"""'}), "(x, y, c='blue')\n", (1336, 1352), True, 'import matplotlib.pyplot as plt\n')] |
import numpy as np
import matplotlib.pyplot as plt
def QR_fact(A):
"""
I spent 4 hours on this. This still does
not work properly. Ultimately I just cries
and left this as is in remembrance.
"""
if A is None:
raise RuntimeError("A cannot be NoneType")
ncols = A.shape[1]
nrows = A.shape[0]
Q = np.zeros(A.shape)
R = np.zeros((ncols, ncols))
for i in range(ncols):
u_i = A[:, i]
u_i-=np.dot(Q[:, :i], np.dot(u_i, Q[:, :i]))
e_i = u_i / np.linalg.norm(u_i, ord=2)
Q[:, i] = e_i
R[:, i] = np.dot(np.dot(u_i, Q[:, :i+1]), np.diag(np.ones(ncols))[:i+1])
return Q, R
def QR_fact_iter(A):
if A is None:
raise RuntimeError("A cannot be NoneType")
ncols = A.shape[1]
nrows = A.shape[0]
Q = np.zeros(A.shape)
R = np.zeros((ncols, ncols))
for k in range(ncols):
Q[:, k] = A[:, k]
for j in range(k):
R[j, k] = np.dot(Q[:, j], A[:, k])
Q[:, k] = Q[:, k] - R[j, k] * Q[:, j]
R[k, k] = np.linalg.norm(Q[:, k], ord=2)
if R[k, k] == 0:
raise RuntimeError("Matrix A is not full rank.")
Q[:, k] = Q[:, k] / R[k, k]
return Q, R
def main():
A = np.random.random((100, 80))
Q, R = QR_fact_iter(A)
if __name__ == '__main__':
main() | [
"numpy.ones",
"numpy.random.random",
"numpy.dot",
"numpy.zeros",
"numpy.linalg.norm"
] | [((317, 334), 'numpy.zeros', 'np.zeros', (['A.shape'], {}), '(A.shape)\n', (325, 334), True, 'import numpy as np\n'), ((340, 364), 'numpy.zeros', 'np.zeros', (['(ncols, ncols)'], {}), '((ncols, ncols))\n', (348, 364), True, 'import numpy as np\n'), ((728, 745), 'numpy.zeros', 'np.zeros', (['A.shape'], {}), '(A.shape)\n', (736, 745), True, 'import numpy as np\n'), ((751, 775), 'numpy.zeros', 'np.zeros', (['(ncols, ncols)'], {}), '((ncols, ncols))\n', (759, 775), True, 'import numpy as np\n'), ((1115, 1142), 'numpy.random.random', 'np.random.random', (['(100, 80)'], {}), '((100, 80))\n', (1131, 1142), True, 'import numpy as np\n'), ((946, 976), 'numpy.linalg.norm', 'np.linalg.norm', (['Q[:, k]'], {'ord': '(2)'}), '(Q[:, k], ord=2)\n', (960, 976), True, 'import numpy as np\n'), ((429, 450), 'numpy.dot', 'np.dot', (['u_i', 'Q[:, :i]'], {}), '(u_i, Q[:, :i])\n', (435, 450), True, 'import numpy as np\n'), ((466, 492), 'numpy.linalg.norm', 'np.linalg.norm', (['u_i'], {'ord': '(2)'}), '(u_i, ord=2)\n', (480, 492), True, 'import numpy as np\n'), ((528, 553), 'numpy.dot', 'np.dot', (['u_i', 'Q[:, :i + 1]'], {}), '(u_i, Q[:, :i + 1])\n', (534, 553), True, 'import numpy as np\n'), ((865, 889), 'numpy.dot', 'np.dot', (['Q[:, j]', 'A[:, k]'], {}), '(Q[:, j], A[:, k])\n', (871, 889), True, 'import numpy as np\n'), ((561, 575), 'numpy.ones', 'np.ones', (['ncols'], {}), '(ncols)\n', (568, 575), True, 'import numpy as np\n')] |
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""DeepSpeech2 model configuration.
References:
https://arxiv.org/abs/1512.02595
Deep Speech 2: End-to-End Speech Recognition in English and Mandarin
"""
import numpy as np
from six.moves import xrange # pylint: disable=redefined-builtin
import tensorflow as tf
from models import model as model_lib
class DeepSpeech2Model(model_lib.Model):
"""Define DeepSpeech2 model."""
# Supported rnn cells.
SUPPORTED_RNNS = {
"lstm": tf.nn.rnn_cell.BasicLSTMCell,
"rnn": tf.nn.rnn_cell.RNNCell,
"gru": tf.nn.rnn_cell.GRUCell,
}
# Parameters for batch normalization.
BATCH_NORM_EPSILON = 1e-5
BATCH_NORM_DECAY = 0.997
# Filters of convolution layer
CONV_FILTERS = 32
def __init__(self,
num_rnn_layers=5,
rnn_type="lstm",
is_bidirectional=True,
rnn_hidden_size=800,
use_bias=True,
params=None):
"""Initialize DeepSpeech2 model.
Args:
num_rnn_layers: an integer, the number of rnn layers (default: 5).
rnn_type: a string, one of the supported rnn cells: gru, rnn or lstm.
is_bidirectional: a boolean to indicate if the rnn layer is bidirectional.
rnn_hidden_size: an integer for the number of hidden units in the RNN
cell.
use_bias: a boolean specifying whether to use a bias in the last fc layer.
params: the params from BenchmarkCNN.
"""
super(DeepSpeech2Model, self).__init__(
"deepspeech2",
batch_size=128,
learning_rate=0.0005,
fp16_loss_scale=128,
params=params)
self.num_rnn_layers = num_rnn_layers
self.rnn_type = rnn_type
self.is_bidirectional = is_bidirectional
self.rnn_hidden_size = rnn_hidden_size
self.use_bias = use_bias
self.num_feature_bins = 161
# TODO(laigd): these are for synthetic data only, for real data we need to
# set self.max_time_steps=3494 and self.max_label_length=576
self.max_time_steps = 180
self.max_label_length = 50
def _batch_norm(self, inputs, training):
"""Batch normalization layer.
Note that the momentum to use will affect validation accuracy over time.
Batch norm has different behaviors during training/evaluation. With a large
momentum, the model takes longer to get a near-accurate estimation of the
moving mean/variance over the entire training dataset, which means we need
more iterations to see good evaluation results. If the training data is
evenly distributed over the feature space, we can also try setting a smaller
momentum (such as 0.1) to get good evaluation result sooner.
Args:
inputs: input data for batch norm layer.
training: a boolean to indicate if it is in training stage.
Returns:
tensor output from batch norm layer.
"""
return tf.layers.batch_normalization(
inputs=inputs,
momentum=DeepSpeech2Model.BATCH_NORM_DECAY,
epsilon=DeepSpeech2Model.BATCH_NORM_EPSILON,
fused=True,
training=training)
def _conv_bn_layer(self, inputs, padding, filters, kernel_size, strides,
layer_id, training):
"""Defines 2D convolutional + batch normalization layer.
Args:
inputs: input data for convolution layer.
padding: padding to be applied before convolution layer.
filters: an integer, number of output filters in the convolution.
kernel_size: a tuple specifying the height and width of the 2D convolution
window.
strides: a tuple specifying the stride length of the convolution.
layer_id: an integer specifying the layer index.
training: a boolean to indicate which stage we are in (training/eval).
Returns:
tensor output from the current layer.
"""
# Perform symmetric padding on the feature dimension of time_step
# This step is required to avoid issues when RNN output sequence is shorter
# than the label length.
inputs = tf.pad(
inputs,
[[0, 0], [padding[0], padding[0]], [padding[1], padding[1]], [0, 0]])
inputs = tf.layers.conv2d(
inputs=inputs,
filters=filters,
kernel_size=kernel_size,
strides=strides,
padding="valid",
use_bias=False,
activation=tf.nn.relu6,
name="cnn_{}".format(layer_id))
return self._batch_norm(inputs, training)
def _rnn_layer(self, inputs, rnn_cell, rnn_hidden_size, layer_id,
use_batch_norm, is_bidirectional, training):
"""Defines a batch normalization + rnn layer.
Args:
inputs: input tensors for the current layer.
rnn_cell: RNN cell instance to use.
rnn_hidden_size: an integer for the dimensionality of the rnn output
space.
layer_id: an integer for the index of current layer.
use_batch_norm: a boolean specifying whether to perform batch
normalization on input states.
is_bidirectional: a boolean specifying whether the rnn layer is
bi-directional.
training: a boolean to indicate which stage we are in (training/eval).
Returns:
tensor output for the current layer.
"""
if use_batch_norm:
inputs = self._batch_norm(inputs, training)
# Construct forward/backward RNN cells.
fw_cell = rnn_cell(
num_units=rnn_hidden_size, name="rnn_fw_{}".format(layer_id))
if is_bidirectional:
bw_cell = rnn_cell(
num_units=rnn_hidden_size, name="rnn_bw_{}".format(layer_id))
outputs, _ = tf.nn.bidirectional_dynamic_rnn(
cell_fw=fw_cell,
cell_bw=bw_cell,
inputs=inputs,
dtype=tf.float32,
swap_memory=True)
rnn_outputs = tf.concat(outputs, -1)
else:
rnn_outputs = tf.nn.dynamic_rnn(
fw_cell, inputs, dtype=tf.float32, swap_memory=True)
return rnn_outputs
def get_input_shape(self):
"""Returns the padded shape of the input spectrogram."""
return [self.max_time_steps, self.num_feature_bins, 1]
def get_synthetic_inputs_and_labels(self, input_name, data_type, nclass):
inputs = tf.random_uniform(
[self.batch_size] + self.get_input_shape(), dtype=data_type)
inputs = tf.contrib.framework.local_variable(inputs, name=input_name)
labels = tf.convert_to_tensor(
np.random.randint(28, size=[self.batch_size, self.max_label_length]))
return (inputs, labels)
# TODO(laigd): support fp16.
# TODO(laigd): support datasets.
# TODO(laigd): support multiple gpus.
def build_network(self,
inputs,
phase_train=True,
nclass=29,
data_type=tf.float32):
"""Builds the forward pass of the deepspeech2 model.
Args:
inputs: The input images
phase_train: True during training. False during evaluation.
nclass: Number of classes that the images can belong to.
data_type: The dtype to run the model in: tf.float32 or tf.float16. The
variable dtype is controlled by a separate parameter: self.fp16_vars.
Returns:
A BuildNetworkResult which contains the logits and model-specific extra
information.
"""
# Two cnn layers.
inputs = self._conv_bn_layer(
inputs,
padding=(20, 5),
filters=DeepSpeech2Model.CONV_FILTERS,
kernel_size=(41, 11),
strides=(2, 2),
layer_id=1,
training=phase_train)
inputs = self._conv_bn_layer(
inputs,
padding=(10, 5),
filters=DeepSpeech2Model.CONV_FILTERS,
kernel_size=(21, 11),
strides=(2, 1),
layer_id=2,
training=phase_train)
# output of conv_layer2 with the shape of
# [batch_size (N), times (T), features (F), channels (C)].
# Convert the conv output to rnn input.
# batch_size = tf.shape(inputs)[0]
feat_size = inputs.get_shape().as_list()[2]
inputs = tf.reshape(
inputs,
[self.batch_size, -1, feat_size * DeepSpeech2Model.CONV_FILTERS])
# RNN layers.
rnn_cell = DeepSpeech2Model.SUPPORTED_RNNS[self.rnn_type]
for layer_counter in xrange(self.num_rnn_layers):
# No batch normalization on the first layer.
use_batch_norm = (layer_counter != 0)
inputs = self._rnn_layer(inputs, rnn_cell, self.rnn_hidden_size,
layer_counter + 1, use_batch_norm,
self.is_bidirectional, phase_train)
# FC layer with batch norm.
inputs = self._batch_norm(inputs, phase_train)
logits = tf.layers.dense(inputs, nclass, use_bias=self.use_bias)
# (2=batchsize, 45, 29=#vocabulary)
return model_lib.BuildNetworkResult(logits=logits, extra_info=None)
def loss_function(self, build_network_result, labels):
"""Computes the ctc loss for the current batch of predictions.
Args:
build_network_result: a BuildNetworkResult returned by build_network().
labels: the label input tensor of the model.
Returns:
The loss tensor of the model.
"""
logits = build_network_result.logits
# TODO(laigd): use the actual time steps read from each wav file.
actual_time_steps = tf.constant(
self.max_time_steps, shape=[self.batch_size, 1])
probs = tf.nn.softmax(logits)
ctc_time_steps = tf.shape(probs)[1]
ctc_input_length = tf.to_float(
tf.multiply(actual_time_steps, ctc_time_steps))
ctc_input_length = tf.to_int32(
tf.floordiv(ctc_input_length, tf.to_float(self.max_time_steps)))
# TODO(laigd): use the actual label length from the dataset files.
# TODO(laigd): this should be obtained from input.
label_length = tf.constant(
self.max_label_length, shape=[self.batch_size, 1])
label_length = tf.to_int32(tf.squeeze(label_length))
ctc_input_length = tf.to_int32(tf.squeeze(ctc_input_length))
sparse_labels = tf.to_int32(
tf.keras.backend.ctc_label_dense_to_sparse(labels, label_length))
y_pred = tf.log(
tf.transpose(probs, perm=[1, 0, 2]) + tf.keras.backend.epsilon())
losses = tf.expand_dims(
tf.nn.ctc_loss(
labels=sparse_labels,
inputs=y_pred,
sequence_length=ctc_input_length,
ignore_longer_outputs_than_inputs=True),
axis=1)
loss = tf.reduce_mean(losses)
return loss
def accuracy_function(self, logits, labels, data_type):
"""Returns the ops to measure the accuracy of the model."""
# TODO(laigd): implement this.
return {}
| [
"tensorflow.nn.bidirectional_dynamic_rnn",
"tensorflow.pad",
"tensorflow.shape",
"tensorflow.transpose",
"tensorflow.keras.backend.ctc_label_dense_to_sparse",
"tensorflow.keras.backend.epsilon",
"tensorflow.multiply",
"six.moves.xrange",
"tensorflow.nn.softmax",
"tensorflow.reduce_mean",
"tensor... | [((3526, 3700), 'tensorflow.layers.batch_normalization', 'tf.layers.batch_normalization', ([], {'inputs': 'inputs', 'momentum': 'DeepSpeech2Model.BATCH_NORM_DECAY', 'epsilon': 'DeepSpeech2Model.BATCH_NORM_EPSILON', 'fused': '(True)', 'training': 'training'}), '(inputs=inputs, momentum=DeepSpeech2Model.\n BATCH_NORM_DECAY, epsilon=DeepSpeech2Model.BATCH_NORM_EPSILON, fused=\n True, training=training)\n', (3555, 3700), True, 'import tensorflow as tf\n'), ((4664, 4752), 'tensorflow.pad', 'tf.pad', (['inputs', '[[0, 0], [padding[0], padding[0]], [padding[1], padding[1]], [0, 0]]'], {}), '(inputs, [[0, 0], [padding[0], padding[0]], [padding[1], padding[1]],\n [0, 0]])\n', (4670, 4752), True, 'import tensorflow as tf\n'), ((6890, 6950), 'tensorflow.contrib.framework.local_variable', 'tf.contrib.framework.local_variable', (['inputs'], {'name': 'input_name'}), '(inputs, name=input_name)\n', (6925, 6950), True, 'import tensorflow as tf\n'), ((8600, 8689), 'tensorflow.reshape', 'tf.reshape', (['inputs', '[self.batch_size, -1, feat_size * DeepSpeech2Model.CONV_FILTERS]'], {}), '(inputs, [self.batch_size, -1, feat_size * DeepSpeech2Model.\n CONV_FILTERS])\n', (8610, 8689), True, 'import tensorflow as tf\n'), ((8808, 8835), 'six.moves.xrange', 'xrange', (['self.num_rnn_layers'], {}), '(self.num_rnn_layers)\n', (8814, 8835), False, 'from six.moves import xrange\n'), ((9233, 9288), 'tensorflow.layers.dense', 'tf.layers.dense', (['inputs', 'nclass'], {'use_bias': 'self.use_bias'}), '(inputs, nclass, use_bias=self.use_bias)\n', (9248, 9288), True, 'import tensorflow as tf\n'), ((9342, 9402), 'models.model.BuildNetworkResult', 'model_lib.BuildNetworkResult', ([], {'logits': 'logits', 'extra_info': 'None'}), '(logits=logits, extra_info=None)\n', (9370, 9402), True, 'from models import model as model_lib\n'), ((9861, 9921), 'tensorflow.constant', 'tf.constant', (['self.max_time_steps'], {'shape': '[self.batch_size, 1]'}), '(self.max_time_steps, shape=[self.batch_size, 1])\n', (9872, 9921), True, 'import tensorflow as tf\n'), ((9943, 9964), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['logits'], {}), '(logits)\n', (9956, 9964), True, 'import tensorflow as tf\n'), ((10352, 10414), 'tensorflow.constant', 'tf.constant', (['self.max_label_length'], {'shape': '[self.batch_size, 1]'}), '(self.max_label_length, shape=[self.batch_size, 1])\n', (10363, 10414), True, 'import tensorflow as tf\n'), ((10990, 11012), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['losses'], {}), '(losses)\n', (11004, 11012), True, 'import tensorflow as tf\n'), ((6202, 6323), 'tensorflow.nn.bidirectional_dynamic_rnn', 'tf.nn.bidirectional_dynamic_rnn', ([], {'cell_fw': 'fw_cell', 'cell_bw': 'bw_cell', 'inputs': 'inputs', 'dtype': 'tf.float32', 'swap_memory': '(True)'}), '(cell_fw=fw_cell, cell_bw=bw_cell, inputs=\n inputs, dtype=tf.float32, swap_memory=True)\n', (6233, 6323), True, 'import tensorflow as tf\n'), ((6390, 6412), 'tensorflow.concat', 'tf.concat', (['outputs', '(-1)'], {}), '(outputs, -1)\n', (6399, 6412), True, 'import tensorflow as tf\n'), ((6443, 6513), 'tensorflow.nn.dynamic_rnn', 'tf.nn.dynamic_rnn', (['fw_cell', 'inputs'], {'dtype': 'tf.float32', 'swap_memory': '(True)'}), '(fw_cell, inputs, dtype=tf.float32, swap_memory=True)\n', (6460, 6513), True, 'import tensorflow as tf\n'), ((6994, 7062), 'numpy.random.randint', 'np.random.randint', (['(28)'], {'size': '[self.batch_size, self.max_label_length]'}), '(28, size=[self.batch_size, self.max_label_length])\n', (7011, 7062), True, 'import numpy as np\n'), ((9986, 10001), 'tensorflow.shape', 'tf.shape', (['probs'], {}), '(probs)\n', (9994, 10001), True, 'import tensorflow as tf\n'), ((10049, 10095), 'tensorflow.multiply', 'tf.multiply', (['actual_time_steps', 'ctc_time_steps'], {}), '(actual_time_steps, ctc_time_steps)\n', (10060, 10095), True, 'import tensorflow as tf\n'), ((10455, 10479), 'tensorflow.squeeze', 'tf.squeeze', (['label_length'], {}), '(label_length)\n', (10465, 10479), True, 'import tensorflow as tf\n'), ((10516, 10544), 'tensorflow.squeeze', 'tf.squeeze', (['ctc_input_length'], {}), '(ctc_input_length)\n', (10526, 10544), True, 'import tensorflow as tf\n'), ((10588, 10652), 'tensorflow.keras.backend.ctc_label_dense_to_sparse', 'tf.keras.backend.ctc_label_dense_to_sparse', (['labels', 'label_length'], {}), '(labels, label_length)\n', (10630, 10652), True, 'import tensorflow as tf\n'), ((10787, 10917), 'tensorflow.nn.ctc_loss', 'tf.nn.ctc_loss', ([], {'labels': 'sparse_labels', 'inputs': 'y_pred', 'sequence_length': 'ctc_input_length', 'ignore_longer_outputs_than_inputs': '(True)'}), '(labels=sparse_labels, inputs=y_pred, sequence_length=\n ctc_input_length, ignore_longer_outputs_than_inputs=True)\n', (10801, 10917), True, 'import tensorflow as tf\n'), ((10171, 10203), 'tensorflow.to_float', 'tf.to_float', (['self.max_time_steps'], {}), '(self.max_time_steps)\n', (10182, 10203), True, 'import tensorflow as tf\n'), ((10683, 10718), 'tensorflow.transpose', 'tf.transpose', (['probs'], {'perm': '[1, 0, 2]'}), '(probs, perm=[1, 0, 2])\n', (10695, 10718), True, 'import tensorflow as tf\n'), ((10721, 10747), 'tensorflow.keras.backend.epsilon', 'tf.keras.backend.epsilon', ([], {}), '()\n', (10745, 10747), True, 'import tensorflow as tf\n')] |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.pipeline import Pipeline
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.preprocessing import StandardScaler, Imputer
from wakeful import log_munger, pipelining, preprocessing
def get_feature_importance(X, y):
extree = ExtraTreesClassifier()
extree.fit(X, y)
return X, extree.feature_importances_
def feature_selection_pipeline(train_df=None, test_df=None, fig_dir=None, fig_file=None, fig_title=None):
# get features and labels
X_train, y_train = preprocessing.split_X_y(train_df)
# create the transformers and estimators
fillna = Imputer(strategy='median')
scaler = StandardScaler()
extree = ExtraTreesClassifier()
pipe = Pipeline(steps=[
('fillna', fillna),
('scaler', scaler),
('extree', extree),
])
# fit the pipe start to finish
pipe.fit(X_train, y_train)
# plot feature
column_names = X_train.columns.values
labels = ['feature', 'importance']
data = [(name, value) for name, value in zip(column_names, extree.feature_importances_)]
plotting_df = pd.DataFrame.from_records(data, columns=labels)
print(plotting_df)
print(len(column_names), len(extree.feature_importances_))
# reverse sort the values from most to least important
values = extree.feature_importances_
#indices = np.argsort(-values)[::-1]
#plot_feature_importance("./plots/feature_importances", column_names[indices], values[indices])
indices = np.argsort(values)[::-1]
num_features = 5
print(f'Explained variance top-{num_features} featurs is {sum(values[indices][:num_features])}')
plot_feature_importance_sns("./plots/feature_importances", column_names[indices][:num_features], values[indices][:num_features])
def plot_feature_importance(plot_path, names, values):
f, ax = plt.subplots(1, 1, figsize=(7, 5))
pos = np.arange(len(names)) + 0.5
plt.barh(pos, values, align='center')
plt.title("Feature Importance")
plt.xlabel("Explained Variance")
plt.ylabel("Feature")
plt.yticks(pos, names)
plt.grid(True)
plt.tight_layout(pad=0.9)
plt.savefig(plot_path)
def plot_feature_importance_sns(plot_path, names, values):
f, ax = plt.subplots(1, 1, figsize=(7, 5))
plt.title('Feature Selection')
ax.set_xlim([0, 1])
sns.barplot(x=values,
y=names,
palette=sns.color_palette('BuGn_r'))
ax.set_xlabel('Importance')
ax.set_ylabel('Feature')
sns.despine(offset=10)
with plt.style.context('seaborn-poster'):
plt.tight_layout(pad=0.8)
plt.savefig(plot_path+'_sns')
def plot_bar_chart(plotting_df):
f, ax = plt.subplots(1, 1, figsize=(7, 5))
plt.title('Feature Selection')
ax.set_xlim([0, 1])
# sns.set_style("whitegrid", { 'axes.edgecolor': '.8', 'text.color': '.15', 'xtick.color': '.15',})
sns.barplot(x='importance',
y='feature',
data=plotting_df,
palette=sns.color_palette('BuGn_r'))
ax.set_xlabel('Importance', fontsize=12)
ax.set_ylabel('Feature', fontsize=12)
sns.despine(offset=10)
#with plt.style.context('seaborn-poster'):
with sns.axes_style('darkgrid'):
plt.tight_layout(pad=0.8)
plt.show()
def LeaveOneOut(data1, data2, columnName, useLOO=False):
# cite: inspired by https://www.kaggle.com/shrutigodbole15792/feature-selection
grpOutcomes = data1.groupby(columnName).mean().reset_index()
outcomes = data2['outcome'].values
x = pd.merge(data2[[columnName, 'outcome']], grpOutcomes,
suffixes=('x_', ''),
how='left',
on=columnName,
left_index=True)['outcome']
if(useLOO):
x = ((x*x.shape[0])-outcomes)/(x.shape[0]-1)
return x.fillna(x.mean())
def fig_title(h5_key):
tokens = [tok.capitalize() for tok in h5_key.split('_')]
return f'Malware: {tokens[0]} -- Log Data Analyzed: {tokens[-2]}'
def fig_name(h5_key):
tokens = [tok.capitalize() for tok in h5_key.split('_')]
return f'{tokens[0]}_{tokens[-2]}.png'
if __name__ == '__main__':
log_types = ['dns', 'conn']
all_data = dict([
('dnscat2_2017_12_31_conn_test', 'dnscat2_2017_12_31_conn_train'),
('dnscat2_2017_12_31_dns_test', 'dnscat2_2017_12_31_dns_train'),
('iodine_forwarded_2017_12_31_conn_test', 'iodine_forwarded_2017_12_31_conn_train'),
('iodine_forwarded_2017_12_31_dns_test', 'iodine_forwarded_2017_12_31_dns_train'),
('iodine_raw_2017_12_31_conn_test', 'iodine_raw_2017_12_31_conn_train'),
('iodine_raw_2017_12_31_dns_test', 'iodine_raw_2017_12_31_dns_train'),
])
half_data = dict([
('dnscat2_2017_12_31_dns_test', 'dnscat2_2017_12_31_dns_train'),
('iodine_forwarded_2017_12_31_conn_test', 'iodine_forwarded_2017_12_31_conn_train'),
('iodine_raw_2017_12_31_conn_test', 'iodine_raw_2017_12_31_conn_train'),
])
small_data = dict([
('iodine_raw_2017_12_31_dns_test', 'iodine_raw_2017_12_31_dns_train'),
])
data_dir = 'data/'
fig_dir = 'plots/'
data = half_data
train_dfs, test_dfs = [], []
for test_key, train_key in data.items():
train_dfs.append(log_munger.hdf5_to_df(train_key, data_dir))
test_dfs.append(log_munger.hdf5_to_df(test_key, data_dir))
train_df = pd.concat(train_dfs)
test_df = pd.concat(test_dfs)
print(train_df.head())
print(train_df.info())
feature_selection_pipeline(train_df=train_df, test_df=None, fig_dir='plots', fig_file='extree', fig_title='Feature Importances')
| [
"matplotlib.pyplot.grid",
"sklearn.ensemble.ExtraTreesClassifier",
"matplotlib.pyplot.ylabel",
"numpy.argsort",
"matplotlib.pyplot.style.context",
"wakeful.preprocessing.split_X_y",
"seaborn.despine",
"seaborn.color_palette",
"wakeful.log_munger.hdf5_to_df",
"matplotlib.pyplot.barh",
"matplotlib... | [((346, 368), 'sklearn.ensemble.ExtraTreesClassifier', 'ExtraTreesClassifier', ([], {}), '()\n', (366, 368), False, 'from sklearn.ensemble import ExtraTreesClassifier\n'), ((593, 626), 'wakeful.preprocessing.split_X_y', 'preprocessing.split_X_y', (['train_df'], {}), '(train_df)\n', (616, 626), False, 'from wakeful import log_munger, pipelining, preprocessing\n'), ((686, 712), 'sklearn.preprocessing.Imputer', 'Imputer', ([], {'strategy': '"""median"""'}), "(strategy='median')\n", (693, 712), False, 'from sklearn.preprocessing import StandardScaler, Imputer\n'), ((726, 742), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (740, 742), False, 'from sklearn.preprocessing import StandardScaler, Imputer\n'), ((756, 778), 'sklearn.ensemble.ExtraTreesClassifier', 'ExtraTreesClassifier', ([], {}), '()\n', (776, 778), False, 'from sklearn.ensemble import ExtraTreesClassifier\n'), ((791, 867), 'sklearn.pipeline.Pipeline', 'Pipeline', ([], {'steps': "[('fillna', fillna), ('scaler', scaler), ('extree', extree)]"}), "(steps=[('fillna', fillna), ('scaler', scaler), ('extree', extree)])\n", (799, 867), False, 'from sklearn.pipeline import Pipeline\n'), ((1179, 1226), 'pandas.DataFrame.from_records', 'pd.DataFrame.from_records', (['data'], {'columns': 'labels'}), '(data, columns=labels)\n', (1204, 1226), True, 'import pandas as pd\n'), ((1916, 1950), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(7, 5)'}), '(1, 1, figsize=(7, 5))\n', (1928, 1950), True, 'import matplotlib.pyplot as plt\n'), ((1993, 2030), 'matplotlib.pyplot.barh', 'plt.barh', (['pos', 'values'], {'align': '"""center"""'}), "(pos, values, align='center')\n", (2001, 2030), True, 'import matplotlib.pyplot as plt\n'), ((2035, 2066), 'matplotlib.pyplot.title', 'plt.title', (['"""Feature Importance"""'], {}), "('Feature Importance')\n", (2044, 2066), True, 'import matplotlib.pyplot as plt\n'), ((2071, 2103), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Explained Variance"""'], {}), "('Explained Variance')\n", (2081, 2103), True, 'import matplotlib.pyplot as plt\n'), ((2108, 2129), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Feature"""'], {}), "('Feature')\n", (2118, 2129), True, 'import matplotlib.pyplot as plt\n'), ((2134, 2156), 'matplotlib.pyplot.yticks', 'plt.yticks', (['pos', 'names'], {}), '(pos, names)\n', (2144, 2156), True, 'import matplotlib.pyplot as plt\n'), ((2161, 2175), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (2169, 2175), True, 'import matplotlib.pyplot as plt\n'), ((2180, 2205), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {'pad': '(0.9)'}), '(pad=0.9)\n', (2196, 2205), True, 'import matplotlib.pyplot as plt\n'), ((2210, 2232), 'matplotlib.pyplot.savefig', 'plt.savefig', (['plot_path'], {}), '(plot_path)\n', (2221, 2232), True, 'import matplotlib.pyplot as plt\n'), ((2305, 2339), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(7, 5)'}), '(1, 1, figsize=(7, 5))\n', (2317, 2339), True, 'import matplotlib.pyplot as plt\n'), ((2344, 2374), 'matplotlib.pyplot.title', 'plt.title', (['"""Feature Selection"""'], {}), "('Feature Selection')\n", (2353, 2374), True, 'import matplotlib.pyplot as plt\n'), ((2575, 2597), 'seaborn.despine', 'sns.despine', ([], {'offset': '(10)'}), '(offset=10)\n', (2586, 2597), True, 'import seaborn as sns\n'), ((2762, 2796), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(7, 5)'}), '(1, 1, figsize=(7, 5))\n', (2774, 2796), True, 'import matplotlib.pyplot as plt\n'), ((2801, 2831), 'matplotlib.pyplot.title', 'plt.title', (['"""Feature Selection"""'], {}), "('Feature Selection')\n", (2810, 2831), True, 'import matplotlib.pyplot as plt\n'), ((3202, 3224), 'seaborn.despine', 'sns.despine', ([], {'offset': '(10)'}), '(offset=10)\n', (3213, 3224), True, 'import seaborn as sns\n'), ((5471, 5491), 'pandas.concat', 'pd.concat', (['train_dfs'], {}), '(train_dfs)\n', (5480, 5491), True, 'import pandas as pd\n'), ((5506, 5525), 'pandas.concat', 'pd.concat', (['test_dfs'], {}), '(test_dfs)\n', (5515, 5525), True, 'import pandas as pd\n'), ((1568, 1586), 'numpy.argsort', 'np.argsort', (['values'], {}), '(values)\n', (1578, 1586), True, 'import numpy as np\n'), ((2607, 2642), 'matplotlib.pyplot.style.context', 'plt.style.context', (['"""seaborn-poster"""'], {}), "('seaborn-poster')\n", (2624, 2642), True, 'import matplotlib.pyplot as plt\n'), ((2652, 2677), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {'pad': '(0.8)'}), '(pad=0.8)\n', (2668, 2677), True, 'import matplotlib.pyplot as plt\n'), ((2686, 2717), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(plot_path + '_sns')"], {}), "(plot_path + '_sns')\n", (2697, 2717), True, 'import matplotlib.pyplot as plt\n'), ((3281, 3307), 'seaborn.axes_style', 'sns.axes_style', (['"""darkgrid"""'], {}), "('darkgrid')\n", (3295, 3307), True, 'import seaborn as sns\n'), ((3317, 3342), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {'pad': '(0.8)'}), '(pad=0.8)\n', (3333, 3342), True, 'import matplotlib.pyplot as plt\n'), ((3351, 3361), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3359, 3361), True, 'import matplotlib.pyplot as plt\n'), ((3617, 3739), 'pandas.merge', 'pd.merge', (["data2[[columnName, 'outcome']]", 'grpOutcomes'], {'suffixes': "('x_', '')", 'how': '"""left"""', 'on': 'columnName', 'left_index': '(True)'}), "(data2[[columnName, 'outcome']], grpOutcomes, suffixes=('x_', ''),\n how='left', on=columnName, left_index=True)\n", (3625, 3739), True, 'import pandas as pd\n'), ((2481, 2508), 'seaborn.color_palette', 'sns.color_palette', (['"""BuGn_r"""'], {}), "('BuGn_r')\n", (2498, 2508), True, 'import seaborn as sns\n'), ((3082, 3109), 'seaborn.color_palette', 'sns.color_palette', (['"""BuGn_r"""'], {}), "('BuGn_r')\n", (3099, 3109), True, 'import seaborn as sns\n'), ((5344, 5386), 'wakeful.log_munger.hdf5_to_df', 'log_munger.hdf5_to_df', (['train_key', 'data_dir'], {}), '(train_key, data_dir)\n', (5365, 5386), False, 'from wakeful import log_munger, pipelining, preprocessing\n'), ((5412, 5453), 'wakeful.log_munger.hdf5_to_df', 'log_munger.hdf5_to_df', (['test_key', 'data_dir'], {}), '(test_key, data_dir)\n', (5433, 5453), False, 'from wakeful import log_munger, pipelining, preprocessing\n')] |
import sys # for sys.argv
import numpy # NumPy math library
# Sigmoid function (S-curve), and its derivative
def sigmoid(x, deriv):
if(deriv == True):
return x * (1 - x)
return 1 / (1 + numpy.exp(-x))
# Implementation of a simple neural network with configurable input size, output size, number of layers, and transfer function
class NeuralNet:
# NeuralNet(): instantiate a NeuralNet object
# Note: transferFunction must take the form of: f(x, bool derivative)
def __init__(self, inputSize, outputSize, numLayers, dataSize, transferFunction = sigmoid):
self.inputSize = inputSize
self.outputSize = outputSize
self.numLayers = numLayers
self.dataSize = dataSize
self.transferFunction = transferFunction
# initialize weights with random values in the range [-1, 1]
self.weights = [None] * self.numLayers
self.weights[0] = 2 * numpy.random.random((self.inputSize, self.dataSize)) - 1 # initialize input weights
for layer in range(1, self.numLayers - 1):
self.weights[layer] = 2 * numpy.random.random((self.dataSize, self.dataSize)) - 1 # initialize hidden weights
self.weights[self.numLayers - 1] = 2 * numpy.random.random((self.dataSize, self.outputSize)) - 1 # initialize output weights
def __repr__(self):
return str(self.weights)
# run(): propagate data forwards through the network
def run(self, inputData):
self.layers = [None] * (self.numLayers + 1)
self.layers[0] = inputData # apply data to input layer
for layer in range(1, self.numLayers + 1):
self.layers[layer] = self.transferFunction(numpy.dot(self.layers[layer - 1], self.weights[layer - 1]), False) # propagate through hidden layers
return self.layers[self.numLayers] # return output layer
# train(): propagate an input data set forwards, then compare against expected results and propagate error backwards to update network weights
def train(self, inputData, expectedResults):
output = self.run(inputData) # forward propagation (i.e. run the neural net!)
# calculate error at output
layer_errors = [None] * (self.numLayers + 1)
layer_errors[self.numLayers] = expectedResults - output
# calculate deltas based on confidence
layer_deltas = [None] * (self.numLayers + 1)
layer_deltas[self.numLayers] = layer_errors[self.numLayers] * self.transferFunction(self.layers[self.numLayers], True)
for layer in reversed(range(1, self.numLayers)):
# how much did each layers[n] value contrinute to the layers[n+1] error (according to weights)?
layer_errors[layer] = layer_deltas[layer + 1].dot(self.weights[layer].T) # .T transposes the array (flips it sideways)
# calculate deltas based on confidence
layer_deltas[layer] = layer_errors[layer] * self.transferFunction(self.layers[layer], True)
# update weights
for layer in range(self.numLayers):
self.weights[layer] += self.layers[layer].T.dot(layer_deltas[layer + 1])
def main(argv):
# input dataset (each row is a training example, each column is one of 3 input nodes)
input_data = numpy.array([[0,0,1],
[0,1,1],
[1,0,1],
[1,1,1]])
# expected output dataset
expected_output_data = numpy.array([[0],
[1],
[1],
[0]])
numpy.random.seed(1) # seed random numbers to make calculation deterministic
net = NeuralNet(inputSize = 3, outputSize = 1, numLayers = 3, dataSize = 4, transferFunction = sigmoid)
for i in range(10000):
net.train(input_data, expected_output_data)
print("Final Output:")
print(net.run(input_data))
pass
if __name__ == "__main__":
main(sys.argv)
| [
"numpy.random.random",
"numpy.exp",
"numpy.array",
"numpy.dot",
"numpy.random.seed"
] | [((3244, 3301), 'numpy.array', 'numpy.array', (['[[0, 0, 1], [0, 1, 1], [1, 0, 1], [1, 1, 1]]'], {}), '([[0, 0, 1], [0, 1, 1], [1, 0, 1], [1, 1, 1]])\n', (3255, 3301), False, 'import numpy\n'), ((3462, 3495), 'numpy.array', 'numpy.array', (['[[0], [1], [1], [0]]'], {}), '([[0], [1], [1], [0]])\n', (3473, 3495), False, 'import numpy\n'), ((3621, 3641), 'numpy.random.seed', 'numpy.random.seed', (['(1)'], {}), '(1)\n', (3638, 3641), False, 'import numpy\n'), ((204, 217), 'numpy.exp', 'numpy.exp', (['(-x)'], {}), '(-x)\n', (213, 217), False, 'import numpy\n'), ((920, 972), 'numpy.random.random', 'numpy.random.random', (['(self.inputSize, self.dataSize)'], {}), '((self.inputSize, self.dataSize))\n', (939, 972), False, 'import numpy\n'), ((1224, 1277), 'numpy.random.random', 'numpy.random.random', (['(self.dataSize, self.outputSize)'], {}), '((self.dataSize, self.outputSize))\n', (1243, 1277), False, 'import numpy\n'), ((1681, 1739), 'numpy.dot', 'numpy.dot', (['self.layers[layer - 1]', 'self.weights[layer - 1]'], {}), '(self.layers[layer - 1], self.weights[layer - 1])\n', (1690, 1739), False, 'import numpy\n'), ((1093, 1144), 'numpy.random.random', 'numpy.random.random', (['(self.dataSize, self.dataSize)'], {}), '((self.dataSize, self.dataSize))\n', (1112, 1144), False, 'import numpy\n')] |
import logging
import numpy as np
from plunc.exceptions import InsufficientPrecisionError, OutsideDomainError
class WaryInterpolator(object):
"""Interpolate (and optionally extrapolation) between points,
raising exception if error larger than desired precision
"""
def __init__(self,
points=tuple(), values=tuple(),
precision=0.01, domain=(-1, 3),
if_lower='raise', if_higher='extrapolate',):
"""
:param points:
:param values:
:param precision:
:param domain: (low, high) boundaries of region where interpolation is used
If no values are known at the boundaries, the effective boundary is tighter
:param if_lower: 'extrapolate' or 'raise'
:param if_higher:
:param loglevel:
:return:
"""
self.precision = precision
self.domain = domain
self.if_lower = if_lower
self.if_higher = if_higher
self.log = logging.getLogger('WaryInterpolator')
self.points = np.array(points)
self.values = np.array(values)
def __call__(self, x):
self.log.debug("Asked for x = %s" % x)
if len(self.points) < 3:
raise InsufficientPrecisionError("Need at least three datapoints before we can interpolate or extrapolate")
if x < self.domain[0]:
self.log.debug("Below domain boundary")
if self.if_lower == 'extrapolate':
return self.extrapolate(x)
else:
raise OutsideDomainError("Value %s is below the lowest known value %s" % (x, self.points.min()))
elif x > self.domain[1]:
self.log.debug("Above domain boundary")
if self.if_higher == 'extrapolate':
return self.extrapolate(x)
else:
raise OutsideDomainError("Value %s is above the highest known value %s" % (x, self.points.max()))
else:
return self.interpolate(x)
def interpolate(self, x):
if x in self.points:
self.log.debug("Exact value known")
return self.values[np.nonzero(self.points == x)[0][0]]
max_i = len(self.points) - 1
if not self.points.min() < x < self.points.max():
self.log.debug("%s is in domain, but outside the range of known values. Trying extrapolation." % x)
return self.extrapolate(x)
# Find index of nearest known point to the right
nearest_right = np.searchsorted(self.points, x)
assert 0 < nearest_right < len(self.points)
if nearest_right == 1:
self.log.debug("Only one point to left")
y = self.linear_interpolant(x, 0, 1)
y2 = self.linear_interpolant(x, 0, 2)
diff = 2 * (y - y2)
elif nearest_right == max_i:
self.log.debug("Only one point to right")
y = self.linear_interpolant(x, max_i - 1, max_i)
y2 = self.linear_interpolant(x, max_i - 2, max_i)
diff = 2 * (y - y2)
else:
self.log.debug("At least two points on either side")
y = self.linear_interpolant(x, nearest_right - 1, nearest_right)
y2 = self.linear_interpolant(x, nearest_right - 1, nearest_right + 1)
diff = y - y2
self.log.debug("Close interpolation gives y=%s, far gives y=%s.\n"
"Difference factor %s, precision tolerance %s" % (y, y2, abs(diff / y), self.precision))
if abs(diff / y) > self.precision:
raise InsufficientPrecisionError("Interpolation failed: achieved precision %s, required %s" % (
abs(diff/y), self.precision))
self.log.debug("Interpolation is ok, returning result")
return y
def linear_interpolant(self, x, index_low, index_high):
x0 = self.points[index_low]
x1 = self.points[index_high]
y0 = self.values[index_low]
y1 = self.values[index_high]
return y0 + (y1 - y0) * (x - x0)/(x1 - x0)
def extrapolate(self, x):
# TODO: change to linear regression on all points in configurable part (e.g. 5%) of range (for y2, 2x range)
# Now this is very vulnerable to small errors on datapoints if datapoints are close together near edge
# TODO: option to ignore InsufficientPrecisionError and barge ahead anyway
if x > self.domain[0]:
max_i = len(self.points) - 1
y = self.linear_interpolant(x, max_i - 1, max_i)
y2 = self.linear_interpolant(x, max_i - 2, max_i)
else:
y = self.linear_interpolant(x, 0, 1)
y2 = self.linear_interpolant(x, 0, 2)
diff = 2 * (y - y2)
self.log.debug("Close extrapolation gives y=%s, far gives y=%s.\n"
"Difference factor %s, precision tolerance %s" % (y, y2, abs(diff / y), self.precision))
if abs(diff / y) > self.precision:
raise InsufficientPrecisionError("Extrapolation precision %s estimated, "
"but %s required" % (abs(diff / y), self.precision))
return y
def add_point(self, x, y):
self.add_points(np.array([x]), np.array([y]))
def add_points(self, xs, ys):
if not self.domain[0] <= np.min(xs) <= np.max(xs) <= self.domain[1]:
raise ValueError("Points to add must lie in the domain [%s-%s], but you passed values from %s to %s" % (
self.domain[0], self.domain[1], np.min(xs), np.max(xs)))
self.points = np.concatenate((self.points, xs))
self.values = np.concatenate((self.values, ys))
sort_indices = np.argsort(self.points)
self.points = self.points[sort_indices]
self.values = self.values[sort_indices]
def plot(self):
if not self.loglog_space:
raise NotImplementedError
import matplotlib.pyplot as plt
x = np.logspace(self.domain[0], self.domain[1], 100)
plt.plot(np.log10(x), [np.log10(self.f(q)) for q in x])
plt.plot(self.points, self.values, marker='o') | [
"logging.getLogger",
"plunc.exceptions.InsufficientPrecisionError",
"numpy.log10",
"numpy.searchsorted",
"matplotlib.pyplot.plot",
"numpy.max",
"numpy.argsort",
"numpy.array",
"numpy.concatenate",
"numpy.min",
"numpy.nonzero",
"numpy.logspace"
] | [((1013, 1050), 'logging.getLogger', 'logging.getLogger', (['"""WaryInterpolator"""'], {}), "('WaryInterpolator')\n", (1030, 1050), False, 'import logging\n'), ((1074, 1090), 'numpy.array', 'np.array', (['points'], {}), '(points)\n', (1082, 1090), True, 'import numpy as np\n'), ((1113, 1129), 'numpy.array', 'np.array', (['values'], {}), '(values)\n', (1121, 1129), True, 'import numpy as np\n'), ((2531, 2562), 'numpy.searchsorted', 'np.searchsorted', (['self.points', 'x'], {}), '(self.points, x)\n', (2546, 2562), True, 'import numpy as np\n'), ((5588, 5621), 'numpy.concatenate', 'np.concatenate', (['(self.points, xs)'], {}), '((self.points, xs))\n', (5602, 5621), True, 'import numpy as np\n'), ((5644, 5677), 'numpy.concatenate', 'np.concatenate', (['(self.values, ys)'], {}), '((self.values, ys))\n', (5658, 5677), True, 'import numpy as np\n'), ((5701, 5724), 'numpy.argsort', 'np.argsort', (['self.points'], {}), '(self.points)\n', (5711, 5724), True, 'import numpy as np\n'), ((5966, 6014), 'numpy.logspace', 'np.logspace', (['self.domain[0]', 'self.domain[1]', '(100)'], {}), '(self.domain[0], self.domain[1], 100)\n', (5977, 6014), True, 'import numpy as np\n'), ((6087, 6133), 'matplotlib.pyplot.plot', 'plt.plot', (['self.points', 'self.values'], {'marker': '"""o"""'}), "(self.points, self.values, marker='o')\n", (6095, 6133), True, 'import matplotlib.pyplot as plt\n'), ((1256, 1362), 'plunc.exceptions.InsufficientPrecisionError', 'InsufficientPrecisionError', (['"""Need at least three datapoints before we can interpolate or extrapolate"""'], {}), "(\n 'Need at least three datapoints before we can interpolate or extrapolate')\n", (1282, 1362), False, 'from plunc.exceptions import InsufficientPrecisionError, OutsideDomainError\n'), ((5234, 5247), 'numpy.array', 'np.array', (['[x]'], {}), '([x])\n', (5242, 5247), True, 'import numpy as np\n'), ((5249, 5262), 'numpy.array', 'np.array', (['[y]'], {}), '([y])\n', (5257, 5262), True, 'import numpy as np\n'), ((6032, 6043), 'numpy.log10', 'np.log10', (['x'], {}), '(x)\n', (6040, 6043), True, 'import numpy as np\n'), ((5332, 5342), 'numpy.min', 'np.min', (['xs'], {}), '(xs)\n', (5338, 5342), True, 'import numpy as np\n'), ((5346, 5356), 'numpy.max', 'np.max', (['xs'], {}), '(xs)\n', (5352, 5356), True, 'import numpy as np\n'), ((2165, 2193), 'numpy.nonzero', 'np.nonzero', (['(self.points == x)'], {}), '(self.points == x)\n', (2175, 2193), True, 'import numpy as np\n'), ((5541, 5551), 'numpy.min', 'np.min', (['xs'], {}), '(xs)\n', (5547, 5551), True, 'import numpy as np\n'), ((5553, 5563), 'numpy.max', 'np.max', (['xs'], {}), '(xs)\n', (5559, 5563), True, 'import numpy as np\n')] |
#!/usr/bin/env python3
import numpy as np
import tensorflow as tf
import cart_pole_evaluator
class Network:
def __init__(self, env, args):
inputs = tf.keras.layers.Input(shape=env.state_shape)
for i in range(args.hidden_layers):
if i == 0:
x_common = tf.keras.layers.Dense(
args.hidden_layer_size, activation="relu"
)(inputs)
elif i < 2:
x_common = tf.keras.layers.Dense(
args.hidden_layer_size, activation="relu"
)(x_common)
elif i == 2:
x_policy = tf.keras.layers.Dense(
args.hidden_layer_size, activation="relu"
)(x_common)
x_baseline = tf.keras.layers.Dense(
args.hidden_layer_size, activation="relu"
)(x_common)
else:
x_policy = tf.keras.layers.Dense(
args.hidden_layer_size, activation="relu"
)(x_policy)
x_baseline = tf.keras.layers.Dense(
args.hidden_layer_size, activation="relu"
)(x_baseline)
predictions_policy = tf.keras.layers.Dense(env.actions, activation="softmax")(
x_policy
)
predictions_baseline = tf.keras.layers.Dense(1, activation=None)(x_baseline)
model_policy = tf.keras.models.Model(inputs=inputs, outputs=predictions_policy)
model_baseline = tf.keras.models.Model(
inputs=inputs, outputs=predictions_baseline
)
model_policy.compile(
optimizer=tf.keras.optimizers.Adam(learning_rate=args.learning_rate),
loss=tf.keras.losses.SparseCategoricalCrossentropy(),
experimental_run_tf_function=False,
)
model_baseline.compile(
optimizer=tf.keras.optimizers.Adam(learning_rate=args.learning_rate),
loss=tf.keras.losses.MeanSquaredError(),
experimental_run_tf_function=False,
)
self.model = model_policy
self.baseline = model_baseline
def train(self, states, actions, returns):
states = [val for sublist in states for val in sublist]
actions = [val for sublist in actions for val in sublist]
returns = [val for sublist in returns for val in sublist]
states, actions, returns = (
np.array(states, np.float32),
np.array(actions, np.int32),
np.array(returns, np.float32),
)
baseline_prediction = self.baseline.predict_on_batch(states)
centered_returns = returns - baseline_prediction.squeeze()
self.model.train_on_batch(states, actions, sample_weight=centered_returns)
self.baseline.train_on_batch(states, returns)
def predict(self, states):
states = np.array(states, np.float32)
return self.model.predict(states)
def save(self):
self.model.save("reinforce_policy.h5")
self.baseline.save("reinforce_baseline.h5")
if __name__ == "__main__":
# Parse arguments
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
"--batch_size", default=32, type=int, help="Number of episodes to train on."
)
parser.add_argument("--episodes", default=5000, type=int, help="Training episodes.")
parser.add_argument("--gamma", default=0.98, type=float, help="Discounting factor.")
parser.add_argument(
"--hidden_layers", default=5, type=int, help="Number of hidden layers."
)
parser.add_argument(
"--hidden_layer_size", default=16, type=int, help="Size of hidden layer."
)
parser.add_argument(
"--learning_rate", default=0.01, type=float, help="Learning rate."
)
parser.add_argument(
"--render_each", default=None, type=int, help="Render some episodes."
)
parser.add_argument(
"--threads", default=4, type=int, help="Maximum number of threads to use."
)
args = parser.parse_args()
# Fix random seeds and number of threads
np.random.seed(42)
tf.random.set_seed(42)
tf.config.threading.set_inter_op_parallelism_threads(args.threads)
tf.config.threading.set_intra_op_parallelism_threads(args.threads)
# Create the environment
env = cart_pole_evaluator.environment(discrete=False)
# Construct the network
network = Network(env, args)
import embedded_baseline
import embedded_policy
baseline = tf.keras.models.load_model("reinforce_baseline.h5")
policy = tf.keras.models.load_model("reinforce_policy.h5")
network.model = policy
network.baseline = baseline
# # Training
# for _ in range(args.episodes // args.batch_size):
# batch_states, batch_actions, batch_returns = [], [], []
# for _ in range(args.batch_size):
# # Perform episode
# states, actions, rewards = [], [], []
# state, done = env.reset(), False
# while not done:
# if (
# args.render_each
# and env.episode > 0
# and env.episode % args.render_each == 0
# ):
# env.render()
# action_probs = network.predict([state])[0]
# action = np.random.choice(list(range(env.actions)), p=action_probs)
# next_state, reward, done, _ = env.step(action)
# states.append(state)
# actions.append(action)
# rewards.append(reward)
# state = next_state
# # TODO: Compute returns by summing rewards (with discounting)
# single_return = 0
# returns = []
# for reward in np.flip(rewards):
# single_return = reward + args.gamma * single_return
# returns.append(single_return)
# batch_states.append(np.array(states))
# batch_actions.append(np.array(actions))
# batch_returns.append(np.flip(returns))
# # Train using the generated batch
# network.train(batch_states, batch_actions, batch_returns)
# network.save()
# # Final evaluation
for _ in range(100):
state, done = env.reset(True), False
while not done:
state = np.array([state]).reshape(1, -1)
probabilities = network.model.predict_on_batch(state)[0]
action = np.argmax(probabilities)
state, reward, done, _ = env.step(action)
| [
"tensorflow.keras.layers.Input",
"tensorflow.config.threading.set_intra_op_parallelism_threads",
"tensorflow.random.set_seed",
"argparse.ArgumentParser",
"tensorflow.keras.losses.MeanSquaredError",
"tensorflow.keras.losses.SparseCategoricalCrossentropy",
"numpy.argmax",
"tensorflow.keras.optimizers.Ad... | [((3147, 3172), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (3170, 3172), False, 'import argparse\n'), ((4101, 4119), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (4115, 4119), True, 'import numpy as np\n'), ((4124, 4146), 'tensorflow.random.set_seed', 'tf.random.set_seed', (['(42)'], {}), '(42)\n', (4142, 4146), True, 'import tensorflow as tf\n'), ((4151, 4217), 'tensorflow.config.threading.set_inter_op_parallelism_threads', 'tf.config.threading.set_inter_op_parallelism_threads', (['args.threads'], {}), '(args.threads)\n', (4203, 4217), True, 'import tensorflow as tf\n'), ((4222, 4288), 'tensorflow.config.threading.set_intra_op_parallelism_threads', 'tf.config.threading.set_intra_op_parallelism_threads', (['args.threads'], {}), '(args.threads)\n', (4274, 4288), True, 'import tensorflow as tf\n'), ((4329, 4376), 'cart_pole_evaluator.environment', 'cart_pole_evaluator.environment', ([], {'discrete': '(False)'}), '(discrete=False)\n', (4360, 4376), False, 'import cart_pole_evaluator\n'), ((4511, 4562), 'tensorflow.keras.models.load_model', 'tf.keras.models.load_model', (['"""reinforce_baseline.h5"""'], {}), "('reinforce_baseline.h5')\n", (4537, 4562), True, 'import tensorflow as tf\n'), ((4576, 4625), 'tensorflow.keras.models.load_model', 'tf.keras.models.load_model', (['"""reinforce_policy.h5"""'], {}), "('reinforce_policy.h5')\n", (4602, 4625), True, 'import tensorflow as tf\n'), ((163, 207), 'tensorflow.keras.layers.Input', 'tf.keras.layers.Input', ([], {'shape': 'env.state_shape'}), '(shape=env.state_shape)\n', (184, 207), True, 'import tensorflow as tf\n'), ((1415, 1479), 'tensorflow.keras.models.Model', 'tf.keras.models.Model', ([], {'inputs': 'inputs', 'outputs': 'predictions_policy'}), '(inputs=inputs, outputs=predictions_policy)\n', (1436, 1479), True, 'import tensorflow as tf\n'), ((1505, 1571), 'tensorflow.keras.models.Model', 'tf.keras.models.Model', ([], {'inputs': 'inputs', 'outputs': 'predictions_baseline'}), '(inputs=inputs, outputs=predictions_baseline)\n', (1526, 1571), True, 'import tensorflow as tf\n'), ((2870, 2898), 'numpy.array', 'np.array', (['states', 'np.float32'], {}), '(states, np.float32)\n', (2878, 2898), True, 'import numpy as np\n'), ((1217, 1273), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['env.actions'], {'activation': '"""softmax"""'}), "(env.actions, activation='softmax')\n", (1238, 1273), True, 'import tensorflow as tf\n'), ((1337, 1378), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['(1)'], {'activation': 'None'}), '(1, activation=None)\n', (1358, 1378), True, 'import tensorflow as tf\n'), ((2423, 2451), 'numpy.array', 'np.array', (['states', 'np.float32'], {}), '(states, np.float32)\n', (2431, 2451), True, 'import numpy as np\n'), ((2465, 2492), 'numpy.array', 'np.array', (['actions', 'np.int32'], {}), '(actions, np.int32)\n', (2473, 2492), True, 'import numpy as np\n'), ((2506, 2535), 'numpy.array', 'np.array', (['returns', 'np.float32'], {}), '(returns, np.float32)\n', (2514, 2535), True, 'import numpy as np\n'), ((6483, 6507), 'numpy.argmax', 'np.argmax', (['probabilities'], {}), '(probabilities)\n', (6492, 6507), True, 'import numpy as np\n'), ((1647, 1705), 'tensorflow.keras.optimizers.Adam', 'tf.keras.optimizers.Adam', ([], {'learning_rate': 'args.learning_rate'}), '(learning_rate=args.learning_rate)\n', (1671, 1705), True, 'import tensorflow as tf\n'), ((1724, 1771), 'tensorflow.keras.losses.SparseCategoricalCrossentropy', 'tf.keras.losses.SparseCategoricalCrossentropy', ([], {}), '()\n', (1769, 1771), True, 'import tensorflow as tf\n'), ((1886, 1944), 'tensorflow.keras.optimizers.Adam', 'tf.keras.optimizers.Adam', ([], {'learning_rate': 'args.learning_rate'}), '(learning_rate=args.learning_rate)\n', (1910, 1944), True, 'import tensorflow as tf\n'), ((1963, 1997), 'tensorflow.keras.losses.MeanSquaredError', 'tf.keras.losses.MeanSquaredError', ([], {}), '()\n', (1995, 1997), True, 'import tensorflow as tf\n'), ((303, 367), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['args.hidden_layer_size'], {'activation': '"""relu"""'}), "(args.hidden_layer_size, activation='relu')\n", (324, 367), True, 'import tensorflow as tf\n'), ((6360, 6377), 'numpy.array', 'np.array', (['[state]'], {}), '([state])\n', (6368, 6377), True, 'import numpy as np\n'), ((465, 529), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['args.hidden_layer_size'], {'activation': '"""relu"""'}), "(args.hidden_layer_size, activation='relu')\n", (486, 529), True, 'import tensorflow as tf\n'), ((630, 694), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['args.hidden_layer_size'], {'activation': '"""relu"""'}), "(args.hidden_layer_size, activation='relu')\n", (651, 694), True, 'import tensorflow as tf\n'), ((772, 836), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['args.hidden_layer_size'], {'activation': '"""relu"""'}), "(args.hidden_layer_size, activation='relu')\n", (793, 836), True, 'import tensorflow as tf\n'), ((930, 994), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['args.hidden_layer_size'], {'activation': '"""relu"""'}), "(args.hidden_layer_size, activation='relu')\n", (951, 994), True, 'import tensorflow as tf\n'), ((1072, 1136), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['args.hidden_layer_size'], {'activation': '"""relu"""'}), "(args.hidden_layer_size, activation='relu')\n", (1093, 1136), True, 'import tensorflow as tf\n')] |
import logging
import numpy as np
logger = logging.getLogger("FederatedAveraging")
class DefaultFederatedAveraging:
def __init__(self, buflength=5):
self.buflength = buflength
def __call__(self, metadata, weights, weight_buffer):
logger.debug("Federated avg: call with buffer length %s", len(weight_buffer))
if len(weight_buffer) < self.buflength:
logger.debug("Federated avg: waiting for more weights, do nothing")
return weights, weight_buffer
new_weights = list()
for weights_list_tuple in zip(*weight_buffer):
new_weights.append(
np.array([np.array(w).mean(axis=0) for w in zip(*weights_list_tuple)])
)
logger.debug("Federated avg: created new weights. Empty buffer")
return new_weights, []
def always_average():
def implementation(_, _1, weight_buffer):
new_weights = list()
for weights_list_tuple in zip(*weight_buffer):
new_weights.append(
np.array([np.array(w).mean(axis=0) for w in zip(*weights_list_tuple)])
)
logger.debug("Federated avg: created new weights. Empty buffer")
return new_weights, []
return implementation
| [
"logging.getLogger",
"numpy.array"
] | [((45, 84), 'logging.getLogger', 'logging.getLogger', (['"""FederatedAveraging"""'], {}), "('FederatedAveraging')\n", (62, 84), False, 'import logging\n'), ((651, 662), 'numpy.array', 'np.array', (['w'], {}), '(w)\n', (659, 662), True, 'import numpy as np\n'), ((1043, 1054), 'numpy.array', 'np.array', (['w'], {}), '(w)\n', (1051, 1054), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 01 15:21:46 2018
@author: <NAME>, <NAME>
"""
from __future__ import division, print_function, absolute_import, unicode_literals
from os import path, remove
import sys
import numpy as np
import h5py
from sidpy.sid import Translator
from sidpy.hdf.hdf_utils import write_simple_attrs
from pyUSID.io.write_utils import Dimension
from pyUSID.io.hdf_utils import create_indexed_group, write_main_dataset, \
write_ind_val_dsets
# packages specific to this kind of file
from .df_utils.gsf_read import gsf_read
import gwyfile
if sys.version_info.major == 3:
unicode = str
class GwyddionTranslator(Translator):
def translate(self, file_path, *args, **kwargs):
# Two kinds of files:
# 1. Simple GSF files -> use metadata, data = gsf_read(file_path)
# 2. Native .gwy files -> use the gwyfile package
# I have a notebook that shows how such data can be read.
# Create the .h5 file from the input file
if not isinstance(file_path, (str, unicode)):
raise TypeError('file_path should be a string!')
if not (file_path.endswith('.gsf') or file_path.endswith('.gwy')):
# TODO: Gwyddion is weird, it doesn't append the file extension some times.
# In theory, you could identify the kind of file by looking at the header (line 38 in gsf_read()).
# Ideally the header check should be used instead of the extension check
raise ValueError('file_path must have a .gsf or .gwy extension!')
file_path = path.abspath(file_path)
folder_path, base_name = path.split(file_path)
base_name = base_name[:-4]
h5_path = path.join(folder_path, base_name + '.h5')
if path.exists(h5_path):
remove(h5_path)
self.h5_file = h5py.File(h5_path, 'w')
"""
Setup the global parameters
---------------------------
translator: Gywddion
data_type: depends on file type
GwyddionGSF_<gsf_meta['title']>
or
GwyddionGWY_<gwy_meta['title']>
"""
self.global_parms = dict()
self.global_parms['translator'] = 'Gwyddion'
# Create the measurement group
meas_grp = create_indexed_group(self.h5_file, 'Measurement')
if file_path.endswith('.gsf'):
self._translate_gsf(file_path, meas_grp)
if file_path.endswith('gwy'):
self._translate_gwy(file_path, meas_grp)
write_simple_attrs(self.h5_file, self.global_parms)
return h5_path
def _translate_gsf(self, file_path, meas_grp):
"""
Parameters
----------
file_path
meas_grp
For more information on the .gsf file format visit the link below -
http://gwyddion.net/documentation/user-guide-en/gsf.html
"""
# Read the data in from the specified file
gsf_meta, gsf_values = gsf_read(file_path)
# Write parameters where available specifically for sample_name
# data_type, comments and experiment_date to file-level parms
# Using pop, move some global parameters from gsf_meta to global_parms:
self.global_parms['data_type'] = 'Gwyddion_GSF'
self.global_parms['comments'] = gsf_meta.get('comment', '')
self.global_parms['experiment_date'] = gsf_meta.get('date', '')
# overwrite some parameters at the file level:
write_simple_attrs(meas_grp.parent, self.global_parms)
# Build the reference values for the ancillary position datasets:
# TODO: Remove information from parameters once it is used meaningfully where it needs to be.
# Here, it is no longer necessary to save XReal anymore so we will pop (remove) it from gsf_meta
x_offset = gsf_meta.get('XOffset', 0)
x_range = gsf_meta.get('XReal', 1.0)
# TODO: Use Numpy wherever possible instead of pure python
x_vals = np.linspace(0, x_range, gsf_meta.get('XRes')) + x_offset
y_offset = gsf_meta.get('YOffset', 0)
y_range = gsf_meta.get('YReal', 1.0)
y_vals = np.linspace(0, y_range, gsf_meta.get('YRes')) + y_offset
# Just define the ancillary position and spectral dimensions. Do not create datasets yet
pos_desc = [Dimension('X', gsf_meta.get('XYUnits', 'arb. units'), x_vals),
Dimension('Y', gsf_meta.get('XYUnits', 'arb. units'), y_vals)]
spec_desc = Dimension('Intensity', gsf_meta.get('ZUnits', 'arb. units'), [1])
"""
You only need to prepare the dimensions for positions and spectroscopic. You do not need to write the
ancillary datasets at this point. write_main_dataset will take care of that. You only need to use
write_ind_val_datasets() for the cases where you may need to reuse the datasets. See the tutorial online.
"""
# Create the channel-level group
chan_grp = create_indexed_group(meas_grp, 'Channel')
write_simple_attrs(chan_grp, gsf_meta)
# Create the main dataset (and the
two_dim_image = gsf_values
write_main_dataset(chan_grp,
np.atleast_2d(np.reshape(two_dim_image,
len(pos_desc[0].values) * len(pos_desc[1].values))).transpose(),
'Raw_Data', gsf_meta.get('Title', 'Unknown'), gsf_meta.get('ZUnits', 'arb. units'),
pos_desc, spec_desc)
# TODO: When passing optional arguments, you are HIGHLY recommended to specify the variable name such as aux_pos_prefix='Position_' instead of just 'Position_' (which is how you pass regulard arguments)
def _translate_gwy(self, file_path, meas_grp):
"""
Parameters
----------
file_path
meas_grp
For more information on the .gwy file format visit the link below -
http://gwyddion.net/documentation/user-guide-en/gwyfile-format.html
"""
# Need to build a set of channels to test against and a function-level variable to write to
channels = {}
# Read the data in from the specified file
gwy_data = gwyfile.load(file_path)
for obj in gwy_data:
gwy_key = obj.split('/')
try:
# if the second index of the gwy_key can be cast into an int then
# it needs to be processed either as an image or a graph
int(gwy_key[1])
if gwy_key[2] == 'graph':
# graph processing
self.global_parms['data_type'] = 'GwyddionGWY_' + 'Graph'
channels = self._translate_graph(meas_grp, gwy_data,
obj, channels)
elif obj.endswith('data'):
self.global_parms['data_type'] = 'GwyddionGWY_' + 'Image'
channels = self._translate_image_stack(meas_grp, gwy_data,
obj, channels)
else:
continue
except ValueError:
# if the second index of the gwy_key cannot be cast into an int
# then it needs to be processed wither as a spectra, volume or xyz
if gwy_key[1] == 'sps':
self.global_parms['data_type'] = 'GwyddionGWY_' + 'Spectra'
channels = self._translate_spectra(meas_grp, gwy_data,
obj, channels)
elif gwy_key[1] == 'brick':
self.global_parms['data_type'] = 'GwyddionGWY_' + 'Volume'
channels = self._translate_volume(meas_grp, gwy_data,
obj, channels)
elif gwy_key[1] == 'xyz':
self.global_parms['data_type'] = 'GwyddionGWY_' + 'XYZ'
channels = self._translate_xyz(meas_grp, gwy_data,
obj, channels)
write_simple_attrs(meas_grp.parent, self.global_parms)
# TODO: Use the Bruker translator as a reference. use the three functions below as necessary to keep the code clean and easy to read.
# Write parameters where available specifically for sample_name
# data_type, comments and experiment_date to file-level parms
# write parameters common across all channels to meas_grp
# Update existing file level parameters where appropriate
# Prepare the list of raw_data datasets
def _translate_image_stack(self, meas_grp, gwy_data, obj, channels):
"""
Use this function to write data corresponding to a stack of scan images (most common)
Returns
-------
"""
current_channel = ''
# Iterate through each object in the gwy dataset
gwy_key = obj.split('/')
# Test whether a new channel needs to be created
# The 'filename' structure in the gwy file should not have a channel created hence the try/except block
try:
if int(gwy_key[1]) not in channels.keys():
current_channel = create_indexed_group(meas_grp, "Channel")
channels[int(gwy_key[1])] = current_channel
else:
current_channel = channels[int(gwy_key[1])]
except ValueError:
if obj.endswith('filename'):
pass
# The data structure of the gwy file will be used to create the main dataset in the h5 file
if obj.endswith('data'):
x_range = gwy_data[obj].get('xreal', 1.0)
x_vals = np.linspace(0, x_range, gwy_data[obj]['xres'])
# print('obj {}\nx_vals {}'.format(obj, x_vals))
y_range = gwy_data[obj].get('yreal', 1.0)
y_vals = np.linspace(0, y_range, gwy_data[obj]['yres'])
pos_desc = [Dimension('X',
gwy_data[obj]['si_unit_xy'].get('unitstr'),
x_vals),
Dimension('Y',
gwy_data[obj]['si_unit_xy'].get('unitstr'),
y_vals)]
# print(pos_desc)
spec_dim = gwy_data['/{}/data/title'.format(gwy_key[1])]
spec_desc = Dimension(spec_dim,
gwy_data[obj]['si_unit_z'].get('unitstr', 'arb. units'),
[0])
two_dim_image = gwy_data[obj]['data']
write_main_dataset(current_channel,
np.atleast_2d(np.reshape(two_dim_image,
len(pos_desc[0].values) * len(pos_desc[1].values))).transpose(),
'Raw_Data',
spec_dim,
gwy_data[obj]['si_unit_z'].get('unitstr'),
pos_desc, spec_desc)
# print('main dataset has been written')
# image data processing
elif obj.endswith('meta'):
meta = {}
write_simple_attrs(current_channel, meta, verbose=False)
return channels
def _translate_spectra(self, meas_grp, gwy_data, obj, channels):
"""
Use this to translate simple 1D data like force curves
Returns
-------
"""
current_channel = ''
gwy_key = obj.split('/')
try:
if int(gwy_key[2]) not in channels.keys():
current_channel = create_indexed_group(meas_grp, "Channel")
channels[int(gwy_key[2])] = current_channel
else:
current_channel = channels[int(gwy_key[2])]
except ValueError:
if obj.endswith('filename'):
pass
else:
raise ValueError('There was an unexpected directory in the spectra file')
title = obj['title']
unitstr = obj['unitstr']
coords = obj['coords']
res = obj['data']['res']
real = obj['data']['real']
offset = obj['data']['off']
x_units = obj['data']['si_unit_x']['unitstr']
y_units = obj['data']['si_unit_y']['unitstr']
data = obj['data']['data']
indices = obj['selected']
x_vals = np.linspace(offset, real, res)
pos_desc = [Dimension('X', x_units, x_vals)]
spec_desc = [Dimension(title, y_units, 0)]
write_main_dataset(current_channel, data,
'Raw_Data', title,
gwy_data[obj]['si_unit_y'],
pos_desc, spec_desc)
return channels
def _translate_graph(self, meas_grp, gwy_data, obj, channels):
"""
Use this to translate graphs
Returns
"""
return channels
def _translate_volume(self, meas_grp, gwy_data, obj, channels):
return channels
def _translate_xyz(self, meas_grp, gwy_data, obj, channels):
return channels | [
"pyUSID.io.write_utils.Dimension",
"os.path.exists",
"gwyfile.load",
"sidpy.hdf.hdf_utils.write_simple_attrs",
"os.path.join",
"h5py.File",
"os.path.split",
"os.remove",
"numpy.linspace",
"os.path.abspath",
"pyUSID.io.hdf_utils.create_indexed_group",
"pyUSID.io.hdf_utils.write_main_dataset"
] | [((1578, 1601), 'os.path.abspath', 'path.abspath', (['file_path'], {}), '(file_path)\n', (1590, 1601), False, 'from os import path, remove\n'), ((1635, 1656), 'os.path.split', 'path.split', (['file_path'], {}), '(file_path)\n', (1645, 1656), False, 'from os import path, remove\n'), ((1710, 1751), 'os.path.join', 'path.join', (['folder_path', "(base_name + '.h5')"], {}), "(folder_path, base_name + '.h5')\n", (1719, 1751), False, 'from os import path, remove\n'), ((1763, 1783), 'os.path.exists', 'path.exists', (['h5_path'], {}), '(h5_path)\n', (1774, 1783), False, 'from os import path, remove\n'), ((1837, 1860), 'h5py.File', 'h5py.File', (['h5_path', '"""w"""'], {}), "(h5_path, 'w')\n", (1846, 1860), False, 'import h5py\n'), ((2301, 2350), 'pyUSID.io.hdf_utils.create_indexed_group', 'create_indexed_group', (['self.h5_file', '"""Measurement"""'], {}), "(self.h5_file, 'Measurement')\n", (2321, 2350), False, 'from pyUSID.io.hdf_utils import create_indexed_group, write_main_dataset, write_ind_val_dsets\n'), ((2553, 2604), 'sidpy.hdf.hdf_utils.write_simple_attrs', 'write_simple_attrs', (['self.h5_file', 'self.global_parms'], {}), '(self.h5_file, self.global_parms)\n', (2571, 2604), False, 'from sidpy.hdf.hdf_utils import write_simple_attrs\n'), ((3507, 3561), 'sidpy.hdf.hdf_utils.write_simple_attrs', 'write_simple_attrs', (['meas_grp.parent', 'self.global_parms'], {}), '(meas_grp.parent, self.global_parms)\n', (3525, 3561), False, 'from sidpy.hdf.hdf_utils import write_simple_attrs\n'), ((5011, 5052), 'pyUSID.io.hdf_utils.create_indexed_group', 'create_indexed_group', (['meas_grp', '"""Channel"""'], {}), "(meas_grp, 'Channel')\n", (5031, 5052), False, 'from pyUSID.io.hdf_utils import create_indexed_group, write_main_dataset, write_ind_val_dsets\n'), ((5061, 5099), 'sidpy.hdf.hdf_utils.write_simple_attrs', 'write_simple_attrs', (['chan_grp', 'gsf_meta'], {}), '(chan_grp, gsf_meta)\n', (5079, 5099), False, 'from sidpy.hdf.hdf_utils import write_simple_attrs\n'), ((6243, 6266), 'gwyfile.load', 'gwyfile.load', (['file_path'], {}), '(file_path)\n', (6255, 6266), False, 'import gwyfile\n'), ((8209, 8263), 'sidpy.hdf.hdf_utils.write_simple_attrs', 'write_simple_attrs', (['meas_grp.parent', 'self.global_parms'], {}), '(meas_grp.parent, self.global_parms)\n', (8227, 8263), False, 'from sidpy.hdf.hdf_utils import write_simple_attrs\n'), ((12494, 12524), 'numpy.linspace', 'np.linspace', (['offset', 'real', 'res'], {}), '(offset, real, res)\n', (12505, 12524), True, 'import numpy as np\n'), ((12637, 12751), 'pyUSID.io.hdf_utils.write_main_dataset', 'write_main_dataset', (['current_channel', 'data', '"""Raw_Data"""', 'title', "gwy_data[obj]['si_unit_y']", 'pos_desc', 'spec_desc'], {}), "(current_channel, data, 'Raw_Data', title, gwy_data[obj][\n 'si_unit_y'], pos_desc, spec_desc)\n", (12655, 12751), False, 'from pyUSID.io.hdf_utils import create_indexed_group, write_main_dataset, write_ind_val_dsets\n'), ((1797, 1812), 'os.remove', 'remove', (['h5_path'], {}), '(h5_path)\n', (1803, 1812), False, 'from os import path, remove\n'), ((9845, 9891), 'numpy.linspace', 'np.linspace', (['(0)', 'x_range', "gwy_data[obj]['xres']"], {}), "(0, x_range, gwy_data[obj]['xres'])\n", (9856, 9891), True, 'import numpy as np\n'), ((10029, 10075), 'numpy.linspace', 'np.linspace', (['(0)', 'y_range', "gwy_data[obj]['yres']"], {}), "(0, y_range, gwy_data[obj]['yres'])\n", (10040, 10075), True, 'import numpy as np\n'), ((12545, 12576), 'pyUSID.io.write_utils.Dimension', 'Dimension', (['"""X"""', 'x_units', 'x_vals'], {}), "('X', x_units, x_vals)\n", (12554, 12576), False, 'from pyUSID.io.write_utils import Dimension\n'), ((12599, 12627), 'pyUSID.io.write_utils.Dimension', 'Dimension', (['title', 'y_units', '(0)'], {}), '(title, y_units, 0)\n', (12608, 12627), False, 'from pyUSID.io.write_utils import Dimension\n'), ((9357, 9398), 'pyUSID.io.hdf_utils.create_indexed_group', 'create_indexed_group', (['meas_grp', '"""Channel"""'], {}), "(meas_grp, 'Channel')\n", (9377, 9398), False, 'from pyUSID.io.hdf_utils import create_indexed_group, write_main_dataset, write_ind_val_dsets\n'), ((11276, 11332), 'sidpy.hdf.hdf_utils.write_simple_attrs', 'write_simple_attrs', (['current_channel', 'meta'], {'verbose': '(False)'}), '(current_channel, meta, verbose=False)\n', (11294, 11332), False, 'from sidpy.hdf.hdf_utils import write_simple_attrs\n'), ((11715, 11756), 'pyUSID.io.hdf_utils.create_indexed_group', 'create_indexed_group', (['meas_grp', '"""Channel"""'], {}), "(meas_grp, 'Channel')\n", (11735, 11756), False, 'from pyUSID.io.hdf_utils import create_indexed_group, write_main_dataset, write_ind_val_dsets\n')] |
#!/usr/bin/env python
from time import time
import rospy
import mavros
import numpy as np
import matplotlib.pyplot as plt
from geometry_msgs.msg import PoseStamped, TwistStamped
import mavros_msgs.msg
class dieptran():
def __init__(self):
rospy.init_node('listener_results', anonymous=True)
self.rate = rospy.Rate(20.0) # MUST be more then 2Hz
mavros.set_namespace('mavros')
state_sub = rospy.Subscriber(mavros.get_topic('state'), mavros_msgs.msg.State, self.state_cb)
# "/mavros/setpoint_velocity/cmd_vel"
vel_pub_sub = rospy.Subscriber(mavros.get_topic('setpoint_velocity', 'cmd_vel'), TwistStamped, self.vel_pub_cb)
vel_local_sub = rospy.Subscriber(mavros.get_topic('local_position','velocity_local'), TwistStamped, self.vel_local_cb)
self.current_state = mavros_msgs.msg.State()
self.vel_pub = [0.0] * 4
self.vel_local = [0.0] * 4
self.vel_pub_x = []
self.vel_pub_y = []
self.vel_pub_z = []
self.vel_local_x = []
self.vel_local_y = []
self.vel_local_z = []
#rospy.spin()
self.show()
self.plot()
def state_cb(self, topic):
self.current_state.armed = topic.armed
self.current_state.connected = topic.connected
self.current_state.mode = topic.mode
def show(self):
rospy.loginfo(self.vel_local[0])
def vel_pub_cb(self, topic):
self.vel_pub[0] = topic.twist.linear.x
self.vel_pub[1] = topic.twist.linear.y
self.vel_pub[2] = topic.twist.linear.z
rospy.loginfo("*****************************")
rospy.loginfo("velocity PUB : " + str(self.vel_pub[0]))
def vel_local_cb(self, topic):
self.vel_local[0] = topic.twist.linear.x
self.vel_local[1] = topic.twist.linear.y
self.vel_local[2] = topic.twist.linear.z
rospy.loginfo("*****************************")
rospy.loginfo("velocity LOCAL : " + str(self.vel_local[0]))
'''
def plot(self):
#rospy.loginfo("velocity : " + str(self.vel_local[0]))
while not rospy.is_shutdown():
if self.current_state.mode == "OFFBOARD" and self.current_state.armed and self.vel_pub != 0 and self.vel_local != 0 :
self.vel_pub_x = np.append(self.vel_pub_x, self.vel_pub[0])
self.vel_pub_y = np.append(self.vel_pub_y, self.vel_pub[1])
self.vel_pub_z = np.append(self.vel_pub_z, self.vel_pub[2])
self.vel_local_x = np.append(self.vel_local_x, self.vel_local[0])
self.vel_local_y = np.append(self.vel_local_y, self.vel_local[1])
self.vel_local_z = np.append(self.vel_local_z, self.vel_local[2])
rospy.spin()
#self.rate.sleep()
if self.vel_pub != 0 and self.vel_local != 0 :
break
'''
def plot(self):
rospy.loginfo("velocity LOCAL : " + str(self.vel_local[0]))
#while self.current_state.mode == "OFFBOARD" and self.current_state.armed and self.vel_pub != 0 and self.vel_local != 0 :
while not rospy.is_shutdown():
if self.vel_pub != 0 and self.vel_local != 0:
self.vel_pub_x = np.append(self.vel_pub_x, self.vel_pub[0])
self.vel_pub_y = np.append(self.vel_pub_y, self.vel_pub[1])
self.vel_pub_z = np.append(self.vel_pub_z, self.vel_pub[2])
self.vel_local_x = np.append(self.vel_local_x, self.vel_local[0])
self.vel_local_y = np.append(self.vel_local_y, self.vel_local[1])
self.vel_local_z = np.append(self.vel_local_z, self.vel_local[2])
rospy.spin()
self.rate.sleep()
if not self.vel_pub and not self.vel_local :
break
#print(len(self.vel_pub_x))
x = np.arange(0, len(self.vel_pub_x))
plt.plot(x, self.vel_pub_x, 'b-', label='vel_pub_x')
plt.plot(x, self.vel_pub_y, 'g-', label='vel_pub_y')
plt.plot(x, self.vel_pub_z, 'r-', label='vel_pub_z')
plt.plot(x, self.vel_local_x, 'c-', label='vel_local_x')
plt.plot(x, self.vel_local_y, 'm-', label='vel_local_y')
plt.plot(x, self.vel_local_z, 'y-', label='vel_local_z')
plt.legend(loc='upper left')
plt.xlabel('time')
plt.ylabel('velocity')
plt.savefig('books_read' + str(time()) + '.png')
if __name__ == "__main__":
run = dieptran()
run.plot()
'''
try:
run.plot()
except rospy.ROSInterruptException:
pass
'''
'''
# callback method for state sub
current_state = State()
def state_cb(state):
global current_state
current_state = state
global vel_pub_sub
def vel_pub_cb(vel_pub):
vel_pub_sub = TwistStamped()
vel_pub_sub.twist = vel_pub
global vel_local_sub
def vel_local_cb(vel_local):
vel_local_sub = TwistStamped()
vel_local_sub.twist = vel_local
def listener():
# In ROS, nodes are uniquely named. If two nodes with the same
# name are launched, the previous one is kicked off. The
# anonymous=True flag means that rospy will choose a unique
# name for our 'listener' node so that multiple listeners can
# run simultaneously.
rospy.init_node('listener_results', anonymous=True)
rate = rospy.Rate(20.0) # MUST be more then 2Hz
state_sub = rospy.Subscriber("/mavros/state", State, state_cb)
vel_pub_sub = rospy.Subscriber("/mavros/setpoint_velocity/cmd_vel", TwistStamped, vel_pub_cb)
vel_local_sub = rospy.Subscriber("/mavros/local_position/velocity_local", TwistStamped, vel_local_cb)
vel_pub_x = []
vel_pub_y = []
vel_pub_z = []
vel_local_x = []
vel_local_y = []
vel_local_z = []
while not rospy.is_shutdown():
#rospy.loginfo("vel_pub_x = %f", vel_pub_x)
rospy.loginfo("Hiiiiiiiiiiiiiiiiiiiiiiiii.................")
#if current_state.mode == "OFFBOARD" and current_state.armed and vel_pub_sub and vel_local_sub:
if vel_pub_sub and vel_local_sub:
vel_pub_x = np.append(vel_pub_x, vel_pub_sub.linear.x)
vel_pub_y = np.append(vel_pub_y, vel_pub_sub.linear.y)
vel_pub_z = np.append(vel_pub_z, vel_pub_sub.linear.z)
vel_local_x = np.append(vel_local_x, vel_local_sub.linear.z)
vel_local_y = np.append(vel_local_y, vel_local_sub.linear.z)
vel_local_z = np.append(vel_local_z, vel_local_sub.linear.z)
rospy.logerr("returned the invalid value %f", vel_pub_x)
#rospy.loginfo("vel_pub_x = %f", vel_pub_x)
#print("vel_pub_x = ", vel_pub_x)
rospy.spin()
rate.sleep()
if not vel_pub_sub:
break
print(len(vel_pub_x))
x = np.arange(0, len(vel_pub_x), 1)
plt.plot(x, vel_pub_x, 'b-', label='vel_pub_x')
plt.plot(x, vel_pub_y, 'g-', label='vel_pub_y')
plt.plot(x, vel_pub_z, 'r-', label='vel_pub_z')
plt.plot(x, vel_local_x, 'c-', label='vel_local_x')
plt.plot(x, vel_local_y, 'm-', label='vel_local_y')
plt.plot(x, vel_local_z, 'y-', label='vel_local_z')
plt.legend(loc='upper left')
plt.xlabel('time')
plt.ylabel('velocity')
plt.savefig('books_read'+str(time())+'.png')
if __name__ == '__main__':
listener()
try:
listener()
except rospy.ROSInterruptException:
pass
''' | [
"mavros.get_topic",
"matplotlib.pyplot.ylabel",
"rospy.is_shutdown",
"rospy.init_node",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"mavros.set_namespace",
"numpy.append",
"rospy.Rate",
"rospy.spin",
"time.time",
"rospy.loginfo",
"matplotlib.pyplot.legend"
] | [((253, 304), 'rospy.init_node', 'rospy.init_node', (['"""listener_results"""'], {'anonymous': '(True)'}), "('listener_results', anonymous=True)\n", (268, 304), False, 'import rospy\n'), ((325, 341), 'rospy.Rate', 'rospy.Rate', (['(20.0)'], {}), '(20.0)\n', (335, 341), False, 'import rospy\n'), ((375, 405), 'mavros.set_namespace', 'mavros.set_namespace', (['"""mavros"""'], {}), "('mavros')\n", (395, 405), False, 'import mavros\n'), ((1371, 1403), 'rospy.loginfo', 'rospy.loginfo', (['self.vel_local[0]'], {}), '(self.vel_local[0])\n', (1384, 1403), False, 'import rospy\n'), ((1587, 1633), 'rospy.loginfo', 'rospy.loginfo', (['"""*****************************"""'], {}), "('*****************************')\n", (1600, 1633), False, 'import rospy\n'), ((1889, 1935), 'rospy.loginfo', 'rospy.loginfo', (['"""*****************************"""'], {}), "('*****************************')\n", (1902, 1935), False, 'import rospy\n'), ((3901, 3953), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'self.vel_pub_x', '"""b-"""'], {'label': '"""vel_pub_x"""'}), "(x, self.vel_pub_x, 'b-', label='vel_pub_x')\n", (3909, 3953), True, 'import matplotlib.pyplot as plt\n'), ((3962, 4014), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'self.vel_pub_y', '"""g-"""'], {'label': '"""vel_pub_y"""'}), "(x, self.vel_pub_y, 'g-', label='vel_pub_y')\n", (3970, 4014), True, 'import matplotlib.pyplot as plt\n'), ((4023, 4075), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'self.vel_pub_z', '"""r-"""'], {'label': '"""vel_pub_z"""'}), "(x, self.vel_pub_z, 'r-', label='vel_pub_z')\n", (4031, 4075), True, 'import matplotlib.pyplot as plt\n'), ((4084, 4140), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'self.vel_local_x', '"""c-"""'], {'label': '"""vel_local_x"""'}), "(x, self.vel_local_x, 'c-', label='vel_local_x')\n", (4092, 4140), True, 'import matplotlib.pyplot as plt\n'), ((4149, 4205), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'self.vel_local_y', '"""m-"""'], {'label': '"""vel_local_y"""'}), "(x, self.vel_local_y, 'm-', label='vel_local_y')\n", (4157, 4205), True, 'import matplotlib.pyplot as plt\n'), ((4214, 4270), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'self.vel_local_z', '"""y-"""'], {'label': '"""vel_local_z"""'}), "(x, self.vel_local_z, 'y-', label='vel_local_z')\n", (4222, 4270), True, 'import matplotlib.pyplot as plt\n'), ((4279, 4307), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper left"""'}), "(loc='upper left')\n", (4289, 4307), True, 'import matplotlib.pyplot as plt\n'), ((4316, 4334), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""time"""'], {}), "('time')\n", (4326, 4334), True, 'import matplotlib.pyplot as plt\n'), ((4343, 4365), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""velocity"""'], {}), "('velocity')\n", (4353, 4365), True, 'import matplotlib.pyplot as plt\n'), ((445, 470), 'mavros.get_topic', 'mavros.get_topic', (['"""state"""'], {}), "('state')\n", (461, 470), False, 'import mavros\n'), ((595, 643), 'mavros.get_topic', 'mavros.get_topic', (['"""setpoint_velocity"""', '"""cmd_vel"""'], {}), "('setpoint_velocity', 'cmd_vel')\n", (611, 643), False, 'import mavros\n'), ((717, 769), 'mavros.get_topic', 'mavros.get_topic', (['"""local_position"""', '"""velocity_local"""'], {}), "('local_position', 'velocity_local')\n", (733, 769), False, 'import mavros\n'), ((3121, 3140), 'rospy.is_shutdown', 'rospy.is_shutdown', ([], {}), '()\n', (3138, 3140), False, 'import rospy\n'), ((3687, 3699), 'rospy.spin', 'rospy.spin', ([], {}), '()\n', (3697, 3699), False, 'import rospy\n'), ((3233, 3275), 'numpy.append', 'np.append', (['self.vel_pub_x', 'self.vel_pub[0]'], {}), '(self.vel_pub_x, self.vel_pub[0])\n', (3242, 3275), True, 'import numpy as np\n'), ((3309, 3351), 'numpy.append', 'np.append', (['self.vel_pub_y', 'self.vel_pub[1]'], {}), '(self.vel_pub_y, self.vel_pub[1])\n', (3318, 3351), True, 'import numpy as np\n'), ((3385, 3427), 'numpy.append', 'np.append', (['self.vel_pub_z', 'self.vel_pub[2]'], {}), '(self.vel_pub_z, self.vel_pub[2])\n', (3394, 3427), True, 'import numpy as np\n'), ((3463, 3509), 'numpy.append', 'np.append', (['self.vel_local_x', 'self.vel_local[0]'], {}), '(self.vel_local_x, self.vel_local[0])\n', (3472, 3509), True, 'import numpy as np\n'), ((3545, 3591), 'numpy.append', 'np.append', (['self.vel_local_y', 'self.vel_local[1]'], {}), '(self.vel_local_y, self.vel_local[1])\n', (3554, 3591), True, 'import numpy as np\n'), ((3627, 3673), 'numpy.append', 'np.append', (['self.vel_local_z', 'self.vel_local[2]'], {}), '(self.vel_local_z, self.vel_local[2])\n', (3636, 3673), True, 'import numpy as np\n'), ((4405, 4411), 'time.time', 'time', ([], {}), '()\n', (4409, 4411), False, 'from time import time\n')] |
#!/usr/bin/python
import numpy as np
class GC:
'Gamma Correction'
def __init__(self, img, lut, mode):
self.img = img
self.lut = lut
self.mode = mode
def execute(self):
img_h = self.img.shape[0]
img_w = self.img.shape[1]
img_c = self.img.shape[2]
gc_img = np.empty((img_h, img_w, img_c), np.uint16)
for y in range(self.img.shape[0]):
for x in range(self.img.shape[1]):
if self.mode == 'rgb':
gc_img[y, x, 0] = self.lut[self.img[y, x, 0]]
gc_img[y, x, 1] = self.lut[self.img[y, x, 1]]
gc_img[y, x, 2] = self.lut[self.img[y, x, 2]]
gc_img[y, x, :] = gc_img[y, x, :] / 4
elif self.mode == 'yuv':
gc_img[y, x, 0] = self.lut[0][self.img[y, x, 0]]
gc_img[y, x, 1] = self.lut[1][self.img[y, x, 1]]
gc_img[y, x, 2] = self.lut[1][self.img[y, x, 2]]
self.img = gc_img
return self.img
| [
"numpy.empty"
] | [((326, 368), 'numpy.empty', 'np.empty', (['(img_h, img_w, img_c)', 'np.uint16'], {}), '((img_h, img_w, img_c), np.uint16)\n', (334, 368), True, 'import numpy as np\n')] |
from __future__ import print_function, absolute_import
import posixpath
import pickle
import numpy as np
import numpy.testing as npt
from utils import *
def test_bytes(hdfs, request):
testname = request.node.name
fname = posixpath.join(TEST_DIR, testname)
data = b'a' * 10 * 2**20
data += b'b' * 10 * 2**20
data += b'c' * 10 * 2**20
with hdfs.open(fname, 'w', replication=1) as f:
f.write(data)
with hdfs.open(fname, 'r') as f:
read = f.read(len(data))
assert len(data) == len(read)
assert read == data
def test_pickle(hdfs, request):
testname = request.node.name
fname = posixpath.join(TEST_DIR, testname)
arr = np.random.normal(10, 2, size=(100, 100))
data = pickle.dumps(arr)
with hdfs.open(fname, 'w') as f:
f.write(data)
with hdfs.open(fname, 'r') as f:
read = f.read(len(data))
assert len(data) == len(read)
assert data == read
read = pickle.loads(read)
npt.assert_equal(arr, read)
def test_read_nonexistent(hdfs, request):
with pytest.raises(IOError):
f = hdfs.open('/tmp/NOFILE', 'r')
def test_open_for_write_read(hdfs, request):
testname = request.node.name
fname = posixpath.join(TEST_DIR, testname)
f = hdfs.open(fname, 'w')
with pytest.raises(IOError):
f.read()
f.close()
def test_open_for_read_write(hdfs, request):
testname = request.node.name
fname = posixpath.join(TEST_DIR, testname)
data = b'a' * 10 * 2**20
with hdfs.open(fname, 'w') as f:
f.write(data)
f = hdfs.open(fname, 'r')
with pytest.raises(IOError):
f.write(data)
f.close()
| [
"numpy.random.normal",
"posixpath.join",
"numpy.testing.assert_equal",
"pickle.dumps",
"pickle.loads"
] | [((234, 268), 'posixpath.join', 'posixpath.join', (['TEST_DIR', 'testname'], {}), '(TEST_DIR, testname)\n', (248, 268), False, 'import posixpath\n'), ((650, 684), 'posixpath.join', 'posixpath.join', (['TEST_DIR', 'testname'], {}), '(TEST_DIR, testname)\n', (664, 684), False, 'import posixpath\n'), ((696, 736), 'numpy.random.normal', 'np.random.normal', (['(10)', '(2)'], {'size': '(100, 100)'}), '(10, 2, size=(100, 100))\n', (712, 736), True, 'import numpy as np\n'), ((748, 765), 'pickle.dumps', 'pickle.dumps', (['arr'], {}), '(arr)\n', (760, 765), False, 'import pickle\n'), ((1244, 1278), 'posixpath.join', 'posixpath.join', (['TEST_DIR', 'testname'], {}), '(TEST_DIR, testname)\n', (1258, 1278), False, 'import posixpath\n'), ((1466, 1500), 'posixpath.join', 'posixpath.join', (['TEST_DIR', 'testname'], {}), '(TEST_DIR, testname)\n', (1480, 1500), False, 'import posixpath\n'), ((978, 996), 'pickle.loads', 'pickle.loads', (['read'], {}), '(read)\n', (990, 996), False, 'import pickle\n'), ((1005, 1032), 'numpy.testing.assert_equal', 'npt.assert_equal', (['arr', 'read'], {}), '(arr, read)\n', (1021, 1032), True, 'import numpy.testing as npt\n')] |
# adapted from yolor/test.py
import argparse
import glob
import json
import os
from pathlib import Path
import numpy as np
import torch
import yaml
from tqdm import tqdm
from yolor.utils.google_utils import attempt_load
from yolor.utils.datasets import create_dataloader
from yolor.utils.general import coco80_to_coco91_class, check_dataset, check_file, check_img_size, box_iou, \
non_max_suppression, scale_coords, xyxy2xywh, xywh2xyxy, clip_coords, set_logging, increment_path
from yolor.utils.loss import compute_loss
from yolor.utils.metrics import ap_per_class,compute_ap
from yolor.utils.plots import plot_images, output_to_target
from yolor.utils.torch_utils import select_device, time_synchronized
from yolor.models.models import *
def load_classes(path):
# Loads *.names file at 'path'
with open(path, 'r') as f:
names = f.read().split('\n')
return list(filter(None, names)) # filter removes empty strings (such as last line)
################################################################################
# load objseeker library
import joblib
from clean_eval import clean_eval
from objseeker.defense import YOLO_wrapper,ObjSeekerModel
#set confidence threshold for saving raw detection results
SAVE_RAW_BASE_CONF_THRES = 0.001#0.01#0.001
SAVE_RAW_MASK_CONF_THRES = 0.1#0.6#0.1
################################################################################
def test(data,
weights=None,
batch_size=16,
imgsz=640,
#conf_thres=0.001,
#iou_thres=0.6, # for NMS
#save_json=False,
single_cls=False,
augment=False,
verbose=False,
model=None,
dataloader=None,
save_dir=Path(''), # for saving images
save_txt=False, # for auto-labelling
save_conf=False,
plots=True,
log_imgs=0,
base_output_list=None,
raw_masked_output_list=None,
args=None): # number of logged images
# Initialize/load model and set device
training = model is not None
if training: # called by train.py
device = next(model.parameters()).device # get model device
else: # called directly
set_logging()
if isinstance(args.device,str):
device = select_device(args.device, batch_size=batch_size)
else:
device = args.device
save_txt = args.save_txt # save *.txt labels
# Directories
#save_dir = Path(increment_path(Path(args.project) / args.name, exist_ok=args.exist_ok)) # increment run
#(save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
save_dir = None
# Load model
model = Darknet(args.cfg).to(device)
# load model
try:
ckpt = torch.load(weights[0], map_location=device) # load checkpoint
ckpt['model'] = {k: v for k, v in ckpt['model'].items() if model.state_dict()[k].numel() == v.numel()}
model.load_state_dict(ckpt['model'], strict=False)
except:
load_darknet_weights(model, weights[0])
imgsz = check_img_size(imgsz, s=64) # check img_size
# Half
half = device.type != 'cpu' # half precision only supported on CUDA
if half:
model.half()
# Configure
model.eval()
is_coco = data.endswith('coco.yaml') # is COCO dataset
with open(data) as f:
data = yaml.load(f, Loader=yaml.FullLoader) # model dict
check_dataset(data) # check
nc = 1 if single_cls else int(data['nc']) # number of classes
iouv = torch.linspace(0.5, 0.95, 10).to(device) # iou vector for mAP@0.5:0.95
niou = iouv.numel()
# Logging
log_imgs, wandb = min(log_imgs, 100), None # ceil
try:
import wandb # Weights & Biases
except ImportError:
log_imgs = 0
# Dataloader
if not training:
img = torch.zeros((1, 3, imgsz, imgsz), device=device) # init img
_ = model(img.half() if half else img) if device.type != 'cpu' else None # run once
path = data['test'] if args.task == 'test' else data['val'] # path to val/test images
dataloader = create_dataloader(path, imgsz, batch_size, 64, args, pad=0.5, rect=True)[0]
seen = 0
try:
names = model.names if hasattr(model, 'names') else model.module.names
except:
names = load_classes(args.names)
coco91class = coco80_to_coco91_class()
s = ('%20s' + '%12s' * 6) % ('Class', 'Images', 'Targets', 'P', 'R', 'mAP@.5', 'mAP@.5:.95')
p, r, f1, mp, mr, map50, map, t0, t1 = 0., 0., 0., 0., 0., 0., 0., 0., 0.
loss = torch.zeros(3, device=device)
jdict, stats, ap, ap_class, wandb_images = [], [], [], [], []
################################################################################
# basic objseeker setup
args.device = device
# build model
model = YOLO_wrapper(model)
if args.load_raw:
model = None
model = ObjSeekerModel(model,args)
if args.certify:
cr_res = [0,0,0,0,0]#far_vul_cnt_iou_total,far_vul_cnt_total,close_vul_cnt_total,over_vul_cnt_total,obj_cnt_total
if not args.map:
dataloader = tqdm(dataloader)
for batch_i, (img, targets, paths, shapes) in enumerate(dataloader):
img = img.to(device, non_blocking=True)
img = img.half() if half else img.float() # uint8 to fp16/32
img /= 255.0 # 0 - 255 to 0.0 - 1.0
targets = targets.to(device)
nb, _, height, width = img.shape # batch size, channels, height, width
whwh = torch.Tensor([width, height, width, height]).to(device)
# Disable gradients
with torch.no_grad():
# inference
if args.one_line: # do inference with one-line function call
output = model(img)
else: #do inference with precomputed detections
if args.load_raw: # if we already loaded the precomputed detection
raw_masked_output = raw_masked_output_list[batch_i]
base_output = base_output_list[batch_i]
else: # otherwise we generate the precomputed detection now
raw_masked_output = model.get_raw_masked_boxes(img)
base_output = model.base_model(img,conf_thres=args.base_conf_thres,nms_iou_thres=args.base_nms_iou_thres)
if args.save_raw: # if we want to save the raw detection to the disk
raw_masked_output_list.append(raw_masked_output)
base_output_list.append([x.detach().cpu() for x in base_output])
# run the inference with precomputed detections
output = model(img,raw_masked_output_precomputed=raw_masked_output,base_output_precomputed=base_output)
if args.certify: # gather certification stats
ground_truth = []
for img_i in range(len(img)):
labels = targets[targets[:, 0] == img_i, 1:] # ground truth labels for this image
labels[:, 1:5] = xywh2xyxy(labels[:, 1:5]) * whwh
labels = labels[:,[1,2,3,4,0]] # -> xyxy cls
ground_truth.append(labels)
res = model.certify(img,raw_masked_output,ground_truth,args.patch_size,args.certify_iou_thres,args.certify_ioa_thres)
cr_res = [cr_res[x]+res[x] for x in range(5)]
if args.save_det: # dump the detection results
for si, pred in enumerate(output):
labels = targets[targets[:, 0] == si, 1:]
nl = len(labels)
tcls = labels[:, 0].tolist() if nl else [] # target class
seen += 1
if len(pred) == 0:
if nl:
stats.append((torch.zeros(0, niou, dtype=torch.bool), torch.Tensor(), torch.Tensor(), tcls))
continue
clip_coords(pred, (height, width))
# Append to text file for voc
path = Path(paths[si])
if 'voc' in args.data:
x = pred.clone()
x[:, :4] = scale_coords(img[si].shape[1:], x[:, :4], shapes[si][0], shapes[si][1]) # to original
with open(os.path.join(args.clean_dir,path.stem + '.txt'), 'w') as f:
for *xyxy, conf, cls in x:
if 'voc' in args.data and cls>19:
continue
xyxy = torch.tensor(xyxy).tolist()
line = (cls, conf,*xyxy)
f.write(('%g ' * len(line)).rstrip() % line + '\n')
# Append to pycocotools JSON dictionary
elif 'coco' in args.data:
# [{"image_id": 42, "category_id": 18, "bbox": [258.15, 41.29, 348.26, 243.78], "score": 0.236}, ...
image_id = int(path.stem) if path.stem.isnumeric() else path.stem
box = pred[:, :4].clone() # xyxy
scale_coords(img[si].shape[1:], box, shapes[si][0], shapes[si][1]) # to original shape
box = xyxy2xywh(box) # xywh
box[:, :2] -= box[:, 2:] / 2 # xy center to top-left corner
for p, b in zip(pred.tolist(), box.tolist()):
jdict.append({'image_id': image_id,
'category_id': coco91class[int(p[5])] if is_coco else int(p[5]),
'bbox': [round(x, 3) for x in b],
'score': round(p[4], 5)})
if 'coco' in args.data:
pred_json = os.path.join(args.clean_dir,'coco_predictions.bbox.json') # predictions json
if len(jdict)>0:
with open(pred_json, 'w') as f:
json.dump(jdict, f)
if args.certify: # print robustness stats
obj_cnt_total = cr_res[-1]
cr_res = cr_res[:4]
cr_res = [100-x/obj_cnt_total*100 for x in cr_res]
print(cr_res)
print('Certified recall results:')
print('Far-patch (IoU): {:.2f}%; Far-patch (IoA): {:.2f}%; Close-patch (IoA): {:.2f}%; Over-patch (IoA): {:.2f}%'.format(*cr_res))
else:
cr_res = []
return cr_res,base_output_list,raw_masked_output_list
if __name__ == '__main__':
parser = argparse.ArgumentParser(prog='test.py')
# original arguments from yolo
parser.add_argument('--weights', nargs='+', type=str, default='yolor_p6.pt', help='model.pt path(s)')
parser.add_argument('--data', type=str, default='data/coco.yaml', help='*.data path')
parser.add_argument('--batch-size', type=int, default=8, help='size of each image batch')
parser.add_argument('--img-size', type=int, default=1280, help='inference size (pixels)')
#parser.add_argument('--conf-thres', type=float, default=0.001, help='object confidence threshold') # renamed to base-conf-thres (see below)
#parser.add_argument('--iou-thres', type=float, default=0.65, help='IOU threshold for NMS') # renamed to base-nms-iou-thres (see below)
parser.add_argument('--task', default='val', help="'val', 'test', 'study'")
parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
parser.add_argument('--single-cls', action='store_true', help='treat as single-class dataset')
parser.add_argument('--augment', action='store_true', help='augmented inference')
parser.add_argument('--verbose', action='store_true', help='report mAP by class')
parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
parser.add_argument('--save-json', action='store_true', help='save a cocoapi-compatible JSON results file')
parser.add_argument('--project', default='runs/test', help='save to project/name')
parser.add_argument('--name', default='exp', help='save to project/name')
parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
parser.add_argument('--cfg', type=str, default='yolor/cfg/yolor_p6.cfg', help='*.cfg path')
parser.add_argument('--names', type=str, default='yolor/data/coco.names', help='*.cfg path')
# objectseeker argumenets
# we call vanilla object detector "base detector"
parser.add_argument('--base-conf-thres', type=float, default=0.6, help='conf thres of base detector')
parser.add_argument('--base-nms-iou-thres', type=float, default=0.65, help='IoU threshold for NMS in base object detector')
parser.add_argument('--num-line', type=int, default=30, help='number of lines $k$')
parser.add_argument('--masked-conf-thres', type=float, default=0.8, help='conf thres for masked predictions ($tau_mask$)')
parser.add_argument('--pruning-mode', type=str, default='ioa', help='ioa or iou')
parser.add_argument('--ioa-prune-thres', type=float, default=0.6, help='ioa threshold for box filtering/pruning ($tau_ioa$)')
parser.add_argument('--iou-prune-thres', type=float, default=0.8, help='iou threshold for box filtering/pruning ($tau_iou$; not used in the main body; see appendix)')
parser.add_argument('--match-class', action='store_true', help='whether consider class label in the pruning (will affect robustness property)')
parser.add_argument('--alpha', type=float, default=0.8, help='minimum masked confidence threshold (used for clean AP calculation; see appendix)')
parser.add_argument('--beta', type=float, default=0.5, help='(used for clean AP calculation; see appendix)')
# certification arguments
parser.add_argument('--certify-iou-thres', type=float, default=0.0, help='iou thres for robustness certification')
parser.add_argument('--certify-ioa-thres', type=float, default=0.5, help='ioa thres for robustness certification')
parser.add_argument('--patch-size', type=float, default=0.01, help='patch size, in percentage of image pixels')
# functional arguments
parser.add_argument('--dump-dir', type=str, default='dump', help='root dir for precomputed raw detections')
parser.add_argument('--clean-dir', type=str, default='clean_det', help='dir for saving clean detection results')
parser.add_argument('--save-det', action='store_true', help='whether to save detection results')
parser.add_argument('--save-raw', action='store_true', help='whether to save raw detection results')
parser.add_argument('--load-raw', action='store_true', help='whether to load precomputed raw detection')
parser.add_argument('--one-line', action='store_true', help='whether use one-line inference mode without any precomputing')
parser.add_argument('--certify', action='store_true', help='whether to certification')
parser.add_argument('--map', action='store_true', help='whether to calculate ap (need to change the confidence threshold)')
args = parser.parse_args()
#args.save_json |= args.data.endswith('coco.yaml')
args.data = check_file(args.data) # check file
print(args)
base_output_list = None
raw_masked_output_list = None
# setup directory, load/save detection results
if args.save_raw or args.load_raw:
DUMP_DIR = args.dump_dir
if not os.path.exists(DUMP_DIR):
os.mkdir(DUMP_DIR)
# a dumb way to extract model and dataset names
model_name = args.weights[0].split('/')[-1].split('.')[0]
dataset_name = args.data.split('/')[-1].split('.')[0]
prefix = 'raw_masked_output_{}_{}_{}_{}_{}'.format(dataset_name,model_name,SAVE_RAW_MASK_CONF_THRES,args.base_nms_iou_thres,args.batch_size)
DUMP_DIR_MASK = os.path.join(DUMP_DIR,prefix)
if not os.path.exists(DUMP_DIR_MASK):
os.mkdir(DUMP_DIR_MASK)
prefix = 'base_output_{}_{}_{}_{}_{}'.format(dataset_name,model_name,SAVE_RAW_BASE_CONF_THRES,args.base_nms_iou_thres,args.batch_size)
DUMP_DIR_BASE = os.path.join(DUMP_DIR,prefix)
if not os.path.exists(DUMP_DIR_BASE):
os.mkdir(DUMP_DIR_BASE)
if args.load_raw:# load saved detection results
base_output_list = joblib.load(os.path.join(DUMP_DIR_BASE,'base_output_list.z'))
if args.num_line>0:
raw_masked_output_list = joblib.load(os.path.join(DUMP_DIR_MASK,'raw_masked_output_list_{}.z'.format(args.num_line)))
else: # vanilla predictions
raw_masked_output_list = [None for i in range(len(base_output_list))]
else:# prepare to gather raw detection results and save
base_output_list = [] # detection results for vanilla object detectors on the original images
raw_masked_output_list = [] # detection results on masked images
# set the flags to the saving mode
args.base_conf_thres = SAVE_RAW_BASE_CONF_THRES
#args.conf_thres = SAVE_RAW_BASE_CONF_THRES
args.masked_conf_thres = SAVE_RAW_MASK_CONF_THRES
if args.map:
conf_thres_list = np.linspace(0,0.99,100)[::-1] # the list of confidence thresholds to vary
else:
conf_thres_list = [args.base_conf_thres]
args.save_det = args.save_det or args.map
if args.save_det: #setup save directory
CLEAN_DIR = args.clean_dir
CLEAN_BASE_DIR = CLEAN_DIR
if not os.path.exists(CLEAN_DIR):
os.mkdir(CLEAN_DIR)
CLEAN_DIR = os.path.join(CLEAN_DIR,dataset_name)
if not os.path.exists(CLEAN_DIR):
os.mkdir(CLEAN_DIR)
match_class = 'cls' if args.match_class else 'nocls'
CLEAN_DIR = os.path.join(CLEAN_DIR,'{}_{}_{}_{}_{}_{}'.format(model_name,args.num_line,args.ioa_prune_thres,args.iou_prune_thres,match_class,args.pruning_mode))
if not os.path.exists(CLEAN_DIR):
os.mkdir(CLEAN_DIR)
for conf in tqdm(conf_thres_list):
args.base_conf_thres = conf
if args.map:
args.masked_conf_thres = max(args.alpha,conf + (1-conf)*args.beta) # get masked confidence threshold # see appendix for more details
if args.save_det:
args.clean_dir = os.path.join(CLEAN_DIR,'{:.3f}_{:.5f}'.format(conf,args.masked_conf_thres))
if not os.path.exists(args.clean_dir):
os.mkdir(args.clean_dir)
cr_res,base_output_list,raw_masked_output_list = test(args.data,
args.weights,
args.batch_size,
args.img_size,
args.single_cls,
args.augment,
args.verbose,
base_output_list=base_output_list,
raw_masked_output_list=raw_masked_output_list,
args=args
)
if args.save_raw: # dump detections
joblib.dump(raw_masked_output_list,os.path.join(DUMP_DIR_MASK,'raw_masked_output_list_{}.z'.format(args.num_line)))
joblib.dump(base_output_list,os.path.join(DUMP_DIR_BASE,'base_output_list.z'))
if args.certify:
match_class = 'cls' if args.match_class else 'nocls'
res_dir = 'results_{}'.format(args.pruning_mode)
if not os.path.exists(res_dir):
os.mkdir(res_dir)
if args.pruning_mode == 'ioa':
joblib.dump(cr_res,'results_{}/cr_{}_{}_{}_{}_{}_{}_{}_{}.z'.format(args.pruning_mode,dataset_name,model_name,args.num_line,args.masked_conf_thres,args.ioa_prune_thres,args.certify_ioa_thres,args.patch_size,match_class))
elif args.pruning_mode == 'iou':
joblib.dump(cr_res,'results_{}/cr_{}_{}_{}_{}_{}_{}_{}_{}_{}_{}.z'.format(args.pruning_mode,dataset_name,model_name,args.num_line,args.masked_conf_thres,args.ioa_prune_thres,args.certify_ioa_thres,args.patch_size,match_class,args.iou_prune_thres,args.certify_iou_thres))
if args.save_det:
print('calling clean_eval.py...')
args.save=True
args.preprocess=True
args.load=False
args.single = not args.map
args.dataset = dataset_name
args.model = model_name
args.clean_dir = CLEAN_BASE_DIR
clean_eval(args)
| [
"yolor.utils.general.scale_coords",
"yolor.utils.general.coco80_to_coco91_class",
"yolor.utils.general.check_file",
"yolor.utils.general.set_logging",
"yaml.load",
"objseeker.defense.YOLO_wrapper",
"yolor.utils.general.check_img_size",
"os.path.exists",
"argparse.ArgumentParser",
"pathlib.Path",
... | [((1713, 1721), 'pathlib.Path', 'Path', (['""""""'], {}), "('')\n", (1717, 1721), False, 'from pathlib import Path\n'), ((3492, 3511), 'yolor.utils.general.check_dataset', 'check_dataset', (['data'], {}), '(data)\n', (3505, 3511), False, 'from yolor.utils.general import coco80_to_coco91_class, check_dataset, check_file, check_img_size, box_iou, non_max_suppression, scale_coords, xyxy2xywh, xywh2xyxy, clip_coords, set_logging, increment_path\n'), ((4432, 4456), 'yolor.utils.general.coco80_to_coco91_class', 'coco80_to_coco91_class', ([], {}), '()\n', (4454, 4456), False, 'from yolor.utils.general import coco80_to_coco91_class, check_dataset, check_file, check_img_size, box_iou, non_max_suppression, scale_coords, xyxy2xywh, xywh2xyxy, clip_coords, set_logging, increment_path\n'), ((4643, 4672), 'torch.zeros', 'torch.zeros', (['(3)'], {'device': 'device'}), '(3, device=device)\n', (4654, 4672), False, 'import torch\n'), ((4909, 4928), 'objseeker.defense.YOLO_wrapper', 'YOLO_wrapper', (['model'], {}), '(model)\n', (4921, 4928), False, 'from objseeker.defense import YOLO_wrapper, ObjSeekerModel\n'), ((4984, 5011), 'objseeker.defense.ObjSeekerModel', 'ObjSeekerModel', (['model', 'args'], {}), '(model, args)\n', (4998, 5011), False, 'from objseeker.defense import YOLO_wrapper, ObjSeekerModel\n'), ((10404, 10443), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'prog': '"""test.py"""'}), "(prog='test.py')\n", (10427, 10443), False, 'import argparse\n'), ((15115, 15136), 'yolor.utils.general.check_file', 'check_file', (['args.data'], {}), '(args.data)\n', (15125, 15136), False, 'from yolor.utils.general import coco80_to_coco91_class, check_dataset, check_file, check_img_size, box_iou, non_max_suppression, scale_coords, xyxy2xywh, xywh2xyxy, clip_coords, set_logging, increment_path\n'), ((17992, 18013), 'tqdm.tqdm', 'tqdm', (['conf_thres_list'], {}), '(conf_thres_list)\n', (17996, 18013), False, 'from tqdm import tqdm\n'), ((2200, 2213), 'yolor.utils.general.set_logging', 'set_logging', ([], {}), '()\n', (2211, 2213), False, 'from yolor.utils.general import coco80_to_coco91_class, check_dataset, check_file, check_img_size, box_iou, non_max_suppression, scale_coords, xyxy2xywh, xywh2xyxy, clip_coords, set_logging, increment_path\n'), ((3137, 3164), 'yolor.utils.general.check_img_size', 'check_img_size', (['imgsz'], {'s': '(64)'}), '(imgsz, s=64)\n', (3151, 3164), False, 'from yolor.utils.general import coco80_to_coco91_class, check_dataset, check_file, check_img_size, box_iou, non_max_suppression, scale_coords, xyxy2xywh, xywh2xyxy, clip_coords, set_logging, increment_path\n'), ((3437, 3473), 'yaml.load', 'yaml.load', (['f'], {'Loader': 'yaml.FullLoader'}), '(f, Loader=yaml.FullLoader)\n', (3446, 3473), False, 'import yaml\n'), ((3913, 3961), 'torch.zeros', 'torch.zeros', (['(1, 3, imgsz, imgsz)'], {'device': 'device'}), '((1, 3, imgsz, imgsz), device=device)\n', (3924, 3961), False, 'import torch\n'), ((5197, 5213), 'tqdm.tqdm', 'tqdm', (['dataloader'], {}), '(dataloader)\n', (5201, 5213), False, 'from tqdm import tqdm\n'), ((15786, 15816), 'os.path.join', 'os.path.join', (['DUMP_DIR', 'prefix'], {}), '(DUMP_DIR, prefix)\n', (15798, 15816), False, 'import os\n'), ((16072, 16102), 'os.path.join', 'os.path.join', (['DUMP_DIR', 'prefix'], {}), '(DUMP_DIR, prefix)\n', (16084, 16102), False, 'import os\n'), ((17550, 17587), 'os.path.join', 'os.path.join', (['CLEAN_DIR', 'dataset_name'], {}), '(CLEAN_DIR, dataset_name)\n', (17562, 17587), False, 'import os\n'), ((20182, 20198), 'clean_eval.clean_eval', 'clean_eval', (['args'], {}), '(args)\n', (20192, 20198), False, 'from clean_eval import clean_eval\n'), ((2275, 2324), 'yolor.utils.torch_utils.select_device', 'select_device', (['args.device'], {'batch_size': 'batch_size'}), '(args.device, batch_size=batch_size)\n', (2288, 2324), False, 'from yolor.utils.torch_utils import select_device, time_synchronized\n'), ((2812, 2855), 'torch.load', 'torch.load', (['weights[0]'], {'map_location': 'device'}), '(weights[0], map_location=device)\n', (2822, 2855), False, 'import torch\n'), ((3599, 3628), 'torch.linspace', 'torch.linspace', (['(0.5)', '(0.95)', '(10)'], {}), '(0.5, 0.95, 10)\n', (3613, 3628), False, 'import torch\n'), ((4183, 4255), 'yolor.utils.datasets.create_dataloader', 'create_dataloader', (['path', 'imgsz', 'batch_size', '(64)', 'args'], {'pad': '(0.5)', 'rect': '(True)'}), '(path, imgsz, batch_size, 64, args, pad=0.5, rect=True)\n', (4200, 4255), False, 'from yolor.utils.datasets import create_dataloader\n'), ((5680, 5695), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (5693, 5695), False, 'import torch\n'), ((15370, 15394), 'os.path.exists', 'os.path.exists', (['DUMP_DIR'], {}), '(DUMP_DIR)\n', (15384, 15394), False, 'import os\n'), ((15408, 15426), 'os.mkdir', 'os.mkdir', (['DUMP_DIR'], {}), '(DUMP_DIR)\n', (15416, 15426), False, 'import os\n'), ((15831, 15860), 'os.path.exists', 'os.path.exists', (['DUMP_DIR_MASK'], {}), '(DUMP_DIR_MASK)\n', (15845, 15860), False, 'import os\n'), ((15874, 15897), 'os.mkdir', 'os.mkdir', (['DUMP_DIR_MASK'], {}), '(DUMP_DIR_MASK)\n', (15882, 15897), False, 'import os\n'), ((16117, 16146), 'os.path.exists', 'os.path.exists', (['DUMP_DIR_BASE'], {}), '(DUMP_DIR_BASE)\n', (16131, 16146), False, 'import os\n'), ((16160, 16183), 'os.mkdir', 'os.mkdir', (['DUMP_DIR_BASE'], {}), '(DUMP_DIR_BASE)\n', (16168, 16183), False, 'import os\n'), ((17161, 17186), 'numpy.linspace', 'np.linspace', (['(0)', '(0.99)', '(100)'], {}), '(0, 0.99, 100)\n', (17172, 17186), True, 'import numpy as np\n'), ((17471, 17496), 'os.path.exists', 'os.path.exists', (['CLEAN_DIR'], {}), '(CLEAN_DIR)\n', (17485, 17496), False, 'import os\n'), ((17510, 17529), 'os.mkdir', 'os.mkdir', (['CLEAN_DIR'], {}), '(CLEAN_DIR)\n', (17518, 17529), False, 'import os\n'), ((17602, 17627), 'os.path.exists', 'os.path.exists', (['CLEAN_DIR'], {}), '(CLEAN_DIR)\n', (17616, 17627), False, 'import os\n'), ((17641, 17660), 'os.mkdir', 'os.mkdir', (['CLEAN_DIR'], {}), '(CLEAN_DIR)\n', (17649, 17660), False, 'import os\n'), ((17915, 17940), 'os.path.exists', 'os.path.exists', (['CLEAN_DIR'], {}), '(CLEAN_DIR)\n', (17929, 17940), False, 'import os\n'), ((17954, 17973), 'os.mkdir', 'os.mkdir', (['CLEAN_DIR'], {}), '(CLEAN_DIR)\n', (17962, 17973), False, 'import os\n'), ((19033, 19082), 'os.path.join', 'os.path.join', (['DUMP_DIR_BASE', '"""base_output_list.z"""'], {}), "(DUMP_DIR_BASE, 'base_output_list.z')\n", (19045, 19082), False, 'import os\n'), ((19237, 19260), 'os.path.exists', 'os.path.exists', (['res_dir'], {}), '(res_dir)\n', (19251, 19260), False, 'import os\n'), ((19274, 19291), 'os.mkdir', 'os.mkdir', (['res_dir'], {}), '(res_dir)\n', (19282, 19291), False, 'import os\n'), ((5583, 5627), 'torch.Tensor', 'torch.Tensor', (['[width, height, width, height]'], {}), '([width, height, width, height])\n', (5595, 5627), False, 'import torch\n'), ((7908, 7942), 'yolor.utils.general.clip_coords', 'clip_coords', (['pred', '(height, width)'], {}), '(pred, (height, width))\n', (7919, 7942), False, 'from yolor.utils.general import coco80_to_coco91_class, check_dataset, check_file, check_img_size, box_iou, non_max_suppression, scale_coords, xyxy2xywh, xywh2xyxy, clip_coords, set_logging, increment_path\n'), ((8013, 8028), 'pathlib.Path', 'Path', (['paths[si]'], {}), '(paths[si])\n', (8017, 8028), False, 'from pathlib import Path\n'), ((9692, 9750), 'os.path.join', 'os.path.join', (['args.clean_dir', '"""coco_predictions.bbox.json"""'], {}), "(args.clean_dir, 'coco_predictions.bbox.json')\n", (9704, 9750), False, 'import os\n'), ((16294, 16343), 'os.path.join', 'os.path.join', (['DUMP_DIR_BASE', '"""base_output_list.z"""'], {}), "(DUMP_DIR_BASE, 'base_output_list.z')\n", (16306, 16343), False, 'import os\n'), ((18368, 18398), 'os.path.exists', 'os.path.exists', (['args.clean_dir'], {}), '(args.clean_dir)\n', (18382, 18398), False, 'import os\n'), ((18416, 18440), 'os.mkdir', 'os.mkdir', (['args.clean_dir'], {}), '(args.clean_dir)\n', (18424, 18440), False, 'import os\n'), ((7060, 7085), 'yolor.utils.general.xywh2xyxy', 'xywh2xyxy', (['labels[:, 1:5]'], {}), '(labels[:, 1:5])\n', (7069, 7085), False, 'from yolor.utils.general import coco80_to_coco91_class, check_dataset, check_file, check_img_size, box_iou, non_max_suppression, scale_coords, xyxy2xywh, xywh2xyxy, clip_coords, set_logging, increment_path\n'), ((8136, 8207), 'yolor.utils.general.scale_coords', 'scale_coords', (['img[si].shape[1:]', 'x[:, :4]', 'shapes[si][0]', 'shapes[si][1]'], {}), '(img[si].shape[1:], x[:, :4], shapes[si][0], shapes[si][1])\n', (8148, 8207), False, 'from yolor.utils.general import coco80_to_coco91_class, check_dataset, check_file, check_img_size, box_iou, non_max_suppression, scale_coords, xyxy2xywh, xywh2xyxy, clip_coords, set_logging, increment_path\n'), ((9043, 9109), 'yolor.utils.general.scale_coords', 'scale_coords', (['img[si].shape[1:]', 'box', 'shapes[si][0]', 'shapes[si][1]'], {}), '(img[si].shape[1:], box, shapes[si][0], shapes[si][1])\n', (9055, 9109), False, 'from yolor.utils.general import coco80_to_coco91_class, check_dataset, check_file, check_img_size, box_iou, non_max_suppression, scale_coords, xyxy2xywh, xywh2xyxy, clip_coords, set_logging, increment_path\n'), ((9157, 9171), 'yolor.utils.general.xyxy2xywh', 'xyxy2xywh', (['box'], {}), '(box)\n', (9166, 9171), False, 'from yolor.utils.general import coco80_to_coco91_class, check_dataset, check_file, check_img_size, box_iou, non_max_suppression, scale_coords, xyxy2xywh, xywh2xyxy, clip_coords, set_logging, increment_path\n'), ((9879, 9898), 'json.dump', 'json.dump', (['jdict', 'f'], {}), '(jdict, f)\n', (9888, 9898), False, 'import json\n'), ((8253, 8301), 'os.path.join', 'os.path.join', (['args.clean_dir', "(path.stem + '.txt')"], {}), "(args.clean_dir, path.stem + '.txt')\n", (8265, 8301), False, 'import os\n'), ((7784, 7822), 'torch.zeros', 'torch.zeros', (['(0)', 'niou'], {'dtype': 'torch.bool'}), '(0, niou, dtype=torch.bool)\n', (7795, 7822), False, 'import torch\n'), ((7824, 7838), 'torch.Tensor', 'torch.Tensor', ([], {}), '()\n', (7836, 7838), False, 'import torch\n'), ((7840, 7854), 'torch.Tensor', 'torch.Tensor', ([], {}), '()\n', (7852, 7854), False, 'import torch\n'), ((8502, 8520), 'torch.tensor', 'torch.tensor', (['xyxy'], {}), '(xyxy)\n', (8514, 8520), False, 'import torch\n')] |
"""
============================
Typing (:mod:`numpy.typing`)
============================
.. warning::
Some of the types in this module rely on features only present in
the standard library in Python 3.8 and greater. If you want to use
these types in earlier versions of Python, you should install the
typing-extensions_ package.
Large parts of the NumPy API have PEP-484-style type annotations. In
addition, the following type aliases are available for users.
- ``typing.ArrayLike``: objects that can be converted to arrays
- ``typing.DTypeLike``: objects that can be converted to dtypes
Roughly speaking, ``typing.ArrayLike`` is "objects that can be used as
inputs to ``np.array``" and ``typing.DTypeLike`` is "objects that can
be used as inputs to ``np.dtype``".
.. _typing-extensions: https://pypi.org/project/typing-extensions/
Differences from the runtime NumPy API
--------------------------------------
NumPy is very flexible. Trying to describe the full range of
possibilities statically would result in types that are not very
helpful. For that reason, the typed NumPy API is often stricter than
the runtime NumPy API. This section describes some notable
differences.
ArrayLike
~~~~~~~~~
The ``ArrayLike`` type tries to avoid creating object arrays. For
example,
.. code-block:: python
>>> np.array(x**2 for x in range(10))
array(<generator object <genexpr> at 0x10c004cd0>, dtype=object)
is valid NumPy code which will create a 0-dimensional object
array. Type checkers will complain about the above example when using
the NumPy types however. If you really intended to do the above, then
you can either use a ``# type: ignore`` comment:
.. code-block:: python
>>> np.array(x**2 for x in range(10)) # type: ignore
or explicitly type the array like object as ``Any``:
.. code-block:: python
>>> from typing import Any
>>> array_like: Any = (x**2 for x in range(10))
>>> np.array(array_like)
array(<generator object <genexpr> at 0x1192741d0>, dtype=object)
ndarray
~~~~~~~
It's possible to mutate the dtype of an array at runtime. For example,
the following code is valid:
.. code-block:: python
>>> x = np.array([1, 2])
>>> x.dtype = np.bool_
This sort of mutation is not allowed by the types. Users who want to
write statically typed code should insted use the `numpy.ndarray.view`
method to create a view of the array with a different dtype.
dtype
~~~~~
The ``DTypeLike`` type tries to avoid creation of dtype objects using
dictionary of fields like below:
.. code-block:: python
>>> x = np.dtype({"field1": (float, 1), "field2": (int, 3)})
Although this is valid Numpy code, the type checker will complain about it,
since its usage is discouraged.
Please see : https://numpy.org/devdocs/reference/arrays.dtypes.html
NBitBase
~~~~~~~~
.. autoclass:: numpy.typing.NBitBase
"""
from typing import TYPE_CHECKING
if TYPE_CHECKING:
import sys
if sys.version_info >= (3, 8):
from typing import final
else:
from typing_extensions import final
else:
def final(f): return f
@final # Dissallow the creation of arbitrary `NBitBase` subclasses
class NBitBase:
"""
An object representing `numpy.number` precision during static type checking.
Used exclusively for the purpose static type checking, `NBitBase`
represents the base of a hierachieral set of subclasses.
Each subsequent subclass is herein used for representing a lower level
of precision, *e.g.* ``64Bit > 32Bit > 16Bit``.
Examples
--------
Below is a typical usage example: `NBitBase` is herein used for annotating a
function that takes a float and integer of arbitrary precision as arguments
and returns a new float of whichever precision is largest
(*e.g.* ``np.float16 + np.int64 -> np.float64``).
.. code-block:: python
>>> from typing import TypeVar, TYPE_CHECKING
>>> import numpy as np
>>> import numpy.typing as npt
>>> T = TypeVar("T", bound=npt.NBitBase)
>>> def add(a: "np.floating[T]", b: "np.integer[T]") -> "np.floating[T]":
... return a + b
>>> a = np.float16()
>>> b = np.int64()
>>> out = add(a, b)
>>> if TYPE_CHECKING:
... reveal_locals()
... # note: Revealed local types are:
... # note: a: numpy.floating[numpy.typing._16Bit*]
... # note: b: numpy.signedinteger[numpy.typing._64Bit*]
... # note: out: numpy.floating[numpy.typing._64Bit*]
"""
def __init_subclass__(cls) -> None:
allowed_names = {
"NBitBase", "_256Bit", "_128Bit", "_96Bit", "_80Bit",
"_64Bit", "_32Bit", "_16Bit", "_8Bit",
}
if cls.__name__ not in allowed_names:
raise TypeError('cannot inherit from final class "NBitBase"')
super().__init_subclass__()
# Silence errors about subclassing a `@final`-decorated class
class _256Bit(NBitBase): ... # type: ignore[misc]
class _128Bit(_256Bit): ... # type: ignore[misc]
class _96Bit(_128Bit): ... # type: ignore[misc]
class _80Bit(_96Bit): ... # type: ignore[misc]
class _64Bit(_80Bit): ... # type: ignore[misc]
class _32Bit(_64Bit): ... # type: ignore[misc]
class _16Bit(_32Bit): ... # type: ignore[misc]
class _8Bit(_16Bit): ... # type: ignore[misc]
# Clean up the namespace
del TYPE_CHECKING, final
from ._scalars import (
_CharLike,
_BoolLike,
_IntLike,
_FloatLike,
_ComplexLike,
_NumberLike,
_ScalarLike,
_VoidLike,
)
from ._array_like import _SupportsArray, ArrayLike
from ._shape import _Shape, _ShapeLike
from ._dtype_like import _SupportsDType, _VoidDTypeLike, DTypeLike
from numpy._pytesttester import PytestTester
test = PytestTester(__name__)
del PytestTester
| [
"numpy._pytesttester.PytestTester"
] | [((5781, 5803), 'numpy._pytesttester.PytestTester', 'PytestTester', (['__name__'], {}), '(__name__)\n', (5793, 5803), False, 'from numpy._pytesttester import PytestTester\n')] |
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 29 12:58:13 2016
@author: benny
"""
from __future__ import division, print_function, absolute_import
import numpy as np
from numpy.testing import (
assert_, TestCase, run_module_suite, assert_array_almost_equal,
assert_raises, assert_allclose, assert_array_equal, assert_equal)
from scikits.odes import ode
from scikits.odes.dopri5 import StatusEnumDOP
class SimpleOscillator():
r"""
Free vibration of a simple oscillator::
m \ddot{u} + k u = 0, u(0) = u_0 \dot{u}(0) \dot{u}_0
Solution::
u(t) = u_0*cos(sqrt(k/m)*t)+\dot{u}_0*sin(sqrt(k/m)*t)/sqrt(k/m)
"""
stop_t = 1 + 0.09
y0 = np.array([1.0, 0.1], float)
k = 4.0
m = 1.0
atol = 1e-6
rtol = 1e-6
def f(self, t, y, out):
tmp = np.zeros((2, 2), float)
tmp[0, 1] = 1.0
tmp[1, 0] = -self.k / self.m
out[:] = np.dot(tmp, y)[:]
def verify(self, t, y):
omega = np.sqrt(self.k / self.m)
u = self.y0[0]*np.cos(omega*t) + self.y0[1]*np.sin(omega*t)/omega
return np.allclose(u, y[0], atol=self.atol, rtol=self.rtol)
class TestDop(TestCase):
def test_dop_oscil(self):
#test calling sequence. End is reached before root is found
prob = SimpleOscillator()
tspan = [0, prob.stop_t]
solver = ode('dopri5', prob.f)
soln = solver.solve(tspan, prob.y0)
assert soln.flag==StatusEnumDOP.SUCCESS, "ERROR: Error occurred"
assert prob.verify(prob.stop_t, soln.values.y[1])
solver = ode('dop853', prob.f)
soln = solver.solve(tspan, prob.y0)
assert soln.flag==StatusEnumDOP.SUCCESS, "ERROR: Error occurred"
assert prob.verify(prob.stop_t, soln.values.y[1])
| [
"numpy.allclose",
"numpy.sqrt",
"scikits.odes.ode",
"numpy.array",
"numpy.zeros",
"numpy.dot",
"numpy.cos",
"numpy.sin"
] | [((682, 709), 'numpy.array', 'np.array', (['[1.0, 0.1]', 'float'], {}), '([1.0, 0.1], float)\n', (690, 709), True, 'import numpy as np\n'), ((810, 833), 'numpy.zeros', 'np.zeros', (['(2, 2)', 'float'], {}), '((2, 2), float)\n', (818, 833), True, 'import numpy as np\n'), ((975, 999), 'numpy.sqrt', 'np.sqrt', (['(self.k / self.m)'], {}), '(self.k / self.m)\n', (982, 999), True, 'import numpy as np\n'), ((1089, 1141), 'numpy.allclose', 'np.allclose', (['u', 'y[0]'], {'atol': 'self.atol', 'rtol': 'self.rtol'}), '(u, y[0], atol=self.atol, rtol=self.rtol)\n', (1100, 1141), True, 'import numpy as np\n'), ((1351, 1372), 'scikits.odes.ode', 'ode', (['"""dopri5"""', 'prob.f'], {}), "('dopri5', prob.f)\n", (1354, 1372), False, 'from scikits.odes import ode\n'), ((1566, 1587), 'scikits.odes.ode', 'ode', (['"""dop853"""', 'prob.f'], {}), "('dop853', prob.f)\n", (1569, 1587), False, 'from scikits.odes import ode\n'), ((912, 926), 'numpy.dot', 'np.dot', (['tmp', 'y'], {}), '(tmp, y)\n', (918, 926), True, 'import numpy as np\n'), ((1023, 1040), 'numpy.cos', 'np.cos', (['(omega * t)'], {}), '(omega * t)\n', (1029, 1040), True, 'import numpy as np\n'), ((1052, 1069), 'numpy.sin', 'np.sin', (['(omega * t)'], {}), '(omega * t)\n', (1058, 1069), True, 'import numpy as np\n')] |
"""
Code inspired from: https://github.com/jchibane/if-net/blob/master/data_processing/voxelized_pointcloud_sampling.py
"""
import utils.implicit_waterproofing as iw
from scipy.spatial import cKDTree as KDTree
import numpy as np
import trimesh
import glob
import os
from os.path import join, split, exists
import argparse
from utils.voxelized_pointcloud_sampling import voxelize
def get_3DSV(mesh):
from opendr.camera import ProjectPoints
from opendr.renderer import DepthRenderer
WIDTH, HEIGHT = 250, 250
camera = ProjectPoints(v=mesh.vertices, f=np.array([WIDTH, WIDTH]), c=np.array([WIDTH, HEIGHT]) / 2.,
t=np.array([0, 0, 2.5]), rt=np.array([np.pi, 0, 0]), k=np.zeros(5))
frustum = {'near': 1., 'far': 10., 'width': WIDTH, 'height': HEIGHT}
rn = DepthRenderer(camera=camera, frustum=frustum, f=mesh.faces, overdraw=False)
points3d = camera.unproject_depth_image(rn.r)
points3d = points3d[points3d[:, :, 2] > np.min(points3d[:, :, 2]) + 0.01]
# print('sampled {} points.'.format(points3d.shape[0]))
return points3d
def voxelized_pointcloud_sampling(mesh_path, name, out_path, res, bounds=(-0.837726, 1.10218), ext=''):
if not exists(mesh_path):
print('Mesh not found, ', mesh_path)
return
out_file = join(out_path, name + '_voxelized_point_cloud_res_{}_points_{}_{}.npz'.format(res, -1, ext))
if exists(out_file) and REDO == False:
print('Already exists, ', split(out_file)[1])
return
mesh = trimesh.load(mesh_path)
point_cloud = get_3DSV(mesh)
_ = voxelize(point_cloud, res, bounds, save_path=out_path)
print('Done, ', split(out_file)[1])
REDO = False
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Run voxelized sampling'
)
parser.add_argument(
'mesh_path',
type=str)
parser.add_argument(
'out_path',
type=str)
parser.add_argument(
'--ext',
type=str, default='')
parser.add_argument(
'--REDO', dest='REDO', action='store_true')
parser.add_argument('--res', type=int, default=32)
args = parser.parse_args()
bb_min = -1.
bb_max = 1.
REDO = args.REDO
name = split(args.mesh_path)[1][:-4]
voxelized_pointcloud_sampling(args.mesh_path, name, args.out_path, args.res, bounds=(bb_min, bb_max), ext=args.ext)
| [
"os.path.exists",
"argparse.ArgumentParser",
"utils.voxelized_pointcloud_sampling.voxelize",
"os.path.split",
"trimesh.load",
"opendr.renderer.DepthRenderer",
"numpy.array",
"numpy.zeros",
"numpy.min"
] | [((805, 880), 'opendr.renderer.DepthRenderer', 'DepthRenderer', ([], {'camera': 'camera', 'frustum': 'frustum', 'f': 'mesh.faces', 'overdraw': '(False)'}), '(camera=camera, frustum=frustum, f=mesh.faces, overdraw=False)\n', (818, 880), False, 'from opendr.renderer import DepthRenderer\n'), ((1520, 1543), 'trimesh.load', 'trimesh.load', (['mesh_path'], {}), '(mesh_path)\n', (1532, 1543), False, 'import trimesh\n'), ((1586, 1640), 'utils.voxelized_pointcloud_sampling.voxelize', 'voxelize', (['point_cloud', 'res', 'bounds'], {'save_path': 'out_path'}), '(point_cloud, res, bounds, save_path=out_path)\n', (1594, 1640), False, 'from utils.voxelized_pointcloud_sampling import voxelize\n'), ((1737, 1798), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Run voxelized sampling"""'}), "(description='Run voxelized sampling')\n", (1760, 1798), False, 'import argparse\n'), ((1208, 1225), 'os.path.exists', 'exists', (['mesh_path'], {}), '(mesh_path)\n', (1214, 1225), False, 'from os.path import join, split, exists\n'), ((1403, 1419), 'os.path.exists', 'exists', (['out_file'], {}), '(out_file)\n', (1409, 1419), False, 'from os.path import join, split, exists\n'), ((568, 592), 'numpy.array', 'np.array', (['[WIDTH, WIDTH]'], {}), '([WIDTH, WIDTH])\n', (576, 592), True, 'import numpy as np\n'), ((657, 678), 'numpy.array', 'np.array', (['[0, 0, 2.5]'], {}), '([0, 0, 2.5])\n', (665, 678), True, 'import numpy as np\n'), ((683, 706), 'numpy.array', 'np.array', (['[np.pi, 0, 0]'], {}), '([np.pi, 0, 0])\n', (691, 706), True, 'import numpy as np\n'), ((710, 721), 'numpy.zeros', 'np.zeros', (['(5)'], {}), '(5)\n', (718, 721), True, 'import numpy as np\n'), ((1662, 1677), 'os.path.split', 'split', (['out_file'], {}), '(out_file)\n', (1667, 1677), False, 'from os.path import join, split, exists\n'), ((2242, 2263), 'os.path.split', 'split', (['args.mesh_path'], {}), '(args.mesh_path)\n', (2247, 2263), False, 'from os.path import join, split, exists\n'), ((596, 621), 'numpy.array', 'np.array', (['[WIDTH, HEIGHT]'], {}), '([WIDTH, HEIGHT])\n', (604, 621), True, 'import numpy as np\n'), ((976, 1001), 'numpy.min', 'np.min', (['points3d[:, :, 2]'], {}), '(points3d[:, :, 2])\n', (982, 1001), True, 'import numpy as np\n'), ((1473, 1488), 'os.path.split', 'split', (['out_file'], {}), '(out_file)\n', (1478, 1488), False, 'from os.path import join, split, exists\n')] |
import numpy
import cupy
from cupy import elementwise
def arange(start, stop=None, step=1, dtype=None):
"""Rerurns an array with evenly spaced values within a given interval.
Values are generated within the half-open interval [start, stop). The first
three arguments are mapped like the ``range`` built-in function, i.e. start
and step are optional.
Args:
start: Start of the interval.
stop: End of the interval.
step: Step width between each pair of consecutive values.
dtype: Data type specifier. It is inferred from other arguments by
default.
Returns:
cupy.ndarray: The 1-D array of range values.
.. seealso:: :func:`numpy.arange`
"""
if dtype is None:
if any(numpy.dtype(type(val)).kind == 'f'
for val in (start, stop, step)):
dtype = float
else:
dtype = int
if stop is None:
stop = start
start = 0
size = int(numpy.ceil((stop - start) / step))
if size <= 0:
return cupy.empty((0,), dtype=dtype)
ret = cupy.empty((size,), dtype=dtype)
typ = numpy.dtype(dtype).type
_arange_ufunc(typ(start), typ(step), ret, dtype=dtype)
return ret
def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None):
"""Returns an array with evenly-spaced values within a given interval.
Instead of specifying the step width like :func:`cupy.arange`, this
function requires the total number of elements specified.
Args:
start: Start of the interval.
stop: End of the interval.
num: Number of elements.
endpoint (bool): If True, the stop value is included as the last
element. Otherwise, the stop value is omitted.
retstep (bool): If True, this function returns (array, step).
Otherwise, it returns only the array.
dtype: Data type specifier. It is inferred from the start and stop
arguments by default.
Returns:
cupy.ndarray: The 1-D array of ranged values.
"""
if num <= 0:
# TODO(beam2d): Return zero-sized array
raise ValueError('linspace with num<=0 is not supported')
if dtype is None:
if any(numpy.dtype(type(val)).kind == 'f' for val in (start, stop)):
dtype = float
else:
dtype = int
ret = cupy.empty((num,), dtype=dtype)
if num == 0:
return ret
elif num == 1:
ret.fill(start)
return ret
if endpoint:
step = (stop - start) / (num - 1)
else:
step = (stop - start) / num
stop = start + step * (num - 1)
typ = numpy.dtype(dtype).type
_linspace_ufunc(typ(start), stop - start, num - 1, ret)
if retstep:
return ret, step
else:
return ret
# TODO(okuta): Implement logspace
# TODO(okuta): Implement meshgrid
# mgrid
# ogrid
_arange_ufunc = elementwise.create_ufunc(
'cupy_arange',
('bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l', 'LL->L',
'qq->q', 'QQ->Q', 'ee->e', 'ff->f', 'dd->d'),
'out0 = in0 + i * in1')
_float_linspace = 'out0 = in0 + i * in1 / in2'
_linspace_ufunc = elementwise.create_ufunc(
'cupy_linspace',
('bbb->b', 'Bbb->B', 'hhh->h', 'Hhh->H', 'iii->i', 'Iii->I', 'lll->l',
'Lll->L', 'qqq->q', 'Qqq->Q', ('eel->e', _float_linspace),
('ffl->f', _float_linspace), ('ddl->d', _float_linspace)),
'out0 = (in0_type)(in0 + _floor_divide(in1_type(i * in1), in2))')
| [
"numpy.dtype",
"cupy.empty",
"numpy.ceil",
"cupy.elementwise.create_ufunc"
] | [((2940, 3130), 'cupy.elementwise.create_ufunc', 'elementwise.create_ufunc', (['"""cupy_arange"""', "('bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l', 'LL->L',\n 'qq->q', 'QQ->Q', 'ee->e', 'ff->f', 'dd->d')", '"""out0 = in0 + i * in1"""'], {}), "('cupy_arange', ('bb->b', 'BB->B', 'hh->h', 'HH->H',\n 'ii->i', 'II->I', 'll->l', 'LL->L', 'qq->q', 'QQ->Q', 'ee->e', 'ff->f',\n 'dd->d'), 'out0 = in0 + i * in1')\n", (2964, 3130), False, 'from cupy import elementwise\n'), ((3208, 3521), 'cupy.elementwise.create_ufunc', 'elementwise.create_ufunc', (['"""cupy_linspace"""', "('bbb->b', 'Bbb->B', 'hhh->h', 'Hhh->H', 'iii->i', 'Iii->I', 'lll->l',\n 'Lll->L', 'qqq->q', 'Qqq->Q', ('eel->e', _float_linspace), ('ffl->f',\n _float_linspace), ('ddl->d', _float_linspace))", '"""out0 = (in0_type)(in0 + _floor_divide(in1_type(i * in1), in2))"""'], {}), "('cupy_linspace', ('bbb->b', 'Bbb->B', 'hhh->h',\n 'Hhh->H', 'iii->i', 'Iii->I', 'lll->l', 'Lll->L', 'qqq->q', 'Qqq->Q', (\n 'eel->e', _float_linspace), ('ffl->f', _float_linspace), ('ddl->d',\n _float_linspace)),\n 'out0 = (in0_type)(in0 + _floor_divide(in1_type(i * in1), in2))')\n", (3232, 3521), False, 'from cupy import elementwise\n'), ((1100, 1132), 'cupy.empty', 'cupy.empty', (['(size,)'], {'dtype': 'dtype'}), '((size,), dtype=dtype)\n', (1110, 1132), False, 'import cupy\n'), ((2391, 2422), 'cupy.empty', 'cupy.empty', (['(num,)'], {'dtype': 'dtype'}), '((num,), dtype=dtype)\n', (2401, 2422), False, 'import cupy\n'), ((991, 1024), 'numpy.ceil', 'numpy.ceil', (['((stop - start) / step)'], {}), '((stop - start) / step)\n', (1001, 1024), False, 'import numpy\n'), ((1059, 1088), 'cupy.empty', 'cupy.empty', (['(0,)'], {'dtype': 'dtype'}), '((0,), dtype=dtype)\n', (1069, 1088), False, 'import cupy\n'), ((1143, 1161), 'numpy.dtype', 'numpy.dtype', (['dtype'], {}), '(dtype)\n', (1154, 1161), False, 'import numpy\n'), ((2678, 2696), 'numpy.dtype', 'numpy.dtype', (['dtype'], {}), '(dtype)\n', (2689, 2696), False, 'import numpy\n')] |
# CPLEX model for the choice-based facility location
# and pricing problem with discrete prices (compact formulation)
# Alternatives are duplicated to account for different possible price levels.
# General
import time
import numpy as np
# CPLEX
import cplex
from cplex.exceptions import CplexSolverError
# Project
import functions
# Data
#import data_N80_I14 as data_file
import data_N08_I10 as data_file
def getModel(data):
# Initialize the model
t_in = time.time()
model = cplex.Cplex()
# Set number of threads
#model.parameters.threads.set(model.get_num_cores())
model.parameters.threads.set(1)
print('\n############\nTHREADS = ', end='')
print(model.parameters.threads.get())
print('############\n')
##########################################
##### ----- OBJECTIVE FUNCTION ----- #####
##########################################
model.objective.set_sense(model.objective.sense.maximize)
##########################################
##### ----- DECISION VARIABLES ----- #####
##########################################
# Customer choice variables
objVar = []
typeVar = []
nameVar = []
lbVar = []
ubVar = []
for i in range(data['I_tot_exp']):
for n in range(data['N']):
for r in range(data['R']):
if data['operator'][data['alt'][i]] == 1:
objVar.append((data['p'][i] - data['customer_cost'][data['alt'][i]]) * data['popN'][n]/data['R'])
else:
objVar.append(0.0)
typeVar.append(model.variables.type.binary)
nameVar.append('x[' + str(i) + ']' + '[' + str(n) + ']' + '[' + str(r) + ']')
lbVar.append(0.0)
ubVar.append(1.0)
model.variables.add(obj = [objVar[i] for i in range(len(objVar))],
types = [typeVar[i] for i in range(len(typeVar))],
lb = [lbVar[i] for i in range(len(typeVar))],
ub = [ubVar[i] for i in range(len(typeVar))],
names = [nameVar[i] for i in range(len(nameVar))])
# Facility location variables
objVar = []
typeVar = []
nameVar = []
for i in range(data['I_tot_exp']):
if data['operator'][data['alt'][i]] == 1:
objVar.append(-data['fixed_cost'][data['alt'][i]])
else:
objVar.append(0.0)
typeVar.append(model.variables.type.binary)
nameVar.append('y[' + str(i) + ']')
model.variables.add(obj = [objVar[i] for i in range(len(objVar))],
types = [typeVar[i] for i in range(len(typeVar))],
names = [nameVar[i] for i in range(len(nameVar))])
# Auxiliary demand variables
typeVar = []
nameVar = []
lbVar = []
ubVar = []
for i in range(data['I_tot_exp']):
typeVar.append(model.variables.type.continuous)
nameVar.append('d[' + str(i) + ']')
lbVar.append(0.0)
ubVar.append(data['Pop'])
model.variables.add(types = [typeVar[i] for i in range(len(typeVar))],
lb = [lbVar[i] for i in range(len(typeVar))],
ub = [ubVar[i] for i in range(len(typeVar))],
names = [nameVar[i] for i in range(len(nameVar))])
print('\nCPLEX model: all decision variables added. N variables: %r. Time: %r'\
%(model.variables.get_num(), round(time.time()-t_in,2)))
# Creating a dictionary that maps variable names to indices, to speed up constraints creation
nameToIndex = { n : j for j, n in enumerate(model.variables.get_names()) }
#########################################
##### -------- CONSTRAINTS -------- #####
#########################################
indicesConstr = []
coefsConstr = []
sensesConstr = []
rhsConstr = []
###################################################
### ------ Instance-specific constraints ------ ###
###################################################
### --- Instance-specific constraints on the binary variables --- ###
for i in range(data['I_out_exp']):
indicesConstr.append([nameToIndex['y[' + str(i) + ']']])
coefsConstr.append([1.0])
sensesConstr.append('E')
rhsConstr.append(1.0)
### --- Choose at most one price level per alternative --- ###
for alt in range(data['I_opt_out'], data['I_tot']):
ind = []
co = []
for i in range(data['I_out_exp'], data['I_tot_exp']):
if data['alt'][i] == alt:
ind.append(nameToIndex['y[' + str(i) + ']'])
co.append(1.0)
indicesConstr.append(ind)
coefsConstr.append(co)
sensesConstr.append('L')
rhsConstr.append(1.0)
###################################################
### ------------ Choice constraints ----------- ###
###################################################
# Each customer chooses one alternative
for n in range(data['N']):
for r in range(data['R']):
ind = []
co = []
for i in range(data['I_tot_exp']):
ind.append(nameToIndex['x[' + str(i) + ']' + '[' + str(n) + ']' + '[' + str(r) + ']'])
co.append(1.0)
indicesConstr.append(ind)
coefsConstr.append(co)
sensesConstr.append('E')
rhsConstr.append(1.0)
# A customer cannot choose an alternative that is not offered
for i in range(data['I_tot_exp']):
for n in range(data['N']):
for r in range(data['R']):
indicesConstr.append([nameToIndex['x[' + str(i) + ']' + '[' + str(n) + ']' + '[' + str(r) + ']'],
nameToIndex['y[' + str(i) + ']']])
coefsConstr.append([1.0, -1.0])
sensesConstr.append('L')
rhsConstr.append(0.0)
# A customer chooses the alternative with the highest utility
for i in range(data['I_tot_exp']):
for n in range(data['N']):
for r in range(data['R']):
ind = []
co = []
for j in range(data['I_tot_exp']):
ind.append(nameToIndex['x[' + str(j) + ']' + '[' + str(n) + ']' + '[' + str(r) + ']'])
co.append(data['U'][j,n,r])
ind.append(nameToIndex['y[' + str(i) + ']'])
co.append(-data['U'][i,n,r])
indicesConstr.append(ind)
coefsConstr.append(co)
sensesConstr.append('G')
rhsConstr.append(0.0)
#######################################
#### ---- Auxiliary constraints --- ###
#######################################
### Calculating demands (not part of the model)
for i in range(data['I_tot_exp']):
ind = []
co = []
for n in range(data['N']):
for r in range(data['R']):
ind.append(nameToIndex['x[' + str(i) + ']' + '[' + str(n) + ']' + '[' + str(r) + ']'])
co.append(-data['popN'][n]/data['R'])
ind.append(nameToIndex['d[' + str(i) + ']'])
co.append(1.0)
indicesConstr.append(ind)
coefsConstr.append(co)
sensesConstr.append('E')
rhsConstr.append(0.0)
model.linear_constraints.add(lin_expr = [[indicesConstr[i], coefsConstr[i]] for i in range(len(indicesConstr))],
senses = [sensesConstr[i] for i in range(len(sensesConstr))],
rhs = [rhsConstr[i] for i in range(len(rhsConstr))])
print('CPLEX model: all constraints added. N constraints: %r. Time: %r\n'\
%(model.linear_constraints.get_num(), round(time.time()-t_in,2)))
return model
def solveModel(data, model):
try:
#model.set_results_stream(None)
#model.set_warning_stream(None)
model.solve()
### PRINT OBJ FUNCTION
print('Objective function value (maximum profit): {:10.4f}'.format(model.solution.get_objective_value()))
### INITIALIZE DICTIONARY OF RESULTS AND SAVE RESULTS
results = {}
results['facilities'] = np.empty(data['I_tot_exp'])
results['demand'] = np.empty(data['I_tot_exp'])
for i in range(data['I_tot_exp']):
results['facilities'][i] = model.solution.get_values('y[' + str(i) + ']')
results['demand'][i] = model.solution.get_values('d[' + str(i) + ']')
### PRINT PRICES, DEMANDS, PROFITS
print('\nAlt Name Supplier Facility Price Demand Market share')
for i in range(data['I_tot_exp']):
print('{:3d} {:6s} {:2d} {:4.0f} {:6.4f} {:8.3f} {:7.4f}'
.format(i, data['name_mapping'][data['alt'][i]], data['operator'][data['alt'][i]],
results['facilities'][i], data['p'][i],
results['demand'][i], results['demand'][i] / data['Pop']))
return results
except CplexSolverError:
raise Exception('Exception raised during solve')
def modelOneScenario(data, r):
print('SCENARIO {:4d} '.format(r), end='')
model = cplex.Cplex()
##########################################
##### ----- OBJECTIVE FUNCTION ----- #####
##########################################
model.objective.set_sense(model.objective.sense.maximize)
##########################################
##### ----- DECISION VARIABLES ----- #####
##########################################
# Customer choice variables
objVar = []
typeVar = []
nameVar = []
lbVar = []
ubVar = []
for i in range(data['I_tot_exp']):
for n in range(data['N']):
if data['operator'][data['alt'][i]] == 1:
objVar.append((data['p'][i] - data['customer_cost'][data['alt'][i]]) * data['popN'][n])
else:
objVar.append(0.0)
typeVar.append(model.variables.type.binary)
nameVar.append('x[' + str(i) + ']' + '[' + str(n) + ']' + '[' + str(r) + ']')
lbVar.append(0.0)
ubVar.append(1.0)
model.variables.add(obj = [objVar[i] for i in range(len(objVar))],
types = [typeVar[i] for i in range(len(typeVar))],
lb = [lbVar[i] for i in range(len(typeVar))],
ub = [ubVar[i] for i in range(len(typeVar))],
names = [nameVar[i] for i in range(len(nameVar))])
# Facility location variables
objVar = []
typeVar = []
nameVar = []
for i in range(data['I_tot_exp']):
if data['operator'][data['alt'][i]] == 1:
objVar.append(-data['fixed_cost'][data['alt'][i]])
else:
objVar.append(0.0)
typeVar.append(model.variables.type.binary)
nameVar.append('y[' + str(i) + ']')
model.variables.add(obj = [objVar[i] for i in range(len(objVar))],
types = [typeVar[i] for i in range(len(typeVar))],
names = [nameVar[i] for i in range(len(nameVar))])
# Creating a dictionary that maps variable names to indices, to speed up constraints creation
nameToIndex = { n : j for j, n in enumerate(model.variables.get_names()) }
#########################################
##### -------- CONSTRAINTS -------- #####
#########################################
indicesConstr = []
coefsConstr = []
sensesConstr = []
rhsConstr = []
### --- Instance-specific constraints on the binary variables --- ###
for i in range(data['I_out_exp']):
indicesConstr.append([nameToIndex['y[' + str(i) + ']']])
coefsConstr.append([1.0])
sensesConstr.append('E')
rhsConstr.append(1.0)
for i in range(data['I_out_exp'], data['I_tot_exp']):
if data['list_open'][i] == 1:
indicesConstr.append([nameToIndex['y[' + str(i) + ']']])
coefsConstr.append([1.0])
sensesConstr.append('E')
rhsConstr.append(1.0)
### --- Choose at most one price level per alternative --- ###
for alt in range(data['I_opt_out'], data['I_tot']):
ind = []
co = []
for i in range(data['I_out_exp'], data['I_tot_exp']):
if data['alt'][i] == alt:
ind.append(nameToIndex['y[' + str(i) + ']'])
co.append(1.0)
indicesConstr.append(ind)
coefsConstr.append(co)
sensesConstr.append('L')
rhsConstr.append(1.0)
# Each customer chooses one alternative
for n in range(data['N']):
ind = []
co = []
for i in range(data['I_tot_exp']):
ind.append(nameToIndex['x[' + str(i) + ']' + '[' + str(n) + ']' + '[' + str(r) + ']'])
co.append(1.0)
indicesConstr.append(ind)
coefsConstr.append(co)
sensesConstr.append('E')
rhsConstr.append(1.0)
# A customer cannot choose an alternative that is not offered
for i in range(data['I_tot_exp']):
for n in range(data['N']):
indicesConstr.append([nameToIndex['x[' + str(i) + ']' + '[' + str(n) + ']' + '[' + str(r) + ']'],
nameToIndex['y[' + str(i) + ']']])
coefsConstr.append([1.0, -1.0])
sensesConstr.append('L')
rhsConstr.append(0.0)
# A customer chooses the alternative with the highest utility
for i in range(data['I_tot_exp']):
for n in range(data['N']):
ind = []
co = []
for j in range(data['I_tot_exp']):
ind.append(nameToIndex['x[' + str(j) + ']' + '[' + str(n) + ']' + '[' + str(r) + ']'])
co.append(data['U'][j,n,r])
ind.append(nameToIndex['y[' + str(i) + ']'])
co.append(-data['U'][i,n,r])
indicesConstr.append(ind)
coefsConstr.append(co)
sensesConstr.append('G')
rhsConstr.append(0.0)
model.linear_constraints.add(lin_expr = [[indicesConstr[i], coefsConstr[i]] for i in range(len(indicesConstr))],
senses = [sensesConstr[i] for i in range(len(sensesConstr))],
rhs = [rhsConstr[i] for i in range(len(rhsConstr))])
#########################################
##### ----------- SOLVE ----------- #####
#########################################
try:
model.set_results_stream(None)
#model.set_warning_stream(None)
model.parameters.timelimit.set(172000.0)
model.solve()
OF = model.solution.get_objective_value()
y = np.empty(data['I_tot_exp'])
for i in range(data['I_tot_exp']):
y[i] = model.solution.get_values('y[' + str(i) + ']')
print(' OF {:10.4f}'.format(OF))
except CplexSolverError:
raise Exception('Exception raised during solve')
return OF, y
def modelOneCustomer(data, n):
print('CUSTOMER {:4d} '.format(n), end='')
model = cplex.Cplex()
##########################################
##### ----- OBJECTIVE FUNCTION ----- #####
##########################################
model.objective.set_sense(model.objective.sense.maximize)
##########################################
##### ----- DECISION VARIABLES ----- #####
##########################################
# Customer choice variables
objVar = []
typeVar = []
nameVar = []
lbVar = []
ubVar = []
for i in range(data['I_tot_exp']):
for r in range(data['R']):
if data['operator'][data['alt'][i]] == 1:
objVar.append((data['p'][i] - data['customer_cost'][data['alt'][i]]) * data['popN'][n] / data['R'])
else:
objVar.append(0.0)
typeVar.append(model.variables.type.binary)
nameVar.append('x[' + str(i) + ']' + '[' + str(n) + ']' + '[' + str(r) + ']')
lbVar.append(0.0)
ubVar.append(1.0)
model.variables.add(obj = [objVar[i] for i in range(len(objVar))],
types = [typeVar[i] for i in range(len(typeVar))],
lb = [lbVar[i] for i in range(len(typeVar))],
ub = [ubVar[i] for i in range(len(typeVar))],
names = [nameVar[i] for i in range(len(nameVar))])
# Facility location variables (fixed cost is adapted to F_i / |N|)
objVar = []
typeVar = []
nameVar = []
for i in range(data['I_tot_exp']):
if data['operator'][data['alt'][i]] == 1:
objVar.append(-data['fixed_cost'][data['alt'][i]] * data['popN'][n] / data['Pop'])
else:
objVar.append(0.0)
typeVar.append(model.variables.type.binary)
nameVar.append('y[' + str(i) + ']')
model.variables.add(obj = [objVar[i] for i in range(len(objVar))],
types = [typeVar[i] for i in range(len(typeVar))],
names = [nameVar[i] for i in range(len(nameVar))])
# Creating a dictionary that maps variable names to indices, to speed up constraints creation
nameToIndex = { n : j for j, n in enumerate(model.variables.get_names()) }
#########################################
##### -------- CONSTRAINTS -------- #####
#########################################
indicesConstr = []
coefsConstr = []
sensesConstr = []
rhsConstr = []
### --- Instance-specific constraints on the binary variables --- ###
for i in range(data['I_out_exp']):
indicesConstr.append([nameToIndex['y[' + str(i) + ']']])
coefsConstr.append([1.0])
sensesConstr.append('E')
rhsConstr.append(1.0)
for i in range(data['I_out_exp'], data['I_tot_exp']):
if data['list_open'][i] == 1:
indicesConstr.append([nameToIndex['y[' + str(i) + ']']])
coefsConstr.append([1.0])
sensesConstr.append('E')
rhsConstr.append(1.0)
### --- Choose at most one price level per alternative --- ###
for alt in range(data['I_opt_out'], data['I_tot']):
ind = []
co = []
for i in range(data['I_out_exp'], data['I_tot_exp']):
if data['alt'][i] == alt:
ind.append(nameToIndex['y[' + str(i) + ']'])
co.append(1.0)
indicesConstr.append(ind)
coefsConstr.append(co)
sensesConstr.append('L')
rhsConstr.append(1.0)
# The customer chooses one alternative
for r in range(data['R']):
ind = []
co = []
for i in range(data['I_tot_exp']):
ind.append(nameToIndex['x[' + str(i) + ']' + '[' + str(n) + ']' + '[' + str(r) + ']'])
co.append(1.0)
indicesConstr.append(ind)
coefsConstr.append(co)
sensesConstr.append('E')
rhsConstr.append(1.0)
# The customer cannot choose an alternative that is not offered
for i in range(data['I_tot_exp']):
for r in range(data['R']):
indicesConstr.append([nameToIndex['x[' + str(i) + ']' + '[' + str(n) + ']' + '[' + str(r) + ']'],
nameToIndex['y[' + str(i) + ']']])
coefsConstr.append([1.0, -1.0])
sensesConstr.append('L')
rhsConstr.append(0.0)
# The customer chooses the alternative with the highest utility
for i in range(data['I_tot_exp']):
for r in range(data['R']):
ind = []
co = []
for j in range(data['I_tot_exp']):
ind.append(nameToIndex['x[' + str(j) + ']' + '[' + str(n) + ']' + '[' + str(r) + ']'])
co.append(data['U'][j,n,r])
ind.append(nameToIndex['y[' + str(i) + ']'])
co.append(-data['U'][i,n,r])
indicesConstr.append(ind)
coefsConstr.append(co)
sensesConstr.append('G')
rhsConstr.append(0.0)
model.linear_constraints.add(lin_expr = [[indicesConstr[i], coefsConstr[i]] for i in range(len(indicesConstr))],
senses = [sensesConstr[i] for i in range(len(sensesConstr))],
rhs = [rhsConstr[i] for i in range(len(rhsConstr))])
#########################################
##### ----------- SOLVE ----------- #####
#########################################
try:
model.set_results_stream(None)
#model.set_warning_stream(None)
model.parameters.timelimit.set(172000.0)
model.solve()
OF = model.solution.get_objective_value()
y = np.empty(data['I_tot_exp'])
for i in range(data['I_tot_exp']):
y[i] = model.solution.get_values('y[' + str(i) + ']')
print(' OF {:10.4f}'.format(OF))
except CplexSolverError:
raise Exception('Exception raised during solve')
return OF, y
if __name__ == '__main__':
nSimulations = 1
for seed in range(1,nSimulations+1):
if nSimulations > 1:
print('\n\n\n\n\n---------\nSEED ={:3d}\n---------\n\n'.format(seed))
t_0 = time.time()
# Read instance and print aggregate customer data
data = data_file.getData(seed)
data_file.printCustomers(data)
# Calculate utilities for all alternatives (1 per discrete price)
functions.discretePriceAlternativeDuplication(data)
data_file.preprocessUtilities(data)
functions.calcDuplicatedUtilities(data)
t_1 = time.time()
#Solve choice-based optimization problem
model = getModel(data)
#model.parameters.preprocessing.presolve.set(0)
results = solveModel(data, model)
t_2 = time.time()
print('\n -- TIMING -- ')
print('Get data + Preprocess: {:10.5f} sec'.format(t_1 - t_0))
print('Run the model: {:10.5f} sec'.format(t_2 - t_1))
print('\n ------------ ')
| [
"data_N08_I10.printCustomers",
"data_N08_I10.getData",
"cplex.Cplex",
"numpy.empty",
"data_N08_I10.preprocessUtilities",
"functions.calcDuplicatedUtilities",
"functions.discretePriceAlternativeDuplication",
"time.time"
] | [((493, 504), 'time.time', 'time.time', ([], {}), '()\n', (502, 504), False, 'import time\n'), ((518, 531), 'cplex.Cplex', 'cplex.Cplex', ([], {}), '()\n', (529, 531), False, 'import cplex\n'), ((9536, 9549), 'cplex.Cplex', 'cplex.Cplex', ([], {}), '()\n', (9547, 9549), False, 'import cplex\n'), ((15631, 15644), 'cplex.Cplex', 'cplex.Cplex', ([], {}), '()\n', (15642, 15644), False, 'import cplex\n'), ((8503, 8530), 'numpy.empty', 'np.empty', (["data['I_tot_exp']"], {}), "(data['I_tot_exp'])\n", (8511, 8530), True, 'import numpy as np\n'), ((8560, 8587), 'numpy.empty', 'np.empty', (["data['I_tot_exp']"], {}), "(data['I_tot_exp'])\n", (8568, 8587), True, 'import numpy as np\n'), ((15219, 15246), 'numpy.empty', 'np.empty', (["data['I_tot_exp']"], {}), "(data['I_tot_exp'])\n", (15227, 15246), True, 'import numpy as np\n'), ((21398, 21425), 'numpy.empty', 'np.empty', (["data['I_tot_exp']"], {}), "(data['I_tot_exp'])\n", (21406, 21425), True, 'import numpy as np\n'), ((21954, 21965), 'time.time', 'time.time', ([], {}), '()\n', (21963, 21965), False, 'import time\n'), ((22051, 22074), 'data_N08_I10.getData', 'data_file.getData', (['seed'], {}), '(seed)\n', (22068, 22074), True, 'import data_N08_I10 as data_file\n'), ((22086, 22116), 'data_N08_I10.printCustomers', 'data_file.printCustomers', (['data'], {}), '(data)\n', (22110, 22116), True, 'import data_N08_I10 as data_file\n'), ((22203, 22254), 'functions.discretePriceAlternativeDuplication', 'functions.discretePriceAlternativeDuplication', (['data'], {}), '(data)\n', (22248, 22254), False, 'import functions\n'), ((22264, 22299), 'data_N08_I10.preprocessUtilities', 'data_file.preprocessUtilities', (['data'], {}), '(data)\n', (22293, 22299), True, 'import data_N08_I10 as data_file\n'), ((22309, 22348), 'functions.calcDuplicatedUtilities', 'functions.calcDuplicatedUtilities', (['data'], {}), '(data)\n', (22342, 22348), False, 'import functions\n'), ((22374, 22385), 'time.time', 'time.time', ([], {}), '()\n', (22383, 22385), False, 'import time\n'), ((22587, 22598), 'time.time', 'time.time', ([], {}), '()\n', (22596, 22598), False, 'import time\n'), ((3580, 3591), 'time.time', 'time.time', ([], {}), '()\n', (3589, 3591), False, 'import time\n'), ((8039, 8050), 'time.time', 'time.time', ([], {}), '()\n', (8048, 8050), False, 'import time\n')] |
"""
This is an example of the application of DeepESN model for multivariate time-series prediction task
on Piano-midi.de (see http://www-etud.iro.umontreal.ca/~boulanni/icml2012) dataset.
The dataset is a polyphonic music task characterized by 88-dimensional sequences representing musical compositions.
Starting from played notes at time t, the aim is to predict the played notes at time t+1.
Reference paper for DeepESN model:
<NAME>, <NAME>, <NAME>, "Deep Reservoir Computing: A Critical Experimental Analysis",
Neurocomputing, 2017, vol. 268, pp. 87-99
In this Example we consider the hyper-parameters designed in the following paper:
<NAME>, <NAME>, <NAME>, "Design of deep echo state networks",
Neural Networks, 2018, vol. 108, pp. 33-47
"""
from pathlib import Path
import time
import numpy as np
from DeepESN import DeepESN
from utils import computeMusicAccuracy, config_pianomidi, load_pianomidi, select_indexes
class Struct(object): pass
# sistemare indici per IP in config_pianomidi, mettere da un'altra parte
# translation: set indexes by IP in config_plans, put elsewhere
# this probably means the confusion of controlling how intrinsic plasticity is used
# sistema selezione indici con transiente messi all'interno della rete
# index selection system with transient placed inside the network
# this probably means that the transient component in main is now redundant?
def main():
# measure time for this code section
t0 = time.perf_counter()
# fix a seed for the reproducibility of results
np.random.seed(7)
# dataset path
path = Path("data")
(dataset,
Nu, # dimension of a single data point
# for example 88 for piano-midi.de
# where 88 corresponds the number of keys on a piano
error_function,
optimization_problem,
TR_indexes, # train set indices
VL_indexes, # validation set indices
TS_indexes # test set indices
) = load_pianomidi(path, computeMusicAccuracy)
# load configuration for pianomidi task
configs = config_pianomidi(list(TR_indexes) + list(VL_indexes))
# Be careful with memory usage
# TODO: What does careful with memory usage mean?
# What are the limits?
Nr = 50 # number of recurrent units
Nl = 1 # number of recurrent layers
reg = 10.0**-2 # probably refers to lambda_r, readout regularization
# BUG: however we also set regularization in the config file
transient = 5
# initialize the ESN
deepESN = DeepESN(Nu, Nr, Nl, configs, verbose=1)
#
states = deepESN.computeState(dataset.inputs, deepESN.IPconf.DeepIP, verbose=1)
train_states = select_indexes(states, list(TR_indexes) + list(VL_indexes), transient)
train_targets = select_indexes(dataset.targets, list(TR_indexes) + list(VL_indexes), transient)
test_states = select_indexes(states, TS_indexes)
test_targets = select_indexes(dataset.targets, TS_indexes)
deepESN.trainReadout(train_states, train_targets, reg)
train_outputs = deepESN.computeOutput(train_states)
train_error = error_function(train_outputs, train_targets)
print(f"Training ACC: {np.mean(train_error):0.5f} \n")
test_outputs = deepESN.computeOutput(test_states)
test_error = error_function(test_outputs, test_targets)
print(f"Test ACC: {np.mean(test_error):0.5f} \n")
# duration is difference between end time and start time
t1 = time.perf_counter()
print(f"Time elapsed: {t1-t0:0.5f} s")
if __name__ == "__main__":
main()
| [
"numpy.mean",
"pathlib.Path",
"time.perf_counter",
"utils.select_indexes",
"numpy.random.seed",
"DeepESN.DeepESN",
"utils.load_pianomidi"
] | [((1454, 1473), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (1471, 1473), False, 'import time\n'), ((1535, 1552), 'numpy.random.seed', 'np.random.seed', (['(7)'], {}), '(7)\n', (1549, 1552), True, 'import numpy as np\n'), ((1588, 1600), 'pathlib.Path', 'Path', (['"""data"""'], {}), "('data')\n", (1592, 1600), False, 'from pathlib import Path\n'), ((1928, 1970), 'utils.load_pianomidi', 'load_pianomidi', (['path', 'computeMusicAccuracy'], {}), '(path, computeMusicAccuracy)\n', (1942, 1970), False, 'from utils import computeMusicAccuracy, config_pianomidi, load_pianomidi, select_indexes\n'), ((2504, 2543), 'DeepESN.DeepESN', 'DeepESN', (['Nu', 'Nr', 'Nl', 'configs'], {'verbose': '(1)'}), '(Nu, Nr, Nl, configs, verbose=1)\n', (2511, 2543), False, 'from DeepESN import DeepESN\n'), ((2848, 2882), 'utils.select_indexes', 'select_indexes', (['states', 'TS_indexes'], {}), '(states, TS_indexes)\n', (2862, 2882), False, 'from utils import computeMusicAccuracy, config_pianomidi, load_pianomidi, select_indexes\n'), ((2902, 2945), 'utils.select_indexes', 'select_indexes', (['dataset.targets', 'TS_indexes'], {}), '(dataset.targets, TS_indexes)\n', (2916, 2945), False, 'from utils import computeMusicAccuracy, config_pianomidi, load_pianomidi, select_indexes\n'), ((3437, 3456), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (3454, 3456), False, 'import time\n'), ((3161, 3181), 'numpy.mean', 'np.mean', (['train_error'], {}), '(train_error)\n', (3168, 3181), True, 'import numpy as np\n'), ((3335, 3354), 'numpy.mean', 'np.mean', (['test_error'], {}), '(test_error)\n', (3342, 3354), True, 'import numpy as np\n')] |
import numpy as np
import pandas as pd
import util
from othello import Othello
from constants import COLUMN_NAMES
class StartTables:
_start_tables = []
def _init_start_tables(self):
"""
read start tables from csv file 'start_moves.csv'
and store them in _start_tables
"""
csv = pd.read_csv('start_moves.csv')
self._start_tables = np.array(csv, dtype="str")
# print(self._start_tables)
# ########################################################
# CAUTION: Call only once or on change of start tables ! #
# self.calculate_missing_start_moves() #
# ########################################################
def get_available_moves_of_start_tables(self, game: Othello):
"""
search self._start_table for move sequences starting with the one of game and get next elements of those
:return: list of available moves
"""
if len(self._start_tables) == 0:
self._init_start_tables()
turn_nr = game.get_turn_nr()
available_moves = []
taken_mv = game.get_taken_mvs_text()
for move_sequence in self._start_tables:
turn = 0
for move in move_sequence:
# move was played
if turn < turn_nr:
if taken_mv[turn] != move:
# move is different to start_table
break
# if start sequence is finished
elif move != "nan":
available_moves.append(move)
break
turn += 1
available_moves = list(dict.fromkeys(available_moves))
if "nan" in available_moves:
available_moves.remove("nan")
return available_moves
def calculate_missing_start_moves(self):
"""
The first version of the database contains no point symmetric move sequences.
This function calculates the point symmetric moves of the whole database.
Use with caution
"""
if len(self._start_tables) == 0:
self._init_start_tables()
new_moves = list()
# add first row in new start table
# first row == header = 0,1,2, ..
header_length = len(self._start_tables[0])
header = list()
for i in range(header_length):
header.append(str(i))
new_moves.append(header)
# calculate for all start sequences in start table
for move_sequence in self._start_tables:
# add move and opposite move to new start table
# |----------------------------------------------------------------|
# | WARNING: Only call each method once !!! |
# | If you use these functions do following: |
# | uncomment ..opposite..; => run code |
# | comment ..opposite..; uncomment ..diagonal..; run code |
# | comment ..diagonal.. ! |
# |----------------------------------------------------------------|
# | new_moves.append(self.calculate_opposite_move(move_sequence)) |
# | new_moves.append(self.calculate_diagonal_moves(move_sequence)) |
# |----------------------------------------------------------------|
new_moves.append(move_sequence)
# new_moves = self.remove_duplicates(new_moves)
# store new start table in file 'start_moves.csv'
with open('start_moves.csv', 'w') as f:
for row in new_moves:
csv_row = ""
for turn in row:
if turn == "nan":
break
if len(csv_row):
csv_row += "," + turn
else:
csv_row = turn
f.write("%s\n" % csv_row)
@staticmethod
def calculate_opposite_move(move_sequence):
"""
calculate the point symmetric moves of one given move sequence
"""
new_turns = list()
for move in move_sequence:
if move[0] not in {"a", "b", "c", "d", "e", "f", "g", "h"}:
break
# move is a char and a int , eg. 'd3'
# translate this move to a x and y coordinate
(row, column) = util.translate_move_to_pair(move)
if column < 8 and row < 7:
# mirror row and column at point 3.5,3.5 => middle of board
row -= 7
row = abs(row)
column -= 7
column = abs(column)
new_turns.append(COLUMN_NAMES[column] + str(row + 1))
print(f"old:{move_sequence}")
print(f"new:{new_turns}")
return new_turns
@staticmethod
def calculate_diagonal_moves(move_sequence):
"""
calculate the point symmetric move of one given move_sequence
"""
new_turns = list()
for move in move_sequence:
if move[0] not in {"a", "b", "c", "d", "e", "f", "g", "h"}:
break
# move is a char and a int , eg. 'd3'
# translate this move to a x and y coordinate
(row, column) = util.translate_move_to_pair(move)
if column < 8 and row < 7:
# mirror row and column at diagonal 0,0; 7,7 => middle of board
row_temp = row
row = column
column = row_temp
new_turns.append(COLUMN_NAMES[column] + str(row + 1))
print(f"old:{move_sequence}")
print(f"new:{new_turns}")
return new_turns
| [
"util.translate_move_to_pair",
"numpy.array",
"pandas.read_csv"
] | [((329, 359), 'pandas.read_csv', 'pd.read_csv', (['"""start_moves.csv"""'], {}), "('start_moves.csv')\n", (340, 359), True, 'import pandas as pd\n'), ((389, 415), 'numpy.array', 'np.array', (['csv'], {'dtype': '"""str"""'}), "(csv, dtype='str')\n", (397, 415), True, 'import numpy as np\n'), ((4459, 4492), 'util.translate_move_to_pair', 'util.translate_move_to_pair', (['move'], {}), '(move)\n', (4486, 4492), False, 'import util\n'), ((5346, 5379), 'util.translate_move_to_pair', 'util.translate_move_to_pair', (['move'], {}), '(move)\n', (5373, 5379), False, 'import util\n')] |
# coding=utf-8
import numpy as np
import pytest
from matplotlib import pyplot as plt
from ..algorithms import density_profiles
from ..classes import Species, Simulation
from pythonpic.classes import PeriodicTestGrid
from pythonpic.classes import TestSpecies as Species
from ..visualization.time_snapshots import SpatialPerturbationDistributionPlot, SpatialDistributionPlot
@pytest.fixture(params=np.linspace(0.05, 0.3, 3), scope='module')
def _fraction(request):
return request.param
_second_fraction = _fraction
@pytest.fixture(params=np.linspace(4000, 10000, 2, dtype=int), scope='module')
def _N_particles(request):
return request.param
@pytest.fixture(params=density_profiles.profiles.keys(), scope='module')
def _profile(request):
return request.param
# noinspection PyUnresolvedReferences
@pytest.fixture()
def test_density_helper(_fraction, _second_fraction, _profile, _N_particles):
g = PeriodicTestGrid(1, 100, 100)
s = Species(1, 1, _N_particles, g)
moat_length = g.L * _fraction
ramp_length = g.L * _second_fraction
plasma_length = 2*ramp_length
# plasma_length = plasma_length if plasma_length > ramp_length else ramp_length
s.distribute_nonuniformly(moat_length, ramp_length, plasma_length,
profile=_profile)
return s, g, moat_length, plasma_length, _profile
@pytest.mark.parametrize("std", [0.00001])
def test_fitness(test_density_helper, std):
np.random.seed(0)
s, g, moat_length, plasma_length, profile = test_density_helper
assert (s.x > moat_length).all(), "Particles running out the right side!"
assert (s.x <= moat_length + plasma_length).all(), "Particles running out the left side!"
# particle conservation
assert s.N == s.x.size, "Particles are not conserved!"
sim = Simulation(g, [s])
s.gather_density()
s.save_particle_values(0)
s.random_position_perturbation(std)
assert (s.x > moat_length).all(), "Particles running out the left side!"
assert (s.x <= moat_length + plasma_length).all(), "Particles running out the right side!"
s.gather_density()
s.save_particle_values(1)
def plots():
fig, ax = plt.subplots()
fig.suptitle(f"{s.N} particles with {profile} profile")
plot = SpatialPerturbationDistributionPlot(sim, ax)
plot.update(1)
plot2 = SpatialDistributionPlot(sim, ax)
ax.plot(g.x, density_profiles.FDENS(g.x, moat_length, plasma_length/2,
plasma_length, s.N, profile))
plot2.update(0)
plt.show()
assert np.allclose(s.density_history[0], s.density_history[1], atol=1e-3), plots()
# @pytest.mark.parametrize("std", [0])
# def test_stability(std):
# S = initial("stability_test", 1000, 1378, 0, 0, std).test_run()
# def plots():
# fig, ax = plt.subplots()
# fig.suptitle(std)
# plot = SpatialPerturbationDistributionPlot(S, ax)
# plot.update(S.NT-1)
# make_sure_path_exists(S.filename)
# fig.savefig(S.filename.replace(".hdf5", ".png"))
# plt.show()
# plt.close(fig)
# s = S.list_species[0]
# assert np.allclose(s.density_history[0], s.density_history[-1]), plots() | [
"numpy.allclose",
"pythonpic.classes.TestSpecies",
"pytest.mark.parametrize",
"numpy.linspace",
"numpy.random.seed",
"matplotlib.pyplot.subplots",
"pytest.fixture",
"pythonpic.classes.PeriodicTestGrid",
"matplotlib.pyplot.show"
] | [((815, 831), 'pytest.fixture', 'pytest.fixture', ([], {}), '()\n', (829, 831), False, 'import pytest\n'), ((1358, 1397), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""std"""', '[1e-05]'], {}), "('std', [1e-05])\n", (1381, 1397), False, 'import pytest\n'), ((919, 948), 'pythonpic.classes.PeriodicTestGrid', 'PeriodicTestGrid', (['(1)', '(100)', '(100)'], {}), '(1, 100, 100)\n', (935, 948), False, 'from pythonpic.classes import PeriodicTestGrid\n'), ((957, 987), 'pythonpic.classes.TestSpecies', 'Species', (['(1)', '(1)', '_N_particles', 'g'], {}), '(1, 1, _N_particles, g)\n', (964, 987), True, 'from pythonpic.classes import TestSpecies as Species\n'), ((1448, 1465), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (1462, 1465), True, 'import numpy as np\n'), ((2593, 2660), 'numpy.allclose', 'np.allclose', (['s.density_history[0]', 's.density_history[1]'], {'atol': '(0.001)'}), '(s.density_history[0], s.density_history[1], atol=0.001)\n', (2604, 2660), True, 'import numpy as np\n'), ((398, 423), 'numpy.linspace', 'np.linspace', (['(0.05)', '(0.3)', '(3)'], {}), '(0.05, 0.3, 3)\n', (409, 423), True, 'import numpy as np\n'), ((545, 583), 'numpy.linspace', 'np.linspace', (['(4000)', '(10000)', '(2)'], {'dtype': 'int'}), '(4000, 10000, 2, dtype=int)\n', (556, 583), True, 'import numpy as np\n'), ((2175, 2189), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (2187, 2189), True, 'from matplotlib import pyplot as plt\n'), ((2571, 2581), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2579, 2581), True, 'from matplotlib import pyplot as plt\n')] |
import numpy as np
import torch
import torch.nn as nn
from PIL import Image
from loader.dataloader import ColorSpace2RGB
from torchvision import transforms
from torchvision.transforms.functional import InterpolationMode as IM
# Only for inference
class plt2pix(object):
def __init__(self, args):
if args.model == 'tag2pix':
from network import Generator
else:
raise Exception('invalid model name: {}'.format(args.model))
self.args = args
self.gpu_mode = not args.cpu
self.input_size = args.input_size
self.color_revert = ColorSpace2RGB(args.color_space)
self.layers = args.layers
self.palette_num = args.palette_num
self.sketch_transform = transforms.Compose([
transforms.Resize((self.input_size, self.input_size), interpolation=IM.LANCZOS),
transforms.ToTensor()])
self.use_crn = (args.load_crn != "")
##### initialize network
self.net_opt = {
'guide': not args.no_guide,
'relu': args.use_relu,
'bn': not args.no_bn,
'cit': False
}
self.G = Generator(input_size=args.input_size, layers=args.layers,
palette_num=self.palette_num, net_opt=self.net_opt)
for param in self.G.parameters():
param.requires_grad = False
if self.gpu_mode:
self.G = nn.DataParallel(self.G)
if self.use_crn:
from network import ColorPredictor
self.CRN = ColorPredictor(palette_num=self.palette_num, net_opt=self.net_opt)
for param in self.CRN.parameters():
param.requires_grad = False
if self.gpu_mode:
self.CRN = nn.DataParallel(self.CRN)
if self.gpu_mode and torch.cuda.is_available():
self.device = torch.device("cuda:0")
else:
self.device = torch.device("cpu")
print("gpu mode: ", self.gpu_mode)
print("device: ", self.device)
if self.gpu_mode:
print(torch.cuda.device_count(), "GPUS!")
if self.gpu_mode:
self.G.to(self.device)
if self.use_crn:
self.CRN.to(self.device)
self.G.eval()
self.load_model(args.load)
if self.use_crn:
self.CRN.eval()
self.load_crn(args.load_crn)
if self.gpu_mode:
self.G.module.net_opt['guide'] = False
else:
self.G.net_opt['guide'] = False
def colorize(self, input_image, palette=None):
'''Colorize input image based on palette
Parameters:
input_image (PIL.Image) -- the input sketch image
palette (np.array) -- RGB-ordered conditional palette (K x 3)
Returns:
G_f (np.array) -- the colorized result of input sketch image
'''
sketch = self.sketch_transform(input_image)
if palette is None:
palette = np.zeros(3 * self.palette_num)
palette = torch.FloatTensor((palette / 255.0))
sketch = sketch.reshape(1, *sketch.shape)
palette = palette.reshape(1, *palette.shape)
if self.gpu_mode:
palette = palette.to(self.device)
sketch = sketch.to(self.device)
G_f, _ = self.G(sketch, palette)
G_f = self.color_revert(G_f.cpu())[0]
return G_f
def recommend_color(self, input_image):
'''Recommend color palette based on sketch image
Parameters:
input_image (PIL.Image) -- the input sketch image
Returns:
palette (np.array) -- RGB-ordered conditional palette (K x 3)
'''
if not self.use_crn:
raise Exception("Color Recommendation Network is not loaded")
sketch = self.sketch_transform(input_image)
sketch = sketch.reshape(1, *sketch.shape)
if self.gpu_mode:
sketch = sketch.to(self.device)
palette = self.CRN(sketch) * 255.
return palette
def load_model(self, checkpoint_path):
checkpoint = torch.load(str(checkpoint_path))
self.G.load_state_dict(checkpoint['G'])
def load_crn(self, checkpoint_path):
checkpoint = torch.load(str(checkpoint_path))
self.CRN.load_state_dict(checkpoint['CRN'])
| [
"network.Generator",
"torchvision.transforms.Resize",
"torch.nn.DataParallel",
"torch.cuda.device_count",
"loader.dataloader.ColorSpace2RGB",
"numpy.zeros",
"torch.cuda.is_available",
"network.ColorPredictor",
"torchvision.transforms.ToTensor",
"torch.FloatTensor",
"torch.device"
] | [((622, 654), 'loader.dataloader.ColorSpace2RGB', 'ColorSpace2RGB', (['args.color_space'], {}), '(args.color_space)\n', (636, 654), False, 'from loader.dataloader import ColorSpace2RGB\n'), ((1259, 1373), 'network.Generator', 'Generator', ([], {'input_size': 'args.input_size', 'layers': 'args.layers', 'palette_num': 'self.palette_num', 'net_opt': 'self.net_opt'}), '(input_size=args.input_size, layers=args.layers, palette_num=self.\n palette_num, net_opt=self.net_opt)\n', (1268, 1373), False, 'from network import Generator\n'), ((3251, 3285), 'torch.FloatTensor', 'torch.FloatTensor', (['(palette / 255.0)'], {}), '(palette / 255.0)\n', (3268, 3285), False, 'import torch\n'), ((1523, 1546), 'torch.nn.DataParallel', 'nn.DataParallel', (['self.G'], {}), '(self.G)\n', (1538, 1546), True, 'import torch.nn as nn\n'), ((1649, 1715), 'network.ColorPredictor', 'ColorPredictor', ([], {'palette_num': 'self.palette_num', 'net_opt': 'self.net_opt'}), '(palette_num=self.palette_num, net_opt=self.net_opt)\n', (1663, 1715), False, 'from network import ColorPredictor\n'), ((1943, 1968), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (1966, 1968), False, 'import torch\n'), ((1997, 2019), 'torch.device', 'torch.device', (['"""cuda:0"""'], {}), "('cuda:0')\n", (2009, 2019), False, 'import torch\n'), ((2062, 2081), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (2074, 2081), False, 'import torch\n'), ((3187, 3217), 'numpy.zeros', 'np.zeros', (['(3 * self.palette_num)'], {}), '(3 * self.palette_num)\n', (3195, 3217), True, 'import numpy as np\n'), ((830, 909), 'torchvision.transforms.Resize', 'transforms.Resize', (['(self.input_size, self.input_size)'], {'interpolation': 'IM.LANCZOS'}), '((self.input_size, self.input_size), interpolation=IM.LANCZOS)\n', (847, 909), False, 'from torchvision import transforms\n'), ((948, 969), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (967, 969), False, 'from torchvision import transforms\n'), ((1885, 1910), 'torch.nn.DataParallel', 'nn.DataParallel', (['self.CRN'], {}), '(self.CRN)\n', (1900, 1910), True, 'import torch.nn as nn\n'), ((2212, 2237), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\n', (2235, 2237), False, 'import torch\n')] |
import numpy as np
import random
import copy
from collections import namedtuple, deque
from models import Actor, Critic
from noise import NoiseReducer
import torch
import torch.nn.functional as F
import torch.optim as optim
BUFFER_SIZE = int(1e5) # replay buffer size
WEIGHT_DECAY = 0 # L2 weight decay
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
class MultiActorCriticAgent():
"""Interacts with and learns from the environment."""
def __init__(self, state_size, action_size, seed, agent_parameters):
"""Initialize an Agent object.
Params
======
state_size (int): dimension of each state
action_size (int): dimension of each action
seed (int): random seed
agent_parameters (AgentParameters) : parameters used to train the agent
"""
self.state_size = state_size
self.action_size = action_size
self.seed = random.seed(seed)
self.gamma = agent_parameters.gamma
self.tau, self.tau_end, self.tau_decay = agent_parameters.tau_param
self.batch_size = agent_parameters.batch_size
self.update_every, self.update_count = agent_parameters.model_update
self.name = f'agent'
lr_actor, lr_critic = agent_parameters.lr_actor_critic
# Actor Networks (local one and target one)
fc1_units, fc2_units = agent_parameters.model_param
self.actor_local = Actor(state_size, action_size, seed, fc1_units=fc1_units, fc2_units=fc2_units).to(device)
self.actor_target = Actor(state_size, action_size, seed, fc1_units=fc1_units, fc2_units=fc2_units).to(device)
self.actor_optimizer = optim.Adam(self.actor_local.parameters(), lr=lr_actor)
# Critic Network (local one and target one)
self.critic_local = Critic(state_size, action_size, seed, fcs1_units=fc1_units, fc2_units=fc2_units).to(device)
self.critic_target = Critic(state_size, action_size, seed, fcs1_units=fc1_units, fc2_units=fc2_units).to(device)
self.critic_optimizer = optim.Adam(self.critic_local.parameters(), lr=lr_critic, weight_decay=WEIGHT_DECAY)
# Initialize the target model weights with the local ones (same values)
self.actor_target.load_state_dict(self.actor_local.state_dict())
self.critic_target.load_state_dict(self.critic_local.state_dict())
# Noise process
factor_reduction, min_factor, rate_reduction = agent_parameters.noise_reducer_param
self.noise = agent_parameters.noise
self.noise_reducer = NoiseReducer(factor_reduction, min_factor, rate_reduction)
# Replay memory
self.memory = ReplayBuffer(action_size, BUFFER_SIZE, agent_parameters.batch_size, seed)
# Initialize time step (for updating every UPDATE_EVERY steps)
self.t_step = 0
def step(self, states, actions, rewards, next_states, dones):
# Save experience in replay memory
for i in range(len(states)):
self.memory.add(states[i], actions[i], rewards[i], next_states[i], dones[i])
# Learn every UPDATE_EVERY time steps.
self.t_step = (self.t_step + 1) % self.update_every
if self.t_step == 0:
# If enough samples are available in memory, get random subset and learn
if len(self.memory) > self.batch_size:
for _ in range(self.update_count):
experiences = self.memory.sample()
self.learn(experiences)
def act(self, states, add_noise=True):
"""Returns actions for given state as per current policy.
Params
======
states (array_like): current state
add_noise: indicates if noise should be added
"""
states = torch.from_numpy(states).float().to(device)
self.actor_local.eval()
with torch.no_grad():
actions = self.actor_local(states).cpu().data.numpy()
self.actor_local.train()
if add_noise:
actions += self.noise_reducer.reduce_noise(self.noise.sample())
return np.clip(actions, -1, 1)
def end_episode(self):
""" Method applied at the end of each episode """
self.tau = max(self.tau_end, self.tau*self.tau_decay)
self.noise_reducer.update_factor()
def reset(self):
self.noise.reset()
def learn(self, experiences):
"""Update value parameters using given batch of experience tuples.
Params
======
experiences (Tuple[torch.Variable]): tuple of (s, a, r, s', done) tuples
"""
states, actions, rewards, next_states, dones = experiences
# ---------------------------- update critic ---------------------------- #
# Get predicted next-state actions and Q values from target models
actions_next = self.actor_target(next_states)
Q_targets_next = self.critic_target(next_states, actions_next)
# Compute Q targets for current states (y_i)
Q_targets = rewards + (self.gamma * Q_targets_next * (1 - dones))
# Compute critic loss
Q_expected = self.critic_local(states, actions)
critic_loss = F.mse_loss(Q_expected, Q_targets)
# Minimize the loss
self.critic_optimizer.zero_grad()
critic_loss.backward()
# as suggested in the "Benchmak implementation" section of the course"
torch.nn.utils.clip_grad_norm_(self.critic_local.parameters(), 1)
self.critic_optimizer.step()
# ---------------------------- update actor ---------------------------- #
# Compute actor loss
actions_pred = self.actor_local(states)
actor_loss = -self.critic_local(states, actions_pred).mean()
# Minimize the loss
self.actor_optimizer.zero_grad()
actor_loss.backward()
self.actor_optimizer.step()
# ----------------------- update target networks ----------------------- #
self.soft_update(self.critic_local, self.critic_target)
self.soft_update(self.actor_local, self.actor_target)
def soft_update(self, local_model, target_model):
"""Soft update model parameters.
θ_target = τ*θ_local + (1 - τ)*θ_target
Params
======
local_model (PyTorch model): weights will be copied from
target_model (PyTorch model): weights will be copied to
tau (float): interpolation parameter
"""
for target_param, local_param in zip(target_model.parameters(), local_model.parameters()):
target_param.data.copy_(self.tau*local_param.data + (1.0-self.tau)*target_param.data)
class ReplayBuffer:
"""Fixed-size buffer to store experience tuples."""
def __init__(self, action_size, buffer_size, batch_size, seed):
"""Initialize a ReplayBuffer object.
Params
======
action_size (int): dimension of each action
buffer_size (int): maximum size of buffer
batch_size (int): size of each training batch
seed (int): random seed
"""
self.action_size = action_size
self.memory = deque(maxlen=buffer_size)
self.batch_size = batch_size
self.experience = namedtuple("Experience", field_names=["state", "action", "reward", "next_state", "done"])
self.seed = random.seed(seed)
def add(self, state, action, reward, next_state, done):
"""Add a new experience to memory."""
e = self.experience(state, action, reward, next_state, done)
self.memory.append(e)
def sample(self):
"""Randomly sample a batch of experiences from memory."""
experiences = random.sample(self.memory, k=self.batch_size)
states = torch.from_numpy(np.vstack([e.state for e in experiences if e is not None])).float().to(device)
actions = torch.from_numpy(np.vstack([e.action for e in experiences if e is not None])).float().to(device)
rewards = torch.from_numpy(np.vstack([e.reward for e in experiences if e is not None])).float().to(device)
next_states = torch.from_numpy(
np.vstack([e.next_state for e in experiences if e is not None])).float().to(device)
dones = torch.from_numpy(
np.vstack([e.done for e in experiences if e is not None]).astype(np.uint8)).float().to(device)
return (states, actions, rewards, next_states, dones)
def __len__(self):
"""Return the current size of internal memory."""
return len(self.memory)
| [
"numpy.clip",
"models.Critic",
"random.sample",
"torch.nn.functional.mse_loss",
"noise.NoiseReducer",
"collections.deque",
"collections.namedtuple",
"random.seed",
"torch.from_numpy",
"torch.cuda.is_available",
"models.Actor",
"numpy.vstack",
"torch.no_grad"
] | [((348, 373), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (371, 373), False, 'import torch\n'), ((959, 976), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (970, 976), False, 'import random\n'), ((2583, 2641), 'noise.NoiseReducer', 'NoiseReducer', (['factor_reduction', 'min_factor', 'rate_reduction'], {}), '(factor_reduction, min_factor, rate_reduction)\n', (2595, 2641), False, 'from noise import NoiseReducer\n'), ((4115, 4138), 'numpy.clip', 'np.clip', (['actions', '(-1)', '(1)'], {}), '(actions, -1, 1)\n', (4122, 4138), True, 'import numpy as np\n'), ((5205, 5238), 'torch.nn.functional.mse_loss', 'F.mse_loss', (['Q_expected', 'Q_targets'], {}), '(Q_expected, Q_targets)\n', (5215, 5238), True, 'import torch.nn.functional as F\n'), ((7176, 7201), 'collections.deque', 'deque', ([], {'maxlen': 'buffer_size'}), '(maxlen=buffer_size)\n', (7181, 7201), False, 'from collections import namedtuple, deque\n'), ((7265, 7358), 'collections.namedtuple', 'namedtuple', (['"""Experience"""'], {'field_names': "['state', 'action', 'reward', 'next_state', 'done']"}), "('Experience', field_names=['state', 'action', 'reward',\n 'next_state', 'done'])\n", (7275, 7358), False, 'from collections import namedtuple, deque\n'), ((7375, 7392), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (7386, 7392), False, 'import random\n'), ((7710, 7755), 'random.sample', 'random.sample', (['self.memory'], {'k': 'self.batch_size'}), '(self.memory, k=self.batch_size)\n', (7723, 7755), False, 'import random\n'), ((3883, 3898), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (3896, 3898), False, 'import torch\n'), ((1460, 1538), 'models.Actor', 'Actor', (['state_size', 'action_size', 'seed'], {'fc1_units': 'fc1_units', 'fc2_units': 'fc2_units'}), '(state_size, action_size, seed, fc1_units=fc1_units, fc2_units=fc2_units)\n', (1465, 1538), False, 'from models import Actor, Critic\n'), ((1578, 1656), 'models.Actor', 'Actor', (['state_size', 'action_size', 'seed'], {'fc1_units': 'fc1_units', 'fc2_units': 'fc2_units'}), '(state_size, action_size, seed, fc1_units=fc1_units, fc2_units=fc2_units)\n', (1583, 1656), False, 'from models import Actor, Critic\n'), ((1835, 1920), 'models.Critic', 'Critic', (['state_size', 'action_size', 'seed'], {'fcs1_units': 'fc1_units', 'fc2_units': 'fc2_units'}), '(state_size, action_size, seed, fcs1_units=fc1_units, fc2_units=fc2_units\n )\n', (1841, 1920), False, 'from models import Actor, Critic\n'), ((1956, 2041), 'models.Critic', 'Critic', (['state_size', 'action_size', 'seed'], {'fcs1_units': 'fc1_units', 'fc2_units': 'fc2_units'}), '(state_size, action_size, seed, fcs1_units=fc1_units, fc2_units=fc2_units\n )\n', (1962, 2041), False, 'from models import Actor, Critic\n'), ((3793, 3817), 'torch.from_numpy', 'torch.from_numpy', (['states'], {}), '(states)\n', (3809, 3817), False, 'import torch\n'), ((7791, 7849), 'numpy.vstack', 'np.vstack', (['[e.state for e in experiences if e is not None]'], {}), '([e.state for e in experiences if e is not None])\n', (7800, 7849), True, 'import numpy as np\n'), ((7905, 7964), 'numpy.vstack', 'np.vstack', (['[e.action for e in experiences if e is not None]'], {}), '([e.action for e in experiences if e is not None])\n', (7914, 7964), True, 'import numpy as np\n'), ((8020, 8079), 'numpy.vstack', 'np.vstack', (['[e.reward for e in experiences if e is not None]'], {}), '([e.reward for e in experiences if e is not None])\n', (8029, 8079), True, 'import numpy as np\n'), ((8152, 8215), 'numpy.vstack', 'np.vstack', (['[e.next_state for e in experiences if e is not None]'], {}), '([e.next_state for e in experiences if e is not None])\n', (8161, 8215), True, 'import numpy as np\n'), ((8282, 8339), 'numpy.vstack', 'np.vstack', (['[e.done for e in experiences if e is not None]'], {}), '([e.done for e in experiences if e is not None])\n', (8291, 8339), True, 'import numpy as np\n')] |
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
x = pd.period_range(pd.datetime.now(), periods=200, freq='d')
x = x.to_timestamp().to_pydatetime()
# 產生三組,每組 200 個隨機常態分布元素
y = np.random.randn(200, 3).cumsum(0)
plt.plot(x, y)
plt.show()
# Matplotlib 使用點 point 而非 pixel 為圖的尺寸測量單位,適合用於印刷出版。1 point = 1 / 72 英吋,但可以調整
mpl.rcParams['lines.linewidth'] = 5
mpl.rcParams['lines.color'] = 'r'
mpl.rcParams['figure.figsize'] = (10, 10)
plt.gcf().set_size_inches(10, 10)
# 產生三組,每組 200 個隨機常態分布元素
y = np.random.randn(200, 3).cumsum(0)
plt.plot(x, y)
plt.show()
# 設定標籤
plots = plt.plot(x, y)
plt.legend(plots, ('Apple', 'Facebook', 'Google'), loc='best', framealpha=0.5, prop={'size': 'large', 'family': 'monospace'})
plt.show()
# 標題與軸標籤
plt.title('Random Trends')
plt.xlabel('Date')
plt.ylabel('Cum. Sum')
plt.figtext(0.995, 0.01, 'CopyRight', ha='right', va='bottom')
# 避免被圖表元素被蓋住
plt.tight_layout()
plt.plot(x, y)
plt.show()
# 儲存圖表
plt.savefig('plt.svg')
# 使用物件導向方式控制圖表,透過控制 figure 和 axes 來操作。其中 figure 和全域 pyplot 部分屬性相同。例如: fig.text() 對應到 plt.fig_text()
fig = plt.figure(figsize=(8, 4), dpi=200, tight_layout=True, linewidth=1, edgecolor='r')
# 軸與子圖表
fig2 = plt.figure(figsize=(8, 4))
# 插入主要軸,可以透過 add_axes 控制軸在圖裡的位置。例如:[bottom*0.1, left*0.1, top*0.5, right*0.5],fig.add_axes([0.1, 0.1, 0.5, 0.5])
ax = fig2.add_axes([0.1, 0.1, 0.8, 0.8])
ax.set_title('Main Axes with Insert Child Axes')
ax.plot(x, y[:, 0])
ax.set_xlabel('Date')
ax.set_ylabel('Cum. sum')
# 插入軸
ax = fig2.add_axes([0.15, 0.15, 0.3, 0.3])
ax.plot(x, y[:, 1], color='g')
ax.set_xticks([])
# 單一圖與軸繪製(subplots 不帶參數回傳擁有一軸 figure 物件,幾乎等同於 matplotlib 全域物件)
# matplotlib 內建版面編排系統相對好用。圖表大小不一可以使用 gridspec 模組
# 使用子圖表
figure, ax = plt.subplots()
plots = ax.plot(x, y, label='')
figure.set_size_inches(8, 4)
ax.legend(plots, ('Apple', 'Faceook', 'Google'), loc='best', framealpha=0.25, prop={'size': 'small', 'family': 'monospace'})
ax.set_title('Random trends')
ax.set_xlabel('Date')
ax.set_ylabel('Cum. sum')
ax.grid(True) # 使用格子
figure.text(0.995, 0.01, 'Acm', ha='right', va='bottom')
figure.tight_layout()
# 使用子圖表產生多個圖表
fig3, axes = plt.subplots(nrows=3, ncols=1, sharex='True', sharey='True', figsize=(8, 8))
labelled_data = zip(y.transpose(), ('Apple', 'Facebook', 'Google'), ('b', 'g', 'r'))
fig3.suptitle('Three Random Trends', fontsize=16)
for i, ld in enumerate(labelled_data):
ax = axes[i]
ax.plot(x, ld[0], label=ld[1], color=ld[2])
ax.set_ylabel('Cum. sum')
ax.legend(loc='upper left', framealpha=0.5, prop={'size': 'small'})
axes[-1].set_xlabel('Date')
# 直方圖
normal_samples = np.random.normal(size=100) # 生成 100 組標準常態分配(平均值為 0,標準差為 1 的常態分配)隨機變數
plt.hist(normal_samples, width=0.1)
plt.show()
# 散佈圖
num_points = 100
gradient = 0.5
x = np.array(range(num_points))
y = np.random.randn(num_points) * 10 + x * gradient
fig, ax = plt.subplots(figsize=(8, 4))
ax.scatter(x, y)
fig.suptitle('A Simple Scatter Plot')
plt.show()
# 散佈圖 + 迴歸
num_points = 100
gradient = 0.5
x = np.array(range(num_points))
y = np.random.randn(num_points) * 10 + x * gradient
fig, ax = plt.subplots(figsize=(8, 4))
ax.scatter(x, y)
m, c = np.polyfit(x, y, 1) # 使用 Numpy 的 polyfit,參數 1 代表一維,算出 fit 直線斜率
ax.plot(x, m * x + c) # 使用 y = m * x + c 斜率和常數匯出直線
fig.suptitle('Scatter with regression')
plt.show()
# 線圖
age = [4, 4, 17, 17, 18]
points = [2, 20, 22, 24, 20]
plt.plot(age, points)
plt.show()
# 長條圖
labels = ['Physics', 'Chemistry', 'Literature', 'Peace']
foo_data = [3, 6, 10, 4]
bar_width = 0.5
xlocations = np.array(range(len(foo_data))) + bar_width
plt.bar(xlocations, foo_data, width=bar_width)
plt.title('Stock Price')
plt.show()
# 盒鬚圖
normal_examples = np.random.normal(size = 100) # 生成 100 組標準常態分配(平均值為 0,標準差為 1 的常態分配)隨機變數
plt.boxplot(normal_examples)
plt.show()
# 圓餅圖
data = np.random.randint(1, 11, 5) # 生成
x = np.arange(len(data))
plt.pie(data)
plt.show() | [
"matplotlib.pyplot.boxplot",
"matplotlib.pyplot.hist",
"matplotlib.pyplot.ylabel",
"numpy.polyfit",
"matplotlib.pyplot.figtext",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"numpy.random.normal",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.gcf",
"matplotlib.pyplot.title",
"numpy.... | [((259, 273), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y'], {}), '(x, y)\n', (267, 273), True, 'import matplotlib.pyplot as plt\n'), ((274, 284), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (282, 284), True, 'import matplotlib.pyplot as plt\n'), ((574, 588), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y'], {}), '(x, y)\n', (582, 588), True, 'import matplotlib.pyplot as plt\n'), ((589, 599), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (597, 599), True, 'import matplotlib.pyplot as plt\n'), ((616, 630), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y'], {}), '(x, y)\n', (624, 630), True, 'import matplotlib.pyplot as plt\n'), ((631, 761), 'matplotlib.pyplot.legend', 'plt.legend', (['plots', "('Apple', 'Facebook', 'Google')"], {'loc': '"""best"""', 'framealpha': '(0.5)', 'prop': "{'size': 'large', 'family': 'monospace'}"}), "(plots, ('Apple', 'Facebook', 'Google'), loc='best', framealpha=\n 0.5, prop={'size': 'large', 'family': 'monospace'})\n", (641, 761), True, 'import matplotlib.pyplot as plt\n'), ((757, 767), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (765, 767), True, 'import matplotlib.pyplot as plt\n'), ((778, 804), 'matplotlib.pyplot.title', 'plt.title', (['"""Random Trends"""'], {}), "('Random Trends')\n", (787, 804), True, 'import matplotlib.pyplot as plt\n'), ((805, 823), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Date"""'], {}), "('Date')\n", (815, 823), True, 'import matplotlib.pyplot as plt\n'), ((824, 846), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Cum. Sum"""'], {}), "('Cum. Sum')\n", (834, 846), True, 'import matplotlib.pyplot as plt\n'), ((847, 909), 'matplotlib.pyplot.figtext', 'plt.figtext', (['(0.995)', '(0.01)', '"""CopyRight"""'], {'ha': '"""right"""', 'va': '"""bottom"""'}), "(0.995, 0.01, 'CopyRight', ha='right', va='bottom')\n", (858, 909), True, 'import matplotlib.pyplot as plt\n'), ((923, 941), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (939, 941), True, 'import matplotlib.pyplot as plt\n'), ((942, 956), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y'], {}), '(x, y)\n', (950, 956), True, 'import matplotlib.pyplot as plt\n'), ((957, 967), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (965, 967), True, 'import matplotlib.pyplot as plt\n'), ((975, 997), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""plt.svg"""'], {}), "('plt.svg')\n", (986, 997), True, 'import matplotlib.pyplot as plt\n'), ((1104, 1190), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 4)', 'dpi': '(200)', 'tight_layout': '(True)', 'linewidth': '(1)', 'edgecolor': '"""r"""'}), "(figsize=(8, 4), dpi=200, tight_layout=True, linewidth=1,\n edgecolor='r')\n", (1114, 1190), True, 'import matplotlib.pyplot as plt\n'), ((1202, 1228), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8, 4)'}), '(figsize=(8, 4))\n', (1212, 1228), True, 'import matplotlib.pyplot as plt\n'), ((1734, 1748), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (1746, 1748), True, 'import matplotlib.pyplot as plt\n'), ((2143, 2219), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(3)', 'ncols': '(1)', 'sharex': '"""True"""', 'sharey': '"""True"""', 'figsize': '(8, 8)'}), "(nrows=3, ncols=1, sharex='True', sharey='True', figsize=(8, 8))\n", (2155, 2219), True, 'import matplotlib.pyplot as plt\n'), ((2614, 2640), 'numpy.random.normal', 'np.random.normal', ([], {'size': '(100)'}), '(size=100)\n', (2630, 2640), True, 'import numpy as np\n'), ((2684, 2719), 'matplotlib.pyplot.hist', 'plt.hist', (['normal_samples'], {'width': '(0.1)'}), '(normal_samples, width=0.1)\n', (2692, 2719), True, 'import matplotlib.pyplot as plt\n'), ((2720, 2730), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2728, 2730), True, 'import matplotlib.pyplot as plt\n'), ((2864, 2892), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(8, 4)'}), '(figsize=(8, 4))\n', (2876, 2892), True, 'import matplotlib.pyplot as plt\n'), ((2949, 2959), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2957, 2959), True, 'import matplotlib.pyplot as plt\n'), ((3099, 3127), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(8, 4)'}), '(figsize=(8, 4))\n', (3111, 3127), True, 'import matplotlib.pyplot as plt\n'), ((3154, 3173), 'numpy.polyfit', 'np.polyfit', (['x', 'y', '(1)'], {}), '(x, y, 1)\n', (3164, 3173), True, 'import numpy as np\n'), ((3310, 3320), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3318, 3320), True, 'import matplotlib.pyplot as plt\n'), ((3382, 3403), 'matplotlib.pyplot.plot', 'plt.plot', (['age', 'points'], {}), '(age, points)\n', (3390, 3403), True, 'import matplotlib.pyplot as plt\n'), ((3404, 3414), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3412, 3414), True, 'import matplotlib.pyplot as plt\n'), ((3577, 3623), 'matplotlib.pyplot.bar', 'plt.bar', (['xlocations', 'foo_data'], {'width': 'bar_width'}), '(xlocations, foo_data, width=bar_width)\n', (3584, 3623), True, 'import matplotlib.pyplot as plt\n'), ((3625, 3649), 'matplotlib.pyplot.title', 'plt.title', (['"""Stock Price"""'], {}), "('Stock Price')\n", (3634, 3649), True, 'import matplotlib.pyplot as plt\n'), ((3650, 3660), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3658, 3660), True, 'import matplotlib.pyplot as plt\n'), ((3686, 3712), 'numpy.random.normal', 'np.random.normal', ([], {'size': '(100)'}), '(size=100)\n', (3702, 3712), True, 'import numpy as np\n'), ((3758, 3786), 'matplotlib.pyplot.boxplot', 'plt.boxplot', (['normal_examples'], {}), '(normal_examples)\n', (3769, 3786), True, 'import matplotlib.pyplot as plt\n'), ((3787, 3797), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3795, 3797), True, 'import matplotlib.pyplot as plt\n'), ((3812, 3839), 'numpy.random.randint', 'np.random.randint', (['(1)', '(11)', '(5)'], {}), '(1, 11, 5)\n', (3829, 3839), True, 'import numpy as np\n'), ((3871, 3884), 'matplotlib.pyplot.pie', 'plt.pie', (['data'], {}), '(data)\n', (3878, 3884), True, 'import matplotlib.pyplot as plt\n'), ((3886, 3896), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3894, 3896), True, 'import matplotlib.pyplot as plt\n'), ((118, 135), 'pandas.datetime.now', 'pd.datetime.now', ([], {}), '()\n', (133, 135), True, 'import pandas as pd\n'), ((225, 248), 'numpy.random.randn', 'np.random.randn', (['(200)', '(3)'], {}), '(200, 3)\n', (240, 248), True, 'import numpy as np\n'), ((477, 486), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '()\n', (484, 486), True, 'import matplotlib.pyplot as plt\n'), ((540, 563), 'numpy.random.randn', 'np.random.randn', (['(200)', '(3)'], {}), '(200, 3)\n', (555, 563), True, 'import numpy as np\n'), ((2806, 2833), 'numpy.random.randn', 'np.random.randn', (['num_points'], {}), '(num_points)\n', (2821, 2833), True, 'import numpy as np\n'), ((3040, 3067), 'numpy.random.randn', 'np.random.randn', (['num_points'], {}), '(num_points)\n', (3055, 3067), True, 'import numpy as np\n')] |
from transformers import (AutoModelForTokenClassification,
AutoModelForSequenceClassification,
TrainingArguments,
AutoTokenizer,
AutoConfig,
Trainer)
from biobert_ner.utils_ner import (convert_examples_to_features, get_labels, NerTestDataset)
from biobert_ner.utils_ner import InputExample as NerExample
from biobert_re.utils_re import RETestDataset
from utils import display_ehr, get_long_relation_table, display_knowledge_graph, get_relation_table
import numpy as np
import os
from torch import nn
from ehr import HealthRecord
from generate_data import scispacy_plus_tokenizer
from annotations import Entity
import logging
import pandas as pd
from typing import Iterable, List, Tuple
logger = logging.getLogger(__name__)
"""
TODO: make this into terminal allowing user to enter filename
"""
with open("../data/datasets/predict_samples/104788.txt") as f:
SAMPLE_EHR = f.read()
"""
TODO: another command line argument for ner_task and re_task
"""
ner_task=True
re_task=True
#======== CONSTANTS ===========
BIOBERT_NER_SEQ_LEN = 128
BIOBERT_RE_SEQ_LEN = 128
logging.getLogger('matplotlib.font_manager').disabled = True
BIOBERT_NER_MODEL_DIR = "../data/results_model/biobert_ner_model/"
BIOBERT_RE_MODEL_DIR = "../data/results_model/biobert_re_model/"
# =====BioBERT Model for NER======
if(ner_task):
biobert_ner_labels = get_labels('../data/results_ner/labels.txt')
biobert_ner_label_map = {i: label for i, label in enumerate(biobert_ner_labels)}
num_labels_ner = len(biobert_ner_labels)
biobert_ner_config = AutoConfig.from_pretrained(
os.path.join(BIOBERT_NER_MODEL_DIR, "config.json"),
num_labels=num_labels_ner,
id2label=biobert_ner_label_map,
label2id={label: i for i, label in enumerate(biobert_ner_labels)})
biobert_ner_tokenizer = AutoTokenizer.from_pretrained(
"dmis-lab/biobert-base-cased-v1.1")
biobert_ner_model = AutoModelForTokenClassification.from_pretrained(
os.path.join(BIOBERT_NER_MODEL_DIR, "pytorch_model.bin"),
config=biobert_ner_config)
biobert_ner_training_args = TrainingArguments(output_dir="./tmp", do_predict=True)
biobert_ner_trainer = Trainer(model=biobert_ner_model, args=biobert_ner_training_args)
label_ent_map = {'DRUG': 'Drug', 'STR': 'Strength',
'DUR': 'Duration', 'ROU': 'Route',
'FOR': 'Form', 'ADE': 'ADE',
'DOS': 'Dosage', 'REA': 'Reason',
'FRE': 'Frequency'}
# =====BioBERT Model for RE======
if(re_task):
re_label_list = ["0", "1"]
re_task_name = "ehr-re"
biobert_re_config = AutoConfig.from_pretrained(
os.path.join(BIOBERT_RE_MODEL_DIR, "config.json"),
num_labels=len(re_label_list),
finetuning_task=re_task_name)
biobert_re_model = AutoModelForSequenceClassification.from_pretrained(
os.path.join(BIOBERT_RE_MODEL_DIR, "pytorch_model.bin"),
config=biobert_re_config,)
biobert_re_training_args = TrainingArguments(output_dir="./tmp", do_predict=True)
biobert_re_trainer = Trainer(model=biobert_re_model, args=biobert_re_training_args)
def align_predictions(predictions: np.ndarray, label_ids: np.ndarray, biobert_ner_label_map: dict) -> List[List[str]]:
"""
Get the list of labelled predictions from model output
Parameters
----------
predictions : np.ndarray
An array of shape (num_examples, seq_len, num_labels).
label_ids : np.ndarray
An array of shape (num_examples, seq_length).
Has -100 at positions which need to be ignored.
Returns
-------
preds_list : List[List[str]]
Labelled output.
"""
preds = np.argmax(predictions, axis=2)
batch_size, seq_len = preds.shape
preds_list = [[] for _ in range(batch_size)]
for i in range(batch_size):
for j in range(seq_len):
if label_ids[i, j] != nn.CrossEntropyLoss().ignore_index:
preds_list[i].append(biobert_ner_label_map[preds[i][j]])
return preds_list
def get_chunk_type(tok: str) -> Tuple[str, str]:
"""
Args:
tok: Label in IOB format
Returns:
tuple: ("B", "DRUG")
"""
tag_class = tok.split('-')[0]
tag_type = tok.split('-')[-1]
return tag_class, tag_type
def get_chunks(seq: List[str]) -> List[Tuple[str, int, int]]:
"""
Given a sequence of tags, group entities and their position
Args:
seq: ["O", "O", "B-DRUG", "I-DRUG", ...] sequence of labels
Returns:
list of (chunk_type, chunk_start, chunk_end)
Example:
seq = ["B-DRUG", "I-DRUG", "O", "B-STR"]
result = [("DRUG", 0, 1), ("STR", 3, 3)]
"""
default = "O"
chunks = []
chunk_type, chunk_start = None, None
for i, tok in enumerate(seq):
# End of a chunk 1
if tok == default and chunk_type is not None:
# Add a chunk.
chunk = (chunk_type, chunk_start, i - 1)
chunks.append(chunk)
chunk_type, chunk_start = None, None
# End of a chunk + start of a chunk!
elif tok != default:
tok_chunk_class, tok_chunk_type = get_chunk_type(tok)
if chunk_type is None:
chunk_type, chunk_start = tok_chunk_type, i
elif tok_chunk_type != chunk_type or tok_chunk_class == "B":
chunk = (chunk_type, chunk_start, i - 1)
chunks.append(chunk)
chunk_type, chunk_start = tok_chunk_type, i
else:
continue
# end condition
if chunk_type is not None:
chunk = (chunk_type, chunk_start, len(seq))
chunks.append(chunk)
return chunks
# noinspection PyTypeChecker
def get_biobert_ner_predictions(test_ehr: HealthRecord) -> List[Tuple[str, int, int]]:
"""
Get predictions for a single EHR record using BioBERT
Parameters
----------
test_ehr : HealthRecord
The EHR record, this object should have a tokenizer set.
Returns
-------
pred_entities : List[Tuple[str, int, int]]
List of predicted Entities each with the format
("entity", start_idx, end_idx).
"""
split_points = test_ehr.get_split_points(max_len=BIOBERT_NER_SEQ_LEN - 2)
examples = []
for idx in range(len(split_points) - 1):
words = test_ehr.tokens[split_points[idx]:split_points[idx + 1]]
# Give dummy label for prediction
examples.append(NerExample(guid=str(split_points[idx]),
words=words,
labels=["O"] * len(words)))
input_features = convert_examples_to_features(
examples,
biobert_ner_labels,
max_seq_length=BIOBERT_NER_SEQ_LEN,
tokenizer=biobert_ner_tokenizer,
cls_token_at_end=False,
cls_token=biobert_ner_tokenizer.cls_token,
cls_token_segment_id=0,
sep_token=biobert_ner_tokenizer.sep_token,
sep_token_extra=False,
pad_on_left=bool(biobert_ner_tokenizer.padding_side == "left"),
pad_token=biobert_ner_tokenizer.pad_token_id,
pad_token_segment_id=biobert_ner_tokenizer.pad_token_type_id,
pad_token_label_id=nn.CrossEntropyLoss().ignore_index,
verbose=0)
test_dataset = NerTestDataset(input_features)
predictions, label_ids, _ = biobert_ner_trainer.predict(test_dataset)
predictions = align_predictions(predictions, label_ids, biobert_ner_label_map)
# Flatten the prediction list
predictions = [p for ex in predictions for p in ex]
input_tokens = test_ehr.get_tokens()
prev_pred = ""
final_predictions = []
idx = 0
for token in input_tokens:
if token.startswith("##"):
if prev_pred == "O":
final_predictions.append(prev_pred)
else:
pred_typ = prev_pred.split("-")[-1]
final_predictions.append("I-" + pred_typ)
else:
prev_pred = predictions[idx]
final_predictions.append(prev_pred)
idx += 1
pred_entities = []
chunk_pred = get_chunks(final_predictions)
for ent in chunk_pred:
pred_entities.append((ent[0],
test_ehr.get_char_idx(ent[1])[0],
test_ehr.get_char_idx(ent[2])[1]))
return pred_entities
# noinspection PyTypeChecker
def get_ner_predictions(ehr_record: str, model_name: str = "biobert", record_id: str = "1") -> HealthRecord:
"""
Get predictions for NER using either BioBERT or BiLSTM
Parameters
--------------
ehr_record : str
An EHR record in text format.
model_name : str
The model to use for prediction. Default is biobert.
record_id : str
The record id of the returned object. Default is 1.
Returns
-----------
A HealthRecord object with entities set.
"""
if model_name.lower() == "biobert":
test_ehr = HealthRecord(record_id=record_id,
text=ehr_record,
tokenizer=biobert_ner_tokenizer.tokenize,
is_training=False)
predictions = get_biobert_ner_predictions(test_ehr)
else:
raise AttributeError("Accepted model names include 'biobert' "
"and 'bilstm'.")
ent_preds = []
for i, pred in enumerate(predictions):
ent = Entity("T%d" % i, label_ent_map[pred[0]], [pred[1], pred[2]])
# maps character indexes to text
ent_text = test_ehr.text[ent[0]:ent[1]]
if not any(letter.isalnum() for letter in ent_text):
continue
ent.set_text(ent_text)
ent_preds.append(ent)
test_ehr.entities = ent_preds
return test_ehr
def get_re_predictions(test_ehr: HealthRecord) -> HealthRecord:
"""
Get predictions for Relation Extraction.
Parameters
-----------
test_ehr : HealthRecord
A HealthRecord object with entities set.
Returns
--------
HealthRecord
The original object with relations set.
"""
test_dataset = RETestDataset(test_ehr, biobert_ner_tokenizer,
BIOBERT_RE_SEQ_LEN, re_label_list)
if len(test_dataset) == 0:
test_ehr.relations = []
return test_ehr
re_predictions = biobert_re_trainer.predict(test_dataset=test_dataset).predictions
re_predictions = np.argmax(re_predictions, axis=1)
idx = 1
rel_preds = []
for relation, pred in zip(test_dataset.relation_list, re_predictions):
if pred == 1:
relation.ann_id = "R%d" % idx
idx += 1
rel_preds.append(relation)
test_ehr.relations = rel_preds
return test_ehr
def get_ner_table(ner_ents: Iterable[Entity])->pd.DataFrame:
ent_table = {'drug_id': [], 'text': [], 'char_range': [], 'type': []}
for ent in ner_ents:
ent_table['drug_id'].append(ent.ann_id)
ent_table['text'].append(ent.ann_text)
ent_table['char_range'].append(ent.get_char_range())
ent_table['type'].append(ent.name)
ent_df = pd.DataFrame(ent_table)
return ent_df
def get_ehr_predictions():
"""Request EHR text data and the model choice for NER Task"""
ner_predictions = get_ner_predictions(
ehr_record=SAMPLE_EHR)
ner_table = get_ner_table(ner_predictions.get_entities())
re_predictions = get_re_predictions(ner_predictions)
relation_table = get_long_relation_table(re_predictions.relations)
relation_table.to_csv('./tmp/relation_table.csv', index=False)
ner_table.to_csv('./tmp/ner_table.csv', index=False)
html_ner = display_ehr(
text=SAMPLE_EHR,
entities=ner_predictions.get_entities(),
relations=re_predictions.relations,
return_html=True)
graph_img = display_knowledge_graph(relation_table, return_html=True)
if len(relation_table) > 0:
relation_table_html = get_relation_table(relation_table)
else:
relation_table_html = "<p>No relations found</p>"
if graph_img is None:
graph_img = "<p>No Relation found!</p>"
return {'tagged_text': html_ner, 're_table': relation_table_html, 'graph': graph_img}
def main():
results=get_ehr_predictions()
# copy paste text here: https://codebeautify.org/htmlviewer
print(results['tagged_text'])
if __name__=="__main__":
main() | [
"logging.getLogger",
"biobert_ner.utils_ner.NerTestDataset",
"utils.display_knowledge_graph",
"transformers.TrainingArguments",
"torch.nn.CrossEntropyLoss",
"os.path.join",
"numpy.argmax",
"utils.get_long_relation_table",
"ehr.HealthRecord",
"annotations.Entity",
"utils.get_relation_table",
"b... | [((831, 858), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (848, 858), False, 'import logging\n'), ((1201, 1245), 'logging.getLogger', 'logging.getLogger', (['"""matplotlib.font_manager"""'], {}), "('matplotlib.font_manager')\n", (1218, 1245), False, 'import logging\n'), ((1470, 1514), 'biobert_ner.utils_ner.get_labels', 'get_labels', (['"""../data/results_ner/labels.txt"""'], {}), "('../data/results_ner/labels.txt')\n", (1480, 1514), False, 'from biobert_ner.utils_ner import convert_examples_to_features, get_labels, NerTestDataset\n'), ((1938, 2003), 'transformers.AutoTokenizer.from_pretrained', 'AutoTokenizer.from_pretrained', (['"""dmis-lab/biobert-base-cased-v1.1"""'], {}), "('dmis-lab/biobert-base-cased-v1.1')\n", (1967, 2003), False, 'from transformers import AutoModelForTokenClassification, AutoModelForSequenceClassification, TrainingArguments, AutoTokenizer, AutoConfig, Trainer\n'), ((2221, 2275), 'transformers.TrainingArguments', 'TrainingArguments', ([], {'output_dir': '"""./tmp"""', 'do_predict': '(True)'}), "(output_dir='./tmp', do_predict=True)\n", (2238, 2275), False, 'from transformers import AutoModelForTokenClassification, AutoModelForSequenceClassification, TrainingArguments, AutoTokenizer, AutoConfig, Trainer\n'), ((2303, 2367), 'transformers.Trainer', 'Trainer', ([], {'model': 'biobert_ner_model', 'args': 'biobert_ner_training_args'}), '(model=biobert_ner_model, args=biobert_ner_training_args)\n', (2310, 2367), False, 'from transformers import AutoModelForTokenClassification, AutoModelForSequenceClassification, TrainingArguments, AutoTokenizer, AutoConfig, Trainer\n'), ((3127, 3181), 'transformers.TrainingArguments', 'TrainingArguments', ([], {'output_dir': '"""./tmp"""', 'do_predict': '(True)'}), "(output_dir='./tmp', do_predict=True)\n", (3144, 3181), False, 'from transformers import AutoModelForTokenClassification, AutoModelForSequenceClassification, TrainingArguments, AutoTokenizer, AutoConfig, Trainer\n'), ((3208, 3270), 'transformers.Trainer', 'Trainer', ([], {'model': 'biobert_re_model', 'args': 'biobert_re_training_args'}), '(model=biobert_re_model, args=biobert_re_training_args)\n', (3215, 3270), False, 'from transformers import AutoModelForTokenClassification, AutoModelForSequenceClassification, TrainingArguments, AutoTokenizer, AutoConfig, Trainer\n'), ((3824, 3854), 'numpy.argmax', 'np.argmax', (['predictions'], {'axis': '(2)'}), '(predictions, axis=2)\n', (3833, 3854), True, 'import numpy as np\n'), ((7429, 7459), 'biobert_ner.utils_ner.NerTestDataset', 'NerTestDataset', (['input_features'], {}), '(input_features)\n', (7443, 7459), False, 'from biobert_ner.utils_ner import convert_examples_to_features, get_labels, NerTestDataset\n'), ((10281, 10366), 'biobert_re.utils_re.RETestDataset', 'RETestDataset', (['test_ehr', 'biobert_ner_tokenizer', 'BIOBERT_RE_SEQ_LEN', 're_label_list'], {}), '(test_ehr, biobert_ner_tokenizer, BIOBERT_RE_SEQ_LEN,\n re_label_list)\n', (10294, 10366), False, 'from biobert_re.utils_re import RETestDataset\n'), ((10593, 10626), 'numpy.argmax', 'np.argmax', (['re_predictions'], {'axis': '(1)'}), '(re_predictions, axis=1)\n', (10602, 10626), True, 'import numpy as np\n'), ((11287, 11310), 'pandas.DataFrame', 'pd.DataFrame', (['ent_table'], {}), '(ent_table)\n', (11299, 11310), True, 'import pandas as pd\n'), ((11639, 11688), 'utils.get_long_relation_table', 'get_long_relation_table', (['re_predictions.relations'], {}), '(re_predictions.relations)\n', (11662, 11688), False, 'from utils import display_ehr, get_long_relation_table, display_knowledge_graph, get_relation_table\n'), ((12004, 12061), 'utils.display_knowledge_graph', 'display_knowledge_graph', (['relation_table'], {'return_html': '(True)'}), '(relation_table, return_html=True)\n', (12027, 12061), False, 'from utils import display_ehr, get_long_relation_table, display_knowledge_graph, get_relation_table\n'), ((1707, 1757), 'os.path.join', 'os.path.join', (['BIOBERT_NER_MODEL_DIR', '"""config.json"""'], {}), "(BIOBERT_NER_MODEL_DIR, 'config.json')\n", (1719, 1757), False, 'import os\n'), ((2095, 2151), 'os.path.join', 'os.path.join', (['BIOBERT_NER_MODEL_DIR', '"""pytorch_model.bin"""'], {}), "(BIOBERT_NER_MODEL_DIR, 'pytorch_model.bin')\n", (2107, 2151), False, 'import os\n'), ((2791, 2840), 'os.path.join', 'os.path.join', (['BIOBERT_RE_MODEL_DIR', '"""config.json"""'], {}), "(BIOBERT_RE_MODEL_DIR, 'config.json')\n", (2803, 2840), False, 'import os\n'), ((3003, 3058), 'os.path.join', 'os.path.join', (['BIOBERT_RE_MODEL_DIR', '"""pytorch_model.bin"""'], {}), "(BIOBERT_RE_MODEL_DIR, 'pytorch_model.bin')\n", (3015, 3058), False, 'import os\n'), ((9110, 9226), 'ehr.HealthRecord', 'HealthRecord', ([], {'record_id': 'record_id', 'text': 'ehr_record', 'tokenizer': 'biobert_ner_tokenizer.tokenize', 'is_training': '(False)'}), '(record_id=record_id, text=ehr_record, tokenizer=\n biobert_ner_tokenizer.tokenize, is_training=False)\n', (9122, 9226), False, 'from ehr import HealthRecord\n'), ((9584, 9645), 'annotations.Entity', 'Entity', (["('T%d' % i)", 'label_ent_map[pred[0]]', '[pred[1], pred[2]]'], {}), "('T%d' % i, label_ent_map[pred[0]], [pred[1], pred[2]])\n", (9590, 9645), False, 'from annotations import Entity\n'), ((12129, 12163), 'utils.get_relation_table', 'get_relation_table', (['relation_table'], {}), '(relation_table)\n', (12147, 12163), False, 'from utils import display_ehr, get_long_relation_table, display_knowledge_graph, get_relation_table\n'), ((7354, 7375), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {}), '()\n', (7373, 7375), False, 'from torch import nn\n'), ((4042, 4063), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {}), '()\n', (4061, 4063), False, 'from torch import nn\n')] |
import os
os.environ['basedir_a'] = '/gpfs/home/cj3272/tmp/'
os.environ["CUDA_VISIBLE_DEVICES"] = '0'
import keras
import PIL
import numpy as np
import scipy
# set tf backend to allow memory to grow, instead of claiming everything
import tensorflow as tf
def get_session():
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
return tf.Session(config=config)
# set the modified tf session as backend in keras
keras.backend.tensorflow_backend.set_session(get_session())
print('keras.__version__=' + str(keras.__version__))
print('tf.__version__=' + str(tf.__version__))
print('PIL.__version__=' + str(PIL.__version__))
print('np.__version__=' + str(np.__version__))
print('scipy.__version__=' + str(scipy.__version__))
print('Using GPU ' + str(os.environ["CUDA_VISIBLE_DEVICES"]) + ' Good luck...')
import sys
from pathlib import Path
from model import *
from luccauchon.data.Generators import AmateurDataFrameDataGenerator
import luccauchon.data.Generators as generators
import luccauchon.data.C as C
print('Using conda env: ' + str(Path(sys.executable).as_posix().split('/')[-3]) + ' [' + str(Path(sys.executable).as_posix()) + ']')
val = 1
dim_image = (256, 256, 3)
batch_size = 24
if val == 1:
df_test = C.generate_X_y_raw_from_amateur_dataset('/gpfs/groups/gc056/APPRANTI/cj3272/dataset/22FEV2019/GEN_segmentation/', dim_image=dim_image, number_elements=batch_size)
trained = keras.models.load_model('/gpfs/home/cj3272/56/APPRANTI/cj3272/unet/unet_weights.01-0.2285.hdf5')
for i in range(0, len(df_test)):
img = df_test.iloc[i]['the_image']
img = np.expand_dims(img, axis=0)
filename = df_test.iloc[i]['filename']
results = trained.predict(x=img, verbose=1)
import scipy.misc
my_mask = results[0]
assert isinstance(my_mask, np.ndarray)
import PIL.Image as Image
scipy.misc.imsave(filename + '_mask.jpg', Image.fromarray(my_mask[:, :, 0]))
else:
df_test = generators.amateur_test('/gpfs/groups/gc056/APPRANTI/cj3272/dataset/22FEV2019/GEN_segmentation/', number_elements=batch_size)
test_generator = AmateurDataFrameDataGenerator(df_test, batch_size=batch_size, dim_image=dim_image)
print(df_test)
trained = keras.models.load_model('/gpfs/home/cj3272/56/APPRANTI/cj3272/unet/unet_weights.01-0.2285.hdf5')
results = trained.predict_generator(test_generator, workers=8, use_multiprocessing=True, verbose=1)
assert batch_size == len(results)
import scipy.misc
my_mask = results[0]
assert isinstance(my_mask, np.ndarray)
import PIL.Image as Image
scipy.misc.imsave('outfile.jpg', Image.fromarray(my_mask[:, :, 0]))
# EDIT: The current scipy version started to normalize all images so that min(data) become black and max(data) become white.
# This is unwanted if the data should be exact grey levels or exact RGB channels. The solution:
# scipy.misc.toimage(image_array, cmin=0.0, cmax=...).save('outfile.jpg')
| [
"PIL.Image.fromarray",
"keras.models.load_model",
"pathlib.Path",
"tensorflow.Session",
"luccauchon.data.Generators.AmateurDataFrameDataGenerator",
"luccauchon.data.C.generate_X_y_raw_from_amateur_dataset",
"luccauchon.data.Generators.amateur_test",
"numpy.expand_dims",
"tensorflow.ConfigProto"
] | [((292, 308), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {}), '()\n', (306, 308), True, 'import tensorflow as tf\n'), ((363, 388), 'tensorflow.Session', 'tf.Session', ([], {'config': 'config'}), '(config=config)\n', (373, 388), True, 'import tensorflow as tf\n'), ((1249, 1420), 'luccauchon.data.C.generate_X_y_raw_from_amateur_dataset', 'C.generate_X_y_raw_from_amateur_dataset', (['"""/gpfs/groups/gc056/APPRANTI/cj3272/dataset/22FEV2019/GEN_segmentation/"""'], {'dim_image': 'dim_image', 'number_elements': 'batch_size'}), "(\n '/gpfs/groups/gc056/APPRANTI/cj3272/dataset/22FEV2019/GEN_segmentation/',\n dim_image=dim_image, number_elements=batch_size)\n", (1288, 1420), True, 'import luccauchon.data.C as C\n'), ((1426, 1527), 'keras.models.load_model', 'keras.models.load_model', (['"""/gpfs/home/cj3272/56/APPRANTI/cj3272/unet/unet_weights.01-0.2285.hdf5"""'], {}), "(\n '/gpfs/home/cj3272/56/APPRANTI/cj3272/unet/unet_weights.01-0.2285.hdf5')\n", (1449, 1527), False, 'import keras\n'), ((1987, 2121), 'luccauchon.data.Generators.amateur_test', 'generators.amateur_test', (['"""/gpfs/groups/gc056/APPRANTI/cj3272/dataset/22FEV2019/GEN_segmentation/"""'], {'number_elements': 'batch_size'}), "(\n '/gpfs/groups/gc056/APPRANTI/cj3272/dataset/22FEV2019/GEN_segmentation/',\n number_elements=batch_size)\n", (2010, 2121), True, 'import luccauchon.data.Generators as generators\n'), ((2134, 2221), 'luccauchon.data.Generators.AmateurDataFrameDataGenerator', 'AmateurDataFrameDataGenerator', (['df_test'], {'batch_size': 'batch_size', 'dim_image': 'dim_image'}), '(df_test, batch_size=batch_size, dim_image=\n dim_image)\n', (2163, 2221), False, 'from luccauchon.data.Generators import AmateurDataFrameDataGenerator\n'), ((2250, 2351), 'keras.models.load_model', 'keras.models.load_model', (['"""/gpfs/home/cj3272/56/APPRANTI/cj3272/unet/unet_weights.01-0.2285.hdf5"""'], {}), "(\n '/gpfs/home/cj3272/56/APPRANTI/cj3272/unet/unet_weights.01-0.2285.hdf5')\n", (2273, 2351), False, 'import keras\n'), ((1617, 1644), 'numpy.expand_dims', 'np.expand_dims', (['img'], {'axis': '(0)'}), '(img, axis=0)\n', (1631, 1644), True, 'import numpy as np\n'), ((2648, 2681), 'PIL.Image.fromarray', 'Image.fromarray', (['my_mask[:, :, 0]'], {}), '(my_mask[:, :, 0])\n', (2663, 2681), True, 'import PIL.Image as Image\n'), ((1932, 1965), 'PIL.Image.fromarray', 'Image.fromarray', (['my_mask[:, :, 0]'], {}), '(my_mask[:, :, 0])\n', (1947, 1965), True, 'import PIL.Image as Image\n'), ((1130, 1150), 'pathlib.Path', 'Path', (['sys.executable'], {}), '(sys.executable)\n', (1134, 1150), False, 'from pathlib import Path\n'), ((1069, 1089), 'pathlib.Path', 'Path', (['sys.executable'], {}), '(sys.executable)\n', (1073, 1089), False, 'from pathlib import Path\n')] |
from lightgbm import LGBMClassifier
from sklearn.model_selection import RandomizedSearchCV, PredefinedSplit
from sklearn import metrics
import pandas as pd
from data import get_data
import numpy as np
import pickle
import hydra
@hydra.main(config_path="config", config_name="config")
def random_forest(cfg):
# Load data
train_df, valid_df, test_df = get_data(cfg)
train_df = train_df[['avg_card_debt', 'card_age', 'non_mtg_acc_past_due_12_months_num', 'inq_12_month_num', 'uti_card', 'Default_ind']]
valid_df = valid_df[['avg_card_debt', 'card_age', 'non_mtg_acc_past_due_12_months_num', 'inq_12_month_num', 'uti_card', 'Default_ind']]
test_df = test_df[['avg_card_debt', 'card_age', 'non_mtg_acc_past_due_12_months_num', 'inq_12_month_num', 'uti_card', 'Default_ind']]
train_x = train_df.drop("Default_ind", axis=1)
train_y = train_df["Default_ind"]
valid_x = valid_df.drop("Default_ind", axis=1)
valid_y = valid_df["Default_ind"]
test_x = test_df.drop("Default_ind", axis=1)
test_y = test_df["Default_ind"]
# Normalize data
df_min = train_x.min()
df_max = train_x.max()
train_x = (train_x-df_min)/(df_max-df_min)
valid_x = (valid_x-df_min)/(df_max-df_min)
test_x = (test_x-df_min)/(df_max-df_min)
X = pd.concat([train_x, valid_x])
X = X.values
y = pd.concat([train_y, valid_y])
y = y.values
test_X = test_x.values
test_y = test_y.values
# Below 2 lines needed for cross-validation in RandomizedSearchCV
split_index = [-1]*len(train_df) + [0]*len(valid_df)
pds = PredefinedSplit(test_fold=split_index)
# Create classifier and the hyperparameter search space
classifier = LGBMClassifier(objective="binary", n_jobs=-1)
param_grid = {
"num_leaves": [31, 63, 127, 255, 511],
"boosting_type": ["gbdt", "dart", "goss"],
"learning_rate": [0.1, 0.5, 0.001],
"max_depth": np.arange(1, 30),
"n_estimators": [100, 400, 700, 900],
"importance_type": ["split", "gain"],
}
model = RandomizedSearchCV(
estimator=classifier,
param_distributions=param_grid,
scoring="f1",
n_iter=200,
verbose=2,
n_jobs=1,
cv=pds,
)
model.fit(X, y)
print(model.best_score_)
print(model.best_estimator_.get_params())
with open("lgbm.pkl", "wb") as f:
pickle.dump([model.best_estimator_, df_min, df_max], f)
clf = model.best_estimator_
y_pred = clf.predict(test_X)
print(f"f1 = {metrics.f1_score(test_y, y_pred)}")
print(f"roc auc = {metrics.roc_auc_score(test_y, y_pred)}")
if __name__ == "__main__":
random_forest()
| [
"sklearn.metrics.f1_score",
"sklearn.model_selection.PredefinedSplit",
"pickle.dump",
"hydra.main",
"data.get_data",
"lightgbm.LGBMClassifier",
"sklearn.metrics.roc_auc_score",
"pandas.concat",
"numpy.arange",
"sklearn.model_selection.RandomizedSearchCV"
] | [((231, 285), 'hydra.main', 'hydra.main', ([], {'config_path': '"""config"""', 'config_name': '"""config"""'}), "(config_path='config', config_name='config')\n", (241, 285), False, 'import hydra\n'), ((360, 373), 'data.get_data', 'get_data', (['cfg'], {}), '(cfg)\n', (368, 373), False, 'from data import get_data\n'), ((1280, 1309), 'pandas.concat', 'pd.concat', (['[train_x, valid_x]'], {}), '([train_x, valid_x])\n', (1289, 1309), True, 'import pandas as pd\n'), ((1335, 1364), 'pandas.concat', 'pd.concat', (['[train_y, valid_y]'], {}), '([train_y, valid_y])\n', (1344, 1364), True, 'import pandas as pd\n'), ((1574, 1612), 'sklearn.model_selection.PredefinedSplit', 'PredefinedSplit', ([], {'test_fold': 'split_index'}), '(test_fold=split_index)\n', (1589, 1612), False, 'from sklearn.model_selection import RandomizedSearchCV, PredefinedSplit\n'), ((1691, 1736), 'lightgbm.LGBMClassifier', 'LGBMClassifier', ([], {'objective': '"""binary"""', 'n_jobs': '(-1)'}), "(objective='binary', n_jobs=-1)\n", (1705, 1736), False, 'from lightgbm import LGBMClassifier\n'), ((2048, 2179), 'sklearn.model_selection.RandomizedSearchCV', 'RandomizedSearchCV', ([], {'estimator': 'classifier', 'param_distributions': 'param_grid', 'scoring': '"""f1"""', 'n_iter': '(200)', 'verbose': '(2)', 'n_jobs': '(1)', 'cv': 'pds'}), "(estimator=classifier, param_distributions=param_grid,\n scoring='f1', n_iter=200, verbose=2, n_jobs=1, cv=pds)\n", (2066, 2179), False, 'from sklearn.model_selection import RandomizedSearchCV, PredefinedSplit\n'), ((1919, 1935), 'numpy.arange', 'np.arange', (['(1)', '(30)'], {}), '(1, 30)\n', (1928, 1935), True, 'import numpy as np\n'), ((2381, 2436), 'pickle.dump', 'pickle.dump', (['[model.best_estimator_, df_min, df_max]', 'f'], {}), '([model.best_estimator_, df_min, df_max], f)\n', (2392, 2436), False, 'import pickle\n'), ((2522, 2554), 'sklearn.metrics.f1_score', 'metrics.f1_score', (['test_y', 'y_pred'], {}), '(test_y, y_pred)\n', (2538, 2554), False, 'from sklearn import metrics\n'), ((2581, 2618), 'sklearn.metrics.roc_auc_score', 'metrics.roc_auc_score', (['test_y', 'y_pred'], {}), '(test_y, y_pred)\n', (2602, 2618), False, 'from sklearn import metrics\n')] |
import pprint
import re
from typing import Any, Dict
import numpy as np
import pytest
from qcelemental.molutil import compute_scramble
from qcengine.programs.tests.standard_suite_contracts import (
contractual_accsd_prt_pr,
contractual_ccd,
contractual_ccsd,
contractual_ccsd_prt_pr,
contractual_ccsdpt_prccsd_pr,
contractual_ccsdt,
contractual_ccsdt1a,
contractual_ccsdt1b,
contractual_ccsdt2,
contractual_ccsdt3,
contractual_ccsdt_prq_pr,
contractual_ccsdtq,
contractual_cisd,
contractual_current,
contractual_dft_current,
contractual_fci,
contractual_hf,
contractual_lccd,
contractual_lccsd,
contractual_mp2,
contractual_mp2p5,
contractual_mp3,
contractual_mp4,
contractual_mp4_prsdq_pr,
contractual_qcisd,
contractual_qcisd_prt_pr,
query_has_qcvar,
query_qcvar,
)
from qcengine.programs.tests.standard_suite_ref import answer_hash, std_suite
from qcengine.programs.util import mill_qcvars
from .utils import compare, compare_values
pp = pprint.PrettyPrinter(width=120)
def runner_asserter(inp, ref_subject, method, basis, tnm, scramble, frame):
qcprog = inp["qc_module"].split("-")[0]
qc_module_in = inp["qc_module"] # returns "<qcprog>"|"<qcprog>-<module>" # input-specified routing
qc_module_xptd = (
(qcprog + "-" + inp["xptd"]["qc_module"]) if inp.get("xptd", {}).get("qc_module", None) else None
) # expected routing
driver = inp["driver"]
reference = inp["reference"]
fcae = inp["fcae"]
mode_options = inp.get("cfg", {})
if qc_module_in == "nwchem-tce" and basis == "cc-pvdz":
pytest.skip(
f"TCE throwing 'non-Abelian symmetry not permitted' for HF molecule when not C1. fix this a different way than setting C1."
)
# <<< Molecule >>>
# 1. ref mol: `ref_subject` nicely oriented mol taken from standard_suite_ref.py
ref_subject.update_geometry()
min_nonzero_coords = np.count_nonzero(np.abs(ref_subject.geometry(np_out=True)) > 1.0e-10)
# print(
# "MOL 1/REF: ref_subject",
# ref_subject.com_fixed(),
# ref_subject.orientation_fixed(),
# ref_subject.symmetry_from_input(),
# )
# with np.printoptions(precision=3, suppress=True):
# print(ref_subject.geometry(np_out=True))
if scramble is None:
subject = ref_subject
ref2in_mill = compute_scramble(
subject.natom(), do_resort=False, do_shift=False, do_rotate=False, do_mirror=False
) # identity AlignmentMill
else:
subject, scramble_data = ref_subject.scramble(**scramble, do_test=False, fix_mode="copy")
ref2in_mill = scramble_data["mill"]
# with np.printoptions(precision=12, suppress=True):
# print(f"ref2in scramble mill= {ref2in_mill}")
# print("MOL 2/IN: subject", subject.com_fixed(), subject.orientation_fixed(), subject.symmetry_from_input())
# with np.printoptions(precision=3, suppress=True):
# print(subject.geometry(np_out=True))
# 2. input mol: `subject` now ready for `atin.molecule`. may have been scrambled away from nice ref orientation
# <<< Reference Values >>>
# ? precedence on next two
mp2_type = inp.get("corl_type", inp["keywords"].get("mp2_type", "df")) # hard-code of read_options.cc MP2_TYPE
mp_type = inp.get("corl_type", inp["keywords"].get("mp_type", "conv")) # hard-code of read_options.cc MP_TYPE
ci_type = inp.get("corl_type", inp["keywords"].get("ci_type", "conv")) # hard-code of read_options.cc CI_TYPE
cc_type = inp.get("corl_type", inp["keywords"].get("cc_type", "conv")) # hard-code of read_options.cc CC_TYPE
corl_natural_values = {
"hf": "conv", # dummy to assure df/cd/conv scf_type refs available
"mp2": mp2_type,
"mp3": mp_type,
"mp4(sdq)": mp_type,
"mp4": mp_type,
"cisd": ci_type,
"qcisd": ci_type,
"qcisd(t)": ci_type,
"fci": ci_type,
"lccd": cc_type,
"lccsd": cc_type,
"ccd": cc_type,
"ccsd": cc_type,
"ccsd+t(ccsd)": cc_type,
"ccsd(t)": cc_type,
"a-ccsd(t)": cc_type,
"ccsdt-1a": cc_type,
"ccsdt-1b": cc_type,
"ccsdt-2": cc_type,
"ccsdt-3": cc_type,
"ccsdt": cc_type,
"ccsdt(q)": cc_type,
"ccsdtq": cc_type,
"pbe": "conv",
"b3lyp": "conv",
"b3lyp5": "conv",
"mrccsdt-1a": cc_type,
"mrccsdt-1b": cc_type,
"mrccsdt-2": cc_type,
"mrccsdt-3": cc_type,
}
corl_type = corl_natural_values[method]
natural_ref = {"conv": "pk", "df": "df", "cd": "cd"}
scf_type = inp["keywords"].get("scf_type", natural_ref[corl_type])
natural_values = {"pk": "pk", "direct": "pk", "df": "df", "mem_df": "df", "disk_df": "df", "cd": "cd"}
scf_type = natural_values[scf_type]
is_dft = method in ["pbe", "b3lyp", "b3lyp5"]
# * absolute and relative tolerances function approx as `or` operation. see https://numpy.org/doc/stable/reference/generated/numpy.allclose.html
# * can't go lower on atol_e because hit digit limits accessible for reference values
# * dz gradients tend to be less accurate than larger basis sets/mols
# * analytic Hessian very loose to catch gms/nwc HF Hessian
atol_e, rtol_e = 2.0e-7, 1.0e-16
atol_g, rtol_g = 5.0e-7, 2.0e-5
atol_h, rtol_h = 1.0e-5, 2.0e-5
if is_dft:
atol_g = 6.0e-6
using_fd = "xptd" in inp and "fd" in inp["xptd"] # T/F: notate fd vs. anal for docs table
loose_fd = inp.get("xptd", {}).get("fd", False) # T/F: relax conv crit for 3-pt internal findif fd
if loose_fd:
if basis == "cc-pvdz":
atol_g = 1.0e-4
atol_h, rtol_h = 1.0e-4, 5.0e-4
else:
atol_g = 2.0e-5
atol_h, rtol_h = 5.0e-5, 2.0e-4
# VIEW atol_e, atol_g, atol_h, rtol_e, rtol_g, rtol_h = 1.e-9, 1.e-9, 1.e-9, 1.e-16, 1.e-16, 1.e-16
chash = answer_hash(
system=subject.name(),
basis=basis,
fcae=fcae,
scf_type=scf_type,
reference=reference,
corl_type=corl_type,
)
ref_block = std_suite[chash]
# check all calcs against conventional reference to looser tolerance
atol_conv = 1.0e-4
rtol_conv = 1.0e-3
chash_conv = answer_hash(
system=subject.name(),
basis=basis,
fcae=fcae,
reference=reference,
corl_type="conv",
scf_type="pk",
)
ref_block_conv = std_suite[chash_conv]
# <<< Prepare Calculation and Call API >>>
import qcdb
driver_call = {"energy": qcdb.energy, "gradient": qcdb.gradient, "hessian": qcdb.hessian}
# local_options = {"nnodes": 1, "ncores": 2, "scratch_messy": False, "memory": 4}
local_options = {"nnodes": 1, "ncores": 1, "scratch_messy": False, "memory": 10}
qcdb.set_options(
{
# "guess": "sad",
# "e_convergence": 8,
# "d_convergence": 7,
# "r_convergence": 7,
"e_convergence": 10,
"d_convergence": 9,
# "r_convergence": 9,
# "points": 5,
}
)
extra_kwargs = inp["keywords"].pop("function_kwargs", {})
qcdb.set_options(inp["keywords"])
if "error" in inp:
errtype, errmatch, reason = inp["error"]
with pytest.raises(errtype) as e:
driver_call[driver](inp["call"], molecule=subject, local_options=local_options, **extra_kwargs)
assert re.search(errmatch, str(e.value)), f"Not found: {errtype} '{errmatch}' in {e.value}"
_recorder(qcprog, qc_module_in, driver, method, reference, fcae, scf_type, corl_type, "error", "nyi: " + reason)
return
ret, wfn = driver_call[driver](
inp["call"], molecule=subject, return_wfn=True, local_options=local_options, mode_options=mode_options, **extra_kwargs
)
print("WFN")
pp.pprint(wfn)
qc_module_out = wfn["provenance"]["creator"].lower()
if "module" in wfn["provenance"]:
qc_module_out += "-" + wfn["provenance"]["module"] # returns "<qcprog>-<module>"
# assert 0, f"{qc_module_xptd=} {qc_module_in=} {qc_module_out=}" # debug
# 3. output mol: `wfn.molecule` after calc. orientation for nonscalar quantities may be different from `subject` if fix_=False
wfn_molecule = qcdb.Molecule.from_schema(wfn["molecule"])
# print(
# "MOL 3/WFN: wfn.mol",
# wfn_molecule.com_fixed(),
# wfn_molecule.orientation_fixed(),
# wfn_molecule.symmetry_from_input(),
# )
# with np.printoptions(precision=3, suppress=True):
# print(wfn_molecule.geometry(np_out=True))
_, ref2out_mill, _ = ref_subject.B787(wfn_molecule, atoms_map=False, mols_align=True, fix_mode="true", verbose=0)
# print(f"{ref2out_mill=}")
# print("PREE REF")
# print(ref_block["HF TOTAL GRADIENT"])
if subject.com_fixed() and subject.orientation_fixed():
assert frame == "fixed"
with np.printoptions(precision=3, suppress=True):
assert compare_values(
subject.geometry(), wfn_molecule.geometry(), atol=5.0e-8
), f"coords: atres ({wfn_molecule.geometry(np_out=True)}) != atin ({subject.geometry(np_out=True)})" # 10 too much
assert (
ref_subject.com_fixed()
and ref_subject.orientation_fixed()
and subject.com_fixed()
and subject.orientation_fixed()
and wfn_molecule.com_fixed()
and wfn_molecule.orientation_fixed()
), f"fixed, so all T: {ref_subject.com_fixed()} {ref_subject.orientation_fixed()} {subject.com_fixed()} {subject.orientation_fixed()} {wfn_molecule.com_fixed()} {wfn_molecule.orientation_fixed()}"
ref_block = mill_qcvars(ref2in_mill, ref_block)
ref_block_conv = mill_qcvars(ref2in_mill, ref_block_conv)
else:
assert frame == "free" or frame == "" # "": direct from standard_suite_ref.std_molecules
with np.printoptions(precision=3, suppress=True):
assert compare(
min_nonzero_coords,
np.count_nonzero(np.abs(wfn_molecule.geometry(np_out=True)) > 1.0e-10),
tnm + " !0 coords wfn",
), f"ncoords {wfn_molecule.geometry(np_out=True)} != {min_nonzero_coords}"
assert (
(not ref_subject.com_fixed())
and (not ref_subject.orientation_fixed())
and (not subject.com_fixed())
and (not subject.orientation_fixed())
and (not wfn_molecule.com_fixed())
and (not wfn_molecule.orientation_fixed())
), f"free, so all F: {ref_subject.com_fixed()} {ref_subject.orientation_fixed()} {subject.com_fixed()} {subject.orientation_fixed()} {wfn_molecule.com_fixed()} {wfn_molecule.orientation_fixed()}"
if scramble is None:
# wfn exactly matches ref_subject and ref_block
with np.printoptions(precision=3, suppress=True):
assert compare_values(
ref_subject.geometry(), wfn_molecule.geometry(), atol=5.0e-8
), f"coords: atres ({wfn_molecule.geometry(np_out=True)}) != atin ({ref_subject.geometry(np_out=True)})"
else:
# wfn is "pretty" (max zeros) but likely not exactly ref_block (by axis exchange, phasing, atom shuffling) since Psi4 ref frame is not unique
ref_block = mill_qcvars(ref2out_mill, ref_block)
ref_block_conv = mill_qcvars(ref2out_mill, ref_block_conv)
# print("POST REF")
# print(ref_block["HF TOTAL GRADIENT"])
# <<< Comparison Tests >>>
assert wfn["success"] is True
assert (
wfn["provenance"]["creator"].lower() == qcprog
), f'ENGINE used ({ wfn["provenance"]["creator"].lower()}) != requested ({qcprog})'
# qcvars
contractual_args = [
qc_module_out,
driver,
reference,
method,
corl_type,
fcae,
]
asserter_args = [
[qcdb, wfn["qcvars"]],
ref_block,
[atol_e, atol_g, atol_h],
[rtol_e, rtol_g, rtol_h],
ref_block_conv,
atol_conv,
rtol_conv,
tnm,
]
def qcvar_assertions():
print("BLOCK", chash, contractual_args)
if method == "hf":
_asserter(asserter_args, contractual_args, contractual_hf)
elif method == "mp2":
_asserter(asserter_args, contractual_args, contractual_mp2)
elif method == "mp3":
_asserter(asserter_args, contractual_args, contractual_mp2)
_asserter(asserter_args, contractual_args, contractual_mp2p5)
_asserter(asserter_args, contractual_args, contractual_mp3)
elif method == "mp4(sdq)":
_asserter(asserter_args, contractual_args, contractual_mp2)
_asserter(asserter_args, contractual_args, contractual_mp2p5)
_asserter(asserter_args, contractual_args, contractual_mp3)
_asserter(asserter_args, contractual_args, contractual_mp4_prsdq_pr)
elif method == "mp4":
_asserter(asserter_args, contractual_args, contractual_mp2)
_asserter(asserter_args, contractual_args, contractual_mp2p5)
_asserter(asserter_args, contractual_args, contractual_mp3)
_asserter(asserter_args, contractual_args, contractual_mp4_prsdq_pr)
_asserter(asserter_args, contractual_args, contractual_mp4)
elif method == "cisd":
_asserter(asserter_args, contractual_args, contractual_cisd)
elif method == "qcisd":
_asserter(asserter_args, contractual_args, contractual_mp2)
_asserter(asserter_args, contractual_args, contractual_qcisd)
elif method == "qcisd(t)":
_asserter(asserter_args, contractual_args, contractual_mp2)
_asserter(asserter_args, contractual_args, contractual_qcisd)
_asserter(asserter_args, contractual_args, contractual_qcisd_prt_pr)
elif method == "fci":
_asserter(asserter_args, contractual_args, contractual_fci)
elif method == "lccd":
_asserter(asserter_args, contractual_args, contractual_mp2)
_asserter(asserter_args, contractual_args, contractual_lccd)
elif method == "lccsd":
_asserter(asserter_args, contractual_args, contractual_mp2)
_asserter(asserter_args, contractual_args, contractual_lccsd)
elif method == "ccd":
_asserter(asserter_args, contractual_args, contractual_mp2)
_asserter(asserter_args, contractual_args, contractual_ccd)
elif method == "ccsd":
_asserter(asserter_args, contractual_args, contractual_mp2)
_asserter(asserter_args, contractual_args, contractual_ccsd)
elif method == "ccsd+t(ccsd)":
_asserter(asserter_args, contractual_args, contractual_mp2)
_asserter(asserter_args, contractual_args, contractual_ccsd)
_asserter(asserter_args, contractual_args, contractual_ccsdpt_prccsd_pr)
elif method == "ccsd(t)":
_asserter(asserter_args, contractual_args, contractual_mp2)
_asserter(asserter_args, contractual_args, contractual_ccsd)
_asserter(asserter_args, contractual_args, contractual_ccsd_prt_pr)
elif method == "a-ccsd(t)":
_asserter(asserter_args, contractual_args, contractual_mp2)
_asserter(asserter_args, contractual_args, contractual_ccsd)
_asserter(asserter_args, contractual_args, contractual_accsd_prt_pr)
elif method == "ccsdt-1a":
_asserter(asserter_args, contractual_args, contractual_mp2)
_asserter(asserter_args, contractual_args, contractual_ccsdt1a)
elif method == "ccsdt-1b":
_asserter(asserter_args, contractual_args, contractual_mp2)
_asserter(asserter_args, contractual_args, contractual_ccsdt1b)
elif method == "ccsdt-2":
_asserter(asserter_args, contractual_args, contractual_mp2)
_asserter(asserter_args, contractual_args, contractual_ccsdt2)
elif method == "ccsdt-3":
_asserter(asserter_args, contractual_args, contractual_mp2)
_asserter(asserter_args, contractual_args, contractual_ccsdt3)
elif method == "ccsdt":
_asserter(asserter_args, contractual_args, contractual_mp2)
_asserter(asserter_args, contractual_args, contractual_ccsdt)
elif method == "ccsdt(q)":
_asserter(asserter_args, contractual_args, contractual_mp2)
_asserter(asserter_args, contractual_args, contractual_ccsdt)
_asserter(asserter_args, contractual_args, contractual_ccsdt_prq_pr)
elif method == "ccsdtq":
_asserter(asserter_args, contractual_args, contractual_mp2)
_asserter(asserter_args, contractual_args, contractual_ccsdtq)
# separations here for DFT appropriate when qcvars are labeled by functional
if "wrong" in inp:
if basis == "cc-pvdz" and contractual_args in [
["cfour-ecc", "gradient", "rhf", mtd, "conv", "fc"]
for mtd in ["ccsdt-1a", "ccsdt-1b", "ccsdt-2", "ccsdt-3"]
]:
# these four tests have pass/fail too close for dz to "get it right" with general tolerances
pass
else:
errmatch, reason = inp["wrong"]
with pytest.raises(AssertionError) as e:
qcvar_assertions()
assert errmatch in str(e.value), f"Not found: AssertionError '{errmatch}' for '{reason}' in {e.value}"
_recorder(
qcprog,
qc_module_out,
driver,
method,
reference,
fcae,
scf_type,
corl_type,
"wrong",
reason + f" First wrong at `{errmatch}`.",
)
pytest.xfail(reason)
# primary label checks
qcvar_assertions()
# routing checks
if qc_module_in != qcprog:
assert qc_module_out == qc_module_in, f"QC_MODULE used ({qc_module_out}) != requested ({qc_module_in})"
if qc_module_xptd:
assert qc_module_out == qc_module_xptd, f"QC_MODULE used ({qc_module_out}) != expected ({qc_module_xptd})"
# aliases checks
if is_dft:
_asserter(asserter_args, contractual_args, contractual_dft_current)
else:
_asserter(asserter_args, contractual_args, contractual_current)
# returns checks
if driver == "energy":
assert compare_values(
ref_block[f"{method.upper()} TOTAL ENERGY"], wfn["return_result"], tnm + " wfn", atol=atol_e, rtol=rtol_e
)
assert compare_values(
ref_block[f"{method.upper()} TOTAL ENERGY"],
wfn["properties"]["return_energy"],
tnm + " prop",
atol=atol_e,
rtol=rtol_e,
)
assert compare_values(ref_block[f"{method.upper()} TOTAL ENERGY"], ret, tnm + " return")
elif driver == "gradient":
assert compare_values(
ref_block[f"{method.upper()} TOTAL GRADIENT"],
wfn["return_result"],
tnm + " grad wfn",
atol=atol_g,
rtol=rtol_g,
)
assert compare_values(
ref_block[f"{method.upper()} TOTAL ENERGY"],
wfn["properties"]["return_energy"],
tnm + " prop",
atol=atol_e,
rtol=rtol_e,
)
assert compare_values(
ref_block[f"{method.upper()} TOTAL GRADIENT"],
wfn["properties"]["return_gradient"],
tnm + " grad prop",
atol=atol_g,
rtol=rtol_g,
)
assert compare_values(
ref_block[f"{method.upper()} TOTAL GRADIENT"], ret, tnm + " grad return", atol=atol_g, rtol=rtol_g
)
elif driver == "hessian":
assert compare_values(
ref_block[f"{method.upper()} TOTAL HESSIAN"],
wfn["return_result"],
tnm + " hess wfn",
atol=atol_h,
rtol=rtol_h,
)
assert compare_values(
ref_block[f"{method.upper()} TOTAL ENERGY"],
wfn["properties"]["return_energy"],
tnm + " prop",
atol=atol_e,
rtol=rtol_e,
)
# assert compare_values(ref_block[f"{method.upper()} TOTAL GRADIENT"], wfn["properties"]["return_gradient"], tnm + " grad prop", atol=atol_g, rtol=rtol_g)
assert compare_values(
ref_block[f"{method.upper()} TOTAL HESSIAN"],
wfn["properties"]["return_hessian"],
tnm + " hess prop",
atol=atol_h,
rtol=rtol_h,
)
assert compare_values(
ref_block[f"{method.upper()} TOTAL HESSIAN"], ret, tnm + " hess return", atol=atol_h, rtol=rtol_h
)
# generics checks
# yapf: disable
assert compare(ref_block["N BASIS FUNCTIONS"], wfn["properties"]["calcinfo_nbasis"], tnm + " nbasis wfn"), f"nbasis {wfn['properties']['calcinfo_nbasis']} != {ref_block['N BASIS FUNCTIONS']}"
assert compare(ref_block["N MOLECULAR ORBITALS"], wfn["properties"]["calcinfo_nmo"], tnm + " nmo wfn"), f"nmo {wfn['properties']['calcinfo_nmo']} != {ref_block['N MOLECULAR ORBITALS']}"
assert compare(ref_block["N ALPHA ELECTRONS"], wfn["properties"]["calcinfo_nalpha"], tnm + " nalpha wfn"), f"nalpha {wfn['properties']['calcinfo_nalpha']} != {ref_block['N ALPHA ELECTRONS']}"
assert compare(ref_block["N BETA ELECTRONS"], wfn["properties"]["calcinfo_nbeta"], tnm + " nbeta wfn"), f"nbeta {wfn['properties']['calcinfo_nbeta']} != {ref_block['N BETA ELECTRONS']}"
# yapf: enable
# record
_recorder(
qcprog, qc_module_out, driver, method, reference, fcae, scf_type, corl_type, "fd" if using_fd else "pass", ""
)
# assert 0
def _asserter(asserter_args, contractual_args, contractual_fn):
"""For expectations in `contractual_fn`, check that the QCVars are present in P::e.globals and wfn and match expected ref_block."""
qcvar_stores, ref_block, atol_egh, rtol_egh, ref_block_conv, atol_conv, rtol_conv, tnm = asserter_args
for obj in qcvar_stores:
for rpv, pv, present in contractual_fn(*contractual_args):
label = tnm + " " + pv
atol = atol_egh["EGH".index(rpv.split()[-1][0])]
rtol = rtol_egh["EGH".index(rpv.split()[-1][0])]
if present:
# verify exact match to method (may be df) and near match to conventional (non-df) method
tf, errmsg = compare_values(
ref_block[rpv], query_qcvar(obj, pv), label, atol=atol, rtol=rtol, return_message=True, quiet=True
)
assert compare_values(ref_block[rpv], query_qcvar(obj, pv), label, atol=atol, rtol=rtol), errmsg
tf, errmsg = compare_values(
ref_block_conv[rpv],
query_qcvar(obj, pv),
label,
atol=atol_conv,
rtol=rtol_conv,
return_message=True,
quiet=True,
)
assert compare_values(
ref_block_conv[rpv], query_qcvar(obj, pv), label, atol=atol_conv, rtol=rtol_conv
), errmsg
# Note that the double compare_values lines are to collect the errmsg in the first for assertion in the second.
# If the errmsg isn't present in the assert, the string isn't accessible through `e.value`.
# If a plain bool is compared in the assert, the printed message will show booleans and not numbers.
else:
# verify and forgive known contract violations
assert compare(False, query_has_qcvar(obj, pv), label + " SKIP"), f"{label} wrongly present"
def _recorder(engine, module, driver, method, reference, fcae, scf_type, corl_type, status, note):
with open("stdsuite_qcng.txt", "a") as fp:
stuff = {
"module": module,
"driver": driver,
"method": method,
"reference": reference,
"fcae": fcae,
"scf_type": scf_type,
"corl_type": corl_type,
"status": status,
"note": note,
}
fp.write(f"{stuff!r}\n")
| [
"qcengine.programs.util.mill_qcvars",
"qcdb.Molecule.from_schema",
"numpy.printoptions",
"pytest.raises",
"pprint.PrettyPrinter",
"qcengine.programs.tests.standard_suite_contracts.query_qcvar",
"qcengine.programs.tests.standard_suite_contracts.query_has_qcvar",
"pytest.skip",
"pytest.xfail",
"qcdb... | [((1056, 1087), 'pprint.PrettyPrinter', 'pprint.PrettyPrinter', ([], {'width': '(120)'}), '(width=120)\n', (1076, 1087), False, 'import pprint\n'), ((6921, 6980), 'qcdb.set_options', 'qcdb.set_options', (["{'e_convergence': 10, 'd_convergence': 9}"], {}), "({'e_convergence': 10, 'd_convergence': 9})\n", (6937, 6980), False, 'import qcdb\n'), ((7289, 7322), 'qcdb.set_options', 'qcdb.set_options', (["inp['keywords']"], {}), "(inp['keywords'])\n", (7305, 7322), False, 'import qcdb\n'), ((8407, 8449), 'qcdb.Molecule.from_schema', 'qcdb.Molecule.from_schema', (["wfn['molecule']"], {}), "(wfn['molecule'])\n", (8432, 8449), False, 'import qcdb\n'), ((1661, 1807), 'pytest.skip', 'pytest.skip', (['f"""TCE throwing \'non-Abelian symmetry not permitted\' for HF molecule when not C1. fix this a different way than setting C1."""'], {}), '(\n f"TCE throwing \'non-Abelian symmetry not permitted\' for HF molecule when not C1. fix this a different way than setting C1."\n )\n', (1672, 1807), False, 'import pytest\n'), ((9841, 9876), 'qcengine.programs.util.mill_qcvars', 'mill_qcvars', (['ref2in_mill', 'ref_block'], {}), '(ref2in_mill, ref_block)\n', (9852, 9876), False, 'from qcengine.programs.util import mill_qcvars\n'), ((9902, 9942), 'qcengine.programs.util.mill_qcvars', 'mill_qcvars', (['ref2in_mill', 'ref_block_conv'], {}), '(ref2in_mill, ref_block_conv)\n', (9913, 9942), False, 'from qcengine.programs.util import mill_qcvars\n'), ((7409, 7431), 'pytest.raises', 'pytest.raises', (['errtype'], {}), '(errtype)\n', (7422, 7431), False, 'import pytest\n'), ((9063, 9106), 'numpy.printoptions', 'np.printoptions', ([], {'precision': '(3)', 'suppress': '(True)'}), '(precision=3, suppress=True)\n', (9078, 9106), True, 'import numpy as np\n'), ((10065, 10108), 'numpy.printoptions', 'np.printoptions', ([], {'precision': '(3)', 'suppress': '(True)'}), '(precision=3, suppress=True)\n', (10080, 10108), True, 'import numpy as np\n'), ((11485, 11521), 'qcengine.programs.util.mill_qcvars', 'mill_qcvars', (['ref2out_mill', 'ref_block'], {}), '(ref2out_mill, ref_block)\n', (11496, 11521), False, 'from qcengine.programs.util import mill_qcvars\n'), ((11551, 11592), 'qcengine.programs.util.mill_qcvars', 'mill_qcvars', (['ref2out_mill', 'ref_block_conv'], {}), '(ref2out_mill, ref_block_conv)\n', (11562, 11592), False, 'from qcengine.programs.util import mill_qcvars\n'), ((18040, 18060), 'pytest.xfail', 'pytest.xfail', (['reason'], {}), '(reason)\n', (18052, 18060), False, 'import pytest\n'), ((11007, 11050), 'numpy.printoptions', 'np.printoptions', ([], {'precision': '(3)', 'suppress': '(True)'}), '(precision=3, suppress=True)\n', (11022, 11050), True, 'import numpy as np\n'), ((17515, 17544), 'pytest.raises', 'pytest.raises', (['AssertionError'], {}), '(AssertionError)\n', (17528, 17544), False, 'import pytest\n'), ((22783, 22803), 'qcengine.programs.tests.standard_suite_contracts.query_qcvar', 'query_qcvar', (['obj', 'pv'], {}), '(obj, pv)\n', (22794, 22803), False, 'from qcengine.programs.tests.standard_suite_contracts import contractual_accsd_prt_pr, contractual_ccd, contractual_ccsd, contractual_ccsd_prt_pr, contractual_ccsdpt_prccsd_pr, contractual_ccsdt, contractual_ccsdt1a, contractual_ccsdt1b, contractual_ccsdt2, contractual_ccsdt3, contractual_ccsdt_prq_pr, contractual_ccsdtq, contractual_cisd, contractual_current, contractual_dft_current, contractual_fci, contractual_hf, contractual_lccd, contractual_lccsd, contractual_mp2, contractual_mp2p5, contractual_mp3, contractual_mp4, contractual_mp4_prsdq_pr, contractual_qcisd, contractual_qcisd_prt_pr, query_has_qcvar, query_qcvar\n'), ((22938, 22958), 'qcengine.programs.tests.standard_suite_contracts.query_qcvar', 'query_qcvar', (['obj', 'pv'], {}), '(obj, pv)\n', (22949, 22958), False, 'from qcengine.programs.tests.standard_suite_contracts import contractual_accsd_prt_pr, contractual_ccd, contractual_ccsd, contractual_ccsd_prt_pr, contractual_ccsdpt_prccsd_pr, contractual_ccsdt, contractual_ccsdt1a, contractual_ccsdt1b, contractual_ccsdt2, contractual_ccsdt3, contractual_ccsdt_prq_pr, contractual_ccsdtq, contractual_cisd, contractual_current, contractual_dft_current, contractual_fci, contractual_hf, contractual_lccd, contractual_lccsd, contractual_mp2, contractual_mp2p5, contractual_mp3, contractual_mp4, contractual_mp4_prsdq_pr, contractual_qcisd, contractual_qcisd_prt_pr, query_has_qcvar, query_qcvar\n'), ((23103, 23123), 'qcengine.programs.tests.standard_suite_contracts.query_qcvar', 'query_qcvar', (['obj', 'pv'], {}), '(obj, pv)\n', (23114, 23123), False, 'from qcengine.programs.tests.standard_suite_contracts import contractual_accsd_prt_pr, contractual_ccd, contractual_ccsd, contractual_ccsd_prt_pr, contractual_ccsdpt_prccsd_pr, contractual_ccsdt, contractual_ccsdt1a, contractual_ccsdt1b, contractual_ccsdt2, contractual_ccsdt3, contractual_ccsdt_prq_pr, contractual_ccsdtq, contractual_cisd, contractual_current, contractual_dft_current, contractual_fci, contractual_hf, contractual_lccd, contractual_lccsd, contractual_mp2, contractual_mp2p5, contractual_mp3, contractual_mp4, contractual_mp4_prsdq_pr, contractual_qcisd, contractual_qcisd_prt_pr, query_has_qcvar, query_qcvar\n'), ((23395, 23415), 'qcengine.programs.tests.standard_suite_contracts.query_qcvar', 'query_qcvar', (['obj', 'pv'], {}), '(obj, pv)\n', (23406, 23415), False, 'from qcengine.programs.tests.standard_suite_contracts import contractual_accsd_prt_pr, contractual_ccd, contractual_ccsd, contractual_ccsd_prt_pr, contractual_ccsdpt_prccsd_pr, contractual_ccsdt, contractual_ccsdt1a, contractual_ccsdt1b, contractual_ccsdt2, contractual_ccsdt3, contractual_ccsdt_prq_pr, contractual_ccsdtq, contractual_cisd, contractual_current, contractual_dft_current, contractual_fci, contractual_hf, contractual_lccd, contractual_lccsd, contractual_mp2, contractual_mp2p5, contractual_mp3, contractual_mp4, contractual_mp4_prsdq_pr, contractual_qcisd, contractual_qcisd_prt_pr, query_has_qcvar, query_qcvar\n'), ((23958, 23982), 'qcengine.programs.tests.standard_suite_contracts.query_has_qcvar', 'query_has_qcvar', (['obj', 'pv'], {}), '(obj, pv)\n', (23973, 23982), False, 'from qcengine.programs.tests.standard_suite_contracts import contractual_accsd_prt_pr, contractual_ccd, contractual_ccsd, contractual_ccsd_prt_pr, contractual_ccsdpt_prccsd_pr, contractual_ccsdt, contractual_ccsdt1a, contractual_ccsdt1b, contractual_ccsdt2, contractual_ccsdt3, contractual_ccsdt_prq_pr, contractual_ccsdtq, contractual_cisd, contractual_current, contractual_dft_current, contractual_fci, contractual_hf, contractual_lccd, contractual_lccsd, contractual_mp2, contractual_mp2p5, contractual_mp3, contractual_mp4, contractual_mp4_prsdq_pr, contractual_qcisd, contractual_qcisd_prt_pr, query_has_qcvar, query_qcvar\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 6 09:44:54 2019
@author: thomas
"""
import numpy as np
import matplotlib.pyplot as plt
plt.close('all')
def graycode(M):
if (M==1):
g=['0','1']
elif (M>1):
gs=graycode(M-1)
gsr=gs[::-1]
gs0=['0'+x for x in gs]
gs1=['1'+x for x in gsr]
g=gs0+gs1
return(g)
M=2**4 # number of levels
gwords=graycode(np.log2(M).astype(int)) # Gray code words
u=np.arange(0,M)
Am = 2*u - M +1 # Symbol levels
for i,g in enumerate(gwords):
print('%d -> %6.2f : %s' %(i,Am[i],g))
plt.figure()
plt.stem(u,Am)
plt.xlabel('$m$')
plt.ylabel('$A_m$')
for n in range(0,M):
A = Am[n]
if A>0:
y=A+1
else:
y=A-2
plt.text(n-0.5,y,gwords[n])
minA=np.min(Am)
maxA=np.max(Am)
plt.ylim(minA-4,maxA+4)
plt.tight_layout()
plt.savefig('levelspam.png')
| [
"matplotlib.pyplot.text",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"numpy.max",
"matplotlib.pyplot.close",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.stem",
"matplotlib.pyplot.tight_layout",
"numpy.min",
"matplotlib.pyplot.ylim",
"numpy.log2",
... | [((160, 176), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (169, 176), True, 'import matplotlib.pyplot as plt\n'), ((527, 542), 'numpy.arange', 'np.arange', (['(0)', 'M'], {}), '(0, M)\n', (536, 542), True, 'import numpy as np\n'), ((691, 703), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (701, 703), True, 'import matplotlib.pyplot as plt\n'), ((708, 723), 'matplotlib.pyplot.stem', 'plt.stem', (['u', 'Am'], {}), '(u, Am)\n', (716, 723), True, 'import matplotlib.pyplot as plt\n'), ((723, 740), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""$m$"""'], {}), "('$m$')\n", (733, 740), True, 'import matplotlib.pyplot as plt\n'), ((741, 760), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$A_m$"""'], {}), "('$A_m$')\n", (751, 760), True, 'import matplotlib.pyplot as plt\n'), ((889, 899), 'numpy.min', 'np.min', (['Am'], {}), '(Am)\n', (895, 899), True, 'import numpy as np\n'), ((905, 915), 'numpy.max', 'np.max', (['Am'], {}), '(Am)\n', (911, 915), True, 'import numpy as np\n'), ((917, 945), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(minA - 4)', '(maxA + 4)'], {}), '(minA - 4, maxA + 4)\n', (925, 945), True, 'import matplotlib.pyplot as plt\n'), ((945, 963), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (961, 963), True, 'import matplotlib.pyplot as plt\n'), ((964, 992), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""levelspam.png"""'], {}), "('levelspam.png')\n", (975, 992), True, 'import matplotlib.pyplot as plt\n'), ((854, 885), 'matplotlib.pyplot.text', 'plt.text', (['(n - 0.5)', 'y', 'gwords[n]'], {}), '(n - 0.5, y, gwords[n])\n', (862, 885), True, 'import matplotlib.pyplot as plt\n'), ((479, 489), 'numpy.log2', 'np.log2', (['M'], {}), '(M)\n', (486, 489), True, 'import numpy as np\n')] |
import torch
import unittest
from qtorch.quant import *
from qtorch import FixedPoint, BlockFloatingPoint, FloatingPoint
DEBUG = False
log = lambda m: print(m) if DEBUG else False
class TestStochastic(unittest.TestCase):
"""
invariant: quantized numbers cannot be greater than the maximum representable number
or lower than the maximum representable number
"""
def test_fixed(self):
"""test fixed point clamping"""
for d in ["cpu", "cuda"]:
for r in ["stochastic", "nearest"]:
wl = 5
fl = 4
t_min = -(2 ** (wl - fl - 1))
t_max = 2 ** (wl - fl - 1) - 2 ** (-fl)
a = torch.linspace(-2, 2, steps=100, device=d)
clamp_a = fixed_point_quantize(a, wl=wl, fl=fl, clamp=True, rounding=r)
self.assertEqual(t_max, clamp_a.max().item())
self.assertEqual(t_min, clamp_a.min().item())
a = torch.linspace(-2, 2, steps=100, device=d)
no_clamp_a = fixed_point_quantize(a, wl=wl, fl=fl, clamp=False, rounding=r)
self.assertLess(t_max, no_clamp_a.max().item())
self.assertGreater(t_min, no_clamp_a.min().item())
def test_float(self):
"""test floating point quantization"""
formats = [(2,2),(2,3),(3,2)]
for exp, man in formats:
for d in ["cpu", "cuda"]:
for r in ["stochastic", "nearest"]:
a_max = 2 ** (2 ** (exp - 1)) * (1 - 2 ** (-man - 1))
a_min = 2 ** (-(2 ** (exp - 1)) + 1)
max_exp=int((2**exp)/2)
min_exp=-(max_exp-2)
mantissa_step=2**(-man)
min_mantissa=mantissa_step # When denormalized
max_mantissa=2-mantissa_step # When normalized, mantissa goes from 1 to 2-mantissa_step
a_min = 2**min_exp*min_mantissa
a_max = 2**max_exp*max_mantissa
expected_vals=[]
log(f"With {exp} exponent bits, our exponent goes from {min_exp} to {max_exp}")
log(f"With {man} mantissa bits, our mantissa goes from {min_mantissa} (denormalized) to {max_mantissa}")
log(f"With {man} mantissa bits and {exp} exponent bits, we can go from {a_min} to {a_max}")
representable_normalized =[]
for sign in [1,-1]:
for e in range(0,2**exp):
for m in range(0,2**man):
if e==0:
val = sign*(2**(e+min_exp)*m*2**(-man))
log(f"{0 if sign==1 else 1} {e:0{exp}b} {m:0{man}b} = {sign} * 2^{e+min_exp} * {m*2**(-man)} \t= {val} (denormalized)")
else:
val = sign*(2**(e+min_exp-1)*(1+(m*2**(-man))))
log(f"{0 if sign==1 else 1} {e:0{exp}b} {m:0{man}b} = {sign} * 2^{e+min_exp-1} * {1+(m*2**(-man))} \t= {val}")
if val not in expected_vals:
expected_vals.append(val)
expected_vals.sort()
# Block box test to get representable numbers
import numpy as np
quant_vals=[]
for i in np.arange(-30,30,.01):
a = torch.Tensor([i]).to(device=d)
quant_a = float_quantize(a, exp=exp, man=man, rounding=r)
if quant_a[0] not in quant_vals:
quant_vals.append(quant_a[0].item())
log("Values representable in QPytorch")
log(quant_vals)
self.assertEqual(quant_vals, expected_vals)
if __name__ == "__main__":
unittest.main()
| [
"unittest.main",
"torch.Tensor",
"torch.linspace",
"numpy.arange"
] | [((3957, 3972), 'unittest.main', 'unittest.main', ([], {}), '()\n', (3970, 3972), False, 'import unittest\n'), ((697, 739), 'torch.linspace', 'torch.linspace', (['(-2)', '(2)'], {'steps': '(100)', 'device': 'd'}), '(-2, 2, steps=100, device=d)\n', (711, 739), False, 'import torch\n'), ((973, 1015), 'torch.linspace', 'torch.linspace', (['(-2)', '(2)'], {'steps': '(100)', 'device': 'd'}), '(-2, 2, steps=100, device=d)\n', (987, 1015), False, 'import torch\n'), ((3478, 3502), 'numpy.arange', 'np.arange', (['(-30)', '(30)', '(0.01)'], {}), '(-30, 30, 0.01)\n', (3487, 3502), True, 'import numpy as np\n'), ((3529, 3546), 'torch.Tensor', 'torch.Tensor', (['[i]'], {}), '([i])\n', (3541, 3546), False, 'import torch\n')] |
import numpy as np
import random
import copy
class Environment():
def __init__(self, agents, n_players=4, tiles_per_player=7):
self.tiles_per_player = tiles_per_player
self.hand_sizes = []
self.n_players = n_players
self.agents = agents
self.pile = generate_tiles()
for agent in agents:
for i in range(tiles_per_player):
agent.hand.append(self.pile.pop())
self.hand_sizes.append(len(agent.hand))
self.table = []
def new_episode(self):
self.pile = generate_tiles()
for agent in agents:
for i in range(tiles_per_player):
agent.hand.append(self.pile.pop())
self.hand_sizes.append(len(agent.hand))
self.table = []
def recalculate_hand_sizes(self):
for i in range(self.n_players):
self.hand_sizes[i] = len(self.agents[i].hand)
def get_observation(self):
observation = []
observation.append(self.table)
self.recalculate_hand_sizes()
observation.append(self.hand_sizes)
return observation
def get_observation_nn(self, agent_id):
observation = []
observation.append(len(self.agents[agent_id].hand))
for i in range(self.tiles_per_player):
if i < len(self.agents[agent_id].hand):
observation.append(tiles_ids[tuple(self.agents[agent_id].hand[i])])
else:
observation.append(-1)
for i in range(len(self.hand_sizes)):
if agent_id != i:
observation.append(self.hand_sizes[i])
for i in range(len(self.agents)):
if agent_id != i:
observation.append(tiles_ids[tuple(self.agents[i].last_tile_played)])
observation.append(str(self.agents[i].last_pos_played))
for i in range(28):
if i < len(self.table):
observation.append(tiles_ids[tuple(self.table[i])])
else:
observation.append(-1)
return observation
def get_winner(self):
winner = -1
for i in range(len(agents)):
if len(agents[i].hand) == 0:
winner = i
return winner
def get_winner_2(self):
print("Overtime")
winner = -1
min_ = self.tiles_per_player
for i in range(len(agents)):
if len(agents[i].hand) < min_:
min_ = len(agents[i].hand)
winner = i
elif len(agents[i].hand) == min_:
winner = -1
break
return winner
class RandomAgent():
def __init__(self):
self.hand = []
self.last_tile_played = []
self.last_pos_played = -1
def act(self, observation):
play = []
for i in range(10):
pos = random.randrange(len(self.hand))
tile = self.hand[pos]
play = playable_tile(observation[0], tile)
if play != []:
self.hand.pop(pos)
break
else:
play = []
if play == []:
last_tile_played = -1
last_pos_played = -1
else:
last_tile_played = play[0]
last_pos_played = play[1]
return play
class DeepQNetworkAgent(AgentBase):
""" Represents a Snake agent powered by DQN with experience replay. """
def __init__(self, model, num_last_frames=4, memory_size=1000):
"""
Create a new DQN-based agent.
Args:
model: a compiled DQN model.
num_last_frames (int): the number of last frames the agent will consider.
memory_size (int): memory size limit for experience replay (-1 for unlimited).
"""
assert model.input_shape[1] == num_last_frames, 'Model input shape should be (num_frames, grid_size, grid_size)'
assert len(model.output_shape) == 2, 'Model output shape should be (num_samples, num_actions)'
self.model = model
self.num_last_frames = num_last_frames
self.memory = ExperienceReplay((num_last_frames,) + model.input_shape[-2:], model.output_shape[-1], memory_size)
self.frames = None
def begin_episode(self):
""" Reset the agent for a new episode. """
self.frames = None
def get_last_frames(self, observation):
"""
Get the pixels of the last `num_last_frames` observations, the current frame being the last.
Args:
observation: observation at the current timestep.
Returns:
Observations for the last `num_last_frames` frames.
"""
frame = observation
if self.frames is None:
self.frames = collections.deque([frame] * self.num_last_frames)
else:
self.frames.append(frame)
self.frames.popleft()
return np.expand_dims(self.frames, 0)
def train(self, env, num_episodes=1000, batch_size=50, discount_factor=0.9, checkpoint_freq=None,
exploration_range=(1.0, 0.1), exploration_phase_size=0.5):
"""
Train the agent to perform well in the given Snake environment.
Args:
env:
an instance of Snake environment.
num_episodes (int):
the number of episodes to run during the training.
batch_size (int):
the size of the learning sample for experience replay.
discount_factor (float):
discount factor (gamma) for computing the value function.
checkpoint_freq (int):
the number of episodes after which a new model checkpoint will be created.
exploration_range (tuple):
a (max, min) range specifying how the exploration rate should decay over time.
exploration_phase_size (float):
the percentage of the training process at which
the exploration rate should reach its minimum.
"""
# Calculate the constant exploration decay speed for each episode.
max_exploration_rate, min_exploration_rate = exploration_range
exploration_decay = ((max_exploration_rate - min_exploration_rate) / (num_episodes * exploration_phase_size))
exploration_rate = max_exploration_rate
for episode in range(num_episodes):
# Reset the environment for the new episode.
timestep = env.new_episode()
self.begin_episode()
game_over = False
loss = 0.0
# Observe the initial state.
state = self.get_last_frames(timestep.observation)
while not game_over:
if np.random.random() < exploration_rate:
# Explore: take a random action.
action = np.random.randint(env.num_actions)
else:
# Exploit: take the best known action for this state.
q = self.model.predict(state)
action = np.argmax(q[0])
# Act on the environment.
env.choose_action(action)
timestep = env.timestep()
# Remember a new piece of experience.
reward = timestep.reward
state_next = self.get_last_frames(timestep.observation)
game_over = timestep.is_episode_end
experience_item = [state, action, reward, state_next, game_over]
self.memory.remember(*experience_item)
state = state_next
# Sample a random batch from experience.
batch = self.memory.get_batch(
model=self.model,
batch_size=batch_size,
discount_factor=discount_factor
)
# Learn on the batch.
if batch:
inputs, targets = batch
loss += float(self.model.train_on_batch(inputs, targets))
if checkpoint_freq and (episode % checkpoint_freq) == 0:
self.model.save(f'dqn-{episode:08d}.model')
if exploration_rate > min_exploration_rate:
exploration_rate -= exploration_decay
summary = 'Episode {:5d}/{:5d} | Loss {:8.4f} | Exploration {:.2f} | ' + \
'Fruits {:2d} | Timesteps {:4d} | Total Reward {:4d}'
print(summary.format(
episode + 1, num_episodes, loss, exploration_rate,
env.stats.fruits_eaten, env.stats.timesteps_survived, env.stats.sum_episode_rewards,
))
self.model.save('dqn-final.model')
def act(self, observation, reward):
"""
Choose the next action to take.
Args:
observation: observable state for the current timestep.
reward: reward received at the beginning of the current timestep.
Returns:
The index of the action to take next.
"""
state = self.get_last_frames(observation)
q = self.model.predict(state)[0]
return np.argmax(q)
tiles_ids = {():0}
def generate_tiles(max_value=6):
tiles = []
a=0
for i in range(max_value+1):
for j in range(i+1):
my_tile = (i,j)
tiles.append([i, j])
tiles_ids[my_tile] = a
tiles_ids[tuple(turn_tile(my_tile))] = a
a += 1
print(tiles_ids)
random.shuffle(tiles)
return tiles
def turn_tile(tile):
new_tile = [copy.copy(tile[1]), copy.copy(tile[0])]
return new_tile
def playable_tile(table, tile):
playable = []
t_left = table[0]
t_right = table[-1]
if t_left[0] == tile[1]:
playable = [tile, 0]
elif t_left[0] == tile[0]:
playable = [turn_tile(tile), 0]
elif t_right[1] == tile[1]:
playable = [turn_tile(tile), 1]
elif t_right[1] == tile[0]:
playable = [tile, 1]
return playable
def play(agents, env, verbose=False, num_episodes=1):
winner = env.get_winner()
turn = 0
passed_count = 0
first_tile = [-1, -1]
first_agent = 0
first_tile_pos = 0
for i in range(len(agents)):
for j in range(len(agents[i].hand)):
if env.agents[i].hand[j][0] > first_tile[0] and env.agents[i].hand[j][0] == agents[i].hand[j][1]:
first_tile = agents[i].hand[j]
first_agent = i
first_tile_pos = j
env.table.append(agents[first_agent].hand.pop(first_tile_pos))
turn += 1
for i in range(first_agent, len(agents)):
print("-------------------------------")
print(f"Table: {env.table}")
print(f"Player {i} hand: {agents[i].hand}")
played_tile = agents[i].act(env.get_observation())
if len(played_tile) > 0:
print(f"Player {i} played {played_tile}")
if(played_tile[1] == 0):
env.table.insert(0, played_tile[0])
elif(played_tile[1] == 1):
env.table.append(played_tile[0])
else:
print("Something went wrong")
else:
passed_count += 1
print(f"Player {i} passed")
winner = env.get_winner()
if winner != -1:
break
while(winner == -1):
print(env.get_observation_nn(0))
if winner != -1:
break
turn += 1
if passed_count == len(agents):
winner = env.get_winner_2()
break
passed_count = 0
for i in range(len(agents)):
print("-------------------------------")
print(f"Table: {env.table}")
print(f"Player {i} hand: {agents[i].hand}")
played_tile = agents[i].act(env.get_observation())
if len(played_tile) > 0:
print(f"Player {i} played {played_tile}")
if(played_tile[1] == 0):
env.table.insert(0, played_tile[0])
elif(played_tile[1] == 1):
env.table.append(played_tile[0])
else:
print("Something went wrong")
else:
passed_count += 1
print(f"Player {i} passed")
winner = env.get_winner()
if winner != -1:
break
if winner == -1:
print()
print("Tie!")
else:
print()
print(f"Player {winner} won!")
agents = []
for i in range(4):
agents.append(RandomAgent())
for i in range(1):
env = Environment(agents)
play(agents, env, verbose=True)
| [
"random.shuffle",
"numpy.random.random",
"numpy.argmax",
"numpy.random.randint",
"numpy.expand_dims",
"copy.copy"
] | [((8798, 8819), 'random.shuffle', 'random.shuffle', (['tiles'], {}), '(tiles)\n', (8812, 8819), False, 'import random\n'), ((4260, 4290), 'numpy.expand_dims', 'np.expand_dims', (['self.frames', '(0)'], {}), '(self.frames, 0)\n', (4274, 4290), True, 'import numpy as np\n'), ((8518, 8530), 'numpy.argmax', 'np.argmax', (['q'], {}), '(q)\n', (8527, 8530), True, 'import numpy as np\n'), ((8870, 8888), 'copy.copy', 'copy.copy', (['tile[1]'], {}), '(tile[1])\n', (8879, 8888), False, 'import copy\n'), ((8890, 8908), 'copy.copy', 'copy.copy', (['tile[0]'], {}), '(tile[0])\n', (8899, 8908), False, 'import copy\n'), ((6096, 6114), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (6112, 6114), True, 'import numpy as np\n'), ((6217, 6251), 'numpy.random.randint', 'np.random.randint', (['env.num_actions'], {}), '(env.num_actions)\n', (6234, 6251), True, 'import numpy as np\n'), ((6427, 6442), 'numpy.argmax', 'np.argmax', (['q[0]'], {}), '(q[0])\n', (6436, 6442), True, 'import numpy as np\n')] |
import os
from pyBigstick.nucleus import Nucleus
import streamlit as st
import numpy as np
import plotly.express as px
from barChartPlotly import plotly_barcharts_3d
from PIL import Image
he4_image = Image.open('assets/he4.png')
nucl_image = Image.open('assets/nucl_symbol.png')
table_image = Image.open('assets/table.jpg')
scattering_image = Image.open('assets/scattering.jpeg')
deexcitation_image = Image.open('assets/deexcitation.png')
lvl_image = Image.open('assets/Energy_levels.png')
shells_image = Image.open('assets/shells.png')
bs = os.getcwd() +'/src/bigstick.x'
header_container = st.container()
intro_container = st.container()
bs_container = st.container()
states_container = st.container()
densities_container = st.container()
hide_table_row_index = """
<style>
tbody th {display:none}
.blank {display:none}
</style>
"""
light_nuclei = ['F', 'Ne', 'Na', 'Mg', 'Al', 'Si', 'P', 'S', 'Cl']
with header_container:
st.title('pyBigstick')
st.markdown("""This streamlit app visualizes the nuclear transitions calculated by [pyBigstick](https://github.com/noctildon/pyBigstick),
including the energy levels and the density matrices.""")
with intro_container:
st.subheader("Basic knowledge about nuclear physics")
st.markdown('Physicists usually use a symbol + 2 number to represent a unique nucleus')
st.image(nucl_image, width=500)
st.markdown('For example, the following is identical to He (Helium) with mass number 4 and atomic number 2, or equivalently 2 protons and 2 neutrons.')
st.image(he4_image,width=300)
st.markdown('Atomic number can be determined by element symbol uniquely, so sometimes it is skipped and ignored.')
st.text('And this is the well-known periodic table')
st.image(table_image,width=800)
st.markdown('Experimentalists use neutrinos (an extremely small and light particle) to hit the nucleus. This process is called "scattering".')
st.image(scattering_image,width=800)
st.markdown("""Before scattering the nucleus has lowest possbile energy (ground state). After scattering nucleus gain some energy from the neutrinos,
being called "excited nucleus" or "excited state". Then there is a chance that the excited nucleus would drop back to the ground state by emitting gamma ray.
""")
col1, col2 = st.columns(2)
with col1:
st.image(deexcitation_image,width=400)
with col2:
st.image(lvl_image,width=400)
st.markdown("""What happen in the scattering is that some of the nucleons get excited to the orbit with high energy.
The core algorithm of pyBigstick is to iterate all possible combinations and transitions of the nucleons.
And the density matrices describe how nucleons move among the orbits by talking us a probability-like value.
""")
st.image(shells_image,width=700)
with bs_container:
st.subheader("Control panel")
st.markdown("""Input the info of the interested nucleus, eg. F19, Be10.
Not sure which nucleus to pick? check out [this](https://periodictable.com/Isotopes/009.19/index.html).
(Not all of the nucleus is possible to calculate).""")
col1_1, col1_2 = st.columns(2)
with col1_1:
s1 = st.selectbox('The nucleus to calculate', light_nuclei, index=0)
with col1_2:
s2 = st.selectbox('Mass number', range(9,41), index=10)
col2_1, col2_2 = st.columns(2)
with col2_1:
n_states = st.selectbox('Number of states to calculate (more states always need more time)', range(1,7), index=2)
with col2_2:
maxiter = st.selectbox('Number of iteration (higher iteration is more accurate on results, but takes longer)', np.arange(50,510,10), index=5)
s1 = s1.lower()
nucl_name = f'{s1}{s2}'
st.text(f'Calculate {nucl_name}...')
nu = Nucleus(nucl_name, n_states=n_states, maxiter=maxiter)
if st.button('Clean the previous result and rerun'):
st.write(f'Successfully clean nucleus {nucl_name}. Running {nucl_name} again...')
nu.clean()
if not nu.check():
nu.script_save()
nu.prepare()
nu.run(bs=bs)
nu.save_results()
with states_container:
st.subheader('Energy level states')
st.markdown("""When the scattering happens to a nucleus, the nucleus could be excited to higher state.
In general, initially the nucleus is in ground state (the state with the lowest energy).
Then after scattering, it is excited to some higher state with energy higher than ground state.
We also label the state with n. Ground state has n=1. First excited state has n=2. Second excited has n=3, and so on.""")
fig = px.bar(nu.states, x='state', y='Ex',
labels={
'state': 'State',
'Ex': 'Excitation energy (MeV)'
})
st.plotly_chart(fig, use_container_width=True)
if st.checkbox('Show all states data'):
st.text('States')
st.write(nu.states)
with densities_container:
st.subheader('Density matrices')
st.markdown("""The amp (transition amplitdue) in the last column below is (to some degree) proportional to the probability that
a nucleon moves from one orbit to another, given the condition that the nucleus jumps from one state to another (say from n=1 to n=2).
Jt and Tt are the spin and isospin of the transition, respectively. They are the attributes of a transition.
A transition could have multiple values of Jt. Tt can be either 0 or 1. Most of the amp is zero.""")
col1, col2, col3, col4 = st.columns(4)
with col1:
statei = st.selectbox('Initial state', nu.states['state'])
with col2:
statej = st.selectbox('Final state', nu.states['state'])
with col3:
Jt = st.selectbox('Jt', np.unique(nu.densities['Jt']))
with col4:
Tt = st.selectbox('Tt', [0,1])
filter_densities = nu.densities.loc[(nu.densities['statei']==statei) & (nu.densities['statej']==statej) &\
(nu.densities['Jt']==Jt) & (nu.densities['Tt']==Tt)]
st.subheader('Non-zero elements')
st.markdown(hide_table_row_index, unsafe_allow_html=True)
st.table(filter_densities)
st.subheader('3D plot of the density matrices')
st.text('The plot only shows non-zero elements.')
if not filter_densities.empty:
fig = plotly_barcharts_3d(filter_densities['orba'], filter_densities['orbb'], filter_densities['amp'],
x_title='orbit a', y_title='orbit b', z_title='amp')
fig.update_layout(width=700, height=700, yaxis = dict(scaleanchor = 'x'))
st.plotly_chart(fig, use_container_width=True)
else:
st.text('All elements are zero, so the plot is skipped.')
if st.checkbox('Show all raw densities data'):
st.text('Density matrices')
st.write(nu.densities) | [
"streamlit.image",
"streamlit.table",
"streamlit.button",
"numpy.arange",
"streamlit.title",
"streamlit.columns",
"streamlit.markdown",
"streamlit.write",
"streamlit.text",
"barChartPlotly.plotly_barcharts_3d",
"streamlit.subheader",
"streamlit.selectbox",
"streamlit.container",
"streamlit... | [((202, 230), 'PIL.Image.open', 'Image.open', (['"""assets/he4.png"""'], {}), "('assets/he4.png')\n", (212, 230), False, 'from PIL import Image\n'), ((244, 280), 'PIL.Image.open', 'Image.open', (['"""assets/nucl_symbol.png"""'], {}), "('assets/nucl_symbol.png')\n", (254, 280), False, 'from PIL import Image\n'), ((295, 325), 'PIL.Image.open', 'Image.open', (['"""assets/table.jpg"""'], {}), "('assets/table.jpg')\n", (305, 325), False, 'from PIL import Image\n'), ((345, 381), 'PIL.Image.open', 'Image.open', (['"""assets/scattering.jpeg"""'], {}), "('assets/scattering.jpeg')\n", (355, 381), False, 'from PIL import Image\n'), ((403, 440), 'PIL.Image.open', 'Image.open', (['"""assets/deexcitation.png"""'], {}), "('assets/deexcitation.png')\n", (413, 440), False, 'from PIL import Image\n'), ((453, 491), 'PIL.Image.open', 'Image.open', (['"""assets/Energy_levels.png"""'], {}), "('assets/Energy_levels.png')\n", (463, 491), False, 'from PIL import Image\n'), ((507, 538), 'PIL.Image.open', 'Image.open', (['"""assets/shells.png"""'], {}), "('assets/shells.png')\n", (517, 538), False, 'from PIL import Image\n'), ((597, 611), 'streamlit.container', 'st.container', ([], {}), '()\n', (609, 611), True, 'import streamlit as st\n'), ((630, 644), 'streamlit.container', 'st.container', ([], {}), '()\n', (642, 644), True, 'import streamlit as st\n'), ((660, 674), 'streamlit.container', 'st.container', ([], {}), '()\n', (672, 674), True, 'import streamlit as st\n'), ((694, 708), 'streamlit.container', 'st.container', ([], {}), '()\n', (706, 708), True, 'import streamlit as st\n'), ((731, 745), 'streamlit.container', 'st.container', ([], {}), '()\n', (743, 745), True, 'import streamlit as st\n'), ((545, 556), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (554, 556), False, 'import os\n'), ((997, 1019), 'streamlit.title', 'st.title', (['"""pyBigstick"""'], {}), "('pyBigstick')\n", (1005, 1019), True, 'import streamlit as st\n'), ((1024, 1237), 'streamlit.markdown', 'st.markdown', (['"""This streamlit app visualizes the nuclear transitions calculated by [pyBigstick](https://github.com/noctildon/pyBigstick),\n including the energy levels and the density matrices."""'], {}), '(\n """This streamlit app visualizes the nuclear transitions calculated by [pyBigstick](https://github.com/noctildon/pyBigstick),\n including the energy levels and the density matrices."""\n )\n', (1035, 1237), True, 'import streamlit as st\n'), ((1256, 1309), 'streamlit.subheader', 'st.subheader', (['"""Basic knowledge about nuclear physics"""'], {}), "('Basic knowledge about nuclear physics')\n", (1268, 1309), True, 'import streamlit as st\n'), ((1314, 1406), 'streamlit.markdown', 'st.markdown', (['"""Physicists usually use a symbol + 2 number to represent a unique nucleus"""'], {}), "(\n 'Physicists usually use a symbol + 2 number to represent a unique nucleus')\n", (1325, 1406), True, 'import streamlit as st\n'), ((1406, 1437), 'streamlit.image', 'st.image', (['nucl_image'], {'width': '(500)'}), '(nucl_image, width=500)\n', (1414, 1437), True, 'import streamlit as st\n'), ((1442, 1603), 'streamlit.markdown', 'st.markdown', (['"""For example, the following is identical to He (Helium) with mass number 4 and atomic number 2, or equivalently 2 protons and 2 neutrons."""'], {}), "(\n 'For example, the following is identical to He (Helium) with mass number 4 and atomic number 2, or equivalently 2 protons and 2 neutrons.'\n )\n", (1453, 1603), True, 'import streamlit as st\n'), ((1598, 1628), 'streamlit.image', 'st.image', (['he4_image'], {'width': '(300)'}), '(he4_image, width=300)\n', (1606, 1628), True, 'import streamlit as st\n'), ((1632, 1756), 'streamlit.markdown', 'st.markdown', (['"""Atomic number can be determined by element symbol uniquely, so sometimes it is skipped and ignored."""'], {}), "(\n 'Atomic number can be determined by element symbol uniquely, so sometimes it is skipped and ignored.'\n )\n", (1643, 1756), True, 'import streamlit as st\n'), ((1752, 1804), 'streamlit.text', 'st.text', (['"""And this is the well-known periodic table"""'], {}), "('And this is the well-known periodic table')\n", (1759, 1804), True, 'import streamlit as st\n'), ((1809, 1841), 'streamlit.image', 'st.image', (['table_image'], {'width': '(800)'}), '(table_image, width=800)\n', (1817, 1841), True, 'import streamlit as st\n'), ((1846, 1998), 'streamlit.markdown', 'st.markdown', (['"""Experimentalists use neutrinos (an extremely small and light particle) to hit the nucleus. This process is called "scattering"."""'], {}), '(\n \'Experimentalists use neutrinos (an extremely small and light particle) to hit the nucleus. This process is called "scattering".\'\n )\n', (1857, 1998), True, 'import streamlit as st\n'), ((1993, 2030), 'streamlit.image', 'st.image', (['scattering_image'], {'width': '(800)'}), '(scattering_image, width=800)\n', (2001, 2030), True, 'import streamlit as st\n'), ((2034, 2368), 'streamlit.markdown', 'st.markdown', (['"""Before scattering the nucleus has lowest possbile energy (ground state). After scattering nucleus gain some energy from the neutrinos,\n being called "excited nucleus" or "excited state". Then there is a chance that the excited nucleus would drop back to the ground state by emitting gamma ray.\n """'], {}), '(\n """Before scattering the nucleus has lowest possbile energy (ground state). After scattering nucleus gain some energy from the neutrinos,\n being called "excited nucleus" or "excited state". Then there is a chance that the excited nucleus would drop back to the ground state by emitting gamma ray.\n """\n )\n', (2045, 2368), True, 'import streamlit as st\n'), ((2377, 2390), 'streamlit.columns', 'st.columns', (['(2)'], {}), '(2)\n', (2387, 2390), True, 'import streamlit as st\n'), ((2512, 2878), 'streamlit.markdown', 'st.markdown', (['"""What happen in the scattering is that some of the nucleons get excited to the orbit with high energy.\n The core algorithm of pyBigstick is to iterate all possible combinations and transitions of the nucleons.\n And the density matrices describe how nucleons move among the orbits by talking us a probability-like value.\n """'], {}), '(\n """What happen in the scattering is that some of the nucleons get excited to the orbit with high energy.\n The core algorithm of pyBigstick is to iterate all possible combinations and transitions of the nucleons.\n And the density matrices describe how nucleons move among the orbits by talking us a probability-like value.\n """\n )\n', (2523, 2878), True, 'import streamlit as st\n'), ((2873, 2906), 'streamlit.image', 'st.image', (['shells_image'], {'width': '(700)'}), '(shells_image, width=700)\n', (2881, 2906), True, 'import streamlit as st\n'), ((2931, 2960), 'streamlit.subheader', 'st.subheader', (['"""Control panel"""'], {}), "('Control panel')\n", (2943, 2960), True, 'import streamlit as st\n'), ((2965, 3221), 'streamlit.markdown', 'st.markdown', (['"""Input the info of the interested nucleus, eg. F19, Be10.\n Not sure which nucleus to pick? check out [this](https://periodictable.com/Isotopes/009.19/index.html).\n (Not all of the nucleus is possible to calculate)."""'], {}), '(\n """Input the info of the interested nucleus, eg. F19, Be10.\n Not sure which nucleus to pick? check out [this](https://periodictable.com/Isotopes/009.19/index.html).\n (Not all of the nucleus is possible to calculate)."""\n )\n', (2976, 3221), True, 'import streamlit as st\n'), ((3234, 3247), 'streamlit.columns', 'st.columns', (['(2)'], {}), '(2)\n', (3244, 3247), True, 'import streamlit as st\n'), ((3445, 3458), 'streamlit.columns', 'st.columns', (['(2)'], {}), '(2)\n', (3455, 3458), True, 'import streamlit as st\n'), ((3818, 3854), 'streamlit.text', 'st.text', (['f"""Calculate {nucl_name}..."""'], {}), "(f'Calculate {nucl_name}...')\n", (3825, 3854), True, 'import streamlit as st\n'), ((3864, 3918), 'pyBigstick.nucleus.Nucleus', 'Nucleus', (['nucl_name'], {'n_states': 'n_states', 'maxiter': 'maxiter'}), '(nucl_name, n_states=n_states, maxiter=maxiter)\n', (3871, 3918), False, 'from pyBigstick.nucleus import Nucleus\n'), ((3927, 3975), 'streamlit.button', 'st.button', (['"""Clean the previous result and rerun"""'], {}), "('Clean the previous result and rerun')\n", (3936, 3975), True, 'import streamlit as st\n'), ((4229, 4264), 'streamlit.subheader', 'st.subheader', (['"""Energy level states"""'], {}), "('Energy level states')\n", (4241, 4264), True, 'import streamlit as st\n'), ((4269, 4712), 'streamlit.markdown', 'st.markdown', (['"""When the scattering happens to a nucleus, the nucleus could be excited to higher state.\n In general, initially the nucleus is in ground state (the state with the lowest energy).\n Then after scattering, it is excited to some higher state with energy higher than ground state.\n We also label the state with n. Ground state has n=1. First excited state has n=2. Second excited has n=3, and so on."""'], {}), '(\n """When the scattering happens to a nucleus, the nucleus could be excited to higher state.\n In general, initially the nucleus is in ground state (the state with the lowest energy).\n Then after scattering, it is excited to some higher state with energy higher than ground state.\n We also label the state with n. Ground state has n=1. First excited state has n=2. Second excited has n=3, and so on."""\n )\n', (4280, 4712), True, 'import streamlit as st\n'), ((4714, 4814), 'plotly.express.bar', 'px.bar', (['nu.states'], {'x': '"""state"""', 'y': '"""Ex"""', 'labels': "{'state': 'State', 'Ex': 'Excitation energy (MeV)'}"}), "(nu.states, x='state', y='Ex', labels={'state': 'State', 'Ex':\n 'Excitation energy (MeV)'})\n", (4720, 4814), True, 'import plotly.express as px\n'), ((4853, 4899), 'streamlit.plotly_chart', 'st.plotly_chart', (['fig'], {'use_container_width': '(True)'}), '(fig, use_container_width=True)\n', (4868, 4899), True, 'import streamlit as st\n'), ((4908, 4943), 'streamlit.checkbox', 'st.checkbox', (['"""Show all states data"""'], {}), "('Show all states data')\n", (4919, 4943), True, 'import streamlit as st\n'), ((5031, 5063), 'streamlit.subheader', 'st.subheader', (['"""Density matrices"""'], {}), "('Density matrices')\n", (5043, 5063), True, 'import streamlit as st\n'), ((5068, 5574), 'streamlit.markdown', 'st.markdown', (['"""The amp (transition amplitdue) in the last column below is (to some degree) proportional to the probability that\n a nucleon moves from one orbit to another, given the condition that the nucleus jumps from one state to another (say from n=1 to n=2).\n Jt and Tt are the spin and isospin of the transition, respectively. They are the attributes of a transition.\n A transition could have multiple values of Jt. Tt can be either 0 or 1. Most of the amp is zero."""'], {}), '(\n """The amp (transition amplitdue) in the last column below is (to some degree) proportional to the probability that\n a nucleon moves from one orbit to another, given the condition that the nucleus jumps from one state to another (say from n=1 to n=2).\n Jt and Tt are the spin and isospin of the transition, respectively. They are the attributes of a transition.\n A transition could have multiple values of Jt. Tt can be either 0 or 1. Most of the amp is zero."""\n )\n', (5079, 5574), True, 'import streamlit as st\n'), ((5595, 5608), 'streamlit.columns', 'st.columns', (['(4)'], {}), '(4)\n', (5605, 5608), True, 'import streamlit as st\n'), ((6082, 6115), 'streamlit.subheader', 'st.subheader', (['"""Non-zero elements"""'], {}), "('Non-zero elements')\n", (6094, 6115), True, 'import streamlit as st\n'), ((6120, 6177), 'streamlit.markdown', 'st.markdown', (['hide_table_row_index'], {'unsafe_allow_html': '(True)'}), '(hide_table_row_index, unsafe_allow_html=True)\n', (6131, 6177), True, 'import streamlit as st\n'), ((6182, 6208), 'streamlit.table', 'st.table', (['filter_densities'], {}), '(filter_densities)\n', (6190, 6208), True, 'import streamlit as st\n'), ((6214, 6261), 'streamlit.subheader', 'st.subheader', (['"""3D plot of the density matrices"""'], {}), "('3D plot of the density matrices')\n", (6226, 6261), True, 'import streamlit as st\n'), ((6266, 6315), 'streamlit.text', 'st.text', (['"""The plot only shows non-zero elements."""'], {}), "('The plot only shows non-zero elements.')\n", (6273, 6315), True, 'import streamlit as st\n'), ((6755, 6797), 'streamlit.checkbox', 'st.checkbox', (['"""Show all raw densities data"""'], {}), "('Show all raw densities data')\n", (6766, 6797), True, 'import streamlit as st\n'), ((2414, 2453), 'streamlit.image', 'st.image', (['deexcitation_image'], {'width': '(400)'}), '(deexcitation_image, width=400)\n', (2422, 2453), True, 'import streamlit as st\n'), ((2476, 2506), 'streamlit.image', 'st.image', (['lvl_image'], {'width': '(400)'}), '(lvl_image, width=400)\n', (2484, 2506), True, 'import streamlit as st\n'), ((3278, 3341), 'streamlit.selectbox', 'st.selectbox', (['"""The nucleus to calculate"""', 'light_nuclei'], {'index': '(0)'}), "('The nucleus to calculate', light_nuclei, index=0)\n", (3290, 3341), True, 'import streamlit as st\n'), ((3985, 4071), 'streamlit.write', 'st.write', (['f"""Successfully clean nucleus {nucl_name}. Running {nucl_name} again..."""'], {}), "(\n f'Successfully clean nucleus {nucl_name}. Running {nucl_name} again...')\n", (3993, 4071), True, 'import streamlit as st\n'), ((4953, 4970), 'streamlit.text', 'st.text', (['"""States"""'], {}), "('States')\n", (4960, 4970), True, 'import streamlit as st\n'), ((4979, 4998), 'streamlit.write', 'st.write', (['nu.states'], {}), '(nu.states)\n', (4987, 4998), True, 'import streamlit as st\n'), ((5641, 5690), 'streamlit.selectbox', 'st.selectbox', (['"""Initial state"""', "nu.states['state']"], {}), "('Initial state', nu.states['state'])\n", (5653, 5690), True, 'import streamlit as st\n'), ((5723, 5770), 'streamlit.selectbox', 'st.selectbox', (['"""Final state"""', "nu.states['state']"], {}), "('Final state', nu.states['state'])\n", (5735, 5770), True, 'import streamlit as st\n'), ((5877, 5903), 'streamlit.selectbox', 'st.selectbox', (['"""Tt"""', '[0, 1]'], {}), "('Tt', [0, 1])\n", (5889, 5903), True, 'import streamlit as st\n'), ((6367, 6525), 'barChartPlotly.plotly_barcharts_3d', 'plotly_barcharts_3d', (["filter_densities['orba']", "filter_densities['orbb']", "filter_densities['amp']"], {'x_title': '"""orbit a"""', 'y_title': '"""orbit b"""', 'z_title': '"""amp"""'}), "(filter_densities['orba'], filter_densities['orbb'],\n filter_densities['amp'], x_title='orbit a', y_title='orbit b', z_title=\n 'amp')\n", (6386, 6525), False, 'from barChartPlotly import plotly_barcharts_3d\n'), ((6623, 6669), 'streamlit.plotly_chart', 'st.plotly_chart', (['fig'], {'use_container_width': '(True)'}), '(fig, use_container_width=True)\n', (6638, 6669), True, 'import streamlit as st\n'), ((6688, 6745), 'streamlit.text', 'st.text', (['"""All elements are zero, so the plot is skipped."""'], {}), "('All elements are zero, so the plot is skipped.')\n", (6695, 6745), True, 'import streamlit as st\n'), ((6807, 6834), 'streamlit.text', 'st.text', (['"""Density matrices"""'], {}), "('Density matrices')\n", (6814, 6834), True, 'import streamlit as st\n'), ((6843, 6865), 'streamlit.write', 'st.write', (['nu.densities'], {}), '(nu.densities)\n', (6851, 6865), True, 'import streamlit as st\n'), ((3734, 3756), 'numpy.arange', 'np.arange', (['(50)', '(510)', '(10)'], {}), '(50, 510, 10)\n', (3743, 3756), True, 'import numpy as np\n'), ((5818, 5847), 'numpy.unique', 'np.unique', (["nu.densities['Jt']"], {}), "(nu.densities['Jt'])\n", (5827, 5847), True, 'import numpy as np\n')] |
import numpy as np
import matplotlib.pyplot as plt
theta = np.arange(0.01, 10., 0.04)
ytan = np.tan(theta)
ytanM = np.ma.masked_where(np.abs(ytan)>20., ytan)
plt.figure()
plt.plot(theta, ytanM)
plt.ylim(-8, 8)
plt.axhline(color="gray", zorder=-1)
plt.savefig('plotLimits3.pdf')
plt.show() | [
"numpy.abs",
"matplotlib.pyplot.savefig",
"numpy.tan",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.axhline",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.ylim",
"numpy.arange",
"matplotlib.pyplot.show"
] | [((60, 87), 'numpy.arange', 'np.arange', (['(0.01)', '(10.0)', '(0.04)'], {}), '(0.01, 10.0, 0.04)\n', (69, 87), True, 'import numpy as np\n'), ((94, 107), 'numpy.tan', 'np.tan', (['theta'], {}), '(theta)\n', (100, 107), True, 'import numpy as np\n'), ((160, 172), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (170, 172), True, 'import matplotlib.pyplot as plt\n'), ((173, 195), 'matplotlib.pyplot.plot', 'plt.plot', (['theta', 'ytanM'], {}), '(theta, ytanM)\n', (181, 195), True, 'import matplotlib.pyplot as plt\n'), ((196, 211), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(-8)', '(8)'], {}), '(-8, 8)\n', (204, 211), True, 'import matplotlib.pyplot as plt\n'), ((212, 248), 'matplotlib.pyplot.axhline', 'plt.axhline', ([], {'color': '"""gray"""', 'zorder': '(-1)'}), "(color='gray', zorder=-1)\n", (223, 248), True, 'import matplotlib.pyplot as plt\n'), ((250, 280), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""plotLimits3.pdf"""'], {}), "('plotLimits3.pdf')\n", (261, 280), True, 'import matplotlib.pyplot as plt\n'), ((282, 292), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (290, 292), True, 'import matplotlib.pyplot as plt\n'), ((135, 147), 'numpy.abs', 'np.abs', (['ytan'], {}), '(ytan)\n', (141, 147), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
import logging
import numpy as np
class phandim(object):
"""
class to hold phantom dimensions
"""
def __init__(self, bx, by, bz):
"""
Constructor. Builds object from boundary vectors
Parameters
----------
bx: array of floats
voxel boundaries in X, mm
by: array of floats
voxel boundaries in Y, mm
bz: array of floats
voxel boundaries in Z, mm
"""
if bx == None:
raise RuntimeError("phantom", "Null bx parameter in constructor")
if len(bx) < 2:
raise RuntimeError("phantom", "bx is too short in constructor")
if by == None:
raise RuntimeError("phantom", "Null by parameter in constructor")
if len(by) < 2:
raise RuntimeError("phantom", "by is too short in constructor")
if bz == None:
raise RuntimeError("phantom", "Null bz parameter in constructor")
if len(bz) < 2:
raise RuntimeError("phantom", "bz is too short in constructor")
self._bx = phandim.copy_boundary_array(bx)
self._by = phandim.copy_boundary_array(by)
self._bz = phandim.copy_boundary_array(bz)
logging.info("phandim initialized")
logging.debug(str(bx))
logging.debug(str(by))
logging.debug(str(bz))
@staticmethod
def copy_boundary_array(b):
"""
allocate NP array and copy content into it
Parameters
----------
b: array of floats
input vector of boundaries, mm
returns:
sorted NP array of boundaries
"""
bnp = np.empty(len(b), dtype=np.float32)
for k in range(0, len(b)):
bnp[k] = np.float32( b[k] )
# just in case, sort boundaries
bnp = np.sort(bnp)
return bnp
@staticmethod
def check_sorted(b):
"""
Check if array is sorted in ascending order without dups
Parameters
----------
b: array
boundaries
returns: boolean
True if sorted, False otherwise
"""
for k in range(1,len(b)):
if b[k] == b[k-1]:
return False
if b[k] < b[k-1]:
return False
return True
def bx(self):
"""
Return X boundaries
returns: array
X boundaries
"""
return self._bx
def by(self):
"""
Return Y boundaries
returns: array
Y boundaries
"""
return self._by
def bz(self):
"""
Return Z boundaries
returns: array
Z boundaries
"""
return self._bz
def nx(self):
"""
Returns number of voxels in X
returns: integer
number of X voxels
"""
return len(self._bx)-1
def ny(self):
"""
Returns number of voxels in Y
returns: integer
number of Y voxels
"""
return len(self._by)-1
def nz(self):
"""
Returns number of voxels
returns: integer
number of Z voxels
"""
return len(self._bz)-1
| [
"numpy.sort",
"logging.info",
"numpy.float32"
] | [((1354, 1389), 'logging.info', 'logging.info', (['"""phandim initialized"""'], {}), "('phandim initialized')\n", (1366, 1389), False, 'import logging\n'), ((2006, 2018), 'numpy.sort', 'np.sort', (['bnp'], {}), '(bnp)\n', (2013, 2018), True, 'import numpy as np\n'), ((1920, 1936), 'numpy.float32', 'np.float32', (['b[k]'], {}), '(b[k])\n', (1930, 1936), True, 'import numpy as np\n')] |
import sys
import numpy as np
import argparse
from mung.data import DataSet, Partition
PART_NAMES = ["train", "dev", "test"]
parser = argparse.ArgumentParser()
parser.add_argument('data_dir', action="store")
parser.add_argument('split_output_file', action="store")
parser.add_argument('train_size', action="store", type=float)
parser.add_argument('dev_size', action="store", type=float)
parser.add_argument('test_size', action="store", type=float)
parser.add_argument('--seed', action='store', dest='seed', type=int, default=1)
parser.add_argument('--maintain_partition_file', action='store', dest='maintain_partition_file', default=None)
args = parser.parse_args()
np.random.seed(args.seed)
data_dir = sys.argv[1]
split_output_file = sys.argv[2]
part_sizes = [args.train_size, args.dev_size, args.test_size]
maintain_part = None
if args.maintain_partition_file is not None:
maintain_part = Partition.load(args.maintain_partition_file)
D_all = DataSet.load(data_dir, id_key="gameid")
partition = Partition.make(D_all, part_sizes, PART_NAMES, lambda d : d.get_id(), maintain_partition=maintain_part)
partition.save(split_output_file)
| [
"mung.data.DataSet.load",
"mung.data.Partition.load",
"numpy.random.seed",
"argparse.ArgumentParser"
] | [((143, 168), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (166, 168), False, 'import argparse\n'), ((686, 711), 'numpy.random.seed', 'np.random.seed', (['args.seed'], {}), '(args.seed)\n', (700, 711), True, 'import numpy as np\n'), ((983, 1022), 'mung.data.DataSet.load', 'DataSet.load', (['data_dir'], {'id_key': '"""gameid"""'}), "(data_dir, id_key='gameid')\n", (995, 1022), False, 'from mung.data import DataSet, Partition\n'), ((927, 971), 'mung.data.Partition.load', 'Partition.load', (['args.maintain_partition_file'], {}), '(args.maintain_partition_file)\n', (941, 971), False, 'from mung.data import DataSet, Partition\n')] |
import tensorflow as tf
import numpy as np
ds = tf.contrib.distributions
def decode(z, observable_space_dims):
with tf.variable_scope('Decoder', [z]):
logits = tf.layers.dense(z, 200, activation=tf.nn.tanh)
logits = tf.layers.dense(logits, np.prod(observable_space_dims))
p_x_given_z = ds.Bernoulli(logits=logits)
return p_x_given_z
def encoder(x, observable_space_dim, latent_dim):
with tf.variable_scope('Encoder', [x]):
x = tf.reshape(x, [-1, np.prod(observable_space_dim)])
h = tf.layers.dense(x, 10, activation=tf.nn.tanh)
mu = tf.layers.dense(h, latent_dim)
sigma_sq = tf.layers.dense(h, latent_dim)
q_z_given_x = ds.MultivariateNormalDiag(mu, sigma_sq)
return q_z_given_x
| [
"tensorflow.layers.dense",
"tensorflow.variable_scope",
"numpy.prod"
] | [((123, 156), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""Decoder"""', '[z]'], {}), "('Decoder', [z])\n", (140, 156), True, 'import tensorflow as tf\n'), ((175, 221), 'tensorflow.layers.dense', 'tf.layers.dense', (['z', '(200)'], {'activation': 'tf.nn.tanh'}), '(z, 200, activation=tf.nn.tanh)\n', (190, 221), True, 'import tensorflow as tf\n'), ((427, 460), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""Encoder"""', '[x]'], {}), "('Encoder', [x])\n", (444, 460), True, 'import tensorflow as tf\n'), ((537, 582), 'tensorflow.layers.dense', 'tf.layers.dense', (['x', '(10)'], {'activation': 'tf.nn.tanh'}), '(x, 10, activation=tf.nn.tanh)\n', (552, 582), True, 'import tensorflow as tf\n'), ((596, 626), 'tensorflow.layers.dense', 'tf.layers.dense', (['h', 'latent_dim'], {}), '(h, latent_dim)\n', (611, 626), True, 'import tensorflow as tf\n'), ((646, 676), 'tensorflow.layers.dense', 'tf.layers.dense', (['h', 'latent_dim'], {}), '(h, latent_dim)\n', (661, 676), True, 'import tensorflow as tf\n'), ((263, 293), 'numpy.prod', 'np.prod', (['observable_space_dims'], {}), '(observable_space_dims)\n', (270, 293), True, 'import numpy as np\n'), ((493, 522), 'numpy.prod', 'np.prod', (['observable_space_dim'], {}), '(observable_space_dim)\n', (500, 522), True, 'import numpy as np\n')] |
import gym
from gym import spaces
import cv2
import pygame
import copy
import numpy as np
from overcooked_ai_py.mdp.overcooked_env import OvercookedEnv as OriginalEnv
from overcooked_ai_py.mdp.overcooked_mdp import OvercookedGridworld
from overcooked_ai_py.visualization.state_visualizer import StateVisualizer
from overcooked_ai_py.mdp.actions import Action
def _convert_action(joint_action) -> list:
action_set = []
for _action in joint_action:
action_set.append(Action.INDEX_TO_ACTION[int(_action)])
return action_set
class OverCookedEnv():
def __init__(self,
scenario="tutorial_0",
episode_length=200
):
super(OverCookedEnv, self).__init__()
self.scenario = scenario
self.episode_length = episode_length
base_mdp = OvercookedGridworld.from_layout_name(scenario)
self.overcooked = OriginalEnv.from_mdp(base_mdp, horizon=episode_length)
self.visualizer = StateVisualizer()
self._available_actions = Action.ALL_ACTIONS
def reset(self):
self.overcooked.reset()
return self._get_observation()
def render(self, mode='rgb_array'):
image = self.visualizer.render_state(state=self.overcooked.state, grid=self.overcooked.mdp.terrain_mtx,
hud_data=StateVisualizer.default_hud_data(self.overcooked.state))
buffer = pygame.surfarray.array3d(image)
image = copy.deepcopy(buffer)
image = np.flip(np.rot90(image, 3), 1)
image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
image = cv2.resize(image, (528, 464))
return image
def step(self, action):
action = _convert_action(action)
next_state, reward, done, info = self.overcooked.step(action)
return self._get_observation(), reward, done, info
def _get_observation(self):
return self.get_feature_state().reshape(len(self.agents), -1)
def get_onehot_state(self):
return np.array(self.overcooked.lossless_state_encoding_mdp(self.overcooked.state))
def get_feature_state(self):
return np.array(self.overcooked.featurize_state_mdp(self.overcooked.state))
@property
def agents(self) -> [str]:
num_agents = len(self.overcooked.lossless_state_encoding_mdp(self.overcooked.state))
return ['ally' for _ in range(num_agents)]
@property
def observation_space(self):
state = self.get_feature_state()[0]
state = np.array(state)
# return spaces.Discrete(4056)
return spaces.Discrete(state.shape[0])
@property
def action_space(self):
return spaces.Discrete(Action.NUM_ACTIONS)
| [
"pygame.surfarray.array3d",
"cv2.resize",
"gym.spaces.Discrete",
"numpy.array",
"overcooked_ai_py.mdp.overcooked_env.OvercookedEnv.from_mdp",
"cv2.cvtColor",
"copy.deepcopy",
"numpy.rot90",
"overcooked_ai_py.visualization.state_visualizer.StateVisualizer.default_hud_data",
"overcooked_ai_py.visual... | [((844, 890), 'overcooked_ai_py.mdp.overcooked_mdp.OvercookedGridworld.from_layout_name', 'OvercookedGridworld.from_layout_name', (['scenario'], {}), '(scenario)\n', (880, 890), False, 'from overcooked_ai_py.mdp.overcooked_mdp import OvercookedGridworld\n'), ((917, 971), 'overcooked_ai_py.mdp.overcooked_env.OvercookedEnv.from_mdp', 'OriginalEnv.from_mdp', (['base_mdp'], {'horizon': 'episode_length'}), '(base_mdp, horizon=episode_length)\n', (937, 971), True, 'from overcooked_ai_py.mdp.overcooked_env import OvercookedEnv as OriginalEnv\n'), ((998, 1015), 'overcooked_ai_py.visualization.state_visualizer.StateVisualizer', 'StateVisualizer', ([], {}), '()\n', (1013, 1015), False, 'from overcooked_ai_py.visualization.state_visualizer import StateVisualizer\n'), ((1445, 1476), 'pygame.surfarray.array3d', 'pygame.surfarray.array3d', (['image'], {}), '(image)\n', (1469, 1476), False, 'import pygame\n'), ((1493, 1514), 'copy.deepcopy', 'copy.deepcopy', (['buffer'], {}), '(buffer)\n', (1506, 1514), False, 'import copy\n'), ((1579, 1617), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_RGB2BGR'], {}), '(image, cv2.COLOR_RGB2BGR)\n', (1591, 1617), False, 'import cv2\n'), ((1634, 1663), 'cv2.resize', 'cv2.resize', (['image', '(528, 464)'], {}), '(image, (528, 464))\n', (1644, 1663), False, 'import cv2\n'), ((2531, 2546), 'numpy.array', 'np.array', (['state'], {}), '(state)\n', (2539, 2546), True, 'import numpy as np\n'), ((2601, 2632), 'gym.spaces.Discrete', 'spaces.Discrete', (['state.shape[0]'], {}), '(state.shape[0])\n', (2616, 2632), False, 'from gym import spaces\n'), ((2691, 2726), 'gym.spaces.Discrete', 'spaces.Discrete', (['Action.NUM_ACTIONS'], {}), '(Action.NUM_ACTIONS)\n', (2706, 2726), False, 'from gym import spaces\n'), ((1539, 1557), 'numpy.rot90', 'np.rot90', (['image', '(3)'], {}), '(image, 3)\n', (1547, 1557), True, 'import numpy as np\n'), ((1370, 1425), 'overcooked_ai_py.visualization.state_visualizer.StateVisualizer.default_hud_data', 'StateVisualizer.default_hud_data', (['self.overcooked.state'], {}), '(self.overcooked.state)\n', (1402, 1425), False, 'from overcooked_ai_py.visualization.state_visualizer import StateVisualizer\n')] |
print('Gathering psychic powers...')
import re
import numpy as np
from gensim.models.keyedvectors import KeyedVectors
word_vectors = KeyedVectors.load_word2vec_format('GoogleNews-vectors-negative300.bin.gz', binary=True, limit=200000)
# word_vectors.save('wvsubset')
# word_vectors = KeyedVectors.load("wvsubset", mmap='r')
from nltk.tokenize import RegexpTokenizer
tokenizer = RegexpTokenizer(r"\w+")
from nltk import pos_tag
from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
read_WVM_from_file = False
def read_words():
words = []
fid = open('emotional_words2.txt', 'r')
while True:
line = fid.readline()
if not line:
break
if len(line) > 0:
word = tokenizer.tokenize(line)
words.append(word[0])
fid.close()
return words
def get_WVM():
words = read_words()
words = [lemmatizer.lemmatize(word) for word in words]
# Select adjectives (?)
# words = [word0 for word0 in words if pos_tag([word0])[0][1] in ['JJ', 'JJR', 'JJS', 'NN', 'RB', 'RBR', 'RBS']]
# Select words known by word_vectors
emowords = [word0 for word0 in words if word0 in word_vectors.vocab]
emowords = set(emowords)
emowords = [word0 for word0 in emowords]
WVM = np.array([word_vectors[word0] for word0 in emowords])
return emowords, WVM
if read_WVM_from_file:
emowords = np.load('emowords.npy')
WVM = np.load('WVM.npy')
else:
emowords, WVM = get_WVM()
np.save('emowords', emowords)
np.save('WVM', WVM)
def emodet(text_all):
sentences = re.split(r'[,;.-]', text_all)
sims_all = []
for text in sentences:
if len(text) == 0:
continue
tokens = tokenizer.tokenize(text)
tokens = [lemmatizer.lemmatize(token) for token in tokens]
tokens = [token0 for token0 in tokens if token0 in word_vectors.vocab]
# Test for negation-tokens (for adjectives)
neg_v = [np.dot(word_vectors['not'] - word_vectors['very'], word_vectors[token]) for token in tokens]
neg_v = np.array(neg_v)
# For nouns
#neg_v2 = [np.dot(word_vectors['lose'] - word_vectors['gain'], word_vectors[token]) for token in tokens]
#neg_v = neg_v + np.array(neg_v2)
nonnegation = 1 - 2 * np.mod(len(neg_v[neg_v > 1]), 2)
# Get nouns and adjectives after preprocessing
pt = pos_tag(tokens);
tokens2 = [x[0] for x in pt if x[1] in ['JJ', 'NN', 'RB', 'VB']]
if len(tokens2) > 0:
tokens = tokens2
# Find strongest match to an emotion
token_sims = []
for token0 in tokens:
sims0 = [nonnegation * np.dot(word_vectors[token0], WVMv) for WVMv in WVM]
token_sims.append(sims0)
sims_all.append(token_sims)
# Get emotional meaning per sentences and average the vector
nEmos_per_token = 3
nEmos_total = 3
emo_indices = []
emo_sims = []
for sentence_level in sims_all:
for token_level in sentence_level:
token_level = np.array(token_level)
indices = np.argsort(token_level)
emo_indices.append(indices[-nEmos_per_token:])
token_level_s = token_level[indices]
emo_sims.append(token_level_s[-nEmos_per_token:])
# mswv = word_vectors.most_similar(positive=[sims])
emo_indices = np.array(emo_indices).flatten()
emo_sims = np.array(emo_sims).flatten()
# return sims_all, emo_indices, emo_sims
indices = np.argsort(emo_sims)
indices = emo_indices[indices]
output = 'I sense you are feeling... '
iEmo = 1
nEmo = 0
used_indices = []
while nEmo < nEmos_total:
this_index = indices[-iEmo]
if not this_index in used_indices:
output = output + emowords[this_index] + "... "
used_indices.append(this_index)
nEmo = nEmo + 1
iEmo = iEmo + 1
print(output)
return output
| [
"re.split",
"nltk.pos_tag",
"gensim.models.keyedvectors.KeyedVectors.load_word2vec_format",
"nltk.stem.WordNetLemmatizer",
"numpy.argsort",
"numpy.array",
"numpy.dot",
"nltk.tokenize.RegexpTokenizer",
"numpy.load",
"numpy.save"
] | [((139, 244), 'gensim.models.keyedvectors.KeyedVectors.load_word2vec_format', 'KeyedVectors.load_word2vec_format', (['"""GoogleNews-vectors-negative300.bin.gz"""'], {'binary': '(True)', 'limit': '(200000)'}), "('GoogleNews-vectors-negative300.bin.gz',\n binary=True, limit=200000)\n", (172, 244), False, 'from gensim.models.keyedvectors import KeyedVectors\n'), ((389, 412), 'nltk.tokenize.RegexpTokenizer', 'RegexpTokenizer', (['"""\\\\w+"""'], {}), "('\\\\w+')\n", (404, 412), False, 'from nltk.tokenize import RegexpTokenizer\n'), ((494, 513), 'nltk.stem.WordNetLemmatizer', 'WordNetLemmatizer', ([], {}), '()\n', (511, 513), False, 'from nltk.stem import WordNetLemmatizer\n'), ((1313, 1366), 'numpy.array', 'np.array', (['[word_vectors[word0] for word0 in emowords]'], {}), '([word_vectors[word0] for word0 in emowords])\n', (1321, 1366), True, 'import numpy as np\n'), ((1435, 1458), 'numpy.load', 'np.load', (['"""emowords.npy"""'], {}), "('emowords.npy')\n", (1442, 1458), True, 'import numpy as np\n'), ((1470, 1488), 'numpy.load', 'np.load', (['"""WVM.npy"""'], {}), "('WVM.npy')\n", (1477, 1488), True, 'import numpy as np\n'), ((1532, 1561), 'numpy.save', 'np.save', (['"""emowords"""', 'emowords'], {}), "('emowords', emowords)\n", (1539, 1561), True, 'import numpy as np\n'), ((1567, 1586), 'numpy.save', 'np.save', (['"""WVM"""', 'WVM'], {}), "('WVM', WVM)\n", (1574, 1586), True, 'import numpy as np\n'), ((1629, 1657), 're.split', 're.split', (['"""[,;.-]"""', 'text_all'], {}), "('[,;.-]', text_all)\n", (1637, 1657), False, 'import re\n'), ((3590, 3610), 'numpy.argsort', 'np.argsort', (['emo_sims'], {}), '(emo_sims)\n', (3600, 3610), True, 'import numpy as np\n'), ((2129, 2144), 'numpy.array', 'np.array', (['neg_v'], {}), '(neg_v)\n', (2137, 2144), True, 'import numpy as np\n'), ((2457, 2472), 'nltk.pos_tag', 'pos_tag', (['tokens'], {}), '(tokens)\n', (2464, 2472), False, 'from nltk import pos_tag\n'), ((2019, 2090), 'numpy.dot', 'np.dot', (["(word_vectors['not'] - word_vectors['very'])", 'word_vectors[token]'], {}), "(word_vectors['not'] - word_vectors['very'], word_vectors[token])\n", (2025, 2090), True, 'import numpy as np\n'), ((3134, 3155), 'numpy.array', 'np.array', (['token_level'], {}), '(token_level)\n', (3142, 3155), True, 'import numpy as np\n'), ((3179, 3202), 'numpy.argsort', 'np.argsort', (['token_level'], {}), '(token_level)\n', (3189, 3202), True, 'import numpy as np\n'), ((3452, 3473), 'numpy.array', 'np.array', (['emo_indices'], {}), '(emo_indices)\n', (3460, 3473), True, 'import numpy as np\n'), ((3500, 3518), 'numpy.array', 'np.array', (['emo_sims'], {}), '(emo_sims)\n', (3508, 3518), True, 'import numpy as np\n'), ((2746, 2780), 'numpy.dot', 'np.dot', (['word_vectors[token0]', 'WVMv'], {}), '(word_vectors[token0], WVMv)\n', (2752, 2780), True, 'import numpy as np\n')] |
from math import sin, pi
import random
import numpy as np
from scipy.stats import norm
def black_box_projectile(theta, v0=10, g=9.81):
assert theta >= 0
assert theta <= 90
return (v0 ** 2) * sin(2 * pi * theta / 180) / g
def random_shooting(n=1, min_a=0, max_a=90):
assert min_a <= max_a
return [random.uniform(min_a, max_a) for i in range(n)]
def pick_elites(actions, M_elites):
actions = np.array(actions)
assert M_elites <= len(actions)
assert M_elites > 0
results = np.array([black_box_projectile(a)
for a in actions])
sorted_ix = np.argsort(results)[-M_elites:][::-1]
return actions[sorted_ix], results[sorted_ix]
def try_random_shooting(trials=10000, n=20):
print("Trying random shooting.")
best_results = []
best_actions = []
for i in range(trials):
actions_to_try = random_shooting(n)
best_action, best_result = pick_elites(actions_to_try, 1)
best_results.append(best_result[0])
best_actions.append(best_action[0])
print(f"Out of {trials} trials:")
print(f"- Average score is {round(np.mean(best_results), 2)}")
print(f"- Average action is {round(np.mean(best_actions), 2)}")
print(f"- Action SD is {round(np.std(best_actions), 2)}")
def try_cem_normal(trials=10000, N=5, M_elites=2, iterations=3):
print("Trying CEM.")
best_results = []
best_actions = []
for i in range(trials):
print(f"================ trial {i}")
print("--iteration: 1")
actions_to_try = random_shooting(N)
elite_acts, _ = pick_elites(actions_to_try, M_elites)
print(f"actions_to_try: {np.round(actions_to_try, 2)}")
print(f"elites: {np.round(elite_acts, 2)}")
for r in range(iterations - 1):
print(f"--iteration: {r + 2}")
mu, std = norm.fit(elite_acts)
print(f"fitted normal mu: {np.round(mu, 2)}, std: {np.round(std, 2)}")
actions_to_try = np.clip(norm.rvs(mu, std, N), 0, 90)
elite_acts, elite_results = pick_elites(actions_to_try,
M_elites)
print(f"actions_to_try: {np.round(actions_to_try, 2)}")
print(f"elites: {np.round(elite_acts, 2)}")
mu, std = norm.fit(elite_acts)
print(f"final action: {np.round(mu, 2)}")
best_results.append(black_box_projectile(mu))
best_actions.append(np.clip(mu, 0, 90))
print(f"Out of {trials} trials:")
print(f"- Average score is {round(np.mean(best_results), 2)}")
print(f"- Average action is {round(np.mean(best_actions), 2)}")
print(f"- Action SD is {round(np.std(best_actions), 2)}") | [
"numpy.clip",
"numpy.mean",
"random.uniform",
"scipy.stats.norm.rvs",
"scipy.stats.norm.fit",
"numpy.array",
"numpy.argsort",
"numpy.std",
"math.sin",
"numpy.round"
] | [((419, 436), 'numpy.array', 'np.array', (['actions'], {}), '(actions)\n', (427, 436), True, 'import numpy as np\n'), ((319, 347), 'random.uniform', 'random.uniform', (['min_a', 'max_a'], {}), '(min_a, max_a)\n', (333, 347), False, 'import random\n'), ((2290, 2310), 'scipy.stats.norm.fit', 'norm.fit', (['elite_acts'], {}), '(elite_acts)\n', (2298, 2310), False, 'from scipy.stats import norm\n'), ((204, 229), 'math.sin', 'sin', (['(2 * pi * theta / 180)'], {}), '(2 * pi * theta / 180)\n', (207, 229), False, 'from math import sin, pi\n'), ((604, 623), 'numpy.argsort', 'np.argsort', (['results'], {}), '(results)\n', (614, 623), True, 'import numpy as np\n'), ((1848, 1868), 'scipy.stats.norm.fit', 'norm.fit', (['elite_acts'], {}), '(elite_acts)\n', (1856, 1868), False, 'from scipy.stats import norm\n'), ((2443, 2461), 'numpy.clip', 'np.clip', (['mu', '(0)', '(90)'], {}), '(mu, 0, 90)\n', (2450, 2461), True, 'import numpy as np\n'), ((1989, 2009), 'scipy.stats.norm.rvs', 'norm.rvs', (['mu', 'std', 'N'], {}), '(mu, std, N)\n', (1997, 2009), False, 'from scipy.stats import norm\n'), ((1121, 1142), 'numpy.mean', 'np.mean', (['best_results'], {}), '(best_results)\n', (1128, 1142), True, 'import numpy as np\n'), ((1189, 1210), 'numpy.mean', 'np.mean', (['best_actions'], {}), '(best_actions)\n', (1196, 1210), True, 'import numpy as np\n'), ((1252, 1272), 'numpy.std', 'np.std', (['best_actions'], {}), '(best_actions)\n', (1258, 1272), True, 'import numpy as np\n'), ((1660, 1687), 'numpy.round', 'np.round', (['actions_to_try', '(2)'], {}), '(actions_to_try, 2)\n', (1668, 1687), True, 'import numpy as np\n'), ((1716, 1739), 'numpy.round', 'np.round', (['elite_acts', '(2)'], {}), '(elite_acts, 2)\n', (1724, 1739), True, 'import numpy as np\n'), ((2342, 2357), 'numpy.round', 'np.round', (['mu', '(2)'], {}), '(mu, 2)\n', (2350, 2357), True, 'import numpy as np\n'), ((2539, 2560), 'numpy.mean', 'np.mean', (['best_results'], {}), '(best_results)\n', (2546, 2560), True, 'import numpy as np\n'), ((2607, 2628), 'numpy.mean', 'np.mean', (['best_actions'], {}), '(best_actions)\n', (2614, 2628), True, 'import numpy as np\n'), ((2670, 2690), 'numpy.std', 'np.std', (['best_actions'], {}), '(best_actions)\n', (2676, 2690), True, 'import numpy as np\n'), ((1908, 1923), 'numpy.round', 'np.round', (['mu', '(2)'], {}), '(mu, 2)\n', (1916, 1923), True, 'import numpy as np\n'), ((1932, 1948), 'numpy.round', 'np.round', (['std', '(2)'], {}), '(std, 2)\n', (1940, 1948), True, 'import numpy as np\n'), ((2185, 2212), 'numpy.round', 'np.round', (['actions_to_try', '(2)'], {}), '(actions_to_try, 2)\n', (2193, 2212), True, 'import numpy as np\n'), ((2245, 2268), 'numpy.round', 'np.round', (['elite_acts', '(2)'], {}), '(elite_acts, 2)\n', (2253, 2268), True, 'import numpy as np\n')] |
#!/usr/bin/env python
# Needed to set seed for random generators for making reproducible experiments
from numpy.random import seed
seed(1)
from tensorflow import set_random_seed
set_random_seed(1)
import numpy as np
import tifffile as tiff
import os
import random
import shutil
from PIL import Image
from ..utils import patch_image
def make_numpy_dataset(params):
"""
Process a numpy dataset from the raw data, and do training/val data split
"""
if params.satellite == 'Sentinel-2':
__make_sentinel2_dataset__(params)
print('Processing validation data set')
__make_sentinel2_val_dataset__(params)
elif params.satellite == 'Landsat8':
if 'Biome' in params.train_dataset:
__make_landsat8_biome_dataset__(params)
print('Processing validation data set')
__make_landsat8_val_dataset__(params)
elif 'SPARCS' in params.train_dataset:
__make_landsat8_sparcs_dataset__(params)
print('Processing validation data set')
__make_landsat8_val_dataset__(params)
def __make_sentinel2_dataset__(params):
"""
Loads the training data into numpy arrays
"""
# The training data always contain all 13 bands and all 12 classes from the sen2cor classification
n_cls_sen2cor = 12
n_cls_fmask = 4
n_bands = 13
imgsize = params.tile_size
patch_size = params.patch_size
data_path = params.project_path + 'data/processed/'
# Initialize x
x = np.zeros((imgsize, imgsize, n_bands), dtype=np.uint16)
# Pixelwise labels for 1 image of size s, with n classes
y_sen2cor = np.zeros((imgsize, imgsize, 1), dtype=np.uint8) # Not in one-hot (classes are integers from 0-11)
y_fmask = np.zeros((imgsize, imgsize, 1), dtype=np.uint8) # Not in one-hot (classes are integers from ?-?)
# Find all files in the raw dataset and filter for .tif files
files = sorted(os.listdir("data/raw"))
files = [f for f in files if '.tif' in f]
# Iterate through the files and create the training data
tile_old = []
date_old = []
for f in files:
# Check if you "hit" a new tile or date
if f[4:10] != tile_old or f[11:19] != date_old:
print('Processing tile: ' + f[0:-13])
# Load bands for the specific tile and date
x[:, :, 0] = tiff.imread('data/raw/' + f[0:-12] + 'B01_60m.tiff')
x[:, :, 1] = tiff.imread('data/raw/' + f[0:-12] + 'B02_10m.tiff')
x[:, :, 2] = tiff.imread('data/raw/' + f[0:-12] + 'B03_10m.tiff')
x[:, :, 3] = tiff.imread('data/raw/' + f[0:-12] + 'B04_10m.tiff')
x[:, :, 4] = tiff.imread('data/raw/' + f[0:-12] + 'B05_20m.tiff')
x[:, :, 5] = tiff.imread('data/raw/' + f[0:-12] + 'B06_20m.tiff')
x[:, :, 6] = tiff.imread('data/raw/' + f[0:-12] + 'B07_20m.tiff')
x[:, :, 7] = tiff.imread('data/raw/' + f[0:-12] + 'B08_10m.tiff')
x[:, :, 8] = tiff.imread('data/raw/' + f[0:-12] + 'B09_60m.tiff')
x[:, :, 9] = tiff.imread('data/raw/' + f[0:-12] + 'B10_60m.tiff')
x[:, :, 10] = tiff.imread('data/raw/' + f[0:-12] + 'B11_20m.tiff')
x[:, :, 11] = tiff.imread('data/raw/' + f[0:-12] + 'B12_20m.tiff')
x[:, :, 12] = tiff.imread('data/raw/' + f[0:-12] + 'B8A_20m.tiff')
# For sen2cor classification mask
y_sen2cor[:, :, 0] = tiff.imread('data/raw/' + f[0:-12] + 'SCL_20m.tiff') # The 20 m is the native resolution
# For fmask classification mask
im = Image.open('data/raw/' + f[0:-12] + 'Fma_20m.tiff') # The 20 m is the native resolution
y_fmask[:, :, 0] = np.array(im)
# Patch the image and the mask
x_patched, _, _ = patch_image(x, patch_size, overlap=0)
y_sen2cor_patched, _, _ = patch_image(y_sen2cor, patch_size, overlap=0)
y_fmask_patched, _, _ = patch_image(y_fmask, patch_size, overlap=0)
# Save all the patches individually
for patch in range(np.size(x_patched, axis=0)):
if np.mean(x_patched[patch, :, :, :]) != 0: # Ignore blank patches
np.save(data_path + 'train/img/' + f[0:-13] + '_x_patch-%d'
% patch, x_patched[patch, :, :, :])
np.save(data_path + 'train/mask/' + f[0:-13] + '_y_sen2cor_%d-cls_patch-%d'
% (n_cls_sen2cor, patch), y_sen2cor_patched[patch, :, :, :])
np.save(data_path + 'train/mask/' + f[0:-13] + '_y_fmask_%d-cls_patch-%d'
% (n_cls_fmask, patch), y_fmask_patched[patch, :, :, :])
tile_old = f[4:10]
date_old = f[11:19]
def __make_landsat8_biome_dataset__(params):
"""
Loads the training data into numpy arrays
"""
# Start by deleting the old processed dataset and create new folders
shutil.rmtree(params.project_path + 'data/processed/train', ignore_errors=True)
shutil.rmtree(params.project_path + 'data/processed/val', ignore_errors=True)
os.makedirs(params.project_path + 'data/processed/train/img')
os.makedirs(params.project_path + 'data/processed/train/mask')
os.makedirs(params.project_path + 'data/processed/val/img')
os.makedirs(params.project_path + 'data/processed/val/mask')
# Create the new dataset
n_bands = 10 # Omitting the panchromatic band for now
patch_size = params.patch_size
data_path = params.project_path + 'data/processed/'
folders = sorted(os.listdir("./data/raw/Biome_dataset/"))
folders = [f for f in folders if '.' not in f] # Filter out .gitignore
for folder in folders:
products = sorted(os.listdir("./data/raw/Biome_dataset/" + folder + "/BC/"))
for product in products:
print('Processing product: ' + folder + ' - ' + product)
product_path = "./data/raw/Biome_dataset/" + folder + "/BC/" + product + "/"
toa_path = "./data/processed/Biome_TOA/" + folder + "/BC/" + product + "/"
fmask_path = "./data/output/Biome/"
# Initialize x and mask
temp = tiff.imread(product_path + product + "_B1.TIF")
x = np.zeros((np.shape(temp)[0], np.shape(temp)[1], n_bands), dtype=np.uint16)
y = np.zeros((np.shape(temp)[0], np.shape(temp)[1], 1), dtype=np.uint8)
# Load bands for the specific tile and date
# x[:, :, 0] = temp
# x[:, :, 1] = tiff.imread(product_path + product + "_B2.TIF")
# x[:, :, 2] = tiff.imread(product_path + product + "_B3.TIF")
# x[:, :, 3] = tiff.imread(product_path + product + "_B4.TIF")
# x[:, :, 4] = tiff.imread(product_path + product + "_B5.TIF")
# x[:, :, 5] = tiff.imread(product_path + product + "_B6.TIF")
# x[:, :, 6] = tiff.imread(product_path + product + "_B7.TIF")
# x[:, :, 7] = tiff.imread(product_path + product + "_B9.TIF") # Omitting panchromatic band (8)
x[:, :, 0:8] = tiff.imread(toa_path + product + "_toa.TIF")
# Set all NaN values to 0
x[x == 32767] = 0
# Load thermal bands
x[:, :, 8] = tiff.imread(product_path + product + "_B10.TIF")
x[:, :, 9] = tiff.imread(product_path + product + "_B11.TIF")
if params.train_dataset == 'Biome_gt':
y[:, :, 0] = tiff.imread(product_path + product + "_fixedmask.TIF")
elif params.train_dataset == 'Biome_fmask':
y[:, :, 0] = Image.open(fmask_path + product + "_fmask.png")
else:
raise ValueError('Invalid dataset. Choose Biome_gt, Biome_fmask, SPARCS_gt, or SPARCS_fmask.')
# Patch the image and the mask
x_patched, _, _ = patch_image(x, patch_size, overlap=params.overlap_train_set)
y_patched, _, _ = patch_image(y, patch_size, overlap=params.overlap_train_set)
# Save all the patches individually
for patch in range(np.size(x_patched, axis=0)):
# if np.mean(x_patched[patch, :, :, :]) != 0: # Ignore blank patches
if np.all(x_patched[patch, :, :, :]) != 0: # Ignore patches with any black pixels
category = folder[0:4].lower()
np.save(data_path + 'train/img/' + category + '_' + product + '_x_patch-%d'
% patch, x_patched[patch, :, :, :])
np.save(data_path + 'train/mask/' + category + '_' + product + '_y_patch-%d'
% patch, y_patched[patch, :, :, :])
def __make_landsat8_sparcs_dataset__(params):
"""
Loads the training data into numpy arrays
"""
# Start by deleting the old processed dataset and create new folders
shutil.rmtree(params.project_path + 'data/processed/train', ignore_errors=True)
shutil.rmtree(params.project_path + 'data/processed/val', ignore_errors=True)
os.makedirs(params.project_path + 'data/processed/train/img')
os.makedirs(params.project_path + 'data/processed/train/mask')
os.makedirs(params.project_path + 'data/processed/val/img')
os.makedirs(params.project_path + 'data/processed/val/mask')
# Define paths
raw_data_path = "./data/raw/SPARCS_dataset/"
toa_data_path = "./data/processed/SPARCS_TOA/"
fmask_path = "./data/output/SPARCS/"
processed_data_path = params.project_path + 'data/processed/'
# Load product names
products = sorted(os.listdir(raw_data_path))
products = [f for f in products if 'data.tif' in f]
products = [f for f in products if 'aux' not in f]
# Init variable for image
x = np.zeros((1000, 1000, 10), dtype=np.uint16) # Use to uint16 to save space (org. data is in uint16)
for product in products:
print('Processing product: ' + product)
# Load img and mask
x[:, :, 0:8] = tiff.imread(toa_data_path + product[:-8] + 'toa.TIF')
x[:, :, 8:10] = tiff.imread(raw_data_path + product)[:, :, 9:11]
x.astype(np.uint16)
y = np.zeros((np.shape(x)[0], np.shape(x)[1], 1), dtype=np.uint8)
if params.train_dataset == 'SPARCS_gt':
y[:, :, 0] = Image.open(raw_data_path + product[:-8] + "mask.png")
elif params.train_dataset == 'SPARCS_fmask':
y[:, :, 0] = Image.open(fmask_path + product[:-8] + "fmask.png")
else:
raise ValueError('Invalid dataset. Choose Biome_gt, Biome_fmask, SPARCS_gt, or SPARCS_fmask.')
# Mirror-pad the image and mask such that it matches the required patches
padding_size = int(params.patch_size/2)
npad = ((padding_size, padding_size), (padding_size, padding_size), (0, 0))
x_padded = np.pad(x, pad_width=npad, mode='symmetric')
y_padded = np.pad(y, pad_width=npad, mode='symmetric')
# Patch the image and the mask
x_patched, _, _ = patch_image(x_padded, params.patch_size, overlap=params.overlap_train_set)
y_patched, _, _ = patch_image(y_padded, params.patch_size, overlap=params.overlap_train_set)
# Save all the patches individually
for patch in range(np.size(x_patched, axis=0)):
if np.all(x_patched[patch, :, :, :]) != 0: # Ignore patches with any black pixels
np.save(processed_data_path + 'train/img/' + product[:-9] + '_x_patch-%d'
% patch, x_patched[patch, :, :, :])
np.save(processed_data_path + 'train/mask/' + product[:-9] + '_y_patch-%d'
% patch, y_patched[patch, :, :, :])
def __make_sentinel2_val_dataset__(params):
"""
Creates validation data set of 20% of the training data set (uses random patches)
"""
data_path = params.project_path + 'data/processed/'
# Create sorted lists of all the training data
trn_files = sorted(os.listdir(data_path + 'train/img/'))
mask_files = os.listdir(data_path + 'train/mask/') # List all mask files
mask_sen2cor_files = [f for f in mask_files if 'sen2cor' in f] # Filter out sen2cor masks
mask_sen2cor_files = sorted(mask_sen2cor_files)
mask_fmask_files = [f for f in mask_files if 'fmask' in f] # Filter out fmask files
mask_fmask_files = sorted(mask_fmask_files)
# Shuffle the list (use the same seed such that images and masks match)
seed = 1
random.seed(seed)
random.shuffle(trn_files)
random.seed(seed)
random.shuffle(mask_sen2cor_files)
random.seed(seed)
random.shuffle(mask_fmask_files)
# Remove the last 80% of the files (ie. keep 20% for validation data set)
trn_files = trn_files[0: int(len(trn_files) * 0.20)]
mask_sen2cor_files = mask_sen2cor_files[0: int(len(mask_sen2cor_files) * 0.20)]
mask_fmask_files = mask_fmask_files[0: int(len(mask_fmask_files) * 0.20)]
# Move the files
for f in trn_files:
shutil.move(data_path + 'train/img/' + f, data_path + 'val/img/' + f)
for f in mask_sen2cor_files:
shutil.move(data_path + 'train/mask/' + f, data_path + 'val/mask/' + f)
for f in mask_fmask_files:
shutil.move(data_path + 'train/mask/' + f, data_path + 'val/mask/' + f)
def __make_landsat8_val_dataset__(params):
"""
Creates validation data set of 10% of the training data set (uses random patches)
"""
data_path = params.project_path + 'data/processed/'
# Create sorted lists of all the training data
trn_files = sorted(os.listdir(data_path + 'train/img/'))
mask_files = sorted(os.listdir(data_path + 'train/mask/')) # List all mask files
# Shuffle the list (use the same seed such that images and masks match)
seed = 1
random.seed(seed)
random.shuffle(trn_files)
random.seed(seed)
random.shuffle(mask_files)
# Remove the last 90% of the files (ie. keep 10% for validation data set)
trn_files = trn_files[0: int(len(trn_files) * 0.10)]
mask_files = mask_files[0: int(len(mask_files) * 0.10)]
# Move the files
for f in trn_files:
shutil.move(data_path + 'train/img/' + f, data_path + 'val/img/' + f)
for f in mask_files:
shutil.move(data_path + 'train/mask/' + f, data_path + 'val/mask/' + f)
| [
"numpy.mean",
"numpy.all",
"os.listdir",
"tifffile.imread",
"random.shuffle",
"os.makedirs",
"shutil.move",
"PIL.Image.open",
"numpy.shape",
"numpy.size",
"random.seed",
"numpy.array",
"numpy.zeros",
"numpy.random.seed",
"shutil.rmtree",
"numpy.pad",
"tensorflow.set_random_seed",
"... | [((132, 139), 'numpy.random.seed', 'seed', (['(1)'], {}), '(1)\n', (136, 139), False, 'from numpy.random import seed\n'), ((179, 197), 'tensorflow.set_random_seed', 'set_random_seed', (['(1)'], {}), '(1)\n', (194, 197), False, 'from tensorflow import set_random_seed\n'), ((1500, 1554), 'numpy.zeros', 'np.zeros', (['(imgsize, imgsize, n_bands)'], {'dtype': 'np.uint16'}), '((imgsize, imgsize, n_bands), dtype=np.uint16)\n', (1508, 1554), True, 'import numpy as np\n'), ((1633, 1680), 'numpy.zeros', 'np.zeros', (['(imgsize, imgsize, 1)'], {'dtype': 'np.uint8'}), '((imgsize, imgsize, 1), dtype=np.uint8)\n', (1641, 1680), True, 'import numpy as np\n'), ((1746, 1793), 'numpy.zeros', 'np.zeros', (['(imgsize, imgsize, 1)'], {'dtype': 'np.uint8'}), '((imgsize, imgsize, 1), dtype=np.uint8)\n', (1754, 1793), True, 'import numpy as np\n'), ((4940, 5019), 'shutil.rmtree', 'shutil.rmtree', (["(params.project_path + 'data/processed/train')"], {'ignore_errors': '(True)'}), "(params.project_path + 'data/processed/train', ignore_errors=True)\n", (4953, 5019), False, 'import shutil\n'), ((5024, 5101), 'shutil.rmtree', 'shutil.rmtree', (["(params.project_path + 'data/processed/val')"], {'ignore_errors': '(True)'}), "(params.project_path + 'data/processed/val', ignore_errors=True)\n", (5037, 5101), False, 'import shutil\n'), ((5106, 5167), 'os.makedirs', 'os.makedirs', (["(params.project_path + 'data/processed/train/img')"], {}), "(params.project_path + 'data/processed/train/img')\n", (5117, 5167), False, 'import os\n'), ((5172, 5234), 'os.makedirs', 'os.makedirs', (["(params.project_path + 'data/processed/train/mask')"], {}), "(params.project_path + 'data/processed/train/mask')\n", (5183, 5234), False, 'import os\n'), ((5239, 5298), 'os.makedirs', 'os.makedirs', (["(params.project_path + 'data/processed/val/img')"], {}), "(params.project_path + 'data/processed/val/img')\n", (5250, 5298), False, 'import os\n'), ((5303, 5363), 'os.makedirs', 'os.makedirs', (["(params.project_path + 'data/processed/val/mask')"], {}), "(params.project_path + 'data/processed/val/mask')\n", (5314, 5363), False, 'import os\n'), ((8853, 8932), 'shutil.rmtree', 'shutil.rmtree', (["(params.project_path + 'data/processed/train')"], {'ignore_errors': '(True)'}), "(params.project_path + 'data/processed/train', ignore_errors=True)\n", (8866, 8932), False, 'import shutil\n'), ((8937, 9014), 'shutil.rmtree', 'shutil.rmtree', (["(params.project_path + 'data/processed/val')"], {'ignore_errors': '(True)'}), "(params.project_path + 'data/processed/val', ignore_errors=True)\n", (8950, 9014), False, 'import shutil\n'), ((9019, 9080), 'os.makedirs', 'os.makedirs', (["(params.project_path + 'data/processed/train/img')"], {}), "(params.project_path + 'data/processed/train/img')\n", (9030, 9080), False, 'import os\n'), ((9085, 9147), 'os.makedirs', 'os.makedirs', (["(params.project_path + 'data/processed/train/mask')"], {}), "(params.project_path + 'data/processed/train/mask')\n", (9096, 9147), False, 'import os\n'), ((9152, 9211), 'os.makedirs', 'os.makedirs', (["(params.project_path + 'data/processed/val/img')"], {}), "(params.project_path + 'data/processed/val/img')\n", (9163, 9211), False, 'import os\n'), ((9216, 9276), 'os.makedirs', 'os.makedirs', (["(params.project_path + 'data/processed/val/mask')"], {}), "(params.project_path + 'data/processed/val/mask')\n", (9227, 9276), False, 'import os\n'), ((9729, 9772), 'numpy.zeros', 'np.zeros', (['(1000, 1000, 10)'], {'dtype': 'np.uint16'}), '((1000, 1000, 10), dtype=np.uint16)\n', (9737, 9772), True, 'import numpy as np\n'), ((11982, 12019), 'os.listdir', 'os.listdir', (["(data_path + 'train/mask/')"], {}), "(data_path + 'train/mask/')\n", (11992, 12019), False, 'import os\n'), ((12421, 12438), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (12432, 12438), False, 'import random\n'), ((12443, 12468), 'random.shuffle', 'random.shuffle', (['trn_files'], {}), '(trn_files)\n', (12457, 12468), False, 'import random\n'), ((12474, 12491), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (12485, 12491), False, 'import random\n'), ((12496, 12530), 'random.shuffle', 'random.shuffle', (['mask_sen2cor_files'], {}), '(mask_sen2cor_files)\n', (12510, 12530), False, 'import random\n'), ((12536, 12553), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (12547, 12553), False, 'import random\n'), ((12558, 12590), 'random.shuffle', 'random.shuffle', (['mask_fmask_files'], {}), '(mask_fmask_files)\n', (12572, 12590), False, 'import random\n'), ((13735, 13752), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (13746, 13752), False, 'import random\n'), ((13757, 13782), 'random.shuffle', 'random.shuffle', (['trn_files'], {}), '(trn_files)\n', (13771, 13782), False, 'import random\n'), ((13788, 13805), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (13799, 13805), False, 'import random\n'), ((13810, 13836), 'random.shuffle', 'random.shuffle', (['mask_files'], {}), '(mask_files)\n', (13824, 13836), False, 'import random\n'), ((1930, 1952), 'os.listdir', 'os.listdir', (['"""data/raw"""'], {}), "('data/raw')\n", (1940, 1952), False, 'import os\n'), ((5567, 5606), 'os.listdir', 'os.listdir', (['"""./data/raw/Biome_dataset/"""'], {}), "('./data/raw/Biome_dataset/')\n", (5577, 5606), False, 'import os\n'), ((9552, 9577), 'os.listdir', 'os.listdir', (['raw_data_path'], {}), '(raw_data_path)\n', (9562, 9577), False, 'import os\n'), ((9958, 10011), 'tifffile.imread', 'tiff.imread', (["(toa_data_path + product[:-8] + 'toa.TIF')"], {}), "(toa_data_path + product[:-8] + 'toa.TIF')\n", (9969, 10011), True, 'import tifffile as tiff\n'), ((10800, 10843), 'numpy.pad', 'np.pad', (['x'], {'pad_width': 'npad', 'mode': '"""symmetric"""'}), "(x, pad_width=npad, mode='symmetric')\n", (10806, 10843), True, 'import numpy as np\n'), ((10863, 10906), 'numpy.pad', 'np.pad', (['y'], {'pad_width': 'npad', 'mode': '"""symmetric"""'}), "(y, pad_width=npad, mode='symmetric')\n", (10869, 10906), True, 'import numpy as np\n'), ((11927, 11963), 'os.listdir', 'os.listdir', (["(data_path + 'train/img/')"], {}), "(data_path + 'train/img/')\n", (11937, 11963), False, 'import os\n'), ((12943, 13012), 'shutil.move', 'shutil.move', (["(data_path + 'train/img/' + f)", "(data_path + 'val/img/' + f)"], {}), "(data_path + 'train/img/' + f, data_path + 'val/img/' + f)\n", (12954, 13012), False, 'import shutil\n'), ((13055, 13126), 'shutil.move', 'shutil.move', (["(data_path + 'train/mask/' + f)", "(data_path + 'val/mask/' + f)"], {}), "(data_path + 'train/mask/' + f, data_path + 'val/mask/' + f)\n", (13066, 13126), False, 'import shutil\n'), ((13167, 13238), 'shutil.move', 'shutil.move', (["(data_path + 'train/mask/' + f)", "(data_path + 'val/mask/' + f)"], {}), "(data_path + 'train/mask/' + f, data_path + 'val/mask/' + f)\n", (13178, 13238), False, 'import shutil\n'), ((13517, 13553), 'os.listdir', 'os.listdir', (["(data_path + 'train/img/')"], {}), "(data_path + 'train/img/')\n", (13527, 13553), False, 'import os\n'), ((13579, 13616), 'os.listdir', 'os.listdir', (["(data_path + 'train/mask/')"], {}), "(data_path + 'train/mask/')\n", (13589, 13616), False, 'import os\n'), ((14087, 14156), 'shutil.move', 'shutil.move', (["(data_path + 'train/img/' + f)", "(data_path + 'val/img/' + f)"], {}), "(data_path + 'train/img/' + f, data_path + 'val/img/' + f)\n", (14098, 14156), False, 'import shutil\n'), ((14191, 14262), 'shutil.move', 'shutil.move', (["(data_path + 'train/mask/' + f)", "(data_path + 'val/mask/' + f)"], {}), "(data_path + 'train/mask/' + f, data_path + 'val/mask/' + f)\n", (14202, 14262), False, 'import shutil\n'), ((2354, 2406), 'tifffile.imread', 'tiff.imread', (["('data/raw/' + f[0:-12] + 'B01_60m.tiff')"], {}), "('data/raw/' + f[0:-12] + 'B01_60m.tiff')\n", (2365, 2406), True, 'import tifffile as tiff\n'), ((2432, 2484), 'tifffile.imread', 'tiff.imread', (["('data/raw/' + f[0:-12] + 'B02_10m.tiff')"], {}), "('data/raw/' + f[0:-12] + 'B02_10m.tiff')\n", (2443, 2484), True, 'import tifffile as tiff\n'), ((2510, 2562), 'tifffile.imread', 'tiff.imread', (["('data/raw/' + f[0:-12] + 'B03_10m.tiff')"], {}), "('data/raw/' + f[0:-12] + 'B03_10m.tiff')\n", (2521, 2562), True, 'import tifffile as tiff\n'), ((2588, 2640), 'tifffile.imread', 'tiff.imread', (["('data/raw/' + f[0:-12] + 'B04_10m.tiff')"], {}), "('data/raw/' + f[0:-12] + 'B04_10m.tiff')\n", (2599, 2640), True, 'import tifffile as tiff\n'), ((2666, 2718), 'tifffile.imread', 'tiff.imread', (["('data/raw/' + f[0:-12] + 'B05_20m.tiff')"], {}), "('data/raw/' + f[0:-12] + 'B05_20m.tiff')\n", (2677, 2718), True, 'import tifffile as tiff\n'), ((2744, 2796), 'tifffile.imread', 'tiff.imread', (["('data/raw/' + f[0:-12] + 'B06_20m.tiff')"], {}), "('data/raw/' + f[0:-12] + 'B06_20m.tiff')\n", (2755, 2796), True, 'import tifffile as tiff\n'), ((2822, 2874), 'tifffile.imread', 'tiff.imread', (["('data/raw/' + f[0:-12] + 'B07_20m.tiff')"], {}), "('data/raw/' + f[0:-12] + 'B07_20m.tiff')\n", (2833, 2874), True, 'import tifffile as tiff\n'), ((2900, 2952), 'tifffile.imread', 'tiff.imread', (["('data/raw/' + f[0:-12] + 'B08_10m.tiff')"], {}), "('data/raw/' + f[0:-12] + 'B08_10m.tiff')\n", (2911, 2952), True, 'import tifffile as tiff\n'), ((2978, 3030), 'tifffile.imread', 'tiff.imread', (["('data/raw/' + f[0:-12] + 'B09_60m.tiff')"], {}), "('data/raw/' + f[0:-12] + 'B09_60m.tiff')\n", (2989, 3030), True, 'import tifffile as tiff\n'), ((3056, 3108), 'tifffile.imread', 'tiff.imread', (["('data/raw/' + f[0:-12] + 'B10_60m.tiff')"], {}), "('data/raw/' + f[0:-12] + 'B10_60m.tiff')\n", (3067, 3108), True, 'import tifffile as tiff\n'), ((3135, 3187), 'tifffile.imread', 'tiff.imread', (["('data/raw/' + f[0:-12] + 'B11_20m.tiff')"], {}), "('data/raw/' + f[0:-12] + 'B11_20m.tiff')\n", (3146, 3187), True, 'import tifffile as tiff\n'), ((3214, 3266), 'tifffile.imread', 'tiff.imread', (["('data/raw/' + f[0:-12] + 'B12_20m.tiff')"], {}), "('data/raw/' + f[0:-12] + 'B12_20m.tiff')\n", (3225, 3266), True, 'import tifffile as tiff\n'), ((3293, 3345), 'tifffile.imread', 'tiff.imread', (["('data/raw/' + f[0:-12] + 'B8A_20m.tiff')"], {}), "('data/raw/' + f[0:-12] + 'B8A_20m.tiff')\n", (3304, 3345), True, 'import tifffile as tiff\n'), ((3426, 3478), 'tifffile.imread', 'tiff.imread', (["('data/raw/' + f[0:-12] + 'SCL_20m.tiff')"], {}), "('data/raw/' + f[0:-12] + 'SCL_20m.tiff')\n", (3437, 3478), True, 'import tifffile as tiff\n'), ((3578, 3629), 'PIL.Image.open', 'Image.open', (["('data/raw/' + f[0:-12] + 'Fma_20m.tiff')"], {}), "('data/raw/' + f[0:-12] + 'Fma_20m.tiff')\n", (3588, 3629), False, 'from PIL import Image\n'), ((3698, 3710), 'numpy.array', 'np.array', (['im'], {}), '(im)\n', (3706, 3710), True, 'import numpy as np\n'), ((5738, 5795), 'os.listdir', 'os.listdir', (["('./data/raw/Biome_dataset/' + folder + '/BC/')"], {}), "('./data/raw/Biome_dataset/' + folder + '/BC/')\n", (5748, 5795), False, 'import os\n'), ((6181, 6228), 'tifffile.imread', 'tiff.imread', (["(product_path + product + '_B1.TIF')"], {}), "(product_path + product + '_B1.TIF')\n", (6192, 6228), True, 'import tifffile as tiff\n'), ((7079, 7123), 'tifffile.imread', 'tiff.imread', (["(toa_path + product + '_toa.TIF')"], {}), "(toa_path + product + '_toa.TIF')\n", (7090, 7123), True, 'import tifffile as tiff\n'), ((7252, 7300), 'tifffile.imread', 'tiff.imread', (["(product_path + product + '_B10.TIF')"], {}), "(product_path + product + '_B10.TIF')\n", (7263, 7300), True, 'import tifffile as tiff\n'), ((7326, 7374), 'tifffile.imread', 'tiff.imread', (["(product_path + product + '_B11.TIF')"], {}), "(product_path + product + '_B11.TIF')\n", (7337, 7374), True, 'import tifffile as tiff\n'), ((10036, 10072), 'tifffile.imread', 'tiff.imread', (['(raw_data_path + product)'], {}), '(raw_data_path + product)\n', (10047, 10072), True, 'import tifffile as tiff\n'), ((10261, 10314), 'PIL.Image.open', 'Image.open', (["(raw_data_path + product[:-8] + 'mask.png')"], {}), "(raw_data_path + product[:-8] + 'mask.png')\n", (10271, 10314), False, 'from PIL import Image\n'), ((11221, 11247), 'numpy.size', 'np.size', (['x_patched'], {'axis': '(0)'}), '(x_patched, axis=0)\n', (11228, 11247), True, 'import numpy as np\n'), ((4067, 4093), 'numpy.size', 'np.size', (['x_patched'], {'axis': '(0)'}), '(x_patched, axis=0)\n', (4074, 4093), True, 'import numpy as np\n'), ((7456, 7510), 'tifffile.imread', 'tiff.imread', (["(product_path + product + '_fixedmask.TIF')"], {}), "(product_path + product + '_fixedmask.TIF')\n", (7467, 7510), True, 'import tifffile as tiff\n'), ((8079, 8105), 'numpy.size', 'np.size', (['x_patched'], {'axis': '(0)'}), '(x_patched, axis=0)\n', (8086, 8105), True, 'import numpy as np\n'), ((10393, 10444), 'PIL.Image.open', 'Image.open', (["(fmask_path + product[:-8] + 'fmask.png')"], {}), "(fmask_path + product[:-8] + 'fmask.png')\n", (10403, 10444), False, 'from PIL import Image\n'), ((11265, 11298), 'numpy.all', 'np.all', (['x_patched[patch, :, :, :]'], {}), '(x_patched[patch, :, :, :])\n', (11271, 11298), True, 'import numpy as np\n'), ((11361, 11474), 'numpy.save', 'np.save', (["(processed_data_path + 'train/img/' + product[:-9] + '_x_patch-%d' % patch)", 'x_patched[patch, :, :, :]'], {}), "(processed_data_path + 'train/img/' + product[:-9] + '_x_patch-%d' %\n patch, x_patched[patch, :, :, :])\n", (11368, 11474), True, 'import numpy as np\n'), ((11512, 11626), 'numpy.save', 'np.save', (["(processed_data_path + 'train/mask/' + product[:-9] + '_y_patch-%d' % patch)", 'y_patched[patch, :, :, :]'], {}), "(processed_data_path + 'train/mask/' + product[:-9] + '_y_patch-%d' %\n patch, y_patched[patch, :, :, :])\n", (11519, 11626), True, 'import numpy as np\n'), ((4115, 4149), 'numpy.mean', 'np.mean', (['x_patched[patch, :, :, :]'], {}), '(x_patched[patch, :, :, :])\n', (4122, 4149), True, 'import numpy as np\n'), ((4200, 4299), 'numpy.save', 'np.save', (["(data_path + 'train/img/' + f[0:-13] + '_x_patch-%d' % patch)", 'x_patched[patch, :, :, :]'], {}), "(data_path + 'train/img/' + f[0:-13] + '_x_patch-%d' % patch,\n x_patched[patch, :, :, :])\n", (4207, 4299), True, 'import numpy as np\n'), ((4345, 4485), 'numpy.save', 'np.save', (["(data_path + 'train/mask/' + f[0:-13] + '_y_sen2cor_%d-cls_patch-%d' % (\n n_cls_sen2cor, patch))", 'y_sen2cor_patched[patch, :, :, :]'], {}), "(data_path + 'train/mask/' + f[0:-13] + '_y_sen2cor_%d-cls_patch-%d' %\n (n_cls_sen2cor, patch), y_sen2cor_patched[patch, :, :, :])\n", (4352, 4485), True, 'import numpy as np\n'), ((4531, 4665), 'numpy.save', 'np.save', (["(data_path + 'train/mask/' + f[0:-13] + '_y_fmask_%d-cls_patch-%d' % (\n n_cls_fmask, patch))", 'y_fmask_patched[patch, :, :, :]'], {}), "(data_path + 'train/mask/' + f[0:-13] + '_y_fmask_%d-cls_patch-%d' %\n (n_cls_fmask, patch), y_fmask_patched[patch, :, :, :])\n", (4538, 4665), True, 'import numpy as np\n'), ((7596, 7643), 'PIL.Image.open', 'Image.open', (["(fmask_path + product + '_fmask.png')"], {}), "(fmask_path + product + '_fmask.png')\n", (7606, 7643), False, 'from PIL import Image\n'), ((8213, 8246), 'numpy.all', 'np.all', (['x_patched[patch, :, :, :]'], {}), '(x_patched[patch, :, :, :])\n', (8219, 8246), True, 'import numpy as np\n'), ((8364, 8479), 'numpy.save', 'np.save', (["(data_path + 'train/img/' + category + '_' + product + '_x_patch-%d' % patch)", 'x_patched[patch, :, :, :]'], {}), "(data_path + 'train/img/' + category + '_' + product + '_x_patch-%d' %\n patch, x_patched[patch, :, :, :])\n", (8371, 8479), True, 'import numpy as np\n'), ((8525, 8642), 'numpy.save', 'np.save', (["(data_path + 'train/mask/' + category + '_' + product + '_y_patch-%d' % patch)", 'y_patched[patch, :, :, :]'], {}), "(data_path + 'train/mask/' + category + '_' + product + \n '_y_patch-%d' % patch, y_patched[patch, :, :, :])\n", (8532, 8642), True, 'import numpy as np\n'), ((10136, 10147), 'numpy.shape', 'np.shape', (['x'], {}), '(x)\n', (10144, 10147), True, 'import numpy as np\n'), ((10152, 10163), 'numpy.shape', 'np.shape', (['x'], {}), '(x)\n', (10160, 10163), True, 'import numpy as np\n'), ((6255, 6269), 'numpy.shape', 'np.shape', (['temp'], {}), '(temp)\n', (6263, 6269), True, 'import numpy as np\n'), ((6274, 6288), 'numpy.shape', 'np.shape', (['temp'], {}), '(temp)\n', (6282, 6288), True, 'import numpy as np\n'), ((6346, 6360), 'numpy.shape', 'np.shape', (['temp'], {}), '(temp)\n', (6354, 6360), True, 'import numpy as np\n'), ((6365, 6379), 'numpy.shape', 'np.shape', (['temp'], {}), '(temp)\n', (6373, 6379), True, 'import numpy as np\n')] |
import os
import json
import numpy as np
from SoccerNet.Downloader import getListGames
from config.classes import EVENT_DICTIONARY_V2, INVERSE_EVENT_DICTIONARY_V2
def label2vector(folder_path, num_classes=17, framerate=2):
label_path = folder_path + "/Labels-v2.json"
# Load labels
labels = json.load(open(label_path))
vector_size = 90*60*framerate
label_half1 = np.zeros((vector_size, num_classes))
label_half2 = np.zeros((vector_size, num_classes))
for annotation in labels["annotations"]:
time = annotation["gameTime"]
event = annotation["label"]
half = int(time[0])
minutes = int(time[-5:-3])
seconds = int(time[-2::])
frame = framerate * ( seconds + 60 * minutes )
if event not in EVENT_DICTIONARY_V2:
continue
label = EVENT_DICTIONARY_V2[event]
value = 1
if "visibility" in annotation.keys():
if annotation["visibility"] == "not shown":
value = -1
if half == 1:
frame = min(frame, vector_size-1)
label_half1[frame][label] = value
if half == 2:
frame = min(frame, vector_size-1)
label_half2[frame][label] = value
return label_half1, label_half2
def predictions2json(predictions_half_1, predictions_half_2, output_path, game_info, framerate=2):
os.makedirs(output_path + game_info, exist_ok=True)
output_file_path = output_path + game_info + "/Predictions-v2.json"
frames_half_1, class_half_1 = np.where(predictions_half_1 >= 0)
frames_half_2, class_half_2 = np.where(predictions_half_2 >= 0)
json_data = dict()
json_data["UrlLocal"] = game_info
json_data["predictions"] = list()
for frame_index, class_index in zip(frames_half_1, class_half_1):
confidence = predictions_half_1[frame_index, class_index]
seconds = int((frame_index//framerate)%60)
minutes = int((frame_index//framerate)//60)
prediction_data = dict()
prediction_data["gameTime"] = str(1) + " - " + str(minutes) + ":" + str(seconds)
prediction_data["label"] = INVERSE_EVENT_DICTIONARY_V2[class_index]
prediction_data["position"] = str(int((frame_index/framerate)*1000))
prediction_data["half"] = str(1)
prediction_data["confidence"] = str(confidence)
json_data["predictions"].append(prediction_data)
for frame_index, class_index in zip(frames_half_2, class_half_2):
confidence = predictions_half_2[frame_index, class_index]
seconds = int((frame_index//framerate)%60)
minutes = int((frame_index//framerate)//60)
prediction_data = dict()
prediction_data["gameTime"] = str(2) + " - " + str(minutes) + ":" + str(seconds)
prediction_data["label"] = INVERSE_EVENT_DICTIONARY_V2[class_index]
prediction_data["position"] = str(int((frame_index/framerate)*1000))
prediction_data["half"] = str(2)
prediction_data["confidence"] = str(confidence)
json_data["predictions"].append(prediction_data)
with open(output_file_path, 'w') as output_file:
json.dump(json_data, output_file, indent=4)
def predictions2vector(folder_path, predictions_path, num_classes=17, framerate=2):
predictions_path = predictions_path + "/Predictions-v2.json"
# Load features
# Load labels
predictions = json.load(open(predictions_path))
vector_size = 90*60*framerate
prediction_half1 = np.zeros((vector_size, num_classes))-1
prediction_half2 = np.zeros((vector_size, num_classes))-1
for annotation in predictions["predictions"]:
time = int(annotation["position"])
event = annotation["label"]
half = int(annotation["half"])
frame = int(framerate * ( time/1000 ))
if event not in EVENT_DICTIONARY_V2:
continue
label = EVENT_DICTIONARY_V2[event]
value = annotation["confidence"]
if half == 1:
frame = min(frame, vector_size-1)
prediction_half1[frame][label] = value
if half == 2:
frame = min(frame, vector_size-1)
prediction_half2[frame][label] = value
return prediction_half1, prediction_half2
if __name__=="__main__":
print("test input")
list_games = getListGames("test")
print(list_games[0])
label_1, label_2 = label2vector("/home/acioppa/Work/Projects/DeepSport/Context-Aware/data_latest/" + list_games[0], "ResNET_TF2_PCA512.npy" )
predictions2json(label_1-0.1, label_2-0.1, "outputs/", list_games[0])
predictions_half_1, predictions_half_2 = predictions2vector("/home/acioppa/Work/Projects/DeepSport/Context-Aware/data_latest/" + list_games[0], "outputs/" + list_games[0], "ResNET_TF2_PCA512.npy")
print(label_1.shape)
print(label_2.shape)
print(predictions_half_1.shape)
print(predictions_half_2.shape) | [
"os.makedirs",
"numpy.where",
"SoccerNet.Downloader.getListGames",
"numpy.zeros",
"json.dump"
] | [((388, 424), 'numpy.zeros', 'np.zeros', (['(vector_size, num_classes)'], {}), '((vector_size, num_classes))\n', (396, 424), True, 'import numpy as np\n'), ((443, 479), 'numpy.zeros', 'np.zeros', (['(vector_size, num_classes)'], {}), '((vector_size, num_classes))\n', (451, 479), True, 'import numpy as np\n'), ((1386, 1437), 'os.makedirs', 'os.makedirs', (['(output_path + game_info)'], {'exist_ok': '(True)'}), '(output_path + game_info, exist_ok=True)\n', (1397, 1437), False, 'import os\n'), ((1545, 1578), 'numpy.where', 'np.where', (['(predictions_half_1 >= 0)'], {}), '(predictions_half_1 >= 0)\n', (1553, 1578), True, 'import numpy as np\n'), ((1613, 1646), 'numpy.where', 'np.where', (['(predictions_half_2 >= 0)'], {}), '(predictions_half_2 >= 0)\n', (1621, 1646), True, 'import numpy as np\n'), ((4328, 4348), 'SoccerNet.Downloader.getListGames', 'getListGames', (['"""test"""'], {}), "('test')\n", (4340, 4348), False, 'from SoccerNet.Downloader import getListGames\n'), ((3155, 3198), 'json.dump', 'json.dump', (['json_data', 'output_file'], {'indent': '(4)'}), '(json_data, output_file, indent=4)\n', (3164, 3198), False, 'import json\n'), ((3501, 3537), 'numpy.zeros', 'np.zeros', (['(vector_size, num_classes)'], {}), '((vector_size, num_classes))\n', (3509, 3537), True, 'import numpy as np\n'), ((3563, 3599), 'numpy.zeros', 'np.zeros', (['(vector_size, num_classes)'], {}), '((vector_size, num_classes))\n', (3571, 3599), True, 'import numpy as np\n')] |
import csv
import numpy as np
def cargar_datos(nombre_archivo):
datos_entrenamiento = []
nombres_entrenamiento = []
with open(nombre_archivo, newline='') as csvfile:
for fila in csv.reader(csvfile):
datos_entrenamiento.append(list(map(lambda x: float(x), fila[:-1])))
nombres_entrenamiento.append(float(fila[-1]))
return np.array(datos_entrenamiento), np.array(nombres_entrenamiento) | [
"numpy.array",
"csv.reader"
] | [((200, 219), 'csv.reader', 'csv.reader', (['csvfile'], {}), '(csvfile)\n', (210, 219), False, 'import csv\n'), ((372, 401), 'numpy.array', 'np.array', (['datos_entrenamiento'], {}), '(datos_entrenamiento)\n', (380, 401), True, 'import numpy as np\n'), ((403, 434), 'numpy.array', 'np.array', (['nombres_entrenamiento'], {}), '(nombres_entrenamiento)\n', (411, 434), True, 'import numpy as np\n')] |
'''
Examples using Sense HAT animations: circle, triangle, line, and square functions.
By <NAME>, 5/15/2017
'''
from sense_hat import SenseHat
import time
import numpy as np
import time
import ect
from random import randint
import sys
sense = SenseHat()
w = [150, 150, 150]
b = [0, 0, 255]
e = [0, 0, 0]
# create empty screen
image = np.array([
e,e,e,e,e,e,e,e,
e,e,e,e,e,e,e,e,
e,e,e,e,e,e,e,e,
e,e,e,e,e,e,e,e,
e,e,e,e,e,e,e,e,
e,e,e,e,e,e,e,e,
e,e,e,e,e,e,e,e,
e,e,e,e,e,e,e,e
])
'''
Demonstrate a bouncing ball
It will draw the ball, erase it, and then draw another ball in a different position
'''
for x in range(0,7):
ect.cell(image,[0,x],[randint(0,255), randint(0,255), randint(0,255)],0.1)
ect.cell(image,[0,x],e,0.1)
for x in range(7,0, -1):
ect.cell(image,[0,x],[randint(0,255), randint(0,255), randint(0,255)],0.1)
ect.cell(image,[0,x],e,0.1)
# triangles
ect.triangle(image,[0,0],[3,3],[0,6],[0,0,255], 1)
ect.triangle(image,[6,0],[3,3],[6,6],[0,0,255], 1)
image = ect.clear(image)
# moving circles
for y in range(5):
ect.circle(image,(3,4), 2, w, .1)
ect.circle(image,(3,4), 2, e, 0)
ect.circle(image,(4,5), 3, w, .1)
ect.circle(image,(4,5), 3, e, 0)
ect.circle(image,(5,6), 3, w, .1)
ect.circle(image,(5,6), 3, e, 0)
ect.circle(image,(6,7), 3, w, .1)
ect.circle(image,(6,7), 3, e, 0)
ect.circle(image,(7,8), 3, w, .1)
ect.circle(image,(7,8), 3, e, 0)
ect.circle(image,(8,9), 3, w, .1)
ect.circle(image,(8,9), 3, e, 0)
ect.circle(image,(1,2), 2, w, .1)
ect.circle(image,(1,2), 2, e, 0)
# colorful squares
for x in range(5):
ect.square(image, [0,0], [7,0], [7,7],[0,7],[randint(0,255),randint(0,255),randint(0,255)],.01)
ect.square(image, [1,1], [6,1], [6,6],[1,6],[randint(0,255),randint(0,255),randint(0,255)],.01)
ect.square(image, [2,2], [5,2], [5,5],[2,5],[randint(0,255),randint(0,255),randint(0,255)],.01)
# clear screen with squares
ect.square(image, [0,0], [7,0], [7,7],[0,7],e,.01)
ect.square(image, [1,1], [6,1], [6,6],[1,6],e,.01)
ect.square(image, [2,2], [5,2], [5,5],[2,5],e,.01)
# more moving circles
ect.circle(image,(3,4), 3, w, 1)
ect.circle(image,(3,4), 3, e, 0)
ect.circle(image,(4,4), 3, w, 1)
ect.circle(image,(4,4), 3, e, 0)
ect.circle(image,(3,4), 3, w, 1)
ect.circle(image,(3,4), 3, e, 0)
'''
This subroutine first draw a circle with an epicenter of (4,4). It then has a radius of 3 followed by
random colors done with [randint(0,255), randint(0,255), randint(0,255)] this can generate a random number
from 0 to 255. For instance, it might generate [10,233,100]. The last value of 0.1 is the number of second
it will keep the image displayed.
'''
for x in range(0, 10):
ect.circle(image,(4,4), 3, [randint(0,255), randint(0,255), randint(0,255)], 0.1)
ect.circle(image,(4,4), 2, [randint(0,255), randint(0,255), randint(0,255)], 0.1)
ect.circle(image,(4,4), 1, [randint(0,255), randint(0,255), randint(0,255)], 0.1)
ect.circle(image,(4,4), 3, w, 1)
ect.circle(image,(4,4), 3, b, 1)
ect.circle(image,(4,4), 3, w, 1)
ect.circle(image,(4,4), 3, b, 1)
ect.circle(image,(4,4), 2, b, 1)
ect.circle(image,(4,4), 1, b, 1)
ect.circle(image,(4,4), 1, e, 1)
ect.circle(image,(4,4), 2, e, 1)
ect.circle(image,(4,4), 3, e, 1)
# stack images ontop of each other
for x in range(0, 10):
r = randint(0,255)
g = randint(0,255)
b = randint(0,255)
image1 = ect.circle(image,(4,4), 3, [r, g, b], 0.1)
image2 = ect.circle(image1,(4,4), 2, [r, g, b], 0.1)
image3 = ect.circle(image2,(4,4), 1, [r, g, b], 0.1)
image3 = ect.clear(image3)
| [
"sense_hat.SenseHat",
"ect.circle",
"ect.square",
"numpy.array",
"ect.triangle",
"ect.clear",
"ect.cell",
"random.randint"
] | [((248, 258), 'sense_hat.SenseHat', 'SenseHat', ([], {}), '()\n', (256, 258), False, 'from sense_hat import SenseHat\n'), ((342, 552), 'numpy.array', 'np.array', (['[e, e, e, e, e, e, e, e, e, e, e, e, e, e, e, e, e, e, e, e, e, e, e, e, e,\n e, e, e, e, e, e, e, e, e, e, e, e, e, e, e, e, e, e, e, e, e, e, e, e,\n e, e, e, e, e, e, e, e, e, e, e, e, e, e, e]'], {}), '([e, e, e, e, e, e, e, e, e, e, e, e, e, e, e, e, e, e, e, e, e, e,\n e, e, e, e, e, e, e, e, e, e, e, e, e, e, e, e, e, e, e, e, e, e, e, e,\n e, e, e, e, e, e, e, e, e, e, e, e, e, e, e, e, e, e])\n', (350, 552), True, 'import numpy as np\n'), ((898, 957), 'ect.triangle', 'ect.triangle', (['image', '[0, 0]', '[3, 3]', '[0, 6]', '[0, 0, 255]', '(1)'], {}), '(image, [0, 0], [3, 3], [0, 6], [0, 0, 255], 1)\n', (910, 957), False, 'import ect\n'), ((949, 1008), 'ect.triangle', 'ect.triangle', (['image', '[6, 0]', '[3, 3]', '[6, 6]', '[0, 0, 255]', '(1)'], {}), '(image, [6, 0], [3, 3], [6, 6], [0, 0, 255], 1)\n', (961, 1008), False, 'import ect\n'), ((1008, 1024), 'ect.clear', 'ect.clear', (['image'], {}), '(image)\n', (1017, 1024), False, 'import ect\n'), ((1958, 2016), 'ect.square', 'ect.square', (['image', '[0, 0]', '[7, 0]', '[7, 7]', '[0, 7]', 'e', '(0.01)'], {}), '(image, [0, 0], [7, 0], [7, 7], [0, 7], e, 0.01)\n', (1968, 2016), False, 'import ect\n'), ((2009, 2067), 'ect.square', 'ect.square', (['image', '[1, 1]', '[6, 1]', '[6, 6]', '[1, 6]', 'e', '(0.01)'], {}), '(image, [1, 1], [6, 1], [6, 6], [1, 6], e, 0.01)\n', (2019, 2067), False, 'import ect\n'), ((2060, 2118), 'ect.square', 'ect.square', (['image', '[2, 2]', '[5, 2]', '[5, 5]', '[2, 5]', 'e', '(0.01)'], {}), '(image, [2, 2], [5, 2], [5, 5], [2, 5], e, 0.01)\n', (2070, 2118), False, 'import ect\n'), ((2134, 2168), 'ect.circle', 'ect.circle', (['image', '(3, 4)', '(3)', 'w', '(1)'], {}), '(image, (3, 4), 3, w, 1)\n', (2144, 2168), False, 'import ect\n'), ((2167, 2201), 'ect.circle', 'ect.circle', (['image', '(3, 4)', '(3)', 'e', '(0)'], {}), '(image, (3, 4), 3, e, 0)\n', (2177, 2201), False, 'import ect\n'), ((2200, 2234), 'ect.circle', 'ect.circle', (['image', '(4, 4)', '(3)', 'w', '(1)'], {}), '(image, (4, 4), 3, w, 1)\n', (2210, 2234), False, 'import ect\n'), ((2233, 2267), 'ect.circle', 'ect.circle', (['image', '(4, 4)', '(3)', 'e', '(0)'], {}), '(image, (4, 4), 3, e, 0)\n', (2243, 2267), False, 'import ect\n'), ((2266, 2300), 'ect.circle', 'ect.circle', (['image', '(3, 4)', '(3)', 'w', '(1)'], {}), '(image, (3, 4), 3, w, 1)\n', (2276, 2300), False, 'import ect\n'), ((2299, 2333), 'ect.circle', 'ect.circle', (['image', '(3, 4)', '(3)', 'e', '(0)'], {}), '(image, (3, 4), 3, e, 0)\n', (2309, 2333), False, 'import ect\n'), ((2983, 3017), 'ect.circle', 'ect.circle', (['image', '(4, 4)', '(3)', 'w', '(1)'], {}), '(image, (4, 4), 3, w, 1)\n', (2993, 3017), False, 'import ect\n'), ((3016, 3050), 'ect.circle', 'ect.circle', (['image', '(4, 4)', '(3)', 'b', '(1)'], {}), '(image, (4, 4), 3, b, 1)\n', (3026, 3050), False, 'import ect\n'), ((3049, 3083), 'ect.circle', 'ect.circle', (['image', '(4, 4)', '(3)', 'w', '(1)'], {}), '(image, (4, 4), 3, w, 1)\n', (3059, 3083), False, 'import ect\n'), ((3082, 3116), 'ect.circle', 'ect.circle', (['image', '(4, 4)', '(3)', 'b', '(1)'], {}), '(image, (4, 4), 3, b, 1)\n', (3092, 3116), False, 'import ect\n'), ((3115, 3149), 'ect.circle', 'ect.circle', (['image', '(4, 4)', '(2)', 'b', '(1)'], {}), '(image, (4, 4), 2, b, 1)\n', (3125, 3149), False, 'import ect\n'), ((3148, 3182), 'ect.circle', 'ect.circle', (['image', '(4, 4)', '(1)', 'b', '(1)'], {}), '(image, (4, 4), 1, b, 1)\n', (3158, 3182), False, 'import ect\n'), ((3181, 3215), 'ect.circle', 'ect.circle', (['image', '(4, 4)', '(1)', 'e', '(1)'], {}), '(image, (4, 4), 1, e, 1)\n', (3191, 3215), False, 'import ect\n'), ((3214, 3248), 'ect.circle', 'ect.circle', (['image', '(4, 4)', '(2)', 'e', '(1)'], {}), '(image, (4, 4), 2, e, 1)\n', (3224, 3248), False, 'import ect\n'), ((3247, 3281), 'ect.circle', 'ect.circle', (['image', '(4, 4)', '(3)', 'e', '(1)'], {}), '(image, (4, 4), 3, e, 1)\n', (3257, 3281), False, 'import ect\n'), ((3596, 3613), 'ect.clear', 'ect.clear', (['image3'], {}), '(image3)\n', (3605, 3613), False, 'import ect\n'), ((720, 751), 'ect.cell', 'ect.cell', (['image', '[0, x]', 'e', '(0.1)'], {}), '(image, [0, x], e, 0.1)\n', (728, 751), False, 'import ect\n'), ((856, 887), 'ect.cell', 'ect.cell', (['image', '[0, x]', 'e', '(0.1)'], {}), '(image, [0, x], e, 0.1)\n', (864, 887), False, 'import ect\n'), ((1067, 1103), 'ect.circle', 'ect.circle', (['image', '(3, 4)', '(2)', 'w', '(0.1)'], {}), '(image, (3, 4), 2, w, 0.1)\n', (1077, 1103), False, 'import ect\n'), ((1105, 1139), 'ect.circle', 'ect.circle', (['image', '(3, 4)', '(2)', 'e', '(0)'], {}), '(image, (3, 4), 2, e, 0)\n', (1115, 1139), False, 'import ect\n'), ((1142, 1178), 'ect.circle', 'ect.circle', (['image', '(4, 5)', '(3)', 'w', '(0.1)'], {}), '(image, (4, 5), 3, w, 0.1)\n', (1152, 1178), False, 'import ect\n'), ((1180, 1214), 'ect.circle', 'ect.circle', (['image', '(4, 5)', '(3)', 'e', '(0)'], {}), '(image, (4, 5), 3, e, 0)\n', (1190, 1214), False, 'import ect\n'), ((1217, 1253), 'ect.circle', 'ect.circle', (['image', '(5, 6)', '(3)', 'w', '(0.1)'], {}), '(image, (5, 6), 3, w, 0.1)\n', (1227, 1253), False, 'import ect\n'), ((1255, 1289), 'ect.circle', 'ect.circle', (['image', '(5, 6)', '(3)', 'e', '(0)'], {}), '(image, (5, 6), 3, e, 0)\n', (1265, 1289), False, 'import ect\n'), ((1292, 1328), 'ect.circle', 'ect.circle', (['image', '(6, 7)', '(3)', 'w', '(0.1)'], {}), '(image, (6, 7), 3, w, 0.1)\n', (1302, 1328), False, 'import ect\n'), ((1330, 1364), 'ect.circle', 'ect.circle', (['image', '(6, 7)', '(3)', 'e', '(0)'], {}), '(image, (6, 7), 3, e, 0)\n', (1340, 1364), False, 'import ect\n'), ((1367, 1403), 'ect.circle', 'ect.circle', (['image', '(7, 8)', '(3)', 'w', '(0.1)'], {}), '(image, (7, 8), 3, w, 0.1)\n', (1377, 1403), False, 'import ect\n'), ((1405, 1439), 'ect.circle', 'ect.circle', (['image', '(7, 8)', '(3)', 'e', '(0)'], {}), '(image, (7, 8), 3, e, 0)\n', (1415, 1439), False, 'import ect\n'), ((1442, 1478), 'ect.circle', 'ect.circle', (['image', '(8, 9)', '(3)', 'w', '(0.1)'], {}), '(image, (8, 9), 3, w, 0.1)\n', (1452, 1478), False, 'import ect\n'), ((1480, 1514), 'ect.circle', 'ect.circle', (['image', '(8, 9)', '(3)', 'e', '(0)'], {}), '(image, (8, 9), 3, e, 0)\n', (1490, 1514), False, 'import ect\n'), ((1517, 1553), 'ect.circle', 'ect.circle', (['image', '(1, 2)', '(2)', 'w', '(0.1)'], {}), '(image, (1, 2), 2, w, 0.1)\n', (1527, 1553), False, 'import ect\n'), ((1555, 1589), 'ect.circle', 'ect.circle', (['image', '(1, 2)', '(2)', 'e', '(0)'], {}), '(image, (1, 2), 2, e, 0)\n', (1565, 1589), False, 'import ect\n'), ((3350, 3365), 'random.randint', 'randint', (['(0)', '(255)'], {}), '(0, 255)\n', (3357, 3365), False, 'from random import randint\n'), ((3373, 3388), 'random.randint', 'randint', (['(0)', '(255)'], {}), '(0, 255)\n', (3380, 3388), False, 'from random import randint\n'), ((3396, 3411), 'random.randint', 'randint', (['(0)', '(255)'], {}), '(0, 255)\n', (3403, 3411), False, 'from random import randint\n'), ((3424, 3468), 'ect.circle', 'ect.circle', (['image', '(4, 4)', '(3)', '[r, g, b]', '(0.1)'], {}), '(image, (4, 4), 3, [r, g, b], 0.1)\n', (3434, 3468), False, 'import ect\n'), ((3481, 3526), 'ect.circle', 'ect.circle', (['image1', '(4, 4)', '(2)', '[r, g, b]', '(0.1)'], {}), '(image1, (4, 4), 2, [r, g, b], 0.1)\n', (3491, 3526), False, 'import ect\n'), ((3538, 3583), 'ect.circle', 'ect.circle', (['image2', '(4, 4)', '(1)', '[r, g, b]', '(0.1)'], {}), '(image2, (4, 4), 1, [r, g, b], 0.1)\n', (3548, 3583), False, 'import ect\n'), ((663, 678), 'random.randint', 'randint', (['(0)', '(255)'], {}), '(0, 255)\n', (670, 678), False, 'from random import randint\n'), ((679, 694), 'random.randint', 'randint', (['(0)', '(255)'], {}), '(0, 255)\n', (686, 694), False, 'from random import randint\n'), ((695, 710), 'random.randint', 'randint', (['(0)', '(255)'], {}), '(0, 255)\n', (702, 710), False, 'from random import randint\n'), ((799, 814), 'random.randint', 'randint', (['(0)', '(255)'], {}), '(0, 255)\n', (806, 814), False, 'from random import randint\n'), ((815, 830), 'random.randint', 'randint', (['(0)', '(255)'], {}), '(0, 255)\n', (822, 830), False, 'from random import randint\n'), ((831, 846), 'random.randint', 'randint', (['(0)', '(255)'], {}), '(0, 255)\n', (838, 846), False, 'from random import randint\n'), ((1677, 1692), 'random.randint', 'randint', (['(0)', '(255)'], {}), '(0, 255)\n', (1684, 1692), False, 'from random import randint\n'), ((1692, 1707), 'random.randint', 'randint', (['(0)', '(255)'], {}), '(0, 255)\n', (1699, 1707), False, 'from random import randint\n'), ((1707, 1722), 'random.randint', 'randint', (['(0)', '(255)'], {}), '(0, 255)\n', (1714, 1722), False, 'from random import randint\n'), ((1777, 1792), 'random.randint', 'randint', (['(0)', '(255)'], {}), '(0, 255)\n', (1784, 1792), False, 'from random import randint\n'), ((1792, 1807), 'random.randint', 'randint', (['(0)', '(255)'], {}), '(0, 255)\n', (1799, 1807), False, 'from random import randint\n'), ((1807, 1822), 'random.randint', 'randint', (['(0)', '(255)'], {}), '(0, 255)\n', (1814, 1822), False, 'from random import randint\n'), ((1877, 1892), 'random.randint', 'randint', (['(0)', '(255)'], {}), '(0, 255)\n', (1884, 1892), False, 'from random import randint\n'), ((1892, 1907), 'random.randint', 'randint', (['(0)', '(255)'], {}), '(0, 255)\n', (1899, 1907), False, 'from random import randint\n'), ((1907, 1922), 'random.randint', 'randint', (['(0)', '(255)'], {}), '(0, 255)\n', (1914, 1922), False, 'from random import randint\n'), ((2749, 2764), 'random.randint', 'randint', (['(0)', '(255)'], {}), '(0, 255)\n', (2756, 2764), False, 'from random import randint\n'), ((2765, 2780), 'random.randint', 'randint', (['(0)', '(255)'], {}), '(0, 255)\n', (2772, 2780), False, 'from random import randint\n'), ((2781, 2796), 'random.randint', 'randint', (['(0)', '(255)'], {}), '(0, 255)\n', (2788, 2796), False, 'from random import randint\n'), ((2836, 2851), 'random.randint', 'randint', (['(0)', '(255)'], {}), '(0, 255)\n', (2843, 2851), False, 'from random import randint\n'), ((2852, 2867), 'random.randint', 'randint', (['(0)', '(255)'], {}), '(0, 255)\n', (2859, 2867), False, 'from random import randint\n'), ((2868, 2883), 'random.randint', 'randint', (['(0)', '(255)'], {}), '(0, 255)\n', (2875, 2883), False, 'from random import randint\n'), ((2922, 2937), 'random.randint', 'randint', (['(0)', '(255)'], {}), '(0, 255)\n', (2929, 2937), False, 'from random import randint\n'), ((2938, 2953), 'random.randint', 'randint', (['(0)', '(255)'], {}), '(0, 255)\n', (2945, 2953), False, 'from random import randint\n'), ((2954, 2969), 'random.randint', 'randint', (['(0)', '(255)'], {}), '(0, 255)\n', (2961, 2969), False, 'from random import randint\n')] |
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 5 17:05:49 2017
@author: thuzhang
"""
import numpy as np
import pandas as pd
File='DataBase/DataBaseNECA.csv'
OriginData=pd.read_table(File,sep=",")
for i in range(0,int(len(OriginData)/24)):
_DailyData=OriginData["SYSLoad"][24*i:24*i+24]
_DryData=OriginData["DryBulb"][24*i:24*i+24]
_DewData=OriginData["DewPnt"][24*i:24*i+24]
_MaxValue=np.max(_DailyData)
_MaxValuePoint=np.where(_DailyData==_MaxValue)[0][0]
_MeanDryData=np.mean(_DryData)
_MeanDewData=np.mean(_DewData)
print(_MaxValue,_MaxValuePoint)
print(_MeanDryData,_MeanDewData)
for j in range(0,24):
OriginData["PkLoad"][24*i+j]=_MaxValue
OriginData["PkLoadPoint"][24*i+j]=_MaxValuePoint
OriginData["MeanDry"][24*i+j]=_MeanDryData
OriginData["MeanDew"][24*i+j]=_MeanDewData
print('Row%d'%i)
OriginData.to_csv('DataBase/DataBaseNECAOutput2.csv') | [
"numpy.where",
"numpy.mean",
"pandas.read_table",
"numpy.max"
] | [((171, 199), 'pandas.read_table', 'pd.read_table', (['File'], {'sep': '""","""'}), "(File, sep=',')\n", (184, 199), True, 'import pandas as pd\n'), ((409, 427), 'numpy.max', 'np.max', (['_DailyData'], {}), '(_DailyData)\n', (415, 427), True, 'import numpy as np\n'), ((507, 524), 'numpy.mean', 'np.mean', (['_DryData'], {}), '(_DryData)\n', (514, 524), True, 'import numpy as np\n'), ((547, 564), 'numpy.mean', 'np.mean', (['_DewData'], {}), '(_DewData)\n', (554, 564), True, 'import numpy as np\n'), ((447, 480), 'numpy.where', 'np.where', (['(_DailyData == _MaxValue)'], {}), '(_DailyData == _MaxValue)\n', (455, 480), True, 'import numpy as np\n')] |
import numpy as np
from scipy import signal, ndimage
from hexrd import convolution
def fast_snip1d(y, w=4, numiter=2):
"""
"""
bkg = np.zeros_like(y)
zfull = np.log(np.log(np.sqrt(y + 1.) + 1.) + 1.)
for k, z in enumerate(zfull):
b = z
for i in range(numiter):
for p in range(w, 0, -1):
kernel = np.zeros(p*2 + 1)
kernel[0] = 0.5
kernel[-1] = 0.5
b = np.minimum(b, signal.fft (z, kernel, mode='same'))
z = b
bkg[k, :] = (np.exp(np.exp(b) - 1.) - 1.)**2 - 1.
return bkg
def snip1d(y, w=4, numiter=2, threshold=0):
"""
Return SNIP-estimated baseline-background for given spectrum y.
!!!: threshold values get marked as NaN in convolution
"""
mask = y <= threshold
zfull = np.log(np.log(np.sqrt(y + 1) + 1) + 1)
bkg = np.zeros_like(zfull)
for k, z in enumerate(zfull):
if np.all(mask[k]):
bkg[k, :] = np.nan
else:
b = z
for i in range(numiter):
for p in range(w, 0, -1):
kernel = np.zeros(p*2 + 1)
kernel[0] = kernel[-1] = 1./2.
b = np.minimum(
b,
convolution.convolve(
z, kernel, boundary='extend', mask=mask[k]
)
)
z = b
bkg[k, :] = (np.exp(np.exp(b) - 1) - 1)**2 - 1
nan_idx = np.isnan(bkg)
bkg[nan_idx] = threshold
return bkg
def snip1d_quad(y, w=4, numiter=2):
"""Return SNIP-estimated baseline-background for given spectrum y.
Adds a quadratic kernel convolution in parallel with the linear kernel."""
convolve1d = ndimage.convolve1d
kernels = []
for p in range(w, 1, -2):
N = p * 2 + 1
# linear kernel
kern1 = np.zeros(N)
kern1[0] = kern1[-1] = 1./2.
# quadratic kernel
kern2 = np.zeros(N)
kern2[0] = kern2[-1] = -1./6.
kern2[p/2] = kern2[3*p/2] = 4./6.
kernels.append([kern1, kern2])
z = b = np.log(np.log(y + 1) + 1)
for i in range(numiter):
for (kern1, kern2) in zip(kernels):
c = np.maximum(convolve1d(z, kern1, mode='nearest'),
convolve1d(z, kern2, mode='nearest'))
b = np.minimum(b, c)
z = b
return np.exp(np.exp(b) - 1) - 1
def snip2d(y, w=4, numiter=2, order=1):
"""
Return estimate of 2D-array background by "clipping" peak-like structures.
2D adaptation of the peak-clipping component of the SNIP algorithm.
Parameters
----------
y : 2-D input array
w : integer (default 4)
kernel size (maximum kernel extent actually = 2 * w * order + 1)
numiter : integer (default 2)
number of iterations
order : integer (default 1)
maximum order of filter kernel, either 1 (linear) or 2 (quadratic)
Returns
-------
out : 2-D array with SNIP-estimated background of y
References!!!
-----
[1] <NAME> et al, "SNIP, A statistics-sensitive background treatment
for the quantitative analysis of PIXE spectra in geoscience
applications," Nucl. Instr. and Meth. B 34, 396 (1988).
[2] <NAME> et al., "Background elimination methods for multidimensional
coincidence gamma-ray spectra," Nucl. Instr. and Meth. A 401, 113
(1997).
"""
maximum, minimum = np.fmax, np.fmin
# create list of kernels
kernels = []
for p in range(w, 0, -1): # decrement window starting from w
N = 2 * p * order + 1 # size of filter kernels
p1 = order * p
# linear filter kernel
kern1 = np.zeros((N, N)) # initialize a kernel with all zeros
xx, yy = np.indices(kern1.shape) # x-y indices of kernel points
ij = np.round(
np.hypot(xx - p1, yy - p1)
) == p1 # select circular shape
kern1[ij] = 1 / ij.sum() # normalize so sum of kernel elements is 1
kernels.append([kern1])
if order >= 2: # add quadratic filter kernel
p2 = p1 // 2
kern2 = np.zeros_like(kern1)
radii, norms = (p2, 2 * p2), (4/3, -1/3)
for radius, norm in zip(radii, norms):
ij = np.round(np.hypot(xx - p1, yy - p1)) == radius
kern2[ij] = norm / ij.sum()
kernels[-1].append(kern2)
# convolve kernels with input array
z = b = np.log(np.log(y + 1) + 1) # perform convolutions in logspace
for i in range(numiter):
for kk in kernels:
if order > 1:
c = maximum(ndimage.convolve(z, kk[0], mode='nearest'),
ndimage.convolve(z, kk[1], mode='nearest'))
else:
c = ndimage.convolve(z, kk[0], mode='nearest')
b = minimum(b, c)
z = b
return np.exp(np.exp(b) - 1) - 1
| [
"numpy.sqrt",
"numpy.minimum",
"scipy.signal.fft",
"numpy.log",
"hexrd.convolution.convolve",
"scipy.ndimage.convolve",
"numpy.indices",
"numpy.exp",
"numpy.zeros",
"numpy.isnan",
"numpy.hypot",
"numpy.all",
"numpy.zeros_like"
] | [((148, 164), 'numpy.zeros_like', 'np.zeros_like', (['y'], {}), '(y)\n', (161, 164), True, 'import numpy as np\n'), ((887, 907), 'numpy.zeros_like', 'np.zeros_like', (['zfull'], {}), '(zfull)\n', (900, 907), True, 'import numpy as np\n'), ((1533, 1546), 'numpy.isnan', 'np.isnan', (['bkg'], {}), '(bkg)\n', (1541, 1546), True, 'import numpy as np\n'), ((953, 968), 'numpy.all', 'np.all', (['mask[k]'], {}), '(mask[k])\n', (959, 968), True, 'import numpy as np\n'), ((1924, 1935), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (1932, 1935), True, 'import numpy as np\n'), ((2017, 2028), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (2025, 2028), True, 'import numpy as np\n'), ((3779, 3795), 'numpy.zeros', 'np.zeros', (['(N, N)'], {}), '((N, N))\n', (3787, 3795), True, 'import numpy as np\n'), ((3851, 3874), 'numpy.indices', 'np.indices', (['kern1.shape'], {}), '(kern1.shape)\n', (3861, 3874), True, 'import numpy as np\n'), ((2168, 2181), 'numpy.log', 'np.log', (['(y + 1)'], {}), '(y + 1)\n', (2174, 2181), True, 'import numpy as np\n'), ((2406, 2422), 'numpy.minimum', 'np.minimum', (['b', 'c'], {}), '(b, c)\n', (2416, 2422), True, 'import numpy as np\n'), ((4219, 4239), 'numpy.zeros_like', 'np.zeros_like', (['kern1'], {}), '(kern1)\n', (4232, 4239), True, 'import numpy as np\n'), ((4554, 4567), 'numpy.log', 'np.log', (['(y + 1)'], {}), '(y + 1)\n', (4560, 4567), True, 'import numpy as np\n'), ((363, 382), 'numpy.zeros', 'np.zeros', (['(p * 2 + 1)'], {}), '(p * 2 + 1)\n', (371, 382), True, 'import numpy as np\n'), ((2456, 2465), 'numpy.exp', 'np.exp', (['b'], {}), '(b)\n', (2462, 2465), True, 'import numpy as np\n'), ((3942, 3968), 'numpy.hypot', 'np.hypot', (['(xx - p1)', '(yy - p1)'], {}), '(xx - p1, yy - p1)\n', (3950, 3968), True, 'import numpy as np\n'), ((4873, 4915), 'scipy.ndimage.convolve', 'ndimage.convolve', (['z', 'kk[0]'], {'mode': '"""nearest"""'}), "(z, kk[0], mode='nearest')\n", (4889, 4915), False, 'from scipy import signal, ndimage\n'), ((4979, 4988), 'numpy.exp', 'np.exp', (['b'], {}), '(b)\n', (4985, 4988), True, 'import numpy as np\n'), ((191, 207), 'numpy.sqrt', 'np.sqrt', (['(y + 1.0)'], {}), '(y + 1.0)\n', (198, 207), True, 'import numpy as np\n'), ((480, 514), 'scipy.signal.fft', 'signal.fft', (['z', 'kernel'], {'mode': '"""same"""'}), "(z, kernel, mode='same')\n", (490, 514), False, 'from scipy import signal, ndimage\n'), ((852, 866), 'numpy.sqrt', 'np.sqrt', (['(y + 1)'], {}), '(y + 1)\n', (859, 866), True, 'import numpy as np\n'), ((1141, 1160), 'numpy.zeros', 'np.zeros', (['(p * 2 + 1)'], {}), '(p * 2 + 1)\n', (1149, 1160), True, 'import numpy as np\n'), ((4719, 4761), 'scipy.ndimage.convolve', 'ndimage.convolve', (['z', 'kk[0]'], {'mode': '"""nearest"""'}), "(z, kk[0], mode='nearest')\n", (4735, 4761), False, 'from scipy import signal, ndimage\n'), ((4791, 4833), 'scipy.ndimage.convolve', 'ndimage.convolve', (['z', 'kk[1]'], {'mode': '"""nearest"""'}), "(z, kk[1], mode='nearest')\n", (4807, 4833), False, 'from scipy import signal, ndimage\n'), ((1297, 1361), 'hexrd.convolution.convolve', 'convolution.convolve', (['z', 'kernel'], {'boundary': '"""extend"""', 'mask': 'mask[k]'}), "(z, kernel, boundary='extend', mask=mask[k])\n", (1317, 1361), False, 'from hexrd import convolution\n'), ((4374, 4400), 'numpy.hypot', 'np.hypot', (['(xx - p1)', '(yy - p1)'], {}), '(xx - p1, yy - p1)\n', (4382, 4400), True, 'import numpy as np\n'), ((566, 575), 'numpy.exp', 'np.exp', (['b'], {}), '(b)\n', (572, 575), True, 'import numpy as np\n'), ((1492, 1501), 'numpy.exp', 'np.exp', (['b'], {}), '(b)\n', (1498, 1501), True, 'import numpy as np\n')] |
import pandas as pd
import numpy as np
import seaborn as sb
import base64
from io import BytesIO
from flask import send_file
from flask import request
from napa import player_information as pi
import matplotlib
matplotlib.use('Agg') # required to solve multithreading issues with matplotlib within flask
import matplotlib.pyplot as plt
import matplotlib.style as style
sb.set_context("talk", font_scale = 1)
style.use('seaborn-whitegrid')
#######################################################################
# napa Database structure
#######################################################################
# TABLE SCHEMA
# team_a
# team_b
# lineup
# all_perms
# perm_score
def get_team_info():
''' If valid team IDs have been entered, then import player data from the NAPA website. If a random team has been selected,
then create a random team using the create_rand_team function. If there is an error with the team IDs, or inconsistent team lengths have been chosen, then set error = True.'''
error = False
# Retrieve ids from the input forms
A = [request.form.get('player_' +str(i) +'a') for i in range(1,6)]
B = [request.form.get('player_' +str(i) +'b') for i in range(1,6)]
rand_a = request.form.get('random_a')
rand_b = request.form.get('random_b')
try:
if (rand_a == '1') & (rand_b == '1'): # Two random teams
(team_A_df, team_B_df) = pi.create_two_rand_teams(5)
elif rand_a == '1': # Team A is random, team B is real
team_A_df = pi.create_rand_team(5)
team_B = [int(x) for x in B if x]
team_B_df = pi.team_data(team_B)
if len(team_A_df) != len(team_B_df):
error = True
elif rand_b == '1': # Team B is random, team A is real
team_B_df = pi.create_rand_team(5)
team_A = [int(x) for x in A if x]
team_A_df = pi.team_data(team_A)
if len(team_A_df) != len(team_B_df):
error = True
else: # Both teams are real
team_A = [int(x) for x in A if x]
team_B = [int(x) for x in B if x]
team_A_df = pi.team_data(team_A)
team_B_df = pi.team_data(team_B)
if len(team_A_df) != len(team_B_df):
error = True
except:
error = True
return [], [], error
return team_A_df, team_B_df, error
def load_team_a(con):
''' Select all players from team_a table and rename the columns. '''
query = ''' SELECT * FROM team_a'''
team_a = pd.read_sql_query(query,con)
return team_a.rename(columns={'name': 'a_name', 'id':'a_id', 'eight_skill': 'a_skill'})
def load_team_b(con):
''' Select all players from team_b table and rename the columns. '''
query = ''' SELECT * FROM team_b'''
team_b = pd.read_sql_query(query,con)
return team_b.rename(columns={'name': 'b_name', 'id':'b_id', 'eight_skill': 'b_skill'})
def get_prev_player(con, player_id, team):
''' Select the name and the ID of the player who was chosen on the previous webpage. '''
query = '''
SELECT name, id
FROM ''' + team + '''
WHERE id = ''' + str(player_id)
player_name = pd.read_sql_query(query,con).values[0][0]
player_id = pd.read_sql_query(query,con).values[0][1]
return player_name, player_id
def update_lineup(con, player_name, player_id, cur_pos, poss):
''' Update the lineup table with the active matchups. Clear all later matchup entries to avoid webpage caching when using the back button. '''
cursor = con.cursor()
cursor.execute('''UPDATE lineup SET name = ''' + "'" + player_name + "'" + ''', id = ''' + str(player_id) + ''' WHERE pos = ''' + str(cur_pos) + ''';''')
# poss is a list of all lineup entries to be cleared
for pos in poss:
cursor.execute('''UPDATE lineup SET id = 0 WHERE pos = ''' + str(pos) + ''';''')
con.commit()
cursor.close()
def add_prev_player(con, form, team, prev_pos, poss):
''' Add the player chosen on the previous webpage to the current lineup.'''
player_id = request.form.get(form)
query = '''
SELECT name, id
FROM ''' + team + '''
WHERE id = ''' + str(player_id)
player_name = pd.read_sql_query(query,con).values[0][0]
player_id = pd.read_sql_query(query,con).values[0][1]
update_lineup(con, player_name, player_id, prev_pos, poss)
return player_name, player_id
def clear_lineup(con):
'''Set all lineup ids equal to zero. '''
cursor = con.cursor()
cursor.execute('''UPDATE lineup SET id = 0 ;''')
con.commit()
cursor.close()
def get_lineup(con):
''' Return the current lineup table as a dataframe.'''
query = ''' SELECT name, id FROM lineup ORDER BY pos '''
return pd.read_sql_query(query,con).values
def get_short_lineup(con):
''' Return the current lineup table as a dataframe, ignoring empty entries.'''
query = ''' SELECT name, id
FROM lineup
WHERE id <> 0
ORDER BY pos '''
return pd.read_sql_query(query,con).values
def load_team(con, team):
''' Return the remaining players available to be picked (i.e. those that have not been added to the lineup table).'''
query = ''' SELECT * FROM team_'''+ team + ''' WHERE id NOT IN (SELECT id FROM lineup)'''
team_df = pd.read_sql_query(query,con)
return team_df.rename(columns={'name': team + '_name', 'id': team + '_id', 'eight_skill': team + '_skill'})
def print_figure_init(pj, cj):
''' Produce a bar plot visualization of the predicted match points for all permutations. Produce a swarmplot showing predicted raw score coefficients for each permutation.'''
img = BytesIO()
fig, axs = plt.subplots(figsize=(15,5), ncols=2)
sb.despine(left=True)
sb.countplot(x='r1', data=pj, color='darkred', ax=axs[0])
axs[0].set_xlabel('Predicted winning points margin')
axs[0].set_ylabel('Permutations')
axs[0].set_xticklabels(['{:.0f}'.format(float(t.get_text())) for t in axs[0].get_xticklabels()])
axs[0].xaxis.set_tick_params(rotation=45)
g2 = sb.swarmplot(x=cj['r1'], color = 'darkred', size=10, ax=axs[1])
axs[1].legend(loc='best', fontsize='small')
axs[1].set_xlabel('Average winning probability')
plt.savefig(img, format='png', bbox_inches = "tight")
plt.close()
img.seek(0)
plot_url = base64.b64encode(img.getvalue()).decode('utf8')
return plot_url
def print_figure(pj, cj):
''' Produce a bar plot visualization of the predicted match points for the remaining permutations. Produce a swarmplot showing predicted raw score coefficients for each permutation, with remaining possible permutations highlighted.'''
img = BytesIO()
fig, axs = plt.subplots(figsize=(15,5), ncols=2)
sb.despine(left=True)
sb.countplot(x='r2', data=pj, color='darkred', ax=axs[0])
axs[0].set_xlabel('Predicted winning points margin')
axs[0].set_ylabel('Permutations')
axs[0].set_xticklabels(['{:.0f}'.format(float(t.get_text())) for t in axs[0].get_xticklabels()])
axs[0].xaxis.set_tick_params(rotation=45)
g2 = sb.swarmplot(x=cj['r1'], y=[""]*len(cj), hue=cj['round'], palette = ['lightgray', 'darkred'], size=10, ax=axs[1])
axs[1].legend(loc='best', fontsize='small')
axs[1].set_xlabel('Average winning probability')
plt.savefig(img, format='png', bbox_inches = "tight")
plt.close()
img.seek(0)
plot_url = base64.b64encode(img.getvalue()).decode('utf8')
return plot_url
def get_clause(lineup):
''' Construct the SQL clause which will filter the remaining permutations based on the currently selected matchups. '''
llen = len(lineup)
clause = ''''''
if llen >= 2: # i.e. if the lineup table contains one or more complete rounds
clause = clause + '''SELECT permutation FROM all_perms WHERE id_a = ''' + str(lineup[0][1]) + ''' AND id_b = ''' + str(lineup[1][1])
if llen >= 4: # i.e. if the lineup table contains one or more complete rounds
rnd = int(np.floor(llen/2) + 1) # current round
for i in range(2,rnd):
pos1 = 2*(i-1)
pos2 = 2*(i-1)+1
clause = clause + ''' INTERSECT SELECT permutation FROM all_perms WHERE id_a = ''' + str(lineup[pos1][1]) + ''' AND id_b = ''' + str(lineup[pos2][1])
return clause
def get_pick_clause(lineup):
''' Construct the SQL clause which will filter the remaining permutations based on the currently selected matchups. '''
llen = len(lineup)
clause = ''''''
rnd = int(np.floor(llen/2) + 1) # current round
for i in range(1,rnd):
pos1 = 2*(i-1)
pos2 = 2*(i-1)+1
clause = clause + ''' INTERSECT SELECT permutation FROM all_perms WHERE id_a = ''' + str(lineup[pos1][1]) + ''' AND id_b = ''' + str(lineup[pos2][1])
return clause
def calc_stds_coef(con, team_A_df, team_B_df):
''' For each remaining possible permutation, find the average winning probability of each permutation containing each possible player matchup. The best choice for your team to put up is the player who has the lowest standard deviation across their matchups, i.e. regardless of who the opposing team chooses, the average winning probability for the subsequent remaining permutations will be approximately the same. '''
lineup = get_short_lineup(con)
clause = get_pick_clause(lineup)
query = '''
SELECT player_a, id_a, STDDEV_POP(avg_prob) as stddev_prob
FROM (
SELECT a.player_a, a.id_a, a.player_b, AVG(s.probability) as avg_prob
FROM (
SELECT permutation FROM all_perms ''' + clause + ''') as f
JOIN all_perms as a ON f.permutation = a.permutation
JOIN perm_score as s ON a.permutation = s.permutation
GROUP BY a.player_b, a.player_a, a.id_a ) as grouped_scores
GROUP BY player_a, id_a
HAVING id_a NOT IN (SELECT id FROM lineup)
ORDER BY stddev_prob'''
stds = pd.read_sql_query(query,con)
return stds
def calc_min_coef(con, team_A_df, team_B_df):
''' For each remaining possible permutation, find the average winning probability of each permutation containing each possible player matchup. The best choice for your team to put up is the player who has the lowest standard deviation across their matchups, i.e. regardless of who the opposing team chooses, the average winning probability for the subsequent remaining permutations will be approximately the same. '''
lineup = get_short_lineup(con)
clause = get_pick_clause(lineup)
query = '''
SELECT player_a, id_a, MIN(avg_prob) as min_prob
FROM (
SELECT a.player_a, a.id_a, a.player_b, AVG(s.probability) as avg_prob
FROM (
SELECT permutation FROM all_perms ''' + clause + ''') as f
JOIN all_perms as a ON f.permutation = a.permutation
JOIN perm_score as s ON a.permutation = s.permutation
GROUP BY a.player_b, a.player_a, a.id_a ) as grouped_scores
GROUP BY player_a, id_a
HAVING id_a NOT IN (SELECT id FROM lineup)
ORDER BY min_prob DESC'''
mins = pd.read_sql_query(query,con)
return mins
def calc_coefs(con, team_A_df, player_b, player_b_id):
''' Find the average winning probability for all permutations containing the remaining players available on your team versus the player the opposition has chosen. The best choice for your team to put up is the player who has the highest average winning probability across all permutations where they play against the opposition's chosen player. Return the dataframe ranked in order of highest to lowest average winning probability.'''
lineup = get_short_lineup(con)
clause = get_pick_clause(lineup)
query = '''
SELECT a.id_a, a.player_a, a.player_b, AVG(s.probability) as avg_prob
FROM (
SELECT permutation FROM all_perms ''' + clause + ''') as f
JOIN all_perms as a ON f.permutation = a.permutation
JOIN perm_score as s ON a.permutation = s.permutation
WHERE a.id_b = ''' + str(player_b_id) + '''
GROUP BY a.id_a, a.player_a, a.player_b
ORDER BY avg_prob DESC '''
team_A_df = pd.read_sql_query(query,con)
return team_A_df
def agg_coefs_init(con):
''' Aggregate the winning probabilities from each permutation, returning their average values in a dataframe.'''
lineup = get_short_lineup(con)
clause = get_clause(lineup)
query = '''
SELECT permutation, probability
FROM perm_score
'''
coef = pd.read_sql_query(query,con).values
return pd.DataFrame(coef, columns = ['permutation','r1'])
def agg_scores_init(con):
''' Aggregate the match scores from each permutation, returning their total values in a dataframe.'''
lineup = get_short_lineup(con)
clause = get_clause(lineup)
query = '''
SELECT permutation, SUM(result)
FROM all_perms
GROUP BY permutation
'''
scores = pd.read_sql_query(query,con).values
return pd.DataFrame(scores, columns = ['permutation','r1'])
def agg_coefs(con):
''' Aggregate the winning probabilities from each permutation, returning their average values in a dataframe. Furthermore, perform the aggregation on the remaining active permutations and add this an extra column.'''
lineup = get_short_lineup(con)
clause = get_clause(lineup)
query = '''
SELECT r1.permutation, r1.avg_prob as r1_coef, r2.tot_score as r2_coef, CASE WHEN r2.tot_score IS NULL THEN 'All Predictions' ELSE 'Active Predictions' END as round
FROM (SELECT permutation, probability as avg_prob FROM perm_score) as r1
LEFT JOIN
(SELECT s.permutation, s.probability as tot_score
FROM (''' + clause + '''
) as p
LEFT JOIN perm_score as s ON p.permutation = s.permutation) as r2 ON r1.permutation = r2.permutation
'''
coef_joined = pd.read_sql_query(query,con).values
return pd.DataFrame(coef_joined, columns = ['permutation','r1','r2','round'])
def agg_scores(con):
''' Aggregate the match scores from each permutation, returning their total values in a dataframe. Futhermore, perform the aggregation on the remaining active permutations and add this an extra column.'''
lineup = get_short_lineup(con)
clause = get_clause(lineup)
query = '''
SELECT r1.permutation, r1.sum as r1_score, r2.tot_score as r2_score
FROM (SELECT permutation, SUM(result) as sum FROM all_perms
GROUP BY permutation) as r1
LEFT JOIN
(SELECT a.permutation, SUM(a.result) as tot_score
FROM (''' + clause + '''
) as p
LEFT JOIN all_perms as a ON p.permutation = a.permutation
GROUP BY a.permutation) as r2 ON r1.permutation = r2.permutation
'''
perms_joined = pd.read_sql_query(query,con).values
return pd.DataFrame(perms_joined, columns = ['permutation','r1','r2'])
def count_perms(con):
''' Return the total number of permutations.'''
query = '''
SELECT COUNT(*) FROM perm_score
'''
return pd.read_sql_query(query,con).values[0][0]
def get_perm(con):
''' Return the active permutation id(s).'''
lineup = get_short_lineup(con)
clause = get_clause(lineup)
query = clause
return pd.read_sql_query(query,con).values[0]
def get_perm_coef(con, perm):
''' Return the active permutation winning probability.'''
query = '''
SELECT probability
FROM perm_score
WHERE permutation = ''' + str(perm)
return pd.read_sql_query(query,con).values[0][0]
def get_average_coef(con):
''' Return the average winning probability over all permutations.'''
query = '''
SELECT AVG(probability)
FROM perm_score
'''
return pd.read_sql_query(query,con).values[0][0]
def get_perm_rank(con, perm):
''' Return the rank of the permutation, ordered by decreasing winning probability.'''
query = '''
SELECT rank
FROM
(SELECT permutation, probability, RANK() OVER(ORDER BY probability DESC)
FROM perm_score) as r
WHERE permutation = ''' + str(perm)
return pd.read_sql_query(query,con).values[0][0]
def final_lineup(con, perm):
''' Return the final lineup and the score coefficients for the individual matchups.'''
query = '''
SELECT player_a, probability, player_b FROM all_perms
WHERE permutation = ''' + str(perm) + '''
ORDER BY probability DESC
'''
return pd.read_sql_query(query,con).values
def a_pick_first(con):
''' When team a is picking first, use the calc_min_coef function to determine the recommended player. Update which permutations are still active for the visualization.'''
lineup = get_lineup(con)
team_A_df = load_team(con, 'a')
team_B_df = load_team(con, 'b')
stds = calc_min_coef(con, team_A_df, team_B_df)
rec =['']*len(team_A_df)
rec[0] = ' (Recommended)'
pj = agg_scores(con)
cj = agg_coefs(con)
plot_url = print_figure(pj, cj)
return lineup, stds, rec, plot_url
def a_pick_second(con, player_b, player_b_id):
''' When team a is picking second, use the calc_coefs function to determine the recommended player. Update which permutations are still active for the visualization.'''
lineup = get_lineup(con)
team_A_df = load_team(con, 'a')
team_A_df = calc_coefs(con, team_A_df, player_b, player_b_id)
rec =['']*len(team_A_df)
rec[0] = ' (Recommended)'
pj = agg_scores(con)
cj = agg_coefs(con)
plot_url = print_figure(pj, cj)
return lineup, team_A_df, rec, plot_url
def b_pick(con):
''' When team b is picking, there is no need to return a recommended player. Return the current lineup and team b players available for selection, and update the visualization.'''
team_B_df = load_team(con, 'b')
lineup = get_lineup(con)
pj = agg_scores(con)
cj = agg_coefs(con)
plot_url = print_figure(pj, cj)
return lineup, team_B_df, plot_url
def create_summary(con):
''' Return summary statistics for the overall match and the final permutation, including the average total score coefficient over all permutations, the total score coefficient of the final permutation, and the rank of this permutation.'''
pj = agg_scores(con)
cj = agg_coefs(con)
plot_url = print_figure(pj, cj)
tot_perms = count_perms(con) #the total number of permutations (120 for 5 player teams)
av_coef = "{0:.2f}".format(get_average_coef(con)) #the average total score coefficient over all permutations
active_perm = get_perm(con)[0] #the id number of the final active permutation
perm_coef = "{0:.2f}".format(get_perm_coef(con, active_perm)) #the total score coefficient of the final permutation
rank = get_perm_rank(con, active_perm) #the rank of this permutation (lower rank number indicates higher total score coefficient)
final = final_lineup(con, active_perm)
return final, tot_perms, perm_coef, av_coef, rank, plot_url
def similar_skills(con, player_b_id):
''' Find the maximum score coefficient of all players on your team vs the chosen player on the opposing team.'''
query = '''
SELECT id, ABS(eight_skill - (SELECT eight_skill FROM team_b WHERE id = ''' + str(player_b_id) + '''))
AS diffs
FROM team_a
WHERE id NOT IN (SELECT id FROM lineup)
ORDER BY diffs
LIMIT 1
'''
return pd.read_sql_query(query,con).values[0][0]
| [
"pandas.read_sql_query",
"matplotlib.pyplot.savefig",
"seaborn.despine",
"pandas.DataFrame",
"matplotlib.use",
"napa.player_information.create_rand_team",
"napa.player_information.create_two_rand_teams",
"seaborn.set_context",
"io.BytesIO",
"numpy.floor",
"napa.player_information.team_data",
"... | [((211, 232), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (225, 232), False, 'import matplotlib\n'), ((369, 405), 'seaborn.set_context', 'sb.set_context', (['"""talk"""'], {'font_scale': '(1)'}), "('talk', font_scale=1)\n", (383, 405), True, 'import seaborn as sb\n'), ((408, 438), 'matplotlib.style.use', 'style.use', (['"""seaborn-whitegrid"""'], {}), "('seaborn-whitegrid')\n", (417, 438), True, 'import matplotlib.style as style\n'), ((1234, 1262), 'flask.request.form.get', 'request.form.get', (['"""random_a"""'], {}), "('random_a')\n", (1250, 1262), False, 'from flask import request\n'), ((1276, 1304), 'flask.request.form.get', 'request.form.get', (['"""random_b"""'], {}), "('random_b')\n", (1292, 1304), False, 'from flask import request\n'), ((2564, 2593), 'pandas.read_sql_query', 'pd.read_sql_query', (['query', 'con'], {}), '(query, con)\n', (2581, 2593), True, 'import pandas as pd\n'), ((2839, 2868), 'pandas.read_sql_query', 'pd.read_sql_query', (['query', 'con'], {}), '(query, con)\n', (2856, 2868), True, 'import pandas as pd\n'), ((4151, 4173), 'flask.request.form.get', 'request.form.get', (['form'], {}), '(form)\n', (4167, 4173), False, 'from flask import request\n'), ((5414, 5443), 'pandas.read_sql_query', 'pd.read_sql_query', (['query', 'con'], {}), '(query, con)\n', (5431, 5443), True, 'import pandas as pd\n'), ((5781, 5790), 'io.BytesIO', 'BytesIO', ([], {}), '()\n', (5788, 5790), False, 'from io import BytesIO\n'), ((5806, 5844), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(15, 5)', 'ncols': '(2)'}), '(figsize=(15, 5), ncols=2)\n', (5818, 5844), True, 'import matplotlib.pyplot as plt\n'), ((5849, 5870), 'seaborn.despine', 'sb.despine', ([], {'left': '(True)'}), '(left=True)\n', (5859, 5870), True, 'import seaborn as sb\n'), ((5875, 5932), 'seaborn.countplot', 'sb.countplot', ([], {'x': '"""r1"""', 'data': 'pj', 'color': '"""darkred"""', 'ax': 'axs[0]'}), "(x='r1', data=pj, color='darkred', ax=axs[0])\n", (5887, 5932), True, 'import seaborn as sb\n'), ((6184, 6245), 'seaborn.swarmplot', 'sb.swarmplot', ([], {'x': "cj['r1']", 'color': '"""darkred"""', 'size': '(10)', 'ax': 'axs[1]'}), "(x=cj['r1'], color='darkred', size=10, ax=axs[1])\n", (6196, 6245), True, 'import seaborn as sb\n'), ((6358, 6409), 'matplotlib.pyplot.savefig', 'plt.savefig', (['img'], {'format': '"""png"""', 'bbox_inches': '"""tight"""'}), "(img, format='png', bbox_inches='tight')\n", (6369, 6409), True, 'import matplotlib.pyplot as plt\n'), ((6416, 6427), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (6425, 6427), True, 'import matplotlib.pyplot as plt\n'), ((6809, 6818), 'io.BytesIO', 'BytesIO', ([], {}), '()\n', (6816, 6818), False, 'from io import BytesIO\n'), ((6834, 6872), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(15, 5)', 'ncols': '(2)'}), '(figsize=(15, 5), ncols=2)\n', (6846, 6872), True, 'import matplotlib.pyplot as plt\n'), ((6877, 6898), 'seaborn.despine', 'sb.despine', ([], {'left': '(True)'}), '(left=True)\n', (6887, 6898), True, 'import seaborn as sb\n'), ((6903, 6960), 'seaborn.countplot', 'sb.countplot', ([], {'x': '"""r2"""', 'data': 'pj', 'color': '"""darkred"""', 'ax': 'axs[0]'}), "(x='r2', data=pj, color='darkred', ax=axs[0])\n", (6915, 6960), True, 'import seaborn as sb\n'), ((7436, 7487), 'matplotlib.pyplot.savefig', 'plt.savefig', (['img'], {'format': '"""png"""', 'bbox_inches': '"""tight"""'}), "(img, format='png', bbox_inches='tight')\n", (7447, 7487), True, 'import matplotlib.pyplot as plt\n'), ((7494, 7505), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (7503, 7505), True, 'import matplotlib.pyplot as plt\n'), ((10113, 10142), 'pandas.read_sql_query', 'pd.read_sql_query', (['query', 'con'], {}), '(query, con)\n', (10130, 10142), True, 'import pandas as pd\n'), ((11263, 11292), 'pandas.read_sql_query', 'pd.read_sql_query', (['query', 'con'], {}), '(query, con)\n', (11280, 11292), True, 'import pandas as pd\n'), ((12326, 12355), 'pandas.read_sql_query', 'pd.read_sql_query', (['query', 'con'], {}), '(query, con)\n', (12343, 12355), True, 'import pandas as pd\n'), ((12741, 12790), 'pandas.DataFrame', 'pd.DataFrame', (['coef'], {'columns': "['permutation', 'r1']"}), "(coef, columns=['permutation', 'r1'])\n", (12753, 12790), True, 'import pandas as pd\n'), ((13168, 13219), 'pandas.DataFrame', 'pd.DataFrame', (['scores'], {'columns': "['permutation', 'r1']"}), "(scores, columns=['permutation', 'r1'])\n", (13180, 13219), True, 'import pandas as pd\n'), ((14093, 14164), 'pandas.DataFrame', 'pd.DataFrame', (['coef_joined'], {'columns': "['permutation', 'r1', 'r2', 'round']"}), "(coef_joined, columns=['permutation', 'r1', 'r2', 'round'])\n", (14105, 14164), True, 'import pandas as pd\n'), ((14970, 15033), 'pandas.DataFrame', 'pd.DataFrame', (['perms_joined'], {'columns': "['permutation', 'r1', 'r2']"}), "(perms_joined, columns=['permutation', 'r1', 'r2'])\n", (14982, 15033), True, 'import pandas as pd\n'), ((4859, 4888), 'pandas.read_sql_query', 'pd.read_sql_query', (['query', 'con'], {}), '(query, con)\n', (4876, 4888), True, 'import pandas as pd\n'), ((5116, 5145), 'pandas.read_sql_query', 'pd.read_sql_query', (['query', 'con'], {}), '(query, con)\n', (5133, 5145), True, 'import pandas as pd\n'), ((12694, 12723), 'pandas.read_sql_query', 'pd.read_sql_query', (['query', 'con'], {}), '(query, con)\n', (12711, 12723), True, 'import pandas as pd\n'), ((13121, 13150), 'pandas.read_sql_query', 'pd.read_sql_query', (['query', 'con'], {}), '(query, con)\n', (13138, 13150), True, 'import pandas as pd\n'), ((14046, 14075), 'pandas.read_sql_query', 'pd.read_sql_query', (['query', 'con'], {}), '(query, con)\n', (14063, 14075), True, 'import pandas as pd\n'), ((14923, 14952), 'pandas.read_sql_query', 'pd.read_sql_query', (['query', 'con'], {}), '(query, con)\n', (14940, 14952), True, 'import pandas as pd\n'), ((16620, 16649), 'pandas.read_sql_query', 'pd.read_sql_query', (['query', 'con'], {}), '(query, con)\n', (16637, 16649), True, 'import pandas as pd\n'), ((1422, 1449), 'napa.player_information.create_two_rand_teams', 'pi.create_two_rand_teams', (['(5)'], {}), '(5)\n', (1446, 1449), True, 'from napa import player_information as pi\n'), ((8705, 8723), 'numpy.floor', 'np.floor', (['(llen / 2)'], {}), '(llen / 2)\n', (8713, 8723), True, 'import numpy as np\n'), ((15410, 15439), 'pandas.read_sql_query', 'pd.read_sql_query', (['query', 'con'], {}), '(query, con)\n', (15427, 15439), True, 'import pandas as pd\n'), ((1537, 1559), 'napa.player_information.create_rand_team', 'pi.create_rand_team', (['(5)'], {}), '(5)\n', (1556, 1559), True, 'from napa import player_information as pi\n'), ((1630, 1650), 'napa.player_information.team_data', 'pi.team_data', (['team_B'], {}), '(team_B)\n', (1642, 1650), True, 'from napa import player_information as pi\n'), ((3227, 3256), 'pandas.read_sql_query', 'pd.read_sql_query', (['query', 'con'], {}), '(query, con)\n', (3244, 3256), True, 'import pandas as pd\n'), ((3285, 3314), 'pandas.read_sql_query', 'pd.read_sql_query', (['query', 'con'], {}), '(query, con)\n', (3302, 3314), True, 'import pandas as pd\n'), ((4300, 4329), 'pandas.read_sql_query', 'pd.read_sql_query', (['query', 'con'], {}), '(query, con)\n', (4317, 4329), True, 'import pandas as pd\n'), ((4358, 4387), 'pandas.read_sql_query', 'pd.read_sql_query', (['query', 'con'], {}), '(query, con)\n', (4375, 4387), True, 'import pandas as pd\n'), ((15189, 15218), 'pandas.read_sql_query', 'pd.read_sql_query', (['query', 'con'], {}), '(query, con)\n', (15206, 15218), True, 'import pandas as pd\n'), ((15666, 15695), 'pandas.read_sql_query', 'pd.read_sql_query', (['query', 'con'], {}), '(query, con)\n', (15683, 15695), True, 'import pandas as pd\n'), ((15901, 15930), 'pandas.read_sql_query', 'pd.read_sql_query', (['query', 'con'], {}), '(query, con)\n', (15918, 15930), True, 'import pandas as pd\n'), ((16269, 16298), 'pandas.read_sql_query', 'pd.read_sql_query', (['query', 'con'], {}), '(query, con)\n', (16286, 16298), True, 'import pandas as pd\n'), ((19653, 19682), 'pandas.read_sql_query', 'pd.read_sql_query', (['query', 'con'], {}), '(query, con)\n', (19670, 19682), True, 'import pandas as pd\n'), ((1816, 1838), 'napa.player_information.create_rand_team', 'pi.create_rand_team', (['(5)'], {}), '(5)\n', (1835, 1838), True, 'from napa import player_information as pi\n'), ((1909, 1929), 'napa.player_information.team_data', 'pi.team_data', (['team_A'], {}), '(team_A)\n', (1921, 1929), True, 'from napa import player_information as pi\n'), ((2160, 2180), 'napa.player_information.team_data', 'pi.team_data', (['team_A'], {}), '(team_A)\n', (2172, 2180), True, 'from napa import player_information as pi\n'), ((2205, 2225), 'napa.player_information.team_data', 'pi.team_data', (['team_B'], {}), '(team_B)\n', (2217, 2225), True, 'from napa import player_information as pi\n'), ((8145, 8163), 'numpy.floor', 'np.floor', (['(llen / 2)'], {}), '(llen / 2)\n', (8153, 8163), True, 'import numpy as np\n')] |
import numpy as np
from torch.utils.data import Dataset
import sys
import torch
from ppo_and_friends.utils.mpi_utils import rank_print
from mpi4py import MPI
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
num_procs = comm.Get_size()
class EpisodeInfo(object):
def __init__(self,
starting_ts = 0,
use_gae = False,
gamma = 0.99,
lambd = 0.95,
bootstrap_clip = (-10., 10.)):
"""
A container for storing episode information.
Arguments:
starting_ts The timestep that this episode starts at.
use_gae Should we use the Generalized Advantage
Estimation algorithm when calculating advantages?
gamma The discount factor to apply when calculating
discounted sums. This is used for advantages and
"rewards-to-go" (expected discounted returns).
labmd A "smoothing" factor used in GAE.
bootstrap_clip A value to clip our bootstrapped rewards to.
"""
self.starting_ts = starting_ts
self.ending_ts = -1
self.use_gae = use_gae
self.gamma = gamma
self.lambd = lambd
self.bootstrap_clip = bootstrap_clip
self.global_observations = []
self.observations = []
self.next_observations = []
self.actions = []
self.raw_actions = []
self.log_probs = []
self.rewards = []
self.values = []
self.actor_hidden = []
self.critic_hidden = []
self.actor_cell = []
self.critic_cell = []
self.rewards_to_go = None
self.advantages = None
self.length = 0
self.is_finished = False
self.has_hidden_states = False
self.has_global_obs = False
def compute_discounted_sums(self, array, gamma):
"""
Compute the discounted sums from a given array,
which is assumed to be in temmporal order,
[t0, t1, t2, ..., tn], where t0 is a 'value' at
time 0, and tn is a 'value' at time n. Note that value
here is not to be confused with the value from a value
function; it's just some number. It could be a reward,
a value from a value function, or whatever else you'd like.
The discounted value at time t, DVt, follows the recursive formula
DVt = DVt + (gamma * DVt+1)
Such that all future values are considered in the current DV but
at a discount.
That is,
DSn = tn
DS(n-1) = t(n-1) + (gamma * tn)
...
DS0 = t0 + (gamma * t1) + (gamma^2 * t2) + ...
+ (gamma^n + tn)
Arguments:
array The array to calculate a discounted sum for.
Returns:
A numpy array containing the discounted sums.
"""
cumulative_array = np.zeros(len(array))
last_idx = len(array) - 1
d_sum = 0
for idx, val in enumerate(array[::-1]):
d_sum = val + gamma * d_sum
cumulative_array[last_idx - idx] = d_sum
return cumulative_array
def _compute_gae_advantages(self,
padded_values,
rewards):
"""
Compute the General Advantage Estimates. This follows the
general GAE equation.
Arguments:
padded_values A list of values from this epsiode with one
extra value added to the end. This will either
be a 0 (if the episode finished) or a repeat
of the last value.
Returns:
An array containing the GAEs.
"""
deltas = rewards + (self.gamma * padded_values[1:]) - \
padded_values[:-1]
sum_gamma = self.gamma * self.lambd
return self.compute_discounted_sums(deltas.tolist(), sum_gamma)
def _compute_standard_advantages(self):
"""
Use a standard method for computing advantages.
Typically, we use Q - values.
"""
advantages = self.rewards_to_go - self.values
return advantages
def add_info(self,
observation,
next_observation,
raw_action,
action,
value,
log_prob,
reward,
global_observation = np.empty(0),
actor_hidden = np.empty(0),
actor_cell = np.empty(0),
critic_hidden = np.empty(0),
critic_cell = np.empty(0)):
"""
Add info from a single step in an episode. These should be
added consecutively, in the order they are encountered.
Arguments:
observation The observation eliciting our action.
next_observation The observation resulting from our
action.
raw_action The un-altered action (there are times
when we squash our actions into a new
range. This value is pre-squash).
action The action taken at this step.
value The predicted value at this step (from
the critic).
log_prob The log probability calculated at this
step.
reward The reward received at this step.
global_observation The global observation used in multi-
agent environments eliciting our
action.
actor_hidden The hidden state of the actor iff the
actor is an lstm.
actor_cell The cell state of the actor iff the
actor is an lstm.
critic_hidden The hidden state of the critic iff the
critic is an lstm.
critic_cell The cell state of the critic iff the
critic is an lstm.
"""
if type(raw_action) == np.ndarray and len(raw_action.shape) > 1:
raw_action = raw_action.squeeze()
if type(action) == np.ndarray and len(action.shape) > 1:
action = action.squeeze()
self.observations.append(observation)
self.next_observations.append(next_observation)
self.actions.append(action)
self.raw_actions.append(raw_action)
self.values.append(value)
self.log_probs.append(log_prob)
self.rewards.append(reward)
if global_observation.size > 0:
self.has_global_obs = True
self.global_observations.append(global_observation)
ac_hidden_check = np.array(
(len(actor_hidden),
len(actor_cell),
len(critic_hidden),
len(critic_cell))).astype(np.int32)
if ( (ac_hidden_check > 0).any() and
(ac_hidden_check == 0).any() ):
msg = "ERROR: if hidden state is provided for either the actor "
msg += "or the critic, both most be provided, but we received "
msg += "only one. Bailing..."
rank_print(msg)
comm.Abort()
if len(actor_hidden) > 0:
self.has_hidden_states = True
self.actor_hidden.append(
actor_hidden.detach().cpu().numpy())
self.critic_hidden.append(
critic_hidden.detach().cpu().numpy())
self.actor_cell.append(
actor_cell.detach().cpu().numpy())
self.critic_cell.append(
critic_cell.detach().cpu().numpy())
def compute_advantages(self):
"""
Compute our advantages using either a standard formula or GAE.
"""
if self.use_gae:
padded_values = np.concatenate((self.values, (self.ending_value,)))
padded_values = padded_values.astype(np.float32)
self.advantages = self._compute_gae_advantages(
padded_values,
self.rewards)
else:
self.advantages = self._compute_standard_advantages()
def end_episode(self,
ending_ts,
terminal,
ending_value,
ending_reward):
"""
End the episode.
Arguments:
ending_ts The time step we ended on.
terminal Did we end in a terminal state?
ending_value The ending value of the episode.
ending_reward The ending reward of the episode.
"""
self.ending_ts = ending_ts
self.terminal = terminal
self.length = self.ending_ts - self.starting_ts
self.is_finished = True
self.ending_value = ending_value
#
# Clipping the ending value can have dramaticly positive
# effects on training. MountainCarContinuous is a great
# example of an environment that I've seen struggle quite
# a bit without a propper bs clip.
#
ending_reward = np.clip(
ending_reward,
self.bootstrap_clip[0],
self.bootstrap_clip[1])
padded_rewards = np.array(self.rewards + [ending_reward],
dtype=np.float32)
self.rewards_to_go = self.compute_discounted_sums(
padded_rewards,
self.gamma)[:-1]
self.values = np.array(self.values).astype(np.float32)
self.compute_advantages()
class PPODataset(Dataset):
def __init__(self,
device,
action_dtype,
sequence_length = 1):
"""
A PyTorch Dataset representing our rollout data.
Arguments:
device The device we're training on.
action_dtype The action data dtype (discrete/continuous).
sequence_length If set to > 1, our dataset will return
obervations as sequences of this length.
"""
self.action_dtype = action_dtype
self.device = device
self.episodes = []
self.is_built = False
self.build_hidden_states = False
self.build_global_obs = False
self.sequence_length = sequence_length
self.build_terminal_mask = False
if self.sequence_length <= 0:
msg = "ERROR: PPODataset must have a sequence length >= 1 "
msg += "but received {}".format(self.sequence_length)
rank_print(msg)
comm.Abort()
elif self.sequence_length > 1:
self.build_terminal_mask = True
self.actions = None
self.raw_actions = None
self.global_observations = None
self.observations = None
self.next_observations = None
self.rewards_to_go = None
self.log_probs = None
self.ep_lens = None
self.advantages = None
self.actor_hidden = None
self.critic_hidden = None
self.actor_cell = None
self.critic_cell = None
self.terminal_mask = None
self.values = None
def add_episode(self, episode):
"""
Add an episode to our dataset.
Arguments:
episode The episode to add.
"""
if episode.has_hidden_states:
self.build_hidden_states = True
elif self.build_hidden_states and not episode.has_hidden_states:
msg = "ERROR: some episodes have hidden states while others "
msg += "do not. Bailing..."
rank_print(msg)
comm.Abort()
if episode.has_global_obs:
self.build_global_obs = True
elif self.build_global_obs and not episode.has_global_obs:
msg = "ERROR: some episodes have global observations while others "
msg += "do not. Bailing..."
rank_print(msg)
comm.Abort()
self.episodes.append(episode)
def recalculate_advantages(self):
"""
Recalculate our advantages. This can be used to mitigate using
stale advantages when training over > 1 epochs.
"""
if not self.is_built:
msg = "WARNING: recalculate_advantages was called before "
msg += "the dataset has been built. Ignoring call."
rank_print(msg)
return
val_idx = 0
for ep in self.episodes:
for ep_ts in range(ep.length):
ep.values[ep_ts] = self.values[val_idx]
val_idx += 1
ep.compute_advantages()
def build(self):
"""
Build our dataset from the existing episodes.
"""
if self.is_built:
msg = "ERROR: attempting to build a batch, but it's "
msg += "already been built! Bailing..."
rank_print(msg)
comm.Abort()
#
# TODO: let's use numpy arrays to save on space.
#
self.actions = []
self.raw_actions = []
self.global_observations = []
self.observations = []
self.next_observations = []
self.rewards_to_go = []
self.log_probs = []
self.ep_lens = []
self.advantages = []
self.actor_hidden = []
self.critic_hidden = []
self.actor_cell = []
self.critic_cell = []
self.values = []
self.num_episodes = len(self.episodes)
self.total_timestates = 0
for ep in self.episodes:
self.total_timestates += ep.length
if self.build_terminal_mask:
terminal_mask = np.zeros(self.total_timestates).astype(np.bool)
cur_ts = 0
for ep in self.episodes:
if not ep.is_finished:
msg = "ERROR: attempting to build a batch using "
msg += "an incomplete episode! Bailing..."
rank_print(msg)
comm.Abort()
self.actions.extend(ep.actions)
self.raw_actions.extend(ep.raw_actions)
self.observations.extend(ep.observations)
self.next_observations.extend(ep.next_observations)
self.rewards_to_go.extend(ep.rewards_to_go)
self.log_probs.extend(ep.log_probs)
self.ep_lens.append(ep.length)
self.advantages.extend(ep.advantages)
self.values.extend(ep.values)
if self.build_hidden_states:
self.actor_hidden.extend(ep.actor_hidden)
self.critic_hidden.extend(ep.critic_hidden)
self.actor_cell.extend(ep.actor_cell)
self.critic_cell.extend(ep.critic_cell)
if self.build_global_obs:
self.global_observations.extend(ep.global_observations)
if self.build_terminal_mask:
cur_ts += ep.length
if ep.terminal:
terminal_mask[cur_ts - 1] = True
if self.build_terminal_mask:
max_ts = self.total_timestates - (self.sequence_length - 1)
self.terminal_sequence_masks = np.array(
[None] * max_ts, dtype=object)
for ts in range(max_ts):
mask = np.zeros(self.sequence_length).astype(np.bool)
mask_idx = 0
stop_ts = ts + self.sequence_length
for mask_ts in range(ts, stop_ts):
if terminal_mask[mask_ts]:
mask[mask_idx + 1:] = True
break
mask_idx += 1
self.terminal_sequence_masks[ts] = mask
if self.total_timestates != len(self.observations):
error_msg = "ERROR: expected the total timestates to match "
error_msg += "the total number of observations, but got "
error_msg += "{} vs {}".format(self.total_timestates,
len(self.observations))
rank_print(error_msg)
comm.Abort()
#
# Note that log_probs is a list of tensors, so we'll skip converting
# it to a numpy array.
#
self.actions = np.array(self.actions)
self.raw_actions = np.array(self.raw_actions)
self.global_observations = np.array(self.global_observations)
self.observations = np.array(self.observations)
self.next_observations = np.array(self.next_observations)
self.rewards_to_go = np.array(self.rewards_to_go)
self.ep_lens = np.array(self.ep_lens)
self.advantages = np.array(self.advantages)
self.values = torch.tensor(self.values)
self.values = self.values.to(self.device)
if self.build_hidden_states:
#
# Torch expects the shape to be
# (num_lstm_layers, batch_size, hidden_size), but our
# data loader will concat on the first dimension. So, we
# need to transpose so that the batch size comes first.
#
self.actor_hidden = torch.tensor(
np.concatenate(self.actor_hidden, axis=1)).to(self.device)
self.critic_hidden = torch.tensor(
np.concatenate(self.critic_hidden, axis=1)).to(self.device)
self.actor_cell = torch.tensor(
np.concatenate(self.actor_cell, axis=1)).to(self.device)
self.critic_cell = torch.tensor(
np.concatenate(self.critic_cell, axis=1)).to(self.device)
self.actor_hidden = torch.transpose(self.actor_hidden, 0, 1)
self.actor_cell = torch.transpose(self.actor_cell, 0, 1)
self.critic_hidden = torch.transpose(self.critic_hidden, 0, 1)
self.critic_cell = torch.transpose(self.critic_cell, 0, 1)
else:
empty_state = np.zeros(self.total_timestates).astype(np.uint8)
self.actor_hidden = empty_state
self.critic_hidden = empty_state
self.actor_cell = empty_state
self.critic_cell = empty_state
self.advantages = torch.tensor(self.advantages,
dtype=torch.float).to(self.device)
self.observations = torch.tensor(self.observations,
dtype=torch.float).to(self.device)
self.next_observations = torch.tensor(self.next_observations,
dtype=torch.float).to(self.device)
#
# If we're building global observations, we use the global observations
# from our episodes. Otherwise, the global observation tensor is a
# reference to our observations tensor.
#
if self.build_global_obs:
self.global_observations = torch.tensor(self.global_observations,
dtype=torch.float).to(self.device)
else:
self.global_observations = self.observations
self.log_probs = torch.tensor(self.log_probs,
dtype=torch.float).to(self.device)
self.rewards_to_go = torch.tensor(self.rewards_to_go,
dtype=torch.float).to(self.device)
if self.action_dtype == "continuous":
self.actions = torch.tensor(self.actions,
dtype=torch.float).to(self.device)
self.raw_actions = torch.tensor(self.raw_actions,
dtype=torch.float).to(self.device)
elif self.action_dtype == "discrete":
self.actions = torch.tensor(self.actions,
dtype=torch.long).to(self.device)
self.raw_actions = torch.tensor(self.raw_actions,
dtype=torch.long).to(self.device)
self.is_built = True
def __len__(self):
"""
Get the length of our dataset.
"""
return self.total_timestates - (self.sequence_length - 1)
def __getitem__(self, idx):
"""
Get data of length self.sequence_length starting at index
idx.
Arguments:
idx The starting point of the data to retrieve.
Returns:
All data associated with the given index in our dataset.
"""
#
# First, handle the easy case of using single time states.
#
if self.sequence_length == 1:
return (self.global_observations[idx],
self.observations[idx],
self.next_observations[idx],
self.raw_actions[idx],
self.actions[idx],
self.advantages[idx],
self.log_probs[idx],
self.rewards_to_go[idx],
self.actor_hidden[idx],
self.critic_hidden[idx],
self.actor_cell[idx],
self.critic_cell[idx],
idx)
#
# We want our time sequence to start at the most recent state,
# which means we'll be building a "tail" of history samples.
#
idx += (self.sequence_length - 1)
start = idx - (self.sequence_length - 1)
stop = idx + 1
glob_obs_seq = self.global_observations[start : stop].clone()
obs_seq = self.observations[start : stop].clone()
nxt_obs_seq = self.next_observations[start : stop].clone()
#
# Once we hit a terminal state, all subsequent observations
# need to be zero'd out so that the model can learn that future
# observations don't exist in this trajectory.
#
term_mask = self.terminal_sequence_masks[start]
obs_seq[term_mask] = 0.0
nxt_obs_seq[term_mask] = 0.0
return (glob_obs_seq,
obs_seq,
nxt_obs_seq,
self.raw_actions[idx],
self.actions[idx],
self.advantages[idx],
self.log_probs[idx],
self.rewards_to_go[idx],
self.actor_hidden[idx],
self.critic_hidden[idx],
self.actor_cell[idx],
self.critic_cell[idx],
idx)
| [
"numpy.clip",
"torch.transpose",
"numpy.array",
"torch.tensor",
"numpy.zeros",
"numpy.empty",
"numpy.concatenate",
"ppo_and_friends.utils.mpi_utils.rank_print"
] | [((5083, 5094), 'numpy.empty', 'np.empty', (['(0)'], {}), '(0)\n', (5091, 5094), True, 'import numpy as np\n'), ((5134, 5145), 'numpy.empty', 'np.empty', (['(0)'], {}), '(0)\n', (5142, 5145), True, 'import numpy as np\n'), ((5185, 5196), 'numpy.empty', 'np.empty', (['(0)'], {}), '(0)\n', (5193, 5196), True, 'import numpy as np\n'), ((5236, 5247), 'numpy.empty', 'np.empty', (['(0)'], {}), '(0)\n', (5244, 5247), True, 'import numpy as np\n'), ((5287, 5298), 'numpy.empty', 'np.empty', (['(0)'], {}), '(0)\n', (5295, 5298), True, 'import numpy as np\n'), ((10194, 10264), 'numpy.clip', 'np.clip', (['ending_reward', 'self.bootstrap_clip[0]', 'self.bootstrap_clip[1]'], {}), '(ending_reward, self.bootstrap_clip[0], self.bootstrap_clip[1])\n', (10201, 10264), True, 'import numpy as np\n'), ((10328, 10386), 'numpy.array', 'np.array', (['(self.rewards + [ending_reward])'], {'dtype': 'np.float32'}), '(self.rewards + [ending_reward], dtype=np.float32)\n', (10336, 10386), True, 'import numpy as np\n'), ((17782, 17804), 'numpy.array', 'np.array', (['self.actions'], {}), '(self.actions)\n', (17790, 17804), True, 'import numpy as np\n'), ((17845, 17871), 'numpy.array', 'np.array', (['self.raw_actions'], {}), '(self.raw_actions)\n', (17853, 17871), True, 'import numpy as np\n'), ((17912, 17946), 'numpy.array', 'np.array', (['self.global_observations'], {}), '(self.global_observations)\n', (17920, 17946), True, 'import numpy as np\n'), ((17987, 18014), 'numpy.array', 'np.array', (['self.observations'], {}), '(self.observations)\n', (17995, 18014), True, 'import numpy as np\n'), ((18055, 18087), 'numpy.array', 'np.array', (['self.next_observations'], {}), '(self.next_observations)\n', (18063, 18087), True, 'import numpy as np\n'), ((18128, 18156), 'numpy.array', 'np.array', (['self.rewards_to_go'], {}), '(self.rewards_to_go)\n', (18136, 18156), True, 'import numpy as np\n'), ((18197, 18219), 'numpy.array', 'np.array', (['self.ep_lens'], {}), '(self.ep_lens)\n', (18205, 18219), True, 'import numpy as np\n'), ((18260, 18285), 'numpy.array', 'np.array', (['self.advantages'], {}), '(self.advantages)\n', (18268, 18285), True, 'import numpy as np\n'), ((18326, 18351), 'torch.tensor', 'torch.tensor', (['self.values'], {}), '(self.values)\n', (18338, 18351), False, 'import torch\n'), ((8230, 8245), 'ppo_and_friends.utils.mpi_utils.rank_print', 'rank_print', (['msg'], {}), '(msg)\n', (8240, 8245), False, 'from ppo_and_friends.utils.mpi_utils import rank_print\n'), ((8900, 8951), 'numpy.concatenate', 'np.concatenate', (['(self.values, (self.ending_value,))'], {}), '((self.values, (self.ending_value,)))\n', (8914, 8951), True, 'import numpy as np\n'), ((11701, 11716), 'ppo_and_friends.utils.mpi_utils.rank_print', 'rank_print', (['msg'], {}), '(msg)\n', (11711, 11716), False, 'from ppo_and_friends.utils.mpi_utils import rank_print\n'), ((13752, 13767), 'ppo_and_friends.utils.mpi_utils.rank_print', 'rank_print', (['msg'], {}), '(msg)\n', (13762, 13767), False, 'from ppo_and_friends.utils.mpi_utils import rank_print\n'), ((14268, 14283), 'ppo_and_friends.utils.mpi_utils.rank_print', 'rank_print', (['msg'], {}), '(msg)\n', (14278, 14283), False, 'from ppo_and_friends.utils.mpi_utils import rank_print\n'), ((16719, 16758), 'numpy.array', 'np.array', (['([None] * max_ts)'], {'dtype': 'object'}), '([None] * max_ts, dtype=object)\n', (16727, 16758), True, 'import numpy as np\n'), ((17566, 17587), 'ppo_and_friends.utils.mpi_utils.rank_print', 'rank_print', (['error_msg'], {}), '(error_msg)\n', (17576, 17587), False, 'from ppo_and_friends.utils.mpi_utils import rank_print\n'), ((19233, 19273), 'torch.transpose', 'torch.transpose', (['self.actor_hidden', '(0)', '(1)'], {}), '(self.actor_hidden, 0, 1)\n', (19248, 19273), False, 'import torch\n'), ((19307, 19345), 'torch.transpose', 'torch.transpose', (['self.actor_cell', '(0)', '(1)'], {}), '(self.actor_cell, 0, 1)\n', (19322, 19345), False, 'import torch\n'), ((19379, 19420), 'torch.transpose', 'torch.transpose', (['self.critic_hidden', '(0)', '(1)'], {}), '(self.critic_hidden, 0, 1)\n', (19394, 19420), False, 'import torch\n'), ((19454, 19493), 'torch.transpose', 'torch.transpose', (['self.critic_cell', '(0)', '(1)'], {}), '(self.critic_cell, 0, 1)\n', (19469, 19493), False, 'import torch\n'), ((10539, 10560), 'numpy.array', 'np.array', (['self.values'], {}), '(self.values)\n', (10547, 10560), True, 'import numpy as np\n'), ((12976, 12991), 'ppo_and_friends.utils.mpi_utils.rank_print', 'rank_print', (['msg'], {}), '(msg)\n', (12986, 12991), False, 'from ppo_and_friends.utils.mpi_utils import rank_print\n'), ((13296, 13311), 'ppo_and_friends.utils.mpi_utils.rank_print', 'rank_print', (['msg'], {}), '(msg)\n', (13306, 13311), False, 'from ppo_and_friends.utils.mpi_utils import rank_print\n'), ((15521, 15536), 'ppo_and_friends.utils.mpi_utils.rank_print', 'rank_print', (['msg'], {}), '(msg)\n', (15531, 15536), False, 'from ppo_and_friends.utils.mpi_utils import rank_print\n'), ((19793, 19841), 'torch.tensor', 'torch.tensor', (['self.advantages'], {'dtype': 'torch.float'}), '(self.advantages, dtype=torch.float)\n', (19805, 19841), False, 'import torch\n'), ((19899, 19949), 'torch.tensor', 'torch.tensor', (['self.observations'], {'dtype': 'torch.float'}), '(self.observations, dtype=torch.float)\n', (19911, 19949), False, 'import torch\n'), ((20012, 20067), 'torch.tensor', 'torch.tensor', (['self.next_observations'], {'dtype': 'torch.float'}), '(self.next_observations, dtype=torch.float)\n', (20024, 20067), False, 'import torch\n'), ((20580, 20627), 'torch.tensor', 'torch.tensor', (['self.log_probs'], {'dtype': 'torch.float'}), '(self.log_probs, dtype=torch.float)\n', (20592, 20627), False, 'import torch\n'), ((20686, 20737), 'torch.tensor', 'torch.tensor', (['self.rewards_to_go'], {'dtype': 'torch.float'}), '(self.rewards_to_go, dtype=torch.float)\n', (20698, 20737), False, 'import torch\n'), ((15238, 15269), 'numpy.zeros', 'np.zeros', (['self.total_timestates'], {}), '(self.total_timestates)\n', (15246, 15269), True, 'import numpy as np\n'), ((19535, 19566), 'numpy.zeros', 'np.zeros', (['self.total_timestates'], {}), '(self.total_timestates)\n', (19543, 19566), True, 'import numpy as np\n'), ((20393, 20450), 'torch.tensor', 'torch.tensor', (['self.global_observations'], {'dtype': 'torch.float'}), '(self.global_observations, dtype=torch.float)\n', (20405, 20450), False, 'import torch\n'), ((20840, 20885), 'torch.tensor', 'torch.tensor', (['self.actions'], {'dtype': 'torch.float'}), '(self.actions, dtype=torch.float)\n', (20852, 20885), False, 'import torch\n'), ((20950, 20999), 'torch.tensor', 'torch.tensor', (['self.raw_actions'], {'dtype': 'torch.float'}), '(self.raw_actions, dtype=torch.float)\n', (20962, 20999), False, 'import torch\n'), ((16841, 16871), 'numpy.zeros', 'np.zeros', (['self.sequence_length'], {}), '(self.sequence_length)\n', (16849, 16871), True, 'import numpy as np\n'), ((18778, 18819), 'numpy.concatenate', 'np.concatenate', (['self.actor_hidden'], {'axis': '(1)'}), '(self.actor_hidden, axis=1)\n', (18792, 18819), True, 'import numpy as np\n'), ((18901, 18943), 'numpy.concatenate', 'np.concatenate', (['self.critic_hidden'], {'axis': '(1)'}), '(self.critic_hidden, axis=1)\n', (18915, 18943), True, 'import numpy as np\n'), ((19022, 19061), 'numpy.concatenate', 'np.concatenate', (['self.actor_cell'], {'axis': '(1)'}), '(self.actor_cell, axis=1)\n', (19036, 19061), True, 'import numpy as np\n'), ((19141, 19181), 'numpy.concatenate', 'np.concatenate', (['self.critic_cell'], {'axis': '(1)'}), '(self.critic_cell, axis=1)\n', (19155, 19181), True, 'import numpy as np\n'), ((21106, 21150), 'torch.tensor', 'torch.tensor', (['self.actions'], {'dtype': 'torch.long'}), '(self.actions, dtype=torch.long)\n', (21118, 21150), False, 'import torch\n'), ((21214, 21262), 'torch.tensor', 'torch.tensor', (['self.raw_actions'], {'dtype': 'torch.long'}), '(self.raw_actions, dtype=torch.long)\n', (21226, 21262), False, 'import torch\n')] |
"""
author: <NAME>
"""
import numpy as np
import time
import copy
from numba import njit
from numba.typed import List
from gglasso.solver.ggl_helper import phiplus, prox_od_1norm, prox_2norm, prox_rank_norm
from gglasso.helper.ext_admm_helper import check_G
def ext_ADMM_MGL(S, lambda1, lambda2, reg , Omega_0, G,\
X0 = None, X1 = None, tol = 1e-5 , rtol = 1e-4, stopping_criterion = 'boyd',\
rho= 1., max_iter = 1000, verbose = False, measure = False, latent = False, mu1 = None):
"""
This is an ADMM algorithm for solving the Group Graphical Lasso problem
where not all instances have the same number of dimensions, i.e. some variables are present in some instances and not in others.
A group sparsity penalty is applied to all pairs of variables present in multiple instances.
IMPORTANT: As the arrays are non-conforming in dimensions here, we operate on dictionaries with keys 1,..,K (as int) and each value is a array of shape :math:`(p_k,p_k)`.
If ``latent=False``, this function solves
.. math::
\min_{\Omega,\Theta,\Lambda} \sum_{k=1}^K - \log \det(\Omega^{(k)}) + \mathrm{Tr}(S^{(k)}\Omega^{(k)}) + \sum_{k=1}^K \lambda_1 ||\Theta^{(k)}||_{1,od}
+ \sum_{l} \lambda_2 \\beta_l ||\Lambda_{[l]}||_2
s.t. \quad \Omega^{(k)} = \Theta^{(k)} \quad k=1,\dots,K
\quad \quad \Lambda^{(k)} = \Theta^{(k)} \quad k=1,\dots,K
where l indexes the groups of overlapping variables and :math:`\Lambda_{[l]}` is the array of all respective components.
To account for differing group sizes we multiply with :math:`\\beta_l`, the square root of the group size.
If ``latent=True``, this function solves
.. math::
\min_{\Omega,\Theta,\Lambda,L} \sum_{k=1}^K - \log \det(\Omega^{(k)}) + \mathrm{Tr}(S^{(k)}\Omega^{(k)}) + \sum_{k=1}^K \lambda_1 ||\Theta^{(k)}||_{1,od}
+ \sum_{l} \lambda_2 \\beta_l ||\Lambda_{[l]}||_2 +\sum_{k=1}^{K} \mu_{1,k} \|L^{(k)}\|_{\star}
s.t. \quad \Omega^{(k)} = \Theta^{(k)} - L^{(k)} \quad k=1,\dots,K
\quad \quad \Lambda^{(k)} = \Theta^{(k)} \quad k=1,\dots,K
Note:
* Typically, ``sol['Omega']`` is positive definite and ``sol['Theta']`` is sparse.
* We use scaled ADMM, i.e. X0 and X1 are the scaled (with 1/rho) dual variables for the equality constraints.
Parameters
----------
S : dict
empirical covariance matrices. S should have keys 1,..,K (as integers) and S[k] contains the :math:`(p_k,p_k)`-array of the empirical cov. matrix of the k-th instance.
Each S[k] needs to be symmetric and positive semidefinite.
lambda1 : float, positive
sparsity regularization parameter.
lambda2 : float, positive
group sparsity regularization parameter.
reg : str
so far only Group Graphical Lasso is available, hence choose 'GGL'.
Omega_0 : dict
starting point for the Omega variable. Should be of same form as S. If no better starting point is available, choose
Omega_0[k] = np.eye(p_k) for k=1,...,K
G : array
bookkeeping arrays which contains information where the respective entries for each group can be found.
X0 : dict, optional
starting point for the X0 variable. If not specified, it is set to zeros.
X1 : dict, optional
starting point for the X1 variable. If not specified, it is set to zeros.
rho : float, positive, optional
step size paramater for the augmented Lagrangian in ADMM. The default is 1. Tune this parameter for optimal performance.
max_iter : int, optional
maximum number of iterations. The default is 1000.
tol : float, positive, optional
tolerance for the primal residual. See "Distributed Optimization and Statistical Learning via the Alternating Direction Method of Multipliers", Boyd et al. for details.
The default is 1e-7.
rtol : float, positive, optional
tolerance for the dual residual. The default is 1e-4.
stopping_criterion : str, optional
* 'boyd': Stopping criterion after Boyd et al.
* 'kkt': KKT residual is chosen as stopping criterion. This is computationally expensive to compute.
The default is 'boyd'.
verbose : boolean, optional
verbosity of the solver. The default is False.
measure : boolean, optional
turn on/off measurements of runtime per iteration. The default is False.
latent : boolean, optional
Solve the GGL problem with or without latent variables (see above for the exact formulations).
The default is False.
mu1 : float, positive, optional
low-rank regularization parameter, possibly different for each instance k=1,..,K. Only needs to be specified if latent=True.
Returns
-------
sol : dict
contains the solution, i.e. Omega, Theta, X0, X1 (and L if latent=True) after termination. All elements are dictionaries with keys 1,..,K and (p_k,p_k)-arrays as values.
info : dict
status and measurement information from the solver.
"""
K = len(S.keys())
p = np.zeros(K, dtype= int)
for k in np.arange(K):
p[k] = S[k].shape[0]
if type(lambda1) == np.float64 or type(lambda1) == float:
lambda1 = lambda1*np.ones(K)
if latent:
if type(mu1) == np.float64 or type(mu1) == float:
mu1 = mu1*np.ones(K)
assert mu1 is not None
assert np.all(mu1 > 0)
assert min(lambda1.min(), lambda2) > 0
assert reg in ['GGL']
check_G(G, p)
assert rho > 0, "ADMM penalization parameter must be positive."
# initialize
Omega_t = Omega_0.copy()
Theta_t = Omega_0.copy()
L_t = dict()
for k in np.arange(K):
L_t[k] = np.zeros((p[k],p[k]))
# helper and dual variables
Lambda_t = Omega_0.copy()
Z_t = dict()
if X0 is None:
X0_t = dict()
for k in np.arange(K):
X0_t[k] = np.zeros((p[k],p[k]))
else:
X0_t = X0.copy()
if X1 is None:
X1_t = dict()
for k in np.arange(K):
X1_t[k] = np.zeros((p[k],p[k]))
else:
X1_t = X1.copy()
runtime = np.zeros(max_iter)
residual = np.zeros(max_iter)
status = ''
if verbose:
print("------------ADMM Algorithm for Multiple Graphical Lasso----------------")
if stopping_criterion == 'boyd':
hdr_fmt = "%4s\t%10s\t%10s\t%10s\t%10s"
out_fmt = "%4d\t%10.4g\t%10.4g\t%10.4g\t%10.4g"
print(hdr_fmt % ("iter", "r_t", "s_t", "eps_pri", "eps_dual"))
elif stopping_criterion == 'kkt':
hdr_fmt = "%4s\t%10s"
out_fmt = "%4d\t%10.4g"
print(hdr_fmt % ("iter", "kkt residual"))
##################################################################
### MAIN LOOP STARTS
##################################################################
for iter_t in np.arange(max_iter):
if measure:
start = time.time()
# Omega Update
Omega_t_1 = Omega_t.copy()
for k in np.arange(K):
W_t = Theta_t[k] - L_t[k] - X0_t[k] - (1/rho) * S[k]
eigD, eigQ = np.linalg.eigh(W_t)
Omega_t[k] = phiplus(beta = 1/rho, D = eigD, Q = eigQ)
# Theta Update
for k in np.arange(K):
V_t = (Omega_t[k] + L_t[k] + X0_t[k] + Lambda_t[k] - X1_t[k]) * 0.5
Theta_t[k] = prox_od_1norm(V_t, lambda1[k]/(2*rho))
#L Update
if latent:
for k in np.arange(K):
C_t = Theta_t[k] - X0_t[k] - Omega_t[k]
C_t = (C_t.T + C_t)/2
eigD, eigQ = np.linalg.eigh(C_t)
L_t[k] = prox_rank_norm(C_t, mu1[k]/rho, D = eigD, Q = eigQ)
# Lambda Update
Lambda_t_1 = Lambda_t.copy()
for k in np.arange(K):
Z_t[k] = Theta_t[k] + X1_t[k]
Lambda_t = prox_2norm_G(Z_t, G, lambda2/rho)
# X Update
for k in np.arange(K):
X0_t[k] += Omega_t[k] - Theta_t[k] + L_t[k]
X1_t[k] += Theta_t[k] - Lambda_t[k]
if measure:
end = time.time()
runtime[iter_t] = end-start
# Stopping condition
if stopping_criterion == 'boyd':
r_t,s_t,e_pri,e_dual = ADMM_stopping_criterion(Omega_t, Omega_t_1, Theta_t, L_t, Lambda_t, Lambda_t_1, X0_t, X1_t,\
S, rho, p, tol, rtol, latent)
residual[iter_t] = max(r_t,s_t)
if verbose:
print(out_fmt % (iter_t,r_t,s_t,e_pri,e_dual))
if (r_t <= e_pri) and (s_t <= e_dual):
status = 'optimal'
break
elif stopping_criterion == 'kkt':
eta_A = kkt_stopping_criterion(Omega_t, Theta_t, L_t, Lambda_t, dict((k, rho*v) for k,v in X0_t.items()), dict((k, rho*v) for k,v in X1_t.items()),\
S , G, lambda1, lambda2, reg, latent, mu1)
residual[iter_t] = eta_A
if verbose:
print(out_fmt % (iter_t,eta_A))
if eta_A <= tol:
status = 'optimal'
break
##################################################################
### MAIN LOOP FINISHED
##################################################################
# retrieve status (partially optimal or max iter)
if status != 'optimal':
if stopping_criterion == 'boyd':
if (r_t <= e_pri):
status = 'primal optimal'
elif (s_t <= e_dual):
status = 'dual optimal'
else:
status = 'max iterations reached'
else:
status = 'max iterations reached'
print(f"ADMM terminated after {iter_t+1} iterations with status: {status}.")
for k in np.arange(K):
assert abs(Omega_t[k].T - Omega_t[k]).max() <= 1e-5, "Solution is not symmetric"
assert abs(Theta_t[k].T - Theta_t[k]).max() <= 1e-5, "Solution is not symmetric"
assert abs(L_t[k].T - L_t[k]).max() <= 1e-5, "Solution is not symmetric"
D = np.linalg.eigvalsh(Theta_t[k]-L_t[k])
if D.min() <= 1e-5:
print("WARNING: Theta (Theta-L resp.) may be not positive definite -- increase accuracy!")
if latent:
D = np.linalg.eigvalsh(L_t[k])
if D.min() <= -1e-5:
print("WARNING: L may be not positive semidefinite -- increase accuracy!")
sol = {'Omega': Omega_t, 'Theta': Theta_t, 'L': L_t, 'X0': X0_t, 'X1': X1_t}
if measure:
info = {'status': status , 'runtime': runtime[:iter_t+1], 'residual': residual[:iter_t+1]}
else:
info = {'status': status}
return sol, info
def ADMM_stopping_criterion(Omega, Omega_t_1, Theta, L, Lambda, Lambda_t_1, X0, X1, S, rho, p, eps_abs, eps_rel, latent=False):
# X0, X1 are inputed as scaled dual vars., this is accounted for by factor rho in e_dual
K = len(S.keys())
if not latent:
for k in np.arange(K):
assert np.all(L[k]==0)
dim = ((p ** 2 + p) / 2).sum() # number of elements of off-diagonal matrix
D1 = np.sqrt(sum([np.linalg.norm(Omega[k])**2 + np.linalg.norm(Lambda[k])**2 for k in np.arange(K)] ))
D2 = np.sqrt(sum([np.linalg.norm(Theta[k] - L[k])**2 + np.linalg.norm(Theta[k])**2 for k in np.arange(K)] ))
D3 = np.sqrt(sum([np.linalg.norm(X0[k])**2 + np.linalg.norm(X1[k])**2 for k in np.arange(K)] ))
e_pri = dim * eps_abs + eps_rel * np.maximum(D1, D2)
e_dual = dim * eps_abs + eps_rel * rho * D3
r = np.sqrt(sum([np.linalg.norm(Omega[k] - Theta[k] + L[k])**2 + np.linalg.norm(Lambda[k] - Theta[k])**2 for k in np.arange(K)] ))
s = rho * np.sqrt(sum([np.linalg.norm(Omega[k] - Omega_t_1[k])**2 + np.linalg.norm(Lambda[k] - Lambda_t_1[k])**2 for k in np.arange(K)] ))
return r,s,e_pri,e_dual
def kkt_stopping_criterion(Omega, Theta, L, Lambda, X0, X1, S , G, lambda1, lambda2, reg, latent = False, mu1 = None):
# X0, X1 are inputed as UNscaled dual variables(!)
K = len(S.keys())
if not latent:
for k in np.arange(K):
assert np.all(L[k]==0)
term1 = np.zeros(K)
term2 = np.zeros(K)
term3 = np.zeros(K)
term4 = np.zeros(K)
term5 = np.zeros(K)
term6 = np.zeros(K)
V = dict()
for k in np.arange(K):
eigD, eigQ = np.linalg.eigh(Omega[k] - S[k] - X0[k])
proxk = phiplus(beta = 1, D = eigD, Q = eigQ)
# primal varibale optimality
term1[k] = np.linalg.norm(Omega[k] - proxk) / (1 + np.linalg.norm(Omega[k]))
term2[k] = np.linalg.norm(Theta[k] - prox_od_1norm(Theta[k] + X0[k] - X1[k] , lambda1[k])) / (1 + np.linalg.norm(Theta[k]))
if latent:
eigD, eigQ = np.linalg.eigh(L[k] - X0[k])
proxk = prox_rank_norm(L[k] - X0[k], beta = mu1[k], D = eigD, Q = eigQ)
term3[k] = np.linalg.norm(L[k] - proxk) / (1 + np.linalg.norm(L[k]))
V[k] = Lambda[k] + X1[k]
# equality constraints
term5[k] = np.linalg.norm(Omega[k] - Theta[k] + L[k]) / (1 + np.linalg.norm(Theta[k]))
term6[k] = np.linalg.norm(Lambda[k] - Theta[k]) / (1 + np.linalg.norm(Theta[k]))
V = prox_2norm_G(V, G, lambda2)
for k in np.arange(K):
term4[k] = np.linalg.norm(V[k] - Lambda[k]) / (1 + np.linalg.norm(Lambda[k]))
res = max(np.linalg.norm(term1), np.linalg.norm(term2), np.linalg.norm(term3), np.linalg.norm(term4), np.linalg.norm(term5), np.linalg.norm(term6) )
return res
def prox_2norm_G(X, G, l2):
"""
calculates the proximal operator at points X for the group penalty induced by G
G: 2xLxK matrix where the -th row contains the (i,j)-index of the element in Theta^k which contains to group l
if G has a entry -1 no element is contained in the group for this Theta^k
X: dictionary with X^k at key k, each X[k] is assumed to be symmetric
"""
assert l2 > 0
K = len(X.keys())
for k in np.arange(K):
assert abs(X[k] - X[k].T).max() <= 1e-5, "X[k] has to be symmetric"
d = G.shape
assert d[0] == 2
assert d[2] == K
group_size = (G[0,:,:] != -1).sum(axis = 1)
tmpX = List()
for k in np.arange(K):
tmpX.append(X[k].copy())
X1 = prox_G_inner(G, tmpX, l2, group_size)
X1 = dict(zip(np.arange(K), X1))
return X1
@njit
def prox_G_inner(G, X, l2, group_size):
L = G.shape[1]
K = G.shape[2]
for l in np.arange(L):
# for each group construct v, calculate prox, and insert the result. Ignore -1 entries of G
v0 = np.zeros(K)
for k in np.arange(K):
if G[0,l,k] == -1:
v0[k] = np.nan
else:
v0[k] = X[k][G[0,l,k], G[1,l,k]]
v = v0[~np.isnan(v0)]
# scale with square root of the group size
lam = l2 * np.sqrt(group_size[l])
a = max(np.sqrt((v**2).sum()), lam)
z0 = v * (a - lam) / a
v0[~np.isnan(v0)] = z0
for k in np.arange(K):
if G[0,l,k] == -1:
continue
else:
X[k][G[0,l,k], G[1,l,k]] = v0[k]
# lower triangular
X[k][G[1,l,k], G[0,l,k]] = v0[k]
return X
#%%
# prox operato in case numba version does not work
# def prox_2norm_G(X, G, l2):
# """
# calculates the proximal operator at points X for the group penalty induced by G
# G: 2xLxK matrix where the -th row contains the (i,j)-index of the element in Theta^k which contains to group l
# if G has a entry -1 no element is contained in the group for this Theta^k
# X: dictionary with X^k at key k, each X[k] is assumed to be symmetric
# """
# assert l2 > 0
# K = len(X.keys())
# for k in np.arange(K):
# assert abs(X[k] - X[k].T).max() <= 1e-5, "X[k] has to be symmetric"
# d = G.shape
# assert d[0] == 2
# assert d[2] == K
# L = d[1]
# X1 = copy.deepcopy(X)
# group_size = (G[0,:,:] != -1).sum(axis = 1)
# for l in np.arange(L):
# # for each group construct v, calculate prox, and insert the result. Ignore -1 entries of G
# v0 = np.zeros(K)
# for k in np.arange(K):
# if G[0,l,k] == -1:
# v0[k] = np.nan
# else:
# v0[k] = X[k][G[0,l,k], G[1,l,k]]
# v = v0[~np.isnan(v0)]
# # scale with square root of the group size
# z0 = prox_2norm(v,l2 * np.sqrt(group_size[l]))
# v0[~np.isnan(v0)] = z0
# for k in np.arange(K):
# if G[0,l,k] == -1:
# continue
# else:
# X1[k][G[0,l,k], G[1,l,k]] = v0[k]
# # lower triangular
# X1[k][G[1,l,k], G[0,l,k]] = v0[k]
# return X1 | [
"numpy.sqrt",
"numpy.ones",
"numpy.maximum",
"gglasso.solver.ggl_helper.phiplus",
"numba.typed.List",
"gglasso.helper.ext_admm_helper.check_G",
"gglasso.solver.ggl_helper.prox_od_1norm",
"gglasso.solver.ggl_helper.prox_rank_norm",
"numpy.linalg.eigvalsh",
"numpy.zeros",
"numpy.isnan",
"numpy.l... | [((5244, 5266), 'numpy.zeros', 'np.zeros', (['K'], {'dtype': 'int'}), '(K, dtype=int)\n', (5252, 5266), True, 'import numpy as np\n'), ((5281, 5293), 'numpy.arange', 'np.arange', (['K'], {}), '(K)\n', (5290, 5293), True, 'import numpy as np\n'), ((5700, 5713), 'gglasso.helper.ext_admm_helper.check_G', 'check_G', (['G', 'p'], {}), '(G, p)\n', (5707, 5713), False, 'from gglasso.helper.ext_admm_helper import check_G\n'), ((5912, 5924), 'numpy.arange', 'np.arange', (['K'], {}), '(K)\n', (5921, 5924), True, 'import numpy as np\n'), ((6392, 6410), 'numpy.zeros', 'np.zeros', (['max_iter'], {}), '(max_iter)\n', (6400, 6410), True, 'import numpy as np\n'), ((6426, 6444), 'numpy.zeros', 'np.zeros', (['max_iter'], {}), '(max_iter)\n', (6434, 6444), True, 'import numpy as np\n'), ((7164, 7183), 'numpy.arange', 'np.arange', (['max_iter'], {}), '(max_iter)\n', (7173, 7183), True, 'import numpy as np\n'), ((10310, 10322), 'numpy.arange', 'np.arange', (['K'], {}), '(K)\n', (10319, 10322), True, 'import numpy as np\n'), ((12745, 12756), 'numpy.zeros', 'np.zeros', (['K'], {}), '(K)\n', (12753, 12756), True, 'import numpy as np\n'), ((12769, 12780), 'numpy.zeros', 'np.zeros', (['K'], {}), '(K)\n', (12777, 12780), True, 'import numpy as np\n'), ((12793, 12804), 'numpy.zeros', 'np.zeros', (['K'], {}), '(K)\n', (12801, 12804), True, 'import numpy as np\n'), ((12817, 12828), 'numpy.zeros', 'np.zeros', (['K'], {}), '(K)\n', (12825, 12828), True, 'import numpy as np\n'), ((12841, 12852), 'numpy.zeros', 'np.zeros', (['K'], {}), '(K)\n', (12849, 12852), True, 'import numpy as np\n'), ((12865, 12876), 'numpy.zeros', 'np.zeros', (['K'], {}), '(K)\n', (12873, 12876), True, 'import numpy as np\n'), ((12910, 12922), 'numpy.arange', 'np.arange', (['K'], {}), '(K)\n', (12919, 12922), True, 'import numpy as np\n'), ((13865, 13877), 'numpy.arange', 'np.arange', (['K'], {}), '(K)\n', (13874, 13877), True, 'import numpy as np\n'), ((14591, 14603), 'numpy.arange', 'np.arange', (['K'], {}), '(K)\n', (14600, 14603), True, 'import numpy as np\n'), ((14813, 14819), 'numba.typed.List', 'List', ([], {}), '()\n', (14817, 14819), False, 'from numba.typed import List\n'), ((14833, 14845), 'numpy.arange', 'np.arange', (['K'], {}), '(K)\n', (14842, 14845), True, 'import numpy as np\n'), ((15112, 15124), 'numpy.arange', 'np.arange', (['L'], {}), '(L)\n', (15121, 15124), True, 'import numpy as np\n'), ((5598, 5613), 'numpy.all', 'np.all', (['(mu1 > 0)'], {}), '(mu1 > 0)\n', (5604, 5613), True, 'import numpy as np\n'), ((5943, 5965), 'numpy.zeros', 'np.zeros', (['(p[k], p[k])'], {}), '((p[k], p[k]))\n', (5951, 5965), True, 'import numpy as np\n'), ((6108, 6120), 'numpy.arange', 'np.arange', (['K'], {}), '(K)\n', (6117, 6120), True, 'import numpy as np\n'), ((6273, 6285), 'numpy.arange', 'np.arange', (['K'], {}), '(K)\n', (6282, 6285), True, 'import numpy as np\n'), ((7323, 7335), 'numpy.arange', 'np.arange', (['K'], {}), '(K)\n', (7332, 7335), True, 'import numpy as np\n'), ((7563, 7575), 'numpy.arange', 'np.arange', (['K'], {}), '(K)\n', (7572, 7575), True, 'import numpy as np\n'), ((8110, 8122), 'numpy.arange', 'np.arange', (['K'], {}), '(K)\n', (8119, 8122), True, 'import numpy as np\n'), ((8278, 8290), 'numpy.arange', 'np.arange', (['K'], {}), '(K)\n', (8287, 8290), True, 'import numpy as np\n'), ((10604, 10643), 'numpy.linalg.eigvalsh', 'np.linalg.eigvalsh', (['(Theta_t[k] - L_t[k])'], {}), '(Theta_t[k] - L_t[k])\n', (10622, 10643), True, 'import numpy as np\n'), ((11554, 11566), 'numpy.arange', 'np.arange', (['K'], {}), '(K)\n', (11563, 11566), True, 'import numpy as np\n'), ((12675, 12687), 'numpy.arange', 'np.arange', (['K'], {}), '(K)\n', (12684, 12687), True, 'import numpy as np\n'), ((12945, 12984), 'numpy.linalg.eigh', 'np.linalg.eigh', (['(Omega[k] - S[k] - X0[k])'], {}), '(Omega[k] - S[k] - X0[k])\n', (12959, 12984), True, 'import numpy as np\n'), ((13001, 13032), 'gglasso.solver.ggl_helper.phiplus', 'phiplus', ([], {'beta': '(1)', 'D': 'eigD', 'Q': 'eigQ'}), '(beta=1, D=eigD, Q=eigQ)\n', (13008, 13032), False, 'from gglasso.solver.ggl_helper import phiplus, prox_od_1norm, prox_2norm, prox_rank_norm\n'), ((13984, 14005), 'numpy.linalg.norm', 'np.linalg.norm', (['term1'], {}), '(term1)\n', (13998, 14005), True, 'import numpy as np\n'), ((14007, 14028), 'numpy.linalg.norm', 'np.linalg.norm', (['term2'], {}), '(term2)\n', (14021, 14028), True, 'import numpy as np\n'), ((14030, 14051), 'numpy.linalg.norm', 'np.linalg.norm', (['term3'], {}), '(term3)\n', (14044, 14051), True, 'import numpy as np\n'), ((14053, 14074), 'numpy.linalg.norm', 'np.linalg.norm', (['term4'], {}), '(term4)\n', (14067, 14074), True, 'import numpy as np\n'), ((14076, 14097), 'numpy.linalg.norm', 'np.linalg.norm', (['term5'], {}), '(term5)\n', (14090, 14097), True, 'import numpy as np\n'), ((14099, 14120), 'numpy.linalg.norm', 'np.linalg.norm', (['term6'], {}), '(term6)\n', (14113, 14120), True, 'import numpy as np\n'), ((15252, 15263), 'numpy.zeros', 'np.zeros', (['K'], {}), '(K)\n', (15260, 15263), True, 'import numpy as np\n'), ((15290, 15302), 'numpy.arange', 'np.arange', (['K'], {}), '(K)\n', (15299, 15302), True, 'import numpy as np\n'), ((15711, 15723), 'numpy.arange', 'np.arange', (['K'], {}), '(K)\n', (15720, 15723), True, 'import numpy as np\n'), ((5421, 5431), 'numpy.ones', 'np.ones', (['K'], {}), '(K)\n', (5428, 5431), True, 'import numpy as np\n'), ((6144, 6166), 'numpy.zeros', 'np.zeros', (['(p[k], p[k])'], {}), '((p[k], p[k]))\n', (6152, 6166), True, 'import numpy as np\n'), ((6309, 6331), 'numpy.zeros', 'np.zeros', (['(p[k], p[k])'], {}), '((p[k], p[k]))\n', (6317, 6331), True, 'import numpy as np\n'), ((7234, 7245), 'time.time', 'time.time', ([], {}), '()\n', (7243, 7245), False, 'import time\n'), ((7427, 7446), 'numpy.linalg.eigh', 'np.linalg.eigh', (['W_t'], {}), '(W_t)\n', (7441, 7446), True, 'import numpy as np\n'), ((7472, 7509), 'gglasso.solver.ggl_helper.phiplus', 'phiplus', ([], {'beta': '(1 / rho)', 'D': 'eigD', 'Q': 'eigQ'}), '(beta=1 / rho, D=eigD, Q=eigQ)\n', (7479, 7509), False, 'from gglasso.solver.ggl_helper import phiplus, prox_od_1norm, prox_2norm, prox_rank_norm\n'), ((7683, 7725), 'gglasso.solver.ggl_helper.prox_od_1norm', 'prox_od_1norm', (['V_t', '(lambda1[k] / (2 * rho))'], {}), '(V_t, lambda1[k] / (2 * rho))\n', (7696, 7725), False, 'from gglasso.solver.ggl_helper import phiplus, prox_od_1norm, prox_2norm, prox_rank_norm\n'), ((7789, 7801), 'numpy.arange', 'np.arange', (['K'], {}), '(K)\n', (7798, 7801), True, 'import numpy as np\n'), ((8445, 8456), 'time.time', 'time.time', ([], {}), '()\n', (8454, 8456), False, 'import time\n'), ((10830, 10856), 'numpy.linalg.eigvalsh', 'np.linalg.eigvalsh', (['L_t[k]'], {}), '(L_t[k])\n', (10848, 10856), True, 'import numpy as np\n'), ((11587, 11604), 'numpy.all', 'np.all', (['(L[k] == 0)'], {}), '(L[k] == 0)\n', (11593, 11604), True, 'import numpy as np\n'), ((12053, 12071), 'numpy.maximum', 'np.maximum', (['D1', 'D2'], {}), '(D1, D2)\n', (12063, 12071), True, 'import numpy as np\n'), ((12708, 12725), 'numpy.all', 'np.all', (['(L[k] == 0)'], {}), '(L[k] == 0)\n', (12714, 12725), True, 'import numpy as np\n'), ((13095, 13127), 'numpy.linalg.norm', 'np.linalg.norm', (['(Omega[k] - proxk)'], {}), '(Omega[k] - proxk)\n', (13109, 13127), True, 'import numpy as np\n'), ((13346, 13374), 'numpy.linalg.eigh', 'np.linalg.eigh', (['(L[k] - X0[k])'], {}), '(L[k] - X0[k])\n', (13360, 13374), True, 'import numpy as np\n'), ((13395, 13452), 'gglasso.solver.ggl_helper.prox_rank_norm', 'prox_rank_norm', (['(L[k] - X0[k])'], {'beta': 'mu1[k]', 'D': 'eigD', 'Q': 'eigQ'}), '(L[k] - X0[k], beta=mu1[k], D=eigD, Q=eigQ)\n', (13409, 13452), False, 'from gglasso.solver.ggl_helper import phiplus, prox_od_1norm, prox_2norm, prox_rank_norm\n'), ((13641, 13683), 'numpy.linalg.norm', 'np.linalg.norm', (['(Omega[k] - Theta[k] + L[k])'], {}), '(Omega[k] - Theta[k] + L[k])\n', (13655, 13683), True, 'import numpy as np\n'), ((13736, 13772), 'numpy.linalg.norm', 'np.linalg.norm', (['(Lambda[k] - Theta[k])'], {}), '(Lambda[k] - Theta[k])\n', (13750, 13772), True, 'import numpy as np\n'), ((13898, 13930), 'numpy.linalg.norm', 'np.linalg.norm', (['(V[k] - Lambda[k])'], {}), '(V[k] - Lambda[k])\n', (13912, 13930), True, 'import numpy as np\n'), ((14971, 14983), 'numpy.arange', 'np.arange', (['K'], {}), '(K)\n', (14980, 14983), True, 'import numpy as np\n'), ((15551, 15573), 'numpy.sqrt', 'np.sqrt', (['group_size[l]'], {}), '(group_size[l])\n', (15558, 15573), True, 'import numpy as np\n'), ((5528, 5538), 'numpy.ones', 'np.ones', (['K'], {}), '(K)\n', (5535, 5538), True, 'import numpy as np\n'), ((7926, 7945), 'numpy.linalg.eigh', 'np.linalg.eigh', (['C_t'], {}), '(C_t)\n', (7940, 7945), True, 'import numpy as np\n'), ((7971, 8020), 'gglasso.solver.ggl_helper.prox_rank_norm', 'prox_rank_norm', (['C_t', '(mu1[k] / rho)'], {'D': 'eigD', 'Q': 'eigQ'}), '(C_t, mu1[k] / rho, D=eigD, Q=eigQ)\n', (7985, 8020), False, 'from gglasso.solver.ggl_helper import phiplus, prox_od_1norm, prox_2norm, prox_rank_norm\n'), ((13135, 13159), 'numpy.linalg.norm', 'np.linalg.norm', (['Omega[k]'], {}), '(Omega[k])\n', (13149, 13159), True, 'import numpy as np\n'), ((13267, 13291), 'numpy.linalg.norm', 'np.linalg.norm', (['Theta[k]'], {}), '(Theta[k])\n', (13281, 13291), True, 'import numpy as np\n'), ((13482, 13510), 'numpy.linalg.norm', 'np.linalg.norm', (['(L[k] - proxk)'], {}), '(L[k] - proxk)\n', (13496, 13510), True, 'import numpy as np\n'), ((13691, 13715), 'numpy.linalg.norm', 'np.linalg.norm', (['Theta[k]'], {}), '(Theta[k])\n', (13705, 13715), True, 'import numpy as np\n'), ((13780, 13804), 'numpy.linalg.norm', 'np.linalg.norm', (['Theta[k]'], {}), '(Theta[k])\n', (13794, 13804), True, 'import numpy as np\n'), ((13938, 13963), 'numpy.linalg.norm', 'np.linalg.norm', (['Lambda[k]'], {}), '(Lambda[k])\n', (13952, 13963), True, 'import numpy as np\n'), ((15467, 15479), 'numpy.isnan', 'np.isnan', (['v0'], {}), '(v0)\n', (15475, 15479), True, 'import numpy as np\n'), ((15666, 15678), 'numpy.isnan', 'np.isnan', (['v0'], {}), '(v0)\n', (15674, 15678), True, 'import numpy as np\n'), ((11780, 11792), 'numpy.arange', 'np.arange', (['K'], {}), '(K)\n', (11789, 11792), True, 'import numpy as np\n'), ((11893, 11905), 'numpy.arange', 'np.arange', (['K'], {}), '(K)\n', (11902, 11905), True, 'import numpy as np\n'), ((11993, 12005), 'numpy.arange', 'np.arange', (['K'], {}), '(K)\n', (12002, 12005), True, 'import numpy as np\n'), ((12248, 12260), 'numpy.arange', 'np.arange', (['K'], {}), '(K)\n', (12257, 12260), True, 'import numpy as np\n'), ((13206, 13257), 'gglasso.solver.ggl_helper.prox_od_1norm', 'prox_od_1norm', (['(Theta[k] + X0[k] - X1[k])', 'lambda1[k]'], {}), '(Theta[k] + X0[k] - X1[k], lambda1[k])\n', (13219, 13257), False, 'from gglasso.solver.ggl_helper import phiplus, prox_od_1norm, prox_2norm, prox_rank_norm\n'), ((13518, 13538), 'numpy.linalg.norm', 'np.linalg.norm', (['L[k]'], {}), '(L[k])\n', (13532, 13538), True, 'import numpy as np\n'), ((11712, 11736), 'numpy.linalg.norm', 'np.linalg.norm', (['Omega[k]'], {}), '(Omega[k])\n', (11726, 11736), True, 'import numpy as np\n'), ((11742, 11767), 'numpy.linalg.norm', 'np.linalg.norm', (['Lambda[k]'], {}), '(Lambda[k])\n', (11756, 11767), True, 'import numpy as np\n'), ((11819, 11850), 'numpy.linalg.norm', 'np.linalg.norm', (['(Theta[k] - L[k])'], {}), '(Theta[k] - L[k])\n', (11833, 11850), True, 'import numpy as np\n'), ((11856, 11880), 'numpy.linalg.norm', 'np.linalg.norm', (['Theta[k]'], {}), '(Theta[k])\n', (11870, 11880), True, 'import numpy as np\n'), ((11932, 11953), 'numpy.linalg.norm', 'np.linalg.norm', (['X0[k]'], {}), '(X0[k])\n', (11946, 11953), True, 'import numpy as np\n'), ((11959, 11980), 'numpy.linalg.norm', 'np.linalg.norm', (['X1[k]'], {}), '(X1[k])\n', (11973, 11980), True, 'import numpy as np\n'), ((12151, 12193), 'numpy.linalg.norm', 'np.linalg.norm', (['(Omega[k] - Theta[k] + L[k])'], {}), '(Omega[k] - Theta[k] + L[k])\n', (12165, 12193), True, 'import numpy as np\n'), ((12199, 12235), 'numpy.linalg.norm', 'np.linalg.norm', (['(Lambda[k] - Theta[k])'], {}), '(Lambda[k] - Theta[k])\n', (12213, 12235), True, 'import numpy as np\n'), ((12391, 12403), 'numpy.arange', 'np.arange', (['K'], {}), '(K)\n', (12400, 12403), True, 'import numpy as np\n'), ((12292, 12331), 'numpy.linalg.norm', 'np.linalg.norm', (['(Omega[k] - Omega_t_1[k])'], {}), '(Omega[k] - Omega_t_1[k])\n', (12306, 12331), True, 'import numpy as np\n'), ((12337, 12378), 'numpy.linalg.norm', 'np.linalg.norm', (['(Lambda[k] - Lambda_t_1[k])'], {}), '(Lambda[k] - Lambda_t_1[k])\n', (12351, 12378), True, 'import numpy as np\n')] |
from collections import namedtuple
import cv2
import matplotlib.pylab as plt
import numpy as np
import pandas as pd
import random
from os.path import join
from prettyparse import Usage
from torch.utils.data.dataset import Dataset as TorchDataset
from autodo.dataset import Dataset
k = np.array([[2304.5479, 0, 1686.2379],
[0, 2305.8757, 1354.9849],
[0, 0, 1]], dtype=np.float32)
IMG_WIDTH = 448
IMG_HEIGHT = 128
StageThreeLabel = namedtuple('StageThreeLabel', 'x y z')
def _load_centers(df, image_id):
return df[df['image_id'] == image_id][['center_x', 'center_y']].values.T
class StageThreeDataset(TorchDataset):
usage = Usage('''
:stage_two_csv str
Csv of stage two output
:dataset_folder str
Folder to load images from
''')
@classmethod
def from_args(cls, args, train=True):
return cls(Dataset.from_folder(args.dataset_folder), args.stage_two_csv, train)
def __init__(self, auto_dataset: Dataset, stage_two_csv, train=True):
super().__init__()
self.auto_dataset = auto_dataset
self.df = pd.read_csv(stage_two_csv)
self.datas = list(self.df.index)
random.seed(1234)
random.shuffle(self.datas)
cutoff = int(len(self.datas) * 0.7)
if train:
self.datas = self.datas[:cutoff]
else:
self.datas = self.datas[cutoff:]
def __len__(self):
return len(self.datas)
def __getitem__(self, idx):
row = self.df.iloc[self.datas[idx]]
image_id = row['image_id']
xcenters, ycenters = _load_centers(self.df, image_id)
input_tensor = self.make_input(join(self.auto_dataset.images_folder[0], image_id + '.jpg'), xcenters, ycenters)
output, out_mask = self.make_target(image_id)
return input_tensor, output, out_mask
@staticmethod
def make_input(filename, xcenters, ycenters, shape_x=IMG_WIDTH, shape_y=IMG_HEIGHT, cutoff_y=1600):
width = 3384
height = 2710
padding_x = width // 6
img = np.zeros((height, width + padding_x * 2, 3), dtype='float32')
img[:, padding_x:-padding_x, :] = plt.imread(filename).astype('float32') / 255
mask = np.zeros((img.shape[0], img.shape[1], 1), dtype='float32')
output = np.zeros((img.shape[0], img.shape[1], 3), dtype='float32')
input_tensor = np.concatenate([img, mask], axis=2)
input_tensor, output = input_tensor[cutoff_y:], output[cutoff_y:]
input_tensor = cv2.resize(input_tensor, (shape_x, shape_y))
for xcenter, ycenter in zip(xcenters, ycenters):
xcenter = xcenter * width
ycenter = ycenter * height
if xcenter < -padding_x or xcenter > width + padding_x or ycenter < 0 or ycenter > height:
# print('fuck') # if result is too ridiculous
continue
xcenter = (xcenter + padding_x) / (width + padding_x * 2) * shape_x
ycenter = (ycenter - cutoff_y) / (height - cutoff_y) * shape_y
input_tensor[int(ycenter), int(xcenter), 3] = 1
return input_tensor.astype('float32').transpose((2, 0, 1))
def make_target(self, image_id, shape_y=IMG_HEIGHT, shape_x=IMG_WIDTH, cutoff_y=1600):
width = 3384
height = 2710
padding_x = width // 6
img = np.zeros((height, width + padding_x * 2, 3), dtype='float32')
filename = join(self.auto_dataset.images_folder[0], image_id + '.jpg')
img[:, padding_x:-padding_x, :] = plt.imread(filename).astype('float32') / 255
mask = np.zeros((img.shape[0], img.shape[1], 1), dtype='float32')
output = np.zeros((img.shape[0], img.shape[1], 3), dtype='float32')
df = self.df[self.df['image_id'] == image_id]
xcenters, ycenters = df[['center_x', 'center_y']].values.T
labels = self.auto_dataset.labels_s[image_id]
xs, ys, zs = np.array([
[label.x, label.y, label.z]
for label in labels
]).T
output = output[cutoff_y:]
target = cv2.resize(output, (shape_x, shape_y))
input_tensor = np.concatenate([img, mask], axis=2)
input_tensor = input_tensor[cutoff_y:]
input_tensor = cv2.resize(input_tensor, (shape_x, shape_y))
out_mask = cv2.resize(input_tensor[:, :, 3], (shape_x, shape_y))[:, :, np.newaxis]
for xcenter, ycenter, x, y, z in zip(xcenters, ycenters, xs, ys, zs):
if xcenter < -padding_x or xcenter > width + padding_x or ycenter < 0 or ycenter > height:
# print('fuck') # if result is too ridiculous
continue
xcenter = (xcenter + padding_x) / (width + padding_x * 2) * shape_x
ycenter = (ycenter - cutoff_y) / (height - cutoff_y) * shape_y
target[int(ycenter), int(xcenter)] = np.array([x, y, z]) / 100
out_mask[int(ycenter), int(xcenter)] = 1
return target.astype('float32').transpose((2, 0, 1)), out_mask.astype('float32').transpose((2, 0, 1))
@staticmethod
def decode_output(network_output, xcenters, ycenters):
print(network_output.shape)
return [
StageThreeLabel(*map(float, network_output.cpu().detach().numpy().transpose((1, 2, 0))[int(xcenter), int(ycenter)] * 100))
for xcenter, ycenter in zip(xcenters, ycenters)
]
| [
"matplotlib.pylab.imread",
"collections.namedtuple",
"random.shuffle",
"pandas.read_csv",
"os.path.join",
"random.seed",
"numpy.array",
"numpy.zeros",
"numpy.concatenate",
"autodo.dataset.Dataset.from_folder",
"prettyparse.Usage",
"cv2.resize"
] | [((288, 385), 'numpy.array', 'np.array', (['[[2304.5479, 0, 1686.2379], [0, 2305.8757, 1354.9849], [0, 0, 1]]'], {'dtype': 'np.float32'}), '([[2304.5479, 0, 1686.2379], [0, 2305.8757, 1354.9849], [0, 0, 1]],\n dtype=np.float32)\n', (296, 385), True, 'import numpy as np\n'), ((462, 500), 'collections.namedtuple', 'namedtuple', (['"""StageThreeLabel"""', '"""x y z"""'], {}), "('StageThreeLabel', 'x y z')\n", (472, 500), False, 'from collections import namedtuple\n'), ((666, 825), 'prettyparse.Usage', 'Usage', (['"""\n :stage_two_csv str\n Csv of stage two output\n\n :dataset_folder str\n Folder to load images from\n """'], {}), '(\n """\n :stage_two_csv str\n Csv of stage two output\n\n :dataset_folder str\n Folder to load images from\n """\n )\n', (671, 825), False, 'from prettyparse import Usage\n'), ((1125, 1151), 'pandas.read_csv', 'pd.read_csv', (['stage_two_csv'], {}), '(stage_two_csv)\n', (1136, 1151), True, 'import pandas as pd\n'), ((1201, 1218), 'random.seed', 'random.seed', (['(1234)'], {}), '(1234)\n', (1212, 1218), False, 'import random\n'), ((1227, 1253), 'random.shuffle', 'random.shuffle', (['self.datas'], {}), '(self.datas)\n', (1241, 1253), False, 'import random\n'), ((2080, 2141), 'numpy.zeros', 'np.zeros', (['(height, width + padding_x * 2, 3)'], {'dtype': '"""float32"""'}), "((height, width + padding_x * 2, 3), dtype='float32')\n", (2088, 2141), True, 'import numpy as np\n'), ((2244, 2302), 'numpy.zeros', 'np.zeros', (['(img.shape[0], img.shape[1], 1)'], {'dtype': '"""float32"""'}), "((img.shape[0], img.shape[1], 1), dtype='float32')\n", (2252, 2302), True, 'import numpy as np\n'), ((2320, 2378), 'numpy.zeros', 'np.zeros', (['(img.shape[0], img.shape[1], 3)'], {'dtype': '"""float32"""'}), "((img.shape[0], img.shape[1], 3), dtype='float32')\n", (2328, 2378), True, 'import numpy as np\n'), ((2402, 2437), 'numpy.concatenate', 'np.concatenate', (['[img, mask]'], {'axis': '(2)'}), '([img, mask], axis=2)\n', (2416, 2437), True, 'import numpy as np\n'), ((2535, 2579), 'cv2.resize', 'cv2.resize', (['input_tensor', '(shape_x, shape_y)'], {}), '(input_tensor, (shape_x, shape_y))\n', (2545, 2579), False, 'import cv2\n'), ((3367, 3428), 'numpy.zeros', 'np.zeros', (['(height, width + padding_x * 2, 3)'], {'dtype': '"""float32"""'}), "((height, width + padding_x * 2, 3), dtype='float32')\n", (3375, 3428), True, 'import numpy as np\n'), ((3448, 3507), 'os.path.join', 'join', (['self.auto_dataset.images_folder[0]', "(image_id + '.jpg')"], {}), "(self.auto_dataset.images_folder[0], image_id + '.jpg')\n", (3452, 3507), False, 'from os.path import join\n'), ((3610, 3668), 'numpy.zeros', 'np.zeros', (['(img.shape[0], img.shape[1], 1)'], {'dtype': '"""float32"""'}), "((img.shape[0], img.shape[1], 1), dtype='float32')\n", (3618, 3668), True, 'import numpy as np\n'), ((3686, 3744), 'numpy.zeros', 'np.zeros', (['(img.shape[0], img.shape[1], 3)'], {'dtype': '"""float32"""'}), "((img.shape[0], img.shape[1], 3), dtype='float32')\n", (3694, 3744), True, 'import numpy as np\n'), ((4091, 4129), 'cv2.resize', 'cv2.resize', (['output', '(shape_x, shape_y)'], {}), '(output, (shape_x, shape_y))\n', (4101, 4129), False, 'import cv2\n'), ((4154, 4189), 'numpy.concatenate', 'np.concatenate', (['[img, mask]'], {'axis': '(2)'}), '([img, mask], axis=2)\n', (4168, 4189), True, 'import numpy as np\n'), ((4260, 4304), 'cv2.resize', 'cv2.resize', (['input_tensor', '(shape_x, shape_y)'], {}), '(input_tensor, (shape_x, shape_y))\n', (4270, 4304), False, 'import cv2\n'), ((895, 935), 'autodo.dataset.Dataset.from_folder', 'Dataset.from_folder', (['args.dataset_folder'], {}), '(args.dataset_folder)\n', (914, 935), False, 'from autodo.dataset import Dataset\n'), ((1688, 1747), 'os.path.join', 'join', (['self.auto_dataset.images_folder[0]', "(image_id + '.jpg')"], {}), "(self.auto_dataset.images_folder[0], image_id + '.jpg')\n", (1692, 1747), False, 'from os.path import join\n'), ((3942, 4001), 'numpy.array', 'np.array', (['[[label.x, label.y, label.z] for label in labels]'], {}), '([[label.x, label.y, label.z] for label in labels])\n', (3950, 4001), True, 'import numpy as np\n'), ((4325, 4378), 'cv2.resize', 'cv2.resize', (['input_tensor[:, :, 3]', '(shape_x, shape_y)'], {}), '(input_tensor[:, :, 3], (shape_x, shape_y))\n', (4335, 4378), False, 'import cv2\n'), ((4870, 4889), 'numpy.array', 'np.array', (['[x, y, z]'], {}), '([x, y, z])\n', (4878, 4889), True, 'import numpy as np\n'), ((2184, 2204), 'matplotlib.pylab.imread', 'plt.imread', (['filename'], {}), '(filename)\n', (2194, 2204), True, 'import matplotlib.pylab as plt\n'), ((3550, 3570), 'matplotlib.pylab.imread', 'plt.imread', (['filename'], {}), '(filename)\n', (3560, 3570), True, 'import matplotlib.pylab as plt\n')] |
import numpy as np
import torch
import torch.nn.functional as F
from maskrcnn_benchmark.modeling.utils import cat
from maskrcnn_benchmark.structures.bounding_box import BoxList
from siammot.utils import registry
from .feature_extractor import EMMFeatureExtractor, EMMPredictor
from .track_loss import EMMLossComputation
from .xcorr import xcorr_depthwise
@registry.SIAMESE_TRACKER.register("EMM")
class EMM(torch.nn.Module):
def __init__(self, cfg, track_utils):
super(EMM, self).__init__()
self.feature_extractor = EMMFeatureExtractor(cfg)
self.predictor = EMMPredictor(cfg)
self.loss = EMMLossComputation(cfg)
self.track_utils = track_utils
self.amodal = cfg.INPUT.AMODAL
self.use_centerness = cfg.MODEL.TRACK_HEAD.EMM.USE_CENTERNESS
self.pad_pixels = cfg.MODEL.TRACK_HEAD.PAD_PIXELS
self.sigma = cfg.MODEL.TRACK_HEAD.EMM.COSINE_WINDOW_WEIGHT
def forward(
self, features, boxes, sr, targets=None, template_features=None
):
"""
forward functions of the tracker
:param features: raw FPN feature maps from feature backbone
:param boxes: template bounding boxes
:param sr: search region bounding boxes
:param targets:
:param template_features: features of the template bounding boxes
the number of track boxes should be the same as that of
search region and template_features
"""
# x, y shifting due to feature padding
shift_x = self.pad_pixels
shift_y = self.pad_pixels
if self.training:
template_features = self.feature_extractor(features, boxes)
features = self.track_utils.shuffle_feature(features)
features = self.track_utils.pad_feature(features)
sr_features = self.feature_extractor(features, boxes, sr)
response_map = xcorr_depthwise(sr_features, template_features)
cls_logits, center_logits, reg_logits = self.predictor(response_map)
if self.training:
locations = get_locations(
sr_features, template_features, sr, shift_xy=(shift_x, shift_y)
)
src_bboxes = cat([b.bbox for b in boxes], dim=0)
gt_bboxes = cat([b.bbox for b in targets], dim=0)
cls_loss, reg_loss, centerness_loss = self.loss(
locations, cls_logits, reg_logits, center_logits, src_bboxes,
gt_bboxes
)
loss = dict(
loss_tracker_class=cls_loss,
loss_tracker_motion=reg_loss,
loss_tracker_center=centerness_loss
)
return {}, {}, loss
else:
cls_logits = F.interpolate(
cls_logits, scale_factor=16, mode='bicubic'
)
center_logits = F.interpolate(
center_logits, scale_factor=16, mode='bicubic'
)
reg_logits = F.interpolate(
reg_logits, scale_factor=16, mode='bicubic'
)
locations = get_locations(
sr_features, template_features, sr, shift_xy=(shift_x, shift_y),
up_scale=16
)
assert len(boxes) == 1
bb, bb_conf = decode_response(
cls_logits, center_logits, reg_logits, locations, boxes[0],
use_centerness=self.use_centerness, sigma=self.sigma
)
track_result = wrap_results_to_boxlist(
bb, bb_conf, boxes, amodal=self.amodal
)
return {}, track_result, {}
def extract_cache(self, features, detection):
"""
Get the cache (state) that is necessary for tracking
output: (features for tracking targets,
search region,
detection bounding boxes)
"""
# get cache features for search region
# FPN features
detection = [detection]
x = self.feature_extractor(features, detection)
sr = self.track_utils.update_boxes_in_pad_images(detection)
sr = self.track_utils.extend_bbox(sr)
cache = (x, sr, detection)
return cache
def decode_response(
cls_logits, center_logits, reg_logits, locations, boxes,
use_centerness=True, sigma=0.4
):
cls_logits = F.softmax(cls_logits, dim=1)
cls_logits = cls_logits[:, 1:2, :, :]
if use_centerness:
centerness = F.sigmoid(center_logits)
obj_confidence = cls_logits * centerness
else:
obj_confidence = cls_logits
num_track_objects = obj_confidence.shape[0]
obj_confidence = obj_confidence.reshape((num_track_objects, -1))
tlbr = reg_logits.reshape((num_track_objects, 4, -1))
scale_penalty = get_scale_penalty(tlbr, boxes)
cos_window = get_cosine_window_penalty(tlbr)
p_obj_confidence = (obj_confidence * scale_penalty) * (
1 - sigma) + sigma * cos_window
idxs = torch.argmax(p_obj_confidence, dim=1)
target_ids = torch.arange(num_track_objects)
bb_c = locations[target_ids, idxs, :]
shift_tlbr = tlbr[target_ids, :, idxs]
bb_tl_x = bb_c[:, 0:1] - shift_tlbr[:, 0:1]
bb_tl_y = bb_c[:, 1:2] - shift_tlbr[:, 1:2]
bb_br_x = bb_c[:, 0:1] + shift_tlbr[:, 2:3]
bb_br_y = bb_c[:, 1:2] + shift_tlbr[:, 3:4]
bb = torch.cat((bb_tl_x, bb_tl_y, bb_br_x, bb_br_y), dim=1)
cls_logits = cls_logits.reshape((num_track_objects, -1))
bb_conf = cls_logits[target_ids, idxs]
return bb, bb_conf
def get_scale_penalty(tlbr: torch.Tensor, boxes: BoxList):
box_w = boxes.bbox[:, 2] - boxes.bbox[:, 0]
box_h = boxes.bbox[:, 3] - boxes.bbox[:, 1]
r_w = tlbr[:, 2] + tlbr[:, 0]
r_h = tlbr[:, 3] + tlbr[:, 1]
scale_w = r_w / box_w[:, None]
scale_h = r_h / box_h[:, None]
scale_w = torch.max(scale_w, 1 / scale_w)
scale_h = torch.max(scale_h, 1 / scale_h)
scale_penalty = torch.exp((-scale_w * scale_h + 1) * 0.1)
return scale_penalty
def get_cosine_window_penalty(tlbr: torch.Tensor):
num_boxes, _, num_elements = tlbr.shape
h_w = int(np.sqrt(num_elements))
hanning = torch.hann_window(h_w, dtype=torch.float, device=tlbr.device)
window = torch.ger(hanning, hanning)
window = window.reshape(-1)
return window[None, :]
def wrap_results_to_boxlist(bb, bb_conf, boxes: [BoxList], amodal=False):
num_boxes_per_image = [len(box) for box in boxes]
bb = bb.split(num_boxes_per_image, dim=0)
bb_conf = bb_conf.split(num_boxes_per_image, dim=0)
track_boxes = []
for _bb, _bb_conf, _boxes in zip(bb, bb_conf, boxes):
_bb = _bb.reshape(-1, 4)
track_box = BoxList(_bb, _boxes.size, mode="xyxy")
track_box.add_field("ids", _boxes.get_field('ids'))
track_box.add_field("labels", _boxes.get_field('labels'))
track_box.add_field("scores", _bb_conf)
if not amodal:
track_box.clip_to_image(remove_empty=True)
track_boxes.append(track_box)
return track_boxes
def get_locations(
fmap: torch.Tensor, template_fmap: torch.Tensor,
sr_boxes: [BoxList], shift_xy, up_scale=1
):
"""
"""
h, w = fmap.size()[-2:]
h, w = h * up_scale, w * up_scale
concat_boxes = cat([b.bbox for b in sr_boxes], dim=0)
box_w = concat_boxes[:, 2] - concat_boxes[:, 0]
box_h = concat_boxes[:, 3] - concat_boxes[:, 1]
stride_h = box_h / (h - 1)
stride_w = box_w / (w - 1)
device = concat_boxes.device
delta_x = torch.arange(0, w, dtype=torch.float32, device=device)
delta_y = torch.arange(0, h, dtype=torch.float32, device=device)
delta_x = (concat_boxes[:, 0])[:, None] + delta_x[None, :] * stride_w[:,
None]
delta_y = (concat_boxes[:, 1])[:, None] + delta_y[None, :] * stride_h[:,
None]
h0, w0 = template_fmap.shape[-2:]
assert (h0 == w0)
border = np.int(np.floor(h0 / 2))
st_end_idx = int(border * up_scale)
delta_x = delta_x[:, st_end_idx:-st_end_idx]
delta_y = delta_y[:, st_end_idx:-st_end_idx]
locations = []
num_boxes = delta_x.shape[0]
for i in range(num_boxes):
_y, _x = torch.meshgrid((delta_y[i, :], delta_x[i, :]))
_y = _y.reshape(-1)
_x = _x.reshape(-1)
_xy = torch.stack((_x, _y), dim=1)
locations.append(_xy)
locations = torch.stack(locations)
# shift the coordinates w.r.t the original image space (before padding)
locations[:, :, 0] -= shift_xy[0]
locations[:, :, 1] -= shift_xy[1]
return locations
| [
"torch.ger",
"siammot.utils.registry.SIAMESE_TRACKER.register",
"numpy.sqrt",
"torch.max",
"torch.stack",
"torch.hann_window",
"torch.exp",
"torch.nn.functional.sigmoid",
"maskrcnn_benchmark.structures.bounding_box.BoxList",
"numpy.floor",
"torch.arange",
"torch.meshgrid",
"torch.nn.function... | [((371, 411), 'siammot.utils.registry.SIAMESE_TRACKER.register', 'registry.SIAMESE_TRACKER.register', (['"""EMM"""'], {}), "('EMM')\n", (404, 411), False, 'from siammot.utils import registry\n'), ((4603, 4631), 'torch.nn.functional.softmax', 'F.softmax', (['cls_logits'], {'dim': '(1)'}), '(cls_logits, dim=1)\n', (4612, 4631), True, 'import torch.nn.functional as F\n'), ((5262, 5299), 'torch.argmax', 'torch.argmax', (['p_obj_confidence'], {'dim': '(1)'}), '(p_obj_confidence, dim=1)\n', (5274, 5299), False, 'import torch\n'), ((5324, 5355), 'torch.arange', 'torch.arange', (['num_track_objects'], {}), '(num_track_objects)\n', (5336, 5355), False, 'import torch\n'), ((5655, 5709), 'torch.cat', 'torch.cat', (['(bb_tl_x, bb_tl_y, bb_br_x, bb_br_y)'], {'dim': '(1)'}), '((bb_tl_x, bb_tl_y, bb_br_x, bb_br_y), dim=1)\n', (5664, 5709), False, 'import torch\n'), ((6183, 6214), 'torch.max', 'torch.max', (['scale_w', '(1 / scale_w)'], {}), '(scale_w, 1 / scale_w)\n', (6192, 6214), False, 'import torch\n'), ((6230, 6261), 'torch.max', 'torch.max', (['scale_h', '(1 / scale_h)'], {}), '(scale_h, 1 / scale_h)\n', (6239, 6261), False, 'import torch\n'), ((6289, 6330), 'torch.exp', 'torch.exp', (['((-scale_w * scale_h + 1) * 0.1)'], {}), '((-scale_w * scale_h + 1) * 0.1)\n', (6298, 6330), False, 'import torch\n'), ((6517, 6578), 'torch.hann_window', 'torch.hann_window', (['h_w'], {'dtype': 'torch.float', 'device': 'tlbr.device'}), '(h_w, dtype=torch.float, device=tlbr.device)\n', (6534, 6578), False, 'import torch\n'), ((6593, 6620), 'torch.ger', 'torch.ger', (['hanning', 'hanning'], {}), '(hanning, hanning)\n', (6602, 6620), False, 'import torch\n'), ((7670, 7708), 'maskrcnn_benchmark.modeling.utils.cat', 'cat', (['[b.bbox for b in sr_boxes]'], {'dim': '(0)'}), '([b.bbox for b in sr_boxes], dim=0)\n', (7673, 7708), False, 'from maskrcnn_benchmark.modeling.utils import cat\n'), ((7934, 7988), 'torch.arange', 'torch.arange', (['(0)', 'w'], {'dtype': 'torch.float32', 'device': 'device'}), '(0, w, dtype=torch.float32, device=device)\n', (7946, 7988), False, 'import torch\n'), ((8004, 8058), 'torch.arange', 'torch.arange', (['(0)', 'h'], {'dtype': 'torch.float32', 'device': 'device'}), '(0, h, dtype=torch.float32, device=device)\n', (8016, 8058), False, 'import torch\n'), ((8798, 8820), 'torch.stack', 'torch.stack', (['locations'], {}), '(locations)\n', (8809, 8820), False, 'import torch\n'), ((4727, 4751), 'torch.nn.functional.sigmoid', 'F.sigmoid', (['center_logits'], {}), '(center_logits)\n', (4736, 4751), True, 'import torch.nn.functional as F\n'), ((6479, 6500), 'numpy.sqrt', 'np.sqrt', (['num_elements'], {}), '(num_elements)\n', (6486, 6500), True, 'import numpy as np\n'), ((7068, 7106), 'maskrcnn_benchmark.structures.bounding_box.BoxList', 'BoxList', (['_bb', '_boxes.size'], {'mode': '"""xyxy"""'}), "(_bb, _boxes.size, mode='xyxy')\n", (7075, 7106), False, 'from maskrcnn_benchmark.structures.bounding_box import BoxList\n'), ((8332, 8348), 'numpy.floor', 'np.floor', (['(h0 / 2)'], {}), '(h0 / 2)\n', (8340, 8348), True, 'import numpy as np\n'), ((8601, 8647), 'torch.meshgrid', 'torch.meshgrid', (['(delta_y[i, :], delta_x[i, :])'], {}), '((delta_y[i, :], delta_x[i, :]))\n', (8615, 8647), False, 'import torch\n'), ((8721, 8749), 'torch.stack', 'torch.stack', (['(_x, _y)'], {'dim': '(1)'}), '((_x, _y), dim=1)\n', (8732, 8749), False, 'import torch\n'), ((2317, 2352), 'maskrcnn_benchmark.modeling.utils.cat', 'cat', (['[b.bbox for b in boxes]'], {'dim': '(0)'}), '([b.bbox for b in boxes], dim=0)\n', (2320, 2352), False, 'from maskrcnn_benchmark.modeling.utils import cat\n'), ((2378, 2415), 'maskrcnn_benchmark.modeling.utils.cat', 'cat', (['[b.bbox for b in targets]'], {'dim': '(0)'}), '([b.bbox for b in targets], dim=0)\n', (2381, 2415), False, 'from maskrcnn_benchmark.modeling.utils import cat\n'), ((2888, 2946), 'torch.nn.functional.interpolate', 'F.interpolate', (['cls_logits'], {'scale_factor': '(16)', 'mode': '"""bicubic"""'}), "(cls_logits, scale_factor=16, mode='bicubic')\n", (2901, 2946), True, 'import torch.nn.functional as F\n'), ((3008, 3069), 'torch.nn.functional.interpolate', 'F.interpolate', (['center_logits'], {'scale_factor': '(16)', 'mode': '"""bicubic"""'}), "(center_logits, scale_factor=16, mode='bicubic')\n", (3021, 3069), True, 'import torch.nn.functional as F\n'), ((3128, 3186), 'torch.nn.functional.interpolate', 'F.interpolate', (['reg_logits'], {'scale_factor': '(16)', 'mode': '"""bicubic"""'}), "(reg_logits, scale_factor=16, mode='bicubic')\n", (3141, 3186), True, 'import torch.nn.functional as F\n')] |
import numpy as np
import scipy.signal
from tqdm import tqdm
possible_motion_estimation_methods = ['decentralized_registration', ]
def init_kwargs_dict(method, method_kwargs):
# handle kwargs by method
if method == 'decentralized_registration':
method_kwargs_ = dict(pairwise_displacement_method='conv2d') # , maximum_displacement_um=400
method_kwargs_.update(method_kwargs)
return method_kwargs_
def estimate_motion(recording, peaks, peak_locations=None,
direction='y', bin_duration_s=10., bin_um=10., margin_um=50,
method='decentralized_registration', method_kwargs={},
non_rigid_kwargs=None, output_extra_check=False, progress_bar=False,
verbose=False):
"""
Estimate motion given peaks and their localization.
Location of peaks can be be included in peaks or given separately in 'peak_locations' argument.
Parameters
----------
recording: RecordingExtractor
The recording extractor
peaks: numpy array
Peak vector (complex dtype)
It can also contain the x/y/z fields
peak_locations: numpy array
If not already contained in 'peaks', the x/y/z field of spike location
direction: 'x', 'y', 'z'
Dimension on which the motion is estimated
bin_duration_s: float
Bin duration in second
bin_um: float
Spatial bin size in micro meter
margin_um: float
Margin in um to exclude from histogram estimation and
non-rigid smoothing functions to avoid edge effects
method: str
The method to be used ('decentralized_registration')
method_kwargs: dict
Specific options for the chosen method.
* 'decentralized_registration':
non_rigid_kwargs: None or dict.
If None then the motion is consider as rigid.
If dict then the motion is estimated in non rigid manner with fields:
* bin_step_um: step in um to construct overlapping gaussian smoothing functions
output_extra_check: bool
If True then return an extra dict that contains variables
to check intermediate steps (motion_histogram, non_rigid_windows, pairwise_displacement)
progress_bar: bool
Display progress bar or not.
verbose: bool
If True, output is verbose
Returns
-------
motion: numpy array
"""
# TODO handle multi segment one day
assert recording.get_num_segments() == 1
assert method in possible_motion_estimation_methods
method_kwargs = init_kwargs_dict(method, method_kwargs)
if output_extra_check:
extra_check = {}
if method =='decentralized_registration':
# make 2D histogram raster
if verbose:
print('Computing motion histogram')
motion_histogram, temporal_bins, spatial_hist_bins = make_motion_histogram(recording, peaks,
peak_locations=peak_locations,
bin_duration_s=bin_duration_s,
bin_um=bin_um,
margin_um=margin_um)
if output_extra_check:
extra_check['motion_histogram'] = motion_histogram
extra_check['temporal_bins'] = temporal_bins
extra_check['spatial_hist_bins'] = spatial_hist_bins
# rigid or non rigid is handled with a family of gaussian non_rigid_windows
non_rigid_windows = []
if non_rigid_kwargs is None:
# one unique block for all depth
non_rigid_windows = [np.ones(motion_histogram.shape[1] , dtype='float64')]
spatial_bins = None
else:
assert 'bin_step_um' in non_rigid_kwargs, "'non_rigid_kwargs' needs to specify the 'bin_step_um' field"
probe = recording.get_probe()
dim = ['x', 'y', 'z'].index(direction)
contact_pos = probe.contact_positions[:, dim]
bin_step_um = non_rigid_kwargs['bin_step_um']
min_ = np.min(contact_pos) - margin_um
max_ = np.max(contact_pos) + margin_um
num_win = int(np.ceil((max_ - min_) / bin_step_um))
spatial_bins = np.arange(num_win) * bin_step_um + bin_step_um / 2. + min_
# TODO check this gaussian with julien
for win_center in spatial_bins:
sigma = bin_step_um
win = np.exp(-(spatial_hist_bins[:-1] - win_center) ** 2 / (2 * sigma ** 2))
non_rigid_windows.append(win)
if output_extra_check:
extra_check['non_rigid_windows'] = non_rigid_windows
if output_extra_check:
extra_check['pairwise_displacement_list'] = []
motion = []
for i, win in enumerate(non_rigid_windows):
motion_hist = win[np.newaxis, :] * motion_histogram
if verbose:
print(f'Computing pairwise displacement: {i + 1} / {len(non_rigid_windows)}')
pairwise_displacement = compute_pairwise_displacement(motion_hist, bin_um,
method=method_kwargs['pairwise_displacement_method'],
progress_bar=progress_bar)
if output_extra_check:
extra_check['pairwise_displacement_list'].append(pairwise_displacement)
if verbose:
print(f'Computing global displacement: {i + 1} / {len(non_rigid_windows)}')
one_motion = compute_global_displacement(pairwise_displacement)
motion.append(one_motion[:, np.newaxis])
motion = np.concatenate(motion, axis=1)
if output_extra_check:
return motion, temporal_bins, spatial_bins, extra_check
else:
return motion, temporal_bins, spatial_bins
def get_location_from_fields(peaks_or_locations):
dims = [dim for dim in ('x', 'y', 'z') if dim in peaks_or_locations.dtype.fields]
peak_locations = np.zeros((peaks_or_locations.size, len(dims)), dtype='float64')
for i, dim in enumerate(dims):
peak_locations[:, i] = peaks_or_locations[dim]
return peak_locations
def make_motion_histogram(recording, peaks, peak_locations=None,
weight_with_amplitude=False, direction='y',
bin_duration_s=1., bin_um=2., margin_um=50):
"""
Generate motion histogram
"""
if peak_locations is None:
peak_locations = get_location_from_fields(peaks)
else:
peak_locations = get_location_from_fields(peak_locations)
fs = recording.get_sampling_frequency()
num_sample = recording.get_num_samples(segment_index=0)
bin = int(bin_duration_s * fs)
sample_bins = np.arange(0, num_sample+bin, bin)
temporal_bins = sample_bins / fs
# contact along one axis
probe = recording.get_probe()
dim = ['x', 'y', 'z'].index(direction)
contact_pos = probe.contact_positions[:, dim]
min_ = np.min(contact_pos) - margin_um
max_ = np.max(contact_pos) + margin_um
spatial_bins = np.arange(min_, max_+bin_um, bin_um)
arr = np.zeros((peaks.size, 2), dtype='float64')
arr[:, 0] = peaks['sample_ind']
arr[:, 1] = peak_locations[:, dim]
if weight_with_amplitude:
weights = np.abs(peaks['amplitude'])
else:
weights = None
motion_histogram, edges = np.histogramdd(arr, bins=(sample_bins, spatial_bins), weights=weights)
return motion_histogram, temporal_bins, spatial_bins
def compute_pairwise_displacement(motion_hist, bin_um, method='conv2d', progress_bar=False): # maximum_displacement_um=400
"""
Compute pairwise displacement
"""
size = motion_hist.shape[0]
pairwise_displacement = np.zeros((size, size), dtype='float32')
if method =='conv2d':
n = motion_hist.shape[1] // 2
possible_displacement = np.arange(motion_hist.shape[1]) * bin_um
possible_displacement -= possible_displacement[n]
# TODO find something faster
loop = range(size)
if progress_bar:
loop = tqdm(loop)
for i in loop:
# print(i, size)
for j in range(size):
conv = np.convolve(motion_hist[i, :], motion_hist[j, ::-1], mode='same')
ind_max = np.argmax(conv)
pairwise_displacement[i, j] = possible_displacement[ind_max]
# for i in range(size):
# print(i, size)
# conv = scipy.ndimage.convolve1d(motion_hist, motion_hist[i, ::-1], axis=1)
# ind_max = np.argmax(conv, axis=1)
# pairwise_displacement[i, :] = possible_displacement[ind_max]
elif method == 'phase_cross_correlation':
try:
import skimage.registration
except ImportError:
raise ImportError("To use 'phase_cross_correlation' method install scikit-image")
for i in range(size):
print(i, size)
for j in range(size):
shift, error, diffphase = skimage.registration.phase_cross_correlation(motion_hist[i, :], motion_hist[j, :])
pairwise_displacement[i, j] = shift
else:
raise ValueError(f'method do not exists for compute_pairwise_displacement {method}')
return pairwise_displacement
def compute_global_displacement(pairwise_displacement, method='gradient_descent', max_iter=1000):
"""
Compute global displacement
"""
if method == 'gradient_descent':
size = pairwise_displacement.shape[0]
displacement = np.zeros(size, dtype='float64')
# use variable name from paper
# DECENTRALIZED MOTION INFERENCE AND REGISTRATION OF NEUROPIXEL DATA
# <NAME>, <NAME>, <NAME>
D = pairwise_displacement
p = displacement
p_prev = p.copy()
for i in range(max_iter):
# print(i)
repeat1 = np.tile(p[:, np.newaxis], [1, size])
repeat2 = np.tile(p[np.newaxis, :], [size, 1])
mat_norm = D + repeat1 - repeat2
p += 2 * (np.sum(D - np.diag(D), axis=1) - (size - 1) * p) / np.linalg.norm(mat_norm)
if np.allclose(p_prev, p):
break
else:
p_prev = p.copy()
elif method =='robust':
pass
# error_mat_S = error_mat[np.where(S != 0)]
# W1 = np.exp(-((error_mat_S-error_mat_S.min())/(error_mat_S.max()-error_mat_S.min()))/error_sigma)
# W2 = np.exp(-squareform(pdist(np.arange(error_mat.shape[0])[:,None]))/time_sigma)
# W2 = W2[np.where(S != 0)]
# W = (W2*W1)[:,None]
# I, J = np.where(S != 0)
# V = displacement_matrix[np.where(S != 0)]
# M = csr_matrix((np.ones(I.shape[0]), (np.arange(I.shape[0]),I)))
# N = csr_matrix((np.ones(I.shape[0]), (np.arange(I.shape[0]),J)))
# A = M - N
# idx = np.ones(A.shape[0]).astype(bool)
# for i in notebook.tqdm(range(n_iter)):
# p = lsqr(A[idx].multiply(W[idx]), V[idx]*W[idx][:,0])[0]
# idx = np.where(np.abs(zscore(A@p-V)) <= robust_regression_sigma)
# return p
else:
raise ValueError(f'method do not exists for compute_global_displacement {method}')
return displacement
| [
"numpy.abs",
"numpy.tile",
"numpy.allclose",
"numpy.ceil",
"numpy.histogramdd",
"numpy.ones",
"numpy.convolve",
"tqdm.tqdm",
"numpy.linalg.norm",
"numpy.argmax",
"numpy.max",
"numpy.exp",
"numpy.diag",
"numpy.zeros",
"numpy.concatenate",
"numpy.min",
"numpy.arange"
] | [((7004, 7039), 'numpy.arange', 'np.arange', (['(0)', '(num_sample + bin)', 'bin'], {}), '(0, num_sample + bin, bin)\n', (7013, 7039), True, 'import numpy as np\n'), ((7351, 7389), 'numpy.arange', 'np.arange', (['min_', '(max_ + bin_um)', 'bin_um'], {}), '(min_, max_ + bin_um, bin_um)\n', (7360, 7389), True, 'import numpy as np\n'), ((7399, 7441), 'numpy.zeros', 'np.zeros', (['(peaks.size, 2)'], {'dtype': '"""float64"""'}), "((peaks.size, 2), dtype='float64')\n", (7407, 7441), True, 'import numpy as np\n'), ((7660, 7730), 'numpy.histogramdd', 'np.histogramdd', (['arr'], {'bins': '(sample_bins, spatial_bins)', 'weights': 'weights'}), '(arr, bins=(sample_bins, spatial_bins), weights=weights)\n', (7674, 7730), True, 'import numpy as np\n'), ((8033, 8072), 'numpy.zeros', 'np.zeros', (['(size, size)'], {'dtype': '"""float32"""'}), "((size, size), dtype='float32')\n", (8041, 8072), True, 'import numpy as np\n'), ((5899, 5929), 'numpy.concatenate', 'np.concatenate', (['motion'], {'axis': '(1)'}), '(motion, axis=1)\n', (5913, 5929), True, 'import numpy as np\n'), ((7257, 7276), 'numpy.min', 'np.min', (['contact_pos'], {}), '(contact_pos)\n', (7263, 7276), True, 'import numpy as np\n'), ((7300, 7319), 'numpy.max', 'np.max', (['contact_pos'], {}), '(contact_pos)\n', (7306, 7319), True, 'import numpy as np\n'), ((7570, 7596), 'numpy.abs', 'np.abs', (["peaks['amplitude']"], {}), "(peaks['amplitude'])\n", (7576, 7596), True, 'import numpy as np\n'), ((9851, 9882), 'numpy.zeros', 'np.zeros', (['size'], {'dtype': '"""float64"""'}), "(size, dtype='float64')\n", (9859, 9882), True, 'import numpy as np\n'), ((8170, 8201), 'numpy.arange', 'np.arange', (['motion_hist.shape[1]'], {}), '(motion_hist.shape[1])\n', (8179, 8201), True, 'import numpy as np\n'), ((8387, 8397), 'tqdm.tqdm', 'tqdm', (['loop'], {}), '(loop)\n', (8391, 8397), False, 'from tqdm import tqdm\n'), ((10197, 10233), 'numpy.tile', 'np.tile', (['p[:, np.newaxis]', '[1, size]'], {}), '(p[:, np.newaxis], [1, size])\n', (10204, 10233), True, 'import numpy as np\n'), ((10256, 10292), 'numpy.tile', 'np.tile', (['p[np.newaxis, :]', '[size, 1]'], {}), '(p[np.newaxis, :], [size, 1])\n', (10263, 10292), True, 'import numpy as np\n'), ((10451, 10473), 'numpy.allclose', 'np.allclose', (['p_prev', 'p'], {}), '(p_prev, p)\n', (10462, 10473), True, 'import numpy as np\n'), ((3784, 3835), 'numpy.ones', 'np.ones', (['motion_histogram.shape[1]'], {'dtype': '"""float64"""'}), "(motion_histogram.shape[1], dtype='float64')\n", (3791, 3835), True, 'import numpy as np\n'), ((4241, 4260), 'numpy.min', 'np.min', (['contact_pos'], {}), '(contact_pos)\n', (4247, 4260), True, 'import numpy as np\n'), ((4292, 4311), 'numpy.max', 'np.max', (['contact_pos'], {}), '(contact_pos)\n', (4298, 4311), True, 'import numpy as np\n'), ((4351, 4387), 'numpy.ceil', 'np.ceil', (['((max_ - min_) / bin_step_um)'], {}), '((max_ - min_) / bin_step_um)\n', (4358, 4387), True, 'import numpy as np\n'), ((4629, 4699), 'numpy.exp', 'np.exp', (['(-(spatial_hist_bins[:-1] - win_center) ** 2 / (2 * sigma ** 2))'], {}), '(-(spatial_hist_bins[:-1] - win_center) ** 2 / (2 * sigma ** 2))\n', (4635, 4699), True, 'import numpy as np\n'), ((8507, 8572), 'numpy.convolve', 'np.convolve', (['motion_hist[i, :]', 'motion_hist[j, ::-1]'], {'mode': '"""same"""'}), "(motion_hist[i, :], motion_hist[j, ::-1], mode='same')\n", (8518, 8572), True, 'import numpy as np\n'), ((8599, 8614), 'numpy.argmax', 'np.argmax', (['conv'], {}), '(conv)\n', (8608, 8614), True, 'import numpy as np\n'), ((10411, 10435), 'numpy.linalg.norm', 'np.linalg.norm', (['mat_norm'], {}), '(mat_norm)\n', (10425, 10435), True, 'import numpy as np\n'), ((4416, 4434), 'numpy.arange', 'np.arange', (['num_win'], {}), '(num_win)\n', (4425, 4434), True, 'import numpy as np\n'), ((10371, 10381), 'numpy.diag', 'np.diag', (['D'], {}), '(D)\n', (10378, 10381), True, 'import numpy as np\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 7 21:32:49 2020
@author: alfredocu
"""
# Bibliotecas.
import numpy as np
import numpy.random as rnd
import matplotlib.pyplot as plt
# Algoritmos.
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.model_selection import train_test_split
# Semilla.
np.random.seed(42)
# Datos
m = 100
# Vector aleatorio.
x = 6 * np.random.rand(m, 1) - 3
# Funsión
y = 0.5 * x**2 + x + 2 + np.random.randn(m, 1)
# Entrenamineto 75% y pruebas 25%. -> Separación de datos.
xtrain, xtest, ytrain, ytest = train_test_split(x, y)
# grado.
d = 2
# Juntar varios modelos a la vez.
model = Pipeline([("poly", PolynomialFeatures(degree=d, include_bias=False)),
("scaler", StandardScaler()),
("lin_reg", LinearRegression())])
# Entrenamos.
model.fit(xtrain, ytrain)
# Resultados del entrenamiento y las pruebas.
print("Train score: ", model.score(xtrain, ytrain))
print("Test score: ", model.score(xtest, ytest))
# Dibujar.
xnew = np.linspace(-3, 3, 1000).reshape(1000, 1)
ynew = model.predict(xnew)
plt.plot(xtrain, ytrain, ".b")
plt.plot(xtest, ytest, ".r")
plt.plot(xnew, ynew, "-k")
plt.xlabel("$x_1$", fontsize=18)
plt.ylabel("$y$", fontsize=18)
plt.axis([-3, 3, -5, 15])
plt.show()
# Intercepción.
# print(model.intercept_)
# Coeficientes.
# print(model.coef_)
| [
"sklearn.preprocessing.PolynomialFeatures",
"numpy.random.rand",
"matplotlib.pyplot.ylabel",
"sklearn.model_selection.train_test_split",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"sklearn.preprocessing.StandardScaler",
"numpy.linspace",
"numpy.random.seed",
"matplotlib.pyplot.axis",
... | [((474, 492), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (488, 492), True, 'import numpy as np\n'), ((713, 735), 'sklearn.model_selection.train_test_split', 'train_test_split', (['x', 'y'], {}), '(x, y)\n', (729, 735), False, 'from sklearn.model_selection import train_test_split\n'), ((1239, 1269), 'matplotlib.pyplot.plot', 'plt.plot', (['xtrain', 'ytrain', '""".b"""'], {}), "(xtrain, ytrain, '.b')\n", (1247, 1269), True, 'import matplotlib.pyplot as plt\n'), ((1270, 1298), 'matplotlib.pyplot.plot', 'plt.plot', (['xtest', 'ytest', '""".r"""'], {}), "(xtest, ytest, '.r')\n", (1278, 1298), True, 'import matplotlib.pyplot as plt\n'), ((1299, 1325), 'matplotlib.pyplot.plot', 'plt.plot', (['xnew', 'ynew', '"""-k"""'], {}), "(xnew, ynew, '-k')\n", (1307, 1325), True, 'import matplotlib.pyplot as plt\n'), ((1326, 1358), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""$x_1$"""'], {'fontsize': '(18)'}), "('$x_1$', fontsize=18)\n", (1336, 1358), True, 'import matplotlib.pyplot as plt\n'), ((1359, 1389), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$y$"""'], {'fontsize': '(18)'}), "('$y$', fontsize=18)\n", (1369, 1389), True, 'import matplotlib.pyplot as plt\n'), ((1390, 1415), 'matplotlib.pyplot.axis', 'plt.axis', (['[-3, 3, -5, 15]'], {}), '([-3, 3, -5, 15])\n', (1398, 1415), True, 'import matplotlib.pyplot as plt\n'), ((1416, 1426), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1424, 1426), True, 'import matplotlib.pyplot as plt\n'), ((600, 621), 'numpy.random.randn', 'np.random.randn', (['m', '(1)'], {}), '(m, 1)\n', (615, 621), True, 'import numpy as np\n'), ((539, 559), 'numpy.random.rand', 'np.random.rand', (['m', '(1)'], {}), '(m, 1)\n', (553, 559), True, 'import numpy as np\n'), ((1169, 1193), 'numpy.linspace', 'np.linspace', (['(-3)', '(3)', '(1000)'], {}), '(-3, 3, 1000)\n', (1180, 1193), True, 'import numpy as np\n'), ((814, 862), 'sklearn.preprocessing.PolynomialFeatures', 'PolynomialFeatures', ([], {'degree': 'd', 'include_bias': '(False)'}), '(degree=d, include_bias=False)\n', (832, 862), False, 'from sklearn.preprocessing import PolynomialFeatures\n'), ((892, 908), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (906, 908), False, 'from sklearn.preprocessing import StandardScaler\n'), ((939, 957), 'sklearn.linear_model.LinearRegression', 'LinearRegression', ([], {}), '()\n', (955, 957), False, 'from sklearn.linear_model import LinearRegression\n')] |
import numpy as np
import plotext as plt
from typing import List
from rich.jupyter import JupyterMixin
from rich.ansi import AnsiDecoder
from rich.console import Group as RenderGroup
from rich.layout import Layout
from rich.panel import Panel
def plot_race(gender: str, length: int, names: List[str], lap_times: np.array, *size):
"""Function that takes all parameters and times and produces the two plots in the tracking view. Depends mainly on
plotext
:param str gender: string indicating if the race is for Men or Women. Accepted values are ["M", "F"]
:param int length: integer indicating the length of the race. Accepted values are
[500, 1000, 1500, 3000, 5000, 10000]
:param List[str] names: List of strings with the names of the athletes.
:param np.array lap_times: Numpy array with the times so far.
:param size: Additional arguments for the width and the height of the plots
:return:
"""
colors = ("red", "blue")
gender_name = "Men" if gender == "M" else "Women"
title_names = " vs ".join(names)
nr_athletes = len(names)
nr_laps = lap_times.shape[1]
plt.subplots(2,1)
total_times = np.cumsum(lap_times, axis=1)
total_times[lap_times == 0] = 0
# Plot of the total
plt.subplot(1, 1)
for i in range(nr_athletes):
if total_times[i, :].sum() == 0:
athlete_times = total_times[i, :]
else:
athlete_times = total_times[i, total_times[i, :] > 0]
plt.plot(athlete_times, color=colors[i], label=names[i])
plt.plotsize(*size)
plt.ylim(0, nr_laps * 35)
plt.title(f"{gender_name}'s {length}m race total times: {title_names}")
plt.xticks(list(range(nr_laps)))
plt.xlim(1, nr_laps)
# Plot of the lap times
plt.subplot(2, 1)
for i in range(nr_athletes):
if total_times[i, :].sum() == 0:
athlete_times = lap_times[i, :]
else:
athlete_times = lap_times[i, lap_times[i, :] > 0]
plt.plot(athlete_times, color=colors[i])
plt.plotsize(*size)
plt.ylim(5, 35)
plt.title(f"{gender_name}'s {length}m race lap times: {title_names}")
plt.xticks(list(range(nr_laps)))
plt.xlim(1, nr_laps)
return plt.build()
class plotextMixin(JupyterMixin):
"""plotextMixin that allows plotext figures to be placed inside a rich.Layout. Got the code from
https://github.com/piccolomo/plotext/issues/26
"""
def __init__(self, gender: str, length: int, names: List[str], lap_times: np.array):
"""Initialize
:param str gender: string indicating if the race is for Men or Women. Accepted values are ["M", "F"]
:param int length: integer indicating the length of the race. Accepted values are
[500, 1000, 1500, 3000, 5000, 10000]
:param List[str] names: List of strings with the names of the athletes.
:param np.array lap_times: Numpy array with the times so far.
"""
self.decoder = AnsiDecoder()
self.gender = gender
self.length = length
self.names = names
self.lap_times = lap_times
def __rich_console__(self, console, options):
self.width = options.max_width or console.width
self.height = options.height or console.height
canvas = plot_race(
self.gender,
self.length,
self.names,
self.lap_times,
self.width,
self.height / 2)
self.rich_canvas = RenderGroup(*self.decoder.decode(canvas))
yield self.rich_canvas
def create_plotext_panel(
gender: str,
length: int,
names: List[str],
lap_times: np.array,
layout: Layout) -> Panel:
"""Creates the actual ponel with the plotext in it. The layouy that is supplied will be used to put the panel into.
:param str gender: string indicating if the race is for Men or Women. Accepted values are ["M", "F"]
:param int length: integer indicating the length of the race. Accepted values are
[500, 1000, 1500, 3000, 5000, 10000]
:param List[str] names: List of strings with the names of the athletes.
:param np.array lap_times: Numpy array with the times so far.
:param rich.Layout layout: The layout in which the plotext figure will be placed.
:return rich.Panel: The panel with the plotext in it is returned
"""
mix = plotextMixin(
gender,
length,
names,
lap_times
)
mix = Panel(mix)
layout.update(mix)
return mix | [
"plotext.subplot",
"plotext.plotsize",
"rich.panel.Panel",
"plotext.plot",
"plotext.build",
"plotext.ylim",
"plotext.subplots",
"plotext.title",
"rich.ansi.AnsiDecoder",
"numpy.cumsum",
"plotext.xlim"
] | [((1131, 1149), 'plotext.subplots', 'plt.subplots', (['(2)', '(1)'], {}), '(2, 1)\n', (1143, 1149), True, 'import plotext as plt\n'), ((1168, 1196), 'numpy.cumsum', 'np.cumsum', (['lap_times'], {'axis': '(1)'}), '(lap_times, axis=1)\n', (1177, 1196), True, 'import numpy as np\n'), ((1261, 1278), 'plotext.subplot', 'plt.subplot', (['(1)', '(1)'], {}), '(1, 1)\n', (1272, 1278), True, 'import plotext as plt\n'), ((1548, 1567), 'plotext.plotsize', 'plt.plotsize', (['*size'], {}), '(*size)\n', (1560, 1567), True, 'import plotext as plt\n'), ((1572, 1597), 'plotext.ylim', 'plt.ylim', (['(0)', '(nr_laps * 35)'], {}), '(0, nr_laps * 35)\n', (1580, 1597), True, 'import plotext as plt\n'), ((1602, 1673), 'plotext.title', 'plt.title', (['f"""{gender_name}\'s {length}m race total times: {title_names}"""'], {}), '(f"{gender_name}\'s {length}m race total times: {title_names}")\n', (1611, 1673), True, 'import plotext as plt\n'), ((1715, 1735), 'plotext.xlim', 'plt.xlim', (['(1)', 'nr_laps'], {}), '(1, nr_laps)\n', (1723, 1735), True, 'import plotext as plt\n'), ((1769, 1786), 'plotext.subplot', 'plt.subplot', (['(2)', '(1)'], {}), '(2, 1)\n', (1780, 1786), True, 'import plotext as plt\n'), ((2034, 2053), 'plotext.plotsize', 'plt.plotsize', (['*size'], {}), '(*size)\n', (2046, 2053), True, 'import plotext as plt\n'), ((2058, 2073), 'plotext.ylim', 'plt.ylim', (['(5)', '(35)'], {}), '(5, 35)\n', (2066, 2073), True, 'import plotext as plt\n'), ((2078, 2147), 'plotext.title', 'plt.title', (['f"""{gender_name}\'s {length}m race lap times: {title_names}"""'], {}), '(f"{gender_name}\'s {length}m race lap times: {title_names}")\n', (2087, 2147), True, 'import plotext as plt\n'), ((2189, 2209), 'plotext.xlim', 'plt.xlim', (['(1)', 'nr_laps'], {}), '(1, nr_laps)\n', (2197, 2209), True, 'import plotext as plt\n'), ((2221, 2232), 'plotext.build', 'plt.build', ([], {}), '()\n', (2230, 2232), True, 'import plotext as plt\n'), ((4480, 4490), 'rich.panel.Panel', 'Panel', (['mix'], {}), '(mix)\n', (4485, 4490), False, 'from rich.panel import Panel\n'), ((1487, 1543), 'plotext.plot', 'plt.plot', (['athlete_times'], {'color': 'colors[i]', 'label': 'names[i]'}), '(athlete_times, color=colors[i], label=names[i])\n', (1495, 1543), True, 'import plotext as plt\n'), ((1989, 2029), 'plotext.plot', 'plt.plot', (['athlete_times'], {'color': 'colors[i]'}), '(athlete_times, color=colors[i])\n', (1997, 2029), True, 'import plotext as plt\n'), ((2974, 2987), 'rich.ansi.AnsiDecoder', 'AnsiDecoder', ([], {}), '()\n', (2985, 2987), False, 'from rich.ansi import AnsiDecoder\n')] |
# Authors: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
#
# License: BSD (3-clause)
from mne_connectivity.io import read_connectivity
import numpy as np
import pytest
from numpy.testing import (assert_allclose, assert_array_equal,
assert_array_less)
from scipy.signal import hilbert
from mne.utils import catch_logging, use_log_level
from mne_connectivity.envelope import envelope_correlation, symmetric_orth
def _compute_corrs_orig(data):
# This is the version of the code by Sheraz and Denis.
# For this version (epochs, labels, time) must be -> (labels, time, epochs)
n_epochs, n_labels, _ = data.shape
corr = np.zeros((n_labels, n_labels))
for epoch_data in data:
for ii in range(n_labels):
for jj in range(n_labels):
# Get timeseries for each pair
x, y = epoch_data[ii], epoch_data[jj]
x_mag = np.abs(x)
x_conj_scaled = x.conj()
x_conj_scaled /= x_mag
# Calculate orthogonalization
y_orth_x = (y * x_conj_scaled).imag
y_orth_x_mag = np.abs(y_orth_x)
# Estimate correlation
corr[ii, jj] += np.abs(np.corrcoef(x_mag, y_orth_x_mag)[0, 1])
corr = (corr + corr.T) / (2. * n_epochs)
corr.flat[::n_labels + 1] = 0.
return corr
def test_roundtrip_envelope_correlation(tmp_path):
"""Test write/read roundtrip for envelope correlation."""
rng = np.random.RandomState(0)
n_epochs, n_signals, n_times = 1, 4, 64
data = rng.randn(n_epochs, n_signals, n_times)
data_hilbert = hilbert(data, axis=-1)
corr = envelope_correlation(data_hilbert)
tmp_file = tmp_path / 'temp_file.nc'
corr.save(tmp_file)
read_corr = read_connectivity(tmp_file)
assert_array_equal(corr.get_data(), read_corr.get_data())
def test_empty_epochs_correlation():
"""Test empty epochs object results in error."""
rng = np.random.RandomState(0)
n_epochs, n_signals, n_times = 0, 4, 64
data = rng.randn(n_epochs, n_signals, n_times)
data_hilbert = hilbert(data, axis=-1)
with pytest.raises(RuntimeError, match='Passing in empty epochs'):
envelope_correlation(data_hilbert)
def test_envelope_correlation():
"""Test the envelope correlation function."""
rng = np.random.RandomState(0)
n_epochs, n_signals, n_times = 2, 4, 64
data = rng.randn(n_epochs, n_signals, n_times)
data_hilbert = hilbert(data, axis=-1)
corr_orig = _compute_corrs_orig(data_hilbert)
assert (0 <= corr_orig).all()
assert (corr_orig < 1).all()
# upper triangular indices to access the "corr_orig"
triu_inds = np.triu_indices(n_signals, k=0)
raveled_triu_inds = np.ravel_multi_index(
triu_inds, dims=(n_signals, n_signals))
condensed_n_estimates = len(raveled_triu_inds)
# using complex data
corr = envelope_correlation(data_hilbert)
assert_allclose(
np.mean(corr.get_data(output='raveled'), axis=0).squeeze(),
corr_orig.flatten()[raveled_triu_inds])
# do Hilbert internally, and don't combine
corr = envelope_correlation(data)
assert corr.shape == (data.shape[0],) + \
(condensed_n_estimates,) + (1,)
corr = np.mean(corr.get_data(output='dense'), axis=0)
assert_allclose(corr.squeeze(), corr_orig)
# degenerate
with pytest.raises(ValueError, match='dtype must be float or complex'):
envelope_correlation(data.astype(int))
with pytest.raises(ValueError, match='entry in data must be 2D'):
envelope_correlation(data[np.newaxis])
with pytest.raises(ValueError, match='n_nodes mismatch'):
envelope_correlation([rng.randn(2, 8), rng.randn(3, 8)])
with pytest.raises(ValueError, match='Invalid value.*orthogonalize.*'):
envelope_correlation(data, orthogonalize='foo')
# test non-orthogonal computation
corr_plain = envelope_correlation(data, orthogonalize=False)
assert corr_plain.shape == (data.shape[0],) + \
(condensed_n_estimates,) + (1,)
assert corr_plain.get_data(output='dense').shape == \
(data.shape[0],) + \
(corr_orig.shape[0], corr_orig.shape[1],) + (1,)
assert np.min(corr_plain.get_data()) < 0
corr_plain_mean = np.mean(corr_plain.get_data(output='dense'), axis=0)
assert_allclose(np.diag(corr_plain_mean.squeeze()), 1)
np_corr = np.array([np.corrcoef(np.abs(x)) for x in data_hilbert])
assert_allclose(corr_plain.get_data(output='dense').squeeze(), np_corr)
# test resulting Epoch -> non-Epoch data structure
# using callable
corr = envelope_correlation(data_hilbert)
corr_combine = corr.combine(combine=lambda data: np.mean(data, axis=0))
assert_allclose(corr_combine.get_data(output='dense').squeeze(),
corr_orig)
with pytest.raises(ValueError, match='Combine option'):
corr.combine(combine=1.)
with pytest.raises(ValueError, match='Combine option'):
corr.combine(combine='foo')
# check against FieldTrip, which uses the square-log-norm version
# from scipy.io import savemat
# savemat('data.mat', dict(data_hilbert=data_hilbert))
# matlab
# load data
# ft_connectivity_powcorr_ortho(reshape(data_hilbert(1,:,:), [4, 64]))
# ft_connectivity_powcorr_ortho(reshape(data_hilbert(2,:,:), [4, 64]))
ft_vals = np.array([
[[np.nan, 0.196734553900236, 0.063173148355451, -0.242638384630448],
[0.196734553900236, np.nan, 0.041799775495150, -0.088205187548542],
[0.063173148355451, 0.041799775495150, np.nan, 0.090331428512317],
[-0.242638384630448, -0.088205187548542, 0.090331428512317, np.nan]],
[[np.nan, -0.013270857462890, 0.185200598081295, 0.140284351572544],
[-0.013270857462890, np.nan, 0.150981508043722, -0.000671809276372],
[0.185200598081295, 0.150981508043722, np.nan, 0.137460244313337],
[0.140284351572544, -0.000671809276372, 0.137460244313337, np.nan]],
], float)
ft_vals[np.isnan(ft_vals)] = 0
corr_log = envelope_correlation(
data, log=True, absolute=False)
assert_allclose(corr_log.get_data(output='dense').squeeze(), ft_vals)
@pytest.mark.parametrize('ndim, generator', [
(2, False),
(3, False),
(3, True),
])
def test_symmetric_orth(ndim, generator):
n_ch, n_time = 5, 1000
rng = np.random.RandomState(0)
Z = rng.randn(n_ch, n_time)
mixing = rng.randn(n_ch, n_ch)
mixing = mixing @ mixing.T
mixing += np.eye(n_ch)
Z = mixing @ Z
assert ndim in (2, 3)
if generator:
assert ndim == 3
Z = [Z]
elif ndim == 3:
Z = Z[np.newaxis]
with catch_logging() as log:
P = symmetric_orth(Z, verbose='debug')
if generator:
assert not isinstance(P, np.ndarray)
with use_log_level('debug'):
P = np.array(list(P))
assert isinstance(P, np.ndarray)
if ndim == 3:
assert P.ndim == 3
assert P.shape[0] == 1
Z, P = Z[0], P[0]
log = log.getvalue()
assert 'Convergence reached' in log
vals = P @ P.T
diag = np.diag(vals)
orig = np.diag(Z @ Z.T)
assert_array_less(diag, orig) # some power lost
assert_array_less(orig * 0.1, diag) # but not too much
off = np.triu(vals, k=1)
assert_allclose(off, 0., atol=1e-6)
# Degenerate cases
with pytest.raises(RuntimeError, match='at least as many time points'):
symmetric_orth(Z[:, :1])
with pytest.warns(RuntimeWarning, match='did not converge'):
symmetric_orth(Z, n_iter=1)
Z_bad = Z.copy()
Z_bad[0] = Z[1] + Z[2]
with pytest.warns(RuntimeWarning, match='rank deficient'):
symmetric_orth(Z_bad)
| [
"numpy.ravel_multi_index",
"numpy.array",
"numpy.random.RandomState",
"numpy.testing.assert_array_less",
"numpy.mean",
"numpy.testing.assert_allclose",
"numpy.triu",
"numpy.abs",
"numpy.eye",
"numpy.triu_indices",
"mne_connectivity.envelope.envelope_correlation",
"numpy.corrcoef",
"mne_conne... | [((6280, 6359), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""ndim, generator"""', '[(2, False), (3, False), (3, True)]'], {}), "('ndim, generator', [(2, False), (3, False), (3, True)])\n", (6303, 6359), False, 'import pytest\n'), ((716, 746), 'numpy.zeros', 'np.zeros', (['(n_labels, n_labels)'], {}), '((n_labels, n_labels))\n', (724, 746), True, 'import numpy as np\n'), ((1549, 1573), 'numpy.random.RandomState', 'np.random.RandomState', (['(0)'], {}), '(0)\n', (1570, 1573), True, 'import numpy as np\n'), ((1688, 1710), 'scipy.signal.hilbert', 'hilbert', (['data'], {'axis': '(-1)'}), '(data, axis=-1)\n', (1695, 1710), False, 'from scipy.signal import hilbert\n'), ((1722, 1756), 'mne_connectivity.envelope.envelope_correlation', 'envelope_correlation', (['data_hilbert'], {}), '(data_hilbert)\n', (1742, 1756), False, 'from mne_connectivity.envelope import envelope_correlation, symmetric_orth\n'), ((1839, 1866), 'mne_connectivity.io.read_connectivity', 'read_connectivity', (['tmp_file'], {}), '(tmp_file)\n', (1856, 1866), False, 'from mne_connectivity.io import read_connectivity\n'), ((2031, 2055), 'numpy.random.RandomState', 'np.random.RandomState', (['(0)'], {}), '(0)\n', (2052, 2055), True, 'import numpy as np\n'), ((2170, 2192), 'scipy.signal.hilbert', 'hilbert', (['data'], {'axis': '(-1)'}), '(data, axis=-1)\n', (2177, 2192), False, 'from scipy.signal import hilbert\n'), ((2403, 2427), 'numpy.random.RandomState', 'np.random.RandomState', (['(0)'], {}), '(0)\n', (2424, 2427), True, 'import numpy as np\n'), ((2542, 2564), 'scipy.signal.hilbert', 'hilbert', (['data'], {'axis': '(-1)'}), '(data, axis=-1)\n', (2549, 2564), False, 'from scipy.signal import hilbert\n'), ((2756, 2787), 'numpy.triu_indices', 'np.triu_indices', (['n_signals'], {'k': '(0)'}), '(n_signals, k=0)\n', (2771, 2787), True, 'import numpy as np\n'), ((2812, 2872), 'numpy.ravel_multi_index', 'np.ravel_multi_index', (['triu_inds'], {'dims': '(n_signals, n_signals)'}), '(triu_inds, dims=(n_signals, n_signals))\n', (2832, 2872), True, 'import numpy as np\n'), ((2970, 3004), 'mne_connectivity.envelope.envelope_correlation', 'envelope_correlation', (['data_hilbert'], {}), '(data_hilbert)\n', (2990, 3004), False, 'from mne_connectivity.envelope import envelope_correlation, symmetric_orth\n'), ((3201, 3227), 'mne_connectivity.envelope.envelope_correlation', 'envelope_correlation', (['data'], {}), '(data)\n', (3221, 3227), False, 'from mne_connectivity.envelope import envelope_correlation, symmetric_orth\n'), ((3992, 4039), 'mne_connectivity.envelope.envelope_correlation', 'envelope_correlation', (['data'], {'orthogonalize': '(False)'}), '(data, orthogonalize=False)\n', (4012, 4039), False, 'from mne_connectivity.envelope import envelope_correlation, symmetric_orth\n'), ((4690, 4724), 'mne_connectivity.envelope.envelope_correlation', 'envelope_correlation', (['data_hilbert'], {}), '(data_hilbert)\n', (4710, 4724), False, 'from mne_connectivity.envelope import envelope_correlation, symmetric_orth\n'), ((5448, 6049), 'numpy.array', 'np.array', (['[[[np.nan, 0.196734553900236, 0.063173148355451, -0.242638384630448], [\n 0.196734553900236, np.nan, 0.04179977549515, -0.088205187548542], [\n 0.063173148355451, 0.04179977549515, np.nan, 0.090331428512317], [-\n 0.242638384630448, -0.088205187548542, 0.090331428512317, np.nan]], [[\n np.nan, -0.01327085746289, 0.185200598081295, 0.140284351572544], [-\n 0.01327085746289, np.nan, 0.150981508043722, -0.000671809276372], [\n 0.185200598081295, 0.150981508043722, np.nan, 0.137460244313337], [\n 0.140284351572544, -0.000671809276372, 0.137460244313337, np.nan]]]', 'float'], {}), '([[[np.nan, 0.196734553900236, 0.063173148355451, -\n 0.242638384630448], [0.196734553900236, np.nan, 0.04179977549515, -\n 0.088205187548542], [0.063173148355451, 0.04179977549515, np.nan, \n 0.090331428512317], [-0.242638384630448, -0.088205187548542, \n 0.090331428512317, np.nan]], [[np.nan, -0.01327085746289, \n 0.185200598081295, 0.140284351572544], [-0.01327085746289, np.nan, \n 0.150981508043722, -0.000671809276372], [0.185200598081295, \n 0.150981508043722, np.nan, 0.137460244313337], [0.140284351572544, -\n 0.000671809276372, 0.137460244313337, np.nan]]], float)\n', (5456, 6049), True, 'import numpy as np\n'), ((6141, 6193), 'mne_connectivity.envelope.envelope_correlation', 'envelope_correlation', (['data'], {'log': '(True)', 'absolute': '(False)'}), '(data, log=True, absolute=False)\n', (6161, 6193), False, 'from mne_connectivity.envelope import envelope_correlation, symmetric_orth\n'), ((6454, 6478), 'numpy.random.RandomState', 'np.random.RandomState', (['(0)'], {}), '(0)\n', (6475, 6478), True, 'import numpy as np\n'), ((6591, 6603), 'numpy.eye', 'np.eye', (['n_ch'], {}), '(n_ch)\n', (6597, 6603), True, 'import numpy as np\n'), ((7218, 7231), 'numpy.diag', 'np.diag', (['vals'], {}), '(vals)\n', (7225, 7231), True, 'import numpy as np\n'), ((7243, 7259), 'numpy.diag', 'np.diag', (['(Z @ Z.T)'], {}), '(Z @ Z.T)\n', (7250, 7259), True, 'import numpy as np\n'), ((7264, 7293), 'numpy.testing.assert_array_less', 'assert_array_less', (['diag', 'orig'], {}), '(diag, orig)\n', (7281, 7293), False, 'from numpy.testing import assert_allclose, assert_array_equal, assert_array_less\n'), ((7317, 7352), 'numpy.testing.assert_array_less', 'assert_array_less', (['(orig * 0.1)', 'diag'], {}), '(orig * 0.1, diag)\n', (7334, 7352), False, 'from numpy.testing import assert_allclose, assert_array_equal, assert_array_less\n'), ((7383, 7401), 'numpy.triu', 'np.triu', (['vals'], {'k': '(1)'}), '(vals, k=1)\n', (7390, 7401), True, 'import numpy as np\n'), ((7406, 7443), 'numpy.testing.assert_allclose', 'assert_allclose', (['off', '(0.0)'], {'atol': '(1e-06)'}), '(off, 0.0, atol=1e-06)\n', (7421, 7443), False, 'from numpy.testing import assert_allclose, assert_array_equal, assert_array_less\n'), ((2203, 2263), 'pytest.raises', 'pytest.raises', (['RuntimeError'], {'match': '"""Passing in empty epochs"""'}), "(RuntimeError, match='Passing in empty epochs')\n", (2216, 2263), False, 'import pytest\n'), ((2273, 2307), 'mne_connectivity.envelope.envelope_correlation', 'envelope_correlation', (['data_hilbert'], {}), '(data_hilbert)\n', (2293, 2307), False, 'from mne_connectivity.envelope import envelope_correlation, symmetric_orth\n'), ((3446, 3511), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': '"""dtype must be float or complex"""'}), "(ValueError, match='dtype must be float or complex')\n", (3459, 3511), False, 'import pytest\n'), ((3569, 3628), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': '"""entry in data must be 2D"""'}), "(ValueError, match='entry in data must be 2D')\n", (3582, 3628), False, 'import pytest\n'), ((3638, 3676), 'mne_connectivity.envelope.envelope_correlation', 'envelope_correlation', (['data[np.newaxis]'], {}), '(data[np.newaxis])\n', (3658, 3676), False, 'from mne_connectivity.envelope import envelope_correlation, symmetric_orth\n'), ((3686, 3737), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': '"""n_nodes mismatch"""'}), "(ValueError, match='n_nodes mismatch')\n", (3699, 3737), False, 'import pytest\n'), ((3813, 3878), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': '"""Invalid value.*orthogonalize.*"""'}), "(ValueError, match='Invalid value.*orthogonalize.*')\n", (3826, 3878), False, 'import pytest\n'), ((3888, 3935), 'mne_connectivity.envelope.envelope_correlation', 'envelope_correlation', (['data'], {'orthogonalize': '"""foo"""'}), "(data, orthogonalize='foo')\n", (3908, 3935), False, 'from mne_connectivity.envelope import envelope_correlation, symmetric_orth\n'), ((4910, 4959), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': '"""Combine option"""'}), "(ValueError, match='Combine option')\n", (4923, 4959), False, 'import pytest\n'), ((5003, 5052), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': '"""Combine option"""'}), "(ValueError, match='Combine option')\n", (5016, 5052), False, 'import pytest\n'), ((6103, 6120), 'numpy.isnan', 'np.isnan', (['ft_vals'], {}), '(ft_vals)\n', (6111, 6120), True, 'import numpy as np\n'), ((6763, 6778), 'mne.utils.catch_logging', 'catch_logging', ([], {}), '()\n', (6776, 6778), False, 'from mne.utils import catch_logging, use_log_level\n'), ((6799, 6833), 'mne_connectivity.envelope.symmetric_orth', 'symmetric_orth', (['Z'], {'verbose': '"""debug"""'}), "(Z, verbose='debug')\n", (6813, 6833), False, 'from mne_connectivity.envelope import envelope_correlation, symmetric_orth\n'), ((7474, 7539), 'pytest.raises', 'pytest.raises', (['RuntimeError'], {'match': '"""at least as many time points"""'}), "(RuntimeError, match='at least as many time points')\n", (7487, 7539), False, 'import pytest\n'), ((7549, 7573), 'mne_connectivity.envelope.symmetric_orth', 'symmetric_orth', (['Z[:, :1]'], {}), '(Z[:, :1])\n', (7563, 7573), False, 'from mne_connectivity.envelope import envelope_correlation, symmetric_orth\n'), ((7583, 7637), 'pytest.warns', 'pytest.warns', (['RuntimeWarning'], {'match': '"""did not converge"""'}), "(RuntimeWarning, match='did not converge')\n", (7595, 7637), False, 'import pytest\n'), ((7647, 7674), 'mne_connectivity.envelope.symmetric_orth', 'symmetric_orth', (['Z'], {'n_iter': '(1)'}), '(Z, n_iter=1)\n', (7661, 7674), False, 'from mne_connectivity.envelope import envelope_correlation, symmetric_orth\n'), ((7732, 7784), 'pytest.warns', 'pytest.warns', (['RuntimeWarning'], {'match': '"""rank deficient"""'}), "(RuntimeWarning, match='rank deficient')\n", (7744, 7784), False, 'import pytest\n'), ((7794, 7815), 'mne_connectivity.envelope.symmetric_orth', 'symmetric_orth', (['Z_bad'], {}), '(Z_bad)\n', (7808, 7815), False, 'from mne_connectivity.envelope import envelope_correlation, symmetric_orth\n'), ((974, 983), 'numpy.abs', 'np.abs', (['x'], {}), '(x)\n', (980, 983), True, 'import numpy as np\n'), ((1193, 1209), 'numpy.abs', 'np.abs', (['y_orth_x'], {}), '(y_orth_x)\n', (1199, 1209), True, 'import numpy as np\n'), ((4491, 4500), 'numpy.abs', 'np.abs', (['x'], {}), '(x)\n', (4497, 4500), True, 'import numpy as np\n'), ((4778, 4799), 'numpy.mean', 'np.mean', (['data'], {'axis': '(0)'}), '(data, axis=0)\n', (4785, 4799), True, 'import numpy as np\n'), ((6922, 6944), 'mne.utils.use_log_level', 'use_log_level', (['"""debug"""'], {}), "('debug')\n", (6935, 6944), False, 'from mne.utils import catch_logging, use_log_level\n'), ((1288, 1320), 'numpy.corrcoef', 'np.corrcoef', (['x_mag', 'y_orth_x_mag'], {}), '(x_mag, y_orth_x_mag)\n', (1299, 1320), True, 'import numpy as np\n')] |
import gym
from gym import error, spaces, utils
from gym.utils import seeding
import numpy as np
import random
class TenArmedBanditGaussianRewardEnv(gym.Env):
metadata = {'render.modes': ['human']}
def __init__(self, seed=42):
self._seed(seed)
self.num_bandits = 10
# each reward distribution is a gaussian described using mean and standard deviation
self.reward_dist = [[random.uniform(0, 1), 0.5] for _ in range(self.num_bandits)]
self.action_space = spaces.Discrete(self.num_bandits)
self.observation_space = spaces.Discrete(1)
def _seed(self, seed=None):
self.np_random, seed = seeding.np_random(seed)
return [seed]
def step(self, action):
assert self.action_space.contains(action)
done = True
# sample reward using the corresponding reward distribution
reward = np.random.normal(self.reward_dist[action][0], self.reward_dist[action][1])
return 0, reward, done, {}
def reset(self):
return 0
def render(self, mode='human'):
pass
def close(self):
pass
| [
"numpy.random.normal",
"random.uniform",
"gym.spaces.Discrete",
"gym.utils.seeding.np_random"
] | [((503, 536), 'gym.spaces.Discrete', 'spaces.Discrete', (['self.num_bandits'], {}), '(self.num_bandits)\n', (518, 536), False, 'from gym import error, spaces, utils\n'), ((570, 588), 'gym.spaces.Discrete', 'spaces.Discrete', (['(1)'], {}), '(1)\n', (585, 588), False, 'from gym import error, spaces, utils\n'), ((653, 676), 'gym.utils.seeding.np_random', 'seeding.np_random', (['seed'], {}), '(seed)\n', (670, 676), False, 'from gym.utils import seeding\n'), ((884, 958), 'numpy.random.normal', 'np.random.normal', (['self.reward_dist[action][0]', 'self.reward_dist[action][1]'], {}), '(self.reward_dist[action][0], self.reward_dist[action][1])\n', (900, 958), True, 'import numpy as np\n'), ((414, 434), 'random.uniform', 'random.uniform', (['(0)', '(1)'], {}), '(0, 1)\n', (428, 434), False, 'import random\n')] |
import h5py as hdf
from functions import *
from sklearn.cluster import DBSCAN
from astLib import vec_astCalc
from astLib import astCoords
from numpy.lib import recfunctions as rfns
from calc_cluster_props import *
import pylab as pyl
# load RA/DEC/z data
f = hdf.File('../data/truth/Aardvark_v1.0c_truth_des_rotated.86.hdf5','r')
dset = f[list(f.keys())[0]]
truth = dset['RA', 'DEC', 'Z', 'HALOID']
f = hdf.File('../data/halos/Aardvark_v1.0_halos_r1_rotated.4.hdf5','r')
dset = f[list(f.keys())[0]]
halo = dset['HALOID', 'RA', 'DEC', 'Z', 'NGALS', 'M200']
# filter halos down
x = (halo['NGALS'] >= 5) & (halo['Z'] < 0.5) & (halo['M200'] >=1e13)
halo = halo[x]
# find the common halos
mask = pyl.in1d(truth['HALOID'], halo['HALOID'])
truth = truth[mask]
# find the haloids
haloids = pyl.intersect1d(halo['HALOID'], truth['HALOID'])
# find the indexes of the haloids in the halo list
inds = find_indices(halo['HALOID'], haloids)
# now we build the truth catalog with xx number of halos
# pick a few random halos
#randomHalos = pyl.random.choice(inds, 10)
randomHalos = pyl.array([42778, 1922, 2800, 5136, 9043, 42107, 42048, 37517,
4399, 9184])
for i in randomHalos:
x = pyl.where(truth['HALOID'] == halo['HALOID'][i])
t_part = truth[x[0]]
try:
t = pyl.append(t, t_part)
except NameError:
t = t_part
ra, dec, z = astCoords.eq2cart(halo['RA'][i], halo['DEC'][i],
vec_astCalc.dm(halo['Z'][i]))
print(ra, dec, z)
#print halo['RA'][i], halo['DEC'][i], halo['Z'][i]
print('members - ', len(x[0]))
print('mass - ', halo['M200'][i])
print('---------')
# add some noise
noise = pyl.zeros(round(len(t)*0.6), dtype=t.dtype)
noise['RA'] = 340 + pyl.random(round(len(t)*0.6)) * 11
noise['DEC'] = -14 - pyl.random(round(len(t)*0.6)) * 8
noise['Z'] = pyl.random(round(len(t)*0.6)) * 0.5
# add the noise to the data array
t = rfns.stack_arrays((t,noise), usemask=False)
# add extra fields to the array
t = updateArray2(t)
# add the mass information
for i in randomHalos:
x = t['HALOID'] == halo['HALOID'][i]
t['M200'][x] = halo['M200'][i]
# convert to physical units
X_,Y_,Z_ = astCoords.eq2cart(t['RA'], t['DEC'], vec_astCalc.dm(t['Z']))
# now we stack all the parts to pass to the cluster finder
rp = pyl.column_stack((X_,Y_,Z_))
# put it in a format it likes.
rp = pyl.array(rp.tolist())
# this does the finding
db = DBSCAN(eps=3, min_samples=6).fit(rp)
core_samples_mask = pyl.zeros_like(db.labels_, dtype=bool)
core_samples_mask[db.core_sample_indices_] = True
labels = db.labels_
unique_labels = set(labels)
# how many clusters?
n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)
for k in unique_labels:
if k == -1:
break
class_member_mask = (labels == k)
xy = rp[class_member_mask & core_samples_mask]
RA = pyl.mean(xy[:,0])
DEC = pyl.mean(xy[:,1])
Z = pyl.mean(xy[:,2])
print('cluster - ', k, 'RA - ', RA, 'DEC - ', DEC, 'z - ', Z)
print('members - ', len(xy))
# update the data array with the recovered information
t[class_member_mask & core_samples_mask] =\
findClusterCenterRedshift(t[class_member_mask & core_samples_mask])
t[class_member_mask & core_samples_mask] = findLOSV(t[class_member_mask &
core_samples_mask])
t['VD'][class_member_mask & core_samples_mask] =\
calcVD_big(t['LOSV'][class_member_mask & core_samples_mask])
t['MASS'][class_member_mask & core_samples_mask] =\
calc_mass_Saro(t[class_member_mask & core_samples_mask])
### BELOW HERE IS ALL OF THE PLOTTING THAT WE DO ###
| [
"pylab.where",
"numpy.lib.recfunctions.stack_arrays",
"pylab.column_stack",
"pylab.mean",
"astLib.vec_astCalc.dm",
"sklearn.cluster.DBSCAN",
"pylab.intersect1d",
"pylab.array",
"h5py.File",
"pylab.zeros_like",
"pylab.append",
"pylab.in1d"
] | [((261, 332), 'h5py.File', 'hdf.File', (['"""../data/truth/Aardvark_v1.0c_truth_des_rotated.86.hdf5"""', '"""r"""'], {}), "('../data/truth/Aardvark_v1.0c_truth_des_rotated.86.hdf5', 'r')\n", (269, 332), True, 'import h5py as hdf\n'), ((405, 473), 'h5py.File', 'hdf.File', (['"""../data/halos/Aardvark_v1.0_halos_r1_rotated.4.hdf5"""', '"""r"""'], {}), "('../data/halos/Aardvark_v1.0_halos_r1_rotated.4.hdf5', 'r')\n", (413, 473), True, 'import h5py as hdf\n'), ((695, 736), 'pylab.in1d', 'pyl.in1d', (["truth['HALOID']", "halo['HALOID']"], {}), "(truth['HALOID'], halo['HALOID'])\n", (703, 736), True, 'import pylab as pyl\n'), ((787, 835), 'pylab.intersect1d', 'pyl.intersect1d', (["halo['HALOID']", "truth['HALOID']"], {}), "(halo['HALOID'], truth['HALOID'])\n", (802, 835), True, 'import pylab as pyl\n'), ((1074, 1149), 'pylab.array', 'pyl.array', (['[42778, 1922, 2800, 5136, 9043, 42107, 42048, 37517, 4399, 9184]'], {}), '([42778, 1922, 2800, 5136, 9043, 42107, 42048, 37517, 4399, 9184])\n', (1083, 1149), True, 'import pylab as pyl\n'), ((1894, 1938), 'numpy.lib.recfunctions.stack_arrays', 'rfns.stack_arrays', (['(t, noise)'], {'usemask': '(False)'}), '((t, noise), usemask=False)\n', (1911, 1938), True, 'from numpy.lib import recfunctions as rfns\n'), ((2283, 2313), 'pylab.column_stack', 'pyl.column_stack', (['(X_, Y_, Z_)'], {}), '((X_, Y_, Z_))\n', (2299, 2313), True, 'import pylab as pyl\n'), ((2459, 2497), 'pylab.zeros_like', 'pyl.zeros_like', (['db.labels_'], {'dtype': 'bool'}), '(db.labels_, dtype=bool)\n', (2473, 2497), True, 'import pylab as pyl\n'), ((1190, 1237), 'pylab.where', 'pyl.where', (["(truth['HALOID'] == halo['HALOID'][i])"], {}), "(truth['HALOID'] == halo['HALOID'][i])\n", (1199, 1237), True, 'import pylab as pyl\n'), ((2194, 2216), 'astLib.vec_astCalc.dm', 'vec_astCalc.dm', (["t['Z']"], {}), "(t['Z'])\n", (2208, 2216), False, 'from astLib import vec_astCalc\n'), ((2831, 2849), 'pylab.mean', 'pyl.mean', (['xy[:, 0]'], {}), '(xy[:, 0])\n', (2839, 2849), True, 'import pylab as pyl\n'), ((2859, 2877), 'pylab.mean', 'pyl.mean', (['xy[:, 1]'], {}), '(xy[:, 1])\n', (2867, 2877), True, 'import pylab as pyl\n'), ((2885, 2903), 'pylab.mean', 'pyl.mean', (['xy[:, 2]'], {}), '(xy[:, 2])\n', (2893, 2903), True, 'import pylab as pyl\n'), ((1284, 1305), 'pylab.append', 'pyl.append', (['t', 't_part'], {}), '(t, t_part)\n', (1294, 1305), True, 'import pylab as pyl\n'), ((1426, 1454), 'astLib.vec_astCalc.dm', 'vec_astCalc.dm', (["halo['Z'][i]"], {}), "(halo['Z'][i])\n", (1440, 1454), False, 'from astLib import vec_astCalc\n'), ((2402, 2430), 'sklearn.cluster.DBSCAN', 'DBSCAN', ([], {'eps': '(3)', 'min_samples': '(6)'}), '(eps=3, min_samples=6)\n', (2408, 2430), False, 'from sklearn.cluster import DBSCAN\n')] |
import numpy as np
import time
class PacketModel(object):
"""Convert data to packets"""
def __init__(self, data, rowsPerPacket):
"""
# Arguments
data: 4-D tensor to be packetized
rowsPerPacket: number of rows of the feature map to be considered as one packet
"""
super(PacketModel, self).__init__()
self.rowsPerPacket = rowsPerPacket
self.dataShape = data.shape
self.packetSeq = self.dataToPacket(data)
def dataToPacket(self, data):
""" Converts 4D tensor to 5D tensor of packets
# Arguments
data: 4D tensor
# Returns
5D tensor
"""
self.numZeros = 0
if self.dataShape[1]%self.rowsPerPacket ==0:
data = np.reshape(data, (self.dataShape[0], -1, self.rowsPerPacket, self.dataShape[2], self.dataShape[3]))
return data
self.numZeros = self.rowsPerPacket - (self.dataShape[1]%self.rowsPerPacket)
zeros = np.zeros((self.dataShape[0], self.numZeros, self.dataShape[2], self.dataShape[3]))
data = np.concatenate((data, zeros), axis=1)
data = np.reshape(data, (self.dataShape[0], -1, self.rowsPerPacket, self.dataShape[2], self.dataShape[3]))
return data
def packetToData(self):
"""Converts the packets back to original 4D tensor
# Returns
4D tensor
"""
if self.numZeros == 0:
self.packetSeq = np.reshape(self.packetSeq, self.dataShape)
return self.packetSeq
self.packetSeq = np.reshape(self.packetSeq, (self.dataShape[0], -1, self.dataShape[2], self.dataShape[3]))
index = -1*self.numZeros
self.packetSeq = self.packetSeq[:, :index, :, :]
return self.packetSeq
| [
"numpy.zeros",
"numpy.reshape",
"numpy.concatenate"
] | [((1036, 1123), 'numpy.zeros', 'np.zeros', (['(self.dataShape[0], self.numZeros, self.dataShape[2], self.dataShape[3])'], {}), '((self.dataShape[0], self.numZeros, self.dataShape[2], self.\n dataShape[3]))\n', (1044, 1123), True, 'import numpy as np\n'), ((1143, 1180), 'numpy.concatenate', 'np.concatenate', (['(data, zeros)'], {'axis': '(1)'}), '((data, zeros), axis=1)\n', (1157, 1180), True, 'import numpy as np\n'), ((1205, 1309), 'numpy.reshape', 'np.reshape', (['data', '(self.dataShape[0], -1, self.rowsPerPacket, self.dataShape[2], self.\n dataShape[3])'], {}), '(data, (self.dataShape[0], -1, self.rowsPerPacket, self.dataShape\n [2], self.dataShape[3]))\n', (1215, 1309), True, 'import numpy as np\n'), ((1629, 1723), 'numpy.reshape', 'np.reshape', (['self.packetSeq', '(self.dataShape[0], -1, self.dataShape[2], self.dataShape[3])'], {}), '(self.packetSeq, (self.dataShape[0], -1, self.dataShape[2], self.\n dataShape[3]))\n', (1639, 1723), True, 'import numpy as np\n'), ((803, 907), 'numpy.reshape', 'np.reshape', (['data', '(self.dataShape[0], -1, self.rowsPerPacket, self.dataShape[2], self.\n dataShape[3])'], {}), '(data, (self.dataShape[0], -1, self.rowsPerPacket, self.dataShape\n [2], self.dataShape[3]))\n', (813, 907), True, 'import numpy as np\n'), ((1526, 1568), 'numpy.reshape', 'np.reshape', (['self.packetSeq', 'self.dataShape'], {}), '(self.packetSeq, self.dataShape)\n', (1536, 1568), True, 'import numpy as np\n')] |
#set matplotlib backend so figures can be saved in the background
import matplotlib
matplotlib.use("Agg")
#import the necessary packages
from sklearn.preprocessing import LabelBinarizer
from sklearn.metrics import classification_report
from utilities.nn.conv.minivggnet import MiniVGGNet
from keras.callbacks import LearningRateScheduler
from keras.optimizers import SGD
from keras.datasets import cifar10
import matplotlib.pyplot as plt
import numpy as np
output = "output/lr_decay_f0.25_plot.png"
"""
import argparse
ap= argparse.ArgumentParser()
ap.add_argument("-o", "--output", required=True, help="path to the output loss/accuracy plot")
args = vars(ap.parse_args())
"""
def step_decay(epoch):
#initialize the base learning rate, drop factor and the number of epochs after which the epoch should be dropped
initAlpha = 0.01
factor = 0.25
dropEvery = 5
#Calculate learning rate for the current epoch
alpha = initAlpha * (factor ** np.floor((1+epoch)/dropEvery))
#return the learning rate.
return float(alpha)
#load the training and testing data, then scale it into the range [0, 1]
print("[INFO] loading CIFAR-10 data")
((trainX, trainY), (testX, testY)) = cifar10.load_data( )
trainX = trainX.astype("float")/255.0
testX = testX.astype("float")/255.0
#convert the targets to vector/tensors
lb = LabelBinarizer()
trainY = lb.fit_transform(trainY)
testY = lb.transform(testY)
#initialize the label names for the CIFAR-10 dataset
labelNames=["airplane", "automobile", "bird", "cat", "deer", "dog", "frog", "horse", "ship", "truck"]
#define the set of callbacks to be passed to the model during Learning
callbacks = [LearningRateScheduler(step_decay)]
#initialize the optimizer and model
opt = SGD(lr=0.01, momentum = 0.9, nesterov=True)
model=MiniVGGNet.build(width=32, height=32, depth=3, classes=10)
model.compile(loss="categorical_crossentropy", optimizer=opt, metrics = ["accuracy"])
#train the model
model.fit(trainX, trainY, validation_data = (testX, testY), batch_size=64, epochs=40, callbacks = callbacks)
#evaluate the network
print("[INFO] evaluating network...")
predictions = model.predict(trainX, batch_size=64)
print(classification_report(testY.argmax(axis=1), predictions.argmax(axis=1), target_names=labelNames))
#plot the training loss and accuracy
plt.style.use("ggplot")
plt.figure()
plt.plot(range(40), H.history["loss"], label="train_loss")
plt.plot(range(40), H.history["val_loss"], label="val_loss")
plt.plot(range(40), H.history["acc"], label="train_acc")
plt.plot(range(40), H.history["val_acc"], label="val_acc")
plt.title("Training loss and Accuracy on CIFAR-10")
plt.xlabel("Epoch #")
plt.ylabel("Loss/Accuracy")
plt.legend()
plt.savefig(output) | [
"sklearn.preprocessing.LabelBinarizer",
"keras.callbacks.LearningRateScheduler",
"matplotlib.pyplot.savefig",
"keras.datasets.cifar10.load_data",
"matplotlib.pyplot.ylabel",
"matplotlib.use",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.xlabel",
"numpy.floor",
"matplotlib.pyplot.style.use",
"m... | [((84, 105), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (98, 105), False, 'import matplotlib\n'), ((1208, 1227), 'keras.datasets.cifar10.load_data', 'cifar10.load_data', ([], {}), '()\n', (1225, 1227), False, 'from keras.datasets import cifar10\n'), ((1350, 1366), 'sklearn.preprocessing.LabelBinarizer', 'LabelBinarizer', ([], {}), '()\n', (1364, 1366), False, 'from sklearn.preprocessing import LabelBinarizer\n'), ((1751, 1792), 'keras.optimizers.SGD', 'SGD', ([], {'lr': '(0.01)', 'momentum': '(0.9)', 'nesterov': '(True)'}), '(lr=0.01, momentum=0.9, nesterov=True)\n', (1754, 1792), False, 'from keras.optimizers import SGD\n'), ((1801, 1859), 'utilities.nn.conv.minivggnet.MiniVGGNet.build', 'MiniVGGNet.build', ([], {'width': '(32)', 'height': '(32)', 'depth': '(3)', 'classes': '(10)'}), '(width=32, height=32, depth=3, classes=10)\n', (1817, 1859), False, 'from utilities.nn.conv.minivggnet import MiniVGGNet\n'), ((2328, 2351), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""ggplot"""'], {}), "('ggplot')\n", (2341, 2351), True, 'import matplotlib.pyplot as plt\n'), ((2352, 2364), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (2362, 2364), True, 'import matplotlib.pyplot as plt\n'), ((2601, 2652), 'matplotlib.pyplot.title', 'plt.title', (['"""Training loss and Accuracy on CIFAR-10"""'], {}), "('Training loss and Accuracy on CIFAR-10')\n", (2610, 2652), True, 'import matplotlib.pyplot as plt\n'), ((2653, 2674), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Epoch #"""'], {}), "('Epoch #')\n", (2663, 2674), True, 'import matplotlib.pyplot as plt\n'), ((2675, 2702), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Loss/Accuracy"""'], {}), "('Loss/Accuracy')\n", (2685, 2702), True, 'import matplotlib.pyplot as plt\n'), ((2703, 2715), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (2713, 2715), True, 'import matplotlib.pyplot as plt\n'), ((2716, 2735), 'matplotlib.pyplot.savefig', 'plt.savefig', (['output'], {}), '(output)\n', (2727, 2735), True, 'import matplotlib.pyplot as plt\n'), ((1672, 1705), 'keras.callbacks.LearningRateScheduler', 'LearningRateScheduler', (['step_decay'], {}), '(step_decay)\n', (1693, 1705), False, 'from keras.callbacks import LearningRateScheduler\n'), ((968, 1001), 'numpy.floor', 'np.floor', (['((1 + epoch) / dropEvery)'], {}), '((1 + epoch) / dropEvery)\n', (976, 1001), True, 'import numpy as np\n')] |
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import fenics as fe
import time
from Core.HSolver import *
from Core.InvFun import *
from Core.AddNoise import *
plt.close()
# load the measuring data
# [sol_all, theta_all, kappa_all, qStrT]
dAR = np.load('/home/jjx323/Projects/ISP/Data/dataRc.npy')
dAI = np.load('/home/jjx323/Projects/ISP/Data/dataIc.npy')
uRT, uIT = dAR[0], dAI[0]
theta_all, kappa_all = dAR[1], dAR[2]
qStrT = dAR[3]
# add noise to the data
shapeU = uRT.shape
for i in range(shapeU[1]):
uRT[:,i], _ = addGaussianNoise(uRT[:,i], {'noise_level': 0.3, 'rate': 1})
uIT[:,i], _ = addGaussianNoise(uIT[:,i], {'noise_level': 0.3, 'rate': 1})
# -----------------------------------------------------------------------------
# specify basic parameters
domain_para = {'nx': 120, 'ny': 120, 'dPML': 0.15, 'xx': 2.0, 'yy': 2.0, \
'sig0': 1.5, 'p': 2.3}
domain = Domain(domain_para)
domain.geneMesh()
#
Ntheta, Nkappa = len(theta_all), len(kappa_all)
NN = Ntheta*Nkappa
NS = 400 # number of measuring points
points = genePoints(NS, 'full', domain_para)
measure = Sample(points)
equ_para = {'kappa': 0.0, 'theta': 0.0}
# init the scatterer
Fsol = Helmholtz(domain, equ_para)
Asol = Helmholtz(domain, equ_para)
Vreal, order = Fsol.getFunctionSpace('real')
# specify the true scatterer for test
q_funT = fe.interpolate(trueScatterer(qStrT, 3), Vreal)
eng2 = fe.assemble(fe.inner(q_funT, q_funT)*fe.dx)
# init the scatterer
q_fun = initScatterer(Vreal, 'Zero')
# init the force term
fR = fe.interpolate(fe.Constant(0.0), Vreal)
fI = fe.interpolate(fe.Constant(0.0), Vreal)
# specify the regularization term
reg = Regu('L2_1')
gamma = 0.05 # regularization parameter
cutL = 0.05
mesh_res1 = fe.RectangleMesh(fe.Point(cutL, cutL), fe.Point(domain.xx-cutL, \
domain.yy-cutL), 120, 120)
V_res1 = fe.FunctionSpace(mesh_res, 'P', 2)
drawF = 'False'
error_all, q_fun_all = [], []
# loop for inversion
iter_num = 0
flag = 'full' # assemble with all of the coefficients
for freIndx in range(Nkappa): # loop for frequencies
for angIndx in range(Ntheta): # loop for incident angle
equ_para['kappa'], equ_para['theta'] = kappa_all[freIndx], theta_all[angIndx]
# ---------------------------------------------------------------------
# solve forward problem
# init the source function
exp1 = 'cos(kappa*(x[0]*cos(theta)+x[1]*sin(theta)))'
uincR = fe.interpolate(fe.Expression(exp1, degree=3, kappa=equ_para['kappa'], \
theta=equ_para['theta']), Vreal)
exp2 = 'sin(kappa*(x[0]*cos(theta)+x[1]*sin(theta)))'
uincI = fe.interpolate(fe.Expression(exp2, degree=3, kappa=equ_para['kappa'], \
theta=equ_para['theta']), Vreal)
fR.vector()[:] = -(equ_para['kappa']**2)*q_fun.vector()[:]*uincR.vector()[:]
fI.vector()[:] = -(equ_para['kappa']**2)*q_fun.vector()[:]*uincI.vector()[:]
# solve equation
Fsol.geneForwardMatrix(flag, q_fun, equ_para['kappa'], fR, fI)
#start = time.time()
Fsol.solve()
uR, uI = fe.interpolate(Fsol.uReal, Vreal), fe.interpolate(Fsol.uImag, Vreal)
#end = time.time()
#print('1: ', end-start)
# ---------------------------------------------------------------------
# calculate residual
uRM = measure.sampling(Fsol.uReal)
uIM = measure.sampling(Fsol.uImag)
resR = uRT[:, iter_num] - uRM
resI = uIT[:, iter_num] - uIM
# ---------------------------------------------------------------------
# solve adjoint problem
# init the source function
Asol.geneForwardMatrix(flag, q_fun, equ_para['kappa']) # fR and fI is zero
# add point source
magnitudeR = -(equ_para['kappa']**2)*resR
magnitudeI = -(equ_para['kappa']**2)*(-resI)
Asol.addPointSourceR(points, magnitudeR)
Asol.addPointSourceI(points, magnitudeI)
# solve equation
#start = time.time()
Asol.solve()
uaR, uaI = fe.interpolate(Asol.uReal, Vreal), fe.interpolate(Asol.uImag, Vreal)
uaI.vector()[:] = -uaI.vector()[:]
#end = time.time()
#print('2: ', end-start)
# ---------------------------------------------------------------------
# calculate the gradient and update the scatterer
#start = time.time()
cR, cI = Fsol.get_s1s2(Vreal, 'vector')
Fdqv = (uincR.vector()[:] + cR*uR.vector()[:] - \
cI*uI.vector()[:])*uaR.vector()[:] + \
(uincI.vector()[:] + cR*uI.vector()[:] + \
cI*uR.vector()[:])*uaI.vector()[:]
# add the regularization term
# regrad = extend_smooth(Vreal, reg.evaGrad(extend_smooth(Vreal, q_fun, \
# V_res1), Vreal), V_res1)
q_fun_res = fe.interpolate(q_fun, V_res1)
regrad_res = reg.evaGrad(q_fun_res, V_res1)
regrad_res.set_allow_extrapolation(True)
regrad = fe.interpolate(regrad_res, Vreal)
grad_v = set_edge_zero(regrad.vector()[:], Vreal, domain, cutL)
if np.max(grad_v) > 0:
Fdqv = Fdqv + gamma*grad_v/np.max(grad_v)
else:
Fdqv = Fdqv + gamma*grad_v
# update the scatterer
q_fun.vector()[:] = q_fun.vector()[:] + 0.01*Fdqv
#end = time.time()
#print('3: ', end-start)
# only assemble coefficients concerned with q_fun
flag = 'simple'
# track the iteration
iter_num += 1
print('kappa = {:2}; angle = {:3.2f}; iter_num = {:3}'.format(equ_para['kappa'], \
equ_para['theta'], iter_num))
# evaluation of the error
eng1 = fe.assemble(fe.inner(q_funT-q_fun, q_funT-q_fun)*fe.dx)
error_temp = eng1/eng2
error_all.append(error_temp)
print('L2 norm error is {:.2f}%'.format(error_temp*100))
# draw and save the intermediate inversion results
if drawF == 'True':
plt.figure()
fig1 = fe.plot(q_fun)
plt.colorbar(fig1)
expN = '/home/jjx323/Projects/ISP/ResultsFig/invQ' + str(iter_num) + '.eps'
plt.savefig(expN, dpi=150)
plt.close()
q_fun_all.append(q_fun.vector()[:])
# -----------------------------------------------------------------------------
# postprocessing
#fe.plot(q_fun, mode="warp")
my_draw3D(q_fun, [-0.15, 2.15, -0.15, 2.15])
#plt.close()
# save inversion results
vtkfile = fe.File('/home/jjx323/Projects/ISP/ResultsFig/q_fun_c.pvd')
vtkfile << q_fun
# save matrix and reconstruct info
np.save('/home/jjx323/Projects/ISP/Results/q_fun_vector_c', [q_fun.vector()[:], \
domain_para, ['P', order], q_fun_all])
# error
plt.figure()
plt.plot(error_all)
plt.show()
print('The final L2 norm error is {:.2f}%'.format(error_all[-1]*100))
np.save('/home/jjx323/Projects/ISP/Results/errorAll_c', error_all)
en = fe.assemble(fe.inner(fe.grad(q_fun), fe.grad(q_fun))*fe.dx)
print('The value of regularization is {:.2f}'.format(en))
| [
"fenics.Constant",
"fenics.interpolate",
"fenics.Point",
"matplotlib.pyplot.savefig",
"fenics.inner",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.colorbar",
"fenics.FunctionSpace",
"numpy.max",
"matplotlib.pyplot.close",
"fenics.grad",
"matplotlib.pyplot.figure",
"fenics.Expression",
"fen... | [((209, 220), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (218, 220), True, 'import matplotlib.pyplot as plt\n'), ((294, 346), 'numpy.load', 'np.load', (['"""/home/jjx323/Projects/ISP/Data/dataRc.npy"""'], {}), "('/home/jjx323/Projects/ISP/Data/dataRc.npy')\n", (301, 346), True, 'import numpy as np\n'), ((353, 405), 'numpy.load', 'np.load', (['"""/home/jjx323/Projects/ISP/Data/dataIc.npy"""'], {}), "('/home/jjx323/Projects/ISP/Data/dataIc.npy')\n", (360, 405), True, 'import numpy as np\n'), ((1897, 1931), 'fenics.FunctionSpace', 'fe.FunctionSpace', (['mesh_res', '"""P"""', '(2)'], {}), "(mesh_res, 'P', 2)\n", (1913, 1931), True, 'import fenics as fe\n'), ((6582, 6641), 'fenics.File', 'fe.File', (['"""/home/jjx323/Projects/ISP/ResultsFig/q_fun_c.pvd"""'], {}), "('/home/jjx323/Projects/ISP/ResultsFig/q_fun_c.pvd')\n", (6589, 6641), True, 'import fenics as fe\n'), ((6831, 6843), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (6841, 6843), True, 'import matplotlib.pyplot as plt\n'), ((6844, 6863), 'matplotlib.pyplot.plot', 'plt.plot', (['error_all'], {}), '(error_all)\n', (6852, 6863), True, 'import matplotlib.pyplot as plt\n'), ((6864, 6874), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6872, 6874), True, 'import matplotlib.pyplot as plt\n'), ((6947, 7013), 'numpy.save', 'np.save', (['"""/home/jjx323/Projects/ISP/Results/errorAll_c"""', 'error_all'], {}), "('/home/jjx323/Projects/ISP/Results/errorAll_c', error_all)\n", (6954, 7013), True, 'import numpy as np\n'), ((1576, 1592), 'fenics.Constant', 'fe.Constant', (['(0.0)'], {}), '(0.0)\n', (1587, 1592), True, 'import fenics as fe\n'), ((1621, 1637), 'fenics.Constant', 'fe.Constant', (['(0.0)'], {}), '(0.0)\n', (1632, 1637), True, 'import fenics as fe\n'), ((1783, 1803), 'fenics.Point', 'fe.Point', (['cutL', 'cutL'], {}), '(cutL, cutL)\n', (1791, 1803), True, 'import fenics as fe\n'), ((1805, 1849), 'fenics.Point', 'fe.Point', (['(domain.xx - cutL)', '(domain.yy - cutL)'], {}), '(domain.xx - cutL, domain.yy - cutL)\n', (1813, 1849), True, 'import fenics as fe\n'), ((1443, 1467), 'fenics.inner', 'fe.inner', (['q_funT', 'q_funT'], {}), '(q_funT, q_funT)\n', (1451, 1467), True, 'import fenics as fe\n'), ((4990, 5019), 'fenics.interpolate', 'fe.interpolate', (['q_fun', 'V_res1'], {}), '(q_fun, V_res1)\n', (5004, 5019), True, 'import fenics as fe\n'), ((5138, 5171), 'fenics.interpolate', 'fe.interpolate', (['regrad_res', 'Vreal'], {}), '(regrad_res, Vreal)\n', (5152, 5171), True, 'import fenics as fe\n'), ((6107, 6119), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (6117, 6119), True, 'import matplotlib.pyplot as plt\n'), ((6135, 6149), 'fenics.plot', 'fe.plot', (['q_fun'], {}), '(q_fun)\n', (6142, 6149), True, 'import fenics as fe\n'), ((6158, 6176), 'matplotlib.pyplot.colorbar', 'plt.colorbar', (['fig1'], {}), '(fig1)\n', (6170, 6176), True, 'import matplotlib.pyplot as plt\n'), ((6269, 6295), 'matplotlib.pyplot.savefig', 'plt.savefig', (['expN'], {'dpi': '(150)'}), '(expN, dpi=150)\n', (6280, 6295), True, 'import matplotlib.pyplot as plt\n'), ((6304, 6315), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (6313, 6315), True, 'import matplotlib.pyplot as plt\n'), ((2512, 2591), 'fenics.Expression', 'fe.Expression', (['exp1'], {'degree': '(3)', 'kappa': "equ_para['kappa']", 'theta': "equ_para['theta']"}), "(exp1, degree=3, kappa=equ_para['kappa'], theta=equ_para['theta'])\n", (2525, 2591), True, 'import fenics as fe\n'), ((2740, 2819), 'fenics.Expression', 'fe.Expression', (['exp2'], {'degree': '(3)', 'kappa': "equ_para['kappa']", 'theta': "equ_para['theta']"}), "(exp2, degree=3, kappa=equ_para['kappa'], theta=equ_para['theta'])\n", (2753, 2819), True, 'import fenics as fe\n'), ((3208, 3241), 'fenics.interpolate', 'fe.interpolate', (['Fsol.uReal', 'Vreal'], {}), '(Fsol.uReal, Vreal)\n', (3222, 3241), True, 'import fenics as fe\n'), ((3243, 3276), 'fenics.interpolate', 'fe.interpolate', (['Fsol.uImag', 'Vreal'], {}), '(Fsol.uImag, Vreal)\n', (3257, 3276), True, 'import fenics as fe\n'), ((4161, 4194), 'fenics.interpolate', 'fe.interpolate', (['Asol.uReal', 'Vreal'], {}), '(Asol.uReal, Vreal)\n', (4175, 4194), True, 'import fenics as fe\n'), ((4196, 4229), 'fenics.interpolate', 'fe.interpolate', (['Asol.uImag', 'Vreal'], {}), '(Asol.uImag, Vreal)\n', (4210, 4229), True, 'import fenics as fe\n'), ((5255, 5269), 'numpy.max', 'np.max', (['grad_v'], {}), '(grad_v)\n', (5261, 5269), True, 'import numpy as np\n'), ((5853, 5893), 'fenics.inner', 'fe.inner', (['(q_funT - q_fun)', '(q_funT - q_fun)'], {}), '(q_funT - q_fun, q_funT - q_fun)\n', (5861, 5893), True, 'import fenics as fe\n'), ((7047, 7061), 'fenics.grad', 'fe.grad', (['q_fun'], {}), '(q_fun)\n', (7054, 7061), True, 'import fenics as fe\n'), ((7063, 7077), 'fenics.grad', 'fe.grad', (['q_fun'], {}), '(q_fun)\n', (7070, 7077), True, 'import fenics as fe\n'), ((5314, 5328), 'numpy.max', 'np.max', (['grad_v'], {}), '(grad_v)\n', (5320, 5328), True, 'import numpy as np\n')] |
"""The :mod:`search` module defines algorithms to search for Push programs."""
from abc import ABC, abstractmethod
from typing import Union, Tuple, Optional
import numpy as np
import math
from functools import partial
from multiprocessing import Pool, Manager
from pyshgp.push.program import ProgramSignature
from pyshgp.tap import tap
from pyshgp.utils import DiscreteProbDistrib
from pyshgp.gp.evaluation import Evaluator
from pyshgp.gp.genome import GeneSpawner, GenomeSimplifier
from pyshgp.gp.individual import Individual
from pyshgp.gp.population import Population
from pyshgp.gp.selection import Selector, get_selector
from pyshgp.gp.variation import VariationOperator, get_variation_operator
from pyshgp.utils import instantiate_using
class ParallelContext:
"""Holds the objects needed to coordinate parallelism."""
def __init__(self,
spawner: GeneSpawner,
evaluator: Evaluator,
n_proc: Optional[int] = None):
self.manager = Manager()
self.ns = self.manager.Namespace()
self.ns.spawner = spawner
self.ns.evaluator = evaluator
if n_proc is None:
self.pool = Pool()
else:
self.pool = Pool(n_proc)
class SearchConfiguration:
"""Configuration of an search algorithm.
@todo change to a PClass
Parameters
----------
evaluator : Evaluator
The Evaluator to use when evaluating individuals.
spawning : GeneSpawner
The GeneSpawner to use when producing Genomes during initialization and
variation.
selection : Union[Selector, DiscreteProbDistrib, str], optional
A Selector, or DiscreteProbDistrib of selectors, to use when selecting
parents. The default is lexicase selection.
variation : Union[VariationOperator, DiscreteProbDistrib, str], optional
A VariationOperator, or DiscreteProbDistrib of VariationOperators, to
use during variation. Default is SIZE_NEUTRAL_UMAD.
population_size : int, optional
The number of individuals hold in the population each generation. Default
is 300.
max_generations : int, optional
The number of generations to run the search algorithm. Default is 100.
error_threshold : float, optional
If the search algorithm finds an Individual with a total error less
than this values, stop searching. Default is 0.0.
initial_genome_size : Tuple[int, int], optional
The range of genome sizes to produce during initialization. Default is
(20, 100)
simplification_steps : int, optional
The number of simplification iterations to apply to the best Push program
produced by the search algorithm. Default is 2000.
parallelism : Union[Int, bool], optional
Set the number of processes to spawn for use when performing embarrassingly
parallel tasks. If false, no processes will spawn and compuation will be
serial. Default is true, which spawns one process per available cpu.
verbosity_config : Union[VerbosityConfig, str], optional
A VerbosityConfig controlling what is logged during the search. Default
is no verbosity.
"""
def __init__(self,
signature: ProgramSignature,
evaluator: Evaluator,
spawner: GeneSpawner,
selection: Union[Selector, DiscreteProbDistrib, str] = "lexicase",
variation: Union[VariationOperator, DiscreteProbDistrib, str] = "umad",
population_size: int = 500,
max_generations: int = 100,
error_threshold: float = 0.0,
initial_genome_size: Tuple[int, int] = (10, 50),
simplification_steps: int = 2000,
parallelism: Union[int, bool] = True,
**kwargs):
self.signature = signature
self.evaluator = evaluator
self.spawner = spawner
self.population_size = population_size
self.max_generations = max_generations
self.error_threshold = error_threshold
self.initial_genome_size = initial_genome_size
self.simplification_steps = simplification_steps
self.ext = kwargs
self.parallel_context = None
if isinstance(parallelism, bool):
if parallelism:
self.parallel_context = ParallelContext(spawner, evaluator)
elif parallelism > 1:
self.parallel_context = ParallelContext(spawner, evaluator, parallelism)
if isinstance(selection, Selector):
self.selection = DiscreteProbDistrib().add(selection, 1.0)
elif isinstance(selection, DiscreteProbDistrib):
self.selection = selection
else:
selector = get_selector(selection, **self.ext)
self.selection = DiscreteProbDistrib().add(selector, 1.0)
if isinstance(variation, VariationOperator):
self.variation = DiscreteProbDistrib().add(variation, 1.0)
elif isinstance(variation, DiscreteProbDistrib):
self.variation = variation
else:
variation_op = get_variation_operator(variation, **self.ext)
self.variation = DiscreteProbDistrib().add(variation_op, 1.0)
def get_selector(self):
"""Return a Selector."""
return self.selection.sample()
def get_variation_op(self):
"""Return a VariationOperator."""
return self.variation.sample()
def _spawn_individual(spawner, genome_size, program_signature: ProgramSignature, *args):
return Individual(spawner.spawn_genome(genome_size), program_signature)
class SearchAlgorithm(ABC):
"""Base class for all search algorithms.
Parameters
----------
config : SearchConfiguration
The configuation of the search algorithm.
Attributes
----------
config : SearchConfiguration
The configuration of the search algorithm.
generation : int
The current generation, or iteration, of the search.
best_seen : Individual
The best Individual, with respect to total error, seen so far.
population : Population
The current Population of individuals.
"""
def __init__(self, config: SearchConfiguration):
self.config = config
self._p_context = config.parallel_context
self.generation = 0
self.best_seen = None
self.population = None
self.init_population()
def init_population(self):
"""Initialize the population."""
spawner = self.config.spawner
init_gn_size = self.config.initial_genome_size
pop_size = self.config.population_size
signature = self.config.signature
self.population = Population()
if self._p_context is not None:
gen_func = partial(_spawn_individual, self._p_context.ns.spawner, init_gn_size, signature)
for indiv in self._p_context.pool.imap_unordered(gen_func, range(pop_size)):
self.population.add(indiv)
else:
for i in range(pop_size):
self.population.add(_spawn_individual(spawner, init_gn_size, signature))
@tap
@abstractmethod
def step(self) -> bool:
"""Perform one generation (step) of the search.
The step method should assume an evaluated Population, and must only
perform parent selection and variation (producing children). The step
method should modify the search algorithms population in-place, or
assign a new Population to the population attribute.
"""
pass
def _full_step(self) -> bool:
self.generation += 1
if self._p_context is not None:
self.population.p_evaluate(self._p_context.ns.evaluator, self._p_context.pool)
else:
self.population.evaluate(self.config.evaluator)
best_this_gen = self.population.best()
if self.best_seen is None or best_this_gen.total_error < self.best_seen.total_error:
self.best_seen = best_this_gen
if self.best_seen.total_error <= self.config.error_threshold:
return False
self.step()
return True
def is_solved(self) -> bool:
"""Return ``True`` if the search algorithm has found a solution or ``False`` otherwise."""
return self.best_seen.total_error <= self.config.error_threshold
@tap
def run(self) -> Individual:
"""Run the algorithm until termination."""
while self._full_step():
if self.generation >= self.config.max_generations:
break
# Simplify the best individual for a better generalization and interpretation.
simplifier = GenomeSimplifier(
self.config.evaluator,
self.config.signature
)
simp_genome, simp_error_vector = simplifier.simplify(
self.best_seen.genome,
self.best_seen.error_vector,
self.config.simplification_steps
)
simplified_best = Individual(simp_genome, self.config.signature)
simplified_best.error_vector = simp_error_vector
self.best_seen = simplified_best
return self.best_seen
class GeneticAlgorithm(SearchAlgorithm):
"""Genetic algorithm to synthesize Push programs.
An initial Population of random Individuals is created. Each generation
begins by evaluating all Individuals in the population. Then the current
Popluation is replaced with children produced by selecting parents from
the Population and applying VariationOperators to them.
"""
def __init__(self, config: SearchConfiguration):
super().__init__(config)
def _make_child(self) -> Individual:
op = self.config.get_variation_op()
selector = self.config.get_selector()
parent_genomes = [p.genome for p in selector.select(self.population, n=op.num_parents)]
child_genome = op.produce(parent_genomes, self.config.spawner)
return Individual(child_genome, self.config.signature)
@tap
def step(self):
"""Perform one generation (step) of the genetic algorithm.
The step method assumes an evaluated Population and performs parent
selection and variation (producing children).
"""
super().step()
self.population = Population(
[self._make_child() for _ in range(self.config.population_size)]
)
class SimulatedAnnealing(SearchAlgorithm):
"""Algorithm to synthesize Push programs with Simulated Annealing.
At each step (generation), the simulated annealing heuristic mutates the
current Individual, and probabilistically decides between accepting or
rejecting the child. If the child is accepted, it becomes the new current
Individual.
After each step, the simmulated annealing system cools its temperature.
As the temperature lowers, the probability of accepting a child that does
not have a lower total error than the current Individual decreases.
"""
def __init__(self, config: SearchConfiguration):
config.population_size = 1
for op in config.variation.elements:
assert op.num_parents <= 1, "SimulatedAnnealing cannot take multiple parant variation operators."
super().__init__(config)
def _get_temp(self, ):
"""Return the temperature."""
return 1.0 - (self.generation / self.config.max_generations)
def _acceptance(self, next_error):
"""Return probability of acceptance given an error."""
current_error = self.population.best().total_error
if np.isinf(current_error) or next_error < current_error:
return 1
else:
return math.exp(-(next_error - current_error) / self._get_temp())
@tap
def step(self):
"""Perform one generation, or step, of the Simulated Annealing.
The step method assumes an evaluated Population one Individual and
produces a single candidate Individual. If the candidate individual
passes the acceptance function, it becomes the Individual in the
Population.
"""
super().step()
if self._get_temp() <= 0:
return
candidate = Individual(
self.config.get_variation_op().produce(
[self.population.best().genome],
self.config.spawner
),
self.config.signature
)
candidate.error_vector = self.config.evaluator.evaluate(candidate.program)
acceptance_probability = self._acceptance(candidate.total_error)
if np.random.random() < acceptance_probability:
self.population = Population().add(candidate)
# @TODO: class EvolutionaryStrategy(SearchAlgorithm):
# ...
def get_search_algo(name: str, **kwargs) -> SearchAlgorithm:
"""Return the search algorithm class with the given name."""
name_to_cls = {
"GA": GeneticAlgorithm,
"SA": SimulatedAnnealing,
# "ES": EvolutionaryStrategy,
}
_cls = name_to_cls.get(name, None)
if _cls is None:
raise ValueError("No search algo '{nm}'. Supported names: {lst}.".format(
nm=name,
lst=list(name_to_cls.keys())
))
return instantiate_using(_cls, kwargs)
| [
"pyshgp.gp.genome.GenomeSimplifier",
"pyshgp.gp.variation.get_variation_operator",
"numpy.random.random",
"pyshgp.utils.instantiate_using",
"pyshgp.gp.population.Population",
"functools.partial",
"multiprocessing.Pool",
"multiprocessing.Manager",
"pyshgp.utils.DiscreteProbDistrib",
"numpy.isinf",
... | [((13319, 13350), 'pyshgp.utils.instantiate_using', 'instantiate_using', (['_cls', 'kwargs'], {}), '(_cls, kwargs)\n', (13336, 13350), False, 'from pyshgp.utils import instantiate_using\n'), ((1005, 1014), 'multiprocessing.Manager', 'Manager', ([], {}), '()\n', (1012, 1014), False, 'from multiprocessing import Pool, Manager\n'), ((6771, 6783), 'pyshgp.gp.population.Population', 'Population', ([], {}), '()\n', (6781, 6783), False, 'from pyshgp.gp.population import Population\n'), ((8756, 8818), 'pyshgp.gp.genome.GenomeSimplifier', 'GenomeSimplifier', (['self.config.evaluator', 'self.config.signature'], {}), '(self.config.evaluator, self.config.signature)\n', (8772, 8818), False, 'from pyshgp.gp.genome import GeneSpawner, GenomeSimplifier\n'), ((9072, 9118), 'pyshgp.gp.individual.Individual', 'Individual', (['simp_genome', 'self.config.signature'], {}), '(simp_genome, self.config.signature)\n', (9082, 9118), False, 'from pyshgp.gp.individual import Individual\n'), ((10044, 10091), 'pyshgp.gp.individual.Individual', 'Individual', (['child_genome', 'self.config.signature'], {}), '(child_genome, self.config.signature)\n', (10054, 10091), False, 'from pyshgp.gp.individual import Individual\n'), ((1181, 1187), 'multiprocessing.Pool', 'Pool', ([], {}), '()\n', (1185, 1187), False, 'from multiprocessing import Pool, Manager\n'), ((1226, 1238), 'multiprocessing.Pool', 'Pool', (['n_proc'], {}), '(n_proc)\n', (1230, 1238), False, 'from multiprocessing import Pool, Manager\n'), ((6847, 6926), 'functools.partial', 'partial', (['_spawn_individual', 'self._p_context.ns.spawner', 'init_gn_size', 'signature'], {}), '(_spawn_individual, self._p_context.ns.spawner, init_gn_size, signature)\n', (6854, 6926), False, 'from functools import partial\n'), ((11665, 11688), 'numpy.isinf', 'np.isinf', (['current_error'], {}), '(current_error)\n', (11673, 11688), True, 'import numpy as np\n'), ((12666, 12684), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (12682, 12684), True, 'import numpy as np\n'), ((4799, 4834), 'pyshgp.gp.selection.get_selector', 'get_selector', (['selection'], {}), '(selection, **self.ext)\n', (4811, 4834), False, 'from pyshgp.gp.selection import Selector, get_selector\n'), ((5167, 5212), 'pyshgp.gp.variation.get_variation_operator', 'get_variation_operator', (['variation'], {}), '(variation, **self.ext)\n', (5189, 5212), False, 'from pyshgp.gp.variation import VariationOperator, get_variation_operator\n'), ((4624, 4645), 'pyshgp.utils.DiscreteProbDistrib', 'DiscreteProbDistrib', ([], {}), '()\n', (4643, 4645), False, 'from pyshgp.utils import DiscreteProbDistrib\n'), ((4988, 5009), 'pyshgp.utils.DiscreteProbDistrib', 'DiscreteProbDistrib', ([], {}), '()\n', (5007, 5009), False, 'from pyshgp.utils import DiscreteProbDistrib\n'), ((12741, 12753), 'pyshgp.gp.population.Population', 'Population', ([], {}), '()\n', (12751, 12753), False, 'from pyshgp.gp.population import Population\n'), ((4864, 4885), 'pyshgp.utils.DiscreteProbDistrib', 'DiscreteProbDistrib', ([], {}), '()\n', (4883, 4885), False, 'from pyshgp.utils import DiscreteProbDistrib\n'), ((5242, 5263), 'pyshgp.utils.DiscreteProbDistrib', 'DiscreteProbDistrib', ([], {}), '()\n', (5261, 5263), False, 'from pyshgp.utils import DiscreteProbDistrib\n')] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.