code stringlengths 31 1.05M | apis list | extract_api stringlengths 97 1.91M |
|---|---|---|
"""
Module to plot a pie chart for the profiled sections of the code.
TODO: Fix legend box size conflict. Make font of legends smaller.
https://matplotlib.org/api/legend_api.html#matplotlib.legend.Legend
TODO: Create several charts instead of hierarchic pie charts..
"""
import os
import pickle
import numpy as np
## Plotting modules
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
# sns.set_style('whitegrid')
from .base import BasePlotter, get_os_friendly_name
import warnings
color_pool = [plt.cm.Blues, plt.cm.Oranges, plt.cm.Purples, plt.cm.Greens, plt.cm.pink, plt.cm.gray, plt.cm.Reds,
plt.cm.OrRd, plt.cm.magma, plt.cm.cividis, plt.cm.afmhot, plt.cm.PuBu, plt.cm.PuRd, plt.cm.ocean,
plt.cm.autumn, plt.cm.winter]
######################
def aggregate_prolog(prolog):
cum = {}
num = {}
avg = {}
for k in prolog.keys():
cum[k] = np.sum(prolog[k]["totals"])
num[k] = np.sum(prolog[k]["occurs"])
avg[k] = cum[k] / num[k]
return cum, num, avg
# def remove_root(D):
# val = D["/"]
# del D["/"]
# return val
#######################
# Routines for making the hierarchical data structure
def find_child_keys(keys, root):
if root == "":
return ["/"]
a = []
for k in keys:
if (os.path.split(k)[0] == root) and (k != "/"):
a.append(k)
return sorted(a)
def retrieve_children(D, root="/", root_value=None, collapse=False, collapse_threshold=0.1, other_threshold=0.01):
labels = find_child_keys(D.keys(), root)
values = []
for l in labels:
values.append(D[l])
if not labels == []:
# Sorting based on significance
values, labels = zip(*sorted(zip(values, labels), reverse=True))
labels = list(labels)
values = list(values)
# Decide on the total value.
if root_value:
T = root_value
elif root in D:
T = D[root]
else:
raise ValueError("We do not know the total value for", root)
S = sum(values)
# Add "other" slot if discrepency is larger than 1% total:
if S > T:
raise ValueError("How can children overall be greater than total time? S={}, T={}, root={}".format(S, T, root))
# Add "other" way in anyways ... We will remove it at the end if not that big.
labels.append(os.path.join(root, "other"))
values.append(T-S)
# Remove those keys that are under 10% of total and add them to "other"
if collapse:
to_be_collapsed = []
for i,l in enumerate(labels[:-1]):
if values[i] < collapse_threshold * T:
values[-1] += values[i]
to_be_collapsed.append(i)
for i in reversed(to_be_collapsed):
del labels[i]
del values[i]
# Sort based on values.
# Also check, if the total value is different than the root, then add a key called "other" at last.
# If other key not big enough then remove it:
if values[-1] < other_threshold * T:
values = values[:-1]
labels = labels[:-1]
return labels, values
# Make a Hierarchy
def make_hierarchy(cum, root, n_levels=1, **kwargs):
level_labels, level_values, level_colors = {}, {}, {}
main_values = {}
total = cum[root]
# Making colors
num_first_generation = len(find_child_keys(cum.keys(), root=root))
h_vec = np.linspace(0.,1., num_first_generation+1)[:-1] #
v_vec = np.linspace(.6,1., n_levels) # Based on # of levels
hsv0 = [0.0,1.0,0.4]
level_labels[0] = [root]
level_values[0] = [1.0]
level_colors[0] = np.concatenate((matplotlib.colors.hsv_to_rgb(hsv0),[1.]))
main_values[0] = [total]
# 1) Make a level based on the previous level.
# 2) Normalize it so it fits under its root.
# 3) Create the color spectrum
for level in range(1, n_levels+1):
level_labels[level] = []
level_values[level] = []
level_colors[level] = []
main_values[level] = []
prev_labels = level_labels[level-1]
prev_values = main_values[level-1]
for i,l in enumerate(prev_labels):
labs, vals = retrieve_children(cum, root=l, root_value=prev_values[i], **kwargs)
level_labels[level] += labs
main_values[level] += vals
# print(np.array(vals))
# print(prev_values[i])
level_values[level] += list(np.array(vals) / sum(vals) * prev_values[i])
# Making the color
if level == 1:
# hsv_vec = [np.array([h_vec[j], 1., v_vec[level-1]]) for j in range(len(labs))]
level_colors[level] = [color_pool[j](0.7) for j in range(len(labs))]
else:
# Retrieve hue from the very first generation.
# Based on l.
# Go back number of levels - 1
dirname = l
for level_up in range(level - 2):
dirname = os.path.dirname(dirname)
# key = os.path.sep + l.split(os.path.sep)[1:2][0]
k = level_labels[1].index(dirname)
h = matplotlib.colors.rgb_to_hsv(level_colors[1][k][:-1])[0]
s_vec = np.linspace(1.,.4, len(labs)) # In each row
hsv_vec = [np.array([h, s_vec[j], v_vec[level-1]]) for j in range(len(labs))]
# Convert the hsv_vec to rgba .
level_colors[level] += [np.concatenate((matplotlib.colors.hsv_to_rgb(hsv_vec[j]),[1.]))
for j in range(len(hsv_vec))]
return level_labels, level_values, level_colors
def whiten_hierarchy(level_labels, level_values, level_colors):
for level in level_labels:
for i in range(len(level_labels[level])):
if os.path.split(level_labels[level][i])[1] == "other":
level_colors[level][i] = np.array([1.,1.,1.,1.])
level_labels[level][i] = "_nolegend_"
return level_labels, level_values, level_colors
#################################
### The Profile Plotter Class ###
#################################
class ProPlot (BasePlotter):
def plot(self, keyx=None, keyy="/"):
"""
This function plots the reward function and saves the `.ext` and `.pkl` files.
To later reload the `.pkl` file, one can use the following (to change format, labels, etc.):
Example:
import matplotlib.pyplot as plt
%matplotlib notebook
import pickle
ax = pickle.load( open( "path_to_pkl_figure.pkl", "rb" ) )
ax.set_title("Alternative title")
plt.show()
See:
https://stackoverflow.com/a/12734723
"""
# assert len(keys) == 1, "We only support a single key at the moment."
# root = keys[0]
# root = self.options.get("root", "/")
root = keyy
fig, ax = self.init_plot()
if len(self.loaders) > 1:
raise ValueError("We do not support multiple loaders for profiler plots.")
loader = self.loaders[0]
if len(loader) > 1:
raise ValueError("We do not support multiple subloaders for profiler plots.")
subloader = self.loaders[0][0]
# Preparing data for plotting
prolog = subloader.getPrologLoader()
cum, num, avg = aggregate_prolog(prolog)
if not root in cum:
raise ValueError("The root:'{}' does not exist in the logged values.".format(root))
overall_time = cum[root]
frame_number = num[root]
average_time = avg[root]
## Print some statistics
# print("*"*41)
# print("* Time: {:6.1f} hours *".format(overall_time/3600.))
# print("* Frames: {:6.1f} million *".format(frame_number/1.e6))
# print("* Time for 1000x frames: {:6.1f} seconds *".format(1000.*average_time))
# print("*"*41)
# level_labels, level_values, level_colors = make_hierarchy(cum, "/", overall_time, 3, collapse=True, collapse_threshold=.05)
level_labels, level_values, level_colors = make_hierarchy(cum, root=root,
n_levels=self.options.get("n_levels", 3),
collapse=self.options.get("collapse", True),
collapse_threshold=self.options.get("collapse_threshold", .1))
# print("Hierarchy is comprised from:", level_labels)
# Whiten the other labels and colors
level_labels, level_values, level_colors = whiten_hierarchy(level_labels, level_values, level_colors)
bbox_extra_artists = self._plot_pie_chart(fig, ax, level_labels, level_values, level_colors)
ax.set_title("Time: {:4.2f} hours".format(overall_time/3600.))
self.close_plot(fig, ax, path=self.output_dir, name="profiler_"+get_os_friendly_name(root), bbox_extra_artists=bbox_extra_artists, save_pickle=False)
def _plot_pie_chart(self, fig, ax, level_labels, level_values, level_colors):
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.3, box.height])
legends = []
for level in sorted(list(set(level_values.keys())-{0})):
patches, texts = ax.pie(level_values[level], colors=level_colors[level],
radius=(2+level)*0.3,
# radius=(5-level)*0.3, # Reverse
# labeldistance=0.7,
startangle=self.options.get("startangle", 0),
counterclock=self.options.get("counterclock", True),
wedgeprops=dict(width=0.3, edgecolor='w'))
with warnings.catch_warnings():
warnings.simplefilter("ignore")
legends += [ax.legend(patches, level_labels[level], loc='center left', bbox_to_anchor=(1+(level-1)*self.options.get("spacing", 0.4), 0.5))]
# Set aspect ratio to be equal so that pie is drawn as a circle.
ax.axis('equal')
plt.tight_layout()
for l in legends:
ax.add_artist(l)
bbox_extra_artists = legends
return bbox_extra_artists
| [
"seaborn.set",
"matplotlib.colors.rgb_to_hsv",
"matplotlib.use",
"os.path.join",
"warnings.catch_warnings",
"os.path.split",
"numpy.sum",
"numpy.linspace",
"numpy.array",
"matplotlib.colors.hsv_to_rgb",
"os.path.dirname",
"matplotlib.pyplot.tight_layout",
"warnings.simplefilter"
] | [((361, 382), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (375, 382), False, 'import matplotlib\n'), ((437, 446), 'seaborn.set', 'sns.set', ([], {}), '()\n', (444, 446), True, 'import seaborn as sns\n'), ((3567, 3598), 'numpy.linspace', 'np.linspace', (['(0.6)', '(1.0)', 'n_levels'], {}), '(0.6, 1.0, n_levels)\n', (3578, 3598), True, 'import numpy as np\n'), ((957, 984), 'numpy.sum', 'np.sum', (["prolog[k]['totals']"], {}), "(prolog[k]['totals'])\n", (963, 984), True, 'import numpy as np\n'), ((1002, 1029), 'numpy.sum', 'np.sum', (["prolog[k]['occurs']"], {}), "(prolog[k]['occurs'])\n", (1008, 1029), True, 'import numpy as np\n'), ((2434, 2461), 'os.path.join', 'os.path.join', (['root', '"""other"""'], {}), "(root, 'other')\n", (2446, 2461), False, 'import os\n'), ((3504, 3551), 'numpy.linspace', 'np.linspace', (['(0.0)', '(1.0)', '(num_first_generation + 1)'], {}), '(0.0, 1.0, num_first_generation + 1)\n', (3515, 3551), True, 'import numpy as np\n'), ((10526, 10544), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (10542, 10544), True, 'import matplotlib.pyplot as plt\n'), ((3768, 3802), 'matplotlib.colors.hsv_to_rgb', 'matplotlib.colors.hsv_to_rgb', (['hsv0'], {}), '(hsv0)\n', (3796, 3802), False, 'import matplotlib\n'), ((6119, 6149), 'numpy.array', 'np.array', (['[1.0, 1.0, 1.0, 1.0]'], {}), '([1.0, 1.0, 1.0, 1.0])\n', (6127, 6149), True, 'import numpy as np\n'), ((10188, 10213), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {}), '()\n', (10211, 10213), False, 'import warnings\n'), ((10231, 10262), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""'], {}), "('ignore')\n", (10252, 10262), False, 'import warnings\n'), ((1360, 1376), 'os.path.split', 'os.path.split', (['k'], {}), '(k)\n', (1373, 1376), False, 'import os\n'), ((5152, 5176), 'os.path.dirname', 'os.path.dirname', (['dirname'], {}), '(dirname)\n', (5167, 5176), False, 'import os\n'), ((5332, 5385), 'matplotlib.colors.rgb_to_hsv', 'matplotlib.colors.rgb_to_hsv', (['level_colors[1][k][:-1]'], {}), '(level_colors[1][k][:-1])\n', (5360, 5385), False, 'import matplotlib\n'), ((5501, 5542), 'numpy.array', 'np.array', (['[h, s_vec[j], v_vec[level - 1]]'], {}), '([h, s_vec[j], v_vec[level - 1]])\n', (5509, 5542), True, 'import numpy as np\n'), ((6025, 6062), 'os.path.split', 'os.path.split', (['level_labels[level][i]'], {}), '(level_labels[level][i])\n', (6038, 6062), False, 'import os\n'), ((4588, 4602), 'numpy.array', 'np.array', (['vals'], {}), '(vals)\n', (4596, 4602), True, 'import numpy as np\n'), ((5688, 5728), 'matplotlib.colors.hsv_to_rgb', 'matplotlib.colors.hsv_to_rgb', (['hsv_vec[j]'], {}), '(hsv_vec[j])\n', (5716, 5728), False, 'import matplotlib\n')] |
import numpy as np
import matplotlib.pylab as plt
import tensorflow as tf
from keras.models import Model, Sequential
from keras.layers import Input, Activation, Dense
from keras.optimizers import SGD
# Generate data from -20, -19.75, -19.5, .... , 20
train_x = np.arange(-20, 20, 0.25)
# Calculate Target : sqrt(2x^2 + 1)
train_y = np.sqrt((2*train_x**2)+1)
# Create Network
inputs = Input(shape=(1,))
h_layer = Dense(8, activation='relu')(inputs)
h_layer = Dense(4, activation='relu')(h_layer)
outputs = Dense(1, activation='linear')(h_layer)
model = Model(inputs=inputs, outputs=outputs)
# Optimizer / Update Rule
sgd = SGD(lr=0.001)
# Compile the model with Mean Squared Error Loss
model.compile(optimizer=sgd, loss='mse')
# Train the network and save the weights after training
model.fit(train_x, train_y, batch_size=20, epochs=10000, verbose=1)
model.save_weights('weights.h5')
# Predict training data
predict = model.predict(np.array([26]))
print('f(26) = ', predict)
predict_y = model.predict(train_x)
# Draw target vs prediction
plt.plot(train_x, train_y, 'r')
plt.plot(train_x, predict_y, 'b')
plt.show() | [
"numpy.sqrt",
"numpy.array",
"keras.layers.Input",
"keras.optimizers.SGD",
"keras.models.Model",
"matplotlib.pylab.show",
"keras.layers.Dense",
"matplotlib.pylab.plot",
"numpy.arange"
] | [((262, 286), 'numpy.arange', 'np.arange', (['(-20)', '(20)', '(0.25)'], {}), '(-20, 20, 0.25)\n', (271, 286), True, 'import numpy as np\n'), ((334, 363), 'numpy.sqrt', 'np.sqrt', (['(2 * train_x ** 2 + 1)'], {}), '(2 * train_x ** 2 + 1)\n', (341, 363), True, 'import numpy as np\n'), ((387, 404), 'keras.layers.Input', 'Input', ([], {'shape': '(1,)'}), '(shape=(1,))\n', (392, 404), False, 'from keras.layers import Input, Activation, Dense\n'), ((555, 592), 'keras.models.Model', 'Model', ([], {'inputs': 'inputs', 'outputs': 'outputs'}), '(inputs=inputs, outputs=outputs)\n', (560, 592), False, 'from keras.models import Model, Sequential\n'), ((626, 639), 'keras.optimizers.SGD', 'SGD', ([], {'lr': '(0.001)'}), '(lr=0.001)\n', (629, 639), False, 'from keras.optimizers import SGD\n'), ((1045, 1076), 'matplotlib.pylab.plot', 'plt.plot', (['train_x', 'train_y', '"""r"""'], {}), "(train_x, train_y, 'r')\n", (1053, 1076), True, 'import matplotlib.pylab as plt\n'), ((1077, 1110), 'matplotlib.pylab.plot', 'plt.plot', (['train_x', 'predict_y', '"""b"""'], {}), "(train_x, predict_y, 'b')\n", (1085, 1110), True, 'import matplotlib.pylab as plt\n'), ((1111, 1121), 'matplotlib.pylab.show', 'plt.show', ([], {}), '()\n', (1119, 1121), True, 'import matplotlib.pylab as plt\n'), ((415, 442), 'keras.layers.Dense', 'Dense', (['(8)'], {'activation': '"""relu"""'}), "(8, activation='relu')\n", (420, 442), False, 'from keras.layers import Input, Activation, Dense\n'), ((461, 488), 'keras.layers.Dense', 'Dense', (['(4)'], {'activation': '"""relu"""'}), "(4, activation='relu')\n", (466, 488), False, 'from keras.layers import Input, Activation, Dense\n'), ((508, 537), 'keras.layers.Dense', 'Dense', (['(1)'], {'activation': '"""linear"""'}), "(1, activation='linear')\n", (513, 537), False, 'from keras.layers import Input, Activation, Dense\n'), ((937, 951), 'numpy.array', 'np.array', (['[26]'], {}), '([26])\n', (945, 951), True, 'import numpy as np\n')] |
import numpy as np
# # blind A
# # Z_Bbin sigma_e neff
# # Flag_SOM_Fid
# 0.1<ZB<=0.3 0.27085526185463465 0.6141903412434272
# 0.3<ZB<=0.5 0.260789170603278 1.1714443526924525
# 0.5<ZB<=0.7 0.27664489739710685 1.8306617593091257
# 0.7<ZB<=0.9 0.2616226704859973 1.2340324684694277
# 0.9<ZB<=1.2 0.2818628832701304 1.2777696421274052
# # blind B
# # Z_Bbin sigma_e neff
# # Flag_SOM_Fid
# 0.1<ZB<=0.3 0.26842505878253875 0.6187082608962824
# 0.3<ZB<=0.5 0.25501768080905934 1.1942152882679087
# 0.5<ZB<=0.7 0.2684949317660632 1.8820489105766731
# 0.7<ZB<=0.9 0.24635057301164487 1.2898847904777375
# 0.9<ZB<=1.2 0.2588042476903187 1.3531528640732855
# # blind C
# # Z_Bbin sigma_e neff
# # Flag_SOM_Fid
# 0.1<ZB<=0.3 0.2696215956290229 0.6163756250182619
# 0.3<ZB<=0.5 0.25788498381059144 1.1821211132939125
# 0.5<ZB<=0.7 0.2725868234515691 1.8541025952232577
# 0.7<ZB<=0.9 0.25393725942022516 1.259196379102648
# 0.9<ZB<=1.2 0.2702738432562588 1.3108755093653546
ngal_A_in=np.asarray([0.6141903412434272,
1.1714443526924525,
1.8306617593091257,
1.2340324684694277,
1.2777696421274052])
ngal_B_in=np.asarray([0.6187082608962824,
1.1942152882679087,
1.8820489105766731,
1.2898847904777375,
1.3531528640732855])
ngal_C_in=np.asarray([0.6163756250182619,
1.1821211132939125,
1.8541025952232577,
1.259196379102648,
1.3108755093653546])
area_omegacam = 777.406
area_healpix4096 = 866.924
ngal_A = ngal_A_in*area_omegacam/area_healpix4096
ngal_B = ngal_B_in*area_omegacam/area_healpix4096
ngal_C = ngal_C_in*area_omegacam/area_healpix4096
np.savetxt('ngal_blindA.ascii',ngal_A.reshape(1,len(ngal_A)),fmt='%1.8f')
np.savetxt('ngal_blindB.ascii',ngal_B.reshape(1,len(ngal_B)),fmt='%1.8f')
np.savetxt('ngal_blindC.ascii',ngal_C.reshape(1,len(ngal_C)),fmt='%1.8f')
sigma_e_A=np.asarray([0.27085526185463465,
0.260789170603278,
0.27664489739710685,
0.2616226704859973,
0.2818628832701304])
sigma_e_B=np.asarray([0.26842505878253875,
0.25501768080905934,
0.2684949317660632,
0.24635057301164487,
0.2588042476903187])
sigma_e_C=np.asarray([0.2696215956290229,
0.25788498381059144,
0.2725868234515691,
0.25393725942022516,
0.2702738432562588])
np.savetxt('../ellipticity_dispersion/sigma_e_blindA.ascii',sigma_e_A.reshape(1,len(sigma_e_A)),fmt='%1.8f')
np.savetxt('../ellipticity_dispersion/sigma_e_blindB.ascii',sigma_e_B.reshape(1,len(sigma_e_B)),fmt='%1.8f')
np.savetxt('../ellipticity_dispersion/sigma_e_blindC.ascii',sigma_e_C.reshape(1,len(sigma_e_C)),fmt='%1.8f')
# old values with wrong zbin edges
# ngal_A_in=np.asarray([0.5696062756935643, 1.1420051774183186, 1.820071990524645, 1.257355966105446, 1.3150376529887304])
# ngal_B_in=np.asarray([0.5738808446605536, 1.1635165129209137, 1.870408698085444, 1.312215197103098, 1.3923624557726593])
# ngal_C_in=np.asarray([0.5716711629725594, 1.1520993491907465, 1.843051137595057, 1.282128974674171, 1.3490061651057792])
# old values with wrong zbin edges:
# sigma_e_a=[ 0.271501816130848, 0.2615574190604257, 0.2754555314207977, 0.2625519982871117, 0.2812947994992024]
# sigma_e_b=[ 0.269029592008083, 0.2559736564818429, 0.2674527764112131, 0.2480196700309332, 0.2583321479620859]
# sigma_e_c=[ 0.270247406769942, 0.2587478515919105, 0.2714697072625222, 0.2552422429840755, 0.2697528938767397]
| [
"numpy.asarray"
] | [((978, 1095), 'numpy.asarray', 'np.asarray', (['[0.6141903412434272, 1.1714443526924525, 1.8306617593091257, \n 1.2340324684694277, 1.2777696421274052]'], {}), '([0.6141903412434272, 1.1714443526924525, 1.8306617593091257, \n 1.2340324684694277, 1.2777696421274052])\n', (988, 1095), True, 'import numpy as np\n'), ((1130, 1247), 'numpy.asarray', 'np.asarray', (['[0.6187082608962824, 1.1942152882679087, 1.8820489105766731, \n 1.2898847904777375, 1.3531528640732855]'], {}), '([0.6187082608962824, 1.1942152882679087, 1.8820489105766731, \n 1.2898847904777375, 1.3531528640732855])\n', (1140, 1247), True, 'import numpy as np\n'), ((1282, 1398), 'numpy.asarray', 'np.asarray', (['[0.6163756250182619, 1.1821211132939125, 1.8541025952232577, \n 1.259196379102648, 1.3108755093653546]'], {}), '([0.6163756250182619, 1.1821211132939125, 1.8541025952232577, \n 1.259196379102648, 1.3108755093653546])\n', (1292, 1398), True, 'import numpy as np\n'), ((1865, 1983), 'numpy.asarray', 'np.asarray', (['[0.27085526185463465, 0.260789170603278, 0.27664489739710685, \n 0.2616226704859973, 0.2818628832701304]'], {}), '([0.27085526185463465, 0.260789170603278, 0.27664489739710685, \n 0.2616226704859973, 0.2818628832701304])\n', (1875, 1983), True, 'import numpy as np\n'), ((2019, 2139), 'numpy.asarray', 'np.asarray', (['[0.26842505878253875, 0.25501768080905934, 0.2684949317660632, \n 0.24635057301164487, 0.2588042476903187]'], {}), '([0.26842505878253875, 0.25501768080905934, 0.2684949317660632, \n 0.24635057301164487, 0.2588042476903187])\n', (2029, 2139), True, 'import numpy as np\n'), ((2174, 2293), 'numpy.asarray', 'np.asarray', (['[0.2696215956290229, 0.25788498381059144, 0.2725868234515691, \n 0.25393725942022516, 0.2702738432562588]'], {}), '([0.2696215956290229, 0.25788498381059144, 0.2725868234515691, \n 0.25393725942022516, 0.2702738432562588])\n', (2184, 2293), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
from __future__ import print_function
import torch
import h5py
import numpy as np
class DatasetHDF5(torch.utils.data.Dataset):
def __init__(self, hdf5fn, t, transform=None, target_transform=None):
"""
t: 'train' or 'val'
"""
super(DatasetHDF5, self).__init__()
self.hf = h5py.File(hdf5fn, 'r', libver='latest', swmr=True)
self.t = t
self.n_images= self.hf['%s_img'%self.t].shape[0]
self.dlabel = self.hf['%s_labels'%self.t][...]
self.transform = transform
self.target_transform = target_transform
def _get_dataset_x_and_target(self, index):
d = self.hf['%s_img'%self.t]
img = d[index, ...]
target = self.dlabel[index]
#if target < 0 or target > 999:
# print('ERROR target: ', index, target)
# raise
return img, np.int64(target)
def __getitem__(self, index):
img, target = self._get_dataset_x_and_target(index)
if self.transform is not None:
img = self.transform(img)
if self.target_transform is not None:
target = self.target_transform(target)
return img, target
def __len__(self):
return self.n_images
| [
"numpy.int64",
"h5py.File"
] | [((341, 391), 'h5py.File', 'h5py.File', (['hdf5fn', '"""r"""'], {'libver': '"""latest"""', 'swmr': '(True)'}), "(hdf5fn, 'r', libver='latest', swmr=True)\n", (350, 391), False, 'import h5py\n'), ((888, 904), 'numpy.int64', 'np.int64', (['target'], {}), '(target)\n', (896, 904), True, 'import numpy as np\n')] |
import json
import numpy as np
from flightsim.shapes import Cuboid
class World(object):
def __init__(self, world_data):
"""
Construct World object from data. Instead of using this constructor
directly, see also class methods 'World.from_file()' for building a
world from a saved .json file or 'World.grid_forest()' for building a
world object of a parameterized style.
Parameters:
world_data, dict containing keys 'bounds' and 'blocks'
bounds, dict containing key 'extents'
extents, list of [xmin, xmax, ymin, ymax, zmin, zmax]
blocks, list of dicts containing keys 'extents' and 'color'
extents, list of [xmin, xmax, ymin, ymax, zmin, zmax]
color, color specification
"""
self.world = world_data
@classmethod
def from_file(cls, filename):
"""
Read world definition from a .json text file and return World object.
Parameters:
filename
Returns:
world, World object
Example use:
my_world = World.from_file('my_filename.json')
"""
with open(filename) as file:
return cls(json.load(file))
def to_file(self, filename):
"""
Write world definition to a .json text file.
Parameters:
filename
Example use:
my_word.to_file('my_filename.json')
"""
with open(filename, 'w') as file:
# Dump dict into stream for .json file.
stream = json.dumps(self.world)
# Adjust whitespace for more readable output (optional).
stream = stream.replace('{"extents"','\n{"extents"')
stream = stream.replace('"blocks"', '\n"blocks"')
stream = stream.replace('"bounds"', '\n"bounds"')
stream = stream.replace('}]}', '}]\n}')
# Write file.
file.write(stream)
def draw(self, ax):
"""
Draw world onto existing Axes3D axes and return artists corresponding to the
blocks.
Parameters:
ax, Axes3D object
Returns:
block_artists, list of Artists associated with blocks
Example use:
my_world.draw(ax)
"""
(xmin, xmax, ymin, ymax, zmin, zmax) = self.world['bounds']['extents']
# Set axes limits all equal to approximate 'axis equal' display.
x_width = xmax-xmin
y_width = ymax-ymin
z_width = zmax-zmin
width = np.max((x_width, y_width, z_width))
ax.set_xlim((xmin, xmin+width))
ax.set_ylim((ymin, ymin+width))
ax.set_zlim((zmin, zmin+width))
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
# This doesn't look nice because the z-order isn't sophisticated enough.
# wireframe = Cuboid(ax, xmax-xmin, ymax-ymin, zmax-zmin, alpha=0, linewidth=1, edgecolors='k')
# wireframe.transform((xmin,ymin,zmin))
blocks = self.world['blocks']
block_artists = []
for b in blocks:
(xmin, xmax, ymin, ymax, zmin, zmax) = b['extents']
c = Cuboid(ax, xmax-xmin, ymax-ymin, zmax-zmin, alpha=0.6, linewidth=1, edgecolors='k')
c.transform(position=(xmin, ymin, zmin))
block_artists.extend(c.artists)
return block_artists
# The follow class methods are convenience functions for building different
# kinds of parametric worlds.
@classmethod
def empty(cls, extents):
"""
Return World object for bounded empty space.
Parameters:
extents, tuple of (xmin, xmax, ymin, ymax, zmin, zmax)
Returns:
world, World object
Example use:
my_world = World.empty((xmin, xmax, ymin, ymax, zmin, zmax))
"""
bounds = {'extents': extents}
blocks = []
world_data = {'bounds':bounds, 'blocks':blocks}
return cls(world_data)
@classmethod
def grid_forest(cls, n_rows, n_cols, width, height, spacing):
"""
Return World object describing a grid forest world parameterized by
arguments. The boundary extents fit tightly to the included trees.
Parameters:
n_rows, rows of trees stacked in the y-direction
n_cols, columns of trees stacked in the x-direction
width, weight of square cross section trees
height, height of trees
spacing, spacing between centers of rows and columns
Returns:
world, World object
Example use:
my_world = World.grid_forest()
"""
# Bounds are outer boundary for world, which are an implicit obstacle.
x_max = (n_cols-1)*spacing + width
y_max = (n_rows-1)*spacing + width
bounds = {'extents': [0, x_max, 0, y_max, 0, height]}
# Blocks are obstacles in the environment.
x_root = spacing * np.arange(n_cols)
y_root = spacing * np.arange(n_rows)
blocks = []
for x in x_root:
for y in y_root:
blocks.append({'extents': [x, x+width, y, y+width, 0, height], 'color': [1, 0, 0]})
world_data = {'bounds':bounds, 'blocks':blocks}
return cls(world_data)
if __name__ == '__main__':
from axes3ds import Axes3Ds
import matplotlib.pyplot as plt
# Test grid_forest world.
world = World.grid_forest(n_rows=4, n_cols=3, width=0.5, height=3.0, spacing=2.0)
# Save to file.
world.to_file('worlds/grid_forest.json')
# Build a new world from the saved file.
world = World.from_file('worlds/grid_forest.json')
# Draw.
fig = plt.figure()
ax = Axes3Ds(fig)
world.draw(ax)
# Draw all plots.
plt.show()
| [
"axes3ds.Axes3Ds",
"json.dumps",
"numpy.max",
"matplotlib.pyplot.figure",
"json.load",
"flightsim.shapes.Cuboid",
"numpy.arange",
"matplotlib.pyplot.show"
] | [((5773, 5785), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (5783, 5785), True, 'import matplotlib.pyplot as plt\n'), ((5795, 5807), 'axes3ds.Axes3Ds', 'Axes3Ds', (['fig'], {}), '(fig)\n', (5802, 5807), False, 'from axes3ds import Axes3Ds\n'), ((5854, 5864), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5862, 5864), True, 'import matplotlib.pyplot as plt\n'), ((2595, 2630), 'numpy.max', 'np.max', (['(x_width, y_width, z_width)'], {}), '((x_width, y_width, z_width))\n', (2601, 2630), True, 'import numpy as np\n'), ((1615, 1637), 'json.dumps', 'json.dumps', (['self.world'], {}), '(self.world)\n', (1625, 1637), False, 'import json\n'), ((3237, 3330), 'flightsim.shapes.Cuboid', 'Cuboid', (['ax', '(xmax - xmin)', '(ymax - ymin)', '(zmax - zmin)'], {'alpha': '(0.6)', 'linewidth': '(1)', 'edgecolors': '"""k"""'}), "(ax, xmax - xmin, ymax - ymin, zmax - zmin, alpha=0.6, linewidth=1,\n edgecolors='k')\n", (3243, 3330), False, 'from flightsim.shapes import Cuboid\n'), ((5048, 5065), 'numpy.arange', 'np.arange', (['n_cols'], {}), '(n_cols)\n', (5057, 5065), True, 'import numpy as np\n'), ((5093, 5110), 'numpy.arange', 'np.arange', (['n_rows'], {}), '(n_rows)\n', (5102, 5110), True, 'import numpy as np\n'), ((1260, 1275), 'json.load', 'json.load', (['file'], {}), '(file)\n', (1269, 1275), False, 'import json\n')] |
import os
import math
from pprint import PrettyPrinter
import random
import numpy as np
import torch # Torch must be imported before sklearn and tf
import sklearn
import tensorflow as tf
import better_exceptions
from tqdm import tqdm, trange
import colorlog
import colorful
from utils.etc_utils import set_logger, set_tcmalloc, set_gpus, check_none_gradients
from utils import config_utils, custom_argparsers
from models import MODELS
from modules.checkpoint_tracker import CheckpointTracker
from modules.trainer import run_wow_evaluation, Trainer
from modules.from_parlai import download_from_google_drive, unzip
from data.wizard_of_wikipedia import WowDatasetReader
from data.holle import HolleDatasetReader
better_exceptions.hook()
_command_args = config_utils.CommandArgs()
pprint = PrettyPrinter().pprint
pformat = PrettyPrinter().pformat
BEST_N_CHECKPOINTS = 5
def main():
# Argument passing/parsing
args, model_args = config_utils.initialize_argparser(
MODELS, _command_args, custom_argparsers.DialogArgumentParser)
hparams, hparams_dict = config_utils.create_or_load_hparams(
args, model_args, args.cfg)
pprint(hparams_dict)
# Set environment variables & gpus
set_logger()
set_gpus(hparams.gpus)
set_tcmalloc()
gpus = tf.config.experimental.list_physical_devices('GPU')
tf.config.experimental.set_visible_devices(gpus, 'GPU')
for gpu in gpus:
tf.config.experimental.set_memory_growth(gpu, True)
# Set random seed
tf.random.set_seed(hparams.random_seed)
np.random.seed(hparams.random_seed)
random.seed(hparams.random_seed)
# For multi-gpu
if hparams.num_gpus > 1:
mirrored_strategy = tf.distribute.MirroredStrategy() # NCCL will be used as default
else:
mirrored_strategy = None
# Download BERT pretrained model
if not os.path.exists(hparams.bert_dir):
os.makedirs(hparams.bert_dir)
fname = 'uncased_L-12_H-768_A-12.zip'
gd_id = '17rfV9CleFBwwfS7m5Yd72vvxdPLWBHl6'
download_from_google_drive(gd_id, os.path.join(hparams.bert_dir, fname))
unzip(hparams.bert_dir, fname)
# Make dataset reader
os.makedirs(hparams.cache_dir, exist_ok=True)
if hparams.data_name == "wizard_of_wikipedia":
reader_cls = WowDatasetReader
elif hparams.data_name == "holle":
reader_cls = HolleDatasetReader
else:
raise ValueError("data_name must be one of 'wizard_of_wikipedia' and 'holle'")
reader = reader_cls(
hparams.batch_size, hparams.num_epochs,
buffer_size=hparams.buffer_size,
bucket_width=hparams.bucket_width,
max_length=hparams.max_length,
max_episode_length=hparams.max_episode_length,
max_knowledge=hparams.max_knowledge,
knowledge_truncate=hparams.knowledge_truncate,
cache_dir=hparams.cache_dir,
bert_dir=hparams.bert_dir,
)
train_dataset, iters_in_train = reader.read('train', mirrored_strategy)
test_dataset, iters_in_test = reader.read('test', mirrored_strategy)
if hparams.data_name == 'wizard_of_wikipedia':
unseen_dataset, iters_in_unseen = reader.read('test_unseen', mirrored_strategy)
vocabulary = reader.vocabulary
# Build model & optimizer & trainer
if mirrored_strategy:
with mirrored_strategy.scope():
model = MODELS[hparams.model](hparams, vocabulary)
optimizer = tf.keras.optimizers.Adam(learning_rate=hparams.init_lr,
clipnorm=hparams.clipnorm)
else:
model = MODELS[hparams.model](hparams, vocabulary)
optimizer = tf.keras.optimizers.Adam(learning_rate=hparams.init_lr,
clipnorm=hparams.clipnorm)
trainer = Trainer(model, optimizer, mirrored_strategy,
hparams.enable_function,
reader_cls.remove_pad)
# misc (tensorboard, checkpoints)
file_writer = tf.summary.create_file_writer(hparams.checkpoint_dir)
file_writer.set_as_default()
global_step = tf.compat.v1.train.get_or_create_global_step()
checkpoint = tf.train.Checkpoint(optimizer=optimizer,
model=model,
optimizer_step=global_step)
checkpoint_manager = tf.train.CheckpointManager(checkpoint,
directory=hparams.checkpoint_dir,
max_to_keep=hparams.max_to_keep)
checkpoint_tracker = CheckpointTracker(
hparams.checkpoint_dir, max_to_keep=BEST_N_CHECKPOINTS)
# Main loop!
train_dataset_iter = iter(train_dataset)
for epoch in range(hparams.num_epochs):
print(hparams.checkpoint_dir)
base_description = f"(Train) Epoch {epoch}, GPU {hparams.gpus}"
train_tqdm = trange(iters_in_train, ncols=120, desc=base_description)
for current_step in train_tqdm:
example = next(train_dataset_iter)
global_step.assign_add(1)
_global_step = int(global_step)
# Train
output_dict = trainer.train_step(example)
# Print model
if _global_step == 1:
model.print_model()
loss_str = str(output_dict['loss'].numpy())
train_tqdm.set_description(f"{base_description}, Loss {loss_str}")
with file_writer.as_default():
if _global_step % int(hparams.logging_step) == 0:
tf.summary.histogram('train/vocab', output_dict['sample_ids'], step=_global_step)
tf.summary.scalar('train/loss', output_dict['loss'], step=_global_step)
tf.summary.scalar('train/gen_loss', output_dict['gen_loss'], step=_global_step)
tf.summary.scalar('train/knowledge_loss', output_dict['knowledge_loss'], step=_global_step)
tf.summary.scalar('train/kl_loss', output_dict['kl_loss'], step=_global_step)
# Test
if _global_step % int(iters_in_train * hparams.evaluation_epoch) == 0:
checkpoint_manager.save(global_step)
test_loop_outputs = trainer.test_loop(test_dataset, iters_in_test, epoch, 'seen')
if hparams.data_name == 'wizard_of_wikipedia':
unseen_loop_outputs = trainer.test_loop(unseen_dataset, iters_in_unseen, epoch, 'unseen')
test_summaries, log_dict = run_wow_evaluation(
test_loop_outputs, hparams.checkpoint_dir, 'seen')
if hparams.data_name == 'wizard_of_wikipedia':
unseen_summaries, unseen_log_dict = run_wow_evaluation(
unseen_loop_outputs, hparams.checkpoint_dir, 'unseen')
# Logging
tqdm.write(colorful.bold_green("seen").styled_string)
tqdm.write(colorful.bold_red(pformat(log_dict)).styled_string)
if hparams.data_name == 'wizard_of_wikipedia':
tqdm.write(colorful.bold_green("unseen").styled_string)
tqdm.write(colorful.bold_red(pformat(unseen_log_dict)).styled_string)
with file_writer.as_default():
for family, test_summary in test_summaries.items():
for key, value in test_summary.items():
tf.summary.scalar(f'{family}/{key}', value, step=_global_step)
if hparams.data_name == 'wizard_of_wikipedia':
for family, unseen_summary in unseen_summaries.items():
for key, value in unseen_summary.items():
tf.summary.scalar(f'{family}/{key}', value, step=_global_step)
if hparams.keep_best_checkpoint:
current_score = log_dict["rouge1"]
checkpoint_tracker.update(current_score, _global_step)
if __name__ == '__main__':
main()
| [
"utils.etc_utils.set_gpus",
"tensorflow.train.Checkpoint",
"modules.from_parlai.unzip",
"better_exceptions.hook",
"tensorflow.config.experimental.set_visible_devices",
"utils.config_utils.CommandArgs",
"utils.etc_utils.set_logger",
"os.path.exists",
"utils.config_utils.initialize_argparser",
"ppri... | [((714, 738), 'better_exceptions.hook', 'better_exceptions.hook', ([], {}), '()\n', (736, 738), False, 'import better_exceptions\n'), ((755, 781), 'utils.config_utils.CommandArgs', 'config_utils.CommandArgs', ([], {}), '()\n', (779, 781), False, 'from utils import config_utils, custom_argparsers\n'), ((791, 806), 'pprint.PrettyPrinter', 'PrettyPrinter', ([], {}), '()\n', (804, 806), False, 'from pprint import PrettyPrinter\n'), ((824, 839), 'pprint.PrettyPrinter', 'PrettyPrinter', ([], {}), '()\n', (837, 839), False, 'from pprint import PrettyPrinter\n'), ((939, 1040), 'utils.config_utils.initialize_argparser', 'config_utils.initialize_argparser', (['MODELS', '_command_args', 'custom_argparsers.DialogArgumentParser'], {}), '(MODELS, _command_args, custom_argparsers.\n DialogArgumentParser)\n', (972, 1040), False, 'from utils import config_utils, custom_argparsers\n'), ((1073, 1136), 'utils.config_utils.create_or_load_hparams', 'config_utils.create_or_load_hparams', (['args', 'model_args', 'args.cfg'], {}), '(args, model_args, args.cfg)\n', (1108, 1136), False, 'from utils import config_utils, custom_argparsers\n'), ((1215, 1227), 'utils.etc_utils.set_logger', 'set_logger', ([], {}), '()\n', (1225, 1227), False, 'from utils.etc_utils import set_logger, set_tcmalloc, set_gpus, check_none_gradients\n'), ((1232, 1254), 'utils.etc_utils.set_gpus', 'set_gpus', (['hparams.gpus'], {}), '(hparams.gpus)\n', (1240, 1254), False, 'from utils.etc_utils import set_logger, set_tcmalloc, set_gpus, check_none_gradients\n'), ((1259, 1273), 'utils.etc_utils.set_tcmalloc', 'set_tcmalloc', ([], {}), '()\n', (1271, 1273), False, 'from utils.etc_utils import set_logger, set_tcmalloc, set_gpus, check_none_gradients\n'), ((1285, 1336), 'tensorflow.config.experimental.list_physical_devices', 'tf.config.experimental.list_physical_devices', (['"""GPU"""'], {}), "('GPU')\n", (1329, 1336), True, 'import tensorflow as tf\n'), ((1341, 1396), 'tensorflow.config.experimental.set_visible_devices', 'tf.config.experimental.set_visible_devices', (['gpus', '"""GPU"""'], {}), "(gpus, 'GPU')\n", (1383, 1396), True, 'import tensorflow as tf\n'), ((1505, 1544), 'tensorflow.random.set_seed', 'tf.random.set_seed', (['hparams.random_seed'], {}), '(hparams.random_seed)\n', (1523, 1544), True, 'import tensorflow as tf\n'), ((1549, 1584), 'numpy.random.seed', 'np.random.seed', (['hparams.random_seed'], {}), '(hparams.random_seed)\n', (1563, 1584), True, 'import numpy as np\n'), ((1589, 1621), 'random.seed', 'random.seed', (['hparams.random_seed'], {}), '(hparams.random_seed)\n', (1600, 1621), False, 'import random\n'), ((2178, 2223), 'os.makedirs', 'os.makedirs', (['hparams.cache_dir'], {'exist_ok': '(True)'}), '(hparams.cache_dir, exist_ok=True)\n', (2189, 2223), False, 'import os\n'), ((3801, 3897), 'modules.trainer.Trainer', 'Trainer', (['model', 'optimizer', 'mirrored_strategy', 'hparams.enable_function', 'reader_cls.remove_pad'], {}), '(model, optimizer, mirrored_strategy, hparams.enable_function,\n reader_cls.remove_pad)\n', (3808, 3897), False, 'from modules.trainer import run_wow_evaluation, Trainer\n'), ((3995, 4048), 'tensorflow.summary.create_file_writer', 'tf.summary.create_file_writer', (['hparams.checkpoint_dir'], {}), '(hparams.checkpoint_dir)\n', (4024, 4048), True, 'import tensorflow as tf\n'), ((4100, 4146), 'tensorflow.compat.v1.train.get_or_create_global_step', 'tf.compat.v1.train.get_or_create_global_step', ([], {}), '()\n', (4144, 4146), True, 'import tensorflow as tf\n'), ((4164, 4250), 'tensorflow.train.Checkpoint', 'tf.train.Checkpoint', ([], {'optimizer': 'optimizer', 'model': 'model', 'optimizer_step': 'global_step'}), '(optimizer=optimizer, model=model, optimizer_step=\n global_step)\n', (4183, 4250), True, 'import tensorflow as tf\n'), ((4343, 4452), 'tensorflow.train.CheckpointManager', 'tf.train.CheckpointManager', (['checkpoint'], {'directory': 'hparams.checkpoint_dir', 'max_to_keep': 'hparams.max_to_keep'}), '(checkpoint, directory=hparams.checkpoint_dir,\n max_to_keep=hparams.max_to_keep)\n', (4369, 4452), True, 'import tensorflow as tf\n'), ((4578, 4651), 'modules.checkpoint_tracker.CheckpointTracker', 'CheckpointTracker', (['hparams.checkpoint_dir'], {'max_to_keep': 'BEST_N_CHECKPOINTS'}), '(hparams.checkpoint_dir, max_to_keep=BEST_N_CHECKPOINTS)\n', (4595, 4651), False, 'from modules.checkpoint_tracker import CheckpointTracker\n'), ((1426, 1477), 'tensorflow.config.experimental.set_memory_growth', 'tf.config.experimental.set_memory_growth', (['gpu', '(True)'], {}), '(gpu, True)\n', (1466, 1477), True, 'import tensorflow as tf\n'), ((1700, 1732), 'tensorflow.distribute.MirroredStrategy', 'tf.distribute.MirroredStrategy', ([], {}), '()\n', (1730, 1732), True, 'import tensorflow as tf\n'), ((1857, 1889), 'os.path.exists', 'os.path.exists', (['hparams.bert_dir'], {}), '(hparams.bert_dir)\n', (1871, 1889), False, 'import os\n'), ((1899, 1928), 'os.makedirs', 'os.makedirs', (['hparams.bert_dir'], {}), '(hparams.bert_dir)\n', (1910, 1928), False, 'import os\n'), ((2116, 2146), 'modules.from_parlai.unzip', 'unzip', (['hparams.bert_dir', 'fname'], {}), '(hparams.bert_dir, fname)\n', (2121, 2146), False, 'from modules.from_parlai import download_from_google_drive, unzip\n'), ((3656, 3743), 'tensorflow.keras.optimizers.Adam', 'tf.keras.optimizers.Adam', ([], {'learning_rate': 'hparams.init_lr', 'clipnorm': 'hparams.clipnorm'}), '(learning_rate=hparams.init_lr, clipnorm=hparams.\n clipnorm)\n', (3680, 3743), True, 'import tensorflow as tf\n'), ((4899, 4955), 'tqdm.trange', 'trange', (['iters_in_train'], {'ncols': '(120)', 'desc': 'base_description'}), '(iters_in_train, ncols=120, desc=base_description)\n', (4905, 4955), False, 'from tqdm import tqdm, trange\n'), ((2069, 2106), 'os.path.join', 'os.path.join', (['hparams.bert_dir', 'fname'], {}), '(hparams.bert_dir, fname)\n', (2081, 2106), False, 'import os\n'), ((3435, 3522), 'tensorflow.keras.optimizers.Adam', 'tf.keras.optimizers.Adam', ([], {'learning_rate': 'hparams.init_lr', 'clipnorm': 'hparams.clipnorm'}), '(learning_rate=hparams.init_lr, clipnorm=hparams.\n clipnorm)\n', (3459, 3522), True, 'import tensorflow as tf\n'), ((6518, 6587), 'modules.trainer.run_wow_evaluation', 'run_wow_evaluation', (['test_loop_outputs', 'hparams.checkpoint_dir', '"""seen"""'], {}), "(test_loop_outputs, hparams.checkpoint_dir, 'seen')\n", (6536, 6587), False, 'from modules.trainer import run_wow_evaluation, Trainer\n'), ((5562, 5648), 'tensorflow.summary.histogram', 'tf.summary.histogram', (['"""train/vocab"""', "output_dict['sample_ids']"], {'step': '_global_step'}), "('train/vocab', output_dict['sample_ids'], step=\n _global_step)\n", (5582, 5648), True, 'import tensorflow as tf\n'), ((5664, 5735), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""train/loss"""', "output_dict['loss']"], {'step': '_global_step'}), "('train/loss', output_dict['loss'], step=_global_step)\n", (5681, 5735), True, 'import tensorflow as tf\n'), ((5756, 5835), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""train/gen_loss"""', "output_dict['gen_loss']"], {'step': '_global_step'}), "('train/gen_loss', output_dict['gen_loss'], step=_global_step)\n", (5773, 5835), True, 'import tensorflow as tf\n'), ((5856, 5951), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""train/knowledge_loss"""', "output_dict['knowledge_loss']"], {'step': '_global_step'}), "('train/knowledge_loss', output_dict['knowledge_loss'],\n step=_global_step)\n", (5873, 5951), True, 'import tensorflow as tf\n'), ((5968, 6045), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""train/kl_loss"""', "output_dict['kl_loss']"], {'step': '_global_step'}), "('train/kl_loss', output_dict['kl_loss'], step=_global_step)\n", (5985, 6045), True, 'import tensorflow as tf\n'), ((6728, 6801), 'modules.trainer.run_wow_evaluation', 'run_wow_evaluation', (['unseen_loop_outputs', 'hparams.checkpoint_dir', '"""unseen"""'], {}), "(unseen_loop_outputs, hparams.checkpoint_dir, 'unseen')\n", (6746, 6801), False, 'from modules.trainer import run_wow_evaluation, Trainer\n'), ((6881, 6908), 'colorful.bold_green', 'colorful.bold_green', (['"""seen"""'], {}), "('seen')\n", (6900, 6908), False, 'import colorful\n'), ((7097, 7126), 'colorful.bold_green', 'colorful.bold_green', (['"""unseen"""'], {}), "('unseen')\n", (7116, 7126), False, 'import colorful\n'), ((7444, 7506), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['f"""{family}/{key}"""', 'value'], {'step': '_global_step'}), "(f'{family}/{key}', value, step=_global_step)\n", (7461, 7506), True, 'import tensorflow as tf\n'), ((7756, 7818), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['f"""{family}/{key}"""', 'value'], {'step': '_global_step'}), "(f'{family}/{key}', value, step=_global_step)\n", (7773, 7818), True, 'import tensorflow as tf\n')] |
import gym
import argparse
import calendar
from rllab.baselines.linear_feature_baseline import LinearFeatureBaseline
from rllab.envs.normalized_env import normalize
from rllab.envs.gym_env import GymEnv
from rllab.config import LOG_DIR
from sandbox import RLLabRunner
from sandbox.rocky.tf.algos.trpo import TRPO
from sandbox.rocky.tf.algos.gail import GAIL
from sandbox.rocky.tf.envs.base import TfEnv
from sandbox.rocky.tf.policies.categorical_mlp_policy import CategoricalMLPPolicy
from sandbox.rocky.tf.policies.gaussian_mlp_policy import GaussianMLPPolicy
from sandbox.rocky.tf.policies.gaussian_lstm_policy import GaussianLSTMPolicy
from sandbox.rocky.tf.policies.gaussian_gru_policy import GaussianGRUPolicy
from sandbox.rocky.tf.core.network import MLP, RewardMLP, BaselineMLP
from sandbox.rocky.tf.optimizers.conjugate_gradient_optimizer import ConjugateGradientOptimizer, FiniteDifferenceHvp
import tensorflow as tf
import numpy as np
import os
import os.path as osp
from rllab import config
parser = argparse.ArgumentParser()
# Logger Params
parser.add_argument('--exp_name',type=str,default='my_exp')
parser.add_argument('--tabular_log_file',type=str,default= 'tab.txt')
parser.add_argument('--text_log_file',type=str,default= 'tex.txt')
parser.add_argument('--params_log_file',type=str,default= 'args.txt')
parser.add_argument('--snapshot_mode',type=str,default='all')
parser.add_argument('--log_tabular_only',type=bool,default=False)
parser.add_argument('--log_dir',type=str)
parser.add_argument('--args_data')
# Environment params
parser.add_argument('--trajdatas',type=int,nargs='+',default=[1,2,3,4,5,6])
parser.add_argument('--n_features',type=int,default=45)
parser.add_argument('--limit_trajs',type=int,default=12000)
parser.add_argument('--max_traj_len',type=int,default=100) # max length of a trajectory (ts)
parser.add_argument('--env_name',type=str,default="Following")
parser.add_argument('--following_distance',type=int,default=10)
parser.add_argument('--normalize_obs',type=bool,default= True)
parser.add_argument('--normalize_act',type=bool,default=False)
parser.add_argument('--norm_tol',type=float,default=1e-1)
parser.add_argument('--render',type=bool, default= False)
# Env dict
## parameters for the environment
# Model Params
parser.add_argument('--policy_type',type=str,default='mlp')
parser.add_argument('--policy_save_name',type=str,default='policy_gail')
parser.add_argument('--baseline_type',type=str,default='linear')
parser.add_argument('--reward_type',type=str,default='mlp') # adversary / discriminator network
parser.add_argument('--load_policy',type=bool,default=False)
parser.add_argument('--hspec',type=int,nargs='+') # specifies architecture of "feature" networks
parser.add_argument('--p_hspec',type=int,nargs='+',default=[]) # policy layers
parser.add_argument('--b_hspec',type=int,nargs='+',default=[]) # baseline layers
parser.add_argument('--r_hspec',type=int,nargs='+',default=[]) # reward layers
parser.add_argument('--gru_dim',type=int,default=64) # hidden dimension of gru
parser.add_argument('--nonlinearity',type=str,default='tanh')
parser.add_argument('--batch_normalization',type=bool,default=False)
# TRPO Params
parser.add_argument('--trpo_batch_size', type=int, default= 40 * 100)
parser.add_argument('--discount', type=float, default=0.95)
parser.add_argument('--gae_lambda', type=float, default=0.99)
parser.add_argument('--n_iter', type=int, default=500) # trpo iterations
parser.add_argument('--max_kl', type=float, default=0.01)
parser.add_argument('--vf_max_kl', type=float, default=0.01)
parser.add_argument('--vf_cg_damping', type=float, default=0.01)
parser.add_argument('--trpo_step_size',type=float,default=0.01)
parser.add_argument('--only_trpo',type=bool,default=False)
# GAILS Params
parser.add_argument('--gail_batch_size', type=int, default= 1024)
parser.add_argument('--adam_steps',type=int,default=1)
parser.add_argument('--adam_lr', type=float, default=0.00005)
parser.add_argument('--adam_beta1',type=float,default=0.9)
parser.add_argument('--adam_beta2',type=float,default=0.99)
parser.add_argument('--adam_epsilon',type=float,default=1e-8)
parser.add_argument('--decay_steps',type=int,default=0)
parser.add_argument('--decay_rate',type=float,default=1.0)
parser.add_argument('--hard_freeze',type=bool,default=True)
parser.add_argument('--freeze_upper',type=float,default=1.0)
parser.add_argument('--freeze_lower',type=float,default=0.5)
parser.add_argument('--policy_ent_reg', type=float, default=0.0)
parser.add_argument('--env_r_weight',type=float,default=0.0)
args = parser.parse_args()
assert not args.batch_normalization, "Batch normalization not implemented."
nonlins = {'tanh':tf.nn.tanh,'relu':tf.nn.relu,'elu':tf.nn.elu,'sigmoid':tf.nn.sigmoid}
nonlinearity = nonlins[args.nonlinearity]
if args.hspec is None:
p_hspec = args.p_hspec
b_hspec = args.b_hspec
r_hspec = args.r_hspec
else:
p_hspec = args.hspec
b_hspec = args.hspec
r_hspec = args.hspec
## DEFINE THE ENVIRONMENT
gym.envs.register(
id="SpellingCorrection-v0",
entry_point='rllab.envs.nlp_env:SpellingCorrection',
timestep_limit=999,
reward_threshold=195.0,
)
## TODO : Write function for loading trajectories
expert_data_path = LOG_DIR + '/expert_data.h5'
expert_data, expert_data_stacked = load_trajs(expert_data_path, args.limit_trajs)
initial_obs_mean = expert_data_stacked['exobs_Bstacked_Do'].mean(axis= 0)
initial_obs_std = expert_data_stacked['exobs_Bstacked_Do'].std(axis= 0)
initial_obs_var = np.square(initial_obs_std)
# normalize observations
if args.normalize_obs:
expert_data = {'obs':(expert_data_stacked['exobs_Bstacked_Do'] - initial_obs_mean) / initial_obs_std}
else:
expert_data = {'obs':expert_data_stacked['exobs_Bstacked_Do']}
# normalize actions
if args.normalize_act:
initial_act_mean = expert_data_stacked['exa_Bstacked_Da'].mean(axis= 0)
initial_act_std = expert_data_stacked['exa_Bstacked_Da'].std(axis= 0)
expert_data.update({'act':(expert_data_stacked['exa_Bstacked_Da'] - initial_act_mean) / initial_act_std})
else:
initial_act_mean = 0.0
initial_act_std = 1.0
expert_data.update({'act':expert_data_stacked['exa_Bstacked_Da']})
# rllab wrapper for gym env. NOTE: takes obs mean and var to normalize during transitions
g_env = normalize(GymEnv(env_id),
initial_obs_mean= initial_obs_mean,
initial_obs_var= initial_obs_var,
normalize_obs= True,
running_obs= False)
env = TfEnv(g_env)
## DEFINE POLICY, ADVERSARY, AND BASELINE NETWORKS
# create policy
if args.policy_type == 'mlp':
policy = GaussianMLPPolicy('mlp_policy', env.spec, hidden_sizes= p_hspec,
std_hidden_nonlinearity=nonlinearity,hidden_nonlinearity=nonlinearity,
batch_normalization=args.batch_normalization
)
elif args.policy_type == 'gru':
if p_hspec == []:
feat_mlp = None
else: # create feature extracting mlp to feed into gru.
feat_mlp = MLP('mlp_policy', p_hspec[-1], p_hspec[:-1], nonlinearity, output_activation,
input_shape= (np.prod(env.spec.observation_space.shape),),
batch_normalization=args.batch_normalization)
policy = GaussianGRUPolicy(name= 'gru_policy', env_spec= env.spec,
hidden_dim= args.gru_dim,
feature_network=feat_mlp,
state_include_action=False)
else:
raise NotImplementedError
# create baseline
if args.baseline_type == 'linear':
baseline = LinearFeatureBaseline(env_spec=env.spec)
elif args.baseline_type == 'mlp':
baseline = BaselineMLP(name='mlp_baseline',
output_dim=1,
hidden_sizes= b_hspec,
hidden_nonlinearity=nonlinearity,
output_nonlinearity=None,
input_shape=(np.prod(env.spec.observation_space.shape),),
batch_normalization=args.batch_normalization)
baseline.initialize_optimizer()
else:
raise NotImplementedError
# create adversary / discriminator network which will act as surrogate reward.
reward = RewardMLP('mlp_reward', 1, r_hspec, nonlinearity,tf.nn.sigmoid,
input_shape= (np.prod(env.spec.observation_space.shape) + env.action_dim,),
batch_normalization= args.batch_normalization)
## DEFINE TRAINING ALGORITHM: GENERATIVE ADVERSARIAL IMITATION LEARNING
algo = GAIL(
env=env,
policy=policy,
baseline=baseline,
reward=reward,
expert_data=expert_data,
batch_size= args.trpo_batch_size,
gail_batch_size=args.gail_batch_size,
max_path_length=args.max_traj_len,
n_itr=args.n_iter,
discount=args.discount,
#step_size=0.01,
step_size=args.trpo_step_size,
force_batch_sampler= True,
whole_paths= True,
adam_steps= args.adam_steps,
decay_rate= args.decay_rate,
decay_steps= args.decay_steps,
act_mean= initial_act_mean,
act_std= initial_act_std,
freeze_upper = args.freeze_upper,
freeze_lower = args.freeze_lower,
fo_optimizer_cls= tf.train.AdamOptimizer,
fo_optimizer_args= dict(learning_rate = args.adam_lr,
beta1 = args.adam_beta1,
beta2 = args.adam_beta2,
epsilon= args.adam_epsilon),
optimizer=ConjugateGradientOptimizer(hvp_approach=FiniteDifferenceHvp(base_eps=1e-5))
)
# crufty code for saving to h5. We probably don't want this.
date= calendar.datetime.date.today().strftime('%y-%m-%d')
if date not in os.listdir(rllab_path+'/data'):
os.mkdir(rllab_path+'/data/'+date)
c = 0
exp_name = args.exp_name + '-'+str(c)
while exp_name in os.listdir(rllab_path+'/data/'+date+'/'):
c += 1
exp_name = args.exp_name + '-'+str(c)
exp_dir = date+'/'+exp_name
log_dir = osp.join(config.LOG_DIR, exp_dir)
policy.set_log_dir(log_dir)
# run the algorithm and save everything to rllab's pickle format.
runner = RLLabRunner(algo, args, exp_dir)
runner.train()
| [
"gym.envs.register",
"calendar.datetime.date.today",
"numpy.prod",
"os.listdir",
"sandbox.rocky.tf.envs.base.TfEnv",
"argparse.ArgumentParser",
"rllab.envs.gym_env.GymEnv",
"sandbox.rocky.tf.policies.gaussian_gru_policy.GaussianGRUPolicy",
"os.path.join",
"numpy.square",
"os.mkdir",
"sandbox.r... | [((1021, 1046), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1044, 1046), False, 'import argparse\n'), ((5024, 5175), 'gym.envs.register', 'gym.envs.register', ([], {'id': '"""SpellingCorrection-v0"""', 'entry_point': '"""rllab.envs.nlp_env:SpellingCorrection"""', 'timestep_limit': '(999)', 'reward_threshold': '(195.0)'}), "(id='SpellingCorrection-v0', entry_point=\n 'rllab.envs.nlp_env:SpellingCorrection', timestep_limit=999,\n reward_threshold=195.0)\n", (5041, 5175), False, 'import gym\n'), ((5531, 5557), 'numpy.square', 'np.square', (['initial_obs_std'], {}), '(initial_obs_std)\n', (5540, 5557), True, 'import numpy as np\n'), ((6536, 6548), 'sandbox.rocky.tf.envs.base.TfEnv', 'TfEnv', (['g_env'], {}), '(g_env)\n', (6541, 6548), False, 'from sandbox.rocky.tf.envs.base import TfEnv\n'), ((10014, 10047), 'os.path.join', 'osp.join', (['config.LOG_DIR', 'exp_dir'], {}), '(config.LOG_DIR, exp_dir)\n', (10022, 10047), True, 'import os.path as osp\n'), ((10152, 10184), 'sandbox.RLLabRunner', 'RLLabRunner', (['algo', 'args', 'exp_dir'], {}), '(algo, args, exp_dir)\n', (10163, 10184), False, 'from sandbox import RLLabRunner\n'), ((6331, 6345), 'rllab.envs.gym_env.GymEnv', 'GymEnv', (['env_id'], {}), '(env_id)\n', (6337, 6345), False, 'from rllab.envs.gym_env import GymEnv\n'), ((6660, 6849), 'sandbox.rocky.tf.policies.gaussian_mlp_policy.GaussianMLPPolicy', 'GaussianMLPPolicy', (['"""mlp_policy"""', 'env.spec'], {'hidden_sizes': 'p_hspec', 'std_hidden_nonlinearity': 'nonlinearity', 'hidden_nonlinearity': 'nonlinearity', 'batch_normalization': 'args.batch_normalization'}), "('mlp_policy', env.spec, hidden_sizes=p_hspec,\n std_hidden_nonlinearity=nonlinearity, hidden_nonlinearity=nonlinearity,\n batch_normalization=args.batch_normalization)\n", (6677, 6849), False, 'from sandbox.rocky.tf.policies.gaussian_mlp_policy import GaussianMLPPolicy\n'), ((7672, 7712), 'rllab.baselines.linear_feature_baseline.LinearFeatureBaseline', 'LinearFeatureBaseline', ([], {'env_spec': 'env.spec'}), '(env_spec=env.spec)\n', (7693, 7712), False, 'from rllab.baselines.linear_feature_baseline import LinearFeatureBaseline\n'), ((9747, 9779), 'os.listdir', 'os.listdir', (["(rllab_path + '/data')"], {}), "(rllab_path + '/data')\n", (9757, 9779), False, 'import os\n'), ((9783, 9821), 'os.mkdir', 'os.mkdir', (["(rllab_path + '/data/' + date)"], {}), "(rllab_path + '/data/' + date)\n", (9791, 9821), False, 'import os\n'), ((9880, 9926), 'os.listdir', 'os.listdir', (["(rllab_path + '/data/' + date + '/')"], {}), "(rllab_path + '/data/' + date + '/')\n", (9890, 9926), False, 'import os\n'), ((7336, 7475), 'sandbox.rocky.tf.policies.gaussian_gru_policy.GaussianGRUPolicy', 'GaussianGRUPolicy', ([], {'name': '"""gru_policy"""', 'env_spec': 'env.spec', 'hidden_dim': 'args.gru_dim', 'feature_network': 'feat_mlp', 'state_include_action': '(False)'}), "(name='gru_policy', env_spec=env.spec, hidden_dim=args.\n gru_dim, feature_network=feat_mlp, state_include_action=False)\n", (7353, 7475), False, 'from sandbox.rocky.tf.policies.gaussian_gru_policy import GaussianGRUPolicy\n'), ((9680, 9710), 'calendar.datetime.date.today', 'calendar.datetime.date.today', ([], {}), '()\n', (9708, 9710), False, 'import calendar\n'), ((8417, 8458), 'numpy.prod', 'np.prod', (['env.spec.observation_space.shape'], {}), '(env.spec.observation_space.shape)\n', (8424, 8458), True, 'import numpy as np\n'), ((9574, 9609), 'sandbox.rocky.tf.optimizers.conjugate_gradient_optimizer.FiniteDifferenceHvp', 'FiniteDifferenceHvp', ([], {'base_eps': '(1e-05)'}), '(base_eps=1e-05)\n', (9593, 9609), False, 'from sandbox.rocky.tf.optimizers.conjugate_gradient_optimizer import ConjugateGradientOptimizer, FiniteDifferenceHvp\n'), ((8041, 8082), 'numpy.prod', 'np.prod', (['env.spec.observation_space.shape'], {}), '(env.spec.observation_space.shape)\n', (8048, 8082), True, 'import numpy as np\n'), ((7209, 7250), 'numpy.prod', 'np.prod', (['env.spec.observation_space.shape'], {}), '(env.spec.observation_space.shape)\n', (7216, 7250), True, 'import numpy as np\n')] |
import argparse
import csv
import functools as fts
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import rc
import sys
rc('font',**{'family':'sans-serif','sans-serif':['Gill Sans']})
## for Palatino and other serif fonts use:
#rc('font',**{'family':'serif','serif':['Palatino']))
rc('text', usetex=True)
matplotlib.rcParams.update({'font.size': 14, 'legend.fontsize': 14})
### Parse command line arguments
parser = argparse.ArgumentParser(description="Numerical approximation -- verifier for 2 bidders")
parser.add_argument('file_name', help='file with approximation results')
args = parser.parse_args()
file_name = args.file_name
# Read data from file
data_in = {}
with open(file_name, 'rt') as f:
f_reader = csv.DictReader(f, delimiter=' ')
for row in f_reader:
for key in row:
data_in[key] = row[key]
# Parse data common to ODE and polynomial methods
w = float(data_in['w'])
reps = [float(r.replace("[", "").replace("]", "")) for r in data_in['reps'].split(',')]
n = len(reps)
# Estimated cost support bounds
lower_extremities = [(1-w)*r for r in reps]
upper_extremities = [(1-w)*r + w for r in reps]
# Parse the rest of the data
try:
bids = [float(b.replace("[","").replace("]","")) for b in data_in['bids'].split(',')]
costs = []
for i in range(n):
label = 'costs_{}'.format(i)
costs += [[float(c.replace("[","").replace("]","")) for c in data_in[label].split(',')]]
except KeyError:
bs = [float(data_in['b_lower']), float(data_in['b_upper'])]
css = []
for i in range(n):
label = 'cs_{}'.format(i)
cs = [float(c.replace("[","").replace("]","")) for c in data_in[label].split(',')]
css += [cs]
# Quantize costs and bids
try:
bids = bids[::20]
costs = [c[::20] for c in costs]
except NameError:
pass
# Compute theoretical results
c1 = [lower_extremities[0], upper_extremities[0]]
c2 = [lower_extremities[1], upper_extremities[1]]
b = [(c1[0]*c2[0] - ((c1[1] + c2[1]) / 2)**2) / (c1[0] - c1[1] + c2[0] - c2[1]),
(c1[1] + c2[1]) / 2]
# Constants of integration
d1 = ((c2[1]-c1[1])**2 + 4*(b[0]-c2[1])*(c1[0]-c1[1])) / (-2*(b[0]-b[1])*(c1[0]-c1[1])) * np.exp((c2[1]-c1[1]) / (2*(b[0]-b[1])))
d2 = ((c1[1]-c2[1])**2 + 4*(b[0]-c1[1])*(c2[0]-c2[1])) / (-2*(b[0]-b[1])*(c2[0]-c2[1])) * np.exp((c1[1]-c2[1]) / (2*(b[0]-b[1])))
# Inverse bid functions
inv1 = lambda x: c1[1] + (c2[1]-c1[1])**2 / (d1*(c2[1]+c1[1]-2*x)*np.exp((c2[1]-c1[1])/(c2[1]+c1[1]-2*x)) + 4*(c2[1]-x))
inv2 = lambda x: c2[1] + (c1[1]-c2[1])**2 / (d2*(c1[1]+c2[1]-2*x)*np.exp((c1[1]-c2[1])/(c1[1]+c2[1]-2*x)) + 4*(c1[1]-x))
t_bids = np.linspace(b[0], b[1], 10000)
# Plot
plt.figure()
plt.plot([inv1(b) for b in t_bids], t_bids, 'b')
plt.plot(costs[0], bids, 'b.')
plt.plot([inv2(b) for b in t_bids], t_bids, 'r--')
plt.plot(costs[1], bids, 'rx')
plt.xlabel(r"Cost-hat, $\hat{c}_i$")
plt.ylabel(r"Bid-hat, $\hat{b}$")
plt.grid()
labels = ['NO 1: Theory', 'NO 1: Numerical', 'NO 2: Theory', 'NO 2: Numerical']
plt.legend(labels, loc='upper left')
plt.savefig('verify.pdf')
| [
"matplotlib.pyplot.grid",
"matplotlib.pyplot.savefig",
"csv.DictReader",
"argparse.ArgumentParser",
"matplotlib.rcParams.update",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"numpy.exp",
"matplotlib.pyplot.figure",
"numpy.linspace",
"matplotlib.rc",
"mat... | [((158, 225), 'matplotlib.rc', 'rc', (['"""font"""'], {}), "('font', **{'family': 'sans-serif', 'sans-serif': ['Gill Sans']})\n", (160, 225), False, 'from matplotlib import rc\n'), ((319, 342), 'matplotlib.rc', 'rc', (['"""text"""'], {'usetex': '(True)'}), "('text', usetex=True)\n", (321, 342), False, 'from matplotlib import rc\n'), ((343, 411), 'matplotlib.rcParams.update', 'matplotlib.rcParams.update', (["{'font.size': 14, 'legend.fontsize': 14}"], {}), "({'font.size': 14, 'legend.fontsize': 14})\n", (369, 411), False, 'import matplotlib\n'), ((455, 548), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Numerical approximation -- verifier for 2 bidders"""'}), "(description=\n 'Numerical approximation -- verifier for 2 bidders')\n", (478, 548), False, 'import argparse\n'), ((2599, 2629), 'numpy.linspace', 'np.linspace', (['b[0]', 'b[1]', '(10000)'], {}), '(b[0], b[1], 10000)\n', (2610, 2629), True, 'import numpy as np\n'), ((2638, 2650), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (2648, 2650), True, 'import matplotlib.pyplot as plt\n'), ((2700, 2730), 'matplotlib.pyplot.plot', 'plt.plot', (['costs[0]', 'bids', '"""b."""'], {}), "(costs[0], bids, 'b.')\n", (2708, 2730), True, 'import matplotlib.pyplot as plt\n'), ((2782, 2812), 'matplotlib.pyplot.plot', 'plt.plot', (['costs[1]', 'bids', '"""rx"""'], {}), "(costs[1], bids, 'rx')\n", (2790, 2812), True, 'import matplotlib.pyplot as plt\n'), ((2813, 2849), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Cost-hat, $\\\\hat{c}_i$"""'], {}), "('Cost-hat, $\\\\hat{c}_i$')\n", (2823, 2849), True, 'import matplotlib.pyplot as plt\n'), ((2850, 2883), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Bid-hat, $\\\\hat{b}$"""'], {}), "('Bid-hat, $\\\\hat{b}$')\n", (2860, 2883), True, 'import matplotlib.pyplot as plt\n'), ((2884, 2894), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (2892, 2894), True, 'import matplotlib.pyplot as plt\n'), ((2975, 3011), 'matplotlib.pyplot.legend', 'plt.legend', (['labels'], {'loc': '"""upper left"""'}), "(labels, loc='upper left')\n", (2985, 3011), True, 'import matplotlib.pyplot as plt\n'), ((3012, 3037), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""verify.pdf"""'], {}), "('verify.pdf')\n", (3023, 3037), True, 'import matplotlib.pyplot as plt\n'), ((753, 785), 'csv.DictReader', 'csv.DictReader', (['f'], {'delimiter': '""" """'}), "(f, delimiter=' ')\n", (767, 785), False, 'import csv\n'), ((2154, 2199), 'numpy.exp', 'np.exp', (['((c2[1] - c1[1]) / (2 * (b[0] - b[1])))'], {}), '((c2[1] - c1[1]) / (2 * (b[0] - b[1])))\n', (2160, 2199), True, 'import numpy as np\n'), ((2284, 2329), 'numpy.exp', 'np.exp', (['((c1[1] - c2[1]) / (2 * (b[0] - b[1])))'], {}), '((c1[1] - c2[1]) / (2 * (b[0] - b[1])))\n', (2290, 2329), True, 'import numpy as np\n'), ((2414, 2463), 'numpy.exp', 'np.exp', (['((c2[1] - c1[1]) / (c2[1] + c1[1] - 2 * x))'], {}), '((c2[1] - c1[1]) / (c2[1] + c1[1] - 2 * x))\n', (2420, 2463), True, 'import numpy as np\n'), ((2535, 2584), 'numpy.exp', 'np.exp', (['((c1[1] - c2[1]) / (c1[1] + c2[1] - 2 * x))'], {}), '((c1[1] - c2[1]) / (c1[1] + c2[1] - 2 * x))\n', (2541, 2584), True, 'import numpy as np\n')] |
import pytest
import numpy as np
import gbmc_v0.util_funcs as uf
from ovito.data import NearestNeighborFinder
@pytest.mark.skip(reason="we can't push the data to repo. It is large.")
@pytest.mark.parametrize('filename0, lat_par, cut_off, num_neighbors, non_p_dir',
[('data/dump_1', 4.05, 10, 12, 2),
('../lammps_dump/dump_after.1', 4.05, 10, 12, 2),
('../lammps_dump/dump_befor.1', 4.05, 10, 12, 2)])
def test_check_a(filename0, lat_par, cut_off, num_neighbors, non_p_dir):
# filename0 = 'data/dump_1'
data = uf.compute_ovito_data(filename0)
num = lat_par / np.sqrt(2)
ptm_struct = data.particles['Structure Type'][...]
position = data.particles['Position'][...]
need_atom = np.where((position[:, non_p_dir] > 0) & (ptm_struct == 1))[0]
pos_sc = position[need_atom, :]
min_Z, max_Z = np.min(pos_sc[:, non_p_dir]) + cut_off, np.max(pos_sc[:, non_p_dir]) - cut_off
area = np.where((position[:, non_p_dir] < max_Z) & (position[:, non_p_dir] > min_Z))[0]
num_particl = np.shape(area)[0]
finder = NearestNeighborFinder(num_neighbors, data)
distances = np.zeros(num_particl)
i = 0
for index in area:
# Iterate over the neighbors of the current particle, starting with the closest:
for neigh in finder.find(index):
distances[i] = neigh.distance + distances[i]
i += 1
cal_lat_par = np.mean(distances) / num_neighbors
if np.abs(num - cal_lat_par) < 5 * 1e-3:
err = 0
assert err == 0
| [
"numpy.mean",
"numpy.abs",
"numpy.sqrt",
"gbmc_v0.util_funcs.compute_ovito_data",
"numpy.where",
"pytest.mark.skip",
"numpy.max",
"pytest.mark.parametrize",
"numpy.zeros",
"numpy.min",
"ovito.data.NearestNeighborFinder",
"numpy.shape"
] | [((113, 184), 'pytest.mark.skip', 'pytest.mark.skip', ([], {'reason': '"""we can\'t push the data to repo. It is large."""'}), '(reason="we can\'t push the data to repo. It is large.")\n', (129, 184), False, 'import pytest\n'), ((186, 412), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""filename0, lat_par, cut_off, num_neighbors, non_p_dir"""', "[('data/dump_1', 4.05, 10, 12, 2), ('../lammps_dump/dump_after.1', 4.05, 10,\n 12, 2), ('../lammps_dump/dump_befor.1', 4.05, 10, 12, 2)]"], {}), "('filename0, lat_par, cut_off, num_neighbors, non_p_dir'\n , [('data/dump_1', 4.05, 10, 12, 2), ('../lammps_dump/dump_after.1', \n 4.05, 10, 12, 2), ('../lammps_dump/dump_befor.1', 4.05, 10, 12, 2)])\n", (209, 412), False, 'import pytest\n'), ((596, 628), 'gbmc_v0.util_funcs.compute_ovito_data', 'uf.compute_ovito_data', (['filename0'], {}), '(filename0)\n', (617, 628), True, 'import gbmc_v0.util_funcs as uf\n'), ((1116, 1158), 'ovito.data.NearestNeighborFinder', 'NearestNeighborFinder', (['num_neighbors', 'data'], {}), '(num_neighbors, data)\n', (1137, 1158), False, 'from ovito.data import NearestNeighborFinder\n'), ((1176, 1197), 'numpy.zeros', 'np.zeros', (['num_particl'], {}), '(num_particl)\n', (1184, 1197), True, 'import numpy as np\n'), ((649, 659), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (656, 659), True, 'import numpy as np\n'), ((778, 836), 'numpy.where', 'np.where', (['((position[:, non_p_dir] > 0) & (ptm_struct == 1))'], {}), '((position[:, non_p_dir] > 0) & (ptm_struct == 1))\n', (786, 836), True, 'import numpy as np\n'), ((986, 1063), 'numpy.where', 'np.where', (['((position[:, non_p_dir] < max_Z) & (position[:, non_p_dir] > min_Z))'], {}), '((position[:, non_p_dir] < max_Z) & (position[:, non_p_dir] > min_Z))\n', (994, 1063), True, 'import numpy as np\n'), ((1085, 1099), 'numpy.shape', 'np.shape', (['area'], {}), '(area)\n', (1093, 1099), True, 'import numpy as np\n'), ((1452, 1470), 'numpy.mean', 'np.mean', (['distances'], {}), '(distances)\n', (1459, 1470), True, 'import numpy as np\n'), ((1494, 1519), 'numpy.abs', 'np.abs', (['(num - cal_lat_par)'], {}), '(num - cal_lat_par)\n', (1500, 1519), True, 'import numpy as np\n'), ((895, 923), 'numpy.min', 'np.min', (['pos_sc[:, non_p_dir]'], {}), '(pos_sc[:, non_p_dir])\n', (901, 923), True, 'import numpy as np\n'), ((935, 963), 'numpy.max', 'np.max', (['pos_sc[:, non_p_dir]'], {}), '(pos_sc[:, non_p_dir])\n', (941, 963), True, 'import numpy as np\n')] |
from .plot_external_data import plot
from gym_electric_motor.physical_systems import SynchronousMotorSystem
from gym.spaces import Box
import numpy as np
class FieldOrientedController:
"""
This class controls the currents of synchronous motors. In the case of continuous manipulated variables, the
control is performed in the rotating dq-coordinates. For this purpose, the two current components are optionally
decoupled and two independent current controllers are used.
In the case of discrete manipulated variables, control takes place in stator-fixed coordinates. The reference
values are converted into these coordinates so that a on-off controller calculates the corresponding
manipulated variable for each current component.
"""
def __init__(self, environment, stages, _controllers, ref_states, external_ref_plots=(), **controller_kwargs):
assert isinstance(environment.physical_system, SynchronousMotorSystem), 'No suitable Environment for FOC Controller'
t32 = environment.physical_system.electrical_motor.t_32
q = environment.physical_system.electrical_motor.q
self.backward_transformation = (lambda quantities, eps: t32(q(quantities, eps)))
self.tau = environment.physical_system.tau
self.ref_d_idx = np.where(ref_states == 'i_sd')[0][0]
self.ref_q_idx = np.where(ref_states == 'i_sq')[0][0]
self.d_idx = environment.state_names.index(ref_states[self.ref_d_idx])
self.q_idx = environment.state_names.index(ref_states[self.ref_q_idx])
self.action_space = environment.action_space
self.state_space = environment.physical_system.state_space
self.state_names = environment.state_names
self.i_sd_idx = environment.state_names.index('i_sd')
self.i_sq_idx = environment.state_names.index('i_sq')
self.u_sd_idx = environment.state_names.index('u_sd')
self.u_sq_idx = environment.state_names.index('u_sq')
self.u_a_idx = environment.state_names.index('u_a')
self.u_b_idx = environment.state_names.index('u_b')
self.u_c_idx = environment.state_names.index('u_c')
self.omega_idx = environment.state_names.index('omega')
self.eps_idx = environment.state_names.index('epsilon')
self.limit = environment.physical_system.limits
self.mp = environment.physical_system.electrical_motor.motor_parameter
self.psi_p = self.mp.get('psi_p', 0)
self.dead_time = 1.5 if environment.physical_system.converter._dead_time else 0.5
self.has_cont_action_space = type(self.action_space) is Box
self.external_ref_plots = external_ref_plots
for ext_ref_plot in self.external_ref_plots:
ext_ref_plot.set_reference(ref_states)
# Initialize continuous controllers
if self.has_cont_action_space:
assert len(stages[0]) == 2, 'Number of stages not correct'
self.decoupling = controller_kwargs.get('decoupling', True)
[self.u_sq_0, self.u_sd_0] = [0, 0]
self.d_controller = _controllers[stages[0][0]['controller_type']][1].make(
environment, stages[0][0], _controllers, **controller_kwargs)
self.q_controller = _controllers[stages[0][1]['controller_type']][1].make(
environment, stages[0][1], _controllers, **controller_kwargs)
# Initialize discrete controllers
else:
assert len(stages) == 3, 'Number of stages not correct'
self.abc_controller = [_controllers[stages[0][0]['controller_type']][1].make(
environment, stages[i][0], _controllers, **controller_kwargs) for i in range(3)]
self.i_abc_idx = [environment.state_names.index(state) for state in ['i_a', 'i_b', 'i_c']]
def control(self, state, reference):
"""
Main method that is called by the user to calculate the manipulated variable.
Args:
state: state of the gem environment
reference: reference for the controlled states
Returns:
action: action for the gem environment
"""
# Calculate delta epsilon
epsilon_d = state[self.eps_idx] * self.limit[self.eps_idx] + self.dead_time * self.tau * \
state[self.omega_idx] * self.limit[self.omega_idx] * self.mp['p']
# Check if action space is continuous
if self.has_cont_action_space:
# Decoupling of the d- and q-component
if self.decoupling:
self.u_sd_0 = -state[self.omega_idx] * self.mp['p'] * self.mp['l_q'] * state[self.i_sq_idx] * self.limit[
self.i_sq_idx] / self.limit[self.u_sd_idx] * self.limit[self.omega_idx]
self.u_sq_0 = state[self.omega_idx] * self.mp['p'] * (
state[self.i_sd_idx] * self.mp['l_d'] * self.limit[self.u_sd_idx] + self.psi_p) / self.limit[
self.u_sq_idx] * self.limit[self.omega_idx]
# Calculate the two actions
u_sd = self.d_controller.control(state[self.d_idx], reference[self.ref_d_idx]) + self.u_sd_0
u_sq = self.q_controller.control(state[self.q_idx], reference[self.ref_q_idx]) + self.u_sq_0
# Shifting the reference potential
action_temp = self.backward_transformation((u_sd, u_sq), epsilon_d)
action_temp = action_temp - 0.5 * (max(action_temp) + min(action_temp))
# Check limit and integrate
action = np.clip(action_temp, self.action_space.low[0], self.action_space.high[0])
if (action == action_temp).all():
self.d_controller.integrate(state[self.d_idx], reference[self.ref_d_idx])
self.q_controller.integrate(state[self.q_idx], reference[self.ref_q_idx])
else:
# Transform reference in abc coordinates
ref_abc = self.backward_transformation((reference[self.ref_d_idx], reference[self.ref_q_idx]), epsilon_d)
action = 0
# Calculate discrete action
for i in range(3):
action += (2 ** (2 - i)) * self.abc_controller[i].control(state[self.i_abc_idx[i]], ref_abc[i])
# Plot external data
plot(self.external_ref_plots, self.state_names, external_data=self.get_plot_data())
return action
@staticmethod
def get_plot_data():
# Getting the external data that should be plotted
return dict(ref_state=[], ref_value=[], external=[])
def reset(self):
# Reset the Controllers
if self.has_cont_action_space:
self.d_controller.reset()
self.q_controller.reset()
| [
"numpy.clip",
"numpy.where"
] | [((5589, 5662), 'numpy.clip', 'np.clip', (['action_temp', 'self.action_space.low[0]', 'self.action_space.high[0]'], {}), '(action_temp, self.action_space.low[0], self.action_space.high[0])\n', (5596, 5662), True, 'import numpy as np\n'), ((1325, 1355), 'numpy.where', 'np.where', (["(ref_states == 'i_sd')"], {}), "(ref_states == 'i_sd')\n", (1333, 1355), True, 'import numpy as np\n'), ((1387, 1417), 'numpy.where', 'np.where', (["(ref_states == 'i_sq')"], {}), "(ref_states == 'i_sq')\n", (1395, 1417), True, 'import numpy as np\n')] |
import os
import shutil
import tempfile
import numpy as np
from astropy.io import fits
from soxs.spectra import Spectrum
from soxs.instrument import instrument_simulator
from soxs.simput import SimputSpectrum, SimputCatalog
from soxs.events import filter_events
def test_filter():
tmpdir = tempfile.mkdtemp()
curdir = os.getcwd()
os.chdir(tmpdir)
alpha_sim = 1.1
nH_sim = 0.02
norm_sim = 1.0e-4
redshift = 0.01
exp_time = (100.0, "ks")
area = 1000.0
inst_name = "chandra_acisi_cy0"
spec = Spectrum.from_powerlaw(alpha_sim, redshift, norm_sim, 0.1, 10.0,
2000)
spec.apply_foreground_absorption(nH_sim, model="tbabs")
pt_src = SimputSpectrum.from_spectrum("plaw_model", spec, 30.0, 45.0)
cat = SimputCatalog.from_source("plaw_model_simput.fits", pt_src,
overwrite=True)
instrument_simulator("plaw_model_simput.fits", "evt.fits",
exp_time, inst_name, [30.0, 45.0], instr_bkgnd=False,
ptsrc_bkgnd=False, foreground=True, prng=24)
filter_events("evt.fits", "evt_filter_en.fits", emin=0.5, emax=2.0, overwrite=True)
with fits.open("evt_filter_en.fits") as f:
e = f["EVENTS"].data["ENERGY"]
assert np.logical_and(e > 500.0, e < 2000.0).all()
reg = "# Region file format: DS9\nimage\ncircle(2430,2454,200)\n"
filter_events("evt.fits", "evt_filter_reg.fits", region=reg, overwrite=True)
with fits.open("evt_filter_reg.fits") as f:
x = f["EVENTS"].data["X"]
y = f["EVENTS"].data["Y"]
r = np.sqrt((x-2430)**2+(y-2454)**2)
assert np.all(r < 201.0)
os.chdir(curdir)
shutil.rmtree(tmpdir)
| [
"soxs.events.filter_events",
"numpy.sqrt",
"numpy.logical_and",
"soxs.instrument.instrument_simulator",
"soxs.simput.SimputCatalog.from_source",
"soxs.spectra.Spectrum.from_powerlaw",
"os.chdir",
"os.getcwd",
"soxs.simput.SimputSpectrum.from_spectrum",
"tempfile.mkdtemp",
"shutil.rmtree",
"ast... | [((299, 317), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), '()\n', (315, 317), False, 'import tempfile\n'), ((331, 342), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (340, 342), False, 'import os\n'), ((347, 363), 'os.chdir', 'os.chdir', (['tmpdir'], {}), '(tmpdir)\n', (355, 363), False, 'import os\n'), ((541, 611), 'soxs.spectra.Spectrum.from_powerlaw', 'Spectrum.from_powerlaw', (['alpha_sim', 'redshift', 'norm_sim', '(0.1)', '(10.0)', '(2000)'], {}), '(alpha_sim, redshift, norm_sim, 0.1, 10.0, 2000)\n', (563, 611), False, 'from soxs.spectra import Spectrum\n'), ((720, 780), 'soxs.simput.SimputSpectrum.from_spectrum', 'SimputSpectrum.from_spectrum', (['"""plaw_model"""', 'spec', '(30.0)', '(45.0)'], {}), "('plaw_model', spec, 30.0, 45.0)\n", (748, 780), False, 'from soxs.simput import SimputSpectrum, SimputCatalog\n'), ((791, 866), 'soxs.simput.SimputCatalog.from_source', 'SimputCatalog.from_source', (['"""plaw_model_simput.fits"""', 'pt_src'], {'overwrite': '(True)'}), "('plaw_model_simput.fits', pt_src, overwrite=True)\n", (816, 866), False, 'from soxs.simput import SimputSpectrum, SimputCatalog\n'), ((908, 1073), 'soxs.instrument.instrument_simulator', 'instrument_simulator', (['"""plaw_model_simput.fits"""', '"""evt.fits"""', 'exp_time', 'inst_name', '[30.0, 45.0]'], {'instr_bkgnd': '(False)', 'ptsrc_bkgnd': '(False)', 'foreground': '(True)', 'prng': '(24)'}), "('plaw_model_simput.fits', 'evt.fits', exp_time,\n inst_name, [30.0, 45.0], instr_bkgnd=False, ptsrc_bkgnd=False,\n foreground=True, prng=24)\n", (928, 1073), False, 'from soxs.instrument import instrument_simulator\n'), ((1121, 1208), 'soxs.events.filter_events', 'filter_events', (['"""evt.fits"""', '"""evt_filter_en.fits"""'], {'emin': '(0.5)', 'emax': '(2.0)', 'overwrite': '(True)'}), "('evt.fits', 'evt_filter_en.fits', emin=0.5, emax=2.0,\n overwrite=True)\n", (1134, 1208), False, 'from soxs.events import filter_events\n'), ((1425, 1501), 'soxs.events.filter_events', 'filter_events', (['"""evt.fits"""', '"""evt_filter_reg.fits"""'], {'region': 'reg', 'overwrite': '(True)'}), "('evt.fits', 'evt_filter_reg.fits', region=reg, overwrite=True)\n", (1438, 1501), False, 'from soxs.events import filter_events\n'), ((1701, 1717), 'os.chdir', 'os.chdir', (['curdir'], {}), '(curdir)\n', (1709, 1717), False, 'import os\n'), ((1722, 1743), 'shutil.rmtree', 'shutil.rmtree', (['tmpdir'], {}), '(tmpdir)\n', (1735, 1743), False, 'import shutil\n'), ((1214, 1245), 'astropy.io.fits.open', 'fits.open', (['"""evt_filter_en.fits"""'], {}), "('evt_filter_en.fits')\n", (1223, 1245), False, 'from astropy.io import fits\n'), ((1511, 1543), 'astropy.io.fits.open', 'fits.open', (['"""evt_filter_reg.fits"""'], {}), "('evt_filter_reg.fits')\n", (1520, 1543), False, 'from astropy.io import fits\n'), ((1630, 1672), 'numpy.sqrt', 'np.sqrt', (['((x - 2430) ** 2 + (y - 2454) ** 2)'], {}), '((x - 2430) ** 2 + (y - 2454) ** 2)\n', (1637, 1672), True, 'import numpy as np\n'), ((1678, 1695), 'numpy.all', 'np.all', (['(r < 201.0)'], {}), '(r < 201.0)\n', (1684, 1695), True, 'import numpy as np\n'), ((1306, 1343), 'numpy.logical_and', 'np.logical_and', (['(e > 500.0)', '(e < 2000.0)'], {}), '(e > 500.0, e < 2000.0)\n', (1320, 1343), True, 'import numpy as np\n')] |
import numpy as np
from sklearn.metrics import roc_auc_score, accuracy_score
import torch
import torch.nn as nn
from torch.autograd import Variable
from globalbaz import args, DP, device
from tqdm import tqdm
from models import *
# Defining criterion with weighted loss based on bias to be unlearned
def criterion_func(df):
if args.instrument:
lst = df['instrument'].value_counts().sort_index().tolist()
lst2 = df['marked'].value_counts().sort_index().tolist()
elif args.instrument and args.rulers:
lst = df['instrument'].value_counts().sort_index().tolist()
lst2 = df['scale'].value_counts().sort_index().tolist()
else:
lst = df['marked'].value_counts().sort_index().tolist()
lst2 = df['scale'].value_counts().sort_index().tolist() # placeholder
sum_lst = sum(lst)
sum_lst2 = sum(lst2)
class_freq = []
class_freq2 = []
for i in lst:
class_freq.append(i / sum_lst * 100)
weights = torch.tensor(class_freq, dtype=torch.float32)
for i in lst2:
class_freq2.append(i / sum_lst2 * 100)
weights2 = torch.tensor(class_freq2, dtype=torch.float32)
weights = weights / weights.sum()
weights2 = weights2 / weights2.sum()
weights = 1.0 / weights
weights2 = 1.0 / weights2
weights = weights / weights.sum()
weights2 = weights2 / weights2.sum()
if args.debias_config != 'baseline': # Only printing auxiliary weights head if using debiasing head
print(f'weights_aux: {weights}')
print(f'weights_aux_2: {weights2}')
weights = weights.to(device)
weights2 = weights2.to(device)
# Note CrossEntropyLoss & BCEWithLogitsLoss includes the Softmax function so logits should be passed in (no softmax layer in model)
criterion = nn.BCEWithLogitsLoss() # nn.CrossEntropyLoss()
criterion_aux = nn.CrossEntropyLoss(weight=weights)
criterion_aux2 = nn.CrossEntropyLoss(weight=weights2)
return criterion, criterion_aux, criterion_aux2
# Defining one training epoch for baseline model
def train_epoch_baseline(model_encoder, model_classifier, loader, optimizer, criterion):
# Setting to train mode
model_encoder.train()
model_classifier.train()
train_loss = [] # creating loss list
bar = tqdm(loader) # using tqdm to display progress bar
for (data, target, _, _) in bar:
optimizer.zero_grad() # zeroing gradients
data, target = data.to(device), target.to(device) # sending data to GPU
feat_out = model_encoder(data) # creating feature representation using the encoder
logits = model_classifier(feat_out) # using the main classifier to get output logits
target = target.unsqueeze(1).type_as(logits) # unsqueezing to[batch_size,1] and same dtype as logits
loss = criterion(logits, target) # calculating loss using categorical crossentorpy
loss.backward() # backpropegating to calculate gradients
optimizer.step() # updating weights
loss_np = loss.detach().cpu().numpy() # sending loss to cpu
train_loss.append(loss_np) # appending loss to loss list
smooth_loss = sum(train_loss[-100:]) / min(len(train_loss), 100) # calculating smooth loss
bar.set_description('loss: %.5f, smth: %.5f' % (loss_np, smooth_loss)) # metrics for loading bar
return train_loss
# Defining one training epoch for learning not to learn model
def train_epoch_LNTL(model_encoder, model_classifier, model_aux, loader, optimizer, optimizer_aux, criterion, criterion_aux):
# setting models to train mode
model_encoder.train()
model_classifier.train()
model_aux.train()
# empty lists for training loss and auxiliary training loss
train_loss = []
train_loss_aux = []
# adding progress bar for easier monitoring during training
bar = tqdm(loader)
for (data, target, target_aux, target_aux2) in bar:
if args.rulers: # Switching to ruler labels
target_aux = target_aux2
# zeroing gradients
optimizer.zero_grad()
optimizer_aux.zero_grad()
# sending data and targets to GPU
data, target, target_aux = data.to(device), target.to(device), target_aux.to(device)
# predicting with model and getting feature maps and logits
feat_out = model_encoder(data) # creating feature representation using the encoder
logits = model_classifier(feat_out) # using the main classifier to get output logits
target = target.unsqueeze(1).type_as(logits) # unsqueezing to [batch_size,1] and same dtype as logits
# ######----------------Main Head & Pseudo Loss---------------###########
# taking pseudo prediction from output of auxillary head (output of softmax)
_, pseudo_pred_aux = model_aux(feat_out)
# loss for main prediction calculated using crossentropyloss and logits output
loss_main = criterion(logits, target)
# pseudo auxilary loss calculated
loss_pseudo_aux = torch.mean(torch.sum(pseudo_pred_aux * torch.log(pseudo_pred_aux), 1))
# pseudo auxiliary loss multiplied by lambda and added to main prediction loss
loss = loss_main + loss_pseudo_aux * args.lambdaa
# backpropegation to calculate gradients
loss.backward()
# updating weights
optimizer.step()
# ######-------------Auxiliary Head Classifier Update------------###########
# zeroing gradients from last step
optimizer.zero_grad()
optimizer_aux.zero_grad()
# predicting with model and getting feature maps and logits
feat_out = model_encoder(data) # creating feaure representation using the encoder
# applying gradient reversal to outputted features of main network
if args.GRL:
feat_out = grad_reverse(feat_out)
# getting logits from auxillary head output (gradient reversal applied ready for updating)
logits_aux, _ = model_aux(feat_out)
# calculating auxiliary loss
loss_aux = criterion_aux(logits_aux, target_aux)
# backpropegating to calculate gradients (with reversal since gradient reversal applied above)
loss_aux.backward()
# updating weights
optimizer.step()
optimizer_aux.step()
# sending losses to cpu for printing
loss_np = loss.detach().cpu().numpy()
loss_aux_np = loss_aux.detach().cpu().numpy()
# appending losses to lists
train_loss.append(loss_np)
train_loss_aux.append(loss_aux_np)
# calculating smooth losses
smooth_loss = sum(train_loss[-100:]) / min(len(train_loss), 100)
smooth_loss_aux = sum(train_loss_aux[-100:]) / min(len(train_loss_aux), 100)
bar.set_description('loss: %.5f, smth: %.5f, aux_loss: %.5f, aux_smth: %.5f' %
(loss_np, smooth_loss, loss_aux_np, smooth_loss_aux,))
return train_loss, train_loss_aux
# Defining one training epoch for learning not to learn
def train_epoch_TABE(model_encoder, model_classifier, model_aux, loader, optimizer, optimizer_aux,
optimizer_confusion, criterion, criterion_aux):
# setting lambda as tuning parameter for auxiliary loss
# setting models to train mode
model_encoder.train()
model_classifier.train()
model_aux.train()
# empty lists for training loss and auxiliary training loss
train_loss = []
train_loss_aux = []
# adding progress bar for easier monitoring during training
bar = tqdm(loader)
for (data, target, target_aux, target_aux2) in bar:
if args.rulers: # switching targets round if wanting to use rulers as target
target_aux = target_aux2
# zeroing gradients
optimizer.zero_grad()
optimizer_aux.zero_grad()
optimizer_confusion.zero_grad()
# sending data and targets to cpu
data, target, target_aux = data.to(device), target.to(device), target_aux.to(device)
# predicting with model and getting feature maps and logits
feat_out = model_encoder(data) # creating feaure representation using the encoder
logits = model_classifier(feat_out) # using the main classifier to get output logits
target = target.unsqueeze(1).type_as(logits) # unsqueezing to[batch_size,1] and same dtype as logits
# ######----------------Main Head & Pseudo Loss---------------###########
loss_main = criterion(logits, target) # using categorical cross entropy (softmax built in) to get loss
_, output_conf = model_aux(feat_out) # getting probabilities from auxiliary head
# defining uniform distribution for calculating KL divergence for confusion loss
uni_distrib = torch.FloatTensor(output_conf.size()).uniform_(0, 1)
uni_distrib = uni_distrib.to(device) # sending to GPU
uni_distrib = Variable(uni_distrib)
loss_conf = - args.alpha * (torch.sum(uni_distrib * torch.log(output_conf))) / float(output_conf.size(0)) # calculating confusion loss
loss = loss_main + loss_conf # adding main and confusion losses
# backpropegation to calculate gradients
loss.backward()
# updating weights
optimizer.step()
optimizer_confusion.step()
# ######-------------------------------Auxiliary Head Classifier Update-------------------------------###########
# zeroing gradients from last step
optimizer.zero_grad()
optimizer_aux.zero_grad()
# predicting with model and getting feature maps and logits
feat_out = model_encoder(data) # creating feaure representation using the encoder
# applying gradient reversal to outputted features of main network
if args.GRL:
feat_out = grad_reverse(feat_out)
# getting logits from auxillary head output (gradient reversal applied ready for updating)
logits_aux, _ = model_aux(feat_out)
# calculating auxiliary loss
loss_aux = criterion_aux(logits_aux, target_aux)
# backpropegating to calculate gradients (with reversal since gradient reversal applied above)
loss_aux.backward()
# updating weights
optimizer.step()
optimizer_aux.step()
# sending losses to cpu for printing
loss_np = loss.detach().cpu().numpy()
loss_aux_np = loss_aux.detach().cpu().numpy()
# appending losses to lists
train_loss.append(loss_np)
train_loss_aux.append(loss_aux_np)
# calculating smooth losses
smooth_loss = sum(train_loss[-100:]) / min(len(train_loss), 100)
smooth_loss_aux = sum(train_loss_aux[-100:]) / min(len(train_loss_aux), 100)
bar.set_description('loss: %.5f, smth: %.5f, aux_loss: %.5f, aux_smth: %.5f' %
(loss_np, smooth_loss, loss_aux_np, smooth_loss_aux,))
return train_loss, train_loss_aux
# Defining one training epoch for learning not to learn
def train_epoch_doubleTABE(model_encoder, model_classifier, model_aux, model_aux2, loader, optimizer, optimizer_aux,
optimizer_aux2, optimizer_confusion, criterion, criterion_aux, criterion_aux2):
# setting lambda as tuning parameter for auxiliary loss
# setting models to train mode
model_encoder.train()
model_classifier.train()
model_aux.train()
model_aux2.train()
# empty lists for training loss and auxiliary training loss
train_loss = []
train_loss_aux = []
train_loss_aux2 = []
# adding progress bar for easier monitoring during training
bar = tqdm(loader)
for (data, target, target_aux, target_aux2) in bar:
# zeroing gradients
optimizer.zero_grad()
optimizer_aux.zero_grad()
optimizer_aux2.zero_grad()
optimizer_confusion.zero_grad()
# sending data and targets to cpu
data, target, target_aux, target_aux2 = data.to(device), target.to(device), target_aux.to(device), target_aux2.to(device)
# predicting with model and getting feature maps and logits
feat_out = model_encoder(data) # creating feaure representation using the encoder
logits = model_classifier(feat_out) # using the main classifier to get output logits
target = target.unsqueeze(1).type_as(logits) # unsqueezing to[batch_size,1] and same dtype as logits
# ######----------------Main Head & Confusion Loss---------------###########
loss_main = criterion(logits, target) # using categorical cross entropy (softmax built in) to get loss
_, output_conf = model_aux(feat_out) # getting probabilities from auxiliary head
_, output_conf2 = model_aux2(feat_out) # getting probabilities from auxiliary head
# defining uniform distribution for calculating KL divergence for confusion loss
uni_distrib = torch.FloatTensor(output_conf.size()).uniform_(0, 1)
uni_distrib = uni_distrib.to(device) # sending to GPU
uni_distrib = Variable(uni_distrib)
loss_conf = - args.alpha * (torch.sum(uni_distrib * torch.log(output_conf))) / float(output_conf.size(0)) # calculating confusion loss
uni_distrib2 = torch.FloatTensor(output_conf2.size()).uniform_(0, 1)
uni_distrib2 = uni_distrib2.to(device) # sending to GPU
uni_distrib2 = Variable(uni_distrib2)
loss_conf2 = - args.alpha * (torch.sum(uni_distrib2 * torch.log(output_conf2))) / float(output_conf2.size(0)) # calculating confusion loss
loss = loss_main + loss_conf + loss_conf2 # adding main and confusion losses
# backpropegation to calculate gradients
loss.backward()
# updating weights
optimizer.step()
optimizer_confusion.step()
# ######-------------------------------Auxiliary Head Classifier Update-------------------------------###########
# zeroing gradients from last step
optimizer.zero_grad()
optimizer_aux.zero_grad()
optimizer_aux2.zero_grad()
# predicting with model and getting feature maps and logits
feat_out = model_encoder(data) # creating feaure representation using the encoder
# applying gradient reversal to outputted features of main network
if args.GRL:
feat_out = grad_reverse(feat_out)
# getting logits from auxillary head output (gradient reversal applied ready for updating)
logits_aux, _ = model_aux(feat_out)
logits_aux2, _ = model_aux2(feat_out)
# calculating auxiliary loss
loss_aux = criterion_aux(logits_aux, target_aux)
loss_aux2 = criterion_aux2(logits_aux2, target_aux2)
aux_losses = loss_aux + loss_aux2
# backpropegating to calculate gradients
aux_losses.backward()
# updating weights
optimizer.step()
optimizer_aux.step()
optimizer_aux2.step()
# sending losses to cpu for printing
loss_np = loss.detach().cpu().numpy()
loss_aux_np = loss_aux.detach().cpu().numpy() # sending loss to cpu
loss_aux2_np = loss_aux2.detach().cpu().numpy() # sending loss to cpu
# ------------------------------------------------------------------
# appending losses to loss lists
train_loss.append(loss_np)
train_loss_aux.append(loss_aux_np)
train_loss_aux2.append(loss_aux2_np)
# calculating smooth losses
smooth_loss = sum(train_loss[-100:]) / min(len(train_loss), 100)
smooth_loss_aux = sum(train_loss_aux[-100:]) / min(len(train_loss_aux), 100)
smooth_loss_aux2 = sum(train_loss_aux2[-100:]) / min(len(train_loss_aux2), 100)
# metrics to be displayed with progress bar
bar.set_description(
'loss: %.5f, smth: %.5f, aux_loss: %.5f, aux_loss2: %.5f, aux_smth: %.5f, aux_smth2: %.5f' %
(loss_np, smooth_loss, loss_aux_np, loss_aux2_np, smooth_loss_aux, smooth_loss_aux2))
return train_loss, train_loss_aux, train_loss_aux2
# Defining one training epoch for learning not to learn
def train_epoch_BOTH(model_encoder, model_classifier, model_aux, model_aux2, loader, optimizer, optimizer_aux,
optimizer_aux2, optimizer_confusion, criterion, criterion_aux, criterion_aux2):
# setting lambda as tuning parameter for auxiliary loss
# setting models to train mode
model_encoder.train()
model_classifier.train()
model_aux.train()
model_aux2.train()
# empty lists for training loss and auxiliary training loss
train_loss = []
train_loss_aux = []
train_loss_aux2 = []
bar = tqdm(loader) # using tqdm to show progress bar
for (data, target, target_aux_pre, target_aux2_pre) in bar:
optimizer.zero_grad()
optimizer_aux.zero_grad()
optimizer_aux2.zero_grad()
optimizer_confusion.zero_grad()
if args.switch_heads: # allowing heads to switch by switchin labels
target_aux = target_aux2_pre
target_aux2 = target_aux_pre
else:
target_aux = target_aux_pre
target_aux2 = target_aux2_pre
data, target, target_aux, target_aux2 = data.to(device), target.to(device), target_aux.to(
device), target_aux2.to(device) # sending data and targets to GPU
# predicting with model and getting feature maps and logits
feat_out = model_encoder(data) # creating feaure representation using the encoder
logits = model_classifier(feat_out) # using the main classifier to get output logits
target = target.unsqueeze(1).type_as(logits) # unsqueezing to[batch_size,1] and same dtype as logits
# ######---------Main Head & Confusion Loss & pseudo loss---------###########
loss_main = criterion(logits, target) # using categorical cross entropy (softmax built in) to get loss
_, output_conf = model_aux(feat_out) # getting probabilities from first auxiliary head
uni_distrib = torch.FloatTensor(output_conf.size()).uniform_(0, 1) # calculating uniform distribution
uni_distrib = uni_distrib.to(device) # sending to GPU
uni_distrib = Variable(uni_distrib)
loss_conf = - args.alpha * (torch.sum(uni_distrib * torch.log(output_conf))) / float(
output_conf.size(0)) # calculating confusion loss
_, pseudo_pred_aux = model_aux(feat_out) # taking pseudo prediction from output of auxillary head (output of softmax)
loss_pseudo_aux = torch.mean(
torch.sum(pseudo_pred_aux * torch.log(pseudo_pred_aux), 1)) # calculating auxiliary pseudo loss
loss = loss_main + loss_conf + loss_pseudo_aux * args.lambdaa # adding losses before backpropegation
loss.backward() # backpropegating loss to calculate gradients
optimizer.step() # updating weights
optimizer_confusion.step()
# ######----------------Auxiliary Head Classifier Update----------------###########
# zeroing gradients from last step
optimizer.zero_grad()
optimizer_aux.zero_grad()
optimizer_aux2.zero_grad()
# predicting with model and getting feature maps and logits
feat_out = model_encoder(data) # creating feaure representation using the encoder
# applying gradient reversal to outputted features of main network
if args.GRL:
feat_out = grad_reverse(feat_out)
# getting logits from auxillary head output (gradient reversal applied ready for updating)
logits_aux, _ = model_aux(feat_out)
logits_aux2, _ = model_aux2(feat_out)
# calculating auxiliary loss
if args.switch_heads:
loss_aux = criterion_aux2(logits_aux, target_aux) # calculating auxiliary loss
loss_aux2 = criterion_aux(logits_aux2, target_aux2) # calculating 2nd auxiliary loss
else:
loss_aux = criterion_aux(logits_aux, target_aux) # calculating auxiliary loss
loss_aux2 = criterion_aux2(logits_aux2, target_aux2) # calculating 2nd auxiliary loss
aux_losses = loss_aux + loss_aux2
# backpropegating to calculate gradients
aux_losses.backward()
# updating weights
optimizer.step()
optimizer_aux.step()
optimizer_aux2.step()
# sending losses to cpu for printing
loss_np = loss.detach().cpu().numpy()
loss_aux_np = loss_aux.detach().cpu().numpy() # sending loss to cpu
loss_aux2_np = loss_aux2.detach().cpu().numpy() # sending loss to cpu
# ------------------------------------------------------------------
# appending losses to loss lists
train_loss.append(loss_np)
train_loss_aux.append(loss_aux_np)
train_loss_aux2.append(loss_aux2_np)
# calculating smooth losses
smooth_loss = sum(train_loss[-100:]) / min(len(train_loss), 100)
smooth_loss_aux = sum(train_loss_aux[-100:]) / min(len(train_loss_aux), 100)
smooth_loss_aux2 = sum(train_loss_aux2[-100:]) / min(len(train_loss_aux2), 100)
# metrics to be displayed with progress bar
bar.set_description(
'loss: %.5f, smth: %.5f, aux_loss: %.5f, aux_loss2: %.5f, aux_smth: %.5f, aux_smth2: %.5f' % (
loss_np, smooth_loss, loss_aux_np, loss_aux2_np, smooth_loss_aux, smooth_loss_aux2))
return train_loss, train_loss_aux, train_loss_aux2
# Defining one training epoch for learning not to learn
def train_epoch_doubleLNTL(model_encoder, model_classifier, model_aux, model_aux2, loader, optimizer, optimizer_aux,
optimizer_aux2, criterion, criterion_aux, criterion_aux2):
# setting lambda as tuning parameter for auxiliary loss
# setting models to train mode
model_encoder.train()
model_classifier.train()
model_aux.train()
model_aux2.train()
# empty lists for training loss and auxiliary training loss
train_loss = []
train_loss_aux = []
train_loss_aux2 = []
bar = tqdm(loader) # using tqdm to show progress bar
for (data, target, target_aux, target_aux2) in bar:
optimizer.zero_grad()
optimizer_aux.zero_grad()
optimizer_aux2.zero_grad()
data, target, target_aux, target_aux2 = data.to(device), target.to(device), target_aux.to(
device), target_aux2.to(device) # sending data and targets to GPU
# predicting with model and getting feature maps and logits
feat_out = model_encoder(data) # creating feaure representation using the encoder
logits = model_classifier(feat_out) # using the main classifier to get output logits
target = target.unsqueeze(1).type_as(logits) # unsqueezing to[batch_size,1] and same dtype as logits
# ######----------------Main Head & Pseudo Losses---------------###########
loss_main = criterion(logits, target) # using categorical cross entropy (softmax built in) to get loss
_, pseudo_pred_aux = model_aux(feat_out) # taking pseudo prediction from output of auxillary head (output of softmax)
loss_pseudo_aux = torch.mean(
torch.sum(pseudo_pred_aux * torch.log(pseudo_pred_aux), 1)) # calculating auxiliary pseudo loss
_, pseudo_pred_aux2 = model_aux2(feat_out) # taking pseudo prediction from output of auxillary head (output of softmax)
loss_pseudo_aux2 = torch.mean(
torch.sum(pseudo_pred_aux2 * torch.log(pseudo_pred_aux2), 1)) # calculating auxiliary pseudo loss
loss = loss_main + (loss_pseudo_aux + loss_pseudo_aux2)*args.lambdaa # adding losses before backpropegation
loss.backward() # backpropegating loss to calculate gradients
optimizer.step() # updating weights
# ######-------------Auxiliary Head Classifier Update------------###########
# zeroing gradients from last step
optimizer.zero_grad()
optimizer_aux.zero_grad()
optimizer_aux2.zero_grad()
# predicting with model and getting feature maps and logits
feat_out = model_encoder(data) # creating feaure representation using the encoder
# applying gradient reversal to outputted features of main network
if args.GRL:
feat_out = grad_reverse(feat_out)
# getting logits from auxillary head output (gradient reversal applied ready for updating)
logits_aux, _ = model_aux(feat_out)
logits_aux2, _ = model_aux2(feat_out)
# calculating auxiliary loss
loss_aux = criterion_aux(logits_aux, target_aux) # calculating auxiliary loss
loss_aux2 = criterion_aux2(logits_aux2, target_aux2) # calculating 2nd auxiliary loss
aux_losses = loss_aux + loss_aux2
# backpropegating to calculate gradients
aux_losses.backward()
# updating weights
optimizer.step()
optimizer_aux.step()
optimizer_aux2.step()
# sending losses to cpu for printing
loss_np = loss.detach().cpu().numpy()
loss_aux_np = loss_aux.detach().cpu().numpy() # sending loss to cpu
loss_aux2_np = loss_aux2.detach().cpu().numpy() # sending loss to cpu
# ------------------------------------------------------------------
# appending losses to loss lists
train_loss.append(loss_np)
train_loss_aux.append(loss_aux_np)
train_loss_aux2.append(loss_aux2_np)
# calculating smooth losses
smooth_loss = sum(train_loss[-100:]) / min(len(train_loss), 100)
smooth_loss_aux = sum(train_loss_aux[-100:]) / min(len(train_loss_aux), 100)
smooth_loss_aux2 = sum(train_loss_aux2[-100:]) / min(len(train_loss_aux2), 100)
# metrics to be displayed with progress bar
bar.set_description(
'loss: %.5f, smth: %.5f, aux_loss: %.5f, aux_loss2: %.5f, aux_smth: %.5f, aux_smth2: %.5f' % (
loss_np, smooth_loss, loss_aux_np, loss_aux2_np, smooth_loss_aux, smooth_loss_aux2))
return train_loss, train_loss_aux, train_loss_aux2
# translations for testing (test-time augmentation)
def get_trans(img, I):
if I >= 4:
img = img.transpose(2, 3)
if I % 4 == 0:
return img
elif I % 4 == 1:
return img.flip(2)
elif I % 4 == 2:
return img.flip(3)
elif I % 4 == 3:
return img.flip(2).flip(3)
def val_epoch(model_encoder, model_classifier, loader, criterion, n_test=1, get_output=False):
# setting models to evaluation mode
model_encoder.eval()
model_classifier.eval()
# setting up storage lists
val_loss = []
LOGITS = []
PROBS = []
TARGETS = []
with torch.no_grad():
for (data, target, _, _) in tqdm(loader): # using tqdm for progress bar
data, target = data.to(device), target.to(device) # sending data to GPU
logits = torch.zeros((data.shape[0], args.out_dim)).to(device) # creating blank tensor for logits
probs = torch.zeros((data.shape[0], args.out_dim)).to(device) # creating blank tensor for probabilities
# using translations to test on same image in different positions and using voting for consensus
for I in range(n_test):
feat_out = model_encoder(get_trans(data, I)) # getting feature representation from encoder
l = model_classifier(feat_out) # getting logits from main classifier head
logits += l # adding logits to logits tensor
probs += torch.sigmoid(l) # adding probabilities to probabilities tensor
logits /= n_test # dividing logits by number of tests for consensus
probs /= n_test # dividing probabilities by number of tests for consensus
# appending logits, probabilities and targets to storage lists
LOGITS.append(logits.detach().cpu())
PROBS.append(probs.detach().cpu())
TARGETS.append(target.detach().cpu())
target = target.unsqueeze(1).type_as(logits) # Unsqueezing to[batch_size,1] and same dtype as logits
loss = criterion(logits, target) # getting batch loss
val_loss.append(loss.detach().cpu().numpy()) # getting batch validation loss
val_loss = np.mean(val_loss) # getting overall validation loss
# converting to numpy
LOGITS = torch.cat(LOGITS).numpy()
PROBS = torch.cat(PROBS).numpy()
TARGETS = torch.cat(TARGETS).numpy()
if get_output:
return PROBS, TARGETS
else:
acc = accuracy_score(TARGETS, np.round(PROBS)) # calculating accuracy, 0.5 threshold
auc = roc_auc_score(TARGETS, PROBS) # calculating area under the curve
return val_loss, acc, auc
| [
"numpy.mean",
"torch.log",
"torch.nn.CrossEntropyLoss",
"numpy.round",
"tqdm.tqdm",
"torch.sigmoid",
"sklearn.metrics.roc_auc_score",
"torch.tensor",
"torch.nn.BCEWithLogitsLoss",
"torch.no_grad",
"torch.autograd.Variable",
"torch.zeros",
"torch.cat"
] | [((977, 1022), 'torch.tensor', 'torch.tensor', (['class_freq'], {'dtype': 'torch.float32'}), '(class_freq, dtype=torch.float32)\n', (989, 1022), False, 'import torch\n'), ((1104, 1150), 'torch.tensor', 'torch.tensor', (['class_freq2'], {'dtype': 'torch.float32'}), '(class_freq2, dtype=torch.float32)\n', (1116, 1150), False, 'import torch\n'), ((1778, 1800), 'torch.nn.BCEWithLogitsLoss', 'nn.BCEWithLogitsLoss', ([], {}), '()\n', (1798, 1800), True, 'import torch.nn as nn\n'), ((1846, 1881), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {'weight': 'weights'}), '(weight=weights)\n', (1865, 1881), True, 'import torch.nn as nn\n'), ((1903, 1939), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {'weight': 'weights2'}), '(weight=weights2)\n', (1922, 1939), True, 'import torch.nn as nn\n'), ((2268, 2280), 'tqdm.tqdm', 'tqdm', (['loader'], {}), '(loader)\n', (2272, 2280), False, 'from tqdm import tqdm\n'), ((3840, 3852), 'tqdm.tqdm', 'tqdm', (['loader'], {}), '(loader)\n', (3844, 3852), False, 'from tqdm import tqdm\n'), ((7546, 7558), 'tqdm.tqdm', 'tqdm', (['loader'], {}), '(loader)\n', (7550, 7558), False, 'from tqdm import tqdm\n'), ((11639, 11651), 'tqdm.tqdm', 'tqdm', (['loader'], {}), '(loader)\n', (11643, 11651), False, 'from tqdm import tqdm\n'), ((16663, 16675), 'tqdm.tqdm', 'tqdm', (['loader'], {}), '(loader)\n', (16667, 16675), False, 'from tqdm import tqdm\n'), ((22065, 22077), 'tqdm.tqdm', 'tqdm', (['loader'], {}), '(loader)\n', (22069, 22077), False, 'from tqdm import tqdm\n'), ((28290, 28307), 'numpy.mean', 'np.mean', (['val_loss'], {}), '(val_loss)\n', (28297, 28307), True, 'import numpy as np\n'), ((8905, 8926), 'torch.autograd.Variable', 'Variable', (['uni_distrib'], {}), '(uni_distrib)\n', (8913, 8926), False, 'from torch.autograd import Variable\n'), ((13042, 13063), 'torch.autograd.Variable', 'Variable', (['uni_distrib'], {}), '(uni_distrib)\n', (13050, 13063), False, 'from torch.autograd import Variable\n'), ((13374, 13396), 'torch.autograd.Variable', 'Variable', (['uni_distrib2'], {}), '(uni_distrib2)\n', (13382, 13396), False, 'from torch.autograd import Variable\n'), ((18206, 18227), 'torch.autograd.Variable', 'Variable', (['uni_distrib'], {}), '(uni_distrib)\n', (18214, 18227), False, 'from torch.autograd import Variable\n'), ((26705, 26720), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (26718, 26720), False, 'import torch\n'), ((26758, 26770), 'tqdm.tqdm', 'tqdm', (['loader'], {}), '(loader)\n', (26762, 26770), False, 'from tqdm import tqdm\n'), ((28654, 28683), 'sklearn.metrics.roc_auc_score', 'roc_auc_score', (['TARGETS', 'PROBS'], {}), '(TARGETS, PROBS)\n', (28667, 28683), False, 'from sklearn.metrics import roc_auc_score, accuracy_score\n'), ((28382, 28399), 'torch.cat', 'torch.cat', (['LOGITS'], {}), '(LOGITS)\n', (28391, 28399), False, 'import torch\n'), ((28420, 28436), 'torch.cat', 'torch.cat', (['PROBS'], {}), '(PROBS)\n', (28429, 28436), False, 'import torch\n'), ((28459, 28477), 'torch.cat', 'torch.cat', (['TARGETS'], {}), '(TARGETS)\n', (28468, 28477), False, 'import torch\n'), ((28584, 28599), 'numpy.round', 'np.round', (['PROBS'], {}), '(PROBS)\n', (28592, 28599), True, 'import numpy as np\n'), ((27548, 27564), 'torch.sigmoid', 'torch.sigmoid', (['l'], {}), '(l)\n', (27561, 27564), False, 'import torch\n'), ((5051, 5077), 'torch.log', 'torch.log', (['pseudo_pred_aux'], {}), '(pseudo_pred_aux)\n', (5060, 5077), False, 'import torch\n'), ((18591, 18617), 'torch.log', 'torch.log', (['pseudo_pred_aux'], {}), '(pseudo_pred_aux)\n', (18600, 18617), False, 'import torch\n'), ((23216, 23242), 'torch.log', 'torch.log', (['pseudo_pred_aux'], {}), '(pseudo_pred_aux)\n', (23225, 23242), False, 'import torch\n'), ((23495, 23522), 'torch.log', 'torch.log', (['pseudo_pred_aux2'], {}), '(pseudo_pred_aux2)\n', (23504, 23522), False, 'import torch\n'), ((26909, 26951), 'torch.zeros', 'torch.zeros', (['(data.shape[0], args.out_dim)'], {}), '((data.shape[0], args.out_dim))\n', (26920, 26951), False, 'import torch\n'), ((27019, 27061), 'torch.zeros', 'torch.zeros', (['(data.shape[0], args.out_dim)'], {}), '((data.shape[0], args.out_dim))\n', (27030, 27061), False, 'import torch\n'), ((8987, 9009), 'torch.log', 'torch.log', (['output_conf'], {}), '(output_conf)\n', (8996, 9009), False, 'import torch\n'), ((13124, 13146), 'torch.log', 'torch.log', (['output_conf'], {}), '(output_conf)\n', (13133, 13146), False, 'import torch\n'), ((13459, 13482), 'torch.log', 'torch.log', (['output_conf2'], {}), '(output_conf2)\n', (13468, 13482), False, 'import torch\n'), ((18288, 18310), 'torch.log', 'torch.log', (['output_conf'], {}), '(output_conf)\n', (18297, 18310), False, 'import torch\n')] |
import numpy as np
import argparse
import matplotlib.pyplot as plt
import cv2
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Flatten
from tensorflow.keras.layers import Conv2D
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.layers import MaxPooling2D
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
# command line argument
ap = argparse.ArgumentParser()
ap.add_argument("--mode", help="train/display")
mode = ap.parse_args().mode
# plots accuracy and loss curves
def plot_model_history(model_history):
"""
Plot Accuracy and Loss curves given the model_history
"""
fig, axs = plt.subplots(1, 2, figsize=(15, 5))
# summarize history for accuracy
axs[0].plot(range(1, len(model_history.history['accuracy'])+1),
model_history.history['accuracy'])
axs[0].plot(range(1, len(model_history.history['val_accuracy'])+1),
model_history.history['val_accuracy'])
axs[0].set_title('Model Accuracy')
axs[0].set_ylabel('Accuracy')
axs[0].set_xlabel('Epoch')
axs[0].set_xticks(np.arange(1, len(model_history.history['accuracy'])+1),
len(model_history.history['accuracy'])/10)
axs[0].legend(['train', 'val'], loc='best')
# summarize history for loss
axs[1].plot(range(1, len(model_history.history['loss'])+1),
model_history.history['loss'])
axs[1].plot(range(1, len(model_history.history['val_loss'])+1),
model_history.history['val_loss'])
axs[1].set_title('Model Loss')
axs[1].set_ylabel('Loss')
axs[1].set_xlabel('Epoch')
axs[1].set_xticks(np.arange(
1, len(model_history.history['loss'])+1), len(model_history.history['loss'])/10)
axs[1].legend(['train', 'val'], loc='best')
fig.savefig('plot.png')
plt.show()
# Create the model
model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
activation='relu', input_shape=(48, 48, 1)))
model.add(Conv2D(64, kernel_size=(3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Conv2D(128, kernel_size=(3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(128, kernel_size=(3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(1024, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(7, activation='softmax'))
print("Start Loading....")
model.load_weights('model.h5')
# prevents openCL usage and unnecessary logging messages
cv2.ocl.setUseOpenCL(False)
# dictionary which assigns each label an emotion (alphabetical order)
emotion_dict = {0: "Angry", 1: "Disgusted", 2: "Fearful",
3: "Happy", 4: "Neutral", 5: "Sad", 6: "Surprised"}
# start the webcam feed
print("Start capturing images")
cap = cv2.VideoCapture(0)
while True:
# Find haar cascade to draw bounding box around face
ret, frame = cap.read()
if not ret:
break
facecasc = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = facecasc.detectMultiScale(
gray, scaleFactor=1.3, minNeighbors=5)
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y-50), (x+w, y+h+10), (255, 0, 0), 2)
roi_gray = gray[y:y + h, x:x + w]
cropped_img = np.expand_dims(np.expand_dims(
cv2.resize(roi_gray, (48, 48)), -1), 0)
prediction = model.predict(cropped_img)
maxindex = int(np.argmax(prediction))
maxindex = 6
cv2.putText(frame, "SLEEP", (x+20, y-60),
cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 3, cv2.LINE_AA)
cv2.imshow('Video', cv2.resize(
frame, (1600, 960), interpolation=cv2.INTER_CUBIC))
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
| [
"cv2.rectangle",
"tensorflow.keras.layers.Dense",
"cv2.destroyAllWindows",
"cv2.CascadeClassifier",
"cv2.ocl.setUseOpenCL",
"tensorflow.keras.layers.Conv2D",
"argparse.ArgumentParser",
"cv2.waitKey",
"tensorflow.keras.models.Sequential",
"tensorflow.keras.layers.Dropout",
"numpy.argmax",
"cv2.... | [((471, 496), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (494, 496), False, 'import argparse\n'), ((1952, 1964), 'tensorflow.keras.models.Sequential', 'Sequential', ([], {}), '()\n', (1962, 1964), False, 'from tensorflow.keras.models import Sequential\n'), ((2678, 2705), 'cv2.ocl.setUseOpenCL', 'cv2.ocl.setUseOpenCL', (['(False)'], {}), '(False)\n', (2698, 2705), False, 'import cv2\n'), ((2966, 2985), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(0)'], {}), '(0)\n', (2982, 2985), False, 'import cv2\n'), ((3988, 4011), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (4009, 4011), False, 'import cv2\n'), ((737, 772), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(2)'], {'figsize': '(15, 5)'}), '(1, 2, figsize=(15, 5))\n', (749, 772), True, 'import matplotlib.pyplot as plt\n'), ((1912, 1922), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1920, 1922), True, 'import matplotlib.pyplot as plt\n'), ((1976, 2050), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(32)'], {'kernel_size': '(3, 3)', 'activation': '"""relu"""', 'input_shape': '(48, 48, 1)'}), "(32, kernel_size=(3, 3), activation='relu', input_shape=(48, 48, 1))\n", (1982, 2050), False, 'from tensorflow.keras.layers import Conv2D\n'), ((2079, 2128), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(64)'], {'kernel_size': '(3, 3)', 'activation': '"""relu"""'}), "(64, kernel_size=(3, 3), activation='relu')\n", (2085, 2128), False, 'from tensorflow.keras.layers import Conv2D\n'), ((2140, 2170), 'tensorflow.keras.layers.MaxPooling2D', 'MaxPooling2D', ([], {'pool_size': '(2, 2)'}), '(pool_size=(2, 2))\n', (2152, 2170), False, 'from tensorflow.keras.layers import MaxPooling2D\n'), ((2182, 2195), 'tensorflow.keras.layers.Dropout', 'Dropout', (['(0.25)'], {}), '(0.25)\n', (2189, 2195), False, 'from tensorflow.keras.layers import Dense, Dropout, Flatten\n'), ((2208, 2258), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(128)'], {'kernel_size': '(3, 3)', 'activation': '"""relu"""'}), "(128, kernel_size=(3, 3), activation='relu')\n", (2214, 2258), False, 'from tensorflow.keras.layers import Conv2D\n'), ((2270, 2300), 'tensorflow.keras.layers.MaxPooling2D', 'MaxPooling2D', ([], {'pool_size': '(2, 2)'}), '(pool_size=(2, 2))\n', (2282, 2300), False, 'from tensorflow.keras.layers import MaxPooling2D\n'), ((2312, 2362), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(128)'], {'kernel_size': '(3, 3)', 'activation': '"""relu"""'}), "(128, kernel_size=(3, 3), activation='relu')\n", (2318, 2362), False, 'from tensorflow.keras.layers import Conv2D\n'), ((2374, 2404), 'tensorflow.keras.layers.MaxPooling2D', 'MaxPooling2D', ([], {'pool_size': '(2, 2)'}), '(pool_size=(2, 2))\n', (2386, 2404), False, 'from tensorflow.keras.layers import MaxPooling2D\n'), ((2416, 2429), 'tensorflow.keras.layers.Dropout', 'Dropout', (['(0.25)'], {}), '(0.25)\n', (2423, 2429), False, 'from tensorflow.keras.layers import Dense, Dropout, Flatten\n'), ((2442, 2451), 'tensorflow.keras.layers.Flatten', 'Flatten', ([], {}), '()\n', (2449, 2451), False, 'from tensorflow.keras.layers import Dense, Dropout, Flatten\n'), ((2463, 2493), 'tensorflow.keras.layers.Dense', 'Dense', (['(1024)'], {'activation': '"""relu"""'}), "(1024, activation='relu')\n", (2468, 2493), False, 'from tensorflow.keras.layers import Dense, Dropout, Flatten\n'), ((2505, 2517), 'tensorflow.keras.layers.Dropout', 'Dropout', (['(0.5)'], {}), '(0.5)\n', (2512, 2517), False, 'from tensorflow.keras.layers import Dense, Dropout, Flatten\n'), ((2529, 2559), 'tensorflow.keras.layers.Dense', 'Dense', (['(7)'], {'activation': '"""softmax"""'}), "(7, activation='softmax')\n", (2534, 2559), False, 'from tensorflow.keras.layers import Dense, Dropout, Flatten\n'), ((3128, 3188), 'cv2.CascadeClassifier', 'cv2.CascadeClassifier', (['"""haarcascade_frontalface_default.xml"""'], {}), "('haarcascade_frontalface_default.xml')\n", (3149, 3188), False, 'import cv2\n'), ((3200, 3239), 'cv2.cvtColor', 'cv2.cvtColor', (['frame', 'cv2.COLOR_BGR2GRAY'], {}), '(frame, cv2.COLOR_BGR2GRAY)\n', (3212, 3239), False, 'import cv2\n'), ((3366, 3436), 'cv2.rectangle', 'cv2.rectangle', (['frame', '(x, y - 50)', '(x + w, y + h + 10)', '(255, 0, 0)', '(2)'], {}), '(frame, (x, y - 50), (x + w, y + h + 10), (255, 0, 0), 2)\n', (3379, 3436), False, 'import cv2\n'), ((3700, 3807), 'cv2.putText', 'cv2.putText', (['frame', '"""SLEEP"""', '(x + 20, y - 60)', 'cv2.FONT_HERSHEY_SIMPLEX', '(1)', '(255, 0, 0)', '(3)', 'cv2.LINE_AA'], {}), "(frame, 'SLEEP', (x + 20, y - 60), cv2.FONT_HERSHEY_SIMPLEX, 1,\n (255, 0, 0), 3, cv2.LINE_AA)\n", (3711, 3807), False, 'import cv2\n'), ((3845, 3906), 'cv2.resize', 'cv2.resize', (['frame', '(1600, 960)'], {'interpolation': 'cv2.INTER_CUBIC'}), '(frame, (1600, 960), interpolation=cv2.INTER_CUBIC)\n', (3855, 3906), False, 'import cv2\n'), ((3648, 3669), 'numpy.argmax', 'np.argmax', (['prediction'], {}), '(prediction)\n', (3657, 3669), True, 'import numpy as np\n'), ((3924, 3938), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (3935, 3938), False, 'import cv2\n'), ((3536, 3566), 'cv2.resize', 'cv2.resize', (['roi_gray', '(48, 48)'], {}), '(roi_gray, (48, 48))\n', (3546, 3566), False, 'import cv2\n')] |
import sys
import numpy as np
import os
from data_management import load_videos,load_optical_flow_dataset
import config
# import tensorflow as tf
# tf.config.experimental_run_functions_eagerly(True)
from models import ROI_C3D_AE_no_pool,Fusion_C3D_no_pool
from trainer.fusionroigan import Params,Fusion_ROI_3DCAE_GAN3D
from trainer.util import create_diff_mask
import argparse
#Select data_type
parser = argparse.ArgumentParser(description='Fusion and Region based adversarial model training')
parser.add_argument('--epochstrained', default='0',
help='Epoch number of the saved model')
parser.add_argument('--lambda_T', default='0.1',
help='MSE loss hyperparameter for thermal frames')
parser.add_argument('--lambda_F', default='0.1',
help='MSE loss hyperparameter for flow frames')
args = parser.parse_args()
dset = config.track_root_folder
d_type='ROI_Fusion'
#parameters
epochs=300
epochs_trained=int(args.epochstrained)
LOAD_DATA_SHAPE=config.LOAD_DATA_SHAPE
width, height = LOAD_DATA_SHAPE[0],LOAD_DATA_SHAPE[1]
thermal_channels=1
flow_channels=3
win_length=config.WIN_LENGTH
regularizer_list = ['BN']
break_win=config.SPLIT_GAP
stride=config.STRIDE
lambdas=[float(args.lambda_T),float(args.lambda_F)]
#aggreagte all parameters in Params class
param=Params(width=width, height=height,win_length=win_length,thermal_channels=thermal_channels,flow_channels=flow_channels,dset=dset,d_type=d_type,regularizer_list=regularizer_list,break_win=break_win)
param.thermal_lambda=lambdas[0]
param.flow_lambda=lambdas[1]
#-----------------
#Load train data
#-----------------
#load thermal frames
ADL_videos=load_videos(dset='Thermal_track',vid_class='ADL',input_type='ROI_FRAME')
#load flow frames
load_optical_flow_dataset(vid_class='ADL',videos=ADL_videos)
#load Gan trainer
GAN3D=Fusion_ROI_3DCAE_GAN3D(train_par=param,stride=stride)
print("\nCreating Windowed ROI Frame data\n")
ADL_ROI_frame_windows=GAN3D.create_windowed_data(ADL_videos,stride=1,data_key='ROI_FRAME')
print("\nCreating Windowed Flow data\n")
ADL_flow_windows=GAN3D.create_windowed_data(ADL_videos,stride=1,data_key='FLOW')
print("\nCreating Windowed Mask data\n")
ADL_mask_windows=GAN3D.create_windowed_data(ADL_videos,stride=1,data_key='MASK')
ADL_mask_windows=ADL_mask_windows.astype('int8')
#Creating diff mask
print("\nCreating Diff Mask data\n")
ADL_diff_mask_windows=create_diff_mask(ADL_mask_windows)
ADL_flow_mask_windows=np.concatenate((ADL_diff_mask_windows,ADL_diff_mask_windows,ADL_diff_mask_windows),axis=-1)
#Aplly masking for ROI on flow windows
#Values are scaled from -1 to 1, so -1 is black
print("\nCreating Masked flow data\n")
ADL_ROI_flow_windows=(ADL_flow_mask_windows*ADL_flow_windows)+ADL_flow_mask_windows-1
#-----------------
#MODEL Initialization
#-----------------
TR, TR_name, _ = ROI_C3D_AE_no_pool(img_width=param.width, img_height=param.height, win_length=param.win_length, regularizer_list=param.regularizer_list,channels=param.thermal_channels,d_type='thermal')
FR, FR_name, _ = ROI_C3D_AE_no_pool(img_width=param.width, img_height=param.height, win_length=param.win_length-1, regularizer_list=param.regularizer_list,channels=param.flow_channels,d_type='flow')
D, D_name, _ = Fusion_C3D_no_pool(img_width=param.width, img_height=param.height, win_length=param.win_length, regularizer_list=param.regularizer_list,thermal_channels=param.thermal_channels,flow_channels=param.flow_channels)
param.TR_name=TR_name
param.FR_name=FR_name
param.D_name=D_name
D_path = param.get_D_path(epochs_trained)
TR_path = param.get_TR_path(epochs_trained)
FR_path = param.get_FR_path(epochs_trained)
if os.path.isfile(TR_path) and os.path.isfile(D_path) and os.path.isfile(FR_path):
TR.load_weights(TR_path)
FR.load_weights(FR_path)
D.load_weights(D_path)
print("Model weights loaded successfully........")
else:
print("Saved model weights not found......")
epochs_trained=0
#-----------------
#model training
#-----------------
GAN3D.initialize_model(T_Reconstructor=TR, F_Reconstructor=FR, Discriminator=D)
GAN3D.train(thermal_frame=ADL_ROI_frame_windows, thermal_mask=ADL_mask_windows,flow_frame=ADL_ROI_flow_windows, flow_mask=ADL_flow_mask_windows,epochs= epochs,epochs_trained=epochs_trained, save_interval = 10)
| [
"trainer.util.create_diff_mask",
"data_management.load_optical_flow_dataset",
"argparse.ArgumentParser",
"models.ROI_C3D_AE_no_pool",
"models.Fusion_C3D_no_pool",
"trainer.fusionroigan.Fusion_ROI_3DCAE_GAN3D",
"os.path.isfile",
"data_management.load_videos",
"trainer.fusionroigan.Params",
"numpy.c... | [((406, 500), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Fusion and Region based adversarial model training"""'}), "(description=\n 'Fusion and Region based adversarial model training')\n", (429, 500), False, 'import argparse\n'), ((1319, 1531), 'trainer.fusionroigan.Params', 'Params', ([], {'width': 'width', 'height': 'height', 'win_length': 'win_length', 'thermal_channels': 'thermal_channels', 'flow_channels': 'flow_channels', 'dset': 'dset', 'd_type': 'd_type', 'regularizer_list': 'regularizer_list', 'break_win': 'break_win'}), '(width=width, height=height, win_length=win_length, thermal_channels=\n thermal_channels, flow_channels=flow_channels, dset=dset, d_type=d_type,\n regularizer_list=regularizer_list, break_win=break_win)\n', (1325, 1531), False, 'from trainer.fusionroigan import Params, Fusion_ROI_3DCAE_GAN3D\n'), ((1664, 1738), 'data_management.load_videos', 'load_videos', ([], {'dset': '"""Thermal_track"""', 'vid_class': '"""ADL"""', 'input_type': '"""ROI_FRAME"""'}), "(dset='Thermal_track', vid_class='ADL', input_type='ROI_FRAME')\n", (1675, 1738), False, 'from data_management import load_videos, load_optical_flow_dataset\n'), ((1755, 1816), 'data_management.load_optical_flow_dataset', 'load_optical_flow_dataset', ([], {'vid_class': '"""ADL"""', 'videos': 'ADL_videos'}), "(vid_class='ADL', videos=ADL_videos)\n", (1780, 1816), False, 'from data_management import load_videos, load_optical_flow_dataset\n'), ((1841, 1895), 'trainer.fusionroigan.Fusion_ROI_3DCAE_GAN3D', 'Fusion_ROI_3DCAE_GAN3D', ([], {'train_par': 'param', 'stride': 'stride'}), '(train_par=param, stride=stride)\n', (1863, 1895), False, 'from trainer.fusionroigan import Params, Fusion_ROI_3DCAE_GAN3D\n'), ((2406, 2440), 'trainer.util.create_diff_mask', 'create_diff_mask', (['ADL_mask_windows'], {}), '(ADL_mask_windows)\n', (2422, 2440), False, 'from trainer.util import create_diff_mask\n'), ((2464, 2562), 'numpy.concatenate', 'np.concatenate', (['(ADL_diff_mask_windows, ADL_diff_mask_windows, ADL_diff_mask_windows)'], {'axis': '(-1)'}), '((ADL_diff_mask_windows, ADL_diff_mask_windows,\n ADL_diff_mask_windows), axis=-1)\n', (2478, 2562), True, 'import numpy as np\n'), ((2847, 3042), 'models.ROI_C3D_AE_no_pool', 'ROI_C3D_AE_no_pool', ([], {'img_width': 'param.width', 'img_height': 'param.height', 'win_length': 'param.win_length', 'regularizer_list': 'param.regularizer_list', 'channels': 'param.thermal_channels', 'd_type': '"""thermal"""'}), "(img_width=param.width, img_height=param.height,\n win_length=param.win_length, regularizer_list=param.regularizer_list,\n channels=param.thermal_channels, d_type='thermal')\n", (2865, 3042), False, 'from models import ROI_C3D_AE_no_pool, Fusion_C3D_no_pool\n'), ((3050, 3244), 'models.ROI_C3D_AE_no_pool', 'ROI_C3D_AE_no_pool', ([], {'img_width': 'param.width', 'img_height': 'param.height', 'win_length': '(param.win_length - 1)', 'regularizer_list': 'param.regularizer_list', 'channels': 'param.flow_channels', 'd_type': '"""flow"""'}), "(img_width=param.width, img_height=param.height,\n win_length=param.win_length - 1, regularizer_list=param.\n regularizer_list, channels=param.flow_channels, d_type='flow')\n", (3068, 3244), False, 'from models import ROI_C3D_AE_no_pool, Fusion_C3D_no_pool\n'), ((3247, 3467), 'models.Fusion_C3D_no_pool', 'Fusion_C3D_no_pool', ([], {'img_width': 'param.width', 'img_height': 'param.height', 'win_length': 'param.win_length', 'regularizer_list': 'param.regularizer_list', 'thermal_channels': 'param.thermal_channels', 'flow_channels': 'param.flow_channels'}), '(img_width=param.width, img_height=param.height,\n win_length=param.win_length, regularizer_list=param.regularizer_list,\n thermal_channels=param.thermal_channels, flow_channels=param.flow_channels)\n', (3265, 3467), False, 'from models import ROI_C3D_AE_no_pool, Fusion_C3D_no_pool\n'), ((3656, 3679), 'os.path.isfile', 'os.path.isfile', (['TR_path'], {}), '(TR_path)\n', (3670, 3679), False, 'import os\n'), ((3684, 3706), 'os.path.isfile', 'os.path.isfile', (['D_path'], {}), '(D_path)\n', (3698, 3706), False, 'import os\n'), ((3711, 3734), 'os.path.isfile', 'os.path.isfile', (['FR_path'], {}), '(FR_path)\n', (3725, 3734), False, 'import os\n')] |
import os
from functools import reduce
import numpy as np
import pandas as pd
from sklearn.preprocessing import minmax_scale, scale
class Data():
def __init__(self, no_hist_days, no_hist_weeks, target_label, root_dir="", begin_test_date=None, scale_data=None):
data_daily = os.path.join(root_dir, "data/slovenia_daily.csv")
data_weekly = os.path.join(root_dir, "data/slovenia_weekly.csv")
self.df_daily = pd.read_csv(data_daily)
self.df_weekly = pd.read_csv(data_weekly)
self.df_daily['date'] = pd.to_datetime(self.df_daily['date'])
self.df_weekly['date'] = pd.to_datetime(self.df_weekly['date'])
self.target_label = target_label
self.no_hist_days = no_hist_days
self.no_hist_weeks = no_hist_weeks
self.begin_test_date = begin_test_date
self.scale_data = scale_data
self.predictors_col_names = []
self.df_data_table = self._create_data_table()
def _create_base_table(self):
""" Create base table filled with daily values, target value and date"""
list_hist_vals = []
for timestamp in self.df_weekly['date']:
end_date = timestamp - pd.DateOffset(6) # 6 day (1 week) offset for week prediction
start_date = end_date - pd.DateOffset(self.no_hist_days)
mask_dates = (self.df_daily["date"] > start_date) & (self.df_daily["date"] <= end_date)
predictors = self.df_daily[mask_dates].loc[:, self.target_label].to_numpy()
list_hist_vals.append(predictors)
bool_hist_vals = [len(hist_vals) == self.no_hist_days for hist_vals in list_hist_vals]
num = len(list_hist_vals) - sum(bool_hist_vals)
# remove num instances which are not equal to self.no_hist_vals
target_df = self.df_weekly[self.target_label].loc[num:].reset_index(drop=True).to_frame("target")
date_target_df = self.df_weekly["date"].loc[num:].reset_index(drop=True).to_frame()
col_names = [f"d_{idx}" for idx in reversed(range(1, len(list_hist_vals[num])+1))]
predictors_df = pd.DataFrame(list_hist_vals[num:], columns=col_names)
self.predictors_col_names.extend(col_names)
df_base_table = pd.concat([date_target_df, target_df, predictors_df], axis=1)
return df_base_table
def _create_weekly_table(self, df_base_table):
""" Create table with weekly values"""
list_hist_vals = []
for timestamp in df_base_table['date']:
end_date = timestamp - pd.DateOffset(weeks=1) # 1 week offset for prediction
start_date = end_date - pd.DateOffset(weeks=self.no_hist_weeks)
mask_dates = (self.df_weekly["date"] > start_date) & (self.df_weekly["date"] <= end_date)
predictors = self.df_weekly[mask_dates].loc[:, self.target_label].to_numpy()
list_hist_vals.append(predictors)
bool_hist_vals = [len(hist_vals) == self.no_hist_weeks for hist_vals in list_hist_vals]
num = len(list_hist_vals) - sum(bool_hist_vals)
date_target_df = df_base_table["date"].loc[num:].reset_index(drop=True).to_frame()
col_names = [f"w_{idx}" for idx in reversed(range(1, len(list_hist_vals[num])+1))]
predictors_df = pd.DataFrame(list_hist_vals[num:], columns=col_names)
self.predictors_col_names.extend(col_names)
df_weekly_table = pd.concat([date_target_df, predictors_df], axis=1)
return df_weekly_table
def _create_other_table(self):
""" Create table with additional informations"""
df_other = self.df_weekly.copy()
df_other = df_other.drop(columns=["week", "new_cases", "new_deaths"])
df_other["date"] = df_other["date"].shift(-1) # predictions from last week
df_other = df_other[:-1]
col_names = df_other.drop(columns=["date"]).columns.to_list()
self.predictors_col_names.extend(col_names)
return df_other
def _create_data_table(self):
base_table = self._create_base_table()
weekly_table = self._create_weekly_table(base_table)
other_table = self._create_other_table()
dfs = [base_table, weekly_table, other_table]
data_table = reduce(lambda left, right: pd.merge(left, right, how="inner", on="date"), dfs)
data_table = self._scale_data_table(data_table)
return data_table
def _scale_data_table(self, data_table):
if self.scale_data == "scale":
data_table[self.predictors_col_names] = scale(data_table[self.predictors_col_names])
elif self.scale_data == "minmax":
data_table[self.predictors_col_names] = minmax_scale(data_table[self.predictors_col_names])
return data_table
def get_data(self, save=False):
if save:
self.df_data_table.to_csv("data/data_table.csv", index=False)
def convert_to_numpy(df):
X = df.reindex(columns = self.predictors_col_names).to_numpy()
y = df.loc[:, "target"].to_numpy()
y = np.expand_dims(y, axis = 1)
return X, y
df_train = self.df_data_table[self.df_data_table["date"] < self.begin_test_date]
df_test = self.df_data_table[self.df_data_table["date"] >= self.begin_test_date]
X_train, y_train = convert_to_numpy(df_train)
X_test, y_test = convert_to_numpy(df_test)
return X_train, y_train, X_test, y_test
if __name__ == "__main__":
from skmultiflow.data import DataStream, RegressionGenerator
target_label = "new_cases"
no_hist_days = 0
no_hist_weeks = 2
begin_test_date = "2021-11-06"
scale_data = None
data = Data(
no_hist_days=no_hist_days,
no_hist_weeks=no_hist_weeks,
target_label=target_label,
begin_test_date=begin_test_date,
scale_data=scale_data
)
X_train, y_train, X_test_t, y_test_t = data.get_data()
stream = DataStream(X_test_t, y_test_t)
| [
"pandas.read_csv",
"pandas.merge",
"os.path.join",
"sklearn.preprocessing.scale",
"skmultiflow.data.DataStream",
"pandas.DateOffset",
"sklearn.preprocessing.minmax_scale",
"numpy.expand_dims",
"pandas.DataFrame",
"pandas.concat",
"pandas.to_datetime"
] | [((5912, 5942), 'skmultiflow.data.DataStream', 'DataStream', (['X_test_t', 'y_test_t'], {}), '(X_test_t, y_test_t)\n', (5922, 5942), False, 'from skmultiflow.data import DataStream, RegressionGenerator\n'), ((289, 338), 'os.path.join', 'os.path.join', (['root_dir', '"""data/slovenia_daily.csv"""'], {}), "(root_dir, 'data/slovenia_daily.csv')\n", (301, 338), False, 'import os\n'), ((361, 411), 'os.path.join', 'os.path.join', (['root_dir', '"""data/slovenia_weekly.csv"""'], {}), "(root_dir, 'data/slovenia_weekly.csv')\n", (373, 411), False, 'import os\n'), ((436, 459), 'pandas.read_csv', 'pd.read_csv', (['data_daily'], {}), '(data_daily)\n', (447, 459), True, 'import pandas as pd\n'), ((485, 509), 'pandas.read_csv', 'pd.read_csv', (['data_weekly'], {}), '(data_weekly)\n', (496, 509), True, 'import pandas as pd\n'), ((543, 580), 'pandas.to_datetime', 'pd.to_datetime', (["self.df_daily['date']"], {}), "(self.df_daily['date'])\n", (557, 580), True, 'import pandas as pd\n'), ((614, 652), 'pandas.to_datetime', 'pd.to_datetime', (["self.df_weekly['date']"], {}), "(self.df_weekly['date'])\n", (628, 652), True, 'import pandas as pd\n'), ((2090, 2143), 'pandas.DataFrame', 'pd.DataFrame', (['list_hist_vals[num:]'], {'columns': 'col_names'}), '(list_hist_vals[num:], columns=col_names)\n', (2102, 2143), True, 'import pandas as pd\n'), ((2221, 2282), 'pandas.concat', 'pd.concat', (['[date_target_df, target_df, predictors_df]'], {'axis': '(1)'}), '([date_target_df, target_df, predictors_df], axis=1)\n', (2230, 2282), True, 'import pandas as pd\n'), ((3250, 3303), 'pandas.DataFrame', 'pd.DataFrame', (['list_hist_vals[num:]'], {'columns': 'col_names'}), '(list_hist_vals[num:], columns=col_names)\n', (3262, 3303), True, 'import pandas as pd\n'), ((3383, 3433), 'pandas.concat', 'pd.concat', (['[date_target_df, predictors_df]'], {'axis': '(1)'}), '([date_target_df, predictors_df], axis=1)\n', (3392, 3433), True, 'import pandas as pd\n'), ((4506, 4550), 'sklearn.preprocessing.scale', 'scale', (['data_table[self.predictors_col_names]'], {}), '(data_table[self.predictors_col_names])\n', (4511, 4550), False, 'from sklearn.preprocessing import minmax_scale, scale\n'), ((5025, 5050), 'numpy.expand_dims', 'np.expand_dims', (['y'], {'axis': '(1)'}), '(y, axis=1)\n', (5039, 5050), True, 'import numpy as np\n'), ((1187, 1203), 'pandas.DateOffset', 'pd.DateOffset', (['(6)'], {}), '(6)\n', (1200, 1203), True, 'import pandas as pd\n'), ((1284, 1316), 'pandas.DateOffset', 'pd.DateOffset', (['self.no_hist_days'], {}), '(self.no_hist_days)\n', (1297, 1316), True, 'import pandas as pd\n'), ((2523, 2545), 'pandas.DateOffset', 'pd.DateOffset', ([], {'weeks': '(1)'}), '(weeks=1)\n', (2536, 2545), True, 'import pandas as pd\n'), ((2613, 2652), 'pandas.DateOffset', 'pd.DateOffset', ([], {'weeks': 'self.no_hist_weeks'}), '(weeks=self.no_hist_weeks)\n', (2626, 2652), True, 'import pandas as pd\n'), ((4234, 4279), 'pandas.merge', 'pd.merge', (['left', 'right'], {'how': '"""inner"""', 'on': '"""date"""'}), "(left, right, how='inner', on='date')\n", (4242, 4279), True, 'import pandas as pd\n'), ((4645, 4696), 'sklearn.preprocessing.minmax_scale', 'minmax_scale', (['data_table[self.predictors_col_names]'], {}), '(data_table[self.predictors_col_names])\n', (4657, 4696), False, 'from sklearn.preprocessing import minmax_scale, scale\n')] |
import os
import numpy as np
def preprocess_item(filename, folder):
return np.genfromtxt(
f"{folder}/{filename}", delimiter=",")
def load_folder_data(folder):
data = []
labels = []
for _, _, files in os.walk(folder):
raw_data = [preprocess_item(filename, folder) for filename in files]
labels = [int(filename.split("_")[0]) for filename in files]
data = np.stack(raw_data)
return data, np.array(labels)
def load_dataset(dataset_path, positive=True, negative=True):
print('START: loading data')
data, labels = load_folder_data(dataset_path)
numClasses = np.max(labels) + 1
idx = [np.where(labels == i)[0] for i in range(0, numClasses)]
pairImages = []
pairLabels = []
for idxA, _ in enumerate(data):
# grab the current image and label belonging to the current
# iteration
currentImage = data[idxA]
label = labels[idxA]
# randomly pick an image that belongs to the *same* class
# label
if positive:
idxB = np.random.choice(idx[label])
posData = data[idxB]
# prepare a positive pair and update the images and labels
# lists, respectively
np.random.shuffle(currentImage)
pairImages.append([currentImage, posData])
pairLabels.append([1])
# grab the indices for each of the class labels *not* equal to
# the current label and randomly pick an image corresponding
# to a label *not* equal to the current label
# print(labels)
if negative:
negIdx = np.where(labels != label)[0]
negData = data[np.random.choice(negIdx)]
# prepare a negative pair of images and update our lists
np.random.shuffle(currentImage)
pairImages.append([currentImage, negData])
pairLabels.append([0])
# return a 2-tuple of our image pairs and labels
print('FINISH: loading data')
return (np.array(pairImages), np.array(pairLabels).astype('float32'))
| [
"numpy.where",
"numpy.random.choice",
"numpy.max",
"numpy.stack",
"numpy.array",
"numpy.genfromtxt",
"os.walk",
"numpy.random.shuffle"
] | [((81, 133), 'numpy.genfromtxt', 'np.genfromtxt', (['f"""{folder}/{filename}"""'], {'delimiter': '""","""'}), "(f'{folder}/{filename}', delimiter=',')\n", (94, 133), True, 'import numpy as np\n'), ((229, 244), 'os.walk', 'os.walk', (['folder'], {}), '(folder)\n', (236, 244), False, 'import os\n'), ((409, 427), 'numpy.stack', 'np.stack', (['raw_data'], {}), '(raw_data)\n', (417, 427), True, 'import numpy as np\n'), ((446, 462), 'numpy.array', 'np.array', (['labels'], {}), '(labels)\n', (454, 462), True, 'import numpy as np\n'), ((628, 642), 'numpy.max', 'np.max', (['labels'], {}), '(labels)\n', (634, 642), True, 'import numpy as np\n'), ((2021, 2041), 'numpy.array', 'np.array', (['pairImages'], {}), '(pairImages)\n', (2029, 2041), True, 'import numpy as np\n'), ((658, 679), 'numpy.where', 'np.where', (['(labels == i)'], {}), '(labels == i)\n', (666, 679), True, 'import numpy as np\n'), ((1066, 1094), 'numpy.random.choice', 'np.random.choice', (['idx[label]'], {}), '(idx[label])\n', (1082, 1094), True, 'import numpy as np\n'), ((1246, 1277), 'numpy.random.shuffle', 'np.random.shuffle', (['currentImage'], {}), '(currentImage)\n', (1263, 1277), True, 'import numpy as np\n'), ((1794, 1825), 'numpy.random.shuffle', 'np.random.shuffle', (['currentImage'], {}), '(currentImage)\n', (1811, 1825), True, 'import numpy as np\n'), ((1630, 1655), 'numpy.where', 'np.where', (['(labels != label)'], {}), '(labels != label)\n', (1638, 1655), True, 'import numpy as np\n'), ((1687, 1711), 'numpy.random.choice', 'np.random.choice', (['negIdx'], {}), '(negIdx)\n', (1703, 1711), True, 'import numpy as np\n'), ((2043, 2063), 'numpy.array', 'np.array', (['pairLabels'], {}), '(pairLabels)\n', (2051, 2063), True, 'import numpy as np\n')] |
"""
Created on Sat May 23 18:17:31 2020
celebx = 'CC1=CC=C(C=C1)C2=CC(=NN2C3=CC=C(C=C3)S(=O)(=O)N)C(F)(F)F'
tiotixene = 'CN1CCN(CC1)CCC=C2C3=CC=CC=C3SC4=C2C=C(C=C4)S(=O)(=O)N(C)C'
Troglitazone = 'CC1=C(C2=C(CCC(O2)(C)COC3=CC=C(C=C3)CC4C(=O)NC(=O)S4)C(=C1O)C)C'
@author: akshat
"""
import selfies
import numpy as np
import random
from rdkit.Chem import MolFromSmiles as smi2mol
from rdkit.Chem import MolToSmiles as mol2smi
from rdkit import Chem
from rdkit.Chem import AllChem
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from selfies import encoder, decoder
from rdkit import RDLogger
RDLogger.DisableLog('rdApp.*')
def get_ECFP4(mol):
''' Return rdkit ECFP4 fingerprint object for mol
Parameters:
mol (rdkit.Chem.rdchem.Mol) : RdKit mol object
Returns:
rdkit ECFP4 fingerprint object for mol
'''
return AllChem.GetMorganFingerprint(mol, 2)
def sanitize_smiles(smi):
'''Return a canonical smile representation of smi
Parameters:
smi (string) : smile string to be canonicalized
Returns:
mol (rdkit.Chem.rdchem.Mol) : RdKit mol object (None if invalid smile string smi)
smi_canon (string) : Canonicalized smile representation of smi (None if invalid smile string smi)
conversion_successful (bool): True/False to indicate if conversion was successful
'''
try:
mol = smi2mol(smi, sanitize=True)
smi_canon = mol2smi(mol, isomericSmiles=False, canonical=True)
return (mol, smi_canon, True)
except:
return (None, None, False)
def mutate_selfie(selfie, max_molecules_len, write_fail_cases=False):
'''Return a mutated selfie string (only one mutation on slefie is performed)
Mutations are done until a valid molecule is obtained
Rules of mutation: With a 50% propbabily, either:
1. Add a random SELFIE character in the string
2. Replace a random SELFIE character with another
Parameters:
selfie (string) : SELFIE string to be mutated
max_molecules_len (int) : Mutations of SELFIE string are allowed up to this length
write_fail_cases (bool) : If true, failed mutations are recorded in "selfie_failure_cases.txt"
Returns:
selfie_mutated (string) : Mutated SELFIE string
smiles_canon (string) : canonical smile of mutated SELFIE string
'''
valid=False
fail_counter = 0
chars_selfie = get_selfie_chars(selfie)
while not valid:
fail_counter += 1
alphabet = list(selfies.get_semantic_robust_alphabet()) # 34 SELFIE characters
choice_ls = [1, 2] # 1=Insert; 2=Replace; 3=Delete
random_choice = np.random.choice(choice_ls, 1)[0]
# Insert a character in a Random Location
if random_choice == 1:
random_index = np.random.randint(len(chars_selfie)+1)
random_character = np.random.choice(alphabet, size=1)[0]
selfie_mutated_chars = chars_selfie[:random_index] + [random_character] + chars_selfie[random_index:]
# Replace a random character
elif random_choice == 2:
random_index = np.random.randint(len(chars_selfie))
random_character = np.random.choice(alphabet, size=1)[0]
if random_index == 0:
selfie_mutated_chars = [random_character] + chars_selfie[random_index+1:]
else:
selfie_mutated_chars = chars_selfie[:random_index] + [random_character] + chars_selfie[random_index+1:]
# Delete a random character
elif random_choice == 3:
random_index = np.random.randint(len(chars_selfie))
if random_index == 0:
selfie_mutated_chars = chars_selfie[random_index+1:]
else:
selfie_mutated_chars = chars_selfie[:random_index] + chars_selfie[random_index+1:]
else:
raise Exception('Invalid Operation trying to be performed')
selfie_mutated = "".join(x for x in selfie_mutated_chars)
sf = "".join(x for x in chars_selfie)
try:
smiles = decoder(selfie_mutated)
mol, smiles_canon, done = sanitize_smiles(smiles)
if len(selfie_mutated_chars) > max_molecules_len or smiles_canon=="":
done = False
if done:
valid = True
else:
valid = False
except:
valid=False
if fail_counter > 1 and write_fail_cases == True:
f = open("selfie_failure_cases.txt", "a+")
f.write('Tried to mutate SELFIE: '+str(sf)+' To Obtain: '+str(selfie_mutated) + '\n')
f.close()
return (selfie_mutated, smiles_canon)
def get_selfie_chars(selfie):
'''Obtain a list of all selfie characters in string selfie
Parameters:
selfie (string) : A selfie string - representing a molecule
Example:
>>> get_selfie_chars('[C][=C][C][=C][C][=C][Ring1][Branch1_1]')
['[C]', '[=C]', '[C]', '[=C]', '[C]', '[=C]', '[Ring1]', '[Branch1_1]']
Returns:
chars_selfie: list of selfie characters present in molecule selfie
'''
chars_selfie = [] # A list of all SELFIE sybols from string selfie
while selfie != '':
chars_selfie.append(selfie[selfie.find('['): selfie.find(']')+1])
selfie = selfie[selfie.find(']')+1:]
return chars_selfie
def get_reward(selfie_A_chars, selfie_B_chars):
'''Return the levenshtein similarity between the selfies characters in 'selfie_A_chars' & 'selfie_B_chars'
Parameters:
selfie_A_chars (list) : list of characters of a single SELFIES
selfie_B_chars (list) : list of characters of a single SELFIES
Returns:
reward (int): Levenshtein similarity between the two SELFIES
'''
reward = 0
iter_num = max(len(selfie_A_chars), len(selfie_B_chars)) # Larger of the selfie chars to iterate over
for i in range(iter_num):
if i+1 > len(selfie_A_chars) or i+1 > len(selfie_B_chars):
return reward
if selfie_A_chars[i] == selfie_B_chars[i]:
reward += 1
return reward
# Executable code for EXPERIMENT C (Three different choices):
# TIOTOXENE RUN
# N = 20 # Number of runs
# simlr_path_collect = []
# svg_file_name = 'Tiotixene_run.svg'
# starting_mol_name = 'Tiotixene'
# data_file_name = '20_runs_data_Tiotixene.txt'
# starting_smile = 'CN1CCN(CC1)CCC=C2C3=CC=CC=C3SC4=C2C=C(C=C4)S(=O)(=O)N(C)C'
# show_gen_out = False
# len_random_struct = len(get_selfie_chars(encoder(starting_smile))) # Length of the starting SELFIE structure
# CELECOXIB RUN
# N = 20 # Number of runs
# simlr_path_collect = []
# svg_file_name = 'Celecoxib_run.svg'
# starting_mol_name = 'Celecoxib'
# data_file_name = '20_runs_data_Celecoxib.txt'
# starting_smile = 'CC1=CC=C(C=C1)C2=CC(=NN2C3=CC=C(C=C3)S(=O)(=O)N)C(F)(F)F'
# show_gen_out = False
# len_random_struct = len(get_selfie_chars(encoder(starting_smile))) # Length of the starting SELFIE structure
# Troglitazone RUN
N = 20 # Number of runs
simlr_path_collect = []
svg_file_name = 'Troglitazone_run.svg'
starting_mol_name = 'Troglitazone'
data_file_name = '20_runs_data_Troglitazone.txt'
starting_smile = 'CC1=C(C2=C(CCC(O2)(C)COC3=CC=C(C=C3)CC4C(=O)NC(=O)S4)C(=C1O)C)C'
show_gen_out = False
len_random_struct = len(get_selfie_chars(encoder(starting_smile))) # Length of the starting SELFIE structure
for i in range(N):
print('Run number: ', i)
with open(data_file_name, 'a') as myfile:
myfile.write('RUN {} \n'.format(i))
# celebx = 'CC1=CC=C(C=C1)C2=CC(=NN2C3=CC=C(C=C3)S(=O)(=O)N)C(F)(F)F'
starting_selfie = encoder(starting_smile)
starting_selfie_chars = get_selfie_chars(starting_selfie)
max_molecules_len = len(starting_selfie_chars)
# Random selfie initiation:
alphabet = list(selfies.get_semantic_robust_alphabet()) # 34 SELFIE characters
selfie = ''
for i in range(random.randint(1, len_random_struct)): # max_molecules_len = max random selfie string length
selfie = selfie + np.random.choice(alphabet, size=1)[0]
starting_selfie = [selfie]
print('Starting SELFIE: ', starting_selfie)
generation_size = 500
num_generations = 10000
save_best = []
simlr_path = []
reward_path = []
# Initial set of molecules
population = np.random.choice(starting_selfie, size=500).tolist() # All molecules are in SELFIES representation
for gen_ in range(num_generations):
# Calculate fitness for all of them
fitness = [get_reward(starting_selfie_chars, get_selfie_chars(x)) for x in population]
fitness = [float(x)/float(max_molecules_len) for x in fitness] # Between 0 and 1
# Keep the best member & mutate the rest
# Step 1: Keep the best molecule
best_idx = np.argmax(fitness)
best_selfie = population[best_idx]
# Diplay some Outputs:
if show_gen_out:
print('Generation: {}/{}'.format(gen_, num_generations))
print(' Top fitness: ', fitness[best_idx])
print(' Top SELFIE: ', best_selfie)
with open(data_file_name, 'a') as myfile:
myfile.write(' SELFIE: {} FITNESS: {} \n'.format(best_selfie, fitness[best_idx]))
# Maybe also print the tanimoto score:
mol = Chem.MolFromSmiles(decoder(best_selfie))
target = Chem.MolFromSmiles(starting_smile)
fp_mol = get_ECFP4(mol)
fp_target = get_ECFP4(target)
score = TanimotoSimilarity(fp_mol, fp_target)
simlr_path.append(score)
reward_path.append(fitness[best_idx])
save_best.append(best_selfie)
# Step 2: Get mutated selfies
new_population = []
for i in range(generation_size-1):
# selfie_mutated, _ = mutate_selfie(best_selfie, max_molecules_len, write_fail_cases=True)
selfie_mutated, _ = mutate_selfie(best_selfie, len_random_struct, write_fail_cases=True) # 100 == max_mol_len allowen in mutation
new_population.append(selfie_mutated)
new_population.append(best_selfie)
# Define new population for the next generation
population = new_population[:]
if score >= 1:
print('Limit reached')
simlr_path_collect.append(simlr_path)
break
import matplotlib.pyplot as plt
x = [i+1 for i in range(max([len(x) for x in simlr_path_collect]))]
plt.style.use(u'classic')
plt.plot(x, [1.2 for _ in range(len(x))], marker='', color='white', linewidth=4) # axis line
plt.plot(x, [1 for _ in range(len(x))], '--', color='orange', linewidth=2.5, label='Rediscovery') # Highlight line
colors = plt.cm.Blues
profiles = 20
color_shift = 0.4
color_values = [ni/profiles + color_shift for ni in range(profiles)]
for ni in range(len(color_values)):
if color_values[ni] < 0.2:
color_values[ni] -= 1
cm = [colors(x) for x in color_values]
for i,simlr_path in enumerate(simlr_path_collect):
plt.plot([i+1 for i in range(len(simlr_path))], simlr_path, marker='', color=cm[i], linewidth=2.5, alpha=0.5)
plt.title('Rediscovering '+starting_mol_name, fontsize=20, fontweight=0, color='black', loc='left')
plt.xlabel('Generation')
plt.ylabel('ECPF4 Similarity')
plt.savefig('Celecoxib_run.png', dpi=196, bbox_inches='tight')
plt.show()
| [
"matplotlib.pyplot.title",
"matplotlib.pyplot.savefig",
"selfies.get_semantic_robust_alphabet",
"matplotlib.pyplot.ylabel",
"numpy.random.choice",
"matplotlib.pyplot.xlabel",
"rdkit.DataStructs.cDataStructs.TanimotoSimilarity",
"rdkit.Chem.MolFromSmiles",
"matplotlib.pyplot.style.use",
"rdkit.Chem... | [((629, 659), 'rdkit.RDLogger.DisableLog', 'RDLogger.DisableLog', (['"""rdApp.*"""'], {}), "('rdApp.*')\n", (648, 659), False, 'from rdkit import RDLogger\n'), ((10876, 10901), 'matplotlib.pyplot.style.use', 'plt.style.use', (['u"""classic"""'], {}), "(u'classic')\n", (10889, 10901), True, 'import matplotlib.pyplot as plt\n'), ((11538, 11643), 'matplotlib.pyplot.title', 'plt.title', (["('Rediscovering ' + starting_mol_name)"], {'fontsize': '(20)', 'fontweight': '(0)', 'color': '"""black"""', 'loc': '"""left"""'}), "('Rediscovering ' + starting_mol_name, fontsize=20, fontweight=0,\n color='black', loc='left')\n", (11547, 11643), True, 'import matplotlib.pyplot as plt\n'), ((11640, 11664), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Generation"""'], {}), "('Generation')\n", (11650, 11664), True, 'import matplotlib.pyplot as plt\n'), ((11665, 11695), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""ECPF4 Similarity"""'], {}), "('ECPF4 Similarity')\n", (11675, 11695), True, 'import matplotlib.pyplot as plt\n'), ((11696, 11758), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""Celecoxib_run.png"""'], {'dpi': '(196)', 'bbox_inches': '"""tight"""'}), "('Celecoxib_run.png', dpi=196, bbox_inches='tight')\n", (11707, 11758), True, 'import matplotlib.pyplot as plt\n'), ((11760, 11770), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (11768, 11770), True, 'import matplotlib.pyplot as plt\n'), ((883, 919), 'rdkit.Chem.AllChem.GetMorganFingerprint', 'AllChem.GetMorganFingerprint', (['mol', '(2)'], {}), '(mol, 2)\n', (911, 919), False, 'from rdkit.Chem import AllChem\n'), ((8005, 8028), 'selfies.encoder', 'encoder', (['starting_smile'], {}), '(starting_smile)\n', (8012, 8028), False, 'from selfies import encoder, decoder\n'), ((1436, 1463), 'rdkit.Chem.MolFromSmiles', 'smi2mol', (['smi'], {'sanitize': '(True)'}), '(smi, sanitize=True)\n', (1443, 1463), True, 'from rdkit.Chem import MolFromSmiles as smi2mol\n'), ((1484, 1534), 'rdkit.Chem.MolToSmiles', 'mol2smi', (['mol'], {'isomericSmiles': '(False)', 'canonical': '(True)'}), '(mol, isomericSmiles=False, canonical=True)\n', (1491, 1534), True, 'from rdkit.Chem import MolToSmiles as mol2smi\n'), ((7691, 7714), 'selfies.encoder', 'encoder', (['starting_smile'], {}), '(starting_smile)\n', (7698, 7714), False, 'from selfies import encoder, decoder\n'), ((8201, 8239), 'selfies.get_semantic_robust_alphabet', 'selfies.get_semantic_robust_alphabet', ([], {}), '()\n', (8237, 8239), False, 'import selfies\n'), ((8300, 8336), 'random.randint', 'random.randint', (['(1)', 'len_random_struct'], {}), '(1, len_random_struct)\n', (8314, 8336), False, 'import random\n'), ((9213, 9231), 'numpy.argmax', 'np.argmax', (['fitness'], {}), '(fitness)\n', (9222, 9231), True, 'import numpy as np\n'), ((9799, 9833), 'rdkit.Chem.MolFromSmiles', 'Chem.MolFromSmiles', (['starting_smile'], {}), '(starting_smile)\n', (9817, 9833), False, 'from rdkit import Chem\n'), ((9920, 9957), 'rdkit.DataStructs.cDataStructs.TanimotoSimilarity', 'TanimotoSimilarity', (['fp_mol', 'fp_target'], {}), '(fp_mol, fp_target)\n', (9938, 9957), False, 'from rdkit.DataStructs.cDataStructs import TanimotoSimilarity\n'), ((2613, 2651), 'selfies.get_semantic_robust_alphabet', 'selfies.get_semantic_robust_alphabet', ([], {}), '()\n', (2649, 2651), False, 'import selfies\n'), ((2761, 2791), 'numpy.random.choice', 'np.random.choice', (['choice_ls', '(1)'], {}), '(choice_ls, 1)\n', (2777, 2791), True, 'import numpy as np\n'), ((4271, 4294), 'selfies.decoder', 'decoder', (['selfie_mutated'], {}), '(selfie_mutated)\n', (4278, 4294), False, 'from selfies import encoder, decoder\n'), ((8710, 8753), 'numpy.random.choice', 'np.random.choice', (['starting_selfie'], {'size': '(500)'}), '(starting_selfie, size=500)\n', (8726, 8753), True, 'import numpy as np\n'), ((9760, 9780), 'selfies.decoder', 'decoder', (['best_selfie'], {}), '(best_selfie)\n', (9767, 9780), False, 'from selfies import encoder, decoder\n'), ((2983, 3017), 'numpy.random.choice', 'np.random.choice', (['alphabet'], {'size': '(1)'}), '(alphabet, size=1)\n', (2999, 3017), True, 'import numpy as np\n'), ((8420, 8454), 'numpy.random.choice', 'np.random.choice', (['alphabet'], {'size': '(1)'}), '(alphabet, size=1)\n', (8436, 8454), True, 'import numpy as np\n'), ((3340, 3374), 'numpy.random.choice', 'np.random.choice', (['alphabet'], {'size': '(1)'}), '(alphabet, size=1)\n', (3356, 3374), True, 'import numpy as np\n')] |
from analyser import Analyser
from explorer import Explorer
import matplotlib.pyplot as plt
import numpy as np
class Reporter():
def __init__(self, explorer):
self.explorer = explorer
self.analyser = Analyser(self.explorer.df)
def plot_tir(self, in_range, below_range, above_range, fname):
"""plot time in range piechart"""
values = np.array([in_range, below_range, above_range])
total = in_range + below_range + above_range
in_range = int(100*in_range/total)
below_range = int(100*below_range/total)
above_range = int(100*above_range/total)
labels = [f"In Range ({in_range}%)", f"Below Range({below_range}%)",
f"Above Range({above_range}%)"]
plt.pie(values, labels=labels, startangle=90)
plt.title("Time in Range")
plt.savefig(fname)
plt.clf()
def plot_grouped_glucose(self, y, x, error, xlabel, ylabel, title,
fname, incline_xlabel=False):
"""plot glucose entries per hour of the day (mean and std)"""
plt.xticks(x, rotation=(90 if incline_xlabel else 0))
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.errorbar(x, y, error, linestyle='-', marker='o', ecolor='green',
capsize=2)
plt.title(title)
plt.savefig(fname)
plt.clf()
def get_values(self):
"""calculate all necessary information"""
self.explorer.last_x_days(90)
# hba1c
hba1c = self.analyser.hba1c() #TODO
self.explorer.reset_df().last_x_days(15)
# tir
in_range, below_range, above_range = self.analyser.tir(70, 180)
tir_graph_fname = 'tir.png'
self.plot_tir(in_range, below_range, above_range, 'tir.png') #TODO
# total entries
total_entries = self.analyser.count() #TODO
groupby_day = self.analyser.groupby_day()
# entries per day
entries_per_day = groupby_day["date"].count() #TODO
# fast insulin total, mean, std per day
fast_per_day = groupby_day["fast_insulin"].sum()
mean_fast_per_day = fast_per_day.mean() #TODO
std_fast_per_day = fast_per_day.std() #TODO
# glucose mean, std per hour
groupby_hour = self.analyser.groupby_hour()
glucose_per_hour = {
"mean": groupby_hour["glucose"].mean(),
"std": groupby_hour["glucose"].std(),
}
self.plot_grouped_glucose(y=glucose_per_hour["mean"],
x=np.array(range(24)),
error=glucose_per_hour["std"],
xlabel="Hour", ylabel="Glucose (mg/dL)",
title="Glucose per Hour",
fname="glucose_hour.png") #TODO
# all entries table (pretty)
show_columns = {
'date': 'Date',
'glucose': 'Glucose',
'bolus_insulin': 'Bolus',
'correction_insulin': 'Correction',
'basal_insulin': 'Basal',
'meal': 'Meal',
'carbs': 'Carbohydrates',
}
table = self.analyser.df[list(show_columns.keys())].copy()
meal_to_str = lambda meal: '; '.join(
[f"{x}, {meal[x]:.1f}g" for x in meal.keys()])
table["meal"] = table["meal"].apply(meal_to_str)
numeric_columns = ["glucose", "carbs", "bolus_insulin",
"correction_insulin", "basal_insulin"]
for col in numeric_columns:
table[col] = table[col].fillna(0).apply(lambda x: int(x))
table = table.rename(columns=show_columns)
if __name__=="__main__":
a = Explorer('diaguard.csv', verbose=True)
b = Reporter(a)
b.get_values()
| [
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.errorbar",
"analyser.Analyser",
"matplotlib.pyplot.clf",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.pie",
"numpy.array",
"explorer.Explorer",
"matplotlib.pyplot.title"
] | [((3693, 3731), 'explorer.Explorer', 'Explorer', (['"""diaguard.csv"""'], {'verbose': '(True)'}), "('diaguard.csv', verbose=True)\n", (3701, 3731), False, 'from explorer import Explorer\n'), ((221, 247), 'analyser.Analyser', 'Analyser', (['self.explorer.df'], {}), '(self.explorer.df)\n', (229, 247), False, 'from analyser import Analyser\n'), ((375, 421), 'numpy.array', 'np.array', (['[in_range, below_range, above_range]'], {}), '([in_range, below_range, above_range])\n', (383, 421), True, 'import numpy as np\n'), ((751, 796), 'matplotlib.pyplot.pie', 'plt.pie', (['values'], {'labels': 'labels', 'startangle': '(90)'}), '(values, labels=labels, startangle=90)\n', (758, 796), True, 'import matplotlib.pyplot as plt\n'), ((805, 831), 'matplotlib.pyplot.title', 'plt.title', (['"""Time in Range"""'], {}), "('Time in Range')\n", (814, 831), True, 'import matplotlib.pyplot as plt\n'), ((840, 858), 'matplotlib.pyplot.savefig', 'plt.savefig', (['fname'], {}), '(fname)\n', (851, 858), True, 'import matplotlib.pyplot as plt\n'), ((867, 876), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (874, 876), True, 'import matplotlib.pyplot as plt\n'), ((1069, 1120), 'matplotlib.pyplot.xticks', 'plt.xticks', (['x'], {'rotation': '(90 if incline_xlabel else 0)'}), '(x, rotation=90 if incline_xlabel else 0)\n', (1079, 1120), True, 'import matplotlib.pyplot as plt\n'), ((1131, 1149), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['xlabel'], {}), '(xlabel)\n', (1141, 1149), True, 'import matplotlib.pyplot as plt\n'), ((1158, 1176), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['ylabel'], {}), '(ylabel)\n', (1168, 1176), True, 'import matplotlib.pyplot as plt\n'), ((1185, 1264), 'matplotlib.pyplot.errorbar', 'plt.errorbar', (['x', 'y', 'error'], {'linestyle': '"""-"""', 'marker': '"""o"""', 'ecolor': '"""green"""', 'capsize': '(2)'}), "(x, y, error, linestyle='-', marker='o', ecolor='green', capsize=2)\n", (1197, 1264), True, 'import matplotlib.pyplot as plt\n'), ((1294, 1310), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (1303, 1310), True, 'import matplotlib.pyplot as plt\n'), ((1319, 1337), 'matplotlib.pyplot.savefig', 'plt.savefig', (['fname'], {}), '(fname)\n', (1330, 1337), True, 'import matplotlib.pyplot as plt\n'), ((1346, 1355), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (1353, 1355), True, 'import matplotlib.pyplot as plt\n')] |
""" Functions to solve orbiting bodies problems.
Written by: <NAME>
"""
import numpy as np
from orbitutils.solvers import rkf45
def two_body_3d_rates(t, Y, m1=1., m2=.1):
"""Find the state derivatives for the two body problem in 3D.
Parameters
----------
t : float
Time to evaluate the derivatives at.
Y : numpy.array
State vector.
m1 : float
Mass of the first body (kg).
m2 : float
Mass of the second body (kg).
Returns
-------
F : numpy.array
Array of state derivatives.
"""
# Extract vectors from state vector
R1 = Y[0:3]
R2 = Y[3:6]
V1 = Y[6:9]
V2 = Y[9:12]
# Constants
G = 6.64742e-11
# Position vector of m2 relative to m1
R = R2 - R1
r = np.linalg.norm(R)
# Compute derivatives
F = np.zeros(Y.shape)
F[0:3] = V1 # dR1/dt = V1
F[3:6] = V2 # dR2/dt = V2
F[6:9] = G * m2 * R / r**3
F[9:12] = - G * m1 * R / r**3
return F
def two_body_3d(R1_0, R2_0, V1_0, V2_0, m1, m2, tSpan=np.array([0., 10.0])):
""" Compute the position and velocity of two bodies in 3D over time.
Parameters
----------
R1_0 : numpy.array
Initial position of the first body.
R2_0 : numpy.array
Initial position of the second body.
V1_0 : numpy.array
Initial velocity of the first body.
V2_0 : numpy.array
Initial velocity of the second body.
m1 : float
Mass of the first body (kg).
m2 : float
Mass of the second body (kg).
tSpan : numpy.array
Range of times to solve for.
Returns
-------
ys : numpy.array
State time response.
ts : numpy.array
Time vector.
"""
Y0 = np.concatenate((R1_0, R2_0, V1_0, V2_0))
# Create anonymous function to pass m1 and m2
def rates(t, Y): return two_body_3d_rates(t, Y, m1, m2)
ys, ts = rkf45(rates, Y0, tSpan)
return (ys, ts)
def n_body_3d_rates(t, Y, M):
"""Find the state derivatives for the N body problem in 3D.
Parameters
----------
t : float
Time to evaluate the derivatives at.
Y : numpy.array
State vector.
M : numpy.array
Array of the masses of the N bodies (kg).
Returns
-------
F : numpy.array
Array of state derivatives.
"""
# Extract vectors from state vector
n = M.shape[0]
# Store the vectors for each mass in a different column
R = np.reshape(Y[0:n * 3], (3, n), order='F')
V = np.reshape(Y[n * 3:], (3, n), order='F')
# Constants
G = 6.67259e-11
# Find acceleration
A = np.zeros(V.shape)
for m in range(n):
R_m = R[:, m]
R_other = np.delete(R, m, 1) - np.reshape(R_m, (3, 1))
r_other = np.linalg.norm(R_other, axis=0)
M_other = np.delete(M, m, 0)
A[:, m] = np.sum(G * M_other * R_other / r_other**3, axis=1)
# Assign the rates
F = np.concatenate((np.reshape(V, (n * 3,), order='F'),
np.reshape(A, (n * 3,), order='F')))
return F
def n_body_3d(R_0, V_0, M, tSpan=np.array([0., 10.0])):
""" Compute the position and velocity of N bodies in 3D over time.
Parameters
----------
R_0 : numpy.array
Vector of initial positions of the N bodies in the form
[x1 y1 z1 x2 y2 z2 ...]
V_0 : numpy.array
Vector of initial velocities of the N bodies in the form
[vx1 vy1 vz1 vx2 vy2 vz2 ...]
M : float
Vector of masses (kg) in the form
[m1 m2 m3 ...]
tSpan : numpy.array
Range of times to solve for.
Returns
-------
ys : numpy.array
State time response.
ts : numpy.array
Time vector.
"""
n = M.shape[0]
Y0 = np.concatenate((np.reshape(R_0, (n * 3,), order='F'),
np.reshape(V_0, (n * 3,), order='F')))
# Create anonymous function to pass m1 and m2
def rates(t, Y): return n_body_3d_rates(t, Y, M)
ys, ts = rkf45(rates, Y0, tSpan)
return (ys, ts)
def orbit_rates(t, Y, m1, m2):
"""Find the state derivatives for the relative orbit problem.
m1 has a non-rotating cartesian coordinate frame.
Parameters
----------
t : float
Time to evaluate the derivatives at.
Y : numpy.array
State vector (km or km/s).
m1 : float
Mass of body 1 (kg).
m2 : float
Mass of body 2 (kg).
Returns
-------
F : numpy.array
Array of state derivatives.
"""
# Store the vectors for each mass in a different column
R = Y[0:3]
RDot = Y[3:6]
# Constants
G = 6.67259e-20
# Find acceleration
mu = G * (m1 + m2)
r = np.linalg.norm(R)
RDDot = - R * mu / r**3
# Assign the rates
F = np.concatenate((RDot, RDDot))
return F
def orbit(R_0, V_0, M, tSpan):
""" Compute the position and velocity of m1 relative to m2.
m1 has a non-rotating cartesian coordinate frame.
Parameters
----------
R_0 : numpy.array
Initial position of m1 relative to m2 (km).
V_0 : numpy.array
Initial velocity of m1 relative to m2 (km/s).
M : numpy.array
Vector of masses (kg) in the form [m1 m2].
tSpan : numpy.array
Range of times to solve for.
Returns
-------
ys : numpy.array
State time response.
ts : numpy.array
Time vector.
"""
Y_0 = np.concatenate((R_0, V_0))
# Create anonymous function to pass m1 and m2
def rates(t, Y): return orbit_rates(t, Y, M[0], M[1])
ys, ts = rkf45(rates, Y_0, tSpan)
return (ys, ts)
| [
"numpy.reshape",
"numpy.delete",
"numpy.array",
"numpy.zeros",
"numpy.sum",
"numpy.concatenate",
"numpy.linalg.norm",
"orbitutils.solvers.rkf45"
] | [((812, 829), 'numpy.linalg.norm', 'np.linalg.norm', (['R'], {}), '(R)\n', (826, 829), True, 'import numpy as np\n'), ((868, 885), 'numpy.zeros', 'np.zeros', (['Y.shape'], {}), '(Y.shape)\n', (876, 885), True, 'import numpy as np\n'), ((1092, 1113), 'numpy.array', 'np.array', (['[0.0, 10.0]'], {}), '([0.0, 10.0])\n', (1100, 1113), True, 'import numpy as np\n'), ((1816, 1856), 'numpy.concatenate', 'np.concatenate', (['(R1_0, R2_0, V1_0, V2_0)'], {}), '((R1_0, R2_0, V1_0, V2_0))\n', (1830, 1856), True, 'import numpy as np\n'), ((1987, 2010), 'orbitutils.solvers.rkf45', 'rkf45', (['rates', 'Y0', 'tSpan'], {}), '(rates, Y0, tSpan)\n', (1992, 2010), False, 'from orbitutils.solvers import rkf45\n'), ((2573, 2614), 'numpy.reshape', 'np.reshape', (['Y[0:n * 3]', '(3, n)'], {'order': '"""F"""'}), "(Y[0:n * 3], (3, n), order='F')\n", (2583, 2614), True, 'import numpy as np\n'), ((2624, 2664), 'numpy.reshape', 'np.reshape', (['Y[n * 3:]', '(3, n)'], {'order': '"""F"""'}), "(Y[n * 3:], (3, n), order='F')\n", (2634, 2664), True, 'import numpy as np\n'), ((2741, 2758), 'numpy.zeros', 'np.zeros', (['V.shape'], {}), '(V.shape)\n', (2749, 2758), True, 'import numpy as np\n'), ((3230, 3251), 'numpy.array', 'np.array', (['[0.0, 10.0]'], {}), '([0.0, 10.0])\n', (3238, 3251), True, 'import numpy as np\n'), ((4158, 4181), 'orbitutils.solvers.rkf45', 'rkf45', (['rates', 'Y0', 'tSpan'], {}), '(rates, Y0, tSpan)\n', (4163, 4181), False, 'from orbitutils.solvers import rkf45\n'), ((4900, 4917), 'numpy.linalg.norm', 'np.linalg.norm', (['R'], {}), '(R)\n', (4914, 4917), True, 'import numpy as np\n'), ((4982, 5011), 'numpy.concatenate', 'np.concatenate', (['(RDot, RDDot)'], {}), '((RDot, RDDot))\n', (4996, 5011), True, 'import numpy as np\n'), ((5652, 5678), 'numpy.concatenate', 'np.concatenate', (['(R_0, V_0)'], {}), '((R_0, V_0))\n', (5666, 5678), True, 'import numpy as np\n'), ((5807, 5831), 'orbitutils.solvers.rkf45', 'rkf45', (['rates', 'Y_0', 'tSpan'], {}), '(rates, Y_0, tSpan)\n', (5812, 5831), False, 'from orbitutils.solvers import rkf45\n'), ((2889, 2920), 'numpy.linalg.norm', 'np.linalg.norm', (['R_other'], {'axis': '(0)'}), '(R_other, axis=0)\n', (2903, 2920), True, 'import numpy as np\n'), ((2940, 2958), 'numpy.delete', 'np.delete', (['M', 'm', '(0)'], {}), '(M, m, 0)\n', (2949, 2958), True, 'import numpy as np\n'), ((2978, 3030), 'numpy.sum', 'np.sum', (['(G * M_other * R_other / r_other ** 3)'], {'axis': '(1)'}), '(G * M_other * R_other / r_other ** 3, axis=1)\n', (2984, 3030), True, 'import numpy as np\n'), ((2825, 2843), 'numpy.delete', 'np.delete', (['R', 'm', '(1)'], {}), '(R, m, 1)\n', (2834, 2843), True, 'import numpy as np\n'), ((2846, 2869), 'numpy.reshape', 'np.reshape', (['R_m', '(3, 1)'], {}), '(R_m, (3, 1))\n', (2856, 2869), True, 'import numpy as np\n'), ((3080, 3114), 'numpy.reshape', 'np.reshape', (['V', '(n * 3,)'], {'order': '"""F"""'}), "(V, (n * 3,), order='F')\n", (3090, 3114), True, 'import numpy as np\n'), ((3141, 3175), 'numpy.reshape', 'np.reshape', (['A', '(n * 3,)'], {'order': '"""F"""'}), "(A, (n * 3,), order='F')\n", (3151, 3175), True, 'import numpy as np\n'), ((3932, 3968), 'numpy.reshape', 'np.reshape', (['R_0', '(n * 3,)'], {'order': '"""F"""'}), "(R_0, (n * 3,), order='F')\n", (3942, 3968), True, 'import numpy as np\n'), ((3996, 4032), 'numpy.reshape', 'np.reshape', (['V_0', '(n * 3,)'], {'order': '"""F"""'}), "(V_0, (n * 3,), order='F')\n", (4006, 4032), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
# Copyright 2018 IBM.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# =============================================================================
import unittest
from itertools import combinations, chain
import numpy as np
from parameterized import parameterized
from qiskit import QuantumCircuit, QuantumRegister
from qiskit_aqua import get_aer_backend
from qiskit import execute as q_execute
from qiskit.quantum_info import state_fidelity
from test.common import QiskitAquaTestCase
class TestMCT(QiskitAquaTestCase):
@parameterized.expand([
[1],
[2],
[3],
[4],
[5],
[6],
[7],
])
def test_mct(self, num_controls):
c = QuantumRegister(num_controls, name='c')
o = QuantumRegister(1, name='o')
allsubsets = list(chain(*[combinations(range(num_controls), ni) for ni in range(num_controls + 1)]))
for subset in allsubsets:
for mode in ['basic', 'advanced']:
qc = QuantumCircuit(o, c)
if mode == 'basic':
if num_controls <= 2:
num_ancillae = 0
else:
num_ancillae = num_controls - 2
else:
if num_controls <= 4:
num_ancillae = 0
else:
num_ancillae = 1
if num_ancillae > 0:
a = QuantumRegister(num_ancillae, name='a')
qc.add_register(a)
for idx in subset:
qc.x(c[idx])
qc.cnx(
[c[i] for i in range(num_controls)],
o[0],
[a[i] for i in range(num_ancillae)],
mode=mode
)
for idx in subset:
qc.x(c[idx])
vec = np.asarray(q_execute(qc, get_aer_backend(
'statevector_simulator')).result().get_statevector(qc, decimals=16))
vec_o = [0, 1] if len(subset) == num_controls else [1, 0]
# print(vec, np.array(vec_o + [0] * (2 ** (num_controls + num_ancillae + 1) - 2)))
f = state_fidelity(vec, np.array(vec_o + [0] * (2 ** (num_controls + num_ancillae + 1) - 2)))
self.assertAlmostEqual(f, 1)
return
if __name__ == '__main__':
unittest.main()
| [
"qiskit_aqua.get_aer_backend",
"parameterized.parameterized.expand",
"numpy.array",
"unittest.main",
"qiskit.QuantumCircuit",
"qiskit.QuantumRegister"
] | [((1055, 1112), 'parameterized.parameterized.expand', 'parameterized.expand', (['[[1], [2], [3], [4], [5], [6], [7]]'], {}), '([[1], [2], [3], [4], [5], [6], [7]])\n', (1075, 1112), False, 'from parameterized import parameterized\n'), ((2934, 2949), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2947, 2949), False, 'import unittest\n'), ((1226, 1265), 'qiskit.QuantumRegister', 'QuantumRegister', (['num_controls'], {'name': '"""c"""'}), "(num_controls, name='c')\n", (1241, 1265), False, 'from qiskit import QuantumCircuit, QuantumRegister\n'), ((1278, 1306), 'qiskit.QuantumRegister', 'QuantumRegister', (['(1)'], {'name': '"""o"""'}), "(1, name='o')\n", (1293, 1306), False, 'from qiskit import QuantumCircuit, QuantumRegister\n'), ((1518, 1538), 'qiskit.QuantumCircuit', 'QuantumCircuit', (['o', 'c'], {}), '(o, c)\n', (1532, 1538), False, 'from qiskit import QuantumCircuit, QuantumRegister\n'), ((1973, 2012), 'qiskit.QuantumRegister', 'QuantumRegister', (['num_ancillae'], {'name': '"""a"""'}), "(num_ancillae, name='a')\n", (1988, 2012), False, 'from qiskit import QuantumCircuit, QuantumRegister\n'), ((2767, 2835), 'numpy.array', 'np.array', (['(vec_o + [0] * (2 ** (num_controls + num_ancillae + 1) - 2))'], {}), '(vec_o + [0] * (2 ** (num_controls + num_ancillae + 1) - 2))\n', (2775, 2835), True, 'import numpy as np\n'), ((2448, 2488), 'qiskit_aqua.get_aer_backend', 'get_aer_backend', (['"""statevector_simulator"""'], {}), "('statevector_simulator')\n", (2463, 2488), False, 'from qiskit_aqua import get_aer_backend\n')] |
import functools
import warnings
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import tensorflow.compat.v2 as tf
import tensorflow_probability as tfp
from tensorflow_probability import bijectors as tfb
from tensorflow_probability import distributions as tfd
tf.enable_v2_behavior()
warnings.filterwarnings('ignore')
def probabilistic_pca(data_dim, latent_dim, num_datapoints, stddv_datapoints, w):
# w = yield tfd.Normal(loc=tf.zeros([data_dim, latent_dim]),
# scale=2.0 * tf.ones([data_dim, latent_dim]),
# name="w")
z = yield tfd.Normal(loc=tf.zeros([latent_dim, num_datapoints]),
scale=tf.ones([latent_dim, num_datapoints]),
name="z")
x = yield tfd.Normal(loc=tf.matmul(w, z),
scale=stddv_datapoints,
name="x")
num_datapoints = 500
data_dim = 2
latent_dim = 1
stddv_datapoints = 0.5
# w = tf.Variable(np.random.normal(size=[data_dim, latent_dim]).astype(np.float32))
w_true = tf.Variable(np.array([[5.], [5.]]).astype(np.float32))
concrete_ppca_model = functools.partial(probabilistic_pca,
data_dim=data_dim,
latent_dim=latent_dim,
num_datapoints=num_datapoints,
stddv_datapoints=stddv_datapoints,
w=w_true)
model = tfd.JointDistributionCoroutineAutoBatched(concrete_ppca_model)
actual_z, x_train = model.sample()
w = tf.Variable(tf.random.normal([data_dim, latent_dim]))
print(w)
concrete_ppca_model = functools.partial(probabilistic_pca,
data_dim=data_dim,
latent_dim=latent_dim,
num_datapoints=num_datapoints,
stddv_datapoints=stddv_datapoints,
w=w)
model = tfd.JointDistributionCoroutineAutoBatched(concrete_ppca_model)
target_log_prob_fn = lambda z: model.log_prob((z, x_train))
# qw_mean = tf.Variable(tf.random.normal([data_dim, latent_dim]))
qz_mean = tf.Variable(tf.random.normal([latent_dim, num_datapoints]))
# qw_stddv = tfp.util.TransformedVariable(1e-4 * tf.ones([data_dim, latent_dim]),
# bijector=tfb.Softplus())
qz_stddv = tfp.util.TransformedVariable(
1e-4 * tf.ones([latent_dim, num_datapoints]),
bijector=tfb.Softplus())
def factored_normal_variational_model():
# qw = yield tfd.Normal(loc=qw_mean, scale=qw_stddv, name="qw")
qz = yield tfd.Normal(loc=qz_mean, scale=qz_stddv, name="qz")
surrogate_posterior = tfd.JointDistributionCoroutineAutoBatched(
factored_normal_variational_model)
losses = tfp.vi.fit_surrogate_posterior(
target_log_prob_fn,
surrogate_posterior=surrogate_posterior,
optimizer=tf.optimizers.Adam(learning_rate=0.05),
num_steps=1000)
print(w)
plt.scatter(x_train.numpy()[0, :], x_train.numpy()[1, :])
plt.axis([-20, 20, -20, 20])
plt.show()
import ipdb; ipdb.set_trace()
| [
"tensorflow_probability.bijectors.Softplus",
"tensorflow_probability.distributions.Normal",
"matplotlib.pyplot.show",
"ipdb.set_trace",
"tensorflow_probability.distributions.JointDistributionCoroutineAutoBatched",
"tensorflow.compat.v2.random.normal",
"tensorflow.compat.v2.optimizers.Adam",
"tensorflo... | [((289, 312), 'tensorflow.compat.v2.enable_v2_behavior', 'tf.enable_v2_behavior', ([], {}), '()\n', (310, 312), True, 'import tensorflow.compat.v2 as tf\n'), ((314, 347), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (337, 347), False, 'import warnings\n'), ((1112, 1276), 'functools.partial', 'functools.partial', (['probabilistic_pca'], {'data_dim': 'data_dim', 'latent_dim': 'latent_dim', 'num_datapoints': 'num_datapoints', 'stddv_datapoints': 'stddv_datapoints', 'w': 'w_true'}), '(probabilistic_pca, data_dim=data_dim, latent_dim=\n latent_dim, num_datapoints=num_datapoints, stddv_datapoints=\n stddv_datapoints, w=w_true)\n', (1129, 1276), False, 'import functools\n'), ((1296, 1358), 'tensorflow_probability.distributions.JointDistributionCoroutineAutoBatched', 'tfd.JointDistributionCoroutineAutoBatched', (['concrete_ppca_model'], {}), '(concrete_ppca_model)\n', (1337, 1358), True, 'from tensorflow_probability import distributions as tfd\n'), ((1485, 1644), 'functools.partial', 'functools.partial', (['probabilistic_pca'], {'data_dim': 'data_dim', 'latent_dim': 'latent_dim', 'num_datapoints': 'num_datapoints', 'stddv_datapoints': 'stddv_datapoints', 'w': 'w'}), '(probabilistic_pca, data_dim=data_dim, latent_dim=\n latent_dim, num_datapoints=num_datapoints, stddv_datapoints=\n stddv_datapoints, w=w)\n', (1502, 1644), False, 'import functools\n'), ((1664, 1726), 'tensorflow_probability.distributions.JointDistributionCoroutineAutoBatched', 'tfd.JointDistributionCoroutineAutoBatched', (['concrete_ppca_model'], {}), '(concrete_ppca_model)\n', (1705, 1726), True, 'from tensorflow_probability import distributions as tfd\n'), ((2387, 2463), 'tensorflow_probability.distributions.JointDistributionCoroutineAutoBatched', 'tfd.JointDistributionCoroutineAutoBatched', (['factored_normal_variational_model'], {}), '(factored_normal_variational_model)\n', (2428, 2463), True, 'from tensorflow_probability import distributions as tfd\n'), ((2722, 2750), 'matplotlib.pyplot.axis', 'plt.axis', (['[-20, 20, -20, 20]'], {}), '([-20, 20, -20, 20])\n', (2730, 2750), True, 'import matplotlib.pyplot as plt\n'), ((2751, 2761), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2759, 2761), True, 'import matplotlib.pyplot as plt\n'), ((2775, 2791), 'ipdb.set_trace', 'ipdb.set_trace', ([], {}), '()\n', (2789, 2791), False, 'import ipdb\n'), ((1412, 1452), 'tensorflow.compat.v2.random.normal', 'tf.random.normal', (['[data_dim, latent_dim]'], {}), '([data_dim, latent_dim])\n', (1428, 1452), True, 'import tensorflow.compat.v2 as tf\n'), ((1876, 1922), 'tensorflow.compat.v2.random.normal', 'tf.random.normal', (['[latent_dim, num_datapoints]'], {}), '([latent_dim, num_datapoints])\n', (1892, 1922), True, 'import tensorflow.compat.v2 as tf\n'), ((2125, 2162), 'tensorflow.compat.v2.ones', 'tf.ones', (['[latent_dim, num_datapoints]'], {}), '([latent_dim, num_datapoints])\n', (2132, 2162), True, 'import tensorflow.compat.v2 as tf\n'), ((2177, 2191), 'tensorflow_probability.bijectors.Softplus', 'tfb.Softplus', ([], {}), '()\n', (2189, 2191), True, 'from tensorflow_probability import bijectors as tfb\n'), ((2313, 2363), 'tensorflow_probability.distributions.Normal', 'tfd.Normal', ([], {'loc': 'qz_mean', 'scale': 'qz_stddv', 'name': '"""qz"""'}), "(loc=qz_mean, scale=qz_stddv, name='qz')\n", (2323, 2363), True, 'from tensorflow_probability import distributions as tfd\n'), ((2594, 2632), 'tensorflow.compat.v2.optimizers.Adam', 'tf.optimizers.Adam', ([], {'learning_rate': '(0.05)'}), '(learning_rate=0.05)\n', (2612, 2632), True, 'import tensorflow.compat.v2 as tf\n'), ((1047, 1071), 'numpy.array', 'np.array', (['[[5.0], [5.0]]'], {}), '([[5.0], [5.0]])\n', (1055, 1071), True, 'import numpy as np\n'), ((614, 652), 'tensorflow.compat.v2.zeros', 'tf.zeros', (['[latent_dim, num_datapoints]'], {}), '([latent_dim, num_datapoints])\n', (622, 652), True, 'import tensorflow.compat.v2 as tf\n'), ((677, 714), 'tensorflow.compat.v2.ones', 'tf.ones', (['[latent_dim, num_datapoints]'], {}), '([latent_dim, num_datapoints])\n', (684, 714), True, 'import tensorflow.compat.v2 as tf\n'), ((770, 785), 'tensorflow.compat.v2.matmul', 'tf.matmul', (['w', 'z'], {}), '(w, z)\n', (779, 785), True, 'import tensorflow.compat.v2 as tf\n')] |
"""
================
Plot Vertex Data
================
This plots example vertex data onto an example subject, S1, onto a flatmap
using quickflat. In order for this to run, you have to have a flatmap for
this subject in the pycortex filestore.
The cortex.Vertex object is instantiated with a numpy array of the same size
as the total number of vertices in that subject's flatmap. Each pixel is
colored according to the value given for the nearest vertex in the flatmap.
Instead of the random test data, you can replace this with any array that is
the length of all of the vertices in the subject.
Additionally, if you create a Vertex object using only the number of vertices
that exists in the left hemisphere of the brain, the right hemisphere is
filled in with zeros.
"""
import cortex
import cortex.polyutils
import numpy as np
np.random.seed(1234)
import matplotlib.pyplot as plt
subject = 'S1'
# In order to get the number of vertices in this subject's cortical surface
# we have to load in their surfaces and get the number of points in each
surfs = [cortex.polyutils.Surface(*d)
for d in cortex.db.get_surf(subject, "fiducial")]
# This is the total number of vertices in both hemispheres combined
num_verts = surfs[0].pts.shape[0] + surfs[1].pts.shape[0]
# Creating a random dataset with one entry for each vertex
test_data = np.random.randn(num_verts)
# This creates a Vertex object for our subject and test dataset
vertex_data = cortex.Vertex(test_data, subject)
# And now we can display it on a flatmap
cortex.quickshow(vertex_data)
plt.show()
# We can also plot just the left hemisphere data
numl = surfs[0].pts.shape[0]
# This creates a Vertex object with an array only as long as the number of
# vertices in the left hemisphere, and the right hemisphere will be filled
# in with zeros
vertex_data_left = cortex.Vertex(test_data[:numl], subject)
cortex.quickshow(vertex_data_left)
plt.show()
| [
"cortex.polyutils.Surface",
"cortex.Vertex",
"cortex.db.get_surf",
"cortex.quickshow",
"numpy.random.seed",
"numpy.random.randn",
"matplotlib.pyplot.show"
] | [((836, 856), 'numpy.random.seed', 'np.random.seed', (['(1234)'], {}), '(1234)\n', (850, 856), True, 'import numpy as np\n'), ((1351, 1377), 'numpy.random.randn', 'np.random.randn', (['num_verts'], {}), '(num_verts)\n', (1366, 1377), True, 'import numpy as np\n'), ((1457, 1490), 'cortex.Vertex', 'cortex.Vertex', (['test_data', 'subject'], {}), '(test_data, subject)\n', (1470, 1490), False, 'import cortex\n'), ((1532, 1561), 'cortex.quickshow', 'cortex.quickshow', (['vertex_data'], {}), '(vertex_data)\n', (1548, 1561), False, 'import cortex\n'), ((1562, 1572), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1570, 1572), True, 'import matplotlib.pyplot as plt\n'), ((1837, 1877), 'cortex.Vertex', 'cortex.Vertex', (['test_data[:numl]', 'subject'], {}), '(test_data[:numl], subject)\n', (1850, 1877), False, 'import cortex\n'), ((1878, 1912), 'cortex.quickshow', 'cortex.quickshow', (['vertex_data_left'], {}), '(vertex_data_left)\n', (1894, 1912), False, 'import cortex\n'), ((1913, 1923), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1921, 1923), True, 'import matplotlib.pyplot as plt\n'), ((1064, 1092), 'cortex.polyutils.Surface', 'cortex.polyutils.Surface', (['*d'], {}), '(*d)\n', (1088, 1092), False, 'import cortex\n'), ((1111, 1150), 'cortex.db.get_surf', 'cortex.db.get_surf', (['subject', '"""fiducial"""'], {}), "(subject, 'fiducial')\n", (1129, 1150), False, 'import cortex\n')] |
"""
Test functions
Author(s): <NAME> (<EMAIL>)
"""
import numpy as np
import tensorflow as tf
class Function(object):
def __init__(self):
pass
def evaluate(self, data):
x = tf.placeholder(tf.float32, shape=[None, self.dim])
y = self.equation(x)
with tf.Session() as sess:
values = sess.run(y, feed_dict={x: data})
return values
class VLMOP2(Function):
'''
Reference:
<NAME>., & <NAME>. (1999, February).
Multiobjective evolutionary algorithm test suites.
In Proceedings of the 1999 ACM symposium on Applied computing (pp. 351-357).
'''
def __init__(self):
self.dim = 2
self.n_obj = 2
self.name = 'VLMOP2'
x1 = np.linspace(-1/self.dim**.5, 1/self.dim**.5, 100)
x2 = np.linspace(-1/self.dim**.5, 1/self.dim**.5, 100)
self.pareto_x = np.vstack((x1, x2)).T
self.pareto_y = self.evaluate(self.pareto_x)
def equation(self, x):
transl = 1 / np.sqrt(2)
part1 = (x[:, 0] - transl) ** 2 + (x[:, 1] - transl) ** 2
part2 = (x[:, 0] + transl) ** 2 + (x[:, 1] + transl) ** 2
y1 = tf.exp(-1 * part1)
y2 = tf.exp(-1 * part2)
return tf.stack((y1, y2), axis=1)
#class OKA1(Function):
# '''
# Reference:
# <NAME>., <NAME>., <NAME>., & <NAME>. (2004, September).
# On test functions for evolutionary multi-objective optimization.
# In International Conference on Parallel Problem Solving from Nature (pp. 792-802).
# Springer, Berlin, Heidelberg.
# '''
# def __init__(self):
# self.dim = 2
# self.n_obj = 2
# self.name = 'OKA1'
class NKNO1(Function):
'''
Normalized KNO1
Reference:
J. Knowles. ParEGO: A hybrid algorithm with on-line landscape approximation for
expensive multiobjective optimization problems. Technical Report TR-COMPSYSBIO-2004-01,
University of Manchester, UK, 2004. Available from http://dbk.ch.umist.ac.uk/knowles/pubs.html
'''
def __init__(self):
self.dim = 2
self.n_obj = 2
self.name = 'NKNO1'
x1 = np.linspace(-0.5+4.4116/3-1, 0.5, 100)
x2 = 4.4116/3 - x1 - 1
self.pareto_x = np.vstack((x1, x2)).T
self.pareto_y = self.evaluate(self.pareto_x)
def equation(self, x):
x = 3*(x+.5)
r = 9 - (3*tf.sin(5/2*(x[:,0]+x[:,1])**2) + 3*tf.sin(4*(x[:,0]+x[:,1])) + 5*tf.sin(2*(x[:,0]+x[:,1])+2))
phi = np.pi/12*(x[:,0]-x[:,1]+3)
y1 = r/20*tf.cos(phi)
y2 = r/20*tf.sin(phi)
return tf.stack((y1, y2), axis=1)
if __name__ == "__main__":
import matplotlib.pyplot as plt
import matplotlib
matplotlib.use('Qt5Agg')
N = 1000
xs = np.random.uniform(-.5, .5, size=(N,2))
func_obj = NKNO1()
ys = func_obj.evaluate(xs)
plt.figure()
plt.subplot(121)
true_pfx = func_obj.pareto_x
plt.plot(true_pfx[:,0], true_pfx[:,1])
plt.subplot(122)
plt.scatter(ys[:,0], ys[:,1])
true_pf = func_obj.pareto_y
plt.plot(true_pf[:,0], true_pf[:,1])
plt.show() | [
"numpy.sqrt",
"matplotlib.use",
"tensorflow.placeholder",
"matplotlib.pyplot.plot",
"tensorflow.Session",
"matplotlib.pyplot.figure",
"numpy.linspace",
"tensorflow.cos",
"numpy.vstack",
"matplotlib.pyplot.scatter",
"numpy.random.uniform",
"tensorflow.sin",
"matplotlib.pyplot.subplot",
"ten... | [((2798, 2822), 'matplotlib.use', 'matplotlib.use', (['"""Qt5Agg"""'], {}), "('Qt5Agg')\n", (2812, 2822), False, 'import matplotlib\n'), ((2850, 2891), 'numpy.random.uniform', 'np.random.uniform', (['(-0.5)', '(0.5)'], {'size': '(N, 2)'}), '(-0.5, 0.5, size=(N, 2))\n', (2867, 2891), True, 'import numpy as np\n'), ((2952, 2964), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (2962, 2964), True, 'import matplotlib.pyplot as plt\n'), ((2969, 2985), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(121)'], {}), '(121)\n', (2980, 2985), True, 'import matplotlib.pyplot as plt\n'), ((3023, 3063), 'matplotlib.pyplot.plot', 'plt.plot', (['true_pfx[:, 0]', 'true_pfx[:, 1]'], {}), '(true_pfx[:, 0], true_pfx[:, 1])\n', (3031, 3063), True, 'import matplotlib.pyplot as plt\n'), ((3066, 3082), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(122)'], {}), '(122)\n', (3077, 3082), True, 'import matplotlib.pyplot as plt\n'), ((3087, 3118), 'matplotlib.pyplot.scatter', 'plt.scatter', (['ys[:, 0]', 'ys[:, 1]'], {}), '(ys[:, 0], ys[:, 1])\n', (3098, 3118), True, 'import matplotlib.pyplot as plt\n'), ((3153, 3191), 'matplotlib.pyplot.plot', 'plt.plot', (['true_pf[:, 0]', 'true_pf[:, 1]'], {}), '(true_pf[:, 0], true_pf[:, 1])\n', (3161, 3191), True, 'import matplotlib.pyplot as plt\n'), ((3194, 3204), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3202, 3204), True, 'import matplotlib.pyplot as plt\n'), ((212, 262), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '[None, self.dim]'}), '(tf.float32, shape=[None, self.dim])\n', (226, 262), True, 'import tensorflow as tf\n'), ((770, 829), 'numpy.linspace', 'np.linspace', (['(-1 / self.dim ** 0.5)', '(1 / self.dim ** 0.5)', '(100)'], {}), '(-1 / self.dim ** 0.5, 1 / self.dim ** 0.5, 100)\n', (781, 829), True, 'import numpy as np\n'), ((833, 892), 'numpy.linspace', 'np.linspace', (['(-1 / self.dim ** 0.5)', '(1 / self.dim ** 0.5)', '(100)'], {}), '(-1 / self.dim ** 0.5, 1 / self.dim ** 0.5, 100)\n', (844, 892), True, 'import numpy as np\n'), ((1191, 1209), 'tensorflow.exp', 'tf.exp', (['(-1 * part1)'], {}), '(-1 * part1)\n', (1197, 1209), True, 'import tensorflow as tf\n'), ((1223, 1241), 'tensorflow.exp', 'tf.exp', (['(-1 * part2)'], {}), '(-1 * part2)\n', (1229, 1241), True, 'import tensorflow as tf\n'), ((1257, 1283), 'tensorflow.stack', 'tf.stack', (['(y1, y2)'], {'axis': '(1)'}), '((y1, y2), axis=1)\n', (1265, 1283), True, 'import tensorflow as tf\n'), ((2216, 2260), 'numpy.linspace', 'np.linspace', (['(-0.5 + 4.4116 / 3 - 1)', '(0.5)', '(100)'], {}), '(-0.5 + 4.4116 / 3 - 1, 0.5, 100)\n', (2227, 2260), True, 'import numpy as np\n'), ((2671, 2697), 'tensorflow.stack', 'tf.stack', (['(y1, y2)'], {'axis': '(1)'}), '((y1, y2), axis=1)\n', (2679, 2697), True, 'import tensorflow as tf\n'), ((305, 317), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (315, 317), True, 'import tensorflow as tf\n'), ((907, 926), 'numpy.vstack', 'np.vstack', (['(x1, x2)'], {}), '((x1, x2))\n', (916, 926), True, 'import numpy as np\n'), ((1035, 1045), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (1042, 1045), True, 'import numpy as np\n'), ((2310, 2329), 'numpy.vstack', 'np.vstack', (['(x1, x2)'], {}), '((x1, x2))\n', (2319, 2329), True, 'import numpy as np\n'), ((2614, 2625), 'tensorflow.cos', 'tf.cos', (['phi'], {}), '(phi)\n', (2620, 2625), True, 'import tensorflow as tf\n'), ((2644, 2655), 'tensorflow.sin', 'tf.sin', (['phi'], {}), '(phi)\n', (2650, 2655), True, 'import tensorflow as tf\n'), ((2526, 2561), 'tensorflow.sin', 'tf.sin', (['(2 * (x[:, 0] + x[:, 1]) + 2)'], {}), '(2 * (x[:, 0] + x[:, 1]) + 2)\n', (2532, 2561), True, 'import tensorflow as tf\n'), ((2461, 2501), 'tensorflow.sin', 'tf.sin', (['(5 / 2 * (x[:, 0] + x[:, 1]) ** 2)'], {}), '(5 / 2 * (x[:, 0] + x[:, 1]) ** 2)\n', (2467, 2501), True, 'import tensorflow as tf\n'), ((2496, 2527), 'tensorflow.sin', 'tf.sin', (['(4 * (x[:, 0] + x[:, 1]))'], {}), '(4 * (x[:, 0] + x[:, 1]))\n', (2502, 2527), True, 'import tensorflow as tf\n')] |
from pddlgym.parser import PDDLDomainParser, PDDLProblemParser
from pddlgym.structs import LiteralConjunction
import pddlgym
import os
import numpy as np
from itertools import count
np.random.seed(0)
PDDLDIR = os.path.join(os.path.dirname(pddlgym.__file__), "pddl")
I, G, W, P, X, H = range(6)
TRAIN_GRID1 = np.array([
[I, P, P, P, X, X, X, W, W, G],
[W, W, X, P, X, W, W, X, X, P],
[W, W, X, P, X, X, W, X, X, P],
[W, W, X, P, X, X, X, X, X, P],
[W, W, X, P, X, W, W, X, X, P],
[W, W, X, P, X, W, W, X, X, P],
[W, W, X, P, X, X, W, X, X, P],
[W, W, X, P, H, P, P, H, P, P],
])
TRAIN_GRID2 = np.array([
[X, X, X, X, X, X, W, W, W, W],
[X, X, X, X, X, X, W, W, W, W],
[P, P, H, P, H, P, P, P, P, P],
[P, X, X, X, X, X, W, W, X, P],
[P, X, X, X, X, X, X, X, W, G],
[P, W, X, X, W, W, X, W, W, X],
[P, X, X, X, W, X, X, X, X, X],
[P, I, W, X, X, X, X, W, X, X],
])
TRAIN_GRID3 = np.array([
[X, P, P, P, P, P, P, P, X, X],
[X, H, X, X, W, W, X, P, X, X],
[X, P, X, X, W, W, X, G, X, X],
[X, P, X, X, X, X, X, X, X, X],
[I, P, X, X, W, W, X, X, X, X],
[X, X, X, X, X, X, X, X, X, X],
[X, X, X, X, W, W, X, X, X, X],
[X, X, X, X, W, W, X, X, X, X],
[X, X, X, X, X, X, X, X, X, X],
])
TRAIN_GRID4 = np.flipud(TRAIN_GRID3)
GRID1 = np.array([
[I, P, P, P, P],
[W, X, W, W, P],
[X, X, X, W, H],
[X, W, X, W, P],
[W, X, X, W, P],
[W, X, W, W, P],
[G, P, P, H, P],
])
GRID2 = np.array([
[P, P, I, X, X],
[P, W, W, W, X],
[P, W, W, X, X],
[H, W, X, X, W],
[P, W, X, X, X],
[P, W, W, W, W],
[P, P, G, W, W],
])
GRID3 = np.array([
[I, P, P, P, P, H, P, P, P, P,],
[X, X, W, W, X, X, X, W, W, P,],
[X, X, X, W, W, X, X, W, W, P,],
[W, X, X, W, W, X, X, X, W, P,],
[W, X, X, W, W, X, W, X, W, H,],
[W, X, X, W, W, X, W, X, W, P,],
[X, X, X, X, X, X, W, X, X, P,],
[X, X, X, W, W, X, W, W, X, P,],
[W, X, W, W, W, X, W, W, W, P,],
[W, X, X, W, W, X, W, W, W, P,],
[W, X, X, W, W, X, G, P, P, P,],
])
GRID4 = np.array([
[X, X, W, X, X, X, X, X, X, X, X, X, X, X, X, X],
[X, X, W, W, X, X, X, X, X, X, W, W, X, X, W, W],
[X, X, X, X, W, X, X, X, X, X, X, W, X, X, W, W],
[X, X, X, X, W, W, W, X, X, X, X, X, X, X, X, X],
[X, X, X, X, W, X, X, X, X, X, X, X, X, X, X, X],
[X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X],
[X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X],
[P, P, P, H, P, P, P, P, P, P, P, H, P, P, P, P],
[P, W, X, X, X, X, W, X, X, W, X, W, X, X, W, P],
[P, W, W, X, X, X, W, X, X, W, X, W, X, X, W, P],
[P, X, X, X, X, X, W, X, W, W, W, W, X, X, W, P],
[I, X, X, X, X, W, W, W, W, W, W, W, X, X, W, G],
])
GRID5 = np.array([
[G, P, P, P, W, W, W, W, W, W, X],
[X, X, X, P, W, W, W, W, W, W, X],
[X, X, X, P, W, W, W, W, W, W, X],
[P, P, P, P, W, W, W, W, W, W, X],
[P, X, X, X, W, W, W, W, W, W, X],
[P, X, X, X, W, W, W, W, W, W, X],
[P, X, X, X, W, W, W, W, W, W, X],
[H, X, X, X, W, W, W, W, W, W, X],
[P, X, X, X, W, W, W, W, W, W, X],
[P, X, X, X, W, W, W, W, W, W, X],
[P, X, X, X, W, W, W, W, W, W, X],
[P, X, X, X, W, W, W, W, W, W, X],
[I, X, X, X, W, W, W, W, W, W, X],
])
TRAIN_GRIDS = [TRAIN_GRID1, TRAIN_GRID2, TRAIN_GRID3, TRAIN_GRID4]
TEST_GRIDS = [GRID1, GRID2, GRID3, GRID4, GRID5]
def create_problem(grid, domain, problem_dir, problem_outfile):
# Create location objects
loc_type = domain.types['loc']
objects = set()
grid_locs = np.empty(grid.shape, dtype=object)
for r in range(grid.shape[0]):
for c in range(grid.shape[1]):
obj = loc_type(f'r{r}_c{c}')
objects.add(obj)
grid_locs[r, c] = obj
initial_state = set()
# Add at, isWater, isHill, isGoal
at = domain.predicates['at']
isWater = domain.predicates['iswater']
isHill = domain.predicates['ishill']
isGoal = domain.predicates['isgoal']
for r in range(grid.shape[0]):
for c in range(grid.shape[1]):
obj = grid_locs[r, c]
if grid[r, c] == I:
initial_state.add(at(obj))
elif grid[r, c] == W:
initial_state.add(isWater(obj))
elif grid[r, c] == H:
initial_state.add(isHill(obj))
elif grid[r, c] == G:
initial_state.add(isGoal(obj))
# Add adjacent
adjacent = domain.predicates['adjacent']
def get_neighbors(r, c):
for dr, dc in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
nr = r + dr
nc = c + dc
if 0 <= nr < grid.shape[0] and 0 <= nc < grid.shape[1]:
yield (nr, nc)
for r in range(grid.shape[0]):
for c in range(grid.shape[1]):
obj = grid_locs[r, c]
for (nr, nc) in get_neighbors(r, c):
nobj = grid_locs[nr, nc]
initial_state.add(adjacent(obj, nobj))
# Add onTrail
onTrail = domain.predicates['ontrail']
# Get the path
path = []
r, c = np.argwhere(grid == I)[0]
while True:
path.append((r, c))
if grid[r, c] == G:
break
for (nr, nc) in get_neighbors(r, c):
if (nr, nc) in path:
continue
if grid[nr, nc] in [P, G, H]:
r, c = nr, nc
break
else:
raise Exception("Should not happen")
for (r, c), (nr, nc) in zip(path[:-1], path[1:]):
obj = grid_locs[r, c]
nobj = grid_locs[nr, nc]
initial_state.add(onTrail(obj, nobj))
# Goal
goal_rcs = np.argwhere(grid == G)
assert len(goal_rcs) == 1
goal_r, goal_c = goal_rcs[0]
goal_obj = grid_locs[goal_r, goal_c]
goal = LiteralConjunction([at(goal_obj)])
filepath = os.path.join(PDDLDIR, problem_dir, problem_outfile)
PDDLProblemParser.create_pddl_file(
filepath,
objects=objects,
initial_state=initial_state,
problem_name="hiking",
domain_name=domain.domain_name,
goal=goal,
fast_downward_order=True,
)
print("Wrote out to {}.".format(filepath))
def generate_problems():
domain = PDDLDomainParser(os.path.join(PDDLDIR, "hiking.pddl"),
expect_action_preds=False,
operators_as_actions=True)
for problem_idx, grid in enumerate(TRAIN_GRIDS + TEST_GRIDS):
if problem_idx < len(TRAIN_GRIDS):
problem_dir = "hiking"
else:
problem_dir = "hiking_test"
problem_outfile = "problem{}.pddl".format(problem_idx)
create_problem(grid, domain, problem_dir, problem_outfile)
if __name__ == "__main__":
generate_problems()
| [
"numpy.flipud",
"os.path.join",
"os.path.dirname",
"numpy.array",
"numpy.argwhere",
"numpy.empty",
"numpy.random.seed",
"pddlgym.parser.PDDLProblemParser.create_pddl_file"
] | [((182, 199), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (196, 199), True, 'import numpy as np\n'), ((313, 592), 'numpy.array', 'np.array', (['[[I, P, P, P, X, X, X, W, W, G], [W, W, X, P, X, W, W, X, X, P], [W, W, X,\n P, X, X, W, X, X, P], [W, W, X, P, X, X, X, X, X, P], [W, W, X, P, X, W,\n W, X, X, P], [W, W, X, P, X, W, W, X, X, P], [W, W, X, P, X, X, W, X, X,\n P], [W, W, X, P, H, P, P, H, P, P]]'], {}), '([[I, P, P, P, X, X, X, W, W, G], [W, W, X, P, X, W, W, X, X, P], [\n W, W, X, P, X, X, W, X, X, P], [W, W, X, P, X, X, X, X, X, P], [W, W, X,\n P, X, W, W, X, X, P], [W, W, X, P, X, W, W, X, X, P], [W, W, X, P, X, X,\n W, X, X, P], [W, W, X, P, H, P, P, H, P, P]])\n', (321, 592), True, 'import numpy as np\n'), ((630, 909), 'numpy.array', 'np.array', (['[[X, X, X, X, X, X, W, W, W, W], [X, X, X, X, X, X, W, W, W, W], [P, P, H,\n P, H, P, P, P, P, P], [P, X, X, X, X, X, W, W, X, P], [P, X, X, X, X, X,\n X, X, W, G], [P, W, X, X, W, W, X, W, W, X], [P, X, X, X, W, X, X, X, X,\n X], [P, I, W, X, X, X, X, W, X, X]]'], {}), '([[X, X, X, X, X, X, W, W, W, W], [X, X, X, X, X, X, W, W, W, W], [\n P, P, H, P, H, P, P, P, P, P], [P, X, X, X, X, X, W, W, X, P], [P, X, X,\n X, X, X, X, X, W, G], [P, W, X, X, W, W, X, W, W, X], [P, X, X, X, W, X,\n X, X, X, X], [P, I, W, X, X, X, X, W, X, X]])\n', (638, 909), True, 'import numpy as np\n'), ((947, 1262), 'numpy.array', 'np.array', (['[[X, P, P, P, P, P, P, P, X, X], [X, H, X, X, W, W, X, P, X, X], [X, P, X,\n X, W, W, X, G, X, X], [X, P, X, X, X, X, X, X, X, X], [I, P, X, X, W, W,\n X, X, X, X], [X, X, X, X, X, X, X, X, X, X], [X, X, X, X, W, W, X, X, X,\n X], [X, X, X, X, W, W, X, X, X, X], [X, X, X, X, X, X, X, X, X, X]]'], {}), '([[X, P, P, P, P, P, P, P, X, X], [X, H, X, X, W, W, X, P, X, X], [\n X, P, X, X, W, W, X, G, X, X], [X, P, X, X, X, X, X, X, X, X], [I, P, X,\n X, W, W, X, X, X, X], [X, X, X, X, X, X, X, X, X, X], [X, X, X, X, W, W,\n X, X, X, X], [X, X, X, X, W, W, X, X, X, X], [X, X, X, X, X, X, X, X, X,\n X]])\n', (955, 1262), True, 'import numpy as np\n'), ((1300, 1322), 'numpy.flipud', 'np.flipud', (['TRAIN_GRID3'], {}), '(TRAIN_GRID3)\n', (1309, 1322), True, 'import numpy as np\n'), ((1332, 1466), 'numpy.array', 'np.array', (['[[I, P, P, P, P], [W, X, W, W, P], [X, X, X, W, H], [X, W, X, W, P], [W, X,\n X, W, P], [W, X, W, W, P], [G, P, P, H, P]]'], {}), '([[I, P, P, P, P], [W, X, W, W, P], [X, X, X, W, H], [X, W, X, W, P\n ], [W, X, X, W, P], [W, X, W, W, P], [G, P, P, H, P]])\n', (1340, 1466), True, 'import numpy as np\n'), ((1502, 1636), 'numpy.array', 'np.array', (['[[P, P, I, X, X], [P, W, W, W, X], [P, W, W, X, X], [H, W, X, X, W], [P, W,\n X, X, X], [P, W, W, W, W], [P, P, G, W, W]]'], {}), '([[P, P, I, X, X], [P, W, W, W, X], [P, W, W, X, X], [H, W, X, X, W\n ], [P, W, X, X, X], [P, W, W, W, W], [P, P, G, W, W]])\n', (1510, 1636), True, 'import numpy as np\n'), ((1672, 2051), 'numpy.array', 'np.array', (['[[I, P, P, P, P, H, P, P, P, P], [X, X, W, W, X, X, X, W, W, P], [X, X, X,\n W, W, X, X, W, W, P], [W, X, X, W, W, X, X, X, W, P], [W, X, X, W, W, X,\n W, X, W, H], [W, X, X, W, W, X, W, X, W, P], [X, X, X, X, X, X, W, X, X,\n P], [X, X, X, W, W, X, W, W, X, P], [W, X, W, W, W, X, W, W, W, P], [W,\n X, X, W, W, X, W, W, W, P], [W, X, X, W, W, X, G, P, P, P]]'], {}), '([[I, P, P, P, P, H, P, P, P, P], [X, X, W, W, X, X, X, W, W, P], [\n X, X, X, W, W, X, X, W, W, P], [W, X, X, W, W, X, X, X, W, P], [W, X, X,\n W, W, X, W, X, W, H], [W, X, X, W, W, X, W, X, W, P], [X, X, X, X, X, X,\n W, X, X, P], [X, X, X, W, W, X, W, W, X, P], [W, X, W, W, W, X, W, W, W,\n P], [W, X, X, W, W, X, W, W, W, P], [W, X, X, W, W, X, G, P, P, P]])\n', (1680, 2051), True, 'import numpy as np\n'), ((2102, 2744), 'numpy.array', 'np.array', (['[[X, X, W, X, X, X, X, X, X, X, X, X, X, X, X, X], [X, X, W, W, X, X, X, X,\n X, X, W, W, X, X, W, W], [X, X, X, X, W, X, X, X, X, X, X, W, X, X, W,\n W], [X, X, X, X, W, W, W, X, X, X, X, X, X, X, X, X], [X, X, X, X, W, X,\n X, X, X, X, X, X, X, X, X, X], [X, X, X, X, X, X, X, X, X, X, X, X, X,\n X, X, X], [X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X], [P, P, P, H,\n P, P, P, P, P, P, P, H, P, P, P, P], [P, W, X, X, X, X, W, X, X, W, X,\n W, X, X, W, P], [P, W, W, X, X, X, W, X, X, W, X, W, X, X, W, P], [P, X,\n X, X, X, X, W, X, W, W, W, W, X, X, W, P], [I, X, X, X, X, W, W, W, W,\n W, W, W, X, X, W, G]]'], {}), '([[X, X, W, X, X, X, X, X, X, X, X, X, X, X, X, X], [X, X, W, W, X,\n X, X, X, X, X, W, W, X, X, W, W], [X, X, X, X, W, X, X, X, X, X, X, W,\n X, X, W, W], [X, X, X, X, W, W, W, X, X, X, X, X, X, X, X, X], [X, X, X,\n X, W, X, X, X, X, X, X, X, X, X, X, X], [X, X, X, X, X, X, X, X, X, X,\n X, X, X, X, X, X], [X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X], [P,\n P, P, H, P, P, P, P, P, P, P, H, P, P, P, P], [P, W, X, X, X, X, W, X,\n X, W, X, W, X, X, W, P], [P, W, W, X, X, X, W, X, X, W, X, W, X, X, W,\n P], [P, X, X, X, X, X, W, X, W, W, W, W, X, X, W, P], [I, X, X, X, X, W,\n W, W, W, W, W, W, X, X, W, G]])\n', (2110, 2744), True, 'import numpy as np\n'), ((2773, 3264), 'numpy.array', 'np.array', (['[[G, P, P, P, W, W, W, W, W, W, X], [X, X, X, P, W, W, W, W, W, W, X], [X,\n X, X, P, W, W, W, W, W, W, X], [P, P, P, P, W, W, W, W, W, W, X], [P, X,\n X, X, W, W, W, W, W, W, X], [P, X, X, X, W, W, W, W, W, W, X], [P, X, X,\n X, W, W, W, W, W, W, X], [H, X, X, X, W, W, W, W, W, W, X], [P, X, X, X,\n W, W, W, W, W, W, X], [P, X, X, X, W, W, W, W, W, W, X], [P, X, X, X, W,\n W, W, W, W, W, X], [P, X, X, X, W, W, W, W, W, W, X], [I, X, X, X, W, W,\n W, W, W, W, X]]'], {}), '([[G, P, P, P, W, W, W, W, W, W, X], [X, X, X, P, W, W, W, W, W, W,\n X], [X, X, X, P, W, W, W, W, W, W, X], [P, P, P, P, W, W, W, W, W, W, X\n ], [P, X, X, X, W, W, W, W, W, W, X], [P, X, X, X, W, W, W, W, W, W, X],\n [P, X, X, X, W, W, W, W, W, W, X], [H, X, X, X, W, W, W, W, W, W, X], [\n P, X, X, X, W, W, W, W, W, W, X], [P, X, X, X, W, W, W, W, W, W, X], [P,\n X, X, X, W, W, W, W, W, W, X], [P, X, X, X, W, W, W, W, W, W, X], [I, X,\n X, X, W, W, W, W, W, W, X]])\n', (2781, 3264), True, 'import numpy as np\n'), ((225, 258), 'os.path.dirname', 'os.path.dirname', (['pddlgym.__file__'], {}), '(pddlgym.__file__)\n', (240, 258), False, 'import os\n'), ((3585, 3619), 'numpy.empty', 'np.empty', (['grid.shape'], {'dtype': 'object'}), '(grid.shape, dtype=object)\n', (3593, 3619), True, 'import numpy as np\n'), ((5681, 5703), 'numpy.argwhere', 'np.argwhere', (['(grid == G)'], {}), '(grid == G)\n', (5692, 5703), True, 'import numpy as np\n'), ((5870, 5921), 'os.path.join', 'os.path.join', (['PDDLDIR', 'problem_dir', 'problem_outfile'], {}), '(PDDLDIR, problem_dir, problem_outfile)\n', (5882, 5921), False, 'import os\n'), ((5927, 6118), 'pddlgym.parser.PDDLProblemParser.create_pddl_file', 'PDDLProblemParser.create_pddl_file', (['filepath'], {'objects': 'objects', 'initial_state': 'initial_state', 'problem_name': '"""hiking"""', 'domain_name': 'domain.domain_name', 'goal': 'goal', 'fast_downward_order': '(True)'}), "(filepath, objects=objects, initial_state\n =initial_state, problem_name='hiking', domain_name=domain.domain_name,\n goal=goal, fast_downward_order=True)\n", (5961, 6118), False, 'from pddlgym.parser import PDDLDomainParser, PDDLProblemParser\n'), ((5114, 5136), 'numpy.argwhere', 'np.argwhere', (['(grid == I)'], {}), '(grid == I)\n', (5125, 5136), True, 'import numpy as np\n'), ((6276, 6312), 'os.path.join', 'os.path.join', (['PDDLDIR', '"""hiking.pddl"""'], {}), "(PDDLDIR, 'hiking.pddl')\n", (6288, 6312), False, 'import os\n')] |
import numpy as np
import cv2 as cv
from imutils.video import WebcamVideoStream
import glob
import time
import math
class PoseEstimation():
def __init__(self, mtx, dist):
self.mtx = mtx
self.dist = dist
def detect_contourn(self, image, color):
hsv = cv.cvtColor(image, cv.COLOR_BGR2HSV)
if color == "Red":
#Define the limits in HSV variables
self.lower = np.array([0, 35, 225])
self.upper = np.array([0, 255, 255])
if color == "Green":
#Define the limits in HSV variables
self.lower = np.array([48, 35, 225])
self.upper = np.array([65, 255, 255])
if color == "Blue":
#Define the limits in HSV variables
self.lower = np.array([70, 35, 225])
self.upper = np.array([120, 255, 255])
if color == "Yellow":
#Define the limits in HSV variables
self.lower = np.array([20, 100, 100])
self.upper = np.array([32, 220, 255])
#Define threshold for red color
mask = cv.inRange(hsv, self.lower, self.upper)
#Create a kernel
kernel = np.ones((5,5), np.uint8)
#Apply opening process
opening = cv.morphologyEx(mask, cv.MORPH_OPEN, kernel, iterations = 1)
#Find BLOB's contours
cnts, _ = cv.findContours(opening.copy(), cv.RETR_EXTERNAL,cv.CHAIN_APPROX_SIMPLE)
return cnts
def center_mass_calculate(self, image, c):
# Compute the center of the contour
M = cv.moments(c)
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])
_, radius = cv.minEnclosingCircle(c)
cX = int(cX)
cY = int(cY)
center = (cX, cY)
radius = int(radius)
perimeter = cv.arcLength(c, True)
#Compute the eccentricity
metric = (4*math.pi*M["m00"])/perimeter**2
if metric > 0.8:
#Draw the contour and center of the shape on the image
cv.drawContours(image, [c], -1, (0, 0, 0), 1)
# cv.circle(image, center, radius, (0, 0, 0),1)
cv.circle(image, center, 1, (0, 0, 0), -1)
# cv.circle(image, (cX+radius, cY), 1, (0, 0, 0), 2)
# cv.circle(image, (cX-radius, cY), 1, (0, 0, 0), 2)
# cv.circle(image, (cX, cY+radius), 1, (0, 0, 0), 2)
# cv.circle(image, (cX, cY-radius), 1, (0, 0, 0), 2)
return cX, cY, radius
def draw(self, image, imgpoints, imgpts):
imgpoint = tuple(imgpoints[0].ravel())
img = cv.line(image, imgpoint, tuple(imgpts[0].ravel()), (255,0,0), 3)
img = cv.line(image, imgpoint, tuple(imgpts[1].ravel()), (0,255,0), 3)
img = cv.line(image, imgpoint, tuple(imgpts[2].ravel()), (0,255,255), 3)
return img
def get_element_vector(self, f1, f2, c1, c2):
#Where f1 is frameA, f2 is frameB
#c1 is the coordinate, let x = 0, y = 1, z = 2
vec = []
for i in range(np.shape(f1)[0]):
cc = f2[i, c1]*f1[i, c2]
vec.append(cc)
return np.sum(vec)
def get_element_A(self, f1, c1, c2):
A = []
for i in range(np.shape(f1)[0]):
cc = f1[i, c1]*f1[i, c2]
A.append(cc)
return np.sum(A)
def get_element_last(self, f1, c1):
last = []
for i in range(np.shape(f1)[0]):
cc = f1[i, c1]
last.append(cc)
return np.sum(last)
def get_transform_frame(self, f1, f2):
matrix = np.zeros((3,4))
for i in range(3):
for j in range(3):
matrix[i, j] = self.get_element_vector(f1, f2, i, j)
matrix[i, 3] = self.get_element_last(f2, i)
A = np.zeros((4,4))
for i in range(3):
for j in range(3):
A[i, j] = self.get_element_A(f1, i, j)
for i in range(3):
A[i,3] = self.get_element_last(f1, i)
A[3, i] = self.get_element_last(f1, i)
A[3,3] = np.shape(f1)[0]
A_inv = np.linalg.inv(A)
matrix = np.transpose(matrix)
T = np.dot(A_inv, matrix)
T = np.transpose(T)
last_row = np.array([0,0,0,1]).reshape(1,4)
T = np.concatenate((T, last_row), axis=0)
return T
def get_pose(self, image, objpoints, imgpoints, mtx, dist):
axis = np.float32([[1, 0, 0], [0, 1, 0], [0, 0, 1]]).reshape(-1,3)
# Find the rotation and translation vectors.
_, rvecs, tvecs,_ = cv.solvePnPRansac(objpoints, imgpoints, mtx, dist, iterationsCount=5)
# project 3D points to image plane
imgpts, jac = cv.projectPoints(axis, rvecs, tvecs, mtx, dist)
imgpts = imgpts.astype(np.int)
img = self.draw(image, imgpoints, imgpts)
R_matrix, _ = cv.Rodrigues(rvecs)
return rvecs, tvecs, R_matrix, image | [
"cv2.projectPoints",
"numpy.array",
"cv2.arcLength",
"cv2.solvePnPRansac",
"numpy.dot",
"numpy.concatenate",
"cv2.drawContours",
"numpy.ones",
"cv2.minEnclosingCircle",
"cv2.morphologyEx",
"cv2.circle",
"cv2.cvtColor",
"cv2.moments",
"numpy.shape",
"numpy.transpose",
"cv2.inRange",
"... | [((296, 332), 'cv2.cvtColor', 'cv.cvtColor', (['image', 'cv.COLOR_BGR2HSV'], {}), '(image, cv.COLOR_BGR2HSV)\n', (307, 332), True, 'import cv2 as cv\n'), ((1092, 1131), 'cv2.inRange', 'cv.inRange', (['hsv', 'self.lower', 'self.upper'], {}), '(hsv, self.lower, self.upper)\n', (1102, 1131), True, 'import cv2 as cv\n'), ((1174, 1199), 'numpy.ones', 'np.ones', (['(5, 5)', 'np.uint8'], {}), '((5, 5), np.uint8)\n', (1181, 1199), True, 'import numpy as np\n'), ((1248, 1306), 'cv2.morphologyEx', 'cv.morphologyEx', (['mask', 'cv.MORPH_OPEN', 'kernel'], {'iterations': '(1)'}), '(mask, cv.MORPH_OPEN, kernel, iterations=1)\n', (1263, 1306), True, 'import cv2 as cv\n'), ((1557, 1570), 'cv2.moments', 'cv.moments', (['c'], {}), '(c)\n', (1567, 1570), True, 'import cv2 as cv\n'), ((1668, 1692), 'cv2.minEnclosingCircle', 'cv.minEnclosingCircle', (['c'], {}), '(c)\n', (1689, 1692), True, 'import cv2 as cv\n'), ((1810, 1831), 'cv2.arcLength', 'cv.arcLength', (['c', '(True)'], {}), '(c, True)\n', (1822, 1831), True, 'import cv2 as cv\n'), ((3140, 3151), 'numpy.sum', 'np.sum', (['vec'], {}), '(vec)\n', (3146, 3151), True, 'import numpy as np\n'), ((3327, 3336), 'numpy.sum', 'np.sum', (['A'], {}), '(A)\n', (3333, 3336), True, 'import numpy as np\n'), ((3507, 3519), 'numpy.sum', 'np.sum', (['last'], {}), '(last)\n', (3513, 3519), True, 'import numpy as np\n'), ((3581, 3597), 'numpy.zeros', 'np.zeros', (['(3, 4)'], {}), '((3, 4))\n', (3589, 3597), True, 'import numpy as np\n'), ((3797, 3813), 'numpy.zeros', 'np.zeros', (['(4, 4)'], {}), '((4, 4))\n', (3805, 3813), True, 'import numpy as np\n'), ((4105, 4121), 'numpy.linalg.inv', 'np.linalg.inv', (['A'], {}), '(A)\n', (4118, 4121), True, 'import numpy as np\n'), ((4140, 4160), 'numpy.transpose', 'np.transpose', (['matrix'], {}), '(matrix)\n', (4152, 4160), True, 'import numpy as np\n'), ((4174, 4195), 'numpy.dot', 'np.dot', (['A_inv', 'matrix'], {}), '(A_inv, matrix)\n', (4180, 4195), True, 'import numpy as np\n'), ((4208, 4223), 'numpy.transpose', 'np.transpose', (['T'], {}), '(T)\n', (4220, 4223), True, 'import numpy as np\n'), ((4288, 4325), 'numpy.concatenate', 'np.concatenate', (['(T, last_row)'], {'axis': '(0)'}), '((T, last_row), axis=0)\n', (4302, 4325), True, 'import numpy as np\n'), ((4583, 4652), 'cv2.solvePnPRansac', 'cv.solvePnPRansac', (['objpoints', 'imgpoints', 'mtx', 'dist'], {'iterationsCount': '(5)'}), '(objpoints, imgpoints, mtx, dist, iterationsCount=5)\n', (4600, 4652), True, 'import cv2 as cv\n'), ((4718, 4765), 'cv2.projectPoints', 'cv.projectPoints', (['axis', 'rvecs', 'tvecs', 'mtx', 'dist'], {}), '(axis, rvecs, tvecs, mtx, dist)\n', (4734, 4765), True, 'import cv2 as cv\n'), ((4877, 4896), 'cv2.Rodrigues', 'cv.Rodrigues', (['rvecs'], {}), '(rvecs)\n', (4889, 4896), True, 'import cv2 as cv\n'), ((434, 456), 'numpy.array', 'np.array', (['[0, 35, 225]'], {}), '([0, 35, 225])\n', (442, 456), True, 'import numpy as np\n'), ((482, 505), 'numpy.array', 'np.array', (['[0, 255, 255]'], {}), '([0, 255, 255])\n', (490, 505), True, 'import numpy as np\n'), ((608, 631), 'numpy.array', 'np.array', (['[48, 35, 225]'], {}), '([48, 35, 225])\n', (616, 631), True, 'import numpy as np\n'), ((657, 681), 'numpy.array', 'np.array', (['[65, 255, 255]'], {}), '([65, 255, 255])\n', (665, 681), True, 'import numpy as np\n'), ((783, 806), 'numpy.array', 'np.array', (['[70, 35, 225]'], {}), '([70, 35, 225])\n', (791, 806), True, 'import numpy as np\n'), ((832, 857), 'numpy.array', 'np.array', (['[120, 255, 255]'], {}), '([120, 255, 255])\n', (840, 857), True, 'import numpy as np\n'), ((961, 985), 'numpy.array', 'np.array', (['[20, 100, 100]'], {}), '([20, 100, 100])\n', (969, 985), True, 'import numpy as np\n'), ((1011, 1035), 'numpy.array', 'np.array', (['[32, 220, 255]'], {}), '([32, 220, 255])\n', (1019, 1035), True, 'import numpy as np\n'), ((2021, 2066), 'cv2.drawContours', 'cv.drawContours', (['image', '[c]', '(-1)', '(0, 0, 0)', '(1)'], {}), '(image, [c], -1, (0, 0, 0), 1)\n', (2036, 2066), True, 'import cv2 as cv\n'), ((2139, 2181), 'cv2.circle', 'cv.circle', (['image', 'center', '(1)', '(0, 0, 0)', '(-1)'], {}), '(image, center, 1, (0, 0, 0), -1)\n', (2148, 2181), True, 'import cv2 as cv\n'), ((4073, 4085), 'numpy.shape', 'np.shape', (['f1'], {}), '(f1)\n', (4081, 4085), True, 'import numpy as np\n'), ((3043, 3055), 'numpy.shape', 'np.shape', (['f1'], {}), '(f1)\n', (3051, 3055), True, 'import numpy as np\n'), ((3232, 3244), 'numpy.shape', 'np.shape', (['f1'], {}), '(f1)\n', (3240, 3244), True, 'import numpy as np\n'), ((3419, 3431), 'numpy.shape', 'np.shape', (['f1'], {}), '(f1)\n', (3427, 3431), True, 'import numpy as np\n'), ((4243, 4265), 'numpy.array', 'np.array', (['[0, 0, 0, 1]'], {}), '([0, 0, 0, 1])\n', (4251, 4265), True, 'import numpy as np\n'), ((4441, 4486), 'numpy.float32', 'np.float32', (['[[1, 0, 0], [0, 1, 0], [0, 0, 1]]'], {}), '([[1, 0, 0], [0, 1, 0], [0, 0, 1]])\n', (4451, 4486), True, 'import numpy as np\n')] |
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/core.ipynb (unless otherwise specified).
__all__ = ['StatsForecast']
# Cell
import inspect
import logging
from functools import partial
from os import cpu_count
import numpy as np
import pandas as pd
# Internal Cell
logging.basicConfig(
format='%(asctime)s %(name)s %(levelname)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
)
logger = logging.getLogger(__name__)
# Internal Cell
class GroupedArray:
def __init__(self, data, indptr):
self.data = data
self.indptr = indptr
self.n_groups = self.indptr.size - 1
def __getitem__(self, idx):
if isinstance(idx, int):
return self.data[self.indptr[idx] : self.indptr[idx + 1]]
elif isinstance(idx, slice):
idx = slice(idx.start, idx.stop + 1, idx.step)
new_indptr = self.indptr[idx].copy()
new_data = self.data[new_indptr[0] : new_indptr[-1]].copy()
new_indptr -= new_indptr[0]
return GroupedArray(new_data, new_indptr)
raise ValueError(f'idx must be either int or slice, got {type(idx)}')
def __len__(self):
return self.n_groups
def __repr__(self):
return f'GroupedArray(n_data={self.data.size:,}, n_groups={self.n_groups:,})'
def __eq__(self, other):
if not hasattr(other, 'data') or not hasattr(other, 'indptr'):
return False
return np.allclose(self.data, other.data) and np.array_equal(self.indptr, other.indptr)
def compute_forecasts(self, h, func, xreg=None, level=None, *args):
has_level = 'level' in inspect.signature(func).parameters and level is not None
if has_level:
out = np.full((h * self.n_groups, 2 * len(level) + 1), np.nan, dtype=np.float32)
func = partial(func, level=level)
else:
out = np.full(h * self.n_groups, np.nan, dtype=np.float32)
xr = None
keys = None
for i, grp in enumerate(self):
if xreg is not None:
xr = xreg[i]
res = func(grp, h, xr, *args)
if has_level:
if keys is None:
keys = list(res.keys())
for j, key in enumerate(keys):
out[h * i : h * (i + 1), j] = res[key]
else:
out[h * i : h * (i + 1)] = res
return out, keys
def split(self, n_chunks):
return [self[x[0] : x[-1] + 1] for x in np.array_split(range(self.n_groups), n_chunks) if x.size]
# Internal Cell
def _grouped_array_from_df(df):
df = df.set_index('ds', append=True)
if not df.index.is_monotonic_increasing:
df = df.sort_index()
data = df.values.astype(np.float32)
indices_sizes = df.index.get_level_values('unique_id').value_counts(sort=False)
indices = indices_sizes.index
sizes = indices_sizes.values
cum_sizes = sizes.cumsum()
dates = df.index.get_level_values('ds')[cum_sizes - 1]
indptr = np.append(0, cum_sizes).astype(np.int32)
return GroupedArray(data, indptr), indices, dates
# Internal Cell
def _build_forecast_name(model, *args) -> str:
model_name = f'{model.__name__}'
func_params = inspect.signature(model).parameters
func_args = list(func_params.items())[3:] # remove input array, horizon and xreg
changed_params = [
f'{name}-{value}'
for value, (name, arg) in zip(args, func_args)
if arg.default != value
]
if changed_params:
model_name += '_' + '_'.join(changed_params)
return model_name
# Internal Cell
def _as_tuple(x):
if isinstance(x, tuple):
return x
return (x,)
# Internal Cell
def _get_n_jobs(n_groups, n_jobs, ray_address):
if ray_address is not None:
logger.info(
'Using ray address,'
'using available resources insted of `n_jobs`'
)
try:
import ray
except ModuleNotFoundError as e:
msg = (
'{e}. To use a ray cluster you have to install '
'ray. Please run `pip install ray`. '
)
raise ModuleNotFoundError(msg) from e
if not ray.is_initialized():
ray.init(ray_address, ignore_reinit_error=True)
actual_n_jobs = int(ray.available_resources()['CPU'])
else:
if n_jobs == -1 or (n_jobs is None):
actual_n_jobs = cpu_count()
else:
actual_n_jobs = n_jobs
return min(n_groups, actual_n_jobs)
# Cell
class StatsForecast:
def __init__(self, df, models, freq, n_jobs=1, ray_address=None):
self.ga, self.uids, self.last_dates = _grouped_array_from_df(df)
self.models = models
self.freq = pd.tseries.frequencies.to_offset(freq)
self.n_jobs = _get_n_jobs(len(self.ga), n_jobs, ray_address)
self.ray_address = ray_address
def forecast(self, h, xreg=None, level=None):
if xreg is not None:
expected_shape = (h * len(self.ga), self.ga.data.shape[1])
if xreg.shape != expected_shape:
raise ValueError(f'Expected xreg to have shape {expected_shape}, but got {xreg.shape}')
xreg, _, _ = _grouped_array_from_df(xreg)
if self.n_jobs == 1:
fcsts = self._sequential_forecast(h, xreg, level)
else:
fcsts = self._data_parallel_forecast(h, xreg, level)
if issubclass(self.last_dates.dtype.type, np.integer):
last_date_f = lambda x: np.arange(x + 1, x + 1 + h, dtype=self.last_dates.dtype)
else:
last_date_f = lambda x: pd.date_range(x + self.freq, periods=h, freq=self.freq)
if len(np.unique(self.last_dates)) == 1:
dates = np.tile(last_date_f(self.last_dates[0]), len(self.ga))
else:
dates = np.hstack([
last_date_f(last_date)
for last_date in self.last_dates
])
idx = pd.Index(np.repeat(self.uids, h), name='unique_id')
return pd.DataFrame({'ds': dates, **fcsts}, index=idx)
def _sequential_forecast(self, h, xreg, level):
fcsts = {}
logger.info('Computing forecasts')
for model_args in self.models:
model, *args = _as_tuple(model_args)
model_name = _build_forecast_name(model, *args)
values, keys = self.ga.compute_forecasts(h, model, xreg, level, *args)
if keys is not None:
for j, key in enumerate(keys):
fcsts[f'{model_name}_{key}'] = values[:, j]
else:
fcsts[model_name] = values
logger.info(f'Computed forecasts for {model_name}.')
return fcsts
def _data_parallel_forecast(self, h, xreg, level):
fcsts = {}
logger.info('Computing forecasts')
gas = self.ga.split(self.n_jobs)
if xreg is not None:
xregs = xreg.split(self.n_jobs)
else:
from itertools import repeat
xregs = repeat(None)
if self.ray_address is not None:
try:
from ray.util.multiprocessing import Pool
except ModuleNotFoundError as e:
msg = (
f'{e}. To use a ray cluster you have to install '
'ray. Please run `pip install ray`. '
)
raise ModuleNotFoundError(msg) from e
kwargs = dict(ray_address=self.ray_address)
else:
from multiprocessing import Pool
kwargs = dict()
with Pool(self.n_jobs, **kwargs) as executor:
for model_args in self.models:
model, *args = _as_tuple(model_args)
model_name = _build_forecast_name(model, *args)
futures = []
for ga, xr in zip(gas, xregs):
future = executor.apply_async(ga.compute_forecasts, (h, model, xr, level, *args,))
futures.append(future)
values, keys = list(zip(*[f.get() for f in futures]))
keys = keys[0]
if keys is not None:
values = np.vstack(values)
for j, key in enumerate(keys):
fcsts[f'{model_name}_{key}'] = values[:, j]
else:
values = np.hstack(values)
fcsts[model_name] = values
logger.info(f'Computed forecasts for {model_name}.')
return fcsts | [
"logging.getLogger",
"numpy.hstack",
"ray.is_initialized",
"inspect.signature",
"os.cpu_count",
"ray.util.multiprocessing.Pool",
"ray.available_resources",
"ray.init",
"pandas.date_range",
"numpy.arange",
"itertools.repeat",
"numpy.repeat",
"numpy.vstack",
"pandas.DataFrame",
"numpy.allc... | [((268, 384), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)s %(name)s %(levelname)s: %(message)s"""', 'datefmt': '"""%Y-%m-%d %H:%M:%S"""'}), "(format=\n '%(asctime)s %(name)s %(levelname)s: %(message)s', datefmt=\n '%Y-%m-%d %H:%M:%S')\n", (287, 384), False, 'import logging\n'), ((395, 422), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (412, 422), False, 'import logging\n'), ((3206, 3230), 'inspect.signature', 'inspect.signature', (['model'], {}), '(model)\n', (3223, 3230), False, 'import inspect\n'), ((4730, 4768), 'pandas.tseries.frequencies.to_offset', 'pd.tseries.frequencies.to_offset', (['freq'], {}), '(freq)\n', (4762, 4768), True, 'import pandas as pd\n'), ((6017, 6064), 'pandas.DataFrame', 'pd.DataFrame', (["{'ds': dates, **fcsts}"], {'index': 'idx'}), "({'ds': dates, **fcsts}, index=idx)\n", (6029, 6064), True, 'import pandas as pd\n'), ((1428, 1462), 'numpy.allclose', 'np.allclose', (['self.data', 'other.data'], {}), '(self.data, other.data)\n', (1439, 1462), True, 'import numpy as np\n'), ((1467, 1508), 'numpy.array_equal', 'np.array_equal', (['self.indptr', 'other.indptr'], {}), '(self.indptr, other.indptr)\n', (1481, 1508), True, 'import numpy as np\n'), ((1804, 1830), 'functools.partial', 'partial', (['func'], {'level': 'level'}), '(func, level=level)\n', (1811, 1830), False, 'from functools import partial\n'), ((1863, 1915), 'numpy.full', 'np.full', (['(h * self.n_groups)', 'np.nan'], {'dtype': 'np.float32'}), '(h * self.n_groups, np.nan, dtype=np.float32)\n', (1870, 1915), True, 'import numpy as np\n'), ((2992, 3015), 'numpy.append', 'np.append', (['(0)', 'cum_sizes'], {}), '(0, cum_sizes)\n', (3001, 3015), True, 'import numpy as np\n'), ((4180, 4200), 'ray.is_initialized', 'ray.is_initialized', ([], {}), '()\n', (4198, 4200), False, 'import ray\n'), ((4214, 4261), 'ray.init', 'ray.init', (['ray_address'], {'ignore_reinit_error': '(True)'}), '(ray_address, ignore_reinit_error=True)\n', (4222, 4261), False, 'import ray\n'), ((4407, 4418), 'os.cpu_count', 'cpu_count', ([], {}), '()\n', (4416, 4418), False, 'from os import cpu_count\n'), ((5959, 5982), 'numpy.repeat', 'np.repeat', (['self.uids', 'h'], {}), '(self.uids, h)\n', (5968, 5982), True, 'import numpy as np\n'), ((7010, 7022), 'itertools.repeat', 'repeat', (['None'], {}), '(None)\n', (7016, 7022), False, 'from itertools import repeat\n'), ((7566, 7593), 'ray.util.multiprocessing.Pool', 'Pool', (['self.n_jobs'], {}), '(self.n_jobs, **kwargs)\n', (7570, 7593), False, 'from ray.util.multiprocessing import Pool\n'), ((4290, 4315), 'ray.available_resources', 'ray.available_resources', ([], {}), '()\n', (4313, 4315), False, 'import ray\n'), ((5500, 5556), 'numpy.arange', 'np.arange', (['(x + 1)', '(x + 1 + h)'], {'dtype': 'self.last_dates.dtype'}), '(x + 1, x + 1 + h, dtype=self.last_dates.dtype)\n', (5509, 5556), True, 'import numpy as np\n'), ((5607, 5662), 'pandas.date_range', 'pd.date_range', (['(x + self.freq)'], {'periods': 'h', 'freq': 'self.freq'}), '(x + self.freq, periods=h, freq=self.freq)\n', (5620, 5662), True, 'import pandas as pd\n'), ((5678, 5704), 'numpy.unique', 'np.unique', (['self.last_dates'], {}), '(self.last_dates)\n', (5687, 5704), True, 'import numpy as np\n'), ((1613, 1636), 'inspect.signature', 'inspect.signature', (['func'], {}), '(func)\n', (1630, 1636), False, 'import inspect\n'), ((8156, 8173), 'numpy.vstack', 'np.vstack', (['values'], {}), '(values)\n', (8165, 8173), True, 'import numpy as np\n'), ((8344, 8361), 'numpy.hstack', 'np.hstack', (['values'], {}), '(values)\n', (8353, 8361), True, 'import numpy as np\n')] |
import unittest
import numpy as np
import torch
from pyscf import gto
from torch.autograd import Variable, grad, gradcheck
from qmctorch.scf import Molecule
from qmctorch.wavefunction import SlaterJastrow
torch.set_default_tensor_type(torch.DoubleTensor)
def hess(out, pos):
# compute the jacobian
z = Variable(torch.ones(out.shape))
jacob = grad(out, pos,
grad_outputs=z,
only_inputs=True,
create_graph=True)[0]
# compute the diagonal element of the Hessian
z = Variable(torch.ones(jacob.shape[0]))
hess = torch.zeros(jacob.shape)
for idim in range(jacob.shape[1]):
tmp = grad(jacob[:, idim], pos,
grad_outputs=z,
only_inputs=True,
create_graph=True)[0]
hess[:, idim] = tmp[:, idim]
return hess
def hess_mixed_terms(out, pos):
# compute the jacobian
z = Variable(torch.ones(out.shape))
jacob = grad(out, pos,
grad_outputs=z,
only_inputs=True,
create_graph=True)[0]
# compute the diagonal element of the Hessian
z = Variable(torch.ones(jacob.shape[0]))
hess = torch.zeros(jacob.shape)
nelec = pos.shape[1]//3
k = 0
for ielec in range(nelec):
ix = ielec*3
tmp = grad(jacob[:, ix], pos,
grad_outputs=z,
only_inputs=True,
create_graph=True)[0]
hess[:, k] = tmp[:, ix+1]
k = k + 1
hess[:, k] = tmp[:, ix+2]
k = k + 1
iy = ielec*3 + 1
tmp = grad(jacob[:, iy], pos,
grad_outputs=z,
only_inputs=True,
create_graph=True)[0]
hess[:, k] = tmp[:, iy+1]
k = k + 1
return hess
class TestAOderivativesPyscf(unittest.TestCase):
def setUp(self):
torch.manual_seed(101)
np.random.seed(101)
# define the molecule
at = 'Li 0 0 0; H 0 0 1'
basis = 'dzp'
self.mol = Molecule(atom=at,
calculator='pyscf',
basis=basis,
unit='bohr')
self.m = gto.M(atom=at, basis=basis, unit='bohr')
# define the wave function
self.wf = SlaterJastrow(self.mol, include_all_mo=True)
# define the grid points
npts = 11
self.pos = torch.rand(npts, self.mol.nelec * 3)
self.pos = Variable(self.pos)
self.pos.requires_grad = True
def test_ao_deriv(self):
ao = self.wf.ao(self.pos)
dao = self.wf.ao(self.pos, derivative=1)
dao_grad = grad(
ao, self.pos, grad_outputs=torch.ones_like(ao))[0]
gradcheck(self.wf.ao, self.pos)
assert(torch.allclose(dao.sum(), dao_grad.sum()))
def test_ao_grad_sum(self):
ao = self.wf.ao(self.pos)
dao_sum = self.wf.ao(self.pos, derivative=1, sum_grad=True)
dao = self.wf.ao(self.pos, derivative=1, sum_grad=False)
assert(torch.allclose(dao_sum, dao.sum(-1)))
def test_ao_hess(self):
ao = self.wf.ao(self.pos)
d2ao = self.wf.ao(self.pos, derivative=2)
d2ao_grad = hess(ao, self.pos)
assert(torch.allclose(d2ao.sum(), d2ao_grad.sum()))
def test_ao_hess_sum(self):
ao = self.wf.ao(self.pos)
d2ao_sum = self.wf.ao(self.pos, derivative=2, sum_hess=True)
d2ao = self.wf.ao(self.pos, derivative=2, sum_hess=False)
assert(torch.allclose(d2ao_sum, d2ao.sum(-1)))
def test_ao_mixed_der(self):
ao = self.wf.ao(self.pos)
d2ao = self.wf.ao(self.pos, derivative=3)
d2ao_auto = hess_mixed_terms(ao, self.pos)
assert(torch.allclose(d2ao.sum(), d2ao_auto.sum()))
def test_ao_all(self):
ao = self.wf.ao(self.pos)
dao = self.wf.ao(self.pos, derivative=1, sum_grad=False)
d2ao = self.wf.ao(self.pos, derivative=2)
ao_all, dao_all, d2ao_all = self.wf.ao(
self.pos, derivative=[0, 1, 2])
assert(torch.allclose(ao, ao_all))
assert(torch.allclose(dao, dao_all))
assert(torch.allclose(d2ao, d2ao_all))
if __name__ == "__main__":
# unittest.main()
t = TestAOderivativesPyscf()
t.setUp()
t.test_ao_mixed_der()
# t.test_ao_all()
# t.test_ao_deriv()
# t.test_ao_hess()
| [
"qmctorch.scf.Molecule",
"torch.manual_seed",
"torch.ones_like",
"pyscf.gto.M",
"torch.set_default_tensor_type",
"torch.autograd.grad",
"numpy.random.seed",
"qmctorch.wavefunction.SlaterJastrow",
"torch.allclose",
"torch.autograd.Variable",
"torch.autograd.gradcheck",
"torch.zeros",
"torch.r... | [((207, 256), 'torch.set_default_tensor_type', 'torch.set_default_tensor_type', (['torch.DoubleTensor'], {}), '(torch.DoubleTensor)\n', (236, 256), False, 'import torch\n'), ((587, 611), 'torch.zeros', 'torch.zeros', (['jacob.shape'], {}), '(jacob.shape)\n', (598, 611), False, 'import torch\n'), ((1204, 1228), 'torch.zeros', 'torch.zeros', (['jacob.shape'], {}), '(jacob.shape)\n', (1215, 1228), False, 'import torch\n'), ((323, 344), 'torch.ones', 'torch.ones', (['out.shape'], {}), '(out.shape)\n', (333, 344), False, 'import torch\n'), ((358, 425), 'torch.autograd.grad', 'grad', (['out', 'pos'], {'grad_outputs': 'z', 'only_inputs': '(True)', 'create_graph': '(True)'}), '(out, pos, grad_outputs=z, only_inputs=True, create_graph=True)\n', (362, 425), False, 'from torch.autograd import Variable, grad, gradcheck\n'), ((548, 574), 'torch.ones', 'torch.ones', (['jacob.shape[0]'], {}), '(jacob.shape[0])\n', (558, 574), False, 'import torch\n'), ((940, 961), 'torch.ones', 'torch.ones', (['out.shape'], {}), '(out.shape)\n', (950, 961), False, 'import torch\n'), ((975, 1042), 'torch.autograd.grad', 'grad', (['out', 'pos'], {'grad_outputs': 'z', 'only_inputs': '(True)', 'create_graph': '(True)'}), '(out, pos, grad_outputs=z, only_inputs=True, create_graph=True)\n', (979, 1042), False, 'from torch.autograd import Variable, grad, gradcheck\n'), ((1165, 1191), 'torch.ones', 'torch.ones', (['jacob.shape[0]'], {}), '(jacob.shape[0])\n', (1175, 1191), False, 'import torch\n'), ((1906, 1928), 'torch.manual_seed', 'torch.manual_seed', (['(101)'], {}), '(101)\n', (1923, 1928), False, 'import torch\n'), ((1937, 1956), 'numpy.random.seed', 'np.random.seed', (['(101)'], {}), '(101)\n', (1951, 1956), True, 'import numpy as np\n'), ((2062, 2125), 'qmctorch.scf.Molecule', 'Molecule', ([], {'atom': 'at', 'calculator': '"""pyscf"""', 'basis': 'basis', 'unit': '"""bohr"""'}), "(atom=at, calculator='pyscf', basis=basis, unit='bohr')\n", (2070, 2125), False, 'from qmctorch.scf import Molecule\n'), ((2228, 2268), 'pyscf.gto.M', 'gto.M', ([], {'atom': 'at', 'basis': 'basis', 'unit': '"""bohr"""'}), "(atom=at, basis=basis, unit='bohr')\n", (2233, 2268), False, 'from pyscf import gto\n'), ((2323, 2367), 'qmctorch.wavefunction.SlaterJastrow', 'SlaterJastrow', (['self.mol'], {'include_all_mo': '(True)'}), '(self.mol, include_all_mo=True)\n', (2336, 2367), False, 'from qmctorch.wavefunction import SlaterJastrow\n'), ((2439, 2475), 'torch.rand', 'torch.rand', (['npts', '(self.mol.nelec * 3)'], {}), '(npts, self.mol.nelec * 3)\n', (2449, 2475), False, 'import torch\n'), ((2495, 2513), 'torch.autograd.Variable', 'Variable', (['self.pos'], {}), '(self.pos)\n', (2503, 2513), False, 'from torch.autograd import Variable, grad, gradcheck\n'), ((2764, 2795), 'torch.autograd.gradcheck', 'gradcheck', (['self.wf.ao', 'self.pos'], {}), '(self.wf.ao, self.pos)\n', (2773, 2795), False, 'from torch.autograd import Variable, grad, gradcheck\n'), ((4095, 4121), 'torch.allclose', 'torch.allclose', (['ao', 'ao_all'], {}), '(ao, ao_all)\n', (4109, 4121), False, 'import torch\n'), ((4138, 4166), 'torch.allclose', 'torch.allclose', (['dao', 'dao_all'], {}), '(dao, dao_all)\n', (4152, 4166), False, 'import torch\n'), ((4183, 4213), 'torch.allclose', 'torch.allclose', (['d2ao', 'd2ao_all'], {}), '(d2ao, d2ao_all)\n', (4197, 4213), False, 'import torch\n'), ((667, 745), 'torch.autograd.grad', 'grad', (['jacob[:, idim]', 'pos'], {'grad_outputs': 'z', 'only_inputs': '(True)', 'create_graph': '(True)'}), '(jacob[:, idim], pos, grad_outputs=z, only_inputs=True, create_graph=True)\n', (671, 745), False, 'from torch.autograd import Variable, grad, gradcheck\n'), ((1335, 1411), 'torch.autograd.grad', 'grad', (['jacob[:, ix]', 'pos'], {'grad_outputs': 'z', 'only_inputs': '(True)', 'create_graph': '(True)'}), '(jacob[:, ix], pos, grad_outputs=z, only_inputs=True, create_graph=True)\n', (1339, 1411), False, 'from torch.autograd import Variable, grad, gradcheck\n'), ((1617, 1693), 'torch.autograd.grad', 'grad', (['jacob[:, iy]', 'pos'], {'grad_outputs': 'z', 'only_inputs': '(True)', 'create_graph': '(True)'}), '(jacob[:, iy], pos, grad_outputs=z, only_inputs=True, create_graph=True)\n', (1621, 1693), False, 'from torch.autograd import Variable, grad, gradcheck\n'), ((2731, 2750), 'torch.ones_like', 'torch.ones_like', (['ao'], {}), '(ao)\n', (2746, 2750), False, 'import torch\n')] |
#Utility file of functions and imports
#Doles, Nix, Terlecky
#File includes standard imports and defined functions used in multiple project files
#
#
import random
import itertools
import numpy as np
import pandas as pd
import numpy as np
import glob
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC
from sklearn.neural_network import MLPClassifier
from sklearn.externals import joblib
#model file names
m = './mlp.pkl'
s = './svc.pkl'
#couldn't find an acceptable non-overfit rf model
#rf = './rf.pkl'
#Define coordinate system for the number pad
#With coords defined as dictionary of digit : position
num_pos=[[0,3],[1,3],[2,3],[0,2],[1,2],[2,2],[0,1],[1,1],[2,1],[1,0]]
nums = [1,2,3,4,5,6,7,8,9,0]
coords = {}
for i in range(len(nums)):
coords[nums[i]] = num_pos[i]
def distance(start,finish):
'''
Returns delta_x, delta_y given starting and ending coords
'''
dist_x=finish[0]-start[0]
dist_y=finish[1]-start[1]
return(dist_x,dist_y)
def pseudo_data(trans):
'''
returns simulated accelerometer data for a single transition with noise
usage: trans is manhattan distance btwm numbers in keypad as returned by distance()
'''
def noise():
return random.random()*.1
test = []
for i in range(12):
test.append([trans[0]*.3+noise(),trans[1]*.3+noise()])
return test
def make_label_map():
label_map = {}
loop_count = 0
for i in range(10):
for j in range(10):
label_map[loop_count] = [i,j]
loop_count+=1
return label_map
def predictKnownPin(pin):
'''
Generates realistic data with random noise for a given pin, then predicts
possible pin numbers from the generated data.
Returns list of pin numbers and list of associated probabilities
'''
label_map = make_label_map()
#pin number translated into number-number sequences
seq = []
for i in range(len(pin)-1):
seq.append([pin[i],pin[i+1]])
#generate pseudo-data for pin number
acc_data = []
for s in seq:
acc_data.append(pseudo_data(distance(coords[s[0]],coords[s[1]])))
acc_data=np.array(acc_data).reshape(3,24)
#Useful to see data, leave commented out otherwise
#print(acc_data)
#Print svc predictions first... they are garbage
print('Support Vector Predictions : ')
svc_pred_ind = predictSVC(acc_data)
svc_pred = [label_map[i[0]] for i in svc_pred_ind]
print(svc_pred)
#import trained mlp
mlp = joblib.load(m)
#get probabilities from predicting on data from above
probs = mlp.predict_proba(acc_data)
#build list of possible pin numbers from probabilities
possible = []
prob_list = []
#loop over each transition
for i in range(len(probs)):
#Get top probabilites and corresponding numbers
poss = [label_map[n] for n in np.argpartition(probs[i], -10)[-10:]]
poss_probs = [probs[i][n] for n in np.argpartition(probs[i], -10)[-10:]]
possible.append(poss)
prob_list.append(poss_probs)
#chain transitions based on sequence of digits (if first.last == next.first then chain and keep, otherwise drop)
colapse_first = []
prob_sum_first = []
for i in range(len(possible[0])):
for j in range(len(possible[1])):
if (possible[0][i][1] == possible[1][j][0]):
l1 = possible[0][i]
l2 = possible[1][j]
colapse_first.append([l1[0],l2[0],l2[1]])
prob_sum_first.append(prob_list[0][i] * prob_list[1][j])
#chain next level of digit transitions with first
poss_pins = []
prob_sums = []
for i in range(len(colapse_first)):
for j in range(len(possible[2])):
if (colapse_first[i][2] == possible[2][j][0]):
l1 = colapse_first[i]
l2 = possible[2][j]
poss_pins.append([l1[0],l1[1],l2[0],l2[1]])
prob_sums.append(prob_sum_first[i] * prob_list[2][j])
#return possible pin numbers and model confidence (liklihood of pin)
return poss_pins, prob_sums
def predictSVC(data):
'''
loads svc from pickle, returns predicted class svc model
'''
ret = []
svc = joblib.load(s)
for d in data:
ret.append(svc.predict(d.reshape(1, -1)))
return ret
def predictKnownPin_rf(pin, model_file):
'''
Generates realistic data with random noise for a given pin, then predicts
possible pin numbers from the generated data.
Returns list of pin numbers and list of associated probabilities
'''
label_map = make_label_map()
#pin number translated into number-number sequences
seq = []
for i in range(len(pin)-1):
seq.append([pin[i],pin[i+1]])
#generate pseudo-data for pin number
acc_data = []
for s in seq:
acc_data.append(pseudo_data(distance(coords[s[0]],coords[s[1]])))
acc_data=np.array(acc_data).reshape(3,24)
#Useful to see data, leave commented out otherwise
#print(acc_data)
#import trained mlp
rfc = joblib.load(model_file)
#get probabilities from predicting on data from above
probs = rfc.predict_proba(acc_data)
#build list of possible pin numbers from probabilities
possible = []
prob_list = []
#loop over each transition
for i in range(len(probs)):
#Get top probabilites and corresponding numbers
poss = [label_map[n] for n in np.argpartition(probs[i], -10)[-10:]]
poss_probs = [probs[i][n] for n in np.argpartition(probs[i], -10)[-10:]]
possible.append(poss)
prob_list.append(poss_probs)
#chain transitions based on sequence of digits (if first.last == next.first then chain and keep, otherwise drop)
colapse_first = []
prob_sum_first = []
for i in range(len(possible[0])):
for j in range(len(possible[1])):
if (possible[0][i][1] == possible[1][j][0]):
l1 = possible[0][i]
l2 = possible[1][j]
colapse_first.append([l1[0],l2[0],l2[1]])
prob_sum_first.append(prob_list[0][i] * prob_list[1][j])
#chain next level of digit transitions with first
poss_pins = []
prob_sums = []
for i in range(len(colapse_first)):
for j in range(len(possible[2])):
if (colapse_first[i][2] == possible[2][j][0]):
l1 = colapse_first[i]
l2 = possible[2][j]
poss_pins.append([l1[0],l1[1],l2[0],l2[1]])
prob_sums.append(prob_sum_first[i] * prob_list[2][j])
#return possible pin numbers and model confidence (liklihood of pin)
return poss_pins, prob_sums
| [
"numpy.array",
"random.random",
"sklearn.externals.joblib.load",
"numpy.argpartition"
] | [((2642, 2656), 'sklearn.externals.joblib.load', 'joblib.load', (['m'], {}), '(m)\n', (2653, 2656), False, 'from sklearn.externals import joblib\n'), ((4446, 4460), 'sklearn.externals.joblib.load', 'joblib.load', (['s'], {}), '(s)\n', (4457, 4460), False, 'from sklearn.externals import joblib\n'), ((5308, 5331), 'sklearn.externals.joblib.load', 'joblib.load', (['model_file'], {}), '(model_file)\n', (5319, 5331), False, 'from sklearn.externals import joblib\n'), ((1331, 1346), 'random.random', 'random.random', ([], {}), '()\n', (1344, 1346), False, 'import random\n'), ((2269, 2287), 'numpy.array', 'np.array', (['acc_data'], {}), '(acc_data)\n', (2277, 2287), True, 'import numpy as np\n'), ((5151, 5169), 'numpy.array', 'np.array', (['acc_data'], {}), '(acc_data)\n', (5159, 5169), True, 'import numpy as np\n'), ((3023, 3053), 'numpy.argpartition', 'np.argpartition', (['probs[i]', '(-10)'], {}), '(probs[i], -10)\n', (3038, 3053), True, 'import numpy as np\n'), ((3104, 3134), 'numpy.argpartition', 'np.argpartition', (['probs[i]', '(-10)'], {}), '(probs[i], -10)\n', (3119, 3134), True, 'import numpy as np\n'), ((5698, 5728), 'numpy.argpartition', 'np.argpartition', (['probs[i]', '(-10)'], {}), '(probs[i], -10)\n', (5713, 5728), True, 'import numpy as np\n'), ((5779, 5809), 'numpy.argpartition', 'np.argpartition', (['probs[i]', '(-10)'], {}), '(probs[i], -10)\n', (5794, 5809), True, 'import numpy as np\n')] |
import os
import random
import warnings
import numpy as np
from tqdm import tqdm
from PIL import Image, ImageFile
from torch.utils.data import Dataset
from taming.data.base import ImagePaths
ImageFile.LOAD_TRUNCATED_IMAGES = True
Image.MAX_IMAGE_PIXELS = None
def test_images(root, images):
passed_images = list()
for fname in tqdm(images):
with warnings.catch_warnings(record=True) as caught_warnings:
image = np.array(Image.open(os.path.join(root, fname)))
if len(caught_warnings) > 0:
continue
if image.ndim == 3 and image.shape[-1] not in [1, 3, 4]:
continue
passed_images.append(fname)
return passed_images
def get_all_images(root):
train_file = os.path.join(root, 'train.npy')
val_file = os.path.join(root, 'val.npy')
if not os.path.isfile(train_file) or not os.path.isfile(val_file):
images = list()
for category in [d for d in os.listdir(root) if os.path.isdir(os.path.join(root, d))]:
category_dir = os.path.join(root, category)
images.extend([os.path.join(category, fname) for fname in os.listdir(category_dir)
if os.path.splitext(fname)[1].lower() in ['.jpg', '.jpeg', '.png']])
passed_images = test_images(root, images)
random.shuffle(passed_images)
num_train_images = int(len(passed_images) * 0.9)
images_train = np.array(passed_images[:num_train_images])
images_val = np.array(passed_images[num_train_images:])
np.save(train_file, images_train)
np.save(val_file, images_val)
else:
images_train = np.load(train_file)
images_val = np.load(val_file)
return {'train': images_train, 'val': images_val}
class WikiArtBase(Dataset):
def __init__(self, *args, **kwargs):
super().__init__()
self.data = None
def __len__(self):
return len(self.data)
def __getitem__(self, i):
example = self.data[i]
return example
class WikiArtTrain(WikiArtBase):
def __init__(self, size, root='/data/datasets/art/wiki-art/',
base=None, ae_augmentations=None, disc_augmentations=None, *args):
super().__init__()
relpaths = get_all_images(root)['train']
paths = [os.path.join(root, relpath) for relpath in relpaths]
self.data = \
ImagePaths(paths=paths, size=size, base=base,
ae_augmentations=ae_augmentations, disc_augmentations=disc_augmentations)
print(f'total {len(self.data)} training data.')
class WikiArtValidation(WikiArtBase):
def __init__(self, size, root='/data/datasets/art/wiki-art/', base=None, *args):
super().__init__()
relpaths = get_all_images(root)['val']
paths = [os.path.join(root, relpath) for relpath in relpaths]
self.data = ImagePaths(paths=paths, size=size, base=base)
print(f'total {len(self.data)} validation data.')
class NatgeoTesing(WikiArtBase):
def __init__(self, size, base=None, *args):
super(NatgeoTesing, self).__init__()
root = '/data/datasets/photography/natgeo/'
paths = [os.path.join(root, fname) for fname in os.listdir(root)
if os.path.splitext(fname)[1].lower() in ['.jpg', '.jpeg', '.png']]
self.data = ImagePaths(paths=sorted(paths), size=size, base=base)
print(f'total {len(self.data)} testing data.')
| [
"taming.data.base.ImagePaths",
"os.listdir",
"random.shuffle",
"tqdm.tqdm",
"os.path.join",
"warnings.catch_warnings",
"os.path.splitext",
"os.path.isfile",
"numpy.array",
"numpy.load",
"numpy.save"
] | [((340, 352), 'tqdm.tqdm', 'tqdm', (['images'], {}), '(images)\n', (344, 352), False, 'from tqdm import tqdm\n'), ((751, 782), 'os.path.join', 'os.path.join', (['root', '"""train.npy"""'], {}), "(root, 'train.npy')\n", (763, 782), False, 'import os\n'), ((798, 827), 'os.path.join', 'os.path.join', (['root', '"""val.npy"""'], {}), "(root, 'val.npy')\n", (810, 827), False, 'import os\n'), ((1325, 1354), 'random.shuffle', 'random.shuffle', (['passed_images'], {}), '(passed_images)\n', (1339, 1354), False, 'import random\n'), ((1435, 1477), 'numpy.array', 'np.array', (['passed_images[:num_train_images]'], {}), '(passed_images[:num_train_images])\n', (1443, 1477), True, 'import numpy as np\n'), ((1499, 1541), 'numpy.array', 'np.array', (['passed_images[num_train_images:]'], {}), '(passed_images[num_train_images:])\n', (1507, 1541), True, 'import numpy as np\n'), ((1551, 1584), 'numpy.save', 'np.save', (['train_file', 'images_train'], {}), '(train_file, images_train)\n', (1558, 1584), True, 'import numpy as np\n'), ((1593, 1622), 'numpy.save', 'np.save', (['val_file', 'images_val'], {}), '(val_file, images_val)\n', (1600, 1622), True, 'import numpy as np\n'), ((1657, 1676), 'numpy.load', 'np.load', (['train_file'], {}), '(train_file)\n', (1664, 1676), True, 'import numpy as np\n'), ((1698, 1715), 'numpy.load', 'np.load', (['val_file'], {}), '(val_file)\n', (1705, 1715), True, 'import numpy as np\n'), ((2398, 2522), 'taming.data.base.ImagePaths', 'ImagePaths', ([], {'paths': 'paths', 'size': 'size', 'base': 'base', 'ae_augmentations': 'ae_augmentations', 'disc_augmentations': 'disc_augmentations'}), '(paths=paths, size=size, base=base, ae_augmentations=\n ae_augmentations, disc_augmentations=disc_augmentations)\n', (2408, 2522), False, 'from taming.data.base import ImagePaths\n'), ((2887, 2932), 'taming.data.base.ImagePaths', 'ImagePaths', ([], {'paths': 'paths', 'size': 'size', 'base': 'base'}), '(paths=paths, size=size, base=base)\n', (2897, 2932), False, 'from taming.data.base import ImagePaths\n'), ((367, 403), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {'record': '(True)'}), '(record=True)\n', (390, 403), False, 'import warnings\n'), ((840, 866), 'os.path.isfile', 'os.path.isfile', (['train_file'], {}), '(train_file)\n', (854, 866), False, 'import os\n'), ((874, 898), 'os.path.isfile', 'os.path.isfile', (['val_file'], {}), '(val_file)\n', (888, 898), False, 'import os\n'), ((1046, 1074), 'os.path.join', 'os.path.join', (['root', 'category'], {}), '(root, category)\n', (1058, 1074), False, 'import os\n'), ((2311, 2338), 'os.path.join', 'os.path.join', (['root', 'relpath'], {}), '(root, relpath)\n', (2323, 2338), False, 'import os\n'), ((2814, 2841), 'os.path.join', 'os.path.join', (['root', 'relpath'], {}), '(root, relpath)\n', (2826, 2841), False, 'import os\n'), ((3189, 3214), 'os.path.join', 'os.path.join', (['root', 'fname'], {}), '(root, fname)\n', (3201, 3214), False, 'import os\n'), ((960, 976), 'os.listdir', 'os.listdir', (['root'], {}), '(root)\n', (970, 976), False, 'import os\n'), ((3228, 3244), 'os.listdir', 'os.listdir', (['root'], {}), '(root)\n', (3238, 3244), False, 'import os\n'), ((464, 489), 'os.path.join', 'os.path.join', (['root', 'fname'], {}), '(root, fname)\n', (476, 489), False, 'import os\n'), ((994, 1015), 'os.path.join', 'os.path.join', (['root', 'd'], {}), '(root, d)\n', (1006, 1015), False, 'import os\n'), ((1102, 1131), 'os.path.join', 'os.path.join', (['category', 'fname'], {}), '(category, fname)\n', (1114, 1131), False, 'import os\n'), ((1145, 1169), 'os.listdir', 'os.listdir', (['category_dir'], {}), '(category_dir)\n', (1155, 1169), False, 'import os\n'), ((3265, 3288), 'os.path.splitext', 'os.path.splitext', (['fname'], {}), '(fname)\n', (3281, 3288), False, 'import os\n'), ((1200, 1223), 'os.path.splitext', 'os.path.splitext', (['fname'], {}), '(fname)\n', (1216, 1223), False, 'import os\n')] |
import json
import numpy as np
from fairseq.criterions.data_utils.task_def import TaskType, DataFormat
def load_data(file_path, data_format, task_type, label_dict=None):
"""
:param file_path:
:param data_format:
:param task_type:
:param label_dict: map string label to numbers.
only valid for Classification task or ranking task.
For ranking task, better label should have large number
:return:
"""
if task_type == TaskType.Ranking:
assert data_format == DataFormat.PremiseAndMultiHypothesis
rows = []
for line in open(file_path, encoding="utf-8"):
fields = line.strip("\n").split("\t")
if data_format == DataFormat.PremiseOnly:
assert len(fields) == 3
row = {"uid": fields[0], "label": fields[1], "premise": fields[2]}
elif data_format == DataFormat.PremiseAndOneHypothesis:
assert len(fields) == 4
row = {"uid": fields[0], "label": fields[1], "premise": fields[2], "hypothesis": fields[3]}
elif data_format == DataFormat.PremiseAndMultiHypothesis:
assert len(fields) > 5
row = {"uid": fields[0], "ruid": fields[1].split(","), "label": fields[2], "premise": fields[3],
"hypothesis": fields[4:]}
else:
raise ValueError(data_format)
if task_type == TaskType.Classification:
if label_dict is not None:
row["label"] = label_dict[row["label"]]
else:
row["label"] = int(row["label"])
elif task_type == TaskType.Regression:
row["label"] = float(row["label"])
elif task_type == TaskType.Ranking:
labels = row["label"].split(",")
if label_dict is not None:
labels = [label_dict[label] for label in labels]
else:
labels = [float(label) for label in labels]
row["label"] = int(np.argmax(labels))
row["olabel"] = labels
rows.append(row)
return rows
def load_score_file(score_path, n_class):
sample_id_2_pred_score_seg_dic = {}
score_obj = json.loads(open(score_path, encoding="utf-8").read())
assert (len(score_obj["scores"]) % len(score_obj["uids"]) == 0) and \
(len(score_obj["scores"]) / len(score_obj["uids"]) == n_class), \
"scores column size should equal to sample count or multiple of sample count (for classification problem)"
scores = score_obj["scores"]
score_segs = [scores[i * n_class: (i+1) * n_class] for i in range(len(score_obj["uids"]))]
for sample_id, pred, score_seg in zip(score_obj["uids"], score_obj["predictions"], score_segs):
sample_id_2_pred_score_seg_dic[sample_id] = (pred, score_seg)
return sample_id_2_pred_score_seg_dic | [
"numpy.argmax"
] | [((2001, 2018), 'numpy.argmax', 'np.argmax', (['labels'], {}), '(labels)\n', (2010, 2018), True, 'import numpy as np\n')] |
import pysplishsplash
import gym
import pickle
import numpy as np
import torch
import argparse
import os,sys
import time
from scipy.ndimage import gaussian_filter,gaussian_filter1d
from scipy.stats import linregress
from scipy.spatial.transform import Rotation as R
import math
import matplotlib.pyplot as plt
from tqdm import tqdm,trange
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def convert_state_to_torch(state):
features = torch.FloatTensor(np.array([state[0]]).reshape(1, -1)).to(device)
particles = torch.FloatTensor(state[1].reshape(1,*state[1].shape)).to(device)
return features,particles
def evalstuff(state,action,td3):
features,particles = convert_state_to_torch(state)
features[-1] = 0
#td3.actor.eval()
#td3.critic.eval()
#print("likestuff",td3.actor(features,particles),td3.critic.Q1(features,particles, td3.actor(features,particles)))
#print("action",action)
q_val = policy.eval_q(state,action)
#print(state[0],action,q_val)
#print("chosen",q_val)
#print("zero",policy.eval_q(state,[0]))
#print("special",policy.eval_q(state,[1]))
#print("one",policy.eval_q(state,[1,1,1]))
return (q_val[0][0]+q_val[1][0])/2
def train(state,td3):
batch_size = 32
all_feat = []
all_part = []
for _ in range(batch_size):
f,p = convert_state_to_torch(state)
all_feat.append(f)
all_part.append(p)
features = torch.cat(all_feat,0)
particles = torch.cat(all_part,0)
td3._actor_learn(features,particles)
def plot_q_compare(rew_lists,q_lists,discount,path,show=False):
maxi = max(len(x) for x in rew_lists)
print([len(x) for x in rew_lists])
emp_rewards = [0 for _ in range(len(rew_lists))]
emp_avg = []
q_avg = []
for i in range(maxi-1,-1,-1):
for j in range(len(rew_lists)):
emp_pot = []
q_pot = []
if len(rew_lists[j]) > i:
emp_rewards[j] = emp_rewards[j]*discount + rew_lists[j][i]
emp_pot.append(emp_rewards[j])
q_pot.append(q_lists[j][i])
emp_avg.append(np.mean(emp_pot))
q_avg.append(np.mean(q_pot))
emp_avg.reverse()
q_avg.reverse()
plt.plot(emp_avg,label="empirical Q value (discounted)")
plt.plot(q_avg,label="TD3 computed Q value")
plt.xlabel("time step")
plt.ylabel("Q-value")
plt.legend()
plt.savefig(path)
if show:
plt.show()
plt.cla()
def running_mean(x, N):
cumsum = np.cumsum(np.insert(x, 0, 0))
return (cumsum[N:] - cumsum[:-N]) / float(N)
def smooth_compare(x_ax1,x_ax2,vals1,vals2,xlabel,ylabel,legend_vals,path,show=False,sigma=5):
fig = plt.figure(figsize=(10,4))
lims = (max(min(x_ax1),min(x_ax2)),min(max(x_ax1),max(x_ax2)))
v1 = gaussian_filter1d(np.array(vals1,dtype=np.float),sigma)
v2 = gaussian_filter1d(np.array(vals2,dtype=np.float),sigma)
plt.plot(x_ax1[:len(v1)],v1,label=legend_vals[0],color="#00664d",linewidth=2)
plt.plot(x_ax1[:len(vals1)],vals1,color="#00664d",alpha=0.4,linewidth=0.8)
plt.plot(x_ax2[:len(v2)],v2,label=legend_vals[1],color="#e65c00",linewidth=2)
plt.plot(x_ax2[:len(vals2)],vals2,color="#e65c00",alpha=0.4,linewidth=0.8)
if ylabel=="Deviation from target fill level (ml)":
plt.ylim(0,50)
if ylabel=="Spilled":
plt.ylim(0,5)
plt.xticks(np.arange(lims[0],lims[1]+1,20))
plt.xlim(lims[0],lims[1])
plt.xlabel(xlabel)
plt.ylabel(ylabel)
#plt.title(title)
plt.legend()
plt.tight_layout()
plt.savefig(path)
if show:
plt.show()
plt.cla()
def plot_mean(x_ax,vals,xlabel,ylabel,legend_val,title,path,show=False,sigma=5):
#plt.rcParams.update({'font.size': 17})
rm = gaussian_filter1d(np.array(vals,dtype=np.float),sigma)
fig = plt.figure(figsize=(10,4))
plt.plot(x_ax,vals,label=legend_val)
plt.plot(x_ax[:len(rm)],rm,label="gaussian smoothed",linewidth=4.0)
plt.xticks(np.arange(min(x_ax),max(x_ax)+1,60))
plt.xlim((min(x_ax),max(x_ax)))
plt.xlabel(xlabel)
plt.ylabel(ylabel)
if title=="Absolute deviation from target fill level":
plt.ylim(0,50)
plt.title(title)
plt.legend()
plt.tight_layout()
plt.savefig(path)
if show:
plt.show()
plt.cla()
def plot_action(all_action_list,path,show=False):
max_len = max(len(x) for x in all_action_list)
avg_actions = []
for i in range(max_len):
pot = []
for acs in all_action_list:
if len(acs)>i:
pot.append(acs[i])
avg_actions.append(np.mean(pot))
plt.plot(avg_actions)
plt.xlabel("Step")
plt.ylabel("Avg rotation action")
plt.title("avg rotation action per step")
plt.savefig(path)
if show:
plt.show()
plt.cla()
def plot_2d(tsps,spills,values,title,path,show=False,sigma=5):
#S,T = np.meshgrid(tsps,spills)
V = np.array(values).reshape((len(tsps),len(tsps)))
print(V)
V = gaussian_filter(V,sigma=5)
#plt.pcolormesh(T,S,V,shading="gouraud")
plt.imshow(V,interpolation="bilinear",cmap='RdBu',origin="lower")#,extent=[tsps[0],tsps[-1],spills[0],spills[-1]])
plt.xticks(range(0,len(tsps),4),[round(x,2) for x in tsps[::4]])
plt.yticks(range(0,len(spills),4),[round(x,2) for x in spills[::4]])
plt.xlabel("time step punish")
plt.ylabel("spill punish")
plt.colorbar()
plt.title(title)
plt.savefig(path)
if show:
plt.show()
plt.clf()
def eval_2d(policy,eval_env,seed,path,root_episodes=30,sigma=5,render=False):
os.makedirs(path,exist_ok=True)
policy.critic.eval()
policy.actor.eval()
eval_env.seed(seed + 100)
eval_env.fixed_tsp = True
eval_env.fixed_spill = True
spills = np.linspace(eval_env.spill_range[0],eval_env.spill_range[1],num=root_episodes)
tsps = np.linspace(eval_env.time_step_punish_range[0],eval_env.time_step_punish_range[1],num=root_episodes)
all_q_val_lists = []
b_list = []
all_reward_lists = []
max_angle_list = []
all_action_list = []
spill_list = []
glass_list = []
print("Evaluating")
"""for spill in tqdm(spills):
for tsp in tsps:
state, done = eval_env.reset(use_gui=render), False
eval_env.spill_punish = spill
eval_env.time_step_punish = tsp
b = 0
reward_list = []
q_val_list = []
action_list = []
max_angle = 0
while not done:
b+=1
action = policy.select_action(state)
action_list.append(action)
max_angle = max(state[0][0],max_angle)
q_val_list.append(evalstuff(state,action,policy))
state, reward, done, _ = eval_env.step(action)
if render:
eval_env.render()
reward_list.append(reward)
all_q_val_lists.append(q_val_list)
all_reward_lists.append(reward_list)
all_action_list.append(action_list)
spill_list.append(eval_env.particle_locations["spilled"])
glass_list.append(eval_env.particle_locations["glass"])
max_angle_list.append(max_angle)
b_list.append(b)
rew_list = [np.sum(x) for x in all_reward_lists]
all_arrays = np.array([b_list,max_angle_list,spill_list,glass_list,[np.sum(x) for x in all_reward_lists]])
np.save(os.path.join(path,"all_arrays.npy"),all_arrays)"""
b_list,max_angle_list,spill_list,glass_list,rew_list = np.load(os.path.join(path,"all_arrays.npy"))
#plot_2d(tsps,spills,glass_list,"Fill state",os.path.join(path,"fill_state.svg"))
#plot_2d(tsps,spills,spill_list,"Spilled",os.path.join(path,"spilled.svg"))
#plot_2d(tsps,spills,max_angle_list,"Max angle",os.path.join(path,"max_angle.svg"))
#plot_2d(tsps,spills,rew_list,"Total return",os.path.join(path,"total_return.svg"))
plot_2d(tsps,spills,b_list,"episode_length",os.path.join(path,"episode_length.svg"),sigma=sigma)
#plot_q_compare(all_reward_lists,all_q_val_lists,args.discount)
def compare2(load1,load2,name1,name2,min_rot1,min_rot2,basepath="plots/test",sigma=5,to_eval="targ"):
os.makedirs(basepath,exist_ok=True)
name_map = {"tsp":"Time Step Punish",
"spill":"Spill Punish",
"targ":"Target fill level (ml)"}
with open(load1,"rb") as f:
all_q_val_lists1, b_list1, all_reward_lists1, max_angle_list1, all_action_list1, ev_list1, spill_list1, glass_list1, avg_reward1 = pickle.load(f)
with open(load2,"rb") as f:
all_q_val_lists2, b_list2, all_reward_lists2, max_angle_list2, all_action_list2, ev_list2, spill_list2, glass_list2, avg_reward2 = pickle.load(f)
print(np.sum(spill_list1),np.sum(spill_list2))
reward_sum1 = [np.sum(x) for x in all_reward_lists1]
reward_sum2 = [np.sum(x) for x in all_reward_lists2]
for i in range(len(max_angle_list1)):
radians = max_angle_list1[i]*(math.pi-min_rot1)+min_rot1
degrees = (radians*180)/math.pi
max_angle_list1[i] = degrees
for i in range(len(max_angle_list2)):
radians = max_angle_list2[i]*(math.pi-min_rot2)+min_rot2
degrees = (radians*180)/math.pi
max_angle_list2[i] = degrees
if to_eval=="targ":
dev_list1 = (np.array(glass_list1)-np.array(ev_list1))
dev_list2 = (np.array(glass_list2)-np.array(ev_list2))
smooth_compare(ev_list1,ev_list2,dev_list1,dev_list2,"Target fill level (ml)","Deviation from target fill level (ml)",
[name1,name2],os.path.join(basepath,"deviation.svg"),sigma=sigma)
smooth_compare(ev_list1,ev_list2,np.abs(dev_list1),np.abs(dev_list2),"Target fill level (ml)","Deviation from target fill level (ml)",
[name1,name2],os.path.join(basepath,"abs_deviation.svg"),sigma=sigma)
smooth_compare(ev_list1,ev_list2,b_list1,b_list2,name_map[to_eval],"Episode length (steps)",
[name1,name2],os.path.join(basepath,"epi_length.svg"),sigma=sigma)
smooth_compare(ev_list1,ev_list2,max_angle_list1,max_angle_list2,name_map[to_eval],"Angle (Degrees)",
[name1,name2],os.path.join(basepath,"angle.svg"),sigma=sigma)
smooth_compare(ev_list1,ev_list2,reward_sum1,reward_sum2,name_map[to_eval],"Return",
[name1,name2],os.path.join(basepath,"return.svg"),sigma=sigma)
smooth_compare(ev_list1,ev_list2,spill_list1,spill_list2,name_map[to_eval],"Spilled",
[name1,name2],os.path.join(basepath,"spilled.svg"),sigma=sigma)
smooth_compare(ev_list1,ev_list2,glass_list1,glass_list2,name_map[to_eval],"fill-level (ml)",
[name1,name2],os.path.join(basepath,"fill_state.svg"),sigma=sigma)
def rotation_volume_analysis(policy,eval_env,save_path,render=False):
eval_env.fixed_tsp = True
eval_env.fixed_spill = True
eval_env.time_step_punish = 1
eval_env.spill_punish = 25
eval_env.fixed_target_fill = True
targ_fills = [120,150,180,210]
action_lists = []
rotation_lists = []
volumes_lists = []
for tf in targ_fills:
eval_env.target_fill_state = tf
state, done = eval_env.reset(use_gui=render), False
action_list = []
rotation_list = []
volumes_list = []
while not done:
action = policy.select_action(state)
if render:
eval_env.render()
volumes_list.append(eval_env.particle_locations["glass"])
action_list.append(action[0])
bottle_radians = R.from_matrix(env.bottle.rotation).as_euler("zyx")[0]
rotation_list.append((bottle_radians/math.pi)*180)
state, reward, done, _ = eval_env.step(action)
action_lists.append(action_list)
rotation_lists.append(rotation_list)
volumes_lists.append(volumes_list)
with open(save_path,"wb") as f:
pickle.dump({"targ_fills":targ_fills,
"actions":action_lists,
"rotations":rotation_lists,
"volumes":volumes_lists},f)
def eval_1d(policy, eval_env, seed, basepath="plots/test", eval_episodes=10, to_eval="tsp", N=5, render=False, load=None):
os.makedirs(basepath,exist_ok=True)
name_map = {"tsp":"Time Step Punish",
"spill":"Spill Punish",
"targ":"Target fill level (ml)"}
if load is None:
policy.critic.eval()
policy.actor.eval()
eval_env.seed(seed + 100)
eval_env.fixed_tsp = True
eval_env.fixed_spill = True
eval_env.fixed_target_fill = True
eval_env.target_fill_state = eval_env.max_in_glass
eval_env.time_step_punish = 1
eval_env.spill_punish = 25
all_q_val_lists = []
b_list = []
all_reward_lists = []
max_angle_list = []
all_action_list = []
ev_list = []
spill_list = []
glass_list = []
print("Evaluating")
for i in trange(eval_episodes):
state, done = eval_env.reset(use_gui=render), False
if to_eval == "tsp":
tsp = (eval_env.time_step_punish_range[0]+(eval_env.time_step_punish_range[1] -
eval_env.time_step_punish_range[0])/(eval_episodes-1) * i)
ev_list.append(tsp)
eval_env.time_step_punish = tsp
elif to_eval == "spill":
spill_punish = (eval_env.spill_range[0]+(eval_env.spill_range[1] -
eval_env.spill_range[0])/(eval_episodes-1) * i)
eval_env.spill_punish = spill_punish
ev_list.append(spill_punish)
elif to_eval == "targ":
target_fill = (eval_env.target_fill_range[0]+(eval_env.target_fill_range[1] -
eval_env.target_fill_range[0])/(eval_episodes-1) * i)
eval_env.target_fill_state = target_fill
print(target_fill)
ev_list.append(target_fill)
b = 0
reward_list = []
q_val_list = []
action_list = []
max_angle = 0
while not done:
b+=1
action = policy.select_action(state)
action_list.append(action)
angle = state[0][0] if type(state)==tuple else state[0]
max_angle = max(angle,max_angle)
q_val_list.append(evalstuff(state,action,policy))
state, reward, done, _ = eval_env.step(action)
if render:
eval_env.render()
reward_list.append(reward)
all_q_val_lists.append(q_val_list)
all_reward_lists.append(reward_list)
all_action_list.append(action_list)
spill_list.append(eval_env.particle_locations["spilled"])
glass_list.append(eval_env.particle_locations["glass"])
max_angle_list.append(max_angle)
b_list.append(b)
avg_reward = np.mean([np.sum(x) for x in all_reward_lists])
with open(os.path.join(basepath,"data.pkl"),"wb") as f:
to_save = [all_q_val_lists, b_list, all_reward_lists,
max_angle_list, all_action_list, ev_list,
spill_list, glass_list, avg_reward]
pickle.dump(to_save,f)
else:
with open(os.path.join(basepath,"data.pkl"),"rb") as f:
all_q_val_lists, b_list, all_reward_lists, max_angle_list, all_action_list, ev_list, spill_list, glass_list, avg_reward = pickle.load(f)
for i in range(len(max_angle_list)):
radians = max_angle_list[i]*(math.pi-env.min_rotation)+env.min_rotation
degrees = (radians*180)/math.pi
max_angle_list[i] = degrees
ev_list = np.array(ev_list)
print(linregress(ev_list[ev_list>=100],np.array(b_list)[ev_list>=100]))
#print(linregress(ev_list[ev_list>=0],np.array(max_angle_list)[ev_list>=0]))
if to_eval=="targ":
dev_list = (np.array(glass_list)-np.array(ev_list))
#percent_list = (np.array(glass_list)-np.array(ev_list))/np.array(ev_list)
#percent_list*=100
#print(linregress(ev_list[ev_list>=340],np.abs(dev_list[ev_list>=340])))
plot_mean(ev_list,dev_list,name_map[to_eval],"Deviation from target fill level (ml)","Deviation",
"Deviation from target fill level",os.path.join(basepath,f"{to_eval}_deviation.svg"),sigma=N)
plot_mean(ev_list,np.abs(dev_list),name_map[to_eval],"Absolute deviation from target fill level (ml)","Deviation",
"Absolute deviation from target fill level",os.path.join(basepath,f"{to_eval}_abs_deviation.svg"),sigma=N)
plot_mean(ev_list,b_list,name_map[to_eval],"Episode length","Episode length",
"Episode lengths",os.path.join(basepath,f"{to_eval}_episode_length.svg"),sigma=N)
plot_mean(ev_list,max_angle_list,name_map[to_eval],"Degrees","Degrees",
f"Maximum angle of inclination",os.path.join(basepath,f"{to_eval}_angle.svg"),sigma=N)
reward_sum = [np.sum(x) for x in all_reward_lists]
plot_mean(ev_list,reward_sum,name_map[to_eval],"Return","total return","total return",
os.path.join(basepath,f"{to_eval}_return.svg"),sigma=N)
plot_action(all_action_list,os.path.join(basepath,"action.svg"))
plot_mean(ev_list,spill_list,name_map[to_eval],"Spilled","num particles spilled",
"Particles Spilled",os.path.join(basepath,f"{to_eval}_spilled.svg"),sigma=N)
plot_mean(ev_list,glass_list,name_map[to_eval],"particles in glass","num particles in glass",
"Final fill state",os.path.join(basepath,f"{to_eval}_fill.svg"),sigma=N)
plot_q_compare(all_reward_lists,all_q_val_lists,args.discount,os.path.join(basepath,"q_compare.svg"))
print("---------------------------------------")
print(f"Evaluation over {eval_episodes} episodes: {avg_reward:.3f}")
print(f"Avg episode length {np.mean(b_list)}")
print("---------------------------------------")
eval_env.fixed_tsp = False
eval_env.reset(use_gui=False)
return avg_reward
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--policy", default="TD3_particles") # Policy name (TD3, DDPG or OurDDPG)
parser.add_argument("--env", default="water_pouring:Pouring-mdp-v0") # OpenAI gym environment name
parser.add_argument("--seed", default=0, type=int) # Sets Gym, PyTorch and Numpy seeds
parser.add_argument("--start_timesteps", default=5e4, type=int) # Time steps initial random policy is used
parser.add_argument("--eval_freq", default=1e2, type=int) # How often (time steps) we evaluate
parser.add_argument("--max_timesteps", default=1e6, type=int) # Max time steps to run environment
parser.add_argument("--expl_noise", default=0.1, type=float) # Std of Gaussian exploration noise
parser.add_argument("--batch_size", default=256, type=int) # Batch size for both actor and critic
parser.add_argument("--discount", default=0.99, type=float) # Discount factor
parser.add_argument("--policy_uncertainty",default=0.3, type=float) # Std of env policy uncertainty
parser.add_argument("--tau", default=0.005, type=float) # Target network update rate
parser.add_argument("--policy_noise", default=0.2, type=float) # Noise added to target policy during critic update
parser.add_argument("--noise_clip", default=0.5, type=float) # Range to clip target policy noise
parser.add_argument("--policy_freq", default=2, type=int) # Frequency of delayed policy updates
#parser.add_argument("--time_step_punish", default=0.1, type=float)
parser.add_argument("--save_model", action="store_true") # Save model and optimizer parameters
parser.add_argument("--load_model", default="") # Model load file name, "" doesn't load, "default" uses file_name
parser.add_argument("--norm",type=str, default="layer")
parser.add_argument("--render", action="store_true")
parser.add_argument("--path",type=str, default="plots/test")
parser.add_argument("--to_eval",type=str, default="tsp")
parser.add_argument("--eval_episodes",type=int,default=100)
parser.add_argument("--running_num",type=int, default=5)
parser.add_argument("--load",type=str, default="")
parser.add_argument("--load2",type=str, default="")
parser.add_argument("--name1",type=str, default="default1")
parser.add_argument("--name2",type=str, default="default2")
parser.add_argument("--min_rot1",type=float, default=1.22)
parser.add_argument("--min_rot2",type=float, default=1.22)
parser.add_argument("--human_compare",action="store_true")
parser.add_argument("--jerk_punish",type=float, default=0)
parser.add_argument("--rot_vol_analysis",action="store_true")
args = parser.parse_args()
if args.load2!="":
compare2(args.load,args.load2,args.name1,args.name2,args.min_rot1,args.min_rot2,basepath=args.path,sigma=args.running_num,to_eval=args.to_eval)
exit()
env_kwargs = {
"policy_uncertainty":args.policy_uncertainty,
"jerk_punish":args.jerk_punish
}
if args.human_compare:
env_kwargs["scene_base"] = "scenes/smaller_scene.json"
env = gym.make(args.env,**env_kwargs)
if args.human_compare:
env.max_in_glass = 215
env.target_fill_range = [114,209]
print(env.observation_space,env.action_space)
print("made Env")
env.seed(args.seed)
torch.manual_seed(args.seed)
np.random.seed(args.seed)
max_action = float(env.action_space.high[0])
kwargs = {
"obs_space": env.observation_space,
"action_space": env.action_space,
"discount": args.discount,
"tau": args.tau,
"policy_freq": int(args.policy_freq),
"norm": None if args.norm=="" else args.norm
}
if args.load == "":
if args.policy == "TD3_featured":
from TD3_featured import TD3
from my_replay_buffer import ReplayBuffer_featured as ReplayBuffer
elif args.policy == "TD3_particles":
from TD3_particles import TD3
from my_replay_buffer import ReplayBuffer_particles as ReplayBuffer
policy = TD3(**kwargs)
if args.load_model != "":
policy_file = file_name if args.load_model == "default" else args.load_model
policy.load(policy_file)
else:
policy = None
if args.rot_vol_analysis:
rotation_volume_analysis(policy,env,args.path,render=args.render)
else:
evaluations = eval_1d(policy, env, args.seed, basepath=args.path, to_eval=args.to_eval, render=args.render, N=args.running_num, eval_episodes=args.eval_episodes, load=None if args.load=="" else args.load)
#eval_2d(policy,env,args.seed,args.path,render=args.render,sigma=args.running_num) | [
"TD3_particles.TD3",
"matplotlib.pyplot.ylabel",
"numpy.array",
"torch.cuda.is_available",
"scipy.ndimage.gaussian_filter",
"gym.make",
"numpy.arange",
"matplotlib.pyplot.imshow",
"numpy.mean",
"argparse.ArgumentParser",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"numpy.linspace",... | [((1444, 1466), 'torch.cat', 'torch.cat', (['all_feat', '(0)'], {}), '(all_feat, 0)\n', (1453, 1466), False, 'import torch\n'), ((1482, 1504), 'torch.cat', 'torch.cat', (['all_part', '(0)'], {}), '(all_part, 0)\n', (1491, 1504), False, 'import torch\n'), ((2226, 2283), 'matplotlib.pyplot.plot', 'plt.plot', (['emp_avg'], {'label': '"""empirical Q value (discounted)"""'}), "(emp_avg, label='empirical Q value (discounted)')\n", (2234, 2283), True, 'import matplotlib.pyplot as plt\n'), ((2287, 2332), 'matplotlib.pyplot.plot', 'plt.plot', (['q_avg'], {'label': '"""TD3 computed Q value"""'}), "(q_avg, label='TD3 computed Q value')\n", (2295, 2332), True, 'import matplotlib.pyplot as plt\n'), ((2336, 2359), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""time step"""'], {}), "('time step')\n", (2346, 2359), True, 'import matplotlib.pyplot as plt\n'), ((2364, 2385), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Q-value"""'], {}), "('Q-value')\n", (2374, 2385), True, 'import matplotlib.pyplot as plt\n'), ((2390, 2402), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (2400, 2402), True, 'import matplotlib.pyplot as plt\n'), ((2407, 2424), 'matplotlib.pyplot.savefig', 'plt.savefig', (['path'], {}), '(path)\n', (2418, 2424), True, 'import matplotlib.pyplot as plt\n'), ((2461, 2470), 'matplotlib.pyplot.cla', 'plt.cla', ([], {}), '()\n', (2468, 2470), True, 'import matplotlib.pyplot as plt\n'), ((2695, 2722), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 4)'}), '(figsize=(10, 4))\n', (2705, 2722), True, 'import matplotlib.pyplot as plt\n'), ((3420, 3446), 'matplotlib.pyplot.xlim', 'plt.xlim', (['lims[0]', 'lims[1]'], {}), '(lims[0], lims[1])\n', (3428, 3446), True, 'import matplotlib.pyplot as plt\n'), ((3450, 3468), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['xlabel'], {}), '(xlabel)\n', (3460, 3468), True, 'import matplotlib.pyplot as plt\n'), ((3473, 3491), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['ylabel'], {}), '(ylabel)\n', (3483, 3491), True, 'import matplotlib.pyplot as plt\n'), ((3518, 3530), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (3528, 3530), True, 'import matplotlib.pyplot as plt\n'), ((3535, 3553), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (3551, 3553), True, 'import matplotlib.pyplot as plt\n'), ((3558, 3575), 'matplotlib.pyplot.savefig', 'plt.savefig', (['path'], {}), '(path)\n', (3569, 3575), True, 'import matplotlib.pyplot as plt\n'), ((3612, 3621), 'matplotlib.pyplot.cla', 'plt.cla', ([], {}), '()\n', (3619, 3621), True, 'import matplotlib.pyplot as plt\n'), ((3822, 3849), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 4)'}), '(figsize=(10, 4))\n', (3832, 3849), True, 'import matplotlib.pyplot as plt\n'), ((3853, 3891), 'matplotlib.pyplot.plot', 'plt.plot', (['x_ax', 'vals'], {'label': 'legend_val'}), '(x_ax, vals, label=legend_val)\n', (3861, 3891), True, 'import matplotlib.pyplot as plt\n'), ((4054, 4072), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['xlabel'], {}), '(xlabel)\n', (4064, 4072), True, 'import matplotlib.pyplot as plt\n'), ((4077, 4095), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['ylabel'], {}), '(ylabel)\n', (4087, 4095), True, 'import matplotlib.pyplot as plt\n'), ((4182, 4198), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (4191, 4198), True, 'import matplotlib.pyplot as plt\n'), ((4203, 4215), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (4213, 4215), True, 'import matplotlib.pyplot as plt\n'), ((4220, 4238), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (4236, 4238), True, 'import matplotlib.pyplot as plt\n'), ((4243, 4260), 'matplotlib.pyplot.savefig', 'plt.savefig', (['path'], {}), '(path)\n', (4254, 4260), True, 'import matplotlib.pyplot as plt\n'), ((4297, 4306), 'matplotlib.pyplot.cla', 'plt.cla', ([], {}), '()\n', (4304, 4306), True, 'import matplotlib.pyplot as plt\n'), ((4619, 4640), 'matplotlib.pyplot.plot', 'plt.plot', (['avg_actions'], {}), '(avg_actions)\n', (4627, 4640), True, 'import matplotlib.pyplot as plt\n'), ((4645, 4663), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Step"""'], {}), "('Step')\n", (4655, 4663), True, 'import matplotlib.pyplot as plt\n'), ((4668, 4701), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Avg rotation action"""'], {}), "('Avg rotation action')\n", (4678, 4701), True, 'import matplotlib.pyplot as plt\n'), ((4706, 4747), 'matplotlib.pyplot.title', 'plt.title', (['"""avg rotation action per step"""'], {}), "('avg rotation action per step')\n", (4715, 4747), True, 'import matplotlib.pyplot as plt\n'), ((4752, 4769), 'matplotlib.pyplot.savefig', 'plt.savefig', (['path'], {}), '(path)\n', (4763, 4769), True, 'import matplotlib.pyplot as plt\n'), ((4806, 4815), 'matplotlib.pyplot.cla', 'plt.cla', ([], {}), '()\n', (4813, 4815), True, 'import matplotlib.pyplot as plt\n'), ((4993, 5020), 'scipy.ndimage.gaussian_filter', 'gaussian_filter', (['V'], {'sigma': '(5)'}), '(V, sigma=5)\n', (5008, 5020), False, 'from scipy.ndimage import gaussian_filter, gaussian_filter1d\n'), ((5069, 5137), 'matplotlib.pyplot.imshow', 'plt.imshow', (['V'], {'interpolation': '"""bilinear"""', 'cmap': '"""RdBu"""', 'origin': '"""lower"""'}), "(V, interpolation='bilinear', cmap='RdBu', origin='lower')\n", (5079, 5137), True, 'import matplotlib.pyplot as plt\n'), ((5330, 5360), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""time step punish"""'], {}), "('time step punish')\n", (5340, 5360), True, 'import matplotlib.pyplot as plt\n'), ((5365, 5391), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""spill punish"""'], {}), "('spill punish')\n", (5375, 5391), True, 'import matplotlib.pyplot as plt\n'), ((5396, 5410), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (5408, 5410), True, 'import matplotlib.pyplot as plt\n'), ((5415, 5431), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (5424, 5431), True, 'import matplotlib.pyplot as plt\n'), ((5436, 5453), 'matplotlib.pyplot.savefig', 'plt.savefig', (['path'], {}), '(path)\n', (5447, 5453), True, 'import matplotlib.pyplot as plt\n'), ((5490, 5499), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (5497, 5499), True, 'import matplotlib.pyplot as plt\n'), ((5583, 5615), 'os.makedirs', 'os.makedirs', (['path'], {'exist_ok': '(True)'}), '(path, exist_ok=True)\n', (5594, 5615), False, 'import os, sys\n'), ((5769, 5854), 'numpy.linspace', 'np.linspace', (['eval_env.spill_range[0]', 'eval_env.spill_range[1]'], {'num': 'root_episodes'}), '(eval_env.spill_range[0], eval_env.spill_range[1], num=root_episodes\n )\n', (5780, 5854), True, 'import numpy as np\n'), ((5859, 5966), 'numpy.linspace', 'np.linspace', (['eval_env.time_step_punish_range[0]', 'eval_env.time_step_punish_range[1]'], {'num': 'root_episodes'}), '(eval_env.time_step_punish_range[0], eval_env.\n time_step_punish_range[1], num=root_episodes)\n', (5870, 5966), True, 'import numpy as np\n'), ((8222, 8258), 'os.makedirs', 'os.makedirs', (['basepath'], {'exist_ok': '(True)'}), '(basepath, exist_ok=True)\n', (8233, 8258), False, 'import os, sys\n'), ((12281, 12317), 'os.makedirs', 'os.makedirs', (['basepath'], {'exist_ok': '(True)'}), '(basepath, exist_ok=True)\n', (12292, 12317), False, 'import os, sys\n'), ((15872, 15889), 'numpy.array', 'np.array', (['ev_list'], {}), '(ev_list)\n', (15880, 15889), True, 'import numpy as np\n'), ((18256, 18281), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (18279, 18281), False, 'import argparse\n'), ((21506, 21538), 'gym.make', 'gym.make', (['args.env'], {}), '(args.env, **env_kwargs)\n', (21514, 21538), False, 'import gym\n'), ((21739, 21767), 'torch.manual_seed', 'torch.manual_seed', (['args.seed'], {}), '(args.seed)\n', (21756, 21767), False, 'import torch\n'), ((21772, 21797), 'numpy.random.seed', 'np.random.seed', (['args.seed'], {}), '(args.seed)\n', (21786, 21797), True, 'import numpy as np\n'), ((373, 398), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (396, 398), False, 'import torch\n'), ((2446, 2456), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2454, 2456), True, 'import matplotlib.pyplot as plt\n'), ((2519, 2537), 'numpy.insert', 'np.insert', (['x', '(0)', '(0)'], {}), '(x, 0, 0)\n', (2528, 2537), True, 'import numpy as np\n'), ((2816, 2847), 'numpy.array', 'np.array', (['vals1'], {'dtype': 'np.float'}), '(vals1, dtype=np.float)\n', (2824, 2847), True, 'import numpy as np\n'), ((2881, 2912), 'numpy.array', 'np.array', (['vals2'], {'dtype': 'np.float'}), '(vals2, dtype=np.float)\n', (2889, 2912), True, 'import numpy as np\n'), ((3305, 3320), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0)', '(50)'], {}), '(0, 50)\n', (3313, 3320), True, 'import matplotlib.pyplot as plt\n'), ((3354, 3368), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0)', '(5)'], {}), '(0, 5)\n', (3362, 3368), True, 'import matplotlib.pyplot as plt\n'), ((3383, 3418), 'numpy.arange', 'np.arange', (['lims[0]', '(lims[1] + 1)', '(20)'], {}), '(lims[0], lims[1] + 1, 20)\n', (3392, 3418), True, 'import numpy as np\n'), ((3597, 3607), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3605, 3607), True, 'import matplotlib.pyplot as plt\n'), ((3775, 3805), 'numpy.array', 'np.array', (['vals'], {'dtype': 'np.float'}), '(vals, dtype=np.float)\n', (3783, 3805), True, 'import numpy as np\n'), ((4163, 4178), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0)', '(50)'], {}), '(0, 50)\n', (4171, 4178), True, 'import matplotlib.pyplot as plt\n'), ((4282, 4292), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4290, 4292), True, 'import matplotlib.pyplot as plt\n'), ((4791, 4801), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4799, 4801), True, 'import matplotlib.pyplot as plt\n'), ((5475, 5485), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5483, 5485), True, 'import matplotlib.pyplot as plt\n'), ((7566, 7602), 'os.path.join', 'os.path.join', (['path', '"""all_arrays.npy"""'], {}), "(path, 'all_arrays.npy')\n", (7578, 7602), False, 'import os, sys\n'), ((7994, 8034), 'os.path.join', 'os.path.join', (['path', '"""episode_length.svg"""'], {}), "(path, 'episode_length.svg')\n", (8006, 8034), False, 'import os, sys\n'), ((8564, 8578), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (8575, 8578), False, 'import pickle\n'), ((8754, 8768), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (8765, 8768), False, 'import pickle\n'), ((8779, 8798), 'numpy.sum', 'np.sum', (['spill_list1'], {}), '(spill_list1)\n', (8785, 8798), True, 'import numpy as np\n'), ((8799, 8818), 'numpy.sum', 'np.sum', (['spill_list2'], {}), '(spill_list2)\n', (8805, 8818), True, 'import numpy as np\n'), ((8839, 8848), 'numpy.sum', 'np.sum', (['x'], {}), '(x)\n', (8845, 8848), True, 'import numpy as np\n'), ((8896, 8905), 'numpy.sum', 'np.sum', (['x'], {}), '(x)\n', (8902, 8905), True, 'import numpy as np\n'), ((10035, 10075), 'os.path.join', 'os.path.join', (['basepath', '"""epi_length.svg"""'], {}), "(basepath, 'epi_length.svg')\n", (10047, 10075), False, 'import os, sys\n'), ((10227, 10262), 'os.path.join', 'os.path.join', (['basepath', '"""angle.svg"""'], {}), "(basepath, 'angle.svg')\n", (10239, 10262), False, 'import os, sys\n'), ((10397, 10433), 'os.path.join', 'os.path.join', (['basepath', '"""return.svg"""'], {}), "(basepath, 'return.svg')\n", (10409, 10433), False, 'import os, sys\n'), ((10569, 10606), 'os.path.join', 'os.path.join', (['basepath', '"""spilled.svg"""'], {}), "(basepath, 'spilled.svg')\n", (10581, 10606), False, 'import os, sys\n'), ((10750, 10790), 'os.path.join', 'os.path.join', (['basepath', '"""fill_state.svg"""'], {}), "(basepath, 'fill_state.svg')\n", (10762, 10790), False, 'import os, sys\n'), ((11967, 12093), 'pickle.dump', 'pickle.dump', (["{'targ_fills': targ_fills, 'actions': action_lists, 'rotations':\n rotation_lists, 'volumes': volumes_lists}", 'f'], {}), "({'targ_fills': targ_fills, 'actions': action_lists, 'rotations':\n rotation_lists, 'volumes': volumes_lists}, f)\n", (11978, 12093), False, 'import pickle\n'), ((13054, 13075), 'tqdm.trange', 'trange', (['eval_episodes'], {}), '(eval_episodes)\n', (13060, 13075), False, 'from tqdm import tqdm, trange\n'), ((16902, 16957), 'os.path.join', 'os.path.join', (['basepath', 'f"""{to_eval}_episode_length.svg"""'], {}), "(basepath, f'{to_eval}_episode_length.svg')\n", (16914, 16957), False, 'import os, sys\n'), ((17088, 17134), 'os.path.join', 'os.path.join', (['basepath', 'f"""{to_eval}_angle.svg"""'], {}), "(basepath, f'{to_eval}_angle.svg')\n", (17100, 17134), False, 'import os, sys\n'), ((17161, 17170), 'numpy.sum', 'np.sum', (['x'], {}), '(x)\n', (17167, 17170), True, 'import numpy as np\n'), ((17303, 17350), 'os.path.join', 'os.path.join', (['basepath', 'f"""{to_eval}_return.svg"""'], {}), "(basepath, f'{to_eval}_return.svg')\n", (17315, 17350), False, 'import os, sys\n'), ((17391, 17427), 'os.path.join', 'os.path.join', (['basepath', '"""action.svg"""'], {}), "(basepath, 'action.svg')\n", (17403, 17427), False, 'import os, sys\n'), ((17548, 17596), 'os.path.join', 'os.path.join', (['basepath', 'f"""{to_eval}_spilled.svg"""'], {}), "(basepath, f'{to_eval}_spilled.svg')\n", (17560, 17596), False, 'import os, sys\n'), ((17736, 17781), 'os.path.join', 'os.path.join', (['basepath', 'f"""{to_eval}_fill.svg"""'], {}), "(basepath, f'{to_eval}_fill.svg')\n", (17748, 17781), False, 'import os, sys\n'), ((17856, 17895), 'os.path.join', 'os.path.join', (['basepath', '"""q_compare.svg"""'], {}), "(basepath, 'q_compare.svg')\n", (17868, 17895), False, 'import os, sys\n'), ((22490, 22503), 'TD3_particles.TD3', 'TD3', ([], {}), '(**kwargs)\n', (22493, 22503), False, 'from TD3_particles import TD3\n'), ((2125, 2141), 'numpy.mean', 'np.mean', (['emp_pot'], {}), '(emp_pot)\n', (2132, 2141), True, 'import numpy as np\n'), ((2164, 2178), 'numpy.mean', 'np.mean', (['q_pot'], {}), '(q_pot)\n', (2171, 2178), True, 'import numpy as np\n'), ((4601, 4613), 'numpy.mean', 'np.mean', (['pot'], {}), '(pot)\n', (4608, 4613), True, 'import numpy as np\n'), ((4924, 4940), 'numpy.array', 'np.array', (['values'], {}), '(values)\n', (4932, 4940), True, 'import numpy as np\n'), ((9348, 9369), 'numpy.array', 'np.array', (['glass_list1'], {}), '(glass_list1)\n', (9356, 9369), True, 'import numpy as np\n'), ((9370, 9388), 'numpy.array', 'np.array', (['ev_list1'], {}), '(ev_list1)\n', (9378, 9388), True, 'import numpy as np\n'), ((9411, 9432), 'numpy.array', 'np.array', (['glass_list2'], {}), '(glass_list2)\n', (9419, 9432), True, 'import numpy as np\n'), ((9433, 9451), 'numpy.array', 'np.array', (['ev_list2'], {}), '(ev_list2)\n', (9441, 9451), True, 'import numpy as np\n'), ((9617, 9656), 'os.path.join', 'os.path.join', (['basepath', '"""deviation.svg"""'], {}), "(basepath, 'deviation.svg')\n", (9629, 9656), False, 'import os, sys\n'), ((9710, 9727), 'numpy.abs', 'np.abs', (['dev_list1'], {}), '(dev_list1)\n', (9716, 9727), True, 'import numpy as np\n'), ((9728, 9745), 'numpy.abs', 'np.abs', (['dev_list2'], {}), '(dev_list2)\n', (9734, 9745), True, 'import numpy as np\n'), ((9849, 9892), 'os.path.join', 'os.path.join', (['basepath', '"""abs_deviation.svg"""'], {}), "(basepath, 'abs_deviation.svg')\n", (9861, 9892), False, 'import os, sys\n'), ((15412, 15435), 'pickle.dump', 'pickle.dump', (['to_save', 'f'], {}), '(to_save, f)\n', (15423, 15435), False, 'import pickle\n'), ((15643, 15657), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (15654, 15657), False, 'import pickle\n'), ((16091, 16111), 'numpy.array', 'np.array', (['glass_list'], {}), '(glass_list)\n', (16099, 16111), True, 'import numpy as np\n'), ((16112, 16129), 'numpy.array', 'np.array', (['ev_list'], {}), '(ev_list)\n', (16120, 16129), True, 'import numpy as np\n'), ((16481, 16531), 'os.path.join', 'os.path.join', (['basepath', 'f"""{to_eval}_deviation.svg"""'], {}), "(basepath, f'{to_eval}_deviation.svg')\n", (16493, 16531), False, 'import os, sys\n'), ((16566, 16582), 'numpy.abs', 'np.abs', (['dev_list'], {}), '(dev_list)\n', (16572, 16582), True, 'import numpy as np\n'), ((16725, 16779), 'os.path.join', 'os.path.join', (['basepath', 'f"""{to_eval}_abs_deviation.svg"""'], {}), "(basepath, f'{to_eval}_abs_deviation.svg')\n", (16737, 16779), False, 'import os, sys\n'), ((15107, 15116), 'numpy.sum', 'np.sum', (['x'], {}), '(x)\n', (15113, 15116), True, 'import numpy as np\n'), ((15163, 15197), 'os.path.join', 'os.path.join', (['basepath', '"""data.pkl"""'], {}), "(basepath, 'data.pkl')\n", (15175, 15197), False, 'import os, sys\n'), ((15463, 15497), 'os.path.join', 'os.path.join', (['basepath', '"""data.pkl"""'], {}), "(basepath, 'data.pkl')\n", (15475, 15497), False, 'import os, sys\n'), ((15933, 15949), 'numpy.array', 'np.array', (['b_list'], {}), '(b_list)\n', (15941, 15949), True, 'import numpy as np\n'), ((18056, 18071), 'numpy.mean', 'np.mean', (['b_list'], {}), '(b_list)\n', (18063, 18071), True, 'import numpy as np\n'), ((480, 500), 'numpy.array', 'np.array', (['[state[0]]'], {}), '([state[0]])\n', (488, 500), True, 'import numpy as np\n'), ((11618, 11652), 'scipy.spatial.transform.Rotation.from_matrix', 'R.from_matrix', (['env.bottle.rotation'], {}), '(env.bottle.rotation)\n', (11631, 11652), True, 'from scipy.spatial.transform import Rotation as R\n')] |
import pandas as pd
import numpy as np
import quandl, math, datetime
from sklearn import preprocessing, svm
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
from matplotlib import style
style.use('ggplot')
df = quandl.get('WIKI/GOOGL')
df = df[['Adj. Open','Adj. High','Adj. Low','Adj. Close','Adj. Volume',]]
df['HL_PCT'] = (df['Adj. High'] - df['Adj. Close']) / df['Adj. Close'] * 100.0
df['PCT_change'] = (df['Adj. Close'] - df['Adj. Open']) / df['Adj. Open'] * 100.0
df = df[['Adj. Close','HL_PCT','PCT_change','Adj. Volume']]
forecast_col= 'Adj. Close'
df.fillna(-99999, inplace=True)
forecast_out = int(math.ceil(0.01*len(df)))
df['Label'] = df[forecast_col].shift(-forecast_out)
X=np.array(df.drop(['Label'],1))
X = preprocessing.scale(X)
X = X[:-forecast_out]
X_lately = X[-forecast_out:]
df.dropna(inplace=True)
y=np.array(df['Label'])
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2)
clf = LinearRegression(n_jobs=-1)
clf.fit(X_train,y_train)
accuracy = clf.score(X_test, y_test)
forecast_set = clf.predict(X_lately)
print(forecast_set,accuracy, forecast_out)
df['Forecast']=np.nan
last_date= df.iloc[-1].name
last_unix = last_date.timestamp()
one_day=86400
next_unix = last_unix + one_day
for i in forecast_set:
next_date = datetime.datetime.fromtimestamp(next_unix)
next_unix += one_day
df.loc[next_date] = [ np.nan for _ in range(len(df.columns)-1)] + [i]
print (df.tail())
df['Adj. Close'].plot()
df['Forecast'].plot()
plt.legend(loc=4)
plt.xlabel('Date')
plt.ylabel('Price')
plt.show()
#fully accurate forecasting code
| [
"datetime.datetime.fromtimestamp",
"matplotlib.pyplot.ylabel",
"sklearn.model_selection.train_test_split",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.xlabel",
"numpy.array",
"quandl.get",
"matplotlib.style.use",
"sklearn.linear_model.LinearRegression",
"sklearn.preprocessing.scale",
"matplot... | [((284, 303), 'matplotlib.style.use', 'style.use', (['"""ggplot"""'], {}), "('ggplot')\n", (293, 303), False, 'from matplotlib import style\n'), ((312, 336), 'quandl.get', 'quandl.get', (['"""WIKI/GOOGL"""'], {}), "('WIKI/GOOGL')\n", (322, 336), False, 'import quandl, math, datetime\n'), ((844, 866), 'sklearn.preprocessing.scale', 'preprocessing.scale', (['X'], {}), '(X)\n', (863, 866), False, 'from sklearn import preprocessing, svm\n'), ((950, 971), 'numpy.array', 'np.array', (["df['Label']"], {}), "(df['Label'])\n", (958, 971), True, 'import numpy as np\n'), ((1007, 1044), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'test_size': '(0.2)'}), '(X, y, test_size=0.2)\n', (1023, 1044), False, 'from sklearn.model_selection import train_test_split\n'), ((1052, 1079), 'sklearn.linear_model.LinearRegression', 'LinearRegression', ([], {'n_jobs': '(-1)'}), '(n_jobs=-1)\n', (1068, 1079), False, 'from sklearn.linear_model import LinearRegression\n'), ((1614, 1631), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '(4)'}), '(loc=4)\n', (1624, 1631), True, 'import matplotlib.pyplot as plt\n'), ((1633, 1651), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Date"""'], {}), "('Date')\n", (1643, 1651), True, 'import matplotlib.pyplot as plt\n'), ((1653, 1672), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Price"""'], {}), "('Price')\n", (1663, 1672), True, 'import matplotlib.pyplot as plt\n'), ((1674, 1684), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1682, 1684), True, 'import matplotlib.pyplot as plt\n'), ((1404, 1446), 'datetime.datetime.fromtimestamp', 'datetime.datetime.fromtimestamp', (['next_unix'], {}), '(next_unix)\n', (1435, 1446), False, 'import quandl, math, datetime\n')] |
import numpy as np
# iterator for X with multiple observation sequences
# copied from hmmlearn
def iter_from_X_lengths(X, lengths):
if lengths is None:
yield 0, len(X)
else:
n_samples = X.shape[0]
end = np.cumsum(lengths).astype(np.int32)
start = end - lengths
if end[-1] > n_samples:
raise ValueError("more than {:d} samples in lengths array {!s}"
.format(n_samples, lengths))
for i in range(len(lengths)):
yield start[i], end[i]
# masks error when applying log(0)
# copied from hmmlearn
def log_mask_zero(a):
with np.errstate(divide="ignore"):
return np.log(a) | [
"numpy.errstate",
"numpy.log",
"numpy.cumsum"
] | [((632, 660), 'numpy.errstate', 'np.errstate', ([], {'divide': '"""ignore"""'}), "(divide='ignore')\n", (643, 660), True, 'import numpy as np\n'), ((677, 686), 'numpy.log', 'np.log', (['a'], {}), '(a)\n', (683, 686), True, 'import numpy as np\n'), ((236, 254), 'numpy.cumsum', 'np.cumsum', (['lengths'], {}), '(lengths)\n', (245, 254), True, 'import numpy as np\n')] |
import numpy as np
def fg_bg_data(labels,fg_labels):
'''
given cifar data convert into fg and background data
inputs : original cifar labels as list, foreground labels as list
returns cifar labels as binary labels with foreground data as class 0 and background data as class 1
'''
labels = np.array(labels)
fg_indices = np.logical_or(np.logical_or(labels==fg_labels[0],labels==fg_labels[1]),labels==fg_labels[2])
bg_indices = np.logical_not(fg_indices)
labels[fg_indices] = 0
labels[bg_indices] = 1
return list(labels)
def fg_data(data,labels,fg_labels):
'''
given cifar data convert into foreground data
inputs : original cifar labels as list, foreground labels as list
returns cifar labels as binary labels with foreground data as class 0 class 1 and so on
'''
labels = np.array(labels)
fg_indices = np.logical_or(np.logical_or(labels==fg_labels[0],labels==fg_labels[1]),labels==fg_labels[2])
cls_max = np.max(fg_labels)
if cls_max >2:
labels = labels[fg_indices] - cls_max
else:
labels = labels[fg_indices]
return data[fg_indices],list(labels) | [
"numpy.array",
"numpy.logical_not",
"numpy.logical_or",
"numpy.max"
] | [((321, 337), 'numpy.array', 'np.array', (['labels'], {}), '(labels)\n', (329, 337), True, 'import numpy as np\n'), ((462, 488), 'numpy.logical_not', 'np.logical_not', (['fg_indices'], {}), '(fg_indices)\n', (476, 488), True, 'import numpy as np\n'), ((837, 853), 'numpy.array', 'np.array', (['labels'], {}), '(labels)\n', (845, 853), True, 'import numpy as np\n'), ((975, 992), 'numpy.max', 'np.max', (['fg_labels'], {}), '(fg_labels)\n', (981, 992), True, 'import numpy as np\n'), ((367, 428), 'numpy.logical_or', 'np.logical_or', (['(labels == fg_labels[0])', '(labels == fg_labels[1])'], {}), '(labels == fg_labels[0], labels == fg_labels[1])\n', (380, 428), True, 'import numpy as np\n'), ((883, 944), 'numpy.logical_or', 'np.logical_or', (['(labels == fg_labels[0])', '(labels == fg_labels[1])'], {}), '(labels == fg_labels[0], labels == fg_labels[1])\n', (896, 944), True, 'import numpy as np\n')] |
"""
References
------------
1. https://www.baeldung.com/cs/svm-multiclass-classification
2. https://shomy.top/2017/02/20/svm04-soft-margin/
3. http://people.csail.mit.edu/dsontag/courses/ml13/slides/lecture6.pdf
"""
import pandas as pd
import numpy as np
class MulticlassSVM:
"""
Simply use one-vs-rest
"""
def __init__(self, n_classes=3, ploy_dim=2):
self.alphas = None
self.ploy_dim = ploy_dim
self.n_classes = n_classes
def kernel_fn(self, p_vec, q_vec):
return (p_vec.dot(q_vec))**self.ploy_dim
def fit(self, X, y):
n_samples, n_dim = X.shape
# record down data
self.data = X
self.n_dim = n_dim
self.n_samples = n_samples
# this is tricky as usually we use alpha to weight samples
# but they use \alpha_i \y_i to represent the fake weighting w_i
self.alphas = np.zeros((self.n_classes, n_samples))
# ------------------------------------------------------
# How to optimize this loop? Levae Douglas as exercise
for i in range(self.n_samples):
cls_vals = self._get_classifier_vals(X[i, :])
preds = self.sign(cls_vals)
truth = self._label_to_custom_onehot(y[i])
for j in range(self.n_classes):
if cls_vals[j]*truth[j] <= 0: # not the same side
# incorrect prediction, apply delta rule
self.alphas[j, i] -= preds[j]
def _get_classifier_vals(self, x):
"""
This is the classifier:
.. math::
w(x) = \sum_i \alpha_i K(x_i, x)
Args:
x (np.ndarray): the input feature you would like to classify
Return:
An array of size (n_classes,). Each value represents the inner product
sum between support vectors of a classifier and the incoming feature.
"""
assert x.shape == (self.n_dim,)
ret = np.zeros((self.n_classes,))
for i in range(self.n_samples):
kernel_val = self.kernel_fn(x, self.data[i, :])
weights = self.alphas[:, i]
# print(f"weights= {weights}")
ret += kernel_val*weights
assert ret.shape == (self.n_classes,)
return ret
def predict(self, x):
cls_vals = self._get_classifier_vals(x)
return np.argmax(cls_vals)
@staticmethod
def sign(val):
ret = np.where(val <= 0.0, -1, 1)
return ret
def _label_to_custom_onehot(self, label: int):
"""
Similar to one-hot encoding, we mark the truth one as 1, otherwise -1
Example:
>>> svm = MulticlassSVM(n_classes=5)
>>> svm._label_to_custom_onehot(2)
[-1, -1, 1, -1, -1]
>>> svm._label_to_custom_onehot(4)
[-1, -1, -1, -1, 1]
"""
ret = np.full((self.n_classes,), -1)
ret[label] = 1
return ret
def load_dat(fname):
dat = pd.read_csv(fname, sep='\s+', header=None).to_numpy()
y = dat[:, 0].astype(np.int) - 1 # we are zero-based indexing
X = dat[:, 1:].astype(np.float32)
return X, y
if __name__ == "__main__":
X_train, y_train = load_dat("dtrain123.dat")
X_train = X_train[:20, :]
y_train = y_train[:20]
svm = MulticlassSVM(n_classes=3)
svm.fit(X_train, y_train)
nsamples = X_train.shape[0]
correct = 0
for i in range(nsamples):
x = X_train[i, :]
y = y_train[i]
if y == svm.predict(x):
correct += 1
# this is different from the mathematica impl., we eval the svm after
# training
print("train correct = ", correct)
print("train acc. = ", correct / nsamples)
print("train misstake = ", nsamples - correct)
# -------------------------------------------------
# pd.read_csv(filename, sep='\s+',header=None)
X_test, y_test = load_dat("dtest123.dat")
nsamples = X_test.shape[0]
correct = 0
for i in range(nsamples):
x = X_test[i, :]
y = y_test[i]
if y == svm.predict(x):
correct += 1
print("test correct = ", correct)
print("test acc. = ", correct / nsamples)
print("test misstake = ", nsamples - correct)
| [
"pandas.read_csv",
"numpy.where",
"numpy.argmax",
"numpy.zeros",
"numpy.full"
] | [((890, 927), 'numpy.zeros', 'np.zeros', (['(self.n_classes, n_samples)'], {}), '((self.n_classes, n_samples))\n', (898, 927), True, 'import numpy as np\n'), ((1956, 1983), 'numpy.zeros', 'np.zeros', (['(self.n_classes,)'], {}), '((self.n_classes,))\n', (1964, 1983), True, 'import numpy as np\n'), ((2360, 2379), 'numpy.argmax', 'np.argmax', (['cls_vals'], {}), '(cls_vals)\n', (2369, 2379), True, 'import numpy as np\n'), ((2432, 2459), 'numpy.where', 'np.where', (['(val <= 0.0)', '(-1)', '(1)'], {}), '(val <= 0.0, -1, 1)\n', (2440, 2459), True, 'import numpy as np\n'), ((2852, 2882), 'numpy.full', 'np.full', (['(self.n_classes,)', '(-1)'], {}), '((self.n_classes,), -1)\n', (2859, 2882), True, 'import numpy as np\n'), ((2958, 3001), 'pandas.read_csv', 'pd.read_csv', (['fname'], {'sep': '"""\\\\s+"""', 'header': 'None'}), "(fname, sep='\\\\s+', header=None)\n", (2969, 3001), True, 'import pandas as pd\n')] |
import numpy as np
from ..utils.dictionary import get_lambda_max
def simulate_data(n_times, n_times_atom, n_atoms, n_channels, noise_level,
random_state=None):
rng = np.random.RandomState(random_state)
rho = n_atoms / (n_channels * n_times_atom)
D = rng.normal(scale=10.0, size=(n_atoms, n_channels, n_times_atom))
D = np.array(D)
nD = np.sqrt((D * D).sum(axis=-1, keepdims=True))
D /= nD + (nD == 0)
Z = (rng.rand(n_atoms, (n_times - 1) * n_times_atom + 1) < rho
).astype(np.float64)
Z *= rng.normal(scale=10, size=(n_atoms, (n_times - 1) * n_times_atom + 1))
X = np.array([[np.convolve(zk, dk, 'full') for dk in Dk]
for Dk, zk in zip(D, Z)]).sum(axis=0)
X += noise_level * rng.normal(size=X.shape)
lmbd_max = get_lambda_max(X, D)
return X, D, lmbd_max
| [
"numpy.array",
"numpy.convolve",
"numpy.random.RandomState"
] | [((191, 226), 'numpy.random.RandomState', 'np.random.RandomState', (['random_state'], {}), '(random_state)\n', (212, 226), True, 'import numpy as np\n'), ((356, 367), 'numpy.array', 'np.array', (['D'], {}), '(D)\n', (364, 367), True, 'import numpy as np\n'), ((644, 671), 'numpy.convolve', 'np.convolve', (['zk', 'dk', '"""full"""'], {}), "(zk, dk, 'full')\n", (655, 671), True, 'import numpy as np\n')] |
import numpy as np
#https://github.com/Robonchu/PythonSimpleManipulation
def skew_mat(vector):
mat = np.zeros((3, 3))
mat[0, 1] = -vector[2]
mat[0, 2] = vector[1]
mat[1, 0] = vector[2]
mat[1, 2] = -vector[0]
mat[2, 0] = -vector[1]
mat[2, 1] = vector[0]
return mat
def rodrigues_mat(vector, angle):
mat = np.eye(3) + skew_mat(vector) * np.sin(angle) + skew_mat(
vector) @ skew_mat(vector) * (1.0 - np.cos(angle))
return mat
def calc_fk(angles, vectors, lengths, dof=6):
iter_num = dof + 1
pos = [0, 0, 0]
R = np.eye(3)
pos_list = np.zeros((dof + 2, 3))
R_list = np.zeros((dof + 2, 3, 3))
pos_list[0] = pos
R_list[0] = R
# Calculate Forward Kinematics
for i in range(iter_num):
pos = pos + R @ lengths[i].T
R = R @ rodrigues_mat(vectors[i], angles[i])
pos_list[i + 1] = pos
R_list[i + 1] = R
return pos, R, pos_list, R_list
| [
"numpy.sin",
"numpy.eye",
"numpy.zeros",
"numpy.cos"
] | [((107, 123), 'numpy.zeros', 'np.zeros', (['(3, 3)'], {}), '((3, 3))\n', (115, 123), True, 'import numpy as np\n'), ((572, 581), 'numpy.eye', 'np.eye', (['(3)'], {}), '(3)\n', (578, 581), True, 'import numpy as np\n'), ((597, 619), 'numpy.zeros', 'np.zeros', (['(dof + 2, 3)'], {}), '((dof + 2, 3))\n', (605, 619), True, 'import numpy as np\n'), ((633, 658), 'numpy.zeros', 'np.zeros', (['(dof + 2, 3, 3)'], {}), '((dof + 2, 3, 3))\n', (641, 658), True, 'import numpy as np\n'), ((343, 352), 'numpy.eye', 'np.eye', (['(3)'], {}), '(3)\n', (349, 352), True, 'import numpy as np\n'), ((374, 387), 'numpy.sin', 'np.sin', (['angle'], {}), '(angle)\n', (380, 387), True, 'import numpy as np\n'), ((444, 457), 'numpy.cos', 'np.cos', (['angle'], {}), '(angle)\n', (450, 457), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
import numpy as np
def Chapman(Q, b_LH, a, return_exceed=False):
"""Chapman filter (Chapman, 1991)
Args:
Q (np.array): streamflow
a (float): recession coefficient
"""
b = [b_LH[0]]
x = b_LH[0]
for i in range(Q.shape[0] - 1):
x = (3 * a - 1) / (3 - a) * x + (1 - a) / (3 - a) * (Q[i + 1] + Q[i])
b.append(x)
b = np.array(b)
mask = b[1:] > Q[1:]
b[1:][mask] = Q[1:][mask]
if return_exceed:
return np.append(b, np.count_nonzero(mask))
return b
| [
"numpy.count_nonzero",
"numpy.array"
] | [((398, 409), 'numpy.array', 'np.array', (['b'], {}), '(b)\n', (406, 409), True, 'import numpy as np\n'), ((515, 537), 'numpy.count_nonzero', 'np.count_nonzero', (['mask'], {}), '(mask)\n', (531, 537), True, 'import numpy as np\n')] |
#!/usr/bin/env python
# Copyright 2020 Johns Hopkins University (Author: <NAME>)
# Apache 2.0
# This script is based on the Bayesian HMM-based xvector clustering
# code released by BUTSpeech at: https://github.com/BUTSpeechFIT/VBx.
# Note that this assumes that the provided labels are for a single
# recording. So this should be called from a script such as
# vb_hmm_xvector.sh which can divide all labels into per recording
# labels.
import sys, argparse, struct, re
import numpy as np
import itertools
import kaldi_io
from scipy.special import softmax
import VB_diarization
########### HELPER FUNCTIONS #####################################
def get_args():
parser = argparse.ArgumentParser(
description="""This script performs Bayesian HMM-based
clustering of x-vectors for one recording""",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--init-smoothing", type=float, default=10,
help="AHC produces hard assignments of x-vetors to speakers."
" These are smoothed to soft assignments as the initialization"
" for VB-HMM. This parameter controls the amount of smoothing."
" Not so important, high value (e.g. 10) is OK => keeping hard assigment")
parser.add_argument("--loop-prob", type=float, default=0.80,
help="probability of not switching speakers between frames")
parser.add_argument("--fa", type=float, default=0.4,
help="scale sufficient statistics collected using UBM")
parser.add_argument("--fb", type=float, default=11,
help="speaker regularization coefficient Fb (controls final # of speaker)")
parser.add_argument("--overlap-rttm", type=str,
help="path to an RTTM file containing overlap segments. If provided,"
"multiple speaker labels will be allocated to these segments.")
parser.add_argument("xvector_ark_file", type=str,
help="Ark file containing xvectors for all subsegments")
parser.add_argument("plda", type=str,
help="path to PLDA model")
parser.add_argument("input_label_file", type=str,
help="path of input label file")
parser.add_argument("output_label_file", type=str,
help="path of output label file")
args = parser.parse_args()
return args
def read_labels_file(label_file):
segments = []
labels = []
with open(label_file, 'r') as f:
for line in f.readlines():
segment, label = line.strip().split()
segments.append(segment)
labels.append(int(label))
return segments, labels
def write_labels_file(seg2label, out_file):
f = open(out_file, 'w')
for seg in sorted(seg2label.keys()):
label = seg2label[seg]
if type(label) is tuple:
f.write("{} {}\n".format(seg, label[0]))
f.write("{} {}\n".format(seg, label[1]))
else:
f.write("{} {}\n".format(seg, label))
f.close()
return
def get_overlap_decision(overlap_segs, subsegment, frac = 0.5):
""" Returns true if at least 'frac' fraction of the subsegment lies
in the overlap_segs."""
start_time = subsegment[0]
end_time = subsegment[1]
dur = end_time - start_time
total_ovl = 0
for seg in overlap_segs:
cur_start, cur_end = seg
if (cur_start >= end_time):
break
ovl_start = max(start_time, cur_start)
ovl_end = min(end_time, cur_end)
ovl_time = max(0, ovl_end-ovl_start)
total_ovl += ovl_time
return (total_ovl >= frac * dur)
def get_overlap_vector(overlap_rttm, segments):
reco_id = '_'.join(segments[0].split('_')[:3])
overlap_segs = []
with open(overlap_rttm, 'r') as f:
for line in f.readlines():
parts = line.strip().split()
if (parts[1] == reco_id):
overlap_segs.append((float(parts[3]), float(parts[3]) + float(parts[4])))
ol_vec = np.zeros(len(segments))
overlap_segs.sort(key=lambda x: x[0])
for i, segment in enumerate(segments):
parts = re.split('_|-',segment)
start_time = (float(parts[3]) + float(parts[5]))/100
end_time = (float(parts[3]) + float(parts[6]))/100
is_overlap = get_overlap_decision(overlap_segs, (start_time, end_time))
if is_overlap:
ol_vec[i] = 1
print ("{}: {} fraction of segments are overlapping".format(id, ol_vec.sum()/len(ol_vec)))
return ol_vec
def read_args(args):
segments, labels = read_labels_file(args.input_label_file)
xvec_all = dict(kaldi_io.read_vec_flt_ark(args.xvector_ark_file))
xvectors = []
for segment in segments:
xvectors.append(xvec_all[segment])
_, _, plda_psi = kaldi_io.read_plda(args.plda)
if (args.overlap_rttm is not None):
print('Getting overlap segments...')
overlaps = get_overlap_vector(args.overlap_rttm, segments)
else:
overlaps = None
return xvectors, segments, labels, plda_psi, overlaps
###################################################################
def vb_hmm(segments, in_labels, xvectors, overlaps, plda_psi, init_smoothing, loop_prob, fa, fb):
x = np.array(xvectors)
dim = x.shape[1]
# Smooth the hard labels obtained from AHC to soft assignments of x-vectors to speakers
q_init = np.zeros((len(in_labels), np.max(in_labels)+1))
q_init[range(len(in_labels)), in_labels] = 1.0
q_init = softmax(q_init*init_smoothing, axis=1)
# Prepare model for VB-HMM clustering
ubmWeights = np.array([1.0])
ubmMeans = np.zeros((1,dim))
invSigma= np.ones((1,dim))
V=np.diag(np.sqrt(plda_psi[:dim]))[:,np.newaxis,:]
# Use VB-HMM for x-vector clustering. Instead of i-vector extractor model, we use PLDA
# => GMM with only 1 component, V derived across-class covariance, and invSigma is inverse
# within-class covariance (i.e. identity)
q, _, _ = VB_diarization.VB_diarization(x, ubmMeans, invSigma, ubmWeights, V, pi=None,
gamma=q_init, maxSpeakers=q_init.shape[1], maxIters=40, epsilon=1e-6, loopProb=loop_prob,
Fa=fa, Fb=fb)
labels = np.argsort(q, axis=1)[:,[-1,-2]]
if overlaps is not None:
final_labels = []
for i in range(len(overlaps)):
if (overlaps[i] == 1):
final_labels.append((labels[i,0], labels[i,1]))
else:
final_labels.append(labels[i,0])
else:
final_labels = labels[:,0]
return {seg:label for seg,label in zip(segments,final_labels)}
def main():
args = get_args()
xvectors, segments, labels, plda_psi, overlaps = read_args(args)
seg2label_vb = vb_hmm(segments, labels, xvectors, overlaps, plda_psi, args.init_smoothing,
args.loop_prob, args.fa, args.fb)
write_labels_file(seg2label_vb, args.output_label_file)
if __name__=="__main__":
main()
| [
"re.split",
"numpy.sqrt",
"numpy.ones",
"argparse.ArgumentParser",
"kaldi_io.read_plda",
"kaldi_io.read_vec_flt_ark",
"numpy.max",
"numpy.argsort",
"numpy.array",
"numpy.zeros",
"VB_diarization.VB_diarization",
"scipy.special.softmax"
] | [((679, 881), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""This script performs Bayesian HMM-based\n clustering of x-vectors for one recording"""', 'formatter_class': 'argparse.ArgumentDefaultsHelpFormatter'}), '(description=\n """This script performs Bayesian HMM-based\n clustering of x-vectors for one recording"""\n , formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n', (702, 881), False, 'import sys, argparse, struct, re\n'), ((4857, 4886), 'kaldi_io.read_plda', 'kaldi_io.read_plda', (['args.plda'], {}), '(args.plda)\n', (4875, 4886), False, 'import kaldi_io\n'), ((5308, 5326), 'numpy.array', 'np.array', (['xvectors'], {}), '(xvectors)\n', (5316, 5326), True, 'import numpy as np\n'), ((5566, 5606), 'scipy.special.softmax', 'softmax', (['(q_init * init_smoothing)'], {'axis': '(1)'}), '(q_init * init_smoothing, axis=1)\n', (5573, 5606), False, 'from scipy.special import softmax\n'), ((5665, 5680), 'numpy.array', 'np.array', (['[1.0]'], {}), '([1.0])\n', (5673, 5680), True, 'import numpy as np\n'), ((5696, 5714), 'numpy.zeros', 'np.zeros', (['(1, dim)'], {}), '((1, dim))\n', (5704, 5714), True, 'import numpy as np\n'), ((5728, 5745), 'numpy.ones', 'np.ones', (['(1, dim)'], {}), '((1, dim))\n', (5735, 5745), True, 'import numpy as np\n'), ((6048, 6237), 'VB_diarization.VB_diarization', 'VB_diarization.VB_diarization', (['x', 'ubmMeans', 'invSigma', 'ubmWeights', 'V'], {'pi': 'None', 'gamma': 'q_init', 'maxSpeakers': 'q_init.shape[1]', 'maxIters': '(40)', 'epsilon': '(1e-06)', 'loopProb': 'loop_prob', 'Fa': 'fa', 'Fb': 'fb'}), '(x, ubmMeans, invSigma, ubmWeights, V, pi=None,\n gamma=q_init, maxSpeakers=q_init.shape[1], maxIters=40, epsilon=1e-06,\n loopProb=loop_prob, Fa=fa, Fb=fb)\n', (6077, 6237), False, 'import VB_diarization\n'), ((4204, 4228), 're.split', 're.split', (['"""_|-"""', 'segment'], {}), "('_|-', segment)\n", (4212, 4228), False, 'import sys, argparse, struct, re\n'), ((4696, 4744), 'kaldi_io.read_vec_flt_ark', 'kaldi_io.read_vec_flt_ark', (['args.xvector_ark_file'], {}), '(args.xvector_ark_file)\n', (4721, 4744), False, 'import kaldi_io\n'), ((6260, 6281), 'numpy.argsort', 'np.argsort', (['q'], {'axis': '(1)'}), '(q, axis=1)\n', (6270, 6281), True, 'import numpy as np\n'), ((5759, 5782), 'numpy.sqrt', 'np.sqrt', (['plda_psi[:dim]'], {}), '(plda_psi[:dim])\n', (5766, 5782), True, 'import numpy as np\n'), ((5480, 5497), 'numpy.max', 'np.max', (['in_labels'], {}), '(in_labels)\n', (5486, 5497), True, 'import numpy as np\n')] |
from copy import copy
import numpy as np
from gym_chess import ChessEnvV1
from gym_chess.envs.chess_v1 import (
KING_ID,
QUEEN_ID,
ROOK_ID,
BISHOP_ID,
KNIGHT_ID,
PAWN_ID,
)
from gym_chess.test.utils import run_test_funcs
# Blank board
BASIC_BOARD = np.array([[0] * 8] * 8, dtype=np.int8)
# Pawn basic movements
def test_pawn_basic_moves():
BOARD = copy(BASIC_BOARD)
BOARD[6, 0] = PAWN_ID
BOARD[1, 0] = -PAWN_ID
env = ChessEnvV1(opponent="none", initial_state=BOARD)
# player_1
actions = env.get_possible_actions()
env.step(actions[0])
# player_2
actions = env.get_possible_actions()
env.step(actions[0])
# player_3
actions = env.get_possible_actions()
env.step(actions[0])
# player_4
actions = env.get_possible_actions()
env.step(actions[0])
EXPECTED_BOARD = copy(BASIC_BOARD)
EXPECTED_BOARD[4, 0] = PAWN_ID
EXPECTED_BOARD[3, 0] = -PAWN_ID
assert (env.state == EXPECTED_BOARD).all()
if __name__ == "__main__":
run_test_funcs(__name__)
| [
"gym_chess.test.utils.run_test_funcs",
"numpy.array",
"copy.copy",
"gym_chess.ChessEnvV1"
] | [((276, 314), 'numpy.array', 'np.array', (['([[0] * 8] * 8)'], {'dtype': 'np.int8'}), '([[0] * 8] * 8, dtype=np.int8)\n', (284, 314), True, 'import numpy as np\n'), ((380, 397), 'copy.copy', 'copy', (['BASIC_BOARD'], {}), '(BASIC_BOARD)\n', (384, 397), False, 'from copy import copy\n'), ((461, 509), 'gym_chess.ChessEnvV1', 'ChessEnvV1', ([], {'opponent': '"""none"""', 'initial_state': 'BOARD'}), "(opponent='none', initial_state=BOARD)\n", (471, 509), False, 'from gym_chess import ChessEnvV1\n'), ((856, 873), 'copy.copy', 'copy', (['BASIC_BOARD'], {}), '(BASIC_BOARD)\n', (860, 873), False, 'from copy import copy\n'), ((1025, 1049), 'gym_chess.test.utils.run_test_funcs', 'run_test_funcs', (['__name__'], {}), '(__name__)\n', (1039, 1049), False, 'from gym_chess.test.utils import run_test_funcs\n')] |
from arcgis import GIS
from arcgis.features import GeoAccessor, GeoSeriesAccessor
import arcpy
from arcpy import env
from arcpy.sa import *
import numpy as np
import os
import pandas as pd
#####
arcpy.env.overwriteOutput = True
arcpy.CheckOutExtension("Spatial")
def select_feature_by_attributes_arcgis(input,Attri_NM,Attri_v,output):
where_clause = '"%s" IN' % (Attri_NM)
where_clause = where_clause + " ("
for i in range(0,len(Attri_v)):
if i == 0:
where_clause = where_clause + str(Attri_v[i])
else:
where_clause = where_clause + "," + str(Attri_v[i])
where_clause = where_clause + ")"
arcpy.Select_analysis(input, output, where_clause)
return
##################
def Remove_Unselected_Lake_Attribute_In_Finalcatinfo_Arcgis(finalcat_ply, Conn_Lake_Ids):
"""Functions will set lake id not in Conn_Lake_Ids to -1.2345 in attribute
table of Path_Finalcatinfo
----------
Notes
-------
Returns:
-------
None, the attribute table of Path_shpfile will be updated
"""
mask1 = np.logical_not(finalcat_ply['HyLakeId'].isin(Conn_Lake_Ids))
mask2 = finalcat_ply['Lake_Cat'] != 2
mask = np.logical_and(mask1,mask2)
finalcat_ply.loc[mask,'HyLakeId'] = 0
finalcat_ply.loc[mask,'LakeVol'] = 0
finalcat_ply.loc[mask,'LakeArea'] = 0
finalcat_ply.loc[mask,'LakeDepth'] = 0
finalcat_ply.loc[mask,'Laketype'] =0
finalcat_ply.loc[mask,'Lake_Cat'] = 0
return finalcat_ply
def save_modified_attributes_to_outputs(mapoldnew_info,tempfolder,OutputFolder,cat_name,riv_name,Path_final_riv,dis_col_name='SubId'):
mapoldnew_info.spatial.to_featureclass(location=os.path.join(tempfolder,'updateattri.shp'),overwrite=True,sanitize_columns=False)
arcpy.Dissolve_management(os.path.join(tempfolder,'updateattri.shp'), os.path.join(OutputFolder,cat_name), [dis_col_name])
arcpy.JoinField_management(os.path.join(OutputFolder,cat_name), dis_col_name, os.path.join(tempfolder,'updateattri.shp'), dis_col_name)
arcpy.DeleteField_management(os.path.join(OutputFolder,cat_name),
["SubId_1", "Id","nsubid2", "nsubid","ndownsubid","Old_SubId","Old_DowSub","Join_Count","TARGET_FID","Id","SubID_Oldr","HRU_ID_N_1","HRU_ID_N_2","facters"]
)
if riv_name != '#':
arcpy.CalculateGeometryAttributes_management(os.path.join(OutputFolder, cat_name), [["centroid_x", "CENTROID_X"], ["centroid_y", "CENTROID_Y"]])
cat_colnms = mapoldnew_info.columns
drop_cat_colnms = cat_colnms[cat_colnms.isin(["SHAPE","SubId_1", "Id","nsubid2", "nsubid","ndownsubid","Old_DowSub","Join_Count","TARGET_FID","Id","SubID_Oldr","HRU_ID_N_1","HRU_ID_N_2","facters","Old_DowSubId"])]
cat_pd = mapoldnew_info.drop(columns=drop_cat_colnms)
riv_pd = pd.DataFrame.spatial.from_featureclass(Path_final_riv)
riv_pd['Old_SubId'] = riv_pd['SubId']
# remove all columns
riv_pd = riv_pd[['SHAPE','Old_SubId']]
riv_pd = pd.merge(riv_pd, cat_pd, on='Old_SubId', how='left')
riv_pd = riv_pd.drop(columns=['Old_SubId'])
riv_pd.spatial.to_featureclass(location=os.path.join(tempfolder,'riv_attri.shp'),overwrite=True,sanitize_columns=False)
arcpy.Dissolve_management(os.path.join(tempfolder,'riv_attri.shp'), os.path.join(OutputFolder,riv_name), ["SubId"])
arcpy.JoinField_management(os.path.join(OutputFolder,riv_name), "SubId", os.path.join(tempfolder,'riv_attri.shp'), "SubId")
arcpy.DeleteField_management(os.path.join(OutputFolder,riv_name),
["SubId_1", "Id","nsubid2", "nsubid","ndownsubid","Old_SubId","Old_DowSub","Join_Count","TARGET_FID","Id","SubID_Oldr","HRU_ID_N_1","HRU_ID_N_2","facters"]
)
def clean_attribute_name_arcgis(table,names):
remove_column_names = table.columns[np.logical_not(np.isin(table.columns,names))]
table = table.drop(columns=remove_column_names)
return table
| [
"numpy.logical_and",
"arcpy.Select_analysis",
"arcpy.CheckOutExtension",
"pandas.merge",
"os.path.join",
"numpy.isin",
"pandas.DataFrame.spatial.from_featureclass"
] | [((230, 264), 'arcpy.CheckOutExtension', 'arcpy.CheckOutExtension', (['"""Spatial"""'], {}), "('Spatial')\n", (253, 264), False, 'import arcpy\n'), ((659, 709), 'arcpy.Select_analysis', 'arcpy.Select_analysis', (['input', 'output', 'where_clause'], {}), '(input, output, where_clause)\n', (680, 709), False, 'import arcpy\n'), ((1215, 1243), 'numpy.logical_and', 'np.logical_and', (['mask1', 'mask2'], {}), '(mask1, mask2)\n', (1229, 1243), True, 'import numpy as np\n'), ((1830, 1873), 'os.path.join', 'os.path.join', (['tempfolder', '"""updateattri.shp"""'], {}), "(tempfolder, 'updateattri.shp')\n", (1842, 1873), False, 'import os\n'), ((1874, 1910), 'os.path.join', 'os.path.join', (['OutputFolder', 'cat_name'], {}), '(OutputFolder, cat_name)\n', (1886, 1910), False, 'import os\n'), ((1958, 1994), 'os.path.join', 'os.path.join', (['OutputFolder', 'cat_name'], {}), '(OutputFolder, cat_name)\n', (1970, 1994), False, 'import os\n'), ((2009, 2052), 'os.path.join', 'os.path.join', (['tempfolder', '"""updateattri.shp"""'], {}), "(tempfolder, 'updateattri.shp')\n", (2021, 2052), False, 'import os\n'), ((2100, 2136), 'os.path.join', 'os.path.join', (['OutputFolder', 'cat_name'], {}), '(OutputFolder, cat_name)\n', (2112, 2136), False, 'import os\n'), ((2841, 2895), 'pandas.DataFrame.spatial.from_featureclass', 'pd.DataFrame.spatial.from_featureclass', (['Path_final_riv'], {}), '(Path_final_riv)\n', (2879, 2895), True, 'import pandas as pd\n'), ((3044, 3096), 'pandas.merge', 'pd.merge', (['riv_pd', 'cat_pd'], {'on': '"""Old_SubId"""', 'how': '"""left"""'}), "(riv_pd, cat_pd, on='Old_SubId', how='left')\n", (3052, 3096), True, 'import pandas as pd\n'), ((1718, 1761), 'os.path.join', 'os.path.join', (['tempfolder', '"""updateattri.shp"""'], {}), "(tempfolder, 'updateattri.shp')\n", (1730, 1761), False, 'import os\n'), ((2395, 2431), 'os.path.join', 'os.path.join', (['OutputFolder', 'cat_name'], {}), '(OutputFolder, cat_name)\n', (2407, 2431), False, 'import os\n'), ((3311, 3352), 'os.path.join', 'os.path.join', (['tempfolder', '"""riv_attri.shp"""'], {}), "(tempfolder, 'riv_attri.shp')\n", (3323, 3352), False, 'import os\n'), ((3353, 3389), 'os.path.join', 'os.path.join', (['OutputFolder', 'riv_name'], {}), '(OutputFolder, riv_name)\n', (3365, 3389), False, 'import os\n'), ((3436, 3472), 'os.path.join', 'os.path.join', (['OutputFolder', 'riv_name'], {}), '(OutputFolder, riv_name)\n', (3448, 3472), False, 'import os\n'), ((3482, 3523), 'os.path.join', 'os.path.join', (['tempfolder', '"""riv_attri.shp"""'], {}), "(tempfolder, 'riv_attri.shp')\n", (3494, 3523), False, 'import os\n'), ((3570, 3606), 'os.path.join', 'os.path.join', (['OutputFolder', 'riv_name'], {}), '(OutputFolder, riv_name)\n', (3582, 3606), False, 'import os\n'), ((3888, 3917), 'numpy.isin', 'np.isin', (['table.columns', 'names'], {}), '(table.columns, names)\n', (3895, 3917), True, 'import numpy as np\n'), ((3197, 3238), 'os.path.join', 'os.path.join', (['tempfolder', '"""riv_attri.shp"""'], {}), "(tempfolder, 'riv_attri.shp')\n", (3209, 3238), False, 'import os\n')] |
from breidablik.interpolate.spectra import Spectra
import numpy as np
import pytest
import warnings
try:
Spectra()
flag = False
except:
flag = True
# skip these tests if the trained models are not present
pytestmark = pytest.mark.skipif(flag, reason = 'No trained Spectra model')
class Test_find_abund:
@classmethod
def setup_class(cls):
cls.models = Spectra()
def test_monontonic(self):
with pytest.raises(ValueError):
Test_find_abund.models.find_abund([1, 3, 2], [4, 5, 6], [1, 1, 1], 4000, 1.5, 0)
def test_shape(self):
with pytest.raises(ValueError):
Test_find_abund.models.find_abund([1, 2], [1], [1], 5000, 2.5, -2)
Test_find_abund.models.find_abund([1], [1, 2], [1], 5000, 2.5, -2)
Test_find_abund.models.find_abund([1], [1], [1, 2], 5000, 2.5, -2)
def test_dimension(self):
with pytest.raises(ValueError):
Test_find_abund.models.find_abund([[1, 2], [2, 3]], [1], [1], 5000, 2.5, -2)
Test_find_abund.models.find_abund([1], [[1, 2], [2, 3]], [1], 5000, 2.5, -2)
Test_find_abund.models.find_abund([1], [1], [[1, 2], [2, 3]], 5000, 2.5, -2)
def test_method(self):
with pytest.raises(ValueError):
Test_find_abund.models.find_abund([1, 2, 3], [4, 5, 6], [1, 1, 1], 5000, 1, 1, method = 'hi')
def test_min_max_abund(self):
with pytest.raises(ValueError):
Test_find_abund.models.find_abund([1], [1], [1], 1, 1, 1, min_abund = 8, max_abund = -1)
def test_abund_prior_warning(self):
with warnings.catch_warnings(record = True) as w:
warnings.simplefilter('always')
Test_find_abund.models.find_abund([600, 700], [1, 0.5], [0.5, 0.5], 5000, 2.5, -2, method = 'chisq', prior = [1, 2, 3], abunds = [1, 2, 3])
Test_find_abund.models.find_abund([600, 700], [1, 0.9], [0.5, 0.5], 5000, 2.5, -2, prior = [1, 2, 3])
Test_find_abund.models.find_abund([600, 700], [1, 0.9], [0.5, 0.5], 5000, 2.5, -2, abunds = [1, 2, 3])
assert len(w) == 3
for i in range(len(w)):
assert issubclass(w[i].category, UserWarning)
def test_wl_overlap(self):
with pytest.raises(ValueError):
Test_find_abund.models.find_abund([1, 2], [1, 0.6], [0.1, 0.21], 5000, 4.5, -1)
def test_abund_prior_shape(self):
with pytest.raises(ValueError):
Test_find_abund.models.find_abund([680, 690], [1, 1], [1, 1], 5000, 2.5, -2, abunds = [1, 2], prior = [1])
Test_find_abund.models.find_abund([680, 690], [1, 1], [1, 1], 5000, 2.5, -2, abunds = [[1, 2]], prior = [[1, 3]])
def test_warning_pred_abund(self):
# define square wave
wls = np.linspace(670.5, 671.4, 1000)
flux = np.full(len(wls), 1)
flux[(670.95 <= wls) & (wls < 670.99)] = 0
flux_err = np.full(len(wls), 0.1)
# catch warning for predicted value outside of grid
with warnings.catch_warnings(record = True) as w:
warnings.simplefilter('always')
Test_find_abund.models.find_abund(wls, flux, flux_err, 6000, 4, -3, method = 'chisq', max_abund = 5)
assert len(w) == 1
assert issubclass(w[0].category, UserWarning)
class Test_predict_flux:
@classmethod
def setup_class(cls):
cls.models = Spectra()
def test_input_shape(self):
with pytest.raises(ValueError):
Test_predict_flux.models.predict_flux([1], 1, 1, 1)
Test_predict_flux.models.predict_flux(1, [1], 1, 1)
Test_predict_flux.models.predict_flux(1, 1, [1], 1)
Test_predict_flux.models.predict_flux(1, 1, 1, [1])
def test_warning_abundance(self):
with warnings.catch_warnings(record = True) as w:
warnings.simplefilter('always')
Test_predict_flux.models.predict_flux(5000, 2.5, -2, -1)
Test_predict_flux.models.predict_flux(5000, 2.5, -2, 5)
assert len(w) == 2
for i in range(len(w)):
assert issubclass(w[i].category, UserWarning)
| [
"warnings.catch_warnings",
"breidablik.interpolate.spectra.Spectra",
"numpy.linspace",
"pytest.raises",
"pytest.mark.skipif",
"warnings.simplefilter"
] | [((231, 290), 'pytest.mark.skipif', 'pytest.mark.skipif', (['flag'], {'reason': '"""No trained Spectra model"""'}), "(flag, reason='No trained Spectra model')\n", (249, 290), False, 'import pytest\n'), ((110, 119), 'breidablik.interpolate.spectra.Spectra', 'Spectra', ([], {}), '()\n', (117, 119), False, 'from breidablik.interpolate.spectra import Spectra\n'), ((382, 391), 'breidablik.interpolate.spectra.Spectra', 'Spectra', ([], {}), '()\n', (389, 391), False, 'from breidablik.interpolate.spectra import Spectra\n'), ((2773, 2804), 'numpy.linspace', 'np.linspace', (['(670.5)', '(671.4)', '(1000)'], {}), '(670.5, 671.4, 1000)\n', (2784, 2804), True, 'import numpy as np\n'), ((3389, 3398), 'breidablik.interpolate.spectra.Spectra', 'Spectra', ([], {}), '()\n', (3396, 3398), False, 'from breidablik.interpolate.spectra import Spectra\n'), ((437, 462), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (450, 462), False, 'import pytest\n'), ((597, 622), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (610, 622), False, 'import pytest\n'), ((905, 930), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (918, 930), False, 'import pytest\n'), ((1240, 1265), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (1253, 1265), False, 'import pytest\n'), ((1421, 1446), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (1434, 1446), False, 'import pytest\n'), ((1603, 1639), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {'record': '(True)'}), '(record=True)\n', (1626, 1639), False, 'import warnings\n'), ((1660, 1691), 'warnings.simplefilter', 'warnings.simplefilter', (['"""always"""'], {}), "('always')\n", (1681, 1691), False, 'import warnings\n'), ((2247, 2272), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (2260, 2272), False, 'import pytest\n'), ((2418, 2443), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (2431, 2443), False, 'import pytest\n'), ((3007, 3043), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {'record': '(True)'}), '(record=True)\n', (3030, 3043), False, 'import warnings\n'), ((3064, 3095), 'warnings.simplefilter', 'warnings.simplefilter', (['"""always"""'], {}), "('always')\n", (3085, 3095), False, 'import warnings\n'), ((3445, 3470), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (3458, 3470), False, 'import pytest\n'), ((3780, 3816), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {'record': '(True)'}), '(record=True)\n', (3803, 3816), False, 'import warnings\n'), ((3837, 3868), 'warnings.simplefilter', 'warnings.simplefilter', (['"""always"""'], {}), "('always')\n", (3858, 3868), False, 'import warnings\n')] |
import os
import sys
import cv2
import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import scipy.misc as sic
class Cube2Equirec(nn.Module):
def __init__(self, cube_length, equ_h):
super().__init__()
self.cube_length = cube_length
self.equ_h = equ_h
equ_w = equ_h * 2
self.equ_w = equ_w
theta = (np.arange(equ_w) / (equ_w-1) - 0.5) * 2 *np.pi
phi = (np.arange(equ_h) / (equ_h-1) - 0.5) * np.pi
theta, phi = np.meshgrid(theta, phi)
x = np.sin(theta) * np.cos(phi)
y = np.sin(phi)
z = np.cos(theta) * np.cos(phi)
xyz = np.concatenate([x[..., None], y[..., None], z[..., None]], axis=-1)
planes = np.asarray([
[0, 0, 1, 1], # z = -1
[0, 1, 0, -1], # y = 1
[0, 0, 1, -1], # z = 1
[1, 0, 0, 1], # x = -1
[1, 0, 0, -1], # x = 1
[0, 1, 0, 1] # y = -1
])
r_lst = np.array([
[0, 1, 0],
[0.5, 0, 0],
[0, 0, 0],
[0, 0.5, 0],
[0, -0.5, 0],
[-0.5, 0, 0]
]) * np.pi
f = cube_length / 2.0
self.K = np.array([
[f, 0, (cube_length-1)/2.0],
[0, f, (cube_length-1)/2.0],
[0, 0, 1]
])
self.R_lst = [cv2.Rodrigues(x)[0] for x in r_lst]
self.mask, self.XY = self._intersection(xyz, planes)
def forward(self, x, mode='bilinear'):
assert mode in ['nearest', 'bilinear']
assert x.shape[0] % 6 == 0
equ_count = x.shape[0] // 6
equi = torch.zeros(equ_count, x.shape[1], self.equ_h, self.equ_w).to(x.device)
for i in range(6):
now = x[i::6, ...]
mask = self.mask[i].to(x.device)
mask = mask[None, ...].repeat(equ_count, x.shape[1], 1, 1)
XY = (self.XY[i].to(x.device)[None, None, :, :].repeat(equ_count, 1, 1, 1) / (self.cube_length-1) - 0.5) * 2
sample = F.grid_sample(now, XY, mode=mode, align_corners=True)[..., 0, :]
equi[mask] = sample.view(-1)
return equi
def _intersection(self, xyz, planes):
abc = planes[:, :-1]
depth = -planes[:, 3][None, None, ...] / np.dot(xyz, abc.T)
depth[depth < 0] = np.inf
arg = np.argmin(depth, axis=-1)
depth = np.min(depth, axis=-1)
pts = depth[..., None] * xyz
mask_lst = []
mapping_XY = []
for i in range(6):
mask = arg == i
mask = np.tile(mask[..., None], [1, 1, 3])
XY = np.dot(np.dot(pts[mask].reshape([-1, 3]), self.R_lst[i].T), self.K.T)
XY = np.clip(XY[..., :2].copy() / XY[..., 2:], 0, self.cube_length-1)
mask_lst.append(mask[..., 0])
mapping_XY.append(XY)
mask_lst = [torch.BoolTensor(x) for x in mask_lst]
mapping_XY = [torch.FloatTensor(x) for x in mapping_XY]
return mask_lst, mapping_XY
if __name__ == '__main__':
import matplotlib.pyplot as plt
batch = torch.zeros(12, 3, 256, 256) + 20
c2e = Cube2Equirec(256, 512)
equi = c2e(batch)
plt.imshow(equi[0, ...].permute(1, 2, 0).cpu().numpy())
plt.show()
| [
"numpy.tile",
"torch.nn.functional.grid_sample",
"numpy.asarray",
"numpy.min",
"torch.FloatTensor",
"numpy.array",
"numpy.dot",
"cv2.Rodrigues",
"numpy.cos",
"numpy.concatenate",
"numpy.argmin",
"numpy.sin",
"numpy.meshgrid",
"torch.BoolTensor",
"torch.zeros",
"numpy.arange",
"matplo... | [((3423, 3433), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3431, 3433), True, 'import matplotlib.pyplot as plt\n'), ((566, 589), 'numpy.meshgrid', 'np.meshgrid', (['theta', 'phi'], {}), '(theta, phi)\n', (577, 589), True, 'import numpy as np\n'), ((642, 653), 'numpy.sin', 'np.sin', (['phi'], {}), '(phi)\n', (648, 653), True, 'import numpy as np\n'), ((708, 775), 'numpy.concatenate', 'np.concatenate', (['[x[..., None], y[..., None], z[..., None]]'], {'axis': '(-1)'}), '([x[..., None], y[..., None], z[..., None]], axis=-1)\n', (722, 775), True, 'import numpy as np\n'), ((794, 897), 'numpy.asarray', 'np.asarray', (['[[0, 0, 1, 1], [0, 1, 0, -1], [0, 0, 1, -1], [1, 0, 0, 1], [1, 0, 0, -1], [\n 0, 1, 0, 1]]'], {}), '([[0, 0, 1, 1], [0, 1, 0, -1], [0, 0, 1, -1], [1, 0, 0, 1], [1, 0,\n 0, -1], [0, 1, 0, 1]])\n', (804, 897), True, 'import numpy as np\n'), ((1358, 1449), 'numpy.array', 'np.array', (['[[f, 0, (cube_length - 1) / 2.0], [0, f, (cube_length - 1) / 2.0], [0, 0, 1]]'], {}), '([[f, 0, (cube_length - 1) / 2.0], [0, f, (cube_length - 1) / 2.0],\n [0, 0, 1]])\n', (1366, 1449), True, 'import numpy as np\n'), ((2514, 2539), 'numpy.argmin', 'np.argmin', (['depth'], {'axis': '(-1)'}), '(depth, axis=-1)\n', (2523, 2539), True, 'import numpy as np\n'), ((2556, 2578), 'numpy.min', 'np.min', (['depth'], {'axis': '(-1)'}), '(depth, axis=-1)\n', (2562, 2578), True, 'import numpy as np\n'), ((3268, 3296), 'torch.zeros', 'torch.zeros', (['(12)', '(3)', '(256)', '(256)'], {}), '(12, 3, 256, 256)\n', (3279, 3296), False, 'import torch\n'), ((602, 615), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (608, 615), True, 'import numpy as np\n'), ((618, 629), 'numpy.cos', 'np.cos', (['phi'], {}), '(phi)\n', (624, 629), True, 'import numpy as np\n'), ((666, 679), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (672, 679), True, 'import numpy as np\n'), ((682, 693), 'numpy.cos', 'np.cos', (['phi'], {}), '(phi)\n', (688, 693), True, 'import numpy as np\n'), ((1106, 1197), 'numpy.array', 'np.array', (['[[0, 1, 0], [0.5, 0, 0], [0, 0, 0], [0, 0.5, 0], [0, -0.5, 0], [-0.5, 0, 0]]'], {}), '([[0, 1, 0], [0.5, 0, 0], [0, 0, 0], [0, 0.5, 0], [0, -0.5, 0], [-\n 0.5, 0, 0]])\n', (1114, 1197), True, 'import numpy as np\n'), ((2447, 2465), 'numpy.dot', 'np.dot', (['xyz', 'abc.T'], {}), '(xyz, abc.T)\n', (2453, 2465), True, 'import numpy as np\n'), ((2747, 2782), 'numpy.tile', 'np.tile', (['mask[..., None]', '[1, 1, 3]'], {}), '(mask[..., None], [1, 1, 3])\n', (2754, 2782), True, 'import numpy as np\n'), ((3049, 3068), 'torch.BoolTensor', 'torch.BoolTensor', (['x'], {}), '(x)\n', (3065, 3068), False, 'import torch\n'), ((3110, 3130), 'torch.FloatTensor', 'torch.FloatTensor', (['x'], {}), '(x)\n', (3127, 3130), False, 'import torch\n'), ((1522, 1538), 'cv2.Rodrigues', 'cv2.Rodrigues', (['x'], {}), '(x)\n', (1535, 1538), False, 'import cv2\n'), ((1801, 1859), 'torch.zeros', 'torch.zeros', (['equ_count', 'x.shape[1]', 'self.equ_h', 'self.equ_w'], {}), '(equ_count, x.shape[1], self.equ_h, self.equ_w)\n', (1812, 1859), False, 'import torch\n'), ((2190, 2243), 'torch.nn.functional.grid_sample', 'F.grid_sample', (['now', 'XY'], {'mode': 'mode', 'align_corners': '(True)'}), '(now, XY, mode=mode, align_corners=True)\n', (2203, 2243), True, 'import torch.nn.functional as F\n'), ((492, 508), 'numpy.arange', 'np.arange', (['equ_h'], {}), '(equ_h)\n', (501, 508), True, 'import numpy as np\n'), ((430, 446), 'numpy.arange', 'np.arange', (['equ_w'], {}), '(equ_w)\n', (439, 446), True, 'import numpy as np\n')] |
import math
import re
import os
import numpy as np
from torch.utils.data import Dataset
class SutskeverDataset(Dataset):
"""
Loads from folder 'path' the dataset generated with 'dataset_generation.py'
as numpy.ndarray.
Expects one .npy file for sequence and returns numpy.ndarrays with shape
(time_lenght, height, width, channels).
Raises OSError either if path does not exist or is not a directory
or is empty.
"""
def __init__(self, path, transform=None, filename_regex='^sequence_[0-9]+\\.npy$'):
super(SutskeverDataset, self).__init__()
if not os.path.exists(path):
raise OSError("Path {} does not exist".format(path))
if not os.path.isdir(path):
raise OSError("{} is not a folder".format(path))
dir_files = os.listdir(path)
if len(dir_files) == 0:
raise OSError("Directory {} is empty".format(path))
self._sample_shape = None
self._path = path
self._transform = transform
regex = re.compile(filename_regex)
self._files = []
for file in dir_files:
result = regex.search(file)
if result:
self._files.append(file)
self._dataset_size = len(self._files)
def __len__(self):
return self._dataset_size
def __getitem__(self, key):
file_path = os.path.join(self._path, self._files[key])
sample = np.load(file_path)
shape = self.get_sample_shape()
sample = sample.reshape(shape)
if self._transform:
sample = self._transform(sample)
return sample
def get_sample_shape(self):
"""
:return: the shape of a dataset element as a tuple
"""
if not self._sample_shape:
file_path = os.path.join(self._path, self._files[0])
sample = np.load(file_path)
height = int(math.sqrt(sample.shape[1]))
self._sample_shape = (sample.shape[0], height, height, 1)
return self._sample_shape
| [
"os.path.exists",
"os.listdir",
"re.compile",
"os.path.join",
"math.sqrt",
"os.path.isdir",
"numpy.load"
] | [((810, 826), 'os.listdir', 'os.listdir', (['path'], {}), '(path)\n', (820, 826), False, 'import os\n'), ((1037, 1063), 're.compile', 're.compile', (['filename_regex'], {}), '(filename_regex)\n', (1047, 1063), False, 'import re\n'), ((1382, 1424), 'os.path.join', 'os.path.join', (['self._path', 'self._files[key]'], {}), '(self._path, self._files[key])\n', (1394, 1424), False, 'import os\n'), ((1442, 1460), 'numpy.load', 'np.load', (['file_path'], {}), '(file_path)\n', (1449, 1460), True, 'import numpy as np\n'), ((605, 625), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (619, 625), False, 'import os\n'), ((707, 726), 'os.path.isdir', 'os.path.isdir', (['path'], {}), '(path)\n', (720, 726), False, 'import os\n'), ((1813, 1853), 'os.path.join', 'os.path.join', (['self._path', 'self._files[0]'], {}), '(self._path, self._files[0])\n', (1825, 1853), False, 'import os\n'), ((1875, 1893), 'numpy.load', 'np.load', (['file_path'], {}), '(file_path)\n', (1882, 1893), True, 'import numpy as np\n'), ((1920, 1946), 'math.sqrt', 'math.sqrt', (['sample.shape[1]'], {}), '(sample.shape[1])\n', (1929, 1946), False, 'import math\n')] |
"""
Plots figure S5:
yt correlation of zonal-mean downward long wave radiation at the surface (top)
and longwave cloud radiative forcing at the surface (bottom)
with vertically and zonally integrated eddy moisture transport at 70N for
(left) reanalysis data (left) and aquaplanet control simulation data (right).
"""
import numpy as np
import xarray as xr
from matplotlib import pyplot as plt
from ds21grl import dim_aqua,dim_erai
from ds21grl.config import data_name,dir_interim,dir_fig
# INPUT -----------------------------------------------------------
write2file = 1
# -----------------------------------------------------------------
# read correlation data for downwar longwave radiation
filename1 = dir_interim + data_name[0] + '/yt_corr_nbs5000_VQ_k1-40_70N_with_zm_FLDS_sfc_' + dim_erai.timestamp + '.nc'
filename2 = dir_interim + data_name[1] + '/yt_corr_nbs5000_VQ_k1-40_70N_with_zm_FLDS_sfc_' + dim_aqua.timestamp + '.nc'
ds1 = xr.open_dataset(filename1)
ds2 = xr.open_dataset(filename2)
corr_erai_1 = ds1['corr'].values
corr_aqua_1 = ds2['corr'].values
sig_erai_1 = ds1['sig'].values
sig_aqua_1 = ds2['sig'].values
lag = ds1['lag'].values
ds1.close()
ds2.close()
# read correlation data for longwave cloud forcing
filename1 = dir_interim + data_name[0] + '/yt_corr_nbs5000_VQ_k1-40_70N_with_zm_LWCFS_sfc_' + dim_erai.timestamp + '.nc'
filename2 = dir_interim + data_name[1] + '/yt_corr_nbs5000_VQ_k1-40_70N_with_zm_LWCFS_sfc_' + dim_aqua.timestamp + '.nc'
ds1 = xr.open_dataset(filename1)
ds2 = xr.open_dataset(filename2)
corr_erai_2 = ds1['corr'].values
corr_aqua_2 = ds2['corr'].values
sig_erai_2 = ds1['sig'].values
sig_aqua_2 = ds2['sig'].values
lag = ds1['lag'].values
ds1.close()
ds2.close()
# Plot
corr_aqua_1 = np.flip(np.swapaxes(corr_aqua_1,0,1),axis=1)
corr_aqua_2 = np.flip(np.swapaxes(corr_aqua_2,0,1),axis=1)
corr_erai_1 = np.flip(np.swapaxes(corr_erai_1,0,1),axis=1)
corr_erai_2 = np.flip(np.swapaxes(corr_erai_2,0,1),axis=1)
sig_aqua_1 = np.flip(np.swapaxes(sig_aqua_1,0,1),axis=1)
sig_aqua_2 = np.flip(np.swapaxes(sig_aqua_2,0,1),axis=1)
sig_erai_1 = np.flip(np.swapaxes(sig_erai_1,0,1),axis=1)
sig_erai_2 = np.flip(np.swapaxes(sig_erai_2,0,1),axis=1)
clevs = np.arange(-0.45,0.50,0.05)
cmap = 'RdBu_r'
figsize = np.array([11,8])
fontsize = 12
fig,axes = plt.subplots(nrows=2,ncols=2,figsize=(figsize[0],figsize[1]))
axes = axes.ravel()
plt.subplots_adjust(hspace=0.3,wspace=0.225,left=0.1,right=0.975,top=0.9,bottom=0.1)
# erai FLDS
p = axes[0].contourf(lag,dim_erai.lat,corr_erai_1,levels=clevs,cmap=cmap,extend='both')
axes[0].contourf(lag,dim_erai.lat,sig_erai_1,levels=1,colors='none',hatches=["", "///"])
plt.rcParams['hatch.linewidth'] = 0.25
axes[0].set_yticks(np.arange(0,100,10))
axes[0].set_xticks(np.arange(lag[0],lag[-1]+1,1))
axes[0].set_yticklabels([0,'','',30,'','',60,'','',90],fontsize=fontsize)
axes[0].set_xticklabels([-10,'','','','',-5,'','','','',0,'','','','',5,'','','','',10],fontsize=fontsize)
axes[0].set_ylabel('latitude',fontsize=fontsize)
axes[0].set_xlabel('lag (days)',fontsize=fontsize)
axes[0].set_title('(a)',fontsize=fontsize)
axes[0].set_ylim([0,90])
axes[0].set_xlim([lag[0],lag[-1]])
cb = fig.colorbar(p, ax=axes[0], orientation='vertical',ticks=clevs[1::4],pad=0.025,aspect=15)
cb.ax.set_title('[r]',fontsize=fontsize)
cb.ax.tick_params(labelsize=fontsize,size=0)
# erai LWCF_sfc
p = axes[2].contourf(lag,dim_erai.lat,corr_erai_2,levels=clevs,cmap=cmap,extend='both')
axes[2].contourf(lag,dim_erai.lat,sig_erai_2,levels=1,colors='none',hatches=["", "///"])
plt.rcParams['hatch.linewidth'] = 0.25
axes[2].set_yticks(np.arange(0,100,10))
axes[2].set_xticks(np.arange(lag[0],lag[-1]+1,1))
axes[2].set_yticklabels([0,'','',30,'','',60,'','',90],fontsize=fontsize)
axes[2].set_xticklabels([-10,'','','','',-5,'','','','',0,'','','','',5,'','','','',10],fontsize=fontsize)
axes[2].set_ylabel('latitude',fontsize=fontsize)
axes[2].set_xlabel('lag (days)',fontsize=fontsize)
axes[2].set_title('(c)',fontsize=fontsize)
axes[2].set_ylim([0,90])
axes[2].set_xlim([lag[0],lag[-1]])
cb = fig.colorbar(p, ax=axes[2], orientation='vertical',ticks=clevs[1::4],pad=0.025,aspect=15)
cb.ax.set_title('[r]',fontsize=fontsize)
cb.ax.tick_params(labelsize=fontsize,size=0)
# aqua FLDS
p = axes[1].contourf(lag,dim_aqua.lat,corr_aqua_1,levels=clevs,cmap=cmap,extend='both')
axes[1].contourf(lag,dim_aqua.lat,sig_aqua_1,levels=1,colors='none',hatches=["", "///"])
plt.rcParams['hatch.linewidth'] = 0.25
axes[1].set_yticks(np.arange(0,100,10))
axes[1].set_xticks(np.arange(lag[0],lag[-1]+1,1))
axes[1].set_yticklabels([0,'','',30,'','',60,'','',90],fontsize=fontsize)
axes[1].set_xticklabels([-10,'','','','',-5,'','','','',0,'','','','',5,'','','','',10],fontsize=fontsize)
axes[1].set_ylabel('latitude',fontsize=fontsize)
axes[1].set_xlabel('lag (days)',fontsize=fontsize)
axes[1].set_title('(b)',fontsize=fontsize)
axes[1].set_ylim([0,90])
axes[1].set_xlim([lag[0],lag[-1]])
cb = fig.colorbar(p, ax=axes[1], orientation='vertical',ticks=clevs[1::4],pad=0.025,aspect=15)
cb.ax.set_title('[r]',fontsize=fontsize)
cb.ax.tick_params(labelsize=fontsize,size=0)
# aqua LWCF_sfc
p = axes[3].contourf(lag,dim_aqua.lat,corr_aqua_2,levels=clevs,cmap=cmap,extend='both')
axes[3].contourf(lag,dim_aqua.lat,sig_aqua_2,levels=1,colors='none',hatches=["", "///"])
plt.rcParams['hatch.linewidth'] = 0.25
axes[3].set_yticks(np.arange(0,100,10))
axes[3].set_xticks(np.arange(lag[0],lag[-1]+1,1))
axes[3].set_yticklabels([0,'','',30,'','',60,'','',90],fontsize=fontsize)
axes[3].set_xticklabels([-10,'','','','',-5,'','','','',0,'','','','',5,'','','','',10],fontsize=fontsize)
axes[3].set_ylabel('latitude',fontsize=fontsize)
axes[3].set_xlabel('lag (days)',fontsize=fontsize)
axes[3].set_title('(d)',fontsize=fontsize)
axes[3].set_ylim([0,90])
axes[3].set_xlim([lag[0],lag[-1]])
cb = fig.colorbar(p, ax=axes[3], orientation='vertical',ticks=clevs[1::4],pad=0.025,aspect=15)
cb.ax.set_title('[r]',fontsize=fontsize)
cb.ax.tick_params(labelsize=fontsize,size=0)
# extra labels
axes[0].text(-0.19,0.5,r'corr $\langle [v^{*} q^{*}] \rangle_{70N}$ & $[DLWR]_{sfc}$',fontsize=fontsize*1.25,fontweight='normal',\
va='bottom', ha='center',rotation='vertical',rotation_mode='anchor',transform=axes[0].transAxes)
axes[0].text(0.5,1.1,'reanalysis',fontsize=fontsize*1.25,fontweight='normal', va='bottom', ha='center',rotation='horizontal',\
rotation_mode='anchor',transform=axes[0].transAxes)
axes[1].text(0.5,1.1,'control',fontsize=fontsize*1.25,fontweight='normal',va='bottom', ha='center',rotation='horizontal',\
rotation_mode='anchor',transform=axes[1].transAxes)
axes[2].text(-0.19,0.5,r'corr $\langle [v^{*} q^{*}] \rangle_{70N}$ & $[LWCRF]_{sfc}$',fontsize=fontsize*1.25,fontweight='normal',\
va='bottom', ha='center',rotation='vertical',rotation_mode='anchor',transform=axes[2].transAxes)
if write2file == 1:
plt.savefig(dir_fig + 'fig_S5.pdf')
plt.show()
| [
"matplotlib.pyplot.savefig",
"numpy.arange",
"numpy.swapaxes",
"numpy.array",
"xarray.open_dataset",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.subplots_adjust",
"matplotlib.pyplot.show"
] | [((1001, 1027), 'xarray.open_dataset', 'xr.open_dataset', (['filename1'], {}), '(filename1)\n', (1016, 1027), True, 'import xarray as xr\n'), ((1042, 1068), 'xarray.open_dataset', 'xr.open_dataset', (['filename2'], {}), '(filename2)\n', (1057, 1068), True, 'import xarray as xr\n'), ((1600, 1626), 'xarray.open_dataset', 'xr.open_dataset', (['filename1'], {}), '(filename1)\n', (1615, 1626), True, 'import xarray as xr\n'), ((1641, 1667), 'xarray.open_dataset', 'xr.open_dataset', (['filename2'], {}), '(filename2)\n', (1656, 1667), True, 'import xarray as xr\n'), ((2372, 2399), 'numpy.arange', 'np.arange', (['(-0.45)', '(0.5)', '(0.05)'], {}), '(-0.45, 0.5, 0.05)\n', (2381, 2399), True, 'import numpy as np\n'), ((2442, 2459), 'numpy.array', 'np.array', (['[11, 8]'], {}), '([11, 8])\n', (2450, 2459), True, 'import numpy as np\n'), ((2496, 2560), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(2)', 'ncols': '(2)', 'figsize': '(figsize[0], figsize[1])'}), '(nrows=2, ncols=2, figsize=(figsize[0], figsize[1]))\n', (2508, 2560), True, 'from matplotlib import pyplot as plt\n'), ((2589, 2683), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'hspace': '(0.3)', 'wspace': '(0.225)', 'left': '(0.1)', 'right': '(0.975)', 'top': '(0.9)', 'bottom': '(0.1)'}), '(hspace=0.3, wspace=0.225, left=0.1, right=0.975, top=\n 0.9, bottom=0.1)\n', (2608, 2683), True, 'from matplotlib import pyplot as plt\n'), ((7273, 7283), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (7281, 7283), True, 'from matplotlib import pyplot as plt\n'), ((1888, 1918), 'numpy.swapaxes', 'np.swapaxes', (['corr_aqua_1', '(0)', '(1)'], {}), '(corr_aqua_1, 0, 1)\n', (1899, 1918), True, 'import numpy as np\n'), ((1950, 1980), 'numpy.swapaxes', 'np.swapaxes', (['corr_aqua_2', '(0)', '(1)'], {}), '(corr_aqua_2, 0, 1)\n', (1961, 1980), True, 'import numpy as np\n'), ((2012, 2042), 'numpy.swapaxes', 'np.swapaxes', (['corr_erai_1', '(0)', '(1)'], {}), '(corr_erai_1, 0, 1)\n', (2023, 2042), True, 'import numpy as np\n'), ((2074, 2104), 'numpy.swapaxes', 'np.swapaxes', (['corr_erai_2', '(0)', '(1)'], {}), '(corr_erai_2, 0, 1)\n', (2085, 2104), True, 'import numpy as np\n'), ((2136, 2165), 'numpy.swapaxes', 'np.swapaxes', (['sig_aqua_1', '(0)', '(1)'], {}), '(sig_aqua_1, 0, 1)\n', (2147, 2165), True, 'import numpy as np\n'), ((2197, 2226), 'numpy.swapaxes', 'np.swapaxes', (['sig_aqua_2', '(0)', '(1)'], {}), '(sig_aqua_2, 0, 1)\n', (2208, 2226), True, 'import numpy as np\n'), ((2258, 2287), 'numpy.swapaxes', 'np.swapaxes', (['sig_erai_1', '(0)', '(1)'], {}), '(sig_erai_1, 0, 1)\n', (2269, 2287), True, 'import numpy as np\n'), ((2319, 2348), 'numpy.swapaxes', 'np.swapaxes', (['sig_erai_2', '(0)', '(1)'], {}), '(sig_erai_2, 0, 1)\n', (2330, 2348), True, 'import numpy as np\n'), ((2922, 2943), 'numpy.arange', 'np.arange', (['(0)', '(100)', '(10)'], {}), '(0, 100, 10)\n', (2931, 2943), True, 'import numpy as np\n'), ((2962, 2995), 'numpy.arange', 'np.arange', (['lag[0]', '(lag[-1] + 1)', '(1)'], {}), '(lag[0], lag[-1] + 1, 1)\n', (2971, 2995), True, 'import numpy as np\n'), ((3908, 3929), 'numpy.arange', 'np.arange', (['(0)', '(100)', '(10)'], {}), '(0, 100, 10)\n', (3917, 3929), True, 'import numpy as np\n'), ((3948, 3981), 'numpy.arange', 'np.arange', (['lag[0]', '(lag[-1] + 1)', '(1)'], {}), '(lag[0], lag[-1] + 1, 1)\n', (3957, 3981), True, 'import numpy as np\n'), ((4795, 4816), 'numpy.arange', 'np.arange', (['(0)', '(100)', '(10)'], {}), '(0, 100, 10)\n', (4804, 4816), True, 'import numpy as np\n'), ((4835, 4868), 'numpy.arange', 'np.arange', (['lag[0]', '(lag[-1] + 1)', '(1)'], {}), '(lag[0], lag[-1] + 1, 1)\n', (4844, 4868), True, 'import numpy as np\n'), ((5687, 5708), 'numpy.arange', 'np.arange', (['(0)', '(100)', '(10)'], {}), '(0, 100, 10)\n', (5696, 5708), True, 'import numpy as np\n'), ((5727, 5760), 'numpy.arange', 'np.arange', (['lag[0]', '(lag[-1] + 1)', '(1)'], {}), '(lag[0], lag[-1] + 1, 1)\n', (5736, 5760), True, 'import numpy as np\n'), ((7232, 7267), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(dir_fig + 'fig_S5.pdf')"], {}), "(dir_fig + 'fig_S5.pdf')\n", (7243, 7267), True, 'from matplotlib import pyplot as plt\n')] |
"""
Generic type & functions for torch.Tensor and np.ndarray
"""
import torch
from torch import Tensor
import numpy as np
from numpy import ndarray
from typing import Tuple, Union, List, TypeVar
TensArr = TypeVar('TensArr', Tensor, ndarray)
def convert(a: TensArr, astype: type) -> TensArr:
if astype == Tensor:
if type(a) == Tensor:
return a
else:
return torch.tensor(a, dtype=torch.float32)
elif astype == ndarray:
if type(a) == Tensor:
return a.numpy()
else:
return a
else:
raise ValueError(astype)
def shape(a: TensArr) -> Tuple[int, ...]:
if type(a) == Tensor:
return tuple(a.size())
elif type(a) == ndarray:
return a.shape
else:
raise TypeError
def ndim(a: TensArr) -> int:
if type(a) == Tensor:
return a.dim()
elif type(a) == ndarray:
return a.ndim
else:
raise TypeError
def transpose(a: TensArr,
axes: Union[int, Tuple[int, ...], List[int]]=None) -> TensArr:
if type(a) == Tensor:
if not axes:
if a.dim() >= 2:
return a.permute((1, 0)+(-1,)*(a.dim()-2))
else:
return a
else:
return a.permute(axes)
elif type(a) == ndarray:
if a.ndim == 1 and not axes:
return a
else:
return a.transpose(axes)
else:
raise TypeError
def squeeze(a: TensArr, axis=None) -> int:
if type(a) == Tensor:
return a.squeeze(dim=axis)
elif type(a) == ndarray:
return a.squeeze(axis=axis)
else:
raise TypeError
def _cat_stack(fn: str,
a: Union[Tuple[TensArr, ...], List[TensArr]],
axis=0,
astype: type=None) -> TensArr:
fn_dict = {(torch, 'cat'): torch.cat,
(np, 'cat'): np.concatenate,
(torch, 'stack'): torch.stack,
(np, 'stack'): np.stack,
}
types = [type(item) for item in a]
if np.any(types != types[0]):
a = [convert(item, (astype if astype else types[0])) for item in a]
if types[0] == Tensor:
result = fn_dict[(torch, fn)](a, dim=axis)
elif types[0] == ndarray:
result = fn_dict[(np, fn)](a, axis=axis)
else:
raise TypeError
return convert(result, astype) if astype else result
def cat(*args, **kargs) -> TensArr:
"""
<parameters>
a:Union[Tuple[TensArr, ...], List[TensArr]]
axis=0
astype: type=None
"""
return _cat_stack('cat', *args, **kargs)
def stack(*args, **kargs) -> TensArr:
"""
<parameters>
a: Union[Tuple[TensArr, ...], List[TensArr]]
axis=0
astype: type=None
"""
return _cat_stack('stack', *args, **kargs)
def sum_axis(a: TensArr, axis=None):
if axis:
if type(a) == Tensor:
return a.sum(dim=axis)
elif type(a) == ndarray:
return a.sum(axis=axis)
else:
raise TypeError
else:
return a.sum()
| [
"torch.tensor",
"numpy.any",
"typing.TypeVar"
] | [((210, 245), 'typing.TypeVar', 'TypeVar', (['"""TensArr"""', 'Tensor', 'ndarray'], {}), "('TensArr', Tensor, ndarray)\n", (217, 245), False, 'from typing import Tuple, Union, List, TypeVar\n'), ((2063, 2088), 'numpy.any', 'np.any', (['(types != types[0])'], {}), '(types != types[0])\n', (2069, 2088), True, 'import numpy as np\n'), ((407, 443), 'torch.tensor', 'torch.tensor', (['a'], {'dtype': 'torch.float32'}), '(a, dtype=torch.float32)\n', (419, 443), False, 'import torch\n')] |
import glob
import os
import os.path as osp
import sys
import torch
import torch.utils.data as data
import cv2
import numpy as np
import torchvision.transforms as T
from layers.box_utils import point_form
from PIL import ImageDraw, ImageOps, Image, ImageFont
import string
tv_transform = T.Compose([
T.ToTensor(),
T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
tv_inv_trans = T.Compose([
T.Normalize([0, 0, 0], [1/0.229, 1/0.224, 1/0.225]),
T.Normalize([-0.485, -0.456, -0.406], [1, 1, 1]),
#T.ToPILImage()
])
def to_coord(box, size):
width, height = size
x_l, y_u, x_r, y_b = box
return [int(x_l*width),
int(y_u*height),
int(x_r*width),
int(y_b*height)]
def target_transform(boxes):
return np.concatenate([boxes[:, :2] - boxes[:, 2:]/2,
boxes[:, :2] + boxes[:, 2:]/2], 1)
class WatermarkDetection(data.Dataset):
def __init__(self, root, transform=None, target_transform=None):
self.root = root
self.transform = transform
self.target_transform = target_transform
self.name = 'Large-scale-Watermark'
# anno file and img are file with same name but different postfix
self.annos = {}
for anno in glob.glob(osp.join(root, '*.txt')):
fn = anno.rsplit('/', 1)[1].rsplit('.', 1)[0]
img_fn = osp.join(root, fn+'.png')
if osp.isfile(img_fn):
with open(anno) as f:
line = f.readlines()
if len(line) > 1:
print(anno)
try:
attrs = line[0][:-1].split(' ')
self.annos[img_fn] = np.array([float(coord) for coord in attrs[2:]])[None, :]
except Exception:
print('Line:', line)
self.ids = list(self.annos.keys())
def __len__(self):
return len(self.ids)
def __getitem__(self, idx):
img = Image.open(self.ids[idx]).convert('RGB')
img = np.array(img)[..., ::-1]
# img = cv2.imread(self.ids[idx])
# if img.shape[-1] == 4:
# img = cv2.cvtColor(img, cv2.COLOR_BGRA2BGR)
#img = Image.open(self.ids[idx]).convert('RGB')
target = self.annos[self.ids[idx]]
height, width, _ = img.shape
if self.target_transform is not None:
target = self.target_transform(target)
if self.transform is not None:
img, boxes, _ = self.transform(img, target)
img = img[..., ::-1]
label_pseudo = np.ones_like(boxes)
target = np.hstack((boxes, label_pseudo[:, 0:1]))
img = tv_transform(img.copy().astype(np.uint8))
return img, target
if __name__ == '__main__':
import sys
sys.path.append('/home/chengk/chk-root/Read/ssd.pytorch')
from config import voc, MEANS
from utils.augmentations import SSDAugmentation
# from voc0712 import SSDAugmentation
from data import *
aug = SSDAugmentation(voc['min_dim'], MEANS)
tmp = WatermarkDetection('/home/chengk/chk/data/Large-scale_Visible_Watermark_Dataset/watermarked_images/test', transform=aug)
img = tmp[2]
import pdb; pdb.set_trace()
print(len(tmp))
| [
"numpy.ones_like",
"PIL.Image.open",
"utils.augmentations.SSDAugmentation",
"numpy.hstack",
"os.path.join",
"os.path.isfile",
"numpy.array",
"pdb.set_trace",
"numpy.concatenate",
"torchvision.transforms.Normalize",
"torchvision.transforms.ToTensor",
"sys.path.append"
] | [((787, 877), 'numpy.concatenate', 'np.concatenate', (['[boxes[:, :2] - boxes[:, 2:] / 2, boxes[:, :2] + boxes[:, 2:] / 2]', '(1)'], {}), '([boxes[:, :2] - boxes[:, 2:] / 2, boxes[:, :2] + boxes[:, 2:\n ] / 2], 1)\n', (801, 877), True, 'import numpy as np\n'), ((2849, 2906), 'sys.path.append', 'sys.path.append', (['"""/home/chengk/chk-root/Read/ssd.pytorch"""'], {}), "('/home/chengk/chk-root/Read/ssd.pytorch')\n", (2864, 2906), False, 'import sys\n'), ((3068, 3106), 'utils.augmentations.SSDAugmentation', 'SSDAugmentation', (["voc['min_dim']", 'MEANS'], {}), "(voc['min_dim'], MEANS)\n", (3083, 3106), False, 'from utils.augmentations import SSDAugmentation\n'), ((3272, 3287), 'pdb.set_trace', 'pdb.set_trace', ([], {}), '()\n', (3285, 3287), False, 'import pdb\n'), ((306, 318), 'torchvision.transforms.ToTensor', 'T.ToTensor', ([], {}), '()\n', (316, 318), True, 'import torchvision.transforms as T\n'), ((324, 381), 'torchvision.transforms.Normalize', 'T.Normalize', (['[0.485, 0.456, 0.406]', '[0.229, 0.224, 0.225]'], {}), '([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n', (335, 381), True, 'import torchvision.transforms as T\n'), ((417, 474), 'torchvision.transforms.Normalize', 'T.Normalize', (['[0, 0, 0]', '[1 / 0.229, 1 / 0.224, 1 / 0.225]'], {}), '([0, 0, 0], [1 / 0.229, 1 / 0.224, 1 / 0.225])\n', (428, 474), True, 'import torchvision.transforms as T\n'), ((474, 522), 'torchvision.transforms.Normalize', 'T.Normalize', (['[-0.485, -0.456, -0.406]', '[1, 1, 1]'], {}), '([-0.485, -0.456, -0.406], [1, 1, 1])\n', (485, 522), True, 'import torchvision.transforms as T\n'), ((1288, 1311), 'os.path.join', 'osp.join', (['root', '"""*.txt"""'], {}), "(root, '*.txt')\n", (1296, 1311), True, 'import os.path as osp\n'), ((1393, 1420), 'os.path.join', 'osp.join', (['root', "(fn + '.png')"], {}), "(root, fn + '.png')\n", (1401, 1420), True, 'import os.path as osp\n'), ((1434, 1452), 'os.path.isfile', 'osp.isfile', (['img_fn'], {}), '(img_fn)\n', (1444, 1452), True, 'import os.path as osp\n'), ((2088, 2101), 'numpy.array', 'np.array', (['img'], {}), '(img)\n', (2096, 2101), True, 'import numpy as np\n'), ((2636, 2655), 'numpy.ones_like', 'np.ones_like', (['boxes'], {}), '(boxes)\n', (2648, 2655), True, 'import numpy as np\n'), ((2677, 2717), 'numpy.hstack', 'np.hstack', (['(boxes, label_pseudo[:, 0:1])'], {}), '((boxes, label_pseudo[:, 0:1]))\n', (2686, 2717), True, 'import numpy as np\n'), ((2033, 2058), 'PIL.Image.open', 'Image.open', (['self.ids[idx]'], {}), '(self.ids[idx])\n', (2043, 2058), False, 'from PIL import ImageDraw, ImageOps, Image, ImageFont\n')] |
# Copyright 2021 NVIDIA Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import argparse
def test(
size_per_proc=1000,
num_procs=1,
num_runs=1,
scale_lhs_only=False,
package="legate",
ty="int64",
key_length=40,
pad_side="right",
):
if package == "legate":
from legate import numpy as np, pandas as pd
from legate.numpy.random import randn
elif package == "cudf":
import cudf as pd
import cupy as np
from cupy.random import randn
elif package == "pandas":
import numpy as np
import pandas as pd
from numpy.random import randn
else:
print("Unknown dataframe package: %s" % package)
assert False
if package == "legate":
from legate.timing import time
def block():
pass
def get_timestamp():
return time()
def compute_elapsed_time(start_ts, stop_ts):
return (stop_ts - start_ts) / 1000.0
else:
import time
def block():
pass
get_timestamp = time.process_time
def compute_elapsed_time(start_ts, stop_ts):
return (stop_ts - start_ts) * 1000.0
size = size_per_proc * num_procs
key = np.arange(size, dtype=np.int64) % size_per_proc
payload = randn(size)
df = pd.DataFrame({"key": key, "payload": payload})
if ty == "int64":
df["key"] = df["key"] * -1
ascending = True
if ty == "string":
df["key"] = (
df["key"]
.astype(str)
.str.pad(width=key_length, side=pad_side, fillchar="0")
)
ascending = False
print("Size: %u, Key dtype: %s" % (size, df["key"].dtype))
block()
for i in range(num_runs):
start_ts = get_timestamp()
result = df.sort_values("key", ignore_index=True, ascending=ascending)
stop_ts = get_timestamp()
print(
"[Run %d] Elapsed time: %lf ms"
% (i + 1, compute_elapsed_time(start_ts, stop_ts))
)
del result
def driver():
parser = argparse.ArgumentParser(description="Join micro-benchmark")
parser.add_argument(
"--size_per_proc",
dest="size_per_proc",
type=int,
default=1000,
help="Join table size per processor",
)
parser.add_argument(
"--num_procs",
dest="num_procs",
type=int,
default=1,
help="Number or processors",
)
parser.add_argument(
"--num_runs",
dest="num_runs",
type=int,
default=1,
help="Number of runs",
)
parser.add_argument(
"--scale_lhs_only",
dest="scale_lhs_only",
action="store_true",
required=False,
default=False,
help="Scaling only the LHS table",
)
parser.add_argument(
"--package",
dest="package",
type=str,
default="legate",
help="Dataframe package to use",
)
parser.add_argument(
"--type",
dest="ty",
type=str,
default="int64",
help="Data type for sorting keys",
)
parser.add_argument(
"--key_length",
dest="key_length",
type=int,
default=40,
help="Length of string keys",
)
parser.add_argument(
"--pad_side",
dest="pad_side",
type=str,
default="right",
help="Padding side for the sorting keys when they are string",
)
args = parser.parse_args()
test(**vars(args))
if __name__ == "__main__":
driver()
| [
"argparse.ArgumentParser",
"time",
"pandas.DataFrame",
"numpy.random.randn",
"numpy.arange"
] | [((1831, 1842), 'numpy.random.randn', 'randn', (['size'], {}), '(size)\n', (1836, 1842), False, 'from numpy.random import randn\n'), ((1853, 1899), 'pandas.DataFrame', 'pd.DataFrame', (["{'key': key, 'payload': payload}"], {}), "({'key': key, 'payload': payload})\n", (1865, 1899), True, 'import pandas as pd\n'), ((2618, 2677), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Join micro-benchmark"""'}), "(description='Join micro-benchmark')\n", (2641, 2677), False, 'import argparse\n'), ((1769, 1800), 'numpy.arange', 'np.arange', (['size'], {'dtype': 'np.int64'}), '(size, dtype=np.int64)\n', (1778, 1800), True, 'import numpy as np\n'), ((1394, 1400), 'time', 'time', ([], {}), '()\n', (1398, 1400), False, 'import time\n')] |
# -*- coding utf-8-*-
"""
Created on Tue Nov 23 10:15:35 2018
@author: galad-loth
"""
import numpy as npy
import mxnet as mx
class SSDHLoss(mx.operator.CustomOp):
"""
Loss layer for supervised semantics-preserving deep hashing.
"""
def __init__(self, w_bin, w_balance):
self._w_bin = w_bin
self._w_balance = w_balance
def forward(self, is_train, req, in_data, out_data, aux):
x=in_data[0].asnumpy()
xs=x-0.5
y=npy.ones(x.shape)
y[xs<0]=0
self.assign(out_data[0], req[0], mx.nd.array(y))
def backward(self, req, out_grad, in_data, out_data, in_grad, aux):
x=in_data[0].asnumpy()
grad1=-2*(x-0.5)/x.shape[0]
mu=npy.mean(x,axis=1)
grad2=2*(mu-0.5)/x.shape[0]
grad=self._w_bin*grad1+self._w_balance*grad2[:,npy.newaxis]
self.assign(in_grad[0], req[0], mx.nd.array(grad))
@mx.operator.register("ssdh_loss")
class SSDHLossProp(mx.operator.CustomOpProp):
def __init__(self, w_bin, w_balance):
super(SSDHLossProp, self).__init__(need_top_grad=False)
self._w_bin=float(w_bin)
self._w_balance=float(w_balance)
def list_arguments(self):
return ['data']
def list_outputs(self):
return ['output']
def infer_shape(self, in_shape):
data_shape=in_shape[0]
return [data_shape],[data_shape]
def create_operator(self, ctx, shapes, dtypes):
return SSDHLoss(self._w_bin, self._w_balance)
class SiamDHLoss(mx.operator.CustomOp):
"""
Loss layer for deep hashing with siamese feature network.
"""
def __init__(self, margin, alpha):
self._margin = margin
self._alpha = alpha
def forward(self, is_train, req, in_data, out_data, aux):
x0=in_data[0].asnumpy()
x1=in_data[1].asnumpy()
l=in_data[0].asnumpy()
d=self._alpha*(x0-x1)*(x0-x1)/2
y=npy.zeros(x0.shape)
y[l>0]=d[l>0]#same class,
y[l<=0]=npy.maximum(0, self.margin - d[l<=0])
self.assign(out_data[0], req[0], mx.nd.array(y))
def backward(self, req, out_grad, in_data, out_data, in_grad, aux):
x0=in_data[0].asnumpy()
x1=in_data[1].asnumpy()
l=in_data[2].asnumpy()
y=out_data[0].asnumpy()
d=self._alpha*(x0-x1)
dx0=npy.zeros(d.shape)
dx1=npy.zeros(d.shape)
dx0[l>0]=d[l>0]
dx0[l<=0]=-d[l<=0]
dx0[y<=0]=0.0
dx1[:]=-dx0
self.assign(in_grad[0], req[0], mx.nd.array(dx0))
self.assign(in_grad[1], req[0], mx.nd.array(dx1))
@mx.operator.register("siam_dh_Loss")
class SiamDHLossProp(mx.operator.CustomOpProp):
def __init__(self, margin, alpha):
super(SSDHLossProp, self).__init__(need_top_grad=False)
self._margin = margin
self._alpha = alpha
def list_arguments(self):
return ['data1','data2','label']
def list_outputs(self):
return ['output']
def infer_shape(self, in_shape):
data_shape=in_shape[0]
label_shape=(in_shape[0][0],)
return [data_shape, data_shape,label_shape],[data_shape]
def create_operator(self, ctx, shapes, dtypes):
return SSDHLoss(self._margin, self._alpha)
def get_ssdh_symbol(net_pre,arg_params,
num_latent, num_class,layer_name='flatten'):
"""
net_pre: the pre-trained network symbol
arg_params: the argument parameters of the pre-trained model
num_latent: the number of latent layer units for the fine-tune datasets
layer_name: the layer name before the last fully-connected layer
"""
all_layers = net_pre.get_internals()
load_net = all_layers[layer_name+'_output']
latent = mx.symbol.FullyConnected(data=load_net, num_hidden=num_latent, name='fc_ssdh_1')
latent = mx.sym.Activation(data=latent, act_type="sigmoid", name="sigmoid_ssdh")
class_net = mx.symbol.FullyConnected(data=latent, num_hidden=num_class, name='fc_ssdh_2')
class_net = mx.symbol.SoftmaxOutput(data=class_net, name='softmax')
hash_net=mx.symbol.Custom(data=latent, w_bin=0.1, w_balance =0.1,
name="hash_loss", op_type="ssdh_loss")
net = mx.sym.Group([class_net,hash_net])
new_args = dict({k:arg_params[k] for k in arg_params if 'fc' not in k})
return (net, new_args)
if __name__=="__main__":
data=mx.sym.Variable("data")
loss=mx.symbol.Custom(data=data, w_bin=0.1, w_balance =0.1,
name="loss", op_type="ssdh_loss")
x=mx.nd.array([[0.5,0.3],[2,5],[-0.2,-3],[0.5,2]])
print("x={}".format(x))
x_grad=mx.nd.zeros((4,2))
e= loss.bind(mx.cpu(), args={'data':x},args_grad={"data":x_grad})
e.forward()
print("out={}".format(e.outputs[0].asnumpy()))
e.backward()
print("x_grad={}".format(x_grad.asnumpy()))
| [
"numpy.mean",
"mxnet.sym.Activation",
"numpy.ones",
"mxnet.symbol.Custom",
"mxnet.nd.zeros",
"mxnet.symbol.FullyConnected",
"mxnet.cpu",
"mxnet.sym.Variable",
"numpy.zeros",
"mxnet.symbol.SoftmaxOutput",
"mxnet.nd.array",
"numpy.maximum",
"mxnet.sym.Group",
"mxnet.operator.register"
] | [((968, 1001), 'mxnet.operator.register', 'mx.operator.register', (['"""ssdh_loss"""'], {}), "('ssdh_loss')\n", (988, 1001), True, 'import mxnet as mx\n'), ((2789, 2825), 'mxnet.operator.register', 'mx.operator.register', (['"""siam_dh_Loss"""'], {}), "('siam_dh_Loss')\n", (2809, 2825), True, 'import mxnet as mx\n'), ((4005, 4090), 'mxnet.symbol.FullyConnected', 'mx.symbol.FullyConnected', ([], {'data': 'load_net', 'num_hidden': 'num_latent', 'name': '"""fc_ssdh_1"""'}), "(data=load_net, num_hidden=num_latent, name='fc_ssdh_1'\n )\n", (4029, 4090), True, 'import mxnet as mx\n'), ((4100, 4171), 'mxnet.sym.Activation', 'mx.sym.Activation', ([], {'data': 'latent', 'act_type': '"""sigmoid"""', 'name': '"""sigmoid_ssdh"""'}), "(data=latent, act_type='sigmoid', name='sigmoid_ssdh')\n", (4117, 4171), True, 'import mxnet as mx\n'), ((4189, 4266), 'mxnet.symbol.FullyConnected', 'mx.symbol.FullyConnected', ([], {'data': 'latent', 'num_hidden': 'num_class', 'name': '"""fc_ssdh_2"""'}), "(data=latent, num_hidden=num_class, name='fc_ssdh_2')\n", (4213, 4266), True, 'import mxnet as mx\n'), ((4284, 4339), 'mxnet.symbol.SoftmaxOutput', 'mx.symbol.SoftmaxOutput', ([], {'data': 'class_net', 'name': '"""softmax"""'}), "(data=class_net, name='softmax')\n", (4307, 4339), True, 'import mxnet as mx\n'), ((4360, 4458), 'mxnet.symbol.Custom', 'mx.symbol.Custom', ([], {'data': 'latent', 'w_bin': '(0.1)', 'w_balance': '(0.1)', 'name': '"""hash_loss"""', 'op_type': '"""ssdh_loss"""'}), "(data=latent, w_bin=0.1, w_balance=0.1, name='hash_loss',\n op_type='ssdh_loss')\n", (4376, 4458), True, 'import mxnet as mx\n'), ((4508, 4543), 'mxnet.sym.Group', 'mx.sym.Group', (['[class_net, hash_net]'], {}), '([class_net, hash_net])\n', (4520, 4543), True, 'import mxnet as mx\n'), ((4712, 4735), 'mxnet.sym.Variable', 'mx.sym.Variable', (['"""data"""'], {}), "('data')\n", (4727, 4735), True, 'import mxnet as mx\n'), ((4746, 4838), 'mxnet.symbol.Custom', 'mx.symbol.Custom', ([], {'data': 'data', 'w_bin': '(0.1)', 'w_balance': '(0.1)', 'name': '"""loss"""', 'op_type': '"""ssdh_loss"""'}), "(data=data, w_bin=0.1, w_balance=0.1, name='loss', op_type=\n 'ssdh_loss')\n", (4762, 4838), True, 'import mxnet as mx\n'), ((4877, 4932), 'mxnet.nd.array', 'mx.nd.array', (['[[0.5, 0.3], [2, 5], [-0.2, -3], [0.5, 2]]'], {}), '([[0.5, 0.3], [2, 5], [-0.2, -3], [0.5, 2]])\n', (4888, 4932), True, 'import mxnet as mx\n'), ((4967, 4986), 'mxnet.nd.zeros', 'mx.nd.zeros', (['(4, 2)'], {}), '((4, 2))\n', (4978, 4986), True, 'import mxnet as mx\n'), ((494, 511), 'numpy.ones', 'npy.ones', (['x.shape'], {}), '(x.shape)\n', (502, 511), True, 'import numpy as npy\n'), ((761, 780), 'numpy.mean', 'npy.mean', (['x'], {'axis': '(1)'}), '(x, axis=1)\n', (769, 780), True, 'import numpy as npy\n'), ((2040, 2059), 'numpy.zeros', 'npy.zeros', (['x0.shape'], {}), '(x0.shape)\n', (2049, 2059), True, 'import numpy as npy\n'), ((2113, 2152), 'numpy.maximum', 'npy.maximum', (['(0)', '(self.margin - d[l <= 0])'], {}), '(0, self.margin - d[l <= 0])\n', (2124, 2152), True, 'import numpy as npy\n'), ((2503, 2521), 'numpy.zeros', 'npy.zeros', (['d.shape'], {}), '(d.shape)\n', (2512, 2521), True, 'import numpy as npy\n'), ((2535, 2553), 'numpy.zeros', 'npy.zeros', (['d.shape'], {}), '(d.shape)\n', (2544, 2553), True, 'import numpy as npy\n'), ((5004, 5012), 'mxnet.cpu', 'mx.cpu', ([], {}), '()\n', (5010, 5012), True, 'import mxnet as mx\n'), ((573, 587), 'mxnet.nd.array', 'mx.nd.array', (['y'], {}), '(y)\n', (584, 587), True, 'import mxnet as mx\n'), ((939, 956), 'mxnet.nd.array', 'mx.nd.array', (['grad'], {}), '(grad)\n', (950, 956), True, 'import mxnet as mx\n'), ((2193, 2207), 'mxnet.nd.array', 'mx.nd.array', (['y'], {}), '(y)\n', (2204, 2207), True, 'import mxnet as mx\n'), ((2704, 2720), 'mxnet.nd.array', 'mx.nd.array', (['dx0'], {}), '(dx0)\n', (2715, 2720), True, 'import mxnet as mx\n'), ((2764, 2780), 'mxnet.nd.array', 'mx.nd.array', (['dx1'], {}), '(dx1)\n', (2775, 2780), True, 'import mxnet as mx\n')] |
# MIT License
# This project is a software package to automate the performance tracking of the HPC algorithms
# Copyright (c) 2021. <NAME>, <NAME>, <NAME>, <NAME>
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""Analyzes the field inputs for integrity check and initiate process to make plot analysis"""
import numpy as np
import dash_bootstrap_components as dbc
import dash_html_components as html
import model
import visuals
import specs
def check_input_integrity(cell_visual_pair):
validated_inputs = []
cell = cell_visual_pair[0]
cell_trio_elements = cell['props']['children'][:-1]
for i in range(len(cell_trio_elements)):
cell_trio_element = cell_trio_elements[i]
field_pair = cell_trio_element['props']['children']['props']['children']['props']['children'][1:]
try:
field_type_selected = field_pair[0]['props']['children']['props']['value']
field_value_selected = field_pair[1]['props']['value']
except KeyError:
message = 'Unselected dropdowns'
error = construct_integrity_fail_message(message)
return error
if not field_value_selected:
message = f'Unselected {field_type_selected} field value dropdown'
error = construct_integrity_fail_message(message)
return error
validated_inputs.append((field_type_selected, field_value_selected))
return validated_inputs
def construct_integrity_fail_message(error):
error_toast = dbc.Toast(
[html.P(error, className="mb-0")],
id="simple-toast",
header="All not good \U0001F616",
icon="danger",
dismissable=True,
)
return error_toast
def analyze_inputs(cell_visual_pair, library):
integrity_result = check_input_integrity(cell_visual_pair)
if not isinstance(integrity_result, list):
failed = integrity_result
return failed
integrity_result = fix_version_all_case(integrity_result, library)
integrity_result = check_for_compulsory_fields(integrity_result, library)
if not isinstance(integrity_result, list):
failed = integrity_result
return failed
inputs = integrity_result[0]
extras = integrity_result[1]
integrity_result = check_for_repetition(inputs)
if not isinstance(integrity_result, list):
failed = integrity_result
return failed
collection_ls = make_possible_collection_permutations(inputs, library)
if not isinstance(collection_ls, list):
failed = collection_ls
return failed
speedup_options = get_speedup_options(inputs)
if not isinstance(speedup_options, list):
failed = speedup_options
return failed
concat_df = model.get_concat_dataframe(collection_ls)
if isinstance(concat_df, list):
failed = construct_integrity_fail_message(concat_df[1] + ' is not a valid suite existing in database')
return failed
if concat_df.empty:
failed = construct_integrity_fail_message('Nothing found for selection')
return failed
else:
graph = get_graph(inputs)
if not isinstance(graph, list):
failed = graph
return failed
versions = get_rocm_versions(inputs)
speedup_options = get_speedup_options(inputs)
figure, table = visuals.make_graph_table(concat_df, "Performance Plot", graph[0], versions, speedup_options, library, extras=extras)
gpu_servers = get_gpu_servers(inputs)
gpu_server_specs = specs.get_specs(gpu_servers, versions)
if len(speedup_options) > 1 or library.lower() == 'rocblas':
return [figure, 'speedup', gpu_server_specs, table]
else:
return [figure, gpu_server_specs, table]
def fix_version_all_case(ls_of_tuples, library):
rocm_versions = get_rocm_versions(ls_of_tuples)
if 'All' in rocm_versions:
for i, data in enumerate(ls_of_tuples):
if data[0] == "Version(s)" and 'All' in data[1]:
rocm_versions = model.get_field_values(library, 'Version(s)')
rocm_versions = rocm_versions[:-1]
tupl_to_ls = list(data)
tupl_to_ls[1] = rocm_versions
ls_of_tuples[i] = tuple(tupl_to_ls)
return ls_of_tuples
def check_for_compulsory_fields(ls_of_tuples, library):
added = False
field_types = [item[0] for item in ls_of_tuples]
if library.lower() == 'rocrand' and 'Algorithm' not in field_types:
error = construct_integrity_fail_message('Must contain HardWare-ID, Test-Suite, Version(s), Graph, Algorithm')
return error
if library.lower() == 'rocrand':
extras = [item[1] for item in ls_of_tuples if item[0]=='Algorithm']
extras = [item for sublist in extras for item in sublist]
added = True
if 'HardWare-ID' not in field_types or 'Test-Suite' not in field_types or 'Version(s)' not in field_types or 'Graph' not in field_types:
error = construct_integrity_fail_message('Must contain HardWare-ID, Test-Suite, Version(s), Graph')
return error
if added:
return [ls_of_tuples, extras]
return [ls_of_tuples, []]
def check_for_repetition(ls_of_tuples):
contains_duplicates = any(ls_of_tuples.count(element) > 1 for element in ls_of_tuples)
if contains_duplicates:
error = construct_integrity_fail_message("Duplicated field pair")
return error
return ls_of_tuples
def make_possible_collection_permutations(ls_of_tuples, library):
gpu_servers = get_gpu_servers(ls_of_tuples)
test_suites = get_test_suites(ls_of_tuples)
rocm_versions = get_rocm_versions(ls_of_tuples)
if 'All' in rocm_versions:
rocm_versions = model.get_field_values(library, 'Version(s)')
library = library.lower()
gpu_servers, test_suites = check_for_possible_gpu_test_suite_conflict(gpu_servers, test_suites)
if not isinstance(gpu_servers, list):
failed = gpu_servers
return failed
collections = []
for server in gpu_servers:
for rocm_version in rocm_versions:
for suite in test_suites:
collection = server.lower() + '/' + library + '/' + rocm_version + '/' + suite
collections.append(collection)
return collections
def get_gpu_servers(ls_of_tuples):
gpu_servers = []
for _, data in enumerate(ls_of_tuples):
if data[0] == "HardWare-ID":
gpu_servers.append(data[1])
ls_elements = [item for item in gpu_servers if isinstance(item, list)]
non_ls_elements = [item for item in gpu_servers if not isinstance(item, list)]
made_list = [[item] for item in non_ls_elements]
for item in made_list:
ls_elements.append(item)
gpu_servers = ls_elements
flattened_gpu_servers = [item for sublist in gpu_servers for item in sublist]
return flattened_gpu_servers
def get_test_suites(ls_of_tuples):
test_suites = []
for _, data in enumerate(ls_of_tuples):
if data[0] == "Test-Suite":
test_suites.append(data[1])
ls_elements = [item for item in test_suites if isinstance(item, list)]
non_ls_elements = [item for item in test_suites if not isinstance(item, list)]
made_list = [[item] for item in non_ls_elements]
for item in made_list:
ls_elements.append(item)
test_suites = ls_elements
flattened_test_suites = [item for sublist in test_suites for item in sublist]
return flattened_test_suites
def get_rocm_versions(ls_of_tuples):
rocm_versions = []
for _, data in enumerate(ls_of_tuples):
if data[0] == "Version(s)":
rocm_versions.append(data[1])
flattened_rocm_versions = [item for sublist in rocm_versions for item in sublist]
return flattened_rocm_versions
def check_for_possible_gpu_test_suite_conflict(gpu_servers, test_suites):
if len(gpu_servers) > 1 and len(test_suites) > 1 and len(np.unique(test_suites)) != len(test_suites):
error = construct_integrity_fail_message('For multiple GPU server analysis, only one test suite analysis is implementable')
return error, error
return gpu_servers, test_suites
def get_speedup_options(ls_of_tuples):
speedup_options = []
multiple_check = 0
for _, data in enumerate(ls_of_tuples):
if data[0] == "SpeedUp-Options":
multiple_check += 1
speedup_options.append(data[1])
if multiple_check > 1:
error = construct_integrity_fail_message('Multiple speedup option field pair not allowed. Select all applicable in a single field pair')
return error
flattened_speedup_options = []
if speedup_options:
flattened_speedup_options = [item for sublist in speedup_options for item in sublist]
return flattened_speedup_options
def get_graph(ls_of_tuples):
graphs = []
multiple_check = 0
for _, data in enumerate(ls_of_tuples):
if data[0] == "Graph":
multiple_check += 1
graphs.append(data[1])
if multiple_check > 1:
error = construct_integrity_fail_message('Multiple Graph field pair not allowed')
return error
return graphs
| [
"model.get_field_values",
"numpy.unique",
"model.get_concat_dataframe",
"visuals.make_graph_table",
"dash_html_components.P",
"specs.get_specs"
] | [((3849, 3890), 'model.get_concat_dataframe', 'model.get_concat_dataframe', (['collection_ls'], {}), '(collection_ls)\n', (3875, 3890), False, 'import model\n'), ((4451, 4571), 'visuals.make_graph_table', 'visuals.make_graph_table', (['concat_df', '"""Performance Plot"""', 'graph[0]', 'versions', 'speedup_options', 'library'], {'extras': 'extras'}), "(concat_df, 'Performance Plot', graph[0], versions,\n speedup_options, library, extras=extras)\n", (4475, 4571), False, 'import visuals\n'), ((4642, 4680), 'specs.get_specs', 'specs.get_specs', (['gpu_servers', 'versions'], {}), '(gpu_servers, versions)\n', (4657, 4680), False, 'import specs\n'), ((6888, 6933), 'model.get_field_values', 'model.get_field_values', (['library', '"""Version(s)"""'], {}), "(library, 'Version(s)')\n", (6910, 6933), False, 'import model\n'), ((2618, 2649), 'dash_html_components.P', 'html.P', (['error'], {'className': '"""mb-0"""'}), "(error, className='mb-0')\n", (2624, 2649), True, 'import dash_html_components as html\n'), ((5158, 5203), 'model.get_field_values', 'model.get_field_values', (['library', '"""Version(s)"""'], {}), "(library, 'Version(s)')\n", (5180, 5203), False, 'import model\n'), ((9086, 9108), 'numpy.unique', 'np.unique', (['test_suites'], {}), '(test_suites)\n', (9095, 9108), True, 'import numpy as np\n')] |
import keras
import numpy as np
import pandas as pd
import os
from keras import backend as K
from keras.layers import Input, Dense, Dropout, GaussianNoise, BatchNormalization, GaussianDropout
import keras.backend as backend
from keras.models import Model, Sequential
from keras.callbacks import ModelCheckpoint, CSVLogger, History
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder, normalize
from keras.utils import np_utils
"""
Created by <NAME> on 3/26/18.
Email : <EMAIL>
Website: http://ce.sharif.edu/~naghipourfar
"""
# Constants
DAMAVAND_LOCATION_FPKM_NORMALIZED = "~/f/Behrooz/dataset_local/fpkm_normalized.csv"
DAMAVAND_LOCATION_CATEGORICAL_DISEASE = "~/f/Behrooz/dataset_local/disease.csv"
DAMAVAND_LOCATION_ENCODED = '../Data/encoded_scae_dropout.csv'
DAMAVAND_RESULTS_ENCODED = '../Results/CAE/encoded_results_{0}_{1}.csv'
DAMAVAND_RESULTS_CLASSIFIER = '../Results/CAE/classifier_results_{0}_{1}.csv'
LOCAL_LOCATION_FPKM_NORMALIZED = "../Data/fpkm_normalized.csv"
LOCAL_LOCATION_CATEGORICAL_DISEASE = "../Data/disease.csv"
LOCAL_LOCATION_ENCODED = "./Results/CAE/old/encoded_scae_dropout.csv"
LOCAL_RESULTS_ENCODED = './Results/CAE/encoded_results_{0}_{1}_notNoised.csv'
# Hyper-Parameters
LEARNING_RATE = 1e-3
DROP_OUT = 0.5
N_SAMPLES = 10787
N_FEATURES = 19671
N_DISEASES = 34
N_BATCHES = 256
N_EPOCHS = 150
N_BATCH_LEARN = 10
N_RANDOM_FEATURES = 200
neurons = {
'in': 12,
'l1': 1024,
'l2': 512,
'l3': 256,
'l4': 128,
'out': N_DISEASES,
'code': 12,
'features': N_FEATURES
}
def run(stddev, x_data, y_data, random_selection=True, seed=2018):
# Train/Test Split
x_train, x_test, y_train, y_test = train_test_split(x_data, y_data, test_size=0.30)
# Random Feature Selection
if random_selection:
np.random.seed(seed)
random_feature_indices = np.random.choice(19671, N_RANDOM_FEATURES, replace=False)
x_train = x_train[random_feature_indices]
x_test = x_test[random_feature_indices]
# network = Sequential()
# Design Model
input_layer = Input(shape=(x_train.shape[1],))
# network.add(input_layer)
# noise_layer = GaussianNoise(stddev)(input_layer)
l1 = Dense(neurons['l1'], activation='relu')(input_layer)
# l1 = BatchNormalization()(l1)
l1_dropout = Dropout(DROP_OUT)(l1)
l2 = Dense(neurons['l2'], activation='relu')(l1_dropout)
# l2 = BatchNormalization()(l2)
l2_dropout = Dropout(DROP_OUT)(l2)
l3 = Dense(neurons['l3'], activation='relu')(l2_dropout)
# l3 = BatchNormalization()(l3)
l3_dropout = Dropout(DROP_OUT)(l3)
l4 = Dense(neurons['l4'], activation='relu')(l3_dropout)
# l4 = BatchNormalization()(l4)
l4_dropout = Dropout(DROP_OUT)(l4)
output_layer = Dense(neurons['out'], activation='softmax')(l4_dropout)
# Compile Model
network = Model(input_layer, output_layer)
network.compile(optimizer='nadam', loss='categorical_crossentropy', metrics=['accuracy'])
# network.summary()
# if not os._exists('./Results/Keras/{0}_{1}/'.format(os.getpid(), stddev)):
# os.makedirs('./Results/Keras/{0}_{1}/'.format(os.getpid(), stddev))
# save_path = './Results/Keras/{0}_{1}/'.format(os.getpid(), stddev) + 'Code.{epoch:02d}-{val_acc:.4f}.hdf5'
# Create a Callback for Model
# checkpointer = ModelCheckpoint(filepath=save_path,
# verbose=0,
# monitor='val_acc',
# save_best_only=True,
# mode='auto',
# period=1)
# get_3rd_layer_output = K.function([network.layers[0].input, K.learning_phase()],
# [network.layers[3].output])
# layer_output = get_3rd_layer_output([x_train, True])
# print(layer_output[0].shape)
# print(len(layer_output))
# print("*" * 100)
# Train Model
# for epoch in range(N_EPOCHS):
# network.fit(x=x_train.as_matrix(),
# y=y_train.as_matrix(),
# epochs=N_EPOCHS,
# batch_size=N_BATCHES,
# shuffle=True,
# validation_data=(x_test.as_matrix(), y_test.as_matrix()),
# callbacks=[checkpointer],
# verbose=2)
network.fit(x=x_train.as_matrix(),
y=y_train.as_matrix(),
epochs=N_EPOCHS,
batch_size=N_BATCHES,
shuffle=True,
validation_data=(x_test.as_matrix(), y_test.as_matrix()),
verbose=2)
# network.save("./classifier-noBatchNorm-noGaussian.h5")
# layer_output.append(get_3rd_layer_output([x_train, True])[0])
# print(layer_output)
# print(layer_output[0].shape)
# print(len(layer_output))
# print("*" * 100)
# Save Accuracy, Loss
import csv
with open(DAMAVAND_RESULTS_CLASSIFIER.format(stddev, N_RANDOM_FEATURES), 'a') as file:
writer = csv.writer(file)
loss, accuracy = network.evaluate(x_test.as_matrix(), y_test.as_matrix(), verbose=0)
writer.writerow([accuracy, loss])
# class DummyCheckpoint(Callback):
# def on_train_begin(self, logs=None):
# self.accuracies = []
#
# def on_epoch_end(self, epoch, logs=None):
# if (max(self.accuracies)) < logs.get('acc'):
# self.accuracies.append(logs.get('acc'))
# return layer_output
def contractive_dropout_autoencoder(machine_name, local_data_folder, local_result_folder, model_specific,
n_random_features, seed=2018):
seed = seed
np.random.seed(seed=seed)
# dataset_folder = "/s/" + machine_name + local_data_folder
dataset_folder = '/Users/Future/Desktop/Summer 2018/Bioinformatics/Feature Selection/Data/dataset_local/'
# dataset_folder = "/s/chopin/a/grad/asharifi/f/Behrooz/dataset_local/"
df_m_rna_address = dataset_folder + "fpkm_normalized.csv"
df_disease_address = dataset_folder + "disease.csv"
df_m_rna = np.loadtxt(df_m_rna_address, delimiter=",")
df_disease = np.ravel(pd.DataFrame.as_matrix(pd.read_csv(df_disease_address, delimiter=",", header=None)))
# df_m_rna = normalize(X=df_m_rna, axis=0, norm="max")
label_encoder_disease = LabelEncoder()
label_encoder_disease.fit(df_disease)
encoded_disease = label_encoder_disease.transform(df_disease)
categorical_disease = np_utils.to_categorical(encoded_disease)
m_rna = df_m_rna
# noise_factor = 0.05
# m_rna_noisy = m_rna + noise_factor * np.random.normal(loc=0.0, scale=1.0, size=m_rna.shape)
np.random.seed(seed)
random_feature_indices = np.random.choice(19671, n_random_features, replace=False)
indices = np.arange(m_rna.shape[0])
indices = indices[0:10787]
np.random.shuffle(indices)
m_rna = m_rna[indices]
# m_rna = m_rna[:, random_feature_indices]
categorical_disease = categorical_disease[indices]
m_rna_train = m_rna[0:9750, ]
m_rna_train_input = m_rna[0:9750, random_feature_indices]
m_rna_test = m_rna[9750:10787, ]
m_rna_test_input = m_rna[9750:10787, random_feature_indices]
categorical_disease_train = categorical_disease[0:9750, ]
categorical_disease_test = categorical_disease[9750: 10787, ]
print("data loading has just been finished")
print(m_rna_train_input.shape, categorical_disease.shape)
batch_size = 64
nb_epochs = 200
def create_model():
inputs = Input(shape=(n_random_features,), name="inputs")
inputs_noise = GaussianNoise(stddev=0.025)(inputs)
inputs_noise = GaussianDropout(rate=0.025 ** 2 / (1 + 0.025 ** 2))(inputs_noise)
inputs_0 = BatchNormalization(name="inputs_0")(inputs_noise)
inputs_0 = Dropout(rate=0.0, name='dropout_1')(inputs_0)
inputs_1 = Dense(1024, activation="softplus", name="inputs_1")(inputs_0)
inputs_2 = BatchNormalization(name="inputs_2")(inputs_1)
inputs_2 = Dropout(rate=0.0, name='dropout_2')(inputs_2)
inputs_3 = Dense(256, activation="softplus", name="inputs_3")(inputs_2)
inputs_4 = BatchNormalization(name="inputs_4")(inputs_3)
inputs_4 = Dropout(rate=0.25, name='dropout_3')(inputs_4)
encoded = Dense(units=12, activation='sigmoid', name='encoded')(inputs_4)
encoded_noise = GaussianNoise(0.025)(encoded)
# encoded_softmax = Dense(units=12, activation='softmax', name='encoded_softmax')(encoded)
# encoded_attention = multiply([encoded, encoded_softmax])
inputs_5 = Dense(512, activation="linear", name="inputs_5")(encoded_noise)
inputs_5 = Dropout(rate=0.25, name='dropout_4')(inputs_5)
decoded_tcga = Dense(units=m_rna.shape[1], activation='relu', name="m_rna")(inputs_5)
cl_2 = Dense(units=categorical_disease.shape[1], activation="softmax", name="cl_disease")(encoded_noise)
scae = Model(inputs=inputs, outputs=[decoded_tcga, cl_2])
lambda_value = 9.5581e-3
def contractive_loss(y_pred, y_true):
mse = backend.mean(backend.square(y_true - y_pred), axis=1)
w = backend.variable(value=scae.get_layer('encoded').get_weights()[0]) # N inputs N_hidden
w = backend.transpose(w) # N_hidden inputs N
h = scae.get_layer('encoded').output
dh = h * (1 - h) # N_batch inputs N_hidden
# N_batch inputs N_hidden * N_hidden inputs 1 = N_batch inputs 1
contractive = lambda_value * backend.sum(dh ** 2 * backend.sum(w ** 2, axis=1), axis=1)
return mse + contractive
# scae.compile(optimizer='nadam',
# loss=[contractive_loss, "mse", "cosine_proximity", "cosine_proximity"],
# loss_weights=[0.001, 0.001, 0.5, 0.5],
# metrics={"m_rna": ["mae", "mse"], "mi_rna": ["mae", "mse"], "cl_tissue": "acc",
# "cl_disease": "acc"})
scae.compile(optimizer='nadam',
loss=[contractive_loss, "mse"],
loss_weights=[0.001, 0.001],
metrics={"m_rna": ["mae", "mse"], "cl_disease": "acc"})
return scae
model = create_model()
# result_folder = "/home/ermia/Desktop/Deep Learning-Bioinfo/Results/"
# result_folder = '/s/' + machine_name + local_result_folder + model_specific
result_folder = '../Results/CAE/'
file_name = "best-scae-dropout.log"
csv_logger = CSVLogger(result_folder + file_name)
history = History()
model.fit(x=m_rna_train_input, y=[m_rna_train, categorical_disease_train],
batch_size=batch_size, epochs=nb_epochs,
callbacks=[csv_logger, history],
validation_data=(
m_rna_test_input, [m_rna_test, categorical_disease_test]), verbose=2)
print(history.history.keys())
print("fitting has just been finished")
model.save_weights("model_weights.h5")
# save the Code and encoded-layer output
# Code.save(filepath=result_folder + "scae-dropout.h5")
#
# layer_name = "encoded"
# encoded_layer_model = Model(inputs=Code.input, outputs=Code.get_layer(layer_name).output)
# encoded_output = encoded_layer_model.predict(df_m_rna)
#
# np.savetxt(X=encoded_output, fname=result_folder + "encoded_scae_dropout.csv", delimiter=",")
#
# noise_matrix = 0.5 * np.random.normal(loc=0.0, scale=1.0, size=encoded_output.shape)
# np.savetxt(X=encoded_output + noise_matrix, fname=result_folder + "encoded_scae_dropout_noised_1.csv",
# delimiter=",")
#
# noise_matrix = 0.5 * np.random.normal(loc=0.0, scale=0.5, size=encoded_output.shape)
# np.savetxt(X=encoded_output + noise_matrix, fname=result_folder + "encoded_scae_dropout_noised_0.5.csv",
# delimiter=",")
#
# noise_matrix = 0.5 * np.random.normal(loc=0.0, scale=0.01, size=encoded_output.shape)
# np.savetxt(X=encoded_output + noise_matrix, fname=result_folder + "encoded_scae_dropout_noised_0.01.csv",
# delimiter=",")
#
# # save the result and prediction value
#
# data_pred = Code.predict(m_rna, batch_size=batch_size, verbose=2)
# np.savetxt(X=m_rna, fname=result_folder + "tcga_genes_scae_dropout.csv", delimiter=",", fmt='%1.3f')
# np.savetxt(X=categorical_disease, fname=result_folder + "categorical_disease_scae_dropout.csv", delimiter=",",
# fmt='%1.3f')
#
# np.savetxt(X=data_pred[0], fname=result_folder + "tcga_genes_scae_dropout_pred.csv", delimiter=",", fmt='%1.3f')
# np.savetxt(X=data_pred[1], fname=result_folder + "micro_rna_scae_dropout_pred.csv", delimiter=",", fmt='%1.3f')
print("prediction process has just been finished")
# import csv
# with open(DAMAVAND_RESULTS_ENCODED.format(0.025, n_random_features), 'a') as file:
# writer = csv.writer(file)
# score = Code.evaluate(m_rna_test_input, [m_rna_test, categorical_disease_test], verbose=0)[0]
# print('score is ', score)
# writer.writerow([float(score)])
# for i in range(1, 51):
# print(i)
# dropout_factor = 1 - np.divide(i, 100)
# dropout_matrix = np.random.binomial(n=1, p=dropout_factor, size=m_rna.shape)
# m_rna_dropout = np.multiply(m_rna, dropout_matrix)
# m_rna_temp_test = m_rna_dropout[9750:10787, ]
# # score = Code.evaluate(m_rna_temp_test,
# # [m_rna_temp_test, mi_rna_test, categorical_tissue_test, categorical_disease_test],
# # verbose=0, batch_size=batch_size)
#
# score = Code.evaluate(m_rna_temp_test,
# [m_rna_temp_test, categorical_disease_test],
# verbose=0, batch_size=batch_size)
# print(score)
#
# # with open(result_folder + 'dropout-Dropout-CAE.txt', 'ab') as file:
# # np.savetxt(file, score, delimiter=",")
#
# print("dropout has just been finished")
#
# for i in range(1, 51):
# print(i)
# noise_factor = np.divide(i, 100)
# noise_matrix = noise_factor * np.random.normal(loc=0.0, scale=1.0, size=m_rna.shape)
# m_rna_noisy = m_rna + noise_matrix
# m_rna_temp_test = m_rna_noisy[9750:10787, ]
# # score = Code.evaluate(m_rna_temp_test,
# # [m_rna_temp_test, mi_rna_test, categorical_tissue_test, categorical_disease_test],
# # verbose=0, batch_size=batch_size)
#
# score = Code.evaluate(m_rna_temp_test,
# [m_rna_temp_test, categorical_disease_test],
# verbose=0, batch_size=batch_size)
# print(score)
#
# # with open(result_folder + 'gaussian-Dropout-CAE.txt', 'ab') as file:
# # np.savetxt(file, score, delimiter=",")
print("gaussian has just been finished")
def auto_encoder(stddev=0.0, x_data=None, y_data=None, n_features=10, random_selection=False, seed=2018):
# noise_matrix = 0.5 * np.random.normal(loc=0.0, scale=stddev, size=y_data.shape)
# y_data_noised = y_data + noise_matrix
# Train/Test Split
x_train, x_test, y_train, y_test = train_test_split(x_data, y_data, test_size=0.30, shuffle=True)
# Random Feature Selection
if random_selection:
if random_selection:
np.random.seed(seed)
random_feature_indices = np.random.choice(19671, n_features, replace=False)
x_train_random = x_train[random_feature_indices]
x_test_random = x_test[random_feature_indices]
def create_model():
input_layer = Input(shape=(n_features,))
l1 = Dense(neurons['l1'], activation='relu')(input_layer)
l1 = BatchNormalization()(l1)
l1_dropout = Dropout(DROP_OUT)(l1)
l2 = Dense(neurons['l2'], activation='relu')(l1_dropout)
l2 = BatchNormalization()(l2)
l2_dropout = Dropout(DROP_OUT)(l2)
l3 = Dense(neurons['l3'], activation='relu')(l2_dropout)
l3 = BatchNormalization()(l3)
l3_dropout = Dropout(DROP_OUT)(l3)
l4 = Dense(neurons['l4'], activation='relu')(l3_dropout)
l4 = BatchNormalization()(l4)
l4_dropout = Dropout(DROP_OUT)(l4)
encoded = Dense(neurons['code'], activation='sigmoid')(l4_dropout)
# encoded = GaussianNoise(0.025)(encoded)
inputs_5 = Dense(512, activation="linear")(encoded)
inputs_5 = Dropout(rate=0.25)(inputs_5)
decoded = Dense(units=N_FEATURES, activation='relu')(inputs_5)
# Compile Model
network = Model(input_layer, decoded)
network.compile(optimizer='nadam', loss='mse')
return network
model = create_model()
model.fit(x=x_train_random.as_matrix(), y=y_train.as_matrix(),
epochs=N_EPOCHS,
batch_size=N_BATCHES,
shuffle=True,
validation_data=(x_test_random.as_matrix(), y_test.as_matrix()),
verbose=2)
import csv
with open(LOCAL_RESULTS_ENCODED.format(stddev, n_features), 'a') as file:
writer = csv.writer(file)
score = model.evaluate(x_test_random.as_matrix(), y_test.as_matrix(), verbose=0)
print('score is ', score)
writer.writerow([float(score)])
K.in_top_k
if __name__ == '__main__':
# Load Data
# x_data = pd.read_csv(LOCAL_LOCATION_FPKM_NORMALIZED, header=None)
# y_data = pd.read_csv(LOCAL_LOCATION_CATEGORICAL_DISEASE, header=None)
# noise_matrix = 0.0 * np.random.normal(loc=0.0, scale=1.0, size=y_data.shape)
# y_data += noise_matrix
# label_encoder = LabelEncoder()
# label_encoder.fit(y_data)
# label_encoder = label_encoder.transform(y_data)
# y_data = pd.DataFrame(keras.utils.to_categorical(label_encoder))
# print(x_data.shape, y_data.shape)
# for i in range(1000):
# for n_features in reversed([2, 4, 8, 16, 32, 64, 128, 256, 512]):
# auto_encoder(0.01, x_data, x_data, n_features=n_features, random_selection=True, seed=2018 * n_features)
n_features = 512;
contractive_dropout_autoencoder(machine_name="local",
local_data_folder=DAMAVAND_LOCATION_FPKM_NORMALIZED,
local_result_folder="../Results/", model_specific="optimal_",
n_random_features=n_features, seed=2018 * n_features)
# for i in range(1000):
# for N_RANDOM_FEATURES in [50, 100, 150, 200]:
# run(0, x_data, y_data, random_selection=False)
print("Finished")
| [
"sklearn.preprocessing.LabelEncoder",
"keras.backend.sum",
"pandas.read_csv",
"keras.callbacks.History",
"keras.layers.Dense",
"numpy.arange",
"keras.backend.square",
"numpy.random.seed",
"keras.models.Model",
"keras.backend.transpose",
"keras.layers.GaussianNoise",
"keras.callbacks.CSVLogger"... | [((1716, 1763), 'sklearn.model_selection.train_test_split', 'train_test_split', (['x_data', 'y_data'], {'test_size': '(0.3)'}), '(x_data, y_data, test_size=0.3)\n', (1732, 1763), False, 'from sklearn.model_selection import train_test_split\n'), ((2107, 2139), 'keras.layers.Input', 'Input', ([], {'shape': '(x_train.shape[1],)'}), '(shape=(x_train.shape[1],))\n', (2112, 2139), False, 'from keras.layers import Input, Dense, Dropout, GaussianNoise, BatchNormalization, GaussianDropout\n'), ((2887, 2919), 'keras.models.Model', 'Model', (['input_layer', 'output_layer'], {}), '(input_layer, output_layer)\n', (2892, 2919), False, 'from keras.models import Model, Sequential\n'), ((5732, 5757), 'numpy.random.seed', 'np.random.seed', ([], {'seed': 'seed'}), '(seed=seed)\n', (5746, 5757), True, 'import numpy as np\n'), ((6144, 6187), 'numpy.loadtxt', 'np.loadtxt', (['df_m_rna_address'], {'delimiter': '""","""'}), "(df_m_rna_address, delimiter=',')\n", (6154, 6187), True, 'import numpy as np\n'), ((6388, 6402), 'sklearn.preprocessing.LabelEncoder', 'LabelEncoder', ([], {}), '()\n', (6400, 6402), False, 'from sklearn.preprocessing import LabelEncoder, normalize\n'), ((6538, 6578), 'keras.utils.np_utils.to_categorical', 'np_utils.to_categorical', (['encoded_disease'], {}), '(encoded_disease)\n', (6561, 6578), False, 'from keras.utils import np_utils\n'), ((6730, 6750), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (6744, 6750), True, 'import numpy as np\n'), ((6780, 6837), 'numpy.random.choice', 'np.random.choice', (['(19671)', 'n_random_features'], {'replace': '(False)'}), '(19671, n_random_features, replace=False)\n', (6796, 6837), True, 'import numpy as np\n'), ((6853, 6878), 'numpy.arange', 'np.arange', (['m_rna.shape[0]'], {}), '(m_rna.shape[0])\n', (6862, 6878), True, 'import numpy as np\n'), ((6914, 6940), 'numpy.random.shuffle', 'np.random.shuffle', (['indices'], {}), '(indices)\n', (6931, 6940), True, 'import numpy as np\n'), ((10597, 10633), 'keras.callbacks.CSVLogger', 'CSVLogger', (['(result_folder + file_name)'], {}), '(result_folder + file_name)\n', (10606, 10633), False, 'from keras.callbacks import ModelCheckpoint, CSVLogger, History\n'), ((10648, 10657), 'keras.callbacks.History', 'History', ([], {}), '()\n', (10655, 10657), False, 'from keras.callbacks import ModelCheckpoint, CSVLogger, History\n'), ((15411, 15472), 'sklearn.model_selection.train_test_split', 'train_test_split', (['x_data', 'y_data'], {'test_size': '(0.3)', 'shuffle': '(True)'}), '(x_data, y_data, test_size=0.3, shuffle=True)\n', (15427, 15472), False, 'from sklearn.model_selection import train_test_split\n'), ((1830, 1850), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (1844, 1850), True, 'import numpy as np\n'), ((1884, 1941), 'numpy.random.choice', 'np.random.choice', (['(19671)', 'N_RANDOM_FEATURES'], {'replace': '(False)'}), '(19671, N_RANDOM_FEATURES, replace=False)\n', (1900, 1941), True, 'import numpy as np\n'), ((2237, 2276), 'keras.layers.Dense', 'Dense', (["neurons['l1']"], {'activation': '"""relu"""'}), "(neurons['l1'], activation='relu')\n", (2242, 2276), False, 'from keras.layers import Input, Dense, Dropout, GaussianNoise, BatchNormalization, GaussianDropout\n'), ((2343, 2360), 'keras.layers.Dropout', 'Dropout', (['DROP_OUT'], {}), '(DROP_OUT)\n', (2350, 2360), False, 'from keras.layers import Input, Dense, Dropout, GaussianNoise, BatchNormalization, GaussianDropout\n'), ((2375, 2414), 'keras.layers.Dense', 'Dense', (["neurons['l2']"], {'activation': '"""relu"""'}), "(neurons['l2'], activation='relu')\n", (2380, 2414), False, 'from keras.layers import Input, Dense, Dropout, GaussianNoise, BatchNormalization, GaussianDropout\n'), ((2480, 2497), 'keras.layers.Dropout', 'Dropout', (['DROP_OUT'], {}), '(DROP_OUT)\n', (2487, 2497), False, 'from keras.layers import Input, Dense, Dropout, GaussianNoise, BatchNormalization, GaussianDropout\n'), ((2512, 2551), 'keras.layers.Dense', 'Dense', (["neurons['l3']"], {'activation': '"""relu"""'}), "(neurons['l3'], activation='relu')\n", (2517, 2551), False, 'from keras.layers import Input, Dense, Dropout, GaussianNoise, BatchNormalization, GaussianDropout\n'), ((2617, 2634), 'keras.layers.Dropout', 'Dropout', (['DROP_OUT'], {}), '(DROP_OUT)\n', (2624, 2634), False, 'from keras.layers import Input, Dense, Dropout, GaussianNoise, BatchNormalization, GaussianDropout\n'), ((2649, 2688), 'keras.layers.Dense', 'Dense', (["neurons['l4']"], {'activation': '"""relu"""'}), "(neurons['l4'], activation='relu')\n", (2654, 2688), False, 'from keras.layers import Input, Dense, Dropout, GaussianNoise, BatchNormalization, GaussianDropout\n'), ((2754, 2771), 'keras.layers.Dropout', 'Dropout', (['DROP_OUT'], {}), '(DROP_OUT)\n', (2761, 2771), False, 'from keras.layers import Input, Dense, Dropout, GaussianNoise, BatchNormalization, GaussianDropout\n'), ((2796, 2839), 'keras.layers.Dense', 'Dense', (["neurons['out']"], {'activation': '"""softmax"""'}), "(neurons['out'], activation='softmax')\n", (2801, 2839), False, 'from keras.layers import Input, Dense, Dropout, GaussianNoise, BatchNormalization, GaussianDropout\n'), ((5062, 5078), 'csv.writer', 'csv.writer', (['file'], {}), '(file)\n', (5072, 5078), False, 'import csv\n'), ((7596, 7644), 'keras.layers.Input', 'Input', ([], {'shape': '(n_random_features,)', 'name': '"""inputs"""'}), "(shape=(n_random_features,), name='inputs')\n", (7601, 7644), False, 'from keras.layers import Input, Dense, Dropout, GaussianNoise, BatchNormalization, GaussianDropout\n'), ((9027, 9077), 'keras.models.Model', 'Model', ([], {'inputs': 'inputs', 'outputs': '[decoded_tcga, cl_2]'}), '(inputs=inputs, outputs=[decoded_tcga, cl_2])\n', (9032, 9077), False, 'from keras.models import Model, Sequential\n'), ((15848, 15874), 'keras.layers.Input', 'Input', ([], {'shape': '(n_features,)'}), '(shape=(n_features,))\n', (15853, 15874), False, 'from keras.layers import Input, Dense, Dropout, GaussianNoise, BatchNormalization, GaussianDropout\n'), ((16814, 16841), 'keras.models.Model', 'Model', (['input_layer', 'decoded'], {}), '(input_layer, decoded)\n', (16819, 16841), False, 'from keras.models import Model, Sequential\n'), ((17328, 17344), 'csv.writer', 'csv.writer', (['file'], {}), '(file)\n', (17338, 17344), False, 'import csv\n'), ((6237, 6296), 'pandas.read_csv', 'pd.read_csv', (['df_disease_address'], {'delimiter': '""","""', 'header': 'None'}), "(df_disease_address, delimiter=',', header=None)\n", (6248, 6296), True, 'import pandas as pd\n'), ((7668, 7695), 'keras.layers.GaussianNoise', 'GaussianNoise', ([], {'stddev': '(0.025)'}), '(stddev=0.025)\n', (7681, 7695), False, 'from keras.layers import Input, Dense, Dropout, GaussianNoise, BatchNormalization, GaussianDropout\n'), ((7727, 7778), 'keras.layers.GaussianDropout', 'GaussianDropout', ([], {'rate': '(0.025 ** 2 / (1 + 0.025 ** 2))'}), '(rate=0.025 ** 2 / (1 + 0.025 ** 2))\n', (7742, 7778), False, 'from keras.layers import Input, Dense, Dropout, GaussianNoise, BatchNormalization, GaussianDropout\n'), ((7812, 7847), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'name': '"""inputs_0"""'}), "(name='inputs_0')\n", (7830, 7847), False, 'from keras.layers import Input, Dense, Dropout, GaussianNoise, BatchNormalization, GaussianDropout\n'), ((7881, 7916), 'keras.layers.Dropout', 'Dropout', ([], {'rate': '(0.0)', 'name': '"""dropout_1"""'}), "(rate=0.0, name='dropout_1')\n", (7888, 7916), False, 'from keras.layers import Input, Dense, Dropout, GaussianNoise, BatchNormalization, GaussianDropout\n'), ((7946, 7997), 'keras.layers.Dense', 'Dense', (['(1024)'], {'activation': '"""softplus"""', 'name': '"""inputs_1"""'}), "(1024, activation='softplus', name='inputs_1')\n", (7951, 7997), False, 'from keras.layers import Input, Dense, Dropout, GaussianNoise, BatchNormalization, GaussianDropout\n'), ((8027, 8062), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'name': '"""inputs_2"""'}), "(name='inputs_2')\n", (8045, 8062), False, 'from keras.layers import Input, Dense, Dropout, GaussianNoise, BatchNormalization, GaussianDropout\n'), ((8092, 8127), 'keras.layers.Dropout', 'Dropout', ([], {'rate': '(0.0)', 'name': '"""dropout_2"""'}), "(rate=0.0, name='dropout_2')\n", (8099, 8127), False, 'from keras.layers import Input, Dense, Dropout, GaussianNoise, BatchNormalization, GaussianDropout\n'), ((8157, 8207), 'keras.layers.Dense', 'Dense', (['(256)'], {'activation': '"""softplus"""', 'name': '"""inputs_3"""'}), "(256, activation='softplus', name='inputs_3')\n", (8162, 8207), False, 'from keras.layers import Input, Dense, Dropout, GaussianNoise, BatchNormalization, GaussianDropout\n'), ((8237, 8272), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'name': '"""inputs_4"""'}), "(name='inputs_4')\n", (8255, 8272), False, 'from keras.layers import Input, Dense, Dropout, GaussianNoise, BatchNormalization, GaussianDropout\n'), ((8302, 8338), 'keras.layers.Dropout', 'Dropout', ([], {'rate': '(0.25)', 'name': '"""dropout_3"""'}), "(rate=0.25, name='dropout_3')\n", (8309, 8338), False, 'from keras.layers import Input, Dense, Dropout, GaussianNoise, BatchNormalization, GaussianDropout\n'), ((8368, 8421), 'keras.layers.Dense', 'Dense', ([], {'units': '(12)', 'activation': '"""sigmoid"""', 'name': '"""encoded"""'}), "(units=12, activation='sigmoid', name='encoded')\n", (8373, 8421), False, 'from keras.layers import Input, Dense, Dropout, GaussianNoise, BatchNormalization, GaussianDropout\n'), ((8456, 8476), 'keras.layers.GaussianNoise', 'GaussianNoise', (['(0.025)'], {}), '(0.025)\n', (8469, 8476), False, 'from keras.layers import Input, Dense, Dropout, GaussianNoise, BatchNormalization, GaussianDropout\n'), ((8673, 8721), 'keras.layers.Dense', 'Dense', (['(512)'], {'activation': '"""linear"""', 'name': '"""inputs_5"""'}), "(512, activation='linear', name='inputs_5')\n", (8678, 8721), False, 'from keras.layers import Input, Dense, Dropout, GaussianNoise, BatchNormalization, GaussianDropout\n'), ((8756, 8792), 'keras.layers.Dropout', 'Dropout', ([], {'rate': '(0.25)', 'name': '"""dropout_4"""'}), "(rate=0.25, name='dropout_4')\n", (8763, 8792), False, 'from keras.layers import Input, Dense, Dropout, GaussianNoise, BatchNormalization, GaussianDropout\n'), ((8827, 8887), 'keras.layers.Dense', 'Dense', ([], {'units': 'm_rna.shape[1]', 'activation': '"""relu"""', 'name': '"""m_rna"""'}), "(units=m_rna.shape[1], activation='relu', name='m_rna')\n", (8832, 8887), False, 'from keras.layers import Input, Dense, Dropout, GaussianNoise, BatchNormalization, GaussianDropout\n'), ((8913, 9000), 'keras.layers.Dense', 'Dense', ([], {'units': 'categorical_disease.shape[1]', 'activation': '"""softmax"""', 'name': '"""cl_disease"""'}), "(units=categorical_disease.shape[1], activation='softmax', name=\n 'cl_disease')\n", (8918, 9000), False, 'from keras.layers import Input, Dense, Dropout, GaussianNoise, BatchNormalization, GaussianDropout\n'), ((9352, 9372), 'keras.backend.transpose', 'backend.transpose', (['w'], {}), '(w)\n', (9369, 9372), True, 'import keras.backend as backend\n'), ((15572, 15592), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (15586, 15592), True, 'import numpy as np\n'), ((15630, 15680), 'numpy.random.choice', 'np.random.choice', (['(19671)', 'n_features'], {'replace': '(False)'}), '(19671, n_features, replace=False)\n', (15646, 15680), True, 'import numpy as np\n'), ((15889, 15928), 'keras.layers.Dense', 'Dense', (["neurons['l1']"], {'activation': '"""relu"""'}), "(neurons['l1'], activation='relu')\n", (15894, 15928), False, 'from keras.layers import Input, Dense, Dropout, GaussianNoise, BatchNormalization, GaussianDropout\n'), ((15955, 15975), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (15973, 15975), False, 'from keras.layers import Input, Dense, Dropout, GaussianNoise, BatchNormalization, GaussianDropout\n'), ((16001, 16018), 'keras.layers.Dropout', 'Dropout', (['DROP_OUT'], {}), '(DROP_OUT)\n', (16008, 16018), False, 'from keras.layers import Input, Dense, Dropout, GaussianNoise, BatchNormalization, GaussianDropout\n'), ((16037, 16076), 'keras.layers.Dense', 'Dense', (["neurons['l2']"], {'activation': '"""relu"""'}), "(neurons['l2'], activation='relu')\n", (16042, 16076), False, 'from keras.layers import Input, Dense, Dropout, GaussianNoise, BatchNormalization, GaussianDropout\n'), ((16102, 16122), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (16120, 16122), False, 'from keras.layers import Input, Dense, Dropout, GaussianNoise, BatchNormalization, GaussianDropout\n'), ((16148, 16165), 'keras.layers.Dropout', 'Dropout', (['DROP_OUT'], {}), '(DROP_OUT)\n', (16155, 16165), False, 'from keras.layers import Input, Dense, Dropout, GaussianNoise, BatchNormalization, GaussianDropout\n'), ((16184, 16223), 'keras.layers.Dense', 'Dense', (["neurons['l3']"], {'activation': '"""relu"""'}), "(neurons['l3'], activation='relu')\n", (16189, 16223), False, 'from keras.layers import Input, Dense, Dropout, GaussianNoise, BatchNormalization, GaussianDropout\n'), ((16249, 16269), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (16267, 16269), False, 'from keras.layers import Input, Dense, Dropout, GaussianNoise, BatchNormalization, GaussianDropout\n'), ((16295, 16312), 'keras.layers.Dropout', 'Dropout', (['DROP_OUT'], {}), '(DROP_OUT)\n', (16302, 16312), False, 'from keras.layers import Input, Dense, Dropout, GaussianNoise, BatchNormalization, GaussianDropout\n'), ((16331, 16370), 'keras.layers.Dense', 'Dense', (["neurons['l4']"], {'activation': '"""relu"""'}), "(neurons['l4'], activation='relu')\n", (16336, 16370), False, 'from keras.layers import Input, Dense, Dropout, GaussianNoise, BatchNormalization, GaussianDropout\n'), ((16396, 16416), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (16414, 16416), False, 'from keras.layers import Input, Dense, Dropout, GaussianNoise, BatchNormalization, GaussianDropout\n'), ((16442, 16459), 'keras.layers.Dropout', 'Dropout', (['DROP_OUT'], {}), '(DROP_OUT)\n', (16449, 16459), False, 'from keras.layers import Input, Dense, Dropout, GaussianNoise, BatchNormalization, GaussianDropout\n'), ((16483, 16527), 'keras.layers.Dense', 'Dense', (["neurons['code']"], {'activation': '"""sigmoid"""'}), "(neurons['code'], activation='sigmoid')\n", (16488, 16527), False, 'from keras.layers import Input, Dense, Dropout, GaussianNoise, BatchNormalization, GaussianDropout\n'), ((16610, 16641), 'keras.layers.Dense', 'Dense', (['(512)'], {'activation': '"""linear"""'}), "(512, activation='linear')\n", (16615, 16641), False, 'from keras.layers import Input, Dense, Dropout, GaussianNoise, BatchNormalization, GaussianDropout\n'), ((16670, 16688), 'keras.layers.Dropout', 'Dropout', ([], {'rate': '(0.25)'}), '(rate=0.25)\n', (16677, 16688), False, 'from keras.layers import Input, Dense, Dropout, GaussianNoise, BatchNormalization, GaussianDropout\n'), ((16718, 16760), 'keras.layers.Dense', 'Dense', ([], {'units': 'N_FEATURES', 'activation': '"""relu"""'}), "(units=N_FEATURES, activation='relu')\n", (16723, 16760), False, 'from keras.layers import Input, Dense, Dropout, GaussianNoise, BatchNormalization, GaussianDropout\n'), ((9190, 9221), 'keras.backend.square', 'backend.square', (['(y_true - y_pred)'], {}), '(y_true - y_pred)\n', (9204, 9221), True, 'import keras.backend as backend\n'), ((9640, 9667), 'keras.backend.sum', 'backend.sum', (['(w ** 2)'], {'axis': '(1)'}), '(w ** 2, axis=1)\n', (9651, 9667), True, 'import keras.backend as backend\n')] |
"""
A collection of classes extending the functionality of Python's builtins.
email <EMAIL>
"""
import re
import typing
import string
import enum
import os
import sys
from glob import glob
from pathlib import Path
import copy
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# %% ========================== File Management =========================================
class Base:
def __init__(self, *args, **kwargs):
pass
@classmethod
def from_saved(cls, path, *args, reader=None, **kwargs):
"""Whether the save format is .json, .mat, .pickle or .npy, Reader returns Structure
For best experience, make sure that your subclass can be initialized with no or only fake inputs.
"""
inst = cls(*args, **kwargs)
if reader is None:
data = Read.read(path)
else:
data = reader(path)
# return inst, data
new_data = data.dict if type(data) is Struct else data # __setitem__ should be defined.
inst.__dict__.update(new_data)
return inst
def save_npy(self, path, **kwargs):
np.save(path, self.__dict__, **kwargs)
def save_pickle(self, path, itself=False, **kwargs):
"""
:param path:
:param itself: determiens whether to save the weights only or the entire class.
"""
if not itself:
Save.pickle(path, self.__dict__, **kwargs)
else:
Save.pickle(path, self, **kwargs)
def save_json(self, path, *args, **kwargs):
"""Use case: json is good for simple dicts, e.g. settings.
Advantage: human-readable from file explorer."""
_ = args
Save.json(path, self.__dict__, **kwargs)
return self
def save_mat(self, path, *args, **kwargs):
"""for Matlab compatibility."""
_ = args
Save.mat(path, self.__dict__, **kwargs)
return self
def get_attributes(self):
attrs = list(filter(lambda x: ('__' not in x) and not x.startswith("_"), dir(self)))
return attrs
# [setattr(Path, name, getattr(MyPath, name)) for name in funcs]
# def get_methods(self):
# def get_dict(self):
# return list(self.__dict__.keys())
def __deepcopy__(self, *args, **kwargs):
"""Literally creates a new copy of values of old object, rather than referencing them.
similar to copy.deepcopy()"""
obj = self.__class__(*args, **kwargs)
obj.__dict__.update(copy.deepcopy(self.__dict__))
return obj
def __copy__(self, *args, **kwargs):
"""Shallow copy. New object, but the keys of which are referencing the values from the old object.
Does similar functionality to copy.copy"""
obj = self.__class__(*args, **kwargs)
obj.__dict__.update(self.__dict__.copy())
return obj
def evalstr(self, string_, expected='self'):
_ = self
if type(string_) is str:
if expected == 'func':
return eval("lambda x: " + string_)
elif expected == 'self':
if "self" in string_:
return eval(string_)
else:
return string_
else:
return string_
class P(type(Path()), Path, Base):
"""Path Class: Designed with one goal in mind: any operation on paths MUST NOT take more than one line of code.
"""
# ===================================== File Specs ================================================================
def size(self, units='mb'):
sizes = List(['b', 'kb', 'mb', 'gb'])
factor = dict(zip(sizes + sizes.apply("x.swapcase()"),
np.tile(1024 ** np.arange(len(sizes)), 2)))[units]
if self.is_file():
total_size = self.stat().st_size
elif self.is_dir():
results = self.rglob("*")
total_size = 0
for item in results:
if item.is_file():
total_size += item.stat().st_size
else:
raise TypeError("This thing is not a file nor a folder.")
return round(total_size / factor, 1)
def time(self, which="m", **kwargs):
"""Meaning of ``which values``
* ``m`` time of modifying file ``content``, i.e. the time it was created.
* ``c`` time of changing file status (its inode is changed like permissions, name etc, but not contents)
* ``a`` last time the file was accessed.
:param which: Determines which time to be returned. Three options are availalable:
:param kwargs:
:return:
"""
time = {"m": self.stat().st_mtime, "a": self.stat().st_atime, "c": self.stat().st_ctime}[which]
from datetime import datetime
return datetime.fromtimestamp(time, **kwargs)
# ================================ Path Object management ===========================================
@property
def trunk(self):
""" useful if you have multiple dots in file name where .stem fails.
"""
return self.name.split('.')[0]
def __add__(self, name):
return self.parent.joinpath(self.stem + name)
def __sub__(self, other):
return P(str(self).replace(str(other), ""))
# def __rtruediv__(self, other):
# tmp = str(self)
# if tmp[0] == "/": # if dir starts with this, all Path methods fail.
# tmp = tmp[1:]
# return P(other) / tmp
def prepend(self, prefix, stem=False):
"""Add extra text before file name
e.g: blah\blah.extenion ==> becomes ==> blah/name_blah.extension
"""
if stem:
return self.parent.joinpath(prefix + self.stem)
else:
return self.parent.joinpath(prefix + self.name)
def append(self, name='', suffix=None):
"""Add extra text after file name, and optionally add extra suffix.
e.g: blah\blah.extenion ==> becomes ==> blah/blah_name.extension
"""
if suffix is None:
suffix = ''.join(self.suffixes)
return self.parent.joinpath(self.stem + name + suffix)
def append_time_stamp(self, ft=None):
return self.append(name="-" + get_time_stamp(ft=ft))
def absolute_from(self, reference=None):
"""As opposed to ``relative_to`` which takes two abolsute paths and make ``self`` relative to ``reference``,
this one takes in two relative paths, and return an absolute version of `self` the reference
for which is ``reference``.
:param reference: a directory `name` from which the current relative path ``self`` is defined.
Default value of reference is current directory name, making the method act like ``absolute`` method
.. warning:: ``reference`` should be within working directory, otherwise it raises an error.
.. note:: If you have the full path of the reference, then this method would give the same result as
agoing with `reference / self`
"""
if reference is None:
reference = P.cwd()[-1].string
return P.cwd().split(at=reference)[0] / reference / self
def split(self, at : str =None, index : int =None, sep: int= 1):
"""Splits a path at a given string or index
:param self:
:param at:
:param index:
:param sep: can be either [-1, 0, 1]. Determines where the separator is going to live with:
left portion, none or right portion.
:return: two paths
"""
if index is None: # at is provided
items = str(self).split(sep=at)
one, two = items[0], items[1]
one = one[:-1] if one.endswith("/") else one
two = two[1:] if two.startswith("/") else two
one, two = P(one), P(two)
else:
one = self[:index]
two = P(*self.parts[index + 1:])
# appending `at` to one of the portions
if sep == 0:
pass # neither of the portions get the sperator appended to it.
elif sep == 1: # append it to right portion
two = at / two
elif sep == -1: # append it to left portion.
one = one / at
else:
raise ValueError(f"`sep` should take a value from the set [-1, 0, 1] but got {sep}")
return one, two
def __getitem__(self, slici):
if type(slici) is slice:
return P(*self.parts[slici])
elif type(slici) is list or type(slice) is np.ndarray:
return P(*[self[item] for item in slici])
else:
return P(self.parts[slici])
def __len__(self):
return len(self.parts)
@property
def len(self):
return self.__len__()
def __setitem__(self, key, value):
fullparts = list(self.parts)
fullparts[key] = value
return P(*fullparts) # TODO: how to change self[-1]
def switch(self, key: str, val: str):
"""Changes a given part of the path to another given one"""
return P(str(self).replace(key, val))
def switch_index(self, key: int, val: str):
"""Changes a given index of the path to another given one"""
fullparts = list(self.parts)
fullparts[key] = val
return P(*fullparts)
def __deepcopy__(self, memodict=None):
if memodict is None:
_ = {}
return P(str(self))
# ================================ String Nature management ====================================
def __repr__(self): # this is useful only for the console
return "P: " + self.__str__()
@property
def string(self): # this method is used by other functions to get string representation of path
return str(self)
def get_num(self, astring=None):
if astring is None:
astring = self.stem
return int("".join(filter(str.isdigit, str(astring))))
def make_valid_filename(self, replace='_'):
return self.make_valid_filename_(self.trunk, replace=replace)
@staticmethod
def make_valid_filename_(astring, replace='_'):
return re.sub(r'^(?=\d)|\W', replace, str(astring))
@staticmethod
def get_random_string(length=10, pool=None):
if pool is None:
pool = string.ascii_letters
import random
result_str = ''.join(random.choice(pool) for _ in range(length))
return result_str
def as_unix(self):
return P(str(self).replace('\\', '/').replace('//', '/'))
# ==================================== File management =========================================
def delete(self, are_you_sure=False):
if are_you_sure:
if self.is_file():
self.unlink() # missing_ok=True added in 3.8
else:
import shutil
shutil.rmtree(self, ignore_errors=True)
# self.rmdir() # dir must be empty
else:
print("File not deleted because user is not sure.")
def send2trash(self):
send2trash = Experimental.assert_package_installed("send2trash")
send2trash.send2trash(self.string)
def move(self, new_path):
new_path = P(new_path)
temp = self.absolute()
temp.rename(new_path.absolute() / temp.name)
return new_path
def renameit(self, new_name):
new_path = self.parent / new_name
self.rename(new_path)
return new_path
def copy(self, target_dir=None, target_name=None, contents=False, verbose=False):
"""
:param target_dir: copy the file to this directory (filename remains the same).
:param target_name: full path of destination (including -potentially different- file name).
:param contents: copy the parent directory or its contents (relevant only if copying a directory)
:param verbose:
:return: path to copied file or directory.
.. wanring:: Do not confuse this with ``copy`` module that creates clones of Python objects.
"""
dest = None # destination.
if target_dir is not None:
assert target_name is None, f"You can either pass target_dir or target_name but not both"
dest = P(target_dir).create() / self.name
if target_name is not None:
assert target_dir is None, f"You can either pass target_dir or target_name but not both"
target_name = P(target_name)
target_name.parent.create()
dest = target_name
if dest is None:
dest = self.append(f"_copy__{get_time_stamp()}")
if self.is_file():
import shutil
shutil.copy(str(self), str(dest)) # str() only there for Python < (3.6)
if verbose:
print(f"File \n{self}\ncopied successfully to: \n{dest}")
elif self.is_dir():
from distutils.dir_util import copy_tree
if contents:
copy_tree(str(self), str(dest))
else:
copy_tree(str(self), str(P(dest).joinpath(self.name).create()))
else:
print("Could not copy this thing. Not a file nor a folder.")
return dest
def clean(self):
"""removes contents on a folder, rather than deleting the folder."""
contents = self.listdir()
for content in contents:
self.joinpath(content).send2trash()
return self
def readit(self, reader=None, notfound=FileNotFoundError, verbose=False, **kwargs):
"""
:param reader: function that reads this file format, if not passed it will be inferred from extension.
:param notfound: behaviour when file ``self`` to be read doesn't actually exist. Default: throw an error.
can be set to return `False` or any other value that will be returned if file not found.
:param verbose:
:param kwargs:
:return:
"""
filename = self
if '.zip' in str(self):
filename = self.unzip(op_path=tmp("unzipped"))
if verbose:
print(f"File {self} was uncompressed to {filename}")
def apply_reader_or_infer_it():
if reader is None:
return Read.read(filename, **kwargs)
else:
return reader(str(filename), **kwargs)
if notfound is FileNotFoundError:
return apply_reader_or_infer_it()
else: # encapsulate the function within a try context manager.
try:
return apply_reader_or_infer_it()
except Exception:
return notfound
def explore(self): # explore folders.
# os.startfile(os.path.realpath(self))
filename = self.absolute().string
if sys.platform == "win32":
os.startfile(filename) # works for files and folders alike
elif sys.platform == 'linux':
import subprocess
opener = "xdg-open"
subprocess.call([opener, filename]) # works for files and folders alike
else: # mac
# os.system(f"open {filename}")
import subprocess
subprocess.call(["open", filename]) # works for files and folders alike
# ======================================== Folder management =======================================
def create(self, parents=True, exist_ok=True, parent_only=False):
"""Creates directory while returning the same object
"""
if parent_only:
self.parent.mkdir(parents=parents, exist_ok=exist_ok)
else:
self.mkdir(parents=parents, exist_ok=exist_ok)
return self
@property
def browse(self):
return self.search("*").to_struct(key_val=lambda x: ("qq_" + x.make_valid_filename(), x)).clean_view
def search(self, pattern='*', r=False, generator=False, files=True, folders=True, compressed=False,
dotfiles=False,
absolute=True, filters: list = None, not_in: list = None, win_order=False):
"""
:param pattern: linux search pattern
:param r: recursive search flag
:param generator: output format, list or generator.
:param files: include files in search.
:param folders: include directories in search.
:param dotfiles: flag to indicate whether the search should include those or not.
:param filters: list of filters
:param absolute: return relative paths or abosolute ones.
:param not_in: list of strings that search results should not contain them (short for filter with simple lambda)
:param win_order: return search results in the order of files as they appear on a Windows machine.
:return: search results.
# :param visible: exclude hidden files and folders (Windows)
"""
# ================= Get concrete values for default arguments ========================================
if filters is None:
filters = []
else:
pass
if not_in is not None:
for notin in not_in:
filters += [lambda x: str(notin) not in str(x)]
# ============================ get generator of search results ========================================
if self.suffix == ".zip":
import zipfile
with zipfile.ZipFile(str(self)) as z:
contents = L(z.namelist())
from fnmatch import fnmatch
raw = contents.filter(lambda x: fnmatch(x, pattern)).apply(lambda x: self / x)
elif dotfiles:
raw = self.glob(pattern) if not r else self.rglob(pattern)
else:
if r:
path = self / "**" / pattern
raw = glob(str(path), recursive=r)
else:
path = self.joinpath(pattern)
raw = glob(str(path))
if compressed:
comp_files = L(raw).filter(lambda x: '.zip' in str(x))
for comp_file in comp_files:
raw += P(comp_file).search(pattern=pattern, r=r, generator=generator, files=files, folders=folders,
compressed=compressed,
dotfiles=dotfiles,
absolute=absolute, filters=filters, not_in=not_in, win_order=win_order)
# if os.name == 'nt':
# import win32api, win32con
# def folder_is_hidden(p):
# if os.name == 'nt':
# attribute = win32api.GetFileAttributes(p)
# return attribute & (win32con.FILE_ATTRIBUTE_HIDDEN | win32con.FILE_ATTRIBUTE_SYSTEM)
def run_filter(item):
flags = [True]
if not files:
flags.append(item.is_dir())
if not folders:
flags.append(item.is_file())
for afilter in filters:
flags.append(afilter(item))
return all(flags)
def do_screening(item):
item = P(item) # because some filters needs advanced functionalities of P objects.
if absolute:
item = item.absolute()
if run_filter(item):
return item
else:
return None
if generator:
def gen():
flag = False
while not flag:
item = next(raw)
flag = do_screening(item)
if flag:
yield item
return gen
else:
# unpack the generator and vet the items (the function also returns P objects)
processed = [result for item in raw if (result := do_screening(item))]
if not processed: # if empty, don't proceeed
return List(processed)
if win_order: # this option only supported in non-generator mode.
processed.sort(key=lambda x: [int(k) if k.isdigit() else k for k in re.split('([0-9]+)', x.stem)])
return List(processed)
def listdir(self):
return List(os.listdir(self)).apply(P)
def find(self, *args, r=True, **kwargs):
"""short for the method ``search`` then pick first item from results.
.. note:: it is delibrately made to return None in case and object is not found.
"""
results = self.search(*args, r=r, **kwargs)
return results[0] if len(results) > 0 else None
# def open_with_system(self):
# self.explore() # if it is a file, it will be opened with its default program.
@staticmethod
def tmp(folder=None, fn=None, path="home"):
"""
folder is created.
file name is not created, only appended.
"""
if str(path) == "home":
path = P.home() / f"tmp_results"
path.mkdir(exist_ok=True, parents=True)
if folder is not None:
path = path / folder
path.mkdir(exist_ok=True, parents=True)
if fn is not None:
path = path / fn
return path
# ====================================== Compression ===========================================
def zip(self, op_path=None, arcname=None, **kwargs):
"""
"""
op_path = op_path or self
arcname = arcname or self.name
arcname = P(self.evalstr(arcname, expected="self"))
op_path = P(self.evalstr(op_path, expected="self"))
if arcname.name != self.name:
arcname /= self.name # arcname has to start from somewhere and end with filename
if self.is_file():
op_path = Compression.zip_file(ip_path=self, op_path=op_path, arcname=arcname, **kwargs)
else:
op_path = Compression.compress_folder(ip_path=self, op_path=op_path,
arcname=arcname, format_='zip', **kwargs)
return op_path
def unzip(self, op_path=None, fname=None, **kwargs):
zipfile = self
if self.suffix != ".zip": # may be there is .zip somewhere in the path.
assert ".zip" in str(self), f"Not a zip archive."
zipfile, fname = self.split(at=".zip", sep=0)
zipfile += ".zip"
if op_path is None:
op_path = zipfile.parent / zipfile.stem
else:
op_path = P(self.evalstr(op_path, expected="self"))
return Compression.unzip(zipfile, op_path, fname, **kwargs)
def compress(self, op_path=None, base_dir=None, format_="zip", **kwargs):
formats = ["zip", "tar", "gzip"]
assert format_ in formats, f"Unsupported format {format_}. The supported formats are {formats}"
_ = self, op_path, base_dir, kwargs
pass
def decompress(self):
pass
tmp = P.tmp
class Compression:
"""Provides consistent behaviour across all methods ...
Both files and folders when compressed, default is being under the root of archive."""
def __init__(self):
pass
@staticmethod
def compress_folder(ip_path, op_path, arcname, format_='zip', **kwargs):
"""Explanation of Shutil parameters:
* ``base_dir`` (here referred to as ``ip_path``) is what is going to be acturally archived.
When provided, it **has to** be relevant to ``root_dir`` (here referred to as ``arcname``).
* ``root_dir`` is where the archive is going to start from. It will create all the necessary subfolder till
it reaches the ``base_dir`` where archiving actually starts.
* Example: If you want to compress a folder in ``Downloads/myfolder/compress_this``
Then, say that your rootdir is where you want the archive structure to include,
then mention the folder you want to actually archive relatively to that root.
.. note:: ``format_`` can only be one of ``zip, tar, gztar, bztar, xztar``.
"""
root_dir = ip_path.split(at=arcname[0])[0]
import shutil # shutil works with folders nicely (recursion is done interally)
result_path = shutil.make_archive(base_name=op_path, format=format_,
root_dir=str(root_dir), base_dir=str(arcname), **kwargs)
return P(result_path) # same as op_path but (possibly) with format extension
@staticmethod
def zip_file(ip_path, op_path, arcname, **kwargs):
"""
arcname determines the directory of the file being archived inside the archive. Defaults to same
as original directory except for drive. When changed, it should still include the file name in its end.
If arcname = filename without any path, then, it will be in the root of the archive.
"""
import zipfile
if op_path.suffix != ".zip":
op_path = op_path + f".zip"
jungle_zip = zipfile.ZipFile(str(op_path), 'w')
jungle_zip.write(filename=str(ip_path), arcname=str(arcname), compress_type=zipfile.ZIP_DEFLATED, **kwargs)
jungle_zip.close()
return op_path
@staticmethod
def unzip(ip_path, op_path, fname=None, **kwargs):
from zipfile import ZipFile
with ZipFile(str(ip_path), 'r') as zipObj:
if fname is None: # extract all:
zipObj.extractall(op_path, **kwargs)
else:
zipObj.extract(str(fname), str(op_path), **kwargs)
op_path = P(op_path) / fname
return P(op_path)
@staticmethod
def gz(file):
import gzip
import shutil
with open(file, 'rb') as f_in:
with gzip.open(str(file) + '.gz', 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
@staticmethod
def ungz(self, op_path=None):
import shutil
import gzip
fn = str(self)
op_path = op_path or self.parent / self.stem
with gzip.open(fn, 'r') as f_in, open(op_path, 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
return P(op_path)
@staticmethod
def tar():
# import tarfile
pass
@staticmethod
def untar(self, fname=None, extract_dir='.', mode='r', **kwargs):
import tarfile
file = tarfile.open(str(self), mode)
if fname is None: # extract all files in the archive
file.extractall(path=extract_dir, **kwargs)
else:
file.extract(fname, **kwargs)
file.close()
return fname
class Read:
@staticmethod
def read(path, **kwargs):
suffix = P(path).suffix[1:]
# if suffix in ['eps', 'jpg', 'jpeg', 'pdf', 'pgf', 'png', 'ps', 'raw', 'rgba', 'svg', 'svgz', 'tif', 'tiff']:
# # plt.gcf().canvas.get_supported_filetypes().keys():
# return plt.imread(path, **kwargs)
# else:
reader = getattr(Read, suffix)
return reader(str(path), **kwargs)
@staticmethod
def npy(path, **kwargs):
"""returns Structure if the object loaded is a dictionary"""
data = np.load(str(path), allow_pickle=True, **kwargs)
if data.dtype == np.object:
data = data.item()
if type(data) is dict:
data = Struct(data)
return data
@staticmethod
def mat(path, **kwargs):
"""
:param path:
:return: Structure object
"""
from scipy.io import loadmat
return Struct(loadmat(path, **kwargs))
@staticmethod
def json(path, r=False, **kwargs):
"""Returns a Structure"""
import json
with open(str(path), "r") as file:
mydict = json.load(file, **kwargs)
if r:
return Struct.recursive_struct(mydict)
else:
return Struct(mydict)
@staticmethod
def yaml(path, r=False):
import yaml
with open(str(path), "r") as file:
mydict = yaml.load(file, Loader=yaml.FullLoader)
if r:
return Struct.recursive_struct(mydict)
else:
return Struct(mydict)
@staticmethod
def csv(path, **kwargs):
w = P(path).append(".dtypes").readit(reader=pd.read_csv, notexist=None)
w = dict(zip(w['index'], w['dtypes'])) if w else w
return pd.read_csv(path, dtypes=w, **kwargs)
@staticmethod
def pickle(path, **kwargs):
# import pickle
dill = Experimental.assert_package_installed("dill")
with open(path, 'rb') as file:
obj = dill.load(file, **kwargs)
if type(obj) is dict:
obj = Struct(obj)
return obj
@staticmethod
def pkl(*args, **kwargs):
return Read.pickle(*args, **kwargs)
@staticmethod
def csv(path, *args, **kwargs):
return pd.read_csv(path, *args, **kwargs)
class Save:
@staticmethod
def csv(path, obj):
obj.to_frame('dtypes').reset_index().to_csv(P(path).append(".dtypes").string)
@staticmethod
def mat(path=P.tmp(), mdict=None, **kwargs):
"""
.. note::
Avoid using mat for saving results because of incompatiblity:
* `None` type is not accepted.
* Scalars are conveteed to [1 x 1] arrays.
* etc. As such, there is no gaurantee that you restore what you saved.
Unless you want to pass the results to Matlab animals, avoid this format.
"""
from scipy.io import savemat
if '.mat' not in str(path):
path += '.mat'
path.parent.mkdir(exist_ok=True, parents=True)
for key, value in mdict.items():
if value is None:
mdict[key] = []
savemat(str(path), mdict, **kwargs)
@staticmethod
def json(path, obj, **kwargs):
"""This format is **compatible** with simple dictionaries that hold strings or numbers
but nothing more than that.
E.g. arrays or any other structure. An example of that is settings dictionary. It is useful because it can be
inspected using any text editor."""
import json
if not str(path).endswith(".json"):
path = str(path) + ".json"
with open(str(path), "w") as file:
json.dump(obj, file, default=lambda x: x.__dict__, **kwargs)
@staticmethod
def yaml(path, obj, **kwargs):
import yaml
if not str(path).endswith(".yaml"):
path = str(path) + ".yaml"
with open(str(path), "w") as file:
yaml.dump(obj, file, **kwargs)
# @staticmethod
# def pickle(path, obj, **kwargs):
# if ".pickle" not in str(path):
# path = path + ".pickle"
# import pickle
# with open(str(path), 'wb') as file:
# pickle.dump(obj, file, **kwargs)
@staticmethod
def pickle(path, obj, **kwargs):
dill = Experimental.assert_package_installed("dill")
with open(str(path), 'wb') as file:
dill.dump(obj, file, **kwargs)
def accelerate(func, ip):
""" Conditions for this to work:
* Must run under __main__ context
* func must be defined outside that context.
To accelerate IO-bound process, use multithreading. An example of that is somthing very cheap to process,
but takes a long time to be obtained like a request from server. For this, multithreading launches all threads
together, then process them in an interleaved fashion as they arrive, all will line-up for same processor,
if it happens that they arrived quickly.
To accelerate processing-bound process use multiprocessing, even better, use Numba.
Method1 use: multiprocessing / multithreading.
Method2: using joblib (still based on multiprocessing)
from joblib import Parallel, delayed
Fast method using Concurrent module
"""
split = np.array_split(ip, os.cpu_count())
# make each thread process multiple inputs to avoid having obscene number of threads with simple fast
# operations
# vectorize the function so that it now accepts lists of ips.
# def my_func(ip):
# return [func(tmp) for tmp in ip]
import concurrent.futures
with concurrent.futures.ProcessPoolExecutor() as executor:
op = executor.map(func, split)
op = list(op) # convert generator to list
op = np.concatenate(op, axis=0)
# op = self.reader.assign_resize(op, f=0.8, nrp=56, ncp=47, interpolation=True)
return op
# %% ========================== Object Management ==============================================
class List(list, Base):
"""Use this class to keep items of the same type.
"""
# =============================== Constructor Methods ====================
def __init__(self, obj_list=None):
super().__init__()
self.list = list(obj_list) if obj_list is not None else []
def __bool__(self):
return bool(self.list)
@classmethod
def from_copies(cls, obj, count):
return cls([copy.deepcopy(obj) for _ in range(count)])
@classmethod
def from_replicating(cls, func, *args, replicas=None, **kwargs):
"""
:param args: could be one item repeated for all instances, or iterable. If iterable, it can by a Cycle object.
:param kwargs: those could be structures:
:param replicas:
:param func:
"""
if not args and not kwargs: # empty args list and kwargs list
return cls([func() for _ in range(replicas)])
else:
result = []
for params in zip(*(args + tuple(kwargs.values()))):
an_arg = params[:len(args)]
a_val = params[len(args):]
a_kwarg = dict(zip(kwargs.keys(), a_val))
result.append(func(*an_arg, **a_kwarg))
return cls(result)
def save_items(self, directory, names=None, saver=None):
if saver is None:
saver = Save.pickle
if names is None:
names = range(len(self))
for name, item in zip(names, self.list):
saver(path=directory / name, obj=item)
def __deepcopy__(self, memodict=None):
if memodict is None:
memodict = {}
_ = memodict
return List([copy.deepcopy(i) for i in self.list])
def __copy__(self):
return List(self.list.copy())
def __getstate__(self):
return self.list
def __setstate__(self, state):
self.list = state
# ================= call methods =====================================
def method(self, name, *args, **kwargs):
return List([getattr(i, name)(*args, **kwargs) for i in self.list])
def attr(self, name):
return List([getattr(i, name) for i in self.list])
# def __getattribute__(self, item):
# # you can dispense with this method. Its only purpose is to make eaisr experience qwith the linter
# # obj = object.__getattribute__(self, "list")[0]
# # try:
# # attr = object.__getattribute__(self, item)
# # if hasattr(obj, item):
# # return self.__getattr__(item)
# # else:
# # return attr
# # except AttributeError:
# # return self.__getattr__(item)
# if item == "list": # grant special access to this attribute.
# return object.__getattribute__(self, "list")
# if item in object.__getattribute__(self, "__dict__").keys():
# return self.__getattr__(item)
# else:
# return object.__getattribute__(self, item)
def __getattr__(self, name): # fallback position when normal mechanism fails.
# this is called when __getattribute__ raises an error or call this explicitly.
result = List([getattr(i, name) for i in self.list])
return result
def __call__(self, *args, lest=True, **kwargs):
if lest:
return List([i(*args, **kwargs) for i in self.list])
else:
return [i(*args, **kwargs) for i in self.list]
# ======================== Access Methods ==========================================
def __getitem__(self, key):
if type(key) is list or type(key) is np.ndarray: # to allow fancy indexing like List[1, 5, 6]
return List([self[item] for item in key])
# behaves similarly to Numpy A[1] vs A[1:2]
result = self.list[key] # return the required item only (not a List)
if type(key) is not slice:
return result # choose one item
else:
return List(result)
def __setitem__(self, key, value):
self.list[key] = value
def sample(self, size=1):
return self[np.random.choice(len(self), size)]
def to_struct(self, key_val=None):
"""
:param key_val: function that returns (key, value) pair.
:return:
"""
if key_val is None:
def key_val(x):
return str(x), x
else:
key_val = self.evalstr(key_val)
return Struct.from_keys_values_pairs(self.apply(key_val))
# def find(self, patt, match="fnmatch"):
# """Looks up the string representation of all items in the list and finds the one that partially matches
# the argument passed. This method is a short for ``self.filter(lambda x: string_ in str(x))`` If you need more
# complicated logic in the search, revert to filter method.
# """
#
# if match == "string" or None:
# for idx, item in enumerate(self.list):
# if patt in str(item):
# return item
# elif match == "fnmatch":
# import fnmatch
# for idx, item in enumerate(self.list):
# if fnmatch.fnmatch(str(item), patt):
# return item
# else: # "regex"
# # escaped = re.escape(string_)
# compiled = re.compile(patt)
# for idx, item in enumerate(self.list):
# if compiled.search(str(item)) is not None:
# return item
# return None
def index(self, func):
""" A generalization of the `.index` method of `list`. It takes in a function rather than an
item to find its index. Additionally, it returns full list of results, not just the first result.
:param func:
:return: List of indices of items where the function returns `True`.
"""
func = self.evalstr(func, expected='func')
res = []
for idx, x in enumerate(self.list):
if func(x):
res.append(idx)
return res
# ======================= Modify Methods ===============================
def combine(self):
res = self.list[0]
for item in self.list[1:]:
res = res + item
return res
def append(self, obj):
self.list.append(obj)
def __add__(self, other):
return List(self.list + other.list)
def __repr__(self):
if len(self.list) > 0:
tmp1 = f"List object with {len(self.list)} elements. One example of those elements: \n"
tmp2 = f"{self.list[0].__repr__()}"
return tmp1 + tmp2
else:
return f"An Empty List []"
def __len__(self):
return len(self.list)
@property
def len(self):
return self.list.__len__()
def __iter__(self):
return iter(self.list)
def apply(self, func, *args, lest=None, jobs=None, depth=1, verbose=False, **kwargs):
"""
:param jobs:
:param func: func has to be a function, possibly a lambda function. At any rate, it should return something.
:param args:
:param lest:
:param verbose:
:param depth: apply the function to inner Lists
:param kwargs: a list of outputs each time the function is called on elements of the list.
:return:
"""
if depth > 1:
depth -= 1
# assert type(self.list[0]) == List, "items are not Lists".
self.apply(lambda x: x.apply(func, *args, lest=lest, jobs=jobs, depth=depth, **kwargs))
func = self.evalstr(func, expected='func')
tqdm = 0
if verbose or jobs:
Experimental.assert_package_installed("tqdm")
from tqdm import tqdm
if lest is None:
if jobs:
from joblib import Parallel, delayed
return List(Parallel(n_jobs=jobs)(delayed(func)(i, *args, **kwargs) for i in tqdm(self.list)))
else:
iterator = self.list if not verbose else tqdm(self.list)
return List([func(x, *args, **kwargs) for x in iterator])
else:
if jobs:
from joblib import Parallel, delayed
return List(Parallel(n_jobs=jobs)(delayed(func)(x, y) for x, y in tqdm(zip(self.list, lest))))
else:
iterator = zip(self.list, lest) if not verbose else tqdm(zip(self.list, lest))
return List([func(x, y) for x, y in iterator])
def modify(self, func, lest=None):
"""Modifies objects rather than returning new list of objects, hence the name of the method.
:param func: a string that will be executed, assuming idx, x and y are given.
:param lest:
:return:
"""
if lest is None:
for x in self.list:
_ = x
exec(func)
else:
for idx, (x, y) in enumerate(zip(self.list, lest)):
_ = idx, x, y
exec(func)
return self
def sort(self, *args, **kwargs):
self.list.sort(*args, **kwargs)
return self
def sorted(self, *args, **kwargs):
return List(sorted(self.list, *args, **kwargs))
def filter(self, func):
if type(func) is str:
func = eval("lambda x: " + func)
result = List()
for item in self.list:
if func(item):
result.append(item)
return result
def print(self, nl=1, sep=False, style=repr):
for idx, item in enumerate(self.list):
print(f"{idx:2}- {style(item)}", end=' ')
for _ in range(nl):
print('', end='\n')
if sep:
print(sep * 100)
def to_dataframe(self, names=None, minimal=True):
DisplayData.set_display()
columns = ['object'] + list(self.list[0].__dict__.keys())
df = pd.DataFrame(columns=columns)
if minimal:
return df
for i, obj in enumerate(self.list):
if names is None:
name = [obj]
else:
name = [names[i]]
df.loc[i] = name + list(self.list[i].__dict__.values())
return df
def to_numpy(self):
return self.np
@property
def np(self):
return np.array(self.list)
L = List
class Struct(Base):
"""Use this class to keep bits and sundry items.
Combines the power of dot notation in classes with strings in dictionaries to provide Pandas-like experience
"""
def __init__(self, dictionary=None, **kwargs):
"""
:param dictionary: a dict, a Struct, None or an object with __dict__ attribute.
"""
super(Struct, self).__init__()
if type(dictionary) is Struct:
dictionary = dictionary.dict
if dictionary is None: # only kwargs were passed
final_dict = kwargs
elif not kwargs: # only dictionary was passed
final_dict = dictionary if type(dictionary) is dict else dictionary.__dict__
else: # both were passed
final_dict = dictionary if type(dictionary) is dict else dictionary.__dict__
final_dict.update(kwargs)
self.__dict__ = final_dict
def __bool__(self):
return bool(self.__dict__)
@staticmethod
def recursive_struct(mydict):
struct = Struct(mydict)
for key, val in struct.items():
if type(val) is dict:
struct[key] = Struct.recursive_struct(val)
return struct
@staticmethod
def recursive_dict(struct):
mydict = struct.dict
for key, val in mydict.items():
if type(val) is Struct:
mydict[key] = Struct.recursive_dict(val)
return mydict
@classmethod
def from_keys_values(cls, keys: list, values: list):
return cls(dict(zip(keys, values)))
@classmethod
def from_keys_values_pairs(cls, my_list):
res = dict()
for k, v in my_list:
res[k] = v
return cls(res)
@classmethod
def from_names(cls, *names, default_=None): # Mimick NamedTuple and defaultdict
if default_ is None:
default_ = [None] * len(names)
return cls.from_keys_values(names, values=default_)
def get_values(self, keys):
return List([self[key] for key in keys])
@property
def clean_view(self):
class Temp:
pass
temp = Temp()
temp.__dict__ = self.__dict__
return temp
def __repr__(self):
repr_string = ""
for key in self.keys().list:
repr_string += str(key) + ", "
return "Struct: [" + repr_string + "]"
def print(self, sep=20, yaml=False):
if yaml:
self.save_yaml(P.tmp(fn="__tmp.yaml"))
txt = P.tmp(fn="__tmp.yaml").read_text()
print(txt)
return None
repr_string = ""
repr_string += "Structure, with following entries:\n"
repr_string += "Key" + " " * sep + "Item Type" + " " * sep + "Item Details\n"
repr_string += "---" + " " * sep + "---------" + " " * sep + "------------\n"
for key in self.keys().list:
key_str = str(key)
type_str = str(type(self[key])).split("'")[1]
val_str = DisplayData.get_repr(self[key])
repr_string += key_str + " " * abs(sep - len(key_str)) + " " * len("Key")
repr_string += type_str + " " * abs(sep - len(type_str)) + " " * len("Item Type")
repr_string += val_str + "\n"
print(repr_string)
def __str__(self):
mystr = str(self.__dict__)
mystr = mystr[1:-1].replace(":", " =").replace("'", "")
return mystr
def __getitem__(self, item): # allows indexing into entries of __dict__ attribute
return self.__dict__[item] # thus, gives both dot notation and string access to elements.
def __setitem__(self, key, value):
self.__dict__[key] = value
def __getattr__(self, item): # this works better with the linter.
try:
self.__dict__[item]
except KeyError:
# try:
# super(Struct, self).__getattribute__(item)
# object.__getattribute__(self, item)
# except AttributeError:
raise AttributeError(f"Could not find the attribute `{item}` in object `{self.__class__}`")
def __getstate__(self): # serialize
return self.__dict__
def __setstate__(self, state): # deserialize
self.__dict__ = state
def __iter__(self):
return iter(self.dict.items())
def save_yaml(self, path):
Save.yaml(path, self.recursive_dict(self))
@property
def dict(self): # allows getting dictionary version without accessing private memebers explicitly.
return self.__dict__
@dict.setter
def dict(self, adict):
self.__dict__ = adict
def update(self, *args, **kwargs):
"""Accepts dicts and keyworded args
"""
new_struct = Struct(*args, **kwargs)
self.__dict__.update(new_struct.__dict__)
return self
def apply(self, func):
func = self.evalstr(func)
for key, val in self.items():
self[key] = func(val)
return self
def inverse(self):
return Struct({v: k for k, v in self.dict.items()})
def append_values(self, *others, **kwargs):
""" """
return Struct(self.concat_dicts(*((self.dict,) + others), **kwargs))
@staticmethod
def concat_values(*dicts, method=None, lenient=True, collect_items=False, clone=True):
if method is None:
method = list.__add__
if not lenient:
keys = dicts[0].keys()
for i in dicts[1:]:
assert i.keys() == keys
# else if lenient, take the union
if clone:
total_dict = copy.deepcopy(dicts[0]) # take first dict in the tuple
else:
total_dict = dicts[0] # take first dict in the tuple
if collect_items:
for key, val in total_dict.item():
total_dict[key] = [val]
def method(tmp1, tmp2):
return tmp1 + [tmp2]
if len(dicts) > 1: # are there more dicts?
for adict in dicts[1:]:
for key in adict.keys(): # get everything from this dict
try: # may be the key exists in the total dict already.
total_dict[key] = method(total_dict[key], adict[key])
except KeyError: # key does not exist in total dict
if collect_items:
total_dict[key] = [adict[key]]
else:
total_dict[key] = adict[key]
return Struct(total_dict)
def keys(self):
"""Same behaviour as that of `dict`, except that is doesn't produce a generator."""
return List(self.dict.keys())
def values(self):
"""Same behaviour as that of `dict`, except that is doesn't produce a generator."""
return List(self.dict.values())
def items(self):
"""Same behaviour as that of `dict`, except that is doesn't produce a generator."""
return List(self.dict.items())
def to_dataframe(self, *args, **kwargs):
# return self.values().to_dataframe(names=self.keys())
return pd.DataFrame(self.__dict__, *args, **kwargs)
def spawn_from_values(self, values):
"""From the same keys, generate a new Struct with different values passed."""
return self.from_keys_values(self.keys(), self.evalstr(values, expected='self'))
def spawn_from_keys(self, keys):
"""From the same values, generate a new Struct with different keys passed."""
return self.from_keys_values(self.evalstr(keys, expected="self"), self.values())
def plot(self, artist=None, xdata=None):
if artist is None:
artist = Artist(figname='Structure Plot')
for key, val in self:
if xdata is None:
xdata = np.arange(len(val))
artist.plot(xdata, val, label=key)
try:
artist.fig.legend()
except AttributeError:
pass
return artist
class Cycle:
def __init__(self, c, name=''):
self.c = c
self.index = -1
self.name = name
def __str__(self):
return self.name
def next(self):
self.index += 1
if self.index >= len(self.c):
self.index = 0
return self.c[self.index]
def previous(self):
self.index -= 1
if self.index < 0:
self.index = len(self.c) - 1
return self.c[self.index]
def set(self, value):
self.index = self.c.index(value)
def get(self):
return self.c[self.index]
def get_index(self):
return self.index
def set_index(self, index):
self.index = index
def sample(self, size=1):
return np.random.choice(self.c, size)
def __add__(self, other):
pass # see behviour of matplotlib cyclers.
class Experimental:
class Log:
def __init__(self, path=None):
if path is None:
path = P('console_output')
self.path = path + '.log'
sys.stdout = open(self.path, 'w')
def finish(self):
sys.stdout.close()
print(f"Finished ... have a look @ \n {self.path}")
@staticmethod
def assert_package_installed(package):
try:
pkg = __import__(package)
return pkg
except ImportError:
# import pip
# pip.main(['install', package])
import subprocess
subprocess.check_call([sys.executable, "-m", "pip", "install", package])
pkg = __import__(package)
return pkg
@staticmethod
def generate_readme(path, obj=None, meta=None, save_source_code=True):
"""Generates a readme file to contextualize any binary files.
:param path: directory or file path.
:param obj: Python module, class, method or function used to generate the result (not the result or an
instance of any class)
:param meta:
:param save_source_code:
"""
import inspect
path = P(path)
readmepath = path / f"README.md" if path.is_dir() else path
separator = "\n" + "-----" + "\n\n"
text = "# Meta\n"
if meta is not None:
text = text + meta
text += separator
if obj is not None:
lines = inspect.getsource(obj)
text += f"# Code to generate the result\n" + "```python\n" + lines + "\n```" + separator
text += f"# Source code file generated me was located here: \n'{inspect.getfile(obj)}'\n" + separator
readmepath.write_text(text)
print(f"Successfully generated README.md file. Checkout:\n", readmepath.as_uri())
if save_source_code:
P(inspect.getmodule(obj).__file__).zip(op_path=readmepath.with_name("source_code.zip"))
print(readmepath.with_name("source_code.zip").as_uri())
@staticmethod
def load_from_source_code(directory, obj=None):
"""Does the following:
* Globs directory passed for ``source_code`` module.
* Loads the directory to the memroy.
* Returns either the package or a piece of it as indicated by ``obj``
"""
P(directory).find("source_code*", r=True).unzip(tmpdir := P.tmp() / get_time_stamp(name="tmp_sourcecode"))
sys.path.insert(0, str(tmpdir))
sourcefile = __import__(tmpdir.find("*").stem)
if obj is not None:
loaded = getattr(sourcefile, obj)
return loaded
else:
return sourcefile
@staticmethod
def get_locals(func):
exec(Experimental.convert_to_global(func)) # run the function here.
return Struct(vars())
@staticmethod
def update_globals(local_dict):
sys.modules['__main__'].__dict__.update(local_dict)
@staticmethod
def in_main(func): # a decorator
def wrapper(): # a wrapper that remembers the function func because it was in the closure when construced.
local_dict = Experimental.get_locals(func)
Experimental.update_globals(local_dict)
return wrapper
@staticmethod
def run_globally(func):
exec(Experimental.convert_to_global(func))
globals().update(vars())
@staticmethod
def convert_to_global(name):
"""Takes in a function name, reads it source code and returns a new version of it that can be run in the main.
This is useful to debug functions and class methods alike.
"""
import inspect
import textwrap
codelines = inspect.getsource(name)
# remove def func_name() line from the list
idx = codelines.find("):\n")
header = codelines[:idx]
codelines = codelines[idx + 3:]
# remove any indentation (4 for funcs and 8 for classes methods, etc)
codelines = textwrap.dedent(codelines)
# remove return statements
codelines = codelines.split("\n")
codelines = [code + "\n" for code in codelines if not code.startswith("return ")]
code_string = ''.join(codelines) # convert list to string.
temp = inspect.getfullargspec(name)
arg_string = """"""
# if isinstance(type(name), types.MethodType) else tmp.args
if temp.defaults: # not None
for key, val in zip(temp.args[1:], temp.defaults):
arg_string += f"{key} = {val}\n"
if "*args" in header:
arg_string += "args = (,)\n"
if "**kwargs" in header:
arg_string += "kwargs = {}\n"
result = arg_string + code_string
clipboard = Experimental.assert_package_installed("clipboard")
clipboard.copy(result)
print("code to be run \n", result, "=" * 100)
return result # ready to be run with exec()
@staticmethod
def edit_source(module, *edits):
sourcelines = P(module.__file__).read_text().split("\n")
for edit_idx, edit in enumerate(edits):
line_idx = 0
for line_idx, line in enumerate(sourcelines):
if f"here{edit_idx}" in line:
new_line = line.replace(edit[0], edit[1])
print(f"Old Line: {line}\nNew Line: {new_line}")
if new_line == line:
raise KeyError(f"Text Not found.")
sourcelines[line_idx] = new_line
break
else:
raise KeyError(f"No marker found in the text. Place the following: 'here{line_idx}'")
newsource = "\n".join(sourcelines)
P(module.__file__).write_text(newsource)
import importlib
importlib.reload(module)
return module
@staticmethod
def monkey_patch(class_inst, func): # lambda *args, **kwargs: func(class_inst, *args, **kwargs)
setattr(class_inst.__class__, func.__name__, func)
@staticmethod
def run_cell(pointer, module=sys.modules[__name__]):
# update the module by reading it again.
# if type(module) is str:
# module = __import__(module)
# import importlib
# importlib.reload(module)
# if type(module) is str:
# sourcecells = P(module).read_text().split("#%%")
# else:
sourcecells = P(module.__file__).read_text().split("#%%")
for cell in sourcecells:
if pointer in cell.split('\n')[0]:
break # bingo
else:
raise KeyError(f"The pointer `{pointer}` was not found in the module `{module}`")
print(cell)
clipboard = Experimental.assert_package_installed("clipboard")
clipboard.copy(cell)
return cell
class Manipulator:
@staticmethod
def merge_adjacent_axes(array, ax1, ax2):
"""Multiplies out two axes to generate reduced order array.
:param array:
:param ax1:
:param ax2:
:return:
"""
shape = array.shape
# order = len(shape)
sz1, sz2 = shape[ax1], shape[ax2]
new_shape = shape[:ax1] + (sz1 * sz2,) + shape[ax2 + 1:]
return array.reshape(new_shape)
@staticmethod
def merge_axes(array, ax1, ax2):
"""Brings ax2 next to ax1 first, then combine the two axes into one.
:param array:
:param ax1:
:param ax2:
:return:
"""
array2 = np.moveaxis(array, ax2, ax1 + 1) # now, previously known as ax2 is located @ ax1 + 1
return Manipulator.merge_adjacent_axes(array2, ax1, ax1 + 1)
@staticmethod
def expand_axis(array, ax_idx, factor):
"""opposite functionality of merge_axes.
While ``numpy.split`` requires the division number, this requies the split size.
"""
total_shape = list(array.shape)
size = total_shape.pop(ax_idx)
new_shape = (int(size / factor), factor)
for index, item in enumerate(new_shape):
total_shape.insert(ax_idx + index, item)
# should be same as return np.split(array, new_shape, ax_idx)
return array.reshape(tuple(total_shape))
@staticmethod
def slicer(array, a_slice: slice, axis=0):
lower_ = a_slice.start
upper_ = a_slice.stop
n = len(array)
lower_ = lower_ % n # if negative, you get the positive equivalent. If > n, you get principal value.
roll = lower_
lower_ = lower_ - roll
upper_ = upper_ - roll
array_ = np.roll(array, -roll, axis=axis)
upper_ = upper_ % n
new_slice = slice(lower_, upper_, a_slice.step)
return array_[Manipulator.indexer(axis=axis, myslice=new_slice, rank=array.ndim)]
@staticmethod
def indexer(axis, myslice, rank=None):
"""
Returns a tuple of slicers.
"""
everything = slice(None, None, None) # `:`
if rank is not None:
indices = [everything] * rank
indices[axis] = myslice
return tuple(indices)
else:
indices = [everything] * (axis + 1)
indices[axis] = myslice
return tuple(indices)
def batcher(func_type='function'):
if func_type == 'method':
def batch(func):
# from functools import wraps
#
# @wraps(func)
def wrapper(self, x, *args, per_instance_kwargs=None, **kwargs):
output = []
for counter, item in enumerate(x):
if per_instance_kwargs is not None:
mykwargs = {key: value[counter] for key, value in per_instance_kwargs.items()}
else:
mykwargs = {}
output.append(func(self, item, *args, **mykwargs, **kwargs))
return np.array(output)
return wrapper
return batch
elif func_type == 'class':
raise NotImplementedError
elif func_type == 'function':
class Batch(object):
def __init__(self, func):
self.func = func
def __call__(self, x, **kwargs):
output = [self.func(item, **kwargs) for item in x]
return np.array(output)
return Batch
def batcherv2(func_type='function', order=1):
if func_type == 'method':
def batch(func):
# from functools import wraps
#
# @wraps(func)
def wrapper(self, *args, **kwargs):
output = [func(self, *items, *args[order:], **kwargs) for items in zip(*args[:order])]
return np.array(output)
return wrapper
return batch
elif func_type == 'class':
raise NotImplementedError
elif func_type == 'function':
class Batch(object):
def __int__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
output = [self.func(self, *items, *args[order:], **kwargs) for items in zip(*args[:order])]
return np.array(output)
return Batch
class DisplayData:
def __init__(self, x):
self.x = pd.DataFrame(x)
@staticmethod
def set_display():
pd.set_option('display.width', 1000)
pd.set_option('display.max_columns', 200)
pd.set_option('display.max_colwidth', 40)
pd.set_option('display.max_rows', 1000)
@staticmethod
def eng():
pd.set_eng_float_format(accuracy=3, use_eng_prefix=True)
pd.options.display.float_format = '{:, .5f}'.format
pd.set_option('precision', 7)
# np.set_printoptions(formatter={'float': '{: 0.3f}'.format})
@staticmethod
def get_repr(data):
"""A well-behaved repr function for all data types."""
if type(data) is np.ndarray:
string_ = f"shape = {data.shape}, dtype = {data.dtype}."
return string_
elif type(data) is str:
return data
elif type(data) is list:
return f"length = {len(data)}. 1st item type = {type(data[0]) if len(data) > 0 else None}"
else:
return repr(data)
@staticmethod
def outline(array, name="Array", imprint=True):
str_ = f"{name}. Shape={array.shape}. Dtype={array.dtype}"
if imprint:
print(str_)
return str_
# %% ========================== Plot Helper funcs ========================================
class FigurePolicy(enum.Enum):
close_create_new = 'Close the previous figure that has the same figname and create a new fresh one'
add_new = 'Create a new figure with same name but with added suffix'
same = 'Grab the figure of the same name'
def get_time_stamp(ft=None, name=None):
if ft is None: # this is better than putting the default non-None value above.
ft = '%Y-%m-%d-%I-%M-%S-%p-%f' # if another function using this internally and wants to expise those kwarg
# then it has to worry about not sending None which will overwrite this defualt value.
from datetime import datetime
_ = datetime.now().strftime(ft)
if name:
name = name + '_' + _
else:
name = _
return name
class FigureManager:
"""
Handles figures of matplotlib.
"""
def __init__(self, info_loc=None, figpolicy=FigurePolicy.same):
self.figpolicy = figpolicy
self.fig = self.ax = self.event = None
self.cmaps = Cycle(plt.colormaps())
import matplotlib.colors as mcolors
self.mcolors = list(mcolors.CSS4_COLORS.keys())
self.facecolor = Cycle(list(mcolors.CSS4_COLORS.values()))
self.colors = Cycle(plt.rcParams['axes.prop_cycle'].by_key()['color'])
self.cmaps.set('viridis')
self.index = self.pause = self.index_max = None
self.auto_brightness = False
self.info_loc = [0.8, 0.01] if info_loc is None else info_loc
self.pix_vals = False
self.help_menu = {'_-=+[{]}\\': {'help': "Adjust Vmin Vmax. Shift + key applies change to all axes. \\ "
"toggles auto-brightness ", 'func': self.adjust_brightness},
"/": {'help': 'Show/Hide info text', 'func': self.text_info},
"h": {'help': 'Show/Hide help menu', 'func': self.show_help},
"tyTY": {'help': 'Change color map', 'func': self.change_cmap},
'<>': {'help': 'Change figure face color', 'func': self.change_facecolor},
"v": {'help': 'Show/Hide pixel values (Toggle)', 'func': self.show_pix_val},
'P': {'help': 'Pause/Proceed (Toggle)', 'func': self.pause_func},
'r': {'help': 'Replay', 'func': self.replay},
'1': {'help': 'Previous Image', 'func': self.previous},
'2': {'help': 'Next Image', 'func': self.next},
'S': {'help': 'Save Object', 'func': self.save},
'c': {'help': 'Show/Hide cursor', 'func': self.show_cursor},
'aA': {'help': 'Show/Hide ticks and their labels', 'func': self.show_ticks},
'alt+a': {'help': 'Show/Hide annotations', 'func': self.toggle_annotate}}
# IMPORTANT: add the 'alt/ctrl+key' versions of key after the key in the dictionary above, not before.
# Otherwise the naked key version will statisfy the condition `is key in this`? in the parser.
self.message = ''
self.message_obj = self.cursor = None
self.annot_flag = False # one flag for all axes?
self.boundaries_flag = True
@staticmethod
def grid(ax, factor=5, x_or_y='both', color='gray', alpha1=0.5, alpha2=0.25):
if type(ax) in {list, List, np.ndarray}:
for an_ax in ax:
FigureManager.grid(an_ax, factor=factor, x_or_y=x_or_y, color=color, alpha1=alpha1, alpha2=alpha2)
return None
# Turning on major grid for both axes.
ax.grid(which='major', axis='x', color='gray', linewidth=0.5, alpha=alpha1)
ax.grid(which='major', axis='y', color='gray', linewidth=0.5, alpha=alpha1)
if x_or_y in {'both', 'x'}:
xt = ax.get_xticks() # major ticks
steps = (xt[1] - xt[0]) / factor
ax.xaxis.set_minor_locator(plt.MultipleLocator(steps))
ax.grid(which='minor', axis='x', color=color, linewidth=0.5, alpha=alpha2)
if x_or_y in {'both', 'y'}:
yt = ax.get_yticks() # major ticks
steps = (yt[1] - yt[0]) / factor
ax.yaxis.set_minor_locator(plt.MultipleLocator(steps))
ax.grid(which='minor', axis='y', color=color, linewidth=0.5, alpha=alpha2)
def maximize_fig(self):
_ = self
# plt.get_current_fig_manager().window.state('zoom')
plt.get_current_fig_manager().full_screen_toggle()
def toggle_annotate(self, event):
self.annot_flag = not self.annot_flag
if event.inaxes:
if event.inaxes.images:
event.inaxes.images[0].set_picker(True)
self.message = f"Annotation flag is toggled to {self.annot_flag}"
if not self.annot_flag: # if it is off
pass # hide all annotations
def annotate(self, event, axis=None, data=None):
self.event = event
e = event.mouseevent
if axis is None:
ax = e.inaxes
else:
ax = axis
if ax:
if not hasattr(ax, 'annot_obj'): # first time
ax.annot_obj = ax.annotate("", xy=(0, 0), xytext=(-30, 30),
textcoords="offset points",
arrowprops=dict(arrowstyle="->", color="w", connectionstyle="arc3"),
va="bottom", ha="left", fontsize=10,
bbox=dict(boxstyle="round", fc="w"), )
else:
ax.annot_obj.set_visible(self.annot_flag)
x, y = int(np.round(e.xdata)), int(np.round(e.ydata))
if data is None:
z = e.inaxes.images[0].get_array()[y, x]
else:
z = data[y, x]
ax.annot_obj.set_text(f'x:{x}\ny:{y}\nvalue:{z:.3f}')
ax.annot_obj.xy = (x, y)
self.fig.canvas.draw_idle()
def save(self, event):
_ = event
Save.pickle('.', obj=self)
def replay(self, event):
_ = event
self.pause = False
self.index = 0
self.message = 'Replaying'
self.animate()
def pause_func(self, event):
_ = event
self.pause = not self.pause
self.message = f'Pause flag is set to {self.pause}'
self.animate()
def previous(self, event):
_ = event
self.index = self.index - 1 if self.index > 0 else self.index_max - 1
self.message = f'Previous {self.index}'
self.animate()
def next(self, event):
_ = event
self.index = self.index + 1 if self.index < self.index_max - 1 else 0
self.message = f'Next {self.index}'
self.animate()
def animate(self):
pass # a method of the artist child class that is inheriting from this class
def text_info(self, event):
_ = event
self.message = ''
def show_help(self, event):
_ = event
default_plt = {"q ": {'help': "Quit Figure."},
"Ll": {'help': "change x/y scale to log and back to linear (toggle)"},
"Gg": {'help': "Turn on and off x and y grid respectively."},
"s ": {'help': "Save Figure"},
"f ": {'help': "Toggle Full screen"},
"p ": {'help': "Select / Deselect Pan"}}
figs = plt.get_figlabels()
if "Keyboard shortcuts" in figs:
plt.close("Keyboard shortcuts") # toggle
else:
fig = plt.figure(num="Keyboard shortcuts")
for i, key in enumerate(self.help_menu.keys()):
fig.text(0.1, 1 - 0.05 * (i + 1), f"{key:30s} {self.help_menu[key]['help']}")
print(pd.DataFrame([[val['help'], key] for key, val in self.help_menu.items()], columns=['Action', 'Key']))
print(f"\nDefault plt Keys:\n")
print(pd.DataFrame([[val['help'], key] for key, val in default_plt.items()], columns=['Action', 'Key']))
def adjust_brightness(self, event):
ax = event.inaxes
if ax is not None and ax.images:
message = 'None'
if event.key == '\\':
self.auto_brightness = not self.auto_brightness
message = f"Auto-brightness flag is set to {self.auto_brightness}"
if self.auto_brightness: # this change is only for the current image.
im = self.ax.images[0]
im.norm.autoscale(im.get_array())
# changes to all ims take place in animate as in ImShow and Nifti methods animate.
vmin, vmax = ax.images[0].get_clim()
if event.key in '-_':
message = 'increase vmin'
vmin += 1
elif event.key in '[{':
message = 'decrease vmin'
vmin -= 1
elif event.key in '=+':
message = 'increase vmax'
vmax += 1
elif event.key in ']}':
message = 'decrease vmax'
vmax -= 1
self.message = message + ' ' + str(round(vmin, 1)) + ' ' + str(round(vmax, 1))
if event.key in '_+}{':
for ax in self.fig.axes:
if ax.images:
ax.images[0].set_clim((vmin, vmax))
else:
if ax.images:
ax.images[0].set_clim((vmin, vmax))
def change_cmap(self, event):
ax = event.inaxes
if ax is not None:
cmap = self.cmaps.next() if event.key in 'tT' else self.cmaps.previous()
if event.key in 'TY':
for ax in self.fig.axes:
for im in ax.images:
im.set_cmap(cmap)
else:
for im in ax.images:
im.set_cmap(cmap)
self.message = f"Color map changed to {ax.images[0].cmap.name}"
def change_facecolor(self, event):
color = self.facecolor.next() if event.key == '>' else self.facecolor.previous()
self.fig.set_facecolor(color)
self.message = f"Figure facecolor was set to {self.mcolors[self.facecolor.get_index()]}"
def show_pix_val(self, event):
ax = event.inaxes
if ax is not None:
self.pix_vals = not self.pix_vals # toggle
self.message = f"Pixel values flag set to {self.pix_vals}"
if self.pix_vals:
self.show_pixels_values(ax)
else:
while len(ax.texts) > 0:
for text in ax.texts:
text.remove()
def process_key(self, event):
self.event = event # useful for debugging.
for key in self.help_menu.keys():
if event.key in key:
self.help_menu[key]['func'](event)
break
self.update_info_text(self.message)
if event.key != 'q': # for smooth quit without throwing errors
fig = event.canvas.figure # don't update if you want to quit.
fig.canvas.draw()
def update_info_text(self, message):
if self.message_obj:
self.message_obj.remove()
self.message_obj = self.fig.text(*self.info_loc, message, fontsize=8)
@staticmethod
def get_nrows_ncols(num_plots, nrows=None, ncols=None):
if not nrows and not ncols:
nrows = int(np.floor(np.sqrt(num_plots)))
ncols = int(np.ceil(np.sqrt(num_plots)))
while nrows * ncols < num_plots:
ncols += 1
elif not ncols and nrows:
ncols = int(np.ceil(num_plots / nrows))
elif not nrows and ncols:
nrows = int(np.ceil(num_plots / ncols))
else:
pass
return nrows, ncols
def show_cursor(self, event):
ax = event.inaxes
if ax: # don't do this if c was pressed outside an axis.
if hasattr(ax, 'cursor_'): # is this the first time?
if ax.cursor_ is None:
from matplotlib import widgets
ax.cursor_ = widgets.Cursor(ax=ax, vertOn=True, horizOn=True, color='red', lw=1.0)
else: # toggle the cursor.
ax.cursor_ = None
self.message = f'Cursor flag set to {bool(ax.cursor_)}'
else: # first call
ax.cursor_ = None
self.show_cursor(event)
def show_ticks(self, event):
self.boundaries_flag = not self.boundaries_flag
axis = event.inaxes
if event.key == 'a':
if axis:
# event.inaxes.axis(['off', 'on'][self.boundaries_flag])
self.toggle_ticks(axis)
self.message = f"Boundaries flag set to {self.boundaries_flag} in {axis}"
else:
for ax in self.ax:
# ax.axis(['off', 'on'][self.boundaries_flag])
self.toggle_ticks(ax)
@staticmethod
def toggle_ticks(an_ax, state=None):
for line in an_ax.get_yticklines():
line.set_visible(not line.get_visible() if state is None else state)
for line in an_ax.get_xticklines():
line.set_visible(not line.get_visible() if state is None else state)
for line in an_ax.get_xticklabels():
line.set_visible(not line.get_visible() if state is None else state)
for line in an_ax.get_yticklabels():
line.set_visible(not line.get_visible() if state is None else state)
def clear_axes(self):
for ax in self.ax:
ax.cla()
@staticmethod
def show_pixels_values(ax):
im = ax.images[0].get_array()
xmin, xmax = ax.get_xlim()
ymin, ymax = ax.get_ylim()
if ymin > ymax: # default imshow settings
ymin, ymax = ymax, ymin
for (j, i), label in np.ndenumerate(im):
if (xmin < i < xmax) and (ymin < j < ymax):
ax.text(i, j, np.round(label).__int__(), ha='center', va='center', size=8)
@staticmethod
def update(figname, obj_name, data=None):
"""Fastest update ever. But, you need access to label name.
Using this function external to the plotter. But inside the plotter you need to define labels to objects
The other alternative is to do the update inside the plotter, but it will become very verbose.
:param figname:
:param obj_name:
:param data:
:return:
"""
obj = FigureManager.findobj(figname, obj_name)
if data is not None:
obj.set_data(data)
# update scale:
# obj.axes.relim()
# obj.axes.autoscale()
@staticmethod
def findobj(figname, obj_name):
if type(figname) is str:
fig = plt.figure(num=figname)
else:
fig = figname
search_results = fig.findobj(lambda x: x.get_label() == obj_name)
if len(search_results) > 0: # list of length 1, 2 ...
search_results = search_results[0] # the first one is good enough.
return search_results
def get_fig(self, figname='', suffix=None, **kwargs):
return FigureManager.get_fig_static(self.figpolicy, figname, suffix, **kwargs)
@staticmethod
def get_fig_static(figpolicy, figname='', suffix=None, **kwargs):
"""
:param figpolicy:
:param figname:
:param suffix: only relevant if figpolicy is add_new
:param kwargs:
:return:
"""
fig = None
exist = True if figname in plt.get_figlabels() else False
if figpolicy is FigurePolicy.same:
fig = plt.figure(num=figname, **kwargs)
elif figpolicy is FigurePolicy.add_new:
if exist:
new_name = get_time_stamp(name=figname) if suffix is None else figname + suffix
else:
new_name = figname
fig = plt.figure(num=new_name, **kwargs)
elif figpolicy is FigurePolicy.close_create_new:
if exist:
plt.close(figname)
fig = plt.figure(num=figname, **kwargs)
return fig
def transperent_fig(self):
self.fig.canvas.manager.window.attributes("-transparentcolor", "white")
@staticmethod
def set_ax_size(ax, w, h):
""" w, h: width, height in inches """
left = ax.figure.subplotpars.left
r = ax.figure.subplotpars.right
t = ax.figure.subplotpars.top
b = ax.figure.subplotpars.bottom
figw = float(w) / (r - left)
figh = float(h) / (t - b)
ax.figure.set_size_inches(figw, figh)
@staticmethod
def get_ax_size(ax): # returns axis size in inches.
w, h = ax.figure.get_size_inches()
width = ax.figure.subplotpars.right - ax.figure.subplotpars.left
height = ax.figure.subplotpars.top - ax.figure.subplotpars.bottom
# width, height = ax.figbox.extents[2:] - ax.figbox.extents[:2]
return w * width, h * height
@staticmethod
def set_ax_to_real_life_size(ax, inch_per_unit=1 / 25.4):
limit_x = ax.get_xlim()[1] - ax.get_xlim()[0]
limit_y = ax.get_ylim()[1] - ax.get_ylim()[0]
FigureManager.set_ax_size(ax, limit_x * inch_per_unit, limit_y * inch_per_unit)
@staticmethod
def try_figure_size():
fig, ax = plt.subplots()
x = np.arange(0, 100, 0.01)
y = np.sin(x) * 100
ax.plot(x, y)
ax.axis("square")
ax.set_xlim(0, 100)
ax.set_ylim(-100, 100)
FigureManager.set_ax_to_real_life_size(ax)
fig.savefig(P.tmp() / "trial.png", dpi=250)
@staticmethod
def write(txt, name="text", size=8, **kwargs):
fig = plt.figure(figsize=(11.69, 8.27), num=name)
FigureManager.maximize_fig(fig)
fig.clf()
fig.text(0.5, 0.5, txt, transform=fig.transFigure, size=size, ha="center", va='center', **kwargs)
return fig
@staticmethod
def activate_latex(size=20):
"""Setting up matplotlib"""
plt.rc('xtick', labelsize=size)
plt.rc('ytick', labelsize=size)
plt.rc('axes', labelsize=size)
plt.rc('axes', titlesize=size)
plt.rc('legend', fontsize=size / 1.5)
# rc('text', usetex=True)
plt.rcParams['text.usetex'] = True
plt.rc('font', **{'family': 'serif', 'serif': ['Computer Modern']})
@staticmethod
def set_linestyles_and_markers_and_colors(test=False):
from cycler import cycler
from matplotlib import lines
colors = plt.rcParams['axes.prop_cycle'].by_key()['color']
markers = list(lines.lineMarkers.keys())[:-4] # ignore the None
linestyles = list(lines.lineStyles.keys())[:-3] # ignore the Nones
linestyles = (linestyles * 10)[:len(markers)]
colors = (colors * 10)[:len(markers)]
default_cycler = (cycler(linestyle=linestyles) + cycler(marker=markers) + cycler(color=colors))
plt.rc('axes', prop_cycle=default_cycler)
if test:
temp = np.random.randn(10, 10)
for idx, aq in enumerate(temp):
plt.plot(aq + idx * 2)
def close(self):
plt.close(self.fig)
class SaveType:
class GenericSave:
""" You can either pass the figures to be tracked or, pass them dynamically at add method, or,
add method will capture every figure and axis
"""
stream = ['clear', 'accumulate', 'update'][0]
def __init__(self, save_dir=None, save_name=None, watch_figs=None, max_calls=2000, delay=100, **kwargs):
self.delay = delay
self.watch_figs = watch_figs
if watch_figs:
assert type(watch_figs) is list, "This should be a list"
if type(watch_figs[0]) is str:
self.watch_figs = [plt.figure(num=afig) for afig in watch_figs]
save_dir = save_dir or P.tmp().string
self.save_name = get_time_stamp(name=save_name)
self.save_dir = save_dir
self.kwargs = kwargs
self.counter = 0
self.max = max_calls
def add(self, fignames=None, names=None, **kwargs):
print(f"Saver added frame number {self.counter}", end='\r')
self.counter += 1
plt.pause(self.delay * 0.001)
if self.counter > self.max:
print('Turning off IO')
plt.ioff()
if fignames: # name sent explicitly
self.watch_figs = [plt.figure(figname) for figname in fignames]
else: # tow choices:
if self.watch_figs is None: # None exist ==> add all
figure_names = plt.get_figlabels() # add all.
self.watch_figs = [plt.figure(k) for k in figure_names]
else: # they exist already.
pass
if names is None: # individual save name, useful for PNG.
names = [get_time_stamp(name=a_figure.get_label()) for a_figure in self.watch_figs]
for afig, aname in zip(self.watch_figs, names):
self._save(afig, aname, **kwargs)
def _save(self, *args, **kwargs):
pass
class Null(GenericSave):
""" Use this when you do not want to save anything. This class will help plot to work faster
by removing lines of previous plot, so you get live animation cheaply.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fname = self.save_dir
def finish(self):
print(f"Nothing saved by {self}")
return self.fname
class PDF(GenericSave):
"""For pdf, you just need any figure manager, [update, clear, accumalate], preferabbly fastest.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
from matplotlib.backends.backend_pdf import PdfPages
self.fname = os.path.join(self.save_dir, self.save_name + '.pdf')
self.pp = PdfPages(self.fname)
def _save(self, a_fig, a_name, bbox_inches='tight', pad_inches=0.3, **kwargs):
self.pp.savefig(a_fig, bbox_inches=bbox_inches, pad_inches=pad_inches, **kwargs)
def finish(self, open_result=True):
print(f"Saving results ...")
self.pp.close()
print(f"PDF Saved @", P(self.fname).absolute().as_uri())
if open_result:
import webbrowser as wb
# chrome_path = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe".replace('\\', '/')
# wb.register('chrome', None, wb.BackgroundBrowser(chrome_path))
# wb.get('chrome').open(self.fname)
wb.open(self.fname)
return self
class PNG(GenericSave):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.save_dir = os.path.join(self.save_dir, self.save_name)
os.makedirs(self.save_dir, exist_ok=True)
self.fname = self.save_dir
def _save(self, afigure, aname, dpi=150, **kwargs):
aname = P(aname).make_python_name()
afigure.savefig(os.path.join(self.save_dir, aname), bbox_inches='tight', pad_inches=0.3,
dpi=dpi, **kwargs)
def finish(self):
print(f"PNGs Saved @", Path(self.fname).absolute().as_uri())
return self.fname
class GIF(GenericSave):
"""Requirements: same axis must persist, only new objects are drawn inside it.
This is not harsh as no one wants to add multiple axes on top of each other.
Next, the objects drawn must not be removed, or updated, instead they should pile up in axis.
# do not pass names in the add method. names will be extracted from figures.
# usually it is smoother when adding animate=True to plot or imshow commands for GIF purpose
Works for images only. Add more .imshow to the same axis, and that's it. imshow will conver up previous images.
For lines, it will superimpose it and will look ugly.
If you clear the axis, nothing will be saved. This should not happend.
The class will automatically detect new lines by their "neo" labels.
and add them then hide them for the next round.
Limitation of ArtistAnimation: works on lines and images list attached to figure axes.
Doesn't work on axes, unless you add large number of them. As such, titles are not incorporated etc.
"""
def __init__(self, interval=100, **kwargs):
super().__init__(**kwargs)
from collections import defaultdict
self.container = defaultdict(lambda: [])
self.interval = interval
self.fname = None # determined at finish time.
def _save(self, afigure, aname, cla=False, **kwargs):
fig_list = self.container[afigure.get_label()]
subcontainer = []
search = FigureManager.findobj(afigure, 'neo')
for item in search:
item.set_label('processed')
item.set_visible(False)
subcontainer += [item]
fig_list.append(subcontainer)
# if you want the method coupled with cla being used in main, then it add_line is required for axes.
def finish(self):
print("Saving the GIF ....")
import matplotlib.animation as animation
from matplotlib.animation import PillowWriter
for idx, a_fig in enumerate(self.watch_figs):
ims = self.container[a_fig.get_label()]
if ims:
ani = animation.ArtistAnimation(a_fig, ims,
interval=self.interval, blit=True, repeat_delay=1000)
self.fname = os.path.join(self.save_dir, f'{a_fig.get_label()}_{self.save_name}.gif')
ani.save(self.fname, writer=PillowWriter(fps=4))
# if you don't specify the writer, it goes to ffmpeg by default then try others if that is not
# available, resulting in behaviours that is not consistent across machines.
print(f"GIF Saved @", Path(self.fname).absolute().as_uri())
else:
print(f"Nothing to be saved by GIF writer.")
return self.fname
class GIFFileBased(GenericSave):
def __init__(self, fps=4, dpi=100, bitrate=1800, _type='GIFFileBased', **kwargs):
super().__init__(**kwargs)
from matplotlib.animation import ImageMagickWriter as Writer
extension = '.gif'
if _type == 'GIFPipeBased':
from matplotlib.animation import ImageMagickFileWriter as Writer
elif _type == 'MPEGFileBased':
from matplotlib.animation import FFMpegFileWriter as Writer
extension = '.mp4'
elif _type == 'MPEGPipeBased':
from matplotlib.animation import FFMpegWriter as Writer
extension = '.mp4'
self.writer = Writer(fps=fps, metadata=dict(artist='<NAME>'), bitrate=bitrate)
self.fname = os.path.join(self.save_dir, self.save_name + extension)
assert self.watch_figs, "No figure was sent during instantiation of saver, therefore the writer cannot" \
"be setup. Did you mean to use an autosaver?"
self.writer.setup(fig=self.watch_figs[0], outfile=self.fname, dpi=dpi)
def _save(self, afig, aname, **kwargs):
self.writer.grab_frame(**kwargs)
def finish(self):
print('Saving results ...')
self.writer.finish()
print(f"Saved @", Path(self.fname).absolute().as_uri())
return self.fname
class GIFPipeBased(GIFFileBased):
def __init__(self, *args, **kwargs):
super().__init__(*args, _type=self.__class__.__name__, **kwargs)
class MPEGFileBased(GIFFileBased):
def __init__(self, *args, **kwargs):
super().__init__(*args, _type=self.__class__.__name__, **kwargs)
class MPEGPipeBased(GIFFileBased):
def __init__(self, *args, **kwargs):
super().__init__(*args, _type=self.__class__.__name__, **kwargs)
"""
Parses the data automatically.
For all subclasses, you need to provide a plotter class with animate method implemetend.
You also need to have .fig attribute.
"""
class GenericAuto(GenericSave):
save_type = 'auto'
def __init__(self, plotter_class, data, names_list=None, **kwargs):
super().__init__(**kwargs)
self.plotter_class = plotter_class
self.data = data
self.names_list = names_list
self.kwargs = kwargs
self.data_gen = None
self.saver = None
self.plotter = None
def animate(self):
def gen_function():
for i in zip(*self.data):
yield i
self.data_gen = gen_function
self.plotter = self.plotter_class(*[piece[0] for piece in self.data], **self.kwargs)
plt.pause(0.5) # give time for figures to show up before updating them
Experimental.assert_package_installed("tqdm")
from tqdm import tqdm
for idx, datum in tqdm(enumerate(self.data_gen())):
self.plotter.animate(datum)
self.saver.add(names=[self.names_list[idx]])
self.saver.finish()
class GIFAuto(GenericAuto):
def __init__(self, plotter_class, data, interval=500, extension='gif', fps=4, **kwargs):
super().__init__(plotter_class, data, **kwargs)
writer = None
from matplotlib import animation
if extension == 'gif':
writer = animation.PillowWriter(fps=fps)
elif extension == 'mp4':
writer = animation.FFMpegWriter(fps=fps, metadata=dict(artist='<NAME>'), bitrate=2500)
def gen_function():
for i in zip(*self.data):
yield i
self.gen = gen_function
self.plotter = self.plotter_class(*[piece[0] for piece in self.data], **kwargs)
plt.pause(self.delay * 0.001) # give time for figures to show up before updating them
self.ani = animation.FuncAnimation(self.plotter.fig, self.plotter.animate, frames=self.gen,
interval=interval, repeat_delay=1500, fargs=None,
cache_frame_data=True, save_count=10000)
fname = f"{os.path.join(self.save_dir, self.save_name)}.{extension}"
self.fname = fname
self.ani.save(filename=fname, writer=writer)
print(f"Saved @", Path(self.fname).absolute().as_uri())
class PDFAuto(GenericAuto):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.saver = SaveType.PDF(**kwargs)
self.animate()
class PNGAuto(GenericAuto):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.saver = SaveType.PNG(**kwargs)
self.save_dir = self.saver.save_dir
self.animate()
self.fname = self.saver.fname
class NullAuto(GenericAuto):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.saver = SaveType.Null(**kwargs)
self.fname = self.saver.fname
self.animate()
class GIFFileBasedAuto(GenericAuto):
def __init__(self, plotter_class, data, fps=4, dpi=150, bitrate=2500,
_type='GIFFileBasedAuto', **kwargs):
super().__init__(**kwargs)
from matplotlib.animation import ImageMagickWriter as Writer
extension = '.gif'
if _type == 'GIFPipeBasedAuto':
from matplotlib.animation import ImageMagickFileWriter as Writer
elif _type == 'MPEGFileBasedAuto':
from matplotlib.animation import FFMpegFileWriter as Writer
extension = '.mp4'
elif _type == 'MPEGPipeBasedAuto':
from matplotlib.animation import FFMpegWriter as Writer
extension = '.mp4'
self.saver = Writer(fps=fps, metadata=dict(artist='<NAME>'), bitrate=bitrate)
self.fname = os.path.join(self.save_dir, self.save_name + extension)
def gen_function():
for i in zip(*data):
yield i
self.data = gen_function
self.plotter = plotter_class(*[piece[0] for piece in data], **kwargs)
plt.pause(0.5) # give time for figures to show up before updating them
Experimental.assert_package_installed("tqdm")
from tqdm import tqdm
with self.saver.saving(fig=self.plotter.fig, outfile=self.fname, dpi=dpi):
for datum in tqdm(self.data()):
self.plotter.animate(datum)
self.saver.grab_frame()
plt.pause(self.delay * 0.001)
print(f"Results saved successfully @ {self.fname}")
class GIFPipeBasedAuto(GIFFileBasedAuto):
def __init__(self, *args, **kwargs):
super().__init__(*args, _type=self.__class__.__name__, **kwargs)
class MPEGFileBasedAuto(GIFFileBasedAuto):
def __init__(self, *args, **kwargs):
super().__init__(*args, _type=self.__class__.__name__, **kwargs)
class MPEGPipeBasedAuto(GIFFileBasedAuto):
def __init__(self, *args, **kwargs):
super().__init__(*args, _type=self.__class__.__name__, **kwargs)
class VisibilityViewer(FigureManager):
artist = ['internal', 'external'][1]
parser = ['internal', 'external'][1]
stream = ['clear', 'accumulate', 'update'][1]
"""
**Viewer Building Philosophy**:
Viewer should act as Saver and Browser:
* How is the data viewed:
* Can either be an artist himself, as in ImShow.
* external artist is required to view the data (especially non image data)
* Data parsing:
* internal for loop to go through all the dataset passed.
# Allows manual control over parsing.
* external for loop. It should have add method.
# Manual control only takes place after the external loop is over. #TODO parallelize this.
* Refresh mechanism.
* Clear the axis. (slowest, but easy on memory)
* accumulate, using visibility to hide previous axes. (Fastest but memory intensive)
* The artist has an update method. (best)
The artist has to have:
* fig, ax, txt attributes. ax and txt should be lists.
* the ax and txt attributes should always belong to the same figure.
Here and in all Visibility classes, the artist is assumed to be always creating new axes along the way.
"""
def __init__(self, artist=None, hide_artist_axes=True):
"""
This class works on hiding axes shown on a plot, so that a new plot can be drawn.
Hiding is done via the method `add`.
Thus, an external loop is required to parse through the plots one by one.
Once the entire loop is finished, you can browse through the plots with the keyboard
Animation is done bia method `animate`
:param artist: A class that draws on one figure. It should have `.fig` attribute.
Can either be passed during instantiation, or everytime when `add` is called.
:param hide_artist_axes:
"""
super().__init__()
self.index = -1
self.index_max = 0
self.current = None
self.axes_repo = []
self.texts_repo = []
self.fig = None
if artist:
self.fig = artist.fig
self.fig.canvas.mpl_connect('key_press_event', self.process_key)
self.add(artist=artist, hide_artist_axes=hide_artist_axes)
def add(self, artist=None, increment_index=True, hide_artist_axes=True):
if artist is not None:
self.artist = artist
if self.fig is None:
self.fig = artist.fig
self.fig.canvas.mpl_connect('key_press_event', self.process_key)
if increment_index:
self.index += 1
self.index_max += 1
self.current = self.index
self.axes_repo.append(self.artist.ax if type(self.artist.ax) is list else self.artist.ax.tolist())
self.texts_repo.append(self.artist.txt if type(self.artist.txt) is list else self.artist.txt.tolist())
print(f"VViewer added plot number {self.index}", end='\r')
if hide_artist_axes:
self.hide_artist_axes()
def hide_artist_axes(self):
for ax in self.artist.ax:
ax.set_visible(False)
for text in self.artist.txt:
text.set_visible(False)
def finish(self): # simply: undo the last hiding
self.current = self.index
self.animate()
def animate(self):
# remove current axes and set self.index as visible.
for ax in self.axes_repo[self.current]:
ax.set_visible(False)
for text in self.texts_repo[self.current]:
text.set_visible(False)
for ax in self.axes_repo[self.index]:
ax.set_visible(True)
for text in self.texts_repo[self.index]:
text.set_visible(True)
self.current = self.index
self.fig.canvas.draw()
class VisibilityViewerAuto(VisibilityViewer):
def __init__(self, data=None, artist=None, memorize=False, transpose=True, save_type=SaveType.Null,
save_dir=None, save_name=None, delay=1,
titles=None, legends=None, x_labels=None, pause=True, **kwargs):
"""
The difference between this class and `VisibilityViewer` is that here the parsing of data is done
internally, hence the suffix `Auto`.
:param data: shoud be of the form [[ip1 list], [ip2 list], ...]
i.e. NumArgsPerPlot x NumInputsForAnimation x Input (possible points x signals)
:param artist: an instance of a class that subclasses `Artist`
:param memorize: if set to True, then axes are hidden and shown again, otherwise, plots constructed freshly
every time they're shown (axes are cleaned instead of hidden)
"""
self.kwargs = kwargs
self.memorize = memorize
self.max_index_memorized = 0
if transpose:
data = np.array(list(zip(*data)))
self.data = data
self.legends = legends
if legends is None:
self.legends = [f"Curve {i}" for i in range(len(self.data))]
self.titles = titles if titles is not None else np.arange(len(self.data))
self.lables = x_labels
if artist is None:
artist = Artist(*self.data[0], title=self.titles[0], legends=self.legends, create_new_axes=True,
**kwargs)
else:
artist.plot(*self.data[0], title=self.titles[0], legends=self.legends)
if memorize:
assert artist.create_new_axes is True, "Auto Viewer is based on hiding and showing and requires new " \
"axes from the artist with every plot"
self.artist = artist
super().__init__(artist=self.artist, hide_artist_axes=False)
self.index_max = len(self.data)
self.pause = pause
self.saver = save_type(watch_figs=[self.fig], save_dir=save_dir, save_name=save_name,
delay=delay, fps=1000 / delay)
self.fname = None
def animate(self):
for i in range(self.index, self.index_max):
datum = self.data[i]
if self.memorize: # ==> plot and use .add() method
if self.index > self.max_index_memorized: # a new plot never done before
self.hide_artist_axes()
self.artist.plot(*datum, title=self.titles[i], legends=self.legends)
self.add(increment_index=False, hide_artist_axes=False) # index incremented via press_key manually
self.max_index_memorized += 1
else: # already seen this plot before ==> use animate method of parent class to hide and show,
# not plot and add
# print(f"current = {self.current}")
super().animate()
else:
self.fig.clf() # instead of making previous axis invisible, delete it completely.
self.artist.plot(*datum, title=self.titles[i], legends=self.legends)
# replot the new data point on a new axis.
self.saver.add()
if self.pause:
break
else:
self.index = i
if self.index == self.index_max - 1 and not self.pause: # arrived at last image and not in manual mode
self.fname = self.saver.finish()
@staticmethod
def test():
return VisibilityViewerAuto(data=np.random.randn(1, 10, 100, 3))
class ImShow(FigureManager):
artist = ['internal', 'external'][0]
parser = ['internal', 'external'][0]
stream = ['clear', 'accumulate', 'update'][2]
def __init__(self, *images_list: typing.Union[list, np.ndarray], sup_titles=None, sub_labels=None, labels=None,
save_type=SaveType.Null, save_name=None, save_dir=None, save_kwargs=None,
subplots_adjust=None, gridspec=None, tight=True, info_loc=None,
nrows=None, ncols=None, ax=None,
figsize=None, figname='im_show', figpolicy=FigurePolicy.add_new,
auto_brightness=True, delay=200, pause=False,
**kwargs):
"""
:param images_list: arbitrary number of image lists separated by comma, say N.
:param sup_titles: Titles for frames. Must have a length equal to number of images in each list, say M.
:param sub_labels: Must have a length = M, and in each entry there should be N labels.
:param labels: if labels are sent via this keyword, they will be repeated for all freames.
:param save_type:
:param save_dir:
:param save_name:
:param nrows:
:param ncols:
:param delay:
:param kwargs: passed to imshow
Design point: The expected inputs are made to be consistent with image_list passed. Labels and titles passed
should have similar structure. The function internally process them.
Tip: Use np.arrray_split to get sublists and have multiple plots per frame. Useful for very long lists.
"""
super(ImShow, self).__init__(info_loc=info_loc)
num_plots = len(images_list) # Number of images in each plot
self.num_plots = num_plots
lengths = [len(images_list[i]) for i in range(num_plots)]
self.index_max = min(lengths)
nrows, ncols = self.get_nrows_ncols(num_plots, nrows, ncols)
# Pad zero images for lists that have differnt length from the max.
# images_list = list(images_list) # now it is mutable, unlike tuple.
# for i, a_list in enumerate(images_list):
# diff = self.num_images - len(a_list)
# if diff > 0:
# for _ in range(diff):
# if type(a_list) is list:
# a_list.append(np.zeros_like(a_list[0]))
# else: # numpy array
# a_list = np.concatenate([a_list, [a_list[0]]])
# images_list[i] = a_list
# # As far as labels are concerned, None is typed, if length is passed.
# axprev = plt.axes([0.7, 0.05, 0.1, 0.075])
# axnext = plt.axes([0.81, 0.05, 0.1, 0.075])
# bnext = Button(axnext, 'Next')
# bnext.on_clicked(callback.next)
# bprev = Button(axprev, 'Previous')
# bprev.on_clicked(callback.prev)
if sup_titles is None:
sup_titles = [str(i) for i in np.arange(self.index_max)]
if labels:
sub_labels = [[a_label for _ in np.arange(self.index_max)] for a_label in labels]
elif sub_labels is None:
sub_labels = [[str(i) for i in np.arange(self.index_max)] for _ in range(self.num_plots)]
self.image_list = images_list
self.sub_labels = sub_labels
self.titles = sup_titles
self.delay = delay
self.fname = None
self.kwargs = kwargs
self.event = None
self.cmaps = Cycle(plt.colormaps())
self.cmaps.set('viridis')
self.auto_brightness = auto_brightness
if ax is None:
self.figpolicy = figpolicy
self.fig = self.get_fig(figname=figname,
figsize=(14, 9) if figsize is None else figsize, facecolor='white')
if figsize is None:
plt.get_current_fig_manager().full_screen_toggle()
# .window.showMaximized() # state('zoom')
# plt.get_current_fig_manager().window.setGeometry(800,70,1000,900)
if gridspec is not None:
gs = self.fig.add_gridspec(gridspec[0])
self.ax = []
for ags in gs[1:]:
self.ax.append(self.fig.add_subplot(gs[ags[0], ags[1]]))
else:
self.ax = self.fig.subplots(nrows=nrows, ncols=ncols)
else:
self.ax = ax
try:
self.fig = ax[0].figure
except TypeError: # Not subscriptable, single axis.
self.fig = ax.figure
self.fig.canvas.mpl_connect('key_press_event', self.process_key)
self.fig.canvas.mpl_connect("pick_event", self.annotate)
if tight:
self.fig.tight_layout()
if subplots_adjust is not None:
self.fig.subplots_adjust(**subplots_adjust)
# if save_type.parser == "internal":
# raise TypeError("Requires external data parser")
if save_kwargs is None:
save_kwargs = {}
self.saver = save_type(watch_figs=[self.fig], save_dir=save_dir, save_name=save_name,
delay=delay, fps=1000 / delay, **save_kwargs)
if nrows == 1 and ncols == 1:
self.ax = [self.ax] # make a list out of it.
else:
self.ax = self.ax.ravel() # make a 1D list out of a 2D array.
for an_ax in self.ax:
# an_ax.set_xticks([])
# an_ax.set_yticks([])
self.toggle_ticks(an_ax, state=False)
self.transposed_images = [images for images in zip(*images_list)]
self.transposed_sublabels = [labels for labels in zip(*sub_labels)]
self.ims = [] # container for images.
self.pause = pause
self.index = 0
self.animate()
def animate(self):
for i in range(self.index, self.index_max):
for j, (an_image, a_label, an_ax) in enumerate(zip(self.transposed_images[i],
self.transposed_sublabels[i],
self.ax)):
# with zipping, the shortest of the three, will stop the loop.
if i == 0 and self.ims.__len__() < self.num_plots:
im = an_ax.imshow(an_image, animated=True, **self.kwargs)
self.ims.append(im)
else:
self.ims[j].set_data(an_image)
if self.auto_brightness:
self.ims[j].norm.autoscale(an_image)
an_ax.set_xlabel(f'{a_label}')
self.fig.suptitle(self.titles[i], fontsize=8)
self.saver.add(names=[self.titles[i]])
if self.pause:
break
else:
self.index = i
if self.index == self.index_max - 1 and not self.pause: # arrived at last image and not in manual mode
self.fname = self.saver.finish()
def annotate(self, event, axis=None, data=None):
for ax in self.ax:
super().annotate(event, axis=ax, data=ax.images[0].get_array())
@classmethod
def from_saved_images_path_lists(cls, *image_list, **kwargs):
images = []
sub_labels = []
for alist in image_list:
image_subcontainer = []
label_subcontainer = []
for an_image in alist:
image_subcontainer.append(plt.imread(an_image))
label_subcontainer.append(P(an_image).name)
images.append(image_subcontainer)
sub_labels.append(label_subcontainer)
return cls(*images, sub_labels=sub_labels, **kwargs)
@classmethod
def from_directories(cls, *directories, extension='png', **kwargs):
paths = []
for a_dir in directories:
paths.append(P(a_dir).search(f"*.{extension}", win_order=True))
return cls.from_saved_images_path_lists(*paths, **kwargs)
@classmethod
def from_saved(cls, *things, **kwargs):
example_item = things[0]
if isinstance(example_item, list):
return cls.from_saved_images_path_lists(*things, **kwargs)
else:
return cls.from_directories(*things, **kwargs)
@staticmethod
def cm(im, nrows=3, ncols=7, **kwargs):
""" Useful for looking at one image in multiple cmaps
:param im:
:param nrows:
:param ncols:
:param kwargs:
:return:
"""
styles = plt.colormaps()
colored = [plt.get_cmap(style)(im) for style in styles]
splitted = np.array_split(colored, nrows * ncols)
labels = np.array_split(styles, nrows * ncols)
_ = ImShow(*splitted, nrows=nrows, ncols=ncols, sub_labels=labels, **kwargs)
return colored
@staticmethod
def test():
return ImShow(*np.random.randn(12, 101, 100, 100))
@classmethod
def complex(cls, data, pause=True, **kwargs):
return cls(data.real, data.imag, np.angle(data), abs(data), labels=['Real Part', 'Imaginary Part',
'Angle in Radians', 'Absolute Value'],
pause=pause, **kwargs)
@staticmethod
def resize(path, m, n):
from skimage.transform import resize
image = plt.imread(path)
image_resized = resize(image, (m, n), anti_aliasing=True)
plt.imsave(path, image_resized)
class Artist(FigureManager):
def __init__(self, *args, ax=None, figname='Graph', title='', label='curve', style='seaborn',
create_new_axes=False, figpolicy=FigurePolicy.add_new, figsize=(7, 4), **kwargs):
super().__init__(figpolicy=figpolicy)
self.style = style
# self.kwargs = kwargs
self.title = title
self.args = args
self.line = self.cursor = self.check_b = None
if ax is None: # create a figure
with plt.style.context(style=self.style):
self.fig = self.get_fig(figname, figsize=figsize)
else: # use the passed axis
self.ax = ax
self.fig = ax[0].figure
if len(args): # if there's something to plot in the init
if not ax: # no ax sent but we need to plot, we need an ax, plot will soon call get_axes.
self.create_new_axes = True # just for the first time in this init method.
self.plot(*self.args, label=label, title=title, **kwargs)
else: # nothing to be plotted in the init
if not create_new_axes: # are we going to ever create new axes?
self.create_new_axes = True # if not then let's create one now.
self.get_axes()
self.create_new_axes = create_new_axes
self.visibility_ax = [0.01, 0.05, 0.2, 0.15]
self.txt = []
def plot(self, *args, **kwargs):
self.get_axes()
self.accessorize(*args, **kwargs)
def accessorize(self, *args, legends=None, title=None, **kwargs):
self.line = self.ax[0].plot(*args, **kwargs)
if legends is not None:
self.ax[0].legend(legends)
if title is not None:
self.ax[0].set_title(title)
self.ax[0].grid('on')
def get_axes(self):
if self.create_new_axes:
axis = self.fig.subplots()
self.ax = np.array([axis])
else: # use same old axes
pass
def suptitle(self, title):
self.txt = [self.fig.text(0.5, 0.98, title, ha='center', va='center', size=9)]
def visibility(self):
from matplotlib.widgets import CheckButtons
self.fig.subplots_adjust(left=0.3)
self.visibility_ax[-1] = 0.05 * len(self.ax.lines)
rax = self.fig.add_axes(self.visibility_ax)
labels = [str(line.get_label()) for line in self.ax.lines]
visibility = [line.get_visible() for line in self.ax.lines]
self.check_b = CheckButtons(rax, labels, visibility)
def func(label):
index = labels.index(label)
self.ax.lines[index].set_visible(not self.ax.lines[index].get_visible())
self.fig.canvas.draw()
self.check_b.on_clicked(func)
@staticmethod
def styler(plot_gen):
styles = plt.style.available
for astyle in styles:
with plt.style.context(style=astyle):
plot_gen()
plt.title(astyle)
plt.pause(1)
plt.cla()
if __name__ == '__main__':
if len(sys.argv) > 1:
exec(sys.argv[1])
| [
"pandas.read_csv",
"gzip.open",
"scipy.io.loadmat",
"webbrowser.open",
"numpy.array_split",
"matplotlib.colors.CSS4_COLORS.keys",
"matplotlib.pyplot.MultipleLocator",
"matplotlib.pyplot.style.context",
"copy.deepcopy",
"numpy.sin",
"numpy.arange",
"textwrap.dedent",
"re.split",
"subprocess... | [((3278, 3284), 'pathlib.Path', 'Path', ([], {}), '()\n', (3282, 3284), False, 'from pathlib import Path\n'), ((32307, 32333), 'numpy.concatenate', 'np.concatenate', (['op'], {'axis': '(0)'}), '(op, axis=0)\n', (32321, 32333), True, 'import numpy as np\n'), ((1126, 1164), 'numpy.save', 'np.save', (['path', 'self.__dict__'], {}), '(path, self.__dict__, **kwargs)\n', (1133, 1164), True, 'import numpy as np\n'), ((4817, 4855), 'datetime.datetime.fromtimestamp', 'datetime.fromtimestamp', (['time'], {}), '(time, **kwargs)\n', (4839, 4855), False, 'from datetime import datetime\n'), ((28287, 28324), 'pandas.read_csv', 'pd.read_csv', (['path'], {'dtypes': 'w'}), '(path, dtypes=w, **kwargs)\n', (28298, 28324), True, 'import pandas as pd\n'), ((28786, 28820), 'pandas.read_csv', 'pd.read_csv', (['path', '*args'], {}), '(path, *args, **kwargs)\n', (28797, 28820), True, 'import pandas as pd\n'), ((31842, 31856), 'os.cpu_count', 'os.cpu_count', ([], {}), '()\n', (31854, 31856), False, 'import os\n'), ((42506, 42535), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': 'columns'}), '(columns=columns)\n', (42518, 42535), True, 'import pandas as pd\n'), ((42915, 42934), 'numpy.array', 'np.array', (['self.list'], {}), '(self.list)\n', (42923, 42934), True, 'import numpy as np\n'), ((50056, 50100), 'pandas.DataFrame', 'pd.DataFrame', (['self.__dict__', '*args'], {}), '(self.__dict__, *args, **kwargs)\n', (50068, 50100), True, 'import pandas as pd\n'), ((51667, 51697), 'numpy.random.choice', 'np.random.choice', (['self.c', 'size'], {}), '(self.c, size)\n', (51683, 51697), True, 'import numpy as np\n'), ((55515, 55538), 'inspect.getsource', 'inspect.getsource', (['name'], {}), '(name)\n', (55532, 55538), False, 'import inspect\n'), ((55800, 55826), 'textwrap.dedent', 'textwrap.dedent', (['codelines'], {}), '(codelines)\n', (55815, 55826), False, 'import textwrap\n'), ((56080, 56108), 'inspect.getfullargspec', 'inspect.getfullargspec', (['name'], {}), '(name)\n', (56102, 56108), False, 'import inspect\n'), ((57606, 57630), 'importlib.reload', 'importlib.reload', (['module'], {}), '(module)\n', (57622, 57630), False, 'import importlib\n'), ((59323, 59355), 'numpy.moveaxis', 'np.moveaxis', (['array', 'ax2', '(ax1 + 1)'], {}), '(array, ax2, ax1 + 1)\n', (59334, 59355), True, 'import numpy as np\n'), ((60401, 60433), 'numpy.roll', 'np.roll', (['array', '(-roll)'], {'axis': 'axis'}), '(array, -roll, axis=axis)\n', (60408, 60433), True, 'import numpy as np\n'), ((63064, 63079), 'pandas.DataFrame', 'pd.DataFrame', (['x'], {}), '(x)\n', (63076, 63079), True, 'import pandas as pd\n'), ((63130, 63166), 'pandas.set_option', 'pd.set_option', (['"""display.width"""', '(1000)'], {}), "('display.width', 1000)\n", (63143, 63166), True, 'import pandas as pd\n'), ((63175, 63216), 'pandas.set_option', 'pd.set_option', (['"""display.max_columns"""', '(200)'], {}), "('display.max_columns', 200)\n", (63188, 63216), True, 'import pandas as pd\n'), ((63225, 63266), 'pandas.set_option', 'pd.set_option', (['"""display.max_colwidth"""', '(40)'], {}), "('display.max_colwidth', 40)\n", (63238, 63266), True, 'import pandas as pd\n'), ((63275, 63314), 'pandas.set_option', 'pd.set_option', (['"""display.max_rows"""', '(1000)'], {}), "('display.max_rows', 1000)\n", (63288, 63314), True, 'import pandas as pd\n'), ((63357, 63413), 'pandas.set_eng_float_format', 'pd.set_eng_float_format', ([], {'accuracy': '(3)', 'use_eng_prefix': '(True)'}), '(accuracy=3, use_eng_prefix=True)\n', (63380, 63413), True, 'import pandas as pd\n'), ((63482, 63511), 'pandas.set_option', 'pd.set_option', (['"""precision"""', '(7)'], {}), "('precision', 7)\n", (63495, 63511), True, 'import pandas as pd\n'), ((71817, 71836), 'matplotlib.pyplot.get_figlabels', 'plt.get_figlabels', ([], {}), '()\n', (71834, 71836), True, 'import matplotlib.pyplot as plt\n'), ((78309, 78327), 'numpy.ndenumerate', 'np.ndenumerate', (['im'], {}), '(im)\n', (78323, 78327), True, 'import numpy as np\n'), ((81800, 81814), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (81812, 81814), True, 'import matplotlib.pyplot as plt\n'), ((81827, 81850), 'numpy.arange', 'np.arange', (['(0)', '(100)', '(0.01)'], {}), '(0, 100, 0.01)\n', (81836, 81850), True, 'import numpy as np\n'), ((82173, 82216), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(11.69, 8.27)', 'num': 'name'}), '(figsize=(11.69, 8.27), num=name)\n', (82183, 82216), True, 'import matplotlib.pyplot as plt\n'), ((82496, 82527), 'matplotlib.pyplot.rc', 'plt.rc', (['"""xtick"""'], {'labelsize': 'size'}), "('xtick', labelsize=size)\n", (82502, 82527), True, 'import matplotlib.pyplot as plt\n'), ((82536, 82567), 'matplotlib.pyplot.rc', 'plt.rc', (['"""ytick"""'], {'labelsize': 'size'}), "('ytick', labelsize=size)\n", (82542, 82567), True, 'import matplotlib.pyplot as plt\n'), ((82576, 82606), 'matplotlib.pyplot.rc', 'plt.rc', (['"""axes"""'], {'labelsize': 'size'}), "('axes', labelsize=size)\n", (82582, 82606), True, 'import matplotlib.pyplot as plt\n'), ((82615, 82645), 'matplotlib.pyplot.rc', 'plt.rc', (['"""axes"""'], {'titlesize': 'size'}), "('axes', titlesize=size)\n", (82621, 82645), True, 'import matplotlib.pyplot as plt\n'), ((82654, 82691), 'matplotlib.pyplot.rc', 'plt.rc', (['"""legend"""'], {'fontsize': '(size / 1.5)'}), "('legend', fontsize=size / 1.5)\n", (82660, 82691), True, 'import matplotlib.pyplot as plt\n'), ((82777, 82844), 'matplotlib.pyplot.rc', 'plt.rc', (['"""font"""'], {}), "('font', **{'family': 'serif', 'serif': ['Computer Modern']})\n", (82783, 82844), True, 'import matplotlib.pyplot as plt\n'), ((83422, 83463), 'matplotlib.pyplot.rc', 'plt.rc', (['"""axes"""'], {'prop_cycle': 'default_cycler'}), "('axes', prop_cycle=default_cycler)\n", (83428, 83463), True, 'import matplotlib.pyplot as plt\n'), ((83637, 83656), 'matplotlib.pyplot.close', 'plt.close', (['self.fig'], {}), '(self.fig)\n', (83646, 83656), True, 'import matplotlib.pyplot as plt\n'), ((114372, 114387), 'matplotlib.pyplot.colormaps', 'plt.colormaps', ([], {}), '()\n', (114385, 114387), True, 'import matplotlib.pyplot as plt\n'), ((114471, 114509), 'numpy.array_split', 'np.array_split', (['colored', '(nrows * ncols)'], {}), '(colored, nrows * ncols)\n', (114485, 114509), True, 'import numpy as np\n'), ((114527, 114564), 'numpy.array_split', 'np.array_split', (['styles', '(nrows * ncols)'], {}), '(styles, nrows * ncols)\n', (114541, 114564), True, 'import numpy as np\n'), ((115207, 115223), 'matplotlib.pyplot.imread', 'plt.imread', (['path'], {}), '(path)\n', (115217, 115223), True, 'import matplotlib.pyplot as plt\n'), ((115248, 115289), 'skimage.transform.resize', 'resize', (['image', '(m, n)'], {'anti_aliasing': '(True)'}), '(image, (m, n), anti_aliasing=True)\n', (115254, 115289), False, 'from skimage.transform import resize\n'), ((115298, 115329), 'matplotlib.pyplot.imsave', 'plt.imsave', (['path', 'image_resized'], {}), '(path, image_resized)\n', (115308, 115329), True, 'import matplotlib.pyplot as plt\n'), ((117820, 117857), 'matplotlib.widgets.CheckButtons', 'CheckButtons', (['rax', 'labels', 'visibility'], {}), '(rax, labels, visibility)\n', (117832, 117857), False, 'from matplotlib.widgets import CheckButtons\n'), ((2498, 2526), 'copy.deepcopy', 'copy.deepcopy', (['self.__dict__'], {}), '(self.__dict__)\n', (2511, 2526), False, 'import copy\n'), ((14844, 14866), 'os.startfile', 'os.startfile', (['filename'], {}), '(filename)\n', (14856, 14866), False, 'import os\n'), ((25940, 25958), 'gzip.open', 'gzip.open', (['fn', '"""r"""'], {}), "(fn, 'r')\n", (25949, 25958), False, 'import gzip\n'), ((26010, 26041), 'shutil.copyfileobj', 'shutil.copyfileobj', (['f_in', 'f_out'], {}), '(f_in, f_out)\n', (26028, 26041), False, 'import shutil\n'), ((27460, 27483), 'scipy.io.loadmat', 'loadmat', (['path'], {}), '(path, **kwargs)\n', (27467, 27483), False, 'from scipy.io import loadmat\n'), ((27661, 27686), 'json.load', 'json.load', (['file'], {}), '(file, **kwargs)\n', (27670, 27686), False, 'import json\n'), ((27932, 27971), 'yaml.load', 'yaml.load', (['file'], {'Loader': 'yaml.FullLoader'}), '(file, Loader=yaml.FullLoader)\n', (27941, 27971), False, 'import yaml\n'), ((30224, 30284), 'json.dump', 'json.dump', (['obj', 'file'], {'default': '(lambda x: x.__dict__)'}), '(obj, file, default=lambda x: x.__dict__, **kwargs)\n', (30233, 30284), False, 'import json\n'), ((30497, 30527), 'yaml.dump', 'yaml.dump', (['obj', 'file'], {}), '(obj, file, **kwargs)\n', (30506, 30527), False, 'import yaml\n'), ((48537, 48560), 'copy.deepcopy', 'copy.deepcopy', (['dicts[0]'], {}), '(dicts[0])\n', (48550, 48560), False, 'import copy\n'), ((52052, 52070), 'sys.stdout.close', 'sys.stdout.close', ([], {}), '()\n', (52068, 52070), False, 'import sys\n'), ((53279, 53301), 'inspect.getsource', 'inspect.getsource', (['obj'], {}), '(obj)\n', (53296, 53301), False, 'import inspect\n'), ((64987, 65001), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (64999, 65001), False, 'from datetime import datetime\n'), ((65353, 65368), 'matplotlib.pyplot.colormaps', 'plt.colormaps', ([], {}), '()\n', (65366, 65368), True, 'import matplotlib.pyplot as plt\n'), ((65442, 65468), 'matplotlib.colors.CSS4_COLORS.keys', 'mcolors.CSS4_COLORS.keys', ([], {}), '()\n', (65466, 65468), True, 'import matplotlib.colors as mcolors\n'), ((71890, 71921), 'matplotlib.pyplot.close', 'plt.close', (['"""Keyboard shortcuts"""'], {}), "('Keyboard shortcuts')\n", (71899, 71921), True, 'import matplotlib.pyplot as plt\n'), ((71964, 72000), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'num': '"""Keyboard shortcuts"""'}), "(num='Keyboard shortcuts')\n", (71974, 72000), True, 'import matplotlib.pyplot as plt\n'), ((79240, 79263), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'num': 'figname'}), '(num=figname)\n', (79250, 79263), True, 'import matplotlib.pyplot as plt\n'), ((80107, 80140), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'num': 'figname'}), '(num=figname, **kwargs)\n', (80117, 80140), True, 'import matplotlib.pyplot as plt\n'), ((81863, 81872), 'numpy.sin', 'np.sin', (['x'], {}), '(x)\n', (81869, 81872), True, 'import numpy as np\n'), ((83392, 83412), 'cycler.cycler', 'cycler', ([], {'color': 'colors'}), '(color=colors)\n', (83398, 83412), False, 'from cycler import cycler\n'), ((83500, 83523), 'numpy.random.randn', 'np.random.randn', (['(10)', '(10)'], {}), '(10, 10)\n', (83515, 83523), True, 'import numpy as np\n'), ((84757, 84786), 'matplotlib.pyplot.pause', 'plt.pause', (['(self.delay * 0.001)'], {}), '(self.delay * 0.001)\n', (84766, 84786), True, 'import matplotlib.pyplot as plt\n'), ((86467, 86519), 'os.path.join', 'os.path.join', (['self.save_dir', "(self.save_name + '.pdf')"], {}), "(self.save_dir, self.save_name + '.pdf')\n", (86479, 86519), False, 'import os\n'), ((86542, 86562), 'matplotlib.backends.backend_pdf.PdfPages', 'PdfPages', (['self.fname'], {}), '(self.fname)\n', (86550, 86562), False, 'from matplotlib.backends.backend_pdf import PdfPages\n'), ((87454, 87497), 'os.path.join', 'os.path.join', (['self.save_dir', 'self.save_name'], {}), '(self.save_dir, self.save_name)\n', (87466, 87497), False, 'import os\n'), ((87510, 87551), 'os.makedirs', 'os.makedirs', (['self.save_dir'], {'exist_ok': '(True)'}), '(self.save_dir, exist_ok=True)\n', (87521, 87551), False, 'import os\n'), ((89249, 89273), 'collections.defaultdict', 'defaultdict', (['(lambda : [])'], {}), '(lambda : [])\n', (89260, 89273), False, 'from collections import defaultdict\n'), ((91784, 91839), 'os.path.join', 'os.path.join', (['self.save_dir', '(self.save_name + extension)'], {}), '(self.save_dir, self.save_name + extension)\n', (91796, 91839), False, 'import os\n'), ((93793, 93807), 'matplotlib.pyplot.pause', 'plt.pause', (['(0.5)'], {}), '(0.5)\n', (93802, 93807), True, 'import matplotlib.pyplot as plt\n'), ((94895, 94924), 'matplotlib.pyplot.pause', 'plt.pause', (['(self.delay * 0.001)'], {}), '(self.delay * 0.001)\n', (94904, 94924), True, 'import matplotlib.pyplot as plt\n'), ((95005, 95185), 'matplotlib.animation.FuncAnimation', 'animation.FuncAnimation', (['self.plotter.fig', 'self.plotter.animate'], {'frames': 'self.gen', 'interval': 'interval', 'repeat_delay': '(1500)', 'fargs': 'None', 'cache_frame_data': '(True)', 'save_count': '(10000)'}), '(self.plotter.fig, self.plotter.animate, frames=self\n .gen, interval=interval, repeat_delay=1500, fargs=None,\n cache_frame_data=True, save_count=10000)\n', (95028, 95185), False, 'from matplotlib import animation\n'), ((97071, 97126), 'os.path.join', 'os.path.join', (['self.save_dir', '(self.save_name + extension)'], {}), '(self.save_dir, self.save_name + extension)\n', (97083, 97126), False, 'import os\n'), ((97357, 97371), 'matplotlib.pyplot.pause', 'plt.pause', (['(0.5)'], {}), '(0.5)\n', (97366, 97371), True, 'import matplotlib.pyplot as plt\n'), ((109346, 109361), 'matplotlib.pyplot.colormaps', 'plt.colormaps', ([], {}), '()\n', (109359, 109361), True, 'import matplotlib.pyplot as plt\n'), ((114876, 114890), 'numpy.angle', 'np.angle', (['data'], {}), '(data)\n', (114884, 114890), True, 'import numpy as np\n'), ((117241, 117257), 'numpy.array', 'np.array', (['[axis]'], {}), '([axis])\n', (117249, 117257), True, 'import numpy as np\n'), ((10378, 10397), 'random.choice', 'random.choice', (['pool'], {}), '(pool)\n', (10391, 10397), False, 'import random\n'), ((10864, 10903), 'shutil.rmtree', 'shutil.rmtree', (['self'], {'ignore_errors': '(True)'}), '(self, ignore_errors=True)\n', (10877, 10903), False, 'import shutil\n'), ((15016, 15051), 'subprocess.call', 'subprocess.call', (['[opener, filename]'], {}), '([opener, filename])\n', (15031, 15051), False, 'import subprocess\n'), ((15196, 15231), 'subprocess.call', 'subprocess.call', (["['open', filename]"], {}), "(['open', filename])\n", (15211, 15231), False, 'import subprocess\n'), ((25724, 25755), 'shutil.copyfileobj', 'shutil.copyfileobj', (['f_in', 'f_out'], {}), '(f_in, f_out)\n', (25742, 25755), False, 'import shutil\n'), ((32964, 32982), 'copy.deepcopy', 'copy.deepcopy', (['obj'], {}), '(obj)\n', (32977, 32982), False, 'import copy\n'), ((34226, 34242), 'copy.deepcopy', 'copy.deepcopy', (['i'], {}), '(i)\n', (34239, 34242), False, 'import copy\n'), ((52411, 52483), 'subprocess.check_call', 'subprocess.check_call', (["[sys.executable, '-m', 'pip', 'install', package]"], {}), "([sys.executable, '-m', 'pip', 'install', package])\n", (52432, 52483), False, 'import subprocess\n'), ((61713, 61729), 'numpy.array', 'np.array', (['output'], {}), '(output)\n', (61721, 61729), True, 'import numpy as np\n'), ((62514, 62530), 'numpy.array', 'np.array', (['output'], {}), '(output)\n', (62522, 62530), True, 'import numpy as np\n'), ((65506, 65534), 'matplotlib.colors.CSS4_COLORS.values', 'mcolors.CSS4_COLORS.values', ([], {}), '()\n', (65532, 65534), True, 'import matplotlib.colors as mcolors\n'), ((68303, 68329), 'matplotlib.pyplot.MultipleLocator', 'plt.MultipleLocator', (['steps'], {}), '(steps)\n', (68322, 68329), True, 'import matplotlib.pyplot as plt\n'), ((68586, 68612), 'matplotlib.pyplot.MultipleLocator', 'plt.MultipleLocator', (['steps'], {}), '(steps)\n', (68605, 68612), True, 'import matplotlib.pyplot as plt\n'), ((68816, 68845), 'matplotlib.pyplot.get_current_fig_manager', 'plt.get_current_fig_manager', ([], {}), '()\n', (68843, 68845), True, 'import matplotlib.pyplot as plt\n'), ((80015, 80034), 'matplotlib.pyplot.get_figlabels', 'plt.get_figlabels', ([], {}), '()\n', (80032, 80034), True, 'import matplotlib.pyplot as plt\n'), ((80378, 80412), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'num': 'new_name'}), '(num=new_name, **kwargs)\n', (80388, 80412), True, 'import matplotlib.pyplot as plt\n'), ((83084, 83108), 'matplotlib.lines.lineMarkers.keys', 'lines.lineMarkers.keys', ([], {}), '()\n', (83106, 83108), False, 'from matplotlib import lines\n'), ((83160, 83183), 'matplotlib.lines.lineStyles.keys', 'lines.lineStyles.keys', ([], {}), '()\n', (83181, 83183), False, 'from matplotlib import lines\n'), ((83336, 83364), 'cycler.cycler', 'cycler', ([], {'linestyle': 'linestyles'}), '(linestyle=linestyles)\n', (83342, 83364), False, 'from cycler import cycler\n'), ((83367, 83389), 'cycler.cycler', 'cycler', ([], {'marker': 'markers'}), '(marker=markers)\n', (83373, 83389), False, 'from cycler import cycler\n'), ((83584, 83606), 'matplotlib.pyplot.plot', 'plt.plot', (['(aq + idx * 2)'], {}), '(aq + idx * 2)\n', (83592, 83606), True, 'import matplotlib.pyplot as plt\n'), ((84883, 84893), 'matplotlib.pyplot.ioff', 'plt.ioff', ([], {}), '()\n', (84891, 84893), True, 'import matplotlib.pyplot as plt\n'), ((87262, 87281), 'webbrowser.open', 'wb.open', (['self.fname'], {}), '(self.fname)\n', (87269, 87281), True, 'import webbrowser as wb\n'), ((87728, 87762), 'os.path.join', 'os.path.join', (['self.save_dir', 'aname'], {}), '(self.save_dir, aname)\n', (87740, 87762), False, 'import os\n'), ((94479, 94510), 'matplotlib.animation.PillowWriter', 'animation.PillowWriter', ([], {'fps': 'fps'}), '(fps=fps)\n', (94501, 94510), False, 'from matplotlib import animation\n'), ((105853, 105883), 'numpy.random.randn', 'np.random.randn', (['(1)', '(10)', '(100)', '(3)'], {}), '(1, 10, 100, 3)\n', (105868, 105883), True, 'import numpy as np\n'), ((114407, 114426), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['style'], {}), '(style)\n', (114419, 114426), True, 'import matplotlib.pyplot as plt\n'), ((114731, 114765), 'numpy.random.randn', 'np.random.randn', (['(12)', '(101)', '(100)', '(100)'], {}), '(12, 101, 100, 100)\n', (114746, 114765), True, 'import numpy as np\n'), ((115827, 115862), 'matplotlib.pyplot.style.context', 'plt.style.context', ([], {'style': 'self.style'}), '(style=self.style)\n', (115844, 115862), True, 'import matplotlib.pyplot as plt\n'), ((118212, 118243), 'matplotlib.pyplot.style.context', 'plt.style.context', ([], {'style': 'astyle'}), '(style=astyle)\n', (118229, 118243), True, 'import matplotlib.pyplot as plt\n'), ((118288, 118305), 'matplotlib.pyplot.title', 'plt.title', (['astyle'], {}), '(astyle)\n', (118297, 118305), True, 'import matplotlib.pyplot as plt\n'), ((118322, 118334), 'matplotlib.pyplot.pause', 'plt.pause', (['(1)'], {}), '(1)\n', (118331, 118334), True, 'import matplotlib.pyplot as plt\n'), ((118351, 118360), 'matplotlib.pyplot.cla', 'plt.cla', ([], {}), '()\n', (118358, 118360), True, 'import matplotlib.pyplot as plt\n'), ((20171, 20187), 'os.listdir', 'os.listdir', (['self'], {}), '(self)\n', (20181, 20187), False, 'import os\n'), ((40624, 40639), 'tqdm.tqdm', 'tqdm', (['self.list'], {}), '(self.list)\n', (40628, 40639), False, 'from tqdm import tqdm\n'), ((70032, 70049), 'numpy.round', 'np.round', (['e.xdata'], {}), '(e.xdata)\n', (70040, 70049), True, 'import numpy as np\n'), ((70056, 70073), 'numpy.round', 'np.round', (['e.ydata'], {}), '(e.ydata)\n', (70064, 70073), True, 'import numpy as np\n'), ((75856, 75874), 'numpy.sqrt', 'np.sqrt', (['num_plots'], {}), '(num_plots)\n', (75863, 75874), True, 'import numpy as np\n'), ((75909, 75927), 'numpy.sqrt', 'np.sqrt', (['num_plots'], {}), '(num_plots)\n', (75916, 75927), True, 'import numpy as np\n'), ((76060, 76086), 'numpy.ceil', 'np.ceil', (['(num_plots / nrows)'], {}), '(num_plots / nrows)\n', (76067, 76086), True, 'import numpy as np\n'), ((76549, 76618), 'matplotlib.widgets.Cursor', 'widgets.Cursor', ([], {'ax': 'ax', 'vertOn': '(True)', 'horizOn': '(True)', 'color': '"""red"""', 'lw': '(1.0)'}), "(ax=ax, vertOn=True, horizOn=True, color='red', lw=1.0)\n", (76563, 76618), False, 'from matplotlib import widgets\n'), ((80545, 80578), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'num': 'figname'}), '(num=figname, **kwargs)\n', (80555, 80578), True, 'import matplotlib.pyplot as plt\n'), ((84979, 84998), 'matplotlib.pyplot.figure', 'plt.figure', (['figname'], {}), '(figname)\n', (84989, 84998), True, 'import matplotlib.pyplot as plt\n'), ((85163, 85182), 'matplotlib.pyplot.get_figlabels', 'plt.get_figlabels', ([], {}), '()\n', (85180, 85182), True, 'import matplotlib.pyplot as plt\n'), ((90236, 90331), 'matplotlib.animation.ArtistAnimation', 'animation.ArtistAnimation', (['a_fig', 'ims'], {'interval': 'self.interval', 'blit': '(True)', 'repeat_delay': '(1000)'}), '(a_fig, ims, interval=self.interval, blit=True,\n repeat_delay=1000)\n', (90261, 90331), False, 'from matplotlib import animation\n'), ((95294, 95337), 'os.path.join', 'os.path.join', (['self.save_dir', 'self.save_name'], {}), '(self.save_dir, self.save_name)\n', (95306, 95337), False, 'import os\n'), ((97768, 97797), 'matplotlib.pyplot.pause', 'plt.pause', (['(self.delay * 0.001)'], {}), '(self.delay * 0.001)\n', (97777, 97797), True, 'import matplotlib.pyplot as plt\n'), ((108826, 108851), 'numpy.arange', 'np.arange', (['self.index_max'], {}), '(self.index_max)\n', (108835, 108851), True, 'import numpy as np\n'), ((113308, 113328), 'matplotlib.pyplot.imread', 'plt.imread', (['an_image'], {}), '(an_image)\n', (113318, 113328), True, 'import matplotlib.pyplot as plt\n'), ((40466, 40487), 'joblib.Parallel', 'Parallel', ([], {'n_jobs': 'jobs'}), '(n_jobs=jobs)\n', (40474, 40487), False, 'from joblib import Parallel, delayed\n'), ((40830, 40851), 'joblib.Parallel', 'Parallel', ([], {'n_jobs': 'jobs'}), '(n_jobs=jobs)\n', (40838, 40851), False, 'from joblib import Parallel, delayed\n'), ((53479, 53499), 'inspect.getfile', 'inspect.getfile', (['obj'], {}), '(obj)\n', (53494, 53499), False, 'import inspect\n'), ((62115, 62131), 'numpy.array', 'np.array', (['output'], {}), '(output)\n', (62123, 62131), True, 'import numpy as np\n'), ((62960, 62976), 'numpy.array', 'np.array', (['output'], {}), '(output)\n', (62968, 62976), True, 'import numpy as np\n'), ((76146, 76172), 'numpy.ceil', 'np.ceil', (['(num_plots / ncols)'], {}), '(num_plots / ncols)\n', (76153, 76172), True, 'import numpy as np\n'), ((80508, 80526), 'matplotlib.pyplot.close', 'plt.close', (['figname'], {}), '(figname)\n', (80517, 80526), True, 'import matplotlib.pyplot as plt\n'), ((84294, 84314), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'num': 'afig'}), '(num=afig)\n', (84304, 84314), True, 'import matplotlib.pyplot as plt\n'), ((85234, 85247), 'matplotlib.pyplot.figure', 'plt.figure', (['k'], {}), '(k)\n', (85244, 85247), True, 'import matplotlib.pyplot as plt\n'), ((108917, 108942), 'numpy.arange', 'np.arange', (['self.index_max'], {}), '(self.index_max)\n', (108926, 108942), True, 'import numpy as np\n'), ((109711, 109740), 'matplotlib.pyplot.get_current_fig_manager', 'plt.get_current_fig_manager', ([], {}), '()\n', (109738, 109740), True, 'import matplotlib.pyplot as plt\n'), ((17550, 17569), 'fnmatch.fnmatch', 'fnmatch', (['x', 'pattern'], {}), '(x, pattern)\n', (17557, 17569), False, 'from fnmatch import fnmatch\n'), ((53688, 53710), 'inspect.getmodule', 'inspect.getmodule', (['obj'], {}), '(obj)\n', (53705, 53710), False, 'import inspect\n'), ((78415, 78430), 'numpy.round', 'np.round', (['label'], {}), '(label)\n', (78423, 78430), True, 'import numpy as np\n'), ((90534, 90553), 'matplotlib.animation.PillowWriter', 'PillowWriter', ([], {'fps': '(4)'}), '(fps=4)\n', (90546, 90553), False, 'from matplotlib.animation import PillowWriter\n'), ((109043, 109068), 'numpy.arange', 'np.arange', (['self.index_max'], {}), '(self.index_max)\n', (109052, 109068), True, 'import numpy as np\n'), ((40488, 40501), 'joblib.delayed', 'delayed', (['func'], {}), '(func)\n', (40495, 40501), False, 'from joblib import Parallel, delayed\n'), ((40531, 40546), 'tqdm.tqdm', 'tqdm', (['self.list'], {}), '(self.list)\n', (40535, 40546), False, 'from tqdm import tqdm\n'), ((40852, 40865), 'joblib.delayed', 'delayed', (['func'], {}), '(func)\n', (40859, 40865), False, 'from joblib import Parallel, delayed\n'), ((87910, 87926), 'pathlib.Path', 'Path', (['self.fname'], {}), '(self.fname)\n', (87914, 87926), False, 'from pathlib import Path\n'), ((92347, 92363), 'pathlib.Path', 'Path', (['self.fname'], {}), '(self.fname)\n', (92351, 92363), False, 'from pathlib import Path\n'), ((95470, 95486), 'pathlib.Path', 'Path', (['self.fname'], {}), '(self.fname)\n', (95474, 95486), False, 'from pathlib import Path\n'), ((20061, 20089), 're.split', 're.split', (['"""([0-9]+)"""', 'x.stem'], {}), "('([0-9]+)', x.stem)\n", (20069, 20089), False, 'import re\n'), ((90809, 90825), 'pathlib.Path', 'Path', (['self.fname'], {}), '(self.fname)\n', (90813, 90825), False, 'from pathlib import Path\n')] |
import numpy as np
import scipy.signal
from gym.spaces import Box, Discrete
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions.normal import Normal
from torch.distributions.categorical import Categorical
def initialize_weights_he(m):
if isinstance(m, nn.Linear) or isinstance(m, nn.Conv2d):
torch.nn.init.kaiming_uniform_(m.weight)
if m.bias is not None:
torch.nn.init.constant_(m.bias, 0)
class Flatten(nn.Module):
def forward(self, x):
return x.view(x.size(0), -1)
def combined_shape(length, shape=None):
if shape is None:
return (length,)
return (length, shape) if np.isscalar(shape) else (length, *shape)
def mlp(sizes, activation, output_activation=nn.Identity):
layers = []
for j in range(len(sizes)-1):
act = activation if j < len(sizes)-2 else output_activation
layers += [nn.Linear(sizes[j], sizes[j+1]), act()]
return nn.Sequential(*layers)
def cnn(obs_dim, channels=[16,32,32], activation=nn.ReLU()):
layers = []
sizes = [obs_dim[0]] + channels
for j in range(len(sizes)-1):
layers += [nn.Conv2d(sizes[j], sizes[j+1], kernel_size=3, stride=1, padding=(1,1)), activation]
layers += [ nn.AdaptiveAvgPool2d(4), Flatten() ] # 4 * 4 * 32 = 512
return nn.Sequential(*layers), 4 * 4 * 32
#def cnn(obs_dim):
# return nn.Sequential(
# nn.Conv2d(obs_dim, 32, kernel_size=8, stride=4, padding=0),
# nn.ReLU(),
# nn.Conv2d(32, 64, kernel_size=4, stride=2, padding=0),
# nn.ReLU(),
# nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=0),
# nn.ReLU(),
# Flatten()).apply(initialize_weights_he)
def count_vars(module):
return sum([np.prod(p.shape) for p in module.parameters()])
LOG_STD_MAX = 2
LOG_STD_MIN = -20
class SquashedGaussianMLPActor(nn.Module):
def __init__(self, obs_dim, act_dim, hidden_sizes, activation, act_limit, feng):
super().__init__()
if feng == 'mlp':
self.fe_net = Flatten() # nn.Identity()
feat_dim = np.prod(obs_dim)
elif feng == 'cnn':
self.fe_net, feat_dim = cnn(obs_dim)
self.net = mlp([feat_dim] + list(hidden_sizes), activation, activation)
self.mu_layer = nn.Linear(hidden_sizes[-1], act_dim)
self.log_std_layer = nn.Linear(hidden_sizes[-1], act_dim)
self.act_limit = act_limit
def forward(self, obs, deterministic=False, with_logprob=True):
net_out = self.net(self.fe_net(obs))
mu = self.mu_layer(net_out)
log_std = self.log_std_layer(net_out)
log_std = torch.clamp(log_std, LOG_STD_MIN, LOG_STD_MAX)
std = torch.exp(log_std)
# Pre-squash distribution and sample
pi_distribution = Normal(mu, std)
if deterministic:
# Only used for evaluating policy at test time.
pi_action = mu
else:
pi_action = pi_distribution.rsample()
if with_logprob:
# Compute logprob from Gaussian, and then apply correction for Tanh squashing.
# NOTE: The correction formula is a little bit magic. To get an understanding
# of where it comes from, check out the original SAC paper (arXiv 1801.01290)
# and look in appendix C. This is a more numerically-stable equivalent to Eq 21.
# Try deriving it yourself as a (very difficult) exercise. :)
logp_pi = pi_distribution.log_prob(pi_action).sum(axis=-1)
logp_pi -= (2*(np.log(2) - pi_action - F.softplus(-2*pi_action))).sum(axis=1)
#logp_pi -= (2*(np.log(2) + pi_action - F.softplus(2*pi_action))).sum(axis=1) # Use parity to simplify a bit log_pi
else:
logp_pi = None
pi_action = torch.tanh(pi_action)
pi_action = self.act_limit * pi_action
return pi_action, logp_pi, -1
class CategoricalMLPActor(nn.Module):
def __init__(self, obs_dim, act_dim, hidden_sizes, activation, feng):
super().__init__()
if feng == 'mlp':
self.fe_net = Flatten() # nn.Identity()
feat_dim = np.prod(obs_dim)
elif feng == 'cnn':
self.fe_net, feat_dim = cnn(obs_dim)
self.logits_net = mlp([feat_dim] + list(hidden_sizes) + [act_dim], activation)
def forward(self, obs, deterministic=False, with_logprob=True):
logits = self.logits_net(self.fe_net(obs))
pi_distribution = Categorical(logits=logits)
if deterministic:
# Only used for evaluating policy at test time.
pi_action = torch.squeeze(torch.argmax(logits, dim=-1, keepdim=True), -1)
else:
pi_action = torch.squeeze(pi_distribution.sample(), -1)
#if with_logprob:
# #logp_pi = pi_distribution.log_prob(pi_action)
# z = logits == 0.0
# z = z.float() * 1e-8
# logp_pi = torch.log(logits + z)
#else:
# logp_pi = None
if with_logprob:
#logp_pi = pi_distribution.log_prob(pi_action)
logp_pi = F.log_softmax(logits, dim=-1)
return pi_action, logp_pi, torch.exp(logp_pi)
else:
return pi_action, None, None
#return pi_action, logp_pi, logits
class MLPQFunction(nn.Module):
def __init__(self, obs_dim, act_dim, hidden_sizes, activation, feng):
super().__init__()
if feng == 'mlp':
self.fe_net = Flatten() # nn.Identity()
feat_dim = np.prod(obs_dim)
elif feng == 'cnn':
self.fe_net, feat_dim = cnn(obs_dim)
self.q = mlp([feat_dim+act_dim] + list(hidden_sizes) + [1], activation)
self.act_dim = act_dim
def forward(self, obs, act):
q = self.q(torch.cat([self.fe_net(obs), act], dim=-1))
return torch.squeeze(q, -1) # Critical to ensure q has right shape.
class MLPQFunctionDiscrete(nn.Module):
def __init__(self, obs_dim, act_dim, hidden_sizes, activation, feng):
super().__init__()
if feng == 'mlp':
self.fe_net = Flatten() # nn.Identity()
feat_dim = np.prod(obs_dim)
elif feng == 'cnn':
self.fe_net, feat_dim = cnn(obs_dim)
self.q = mlp([feat_dim] + list(hidden_sizes) + [act_dim], activation)
self.act_dim = act_dim
def forward(self, obs, act):
#if len(act.shape) == 1: # discrete action
# act = (F.one_hot(act.to(torch.int64),num_classes=self.act_dim)).to(torch.float32)
pvec = self.q(self.fe_net(obs))
return pvec
class MLPActorCritic(nn.Module):
def __init__(self, observation_space, action_space, hidden_sizes=(256,256),
activation=nn.ReLU, feng='mlp'):
super().__init__()
obs_dim = observation_space.shape # [0]
if isinstance(action_space, Box):
act_dim = action_space.shape[0]
act_limit = action_space.high[0]
elif isinstance(action_space, Discrete):
act_dim = action_space.n
# build policy and value functions
if isinstance(action_space, Box):
self.pi = SquashedGaussianMLPActor(obs_dim, act_dim, hidden_sizes, activation, act_limit, feng)
self.q1 = MLPQFunction(obs_dim, act_dim, hidden_sizes, activation, feng)
self.q2 = MLPQFunction(obs_dim, act_dim, hidden_sizes, activation, feng)
elif isinstance(action_space, Discrete):
self.pi = CategoricalMLPActor(obs_dim, act_dim, hidden_sizes, activation, feng)
self.q1 = MLPQFunctionDiscrete(obs_dim, act_dim, hidden_sizes, activation, feng)
self.q2 = MLPQFunctionDiscrete(obs_dim, act_dim, hidden_sizes, activation, feng)
def act(self, obs, deterministic=False):
with torch.no_grad():
a, _, _ = self.pi(obs, deterministic, False)
return a.cpu().numpy()
| [
"numpy.prod",
"torch.nn.ReLU",
"torch.nn.init.constant_",
"torch.nn.Sequential",
"torch.distributions.normal.Normal",
"numpy.log",
"torch.exp",
"torch.squeeze",
"torch.tanh",
"numpy.isscalar",
"torch.nn.AdaptiveAvgPool2d",
"torch.argmax",
"torch.nn.init.kaiming_uniform_",
"torch.nn.functio... | [((962, 984), 'torch.nn.Sequential', 'nn.Sequential', (['*layers'], {}), '(*layers)\n', (975, 984), True, 'import torch.nn as nn\n'), ((1035, 1044), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (1042, 1044), True, 'import torch.nn as nn\n'), ((346, 386), 'torch.nn.init.kaiming_uniform_', 'torch.nn.init.kaiming_uniform_', (['m.weight'], {}), '(m.weight)\n', (376, 386), False, 'import torch\n'), ((673, 691), 'numpy.isscalar', 'np.isscalar', (['shape'], {}), '(shape)\n', (684, 691), True, 'import numpy as np\n'), ((1253, 1276), 'torch.nn.AdaptiveAvgPool2d', 'nn.AdaptiveAvgPool2d', (['(4)'], {}), '(4)\n', (1273, 1276), True, 'import torch.nn as nn\n'), ((1321, 1343), 'torch.nn.Sequential', 'nn.Sequential', (['*layers'], {}), '(*layers)\n', (1334, 1343), True, 'import torch.nn as nn\n'), ((2318, 2354), 'torch.nn.Linear', 'nn.Linear', (['hidden_sizes[-1]', 'act_dim'], {}), '(hidden_sizes[-1], act_dim)\n', (2327, 2354), True, 'import torch.nn as nn\n'), ((2384, 2420), 'torch.nn.Linear', 'nn.Linear', (['hidden_sizes[-1]', 'act_dim'], {}), '(hidden_sizes[-1], act_dim)\n', (2393, 2420), True, 'import torch.nn as nn\n'), ((2670, 2716), 'torch.clamp', 'torch.clamp', (['log_std', 'LOG_STD_MIN', 'LOG_STD_MAX'], {}), '(log_std, LOG_STD_MIN, LOG_STD_MAX)\n', (2681, 2716), False, 'import torch\n'), ((2731, 2749), 'torch.exp', 'torch.exp', (['log_std'], {}), '(log_std)\n', (2740, 2749), False, 'import torch\n'), ((2822, 2837), 'torch.distributions.normal.Normal', 'Normal', (['mu', 'std'], {}), '(mu, std)\n', (2828, 2837), False, 'from torch.distributions.normal import Normal\n'), ((3830, 3851), 'torch.tanh', 'torch.tanh', (['pi_action'], {}), '(pi_action)\n', (3840, 3851), False, 'import torch\n'), ((4509, 4535), 'torch.distributions.categorical.Categorical', 'Categorical', ([], {'logits': 'logits'}), '(logits=logits)\n', (4520, 4535), False, 'from torch.distributions.categorical import Categorical\n'), ((5877, 5897), 'torch.squeeze', 'torch.squeeze', (['q', '(-1)'], {}), '(q, -1)\n', (5890, 5897), False, 'import torch\n'), ((430, 464), 'torch.nn.init.constant_', 'torch.nn.init.constant_', (['m.bias', '(0)'], {}), '(m.bias, 0)\n', (453, 464), False, 'import torch\n'), ((911, 944), 'torch.nn.Linear', 'nn.Linear', (['sizes[j]', 'sizes[j + 1]'], {}), '(sizes[j], sizes[j + 1])\n', (920, 944), True, 'import torch.nn as nn\n'), ((1152, 1226), 'torch.nn.Conv2d', 'nn.Conv2d', (['sizes[j]', 'sizes[j + 1]'], {'kernel_size': '(3)', 'stride': '(1)', 'padding': '(1, 1)'}), '(sizes[j], sizes[j + 1], kernel_size=3, stride=1, padding=(1, 1))\n', (1161, 1226), True, 'import torch.nn as nn\n'), ((1778, 1794), 'numpy.prod', 'np.prod', (['p.shape'], {}), '(p.shape)\n', (1785, 1794), True, 'import numpy as np\n'), ((2120, 2136), 'numpy.prod', 'np.prod', (['obs_dim'], {}), '(obs_dim)\n', (2127, 2136), True, 'import numpy as np\n'), ((4181, 4197), 'numpy.prod', 'np.prod', (['obs_dim'], {}), '(obs_dim)\n', (4188, 4197), True, 'import numpy as np\n'), ((5137, 5166), 'torch.nn.functional.log_softmax', 'F.log_softmax', (['logits'], {'dim': '(-1)'}), '(logits, dim=-1)\n', (5150, 5166), True, 'import torch.nn.functional as F\n'), ((5559, 5575), 'numpy.prod', 'np.prod', (['obs_dim'], {}), '(obs_dim)\n', (5566, 5575), True, 'import numpy as np\n'), ((6183, 6199), 'numpy.prod', 'np.prod', (['obs_dim'], {}), '(obs_dim)\n', (6190, 6199), True, 'import numpy as np\n'), ((7838, 7853), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (7851, 7853), False, 'import torch\n'), ((4661, 4703), 'torch.argmax', 'torch.argmax', (['logits'], {'dim': '(-1)', 'keepdim': '(True)'}), '(logits, dim=-1, keepdim=True)\n', (4673, 4703), False, 'import torch\n'), ((5206, 5224), 'torch.exp', 'torch.exp', (['logp_pi'], {}), '(logp_pi)\n', (5215, 5224), False, 'import torch\n'), ((3601, 3627), 'torch.nn.functional.softplus', 'F.softplus', (['(-2 * pi_action)'], {}), '(-2 * pi_action)\n', (3611, 3627), True, 'import torch.nn.functional as F\n'), ((3577, 3586), 'numpy.log', 'np.log', (['(2)'], {}), '(2)\n', (3583, 3586), True, 'import numpy as np\n')] |
from __future__ import absolute_import, division, print_function, unicode_literals
import unittest
import io
import os
import tempfile
import numpy as np
from pystan import stan, stanc
class TestStanFileIO(unittest.TestCase):
def test_stan_model_from_file(self):
bernoulli_model_code = """
data {
int<lower=0> N;
int<lower=0,upper=1> y[N];
}
parameters {
real<lower=0,upper=1> theta;
}
model {
for (n in 1:N)
y[n] ~ bernoulli(theta);
}
"""
bernoulli_data = {'N': 10, 'y': [0, 1, 0, 0, 0, 0, 0, 0, 0, 1]}
temp_dir = tempfile.mkdtemp()
temp_fn = os.path.join(temp_dir, 'modelcode.stan')
with io.open(temp_fn, 'wt') as outfile:
outfile.write(bernoulli_model_code)
code = stanc(file=temp_fn)['model_code']
fit = stan(model_code=code, data=bernoulli_data)
extr = fit.extract(permuted=True)
assert -7.9 < np.mean(extr['lp__']) < -7.0
assert 0.1 < np.mean(extr['theta']) < 0.4
assert 0.01 < np.var(extr['theta']) < 0.02
# permuted=False
extr = fit.extract(permuted=False)
assert extr.shape == (1000, 4, 2)
assert 0.1 < np.mean(extr[:, 0, 0]) < 0.4
# permuted=True
extr = fit.extract('lp__', permuted=True)
assert -7.9 < np.mean(extr['lp__']) < -7.0
extr = fit.extract('theta', permuted=True)
assert 0.1 < np.mean(extr['theta']) < 0.4
assert 0.01 < np.var(extr['theta']) < 0.02
extr = fit.extract('theta', permuted=False)
assert extr['theta'].shape == (1000, 4)
assert 0.1 < np.mean(extr['theta'][:, 0]) < 0.4
fit = stan(file=temp_fn, data=bernoulli_data)
extr = fit.extract(permuted=True)
assert -7.9 < np.mean(extr['lp__']) < -7.0
assert 0.1 < np.mean(extr['theta']) < 0.4
assert 0.01 < np.var(extr['theta']) < 0.02
# permuted=False
extr = fit.extract(permuted=False)
assert extr.shape == (1000, 4, 2)
assert 0.1 < np.mean(extr[:, 0, 0]) < 0.4
# permuted=True
extr = fit.extract('lp__', permuted=True)
assert -7.9 < np.mean(extr['lp__']) < -7.0
extr = fit.extract('theta', permuted=True)
assert 0.1 < np.mean(extr['theta']) < 0.4
assert 0.01 < np.var(extr['theta']) < 0.02
extr = fit.extract('theta', permuted=False)
assert extr['theta'].shape == (1000, 4)
assert 0.1 < np.mean(extr['theta'][:, 0]) < 0.4
os.remove(temp_fn)
| [
"numpy.mean",
"pystan.stanc",
"os.path.join",
"io.open",
"pystan.stan",
"tempfile.mkdtemp",
"numpy.var",
"os.remove"
] | [((698, 716), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), '()\n', (714, 716), False, 'import tempfile\n'), ((735, 775), 'os.path.join', 'os.path.join', (['temp_dir', '"""modelcode.stan"""'], {}), "(temp_dir, 'modelcode.stan')\n", (747, 775), False, 'import os\n'), ((936, 978), 'pystan.stan', 'stan', ([], {'model_code': 'code', 'data': 'bernoulli_data'}), '(model_code=code, data=bernoulli_data)\n', (940, 978), False, 'from pystan import stan, stanc\n'), ((1783, 1822), 'pystan.stan', 'stan', ([], {'file': 'temp_fn', 'data': 'bernoulli_data'}), '(file=temp_fn, data=bernoulli_data)\n', (1787, 1822), False, 'from pystan import stan, stanc\n'), ((2621, 2639), 'os.remove', 'os.remove', (['temp_fn'], {}), '(temp_fn)\n', (2630, 2639), False, 'import os\n'), ((789, 811), 'io.open', 'io.open', (['temp_fn', '"""wt"""'], {}), "(temp_fn, 'wt')\n", (796, 811), False, 'import io\n'), ((888, 907), 'pystan.stanc', 'stanc', ([], {'file': 'temp_fn'}), '(file=temp_fn)\n', (893, 907), False, 'from pystan import stan, stanc\n'), ((1043, 1064), 'numpy.mean', 'np.mean', (["extr['lp__']"], {}), "(extr['lp__'])\n", (1050, 1064), True, 'import numpy as np\n'), ((1093, 1115), 'numpy.mean', 'np.mean', (["extr['theta']"], {}), "(extr['theta'])\n", (1100, 1115), True, 'import numpy as np\n'), ((1144, 1165), 'numpy.var', 'np.var', (["extr['theta']"], {}), "(extr['theta'])\n", (1150, 1165), True, 'import numpy as np\n'), ((1305, 1327), 'numpy.mean', 'np.mean', (['extr[:, 0, 0]'], {}), '(extr[:, 0, 0])\n', (1312, 1327), True, 'import numpy as np\n'), ((1431, 1452), 'numpy.mean', 'np.mean', (["extr['lp__']"], {}), "(extr['lp__'])\n", (1438, 1452), True, 'import numpy as np\n'), ((1532, 1554), 'numpy.mean', 'np.mean', (["extr['theta']"], {}), "(extr['theta'])\n", (1539, 1554), True, 'import numpy as np\n'), ((1583, 1604), 'numpy.var', 'np.var', (["extr['theta']"], {}), "(extr['theta'])\n", (1589, 1604), True, 'import numpy as np\n'), ((1733, 1761), 'numpy.mean', 'np.mean', (["extr['theta'][:, 0]"], {}), "(extr['theta'][:, 0])\n", (1740, 1761), True, 'import numpy as np\n'), ((1887, 1908), 'numpy.mean', 'np.mean', (["extr['lp__']"], {}), "(extr['lp__'])\n", (1894, 1908), True, 'import numpy as np\n'), ((1937, 1959), 'numpy.mean', 'np.mean', (["extr['theta']"], {}), "(extr['theta'])\n", (1944, 1959), True, 'import numpy as np\n'), ((1988, 2009), 'numpy.var', 'np.var', (["extr['theta']"], {}), "(extr['theta'])\n", (1994, 2009), True, 'import numpy as np\n'), ((2149, 2171), 'numpy.mean', 'np.mean', (['extr[:, 0, 0]'], {}), '(extr[:, 0, 0])\n', (2156, 2171), True, 'import numpy as np\n'), ((2275, 2296), 'numpy.mean', 'np.mean', (["extr['lp__']"], {}), "(extr['lp__'])\n", (2282, 2296), True, 'import numpy as np\n'), ((2376, 2398), 'numpy.mean', 'np.mean', (["extr['theta']"], {}), "(extr['theta'])\n", (2383, 2398), True, 'import numpy as np\n'), ((2427, 2448), 'numpy.var', 'np.var', (["extr['theta']"], {}), "(extr['theta'])\n", (2433, 2448), True, 'import numpy as np\n'), ((2577, 2605), 'numpy.mean', 'np.mean', (["extr['theta'][:, 0]"], {}), "(extr['theta'][:, 0])\n", (2584, 2605), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 26 15:55:37 2017
@author: Administrator
"""
import numpy as np#使用import导入模块numpy
import matplotlib.pyplot as plt#使用import导入模块matplotlib.pyplot
import plotly as py # 导入plotly库并命名为py
# -------------pre def
pympl = py.offline.plot_mpl
# 配置中文显示
plt.rcParams['font.family'] = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
fig, ax = plt.subplots()
#产生测试数据
x = np.arange(1,30)
y =np.sin(x)
ax1 = fig.add_subplot(111)
#设置标题
ax1.set_title('散点图')
#设置X轴标签
plt.xlabel('X')
#设置Y轴标签
plt.ylabel('Y')
#画散点图
lValue = x
ax1.scatter(x,y,c='r',s= 100,linewidths=lValue,marker='o')
#设置图标
plt.legend('x1')
plot_url = pympl(fig,filename=r'tmp/scatter_1.html', show_link=False,resize=True) | [
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.xlabel",
"numpy.sin",
"matplotlib.pyplot.subplots",
"numpy.arange"
] | [((411, 425), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (423, 425), True, 'import matplotlib.pyplot as plt\n'), ((438, 454), 'numpy.arange', 'np.arange', (['(1)', '(30)'], {}), '(1, 30)\n', (447, 454), True, 'import numpy as np\n'), ((457, 466), 'numpy.sin', 'np.sin', (['x'], {}), '(x)\n', (463, 466), True, 'import numpy as np\n'), ((529, 544), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""X"""'], {}), "('X')\n", (539, 544), True, 'import matplotlib.pyplot as plt\n'), ((553, 568), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Y"""'], {}), "('Y')\n", (563, 568), True, 'import matplotlib.pyplot as plt\n'), ((651, 667), 'matplotlib.pyplot.legend', 'plt.legend', (['"""x1"""'], {}), "('x1')\n", (661, 667), True, 'import matplotlib.pyplot as plt\n')] |
import matplotlib
import matplotlib.pyplot as plt
import os
import numpy as np
import torch
import torch.nn.functional as F
from configs.Config_chd import get_config
from utilities.file_and_folder_operations import subfiles
def reshape_array(numpy_array, axis=1):
image_shape = numpy_array.shape[1]
channel = numpy_array.shape[0]
if axis == 1:
slice_img = numpy_array[:, 0, :, :].reshape(1, channel, image_shape, image_shape)
slice_len = np.shape(numpy_array)[1]
for k in range(1, slice_len):
slice_array = numpy_array[:, k, :, :].reshape(1, channel, image_shape, image_shape)
slice_img = np.concatenate((slice_img, slice_array))
return slice_img
elif axis == 2:
slice_img = numpy_array[:, :, 0, :].reshape(1, channel, image_shape, image_shape)
slice_len = np.shape(numpy_array)[2]
for k in range(1, slice_len):
slice_array = numpy_array[:, :, k, :].reshape(1, channel, image_shape, image_shape)
slice_img = np.concatenate((slice_img, slice_array))
return slice_img
elif axis == 3:
slice_img = numpy_array[:, :, :, 0].reshape(1, channel, image_shape, image_shape)
slice_len = np.shape(numpy_array)[3]
for k in range(1, slice_len):
slice_array = numpy_array[:, :, :, k].reshape(1, channel, image_shape, image_shape)
slice_img = np.concatenate((slice_img, slice_array))
return slice_img
if __name__ == '__main__':
c = get_config()
"""
data_dir = c.data_dir
image_num = '1016'
scaled_image_dir = os.path.join(c.data_dir, 'scaled_to_16')
scaled_image = os.path.join(c.data_dir, 'ct_1083_image.npy')
train_image = np.load(scaled_image)
label_image = np.load(scaled_image)[:, 1]
max_value = label_image.max()
plt.imshow(train_image[12], cmap='gray')
plt.show()
plt.imshow(val_image[12], cmap='gray')
plt.show()
pred_dir = os.path.join(c.base_dir, c.dataset_name
+ '_' + str(
c.batch_size) + c.cross_vali_result_all_dir + '_20190425-213808')
test_num = c.dataset_name + '_006'
image_dir = os.path.join(pred_dir, 'results', 'pred_' + test_num + '.npy')
# all_image = np.load(image_dir)[25]
plt.figure(1)
for i in range(np.shape(all_image)[0]):
plt.subplot(1,3,i+1)
plt.imshow(train_image[i], cmap='gray')
if i == 0:
plt.xlabel('original image')
elif i == 1:
plt.xlabel('label image')
else:
plt.xlabel('segmented image')
if not os.path.exists(os.path.join(pred_dir, 'images')):
os.makedirs(os.path.join(pred_dir, 'images'))
plt.savefig(os.path.join(pred_dir, 'images') + '/_006_25.jpg')
plt.show()
"""
n = 4
k = 115
scaled_16_files = subfiles(c.scaled_image_16_dir, suffix='.npy', join=False)
pred_32_files = subfiles(c.stage_1_dir_32, suffix='64.npy', join=False)
org_files = subfiles(c.data_dir, suffix='.npy', join=False)
############ original image and target ########################
file = org_files[2]
data = np.load(os.path.join(c.data_dir, file))
data = reshape_array(data, axis=3)
image = data[:, 0]
target = data[:, 1]
############ down scale using interpolation ########################
data = torch.tensor(data)
data_256 = F.interpolate(data, scale_factor=1/16, mode='bilinear')
image_256 = data_256[:, 0]
target_256 = data_256[:, 1]
plt.figure(1)
plt.subplot(2, 2, 1)
plt.title('image:%d, slice:%d, original image' % (n, k))
plt.imshow(image[k], cmap='gray')
plt.subplot(2, 2, 2)
plt.title('image:%d, slice:%d, original target' % (n, k))
plt.imshow(target[k], cmap='gray')
plt.subplot(2, 2, 3)
plt.title('image:%d, slice:%d, image scale by 0.5' % (n, k))
plt.imshow(image_256[k], cmap='gray')
plt.subplot(2, 2, 4)
plt.title('image:%d, slice:%d, target scale by 0.5' % (n, k))
plt.imshow(target_256[k], cmap='gray')
plt.show()
############ down scale using max-pooling ########################
file_64 = pred_32_files[n]
pred_64 = np.load(os.path.join(c.stage_1_dir_32, file_64))[:, 0:8]
target_64 = np.load(os.path.join(c.stage_1_dir_32, file_64))[:, 8:9]
pred_64 = torch.tensor(pred_64).float()
target_64 = torch.tensor(target_64).long()
# 32*32 image and target
data_32 = np.load(os.path.join(c.scaled_image_32_dir, 'ct_1010_image.npy'))
image_32 = data_32[:, 0]
target_32 = data_32[:, 1]
soft_max = F.softmax(pred_64[k:k + 1], dim=1)
cf_img = torch.max(soft_max, 1)[0].numpy()
pred_img = torch.argmax(soft_max, dim=1)
# plot target
plt.figure(2)
plt.subplot(2, 2, 1)
plt.title('image:%d, slice:%d, confidence' % (n, k))
plt.imshow(cf_img[0], cmap='gray')
plt.subplot(2, 2, 2)
plt.title('image:%d, slice:%d, target' % (n, k))
plt.imshow(target_64[k][0], cmap='gray')
plt.subplot(2, 2, 3)
plt.title('image:%d, slice:%d, pred_image' % (n, k))
plt.imshow(pred_img[0], cmap='gray')
plt.show()
plt.figure(3)
plt.subplot(1, 2, 1)
plt.title('image:%d, slice:%d, original image' % (n, k))
plt.imshow(image_32[k], cmap='gray')
plt.subplot(1, 2, 2)
plt.title('image:%d, slice:%d, original target' % (n, k))
plt.imshow(target_32[k], cmap='gray')
plt.show()
| [
"matplotlib.pyplot.imshow",
"utilities.file_and_folder_operations.subfiles",
"torch.max",
"os.path.join",
"torch.argmax",
"torch.tensor",
"matplotlib.pyplot.figure",
"configs.Config_chd.get_config",
"torch.nn.functional.interpolate",
"numpy.concatenate",
"matplotlib.pyplot.title",
"numpy.shape... | [((1511, 1523), 'configs.Config_chd.get_config', 'get_config', ([], {}), '()\n', (1521, 1523), False, 'from configs.Config_chd import get_config\n'), ((2877, 2935), 'utilities.file_and_folder_operations.subfiles', 'subfiles', (['c.scaled_image_16_dir'], {'suffix': '""".npy"""', 'join': '(False)'}), "(c.scaled_image_16_dir, suffix='.npy', join=False)\n", (2885, 2935), False, 'from utilities.file_and_folder_operations import subfiles\n'), ((2956, 3011), 'utilities.file_and_folder_operations.subfiles', 'subfiles', (['c.stage_1_dir_32'], {'suffix': '"""64.npy"""', 'join': '(False)'}), "(c.stage_1_dir_32, suffix='64.npy', join=False)\n", (2964, 3011), False, 'from utilities.file_and_folder_operations import subfiles\n'), ((3028, 3075), 'utilities.file_and_folder_operations.subfiles', 'subfiles', (['c.data_dir'], {'suffix': '""".npy"""', 'join': '(False)'}), "(c.data_dir, suffix='.npy', join=False)\n", (3036, 3075), False, 'from utilities.file_and_folder_operations import subfiles\n'), ((3392, 3410), 'torch.tensor', 'torch.tensor', (['data'], {}), '(data)\n', (3404, 3410), False, 'import torch\n'), ((3426, 3483), 'torch.nn.functional.interpolate', 'F.interpolate', (['data'], {'scale_factor': '(1 / 16)', 'mode': '"""bilinear"""'}), "(data, scale_factor=1 / 16, mode='bilinear')\n", (3439, 3483), True, 'import torch.nn.functional as F\n'), ((3554, 3567), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {}), '(1)\n', (3564, 3567), True, 'import matplotlib.pyplot as plt\n'), ((3572, 3592), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(2)', '(1)'], {}), '(2, 2, 1)\n', (3583, 3592), True, 'import matplotlib.pyplot as plt\n'), ((3597, 3654), 'matplotlib.pyplot.title', 'plt.title', (["('image:%d, slice:%d, original image' % (n, k))"], {}), "('image:%d, slice:%d, original image' % (n, k))\n", (3606, 3654), True, 'import matplotlib.pyplot as plt\n'), ((3659, 3692), 'matplotlib.pyplot.imshow', 'plt.imshow', (['image[k]'], {'cmap': '"""gray"""'}), "(image[k], cmap='gray')\n", (3669, 3692), True, 'import matplotlib.pyplot as plt\n'), ((3697, 3717), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(2)', '(2)'], {}), '(2, 2, 2)\n', (3708, 3717), True, 'import matplotlib.pyplot as plt\n'), ((3722, 3780), 'matplotlib.pyplot.title', 'plt.title', (["('image:%d, slice:%d, original target' % (n, k))"], {}), "('image:%d, slice:%d, original target' % (n, k))\n", (3731, 3780), True, 'import matplotlib.pyplot as plt\n'), ((3785, 3819), 'matplotlib.pyplot.imshow', 'plt.imshow', (['target[k]'], {'cmap': '"""gray"""'}), "(target[k], cmap='gray')\n", (3795, 3819), True, 'import matplotlib.pyplot as plt\n'), ((3824, 3844), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(2)', '(3)'], {}), '(2, 2, 3)\n', (3835, 3844), True, 'import matplotlib.pyplot as plt\n'), ((3849, 3910), 'matplotlib.pyplot.title', 'plt.title', (["('image:%d, slice:%d, image scale by 0.5' % (n, k))"], {}), "('image:%d, slice:%d, image scale by 0.5' % (n, k))\n", (3858, 3910), True, 'import matplotlib.pyplot as plt\n'), ((3915, 3952), 'matplotlib.pyplot.imshow', 'plt.imshow', (['image_256[k]'], {'cmap': '"""gray"""'}), "(image_256[k], cmap='gray')\n", (3925, 3952), True, 'import matplotlib.pyplot as plt\n'), ((3957, 3977), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(2)', '(4)'], {}), '(2, 2, 4)\n', (3968, 3977), True, 'import matplotlib.pyplot as plt\n'), ((3982, 4044), 'matplotlib.pyplot.title', 'plt.title', (["('image:%d, slice:%d, target scale by 0.5' % (n, k))"], {}), "('image:%d, slice:%d, target scale by 0.5' % (n, k))\n", (3991, 4044), True, 'import matplotlib.pyplot as plt\n'), ((4049, 4087), 'matplotlib.pyplot.imshow', 'plt.imshow', (['target_256[k]'], {'cmap': '"""gray"""'}), "(target_256[k], cmap='gray')\n", (4059, 4087), True, 'import matplotlib.pyplot as plt\n'), ((4092, 4102), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4100, 4102), True, 'import matplotlib.pyplot as plt\n'), ((4627, 4661), 'torch.nn.functional.softmax', 'F.softmax', (['pred_64[k:k + 1]'], {'dim': '(1)'}), '(pred_64[k:k + 1], dim=1)\n', (4636, 4661), True, 'import torch.nn.functional as F\n'), ((4724, 4753), 'torch.argmax', 'torch.argmax', (['soft_max'], {'dim': '(1)'}), '(soft_max, dim=1)\n', (4736, 4753), False, 'import torch\n'), ((4777, 4790), 'matplotlib.pyplot.figure', 'plt.figure', (['(2)'], {}), '(2)\n', (4787, 4790), True, 'import matplotlib.pyplot as plt\n'), ((4795, 4815), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(2)', '(1)'], {}), '(2, 2, 1)\n', (4806, 4815), True, 'import matplotlib.pyplot as plt\n'), ((4820, 4873), 'matplotlib.pyplot.title', 'plt.title', (["('image:%d, slice:%d, confidence' % (n, k))"], {}), "('image:%d, slice:%d, confidence' % (n, k))\n", (4829, 4873), True, 'import matplotlib.pyplot as plt\n'), ((4878, 4912), 'matplotlib.pyplot.imshow', 'plt.imshow', (['cf_img[0]'], {'cmap': '"""gray"""'}), "(cf_img[0], cmap='gray')\n", (4888, 4912), True, 'import matplotlib.pyplot as plt\n'), ((4917, 4937), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(2)', '(2)'], {}), '(2, 2, 2)\n', (4928, 4937), True, 'import matplotlib.pyplot as plt\n'), ((4942, 4991), 'matplotlib.pyplot.title', 'plt.title', (["('image:%d, slice:%d, target' % (n, k))"], {}), "('image:%d, slice:%d, target' % (n, k))\n", (4951, 4991), True, 'import matplotlib.pyplot as plt\n'), ((4996, 5036), 'matplotlib.pyplot.imshow', 'plt.imshow', (['target_64[k][0]'], {'cmap': '"""gray"""'}), "(target_64[k][0], cmap='gray')\n", (5006, 5036), True, 'import matplotlib.pyplot as plt\n'), ((5041, 5061), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(2)', '(2)', '(3)'], {}), '(2, 2, 3)\n', (5052, 5061), True, 'import matplotlib.pyplot as plt\n'), ((5066, 5119), 'matplotlib.pyplot.title', 'plt.title', (["('image:%d, slice:%d, pred_image' % (n, k))"], {}), "('image:%d, slice:%d, pred_image' % (n, k))\n", (5075, 5119), True, 'import matplotlib.pyplot as plt\n'), ((5124, 5160), 'matplotlib.pyplot.imshow', 'plt.imshow', (['pred_img[0]'], {'cmap': '"""gray"""'}), "(pred_img[0], cmap='gray')\n", (5134, 5160), True, 'import matplotlib.pyplot as plt\n'), ((5165, 5175), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5173, 5175), True, 'import matplotlib.pyplot as plt\n'), ((5181, 5194), 'matplotlib.pyplot.figure', 'plt.figure', (['(3)'], {}), '(3)\n', (5191, 5194), True, 'import matplotlib.pyplot as plt\n'), ((5199, 5219), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(2)', '(1)'], {}), '(1, 2, 1)\n', (5210, 5219), True, 'import matplotlib.pyplot as plt\n'), ((5224, 5281), 'matplotlib.pyplot.title', 'plt.title', (["('image:%d, slice:%d, original image' % (n, k))"], {}), "('image:%d, slice:%d, original image' % (n, k))\n", (5233, 5281), True, 'import matplotlib.pyplot as plt\n'), ((5286, 5322), 'matplotlib.pyplot.imshow', 'plt.imshow', (['image_32[k]'], {'cmap': '"""gray"""'}), "(image_32[k], cmap='gray')\n", (5296, 5322), True, 'import matplotlib.pyplot as plt\n'), ((5327, 5347), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(2)', '(2)'], {}), '(1, 2, 2)\n', (5338, 5347), True, 'import matplotlib.pyplot as plt\n'), ((5352, 5410), 'matplotlib.pyplot.title', 'plt.title', (["('image:%d, slice:%d, original target' % (n, k))"], {}), "('image:%d, slice:%d, original target' % (n, k))\n", (5361, 5410), True, 'import matplotlib.pyplot as plt\n'), ((5415, 5452), 'matplotlib.pyplot.imshow', 'plt.imshow', (['target_32[k]'], {'cmap': '"""gray"""'}), "(target_32[k], cmap='gray')\n", (5425, 5452), True, 'import matplotlib.pyplot as plt\n'), ((5457, 5467), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5465, 5467), True, 'import matplotlib.pyplot as plt\n'), ((3188, 3218), 'os.path.join', 'os.path.join', (['c.data_dir', 'file'], {}), '(c.data_dir, file)\n', (3200, 3218), False, 'import os\n'), ((4494, 4550), 'os.path.join', 'os.path.join', (['c.scaled_image_32_dir', '"""ct_1010_image.npy"""'], {}), "(c.scaled_image_32_dir, 'ct_1010_image.npy')\n", (4506, 4550), False, 'import os\n'), ((468, 489), 'numpy.shape', 'np.shape', (['numpy_array'], {}), '(numpy_array)\n', (476, 489), True, 'import numpy as np\n'), ((651, 691), 'numpy.concatenate', 'np.concatenate', (['(slice_img, slice_array)'], {}), '((slice_img, slice_array))\n', (665, 691), True, 'import numpy as np\n'), ((4228, 4267), 'os.path.join', 'os.path.join', (['c.stage_1_dir_32', 'file_64'], {}), '(c.stage_1_dir_32, file_64)\n', (4240, 4267), False, 'import os\n'), ((4301, 4340), 'os.path.join', 'os.path.join', (['c.stage_1_dir_32', 'file_64'], {}), '(c.stage_1_dir_32, file_64)\n', (4313, 4340), False, 'import os\n'), ((4365, 4386), 'torch.tensor', 'torch.tensor', (['pred_64'], {}), '(pred_64)\n', (4377, 4386), False, 'import torch\n'), ((4411, 4434), 'torch.tensor', 'torch.tensor', (['target_64'], {}), '(target_64)\n', (4423, 4434), False, 'import torch\n'), ((847, 868), 'numpy.shape', 'np.shape', (['numpy_array'], {}), '(numpy_array)\n', (855, 868), True, 'import numpy as np\n'), ((1030, 1070), 'numpy.concatenate', 'np.concatenate', (['(slice_img, slice_array)'], {}), '((slice_img, slice_array))\n', (1044, 1070), True, 'import numpy as np\n'), ((4675, 4697), 'torch.max', 'torch.max', (['soft_max', '(1)'], {}), '(soft_max, 1)\n', (4684, 4697), False, 'import torch\n'), ((1226, 1247), 'numpy.shape', 'np.shape', (['numpy_array'], {}), '(numpy_array)\n', (1234, 1247), True, 'import numpy as np\n'), ((1409, 1449), 'numpy.concatenate', 'np.concatenate', (['(slice_img, slice_array)'], {}), '((slice_img, slice_array))\n', (1423, 1449), 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.
# ==============================================================================
"""Runs a ResNet model on the ImageNet dataset."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from functools import partial
from functools import wraps
import argparse
import sys
import numpy as np
import math
import functools
import os
import shutil
import tensorflow as tf
from official.resnet import resnet_run_loop
from official.resnet import imagenet_main
from official.resnet import imagenet_preprocessing
_NUM_IMAGES = {
'train': 1281167,
'validation': 50000,
}
_NUM_TRAIN_FILES = 1024
_SHUFFLE_BUFFER = 1500
sys.path.append('/work/generalisation-humans-DNNs/code/accuracy_evaluation/')
import imagenet_16
# sys.path.append('./object-recognition-combined/code/')
import image_manipulation
# import additional_image_manipulations
import image_manipulation as additional_image_manipulations
def as_perturbation_fn(f):
@wraps(f)
def wrapper(image):
assert image.shape == (224, 224, 3)
assert image.dtype == np.float32
perturbed = f(image)
assert perturbed.dtype in [np.float32, np.float64]
if perturbed.ndim == 2:
perturbed = perturbed[..., np.newaxis].repeat(3, axis=2)
assert image.shape == perturbed.shape
if perturbed.dtype == np.float64:
perturbed = perturbed.astype(np.float32)
return perturbed
return wrapper
def uniform_noise_multiple(x, rng=np.random.RandomState()):
levels = np.array([0.00, 0.03, 0.05, 0.10, 0.20, 0.35, 0.60, 0.90])
width = rng.choice(levels)
return image_manipulation.uniform_noise(
x, width=width, contrast_level=0.3, rng=rng)
def salt_and_pepper_noise_multiple(x, rng=np.random.RandomState()):
levels = np.array([0.0, 0.1, 0.2, 0.35, 0.5, 0.65, 0.8, 0.95])
p = rng.choice(levels)
return additional_image_manipulations.salt_and_pepper_noise(
x, p=p, contrast_level=0.3, rng=rng)
def salt_and_pepper_noise_multiple__uniform_noise_multiple(
x, rng=np.random.RandomState()):
type_ = rng.randint(2)
if type_ == 0:
return salt_and_pepper_noise_multiple(x)
elif type_ == 1:
return uniform_noise_multiple(x)
assert False
def uniform_noise_multiple_partial(x, rng=np.random.RandomState()):
levels = np.array([0.00, 0.03, 0.05, 0.10, 0.20, 0.35])
width = rng.choice(levels)
return image_manipulation.uniform_noise(
x, width=width, contrast_level=0.3, rng=rng)
def uniform_noise_all(x, rng=np.random.RandomState()):
width = rng.uniform(0.0, 0.9)
return image_manipulation.uniform_noise(
x, width=width, contrast_level=0.3, rng=rng)
def color__uniform_noise_multiple(x, rng=np.random.RandomState()):
color = rng.uniform() < 0.5
if color:
return x
else:
return uniform_noise_multiple(x, rng=rng)
def color__grayscale(x, rng=np.random.RandomState()):
color = rng.uniform() < 0.5
if color:
return x
else:
return image_manipulation.rgb2gray(x)
def color__grayscale_contrast_multiple__uniform_noise_multiple(
x, rng=np.random.RandomState()):
type_ = rng.randint(3)
if type_ == 0:
return x
elif type_ == 1:
return grayscale_contrast_multiple(x)
elif type_ == 2:
return uniform_noise_multiple(x)
assert False
def grayscale_contrast_multiple(x, rng=np.random.RandomState()):
levels = np.array([1.0, 0.5, 0.3, 0.15, 0.1, 0.05, 0.03, 0.01])
level = rng.choice(levels)
return image_manipulation.grayscale_contrast(
x, contrast_level=level)
def low_pass_multiple(x, rng=np.random.RandomState()):
levels = np.array([0, 1, 3, 5, 7, 10, 15, 40])
level = rng.choice(levels)
return image_manipulation.low_pass_filter(
x, std=level)
def high_pass_multiple(x, rng=np.random.RandomState()):
levels = np.array([np.inf, 3., 1.5, 1., 0.7, 0.55, 0.45, 0.4])
level = rng.choice(levels)
if level == np.inf:
return image_manipulation.rgb2gray(x)
else:
return image_manipulation.high_pass_filter(
x, std=level)
def rotation_multiple(x, rng=np.random.RandomState()):
angles = np.array([0, 90, 180, 270])
angle = rng.choice(angles)
if angle == 0:
return x
elif angle == 90:
return image_manipulation.rotate90(x)
elif angle == 180:
return image_manipulation.rotate180(x)
elif angle == 270:
return image_manipulation.rotate270(x)
def color__grayscale_contrast__high_pass__low_pass__rotation__uniform_noise(
x, rng=np.random.RandomState()):
type_ = rng.randint(6)
if type_ == 0:
return x
elif type_ == 1:
return grayscale_contrast_multiple(x)
elif type_ == 2:
return high_pass_multiple(x)
elif type_ == 3:
return low_pass_multiple(x)
elif type_ == 4:
return rotation_multiple(x)
elif type_ == 5:
return uniform_noise_multiple(x)
assert False
def color__grayscale_contrast__high_pass__low_pass__rotation__salt_and_pepper_noise( # noqa: E501
x, rng=np.random.RandomState()):
type_ = rng.randint(6)
if type_ == 0:
return x
elif type_ == 1:
return grayscale_contrast_multiple(x)
elif type_ == 2:
return high_pass_multiple(x)
elif type_ == 3:
return low_pass_multiple(x)
elif type_ == 4:
return rotation_multiple(x)
elif type_ == 5:
return salt_and_pepper_noise_multiple(x)
assert False
def color__grayscale_contrast__high_pass__low_pass__rotation__phase_scrambling__uniform_noise( # noqa: E501
x, rng=np.random.RandomState()):
type_ = rng.randint(7)
if type_ == 0:
return x
elif type_ == 1:
return grayscale_contrast_multiple(x)
elif type_ == 2:
return high_pass_multiple(x)
elif type_ == 3:
return low_pass_multiple(x)
elif type_ == 4:
return rotation_multiple(x)
elif type_ == 5:
return phase_scrambling_multiple(x)
elif type_ == 6:
return uniform_noise_multiple(x)
assert False
def color__grayscale_contrast__high_pass__low_pass__rotation__phase_scrambling__salt_and_pepper_noise( # noqa: E501
x, rng=np.random.RandomState()):
type_ = rng.randint(7)
if type_ == 0:
return x
elif type_ == 1:
return grayscale_contrast_multiple(x)
elif type_ == 2:
return high_pass_multiple(x)
elif type_ == 3:
return low_pass_multiple(x)
elif type_ == 4:
return rotation_multiple(x)
elif type_ == 5:
return phase_scrambling_multiple(x)
elif type_ == 6:
return salt_and_pepper_noise_multiple(x)
assert False
def eidolon_reach_multiple_coherence_1(x, rng=np.random.RandomState()):
assert False, 'needs eidolon package plus bugfix; but py2 only?'
reach_levels = np.array([1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0, 128.0])
reach = rng.choice(reach_levels)
coherence = 1.
grain = 10.
return image_manipulation.eidolon_partially_coherent_disarray(
x, reach, coherence, grain)
def phase_scrambling_multiple(x, rng=np.random.RandomState()):
levels = np.array([0., 30., 60., 90., 120., 150., 180.])
level = rng.choice(levels)
return image_manipulation.phase_scrambling(
x, width=level, rng=rng)
def placeholder__uniform_noise_multiple(
x, rng=np.random.RandomState(), placeholder=None):
type_ = rng.randint(2)
if type_ == 0:
return placeholder(x)
elif type_ == 1:
return uniform_noise_multiple(x)
assert False
def parse_record_and_perturb(perturbation, input_dropout, sixteen,
raw_record, is_training):
if sixteen:
features, label = imagenet_16.parse_record(raw_record, is_training)
image = features['image']
weight = features['weight']
else:
image, label = imagenet_main.parse_record(raw_record, is_training)
if perturbation is not None:
print(f'applying perturbation "{perturbation}"')
if perturbation == 'grayscale_contrast':
perturbation_fn = partial(
image_manipulation.grayscale_contrast,
contrast_level=0.3)
elif perturbation == 'uniform_noise':
perturbation_fn = partial(
image_manipulation.uniform_noise,
width=0.2, contrast_level=0.3, rng=np.random.RandomState())
elif perturbation == 'salt_and_pepper_noise':
perturbation_fn = partial(
additional_image_manipulations.salt_and_pepper_noise,
p=0.5, contrast_level=0.3, rng=np.random.RandomState())
elif perturbation == 'uniform_noise_multiple':
perturbation_fn = uniform_noise_multiple
elif perturbation == 'salt_and_pepper_noise_multiple':
perturbation_fn = salt_and_pepper_noise_multiple
elif perturbation == 'uniform_noise_multiple_partial':
perturbation_fn = uniform_noise_multiple_partial
elif perturbation == 'uniform_noise_all':
perturbation_fn = uniform_noise_all
elif perturbation == 'grayscale':
perturbation_fn = image_manipulation.rgb2gray
elif perturbation == 'color__grayscale':
perturbation_fn = color__grayscale
elif perturbation == 'color__uniform_noise_multiple':
perturbation_fn = color__uniform_noise_multiple
elif perturbation == 'grayscale_contrast_multiple':
perturbation_fn = grayscale_contrast_multiple
elif perturbation == 'low_pass_multiple':
perturbation_fn = low_pass_multiple
elif perturbation == 'high_pass_multiple':
perturbation_fn = high_pass_multiple
elif perturbation == 'rotation_multiple':
perturbation_fn = rotation_multiple
elif perturbation == 'phase_scrambling_multiple':
perturbation_fn = phase_scrambling_multiple
elif perturbation == 'salt_and_pepper_noise_multiple__uniform_noise_multiple': # noqa: E501
perturbation_fn = salt_and_pepper_noise_multiple__uniform_noise_multiple # noqa: E501
elif perturbation == 'color__grayscale_contrast_multiple__uniform_noise_multiple': # noqa: E501
perturbation_fn = color__grayscale_contrast_multiple__uniform_noise_multiple # noqa: E501
elif perturbation == 'color__grayscale_contrast__high_pass__low_pass__rotation__uniform_noise': # noqa: E501
perturbation_fn = color__grayscale_contrast__high_pass__low_pass__rotation__uniform_noise # noqa: E501
elif perturbation == 'color__grayscale_contrast__high_pass__low_pass__rotation__salt_and_pepper_noise': # noqa: E501
perturbation_fn = color__grayscale_contrast__high_pass__low_pass__rotation__salt_and_pepper_noise # noqa: E501
elif perturbation == 'color__grayscale_contrast__high_pass__low_pass__rotation__phase_scrambling__uniform_noise': # noqa: E501
perturbation_fn = color__grayscale_contrast__high_pass__low_pass__rotation__phase_scrambling__uniform_noise # noqa: E501
elif perturbation == 'color__grayscale_contrast__high_pass__low_pass__rotation__phase_scrambling__salt_and_pepper_noise': # noqa: E501
perturbation_fn = color__grayscale_contrast__high_pass__low_pass__rotation__phase_scrambling__salt_and_pepper_noise # noqa: E501
elif perturbation == 'grayscale__uniform_noise_multiple':
perturbation_fn = partial(
placeholder__uniform_noise_multiple,
placeholder=image_manipulation.rgb2gray)
elif perturbation == ('grayscale_contrast_multiple'
'__uniform_noise_multiple'):
perturbation_fn = partial(
placeholder__uniform_noise_multiple,
placeholder=grayscale_contrast_multiple)
elif perturbation == ('low_pass_multiple'
'__uniform_noise_multiple'):
perturbation_fn = partial(
placeholder__uniform_noise_multiple,
placeholder=low_pass_multiple)
elif perturbation == ('high_pass_multiple'
'__uniform_noise_multiple'):
perturbation_fn = partial(
placeholder__uniform_noise_multiple,
placeholder=high_pass_multiple)
elif perturbation == ('phase_scrambling_multiple'
'__uniform_noise_multiple'):
perturbation_fn = partial(
placeholder__uniform_noise_multiple,
placeholder=phase_scrambling_multiple)
elif perturbation == ('rotation_multiple'
'__uniform_noise_multiple'):
perturbation_fn = partial(
placeholder__uniform_noise_multiple,
placeholder=rotation_multiple)
else:
raise ValueError('unknown perturbation')
perturbation_fn = as_perturbation_fn(perturbation_fn)
num_channels = 3
channel_means = imagenet_preprocessing._CHANNEL_MEANS
neg_channel_means = [-x for x in channel_means]
image = imagenet_preprocessing._mean_image_subtraction(
image, neg_channel_means, num_channels)
image = image / 255.
shape = image.shape
image = tf.py_func(
perturbation_fn,
[image],
tf.float32,
stateful=False,
name=perturbation)
image.set_shape(shape)
image = image * 255.
image = imagenet_preprocessing._mean_image_subtraction(
image, channel_means, num_channels)
else:
print('finetuning on unperturbed images')
if input_dropout:
print('adding input dropout with keep_prob = 0.5')
image = tf.nn.dropout(image, 0.5, name='input_dropout')
if sixteen:
return {'image': image, 'weight': weight}, label
return image, label
def input_fn(perturbation, input_dropout, sixteen, is_training, data_dir,
batch_size, num_epochs=1, num_parallel_calls=1, multi_gpu=False):
"""Input function which provides batches for train or eval.
Args:
is_training: A boolean denoting whether the input is for training.
data_dir: The directory containing the input data.
batch_size: The number of samples per batch.
num_epochs: The number of epochs to repeat the dataset.
num_parallel_calls: The number of records that are processed in parallel.
This can be optimized per data set but for generally homogeneous data
sets, should be approximately the number of available CPU cores.
multi_gpu: Whether this is run multi-GPU. Note that this is only required
currently to handle the batch leftovers, and can be removed
when that is handled directly by Estimator.
Returns:
A dataset that can be used for iteration.
"""
filenames = imagenet_main.get_filenames(is_training, data_dir)
dataset = tf.data.Dataset.from_tensor_slices(filenames)
if is_training:
# Shuffle the input files
dataset = dataset.shuffle(buffer_size=_NUM_TRAIN_FILES)
num_images = is_training and _NUM_IMAGES['train'] or \
_NUM_IMAGES['validation']
# Convert to individual records
dataset = dataset.flat_map(tf.data.TFRecordDataset)
if sixteen:
process_record_dataset_fn = imagenet_16.process_record_dataset
else:
process_record_dataset_fn = resnet_run_loop.process_record_dataset
return process_record_dataset_fn(
dataset, is_training, batch_size, _SHUFFLE_BUFFER,
partial(parse_record_and_perturb,
perturbation, input_dropout, sixteen),
num_epochs, num_parallel_calls, examples_per_epoch=num_images,
multi_gpu=multi_gpu)
def imagenet_finetuning_model_fn(
features, labels, mode, params, boundaries, tempfix):
"""Our model_fn for ResNet to be used with our Estimator."""
# TODO: right now, the pretrained weights expect inputs to be divided
# by 255; I reported this and once new weights are available, I
# should use them and remove this code here;
# When training from scratch I won't do the downscaling
# because I already started without it and it should
# be removed from this later as well;
# right now that means they are incompatible
# UPDATE: it doesn't have much off an effect at the training
# curves because in training mode, the scaling is mostly
# canceled out by batch norm anyway, and after some training
# or finetuning, the batch norm exp. averages will have adjusted
# so that it will also be fine during evaluation;
# maybe I shouldn't use the fix at all
# https://github.com/tensorflow/models/issues/3779
if tempfix:
features = features / 255
print('dividing pixel values by 255 as a temporary fix')
else:
print('not using temporary fix')
sys.stdout.flush()
pretrained_steps = 6085624 # corresponded to batch size 32
pretrained_steps_per_epoch_new = int(math.ceil(
_NUM_IMAGES['train'] / params['batch_size']))
pretrained_epochs_new = int(math.ceil(
pretrained_steps / pretrained_steps_per_epoch_new))
print('correcting learning rate boundaries by {} epochs'.format(
pretrained_epochs_new))
assert len(boundaries) <= 4
boundaries = [-1] * (4 - len(boundaries)) + boundaries
print('epoch boundaries for finetuning: {}'.format(boundaries))
boundaries = [pretrained_epochs_new + x for x in boundaries]
decay_rates = [1, 0.1, 0.01, 0.001, 1e-4]
learning_rate_fn = resnet_run_loop.learning_rate_with_decay(
batch_size=params['batch_size'], batch_denom=256,
num_images=_NUM_IMAGES['train'], boundary_epochs=boundaries,
decay_rates=decay_rates)
result = resnet_run_loop.resnet_model_fn(
features, labels, mode, imagenet_main.ImagenetModel,
resnet_size=params['resnet_size'],
weight_decay=1e-4,
learning_rate_fn=learning_rate_fn,
momentum=0.9,
data_format=params['data_format'],
version=params['version'],
loss_filter_fn=None,
multi_gpu=params['multi_gpu'])
def add_tensor_summary(name):
g = tf.get_default_graph()
t = g.get_tensor_by_name(name)
assert name[-2:] == ':0'
tf.summary.tensor_summary(name[:-2], t)
# added this for debugging / learning rate tweaking
add_tensor_summary('batch_normalization/moving_mean:0')
add_tensor_summary('batch_normalization/moving_variance:0')
add_tensor_summary('batch_normalization_48/moving_mean:0')
add_tensor_summary('batch_normalization_48/moving_variance:0')
return result
# from models.official.utils.arg_parsers import parsers
# class ResnetArgParser(argparse.ArgumentParser):
# """Arguments for configuring and running a Resnet Model."""
# def __init__(self, resnet_size_choices=None):
# super(ResnetArgParser, self).__init__(parents=[
# parsers.BaseParser(multi_gpu=False),
# parsers.PerformanceParser(num_parallel_calls=False),
# parsers.ImageModelParser(),
# parsers.ExportParser(),
# parsers.BenchmarkParser(),
# ])
# self.add_argument(
# '--version', '-v', type=int, choices=[1, 2],
# default=resnet_model.DEFAULT_VERSION,
# help='Version of ResNet. (1 or 2) See README.md for details.'
# )
# self.add_argument(
# '--resnet_size', '-rs', type=int, default=50,
# choices=resnet_size_choices,
# help='[default: %(default)s] The size of the ResNet model to use.',
# metavar='<RS>' if resnet_size_choices is None else None
# )
# def parse_args(self, args=None, namespace=None):
# args = super(ResnetArgParser, self).parse_args(
# args=args, namespace=namespace)
# # handle coupling between dtype and loss_scale
# parsers.parse_dtype_info(args)
# return args
class FinetuningArgParser(argparse.ArgumentParser):
"""Arguments for configuring and finetuning a Resnet Model.
"""
def __init__(self, resnet_size_choices=None):
super(FinetuningArgParser, self).__init__(parents=[
resnet_run_loop.ResnetArgParser(
resnet_size_choices=[18, 34, 50, 101, 152, 200])
# ResnetArgParser(resnet_size_choices=[18, 34, 50, 101, 152, 200])
# resnet_run_loop.define_resnet_flags(
# resnet_size_choices=['18', '34', '50', '101', '152', '200'])
], add_help=False)
self.add_argument('--perturbation', type=str, default=None)
self.add_argument('--from_scratch', action='store_true')
self.add_argument('--lr_boundaries', nargs='*', type=int)
self.add_argument('--sixteen', action='store_true')
self.add_argument('--input_dropout', action='store_true')
self.add_argument('--tempfix', action='store_true')
def main(argv):
# parser = FinetuningArgParser()
# flags = parser.parse_args(args=argv[1:])
from resnet_run_loop import flags
resnet_run_loop.define_resnet_flags(resnet_size_choices=['18', '34', '50', '101', '152', '200'])
print(flags)
perturbation = flags.perturbation
print('flags', flags)
sys.stdout.flush()
if flags.sixteen:
assert flags.from_scratch
if not os.path.exists(flags.model_dir):
if flags.from_scratch:
print('creating empty directory {}'.format(flags.model_dir))
os.mkdir(flags.model_dir)
else:
print('copying pretrained model to {}'.format(flags.model_dir))
shutil.copytree('./pretrained', flags.model_dir)
if flags.from_scratch:
# assert tf.train.latest_checkpoint(flags.model_dir) is None
if flags.sixteen:
if flags.lr_boundaries is None:
model_fn = functools.partial(
imagenet_16.imagenet_model_fn,
boundary_epochs=None)
else:
print('=' * 70)
assert len(flags.lr_boundaries) == 4
print('training from scratch with custom learning'
' rate boundaries: {}'.format(flags.lr_boundaries))
model_fn = functools.partial(
imagenet_16.imagenet_model_fn,
boundary_epochs=flags.lr_boundaries)
else:
assert flags.lr_boundaries is None
model_fn = imagenet_main.imagenet_model_fn
else:
assert tf.train.latest_checkpoint(flags.model_dir) is not None
model_fn = functools.partial(imagenet_finetuning_model_fn,
boundaries=flags.lr_boundaries,
tempfix=flags.tempfix)
input_function = flags.use_synthetic_data and \
imagenet_main.get_synth_input_fn() or \
partial(input_fn, perturbation, flags.input_dropout, flags.sixteen)
resnet_run_loop.resnet_main(
flags, model_fn, input_function)
if __name__ == '__main__':
tf.logging.set_verbosity(tf.logging.INFO)
tf.app.run(argv=sys.argv)
| [
"image_manipulation.rotate180",
"official.resnet.resnet_run_loop.resnet_model_fn",
"tensorflow.logging.set_verbosity",
"official.resnet.resnet_run_loop.ResnetArgParser",
"image_manipulation.rotate270",
"numpy.array",
"image_manipulation.grayscale_contrast",
"tensorflow.nn.dropout",
"sys.path.append"... | [((1288, 1365), 'sys.path.append', 'sys.path.append', (['"""/work/generalisation-humans-DNNs/code/accuracy_evaluation/"""'], {}), "('/work/generalisation-humans-DNNs/code/accuracy_evaluation/')\n", (1303, 1365), False, 'import sys\n'), ((1604, 1612), 'functools.wraps', 'wraps', (['f'], {}), '(f)\n', (1609, 1612), False, 'from functools import wraps\n'), ((2132, 2155), 'numpy.random.RandomState', 'np.random.RandomState', ([], {}), '()\n', (2153, 2155), True, 'import numpy as np\n'), ((2171, 2224), 'numpy.array', 'np.array', (['[0.0, 0.03, 0.05, 0.1, 0.2, 0.35, 0.6, 0.9]'], {}), '([0.0, 0.03, 0.05, 0.1, 0.2, 0.35, 0.6, 0.9])\n', (2179, 2224), True, 'import numpy as np\n'), ((2272, 2349), 'image_manipulation.uniform_noise', 'image_manipulation.uniform_noise', (['x'], {'width': 'width', 'contrast_level': '(0.3)', 'rng': 'rng'}), '(x, width=width, contrast_level=0.3, rng=rng)\n', (2304, 2349), False, 'import image_manipulation\n'), ((2403, 2426), 'numpy.random.RandomState', 'np.random.RandomState', ([], {}), '()\n', (2424, 2426), True, 'import numpy as np\n'), ((2442, 2495), 'numpy.array', 'np.array', (['[0.0, 0.1, 0.2, 0.35, 0.5, 0.65, 0.8, 0.95]'], {}), '([0.0, 0.1, 0.2, 0.35, 0.5, 0.65, 0.8, 0.95])\n', (2450, 2495), True, 'import numpy as np\n'), ((2534, 2628), 'image_manipulation.salt_and_pepper_noise', 'additional_image_manipulations.salt_and_pepper_noise', (['x'], {'p': 'p', 'contrast_level': '(0.3)', 'rng': 'rng'}), '(x, p=p, contrast_level\n =0.3, rng=rng)\n', (2586, 2628), True, 'import image_manipulation as additional_image_manipulations\n'), ((2710, 2733), 'numpy.random.RandomState', 'np.random.RandomState', ([], {}), '()\n', (2731, 2733), True, 'import numpy as np\n'), ((2954, 2977), 'numpy.random.RandomState', 'np.random.RandomState', ([], {}), '()\n', (2975, 2977), True, 'import numpy as np\n'), ((2993, 3036), 'numpy.array', 'np.array', (['[0.0, 0.03, 0.05, 0.1, 0.2, 0.35]'], {}), '([0.0, 0.03, 0.05, 0.1, 0.2, 0.35])\n', (3001, 3036), True, 'import numpy as np\n'), ((3082, 3159), 'image_manipulation.uniform_noise', 'image_manipulation.uniform_noise', (['x'], {'width': 'width', 'contrast_level': '(0.3)', 'rng': 'rng'}), '(x, width=width, contrast_level=0.3, rng=rng)\n', (3114, 3159), False, 'import image_manipulation\n'), ((3200, 3223), 'numpy.random.RandomState', 'np.random.RandomState', ([], {}), '()\n', (3221, 3223), True, 'import numpy as np\n'), ((3271, 3348), 'image_manipulation.uniform_noise', 'image_manipulation.uniform_noise', (['x'], {'width': 'width', 'contrast_level': '(0.3)', 'rng': 'rng'}), '(x, width=width, contrast_level=0.3, rng=rng)\n', (3303, 3348), False, 'import image_manipulation\n'), ((3401, 3424), 'numpy.random.RandomState', 'np.random.RandomState', ([], {}), '()\n', (3422, 3424), True, 'import numpy as np\n'), ((3580, 3603), 'numpy.random.RandomState', 'np.random.RandomState', ([], {}), '()\n', (3601, 3603), True, 'import numpy as np\n'), ((3806, 3829), 'numpy.random.RandomState', 'np.random.RandomState', ([], {}), '()\n', (3827, 3829), True, 'import numpy as np\n'), ((4082, 4105), 'numpy.random.RandomState', 'np.random.RandomState', ([], {}), '()\n', (4103, 4105), True, 'import numpy as np\n'), ((4121, 4175), 'numpy.array', 'np.array', (['[1.0, 0.5, 0.3, 0.15, 0.1, 0.05, 0.03, 0.01]'], {}), '([1.0, 0.5, 0.3, 0.15, 0.1, 0.05, 0.03, 0.01])\n', (4129, 4175), True, 'import numpy as np\n'), ((4218, 4280), 'image_manipulation.grayscale_contrast', 'image_manipulation.grayscale_contrast', (['x'], {'contrast_level': 'level'}), '(x, contrast_level=level)\n', (4255, 4280), False, 'import image_manipulation\n'), ((4321, 4344), 'numpy.random.RandomState', 'np.random.RandomState', ([], {}), '()\n', (4342, 4344), True, 'import numpy as np\n'), ((4360, 4397), 'numpy.array', 'np.array', (['[0, 1, 3, 5, 7, 10, 15, 40]'], {}), '([0, 1, 3, 5, 7, 10, 15, 40])\n', (4368, 4397), True, 'import numpy as np\n'), ((4440, 4488), 'image_manipulation.low_pass_filter', 'image_manipulation.low_pass_filter', (['x'], {'std': 'level'}), '(x, std=level)\n', (4474, 4488), False, 'import image_manipulation\n'), ((4530, 4553), 'numpy.random.RandomState', 'np.random.RandomState', ([], {}), '()\n', (4551, 4553), True, 'import numpy as np\n'), ((4569, 4624), 'numpy.array', 'np.array', (['[np.inf, 3.0, 1.5, 1.0, 0.7, 0.55, 0.45, 0.4]'], {}), '([np.inf, 3.0, 1.5, 1.0, 0.7, 0.55, 0.45, 0.4])\n', (4577, 4624), True, 'import numpy as np\n'), ((4843, 4866), 'numpy.random.RandomState', 'np.random.RandomState', ([], {}), '()\n', (4864, 4866), True, 'import numpy as np\n'), ((4882, 4909), 'numpy.array', 'np.array', (['[0, 90, 180, 270]'], {}), '([0, 90, 180, 270])\n', (4890, 4909), True, 'import numpy as np\n'), ((5279, 5302), 'numpy.random.RandomState', 'np.random.RandomState', ([], {}), '()\n', (5300, 5302), True, 'import numpy as np\n'), ((5802, 5825), 'numpy.random.RandomState', 'np.random.RandomState', ([], {}), '()\n', (5823, 5825), True, 'import numpy as np\n'), ((6343, 6366), 'numpy.random.RandomState', 'np.random.RandomState', ([], {}), '()\n', (6364, 6366), True, 'import numpy as np\n'), ((6949, 6972), 'numpy.random.RandomState', 'np.random.RandomState', ([], {}), '()\n', (6970, 6972), True, 'import numpy as np\n'), ((7477, 7500), 'numpy.random.RandomState', 'np.random.RandomState', ([], {}), '()\n', (7498, 7500), True, 'import numpy as np\n'), ((7592, 7647), 'numpy.array', 'np.array', (['[1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0, 128.0]'], {}), '([1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0, 128.0])\n', (7600, 7647), True, 'import numpy as np\n'), ((7731, 7817), 'image_manipulation.eidolon_partially_coherent_disarray', 'image_manipulation.eidolon_partially_coherent_disarray', (['x', 'reach', 'coherence', 'grain'], {}), '(x, reach, coherence,\n grain)\n', (7785, 7817), False, 'import image_manipulation\n'), ((7862, 7885), 'numpy.random.RandomState', 'np.random.RandomState', ([], {}), '()\n', (7883, 7885), True, 'import numpy as np\n'), ((7901, 7955), 'numpy.array', 'np.array', (['[0.0, 30.0, 60.0, 90.0, 120.0, 150.0, 180.0]'], {}), '([0.0, 30.0, 60.0, 90.0, 120.0, 150.0, 180.0])\n', (7909, 7955), True, 'import numpy as np\n'), ((7991, 8051), 'image_manipulation.phase_scrambling', 'image_manipulation.phase_scrambling', (['x'], {'width': 'level', 'rng': 'rng'}), '(x, width=level, rng=rng)\n', (8026, 8051), False, 'import image_manipulation\n'), ((8119, 8142), 'numpy.random.RandomState', 'np.random.RandomState', ([], {}), '()\n', (8140, 8142), True, 'import numpy as np\n'), ((15722, 15772), 'official.resnet.imagenet_main.get_filenames', 'imagenet_main.get_filenames', (['is_training', 'data_dir'], {}), '(is_training, data_dir)\n', (15749, 15772), False, 'from official.resnet import imagenet_main\n'), ((15787, 15832), 'tensorflow.data.Dataset.from_tensor_slices', 'tf.data.Dataset.from_tensor_slices', (['filenames'], {}), '(filenames)\n', (15821, 15832), True, 'import tensorflow as tf\n'), ((17751, 17769), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (17767, 17769), False, 'import sys\n'), ((18441, 18626), 'official.resnet.resnet_run_loop.learning_rate_with_decay', 'resnet_run_loop.learning_rate_with_decay', ([], {'batch_size': "params['batch_size']", 'batch_denom': '(256)', 'num_images': "_NUM_IMAGES['train']", 'boundary_epochs': 'boundaries', 'decay_rates': 'decay_rates'}), "(batch_size=params['batch_size'],\n batch_denom=256, num_images=_NUM_IMAGES['train'], boundary_epochs=\n boundaries, decay_rates=decay_rates)\n", (18481, 18626), False, 'from official.resnet import resnet_run_loop\n'), ((18657, 18978), 'official.resnet.resnet_run_loop.resnet_model_fn', 'resnet_run_loop.resnet_model_fn', (['features', 'labels', 'mode', 'imagenet_main.ImagenetModel'], {'resnet_size': "params['resnet_size']", 'weight_decay': '(0.0001)', 'learning_rate_fn': 'learning_rate_fn', 'momentum': '(0.9)', 'data_format': "params['data_format']", 'version': "params['version']", 'loss_filter_fn': 'None', 'multi_gpu': "params['multi_gpu']"}), "(features, labels, mode, imagenet_main.\n ImagenetModel, resnet_size=params['resnet_size'], weight_decay=0.0001,\n learning_rate_fn=learning_rate_fn, momentum=0.9, data_format=params[\n 'data_format'], version=params['version'], loss_filter_fn=None,\n multi_gpu=params['multi_gpu'])\n", (18688, 18978), False, 'from official.resnet import resnet_run_loop\n'), ((22001, 22101), 'official.resnet.resnet_run_loop.define_resnet_flags', 'resnet_run_loop.define_resnet_flags', ([], {'resnet_size_choices': "['18', '34', '50', '101', '152', '200']"}), "(resnet_size_choices=['18', '34', '50',\n '101', '152', '200'])\n", (22036, 22101), False, 'from official.resnet import resnet_run_loop\n'), ((22184, 22202), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (22200, 22202), False, 'import sys\n'), ((23876, 23936), 'official.resnet.resnet_run_loop.resnet_main', 'resnet_run_loop.resnet_main', (['flags', 'model_fn', 'input_function'], {}), '(flags, model_fn, input_function)\n', (23903, 23936), False, 'from official.resnet import resnet_run_loop\n'), ((23979, 24020), 'tensorflow.logging.set_verbosity', 'tf.logging.set_verbosity', (['tf.logging.INFO'], {}), '(tf.logging.INFO)\n', (24003, 24020), True, 'import tensorflow as tf\n'), ((24025, 24050), 'tensorflow.app.run', 'tf.app.run', ([], {'argv': 'sys.argv'}), '(argv=sys.argv)\n', (24035, 24050), True, 'import tensorflow as tf\n'), ((3694, 3724), 'image_manipulation.rgb2gray', 'image_manipulation.rgb2gray', (['x'], {}), '(x)\n', (3721, 3724), False, 'import image_manipulation\n'), ((4693, 4723), 'image_manipulation.rgb2gray', 'image_manipulation.rgb2gray', (['x'], {}), '(x)\n', (4720, 4723), False, 'import image_manipulation\n'), ((4749, 4798), 'image_manipulation.high_pass_filter', 'image_manipulation.high_pass_filter', (['x'], {'std': 'level'}), '(x, std=level)\n', (4784, 4798), False, 'import image_manipulation\n'), ((8484, 8533), 'imagenet_16.parse_record', 'imagenet_16.parse_record', (['raw_record', 'is_training'], {}), '(raw_record, is_training)\n', (8508, 8533), False, 'import imagenet_16\n'), ((8637, 8688), 'official.resnet.imagenet_main.parse_record', 'imagenet_main.parse_record', (['raw_record', 'is_training'], {}), '(raw_record, is_training)\n', (8663, 8688), False, 'from official.resnet import imagenet_main\n'), ((13937, 14027), 'official.resnet.imagenet_preprocessing._mean_image_subtraction', 'imagenet_preprocessing._mean_image_subtraction', (['image', 'neg_channel_means', 'num_channels'], {}), '(image, neg_channel_means,\n num_channels)\n', (13983, 14027), False, 'from official.resnet import imagenet_preprocessing\n'), ((14111, 14199), 'tensorflow.py_func', 'tf.py_func', (['perturbation_fn', '[image]', 'tf.float32'], {'stateful': '(False)', 'name': 'perturbation'}), '(perturbation_fn, [image], tf.float32, stateful=False, name=\n perturbation)\n', (14121, 14199), True, 'import tensorflow as tf\n'), ((14333, 14419), 'official.resnet.imagenet_preprocessing._mean_image_subtraction', 'imagenet_preprocessing._mean_image_subtraction', (['image', 'channel_means', 'num_channels'], {}), '(image, channel_means,\n num_channels)\n', (14379, 14419), False, 'from official.resnet import imagenet_preprocessing\n'), ((14587, 14634), 'tensorflow.nn.dropout', 'tf.nn.dropout', (['image', '(0.5)'], {'name': '"""input_dropout"""'}), "(image, 0.5, name='input_dropout')\n", (14600, 14634), True, 'import tensorflow as tf\n'), ((16418, 16489), 'functools.partial', 'partial', (['parse_record_and_perturb', 'perturbation', 'input_dropout', 'sixteen'], {}), '(parse_record_and_perturb, perturbation, input_dropout, sixteen)\n', (16425, 16489), False, 'from functools import partial\n'), ((17876, 17930), 'math.ceil', 'math.ceil', (["(_NUM_IMAGES['train'] / params['batch_size'])"], {}), "(_NUM_IMAGES['train'] / params['batch_size'])\n", (17885, 17930), False, 'import math\n'), ((17973, 18033), 'math.ceil', 'math.ceil', (['(pretrained_steps / pretrained_steps_per_epoch_new)'], {}), '(pretrained_steps / pretrained_steps_per_epoch_new)\n', (17982, 18033), False, 'import math\n'), ((19079, 19101), 'tensorflow.get_default_graph', 'tf.get_default_graph', ([], {}), '()\n', (19099, 19101), True, 'import tensorflow as tf\n'), ((19182, 19221), 'tensorflow.summary.tensor_summary', 'tf.summary.tensor_summary', (['name[:-2]', 't'], {}), '(name[:-2], t)\n', (19207, 19221), True, 'import tensorflow as tf\n'), ((22272, 22303), 'os.path.exists', 'os.path.exists', (['flags.model_dir'], {}), '(flags.model_dir)\n', (22286, 22303), False, 'import os\n'), ((23518, 23625), 'functools.partial', 'functools.partial', (['imagenet_finetuning_model_fn'], {'boundaries': 'flags.lr_boundaries', 'tempfix': 'flags.tempfix'}), '(imagenet_finetuning_model_fn, boundaries=flags.\n lr_boundaries, tempfix=flags.tempfix)\n', (23535, 23625), False, 'import functools\n'), ((23804, 23871), 'functools.partial', 'partial', (['input_fn', 'perturbation', 'flags.input_dropout', 'flags.sixteen'], {}), '(input_fn, perturbation, flags.input_dropout, flags.sixteen)\n', (23811, 23871), False, 'from functools import partial\n'), ((5014, 5044), 'image_manipulation.rotate90', 'image_manipulation.rotate90', (['x'], {}), '(x)\n', (5041, 5044), False, 'import image_manipulation\n'), ((8859, 8925), 'functools.partial', 'partial', (['image_manipulation.grayscale_contrast'], {'contrast_level': '(0.3)'}), '(image_manipulation.grayscale_contrast, contrast_level=0.3)\n', (8866, 8925), False, 'from functools import partial\n'), ((22421, 22446), 'os.mkdir', 'os.mkdir', (['flags.model_dir'], {}), '(flags.model_dir)\n', (22429, 22446), False, 'import os\n'), ((22549, 22597), 'shutil.copytree', 'shutil.copytree', (['"""./pretrained"""', 'flags.model_dir'], {}), "('./pretrained', flags.model_dir)\n", (22564, 22597), False, 'import shutil\n'), ((23443, 23486), 'tensorflow.train.latest_checkpoint', 'tf.train.latest_checkpoint', (['flags.model_dir'], {}), '(flags.model_dir)\n', (23469, 23486), True, 'import tensorflow as tf\n'), ((23756, 23790), 'official.resnet.imagenet_main.get_synth_input_fn', 'imagenet_main.get_synth_input_fn', ([], {}), '()\n', (23788, 23790), False, 'from official.resnet import imagenet_main\n'), ((5083, 5114), 'image_manipulation.rotate180', 'image_manipulation.rotate180', (['x'], {}), '(x)\n', (5111, 5114), False, 'import image_manipulation\n'), ((22792, 22862), 'functools.partial', 'functools.partial', (['imagenet_16.imagenet_model_fn'], {'boundary_epochs': 'None'}), '(imagenet_16.imagenet_model_fn, boundary_epochs=None)\n', (22809, 22862), False, 'import functools\n'), ((23175, 23265), 'functools.partial', 'functools.partial', (['imagenet_16.imagenet_model_fn'], {'boundary_epochs': 'flags.lr_boundaries'}), '(imagenet_16.imagenet_model_fn, boundary_epochs=flags.\n lr_boundaries)\n', (23192, 23265), False, 'import functools\n'), ((5153, 5184), 'image_manipulation.rotate270', 'image_manipulation.rotate270', (['x'], {}), '(x)\n', (5181, 5184), False, 'import image_manipulation\n'), ((21137, 21222), 'official.resnet.resnet_run_loop.ResnetArgParser', 'resnet_run_loop.ResnetArgParser', ([], {'resnet_size_choices': '[18, 34, 50, 101, 152, 200]'}), '(resnet_size_choices=[18, 34, 50, 101, 152, 200]\n )\n', (21168, 21222), False, 'from official.resnet import resnet_run_loop\n'), ((9145, 9168), 'numpy.random.RandomState', 'np.random.RandomState', ([], {}), '()\n', (9166, 9168), True, 'import numpy as np\n'), ((9380, 9403), 'numpy.random.RandomState', 'np.random.RandomState', ([], {}), '()\n', (9401, 9403), True, 'import numpy as np\n'), ((12249, 12339), 'functools.partial', 'partial', (['placeholder__uniform_noise_multiple'], {'placeholder': 'image_manipulation.rgb2gray'}), '(placeholder__uniform_noise_multiple, placeholder=image_manipulation\n .rgb2gray)\n', (12256, 12339), False, 'from functools import partial\n'), ((12517, 12607), 'functools.partial', 'partial', (['placeholder__uniform_noise_multiple'], {'placeholder': 'grayscale_contrast_multiple'}), '(placeholder__uniform_noise_multiple, placeholder=\n grayscale_contrast_multiple)\n', (12524, 12607), False, 'from functools import partial\n'), ((12775, 12850), 'functools.partial', 'partial', (['placeholder__uniform_noise_multiple'], {'placeholder': 'low_pass_multiple'}), '(placeholder__uniform_noise_multiple, placeholder=low_pass_multiple)\n', (12782, 12850), False, 'from functools import partial\n'), ((13024, 13100), 'functools.partial', 'partial', (['placeholder__uniform_noise_multiple'], {'placeholder': 'high_pass_multiple'}), '(placeholder__uniform_noise_multiple, placeholder=high_pass_multiple)\n', (13031, 13100), False, 'from functools import partial\n'), ((13281, 13369), 'functools.partial', 'partial', (['placeholder__uniform_noise_multiple'], {'placeholder': 'phase_scrambling_multiple'}), '(placeholder__uniform_noise_multiple, placeholder=\n phase_scrambling_multiple)\n', (13288, 13369), False, 'from functools import partial\n'), ((13537, 13612), 'functools.partial', 'partial', (['placeholder__uniform_noise_multiple'], {'placeholder': 'rotation_multiple'}), '(placeholder__uniform_noise_multiple, placeholder=rotation_multiple)\n', (13544, 13612), False, 'from functools import partial\n')] |
import numpy as np
import random
from nltk import word_tokenize
from nltk.corpus import stopwords
from nltk import WordNetLemmatizer
from sklearn import svm
from sklearn.model_selection import GridSearchCV
import random
with open('./data/vocab.txt', 'r') as fp:
vocab_list = fp.read().split('\n')
vocab = {word: count for count, word in enumerate(vocab_list)}
def ngrams(w_input, n):
"""
Generate a set of n-grams for more complex features
"""
output = []
for i in range(len(w_input) - n + 1):
output.append(w_input[i: i + n])
return [''.join(x) for x in output]
def tokenize_sentence(sentence):
"""
Group tokenized sentences and it's corresponding sentiment into a tuple
"""
stop = stopwords.words('english')
lmtzr = WordNetLemmatizer()
token_words = word_tokenize(sentence)
sentiment = token_words[-1]
tokens = [lmtzr.lemmatize(w.lower()) for w in token_words if w not in stop and w.isalpha() and len(w) >= 3]
bi_grams = ngrams(tokens, 2)
return (tokens + bi_grams, sentiment)
def extract_features(sentence):
"""
Extract features from tokenized sentence and build a feature vector
"""
feature_vector = [0] * len(vocab)
tokens, sentiment = tokenize_sentence(sentence)
for word in tokens:
if word in vocab:
feature_vector[vocab[word]] = 1
return (feature_vector, sentiment)
def get_sentences_from_files(files):
"""
Load corpus from file
"""
sentences = []
for file_name in files:
with open(file_name, 'r') as fp:
sentences.extend(fp.readlines())
return sentences
def build_data_set(sentences):
"""
Build feature vector X and output vector y for training the classifier
"""
X = []
y = []
for each_sentence in sentences:
features, sentiment = extract_features(each_sentence)
X.append(features)
y.append(sentiment)
X = np.array(X)
y = np.array(y)
return X, y
def optimize_params(X, y, clf, param_grid):
"""
Find optiumum values for C, gamma and degree using GridSearch
and Cross Fold Validation
"""
clf = GridSearchCV(clf, param_grid, cv=2, n_jobs=2)
clf.fit(X, y)
return clf.best_params_
if __name__ == '__main__':
sentences = get_sentences_from_files(['./data/sentences_labelled.txt'])
X, y = build_data_set(sentences)
# Training dataset
train_X = X[:2000]
train_y = y[:2000]
# Cross-validation dataset
cross_X = X[2000: 2400]
cross_y = y[2000: 2400]
# Testing dataset
test_X = X[2400:]
test_y = y[2400:]
svc = svm.SVC(kernel='poly', C=10, gamma=0.1, degree=2)
svc.fit(train_X, train_y)
print(svc.score(cross_X, cross_y))
| [
"sklearn.model_selection.GridSearchCV",
"nltk.corpus.stopwords.words",
"nltk.word_tokenize",
"nltk.WordNetLemmatizer",
"numpy.array",
"sklearn.svm.SVC"
] | [((748, 774), 'nltk.corpus.stopwords.words', 'stopwords.words', (['"""english"""'], {}), "('english')\n", (763, 774), False, 'from nltk.corpus import stopwords\n'), ((787, 806), 'nltk.WordNetLemmatizer', 'WordNetLemmatizer', ([], {}), '()\n', (804, 806), False, 'from nltk import WordNetLemmatizer\n'), ((826, 849), 'nltk.word_tokenize', 'word_tokenize', (['sentence'], {}), '(sentence)\n', (839, 849), False, 'from nltk import word_tokenize\n'), ((1959, 1970), 'numpy.array', 'np.array', (['X'], {}), '(X)\n', (1967, 1970), True, 'import numpy as np\n'), ((1979, 1990), 'numpy.array', 'np.array', (['y'], {}), '(y)\n', (1987, 1990), True, 'import numpy as np\n'), ((2176, 2221), 'sklearn.model_selection.GridSearchCV', 'GridSearchCV', (['clf', 'param_grid'], {'cv': '(2)', 'n_jobs': '(2)'}), '(clf, param_grid, cv=2, n_jobs=2)\n', (2188, 2221), False, 'from sklearn.model_selection import GridSearchCV\n'), ((2646, 2695), 'sklearn.svm.SVC', 'svm.SVC', ([], {'kernel': '"""poly"""', 'C': '(10)', 'gamma': '(0.1)', 'degree': '(2)'}), "(kernel='poly', C=10, gamma=0.1, degree=2)\n", (2653, 2695), False, 'from sklearn import svm\n')] |
'''The module creates image directories for various
classes out of a dataframe for data augmentation purposes.'''
#importing libraries
import numpy as np
import pandas as pd
import os
from PIL import Image
def create_dir(path,class_list):
''' The function takes in the path and list of the classes to
create directories for different classes.
Parameters:
path: The path where train and validation directories needs to be created.
class_list: The list of labels in the dataset.'''
#Create train and validation directories
train_path = os.path.join(path,'train')
val_path = os.path.join(path,'valid')
os.mkdir(train_path)
os.mkdir(val_path)
for data_path,cat in {train_path:'train-',val_path:'valid-'}.items():
for label in class_list:
label_dir = os.path.join(data_path,cat+str(label))
os.mkdir(label_dir)
def save_imgs(df,df_path,pixel_col,class_col,class_list,prefix):
'''This function takes in the dataframes and
creates images and saves images in directories.
Parameters:
df: Dataframe that needs to be converted.
df_path: Path to the directory (dtype-string)
Example- If the training dataframe is fed, df_path should be the path
to the train directory created.
pixel_col: Name of the column containing pixels in string object
class_col: Name of the column for data labels
prefix: train- for training set, valid- for validation set '''
for i in range(len(df)):
pixel_string = df[pixel_col][i]
pixels = list(map(int, pixel_string.split()))
matrix = np.array(pixels).reshape(48,48).astype(np.uint8)
img = Image.fromarray(matrix)
for label in class_list:
if str(df[class_col][i]) in prefix + str(label):
img.save(df_path +'/'+ prefix + str(label)+'/'+ prefix + str(label)+'-'+str(i)+'.png')
else:
continue
| [
"numpy.array",
"PIL.Image.fromarray",
"os.path.join",
"os.mkdir"
] | [((581, 608), 'os.path.join', 'os.path.join', (['path', '"""train"""'], {}), "(path, 'train')\n", (593, 608), False, 'import os\n'), ((621, 648), 'os.path.join', 'os.path.join', (['path', '"""valid"""'], {}), "(path, 'valid')\n", (633, 648), False, 'import os\n'), ((650, 670), 'os.mkdir', 'os.mkdir', (['train_path'], {}), '(train_path)\n', (658, 670), False, 'import os\n'), ((673, 691), 'os.mkdir', 'os.mkdir', (['val_path'], {}), '(val_path)\n', (681, 691), False, 'import os\n'), ((1683, 1706), 'PIL.Image.fromarray', 'Image.fromarray', (['matrix'], {}), '(matrix)\n', (1698, 1706), False, 'from PIL import Image\n'), ((857, 876), 'os.mkdir', 'os.mkdir', (['label_dir'], {}), '(label_dir)\n', (865, 876), False, 'import os\n'), ((1622, 1638), 'numpy.array', 'np.array', (['pixels'], {}), '(pixels)\n', (1630, 1638), True, 'import numpy as np\n')] |
import cv2
import numpy as np
def build_transformation_matrix(transform):
"""Convert transform list to transformation matrix
:param transform: transform list as [dx, dy, da]
:return: transform matrix as 2d (2, 3) numpy array
"""
transform_matrix = np.zeros((2, 3))
transform_matrix[0, 0] = np.cos(transform[2])*transform[3]*(-1.0)
transform_matrix[0, 1] = -np.sin(transform[2])*transform[3]*(-1.0)
transform_matrix[1, 0] = np.sin(transform[2])*transform[3]*(-1.0)
transform_matrix[1, 1] = np.cos(transform[2])*transform[3]*(-1.0)
transform_matrix[0, 2] = transform[0]
transform_matrix[1, 2] = transform[1]
return transform_matrix
def border_frame(frame, border_size, border_type):
"""Convenience wrapper of cv2.copyMakeBorder for how vidstab applies borders
:param frame: frame to apply border to
:param border_size: int border size in number of pixels
:param border_type: one of the following ['black', 'reflect', 'replicate']
:return: bordered version of frame
"""
border_modes = {'black': cv2.BORDER_CONSTANT,
'reflect': cv2.BORDER_REFLECT,
'replicate': cv2.BORDER_REPLICATE}
border_mode = border_modes[border_type]
bordered_frame = cv2.copyMakeBorder(frame,
top=border_size,
bottom=border_size,
left=border_size,
right=border_size,
borderType=border_mode,
value=[0, 0, 0])
alpha_bordered_frame = cv2.cvtColor(bordered_frame, cv2.COLOR_BGR2BGRA)
alpha_bordered_frame[:, :, 3] = 0
h, w = frame.shape[:2]
alpha_bordered_frame[border_size:border_size + h, border_size:border_size + w, 3] = 255
return alpha_bordered_frame, border_mode
def match_keypoints(optical_flow, prev_kps):
"""Match optical flow keypoints
:param optical_flow: output of cv2.calcOpticalFlowPyrLK
:param prev_kps: keypoints that were passed to cv2.calcOpticalFlowPyrLK to create optical_flow
:return: tuple of (cur_matched_kp, prev_matched_kp)
"""
cur_kps, status, err = optical_flow
# storage for keypoints with status 1
prev_matched_kp = []
cur_matched_kp = []
for i, matched in enumerate(status):
# store coords of keypoints that appear in both
if matched:
prev_matched_kp.append(prev_kps[i])
cur_matched_kp.append(cur_kps[i])
return cur_matched_kp, prev_matched_kp
def estimate_partial_transform(matched_keypoints,scale=False):
"""Wrapper of cv2.estimateRigidTransform for convenience in vidstab process
:param matched_keypoints: output of match_keypoints util function; tuple of (cur_matched_kp, prev_matched_kp)
:return: transform as list of [dx, dy, da]
"""
cur_matched_kp, prev_matched_kp = matched_keypoints
transform = cv2.estimateRigidTransform(np.array(prev_matched_kp),
np.array(cur_matched_kp),
False)
print("estimateRigidTransform::transform:\n",transform)
if transform is not None:
# translation x
dx = transform[0, 2]
# translation y
dy = transform[1, 2]
# rotation
da = np.arctan2(transform[1, 0], transform[0, 0])
if scale:
# scale
s = transform[0,0]/np.cos(da)
else:
s = 1.0
else:
dx = dy = da = 0
s = 1.0
return [dx, dy, da, s]
| [
"cv2.copyMakeBorder",
"numpy.array",
"numpy.zeros",
"numpy.arctan2",
"numpy.cos",
"cv2.cvtColor",
"numpy.sin"
] | [((271, 287), 'numpy.zeros', 'np.zeros', (['(2, 3)'], {}), '((2, 3))\n', (279, 287), True, 'import numpy as np\n'), ((1269, 1414), 'cv2.copyMakeBorder', 'cv2.copyMakeBorder', (['frame'], {'top': 'border_size', 'bottom': 'border_size', 'left': 'border_size', 'right': 'border_size', 'borderType': 'border_mode', 'value': '[0, 0, 0]'}), '(frame, top=border_size, bottom=border_size, left=\n border_size, right=border_size, borderType=border_mode, value=[0, 0, 0])\n', (1287, 1414), False, 'import cv2\n'), ((1678, 1726), 'cv2.cvtColor', 'cv2.cvtColor', (['bordered_frame', 'cv2.COLOR_BGR2BGRA'], {}), '(bordered_frame, cv2.COLOR_BGR2BGRA)\n', (1690, 1726), False, 'import cv2\n'), ((3039, 3064), 'numpy.array', 'np.array', (['prev_matched_kp'], {}), '(prev_matched_kp)\n', (3047, 3064), True, 'import numpy as np\n'), ((3109, 3133), 'numpy.array', 'np.array', (['cur_matched_kp'], {}), '(cur_matched_kp)\n', (3117, 3133), True, 'import numpy as np\n'), ((3413, 3457), 'numpy.arctan2', 'np.arctan2', (['transform[1, 0]', 'transform[0, 0]'], {}), '(transform[1, 0], transform[0, 0])\n', (3423, 3457), True, 'import numpy as np\n'), ((318, 338), 'numpy.cos', 'np.cos', (['transform[2]'], {}), '(transform[2])\n', (324, 338), True, 'import numpy as np\n'), ((459, 479), 'numpy.sin', 'np.sin', (['transform[2]'], {}), '(transform[2])\n', (465, 479), True, 'import numpy as np\n'), ((529, 549), 'numpy.cos', 'np.cos', (['transform[2]'], {}), '(transform[2])\n', (535, 549), True, 'import numpy as np\n'), ((389, 409), 'numpy.sin', 'np.sin', (['transform[2]'], {}), '(transform[2])\n', (395, 409), True, 'import numpy as np\n'), ((3527, 3537), 'numpy.cos', 'np.cos', (['da'], {}), '(da)\n', (3533, 3537), True, 'import numpy as np\n')] |
#
# Simulations: discharge of a lead-acid battery
#
import argparse
import matplotlib.pyplot as plt
import numpy as np
import pickle
import pybamm
import shared_plotting
from collections import defaultdict
from shared_solutions import model_comparison, convergence_study
try:
from config import OUTPUT_DIR
except ImportError:
OUTPUT_DIR = None
def plot_voltages(all_variables, t_eval):
Crates = [0.1, 0.2, 0.5, 1, 2, 5]
all_variables = {k: v for k, v in all_variables.items() if k in Crates}
shared_plotting.plot_voltages(all_variables, t_eval)
file_name = "discharge_voltage_comparison.eps"
if OUTPUT_DIR is not None:
plt.savefig(OUTPUT_DIR + file_name, format="eps", dpi=1000)
def plot_variables(all_variables, t_eval):
# Set up
Crates = [0.1, 1, 4]
times = np.array([0, 0.195, 0.375, 0.545])
var_file_names = {
"Electrolyte concentration [Molar]"
+ "": "discharge_electrolyte_concentration_comparison.eps",
"Electrolyte potential [V]": "discharge_electrolyte_potential_comparison.eps",
"Interfacial current density"
+ "": "discharge_interfacial_current_density_comparison.eps",
}
limits_exceptions = {"Electrolyte concentration [Molar]": {"min": 0}}
all_variables = {k: v for k, v in all_variables.items() if k in Crates}
for var, file_name in var_file_names.items():
if var in limits_exceptions:
exceptions = limits_exceptions[var]
else:
exceptions = {}
shared_plotting.plot_variable(all_variables, times, var, exceptions)
if OUTPUT_DIR is not None:
plt.savefig(OUTPUT_DIR + file_name, format="eps", dpi=1000)
def plot_voltage_components(all_variables, t_eval):
Crates = [0.1, 2, 5]
model = "Composite"
shared_plotting.plot_voltage_components(all_variables, t_eval, model, Crates)
file_name = "discharge_voltage_components.eps"
if OUTPUT_DIR is not None:
plt.savefig(OUTPUT_DIR + file_name, format="eps", dpi=1000)
def discharge_states(compute):
savefile = "discharge_asymptotics_data.pickle"
if compute:
models = [
pybamm.lead_acid.Full(name="Full"),
pybamm.lead_acid.LOQS(name="LOQS"),
pybamm.lead_acid.FOQS(name="FOQS"),
pybamm.lead_acid.Composite(name="Composite"),
]
Crates = [0.1, 0.2, 0.5, 1, 2, 4, 5, 10, 20]
t_eval = np.linspace(0, 1, 100)
extra_parameter_values = {"Bruggeman coefficient": 0.001}
all_variables, t_eval = model_comparison(
models, Crates, t_eval, extra_parameter_values=extra_parameter_values
)
with open(savefile, "wb") as f:
data = (all_variables, t_eval)
pickle.dump(data, f, pickle.HIGHEST_PROTOCOL)
else:
try:
with open(savefile, "rb") as f:
(all_variables, t_eval) = pickle.load(f)
except FileNotFoundError:
raise FileNotFoundError(
"Run script with '--compute' first to generate results"
)
plot_voltages(all_variables, t_eval)
plot_variables(all_variables, t_eval)
plot_voltage_components(all_variables, t_eval)
def plot_errors(models_times_and_voltages):
npts = 20
linestyles = ["k-", "g--", "r:", "b-."]
Crates = defaultdict(list)
voltage_errors = defaultdict(list)
fig, ax = plt.subplots(1, 1)
for i, (model, times_and_voltages) in enumerate(models_times_and_voltages.items()):
if model != "Full":
for Crate, variables in times_and_voltages[npts].items():
Crates[model].append(Crate)
full_voltage = models_times_and_voltages["Full"][npts][Crate][
"Battery voltage [V]"
]
reduced_voltage = variables["Battery voltage [V]"]
voltage_errors[model].append(pybamm.rmse(full_voltage, reduced_voltage))
ax.semilogx(
Crates[model], voltage_errors[model], linestyles[i], label=model
)
ax.set_xlabel("C-rate")
ax.set_ylabel("RMSE [V]")
ax.legend(loc="best")
fig.tight_layout()
file_name = "discharge_asymptotics_rmse.eps"
if OUTPUT_DIR is not None:
plt.savefig(OUTPUT_DIR + file_name, format="eps", dpi=1000)
def plot_times(models_times_and_voltages):
shared_plotting.plot_times(models_times_and_voltages, Crate=1)
file_name = "discharge_asymptotics_solver_times.eps"
if OUTPUT_DIR is not None:
plt.savefig(OUTPUT_DIR + file_name, format="eps", dpi=1000)
def discharge_times_and_errors(compute):
savefile = "discharge_asymptotics_times_and_errors.pickle"
if compute:
try:
with open(savefile, "rb") as f:
models_times_and_voltages = pickle.load(f)
except FileNotFoundError:
models_times_and_voltages = pybamm.get_infinite_nested_dict()
models = [
pybamm.lead_acid.Full({"surface form": "algebraic"}, name="Full"),
pybamm.lead_acid.LOQS(name="LOQS"),
# pybamm.lead_acid.FOQS(name="FOQS"),
# pybamm.lead_acid.Composite(name="Composite"),
]
Crates = np.linspace(0.01, 5, 2)
all_npts = [20]
t_eval = np.linspace(0, 1, 100)
new_models_times_and_voltages = convergence_study(
models, Crates, all_npts, t_eval
)
models_times_and_voltages.update(new_models_times_and_voltages)
with open(savefile, "wb") as f:
pickle.dump(models_times_and_voltages, f, pickle.HIGHEST_PROTOCOL)
else:
try:
with open(savefile, "rb") as f:
models_times_and_voltages = pickle.load(f)
except FileNotFoundError:
raise FileNotFoundError(
"Run script with '--compute' first to generate results"
)
plot_errors(models_times_and_voltages)
plot_times(models_times_and_voltages)
if __name__ == "__main__":
pybamm.set_logging_level("INFO")
parser = argparse.ArgumentParser()
parser.add_argument("--compute", action="store_true", help="(Re)-compute results.")
args = parser.parse_args()
discharge_states(args.compute)
# discharge_times_and_errors(args.compute)
plt.show()
| [
"pybamm.set_logging_level",
"shared_plotting.plot_variable",
"numpy.array",
"pybamm.lead_acid.LOQS",
"shared_solutions.model_comparison",
"shared_plotting.plot_voltage_components",
"argparse.ArgumentParser",
"shared_plotting.plot_voltages",
"pybamm.rmse",
"numpy.linspace",
"pybamm.lead_acid.Comp... | [((515, 567), 'shared_plotting.plot_voltages', 'shared_plotting.plot_voltages', (['all_variables', 't_eval'], {}), '(all_variables, t_eval)\n', (544, 567), False, 'import shared_plotting\n'), ((813, 847), 'numpy.array', 'np.array', (['[0, 0.195, 0.375, 0.545]'], {}), '([0, 0.195, 0.375, 0.545])\n', (821, 847), True, 'import numpy as np\n'), ((1802, 1879), 'shared_plotting.plot_voltage_components', 'shared_plotting.plot_voltage_components', (['all_variables', 't_eval', 'model', 'Crates'], {}), '(all_variables, t_eval, model, Crates)\n', (1841, 1879), False, 'import shared_plotting\n'), ((3335, 3352), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (3346, 3352), False, 'from collections import defaultdict\n'), ((3374, 3391), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (3385, 3391), False, 'from collections import defaultdict\n'), ((3406, 3424), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {}), '(1, 1)\n', (3418, 3424), True, 'import matplotlib.pyplot as plt\n'), ((4374, 4436), 'shared_plotting.plot_times', 'shared_plotting.plot_times', (['models_times_and_voltages'], {'Crate': '(1)'}), '(models_times_and_voltages, Crate=1)\n', (4400, 4436), False, 'import shared_plotting\n'), ((6016, 6048), 'pybamm.set_logging_level', 'pybamm.set_logging_level', (['"""INFO"""'], {}), "('INFO')\n", (6040, 6048), False, 'import pybamm\n'), ((6062, 6087), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (6085, 6087), False, 'import argparse\n'), ((6293, 6303), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6301, 6303), True, 'import matplotlib.pyplot as plt\n'), ((658, 717), 'matplotlib.pyplot.savefig', 'plt.savefig', (['(OUTPUT_DIR + file_name)'], {'format': '"""eps"""', 'dpi': '(1000)'}), "(OUTPUT_DIR + file_name, format='eps', dpi=1000)\n", (669, 717), True, 'import matplotlib.pyplot as plt\n'), ((1519, 1587), 'shared_plotting.plot_variable', 'shared_plotting.plot_variable', (['all_variables', 'times', 'var', 'exceptions'], {}), '(all_variables, times, var, exceptions)\n', (1548, 1587), False, 'import shared_plotting\n'), ((1970, 2029), 'matplotlib.pyplot.savefig', 'plt.savefig', (['(OUTPUT_DIR + file_name)'], {'format': '"""eps"""', 'dpi': '(1000)'}), "(OUTPUT_DIR + file_name, format='eps', dpi=1000)\n", (1981, 2029), True, 'import matplotlib.pyplot as plt\n'), ((2431, 2453), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(100)'], {}), '(0, 1, 100)\n', (2442, 2453), True, 'import numpy as np\n'), ((2552, 2644), 'shared_solutions.model_comparison', 'model_comparison', (['models', 'Crates', 't_eval'], {'extra_parameter_values': 'extra_parameter_values'}), '(models, Crates, t_eval, extra_parameter_values=\n extra_parameter_values)\n', (2568, 2644), False, 'from shared_solutions import model_comparison, convergence_study\n'), ((4265, 4324), 'matplotlib.pyplot.savefig', 'plt.savefig', (['(OUTPUT_DIR + file_name)'], {'format': '"""eps"""', 'dpi': '(1000)'}), "(OUTPUT_DIR + file_name, format='eps', dpi=1000)\n", (4276, 4324), True, 'import matplotlib.pyplot as plt\n'), ((4533, 4592), 'matplotlib.pyplot.savefig', 'plt.savefig', (['(OUTPUT_DIR + file_name)'], {'format': '"""eps"""', 'dpi': '(1000)'}), "(OUTPUT_DIR + file_name, format='eps', dpi=1000)\n", (4544, 4592), True, 'import matplotlib.pyplot as plt\n'), ((5222, 5245), 'numpy.linspace', 'np.linspace', (['(0.01)', '(5)', '(2)'], {}), '(0.01, 5, 2)\n', (5233, 5245), True, 'import numpy as np\n'), ((5287, 5309), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', '(100)'], {}), '(0, 1, 100)\n', (5298, 5309), True, 'import numpy as np\n'), ((5350, 5401), 'shared_solutions.convergence_study', 'convergence_study', (['models', 'Crates', 'all_npts', 't_eval'], {}), '(models, Crates, all_npts, t_eval)\n', (5367, 5401), False, 'from shared_solutions import model_comparison, convergence_study\n'), ((1635, 1694), 'matplotlib.pyplot.savefig', 'plt.savefig', (['(OUTPUT_DIR + file_name)'], {'format': '"""eps"""', 'dpi': '(1000)'}), "(OUTPUT_DIR + file_name, format='eps', dpi=1000)\n", (1646, 1694), True, 'import matplotlib.pyplot as plt\n'), ((2161, 2195), 'pybamm.lead_acid.Full', 'pybamm.lead_acid.Full', ([], {'name': '"""Full"""'}), "(name='Full')\n", (2182, 2195), False, 'import pybamm\n'), ((2209, 2243), 'pybamm.lead_acid.LOQS', 'pybamm.lead_acid.LOQS', ([], {'name': '"""LOQS"""'}), "(name='LOQS')\n", (2230, 2243), False, 'import pybamm\n'), ((2257, 2291), 'pybamm.lead_acid.FOQS', 'pybamm.lead_acid.FOQS', ([], {'name': '"""FOQS"""'}), "(name='FOQS')\n", (2278, 2291), False, 'import pybamm\n'), ((2305, 2349), 'pybamm.lead_acid.Composite', 'pybamm.lead_acid.Composite', ([], {'name': '"""Composite"""'}), "(name='Composite')\n", (2331, 2349), False, 'import pybamm\n'), ((2757, 2802), 'pickle.dump', 'pickle.dump', (['data', 'f', 'pickle.HIGHEST_PROTOCOL'], {}), '(data, f, pickle.HIGHEST_PROTOCOL)\n', (2768, 2802), False, 'import pickle\n'), ((4970, 5035), 'pybamm.lead_acid.Full', 'pybamm.lead_acid.Full', (["{'surface form': 'algebraic'}"], {'name': '"""Full"""'}), "({'surface form': 'algebraic'}, name='Full')\n", (4991, 5035), False, 'import pybamm\n'), ((5049, 5083), 'pybamm.lead_acid.LOQS', 'pybamm.lead_acid.LOQS', ([], {'name': '"""LOQS"""'}), "(name='LOQS')\n", (5070, 5083), False, 'import pybamm\n'), ((5548, 5614), 'pickle.dump', 'pickle.dump', (['models_times_and_voltages', 'f', 'pickle.HIGHEST_PROTOCOL'], {}), '(models_times_and_voltages, f, pickle.HIGHEST_PROTOCOL)\n', (5559, 5614), False, 'import pickle\n'), ((2912, 2926), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (2923, 2926), False, 'import pickle\n'), ((4816, 4830), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (4827, 4830), False, 'import pickle\n'), ((4905, 4938), 'pybamm.get_infinite_nested_dict', 'pybamm.get_infinite_nested_dict', ([], {}), '()\n', (4936, 4938), False, 'import pybamm\n'), ((5726, 5740), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (5737, 5740), False, 'import pickle\n'), ((3906, 3948), 'pybamm.rmse', 'pybamm.rmse', (['full_voltage', 'reduced_voltage'], {}), '(full_voltage, reduced_voltage)\n', (3917, 3948), False, 'import pybamm\n')] |
# Copyright 2018-2021 Lawrence Livermore National Security, LLC and other
# Fat Crayon Toolkit Project Developers. See the top-level COPYRIGHT file for details.
from __future__ import print_function
""" Classes and routines for generating 3D objects
"""
import math
import numpy as np
from scipy.spatial import ConvexHull
from scipy.spatial import Delaunay
from copy import deepcopy
import sys
import random
import re
# If you have placed the other modules in another directory, this can be useful to add that location to the path
#import os, sys; sys.path.append(os.path.dirname(__file__)); import Units as unit
def dipDirectionAndDipAng(tangent):
# Given the tangent to a curve, convert into dip direction and dip
e=tangent[0]
n=tangent[1]
up=tangent[2]
# If we rotate compass to align with math coords:
# W
# |
# S-------N
# |
# E
x=n
y=-e
thetaMath=math.atan2(y,x)
thetaCompass=-thetaMath*180.0/math.pi
dipDirection=thetaCompass
# Dip angle is the amount we are dipping from horizontal
# We chose orientation such that up is -ve
dipAngle=math.atan2( -up, math.sqrt( e*e + n*n ) )*180.0/math.pi
return dipDirection,dipAngle
def dipToStrikeDeg(dip_dir_deg):
# Definitions published by Wikipedia: https://en.wikipedia.org/wiki/Strike_and_dip
# One technique is to always take the strike so the dip is 90 deg to the right of the strike, in which case the redundant letter following the dip angle is omitted (right hand rule, or RHR).
#strike_rad=dip_dir_radians-0.5*np.pi
strike_deg=dip_dir_deg-90.0
return strike_deg
def strikeToDipDeg(strike_deg):
# Definitions published by Wikipedia: https://en.wikipedia.org/wiki/Strike_and_dip
# One technique is to always take the strike so the dip is 90 deg to the right of the strike, in which case the redundant letter following the dip angle is omitted (right hand rule, or RHR).
#strike_rad=dip_dir_radians-0.5*np.pi
#strike_deg=dip_dir_deg-90.0
dip_dir_deg=strike_deg+90.0
return dip_dir_deg
def degToRad(deg):
return deg*np.pi/180.0
def radToDeg(rad):
return rad*180.0/np.pi
# Return a tangent normal given azimuth and declination in degrees
def vectFromAzDecDeg(azDeg, decDeg):
v=np.asarray([0.0,1.0,0.0]) # Due North
v=rotatePoints( [v], np.asarray([1,0,0]), -degToRad(decDeg) )[0] # Rotate decDeg degrees sub-horizontal
v=rotatePoints( [v], np.asarray([0,0,1]), -degToRad(azDeg) )[0] # Rotate azDeg degrees clockwise of North
return v
# Return azimuth and dec from a tangent normal
def azDecDegFromVect(v):
# math.atan2(y, x): Return atan(y / x), in radians. The result is between -pi and pi
return (
(90.0-radToDeg(math.atan2(v[1],v[0])))%360.0, # Azimuth has different sign convention than math convention
-radToDeg(math.atan2(v[2],math.sqrt(v[0]*v[0]+v[1]*v[1])))
)
# Return a normalized vector
def normalize(v):
return v/math.sqrt(np.dot(v, v))
def writeStlObject(points,simplices,fd):
for simplex in simplices:
# I'm not sure we need to calculate a normal...
fd.write("facet normal 0.0 0.0 0.0\n")
fd.write("outer loop\n")
for iPt in simplex:
#print iPt,simplex
fd.write("vertex %g %g %g\n"%(points[iPt][0],points[iPt][1],points[iPt][2]))
fd.write("endloop\n")
fd.write("endfacet\n")
def writeStlFile(points,simplices,stlFile,name="stlObject"):
fd=open(stlFile,'w')
fd.write("solid %s\n"%(name))
writeStlObject(points,simplices,fd)
fd.write("endsolid\n");
def writeObjectsStlFile(objects,stlFile,name="stlObject"):
fd=open(stlFile,'w')
fd.write("solid %s\n"%(name))
#for object in objects:
(points,simplices)=objects
writeStlObject(points,simplices,fd)
fd.write("endsolid\n");
def writeVtk(objectListIn,scalarsIn,scalarNames,vtkFile,name="vtkObjects"):
# Remove empty object lists
#print 'len(objectListIn)',len(objectListIn),'len(scalarsIn)',len(scalarsIn),'len(scalarsIn[0])',len(scalarsIn[0])
if False:
# I don't get it, but this seems to be misbehaving now:
# In retrospect, it isn't clear it ever worked for the case where we have more than one scalar!
objectList=[objectListIn[i] for i in range(len(objectListIn)) if objectListIn[i] is not None]
scalars=[[scalarsIn[0][i] for i in range(len(objectListIn)) if objectListIn[i] is not None]]
if False:
# This is for a more general case with multiple scalars
# But it doesn't seem to work
objectList=[objectListIn[i] for i in range(len(objectListIn)) if objectListIn[i] is not None]
#scalars=[[scalarsIn[:][i]] for i in range(len(objectListIn)) if objectListIn[i] is not None]
scalars=[scalarsIn[:][i] for i in range(len(objectListIn)) if objectListIn[i] is not None]
if True:
# This works, but is not Pythonic
objectList=[]
scalars=[]
for i in range(len(scalarsIn)):
scalars.append([])
for i in range(len(objectListIn)):
if objectListIn[i] is not None:
objectList.append(objectListIn[i])
for iS in range(len(scalarsIn)):
scalars[iS].append(scalarsIn[iS][i])
#print objectList
#print scalars
#print 'len(objectList)',len(objectList),'len(scalars)',len(scalars)
fd=open(vtkFile,'w')
nPtsObj=[]
nPts=0
nTri=0
nObj=len(objectList)
for pts,simps in (objectList):
nPtsObj.append(len(pts))
nPts+=len(pts)
nTri+=len(simps)
nShift=[0]*nObj
for iShift in range(nObj-1):
nShift[iShift+1]=nShift[iShift]+nPtsObj[iShift]
fd.write("# vtk DataFile Version 2.0\n")
fd.write("%s\n"%(name))
fd.write("ASCII\n")
fd.write("DATASET UNSTRUCTURED_GRID\n")
fd.write("POINTS %d float\n"%(nPts))
for pts,simps in (objectList):
for pt in (pts):
fd.write("%g %g %g\n"%(pt[0],pt[1],pt[2]))
fd.write("CELLS %d %d\n"%(nTri,(1+3)*nTri))
iObj=0
#col=[]
for pts,simps in (objectList):
for tri in (simps):
fd.write("3 %d %d %d\n"%(tri[0]+nShift[iObj],tri[1]+nShift[iObj],tri[2]+nShift[iObj]))
#col.append(colorList[iObj])
iObj+=1
fd.write("CELL_TYPES %d\n"%(nTri))
for i in range(nTri):
fd.write("5 ") # http://www.vtk.org/wp-content/uploads/2015/04/file-formats.pdf (see Fig. 2)
if (i%10==9):
fd.write("\n")
fd.write("\n")
fd.write("CELL_DATA %d\n"%(nTri))
# Repeat as many of these as you want to define data on the tris
#for colorList, scalarName in scalars,scalarNames:
#print "check",len(scalars),scalarNames
for iCol in range(len(scalars)):
colorList=scalars[iCol]; scalarName=scalarNames[iCol]
fd.write("SCALARS "+scalarName+" float 1\n")
fd.write("LOOKUP_TABLE default\n")
iObj=0
i=0
for pts,simps in (objectList):
for tri in (simps):
fd.write("%g "%(colorList[iObj])); i+=1
if (i%10==9):
fd.write("\n")
iObj+=1
fd.write("\n")
fd.close()
def simplicesFromPoints(points):
hull=ConvexHull(points)
return hull.simplices
def convexFromPoints(points):
return ( points, simplicesFromPoints(points) )
def delaunayFromPoints(points):
return ( points, Delaunay(points).simplices )
# A non-object
emptyObject=None
# Merging two objects requires a shift in the indices
def mergeObj(obj1, obj2):
if (obj1 is None):
return obj2
if (obj2 is None):
return obj1
if (obj1==emptyObject):
return obj2
if (obj2==emptyObject):
return obj1
return (
np.vstack( (obj1[0],obj2[0]) ),
np.vstack( (obj1[1],obj2[1]+len(obj1[0])) )
)
def mergeObjects(objects):
nObj=len(objects)
merged=np.asarray(deepcopy(objects[0]))
nShift=0
for i in range(nObj-1):
#print i
nShift+=len(objects[i][0])
merged[0]=np.vstack( (merged[0],objects[i+1][0]) )
merged[1]=np.vstack( (merged[1],objects[i+1][1]+nShift) )
return merged
# Some useful objects
unitCubePts=np.asarray([
[-0.5,-0.5,-0.5],
[ 0.5,-0.5,-0.5],
[-0.5, 0.5,-0.5],
[ 0.5, 0.5,-0.5],
[-0.5,-0.5, 0.5],
[ 0.5,-0.5, 0.5],
[-0.5, 0.5, 0.5],
[ 0.5, 0.5, 0.5]
])
Cube=convexFromPoints(unitCubePts)
unitWedgePts=np.asarray([
[-0.5,-0.5,-0.5],
[ 0.5,-0.5,-0.5],
[ 0.0, 0.5,-0.5],
[-0.5,-0.5, 0.5],
[ 0.5,-0.5, 0.5],
[ 0.0, 0.5, 0.5]
])
unitWedge=convexFromPoints(unitWedgePts)
def diskObj(r, h, n=50):
dTh=2*math.pi/n
pts=[]
for i in range(n):
x=r*math.cos(i*dTh); y=r*math.sin(i*dTh)
pts.append( [x,y,-0.5*h] )
pts.append( [x,y, 0.5*h] )
pts=np.asarray(pts)
return convexFromPoints(pts)
# This was published on: https://en.wikipedia.org/wiki/Regular_dodecahedron
# Golden ratio
gr=(1.0+math.sqrt(5.0))/2.0
radiusOneSpherePts=np.asarray([
[-1,-1,-1],[ 1,-1,-1], [-1, 1,-1],[ 1, 1,-1], [-1,-1, 1],[ 1,-1, 1], [-1, 1, 1],[ 1, 1, 1],
[0,-1/gr,-gr],[0, 1/gr,-gr],[0,-1/gr, gr],[0, 1/gr, gr],
[-1/gr,-gr,0],[ 1/gr,-gr,0],[-1/gr, gr,0],[ 1/gr, gr,0],
[-gr,0,-1/gr],[-gr,0, 1/gr],[ gr,0,-1/gr],[ gr,0, 1/gr]
])
radiusOneSphereObj=convexFromPoints(radiusOneSpherePts)
def randSpherePtsFromGaussians(n,rad):
np.random.seed(1)
pts=[]
for i in range(n):
u = np.random.normal(0,1)
v = np.random.normal(0,1)
w = np.random.normal(0,1)
d= math.sqrt(u*u+v*v+w*w)
pts.append( rad*np.asarray([u,v,w])/d )
return pts
def cylObj(x0, x1, r, n=10, lengthSum=None):
sphere0=(r*radiusOneSpherePts)
sphere0[:,0]+=x0[0]; sphere0[:,1]+=x0[1]; sphere0[:,2]+=x0[2];
sphere1=(r*radiusOneSpherePts)
sphere1[:,0]+=x1[0]; sphere1[:,1]+=x1[1]; sphere1[:,2]+=x1[2];
pts=np.vstack( (sphere0, sphere1) )
#print lengthSum
#if (lengthSum != None):
try:
lengthSum[0]+=np.sqrt( np.dot((x1-x0),(x1-x0)) )
except:
pass
#print lengthSum
return convexFromPoints(pts)
# Set up a unit arrow pointing in y-direction
pts1=deepcopy(unitCubePts); pts1[:,1]-=0.5
pts2=deepcopy(unitWedgePts); pts2[:,0]*=2.0; pts2[:,1]+=0.5
unitArrow1=convexFromPoints(pts1)
unitArrow2=convexFromPoints(pts2)
unitArrowY=mergeObj(unitArrow1,unitArrow2)
def extrudePoints(points, disp):
"""
Return a list of points including the initial points and extruded end
"""
farEnd=deepcopy(points)
farEnd[:,0]+=disp[0]
farEnd[:,1]+=disp[1]
farEnd[:,2]+=disp[2]
return np.vstack( (points,farEnd) )
def transObj(object, disp):
"""
Translate an object
"""
return (object[0]+disp,object[1])
def scaleObj(object, scale):
"""
Scale an object
"""
return (object[0]*scale,object[1])
def getPoints(object):
"""
Return the list of points/vertices
"""
return object[0]
def getNPoly(object):
"""
Return the number polygons in the object
"""
return len(object[1])
def getPolyPoints(object, i):
"""
Return the list of points for polygon i
"""
return object[0][object[1][i]]
def getPolyNormal(object, x0, i):
"""
Return the normal to polygon i that points away from x0
"""
pts=getPolyPoints(object,i)
# Note that this normal could be badly behaved if aVec and bVec are close to parallel
aVec=pts[2]-pts[0]
bVec=pts[1]-pts[0]
nVec=np.cross(aVec,bVec)
nVec=nVec/np.linalg.norm(nVec)
# Check if our normal is pointing away from x0
#print 'nVec',nVec
#print 'pts[0]',pts[0]
#print 'x0',x0
if np.dot( nVec, pts[0]-x0 ) > 0.0:
return nVec
else:
return -1.0*nVec
def getPolyArea(object, i):
"""
Return the area of the polygon i
"""
pts = getPolyPoints(object, i)
area=0.0
for j in range(1,len(pts)-1):
#print 'j',j
vtmp = np.cross(pts[j]-pts[0],pts[j+1]-pts[0])
area += 0.5*np.sqrt(np.dot(vtmp,vtmp))
return area
# http://stackoverflow.com/questions/6802577/python-rotation-of-3d-vector
def rotationMatrix(axis, theta):
"""
Return the rotation matrix associated with counterclockwise rotation about
the given axis by theta radians.
"""
axis = np.asarray(axis)
axis = axis/math.sqrt(np.dot(axis, axis))
a = math.cos(theta/2.0)
b, c, d = -axis*math.sin(theta/2.0)
aa, bb, cc, dd = a*a, b*b, c*c, d*d
bc, ad, ac, ab, bd, cd = b*c, a*d, a*c, a*b, b*d, c*d
return np.array([[aa+bb-cc-dd, 2*(bc+ad), 2*(bd-ac)],
[2*(bc-ad), aa+cc-bb-dd, 2*(cd+ab)],
[2*(bd+ac), 2*(cd-ab), aa+dd-bb-cc]])
def rotatePoints(points, axis, theta):
rot=rotationMatrix(axis,theta)
#return rot*points
return np.transpose( np.dot(rot, np.transpose( points ) ) )
def rotateTensor(tensor, axis, theta):
#http://www.continuummechanics.org/stressxforms.html
rot=rotationMatrix(axis,theta)
return np.dot(rot,np.dot(tensor,np.transpose(rot)))
def rotateObj(object, axis, theta):
rot=rotationMatrix(axis,theta)
return ( np.transpose( np.dot(rot, np.transpose(object[0])) ) , object[1])
# This was published by http://geomalgorithms.com/a05-_intersect-1.html
def intersectionOfLineAndPlane(lineX,lineS,planeX,planeN):
V0=np.asarray(planeX)
n=np.asarray(planeN)
P0=np.asarray(lineX)
u=np.asarray(lineS)
sI=( np.dot( n, (V0-P0) ) )/( np.dot( n,u ) )
return P0+sI*u
def distOfIntersectionOfLineAndPlane(lineX,lineS,planeX,planeN):
V0=np.asarray(planeX)
n=np.asarray(planeN)
P0=np.asarray(lineX)
u=np.asarray(lineS)
sI=( np.dot( n, (V0-P0) ) )/( np.dot( n,u ) )
return sI,P0+sI*u
def shortestDistanceBetweenLineSegments( xio,xif, xjo,xjf ):
# Calculate tangents to the line segments
p1=xio; p2=xif
p3=xjo; p4=xjf
# The Python code in this function is based upon C++ code developed by <NAME>.
# The original C++ code had the following request:
# // Copyright 2001 softSurfer, 2012 <NAME>
# // This code may be freely used and modified for any purpose
# // providing that this copyright notice is included with it.
# // SoftSurfer makes no warranty for this code, and cannot be held
# // liable for any real or imagined damage resulting from its use.
# // Users of this code must verify correctness for their application.
u = p1 - p2;
v = p3 - p4;
w = p2 - p4;
a = np.dot(u,u);
b = np.dot(u,v);
c = np.dot(v,v);
d = np.dot(u,w);
e = np.dot(v,w);
D = a*c - b*b;
sD = D;
tD = D;
SMALL_NUM = 0.00000001;
# compute the line parameters of the two closest points
if (D < SMALL_NUM): # the lines are almost parallel
sN = 0.0; # force using point P0 on segment S1
sD = 1.0; # to prevent possible division by 0.0 later
tN = e;
tD = c;
else: # get the closest points on the infinite lines
sN = (b*e - c*d);
tN = (a*e - b*d);
if (sN < 0.0): # sc < 0 => the s=0 edge is visible
sN = 0.0;
tN = e;
tD = c;
elif (sN > sD):# sc > 1 => the s=1 edge is visible
sN = sD;
tN = e + b;
tD = c;
if (tN < 0.0): # tc < 0 => the t=0 edge is visible
tN = 0.0;
# recompute sc for this edge
if (-d < 0.0):
sN = 0.0;
elif (-d > a):
sN = sD;
else:
sN = -d;
sD = a;
elif (tN > tD): # tc > 1 => the t=1 edge is visible
tN = tD;
# recompute sc for this edge
if ((-d + b) < 0.0):
sN = 0;
elif ((-d + b) > a):
sN = sD;
else:
sN = (-d + b);
sD = a;
# finally do the division to get sc and tc
if(abs(sN) < SMALL_NUM):
sc = 0.0;
else:
sc = sN / sD;
if(abs(tN) < SMALL_NUM):
tc = 0.0;
else:
tc = tN / tD;
# get the difference of the two closest points
dP = w + (sc * u) - (tc * v);
distance = np.linalg.norm(dP);
return distance
# Generate a convex hull from points - Not good in general because drifts are not always convex
def pointCloudToConvexPolyhedron(drift_scan, dt, keepFraction=0.01):
np.random.seed(1)
nPoints=len(dt['x'])
pts = []
for i in range(nPoints):
#print "%.1f"%((100.0*i)/nPoints)
if (i%100==0):
sys.stdout.write("Scan progress %d%% \r" % ((100.0*i)/nPoints) )
sys.stdout.flush()
if random.random()<keepFraction:
pts.append( [dt['x'][i],dt['y'][i],dt['z'][i]] )
drift_scan=mergeObj( drift_scan, convexFromPoints( pts ) )
return drift_scan
# Generate a Delaunay triangular mesh from points - Not good on its own because it will not handle concavity
# However, we can prune the larger triangles to recover a resonable representation of a complex tunnel
def pointCloudToDelaunay(drift_scan, dt, keepFraction=0.01):
np.random.seed(1)
nPoints=len(dt['x'])
pts = []
for i in range(nPoints):
#print "%.1f"%((100.0*i)/nPoints)
if (i%100==0):
sys.stdout.write("Scan progress %d%% \r" % ((100.0*i)/nPoints) )
sys.stdout.flush()
if random.random()<keepFraction:
pts.append( [dt['x'][i],dt['y'][i],dt['z'][i]] )
drift_scan=mergeObj( drift_scan, delaunayFromPoints( pts ) )
return drift_scan
# Remove large triangles from an object - we assume we are given a bunch of triangles
# We drop any triangle with at least one side larger than L
def pruneLargeTriangles(obj, L):
pts, simps_in = obj
simps_out = []
nTri = len(simps_in)
for i in range(nTri):
if (i%100==0):
sys.stdout.write("Pruning progress %d%% \r" % ((100.0*i)/nTri) )
sys.stdout.flush()
tri = simps_in[i]
if np.linalg.norm( np.asarray(pts[tri[1]])-np.asarray(pts[tri[0]]) ) > L:
continue
if np.linalg.norm( np.asarray(pts[tri[2]])-np.asarray(pts[tri[1]]) ) > L:
continue
if np.linalg.norm( np.asarray(pts[tri[0]])-np.asarray(pts[tri[2]]) ) > L:
continue
# If we made it this far, the triangle is small enough to keep
simps_out.append( tri )
return (pts, simps_out)
def pointCloudToCubes(drift_scan, dt, keepFraction=0.01, size=0.2):
np.random.seed(1)
#print 'reading from',scanFile
#dt=pd.read_csv(scanFile,usecols=[0,1,2],names=['x','y','z'])
#dt=pd.read_csv(scanFile)
#print dt['x'][:10]
#pts=[]
nPoints=len(dt['x'])
#pntObj=sg.scaleObj(sg.radiusOneSphereObj,[0.1,0.1,0.1])
pntObj=scaleObj(Cube,[size,size,size])
for i in range(nPoints):
#print "%.1f"%((100.0*i)/nPoints)
if (i%100==0):
sys.stdout.write("Scan progress %d%% \r" % ((100.0*i)/nPoints) )
sys.stdout.flush()
if random.random()<keepFraction:
#pts.append( [dt['x'][i],dt['y'][i],dt['z'][i]] )
# Note that this repeated merging is not at all efficient, but it's acceptable performance for the number of points we want to keep
drift_scan=mergeObj(drift_scan,
transObj( pntObj, [dt['x'][i],dt['y'][i],dt['z'][i]] )
)
print('Scan complete')
#pts=np.asarray(pts)
#drift_scan=sg.convexFromPoints(pts) # This turns a list of points into a polyhedron
return drift_scan
def grepPointCloudToCubes(drift_scan, filename, grepString, keepFraction=0.01, size=0.2):
np.random.seed(1)
dt={'x':[],'y':[],'z':[]}
fd=open(filename,'r')
for line in fd:
m = re.match(grepString, line)
if m:
x = float(m.group(1))
y = float(m.group(2))
z = float(m.group(3))
dt['x'].append(x)
dt['y'].append(y)
dt['z'].append(z)
fd.close()
nPoints=len(dt['x'])
#pntObj=sg.scaleObj(sg.radiusOneSphereObj,[0.1,0.1,0.1])
pntObj=scaleObj(Cube,[size,size,size])
for i in range(nPoints):
#print "%.1f"%((100.0*i)/nPoints)
if (i%100==0):
sys.stdout.write("Scan progress %d%% \r" % ((100.0*i)/nPoints) )
sys.stdout.flush()
if random.random()<keepFraction:
#pts.append( [dt['x'][i],dt['y'][i],dt['z'][i]] )
# Note that this repeated merging is not at all efficient, but it's acceptable performance for the number of points we want to keep
drift_scan=mergeObj(drift_scan,
transObj( pntObj, [dt['x'][i],dt['y'][i],dt['z'][i]] )
)
print('Scan complete')
#pts=np.asarray(pts)
#drift_scan=sg.convexFromPoints(pts) # This turns a list of points into a polyhedron
return drift_scan
# From math.stackexchange.com find-shortest-distance-between-lines-in-3d
def shortestDistanceBetweenLines(a,b, c,d):
# a=origin of first line
# b=tangent to first line
# c=origin of second line
# d=tangent to second line
#print "a",a
#print "b",b
#print "c",c
#print "d",d
# t=path length along first line
# s=path length along second line
e=a-c
A = -np.dot(b,b)*np.dot(d,d) + np.dot(b,d)*np.dot(b,d)
# A=0 if the lines are parallel
s = ( -np.dot(b,b)*np.dot(d,e) + np.dot(b,e)*np.dot(d,b) )/A
t = ( np.dot(d,d)*np.dot(b,e) - np.dot(b,e)*np.dot(d,b) )/A
dvect=e+b*t-d*s
dist=np.sqrt( np.dot( dvect, dvect ) )
return dist
# Place a radial hydraulic fracture of radius r at x0
def HF(r,x0, strikeRad, dipRad, h=0.5):
# start with a disk
disk=diskObj(r,h)
disk=rotateObj(disk,[0.0,1.0,0.0],dipRad)
disk=rotateObj(disk,[0.0,0.0,1.0],-strikeRad)
disk=transObj(disk,x0)
return disk
# Look for intersection of ellipses with a line segment
# A line segment is described by:
# - Origin l0
# - Tangent tVec
# - Length l
# An ellipse is described by:
# - Center e0
# - Major axis aVec
# - Minor axis bVec
# Note: These choices of defininition make the calculations more efficient
# First we locate the intersection of the line with the plane of the ellipse
# Then we check if the point of intersection is BOTH
# - Inside the ellipse
# - Inside the line segment
def ellipseIntersectSegmentVect(l0, tVec, l, e0, aVec, bVec):
# Obtain normal to the ellipse (note that we must non-dimensionalize)
aMag=np.linalg.norm(aVec)
aVecN=aVec/aMag
bMag=np.linalg.norm(bVec)
bVecN=bVec/bMag
nVec=np.cross(aVecN,bVecN)
# Location of intersection along the length of the line segment:
s,xInt=distOfIntersectionOfLineAndPlane(lineX=l0,lineS=tVec,planeX=e0,planeN=nVec)
# These will later be set to the distances along the a- and b-axes
aa=np.Inf; bb=np.Inf
if s<0.0 or s>l:
# The point of intersection lies outside the line segment
return False,s,aa,bb,xInt
# The intersection is within the line segment
# Is the intersection inside the ellipse?
# Need to obtain the projection of the point of intersection onto the aVec and bVec directions
aa=np.dot((xInt-e0),aVecN)
bb=np.dot((xInt-e0),bVecN)
if aa*aa/(aMag*aMag)+bb*bb/(bMag*bMag) > 1.0:
# We are outside the ellipse
return False,s,aa,bb,xInt
# If we made it this far we are inside the ellipse and the line segment
return True,s,aa,bb,xInt
def ellipseIntersectSegmentEndPts(x0, x1, e0, aVec, bVec):
l0=x0
tVec=x1-x0
l=np.linalg.norm(tVec)
tVec=tVec/l
return ellipseIntersectSegmentVect(l0, tVec, l, e0, aVec, bVec)
def diskIntersectSegmentEndPts(x0, x1, c0, strikeDeg, dipDeg, r):
# Convert our disk into an equivalent ellipse
aVec, bVec=strikeDipToAxes(strikeDeg,dipDeg,r)
intersects,s,aa,bb,xInt=ellipseIntersectSegmentEndPts(x0, x1, c0, aVec, bVec)
return intersects,xInt
# Convert strike and dip into major and minor axes of an ellipse
def strikeDipToAxes(strikeDeg,dipDeg,radius):
strikeRad=degToRad(strikeDeg)
dipRad=degToRad(dipDeg)
aVec=rotatePoints( [0.0,radius,0.0], [0.0,0.0,1.0], -strikeRad )
bVec=rotatePoints( [0.0,0.0,radius], aVec, dipRad+0.5*np.pi )
return aVec, bVec
| [
"math.sqrt",
"math.cos",
"numpy.array",
"numpy.linalg.norm",
"copy.deepcopy",
"numpy.cross",
"numpy.asarray",
"numpy.dot",
"numpy.random.seed",
"numpy.vstack",
"sys.stdout.flush",
"numpy.random.normal",
"re.match",
"scipy.spatial.ConvexHull",
"math.atan2",
"numpy.transpose",
"scipy.s... | [((8328, 8496), 'numpy.asarray', 'np.asarray', (['[[-0.5, -0.5, -0.5], [0.5, -0.5, -0.5], [-0.5, 0.5, -0.5], [0.5, 0.5, -0.5],\n [-0.5, -0.5, 0.5], [0.5, -0.5, 0.5], [-0.5, 0.5, 0.5], [0.5, 0.5, 0.5]]'], {}), '([[-0.5, -0.5, -0.5], [0.5, -0.5, -0.5], [-0.5, 0.5, -0.5], [0.5,\n 0.5, -0.5], [-0.5, -0.5, 0.5], [0.5, -0.5, 0.5], [-0.5, 0.5, 0.5], [0.5,\n 0.5, 0.5]])\n', (8338, 8496), True, 'import numpy as np\n'), ((8571, 8698), 'numpy.asarray', 'np.asarray', (['[[-0.5, -0.5, -0.5], [0.5, -0.5, -0.5], [0.0, 0.5, -0.5], [-0.5, -0.5, 0.5],\n [0.5, -0.5, 0.5], [0.0, 0.5, 0.5]]'], {}), '([[-0.5, -0.5, -0.5], [0.5, -0.5, -0.5], [0.0, 0.5, -0.5], [-0.5,\n -0.5, 0.5], [0.5, -0.5, 0.5], [0.0, 0.5, 0.5]])\n', (8581, 8698), True, 'import numpy as np\n'), ((9158, 9502), 'numpy.asarray', 'np.asarray', (['[[-1, -1, -1], [1, -1, -1], [-1, 1, -1], [1, 1, -1], [-1, -1, 1], [1, -1, 1\n ], [-1, 1, 1], [1, 1, 1], [0, -1 / gr, -gr], [0, 1 / gr, -gr], [0, -1 /\n gr, gr], [0, 1 / gr, gr], [-1 / gr, -gr, 0], [1 / gr, -gr, 0], [-1 / gr,\n gr, 0], [1 / gr, gr, 0], [-gr, 0, -1 / gr], [-gr, 0, 1 / gr], [gr, 0, -\n 1 / gr], [gr, 0, 1 / gr]]'], {}), '([[-1, -1, -1], [1, -1, -1], [-1, 1, -1], [1, 1, -1], [-1, -1, 1],\n [1, -1, 1], [-1, 1, 1], [1, 1, 1], [0, -1 / gr, -gr], [0, 1 / gr, -gr],\n [0, -1 / gr, gr], [0, 1 / gr, gr], [-1 / gr, -gr, 0], [1 / gr, -gr, 0],\n [-1 / gr, gr, 0], [1 / gr, gr, 0], [-gr, 0, -1 / gr], [-gr, 0, 1 / gr],\n [gr, 0, -1 / gr], [gr, 0, 1 / gr]])\n', (9168, 9502), True, 'import numpy as np\n'), ((10345, 10366), 'copy.deepcopy', 'deepcopy', (['unitCubePts'], {}), '(unitCubePts)\n', (10353, 10366), False, 'from copy import deepcopy\n'), ((10388, 10410), 'copy.deepcopy', 'deepcopy', (['unitWedgePts'], {}), '(unitWedgePts)\n', (10396, 10410), False, 'from copy import deepcopy\n'), ((938, 954), 'math.atan2', 'math.atan2', (['y', 'x'], {}), '(y, x)\n', (948, 954), False, 'import math\n'), ((2302, 2329), 'numpy.asarray', 'np.asarray', (['[0.0, 1.0, 0.0]'], {}), '([0.0, 1.0, 0.0])\n', (2312, 2329), True, 'import numpy as np\n'), ((7342, 7360), 'scipy.spatial.ConvexHull', 'ConvexHull', (['points'], {}), '(points)\n', (7352, 7360), False, 'from scipy.spatial import ConvexHull\n'), ((8970, 8985), 'numpy.asarray', 'np.asarray', (['pts'], {}), '(pts)\n', (8980, 8985), True, 'import numpy as np\n'), ((9556, 9573), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (9570, 9573), True, 'import numpy as np\n'), ((10066, 10095), 'numpy.vstack', 'np.vstack', (['(sphere0, sphere1)'], {}), '((sphere0, sphere1))\n', (10075, 10095), True, 'import numpy as np\n'), ((10689, 10705), 'copy.deepcopy', 'deepcopy', (['points'], {}), '(points)\n', (10697, 10705), False, 'from copy import deepcopy\n'), ((10792, 10819), 'numpy.vstack', 'np.vstack', (['(points, farEnd)'], {}), '((points, farEnd))\n', (10801, 10819), True, 'import numpy as np\n'), ((11658, 11678), 'numpy.cross', 'np.cross', (['aVec', 'bVec'], {}), '(aVec, bVec)\n', (11666, 11678), True, 'import numpy as np\n'), ((12483, 12499), 'numpy.asarray', 'np.asarray', (['axis'], {}), '(axis)\n', (12493, 12499), True, 'import numpy as np\n'), ((12554, 12575), 'math.cos', 'math.cos', (['(theta / 2.0)'], {}), '(theta / 2.0)\n', (12562, 12575), False, 'import math\n'), ((12723, 12894), 'numpy.array', 'np.array', (['[[aa + bb - cc - dd, 2 * (bc + ad), 2 * (bd - ac)], [2 * (bc - ad), aa + cc -\n bb - dd, 2 * (cd + ab)], [2 * (bd + ac), 2 * (cd - ab), aa + dd - bb - cc]]'], {}), '([[aa + bb - cc - dd, 2 * (bc + ad), 2 * (bd - ac)], [2 * (bc - ad),\n aa + cc - bb - dd, 2 * (cd + ab)], [2 * (bd + ac), 2 * (cd - ab), aa +\n dd - bb - cc]])\n', (12731, 12894), True, 'import numpy as np\n'), ((13531, 13549), 'numpy.asarray', 'np.asarray', (['planeX'], {}), '(planeX)\n', (13541, 13549), True, 'import numpy as np\n'), ((13556, 13574), 'numpy.asarray', 'np.asarray', (['planeN'], {}), '(planeN)\n', (13566, 13574), True, 'import numpy as np\n'), ((13582, 13599), 'numpy.asarray', 'np.asarray', (['lineX'], {}), '(lineX)\n', (13592, 13599), True, 'import numpy as np\n'), ((13606, 13623), 'numpy.asarray', 'np.asarray', (['lineS'], {}), '(lineS)\n', (13616, 13623), True, 'import numpy as np\n'), ((13765, 13783), 'numpy.asarray', 'np.asarray', (['planeX'], {}), '(planeX)\n', (13775, 13783), True, 'import numpy as np\n'), ((13790, 13808), 'numpy.asarray', 'np.asarray', (['planeN'], {}), '(planeN)\n', (13800, 13808), True, 'import numpy as np\n'), ((13816, 13833), 'numpy.asarray', 'np.asarray', (['lineX'], {}), '(lineX)\n', (13826, 13833), True, 'import numpy as np\n'), ((13840, 13857), 'numpy.asarray', 'np.asarray', (['lineS'], {}), '(lineS)\n', (13850, 13857), True, 'import numpy as np\n'), ((14680, 14692), 'numpy.dot', 'np.dot', (['u', 'u'], {}), '(u, u)\n', (14686, 14692), True, 'import numpy as np\n'), ((14701, 14713), 'numpy.dot', 'np.dot', (['u', 'v'], {}), '(u, v)\n', (14707, 14713), True, 'import numpy as np\n'), ((14722, 14734), 'numpy.dot', 'np.dot', (['v', 'v'], {}), '(v, v)\n', (14728, 14734), True, 'import numpy as np\n'), ((14743, 14755), 'numpy.dot', 'np.dot', (['u', 'w'], {}), '(u, w)\n', (14749, 14755), True, 'import numpy as np\n'), ((14764, 14776), 'numpy.dot', 'np.dot', (['v', 'w'], {}), '(v, w)\n', (14770, 14776), True, 'import numpy as np\n'), ((16369, 16387), 'numpy.linalg.norm', 'np.linalg.norm', (['dP'], {}), '(dP)\n', (16383, 16387), True, 'import numpy as np\n'), ((16581, 16598), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (16595, 16598), True, 'import numpy as np\n'), ((17306, 17323), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (17320, 17323), True, 'import numpy as np\n'), ((18701, 18718), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (18715, 18718), True, 'import numpy as np\n'), ((19900, 19917), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (19914, 19917), True, 'import numpy as np\n'), ((22795, 22815), 'numpy.linalg.norm', 'np.linalg.norm', (['aVec'], {}), '(aVec)\n', (22809, 22815), True, 'import numpy as np\n'), ((22845, 22865), 'numpy.linalg.norm', 'np.linalg.norm', (['bVec'], {}), '(bVec)\n', (22859, 22865), True, 'import numpy as np\n'), ((22895, 22917), 'numpy.cross', 'np.cross', (['aVecN', 'bVecN'], {}), '(aVecN, bVecN)\n', (22903, 22917), True, 'import numpy as np\n'), ((23492, 23516), 'numpy.dot', 'np.dot', (['(xInt - e0)', 'aVecN'], {}), '(xInt - e0, aVecN)\n', (23498, 23516), True, 'import numpy as np\n'), ((23523, 23547), 'numpy.dot', 'np.dot', (['(xInt - e0)', 'bVecN'], {}), '(xInt - e0, bVecN)\n', (23529, 23547), True, 'import numpy as np\n'), ((23864, 23884), 'numpy.linalg.norm', 'np.linalg.norm', (['tVec'], {}), '(tVec)\n', (23878, 23884), True, 'import numpy as np\n'), ((7869, 7898), 'numpy.vstack', 'np.vstack', (['(obj1[0], obj2[0])'], {}), '((obj1[0], obj2[0]))\n', (7878, 7898), True, 'import numpy as np\n'), ((8031, 8051), 'copy.deepcopy', 'deepcopy', (['objects[0]'], {}), '(objects[0])\n', (8039, 8051), False, 'from copy import deepcopy\n'), ((8164, 8205), 'numpy.vstack', 'np.vstack', (['(merged[0], objects[i + 1][0])'], {}), '((merged[0], objects[i + 1][0]))\n', (8173, 8205), True, 'import numpy as np\n'), ((8223, 8273), 'numpy.vstack', 'np.vstack', (['(merged[1], objects[i + 1][1] + nShift)'], {}), '((merged[1], objects[i + 1][1] + nShift))\n', (8232, 8273), True, 'import numpy as np\n'), ((9119, 9133), 'math.sqrt', 'math.sqrt', (['(5.0)'], {}), '(5.0)\n', (9128, 9133), False, 'import math\n'), ((9620, 9642), 'numpy.random.normal', 'np.random.normal', (['(0)', '(1)'], {}), '(0, 1)\n', (9636, 9642), True, 'import numpy as np\n'), ((9654, 9676), 'numpy.random.normal', 'np.random.normal', (['(0)', '(1)'], {}), '(0, 1)\n', (9670, 9676), True, 'import numpy as np\n'), ((9688, 9710), 'numpy.random.normal', 'np.random.normal', (['(0)', '(1)'], {}), '(0, 1)\n', (9704, 9710), True, 'import numpy as np\n'), ((9721, 9753), 'math.sqrt', 'math.sqrt', (['(u * u + v * v + w * w)'], {}), '(u * u + v * v + w * w)\n', (9730, 9753), False, 'import math\n'), ((11692, 11712), 'numpy.linalg.norm', 'np.linalg.norm', (['nVec'], {}), '(nVec)\n', (11706, 11712), True, 'import numpy as np\n'), ((11840, 11865), 'numpy.dot', 'np.dot', (['nVec', '(pts[0] - x0)'], {}), '(nVec, pts[0] - x0)\n', (11846, 11865), True, 'import numpy as np\n'), ((12128, 12174), 'numpy.cross', 'np.cross', (['(pts[j] - pts[0])', '(pts[j + 1] - pts[0])'], {}), '(pts[j] - pts[0], pts[j + 1] - pts[0])\n', (12136, 12174), True, 'import numpy as np\n'), ((12594, 12615), 'math.sin', 'math.sin', (['(theta / 2.0)'], {}), '(theta / 2.0)\n', (12602, 12615), False, 'import math\n'), ((13633, 13651), 'numpy.dot', 'np.dot', (['n', '(V0 - P0)'], {}), '(n, V0 - P0)\n', (13639, 13651), True, 'import numpy as np\n'), ((13658, 13670), 'numpy.dot', 'np.dot', (['n', 'u'], {}), '(n, u)\n', (13664, 13670), True, 'import numpy as np\n'), ((13867, 13885), 'numpy.dot', 'np.dot', (['n', '(V0 - P0)'], {}), '(n, V0 - P0)\n', (13873, 13885), True, 'import numpy as np\n'), ((13892, 13904), 'numpy.dot', 'np.dot', (['n', 'u'], {}), '(n, u)\n', (13898, 13904), True, 'import numpy as np\n'), ((20006, 20032), 're.match', 're.match', (['grepString', 'line'], {}), '(grepString, line)\n', (20014, 20032), False, 'import re\n'), ((21837, 21857), 'numpy.dot', 'np.dot', (['dvect', 'dvect'], {}), '(dvect, dvect)\n', (21843, 21857), True, 'import numpy as np\n'), ((2365, 2386), 'numpy.asarray', 'np.asarray', (['[1, 0, 0]'], {}), '([1, 0, 0])\n', (2375, 2386), True, 'import numpy as np\n'), ((2473, 2494), 'numpy.asarray', 'np.asarray', (['[0, 0, 1]'], {}), '([0, 0, 1])\n', (2483, 2494), True, 'import numpy as np\n'), ((3009, 3021), 'numpy.dot', 'np.dot', (['v', 'v'], {}), '(v, v)\n', (3015, 3021), True, 'import numpy as np\n'), ((7523, 7539), 'scipy.spatial.Delaunay', 'Delaunay', (['points'], {}), '(points)\n', (7531, 7539), False, 'from scipy.spatial import Delaunay\n'), ((8855, 8872), 'math.cos', 'math.cos', (['(i * dTh)'], {}), '(i * dTh)\n', (8863, 8872), False, 'import math\n'), ((8876, 8893), 'math.sin', 'math.sin', (['(i * dTh)'], {}), '(i * dTh)\n', (8884, 8893), False, 'import math\n'), ((10188, 10212), 'numpy.dot', 'np.dot', (['(x1 - x0)', '(x1 - x0)'], {}), '(x1 - x0, x1 - x0)\n', (10194, 10212), True, 'import numpy as np\n'), ((12526, 12544), 'numpy.dot', 'np.dot', (['axis', 'axis'], {}), '(axis, axis)\n', (12532, 12544), True, 'import numpy as np\n'), ((13022, 13042), 'numpy.transpose', 'np.transpose', (['points'], {}), '(points)\n', (13034, 13042), True, 'import numpy as np\n'), ((13217, 13234), 'numpy.transpose', 'np.transpose', (['rot'], {}), '(rot)\n', (13229, 13234), True, 'import numpy as np\n'), ((16743, 16810), 'sys.stdout.write', 'sys.stdout.write', (["('Scan progress %d%% \\r' % (100.0 * i / nPoints))"], {}), "('Scan progress %d%% \\r' % (100.0 * i / nPoints))\n", (16759, 16810), False, 'import sys\n'), ((16822, 16840), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (16838, 16840), False, 'import sys\n'), ((16852, 16867), 'random.random', 'random.random', ([], {}), '()\n', (16865, 16867), False, 'import random\n'), ((17468, 17535), 'sys.stdout.write', 'sys.stdout.write', (["('Scan progress %d%% \\r' % (100.0 * i / nPoints))"], {}), "('Scan progress %d%% \\r' % (100.0 * i / nPoints))\n", (17484, 17535), False, 'import sys\n'), ((17547, 17565), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (17563, 17565), False, 'import sys\n'), ((17577, 17592), 'random.random', 'random.random', ([], {}), '()\n', (17590, 17592), False, 'import random\n'), ((18064, 18131), 'sys.stdout.write', 'sys.stdout.write', (["('Pruning progress %d%% \\r' % (100.0 * i / nTri))"], {}), "('Pruning progress %d%% \\r' % (100.0 * i / nTri))\n", (18080, 18131), False, 'import sys\n'), ((18143, 18161), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (18159, 18161), False, 'import sys\n'), ((19121, 19188), 'sys.stdout.write', 'sys.stdout.write', (["('Scan progress %d%% \\r' % (100.0 * i / nPoints))"], {}), "('Scan progress %d%% \\r' % (100.0 * i / nPoints))\n", (19137, 19188), False, 'import sys\n'), ((19200, 19218), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (19216, 19218), False, 'import sys\n'), ((19230, 19245), 'random.random', 'random.random', ([], {}), '()\n', (19243, 19245), False, 'import random\n'), ((20489, 20556), 'sys.stdout.write', 'sys.stdout.write', (["('Scan progress %d%% \\r' % (100.0 * i / nPoints))"], {}), "('Scan progress %d%% \\r' % (100.0 * i / nPoints))\n", (20505, 20556), False, 'import sys\n'), ((20568, 20586), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (20584, 20586), False, 'import sys\n'), ((20598, 20613), 'random.random', 'random.random', ([], {}), '()\n', (20611, 20613), False, 'import random\n'), ((21587, 21599), 'numpy.dot', 'np.dot', (['d', 'd'], {}), '(d, d)\n', (21593, 21599), True, 'import numpy as np\n'), ((21601, 21613), 'numpy.dot', 'np.dot', (['b', 'd'], {}), '(b, d)\n', (21607, 21613), True, 'import numpy as np\n'), ((21613, 21625), 'numpy.dot', 'np.dot', (['b', 'd'], {}), '(b, d)\n', (21619, 21625), True, 'import numpy as np\n'), ((1164, 1188), 'math.sqrt', 'math.sqrt', (['(e * e + n * n)'], {}), '(e * e + n * n)\n', (1173, 1188), False, 'import math\n'), ((12196, 12214), 'numpy.dot', 'np.dot', (['vtmp', 'vtmp'], {}), '(vtmp, vtmp)\n', (12202, 12214), True, 'import numpy as np\n'), ((13352, 13375), 'numpy.transpose', 'np.transpose', (['object[0]'], {}), '(object[0])\n', (13364, 13375), True, 'import numpy as np\n'), ((21575, 21587), 'numpy.dot', 'np.dot', (['b', 'b'], {}), '(b, b)\n', (21581, 21587), True, 'import numpy as np\n'), ((21690, 21702), 'numpy.dot', 'np.dot', (['d', 'e'], {}), '(d, e)\n', (21696, 21702), True, 'import numpy as np\n'), ((21704, 21716), 'numpy.dot', 'np.dot', (['b', 'e'], {}), '(b, e)\n', (21710, 21716), True, 'import numpy as np\n'), ((21716, 21728), 'numpy.dot', 'np.dot', (['d', 'b'], {}), '(d, b)\n', (21722, 21728), True, 'import numpy as np\n'), ((21743, 21755), 'numpy.dot', 'np.dot', (['d', 'd'], {}), '(d, d)\n', (21749, 21755), True, 'import numpy as np\n'), ((21755, 21767), 'numpy.dot', 'np.dot', (['b', 'e'], {}), '(b, e)\n', (21761, 21767), True, 'import numpy as np\n'), ((21769, 21781), 'numpy.dot', 'np.dot', (['b', 'e'], {}), '(b, e)\n', (21775, 21781), True, 'import numpy as np\n'), ((21781, 21793), 'numpy.dot', 'np.dot', (['d', 'b'], {}), '(d, b)\n', (21787, 21793), True, 'import numpy as np\n'), ((2769, 2791), 'math.atan2', 'math.atan2', (['v[1]', 'v[0]'], {}), '(v[1], v[0])\n', (2779, 2791), False, 'import math\n'), ((2895, 2931), 'math.sqrt', 'math.sqrt', (['(v[0] * v[0] + v[1] * v[1])'], {}), '(v[0] * v[0] + v[1] * v[1])\n', (2904, 2931), False, 'import math\n'), ((9768, 9789), 'numpy.asarray', 'np.asarray', (['[u, v, w]'], {}), '([u, v, w])\n', (9778, 9789), True, 'import numpy as np\n'), ((18215, 18238), 'numpy.asarray', 'np.asarray', (['pts[tri[1]]'], {}), '(pts[tri[1]])\n', (18225, 18238), True, 'import numpy as np\n'), ((18239, 18262), 'numpy.asarray', 'np.asarray', (['pts[tri[0]]'], {}), '(pts[tri[0]])\n', (18249, 18262), True, 'import numpy as np\n'), ((18318, 18341), 'numpy.asarray', 'np.asarray', (['pts[tri[2]]'], {}), '(pts[tri[2]])\n', (18328, 18341), True, 'import numpy as np\n'), ((18342, 18365), 'numpy.asarray', 'np.asarray', (['pts[tri[1]]'], {}), '(pts[tri[1]])\n', (18352, 18365), True, 'import numpy as np\n'), ((18421, 18444), 'numpy.asarray', 'np.asarray', (['pts[tri[0]]'], {}), '(pts[tri[0]])\n', (18431, 18444), True, 'import numpy as np\n'), ((18445, 18468), 'numpy.asarray', 'np.asarray', (['pts[tri[2]]'], {}), '(pts[tri[2]])\n', (18455, 18468), True, 'import numpy as np\n'), ((21678, 21690), 'numpy.dot', 'np.dot', (['b', 'b'], {}), '(b, b)\n', (21684, 21690), True, 'import numpy as np\n')] |
import numpy as np
from pommerman.constants import Item
from util.analytics import Stopwatch
def transform_observation(obs, p_obs=False, centralized=False):
"""
Transform a singular observation of the board into a stack of
binary planes.
:param obs: The observation containing the board
:param p_obs: Whether the observation is partially observable
:param centralized: Whether we want the fully observable board to centralize
:return: A stack of binary planes
"""
features = {}
board = obs['board']
plane_type=np.float64
planes = [ # Index
np.isin(board, Item.Passage.value).astype(plane_type), # 0
np.isin(board, Item.Rigid.value).astype(plane_type), # 1
np.isin(board, Item.Wood.value).astype(plane_type), # 2
np.isin(board, Item.Bomb.value).astype(plane_type), # 3
np.isin(board, Item.Flames.value).astype(plane_type), # 4
np.isin(board, Item.ExtraBomb.value).astype(plane_type), # 5
np.isin(board, Item.IncrRange.value).astype(plane_type), # 6
np.isin(board, Item.Kick.value).astype(plane_type), # 7
np.isin(board, Item.Agent0.value).astype(plane_type), # 8
np.isin(board, Item.Agent1.value).astype(plane_type), # 9
np.isin(board, Item.Agent2.value).astype(plane_type), # 10
np.isin(board, Item.Agent3.value).astype(plane_type), # 11
obs['flame_life'].astype(plane_type),
obs['bomb_life'].astype(plane_type)
#np.isin(board, Item.Fog.value).astype(np.uint8) # 12
]
if p_obs:
planes = _centralize_planes_partial(planes, obs['position'])
elif centralized:
planes = _centralize_planes(planes, obs['position'])
transformed = np.stack(planes, axis=-1)
transformed = np.moveaxis(transformed, -1, 0) # move channel dimension to front (pytorch expects this)
features['board'] = transformed
return transformed
def _centralize_planes(planes, pos):
b_size = planes[0].shape[0]
central_b_size = 2 * b_size - 1
centralized_planes = []
for p in planes:
central = np.zeros((central_b_size, central_b_size))
start = ((b_size - 1) - pos[0], (b_size - 1) - pos[1])
central[start[0]:start[0] + b_size, start[1]:start[1] + b_size] = p
centralized_planes.append(central)
outside_board = np.zeros((central_b_size, central_b_size))
outside_board[max((b_size - 1) - pos[0], 0):min(max((b_size - 1) - pos[0], 0) + b_size, central_b_size),
max((b_size - 1) - pos[1], 0):min(max((b_size - 1) - pos[1], 0) + b_size, central_b_size)] = np.ones(
(b_size, b_size))
centralized_planes.append(outside_board)
return centralized_planes
def _centralize_planes_partial(planes, pos):
b_size = 5
central_b_size = 2 * b_size - 1
partial_planes = []
board_length = len(planes[0][0])
for p in planes:
partial = np.zeros((central_b_size, central_b_size))
partial[max((b_size-1) - pos[0], 0):min(board_length - pos[0] + b_size-1, central_b_size),
max((b_size-1) - pos[1], 0):min(board_length - pos[1] + b_size-1, central_b_size)] = \
p[max(pos[0] - (b_size - 1), 0):min(board_length, pos[0] + (b_size)),
max(pos[1] - (b_size - 1), 0):min(board_length, pos[1] + (b_size))]
partial_planes.append(partial)
outside_board = np.zeros((central_b_size, central_b_size))
outside_board[max((b_size-1) - pos[0], 0):min(max((b_size-1) - pos[0], 0) + b_size, central_b_size),
max((b_size-1) - pos[1], 0):min(max((b_size-1) - pos[1], 0) + b_size, central_b_size)] = np.ones((b_size, b_size))
partial_planes.append(outside_board)
return partial_planes
def transform_observation_centralized(obs):
return transform_observation(obs, p_obs=False, centralized=True)
def transform_observation_partial(obs):
return transform_observation(obs, p_obs=True)
def transform_observation_simple(obs):
return transform_observation(obs)
def calc_dist(agent_ind, nobs, teammate_ind=-1):
other_inds = [i for i in range(0, len(nobs))]
other_inds.remove(agent_ind)
if teammate_ind != -1:
other_inds.remove(teammate_ind)
dist = np.min(
[np.sqrt(np.sum(np.power(np.array(nobs[agent_ind]['position']) - np.array(nobs[ind]['position']), 2))) for ind
in other_inds])
dist = max(1.0, dist)
return dist
def merge_views(first: np.array, second: np.array, fov: np.array, forgetfullness: float=0.0):
"""
Merge the first and second view in the field of view and forget data
outside of it.
:param first: A numpy array respresenting the first view
:param second: A numpy array respresenting the second view
:param fov: A binary numpy array respresenting the field of view
:param forgetfullness: A value ranging from 0.0 to 1.0 that reduces
values outside the field of view.
"""
assert first.shape == second.shape == fov.shape, f"Shapes of planes to merge must match exactly, but first is {first.shape}, second is {second.shape} and fov is {fov.shape}"
assert forgetfullness >= 0.0 and forgetfullness <= 1.0, "forgetfullness must be a value in the range 0.0 to 1.0"
remembrance=1-forgetfullness
fog = 1-fov
merged = second*fov + first*fog*remembrance
return merged | [
"numpy.ones",
"numpy.isin",
"numpy.stack",
"numpy.zeros",
"numpy.array",
"numpy.moveaxis"
] | [((1877, 1902), 'numpy.stack', 'np.stack', (['planes'], {'axis': '(-1)'}), '(planes, axis=-1)\n', (1885, 1902), True, 'import numpy as np\n'), ((1922, 1953), 'numpy.moveaxis', 'np.moveaxis', (['transformed', '(-1)', '(0)'], {}), '(transformed, -1, 0)\n', (1933, 1953), True, 'import numpy as np\n'), ((2506, 2548), 'numpy.zeros', 'np.zeros', (['(central_b_size, central_b_size)'], {}), '((central_b_size, central_b_size))\n', (2514, 2548), True, 'import numpy as np\n'), ((2757, 2782), 'numpy.ones', 'np.ones', (['(b_size, b_size)'], {}), '((b_size, b_size))\n', (2764, 2782), True, 'import numpy as np\n'), ((3543, 3585), 'numpy.zeros', 'np.zeros', (['(central_b_size, central_b_size)'], {}), '((central_b_size, central_b_size))\n', (3551, 3585), True, 'import numpy as np\n'), ((3790, 3815), 'numpy.ones', 'np.ones', (['(b_size, b_size)'], {}), '((b_size, b_size))\n', (3797, 3815), True, 'import numpy as np\n'), ((2255, 2297), 'numpy.zeros', 'np.zeros', (['(central_b_size, central_b_size)'], {}), '((central_b_size, central_b_size))\n', (2263, 2297), True, 'import numpy as np\n'), ((3077, 3119), 'numpy.zeros', 'np.zeros', (['(central_b_size, central_b_size)'], {}), '((central_b_size, central_b_size))\n', (3085, 3119), True, 'import numpy as np\n'), ((671, 705), 'numpy.isin', 'np.isin', (['board', 'Item.Passage.value'], {}), '(board, Item.Passage.value)\n', (678, 705), True, 'import numpy as np\n'), ((742, 774), 'numpy.isin', 'np.isin', (['board', 'Item.Rigid.value'], {}), '(board, Item.Rigid.value)\n', (749, 774), True, 'import numpy as np\n'), ((813, 844), 'numpy.isin', 'np.isin', (['board', 'Item.Wood.value'], {}), '(board, Item.Wood.value)\n', (820, 844), True, 'import numpy as np\n'), ((884, 915), 'numpy.isin', 'np.isin', (['board', 'Item.Bomb.value'], {}), '(board, Item.Bomb.value)\n', (891, 915), True, 'import numpy as np\n'), ((955, 988), 'numpy.isin', 'np.isin', (['board', 'Item.Flames.value'], {}), '(board, Item.Flames.value)\n', (962, 988), True, 'import numpy as np\n'), ((1026, 1062), 'numpy.isin', 'np.isin', (['board', 'Item.ExtraBomb.value'], {}), '(board, Item.ExtraBomb.value)\n', (1033, 1062), True, 'import numpy as np\n'), ((1097, 1133), 'numpy.isin', 'np.isin', (['board', 'Item.IncrRange.value'], {}), '(board, Item.IncrRange.value)\n', (1104, 1133), True, 'import numpy as np\n'), ((1168, 1199), 'numpy.isin', 'np.isin', (['board', 'Item.Kick.value'], {}), '(board, Item.Kick.value)\n', (1175, 1199), True, 'import numpy as np\n'), ((1239, 1272), 'numpy.isin', 'np.isin', (['board', 'Item.Agent0.value'], {}), '(board, Item.Agent0.value)\n', (1246, 1272), True, 'import numpy as np\n'), ((1310, 1343), 'numpy.isin', 'np.isin', (['board', 'Item.Agent1.value'], {}), '(board, Item.Agent1.value)\n', (1317, 1343), True, 'import numpy as np\n'), ((1381, 1414), 'numpy.isin', 'np.isin', (['board', 'Item.Agent2.value'], {}), '(board, Item.Agent2.value)\n', (1388, 1414), True, 'import numpy as np\n'), ((1453, 1486), 'numpy.isin', 'np.isin', (['board', 'Item.Agent3.value'], {}), '(board, Item.Agent3.value)\n', (1460, 1486), True, 'import numpy as np\n'), ((4445, 4482), 'numpy.array', 'np.array', (["nobs[agent_ind]['position']"], {}), "(nobs[agent_ind]['position'])\n", (4453, 4482), True, 'import numpy as np\n'), ((4485, 4516), 'numpy.array', 'np.array', (["nobs[ind]['position']"], {}), "(nobs[ind]['position'])\n", (4493, 4516), True, 'import numpy as np\n')] |
import gym
import numpy as np
class SpaceWrapper:
def __init__(self, space):
if isinstance(space, gym.spaces.Discrete):
self.shape = ()
self.dtype = np.dtype(np.int64)
elif isinstance(space, gym.spaces.Box):
self.shape = space.shape
self.dtype = np.dtype(space.dtype)
else:
assert False, "ProcVectorEnv only support Box and Discrete types"
| [
"numpy.dtype"
] | [((187, 205), 'numpy.dtype', 'np.dtype', (['np.int64'], {}), '(np.int64)\n', (195, 205), True, 'import numpy as np\n'), ((316, 337), 'numpy.dtype', 'np.dtype', (['space.dtype'], {}), '(space.dtype)\n', (324, 337), True, 'import numpy as np\n')] |
import numpy as np
import torch.nn.functional as F
import math
from torchvision import transforms
import torch
import cv2
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.patches as patches
matplotlib.use('agg')
MAPS = ['map3','map4']
Scales = [0.9, 1.1]
MIN_HW = 384
MAX_HW = 1584
IM_NORM_MEAN = [0.485, 0.456, 0.406]
IM_NORM_STD = [0.229, 0.224, 0.225]
def select_exemplar_rois(image):
all_rois = []
print("Press 'q' or Esc to quit. Press 'n' and then use mouse drag to draw a new examplar, 'space' to save.")
while True:
key = cv2.waitKey(1) & 0xFF
if key == 27 or key == ord('q'):
break
elif key == ord('n') or key == '\r':
rect = cv2.selectROI("image", image, False, False)
x1 = rect[0]
y1 = rect[1]
x2 = x1 + rect[2] - 1
y2 = y1 + rect[3] - 1
all_rois.append([y1, x1, y2, x2])
for rect in all_rois:
y1, x1, y2, x2 = rect
cv2.rectangle(image, (x1, y1), (x2, y2), (255, 0, 0), 2)
print("Press q or Esc to quit. Press 'n' and then use mouse drag to draw a new examplar")
return all_rois
def matlab_style_gauss2D(shape=(3,3),sigma=0.5):
"""
2D gaussian mask - should give the same result as MATLAB's
fspecial('gaussian',[shape],[sigma])
"""
m,n = [(ss-1.)/2. for ss in shape]
y,x = np.ogrid[-m:m+1,-n:n+1]
h = np.exp( -(x*x + y*y) / (2.*sigma*sigma) )
h[ h < np.finfo(h.dtype).eps*h.max() ] = 0
sumh = h.sum()
if sumh != 0:
h /= sumh
return h
def PerturbationLoss(output,boxes,sigma=8, use_gpu=True):
Loss = 0.
if boxes.shape[1] > 1:
boxes = boxes.squeeze()
for tempBoxes in boxes.squeeze():
y1 = int(tempBoxes[1])
y2 = int(tempBoxes[3])
x1 = int(tempBoxes[2])
x2 = int(tempBoxes[4])
out = output[:,:,y1:y2,x1:x2]
GaussKernel = matlab_style_gauss2D(shape=(out.shape[2],out.shape[3]),sigma=sigma)
GaussKernel = torch.from_numpy(GaussKernel).float()
if use_gpu: GaussKernel = GaussKernel.cuda()
Loss += F.mse_loss(out.squeeze(),GaussKernel)
else:
boxes = boxes.squeeze()
y1 = int(boxes[1])
y2 = int(boxes[3])
x1 = int(boxes[2])
x2 = int(boxes[4])
out = output[:,:,y1:y2,x1:x2]
Gauss = matlab_style_gauss2D(shape=(out.shape[2],out.shape[3]),sigma=sigma)
GaussKernel = torch.from_numpy(Gauss).float()
if use_gpu: GaussKernel = GaussKernel.cuda()
Loss += F.mse_loss(out.squeeze(),GaussKernel)
return Loss
def MincountLoss(output,boxes, use_gpu=True):
ones = torch.ones(1)
if use_gpu: ones = ones.cuda()
Loss = 0.
if boxes.shape[1] > 1:
boxes = boxes.squeeze()
for tempBoxes in boxes.squeeze():
y1 = int(tempBoxes[1])
y2 = int(tempBoxes[3])
x1 = int(tempBoxes[2])
x2 = int(tempBoxes[4])
X = output[:,:,y1:y2,x1:x2].sum()
if X.item() <= 1:
Loss += F.mse_loss(X,ones)
else:
boxes = boxes.squeeze()
y1 = int(boxes[1])
y2 = int(boxes[3])
x1 = int(boxes[2])
x2 = int(boxes[4])
X = output[:,:,y1:y2,x1:x2].sum()
if X.item() <= 1:
Loss += F.mse_loss(X,ones)
return Loss
def pad_to_size(feat, desire_h, desire_w):
""" zero-padding a four dim feature matrix: N*C*H*W so that the new Height and Width are the desired ones
desire_h and desire_w should be largers than the current height and weight
"""
cur_h = feat.shape[-2]
cur_w = feat.shape[-1]
left_pad = (desire_w - cur_w + 1) // 2
right_pad = (desire_w - cur_w) - left_pad
top_pad = (desire_h - cur_h + 1) // 2
bottom_pad =(desire_h - cur_h) - top_pad
return F.pad(feat, (left_pad, right_pad, top_pad, bottom_pad))
def extract_features(feature_model, image, boxes,feat_map_keys=['map3','map4'], exemplar_scales=[0.9, 1.1]):
N, M = image.shape[0], boxes.shape[2]
"""
Getting features for the image N * C * H * W
"""
Image_features = feature_model(image)
"""
Getting features for the examples (N*M) * C * h * w
"""
for ix in range(0,N):
# boxes = boxes.squeeze(0)
boxes = boxes[ix][0]
cnter = 0
Cnter1 = 0
for keys in feat_map_keys:
image_features = Image_features[keys][ix].unsqueeze(0)
if keys == 'map1' or keys == 'map2':
Scaling = 4.0
elif keys == 'map3':
Scaling = 8.0
elif keys == 'map4':
Scaling = 16.0
else:
Scaling = 32.0
boxes_scaled = boxes / Scaling
boxes_scaled[:, 1:3] = torch.floor(boxes_scaled[:, 1:3])
boxes_scaled[:, 3:5] = torch.ceil(boxes_scaled[:, 3:5])
boxes_scaled[:, 3:5] = boxes_scaled[:, 3:5] + 1 # make the end indices exclusive
feat_h, feat_w = image_features.shape[-2], image_features.shape[-1]
# make sure exemplars don't go out of bound
boxes_scaled[:, 1:3] = torch.clamp_min(boxes_scaled[:, 1:3], 0)
boxes_scaled[:, 3] = torch.clamp_max(boxes_scaled[:, 3], feat_h)
boxes_scaled[:, 4] = torch.clamp_max(boxes_scaled[:, 4], feat_w)
box_hs = boxes_scaled[:, 3] - boxes_scaled[:, 1]
box_ws = boxes_scaled[:, 4] - boxes_scaled[:, 2]
max_h = math.ceil(max(box_hs))
max_w = math.ceil(max(box_ws))
for j in range(0,M):
y1, x1 = int(boxes_scaled[j,1]), int(boxes_scaled[j,2])
y2, x2 = int(boxes_scaled[j,3]), int(boxes_scaled[j,4])
#print(y1,y2,x1,x2,max_h,max_w)
if j == 0:
examples_features = image_features[:,:,y1:y2, x1:x2]
if examples_features.shape[2] != max_h or examples_features.shape[3] != max_w:
#examples_features = pad_to_size(examples_features, max_h, max_w)
examples_features = F.interpolate(examples_features, size=(max_h,max_w),mode='bilinear')
else:
feat = image_features[:,:,y1:y2, x1:x2]
if feat.shape[2] != max_h or feat.shape[3] != max_w:
feat = F.interpolate(feat, size=(max_h,max_w),mode='bilinear')
#feat = pad_to_size(feat, max_h, max_w)
examples_features = torch.cat((examples_features,feat),dim=0)
"""
Convolving example features over image features
"""
h, w = examples_features.shape[2], examples_features.shape[3]
features = F.conv2d(
F.pad(image_features, ((int(w/2)), int((w-1)/2), int(h/2), int((h-1)/2))),
examples_features
)
combined = features.permute([1,0,2,3])
# computing features for scales 0.9 and 1.1
for scale in exemplar_scales:
h1 = math.ceil(h * scale)
w1 = math.ceil(w * scale)
if h1 < 1: # use original size if scaled size is too small
h1 = h
if w1 < 1:
w1 = w
examples_features_scaled = F.interpolate(examples_features, size=(h1,w1),mode='bilinear')
features_scaled = F.conv2d(F.pad(image_features, ((int(w1/2)), int((w1-1)/2), int(h1/2), int((h1-1)/2))),
examples_features_scaled)
features_scaled = features_scaled.permute([1,0,2,3])
combined = torch.cat((combined,features_scaled),dim=1)
if cnter == 0:
Combined = 1.0 * combined
else:
if Combined.shape[2] != combined.shape[2] or Combined.shape[3] != combined.shape[3]:
combined = F.interpolate(combined, size=(Combined.shape[2],Combined.shape[3]),mode='bilinear')
Combined = torch.cat((Combined,combined),dim=1)
cnter += 1
if ix == 0:
All_feat = 1.0 * Combined.unsqueeze(0)
else:
All_feat = torch.cat((All_feat,Combined.unsqueeze(0)),dim=0)
return All_feat
class resizeImage(object):
"""
If either the width or height of an image exceed a specified value, resize the image so that:
1. The maximum of the new height and new width does not exceed a specified value
2. The new height and new width are divisible by 8
3. The aspect ratio is preserved
No resizing is done if both height and width are smaller than the specified value
By: <NAME> (<EMAIL>)
"""
def __init__(self, MAX_HW=1504):
self.max_hw = MAX_HW
def __call__(self, sample):
image,lines_boxes = sample['image'], sample['lines_boxes']
W, H = image.size
if W > self.max_hw or H > self.max_hw:
scale_factor = float(self.max_hw)/ max(H, W)
new_H = 8*int(H*scale_factor/8)
new_W = 8*int(W*scale_factor/8)
resized_image = transforms.Resize((new_H, new_W))(image)
else:
scale_factor = 1
resized_image = image
boxes = list()
for box in lines_boxes:
box2 = [int(k*scale_factor) for k in box]
y1, x1, y2, x2 = box2[0], box2[1], box2[2], box2[3]
boxes.append([0, y1,x1,y2,x2])
boxes = torch.Tensor(boxes).unsqueeze(0)
resized_image = Normalize(resized_image)
sample = {'image':resized_image,'boxes':boxes}
return sample
class resizeImageWithGT(object):
"""
If either the width or height of an image exceed a specified value, resize the image so that:
1. The maximum of the new height and new width does not exceed a specified value
2. The new height and new width are divisible by 8
3. The aspect ratio is preserved
No resizing is done if both height and width are smaller than the specified value
By: <NAME> (<EMAIL>)
Modified by: Viresh
"""
def __init__(self, MAX_HW=1504):
self.max_hw = MAX_HW
def __call__(self, sample):
image,lines_boxes,density = sample['image'], sample['lines_boxes'],sample['gt_density']
W, H = image.size
if W > self.max_hw or H > self.max_hw:
scale_factor = float(self.max_hw)/ max(H, W)
new_H = 8*int(H*scale_factor/8)
new_W = 8*int(W*scale_factor/8)
resized_image = transforms.Resize((new_H, new_W))(image)
resized_density = cv2.resize(density, (new_W, new_H))
orig_count = np.sum(density)
new_count = np.sum(resized_density)
if new_count > 0: resized_density = resized_density * (orig_count / new_count)
else:
scale_factor = 1
resized_image = image
resized_density = density
boxes = list()
for box in lines_boxes:
box2 = [int(k*scale_factor) for k in box]
y1, x1, y2, x2 = box2[0], box2[1], box2[2], box2[3]
boxes.append([0, y1,x1,y2,x2])
boxes = torch.Tensor(boxes).unsqueeze(0)
resized_image = Normalize(resized_image)
resized_density = torch.from_numpy(resized_density).unsqueeze(0).unsqueeze(0)
sample = {'image':resized_image,'boxes':boxes,'gt_density':resized_density}
return sample
Normalize = transforms.Compose([transforms.ToTensor(),
transforms.Normalize(mean=IM_NORM_MEAN, std=IM_NORM_STD)])
Transform = transforms.Compose([resizeImage( MAX_HW)])
TransformTrain = transforms.Compose([resizeImageWithGT(MAX_HW)])
def denormalize(tensor, means=IM_NORM_MEAN, stds=IM_NORM_STD):
"""Reverses the normalisation on a tensor.
Performs a reverse operation on a tensor, so the pixel value range is
between 0 and 1. Useful for when plotting a tensor into an image.
Normalisation: (image - mean) / std
Denormalisation: image * std + mean
Args:
tensor (torch.Tensor, dtype=torch.float32): Normalized image tensor
Shape:
Input: :math:`(N, C, H, W)`
Output: :math:`(N, C, H, W)` (same shape as input)
Return:
torch.Tensor (torch.float32): Demornalised image tensor with pixel
values between [0, 1]
Note:
Symbols used to describe dimensions:
- N: number of images in a batch
- C: number of channels
- H: height of the image
- W: width of the image
"""
denormalized = tensor.clone()
for channel, mean, std in zip(denormalized, means, stds):
channel.mul_(std).add_(mean)
return denormalized
def scale_and_clip(val, scale_factor, min_val, max_val):
"Helper function to scale a value and clip it within range"
new_val = int(round(val*scale_factor))
new_val = max(new_val, min_val)
new_val = min(new_val, max_val)
return new_val
def visualize_output_and_save(input_, output, boxes, save_path, figsize=(20, 12), dots=None):
"""
dots: Nx2 numpy array for the ground truth locations of the dot annotation
if dots is None, this information is not available
"""
# get the total count
pred_cnt = output.sum().item()
boxes = boxes.squeeze(0)
boxes2 = []
for i in range(0, boxes.shape[0]):
y1, x1, y2, x2 = int(boxes[i, 1].item()), int(boxes[i, 2].item()), int(boxes[i, 3].item()), int(
boxes[i, 4].item())
roi_cnt = output[0,0,y1:y2, x1:x2].sum().item()
boxes2.append([y1, x1, y2, x2, roi_cnt])
img1 = format_for_plotting(denormalize(input_))
output = format_for_plotting(output)
fig = plt.figure(figsize=figsize)
# display the input image
ax = fig.add_subplot(2, 2, 1)
ax.set_axis_off()
ax.imshow(img1)
for bbox in boxes2:
y1, x1, y2, x2 = bbox[0], bbox[1], bbox[2], bbox[3]
rect = patches.Rectangle((x1, y1), x2-x1, y2-y1, linewidth=3, edgecolor='y', facecolor='none')
rect2 = patches.Rectangle((x1, y1), x2 - x1, y2 - y1, linewidth=1, edgecolor='k', linestyle='--', facecolor='none')
ax.add_patch(rect)
ax.add_patch(rect2)
if dots is not None:
ax.scatter(dots[:, 0], dots[:, 1], c='red', edgecolors='blue')
# ax.scatter(dots[:,0], dots[:,1], c='black', marker='+')
ax.set_title("Input image, gt count: {}".format(dots.shape[0]))
else:
ax.set_title("Input image")
ax = fig.add_subplot(2, 2, 2)
ax.set_axis_off()
ax.set_title("Overlaid result, predicted count: {:.2f}".format(pred_cnt))
img2 = 0.2989*img1[:,:,0] + 0.5870*img1[:,:,1] + 0.1140*img1[:,:,2]
ax.imshow(img2, cmap='gray')
ax.imshow(output, cmap=plt.cm.viridis, alpha=0.5)
# display the density map
ax = fig.add_subplot(2, 2, 3)
ax.set_axis_off()
ax.set_title("Density map, predicted count: {:.2f}".format(pred_cnt))
ax.imshow(output)
# plt.colorbar()
ax = fig.add_subplot(2, 2, 4)
ax.set_axis_off()
ax.set_title("Density map, predicted count: {:.2f}".format(pred_cnt))
ret_fig = ax.imshow(output)
for bbox in boxes2:
y1, x1, y2, x2, roi_cnt = bbox[0], bbox[1], bbox[2], bbox[3], bbox[4]
rect = patches.Rectangle((x1, y1), x2 - x1, y2 - y1, linewidth=3, edgecolor='y', facecolor='none')
rect2 = patches.Rectangle((x1, y1), x2 - x1, y2 - y1, linewidth=1, edgecolor='k', linestyle='--',
facecolor='none')
ax.add_patch(rect)
ax.add_patch(rect2)
ax.text(x1, y1, '{:.2f}'.format(roi_cnt), backgroundcolor='y')
fig.colorbar(ret_fig, ax=ax)
fig.savefig(save_path, bbox_inches="tight")
plt.close()
def format_for_plotting(tensor):
"""Formats the shape of tensor for plotting.
Tensors typically have a shape of :math:`(N, C, H, W)` or :math:`(C, H, W)`
which is not suitable for plotting as images. This function formats an
input tensor :math:`(H, W, C)` for RGB and :math:`(H, W)` for mono-channel
data.
Args:
tensor (torch.Tensor, torch.float32): Image tensor
Shape:
Input: :math:`(N, C, H, W)` or :math:`(C, H, W)`
Output: :math:`(H, W, C)` or :math:`(H, W)`, respectively
Return:
torch.Tensor (torch.float32): Formatted image tensor (detached)
Note:
Symbols used to describe dimensions:
- N: number of images in a batch
- C: number of channels
- H: height of the image
- W: width of the image
"""
has_batch_dimension = len(tensor.shape) == 4
formatted = tensor.clone()
if has_batch_dimension:
formatted = tensor.squeeze(0)
if formatted.shape[0] == 1:
return formatted.squeeze(0).detach()
else:
return formatted.permute(1, 2, 0).detach()
| [
"cv2.rectangle",
"torch.from_numpy",
"torch.nn.functional.interpolate",
"torch.nn.functional.pad",
"torch.floor",
"torch.clamp_min",
"numpy.exp",
"matplotlib.pyplot.close",
"torchvision.transforms.ToTensor",
"cv2.waitKey",
"torch.nn.functional.mse_loss",
"matplotlib.use",
"torch.Tensor",
"... | [((209, 230), 'matplotlib.use', 'matplotlib.use', (['"""agg"""'], {}), "('agg')\n", (223, 230), False, 'import matplotlib\n'), ((1447, 1495), 'numpy.exp', 'np.exp', (['(-(x * x + y * y) / (2.0 * sigma * sigma))'], {}), '(-(x * x + y * y) / (2.0 * sigma * sigma))\n', (1453, 1495), True, 'import numpy as np\n'), ((2742, 2755), 'torch.ones', 'torch.ones', (['(1)'], {}), '(1)\n', (2752, 2755), False, 'import torch\n'), ((3930, 3985), 'torch.nn.functional.pad', 'F.pad', (['feat', '(left_pad, right_pad, top_pad, bottom_pad)'], {}), '(feat, (left_pad, right_pad, top_pad, bottom_pad))\n', (3935, 3985), True, 'import torch.nn.functional as F\n'), ((14002, 14029), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': 'figsize'}), '(figsize=figsize)\n', (14012, 14029), True, 'import matplotlib.pyplot as plt\n'), ((16028, 16039), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (16037, 16039), True, 'import matplotlib.pyplot as plt\n'), ((11760, 11781), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (11779, 11781), False, 'from torchvision import transforms\n'), ((11787, 11843), 'torchvision.transforms.Normalize', 'transforms.Normalize', ([], {'mean': 'IM_NORM_MEAN', 'std': 'IM_NORM_STD'}), '(mean=IM_NORM_MEAN, std=IM_NORM_STD)\n', (11807, 11843), False, 'from torchvision import transforms\n'), ((14237, 14332), 'matplotlib.patches.Rectangle', 'patches.Rectangle', (['(x1, y1)', '(x2 - x1)', '(y2 - y1)'], {'linewidth': '(3)', 'edgecolor': '"""y"""', 'facecolor': '"""none"""'}), "((x1, y1), x2 - x1, y2 - y1, linewidth=3, edgecolor='y',\n facecolor='none')\n", (14254, 14332), True, 'import matplotlib.patches as patches\n'), ((14341, 14452), 'matplotlib.patches.Rectangle', 'patches.Rectangle', (['(x1, y1)', '(x2 - x1)', '(y2 - y1)'], {'linewidth': '(1)', 'edgecolor': '"""k"""', 'linestyle': '"""--"""', 'facecolor': '"""none"""'}), "((x1, y1), x2 - x1, y2 - y1, linewidth=1, edgecolor='k',\n linestyle='--', facecolor='none')\n", (14358, 14452), True, 'import matplotlib.patches as patches\n'), ((15565, 15660), 'matplotlib.patches.Rectangle', 'patches.Rectangle', (['(x1, y1)', '(x2 - x1)', '(y2 - y1)'], {'linewidth': '(3)', 'edgecolor': '"""y"""', 'facecolor': '"""none"""'}), "((x1, y1), x2 - x1, y2 - y1, linewidth=3, edgecolor='y',\n facecolor='none')\n", (15582, 15660), True, 'import matplotlib.patches as patches\n'), ((15673, 15784), 'matplotlib.patches.Rectangle', 'patches.Rectangle', (['(x1, y1)', '(x2 - x1)', '(y2 - y1)'], {'linewidth': '(1)', 'edgecolor': '"""k"""', 'linestyle': '"""--"""', 'facecolor': '"""none"""'}), "((x1, y1), x2 - x1, y2 - y1, linewidth=1, edgecolor='k',\n linestyle='--', facecolor='none')\n", (15690, 15784), True, 'import matplotlib.patches as patches\n'), ((574, 588), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (585, 588), False, 'import cv2\n'), ((3403, 3422), 'torch.nn.functional.mse_loss', 'F.mse_loss', (['X', 'ones'], {}), '(X, ones)\n', (3413, 3422), True, 'import torch.nn.functional as F\n'), ((4881, 4914), 'torch.floor', 'torch.floor', (['boxes_scaled[:, 1:3]'], {}), '(boxes_scaled[:, 1:3])\n', (4892, 4914), False, 'import torch\n'), ((4950, 4982), 'torch.ceil', 'torch.ceil', (['boxes_scaled[:, 3:5]'], {}), '(boxes_scaled[:, 3:5])\n', (4960, 4982), False, 'import torch\n'), ((5248, 5288), 'torch.clamp_min', 'torch.clamp_min', (['boxes_scaled[:, 1:3]', '(0)'], {}), '(boxes_scaled[:, 1:3], 0)\n', (5263, 5288), False, 'import torch\n'), ((5322, 5365), 'torch.clamp_max', 'torch.clamp_max', (['boxes_scaled[:, 3]', 'feat_h'], {}), '(boxes_scaled[:, 3], feat_h)\n', (5337, 5365), False, 'import torch\n'), ((5399, 5442), 'torch.clamp_max', 'torch.clamp_max', (['boxes_scaled[:, 4]', 'feat_w'], {}), '(boxes_scaled[:, 4], feat_w)\n', (5414, 5442), False, 'import torch\n'), ((10874, 10909), 'cv2.resize', 'cv2.resize', (['density', '(new_W, new_H)'], {}), '(density, (new_W, new_H))\n', (10884, 10909), False, 'import cv2\n'), ((10935, 10950), 'numpy.sum', 'np.sum', (['density'], {}), '(density)\n', (10941, 10950), True, 'import numpy as np\n'), ((10975, 10998), 'numpy.sum', 'np.sum', (['resized_density'], {}), '(resized_density)\n', (10981, 10998), True, 'import numpy as np\n'), ((719, 762), 'cv2.selectROI', 'cv2.selectROI', (['"""image"""', 'image', '(False)', '(False)'], {}), "('image', image, False, False)\n", (732, 762), False, 'import cv2\n'), ((2527, 2550), 'torch.from_numpy', 'torch.from_numpy', (['Gauss'], {}), '(Gauss)\n', (2543, 2550), False, 'import torch\n'), ((3146, 3165), 'torch.nn.functional.mse_loss', 'F.mse_loss', (['X', 'ones'], {}), '(X, ones)\n', (3156, 3165), True, 'import torch.nn.functional as F\n'), ((7253, 7273), 'math.ceil', 'math.ceil', (['(h * scale)'], {}), '(h * scale)\n', (7262, 7273), False, 'import math\n'), ((7299, 7319), 'math.ceil', 'math.ceil', (['(w * scale)'], {}), '(w * scale)\n', (7308, 7319), False, 'import math\n'), ((7539, 7603), 'torch.nn.functional.interpolate', 'F.interpolate', (['examples_features'], {'size': '(h1, w1)', 'mode': '"""bilinear"""'}), "(examples_features, size=(h1, w1), mode='bilinear')\n", (7552, 7603), True, 'import torch.nn.functional as F\n'), ((7883, 7928), 'torch.cat', 'torch.cat', (['(combined, features_scaled)'], {'dim': '(1)'}), '((combined, features_scaled), dim=1)\n', (7892, 7928), False, 'import torch\n'), ((8257, 8295), 'torch.cat', 'torch.cat', (['(Combined, combined)'], {'dim': '(1)'}), '((Combined, combined), dim=1)\n', (8266, 8295), False, 'import torch\n'), ((9364, 9397), 'torchvision.transforms.Resize', 'transforms.Resize', (['(new_H, new_W)'], {}), '((new_H, new_W))\n', (9381, 9397), False, 'from torchvision import transforms\n'), ((9716, 9735), 'torch.Tensor', 'torch.Tensor', (['boxes'], {}), '(boxes)\n', (9728, 9735), False, 'import torch\n'), ((10803, 10836), 'torchvision.transforms.Resize', 'transforms.Resize', (['(new_H, new_W)'], {}), '((new_H, new_W))\n', (10820, 10836), False, 'from torchvision import transforms\n'), ((11452, 11471), 'torch.Tensor', 'torch.Tensor', (['boxes'], {}), '(boxes)\n', (11464, 11471), False, 'import torch\n'), ((1016, 1072), 'cv2.rectangle', 'cv2.rectangle', (['image', '(x1, y1)', '(x2, y2)', '(255, 0, 0)', '(2)'], {}), '(image, (x1, y1), (x2, y2), (255, 0, 0), 2)\n', (1029, 1072), False, 'import cv2\n'), ((1500, 1517), 'numpy.finfo', 'np.finfo', (['h.dtype'], {}), '(h.dtype)\n', (1508, 1517), True, 'import numpy as np\n'), ((2080, 2109), 'torch.from_numpy', 'torch.from_numpy', (['GaussKernel'], {}), '(GaussKernel)\n', (2096, 2109), False, 'import torch\n'), ((6683, 6726), 'torch.cat', 'torch.cat', (['(examples_features, feat)'], {'dim': '(0)'}), '((examples_features, feat), dim=0)\n', (6692, 6726), False, 'import torch\n'), ((8146, 8236), 'torch.nn.functional.interpolate', 'F.interpolate', (['combined'], {'size': '(Combined.shape[2], Combined.shape[3])', 'mode': '"""bilinear"""'}), "(combined, size=(Combined.shape[2], Combined.shape[3]), mode=\n 'bilinear')\n", (8159, 8236), True, 'import torch.nn.functional as F\n'), ((6248, 6318), 'torch.nn.functional.interpolate', 'F.interpolate', (['examples_features'], {'size': '(max_h, max_w)', 'mode': '"""bilinear"""'}), "(examples_features, size=(max_h, max_w), mode='bilinear')\n", (6261, 6318), True, 'import torch.nn.functional as F\n'), ((6523, 6580), 'torch.nn.functional.interpolate', 'F.interpolate', (['feat'], {'size': '(max_h, max_w)', 'mode': '"""bilinear"""'}), "(feat, size=(max_h, max_w), mode='bilinear')\n", (6536, 6580), True, 'import torch.nn.functional as F\n'), ((11560, 11593), 'torch.from_numpy', 'torch.from_numpy', (['resized_density'], {}), '(resized_density)\n', (11576, 11593), False, 'import torch\n')] |
#!/usr/bin/env py3
from __future__ import division, print_function, absolute_import
import os
import sys
import re
import numpy as np
import pdb
'''
============================
@FileName: gen_fi_validation_data.py
@Author: <NAME> (<EMAIL>)
@Version: 1.0
@DateTime: 2018-03-22 17:07:19
============================
'''
class GENFIVALIDATION(object):
"""docstring for GENFIVALIDATION"""
def __init__(self, options, logger):
self.options = options
self.logger = logger
self.embedding = self.__load_embedding(options['embed_path'],options['hand_path'])
self.inputs = self.__load_text_input(options['input'])
def __load_embedding(self, embed_path, hand_path):
hand_embedding = np.load(hand_path)
self.logger.info("load embedding from %s"%embed_path)
embedding = {}
try:
with open(embed_path, 'r', encoding='utf-8') as fi:
idx = 0
for line in fi:
line = line.strip().split()
embedding[line[0]] = line[1:] + list(map(lambda x: str(float(x)), hand_embedding[idx]))
# pdb.set_trace()
idx+=1
except Exception as e:
raise e
return embedding
def __load_text_input(self, text_path):
self.logger.info("load text from %s"%text_path)
try:
with open(text_path, 'r', encoding='utf-8') as fi:
input_array = []
for line in fi:
cur_line = []
line = re.sub("[a-zA-Z]+", "ENG", line)
line = re.sub("[0-9]+", "NUM", line)
line = list(line.strip())
idx = 0
while(idx < len(line)):
if line[idx] == '':
char = "".join(line[idx:idx+4])
cur_line.append(char)
idx+=4
elif line[idx] == " ":
idx+=1
continue
else:
char = line[idx]
cur_line.append(char)
idx+=1
input_array.append(cur_line)
return input_array
except Exception as e:
raise e
def __embed_lkp(self, char):
if char in self.embedding.keys():
return self.embedding[char]
else:
return self.embedding[r"</s>"]
def __gen_embedding(self):
char_embed = []
for sent in self.inputs:
cur_embed = []
for char in sent:
cur_embed.append(self.__embed_lkp(char))
char_embed.append(cur_embed)
# pdb.set_trace()
return char_embed
def process(self):
try:
char_embed = self.__gen_embedding()
time_step = 50
with open(self.options['output'], 'w', encoding='utf-8') as fo:
fo.write("feats : L3\nlabel : L2 string \nfeat_sep : space\ncol_sep: vb\nndim :2\n===============\n")
for sent, sent_embed in zip(self.inputs, char_embed):
count = 0
for char, char_embed in zip(sent, sent_embed ):
if char == "|" or char == " " or char =="\t":
char = "S"
elif char == "ENG":
char = "E"
elif char == "NUM":
char = "N"
fo.write("%s|0|%s|\n"%(char," ".join(char_embed)))
count += 1
for i in range(time_step - count):
fo.write("%s|0|%s|\n"%(char," ".join(map(str, np.zeros(311)))))
fo.write("*EOS*\n")
except Exception as e:
raise e
if __name__ == '__main__':
import time
import logging
from argparse import ArgumentParser
parser = ArgumentParser(description='gen_fi_validation_data')
parser.add_argument("--version", action="version", version="gen_fi_validation_data 1.0")
parser.add_argument("-i", "--input", action="store", dest="input", default="", help='input sentence file')
parser.add_argument("-e", "--embed", action="store", dest="embed_path", default="", help='embedding path')
parser.add_argument("-f", "--hand", action="store", dest="hand_path", default="", help='embedding path')
parser.add_argument("-o", "--output", action="store", dest="output", default="valid.txt", help='output name')
args = parser.parse_args()
options = vars(args)
logger = logging.getLogger()
formatter = logging.Formatter('[%(asctime)s][*%(levelname)s*][%(filename)s:%(lineno)d|%(funcName)s] - %(message)s', '%Y%m%d-%H:%M:%S')
file_handler = logging.FileHandler('LOG-gen_fi_validation_data.txt', 'w','utf-8')
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
logger.addHandler(stream_handler)
logger.setLevel(logging.INFO)
allStartTP = time.time()
appInst = GENFIVALIDATION(options, logger)
appInst.process()
allEndTP = time.time()
logger.info("Operation Finished [Time Cost:%0.3f Seconds]" % float(allEndTP - allStartTP))
| [
"logging.getLogger",
"logging.StreamHandler",
"argparse.ArgumentParser",
"logging.Formatter",
"numpy.zeros",
"logging.FileHandler",
"re.sub",
"numpy.load",
"time.time"
] | [((4064, 4116), 'argparse.ArgumentParser', 'ArgumentParser', ([], {'description': '"""gen_fi_validation_data"""'}), "(description='gen_fi_validation_data')\n", (4078, 4116), False, 'from argparse import ArgumentParser\n'), ((4711, 4730), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (4728, 4730), False, 'import logging\n'), ((4745, 4877), 'logging.Formatter', 'logging.Formatter', (['"""[%(asctime)s][*%(levelname)s*][%(filename)s:%(lineno)d|%(funcName)s] - %(message)s"""', '"""%Y%m%d-%H:%M:%S"""'], {}), "(\n '[%(asctime)s][*%(levelname)s*][%(filename)s:%(lineno)d|%(funcName)s] - %(message)s'\n , '%Y%m%d-%H:%M:%S')\n", (4762, 4877), False, 'import logging\n'), ((4885, 4952), 'logging.FileHandler', 'logging.FileHandler', (['"""LOG-gen_fi_validation_data.txt"""', '"""w"""', '"""utf-8"""'], {}), "('LOG-gen_fi_validation_data.txt', 'w', 'utf-8')\n", (4904, 4952), False, 'import logging\n'), ((5045, 5068), 'logging.StreamHandler', 'logging.StreamHandler', ([], {}), '()\n', (5066, 5068), False, 'import logging\n'), ((5194, 5205), 'time.time', 'time.time', ([], {}), '()\n', (5203, 5205), False, 'import time\n'), ((5284, 5295), 'time.time', 'time.time', ([], {}), '()\n', (5293, 5295), False, 'import time\n'), ((740, 758), 'numpy.load', 'np.load', (['hand_path'], {}), '(hand_path)\n', (747, 758), True, 'import numpy as np\n'), ((1577, 1613), 're.sub', 're.sub', (['"""[a-zA-Z]+"""', '"""\x1bENG"""', 'line'], {}), "('[a-zA-Z]+', '\\x1bENG', line)\n", (1583, 1613), False, 'import re\n'), ((1638, 1671), 're.sub', 're.sub', (['"""[0-9]+"""', '"""\x1bNUM"""', 'line'], {}), "('[0-9]+', '\\x1bNUM', line)\n", (1644, 1671), False, 'import re\n'), ((3846, 3859), 'numpy.zeros', 'np.zeros', (['(311)'], {}), '(311)\n', (3854, 3859), True, 'import numpy as np\n')] |
import numpy
from ._gauss_kronrod import _gauss_kronrod_integrate
def _numpy_all_except(a, axis=-1):
axes = numpy.arange(a.ndim)
axes = numpy.delete(axes, axis)
return numpy.all(a, axis=tuple(axes))
class IntegrationError(Exception):
pass
def integrate_adaptive(
f,
intervals,
eps_abs=1.0e-10,
eps_rel=1.0e-10,
kronrod_degree=7,
minimum_interval_length=0.0,
dot=numpy.dot,
):
sumfun = numpy.sum
intervals = numpy.array(intervals)
if len(intervals.shape) == 1:
intervals = intervals[..., None]
lengths = abs(intervals[1] - intervals[0])
total_length = sumfun(lengths)
# Use Gauss-Kronrod 7/15 scheme for error estimation and adaptivity.
_, val_g, error_estimate = _gauss_kronrod_integrate(
kronrod_degree, f, intervals, dot=dot
)
# Mark intervals with acceptable approximations. For this, take all() across every
# dimension except the last one (which is the interval index).
is_good = _numpy_all_except(
error_estimate < eps_abs * lengths / total_length, axis=-1
) & _numpy_all_except(
error_estimate < eps_rel * numpy.abs(val_g) * lengths / total_length, axis=-1
)
# add values from good intervals to sum
quad_sum = sumfun(val_g[..., is_good], axis=-1)
global_error_estimate = sumfun(error_estimate[..., is_good], axis=-1)
while any(~is_good):
# split the bad intervals in half
intervals = intervals[..., ~is_good]
midpoints = 0.5 * (intervals[0] + intervals[1])
intervals = numpy.array(
[
numpy.concatenate([intervals[0], midpoints]),
numpy.concatenate([midpoints, intervals[1]]),
]
)
# compute values and error estimates for the new intervals
_, val_g, error_estimate = _gauss_kronrod_integrate(
kronrod_degree, f, intervals, dot=dot
)
# mark good intervals, gather values and error estimates
lengths = abs(intervals[1] - intervals[0])
if any(lengths < minimum_interval_length):
raise IntegrationError(
"Tolerances (abs: {}, rel: {}) could not be reached with the minimum_interval_length (= {}).".format(
eps_abs, eps_rel, minimum_interval_length
)
)
is_good = _numpy_all_except(
error_estimate < eps_abs * lengths / total_length, axis=-1
) & _numpy_all_except(
error_estimate < eps_rel * numpy.abs(val_g) * lengths / total_length,
axis=-1,
)
# add values from good intervals to sum
quad_sum += sumfun(val_g[..., is_good], axis=-1)
global_error_estimate += sumfun(error_estimate[..., is_good], axis=-1)
return quad_sum, global_error_estimate
| [
"numpy.abs",
"numpy.delete",
"numpy.array",
"numpy.concatenate",
"numpy.arange"
] | [((115, 135), 'numpy.arange', 'numpy.arange', (['a.ndim'], {}), '(a.ndim)\n', (127, 135), False, 'import numpy\n'), ((147, 171), 'numpy.delete', 'numpy.delete', (['axes', 'axis'], {}), '(axes, axis)\n', (159, 171), False, 'import numpy\n'), ((467, 489), 'numpy.array', 'numpy.array', (['intervals'], {}), '(intervals)\n', (478, 489), False, 'import numpy\n'), ((1607, 1651), 'numpy.concatenate', 'numpy.concatenate', (['[intervals[0], midpoints]'], {}), '([intervals[0], midpoints])\n', (1624, 1651), False, 'import numpy\n'), ((1669, 1713), 'numpy.concatenate', 'numpy.concatenate', (['[midpoints, intervals[1]]'], {}), '([midpoints, intervals[1]])\n', (1686, 1713), False, 'import numpy\n'), ((1148, 1164), 'numpy.abs', 'numpy.abs', (['val_g'], {}), '(val_g)\n', (1157, 1164), False, 'import numpy\n'), ((2520, 2536), 'numpy.abs', 'numpy.abs', (['val_g'], {}), '(val_g)\n', (2529, 2536), False, 'import numpy\n')] |
import torch
import numpy as np
from eval import metrics
import gc
def evaluate_user(model, eval_loader, device, mode='pretrain'):
""" evaluate model on recommending items to users (primarily during pre-training step) """
model.eval()
eval_loss = 0.0
n100_list, r20_list, r50_list = [], [], []
eval_preds = []
with torch.no_grad():
for batch_index, eval_data in enumerate(eval_loader):
eval_data = [x.to(device, non_blocking=True) for x in eval_data]
(users, fold_in_items, held_out_items) = eval_data
fold_in_items = fold_in_items.to(device)
if mode == 'pretrain':
recon_batch, emb = model.user_preference_encoder.pre_train_forward(fold_in_items)
else:
recon_batch = model.group_predictor(model.user_preference_encoder(fold_in_items))
loss = model.multinomial_loss(recon_batch, held_out_items)
eval_loss += loss.item()
fold_in_items = fold_in_items.cpu().numpy()
recon_batch = torch.softmax(recon_batch, 1) # softmax over the item set to get normalized scores.
recon_batch[fold_in_items.nonzero()] = -np.inf
n100 = metrics.ndcg_binary_at_k_batch_torch(recon_batch, held_out_items, 100, device=device)
r20 = metrics.recall_at_k_batch_torch(recon_batch, held_out_items, 20)
r50 = metrics.recall_at_k_batch_torch(recon_batch, held_out_items, 50)
n100_list.append(n100)
r20_list.append(r20)
r50_list.append(r50)
eval_preds.append(recon_batch.cpu().numpy())
del users, fold_in_items, held_out_items, recon_batch
gc.collect()
num_batches = max(1, len(eval_loader.dataset) / eval_loader.batch_size)
eval_loss /= num_batches
n100_list = torch.cat(n100_list)
r20_list = torch.cat(r20_list)
r50_list = torch.cat(r50_list)
return eval_loss, torch.mean(n100_list), torch.mean(r20_list), torch.mean(r50_list), np.array(eval_preds)
def evaluate_group(model, eval_group_loader, device):
""" evaluate model on recommending items to groups """
model.eval()
eval_loss = 0.0
n100_list, r20_list, r50_list = [], [], []
eval_preds = []
with torch.no_grad():
for batch_idx, data in enumerate(eval_group_loader):
data = [x.to(device, non_blocking=True) for x in data]
group, group_users, group_mask, group_items, user_items = data
recon_batch, _, _ = model(group, group_users, group_mask, user_items)
loss = model.multinomial_loss(recon_batch, group_items)
eval_loss += loss.item()
result = recon_batch.softmax(1) # softmax over the item set to get normalized scores.
heldout_data = group_items
r20 = metrics.recall_at_k_batch_torch(result, heldout_data, 20)
r50 = metrics.recall_at_k_batch_torch(result, heldout_data, 50)
n100 = metrics.ndcg_binary_at_k_batch_torch(result, heldout_data, 100, device=device)
n100_list.append(n100)
r20_list.append(r20)
r50_list.append(r50)
eval_preds.append(recon_batch.cpu().numpy())
del group, group_users, group_mask, group_items, user_items
gc.collect()
n100_list = torch.cat(n100_list)
r20_list = torch.cat(r20_list)
r50_list = torch.cat(r50_list)
return eval_loss, torch.mean(n100_list), torch.mean(r20_list), torch.mean(r50_list), np.array(eval_preds)
| [
"torch.mean",
"eval.metrics.recall_at_k_batch_torch",
"torch.softmax",
"numpy.array",
"eval.metrics.ndcg_binary_at_k_batch_torch",
"gc.collect",
"torch.no_grad",
"torch.cat"
] | [((1699, 1711), 'gc.collect', 'gc.collect', ([], {}), '()\n', (1709, 1711), False, 'import gc\n'), ((1833, 1853), 'torch.cat', 'torch.cat', (['n100_list'], {}), '(n100_list)\n', (1842, 1853), False, 'import torch\n'), ((1869, 1888), 'torch.cat', 'torch.cat', (['r20_list'], {}), '(r20_list)\n', (1878, 1888), False, 'import torch\n'), ((1904, 1923), 'torch.cat', 'torch.cat', (['r50_list'], {}), '(r50_list)\n', (1913, 1923), False, 'import torch\n'), ((3296, 3308), 'gc.collect', 'gc.collect', ([], {}), '()\n', (3306, 3308), False, 'import gc\n'), ((3326, 3346), 'torch.cat', 'torch.cat', (['n100_list'], {}), '(n100_list)\n', (3335, 3346), False, 'import torch\n'), ((3362, 3381), 'torch.cat', 'torch.cat', (['r20_list'], {}), '(r20_list)\n', (3371, 3381), False, 'import torch\n'), ((3397, 3416), 'torch.cat', 'torch.cat', (['r50_list'], {}), '(r50_list)\n', (3406, 3416), False, 'import torch\n'), ((341, 356), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (354, 356), False, 'import torch\n'), ((1946, 1967), 'torch.mean', 'torch.mean', (['n100_list'], {}), '(n100_list)\n', (1956, 1967), False, 'import torch\n'), ((1969, 1989), 'torch.mean', 'torch.mean', (['r20_list'], {}), '(r20_list)\n', (1979, 1989), False, 'import torch\n'), ((1991, 2011), 'torch.mean', 'torch.mean', (['r50_list'], {}), '(r50_list)\n', (2001, 2011), False, 'import torch\n'), ((2013, 2033), 'numpy.array', 'np.array', (['eval_preds'], {}), '(eval_preds)\n', (2021, 2033), True, 'import numpy as np\n'), ((2263, 2278), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (2276, 2278), False, 'import torch\n'), ((3439, 3460), 'torch.mean', 'torch.mean', (['n100_list'], {}), '(n100_list)\n', (3449, 3460), False, 'import torch\n'), ((3462, 3482), 'torch.mean', 'torch.mean', (['r20_list'], {}), '(r20_list)\n', (3472, 3482), False, 'import torch\n'), ((3484, 3504), 'torch.mean', 'torch.mean', (['r50_list'], {}), '(r50_list)\n', (3494, 3504), False, 'import torch\n'), ((3506, 3526), 'numpy.array', 'np.array', (['eval_preds'], {}), '(eval_preds)\n', (3514, 3526), True, 'import numpy as np\n'), ((1053, 1082), 'torch.softmax', 'torch.softmax', (['recon_batch', '(1)'], {}), '(recon_batch, 1)\n', (1066, 1082), False, 'import torch\n'), ((1217, 1306), 'eval.metrics.ndcg_binary_at_k_batch_torch', 'metrics.ndcg_binary_at_k_batch_torch', (['recon_batch', 'held_out_items', '(100)'], {'device': 'device'}), '(recon_batch, held_out_items, 100,\n device=device)\n', (1253, 1306), False, 'from eval import metrics\n'), ((1321, 1385), 'eval.metrics.recall_at_k_batch_torch', 'metrics.recall_at_k_batch_torch', (['recon_batch', 'held_out_items', '(20)'], {}), '(recon_batch, held_out_items, 20)\n', (1352, 1385), False, 'from eval import metrics\n'), ((1404, 1468), 'eval.metrics.recall_at_k_batch_torch', 'metrics.recall_at_k_batch_torch', (['recon_batch', 'held_out_items', '(50)'], {}), '(recon_batch, held_out_items, 50)\n', (1435, 1468), False, 'from eval import metrics\n'), ((2828, 2885), 'eval.metrics.recall_at_k_batch_torch', 'metrics.recall_at_k_batch_torch', (['result', 'heldout_data', '(20)'], {}), '(result, heldout_data, 20)\n', (2859, 2885), False, 'from eval import metrics\n'), ((2904, 2961), 'eval.metrics.recall_at_k_batch_torch', 'metrics.recall_at_k_batch_torch', (['result', 'heldout_data', '(50)'], {}), '(result, heldout_data, 50)\n', (2935, 2961), False, 'from eval import metrics\n'), ((2981, 3059), 'eval.metrics.ndcg_binary_at_k_batch_torch', 'metrics.ndcg_binary_at_k_batch_torch', (['result', 'heldout_data', '(100)'], {'device': 'device'}), '(result, heldout_data, 100, device=device)\n', (3017, 3059), False, 'from eval import metrics\n')] |
import numpy as np
'''
REFERENCES
<NAME>., <NAME>, <NAME>, and <NAME> (2001),
Plants in water-controlled ecosystems Active role in hydrologic processes and response to water stress II. Probabilistic soil moisture dynamics,
Adv. Water Resour., 24(7), 707-723, doi 10.1016/S0309-1708(01)00005-7.
<NAME>., <NAME>, <NAME>, and <NAME> (2001),
Plants in water-controlled ecosystems Active role in hydrologic processes and response to water stress III. Vegetation-water stress,
Adv. Water Resour., 24(7), 725-744, doi 10.1016/S0309-1708(01)00006-9.
<NAME>., <NAME>, and <NAME> (1984),
Scale considerations in the modeling of temporal rainfall,
Water Resour. Res., 20(11), 1611-1619, doi 10.1029/WR020i011p01611.
Clapp and Hornberger (1978)
<NAME>., and <NAME> (2016),
A minimalistic probabilistic model for soil moisture in seasonlly dry climates,
Water Resour. Res., 52, 1507 - 1517
'''
class SM_L(object):
'''
from Laio et al., 2001
Model assumptions
- daily time scale
- at a point
- soil moisture processes are Markovian (no memory)
- soil is a horizontal layer with constant homogenious characteristics (depth Zr, porosity n)
- growing season in which climate, vegetation parameters are constant
- rainfall is a marked Poisson process (lambda, alpha)
- actual precipitation (Rainfall - Interception) is a censored marked Poisson Process (threshold delta -> lambda_p, alpha_p)
- between rain events soil moisture loss processes vary within s thresholds: s_fc, s_star, s_w, s_h.
parameter definition:
's_h': relative soil moisture at the hydroscopic point
's_wilt': relative soil moisture at wilting point
's_star': relativesoil moisture at incipient stomatal closure
's_fc': relative soil moisture at field capacity
'delta': canopy interception of rainfall
'rf_lambda': mean rainfall frequency
'rf_alpha': mean rainfall depth
'Zr': (rooting) soil depth
'b': b, water retention curve (Clapp and Hornberger [1978])
'Ks': saturated soil hydraulic conductivity
'n': porosity
'e_max': max ET
'e_w': E at s = s_w, e_w = f_w * e_t0
'et0': reference et
'''
def __init__(self, params):
[self.s_h, self.s_wilt, self.s_star, self.s_fc,
self.f_max, self.f_w, self.et0,
self.rf_alpha, self.rf_lambda, self.delta,
self.b, self.Ks, self.n, self.Zr] = params
if self.s_h == self.s_wilt:
self.f_w = 0.0001
self.e_w = self.f_w * self.et0
self.e_max = self.f_max * self.et0
self.lambda_p = self.get_lambda_p()
self.eta = self.get_eta()
self.eta_w = self.get_eta_w()
self.beta = self.get_beta()
self.m = self.get_m()
self.gamma = self.get_gamma()
def get_beta(self):
return 2. * self.b + 4.
def get_gamma(self):
return self.n * self.Zr / (self.rf_alpha - self.delta)
def get_lambda_p(self):
return self.rf_lambda * np.exp(- self.delta / self.rf_alpha)
def get_eta(self, e=None):
if e is None:
return self.e_max / (self.n * self.Zr)
else:
return e / (self.n * self.Zr)
def get_eta_w(self, e=None):
if e is None:
return self.e_w / (self.n * self.Zr)
else:
return e / (self.n * self.Zr)
def get_m(self):
try:
m = self.Ks \
/ ((self.n * self.Zr)
* (np.exp(self.beta * (1. - self.s_fc)) - 1.))
return m
except:
return np.nan
def __rho_s_h(self, s):
return self.eta_w * ((s - self.s_h) / (self.s_wilt - self.s_h))
def __rho_s_w(self, s):
return self.eta_w + (self.eta - self.eta_w) * ((s - self.s_wilt) / (self.s_star - self.s_wilt))
def __rho_s_star(self, s):
return self.eta
def __rho_s_fc(self, s):
x = self.beta * (s - self.s_fc)
e = np.exp(x)
return self.eta + self.m * (e - 1)
def __rho(self, s):
if s > self.s_fc:
return self.__rho_s_fc(s)
elif (s > self.s_star) and (s <= self.s_fc):
return self.__rho_s_star(s)
elif (s > self.s_wilt) and (s <= self.s_star):
return self.__rho_s_w(s)
elif (s > self.s_h) and (s <= self.s_wilt):
return self.__rho_s_h(s)
else:
return 0
def __p_s_h(self, s):
# s_h < s <= s_wilt
ch1 = (s - self.s_h) / (self.s_wilt - self.s_h)
ch2 = (self.lambda_p * (self.s_wilt - self.s_h) / self.eta_w) - 1.
p = (1. / self.eta_w) * ch1 ** ch2 * np.exp(- self.gamma * s)
return p
def __p_s_w(self, s):
# s_wilt < s <= s_star
sw1 = 1. + (self.eta / self.eta_w - 1.) * ((s - self.s_wilt) / (self.s_star - self.s_wilt))
sw2 = self.lambda_p * (self.s_star - self.s_wilt) / (self.eta - self.eta_w) - 1.
p = (1. / self.eta_w) * sw1 ** sw2 * np.exp(- self.gamma * s)
return p
def __p_s_star(self, s):
# s_star < s <= s_fc
sst0 = (1. / self.eta)
sst_e1 = - self.gamma * s + self.lambda_p / self.eta * (s - self.s_star)
sst1 = np.exp(sst_e1)
sst_e2 = self.lambda_p * (self.s_star - self.s_wilt) / (self.eta - self.eta_w)
sst2 = (self.eta / self.eta_w) ** sst_e2
p = sst0 * sst1 * sst2
return p
def __p_s_fc(self, s):
# s_fc < s <= 1
fc_e1 = - (self.beta + self.gamma) * s + self.beta * self.s_fc
fc_e2 = (self.lambda_p / (self.beta * (self.eta - self.m))) + 1.
fc_e3 = self.lambda_p * (self.s_star - self.s_wilt) / (self.eta - self.eta_w)
sfc0 = 1. / self.eta
sfc1 = np.exp(fc_e1)
sfc20 = (self.eta * (np.exp(self.beta * s))) / ((self.eta - self.m) * \
(np.exp(self.beta * self.s_fc)) + self.m * (np.exp(self.beta * s)))
sfc2 = sfc20 ** fc_e2
sfc3 = (self.eta / self.eta_w) ** fc_e3
sfc4 = np.exp((self.lambda_p / self.eta) * (self.s_fc - self.s_star))
p = sfc0 * sfc1 * sfc2 * sfc3 * sfc4
return p
def __p0(self, s):
if s > self.s_fc:
return self.__p_s_fc(s)
elif (s > self.s_star) and (s <= self.s_fc):
return self.__p_s_star(s)
elif (s > self.s_wilt) and (s <= self.s_star):
return self.__p_s_w(s)
elif (s > self.s_h) and (s <= self.s_wilt):
return self.__p_s_h(s)
else:
return 0
def et_losses(self, s):
if s > self.s_fc:
return self.e_max
elif s > self.s_star:
return self.e_max
elif s > self.s_wilt:
return (self.e_max - self.e_w) * (s - self.s_wilt) / (self.s_star - self.s_wilt) + self.e_w
elif s > self.s_h:
return self.e_w * (s - self.s_h) / (self.s_wilt - self.s_h)
else:
return 0
def stress(self, s, q):
if s > self.s_fc:
return 0
elif s > self.s_star:
return 0
elif s > self.s_wilt:
return ((self.s_star - s) / (self.s_star - self.s_wilt)) ** q
elif s > self.s_h:
return 1
else:
return 1
def get_p0(self, s_list_len=100):
s_list = np.linspace(0., 1., (s_list_len + 1))
if self.s_fc < 1 \
and self.s_fc >= self.s_star \
and self.s_star >= self.s_wilt \
and self.s_wilt >= self.s_h \
and np.isnan(self.s_fc) == 0 \
and np.isnan(self.s_star) == 0 \
and np.isnan(self.s_wilt) == 0 \
and np.isnan(self.eta_w) == 0 \
and np.isnan(self.eta) == 0 \
and self.eta_w > 0:
p0 = np.array([self.__p0(s) for s in s_list])
c = np.sum(p0)
return p0 / c
else:
return [0 for s in s_list]
def get_mean_et(self, p0, s_list_len=100):
s_list = np.linspace(0., 1., (s_list_len + 1))
e = np.array([self.et_losses(s) for s in s_list])
e = e * p0
return np.sum(e)
def get_mean_stress(self, p0, q=2, s_list_len=100):
s_list = np.linspace(0., 1., (s_list_len + 1))
st = np.array([self.stress(s, q) for s in s_list])
st = st * p0
return np.sum(st)
class SM_D(object):
'''
modified from Dralle and Thompson, 2016
Model assumptions
t_d >> 1/lambda: length of dry season constant year to year
p_w from SM_L
p_d: negligeable rainfall: exponential decay following s0
soil moisture thresholds constant within the year
e_max_dry different from e_max
s0: random variable, start of dry season
'''
def __init__(self, params):
[self.s_h, self.s_wilt, self.s_star, self.s_fc,
self.f_max, self.f_w, self.et0,
self.rf_alpha, self.rf_lambda, self.delta,
self.b, self.Ks, self.n, self.Zr,
self.et0_dry, self.t_d] = params
self.smpdf_w = SM_L(params[:-2])
if self.s_h == self.s_wilt:
self.f_w = 0.0001
self.e_max_dry = self.f_max * self.et0_dry
self.e_w_dry = self.f_w * self.et0_dry
self.eta_dry = self.smpdf_w.get_eta(e=self.e_max_dry)
self.eta_w_dry = self.smpdf_w.get_eta_w(e=self.e_w_dry)
self.beta = self.smpdf_w.get_beta()
self.m = self.smpdf_w.get_m()
def get_p0(self, ps0, s_list_len=100):
s_list = np.linspace(0., 1., (s_list_len + 1))
s_fin_list = [self.get_s_t(s0, self.t_d) for s0 in s_list]
p0d = [self.get_p0_sdi(sdi, s_list, s_fin_list, ps0) if sdi >= self.s_h else 0 for sdi in s_list]
p0d = p0d / np.sum(p0d)
return p0d
def get_ps0(self, s_list_len=100):
ps0 = self.smpdf_w.get_p0(s_list_len=s_list_len)
return ps0
def get_p0_sdi(self, sdi, s_list, s_fin_list, ps0):
p0d_si = [self.__p_sd_given_s0(s0i, sdi) * ps0i \
for s0i, s_fini, ps0i in zip(s_list, s_fin_list, ps0) \
if (sdi <= s0i) and (sdi >= s_fini)]
return np.sum(p0d_si)
def __p_sd_given_s0(self, s0, sd):
if (sd > self.s_h) and (sd <= self.s_wilt):
return self.__psdso_s_h(sd, s0)
elif (sd > self.s_wilt) and (sd <= self.s_star):
return self.__psdso_s_w(sd, s0)
elif (sd > self.s_star) and (sd <= self.s_fc):
return self.__psdso_s_star(sd, s0)
elif sd > self.s_fc:
return self.__psdso_s_fc(sd, s0)
else:
return 0
def __psdso_s_h(self, sd, s0):
a = self.s_wilt - self.s_h
b = (sd - self.s_h) * self.t_d * self.eta_w_dry
return a / b
def __psdso_s_w(self, sd, s0):
a = (self.s_star - self.s_wilt) / (self.t_d * (self.eta_dry - self.eta_w_dry))
b = self.eta_dry - self.eta_w_dry
c = b * (sd - self.s_wilt) + self.eta_w_dry * (self.s_star - self.s_wilt)
return a * b / c
def __psdso_s_star(self, sd, s0):
return 1 / (self.t_d * self.eta_dry)
def __psdso_s_fc(self, sd, s0):
a = 1 / (self.beta * self.t_d * (self.eta_dry - self.m))
b = (self.eta_dry - self.m) * np.exp(self.beta * (s0 - sd))
c = - self.eta_dry + self.m + self.m * np.exp(self.beta * (s0 - self.s_fc))
return a * (self.beta * b / (b + c ))
def __t_s_fc(self, s0):
if s0 > self.s_fc:
return 1 / (self.beta * (self.m - self.eta_dry)) * \
(self.beta * (self.s_fc - s0) \
+ np.log((self.eta_dry - self.m \
+ self.m * np.exp(self.beta * (s0 - self.s_fc))) \
/ self.eta_dry)
)
else:
return 0
def __t_s_star(self, t_s_fci, s0):
if s0 > self.s_star:
if s0 > self.s_fc:
s0 = self.s_fc
return t_s_fci \
+ (s0 - self.s_star) \
/ self.eta_dry
else:
return 0
def __t_s_wilt(self, t_s_stari, s0):
if s0 > self.s_wilt:
if s0 > self.s_star:
s0 = self.s_star
return t_s_stari \
+ (s0 - self.s_wilt) / (self.eta_dry - self.eta_w_dry) \
* np.log(self.eta_dry / self.eta_w_dry)
else:
return 0
def __s_h_t(self, t, t_s_wilti):
return self.s_h + (self.s_wilt - self.s_h) \
* np.exp(- self.eta_w_dry / (self.s_wilt - self.s_h) \
* (t - t_s_wilti))
def __s_wilt_t(self, t, t_s_stari):
return self.s_wilt + (self.s_star - self.s_wilt) \
* (self.eta_dry / (self.eta_dry - self.eta_w_dry) \
* np.exp(- (self.eta_dry - self.eta_w_dry) / (self.s_star - self.s_wilt) \
* (t - t_s_stari)) \
- self.eta_dry / (self.eta_dry - self.eta_w_dry))
def __s_star_t(self, t, t_s_fci):
return self.s_fc - \
self.eta_dry * (t - t_s_fci)
def __s_fc_t(self, t):
return s0 - 1 / self.beta \
* np.log((self.eta_dry - self.m \
+ self.m * np.exp(self.beta * (s0 - self.s_fc)) \
* self.m * np.exp(self.beta * (self.eta_dry - self.m) * t)\
- self.m * np.exp(self.beta * (s0 - self.s_fc))) \
/ (self.eta_dry - self.m))
def get_s_t(self, s0, t):
t_s_fci = self.__t_s_fc(s0)
t_s_stari = self.__t_s_star(t_s_fci, s0)
t_s_wilti = self.__t_s_wilt(t_s_stari, s0)
if t < t_s_fci:
return self.__s_fc_t(t)
elif (t < t_s_stari) and (t >= t_s_fci):
return self.__s_star_t(t, t_s_fci)
elif (t < t_s_wilti) and (t >= t_s_stari):
return self.__s_wilt_t(t, t_s_stari)
else:
return self.__s_h_t(t, t_s_wilti)
class SM_A(object):
def __init__(self, params):
self.smpdf_w = SM_L(params[:-2])
self.smpdf_d = SM_D(params)
[self.s_h, self.s_wilt, self.s_star, self.s_fc,
self.f_max, self.f_w, self.et0,
self.rf_alpha, self.rf_lambda, self.delta,
self.b, self.Ks, self.n, self.Zr,
self.et0_dry, self.t_d] = params
self.e_w = self.et0 * self.f_w
self.e_max = self.et0 * self.f_max
self.e_max_dry = self.et0_dry * self.f_max
self.e_w_dry = self.et0_dry * self.f_w
def get_p0(self, s_list_len=100):
if self.s_fc < 1 \
and self.s_fc >= self.s_star \
and self.s_star >= self.s_wilt \
and self.s_wilt >= self.s_h \
and np.isnan(self.s_fc) == 0 \
and np.isnan(self.s_star) == 0 \
and np.isnan(self.s_wilt) == 0 \
and self.e_max > 0:
if self.t_d > 0:
p0w = self.smpdf_w.get_p0(s_list_len=s_list_len)
p0d = self.smpdf_d.get_p0(p0w, s_list_len=s_list_len)
return (1 - self.t_d / 365.) * np.array(p0w) + \
self.t_d / 365. * np.array(p0d)
else:
p0w = self.smpdf_w.get_p0(s_list_len=s_list_len)
return p0w
else:
return [0 for s in range(s_list_len + 1)]
class Stochastic_rf_char(object):
# Rodriguez-Iturbe et al., 1984
def __init__(self, rf_ts):
self.rf_ts = np.array(rf_ts)
self.mu = self.get_mu()
self.var = self.get_var()
self.l = self.get_poisson_lambda()
self.a = self.get_poisson_alpha()
def get_mu(self):
return np.mean(self.rf_ts)
def get_var(self):
return np.var(self.rf_ts)
def get_poisson_lambda(self):
return 2 * self.mu**2 / self.var
def get_poisson_alpha(self):
return self.mu / self.l
def get_lambda_p(self, delta):
return self.l * np.exp(- delta / self.a)
if __name__ == "__main__":
pass
| [
"numpy.mean",
"numpy.log",
"numpy.exp",
"numpy.sum",
"numpy.linspace",
"numpy.array",
"numpy.isnan",
"numpy.var"
] | [((4089, 4098), 'numpy.exp', 'np.exp', (['x'], {}), '(x)\n', (4095, 4098), True, 'import numpy as np\n'), ((5333, 5347), 'numpy.exp', 'np.exp', (['sst_e1'], {}), '(sst_e1)\n', (5339, 5347), True, 'import numpy as np\n'), ((5859, 5872), 'numpy.exp', 'np.exp', (['fc_e1'], {}), '(fc_e1)\n', (5865, 5872), True, 'import numpy as np\n'), ((6131, 6191), 'numpy.exp', 'np.exp', (['(self.lambda_p / self.eta * (self.s_fc - self.s_star))'], {}), '(self.lambda_p / self.eta * (self.s_fc - self.s_star))\n', (6137, 6191), True, 'import numpy as np\n'), ((7430, 7467), 'numpy.linspace', 'np.linspace', (['(0.0)', '(1.0)', '(s_list_len + 1)'], {}), '(0.0, 1.0, s_list_len + 1)\n', (7441, 7467), True, 'import numpy as np\n'), ((8142, 8179), 'numpy.linspace', 'np.linspace', (['(0.0)', '(1.0)', '(s_list_len + 1)'], {}), '(0.0, 1.0, s_list_len + 1)\n', (8153, 8179), True, 'import numpy as np\n'), ((8272, 8281), 'numpy.sum', 'np.sum', (['e'], {}), '(e)\n', (8278, 8281), True, 'import numpy as np\n'), ((8356, 8393), 'numpy.linspace', 'np.linspace', (['(0.0)', '(1.0)', '(s_list_len + 1)'], {}), '(0.0, 1.0, s_list_len + 1)\n', (8367, 8393), True, 'import numpy as np\n'), ((8489, 8499), 'numpy.sum', 'np.sum', (['st'], {}), '(st)\n', (8495, 8499), True, 'import numpy as np\n'), ((9626, 9663), 'numpy.linspace', 'np.linspace', (['(0.0)', '(1.0)', '(s_list_len + 1)'], {}), '(0.0, 1.0, s_list_len + 1)\n', (9637, 9663), True, 'import numpy as np\n'), ((10265, 10279), 'numpy.sum', 'np.sum', (['p0d_si'], {}), '(p0d_si)\n', (10271, 10279), True, 'import numpy as np\n'), ((15631, 15646), 'numpy.array', 'np.array', (['rf_ts'], {}), '(rf_ts)\n', (15639, 15646), True, 'import numpy as np\n'), ((15836, 15855), 'numpy.mean', 'np.mean', (['self.rf_ts'], {}), '(self.rf_ts)\n', (15843, 15855), True, 'import numpy as np\n'), ((15895, 15913), 'numpy.var', 'np.var', (['self.rf_ts'], {}), '(self.rf_ts)\n', (15901, 15913), True, 'import numpy as np\n'), ((3129, 3164), 'numpy.exp', 'np.exp', (['(-self.delta / self.rf_alpha)'], {}), '(-self.delta / self.rf_alpha)\n', (3135, 3164), True, 'import numpy as np\n'), ((4771, 4794), 'numpy.exp', 'np.exp', (['(-self.gamma * s)'], {}), '(-self.gamma * s)\n', (4777, 4794), True, 'import numpy as np\n'), ((5105, 5128), 'numpy.exp', 'np.exp', (['(-self.gamma * s)'], {}), '(-self.gamma * s)\n', (5111, 5128), True, 'import numpy as np\n'), ((7987, 7997), 'numpy.sum', 'np.sum', (['p0'], {}), '(p0)\n', (7993, 7997), True, 'import numpy as np\n'), ((9857, 9868), 'numpy.sum', 'np.sum', (['p0d'], {}), '(p0d)\n', (9863, 9868), True, 'import numpy as np\n'), ((11372, 11401), 'numpy.exp', 'np.exp', (['(self.beta * (s0 - sd))'], {}), '(self.beta * (s0 - sd))\n', (11378, 11401), True, 'import numpy as np\n'), ((16116, 16139), 'numpy.exp', 'np.exp', (['(-delta / self.a)'], {}), '(-delta / self.a)\n', (16122, 16139), True, 'import numpy as np\n'), ((5902, 5923), 'numpy.exp', 'np.exp', (['(self.beta * s)'], {}), '(self.beta * s)\n', (5908, 5923), True, 'import numpy as np\n'), ((7658, 7677), 'numpy.isnan', 'np.isnan', (['self.s_fc'], {}), '(self.s_fc)\n', (7666, 7677), True, 'import numpy as np\n'), ((7705, 7726), 'numpy.isnan', 'np.isnan', (['self.s_star'], {}), '(self.s_star)\n', (7713, 7726), True, 'import numpy as np\n'), ((7754, 7775), 'numpy.isnan', 'np.isnan', (['self.s_wilt'], {}), '(self.s_wilt)\n', (7762, 7775), True, 'import numpy as np\n'), ((7803, 7823), 'numpy.isnan', 'np.isnan', (['self.eta_w'], {}), '(self.eta_w)\n', (7811, 7823), True, 'import numpy as np\n'), ((7851, 7869), 'numpy.isnan', 'np.isnan', (['self.eta'], {}), '(self.eta)\n', (7859, 7869), True, 'import numpy as np\n'), ((11449, 11485), 'numpy.exp', 'np.exp', (['(self.beta * (s0 - self.s_fc))'], {}), '(self.beta * (s0 - self.s_fc))\n', (11455, 11485), True, 'import numpy as np\n'), ((12659, 12727), 'numpy.exp', 'np.exp', (['(-self.eta_w_dry / (self.s_wilt - self.s_h) * (t - t_s_wilti))'], {}), '(-self.eta_w_dry / (self.s_wilt - self.s_h) * (t - t_s_wilti))\n', (12665, 12727), True, 'import numpy as np\n'), ((14884, 14903), 'numpy.isnan', 'np.isnan', (['self.s_fc'], {}), '(self.s_fc)\n', (14892, 14903), True, 'import numpy as np\n'), ((14931, 14952), 'numpy.isnan', 'np.isnan', (['self.s_star'], {}), '(self.s_star)\n', (14939, 14952), True, 'import numpy as np\n'), ((14980, 15001), 'numpy.isnan', 'np.isnan', (['self.s_wilt'], {}), '(self.s_wilt)\n', (14988, 15001), True, 'import numpy as np\n'), ((5971, 6000), 'numpy.exp', 'np.exp', (['(self.beta * self.s_fc)'], {}), '(self.beta * self.s_fc)\n', (5977, 6000), True, 'import numpy as np\n'), ((6014, 6035), 'numpy.exp', 'np.exp', (['(self.beta * s)'], {}), '(self.beta * s)\n', (6020, 6035), True, 'import numpy as np\n'), ((12477, 12514), 'numpy.log', 'np.log', (['(self.eta_dry / self.eta_w_dry)'], {}), '(self.eta_dry / self.eta_w_dry)\n', (12483, 12514), True, 'import numpy as np\n'), ((3610, 3647), 'numpy.exp', 'np.exp', (['(self.beta * (1.0 - self.s_fc))'], {}), '(self.beta * (1.0 - self.s_fc))\n', (3616, 3647), True, 'import numpy as np\n'), ((12945, 13037), 'numpy.exp', 'np.exp', (['(-(self.eta_dry - self.eta_w_dry) / (self.s_star - self.s_wilt) * (t -\n t_s_stari))'], {}), '(-(self.eta_dry - self.eta_w_dry) / (self.s_star - self.s_wilt) * (t -\n t_s_stari))\n', (12951, 13037), True, 'import numpy as np\n'), ((15256, 15269), 'numpy.array', 'np.array', (['p0w'], {}), '(p0w)\n', (15264, 15269), True, 'import numpy as np\n'), ((15315, 15328), 'numpy.array', 'np.array', (['p0d'], {}), '(p0d)\n', (15323, 15328), True, 'import numpy as np\n'), ((13537, 13573), 'numpy.exp', 'np.exp', (['(self.beta * (s0 - self.s_fc))'], {}), '(self.beta * (s0 - self.s_fc))\n', (13543, 13573), True, 'import numpy as np\n'), ((11799, 11835), 'numpy.exp', 'np.exp', (['(self.beta * (s0 - self.s_fc))'], {}), '(self.beta * (s0 - self.s_fc))\n', (11805, 11835), True, 'import numpy as np\n'), ((13457, 13504), 'numpy.exp', 'np.exp', (['(self.beta * (self.eta_dry - self.m) * t)'], {}), '(self.beta * (self.eta_dry - self.m) * t)\n', (13463, 13504), True, 'import numpy as np\n'), ((13387, 13423), 'numpy.exp', 'np.exp', (['(self.beta * (s0 - self.s_fc))'], {}), '(self.beta * (s0 - self.s_fc))\n', (13393, 13423), True, 'import numpy as np\n')] |
import math
import sys
import numpy as np
import scipy
import itertools
import copy as cp
from helpers import *
import opt_einsum as oe
import tools
import time
from ClusteredOperator import *
from ClusteredState import *
from Cluster import *
from ham_build import *
def compute_rspt2_correction(ci_vector, clustered_ham, e0, nproc=1):
# {{{
print(" Compute Matrix Vector Product:", flush=True)
start = time.time()
if nproc==1:
#h0v(clustered_ham,ci_vector)
#exit()
pt_vector = matvec1(clustered_ham, ci_vector)
else:
pt_vector = matvec1_parallel1(clustered_ham, ci_vector, nproc=nproc)
stop = time.time()
print(" Time spent in matvec: ", stop-start)
#pt_vector.prune_empty_fock_spaces()
tmp = ci_vector.dot(pt_vector)
var = pt_vector.norm() - tmp*tmp
print(" Variance: %12.8f" % var,flush=True)
print("Dim of PT space %4d"%len(pt_vector))
print(" Remove CI space from pt_vector vector")
for fockspace,configs in pt_vector.items():
if fockspace in ci_vector.fblocks():
for config,coeff in list(configs.items()):
if config in ci_vector[fockspace]:
del pt_vector[fockspace][config]
print("Dim of PT space %4d"%len(pt_vector))
for fockspace,configs in ci_vector.items():
if fockspace in pt_vector:
for config,coeff in configs.items():
assert(config not in pt_vector[fockspace])
print(" Norm of CI vector = %12.8f" %ci_vector.norm())
print(" Dimension of CI space: ", len(ci_vector))
print(" Dimension of PT space: ", len(pt_vector))
print(" Compute Denominator",flush=True)
# compute diagonal for PT2
start = time.time()
#pt_vector.prune_empty_fock_spaces()
if nproc==1:
Hd = build_h0(clustered_ham, ci_vector, pt_vector)
else:
Hd = build_h0(clustered_ham, ci_vector, pt_vector)
#Hd = build_hamiltonian_diagonal_parallel1(clustered_ham, pt_vector, nproc=nproc)
#pr.disable()
#pr.print_stats(sort='time')
end = time.time()
print(" Time spent in demonimator: ", end - start)
denom = 1/(e0 - Hd)
pt_vector_v = pt_vector.get_vector()
pt_vector_v.shape = (pt_vector_v.shape[0])
e2 = np.multiply(denom,pt_vector_v)
pt_vector.set_vector(e2)
e2 = np.dot(pt_vector_v,e2)
print(" PT2 Energy Correction = %12.8f" %e2)
return e2,pt_vector
# }}}
def compute_lcc2_correction(ci_vector, clustered_ham, e0, nproc=1):
# {{{
print(" Compute Matrix Vector Product:", flush=True)
start = time.time()
if nproc==1:
#h0v(clustered_ham,ci_vector)
#exit()
pt_vector = matvec1(clustered_ham, ci_vector)
else:
pt_vector = matvec1_parallel1(clustered_ham, ci_vector, nproc=nproc)
stop = time.time()
print(" Time spent in matvec: ", stop-start)
#pt_vector.prune_empty_fock_spaces()
tmp = ci_vector.dot(pt_vector)
var = pt_vector.norm() - tmp*tmp
print(" Variance: %12.8f" % var,flush=True)
print("Dim of PT space %4d"%len(pt_vector))
print(" Remove CI space from pt_vector vector")
for fockspace,configs in pt_vector.items():
if fockspace in ci_vector.fblocks():
for config,coeff in list(configs.items()):
if config in ci_vector[fockspace]:
del pt_vector[fockspace][config]
print("Dim of PT space %4d"%len(pt_vector))
for fockspace,configs in ci_vector.items():
if fockspace in pt_vector:
for config,coeff in configs.items():
assert(config not in pt_vector[fockspace])
print(" Norm of CI vector = %12.8f" %ci_vector.norm())
print(" Dimension of CI space: ", len(ci_vector))
print(" Dimension of PT space: ", len(pt_vector))
print(" Compute Denominator",flush=True)
# compute diagonal for PT2
start = time.time()
#pt_vector.prune_empty_fock_spaces()
if nproc==1:
Hd = build_h0(clustered_ham, ci_vector, pt_vector)
Hd2 = build_hamiltonian_diagonal(clustered_ham, pt_vector)
else:
Hd = build_h0(clustered_ham, ci_vector, pt_vector)
Hd2 = build_hamiltonian_diagonal_parallel1(clustered_ham, pt_vector, nproc=nproc)
#pr.disable()
#pr.print_stats(sort='time')
end = time.time()
print(" Time spent in demonimator: ", end - start)
denom = 1/(e0 - Hd)
pt_vector_v = pt_vector.get_vector()
pt_vector_v.shape = (pt_vector_v.shape[0])
e2 = np.multiply(denom,pt_vector_v)
pt_vector.set_vector(e2)
e2 = np.dot(pt_vector_v,e2)
print(" PT2 Energy Correction = %12.8f" %e2)
print("E DPS %16.8f"%e0)
#ci_vector.add(pt_vector)
H = build_full_hamiltonian(clustered_ham, pt_vector)
np.fill_diagonal(H,0)
denom.shape = (denom.shape[0],1)
v1 = pt_vector.get_vector()
for j in range(0,10):
print("v1",v1.shape)
v2 = H @ v1
#print("v2",v2.shape)
#print("denom",denom.shape)
v2 = np.multiply(denom,v2)
#print("afrer denom",v2.shape)
e3 = np.dot(pt_vector_v,v2)
print(e3.shape)
print("PT2",e2)
print("PT3",e3[0])
v1 = v2
pt_vector.set_vector(v2)
return e3[0],pt_vector
# }}}
def build_h0(clustered_ham,ci_vector,pt_vector):
"""
Build hamiltonian diagonal in basis in ci_vector as difference of cluster energies as in RSPT
"""
# {{{
clusters = clustered_ham.clusters
Hd = np.zeros((len(pt_vector)))
E0 = build_full_hamiltonian(clustered_ham,ci_vector,iprint=0, opt_einsum=True)[0,0]
assert(len(ci_vector)==1)
print("E0%16.8f"%E0)
#idx = 0
#Hd1 = np.zeros((len(pt_vector)))
#for f,c,v in pt_vector:
# e0_X = 0
# for ci in clustered_ham.clusters:
# e0_X += ci.ops['H_mf'][(f[ci.idx],f[ci.idx])][c[ci.idx],c[ci.idx]]
# Hd1[idx] = e0_X
# idx += 1
idx = 0
Hd = np.zeros((len(pt_vector)))
for ci_fspace, ci_configs in ci_vector.items():
for ci_config, ci_coeff in ci_configs.items():
for fockspace, configs in pt_vector.items():
#print("FS",fockspace)
active = []
inactive = []
for ind,fs in enumerate(fockspace):
if fs != ci_fspace[ind]:
active.append(ind)
else:
inactive.append(ind)
delta_fock= tuple([(fockspace[ci][0]-ci_fspace[ci][0], fockspace[ci][1]-ci_fspace[ci][1]) for ci in range(len(clusters))])
#print("active",active)
#print("active",delta_fock)
#print(tuple(np.array(list(fockspace))[inactive]))
for config, coeff in configs.items():
delta_fock= tuple([(0,0) for ci in range(len(clusters))])
diff = tuple(x-y for x,y in zip(ci_config,config))
#print("CI",ci_config)
for x in inactive:
if diff[x] != 0 and x not in active:
active.append(x)
#print("PT",config)
#print("d ",diff)
#print("ACTIVE",active)
Hd[idx] = E0
for cidx in active:
fspace = fockspace[cidx]
conf = config[cidx]
#print(" Cluster: %4d Fock Space:%s config:%4d Energies %16.8f"%(cidx,fspace,conf,clusters[cidx].energies[fspace][conf]))
#Hd[idx] += clusters[cidx].energies[fockspace[cidx]][config[cidx]]
#Hd[idx] -= clusters[cidx].energies[ci_fspace[cidx]][ci_config[cidx]]
Hd[idx] += clusters[cidx].ops['H_mf'][(fockspace[cidx],fockspace[cidx])][config[cidx],config[cidx]]
Hd[idx] -= clusters[cidx].ops['H_mf'][(ci_fspace[cidx],ci_fspace[cidx])][ci_config[cidx],ci_config[cidx]]
#print("-Cluster: %4d Fock Space:%s config:%4d Energies %16.8f"%(cidx,ci_fspace[cidx],ci_config[cidx],clusters[cidx].energies[ci_fspace[cidx]][ci_config[cidx]]))
# for EN:
#for term in terms:
# Hd[idx] += term.matrix_element(fockspace,config,fockspace,config)
# print(term.active)
# for RS
#Hd[idx] = E0 - term.active
idx += 1
return Hd
# }}}
def cepa(clustered_ham,ci_vector,pt_vector,cepa_shift):
# {{{
ts = 0
H00 = build_full_hamiltonian(clustered_ham,ci_vector,iprint=0)
#H00 = H[tb0.start:tb0.stop,tb0.start:tb0.stop]
E0,V0 = np.linalg.eigh(H00)
E0 = E0[ts]
Ec = 0.0
#cepa_shift = 'aqcc'
#cepa_shift = 'cisd'
#cepa_shift = 'acpf'
#cepa_shift = 'cepa0'
cepa_mit = 1
cepa_mit = 100
for cit in range(0,cepa_mit):
#Hdd = cp.deepcopy(H[tb0.stop::,tb0.stop::])
Hdd = build_full_hamiltonian(clustered_ham,pt_vector,iprint=0)
shift = 0.0
if cepa_shift == 'acpf':
shift = Ec * 2.0 / n_blocks
#shift = Ec * 2.0 / n_sites
elif cepa_shift == 'aqcc':
shift = (1.0 - (n_blocks-3.0)*(n_blocks - 2.0)/(n_blocks * ( n_blocks-1.0) )) * Ec
elif cepa_shift == 'cisd':
shift = Ec
elif cepa_shift == 'cepa0':
shift = 0
Hdd += -np.eye(Hdd.shape[0])*(E0 + shift)
#Hdd += -np.eye(Hdd.shape[0])*(E0 + -0.220751700895 * 2.0 / 8.0)
#Hd0 = H[tb0.stop::,tb0.start:tb0.stop].dot(V0[:,ts])
H0d = build_block_hamiltonian(clustered_ham,ci_vector,pt_vector,iprint=0)
Hd0 = H0d.T
Hd0 = Hd0.dot(V0[:,ts])
#Cd = -np.linalg.inv(Hdd-np.eye(Hdd.shape[0])*E0).dot(Hd0)
#Cd = np.linalg.inv(Hdd).dot(-Hd0)
Cd = np.linalg.solve(Hdd, -Hd0)
print(" CEPA(0) Norm : %16.12f"%np.linalg.norm(Cd))
V0 = V0[:,ts]
V0.shape = (V0.shape[0],1)
Cd.shape = (Cd.shape[0],1)
C = np.vstack((V0,Cd))
H00d = np.insert(H0d,0,E0,axis=1)
#E = V0[:,ts].T.dot(H[tb0.start:tb0.stop,:]).dot(C)
E = V0[:,ts].T.dot(H00d).dot(C)
cepa_last_vectors = C
cepa_last_values = E
print(" CEPA(0) Energy: %16.12f"%E)
if abs(E-E0 - Ec) < 1e-10:
print("Converged")
break
Ec = E - E0
print("Ec %16.8f"%Ec)
return Ec[0]
# }}}
def build_block_hamiltonian(clustered_ham,ci_vector,pt_vector,iprint=0):
"""
Build hamiltonian in basis of two different clustered states
"""
# {{{
clusters = clustered_ham.clusters
H0d = np.zeros((len(ci_vector),len(pt_vector)))
shift_l = 0
for fock_li, fock_l in enumerate(ci_vector.data):
configs_l = ci_vector[fock_l]
if iprint > 0:
print(fock_l)
for config_li, config_l in enumerate(configs_l):
idx_l = shift_l + config_li
shift_r = 0
for fock_ri, fock_r in enumerate(pt_vector.data):
configs_r = pt_vector[fock_r]
delta_fock= tuple([(fock_l[ci][0]-fock_r[ci][0], fock_l[ci][1]-fock_r[ci][1]) for ci in range(len(clusters))])
try:
terms = clustered_ham.terms[delta_fock]
except KeyError:
shift_r += len(configs_r)
continue
for config_ri, config_r in enumerate(configs_r):
idx_r = shift_r + config_ri
#print("FOC",fock_l,fock_r)
#print("con",config_l,config_r)
#print(shift_r,config_ri)
#print("idx",idx_l,idx_r)
for term in terms:
me = term.matrix_element(fock_l,config_l,fock_r,config_r)
H0d[idx_l,idx_r] += me
shift_r += len(configs_r)
shift_l += len(configs_l)
return H0d
# }}}
def compute_cisd_correction(ci_vector, clustered_ham, nproc=1):
# {{{
print(" Compute Matrix Vector Product:", flush=True)
start = time.time()
H00 = build_full_hamiltonian(clustered_ham,ci_vector,iprint=0)
E0,V0 = np.linalg.eigh(H00)
E0 = E0[0]
if nproc==1:
pt_vector = matvec1(clustered_ham, ci_vector)
else:
pt_vector = matvec1_parallel1(clustered_ham, ci_vector, nproc=nproc)
stop = time.time()
print(" Time spent in matvec: ", stop-start)
print(" Remove CI space from pt_vector vector")
for fockspace,configs in pt_vector.items():
if fockspace in ci_vector.fblocks():
for config,coeff in list(configs.items()):
if config in ci_vector[fockspace]:
del pt_vector[fockspace][config]
for fockspace,configs in ci_vector.items():
if fockspace in pt_vector:
for config,coeff in configs.items():
assert(config not in pt_vector[fockspace])
ci_vector.add(pt_vector)
if nproc==1:
H = build_full_hamiltonian(clustered_ham, ci_vector)
else:
H = build_full_hamiltonian(clustered_ham, ci_vector)
e,v = scipy.sparse.linalg.eigsh(H,10,which='SA')
idx = e.argsort()
e = e[idx]
v = v[:,idx]
v = v[:,0]
e0 = e[0]
e = e[0]
Ec = e - E0
print(" CISD Energy Correction = %12.8f" %Ec)
return Ec
# }}}
def truncated_ci(clustered_ham, ci_vector, pt_vector=None, nproc=1):
# {{{
print(" Compute Matrix Vector Product:", flush=True)
if pt_vector==None:
H = build_full_hamiltonian(clustered_ham, ci_vector)
e,v = scipy.sparse.linalg.eigsh(H,10,which='SA')
idx = e.argsort()
e = e[idx]
v = v[:,idx]
v = v[:,0]
e0 = e[0]
e = e[0]
else:
H00 = build_full_hamiltonian(clustered_ham,ci_vector,iprint=0)
E0,V0 = np.linalg.eigh(H00)
E0 = E0[0]
ci_vector.add(pt_vector)
H = build_full_hamiltonian(clustered_ham, ci_vector)
e,v = scipy.sparse.linalg.eigsh(H,10,which='SA')
idx = e.argsort()
e = e[idx]
v = v[:,idx]
v = v[:,0]
e0 = e[0]
e = e[0]
Ec = e - E0
print(" Truncated CI Correction = %12.8f" %Ec)
ci_vector.set_vector(v)
return e,ci_vector
# }}}
def expand_doubles(ci_vector,clusters):
# {{{
ci_vector.print_configs()
for fspace in ci_vector.keys():
for ci in clusters:
for cj in clusters:
if cj.idx != ci.idx:
#same fock space
nfs = fspace
fock_i = nfs[ci.idx]
fock_j = nfs[cj.idx]
dims = [[0] for ca in range(len(clusters))]
dims[ci.idx] = range(1,ci.basis[fock_i].shape[1])
dims[cj.idx] = range(1,cj.basis[fock_j].shape[1])
for newconfig_idx, newconfig in enumerate(itertools.product(*dims)):
ci_vector[nfs][newconfig] = 0
# alpha excitation
new_fspace_a = [list(fs) for fs in fspace]
new_fspace_a[ci.idx][0] += 1
new_fspace_a[cj.idx][0] -= 1
new_fspace_a = tuple( tuple(fs) for fs in new_fspace_a)
good = True
for c in clusters:
if min(new_fspace_a[c.idx]) < 0 or max(new_fspace_a[c.idx]) > c.n_orb:
good = False
break
if good == False:
p = 1
else:
print(new_fspace_a)
ci_vector.add_fockspace(new_fspace_a)
nfs = new_fspace_a
fock_i = nfs[ci.idx]
fock_j = nfs[cj.idx]
dims = [[0] for ca in range(len(clusters))]
dims[ci.idx] = range(ci.basis[fock_i].shape[1])
dims[cj.idx] = range(cj.basis[fock_j].shape[1])
for newconfig_idx, newconfig in enumerate(itertools.product(*dims)):
ci_vector[nfs][newconfig] = 0
# beta excitation
new_fspace_b = [list(fs) for fs in fspace]
new_fspace_b[ci.idx][1] += 1
new_fspace_b[cj.idx][1] -= 1
new_fspace_b = tuple( tuple(fs) for fs in new_fspace_b)
good = True
for c in clusters:
if min(new_fspace_b[c.idx]) < 0 or max(new_fspace_b[c.idx]) > c.n_orb:
good = False
break
if good == False:
p = 1
else:
print(new_fspace_b)
ci_vector.add_fockspace(new_fspace_b)
nfs = new_fspace_b
fock_i = nfs[ci.idx]
fock_j = nfs[cj.idx]
dims = [[0] for ca in range(len(clusters))]
dims[ci.idx] = range(ci.basis[fock_i].shape[1])
dims[cj.idx] = range(cj.basis[fock_j].shape[1])
for newconfig_idx, newconfig in enumerate(itertools.product(*dims)):
ci_vector[nfs][newconfig] = 0
new_fspace_aa = [list(fs) for fs in fspace]
new_fspace_aa[ci.idx][0] += 2
new_fspace_aa[cj.idx][0] -= 2
new_fspace_aa = tuple( tuple(fs) for fs in new_fspace_aa)
good = True
for c in clusters:
if min(new_fspace_aa[c.idx]) < 0 or max(new_fspace_aa[c.idx]) > c.n_orb:
good = False
break
if good == False:
p = 1
else:
print(new_fspace_aa)
ci_vector.add_fockspace(new_fspace_aa)
nfs = new_fspace_aa
fock_i = nfs[ci.idx]
fock_j = nfs[cj.idx]
dims = [[0] for ca in range(len(clusters))]
dims[ci.idx] = range(ci.basis[fock_i].shape[1])
dims[cj.idx] = range(cj.basis[fock_j].shape[1])
for newconfig_idx, newconfig in enumerate(itertools.product(*dims)):
ci_vector[nfs][newconfig] = 0
new_fspace_bb = [list(fs) for fs in fspace]
new_fspace_bb[ci.idx][1] += 2
new_fspace_bb[cj.idx][1] -= 2
new_fspace_bb = tuple( tuple(fs) for fs in new_fspace_bb)
print(new_fspace_bb)
good = True
for c in clusters:
if min(new_fspace_bb[c.idx]) < 0 or max(new_fspace_bb[c.idx]) > c.n_orb:
good = False
break
if good == False:
p = 1
else:
print(new_fspace_bb)
ci_vector.add_fockspace(new_fspace_bb)
nfs = new_fspace_bb
fock_i = nfs[ci.idx]
fock_j = nfs[cj.idx]
dims = [[0] for ca in range(len(clusters))]
dims[ci.idx] = range(ci.basis[fock_i].shape[1])
dims[cj.idx] = range(cj.basis[fock_j].shape[1])
for newconfig_idx, newconfig in enumerate(itertools.product(*dims)):
ci_vector[nfs][newconfig] = 0
new_fspace_ab = [list(fs) for fs in fspace]
new_fspace_ab[ci.idx][0] += 1
new_fspace_ab[cj.idx][0] -= 1
new_fspace_ab[ci.idx][1] += 1
new_fspace_ab[cj.idx][1] -= 1
new_fspace_ab = tuple( tuple(fs) for fs in new_fspace_ab)
print("AB",new_fspace_ab)
good = True
for c in clusters:
if min(new_fspace_ab[c.idx]) < 0 or max(new_fspace_ab[c.idx]) > c.n_orb:
good = False
break
if good == False:
p = 1
else:
print(new_fspace_ab)
ci_vector.add_fockspace(new_fspace_ab)
nfs = new_fspace_ab
fock_i = nfs[ci.idx]
fock_j = nfs[cj.idx]
dims = [[0] for ca in range(len(clusters))]
dims[ci.idx] = range(ci.basis[fock_i].shape[1])
dims[cj.idx] = range(cj.basis[fock_j].shape[1])
for newconfig_idx, newconfig in enumerate(itertools.product(*dims)):
ci_vector[nfs][newconfig] = 0
new_fspace_ab = [list(fs) for fs in fspace]
new_fspace_ab[ci.idx][0] += 1
new_fspace_ab[cj.idx][0] -= 1
new_fspace_ab[ci.idx][1] -= 1
new_fspace_ab[cj.idx][1] += 1
new_fspace_ab = tuple( tuple(fs) for fs in new_fspace_ab)
print("AB",new_fspace_ab)
good = True
for c in clusters:
if min(new_fspace_ab[c.idx]) < 0 or max(new_fspace_ab[c.idx]) > c.n_orb:
good = False
break
if good == False:
p = 1
else:
print(new_fspace_ab)
ci_vector.add_fockspace(new_fspace_ab)
nfs = new_fspace_ab
fock_i = nfs[ci.idx]
fock_j = nfs[cj.idx]
dims = [[0] for ca in range(len(clusters))]
dims[ci.idx] = range(ci.basis[fock_i].shape[1])
dims[cj.idx] = range(cj.basis[fock_j].shape[1])
for newconfig_idx, newconfig in enumerate(itertools.product(*dims)):
ci_vector[nfs][newconfig] = 0
ci_vector.print_configs()
print(len(ci_vector))
#ci_vector.add_single_excitonic_states()
#ci_vector.expand_each_fock_space()
#ci_vector.print()
print(len(ci_vector))
ci_vector.print_configs()
"""
for fspace in ci_vector.keys():
config = [0]*len(self.clusters)
for ci in self.clusters:
fock_i = fspace[ci.idx]
new_config = cp.deepcopy(config)
for cii in range(ci.basis[fock_i].shape[1]):
new_config[ci.idx] = cii
self[fspace][tuple(new_config)] = 0
"""
return ci_vector
# }}}
def truncated_pt2(clustered_ham,ci_vector,pt_vector,method = 'mp2',inf=False):
# {{{
""" method: mp2,mplcc2,en2,enlcc, use the inf command to do infinite order PT when u have the full H"""
clusters = clustered_ham.clusters
ts = 0
print("len CI",len(ci_vector))
print("len PT",len(pt_vector))
print(" Remove CI space from pt_vector vector")
for fockspace,configs in pt_vector.items():
if fockspace in ci_vector.fblocks():
for config,coeff in list(configs.items()):
if config in ci_vector[fockspace]:
del pt_vector[fockspace][config]
print("Dim of PT space %4d"%len(pt_vector))
pt_dim = len(pt_vector)
ci_dim = len(ci_vector)
pt_order = 500
for fockspace,configs in ci_vector.items():
if fockspace in pt_vector:
for config,coeff in configs.items():
assert(config not in pt_vector[fockspace])
H0d = build_block_hamiltonian(clustered_ham,ci_vector,pt_vector,iprint=0)
H00 = build_full_hamiltonian(clustered_ham,ci_vector,iprint=0)
Hdd = build_full_hamiltonian(clustered_ham,pt_vector,iprint=0)
print(H00)
E0,V0 = np.linalg.eigh(H00)
E0 = E0[ts]
if method == 'en2' or method == 'enlcc':
Hd = build_hamiltonian_diagonal(clustered_ham,pt_vector)
np.fill_diagonal(Hdd,0)
elif method == 'mp2' or method == 'mplcc':
Hd = build_h0(clustered_ham, ci_vector, pt_vector)
#Hd += 10
for i in range(0,Hdd.shape[0]):
Hdd[i,i] -= (Hd[i])
else:
print("Method not found")
print("E0 %16.8f"%E0)
print(Hdd)
R0 = 1/(E0 - Hd)
print(R0)
v1 = np.multiply(R0,H0d)
pt_vector.set_vector(v1.T)
print(v1.shape)
print(H0d.shape)
e2 = H0d @ v1.T
print(e2)
v_n = np.zeros((pt_dim,pt_order+1)) #list of PT vectors
E_mpn = np.zeros((pt_order+1)) #PT energy
v_n[: ,0] = v1
E_mpn[0] = e2
E_corr = 0
print(" %6s %16s %16s "%("Order","Correction","Energy"))
#print(" %6i %16.8f %16.8f "%(1,first_order_E[0,s],E_mpn[0]))
E_corr = E_mpn[0]
print(" %6i %16.8f %16.8f "%(2,E_mpn[0],E_corr))
if method == 'enlcc' or method == 'mplcc':
Eold = E_corr
for i in range(1,pt_order-1):
h1 = Hdd @ v_n[:,i-1]
v_n[:,i] = h1.reshape(pt_dim)
if inf ==True:
for k in range(0,i):
v_n[:,i] -= np.multiply(E_mpn[k-1],v_n[:,(i-k-1)].reshape(pt_dim))
v_n[:,i] = np.multiply(R0,v_n[:,i])
E_mpn[i] = H0d @ v_n[:,i].T
#print(E_mpn)
E_corr += E_mpn[i]
print(" %6i %16.8f %16.8f "%(i+2,E_mpn[i],E_corr))
pt_vector.set_vector(v_n[:,i])
if abs(E_corr - Eold) < 1e-10:
print("LCC:%16.8f "%E_corr)
break
else:
Eold = E_corr
#v_n[:,i] = 0.8 * v_n[:,i] + 0.2 * v_n[:,i-1]
elif method == 'en2' or method == 'mp2':
print("MP2:%16.8f "%E_corr)
return E_corr, pt_vector
# }}}
def pt2infty(clustered_ham,ci_vector,pt_vector,form_H=True,nproc=None):
"""
The DMBPT infty equivalent for TPS methods. equvalent to CEPA/ LCCSD
Input:
clustered_ham: clustered_ham for the system
ci_vector: single CMF state for now
pt_vector: the pt_vector generated using compute_pt2_correction function
Output:
The correlation energy using cepa
pt_vector: which is the updated LCC vector
"""
# {{{
clusters = clustered_ham.clusters
ts = 0
print("len CI",len(ci_vector))
print("len PT",len(pt_vector))
pt_dim = len(pt_vector)
ci_dim = len(ci_vector)
pt_order = 500
for fockspace,configs in ci_vector.items():
if fockspace in pt_vector:
for config,coeff in configs.items():
assert(config not in pt_vector[fockspace])
H0d = build_block_hamiltonian(clustered_ham,ci_vector,pt_vector,iprint=0)
H00 = build_full_hamiltonian(clustered_ham,ci_vector,iprint=0)
if form_H:
print("Storage for H %8.4f GB"%((pt_dim*pt_dim*8)/10e9))
if pt_dim > 60000:
print("Memory for just storing H is approx 29 GB")
exit()
Hdd = build_full_hamiltonian_parallel2(clustered_ham,pt_vector,iprint=0,nproc=nproc)
np.fill_diagonal(Hdd,0)
print(H00)
E0,V0 = np.linalg.eigh(H00)
E0 = E0[ts]
Hd = build_hamiltonian_diagonal(clustered_ham,pt_vector)
print("E0 %16.8f"%E0)
R0 = 1/(E0 - Hd)
print(R0)
v1 = np.multiply(R0,H0d)
pt_vector.set_vector(v1.T)
print(v1.shape)
print(H0d.shape)
e2 = H0d @ v1.T
print(e2)
v_n = np.zeros((pt_dim,pt_order+1)) #list of PT vectors
E_mpn = np.zeros((pt_order+1)) #PT energy
v_n[: ,0] = v1
E_mpn[0] = e2
E_corr = 0
print(" %6s %16s %16s "%("Order","Correction","Energy"))
#print(" %6i %16.8f %16.8f "%(1,first_order_E[0,s],E_mpn[0]))
E_corr = E_mpn[0]
print(" %6i %16.8f %16.8f "%(2,E_mpn[0],E_corr))
Eold = E_corr
for i in range(1,pt_order-1):
#h1 = Hdd @ v_n[:,i-1]
if form_H:
h1 = Hdd @ v_n[:,i-1]
else:
sigma = build_sigma(clustered_ham,pt_vector,iprint=0, opt_einsum=True)
h1 = sigma.get_vector()
v_n[:,i] = h1.reshape(pt_dim)
#for k in range(0,i):
# v_n[:,i] -= np.multiply(E_mpn[k-1],v_n[:,(i-k-1)].reshape(pt_dim))
v_n[:,i] = np.multiply(R0,v_n[:,i])
E_mpn[i] = H0d @ v_n[:,i].T
#print(E_mpn)
E_corr += E_mpn[i]
print(" %6i %16.8f %16.8f "%(i+2,E_mpn[i],E_corr))
pt_vector.set_vector(v_n[:,i])
if abs(E_corr - Eold) < 1e-10:
print("LCC:%16.8f "%E_corr)
break
else:
Eold = E_corr
#v_n[:,i] = 0.8 * v_n[:,i] + 0.2 * v_n[:,i-1]
return E_corr, pt_vector
# }}}
def build_sigma(clustered_ham,ci_vector,iprint=0, opt_einsum=True):
"""
Form the sigma vector using the EN zero order hamiltonian
Cannot be used for davidson since this is for H0 of EN partitioning(diagonal of H is 0)
"""
# {{{
clusters = clustered_ham.clusters
sigma = np.zeros(len(ci_vector))
ci_v = ci_vector.get_vector()
shift_l = 0
for fock_li, fock_l in enumerate(ci_vector.data):
configs_l = ci_vector[fock_l]
if iprint > 0:
print(fock_l)
for config_li, config_l in enumerate(configs_l):
idx_l = shift_l + config_li
shift_r = 0
for fock_ri, fock_r in enumerate(ci_vector.data):
configs_r = ci_vector[fock_r]
delta_fock= tuple([(fock_l[ci][0]-fock_r[ci][0], fock_l[ci][1]-fock_r[ci][1]) for ci in range(len(clusters))])
if fock_ri<fock_li:
shift_r += len(configs_r)
continue
try:
terms = clustered_ham.terms[delta_fock]
except KeyError:
shift_r += len(configs_r)
continue
for config_ri, config_r in enumerate(configs_r):
idx_r = shift_r + config_ri
if idx_r<idx_l:
continue
for term in terms:
me = term.matrix_element(fock_l,config_l,fock_r,config_r)
if idx_r == idx_l:
me = 0
sigma[idx_l] += me * ci_v[idx_r]
if idx_r>idx_l:
sigma[idx_r] += me * ci_v[idx_l]
#print(" %4i %4i = %12.8f"%(idx_l,idx_r,me)," : ",config_l,config_r, " :: ", term)
shift_r += len(configs_r)
shift_l += len(configs_l)
sigma_vec = ci_vector.copy()
sigma_vec.set_vector(sigma)
return sigma_vec
# }}}
| [
"numpy.insert",
"numpy.multiply",
"numpy.linalg.solve",
"numpy.eye",
"itertools.product",
"numpy.fill_diagonal",
"scipy.sparse.linalg.eigsh",
"numpy.dot",
"numpy.zeros",
"numpy.vstack",
"numpy.linalg.norm",
"numpy.linalg.eigh",
"time.time"
] | [((419, 430), 'time.time', 'time.time', ([], {}), '()\n', (428, 430), False, 'import time\n'), ((654, 665), 'time.time', 'time.time', ([], {}), '()\n', (663, 665), False, 'import time\n'), ((1763, 1774), 'time.time', 'time.time', ([], {}), '()\n', (1772, 1774), False, 'import time\n'), ((2130, 2141), 'time.time', 'time.time', ([], {}), '()\n', (2139, 2141), False, 'import time\n'), ((2320, 2351), 'numpy.multiply', 'np.multiply', (['denom', 'pt_vector_v'], {}), '(denom, pt_vector_v)\n', (2331, 2351), True, 'import numpy as np\n'), ((2389, 2412), 'numpy.dot', 'np.dot', (['pt_vector_v', 'e2'], {}), '(pt_vector_v, e2)\n', (2395, 2412), True, 'import numpy as np\n'), ((2641, 2652), 'time.time', 'time.time', ([], {}), '()\n', (2650, 2652), False, 'import time\n'), ((2876, 2887), 'time.time', 'time.time', ([], {}), '()\n', (2885, 2887), False, 'import time\n'), ((3970, 3981), 'time.time', 'time.time', ([], {}), '()\n', (3979, 3981), False, 'import time\n'), ((4404, 4415), 'time.time', 'time.time', ([], {}), '()\n', (4413, 4415), False, 'import time\n'), ((4594, 4625), 'numpy.multiply', 'np.multiply', (['denom', 'pt_vector_v'], {}), '(denom, pt_vector_v)\n', (4605, 4625), True, 'import numpy as np\n'), ((4663, 4686), 'numpy.dot', 'np.dot', (['pt_vector_v', 'e2'], {}), '(pt_vector_v, e2)\n', (4669, 4686), True, 'import numpy as np\n'), ((4857, 4879), 'numpy.fill_diagonal', 'np.fill_diagonal', (['H', '(0)'], {}), '(H, 0)\n', (4873, 4879), True, 'import numpy as np\n'), ((8862, 8881), 'numpy.linalg.eigh', 'np.linalg.eigh', (['H00'], {}), '(H00)\n', (8876, 8881), True, 'import numpy as np\n'), ((12470, 12481), 'time.time', 'time.time', ([], {}), '()\n', (12479, 12481), False, 'import time\n'), ((12562, 12581), 'numpy.linalg.eigh', 'np.linalg.eigh', (['H00'], {}), '(H00)\n', (12576, 12581), True, 'import numpy as np\n'), ((12767, 12778), 'time.time', 'time.time', ([], {}), '()\n', (12776, 12778), False, 'import time\n'), ((13539, 13583), 'scipy.sparse.linalg.eigsh', 'scipy.sparse.linalg.eigsh', (['H', '(10)'], {'which': '"""SA"""'}), "(H, 10, which='SA')\n", (13564, 13583), False, 'import scipy\n'), ((24729, 24748), 'numpy.linalg.eigh', 'np.linalg.eigh', (['H00'], {}), '(H00)\n', (24743, 24748), True, 'import numpy as np\n'), ((25241, 25261), 'numpy.multiply', 'np.multiply', (['R0', 'H0d'], {}), '(R0, H0d)\n', (25252, 25261), True, 'import numpy as np\n'), ((25380, 25412), 'numpy.zeros', 'np.zeros', (['(pt_dim, pt_order + 1)'], {}), '((pt_dim, pt_order + 1))\n', (25388, 25412), True, 'import numpy as np\n'), ((25444, 25466), 'numpy.zeros', 'np.zeros', (['(pt_order + 1)'], {}), '(pt_order + 1)\n', (25452, 25466), True, 'import numpy as np\n'), ((28035, 28054), 'numpy.linalg.eigh', 'np.linalg.eigh', (['H00'], {}), '(H00)\n', (28049, 28054), True, 'import numpy as np\n'), ((28210, 28230), 'numpy.multiply', 'np.multiply', (['R0', 'H0d'], {}), '(R0, H0d)\n', (28221, 28230), True, 'import numpy as np\n'), ((28349, 28381), 'numpy.zeros', 'np.zeros', (['(pt_dim, pt_order + 1)'], {}), '((pt_dim, pt_order + 1))\n', (28357, 28381), True, 'import numpy as np\n'), ((28413, 28435), 'numpy.zeros', 'np.zeros', (['(pt_order + 1)'], {}), '(pt_order + 1)\n', (28421, 28435), True, 'import numpy as np\n'), ((5103, 5125), 'numpy.multiply', 'np.multiply', (['denom', 'v2'], {}), '(denom, v2)\n', (5114, 5125), True, 'import numpy as np\n'), ((5177, 5200), 'numpy.dot', 'np.dot', (['pt_vector_v', 'v2'], {}), '(pt_vector_v, v2)\n', (5183, 5200), True, 'import numpy as np\n'), ((10071, 10097), 'numpy.linalg.solve', 'np.linalg.solve', (['Hdd', '(-Hd0)'], {}), '(Hdd, -Hd0)\n', (10086, 10097), True, 'import numpy as np\n'), ((10281, 10300), 'numpy.vstack', 'np.vstack', (['(V0, Cd)'], {}), '((V0, Cd))\n', (10290, 10300), True, 'import numpy as np\n'), ((10315, 10344), 'numpy.insert', 'np.insert', (['H0d', '(0)', 'E0'], {'axis': '(1)'}), '(H0d, 0, E0, axis=1)\n', (10324, 10344), True, 'import numpy as np\n'), ((14002, 14046), 'scipy.sparse.linalg.eigsh', 'scipy.sparse.linalg.eigsh', (['H', '(10)'], {'which': '"""SA"""'}), "(H, 10, which='SA')\n", (14027, 14046), False, 'import scipy\n'), ((14262, 14281), 'numpy.linalg.eigh', 'np.linalg.eigh', (['H00'], {}), '(H00)\n', (14276, 14281), True, 'import numpy as np\n'), ((14411, 14455), 'scipy.sparse.linalg.eigsh', 'scipy.sparse.linalg.eigsh', (['H', '(10)'], {'which': '"""SA"""'}), "(H, 10, which='SA')\n", (14436, 14455), False, 'import scipy\n'), ((24884, 24908), 'numpy.fill_diagonal', 'np.fill_diagonal', (['Hdd', '(0)'], {}), '(Hdd, 0)\n', (24900, 24908), True, 'import numpy as np\n'), ((27983, 28007), 'numpy.fill_diagonal', 'np.fill_diagonal', (['Hdd', '(0)'], {}), '(Hdd, 0)\n', (27999, 28007), True, 'import numpy as np\n'), ((29161, 29187), 'numpy.multiply', 'np.multiply', (['R0', 'v_n[:, i]'], {}), '(R0, v_n[:, i])\n', (29172, 29187), True, 'import numpy as np\n'), ((26111, 26137), 'numpy.multiply', 'np.multiply', (['R0', 'v_n[:, i]'], {}), '(R0, v_n[:, i])\n', (26122, 26137), True, 'import numpy as np\n'), ((9609, 9629), 'numpy.eye', 'np.eye', (['Hdd.shape[0]'], {}), '(Hdd.shape[0])\n', (9615, 9629), True, 'import numpy as np\n'), ((10148, 10166), 'numpy.linalg.norm', 'np.linalg.norm', (['Cd'], {}), '(Cd)\n', (10162, 10166), True, 'import numpy as np\n'), ((15339, 15363), 'itertools.product', 'itertools.product', (['*dims'], {}), '(*dims)\n', (15356, 15363), False, 'import itertools\n'), ((16552, 16576), 'itertools.product', 'itertools.product', (['*dims'], {}), '(*dims)\n', (16569, 16576), False, 'import itertools\n'), ((17768, 17792), 'itertools.product', 'itertools.product', (['*dims'], {}), '(*dims)\n', (17785, 17792), False, 'import itertools\n'), ((18955, 18979), 'itertools.product', 'itertools.product', (['*dims'], {}), '(*dims)\n', (18972, 18979), False, 'import itertools\n'), ((20183, 20207), 'itertools.product', 'itertools.product', (['*dims'], {}), '(*dims)\n', (20200, 20207), False, 'import itertools\n'), ((21516, 21540), 'itertools.product', 'itertools.product', (['*dims'], {}), '(*dims)\n', (21533, 21540), False, 'import itertools\n'), ((22849, 22873), 'itertools.product', 'itertools.product', (['*dims'], {}), '(*dims)\n', (22866, 22873), False, 'import itertools\n')] |
import numpy as np
import argparse, os, sys, h5py
from hfd.variables import label_df
parser = argparse.ArgumentParser(description='Add latent annotations to h5s.')
parser.add_argument('folder', type=str, help='Folder to search for h5 files.')
parser.add_argument('fontsize', type=int, help='Fontsize.')
args = parser.parse_args()
folder = args.folder
fontsize =args.fontsize
labels = ['initial_geometry', 'medial_geometry', 'final_geometry', 'all_geometry']
bof = ['atom_bof', 'atom_mod_rotations_bof']
files = []
for d, _, files in os.walk(folder):
for fname in files:
if '{}.h5'.format(fontsize) in fname:
with h5py.File(os.path.join(d, fname), 'a') as f:
for l in labels:
try:
del f[l]
except KeyError:
pass
f.create_dataset(l, data=label_df[l].values)
for l in bof:
try:
del f[l]
except KeyError:
pass
f.create_dataset(l, data=np.stack([*label_df[l].values]))
| [
"numpy.stack",
"os.walk",
"os.path.join",
"argparse.ArgumentParser"
] | [((96, 165), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Add latent annotations to h5s."""'}), "(description='Add latent annotations to h5s.')\n", (119, 165), False, 'import argparse, os, sys, h5py\n'), ((537, 552), 'os.walk', 'os.walk', (['folder'], {}), '(folder)\n', (544, 552), False, 'import argparse, os, sys, h5py\n'), ((651, 673), 'os.path.join', 'os.path.join', (['d', 'fname'], {}), '(d, fname)\n', (663, 673), False, 'import argparse, os, sys, h5py\n'), ((1107, 1138), 'numpy.stack', 'np.stack', (['[*label_df[l].values]'], {}), '([*label_df[l].values])\n', (1115, 1138), True, 'import numpy as np\n')] |
import argparse
import cv2
import numpy as np
import torch
from models.with_mobilenet import PoseEstimationWithMobileNet
from modules.keypoints import extract_keypoints, group_keypoints
from modules.load_state import load_state
from modules.pose import Pose, track_poses
from val import normalize, pad_width
import time
import os
import sys
####sound
#from pydub import AudioSegment
#from pydub.playback import play
#####line notification
from line_notify import *
####end line notification
'''import imagezmq
import threading
import socket
# Helper class implementing an IO deamon thread
class VideoStreamSubscriber:
def __init__(self, hostname, port):
self.hostname = hostname
self.port = port
self._stop = False
self._data_ready = threading.Event()
self._thread = threading.Thread(target=self._run, args=())
self._thread.daemon = True
self._thread.start()
def receive(self, timeout=15.0):
flag = self._data_ready.wait(timeout=timeout)
if not flag:
raise TimeoutError(
"Timeout while reading from subscriber tcp://{}:{}".format(self.hostname, self.port))
self._data_ready.clear()
return self._data
def _run(self):
receiver = imagezmq.ImageHub("tcp://{}:{}".format(self.hostname, self.port), REQ_REP=False)
while not self._stop:
self._data = receiver.recv_jpg()
self._data_ready.set()
# Close socket here, not implemented in ImageHub :(
# zmq_socket.close()
def close(self):
self._stop = True
hostname = "192.168.1.128"
port = 5555
receiver = VideoStreamSubscriber(hostname, port)'''
def infer_fast(net, img, net_input_height_size, stride, upsample_ratio,
pad_value=(0, 0, 0), img_mean=(128, 128, 128), img_scale=1/256):
height, width, _ = img.shape
scale = net_input_height_size / height
scaled_img = cv2.resize(img, (0, 0), fx=scale, fy=scale, interpolation=cv2.INTER_CUBIC)
scaled_img = normalize(scaled_img, img_mean, img_scale)
min_dims = [net_input_height_size, max(scaled_img.shape[1], net_input_height_size)]
padded_img, pad = pad_width(scaled_img, stride, pad_value, min_dims)
tensor_img = torch.from_numpy(padded_img).permute(2, 0, 1).unsqueeze(0).float()
tensor_img = tensor_img.cuda()
stages_output = net(tensor_img)
stage2_heatmaps = stages_output[-2]
heatmaps = np.transpose(stage2_heatmaps.squeeze().cpu().data.numpy(), (1, 2, 0))
heatmaps = cv2.resize(heatmaps, (0, 0), fx=upsample_ratio, fy=upsample_ratio, interpolation=cv2.INTER_CUBIC)
stage2_pafs = stages_output[-1]
pafs = np.transpose(stage2_pafs.squeeze().cpu().data.numpy(), (1, 2, 0))
pafs = cv2.resize(pafs, (0, 0), fx=upsample_ratio, fy=upsample_ratio, interpolation=cv2.INTER_CUBIC)
return heatmaps, pafs, scale, pad
def cal_slope(pt1,pt2):
return (pt1[1]-pt2[1])/(pt1[0]-pt2[0])
def run_demo(net, height_size, track, smooth, record_vid, camera_type):
net = net.eval()
net = net.cuda()
stride = 8
upsample_ratio = 4
num_keypoints = Pose.num_kpts
previous_poses = []
##Tarit defined
slope_threshold = 0.4
ear_slope_threshold = 0.5
eye_ear_slope_threshold = 0.5
not_detected = (-1,-1)
sleep_confirmation_time = 60 #in seconds
#flags to detect whether the person is sleeping or not
sleeping = False
timer_started = False
time_notified = 0
selected_pose = None
while True:
#msg, frame = receiver.receive(timeout = 60.0)
#img = cv2.imdecode(np.frombuffer(frame, dtype='uint8'), -1)
img = cap.read()
if camera_type == "jetson":
img = img[1300:1780,1320:1960]
#start_time = time.time()
orig_img = img.copy()
heatmaps, pafs, scale, pad = infer_fast(net, img, height_size, stride, upsample_ratio)
total_keypoints_num = 0
all_keypoints_by_type = []
for kpt_idx in range(num_keypoints): # 19th for bg
total_keypoints_num += extract_keypoints(heatmaps[:, :, kpt_idx], all_keypoints_by_type, total_keypoints_num)
pose_entries, all_keypoints = group_keypoints(all_keypoints_by_type, pafs)
for kpt_id in range(all_keypoints.shape[0]):
all_keypoints[kpt_id, 0] = (all_keypoints[kpt_id, 0] * stride / upsample_ratio - pad[1]) / scale
all_keypoints[kpt_id, 1] = (all_keypoints[kpt_id, 1] * stride / upsample_ratio - pad[0]) / scale
current_poses = []
for n in range(len(pose_entries)):
if len(pose_entries[n]) == 0:
continue
pose_keypoints = np.ones((num_keypoints, 2), dtype=np.int32) * -1
for kpt_id in range(num_keypoints):
if pose_entries[n][kpt_id] != -1.0: # keypoint was found
pose_keypoints[kpt_id, 0] = int(all_keypoints[int(pose_entries[n][kpt_id]), 0])
pose_keypoints[kpt_id, 1] = int(all_keypoints[int(pose_entries[n][kpt_id]), 1])
pose = Pose(pose_keypoints, pose_entries[n][18])
current_poses.append(pose)
if track:
track_poses(previous_poses, current_poses, smooth=smooth)
previous_poses = current_poses
'''for pose in current_poses:
pose.draw(img)'''
##find longest_nect_to_nose_dst and select that pose
longest_nect_to_nose_dst = 0
for pose in current_poses:
nose = tuple(pose.keypoints[0])
neck = tuple(pose.keypoints[1])
##pythagoras
nect_to_nose_dst = pow((pow(abs(nose[0] - neck[0]) ,2)) + (pow(abs(nose[1] - neck[1]) ,2)),1/2)
if nect_to_nose_dst > longest_nect_to_nose_dst:
longest_nect_to_nose_dst = nect_to_nose_dst
selected_pose = pose
if selected_pose is not None:
selected_pose.draw(img)
nose = tuple(selected_pose.keypoints[0])
neck = tuple(selected_pose.keypoints[1])
l_ear = tuple(selected_pose.keypoints[16])
r_ear = tuple(selected_pose.keypoints[17])
l_eye = tuple(selected_pose.keypoints[15])
r_eye = tuple(selected_pose.keypoints[14])
#print(cal_slope(l_eye,l_ear),cal_slope(r_eye,r_ear))
##detect if the person back if facing to the camera
if nose == (-1,-1):
if l_ear != not_detected and r_ear != not_detected:
ear_slope = abs(l_ear[1] - r_ear[1])/abs(l_ear[0]-r_ear[0])
cv2.circle(img,l_ear,5,(255,0,0),3)
cv2.circle(img,r_ear,5,(0,255,0),3)
if ear_slope > ear_slope_threshold:
sleeping = True
print("sleeping")
else:
sleeping = False
else:
##out of condition, can't detect
sleeping = False
else:
cv2.circle(img,nose,5,(255,0,0),3)
cv2.circle(img,neck,5,(0,255,0),3)
slope_inverse = (nose[0] - neck[0])/ (nose[1] - neck[1])
l_ear_eye_slope = cal_slope(l_eye,l_ear)
r_ear_eye_slope = cal_slope(r_eye,r_ear)
#increase the slope_threshold if the person is turning their head
#print(pose.keypoints[16],pose.keypoints[17]) #print ear location
if l_ear == (-1,-1) or r_ear == (-1,-1):
slope_threshold = 1
print("one ear missing , Increasing slope_threshold")
else:
slope_threshold = 0.4
if abs(slope_inverse) > slope_threshold:
#cv2.putText(img,"".join([str(pose.id),"sleeping"]),(20,50),cv2.FONT_HERSHEY_COMPLEX,2,(255,0,0),3)
print("Sleeping (neck bend more than threshold)")
#cv2.putText(img,"sleeping",(20,50),cv2.FONT_HERSHEY_COMPLEX,2,(255,0,0),3)
sleeping = True
elif l_eye == not_detected or r_eye == not_detected:
sleeping = True
print("Sleeping (not seeing both eyes)")
elif l_ear_eye_slope < -0.6 or r_ear_eye_slope > 0.6 or l_ear_eye_slope > eye_ear_slope_threshold or r_ear_eye_slope < -eye_ear_slope_threshold:
sleeping = True
print("Sleeping (ears higher/lower than eyes)")
else:
print("Not sleeping")
sleeping = False
if sleeping:
if not timer_started:
t_start_sleep = time.time()
timer_started = True
else:
if time.time() - t_start_sleep > sleep_confirmation_time:
print("sending line message")
pic_name = "".join(["log_data/",str(time_notified),".jpg"])
cv2.imwrite(pic_name,img)
#lineNotify("Elderly sleeping %d"%time_notified)
notifyFile("Elderly sleeping %d"%time_notified,pic_name)
time_notified += 1
timer_started = False
sleeping = False
else:
timer_started = False
#song = AudioSegment.from_mp3("Alarm_Clock_Sound.mp3")
#play(song)
img = cv2.addWeighted(orig_img, 0.6, img, 0.6, 0)
for pose in current_poses:
cv2.rectangle(img, (pose.bbox[0], pose.bbox[1]),
(pose.bbox[0] + pose.bbox[2], pose.bbox[1] + pose.bbox[3]), (0, 255, 0))
if track:
cv2.putText(img, 'id: {}'.format(pose.id), (pose.bbox[0], pose.bbox[1] - 16),
cv2.FONT_HERSHEY_COMPLEX, 0.5, (0, 0, 255))
cv2.imshow('Sleep detector', img)
if record_vid:
out_raw.write(orig_img)
out_pose.write(img)
#print((1/(time.time()-start_time)))
if cv2.waitKey(1) == 27: # esc
#receiver.close()
cap.stop()
if record_vid:
out_raw.release()
out_pose.release()
return
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='''Lightweight human pose estimation python demo.
This is just for quick results preview.
Please, consider c++ demo for the best performance.''')
parser.add_argument('--checkpoint-path', type=str, default="checkpoint_iter_370000.pth", help='path to the checkpoint')
parser.add_argument('--height-size', type=int, default=128, help='network input layer height size')
parser.add_argument('--track', type=int, default=1, help='track pose id in video')
parser.add_argument('--smooth', type=int, default=1, help='smooth pose keypoints')
parser.add_argument('--camera', type=str,required=True, help='select jetson or webcam')
parser.add_argument('--record', action="store_true", help='record to video file')
args = parser.parse_args()
if not os.path.isdir("log_data"):
os.mkdir("log_data")
if args.record:
if os.path.isfile("log_data/out_no_vis.avi") or os.path.isfile("log_data/out_with_vis.avi"):
print("video exist, quitting")
sys.exit()
fourcc = cv2.VideoWriter_fourcc(*'X264')
out_raw = cv2.VideoWriter("log_data/out_no_vis.avi",fourcc,5.0,(640,480))
out_pose = cv2.VideoWriter("log_data/out_with_vis.avi",fourcc,5.0,(640,480))
if args.camera == "webcam":
from threaded_cam import ThreadedCamera
cap = ThreadedCamera()
elif args.camera == "jetson":
from threaded_cam import jetson_csi_camera
camSet = "nvarguscamerasrc sensor-id=0 ! video/x-raw(memory:NVMM), width=3280, height=2464, framerate=21/1, format=NV12 ! nvvidconv flip-method=0 ! video/x-raw, format=BGRx ! videoconvert ! video/x-raw, format=BGR ! appsink"
cap = jetson_csi_camera(camSet)
net = PoseEstimationWithMobileNet()
checkpoint = torch.load(args.checkpoint_path, map_location='cpu')
load_state(net, checkpoint)
run_demo(net, args.height_size, args.track, args.smooth,args.record, args.camera)
| [
"cv2.rectangle",
"modules.keypoints.group_keypoints",
"models.with_mobilenet.PoseEstimationWithMobileNet",
"torch.from_numpy",
"cv2.imshow",
"sys.exit",
"modules.keypoints.extract_keypoints",
"modules.pose.Pose",
"argparse.ArgumentParser",
"cv2.VideoWriter",
"cv2.addWeighted",
"os.path.isdir",... | [((1940, 2014), 'cv2.resize', 'cv2.resize', (['img', '(0, 0)'], {'fx': 'scale', 'fy': 'scale', 'interpolation': 'cv2.INTER_CUBIC'}), '(img, (0, 0), fx=scale, fy=scale, interpolation=cv2.INTER_CUBIC)\n', (1950, 2014), False, 'import cv2\n'), ((2032, 2074), 'val.normalize', 'normalize', (['scaled_img', 'img_mean', 'img_scale'], {}), '(scaled_img, img_mean, img_scale)\n', (2041, 2074), False, 'from val import normalize, pad_width\n'), ((2185, 2235), 'val.pad_width', 'pad_width', (['scaled_img', 'stride', 'pad_value', 'min_dims'], {}), '(scaled_img, stride, pad_value, min_dims)\n', (2194, 2235), False, 'from val import normalize, pad_width\n'), ((2534, 2635), 'cv2.resize', 'cv2.resize', (['heatmaps', '(0, 0)'], {'fx': 'upsample_ratio', 'fy': 'upsample_ratio', 'interpolation': 'cv2.INTER_CUBIC'}), '(heatmaps, (0, 0), fx=upsample_ratio, fy=upsample_ratio,\n interpolation=cv2.INTER_CUBIC)\n', (2544, 2635), False, 'import cv2\n'), ((2757, 2854), 'cv2.resize', 'cv2.resize', (['pafs', '(0, 0)'], {'fx': 'upsample_ratio', 'fy': 'upsample_ratio', 'interpolation': 'cv2.INTER_CUBIC'}), '(pafs, (0, 0), fx=upsample_ratio, fy=upsample_ratio,\n interpolation=cv2.INTER_CUBIC)\n', (2767, 2854), False, 'import cv2\n'), ((10454, 10691), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Lightweight human pose estimation python demo.\n This is just for quick results preview.\n Please, consider c++ demo for the best performance."""'}), '(description=\n """Lightweight human pose estimation python demo.\n This is just for quick results preview.\n Please, consider c++ demo for the best performance."""\n )\n', (10477, 10691), False, 'import argparse\n'), ((12261, 12290), 'models.with_mobilenet.PoseEstimationWithMobileNet', 'PoseEstimationWithMobileNet', ([], {}), '()\n', (12288, 12290), False, 'from models.with_mobilenet import PoseEstimationWithMobileNet\n'), ((12308, 12360), 'torch.load', 'torch.load', (['args.checkpoint_path'], {'map_location': '"""cpu"""'}), "(args.checkpoint_path, map_location='cpu')\n", (12318, 12360), False, 'import torch\n'), ((12365, 12392), 'modules.load_state.load_state', 'load_state', (['net', 'checkpoint'], {}), '(net, checkpoint)\n', (12375, 12392), False, 'from modules.load_state import load_state\n'), ((4203, 4247), 'modules.keypoints.group_keypoints', 'group_keypoints', (['all_keypoints_by_type', 'pafs'], {}), '(all_keypoints_by_type, pafs)\n', (4218, 4247), False, 'from modules.keypoints import extract_keypoints, group_keypoints\n'), ((9596, 9639), 'cv2.addWeighted', 'cv2.addWeighted', (['orig_img', '(0.6)', 'img', '(0.6)', '(0)'], {}), '(orig_img, 0.6, img, 0.6, 0)\n', (9611, 9639), False, 'import cv2\n'), ((10033, 10066), 'cv2.imshow', 'cv2.imshow', (['"""Sleep detector"""', 'img'], {}), "('Sleep detector', img)\n", (10043, 10066), False, 'import cv2\n'), ((11314, 11339), 'os.path.isdir', 'os.path.isdir', (['"""log_data"""'], {}), "('log_data')\n", (11327, 11339), False, 'import os\n'), ((11349, 11369), 'os.mkdir', 'os.mkdir', (['"""log_data"""'], {}), "('log_data')\n", (11357, 11369), False, 'import os\n'), ((11575, 11606), 'cv2.VideoWriter_fourcc', 'cv2.VideoWriter_fourcc', (["*'X264'"], {}), "(*'X264')\n", (11597, 11606), False, 'import cv2\n'), ((11630, 11697), 'cv2.VideoWriter', 'cv2.VideoWriter', (['"""log_data/out_no_vis.avi"""', 'fourcc', '(5.0)', '(640, 480)'], {}), "('log_data/out_no_vis.avi', fourcc, 5.0, (640, 480))\n", (11645, 11697), False, 'import cv2\n'), ((11713, 11782), 'cv2.VideoWriter', 'cv2.VideoWriter', (['"""log_data/out_with_vis.avi"""', 'fourcc', '(5.0)', '(640, 480)'], {}), "('log_data/out_with_vis.avi', fourcc, 5.0, (640, 480))\n", (11728, 11782), False, 'import cv2\n'), ((11874, 11890), 'threaded_cam.ThreadedCamera', 'ThreadedCamera', ([], {}), '()\n', (11888, 11890), False, 'from threaded_cam import ThreadedCamera\n'), ((4077, 4167), 'modules.keypoints.extract_keypoints', 'extract_keypoints', (['heatmaps[:, :, kpt_idx]', 'all_keypoints_by_type', 'total_keypoints_num'], {}), '(heatmaps[:, :, kpt_idx], all_keypoints_by_type,\n total_keypoints_num)\n', (4094, 4167), False, 'from modules.keypoints import extract_keypoints, group_keypoints\n'), ((5076, 5117), 'modules.pose.Pose', 'Pose', (['pose_keypoints', 'pose_entries[n][18]'], {}), '(pose_keypoints, pose_entries[n][18])\n', (5080, 5117), False, 'from modules.pose import Pose, track_poses\n'), ((5188, 5245), 'modules.pose.track_poses', 'track_poses', (['previous_poses', 'current_poses'], {'smooth': 'smooth'}), '(previous_poses, current_poses, smooth=smooth)\n', (5199, 5245), False, 'from modules.pose import Pose, track_poses\n'), ((9688, 9814), 'cv2.rectangle', 'cv2.rectangle', (['img', '(pose.bbox[0], pose.bbox[1])', '(pose.bbox[0] + pose.bbox[2], pose.bbox[1] + pose.bbox[3])', '(0, 255, 0)'], {}), '(img, (pose.bbox[0], pose.bbox[1]), (pose.bbox[0] + pose.bbox[\n 2], pose.bbox[1] + pose.bbox[3]), (0, 255, 0))\n', (9701, 9814), False, 'import cv2\n'), ((10215, 10229), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (10226, 10229), False, 'import cv2\n'), ((11401, 11442), 'os.path.isfile', 'os.path.isfile', (['"""log_data/out_no_vis.avi"""'], {}), "('log_data/out_no_vis.avi')\n", (11415, 11442), False, 'import os\n'), ((11446, 11489), 'os.path.isfile', 'os.path.isfile', (['"""log_data/out_with_vis.avi"""'], {}), "('log_data/out_with_vis.avi')\n", (11460, 11489), False, 'import os\n'), ((11546, 11556), 'sys.exit', 'sys.exit', ([], {}), '()\n', (11554, 11556), False, 'import sys\n'), ((12224, 12249), 'threaded_cam.jetson_csi_camera', 'jetson_csi_camera', (['camSet'], {}), '(camSet)\n', (12241, 12249), False, 'from threaded_cam import jetson_csi_camera\n'), ((4685, 4728), 'numpy.ones', 'np.ones', (['(num_keypoints, 2)'], {'dtype': 'np.int32'}), '((num_keypoints, 2), dtype=np.int32)\n', (4692, 4728), True, 'import numpy as np\n'), ((7067, 7107), 'cv2.circle', 'cv2.circle', (['img', 'nose', '(5)', '(255, 0, 0)', '(3)'], {}), '(img, nose, 5, (255, 0, 0), 3)\n', (7077, 7107), False, 'import cv2\n'), ((7118, 7158), 'cv2.circle', 'cv2.circle', (['img', 'neck', '(5)', '(0, 255, 0)', '(3)'], {}), '(img, neck, 5, (0, 255, 0), 3)\n', (7128, 7158), False, 'import cv2\n'), ((6624, 6665), 'cv2.circle', 'cv2.circle', (['img', 'l_ear', '(5)', '(255, 0, 0)', '(3)'], {}), '(img, l_ear, 5, (255, 0, 0), 3)\n', (6634, 6665), False, 'import cv2\n'), ((6680, 6721), 'cv2.circle', 'cv2.circle', (['img', 'r_ear', '(5)', '(0, 255, 0)', '(3)'], {}), '(img, r_ear, 5, (0, 255, 0), 3)\n', (6690, 6721), False, 'import cv2\n'), ((8796, 8807), 'time.time', 'time.time', ([], {}), '()\n', (8805, 8807), False, 'import time\n'), ((9111, 9137), 'cv2.imwrite', 'cv2.imwrite', (['pic_name', 'img'], {}), '(pic_name, img)\n', (9122, 9137), False, 'import cv2\n'), ((2254, 2282), 'torch.from_numpy', 'torch.from_numpy', (['padded_img'], {}), '(padded_img)\n', (2270, 2282), False, 'import torch\n'), ((8894, 8905), 'time.time', 'time.time', ([], {}), '()\n', (8903, 8905), False, 'import time\n')] |
import numpy as np
from gym_env.feature_processors.enums import ACTION_NAME_TO_INDEX, DOUBLE_ACTION_PARA_TYPE
class Instance:
# reward is the td n reward plus the target state value
def __init__(self,
dota_time=None,
state_gf=None,
state_ucf=None,
state_ucategory=None,
mask=None,
reward=0,
action=None,
action_params=None,
state_value=0,
dump_path=None,
instant_reward=0.,
gae_advantage=0,
action_prob=None,
sub_action_prob=1,
final_action_prob=None,
model_time=None,
units_mask=None,
lstm_state=None,
lstm_gradient_mask=None,
embedding_dict=None,
dota_map=None,
update_times=0):
self.dota_time = dota_time
self.state_gf = state_gf
self.state_ucf = state_ucf
self.state_ucategory = state_ucategory
self.mask = mask
self.state_value = state_value
self.action = action
self.action_params = action_params
self.q_reward = reward
self.instant_reward = instant_reward
self.model_time = model_time
self.action_prob = action_prob
self.sub_action_prob = sub_action_prob
self.gae_advantage = gae_advantage
self.units_mask = units_mask
self.lstm_state = lstm_state
self.lstm_gradient_mask = 1
self.embedding_dict = embedding_dict
self.dota_map = dota_map
self.update_times = update_times
def zeros_like(self, target_instance):
self.dota_time = 0
self.state_gf = np.zeros_like(target_instance.state_gf)
self.state_ucf = np.zeros_like(target_instance.state_ucf)
# for ensure there is one enemy hero/tower
self.state_ucategory = target_instance.state_ucategory
self.mask = np.zeros_like(target_instance.mask)
self.state_value = 0
self.action = ACTION_NAME_TO_INDEX["STOP"]
self.action_params = {}
for atype in DOUBLE_ACTION_PARA_TYPE:
self.action_params[atype] = 0
self.q_reward = 0
self.instant_reward = 0
self.model_time = target_instance.model_time
self.action_prob = 1
self.sub_action_prob = 1
self.gae_advantage = 0
self.units_mask = np.zeros_like(target_instance.units_mask)
self.lstm_state = np.zeros_like(target_instance.lstm_state)
self.lstm_gradient_mask = 1
self.embedding_dict = target_instance.embedding_dict
self.dota_map = np.zeros_like(target_instance.dota_map)
self.update_times = 0
def padding_instance(reward_instance, latest_instance, total_length, exclude_last_instance):
padding_length = total_length - len(reward_instance)
if exclude_last_instance:
start_position = -len(reward_instance) - 1
else:
start_position = -len(reward_instance)
padding_instances = latest_instance[start_position - padding_length:start_position]
if len(padding_instances) < padding_length:
zero_instance = Instance()
zero_instance.zeros_like(reward_instance[0])
for i in range(padding_length - len(padding_instances)):
padding_instances.insert(0, zero_instance)
#padding instance do not compute gradient
for index, item in enumerate(padding_instances):
padding_instances[index].lstm_gradient_mask = 0
for index, item in enumerate(reward_instance):
reward_instance[index].lstm_gradient_mask = 1
padding_instances.extend(reward_instance)
return padding_instances
| [
"numpy.zeros_like"
] | [((1822, 1861), 'numpy.zeros_like', 'np.zeros_like', (['target_instance.state_gf'], {}), '(target_instance.state_gf)\n', (1835, 1861), True, 'import numpy as np\n'), ((1887, 1927), 'numpy.zeros_like', 'np.zeros_like', (['target_instance.state_ucf'], {}), '(target_instance.state_ucf)\n', (1900, 1927), True, 'import numpy as np\n'), ((2062, 2097), 'numpy.zeros_like', 'np.zeros_like', (['target_instance.mask'], {}), '(target_instance.mask)\n', (2075, 2097), True, 'import numpy as np\n'), ((2530, 2571), 'numpy.zeros_like', 'np.zeros_like', (['target_instance.units_mask'], {}), '(target_instance.units_mask)\n', (2543, 2571), True, 'import numpy as np\n'), ((2599, 2640), 'numpy.zeros_like', 'np.zeros_like', (['target_instance.lstm_state'], {}), '(target_instance.lstm_state)\n', (2612, 2640), True, 'import numpy as np\n'), ((2762, 2801), 'numpy.zeros_like', 'np.zeros_like', (['target_instance.dota_map'], {}), '(target_instance.dota_map)\n', (2775, 2801), True, 'import numpy as np\n')] |
import random
import numpy as np
class DiscreteDistribution:
"""
This class represents a (conditional) discrete probability distribution.
More specifically, it stores the probabilities `P(output = j | input = i)`
of generating an output j given an input i.
Generally, such a distribution is represented by a matrix where p_ij denotes
the entry in row i and column j.
Each row is guaranteed to sum up to 1 to satisfy the property of a probability distribution.
As an optimization, if `P(output = j | input = i) = P(output = j)`, i.e., the distribution is independent
of the input value, only a single row is stored.
"""
def __init__(self, weights):
"""
Creates a new discrete distribution.
The input can be either a list of weights (if `P(output = j | input = i) = P(output = j)`),
or a matrix of weights.
This method will take care of normalizing the weights, so that each row sums up to 1.
"""
if not isinstance(weights, np.ndarray):
weights = np.array(weights)
if weights.dtype == np.dtype("O"):
raise ValueError("Weights must be a list or matrix of number types")
if len(weights.shape) not in (1, 2):
raise ValueError("Weights must be a list or matrix")
if any([length < 1 for length in weights.shape]):
raise ValueError("Cannot create an empty probability distribution")
self.probabilities = weights
self.is_matrix = len(weights.shape) == 2
self.normalize()
@classmethod
def __get_validators__(cls):
# one or more validators may be yielded which will be called in the
# order to validate the input, each validator will receive as an input
# the value returned from the previous validator
yield cls.validate
@classmethod
def __modify_schema__(cls, field_schema):
# __modify_schema__ should mutate the dict it receives in place,
# the returned value will be ignored
field_schema.update(
title="DiscreteDistribution", type="object",
)
@classmethod
def validate(cls, v):
if not isinstance(v, DiscreteDistribution):
raise TypeError("DiscreteDistribution required")
return v
@classmethod
def uniform_distribution(cls, n):
"""
Creates a uniform distribution over n values.
"""
return UniformDistribution(n)
def normalize(self):
"""
Normalizes the weights to ensure that each row sums up to 1.
This is achieved by dividing each entry by the sum of all probabilities.
If the weights are a matrix, the operation is performed per row.
"""
if self.is_matrix:
# Matrix case
norm = np.abs(self.probabilities).sum(axis=1)[np.newaxis]
self.probabilities = self.probabilities / norm.transpose()
else:
# Array case
norm = np.abs(self.probabilities).sum()
self.probabilities = self.probabilities / norm
def to_full_distribution(self):
"""
Returns the full matrix representation for any discrete distribution representation.
This allows to have a consistent representation for operations on the matrix.
If the current distribution is already represented as a matrix, self is returned.
"""
if self.is_matrix:
return self
else:
size = self.probabilities.shape[0]
probabilities = np.tile(self.probabilities, (size, size))
return DiscreteDistribution(probabilities)
def to_cumulative(self):
"""
Returns the corresponding cumulative distribution.
The cumulative distribution is used for sampling.
"""
return CumulativeDiscreteDistribution(self)
def with_rr_toss(self, p):
"""
Simulates a randomized response toss with a probability of p for reporting the true value.
This results in a probability of p'_ii = p + (1 - p) * p_ii along the diagonal
and multiplies all other probabilities by (1 - p).
Returns a new distribution and does not modify the current one.
"""
full = self.to_full_distribution()
# Multiply each entry by (1 - p)
full.probabilities *= 1 - p
# Create diagonal matrix with p
diag = np.zeros(full.probabilities.shape)
np.fill_diagonal(diag, p)
# Add p along diagonal
full.probabilities += diag
return full
def __len__(self):
"""
Returns the number of items in the distribution.
"""
return len(self.probabilities)
class CumulativeDiscreteDistribution:
"""
A cumulative representation of a discrete probability distribution.
This can be used to speed up sampling.
"""
def __init__(self, discrete_distribution):
"""
Creates a new cumulative distribution from a DiscreteDistribution.
"""
if discrete_distribution.is_matrix:
self.cum_probabilities = np.cumsum(discrete_distribution.probabilities, axis=1)
self.is_matrix = True
else:
self.cum_probabilities = np.cumsum(discrete_distribution.probabilities)
self.is_matrix = False
def sample_element(self, input_idx, rng=random.SystemRandom()):
"""
Samples an output index j based in the given input index `input_idx`
according to the distribution `P(output = j | input = i)`.
Optionally takes an random number generator that implements the method `choices` following `random.choices`.
By default, SystemRandom is used.
"""
row = self.cum_probabilities
if self.is_matrix:
row = self.cum_probabilities[input_idx]
return rng.choices(range(len(row)), cum_weights=row)[0]
def __len__(self):
"""
Returns the number of items in the distribution.
"""
return len(self.cum_probabilities)
class UniformDistribution(DiscreteDistribution, CumulativeDiscreteDistribution):
"""
The uniform distribution is a special case of a distribution, which can efficiently be represented by
the number of possible values n (also for the cumulative distribution).
"""
def __init__(self, n):
"""
Instantiates a uniform distribution over n values.
"""
super().__init__([1])
self.n = n
def normalize(self):
"""
No need for normalization here.
"""
pass
def to_full_distribution(self):
"""
Returns the full matrix representation for any discrete distribution representation.
This allows to have a consistent representation for operations on the matrix.
"""
probabilities = np.ones((self.n, self.n))
return DiscreteDistribution(probabilities)
def to_cumulative(self):
"""
Returns the corresponding cumulative distribution.
The cumulative distribution is used for sampling.
"""
return self
def sample_element(self, input_idx, rng=random.SystemRandom()):
"""
Samples an output index j based in the given input index `input_idx`
according to the distribution `P(output = j | input = i)`.
Optionally takes an random number generator that implements the method `choices` following `random.choices`.
By default, SystemRandom is used.
"""
return rng.choices(range(self.n))[0]
def __len__(self):
"""
Returns the number of items in the distribution.
"""
return self.n
| [
"numpy.tile",
"numpy.abs",
"numpy.ones",
"numpy.fill_diagonal",
"numpy.array",
"numpy.zeros",
"numpy.cumsum",
"numpy.dtype",
"random.SystemRandom"
] | [((4440, 4474), 'numpy.zeros', 'np.zeros', (['full.probabilities.shape'], {}), '(full.probabilities.shape)\n', (4448, 4474), True, 'import numpy as np\n'), ((4483, 4508), 'numpy.fill_diagonal', 'np.fill_diagonal', (['diag', 'p'], {}), '(diag, p)\n', (4499, 4508), True, 'import numpy as np\n'), ((5406, 5427), 'random.SystemRandom', 'random.SystemRandom', ([], {}), '()\n', (5425, 5427), False, 'import random\n'), ((6894, 6919), 'numpy.ones', 'np.ones', (['(self.n, self.n)'], {}), '((self.n, self.n))\n', (6901, 6919), True, 'import numpy as np\n'), ((7207, 7228), 'random.SystemRandom', 'random.SystemRandom', ([], {}), '()\n', (7226, 7228), False, 'import random\n'), ((1064, 1081), 'numpy.array', 'np.array', (['weights'], {}), '(weights)\n', (1072, 1081), True, 'import numpy as np\n'), ((1111, 1124), 'numpy.dtype', 'np.dtype', (['"""O"""'], {}), "('O')\n", (1119, 1124), True, 'import numpy as np\n'), ((3570, 3611), 'numpy.tile', 'np.tile', (['self.probabilities', '(size, size)'], {}), '(self.probabilities, (size, size))\n', (3577, 3611), True, 'import numpy as np\n'), ((5139, 5193), 'numpy.cumsum', 'np.cumsum', (['discrete_distribution.probabilities'], {'axis': '(1)'}), '(discrete_distribution.probabilities, axis=1)\n', (5148, 5193), True, 'import numpy as np\n'), ((5279, 5325), 'numpy.cumsum', 'np.cumsum', (['discrete_distribution.probabilities'], {}), '(discrete_distribution.probabilities)\n', (5288, 5325), True, 'import numpy as np\n'), ((3007, 3033), 'numpy.abs', 'np.abs', (['self.probabilities'], {}), '(self.probabilities)\n', (3013, 3033), True, 'import numpy as np\n'), ((2827, 2853), 'numpy.abs', 'np.abs', (['self.probabilities'], {}), '(self.probabilities)\n', (2833, 2853), True, 'import numpy as np\n')] |
__copyright__ = """
Copyright (C) 2020 University of Illinois Board of Trustees
Copyright (C) 2021 <NAME>
"""
__license__ = """
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import sys
import cantera as ct
import numpy as np # noqa: F401
import pyrometheus as pyro
import pytest
try:
import jax
except ImportError:
numpy_list = [np]
jnp = None
else:
import jax.numpy as jnp # noqa: F401
jax.config.update("jax_enable_x64", 1)
numpy_list = [np, jnp]
def make_jax_pyro_class(ptk_base_cls, usr_np):
if usr_np != jnp:
return ptk_base_cls(usr_np)
class PyroJaxNumpy(ptk_base_cls):
def _pyro_make_array(self, res_list):
"""This works around (e.g.) numpy.exp not working with object arrays of numpy
scalars. It defaults to making object arrays, however if an array
consists of all scalars, it makes a "plain old" :class:`numpy.ndarray`.
See ``this numpy bug <https://github.com/numpy/numpy/issues/18004>`__
for more context.
"""
from numbers import Number
# Needed to play nicely with Jax, which frequently creates
# arrays of shape () when handed numbers
all_numbers = all(
isinstance(e, Number)
or (isinstance(e, self.usr_np.ndarray) and e.shape == ())
for e in res_list)
if all_numbers:
return self.usr_np.array(res_list, dtype=self.usr_np.float64)
result = self.usr_np.empty_like(res_list, dtype=object,
shape=(len(res_list),))
# 'result[:] = res_list' may look tempting, however:
# https://github.com/numpy/numpy/issues/16564
for idx in range(len(res_list)):
result[idx] = res_list[idx]
return result
def _pyro_norm(self, argument, normord):
"""This works around numpy.linalg norm not working with scalars.
If the argument is a regular ole number, it uses :func:`numpy.abs`,
otherwise it uses ``usr_np.linalg.norm``.
"""
# Wrap norm for scalars
from numbers import Number
if isinstance(argument, Number):
return self.usr_np.abs(argument)
# Needed to play nicely with Jax, which frequently creates
# arrays of shape () when handed numbers
if isinstance(argument, self.usr_np.ndarray) and argument.shape == ():
return self.usr_np.abs(argument)
return self.usr_np.linalg.norm(argument, normord)
return PyroJaxNumpy(usr_np=usr_np)
# Write out all the mechanisms for inspection
@pytest.mark.parametrize("mechname", ["uiuc", "sanDiego"])
def test_generate_mechfile(mechname):
"""This "test" produces the mechanism codes."""
sol = ct.Solution(f"mechs/{mechname}.cti", "gas")
with open(f"mechs/{mechname}.py", "w") as mech_file:
code = pyro.gen_thermochem_code(sol)
print(code, file=mech_file)
@pytest.mark.parametrize("mechname", ["uiuc", "sanDiego"])
@pytest.mark.parametrize("usr_np", numpy_list)
def test_get_rate_coefficients(mechname, usr_np):
"""This function tests that pyrometheus-generated code
computes the rate coefficients matching Cantera
for given temperature and composition"""
sol = ct.Solution(f"mechs/{mechname}.cti", "gas")
ptk_base_cls = pyro.get_thermochem_class(sol)
ptk = make_jax_pyro_class(ptk_base_cls, usr_np)
# Test temperatures
temp = np.linspace(500.0, 3000.0, 10)
for t in temp:
# Set new temperature in Cantera
sol.TP = t, ct.one_atm
# Concentrations
y = sol.Y
rho = sol.density
c = ptk.get_concentrations(rho, y)
# Get rate coefficients and compare
k_ct = sol.forward_rate_constants
k_pm = ptk.get_fwd_rate_coefficients(t, c)
print(k_ct)
print(np.abs((k_ct-k_pm)/k_ct))
assert np.linalg.norm((k_ct-k_pm)/k_ct, np.inf) < 1e-14
return
@pytest.mark.parametrize("mechname", ["uiuc", "sanDiego"])
@pytest.mark.parametrize("usr_np", numpy_list)
def test_get_pressure(mechname, usr_np):
"""This function tests that pyrometheus-generated code
computes the Cantera-predicted pressure for given density,
temperature, and mass fractions
"""
# Create Cantera and pyrometheus objects
sol = ct.Solution(f"mechs/{mechname}.cti", "gas")
ptk_base_cls = pyro.get_thermochem_class(sol)
ptk = make_jax_pyro_class(ptk_base_cls, usr_np)
# Temperature, equivalence ratio, oxidizer ratio, stoichiometry ratio
t = 300.0
phi = 2.0
alpha = 0.21
nu = 0.5
# Species mass fractions
i_fu = ptk.species_index("H2")
i_ox = ptk.species_index("O2")
i_di = ptk.species_index("N2")
x = np.zeros(ptk.num_species)
x[i_fu] = (alpha * phi) / (nu + alpha * phi)
x[i_ox] = nu * x[i_fu] / phi
x[i_di] = (1.0 - alpha) * x[i_ox] / alpha
# Get equilibrium composition
sol.TPX = t, ct.one_atm, x
sol.equilibrate("UV")
t, rho, y = sol.TDY
p_ct = sol.P
# Compute pressure with pyrometheus and compare to Cantera
p_pm = ptk.get_pressure(rho, t, y)
assert abs(p_ct - p_pm) / p_ct < 1.0e-12
@pytest.mark.parametrize("mechname", ["uiuc", "sanDiego"])
@pytest.mark.parametrize("usr_np", numpy_list)
def test_get_thermo_properties(mechname, usr_np):
"""This function tests that pyrometheus-generated code
computes thermodynamic properties c_p, s_r, h_rt, and k_eq
correctly by comparing against Cantera"""
# Create Cantera and pyrometheus objects
sol = ct.Solution(f"mechs/{mechname}.cti", "gas")
ptk_base_cls = pyro.get_thermochem_class(sol)
ptk = make_jax_pyro_class(ptk_base_cls, usr_np)
# Loop over temperatures
temp = np.linspace(500.0, 3000.0, 10)
for t in temp:
# Set state in cantera for comparison
sol.TP = t, ct.one_atm
# Get properties from pyrometheus and compare to Cantera
cp_pm = ptk.get_species_specific_heats_r(t)
cp_err = np.linalg.norm(cp_pm - sol.standard_cp_R, np.inf)
print(f"cp_pm = {cp_pm}")
print(f"cnt_cp = {sol.standard_cp_R}")
assert cp_err < 1.0e-13
s_pm = ptk.get_species_entropies_r(t)
s_err = np.linalg.norm(s_pm - sol.standard_entropies_R, np.inf)
print(f"s_pm = {s_pm}")
print(f"cnt_s = {sol.standard_entropies_R}")
assert s_err < 1.0e-13
h_pm = ptk.get_species_enthalpies_rt(t)
h_err = np.linalg.norm(h_pm - sol.standard_enthalpies_RT, np.inf)
print(f"h_pm = {h_pm}")
print(f"cnt_h = {sol.standard_enthalpies_RT}")
assert h_err < 1.0e-13
keq_pm1 = ptk.get_equilibrium_constants(t)
print(f"keq1 = {keq_pm1}")
keq_pm = 1.0 / np.exp(ptk.get_equilibrium_constants(t))
keq_ct = sol.equilibrium_constants
print(f"keq_pm = {keq_pm}")
print(f"keq_cnt = {keq_ct}")
print(f"temperature = {t}")
# xclude meaningless check on equilibrium constants for irreversible reaction
for i, reaction in enumerate(sol.reactions()):
if reaction.reversible:
keq_err = np.abs((keq_pm[i] - keq_ct[i]) / keq_ct[i])
print(f"keq_err = {keq_err}")
assert keq_err < 1.0e-13
# keq_pm_test = keq_pm[1:]
# keq_ct_test = keq_ct[1:]
# keq_err = np.linalg.norm((keq_pm_test - keq_ct_test) / keq_ct_test, np.inf)
# assert keq_err < 1.0e-13
return
@pytest.mark.parametrize("mechname", ["uiuc", "sanDiego"])
@pytest.mark.parametrize("usr_np", numpy_list)
def test_get_temperature(mechname, usr_np):
"""This function tests that pyrometheus-generated code
computes the Cantera-predicted temperature for given internal energy
and mass fractions"""
# Create Cantera and pyrometheus objects
sol = ct.Solution(f"mechs/{mechname}.cti", "gas")
ptk_base_cls = pyro.get_thermochem_class(sol)
ptk = make_jax_pyro_class(ptk_base_cls, usr_np)
tol = 1.0e-10
# Test temperatures
temp = np.linspace(500.0, 3000.0, 10)
# First test individual species
y = np.zeros(ptk.num_species)
for sp in range(ptk.num_species):
y[sp] = 1.0
for t in temp:
sol.TPY = t, ct.one_atm, y
e = sol.int_energy_mass
t_guess = 0.9 * t
t_pm = ptk.get_temperature(e, t_guess, y, True)
assert np.abs(t - t_pm) < tol
y[sp] = 0.0
# Now test a mixture with fully-populated composition
# All mass fractions set to the same value for now,
# though a more representative test would be ignition composition
y = np.ones(ptk.num_species) / ptk.num_species
for t in temp:
sol.TPY = t, ct.one_atm, y
e = sol.int_energy_mass
t_guess = 0.9 * t
t_pm = ptk.get_temperature(e, t_guess, y, True)
assert np.abs(t - t_pm) < tol
@pytest.mark.parametrize("mechname, fuel, stoich_ratio, dt",
[("uiuc", "C2H4", 3.0, 1e-7),
("sanDiego", "H2", 0.5, 1e-6)])
@pytest.mark.parametrize("usr_np", numpy_list)
def test_kinetics(mechname, fuel, stoich_ratio, dt, usr_np):
"""This function tests that pyrometheus-generated code
computes the Cantera-predicted rates of progress for given
temperature and composition"""
sol = ct.Solution(f"mechs/{mechname}.cti", "gas")
ptk_base_cls = pyro.get_thermochem_class(sol)
ptk = make_jax_pyro_class(ptk_base_cls, usr_np)
# Homogeneous reactor to get test data
init_temperature = 1500.0
equiv_ratio = 1.0
ox_di_ratio = 0.21
i_fu = sol.species_index(fuel)
i_ox = sol.species_index("O2")
i_di = sol.species_index("N2")
x = np.zeros(ptk.num_species)
x[i_fu] = (ox_di_ratio*equiv_ratio)/(stoich_ratio+ox_di_ratio*equiv_ratio)
x[i_ox] = stoich_ratio*x[i_fu]/equiv_ratio
x[i_di] = (1.0-ox_di_ratio)*x[i_ox]/ox_di_ratio
# Init Cantera reactor
sol.TPX = init_temperature, ct.one_atm, x
reactor = ct.IdealGasConstPressureReactor(sol)
sim = ct.ReactorNet([reactor])
time = 0.0
for _ in range(100):
time += dt
sim.advance(time)
# Cantera kinetics
r_ct = reactor.kinetics.net_rates_of_progress
omega_ct = reactor.kinetics.net_production_rates
# Get state from Cantera
temp = reactor.T
rho = reactor.density
y = np.where(reactor.Y > 0, reactor.Y, 0)
# Prometheus kinetics
c = ptk.get_concentrations(rho, y)
r_pm = ptk.get_net_rates_of_progress(temp, c)
omega_pm = ptk.get_net_production_rates(rho, temp, y)
err_r = np.linalg.norm(r_ct-r_pm, np.inf)
err_omega = np.linalg.norm(omega_ct - omega_pm, np.inf)
# Print
print("T = ", reactor.T)
print("y_ct", reactor.Y)
print("y = ", y)
print("omega_ct = ", omega_ct)
print("omega_pm = ", omega_pm)
print("err_omega = ", err_omega)
print("err_r = ", err_r)
print()
# Compare
assert err_r < 1.0e-10
assert err_omega < 1.0e-10
return
def test_autodiff_accuracy():
pytest.importorskip("jax")
assert jnp is not None
sol = ct.Solution("mechs/sanDiego.cti", "gas")
ptk_base_cls = pyro.get_thermochem_class(sol)
ptk = make_jax_pyro_class(ptk_base_cls, jnp)
# mass ratios
equiv_ratio = 1.0
ox_di_ratio = 0.21
stoich_ratio = 0.5
# indices
i_fu = ptk.species_index("H2")
i_ox = ptk.species_index("O2")
i_di = ptk.species_index("N2")
# mole fractions
x = np.zeros(ptk.num_species)
x[i_fu] = (ox_di_ratio*equiv_ratio)/(stoich_ratio+ox_di_ratio*equiv_ratio)
x[i_ox] = stoich_ratio*x[i_fu]/equiv_ratio
x[i_di] = (1.0-ox_di_ratio)*x[i_ox]/ox_di_ratio
# mass fractions
y = x * ptk.wts / sum(x*ptk.wts)
# energy
temperature = 1500
enthalpy = ptk.get_mixture_enthalpy_mass(temperature, y)
# get equilibrium temperature
sol.TPX = temperature, ct.one_atm, x
y = sol.Y
mass_fractions = jnp.array(y)
guess_temp = 1400
def chemical_source_term(mass_fractions):
temperature = ptk.get_temperature(enthalpy, guess_temp, mass_fractions)
density = ptk.get_density(ptk.one_atm, temperature, mass_fractions)
return ptk.get_net_production_rates(density, temperature, mass_fractions)
from jax import jacfwd
chemical_jacobian = jacfwd(chemical_source_term)
def jacobian_fd_approx(mass_fractions, delta_y):
# Second-order (central) difference
return jnp.array([
(chemical_source_term(mass_fractions+delta_y*v)
- chemical_source_term(mass_fractions-delta_y*v))/(2*delta_y)
for v in jnp.eye(len(mass_fractions))
]).T
j = chemical_jacobian(mass_fractions)
deltas = np.array([1e-5, 1e-6, 1e-7])
err = np.zeros(len(deltas))
from pytools.convergence import EOCRecorder
eocrec = EOCRecorder()
for i, delta_y in enumerate(deltas):
j_fd = jacobian_fd_approx(mass_fractions, delta_y)
# Lapack norm (Anderson)
err[i] = np.linalg.norm(j-j_fd, "fro")/np.linalg.norm(j, "fro")
eocrec.add_data_point(delta_y, err[i])
print("------------------------------------------------------")
print("expected order: 2")
print("------------------------------------------------------")
print(eocrec.pretty_print())
orderest = eocrec.estimate_order_of_convergence()[0, 1]
assert orderest > 1.95
@pytest.mark.parametrize("mechname, fuel, stoich_ratio",
[("UConn32", "C2H4", 3),
("sanDiego", "H2", 0.5)])
def test_falloff_kinetics(mechname, fuel, stoich_ratio):
"""This function tests that pyrometheus-generated code
computes the Cantera-predicted falloff rate coefficients"""
sol = ct.Solution(f"mechs/{mechname}.cti", "gas")
ptk = pyro.get_thermochem_class(sol)()
# Homogeneous reactor to get test data
init_temperature = 1500
equiv_ratio = 1
ox_di_ratio = 0.21
i_fu = sol.species_index(fuel)
i_ox = sol.species_index("O2")
i_di = sol.species_index("N2")
x = np.zeros(ptk.num_species)
x[i_fu] = (ox_di_ratio*equiv_ratio)/(stoich_ratio+ox_di_ratio*equiv_ratio)
x[i_ox] = stoich_ratio*x[i_fu]/equiv_ratio
x[i_di] = (1.0-ox_di_ratio)*x[i_ox]/ox_di_ratio
# Init Cantera reactor
sol.TPX = init_temperature, ct.one_atm, x
reactor = ct.IdealGasConstPressureReactor(sol)
sim = ct.ReactorNet([reactor])
# Falloff reactions
i_falloff = [i for i, r in enumerate(sol.reactions())
if isinstance(r, ct.FalloffReaction)]
dt = 1e-6
time = 0
for _ in range(100):
time += dt
sim.advance(time)
# Cantera kinetics
k_ct = reactor.kinetics.forward_rate_constants
# Get state from Cantera
density = reactor.density
temperature = reactor.T
mass_fractions = np.where(reactor.Y > 0, reactor.Y, 0)
# Prometheus kinetics
concentrations = ptk.get_concentrations(density, mass_fractions)
k_pm = ptk.get_fwd_rate_coefficients(temperature, concentrations)
err = np.linalg.norm((k_ct[i_falloff] - k_pm[i_falloff])/k_ct[i_falloff],
np.inf)
# Print
print("T = ", reactor.T)
print("k_ct = ", k_ct[i_falloff])
print("k_pm = ", k_pm[i_falloff])
print("err = ", err)
# Compare
assert err < 2e-14
return
# run single tests using
# $ python test_codegen.py 'test_sandiego()'
if __name__ == "__main__":
if len(sys.argv) > 1:
exec(sys.argv[1])
else:
from pytest import main
main([__file__])
| [
"pyrometheus.gen_thermochem_code",
"pytools.convergence.EOCRecorder",
"numpy.array",
"numpy.linalg.norm",
"numpy.where",
"pytest.main",
"numpy.linspace",
"cantera.Solution",
"numpy.abs",
"numpy.ones",
"cantera.ReactorNet",
"jax.jacfwd",
"jax.config.update",
"jax.numpy.array",
"pytest.mar... | [((3714, 3771), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""mechname"""', "['uiuc', 'sanDiego']"], {}), "('mechname', ['uiuc', 'sanDiego'])\n", (3737, 3771), False, 'import pytest\n'), ((4057, 4114), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""mechname"""', "['uiuc', 'sanDiego']"], {}), "('mechname', ['uiuc', 'sanDiego'])\n", (4080, 4114), False, 'import pytest\n'), ((4116, 4161), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""usr_np"""', 'numpy_list'], {}), "('usr_np', numpy_list)\n", (4139, 4161), False, 'import pytest\n'), ((5069, 5126), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""mechname"""', "['uiuc', 'sanDiego']"], {}), "('mechname', ['uiuc', 'sanDiego'])\n", (5092, 5126), False, 'import pytest\n'), ((5128, 5173), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""usr_np"""', 'numpy_list'], {}), "('usr_np', numpy_list)\n", (5151, 5173), False, 'import pytest\n'), ((6296, 6353), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""mechname"""', "['uiuc', 'sanDiego']"], {}), "('mechname', ['uiuc', 'sanDiego'])\n", (6319, 6353), False, 'import pytest\n'), ((6355, 6400), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""usr_np"""', 'numpy_list'], {}), "('usr_np', numpy_list)\n", (6378, 6400), False, 'import pytest\n'), ((8607, 8664), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""mechname"""', "['uiuc', 'sanDiego']"], {}), "('mechname', ['uiuc', 'sanDiego'])\n", (8630, 8664), False, 'import pytest\n'), ((8666, 8711), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""usr_np"""', 'numpy_list'], {}), "('usr_np', numpy_list)\n", (8689, 8711), False, 'import pytest\n'), ((10022, 10149), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""mechname, fuel, stoich_ratio, dt"""', "[('uiuc', 'C2H4', 3.0, 1e-07), ('sanDiego', 'H2', 0.5, 1e-06)]"], {}), "('mechname, fuel, stoich_ratio, dt', [('uiuc',\n 'C2H4', 3.0, 1e-07), ('sanDiego', 'H2', 0.5, 1e-06)])\n", (10045, 10149), False, 'import pytest\n'), ((10196, 10241), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""usr_np"""', 'numpy_list'], {}), "('usr_np', numpy_list)\n", (10219, 10241), False, 'import pytest\n'), ((14672, 14782), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""mechname, fuel, stoich_ratio"""', "[('UConn32', 'C2H4', 3), ('sanDiego', 'H2', 0.5)]"], {}), "('mechname, fuel, stoich_ratio', [('UConn32', 'C2H4',\n 3), ('sanDiego', 'H2', 0.5)])\n", (14695, 14782), False, 'import pytest\n'), ((1394, 1432), 'jax.config.update', 'jax.config.update', (['"""jax_enable_x64"""', '(1)'], {}), "('jax_enable_x64', 1)\n", (1411, 1432), False, 'import jax\n'), ((3872, 3915), 'cantera.Solution', 'ct.Solution', (['f"""mechs/{mechname}.cti"""', '"""gas"""'], {}), "(f'mechs/{mechname}.cti', 'gas')\n", (3883, 3915), True, 'import cantera as ct\n'), ((4378, 4421), 'cantera.Solution', 'ct.Solution', (['f"""mechs/{mechname}.cti"""', '"""gas"""'], {}), "(f'mechs/{mechname}.cti', 'gas')\n", (4389, 4421), True, 'import cantera as ct\n'), ((4441, 4471), 'pyrometheus.get_thermochem_class', 'pyro.get_thermochem_class', (['sol'], {}), '(sol)\n', (4466, 4471), True, 'import pyrometheus as pyro\n'), ((4560, 4590), 'numpy.linspace', 'np.linspace', (['(500.0)', '(3000.0)', '(10)'], {}), '(500.0, 3000.0, 10)\n', (4571, 4590), True, 'import numpy as np\n'), ((5436, 5479), 'cantera.Solution', 'ct.Solution', (['f"""mechs/{mechname}.cti"""', '"""gas"""'], {}), "(f'mechs/{mechname}.cti', 'gas')\n", (5447, 5479), True, 'import cantera as ct\n'), ((5499, 5529), 'pyrometheus.get_thermochem_class', 'pyro.get_thermochem_class', (['sol'], {}), '(sol)\n', (5524, 5529), True, 'import pyrometheus as pyro\n'), ((5858, 5883), 'numpy.zeros', 'np.zeros', (['ptk.num_species'], {}), '(ptk.num_species)\n', (5866, 5883), True, 'import numpy as np\n'), ((6674, 6717), 'cantera.Solution', 'ct.Solution', (['f"""mechs/{mechname}.cti"""', '"""gas"""'], {}), "(f'mechs/{mechname}.cti', 'gas')\n", (6685, 6717), True, 'import cantera as ct\n'), ((6737, 6767), 'pyrometheus.get_thermochem_class', 'pyro.get_thermochem_class', (['sol'], {}), '(sol)\n', (6762, 6767), True, 'import pyrometheus as pyro\n'), ((6861, 6891), 'numpy.linspace', 'np.linspace', (['(500.0)', '(3000.0)', '(10)'], {}), '(500.0, 3000.0, 10)\n', (6872, 6891), True, 'import numpy as np\n'), ((8969, 9012), 'cantera.Solution', 'ct.Solution', (['f"""mechs/{mechname}.cti"""', '"""gas"""'], {}), "(f'mechs/{mechname}.cti', 'gas')\n", (8980, 9012), True, 'import cantera as ct\n'), ((9032, 9062), 'pyrometheus.get_thermochem_class', 'pyro.get_thermochem_class', (['sol'], {}), '(sol)\n', (9057, 9062), True, 'import pyrometheus as pyro\n'), ((9168, 9198), 'numpy.linspace', 'np.linspace', (['(500.0)', '(3000.0)', '(10)'], {}), '(500.0, 3000.0, 10)\n', (9179, 9198), True, 'import numpy as np\n'), ((9243, 9268), 'numpy.zeros', 'np.zeros', (['ptk.num_species'], {}), '(ptk.num_species)\n', (9251, 9268), True, 'import numpy as np\n'), ((10470, 10513), 'cantera.Solution', 'ct.Solution', (['f"""mechs/{mechname}.cti"""', '"""gas"""'], {}), "(f'mechs/{mechname}.cti', 'gas')\n", (10481, 10513), True, 'import cantera as ct\n'), ((10533, 10563), 'pyrometheus.get_thermochem_class', 'pyro.get_thermochem_class', (['sol'], {}), '(sol)\n', (10558, 10563), True, 'import pyrometheus as pyro\n'), ((10850, 10875), 'numpy.zeros', 'np.zeros', (['ptk.num_species'], {}), '(ptk.num_species)\n', (10858, 10875), True, 'import numpy as np\n'), ((11142, 11178), 'cantera.IdealGasConstPressureReactor', 'ct.IdealGasConstPressureReactor', (['sol'], {}), '(sol)\n', (11173, 11178), True, 'import cantera as ct\n'), ((11189, 11213), 'cantera.ReactorNet', 'ct.ReactorNet', (['[reactor]'], {}), '([reactor])\n', (11202, 11213), True, 'import cantera as ct\n'), ((12291, 12317), 'pytest.importorskip', 'pytest.importorskip', (['"""jax"""'], {}), "('jax')\n", (12310, 12317), False, 'import pytest\n'), ((12356, 12396), 'cantera.Solution', 'ct.Solution', (['"""mechs/sanDiego.cti"""', '"""gas"""'], {}), "('mechs/sanDiego.cti', 'gas')\n", (12367, 12396), True, 'import cantera as ct\n'), ((12416, 12446), 'pyrometheus.get_thermochem_class', 'pyro.get_thermochem_class', (['sol'], {}), '(sol)\n', (12441, 12446), True, 'import pyrometheus as pyro\n'), ((12732, 12757), 'numpy.zeros', 'np.zeros', (['ptk.num_species'], {}), '(ptk.num_species)\n', (12740, 12757), True, 'import numpy as np\n'), ((13203, 13215), 'jax.numpy.array', 'jnp.array', (['y'], {}), '(y)\n', (13212, 13215), True, 'import jax.numpy as jnp\n'), ((13576, 13604), 'jax.jacfwd', 'jacfwd', (['chemical_source_term'], {}), '(chemical_source_term)\n', (13582, 13604), False, 'from jax import jacfwd\n'), ((13993, 14024), 'numpy.array', 'np.array', (['[1e-05, 1e-06, 1e-07]'], {}), '([1e-05, 1e-06, 1e-07])\n', (14001, 14024), True, 'import numpy as np\n'), ((14115, 14128), 'pytools.convergence.EOCRecorder', 'EOCRecorder', ([], {}), '()\n', (14126, 14128), False, 'from pytools.convergence import EOCRecorder\n'), ((15020, 15063), 'cantera.Solution', 'ct.Solution', (['f"""mechs/{mechname}.cti"""', '"""gas"""'], {}), "(f'mechs/{mechname}.cti', 'gas')\n", (15031, 15063), True, 'import cantera as ct\n'), ((15337, 15362), 'numpy.zeros', 'np.zeros', (['ptk.num_species'], {}), '(ptk.num_species)\n', (15345, 15362), True, 'import numpy as np\n'), ((15629, 15665), 'cantera.IdealGasConstPressureReactor', 'ct.IdealGasConstPressureReactor', (['sol'], {}), '(sol)\n', (15660, 15665), True, 'import cantera as ct\n'), ((15676, 15700), 'cantera.ReactorNet', 'ct.ReactorNet', (['[reactor]'], {}), '([reactor])\n', (15689, 15700), True, 'import cantera as ct\n'), ((3988, 4017), 'pyrometheus.gen_thermochem_code', 'pyro.gen_thermochem_code', (['sol'], {}), '(sol)\n', (4012, 4017), True, 'import pyrometheus as pyro\n'), ((7124, 7173), 'numpy.linalg.norm', 'np.linalg.norm', (['(cp_pm - sol.standard_cp_R)', 'np.inf'], {}), '(cp_pm - sol.standard_cp_R, np.inf)\n', (7138, 7173), True, 'import numpy as np\n'), ((7350, 7405), 'numpy.linalg.norm', 'np.linalg.norm', (['(s_pm - sol.standard_entropies_R)', 'np.inf'], {}), '(s_pm - sol.standard_entropies_R, np.inf)\n', (7364, 7405), True, 'import numpy as np\n'), ((7587, 7644), 'numpy.linalg.norm', 'np.linalg.norm', (['(h_pm - sol.standard_enthalpies_RT)', 'np.inf'], {}), '(h_pm - sol.standard_enthalpies_RT, np.inf)\n', (7601, 7644), True, 'import numpy as np\n'), ((9770, 9794), 'numpy.ones', 'np.ones', (['ptk.num_species'], {}), '(ptk.num_species)\n', (9777, 9794), True, 'import numpy as np\n'), ((11540, 11577), 'numpy.where', 'np.where', (['(reactor.Y > 0)', 'reactor.Y', '(0)'], {}), '(reactor.Y > 0, reactor.Y, 0)\n', (11548, 11577), True, 'import numpy as np\n'), ((11784, 11819), 'numpy.linalg.norm', 'np.linalg.norm', (['(r_ct - r_pm)', 'np.inf'], {}), '(r_ct - r_pm, np.inf)\n', (11798, 11819), True, 'import numpy as np\n'), ((11838, 11881), 'numpy.linalg.norm', 'np.linalg.norm', (['(omega_ct - omega_pm)', 'np.inf'], {}), '(omega_ct - omega_pm, np.inf)\n', (11852, 11881), True, 'import numpy as np\n'), ((15074, 15104), 'pyrometheus.get_thermochem_class', 'pyro.get_thermochem_class', (['sol'], {}), '(sol)\n', (15099, 15104), True, 'import pyrometheus as pyro\n'), ((16140, 16177), 'numpy.where', 'np.where', (['(reactor.Y > 0)', 'reactor.Y', '(0)'], {}), '(reactor.Y > 0, reactor.Y, 0)\n', (16148, 16177), True, 'import numpy as np\n'), ((16370, 16447), 'numpy.linalg.norm', 'np.linalg.norm', (['((k_ct[i_falloff] - k_pm[i_falloff]) / k_ct[i_falloff])', 'np.inf'], {}), '((k_ct[i_falloff] - k_pm[i_falloff]) / k_ct[i_falloff], np.inf)\n', (16384, 16447), True, 'import numpy as np\n'), ((16886, 16902), 'pytest.main', 'main', (['[__file__]'], {}), '([__file__])\n', (16890, 16902), False, 'from pytest import main\n'), ((4965, 4993), 'numpy.abs', 'np.abs', (['((k_ct - k_pm) / k_ct)'], {}), '((k_ct - k_pm) / k_ct)\n', (4971, 4993), True, 'import numpy as np\n'), ((5006, 5050), 'numpy.linalg.norm', 'np.linalg.norm', (['((k_ct - k_pm) / k_ct)', 'np.inf'], {}), '((k_ct - k_pm) / k_ct, np.inf)\n', (5020, 5050), True, 'import numpy as np\n'), ((9996, 10012), 'numpy.abs', 'np.abs', (['(t - t_pm)'], {}), '(t - t_pm)\n', (10002, 10012), True, 'import numpy as np\n'), ((14279, 14310), 'numpy.linalg.norm', 'np.linalg.norm', (['(j - j_fd)', '"""fro"""'], {}), "(j - j_fd, 'fro')\n", (14293, 14310), True, 'import numpy as np\n'), ((14309, 14333), 'numpy.linalg.norm', 'np.linalg.norm', (['j', '"""fro"""'], {}), "(j, 'fro')\n", (14323, 14333), True, 'import numpy as np\n'), ((8270, 8313), 'numpy.abs', 'np.abs', (['((keq_pm[i] - keq_ct[i]) / keq_ct[i])'], {}), '((keq_pm[i] - keq_ct[i]) / keq_ct[i])\n', (8276, 8313), True, 'import numpy as np\n'), ((9534, 9550), 'numpy.abs', 'np.abs', (['(t - t_pm)'], {}), '(t - t_pm)\n', (9540, 9550), True, 'import numpy as np\n')] |
import scipy.io as sio
import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D
from tensorflow.keras.layers import MaxPooling2D
from tensorflow.keras.layers import Flatten
from tensorflow.keras.layers import Dense
from tensorflow.keras.layers import Dropout
class SVHNDataset():
def load_dataset(self, path_train, path_test):
"""
Loads the .mat file from the SVHN Dataset (train and test) indicated at location path. Returns it as numpy array,
"""
train_dataset = sio.loadmat(path_train)
test_dataset = sio.loadmat(path_test)
train_data, train_labels = train_dataset['X'], train_dataset['y']
test_data, test_labels = test_dataset['X'], test_dataset['y']
print( 'Train data:', train_data.shape,', Train labels:', train_labels.shape )
print( 'Test data:', test_data.shape,', Test labels:', test_labels.shape )
return train_data, train_labels, test_data, test_labels
def convert_to_gray(self, data):
"""
Converts all the images in the dataset into gray scale. Returns the dataset with grayscale entries.
"""
r, g, b = data[:,:,0,:], data[:,:,1,:], data[:,:,2,:]
gray = 0.2989 * r + 0.5870 * g + 0.1140 * b
data[:,:,0,:] = gray
data = data[:,:,0,:]
return data
def preprocess_for_KERAS_reshaping(self, framesize, dataset):
"""
Preprocessing for the dataset to be used in KERAS.
INPUT:
- dataset: numpy array with shape (framesize, framesize, #examples). Should be
after the grayscaling step!
- framesize: number that depicts the size of the frame, i.e. 32x32
OUTPUT:
- dataset that is still a numpy array. Shape is (#examples, framesize, framesize, 1)
"""
dataset = np.rollaxis(dataset,2)
dataset = dataset.reshape(-1, framesize, framesize, 1)
# print(f'Dataset reshaped to: {dataset.shape}')
return dataset
def preprocess_for_KERAS_labels(self, labels_dataset):
"""
Preprocessing for the labels of dataset to be used in KERAS. Converts 10 to 0, and reshapes.
INPUT:
- labels_dataset: numpy array with shape (#examples,1).
OUTPUT:
- labels_dataset that is still a numpy array. Shape is (#examples,). 10 is replaced with 0
"""
labels_dataset = labels_dataset[:,0]
labels_dataset[labels_dataset==10] = 0
return labels_dataset
def model_definition(self):
"""
Builds the model for the digit detection.
Taken from https://nbviewer.jupyter.org/github/dyckia/SVHN-CNN/blob/master/SVHN.ipynb.
"""
model = Sequential([
Conv2D(32, (3,3), activation='relu', input_shape=(32,32,1)),
Conv2D(32, (3,3), activation='relu'),
MaxPooling2D(2, 2),
Dropout(0.3),
Conv2D(64, (3,3), activation='relu'),
Conv2D(64, (3,3), activation='relu'),
MaxPooling2D(2, 2),
Dropout(0.3),
Flatten(),
Dense(512, activation='relu'),
Dropout(0.3),
Dense(10, activation='softmax')
])
# get a summary of our built model
return model
def load_model(self,path):
"""
Loads a pre-trained keras model at the path. Returns the model.
"""
import tensorflow as tf
import os
os.environ['KMP_DUPLICATE_LIB_OK']='True' # otherwise there will be an error
model = tf.keras.models.load_model(path)
return model | [
"tensorflow.keras.layers.Conv2D",
"tensorflow.keras.layers.MaxPooling2D",
"scipy.io.loadmat",
"numpy.rollaxis",
"tensorflow.keras.layers.Dropout",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.models.load_model",
"tensorflow.keras.layers.Flatten"
] | [((555, 578), 'scipy.io.loadmat', 'sio.loadmat', (['path_train'], {}), '(path_train)\n', (566, 578), True, 'import scipy.io as sio\n'), ((602, 624), 'scipy.io.loadmat', 'sio.loadmat', (['path_test'], {}), '(path_test)\n', (613, 624), True, 'import scipy.io as sio\n'), ((1888, 1911), 'numpy.rollaxis', 'np.rollaxis', (['dataset', '(2)'], {}), '(dataset, 2)\n', (1899, 1911), True, 'import numpy as np\n'), ((3634, 3666), 'tensorflow.keras.models.load_model', 'tf.keras.models.load_model', (['path'], {}), '(path)\n', (3660, 3666), True, 'import tensorflow as tf\n'), ((2814, 2876), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(32)', '(3, 3)'], {'activation': '"""relu"""', 'input_shape': '(32, 32, 1)'}), "(32, (3, 3), activation='relu', input_shape=(32, 32, 1))\n", (2820, 2876), False, 'from tensorflow.keras.layers import Conv2D\n'), ((2887, 2924), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(32)', '(3, 3)'], {'activation': '"""relu"""'}), "(32, (3, 3), activation='relu')\n", (2893, 2924), False, 'from tensorflow.keras.layers import Conv2D\n'), ((2937, 2955), 'tensorflow.keras.layers.MaxPooling2D', 'MaxPooling2D', (['(2)', '(2)'], {}), '(2, 2)\n', (2949, 2955), False, 'from tensorflow.keras.layers import MaxPooling2D\n'), ((2969, 2981), 'tensorflow.keras.layers.Dropout', 'Dropout', (['(0.3)'], {}), '(0.3)\n', (2976, 2981), False, 'from tensorflow.keras.layers import Dropout\n'), ((2995, 3032), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(64)', '(3, 3)'], {'activation': '"""relu"""'}), "(64, (3, 3), activation='relu')\n", (3001, 3032), False, 'from tensorflow.keras.layers import Conv2D\n'), ((3045, 3082), 'tensorflow.keras.layers.Conv2D', 'Conv2D', (['(64)', '(3, 3)'], {'activation': '"""relu"""'}), "(64, (3, 3), activation='relu')\n", (3051, 3082), False, 'from tensorflow.keras.layers import Conv2D\n'), ((3095, 3113), 'tensorflow.keras.layers.MaxPooling2D', 'MaxPooling2D', (['(2)', '(2)'], {}), '(2, 2)\n', (3107, 3113), False, 'from tensorflow.keras.layers import MaxPooling2D\n'), ((3127, 3139), 'tensorflow.keras.layers.Dropout', 'Dropout', (['(0.3)'], {}), '(0.3)\n', (3134, 3139), False, 'from tensorflow.keras.layers import Dropout\n'), ((3153, 3162), 'tensorflow.keras.layers.Flatten', 'Flatten', ([], {}), '()\n', (3160, 3162), False, 'from tensorflow.keras.layers import Flatten\n'), ((3176, 3205), 'tensorflow.keras.layers.Dense', 'Dense', (['(512)'], {'activation': '"""relu"""'}), "(512, activation='relu')\n", (3181, 3205), False, 'from tensorflow.keras.layers import Dense\n'), ((3219, 3231), 'tensorflow.keras.layers.Dropout', 'Dropout', (['(0.3)'], {}), '(0.3)\n', (3226, 3231), False, 'from tensorflow.keras.layers import Dropout\n'), ((3245, 3276), 'tensorflow.keras.layers.Dense', 'Dense', (['(10)'], {'activation': '"""softmax"""'}), "(10, activation='softmax')\n", (3250, 3276), False, 'from tensorflow.keras.layers import Dense\n')] |
import numpy as np
import sklearn.metrics as metrics
from scipy.sparse import csr_matrix
def evaluation_score(label_test, predict_label):
f1_micro=metrics.f1_score(label_test, predict_label, average='micro')
hamm=metrics.hamming_loss(label_test,predict_label)
accuracy = metrics.accuracy_score(label_test, predict_label)
precision = metrics.precision_score(label_test, predict_label,average='micro')
# f1=metrics.f1_score(label_test, predict_label)
recall=metrics.recall_score(label_test, predict_label,average='micro')
print('F1-score:',round(f1_micro,4))
print('Hamming Loss:',round(hamm,4))
print("accuracy :", round(accuracy, 4))
print("precision :", round(precision, 4))
# print("f1 :", round(f1, 4))
print("recall :", round(recall, 4))
return
def f1(y_true, y_pred):
correct_preds, total_correct, total_preds = 0., 0., 0.
for i in range(y_true.shape[0]):
set_true = set( np.where(y_true[i])[0])
set_pred = set( np.where(y_pred[i])[0] )
correct_preds += len(set_true & set_pred)
total_preds += len(set_pred)
total_correct += len(set_true)
p = correct_preds / total_preds if correct_preds > 0 else 0
r = correct_preds / total_correct if correct_preds > 0 else 0
f1 = 2 * p * r / (p + r) if correct_preds > 0 else 0
return p, r, f1
def hamming_score(y_true, y_pred, normalize=True, sample_weight=None):
'''
Compute the Hamming score (a.k.a. label-based accuracy) for the multi-label case
http://stackoverflow.com/q/32239577/395857
'''
acc_list = []
# y_true = np.array(y_true) # since y_true is numpy.matrix
# if not isinstance(y_pred, np.ndarray) or not isinstance(y_pred, np.matrix):
# y_pred = y_pred.toarray() # since y_pre is scipy.sparse.lil_matrix
for i in range(y_true.shape[0]):
#print(y_true[i])
#print(y_pred[i])
set_true = set( np.where(y_true[i])[0] )
set_pred = set( np.where(y_pred[i])[0] )
#print('\nset_true: {0}'.format(set_true))
#print('set_pred: {0}'.format(set_pred))
tmp_a = None
if len(set_true) == 0 and len(set_pred) == 0:
tmp_a = 1
else:
tmp_a = len(set_true.intersection(set_pred))/\
float( len(set_true.union(set_pred)) )
#print('tmp_a: {0}'.format(tmp_a))
acc_list.append(tmp_a)
return np.mean(acc_list)
if __name__ == "__main__":
y_true = np.array([[0,1,0],
[0,1,1],
[1,0,1],
[0,0,1]])
y_pred = np.array([[0,1,1],
[0,1,1],
[0,1,0],
[0,0,0]])
print('Hamming score: {0}'.format(hamming_score(y_true, y_pred))) # 0.375 (= (0.5+1+0+0)/4)
# Subset accuracy
# 0.25 (= 0+1+0+0 / 4) --> 1 if the prediction for one sample fully matches the gold. 0 otherwise.
print('Subset accuracy: {0}'.format(metrics.accuracy_score(y_true, y_pred, normalize=True, sample_weight=None)))
# Hamming loss (smaller is better)
# $$ \text{HammingLoss}(x_i, y_i) = \frac{1}{|D|} \sum_{i=1}^{|D|} \frac{xor(x_i, y_i)}{|L|}, $$
# where
# - \\(|D|\\) is the number of samples
# - \\(|L|\\) is the number of labels
# - \\(y_i\\) is the ground truth
# - \\(x_i\\) is the prediction.
# 0.416666666667 (= (1+0+3+1) / (3*4) )
print('Hamming loss: {0}'.format(metrics.hamming_loss(y_true, y_pred))) | [
"numpy.mean",
"sklearn.metrics.f1_score",
"numpy.where",
"sklearn.metrics.precision_score",
"sklearn.metrics.recall_score",
"numpy.array",
"sklearn.metrics.hamming_loss",
"sklearn.metrics.accuracy_score"
] | [((153, 213), 'sklearn.metrics.f1_score', 'metrics.f1_score', (['label_test', 'predict_label'], {'average': '"""micro"""'}), "(label_test, predict_label, average='micro')\n", (169, 213), True, 'import sklearn.metrics as metrics\n'), ((223, 270), 'sklearn.metrics.hamming_loss', 'metrics.hamming_loss', (['label_test', 'predict_label'], {}), '(label_test, predict_label)\n', (243, 270), True, 'import sklearn.metrics as metrics\n'), ((285, 334), 'sklearn.metrics.accuracy_score', 'metrics.accuracy_score', (['label_test', 'predict_label'], {}), '(label_test, predict_label)\n', (307, 334), True, 'import sklearn.metrics as metrics\n'), ((351, 418), 'sklearn.metrics.precision_score', 'metrics.precision_score', (['label_test', 'predict_label'], {'average': '"""micro"""'}), "(label_test, predict_label, average='micro')\n", (374, 418), True, 'import sklearn.metrics as metrics\n'), ((483, 547), 'sklearn.metrics.recall_score', 'metrics.recall_score', (['label_test', 'predict_label'], {'average': '"""micro"""'}), "(label_test, predict_label, average='micro')\n", (503, 547), True, 'import sklearn.metrics as metrics\n'), ((2444, 2461), 'numpy.mean', 'np.mean', (['acc_list'], {}), '(acc_list)\n', (2451, 2461), True, 'import numpy as np\n'), ((2506, 2560), 'numpy.array', 'np.array', (['[[0, 1, 0], [0, 1, 1], [1, 0, 1], [0, 0, 1]]'], {}), '([[0, 1, 0], [0, 1, 1], [1, 0, 1], [0, 0, 1]])\n', (2514, 2560), True, 'import numpy as np\n'), ((2624, 2678), 'numpy.array', 'np.array', (['[[0, 1, 1], [0, 1, 1], [0, 1, 0], [0, 0, 0]]'], {}), '([[0, 1, 1], [0, 1, 1], [0, 1, 0], [0, 0, 0]])\n', (2632, 2678), True, 'import numpy as np\n'), ((2995, 3069), 'sklearn.metrics.accuracy_score', 'metrics.accuracy_score', (['y_true', 'y_pred'], {'normalize': '(True)', 'sample_weight': 'None'}), '(y_true, y_pred, normalize=True, sample_weight=None)\n', (3017, 3069), True, 'import sklearn.metrics as metrics\n'), ((3479, 3515), 'sklearn.metrics.hamming_loss', 'metrics.hamming_loss', (['y_true', 'y_pred'], {}), '(y_true, y_pred)\n', (3499, 3515), True, 'import sklearn.metrics as metrics\n'), ((958, 977), 'numpy.where', 'np.where', (['y_true[i]'], {}), '(y_true[i])\n', (966, 977), True, 'import numpy as np\n'), ((1006, 1025), 'numpy.where', 'np.where', (['y_pred[i]'], {}), '(y_pred[i])\n', (1014, 1025), True, 'import numpy as np\n'), ((1956, 1975), 'numpy.where', 'np.where', (['y_true[i]'], {}), '(y_true[i])\n', (1964, 1975), True, 'import numpy as np\n'), ((2005, 2024), 'numpy.where', 'np.where', (['y_pred[i]'], {}), '(y_pred[i])\n', (2013, 2024), True, 'import numpy as np\n')] |
import numpy as np
from pyiid.experiments.elasticscatter.kernels.cpu_nxn import *
from ..kernels.cpu_flat import get_normalization_array as flat_norm
from pyiid.experiments.elasticscatter.atomics import pad_pdf
__author__ = 'christopher'
def wrap_fq(atoms, qbin=.1, sum_type='fq'):
"""
Generate the reduced structure function
Parameters
----------
atoms: ase.Atoms
The atomic configuration
qbin: float
The size of the scatter vector increment
sum_type: {'fq', 'pdf'}
Which scatter array should be used for the calculation
Returns
-------
fq:1darray
The reduced structure function
"""
q = atoms.get_positions().astype(np.float32)
# get scatter array
if sum_type == 'fq':
scatter_array = atoms.get_array('F(Q) scatter')
else:
scatter_array = atoms.get_array('PDF scatter')
# define scatter_q information and initialize constants
n, qmax_bin = scatter_array.shape
# Get pair coordinate distance array
d = np.zeros((n, n, 3), np.float32)
get_d_array(d, q)
# Get pair distance array
r = np.zeros((n, n), np.float32)
get_r_array(r, d)
# Get normalization array
norm = np.zeros((n, n, qmax_bin), np.float32)
get_normalization_array(norm, scatter_array)
# Get omega
omega = np.zeros((n, n, qmax_bin), np.float32)
get_omega(omega, r, qbin)
get_fq_inplace(omega, norm)
fq = omega
# Normalize fq
fq = np.sum(fq, axis=(0, 1), dtype=np.float64)
fq = fq.astype(np.float32)
# fq = np.sum(fq, axis=0, dtype=np.float32)
# fq = np.sum(fq, axis=0, dtype=np.float32)
norm2 = np.zeros((n * (n - 1) / 2., qmax_bin), np.float32)
flat_norm(norm2, scatter_array, 0)
na = np.mean(norm2, axis=0, dtype=np.float32) * np.float32(n)
# na = np.mean(norm2, axis=0, dtype=np.float64) * n
old_settings = np.seterr(all='ignore')
fq = np.nan_to_num(fq / na)
np.seterr(**old_settings)
del q, d, r, norm, omega, na
return fq
def wrap_fq_grad(atoms, qbin=.1, sum_type='fq'):
"""
Generate the reduced structure function gradient
Parameters
----------
atoms: ase.Atoms
The atomic configuration
qbin: float
The size of the scatter vector increment
sum_type: {'fq', 'pdf'}
Which scatter array should be used for the calculation
Returns
-------
dfq_dq:ndarray
The reduced structure function gradient
"""
q = atoms.get_positions().astype(np.float32)
qbin = np.float32(qbin)
# get scatter array
if sum_type == 'fq':
scatter_array = atoms.get_array('F(Q) scatter')
else:
scatter_array = atoms.get_array('PDF scatter')
# define scatter_q information and initialize constants
qmax_bin = scatter_array.shape[1]
n = len(q)
# Get pair coordinate distance array
d = np.zeros((n, n, 3), np.float32)
get_d_array(d, q)
# Get pair distance array
r = np.zeros((n, n), np.float32)
get_r_array(r, d)
# Get normalization array
norm = np.zeros((n, n, qmax_bin), np.float32)
get_normalization_array(norm, scatter_array)
# Get omega
omega = np.zeros((n, n, qmax_bin), np.float32)
get_omega(omega, r, qbin)
# Get grad omega
grad_omega = np.zeros((n, n, 3, qmax_bin), np.float32)
get_grad_omega(grad_omega, omega, r, d, qbin)
# Get grad FQ
get_grad_fq_inplace(grad_omega, norm)
grad_fq = grad_omega
# Normalize FQ
grad_fq = grad_fq.sum(1)
# '''
norm = np.zeros((n * (n - 1) / 2., qmax_bin), np.float32)
flat_norm(norm, scatter_array, 0)
na = np.mean(norm, axis=0) * np.float32(n)
old_settings = np.seterr(all='ignore')
grad_fq = np.nan_to_num(grad_fq / na)
np.seterr(**old_settings)
del d, r, scatter_array, norm, omega, grad_omega
return grad_fq
| [
"numpy.mean",
"numpy.sum",
"numpy.zeros",
"numpy.seterr",
"numpy.float32",
"numpy.nan_to_num"
] | [((1033, 1064), 'numpy.zeros', 'np.zeros', (['(n, n, 3)', 'np.float32'], {}), '((n, n, 3), np.float32)\n', (1041, 1064), True, 'import numpy as np\n'), ((1126, 1154), 'numpy.zeros', 'np.zeros', (['(n, n)', 'np.float32'], {}), '((n, n), np.float32)\n', (1134, 1154), True, 'import numpy as np\n'), ((1219, 1257), 'numpy.zeros', 'np.zeros', (['(n, n, qmax_bin)', 'np.float32'], {}), '((n, n, qmax_bin), np.float32)\n', (1227, 1257), True, 'import numpy as np\n'), ((1336, 1374), 'numpy.zeros', 'np.zeros', (['(n, n, qmax_bin)', 'np.float32'], {}), '((n, n, qmax_bin), np.float32)\n', (1344, 1374), True, 'import numpy as np\n'), ((1482, 1523), 'numpy.sum', 'np.sum', (['fq'], {'axis': '(0, 1)', 'dtype': 'np.float64'}), '(fq, axis=(0, 1), dtype=np.float64)\n', (1488, 1523), True, 'import numpy as np\n'), ((1663, 1714), 'numpy.zeros', 'np.zeros', (['(n * (n - 1) / 2.0, qmax_bin)', 'np.float32'], {}), '((n * (n - 1) / 2.0, qmax_bin), np.float32)\n', (1671, 1714), True, 'import numpy as np\n'), ((1894, 1917), 'numpy.seterr', 'np.seterr', ([], {'all': '"""ignore"""'}), "(all='ignore')\n", (1903, 1917), True, 'import numpy as np\n'), ((1927, 1949), 'numpy.nan_to_num', 'np.nan_to_num', (['(fq / na)'], {}), '(fq / na)\n', (1940, 1949), True, 'import numpy as np\n'), ((1954, 1979), 'numpy.seterr', 'np.seterr', ([], {}), '(**old_settings)\n', (1963, 1979), True, 'import numpy as np\n'), ((2541, 2557), 'numpy.float32', 'np.float32', (['qbin'], {}), '(qbin)\n', (2551, 2557), True, 'import numpy as np\n'), ((2892, 2923), 'numpy.zeros', 'np.zeros', (['(n, n, 3)', 'np.float32'], {}), '((n, n, 3), np.float32)\n', (2900, 2923), True, 'import numpy as np\n'), ((2985, 3013), 'numpy.zeros', 'np.zeros', (['(n, n)', 'np.float32'], {}), '((n, n), np.float32)\n', (2993, 3013), True, 'import numpy as np\n'), ((3078, 3116), 'numpy.zeros', 'np.zeros', (['(n, n, qmax_bin)', 'np.float32'], {}), '((n, n, qmax_bin), np.float32)\n', (3086, 3116), True, 'import numpy as np\n'), ((3195, 3233), 'numpy.zeros', 'np.zeros', (['(n, n, qmax_bin)', 'np.float32'], {}), '((n, n, qmax_bin), np.float32)\n', (3203, 3233), True, 'import numpy as np\n'), ((3303, 3344), 'numpy.zeros', 'np.zeros', (['(n, n, 3, qmax_bin)', 'np.float32'], {}), '((n, n, 3, qmax_bin), np.float32)\n', (3311, 3344), True, 'import numpy as np\n'), ((3551, 3602), 'numpy.zeros', 'np.zeros', (['(n * (n - 1) / 2.0, qmax_bin)', 'np.float32'], {}), '((n * (n - 1) / 2.0, qmax_bin), np.float32)\n', (3559, 3602), True, 'import numpy as np\n'), ((3706, 3729), 'numpy.seterr', 'np.seterr', ([], {'all': '"""ignore"""'}), "(all='ignore')\n", (3715, 3729), True, 'import numpy as np\n'), ((3744, 3771), 'numpy.nan_to_num', 'np.nan_to_num', (['(grad_fq / na)'], {}), '(grad_fq / na)\n', (3757, 3771), True, 'import numpy as np\n'), ((3776, 3801), 'numpy.seterr', 'np.seterr', ([], {}), '(**old_settings)\n', (3785, 3801), True, 'import numpy as np\n'), ((1762, 1802), 'numpy.mean', 'np.mean', (['norm2'], {'axis': '(0)', 'dtype': 'np.float32'}), '(norm2, axis=0, dtype=np.float32)\n', (1769, 1802), True, 'import numpy as np\n'), ((1805, 1818), 'numpy.float32', 'np.float32', (['n'], {}), '(n)\n', (1815, 1818), True, 'import numpy as np\n'), ((3649, 3670), 'numpy.mean', 'np.mean', (['norm'], {'axis': '(0)'}), '(norm, axis=0)\n', (3656, 3670), True, 'import numpy as np\n'), ((3673, 3686), 'numpy.float32', 'np.float32', (['n'], {}), '(n)\n', (3683, 3686), True, 'import numpy as np\n')] |
'''
Abstraction of machine learning model
Authors: <NAME>, <NAME>
'''
import os
import multiprocessing
import logging
import warnings
import itertools
import numpy as np
import scipy as sp
from sklearn.svm import SVC
from sklearn.naive_bayes import GaussianNB
from sklearn.linear_model import SGDClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.pipeline import Pipeline
from sklearn.feature_selection import chi2
from sklearn.base import TransformerMixin, BaseEstimator
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
from smapp_text_classifier.vectorizers import (CachedCountVectorizer,
CachedEmbeddingVectorizer)
class TextClassifier:
'''Abstraction that creates a sklearn pipeline and precomputes feature sets
Attributes:
----------
dataset: object of class DataSet
algorithm: str, one of ['random_forest', 'svm', 'elasticnet', 'naive_bayes',
'linear_svm']
feature_set: str, one of ['embeddings', 'char_ngrams', 'word_ngrams']
max_n_features: int, maximum number of features to retain from Chi2Reducer.
Not relevant for embeddings since embedding dimensionality is usually
much smaller than common bag-of-words feature set sizes.
embedding_model_name: str, name of a a pre-trained gensim embedding model.
(see here for https://github.com/RaRe-Technologies/gensim-data
available models). Self-trained models are currently not available
but will be coming soon.
cache_dir: str, directory to cache precomputed features
recompute_features: bool, should feature matrices be re-computed even if
they already exist in `cache_dir`? Note that, for character and word
embeddings vectorizing from scratch might be faster than loading the
cached matrices. This depends on the size of the dataset.
ngram_range: tuple(int, int), range of n_gram matrices to compute. The
pipeline will cross validate over all ranges from shortest to longest.
E.g. if `ngram_range=(1,3)` the following combinations of n-grams are
used as feature sets: 1) only 1-grams 2) 1 and 2-grams, 3) 1, 2 and
3-grams.
Methods:
----------
precompute_features: Creates all feature matrices and stores them in
`cache_dir`
'''
def __init__(self, dataset, algorithm, feature_set,
max_n_features=20000, embedding_model_name=None,
cache_dir='feature_cache/', recompute_features=False,
ngram_range=None, tokenize=None):
self.algorithm = algorithm
self.dataset = dataset
self.max_n_features = max_n_features
self.cache_dir = cache_dir
self.embedding_model_name = embedding_model_name
self.feature_set = feature_set
self.recompute_features = recompute_features
self.ngram_range = ngram_range
self.tokenize = tokenize
self.repr = f'{self.dataset.name}_{self.feature_set}_{self.algorithm}'
# If ngram range is not specified, set it to reasonable defaults
if self.ngram_range is None:
if self.feature_set == 'word_ngrams':
self.ngram_range = (1, 3)
if self.feature_set == 'char_ngrams':
self.ngram_range = (3, 5)
# Create the tuning parameters for the vectorizer (ngram ranges and
# pooling methods)
if 'ngrams' in feature_set:
ranges = [(self.ngram_range[0], x)
for x in range(self.ngram_range[0],
self.ngram_range[1]+1)]
self.params = {
'vectorize__ngram_range': ranges,
}
elif feature_set == 'embeddings':
self.params = {
'vectorize__pooling_method': ['mean', 'max']
}
else:
raise ValueError("feature_set must be one of ['embeddings', "
"'word_ngrams', 'char_ngrams']")
# Create the classifiers and set their tuning parameters
if self.algorithm == 'random_forest':
self.classifier = RandomForestClassifier(max_features='auto')
self.params.update(
{'clf__n_estimators': sp.stats.randint(10, 500),
'clf__min_samples_split': sp.stats.uniform(0.0001, 0.1)}
)
elif self.algorithm == 'elasticnet':
self.classifier = SGDClassifier(loss='log', penalty='elasticnet')
self.params.update({'clf__alpha': sp.stats.uniform(0.00001, 0.01),
'clf__l1_ratio': sp.stats.uniform(0, 1)})
elif self.algorithm == 'linear_svm':
self.classifier = SGDClassifier(loss='hinge', penalty='elasticnet')
self.params.update({'clf__alpha': sp.stats.uniform(0.00001, 0.01),
'clf__l1_ratio': sp.stats.uniform(0, 1)})
elif self.algorithm == 'naive_bayes':
self.classifier = GaussianNB()
self.params.update({'clf__var_smoothing': sp.stats.uniform(1e-12,
1e-6)})
elif self.algorithm == "svm":
self.classifier = SVC()
self.params.update({'clf__gamma': sp.stats.uniform(1e-3, 1e3),
'clf__C': sp.stats.uniform(1e-2, 1e2),
'clf__kernel': ['linear', 'rbf'],
'clf__tol': sp.stats.uniform(1e-1, 1e-5)})
else:
raise ValueError("`algorithm` must be one of ['naive_bayes', 'elast"
"icnet', 'random_forest', 'svm', 'linear_svm']")
# Precompute features
# Before cross-validation each vectorizer has to be fit once to
# precompute features on the complete dataset (the data that is passed
# to the vectorizer during cross-validation is always missing one fold,
# therefore, an incomplete cache would be created of the data if caching
# was based on the first time a vectorizer is used in the
# cross-validation)
# Initialize the vectorizer depending on the requested feature type
if feature_set == 'embeddings':
vectorizer = CachedEmbeddingVectorizer(
cache_dir=self.cache_dir,
ds_name=dataset.name,
embedding_model_name=self.embedding_model_name,
tokenizer=self.tokenize,
recompute=self.recompute_features,
)
else:
analyzer = 'word' if feature_set == 'word_ngrams' else 'char_wb'
vectorizer = CachedCountVectorizer(
cache_dir=self.cache_dir,
ds_name=dataset.name,
analyzer=analyzer,
recompute=self.recompute_features,
tokenizer=self.tokenize,
max_features=self.max_n_features
)
prefix = 'vectorize__'
vec_params = {k: v for k, v in self.params.items()
if k.startswith(prefix)}
init_params = vectorizer.get_params()
for value_combo in itertools.product(*vec_params.values()):
par = {key[len(prefix):]: value_combo[i]
for i, key in enumerate(vec_params)}
vectorizer = vectorizer.set_params(**par)
if not os.path.exists(vectorizer.cache) or self.recompute_features:
logging.debug(f'Pre-computing {vectorizer.cache}')
vectorizer = vectorizer.fit(self.dataset.df.text)
vectorizer = vectorizer.set_params(**init_params)
#recompute=self.recompute_features, **{key: None for key in par}
#)
# Assemble Pipeline
if feature_set == 'embeddings':
self.pipeline = Pipeline([
('vectorize', vectorizer),
('clf', self.classifier)])
else:
self.pipeline = Pipeline([
('vectorize', vectorizer),
#('reduce', Chi2Reducer(max_n_features=self.max_n_features)),
('clf', self.classifier)])
def __str__(self):
'''Return a string uniquely identify the combination of dataset, and
feature set'''
return self.repr
class Chi2Reducer(TransformerMixin, BaseEstimator):
'''Estimator that reduces the number of features by
selecting the top predictive features according to
chi^2 statistic (see sklearn.feature_selection.chi2)
Attributes:
----------
max_n_features: Maximum numbers of features to return.
top_idxs: Vocabulary indices in order of chi2 importance.
self.p_values: P-values of chi2 test for each feature in the
order of the occurence in X (columns).
'''
def __init__(self, max_n_features):
self.max_n_features = int(max_n_features)
self.top_idxs = None
self.p_values = None
def fit(self, X, y):
'''Calculates chi2 statistics for all features in X'''
# Warnings are suppressed here because some features have zero occurence
# due to the train test split (the feature matrix is generated for the
# complete dataset, but the precompute vectorizer only returns rows for
# documents in the training/test set). These features are taken care of
# explicitly later
with warnings.catch_warnings():
warnings.simplefilter("ignore")
c2 = chi2(X, y)
# Set p-value of nan feature to 1 and chi2 statistic to 0
new_pval = [1.0 if np.isnan(x) else x for x in c2[1]]
sorted_features = sorted([(pval, idx) for idx, pval
in enumerate(new_pval)],
key=lambda x: x[0],
reverse=False)
self.p_values = [x[0] for x in sorted(sorted_features,
key=lambda x: x[1])]
top_features = sorted_features[:self.max_n_features]
self.top_idxs = list(map(lambda x: x[1], top_features))
return self
def transform(self, X, y=None):
'''Returns the top self.max_n_features from X'''
return X.tocsr()[:, self.top_idxs]
def fit_transform(self, X, y):
self.fit(X, y)
return self.transform(X)
class DictionaryModel:
'''
A high level wrapper around vaderSentiment packageself.
tokenizer: function that tokenizes string
model: specifies which dictionary model is applied. Only 'vader' is
supported in this version.
labels: list of three label values for positive, negative, neutral
(in that order)
Method:
---
predict: return a list of predicted sentiment for each tweet in X.
'''
def __init__(self, tokenizer, model='vader', n_jobs=-1,
labels=['positive', 'negative', 'neutral']):
self.tokenizer = tokenizer
self.labels = labels
if model == 'vader':
self.analyzer = SentimentIntensityAnalyzer()
else:
raise ValueError('Invalid dictionary method model.')
self.n_jobs = n_jobs if n_jobs > 0 else multiprocessing.cpu_count()
def score_document(self, document):
'''Score a single document'''
vs = self.analyzer.polarity_scores(document.lower())
if vs['compound'] > 0:
return self.labels[0]
elif vs['compound'] < 0:
return self.labels[1]
else:
return self.labels[2]
def predict(self, X):
'''Score a collection of documents in parallel'''
vader_sentiments = []
with multiprocessing.Pool(self.n_jobs) as pool:
vader_sentiments = pool.map(self.score_document, X)
return vader_sentiments
| [
"scipy.stats.randint",
"vaderSentiment.vaderSentiment.SentimentIntensityAnalyzer",
"smapp_text_classifier.vectorizers.CachedCountVectorizer",
"sklearn.linear_model.SGDClassifier",
"smapp_text_classifier.vectorizers.CachedEmbeddingVectorizer",
"sklearn.feature_selection.chi2",
"logging.debug",
"os.path... | [((4198, 4241), 'sklearn.ensemble.RandomForestClassifier', 'RandomForestClassifier', ([], {'max_features': '"""auto"""'}), "(max_features='auto')\n", (4220, 4241), False, 'from sklearn.ensemble import RandomForestClassifier\n'), ((6341, 6530), 'smapp_text_classifier.vectorizers.CachedEmbeddingVectorizer', 'CachedEmbeddingVectorizer', ([], {'cache_dir': 'self.cache_dir', 'ds_name': 'dataset.name', 'embedding_model_name': 'self.embedding_model_name', 'tokenizer': 'self.tokenize', 'recompute': 'self.recompute_features'}), '(cache_dir=self.cache_dir, ds_name=dataset.name,\n embedding_model_name=self.embedding_model_name, tokenizer=self.tokenize,\n recompute=self.recompute_features)\n', (6366, 6530), False, 'from smapp_text_classifier.vectorizers import CachedCountVectorizer, CachedEmbeddingVectorizer\n'), ((6734, 6925), 'smapp_text_classifier.vectorizers.CachedCountVectorizer', 'CachedCountVectorizer', ([], {'cache_dir': 'self.cache_dir', 'ds_name': 'dataset.name', 'analyzer': 'analyzer', 'recompute': 'self.recompute_features', 'tokenizer': 'self.tokenize', 'max_features': 'self.max_n_features'}), '(cache_dir=self.cache_dir, ds_name=dataset.name,\n analyzer=analyzer, recompute=self.recompute_features, tokenizer=self.\n tokenize, max_features=self.max_n_features)\n', (6755, 6925), False, 'from smapp_text_classifier.vectorizers import CachedCountVectorizer, CachedEmbeddingVectorizer\n'), ((7907, 7970), 'sklearn.pipeline.Pipeline', 'Pipeline', (["[('vectorize', vectorizer), ('clf', self.classifier)]"], {}), "([('vectorize', vectorizer), ('clf', self.classifier)])\n", (7915, 7970), False, 'from sklearn.pipeline import Pipeline\n'), ((8046, 8109), 'sklearn.pipeline.Pipeline', 'Pipeline', (["[('vectorize', vectorizer), ('clf', self.classifier)]"], {}), "([('vectorize', vectorizer), ('clf', self.classifier)])\n", (8054, 8109), False, 'from sklearn.pipeline import Pipeline\n'), ((9464, 9489), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {}), '()\n', (9487, 9489), False, 'import warnings\n'), ((9503, 9534), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""'], {}), "('ignore')\n", (9524, 9534), False, 'import warnings\n'), ((9552, 9562), 'sklearn.feature_selection.chi2', 'chi2', (['X', 'y'], {}), '(X, y)\n', (9556, 9562), False, 'from sklearn.feature_selection import chi2\n'), ((11103, 11131), 'vaderSentiment.vaderSentiment.SentimentIntensityAnalyzer', 'SentimentIntensityAnalyzer', ([], {}), '()\n', (11129, 11131), False, 'from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer\n'), ((11259, 11286), 'multiprocessing.cpu_count', 'multiprocessing.cpu_count', ([], {}), '()\n', (11284, 11286), False, 'import multiprocessing\n'), ((11735, 11768), 'multiprocessing.Pool', 'multiprocessing.Pool', (['self.n_jobs'], {}), '(self.n_jobs)\n', (11755, 11768), False, 'import multiprocessing\n'), ((4502, 4549), 'sklearn.linear_model.SGDClassifier', 'SGDClassifier', ([], {'loss': '"""log"""', 'penalty': '"""elasticnet"""'}), "(loss='log', penalty='elasticnet')\n", (4515, 4549), False, 'from sklearn.linear_model import SGDClassifier\n'), ((7547, 7597), 'logging.debug', 'logging.debug', (['f"""Pre-computing {vectorizer.cache}"""'], {}), "(f'Pre-computing {vectorizer.cache}')\n", (7560, 7597), False, 'import logging\n'), ((9657, 9668), 'numpy.isnan', 'np.isnan', (['x'], {}), '(x)\n', (9665, 9668), True, 'import numpy as np\n'), ((4312, 4337), 'scipy.stats.randint', 'sp.stats.randint', (['(10)', '(500)'], {}), '(10, 500)\n', (4328, 4337), True, 'import scipy as sp\n'), ((4382, 4411), 'scipy.stats.uniform', 'sp.stats.uniform', (['(0.0001)', '(0.1)'], {}), '(0.0001, 0.1)\n', (4398, 4411), True, 'import scipy as sp\n'), ((4778, 4827), 'sklearn.linear_model.SGDClassifier', 'SGDClassifier', ([], {'loss': '"""hinge"""', 'penalty': '"""elasticnet"""'}), "(loss='hinge', penalty='elasticnet')\n", (4791, 4827), False, 'from sklearn.linear_model import SGDClassifier\n'), ((7470, 7502), 'os.path.exists', 'os.path.exists', (['vectorizer.cache'], {}), '(vectorizer.cache)\n', (7484, 7502), False, 'import os\n'), ((4596, 4625), 'scipy.stats.uniform', 'sp.stats.uniform', (['(1e-05)', '(0.01)'], {}), '(1e-05, 0.01)\n', (4612, 4625), True, 'import scipy as sp\n'), ((4678, 4700), 'scipy.stats.uniform', 'sp.stats.uniform', (['(0)', '(1)'], {}), '(0, 1)\n', (4694, 4700), True, 'import scipy as sp\n'), ((5057, 5069), 'sklearn.naive_bayes.GaussianNB', 'GaussianNB', ([], {}), '()\n', (5067, 5069), False, 'from sklearn.naive_bayes import GaussianNB\n'), ((4874, 4903), 'scipy.stats.uniform', 'sp.stats.uniform', (['(1e-05)', '(0.01)'], {}), '(1e-05, 0.01)\n', (4890, 4903), True, 'import scipy as sp\n'), ((4956, 4978), 'scipy.stats.uniform', 'sp.stats.uniform', (['(0)', '(1)'], {}), '(0, 1)\n', (4972, 4978), True, 'import scipy as sp\n'), ((5295, 5300), 'sklearn.svm.SVC', 'SVC', ([], {}), '()\n', (5298, 5300), False, 'from sklearn.svm import SVC\n'), ((5124, 5154), 'scipy.stats.uniform', 'sp.stats.uniform', (['(1e-12)', '(1e-06)'], {}), '(1e-12, 1e-06)\n', (5140, 5154), True, 'import scipy as sp\n'), ((5347, 5378), 'scipy.stats.uniform', 'sp.stats.uniform', (['(0.001)', '(1000.0)'], {}), '(0.001, 1000.0)\n', (5363, 5378), True, 'import scipy as sp\n'), ((5418, 5447), 'scipy.stats.uniform', 'sp.stats.uniform', (['(0.01)', '(100.0)'], {}), '(0.01, 100.0)\n', (5434, 5447), True, 'import scipy as sp\n'), ((5557, 5585), 'scipy.stats.uniform', 'sp.stats.uniform', (['(0.1)', '(1e-05)'], {}), '(0.1, 1e-05)\n', (5573, 5585), True, 'import scipy as sp\n')] |
#encoding:utf-8
import cv2, numpy, sys, pickle
from detector import Detector
AREA_MIN = 1000
AREA_MAX = 10000
AZUL_MIN = numpy.array([100, 150, 110], numpy.uint8)
AZUL_MAX = numpy.array([130, 255, 255], numpy.uint8)
BLANCO_MIN = cv2.mean((200, 200, 200))
BLANCO_MAX = cv2.mean((255, 255, 255))
class Calibrador():
def __init__(self, camara):
self.detector = Detector(camara, True, False, AREA_MIN, AREA_MAX, BLANCO_MIN, BLANCO_MAX, AZUL_MIN, AZUL_MAX)
def calibrar(self, tipo):
if (tipo == "franjas"):
self.franjas = open("franjas.obj", "wb")
self.detector.detectarFranjas()
elif (tipo == "zapato"):
self.yMin = open("limite.txt", "w")
self.detector.detectarZapatos()
else:
print("No se reconoce el parámetro: '%s'" % tipo)
sys.exit(0)
def guardar(self, tipo):
if (tipo == "franjas"):
pickle.dump(self.detector.getFranjas(), self.franjas)
self.franjas.close()
elif (tipo == "zapato"):
self.yMin.write("%d" % self.detector.getZapatos()[0].getYMin())
self.yMin.close()
if __name__ == "__main__":
if (len(sys.argv) > 2):
calibrador = Calibrador(int(sys.argv[2]))
else:
calibrador = Calibrador(0)
while True:
calibrador.calibrar(sys.argv[1])
if (cv2.waitKey(27) != -1):
calibrador.guardar(sys.argv[1])
break
| [
"detector.Detector",
"numpy.array",
"sys.exit",
"cv2.waitKey",
"cv2.mean"
] | [((128, 169), 'numpy.array', 'numpy.array', (['[100, 150, 110]', 'numpy.uint8'], {}), '([100, 150, 110], numpy.uint8)\n', (139, 169), False, 'import cv2, numpy, sys, pickle\n'), ((182, 223), 'numpy.array', 'numpy.array', (['[130, 255, 255]', 'numpy.uint8'], {}), '([130, 255, 255], numpy.uint8)\n', (193, 223), False, 'import cv2, numpy, sys, pickle\n'), ((238, 263), 'cv2.mean', 'cv2.mean', (['(200, 200, 200)'], {}), '((200, 200, 200))\n', (246, 263), False, 'import cv2, numpy, sys, pickle\n'), ((278, 303), 'cv2.mean', 'cv2.mean', (['(255, 255, 255)'], {}), '((255, 255, 255))\n', (286, 303), False, 'import cv2, numpy, sys, pickle\n'), ((401, 498), 'detector.Detector', 'Detector', (['camara', '(True)', '(False)', 'AREA_MIN', 'AREA_MAX', 'BLANCO_MIN', 'BLANCO_MAX', 'AZUL_MIN', 'AZUL_MAX'], {}), '(camara, True, False, AREA_MIN, AREA_MAX, BLANCO_MIN, BLANCO_MAX,\n AZUL_MIN, AZUL_MAX)\n', (409, 498), False, 'from detector import Detector\n'), ((1505, 1520), 'cv2.waitKey', 'cv2.waitKey', (['(27)'], {}), '(27)\n', (1516, 1520), False, 'import cv2, numpy, sys, pickle\n'), ((911, 922), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (919, 922), False, 'import cv2, numpy, sys, pickle\n')] |
import numpy as np
from PIL import Image
from scipy.ndimage.morphology import binary_erosion
from improc3d import quantile_scale, calc_bbox3d
from .utils import MIN_UINT8, MAX_UINT8
from .utils import assign_colors, compose_image_and_labels
class ImageRenderer:
"""Renders slices from a 3D image using PIL.
Note:
The 3rd dimension is used as the slice dimension. Use `improc3d
<https://github.com/shuohan/improc3d>`_ to reslice the image.
>>> from improc3d import transform_to_sagittal
>>> sagittal = transform_to_sagittal(image, lpim_affine)
>>> renderer = ImageRenderer(sagittal)
>>> print('Number of slices', len(renderer))
>>> sag_slice = renderer[100]
Attributes:
image (numpy.ndarray): The image to render.
"""
def __init__(self, image):
self.image = image
self._rescaled = image
self.rescale_intensity()
def automatic_rescale(self):
"""Rescales the image automatically. Works fine for T1w brain images."""
self._rescaled = quantile_scale(self.image, lower_th=MIN_UINT8,
upper_th=MAX_UINT8)
self._rescaled = self._rescaled.astype(np.uint8)
@property
def slice_size(self):
"""Returns the width and height of image slices."""
width = self.image.shape[1]
height = self.image.shape[0]
return width, height
@property
def intensity_range(self):
"""Returns the value range of the image intensities ``[vmin, vmax]``."""
vmin = np.min(self.image)
vmax = np.max(self.image)
return vmin, vmax
def rescale_intensity(self, vmin=None, vmax=None):
"""Rescales image intensity into ``[vmin, vmax]``.
Args:
vmin (float): Any values below ``vmin`` are set to 0.
vmax (float): Any values above ``vmax`` are set to 255.
"""
int_range = self.intensity_range
vmin = int_range[0] if vmin is None else vmin
vmax = int_range[1] if vmax is None else vmax
self._rescaled = self.image.copy()
self._rescaled[self._rescaled < vmin] = vmin
self._rescaled[self._rescaled > vmax] = vmax
self._rescaled = (self._rescaled - vmin) / (vmax - vmin)
self._rescaled = self._rescaled * (MAX_UINT8 - MIN_UINT8) + MIN_UINT8
self._rescaled = self._rescaled.astype(np.uint8)
def __len__(self):
return self.image.shape[-1]
def __getitem__(self, ind):
ind = self._check_slice_ind(ind)
image_slice = self._rescaled[:, :, ind]
image_slice = Image.fromarray(image_slice, 'L')
image_slice = image_slice.transpose(Image.TRANSPOSE)
return image_slice
def _check_slice_ind(self, ind):
if ind < 0:
ind = 0
print('Slice index should not be less than {}.'.format(ind))
if ind > len(self) - 1:
ind = len(self) - 1
print('Slice index should not be greater than {}.'.format(ind))
return ind
class ImagePairRenderer(ImageRenderer):
"""Renders image and its corresponding label image as an alpha-composite.
Note:
The attribute :attr:`label_image` will be converted into a "colored"
image by assigning :attr:`colors` to its label values. As the input,
it should have the same shape with :attr:`image`; after conversion, it
will have a 4th dimension as the colors.
Attributes:
label_image (numpy.ndarray): The corresponding label image. It should
have the same spatial shape with :attr:`image`.
colors (numpy.ndarray): The num_colors x 4 RGBA colors array.
alpha (float): The alpha value of the label image.
"""
def __init__(self, image, label_image, colors, alpha=1.0):
assert image.shape == label_image.shape
super().__init__(image)
self._alpha = alpha
self.colors = colors
self.label_image = label_image
self._assign_colors()
@property
def alpha(self):
return self._alpha
@alpha.setter
def alpha(self, value):
self._alpha = value
self._assign_colors()
def _assign_colors(self):
self._colored_label_image = assign_colors(self.label_image, self.colors)
def __getitem__(self, ind):
ind = self._check_slice_ind(ind)
image_slice = self._rescaled[:, :, ind]
label_slice = self._colored_label_image[:, :, ind, :]
comp = compose_image_and_labels(image_slice, label_slice, self.alpha)
comp = comp.transpose(Image.TRANSPOSE)
return comp
def get_label_range(self):
"""Returns the index range of slices with non-background labels."""
bbox = calc_bbox3d(self.label_image > 0)
slice_range = bbox[-1]
return slice_range.start, slice_range.stop
class ImageEdgeRenderer(ImagePairRenderer):
"""Renders an image and the outside contours (edge) of each labeled region.
Attributes:
edge_width (int): The width of the edge as the number of pixels.
"""
def __init__(self, image, label_image, colors, alpha=1, edge_width=1):
self._edge_width = edge_width
super().__init__(image, label_image, colors, alpha)
@property
def edge_width(self):
return self._edge_width
@edge_width.setter
def edge_width(self, width):
self._edge_width = width
self._assign_colors()
def _assign_colors(self):
"""Only assigns the colors to the outside contours (edges)."""
label_image = self.label_image.copy()
for label in np.unique(label_image):
mask = label_image == label
erosion = binary_erosion(mask, iterations=self.edge_width)
label_image[erosion] = 0
self._colored_label_image = assign_colors(label_image, self.colors)
class CheckerboardRenderer(ImageRenderer):
def __init__(self, image1, image2, patch_size=20, alpha=0):
self._renderer1 = ImageRenderer(image1)
self._renderer2 = ImageRenderer(image2)
assert self._renderer1.slice_size == self._renderer2.slice_size
self.patch_size = patch_size
self.alpha = alpha
def automatic_rescale(self):
self._renderer1.automatic_rescale()
self._renderer2.automatic_rescale()
@property
def slice_size(self):
return self._renderer1.slice_size
@property
def intensity_range(self):
vmin1, vmax1 = self._renderer1.intensity_range
vmin2, vmax2 = self._renderer2.intensity_range
return vmin1, vmax1, vmin2, vmax2
def rescale_intensity(self, vmin1=None, vmax1=None, vmin2=None, vmax2=None):
self._renderer1.rescale_intensity(vmin1, vmax1)
self._renderer2.rescale_intensity(vmin2, vmax2)
def __len__(self):
return len(self._renderer1)
def __getitem__(self, ind):
image_slice1 = self._renderer1[ind]
image_slice2 = self._renderer2[ind]
image_slice = self._compose(image_slice1, image_slice2)
return image_slice
def _check_slice_ind(self, ind):
assert False
def _compose(self, image_slice1, image_slice2):
array1 = np.array(image_slice1.convert('RGBA'), dtype=np.uint8)
array2 = np.array(image_slice2.convert('RGBA'), dtype=np.uint8)
height, width = array1.shape[:2]
left = 0
top = 0
alpha_upper = self.alpha
alpha = self.alpha
while top < height:
hstart = top
hend = hstart + self.patch_size
while left < width:
wstart = left
wend = left + self.patch_size
array1[hstart:hend, wstart:wend, 3] = \
array1[hstart:hend, wstart:wend, 3] * (1 - alpha)
array2[hstart:hend, wstart:wend, 3] = \
array2[hstart:hend, wstart:wend, 3] * alpha
left = wend
alpha = 1 - alpha
top = hend
left = 0
alpha = 1 - alpha_upper
alpha_upper = alpha
image1 = Image.fromarray(array1)
image2 = Image.fromarray(array2)
composition = Image.alpha_composite(image1, image2)
return composition
class AlphaRenderer(ImageRenderer):
def __init__(self, image1, image2, alpha=0):
self._renderer1 = ImageRenderer(image1)
self._renderer2 = ImageRenderer(image2)
assert self._renderer1.slice_size == self._renderer2.slice_size
self.alpha = alpha
def automatic_rescale(self):
self._renderer1.automatic_rescale()
self._renderer2.automatic_rescale()
@property
def slice_size(self):
return self._renderer1.slice_size
@property
def intensity_range(self):
vmin1, vmax1 = self._renderer1.intensity_range
vmin2, vmax2 = self._renderer2.intensity_range
return vmin1, vmax1, vmin2, vmax2
def rescale_intensity(self, vmin1=None, vmax1=None, vmin2=None, vmax2=None):
self._renderer1.rescale_intensity(vmin1, vmax1)
self._renderer2.rescale_intensity(vmin2, vmax2)
def __len__(self):
return len(self._renderer1)
def __getitem__(self, ind):
image_slice1 = self._renderer1[ind]
image_slice2 = self._renderer2[ind]
image_slice = self._compose(image_slice1, image_slice2)
return image_slice
def _check_slice_ind(self, ind):
assert False
def _compose(self, image_slice1, image_slice2):
array1 = np.array(image_slice1.convert('RGBA'), dtype=np.uint8)
array2 = np.array(image_slice2.convert('RGBA'), dtype=np.uint8)
array2[..., 3] = array2[..., 3] * self.alpha
image1 = Image.fromarray(array1)
image2 = Image.fromarray(array2)
composition = Image.alpha_composite(image1, image2)
return composition
| [
"PIL.Image.fromarray",
"numpy.unique",
"improc3d.quantile_scale",
"numpy.max",
"PIL.Image.alpha_composite",
"numpy.min",
"scipy.ndimage.morphology.binary_erosion",
"improc3d.calc_bbox3d"
] | [((1066, 1132), 'improc3d.quantile_scale', 'quantile_scale', (['self.image'], {'lower_th': 'MIN_UINT8', 'upper_th': 'MAX_UINT8'}), '(self.image, lower_th=MIN_UINT8, upper_th=MAX_UINT8)\n', (1080, 1132), False, 'from improc3d import quantile_scale, calc_bbox3d\n'), ((1575, 1593), 'numpy.min', 'np.min', (['self.image'], {}), '(self.image)\n', (1581, 1593), True, 'import numpy as np\n'), ((1609, 1627), 'numpy.max', 'np.max', (['self.image'], {}), '(self.image)\n', (1615, 1627), True, 'import numpy as np\n'), ((2634, 2667), 'PIL.Image.fromarray', 'Image.fromarray', (['image_slice', '"""L"""'], {}), "(image_slice, 'L')\n", (2649, 2667), False, 'from PIL import Image\n'), ((4773, 4806), 'improc3d.calc_bbox3d', 'calc_bbox3d', (['(self.label_image > 0)'], {}), '(self.label_image > 0)\n', (4784, 4806), False, 'from improc3d import quantile_scale, calc_bbox3d\n'), ((5649, 5671), 'numpy.unique', 'np.unique', (['label_image'], {}), '(label_image)\n', (5658, 5671), True, 'import numpy as np\n'), ((8140, 8163), 'PIL.Image.fromarray', 'Image.fromarray', (['array1'], {}), '(array1)\n', (8155, 8163), False, 'from PIL import Image\n'), ((8181, 8204), 'PIL.Image.fromarray', 'Image.fromarray', (['array2'], {}), '(array2)\n', (8196, 8204), False, 'from PIL import Image\n'), ((8227, 8264), 'PIL.Image.alpha_composite', 'Image.alpha_composite', (['image1', 'image2'], {}), '(image1, image2)\n', (8248, 8264), False, 'from PIL import Image\n'), ((9769, 9792), 'PIL.Image.fromarray', 'Image.fromarray', (['array1'], {}), '(array1)\n', (9784, 9792), False, 'from PIL import Image\n'), ((9810, 9833), 'PIL.Image.fromarray', 'Image.fromarray', (['array2'], {}), '(array2)\n', (9825, 9833), False, 'from PIL import Image\n'), ((9856, 9893), 'PIL.Image.alpha_composite', 'Image.alpha_composite', (['image1', 'image2'], {}), '(image1, image2)\n', (9877, 9893), False, 'from PIL import Image\n'), ((5735, 5783), 'scipy.ndimage.morphology.binary_erosion', 'binary_erosion', (['mask'], {'iterations': 'self.edge_width'}), '(mask, iterations=self.edge_width)\n', (5749, 5783), False, 'from scipy.ndimage.morphology import binary_erosion\n')] |
# Copyright (c) 2019 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Classes for accessing arrays and data in the underlying :class:`netCDF4.Dataset`.
"""
#__all__ = ["get_values_from_array", "DatasetVariables", "StringArray", "Variable"]
import numpy as np
def filled_if_masked(array):
if type(array) is np.ma.MaskedArray: return array.filled()
return array
def is_integer(val):
return np.issubdtype(type(val), np.integer)
def get_slice_tuple(dimensions, indices=None):
if indices is None: return tuple([slice(None) for x in dimensions])
if "M" in indices and "I" in dimensions:
indices["I"] = 0 if is_integer(indices["M"]) else slice(None)
return tuple([slice(None) if x not in indices else indices[x] for x in dimensions])
def get_default_dimension_order(dimensions, indices=None):
if indices is None: return dimensions
if "M" in indices and "I" in dimensions:
indices["I"] = 0 if is_integer(indices["M"]) else slice(None)
dim_order = tuple([x for x in dimensions if x not in indices or not is_integer(indices[x])])
return dim_order
def get_dimension_order_transposition(original, new):
old = original
if "M" in new and "I" in old: # replace "I" with "M" if necessary
old = list(old)
old[old.index("I")] = "M"
if "M" in old and "I" in new: # replace "I" with "M" if necessary
new = list(new)
new[new.index("I")] = "M"
transposition = [old.index(x) for x in new]
return tuple(transposition)
def get_values_from_array(array, dimensions, indices=None, dim_order=None):
"""Extract values of a given range from an array
Parameters
----------
array : array_like
Source array
dimensions : tuple of str
Names of the array dimensions in order
indices : dict(key:str, value:int or slice), optional
Key: dimension name, value: indices to be returned, complete axis assumed if not provided
dim_order : tuple of str
Desired order of dimensions in the output array
Returns
-------
values : np.ndarray
Requested array range in regular or desired dimension order, if provided
"""
sls = get_slice_tuple(dimensions, indices)
if dim_order is None: return filled_if_masked(array[sls])
old_dim_order = get_default_dimension_order(dimensions, indices)
transposition = get_dimension_order_transposition(old_dim_order, dim_order)
try:
return filled_if_masked(np.transpose(array[sls], transposition))
except Exception as e:
raise Exception(
"dimension mismatch: cannot transpose from {0} to {1} in order {2}, error {3}".format(old_dim_order,
dim_order,
transposition, e))
return transposed
class _VariableBase:
# """Access the values of a NETCDF4 dataset variable"""
def __init__(self, database, name):
# """
# Parameters
# ----------
# database : :class:`sofa.Database`
# Parent database instance
# name : str
# Variable name within the netCDF4 dataset
# """
self._database = database
self._name = name
@property
def name(self):
return self._name
@property
def database(self):
return self._database
def __getattribute__(self, name):
try:
return super().__getattribute__(name)
except AttributeError:
try:
return self._Matrix.__getattribute__(name)
except: raise
def __setattr__(self, name, value):
if '_' in name:
super().__setattr__(name, value)
return
# TODO: are there any cases in which this is wrong?
self._Matrix.setncattr_string(name, value)
def initialize(self, dims, data_type="d", fill_value=0):
"""Create the variable in the underlying netCDF4 dataset"""
defined = self.database.Dimensions.list_dimensions()
missing = []
for d in dims:
if d not in defined: missing.append(d)
if len(missing): raise Exception("Cannot initialize, dimensions undefined: {0}".format(missing))
try:
self.database.dataset.createVariable(self.name, data_type, dims, fill_value=fill_value)
except Exception as ex:
raise Exception(
"Failed to create variable for {0} of type {1} with fill value {2}, error = {3}".format(self.name,
data_type, dims,
fill_value,
str(ex)))
@property
def _Matrix(self):
if self.name not in self.database.Variables.list_variables(): return None
return self.database.dataset[self.name]
def exists(self):
"""Returns
-------
exists : bool
True if variable exists, False otherwise
"""
return self._Matrix is not None
def dimensions(self):
"""Returns
-------
dimensions : tuple of str
Variable dimension names in order
"""
if not self.exists(): return None
return self._Matrix.dimensions
def axis(self, dim):
"""Parameters
----------
dim : str
Name of the dimension
Returns
-------
axis : int
Index of the dimension axis or None if unused
"""
if dim in self.dimensions(): return self.dimensions().index(dim)
if dim == "M" and "I" in self.dimensions(): return self.dimensions().index("I")
return None
def get_values(self, indices=None, dim_order=None):
"""
Parameters
----------
indices : dict(key:str, value:int or slice), optional
Key: dimension name, value: indices to be returned, complete axis assumed if not provided
dim_order : tuple of str, optional
Desired order of dimensions in the output array
Returns
-------
values : np.ndarray
Requested array range in regular or desired dimension order, if provided
"""
if not self.exists():
raise Exception("failed to get values of {0}, variable not initialized".format(self.name))
return get_values_from_array(self._Matrix, self.dimensions(), indices=indices, dim_order=dim_order)
def _reorder_values_for_set(self, values, indices=None, dim_order=None, repeat_dim=None):
"""
Parameters
----------
values : np.ndarray
New values for the array range
indices : dict(key:str, value:int or slice), optional
Key: dimension name, value: indices to be set, complete axis assumed if not provided
dim_order : tuple of str, optional
Dimension names in provided order, regular order assumed
repeat_dim : tuple of str, optional
Tuple of dimension names along which to repeat the values
"""
if not self.exists():
raise Exception("Variable {0} not initialized".format(self.name))
dimensions = self.dimensions()
if "I" in dimensions:
dimensions = list(dimensions)
dimensions[dimensions.index("I")] = "M"
dimensions = tuple(dimensions)
if indices is not None and "M" in indices.keys(): indices["M"] = 0
if dim_order is not None and "I" in dim_order:
dim_order = list(dim_order)
dim_order[dim_order.index("I")] = "M"
dim_order = tuple(dim_order)
if repeat_dim is not None and "I" in repeat_dim:
repeat_dim = list(repeat_dim)
repeat_dim[repeat_dim.index("I")] = "M"
repeat_dim = tuple(repeat_dim)
sls = ()
for d in dimensions:
sl = slice(None)
if indices is not None and d in indices: sl = indices[d]
sls = sls + (sl,)
new_values = np.asarray(values)
# repeat along provided dimensions
full_dim_order = dim_order
if repeat_dim is not None:
if full_dim_order is None:
full_dim_order = tuple(x for x in dimensions if x not in repeat_dim)
for d in repeat_dim:
if dim_order is not None and d in dim_order:
raise Exception("cannot repeat values along dimension {0}: dimension already provided".format(d))
return None
i = self.axis(d)
if i is None:
raise Exception(
"cannot repeat values along dimension {0}: dimension unused by variable {1}".format(d,
self.name))
return None
count = self._Matrix[sls].shape[i]
new_values = np.repeat([new_values], count, axis=0)
full_dim_order = (d,) + full_dim_order
# change order if necessary
if full_dim_order is not None:
do = ()
for d in dimensions:
if d in full_dim_order:
if indices is not None and d in indices.keys() and type(indices[d]) != slice:
raise Exception(
"cannot assign values to variable {0}: dimension {1} is {2}, not a slice".format(self.name,
d, type(
indices[d])))
return None
do = do + (full_dim_order.index(d),)
elif indices is None or d not in indices.keys():
raise Exception("cannot assign values to variable {0}: missing dimension {1}".format(self.name, d))
return None
new_values = np.transpose(new_values, do)
return new_values, sls
def set_values(self, values, indices=None, dim_order=None, repeat_dim=None):
"""
Parameters
----------
values : np.ndarray
New values for the array range
indices : dict(key:str, value:int or slice), optional
Key: dimension name, value: indices to be set, complete axis assumed if not provided
dim_order : tuple of str, optional
Dimension names in provided order, regular order assumed
repeat_dim : tuple of str, optional
Tuple of dimension names along which to repeat the values
"""
if not self.exists():
raise Exception("failed to set values of {0}, variable not initialized".format(self.name))
new_values, sls = self._reorder_values_for_set(values, indices, dim_order, repeat_dim)
# assign
self._Matrix[sls] = new_values
return
class Variable(_VariableBase):
def __init__(self, database, name):
super().__init__(database, name)
self._unit_proxy = None
@property
def Units(self):
"""Units of the values"""
if not self.exists():
raise Exception("failed to get Units of {0}, variable not initialized".format(self.name))
if self._unit_proxy is None: return self._Matrix.Units
return self._unit_proxy.Units
@Units.setter
def Units(self, value):
if not self.exists():
raise Exception("failed to set Units of {0}, variable not initialized".format(self.name))
self._Matrix.Units = value
class DatasetVariables:
# """Direct access the dataset variables"""
def __init__(self, database):
self.database = database
def get_variable(self, name):
"""Parameters
----------
name : str
Name of the variable
Returns
-------
value : `sofa.access.Variable`
Access object for the variable
"""
return Variable(self.database, name)
def get_string_array(self, name):
"""Parameters
----------
name : str
Name of the string array
Returns
-------
value : `sofa.access.StringArray`
Access object for the string array
"""
return StringArray(self.database, name)
def create_variable(self, name, dims, data_type="d", fill_value=0):
"""Parameters
----------
name : str
Name of the variable
dims : tuple(str)
Dimensions of the variable
Returns
-------
value : `sofa.access.Variable`
Access object for the variable
"""
var = self.get_variable(name)
if var.exists():
# TODO: add raise error?
print(name, "already exists in the dataset!")
return var
var.initialize(dims, data_type=data_type, fill_value=fill_value)
return var
def create_string_array(self, name, dims):
"""Parameters
----------
name : str
Name of the variable
dims : tuple(str)
Dimensions of the variable
Returns
-------
value : `sofa.access.StringArray`
Access object for the string array
"""
var = self.get_string_array(name)
if var.exists():
# TODO: add raise error?
print(name, "already exists in the dataset!")
return var
var.initialize(dims)
return var
def list_variables(self):
"""Returns
-------
attrs : list
List of the existing dataset variable and string array names
"""
return sorted(self.database.dataset.variables.keys())
def dump(self):
"""Prints all variables and their dimensions"""
for vname in self.list_variables():
print("{0}: {1}".format(vname, self.get_variable(vname).dimensions()))
return
class StringArray(_VariableBase):
def initialize(self, dims, data_type="c", fill_value='\0'):
"""Create the zero-padded character array in the underlying netCDF4 dataset.
Dimension 'S' must be the last dimension, and is appended if not included in dims."""
if "S" not in dims: dims = dims + ("S",)
if dims[-1] != "S": raise Exception("Failed to initialize character array with dimensions {0}, 'S' must be last dimension.".format(dims))
super().initialize(dims, data_type, fill_value)
def get_values(self, indices=None, dim_order=None):
"""
Parameters
----------
indices : dict(key:str, value:int or slice), optional
Key: dimension name, value: indices to be returned, complete axis assumed if not provided
dim_order : tuple of str, optional
Desired order of dimensions in the output array
Returns
-------
values : np.ndarray
Requested array range in regular or desired dimension order, if provided
"""
if dim_order is not None and "S" not in dim_order: dim_order = dim_order + ("S",)
return super().get_values(indices, dim_order)
def set_values(self, values, indices=None, dim_order=None, repeat_dim=None):
"""
Parameters
----------
values : np.ndarray
New values for the array range
indices : dict(key:str, value:int or slice), optional
Key: dimension name, value: indices to be set, complete axis assumed if not provided
dim_order : tuple of str, optional
Dimension names in provided order, regular order assumed
repeat_dim : tuple of str, optional
Tuple of dimension names along which to repeat the values
"""
if dim_order is not None and "S" not in dim_order: dim_order = dim_order + ("S",)
# TODO: accept nested lists of strings that may be too short, convert into proper character array
return super().set_values(values, indices, dim_order, repeat_dim) | [
"numpy.transpose",
"numpy.asarray",
"numpy.repeat"
] | [((9425, 9443), 'numpy.asarray', 'np.asarray', (['values'], {}), '(values)\n', (9435, 9443), True, 'import numpy as np\n'), ((3498, 3537), 'numpy.transpose', 'np.transpose', (['array[sls]', 'transposition'], {}), '(array[sls], transposition)\n', (3510, 3537), True, 'import numpy as np\n'), ((11394, 11422), 'numpy.transpose', 'np.transpose', (['new_values', 'do'], {}), '(new_values, do)\n', (11406, 11422), True, 'import numpy as np\n'), ((10369, 10407), 'numpy.repeat', 'np.repeat', (['[new_values]', 'count'], {'axis': '(0)'}), '([new_values], count, axis=0)\n', (10378, 10407), True, 'import numpy as np\n')] |
""" Test Binary Relevance Model
"""
import unittest
import numpy as np
from numpy.testing import assert_array_equal
from sklearn import datasets
try:
from sklearn.model_selection import train_test_split
except ImportError:
from sklearn.cross_validation import train_test_split
import sklearn.linear_model
from libact.base.dataset import Dataset
from libact.models import LogisticRegression
from libact.models.multilabel import BinaryRelevance
class BinaryRelevanceTestCase(unittest.TestCase):
def setUp(self):
X, Y = datasets.make_multilabel_classification(random_state=1126)
self.X_train, self.X_test, self.Y_train, self.Y_test = \
train_test_split(X, Y, test_size=0.3, random_state=1126)
def test_binary_relevance_lr(self):
br = BinaryRelevance(base_clf=LogisticRegression(random_state=1126))
br.train(Dataset(self.X_train, self.Y_train))
br_pred_train = br.predict(self.X_train).astype(int)
br_pred_test = br.predict(self.X_test).astype(int)
br_pred_proba_train = br.predict_proba(self.X_train).astype(float)
br_pred_proba_test = br.predict_proba(self.X_test).astype(float)
for i in range(np.shape(self.Y_train)[1]):
clf = sklearn.linear_model.LogisticRegression(random_state=1126)
clf.fit(self.X_train, self.Y_train[:, i])
assert_array_equal(clf.predict(self.X_train).astype(int),
br_pred_train[:, i])
assert_array_equal(clf.predict(self.X_test).astype(int),
br_pred_test[:, i])
assert_array_equal(clf.predict_proba(self.X_train)[:, 1].astype(float),
br_pred_proba_train[:, i])
assert_array_equal(clf.predict_proba(self.X_test)[:, 1].astype(float),
br_pred_proba_test[:, i])
self.assertEqual(
np.mean(np.abs(self.Y_test - br_pred_test).mean(axis=1)),
br.score(Dataset(self.X_test, self.Y_test), 'hamming'))
self.assertRaises(NotImplementedError,
lambda: br.score(Dataset(self.X_test, self.Y_test),
criterion='not_exist'))
def test_binary_relevance_parallel(self):
br = BinaryRelevance(base_clf=LogisticRegression(random_state=1126),
n_jobs=1)
br.train(Dataset(self.X_train, self.Y_train))
br_par = BinaryRelevance(
base_clf=LogisticRegression(random_state=1126), n_jobs=2)
br_par.train(Dataset(self.X_train, self.Y_train))
assert_array_equal(br.predict(self.X_test).astype(int),
br_par.predict(self.X_test).astype(int))
if __name__ == '__main__':
unittest.main()
| [
"numpy.abs",
"libact.models.LogisticRegression",
"sklearn.datasets.make_multilabel_classification",
"sklearn.cross_validation.train_test_split",
"libact.base.dataset.Dataset",
"unittest.main",
"numpy.shape"
] | [((2773, 2788), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2786, 2788), False, 'import unittest\n'), ((542, 600), 'sklearn.datasets.make_multilabel_classification', 'datasets.make_multilabel_classification', ([], {'random_state': '(1126)'}), '(random_state=1126)\n', (581, 600), False, 'from sklearn import datasets\n'), ((678, 734), 'sklearn.cross_validation.train_test_split', 'train_test_split', (['X', 'Y'], {'test_size': '(0.3)', 'random_state': '(1126)'}), '(X, Y, test_size=0.3, random_state=1126)\n', (694, 734), False, 'from sklearn.cross_validation import train_test_split\n'), ((870, 905), 'libact.base.dataset.Dataset', 'Dataset', (['self.X_train', 'self.Y_train'], {}), '(self.X_train, self.Y_train)\n', (877, 905), False, 'from libact.base.dataset import Dataset\n'), ((2404, 2439), 'libact.base.dataset.Dataset', 'Dataset', (['self.X_train', 'self.Y_train'], {}), '(self.X_train, self.Y_train)\n', (2411, 2439), False, 'from libact.base.dataset import Dataset\n'), ((2570, 2605), 'libact.base.dataset.Dataset', 'Dataset', (['self.X_train', 'self.Y_train'], {}), '(self.X_train, self.Y_train)\n', (2577, 2605), False, 'from libact.base.dataset import Dataset\n'), ((814, 851), 'libact.models.LogisticRegression', 'LogisticRegression', ([], {'random_state': '(1126)'}), '(random_state=1126)\n', (832, 851), False, 'from libact.models import LogisticRegression\n'), ((1201, 1223), 'numpy.shape', 'np.shape', (['self.Y_train'], {}), '(self.Y_train)\n', (1209, 1223), True, 'import numpy as np\n'), ((2004, 2037), 'libact.base.dataset.Dataset', 'Dataset', (['self.X_test', 'self.Y_test'], {}), '(self.X_test, self.Y_test)\n', (2011, 2037), False, 'from libact.base.dataset import Dataset\n'), ((2309, 2346), 'libact.models.LogisticRegression', 'LogisticRegression', ([], {'random_state': '(1126)'}), '(random_state=1126)\n', (2327, 2346), False, 'from libact.models import LogisticRegression\n'), ((2500, 2537), 'libact.models.LogisticRegression', 'LogisticRegression', ([], {'random_state': '(1126)'}), '(random_state=1126)\n', (2518, 2537), False, 'from libact.models import LogisticRegression\n'), ((2132, 2165), 'libact.base.dataset.Dataset', 'Dataset', (['self.X_test', 'self.Y_test'], {}), '(self.X_test, self.Y_test)\n', (2139, 2165), False, 'from libact.base.dataset import Dataset\n'), ((1933, 1967), 'numpy.abs', 'np.abs', (['(self.Y_test - br_pred_test)'], {}), '(self.Y_test - br_pred_test)\n', (1939, 1967), True, 'import numpy as np\n')] |
from __future__ import absolute_import, division, print_function
import argparse
import os
import os.path as op
import code
import json
import zipfile
import torch
import numpy as np
from metro.utils.metric_pampjpe import get_alignMesh
def load_pred_json(filepath):
archive = zipfile.ZipFile(filepath, 'r')
jsondata = archive.read('pred.json')
reference = json.loads(jsondata.decode("utf-8"))
return reference[0], reference[1]
def multiscale_fusion(output_dir):
s = '10'
filepath = output_dir + 'ckpt200-sc10_rot0-pred.zip'
ref_joints, ref_vertices = load_pred_json(filepath)
ref_joints_array = np.asarray(ref_joints)
ref_vertices_array = np.asarray(ref_vertices)
rotations = [0.0]
for i in range(1, 10):
rotations.append(i * 10)
rotations.append(i * -10)
scale = [0.7, 0.8, 0.9, 1.0, 1.1]
multiscale_joints = []
multiscale_vertices = []
counter = 0
for s in scale:
for r in rotations:
setting = 'sc%02d_rot%s' % (int(s * 10), str(int(r)))
filepath = output_dir + 'ckpt200-' + setting + '-pred.zip'
joints, vertices = load_pred_json(filepath)
joints_array = np.asarray(joints)
vertices_array = np.asarray(vertices)
pa_joint_error, pa_joint_array, _ = get_alignMesh(joints_array, ref_joints_array, reduction=None)
pa_vertices_error, pa_vertices_array, _ = get_alignMesh(vertices_array, ref_vertices_array, reduction=None)
print('--------------------------')
print('scale:', s, 'rotate', r)
print('PAMPJPE:', 1000 * np.mean(pa_joint_error))
print('PAMPVPE:', 1000 * np.mean(pa_vertices_error))
multiscale_joints.append(pa_joint_array)
multiscale_vertices.append(pa_vertices_array)
counter = counter + 1
overall_joints_array = ref_joints_array.copy()
overall_vertices_array = ref_vertices_array.copy()
for i in range(counter):
overall_joints_array += multiscale_joints[i]
overall_vertices_array += multiscale_vertices[i]
overall_joints_array /= (1 + counter)
overall_vertices_array /= (1 + counter)
pa_joint_error, pa_joint_array, _ = get_alignMesh(overall_joints_array, ref_joints_array, reduction=None)
pa_vertices_error, pa_vertices_array, _ = get_alignMesh(overall_vertices_array, ref_vertices_array, reduction=None)
print('--------------------------')
print('overall:')
print('PAMPJPE:', 1000 * np.mean(pa_joint_error))
print('PAMPVPE:', 1000 * np.mean(pa_vertices_error))
joint_output_save = overall_joints_array.tolist()
mesh_output_save = overall_vertices_array.tolist()
print('save results to pred.json')
with open('pred.json', 'w') as f:
json.dump([joint_output_save, mesh_output_save], f)
filepath = output_dir + 'ckpt200-multisc-pred.zip'
resolved_submit_cmd = 'zip ' + filepath + ' ' + 'pred.json'
print(resolved_submit_cmd)
os.system(resolved_submit_cmd)
resolved_submit_cmd = 'rm pred.json'
print(resolved_submit_cmd)
os.system(resolved_submit_cmd)
def run_multiscale_inference(model_path, mode, output_dir):
if mode == True:
rotations = [0.0]
for i in range(1, 10):
rotations.append(i * 10)
rotations.append(i * -10)
scale = [0.7, 0.8, 0.9, 1.0, 1.1]
else:
rotations = [0.0]
scale = [1.0]
job_cmd = "python ./metro/tools/run_metro_handmesh.py " \
"--val_yaml freihand_v3/test.yaml " \
"--resume_checkpoint %s " \
"--per_gpu_eval_batch_size 32 --run_eval_only --num_worker 2 " \
"--multiscale_inference " \
"--rot %f " \
"--sc %s " \
"--arch hrnet-w64 " \
"--num_hidden_layers 4 " \
"--num_attention_heads 4 " \
"--input_feat_dim 2051,512,128 " \
"--hidden_feat_dim 1024,256,64 " \
"--output_dir %s"
for s in scale:
for r in rotations:
resolved_submit_cmd = job_cmd % (model_path, r, s, output_dir)
print(resolved_submit_cmd)
os.system(resolved_submit_cmd)
def main(args):
model_path = args.model_path
mode = args.multiscale_inference
output_dir = args.output_dir
run_multiscale_inference(model_path, mode, output_dir)
if mode == True:
multiscale_fusion(output_dir)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Evaluate a checkpoint in the folder")
parser.add_argument("--model_path")
parser.add_argument(
"--multiscale_inference",
default=False,
action='store_true',
)
parser.add_argument(
"--output_dir",
default='output/',
type=str,
required=False,
help="The output directory to save checkpoint and test results."
)
args = parser.parse_args()
main(args)
| [
"numpy.mean",
"argparse.ArgumentParser",
"zipfile.ZipFile",
"metro.utils.metric_pampjpe.get_alignMesh",
"numpy.asarray",
"os.system",
"json.dump"
] | [((283, 313), 'zipfile.ZipFile', 'zipfile.ZipFile', (['filepath', '"""r"""'], {}), "(filepath, 'r')\n", (298, 313), False, 'import zipfile\n'), ((632, 654), 'numpy.asarray', 'np.asarray', (['ref_joints'], {}), '(ref_joints)\n', (642, 654), True, 'import numpy as np\n'), ((680, 704), 'numpy.asarray', 'np.asarray', (['ref_vertices'], {}), '(ref_vertices)\n', (690, 704), True, 'import numpy as np\n'), ((2239, 2308), 'metro.utils.metric_pampjpe.get_alignMesh', 'get_alignMesh', (['overall_joints_array', 'ref_joints_array'], {'reduction': 'None'}), '(overall_joints_array, ref_joints_array, reduction=None)\n', (2252, 2308), False, 'from metro.utils.metric_pampjpe import get_alignMesh\n'), ((2355, 2428), 'metro.utils.metric_pampjpe.get_alignMesh', 'get_alignMesh', (['overall_vertices_array', 'ref_vertices_array'], {'reduction': 'None'}), '(overall_vertices_array, ref_vertices_array, reduction=None)\n', (2368, 2428), False, 'from metro.utils.metric_pampjpe import get_alignMesh\n'), ((3006, 3036), 'os.system', 'os.system', (['resolved_submit_cmd'], {}), '(resolved_submit_cmd)\n', (3015, 3036), False, 'import os\n'), ((3113, 3143), 'os.system', 'os.system', (['resolved_submit_cmd'], {}), '(resolved_submit_cmd)\n', (3122, 3143), False, 'import os\n'), ((4506, 4580), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Evaluate a checkpoint in the folder"""'}), "(description='Evaluate a checkpoint in the folder')\n", (4529, 4580), False, 'import argparse\n'), ((2798, 2849), 'json.dump', 'json.dump', (['[joint_output_save, mesh_output_save]', 'f'], {}), '([joint_output_save, mesh_output_save], f)\n', (2807, 2849), False, 'import json\n'), ((1202, 1220), 'numpy.asarray', 'np.asarray', (['joints'], {}), '(joints)\n', (1212, 1220), True, 'import numpy as np\n'), ((1250, 1270), 'numpy.asarray', 'np.asarray', (['vertices'], {}), '(vertices)\n', (1260, 1270), True, 'import numpy as np\n'), ((1320, 1381), 'metro.utils.metric_pampjpe.get_alignMesh', 'get_alignMesh', (['joints_array', 'ref_joints_array'], {'reduction': 'None'}), '(joints_array, ref_joints_array, reduction=None)\n', (1333, 1381), False, 'from metro.utils.metric_pampjpe import get_alignMesh\n'), ((1436, 1501), 'metro.utils.metric_pampjpe.get_alignMesh', 'get_alignMesh', (['vertices_array', 'ref_vertices_array'], {'reduction': 'None'}), '(vertices_array, ref_vertices_array, reduction=None)\n', (1449, 1501), False, 'from metro.utils.metric_pampjpe import get_alignMesh\n'), ((2520, 2543), 'numpy.mean', 'np.mean', (['pa_joint_error'], {}), '(pa_joint_error)\n', (2527, 2543), True, 'import numpy as np\n'), ((2574, 2600), 'numpy.mean', 'np.mean', (['pa_vertices_error'], {}), '(pa_vertices_error)\n', (2581, 2600), True, 'import numpy as np\n'), ((4194, 4224), 'os.system', 'os.system', (['resolved_submit_cmd'], {}), '(resolved_submit_cmd)\n', (4203, 4224), False, 'import os\n'), ((1631, 1654), 'numpy.mean', 'np.mean', (['pa_joint_error'], {}), '(pa_joint_error)\n', (1638, 1654), True, 'import numpy as np\n'), ((1693, 1719), 'numpy.mean', 'np.mean', (['pa_vertices_error'], {}), '(pa_vertices_error)\n', (1700, 1719), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 23 12:31:50 2018
@author: <NAME>
"""
from QChemTool import Structure
from QChemTool.Development.polarizablesytem_periodic import PolarizableSystem
from QChemTool import energy_units
from QChemTool.QuantumChem.Fluorographene.fluorographene import orientFG
import numpy as np
parameters_type_manual = False
system = "2perylene" # "anthanthrene", "perylene", "2perylene"
if not parameters_type_manual: # Automatic definition of parameters
# Set parameters of the system
FG_charges = "ESPfit"
params_polar={"VinterFG": True,"coarse_grain": "plane", "charge_type": FG_charges,"approximation": 1.1, "symm": True}
# Load FG structure
struc = Structure()
if system == "perylene":
struc.load_xyz("FGrph_1perylene_2dist_ser_TDDFT-wB97XD_geom_BLYP-landl2dz_symm.xyz")
# For practical calculation also reorient sheet in propper direction (plane) and carbons has to be before fluorines
#struc.center(72,73,86)
struc = orientFG(struc)
elif system == "anthanthrene":
struc.load_xyz("FGrph_1anthranthrene_1dist_par_TDDFT-wB97XD_geom_BLYP-landl2dz_symm_7x11.xyz")
# For practical calculation also reorient sheet in propper direction (plane) and carbons has to be before fluorines
# struc.center(41,43,133)
struc = orientFG(struc)
elif system == "2perylene":
struc.load_xyz("FGrph_2perylene_1dist_par_TDDFT-wB97XD_geom_BLYP-landl2dz_symm_9x12.xyz")
# For practical calculation also reorient sheet in propper direction (plane) and carbons has to be before fluorines
# struc.center(58,57,83)
struc = orientFG(struc)
struc.output_to_xyz("FGrph_2perylene_1dist_par_reorient.xyz")
# Initialize the system
elstat = {"structure": struc,"charge": FG_charges}
diel = {"structure": struc,"polar": params_polar}
params = {"energy_type": "QC","permivity": 1.0,"order": 2}
system = PolarizableSystem(diel = diel, elstat = elstat, params = params)
# identify defects - separated because now changes can be made to the database
system.identify_defects()
# Calculate energies in the system
Ndef = len(system.defects)
HH = np.zeros((Ndef,Ndef),dtype='f8')
for ii in range(Ndef):
dAVA = system.get_elstat_energy(ii,"excited-ground")
Eshift, res_Energy, TrDip = system.get_SingleDefectProperties(ii)
E01_vacuum = system.defects[ii].get_transition_energy()
HH[ii,ii] = E01_vacuum._value + Eshift._value
with energy_units("1/cm"):
# print(system.defects[0].name,dAVA.value)
print(system.defects[ii].name,ii+1,"energy shift:",Eshift.value)
print(system.defects[ii].name,ii+1,"transition dipole:",TrDip)
for ii in range(Ndef):
for jj in range(ii+1,Ndef):
J_inter, res = system.get_HeterodimerProperties(ii, jj, EngA = HH[ii,ii], EngB = HH[jj,jj], approx=1.1)
#J_inter, res = system.get_HeterodimerProperties(ii, jj, approx=1.1)
HH[ii,jj] = J_inter._value
HH[jj,ii] = HH[ii,jj]
with energy_units("1/cm"):
print(system.defects[ii].name,ii+1,"-",system.defects[jj].name,jj+1,"interaction E:",J_inter.value)
else:
# Set fluorographene charges
# manual definition
CF_charge = -0.0522
CF2_charge = 2*CF_charge
FG_charges={'CF': CF_charge,'CF2': CF2_charge,'CD': 0.0,'C': 0.0}
FG_charges['FC'] = -FG_charges['CF']
FG_charges['F2C'] = -FG_charges["CF2"]/2.0
# set fluorographene atomic polarizabilities
# manual definition
#------------------------------------------------------------------------------
# polxy polz amp per phase
# CF_AE_params = [7.53538330517, 0.0000, 1.0326577124, 2, 0.0]
# CF_A_E_params = [0.505521019116, 0.000000, 0.4981493, 2, np.pi/2]
# CF_BE_params = [0.129161747387, 0.0000, 0.05876077, 2, 0.0]
# CF_Ast_params = [2.30828107, 0.0000000, 0.08196599, 2, 0.0] #[2.30828107, 0.00000, 0.081966, 2]
CF_AE_params = [8.94690348, 4.50738195, 1.65097606, 3, 0.0]
CF_A_E_params = [0.39013017, 2.09784509, 0.59003868, 3, 0.0]
CF_BE_params = [0.57543444, 3.98822098, 0.63754235, 3, 0.0]
CF_Ast_params = [5.17064221/2, 4.99791421/2, 0.25093473/2, 3, 0.0]
VinterFG = 0.0
C_params = [0.00000000, 0.0000000, 0.0, 0, 0.0]
FC_AE_params = [0.00000000, 0.0000000, 0.0, 0, 0.0]
FC_A_E_params = [0.0000000, 0.0000000, 0.0, 0, 0.0]
FC_BE_params = [0.00000000, 0.0000000, 0.0, 0, 0.0]
FC_Ast_params = [0.0000000, 0.0000000, 0.0, 0, 0.0]
polar = {'AlphaE': {"CF": CF_AE_params, "FC": FC_AE_params, "C": C_params}}
polar['Alpha_E'] = {"CF": CF_A_E_params, "FC": FC_A_E_params, "C": C_params}
polar['BetaEE'] = {"CF": CF_BE_params, "FC": FC_BE_params, "C": C_params}
polar['Alpha_st'] = {"CF": CF_Ast_params, "FC": FC_Ast_params, "C": C_params}
params_polar={"VinterFG": 0.0,"coarse_grain": "C", "polarizability": polar,"approximation": 1.1}
# Load FG structure
struc = Structure()
if system == "perylene":
struc.load_xyz("FGrph_1perylene_2dist_ser_TDDFT-wB97XD_geom_BLYP-landl2dz_symm.xyz")
# For practical calculation also reorient sheet in propper direction (plane) and carbons has to be before fluorines
#struc.center(72,73,86)
struc = orientFG(struc)
elif system == "anthanthrene":
struc.load_xyz("FGrph_1anthranthrene_1dist_par_TDDFT-wB97XD_geom_BLYP-landl2dz_symm_7x11.xyz")
# For practical calculation also reorient sheet in propper direction (plane) and carbons has to be before fluorines
# struc.center(41,43,133)
struc = orientFG(struc)
elif system == "2perylene":
struc.load_xyz("FGrph_2perylene_1dist_par_TDDFT-wB97XD_geom_BLYP-landl2dz_symm_9x12.xyz")
# For practical calculation also reorient sheet in propper direction (plane) and carbons has to be before fluorines
# struc.center(58,57,83)
struc = orientFG(struc)
struc.output_to_xyz("FGrph_2perylene_1dist_par_reorient.xyz")
# Initialize the system
elstat = {"structure": struc,"charge": FG_charges}
diel = {"structure": struc,"polar": params_polar}
params = {"energy_type": "QC","permivity": 1.0,"order": 2}
system = PolarizableSystem(diel = diel, elstat = elstat, params = params)
# identify defects - separated because now changes can be made to the database
system.identify_defects()
# Calculate energies in the system
Ndef = len(system.defects)
HH = np.zeros((Ndef,Ndef),dtype='f8')
for ii in range(Ndef):
dAVA = system.get_elstat_energy(ii,"excited-ground")
Eshift, res_Energy, TrDip = system.get_SingleDefectProperties(ii)
E01_vacuum = system.defects[ii].get_transition_energy()
HH[ii,ii] = E01_vacuum._value + Eshift._value
with energy_units("1/cm"):
# print(system.defects[0].name,dAVA.value)
print(system.defects[ii].name,ii+1,"energy shift:",Eshift.value)
print(system.defects[ii].name,ii+1,"transition dipole:",TrDip)
for ii in range(Ndef):
for jj in range(ii+1,Ndef):
J_inter, res = system.get_HeterodimerProperties(ii, jj, EngA = HH[ii,ii], EngB = HH[jj,jj], approx=1.1)
#J_inter, res = system.get_HeterodimerProperties(ii, jj, approx=1.1)
HH[ii,jj] = J_inter._value
HH[jj,ii] = HH[ii,jj]
with energy_units("1/cm"):
print(system.defects[ii].name,ii+1,"-",system.defects[jj].name,jj+1,"interaction E:",J_inter.value)
| [
"QChemTool.Development.polarizablesytem_periodic.PolarizableSystem",
"numpy.zeros",
"QChemTool.QuantumChem.Fluorographene.fluorographene.orientFG",
"QChemTool.energy_units",
"QChemTool.Structure"
] | [((732, 743), 'QChemTool.Structure', 'Structure', ([], {}), '()\n', (741, 743), False, 'from QChemTool import Structure\n'), ((2013, 2071), 'QChemTool.Development.polarizablesytem_periodic.PolarizableSystem', 'PolarizableSystem', ([], {'diel': 'diel', 'elstat': 'elstat', 'params': 'params'}), '(diel=diel, elstat=elstat, params=params)\n', (2030, 2071), False, 'from QChemTool.Development.polarizablesytem_periodic import PolarizableSystem\n'), ((2287, 2321), 'numpy.zeros', 'np.zeros', (['(Ndef, Ndef)'], {'dtype': '"""f8"""'}), "((Ndef, Ndef), dtype='f8')\n", (2295, 2321), True, 'import numpy as np\n'), ((5290, 5301), 'QChemTool.Structure', 'Structure', ([], {}), '()\n', (5299, 5301), False, 'from QChemTool import Structure\n'), ((6571, 6629), 'QChemTool.Development.polarizablesytem_periodic.PolarizableSystem', 'PolarizableSystem', ([], {'diel': 'diel', 'elstat': 'elstat', 'params': 'params'}), '(diel=diel, elstat=elstat, params=params)\n', (6588, 6629), False, 'from QChemTool.Development.polarizablesytem_periodic import PolarizableSystem\n'), ((6845, 6879), 'numpy.zeros', 'np.zeros', (['(Ndef, Ndef)'], {'dtype': '"""f8"""'}), "((Ndef, Ndef), dtype='f8')\n", (6853, 6879), True, 'import numpy as np\n'), ((1043, 1058), 'QChemTool.QuantumChem.Fluorographene.fluorographene.orientFG', 'orientFG', (['struc'], {}), '(struc)\n', (1051, 1058), False, 'from QChemTool.QuantumChem.Fluorographene.fluorographene import orientFG\n'), ((5601, 5616), 'QChemTool.QuantumChem.Fluorographene.fluorographene.orientFG', 'orientFG', (['struc'], {}), '(struc)\n', (5609, 5616), False, 'from QChemTool.QuantumChem.Fluorographene.fluorographene import orientFG\n'), ((1377, 1392), 'QChemTool.QuantumChem.Fluorographene.fluorographene.orientFG', 'orientFG', (['struc'], {}), '(struc)\n', (1385, 1392), False, 'from QChemTool.QuantumChem.Fluorographene.fluorographene import orientFG\n'), ((2619, 2639), 'QChemTool.energy_units', 'energy_units', (['"""1/cm"""'], {}), "('1/cm')\n", (2631, 2639), False, 'from QChemTool import energy_units\n'), ((5935, 5950), 'QChemTool.QuantumChem.Fluorographene.fluorographene.orientFG', 'orientFG', (['struc'], {}), '(struc)\n', (5943, 5950), False, 'from QChemTool.QuantumChem.Fluorographene.fluorographene import orientFG\n'), ((7177, 7197), 'QChemTool.energy_units', 'energy_units', (['"""1/cm"""'], {}), "('1/cm')\n", (7189, 7197), False, 'from QChemTool import energy_units\n'), ((1701, 1716), 'QChemTool.QuantumChem.Fluorographene.fluorographene.orientFG', 'orientFG', (['struc'], {}), '(struc)\n', (1709, 1716), False, 'from QChemTool.QuantumChem.Fluorographene.fluorographene import orientFG\n'), ((3214, 3234), 'QChemTool.energy_units', 'energy_units', (['"""1/cm"""'], {}), "('1/cm')\n", (3226, 3234), False, 'from QChemTool import energy_units\n'), ((6259, 6274), 'QChemTool.QuantumChem.Fluorographene.fluorographene.orientFG', 'orientFG', (['struc'], {}), '(struc)\n', (6267, 6274), False, 'from QChemTool.QuantumChem.Fluorographene.fluorographene import orientFG\n'), ((7772, 7792), 'QChemTool.energy_units', 'energy_units', (['"""1/cm"""'], {}), "('1/cm')\n", (7784, 7792), False, 'from QChemTool import energy_units\n')] |
import numpy as np
import os
from welib import weio # https://github.com/ebranlard/weio
from welib.fast import fastlib as fastlib # latest fastlib is found at https://github.com/ebranlard/welib
def CPLambda():
""" Determine the CP-CT Lambda Pitch matrices of a turbine.
This scrip uses the function CPCT_LambdaPitch which basically does the same as ParametricExample
above.
"""
GE=True
ReRun=False # we don't rerun simulations that were already run
base = '../../_data/NREL5MW'
ref_dir = '../../_data/NREL5MW/' # Folder where the fast input files are located (will be copied)
main_file = '../../_data/NREL5MW/Main_Onshore_OF2.fst' # Main file in ref_dir, used as a template
FAST_EXE = '../../_data/OpenFAST2_x64s_ebra.exe' # Location of a FAST exe (and dll)
# --- Computing CP and CT matrices for range of lambda and pitches
nLambda = 6
nPitch = 8
Lambda = np.linspace(0.10 ,22,nLambda)
Pitch = np.linspace(-5,40,nPitch)
CP,CT,Lambda,Pitch,MaxVal,result = fastlib.CPCT_LambdaPitch(ref_dir,main_file,Lambda,Pitch,fastExe=FAST_EXE,showOutputs=False,nCores=4,TMax=30,reRun=ReRun)
print('CP max',MaxVal)
np.savetxt(base+'_Lambda.csv',Lambda,delimiter = ',')
np.savetxt(base+'_Pitch.csv' ,Pitch ,delimiter = ',')
np.savetxt(base+'_CP.csv' ,CP ,delimiter = ',')
np.savetxt(base+'_CT.csv' ,CT ,delimiter = ',')
# --- Plotting matrix of CP values
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.gca(projection='3d')
LAMBDA, PITCH = np.meshgrid(Lambda, Pitch)
CP[CP<0]=0
surf = ax.plot_surface(LAMBDA, PITCH, np.transpose(CP), cmap=cm.coolwarm, linewidth=0, antialiased=True,alpha=0.8)
ax.scatter(MaxVal['lambda_opt'],MaxVal['pitch_opt'],MaxVal['CP_max'],c='k',marker='o',s=20)
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()
# def focus_mesh(xmin,xmax,xfocus)
if __name__=='__main__':
CPLambda()
| [
"numpy.linspace",
"matplotlib.pyplot.figure",
"numpy.savetxt",
"numpy.meshgrid",
"numpy.transpose",
"welib.fast.fastlib.CPCT_LambdaPitch",
"matplotlib.pyplot.show"
] | [((954, 983), 'numpy.linspace', 'np.linspace', (['(0.1)', '(22)', 'nLambda'], {}), '(0.1, 22, nLambda)\n', (965, 983), True, 'import numpy as np\n'), ((997, 1024), 'numpy.linspace', 'np.linspace', (['(-5)', '(40)', 'nPitch'], {}), '(-5, 40, nPitch)\n', (1008, 1024), True, 'import numpy as np\n'), ((1063, 1196), 'welib.fast.fastlib.CPCT_LambdaPitch', 'fastlib.CPCT_LambdaPitch', (['ref_dir', 'main_file', 'Lambda', 'Pitch'], {'fastExe': 'FAST_EXE', 'showOutputs': '(False)', 'nCores': '(4)', 'TMax': '(30)', 'reRun': 'ReRun'}), '(ref_dir, main_file, Lambda, Pitch, fastExe=\n FAST_EXE, showOutputs=False, nCores=4, TMax=30, reRun=ReRun)\n', (1087, 1196), True, 'from welib.fast import fastlib as fastlib\n'), ((1217, 1272), 'numpy.savetxt', 'np.savetxt', (["(base + '_Lambda.csv')", 'Lambda'], {'delimiter': '""","""'}), "(base + '_Lambda.csv', Lambda, delimiter=',')\n", (1227, 1272), True, 'import numpy as np\n'), ((1275, 1328), 'numpy.savetxt', 'np.savetxt', (["(base + '_Pitch.csv')", 'Pitch'], {'delimiter': '""","""'}), "(base + '_Pitch.csv', Pitch, delimiter=',')\n", (1285, 1328), True, 'import numpy as np\n'), ((1333, 1380), 'numpy.savetxt', 'np.savetxt', (["(base + '_CP.csv')", 'CP'], {'delimiter': '""","""'}), "(base + '_CP.csv', CP, delimiter=',')\n", (1343, 1380), True, 'import numpy as np\n'), ((1391, 1438), 'numpy.savetxt', 'np.savetxt', (["(base + '_CT.csv')", 'CT'], {'delimiter': '""","""'}), "(base + '_CT.csv', CT, delimiter=',')\n", (1401, 1438), True, 'import numpy as np\n'), ((1605, 1617), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1615, 1617), True, 'import matplotlib.pyplot as plt\n'), ((1672, 1698), 'numpy.meshgrid', 'np.meshgrid', (['Lambda', 'Pitch'], {}), '(Lambda, Pitch)\n', (1683, 1698), True, 'import numpy as np\n'), ((1978, 1988), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1986, 1988), True, 'import matplotlib.pyplot as plt\n'), ((1756, 1772), 'numpy.transpose', 'np.transpose', (['CP'], {}), '(CP)\n', (1768, 1772), True, 'import numpy as np\n')] |
import os
import h5py
import pickle
import numpy as np
from termcolor import colored
from torch.utils.data import Dataset, DataLoader
class CIFAR10Loader(Dataset):
'''Data loader for cifar10 dataset'''
def __init__(self, data_path='data/cifar-10-batches-py', mode='train', transform=None):
self.data_path = data_path
self.transform = transform
self.mode = mode
self.data = []
self.labels = []
self._init_loader()
def __len__(self):
return len(self.labels)
def __getitem__(self, idx):
sample_train = self.data[idx]
label_train = self.labels[idx]
if self.transform:
sample_train = self.transform(sample_train)
label_train = self.transform(label_train)
return sample_train, label_train
def _init_loader(self):
if self.mode == 'train':
batch_list = [
['data_batch_1', 'c99cafc152244af753f735de768cd75f'],
['data_batch_2', 'd4bba439e000b95fd0a9bffe97cbabec'],
['data_batch_3', '54ebc095f3ab1f0389bbae665268c751'],
['data_batch_4', '634d18415352ddfa80567beed471001a'],
['data_batch_5', '482c414d41f54cd18b22e5b47cb7c3cb'],
]
elif self.mode == 'test':
batch_list = [
['test_batch', '40351d587109b95175f43aff81a1287e'],
]
else:
raise Exception('Unknown: mode type(Options: train, test)')
for batch in batch_list:
print(colored('====> ', 'blue') + 'Processing file: ', os.path.join(self.data_path, batch[0]))
batch = unpickle(os.path.join(self.data_path, batch[0]))
tmp = batch[b'data']
self.data.append(tmp)
self.labels.append(batch[b'labels'])
self.data = np.float32(np.concatenate(self.data))
self.data = self.data.reshape(self.data.shape[0], 3, 32, 32) #.swapaxes(1, 3).swapaxes(1, 2)
self.labels = np.concatenate(self.labels).astype(np.long)
print('Data dims, Label dims :', self.data.shape, self.labels.shape)
def unpickle(file):
with open(file, 'rb') as fp:
dict = pickle.load(fp, encoding='bytes')
return dict
class PCamLoader(Dataset):
'''Data loader for PCam dataset'''
def __init__(self, data_path='data/', mode='train', transform=None):
self.data_path = data_path
self.transform = transform
self.mode = mode
self.data = []
self.labels = []
self._init_loader()
def __len__(self):
return len(self.labels)
def __getitem__(self, idx):
sample_train = self.data[idx]
label_train = self.labels[idx]
if self.transform:
sample_train = self.transform(sample_train)
label_train = self.transform(label_train)
return sample_train, label_train
def _init_loader(self):
if self.mode == 'train':
batch_list = [
'camelyonpatch_level_2_split_train_x.h5',
'camelyonpatch_level_2_split_train_y.h5'
]
elif self.mode == 'valid':
batch_list = [
'camelyonpatch_level_2_split_valid_x.h5',
'camelyonpatch_level_2_split_valid_y.h5'
]
else:
batch_list = [
'camelyonpatch_level_2_split_test_x.h5',
'camelyonpatch_level_2_split_test_y.h5'
]
data_file, label_file = batch_list
self.data = np.array(extract_hdf5(
os.path.join(self.data_path, data_file)
)['x'][:,32:64, 32:64, :],
dtype=np.float32).swapaxes(1, 2).swapaxes(1,3)
self.labels = np.array(
extract_hdf5(os.path.join(self.data_path, label_file))['y'],
).astype(np.long).reshape(-1)
print('Data dims, Label dims :', self.data.shape, self.labels.shape)
return 0
def extract_hdf5(filename):
f = h5py.File(filename, 'r')
return f
| [
"termcolor.colored",
"os.path.join",
"pickle.load",
"h5py.File",
"numpy.concatenate"
] | [((4103, 4127), 'h5py.File', 'h5py.File', (['filename', '"""r"""'], {}), "(filename, 'r')\n", (4112, 4127), False, 'import h5py\n'), ((2204, 2237), 'pickle.load', 'pickle.load', (['fp'], {'encoding': '"""bytes"""'}), "(fp, encoding='bytes')\n", (2215, 2237), False, 'import pickle\n'), ((1861, 1886), 'numpy.concatenate', 'np.concatenate', (['self.data'], {}), '(self.data)\n', (1875, 1886), True, 'import numpy as np\n'), ((1604, 1642), 'os.path.join', 'os.path.join', (['self.data_path', 'batch[0]'], {}), '(self.data_path, batch[0])\n', (1616, 1642), False, 'import os\n'), ((1673, 1711), 'os.path.join', 'os.path.join', (['self.data_path', 'batch[0]'], {}), '(self.data_path, batch[0])\n', (1685, 1711), False, 'import os\n'), ((2012, 2039), 'numpy.concatenate', 'np.concatenate', (['self.labels'], {}), '(self.labels)\n', (2026, 2039), True, 'import numpy as np\n'), ((1555, 1580), 'termcolor.colored', 'colored', (['"""====> """', '"""blue"""'], {}), "('====> ', 'blue')\n", (1562, 1580), False, 'from termcolor import colored\n'), ((3862, 3902), 'os.path.join', 'os.path.join', (['self.data_path', 'label_file'], {}), '(self.data_path, label_file)\n', (3874, 3902), False, 'import os\n'), ((3614, 3653), 'os.path.join', 'os.path.join', (['self.data_path', 'data_file'], {}), '(self.data_path, data_file)\n', (3626, 3653), False, 'import os\n')] |
"""
SAMS umbrella sampling for DDR1 kinase DFG loop flip.
"""
__author__ = '<NAME>'
################################################################################
# IMPORTS
################################################################################
import os, os.path
import sys, math
import numpy as np
import time
from simtk import openmm, unit
from simtk.openmm import app
import mdtraj as md
import netCDF4
from sams import ThermodynamicState
################################################################################
# MAJOR SETTINGS AND PARAMETERS
################################################################################
# Define paths for explicitly-solvated complex
system_xml_filename = 'setup/system.xml'
state_xml_filename = 'setup/state_DFG_IN.xml'
state_pdb_filename = 'setup/state_DFG_IN.pdb'
pdb_filename = 'setup/systems/Abl-STI/complex.pdb'
top = md.load(state_pdb_filename).topology
# Specify umbrellas for distance restraint
angle_sigma = 10*unit.degrees # umbrella stddev width in absence of external PMF (no Jacobian)
distance_sigma = 1*unit.angstroms # umbrella stddev width
# add our known kinase coordinates
# Roux pseudo-dihedral
Roux = ['resid 179 and resname ALA and name CB',
'resid 179 and resname ALA and name CA',
'resid 180 and resname ASP and name CA',
'resid 180 and resname ASP and name CG']
Roux_atoms = list()
for atom in Roux:
atom_select = int(top.select(atom)[0])
Roux_atoms.append(atom_select)
# DFG distance
DFG_distance = ['resid 149 and resname GLY and name CA',
'resid 181 and resname PHE and name CZ']
DFG_atoms = list()
for atom in DFG_distance:
atom_select = int(top.select(atom)[0])
DFG_atoms.append(atom_select)
min_dihedral = -180*unit.degrees
max_dihedral = +180*unit.degrees
dihedral_unit = unit.degrees
ntorsion_umbrellas = int((max_dihedral - min_dihedral) / angle_sigma)
torsion_umbrella_values = np.linspace((min_dihedral+angle_sigma/2)/dihedral_unit, (max_dihedral-angle_sigma/2)/dihedral_unit, ntorsion_umbrellas) * dihedral_unit
min_distance = 1.0*unit.angstroms
max_distance = 10.0*unit.angstroms
distance_unit = unit.angstroms
ndistance_umbrellas = int((max_distance - min_distance) / distance_sigma)
distance_umbrella_values = np.linspace((min_distance+distance_sigma/2)/distance_unit, (max_distance-distance_sigma/2)/distance_unit, ndistance_umbrellas) * distance_unit
# Output SAMS filename
netcdf_filename = 'output.nc'
pdb_trajectory_filename = 'trajectory.pdb' # first frame of trajectory to be written at end
dcd_trajectory_filename = 'trajectory.dcd' # DCD format for trajectory to be written at end
# Simulation conditions
temperature = 298.0 * unit.kelvin
pressure = 1.0 * unit.atmospheres
collision_rate = 1.0 / unit.picoseconds
timestep = 2.0 * unit.femtoseconds
#minimize = True # if True, will minimize the structure before simulation (highly recommended)
minimize = False
################################################################################
# SUBROUTINES
################################################################################
def read_file(filename):
infile = open(filename, 'r')
contents = infile.read()
return contents
################################################################################
# MAIN
################################################################################
from sams import kB
kT = kB * temperature
beta = 1.0 / kT
# Load system
print('Loading system...')
system = openmm.XmlSerializer.deserialize(read_file(system_xml_filename))
pdbfile = app.PDBFile(state_pdb_filename)
topology = pdbfile.topology
state = openmm.XmlSerializer.deserialize(read_file(state_xml_filename))
positions = state.getPositions(asNumpy=True)
box_vectors = state.getPeriodicBoxVectors()
print('System has %d atoms.' % system.getNumParticles())
forces = { force.__class__.__name__ : force for force in system.getForces() }
if (pressure is not None) and ('MonteCarloBarostat' not in forces):
# Add a barostat
print("Adding barostat...")
barostat = openmm.MonteCarloBarostat(pressure, temperature)
reference_system.addForce(barostat)
else:
# TODO: Update barostat
pass
# Add umbrella restraint with global variable to control umbrella position
print('umbrella schedule for dihedral defined by atoms %s : %s' % (str(Roux_atoms), str(torsion_umbrella_values)))
print('umbrella schedule for distance defined by atoms %s : %s' % (str(DFG_atoms), str(distance_umbrella_values)))
from numpy import pi
energy_function = '- (torsion_K/2) * cos(min(dtheta, 2*pi-dtheta)); dtheta = abs(theta-torsion_theta0);'
energy_function += 'pi = %f;' % pi
umbrella_force = openmm.CustomTorsionForce(energy_function)
umbrella_force.addGlobalParameter('torsion_K', 0.0)
umbrella_force.addGlobalParameter('torsion_theta0', 0.0)
umbrella_force.addTorsion(*Roux_atoms, [])
torsion_K = kT/angle_sigma**2
system.addForce(umbrella_force)
energy_function = '(distance_K/2) * (r-distance_r0)^2;'
umbrella_force = openmm.CustomBondForce(energy_function)
umbrella_force.addGlobalParameter('distance_K', 0.0)
umbrella_force.addGlobalParameter('distance_r0', 0.0)
umbrella_force.addBond(*DFG_atoms, [])
distance_K = kT/distance_sigma**2
system.addForce(umbrella_force)
# Create thermodynamic states
thermodynamic_states = list()
# Umbrella off state
parameters = {
'torsion_K' : 0.0, 'torsion_theta0' : 0.0, # umbrella parameters
'distance_K' : 0.0, 'distance_r0' : 0.0, # umbrella parameters
}
thermodynamic_states.append( ThermodynamicState(system=system, temperature=temperature, pressure=pressure, parameters=parameters) )
# Umbrella on state
alchemical_lambda = 0.0
for theta0 in torsion_umbrella_values:
for r0 in distance_umbrella_values:
parameters = {
'torsion_K' : torsion_K.value_in_unit_system(unit.md_unit_system), 'torsion_theta0' : theta0.value_in_unit_system(unit.md_unit_system), # umbrella parameters
'distance_K' : distance_K.value_in_unit_system(unit.md_unit_system), 'distance_r0' : r0.value_in_unit_system(unit.md_unit_system), # umbrella parameters
}
thermodynamic_states.append( ThermodynamicState(system=system, temperature=temperature, pressure=pressure, parameters=parameters) )
# Select platform automatically; use mixed precision
from openmmtools.integrators import LangevinIntegrator
integrator = LangevinIntegrator(temperature=temperature, collision_rate=collision_rate, timestep=timestep)
context = openmm.Context(system, integrator)
platform = context.getPlatform()
del context
try:
platform.setPropertyDefaultValue('Precision', 'mixed')
platform.setPropertyDefaultValue('DeterministicForces', 'true')
except:
pass
# Minimize
if minimize:
print('Minimizing...')
integrator = openmm.VerletIntegrator(timestep)
context = openmm.Context(system, integrator)
context.setPeriodicBoxVectors(*state.getPeriodicBoxVectors())
context.setPositions(state.getPositions(asNumpy=True))
print("Initial energy is %12.3f kcal/mol" % (context.getState(getEnergy=True).getPotentialEnergy() / unit.kilocalories_per_mole))
TOL = 1.0
MAX_STEPS = 500
openmm.LocalEnergyMinimizer.minimize(context, TOL, MAX_STEPS)
print("Final energy is %12.3f kcal/mol" % (context.getState(getEnergy=True).getPotentialEnergy() / unit.kilocalories_per_mole))
# Update positions.
positions = context.getState(getPositions=True).getPositions(asNumpy=True)
# Clean up.
del context, integrator
# Create output SAMS file
print('Opening %s for writing...' % netcdf_filename)
ncfile = netCDF4.Dataset(netcdf_filename, mode='w')
# Create SAMS samplers
print('Setting up samplers...')
from sams.samplers import SamplerState, MCMCSampler, ExpandedEnsembleSampler, SAMSSampler
thermodynamic_state_index = 0 # initial thermodynamic state index
thermodynamic_state = thermodynamic_states[thermodynamic_state_index]
sampler_state = SamplerState(positions=positions, box_vectors=box_vectors)
mcmc_sampler = MCMCSampler(sampler_state=sampler_state, thermodynamic_state=thermodynamic_state, ncfile=ncfile, platform=platform)
mcmc_sampler.timestep = timestep
mcmc_sampler.nsteps = 500
#mcmc_sampler.pdbfile = open('output.pdb', 'w') # uncomment this if you want to write a PDB trajectory as you simulate; WARNING: LARGE!
mcmc_sampler.topology = topology
mcmc_sampler.verbose = True
exen_sampler = ExpandedEnsembleSampler(mcmc_sampler, thermodynamic_states)
exen_sampler.verbose = True
sams_sampler = SAMSSampler(exen_sampler)
sams_sampler.verbose = True
# DEBUG: Write PDB of initial frame
print("Writing initial frame to 'initial.pdb'...")
from simtk.openmm.app import PDBFile
outfile = open('initial.pdb', 'w')
PDBFile.writeFile(topology, positions, outfile)
outfile.close()
# Run the simulation
print('Running simulation...')
#exen_sampler.update_scheme = 'restricted-range' # scheme for deciding which alchemical state to jump to
exen_sampler.update_scheme = 'global-jump' # scheme for deciding which alchemical state to jump to
#exen_sampler.locality = thermodynamic_state_neighbors # neighbors to examine for each state
sams_sampler.update_method = 'rao-blackwellized' # scheme for updating free energy estimates
niterations = 20000 # number of iterations to run
sams_sampler.run(niterations) # run sampler
ncfile.close()
# Analyze
from sams import analysis
# States
from collections import namedtuple
MockTestsystem = namedtuple('MockTestsystem', ['description', 'thermodynamic_states'])
testsystem = MockTestsystem(description='DDR1 umbrella states', thermodynamic_states=thermodynamic_states)
analysis.analyze(netcdf_filename, testsystem, 'output.pdf')
# Write trajectory
reference_pdb_filename = 'trajectory.pdb'
trajectory_filename = 'trajectory.xtc'
analysis.write_trajectory(netcdf_filename, topology, reference_pdb_filename, trajectory_filename)
| [
"simtk.openmm.VerletIntegrator",
"simtk.openmm.LocalEnergyMinimizer.minimize",
"simtk.openmm.app.PDBFile",
"simtk.openmm.MonteCarloBarostat",
"sams.samplers.SamplerState",
"simtk.openmm.CustomBondForce",
"netCDF4.Dataset",
"openmmtools.integrators.LangevinIntegrator",
"numpy.linspace",
"sams.sampl... | [((3583, 3614), 'simtk.openmm.app.PDBFile', 'app.PDBFile', (['state_pdb_filename'], {}), '(state_pdb_filename)\n', (3594, 3614), False, 'from simtk.openmm import app\n'), ((4693, 4735), 'simtk.openmm.CustomTorsionForce', 'openmm.CustomTorsionForce', (['energy_function'], {}), '(energy_function)\n', (4718, 4735), False, 'from simtk import openmm, unit\n'), ((5024, 5063), 'simtk.openmm.CustomBondForce', 'openmm.CustomBondForce', (['energy_function'], {}), '(energy_function)\n', (5046, 5063), False, 'from simtk import openmm, unit\n'), ((6398, 6495), 'openmmtools.integrators.LangevinIntegrator', 'LangevinIntegrator', ([], {'temperature': 'temperature', 'collision_rate': 'collision_rate', 'timestep': 'timestep'}), '(temperature=temperature, collision_rate=collision_rate,\n timestep=timestep)\n', (6416, 6495), False, 'from openmmtools.integrators import LangevinIntegrator\n'), ((6502, 6536), 'simtk.openmm.Context', 'openmm.Context', (['system', 'integrator'], {}), '(system, integrator)\n', (6516, 6536), False, 'from simtk import openmm, unit\n'), ((7612, 7654), 'netCDF4.Dataset', 'netCDF4.Dataset', (['netcdf_filename'], {'mode': '"""w"""'}), "(netcdf_filename, mode='w')\n", (7627, 7654), False, 'import netCDF4\n'), ((7953, 8011), 'sams.samplers.SamplerState', 'SamplerState', ([], {'positions': 'positions', 'box_vectors': 'box_vectors'}), '(positions=positions, box_vectors=box_vectors)\n', (7965, 8011), False, 'from sams.samplers import SamplerState, MCMCSampler, ExpandedEnsembleSampler, SAMSSampler\n'), ((8027, 8147), 'sams.samplers.MCMCSampler', 'MCMCSampler', ([], {'sampler_state': 'sampler_state', 'thermodynamic_state': 'thermodynamic_state', 'ncfile': 'ncfile', 'platform': 'platform'}), '(sampler_state=sampler_state, thermodynamic_state=\n thermodynamic_state, ncfile=ncfile, platform=platform)\n', (8038, 8147), False, 'from sams.samplers import SamplerState, MCMCSampler, ExpandedEnsembleSampler, SAMSSampler\n'), ((8414, 8473), 'sams.samplers.ExpandedEnsembleSampler', 'ExpandedEnsembleSampler', (['mcmc_sampler', 'thermodynamic_states'], {}), '(mcmc_sampler, thermodynamic_states)\n', (8437, 8473), False, 'from sams.samplers import SamplerState, MCMCSampler, ExpandedEnsembleSampler, SAMSSampler\n'), ((8517, 8542), 'sams.samplers.SAMSSampler', 'SAMSSampler', (['exen_sampler'], {}), '(exen_sampler)\n', (8528, 8542), False, 'from sams.samplers import SamplerState, MCMCSampler, ExpandedEnsembleSampler, SAMSSampler\n'), ((8731, 8778), 'simtk.openmm.app.PDBFile.writeFile', 'PDBFile.writeFile', (['topology', 'positions', 'outfile'], {}), '(topology, positions, outfile)\n', (8748, 8778), False, 'from simtk.openmm.app import PDBFile\n'), ((9445, 9514), 'collections.namedtuple', 'namedtuple', (['"""MockTestsystem"""', "['description', 'thermodynamic_states']"], {}), "('MockTestsystem', ['description', 'thermodynamic_states'])\n", (9455, 9514), False, 'from collections import namedtuple\n'), ((9622, 9681), 'sams.analysis.analyze', 'analysis.analyze', (['netcdf_filename', 'testsystem', '"""output.pdf"""'], {}), "(netcdf_filename, testsystem, 'output.pdf')\n", (9638, 9681), False, 'from sams import analysis\n'), ((9782, 9883), 'sams.analysis.write_trajectory', 'analysis.write_trajectory', (['netcdf_filename', 'topology', 'reference_pdb_filename', 'trajectory_filename'], {}), '(netcdf_filename, topology, reference_pdb_filename,\n trajectory_filename)\n', (9807, 9883), False, 'from sams import analysis\n'), ((894, 921), 'mdtraj.load', 'md.load', (['state_pdb_filename'], {}), '(state_pdb_filename)\n', (901, 921), True, 'import mdtraj as md\n'), ((1945, 2080), 'numpy.linspace', 'np.linspace', (['((min_dihedral + angle_sigma / 2) / dihedral_unit)', '((max_dihedral - angle_sigma / 2) / dihedral_unit)', 'ntorsion_umbrellas'], {}), '((min_dihedral + angle_sigma / 2) / dihedral_unit, (max_dihedral -\n angle_sigma / 2) / dihedral_unit, ntorsion_umbrellas)\n', (1956, 2080), True, 'import numpy as np\n'), ((2283, 2426), 'numpy.linspace', 'np.linspace', (['((min_distance + distance_sigma / 2) / distance_unit)', '((max_distance - distance_sigma / 2) / distance_unit)', 'ndistance_umbrellas'], {}), '((min_distance + distance_sigma / 2) / distance_unit, (\n max_distance - distance_sigma / 2) / distance_unit, ndistance_umbrellas)\n', (2294, 2426), True, 'import numpy as np\n'), ((4076, 4124), 'simtk.openmm.MonteCarloBarostat', 'openmm.MonteCarloBarostat', (['pressure', 'temperature'], {}), '(pressure, temperature)\n', (4101, 4124), False, 'from simtk import openmm, unit\n'), ((5541, 5646), 'sams.ThermodynamicState', 'ThermodynamicState', ([], {'system': 'system', 'temperature': 'temperature', 'pressure': 'pressure', 'parameters': 'parameters'}), '(system=system, temperature=temperature, pressure=\n pressure, parameters=parameters)\n', (5559, 5646), False, 'from sams import ThermodynamicState\n'), ((6800, 6833), 'simtk.openmm.VerletIntegrator', 'openmm.VerletIntegrator', (['timestep'], {}), '(timestep)\n', (6823, 6833), False, 'from simtk import openmm, unit\n'), ((6848, 6882), 'simtk.openmm.Context', 'openmm.Context', (['system', 'integrator'], {}), '(system, integrator)\n', (6862, 6882), False, 'from simtk import openmm, unit\n'), ((7180, 7241), 'simtk.openmm.LocalEnergyMinimizer.minimize', 'openmm.LocalEnergyMinimizer.minimize', (['context', 'TOL', 'MAX_STEPS'], {}), '(context, TOL, MAX_STEPS)\n', (7216, 7241), False, 'from simtk import openmm, unit\n'), ((6173, 6278), 'sams.ThermodynamicState', 'ThermodynamicState', ([], {'system': 'system', 'temperature': 'temperature', 'pressure': 'pressure', 'parameters': 'parameters'}), '(system=system, temperature=temperature, pressure=\n pressure, parameters=parameters)\n', (6191, 6278), False, 'from sams import ThermodynamicState\n')] |
"""
The board class manages the position of pieces, and conversion to and from
Forsyth-Edwards Notation (FEN). This class is only used internally by the
`Game` class.
"""
import numpy as np
class Board(object):
"""
This class manages the position of all pieces in a chess game. The
position is stored as a list of single-character strings.
"""
_position = []
def __init__(self, position=' ' * 64, row_size=8):
# castling type look up
self.castling_type_dict = {62: 'K', 58: 'Q', 6: 'k', 2: 'q'}
self._row_size = row_size
self._position = []
self.set_position(position)
def __repr__(self):
"""
Return 2D the piece placement array to a string.
"""
np_pos = np.array(self._position.copy())
np_pos = np.reshape(np_pos, (-1, self._row_size))
ranks = np.arange(self._row_size, 0, -1).reshape((self._row_size, 1))
np_pos = np.hstack((ranks, np_pos))
files = [' '] + list(map(chr, range(97, 97 + self._row_size)))
files = np.array(files).reshape((1, self._row_size + 1))
np_pos = np.vstack((np_pos, files))
return str(np_pos)
def __str__(self):
"""
Convert the piece placement array to a FEN string.
"""
pos = []
for idx, piece in enumerate(self._position):
# add a '/' at the end of each row
if idx > 0 and idx % self._row_size == 0:
pos.append('/')
# blank spaces must be converted to numbers in the final FEN
if not piece.isspace():
pos.append(piece)
elif pos and pos[-1].isdigit():
pos[-1] = str(int(pos[-1]) + 1)
else:
pos.append('1')
return ''.join(pos)
def set_position(self, position):
"""
Convert a FEN position string into a piece placement array.
"""
self._position = []
for char in position:
if char == '/': # skip row separator character
continue
elif char.isdigit():
# replace numbers characters with that number of spaces
self._position.extend([' '] * int(char))
else:
self._position.append(char)
def get_piece(self, index):
"""Get the piece at the given index in the position array."""
return self._position[index]
def get_owner(self, index):
"""
Get the owner of the piece at the given index in the position array.
"""
piece = self.get_piece(index)
if not piece.isspace():
return 'w' if piece.isupper() else 'b'
return None
def move_piece(self, start, end, piece):
"""
Move a piece by removing it from the starting position and adding it
to the end position. If a different piece is provided, that piece will
be placed at the end index instead.
"""
self._position[end] = piece
self._position[start] = ' '
def find_piece(self, symbol):
"""
Find the index of the specified piece on the board, returns -1 if the
piece is not on the board.
"""
return ''.join(self._position).find(symbol)
def get_row_size(self):
return self._row_size
def get_idx_range(self):
return len(self._position)
@staticmethod
def is_promotion(target):
return target < 8 or target > 55
| [
"numpy.reshape",
"numpy.hstack",
"numpy.array",
"numpy.vstack",
"numpy.arange"
] | [((809, 849), 'numpy.reshape', 'np.reshape', (['np_pos', '(-1, self._row_size)'], {}), '(np_pos, (-1, self._row_size))\n', (819, 849), True, 'import numpy as np\n'), ((945, 971), 'numpy.hstack', 'np.hstack', (['(ranks, np_pos)'], {}), '((ranks, np_pos))\n', (954, 971), True, 'import numpy as np\n'), ((1125, 1151), 'numpy.vstack', 'np.vstack', (['(np_pos, files)'], {}), '((np_pos, files))\n', (1134, 1151), True, 'import numpy as np\n'), ((866, 898), 'numpy.arange', 'np.arange', (['self._row_size', '(0)', '(-1)'], {}), '(self._row_size, 0, -1)\n', (875, 898), True, 'import numpy as np\n'), ((1059, 1074), 'numpy.array', 'np.array', (['files'], {}), '(files)\n', (1067, 1074), True, 'import numpy as np\n')] |
#!/usr/bin/env python
"""
Created on 2015-09-26T12:13:49
"""
from __future__ import division, print_function
import sys
import argparse
import re
import time
try:
import numpy as np
except ImportError:
print('You need numpy installed')
sys.exit(1)
import pandas as pd
from splinter.browser import Browser
import connect_aws_db as cadb
__author__ = "<NAME> (github: @mattgiguere)"
__license__ = "MIT"
__version__ = '0.0.1'
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__status__ = " Development NOT(Prototype or Production)"
def get_city(city):
city_urls = {'new_york_ny': 'http://www.tripadvisor.com/Hotels-g60763-New_York_City_New_York-Hotels.html',
'los_angeles_ca': 'http://www.tripadvisor.com/Hotels-g32655-Los_Angeles_California-Hotels.html',
'chicago_il': 'http://www.tripadvisor.com/Hotels-g35805-Chicago_Illinois-Hotels.html',
'houston_tx': 'http://www.tripadvisor.com/Hotels-g56003-Houston_Texas-Hotels.html',
'philadelphia_pa': 'http://www.tripadvisor.com/Hotels-g60795-Philadelphia_Pennsylvania-Hotels.html',
'phoenix_az': 'http://www.tripadvisor.com/Hotels-g31310-Phoenix_Arizona-Hotels.html',
'san_antonio_tx': 'http://www.tripadvisor.com/Hotels-g60956-San_Antonio_Texas-Hotels.html',
'san_diego_ca': 'http://www.tripadvisor.com/Hotels-g60750-San_Diego_California-Hotels.html',
'dallas_tx': 'http://www.tripadvisor.com/Hotels-g55711-Dallas_Texas-Hotels.html',
'san_jose_ca': 'http://www.tripadvisor.com/Hotels-g33020-San_Jose_California-Hotels.html',
'austin_tx': 'http://www.tripadvisor.com/Hotels-g30196-Austin_Texas-Hotels.html',
'jacksonville_fl': 'http://www.tripadvisor.com/Hotels-g60805-Jacksonville_Florida-Hotels.html',
'san_francisco_ca': 'http://www.tripadvisor.com/Hotels-g60713-San_Francisco_California-Hotels.html',
'indianapolis_in': 'http://www.tripadvisor.com/Hotels-g37209-Indianapolis_Indiana-Hotels.html',
'columbus_oh': 'http://www.tripadvisor.com/Hotels-g50226-Columbus_Ohio-Hotels.html',
'new_haven_ct': 'http://www.tripadvisor.com/Hotels-g33851-New_Haven_Connecticut-Hotels.html',
'palo_alto_ca': 'http://www.tripadvisor.com/Hotels-g32849-Palo_Alto_California-Hotels.html',
'mountain_view_ca': 'http://www.tripadvisor.com/Hotels-g32761-Mountain_View_California-Hotels.html',
'sunnyvale_ca': 'http://www.tripadvisor.com/Hotels-g33146-Sunnyvale_California-Hotels.html',
'santa_clara_ca': 'http://www.tripadvisor.com/Hotels-g33046-Santa_Clara_California-Hotels.html',
}
return city_urls[city]
def get_biz_ids(city, engine):
cmd = 'SELECT business_id FROM ta_hotels '
cmd += 'where hotel_city = '
cmd += '"'+(' ').join(city.split('_'))+'"'
try:
xstng_bizs = [int(biz_id[0]) for biz_id in pd.read_sql_query(cmd, engine).values]
except:
engine = cadb.connect_aws_db(write_unicode=True)
xstng_bizs = [int(biz_id[0]) for biz_id in pd.read_sql_query(cmd, engine).values]
return xstng_bizs
def remove_duplicate_hotels(bigdf, city, engine):
"""
PURPOSE: To remove the duplicate hotel entries before attempting to write the new entries to the DB.
"""
xstng_bizs = get_biz_ids(city, engine)
bigdf['business_id'] = np.int64(bigdf['business_id'].values)
if len(xstng_bizs) > 0:
bigdf = bigdf[~bigdf['business_id'].isin(xstng_bizs)].copy()
return bigdf
def remove_ad_hotels(bigdf):
"""
PURPOSE:
Delete hotels without a business_id (i.e. the advertisement
hotels at the top of some pages)
"""
bigdf = bigdf[bigdf['business_id'] != None].copy()
return bigdf
def splinter_scrape_ta_hotels(city_url='', city='new_haven', state='ct', write_to_db=False, max_pages=20):
"""PURPOSE: To """
# this only needs to be done at the very beginning
br = Browser()
if city_url == '':
city_url = get_city(city.lower()+'_'+state.lower())
print('using the following url:')
print('{}'.format(city_url))
#city_url = "http://www.tripadvisor.com/Hotels-g31310-Phoenix_Arizona-Hotels.html"
#####################################################
# do not edit below this line
#####################################################
# more_pages is used to keep track if there is more
# than one page of hotel results for the given city
more_pages = True
# scraping will start on page 1 of the hotel results
page = 1
# open the URL in a browser object:
br.visit(city_url)
# find the div to enter the date range. This is needed to get pricing info:
date_bar = br.find_by_xpath('//*[contains(@class, "meta_date_wrapper")]')
# find the check in calendar span:
cin_btn = date_bar.find_by_xpath('span[contains(@class, "meta_date_field check_in")]/span')[0]
# now click the check_in span to activate it
cin_btn.click()
# select the right calendar div (next month)
rightcal = br.find_by_xpath('//div[contains(@class, "month")]')[1]
# now select the third Friday of next month as the check in date
fri_btn = rightcal.find_by_xpath('table/tbody/tr[3]/td[6]/div')
# and click it
fri_btn.click()
# now choose the next day (saturday) as the check out date
cout_btn = date_bar.find_by_xpath('span[contains(@class, "meta_date_field check_out")]/span')[0]
cout_btn.click()
leftcal = br.find_by_xpath('//div[contains(@class, "month")]')[0]
sat_btn = leftcal.find_by_xpath('table/tbody/tr[3]/td[7]/div')
sat_btn.click()
print('Dates selected.')
# wait a few seconds for ta to retrieve prices
time.sleep(5)
# get the city and state info
loclist = br.find_by_xpath('//*[contains(@id, "BREADCRUMBS")]')
locstring = loclist.text.split(u'\u203a')
hotel_city = city = locstring[2].lower()
hotel_state = re.findall('\w+ \(([A-Z][A-Z])\)', locstring[1])[0].lower()
# create a pandas dataframe that will be used for writing
# the results to the DB:
columns = ['hotel_id',
'hotel_url',
'hotel_img_url',
'hotel_name',
'hotel_address',
'hotel_city',
'hotel_state',
'hotel_rating',
'hotel_latitude',
'hotel_longitude',
'hotel_price',
'business_id',
'review_count',
'dog_review_count',
]
bigdf = pd.DataFrame(columns=columns)
# create some lists to fill w. the results from each page
hotel_names = []
links = []
img_url = []
hotel_price = []
business_id = []
print('starting scraper loop.')
while more_pages and page <= max_pages:
print('*'*75)
print('Now scraping page {} of {} of the hotel results'.format(page, max_pages))
print('*'*75)
# get all the review divs
print('waiting a few seconds before scraping...')
time.sleep(np.random.uniform(8, 20))
listing_div = br.find_by_xpath('//*[contains(@class, "hotels_lf_condensed")]')
xsts1 = br.is_element_present_by_xpath('//*[contains(@class, "photo_booking")]', wait_time=1)
xsts2 = br.is_element_present_by_xpath('//*[contains(@class, "property_details")]', wait_time=1)
xsts3 = br.is_element_present_by_xpath('//*[contains(@class, "prw_rup")]/div/div/div/div[@class="headerContents"]/div[contains(@class, "price")]', wait_time=1)
while len(listing_div) < 1 or not xsts1 or not xsts2 or not xsts3:
print('now waiting for DOIs to return')
time.sleep(5)
listing_div = br.find_by_xpath('//*[contains(@class, "hotels_lf_condensed")]')
xsts1 = br.is_element_present_by_xpath('//*[contains(@class, "photo_booking")]', wait_time=1)
xsts2 = br.is_element_present_by_xpath('//*[contains(@class, "property_details")]', wait_time=1)
xsts3 = br.is_element_present_by_xpath('//*[contains(@class, "prw_rup")]/div/div/div/div[@class="headerContents"]/div[contains(@class, "price")]', wait_time=1)
print('# of listings: {}'.format(len(listing_div)))
print('photo_booking exists: {}'.format(xsts1))
print('property_details exists: {}'.format(xsts2))
print('prw_up exists: {}'.format(xsts3))
print('Number of hotel listings on this page: {}'.format(len(listing_div)))
df = pd.DataFrame(columns=columns)
for listing in listing_div:
try:
biz_id = re.findall('hotel_(\d+)', listing['id'])
if len(biz_id) > 0:
biz_id = biz_id[0]
else:
biz_id = None
print('business_id: {}'.format(biz_id))
business_id.append(biz_id)
except:
print('!'*80)
print('biz_id DOES NOT EXIST!')
print('!'*80)
business_id.append(None)
try:
prop = listing.find_by_xpath('div/div/div/div[contains(@class, "property_details")]')
except:
print('!'*80)
print('prop DIV DOES NOT EXIST!')
print('!'*80)
try:
title = prop.find_by_xpath('div/div[@class="listing_title"]')
print(title.text)
hotel_names.append(title.text)
except:
print('!'*80)
print('TITLE DIV DOES NOT EXIST!')
print('!'*80)
hotel_names.append(None)
try:
hotel_link = title.find_by_xpath('a')['href']
print(hotel_link)
links.append(hotel_link)
except:
print('!'*80)
print('hotel_link DOES NOT EXIST!')
print('!'*80)
links.append(None)
try:
hotel_img = prop.find_by_xpath('div[@class="photo_booking"]/div/div/a/img')['src']
print('Hotel img URL: {}'.format(hotel_img))
img_url.append(hotel_img)
except:
print('!'*80)
print('hotel_img DIV DOES NOT EXIST!')
print('!'*80)
img_url.append(None)
try:
price_text = prop.find_by_xpath('div[contains(@class, "prw_rup")]/div/div/div/div[@class="headerContents"]/div[contains(@class, "price")]').text
price = re.findall('(\d+)', price_text)[0]
print('Price: ${}'.format(price))
hotel_price.append(price)
except:
print('!'*80)
print('price DIV DOES NOT EXIST!')
print('!'*80)
hotel_price.append(None)
print('*'*50)
if len(hotel_names) > 0:
print('len of hotel_names: {}'.format(len(hotel_names)))
print('len of hotel_price: {}'.format(len(hotel_price)))
print('len of img_url: {}'.format(len(img_url)))
print('len of business_id: {}'.format(len(business_id)))
print('len of hotel_city: {}'.format(len(hotel_city)))
print('len of hotel_state: {}'.format(len(hotel_state)))
df['hotel_name'] = hotel_names
df['hotel_price'] = hotel_price
df['hotel_img_url'] = img_url
df['hotel_url'] = links
df['business_id'] = business_id
df['hotel_city'] = hotel_city
df['hotel_state'] = hotel_state
bigdf = bigdf.append(df)
# update the page number
page += 1
# if more pages are desired, look for a "next" button
if page <= max_pages:
nxt_btn = br.find_by_xpath('//div[contains(@class, "deckTools")]/div[contains(@class, "unified")]/a[contains(@class, "next")]')
# if there is a next button, click it
# else exit the while loop
if len(nxt_btn) > 0:
nxt_btn.click()
else:
more_pages = False
if write_to_db:
engine = cadb.connect_aws_db(write_unicode=True)
bigdf = remove_ad_hotels(bigdf)
remove_duplicate_hotels(bigdf, city, engine)
bigdf.to_sql('ta_hotels', engine, if_exists='append', index=False)
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='argparse object.')
parser.add_argument(
'--city_url',
help='The url of the city to scrape.',
nargs='?', default='')
parser.add_argument(
'-c', '--city',
help='The url of the city to scrape.',
nargs='?', default='')
parser.add_argument(
'-s', '--state',
help='This name of the state to scrape.',
nargs='?', default='')
parser.add_argument(
'-w', '--write_to_db',
help='Set if you want to write the results to the DB.',
default=False, action='store_true')
if len(sys.argv) > 7:
print('use the command')
print('python splinter_scrape_bf.py city state')
print('For example:')
print('python splinter_scrape_bf.py http://www.tripadvisor.com/Hotels-g31310-Phoenix_Arizona-Hotels.html')
sys.exit(2)
args = parser.parse_args()
splinter_scrape_ta_hotels(city_url=args.city_url, city=args.city, state=args.state, write_to_db=args.write_to_db)
| [
"pandas.read_sql_query",
"numpy.int64",
"argparse.ArgumentParser",
"splinter.browser.Browser",
"connect_aws_db.connect_aws_db",
"time.sleep",
"numpy.random.uniform",
"sys.exit",
"pandas.DataFrame",
"re.findall"
] | [((3479, 3516), 'numpy.int64', 'np.int64', (["bigdf['business_id'].values"], {}), "(bigdf['business_id'].values)\n", (3487, 3516), True, 'import numpy as np\n'), ((4060, 4069), 'splinter.browser.Browser', 'Browser', ([], {}), '()\n', (4067, 4069), False, 'from splinter.browser import Browser\n'), ((5832, 5845), 'time.sleep', 'time.sleep', (['(5)'], {}), '(5)\n', (5842, 5845), False, 'import time\n'), ((6673, 6702), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': 'columns'}), '(columns=columns)\n', (6685, 6702), True, 'import pandas as pd\n'), ((12578, 12633), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""argparse object."""'}), "(description='argparse object.')\n", (12601, 12633), False, 'import argparse\n'), ((250, 261), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (258, 261), False, 'import sys\n'), ((8643, 8672), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': 'columns'}), '(columns=columns)\n', (8655, 8672), True, 'import pandas as pd\n'), ((12328, 12367), 'connect_aws_db.connect_aws_db', 'cadb.connect_aws_db', ([], {'write_unicode': '(True)'}), '(write_unicode=True)\n', (12347, 12367), True, 'import connect_aws_db as cadb\n'), ((13469, 13480), 'sys.exit', 'sys.exit', (['(2)'], {}), '(2)\n', (13477, 13480), False, 'import sys\n'), ((3084, 3123), 'connect_aws_db.connect_aws_db', 'cadb.connect_aws_db', ([], {'write_unicode': '(True)'}), '(write_unicode=True)\n', (3103, 3123), True, 'import connect_aws_db as cadb\n'), ((7185, 7209), 'numpy.random.uniform', 'np.random.uniform', (['(8)', '(20)'], {}), '(8, 20)\n', (7202, 7209), True, 'import numpy as np\n'), ((7812, 7825), 'time.sleep', 'time.sleep', (['(5)'], {}), '(5)\n', (7822, 7825), False, 'import time\n'), ((6059, 6110), 're.findall', 're.findall', (['"""\\\\w+ \\\\(([A-Z][A-Z])\\\\)"""', 'locstring[1]'], {}), "('\\\\w+ \\\\(([A-Z][A-Z])\\\\)', locstring[1])\n", (6069, 6110), False, 'import re\n'), ((8752, 8793), 're.findall', 're.findall', (['"""hotel_(\\\\d+)"""', "listing['id']"], {}), "('hotel_(\\\\d+)', listing['id'])\n", (8762, 8793), False, 'import re\n'), ((3016, 3046), 'pandas.read_sql_query', 'pd.read_sql_query', (['cmd', 'engine'], {}), '(cmd, engine)\n', (3033, 3046), True, 'import pandas as pd\n'), ((10703, 10735), 're.findall', 're.findall', (['"""(\\\\d+)"""', 'price_text'], {}), "('(\\\\d+)', price_text)\n", (10713, 10735), False, 'import re\n'), ((3175, 3205), 'pandas.read_sql_query', 'pd.read_sql_query', (['cmd', 'engine'], {}), '(cmd, engine)\n', (3192, 3205), True, 'import pandas as pd\n')] |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib
matplotlib.rc('font', family='FreeSans', size=16)
data = []
with open('weak_scaling.txt', 'r') as file:
for line in file:
if 'Average' in line:
_line = line.split(' ')
data.append(float(_line[-1]))
if 'standard' in line:
_line = line.split(' ')
data.append(float(_line[-1]))
data = np.asarray(data).reshape((-1, 6, 2))
nprocs = np.asarray([1, 4, 9, 18, 36, 72])
nparts = np.asarray([36, 144, 324, 648, 1296, 2592])
flock_weak_numba = data[0,:,0]
flock_weak_numba_par = data[1,:,0]
flock_weak_joblib = data[2,:,0]
flock_weak_ray = data[3,:,0]
predator_weak_numba = data[4,:,0]
predator_weak_numba_par = data[5,:,0]
predator_weak_joblib = data[6,:,0]
predator_weak_ray = data[7,:,0]
fig = plt.figure(figsize=(5,3.5))
ax = fig.gca()
for nproc, npart in zip(nprocs, nparts):
ax.text(nproc, 0.5, 'N = %d' % npart, rotation=270)
ax.axvline(x=nproc, linestyle='--', color='k')
ax.plot(nprocs, flock_weak_numba, '-o', label='flock numba')
ax.plot(nprocs, flock_weak_numba_par, '-*', label='flock numba par')
ax.plot(nprocs, flock_weak_joblib, '-+', label='flock joblib')
ax.plot(nprocs, flock_weak_ray, '-^', label='flock ray')
ax.set_xlabel('Number of Processors')
ax.set_ylabel('Running Time (s)')
ax.set_xscale('log')
ax.set_yscale('log')
plt.legend()
plt.tight_layout()
plt.savefig('figures/'+'flock_weak_scale.png', bbox_inches='tight')
fig = plt.figure(figsize=(5,3.5))
ax = fig.gca()
for nproc, npart in zip(nprocs, nparts):
ax.text(nproc, 0.5, 'N = %d' % npart, rotation=270)
ax.axvline(x=nproc, linestyle='--', color='k')
ax.plot(nprocs, predator_weak_numba, '-o', label='predator numba')
ax.plot(nprocs, predator_weak_numba_par, '-*', label='predator numba par')
ax.plot(nprocs, predator_weak_joblib, '-+', label='predator joblib')
ax.plot(nprocs, predator_weak_ray, '-^', label='predator ray')
ax.set_xlabel('Number of Processors')
ax.set_ylabel('Running Time (s)')
ax.set_xscale('log')
ax.set_yscale('log')
plt.legend()
plt.tight_layout()
plt.savefig('figures/'+'predator_weak_scale.png', bbox_inches='tight')
flock_strong_numba = np.asarray([flock_weak_numba[-1] for _ in range(len(nprocs))])
predator_strong_numba = np.asarray([predator_weak_numba[-1] for _ in range(len(nprocs))])
data = []
with open('strong_scaling.txt', 'r') as file:
for line in file:
if 'Average' in line:
_line = line.split(' ')
data.append(float(_line[-1]))
if 'standard' in line:
_line = line.split(' ')
data.append(float(_line[-1]))
data = np.asarray(data).reshape((-1, 3, 2))
flock_strong = data[::2, ...].copy()
predator_strong = data[1::2, ...].copy()
nprocs = np.asarray([1, 4, 9, 18, 36, 72])
npart = 2592
flock_strong_numba_par = flock_strong[:, 0, 0]
flock_strong_joblib = flock_strong[:, 1, 0]
flock_strong_ray = flock_strong[:, 2, 0]
predator_strong_numba_par = predator_strong[:, 0, 0]
predator_strong_joblib = predator_strong[:, 1, 0]
predator_strong_ray = predator_strong[:, 2, 0]
fig = plt.figure(figsize=(5,3.5))
ax = fig.gca()
ax.plot(nprocs, flock_strong_numba, '-o', label='flock numba')
ax.plot(nprocs, flock_strong_numba_par, '-*', label='flock numba par')
ax.plot(nprocs, flock_strong_joblib, '-+', label='flock joblib')
ax.plot(nprocs, flock_strong_ray, '-^', label='flock ray')
ax.set_xlabel('Number of Processors')
ax.set_ylabel('Running Time (s)')
ax.set_xscale('log')
ax.set_yscale('log')
plt.legend()
plt.tight_layout()
plt.savefig('figures/'+'flock_strong_scale.png', bbox_inches='tight')
fig = plt.figure(figsize=(5,3.5))
ax = fig.gca()
ax.plot(nprocs, predator_strong_numba, '-o', label='predator numba')
ax.plot(nprocs, predator_strong_numba_par, '-*', label='predator numba par')
ax.plot(nprocs, predator_strong_joblib, '-+', label='predator joblib')
ax.plot(nprocs, predator_strong_ray, '-^', label='predator ray')
ax.set_xlabel('Number of Processors')
ax.set_ylabel('Running Time (s)')
ax.set_xscale('log')
ax.set_yscale('log')
plt.legend()
plt.tight_layout()
plt.savefig('figures/'+'predator_strong_scale.png', bbox_inches='tight')
| [
"matplotlib.pyplot.savefig",
"numpy.asarray",
"matplotlib.pyplot.figure",
"matplotlib.rc",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.legend"
] | [((80, 129), 'matplotlib.rc', 'matplotlib.rc', (['"""font"""'], {'family': '"""FreeSans"""', 'size': '(16)'}), "('font', family='FreeSans', size=16)\n", (93, 129), False, 'import matplotlib\n'), ((478, 511), 'numpy.asarray', 'np.asarray', (['[1, 4, 9, 18, 36, 72]'], {}), '([1, 4, 9, 18, 36, 72])\n', (488, 511), True, 'import numpy as np\n'), ((521, 564), 'numpy.asarray', 'np.asarray', (['[36, 144, 324, 648, 1296, 2592]'], {}), '([36, 144, 324, 648, 1296, 2592])\n', (531, 564), True, 'import numpy as np\n'), ((838, 866), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(5, 3.5)'}), '(figsize=(5, 3.5))\n', (848, 866), True, 'import matplotlib.pyplot as plt\n'), ((1393, 1405), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (1403, 1405), True, 'import matplotlib.pyplot as plt\n'), ((1406, 1424), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (1422, 1424), True, 'import matplotlib.pyplot as plt\n'), ((1425, 1494), 'matplotlib.pyplot.savefig', 'plt.savefig', (["('figures/' + 'flock_weak_scale.png')"], {'bbox_inches': '"""tight"""'}), "('figures/' + 'flock_weak_scale.png', bbox_inches='tight')\n", (1436, 1494), True, 'import matplotlib.pyplot as plt\n'), ((1500, 1528), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(5, 3.5)'}), '(figsize=(5, 3.5))\n', (1510, 1528), True, 'import matplotlib.pyplot as plt\n'), ((2079, 2091), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (2089, 2091), True, 'import matplotlib.pyplot as plt\n'), ((2092, 2110), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (2108, 2110), True, 'import matplotlib.pyplot as plt\n'), ((2111, 2183), 'matplotlib.pyplot.savefig', 'plt.savefig', (["('figures/' + 'predator_weak_scale.png')"], {'bbox_inches': '"""tight"""'}), "('figures/' + 'predator_weak_scale.png', bbox_inches='tight')\n", (2122, 2183), True, 'import matplotlib.pyplot as plt\n'), ((2785, 2818), 'numpy.asarray', 'np.asarray', (['[1, 4, 9, 18, 36, 72]'], {}), '([1, 4, 9, 18, 36, 72])\n', (2795, 2818), True, 'import numpy as np\n'), ((3121, 3149), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(5, 3.5)'}), '(figsize=(5, 3.5))\n', (3131, 3149), True, 'import matplotlib.pyplot as plt\n'), ((3536, 3548), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (3546, 3548), True, 'import matplotlib.pyplot as plt\n'), ((3549, 3567), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (3565, 3567), True, 'import matplotlib.pyplot as plt\n'), ((3568, 3639), 'matplotlib.pyplot.savefig', 'plt.savefig', (["('figures/' + 'flock_strong_scale.png')"], {'bbox_inches': '"""tight"""'}), "('figures/' + 'flock_strong_scale.png', bbox_inches='tight')\n", (3579, 3639), True, 'import matplotlib.pyplot as plt\n'), ((3645, 3673), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(5, 3.5)'}), '(figsize=(5, 3.5))\n', (3655, 3673), True, 'import matplotlib.pyplot as plt\n'), ((4084, 4096), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (4094, 4096), True, 'import matplotlib.pyplot as plt\n'), ((4097, 4115), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (4113, 4115), True, 'import matplotlib.pyplot as plt\n'), ((4116, 4190), 'matplotlib.pyplot.savefig', 'plt.savefig', (["('figures/' + 'predator_strong_scale.png')"], {'bbox_inches': '"""tight"""'}), "('figures/' + 'predator_strong_scale.png', bbox_inches='tight')\n", (4127, 4190), True, 'import matplotlib.pyplot as plt\n'), ((431, 447), 'numpy.asarray', 'np.asarray', (['data'], {}), '(data)\n', (441, 447), True, 'import numpy as np\n'), ((2659, 2675), 'numpy.asarray', 'np.asarray', (['data'], {}), '(data)\n', (2669, 2675), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 7 09:58:55 2021
@author: emari
"""
import numpy as np
import pandas as pd
class node():
def __init__(self):
self.parent_node = ""
self.child_connections = [np.array([],dtype=object),np.array([],dtype=object),np.array([],dtype=object),np.array([],dtype=object),np.array([],dtype=object)]
self.username = ""
self.connection_type = ""
self.bio = ""
self.captions = []
self.total_likes = 0
self.total_followers = 0
self.total_following = 0
self.post_date = ""
self.root_post_url = ""
self.profile_img_url = ""
#This is selector for profile image
##react-root > section > main > div > header > div > div > span > img
def printNode(self):
print("parent node: ",self.parent_node)
print("username: ",self.username)
print("connection_type: ",self.connection_type)
print("total_likes: ",self.total_likes)
print("total_followers: ",self.total_followers)
print("total_following: ",self.total_following)
class nodeClassifier():
def __init__(self,output_location):
self.node_list = []
self.output_location = output_location
self.node_df = pd.DataFrame(columns=["parent_node","username","connection_type","bio","captions","total_likes","total_followers","total_following","profile_img_url","root_post_url"])
def addNode(self,node):#(self,parent_node,username,connection_type):
#nodeBuffer = [parent_node,username,connection_type]
nodeBuffer = [node.parent_node,node.username,node.connection_type,node.bio,'foo',node.total_likes,node.total_followers,node.total_following,node.profile_img_url,node.root_post_url]
self.node_df = self.node_df.append(pd.Series(nodeBuffer,index=self.node_df.columns),ignore_index=True)
self.node_list.append(node)
#self.exportNode(node)
#print(self.node_df)
def printNetwork(self):
print(self.node_df)
#assume that the parent_node has already been added
#add the child node to the db
#find the parent node
#create the connection from the "parent" to the username
def exportNetwork(self):
self.node_df.to_csv(self.output_location+"\output.csv",index=False) | [
"pandas.DataFrame",
"numpy.array",
"pandas.Series"
] | [((1286, 1470), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['parent_node', 'username', 'connection_type', 'bio', 'captions',\n 'total_likes', 'total_followers', 'total_following', 'profile_img_url',\n 'root_post_url']"}), "(columns=['parent_node', 'username', 'connection_type', 'bio',\n 'captions', 'total_likes', 'total_followers', 'total_following',\n 'profile_img_url', 'root_post_url'])\n", (1298, 1470), True, 'import pandas as pd\n'), ((227, 253), 'numpy.array', 'np.array', (['[]'], {'dtype': 'object'}), '([], dtype=object)\n', (235, 253), True, 'import numpy as np\n'), ((253, 279), 'numpy.array', 'np.array', (['[]'], {'dtype': 'object'}), '([], dtype=object)\n', (261, 279), True, 'import numpy as np\n'), ((279, 305), 'numpy.array', 'np.array', (['[]'], {'dtype': 'object'}), '([], dtype=object)\n', (287, 305), True, 'import numpy as np\n'), ((305, 331), 'numpy.array', 'np.array', (['[]'], {'dtype': 'object'}), '([], dtype=object)\n', (313, 331), True, 'import numpy as np\n'), ((331, 357), 'numpy.array', 'np.array', (['[]'], {'dtype': 'object'}), '([], dtype=object)\n', (339, 357), True, 'import numpy as np\n'), ((1831, 1880), 'pandas.Series', 'pd.Series', (['nodeBuffer'], {'index': 'self.node_df.columns'}), '(nodeBuffer, index=self.node_df.columns)\n', (1840, 1880), True, 'import pandas as pd\n')] |
"""
marchenko_pastur.py
--------------
Graph reconstruction algorithm based on <NAME>., & <NAME>. (1967).
Distribution of eigenvalues for some sets of random matrices. Matematicheskii
Sbornik, 114(4), 507-536.
author: <NAME>
Submitted as part of the 2019 NetSI Collabathon.
"""
from .base import BaseReconstructor
import numpy as np
import networkx as nx
from ..utilities import create_graph, threshold
class MarchenkoPastur(BaseReconstructor):
def fit(self, TS, remove_largest=False, metric_distance=False, threshold_type='range', **kwargs):
"""Create a correlation-based graph using Marchenko-Pastur law to remove noise.
A signed graph is built by constructing a projection of the empirical correlation
matrix generated from the time series data after having removed *noisy* components.
This method combines the results presented in [1],[2], and [3].
Params
------
TS (np.ndarray): $N \\times L$ array consisting of $L$ observations
from $N$ sensors.
remove_largest (bool), optional: If ``False``, all the eigenvectors
associated to the significant eigenvalues will be used to reconstruct
the de-noised empirical correlation matrix. If ``True``, the eigenvector
associated to the largest eigenvalue (normally known as the ``market`` mode, [2])
is going to be excluded from the recontruction step.
metric_distance (bool), optional: If ``False``, a signed graph is obtained.
The weights associated to the edges represent the de-noised correlation
coefficient $\\rho_{i,j}$ between time series $i$ and $j$.
If ``True``, the correlation is transformed by defining a metric distance
between each pair of nodes where $d_{i,j} = \\sqrt{2(1-\\rho_{i,j})}$ as
proposed in [3].
threshold_type (str): Which thresholding function to use on the matrix of
weights. See `netrd.utilities.threshold.py` for documentation. Pass additional
arguments to the thresholder using `**kwargs`.
Returns
-------
G (nx.Graph): A reconstructed graph with $N$ nodes.
Example
--------
import numpy as np
import networkx as nx
from matplotlib import pyplot as plt
from netrd.reconstruction import MarchenkoPastur
N = 250
T = 300
M = np.random.normal(size=(N,T))
print('Create correlated time series')
market_mode = 0.4*np.random.normal(size=(1,T))
M += market_mode
sector_modes = {d: 0.5*np.random.normal(size=(1,T)) for d in range(5)}
for sector_mode, vals in sector_modes.items():
M[sector_mode*50:(sector_mode+1)*50,:] += vals
print('Network reconstruction step')
mp_net = MarchenkoPastur()
G = mp_net.fit(M, only_positive=True)
G_no_market = mp_net.fit(M, only_positive=True, remove_largest=True)
print('Observed noisy correlation')
C = np.corrcoef(M)
C[C<0] = 0 # remove negative values
np.fill_diagonal(C,0) # remove self-loops
G_noisy = nx.from_numpy_array(C) # create graph
print('Plot observed noisy correlation graph')
fig, ax = plt.subplots()
nx.draw(G_noisy, ax=ax)
print('Plot reconstructed correlation graph')
fig, ax = plt.subplots()
nx.draw(G, ax=ax)
print('Plot reconstructed correlation graph without market mode')
fig, ax = plt.subplots()
nx.draw(G_no_market, ax=ax)
References
----------
.. [1] <NAME>., & <NAME>. (1967). Distribution of eigenvalues for
some sets of random matrices. Matematicheskii Sbornik, 114(4), 507-536.
http://www.mathnet.ru/links/a8d2a49dec161f50c944d9a96298c35a/sm4101.pdf
.. [2] <NAME>., <NAME>., <NAME>., & <NAME>. (1999). Noise dressing
of financial correlation matrices. Physical review letters, 83(7), 1467.
https://journals.aps.org/prl/abstract/10.1103/PhysRevLett.83.1467
.. [3] <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., & Mantegna,
<NAME>. (2004). Networks of equities in financial markets. The European Physical Journal
B, 38(2), 363-371.
https://link.springer.com/article/10.1140/epjb/e2004-00129-6
"""
N, L = TS.shape
if N>L:
raise ValueError("L must be greater or equal than N.")
Q = L/N
C = np.corrcoef(TS) # Empirical correlation matrix
w, v = np.linalg.eigh(C) # Spectral decomposition of C
w_min = (1+1/Q-2*np.sqrt(1/Q))
w_max = (1+1/Q+2*np.sqrt(1/Q))
selected = (w<w_min)|(w>w_max)
if selected.sum()==0:
G = nx.empty_graph(n=N)
self.results['graph'] = G
return G
if remove_largest:
selected[-1] = False
w_signal = w[selected]
v_signal = v[:,selected]
C_signal = v_signal.dot(np.diag(w_signal)).dot(v_signal.T)
if metric_distance:
C_signal = np.sqrt(2*(1-C_signal))
self.results['matrix'] = C_signal
#threshold signal matrix
self.results['thresholded_matrix'] = threshold(C_signal, threshold_type, **kwargs)
G = create_graph(self.results['thresholded_matrix'])
self.results['graph'] = G
return G
| [
"numpy.sqrt",
"numpy.corrcoef",
"networkx.empty_graph",
"numpy.diag",
"numpy.linalg.eigh"
] | [((4505, 4520), 'numpy.corrcoef', 'np.corrcoef', (['TS'], {}), '(TS)\n', (4516, 4520), True, 'import numpy as np\n'), ((4568, 4585), 'numpy.linalg.eigh', 'np.linalg.eigh', (['C'], {}), '(C)\n', (4582, 4585), True, 'import numpy as np\n'), ((4782, 4801), 'networkx.empty_graph', 'nx.empty_graph', ([], {'n': 'N'}), '(n=N)\n', (4796, 4801), True, 'import networkx as nx\n'), ((5107, 5134), 'numpy.sqrt', 'np.sqrt', (['(2 * (1 - C_signal))'], {}), '(2 * (1 - C_signal))\n', (5114, 5134), True, 'import numpy as np\n'), ((4642, 4656), 'numpy.sqrt', 'np.sqrt', (['(1 / Q)'], {}), '(1 / Q)\n', (4649, 4656), True, 'import numpy as np\n'), ((4681, 4695), 'numpy.sqrt', 'np.sqrt', (['(1 / Q)'], {}), '(1 / Q)\n', (4688, 4695), True, 'import numpy as np\n'), ((5020, 5037), 'numpy.diag', 'np.diag', (['w_signal'], {}), '(w_signal)\n', (5027, 5037), True, 'import numpy as np\n')] |
import numpy as np
from scipy import special as special
from scipy.special import logsumexp
from mimo.abstraction import MixtureDistribution
from mimo.abstraction import BayesianMixtureDistribution
from mimo.distributions.bayesian import CategoricalWithDirichlet
from mimo.distributions.bayesian import CategoricalWithStickBreaking
from mimo.util.decorate import pass_obs_arg, pass_obs_and_labels_arg
from mimo.util.stats import sample_discrete_from_log
from mimo.util.data import batches
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from tqdm import tqdm
from pathos.helpers import mp
class MixtureOfGaussians(MixtureDistribution):
"""
This class is for mixtures of Gaussians.
"""
def __init__(self, gating, components):
assert len(components) > 0
assert len(components) == gating.K
self.gating = gating
self.components = components
@property
def params(self):
raise NotImplementedError
@property
def nb_params(self):
return sum(c.nb_params for c in self.components) + self.gating.nb_params
@property
def size(self):
return len(self.components)
@property
def dim(self):
return self.components[0].dim
def rvs(self, size=1):
z = self.gating.rvs(size)
counts = np.bincount(z, minlength=self.size)
obs = np.zeros((size, self.dim))
for idx, (c, count) in enumerate(zip(self.components, counts)):
obs[z == idx, ...] = c.rvs(count)
perm = np.random.permutation(size)
obs, z = obs[perm], z[perm]
return obs, z
def log_likelihood(self, obs):
assert isinstance(obs, (np.ndarray, list))
if isinstance(obs, list):
return [self.log_likelihood(_obs) for _obs in obs]
else:
scores = self.log_scores(obs)
return logsumexp(scores[~np.isnan(obs).any(axis=1)], axis=1)
# Expectation-Maximization
def log_scores(self, obs):
N, K = obs.shape[0], self.size
# update, see Eq. 10.67 in Bishop
component_scores = np.empty((N, K))
for idx, c in enumerate(self.components):
component_scores[:, idx] = c.log_likelihood(obs)
component_scores = np.nan_to_num(component_scores, copy=False)
gating_scores = self.gating.log_likelihood(np.arange(K))
score = gating_scores + component_scores
return score
def scores(self, obs):
logr = self.log_scores(obs)
score = np.exp(logr - np.max(logr, axis=1, keepdims=True))
score /= np.sum(score, axis=1, keepdims=True)
return score
def max_likelihood(self, obs, maxiter=1, progprint=True):
current = mp.current_process()
if len(current._identity) > 0:
pos = current._identity[0] - 1
else:
pos = 0
obs = obs if isinstance(obs, list) else [obs]
elbo = []
with tqdm(total=maxiter, desc=f'EM #{pos + 1}',
position=pos, disable=not progprint) as pbar:
for _ in range(maxiter):
# Expectation step
scores = [self.scores(_obs) for _obs in obs]
# Maximization step
for idx, c in enumerate(self.components):
c.max_likelihood([_obs for _obs in obs],
[_score[:, idx] for _score in scores])
# mixture weights
self.gating.max_likelihood(None, scores)
elbo.append(np.sum(self.log_likelihood(obs)))
pbar.update(1)
return elbo
def plot(self, obs=None, color=None, legend=False, alpha=None):
obs = obs if isinstance(obs, list) else [obs]
import matplotlib.pyplot as plt
from matplotlib import cm
artists = []
# get colors
cmap = cm.get_cmap('RdBu')
if color is None:
label_colors = dict((idx, cmap(v)) for idx, v in
enumerate(np.linspace(0, 1, self.size, endpoint=True)))
else:
label_colors = dict((idx, color) for idx in range(self.size))
labels = []
for _obs in obs:
labels.append(np.argmax(self.scores(_obs), axis=1))
# plot data scatter
for _obs, _label in zip(obs, labels):
colorseq = [label_colors[l] for l in _label]
artists.append(plt.scatter(_obs[:, 0], _obs[:, 1], c=colorseq, marker='+'))
# plot parameters
axis = plt.axis()
for label, (c, w) in enumerate(zip(self.components, self.gating.probs)):
artists.extend(c.plot(color=label_colors[label], label='%d' % label,
alpha=min(0.25, 1. - (1. - w) ** 2) / 0.25
if alpha is None else alpha))
plt.axis(axis)
# add legend
if legend and color is None:
plt.legend([plt.Rectangle((0, 0), 1, 1, fc=c)
for i, c in label_colors.items() if i in self.used_labels],
[i for i in label_colors if i in self.used_labels], loc='best', ncol=2)
plt.show()
return artists
class BayesianMixtureOfGaussians(BayesianMixtureDistribution):
"""
This class is for a Bayesian mixtures of Gaussians.
"""
def __init__(self, gating, components):
assert len(components) > 0
self.gating = gating
self.components = components
self.likelihood = MixtureOfGaussians(gating=self.gating.likelihood,
components=[c.likelihood for c in self.components])
self.obs = []
self.labels = []
self.whitend = False
self.transform = None
@property
def used_labels(self):
assert self.has_data()
label_usages = sum(np.bincount(_label, minlength=self.likelihood.size)
for _label in self.labels)
used_labels, = np.where(label_usages > 0)
return used_labels
def add_data(self, obs, whiten=False,
transform_type='PCA',
labels_from_prior=False):
obs = obs if isinstance(obs, list) else [obs]
if whiten:
self.whitend = True
data = np.vstack([_obs for _obs in obs])
if transform_type == 'PCA':
self.transform = PCA(n_components=data.shape[-1], whiten=True)
elif transform_type == 'Standard':
self.transform = StandardScaler()
elif transform_type == 'MinMax':
self.transform = MinMaxScaler((-1., 1.))
else:
raise NotImplementedError
self.transform.fit(data)
for _obs in obs:
self.obs.append(self.transform.transform(_obs))
else:
self.obs = obs
if labels_from_prior:
for _obs in self.obs:
self.labels.append(self.likelihood.gating.rvs(len(_obs)))
else:
self.labels = self._resample_labels(self.obs)
def clear_data(self):
self.obs.clear()
self.labels.clear()
def clear_transform(self):
self.whitend = False
self.transform = None
def has_data(self):
return len(self.obs) > 0
# Expectation-Maximization
@pass_obs_arg
def max_aposteriori(self, obs, maxiter=1, progprint=True):
current = mp.current_process()
if len(current._identity) > 0:
pos = current._identity[0] - 1
else:
pos = 0
obs = obs if isinstance(obs, list) else [obs]
with tqdm(total=maxiter, desc=f'MAP #{pos + 1}',
position=pos, disable=not progprint) as pbar:
for i in range(maxiter):
# Expectation step
scores = []
for _obs in obs:
scores.append(self.likelihood.scores(_obs))
# Maximization step
for idx, c in enumerate(self.components):
c.max_aposteriori([_obs for _obs in obs],
[_score[:, idx] for _score in scores])
# mixture weights
self.gating.max_aposteriori(None, scores)
pbar.update(1)
# Gibbs sampling
@pass_obs_and_labels_arg
def resample(self, obs=None, labels=None,
maxiter=1, progprint=True):
current = mp.current_process()
if len(current._identity) > 0:
pos = current._identity[0] - 1
else:
pos = 0
with tqdm(total=maxiter, desc=f'Gibbs #{pos + 1}',
position=pos, disable=not progprint) as pbar:
for _ in range(maxiter):
self._resample_components(obs, labels)
self._resample_gating(labels)
labels = self._resample_labels(obs)
if self.has_data():
self.labels = labels
pbar.update(1)
def _resample_components(self, obs, labels):
for idx, c in enumerate(self.components):
c.resample(data=[_obs[_label == idx]
for _obs, _label in zip(obs, labels)])
def _resample_gating(self, labels):
self.gating.resample([_label for _label in labels])
def _resample_labels(self, obs):
labels = []
for _obs in obs:
score = self.likelihood.log_scores(_obs)
labels.append(sample_discrete_from_log(score, axis=1))
return labels
# Mean Field
def expected_scores(self, obs):
N, K = obs.shape[0], self.likelihood.size
# update, see Eq. 10.67 in Bishop
component_scores = np.empty((N, K))
for idx, c in enumerate(self.components):
component_scores[:, idx] = c.posterior.expected_log_likelihood(obs)
component_scores = np.nan_to_num(component_scores, copy=False)
if isinstance(self.gating, CategoricalWithDirichlet):
gating_scores = self.gating.posterior.expected_statistics()
elif isinstance(self.gating, CategoricalWithStickBreaking):
E_log_stick, E_log_rest = self.gating.posterior.expected_statistics()
gating_scores = E_log_stick + np.hstack((0, np.cumsum(E_log_rest)[:-1]))
else:
raise NotImplementedError
logr = gating_scores + component_scores
r = np.exp(logr - np.max(logr, axis=1, keepdims=True))
r /= np.sum(r, axis=1, keepdims=True)
return r
def meanfield_coordinate_descent(self, tol=1e-2, maxiter=250, progprint=True):
elbo = []
current = mp.current_process()
if len(current._identity) > 0:
pos = current._identity[0] - 1
else:
pos = 0
with tqdm(total=maxiter, desc=f'VI #{pos + 1}',
position=pos, disable=not progprint) as pbar:
for i in range(maxiter):
elbo.append(self.meanfield_update())
if elbo[-1] is not None and len(elbo) > 1:
if elbo[-1] < elbo[-2]:
print('WARNING: ELBO should always increase')
return elbo
if (elbo[-1] - elbo[-2]) < tol:
return elbo
pbar.update(1)
# print('WARNING: meanfield_coordinate_descent hit maxiter of %d' % maxiter)
return elbo
@pass_obs_arg
def meanfield_update(self, obs=None):
scores, labels = self._meanfield_update_sweep(obs)
if self.has_data():
self.labels = labels
return self.variational_lowerbound(obs, scores)
def _meanfield_update_sweep(self, obs):
scores, z = self._meanfield_update_labels(obs)
self._meanfield_update_parameters(obs, scores)
return scores, z
def _meanfield_update_labels(self, obs):
scores, labels = [], []
for _obs in obs:
scores.append(self.expected_scores(_obs))
labels.append(np.argmax(scores[-1], axis=1))
return scores, labels
def _meanfield_update_parameters(self, obs, scores):
self._meanfield_update_components(obs, scores)
self._meanfield_update_gating(scores)
def _meanfield_update_gating(self, scores):
self.gating.meanfield_update(None, scores)
def _meanfield_update_components(self, obs, scores):
for idx, c in enumerate(self.components):
c.meanfield_update([_obs for _obs in obs],
[_score[:, idx] for _score in scores])
# SVI
def meanfield_stochastic_descent(self, stepsize=1e-3, batchsize=128,
maxiter=500, progprint=True):
assert self.has_data()
current = mp.current_process()
if len(current._identity) > 0:
pos = current._identity[0] - 1
else:
pos = 0
prob = batchsize / float(sum(len(_obs) for _obs in self.obs))
with tqdm(total=maxiter, desc=f'SVI #{pos + 1}',
position=pos, disable=not progprint) as pbar:
for _ in range(maxiter):
for _obs in self.obs:
for batch in batches(batchsize, len(_obs)):
self.meanfield_sgdstep(_obs[batch, :], prob, stepsize)
pbar.update(1)
def meanfield_sgdstep(self, obs, prob, stepsize):
obs = obs if isinstance(obs, list) else [obs]
scores, _ = self._meanfield_update_labels(obs)
self._meanfield_sgdstep_parameters(obs, scores, prob, stepsize)
if self.has_data():
for _obs in self.obs:
self.labels.append(np.argmax(self.expected_scores(_obs), axis=1))
def _meanfield_sgdstep_parameters(self, obs, scores, prob, stepsize):
self._meanfield_sgdstep_components(obs, scores, prob, stepsize)
self._meanfield_sgdstep_gating(scores, prob, stepsize)
def _meanfield_sgdstep_components(self, obs, scores, prob, stepsize):
for idx, c in enumerate(self.components):
c.meanfield_sgdstep([_obs for _obs in obs],
[_score[:, idx] for _score in scores], prob, stepsize)
def _meanfield_sgdstep_gating(self, scores, prob, stepsize):
self.gating.meanfield_sgdstep(None, scores, prob, stepsize)
def _variational_lowerbound_labels(self, scores):
vlb = 0.
if isinstance(self.gating, CategoricalWithDirichlet):
vlb += np.sum(scores * self.gating.posterior.expected_log_likelihood())
elif isinstance(self.gating, CategoricalWithStickBreaking):
cumscores = np.hstack((np.cumsum(scores[:, ::-1], axis=1)[:, -2::-1],
np.zeros((len(scores), 1))))
E_log_stick, E_log_rest = self.gating.posterior.expected_log_likelihood()
vlb += np.sum(scores * E_log_stick + cumscores * E_log_rest)
errs = np.seterr(invalid='ignore', divide='ignore')
vlb -= np.nansum(scores * np.log(scores)) # treats nans as zeros
np.seterr(**errs)
return vlb
def _variational_lowerbound_obs(self, obs, scores):
return np.sum([r.dot(c.posterior.expected_log_likelihood(obs))
for c, r in zip(self.components, scores.T)])
def variational_lowerbound(self, obs, scores):
vlb = 0.
vlb += sum(self._variational_lowerbound_labels(_score) for _score in scores)
vlb += self.gating.variational_lowerbound()
vlb += sum(c.variational_lowerbound() for c in self.components)
vlb += sum(self._variational_lowerbound_obs(_obs, _score)
for _obs, _score in zip(obs, scores))
# add in symmetry factor (if we're actually symmetric)
if len(set(type(c) for c in self.components)) == 1:
vlb += special.gammaln(self.likelihood.size + 1)
return vlb
# Misc
def bic(self, obs=None):
assert obs is not None
return - 2. * np.sum(self.likelihood.log_likelihood(obs)) + self.likelihood.nb_params\
* np.log(sum([_obs.shape[0] for _obs in obs]))
def aic(self):
assert self.has_data()
return 2. * self.likelihood.nb_params - 2. * sum(np.sum(self.likelihood.log_likelihood(_obs))
for _obs in self.obs)
@pass_obs_arg
def plot(self, obs=None, color=None, legend=False, alpha=None):
# I haven't implemented plotting
# for whitend data, it's a hassle :D
assert self.whitend is False
artists = self.likelihood.plot(obs, color, legend, alpha)
return artists
| [
"numpy.log",
"numpy.arange",
"pathos.helpers.mp.current_process",
"numpy.where",
"sklearn.decomposition.PCA",
"numpy.max",
"numpy.linspace",
"numpy.empty",
"numpy.vstack",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.Rectangle",
"matplotlib.pyplot.axis",
"sklearn.preprocessing.MinMaxScale... | [((1361, 1396), 'numpy.bincount', 'np.bincount', (['z'], {'minlength': 'self.size'}), '(z, minlength=self.size)\n', (1372, 1396), True, 'import numpy as np\n'), ((1412, 1438), 'numpy.zeros', 'np.zeros', (['(size, self.dim)'], {}), '((size, self.dim))\n', (1420, 1438), True, 'import numpy as np\n'), ((1573, 1600), 'numpy.random.permutation', 'np.random.permutation', (['size'], {}), '(size)\n', (1594, 1600), True, 'import numpy as np\n'), ((2145, 2161), 'numpy.empty', 'np.empty', (['(N, K)'], {}), '((N, K))\n', (2153, 2161), True, 'import numpy as np\n'), ((2300, 2343), 'numpy.nan_to_num', 'np.nan_to_num', (['component_scores'], {'copy': '(False)'}), '(component_scores, copy=False)\n', (2313, 2343), True, 'import numpy as np\n'), ((2628, 2664), 'numpy.sum', 'np.sum', (['score'], {'axis': '(1)', 'keepdims': '(True)'}), '(score, axis=1, keepdims=True)\n', (2634, 2664), True, 'import numpy as np\n'), ((2768, 2788), 'pathos.helpers.mp.current_process', 'mp.current_process', ([], {}), '()\n', (2786, 2788), False, 'from pathos.helpers import mp\n'), ((3928, 3947), 'matplotlib.cm.get_cmap', 'cm.get_cmap', (['"""RdBu"""'], {}), "('RdBu')\n", (3939, 3947), False, 'from matplotlib import cm\n'), ((4583, 4593), 'matplotlib.pyplot.axis', 'plt.axis', ([], {}), '()\n', (4591, 4593), True, 'import matplotlib.pyplot as plt\n'), ((4905, 4919), 'matplotlib.pyplot.axis', 'plt.axis', (['axis'], {}), '(axis)\n', (4913, 4919), True, 'import matplotlib.pyplot as plt\n'), ((5224, 5234), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5232, 5234), True, 'import matplotlib.pyplot as plt\n'), ((6054, 6080), 'numpy.where', 'np.where', (['(label_usages > 0)'], {}), '(label_usages > 0)\n', (6062, 6080), True, 'import numpy as np\n'), ((7517, 7537), 'pathos.helpers.mp.current_process', 'mp.current_process', ([], {}), '()\n', (7535, 7537), False, 'from pathos.helpers import mp\n'), ((8548, 8568), 'pathos.helpers.mp.current_process', 'mp.current_process', ([], {}), '()\n', (8566, 8568), False, 'from pathos.helpers import mp\n'), ((9826, 9842), 'numpy.empty', 'np.empty', (['(N, K)'], {}), '((N, K))\n', (9834, 9842), True, 'import numpy as np\n'), ((10000, 10043), 'numpy.nan_to_num', 'np.nan_to_num', (['component_scores'], {'copy': '(False)'}), '(component_scores, copy=False)\n', (10013, 10043), True, 'import numpy as np\n'), ((10592, 10624), 'numpy.sum', 'np.sum', (['r'], {'axis': '(1)', 'keepdims': '(True)'}), '(r, axis=1, keepdims=True)\n', (10598, 10624), True, 'import numpy as np\n'), ((10764, 10784), 'pathos.helpers.mp.current_process', 'mp.current_process', ([], {}), '()\n', (10782, 10784), False, 'from pathos.helpers import mp\n'), ((12901, 12921), 'pathos.helpers.mp.current_process', 'mp.current_process', ([], {}), '()\n', (12919, 12921), False, 'from pathos.helpers import mp\n'), ((15082, 15126), 'numpy.seterr', 'np.seterr', ([], {'invalid': '"""ignore"""', 'divide': '"""ignore"""'}), "(invalid='ignore', divide='ignore')\n", (15091, 15126), True, 'import numpy as np\n'), ((15209, 15226), 'numpy.seterr', 'np.seterr', ([], {}), '(**errs)\n', (15218, 15226), True, 'import numpy as np\n'), ((2396, 2408), 'numpy.arange', 'np.arange', (['K'], {}), '(K)\n', (2405, 2408), True, 'import numpy as np\n'), ((2992, 3071), 'tqdm.tqdm', 'tqdm', ([], {'total': 'maxiter', 'desc': 'f"""EM #{pos + 1}"""', 'position': 'pos', 'disable': '(not progprint)'}), "(total=maxiter, desc=f'EM #{pos + 1}', position=pos, disable=not progprint)\n", (2996, 3071), False, 'from tqdm import tqdm\n'), ((6360, 6393), 'numpy.vstack', 'np.vstack', (['[_obs for _obs in obs]'], {}), '([_obs for _obs in obs])\n', (6369, 6393), True, 'import numpy as np\n'), ((7723, 7808), 'tqdm.tqdm', 'tqdm', ([], {'total': 'maxiter', 'desc': 'f"""MAP #{pos + 1}"""', 'position': 'pos', 'disable': '(not progprint)'}), "(total=maxiter, desc=f'MAP #{pos + 1}', position=pos, disable=not progprint\n )\n", (7727, 7808), False, 'from tqdm import tqdm\n'), ((8699, 8785), 'tqdm.tqdm', 'tqdm', ([], {'total': 'maxiter', 'desc': 'f"""Gibbs #{pos + 1}"""', 'position': 'pos', 'disable': '(not progprint)'}), "(total=maxiter, desc=f'Gibbs #{pos + 1}', position=pos, disable=not\n progprint)\n", (8703, 8785), False, 'from tqdm import tqdm\n'), ((10915, 10994), 'tqdm.tqdm', 'tqdm', ([], {'total': 'maxiter', 'desc': 'f"""VI #{pos + 1}"""', 'position': 'pos', 'disable': '(not progprint)'}), "(total=maxiter, desc=f'VI #{pos + 1}', position=pos, disable=not progprint)\n", (10919, 10994), False, 'from tqdm import tqdm\n'), ((13123, 13208), 'tqdm.tqdm', 'tqdm', ([], {'total': 'maxiter', 'desc': 'f"""SVI #{pos + 1}"""', 'position': 'pos', 'disable': '(not progprint)'}), "(total=maxiter, desc=f'SVI #{pos + 1}', position=pos, disable=not progprint\n )\n", (13127, 13208), False, 'from tqdm import tqdm\n'), ((15987, 16028), 'scipy.special.gammaln', 'special.gammaln', (['(self.likelihood.size + 1)'], {}), '(self.likelihood.size + 1)\n', (16002, 16028), True, 'from scipy import special as special\n'), ((2574, 2609), 'numpy.max', 'np.max', (['logr'], {'axis': '(1)', 'keepdims': '(True)'}), '(logr, axis=1, keepdims=True)\n', (2580, 2609), True, 'import numpy as np\n'), ((4480, 4539), 'matplotlib.pyplot.scatter', 'plt.scatter', (['_obs[:, 0]', '_obs[:, 1]'], {'c': 'colorseq', 'marker': '"""+"""'}), "(_obs[:, 0], _obs[:, 1], c=colorseq, marker='+')\n", (4491, 4539), True, 'import matplotlib.pyplot as plt\n'), ((5925, 5976), 'numpy.bincount', 'np.bincount', (['_label'], {'minlength': 'self.likelihood.size'}), '(_label, minlength=self.likelihood.size)\n', (5936, 5976), True, 'import numpy as np\n'), ((6468, 6513), 'sklearn.decomposition.PCA', 'PCA', ([], {'n_components': 'data.shape[-1]', 'whiten': '(True)'}), '(n_components=data.shape[-1], whiten=True)\n', (6471, 6513), False, 'from sklearn.decomposition import PCA\n'), ((9589, 9628), 'mimo.util.stats.sample_discrete_from_log', 'sample_discrete_from_log', (['score'], {'axis': '(1)'}), '(score, axis=1)\n', (9613, 9628), False, 'from mimo.util.stats import sample_discrete_from_log\n'), ((10542, 10577), 'numpy.max', 'np.max', (['logr'], {'axis': '(1)', 'keepdims': '(True)'}), '(logr, axis=1, keepdims=True)\n', (10548, 10577), True, 'import numpy as np\n'), ((12146, 12175), 'numpy.argmax', 'np.argmax', (['scores[-1]'], {'axis': '(1)'}), '(scores[-1], axis=1)\n', (12155, 12175), True, 'import numpy as np\n'), ((15012, 15065), 'numpy.sum', 'np.sum', (['(scores * E_log_stick + cumscores * E_log_rest)'], {}), '(scores * E_log_stick + cumscores * E_log_rest)\n', (15018, 15065), True, 'import numpy as np\n'), ((15161, 15175), 'numpy.log', 'np.log', (['scores'], {}), '(scores)\n', (15167, 15175), True, 'import numpy as np\n'), ((5003, 5036), 'matplotlib.pyplot.Rectangle', 'plt.Rectangle', (['(0, 0)', '(1)', '(1)'], {'fc': 'c'}), '((0, 0), 1, 1, fc=c)\n', (5016, 5036), True, 'import matplotlib.pyplot as plt\n'), ((6594, 6610), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (6608, 6610), False, 'from sklearn.preprocessing import StandardScaler, MinMaxScaler\n'), ((6689, 6714), 'sklearn.preprocessing.MinMaxScaler', 'MinMaxScaler', (['(-1.0, 1.0)'], {}), '((-1.0, 1.0))\n', (6701, 6714), False, 'from sklearn.preprocessing import StandardScaler, MinMaxScaler\n'), ((4077, 4120), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', 'self.size'], {'endpoint': '(True)'}), '(0, 1, self.size, endpoint=True)\n', (4088, 4120), True, 'import numpy as np\n'), ((14796, 14830), 'numpy.cumsum', 'np.cumsum', (['scores[:, ::-1]'], {'axis': '(1)'}), '(scores[:, ::-1], axis=1)\n', (14805, 14830), True, 'import numpy as np\n'), ((1937, 1950), 'numpy.isnan', 'np.isnan', (['obs'], {}), '(obs)\n', (1945, 1950), True, 'import numpy as np\n'), ((10385, 10406), 'numpy.cumsum', 'np.cumsum', (['E_log_rest'], {}), '(E_log_rest)\n', (10394, 10406), True, 'import numpy as np\n')] |
# ------------------------------------------------------
# Morphological Operations
#
# Created by <NAME> on 19/09/21.
# Copyright (c) 2021 <NAME>. All rights reserved.
#
# ------------------------------------------------------
import cv2
import numpy as np
# Image path
# Tried with other images to by changing the file names to:
# Path for MSRA Images: ../images/MSRA-Images/ + IMG_0714.JPG, IMG_0753.JPG, IMG_0827.JPG, IMG_0870.JPG, IMG_2222.JPG
# Path for lwf Images: ../images/lwf/ + Emma_Watson_0005.jpg, Scott_Wolf_0001,jpg, Skip_Prosser_0001.jpg, Suzanne_Somers_0001.jpg, Tom_Cruise_0010.jpg
img_path = '../images/lwf/Emma_Watson_0005.jpg'
# Reading Image
img = cv2.imread(img_path, 0)
# Kernel
kernel = np.ones((5, 5), np.uint8)
# Erosion
erosion = cv2.erode(img, kernel, iterations=1)
# Dilation
dilation = cv2.dilate(img, kernel, iterations=1)
# Hit and miss
hit_miss = cv2.morphologyEx(img, cv2.MORPH_HITMISS, kernel)
# Tinning
#tinning = cv2.add(img, cv2.bitwise_not(hit_miss))
#tinning = img - hit_miss
tinning = cv2.bitwise_and(img, cv2.bitwise_not(hit_miss))
# Skeletonization
# Threshold the image
ret,img = cv2.threshold(img, 127, 255, 0)
# Step 1: Create an empty skeleton
size = np.size(img)
skel = np.zeros(img.shape, np.uint8)
# Get a Cross Shaped Kernel
element = cv2.getStructuringElement(cv2.MORPH_CROSS, (3,3))
# Repeat steps 2-4
while True:
#Step 2: Open the image
open = cv2.morphologyEx(img, cv2.MORPH_OPEN, element)
#Step 3: Substract open from the original image
temp = cv2.subtract(img, open)
#Step 4: Erode the original image and refine the skeleton
eroded = cv2.erode(img, element)
skel = cv2.bitwise_or(skel,temp)
img = eroded.copy()
# Step 5: If there are no white pixels left ie.. the image has been completely eroded, quit the loop
if cv2.countNonZero(img)==0:
break
# Thickening
thickening = cv2.bitwise_or(img, hit_miss)
# To display Image
#cv2.imshow('Eroded Image', erosion)
#cv2.imshow('Dilated Image', dilation)
#cv2.imshow('Hit And Miss', hit_miss)
#cv2.imshow('Tinning', tinning)
#cv2.imshow('Skeletonization', skel)
#cv2.imshow('Thickening', thickening)
# To save image
cv2.imwrite('../images/output_images/ques2_erosion.png', erosion)
cv2.imwrite('../images/output_images/ques2_dilation.png', dilation)
cv2.imwrite('../images/output_images/ques2_hit_miss.png', hit_miss)
cv2.imwrite('../images/output_images/ques2_tinning.png', tinning)
cv2.imwrite('../images/output_images/ques2_skeletonization.png', skel)
cv2.imwrite('../images/output_images/ques2_thickening.png', thickening)
# Waits till any key is pressed
cv2.waitKey(0)
# Closing all open windows
cv2.destroyAllWindows()
| [
"cv2.imwrite",
"cv2.countNonZero",
"numpy.ones",
"cv2.threshold",
"cv2.erode",
"numpy.size",
"cv2.morphologyEx",
"numpy.zeros",
"cv2.getStructuringElement",
"cv2.waitKey",
"cv2.bitwise_or",
"cv2.destroyAllWindows",
"cv2.bitwise_not",
"cv2.dilate",
"cv2.subtract",
"cv2.imread"
] | [((675, 698), 'cv2.imread', 'cv2.imread', (['img_path', '(0)'], {}), '(img_path, 0)\n', (685, 698), False, 'import cv2\n'), ((718, 743), 'numpy.ones', 'np.ones', (['(5, 5)', 'np.uint8'], {}), '((5, 5), np.uint8)\n', (725, 743), True, 'import numpy as np\n'), ((765, 801), 'cv2.erode', 'cv2.erode', (['img', 'kernel'], {'iterations': '(1)'}), '(img, kernel, iterations=1)\n', (774, 801), False, 'import cv2\n'), ((825, 862), 'cv2.dilate', 'cv2.dilate', (['img', 'kernel'], {'iterations': '(1)'}), '(img, kernel, iterations=1)\n', (835, 862), False, 'import cv2\n'), ((890, 938), 'cv2.morphologyEx', 'cv2.morphologyEx', (['img', 'cv2.MORPH_HITMISS', 'kernel'], {}), '(img, cv2.MORPH_HITMISS, kernel)\n', (906, 938), False, 'import cv2\n'), ((1136, 1167), 'cv2.threshold', 'cv2.threshold', (['img', '(127)', '(255)', '(0)'], {}), '(img, 127, 255, 0)\n', (1149, 1167), False, 'import cv2\n'), ((1211, 1223), 'numpy.size', 'np.size', (['img'], {}), '(img)\n', (1218, 1223), True, 'import numpy as np\n'), ((1231, 1260), 'numpy.zeros', 'np.zeros', (['img.shape', 'np.uint8'], {}), '(img.shape, np.uint8)\n', (1239, 1260), True, 'import numpy as np\n'), ((1300, 1350), 'cv2.getStructuringElement', 'cv2.getStructuringElement', (['cv2.MORPH_CROSS', '(3, 3)'], {}), '(cv2.MORPH_CROSS, (3, 3))\n', (1325, 1350), False, 'import cv2\n'), ((1894, 1923), 'cv2.bitwise_or', 'cv2.bitwise_or', (['img', 'hit_miss'], {}), '(img, hit_miss)\n', (1908, 1923), False, 'import cv2\n'), ((2182, 2247), 'cv2.imwrite', 'cv2.imwrite', (['"""../images/output_images/ques2_erosion.png"""', 'erosion'], {}), "('../images/output_images/ques2_erosion.png', erosion)\n", (2193, 2247), False, 'import cv2\n'), ((2248, 2315), 'cv2.imwrite', 'cv2.imwrite', (['"""../images/output_images/ques2_dilation.png"""', 'dilation'], {}), "('../images/output_images/ques2_dilation.png', dilation)\n", (2259, 2315), False, 'import cv2\n'), ((2316, 2383), 'cv2.imwrite', 'cv2.imwrite', (['"""../images/output_images/ques2_hit_miss.png"""', 'hit_miss'], {}), "('../images/output_images/ques2_hit_miss.png', hit_miss)\n", (2327, 2383), False, 'import cv2\n'), ((2384, 2449), 'cv2.imwrite', 'cv2.imwrite', (['"""../images/output_images/ques2_tinning.png"""', 'tinning'], {}), "('../images/output_images/ques2_tinning.png', tinning)\n", (2395, 2449), False, 'import cv2\n'), ((2450, 2520), 'cv2.imwrite', 'cv2.imwrite', (['"""../images/output_images/ques2_skeletonization.png"""', 'skel'], {}), "('../images/output_images/ques2_skeletonization.png', skel)\n", (2461, 2520), False, 'import cv2\n'), ((2521, 2592), 'cv2.imwrite', 'cv2.imwrite', (['"""../images/output_images/ques2_thickening.png"""', 'thickening'], {}), "('../images/output_images/ques2_thickening.png', thickening)\n", (2532, 2592), False, 'import cv2\n'), ((2626, 2640), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (2637, 2640), False, 'import cv2\n'), ((2669, 2692), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (2690, 2692), False, 'import cv2\n'), ((1058, 1083), 'cv2.bitwise_not', 'cv2.bitwise_not', (['hit_miss'], {}), '(hit_miss)\n', (1073, 1083), False, 'import cv2\n'), ((1421, 1467), 'cv2.morphologyEx', 'cv2.morphologyEx', (['img', 'cv2.MORPH_OPEN', 'element'], {}), '(img, cv2.MORPH_OPEN, element)\n', (1437, 1467), False, 'import cv2\n'), ((1531, 1554), 'cv2.subtract', 'cv2.subtract', (['img', 'open'], {}), '(img, open)\n', (1543, 1554), False, 'import cv2\n'), ((1630, 1653), 'cv2.erode', 'cv2.erode', (['img', 'element'], {}), '(img, element)\n', (1639, 1653), False, 'import cv2\n'), ((1665, 1691), 'cv2.bitwise_or', 'cv2.bitwise_or', (['skel', 'temp'], {}), '(skel, temp)\n', (1679, 1691), False, 'import cv2\n'), ((1827, 1848), 'cv2.countNonZero', 'cv2.countNonZero', (['img'], {}), '(img)\n', (1843, 1848), False, 'import cv2\n')] |
import pandas as pd
import numpy as np
import sys
import pickle
import os
import shutil
import time
import argparse
import peakutils
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.model_selection import RandomizedSearchCV
from sklearn.model_selection import train_test_split
import configparser
from configparser import ExtendedInterpolation
def generate_estimator(X_train, X_test, y_train, y_test):
if args.search_for_new_model_parameters:
# do a randomised search to find the best regressor dimensions
print('setting up randomised search')
parameter_search_space = {
"loss": ['ls','lad','huber'],
"learning_rate": [0.01, 0.05, 0.1, 0.2],
'n_estimators': range(20,510,10),
'max_depth':range(5,30,2),
'min_samples_split':range(100,1001,100),
'subsample':list(np.arange(0.2,0.9,0.1)),
'min_samples_leaf':range(10,71,10),
'max_features':["log2", "sqrt"],
}
# cross-validation splitting strategy uses 'cv' folds in a (Stratified)KFold
rsearch = RandomizedSearchCV(GradientBoostingRegressor(), parameter_search_space, n_iter=100, n_jobs=-1, random_state=10, cv=5, scoring='r2', verbose=1) # All scorer objects follow the convention that higher return values are better than lower return values, so we want the negated version for error metrics
print('fitting to the training set')
# find the best fit within the parameter search space
rsearch.fit(X_train, y_train)
best_estimator = rsearch.best_estimator_
print('best score from the search: {}'.format(round(rsearch.best_score_, 4)))
best_params = rsearch.best_params_
print(best_params)
else:
print('fitting the estimator to the training data')
# use the model parameters we found previously
best_params = {'subsample': 0.6, 'n_estimators': 280, 'min_samples_split': 400, 'min_samples_leaf': 10, 'max_features': 'log2', 'max_depth': 11, 'loss': 'lad', 'learning_rate': 0.05}
best_estimator = GradientBoostingRegressor(**best_params)
best_estimator.fit(X_train, y_train) # find the best fit within the parameter search space
# calculate the estimator's score on the train and test sets
print('evaluating against the training and test set')
y_train_pred = best_estimator.predict(X_train)
y_test_pred = best_estimator.predict(X_test)
print("mean absolute error for training set: {}, test set: {}".format(round(np.abs(y_train-y_train_pred).mean(),4), round(np.abs(y_test-y_test_pred).mean(),4)))
return best_estimator
####################################################################
# This program uses the sequence library to build estimation models to estimate where in each run the library sequence should be.
parser = argparse.ArgumentParser(description='Using the library sequences, build run-specific coordinate estimators for the sequence-charges identified in the experiment.')
parser.add_argument('-eb','--experiment_base_dir', type=str, default='./experiments', help='Path to the experiments directory.', required=False)
parser.add_argument('-en','--experiment_name', type=str, help='Name of the experiment.', required=True)
parser.add_argument('-ini','--ini_file', type=str, default='./tfde/pipeline/pasef-process-short-gradient.ini', help='Path to the config file.', required=False)
parser.add_argument('-snmp','--search_for_new_model_parameters', action='store_true', help='Search for new model parameters.')
parser.add_argument('-pdm','--precursor_definition_method', type=str, choices=['pasef','3did','mq'], default='pasef', help='The method used to define the precursor cuboids.', required=False)
args = parser.parse_args()
# Print the arguments for the log
info = []
for arg in vars(args):
info.append((arg, getattr(args, arg)))
print(info)
# check the experiment directory exists
EXPERIMENT_DIR = "{}/{}".format(args.experiment_base_dir, args.experiment_name)
if not os.path.exists(EXPERIMENT_DIR):
print("The experiment directory is required but doesn't exist: {}".format(EXPERIMENT_DIR))
sys.exit(1)
# load the sequence library
SEQUENCE_LIBRARY_DIR = "{}/sequence-library-{}".format(EXPERIMENT_DIR, args.precursor_definition_method)
SEQUENCE_LIBRARY_FILE_NAME = "{}/sequence-library.feather".format(SEQUENCE_LIBRARY_DIR)
if not os.path.isfile(SEQUENCE_LIBRARY_FILE_NAME):
print("The sequences library file doesn't exist: {}".format(SEQUENCE_LIBRARY_FILE_NAME))
sys.exit(1)
# load the sequence library
library_sequences_df = pd.read_feather(SEQUENCE_LIBRARY_FILE_NAME)
print('loaded {} sequences from the library {}'.format(len(library_sequences_df), SEQUENCE_LIBRARY_FILE_NAME))
# load the indentifications from each run
IDENTIFICATIONS_DIR = '{}/identifications-pasef'.format(EXPERIMENT_DIR)
IDENTIFICATIONS_FILE = '{}/exp-{}-identifications-pasef-recalibrated.feather'.format(IDENTIFICATIONS_DIR, args.experiment_name)
if not os.path.isfile(IDENTIFICATIONS_FILE):
print("The identifications file doesn't exist: {}".format(IDENTIFICATIONS_FILE))
sys.exit(1)
# load the experiment identifications
identifications_df = pd.read_feather(IDENTIFICATIONS_FILE)
print('loaded {} identifications from {}'.format(len(identifications_df), IDENTIFICATIONS_FILE))
identifications_df['human'] = identifications_df['protein id'].str.contains('HUMAN')
# set up the coordinate estimators directory
COORDINATE_ESTIMATORS_DIR = "{}/coordinate-estimators".format(EXPERIMENT_DIR)
if os.path.exists(COORDINATE_ESTIMATORS_DIR):
shutil.rmtree(COORDINATE_ESTIMATORS_DIR)
os.makedirs(COORDINATE_ESTIMATORS_DIR)
print("The coordinate estimators directory was created: {}".format(COORDINATE_ESTIMATORS_DIR))
# outputs
RUN_SEQUENCES_FILE_NAME = "{}/run-sequence-attribs.feather".format(COORDINATE_ESTIMATORS_DIR)
MERGED_RUN_LIBRARY_SEQUENCES_FILE_NAME = "{}/merged-run-library-sequence-attribs.feather".format(COORDINATE_ESTIMATORS_DIR)
# check the INI file exists
if not os.path.isfile(args.ini_file):
print("The configuration file doesn't exist: {}".format(args.ini_file))
sys.exit(1)
# load the INI file
cfg = configparser.ConfigParser(interpolation=ExtendedInterpolation())
cfg.read(args.ini_file)
# set up constants
MINIMUM_PROPORTION_OF_IDENTS_FOR_COORD_ESTIMATOR_TRAINING = cfg.getfloat('extraction','MINIMUM_PROPORTION_OF_IDENTS_FOR_COORD_ESTIMATOR_TRAINING')
start_run = time.time()
# for each run, find the mz, scan, RT, and intensity for each sequence-charge identified
run_sequences_l = []
for group_name,group_df in identifications_df.groupby(['run_name','sequence','charge'], as_index=False):
run_name = group_name[0]
sequence = group_name[1]
charge = group_name[2]
run_mz_mean = peakutils.centroid(group_df.recalibrated_monoisotopic_mz, group_df.feature_intensity)
run_mz_std_dev = np.std(group_df.recalibrated_monoisotopic_mz)
run_scan_mean = np.mean(group_df.scan_apex)
run_scan_std_dev = np.std(group_df.scan_apex)
run_rt_mean = np.mean(group_df.rt_apex)
run_rt_std_dev = np.std(group_df.rt_apex)
run_intensity_mean = np.mean(group_df.feature_intensity)
run_intensity_std_dev = np.std(group_df.feature_intensity)
run_sequences_l.append((run_name,sequence,charge,run_mz_mean,run_scan_mean,run_rt_mean,run_mz_std_dev,run_scan_std_dev,run_rt_std_dev,run_intensity_mean,run_intensity_std_dev))
run_sequences_df = pd.DataFrame(run_sequences_l, columns=['run_name','sequence','charge','run_mz','run_scan','run_rt','run_mz_std_dev','run_scan_std_dev','run_rt_std_dev','run_intensity','run_intensity_std_dev'])
# calculate the coefficients of variance
run_sequences_df['cv_mz'] = run_sequences_df.run_mz_std_dev / run_sequences_df.run_mz
run_sequences_df['cv_scan'] = run_sequences_df.run_scan_std_dev / run_sequences_df.run_scan
run_sequences_df['cv_rt'] = run_sequences_df.run_rt_std_dev / run_sequences_df.run_rt
run_sequences_df['cv_intensity'] = run_sequences_df.run_intensity_std_dev / run_sequences_df.run_intensity
run_sequences_df.to_feather(RUN_SEQUENCES_FILE_NAME)
# merge the sequence-charges for each run with their library counterparts
merged_df = pd.merge(run_sequences_df, library_sequences_df, how='left', left_on=['sequence','charge'], right_on=['sequence','charge'])
# for each run-sequence-charge, calculate the delta from the library
merged_df['delta_mz'] = merged_df.run_mz - merged_df.theoretical_mz
merged_df['delta_mz_ppm'] = (merged_df.run_mz - merged_df.theoretical_mz) / merged_df.theoretical_mz * 1e6
merged_df['delta_scan'] = (merged_df.run_scan - merged_df.experiment_scan_mean) / merged_df.experiment_scan_mean
merged_df['delta_rt'] = (merged_df.run_rt - merged_df.experiment_rt_mean) / merged_df.experiment_rt_mean
merged_df.drop(['run_mz_std_dev','run_scan_std_dev','run_rt_std_dev','run_intensity_std_dev'], axis=1, inplace=True)
print("writing {} merged run-library sequence attributes to {}".format(len(merged_df), MERGED_RUN_LIBRARY_SEQUENCES_FILE_NAME))
merged_df.to_feather(MERGED_RUN_LIBRARY_SEQUENCES_FILE_NAME)
# create an estimator for each run in the experiment
run_names_l = list(identifications_df.run_name.unique())
for run_name in run_names_l:
print("building the coordinate estimators for run {}".format(run_name))
estimator_training_set_df = merged_df[(merged_df.run_name == run_name) & (merged_df.number_of_runs_identified > round(len(run_names_l) * MINIMUM_PROPORTION_OF_IDENTS_FOR_COORD_ESTIMATOR_TRAINING))]
# X is the same for all the estimators
# filter out rows not to be used in this training set
X = estimator_training_set_df[['theoretical_mz','experiment_rt_mean','experiment_rt_std_dev','experiment_scan_mean','experiment_scan_std_dev','experiment_intensity_mean','experiment_intensity_std_dev']].values
y = estimator_training_set_df[['delta_mz_ppm','delta_scan','delta_rt','run_mz','run_scan','run_rt']].values
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.02)
print('there are {} examples in the training set, {} in the test set'.format(len(X_train), len(X_test)))
# save the test set so we can evaluate performance
np.save('{}/run-{}-X_test.npy'.format(COORDINATE_ESTIMATORS_DIR, run_name), X_test)
np.save('{}/run-{}-y_test.npy'.format(COORDINATE_ESTIMATORS_DIR, run_name), y_test)
# build the m/z delta estimation model - estimate the m/z delta ppm as a proportion of the experiment-wide value
print('training the m/z model')
mz_estimator = generate_estimator(X_train, X_test, y_train[:,0], y_test[:,0])
# save the trained m/z model
ESTIMATOR_MODEL_FILE_NAME = "{}/run-{}-{}-estimator.pkl".format(COORDINATE_ESTIMATORS_DIR, run_name, 'mz')
with open(ESTIMATOR_MODEL_FILE_NAME, 'wb') as file:
pickle.dump(mz_estimator, file)
# build the scan estimation model - estimate the delta scan as a proportion of the experiment-wide value
print('training the scan model')
scan_estimator = generate_estimator(X_train, X_test, y_train[:,1], y_test[:,1])
# save the trained scan model
ESTIMATOR_MODEL_FILE_NAME = "{}/run-{}-{}-estimator.pkl".format(COORDINATE_ESTIMATORS_DIR, run_name, 'scan')
with open(ESTIMATOR_MODEL_FILE_NAME, 'wb') as file:
pickle.dump(scan_estimator, file)
# RT estimation model - estimate the RT delta as a proportion of the experiment-wide value
print('training the RT model')
rt_estimator = generate_estimator(X_train, X_test, y_train[:,2], y_test[:,2])
# save the trained RT model
ESTIMATOR_MODEL_FILE_NAME = "{}/run-{}-{}-estimator.pkl".format(COORDINATE_ESTIMATORS_DIR, run_name, 'rt')
with open(ESTIMATOR_MODEL_FILE_NAME, 'wb') as file:
pickle.dump(rt_estimator, file)
print()
stop_run = time.time()
print("total running time ({}): {} seconds".format(parser.prog, round(stop_run-start_run,1)))
| [
"sys.exit",
"numpy.arange",
"pandas.read_feather",
"os.path.exists",
"numpy.mean",
"argparse.ArgumentParser",
"pandas.DataFrame",
"sklearn.ensemble.GradientBoostingRegressor",
"configparser.ExtendedInterpolation",
"numpy.abs",
"sklearn.model_selection.train_test_split",
"pandas.merge",
"os.p... | [((2876, 3049), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Using the library sequences, build run-specific coordinate estimators for the sequence-charges identified in the experiment."""'}), "(description=\n 'Using the library sequences, build run-specific coordinate estimators for the sequence-charges identified in the experiment.'\n )\n", (2899, 3049), False, 'import argparse\n'), ((4622, 4665), 'pandas.read_feather', 'pd.read_feather', (['SEQUENCE_LIBRARY_FILE_NAME'], {}), '(SEQUENCE_LIBRARY_FILE_NAME)\n', (4637, 4665), True, 'import pandas as pd\n'), ((5226, 5263), 'pandas.read_feather', 'pd.read_feather', (['IDENTIFICATIONS_FILE'], {}), '(IDENTIFICATIONS_FILE)\n', (5241, 5263), True, 'import pandas as pd\n'), ((5573, 5614), 'os.path.exists', 'os.path.exists', (['COORDINATE_ESTIMATORS_DIR'], {}), '(COORDINATE_ESTIMATORS_DIR)\n', (5587, 5614), False, 'import os\n'), ((5661, 5699), 'os.makedirs', 'os.makedirs', (['COORDINATE_ESTIMATORS_DIR'], {}), '(COORDINATE_ESTIMATORS_DIR)\n', (5672, 5699), False, 'import os\n'), ((6479, 6490), 'time.time', 'time.time', ([], {}), '()\n', (6488, 6490), False, 'import time\n'), ((7476, 7687), 'pandas.DataFrame', 'pd.DataFrame', (['run_sequences_l'], {'columns': "['run_name', 'sequence', 'charge', 'run_mz', 'run_scan', 'run_rt',\n 'run_mz_std_dev', 'run_scan_std_dev', 'run_rt_std_dev', 'run_intensity',\n 'run_intensity_std_dev']"}), "(run_sequences_l, columns=['run_name', 'sequence', 'charge',\n 'run_mz', 'run_scan', 'run_rt', 'run_mz_std_dev', 'run_scan_std_dev',\n 'run_rt_std_dev', 'run_intensity', 'run_intensity_std_dev'])\n", (7488, 7687), True, 'import pandas as pd\n'), ((8224, 8354), 'pandas.merge', 'pd.merge', (['run_sequences_df', 'library_sequences_df'], {'how': '"""left"""', 'left_on': "['sequence', 'charge']", 'right_on': "['sequence', 'charge']"}), "(run_sequences_df, library_sequences_df, how='left', left_on=[\n 'sequence', 'charge'], right_on=['sequence', 'charge'])\n", (8232, 8354), True, 'import pandas as pd\n'), ((11819, 11830), 'time.time', 'time.time', ([], {}), '()\n', (11828, 11830), False, 'import time\n'), ((4045, 4075), 'os.path.exists', 'os.path.exists', (['EXPERIMENT_DIR'], {}), '(EXPERIMENT_DIR)\n', (4059, 4075), False, 'import os\n'), ((4176, 4187), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (4184, 4187), False, 'import sys\n'), ((4417, 4459), 'os.path.isfile', 'os.path.isfile', (['SEQUENCE_LIBRARY_FILE_NAME'], {}), '(SEQUENCE_LIBRARY_FILE_NAME)\n', (4431, 4459), False, 'import os\n'), ((4558, 4569), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (4566, 4569), False, 'import sys\n'), ((5027, 5063), 'os.path.isfile', 'os.path.isfile', (['IDENTIFICATIONS_FILE'], {}), '(IDENTIFICATIONS_FILE)\n', (5041, 5063), False, 'import os\n'), ((5154, 5165), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (5162, 5165), False, 'import sys\n'), ((5620, 5660), 'shutil.rmtree', 'shutil.rmtree', (['COORDINATE_ESTIMATORS_DIR'], {}), '(COORDINATE_ESTIMATORS_DIR)\n', (5633, 5660), False, 'import shutil\n'), ((6060, 6089), 'os.path.isfile', 'os.path.isfile', (['args.ini_file'], {}), '(args.ini_file)\n', (6074, 6089), False, 'import os\n'), ((6171, 6182), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (6179, 6182), False, 'import sys\n'), ((6810, 6900), 'peakutils.centroid', 'peakutils.centroid', (['group_df.recalibrated_monoisotopic_mz', 'group_df.feature_intensity'], {}), '(group_df.recalibrated_monoisotopic_mz, group_df.\n feature_intensity)\n', (6828, 6900), False, 'import peakutils\n'), ((6917, 6962), 'numpy.std', 'np.std', (['group_df.recalibrated_monoisotopic_mz'], {}), '(group_df.recalibrated_monoisotopic_mz)\n', (6923, 6962), True, 'import numpy as np\n'), ((6983, 7010), 'numpy.mean', 'np.mean', (['group_df.scan_apex'], {}), '(group_df.scan_apex)\n', (6990, 7010), True, 'import numpy as np\n'), ((7034, 7060), 'numpy.std', 'np.std', (['group_df.scan_apex'], {}), '(group_df.scan_apex)\n', (7040, 7060), True, 'import numpy as np\n'), ((7079, 7104), 'numpy.mean', 'np.mean', (['group_df.rt_apex'], {}), '(group_df.rt_apex)\n', (7086, 7104), True, 'import numpy as np\n'), ((7126, 7150), 'numpy.std', 'np.std', (['group_df.rt_apex'], {}), '(group_df.rt_apex)\n', (7132, 7150), True, 'import numpy as np\n'), ((7176, 7211), 'numpy.mean', 'np.mean', (['group_df.feature_intensity'], {}), '(group_df.feature_intensity)\n', (7183, 7211), True, 'import numpy as np\n'), ((7240, 7274), 'numpy.std', 'np.std', (['group_df.feature_intensity'], {}), '(group_df.feature_intensity)\n', (7246, 7274), True, 'import numpy as np\n'), ((10003, 10041), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'test_size': '(0.02)'}), '(X, y, test_size=0.02)\n', (10019, 10041), False, 'from sklearn.model_selection import train_test_split\n'), ((2108, 2148), 'sklearn.ensemble.GradientBoostingRegressor', 'GradientBoostingRegressor', ([], {}), '(**best_params)\n', (2133, 2148), False, 'from sklearn.ensemble import GradientBoostingRegressor\n'), ((6250, 6273), 'configparser.ExtendedInterpolation', 'ExtendedInterpolation', ([], {}), '()\n', (6271, 6273), False, 'from configparser import ExtendedInterpolation\n'), ((10828, 10859), 'pickle.dump', 'pickle.dump', (['mz_estimator', 'file'], {}), '(mz_estimator, file)\n', (10839, 10859), False, 'import pickle\n'), ((11303, 11336), 'pickle.dump', 'pickle.dump', (['scan_estimator', 'file'], {}), '(scan_estimator, file)\n', (11314, 11336), False, 'import pickle\n'), ((11758, 11789), 'pickle.dump', 'pickle.dump', (['rt_estimator', 'file'], {}), '(rt_estimator, file)\n', (11769, 11789), False, 'import pickle\n'), ((1137, 1164), 'sklearn.ensemble.GradientBoostingRegressor', 'GradientBoostingRegressor', ([], {}), '()\n', (1162, 1164), False, 'from sklearn.ensemble import GradientBoostingRegressor\n'), ((883, 907), 'numpy.arange', 'np.arange', (['(0.2)', '(0.9)', '(0.1)'], {}), '(0.2, 0.9, 0.1)\n', (892, 907), True, 'import numpy as np\n'), ((2553, 2583), 'numpy.abs', 'np.abs', (['(y_train - y_train_pred)'], {}), '(y_train - y_train_pred)\n', (2559, 2583), True, 'import numpy as np\n'), ((2599, 2627), 'numpy.abs', 'np.abs', (['(y_test - y_test_pred)'], {}), '(y_test - y_test_pred)\n', (2605, 2627), 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.
# ==============================================================================
"""Tests for checkpointing the dataset constructors."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import parameterized
import numpy as np
from tensorflow.python.data.kernel_tests import checkpoint_test_base
from tensorflow.python.data.kernel_tests import test_base
from tensorflow.python.data.ops import dataset_ops
from tensorflow.python.framework import combinations
from tensorflow.python.framework import sparse_tensor
from tensorflow.python.platform import test
class FromTensorsCheckpointTest(checkpoint_test_base.CheckpointTestBase,
parameterized.TestCase):
def _build_tensor_dataset(self, variable_array):
components = (variable_array, np.array([1, 2, 3]), np.array(37.0))
return dataset_ops.Dataset.from_tensors(components)
@combinations.generate(test_base.default_test_combinations())
def testFromTensorsCore(self):
# Equal length components
arr = np.array(1)
num_outputs = 1
self.run_core_tests(lambda: self._build_tensor_dataset(arr),
num_outputs)
class FromTensorSlicesCheckpointTest(checkpoint_test_base.CheckpointTestBase,
parameterized.TestCase):
def _build_tensor_slices_dataset(self, components):
return dataset_ops.Dataset.from_tensor_slices(components)
@combinations.generate(test_base.default_test_combinations())
def testFromTensorSlicesCore(self):
# Equal length components
components = (np.tile(np.array([[1], [2], [3], [4]]), 20),
np.tile(np.array([[12], [13], [14], [15]]), 22),
np.array([37.0, 38.0, 39.0, 40.0]))
dict_components = {"foo": [1, 2, 3], "bar": [[4.0], [5.0], [6.0]]}
self.run_core_tests(lambda: self._build_tensor_slices_dataset(components),
4)
self.run_core_tests(
lambda: self._build_tensor_slices_dataset(dict_components), 3)
class FromSparseTensorSlicesCheckpointTest(
checkpoint_test_base.CheckpointTestBase, parameterized.TestCase):
def _build_sparse_tensor_slice_dataset(self, slices):
indices = np.array(
[[i, j] for i in range(len(slices)) for j in range(len(slices[i]))],
dtype=np.int64)
values = np.array([val for s in slices for val in s], dtype=np.float64)
dense_shape = np.array(
[len(slices), max(len(s) for s in slices) + 1], dtype=np.int64)
sparse_components = sparse_tensor.SparseTensor(indices, values, dense_shape)
return dataset_ops.Dataset.from_sparse_tensor_slices(sparse_components)
@combinations.generate(
combinations.combine(
tf_api_version=1,
mode=["graph", "eager"]))
def testFromSparseTensorSlicesCore(self):
slices = [[1., 2., 3.], [1.], [1.], [1., 2.], [], [1., 2.], [], [], []]
self.run_core_tests(
lambda: self._build_sparse_tensor_slice_dataset(slices),
9,
sparse_tensors=True)
if __name__ == "__main__":
test.main()
| [
"tensorflow.python.data.ops.dataset_ops.Dataset.from_tensors",
"tensorflow.python.data.ops.dataset_ops.Dataset.from_sparse_tensor_slices",
"numpy.array",
"tensorflow.python.data.kernel_tests.test_base.default_test_combinations",
"tensorflow.python.framework.sparse_tensor.SparseTensor",
"tensorflow.python.... | [((3710, 3721), 'tensorflow.python.platform.test.main', 'test.main', ([], {}), '()\n', (3719, 3721), False, 'from tensorflow.python.platform import test\n'), ((1510, 1554), 'tensorflow.python.data.ops.dataset_ops.Dataset.from_tensors', 'dataset_ops.Dataset.from_tensors', (['components'], {}), '(components)\n', (1542, 1554), False, 'from tensorflow.python.data.ops import dataset_ops\n'), ((1693, 1704), 'numpy.array', 'np.array', (['(1)'], {}), '(1)\n', (1701, 1704), True, 'import numpy as np\n'), ((1581, 1618), 'tensorflow.python.data.kernel_tests.test_base.default_test_combinations', 'test_base.default_test_combinations', ([], {}), '()\n', (1616, 1618), False, 'from tensorflow.python.data.kernel_tests import test_base\n'), ((2035, 2085), 'tensorflow.python.data.ops.dataset_ops.Dataset.from_tensor_slices', 'dataset_ops.Dataset.from_tensor_slices', (['components'], {}), '(components)\n', (2073, 2085), False, 'from tensorflow.python.data.ops import dataset_ops\n'), ((2112, 2149), 'tensorflow.python.data.kernel_tests.test_base.default_test_combinations', 'test_base.default_test_combinations', ([], {}), '()\n', (2147, 2149), False, 'from tensorflow.python.data.kernel_tests import test_base\n'), ((2989, 3051), 'numpy.array', 'np.array', (['[val for s in slices for val in s]'], {'dtype': 'np.float64'}), '([val for s in slices for val in s], dtype=np.float64)\n', (2997, 3051), True, 'import numpy as np\n'), ((3176, 3232), 'tensorflow.python.framework.sparse_tensor.SparseTensor', 'sparse_tensor.SparseTensor', (['indices', 'values', 'dense_shape'], {}), '(indices, values, dense_shape)\n', (3202, 3232), False, 'from tensorflow.python.framework import sparse_tensor\n'), ((3244, 3308), 'tensorflow.python.data.ops.dataset_ops.Dataset.from_sparse_tensor_slices', 'dataset_ops.Dataset.from_sparse_tensor_slices', (['sparse_components'], {}), '(sparse_components)\n', (3289, 3308), False, 'from tensorflow.python.data.ops import dataset_ops\n'), ((3342, 3405), 'tensorflow.python.framework.combinations.combine', 'combinations.combine', ([], {'tf_api_version': '(1)', 'mode': "['graph', 'eager']"}), "(tf_api_version=1, mode=['graph', 'eager'])\n", (3362, 3405), False, 'from tensorflow.python.framework import combinations\n'), ((1461, 1480), 'numpy.array', 'np.array', (['[1, 2, 3]'], {}), '([1, 2, 3])\n', (1469, 1480), True, 'import numpy as np\n'), ((1482, 1496), 'numpy.array', 'np.array', (['(37.0)'], {}), '(37.0)\n', (1490, 1496), True, 'import numpy as np\n'), ((2367, 2401), 'numpy.array', 'np.array', (['[37.0, 38.0, 39.0, 40.0]'], {}), '([37.0, 38.0, 39.0, 40.0])\n', (2375, 2401), True, 'import numpy as np\n'), ((2245, 2275), 'numpy.array', 'np.array', (['[[1], [2], [3], [4]]'], {}), '([[1], [2], [3], [4]])\n', (2253, 2275), True, 'import numpy as np\n'), ((2308, 2342), 'numpy.array', 'np.array', (['[[12], [13], [14], [15]]'], {}), '([[12], [13], [14], [15]])\n', (2316, 2342), True, 'import numpy as np\n')] |
from __future__ import division, print_function, absolute_import
import vzlog
import vzlog.pyplot as plt
import numpy as np
vz = vzlog.VzLog('log-image-grids')
vz.title('Image grids')
rs = np.random.RandomState(0)
x = rs.uniform(size=(9, 20, 20))
grid = vzlog.image.ImageGrid(x, cmap=plt.cm.rainbow)
grid.save(vz.impath('png'))
vz.text('You can scale the grid, creating a larger image:')
grid.save(vz.impath('png'), scale=3)
vz.text('Or, you can let your browser scale the image:')
grid.save(vz.impath('png', scale=3))
vz.text('Currently, only Firefox resizes this without blurring the image.')
vz.text('Use `ColorImageGrid` for RGB images:')
y = rs.uniform(size=(3, 20, 20, 3))
for i in range(3):
y[i, ..., i] = 0
rgb_grid = vzlog.image.ColorImageGrid(y, rows=1)
rgb_grid.save(vz.impath('png', scale=3))
z = rs.uniform(size=(10, 10))
rgb_grid = vzlog.image.ImageGrid(z)
rgb_grid.save(vz.impath('png', scale=3))
| [
"vzlog.image.ImageGrid",
"vzlog.image.ColorImageGrid",
"numpy.random.RandomState",
"vzlog.VzLog"
] | [((131, 161), 'vzlog.VzLog', 'vzlog.VzLog', (['"""log-image-grids"""'], {}), "('log-image-grids')\n", (142, 161), False, 'import vzlog\n'), ((193, 217), 'numpy.random.RandomState', 'np.random.RandomState', (['(0)'], {}), '(0)\n', (214, 217), True, 'import numpy as np\n'), ((259, 304), 'vzlog.image.ImageGrid', 'vzlog.image.ImageGrid', (['x'], {'cmap': 'plt.cm.rainbow'}), '(x, cmap=plt.cm.rainbow)\n', (280, 304), False, 'import vzlog\n'), ((739, 776), 'vzlog.image.ColorImageGrid', 'vzlog.image.ColorImageGrid', (['y'], {'rows': '(1)'}), '(y, rows=1)\n', (765, 776), False, 'import vzlog\n'), ((860, 884), 'vzlog.image.ImageGrid', 'vzlog.image.ImageGrid', (['z'], {}), '(z)\n', (881, 884), False, 'import vzlog\n')] |
import os
import cv2
import pandas as pd
import numpy as np
import imgaug.augmenters as iaa
from sklearn.utils import shuffle
from tensorflow.keras.models import Sequential
from tensorflow.keras import layers
from tensorflow.keras.optimizers import Adam
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import random
# 1 - INITIALIZE DATA
def get_name(filepath):
'''
Returns the path of the image and its current directory
'''
image_path_list = filepath.split('/')[-2:]
image_path = os.path.join(image_path_list[0], image_path_list[1])
return image_path
def import_data_info(path):
'''
Converts the contents of the log csv file
into a pandas data frame
'''
columns = ['ImgPath', 'Steering']
no_of_folders = len(os.listdir(path)) // 2
data = pd.DataFrame()
for x in range(no_of_folders):
data_new = pd.read_csv(os.path.join(path, f'log_{x}.csv'), names=columns)
print(f'{x}:{data_new.shape[0]}')
data_new['ImgPath'] = data_new['ImgPath'].apply(get_name)
data = data.append(data_new, True)
print('')
print('Total Images Imported', data.shape[0])
return data
# 2 - VISUALIZE AND BALANCE DATA
def balance_data(data, samples_per_bin=300, display=True):
'''
Balances the data to prevent overfitting
'''
n_bin = 31
hist, bins = np.histogram(data['Steering'], n_bin)
if display:
center = (bins[:-1] + bins[1:]) * 0.5
plt.bar(center, hist, width=0.03)
plt.plot((np.min(data['Steering']), np.max(data['Steering'])), (samples_per_bin, samples_per_bin))
plt.title('Data Visualization')
plt.xlabel('Steering Angle')
plt.ylabel('No of Samples')
plt.show()
remove_index_list = []
for j in range(n_bin):
bin_data_list = []
for i in range(len(data['Steering'])):
if data['Steering'][i] >= bins[j] and data['Steering'][i] <= bins[j + 1]:
bin_data_list.append(i)
bin_data_list = shuffle(bin_data_list)
bin_data_list = bin_data_list[samples_per_bin:]
remove_index_list.extend(bin_data_list)
print('Removed Images: ', len(remove_index_list))
data.drop(data.index[remove_index_list], inplace=True)
print('Remaining Images: ', len(data))
if display:
hist, _ = np.histogram(data['Steering'], (n_bin))
plt.bar(center, hist, width=0.03)
plt.plot((np.min(data['Steering']), np.max(data['Steering'])), (samples_per_bin, samples_per_bin))
plt.title('Balanced Data')
plt.xlabel('Steering Angle')
plt.ylabel('No of Samples')
plt.show()
return data
# 3 - PREPARE FOR PROCESSING
def load_data(path, data):
images_path = []
steering = []
for i in range(len(data)):
indexed_data = data.iloc[i]
images_path.append(os.path.join(path, indexed_data[0]))
steering.append(float(indexed_data[1]))
images_path = np.asarray(images_path)
steering = np.asarray(steering)
return images_path, steering
# 5 - AUGMENT IMAGES
def augment_image(img_path, steering):
'''
Reads an image from a given path
and then randomly augments the image
'''
img = cv2.imread(img_path)
if np.random.rand() < 0.5:
pan = iaa.Affine(translate_percent={'x': (-0.1, 0.1), 'y': (-0.1, 0.1)})
img = pan.augment_image(img)
if np.random.rand() < 0.5:
zoom = iaa.Affine(scale=(1, 1.2))
img = zoom.augment_image(img)
if np.random.rand() < 0.5:
brightness = iaa.Multiply((0.5, 1.2))
img = brightness.augment_image(img)
if np.random.rand() < 0.5:
img = cv2.flip(img, 1)
steering = -steering
return img, steering
# 6 - PREPROCESS
def preprocess(img):
img = img[174:, :, :]
img = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)
img = cv2.GaussianBlur(img, (3, 3), 0)
img = cv2.resize(img, (200, 66))
img = img / 255
return img
# 7 - CREATE MODEL
def create_model():
model = Sequential(
[
layers.Convolution2D(24, (5, 5), (2, 2), input_shape=(66, 200, 3), activation='elu'),
layers.Convolution2D(36, (5, 5), (2, 2), activation='elu'),
layers.Convolution2D(48, (5, 5), (2, 2), activation='elu'),
layers.Convolution2D(64, (3, 3), activation='elu'),
layers.Convolution2D(64, (3, 3), activation='elu'),
layers.Flatten(),
layers.Dense(100, activation='elu'),
layers.Dense(50, activation='elu'),
layers.Dense(10, activation='elu'),
layers.Dense(1)
]
)
opt = Adam(learning_rate=0.0003)
model.compile(loss='mse', optimizer=opt)
return model
# 8 - TRAINING
def data_gen(images_path, steering_list, batch_size, train_flag):
'''
Generates a batch of images and its corresponding steering angle.
If the train flag is set to true, this function will augment the images.
'''
while True:
img_batch = []
steering_batch = []
for i in range(batch_size):
index = random.randint(0, len(images_path) - 1)
if train_flag:
img, steering = augment_image(images_path[index], steering_list[index])
else:
img = cv2.imread(images_path[index])
steering = steering_list[index]
img = preprocess(img)
img_batch.append(img)
steering_batch.append(steering)
yield (np.asarray(img_batch), np.asarray(steering_batch))
| [
"tensorflow.keras.layers.Convolution2D",
"numpy.random.rand",
"matplotlib.pyplot.ylabel",
"tensorflow.keras.layers.Dense",
"numpy.histogram",
"os.listdir",
"matplotlib.pyplot.xlabel",
"numpy.asarray",
"numpy.max",
"numpy.min",
"pandas.DataFrame",
"cv2.cvtColor",
"imgaug.augmenters.Multiply",... | [((523, 575), 'os.path.join', 'os.path.join', (['image_path_list[0]', 'image_path_list[1]'], {}), '(image_path_list[0], image_path_list[1])\n', (535, 575), False, 'import os\n'), ((814, 828), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (826, 828), True, 'import pandas as pd\n'), ((1363, 1400), 'numpy.histogram', 'np.histogram', (["data['Steering']", 'n_bin'], {}), "(data['Steering'], n_bin)\n", (1375, 1400), True, 'import numpy as np\n'), ((2964, 2987), 'numpy.asarray', 'np.asarray', (['images_path'], {}), '(images_path)\n', (2974, 2987), True, 'import numpy as np\n'), ((3003, 3023), 'numpy.asarray', 'np.asarray', (['steering'], {}), '(steering)\n', (3013, 3023), True, 'import numpy as np\n'), ((3222, 3242), 'cv2.imread', 'cv2.imread', (['img_path'], {}), '(img_path)\n', (3232, 3242), False, 'import cv2\n'), ((3816, 3852), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2YUV'], {}), '(img, cv2.COLOR_BGR2YUV)\n', (3828, 3852), False, 'import cv2\n'), ((3863, 3895), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['img', '(3, 3)', '(0)'], {}), '(img, (3, 3), 0)\n', (3879, 3895), False, 'import cv2\n'), ((3906, 3932), 'cv2.resize', 'cv2.resize', (['img', '(200, 66)'], {}), '(img, (200, 66))\n', (3916, 3932), False, 'import cv2\n'), ((4657, 4683), 'tensorflow.keras.optimizers.Adam', 'Adam', ([], {'learning_rate': '(0.0003)'}), '(learning_rate=0.0003)\n', (4661, 4683), False, 'from tensorflow.keras.optimizers import Adam\n'), ((1471, 1504), 'matplotlib.pyplot.bar', 'plt.bar', (['center', 'hist'], {'width': '(0.03)'}), '(center, hist, width=0.03)\n', (1478, 1504), True, 'import matplotlib.pyplot as plt\n'), ((1620, 1651), 'matplotlib.pyplot.title', 'plt.title', (['"""Data Visualization"""'], {}), "('Data Visualization')\n", (1629, 1651), True, 'import matplotlib.pyplot as plt\n'), ((1660, 1688), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Steering Angle"""'], {}), "('Steering Angle')\n", (1670, 1688), True, 'import matplotlib.pyplot as plt\n'), ((1697, 1724), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""No of Samples"""'], {}), "('No of Samples')\n", (1707, 1724), True, 'import matplotlib.pyplot as plt\n'), ((1733, 1743), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1741, 1743), True, 'import matplotlib.pyplot as plt\n'), ((2022, 2044), 'sklearn.utils.shuffle', 'shuffle', (['bin_data_list'], {}), '(bin_data_list)\n', (2029, 2044), False, 'from sklearn.utils import shuffle\n'), ((2339, 2376), 'numpy.histogram', 'np.histogram', (["data['Steering']", 'n_bin'], {}), "(data['Steering'], n_bin)\n", (2351, 2376), True, 'import numpy as np\n'), ((2387, 2420), 'matplotlib.pyplot.bar', 'plt.bar', (['center', 'hist'], {'width': '(0.03)'}), '(center, hist, width=0.03)\n', (2394, 2420), True, 'import matplotlib.pyplot as plt\n'), ((2536, 2562), 'matplotlib.pyplot.title', 'plt.title', (['"""Balanced Data"""'], {}), "('Balanced Data')\n", (2545, 2562), True, 'import matplotlib.pyplot as plt\n'), ((2571, 2599), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Steering Angle"""'], {}), "('Steering Angle')\n", (2581, 2599), True, 'import matplotlib.pyplot as plt\n'), ((2608, 2635), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""No of Samples"""'], {}), "('No of Samples')\n", (2618, 2635), True, 'import matplotlib.pyplot as plt\n'), ((2644, 2654), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2652, 2654), True, 'import matplotlib.pyplot as plt\n'), ((3250, 3266), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (3264, 3266), True, 'import numpy as np\n'), ((3288, 3354), 'imgaug.augmenters.Affine', 'iaa.Affine', ([], {'translate_percent': "{'x': (-0.1, 0.1), 'y': (-0.1, 0.1)}"}), "(translate_percent={'x': (-0.1, 0.1), 'y': (-0.1, 0.1)})\n", (3298, 3354), True, 'import imgaug.augmenters as iaa\n'), ((3399, 3415), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (3413, 3415), True, 'import numpy as np\n'), ((3438, 3464), 'imgaug.augmenters.Affine', 'iaa.Affine', ([], {'scale': '(1, 1.2)'}), '(scale=(1, 1.2))\n', (3448, 3464), True, 'import imgaug.augmenters as iaa\n'), ((3510, 3526), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (3524, 3526), True, 'import numpy as np\n'), ((3555, 3579), 'imgaug.augmenters.Multiply', 'iaa.Multiply', (['(0.5, 1.2)'], {}), '((0.5, 1.2))\n', (3567, 3579), True, 'import imgaug.augmenters as iaa\n'), ((3631, 3647), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (3645, 3647), True, 'import numpy as np\n'), ((3669, 3685), 'cv2.flip', 'cv2.flip', (['img', '(1)'], {}), '(img, 1)\n', (3677, 3685), False, 'import cv2\n'), ((780, 796), 'os.listdir', 'os.listdir', (['path'], {}), '(path)\n', (790, 796), False, 'import os\n'), ((895, 929), 'os.path.join', 'os.path.join', (['path', 'f"""log_{x}.csv"""'], {}), "(path, f'log_{x}.csv')\n", (907, 929), False, 'import os\n'), ((2861, 2896), 'os.path.join', 'os.path.join', (['path', 'indexed_data[0]'], {}), '(path, indexed_data[0])\n', (2873, 2896), False, 'import os\n'), ((4055, 4143), 'tensorflow.keras.layers.Convolution2D', 'layers.Convolution2D', (['(24)', '(5, 5)', '(2, 2)'], {'input_shape': '(66, 200, 3)', 'activation': '"""elu"""'}), "(24, (5, 5), (2, 2), input_shape=(66, 200, 3),\n activation='elu')\n", (4075, 4143), False, 'from tensorflow.keras import layers\n'), ((4153, 4211), 'tensorflow.keras.layers.Convolution2D', 'layers.Convolution2D', (['(36)', '(5, 5)', '(2, 2)'], {'activation': '"""elu"""'}), "(36, (5, 5), (2, 2), activation='elu')\n", (4173, 4211), False, 'from tensorflow.keras import layers\n'), ((4225, 4283), 'tensorflow.keras.layers.Convolution2D', 'layers.Convolution2D', (['(48)', '(5, 5)', '(2, 2)'], {'activation': '"""elu"""'}), "(48, (5, 5), (2, 2), activation='elu')\n", (4245, 4283), False, 'from tensorflow.keras import layers\n'), ((4297, 4347), 'tensorflow.keras.layers.Convolution2D', 'layers.Convolution2D', (['(64)', '(3, 3)'], {'activation': '"""elu"""'}), "(64, (3, 3), activation='elu')\n", (4317, 4347), False, 'from tensorflow.keras import layers\n'), ((4361, 4411), 'tensorflow.keras.layers.Convolution2D', 'layers.Convolution2D', (['(64)', '(3, 3)'], {'activation': '"""elu"""'}), "(64, (3, 3), activation='elu')\n", (4381, 4411), False, 'from tensorflow.keras import layers\n'), ((4438, 4454), 'tensorflow.keras.layers.Flatten', 'layers.Flatten', ([], {}), '()\n', (4452, 4454), False, 'from tensorflow.keras import layers\n'), ((4468, 4503), 'tensorflow.keras.layers.Dense', 'layers.Dense', (['(100)'], {'activation': '"""elu"""'}), "(100, activation='elu')\n", (4480, 4503), False, 'from tensorflow.keras import layers\n'), ((4517, 4551), 'tensorflow.keras.layers.Dense', 'layers.Dense', (['(50)'], {'activation': '"""elu"""'}), "(50, activation='elu')\n", (4529, 4551), False, 'from tensorflow.keras import layers\n'), ((4565, 4599), 'tensorflow.keras.layers.Dense', 'layers.Dense', (['(10)'], {'activation': '"""elu"""'}), "(10, activation='elu')\n", (4577, 4599), False, 'from tensorflow.keras import layers\n'), ((4613, 4628), 'tensorflow.keras.layers.Dense', 'layers.Dense', (['(1)'], {}), '(1)\n', (4625, 4628), False, 'from tensorflow.keras import layers\n'), ((1523, 1547), 'numpy.min', 'np.min', (["data['Steering']"], {}), "(data['Steering'])\n", (1529, 1547), True, 'import numpy as np\n'), ((1549, 1573), 'numpy.max', 'np.max', (["data['Steering']"], {}), "(data['Steering'])\n", (1555, 1573), True, 'import numpy as np\n'), ((2439, 2463), 'numpy.min', 'np.min', (["data['Steering']"], {}), "(data['Steering'])\n", (2445, 2463), True, 'import numpy as np\n'), ((2465, 2489), 'numpy.max', 'np.max', (["data['Steering']"], {}), "(data['Steering'])\n", (2471, 2489), True, 'import numpy as np\n'), ((5315, 5345), 'cv2.imread', 'cv2.imread', (['images_path[index]'], {}), '(images_path[index])\n', (5325, 5345), False, 'import cv2\n'), ((5525, 5546), 'numpy.asarray', 'np.asarray', (['img_batch'], {}), '(img_batch)\n', (5535, 5546), True, 'import numpy as np\n'), ((5548, 5574), 'numpy.asarray', 'np.asarray', (['steering_batch'], {}), '(steering_batch)\n', (5558, 5574), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
#~ from __future__ import (unicode_literals, print_function, division, absolute_import)
import numpy as np
import scipy.fftpack
import scipy.signal
import matplotlib.cm
import matplotlib.colors
from .myqt import QT
import pyqtgraph as pg
from .base import BaseMultiChannelViewer, Base_MultiChannel_ParamController, MyViewBox
from .datasource import InMemoryAnalogSignalSource
from .tools import create_plot_grid
#todo remove this
import time
import threading
default_params = [
{'name': 'xsize', 'type': 'float', 'value': 3., 'step': 0.1},
{'name': 'nb_column', 'type': 'int', 'value': 4},
{'name': 'background_color', 'type': 'color', 'value': 'k'},
{'name': 'vline_color', 'type': 'color', 'value': '#FFFFFFAA'},
{'name': 'colormap', 'type': 'list', 'value': 'viridis', 'values' : ['viridis', 'jet', 'gray', 'hot', ] },
{'name': 'display_labels', 'type': 'bool', 'value': True},
{'name': 'show_axis', 'type': 'bool', 'value': True},
{'name': 'scale_mode', 'type': 'list', 'value': 'same_for_all', 'values' : ['by_channel', 'same_for_all', ] },
{'name': 'timefreq', 'type': 'group', 'children': [
{'name': 'f_start', 'type': 'float', 'value': 3., 'step': 1.},
{'name': 'f_stop', 'type': 'float', 'value': 90., 'step': 1.},
{'name': 'deltafreq', 'type': 'float', 'value': 3., 'step': 1., 'limits': [0.1, 1.e6]},
{'name': 'f0', 'type': 'float', 'value': 2.5, 'step': 0.1},
{'name': 'normalisation', 'type': 'float', 'value': 0., 'step': 0.1},]}
]
default_by_channel_params = [
{'name': 'visible', 'type': 'bool', 'value': True},
{'name': 'clim', 'type': 'float', 'value': .1},
]
def generate_wavelet_fourier(len_wavelet, f_start, f_stop, deltafreq, sample_rate, f0, normalisation):
"""
Compute the wavelet coefficients at all scales and compute its Fourier transform.
Parameters
----------
len_wavelet : int
length in samples of the wavelet window
f_start: float
First frequency in Hz
f_stop: float
Last frequency in Hz
deltafreq : float
Frequency interval in Hz
sample_rate : float
Sample rate in Hz
f0 : float
normalisation : float
Returns:
-------
wf : array
Fourier transform of the wavelet coefficients (after weighting).
Axis 0 is time; axis 1 is frequency.
"""
# compute final map scales
scales = f0/np.arange(f_start,f_stop,deltafreq)*sample_rate
# compute wavelet coeffs at all scales
xi=np.arange(-len_wavelet/2.,len_wavelet/2.)
xsd = xi[:,np.newaxis] / scales
wavelet_coefs=np.exp(complex(1j)*2.*np.pi*f0*xsd)*np.exp(-np.power(xsd,2)/2.)
weighting_function = lambda x: x**(-(1.0+normalisation))
wavelet_coefs = wavelet_coefs*weighting_function(scales[np.newaxis,:])
# Transform the wavelet into the Fourier domain
wf=scipy.fftpack.fft(wavelet_coefs,axis=0)
wf=wf.conj()
return wf
class TimeFreqViewer_ParamController(Base_MultiChannel_ParamController):
some_clim_changed = QT.pyqtSignal()
def on_channel_visibility_changed(self):
print('TimeFreqViewer_ParamController.on_channel_visibility_changed')
self.viewer.create_grid()
self.viewer.initialize_time_freq()
self.viewer.refresh()
def clim_zoom(self, factor):
#~ print('clim_zoom factor', factor)
self.viewer.by_channel_params.blockSignals(True)
for i, p in enumerate(self.viewer.by_channel_params.children()):
p.param('clim').setValue(p.param('clim').value()*factor)
self.viewer.by_channel_params.blockSignals(False)
self.some_clim_changed.emit()
def compute_auto_clim(self):
print('compute_auto_clim')
print(self.visible_channels)
self.viewer.by_channel_params.blockSignals(True)
maxs = []
visibles, = np.nonzero(self.visible_channels)
for chan in visibles:
if chan in self.viewer.last_wt_maps.keys():
m = np.max(self.viewer.last_wt_maps[chan])
if self.viewer.params['scale_mode'] == 'by_channel':
self.viewer.by_channel_params['ch'+str(chan), 'clim'] = m
else:
maxs.append(m)
if self.viewer.params['scale_mode'] == 'same_for_all' and len(maxs)>0:
for chan in visibles:
self.viewer.by_channel_params['ch'+str(chan), 'clim'] = max(maxs)
self.viewer.by_channel_params.blockSignals(False)
self.some_clim_changed.emit()
class TimeFreqWorker(QT.QObject):
data_ready = QT.pyqtSignal(int, float, float, float, float, float, object)
def __init__(self, source,viewer, chan, parent=None):
QT.QObject.__init__(self, parent)
self.source = source
self.viewer = viewer
self.chan = chan
def on_request_data(self, chan, t, t_start, t_stop, visible_channels, worker_params):
if chan != self.chan:
return
if not visible_channels[chan]:
return
if self.viewer.t != t:
print('viewer has moved already', chan, self.viewer.t, t)
# viewer has moved already
return
ds_ratio = worker_params['downsample_ratio']
sig_chunk_size = worker_params['sig_chunk_size']
filter_sos = worker_params['filter_sos']
wavelet_fourrier = worker_params['wavelet_fourrier']
plot_length = worker_params['plot_length']
i_start = self.source.time_to_index(t_start)
#~ print('ds_ratio', ds_ratio)
#~ print('start', t_start, i_start)
if ds_ratio>1:
i_start = i_start - (i_start%ds_ratio)
#~ print('start', t_start, i_start)
#clip it
i_start = max(0, i_start)
i_start = min(i_start, self.source.get_length())
if ds_ratio>1:
#after clip
i_start = i_start - (i_start%ds_ratio)
#~ print('start', t_start, i_start)
i_stop = i_start + sig_chunk_size
i_stop = min(i_stop, self.source.get_length())
sigs_chunk = self.source.get_chunk(i_start=i_start, i_stop=i_stop)
sig = sigs_chunk[:, chan]
if ds_ratio>1:
small_sig = scipy.signal.sosfiltfilt(filter_sos, sig)
small_sig =small_sig[::ds_ratio].copy() # to ensure continuity
else:
small_sig = sig.copy() # to ensure continuity
small_sig = small_sig.astype('float64')
left_pad = 0
if small_sig.shape[0] != wavelet_fourrier.shape[0]:
#Pad it
z = np.zeros(wavelet_fourrier.shape[0], dtype=small_sig.dtype)
left_pad = wavelet_fourrier.shape[0] - small_sig.shape[0]
z[:small_sig.shape[0]] = small_sig
small_sig = z
#avoid border effect
small_sig -= small_sig.mean()
#~ print('sig', sig.shape, 'small_sig', small_sig.shape)
small_sig_f = scipy.fftpack.fft(small_sig)
if small_sig_f.shape[0] != wavelet_fourrier.shape[0]:
print('oulala', small_sig_f.shape, wavelet_fourrier.shape)
#TODO pad with zeros somewhere
return
wt_tmp=scipy.fftpack.ifft(small_sig_f[:,np.newaxis]*wavelet_fourrier,axis=0)
wt = scipy.fftpack.fftshift(wt_tmp,axes=[0])
wt = np.abs(wt).astype('float32')
if left_pad>0:
wt = wt[:-left_pad]
wt_map = wt[:plot_length]
#~ wt_map =wt
#~ print('wt_map', wt_map.shape)
#~ print('sleep', chan)
#~ time.sleep(2.)
#TODO t_start and t_stop wrong
#~ print('sub_sample_rate', worker_params['sub_sample_rate'])
#~ print('wanted_size', worker_params['wanted_size'])
#~ print('plot_length', plot_length)
#~ print(i_start, i_stop)
t1 = self.source.index_to_time(i_start)
t2 = self.source.index_to_time(i_start+wt_map.shape[0]*ds_ratio)
#~ t2 = self.source.index_to_time(i_stop)
self.data_ready.emit(chan, t, t_start, t_stop, t1, t2, wt_map)
class TimeFreqViewer(BaseMultiChannelViewer):
_default_params = default_params
_default_by_channel_params = default_by_channel_params
_ControllerClass = TimeFreqViewer_ParamController
request_data = QT.pyqtSignal(int, float, float, float, object, object)
def __init__(self, **kargs):
BaseMultiChannelViewer.__init__(self, **kargs)
self.make_params()
# make all not visible
self.by_channel_params.blockSignals(True)
for c in range(self.source.nb_channel):
self.by_channel_params['ch'+str(c), 'visible'] = c==0
self.by_channel_params.blockSignals(False)
self.make_param_controller()
self.params_controller.some_clim_changed.connect(self.refresh)
self.set_layout()
self.change_color_scale()
self.create_grid()
self.initialize_time_freq()
self._xratio = 0.3
self.last_wt_maps = {}
self.threads = []
self.timefreq_makers = []
for c in range(self.source.nb_channel):
thread = QT.QThread(parent=self)
self.threads.append(thread)
worker = TimeFreqWorker(self.source, self, c)
self.timefreq_makers.append(worker)
worker.moveToThread(thread)
thread.start()
worker.data_ready.connect(self.on_data_ready)
self.request_data.connect(worker.on_request_data)
self.params.param('xsize').setLimits((0, np.inf))
@classmethod
def from_numpy(cls, sigs, sample_rate, t_start, name, channel_names=None):
source = InMemoryAnalogSignalSource(sigs, sample_rate, t_start, channel_names=channel_names)
view = cls(source=source, name=name)
return view
def closeEvent(self, event):
for i, thread in enumerate(self.threads):
thread.quit()
thread.wait()
event.accept()
def set_layout(self):
self.mainlayout = QT.QVBoxLayout()
self.setLayout(self.mainlayout)
self.graphiclayout = pg.GraphicsLayoutWidget()
self.mainlayout.addWidget(self.graphiclayout)
def on_param_change(self, params=None, changes=None):
#~ print('on_param_change')
#track if new scale mode
#~ for param, change, data in changes:
#~ if change != 'value': continue
#~ if param.name()=='scale_mode':
#~ self.params_controller.compute_rescale()
#for simplification everything is recompute
self.change_color_scale()
self.create_grid()
self.initialize_time_freq()
self.refresh()
def create_grid(self):
visible_channels = self.params_controller.visible_channels
self.plots = create_plot_grid(
self.graphiclayout, self.params['nb_column'], visible_channels,
ViewBoxClass=MyViewBox, vb_params={})
for plot in self.plots:
if plot is not None:
plot.vb.doubleclicked.connect(self.show_params_controller)
plot.vb.ygain_zoom.connect(self.params_controller.clim_zoom)
# plot.vb.xsize_zoom.connect(self.params_controller.apply_xsize_zoom)
self.images = []
self.vlines = []
for c in range(self.source.nb_channel):
if visible_channels[c]:
image = pg.ImageItem()
self.plots[c].addItem(image)
self.images.append(image)
vline = pg.InfiniteLine(angle = 90, movable = False, pen = self.params['vline_color'])
vline.setZValue(1) # ensure vline is above plot elements
self.plots[c].addItem(vline)
self.vlines.append(vline)
else:
self.images.append(None)
self.vlines.append(None)
def initialize_time_freq(self):
tfr_params = self.params.param('timefreq')
sample_rate = self.source.sample_rate
# we take sample_rate = f_stop*4 or (original sample_rate)
if tfr_params['f_stop']*4 < sample_rate:
wanted_sub_sample_rate = tfr_params['f_stop']*4
else:
wanted_sub_sample_rate = sample_rate
# this try to find the best size to get a timefreq of 2**N by changing
# the sub_sample_rate and the sig_chunk_size
d = self.worker_params = {}
d['wanted_size'] = self.params['xsize']
l = d['len_wavelet'] = int(2**np.ceil(np.log(d['wanted_size']*wanted_sub_sample_rate)/np.log(2)))
d['sig_chunk_size'] = d['wanted_size']*self.source.sample_rate
d['downsample_ratio'] = int(np.ceil(d['sig_chunk_size']/l))
d['sig_chunk_size'] = d['downsample_ratio']*l
d['sub_sample_rate'] = self.source.sample_rate/d['downsample_ratio']
d['plot_length'] = int(d['wanted_size']*d['sub_sample_rate'])
d['wavelet_fourrier'] = generate_wavelet_fourier(d['len_wavelet'], tfr_params['f_start'], tfr_params['f_stop'],
tfr_params['deltafreq'], d['sub_sample_rate'], tfr_params['f0'], tfr_params['normalisation'])
if d['downsample_ratio']>1:
n = 8
q = d['downsample_ratio']
d['filter_sos'] = scipy.signal.cheby1(n, 0.05, 0.8 / q, output='sos')
else:
d['filter_sos'] = None
def change_color_scale(self):
N = 512
cmap_name = self.params['colormap']
cmap = matplotlib.cm.get_cmap(cmap_name , N)
lut = []
for i in range(N):
r,g,b,_ = matplotlib.colors.ColorConverter().to_rgba(cmap(i))
lut.append([r*255,g*255,b*255])
self.lut = np.array(lut, dtype='uint8')
def auto_scale(self):
print('auto_scale', self.params['scale_mode'])
self.params_controller.compute_auto_clim()
self.refresh()
def refresh(self):
#~ print('TimeFreqViewer.refresh', self.t)
visible_channels = self.params_controller.visible_channels
xsize = self.params['xsize']
t_start, t_stop = self.t-xsize*self._xratio , self.t+xsize*(1-self._xratio)
for c in range(self.source.nb_channel):
if visible_channels[c]:
self.request_data.emit(c, self.t, t_start, t_stop, visible_channels, self.worker_params)
self.graphiclayout.setBackground(self.params['background_color'])
def on_data_ready(self, chan, t, t_start, t_stop, t1,t2, wt_map):
if not self.params_controller.visible_channels[chan]:
return
if self.images[chan] is None:
return
self.last_wt_maps[chan] = wt_map
f_start = self.params['timefreq', 'f_start']
f_stop = self.params['timefreq', 'f_stop']
image = self.images[chan]
#~ print(t_start, f_start,self.worker_params['wanted_size'], f_stop-f_start)
#~ image.updateImage(wt_map)
clim = self.by_channel_params['ch{}'.format(chan), 'clim']
image.setImage(wt_map, lut=self.lut, levels=[0, clim])
image.setRect(QT.QRectF(t1, f_start,t2-t1, f_stop-f_start))
#TODO
# display_labels
self.vlines[chan].setPos(t)
self.vlines[chan].setPen(color=self.params['vline_color'])
plot = self.plots[chan]
plot.setXRange(t_start, t_stop, padding = 0.0)
plot.setYRange(f_start, f_stop, padding = 0.0)
if self.params['display_labels']:
ch_name = '{}: {}'.format(chan, self.source.get_channel_name(chan=chan))
self.plots[chan].setTitle(ch_name)
else:
self.plots[chan].setTitle(None)
self.plots[chan].showAxis('left', self.params['show_axis'])
self.plots[chan].showAxis('bottom', self.params['show_axis'])
| [
"numpy.abs",
"numpy.ceil",
"numpy.power",
"numpy.log",
"pyqtgraph.ImageItem",
"pyqtgraph.InfiniteLine",
"numpy.max",
"numpy.array",
"numpy.zeros",
"numpy.nonzero",
"pyqtgraph.GraphicsLayoutWidget",
"numpy.arange"
] | [((2622, 2670), 'numpy.arange', 'np.arange', (['(-len_wavelet / 2.0)', '(len_wavelet / 2.0)'], {}), '(-len_wavelet / 2.0, len_wavelet / 2.0)\n', (2631, 2670), True, 'import numpy as np\n'), ((3977, 4010), 'numpy.nonzero', 'np.nonzero', (['self.visible_channels'], {}), '(self.visible_channels)\n', (3987, 4010), True, 'import numpy as np\n'), ((10223, 10248), 'pyqtgraph.GraphicsLayoutWidget', 'pg.GraphicsLayoutWidget', ([], {}), '()\n', (10246, 10248), True, 'import pyqtgraph as pg\n'), ((13830, 13858), 'numpy.array', 'np.array', (['lut'], {'dtype': '"""uint8"""'}), "(lut, dtype='uint8')\n", (13838, 13858), True, 'import numpy as np\n'), ((2523, 2560), 'numpy.arange', 'np.arange', (['f_start', 'f_stop', 'deltafreq'], {}), '(f_start, f_stop, deltafreq)\n', (2532, 2560), True, 'import numpy as np\n'), ((6708, 6766), 'numpy.zeros', 'np.zeros', (['wavelet_fourrier.shape[0]'], {'dtype': 'small_sig.dtype'}), '(wavelet_fourrier.shape[0], dtype=small_sig.dtype)\n', (6716, 6766), True, 'import numpy as np\n'), ((12799, 12831), 'numpy.ceil', 'np.ceil', (["(d['sig_chunk_size'] / l)"], {}), "(d['sig_chunk_size'] / l)\n", (12806, 12831), True, 'import numpy as np\n'), ((4117, 4155), 'numpy.max', 'np.max', (['self.viewer.last_wt_maps[chan]'], {}), '(self.viewer.last_wt_maps[chan])\n', (4123, 4155), True, 'import numpy as np\n'), ((7443, 7453), 'numpy.abs', 'np.abs', (['wt'], {}), '(wt)\n', (7449, 7453), True, 'import numpy as np\n'), ((11528, 11542), 'pyqtgraph.ImageItem', 'pg.ImageItem', ([], {}), '()\n', (11540, 11542), True, 'import pyqtgraph as pg\n'), ((11655, 11727), 'pyqtgraph.InfiniteLine', 'pg.InfiniteLine', ([], {'angle': '(90)', 'movable': '(False)', 'pen': "self.params['vline_color']"}), "(angle=90, movable=False, pen=self.params['vline_color'])\n", (11670, 11727), True, 'import pyqtgraph as pg\n'), ((2762, 2778), 'numpy.power', 'np.power', (['xsd', '(2)'], {}), '(xsd, 2)\n', (2770, 2778), True, 'import numpy as np\n'), ((12632, 12681), 'numpy.log', 'np.log', (["(d['wanted_size'] * wanted_sub_sample_rate)"], {}), "(d['wanted_size'] * wanted_sub_sample_rate)\n", (12638, 12681), True, 'import numpy as np\n'), ((12680, 12689), 'numpy.log', 'np.log', (['(2)'], {}), '(2)\n', (12686, 12689), True, 'import numpy as np\n')] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.